blob: 22a31635a644dcff20923980af3b410e18bc9e55 [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
Andreas Gampe46ee31b2016-12-14 10:11:49 -080023#include "android-base/stringprintf.h"
24
Ian Rogers166db042013-07-26 12:05:57 -070025#include "arch/context.h"
Mathieu Chartierc7853442015-03-27 14:35:38 -070026#include "art_field-inl.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070027#include "art_method-inl.h"
Andreas Gampe542451c2016-07-26 09:02:02 -070028#include "base/enums.h"
Vladimir Marko80afd022015-05-19 18:08:00 +010029#include "base/time_utils.h"
Elliott Hughes545a0642011-11-08 19:10:03 -080030#include "class_linker.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080031#include "class_linker-inl.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070032#include "dex_file-inl.h"
David Sehr9323e6e2016-09-13 08:58:35 -070033#include "dex_file_annotations.h"
Ian Rogers776ac1f2012-04-13 23:36:36 -070034#include "dex_instruction.h"
Mingyao Yang6ea1a0e2016-01-29 12:12:49 -080035#include "entrypoints/runtime_asm_entrypoints.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070036#include "gc/accounting/card_table-inl.h"
Man Cao8c2ff642015-05-27 17:25:30 -070037#include "gc/allocation_record.h"
Mathieu Chartieraa516822015-10-02 15:53:37 -070038#include "gc/scoped_gc_critical_section.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070039#include "gc/space/large_object_space.h"
40#include "gc/space/space-inl.h"
Mathieu Chartiereb8167a2014-05-07 15:43:14 -070041#include "handle_scope.h"
Sebastien Hertzcbc50642015-06-01 17:33:12 +020042#include "jdwp/jdwp_priv.h"
Elliott Hughes64f574f2013-02-20 14:57:12 -080043#include "jdwp/object_registry.h"
Andreas Gampe13b27842016-11-07 16:48:23 -080044#include "jni_internal.h"
Mathieu Chartier28bd2e42016-10-04 13:54:57 -070045#include "jvalue-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080046#include "mirror/class.h"
47#include "mirror/class-inl.h"
48#include "mirror/class_loader.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080049#include "mirror/object-inl.h"
50#include "mirror/object_array-inl.h"
Ian Rogersb0fa5dc2014-04-28 16:47:08 -070051#include "mirror/string-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080052#include "mirror/throwable.h"
Mathieu Chartier3398c782016-09-30 10:27:43 -070053#include "obj_ptr-inl.h"
Ian Rogers53b8b092014-03-13 23:45:53 -070054#include "reflection.h"
Elliott Hughesa0e18062012-04-13 15:59:59 -070055#include "safe_map.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070056#include "scoped_thread_state_change-inl.h"
Elliott Hughes6a5bd492011-10-28 14:33:57 -070057#include "ScopedLocalRef.h"
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -070058#include "ScopedPrimitiveArray.h"
Mathieu Chartiereb8167a2014-05-07 15:43:14 -070059#include "handle_scope-inl.h"
Elliott Hughes475fc232011-10-25 15:00:35 -070060#include "thread_list.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080061#include "utf.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070062#include "well_known_classes.h"
Elliott Hughes475fc232011-10-25 15:00:35 -070063
Elliott Hughes872d4ec2011-10-21 17:07:15 -070064namespace art {
65
Andreas Gampe46ee31b2016-12-14 10:11:49 -080066using android::base::StringPrintf;
67
Sebastien Hertz0462c4c2015-04-01 16:34:17 +020068// The key identifying the debugger to update instrumentation.
69static constexpr const char* kDbgInstrumentationKey = "Debugger";
70
Man Cao8c2ff642015-05-27 17:25:30 -070071// 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 -070072static uint16_t CappedAllocRecordCount(size_t alloc_record_count) {
Man Cao1ed11b92015-06-11 22:47:35 -070073 const size_t cap = 0xffff;
Man Cao8c2ff642015-05-27 17:25:30 -070074 if (alloc_record_count > cap) {
75 return cap;
Brian Carlstrom306db812014-09-05 13:01:41 -070076 }
77 return alloc_record_count;
78}
Elliott Hughes475fc232011-10-25 15:00:35 -070079
Alex Light6c8467f2015-11-20 15:03:26 -080080// Takes a method and returns a 'canonical' one if the method is default (and therefore potentially
81// copied from some other class). This ensures that the debugger does not get confused as to which
82// method we are in.
83static ArtMethod* GetCanonicalMethod(ArtMethod* m)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -070084 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light6c8467f2015-11-20 15:03:26 -080085 if (LIKELY(!m->IsDefault())) {
86 return m;
87 } else {
88 mirror::Class* declaring_class = m->GetDeclaringClass();
89 return declaring_class->FindDeclaredVirtualMethod(declaring_class->GetDexCache(),
90 m->GetDexMethodIndex(),
Andreas Gampe542451c2016-07-26 09:02:02 -070091 kRuntimePointerSize);
Alex Light6c8467f2015-11-20 15:03:26 -080092 }
93}
94
Mathieu Chartier41af5e52015-10-28 11:10:46 -070095class Breakpoint : public ValueObject {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -070096 public:
Mathieu Chartier41af5e52015-10-28 11:10:46 -070097 Breakpoint(ArtMethod* method, uint32_t dex_pc, DeoptimizationRequest::Kind deoptimization_kind)
Alex Light6c8467f2015-11-20 15:03:26 -080098 : method_(GetCanonicalMethod(method)),
Mathieu Chartier41af5e52015-10-28 11:10:46 -070099 dex_pc_(dex_pc),
100 deoptimization_kind_(deoptimization_kind) {
Sebastien Hertzf3928792014-11-17 19:00:37 +0100101 CHECK(deoptimization_kind_ == DeoptimizationRequest::kNothing ||
102 deoptimization_kind_ == DeoptimizationRequest::kSelectiveDeoptimization ||
103 deoptimization_kind_ == DeoptimizationRequest::kFullDeoptimization);
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700104 }
105
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700106 Breakpoint(const Breakpoint& other) REQUIRES_SHARED(Locks::mutator_lock_)
Mathieu Chartier41af5e52015-10-28 11:10:46 -0700107 : method_(other.method_),
108 dex_pc_(other.dex_pc_),
109 deoptimization_kind_(other.deoptimization_kind_) {}
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700110
Mathieu Chartier41af5e52015-10-28 11:10:46 -0700111 // Method() is called from root visiting, do not use ScopedObjectAccess here or it can cause
112 // GC to deadlock if another thread tries to call SuspendAll while the GC is in a runnable state.
113 ArtMethod* Method() const {
114 return method_;
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700115 }
116
117 uint32_t DexPc() const {
118 return dex_pc_;
119 }
120
Sebastien Hertzf3928792014-11-17 19:00:37 +0100121 DeoptimizationRequest::Kind GetDeoptimizationKind() const {
122 return deoptimization_kind_;
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700123 }
124
Alex Light6c8467f2015-11-20 15:03:26 -0800125 // Returns true if the method of this breakpoint and the passed in method should be considered the
126 // same. That is, they are either the same method or they are copied from the same method.
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700127 bool IsInMethod(ArtMethod* m) const REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light6c8467f2015-11-20 15:03:26 -0800128 return method_ == GetCanonicalMethod(m);
129 }
130
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700131 private:
Sebastien Hertza76a6d42014-03-20 16:40:17 +0100132 // The location of this breakpoint.
Mathieu Chartier41af5e52015-10-28 11:10:46 -0700133 ArtMethod* method_;
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700134 uint32_t dex_pc_;
Sebastien Hertza76a6d42014-03-20 16:40:17 +0100135
136 // Indicates whether breakpoint needs full deoptimization or selective deoptimization.
Sebastien Hertzf3928792014-11-17 19:00:37 +0100137 DeoptimizationRequest::Kind deoptimization_kind_;
Elliott Hughes86964332012-02-15 19:37:42 -0800138};
139
Sebastien Hertzed2be172014-08-19 15:33:43 +0200140static std::ostream& operator<<(std::ostream& os, const Breakpoint& rhs)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700141 REQUIRES_SHARED(Locks::mutator_lock_) {
David Sehr709b0702016-10-13 09:12:37 -0700142 os << StringPrintf("Breakpoint[%s @%#x]", ArtMethod::PrettyMethod(rhs.Method()).c_str(),
143 rhs.DexPc());
Elliott Hughes86964332012-02-15 19:37:42 -0800144 return os;
145}
146
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200147class DebugInstrumentationListener FINAL : public instrumentation::InstrumentationListener {
Ian Rogers62d6c772013-02-27 08:32:07 -0800148 public:
149 DebugInstrumentationListener() {}
150 virtual ~DebugInstrumentationListener() {}
151
Mathieu Chartiere401d142015-04-22 13:56:20 -0700152 void MethodEntered(Thread* thread, mirror::Object* this_object, ArtMethod* method,
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200153 uint32_t dex_pc)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700154 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800155 if (method->IsNative()) {
156 // TODO: post location events is a suspension point and native method entry stubs aren't.
157 return;
158 }
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200159 if (IsListeningToDexPcMoved()) {
160 // We also listen to kDexPcMoved instrumentation event so we know the DexPcMoved method is
161 // going to be called right after us. To avoid sending JDWP events twice for this location,
162 // we report the event in DexPcMoved. However, we must remind this is method entry so we
163 // send the METHOD_ENTRY event. And we can also group it with other events for this location
164 // like BREAKPOINT or SINGLE_STEP (or even METHOD_EXIT if this is a RETURN instruction).
165 thread->SetDebugMethodEntry();
166 } else if (IsListeningToMethodExit() && IsReturn(method, dex_pc)) {
167 // We also listen to kMethodExited instrumentation event and the current instruction is a
168 // RETURN so we know the MethodExited method is going to be called right after us. To avoid
169 // sending JDWP events twice for this location, we report the event(s) in MethodExited.
170 // However, we must remind this is method entry so we send the METHOD_ENTRY event. And we can
171 // also group it with other events for this location like BREAKPOINT or SINGLE_STEP.
172 thread->SetDebugMethodEntry();
173 } else {
174 Dbg::UpdateDebugger(thread, this_object, method, 0, Dbg::kMethodEntry, nullptr);
175 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800176 }
177
Mathieu Chartiere401d142015-04-22 13:56:20 -0700178 void MethodExited(Thread* thread, mirror::Object* this_object, ArtMethod* method,
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200179 uint32_t dex_pc, const JValue& return_value)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700180 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800181 if (method->IsNative()) {
182 // TODO: post location events is a suspension point and native method entry stubs aren't.
183 return;
184 }
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200185 uint32_t events = Dbg::kMethodExit;
186 if (thread->IsDebugMethodEntry()) {
187 // It is also the method entry.
188 DCHECK(IsReturn(method, dex_pc));
189 events |= Dbg::kMethodEntry;
190 thread->ClearDebugMethodEntry();
191 }
192 Dbg::UpdateDebugger(thread, this_object, method, dex_pc, events, &return_value);
Ian Rogers62d6c772013-02-27 08:32:07 -0800193 }
194
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200195 void MethodUnwind(Thread* thread ATTRIBUTE_UNUSED, mirror::Object* this_object ATTRIBUTE_UNUSED,
Mathieu Chartiere401d142015-04-22 13:56:20 -0700196 ArtMethod* method, uint32_t dex_pc)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700197 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800198 // We're not recorded to listen to this kind of event, so complain.
David Sehr709b0702016-10-13 09:12:37 -0700199 LOG(ERROR) << "Unexpected method unwind event in debugger " << ArtMethod::PrettyMethod(method)
Sebastien Hertz51db44a2013-11-19 10:00:29 +0100200 << " " << dex_pc;
Ian Rogers62d6c772013-02-27 08:32:07 -0800201 }
202
Mathieu Chartiere401d142015-04-22 13:56:20 -0700203 void DexPcMoved(Thread* thread, mirror::Object* this_object, ArtMethod* method,
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200204 uint32_t new_dex_pc)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700205 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200206 if (IsListeningToMethodExit() && IsReturn(method, new_dex_pc)) {
207 // We also listen to kMethodExited instrumentation event and the current instruction is a
208 // RETURN so we know the MethodExited method is going to be called right after us. Like in
209 // MethodEntered, we delegate event reporting to MethodExited.
210 // Besides, if this RETURN instruction is the only one in the method, we can send multiple
211 // JDWP events in the same packet: METHOD_ENTRY, METHOD_EXIT, BREAKPOINT and/or SINGLE_STEP.
212 // Therefore, we must not clear the debug method entry flag here.
213 } else {
214 uint32_t events = 0;
215 if (thread->IsDebugMethodEntry()) {
216 // It is also the method entry.
217 events = Dbg::kMethodEntry;
218 thread->ClearDebugMethodEntry();
219 }
220 Dbg::UpdateDebugger(thread, this_object, method, new_dex_pc, events, nullptr);
221 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800222 }
223
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200224 void FieldRead(Thread* thread ATTRIBUTE_UNUSED, mirror::Object* this_object,
Mathieu Chartiere401d142015-04-22 13:56:20 -0700225 ArtMethod* method, uint32_t dex_pc, ArtField* field)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700226 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200227 Dbg::PostFieldAccessEvent(method, dex_pc, this_object, field);
Ian Rogers62d6c772013-02-27 08:32:07 -0800228 }
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200229
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700230 void FieldWritten(Thread* thread ATTRIBUTE_UNUSED, mirror::Object* this_object,
Mathieu Chartiere401d142015-04-22 13:56:20 -0700231 ArtMethod* method, uint32_t dex_pc, ArtField* field,
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700232 const JValue& field_value)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700233 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200234 Dbg::PostFieldModificationEvent(method, dex_pc, this_object, field, &field_value);
235 }
236
Nicolas Geoffray14691c52015-03-05 10:40:17 +0000237 void ExceptionCaught(Thread* thread ATTRIBUTE_UNUSED, mirror::Throwable* exception_object)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700238 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray14691c52015-03-05 10:40:17 +0000239 Dbg::PostException(exception_object);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200240 }
241
Nicolas Geoffray81f0f952016-01-20 16:25:19 +0000242 // We only care about branches in the Jit.
243 void Branch(Thread* /*thread*/, ArtMethod* method, uint32_t dex_pc, int32_t dex_pc_offset)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700244 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
David Sehr709b0702016-10-13 09:12:37 -0700245 LOG(ERROR) << "Unexpected branch event in debugger " << ArtMethod::PrettyMethod(method)
Nicolas Geoffray81f0f952016-01-20 16:25:19 +0000246 << " " << dex_pc << ", " << dex_pc_offset;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800247 }
248
Nicolas Geoffray5550ca82015-08-21 18:38:30 +0100249 // We only care about invokes in the Jit.
250 void InvokeVirtualOrInterface(Thread* thread ATTRIBUTE_UNUSED,
251 mirror::Object*,
252 ArtMethod* method,
253 uint32_t dex_pc,
254 ArtMethod*)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700255 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
David Sehr709b0702016-10-13 09:12:37 -0700256 LOG(ERROR) << "Unexpected invoke event in debugger " << ArtMethod::PrettyMethod(method)
Nicolas Geoffray5550ca82015-08-21 18:38:30 +0100257 << " " << dex_pc;
258 }
259
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200260 private:
Mathieu Chartiere401d142015-04-22 13:56:20 -0700261 static bool IsReturn(ArtMethod* method, uint32_t dex_pc)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700262 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200263 const DexFile::CodeItem* code_item = method->GetCodeItem();
264 const Instruction* instruction = Instruction::At(&code_item->insns_[dex_pc]);
265 return instruction->IsReturn();
266 }
267
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700268 static bool IsListeningToDexPcMoved() REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200269 return IsListeningTo(instrumentation::Instrumentation::kDexPcMoved);
270 }
271
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700272 static bool IsListeningToMethodExit() REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200273 return IsListeningTo(instrumentation::Instrumentation::kMethodExited);
274 }
275
276 static bool IsListeningTo(instrumentation::Instrumentation::InstrumentationEvent event)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700277 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200278 return (Dbg::GetInstrumentationEvents() & event) != 0;
279 }
280
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200281 DISALLOW_COPY_AND_ASSIGN(DebugInstrumentationListener);
Ian Rogers62d6c772013-02-27 08:32:07 -0800282} gDebugInstrumentationListener;
283
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700284// JDWP is allowed unless the Zygote forbids it.
285static bool gJdwpAllowed = true;
286
Elliott Hughesc0f09332012-03-26 13:27:06 -0700287// Was there a -Xrunjdwp or -agentlib:jdwp= argument on the command line?
Elliott Hughes3bb81562011-10-21 18:52:59 -0700288static bool gJdwpConfigured = false;
289
Sebastien Hertzb3b173b2015-02-06 09:16:32 +0100290// JDWP options for debugging. Only valid if IsJdwpConfigured() is true.
291static JDWP::JdwpOptions gJdwpOptions;
292
Elliott Hughes3bb81562011-10-21 18:52:59 -0700293// Runtime JDWP state.
Ian Rogersc0542af2014-09-03 16:16:56 -0700294static JDWP::JdwpState* gJdwpState = nullptr;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700295static bool gDebuggerConnected; // debugger or DDMS is connected.
Elliott Hughes3bb81562011-10-21 18:52:59 -0700296
Elliott Hughes47fce012011-10-25 18:37:19 -0700297static bool gDdmThreadNotification = false;
298
Elliott Hughes767a1472011-10-26 18:49:02 -0700299// DDMS GC-related settings.
300static Dbg::HpifWhen gDdmHpifWhen = Dbg::HPIF_WHEN_NEVER;
301static Dbg::HpsgWhen gDdmHpsgWhen = Dbg::HPSG_WHEN_NEVER;
302static Dbg::HpsgWhat gDdmHpsgWhat;
303static Dbg::HpsgWhen gDdmNhsgWhen = Dbg::HPSG_WHEN_NEVER;
304static Dbg::HpsgWhat gDdmNhsgWhat;
305
Daniel Mihalyieb076692014-08-22 17:33:31 +0200306bool Dbg::gDebuggerActive = false;
Sebastien Hertz4e5b2082015-03-24 19:03:40 +0100307bool Dbg::gDisposed = false;
Sebastien Hertz6995c602014-09-09 12:10:13 +0200308ObjectRegistry* Dbg::gRegistry = nullptr;
Elliott Hughes475fc232011-10-25 15:00:35 -0700309
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100310// Deoptimization support.
Sebastien Hertz4d25df32014-03-21 17:44:46 +0100311std::vector<DeoptimizationRequest> Dbg::deoptimization_requests_;
312size_t Dbg::full_deoptimization_event_count_ = 0;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100313
Sebastien Hertz42cd43f2014-05-13 14:15:41 +0200314// Instrumentation event reference counters.
315size_t Dbg::dex_pc_change_event_ref_count_ = 0;
316size_t Dbg::method_enter_event_ref_count_ = 0;
317size_t Dbg::method_exit_event_ref_count_ = 0;
318size_t Dbg::field_read_event_ref_count_ = 0;
319size_t Dbg::field_write_event_ref_count_ = 0;
320size_t Dbg::exception_catch_event_ref_count_ = 0;
321uint32_t Dbg::instrumentation_events_ = 0;
322
Andreas Gampe04bbb5b2017-01-19 17:49:03 +0000323Dbg::DbgThreadLifecycleCallback Dbg::thread_lifecycle_callback_;
Andreas Gampe0f01b582017-01-18 15:22:37 -0800324Dbg::DbgClassLoadCallback Dbg::class_load_callback_;
Andreas Gampe04bbb5b2017-01-19 17:49:03 +0000325
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100326// Breakpoints.
jeffhao09bfc6a2012-12-11 18:11:43 -0800327static std::vector<Breakpoint> gBreakpoints GUARDED_BY(Locks::breakpoint_lock_);
Elliott Hughes86964332012-02-15 19:37:42 -0800328
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700329void DebugInvokeReq::VisitRoots(RootVisitor* visitor, const RootInfo& root_info) {
330 receiver.VisitRootIfNonNull(visitor, root_info); // null for static method call.
331 klass.VisitRoot(visitor, root_info);
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700332}
333
Sebastien Hertz597c4f02015-01-26 17:37:14 +0100334void SingleStepControl::AddDexPc(uint32_t dex_pc) {
335 dex_pcs_.insert(dex_pc);
Sebastien Hertzbb43b432014-04-14 11:59:08 +0200336}
337
Sebastien Hertz597c4f02015-01-26 17:37:14 +0100338bool SingleStepControl::ContainsDexPc(uint32_t dex_pc) const {
339 return dex_pcs_.find(dex_pc) == dex_pcs_.end();
Sebastien Hertzbb43b432014-04-14 11:59:08 +0200340}
341
Alex Light6c8467f2015-11-20 15:03:26 -0800342static bool IsBreakpoint(ArtMethod* m, uint32_t dex_pc)
Mathieu Chartier90443472015-07-16 20:32:27 -0700343 REQUIRES(!Locks::breakpoint_lock_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700344 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertzed2be172014-08-19 15:33:43 +0200345 ReaderMutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100346 for (size_t i = 0, e = gBreakpoints.size(); i < e; ++i) {
Alex Light6c8467f2015-11-20 15:03:26 -0800347 if (gBreakpoints[i].DexPc() == dex_pc && gBreakpoints[i].IsInMethod(m)) {
Elliott Hughes86964332012-02-15 19:37:42 -0800348 VLOG(jdwp) << "Hit breakpoint #" << i << ": " << gBreakpoints[i];
349 return true;
350 }
351 }
352 return false;
353}
354
Sebastien Hertz52d131d2014-03-13 16:17:40 +0100355static bool IsSuspendedForDebugger(ScopedObjectAccessUnchecked& soa, Thread* thread)
Mathieu Chartier90443472015-07-16 20:32:27 -0700356 REQUIRES(!Locks::thread_suspend_count_lock_) {
Elliott Hughes9e0c1752013-01-09 14:02:58 -0800357 MutexLock mu(soa.Self(), *Locks::thread_suspend_count_lock_);
358 // A thread may be suspended for GC; in this code, we really want to know whether
359 // there's a debugger suspension active.
360 return thread->IsSuspended() && thread->GetDebugSuspendCount() > 0;
361}
362
Ian Rogersc0542af2014-09-03 16:16:56 -0700363static mirror::Array* DecodeNonNullArray(JDWP::RefTypeId id, JDWP::JdwpError* error)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700364 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz6995c602014-09-09 12:10:13 +0200365 mirror::Object* o = Dbg::GetObjectRegistry()->Get<mirror::Object*>(id, error);
Ian Rogersc0542af2014-09-03 16:16:56 -0700366 if (o == nullptr) {
367 *error = JDWP::ERR_INVALID_OBJECT;
368 return nullptr;
Elliott Hughes436e3722012-02-17 20:01:47 -0800369 }
370 if (!o->IsArrayInstance()) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700371 *error = JDWP::ERR_INVALID_ARRAY;
372 return nullptr;
Elliott Hughes436e3722012-02-17 20:01:47 -0800373 }
Ian Rogersc0542af2014-09-03 16:16:56 -0700374 *error = JDWP::ERR_NONE;
Elliott Hughes436e3722012-02-17 20:01:47 -0800375 return o->AsArray();
376}
377
Ian Rogersc0542af2014-09-03 16:16:56 -0700378static mirror::Class* DecodeClass(JDWP::RefTypeId id, JDWP::JdwpError* error)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700379 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz6995c602014-09-09 12:10:13 +0200380 mirror::Object* o = Dbg::GetObjectRegistry()->Get<mirror::Object*>(id, error);
Ian Rogersc0542af2014-09-03 16:16:56 -0700381 if (o == nullptr) {
382 *error = JDWP::ERR_INVALID_OBJECT;
383 return nullptr;
Elliott Hughes436e3722012-02-17 20:01:47 -0800384 }
385 if (!o->IsClass()) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700386 *error = JDWP::ERR_INVALID_CLASS;
387 return nullptr;
Elliott Hughes436e3722012-02-17 20:01:47 -0800388 }
Ian Rogersc0542af2014-09-03 16:16:56 -0700389 *error = JDWP::ERR_NONE;
Elliott Hughes436e3722012-02-17 20:01:47 -0800390 return o->AsClass();
391}
392
Ian Rogersc0542af2014-09-03 16:16:56 -0700393static Thread* DecodeThread(ScopedObjectAccessUnchecked& soa, JDWP::ObjectId thread_id,
394 JDWP::JdwpError* error)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700395 REQUIRES_SHARED(Locks::mutator_lock_)
Mathieu Chartier90443472015-07-16 20:32:27 -0700396 REQUIRES(!Locks::thread_list_lock_, !Locks::thread_suspend_count_lock_) {
Sebastien Hertz6995c602014-09-09 12:10:13 +0200397 mirror::Object* thread_peer = Dbg::GetObjectRegistry()->Get<mirror::Object*>(thread_id, error);
Ian Rogersc0542af2014-09-03 16:16:56 -0700398 if (thread_peer == nullptr) {
Elliott Hughes221229c2013-01-08 18:17:50 -0800399 // This isn't even an object.
Ian Rogersc0542af2014-09-03 16:16:56 -0700400 *error = JDWP::ERR_INVALID_OBJECT;
401 return nullptr;
Elliott Hughes436e3722012-02-17 20:01:47 -0800402 }
Elliott Hughes221229c2013-01-08 18:17:50 -0800403
Mathieu Chartier0795f232016-09-27 18:43:30 -0700404 ObjPtr<mirror::Class> java_lang_Thread =
405 soa.Decode<mirror::Class>(WellKnownClasses::java_lang_Thread);
Elliott Hughes221229c2013-01-08 18:17:50 -0800406 if (!java_lang_Thread->IsAssignableFrom(thread_peer->GetClass())) {
407 // This isn't a thread.
Ian Rogersc0542af2014-09-03 16:16:56 -0700408 *error = JDWP::ERR_INVALID_THREAD;
409 return nullptr;
Elliott Hughes221229c2013-01-08 18:17:50 -0800410 }
411
Sebastien Hertz69206392015-04-07 15:54:25 +0200412 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogersc0542af2014-09-03 16:16:56 -0700413 Thread* thread = Thread::FromManagedThread(soa, thread_peer);
414 // If thread is null then this a java.lang.Thread without a Thread*. Must be a un-started or a
415 // zombie.
416 *error = (thread == nullptr) ? JDWP::ERR_THREAD_NOT_ALIVE : JDWP::ERR_NONE;
417 return thread;
Elliott Hughes436e3722012-02-17 20:01:47 -0800418}
419
Elliott Hughes24437992011-11-30 14:49:33 -0800420static JDWP::JdwpTag BasicTagFromDescriptor(const char* descriptor) {
421 // JDWP deliberately uses the descriptor characters' ASCII values for its enum.
422 // Note that by "basic" we mean that we don't get more specific than JT_OBJECT.
423 return static_cast<JDWP::JdwpTag>(descriptor[0]);
424}
425
Ian Rogers1ff3c982014-08-12 02:30:58 -0700426static JDWP::JdwpTag BasicTagFromClass(mirror::Class* klass)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700427 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers1ff3c982014-08-12 02:30:58 -0700428 std::string temp;
429 const char* descriptor = klass->GetDescriptor(&temp);
430 return BasicTagFromDescriptor(descriptor);
431}
432
Ian Rogers98379392014-02-24 16:53:16 -0800433static JDWP::JdwpTag TagFromClass(const ScopedObjectAccessUnchecked& soa, mirror::Class* c)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700434 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700435 CHECK(c != nullptr);
Elliott Hughes24437992011-11-30 14:49:33 -0800436 if (c->IsArrayClass()) {
437 return JDWP::JT_ARRAY;
438 }
Elliott Hughes24437992011-11-30 14:49:33 -0800439 if (c->IsStringClass()) {
440 return JDWP::JT_STRING;
Elliott Hughes24437992011-11-30 14:49:33 -0800441 }
Ian Rogers98379392014-02-24 16:53:16 -0800442 if (c->IsClassClass()) {
443 return JDWP::JT_CLASS_OBJECT;
444 }
445 {
Mathieu Chartier0795f232016-09-27 18:43:30 -0700446 ObjPtr<mirror::Class> thread_class =
447 soa.Decode<mirror::Class>(WellKnownClasses::java_lang_Thread);
Ian Rogers98379392014-02-24 16:53:16 -0800448 if (thread_class->IsAssignableFrom(c)) {
449 return JDWP::JT_THREAD;
450 }
451 }
452 {
Mathieu Chartier0795f232016-09-27 18:43:30 -0700453 ObjPtr<mirror::Class> thread_group_class =
454 soa.Decode<mirror::Class>(WellKnownClasses::java_lang_ThreadGroup);
Ian Rogers98379392014-02-24 16:53:16 -0800455 if (thread_group_class->IsAssignableFrom(c)) {
456 return JDWP::JT_THREAD_GROUP;
457 }
458 }
459 {
Mathieu Chartier0795f232016-09-27 18:43:30 -0700460 ObjPtr<mirror::Class> class_loader_class =
461 soa.Decode<mirror::Class>(WellKnownClasses::java_lang_ClassLoader);
Ian Rogers98379392014-02-24 16:53:16 -0800462 if (class_loader_class->IsAssignableFrom(c)) {
463 return JDWP::JT_CLASS_LOADER;
464 }
465 }
466 return JDWP::JT_OBJECT;
Elliott Hughes24437992011-11-30 14:49:33 -0800467}
468
469/*
470 * Objects declared to hold Object might actually hold a more specific
471 * type. The debugger may take a special interest in these (e.g. it
472 * wants to display the contents of Strings), so we want to return an
473 * appropriate tag.
474 *
475 * Null objects are tagged JT_OBJECT.
476 */
Sebastien Hertz6995c602014-09-09 12:10:13 +0200477JDWP::JdwpTag Dbg::TagFromObject(const ScopedObjectAccessUnchecked& soa, mirror::Object* o) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700478 return (o == nullptr) ? JDWP::JT_OBJECT : TagFromClass(soa, o->GetClass());
Elliott Hughes24437992011-11-30 14:49:33 -0800479}
480
481static bool IsPrimitiveTag(JDWP::JdwpTag tag) {
482 switch (tag) {
483 case JDWP::JT_BOOLEAN:
484 case JDWP::JT_BYTE:
485 case JDWP::JT_CHAR:
486 case JDWP::JT_FLOAT:
487 case JDWP::JT_DOUBLE:
488 case JDWP::JT_INT:
489 case JDWP::JT_LONG:
490 case JDWP::JT_SHORT:
491 case JDWP::JT_VOID:
492 return true;
493 default:
494 return false;
495 }
496}
497
Sebastien Hertzb3b173b2015-02-06 09:16:32 +0100498void Dbg::StartJdwp() {
Elliott Hughesc0f09332012-03-26 13:27:06 -0700499 if (!gJdwpAllowed || !IsJdwpConfigured()) {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700500 // No JDWP for you!
501 return;
502 }
503
Ian Rogers719d1a32014-03-06 12:13:39 -0800504 CHECK(gRegistry == nullptr);
Elliott Hughes475fc232011-10-25 15:00:35 -0700505 gRegistry = new ObjectRegistry;
506
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700507 // Init JDWP if the debugger is enabled. This may connect out to a
508 // debugger, passively listen for a debugger, or block waiting for a
509 // debugger.
Sebastien Hertzb3b173b2015-02-06 09:16:32 +0100510 gJdwpState = JDWP::JdwpState::Create(&gJdwpOptions);
Ian Rogersc0542af2014-09-03 16:16:56 -0700511 if (gJdwpState == nullptr) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -0800512 // We probably failed because some other process has the port already, which means that
513 // if we don't abort the user is likely to think they're talking to us when they're actually
514 // talking to that other process.
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800515 LOG(FATAL) << "Debugger thread failed to initialize";
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700516 }
517
518 // If a debugger has already attached, send the "welcome" message.
519 // This may cause us to suspend all threads.
Elliott Hughes376a7a02011-10-24 18:35:55 -0700520 if (gJdwpState->IsActive()) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700521 ScopedObjectAccess soa(Thread::Current());
Sebastien Hertz7d955652014-10-22 10:57:10 +0200522 gJdwpState->PostVMStart();
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700523 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700524}
525
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700526void Dbg::StopJdwp() {
Sebastien Hertzc6345ef2014-08-18 19:26:39 +0200527 // Post VM_DEATH event before the JDWP connection is closed (either by the JDWP thread or the
528 // destruction of gJdwpState).
529 if (gJdwpState != nullptr && gJdwpState->IsActive()) {
530 gJdwpState->PostVMDeath();
531 }
Sebastien Hertz0376e6b2014-02-06 18:12:59 +0100532 // Prevent the JDWP thread from processing JDWP incoming packets after we close the connection.
Sebastien Hertz4e5b2082015-03-24 19:03:40 +0100533 Dispose();
Elliott Hughes376a7a02011-10-24 18:35:55 -0700534 delete gJdwpState;
Ian Rogers719d1a32014-03-06 12:13:39 -0800535 gJdwpState = nullptr;
Elliott Hughes475fc232011-10-25 15:00:35 -0700536 delete gRegistry;
Ian Rogers719d1a32014-03-06 12:13:39 -0800537 gRegistry = nullptr;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700538}
539
Elliott Hughes767a1472011-10-26 18:49:02 -0700540void Dbg::GcDidFinish() {
541 if (gDdmHpifWhen != HPIF_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700542 ScopedObjectAccess soa(Thread::Current());
Brian Carlstrom4d466a82014-05-08 19:05:29 -0700543 VLOG(jdwp) << "Sending heap info to DDM";
Elliott Hughes7162ad92011-10-27 14:08:42 -0700544 DdmSendHeapInfo(gDdmHpifWhen);
Elliott Hughes767a1472011-10-26 18:49:02 -0700545 }
546 if (gDdmHpsgWhen != HPSG_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700547 ScopedObjectAccess soa(Thread::Current());
Brian Carlstrom4d466a82014-05-08 19:05:29 -0700548 VLOG(jdwp) << "Dumping heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700549 DdmSendHeapSegments(false);
Elliott Hughes767a1472011-10-26 18:49:02 -0700550 }
551 if (gDdmNhsgWhen != HPSG_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700552 ScopedObjectAccess soa(Thread::Current());
Brian Carlstrom4d466a82014-05-08 19:05:29 -0700553 VLOG(jdwp) << "Dumping native heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700554 DdmSendHeapSegments(true);
Elliott Hughes767a1472011-10-26 18:49:02 -0700555 }
556}
557
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700558void Dbg::SetJdwpAllowed(bool allowed) {
559 gJdwpAllowed = allowed;
560}
561
Leonard Mosescueb842212016-10-06 17:26:36 -0700562bool Dbg::IsJdwpAllowed() {
563 return gJdwpAllowed;
564}
565
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700566DebugInvokeReq* Dbg::GetInvokeReq() {
Elliott Hughes475fc232011-10-25 15:00:35 -0700567 return Thread::Current()->GetInvokeReq();
568}
569
570Thread* Dbg::GetDebugThread() {
Ian Rogersc0542af2014-09-03 16:16:56 -0700571 return (gJdwpState != nullptr) ? gJdwpState->GetDebugThread() : nullptr;
Elliott Hughes475fc232011-10-25 15:00:35 -0700572}
573
574void Dbg::ClearWaitForEventThread() {
Sebastien Hertz2bf93f42015-01-09 18:44:05 +0100575 gJdwpState->ReleaseJdwpTokenForEvent();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700576}
577
578void Dbg::Connected() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700579 CHECK(!gDebuggerConnected);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800580 VLOG(jdwp) << "JDWP has attached";
Elliott Hughes3bb81562011-10-21 18:52:59 -0700581 gDebuggerConnected = true;
Elliott Hughes86964332012-02-15 19:37:42 -0800582 gDisposed = false;
583}
584
Sebastien Hertzf3928792014-11-17 19:00:37 +0100585bool Dbg::RequiresDeoptimization() {
586 // We don't need deoptimization if everything runs with interpreter after
587 // enabling -Xint mode.
588 return !Runtime::Current()->GetInstrumentation()->IsForcedInterpretOnly();
589}
590
Mingyao Yang6ea1a0e2016-01-29 12:12:49 -0800591// Used to patch boot image method entry point to interpreter bridge.
592class UpdateEntryPointsClassVisitor : public ClassVisitor {
593 public:
594 explicit UpdateEntryPointsClassVisitor(instrumentation::Instrumentation* instrumentation)
595 : instrumentation_(instrumentation) {}
596
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700597 bool operator()(ObjPtr<mirror::Class> klass) OVERRIDE REQUIRES(Locks::mutator_lock_) {
Mingyao Yang6ea1a0e2016-01-29 12:12:49 -0800598 auto pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
599 for (auto& m : klass->GetMethods(pointer_size)) {
600 const void* code = m.GetEntryPointFromQuickCompiledCode();
601 if (Runtime::Current()->GetHeap()->IsInBootImageOatFile(code) &&
602 !m.IsNative() &&
603 !m.IsProxyMethod()) {
Mingyao Yang3fd448a2016-05-10 14:30:41 -0700604 instrumentation_->UpdateMethodsCodeFromDebugger(&m, GetQuickToInterpreterBridge());
Mingyao Yang6ea1a0e2016-01-29 12:12:49 -0800605 }
606 }
607 return true;
608 }
609
610 private:
611 instrumentation::Instrumentation* const instrumentation_;
612};
613
Elliott Hughesa2155262011-11-16 16:26:58 -0800614void Dbg::GoActive() {
615 // Enable all debugging features, including scans for breakpoints.
616 // This is a no-op if we're already active.
617 // Only called from the JDWP handler thread.
Daniel Mihalyieb076692014-08-22 17:33:31 +0200618 if (IsDebuggerActive()) {
Elliott Hughesa2155262011-11-16 16:26:58 -0800619 return;
620 }
621
Mathieu Chartieraa516822015-10-02 15:53:37 -0700622 Thread* const self = Thread::Current();
Elliott Hughesc0f09332012-03-26 13:27:06 -0700623 {
624 // TODO: dalvik only warned if there were breakpoints left over. clear in Dbg::Disconnected?
Mathieu Chartieraa516822015-10-02 15:53:37 -0700625 ReaderMutexLock mu(self, *Locks::breakpoint_lock_);
Elliott Hughesc0f09332012-03-26 13:27:06 -0700626 CHECK_EQ(gBreakpoints.size(), 0U);
627 }
Elliott Hughesa2155262011-11-16 16:26:58 -0800628
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100629 {
Mathieu Chartieraa516822015-10-02 15:53:37 -0700630 MutexLock mu(self, *Locks::deoptimization_lock_);
Sebastien Hertz4d25df32014-03-21 17:44:46 +0100631 CHECK_EQ(deoptimization_requests_.size(), 0U);
632 CHECK_EQ(full_deoptimization_event_count_, 0U);
Sebastien Hertz42cd43f2014-05-13 14:15:41 +0200633 CHECK_EQ(dex_pc_change_event_ref_count_, 0U);
634 CHECK_EQ(method_enter_event_ref_count_, 0U);
635 CHECK_EQ(method_exit_event_ref_count_, 0U);
636 CHECK_EQ(field_read_event_ref_count_, 0U);
637 CHECK_EQ(field_write_event_ref_count_, 0U);
638 CHECK_EQ(exception_catch_event_ref_count_, 0U);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100639 }
640
Ian Rogers62d6c772013-02-27 08:32:07 -0800641 Runtime* runtime = Runtime::Current();
David Srbeckyf4480162016-03-16 00:06:24 +0000642 // Since boot image code may be AOT compiled as not debuggable, we need to patch
Mingyao Yang6ea1a0e2016-01-29 12:12:49 -0800643 // entry points of methods in boot image to interpreter bridge.
David Srbeckyf4480162016-03-16 00:06:24 +0000644 // However, the performance cost of this is non-negligible during native-debugging due to the
645 // forced JIT, so we keep the AOT code in that case in exchange for limited native debugging.
646 if (!runtime->GetInstrumentation()->IsForcedInterpretOnly() && !runtime->IsNativeDebuggable()) {
Mingyao Yang6ea1a0e2016-01-29 12:12:49 -0800647 ScopedObjectAccess soa(self);
648 UpdateEntryPointsClassVisitor visitor(runtime->GetInstrumentation());
649 runtime->GetClassLinker()->VisitClasses(&visitor);
650 }
651
Mathieu Chartier4f55e222015-09-04 13:26:21 -0700652 ScopedSuspendAll ssa(__FUNCTION__);
Sebastien Hertzf3928792014-11-17 19:00:37 +0100653 if (RequiresDeoptimization()) {
654 runtime->GetInstrumentation()->EnableDeoptimization();
655 }
Sebastien Hertz42cd43f2014-05-13 14:15:41 +0200656 instrumentation_events_ = 0;
Elliott Hughesa2155262011-11-16 16:26:58 -0800657 gDebuggerActive = true;
Ian Rogers62d6c772013-02-27 08:32:07 -0800658 LOG(INFO) << "Debugger is active";
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700659}
660
661void Dbg::Disconnected() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700662 CHECK(gDebuggerConnected);
663
Elliott Hughesc0f09332012-03-26 13:27:06 -0700664 LOG(INFO) << "Debugger is no longer active";
Elliott Hughes234ab152011-10-26 14:02:26 -0700665
Hiroshi Yamauchi98810e32016-05-24 14:55:40 -0700666 // Suspend all threads and exclusively acquire the mutator lock. Remove the debugger as a listener
Ian Rogers62d6c772013-02-27 08:32:07 -0800667 // and clear the object registry.
668 Runtime* runtime = Runtime::Current();
Ian Rogers62d6c772013-02-27 08:32:07 -0800669 Thread* self = Thread::Current();
Mathieu Chartier4f55e222015-09-04 13:26:21 -0700670 {
Mathieu Chartieraa516822015-10-02 15:53:37 -0700671 // Required for DisableDeoptimization.
672 gc::ScopedGCCriticalSection gcs(self,
673 gc::kGcCauseInstrumentation,
674 gc::kCollectorTypeInstrumentation);
Mathieu Chartier4f55e222015-09-04 13:26:21 -0700675 ScopedSuspendAll ssa(__FUNCTION__);
Mathieu Chartier4f55e222015-09-04 13:26:21 -0700676 // Debugger may not be active at this point.
677 if (IsDebuggerActive()) {
678 {
679 // Since we're going to disable deoptimization, we clear the deoptimization requests queue.
680 // This prevents us from having any pending deoptimization request when the debugger attaches
681 // to us again while no event has been requested yet.
Mathieu Chartiera6b1ead2015-10-06 10:32:38 -0700682 MutexLock mu(self, *Locks::deoptimization_lock_);
Mathieu Chartier4f55e222015-09-04 13:26:21 -0700683 deoptimization_requests_.clear();
684 full_deoptimization_event_count_ = 0U;
685 }
686 if (instrumentation_events_ != 0) {
687 runtime->GetInstrumentation()->RemoveListener(&gDebugInstrumentationListener,
688 instrumentation_events_);
689 instrumentation_events_ = 0;
690 }
691 if (RequiresDeoptimization()) {
692 runtime->GetInstrumentation()->DisableDeoptimization(kDbgInstrumentationKey);
693 }
694 gDebuggerActive = false;
Sebastien Hertzaaea7342014-02-25 15:10:04 +0100695 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100696 }
Sebastien Hertz55f65342015-01-13 22:48:34 +0100697
698 {
699 ScopedObjectAccess soa(self);
700 gRegistry->Clear();
701 }
702
703 gDebuggerConnected = false;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700704}
705
Sebastien Hertzb3b173b2015-02-06 09:16:32 +0100706void Dbg::ConfigureJdwp(const JDWP::JdwpOptions& jdwp_options) {
707 CHECK_NE(jdwp_options.transport, JDWP::kJdwpTransportUnknown);
708 gJdwpOptions = jdwp_options;
709 gJdwpConfigured = true;
710}
711
Elliott Hughesc0f09332012-03-26 13:27:06 -0700712bool Dbg::IsJdwpConfigured() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700713 return gJdwpConfigured;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700714}
715
716int64_t Dbg::LastDebuggerActivity() {
Elliott Hughesca951522011-12-05 12:01:32 -0800717 return gJdwpState->LastDebuggerActivity();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700718}
719
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700720void Dbg::UndoDebuggerSuspensions() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700721 Runtime::Current()->GetThreadList()->UndoDebuggerSuspensions();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700722}
723
Elliott Hughes88d63092013-01-09 09:55:54 -0800724std::string Dbg::GetClassName(JDWP::RefTypeId class_id) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700725 JDWP::JdwpError error;
726 mirror::Object* o = gRegistry->Get<mirror::Object*>(class_id, &error);
727 if (o == nullptr) {
728 if (error == JDWP::ERR_NONE) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700729 return "null";
Ian Rogersc0542af2014-09-03 16:16:56 -0700730 } else {
731 return StringPrintf("invalid object %p", reinterpret_cast<void*>(class_id));
732 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800733 }
734 if (!o->IsClass()) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700735 return StringPrintf("non-class %p", o); // This is only used for debugging output anyway.
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800736 }
Sebastien Hertz6995c602014-09-09 12:10:13 +0200737 return GetClassName(o->AsClass());
738}
739
740std::string Dbg::GetClassName(mirror::Class* klass) {
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +0200741 if (klass == nullptr) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700742 return "null";
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +0200743 }
Ian Rogers1ff3c982014-08-12 02:30:58 -0700744 std::string temp;
Sebastien Hertz6995c602014-09-09 12:10:13 +0200745 return DescriptorToName(klass->GetDescriptor(&temp));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700746}
747
Ian Rogersc0542af2014-09-03 16:16:56 -0700748JDWP::JdwpError Dbg::GetClassObject(JDWP::RefTypeId id, JDWP::ObjectId* class_object_id) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800749 JDWP::JdwpError status;
Ian Rogersc0542af2014-09-03 16:16:56 -0700750 mirror::Class* c = DecodeClass(id, &status);
751 if (c == nullptr) {
752 *class_object_id = 0;
Elliott Hughes436e3722012-02-17 20:01:47 -0800753 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800754 }
Ian Rogersc0542af2014-09-03 16:16:56 -0700755 *class_object_id = gRegistry->Add(c);
Elliott Hughes436e3722012-02-17 20:01:47 -0800756 return JDWP::ERR_NONE;
Elliott Hughes86964332012-02-15 19:37:42 -0800757}
758
Ian Rogersc0542af2014-09-03 16:16:56 -0700759JDWP::JdwpError Dbg::GetSuperclass(JDWP::RefTypeId id, JDWP::RefTypeId* superclass_id) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800760 JDWP::JdwpError status;
Ian Rogersc0542af2014-09-03 16:16:56 -0700761 mirror::Class* c = DecodeClass(id, &status);
762 if (c == nullptr) {
763 *superclass_id = 0;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800764 return status;
765 }
766 if (c->IsInterface()) {
767 // http://code.google.com/p/android/issues/detail?id=20856
Ian Rogersc0542af2014-09-03 16:16:56 -0700768 *superclass_id = 0;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800769 } else {
Ian Rogersc0542af2014-09-03 16:16:56 -0700770 *superclass_id = gRegistry->Add(c->GetSuperClass());
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800771 }
772 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700773}
774
Elliott Hughes436e3722012-02-17 20:01:47 -0800775JDWP::JdwpError Dbg::GetClassLoader(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700776 JDWP::JdwpError error;
Andreas Gampe7929a482015-12-30 19:33:49 -0800777 mirror::Class* c = DecodeClass(id, &error);
778 if (c == nullptr) {
779 return error;
Elliott Hughes436e3722012-02-17 20:01:47 -0800780 }
Andreas Gampe7929a482015-12-30 19:33:49 -0800781 expandBufAddObjectId(pReply, gRegistry->Add(c->GetClassLoader()));
Elliott Hughes436e3722012-02-17 20:01:47 -0800782 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700783}
784
Elliott Hughes436e3722012-02-17 20:01:47 -0800785JDWP::JdwpError Dbg::GetModifiers(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700786 JDWP::JdwpError error;
787 mirror::Class* c = DecodeClass(id, &error);
788 if (c == nullptr) {
789 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800790 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800791
792 uint32_t access_flags = c->GetAccessFlags() & kAccJavaFlagsMask;
793
Yevgeny Roubande34eea2014-02-15 01:06:03 +0700794 // Set ACC_SUPER. Dex files don't contain this flag but only classes are supposed to have it set,
795 // not interfaces.
Elliott Hughes436e3722012-02-17 20:01:47 -0800796 // Class.getModifiers doesn't return it, but JDWP does, so we set it here.
Yevgeny Roubande34eea2014-02-15 01:06:03 +0700797 if ((access_flags & kAccInterface) == 0) {
798 access_flags |= kAccSuper;
799 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800800
801 expandBufAdd4BE(pReply, access_flags);
802
803 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700804}
805
Ian Rogersc0542af2014-09-03 16:16:56 -0700806JDWP::JdwpError Dbg::GetMonitorInfo(JDWP::ObjectId object_id, JDWP::ExpandBuf* reply) {
807 JDWP::JdwpError error;
808 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
809 if (o == nullptr) {
Elliott Hughesf327e072013-01-09 16:01:26 -0800810 return JDWP::ERR_INVALID_OBJECT;
811 }
812
813 // Ensure all threads are suspended while we read objects' lock words.
814 Thread* self = Thread::Current();
Sebastien Hertz54263242014-03-19 18:16:50 +0100815 CHECK_EQ(self->GetState(), kRunnable);
Elliott Hughesf327e072013-01-09 16:01:26 -0800816
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700817 MonitorInfo monitor_info;
818 {
819 ScopedThreadSuspension sts(self, kSuspended);
Mathieu Chartier4f55e222015-09-04 13:26:21 -0700820 ScopedSuspendAll ssa(__FUNCTION__);
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700821 monitor_info = MonitorInfo(o);
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700822 }
Ian Rogersc0542af2014-09-03 16:16:56 -0700823 if (monitor_info.owner_ != nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700824 expandBufAddObjectId(reply, gRegistry->Add(monitor_info.owner_->GetPeer()));
Elliott Hughesf327e072013-01-09 16:01:26 -0800825 } else {
Ian Rogersc0542af2014-09-03 16:16:56 -0700826 expandBufAddObjectId(reply, gRegistry->Add(nullptr));
Elliott Hughesf327e072013-01-09 16:01:26 -0800827 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700828 expandBufAdd4BE(reply, monitor_info.entry_count_);
829 expandBufAdd4BE(reply, monitor_info.waiters_.size());
830 for (size_t i = 0; i < monitor_info.waiters_.size(); ++i) {
831 expandBufAddObjectId(reply, gRegistry->Add(monitor_info.waiters_[i]->GetPeer()));
Elliott Hughesf327e072013-01-09 16:01:26 -0800832 }
833 return JDWP::ERR_NONE;
834}
835
Elliott Hughes734b8c62013-01-11 15:32:45 -0800836JDWP::JdwpError Dbg::GetOwnedMonitors(JDWP::ObjectId thread_id,
Ian Rogersc0542af2014-09-03 16:16:56 -0700837 std::vector<JDWP::ObjectId>* monitors,
838 std::vector<uint32_t>* stack_depths) {
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800839 struct OwnedMonitorVisitor : public StackVisitor {
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700840 OwnedMonitorVisitor(Thread* thread, Context* context,
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -0700841 std::vector<JDWP::ObjectId>* monitor_vector,
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700842 std::vector<uint32_t>* stack_depth_vector)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700843 REQUIRES_SHARED(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +0100844 : StackVisitor(thread, context, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
845 current_stack_depth(0),
846 monitors(monitor_vector),
847 stack_depths(stack_depth_vector) {}
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800848
849 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
850 // annotalysis.
851 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
852 if (!GetMethod()->IsRuntimeMethod()) {
853 Monitor::VisitLocks(this, AppendOwnedMonitors, this);
Elliott Hughes734b8c62013-01-11 15:32:45 -0800854 ++current_stack_depth;
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800855 }
856 return true;
857 }
858
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -0700859 static void AppendOwnedMonitors(mirror::Object* owned_monitor, void* arg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700860 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers7a22fa62013-01-23 12:16:16 -0800861 OwnedMonitorVisitor* visitor = reinterpret_cast<OwnedMonitorVisitor*>(arg);
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -0700862 visitor->monitors->push_back(gRegistry->Add(owned_monitor));
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700863 visitor->stack_depths->push_back(visitor->current_stack_depth);
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800864 }
865
Elliott Hughes734b8c62013-01-11 15:32:45 -0800866 size_t current_stack_depth;
Ian Rogersc0542af2014-09-03 16:16:56 -0700867 std::vector<JDWP::ObjectId>* const monitors;
868 std::vector<uint32_t>* const stack_depths;
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800869 };
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800870
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700871 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz69206392015-04-07 15:54:25 +0200872 JDWP::JdwpError error;
873 Thread* thread = DecodeThread(soa, thread_id, &error);
874 if (thread == nullptr) {
875 return error;
876 }
877 if (!IsSuspendedForDebugger(soa, thread)) {
878 return JDWP::ERR_THREAD_NOT_SUSPENDED;
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700879 }
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -0700880 std::unique_ptr<Context> context(Context::Create());
Ian Rogersc0542af2014-09-03 16:16:56 -0700881 OwnedMonitorVisitor visitor(thread, context.get(), monitors, stack_depths);
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -0700882 visitor.WalkStack();
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800883 return JDWP::ERR_NONE;
884}
885
Sebastien Hertz52d131d2014-03-13 16:17:40 +0100886JDWP::JdwpError Dbg::GetContendedMonitor(JDWP::ObjectId thread_id,
Ian Rogersc0542af2014-09-03 16:16:56 -0700887 JDWP::ObjectId* contended_monitor) {
Elliott Hughesf9501702013-01-11 11:22:27 -0800888 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -0700889 *contended_monitor = 0;
Sebastien Hertz69206392015-04-07 15:54:25 +0200890 JDWP::JdwpError error;
891 Thread* thread = DecodeThread(soa, thread_id, &error);
892 if (thread == nullptr) {
893 return error;
Elliott Hughesf9501702013-01-11 11:22:27 -0800894 }
Sebastien Hertz69206392015-04-07 15:54:25 +0200895 if (!IsSuspendedForDebugger(soa, thread)) {
896 return JDWP::ERR_THREAD_NOT_SUSPENDED;
897 }
898 mirror::Object* contended_monitor_obj = Monitor::GetContendedMonitor(thread);
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700899 // Add() requires the thread_list_lock_ not held to avoid the lock
900 // level violation.
Ian Rogersc0542af2014-09-03 16:16:56 -0700901 *contended_monitor = gRegistry->Add(contended_monitor_obj);
Elliott Hughesf9501702013-01-11 11:22:27 -0800902 return JDWP::ERR_NONE;
903}
904
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800905JDWP::JdwpError Dbg::GetInstanceCounts(const std::vector<JDWP::RefTypeId>& class_ids,
Ian Rogersc0542af2014-09-03 16:16:56 -0700906 std::vector<uint64_t>* counts) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800907 gc::Heap* heap = Runtime::Current()->GetHeap();
908 heap->CollectGarbage(false);
Mathieu Chartiere8a3c572016-10-11 16:52:17 -0700909 VariableSizedHandleScope hs(Thread::Current());
Mathieu Chartier9d156d52016-10-06 17:44:26 -0700910 std::vector<Handle<mirror::Class>> classes;
Ian Rogersc0542af2014-09-03 16:16:56 -0700911 counts->clear();
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800912 for (size_t i = 0; i < class_ids.size(); ++i) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700913 JDWP::JdwpError error;
Mathieu Chartier9d156d52016-10-06 17:44:26 -0700914 ObjPtr<mirror::Class> c = DecodeClass(class_ids[i], &error);
Ian Rogersc0542af2014-09-03 16:16:56 -0700915 if (c == nullptr) {
916 return error;
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800917 }
Mathieu Chartier9d156d52016-10-06 17:44:26 -0700918 classes.push_back(hs.NewHandle(c));
Ian Rogersc0542af2014-09-03 16:16:56 -0700919 counts->push_back(0);
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800920 }
Ian Rogersc0542af2014-09-03 16:16:56 -0700921 heap->CountInstances(classes, false, &(*counts)[0]);
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800922 return JDWP::ERR_NONE;
923}
924
Ian Rogersc0542af2014-09-03 16:16:56 -0700925JDWP::JdwpError Dbg::GetInstances(JDWP::RefTypeId class_id, int32_t max_count,
926 std::vector<JDWP::ObjectId>* instances) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800927 gc::Heap* heap = Runtime::Current()->GetHeap();
928 // We only want reachable instances, so do a GC.
929 heap->CollectGarbage(false);
Ian Rogersc0542af2014-09-03 16:16:56 -0700930 JDWP::JdwpError error;
Mathieu Chartier9d156d52016-10-06 17:44:26 -0700931 ObjPtr<mirror::Class> c = DecodeClass(class_id, &error);
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800932 if (c == nullptr) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700933 return error;
Elliott Hughes3b78c942013-01-15 17:35:41 -0800934 }
Mathieu Chartier2d855952016-10-12 19:37:59 -0700935 VariableSizedHandleScope hs(Thread::Current());
936 std::vector<Handle<mirror::Object>> raw_instances;
937 Runtime::Current()->GetHeap()->GetInstances(hs, hs.NewHandle(c), max_count, raw_instances);
Elliott Hughes3b78c942013-01-15 17:35:41 -0800938 for (size_t i = 0; i < raw_instances.size(); ++i) {
Mathieu Chartier2d855952016-10-12 19:37:59 -0700939 instances->push_back(gRegistry->Add(raw_instances[i].Get()));
Elliott Hughes3b78c942013-01-15 17:35:41 -0800940 }
941 return JDWP::ERR_NONE;
942}
943
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800944JDWP::JdwpError Dbg::GetReferringObjects(JDWP::ObjectId object_id, int32_t max_count,
Ian Rogersc0542af2014-09-03 16:16:56 -0700945 std::vector<JDWP::ObjectId>* referring_objects) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800946 gc::Heap* heap = Runtime::Current()->GetHeap();
947 heap->CollectGarbage(false);
Ian Rogersc0542af2014-09-03 16:16:56 -0700948 JDWP::JdwpError error;
Mathieu Chartier9d156d52016-10-06 17:44:26 -0700949 ObjPtr<mirror::Object> o = gRegistry->Get<mirror::Object*>(object_id, &error);
Ian Rogersc0542af2014-09-03 16:16:56 -0700950 if (o == nullptr) {
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800951 return JDWP::ERR_INVALID_OBJECT;
952 }
Mathieu Chartieraea9bfb2016-10-12 19:19:56 -0700953 VariableSizedHandleScope hs(Thread::Current());
954 std::vector<Handle<mirror::Object>> raw_instances;
955 heap->GetReferringObjects(hs, hs.NewHandle(o), max_count, raw_instances);
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800956 for (size_t i = 0; i < raw_instances.size(); ++i) {
Mathieu Chartieraea9bfb2016-10-12 19:19:56 -0700957 referring_objects->push_back(gRegistry->Add(raw_instances[i].Get()));
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800958 }
959 return JDWP::ERR_NONE;
960}
961
Ian Rogersc0542af2014-09-03 16:16:56 -0700962JDWP::JdwpError Dbg::DisableCollection(JDWP::ObjectId object_id) {
963 JDWP::JdwpError error;
964 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
965 if (o == nullptr) {
Sebastien Hertze96060a2013-12-11 12:06:28 +0100966 return JDWP::ERR_INVALID_OBJECT;
967 }
Elliott Hughes64f574f2013-02-20 14:57:12 -0800968 gRegistry->DisableCollection(object_id);
969 return JDWP::ERR_NONE;
970}
971
Ian Rogersc0542af2014-09-03 16:16:56 -0700972JDWP::JdwpError Dbg::EnableCollection(JDWP::ObjectId object_id) {
973 JDWP::JdwpError error;
974 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
Sebastien Hertze96060a2013-12-11 12:06:28 +0100975 // Unlike DisableCollection, JDWP specs do not state an invalid object causes an error. The RI
976 // also ignores these cases and never return an error. However it's not obvious why this command
977 // should behave differently from DisableCollection and IsCollected commands. So let's be more
978 // strict and return an error if this happens.
Ian Rogersc0542af2014-09-03 16:16:56 -0700979 if (o == nullptr) {
Sebastien Hertze96060a2013-12-11 12:06:28 +0100980 return JDWP::ERR_INVALID_OBJECT;
981 }
Elliott Hughes64f574f2013-02-20 14:57:12 -0800982 gRegistry->EnableCollection(object_id);
983 return JDWP::ERR_NONE;
984}
985
Ian Rogersc0542af2014-09-03 16:16:56 -0700986JDWP::JdwpError Dbg::IsCollected(JDWP::ObjectId object_id, bool* is_collected) {
987 *is_collected = true;
Sebastien Hertz65637eb2014-01-10 17:40:02 +0100988 if (object_id == 0) {
989 // Null object id is invalid.
Sebastien Hertze96060a2013-12-11 12:06:28 +0100990 return JDWP::ERR_INVALID_OBJECT;
991 }
Sebastien Hertz65637eb2014-01-10 17:40:02 +0100992 // JDWP specs state an INVALID_OBJECT error is returned if the object ID is not valid. However
993 // the RI seems to ignore this and assume object has been collected.
Ian Rogersc0542af2014-09-03 16:16:56 -0700994 JDWP::JdwpError error;
995 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
996 if (o != nullptr) {
997 *is_collected = gRegistry->IsCollected(object_id);
Sebastien Hertz65637eb2014-01-10 17:40:02 +0100998 }
Elliott Hughes64f574f2013-02-20 14:57:12 -0800999 return JDWP::ERR_NONE;
1000}
1001
Ian Rogersc0542af2014-09-03 16:16:56 -07001002void Dbg::DisposeObject(JDWP::ObjectId object_id, uint32_t reference_count) {
Elliott Hughes64f574f2013-02-20 14:57:12 -08001003 gRegistry->DisposeObject(object_id, reference_count);
1004}
1005
Mathieu Chartier3398c782016-09-30 10:27:43 -07001006JDWP::JdwpTypeTag Dbg::GetTypeTag(ObjPtr<mirror::Class> klass) {
Sebastien Hertz4d8fd492014-03-28 16:29:41 +01001007 DCHECK(klass != nullptr);
1008 if (klass->IsArrayClass()) {
1009 return JDWP::TT_ARRAY;
1010 } else if (klass->IsInterface()) {
1011 return JDWP::TT_INTERFACE;
1012 } else {
1013 return JDWP::TT_CLASS;
1014 }
1015}
1016
Elliott Hughes88d63092013-01-09 09:55:54 -08001017JDWP::JdwpError Dbg::GetReflectedType(JDWP::RefTypeId class_id, JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001018 JDWP::JdwpError error;
1019 mirror::Class* c = DecodeClass(class_id, &error);
1020 if (c == nullptr) {
1021 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001022 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001023
Sebastien Hertz4d8fd492014-03-28 16:29:41 +01001024 JDWP::JdwpTypeTag type_tag = GetTypeTag(c);
1025 expandBufAdd1(pReply, type_tag);
Elliott Hughes88d63092013-01-09 09:55:54 -08001026 expandBufAddRefTypeId(pReply, class_id);
Elliott Hughes436e3722012-02-17 20:01:47 -08001027 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001028}
1029
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001030// Get the complete list of reference classes (i.e. all classes except
1031// the primitive types).
1032// Returns a newly-allocated buffer full of RefTypeId values.
1033class ClassListCreator : public ClassVisitor {
1034 public:
1035 explicit ClassListCreator(std::vector<JDWP::RefTypeId>* classes) : classes_(classes) {}
1036
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001037 bool operator()(ObjPtr<mirror::Class> c) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001038 if (!c->IsPrimitive()) {
1039 classes_->push_back(Dbg::GetObjectRegistry()->AddRefType(c));
1040 }
1041 return true;
1042 }
1043
1044 private:
1045 std::vector<JDWP::RefTypeId>* const classes_;
1046};
1047
Ian Rogersc0542af2014-09-03 16:16:56 -07001048void Dbg::GetClassList(std::vector<JDWP::RefTypeId>* classes) {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001049 ClassListCreator clc(classes);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001050 Runtime::Current()->GetClassLinker()->VisitClassesWithoutClassesLock(&clc);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001051}
1052
Ian Rogers1ff3c982014-08-12 02:30:58 -07001053JDWP::JdwpError Dbg::GetClassInfo(JDWP::RefTypeId class_id, JDWP::JdwpTypeTag* pTypeTag,
1054 uint32_t* pStatus, std::string* pDescriptor) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001055 JDWP::JdwpError error;
1056 mirror::Class* c = DecodeClass(class_id, &error);
1057 if (c == nullptr) {
1058 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001059 }
1060
Elliott Hughesa2155262011-11-16 16:26:58 -08001061 if (c->IsArrayClass()) {
1062 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
1063 *pTypeTag = JDWP::TT_ARRAY;
1064 } else {
1065 if (c->IsErroneous()) {
1066 *pStatus = JDWP::CS_ERROR;
1067 } else {
1068 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED | JDWP::CS_INITIALIZED;
1069 }
1070 *pTypeTag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
1071 }
1072
Ian Rogersc0542af2014-09-03 16:16:56 -07001073 if (pDescriptor != nullptr) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07001074 std::string temp;
1075 *pDescriptor = c->GetDescriptor(&temp);
Elliott Hughesa2155262011-11-16 16:26:58 -08001076 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001077 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001078}
1079
Ian Rogersc0542af2014-09-03 16:16:56 -07001080void Dbg::FindLoadedClassBySignature(const char* descriptor, std::vector<JDWP::RefTypeId>* ids) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001081 std::vector<ObjPtr<mirror::Class>> classes;
Igor Murashkinb1d8c312015-08-04 11:18:43 -07001082 Runtime::Current()->GetClassLinker()->LookupClasses(descriptor, classes);
Ian Rogersc0542af2014-09-03 16:16:56 -07001083 ids->clear();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001084 for (ObjPtr<mirror::Class> c : classes) {
1085 ids->push_back(gRegistry->Add(c));
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001086 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001087}
1088
Ian Rogersc0542af2014-09-03 16:16:56 -07001089JDWP::JdwpError Dbg::GetReferenceType(JDWP::ObjectId object_id, JDWP::ExpandBuf* pReply) {
1090 JDWP::JdwpError error;
1091 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
1092 if (o == nullptr) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001093 return JDWP::ERR_INVALID_OBJECT;
Elliott Hughes499c5132011-11-17 14:55:11 -08001094 }
Elliott Hughes2435a572012-02-17 16:07:41 -08001095
Sebastien Hertz4d8fd492014-03-28 16:29:41 +01001096 JDWP::JdwpTypeTag type_tag = GetTypeTag(o->GetClass());
Elliott Hughes64f574f2013-02-20 14:57:12 -08001097 JDWP::RefTypeId type_id = gRegistry->AddRefType(o->GetClass());
Elliott Hughes2435a572012-02-17 16:07:41 -08001098
1099 expandBufAdd1(pReply, type_tag);
1100 expandBufAddRefTypeId(pReply, type_id);
1101
1102 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001103}
1104
Ian Rogersfc0e94b2013-09-23 23:51:32 -07001105JDWP::JdwpError Dbg::GetSignature(JDWP::RefTypeId class_id, std::string* signature) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001106 JDWP::JdwpError error;
1107 mirror::Class* c = DecodeClass(class_id, &error);
1108 if (c == nullptr) {
1109 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001110 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07001111 std::string temp;
1112 *signature = c->GetDescriptor(&temp);
Elliott Hughes1fe7afb2012-02-13 17:23:03 -08001113 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001114}
1115
Ian Rogersc0542af2014-09-03 16:16:56 -07001116JDWP::JdwpError Dbg::GetSourceFile(JDWP::RefTypeId class_id, std::string* result) {
1117 JDWP::JdwpError error;
1118 mirror::Class* c = DecodeClass(class_id, &error);
Sebastien Hertz4206eb52014-06-05 10:15:45 +02001119 if (c == nullptr) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001120 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001121 }
Sebastien Hertz4206eb52014-06-05 10:15:45 +02001122 const char* source_file = c->GetSourceFile();
1123 if (source_file == nullptr) {
Sebastien Hertzb7054ba2014-03-13 11:52:31 +01001124 return JDWP::ERR_ABSENT_INFORMATION;
1125 }
Ian Rogersc0542af2014-09-03 16:16:56 -07001126 *result = source_file;
Elliott Hughes436e3722012-02-17 20:01:47 -08001127 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001128}
1129
Ian Rogersc0542af2014-09-03 16:16:56 -07001130JDWP::JdwpError Dbg::GetObjectTag(JDWP::ObjectId object_id, uint8_t* tag) {
Ian Rogers98379392014-02-24 16:53:16 -08001131 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07001132 JDWP::JdwpError error;
1133 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
1134 if (error != JDWP::ERR_NONE) {
1135 *tag = JDWP::JT_VOID;
1136 return error;
Elliott Hughes546b9862012-06-20 16:06:13 -07001137 }
Ian Rogersc0542af2014-09-03 16:16:56 -07001138 *tag = TagFromObject(soa, o);
Elliott Hughes546b9862012-06-20 16:06:13 -07001139 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001140}
1141
Elliott Hughesaed4be92011-12-02 16:16:23 -08001142size_t Dbg::GetTagWidth(JDWP::JdwpTag tag) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001143 switch (tag) {
1144 case JDWP::JT_VOID:
1145 return 0;
1146 case JDWP::JT_BYTE:
1147 case JDWP::JT_BOOLEAN:
1148 return 1;
1149 case JDWP::JT_CHAR:
1150 case JDWP::JT_SHORT:
1151 return 2;
1152 case JDWP::JT_FLOAT:
1153 case JDWP::JT_INT:
1154 return 4;
1155 case JDWP::JT_ARRAY:
1156 case JDWP::JT_OBJECT:
1157 case JDWP::JT_STRING:
1158 case JDWP::JT_THREAD:
1159 case JDWP::JT_THREAD_GROUP:
1160 case JDWP::JT_CLASS_LOADER:
1161 case JDWP::JT_CLASS_OBJECT:
1162 return sizeof(JDWP::ObjectId);
1163 case JDWP::JT_DOUBLE:
1164 case JDWP::JT_LONG:
1165 return 8;
1166 default:
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001167 LOG(FATAL) << "Unknown tag " << tag;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001168 return -1;
1169 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001170}
1171
Ian Rogersc0542af2014-09-03 16:16:56 -07001172JDWP::JdwpError Dbg::GetArrayLength(JDWP::ObjectId array_id, int32_t* length) {
1173 JDWP::JdwpError error;
1174 mirror::Array* a = DecodeNonNullArray(array_id, &error);
1175 if (a == nullptr) {
1176 return error;
Elliott Hughes24437992011-11-30 14:49:33 -08001177 }
Ian Rogersc0542af2014-09-03 16:16:56 -07001178 *length = a->GetLength();
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001179 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001180}
1181
Elliott Hughes88d63092013-01-09 09:55:54 -08001182JDWP::JdwpError Dbg::OutputArray(JDWP::ObjectId array_id, int offset, int count, JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001183 JDWP::JdwpError error;
1184 mirror::Array* a = DecodeNonNullArray(array_id, &error);
Ian Rogers98379392014-02-24 16:53:16 -08001185 if (a == nullptr) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001186 return error;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001187 }
Elliott Hughes24437992011-11-30 14:49:33 -08001188
1189 if (offset < 0 || count < 0 || offset > a->GetLength() || a->GetLength() - offset < count) {
1190 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001191 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughes24437992011-11-30 14:49:33 -08001192 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07001193 JDWP::JdwpTag element_tag = BasicTagFromClass(a->GetClass()->GetComponentType());
1194 expandBufAdd1(pReply, element_tag);
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001195 expandBufAdd4BE(pReply, count);
1196
Ian Rogers1ff3c982014-08-12 02:30:58 -07001197 if (IsPrimitiveTag(element_tag)) {
1198 size_t width = GetTagWidth(element_tag);
Elliott Hughes24437992011-11-30 14:49:33 -08001199 uint8_t* dst = expandBufAddSpace(pReply, count * width);
1200 if (width == 8) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001201 const uint64_t* src8 = reinterpret_cast<uint64_t*>(a->GetRawData(sizeof(uint64_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001202 for (int i = 0; i < count; ++i) JDWP::Write8BE(&dst, src8[offset + i]);
1203 } else if (width == 4) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001204 const uint32_t* src4 = reinterpret_cast<uint32_t*>(a->GetRawData(sizeof(uint32_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001205 for (int i = 0; i < count; ++i) JDWP::Write4BE(&dst, src4[offset + i]);
1206 } else if (width == 2) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001207 const uint16_t* src2 = reinterpret_cast<uint16_t*>(a->GetRawData(sizeof(uint16_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001208 for (int i = 0; i < count; ++i) JDWP::Write2BE(&dst, src2[offset + i]);
1209 } else {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001210 const uint8_t* src = reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint8_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001211 memcpy(dst, &src[offset * width], count * width);
1212 }
1213 } else {
Ian Rogers98379392014-02-24 16:53:16 -08001214 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001215 mirror::ObjectArray<mirror::Object>* oa = a->AsObjectArray<mirror::Object>();
Elliott Hughes24437992011-11-30 14:49:33 -08001216 for (int i = 0; i < count; ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001217 mirror::Object* element = oa->Get(offset + i);
Ian Rogers98379392014-02-24 16:53:16 -08001218 JDWP::JdwpTag specific_tag = (element != nullptr) ? TagFromObject(soa, element)
Ian Rogers1ff3c982014-08-12 02:30:58 -07001219 : element_tag;
Elliott Hughes24437992011-11-30 14:49:33 -08001220 expandBufAdd1(pReply, specific_tag);
1221 expandBufAddObjectId(pReply, gRegistry->Add(element));
1222 }
1223 }
1224
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001225 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001226}
1227
Ian Rogersef7d42f2014-01-06 12:55:46 -08001228template <typename T>
Ian Rogersc0542af2014-09-03 16:16:56 -07001229static void CopyArrayData(mirror::Array* a, JDWP::Request* src, int offset, int count)
Ian Rogersef7d42f2014-01-06 12:55:46 -08001230 NO_THREAD_SAFETY_ANALYSIS {
1231 // TODO: fix when annotalysis correctly handles non-member functions.
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001232 DCHECK(a->GetClass()->IsPrimitiveArray());
1233
Ian Rogersef7d42f2014-01-06 12:55:46 -08001234 T* dst = reinterpret_cast<T*>(a->GetRawData(sizeof(T), offset));
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001235 for (int i = 0; i < count; ++i) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001236 *dst++ = src->ReadValue(sizeof(T));
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001237 }
1238}
1239
Elliott Hughes88d63092013-01-09 09:55:54 -08001240JDWP::JdwpError Dbg::SetArrayElements(JDWP::ObjectId array_id, int offset, int count,
Ian Rogersc0542af2014-09-03 16:16:56 -07001241 JDWP::Request* request) {
1242 JDWP::JdwpError error;
1243 mirror::Array* dst = DecodeNonNullArray(array_id, &error);
1244 if (dst == nullptr) {
1245 return error;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001246 }
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001247
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001248 if (offset < 0 || count < 0 || offset > dst->GetLength() || dst->GetLength() - offset < count) {
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001249 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001250 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001251 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07001252 JDWP::JdwpTag element_tag = BasicTagFromClass(dst->GetClass()->GetComponentType());
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001253
Ian Rogers1ff3c982014-08-12 02:30:58 -07001254 if (IsPrimitiveTag(element_tag)) {
1255 size_t width = GetTagWidth(element_tag);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001256 if (width == 8) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001257 CopyArrayData<uint64_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001258 } else if (width == 4) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001259 CopyArrayData<uint32_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001260 } else if (width == 2) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001261 CopyArrayData<uint16_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001262 } else {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001263 CopyArrayData<uint8_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001264 }
1265 } else {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001266 mirror::ObjectArray<mirror::Object>* oa = dst->AsObjectArray<mirror::Object>();
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001267 for (int i = 0; i < count; ++i) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001268 JDWP::ObjectId id = request->ReadObjectId();
Ian Rogersc0542af2014-09-03 16:16:56 -07001269 mirror::Object* o = gRegistry->Get<mirror::Object*>(id, &error);
1270 if (error != JDWP::ERR_NONE) {
1271 return error;
Elliott Hughes436e3722012-02-17 20:01:47 -08001272 }
Sebastien Hertz2e1c16d2015-08-28 11:57:49 +02001273 // Check if the object's type is compatible with the array's type.
1274 if (o != nullptr && !o->InstanceOf(oa->GetClass()->GetComponentType())) {
1275 return JDWP::ERR_TYPE_MISMATCH;
1276 }
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001277 oa->Set<false>(offset + i, o);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001278 }
1279 }
1280
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001281 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001282}
1283
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001284JDWP::JdwpError Dbg::CreateString(const std::string& str, JDWP::ObjectId* new_string_id) {
1285 Thread* self = Thread::Current();
1286 mirror::String* new_string = mirror::String::AllocFromModifiedUtf8(self, str.c_str());
1287 if (new_string == nullptr) {
1288 DCHECK(self->IsExceptionPending());
1289 self->ClearException();
1290 LOG(ERROR) << "Could not allocate string";
1291 *new_string_id = 0;
1292 return JDWP::ERR_OUT_OF_MEMORY;
1293 }
1294 *new_string_id = gRegistry->Add(new_string);
1295 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001296}
1297
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001298JDWP::JdwpError Dbg::CreateObject(JDWP::RefTypeId class_id, JDWP::ObjectId* new_object_id) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001299 JDWP::JdwpError error;
1300 mirror::Class* c = DecodeClass(class_id, &error);
1301 if (c == nullptr) {
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001302 *new_object_id = 0;
Ian Rogersc0542af2014-09-03 16:16:56 -07001303 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001304 }
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001305 Thread* self = Thread::Current();
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001306 ObjPtr<mirror::Object> new_object;
Sebastien Hertz56d5e502015-11-03 17:38:35 +01001307 if (c->IsStringClass()) {
1308 // Special case for java.lang.String.
1309 gc::AllocatorType allocator_type = Runtime::Current()->GetHeap()->GetCurrentAllocator();
jessicahandojo3aaa37b2016-07-29 14:46:37 -07001310 new_object = mirror::String::AllocEmptyString<true>(self, allocator_type);
Sebastien Hertz56d5e502015-11-03 17:38:35 +01001311 } else {
1312 new_object = c->AllocObject(self);
1313 }
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001314 if (new_object == nullptr) {
1315 DCHECK(self->IsExceptionPending());
1316 self->ClearException();
David Sehr709b0702016-10-13 09:12:37 -07001317 LOG(ERROR) << "Could not allocate object of type " << mirror::Class::PrettyDescriptor(c);
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001318 *new_object_id = 0;
1319 return JDWP::ERR_OUT_OF_MEMORY;
1320 }
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001321 *new_object_id = gRegistry->Add(new_object.Ptr());
Elliott Hughes436e3722012-02-17 20:01:47 -08001322 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001323}
1324
Elliott Hughesbf13d362011-12-08 15:51:37 -08001325/*
1326 * Used by Eclipse's "Display" view to evaluate "new byte[5]" to get "(byte[]) [0, 0, 0, 0, 0]".
1327 */
Elliott Hughes88d63092013-01-09 09:55:54 -08001328JDWP::JdwpError Dbg::CreateArrayObject(JDWP::RefTypeId array_class_id, uint32_t length,
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001329 JDWP::ObjectId* new_array_id) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001330 JDWP::JdwpError error;
1331 mirror::Class* c = DecodeClass(array_class_id, &error);
1332 if (c == nullptr) {
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001333 *new_array_id = 0;
Ian Rogersc0542af2014-09-03 16:16:56 -07001334 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001335 }
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001336 Thread* self = Thread::Current();
1337 gc::Heap* heap = Runtime::Current()->GetHeap();
1338 mirror::Array* new_array = mirror::Array::Alloc<true>(self, c, length,
1339 c->GetComponentSizeShift(),
1340 heap->GetCurrentAllocator());
1341 if (new_array == nullptr) {
1342 DCHECK(self->IsExceptionPending());
1343 self->ClearException();
David Sehr709b0702016-10-13 09:12:37 -07001344 LOG(ERROR) << "Could not allocate array of type " << mirror::Class::PrettyDescriptor(c);
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001345 *new_array_id = 0;
1346 return JDWP::ERR_OUT_OF_MEMORY;
1347 }
1348 *new_array_id = gRegistry->Add(new_array);
Elliott Hughes436e3722012-02-17 20:01:47 -08001349 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001350}
1351
Mathieu Chartierc7853442015-03-27 14:35:38 -07001352JDWP::FieldId Dbg::ToFieldId(const ArtField* f) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001353 return static_cast<JDWP::FieldId>(reinterpret_cast<uintptr_t>(f));
Elliott Hughes03181a82011-11-17 17:22:21 -08001354}
1355
Alex Light6c8467f2015-11-20 15:03:26 -08001356static JDWP::MethodId ToMethodId(ArtMethod* m)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001357 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light6c8467f2015-11-20 15:03:26 -08001358 return static_cast<JDWP::MethodId>(reinterpret_cast<uintptr_t>(GetCanonicalMethod(m)));
Elliott Hughes03181a82011-11-17 17:22:21 -08001359}
1360
Mathieu Chartierc7853442015-03-27 14:35:38 -07001361static ArtField* FromFieldId(JDWP::FieldId fid)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001362 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001363 return reinterpret_cast<ArtField*>(static_cast<uintptr_t>(fid));
Elliott Hughesaed4be92011-12-02 16:16:23 -08001364}
1365
Mathieu Chartiere401d142015-04-22 13:56:20 -07001366static ArtMethod* FromMethodId(JDWP::MethodId mid)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001367 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001368 return reinterpret_cast<ArtMethod*>(static_cast<uintptr_t>(mid));
Elliott Hughes03181a82011-11-17 17:22:21 -08001369}
1370
Sebastien Hertz6995c602014-09-09 12:10:13 +02001371bool Dbg::MatchThread(JDWP::ObjectId expected_thread_id, Thread* event_thread) {
1372 CHECK(event_thread != nullptr);
1373 JDWP::JdwpError error;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001374 mirror::Object* expected_thread_peer = gRegistry->Get<mirror::Object*>(
1375 expected_thread_id, &error);
Sebastien Hertz6995c602014-09-09 12:10:13 +02001376 return expected_thread_peer == event_thread->GetPeer();
1377}
1378
1379bool Dbg::MatchLocation(const JDWP::JdwpLocation& expected_location,
1380 const JDWP::EventLocation& event_location) {
1381 if (expected_location.dex_pc != event_location.dex_pc) {
1382 return false;
1383 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001384 ArtMethod* m = FromMethodId(expected_location.method_id);
Sebastien Hertz6995c602014-09-09 12:10:13 +02001385 return m == event_location.method;
1386}
1387
Mathieu Chartier3398c782016-09-30 10:27:43 -07001388bool Dbg::MatchType(ObjPtr<mirror::Class> event_class, JDWP::RefTypeId class_id) {
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001389 if (event_class == nullptr) {
1390 return false;
1391 }
Sebastien Hertz6995c602014-09-09 12:10:13 +02001392 JDWP::JdwpError error;
Mathieu Chartier3398c782016-09-30 10:27:43 -07001393 ObjPtr<mirror::Class> expected_class = DecodeClass(class_id, &error);
Sebastien Hertz6995c602014-09-09 12:10:13 +02001394 CHECK(expected_class != nullptr);
1395 return expected_class->IsAssignableFrom(event_class);
1396}
1397
1398bool Dbg::MatchField(JDWP::RefTypeId expected_type_id, JDWP::FieldId expected_field_id,
Mathieu Chartierc7853442015-03-27 14:35:38 -07001399 ArtField* event_field) {
1400 ArtField* expected_field = FromFieldId(expected_field_id);
Sebastien Hertz6995c602014-09-09 12:10:13 +02001401 if (expected_field != event_field) {
1402 return false;
1403 }
1404 return Dbg::MatchType(event_field->GetDeclaringClass(), expected_type_id);
1405}
1406
1407bool Dbg::MatchInstance(JDWP::ObjectId expected_instance_id, mirror::Object* event_instance) {
1408 JDWP::JdwpError error;
1409 mirror::Object* modifier_instance = gRegistry->Get<mirror::Object*>(expected_instance_id, &error);
1410 return modifier_instance == event_instance;
1411}
1412
Mathieu Chartier90443472015-07-16 20:32:27 -07001413void Dbg::SetJdwpLocation(JDWP::JdwpLocation* location, ArtMethod* m, uint32_t dex_pc) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001414 if (m == nullptr) {
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001415 memset(location, 0, sizeof(*location));
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001416 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001417 mirror::Class* c = m->GetDeclaringClass();
Ian Rogersc0542af2014-09-03 16:16:56 -07001418 location->type_tag = GetTypeTag(c);
1419 location->class_id = gRegistry->AddRefType(c);
1420 location->method_id = ToMethodId(m);
1421 location->dex_pc = (m->IsNative() || m->IsProxyMethod()) ? static_cast<uint64_t>(-1) : dex_pc;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001422 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08001423}
1424
Ian Rogersc0542af2014-09-03 16:16:56 -07001425std::string Dbg::GetMethodName(JDWP::MethodId method_id) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001426 ArtMethod* m = FromMethodId(method_id);
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001427 if (m == nullptr) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001428 return "null";
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001429 }
Andreas Gampe542451c2016-07-26 09:02:02 -07001430 return m->GetInterfaceMethodIfProxy(kRuntimePointerSize)->GetName();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001431}
1432
Ian Rogersc0542af2014-09-03 16:16:56 -07001433std::string Dbg::GetFieldName(JDWP::FieldId field_id) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001434 ArtField* f = FromFieldId(field_id);
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001435 if (f == nullptr) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001436 return "null";
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001437 }
1438 return f->GetName();
Elliott Hughesa96836a2013-01-17 12:27:49 -08001439}
1440
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001441/*
1442 * Augment the access flags for synthetic methods and fields by setting
1443 * the (as described by the spec) "0xf0000000 bit". Also, strip out any
1444 * flags not specified by the Java programming language.
1445 */
1446static uint32_t MangleAccessFlags(uint32_t accessFlags) {
1447 accessFlags &= kAccJavaFlagsMask;
1448 if ((accessFlags & kAccSynthetic) != 0) {
1449 accessFlags |= 0xf0000000;
1450 }
1451 return accessFlags;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001452}
1453
Elliott Hughesdbb40792011-11-18 17:05:22 -08001454/*
Jeff Haob7cefc72013-11-14 14:51:09 -08001455 * Circularly shifts registers so that arguments come first. Debuggers
1456 * expect slots to begin with arguments, but dex code places them at
1457 * the end.
Elliott Hughesdbb40792011-11-18 17:05:22 -08001458 */
Mathieu Chartiere401d142015-04-22 13:56:20 -07001459static uint16_t MangleSlot(uint16_t slot, ArtMethod* m)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001460 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001461 const DexFile::CodeItem* code_item = m->GetCodeItem();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001462 if (code_item == nullptr) {
1463 // We should not get here for a method without code (native, proxy or abstract). Log it and
1464 // return the slot as is since all registers are arguments.
David Sehr709b0702016-10-13 09:12:37 -07001465 LOG(WARNING) << "Trying to mangle slot for method without code " << m->PrettyMethod();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001466 return slot;
1467 }
Jeff Haob7cefc72013-11-14 14:51:09 -08001468 uint16_t ins_size = code_item->ins_size_;
1469 uint16_t locals_size = code_item->registers_size_ - ins_size;
1470 if (slot >= locals_size) {
1471 return slot - locals_size;
1472 } else {
1473 return slot + ins_size;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001474 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001475}
1476
Sebastien Hertzaef0c912016-08-08 10:20:28 +02001477static size_t GetMethodNumArgRegistersIncludingThis(ArtMethod* method)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001478 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertzaef0c912016-08-08 10:20:28 +02001479 uint32_t num_registers = ArtMethod::NumArgRegisters(method->GetShorty());
1480 if (!method->IsStatic()) {
1481 ++num_registers;
1482 }
1483 return num_registers;
1484}
1485
Jeff Haob7cefc72013-11-14 14:51:09 -08001486/*
1487 * Circularly shifts registers so that arguments come last. Reverts
1488 * slots to dex style argument placement.
1489 */
Mathieu Chartiere401d142015-04-22 13:56:20 -07001490static uint16_t DemangleSlot(uint16_t slot, ArtMethod* m, JDWP::JdwpError* error)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001491 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001492 const DexFile::CodeItem* code_item = m->GetCodeItem();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001493 if (code_item == nullptr) {
1494 // We should not get here for a method without code (native, proxy or abstract). Log it and
1495 // return the slot as is since all registers are arguments.
David Sehr709b0702016-10-13 09:12:37 -07001496 LOG(WARNING) << "Trying to demangle slot for method without code "
1497 << m->PrettyMethod();
Sebastien Hertzaef0c912016-08-08 10:20:28 +02001498 uint16_t vreg_count = GetMethodNumArgRegistersIncludingThis(m);
Sebastien Hertzabbabc82015-03-26 08:47:47 +01001499 if (slot < vreg_count) {
1500 *error = JDWP::ERR_NONE;
1501 return slot;
1502 }
Jeff Haob7cefc72013-11-14 14:51:09 -08001503 } else {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01001504 if (slot < code_item->registers_size_) {
1505 uint16_t ins_size = code_item->ins_size_;
1506 uint16_t locals_size = code_item->registers_size_ - ins_size;
1507 *error = JDWP::ERR_NONE;
1508 return (slot < ins_size) ? slot + locals_size : slot - ins_size;
1509 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001510 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01001511
1512 // Slot is invalid in the method.
David Sehr709b0702016-10-13 09:12:37 -07001513 LOG(ERROR) << "Invalid local slot " << slot << " for method " << m->PrettyMethod();
Sebastien Hertzabbabc82015-03-26 08:47:47 +01001514 *error = JDWP::ERR_INVALID_SLOT;
1515 return DexFile::kDexNoIndex16;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001516}
1517
Mathieu Chartier90443472015-07-16 20:32:27 -07001518JDWP::JdwpError Dbg::OutputDeclaredFields(JDWP::RefTypeId class_id, bool with_generic,
1519 JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001520 JDWP::JdwpError error;
1521 mirror::Class* c = DecodeClass(class_id, &error);
1522 if (c == nullptr) {
1523 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001524 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001525
1526 size_t instance_field_count = c->NumInstanceFields();
1527 size_t static_field_count = c->NumStaticFields();
1528
1529 expandBufAdd4BE(pReply, instance_field_count + static_field_count);
1530
1531 for (size_t i = 0; i < instance_field_count + static_field_count; ++i) {
Mathieu Chartier90443472015-07-16 20:32:27 -07001532 ArtField* f = (i < instance_field_count) ? c->GetInstanceField(i) :
1533 c->GetStaticField(i - instance_field_count);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001534 expandBufAddFieldId(pReply, ToFieldId(f));
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001535 expandBufAddUtf8String(pReply, f->GetName());
1536 expandBufAddUtf8String(pReply, f->GetTypeDescriptor());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001537 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001538 static const char genericSignature[1] = "";
1539 expandBufAddUtf8String(pReply, genericSignature);
1540 }
1541 expandBufAdd4BE(pReply, MangleAccessFlags(f->GetAccessFlags()));
1542 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001543 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001544}
1545
Elliott Hughes88d63092013-01-09 09:55:54 -08001546JDWP::JdwpError Dbg::OutputDeclaredMethods(JDWP::RefTypeId class_id, bool with_generic,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001547 JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001548 JDWP::JdwpError error;
1549 mirror::Class* c = DecodeClass(class_id, &error);
1550 if (c == nullptr) {
1551 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001552 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001553
Alex Light51a64d52015-12-17 13:55:59 -08001554 expandBufAdd4BE(pReply, c->NumMethods());
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001555
Mathieu Chartiere401d142015-04-22 13:56:20 -07001556 auto* cl = Runtime::Current()->GetClassLinker();
1557 auto ptr_size = cl->GetImagePointerSize();
Alex Light51a64d52015-12-17 13:55:59 -08001558 for (ArtMethod& m : c->GetMethods(ptr_size)) {
1559 expandBufAddMethodId(pReply, ToMethodId(&m));
Andreas Gampe542451c2016-07-26 09:02:02 -07001560 expandBufAddUtf8String(pReply, m.GetInterfaceMethodIfProxy(kRuntimePointerSize)->GetName());
1561 expandBufAddUtf8String(
1562 pReply, m.GetInterfaceMethodIfProxy(kRuntimePointerSize)->GetSignature().ToString());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001563 if (with_generic) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001564 const char* generic_signature = "";
1565 expandBufAddUtf8String(pReply, generic_signature);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001566 }
Alex Light51a64d52015-12-17 13:55:59 -08001567 expandBufAdd4BE(pReply, MangleAccessFlags(m.GetAccessFlags()));
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001568 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001569 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001570}
1571
Elliott Hughes88d63092013-01-09 09:55:54 -08001572JDWP::JdwpError Dbg::OutputDeclaredInterfaces(JDWP::RefTypeId class_id, JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001573 JDWP::JdwpError error;
Mathieu Chartierf8322842014-05-16 10:59:25 -07001574 Thread* self = Thread::Current();
Vladimir Marko19a4d372016-12-08 14:41:46 +00001575 ObjPtr<mirror::Class> c = DecodeClass(class_id, &error);
1576 if (c == nullptr) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001577 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001578 }
Mathieu Chartierf8322842014-05-16 10:59:25 -07001579 size_t interface_count = c->NumDirectInterfaces();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001580 expandBufAdd4BE(pReply, interface_count);
1581 for (size_t i = 0; i < interface_count; ++i) {
Vladimir Marko19a4d372016-12-08 14:41:46 +00001582 ObjPtr<mirror::Class> interface = mirror::Class::GetDirectInterface(self, c, i);
1583 DCHECK(interface != nullptr);
1584 expandBufAddRefTypeId(pReply, gRegistry->AddRefType(interface));
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001585 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001586 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001587}
1588
Ian Rogersc0542af2014-09-03 16:16:56 -07001589void Dbg::OutputLineTable(JDWP::RefTypeId, JDWP::MethodId method_id, JDWP::ExpandBuf* pReply) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001590 struct DebugCallbackContext {
1591 int numItems;
1592 JDWP::ExpandBuf* pReply;
1593
David Srbeckyb06e28e2015-12-10 13:15:00 +00001594 static bool Callback(void* context, const DexFile::PositionInfo& entry) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001595 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
David Srbeckyb06e28e2015-12-10 13:15:00 +00001596 expandBufAdd8BE(pContext->pReply, entry.address_);
1597 expandBufAdd4BE(pContext->pReply, entry.line_);
Elliott Hughes03181a82011-11-17 17:22:21 -08001598 pContext->numItems++;
Sebastien Hertzf2910ee2013-10-19 16:39:24 +02001599 return false;
Elliott Hughes03181a82011-11-17 17:22:21 -08001600 }
1601 };
Mathieu Chartiere401d142015-04-22 13:56:20 -07001602 ArtMethod* m = FromMethodId(method_id);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001603 const DexFile::CodeItem* code_item = m->GetCodeItem();
Elliott Hughes03181a82011-11-17 17:22:21 -08001604 uint64_t start, end;
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001605 if (code_item == nullptr) {
1606 DCHECK(m->IsNative() || m->IsProxyMethod());
Elliott Hughes03181a82011-11-17 17:22:21 -08001607 start = -1;
1608 end = -1;
1609 } else {
1610 start = 0;
jeffhao14f0db92012-12-14 17:50:42 -08001611 // Return the index of the last instruction
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001612 end = code_item->insns_size_in_code_units_ - 1;
Elliott Hughes03181a82011-11-17 17:22:21 -08001613 }
1614
1615 expandBufAdd8BE(pReply, start);
1616 expandBufAdd8BE(pReply, end);
1617
1618 // Add numLines later
1619 size_t numLinesOffset = expandBufGetLength(pReply);
1620 expandBufAdd4BE(pReply, 0);
1621
1622 DebugCallbackContext context;
1623 context.numItems = 0;
1624 context.pReply = pReply;
1625
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001626 if (code_item != nullptr) {
David Srbeckyb06e28e2015-12-10 13:15:00 +00001627 m->GetDexFile()->DecodeDebugPositionInfo(code_item, DebugCallbackContext::Callback, &context);
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001628 }
Elliott Hughes03181a82011-11-17 17:22:21 -08001629
1630 JDWP::Set4BE(expandBufGetBuffer(pReply) + numLinesOffset, context.numItems);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001631}
1632
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001633void Dbg::OutputVariableTable(JDWP::RefTypeId, JDWP::MethodId method_id, bool with_generic,
1634 JDWP::ExpandBuf* pReply) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001635 struct DebugCallbackContext {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001636 ArtMethod* method;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001637 JDWP::ExpandBuf* pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001638 size_t variable_count;
1639 bool with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001640
David Srbeckyb06e28e2015-12-10 13:15:00 +00001641 static void Callback(void* context, const DexFile::LocalInfo& entry)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001642 REQUIRES_SHARED(Locks::mutator_lock_) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001643 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
1644
David Srbeckyb06e28e2015-12-10 13:15:00 +00001645 uint16_t slot = entry.reg_;
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001646 VLOG(jdwp) << StringPrintf(" %2zd: %d(%d) '%s' '%s' '%s' actual slot=%d mangled slot=%d",
David Srbeckyb06e28e2015-12-10 13:15:00 +00001647 pContext->variable_count, entry.start_address_,
1648 entry.end_address_ - entry.start_address_,
1649 entry.name_, entry.descriptor_, entry.signature_, slot,
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001650 MangleSlot(slot, pContext->method));
Elliott Hughesdbb40792011-11-18 17:05:22 -08001651
Jeff Haob7cefc72013-11-14 14:51:09 -08001652 slot = MangleSlot(slot, pContext->method);
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001653
David Srbeckyb06e28e2015-12-10 13:15:00 +00001654 expandBufAdd8BE(pContext->pReply, entry.start_address_);
1655 expandBufAddUtf8String(pContext->pReply, entry.name_);
1656 expandBufAddUtf8String(pContext->pReply, entry.descriptor_);
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001657 if (pContext->with_generic) {
David Srbeckyb06e28e2015-12-10 13:15:00 +00001658 expandBufAddUtf8String(pContext->pReply, entry.signature_);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001659 }
David Srbeckyb06e28e2015-12-10 13:15:00 +00001660 expandBufAdd4BE(pContext->pReply, entry.end_address_- entry.start_address_);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001661 expandBufAdd4BE(pContext->pReply, slot);
1662
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001663 ++pContext->variable_count;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001664 }
1665 };
Mathieu Chartiere401d142015-04-22 13:56:20 -07001666 ArtMethod* m = FromMethodId(method_id);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001667
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001668 // arg_count considers doubles and longs to take 2 units.
1669 // variable_count considers everything to take 1 unit.
Sebastien Hertzaef0c912016-08-08 10:20:28 +02001670 expandBufAdd4BE(pReply, GetMethodNumArgRegistersIncludingThis(m));
Elliott Hughesdbb40792011-11-18 17:05:22 -08001671
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001672 // We don't know the total number of variables yet, so leave a blank and update it later.
1673 size_t variable_count_offset = expandBufGetLength(pReply);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001674 expandBufAdd4BE(pReply, 0);
1675
1676 DebugCallbackContext context;
Jeff Haob7cefc72013-11-14 14:51:09 -08001677 context.method = m;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001678 context.pReply = pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001679 context.variable_count = 0;
1680 context.with_generic = with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001681
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001682 const DexFile::CodeItem* code_item = m->GetCodeItem();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001683 if (code_item != nullptr) {
David Srbeckyb06e28e2015-12-10 13:15:00 +00001684 m->GetDexFile()->DecodeDebugLocalInfo(
1685 code_item, m->IsStatic(), m->GetDexMethodIndex(), DebugCallbackContext::Callback,
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001686 &context);
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001687 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001688
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001689 JDWP::Set4BE(expandBufGetBuffer(pReply) + variable_count_offset, context.variable_count);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001690}
1691
Jeff Hao579b0242013-11-18 13:16:49 -08001692void Dbg::OutputMethodReturnValue(JDWP::MethodId method_id, const JValue* return_value,
1693 JDWP::ExpandBuf* pReply) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001694 ArtMethod* m = FromMethodId(method_id);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001695 JDWP::JdwpTag tag = BasicTagFromDescriptor(m->GetShorty());
Jeff Hao579b0242013-11-18 13:16:49 -08001696 OutputJValue(tag, return_value, pReply);
1697}
1698
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02001699void Dbg::OutputFieldValue(JDWP::FieldId field_id, const JValue* field_value,
1700 JDWP::ExpandBuf* pReply) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001701 ArtField* f = FromFieldId(field_id);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001702 JDWP::JdwpTag tag = BasicTagFromDescriptor(f->GetTypeDescriptor());
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02001703 OutputJValue(tag, field_value, pReply);
1704}
1705
Elliott Hughes9777ba22013-01-17 09:04:19 -08001706JDWP::JdwpError Dbg::GetBytecodes(JDWP::RefTypeId, JDWP::MethodId method_id,
Ian Rogersc0542af2014-09-03 16:16:56 -07001707 std::vector<uint8_t>* bytecodes) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001708 ArtMethod* m = FromMethodId(method_id);
Ian Rogersc0542af2014-09-03 16:16:56 -07001709 if (m == nullptr) {
Elliott Hughes9777ba22013-01-17 09:04:19 -08001710 return JDWP::ERR_INVALID_METHODID;
1711 }
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001712 const DexFile::CodeItem* code_item = m->GetCodeItem();
Elliott Hughes9777ba22013-01-17 09:04:19 -08001713 size_t byte_count = code_item->insns_size_in_code_units_ * 2;
1714 const uint8_t* begin = reinterpret_cast<const uint8_t*>(code_item->insns_);
1715 const uint8_t* end = begin + byte_count;
1716 for (const uint8_t* p = begin; p != end; ++p) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001717 bytecodes->push_back(*p);
Elliott Hughes9777ba22013-01-17 09:04:19 -08001718 }
1719 return JDWP::ERR_NONE;
1720}
1721
Elliott Hughes88d63092013-01-09 09:55:54 -08001722JDWP::JdwpTag Dbg::GetFieldBasicTag(JDWP::FieldId field_id) {
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001723 return BasicTagFromDescriptor(FromFieldId(field_id)->GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001724}
1725
Elliott Hughes88d63092013-01-09 09:55:54 -08001726JDWP::JdwpTag Dbg::GetStaticFieldBasicTag(JDWP::FieldId field_id) {
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001727 return BasicTagFromDescriptor(FromFieldId(field_id)->GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001728}
1729
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001730static JValue GetArtFieldValue(ArtField* f, mirror::Object* o)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001731 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001732 Primitive::Type fieldType = f->GetTypeAsPrimitiveType();
1733 JValue field_value;
1734 switch (fieldType) {
1735 case Primitive::kPrimBoolean:
1736 field_value.SetZ(f->GetBoolean(o));
1737 return field_value;
1738
1739 case Primitive::kPrimByte:
1740 field_value.SetB(f->GetByte(o));
1741 return field_value;
1742
1743 case Primitive::kPrimChar:
1744 field_value.SetC(f->GetChar(o));
1745 return field_value;
1746
1747 case Primitive::kPrimShort:
1748 field_value.SetS(f->GetShort(o));
1749 return field_value;
1750
1751 case Primitive::kPrimInt:
1752 case Primitive::kPrimFloat:
1753 // Int and Float must be treated as 32-bit values in JDWP.
1754 field_value.SetI(f->GetInt(o));
1755 return field_value;
1756
1757 case Primitive::kPrimLong:
1758 case Primitive::kPrimDouble:
1759 // Long and Double must be treated as 64-bit values in JDWP.
1760 field_value.SetJ(f->GetLong(o));
1761 return field_value;
1762
1763 case Primitive::kPrimNot:
Mathieu Chartier1cc62e42016-10-03 18:01:28 -07001764 field_value.SetL(f->GetObject(o).Ptr());
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001765 return field_value;
1766
1767 case Primitive::kPrimVoid:
1768 LOG(FATAL) << "Attempt to read from field of type 'void'";
1769 UNREACHABLE();
1770 }
1771 LOG(FATAL) << "Attempt to read from field of unknown type";
1772 UNREACHABLE();
1773}
1774
Elliott Hughes88d63092013-01-09 09:55:54 -08001775static JDWP::JdwpError GetFieldValueImpl(JDWP::RefTypeId ref_type_id, JDWP::ObjectId object_id,
1776 JDWP::FieldId field_id, JDWP::ExpandBuf* pReply,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001777 bool is_static)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001778 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001779 JDWP::JdwpError error;
1780 mirror::Class* c = DecodeClass(ref_type_id, &error);
1781 if (ref_type_id != 0 && c == nullptr) {
1782 return error;
Elliott Hughes0cf74332012-02-23 23:14:00 -08001783 }
1784
Jeff Haode19a252016-09-14 15:56:35 -07001785 Thread* self = Thread::Current();
1786 StackHandleScope<2> hs(self);
1787 MutableHandle<mirror::Object>
1788 o(hs.NewHandle(Dbg::GetObjectRegistry()->Get<mirror::Object*>(object_id, &error)));
1789 if ((!is_static && o.Get() == nullptr) || error != JDWP::ERR_NONE) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001790 return JDWP::ERR_INVALID_OBJECT;
1791 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001792 ArtField* f = FromFieldId(field_id);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001793
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001794 mirror::Class* receiver_class = c;
Jeff Haode19a252016-09-14 15:56:35 -07001795 if (receiver_class == nullptr && o.Get() != nullptr) {
Elliott Hughes0cf74332012-02-23 23:14:00 -08001796 receiver_class = o->GetClass();
1797 }
Jeff Haode19a252016-09-14 15:56:35 -07001798
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001799 // TODO: should we give up now if receiver_class is null?
Ian Rogersc0542af2014-09-03 16:16:56 -07001800 if (receiver_class != nullptr && !f->GetDeclaringClass()->IsAssignableFrom(receiver_class)) {
David Sehr709b0702016-10-13 09:12:37 -07001801 LOG(INFO) << "ERR_INVALID_FIELDID: " << f->PrettyField() << " "
1802 << receiver_class->PrettyClass();
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001803 return JDWP::ERR_INVALID_FIELDID;
1804 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001805
Jeff Haode19a252016-09-14 15:56:35 -07001806 // Ensure the field's class is initialized.
1807 Handle<mirror::Class> klass(hs.NewHandle(f->GetDeclaringClass()));
1808 if (!Runtime::Current()->GetClassLinker()->EnsureInitialized(self, klass, true, false)) {
David Sehr709b0702016-10-13 09:12:37 -07001809 LOG(WARNING) << "Not able to initialize class for SetValues: "
1810 << mirror::Class::PrettyClass(klass.Get());
Jeff Haode19a252016-09-14 15:56:35 -07001811 }
1812
Elliott Hughes0cf74332012-02-23 23:14:00 -08001813 // The RI only enforces the static/non-static mismatch in one direction.
1814 // TODO: should we change the tests and check both?
1815 if (is_static) {
1816 if (!f->IsStatic()) {
1817 return JDWP::ERR_INVALID_FIELDID;
1818 }
1819 } else {
1820 if (f->IsStatic()) {
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001821 LOG(WARNING) << "Ignoring non-nullptr receiver for ObjectReference.GetValues"
David Sehr709b0702016-10-13 09:12:37 -07001822 << " on static field " << f->PrettyField();
Elliott Hughes0cf74332012-02-23 23:14:00 -08001823 }
1824 }
jeffhao0dfbb7e2012-11-28 15:26:03 -08001825 if (f->IsStatic()) {
Jeff Haode19a252016-09-14 15:56:35 -07001826 o.Assign(f->GetDeclaringClass());
jeffhao0dfbb7e2012-11-28 15:26:03 -08001827 }
Elliott Hughes0cf74332012-02-23 23:14:00 -08001828
Jeff Haode19a252016-09-14 15:56:35 -07001829 JValue field_value(GetArtFieldValue(f, o.Get()));
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001830 JDWP::JdwpTag tag = BasicTagFromDescriptor(f->GetTypeDescriptor());
Jeff Hao579b0242013-11-18 13:16:49 -08001831 Dbg::OutputJValue(tag, &field_value, pReply);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001832 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001833}
1834
Elliott Hughes88d63092013-01-09 09:55:54 -08001835JDWP::JdwpError Dbg::GetFieldValue(JDWP::ObjectId object_id, JDWP::FieldId field_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001836 JDWP::ExpandBuf* pReply) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001837 return GetFieldValueImpl(0, object_id, field_id, pReply, false);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001838}
1839
Ian Rogersc0542af2014-09-03 16:16:56 -07001840JDWP::JdwpError Dbg::GetStaticFieldValue(JDWP::RefTypeId ref_type_id, JDWP::FieldId field_id,
1841 JDWP::ExpandBuf* pReply) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001842 return GetFieldValueImpl(ref_type_id, 0, field_id, pReply, true);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001843}
1844
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001845static JDWP::JdwpError SetArtFieldValue(ArtField* f, mirror::Object* o, uint64_t value, int width)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001846 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001847 Primitive::Type fieldType = f->GetTypeAsPrimitiveType();
1848 // Debugging only happens at runtime so we know we are not running in a transaction.
1849 static constexpr bool kNoTransactionMode = false;
1850 switch (fieldType) {
1851 case Primitive::kPrimBoolean:
1852 CHECK_EQ(width, 1);
1853 f->SetBoolean<kNoTransactionMode>(o, static_cast<uint8_t>(value));
1854 return JDWP::ERR_NONE;
1855
1856 case Primitive::kPrimByte:
1857 CHECK_EQ(width, 1);
1858 f->SetByte<kNoTransactionMode>(o, static_cast<uint8_t>(value));
1859 return JDWP::ERR_NONE;
1860
1861 case Primitive::kPrimChar:
1862 CHECK_EQ(width, 2);
1863 f->SetChar<kNoTransactionMode>(o, static_cast<uint16_t>(value));
1864 return JDWP::ERR_NONE;
1865
1866 case Primitive::kPrimShort:
1867 CHECK_EQ(width, 2);
1868 f->SetShort<kNoTransactionMode>(o, static_cast<int16_t>(value));
1869 return JDWP::ERR_NONE;
1870
1871 case Primitive::kPrimInt:
1872 case Primitive::kPrimFloat:
1873 CHECK_EQ(width, 4);
1874 // Int and Float must be treated as 32-bit values in JDWP.
1875 f->SetInt<kNoTransactionMode>(o, static_cast<int32_t>(value));
1876 return JDWP::ERR_NONE;
1877
1878 case Primitive::kPrimLong:
1879 case Primitive::kPrimDouble:
1880 CHECK_EQ(width, 8);
1881 // Long and Double must be treated as 64-bit values in JDWP.
1882 f->SetLong<kNoTransactionMode>(o, value);
1883 return JDWP::ERR_NONE;
1884
1885 case Primitive::kPrimNot: {
1886 JDWP::JdwpError error;
1887 mirror::Object* v = Dbg::GetObjectRegistry()->Get<mirror::Object*>(value, &error);
1888 if (error != JDWP::ERR_NONE) {
1889 return JDWP::ERR_INVALID_OBJECT;
1890 }
1891 if (v != nullptr) {
Mathieu Chartier3398c782016-09-30 10:27:43 -07001892 ObjPtr<mirror::Class> field_type;
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001893 {
1894 StackHandleScope<2> hs(Thread::Current());
1895 HandleWrapper<mirror::Object> h_v(hs.NewHandleWrapper(&v));
1896 HandleWrapper<mirror::Object> h_o(hs.NewHandleWrapper(&o));
1897 field_type = f->GetType<true>();
1898 }
1899 if (!field_type->IsAssignableFrom(v->GetClass())) {
1900 return JDWP::ERR_INVALID_OBJECT;
1901 }
1902 }
1903 f->SetObject<kNoTransactionMode>(o, v);
1904 return JDWP::ERR_NONE;
1905 }
1906
1907 case Primitive::kPrimVoid:
1908 LOG(FATAL) << "Attempt to write to field of type 'void'";
1909 UNREACHABLE();
1910 }
1911 LOG(FATAL) << "Attempt to write to field of unknown type";
1912 UNREACHABLE();
1913}
1914
Elliott Hughes88d63092013-01-09 09:55:54 -08001915static JDWP::JdwpError SetFieldValueImpl(JDWP::ObjectId object_id, JDWP::FieldId field_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001916 uint64_t value, int width, bool is_static)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001917 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001918 JDWP::JdwpError error;
Jeff Haode19a252016-09-14 15:56:35 -07001919 Thread* self = Thread::Current();
1920 StackHandleScope<2> hs(self);
1921 MutableHandle<mirror::Object>
1922 o(hs.NewHandle(Dbg::GetObjectRegistry()->Get<mirror::Object*>(object_id, &error)));
1923 if ((!is_static && o.Get() == nullptr) || error != JDWP::ERR_NONE) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001924 return JDWP::ERR_INVALID_OBJECT;
1925 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001926 ArtField* f = FromFieldId(field_id);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001927
Jeff Haode19a252016-09-14 15:56:35 -07001928 // Ensure the field's class is initialized.
1929 Handle<mirror::Class> klass(hs.NewHandle(f->GetDeclaringClass()));
1930 if (!Runtime::Current()->GetClassLinker()->EnsureInitialized(self, klass, true, false)) {
David Sehr709b0702016-10-13 09:12:37 -07001931 LOG(WARNING) << "Not able to initialize class for SetValues: "
1932 << mirror::Class::PrettyClass(klass.Get());
Jeff Haode19a252016-09-14 15:56:35 -07001933 }
1934
Elliott Hughes0cf74332012-02-23 23:14:00 -08001935 // The RI only enforces the static/non-static mismatch in one direction.
1936 // TODO: should we change the tests and check both?
1937 if (is_static) {
1938 if (!f->IsStatic()) {
1939 return JDWP::ERR_INVALID_FIELDID;
1940 }
1941 } else {
1942 if (f->IsStatic()) {
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001943 LOG(WARNING) << "Ignoring non-nullptr receiver for ObjectReference.SetValues"
David Sehr709b0702016-10-13 09:12:37 -07001944 << " on static field " << f->PrettyField();
Elliott Hughes0cf74332012-02-23 23:14:00 -08001945 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001946 }
jeffhao0dfbb7e2012-11-28 15:26:03 -08001947 if (f->IsStatic()) {
Jeff Haode19a252016-09-14 15:56:35 -07001948 o.Assign(f->GetDeclaringClass());
jeffhao0dfbb7e2012-11-28 15:26:03 -08001949 }
Jeff Haode19a252016-09-14 15:56:35 -07001950 return SetArtFieldValue(f, o.Get(), value, width);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001951}
1952
Elliott Hughes88d63092013-01-09 09:55:54 -08001953JDWP::JdwpError Dbg::SetFieldValue(JDWP::ObjectId object_id, JDWP::FieldId field_id, uint64_t value,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001954 int width) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001955 return SetFieldValueImpl(object_id, field_id, value, width, false);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001956}
1957
Elliott Hughes88d63092013-01-09 09:55:54 -08001958JDWP::JdwpError Dbg::SetStaticFieldValue(JDWP::FieldId field_id, uint64_t value, int width) {
1959 return SetFieldValueImpl(0, field_id, value, width, true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001960}
1961
Sebastien Hertzb0b0b492014-09-15 11:27:27 +02001962JDWP::JdwpError Dbg::StringToUtf8(JDWP::ObjectId string_id, std::string* str) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001963 JDWP::JdwpError error;
Sebastien Hertzb0b0b492014-09-15 11:27:27 +02001964 mirror::Object* obj = gRegistry->Get<mirror::Object*>(string_id, &error);
1965 if (error != JDWP::ERR_NONE) {
1966 return error;
1967 }
1968 if (obj == nullptr) {
1969 return JDWP::ERR_INVALID_OBJECT;
1970 }
1971 {
1972 ScopedObjectAccessUnchecked soa(Thread::Current());
Mathieu Chartier0795f232016-09-27 18:43:30 -07001973 ObjPtr<mirror::Class> java_lang_String =
1974 soa.Decode<mirror::Class>(WellKnownClasses::java_lang_String);
Sebastien Hertzb0b0b492014-09-15 11:27:27 +02001975 if (!java_lang_String->IsAssignableFrom(obj->GetClass())) {
1976 // This isn't a string.
1977 return JDWP::ERR_INVALID_STRING;
1978 }
1979 }
1980 *str = obj->AsString()->ToModifiedUtf8();
1981 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001982}
1983
Jeff Hao579b0242013-11-18 13:16:49 -08001984void Dbg::OutputJValue(JDWP::JdwpTag tag, const JValue* return_value, JDWP::ExpandBuf* pReply) {
1985 if (IsPrimitiveTag(tag)) {
1986 expandBufAdd1(pReply, tag);
1987 if (tag == JDWP::JT_BOOLEAN || tag == JDWP::JT_BYTE) {
1988 expandBufAdd1(pReply, return_value->GetI());
1989 } else if (tag == JDWP::JT_CHAR || tag == JDWP::JT_SHORT) {
1990 expandBufAdd2BE(pReply, return_value->GetI());
1991 } else if (tag == JDWP::JT_FLOAT || tag == JDWP::JT_INT) {
1992 expandBufAdd4BE(pReply, return_value->GetI());
1993 } else if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
1994 expandBufAdd8BE(pReply, return_value->GetJ());
1995 } else {
1996 CHECK_EQ(tag, JDWP::JT_VOID);
1997 }
1998 } else {
Ian Rogers98379392014-02-24 16:53:16 -08001999 ScopedObjectAccessUnchecked soa(Thread::Current());
Jeff Hao579b0242013-11-18 13:16:49 -08002000 mirror::Object* value = return_value->GetL();
Ian Rogers98379392014-02-24 16:53:16 -08002001 expandBufAdd1(pReply, TagFromObject(soa, value));
Jeff Hao579b0242013-11-18 13:16:49 -08002002 expandBufAddObjectId(pReply, gRegistry->Add(value));
2003 }
2004}
2005
Ian Rogersc0542af2014-09-03 16:16:56 -07002006JDWP::JdwpError Dbg::GetThreadName(JDWP::ObjectId thread_id, std::string* name) {
jeffhaoa77f0f62012-12-05 17:19:31 -08002007 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002008 JDWP::JdwpError error;
Roland Levillain4b8f1ec2015-08-26 18:34:03 +01002009 DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002010 if (error != JDWP::ERR_NONE && error != JDWP::ERR_THREAD_NOT_ALIVE) {
2011 return error;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08002012 }
Elliott Hughes221229c2013-01-08 18:17:50 -08002013
2014 // We still need to report the zombie threads' names, so we can't just call Thread::GetThreadName.
Ian Rogersc0542af2014-09-03 16:16:56 -07002015 mirror::Object* thread_object = gRegistry->Get<mirror::Object*>(thread_id, &error);
2016 CHECK(thread_object != nullptr) << error;
Mathieu Chartierc7853442015-03-27 14:35:38 -07002017 ArtField* java_lang_Thread_name_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08002018 jni::DecodeArtField(WellKnownClasses::java_lang_Thread_name);
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07002019 ObjPtr<mirror::String> s(java_lang_Thread_name_field->GetObject(thread_object)->AsString());
Ian Rogersc0542af2014-09-03 16:16:56 -07002020 if (s != nullptr) {
2021 *name = s->ToModifiedUtf8();
Elliott Hughes221229c2013-01-08 18:17:50 -08002022 }
2023 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002024}
2025
Elliott Hughes221229c2013-01-08 18:17:50 -08002026JDWP::JdwpError Dbg::GetThreadGroup(JDWP::ObjectId thread_id, JDWP::ExpandBuf* pReply) {
Sebastien Hertza06430c2014-09-15 19:21:30 +02002027 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002028 JDWP::JdwpError error;
2029 mirror::Object* thread_object = gRegistry->Get<mirror::Object*>(thread_id, &error);
2030 if (error != JDWP::ERR_NONE) {
Elliott Hughes2435a572012-02-17 16:07:41 -08002031 return JDWP::ERR_INVALID_OBJECT;
2032 }
Mathieu Chartier268764d2016-09-13 12:09:38 -07002033 ScopedAssertNoThreadSuspension ants("Debugger: GetThreadGroup");
Elliott Hughes2435a572012-02-17 16:07:41 -08002034 // Okay, so it's an object, but is it actually a thread?
Roland Levillain4b8f1ec2015-08-26 18:34:03 +01002035 DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002036 if (error == JDWP::ERR_THREAD_NOT_ALIVE) {
2037 // Zombie threads are in the null group.
2038 expandBufAddObjectId(pReply, JDWP::ObjectId(0));
Sebastien Hertz52d131d2014-03-13 16:17:40 +01002039 error = JDWP::ERR_NONE;
2040 } else if (error == JDWP::ERR_NONE) {
Mathieu Chartier0795f232016-09-27 18:43:30 -07002041 ObjPtr<mirror::Class> c = soa.Decode<mirror::Class>(WellKnownClasses::java_lang_Thread);
Sebastien Hertz52d131d2014-03-13 16:17:40 +01002042 CHECK(c != nullptr);
Andreas Gampe08883de2016-11-08 13:20:52 -08002043 ArtField* f = jni::DecodeArtField(WellKnownClasses::java_lang_Thread_group);
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07002044 CHECK(f != nullptr);
Mathieu Chartier3398c782016-09-30 10:27:43 -07002045 ObjPtr<mirror::Object> group = f->GetObject(thread_object);
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07002046 CHECK(group != nullptr);
Sebastien Hertz52d131d2014-03-13 16:17:40 +01002047 JDWP::ObjectId thread_group_id = gRegistry->Add(group);
2048 expandBufAddObjectId(pReply, thread_group_id);
Elliott Hughes221229c2013-01-08 18:17:50 -08002049 }
Sebastien Hertz52d131d2014-03-13 16:17:40 +01002050 return error;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002051}
2052
Sebastien Hertza06430c2014-09-15 19:21:30 +02002053static mirror::Object* DecodeThreadGroup(ScopedObjectAccessUnchecked& soa,
2054 JDWP::ObjectId thread_group_id, JDWP::JdwpError* error)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002055 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz6995c602014-09-09 12:10:13 +02002056 mirror::Object* thread_group = Dbg::GetObjectRegistry()->Get<mirror::Object*>(thread_group_id,
2057 error);
Sebastien Hertza06430c2014-09-15 19:21:30 +02002058 if (*error != JDWP::ERR_NONE) {
2059 return nullptr;
2060 }
2061 if (thread_group == nullptr) {
2062 *error = JDWP::ERR_INVALID_OBJECT;
2063 return nullptr;
2064 }
Mathieu Chartier0795f232016-09-27 18:43:30 -07002065 ObjPtr<mirror::Class> c =
2066 soa.Decode<mirror::Class>(WellKnownClasses::java_lang_ThreadGroup);
Ian Rogers98379392014-02-24 16:53:16 -08002067 CHECK(c != nullptr);
Sebastien Hertza06430c2014-09-15 19:21:30 +02002068 if (!c->IsAssignableFrom(thread_group->GetClass())) {
2069 // This is not a java.lang.ThreadGroup.
2070 *error = JDWP::ERR_INVALID_THREAD_GROUP;
2071 return nullptr;
2072 }
2073 *error = JDWP::ERR_NONE;
2074 return thread_group;
2075}
2076
2077JDWP::JdwpError Dbg::GetThreadGroupName(JDWP::ObjectId thread_group_id, JDWP::ExpandBuf* pReply) {
2078 ScopedObjectAccessUnchecked soa(Thread::Current());
2079 JDWP::JdwpError error;
2080 mirror::Object* thread_group = DecodeThreadGroup(soa, thread_group_id, &error);
2081 if (error != JDWP::ERR_NONE) {
2082 return error;
2083 }
Mathieu Chartier268764d2016-09-13 12:09:38 -07002084 ScopedAssertNoThreadSuspension ants("Debugger: GetThreadGroupName");
Andreas Gampe08883de2016-11-08 13:20:52 -08002085 ArtField* f = jni::DecodeArtField(WellKnownClasses::java_lang_ThreadGroup_name);
Ian Rogersc0542af2014-09-03 16:16:56 -07002086 CHECK(f != nullptr);
Mathieu Chartier3398c782016-09-30 10:27:43 -07002087 ObjPtr<mirror::String> s = f->GetObject(thread_group)->AsString();
Sebastien Hertza06430c2014-09-15 19:21:30 +02002088
2089 std::string thread_group_name(s->ToModifiedUtf8());
2090 expandBufAddUtf8String(pReply, thread_group_name);
2091 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002092}
2093
Sebastien Hertza06430c2014-09-15 19:21:30 +02002094JDWP::JdwpError Dbg::GetThreadGroupParent(JDWP::ObjectId thread_group_id, JDWP::ExpandBuf* pReply) {
Ian Rogers98379392014-02-24 16:53:16 -08002095 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002096 JDWP::JdwpError error;
Sebastien Hertza06430c2014-09-15 19:21:30 +02002097 mirror::Object* thread_group = DecodeThreadGroup(soa, thread_group_id, &error);
2098 if (error != JDWP::ERR_NONE) {
2099 return error;
2100 }
Mathieu Chartier3398c782016-09-30 10:27:43 -07002101 ObjPtr<mirror::Object> parent;
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07002102 {
Mathieu Chartier268764d2016-09-13 12:09:38 -07002103 ScopedAssertNoThreadSuspension ants("Debugger: GetThreadGroupParent");
Andreas Gampe08883de2016-11-08 13:20:52 -08002104 ArtField* f = jni::DecodeArtField(WellKnownClasses::java_lang_ThreadGroup_parent);
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07002105 CHECK(f != nullptr);
2106 parent = f->GetObject(thread_group);
2107 }
Sebastien Hertza06430c2014-09-15 19:21:30 +02002108 JDWP::ObjectId parent_group_id = gRegistry->Add(parent);
2109 expandBufAddObjectId(pReply, parent_group_id);
2110 return JDWP::ERR_NONE;
2111}
2112
Andreas Gampe08883de2016-11-08 13:20:52 -08002113static void GetChildThreadGroups(mirror::Object* thread_group,
Sebastien Hertza06430c2014-09-15 19:21:30 +02002114 std::vector<JDWP::ObjectId>* child_thread_group_ids)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002115 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertza06430c2014-09-15 19:21:30 +02002116 CHECK(thread_group != nullptr);
2117
Przemyslaw Szczepaniak464595f2015-11-24 11:59:59 +00002118 // Get the int "ngroups" count of this thread group...
Andreas Gampe08883de2016-11-08 13:20:52 -08002119 ArtField* ngroups_field = jni::DecodeArtField(WellKnownClasses::java_lang_ThreadGroup_ngroups);
Przemyslaw Szczepaniak464595f2015-11-24 11:59:59 +00002120 CHECK(ngroups_field != nullptr);
2121 const int32_t size = ngroups_field->GetInt(thread_group);
2122 if (size == 0) {
2123 return;
Sebastien Hertze49e1952014-10-13 11:27:13 +02002124 }
Sebastien Hertza06430c2014-09-15 19:21:30 +02002125
Przemyslaw Szczepaniak464595f2015-11-24 11:59:59 +00002126 // Get the ThreadGroup[] "groups" out of this thread group...
Andreas Gampe08883de2016-11-08 13:20:52 -08002127 ArtField* groups_field = jni::DecodeArtField(WellKnownClasses::java_lang_ThreadGroup_groups);
Mathieu Chartier3398c782016-09-30 10:27:43 -07002128 ObjPtr<mirror::Object> groups_array = groups_field->GetObject(thread_group);
Przemyslaw Szczepaniak464595f2015-11-24 11:59:59 +00002129
2130 CHECK(groups_array != nullptr);
2131 CHECK(groups_array->IsObjectArray());
2132
Mathieu Chartier3398c782016-09-30 10:27:43 -07002133 ObjPtr<mirror::ObjectArray<mirror::Object>> groups_array_as_array =
Przemyslaw Szczepaniak464595f2015-11-24 11:59:59 +00002134 groups_array->AsObjectArray<mirror::Object>();
Sebastien Hertza06430c2014-09-15 19:21:30 +02002135
2136 // Copy the first 'size' elements out of the array into the result.
Sebastien Hertz6995c602014-09-09 12:10:13 +02002137 ObjectRegistry* registry = Dbg::GetObjectRegistry();
Sebastien Hertza06430c2014-09-15 19:21:30 +02002138 for (int32_t i = 0; i < size; ++i) {
Przemyslaw Szczepaniak464595f2015-11-24 11:59:59 +00002139 child_thread_group_ids->push_back(registry->Add(groups_array_as_array->Get(i)));
Sebastien Hertza06430c2014-09-15 19:21:30 +02002140 }
2141}
2142
2143JDWP::JdwpError Dbg::GetThreadGroupChildren(JDWP::ObjectId thread_group_id,
2144 JDWP::ExpandBuf* pReply) {
2145 ScopedObjectAccessUnchecked soa(Thread::Current());
2146 JDWP::JdwpError error;
2147 mirror::Object* thread_group = DecodeThreadGroup(soa, thread_group_id, &error);
2148 if (error != JDWP::ERR_NONE) {
2149 return error;
2150 }
2151
2152 // Add child threads.
2153 {
2154 std::vector<JDWP::ObjectId> child_thread_ids;
2155 GetThreads(thread_group, &child_thread_ids);
2156 expandBufAdd4BE(pReply, child_thread_ids.size());
2157 for (JDWP::ObjectId child_thread_id : child_thread_ids) {
2158 expandBufAddObjectId(pReply, child_thread_id);
2159 }
2160 }
2161
2162 // Add child thread groups.
2163 {
2164 std::vector<JDWP::ObjectId> child_thread_groups_ids;
Andreas Gampe08883de2016-11-08 13:20:52 -08002165 GetChildThreadGroups(thread_group, &child_thread_groups_ids);
Sebastien Hertza06430c2014-09-15 19:21:30 +02002166 expandBufAdd4BE(pReply, child_thread_groups_ids.size());
2167 for (JDWP::ObjectId child_thread_group_id : child_thread_groups_ids) {
2168 expandBufAddObjectId(pReply, child_thread_group_id);
2169 }
2170 }
2171
2172 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002173}
2174
2175JDWP::ObjectId Dbg::GetSystemThreadGroupId() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002176 ScopedObjectAccessUnchecked soa(Thread::Current());
Andreas Gampe08883de2016-11-08 13:20:52 -08002177 ArtField* f = jni::DecodeArtField(WellKnownClasses::java_lang_ThreadGroup_systemThreadGroup);
Mathieu Chartier3398c782016-09-30 10:27:43 -07002178 ObjPtr<mirror::Object> group = f->GetObject(f->GetDeclaringClass());
Ian Rogers365c1022012-06-22 15:05:28 -07002179 return gRegistry->Add(group);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002180}
2181
Jeff Hao920af3e2013-08-28 15:46:38 -07002182JDWP::JdwpThreadStatus Dbg::ToJdwpThreadStatus(ThreadState state) {
2183 switch (state) {
2184 case kBlocked:
2185 return JDWP::TS_MONITOR;
2186 case kNative:
2187 case kRunnable:
2188 case kSuspended:
2189 return JDWP::TS_RUNNING;
2190 case kSleeping:
2191 return JDWP::TS_SLEEPING;
2192 case kStarting:
2193 case kTerminated:
2194 return JDWP::TS_ZOMBIE;
2195 case kTimedWaiting:
Sebastien Hertzbae182c2013-12-17 10:42:03 +01002196 case kWaitingForCheckPointsToRun:
Jeff Hao920af3e2013-08-28 15:46:38 -07002197 case kWaitingForDebuggerSend:
2198 case kWaitingForDebuggerSuspension:
2199 case kWaitingForDebuggerToAttach:
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002200 case kWaitingForDeoptimization:
Jeff Hao920af3e2013-08-28 15:46:38 -07002201 case kWaitingForGcToComplete:
Mathieu Chartierb43390c2015-05-12 10:47:11 -07002202 case kWaitingForGetObjectsAllocated:
Jeff Hao920af3e2013-08-28 15:46:38 -07002203 case kWaitingForJniOnLoad:
Sebastien Hertzbae182c2013-12-17 10:42:03 +01002204 case kWaitingForMethodTracingStart:
Jeff Hao920af3e2013-08-28 15:46:38 -07002205 case kWaitingForSignalCatcherOutput:
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -08002206 case kWaitingForVisitObjects:
Jeff Hao920af3e2013-08-28 15:46:38 -07002207 case kWaitingInMainDebuggerLoop:
2208 case kWaitingInMainSignalCatcherLoop:
2209 case kWaitingPerformingGc:
Mathieu Chartier90ef3db2015-08-04 15:19:41 -07002210 case kWaitingWeakGcRootRead:
Hiroshi Yamauchi76f55b02015-08-21 16:10:39 -07002211 case kWaitingForGcThreadFlip:
Jeff Hao920af3e2013-08-28 15:46:38 -07002212 case kWaiting:
2213 return JDWP::TS_WAIT;
2214 // Don't add a 'default' here so the compiler can spot incompatible enum changes.
2215 }
2216 LOG(FATAL) << "Unknown thread state: " << state;
2217 return JDWP::TS_ZOMBIE;
2218}
2219
Sebastien Hertz52d131d2014-03-13 16:17:40 +01002220JDWP::JdwpError Dbg::GetThreadStatus(JDWP::ObjectId thread_id, JDWP::JdwpThreadStatus* pThreadStatus,
2221 JDWP::JdwpSuspendStatus* pSuspendStatus) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002222 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes499c5132011-11-17 14:55:11 -08002223
Elliott Hughes9e0c1752013-01-09 14:02:58 -08002224 *pSuspendStatus = JDWP::SUSPEND_STATUS_NOT_SUSPENDED;
2225
Ian Rogersc0542af2014-09-03 16:16:56 -07002226 JDWP::JdwpError error;
2227 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002228 if (error != JDWP::ERR_NONE) {
2229 if (error == JDWP::ERR_THREAD_NOT_ALIVE) {
2230 *pThreadStatus = JDWP::TS_ZOMBIE;
Elliott Hughes221229c2013-01-08 18:17:50 -08002231 return JDWP::ERR_NONE;
2232 }
2233 return error;
Elliott Hughes499c5132011-11-17 14:55:11 -08002234 }
2235
Elliott Hughes9e0c1752013-01-09 14:02:58 -08002236 if (IsSuspendedForDebugger(soa, thread)) {
2237 *pSuspendStatus = JDWP::SUSPEND_STATUS_SUSPENDED;
Elliott Hughes499c5132011-11-17 14:55:11 -08002238 }
2239
Jeff Hao920af3e2013-08-28 15:46:38 -07002240 *pThreadStatus = ToJdwpThreadStatus(thread->GetState());
Elliott Hughes221229c2013-01-08 18:17:50 -08002241 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002242}
2243
Elliott Hughes221229c2013-01-08 18:17:50 -08002244JDWP::JdwpError Dbg::GetThreadDebugSuspendCount(JDWP::ObjectId thread_id, JDWP::ExpandBuf* pReply) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002245 ScopedObjectAccess soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002246 JDWP::JdwpError error;
2247 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002248 if (error != JDWP::ERR_NONE) {
2249 return error;
Elliott Hughes2435a572012-02-17 16:07:41 -08002250 }
Ian Rogers50b35e22012-10-04 10:09:15 -07002251 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002252 expandBufAdd4BE(pReply, thread->GetDebugSuspendCount());
Elliott Hughes2435a572012-02-17 16:07:41 -08002253 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002254}
2255
Elliott Hughesf9501702013-01-11 11:22:27 -08002256JDWP::JdwpError Dbg::Interrupt(JDWP::ObjectId thread_id) {
2257 ScopedObjectAccess soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002258 JDWP::JdwpError error;
2259 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughesf9501702013-01-11 11:22:27 -08002260 if (error != JDWP::ERR_NONE) {
2261 return error;
2262 }
Ian Rogersdd7624d2014-03-14 17:43:00 -07002263 thread->Interrupt(soa.Self());
Elliott Hughesf9501702013-01-11 11:22:27 -08002264 return JDWP::ERR_NONE;
2265}
2266
Andreas Gampe08883de2016-11-08 13:20:52 -08002267static bool IsInDesiredThreadGroup(mirror::Object* desired_thread_group, mirror::Object* peer)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002268 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz070f7322014-09-09 12:08:49 +02002269 // Do we want threads from all thread groups?
2270 if (desired_thread_group == nullptr) {
2271 return true;
2272 }
Andreas Gampe08883de2016-11-08 13:20:52 -08002273 ArtField* thread_group_field = jni::DecodeArtField(WellKnownClasses::java_lang_Thread_group);
Sebastien Hertz070f7322014-09-09 12:08:49 +02002274 DCHECK(thread_group_field != nullptr);
Mathieu Chartier3398c782016-09-30 10:27:43 -07002275 ObjPtr<mirror::Object> group = thread_group_field->GetObject(peer);
Sebastien Hertz070f7322014-09-09 12:08:49 +02002276 return (group == desired_thread_group);
2277}
2278
Sebastien Hertza06430c2014-09-15 19:21:30 +02002279void Dbg::GetThreads(mirror::Object* thread_group, std::vector<JDWP::ObjectId>* thread_ids) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002280 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz070f7322014-09-09 12:08:49 +02002281 std::list<Thread*> all_threads_list;
2282 {
2283 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
2284 all_threads_list = Runtime::Current()->GetThreadList()->GetList();
2285 }
2286 for (Thread* t : all_threads_list) {
2287 if (t == Dbg::GetDebugThread()) {
2288 // Skip the JDWP thread. Some debuggers get bent out of shape when they can't suspend and
2289 // query all threads, so it's easier if we just don't tell them about this thread.
2290 continue;
2291 }
2292 if (t->IsStillStarting()) {
2293 // This thread is being started (and has been registered in the thread list). However, it is
2294 // not completely started yet so we must ignore it.
2295 continue;
2296 }
2297 mirror::Object* peer = t->GetPeer();
2298 if (peer == nullptr) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002299 // 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 +02002300 // this thread yet.
2301 // TODO: if we identified threads to the debugger by their Thread*
2302 // rather than their peer's mirror::Object*, we could fix this.
2303 // Doing so might help us report ZOMBIE threads too.
2304 continue;
2305 }
Andreas Gampe08883de2016-11-08 13:20:52 -08002306 if (IsInDesiredThreadGroup(thread_group, peer)) {
Sebastien Hertz070f7322014-09-09 12:08:49 +02002307 thread_ids->push_back(gRegistry->Add(peer));
2308 }
2309 }
Elliott Hughescaf76542012-06-28 16:08:22 -07002310}
Elliott Hughesa2155262011-11-16 16:26:58 -08002311
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002312static int GetStackDepth(Thread* thread) REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002313 struct CountStackDepthVisitor : public StackVisitor {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002314 explicit CountStackDepthVisitor(Thread* thread_in)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01002315 : StackVisitor(thread_in, nullptr, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
2316 depth(0) {}
Ian Rogers0399dde2012-06-06 17:09:28 -07002317
Elliott Hughes64f574f2013-02-20 14:57:12 -08002318 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2319 // annotalysis.
2320 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07002321 if (!GetMethod()->IsRuntimeMethod()) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -08002322 ++depth;
2323 }
Elliott Hughes530fa002012-03-12 11:44:49 -07002324 return true;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08002325 }
2326 size_t depth;
2327 };
Elliott Hughes08fc03a2012-06-26 17:34:00 -07002328
Ian Rogers7a22fa62013-01-23 12:16:16 -08002329 CountStackDepthVisitor visitor(thread);
Ian Rogers0399dde2012-06-06 17:09:28 -07002330 visitor.WalkStack();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08002331 return visitor.depth;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002332}
2333
Ian Rogersc0542af2014-09-03 16:16:56 -07002334JDWP::JdwpError Dbg::GetThreadFrameCount(JDWP::ObjectId thread_id, size_t* result) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002335 ScopedObjectAccess soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002336 JDWP::JdwpError error;
2337 *result = 0;
2338 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002339 if (error != JDWP::ERR_NONE) {
2340 return error;
2341 }
Elliott Hughesf15f4a02013-01-09 10:09:38 -08002342 if (!IsSuspendedForDebugger(soa, thread)) {
2343 return JDWP::ERR_THREAD_NOT_SUSPENDED;
2344 }
Ian Rogersc0542af2014-09-03 16:16:56 -07002345 *result = GetStackDepth(thread);
Elliott Hughes221229c2013-01-08 18:17:50 -08002346 return JDWP::ERR_NONE;
Elliott Hughes86964332012-02-15 19:37:42 -08002347}
2348
Ian Rogers306057f2012-11-26 12:45:53 -08002349JDWP::JdwpError Dbg::GetThreadFrames(JDWP::ObjectId thread_id, size_t start_frame,
2350 size_t frame_count, JDWP::ExpandBuf* buf) {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002351 class GetFrameVisitor : public StackVisitor {
2352 public:
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002353 GetFrameVisitor(Thread* thread, size_t start_frame_in, size_t frame_count_in,
2354 JDWP::ExpandBuf* buf_in)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002355 REQUIRES_SHARED(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01002356 : StackVisitor(thread, nullptr, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
2357 depth_(0),
2358 start_frame_(start_frame_in),
2359 frame_count_(frame_count_in),
2360 buf_(buf_in) {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002361 expandBufAdd4BE(buf_, frame_count_);
Elliott Hughes03181a82011-11-17 17:22:21 -08002362 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002363
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002364 bool VisitFrame() OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002365 if (GetMethod()->IsRuntimeMethod()) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07002366 return true; // The debugger can't do anything useful with a frame that has no Method*.
Elliott Hughes03181a82011-11-17 17:22:21 -08002367 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002368 if (depth_ >= start_frame_ + frame_count_) {
Elliott Hughes530fa002012-03-12 11:44:49 -07002369 return false;
Elliott Hughes03181a82011-11-17 17:22:21 -08002370 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002371 if (depth_ >= start_frame_) {
2372 JDWP::FrameId frame_id(GetFrameId());
2373 JDWP::JdwpLocation location;
Sebastien Hertz6995c602014-09-09 12:10:13 +02002374 SetJdwpLocation(&location, GetMethod(), GetDexPc());
Ian Rogersef7d42f2014-01-06 12:55:46 -08002375 VLOG(jdwp) << StringPrintf(" Frame %3zd: id=%3" PRIu64 " ", depth_, frame_id) << location;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002376 expandBufAdd8BE(buf_, frame_id);
2377 expandBufAddLocation(buf_, location);
2378 }
2379 ++depth_;
Elliott Hughes530fa002012-03-12 11:44:49 -07002380 return true;
Elliott Hughes03181a82011-11-17 17:22:21 -08002381 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002382
2383 private:
2384 size_t depth_;
2385 const size_t start_frame_;
2386 const size_t frame_count_;
2387 JDWP::ExpandBuf* buf_;
Elliott Hughes03181a82011-11-17 17:22:21 -08002388 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002389
2390 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002391 JDWP::JdwpError error;
2392 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002393 if (error != JDWP::ERR_NONE) {
2394 return error;
2395 }
Elliott Hughesf15f4a02013-01-09 10:09:38 -08002396 if (!IsSuspendedForDebugger(soa, thread)) {
2397 return JDWP::ERR_THREAD_NOT_SUSPENDED;
2398 }
Ian Rogers7a22fa62013-01-23 12:16:16 -08002399 GetFrameVisitor visitor(thread, start_frame, frame_count, buf);
Ian Rogers0399dde2012-06-06 17:09:28 -07002400 visitor.WalkStack();
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002401 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002402}
2403
2404JDWP::ObjectId Dbg::GetThreadSelfId() {
Sebastien Hertz6995c602014-09-09 12:10:13 +02002405 return GetThreadId(Thread::Current());
2406}
2407
2408JDWP::ObjectId Dbg::GetThreadId(Thread* thread) {
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07002409 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz6995c602014-09-09 12:10:13 +02002410 return gRegistry->Add(thread->GetPeer());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002411}
2412
Elliott Hughes475fc232011-10-25 15:00:35 -07002413void Dbg::SuspendVM() {
Hiroshi Yamauchi8f95cf32016-04-19 11:14:06 -07002414 // Avoid a deadlock between GC and debugger where GC gets suspended during GC. b/25800335.
2415 gc::ScopedGCCriticalSection gcs(Thread::Current(),
2416 gc::kGcCauseDebugger,
2417 gc::kCollectorTypeDebugger);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002418 Runtime::Current()->GetThreadList()->SuspendAllForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002419}
2420
2421void Dbg::ResumeVM() {
Sebastien Hertz253fa552014-10-14 17:27:15 +02002422 Runtime::Current()->GetThreadList()->ResumeAllForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002423}
2424
Elliott Hughes221229c2013-01-08 18:17:50 -08002425JDWP::JdwpError Dbg::SuspendThread(JDWP::ObjectId thread_id, bool request_suspension) {
Ian Rogersf3d874c2014-07-17 18:52:42 -07002426 Thread* self = Thread::Current();
Ian Rogersc0542af2014-09-03 16:16:56 -07002427 ScopedLocalRef<jobject> peer(self->GetJniEnv(), nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002428 {
Ian Rogersf3d874c2014-07-17 18:52:42 -07002429 ScopedObjectAccess soa(self);
Ian Rogersc0542af2014-09-03 16:16:56 -07002430 JDWP::JdwpError error;
2431 peer.reset(soa.AddLocalReference<jobject>(gRegistry->Get<mirror::Object*>(thread_id, &error)));
Elliott Hughes4e235312011-12-02 11:34:15 -08002432 }
Ian Rogersc0542af2014-09-03 16:16:56 -07002433 if (peer.get() == nullptr) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002434 return JDWP::ERR_THREAD_NOT_ALIVE;
2435 }
Ian Rogers4ad5cd32014-11-11 23:08:07 -08002436 // Suspend thread to build stack trace.
Elliott Hughesf327e072013-01-09 16:01:26 -08002437 bool timed_out;
Brian Carlstromba32de42014-08-27 23:43:46 -07002438 ThreadList* thread_list = Runtime::Current()->GetThreadList();
2439 Thread* thread = thread_list->SuspendThreadByPeer(peer.get(), request_suspension, true,
2440 &timed_out);
Ian Rogersc0542af2014-09-03 16:16:56 -07002441 if (thread != nullptr) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002442 return JDWP::ERR_NONE;
Elliott Hughesf327e072013-01-09 16:01:26 -08002443 } else if (timed_out) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002444 return JDWP::ERR_INTERNAL;
2445 } else {
2446 return JDWP::ERR_THREAD_NOT_ALIVE;
2447 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002448}
2449
Elliott Hughes221229c2013-01-08 18:17:50 -08002450void Dbg::ResumeThread(JDWP::ObjectId thread_id) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002451 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002452 JDWP::JdwpError error;
2453 mirror::Object* peer = gRegistry->Get<mirror::Object*>(thread_id, &error);
2454 CHECK(peer != nullptr) << error;
jeffhaoa77f0f62012-12-05 17:19:31 -08002455 Thread* thread;
2456 {
2457 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
2458 thread = Thread::FromManagedThread(soa, peer);
2459 }
Ian Rogersc0542af2014-09-03 16:16:56 -07002460 if (thread == nullptr) {
Elliott Hughes4e235312011-12-02 11:34:15 -08002461 LOG(WARNING) << "No such thread for resume: " << peer;
2462 return;
2463 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002464 bool needs_resume;
2465 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002466 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002467 needs_resume = thread->GetSuspendCount() > 0;
2468 }
2469 if (needs_resume) {
Elliott Hughes546b9862012-06-20 16:06:13 -07002470 Runtime::Current()->GetThreadList()->Resume(thread, true);
2471 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002472}
2473
2474void Dbg::SuspendSelf() {
Elliott Hughes475fc232011-10-25 15:00:35 -07002475 Runtime::Current()->GetThreadList()->SuspendSelfForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002476}
2477
Ian Rogers0399dde2012-06-06 17:09:28 -07002478struct GetThisVisitor : public StackVisitor {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002479 GetThisVisitor(Thread* thread, Context* context, JDWP::FrameId frame_id_in)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002480 REQUIRES_SHARED(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01002481 : StackVisitor(thread, context, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
2482 this_object(nullptr),
2483 frame_id(frame_id_in) {}
Ian Rogers0399dde2012-06-06 17:09:28 -07002484
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002485 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2486 // annotalysis.
2487 virtual bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002488 if (frame_id != GetFrameId()) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002489 return true; // continue
Ian Rogers0399dde2012-06-06 17:09:28 -07002490 } else {
Ian Rogers62d6c772013-02-27 08:32:07 -08002491 this_object = GetThisObject();
2492 return false;
Ian Rogers0399dde2012-06-06 17:09:28 -07002493 }
Elliott Hughes86b00102011-12-05 17:54:26 -08002494 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002495
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002496 mirror::Object* this_object;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002497 JDWP::FrameId frame_id;
Ian Rogers0399dde2012-06-06 17:09:28 -07002498};
2499
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002500JDWP::JdwpError Dbg::GetThisObject(JDWP::ObjectId thread_id, JDWP::FrameId frame_id,
2501 JDWP::ObjectId* result) {
2502 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz69206392015-04-07 15:54:25 +02002503 JDWP::JdwpError error;
2504 Thread* thread = DecodeThread(soa, thread_id, &error);
2505 if (error != JDWP::ERR_NONE) {
2506 return error;
2507 }
2508 if (!IsSuspendedForDebugger(soa, thread)) {
2509 return JDWP::ERR_THREAD_NOT_SUSPENDED;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002510 }
Ian Rogers700a4022014-05-19 16:49:03 -07002511 std::unique_ptr<Context> context(Context::Create());
Ian Rogers7a22fa62013-01-23 12:16:16 -08002512 GetThisVisitor visitor(thread, context.get(), frame_id);
Ian Rogers0399dde2012-06-06 17:09:28 -07002513 visitor.WalkStack();
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002514 *result = gRegistry->Add(visitor.this_object);
2515 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002516}
2517
Sebastien Hertz8009f392014-09-01 17:07:11 +02002518// Walks the stack until we find the frame with the given FrameId.
2519class FindFrameVisitor FINAL : public StackVisitor {
2520 public:
2521 FindFrameVisitor(Thread* thread, Context* context, JDWP::FrameId frame_id)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002522 REQUIRES_SHARED(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01002523 : StackVisitor(thread, context, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
2524 frame_id_(frame_id),
2525 error_(JDWP::ERR_INVALID_FRAMEID) {}
Ian Rogersca190662012-06-26 15:45:57 -07002526
Sebastien Hertz8009f392014-09-01 17:07:11 +02002527 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2528 // annotalysis.
2529 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
2530 if (GetFrameId() != frame_id_) {
2531 return true; // Not our frame, carry on.
Ian Rogers0399dde2012-06-06 17:09:28 -07002532 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07002533 ArtMethod* m = GetMethod();
Sebastien Hertz8009f392014-09-01 17:07:11 +02002534 if (m->IsNative()) {
2535 // We can't read/write local value from/into native method.
2536 error_ = JDWP::ERR_OPAQUE_FRAME;
2537 } else {
2538 // We found our frame.
2539 error_ = JDWP::ERR_NONE;
2540 }
2541 return false;
2542 }
2543
2544 JDWP::JdwpError GetError() const {
2545 return error_;
2546 }
2547
2548 private:
2549 const JDWP::FrameId frame_id_;
2550 JDWP::JdwpError error_;
Sebastien Hertz26f72862015-09-15 09:52:07 +02002551
2552 DISALLOW_COPY_AND_ASSIGN(FindFrameVisitor);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002553};
2554
2555JDWP::JdwpError Dbg::GetLocalValues(JDWP::Request* request, JDWP::ExpandBuf* pReply) {
2556 JDWP::ObjectId thread_id = request->ReadThreadId();
2557 JDWP::FrameId frame_id = request->ReadFrameId();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002558
2559 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz69206392015-04-07 15:54:25 +02002560 JDWP::JdwpError error;
2561 Thread* thread = DecodeThread(soa, thread_id, &error);
2562 if (error != JDWP::ERR_NONE) {
2563 return error;
2564 }
2565 if (!IsSuspendedForDebugger(soa, thread)) {
2566 return JDWP::ERR_THREAD_NOT_SUSPENDED;
Elliott Hughes221229c2013-01-08 18:17:50 -08002567 }
Sebastien Hertz8009f392014-09-01 17:07:11 +02002568 // Find the frame with the given frame_id.
Ian Rogers700a4022014-05-19 16:49:03 -07002569 std::unique_ptr<Context> context(Context::Create());
Sebastien Hertz8009f392014-09-01 17:07:11 +02002570 FindFrameVisitor visitor(thread, context.get(), frame_id);
Ian Rogers0399dde2012-06-06 17:09:28 -07002571 visitor.WalkStack();
Sebastien Hertz8009f392014-09-01 17:07:11 +02002572 if (visitor.GetError() != JDWP::ERR_NONE) {
2573 return visitor.GetError();
2574 }
2575
2576 // Read the values from visitor's context.
2577 int32_t slot_count = request->ReadSigned32("slot count");
2578 expandBufAdd4BE(pReply, slot_count); /* "int values" */
2579 for (int32_t i = 0; i < slot_count; ++i) {
2580 uint32_t slot = request->ReadUnsigned32("slot");
2581 JDWP::JdwpTag reqSigByte = request->ReadTag();
2582
2583 VLOG(jdwp) << " --> slot " << slot << " " << reqSigByte;
2584
2585 size_t width = Dbg::GetTagWidth(reqSigByte);
Sebastien Hertz7d955652014-10-22 10:57:10 +02002586 uint8_t* ptr = expandBufAddSpace(pReply, width + 1);
Sebastien Hertz69206392015-04-07 15:54:25 +02002587 error = Dbg::GetLocalValue(visitor, soa, slot, reqSigByte, ptr, width);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002588 if (error != JDWP::ERR_NONE) {
2589 return error;
2590 }
2591 }
2592 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002593}
2594
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002595constexpr JDWP::JdwpError kStackFrameLocalAccessError = JDWP::ERR_ABSENT_INFORMATION;
2596
2597static std::string GetStackContextAsString(const StackVisitor& visitor)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002598 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002599 return StringPrintf(" at DEX pc 0x%08x in method %s", visitor.GetDexPc(false),
David Sehr709b0702016-10-13 09:12:37 -07002600 ArtMethod::PrettyMethod(visitor.GetMethod()).c_str());
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002601}
2602
2603static JDWP::JdwpError FailGetLocalValue(const StackVisitor& visitor, uint16_t vreg,
2604 JDWP::JdwpTag tag)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002605 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002606 LOG(ERROR) << "Failed to read " << tag << " local from register v" << vreg
2607 << GetStackContextAsString(visitor);
2608 return kStackFrameLocalAccessError;
2609}
2610
Sebastien Hertz8009f392014-09-01 17:07:11 +02002611JDWP::JdwpError Dbg::GetLocalValue(const StackVisitor& visitor, ScopedObjectAccessUnchecked& soa,
2612 int slot, JDWP::JdwpTag tag, uint8_t* buf, size_t width) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002613 ArtMethod* m = visitor.GetMethod();
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002614 JDWP::JdwpError error = JDWP::ERR_NONE;
2615 uint16_t vreg = DemangleSlot(slot, m, &error);
2616 if (error != JDWP::ERR_NONE) {
2617 return error;
2618 }
Sebastien Hertz8009f392014-09-01 17:07:11 +02002619 // TODO: check that the tag is compatible with the actual type of the slot!
Sebastien Hertz8009f392014-09-01 17:07:11 +02002620 switch (tag) {
2621 case JDWP::JT_BOOLEAN: {
2622 CHECK_EQ(width, 1U);
2623 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002624 if (!visitor.GetVReg(m, vreg, kIntVReg, &intVal)) {
2625 return FailGetLocalValue(visitor, vreg, tag);
Ian Rogers0399dde2012-06-06 17:09:28 -07002626 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002627 VLOG(jdwp) << "get boolean local " << vreg << " = " << intVal;
2628 JDWP::Set1(buf + 1, intVal != 0);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002629 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002630 }
Sebastien Hertz8009f392014-09-01 17:07:11 +02002631 case JDWP::JT_BYTE: {
2632 CHECK_EQ(width, 1U);
2633 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002634 if (!visitor.GetVReg(m, vreg, kIntVReg, &intVal)) {
2635 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002636 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002637 VLOG(jdwp) << "get byte local " << vreg << " = " << intVal;
2638 JDWP::Set1(buf + 1, intVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002639 break;
2640 }
2641 case JDWP::JT_SHORT:
2642 case JDWP::JT_CHAR: {
2643 CHECK_EQ(width, 2U);
2644 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002645 if (!visitor.GetVReg(m, vreg, kIntVReg, &intVal)) {
2646 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002647 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002648 VLOG(jdwp) << "get short/char local " << vreg << " = " << intVal;
2649 JDWP::Set2BE(buf + 1, intVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002650 break;
2651 }
2652 case JDWP::JT_INT: {
2653 CHECK_EQ(width, 4U);
2654 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002655 if (!visitor.GetVReg(m, vreg, kIntVReg, &intVal)) {
2656 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002657 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002658 VLOG(jdwp) << "get int local " << vreg << " = " << intVal;
2659 JDWP::Set4BE(buf + 1, intVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002660 break;
2661 }
2662 case JDWP::JT_FLOAT: {
2663 CHECK_EQ(width, 4U);
2664 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002665 if (!visitor.GetVReg(m, vreg, kFloatVReg, &intVal)) {
2666 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002667 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002668 VLOG(jdwp) << "get float local " << vreg << " = " << intVal;
2669 JDWP::Set4BE(buf + 1, intVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002670 break;
2671 }
2672 case JDWP::JT_ARRAY:
2673 case JDWP::JT_CLASS_LOADER:
2674 case JDWP::JT_CLASS_OBJECT:
2675 case JDWP::JT_OBJECT:
2676 case JDWP::JT_STRING:
2677 case JDWP::JT_THREAD:
2678 case JDWP::JT_THREAD_GROUP: {
2679 CHECK_EQ(width, sizeof(JDWP::ObjectId));
2680 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002681 if (!visitor.GetVReg(m, vreg, kReferenceVReg, &intVal)) {
2682 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002683 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002684 mirror::Object* o = reinterpret_cast<mirror::Object*>(intVal);
2685 VLOG(jdwp) << "get " << tag << " object local " << vreg << " = " << o;
2686 if (!Runtime::Current()->GetHeap()->IsValidObjectAddress(o)) {
2687 LOG(FATAL) << StringPrintf("Found invalid object %#" PRIxPTR " in register v%u",
2688 reinterpret_cast<uintptr_t>(o), vreg)
2689 << GetStackContextAsString(visitor);
2690 UNREACHABLE();
2691 }
2692 tag = TagFromObject(soa, o);
2693 JDWP::SetObjectId(buf + 1, gRegistry->Add(o));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002694 break;
2695 }
2696 case JDWP::JT_DOUBLE: {
2697 CHECK_EQ(width, 8U);
2698 uint64_t longVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002699 if (!visitor.GetVRegPair(m, vreg, kDoubleLoVReg, kDoubleHiVReg, &longVal)) {
2700 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002701 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002702 VLOG(jdwp) << "get double local " << vreg << " = " << longVal;
2703 JDWP::Set8BE(buf + 1, longVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002704 break;
2705 }
2706 case JDWP::JT_LONG: {
2707 CHECK_EQ(width, 8U);
2708 uint64_t longVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002709 if (!visitor.GetVRegPair(m, vreg, kLongLoVReg, kLongHiVReg, &longVal)) {
2710 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002711 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002712 VLOG(jdwp) << "get long local " << vreg << " = " << longVal;
2713 JDWP::Set8BE(buf + 1, longVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002714 break;
2715 }
2716 default:
2717 LOG(FATAL) << "Unknown tag " << tag;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002718 UNREACHABLE();
Sebastien Hertz8009f392014-09-01 17:07:11 +02002719 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002720
Sebastien Hertz8009f392014-09-01 17:07:11 +02002721 // Prepend tag, which may have been updated.
2722 JDWP::Set1(buf, tag);
2723 return JDWP::ERR_NONE;
2724}
2725
2726JDWP::JdwpError Dbg::SetLocalValues(JDWP::Request* request) {
2727 JDWP::ObjectId thread_id = request->ReadThreadId();
2728 JDWP::FrameId frame_id = request->ReadFrameId();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002729
2730 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz69206392015-04-07 15:54:25 +02002731 JDWP::JdwpError error;
2732 Thread* thread = DecodeThread(soa, thread_id, &error);
2733 if (error != JDWP::ERR_NONE) {
2734 return error;
2735 }
2736 if (!IsSuspendedForDebugger(soa, thread)) {
2737 return JDWP::ERR_THREAD_NOT_SUSPENDED;
Elliott Hughes221229c2013-01-08 18:17:50 -08002738 }
Sebastien Hertz8009f392014-09-01 17:07:11 +02002739 // Find the frame with the given frame_id.
Ian Rogers700a4022014-05-19 16:49:03 -07002740 std::unique_ptr<Context> context(Context::Create());
Sebastien Hertz8009f392014-09-01 17:07:11 +02002741 FindFrameVisitor visitor(thread, context.get(), frame_id);
Ian Rogers0399dde2012-06-06 17:09:28 -07002742 visitor.WalkStack();
Sebastien Hertz8009f392014-09-01 17:07:11 +02002743 if (visitor.GetError() != JDWP::ERR_NONE) {
2744 return visitor.GetError();
2745 }
2746
2747 // Writes the values into visitor's context.
2748 int32_t slot_count = request->ReadSigned32("slot count");
2749 for (int32_t i = 0; i < slot_count; ++i) {
2750 uint32_t slot = request->ReadUnsigned32("slot");
2751 JDWP::JdwpTag sigByte = request->ReadTag();
2752 size_t width = Dbg::GetTagWidth(sigByte);
2753 uint64_t value = request->ReadValue(width);
2754
2755 VLOG(jdwp) << " --> slot " << slot << " " << sigByte << " " << value;
Mingyao Yang99170c62015-07-06 11:10:37 -07002756 error = Dbg::SetLocalValue(thread, visitor, slot, sigByte, value, width);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002757 if (error != JDWP::ERR_NONE) {
2758 return error;
2759 }
2760 }
2761 return JDWP::ERR_NONE;
2762}
2763
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002764template<typename T>
2765static JDWP::JdwpError FailSetLocalValue(const StackVisitor& visitor, uint16_t vreg,
2766 JDWP::JdwpTag tag, T value)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002767 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002768 LOG(ERROR) << "Failed to write " << tag << " local " << value
2769 << " (0x" << std::hex << value << ") into register v" << vreg
2770 << GetStackContextAsString(visitor);
2771 return kStackFrameLocalAccessError;
2772}
2773
Mingyao Yang99170c62015-07-06 11:10:37 -07002774JDWP::JdwpError Dbg::SetLocalValue(Thread* thread, StackVisitor& visitor, int slot,
2775 JDWP::JdwpTag tag, uint64_t value, size_t width) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002776 ArtMethod* m = visitor.GetMethod();
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002777 JDWP::JdwpError error = JDWP::ERR_NONE;
2778 uint16_t vreg = DemangleSlot(slot, m, &error);
2779 if (error != JDWP::ERR_NONE) {
2780 return error;
2781 }
Sebastien Hertz8009f392014-09-01 17:07:11 +02002782 // TODO: check that the tag is compatible with the actual type of the slot!
Sebastien Hertz8009f392014-09-01 17:07:11 +02002783 switch (tag) {
2784 case JDWP::JT_BOOLEAN:
2785 case JDWP::JT_BYTE:
2786 CHECK_EQ(width, 1U);
Mingyao Yang636b9252015-07-31 16:40:24 -07002787 if (!visitor.SetVReg(m, vreg, static_cast<uint32_t>(value), kIntVReg)) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002788 return FailSetLocalValue(visitor, vreg, tag, static_cast<uint32_t>(value));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002789 }
2790 break;
2791 case JDWP::JT_SHORT:
2792 case JDWP::JT_CHAR:
2793 CHECK_EQ(width, 2U);
Mingyao Yang636b9252015-07-31 16:40:24 -07002794 if (!visitor.SetVReg(m, vreg, static_cast<uint32_t>(value), kIntVReg)) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002795 return FailSetLocalValue(visitor, vreg, tag, static_cast<uint32_t>(value));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002796 }
2797 break;
2798 case JDWP::JT_INT:
2799 CHECK_EQ(width, 4U);
Mingyao Yang636b9252015-07-31 16:40:24 -07002800 if (!visitor.SetVReg(m, vreg, static_cast<uint32_t>(value), kIntVReg)) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002801 return FailSetLocalValue(visitor, vreg, tag, static_cast<uint32_t>(value));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002802 }
2803 break;
2804 case JDWP::JT_FLOAT:
2805 CHECK_EQ(width, 4U);
Mingyao Yang636b9252015-07-31 16:40:24 -07002806 if (!visitor.SetVReg(m, vreg, static_cast<uint32_t>(value), kFloatVReg)) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002807 return FailSetLocalValue(visitor, vreg, tag, static_cast<uint32_t>(value));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002808 }
2809 break;
2810 case JDWP::JT_ARRAY:
2811 case JDWP::JT_CLASS_LOADER:
2812 case JDWP::JT_CLASS_OBJECT:
2813 case JDWP::JT_OBJECT:
2814 case JDWP::JT_STRING:
2815 case JDWP::JT_THREAD:
2816 case JDWP::JT_THREAD_GROUP: {
2817 CHECK_EQ(width, sizeof(JDWP::ObjectId));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002818 mirror::Object* o = gRegistry->Get<mirror::Object*>(static_cast<JDWP::ObjectId>(value),
2819 &error);
2820 if (error != JDWP::ERR_NONE) {
2821 VLOG(jdwp) << tag << " object " << o << " is an invalid object";
2822 return JDWP::ERR_INVALID_OBJECT;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002823 }
Mingyao Yang636b9252015-07-31 16:40:24 -07002824 if (!visitor.SetVReg(m, vreg, static_cast<uint32_t>(reinterpret_cast<uintptr_t>(o)),
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002825 kReferenceVReg)) {
2826 return FailSetLocalValue(visitor, vreg, tag, reinterpret_cast<uintptr_t>(o));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002827 }
2828 break;
2829 }
2830 case JDWP::JT_DOUBLE: {
2831 CHECK_EQ(width, 8U);
Mingyao Yang636b9252015-07-31 16:40:24 -07002832 if (!visitor.SetVRegPair(m, vreg, value, kDoubleLoVReg, kDoubleHiVReg)) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002833 return FailSetLocalValue(visitor, vreg, tag, value);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002834 }
2835 break;
2836 }
2837 case JDWP::JT_LONG: {
2838 CHECK_EQ(width, 8U);
Mingyao Yang636b9252015-07-31 16:40:24 -07002839 if (!visitor.SetVRegPair(m, vreg, value, kLongLoVReg, kLongHiVReg)) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002840 return FailSetLocalValue(visitor, vreg, tag, value);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002841 }
2842 break;
2843 }
2844 default:
2845 LOG(FATAL) << "Unknown tag " << tag;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002846 UNREACHABLE();
Sebastien Hertz8009f392014-09-01 17:07:11 +02002847 }
Mingyao Yang99170c62015-07-06 11:10:37 -07002848
2849 // If we set the local variable in a compiled frame, we need to trigger a deoptimization of
2850 // the stack so we continue execution with the interpreter using the new value(s) of the updated
2851 // local variable(s). To achieve this, we install instrumentation exit stub on each method of the
2852 // thread's stack. The stub will cause the deoptimization to happen.
2853 if (!visitor.IsShadowFrame() && thread->HasDebuggerShadowFrames()) {
2854 Runtime::Current()->GetInstrumentation()->InstrumentThreadStack(thread);
2855 }
2856
Sebastien Hertz8009f392014-09-01 17:07:11 +02002857 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002858}
2859
Mathieu Chartiere401d142015-04-22 13:56:20 -07002860static void SetEventLocation(JDWP::EventLocation* location, ArtMethod* m, uint32_t dex_pc)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002861 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz6995c602014-09-09 12:10:13 +02002862 DCHECK(location != nullptr);
2863 if (m == nullptr) {
2864 memset(location, 0, sizeof(*location));
2865 } else {
Alex Light6c8467f2015-11-20 15:03:26 -08002866 location->method = GetCanonicalMethod(m);
Sebastien Hertz6995c602014-09-09 12:10:13 +02002867 location->dex_pc = (m->IsNative() || m->IsProxyMethod()) ? static_cast<uint32_t>(-1) : dex_pc;
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002868 }
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002869}
2870
Mathieu Chartiere401d142015-04-22 13:56:20 -07002871void Dbg::PostLocationEvent(ArtMethod* m, int dex_pc, mirror::Object* this_object,
Jeff Hao579b0242013-11-18 13:16:49 -08002872 int event_flags, const JValue* return_value) {
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002873 if (!IsDebuggerActive()) {
2874 return;
2875 }
2876 DCHECK(m != nullptr);
2877 DCHECK_EQ(m->IsStatic(), this_object == nullptr);
Sebastien Hertz6995c602014-09-09 12:10:13 +02002878 JDWP::EventLocation location;
2879 SetEventLocation(&location, m, dex_pc);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002880
Sebastien Hertzde48aa62015-05-26 11:53:39 +02002881 // We need to be sure no exception is pending when calling JdwpState::PostLocationEvent.
2882 // This is required to be able to call JNI functions to create JDWP ids. To achieve this,
2883 // we temporarily clear the current thread's exception (if any) and will restore it after
2884 // the call.
2885 // Note: the only way to get a pending exception here is to suspend on a move-exception
2886 // instruction.
2887 Thread* const self = Thread::Current();
2888 StackHandleScope<1> hs(self);
2889 Handle<mirror::Throwable> pending_exception(hs.NewHandle(self->GetException()));
2890 self->ClearException();
2891 if (kIsDebugBuild && pending_exception.Get() != nullptr) {
2892 const DexFile::CodeItem* code_item = location.method->GetCodeItem();
2893 const Instruction* instr = Instruction::At(&code_item->insns_[location.dex_pc]);
2894 CHECK_EQ(Instruction::MOVE_EXCEPTION, instr->Opcode());
2895 }
2896
Sebastien Hertz6995c602014-09-09 12:10:13 +02002897 gJdwpState->PostLocationEvent(&location, this_object, event_flags, return_value);
Sebastien Hertzde48aa62015-05-26 11:53:39 +02002898
2899 if (pending_exception.Get() != nullptr) {
2900 self->SetException(pending_exception.Get());
2901 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002902}
2903
Mathieu Chartiere401d142015-04-22 13:56:20 -07002904void Dbg::PostFieldAccessEvent(ArtMethod* m, int dex_pc,
Mathieu Chartierc7853442015-03-27 14:35:38 -07002905 mirror::Object* this_object, ArtField* f) {
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002906 if (!IsDebuggerActive()) {
2907 return;
2908 }
2909 DCHECK(m != nullptr);
2910 DCHECK(f != nullptr);
Sebastien Hertz6995c602014-09-09 12:10:13 +02002911 JDWP::EventLocation location;
2912 SetEventLocation(&location, m, dex_pc);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002913
Sebastien Hertz6995c602014-09-09 12:10:13 +02002914 gJdwpState->PostFieldEvent(&location, f, this_object, nullptr, false);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002915}
2916
Mathieu Chartiere401d142015-04-22 13:56:20 -07002917void Dbg::PostFieldModificationEvent(ArtMethod* m, int dex_pc,
Mathieu Chartierc7853442015-03-27 14:35:38 -07002918 mirror::Object* this_object, ArtField* f,
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002919 const JValue* field_value) {
2920 if (!IsDebuggerActive()) {
2921 return;
2922 }
2923 DCHECK(m != nullptr);
2924 DCHECK(f != nullptr);
2925 DCHECK(field_value != nullptr);
Sebastien Hertz6995c602014-09-09 12:10:13 +02002926 JDWP::EventLocation location;
2927 SetEventLocation(&location, m, dex_pc);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002928
Sebastien Hertz6995c602014-09-09 12:10:13 +02002929 gJdwpState->PostFieldEvent(&location, f, this_object, field_value, true);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002930}
2931
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002932/**
2933 * Finds the location where this exception will be caught. We search until we reach the top
2934 * frame, in which case this exception is considered uncaught.
2935 */
2936class CatchLocationFinder : public StackVisitor {
2937 public:
2938 CatchLocationFinder(Thread* self, const Handle<mirror::Throwable>& exception, Context* context)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002939 REQUIRES_SHARED(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01002940 : StackVisitor(self, context, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002941 exception_(exception),
2942 handle_scope_(self),
2943 this_at_throw_(handle_scope_.NewHandle<mirror::Object>(nullptr)),
Mathieu Chartiere401d142015-04-22 13:56:20 -07002944 catch_method_(nullptr),
2945 throw_method_(nullptr),
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002946 catch_dex_pc_(DexFile::kDexNoIndex),
2947 throw_dex_pc_(DexFile::kDexNoIndex) {
2948 }
2949
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002950 bool VisitFrame() OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002951 ArtMethod* method = GetMethod();
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002952 DCHECK(method != nullptr);
2953 if (method->IsRuntimeMethod()) {
2954 // Ignore callee save method.
2955 DCHECK(method->IsCalleeSaveMethod());
2956 return true;
2957 }
2958
2959 uint32_t dex_pc = GetDexPc();
Mathieu Chartiere401d142015-04-22 13:56:20 -07002960 if (throw_method_ == nullptr) {
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002961 // First Java method found. It is either the method that threw the exception,
2962 // or the Java native method that is reporting an exception thrown by
2963 // native code.
2964 this_at_throw_.Assign(GetThisObject());
Mathieu Chartiere401d142015-04-22 13:56:20 -07002965 throw_method_ = method;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002966 throw_dex_pc_ = dex_pc;
2967 }
2968
2969 if (dex_pc != DexFile::kDexNoIndex) {
Sebastien Hertz26f72862015-09-15 09:52:07 +02002970 StackHandleScope<1> hs(GetThread());
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002971 uint32_t found_dex_pc;
2972 Handle<mirror::Class> exception_class(hs.NewHandle(exception_->GetClass()));
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002973 bool unused_clear_exception;
Mathieu Chartiere401d142015-04-22 13:56:20 -07002974 found_dex_pc = method->FindCatchBlock(exception_class, dex_pc, &unused_clear_exception);
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002975 if (found_dex_pc != DexFile::kDexNoIndex) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002976 catch_method_ = method;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002977 catch_dex_pc_ = found_dex_pc;
2978 return false; // End stack walk.
2979 }
2980 }
2981 return true; // Continue stack walk.
2982 }
2983
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002984 ArtMethod* GetCatchMethod() REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002985 return catch_method_;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002986 }
2987
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002988 ArtMethod* GetThrowMethod() REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002989 return throw_method_;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002990 }
2991
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002992 mirror::Object* GetThisAtThrow() REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002993 return this_at_throw_.Get();
2994 }
2995
2996 uint32_t GetCatchDexPc() const {
2997 return catch_dex_pc_;
2998 }
2999
3000 uint32_t GetThrowDexPc() const {
3001 return throw_dex_pc_;
3002 }
3003
3004 private:
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003005 const Handle<mirror::Throwable>& exception_;
Mathieu Chartiere401d142015-04-22 13:56:20 -07003006 StackHandleScope<1> handle_scope_;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003007 MutableHandle<mirror::Object> this_at_throw_;
Mathieu Chartiere401d142015-04-22 13:56:20 -07003008 ArtMethod* catch_method_;
3009 ArtMethod* throw_method_;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003010 uint32_t catch_dex_pc_;
3011 uint32_t throw_dex_pc_;
3012
3013 DISALLOW_COPY_AND_ASSIGN(CatchLocationFinder);
3014};
3015
3016void Dbg::PostException(mirror::Throwable* exception_object) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07003017 if (!IsDebuggerActive()) {
Ian Rogers0ad5bb82011-12-07 10:16:32 -08003018 return;
3019 }
Sebastien Hertz261bc042015-04-08 09:36:07 +02003020 Thread* const self = Thread::Current();
3021 StackHandleScope<1> handle_scope(self);
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003022 Handle<mirror::Throwable> h_exception(handle_scope.NewHandle(exception_object));
3023 std::unique_ptr<Context> context(Context::Create());
Sebastien Hertz261bc042015-04-08 09:36:07 +02003024 CatchLocationFinder clf(self, h_exception, context.get());
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003025 clf.WalkStack(/* include_transitions */ false);
Sebastien Hertz6995c602014-09-09 12:10:13 +02003026 JDWP::EventLocation exception_throw_location;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003027 SetEventLocation(&exception_throw_location, clf.GetThrowMethod(), clf.GetThrowDexPc());
Sebastien Hertz6995c602014-09-09 12:10:13 +02003028 JDWP::EventLocation exception_catch_location;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003029 SetEventLocation(&exception_catch_location, clf.GetCatchMethod(), clf.GetCatchDexPc());
Elliott Hughes4740cdf2011-12-07 14:07:12 -08003030
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003031 gJdwpState->PostException(&exception_throw_location, h_exception.Get(), &exception_catch_location,
3032 clf.GetThisAtThrow());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003033}
3034
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003035void Dbg::PostClassPrepare(mirror::Class* c) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07003036 if (!IsDebuggerActive()) {
Elliott Hughes4740cdf2011-12-07 14:07:12 -08003037 return;
3038 }
Sebastien Hertz6995c602014-09-09 12:10:13 +02003039 gJdwpState->PostClassPrepare(c);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003040}
3041
Ian Rogers62d6c772013-02-27 08:32:07 -08003042void Dbg::UpdateDebugger(Thread* thread, mirror::Object* this_object,
Mathieu Chartiere401d142015-04-22 13:56:20 -07003043 ArtMethod* m, uint32_t dex_pc,
Sebastien Hertz8379b222014-02-24 17:38:15 +01003044 int event_flags, const JValue* return_value) {
Ian Rogers62d6c772013-02-27 08:32:07 -08003045 if (!IsDebuggerActive() || dex_pc == static_cast<uint32_t>(-2) /* fake method exit */) {
Elliott Hughes2aa2e392012-02-17 17:15:43 -08003046 return;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003047 }
3048
Elliott Hughes86964332012-02-15 19:37:42 -08003049 if (IsBreakpoint(m, dex_pc)) {
3050 event_flags |= kBreakpoint;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003051 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003052
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003053 // If the debugger is single-stepping one of our threads, check to
3054 // see if we're that thread and we've reached a step point.
3055 const SingleStepControl* single_step_control = thread->GetSingleStepControl();
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003056 if (single_step_control != nullptr) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003057 CHECK(!m->IsNative());
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003058 if (single_step_control->GetStepDepth() == JDWP::SD_INTO) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003059 // Step into method calls. We break when the line number
3060 // or method pointer changes. If we're in SS_MIN mode, we
3061 // always stop.
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003062 if (single_step_control->GetMethod() != m) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003063 event_flags |= kSingleStep;
3064 VLOG(jdwp) << "SS new method";
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003065 } else if (single_step_control->GetStepSize() == JDWP::SS_MIN) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003066 event_flags |= kSingleStep;
3067 VLOG(jdwp) << "SS new instruction";
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003068 } else if (single_step_control->ContainsDexPc(dex_pc)) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003069 event_flags |= kSingleStep;
3070 VLOG(jdwp) << "SS new line";
3071 }
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003072 } else if (single_step_control->GetStepDepth() == JDWP::SD_OVER) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003073 // Step over method calls. We break when the line number is
3074 // different and the frame depth is <= the original frame
3075 // depth. (We can't just compare on the method, because we
3076 // might get unrolled past it by an exception, and it's tricky
3077 // to identify recursion.)
3078
3079 int stack_depth = GetStackDepth(thread);
3080
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003081 if (stack_depth < single_step_control->GetStackDepth()) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003082 // Popped up one or more frames, always trigger.
3083 event_flags |= kSingleStep;
3084 VLOG(jdwp) << "SS method pop";
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003085 } else if (stack_depth == single_step_control->GetStackDepth()) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003086 // Same depth, see if we moved.
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003087 if (single_step_control->GetStepSize() == JDWP::SS_MIN) {
Elliott Hughes86964332012-02-15 19:37:42 -08003088 event_flags |= kSingleStep;
3089 VLOG(jdwp) << "SS new instruction";
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003090 } else if (single_step_control->ContainsDexPc(dex_pc)) {
Elliott Hughes2435a572012-02-17 16:07:41 -08003091 event_flags |= kSingleStep;
3092 VLOG(jdwp) << "SS new line";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003093 }
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003094 }
3095 } else {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003096 CHECK_EQ(single_step_control->GetStepDepth(), JDWP::SD_OUT);
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003097 // Return from the current method. We break when the frame
3098 // depth pops up.
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003099
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003100 // This differs from the "method exit" break in that it stops
3101 // with the PC at the next instruction in the returned-to
3102 // function, rather than the end of the returning function.
Elliott Hughes86964332012-02-15 19:37:42 -08003103
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003104 int stack_depth = GetStackDepth(thread);
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003105 if (stack_depth < single_step_control->GetStackDepth()) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003106 event_flags |= kSingleStep;
3107 VLOG(jdwp) << "SS method pop";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003108 }
3109 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003110 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003111
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003112 // If there's something interesting going on, see if it matches one
3113 // of the debugger filters.
3114 if (event_flags != 0) {
Sebastien Hertz8379b222014-02-24 17:38:15 +01003115 Dbg::PostLocationEvent(m, dex_pc, this_object, event_flags, return_value);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003116 }
3117}
3118
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003119size_t* Dbg::GetReferenceCounterForEvent(uint32_t instrumentation_event) {
3120 switch (instrumentation_event) {
3121 case instrumentation::Instrumentation::kMethodEntered:
3122 return &method_enter_event_ref_count_;
3123 case instrumentation::Instrumentation::kMethodExited:
3124 return &method_exit_event_ref_count_;
3125 case instrumentation::Instrumentation::kDexPcMoved:
3126 return &dex_pc_change_event_ref_count_;
3127 case instrumentation::Instrumentation::kFieldRead:
3128 return &field_read_event_ref_count_;
3129 case instrumentation::Instrumentation::kFieldWritten:
3130 return &field_write_event_ref_count_;
3131 case instrumentation::Instrumentation::kExceptionCaught:
3132 return &exception_catch_event_ref_count_;
3133 default:
3134 return nullptr;
3135 }
3136}
3137
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003138// Process request while all mutator threads are suspended.
3139void Dbg::ProcessDeoptimizationRequest(const DeoptimizationRequest& request) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003140 instrumentation::Instrumentation* instrumentation = Runtime::Current()->GetInstrumentation();
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003141 switch (request.GetKind()) {
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003142 case DeoptimizationRequest::kNothing:
3143 LOG(WARNING) << "Ignoring empty deoptimization request.";
3144 break;
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003145 case DeoptimizationRequest::kRegisterForEvent:
3146 VLOG(jdwp) << StringPrintf("Add debugger as listener for instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003147 request.InstrumentationEvent());
3148 instrumentation->AddListener(&gDebugInstrumentationListener, request.InstrumentationEvent());
3149 instrumentation_events_ |= request.InstrumentationEvent();
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003150 break;
3151 case DeoptimizationRequest::kUnregisterForEvent:
3152 VLOG(jdwp) << StringPrintf("Remove debugger as listener for instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003153 request.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003154 instrumentation->RemoveListener(&gDebugInstrumentationListener,
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003155 request.InstrumentationEvent());
3156 instrumentation_events_ &= ~request.InstrumentationEvent();
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003157 break;
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003158 case DeoptimizationRequest::kFullDeoptimization:
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003159 VLOG(jdwp) << "Deoptimize the world ...";
Sebastien Hertz0462c4c2015-04-01 16:34:17 +02003160 instrumentation->DeoptimizeEverything(kDbgInstrumentationKey);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003161 VLOG(jdwp) << "Deoptimize the world DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003162 break;
3163 case DeoptimizationRequest::kFullUndeoptimization:
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003164 VLOG(jdwp) << "Undeoptimize the world ...";
Sebastien Hertz0462c4c2015-04-01 16:34:17 +02003165 instrumentation->UndeoptimizeEverything(kDbgInstrumentationKey);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003166 VLOG(jdwp) << "Undeoptimize the world DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003167 break;
3168 case DeoptimizationRequest::kSelectiveDeoptimization:
David Sehr709b0702016-10-13 09:12:37 -07003169 VLOG(jdwp) << "Deoptimize method " << ArtMethod::PrettyMethod(request.Method()) << " ...";
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003170 instrumentation->Deoptimize(request.Method());
David Sehr709b0702016-10-13 09:12:37 -07003171 VLOG(jdwp) << "Deoptimize method " << ArtMethod::PrettyMethod(request.Method()) << " DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003172 break;
3173 case DeoptimizationRequest::kSelectiveUndeoptimization:
David Sehr709b0702016-10-13 09:12:37 -07003174 VLOG(jdwp) << "Undeoptimize method " << ArtMethod::PrettyMethod(request.Method()) << " ...";
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003175 instrumentation->Undeoptimize(request.Method());
David Sehr709b0702016-10-13 09:12:37 -07003176 VLOG(jdwp) << "Undeoptimize method " << ArtMethod::PrettyMethod(request.Method()) << " DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003177 break;
3178 default:
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003179 LOG(FATAL) << "Unsupported deoptimization request kind " << request.GetKind();
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003180 break;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003181 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003182}
3183
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003184void Dbg::RequestDeoptimization(const DeoptimizationRequest& req) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003185 if (req.GetKind() == DeoptimizationRequest::kNothing) {
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003186 // Nothing to do.
3187 return;
3188 }
Brian Carlstrom306db812014-09-05 13:01:41 -07003189 MutexLock mu(Thread::Current(), *Locks::deoptimization_lock_);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003190 RequestDeoptimizationLocked(req);
3191}
3192
3193void Dbg::RequestDeoptimizationLocked(const DeoptimizationRequest& req) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003194 switch (req.GetKind()) {
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003195 case DeoptimizationRequest::kRegisterForEvent: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003196 DCHECK_NE(req.InstrumentationEvent(), 0u);
3197 size_t* counter = GetReferenceCounterForEvent(req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003198 CHECK(counter != nullptr) << StringPrintf("No counter for instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003199 req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003200 if (*counter == 0) {
Sebastien Hertz7d2ae432014-05-15 11:26:34 +02003201 VLOG(jdwp) << StringPrintf("Queue request #%zd to start listening to instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003202 deoptimization_requests_.size(), req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003203 deoptimization_requests_.push_back(req);
3204 }
3205 *counter = *counter + 1;
3206 break;
3207 }
3208 case DeoptimizationRequest::kUnregisterForEvent: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003209 DCHECK_NE(req.InstrumentationEvent(), 0u);
3210 size_t* counter = GetReferenceCounterForEvent(req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003211 CHECK(counter != nullptr) << StringPrintf("No counter for instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003212 req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003213 *counter = *counter - 1;
3214 if (*counter == 0) {
Sebastien Hertz7d2ae432014-05-15 11:26:34 +02003215 VLOG(jdwp) << StringPrintf("Queue request #%zd to stop listening to instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003216 deoptimization_requests_.size(), req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003217 deoptimization_requests_.push_back(req);
3218 }
3219 break;
3220 }
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003221 case DeoptimizationRequest::kFullDeoptimization: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003222 DCHECK(req.Method() == nullptr);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003223 if (full_deoptimization_event_count_ == 0) {
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003224 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
3225 << " for full deoptimization";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003226 deoptimization_requests_.push_back(req);
3227 }
3228 ++full_deoptimization_event_count_;
3229 break;
3230 }
3231 case DeoptimizationRequest::kFullUndeoptimization: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003232 DCHECK(req.Method() == nullptr);
Sebastien Hertze713d932014-05-15 10:48:53 +02003233 DCHECK_GT(full_deoptimization_event_count_, 0U);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003234 --full_deoptimization_event_count_;
3235 if (full_deoptimization_event_count_ == 0) {
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003236 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
3237 << " for full undeoptimization";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003238 deoptimization_requests_.push_back(req);
3239 }
3240 break;
3241 }
3242 case DeoptimizationRequest::kSelectiveDeoptimization: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003243 DCHECK(req.Method() != nullptr);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003244 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
David Sehr709b0702016-10-13 09:12:37 -07003245 << " for deoptimization of " << req.Method()->PrettyMethod();
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003246 deoptimization_requests_.push_back(req);
3247 break;
3248 }
3249 case DeoptimizationRequest::kSelectiveUndeoptimization: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003250 DCHECK(req.Method() != nullptr);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003251 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
David Sehr709b0702016-10-13 09:12:37 -07003252 << " for undeoptimization of " << req.Method()->PrettyMethod();
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003253 deoptimization_requests_.push_back(req);
3254 break;
3255 }
3256 default: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003257 LOG(FATAL) << "Unknown deoptimization request kind " << req.GetKind();
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003258 break;
3259 }
3260 }
3261}
3262
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003263void Dbg::ManageDeoptimization() {
3264 Thread* const self = Thread::Current();
3265 {
3266 // Avoid suspend/resume if there is no pending request.
Brian Carlstrom306db812014-09-05 13:01:41 -07003267 MutexLock mu(self, *Locks::deoptimization_lock_);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003268 if (deoptimization_requests_.empty()) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003269 return;
3270 }
3271 }
3272 CHECK_EQ(self->GetState(), kRunnable);
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07003273 ScopedThreadSuspension sts(self, kWaitingForDeoptimization);
Mathieu Chartieraa516822015-10-02 15:53:37 -07003274 // Required for ProcessDeoptimizationRequest.
3275 gc::ScopedGCCriticalSection gcs(self,
3276 gc::kGcCauseInstrumentation,
3277 gc::kCollectorTypeInstrumentation);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003278 // We need to suspend mutator threads first.
Mathieu Chartier4f55e222015-09-04 13:26:21 -07003279 ScopedSuspendAll ssa(__FUNCTION__);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003280 const ThreadState old_state = self->SetStateUnsafe(kRunnable);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003281 {
Brian Carlstrom306db812014-09-05 13:01:41 -07003282 MutexLock mu(self, *Locks::deoptimization_lock_);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003283 size_t req_index = 0;
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003284 for (DeoptimizationRequest& request : deoptimization_requests_) {
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003285 VLOG(jdwp) << "Process deoptimization request #" << req_index++;
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003286 ProcessDeoptimizationRequest(request);
3287 }
3288 deoptimization_requests_.clear();
3289 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003290 CHECK_EQ(self->SetStateUnsafe(old_state), kRunnable);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003291}
3292
Mathieu Chartiere401d142015-04-22 13:56:20 -07003293static const Breakpoint* FindFirstBreakpointForMethod(ArtMethod* m)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003294 REQUIRES_SHARED(Locks::mutator_lock_, Locks::breakpoint_lock_) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003295 for (Breakpoint& breakpoint : gBreakpoints) {
Alex Light6c8467f2015-11-20 15:03:26 -08003296 if (breakpoint.IsInMethod(m)) {
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003297 return &breakpoint;
3298 }
3299 }
3300 return nullptr;
3301}
3302
Mathieu Chartiere401d142015-04-22 13:56:20 -07003303bool Dbg::MethodHasAnyBreakpoints(ArtMethod* method) {
Mathieu Chartierd8565452015-03-26 09:41:50 -07003304 ReaderMutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
3305 return FindFirstBreakpointForMethod(method) != nullptr;
3306}
3307
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003308// Sanity checks all existing breakpoints on the same method.
Mathieu Chartiere401d142015-04-22 13:56:20 -07003309static void SanityCheckExistingBreakpoints(ArtMethod* m,
Sebastien Hertzf3928792014-11-17 19:00:37 +01003310 DeoptimizationRequest::Kind deoptimization_kind)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003311 REQUIRES_SHARED(Locks::mutator_lock_, Locks::breakpoint_lock_) {
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003312 for (const Breakpoint& breakpoint : gBreakpoints) {
Alex Light6c8467f2015-11-20 15:03:26 -08003313 if (breakpoint.IsInMethod(m)) {
Sebastien Hertzf3928792014-11-17 19:00:37 +01003314 CHECK_EQ(deoptimization_kind, breakpoint.GetDeoptimizationKind());
3315 }
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003316 }
Sebastien Hertzf3928792014-11-17 19:00:37 +01003317 instrumentation::Instrumentation* instrumentation = Runtime::Current()->GetInstrumentation();
3318 if (deoptimization_kind == DeoptimizationRequest::kFullDeoptimization) {
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003319 // We should have deoptimized everything but not "selectively" deoptimized this method.
Sebastien Hertzf3928792014-11-17 19:00:37 +01003320 CHECK(instrumentation->AreAllMethodsDeoptimized());
3321 CHECK(!instrumentation->IsDeoptimized(m));
3322 } else if (deoptimization_kind == DeoptimizationRequest::kSelectiveDeoptimization) {
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003323 // We should have "selectively" deoptimized this method.
3324 // Note: while we have not deoptimized everything for this method, we may have done it for
3325 // another event.
Sebastien Hertzf3928792014-11-17 19:00:37 +01003326 CHECK(instrumentation->IsDeoptimized(m));
3327 } else {
3328 // This method does not require deoptimization.
3329 CHECK_EQ(deoptimization_kind, DeoptimizationRequest::kNothing);
3330 CHECK(!instrumentation->IsDeoptimized(m));
3331 }
3332}
3333
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003334// Returns the deoptimization kind required to set a breakpoint in a method.
3335// If a breakpoint has already been set, we also return the first breakpoint
3336// through the given 'existing_brkpt' pointer.
Sebastien Hertzf3928792014-11-17 19:00:37 +01003337static DeoptimizationRequest::Kind GetRequiredDeoptimizationKind(Thread* self,
Mathieu Chartiere401d142015-04-22 13:56:20 -07003338 ArtMethod* m,
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003339 const Breakpoint** existing_brkpt)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003340 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertzf3928792014-11-17 19:00:37 +01003341 if (!Dbg::RequiresDeoptimization()) {
3342 // We already run in interpreter-only mode so we don't need to deoptimize anything.
3343 VLOG(jdwp) << "No need for deoptimization when fully running with interpreter for method "
David Sehr709b0702016-10-13 09:12:37 -07003344 << ArtMethod::PrettyMethod(m);
Sebastien Hertzf3928792014-11-17 19:00:37 +01003345 return DeoptimizationRequest::kNothing;
3346 }
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003347 const Breakpoint* first_breakpoint;
Sebastien Hertzf3928792014-11-17 19:00:37 +01003348 {
3349 ReaderMutexLock mu(self, *Locks::breakpoint_lock_);
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003350 first_breakpoint = FindFirstBreakpointForMethod(m);
3351 *existing_brkpt = first_breakpoint;
Sebastien Hertzf3928792014-11-17 19:00:37 +01003352 }
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003353
3354 if (first_breakpoint == nullptr) {
Nicolas Geoffray6300fd72016-03-18 09:40:17 +00003355 // There is no breakpoint on this method yet: we need to deoptimize. If this method is default,
3356 // we deoptimize everything; otherwise we deoptimize only this method. We
Alex Light6c8467f2015-11-20 15:03:26 -08003357 // deoptimize with defaults because we do not know everywhere they are used. It is possible some
Nicolas Geoffray6300fd72016-03-18 09:40:17 +00003358 // of the copies could be missed.
Alex Light6c8467f2015-11-20 15:03:26 -08003359 // TODO Deoptimizing on default methods might not be necessary in all cases.
Nicolas Geoffray6300fd72016-03-18 09:40:17 +00003360 bool need_full_deoptimization = m->IsDefault();
Sebastien Hertzf3928792014-11-17 19:00:37 +01003361 if (need_full_deoptimization) {
Nicolas Geoffray6300fd72016-03-18 09:40:17 +00003362 VLOG(jdwp) << "Need full deoptimization because of copying of method "
David Sehr709b0702016-10-13 09:12:37 -07003363 << ArtMethod::PrettyMethod(m);
Sebastien Hertzf3928792014-11-17 19:00:37 +01003364 return DeoptimizationRequest::kFullDeoptimization;
3365 } else {
3366 // We don't need to deoptimize if the method has not been compiled.
Nicolas Geoffraya5891e82015-11-06 14:18:27 +00003367 const bool is_compiled = m->HasAnyCompiledCode();
Sebastien Hertzf3928792014-11-17 19:00:37 +01003368 if (is_compiled) {
David Sehr709b0702016-10-13 09:12:37 -07003369 VLOG(jdwp) << "Need selective deoptimization for compiled method "
3370 << ArtMethod::PrettyMethod(m);
Nicolas Geoffray6300fd72016-03-18 09:40:17 +00003371 return DeoptimizationRequest::kSelectiveDeoptimization;
Sebastien Hertzf3928792014-11-17 19:00:37 +01003372 } else {
3373 // Method is not compiled: we don't need to deoptimize.
David Sehr709b0702016-10-13 09:12:37 -07003374 VLOG(jdwp) << "No need for deoptimization for non-compiled method "
3375 << ArtMethod::PrettyMethod(m);
Sebastien Hertzf3928792014-11-17 19:00:37 +01003376 return DeoptimizationRequest::kNothing;
3377 }
3378 }
3379 } else {
3380 // There is at least one breakpoint for this method: we don't need to deoptimize.
3381 // Let's check that all breakpoints are configured the same way for deoptimization.
3382 VLOG(jdwp) << "Breakpoint already set: no deoptimization is required";
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003383 DeoptimizationRequest::Kind deoptimization_kind = first_breakpoint->GetDeoptimizationKind();
Sebastien Hertzf3928792014-11-17 19:00:37 +01003384 if (kIsDebugBuild) {
3385 ReaderMutexLock mu(self, *Locks::breakpoint_lock_);
3386 SanityCheckExistingBreakpoints(m, deoptimization_kind);
3387 }
3388 return DeoptimizationRequest::kNothing;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003389 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003390}
3391
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003392// Installs a breakpoint at the specified location. Also indicates through the deoptimization
3393// request if we need to deoptimize.
3394void Dbg::WatchLocation(const JDWP::JdwpLocation* location, DeoptimizationRequest* req) {
3395 Thread* const self = Thread::Current();
Mathieu Chartiere401d142015-04-22 13:56:20 -07003396 ArtMethod* m = FromMethodId(location->method_id);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003397 DCHECK(m != nullptr) << "No method for method id " << location->method_id;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003398
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003399 const Breakpoint* existing_breakpoint = nullptr;
3400 const DeoptimizationRequest::Kind deoptimization_kind =
3401 GetRequiredDeoptimizationKind(self, m, &existing_breakpoint);
Sebastien Hertzf3928792014-11-17 19:00:37 +01003402 req->SetKind(deoptimization_kind);
3403 if (deoptimization_kind == DeoptimizationRequest::kSelectiveDeoptimization) {
3404 req->SetMethod(m);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003405 } else {
Sebastien Hertzf3928792014-11-17 19:00:37 +01003406 CHECK(deoptimization_kind == DeoptimizationRequest::kNothing ||
3407 deoptimization_kind == DeoptimizationRequest::kFullDeoptimization);
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003408 req->SetMethod(nullptr);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003409 }
3410
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003411 {
3412 WriterMutexLock mu(self, *Locks::breakpoint_lock_);
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003413 // If there is at least one existing breakpoint on the same method, the new breakpoint
3414 // must have the same deoptimization kind than the existing breakpoint(s).
3415 DeoptimizationRequest::Kind breakpoint_deoptimization_kind;
3416 if (existing_breakpoint != nullptr) {
3417 breakpoint_deoptimization_kind = existing_breakpoint->GetDeoptimizationKind();
3418 } else {
3419 breakpoint_deoptimization_kind = deoptimization_kind;
3420 }
3421 gBreakpoints.push_back(Breakpoint(m, location->dex_pc, breakpoint_deoptimization_kind));
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003422 VLOG(jdwp) << "Set breakpoint #" << (gBreakpoints.size() - 1) << ": "
3423 << gBreakpoints[gBreakpoints.size() - 1];
3424 }
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003425}
3426
3427// Uninstalls a breakpoint at the specified location. Also indicates through the deoptimization
3428// request if we need to undeoptimize.
3429void Dbg::UnwatchLocation(const JDWP::JdwpLocation* location, DeoptimizationRequest* req) {
Sebastien Hertzed2be172014-08-19 15:33:43 +02003430 WriterMutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003431 ArtMethod* m = FromMethodId(location->method_id);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003432 DCHECK(m != nullptr) << "No method for method id " << location->method_id;
Sebastien Hertzf3928792014-11-17 19:00:37 +01003433 DeoptimizationRequest::Kind deoptimization_kind = DeoptimizationRequest::kNothing;
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003434 for (size_t i = 0, e = gBreakpoints.size(); i < e; ++i) {
Alex Light6c8467f2015-11-20 15:03:26 -08003435 if (gBreakpoints[i].DexPc() == location->dex_pc && gBreakpoints[i].IsInMethod(m)) {
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003436 VLOG(jdwp) << "Removed breakpoint #" << i << ": " << gBreakpoints[i];
Sebastien Hertzf3928792014-11-17 19:00:37 +01003437 deoptimization_kind = gBreakpoints[i].GetDeoptimizationKind();
3438 DCHECK_EQ(deoptimization_kind == DeoptimizationRequest::kSelectiveDeoptimization,
3439 Runtime::Current()->GetInstrumentation()->IsDeoptimized(m));
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003440 gBreakpoints.erase(gBreakpoints.begin() + i);
3441 break;
3442 }
3443 }
3444 const Breakpoint* const existing_breakpoint = FindFirstBreakpointForMethod(m);
3445 if (existing_breakpoint == nullptr) {
3446 // There is no more breakpoint on this method: we need to undeoptimize.
Sebastien Hertzf3928792014-11-17 19:00:37 +01003447 if (deoptimization_kind == DeoptimizationRequest::kFullDeoptimization) {
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003448 // This method required full deoptimization: we need to undeoptimize everything.
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003449 req->SetKind(DeoptimizationRequest::kFullUndeoptimization);
3450 req->SetMethod(nullptr);
Sebastien Hertzf3928792014-11-17 19:00:37 +01003451 } else if (deoptimization_kind == DeoptimizationRequest::kSelectiveDeoptimization) {
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003452 // This method required selective deoptimization: we need to undeoptimize only that method.
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003453 req->SetKind(DeoptimizationRequest::kSelectiveUndeoptimization);
3454 req->SetMethod(m);
Sebastien Hertzf3928792014-11-17 19:00:37 +01003455 } else {
3456 // This method had no need for deoptimization: do nothing.
3457 CHECK_EQ(deoptimization_kind, DeoptimizationRequest::kNothing);
3458 req->SetKind(DeoptimizationRequest::kNothing);
3459 req->SetMethod(nullptr);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003460 }
3461 } else {
3462 // There is at least one breakpoint for this method: we don't need to undeoptimize.
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003463 req->SetKind(DeoptimizationRequest::kNothing);
3464 req->SetMethod(nullptr);
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003465 if (kIsDebugBuild) {
Sebastien Hertzf3928792014-11-17 19:00:37 +01003466 SanityCheckExistingBreakpoints(m, deoptimization_kind);
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003467 }
Elliott Hughes86964332012-02-15 19:37:42 -08003468 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003469}
3470
Mathieu Chartiere401d142015-04-22 13:56:20 -07003471bool Dbg::IsForcedInterpreterNeededForCallingImpl(Thread* thread, ArtMethod* m) {
Daniel Mihalyieb076692014-08-22 17:33:31 +02003472 const SingleStepControl* const ssc = thread->GetSingleStepControl();
3473 if (ssc == nullptr) {
3474 // If we are not single-stepping, then we don't have to force interpreter.
3475 return false;
3476 }
3477 if (Runtime::Current()->GetInstrumentation()->InterpretOnly()) {
3478 // If we are in interpreter only mode, then we don't have to force interpreter.
3479 return false;
3480 }
3481
3482 if (!m->IsNative() && !m->IsProxyMethod()) {
3483 // If we want to step into a method, then we have to force interpreter on that call.
3484 if (ssc->GetStepDepth() == JDWP::SD_INTO) {
3485 return true;
3486 }
3487 }
3488 return false;
3489}
3490
Mathieu Chartiere401d142015-04-22 13:56:20 -07003491bool Dbg::IsForcedInterpreterNeededForResolutionImpl(Thread* thread, ArtMethod* m) {
Daniel Mihalyieb076692014-08-22 17:33:31 +02003492 instrumentation::Instrumentation* const instrumentation =
3493 Runtime::Current()->GetInstrumentation();
3494 // If we are in interpreter only mode, then we don't have to force interpreter.
3495 if (instrumentation->InterpretOnly()) {
3496 return false;
3497 }
3498 // We can only interpret pure Java method.
3499 if (m->IsNative() || m->IsProxyMethod()) {
3500 return false;
3501 }
3502 const SingleStepControl* const ssc = thread->GetSingleStepControl();
3503 if (ssc != nullptr) {
3504 // If we want to step into a method, then we have to force interpreter on that call.
3505 if (ssc->GetStepDepth() == JDWP::SD_INTO) {
3506 return true;
3507 }
3508 // If we are stepping out from a static initializer, by issuing a step
3509 // in or step over, that was implicitly invoked by calling a static method,
3510 // then we need to step into that method. Having a lower stack depth than
3511 // the one the single step control has indicates that the step originates
3512 // from the static initializer.
3513 if (ssc->GetStepDepth() != JDWP::SD_OUT &&
3514 ssc->GetStackDepth() > GetStackDepth(thread)) {
3515 return true;
3516 }
3517 }
3518 // There are cases where we have to force interpreter on deoptimized methods,
3519 // because in some cases the call will not be performed by invoking an entry
3520 // point that has been replaced by the deoptimization, but instead by directly
3521 // invoking the compiled code of the method, for example.
3522 return instrumentation->IsDeoptimized(m);
3523}
3524
Mathieu Chartiere401d142015-04-22 13:56:20 -07003525bool Dbg::IsForcedInstrumentationNeededForResolutionImpl(Thread* thread, ArtMethod* m) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07003526 // The upcall can be null and in that case we don't need to do anything.
Daniel Mihalyieb076692014-08-22 17:33:31 +02003527 if (m == nullptr) {
3528 return false;
3529 }
3530 instrumentation::Instrumentation* const instrumentation =
3531 Runtime::Current()->GetInstrumentation();
3532 // If we are in interpreter only mode, then we don't have to force interpreter.
3533 if (instrumentation->InterpretOnly()) {
3534 return false;
3535 }
3536 // We can only interpret pure Java method.
3537 if (m->IsNative() || m->IsProxyMethod()) {
3538 return false;
3539 }
3540 const SingleStepControl* const ssc = thread->GetSingleStepControl();
3541 if (ssc != nullptr) {
3542 // If we are stepping out from a static initializer, by issuing a step
3543 // out, that was implicitly invoked by calling a static method, then we
3544 // need to step into the caller of that method. Having a lower stack
3545 // depth than the one the single step control has indicates that the
3546 // step originates from the static initializer.
3547 if (ssc->GetStepDepth() == JDWP::SD_OUT &&
3548 ssc->GetStackDepth() > GetStackDepth(thread)) {
3549 return true;
3550 }
3551 }
3552 // If we are returning from a static intializer, that was implicitly
3553 // invoked by calling a static method and the caller is deoptimized,
3554 // then we have to deoptimize the stack without forcing interpreter
3555 // on the static method that was called originally. This problem can
3556 // be solved easily by forcing instrumentation on the called method,
3557 // because the instrumentation exit hook will recognise the need of
3558 // stack deoptimization by calling IsForcedInterpreterNeededForUpcall.
3559 return instrumentation->IsDeoptimized(m);
3560}
3561
Mathieu Chartiere401d142015-04-22 13:56:20 -07003562bool Dbg::IsForcedInterpreterNeededForUpcallImpl(Thread* thread, ArtMethod* m) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07003563 // The upcall can be null and in that case we don't need to do anything.
Daniel Mihalyieb076692014-08-22 17:33:31 +02003564 if (m == nullptr) {
3565 return false;
3566 }
3567 instrumentation::Instrumentation* const instrumentation =
3568 Runtime::Current()->GetInstrumentation();
3569 // If we are in interpreter only mode, then we don't have to force interpreter.
3570 if (instrumentation->InterpretOnly()) {
3571 return false;
3572 }
3573 // We can only interpret pure Java method.
3574 if (m->IsNative() || m->IsProxyMethod()) {
3575 return false;
3576 }
3577 const SingleStepControl* const ssc = thread->GetSingleStepControl();
3578 if (ssc != nullptr) {
3579 // The debugger is not interested in what is happening under the level
3580 // of the step, thus we only force interpreter when we are not below of
3581 // the step.
3582 if (ssc->GetStackDepth() >= GetStackDepth(thread)) {
3583 return true;
3584 }
3585 }
Mingyao Yang99170c62015-07-06 11:10:37 -07003586 if (thread->HasDebuggerShadowFrames()) {
3587 // We need to deoptimize the stack for the exception handling flow so that
3588 // we don't miss any deoptimization that should be done when there are
3589 // debugger shadow frames.
3590 return true;
3591 }
Daniel Mihalyieb076692014-08-22 17:33:31 +02003592 // We have to require stack deoptimization if the upcall is deoptimized.
3593 return instrumentation->IsDeoptimized(m);
3594}
3595
Mingyao Yang99170c62015-07-06 11:10:37 -07003596class NeedsDeoptimizationVisitor : public StackVisitor {
Sebastien Hertz520633b2015-09-08 17:03:36 +02003597 public:
3598 explicit NeedsDeoptimizationVisitor(Thread* self)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003599 REQUIRES_SHARED(Locks::mutator_lock_)
Sebastien Hertz520633b2015-09-08 17:03:36 +02003600 : StackVisitor(self, nullptr, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
3601 needs_deoptimization_(false) {}
3602
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003603 bool VisitFrame() OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz520633b2015-09-08 17:03:36 +02003604 // The visitor is meant to be used when handling exception from compiled code only.
David Sehr709b0702016-10-13 09:12:37 -07003605 CHECK(!IsShadowFrame()) << "We only expect to visit compiled frame: "
3606 << ArtMethod::PrettyMethod(GetMethod());
Sebastien Hertz520633b2015-09-08 17:03:36 +02003607 ArtMethod* method = GetMethod();
3608 if (method == nullptr) {
3609 // We reach an upcall and don't need to deoptimize this part of the stack (ManagedFragment)
3610 // so we can stop the visit.
3611 DCHECK(!needs_deoptimization_);
3612 return false;
3613 }
3614 if (Runtime::Current()->GetInstrumentation()->InterpretOnly()) {
3615 // We found a compiled frame in the stack but instrumentation is set to interpret
3616 // everything: we need to deoptimize.
3617 needs_deoptimization_ = true;
3618 return false;
3619 }
3620 if (Runtime::Current()->GetInstrumentation()->IsDeoptimized(method)) {
3621 // We found a deoptimized method in the stack.
3622 needs_deoptimization_ = true;
3623 return false;
3624 }
Mingyao Yang99170c62015-07-06 11:10:37 -07003625 ShadowFrame* frame = GetThread()->FindDebuggerShadowFrame(GetFrameId());
3626 if (frame != nullptr) {
3627 // The debugger allocated a ShadowFrame to update a variable in the stack: we need to
3628 // deoptimize the stack to execute (and deallocate) this frame.
3629 needs_deoptimization_ = true;
3630 return false;
3631 }
Sebastien Hertz520633b2015-09-08 17:03:36 +02003632 return true;
3633 }
3634
3635 bool NeedsDeoptimization() const {
3636 return needs_deoptimization_;
3637 }
3638
3639 private:
3640 // Do we need to deoptimize the stack?
3641 bool needs_deoptimization_;
3642
3643 DISALLOW_COPY_AND_ASSIGN(NeedsDeoptimizationVisitor);
3644};
3645
3646// Do we need to deoptimize the stack to handle an exception?
3647bool Dbg::IsForcedInterpreterNeededForExceptionImpl(Thread* thread) {
3648 const SingleStepControl* const ssc = thread->GetSingleStepControl();
3649 if (ssc != nullptr) {
3650 // We deopt to step into the catch handler.
3651 return true;
3652 }
3653 // Deoptimization is required if at least one method in the stack needs it. However we
3654 // skip frames that will be unwound (thus not executed).
3655 NeedsDeoptimizationVisitor visitor(thread);
3656 visitor.WalkStack(true); // includes upcall.
3657 return visitor.NeedsDeoptimization();
3658}
3659
Jeff Hao449db332013-04-12 18:30:52 -07003660// Scoped utility class to suspend a thread so that we may do tasks such as walk its stack. Doesn't
3661// cause suspension if the thread is the current thread.
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07003662class ScopedDebuggerThreadSuspension {
Jeff Hao449db332013-04-12 18:30:52 -07003663 public:
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07003664 ScopedDebuggerThreadSuspension(Thread* self, JDWP::ObjectId thread_id)
Mathieu Chartier90443472015-07-16 20:32:27 -07003665 REQUIRES(!Locks::thread_list_lock_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003666 REQUIRES_SHARED(Locks::mutator_lock_) :
Ian Rogersf3d874c2014-07-17 18:52:42 -07003667 thread_(nullptr),
Jeff Hao449db332013-04-12 18:30:52 -07003668 error_(JDWP::ERR_NONE),
3669 self_suspend_(false),
Ian Rogers33e95662013-05-20 20:29:14 -07003670 other_suspend_(false) {
Jeff Hao449db332013-04-12 18:30:52 -07003671 ScopedObjectAccessUnchecked soa(self);
Sebastien Hertz69206392015-04-07 15:54:25 +02003672 thread_ = DecodeThread(soa, thread_id, &error_);
Jeff Hao449db332013-04-12 18:30:52 -07003673 if (error_ == JDWP::ERR_NONE) {
3674 if (thread_ == soa.Self()) {
3675 self_suspend_ = true;
3676 } else {
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07003677 Thread* suspended_thread;
3678 {
3679 ScopedThreadSuspension sts(self, kWaitingForDebuggerSuspension);
3680 jobject thread_peer = Dbg::GetObjectRegistry()->GetJObject(thread_id);
3681 bool timed_out;
3682 ThreadList* const thread_list = Runtime::Current()->GetThreadList();
3683 suspended_thread = thread_list->SuspendThreadByPeer(thread_peer, true, true, &timed_out);
3684 }
Ian Rogersf3d874c2014-07-17 18:52:42 -07003685 if (suspended_thread == nullptr) {
Jeff Hao449db332013-04-12 18:30:52 -07003686 // Thread terminated from under us while suspending.
3687 error_ = JDWP::ERR_INVALID_THREAD;
3688 } else {
3689 CHECK_EQ(suspended_thread, thread_);
3690 other_suspend_ = true;
3691 }
3692 }
3693 }
Elliott Hughes2435a572012-02-17 16:07:41 -08003694 }
Elliott Hughes86964332012-02-15 19:37:42 -08003695
Jeff Hao449db332013-04-12 18:30:52 -07003696 Thread* GetThread() const {
3697 return thread_;
3698 }
3699
3700 JDWP::JdwpError GetError() const {
3701 return error_;
3702 }
3703
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07003704 ~ScopedDebuggerThreadSuspension() {
Jeff Hao449db332013-04-12 18:30:52 -07003705 if (other_suspend_) {
3706 Runtime::Current()->GetThreadList()->Resume(thread_, true);
3707 }
3708 }
3709
3710 private:
3711 Thread* thread_;
3712 JDWP::JdwpError error_;
3713 bool self_suspend_;
3714 bool other_suspend_;
3715};
3716
3717JDWP::JdwpError Dbg::ConfigureStep(JDWP::ObjectId thread_id, JDWP::JdwpStepSize step_size,
3718 JDWP::JdwpStepDepth step_depth) {
3719 Thread* self = Thread::Current();
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07003720 ScopedDebuggerThreadSuspension sts(self, thread_id);
Jeff Hao449db332013-04-12 18:30:52 -07003721 if (sts.GetError() != JDWP::ERR_NONE) {
3722 return sts.GetError();
3723 }
3724
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003725 // Work out what ArtMethod* we're in, the current line number, and how deep the stack currently
Elliott Hughes2435a572012-02-17 16:07:41 -08003726 // is for step-out.
Ian Rogers0399dde2012-06-06 17:09:28 -07003727 struct SingleStepStackVisitor : public StackVisitor {
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003728 explicit SingleStepStackVisitor(Thread* thread) REQUIRES_SHARED(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01003729 : StackVisitor(thread, nullptr, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
3730 stack_depth(0),
3731 method(nullptr),
3732 line_number(-1) {}
Ian Rogersca190662012-06-26 15:45:57 -07003733
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003734 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
3735 // annotalysis.
3736 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003737 ArtMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07003738 if (!m->IsRuntimeMethod()) {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003739 ++stack_depth;
3740 if (method == nullptr) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08003741 mirror::DexCache* dex_cache = m->GetDeclaringClass()->GetDexCache();
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003742 method = m;
Ian Rogersc0542af2014-09-03 16:16:56 -07003743 if (dex_cache != nullptr) {
David Sehr9323e6e2016-09-13 08:58:35 -07003744 const DexFile* dex_file = dex_cache->GetDexFile();
3745 line_number = annotations::GetLineNumFromPC(dex_file, m, GetDexPc());
Elliott Hughes2435a572012-02-17 16:07:41 -08003746 }
Elliott Hughes86964332012-02-15 19:37:42 -08003747 }
3748 }
Elliott Hughes530fa002012-03-12 11:44:49 -07003749 return true;
Elliott Hughes86964332012-02-15 19:37:42 -08003750 }
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003751
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003752 int stack_depth;
Mathieu Chartiere401d142015-04-22 13:56:20 -07003753 ArtMethod* method;
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003754 int32_t line_number;
Elliott Hughes86964332012-02-15 19:37:42 -08003755 };
Jeff Hao449db332013-04-12 18:30:52 -07003756
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003757 Thread* const thread = sts.GetThread();
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003758 SingleStepStackVisitor visitor(thread);
Ian Rogers0399dde2012-06-06 17:09:28 -07003759 visitor.WalkStack();
Elliott Hughes86964332012-02-15 19:37:42 -08003760
Elliott Hughes2435a572012-02-17 16:07:41 -08003761 // Find the dex_pc values that correspond to the current line, for line-based single-stepping.
Elliott Hughes2435a572012-02-17 16:07:41 -08003762 struct DebugCallbackContext {
Roland Levillain3887c462015-08-12 18:15:42 +01003763 DebugCallbackContext(SingleStepControl* single_step_control_cb,
3764 int32_t line_number_cb, const DexFile::CodeItem* code_item)
3765 : single_step_control_(single_step_control_cb), line_number_(line_number_cb),
3766 code_item_(code_item), last_pc_valid(false), last_pc(0) {
Elliott Hughes2435a572012-02-17 16:07:41 -08003767 }
3768
David Srbeckyb06e28e2015-12-10 13:15:00 +00003769 static bool Callback(void* raw_context, const DexFile::PositionInfo& entry) {
Elliott Hughes2435a572012-02-17 16:07:41 -08003770 DebugCallbackContext* context = reinterpret_cast<DebugCallbackContext*>(raw_context);
David Srbeckyb06e28e2015-12-10 13:15:00 +00003771 if (static_cast<int32_t>(entry.line_) == context->line_number_) {
Elliott Hughes2435a572012-02-17 16:07:41 -08003772 if (!context->last_pc_valid) {
3773 // Everything from this address until the next line change is ours.
David Srbeckyb06e28e2015-12-10 13:15:00 +00003774 context->last_pc = entry.address_;
Elliott Hughes2435a572012-02-17 16:07:41 -08003775 context->last_pc_valid = true;
3776 }
3777 // Otherwise, if we're already in a valid range for this line,
3778 // just keep going (shouldn't really happen)...
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003779 } else if (context->last_pc_valid) { // and the line number is new
Elliott Hughes2435a572012-02-17 16:07:41 -08003780 // Add everything from the last entry up until here to the set
David Srbeckyb06e28e2015-12-10 13:15:00 +00003781 for (uint32_t dex_pc = context->last_pc; dex_pc < entry.address_; ++dex_pc) {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003782 context->single_step_control_->AddDexPc(dex_pc);
Elliott Hughes2435a572012-02-17 16:07:41 -08003783 }
3784 context->last_pc_valid = false;
3785 }
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003786 return false; // There may be multiple entries for any given line.
Elliott Hughes2435a572012-02-17 16:07:41 -08003787 }
3788
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003789 ~DebugCallbackContext() {
Elliott Hughes2435a572012-02-17 16:07:41 -08003790 // If the line number was the last in the position table...
3791 if (last_pc_valid) {
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003792 size_t end = code_item_->insns_size_in_code_units_;
Elliott Hughes2435a572012-02-17 16:07:41 -08003793 for (uint32_t dex_pc = last_pc; dex_pc < end; ++dex_pc) {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003794 single_step_control_->AddDexPc(dex_pc);
Elliott Hughes2435a572012-02-17 16:07:41 -08003795 }
3796 }
3797 }
3798
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003799 SingleStepControl* const single_step_control_;
3800 const int32_t line_number_;
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003801 const DexFile::CodeItem* const code_item_;
Elliott Hughes2435a572012-02-17 16:07:41 -08003802 bool last_pc_valid;
3803 uint32_t last_pc;
3804 };
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003805
3806 // Allocate single step.
Sebastien Hertz1558b572015-02-25 15:05:59 +01003807 SingleStepControl* single_step_control =
3808 new (std::nothrow) SingleStepControl(step_size, step_depth,
3809 visitor.stack_depth, visitor.method);
3810 if (single_step_control == nullptr) {
3811 LOG(ERROR) << "Failed to allocate SingleStepControl";
3812 return JDWP::ERR_OUT_OF_MEMORY;
3813 }
3814
Mathieu Chartiere401d142015-04-22 13:56:20 -07003815 ArtMethod* m = single_step_control->GetMethod();
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003816 const int32_t line_number = visitor.line_number;
Sebastien Hertz52f5f932015-05-28 11:00:57 +02003817 // Note: if the thread is not running Java code (pure native thread), there is no "current"
3818 // method on the stack (and no line number either).
3819 if (m != nullptr && !m->IsNative()) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003820 const DexFile::CodeItem* const code_item = m->GetCodeItem();
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003821 DebugCallbackContext context(single_step_control, line_number, code_item);
David Srbeckyb06e28e2015-12-10 13:15:00 +00003822 m->GetDexFile()->DecodeDebugPositionInfo(code_item, DebugCallbackContext::Callback, &context);
Elliott Hughes3e2e1a22012-02-21 11:33:41 -08003823 }
Elliott Hughes2435a572012-02-17 16:07:41 -08003824
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003825 // Activate single-step in the thread.
3826 thread->ActivateSingleStepControl(single_step_control);
Elliott Hughes86964332012-02-15 19:37:42 -08003827
Elliott Hughes2435a572012-02-17 16:07:41 -08003828 if (VLOG_IS_ON(jdwp)) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003829 VLOG(jdwp) << "Single-step thread: " << *thread;
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003830 VLOG(jdwp) << "Single-step step size: " << single_step_control->GetStepSize();
3831 VLOG(jdwp) << "Single-step step depth: " << single_step_control->GetStepDepth();
David Sehr709b0702016-10-13 09:12:37 -07003832 VLOG(jdwp) << "Single-step current method: "
3833 << ArtMethod::PrettyMethod(single_step_control->GetMethod());
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003834 VLOG(jdwp) << "Single-step current line: " << line_number;
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003835 VLOG(jdwp) << "Single-step current stack depth: " << single_step_control->GetStackDepth();
Elliott Hughes2435a572012-02-17 16:07:41 -08003836 VLOG(jdwp) << "Single-step dex_pc values:";
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003837 for (uint32_t dex_pc : single_step_control->GetDexPcs()) {
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003838 VLOG(jdwp) << StringPrintf(" %#x", dex_pc);
Elliott Hughes2435a572012-02-17 16:07:41 -08003839 }
3840 }
3841
3842 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003843}
3844
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003845void Dbg::UnconfigureStep(JDWP::ObjectId thread_id) {
3846 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07003847 JDWP::JdwpError error;
3848 Thread* thread = DecodeThread(soa, thread_id, &error);
Sebastien Hertz87118ed2013-11-26 17:57:18 +01003849 if (error == JDWP::ERR_NONE) {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003850 thread->DeactivateSingleStepControl();
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003851 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003852}
3853
Elliott Hughes45651fd2012-02-21 15:48:20 -08003854static char JdwpTagToShortyChar(JDWP::JdwpTag tag) {
3855 switch (tag) {
3856 default:
3857 LOG(FATAL) << "unknown JDWP tag: " << PrintableChar(tag);
Ian Rogersfc787ec2014-10-09 21:56:44 -07003858 UNREACHABLE();
Elliott Hughes45651fd2012-02-21 15:48:20 -08003859
3860 // Primitives.
3861 case JDWP::JT_BYTE: return 'B';
3862 case JDWP::JT_CHAR: return 'C';
3863 case JDWP::JT_FLOAT: return 'F';
3864 case JDWP::JT_DOUBLE: return 'D';
3865 case JDWP::JT_INT: return 'I';
3866 case JDWP::JT_LONG: return 'J';
3867 case JDWP::JT_SHORT: return 'S';
3868 case JDWP::JT_VOID: return 'V';
3869 case JDWP::JT_BOOLEAN: return 'Z';
3870
3871 // Reference types.
3872 case JDWP::JT_ARRAY:
3873 case JDWP::JT_OBJECT:
3874 case JDWP::JT_STRING:
3875 case JDWP::JT_THREAD:
3876 case JDWP::JT_THREAD_GROUP:
3877 case JDWP::JT_CLASS_LOADER:
3878 case JDWP::JT_CLASS_OBJECT:
3879 return 'L';
3880 }
3881}
3882
Sebastien Hertzcbc50642015-06-01 17:33:12 +02003883JDWP::JdwpError Dbg::PrepareInvokeMethod(uint32_t request_id, JDWP::ObjectId thread_id,
3884 JDWP::ObjectId object_id, JDWP::RefTypeId class_id,
3885 JDWP::MethodId method_id, uint32_t arg_count,
3886 uint64_t arg_values[], JDWP::JdwpTag* arg_types,
3887 uint32_t options) {
3888 Thread* const self = Thread::Current();
3889 CHECK_EQ(self, GetDebugThread()) << "This must be called by the JDWP thread";
Sebastien Hertzd4032e42015-06-12 15:47:34 +02003890 const bool resume_all_threads = ((options & JDWP::INVOKE_SINGLE_THREADED) == 0);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003891
Sebastien Hertzcbc50642015-06-01 17:33:12 +02003892 ThreadList* thread_list = Runtime::Current()->GetThreadList();
Ian Rogersc0542af2014-09-03 16:16:56 -07003893 Thread* targetThread = nullptr;
Elliott Hughesd07986f2011-12-06 18:27:45 -08003894 {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003895 ScopedObjectAccessUnchecked soa(self);
Ian Rogersc0542af2014-09-03 16:16:56 -07003896 JDWP::JdwpError error;
3897 targetThread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08003898 if (error != JDWP::ERR_NONE) {
3899 LOG(ERROR) << "InvokeMethod request for invalid thread id " << thread_id;
3900 return error;
Elliott Hughesd07986f2011-12-06 18:27:45 -08003901 }
Sebastien Hertz1558b572015-02-25 15:05:59 +01003902 if (targetThread->GetInvokeReq() != nullptr) {
3903 // Thread is already invoking a method on behalf of the debugger.
3904 LOG(ERROR) << "InvokeMethod request for thread already invoking a method: " << *targetThread;
3905 return JDWP::ERR_ALREADY_INVOKING;
3906 }
3907 if (!targetThread->IsReadyForDebugInvoke()) {
3908 // Thread is not suspended by an event so it cannot invoke a method.
Elliott Hughesd07986f2011-12-06 18:27:45 -08003909 LOG(ERROR) << "InvokeMethod request for thread not stopped by event: " << *targetThread;
3910 return JDWP::ERR_INVALID_THREAD;
3911 }
3912
3913 /*
Sebastien Hertzd4032e42015-06-12 15:47:34 +02003914 * According to the JDWP specs, we are expected to resume all threads (or only the
3915 * target thread) once. So if a thread has been suspended more than once (either by
3916 * the debugger for an event or by the runtime for GC), it will remain suspended before
3917 * the invoke is executed. This means the debugger is responsible to properly resume all
3918 * the threads it has suspended so the target thread can execute the method.
Elliott Hughesd07986f2011-12-06 18:27:45 -08003919 *
Sebastien Hertzd4032e42015-06-12 15:47:34 +02003920 * However, for compatibility reason with older versions of debuggers (like Eclipse), we
3921 * fully resume all threads (by canceling *all* debugger suspensions) when the debugger
3922 * wants us to resume all threads. This is to avoid ending up in deadlock situation.
3923 *
3924 * On the other hand, if we are asked to only resume the target thread, then we follow the
3925 * JDWP specs by resuming that thread only once. This means the thread will remain suspended
3926 * if it has been suspended more than once before the invoke (and again, this is the
3927 * responsibility of the debugger to properly resume that thread before invoking a method).
Elliott Hughesd07986f2011-12-06 18:27:45 -08003928 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003929 int suspend_count;
3930 {
Ian Rogers50b35e22012-10-04 10:09:15 -07003931 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003932 suspend_count = targetThread->GetSuspendCount();
3933 }
Sebastien Hertzd4032e42015-06-12 15:47:34 +02003934 if (suspend_count > 1 && resume_all_threads) {
3935 // The target thread will remain suspended even after we resume it. Let's emit a warning
3936 // to indicate the invoke won't be executed until the thread is resumed.
3937 LOG(WARNING) << *targetThread << " suspended more than once (suspend count == "
3938 << suspend_count << "). This thread will invoke the method only once "
3939 << "it is fully resumed.";
Elliott Hughesd07986f2011-12-06 18:27:45 -08003940 }
3941
Ian Rogersc0542af2014-09-03 16:16:56 -07003942 mirror::Object* receiver = gRegistry->Get<mirror::Object*>(object_id, &error);
3943 if (error != JDWP::ERR_NONE) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08003944 return JDWP::ERR_INVALID_OBJECT;
3945 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003946
Sebastien Hertz1558b572015-02-25 15:05:59 +01003947 gRegistry->Get<mirror::Object*>(thread_id, &error);
Ian Rogersc0542af2014-09-03 16:16:56 -07003948 if (error != JDWP::ERR_NONE) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08003949 return JDWP::ERR_INVALID_OBJECT;
3950 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003951
Ian Rogersc0542af2014-09-03 16:16:56 -07003952 mirror::Class* c = DecodeClass(class_id, &error);
3953 if (c == nullptr) {
3954 return error;
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08003955 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003956
Mathieu Chartiere401d142015-04-22 13:56:20 -07003957 ArtMethod* m = FromMethodId(method_id);
Ian Rogersc0542af2014-09-03 16:16:56 -07003958 if (m->IsStatic() != (receiver == nullptr)) {
Elliott Hughes45651fd2012-02-21 15:48:20 -08003959 return JDWP::ERR_INVALID_METHODID;
3960 }
3961 if (m->IsStatic()) {
3962 if (m->GetDeclaringClass() != c) {
3963 return JDWP::ERR_INVALID_METHODID;
3964 }
3965 } else {
3966 if (!m->GetDeclaringClass()->IsAssignableFrom(c)) {
3967 return JDWP::ERR_INVALID_METHODID;
3968 }
3969 }
3970
3971 // Check the argument list matches the method.
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003972 uint32_t shorty_len = 0;
3973 const char* shorty = m->GetShorty(&shorty_len);
3974 if (shorty_len - 1 != arg_count) {
Elliott Hughes45651fd2012-02-21 15:48:20 -08003975 return JDWP::ERR_ILLEGAL_ARGUMENT;
3976 }
Elliott Hughes09201632013-04-15 15:50:07 -07003977
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003978 {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003979 StackHandleScope<2> hs(soa.Self());
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003980 HandleWrapper<mirror::Object> h_obj(hs.NewHandleWrapper(&receiver));
3981 HandleWrapper<mirror::Class> h_klass(hs.NewHandleWrapper(&c));
3982 const DexFile::TypeList* types = m->GetParameterTypeList();
3983 for (size_t i = 0; i < arg_count; ++i) {
3984 if (shorty[i + 1] != JdwpTagToShortyChar(arg_types[i])) {
Elliott Hughes09201632013-04-15 15:50:07 -07003985 return JDWP::ERR_ILLEGAL_ARGUMENT;
3986 }
3987
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003988 if (shorty[i + 1] == 'L') {
3989 // Did we really get an argument of an appropriate reference type?
Ian Rogersa0485602014-12-02 15:48:04 -08003990 mirror::Class* parameter_type =
Vladimir Marko942fd312017-01-16 20:52:19 +00003991 m->GetClassFromTypeIndex(types->GetTypeItem(i).type_idx_, true /* resolve */);
Ian Rogersc0542af2014-09-03 16:16:56 -07003992 mirror::Object* argument = gRegistry->Get<mirror::Object*>(arg_values[i], &error);
3993 if (error != JDWP::ERR_NONE) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003994 return JDWP::ERR_INVALID_OBJECT;
3995 }
Ian Rogersc0542af2014-09-03 16:16:56 -07003996 if (argument != nullptr && !argument->InstanceOf(parameter_type)) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003997 return JDWP::ERR_ILLEGAL_ARGUMENT;
3998 }
3999
4000 // Turn the on-the-wire ObjectId into a jobject.
4001 jvalue& v = reinterpret_cast<jvalue&>(arg_values[i]);
4002 v.l = gRegistry->GetJObject(arg_values[i]);
4003 }
Elliott Hughes09201632013-04-15 15:50:07 -07004004 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08004005 }
4006
Sebastien Hertz1558b572015-02-25 15:05:59 +01004007 // Allocates a DebugInvokeReq.
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004008 DebugInvokeReq* req = new (std::nothrow) DebugInvokeReq(request_id, thread_id, receiver, c, m,
4009 options, arg_values, arg_count);
4010 if (req == nullptr) {
Sebastien Hertz1558b572015-02-25 15:05:59 +01004011 LOG(ERROR) << "Failed to allocate DebugInvokeReq";
4012 return JDWP::ERR_OUT_OF_MEMORY;
4013 }
4014
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004015 // Attaches the DebugInvokeReq to the target thread so it executes the method when
4016 // it is resumed. Once the invocation completes, the target thread will delete it before
4017 // suspending itself (see ThreadList::SuspendSelfForDebugger).
4018 targetThread->SetDebugInvokeReq(req);
Elliott Hughesd07986f2011-12-06 18:27:45 -08004019 }
4020
4021 // 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 +02004022 // away we're sitting high and dry -- but we must release this before the UndoDebuggerSuspensions
4023 // call.
Sebastien Hertzd4032e42015-06-12 15:47:34 +02004024 if (resume_all_threads) {
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004025 VLOG(jdwp) << " Resuming all threads";
4026 thread_list->UndoDebuggerSuspensions();
4027 } else {
4028 VLOG(jdwp) << " Resuming event thread only";
Elliott Hughesd07986f2011-12-06 18:27:45 -08004029 thread_list->Resume(targetThread, true);
4030 }
4031
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004032 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004033}
4034
4035void Dbg::ExecuteMethod(DebugInvokeReq* pReq) {
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004036 Thread* const self = Thread::Current();
4037 CHECK_NE(self, GetDebugThread()) << "This must be called by the event thread";
4038
4039 ScopedObjectAccess soa(self);
Elliott Hughesd07986f2011-12-06 18:27:45 -08004040
Elliott Hughes81ff3182012-03-23 20:35:56 -07004041 // We can be called while an exception is pending. We need
Elliott Hughesd07986f2011-12-06 18:27:45 -08004042 // to preserve that across the method invocation.
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004043 StackHandleScope<1> hs(soa.Self());
4044 Handle<mirror::Throwable> old_exception = hs.NewHandle(soa.Self()->GetException());
Sebastien Hertz1558b572015-02-25 15:05:59 +01004045 soa.Self()->ClearException();
Elliott Hughesd07986f2011-12-06 18:27:45 -08004046
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004047 // Execute the method then sends reply to the debugger.
4048 ExecuteMethodWithoutPendingException(soa, pReq);
4049
4050 // If an exception was pending before the invoke, restore it now.
4051 if (old_exception.Get() != nullptr) {
4052 soa.Self()->SetException(old_exception.Get());
4053 }
4054}
4055
4056// Helper function: write a variable-width value into the output input buffer.
4057static void WriteValue(JDWP::ExpandBuf* pReply, int width, uint64_t value) {
4058 switch (width) {
4059 case 1:
4060 expandBufAdd1(pReply, value);
4061 break;
4062 case 2:
4063 expandBufAdd2BE(pReply, value);
4064 break;
4065 case 4:
4066 expandBufAdd4BE(pReply, value);
4067 break;
4068 case 8:
4069 expandBufAdd8BE(pReply, value);
4070 break;
4071 default:
4072 LOG(FATAL) << width;
4073 UNREACHABLE();
4074 }
4075}
4076
4077void Dbg::ExecuteMethodWithoutPendingException(ScopedObjectAccess& soa, DebugInvokeReq* pReq) {
4078 soa.Self()->AssertNoPendingException();
4079
Elliott Hughesd07986f2011-12-06 18:27:45 -08004080 // Translate the method through the vtable, unless the debugger wants to suppress it.
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004081 ArtMethod* m = pReq->method;
Andreas Gampe542451c2016-07-26 09:02:02 -07004082 PointerSize image_pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
Sebastien Hertz1558b572015-02-25 15:05:59 +01004083 if ((pReq->options & JDWP::INVOKE_NONVIRTUAL) == 0 && pReq->receiver.Read() != nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004084 ArtMethod* actual_method =
4085 pReq->klass.Read()->FindVirtualMethodForVirtualOrInterface(m, image_pointer_size);
4086 if (actual_method != m) {
David Sehr709b0702016-10-13 09:12:37 -07004087 VLOG(jdwp) << "ExecuteMethod translated " << ArtMethod::PrettyMethod(m)
4088 << " to " << ArtMethod::PrettyMethod(actual_method);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004089 m = actual_method;
Elliott Hughes45651fd2012-02-21 15:48:20 -08004090 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08004091 }
David Sehr709b0702016-10-13 09:12:37 -07004092 VLOG(jdwp) << "ExecuteMethod " << ArtMethod::PrettyMethod(m)
Sebastien Hertz1558b572015-02-25 15:05:59 +01004093 << " receiver=" << pReq->receiver.Read()
Sebastien Hertzd38667a2013-11-25 15:43:54 +01004094 << " arg_count=" << pReq->arg_count;
Mathieu Chartiere401d142015-04-22 13:56:20 -07004095 CHECK(m != nullptr);
Elliott Hughesd07986f2011-12-06 18:27:45 -08004096
Roland Levillain33d69032015-06-18 18:20:59 +01004097 static_assert(sizeof(jvalue) == sizeof(uint64_t), "jvalue and uint64_t have different sizes.");
Elliott Hughesd07986f2011-12-06 18:27:45 -08004098
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004099 // Invoke the method.
Jeff Hao39b6c242015-05-19 20:30:23 -07004100 ScopedLocalRef<jobject> ref(soa.Env(), soa.AddLocalReference<jobject>(pReq->receiver.Read()));
Andreas Gampe13b27842016-11-07 16:48:23 -08004101 JValue result = InvokeWithJValues(soa, ref.get(), jni::EncodeArtMethod(m),
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004102 reinterpret_cast<jvalue*>(pReq->arg_values.get()));
Elliott Hughesd07986f2011-12-06 18:27:45 -08004103
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004104 // Prepare JDWP ids for the reply.
4105 JDWP::JdwpTag result_tag = BasicTagFromDescriptor(m->GetShorty());
4106 const bool is_object_result = (result_tag == JDWP::JT_OBJECT);
Jeff Hao064d24e2016-08-25 03:52:40 +00004107 StackHandleScope<3> hs(soa.Self());
Sebastien Hertz1558b572015-02-25 15:05:59 +01004108 Handle<mirror::Object> object_result = hs.NewHandle(is_object_result ? result.GetL() : nullptr);
4109 Handle<mirror::Throwable> exception = hs.NewHandle(soa.Self()->GetException());
4110 soa.Self()->ClearException();
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004111
4112 if (!IsDebuggerActive()) {
4113 // The debugger detached: we must not re-suspend threads. We also don't need to fill the reply
4114 // because it won't be sent either.
4115 return;
4116 }
4117
4118 JDWP::ObjectId exceptionObjectId = gRegistry->Add(exception);
4119 uint64_t result_value = 0;
4120 if (exceptionObjectId != 0) {
Sebastien Hertz1558b572015-02-25 15:05:59 +01004121 VLOG(jdwp) << " JDWP invocation returning with exception=" << exception.Get()
4122 << " " << exception->Dump();
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004123 result_value = 0;
Sebastien Hertz1558b572015-02-25 15:05:59 +01004124 } else if (is_object_result) {
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004125 /* if no exception was thrown, examine object result more closely */
Sebastien Hertz1558b572015-02-25 15:05:59 +01004126 JDWP::JdwpTag new_tag = TagFromObject(soa, object_result.Get());
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004127 if (new_tag != result_tag) {
4128 VLOG(jdwp) << " JDWP promoted result from " << result_tag << " to " << new_tag;
4129 result_tag = new_tag;
Elliott Hughesd07986f2011-12-06 18:27:45 -08004130 }
4131
Sebastien Hertz1558b572015-02-25 15:05:59 +01004132 // Register the object in the registry and reference its ObjectId. This ensures
4133 // GC safety and prevents from accessing stale reference if the object is moved.
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004134 result_value = gRegistry->Add(object_result.Get());
Sebastien Hertz1558b572015-02-25 15:05:59 +01004135 } else {
4136 // Primitive result.
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004137 DCHECK(IsPrimitiveTag(result_tag));
4138 result_value = result.GetJ();
4139 }
4140 const bool is_constructor = m->IsConstructor() && !m->IsStatic();
4141 if (is_constructor) {
4142 // If we invoked a constructor (which actually returns void), return the receiver,
4143 // unless we threw, in which case we return null.
Sebastien Hertza3e13772015-11-05 12:09:44 +01004144 DCHECK_EQ(JDWP::JT_VOID, result_tag);
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004145 if (exceptionObjectId == 0) {
Jeff Hao064d24e2016-08-25 03:52:40 +00004146 if (m->GetDeclaringClass()->IsStringClass()) {
4147 // For string constructors, the new string is remapped to the receiver (stored in ref).
4148 Handle<mirror::Object> decoded_ref = hs.NewHandle(soa.Self()->DecodeJObject(ref.get()));
4149 result_value = gRegistry->Add(decoded_ref);
4150 result_tag = TagFromObject(soa, decoded_ref.Get());
4151 } else {
4152 // TODO we could keep the receiver ObjectId in the DebugInvokeReq to avoid looking into the
4153 // object registry.
4154 result_value = GetObjectRegistry()->Add(pReq->receiver.Read());
4155 result_tag = TagFromObject(soa, pReq->receiver.Read());
4156 }
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004157 } else {
4158 result_value = 0;
Sebastien Hertza3e13772015-11-05 12:09:44 +01004159 result_tag = JDWP::JT_OBJECT;
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004160 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08004161 }
4162
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004163 // Suspend other threads if the invoke is not single-threaded.
4164 if ((pReq->options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07004165 ScopedThreadSuspension sts(soa.Self(), kWaitingForDebuggerSuspension);
Hiroshi Yamauchi8f95cf32016-04-19 11:14:06 -07004166 // Avoid a deadlock between GC and debugger where GC gets suspended during GC. b/25800335.
4167 gc::ScopedGCCriticalSection gcs(soa.Self(), gc::kGcCauseDebugger, gc::kCollectorTypeDebugger);
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004168 VLOG(jdwp) << " Suspending all threads";
4169 Runtime::Current()->GetThreadList()->SuspendAllForDebugger();
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004170 }
4171
4172 VLOG(jdwp) << " --> returned " << result_tag
4173 << StringPrintf(" %#" PRIx64 " (except=%#" PRIx64 ")", result_value,
4174 exceptionObjectId);
4175
4176 // Show detailed debug output.
4177 if (result_tag == JDWP::JT_STRING && exceptionObjectId == 0) {
4178 if (result_value != 0) {
4179 if (VLOG_IS_ON(jdwp)) {
4180 std::string result_string;
4181 JDWP::JdwpError error = Dbg::StringToUtf8(result_value, &result_string);
4182 CHECK_EQ(error, JDWP::ERR_NONE);
4183 VLOG(jdwp) << " string '" << result_string << "'";
4184 }
4185 } else {
4186 VLOG(jdwp) << " string (null)";
4187 }
4188 }
4189
4190 // Attach the reply to DebugInvokeReq so it can be sent to the debugger when the event thread
4191 // is ready to suspend.
4192 BuildInvokeReply(pReq->reply, pReq->request_id, result_tag, result_value, exceptionObjectId);
4193}
4194
4195void Dbg::BuildInvokeReply(JDWP::ExpandBuf* pReply, uint32_t request_id, JDWP::JdwpTag result_tag,
4196 uint64_t result_value, JDWP::ObjectId exception) {
4197 // Make room for the JDWP header since we do not know the size of the reply yet.
4198 JDWP::expandBufAddSpace(pReply, kJDWPHeaderLen);
4199
4200 size_t width = GetTagWidth(result_tag);
4201 JDWP::expandBufAdd1(pReply, result_tag);
4202 if (width != 0) {
4203 WriteValue(pReply, width, result_value);
4204 }
4205 JDWP::expandBufAdd1(pReply, JDWP::JT_OBJECT);
4206 JDWP::expandBufAddObjectId(pReply, exception);
4207
4208 // Now we know the size, we can complete the JDWP header.
4209 uint8_t* buf = expandBufGetBuffer(pReply);
4210 JDWP::Set4BE(buf + kJDWPHeaderSizeOffset, expandBufGetLength(pReply));
4211 JDWP::Set4BE(buf + kJDWPHeaderIdOffset, request_id);
4212 JDWP::Set1(buf + kJDWPHeaderFlagsOffset, kJDWPFlagReply); // flags
4213 JDWP::Set2BE(buf + kJDWPHeaderErrorCodeOffset, JDWP::ERR_NONE);
4214}
4215
4216void Dbg::FinishInvokeMethod(DebugInvokeReq* pReq) {
4217 CHECK_NE(Thread::Current(), GetDebugThread()) << "This must be called by the event thread";
4218
4219 JDWP::ExpandBuf* const pReply = pReq->reply;
4220 CHECK(pReply != nullptr) << "No reply attached to DebugInvokeReq";
4221
4222 // We need to prevent other threads (including JDWP thread) from interacting with the debugger
4223 // while we send the reply but are not yet suspended. The JDWP token will be released just before
4224 // we suspend ourself again (see ThreadList::SuspendSelfForDebugger).
4225 gJdwpState->AcquireJdwpTokenForEvent(pReq->thread_id);
4226
4227 // Send the reply unless the debugger detached before the completion of the method.
4228 if (IsDebuggerActive()) {
4229 const size_t replyDataLength = expandBufGetLength(pReply) - kJDWPHeaderLen;
4230 VLOG(jdwp) << StringPrintf("REPLY INVOKE id=0x%06x (length=%zu)",
4231 pReq->request_id, replyDataLength);
4232
4233 gJdwpState->SendRequest(pReply);
4234 } else {
4235 VLOG(jdwp) << "Not sending invoke reply because debugger detached";
Elliott Hughesd07986f2011-12-06 18:27:45 -08004236 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004237}
4238
Elliott Hughesd07986f2011-12-06 18:27:45 -08004239/*
Elliott Hughes4b9702c2013-02-20 18:13:24 -08004240 * "request" contains a full JDWP packet, possibly with multiple chunks. We
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004241 * need to process each, accumulate the replies, and ship the whole thing
4242 * back.
4243 *
4244 * Returns "true" if we have a reply. The reply buffer is newly allocated,
4245 * and includes the chunk type/length, followed by the data.
4246 *
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08004247 * OLD-TODO: we currently assume that the request and reply include a single
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004248 * chunk. If this becomes inconvenient we will need to adapt.
4249 */
Ian Rogersc0542af2014-09-03 16:16:56 -07004250bool Dbg::DdmHandlePacket(JDWP::Request* request, uint8_t** pReplyBuf, int* pReplyLen) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004251 Thread* self = Thread::Current();
4252 JNIEnv* env = self->GetJniEnv();
4253
Ian Rogersc0542af2014-09-03 16:16:56 -07004254 uint32_t type = request->ReadUnsigned32("type");
4255 uint32_t length = request->ReadUnsigned32("length");
Elliott Hughes4b9702c2013-02-20 18:13:24 -08004256
4257 // Create a byte[] corresponding to 'request'.
Ian Rogersc0542af2014-09-03 16:16:56 -07004258 size_t request_length = request->size();
Elliott Hughes4b9702c2013-02-20 18:13:24 -08004259 ScopedLocalRef<jbyteArray> dataArray(env, env->NewByteArray(request_length));
Ian Rogersc0542af2014-09-03 16:16:56 -07004260 if (dataArray.get() == nullptr) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08004261 LOG(WARNING) << "byte[] allocation failed: " << request_length;
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004262 env->ExceptionClear();
4263 return false;
4264 }
Ian Rogersc0542af2014-09-03 16:16:56 -07004265 env->SetByteArrayRegion(dataArray.get(), 0, request_length,
4266 reinterpret_cast<const jbyte*>(request->data()));
4267 request->Skip(request_length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004268
4269 // Run through and find all chunks. [Currently just find the first.]
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004270 ScopedByteArrayRO contents(env, dataArray.get());
Elliott Hughes4b9702c2013-02-20 18:13:24 -08004271 if (length != request_length) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08004272 LOG(WARNING) << StringPrintf("bad chunk found (len=%u pktLen=%zd)", length, request_length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004273 return false;
4274 }
4275
4276 // Call "private static Chunk dispatch(int type, byte[] data, int offset, int length)".
Elliott Hugheseac76672012-05-24 21:56:51 -07004277 ScopedLocalRef<jobject> chunk(env, env->CallStaticObjectMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
4278 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_dispatch,
Elliott Hughes4b9702c2013-02-20 18:13:24 -08004279 type, dataArray.get(), 0, length));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004280 if (env->ExceptionCheck()) {
4281 LOG(INFO) << StringPrintf("Exception thrown by dispatcher for 0x%08x", type);
4282 env->ExceptionDescribe();
4283 env->ExceptionClear();
4284 return false;
4285 }
4286
Ian Rogersc0542af2014-09-03 16:16:56 -07004287 if (chunk.get() == nullptr) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004288 return false;
4289 }
4290
4291 /*
4292 * Pull the pieces out of the chunk. We copy the results into a
4293 * newly-allocated buffer that the caller can free. We don't want to
4294 * continue using the Chunk object because nothing has a reference to it.
4295 *
4296 * We could avoid this by returning type/data/offset/length and having
4297 * the caller be aware of the object lifetime issues, but that
Elliott Hughes81ff3182012-03-23 20:35:56 -07004298 * integrates the JDWP code more tightly into the rest of the runtime, and doesn't work
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004299 * if we have responses for multiple chunks.
4300 *
4301 * So we're pretty much stuck with copying data around multiple times.
4302 */
Elliott Hugheseac76672012-05-24 21:56:51 -07004303 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 -08004304 jint offset = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_offset);
Elliott Hugheseac76672012-05-24 21:56:51 -07004305 length = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_length);
Elliott Hugheseac76672012-05-24 21:56:51 -07004306 type = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_type);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004307
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08004308 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 -07004309 if (length == 0 || replyData.get() == nullptr) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004310 return false;
4311 }
4312
Elliott Hughes4b9702c2013-02-20 18:13:24 -08004313 const int kChunkHdrLen = 8;
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004314 uint8_t* reply = new uint8_t[length + kChunkHdrLen];
Ian Rogersc0542af2014-09-03 16:16:56 -07004315 if (reply == nullptr) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004316 LOG(WARNING) << "malloc failed: " << (length + kChunkHdrLen);
4317 return false;
4318 }
Elliott Hughesf7c3b662011-10-27 12:04:56 -07004319 JDWP::Set4BE(reply + 0, type);
4320 JDWP::Set4BE(reply + 4, length);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004321 env->GetByteArrayRegion(replyData.get(), offset, length, reinterpret_cast<jbyte*>(reply + kChunkHdrLen));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004322
4323 *pReplyBuf = reply;
4324 *pReplyLen = length + kChunkHdrLen;
4325
Elliott Hughes4b9702c2013-02-20 18:13:24 -08004326 VLOG(jdwp) << StringPrintf("dvmHandleDdm returning type=%.4s %p len=%d", reinterpret_cast<char*>(reply), reply, length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004327 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004328}
4329
Elliott Hughesa2155262011-11-16 16:26:58 -08004330void Dbg::DdmBroadcast(bool connect) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08004331 VLOG(jdwp) << "Broadcasting DDM " << (connect ? "connect" : "disconnect") << "...";
Elliott Hughes47fce012011-10-25 18:37:19 -07004332
4333 Thread* self = Thread::Current();
Ian Rogers50b35e22012-10-04 10:09:15 -07004334 if (self->GetState() != kRunnable) {
4335 LOG(ERROR) << "DDM broadcast in thread state " << self->GetState();
4336 /* try anyway? */
Elliott Hughes47fce012011-10-25 18:37:19 -07004337 }
4338
4339 JNIEnv* env = self->GetJniEnv();
Elliott Hughes47fce012011-10-25 18:37:19 -07004340 jint event = connect ? 1 /*DdmServer.CONNECTED*/ : 2 /*DdmServer.DISCONNECTED*/;
Elliott Hugheseac76672012-05-24 21:56:51 -07004341 env->CallStaticVoidMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
4342 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_broadcast,
4343 event);
Elliott Hughes47fce012011-10-25 18:37:19 -07004344 if (env->ExceptionCheck()) {
4345 LOG(ERROR) << "DdmServer.broadcast " << event << " failed";
4346 env->ExceptionDescribe();
4347 env->ExceptionClear();
4348 }
4349}
4350
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004351void Dbg::DdmConnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08004352 Dbg::DdmBroadcast(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004353}
4354
4355void Dbg::DdmDisconnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08004356 Dbg::DdmBroadcast(false);
Elliott Hughes47fce012011-10-25 18:37:19 -07004357 gDdmThreadNotification = false;
4358}
4359
4360/*
Elliott Hughes82188472011-11-07 18:11:48 -08004361 * Send a notification when a thread starts, stops, or changes its name.
Elliott Hughes47fce012011-10-25 18:37:19 -07004362 *
4363 * Because we broadcast the full set of threads when the notifications are
4364 * first enabled, it's possible for "thread" to be actively executing.
4365 */
Elliott Hughes82188472011-11-07 18:11:48 -08004366void Dbg::DdmSendThreadNotification(Thread* t, uint32_t type) {
Elliott Hughes47fce012011-10-25 18:37:19 -07004367 if (!gDdmThreadNotification) {
4368 return;
4369 }
4370
Elliott Hughes82188472011-11-07 18:11:48 -08004371 if (type == CHUNK_TYPE("THDE")) {
Elliott Hughes47fce012011-10-25 18:37:19 -07004372 uint8_t buf[4];
Ian Rogersd9c4fc92013-10-01 19:45:43 -07004373 JDWP::Set4BE(&buf[0], t->GetThreadId());
Elliott Hughes47fce012011-10-25 18:37:19 -07004374 Dbg::DdmSendChunk(CHUNK_TYPE("THDE"), 4, buf);
Elliott Hughes82188472011-11-07 18:11:48 -08004375 } else {
4376 CHECK(type == CHUNK_TYPE("THCR") || type == CHUNK_TYPE("THNM")) << type;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004377 ScopedObjectAccessUnchecked soa(Thread::Current());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004378 StackHandleScope<1> hs(soa.Self());
Andreas Gampe08883de2016-11-08 13:20:52 -08004379 Handle<mirror::String> name(hs.NewHandle(t->GetThreadName()));
Ian Rogersc0542af2014-09-03 16:16:56 -07004380 size_t char_count = (name.Get() != nullptr) ? name->GetLength() : 0;
Jeff Hao848f70a2014-01-15 13:49:50 -08004381 const jchar* chars = (name.Get() != nullptr) ? name->GetValue() : nullptr;
jessicahandojo3aaa37b2016-07-29 14:46:37 -07004382 bool is_compressed = (name.Get() != nullptr) ? name->IsCompressed() : false;
Elliott Hughes82188472011-11-07 18:11:48 -08004383
Elliott Hughes21f32d72011-11-09 17:44:13 -08004384 std::vector<uint8_t> bytes;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07004385 JDWP::Append4BE(bytes, t->GetThreadId());
jessicahandojo3aaa37b2016-07-29 14:46:37 -07004386 if (is_compressed) {
4387 const uint8_t* chars_compressed = name->GetValueCompressed();
4388 JDWP::AppendUtf16CompressedBE(bytes, chars_compressed, char_count);
4389 } else {
4390 JDWP::AppendUtf16BE(bytes, chars, char_count);
4391 }
Elliott Hughes21f32d72011-11-09 17:44:13 -08004392 CHECK_EQ(bytes.size(), char_count*2 + sizeof(uint32_t)*2);
4393 Dbg::DdmSendChunk(type, bytes);
Elliott Hughes47fce012011-10-25 18:37:19 -07004394 }
4395}
4396
Elliott Hughes47fce012011-10-25 18:37:19 -07004397void Dbg::DdmSetThreadNotification(bool enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004398 // Enable/disable thread notifications.
Elliott Hughes47fce012011-10-25 18:37:19 -07004399 gDdmThreadNotification = enable;
4400 if (enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004401 // Suspend the VM then post thread start notifications for all threads. Threads attaching will
4402 // see a suspension in progress and block until that ends. They then post their own start
4403 // notification.
4404 SuspendVM();
4405 std::list<Thread*> threads;
Ian Rogers50b35e22012-10-04 10:09:15 -07004406 Thread* self = Thread::Current();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004407 {
Ian Rogers50b35e22012-10-04 10:09:15 -07004408 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004409 threads = Runtime::Current()->GetThreadList()->GetList();
4410 }
4411 {
Ian Rogers50b35e22012-10-04 10:09:15 -07004412 ScopedObjectAccess soa(self);
Mathieu Chartier02e25112013-08-14 16:14:24 -07004413 for (Thread* thread : threads) {
4414 Dbg::DdmSendThreadNotification(thread, CHUNK_TYPE("THCR"));
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004415 }
4416 }
4417 ResumeVM();
Elliott Hughes47fce012011-10-25 18:37:19 -07004418 }
4419}
4420
Elliott Hughesa2155262011-11-16 16:26:58 -08004421void Dbg::PostThreadStartOrStop(Thread* t, uint32_t type) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07004422 if (IsDebuggerActive()) {
Sebastien Hertz6995c602014-09-09 12:10:13 +02004423 gJdwpState->PostThreadChange(t, type == CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07004424 }
Elliott Hughes82188472011-11-07 18:11:48 -08004425 Dbg::DdmSendThreadNotification(t, type);
Elliott Hughes47fce012011-10-25 18:37:19 -07004426}
4427
4428void Dbg::PostThreadStart(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004429 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07004430}
4431
4432void Dbg::PostThreadDeath(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004433 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THDE"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004434}
4435
Elliott Hughes82188472011-11-07 18:11:48 -08004436void Dbg::DdmSendChunk(uint32_t type, size_t byte_count, const uint8_t* buf) {
Ian Rogersc0542af2014-09-03 16:16:56 -07004437 CHECK(buf != nullptr);
Elliott Hughes3bb81562011-10-21 18:52:59 -07004438 iovec vec[1];
4439 vec[0].iov_base = reinterpret_cast<void*>(const_cast<uint8_t*>(buf));
4440 vec[0].iov_len = byte_count;
4441 Dbg::DdmSendChunkV(type, vec, 1);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004442}
4443
Elliott Hughes21f32d72011-11-09 17:44:13 -08004444void Dbg::DdmSendChunk(uint32_t type, const std::vector<uint8_t>& bytes) {
4445 DdmSendChunk(type, bytes.size(), &bytes[0]);
4446}
4447
Brian Carlstromf5293522013-07-19 00:24:00 -07004448void Dbg::DdmSendChunkV(uint32_t type, const iovec* iov, int iov_count) {
Ian Rogersc0542af2014-09-03 16:16:56 -07004449 if (gJdwpState == nullptr) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08004450 VLOG(jdwp) << "Debugger thread not active, ignoring DDM send: " << type;
Elliott Hughes3bb81562011-10-21 18:52:59 -07004451 } else {
Elliott Hughescccd84f2011-12-05 16:51:54 -08004452 gJdwpState->DdmSendChunkV(type, iov, iov_count);
Elliott Hughes3bb81562011-10-21 18:52:59 -07004453 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004454}
4455
Mathieu Chartierad466ad2015-01-08 16:28:08 -08004456JDWP::JdwpState* Dbg::GetJdwpState() {
4457 return gJdwpState;
4458}
4459
Elliott Hughes767a1472011-10-26 18:49:02 -07004460int Dbg::DdmHandleHpifChunk(HpifWhen when) {
4461 if (when == HPIF_WHEN_NOW) {
Elliott Hughes7162ad92011-10-27 14:08:42 -07004462 DdmSendHeapInfo(when);
Elliott Hughes767a1472011-10-26 18:49:02 -07004463 return true;
4464 }
4465
4466 if (when != HPIF_WHEN_NEVER && when != HPIF_WHEN_NEXT_GC && when != HPIF_WHEN_EVERY_GC) {
4467 LOG(ERROR) << "invalid HpifWhen value: " << static_cast<int>(when);
4468 return false;
4469 }
4470
4471 gDdmHpifWhen = when;
4472 return true;
4473}
4474
4475bool Dbg::DdmHandleHpsgNhsgChunk(Dbg::HpsgWhen when, Dbg::HpsgWhat what, bool native) {
4476 if (when != HPSG_WHEN_NEVER && when != HPSG_WHEN_EVERY_GC) {
4477 LOG(ERROR) << "invalid HpsgWhen value: " << static_cast<int>(when);
4478 return false;
4479 }
4480
4481 if (what != HPSG_WHAT_MERGED_OBJECTS && what != HPSG_WHAT_DISTINCT_OBJECTS) {
4482 LOG(ERROR) << "invalid HpsgWhat value: " << static_cast<int>(what);
4483 return false;
4484 }
4485
4486 if (native) {
4487 gDdmNhsgWhen = when;
4488 gDdmNhsgWhat = what;
4489 } else {
4490 gDdmHpsgWhen = when;
4491 gDdmHpsgWhat = what;
4492 }
4493 return true;
4494}
4495
Elliott Hughes7162ad92011-10-27 14:08:42 -07004496void Dbg::DdmSendHeapInfo(HpifWhen reason) {
4497 // If there's a one-shot 'when', reset it.
4498 if (reason == gDdmHpifWhen) {
4499 if (gDdmHpifWhen == HPIF_WHEN_NEXT_GC) {
4500 gDdmHpifWhen = HPIF_WHEN_NEVER;
4501 }
4502 }
4503
4504 /*
4505 * Chunk HPIF (client --> server)
4506 *
4507 * Heap Info. General information about the heap,
4508 * suitable for a summary display.
4509 *
4510 * [u4]: number of heaps
4511 *
4512 * For each heap:
4513 * [u4]: heap ID
4514 * [u8]: timestamp in ms since Unix epoch
4515 * [u1]: capture reason (same as 'when' value from server)
4516 * [u4]: max heap size in bytes (-Xmx)
4517 * [u4]: current heap size in bytes
4518 * [u4]: current number of bytes allocated
4519 * [u4]: current number of objects allocated
4520 */
4521 uint8_t heap_count = 1;
Ian Rogers1d54e732013-05-02 21:10:01 -07004522 gc::Heap* heap = Runtime::Current()->GetHeap();
Elliott Hughes21f32d72011-11-09 17:44:13 -08004523 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08004524 JDWP::Append4BE(bytes, heap_count);
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004525 JDWP::Append4BE(bytes, 1); // Heap id (bogus; we only have one heap).
Elliott Hughes545a0642011-11-08 19:10:03 -08004526 JDWP::Append8BE(bytes, MilliTime());
4527 JDWP::Append1BE(bytes, reason);
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004528 JDWP::Append4BE(bytes, heap->GetMaxMemory()); // Max allowed heap size in bytes.
4529 JDWP::Append4BE(bytes, heap->GetTotalMemory()); // Current heap size in bytes.
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08004530 JDWP::Append4BE(bytes, heap->GetBytesAllocated());
4531 JDWP::Append4BE(bytes, heap->GetObjectsAllocated());
Elliott Hughes21f32d72011-11-09 17:44:13 -08004532 CHECK_EQ(bytes.size(), 4U + (heap_count * (4 + 8 + 1 + 4 + 4 + 4 + 4)));
4533 Dbg::DdmSendChunk(CHUNK_TYPE("HPIF"), bytes);
Elliott Hughes767a1472011-10-26 18:49:02 -07004534}
4535
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004536enum HpsgSolidity {
4537 SOLIDITY_FREE = 0,
4538 SOLIDITY_HARD = 1,
4539 SOLIDITY_SOFT = 2,
4540 SOLIDITY_WEAK = 3,
4541 SOLIDITY_PHANTOM = 4,
4542 SOLIDITY_FINALIZABLE = 5,
4543 SOLIDITY_SWEEP = 6,
4544};
4545
4546enum HpsgKind {
4547 KIND_OBJECT = 0,
4548 KIND_CLASS_OBJECT = 1,
4549 KIND_ARRAY_1 = 2,
4550 KIND_ARRAY_2 = 3,
4551 KIND_ARRAY_4 = 4,
4552 KIND_ARRAY_8 = 5,
4553 KIND_UNKNOWN = 6,
4554 KIND_NATIVE = 7,
4555};
4556
4557#define HPSG_PARTIAL (1<<7)
4558#define HPSG_STATE(solidity, kind) ((uint8_t)((((kind) & 0x7) << 3) | ((solidity) & 0x7)))
4559
Ian Rogers30fab402012-01-23 15:43:46 -08004560class HeapChunkContext {
4561 public:
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004562 // Maximum chunk size. Obtain this from the formula:
4563 // (((maximum_heap_size / ALLOCATION_UNIT_SIZE) + 255) / 256) * 2
4564 HeapChunkContext(bool merge, bool native)
Ian Rogers30fab402012-01-23 15:43:46 -08004565 : buf_(16384 - 16),
4566 type_(0),
Mathieu Chartier36dab362014-07-30 14:59:56 -07004567 chunk_overhead_(0) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004568 Reset();
4569 if (native) {
Ian Rogers30fab402012-01-23 15:43:46 -08004570 type_ = CHUNK_TYPE("NHSG");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004571 } else {
Ian Rogers30fab402012-01-23 15:43:46 -08004572 type_ = merge ? CHUNK_TYPE("HPSG") : CHUNK_TYPE("HPSO");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004573 }
4574 }
4575
4576 ~HeapChunkContext() {
Ian Rogers30fab402012-01-23 15:43:46 -08004577 if (p_ > &buf_[0]) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004578 Flush();
4579 }
4580 }
4581
Mathieu Chartier36dab362014-07-30 14:59:56 -07004582 void SetChunkOverhead(size_t chunk_overhead) {
4583 chunk_overhead_ = chunk_overhead;
4584 }
4585
4586 void ResetStartOfNextChunk() {
4587 startOfNextMemoryChunk_ = nullptr;
4588 }
4589
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004590 void EnsureHeader(const void* chunk_ptr) {
Ian Rogers30fab402012-01-23 15:43:46 -08004591 if (!needHeader_) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004592 return;
4593 }
4594
4595 // Start a new HPSx chunk.
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004596 JDWP::Write4BE(&p_, 1); // Heap id (bogus; we only have one heap).
4597 JDWP::Write1BE(&p_, 8); // Size of allocation unit, in bytes.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004598
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004599 JDWP::Write4BE(&p_, reinterpret_cast<uintptr_t>(chunk_ptr)); // virtual address of segment start.
4600 JDWP::Write4BE(&p_, 0); // offset of this piece (relative to the virtual address).
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004601 // [u4]: length of piece, in allocation units
4602 // 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 -08004603 pieceLenField_ = p_;
4604 JDWP::Write4BE(&p_, 0x55555555);
4605 needHeader_ = false;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004606 }
4607
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004608 void Flush() REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -07004609 if (pieceLenField_ == nullptr) {
Ian Rogersd636b062013-01-18 17:51:18 -08004610 // Flush immediately post Reset (maybe back-to-back Flush). Ignore.
4611 CHECK(needHeader_);
4612 return;
4613 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004614 // Patch the "length of piece" field.
Ian Rogers30fab402012-01-23 15:43:46 -08004615 CHECK_LE(&buf_[0], pieceLenField_);
4616 CHECK_LE(pieceLenField_, p_);
4617 JDWP::Set4BE(pieceLenField_, totalAllocationUnits_);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004618
Ian Rogers30fab402012-01-23 15:43:46 -08004619 Dbg::DdmSendChunk(type_, p_ - &buf_[0], &buf_[0]);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004620 Reset();
4621 }
4622
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004623 static void HeapChunkJavaCallback(void* start, void* end, size_t used_bytes, void* arg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004624 REQUIRES_SHARED(Locks::heap_bitmap_lock_,
Ian Rogersb726dcb2012-09-05 08:57:23 -07004625 Locks::mutator_lock_) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004626 reinterpret_cast<HeapChunkContext*>(arg)->HeapChunkJavaCallback(start, end, used_bytes);
4627 }
4628
4629 static void HeapChunkNativeCallback(void* start, void* end, size_t used_bytes, void* arg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004630 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004631 reinterpret_cast<HeapChunkContext*>(arg)->HeapChunkNativeCallback(start, end, used_bytes);
Elliott Hughesa2155262011-11-16 16:26:58 -08004632 }
4633
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004634 private:
Elliott Hughesa2155262011-11-16 16:26:58 -08004635 enum { ALLOCATION_UNIT_SIZE = 8 };
4636
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004637 void Reset() {
Ian Rogers30fab402012-01-23 15:43:46 -08004638 p_ = &buf_[0];
Mathieu Chartier36dab362014-07-30 14:59:56 -07004639 ResetStartOfNextChunk();
Ian Rogers30fab402012-01-23 15:43:46 -08004640 totalAllocationUnits_ = 0;
4641 needHeader_ = true;
Ian Rogersc0542af2014-09-03 16:16:56 -07004642 pieceLenField_ = nullptr;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004643 }
4644
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004645 bool IsNative() const {
4646 return type_ == CHUNK_TYPE("NHSG");
4647 }
4648
4649 // Returns true if the object is not an empty chunk.
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004650 bool ProcessRecord(void* start, size_t used_bytes) REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers30fab402012-01-23 15:43:46 -08004651 // Note: heap call backs cannot manipulate the heap upon which they are crawling, care is taken
4652 // in the following code not to allocate memory, by ensuring buf_ is of the correct size
Ian Rogers15bf2d32012-08-28 17:33:04 -07004653 if (used_bytes == 0) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004654 if (start == nullptr) {
4655 // Reset for start of new heap.
4656 startOfNextMemoryChunk_ = nullptr;
4657 Flush();
4658 }
4659 // Only process in use memory so that free region information
4660 // also includes dlmalloc book keeping.
4661 return false;
Elliott Hughesa2155262011-11-16 16:26:58 -08004662 }
Ian Rogersc0542af2014-09-03 16:16:56 -07004663 if (startOfNextMemoryChunk_ != nullptr) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004664 // Transmit any pending free memory. Native free memory of over kMaxFreeLen could be because
4665 // of the use of mmaps, so don't report. If not free memory then start a new segment.
4666 bool flush = true;
4667 if (start > startOfNextMemoryChunk_) {
4668 const size_t kMaxFreeLen = 2 * kPageSize;
4669 void* free_start = startOfNextMemoryChunk_;
4670 void* free_end = start;
4671 const size_t free_len =
4672 reinterpret_cast<uintptr_t>(free_end) - reinterpret_cast<uintptr_t>(free_start);
4673 if (!IsNative() || free_len < kMaxFreeLen) {
4674 AppendChunk(HPSG_STATE(SOLIDITY_FREE, 0), free_start, free_len, IsNative());
4675 flush = false;
Ian Rogers15bf2d32012-08-28 17:33:04 -07004676 }
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004677 }
4678 if (flush) {
4679 startOfNextMemoryChunk_ = nullptr;
4680 Flush();
4681 }
Ian Rogers15bf2d32012-08-28 17:33:04 -07004682 }
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004683 return true;
Ian Rogers15bf2d32012-08-28 17:33:04 -07004684 }
Elliott Hughesa2155262011-11-16 16:26:58 -08004685
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004686 void HeapChunkNativeCallback(void* start, void* /*end*/, size_t used_bytes)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004687 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004688 if (ProcessRecord(start, used_bytes)) {
4689 uint8_t state = ExamineNativeObject(start);
4690 AppendChunk(state, start, used_bytes + chunk_overhead_, true /*is_native*/);
4691 startOfNextMemoryChunk_ = reinterpret_cast<char*>(start) + used_bytes + chunk_overhead_;
4692 }
4693 }
4694
4695 void HeapChunkJavaCallback(void* start, void* /*end*/, size_t used_bytes)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004696 REQUIRES_SHARED(Locks::heap_bitmap_lock_, Locks::mutator_lock_) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004697 if (ProcessRecord(start, used_bytes)) {
4698 // Determine the type of this chunk.
4699 // OLD-TODO: if context.merge, see if this chunk is different from the last chunk.
4700 // If it's the same, we should combine them.
4701 uint8_t state = ExamineJavaObject(reinterpret_cast<mirror::Object*>(start));
4702 AppendChunk(state, start, used_bytes + chunk_overhead_, false /*is_native*/);
4703 startOfNextMemoryChunk_ = reinterpret_cast<char*>(start) + used_bytes + chunk_overhead_;
4704 }
4705 }
4706
4707 void AppendChunk(uint8_t state, void* ptr, size_t length, bool is_native)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004708 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07004709 // Make sure there's enough room left in the buffer.
4710 // We need to use two bytes for every fractional 256 allocation units used by the chunk plus
4711 // 17 bytes for any header.
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004712 const size_t needed = ((RoundUp(length / ALLOCATION_UNIT_SIZE, 256) / 256) * 2) + 17;
4713 size_t byte_left = &buf_.back() - p_;
4714 if (byte_left < needed) {
4715 if (is_native) {
Pavel Vyssotski7522c742014-12-08 13:38:26 +06004716 // Cannot trigger memory allocation while walking native heap.
Pavel Vyssotski7522c742014-12-08 13:38:26 +06004717 return;
4718 }
Ian Rogers15bf2d32012-08-28 17:33:04 -07004719 Flush();
4720 }
4721
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004722 byte_left = &buf_.back() - p_;
4723 if (byte_left < needed) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07004724 LOG(WARNING) << "Chunk is too big to transmit (chunk_len=" << length << ", "
4725 << needed << " bytes)";
4726 return;
4727 }
4728 EnsureHeader(ptr);
Elliott Hughesa2155262011-11-16 16:26:58 -08004729 // Write out the chunk description.
Ian Rogers15bf2d32012-08-28 17:33:04 -07004730 length /= ALLOCATION_UNIT_SIZE; // Convert to allocation units.
4731 totalAllocationUnits_ += length;
4732 while (length > 256) {
Ian Rogers30fab402012-01-23 15:43:46 -08004733 *p_++ = state | HPSG_PARTIAL;
4734 *p_++ = 255; // length - 1
Ian Rogers15bf2d32012-08-28 17:33:04 -07004735 length -= 256;
Elliott Hughesa2155262011-11-16 16:26:58 -08004736 }
Ian Rogers30fab402012-01-23 15:43:46 -08004737 *p_++ = state;
Ian Rogers15bf2d32012-08-28 17:33:04 -07004738 *p_++ = length - 1;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004739 }
4740
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004741 uint8_t ExamineNativeObject(const void* p) REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004742 return p == nullptr ? HPSG_STATE(SOLIDITY_FREE, 0) : HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
4743 }
4744
4745 uint8_t ExamineJavaObject(mirror::Object* o)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004746 REQUIRES_SHARED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -07004747 if (o == nullptr) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004748 return HPSG_STATE(SOLIDITY_FREE, 0);
4749 }
Elliott Hughesa2155262011-11-16 16:26:58 -08004750 // It's an allocated chunk. Figure out what it is.
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004751 gc::Heap* heap = Runtime::Current()->GetHeap();
4752 if (!heap->IsLiveObjectLocked(o)) {
4753 LOG(ERROR) << "Invalid object in managed heap: " << o;
Elliott Hughesa2155262011-11-16 16:26:58 -08004754 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
4755 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004756 mirror::Class* c = o->GetClass();
Ian Rogersc0542af2014-09-03 16:16:56 -07004757 if (c == nullptr) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004758 // The object was probably just created but hasn't been initialized yet.
4759 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
4760 }
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004761 if (!heap->IsValidObjectAddress(c)) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07004762 LOG(ERROR) << "Invalid class for managed heap object: " << o << " " << c;
Elliott Hughesa2155262011-11-16 16:26:58 -08004763 return HPSG_STATE(SOLIDITY_HARD, KIND_UNKNOWN);
4764 }
Mathieu Chartierf26e1b32015-01-29 10:47:10 -08004765 if (c->GetClass() == nullptr) {
4766 LOG(ERROR) << "Null class of class " << c << " for object " << o;
4767 return HPSG_STATE(SOLIDITY_HARD, KIND_UNKNOWN);
4768 }
Elliott Hughesa2155262011-11-16 16:26:58 -08004769 if (c->IsClassClass()) {
4770 return HPSG_STATE(SOLIDITY_HARD, KIND_CLASS_OBJECT);
4771 }
Elliott Hughesa2155262011-11-16 16:26:58 -08004772 if (c->IsArrayClass()) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004773 switch (c->GetComponentSize()) {
4774 case 1: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_1);
4775 case 2: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_2);
4776 case 4: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
4777 case 8: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_8);
4778 }
4779 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004780 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
4781 }
4782
Ian Rogers30fab402012-01-23 15:43:46 -08004783 std::vector<uint8_t> buf_;
4784 uint8_t* p_;
4785 uint8_t* pieceLenField_;
Ian Rogers15bf2d32012-08-28 17:33:04 -07004786 void* startOfNextMemoryChunk_;
Ian Rogers30fab402012-01-23 15:43:46 -08004787 size_t totalAllocationUnits_;
4788 uint32_t type_;
Ian Rogers30fab402012-01-23 15:43:46 -08004789 bool needHeader_;
Mathieu Chartier36dab362014-07-30 14:59:56 -07004790 size_t chunk_overhead_;
Ian Rogers30fab402012-01-23 15:43:46 -08004791
Elliott Hughesa2155262011-11-16 16:26:58 -08004792 DISALLOW_COPY_AND_ASSIGN(HeapChunkContext);
4793};
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004794
Mathieu Chartier36dab362014-07-30 14:59:56 -07004795static void BumpPointerSpaceCallback(mirror::Object* obj, void* arg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004796 REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
Mathieu Chartier36dab362014-07-30 14:59:56 -07004797 const size_t size = RoundUp(obj->SizeOf(), kObjectAlignment);
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004798 HeapChunkContext::HeapChunkJavaCallback(
Mathieu Chartier36dab362014-07-30 14:59:56 -07004799 obj, reinterpret_cast<void*>(reinterpret_cast<uintptr_t>(obj) + size), size, arg);
4800}
4801
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004802void Dbg::DdmSendHeapSegments(bool native) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004803 Dbg::HpsgWhen when = native ? gDdmNhsgWhen : gDdmHpsgWhen;
4804 Dbg::HpsgWhat what = native ? gDdmNhsgWhat : gDdmHpsgWhat;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004805 if (when == HPSG_WHEN_NEVER) {
4806 return;
4807 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004808 // Figure out what kind of chunks we'll be sending.
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004809 CHECK(what == HPSG_WHAT_MERGED_OBJECTS || what == HPSG_WHAT_DISTINCT_OBJECTS)
4810 << static_cast<int>(what);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004811
4812 // First, send a heap start chunk.
4813 uint8_t heap_id[4];
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004814 JDWP::Set4BE(&heap_id[0], 1); // Heap id (bogus; we only have one heap).
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004815 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHST") : CHUNK_TYPE("HPST"), sizeof(heap_id), heap_id);
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07004816 Thread* self = Thread::Current();
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07004817 Locks::mutator_lock_->AssertSharedHeld(self);
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07004818
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004819 // Send a series of heap segment chunks.
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004820 HeapChunkContext context(what == HPSG_WHAT_MERGED_OBJECTS, native);
Elliott Hughesa2155262011-11-16 16:26:58 -08004821 if (native) {
Dimitry Ivanove6465bc2015-12-14 18:55:02 -08004822 UNIMPLEMENTED(WARNING) << "Native heap inspection is not supported";
Elliott Hughesa2155262011-11-16 16:26:58 -08004823 } else {
Ian Rogers1d54e732013-05-02 21:10:01 -07004824 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartier36dab362014-07-30 14:59:56 -07004825 for (const auto& space : heap->GetContinuousSpaces()) {
4826 if (space->IsDlMallocSpace()) {
Mathieu Chartier4c69d7f2014-10-10 12:45:50 -07004827 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004828 // dlmalloc's chunk header is 2 * sizeof(size_t), but if the previous chunk is in use for an
4829 // allocation then the first sizeof(size_t) may belong to it.
4830 context.SetChunkOverhead(sizeof(size_t));
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004831 space->AsDlMallocSpace()->Walk(HeapChunkContext::HeapChunkJavaCallback, &context);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004832 } else if (space->IsRosAllocSpace()) {
4833 context.SetChunkOverhead(0);
Mathieu Chartier4c69d7f2014-10-10 12:45:50 -07004834 // Need to acquire the mutator lock before the heap bitmap lock with exclusive access since
4835 // RosAlloc's internal logic doesn't know to release and reacquire the heap bitmap lock.
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07004836 ScopedThreadSuspension sts(self, kSuspended);
Mathieu Chartier4f55e222015-09-04 13:26:21 -07004837 ScopedSuspendAll ssa(__FUNCTION__);
4838 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
4839 space->AsRosAllocSpace()->Walk(HeapChunkContext::HeapChunkJavaCallback, &context);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004840 } else if (space->IsBumpPointerSpace()) {
Mathieu Chartier4c69d7f2014-10-10 12:45:50 -07004841 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004842 context.SetChunkOverhead(0);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004843 space->AsBumpPointerSpace()->Walk(BumpPointerSpaceCallback, &context);
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004844 HeapChunkContext::HeapChunkJavaCallback(nullptr, nullptr, 0, &context);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08004845 } else if (space->IsRegionSpace()) {
4846 heap->IncrementDisableMovingGC(self);
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07004847 {
4848 ScopedThreadSuspension sts(self, kSuspended);
Mathieu Chartier4f55e222015-09-04 13:26:21 -07004849 ScopedSuspendAll ssa(__FUNCTION__);
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07004850 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
4851 context.SetChunkOverhead(0);
4852 space->AsRegionSpace()->Walk(BumpPointerSpaceCallback, &context);
4853 HeapChunkContext::HeapChunkJavaCallback(nullptr, nullptr, 0, &context);
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07004854 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08004855 heap->DecrementDisableMovingGC(self);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004856 } else {
4857 UNIMPLEMENTED(WARNING) << "Not counting objects in space " << *space;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07004858 }
Mathieu Chartier36dab362014-07-30 14:59:56 -07004859 context.ResetStartOfNextChunk();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07004860 }
Mathieu Chartier4c69d7f2014-10-10 12:45:50 -07004861 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07004862 // Walk the large objects, these are not in the AllocSpace.
Mathieu Chartier36dab362014-07-30 14:59:56 -07004863 context.SetChunkOverhead(0);
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004864 heap->GetLargeObjectsSpace()->Walk(HeapChunkContext::HeapChunkJavaCallback, &context);
Elliott Hughesa2155262011-11-16 16:26:58 -08004865 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004866
4867 // Finally, send a heap end chunk.
4868 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHEN") : CHUNK_TYPE("HPEN"), sizeof(heap_id), heap_id);
Elliott Hughes767a1472011-10-26 18:49:02 -07004869}
4870
Brian Carlstrom306db812014-09-05 13:01:41 -07004871void Dbg::SetAllocTrackingEnabled(bool enable) {
Man Cao8c2ff642015-05-27 17:25:30 -07004872 gc::AllocRecordObjectMap::SetAllocTrackingEnabled(enable);
Elliott Hughes545a0642011-11-08 19:10:03 -08004873}
4874
4875void Dbg::DumpRecentAllocations() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004876 ScopedObjectAccess soa(Thread::Current());
Brian Carlstrom306db812014-09-05 13:01:41 -07004877 MutexLock mu(soa.Self(), *Locks::alloc_tracker_lock_);
Man Cao8c2ff642015-05-27 17:25:30 -07004878 if (!Runtime::Current()->GetHeap()->IsAllocTrackingEnabled()) {
Elliott Hughes545a0642011-11-08 19:10:03 -08004879 LOG(INFO) << "Not recording tracked allocations";
4880 return;
4881 }
Man Cao8c2ff642015-05-27 17:25:30 -07004882 gc::AllocRecordObjectMap* records = Runtime::Current()->GetHeap()->GetAllocationRecords();
4883 CHECK(records != nullptr);
Elliott Hughes545a0642011-11-08 19:10:03 -08004884
Man Cao1ed11b92015-06-11 22:47:35 -07004885 const uint16_t capped_count = CappedAllocRecordCount(records->GetRecentAllocationSize());
Brian Carlstrom306db812014-09-05 13:01:41 -07004886 uint16_t count = capped_count;
Elliott Hughes545a0642011-11-08 19:10:03 -08004887
Man Cao8c2ff642015-05-27 17:25:30 -07004888 LOG(INFO) << "Tracked allocations, (count=" << count << ")";
4889 for (auto it = records->RBegin(), end = records->REnd();
4890 count > 0 && it != end; count--, it++) {
Mathieu Chartier458b1052016-03-29 14:02:55 -07004891 const gc::AllocRecord* record = &it->second;
Elliott Hughes545a0642011-11-08 19:10:03 -08004892
Man Cao8c2ff642015-05-27 17:25:30 -07004893 LOG(INFO) << StringPrintf(" Thread %-2d %6zd bytes ", record->GetTid(), record->ByteCount())
David Sehr709b0702016-10-13 09:12:37 -07004894 << mirror::Class::PrettyClass(record->GetClass());
Elliott Hughes545a0642011-11-08 19:10:03 -08004895
Man Cao8c2ff642015-05-27 17:25:30 -07004896 for (size_t stack_frame = 0, depth = record->GetDepth(); stack_frame < depth; ++stack_frame) {
4897 const gc::AllocRecordStackTraceElement& stack_element = record->StackElement(stack_frame);
4898 ArtMethod* m = stack_element.GetMethod();
David Sehr709b0702016-10-13 09:12:37 -07004899 LOG(INFO) << " " << ArtMethod::PrettyMethod(m) << " line "
4900 << stack_element.ComputeLineNumber();
Elliott Hughes545a0642011-11-08 19:10:03 -08004901 }
4902
4903 // pause periodically to help logcat catch up
4904 if ((count % 5) == 0) {
4905 usleep(40000);
4906 }
Elliott Hughes545a0642011-11-08 19:10:03 -08004907 }
4908}
4909
4910class StringTable {
4911 public:
4912 StringTable() {
4913 }
4914
Mathieu Chartier4345c462014-06-27 10:20:14 -07004915 void Add(const std::string& str) {
4916 table_.insert(str);
4917 }
4918
4919 void Add(const char* str) {
4920 table_.insert(str);
Elliott Hughes545a0642011-11-08 19:10:03 -08004921 }
4922
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004923 size_t IndexOf(const char* s) const {
Mathieu Chartier02e25112013-08-14 16:14:24 -07004924 auto it = table_.find(s);
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004925 if (it == table_.end()) {
4926 LOG(FATAL) << "IndexOf(\"" << s << "\") failed";
4927 }
4928 return std::distance(table_.begin(), it);
Elliott Hughes545a0642011-11-08 19:10:03 -08004929 }
4930
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004931 size_t Size() const {
Elliott Hughes545a0642011-11-08 19:10:03 -08004932 return table_.size();
4933 }
4934
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004935 void WriteTo(std::vector<uint8_t>& bytes) const {
Mathieu Chartier02e25112013-08-14 16:14:24 -07004936 for (const std::string& str : table_) {
4937 const char* s = str.c_str();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004938 size_t s_len = CountModifiedUtf8Chars(s);
Christopher Ferris8a354052015-04-24 17:23:53 -07004939 std::unique_ptr<uint16_t[]> s_utf16(new uint16_t[s_len]);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004940 ConvertModifiedUtf8ToUtf16(s_utf16.get(), s);
4941 JDWP::AppendUtf16BE(bytes, s_utf16.get(), s_len);
Elliott Hughes545a0642011-11-08 19:10:03 -08004942 }
4943 }
4944
4945 private:
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004946 std::set<std::string> table_;
Elliott Hughes545a0642011-11-08 19:10:03 -08004947 DISALLOW_COPY_AND_ASSIGN(StringTable);
4948};
4949
Mathieu Chartiere401d142015-04-22 13:56:20 -07004950static const char* GetMethodSourceFile(ArtMethod* method)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004951 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004952 DCHECK(method != nullptr);
4953 const char* source_file = method->GetDeclaringClassSourceFile();
Sebastien Hertz280286a2014-04-28 09:26:50 +02004954 return (source_file != nullptr) ? source_file : "";
4955}
4956
Elliott Hughes545a0642011-11-08 19:10:03 -08004957/*
4958 * The data we send to DDMS contains everything we have recorded.
4959 *
4960 * Message header (all values big-endian):
4961 * (1b) message header len (to allow future expansion); includes itself
4962 * (1b) entry header len
4963 * (1b) stack frame len
4964 * (2b) number of entries
4965 * (4b) offset to string table from start of message
4966 * (2b) number of class name strings
4967 * (2b) number of method name strings
4968 * (2b) number of source file name strings
4969 * For each entry:
4970 * (4b) total allocation size
Elliott Hughes221229c2013-01-08 18:17:50 -08004971 * (2b) thread id
Elliott Hughes545a0642011-11-08 19:10:03 -08004972 * (2b) allocated object's class name index
4973 * (1b) stack depth
4974 * For each stack frame:
4975 * (2b) method's class name
4976 * (2b) method name
4977 * (2b) method source file
4978 * (2b) line number, clipped to 32767; -2 if native; -1 if no source
4979 * (xb) class name strings
4980 * (xb) method name strings
4981 * (xb) source file strings
4982 *
4983 * As with other DDM traffic, strings are sent as a 4-byte length
4984 * followed by UTF-16 data.
4985 *
4986 * We send up 16-bit unsigned indexes into string tables. In theory there
Brian Carlstrom306db812014-09-05 13:01:41 -07004987 * can be (kMaxAllocRecordStackDepth * alloc_record_max_) unique strings in
Elliott Hughes545a0642011-11-08 19:10:03 -08004988 * each table, but in practice there should be far fewer.
4989 *
4990 * The chief reason for using a string table here is to keep the size of
4991 * the DDMS message to a minimum. This is partly to make the protocol
4992 * efficient, but also because we have to form the whole thing up all at
4993 * once in a memory buffer.
4994 *
4995 * We use separate string tables for class names, method names, and source
4996 * files to keep the indexes small. There will generally be no overlap
4997 * between the contents of these tables.
4998 */
4999jbyteArray Dbg::GetRecentAllocations() {
Ian Rogerscf7f1912014-10-22 22:06:39 -07005000 if ((false)) {
Elliott Hughes545a0642011-11-08 19:10:03 -08005001 DumpRecentAllocations();
5002 }
5003
Ian Rogers50b35e22012-10-04 10:09:15 -07005004 Thread* self = Thread::Current();
Elliott Hughes545a0642011-11-08 19:10:03 -08005005 std::vector<uint8_t> bytes;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005006 {
Brian Carlstrom306db812014-09-05 13:01:41 -07005007 MutexLock mu(self, *Locks::alloc_tracker_lock_);
Man Cao8c2ff642015-05-27 17:25:30 -07005008 gc::AllocRecordObjectMap* records = Runtime::Current()->GetHeap()->GetAllocationRecords();
5009 // In case this method is called when allocation tracker is disabled,
5010 // we should still send some data back.
5011 gc::AllocRecordObjectMap dummy;
5012 if (records == nullptr) {
5013 CHECK(!Runtime::Current()->GetHeap()->IsAllocTrackingEnabled());
5014 records = &dummy;
5015 }
Man Cao41656de2015-07-06 18:53:15 -07005016 // We don't need to wait on the condition variable records->new_record_condition_, because this
5017 // function only reads the class objects, which are already marked so it doesn't change their
5018 // reachability.
Man Cao8c2ff642015-05-27 17:25:30 -07005019
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005020 //
5021 // Part 1: generate string tables.
5022 //
5023 StringTable class_names;
5024 StringTable method_names;
5025 StringTable filenames;
Elliott Hughes545a0642011-11-08 19:10:03 -08005026
Man Cao1ed11b92015-06-11 22:47:35 -07005027 const uint16_t capped_count = CappedAllocRecordCount(records->GetRecentAllocationSize());
Brian Carlstrom306db812014-09-05 13:01:41 -07005028 uint16_t count = capped_count;
Man Cao8c2ff642015-05-27 17:25:30 -07005029 for (auto it = records->RBegin(), end = records->REnd();
5030 count > 0 && it != end; count--, it++) {
Mathieu Chartier458b1052016-03-29 14:02:55 -07005031 const gc::AllocRecord* record = &it->second;
Ian Rogers1ff3c982014-08-12 02:30:58 -07005032 std::string temp;
Man Cao41656de2015-07-06 18:53:15 -07005033 class_names.Add(record->GetClassDescriptor(&temp));
Man Cao8c2ff642015-05-27 17:25:30 -07005034 for (size_t i = 0, depth = record->GetDepth(); i < depth; i++) {
5035 ArtMethod* m = record->StackElement(i).GetMethod();
5036 class_names.Add(m->GetDeclaringClassDescriptor());
5037 method_names.Add(m->GetName());
5038 filenames.Add(GetMethodSourceFile(m));
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005039 }
Elliott Hughes545a0642011-11-08 19:10:03 -08005040 }
5041
Man Cao8c2ff642015-05-27 17:25:30 -07005042 LOG(INFO) << "recent allocation records: " << capped_count;
5043 LOG(INFO) << "allocation records all objects: " << records->Size();
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005044
5045 //
5046 // Part 2: Generate the output and store it in the buffer.
5047 //
5048
5049 // (1b) message header len (to allow future expansion); includes itself
5050 // (1b) entry header len
5051 // (1b) stack frame len
5052 const int kMessageHeaderLen = 15;
5053 const int kEntryHeaderLen = 9;
5054 const int kStackFrameLen = 8;
5055 JDWP::Append1BE(bytes, kMessageHeaderLen);
5056 JDWP::Append1BE(bytes, kEntryHeaderLen);
5057 JDWP::Append1BE(bytes, kStackFrameLen);
5058
5059 // (2b) number of entries
5060 // (4b) offset to string table from start of message
5061 // (2b) number of class name strings
5062 // (2b) number of method name strings
5063 // (2b) number of source file name strings
Brian Carlstrom306db812014-09-05 13:01:41 -07005064 JDWP::Append2BE(bytes, capped_count);
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005065 size_t string_table_offset = bytes.size();
Brian Carlstrom7934ac22013-07-26 10:54:15 -07005066 JDWP::Append4BE(bytes, 0); // We'll patch this later...
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005067 JDWP::Append2BE(bytes, class_names.Size());
5068 JDWP::Append2BE(bytes, method_names.Size());
5069 JDWP::Append2BE(bytes, filenames.Size());
5070
Ian Rogers1ff3c982014-08-12 02:30:58 -07005071 std::string temp;
Man Cao8c2ff642015-05-27 17:25:30 -07005072 count = capped_count;
5073 // The last "count" number of allocation records in "records" are the most recent "count" number
5074 // of allocations. Reverse iterate to get them. The most recent allocation is sent first.
5075 for (auto it = records->RBegin(), end = records->REnd();
5076 count > 0 && it != end; count--, it++) {
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005077 // For each entry:
5078 // (4b) total allocation size
5079 // (2b) thread id
5080 // (2b) allocated object's class name index
5081 // (1b) stack depth
Mathieu Chartier458b1052016-03-29 14:02:55 -07005082 const gc::AllocRecord* record = &it->second;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005083 size_t stack_depth = record->GetDepth();
Mathieu Chartierf8322842014-05-16 10:59:25 -07005084 size_t allocated_object_class_name_index =
Man Cao41656de2015-07-06 18:53:15 -07005085 class_names.IndexOf(record->GetClassDescriptor(&temp));
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07005086 JDWP::Append4BE(bytes, record->ByteCount());
Man Cao8c2ff642015-05-27 17:25:30 -07005087 JDWP::Append2BE(bytes, static_cast<uint16_t>(record->GetTid()));
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005088 JDWP::Append2BE(bytes, allocated_object_class_name_index);
5089 JDWP::Append1BE(bytes, stack_depth);
5090
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005091 for (size_t stack_frame = 0; stack_frame < stack_depth; ++stack_frame) {
5092 // For each stack frame:
5093 // (2b) method's class name
5094 // (2b) method name
5095 // (2b) method source file
5096 // (2b) line number, clipped to 32767; -2 if native; -1 if no source
Man Cao8c2ff642015-05-27 17:25:30 -07005097 ArtMethod* m = record->StackElement(stack_frame).GetMethod();
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07005098 size_t class_name_index = class_names.IndexOf(m->GetDeclaringClassDescriptor());
5099 size_t method_name_index = method_names.IndexOf(m->GetName());
5100 size_t file_name_index = filenames.IndexOf(GetMethodSourceFile(m));
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005101 JDWP::Append2BE(bytes, class_name_index);
5102 JDWP::Append2BE(bytes, method_name_index);
5103 JDWP::Append2BE(bytes, file_name_index);
Man Cao8c2ff642015-05-27 17:25:30 -07005104 JDWP::Append2BE(bytes, record->StackElement(stack_frame).ComputeLineNumber());
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005105 }
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005106 }
5107
5108 // (xb) class name strings
5109 // (xb) method name strings
5110 // (xb) source file strings
5111 JDWP::Set4BE(&bytes[string_table_offset], bytes.size());
5112 class_names.WriteTo(bytes);
5113 method_names.WriteTo(bytes);
5114 filenames.WriteTo(bytes);
Elliott Hughes545a0642011-11-08 19:10:03 -08005115 }
Ian Rogers50b35e22012-10-04 10:09:15 -07005116 JNIEnv* env = self->GetJniEnv();
Elliott Hughes545a0642011-11-08 19:10:03 -08005117 jbyteArray result = env->NewByteArray(bytes.size());
Ian Rogersc0542af2014-09-03 16:16:56 -07005118 if (result != nullptr) {
Elliott Hughes545a0642011-11-08 19:10:03 -08005119 env->SetByteArrayRegion(result, 0, bytes.size(), reinterpret_cast<const jbyte*>(&bytes[0]));
5120 }
5121 return result;
5122}
5123
Mathieu Chartiere401d142015-04-22 13:56:20 -07005124ArtMethod* DeoptimizationRequest::Method() const {
Andreas Gampe13b27842016-11-07 16:48:23 -08005125 return jni::DecodeArtMethod(method_);
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07005126}
5127
Mathieu Chartiere401d142015-04-22 13:56:20 -07005128void DeoptimizationRequest::SetMethod(ArtMethod* m) {
Andreas Gampe13b27842016-11-07 16:48:23 -08005129 method_ = jni::EncodeArtMethod(m);
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07005130}
5131
Mathieu Chartiera6b1ead2015-10-06 10:32:38 -07005132void Dbg::VisitRoots(RootVisitor* visitor) {
5133 // Visit breakpoint roots, used to prevent unloading of methods with breakpoints.
5134 ReaderMutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
5135 BufferedRootVisitor<128> root_visitor(visitor, RootInfo(kRootVMInternal));
5136 for (Breakpoint& breakpoint : gBreakpoints) {
Andreas Gampe542451c2016-07-26 09:02:02 -07005137 breakpoint.Method()->VisitRoots(root_visitor, kRuntimePointerSize);
Mathieu Chartiera6b1ead2015-10-06 10:32:38 -07005138 }
5139}
5140
Andreas Gampe04bbb5b2017-01-19 17:49:03 +00005141void Dbg::DbgThreadLifecycleCallback::ThreadStart(Thread* self) {
5142 Dbg::PostThreadStart(self);
5143}
5144
5145void Dbg::DbgThreadLifecycleCallback::ThreadDeath(Thread* self) {
5146 Dbg::PostThreadDeath(self);
5147}
5148
Andreas Gampe0f01b582017-01-18 15:22:37 -08005149void Dbg::DbgClassLoadCallback::ClassLoad(Handle<mirror::Class> klass ATTRIBUTE_UNUSED) {
5150 // Ignore ClassLoad;
5151}
5152void Dbg::DbgClassLoadCallback::ClassPrepare(Handle<mirror::Class> temp_klass ATTRIBUTE_UNUSED,
5153 Handle<mirror::Class> klass) {
5154 Dbg::PostClassPrepare(klass.Get());
5155}
5156
Elliott Hughes872d4ec2011-10-21 17:07:15 -07005157} // namespace art