blob: 5a87ae8420a911e2a17ef88223816c8c17d4021b [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
Andreas Gampef774a4e2017-07-06 22:15:18 -070021#include <memory>
Elliott Hughes545a0642011-11-08 19:10:03 -080022#include <set>
Andreas Gampef774a4e2017-07-06 22:15:18 -070023#include <vector>
Elliott Hughes545a0642011-11-08 19:10:03 -080024
Andreas Gampe46ee31b2016-12-14 10:11:49 -080025#include "android-base/stringprintf.h"
26
Ian Rogers166db042013-07-26 12:05:57 -070027#include "arch/context.h"
Mathieu Chartierc7853442015-03-27 14:35:38 -070028#include "art_field-inl.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070029#include "art_method-inl.h"
Andreas Gampe542451c2016-07-26 09:02:02 -070030#include "base/enums.h"
Andreas Gampef774a4e2017-07-06 22:15:18 -070031#include "base/strlcpy.h"
Vladimir Marko80afd022015-05-19 18:08:00 +010032#include "base/time_utils.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080033#include "class_linker-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -070034#include "class_linker.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070035#include "dex_file-inl.h"
David Sehr9323e6e2016-09-13 08:58:35 -070036#include "dex_file_annotations.h"
Ian Rogers776ac1f2012-04-13 23:36:36 -070037#include "dex_instruction.h"
Mingyao Yang6ea1a0e2016-01-29 12:12:49 -080038#include "entrypoints/runtime_asm_entrypoints.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070039#include "gc/accounting/card_table-inl.h"
Man Cao8c2ff642015-05-27 17:25:30 -070040#include "gc/allocation_record.h"
Mathieu Chartieraa516822015-10-02 15:53:37 -070041#include "gc/scoped_gc_critical_section.h"
Andreas Gampe0c183382017-07-13 22:26:24 -070042#include "gc/space/bump_pointer_space-walk-inl.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070043#include "gc/space/large_object_space.h"
44#include "gc/space/space-inl.h"
Andreas Gampe513061a2017-06-01 09:17:34 -070045#include "handle_scope-inl.h"
Sebastien Hertzcbc50642015-06-01 17:33:12 +020046#include "jdwp/jdwp_priv.h"
Elliott Hughes64f574f2013-02-20 14:57:12 -080047#include "jdwp/object_registry.h"
Andreas Gampe13b27842016-11-07 16:48:23 -080048#include "jni_internal.h"
Mathieu Chartier28bd2e42016-10-04 13:54:57 -070049#include "jvalue-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080050#include "mirror/class-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -070051#include "mirror/class.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080052#include "mirror/class_loader.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080053#include "mirror/object-inl.h"
54#include "mirror/object_array-inl.h"
Ian Rogersb0fa5dc2014-04-28 16:47:08 -070055#include "mirror/string-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080056#include "mirror/throwable.h"
Steven Morelande431e272017-07-18 16:53:49 -070057#include "nativehelper/ScopedLocalRef.h"
58#include "nativehelper/ScopedPrimitiveArray.h"
Mathieu Chartier3398c782016-09-30 10:27:43 -070059#include "obj_ptr-inl.h"
Ian Rogers53b8b092014-03-13 23:45:53 -070060#include "reflection.h"
Elliott Hughesa0e18062012-04-13 15:59:59 -070061#include "safe_map.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070062#include "scoped_thread_state_change-inl.h"
Andreas Gampe513061a2017-06-01 09:17:34 -070063#include "stack.h"
Elliott Hughes475fc232011-10-25 15:00:35 -070064#include "thread_list.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080065#include "utf.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070066#include "well_known_classes.h"
Elliott Hughes475fc232011-10-25 15:00:35 -070067
Elliott Hughes872d4ec2011-10-21 17:07:15 -070068namespace art {
69
Andreas Gampe46ee31b2016-12-14 10:11:49 -080070using android::base::StringPrintf;
71
Sebastien Hertz0462c4c2015-04-01 16:34:17 +020072// The key identifying the debugger to update instrumentation.
73static constexpr const char* kDbgInstrumentationKey = "Debugger";
74
Man Cao8c2ff642015-05-27 17:25:30 -070075// 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 -070076static uint16_t CappedAllocRecordCount(size_t alloc_record_count) {
Man Cao1ed11b92015-06-11 22:47:35 -070077 const size_t cap = 0xffff;
Man Cao8c2ff642015-05-27 17:25:30 -070078 if (alloc_record_count > cap) {
79 return cap;
Brian Carlstrom306db812014-09-05 13:01:41 -070080 }
81 return alloc_record_count;
82}
Elliott Hughes475fc232011-10-25 15:00:35 -070083
Mathieu Chartier41af5e52015-10-28 11:10:46 -070084class Breakpoint : public ValueObject {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -070085 public:
Mathieu Chartier41af5e52015-10-28 11:10:46 -070086 Breakpoint(ArtMethod* method, uint32_t dex_pc, DeoptimizationRequest::Kind deoptimization_kind)
Alex Light97e78032017-06-27 17:51:55 -070087 : method_(method->GetCanonicalMethod(kRuntimePointerSize)),
Mathieu Chartier41af5e52015-10-28 11:10:46 -070088 dex_pc_(dex_pc),
89 deoptimization_kind_(deoptimization_kind) {
Sebastien Hertzf3928792014-11-17 19:00:37 +010090 CHECK(deoptimization_kind_ == DeoptimizationRequest::kNothing ||
91 deoptimization_kind_ == DeoptimizationRequest::kSelectiveDeoptimization ||
92 deoptimization_kind_ == DeoptimizationRequest::kFullDeoptimization);
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -070093 }
94
Andreas Gampebdf7f1c2016-08-30 16:38:47 -070095 Breakpoint(const Breakpoint& other) REQUIRES_SHARED(Locks::mutator_lock_)
Mathieu Chartier41af5e52015-10-28 11:10:46 -070096 : method_(other.method_),
97 dex_pc_(other.dex_pc_),
98 deoptimization_kind_(other.deoptimization_kind_) {}
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -070099
Mathieu Chartier41af5e52015-10-28 11:10:46 -0700100 // Method() is called from root visiting, do not use ScopedObjectAccess here or it can cause
101 // GC to deadlock if another thread tries to call SuspendAll while the GC is in a runnable state.
102 ArtMethod* Method() const {
103 return method_;
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700104 }
105
106 uint32_t DexPc() const {
107 return dex_pc_;
108 }
109
Sebastien Hertzf3928792014-11-17 19:00:37 +0100110 DeoptimizationRequest::Kind GetDeoptimizationKind() const {
111 return deoptimization_kind_;
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700112 }
113
Alex Light6c8467f2015-11-20 15:03:26 -0800114 // Returns true if the method of this breakpoint and the passed in method should be considered the
115 // same. That is, they are either the same method or they are copied from the same method.
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700116 bool IsInMethod(ArtMethod* m) const REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light97e78032017-06-27 17:51:55 -0700117 return method_ == m->GetCanonicalMethod(kRuntimePointerSize);
Alex Light6c8467f2015-11-20 15:03:26 -0800118 }
119
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700120 private:
Sebastien Hertza76a6d42014-03-20 16:40:17 +0100121 // The location of this breakpoint.
Mathieu Chartier41af5e52015-10-28 11:10:46 -0700122 ArtMethod* method_;
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700123 uint32_t dex_pc_;
Sebastien Hertza76a6d42014-03-20 16:40:17 +0100124
125 // Indicates whether breakpoint needs full deoptimization or selective deoptimization.
Sebastien Hertzf3928792014-11-17 19:00:37 +0100126 DeoptimizationRequest::Kind deoptimization_kind_;
Elliott Hughes86964332012-02-15 19:37:42 -0800127};
128
Sebastien Hertzed2be172014-08-19 15:33:43 +0200129static std::ostream& operator<<(std::ostream& os, const Breakpoint& rhs)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700130 REQUIRES_SHARED(Locks::mutator_lock_) {
David Sehr709b0702016-10-13 09:12:37 -0700131 os << StringPrintf("Breakpoint[%s @%#x]", ArtMethod::PrettyMethod(rhs.Method()).c_str(),
132 rhs.DexPc());
Elliott Hughes86964332012-02-15 19:37:42 -0800133 return os;
134}
135
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200136class DebugInstrumentationListener FINAL : public instrumentation::InstrumentationListener {
Ian Rogers62d6c772013-02-27 08:32:07 -0800137 public:
138 DebugInstrumentationListener() {}
139 virtual ~DebugInstrumentationListener() {}
140
Alex Lightd7661582017-05-01 13:48:16 -0700141 void MethodEntered(Thread* thread,
142 Handle<mirror::Object> this_object,
143 ArtMethod* method,
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200144 uint32_t dex_pc)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700145 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800146 if (method->IsNative()) {
147 // TODO: post location events is a suspension point and native method entry stubs aren't.
148 return;
149 }
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200150 if (IsListeningToDexPcMoved()) {
151 // We also listen to kDexPcMoved instrumentation event so we know the DexPcMoved method is
152 // going to be called right after us. To avoid sending JDWP events twice for this location,
153 // we report the event in DexPcMoved. However, we must remind this is method entry so we
154 // send the METHOD_ENTRY event. And we can also group it with other events for this location
155 // like BREAKPOINT or SINGLE_STEP (or even METHOD_EXIT if this is a RETURN instruction).
156 thread->SetDebugMethodEntry();
157 } else if (IsListeningToMethodExit() && IsReturn(method, dex_pc)) {
158 // We also listen to kMethodExited instrumentation event and the current instruction is a
159 // RETURN so we know the MethodExited method is going to be called right after us. To avoid
160 // sending JDWP events twice for this location, we report the event(s) in MethodExited.
161 // However, we must remind this is method entry so we send the METHOD_ENTRY event. And we can
162 // also group it with other events for this location like BREAKPOINT or SINGLE_STEP.
163 thread->SetDebugMethodEntry();
164 } else {
Alex Lightd7661582017-05-01 13:48:16 -0700165 Dbg::UpdateDebugger(thread, this_object.Get(), method, 0, Dbg::kMethodEntry, nullptr);
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200166 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800167 }
168
Alex Lightd7661582017-05-01 13:48:16 -0700169 void MethodExited(Thread* thread,
170 Handle<mirror::Object> this_object,
171 ArtMethod* method,
172 uint32_t dex_pc,
173 const JValue& return_value)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700174 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800175 if (method->IsNative()) {
176 // TODO: post location events is a suspension point and native method entry stubs aren't.
177 return;
178 }
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200179 uint32_t events = Dbg::kMethodExit;
180 if (thread->IsDebugMethodEntry()) {
181 // It is also the method entry.
182 DCHECK(IsReturn(method, dex_pc));
183 events |= Dbg::kMethodEntry;
184 thread->ClearDebugMethodEntry();
185 }
Alex Lightd7661582017-05-01 13:48:16 -0700186 Dbg::UpdateDebugger(thread, this_object.Get(), method, dex_pc, events, &return_value);
Ian Rogers62d6c772013-02-27 08:32:07 -0800187 }
188
Alex Lightd7661582017-05-01 13:48:16 -0700189 void MethodUnwind(Thread* thread ATTRIBUTE_UNUSED,
190 Handle<mirror::Object> this_object ATTRIBUTE_UNUSED,
191 ArtMethod* method,
192 uint32_t dex_pc)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700193 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800194 // We're not recorded to listen to this kind of event, so complain.
David Sehr709b0702016-10-13 09:12:37 -0700195 LOG(ERROR) << "Unexpected method unwind event in debugger " << ArtMethod::PrettyMethod(method)
Sebastien Hertz51db44a2013-11-19 10:00:29 +0100196 << " " << dex_pc;
Ian Rogers62d6c772013-02-27 08:32:07 -0800197 }
198
Alex Lightd7661582017-05-01 13:48:16 -0700199 void DexPcMoved(Thread* thread,
200 Handle<mirror::Object> this_object,
201 ArtMethod* method,
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200202 uint32_t new_dex_pc)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700203 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200204 if (IsListeningToMethodExit() && IsReturn(method, new_dex_pc)) {
205 // We also listen to kMethodExited instrumentation event and the current instruction is a
206 // RETURN so we know the MethodExited method is going to be called right after us. Like in
207 // MethodEntered, we delegate event reporting to MethodExited.
208 // Besides, if this RETURN instruction is the only one in the method, we can send multiple
209 // JDWP events in the same packet: METHOD_ENTRY, METHOD_EXIT, BREAKPOINT and/or SINGLE_STEP.
210 // Therefore, we must not clear the debug method entry flag here.
211 } else {
212 uint32_t events = 0;
213 if (thread->IsDebugMethodEntry()) {
214 // It is also the method entry.
215 events = Dbg::kMethodEntry;
216 thread->ClearDebugMethodEntry();
217 }
Alex Lightd7661582017-05-01 13:48:16 -0700218 Dbg::UpdateDebugger(thread, this_object.Get(), method, new_dex_pc, events, nullptr);
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200219 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800220 }
221
Alex Lightd7661582017-05-01 13:48:16 -0700222 void FieldRead(Thread* thread ATTRIBUTE_UNUSED,
223 Handle<mirror::Object> this_object,
224 ArtMethod* method,
225 uint32_t dex_pc,
226 ArtField* field)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700227 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Lightd7661582017-05-01 13:48:16 -0700228 Dbg::PostFieldAccessEvent(method, dex_pc, this_object.Get(), field);
Ian Rogers62d6c772013-02-27 08:32:07 -0800229 }
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200230
Alex Lightd7661582017-05-01 13:48:16 -0700231 void FieldWritten(Thread* thread ATTRIBUTE_UNUSED,
232 Handle<mirror::Object> this_object,
233 ArtMethod* method,
234 uint32_t dex_pc,
235 ArtField* field,
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700236 const JValue& field_value)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700237 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Lightd7661582017-05-01 13:48:16 -0700238 Dbg::PostFieldModificationEvent(method, dex_pc, this_object.Get(), field, &field_value);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200239 }
240
Alex Lightd7661582017-05-01 13:48:16 -0700241 void ExceptionCaught(Thread* thread ATTRIBUTE_UNUSED,
242 Handle<mirror::Throwable> exception_object)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700243 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Lightd7661582017-05-01 13:48:16 -0700244 Dbg::PostException(exception_object.Get());
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200245 }
246
Nicolas Geoffray81f0f952016-01-20 16:25:19 +0000247 // We only care about branches in the Jit.
248 void Branch(Thread* /*thread*/, ArtMethod* method, uint32_t dex_pc, int32_t dex_pc_offset)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700249 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
David Sehr709b0702016-10-13 09:12:37 -0700250 LOG(ERROR) << "Unexpected branch event in debugger " << ArtMethod::PrettyMethod(method)
Nicolas Geoffray81f0f952016-01-20 16:25:19 +0000251 << " " << dex_pc << ", " << dex_pc_offset;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800252 }
253
Nicolas Geoffray5550ca82015-08-21 18:38:30 +0100254 // We only care about invokes in the Jit.
255 void InvokeVirtualOrInterface(Thread* thread ATTRIBUTE_UNUSED,
Alex Lightd7661582017-05-01 13:48:16 -0700256 Handle<mirror::Object> this_object ATTRIBUTE_UNUSED,
Nicolas Geoffray5550ca82015-08-21 18:38:30 +0100257 ArtMethod* method,
258 uint32_t dex_pc,
Alex Lightd7661582017-05-01 13:48:16 -0700259 ArtMethod* target ATTRIBUTE_UNUSED)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700260 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
David Sehr709b0702016-10-13 09:12:37 -0700261 LOG(ERROR) << "Unexpected invoke event in debugger " << ArtMethod::PrettyMethod(method)
Nicolas Geoffray5550ca82015-08-21 18:38:30 +0100262 << " " << dex_pc;
263 }
264
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200265 private:
Mathieu Chartiere401d142015-04-22 13:56:20 -0700266 static bool IsReturn(ArtMethod* method, uint32_t dex_pc)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700267 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200268 const DexFile::CodeItem* code_item = method->GetCodeItem();
269 const Instruction* instruction = Instruction::At(&code_item->insns_[dex_pc]);
270 return instruction->IsReturn();
271 }
272
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700273 static bool IsListeningToDexPcMoved() REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200274 return IsListeningTo(instrumentation::Instrumentation::kDexPcMoved);
275 }
276
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700277 static bool IsListeningToMethodExit() REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200278 return IsListeningTo(instrumentation::Instrumentation::kMethodExited);
279 }
280
281 static bool IsListeningTo(instrumentation::Instrumentation::InstrumentationEvent event)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700282 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200283 return (Dbg::GetInstrumentationEvents() & event) != 0;
284 }
285
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200286 DISALLOW_COPY_AND_ASSIGN(DebugInstrumentationListener);
Ian Rogers62d6c772013-02-27 08:32:07 -0800287} gDebugInstrumentationListener;
288
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700289// JDWP is allowed unless the Zygote forbids it.
290static bool gJdwpAllowed = true;
291
Elliott Hughesc0f09332012-03-26 13:27:06 -0700292// Was there a -Xrunjdwp or -agentlib:jdwp= argument on the command line?
Elliott Hughes3bb81562011-10-21 18:52:59 -0700293static bool gJdwpConfigured = false;
294
Sebastien Hertzb3b173b2015-02-06 09:16:32 +0100295// JDWP options for debugging. Only valid if IsJdwpConfigured() is true.
296static JDWP::JdwpOptions gJdwpOptions;
297
Elliott Hughes3bb81562011-10-21 18:52:59 -0700298// Runtime JDWP state.
Ian Rogersc0542af2014-09-03 16:16:56 -0700299static JDWP::JdwpState* gJdwpState = nullptr;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700300static bool gDebuggerConnected; // debugger or DDMS is connected.
Elliott Hughes3bb81562011-10-21 18:52:59 -0700301
Elliott Hughes47fce012011-10-25 18:37:19 -0700302static bool gDdmThreadNotification = false;
303
Elliott Hughes767a1472011-10-26 18:49:02 -0700304// DDMS GC-related settings.
305static Dbg::HpifWhen gDdmHpifWhen = Dbg::HPIF_WHEN_NEVER;
306static Dbg::HpsgWhen gDdmHpsgWhen = Dbg::HPSG_WHEN_NEVER;
307static Dbg::HpsgWhat gDdmHpsgWhat;
308static Dbg::HpsgWhen gDdmNhsgWhen = Dbg::HPSG_WHEN_NEVER;
309static Dbg::HpsgWhat gDdmNhsgWhat;
310
Daniel Mihalyieb076692014-08-22 17:33:31 +0200311bool Dbg::gDebuggerActive = false;
Sebastien Hertz4e5b2082015-03-24 19:03:40 +0100312bool Dbg::gDisposed = false;
Sebastien Hertz6995c602014-09-09 12:10:13 +0200313ObjectRegistry* Dbg::gRegistry = nullptr;
Elliott Hughes475fc232011-10-25 15:00:35 -0700314
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100315// Deoptimization support.
Sebastien Hertz4d25df32014-03-21 17:44:46 +0100316std::vector<DeoptimizationRequest> Dbg::deoptimization_requests_;
317size_t Dbg::full_deoptimization_event_count_ = 0;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100318
Sebastien Hertz42cd43f2014-05-13 14:15:41 +0200319// Instrumentation event reference counters.
320size_t Dbg::dex_pc_change_event_ref_count_ = 0;
321size_t Dbg::method_enter_event_ref_count_ = 0;
322size_t Dbg::method_exit_event_ref_count_ = 0;
323size_t Dbg::field_read_event_ref_count_ = 0;
324size_t Dbg::field_write_event_ref_count_ = 0;
325size_t Dbg::exception_catch_event_ref_count_ = 0;
326uint32_t Dbg::instrumentation_events_ = 0;
327
Andreas Gampe04bbb5b2017-01-19 17:49:03 +0000328Dbg::DbgThreadLifecycleCallback Dbg::thread_lifecycle_callback_;
Andreas Gampe0f01b582017-01-18 15:22:37 -0800329Dbg::DbgClassLoadCallback Dbg::class_load_callback_;
Andreas Gampe04bbb5b2017-01-19 17:49:03 +0000330
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100331// Breakpoints.
jeffhao09bfc6a2012-12-11 18:11:43 -0800332static std::vector<Breakpoint> gBreakpoints GUARDED_BY(Locks::breakpoint_lock_);
Elliott Hughes86964332012-02-15 19:37:42 -0800333
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700334void DebugInvokeReq::VisitRoots(RootVisitor* visitor, const RootInfo& root_info) {
335 receiver.VisitRootIfNonNull(visitor, root_info); // null for static method call.
336 klass.VisitRoot(visitor, root_info);
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700337}
338
Sebastien Hertz597c4f02015-01-26 17:37:14 +0100339void SingleStepControl::AddDexPc(uint32_t dex_pc) {
340 dex_pcs_.insert(dex_pc);
Sebastien Hertzbb43b432014-04-14 11:59:08 +0200341}
342
Sebastien Hertz597c4f02015-01-26 17:37:14 +0100343bool SingleStepControl::ContainsDexPc(uint32_t dex_pc) const {
344 return dex_pcs_.find(dex_pc) == dex_pcs_.end();
Sebastien Hertzbb43b432014-04-14 11:59:08 +0200345}
346
Alex Light6c8467f2015-11-20 15:03:26 -0800347static bool IsBreakpoint(ArtMethod* m, uint32_t dex_pc)
Mathieu Chartier90443472015-07-16 20:32:27 -0700348 REQUIRES(!Locks::breakpoint_lock_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700349 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertzed2be172014-08-19 15:33:43 +0200350 ReaderMutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100351 for (size_t i = 0, e = gBreakpoints.size(); i < e; ++i) {
Alex Light6c8467f2015-11-20 15:03:26 -0800352 if (gBreakpoints[i].DexPc() == dex_pc && gBreakpoints[i].IsInMethod(m)) {
Elliott Hughes86964332012-02-15 19:37:42 -0800353 VLOG(jdwp) << "Hit breakpoint #" << i << ": " << gBreakpoints[i];
354 return true;
355 }
356 }
357 return false;
358}
359
Sebastien Hertz52d131d2014-03-13 16:17:40 +0100360static bool IsSuspendedForDebugger(ScopedObjectAccessUnchecked& soa, Thread* thread)
Mathieu Chartier90443472015-07-16 20:32:27 -0700361 REQUIRES(!Locks::thread_suspend_count_lock_) {
Elliott Hughes9e0c1752013-01-09 14:02:58 -0800362 MutexLock mu(soa.Self(), *Locks::thread_suspend_count_lock_);
363 // A thread may be suspended for GC; in this code, we really want to know whether
364 // there's a debugger suspension active.
365 return thread->IsSuspended() && thread->GetDebugSuspendCount() > 0;
366}
367
Ian Rogersc0542af2014-09-03 16:16:56 -0700368static mirror::Array* DecodeNonNullArray(JDWP::RefTypeId id, JDWP::JdwpError* error)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700369 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz6995c602014-09-09 12:10:13 +0200370 mirror::Object* o = Dbg::GetObjectRegistry()->Get<mirror::Object*>(id, error);
Ian Rogersc0542af2014-09-03 16:16:56 -0700371 if (o == nullptr) {
372 *error = JDWP::ERR_INVALID_OBJECT;
373 return nullptr;
Elliott Hughes436e3722012-02-17 20:01:47 -0800374 }
375 if (!o->IsArrayInstance()) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700376 *error = JDWP::ERR_INVALID_ARRAY;
377 return nullptr;
Elliott Hughes436e3722012-02-17 20:01:47 -0800378 }
Ian Rogersc0542af2014-09-03 16:16:56 -0700379 *error = JDWP::ERR_NONE;
Elliott Hughes436e3722012-02-17 20:01:47 -0800380 return o->AsArray();
381}
382
Ian Rogersc0542af2014-09-03 16:16:56 -0700383static mirror::Class* DecodeClass(JDWP::RefTypeId id, JDWP::JdwpError* error)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700384 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz6995c602014-09-09 12:10:13 +0200385 mirror::Object* o = Dbg::GetObjectRegistry()->Get<mirror::Object*>(id, error);
Ian Rogersc0542af2014-09-03 16:16:56 -0700386 if (o == nullptr) {
387 *error = JDWP::ERR_INVALID_OBJECT;
388 return nullptr;
Elliott Hughes436e3722012-02-17 20:01:47 -0800389 }
390 if (!o->IsClass()) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700391 *error = JDWP::ERR_INVALID_CLASS;
392 return nullptr;
Elliott Hughes436e3722012-02-17 20:01:47 -0800393 }
Ian Rogersc0542af2014-09-03 16:16:56 -0700394 *error = JDWP::ERR_NONE;
Elliott Hughes436e3722012-02-17 20:01:47 -0800395 return o->AsClass();
396}
397
Ian Rogersc0542af2014-09-03 16:16:56 -0700398static Thread* DecodeThread(ScopedObjectAccessUnchecked& soa, JDWP::ObjectId thread_id,
399 JDWP::JdwpError* error)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700400 REQUIRES_SHARED(Locks::mutator_lock_)
Mathieu Chartier90443472015-07-16 20:32:27 -0700401 REQUIRES(!Locks::thread_list_lock_, !Locks::thread_suspend_count_lock_) {
Sebastien Hertz6995c602014-09-09 12:10:13 +0200402 mirror::Object* thread_peer = Dbg::GetObjectRegistry()->Get<mirror::Object*>(thread_id, error);
Ian Rogersc0542af2014-09-03 16:16:56 -0700403 if (thread_peer == nullptr) {
Elliott Hughes221229c2013-01-08 18:17:50 -0800404 // This isn't even an object.
Ian Rogersc0542af2014-09-03 16:16:56 -0700405 *error = JDWP::ERR_INVALID_OBJECT;
406 return nullptr;
Elliott Hughes436e3722012-02-17 20:01:47 -0800407 }
Elliott Hughes221229c2013-01-08 18:17:50 -0800408
Mathieu Chartier0795f232016-09-27 18:43:30 -0700409 ObjPtr<mirror::Class> java_lang_Thread =
410 soa.Decode<mirror::Class>(WellKnownClasses::java_lang_Thread);
Elliott Hughes221229c2013-01-08 18:17:50 -0800411 if (!java_lang_Thread->IsAssignableFrom(thread_peer->GetClass())) {
412 // This isn't a thread.
Ian Rogersc0542af2014-09-03 16:16:56 -0700413 *error = JDWP::ERR_INVALID_THREAD;
414 return nullptr;
Elliott Hughes221229c2013-01-08 18:17:50 -0800415 }
416
Sebastien Hertz69206392015-04-07 15:54:25 +0200417 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogersc0542af2014-09-03 16:16:56 -0700418 Thread* thread = Thread::FromManagedThread(soa, thread_peer);
419 // If thread is null then this a java.lang.Thread without a Thread*. Must be a un-started or a
420 // zombie.
421 *error = (thread == nullptr) ? JDWP::ERR_THREAD_NOT_ALIVE : JDWP::ERR_NONE;
422 return thread;
Elliott Hughes436e3722012-02-17 20:01:47 -0800423}
424
Elliott Hughes24437992011-11-30 14:49:33 -0800425static JDWP::JdwpTag BasicTagFromDescriptor(const char* descriptor) {
426 // JDWP deliberately uses the descriptor characters' ASCII values for its enum.
427 // Note that by "basic" we mean that we don't get more specific than JT_OBJECT.
428 return static_cast<JDWP::JdwpTag>(descriptor[0]);
429}
430
Ian Rogers1ff3c982014-08-12 02:30:58 -0700431static JDWP::JdwpTag BasicTagFromClass(mirror::Class* klass)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700432 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers1ff3c982014-08-12 02:30:58 -0700433 std::string temp;
434 const char* descriptor = klass->GetDescriptor(&temp);
435 return BasicTagFromDescriptor(descriptor);
436}
437
Ian Rogers98379392014-02-24 16:53:16 -0800438static JDWP::JdwpTag TagFromClass(const ScopedObjectAccessUnchecked& soa, mirror::Class* c)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700439 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700440 CHECK(c != nullptr);
Elliott Hughes24437992011-11-30 14:49:33 -0800441 if (c->IsArrayClass()) {
442 return JDWP::JT_ARRAY;
443 }
Elliott Hughes24437992011-11-30 14:49:33 -0800444 if (c->IsStringClass()) {
445 return JDWP::JT_STRING;
Elliott Hughes24437992011-11-30 14:49:33 -0800446 }
Ian Rogers98379392014-02-24 16:53:16 -0800447 if (c->IsClassClass()) {
448 return JDWP::JT_CLASS_OBJECT;
449 }
450 {
Mathieu Chartier0795f232016-09-27 18:43:30 -0700451 ObjPtr<mirror::Class> thread_class =
452 soa.Decode<mirror::Class>(WellKnownClasses::java_lang_Thread);
Ian Rogers98379392014-02-24 16:53:16 -0800453 if (thread_class->IsAssignableFrom(c)) {
454 return JDWP::JT_THREAD;
455 }
456 }
457 {
Mathieu Chartier0795f232016-09-27 18:43:30 -0700458 ObjPtr<mirror::Class> thread_group_class =
459 soa.Decode<mirror::Class>(WellKnownClasses::java_lang_ThreadGroup);
Ian Rogers98379392014-02-24 16:53:16 -0800460 if (thread_group_class->IsAssignableFrom(c)) {
461 return JDWP::JT_THREAD_GROUP;
462 }
463 }
464 {
Mathieu Chartier0795f232016-09-27 18:43:30 -0700465 ObjPtr<mirror::Class> class_loader_class =
466 soa.Decode<mirror::Class>(WellKnownClasses::java_lang_ClassLoader);
Ian Rogers98379392014-02-24 16:53:16 -0800467 if (class_loader_class->IsAssignableFrom(c)) {
468 return JDWP::JT_CLASS_LOADER;
469 }
470 }
471 return JDWP::JT_OBJECT;
Elliott Hughes24437992011-11-30 14:49:33 -0800472}
473
474/*
475 * Objects declared to hold Object might actually hold a more specific
476 * type. The debugger may take a special interest in these (e.g. it
477 * wants to display the contents of Strings), so we want to return an
478 * appropriate tag.
479 *
480 * Null objects are tagged JT_OBJECT.
481 */
Sebastien Hertz6995c602014-09-09 12:10:13 +0200482JDWP::JdwpTag Dbg::TagFromObject(const ScopedObjectAccessUnchecked& soa, mirror::Object* o) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700483 return (o == nullptr) ? JDWP::JT_OBJECT : TagFromClass(soa, o->GetClass());
Elliott Hughes24437992011-11-30 14:49:33 -0800484}
485
486static bool IsPrimitiveTag(JDWP::JdwpTag tag) {
487 switch (tag) {
488 case JDWP::JT_BOOLEAN:
489 case JDWP::JT_BYTE:
490 case JDWP::JT_CHAR:
491 case JDWP::JT_FLOAT:
492 case JDWP::JT_DOUBLE:
493 case JDWP::JT_INT:
494 case JDWP::JT_LONG:
495 case JDWP::JT_SHORT:
496 case JDWP::JT_VOID:
497 return true;
498 default:
499 return false;
500 }
501}
502
Sebastien Hertzb3b173b2015-02-06 09:16:32 +0100503void Dbg::StartJdwp() {
Elliott Hughesc0f09332012-03-26 13:27:06 -0700504 if (!gJdwpAllowed || !IsJdwpConfigured()) {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700505 // No JDWP for you!
506 return;
507 }
508
Ian Rogers719d1a32014-03-06 12:13:39 -0800509 CHECK(gRegistry == nullptr);
Elliott Hughes475fc232011-10-25 15:00:35 -0700510 gRegistry = new ObjectRegistry;
511
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700512 // Init JDWP if the debugger is enabled. This may connect out to a
513 // debugger, passively listen for a debugger, or block waiting for a
514 // debugger.
Sebastien Hertzb3b173b2015-02-06 09:16:32 +0100515 gJdwpState = JDWP::JdwpState::Create(&gJdwpOptions);
Ian Rogersc0542af2014-09-03 16:16:56 -0700516 if (gJdwpState == nullptr) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -0800517 // We probably failed because some other process has the port already, which means that
518 // if we don't abort the user is likely to think they're talking to us when they're actually
519 // talking to that other process.
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800520 LOG(FATAL) << "Debugger thread failed to initialize";
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700521 }
522
523 // If a debugger has already attached, send the "welcome" message.
524 // This may cause us to suspend all threads.
Elliott Hughes376a7a02011-10-24 18:35:55 -0700525 if (gJdwpState->IsActive()) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700526 ScopedObjectAccess soa(Thread::Current());
Sebastien Hertz7d955652014-10-22 10:57:10 +0200527 gJdwpState->PostVMStart();
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700528 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700529}
530
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700531void Dbg::StopJdwp() {
Sebastien Hertzc6345ef2014-08-18 19:26:39 +0200532 // Post VM_DEATH event before the JDWP connection is closed (either by the JDWP thread or the
533 // destruction of gJdwpState).
534 if (gJdwpState != nullptr && gJdwpState->IsActive()) {
535 gJdwpState->PostVMDeath();
536 }
Sebastien Hertz0376e6b2014-02-06 18:12:59 +0100537 // Prevent the JDWP thread from processing JDWP incoming packets after we close the connection.
Sebastien Hertz4e5b2082015-03-24 19:03:40 +0100538 Dispose();
Elliott Hughes376a7a02011-10-24 18:35:55 -0700539 delete gJdwpState;
Ian Rogers719d1a32014-03-06 12:13:39 -0800540 gJdwpState = nullptr;
Elliott Hughes475fc232011-10-25 15:00:35 -0700541 delete gRegistry;
Ian Rogers719d1a32014-03-06 12:13:39 -0800542 gRegistry = nullptr;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700543}
544
Elliott Hughes767a1472011-10-26 18:49:02 -0700545void Dbg::GcDidFinish() {
546 if (gDdmHpifWhen != HPIF_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700547 ScopedObjectAccess soa(Thread::Current());
Brian Carlstrom4d466a82014-05-08 19:05:29 -0700548 VLOG(jdwp) << "Sending heap info to DDM";
Elliott Hughes7162ad92011-10-27 14:08:42 -0700549 DdmSendHeapInfo(gDdmHpifWhen);
Elliott Hughes767a1472011-10-26 18:49:02 -0700550 }
551 if (gDdmHpsgWhen != 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 heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700554 DdmSendHeapSegments(false);
Elliott Hughes767a1472011-10-26 18:49:02 -0700555 }
556 if (gDdmNhsgWhen != HPSG_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700557 ScopedObjectAccess soa(Thread::Current());
Brian Carlstrom4d466a82014-05-08 19:05:29 -0700558 VLOG(jdwp) << "Dumping native heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700559 DdmSendHeapSegments(true);
Elliott Hughes767a1472011-10-26 18:49:02 -0700560 }
561}
562
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700563void Dbg::SetJdwpAllowed(bool allowed) {
564 gJdwpAllowed = allowed;
565}
566
Leonard Mosescueb842212016-10-06 17:26:36 -0700567bool Dbg::IsJdwpAllowed() {
568 return gJdwpAllowed;
569}
570
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700571DebugInvokeReq* Dbg::GetInvokeReq() {
Elliott Hughes475fc232011-10-25 15:00:35 -0700572 return Thread::Current()->GetInvokeReq();
573}
574
575Thread* Dbg::GetDebugThread() {
Ian Rogersc0542af2014-09-03 16:16:56 -0700576 return (gJdwpState != nullptr) ? gJdwpState->GetDebugThread() : nullptr;
Elliott Hughes475fc232011-10-25 15:00:35 -0700577}
578
579void Dbg::ClearWaitForEventThread() {
Sebastien Hertz2bf93f42015-01-09 18:44:05 +0100580 gJdwpState->ReleaseJdwpTokenForEvent();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700581}
582
583void Dbg::Connected() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700584 CHECK(!gDebuggerConnected);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800585 VLOG(jdwp) << "JDWP has attached";
Elliott Hughes3bb81562011-10-21 18:52:59 -0700586 gDebuggerConnected = true;
Elliott Hughes86964332012-02-15 19:37:42 -0800587 gDisposed = false;
588}
589
Sebastien Hertzf3928792014-11-17 19:00:37 +0100590bool Dbg::RequiresDeoptimization() {
591 // We don't need deoptimization if everything runs with interpreter after
592 // enabling -Xint mode.
593 return !Runtime::Current()->GetInstrumentation()->IsForcedInterpretOnly();
594}
595
Elliott Hughesa2155262011-11-16 16:26:58 -0800596void Dbg::GoActive() {
597 // Enable all debugging features, including scans for breakpoints.
598 // This is a no-op if we're already active.
599 // Only called from the JDWP handler thread.
Daniel Mihalyieb076692014-08-22 17:33:31 +0200600 if (IsDebuggerActive()) {
Elliott Hughesa2155262011-11-16 16:26:58 -0800601 return;
602 }
603
Mathieu Chartieraa516822015-10-02 15:53:37 -0700604 Thread* const self = Thread::Current();
Elliott Hughesc0f09332012-03-26 13:27:06 -0700605 {
606 // TODO: dalvik only warned if there were breakpoints left over. clear in Dbg::Disconnected?
Mathieu Chartieraa516822015-10-02 15:53:37 -0700607 ReaderMutexLock mu(self, *Locks::breakpoint_lock_);
Elliott Hughesc0f09332012-03-26 13:27:06 -0700608 CHECK_EQ(gBreakpoints.size(), 0U);
609 }
Elliott Hughesa2155262011-11-16 16:26:58 -0800610
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100611 {
Mathieu Chartieraa516822015-10-02 15:53:37 -0700612 MutexLock mu(self, *Locks::deoptimization_lock_);
Sebastien Hertz4d25df32014-03-21 17:44:46 +0100613 CHECK_EQ(deoptimization_requests_.size(), 0U);
614 CHECK_EQ(full_deoptimization_event_count_, 0U);
Sebastien Hertz42cd43f2014-05-13 14:15:41 +0200615 CHECK_EQ(dex_pc_change_event_ref_count_, 0U);
616 CHECK_EQ(method_enter_event_ref_count_, 0U);
617 CHECK_EQ(method_exit_event_ref_count_, 0U);
618 CHECK_EQ(field_read_event_ref_count_, 0U);
619 CHECK_EQ(field_write_event_ref_count_, 0U);
620 CHECK_EQ(exception_catch_event_ref_count_, 0U);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100621 }
622
Ian Rogers62d6c772013-02-27 08:32:07 -0800623 Runtime* runtime = Runtime::Current();
Nicolas Geoffray433b79a2017-01-30 20:54:45 +0000624 // Best effort deoptimization if the runtime is non-Java debuggable. This happens when
625 // ro.debuggable is set, but the application is not debuggable, or when a standalone
626 // dalvikvm invocation is not passed the debuggable option (-Xcompiler-option --debuggable).
627 //
628 // The performance cost of this is non-negligible during native-debugging due to the
David Srbeckyf4480162016-03-16 00:06:24 +0000629 // forced JIT, so we keep the AOT code in that case in exchange for limited native debugging.
Nicolas Geoffray433b79a2017-01-30 20:54:45 +0000630 if (!runtime->IsJavaDebuggable() &&
631 !runtime->GetInstrumentation()->IsForcedInterpretOnly() &&
632 !runtime->IsNativeDebuggable()) {
633 runtime->DeoptimizeBootImage();
Mingyao Yang6ea1a0e2016-01-29 12:12:49 -0800634 }
635
Mathieu Chartier4f55e222015-09-04 13:26:21 -0700636 ScopedSuspendAll ssa(__FUNCTION__);
Sebastien Hertzf3928792014-11-17 19:00:37 +0100637 if (RequiresDeoptimization()) {
638 runtime->GetInstrumentation()->EnableDeoptimization();
639 }
Sebastien Hertz42cd43f2014-05-13 14:15:41 +0200640 instrumentation_events_ = 0;
Elliott Hughesa2155262011-11-16 16:26:58 -0800641 gDebuggerActive = true;
Ian Rogers62d6c772013-02-27 08:32:07 -0800642 LOG(INFO) << "Debugger is active";
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700643}
644
645void Dbg::Disconnected() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700646 CHECK(gDebuggerConnected);
647
Elliott Hughesc0f09332012-03-26 13:27:06 -0700648 LOG(INFO) << "Debugger is no longer active";
Elliott Hughes234ab152011-10-26 14:02:26 -0700649
Hiroshi Yamauchi98810e32016-05-24 14:55:40 -0700650 // Suspend all threads and exclusively acquire the mutator lock. Remove the debugger as a listener
Ian Rogers62d6c772013-02-27 08:32:07 -0800651 // and clear the object registry.
652 Runtime* runtime = Runtime::Current();
Ian Rogers62d6c772013-02-27 08:32:07 -0800653 Thread* self = Thread::Current();
Mathieu Chartier4f55e222015-09-04 13:26:21 -0700654 {
Mathieu Chartieraa516822015-10-02 15:53:37 -0700655 // Required for DisableDeoptimization.
656 gc::ScopedGCCriticalSection gcs(self,
657 gc::kGcCauseInstrumentation,
658 gc::kCollectorTypeInstrumentation);
Mathieu Chartier4f55e222015-09-04 13:26:21 -0700659 ScopedSuspendAll ssa(__FUNCTION__);
Mathieu Chartier4f55e222015-09-04 13:26:21 -0700660 // Debugger may not be active at this point.
661 if (IsDebuggerActive()) {
662 {
663 // Since we're going to disable deoptimization, we clear the deoptimization requests queue.
664 // This prevents us from having any pending deoptimization request when the debugger attaches
665 // to us again while no event has been requested yet.
Mathieu Chartiera6b1ead2015-10-06 10:32:38 -0700666 MutexLock mu(self, *Locks::deoptimization_lock_);
Mathieu Chartier4f55e222015-09-04 13:26:21 -0700667 deoptimization_requests_.clear();
668 full_deoptimization_event_count_ = 0U;
669 }
670 if (instrumentation_events_ != 0) {
671 runtime->GetInstrumentation()->RemoveListener(&gDebugInstrumentationListener,
672 instrumentation_events_);
673 instrumentation_events_ = 0;
674 }
675 if (RequiresDeoptimization()) {
676 runtime->GetInstrumentation()->DisableDeoptimization(kDbgInstrumentationKey);
677 }
678 gDebuggerActive = false;
Sebastien Hertzaaea7342014-02-25 15:10:04 +0100679 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100680 }
Sebastien Hertz55f65342015-01-13 22:48:34 +0100681
682 {
683 ScopedObjectAccess soa(self);
684 gRegistry->Clear();
685 }
686
687 gDebuggerConnected = false;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700688}
689
Sebastien Hertzb3b173b2015-02-06 09:16:32 +0100690void Dbg::ConfigureJdwp(const JDWP::JdwpOptions& jdwp_options) {
691 CHECK_NE(jdwp_options.transport, JDWP::kJdwpTransportUnknown);
692 gJdwpOptions = jdwp_options;
693 gJdwpConfigured = true;
694}
695
Elliott Hughesc0f09332012-03-26 13:27:06 -0700696bool Dbg::IsJdwpConfigured() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700697 return gJdwpConfigured;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700698}
699
700int64_t Dbg::LastDebuggerActivity() {
Elliott Hughesca951522011-12-05 12:01:32 -0800701 return gJdwpState->LastDebuggerActivity();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700702}
703
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700704void Dbg::UndoDebuggerSuspensions() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700705 Runtime::Current()->GetThreadList()->UndoDebuggerSuspensions();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700706}
707
Elliott Hughes88d63092013-01-09 09:55:54 -0800708std::string Dbg::GetClassName(JDWP::RefTypeId class_id) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700709 JDWP::JdwpError error;
710 mirror::Object* o = gRegistry->Get<mirror::Object*>(class_id, &error);
711 if (o == nullptr) {
712 if (error == JDWP::ERR_NONE) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700713 return "null";
Ian Rogersc0542af2014-09-03 16:16:56 -0700714 } else {
715 return StringPrintf("invalid object %p", reinterpret_cast<void*>(class_id));
716 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800717 }
718 if (!o->IsClass()) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700719 return StringPrintf("non-class %p", o); // This is only used for debugging output anyway.
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800720 }
Sebastien Hertz6995c602014-09-09 12:10:13 +0200721 return GetClassName(o->AsClass());
722}
723
724std::string Dbg::GetClassName(mirror::Class* klass) {
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +0200725 if (klass == nullptr) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700726 return "null";
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +0200727 }
Ian Rogers1ff3c982014-08-12 02:30:58 -0700728 std::string temp;
Sebastien Hertz6995c602014-09-09 12:10:13 +0200729 return DescriptorToName(klass->GetDescriptor(&temp));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700730}
731
Ian Rogersc0542af2014-09-03 16:16:56 -0700732JDWP::JdwpError Dbg::GetClassObject(JDWP::RefTypeId id, JDWP::ObjectId* class_object_id) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800733 JDWP::JdwpError status;
Ian Rogersc0542af2014-09-03 16:16:56 -0700734 mirror::Class* c = DecodeClass(id, &status);
735 if (c == nullptr) {
736 *class_object_id = 0;
Elliott Hughes436e3722012-02-17 20:01:47 -0800737 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800738 }
Ian Rogersc0542af2014-09-03 16:16:56 -0700739 *class_object_id = gRegistry->Add(c);
Elliott Hughes436e3722012-02-17 20:01:47 -0800740 return JDWP::ERR_NONE;
Elliott Hughes86964332012-02-15 19:37:42 -0800741}
742
Ian Rogersc0542af2014-09-03 16:16:56 -0700743JDWP::JdwpError Dbg::GetSuperclass(JDWP::RefTypeId id, JDWP::RefTypeId* superclass_id) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800744 JDWP::JdwpError status;
Ian Rogersc0542af2014-09-03 16:16:56 -0700745 mirror::Class* c = DecodeClass(id, &status);
746 if (c == nullptr) {
747 *superclass_id = 0;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800748 return status;
749 }
750 if (c->IsInterface()) {
751 // http://code.google.com/p/android/issues/detail?id=20856
Ian Rogersc0542af2014-09-03 16:16:56 -0700752 *superclass_id = 0;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800753 } else {
Ian Rogersc0542af2014-09-03 16:16:56 -0700754 *superclass_id = gRegistry->Add(c->GetSuperClass());
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800755 }
756 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700757}
758
Elliott Hughes436e3722012-02-17 20:01:47 -0800759JDWP::JdwpError Dbg::GetClassLoader(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700760 JDWP::JdwpError error;
Andreas Gampe7929a482015-12-30 19:33:49 -0800761 mirror::Class* c = DecodeClass(id, &error);
762 if (c == nullptr) {
763 return error;
Elliott Hughes436e3722012-02-17 20:01:47 -0800764 }
Andreas Gampe7929a482015-12-30 19:33:49 -0800765 expandBufAddObjectId(pReply, gRegistry->Add(c->GetClassLoader()));
Elliott Hughes436e3722012-02-17 20:01:47 -0800766 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700767}
768
Elliott Hughes436e3722012-02-17 20:01:47 -0800769JDWP::JdwpError Dbg::GetModifiers(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700770 JDWP::JdwpError error;
771 mirror::Class* c = DecodeClass(id, &error);
772 if (c == nullptr) {
773 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800774 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800775
776 uint32_t access_flags = c->GetAccessFlags() & kAccJavaFlagsMask;
777
Yevgeny Roubande34eea2014-02-15 01:06:03 +0700778 // Set ACC_SUPER. Dex files don't contain this flag but only classes are supposed to have it set,
779 // not interfaces.
Elliott Hughes436e3722012-02-17 20:01:47 -0800780 // Class.getModifiers doesn't return it, but JDWP does, so we set it here.
Yevgeny Roubande34eea2014-02-15 01:06:03 +0700781 if ((access_flags & kAccInterface) == 0) {
782 access_flags |= kAccSuper;
783 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800784
785 expandBufAdd4BE(pReply, access_flags);
786
787 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700788}
789
Ian Rogersc0542af2014-09-03 16:16:56 -0700790JDWP::JdwpError Dbg::GetMonitorInfo(JDWP::ObjectId object_id, JDWP::ExpandBuf* reply) {
791 JDWP::JdwpError error;
792 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
793 if (o == nullptr) {
Elliott Hughesf327e072013-01-09 16:01:26 -0800794 return JDWP::ERR_INVALID_OBJECT;
795 }
796
797 // Ensure all threads are suspended while we read objects' lock words.
798 Thread* self = Thread::Current();
Sebastien Hertz54263242014-03-19 18:16:50 +0100799 CHECK_EQ(self->GetState(), kRunnable);
Elliott Hughesf327e072013-01-09 16:01:26 -0800800
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700801 MonitorInfo monitor_info;
802 {
803 ScopedThreadSuspension sts(self, kSuspended);
Mathieu Chartier4f55e222015-09-04 13:26:21 -0700804 ScopedSuspendAll ssa(__FUNCTION__);
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700805 monitor_info = MonitorInfo(o);
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700806 }
Ian Rogersc0542af2014-09-03 16:16:56 -0700807 if (monitor_info.owner_ != nullptr) {
Nicolas Geoffraycafa0812017-02-15 18:27:34 +0000808 expandBufAddObjectId(reply, gRegistry->Add(monitor_info.owner_->GetPeerFromOtherThread()));
Elliott Hughesf327e072013-01-09 16:01:26 -0800809 } else {
Ian Rogersc0542af2014-09-03 16:16:56 -0700810 expandBufAddObjectId(reply, gRegistry->Add(nullptr));
Elliott Hughesf327e072013-01-09 16:01:26 -0800811 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700812 expandBufAdd4BE(reply, monitor_info.entry_count_);
813 expandBufAdd4BE(reply, monitor_info.waiters_.size());
814 for (size_t i = 0; i < monitor_info.waiters_.size(); ++i) {
Nicolas Geoffraycafa0812017-02-15 18:27:34 +0000815 expandBufAddObjectId(reply, gRegistry->Add(monitor_info.waiters_[i]->GetPeerFromOtherThread()));
Elliott Hughesf327e072013-01-09 16:01:26 -0800816 }
817 return JDWP::ERR_NONE;
818}
819
Elliott Hughes734b8c62013-01-11 15:32:45 -0800820JDWP::JdwpError Dbg::GetOwnedMonitors(JDWP::ObjectId thread_id,
Ian Rogersc0542af2014-09-03 16:16:56 -0700821 std::vector<JDWP::ObjectId>* monitors,
822 std::vector<uint32_t>* stack_depths) {
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800823 struct OwnedMonitorVisitor : public StackVisitor {
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700824 OwnedMonitorVisitor(Thread* thread, Context* context,
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -0700825 std::vector<JDWP::ObjectId>* monitor_vector,
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700826 std::vector<uint32_t>* stack_depth_vector)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700827 REQUIRES_SHARED(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +0100828 : StackVisitor(thread, context, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
829 current_stack_depth(0),
830 monitors(monitor_vector),
831 stack_depths(stack_depth_vector) {}
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800832
833 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
834 // annotalysis.
835 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
836 if (!GetMethod()->IsRuntimeMethod()) {
837 Monitor::VisitLocks(this, AppendOwnedMonitors, this);
Elliott Hughes734b8c62013-01-11 15:32:45 -0800838 ++current_stack_depth;
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800839 }
840 return true;
841 }
842
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -0700843 static void AppendOwnedMonitors(mirror::Object* owned_monitor, void* arg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700844 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers7a22fa62013-01-23 12:16:16 -0800845 OwnedMonitorVisitor* visitor = reinterpret_cast<OwnedMonitorVisitor*>(arg);
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -0700846 visitor->monitors->push_back(gRegistry->Add(owned_monitor));
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700847 visitor->stack_depths->push_back(visitor->current_stack_depth);
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800848 }
849
Elliott Hughes734b8c62013-01-11 15:32:45 -0800850 size_t current_stack_depth;
Ian Rogersc0542af2014-09-03 16:16:56 -0700851 std::vector<JDWP::ObjectId>* const monitors;
852 std::vector<uint32_t>* const stack_depths;
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800853 };
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800854
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700855 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz69206392015-04-07 15:54:25 +0200856 JDWP::JdwpError error;
857 Thread* thread = DecodeThread(soa, thread_id, &error);
858 if (thread == nullptr) {
859 return error;
860 }
861 if (!IsSuspendedForDebugger(soa, thread)) {
862 return JDWP::ERR_THREAD_NOT_SUSPENDED;
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700863 }
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -0700864 std::unique_ptr<Context> context(Context::Create());
Ian Rogersc0542af2014-09-03 16:16:56 -0700865 OwnedMonitorVisitor visitor(thread, context.get(), monitors, stack_depths);
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -0700866 visitor.WalkStack();
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800867 return JDWP::ERR_NONE;
868}
869
Sebastien Hertz52d131d2014-03-13 16:17:40 +0100870JDWP::JdwpError Dbg::GetContendedMonitor(JDWP::ObjectId thread_id,
Ian Rogersc0542af2014-09-03 16:16:56 -0700871 JDWP::ObjectId* contended_monitor) {
Elliott Hughesf9501702013-01-11 11:22:27 -0800872 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -0700873 *contended_monitor = 0;
Sebastien Hertz69206392015-04-07 15:54:25 +0200874 JDWP::JdwpError error;
875 Thread* thread = DecodeThread(soa, thread_id, &error);
876 if (thread == nullptr) {
877 return error;
Elliott Hughesf9501702013-01-11 11:22:27 -0800878 }
Sebastien Hertz69206392015-04-07 15:54:25 +0200879 if (!IsSuspendedForDebugger(soa, thread)) {
880 return JDWP::ERR_THREAD_NOT_SUSPENDED;
881 }
882 mirror::Object* contended_monitor_obj = Monitor::GetContendedMonitor(thread);
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700883 // Add() requires the thread_list_lock_ not held to avoid the lock
884 // level violation.
Ian Rogersc0542af2014-09-03 16:16:56 -0700885 *contended_monitor = gRegistry->Add(contended_monitor_obj);
Elliott Hughesf9501702013-01-11 11:22:27 -0800886 return JDWP::ERR_NONE;
887}
888
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800889JDWP::JdwpError Dbg::GetInstanceCounts(const std::vector<JDWP::RefTypeId>& class_ids,
Ian Rogersc0542af2014-09-03 16:16:56 -0700890 std::vector<uint64_t>* counts) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800891 gc::Heap* heap = Runtime::Current()->GetHeap();
892 heap->CollectGarbage(false);
Mathieu Chartiere8a3c572016-10-11 16:52:17 -0700893 VariableSizedHandleScope hs(Thread::Current());
Mathieu Chartier9d156d52016-10-06 17:44:26 -0700894 std::vector<Handle<mirror::Class>> classes;
Ian Rogersc0542af2014-09-03 16:16:56 -0700895 counts->clear();
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800896 for (size_t i = 0; i < class_ids.size(); ++i) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700897 JDWP::JdwpError error;
Mathieu Chartier9d156d52016-10-06 17:44:26 -0700898 ObjPtr<mirror::Class> c = DecodeClass(class_ids[i], &error);
Ian Rogersc0542af2014-09-03 16:16:56 -0700899 if (c == nullptr) {
900 return error;
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800901 }
Mathieu Chartier9d156d52016-10-06 17:44:26 -0700902 classes.push_back(hs.NewHandle(c));
Ian Rogersc0542af2014-09-03 16:16:56 -0700903 counts->push_back(0);
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800904 }
Ian Rogersc0542af2014-09-03 16:16:56 -0700905 heap->CountInstances(classes, false, &(*counts)[0]);
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800906 return JDWP::ERR_NONE;
907}
908
Ian Rogersc0542af2014-09-03 16:16:56 -0700909JDWP::JdwpError Dbg::GetInstances(JDWP::RefTypeId class_id, int32_t max_count,
910 std::vector<JDWP::ObjectId>* instances) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800911 gc::Heap* heap = Runtime::Current()->GetHeap();
912 // We only want reachable instances, so do a GC.
913 heap->CollectGarbage(false);
Ian Rogersc0542af2014-09-03 16:16:56 -0700914 JDWP::JdwpError error;
Mathieu Chartier9d156d52016-10-06 17:44:26 -0700915 ObjPtr<mirror::Class> c = DecodeClass(class_id, &error);
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800916 if (c == nullptr) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700917 return error;
Elliott Hughes3b78c942013-01-15 17:35:41 -0800918 }
Mathieu Chartier2d855952016-10-12 19:37:59 -0700919 VariableSizedHandleScope hs(Thread::Current());
920 std::vector<Handle<mirror::Object>> raw_instances;
921 Runtime::Current()->GetHeap()->GetInstances(hs, hs.NewHandle(c), max_count, raw_instances);
Elliott Hughes3b78c942013-01-15 17:35:41 -0800922 for (size_t i = 0; i < raw_instances.size(); ++i) {
Mathieu Chartier2d855952016-10-12 19:37:59 -0700923 instances->push_back(gRegistry->Add(raw_instances[i].Get()));
Elliott Hughes3b78c942013-01-15 17:35:41 -0800924 }
925 return JDWP::ERR_NONE;
926}
927
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800928JDWP::JdwpError Dbg::GetReferringObjects(JDWP::ObjectId object_id, int32_t max_count,
Ian Rogersc0542af2014-09-03 16:16:56 -0700929 std::vector<JDWP::ObjectId>* referring_objects) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800930 gc::Heap* heap = Runtime::Current()->GetHeap();
931 heap->CollectGarbage(false);
Ian Rogersc0542af2014-09-03 16:16:56 -0700932 JDWP::JdwpError error;
Mathieu Chartier9d156d52016-10-06 17:44:26 -0700933 ObjPtr<mirror::Object> o = gRegistry->Get<mirror::Object*>(object_id, &error);
Ian Rogersc0542af2014-09-03 16:16:56 -0700934 if (o == nullptr) {
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800935 return JDWP::ERR_INVALID_OBJECT;
936 }
Mathieu Chartieraea9bfb2016-10-12 19:19:56 -0700937 VariableSizedHandleScope hs(Thread::Current());
938 std::vector<Handle<mirror::Object>> raw_instances;
939 heap->GetReferringObjects(hs, hs.NewHandle(o), max_count, raw_instances);
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800940 for (size_t i = 0; i < raw_instances.size(); ++i) {
Mathieu Chartieraea9bfb2016-10-12 19:19:56 -0700941 referring_objects->push_back(gRegistry->Add(raw_instances[i].Get()));
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800942 }
943 return JDWP::ERR_NONE;
944}
945
Ian Rogersc0542af2014-09-03 16:16:56 -0700946JDWP::JdwpError Dbg::DisableCollection(JDWP::ObjectId object_id) {
947 JDWP::JdwpError error;
948 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
949 if (o == nullptr) {
Sebastien Hertze96060a2013-12-11 12:06:28 +0100950 return JDWP::ERR_INVALID_OBJECT;
951 }
Elliott Hughes64f574f2013-02-20 14:57:12 -0800952 gRegistry->DisableCollection(object_id);
953 return JDWP::ERR_NONE;
954}
955
Ian Rogersc0542af2014-09-03 16:16:56 -0700956JDWP::JdwpError Dbg::EnableCollection(JDWP::ObjectId object_id) {
957 JDWP::JdwpError error;
958 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
Sebastien Hertze96060a2013-12-11 12:06:28 +0100959 // Unlike DisableCollection, JDWP specs do not state an invalid object causes an error. The RI
960 // also ignores these cases and never return an error. However it's not obvious why this command
961 // should behave differently from DisableCollection and IsCollected commands. So let's be more
962 // strict and return an error if this happens.
Ian Rogersc0542af2014-09-03 16:16:56 -0700963 if (o == nullptr) {
Sebastien Hertze96060a2013-12-11 12:06:28 +0100964 return JDWP::ERR_INVALID_OBJECT;
965 }
Elliott Hughes64f574f2013-02-20 14:57:12 -0800966 gRegistry->EnableCollection(object_id);
967 return JDWP::ERR_NONE;
968}
969
Ian Rogersc0542af2014-09-03 16:16:56 -0700970JDWP::JdwpError Dbg::IsCollected(JDWP::ObjectId object_id, bool* is_collected) {
971 *is_collected = true;
Sebastien Hertz65637eb2014-01-10 17:40:02 +0100972 if (object_id == 0) {
973 // Null object id is invalid.
Sebastien Hertze96060a2013-12-11 12:06:28 +0100974 return JDWP::ERR_INVALID_OBJECT;
975 }
Sebastien Hertz65637eb2014-01-10 17:40:02 +0100976 // JDWP specs state an INVALID_OBJECT error is returned if the object ID is not valid. However
977 // the RI seems to ignore this and assume object has been collected.
Ian Rogersc0542af2014-09-03 16:16:56 -0700978 JDWP::JdwpError error;
979 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
980 if (o != nullptr) {
981 *is_collected = gRegistry->IsCollected(object_id);
Sebastien Hertz65637eb2014-01-10 17:40:02 +0100982 }
Elliott Hughes64f574f2013-02-20 14:57:12 -0800983 return JDWP::ERR_NONE;
984}
985
Ian Rogersc0542af2014-09-03 16:16:56 -0700986void Dbg::DisposeObject(JDWP::ObjectId object_id, uint32_t reference_count) {
Elliott Hughes64f574f2013-02-20 14:57:12 -0800987 gRegistry->DisposeObject(object_id, reference_count);
988}
989
Mathieu Chartier3398c782016-09-30 10:27:43 -0700990JDWP::JdwpTypeTag Dbg::GetTypeTag(ObjPtr<mirror::Class> klass) {
Sebastien Hertz4d8fd492014-03-28 16:29:41 +0100991 DCHECK(klass != nullptr);
992 if (klass->IsArrayClass()) {
993 return JDWP::TT_ARRAY;
994 } else if (klass->IsInterface()) {
995 return JDWP::TT_INTERFACE;
996 } else {
997 return JDWP::TT_CLASS;
998 }
999}
1000
Elliott Hughes88d63092013-01-09 09:55:54 -08001001JDWP::JdwpError Dbg::GetReflectedType(JDWP::RefTypeId class_id, JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001002 JDWP::JdwpError error;
1003 mirror::Class* c = DecodeClass(class_id, &error);
1004 if (c == nullptr) {
1005 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001006 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001007
Sebastien Hertz4d8fd492014-03-28 16:29:41 +01001008 JDWP::JdwpTypeTag type_tag = GetTypeTag(c);
1009 expandBufAdd1(pReply, type_tag);
Elliott Hughes88d63092013-01-09 09:55:54 -08001010 expandBufAddRefTypeId(pReply, class_id);
Elliott Hughes436e3722012-02-17 20:01:47 -08001011 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001012}
1013
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001014// Get the complete list of reference classes (i.e. all classes except
1015// the primitive types).
1016// Returns a newly-allocated buffer full of RefTypeId values.
1017class ClassListCreator : public ClassVisitor {
1018 public:
1019 explicit ClassListCreator(std::vector<JDWP::RefTypeId>* classes) : classes_(classes) {}
1020
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001021 bool operator()(ObjPtr<mirror::Class> c) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001022 if (!c->IsPrimitive()) {
1023 classes_->push_back(Dbg::GetObjectRegistry()->AddRefType(c));
1024 }
1025 return true;
1026 }
1027
1028 private:
1029 std::vector<JDWP::RefTypeId>* const classes_;
1030};
1031
Ian Rogersc0542af2014-09-03 16:16:56 -07001032void Dbg::GetClassList(std::vector<JDWP::RefTypeId>* classes) {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001033 ClassListCreator clc(classes);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001034 Runtime::Current()->GetClassLinker()->VisitClassesWithoutClassesLock(&clc);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001035}
1036
Ian Rogers1ff3c982014-08-12 02:30:58 -07001037JDWP::JdwpError Dbg::GetClassInfo(JDWP::RefTypeId class_id, JDWP::JdwpTypeTag* pTypeTag,
1038 uint32_t* pStatus, std::string* pDescriptor) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001039 JDWP::JdwpError error;
1040 mirror::Class* c = DecodeClass(class_id, &error);
1041 if (c == nullptr) {
1042 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001043 }
1044
Elliott Hughesa2155262011-11-16 16:26:58 -08001045 if (c->IsArrayClass()) {
1046 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
1047 *pTypeTag = JDWP::TT_ARRAY;
1048 } else {
1049 if (c->IsErroneous()) {
1050 *pStatus = JDWP::CS_ERROR;
1051 } else {
1052 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED | JDWP::CS_INITIALIZED;
1053 }
1054 *pTypeTag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
1055 }
1056
Ian Rogersc0542af2014-09-03 16:16:56 -07001057 if (pDescriptor != nullptr) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07001058 std::string temp;
1059 *pDescriptor = c->GetDescriptor(&temp);
Elliott Hughesa2155262011-11-16 16:26:58 -08001060 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001061 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001062}
1063
Ian Rogersc0542af2014-09-03 16:16:56 -07001064void Dbg::FindLoadedClassBySignature(const char* descriptor, std::vector<JDWP::RefTypeId>* ids) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001065 std::vector<ObjPtr<mirror::Class>> classes;
Igor Murashkinb1d8c312015-08-04 11:18:43 -07001066 Runtime::Current()->GetClassLinker()->LookupClasses(descriptor, classes);
Ian Rogersc0542af2014-09-03 16:16:56 -07001067 ids->clear();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001068 for (ObjPtr<mirror::Class> c : classes) {
1069 ids->push_back(gRegistry->Add(c));
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001070 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001071}
1072
Ian Rogersc0542af2014-09-03 16:16:56 -07001073JDWP::JdwpError Dbg::GetReferenceType(JDWP::ObjectId object_id, JDWP::ExpandBuf* pReply) {
1074 JDWP::JdwpError error;
1075 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
1076 if (o == nullptr) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001077 return JDWP::ERR_INVALID_OBJECT;
Elliott Hughes499c5132011-11-17 14:55:11 -08001078 }
Elliott Hughes2435a572012-02-17 16:07:41 -08001079
Sebastien Hertz4d8fd492014-03-28 16:29:41 +01001080 JDWP::JdwpTypeTag type_tag = GetTypeTag(o->GetClass());
Elliott Hughes64f574f2013-02-20 14:57:12 -08001081 JDWP::RefTypeId type_id = gRegistry->AddRefType(o->GetClass());
Elliott Hughes2435a572012-02-17 16:07:41 -08001082
1083 expandBufAdd1(pReply, type_tag);
1084 expandBufAddRefTypeId(pReply, type_id);
1085
1086 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001087}
1088
Ian Rogersfc0e94b2013-09-23 23:51:32 -07001089JDWP::JdwpError Dbg::GetSignature(JDWP::RefTypeId class_id, std::string* signature) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001090 JDWP::JdwpError error;
1091 mirror::Class* c = DecodeClass(class_id, &error);
1092 if (c == nullptr) {
1093 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001094 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07001095 std::string temp;
1096 *signature = c->GetDescriptor(&temp);
Elliott Hughes1fe7afb2012-02-13 17:23:03 -08001097 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001098}
1099
Orion Hodson77d8a1c2017-04-24 14:53:19 +01001100JDWP::JdwpError Dbg::GetSourceDebugExtension(JDWP::RefTypeId class_id,
1101 std::string* extension_data) {
1102 JDWP::JdwpError error;
1103 mirror::Class* c = DecodeClass(class_id, &error);
1104 if (c == nullptr) {
1105 return error;
1106 }
1107 StackHandleScope<1> hs(Thread::Current());
1108 Handle<mirror::Class> klass(hs.NewHandle(c));
1109 const char* data = annotations::GetSourceDebugExtension(klass);
1110 if (data == nullptr) {
1111 return JDWP::ERR_ABSENT_INFORMATION;
1112 }
1113 *extension_data = data;
1114 return JDWP::ERR_NONE;
1115}
1116
Ian Rogersc0542af2014-09-03 16:16:56 -07001117JDWP::JdwpError Dbg::GetSourceFile(JDWP::RefTypeId class_id, std::string* result) {
1118 JDWP::JdwpError error;
1119 mirror::Class* c = DecodeClass(class_id, &error);
Sebastien Hertz4206eb52014-06-05 10:15:45 +02001120 if (c == nullptr) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001121 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001122 }
Sebastien Hertz4206eb52014-06-05 10:15:45 +02001123 const char* source_file = c->GetSourceFile();
1124 if (source_file == nullptr) {
Sebastien Hertzb7054ba2014-03-13 11:52:31 +01001125 return JDWP::ERR_ABSENT_INFORMATION;
1126 }
Ian Rogersc0542af2014-09-03 16:16:56 -07001127 *result = source_file;
Elliott Hughes436e3722012-02-17 20:01:47 -08001128 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001129}
1130
Ian Rogersc0542af2014-09-03 16:16:56 -07001131JDWP::JdwpError Dbg::GetObjectTag(JDWP::ObjectId object_id, uint8_t* tag) {
Ian Rogers98379392014-02-24 16:53:16 -08001132 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07001133 JDWP::JdwpError error;
1134 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
1135 if (error != JDWP::ERR_NONE) {
1136 *tag = JDWP::JT_VOID;
1137 return error;
Elliott Hughes546b9862012-06-20 16:06:13 -07001138 }
Ian Rogersc0542af2014-09-03 16:16:56 -07001139 *tag = TagFromObject(soa, o);
Elliott Hughes546b9862012-06-20 16:06:13 -07001140 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001141}
1142
Elliott Hughesaed4be92011-12-02 16:16:23 -08001143size_t Dbg::GetTagWidth(JDWP::JdwpTag tag) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001144 switch (tag) {
1145 case JDWP::JT_VOID:
1146 return 0;
1147 case JDWP::JT_BYTE:
1148 case JDWP::JT_BOOLEAN:
1149 return 1;
1150 case JDWP::JT_CHAR:
1151 case JDWP::JT_SHORT:
1152 return 2;
1153 case JDWP::JT_FLOAT:
1154 case JDWP::JT_INT:
1155 return 4;
1156 case JDWP::JT_ARRAY:
1157 case JDWP::JT_OBJECT:
1158 case JDWP::JT_STRING:
1159 case JDWP::JT_THREAD:
1160 case JDWP::JT_THREAD_GROUP:
1161 case JDWP::JT_CLASS_LOADER:
1162 case JDWP::JT_CLASS_OBJECT:
1163 return sizeof(JDWP::ObjectId);
1164 case JDWP::JT_DOUBLE:
1165 case JDWP::JT_LONG:
1166 return 8;
1167 default:
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001168 LOG(FATAL) << "Unknown tag " << tag;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001169 return -1;
1170 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001171}
1172
Ian Rogersc0542af2014-09-03 16:16:56 -07001173JDWP::JdwpError Dbg::GetArrayLength(JDWP::ObjectId array_id, int32_t* length) {
1174 JDWP::JdwpError error;
1175 mirror::Array* a = DecodeNonNullArray(array_id, &error);
1176 if (a == nullptr) {
1177 return error;
Elliott Hughes24437992011-11-30 14:49:33 -08001178 }
Ian Rogersc0542af2014-09-03 16:16:56 -07001179 *length = a->GetLength();
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001180 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001181}
1182
Elliott Hughes88d63092013-01-09 09:55:54 -08001183JDWP::JdwpError Dbg::OutputArray(JDWP::ObjectId array_id, int offset, int count, JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001184 JDWP::JdwpError error;
1185 mirror::Array* a = DecodeNonNullArray(array_id, &error);
Ian Rogers98379392014-02-24 16:53:16 -08001186 if (a == nullptr) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001187 return error;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001188 }
Elliott Hughes24437992011-11-30 14:49:33 -08001189
1190 if (offset < 0 || count < 0 || offset > a->GetLength() || a->GetLength() - offset < count) {
1191 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001192 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughes24437992011-11-30 14:49:33 -08001193 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07001194 JDWP::JdwpTag element_tag = BasicTagFromClass(a->GetClass()->GetComponentType());
1195 expandBufAdd1(pReply, element_tag);
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001196 expandBufAdd4BE(pReply, count);
1197
Ian Rogers1ff3c982014-08-12 02:30:58 -07001198 if (IsPrimitiveTag(element_tag)) {
1199 size_t width = GetTagWidth(element_tag);
Elliott Hughes24437992011-11-30 14:49:33 -08001200 uint8_t* dst = expandBufAddSpace(pReply, count * width);
1201 if (width == 8) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001202 const uint64_t* src8 = reinterpret_cast<uint64_t*>(a->GetRawData(sizeof(uint64_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001203 for (int i = 0; i < count; ++i) JDWP::Write8BE(&dst, src8[offset + i]);
1204 } else if (width == 4) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001205 const uint32_t* src4 = reinterpret_cast<uint32_t*>(a->GetRawData(sizeof(uint32_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001206 for (int i = 0; i < count; ++i) JDWP::Write4BE(&dst, src4[offset + i]);
1207 } else if (width == 2) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001208 const uint16_t* src2 = reinterpret_cast<uint16_t*>(a->GetRawData(sizeof(uint16_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001209 for (int i = 0; i < count; ++i) JDWP::Write2BE(&dst, src2[offset + i]);
1210 } else {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001211 const uint8_t* src = reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint8_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001212 memcpy(dst, &src[offset * width], count * width);
1213 }
1214 } else {
Ian Rogers98379392014-02-24 16:53:16 -08001215 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001216 mirror::ObjectArray<mirror::Object>* oa = a->AsObjectArray<mirror::Object>();
Elliott Hughes24437992011-11-30 14:49:33 -08001217 for (int i = 0; i < count; ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001218 mirror::Object* element = oa->Get(offset + i);
Ian Rogers98379392014-02-24 16:53:16 -08001219 JDWP::JdwpTag specific_tag = (element != nullptr) ? TagFromObject(soa, element)
Ian Rogers1ff3c982014-08-12 02:30:58 -07001220 : element_tag;
Elliott Hughes24437992011-11-30 14:49:33 -08001221 expandBufAdd1(pReply, specific_tag);
1222 expandBufAddObjectId(pReply, gRegistry->Add(element));
1223 }
1224 }
1225
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001226 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001227}
1228
Ian Rogersef7d42f2014-01-06 12:55:46 -08001229template <typename T>
Ian Rogersc0542af2014-09-03 16:16:56 -07001230static void CopyArrayData(mirror::Array* a, JDWP::Request* src, int offset, int count)
Ian Rogersef7d42f2014-01-06 12:55:46 -08001231 NO_THREAD_SAFETY_ANALYSIS {
1232 // TODO: fix when annotalysis correctly handles non-member functions.
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001233 DCHECK(a->GetClass()->IsPrimitiveArray());
1234
Ian Rogersef7d42f2014-01-06 12:55:46 -08001235 T* dst = reinterpret_cast<T*>(a->GetRawData(sizeof(T), offset));
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001236 for (int i = 0; i < count; ++i) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001237 *dst++ = src->ReadValue(sizeof(T));
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001238 }
1239}
1240
Elliott Hughes88d63092013-01-09 09:55:54 -08001241JDWP::JdwpError Dbg::SetArrayElements(JDWP::ObjectId array_id, int offset, int count,
Ian Rogersc0542af2014-09-03 16:16:56 -07001242 JDWP::Request* request) {
1243 JDWP::JdwpError error;
1244 mirror::Array* dst = DecodeNonNullArray(array_id, &error);
1245 if (dst == nullptr) {
1246 return error;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001247 }
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001248
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001249 if (offset < 0 || count < 0 || offset > dst->GetLength() || dst->GetLength() - offset < count) {
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001250 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001251 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001252 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07001253 JDWP::JdwpTag element_tag = BasicTagFromClass(dst->GetClass()->GetComponentType());
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001254
Ian Rogers1ff3c982014-08-12 02:30:58 -07001255 if (IsPrimitiveTag(element_tag)) {
1256 size_t width = GetTagWidth(element_tag);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001257 if (width == 8) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001258 CopyArrayData<uint64_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001259 } else if (width == 4) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001260 CopyArrayData<uint32_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001261 } else if (width == 2) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001262 CopyArrayData<uint16_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001263 } else {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001264 CopyArrayData<uint8_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001265 }
1266 } else {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001267 mirror::ObjectArray<mirror::Object>* oa = dst->AsObjectArray<mirror::Object>();
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001268 for (int i = 0; i < count; ++i) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001269 JDWP::ObjectId id = request->ReadObjectId();
Ian Rogersc0542af2014-09-03 16:16:56 -07001270 mirror::Object* o = gRegistry->Get<mirror::Object*>(id, &error);
1271 if (error != JDWP::ERR_NONE) {
1272 return error;
Elliott Hughes436e3722012-02-17 20:01:47 -08001273 }
Sebastien Hertz2e1c16d2015-08-28 11:57:49 +02001274 // Check if the object's type is compatible with the array's type.
1275 if (o != nullptr && !o->InstanceOf(oa->GetClass()->GetComponentType())) {
1276 return JDWP::ERR_TYPE_MISMATCH;
1277 }
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001278 oa->Set<false>(offset + i, o);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001279 }
1280 }
1281
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001282 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001283}
1284
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001285JDWP::JdwpError Dbg::CreateString(const std::string& str, JDWP::ObjectId* new_string_id) {
1286 Thread* self = Thread::Current();
1287 mirror::String* new_string = mirror::String::AllocFromModifiedUtf8(self, str.c_str());
1288 if (new_string == nullptr) {
1289 DCHECK(self->IsExceptionPending());
1290 self->ClearException();
1291 LOG(ERROR) << "Could not allocate string";
1292 *new_string_id = 0;
1293 return JDWP::ERR_OUT_OF_MEMORY;
1294 }
1295 *new_string_id = gRegistry->Add(new_string);
1296 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001297}
1298
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001299JDWP::JdwpError Dbg::CreateObject(JDWP::RefTypeId class_id, JDWP::ObjectId* new_object_id) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001300 JDWP::JdwpError error;
1301 mirror::Class* c = DecodeClass(class_id, &error);
1302 if (c == nullptr) {
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001303 *new_object_id = 0;
Ian Rogersc0542af2014-09-03 16:16:56 -07001304 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001305 }
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001306 Thread* self = Thread::Current();
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001307 ObjPtr<mirror::Object> new_object;
Sebastien Hertz56d5e502015-11-03 17:38:35 +01001308 if (c->IsStringClass()) {
1309 // Special case for java.lang.String.
1310 gc::AllocatorType allocator_type = Runtime::Current()->GetHeap()->GetCurrentAllocator();
jessicahandojo3aaa37b2016-07-29 14:46:37 -07001311 new_object = mirror::String::AllocEmptyString<true>(self, allocator_type);
Sebastien Hertz56d5e502015-11-03 17:38:35 +01001312 } else {
1313 new_object = c->AllocObject(self);
1314 }
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001315 if (new_object == nullptr) {
1316 DCHECK(self->IsExceptionPending());
1317 self->ClearException();
David Sehr709b0702016-10-13 09:12:37 -07001318 LOG(ERROR) << "Could not allocate object of type " << mirror::Class::PrettyDescriptor(c);
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001319 *new_object_id = 0;
1320 return JDWP::ERR_OUT_OF_MEMORY;
1321 }
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001322 *new_object_id = gRegistry->Add(new_object.Ptr());
Elliott Hughes436e3722012-02-17 20:01:47 -08001323 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001324}
1325
Elliott Hughesbf13d362011-12-08 15:51:37 -08001326/*
1327 * Used by Eclipse's "Display" view to evaluate "new byte[5]" to get "(byte[]) [0, 0, 0, 0, 0]".
1328 */
Elliott Hughes88d63092013-01-09 09:55:54 -08001329JDWP::JdwpError Dbg::CreateArrayObject(JDWP::RefTypeId array_class_id, uint32_t length,
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001330 JDWP::ObjectId* new_array_id) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001331 JDWP::JdwpError error;
1332 mirror::Class* c = DecodeClass(array_class_id, &error);
1333 if (c == nullptr) {
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001334 *new_array_id = 0;
Ian Rogersc0542af2014-09-03 16:16:56 -07001335 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001336 }
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001337 Thread* self = Thread::Current();
1338 gc::Heap* heap = Runtime::Current()->GetHeap();
1339 mirror::Array* new_array = mirror::Array::Alloc<true>(self, c, length,
1340 c->GetComponentSizeShift(),
1341 heap->GetCurrentAllocator());
1342 if (new_array == nullptr) {
1343 DCHECK(self->IsExceptionPending());
1344 self->ClearException();
David Sehr709b0702016-10-13 09:12:37 -07001345 LOG(ERROR) << "Could not allocate array of type " << mirror::Class::PrettyDescriptor(c);
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001346 *new_array_id = 0;
1347 return JDWP::ERR_OUT_OF_MEMORY;
1348 }
1349 *new_array_id = gRegistry->Add(new_array);
Elliott Hughes436e3722012-02-17 20:01:47 -08001350 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001351}
1352
Mathieu Chartierc7853442015-03-27 14:35:38 -07001353JDWP::FieldId Dbg::ToFieldId(const ArtField* f) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001354 return static_cast<JDWP::FieldId>(reinterpret_cast<uintptr_t>(f));
Elliott Hughes03181a82011-11-17 17:22:21 -08001355}
1356
Alex Light6c8467f2015-11-20 15:03:26 -08001357static JDWP::MethodId ToMethodId(ArtMethod* m)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001358 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light97e78032017-06-27 17:51:55 -07001359 return static_cast<JDWP::MethodId>(
1360 reinterpret_cast<uintptr_t>(m->GetCanonicalMethod(kRuntimePointerSize)));
Elliott Hughes03181a82011-11-17 17:22:21 -08001361}
1362
Mathieu Chartierc7853442015-03-27 14:35:38 -07001363static ArtField* FromFieldId(JDWP::FieldId fid)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001364 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001365 return reinterpret_cast<ArtField*>(static_cast<uintptr_t>(fid));
Elliott Hughesaed4be92011-12-02 16:16:23 -08001366}
1367
Mathieu Chartiere401d142015-04-22 13:56:20 -07001368static ArtMethod* FromMethodId(JDWP::MethodId mid)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001369 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001370 return reinterpret_cast<ArtMethod*>(static_cast<uintptr_t>(mid));
Elliott Hughes03181a82011-11-17 17:22:21 -08001371}
1372
Sebastien Hertz6995c602014-09-09 12:10:13 +02001373bool Dbg::MatchThread(JDWP::ObjectId expected_thread_id, Thread* event_thread) {
1374 CHECK(event_thread != nullptr);
1375 JDWP::JdwpError error;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001376 mirror::Object* expected_thread_peer = gRegistry->Get<mirror::Object*>(
1377 expected_thread_id, &error);
Nicolas Geoffraycafa0812017-02-15 18:27:34 +00001378 return expected_thread_peer == event_thread->GetPeerFromOtherThread();
Sebastien Hertz6995c602014-09-09 12:10:13 +02001379}
1380
1381bool Dbg::MatchLocation(const JDWP::JdwpLocation& expected_location,
1382 const JDWP::EventLocation& event_location) {
1383 if (expected_location.dex_pc != event_location.dex_pc) {
1384 return false;
1385 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001386 ArtMethod* m = FromMethodId(expected_location.method_id);
Sebastien Hertz6995c602014-09-09 12:10:13 +02001387 return m == event_location.method;
1388}
1389
Mathieu Chartier3398c782016-09-30 10:27:43 -07001390bool Dbg::MatchType(ObjPtr<mirror::Class> event_class, JDWP::RefTypeId class_id) {
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001391 if (event_class == nullptr) {
1392 return false;
1393 }
Sebastien Hertz6995c602014-09-09 12:10:13 +02001394 JDWP::JdwpError error;
Mathieu Chartier3398c782016-09-30 10:27:43 -07001395 ObjPtr<mirror::Class> expected_class = DecodeClass(class_id, &error);
Sebastien Hertz6995c602014-09-09 12:10:13 +02001396 CHECK(expected_class != nullptr);
1397 return expected_class->IsAssignableFrom(event_class);
1398}
1399
1400bool Dbg::MatchField(JDWP::RefTypeId expected_type_id, JDWP::FieldId expected_field_id,
Mathieu Chartierc7853442015-03-27 14:35:38 -07001401 ArtField* event_field) {
1402 ArtField* expected_field = FromFieldId(expected_field_id);
Sebastien Hertz6995c602014-09-09 12:10:13 +02001403 if (expected_field != event_field) {
1404 return false;
1405 }
1406 return Dbg::MatchType(event_field->GetDeclaringClass(), expected_type_id);
1407}
1408
1409bool Dbg::MatchInstance(JDWP::ObjectId expected_instance_id, mirror::Object* event_instance) {
1410 JDWP::JdwpError error;
1411 mirror::Object* modifier_instance = gRegistry->Get<mirror::Object*>(expected_instance_id, &error);
1412 return modifier_instance == event_instance;
1413}
1414
Mathieu Chartier90443472015-07-16 20:32:27 -07001415void Dbg::SetJdwpLocation(JDWP::JdwpLocation* location, ArtMethod* m, uint32_t dex_pc) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001416 if (m == nullptr) {
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001417 memset(location, 0, sizeof(*location));
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001418 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001419 mirror::Class* c = m->GetDeclaringClass();
Ian Rogersc0542af2014-09-03 16:16:56 -07001420 location->type_tag = GetTypeTag(c);
1421 location->class_id = gRegistry->AddRefType(c);
Alex Light73376312017-04-06 10:10:51 -07001422 // The RI Seems to return 0 for all obsolete methods. For compatibility we shall do the same.
1423 location->method_id = m->IsObsolete() ? 0 : ToMethodId(m);
Ian Rogersc0542af2014-09-03 16:16:56 -07001424 location->dex_pc = (m->IsNative() || m->IsProxyMethod()) ? static_cast<uint64_t>(-1) : dex_pc;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001425 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08001426}
1427
Ian Rogersc0542af2014-09-03 16:16:56 -07001428std::string Dbg::GetMethodName(JDWP::MethodId method_id) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001429 ArtMethod* m = FromMethodId(method_id);
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001430 if (m == nullptr) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001431 return "null";
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001432 }
Andreas Gampe542451c2016-07-26 09:02:02 -07001433 return m->GetInterfaceMethodIfProxy(kRuntimePointerSize)->GetName();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001434}
1435
Alex Light73376312017-04-06 10:10:51 -07001436bool Dbg::IsMethodObsolete(JDWP::MethodId method_id) {
1437 ArtMethod* m = FromMethodId(method_id);
1438 if (m == nullptr) {
1439 // NB Since we return 0 as MID for obsolete methods we want to default to true here.
1440 return true;
1441 }
1442 return m->IsObsolete();
1443}
1444
Ian Rogersc0542af2014-09-03 16:16:56 -07001445std::string Dbg::GetFieldName(JDWP::FieldId field_id) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001446 ArtField* f = FromFieldId(field_id);
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001447 if (f == nullptr) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001448 return "null";
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001449 }
1450 return f->GetName();
Elliott Hughesa96836a2013-01-17 12:27:49 -08001451}
1452
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001453/*
1454 * Augment the access flags for synthetic methods and fields by setting
1455 * the (as described by the spec) "0xf0000000 bit". Also, strip out any
1456 * flags not specified by the Java programming language.
1457 */
1458static uint32_t MangleAccessFlags(uint32_t accessFlags) {
1459 accessFlags &= kAccJavaFlagsMask;
1460 if ((accessFlags & kAccSynthetic) != 0) {
1461 accessFlags |= 0xf0000000;
1462 }
1463 return accessFlags;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001464}
1465
Elliott Hughesdbb40792011-11-18 17:05:22 -08001466/*
Jeff Haob7cefc72013-11-14 14:51:09 -08001467 * Circularly shifts registers so that arguments come first. Debuggers
1468 * expect slots to begin with arguments, but dex code places them at
1469 * the end.
Elliott Hughesdbb40792011-11-18 17:05:22 -08001470 */
Mathieu Chartiere401d142015-04-22 13:56:20 -07001471static uint16_t MangleSlot(uint16_t slot, ArtMethod* m)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001472 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001473 const DexFile::CodeItem* code_item = m->GetCodeItem();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001474 if (code_item == nullptr) {
1475 // We should not get here for a method without code (native, proxy or abstract). Log it and
1476 // return the slot as is since all registers are arguments.
David Sehr709b0702016-10-13 09:12:37 -07001477 LOG(WARNING) << "Trying to mangle slot for method without code " << m->PrettyMethod();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001478 return slot;
1479 }
Jeff Haob7cefc72013-11-14 14:51:09 -08001480 uint16_t ins_size = code_item->ins_size_;
1481 uint16_t locals_size = code_item->registers_size_ - ins_size;
1482 if (slot >= locals_size) {
1483 return slot - locals_size;
1484 } else {
1485 return slot + ins_size;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001486 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001487}
1488
Sebastien Hertzaef0c912016-08-08 10:20:28 +02001489static size_t GetMethodNumArgRegistersIncludingThis(ArtMethod* method)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001490 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertzaef0c912016-08-08 10:20:28 +02001491 uint32_t num_registers = ArtMethod::NumArgRegisters(method->GetShorty());
1492 if (!method->IsStatic()) {
1493 ++num_registers;
1494 }
1495 return num_registers;
1496}
1497
Jeff Haob7cefc72013-11-14 14:51:09 -08001498/*
1499 * Circularly shifts registers so that arguments come last. Reverts
1500 * slots to dex style argument placement.
1501 */
Mathieu Chartiere401d142015-04-22 13:56:20 -07001502static uint16_t DemangleSlot(uint16_t slot, ArtMethod* m, JDWP::JdwpError* error)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001503 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001504 const DexFile::CodeItem* code_item = m->GetCodeItem();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001505 if (code_item == nullptr) {
1506 // We should not get here for a method without code (native, proxy or abstract). Log it and
1507 // return the slot as is since all registers are arguments.
David Sehr709b0702016-10-13 09:12:37 -07001508 LOG(WARNING) << "Trying to demangle slot for method without code "
1509 << m->PrettyMethod();
Sebastien Hertzaef0c912016-08-08 10:20:28 +02001510 uint16_t vreg_count = GetMethodNumArgRegistersIncludingThis(m);
Sebastien Hertzabbabc82015-03-26 08:47:47 +01001511 if (slot < vreg_count) {
1512 *error = JDWP::ERR_NONE;
1513 return slot;
1514 }
Jeff Haob7cefc72013-11-14 14:51:09 -08001515 } else {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01001516 if (slot < code_item->registers_size_) {
1517 uint16_t ins_size = code_item->ins_size_;
1518 uint16_t locals_size = code_item->registers_size_ - ins_size;
1519 *error = JDWP::ERR_NONE;
1520 return (slot < ins_size) ? slot + locals_size : slot - ins_size;
1521 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001522 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01001523
1524 // Slot is invalid in the method.
David Sehr709b0702016-10-13 09:12:37 -07001525 LOG(ERROR) << "Invalid local slot " << slot << " for method " << m->PrettyMethod();
Sebastien Hertzabbabc82015-03-26 08:47:47 +01001526 *error = JDWP::ERR_INVALID_SLOT;
1527 return DexFile::kDexNoIndex16;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001528}
1529
Mathieu Chartier90443472015-07-16 20:32:27 -07001530JDWP::JdwpError Dbg::OutputDeclaredFields(JDWP::RefTypeId class_id, bool with_generic,
1531 JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001532 JDWP::JdwpError error;
1533 mirror::Class* c = DecodeClass(class_id, &error);
1534 if (c == nullptr) {
1535 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001536 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001537
1538 size_t instance_field_count = c->NumInstanceFields();
1539 size_t static_field_count = c->NumStaticFields();
1540
1541 expandBufAdd4BE(pReply, instance_field_count + static_field_count);
1542
1543 for (size_t i = 0; i < instance_field_count + static_field_count; ++i) {
Mathieu Chartier90443472015-07-16 20:32:27 -07001544 ArtField* f = (i < instance_field_count) ? c->GetInstanceField(i) :
1545 c->GetStaticField(i - instance_field_count);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001546 expandBufAddFieldId(pReply, ToFieldId(f));
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001547 expandBufAddUtf8String(pReply, f->GetName());
1548 expandBufAddUtf8String(pReply, f->GetTypeDescriptor());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001549 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001550 static const char genericSignature[1] = "";
1551 expandBufAddUtf8String(pReply, genericSignature);
1552 }
1553 expandBufAdd4BE(pReply, MangleAccessFlags(f->GetAccessFlags()));
1554 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001555 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001556}
1557
Elliott Hughes88d63092013-01-09 09:55:54 -08001558JDWP::JdwpError Dbg::OutputDeclaredMethods(JDWP::RefTypeId class_id, bool with_generic,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001559 JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001560 JDWP::JdwpError error;
1561 mirror::Class* c = DecodeClass(class_id, &error);
1562 if (c == nullptr) {
1563 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001564 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001565
Alex Light51a64d52015-12-17 13:55:59 -08001566 expandBufAdd4BE(pReply, c->NumMethods());
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001567
Mathieu Chartiere401d142015-04-22 13:56:20 -07001568 auto* cl = Runtime::Current()->GetClassLinker();
1569 auto ptr_size = cl->GetImagePointerSize();
Alex Light51a64d52015-12-17 13:55:59 -08001570 for (ArtMethod& m : c->GetMethods(ptr_size)) {
1571 expandBufAddMethodId(pReply, ToMethodId(&m));
Andreas Gampe542451c2016-07-26 09:02:02 -07001572 expandBufAddUtf8String(pReply, m.GetInterfaceMethodIfProxy(kRuntimePointerSize)->GetName());
1573 expandBufAddUtf8String(
1574 pReply, m.GetInterfaceMethodIfProxy(kRuntimePointerSize)->GetSignature().ToString());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001575 if (with_generic) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001576 const char* generic_signature = "";
1577 expandBufAddUtf8String(pReply, generic_signature);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001578 }
Alex Light51a64d52015-12-17 13:55:59 -08001579 expandBufAdd4BE(pReply, MangleAccessFlags(m.GetAccessFlags()));
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001580 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001581 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001582}
1583
Elliott Hughes88d63092013-01-09 09:55:54 -08001584JDWP::JdwpError Dbg::OutputDeclaredInterfaces(JDWP::RefTypeId class_id, JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001585 JDWP::JdwpError error;
Mathieu Chartierf8322842014-05-16 10:59:25 -07001586 Thread* self = Thread::Current();
Vladimir Marko19a4d372016-12-08 14:41:46 +00001587 ObjPtr<mirror::Class> c = DecodeClass(class_id, &error);
1588 if (c == nullptr) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001589 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001590 }
Mathieu Chartierf8322842014-05-16 10:59:25 -07001591 size_t interface_count = c->NumDirectInterfaces();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001592 expandBufAdd4BE(pReply, interface_count);
1593 for (size_t i = 0; i < interface_count; ++i) {
Vladimir Marko19a4d372016-12-08 14:41:46 +00001594 ObjPtr<mirror::Class> interface = mirror::Class::GetDirectInterface(self, c, i);
1595 DCHECK(interface != nullptr);
1596 expandBufAddRefTypeId(pReply, gRegistry->AddRefType(interface));
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001597 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001598 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001599}
1600
Ian Rogersc0542af2014-09-03 16:16:56 -07001601void Dbg::OutputLineTable(JDWP::RefTypeId, JDWP::MethodId method_id, JDWP::ExpandBuf* pReply) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001602 struct DebugCallbackContext {
1603 int numItems;
1604 JDWP::ExpandBuf* pReply;
1605
David Srbeckyb06e28e2015-12-10 13:15:00 +00001606 static bool Callback(void* context, const DexFile::PositionInfo& entry) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001607 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
David Srbeckyb06e28e2015-12-10 13:15:00 +00001608 expandBufAdd8BE(pContext->pReply, entry.address_);
1609 expandBufAdd4BE(pContext->pReply, entry.line_);
Elliott Hughes03181a82011-11-17 17:22:21 -08001610 pContext->numItems++;
Sebastien Hertzf2910ee2013-10-19 16:39:24 +02001611 return false;
Elliott Hughes03181a82011-11-17 17:22:21 -08001612 }
1613 };
Mathieu Chartiere401d142015-04-22 13:56:20 -07001614 ArtMethod* m = FromMethodId(method_id);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001615 const DexFile::CodeItem* code_item = m->GetCodeItem();
Elliott Hughes03181a82011-11-17 17:22:21 -08001616 uint64_t start, end;
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001617 if (code_item == nullptr) {
1618 DCHECK(m->IsNative() || m->IsProxyMethod());
Elliott Hughes03181a82011-11-17 17:22:21 -08001619 start = -1;
1620 end = -1;
1621 } else {
1622 start = 0;
jeffhao14f0db92012-12-14 17:50:42 -08001623 // Return the index of the last instruction
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001624 end = code_item->insns_size_in_code_units_ - 1;
Elliott Hughes03181a82011-11-17 17:22:21 -08001625 }
1626
1627 expandBufAdd8BE(pReply, start);
1628 expandBufAdd8BE(pReply, end);
1629
1630 // Add numLines later
1631 size_t numLinesOffset = expandBufGetLength(pReply);
1632 expandBufAdd4BE(pReply, 0);
1633
1634 DebugCallbackContext context;
1635 context.numItems = 0;
1636 context.pReply = pReply;
1637
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001638 if (code_item != nullptr) {
David Srbeckyb06e28e2015-12-10 13:15:00 +00001639 m->GetDexFile()->DecodeDebugPositionInfo(code_item, DebugCallbackContext::Callback, &context);
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001640 }
Elliott Hughes03181a82011-11-17 17:22:21 -08001641
1642 JDWP::Set4BE(expandBufGetBuffer(pReply) + numLinesOffset, context.numItems);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001643}
1644
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001645void Dbg::OutputVariableTable(JDWP::RefTypeId, JDWP::MethodId method_id, bool with_generic,
1646 JDWP::ExpandBuf* pReply) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001647 struct DebugCallbackContext {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001648 ArtMethod* method;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001649 JDWP::ExpandBuf* pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001650 size_t variable_count;
1651 bool with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001652
David Srbeckyb06e28e2015-12-10 13:15:00 +00001653 static void Callback(void* context, const DexFile::LocalInfo& entry)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001654 REQUIRES_SHARED(Locks::mutator_lock_) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001655 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
1656
David Srbeckyb06e28e2015-12-10 13:15:00 +00001657 uint16_t slot = entry.reg_;
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001658 VLOG(jdwp) << StringPrintf(" %2zd: %d(%d) '%s' '%s' '%s' actual slot=%d mangled slot=%d",
David Srbeckyb06e28e2015-12-10 13:15:00 +00001659 pContext->variable_count, entry.start_address_,
1660 entry.end_address_ - entry.start_address_,
1661 entry.name_, entry.descriptor_, entry.signature_, slot,
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001662 MangleSlot(slot, pContext->method));
Elliott Hughesdbb40792011-11-18 17:05:22 -08001663
Jeff Haob7cefc72013-11-14 14:51:09 -08001664 slot = MangleSlot(slot, pContext->method);
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001665
David Srbeckyb06e28e2015-12-10 13:15:00 +00001666 expandBufAdd8BE(pContext->pReply, entry.start_address_);
1667 expandBufAddUtf8String(pContext->pReply, entry.name_);
1668 expandBufAddUtf8String(pContext->pReply, entry.descriptor_);
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001669 if (pContext->with_generic) {
David Srbeckyb06e28e2015-12-10 13:15:00 +00001670 expandBufAddUtf8String(pContext->pReply, entry.signature_);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001671 }
David Srbeckyb06e28e2015-12-10 13:15:00 +00001672 expandBufAdd4BE(pContext->pReply, entry.end_address_- entry.start_address_);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001673 expandBufAdd4BE(pContext->pReply, slot);
1674
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001675 ++pContext->variable_count;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001676 }
1677 };
Mathieu Chartiere401d142015-04-22 13:56:20 -07001678 ArtMethod* m = FromMethodId(method_id);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001679
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001680 // arg_count considers doubles and longs to take 2 units.
1681 // variable_count considers everything to take 1 unit.
Sebastien Hertzaef0c912016-08-08 10:20:28 +02001682 expandBufAdd4BE(pReply, GetMethodNumArgRegistersIncludingThis(m));
Elliott Hughesdbb40792011-11-18 17:05:22 -08001683
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001684 // We don't know the total number of variables yet, so leave a blank and update it later.
1685 size_t variable_count_offset = expandBufGetLength(pReply);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001686 expandBufAdd4BE(pReply, 0);
1687
1688 DebugCallbackContext context;
Jeff Haob7cefc72013-11-14 14:51:09 -08001689 context.method = m;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001690 context.pReply = pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001691 context.variable_count = 0;
1692 context.with_generic = with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001693
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001694 const DexFile::CodeItem* code_item = m->GetCodeItem();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001695 if (code_item != nullptr) {
David Srbeckyb06e28e2015-12-10 13:15:00 +00001696 m->GetDexFile()->DecodeDebugLocalInfo(
1697 code_item, m->IsStatic(), m->GetDexMethodIndex(), DebugCallbackContext::Callback,
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001698 &context);
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001699 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001700
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001701 JDWP::Set4BE(expandBufGetBuffer(pReply) + variable_count_offset, context.variable_count);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001702}
1703
Jeff Hao579b0242013-11-18 13:16:49 -08001704void Dbg::OutputMethodReturnValue(JDWP::MethodId method_id, const JValue* return_value,
1705 JDWP::ExpandBuf* pReply) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001706 ArtMethod* m = FromMethodId(method_id);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001707 JDWP::JdwpTag tag = BasicTagFromDescriptor(m->GetShorty());
Jeff Hao579b0242013-11-18 13:16:49 -08001708 OutputJValue(tag, return_value, pReply);
1709}
1710
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02001711void Dbg::OutputFieldValue(JDWP::FieldId field_id, const JValue* field_value,
1712 JDWP::ExpandBuf* pReply) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001713 ArtField* f = FromFieldId(field_id);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001714 JDWP::JdwpTag tag = BasicTagFromDescriptor(f->GetTypeDescriptor());
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02001715 OutputJValue(tag, field_value, pReply);
1716}
1717
Elliott Hughes9777ba22013-01-17 09:04:19 -08001718JDWP::JdwpError Dbg::GetBytecodes(JDWP::RefTypeId, JDWP::MethodId method_id,
Ian Rogersc0542af2014-09-03 16:16:56 -07001719 std::vector<uint8_t>* bytecodes) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001720 ArtMethod* m = FromMethodId(method_id);
Ian Rogersc0542af2014-09-03 16:16:56 -07001721 if (m == nullptr) {
Elliott Hughes9777ba22013-01-17 09:04:19 -08001722 return JDWP::ERR_INVALID_METHODID;
1723 }
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001724 const DexFile::CodeItem* code_item = m->GetCodeItem();
Elliott Hughes9777ba22013-01-17 09:04:19 -08001725 size_t byte_count = code_item->insns_size_in_code_units_ * 2;
1726 const uint8_t* begin = reinterpret_cast<const uint8_t*>(code_item->insns_);
1727 const uint8_t* end = begin + byte_count;
1728 for (const uint8_t* p = begin; p != end; ++p) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001729 bytecodes->push_back(*p);
Elliott Hughes9777ba22013-01-17 09:04:19 -08001730 }
1731 return JDWP::ERR_NONE;
1732}
1733
Elliott Hughes88d63092013-01-09 09:55:54 -08001734JDWP::JdwpTag Dbg::GetFieldBasicTag(JDWP::FieldId field_id) {
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001735 return BasicTagFromDescriptor(FromFieldId(field_id)->GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001736}
1737
Elliott Hughes88d63092013-01-09 09:55:54 -08001738JDWP::JdwpTag Dbg::GetStaticFieldBasicTag(JDWP::FieldId field_id) {
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001739 return BasicTagFromDescriptor(FromFieldId(field_id)->GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001740}
1741
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001742static JValue GetArtFieldValue(ArtField* f, mirror::Object* o)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001743 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001744 Primitive::Type fieldType = f->GetTypeAsPrimitiveType();
1745 JValue field_value;
1746 switch (fieldType) {
1747 case Primitive::kPrimBoolean:
1748 field_value.SetZ(f->GetBoolean(o));
1749 return field_value;
1750
1751 case Primitive::kPrimByte:
1752 field_value.SetB(f->GetByte(o));
1753 return field_value;
1754
1755 case Primitive::kPrimChar:
1756 field_value.SetC(f->GetChar(o));
1757 return field_value;
1758
1759 case Primitive::kPrimShort:
1760 field_value.SetS(f->GetShort(o));
1761 return field_value;
1762
1763 case Primitive::kPrimInt:
1764 case Primitive::kPrimFloat:
1765 // Int and Float must be treated as 32-bit values in JDWP.
1766 field_value.SetI(f->GetInt(o));
1767 return field_value;
1768
1769 case Primitive::kPrimLong:
1770 case Primitive::kPrimDouble:
1771 // Long and Double must be treated as 64-bit values in JDWP.
1772 field_value.SetJ(f->GetLong(o));
1773 return field_value;
1774
1775 case Primitive::kPrimNot:
Mathieu Chartier1cc62e42016-10-03 18:01:28 -07001776 field_value.SetL(f->GetObject(o).Ptr());
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001777 return field_value;
1778
1779 case Primitive::kPrimVoid:
1780 LOG(FATAL) << "Attempt to read from field of type 'void'";
1781 UNREACHABLE();
1782 }
1783 LOG(FATAL) << "Attempt to read from field of unknown type";
1784 UNREACHABLE();
1785}
1786
Elliott Hughes88d63092013-01-09 09:55:54 -08001787static JDWP::JdwpError GetFieldValueImpl(JDWP::RefTypeId ref_type_id, JDWP::ObjectId object_id,
1788 JDWP::FieldId field_id, JDWP::ExpandBuf* pReply,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001789 bool is_static)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001790 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001791 JDWP::JdwpError error;
1792 mirror::Class* c = DecodeClass(ref_type_id, &error);
1793 if (ref_type_id != 0 && c == nullptr) {
1794 return error;
Elliott Hughes0cf74332012-02-23 23:14:00 -08001795 }
1796
Jeff Haode19a252016-09-14 15:56:35 -07001797 Thread* self = Thread::Current();
1798 StackHandleScope<2> hs(self);
1799 MutableHandle<mirror::Object>
1800 o(hs.NewHandle(Dbg::GetObjectRegistry()->Get<mirror::Object*>(object_id, &error)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08001801 if ((!is_static && o == nullptr) || error != JDWP::ERR_NONE) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001802 return JDWP::ERR_INVALID_OBJECT;
1803 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001804 ArtField* f = FromFieldId(field_id);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001805
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001806 mirror::Class* receiver_class = c;
Andreas Gampefa4333d2017-02-14 11:10:34 -08001807 if (receiver_class == nullptr && o != nullptr) {
Elliott Hughes0cf74332012-02-23 23:14:00 -08001808 receiver_class = o->GetClass();
1809 }
Jeff Haode19a252016-09-14 15:56:35 -07001810
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001811 // TODO: should we give up now if receiver_class is null?
Ian Rogersc0542af2014-09-03 16:16:56 -07001812 if (receiver_class != nullptr && !f->GetDeclaringClass()->IsAssignableFrom(receiver_class)) {
David Sehr709b0702016-10-13 09:12:37 -07001813 LOG(INFO) << "ERR_INVALID_FIELDID: " << f->PrettyField() << " "
1814 << receiver_class->PrettyClass();
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001815 return JDWP::ERR_INVALID_FIELDID;
1816 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001817
Jeff Haode19a252016-09-14 15:56:35 -07001818 // Ensure the field's class is initialized.
1819 Handle<mirror::Class> klass(hs.NewHandle(f->GetDeclaringClass()));
1820 if (!Runtime::Current()->GetClassLinker()->EnsureInitialized(self, klass, true, false)) {
David Sehr709b0702016-10-13 09:12:37 -07001821 LOG(WARNING) << "Not able to initialize class for SetValues: "
1822 << mirror::Class::PrettyClass(klass.Get());
Jeff Haode19a252016-09-14 15:56:35 -07001823 }
1824
Elliott Hughes0cf74332012-02-23 23:14:00 -08001825 // The RI only enforces the static/non-static mismatch in one direction.
1826 // TODO: should we change the tests and check both?
1827 if (is_static) {
1828 if (!f->IsStatic()) {
1829 return JDWP::ERR_INVALID_FIELDID;
1830 }
1831 } else {
1832 if (f->IsStatic()) {
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001833 LOG(WARNING) << "Ignoring non-nullptr receiver for ObjectReference.GetValues"
David Sehr709b0702016-10-13 09:12:37 -07001834 << " on static field " << f->PrettyField();
Elliott Hughes0cf74332012-02-23 23:14:00 -08001835 }
1836 }
jeffhao0dfbb7e2012-11-28 15:26:03 -08001837 if (f->IsStatic()) {
Jeff Haode19a252016-09-14 15:56:35 -07001838 o.Assign(f->GetDeclaringClass());
jeffhao0dfbb7e2012-11-28 15:26:03 -08001839 }
Elliott Hughes0cf74332012-02-23 23:14:00 -08001840
Jeff Haode19a252016-09-14 15:56:35 -07001841 JValue field_value(GetArtFieldValue(f, o.Get()));
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001842 JDWP::JdwpTag tag = BasicTagFromDescriptor(f->GetTypeDescriptor());
Jeff Hao579b0242013-11-18 13:16:49 -08001843 Dbg::OutputJValue(tag, &field_value, pReply);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001844 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001845}
1846
Elliott Hughes88d63092013-01-09 09:55:54 -08001847JDWP::JdwpError Dbg::GetFieldValue(JDWP::ObjectId object_id, JDWP::FieldId field_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001848 JDWP::ExpandBuf* pReply) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001849 return GetFieldValueImpl(0, object_id, field_id, pReply, false);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001850}
1851
Ian Rogersc0542af2014-09-03 16:16:56 -07001852JDWP::JdwpError Dbg::GetStaticFieldValue(JDWP::RefTypeId ref_type_id, JDWP::FieldId field_id,
1853 JDWP::ExpandBuf* pReply) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001854 return GetFieldValueImpl(ref_type_id, 0, field_id, pReply, true);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001855}
1856
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001857static JDWP::JdwpError SetArtFieldValue(ArtField* f, mirror::Object* o, uint64_t value, int width)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001858 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001859 Primitive::Type fieldType = f->GetTypeAsPrimitiveType();
1860 // Debugging only happens at runtime so we know we are not running in a transaction.
1861 static constexpr bool kNoTransactionMode = false;
1862 switch (fieldType) {
1863 case Primitive::kPrimBoolean:
1864 CHECK_EQ(width, 1);
1865 f->SetBoolean<kNoTransactionMode>(o, static_cast<uint8_t>(value));
1866 return JDWP::ERR_NONE;
1867
1868 case Primitive::kPrimByte:
1869 CHECK_EQ(width, 1);
1870 f->SetByte<kNoTransactionMode>(o, static_cast<uint8_t>(value));
1871 return JDWP::ERR_NONE;
1872
1873 case Primitive::kPrimChar:
1874 CHECK_EQ(width, 2);
1875 f->SetChar<kNoTransactionMode>(o, static_cast<uint16_t>(value));
1876 return JDWP::ERR_NONE;
1877
1878 case Primitive::kPrimShort:
1879 CHECK_EQ(width, 2);
1880 f->SetShort<kNoTransactionMode>(o, static_cast<int16_t>(value));
1881 return JDWP::ERR_NONE;
1882
1883 case Primitive::kPrimInt:
1884 case Primitive::kPrimFloat:
1885 CHECK_EQ(width, 4);
1886 // Int and Float must be treated as 32-bit values in JDWP.
1887 f->SetInt<kNoTransactionMode>(o, static_cast<int32_t>(value));
1888 return JDWP::ERR_NONE;
1889
1890 case Primitive::kPrimLong:
1891 case Primitive::kPrimDouble:
1892 CHECK_EQ(width, 8);
1893 // Long and Double must be treated as 64-bit values in JDWP.
1894 f->SetLong<kNoTransactionMode>(o, value);
1895 return JDWP::ERR_NONE;
1896
1897 case Primitive::kPrimNot: {
1898 JDWP::JdwpError error;
1899 mirror::Object* v = Dbg::GetObjectRegistry()->Get<mirror::Object*>(value, &error);
1900 if (error != JDWP::ERR_NONE) {
1901 return JDWP::ERR_INVALID_OBJECT;
1902 }
1903 if (v != nullptr) {
Mathieu Chartier3398c782016-09-30 10:27:43 -07001904 ObjPtr<mirror::Class> field_type;
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001905 {
1906 StackHandleScope<2> hs(Thread::Current());
1907 HandleWrapper<mirror::Object> h_v(hs.NewHandleWrapper(&v));
1908 HandleWrapper<mirror::Object> h_o(hs.NewHandleWrapper(&o));
1909 field_type = f->GetType<true>();
1910 }
1911 if (!field_type->IsAssignableFrom(v->GetClass())) {
1912 return JDWP::ERR_INVALID_OBJECT;
1913 }
1914 }
1915 f->SetObject<kNoTransactionMode>(o, v);
1916 return JDWP::ERR_NONE;
1917 }
1918
1919 case Primitive::kPrimVoid:
1920 LOG(FATAL) << "Attempt to write to field of type 'void'";
1921 UNREACHABLE();
1922 }
1923 LOG(FATAL) << "Attempt to write to field of unknown type";
1924 UNREACHABLE();
1925}
1926
Elliott Hughes88d63092013-01-09 09:55:54 -08001927static JDWP::JdwpError SetFieldValueImpl(JDWP::ObjectId object_id, JDWP::FieldId field_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001928 uint64_t value, int width, bool is_static)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001929 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001930 JDWP::JdwpError error;
Jeff Haode19a252016-09-14 15:56:35 -07001931 Thread* self = Thread::Current();
1932 StackHandleScope<2> hs(self);
1933 MutableHandle<mirror::Object>
1934 o(hs.NewHandle(Dbg::GetObjectRegistry()->Get<mirror::Object*>(object_id, &error)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08001935 if ((!is_static && o == nullptr) || error != JDWP::ERR_NONE) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001936 return JDWP::ERR_INVALID_OBJECT;
1937 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001938 ArtField* f = FromFieldId(field_id);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001939
Jeff Haode19a252016-09-14 15:56:35 -07001940 // Ensure the field's class is initialized.
1941 Handle<mirror::Class> klass(hs.NewHandle(f->GetDeclaringClass()));
1942 if (!Runtime::Current()->GetClassLinker()->EnsureInitialized(self, klass, true, false)) {
David Sehr709b0702016-10-13 09:12:37 -07001943 LOG(WARNING) << "Not able to initialize class for SetValues: "
1944 << mirror::Class::PrettyClass(klass.Get());
Jeff Haode19a252016-09-14 15:56:35 -07001945 }
1946
Elliott Hughes0cf74332012-02-23 23:14:00 -08001947 // The RI only enforces the static/non-static mismatch in one direction.
1948 // TODO: should we change the tests and check both?
1949 if (is_static) {
1950 if (!f->IsStatic()) {
1951 return JDWP::ERR_INVALID_FIELDID;
1952 }
1953 } else {
1954 if (f->IsStatic()) {
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001955 LOG(WARNING) << "Ignoring non-nullptr receiver for ObjectReference.SetValues"
David Sehr709b0702016-10-13 09:12:37 -07001956 << " on static field " << f->PrettyField();
Elliott Hughes0cf74332012-02-23 23:14:00 -08001957 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001958 }
jeffhao0dfbb7e2012-11-28 15:26:03 -08001959 if (f->IsStatic()) {
Jeff Haode19a252016-09-14 15:56:35 -07001960 o.Assign(f->GetDeclaringClass());
jeffhao0dfbb7e2012-11-28 15:26:03 -08001961 }
Jeff Haode19a252016-09-14 15:56:35 -07001962 return SetArtFieldValue(f, o.Get(), value, width);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001963}
1964
Elliott Hughes88d63092013-01-09 09:55:54 -08001965JDWP::JdwpError Dbg::SetFieldValue(JDWP::ObjectId object_id, JDWP::FieldId field_id, uint64_t value,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001966 int width) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001967 return SetFieldValueImpl(object_id, field_id, value, width, false);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001968}
1969
Elliott Hughes88d63092013-01-09 09:55:54 -08001970JDWP::JdwpError Dbg::SetStaticFieldValue(JDWP::FieldId field_id, uint64_t value, int width) {
1971 return SetFieldValueImpl(0, field_id, value, width, true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001972}
1973
Sebastien Hertzb0b0b492014-09-15 11:27:27 +02001974JDWP::JdwpError Dbg::StringToUtf8(JDWP::ObjectId string_id, std::string* str) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001975 JDWP::JdwpError error;
Sebastien Hertzb0b0b492014-09-15 11:27:27 +02001976 mirror::Object* obj = gRegistry->Get<mirror::Object*>(string_id, &error);
1977 if (error != JDWP::ERR_NONE) {
1978 return error;
1979 }
1980 if (obj == nullptr) {
1981 return JDWP::ERR_INVALID_OBJECT;
1982 }
1983 {
1984 ScopedObjectAccessUnchecked soa(Thread::Current());
Mathieu Chartier0795f232016-09-27 18:43:30 -07001985 ObjPtr<mirror::Class> java_lang_String =
1986 soa.Decode<mirror::Class>(WellKnownClasses::java_lang_String);
Sebastien Hertzb0b0b492014-09-15 11:27:27 +02001987 if (!java_lang_String->IsAssignableFrom(obj->GetClass())) {
1988 // This isn't a string.
1989 return JDWP::ERR_INVALID_STRING;
1990 }
1991 }
1992 *str = obj->AsString()->ToModifiedUtf8();
1993 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001994}
1995
Jeff Hao579b0242013-11-18 13:16:49 -08001996void Dbg::OutputJValue(JDWP::JdwpTag tag, const JValue* return_value, JDWP::ExpandBuf* pReply) {
1997 if (IsPrimitiveTag(tag)) {
1998 expandBufAdd1(pReply, tag);
1999 if (tag == JDWP::JT_BOOLEAN || tag == JDWP::JT_BYTE) {
2000 expandBufAdd1(pReply, return_value->GetI());
2001 } else if (tag == JDWP::JT_CHAR || tag == JDWP::JT_SHORT) {
2002 expandBufAdd2BE(pReply, return_value->GetI());
2003 } else if (tag == JDWP::JT_FLOAT || tag == JDWP::JT_INT) {
2004 expandBufAdd4BE(pReply, return_value->GetI());
2005 } else if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
2006 expandBufAdd8BE(pReply, return_value->GetJ());
2007 } else {
2008 CHECK_EQ(tag, JDWP::JT_VOID);
2009 }
2010 } else {
Ian Rogers98379392014-02-24 16:53:16 -08002011 ScopedObjectAccessUnchecked soa(Thread::Current());
Jeff Hao579b0242013-11-18 13:16:49 -08002012 mirror::Object* value = return_value->GetL();
Ian Rogers98379392014-02-24 16:53:16 -08002013 expandBufAdd1(pReply, TagFromObject(soa, value));
Jeff Hao579b0242013-11-18 13:16:49 -08002014 expandBufAddObjectId(pReply, gRegistry->Add(value));
2015 }
2016}
2017
Ian Rogersc0542af2014-09-03 16:16:56 -07002018JDWP::JdwpError Dbg::GetThreadName(JDWP::ObjectId thread_id, std::string* name) {
jeffhaoa77f0f62012-12-05 17:19:31 -08002019 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002020 JDWP::JdwpError error;
Roland Levillain4b8f1ec2015-08-26 18:34:03 +01002021 DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002022 if (error != JDWP::ERR_NONE && error != JDWP::ERR_THREAD_NOT_ALIVE) {
2023 return error;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08002024 }
Elliott Hughes221229c2013-01-08 18:17:50 -08002025
2026 // We still need to report the zombie threads' names, so we can't just call Thread::GetThreadName.
Ian Rogersc0542af2014-09-03 16:16:56 -07002027 mirror::Object* thread_object = gRegistry->Get<mirror::Object*>(thread_id, &error);
2028 CHECK(thread_object != nullptr) << error;
Mathieu Chartierc7853442015-03-27 14:35:38 -07002029 ArtField* java_lang_Thread_name_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08002030 jni::DecodeArtField(WellKnownClasses::java_lang_Thread_name);
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07002031 ObjPtr<mirror::String> s(java_lang_Thread_name_field->GetObject(thread_object)->AsString());
Ian Rogersc0542af2014-09-03 16:16:56 -07002032 if (s != nullptr) {
2033 *name = s->ToModifiedUtf8();
Elliott Hughes221229c2013-01-08 18:17:50 -08002034 }
2035 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002036}
2037
Elliott Hughes221229c2013-01-08 18:17:50 -08002038JDWP::JdwpError Dbg::GetThreadGroup(JDWP::ObjectId thread_id, JDWP::ExpandBuf* pReply) {
Sebastien Hertza06430c2014-09-15 19:21:30 +02002039 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002040 JDWP::JdwpError error;
2041 mirror::Object* thread_object = gRegistry->Get<mirror::Object*>(thread_id, &error);
2042 if (error != JDWP::ERR_NONE) {
Elliott Hughes2435a572012-02-17 16:07:41 -08002043 return JDWP::ERR_INVALID_OBJECT;
2044 }
Mathieu Chartier268764d2016-09-13 12:09:38 -07002045 ScopedAssertNoThreadSuspension ants("Debugger: GetThreadGroup");
Elliott Hughes2435a572012-02-17 16:07:41 -08002046 // Okay, so it's an object, but is it actually a thread?
Roland Levillain4b8f1ec2015-08-26 18:34:03 +01002047 DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002048 if (error == JDWP::ERR_THREAD_NOT_ALIVE) {
2049 // Zombie threads are in the null group.
2050 expandBufAddObjectId(pReply, JDWP::ObjectId(0));
Sebastien Hertz52d131d2014-03-13 16:17:40 +01002051 error = JDWP::ERR_NONE;
2052 } else if (error == JDWP::ERR_NONE) {
Mathieu Chartier0795f232016-09-27 18:43:30 -07002053 ObjPtr<mirror::Class> c = soa.Decode<mirror::Class>(WellKnownClasses::java_lang_Thread);
Sebastien Hertz52d131d2014-03-13 16:17:40 +01002054 CHECK(c != nullptr);
Andreas Gampe08883de2016-11-08 13:20:52 -08002055 ArtField* f = jni::DecodeArtField(WellKnownClasses::java_lang_Thread_group);
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07002056 CHECK(f != nullptr);
Mathieu Chartier3398c782016-09-30 10:27:43 -07002057 ObjPtr<mirror::Object> group = f->GetObject(thread_object);
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07002058 CHECK(group != nullptr);
Sebastien Hertz52d131d2014-03-13 16:17:40 +01002059 JDWP::ObjectId thread_group_id = gRegistry->Add(group);
2060 expandBufAddObjectId(pReply, thread_group_id);
Elliott Hughes221229c2013-01-08 18:17:50 -08002061 }
Sebastien Hertz52d131d2014-03-13 16:17:40 +01002062 return error;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002063}
2064
Sebastien Hertza06430c2014-09-15 19:21:30 +02002065static mirror::Object* DecodeThreadGroup(ScopedObjectAccessUnchecked& soa,
2066 JDWP::ObjectId thread_group_id, JDWP::JdwpError* error)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002067 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz6995c602014-09-09 12:10:13 +02002068 mirror::Object* thread_group = Dbg::GetObjectRegistry()->Get<mirror::Object*>(thread_group_id,
2069 error);
Sebastien Hertza06430c2014-09-15 19:21:30 +02002070 if (*error != JDWP::ERR_NONE) {
2071 return nullptr;
2072 }
2073 if (thread_group == nullptr) {
2074 *error = JDWP::ERR_INVALID_OBJECT;
2075 return nullptr;
2076 }
Mathieu Chartier0795f232016-09-27 18:43:30 -07002077 ObjPtr<mirror::Class> c =
2078 soa.Decode<mirror::Class>(WellKnownClasses::java_lang_ThreadGroup);
Ian Rogers98379392014-02-24 16:53:16 -08002079 CHECK(c != nullptr);
Sebastien Hertza06430c2014-09-15 19:21:30 +02002080 if (!c->IsAssignableFrom(thread_group->GetClass())) {
2081 // This is not a java.lang.ThreadGroup.
2082 *error = JDWP::ERR_INVALID_THREAD_GROUP;
2083 return nullptr;
2084 }
2085 *error = JDWP::ERR_NONE;
2086 return thread_group;
2087}
2088
2089JDWP::JdwpError Dbg::GetThreadGroupName(JDWP::ObjectId thread_group_id, JDWP::ExpandBuf* pReply) {
2090 ScopedObjectAccessUnchecked soa(Thread::Current());
2091 JDWP::JdwpError error;
2092 mirror::Object* thread_group = DecodeThreadGroup(soa, thread_group_id, &error);
2093 if (error != JDWP::ERR_NONE) {
2094 return error;
2095 }
Mathieu Chartier268764d2016-09-13 12:09:38 -07002096 ScopedAssertNoThreadSuspension ants("Debugger: GetThreadGroupName");
Andreas Gampe08883de2016-11-08 13:20:52 -08002097 ArtField* f = jni::DecodeArtField(WellKnownClasses::java_lang_ThreadGroup_name);
Ian Rogersc0542af2014-09-03 16:16:56 -07002098 CHECK(f != nullptr);
Mathieu Chartier3398c782016-09-30 10:27:43 -07002099 ObjPtr<mirror::String> s = f->GetObject(thread_group)->AsString();
Sebastien Hertza06430c2014-09-15 19:21:30 +02002100
2101 std::string thread_group_name(s->ToModifiedUtf8());
2102 expandBufAddUtf8String(pReply, thread_group_name);
2103 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002104}
2105
Sebastien Hertza06430c2014-09-15 19:21:30 +02002106JDWP::JdwpError Dbg::GetThreadGroupParent(JDWP::ObjectId thread_group_id, JDWP::ExpandBuf* pReply) {
Ian Rogers98379392014-02-24 16:53:16 -08002107 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002108 JDWP::JdwpError error;
Sebastien Hertza06430c2014-09-15 19:21:30 +02002109 mirror::Object* thread_group = DecodeThreadGroup(soa, thread_group_id, &error);
2110 if (error != JDWP::ERR_NONE) {
2111 return error;
2112 }
Mathieu Chartier3398c782016-09-30 10:27:43 -07002113 ObjPtr<mirror::Object> parent;
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07002114 {
Mathieu Chartier268764d2016-09-13 12:09:38 -07002115 ScopedAssertNoThreadSuspension ants("Debugger: GetThreadGroupParent");
Andreas Gampe08883de2016-11-08 13:20:52 -08002116 ArtField* f = jni::DecodeArtField(WellKnownClasses::java_lang_ThreadGroup_parent);
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07002117 CHECK(f != nullptr);
2118 parent = f->GetObject(thread_group);
2119 }
Sebastien Hertza06430c2014-09-15 19:21:30 +02002120 JDWP::ObjectId parent_group_id = gRegistry->Add(parent);
2121 expandBufAddObjectId(pReply, parent_group_id);
2122 return JDWP::ERR_NONE;
2123}
2124
Andreas Gampe08883de2016-11-08 13:20:52 -08002125static void GetChildThreadGroups(mirror::Object* thread_group,
Sebastien Hertza06430c2014-09-15 19:21:30 +02002126 std::vector<JDWP::ObjectId>* child_thread_group_ids)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002127 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertza06430c2014-09-15 19:21:30 +02002128 CHECK(thread_group != nullptr);
2129
Przemyslaw Szczepaniak464595f2015-11-24 11:59:59 +00002130 // Get the int "ngroups" count of this thread group...
Andreas Gampe08883de2016-11-08 13:20:52 -08002131 ArtField* ngroups_field = jni::DecodeArtField(WellKnownClasses::java_lang_ThreadGroup_ngroups);
Przemyslaw Szczepaniak464595f2015-11-24 11:59:59 +00002132 CHECK(ngroups_field != nullptr);
2133 const int32_t size = ngroups_field->GetInt(thread_group);
2134 if (size == 0) {
2135 return;
Sebastien Hertze49e1952014-10-13 11:27:13 +02002136 }
Sebastien Hertza06430c2014-09-15 19:21:30 +02002137
Przemyslaw Szczepaniak464595f2015-11-24 11:59:59 +00002138 // Get the ThreadGroup[] "groups" out of this thread group...
Andreas Gampe08883de2016-11-08 13:20:52 -08002139 ArtField* groups_field = jni::DecodeArtField(WellKnownClasses::java_lang_ThreadGroup_groups);
Mathieu Chartier3398c782016-09-30 10:27:43 -07002140 ObjPtr<mirror::Object> groups_array = groups_field->GetObject(thread_group);
Przemyslaw Szczepaniak464595f2015-11-24 11:59:59 +00002141
2142 CHECK(groups_array != nullptr);
2143 CHECK(groups_array->IsObjectArray());
2144
Mathieu Chartier3398c782016-09-30 10:27:43 -07002145 ObjPtr<mirror::ObjectArray<mirror::Object>> groups_array_as_array =
Przemyslaw Szczepaniak464595f2015-11-24 11:59:59 +00002146 groups_array->AsObjectArray<mirror::Object>();
Sebastien Hertza06430c2014-09-15 19:21:30 +02002147
2148 // Copy the first 'size' elements out of the array into the result.
Sebastien Hertz6995c602014-09-09 12:10:13 +02002149 ObjectRegistry* registry = Dbg::GetObjectRegistry();
Sebastien Hertza06430c2014-09-15 19:21:30 +02002150 for (int32_t i = 0; i < size; ++i) {
Przemyslaw Szczepaniak464595f2015-11-24 11:59:59 +00002151 child_thread_group_ids->push_back(registry->Add(groups_array_as_array->Get(i)));
Sebastien Hertza06430c2014-09-15 19:21:30 +02002152 }
2153}
2154
2155JDWP::JdwpError Dbg::GetThreadGroupChildren(JDWP::ObjectId thread_group_id,
2156 JDWP::ExpandBuf* pReply) {
2157 ScopedObjectAccessUnchecked soa(Thread::Current());
2158 JDWP::JdwpError error;
2159 mirror::Object* thread_group = DecodeThreadGroup(soa, thread_group_id, &error);
2160 if (error != JDWP::ERR_NONE) {
2161 return error;
2162 }
2163
2164 // Add child threads.
2165 {
2166 std::vector<JDWP::ObjectId> child_thread_ids;
2167 GetThreads(thread_group, &child_thread_ids);
2168 expandBufAdd4BE(pReply, child_thread_ids.size());
2169 for (JDWP::ObjectId child_thread_id : child_thread_ids) {
2170 expandBufAddObjectId(pReply, child_thread_id);
2171 }
2172 }
2173
2174 // Add child thread groups.
2175 {
2176 std::vector<JDWP::ObjectId> child_thread_groups_ids;
Andreas Gampe08883de2016-11-08 13:20:52 -08002177 GetChildThreadGroups(thread_group, &child_thread_groups_ids);
Sebastien Hertza06430c2014-09-15 19:21:30 +02002178 expandBufAdd4BE(pReply, child_thread_groups_ids.size());
2179 for (JDWP::ObjectId child_thread_group_id : child_thread_groups_ids) {
2180 expandBufAddObjectId(pReply, child_thread_group_id);
2181 }
2182 }
2183
2184 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002185}
2186
2187JDWP::ObjectId Dbg::GetSystemThreadGroupId() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002188 ScopedObjectAccessUnchecked soa(Thread::Current());
Andreas Gampe08883de2016-11-08 13:20:52 -08002189 ArtField* f = jni::DecodeArtField(WellKnownClasses::java_lang_ThreadGroup_systemThreadGroup);
Mathieu Chartier3398c782016-09-30 10:27:43 -07002190 ObjPtr<mirror::Object> group = f->GetObject(f->GetDeclaringClass());
Ian Rogers365c1022012-06-22 15:05:28 -07002191 return gRegistry->Add(group);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002192}
2193
Jeff Hao920af3e2013-08-28 15:46:38 -07002194JDWP::JdwpThreadStatus Dbg::ToJdwpThreadStatus(ThreadState state) {
2195 switch (state) {
2196 case kBlocked:
2197 return JDWP::TS_MONITOR;
2198 case kNative:
2199 case kRunnable:
2200 case kSuspended:
2201 return JDWP::TS_RUNNING;
2202 case kSleeping:
2203 return JDWP::TS_SLEEPING;
2204 case kStarting:
2205 case kTerminated:
2206 return JDWP::TS_ZOMBIE;
2207 case kTimedWaiting:
Sebastien Hertzbae182c2013-12-17 10:42:03 +01002208 case kWaitingForCheckPointsToRun:
Jeff Hao920af3e2013-08-28 15:46:38 -07002209 case kWaitingForDebuggerSend:
2210 case kWaitingForDebuggerSuspension:
2211 case kWaitingForDebuggerToAttach:
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002212 case kWaitingForDeoptimization:
Jeff Hao920af3e2013-08-28 15:46:38 -07002213 case kWaitingForGcToComplete:
Mathieu Chartierb43390c2015-05-12 10:47:11 -07002214 case kWaitingForGetObjectsAllocated:
Jeff Hao920af3e2013-08-28 15:46:38 -07002215 case kWaitingForJniOnLoad:
Sebastien Hertzbae182c2013-12-17 10:42:03 +01002216 case kWaitingForMethodTracingStart:
Jeff Hao920af3e2013-08-28 15:46:38 -07002217 case kWaitingForSignalCatcherOutput:
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -08002218 case kWaitingForVisitObjects:
Jeff Hao920af3e2013-08-28 15:46:38 -07002219 case kWaitingInMainDebuggerLoop:
2220 case kWaitingInMainSignalCatcherLoop:
2221 case kWaitingPerformingGc:
Mathieu Chartier90ef3db2015-08-04 15:19:41 -07002222 case kWaitingWeakGcRootRead:
Hiroshi Yamauchi76f55b02015-08-21 16:10:39 -07002223 case kWaitingForGcThreadFlip:
Jeff Hao920af3e2013-08-28 15:46:38 -07002224 case kWaiting:
2225 return JDWP::TS_WAIT;
2226 // Don't add a 'default' here so the compiler can spot incompatible enum changes.
2227 }
2228 LOG(FATAL) << "Unknown thread state: " << state;
2229 return JDWP::TS_ZOMBIE;
2230}
2231
Sebastien Hertz52d131d2014-03-13 16:17:40 +01002232JDWP::JdwpError Dbg::GetThreadStatus(JDWP::ObjectId thread_id, JDWP::JdwpThreadStatus* pThreadStatus,
2233 JDWP::JdwpSuspendStatus* pSuspendStatus) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002234 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes499c5132011-11-17 14:55:11 -08002235
Elliott Hughes9e0c1752013-01-09 14:02:58 -08002236 *pSuspendStatus = JDWP::SUSPEND_STATUS_NOT_SUSPENDED;
2237
Ian Rogersc0542af2014-09-03 16:16:56 -07002238 JDWP::JdwpError error;
2239 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002240 if (error != JDWP::ERR_NONE) {
2241 if (error == JDWP::ERR_THREAD_NOT_ALIVE) {
2242 *pThreadStatus = JDWP::TS_ZOMBIE;
Elliott Hughes221229c2013-01-08 18:17:50 -08002243 return JDWP::ERR_NONE;
2244 }
2245 return error;
Elliott Hughes499c5132011-11-17 14:55:11 -08002246 }
2247
Elliott Hughes9e0c1752013-01-09 14:02:58 -08002248 if (IsSuspendedForDebugger(soa, thread)) {
2249 *pSuspendStatus = JDWP::SUSPEND_STATUS_SUSPENDED;
Elliott Hughes499c5132011-11-17 14:55:11 -08002250 }
2251
Jeff Hao920af3e2013-08-28 15:46:38 -07002252 *pThreadStatus = ToJdwpThreadStatus(thread->GetState());
Elliott Hughes221229c2013-01-08 18:17:50 -08002253 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002254}
2255
Elliott Hughes221229c2013-01-08 18:17:50 -08002256JDWP::JdwpError Dbg::GetThreadDebugSuspendCount(JDWP::ObjectId thread_id, JDWP::ExpandBuf* pReply) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002257 ScopedObjectAccess soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002258 JDWP::JdwpError error;
2259 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002260 if (error != JDWP::ERR_NONE) {
2261 return error;
Elliott Hughes2435a572012-02-17 16:07:41 -08002262 }
Ian Rogers50b35e22012-10-04 10:09:15 -07002263 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002264 expandBufAdd4BE(pReply, thread->GetDebugSuspendCount());
Elliott Hughes2435a572012-02-17 16:07:41 -08002265 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002266}
2267
Elliott Hughesf9501702013-01-11 11:22:27 -08002268JDWP::JdwpError Dbg::Interrupt(JDWP::ObjectId thread_id) {
2269 ScopedObjectAccess soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002270 JDWP::JdwpError error;
2271 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughesf9501702013-01-11 11:22:27 -08002272 if (error != JDWP::ERR_NONE) {
2273 return error;
2274 }
Ian Rogersdd7624d2014-03-14 17:43:00 -07002275 thread->Interrupt(soa.Self());
Elliott Hughesf9501702013-01-11 11:22:27 -08002276 return JDWP::ERR_NONE;
2277}
2278
Andreas Gampe08883de2016-11-08 13:20:52 -08002279static bool IsInDesiredThreadGroup(mirror::Object* desired_thread_group, mirror::Object* peer)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002280 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz070f7322014-09-09 12:08:49 +02002281 // Do we want threads from all thread groups?
2282 if (desired_thread_group == nullptr) {
2283 return true;
2284 }
Andreas Gampe08883de2016-11-08 13:20:52 -08002285 ArtField* thread_group_field = jni::DecodeArtField(WellKnownClasses::java_lang_Thread_group);
Sebastien Hertz070f7322014-09-09 12:08:49 +02002286 DCHECK(thread_group_field != nullptr);
Mathieu Chartier3398c782016-09-30 10:27:43 -07002287 ObjPtr<mirror::Object> group = thread_group_field->GetObject(peer);
Sebastien Hertz070f7322014-09-09 12:08:49 +02002288 return (group == desired_thread_group);
2289}
2290
Sebastien Hertza06430c2014-09-15 19:21:30 +02002291void Dbg::GetThreads(mirror::Object* thread_group, std::vector<JDWP::ObjectId>* thread_ids) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002292 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz070f7322014-09-09 12:08:49 +02002293 std::list<Thread*> all_threads_list;
2294 {
2295 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
2296 all_threads_list = Runtime::Current()->GetThreadList()->GetList();
2297 }
2298 for (Thread* t : all_threads_list) {
2299 if (t == Dbg::GetDebugThread()) {
2300 // Skip the JDWP thread. Some debuggers get bent out of shape when they can't suspend and
2301 // query all threads, so it's easier if we just don't tell them about this thread.
2302 continue;
2303 }
2304 if (t->IsStillStarting()) {
2305 // This thread is being started (and has been registered in the thread list). However, it is
2306 // not completely started yet so we must ignore it.
2307 continue;
2308 }
Nicolas Geoffraycafa0812017-02-15 18:27:34 +00002309 mirror::Object* peer = t->GetPeerFromOtherThread();
Sebastien Hertz070f7322014-09-09 12:08:49 +02002310 if (peer == nullptr) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002311 // 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 +02002312 // this thread yet.
2313 // TODO: if we identified threads to the debugger by their Thread*
2314 // rather than their peer's mirror::Object*, we could fix this.
2315 // Doing so might help us report ZOMBIE threads too.
2316 continue;
2317 }
Andreas Gampe08883de2016-11-08 13:20:52 -08002318 if (IsInDesiredThreadGroup(thread_group, peer)) {
Sebastien Hertz070f7322014-09-09 12:08:49 +02002319 thread_ids->push_back(gRegistry->Add(peer));
2320 }
2321 }
Elliott Hughescaf76542012-06-28 16:08:22 -07002322}
Elliott Hughesa2155262011-11-16 16:26:58 -08002323
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002324static int GetStackDepth(Thread* thread) REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002325 struct CountStackDepthVisitor : public StackVisitor {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002326 explicit CountStackDepthVisitor(Thread* thread_in)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01002327 : StackVisitor(thread_in, nullptr, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
2328 depth(0) {}
Ian Rogers0399dde2012-06-06 17:09:28 -07002329
Elliott Hughes64f574f2013-02-20 14:57:12 -08002330 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2331 // annotalysis.
2332 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07002333 if (!GetMethod()->IsRuntimeMethod()) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -08002334 ++depth;
2335 }
Elliott Hughes530fa002012-03-12 11:44:49 -07002336 return true;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08002337 }
2338 size_t depth;
2339 };
Elliott Hughes08fc03a2012-06-26 17:34:00 -07002340
Ian Rogers7a22fa62013-01-23 12:16:16 -08002341 CountStackDepthVisitor visitor(thread);
Ian Rogers0399dde2012-06-06 17:09:28 -07002342 visitor.WalkStack();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08002343 return visitor.depth;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002344}
2345
Ian Rogersc0542af2014-09-03 16:16:56 -07002346JDWP::JdwpError Dbg::GetThreadFrameCount(JDWP::ObjectId thread_id, size_t* result) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002347 ScopedObjectAccess soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002348 JDWP::JdwpError error;
2349 *result = 0;
2350 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002351 if (error != JDWP::ERR_NONE) {
2352 return error;
2353 }
Elliott Hughesf15f4a02013-01-09 10:09:38 -08002354 if (!IsSuspendedForDebugger(soa, thread)) {
2355 return JDWP::ERR_THREAD_NOT_SUSPENDED;
2356 }
Ian Rogersc0542af2014-09-03 16:16:56 -07002357 *result = GetStackDepth(thread);
Elliott Hughes221229c2013-01-08 18:17:50 -08002358 return JDWP::ERR_NONE;
Elliott Hughes86964332012-02-15 19:37:42 -08002359}
2360
Ian Rogers306057f2012-11-26 12:45:53 -08002361JDWP::JdwpError Dbg::GetThreadFrames(JDWP::ObjectId thread_id, size_t start_frame,
2362 size_t frame_count, JDWP::ExpandBuf* buf) {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002363 class GetFrameVisitor : public StackVisitor {
2364 public:
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002365 GetFrameVisitor(Thread* thread, size_t start_frame_in, size_t frame_count_in,
2366 JDWP::ExpandBuf* buf_in)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002367 REQUIRES_SHARED(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01002368 : StackVisitor(thread, nullptr, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
2369 depth_(0),
2370 start_frame_(start_frame_in),
2371 frame_count_(frame_count_in),
2372 buf_(buf_in) {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002373 expandBufAdd4BE(buf_, frame_count_);
Elliott Hughes03181a82011-11-17 17:22:21 -08002374 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002375
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002376 bool VisitFrame() OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002377 if (GetMethod()->IsRuntimeMethod()) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07002378 return true; // The debugger can't do anything useful with a frame that has no Method*.
Elliott Hughes03181a82011-11-17 17:22:21 -08002379 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002380 if (depth_ >= start_frame_ + frame_count_) {
Elliott Hughes530fa002012-03-12 11:44:49 -07002381 return false;
Elliott Hughes03181a82011-11-17 17:22:21 -08002382 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002383 if (depth_ >= start_frame_) {
2384 JDWP::FrameId frame_id(GetFrameId());
2385 JDWP::JdwpLocation location;
Sebastien Hertz6995c602014-09-09 12:10:13 +02002386 SetJdwpLocation(&location, GetMethod(), GetDexPc());
Ian Rogersef7d42f2014-01-06 12:55:46 -08002387 VLOG(jdwp) << StringPrintf(" Frame %3zd: id=%3" PRIu64 " ", depth_, frame_id) << location;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002388 expandBufAdd8BE(buf_, frame_id);
2389 expandBufAddLocation(buf_, location);
2390 }
2391 ++depth_;
Elliott Hughes530fa002012-03-12 11:44:49 -07002392 return true;
Elliott Hughes03181a82011-11-17 17:22:21 -08002393 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002394
2395 private:
2396 size_t depth_;
2397 const size_t start_frame_;
2398 const size_t frame_count_;
2399 JDWP::ExpandBuf* buf_;
Elliott Hughes03181a82011-11-17 17:22:21 -08002400 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002401
2402 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002403 JDWP::JdwpError error;
2404 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002405 if (error != JDWP::ERR_NONE) {
2406 return error;
2407 }
Elliott Hughesf15f4a02013-01-09 10:09:38 -08002408 if (!IsSuspendedForDebugger(soa, thread)) {
2409 return JDWP::ERR_THREAD_NOT_SUSPENDED;
2410 }
Ian Rogers7a22fa62013-01-23 12:16:16 -08002411 GetFrameVisitor visitor(thread, start_frame, frame_count, buf);
Ian Rogers0399dde2012-06-06 17:09:28 -07002412 visitor.WalkStack();
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002413 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002414}
2415
2416JDWP::ObjectId Dbg::GetThreadSelfId() {
Sebastien Hertz6995c602014-09-09 12:10:13 +02002417 return GetThreadId(Thread::Current());
2418}
2419
2420JDWP::ObjectId Dbg::GetThreadId(Thread* thread) {
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07002421 ScopedObjectAccessUnchecked soa(Thread::Current());
Nicolas Geoffraycafa0812017-02-15 18:27:34 +00002422 return gRegistry->Add(thread->GetPeerFromOtherThread());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002423}
2424
Elliott Hughes475fc232011-10-25 15:00:35 -07002425void Dbg::SuspendVM() {
Hiroshi Yamauchi8f95cf32016-04-19 11:14:06 -07002426 // Avoid a deadlock between GC and debugger where GC gets suspended during GC. b/25800335.
2427 gc::ScopedGCCriticalSection gcs(Thread::Current(),
2428 gc::kGcCauseDebugger,
2429 gc::kCollectorTypeDebugger);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002430 Runtime::Current()->GetThreadList()->SuspendAllForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002431}
2432
2433void Dbg::ResumeVM() {
Sebastien Hertz253fa552014-10-14 17:27:15 +02002434 Runtime::Current()->GetThreadList()->ResumeAllForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002435}
2436
Elliott Hughes221229c2013-01-08 18:17:50 -08002437JDWP::JdwpError Dbg::SuspendThread(JDWP::ObjectId thread_id, bool request_suspension) {
Ian Rogersf3d874c2014-07-17 18:52:42 -07002438 Thread* self = Thread::Current();
Ian Rogersc0542af2014-09-03 16:16:56 -07002439 ScopedLocalRef<jobject> peer(self->GetJniEnv(), nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002440 {
Ian Rogersf3d874c2014-07-17 18:52:42 -07002441 ScopedObjectAccess soa(self);
Ian Rogersc0542af2014-09-03 16:16:56 -07002442 JDWP::JdwpError error;
2443 peer.reset(soa.AddLocalReference<jobject>(gRegistry->Get<mirror::Object*>(thread_id, &error)));
Elliott Hughes4e235312011-12-02 11:34:15 -08002444 }
Ian Rogersc0542af2014-09-03 16:16:56 -07002445 if (peer.get() == nullptr) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002446 return JDWP::ERR_THREAD_NOT_ALIVE;
2447 }
Ian Rogers4ad5cd32014-11-11 23:08:07 -08002448 // Suspend thread to build stack trace.
Elliott Hughesf327e072013-01-09 16:01:26 -08002449 bool timed_out;
Brian Carlstromba32de42014-08-27 23:43:46 -07002450 ThreadList* thread_list = Runtime::Current()->GetThreadList();
Sebastien Hertzcdd798d2017-04-18 18:28:51 +02002451 Thread* thread = thread_list->SuspendThreadByPeer(peer.get(),
2452 request_suspension,
Alex Light46f93402017-06-29 11:59:50 -07002453 SuspendReason::kForDebugger,
Brian Carlstromba32de42014-08-27 23:43:46 -07002454 &timed_out);
Ian Rogersc0542af2014-09-03 16:16:56 -07002455 if (thread != nullptr) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002456 return JDWP::ERR_NONE;
Elliott Hughesf327e072013-01-09 16:01:26 -08002457 } else if (timed_out) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002458 return JDWP::ERR_INTERNAL;
2459 } else {
2460 return JDWP::ERR_THREAD_NOT_ALIVE;
2461 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002462}
2463
Elliott Hughes221229c2013-01-08 18:17:50 -08002464void Dbg::ResumeThread(JDWP::ObjectId thread_id) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002465 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002466 JDWP::JdwpError error;
2467 mirror::Object* peer = gRegistry->Get<mirror::Object*>(thread_id, &error);
2468 CHECK(peer != nullptr) << error;
jeffhaoa77f0f62012-12-05 17:19:31 -08002469 Thread* thread;
2470 {
2471 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
2472 thread = Thread::FromManagedThread(soa, peer);
2473 }
Ian Rogersc0542af2014-09-03 16:16:56 -07002474 if (thread == nullptr) {
Elliott Hughes4e235312011-12-02 11:34:15 -08002475 LOG(WARNING) << "No such thread for resume: " << peer;
2476 return;
2477 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002478 bool needs_resume;
2479 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002480 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Sebastien Hertz70d60272017-04-14 14:18:36 +02002481 needs_resume = thread->GetDebugSuspendCount() > 0;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002482 }
2483 if (needs_resume) {
Alex Light88fd7202017-06-30 08:31:59 -07002484 bool resumed = Runtime::Current()->GetThreadList()->Resume(thread, SuspendReason::kForDebugger);
2485 DCHECK(resumed);
Elliott Hughes546b9862012-06-20 16:06:13 -07002486 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002487}
2488
2489void Dbg::SuspendSelf() {
Elliott Hughes475fc232011-10-25 15:00:35 -07002490 Runtime::Current()->GetThreadList()->SuspendSelfForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002491}
2492
Ian Rogers0399dde2012-06-06 17:09:28 -07002493struct GetThisVisitor : public StackVisitor {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002494 GetThisVisitor(Thread* thread, Context* context, JDWP::FrameId frame_id_in)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002495 REQUIRES_SHARED(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01002496 : StackVisitor(thread, context, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
2497 this_object(nullptr),
2498 frame_id(frame_id_in) {}
Ian Rogers0399dde2012-06-06 17:09:28 -07002499
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002500 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2501 // annotalysis.
2502 virtual bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002503 if (frame_id != GetFrameId()) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002504 return true; // continue
Ian Rogers0399dde2012-06-06 17:09:28 -07002505 } else {
Ian Rogers62d6c772013-02-27 08:32:07 -08002506 this_object = GetThisObject();
2507 return false;
Ian Rogers0399dde2012-06-06 17:09:28 -07002508 }
Elliott Hughes86b00102011-12-05 17:54:26 -08002509 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002510
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002511 mirror::Object* this_object;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002512 JDWP::FrameId frame_id;
Ian Rogers0399dde2012-06-06 17:09:28 -07002513};
2514
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002515JDWP::JdwpError Dbg::GetThisObject(JDWP::ObjectId thread_id, JDWP::FrameId frame_id,
2516 JDWP::ObjectId* result) {
2517 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz69206392015-04-07 15:54:25 +02002518 JDWP::JdwpError error;
2519 Thread* thread = DecodeThread(soa, thread_id, &error);
2520 if (error != JDWP::ERR_NONE) {
2521 return error;
2522 }
2523 if (!IsSuspendedForDebugger(soa, thread)) {
2524 return JDWP::ERR_THREAD_NOT_SUSPENDED;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002525 }
Ian Rogers700a4022014-05-19 16:49:03 -07002526 std::unique_ptr<Context> context(Context::Create());
Ian Rogers7a22fa62013-01-23 12:16:16 -08002527 GetThisVisitor visitor(thread, context.get(), frame_id);
Ian Rogers0399dde2012-06-06 17:09:28 -07002528 visitor.WalkStack();
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002529 *result = gRegistry->Add(visitor.this_object);
2530 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002531}
2532
Sebastien Hertz8009f392014-09-01 17:07:11 +02002533// Walks the stack until we find the frame with the given FrameId.
2534class FindFrameVisitor FINAL : public StackVisitor {
2535 public:
2536 FindFrameVisitor(Thread* thread, Context* context, JDWP::FrameId frame_id)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002537 REQUIRES_SHARED(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01002538 : StackVisitor(thread, context, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
2539 frame_id_(frame_id),
2540 error_(JDWP::ERR_INVALID_FRAMEID) {}
Ian Rogersca190662012-06-26 15:45:57 -07002541
Sebastien Hertz8009f392014-09-01 17:07:11 +02002542 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2543 // annotalysis.
2544 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
2545 if (GetFrameId() != frame_id_) {
2546 return true; // Not our frame, carry on.
Ian Rogers0399dde2012-06-06 17:09:28 -07002547 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07002548 ArtMethod* m = GetMethod();
Sebastien Hertz8009f392014-09-01 17:07:11 +02002549 if (m->IsNative()) {
2550 // We can't read/write local value from/into native method.
2551 error_ = JDWP::ERR_OPAQUE_FRAME;
2552 } else {
2553 // We found our frame.
2554 error_ = JDWP::ERR_NONE;
2555 }
2556 return false;
2557 }
2558
2559 JDWP::JdwpError GetError() const {
2560 return error_;
2561 }
2562
2563 private:
2564 const JDWP::FrameId frame_id_;
2565 JDWP::JdwpError error_;
Sebastien Hertz26f72862015-09-15 09:52:07 +02002566
2567 DISALLOW_COPY_AND_ASSIGN(FindFrameVisitor);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002568};
2569
2570JDWP::JdwpError Dbg::GetLocalValues(JDWP::Request* request, JDWP::ExpandBuf* pReply) {
2571 JDWP::ObjectId thread_id = request->ReadThreadId();
2572 JDWP::FrameId frame_id = request->ReadFrameId();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002573
2574 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz69206392015-04-07 15:54:25 +02002575 JDWP::JdwpError error;
2576 Thread* thread = DecodeThread(soa, thread_id, &error);
2577 if (error != JDWP::ERR_NONE) {
2578 return error;
2579 }
2580 if (!IsSuspendedForDebugger(soa, thread)) {
2581 return JDWP::ERR_THREAD_NOT_SUSPENDED;
Elliott Hughes221229c2013-01-08 18:17:50 -08002582 }
Sebastien Hertz8009f392014-09-01 17:07:11 +02002583 // Find the frame with the given frame_id.
Ian Rogers700a4022014-05-19 16:49:03 -07002584 std::unique_ptr<Context> context(Context::Create());
Sebastien Hertz8009f392014-09-01 17:07:11 +02002585 FindFrameVisitor visitor(thread, context.get(), frame_id);
Ian Rogers0399dde2012-06-06 17:09:28 -07002586 visitor.WalkStack();
Sebastien Hertz8009f392014-09-01 17:07:11 +02002587 if (visitor.GetError() != JDWP::ERR_NONE) {
2588 return visitor.GetError();
2589 }
2590
2591 // Read the values from visitor's context.
2592 int32_t slot_count = request->ReadSigned32("slot count");
2593 expandBufAdd4BE(pReply, slot_count); /* "int values" */
2594 for (int32_t i = 0; i < slot_count; ++i) {
2595 uint32_t slot = request->ReadUnsigned32("slot");
2596 JDWP::JdwpTag reqSigByte = request->ReadTag();
2597
2598 VLOG(jdwp) << " --> slot " << slot << " " << reqSigByte;
2599
2600 size_t width = Dbg::GetTagWidth(reqSigByte);
Sebastien Hertz7d955652014-10-22 10:57:10 +02002601 uint8_t* ptr = expandBufAddSpace(pReply, width + 1);
Sebastien Hertz69206392015-04-07 15:54:25 +02002602 error = Dbg::GetLocalValue(visitor, soa, slot, reqSigByte, ptr, width);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002603 if (error != JDWP::ERR_NONE) {
2604 return error;
2605 }
2606 }
2607 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002608}
2609
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002610constexpr JDWP::JdwpError kStackFrameLocalAccessError = JDWP::ERR_ABSENT_INFORMATION;
2611
2612static std::string GetStackContextAsString(const StackVisitor& visitor)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002613 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002614 return StringPrintf(" at DEX pc 0x%08x in method %s", visitor.GetDexPc(false),
David Sehr709b0702016-10-13 09:12:37 -07002615 ArtMethod::PrettyMethod(visitor.GetMethod()).c_str());
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002616}
2617
2618static JDWP::JdwpError FailGetLocalValue(const StackVisitor& visitor, uint16_t vreg,
2619 JDWP::JdwpTag tag)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002620 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002621 LOG(ERROR) << "Failed to read " << tag << " local from register v" << vreg
2622 << GetStackContextAsString(visitor);
2623 return kStackFrameLocalAccessError;
2624}
2625
Sebastien Hertz8009f392014-09-01 17:07:11 +02002626JDWP::JdwpError Dbg::GetLocalValue(const StackVisitor& visitor, ScopedObjectAccessUnchecked& soa,
2627 int slot, JDWP::JdwpTag tag, uint8_t* buf, size_t width) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002628 ArtMethod* m = visitor.GetMethod();
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002629 JDWP::JdwpError error = JDWP::ERR_NONE;
2630 uint16_t vreg = DemangleSlot(slot, m, &error);
2631 if (error != JDWP::ERR_NONE) {
2632 return error;
2633 }
Sebastien Hertz8009f392014-09-01 17:07:11 +02002634 // TODO: check that the tag is compatible with the actual type of the slot!
Sebastien Hertz8009f392014-09-01 17:07:11 +02002635 switch (tag) {
2636 case JDWP::JT_BOOLEAN: {
2637 CHECK_EQ(width, 1U);
2638 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002639 if (!visitor.GetVReg(m, vreg, kIntVReg, &intVal)) {
2640 return FailGetLocalValue(visitor, vreg, tag);
Ian Rogers0399dde2012-06-06 17:09:28 -07002641 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002642 VLOG(jdwp) << "get boolean local " << vreg << " = " << intVal;
2643 JDWP::Set1(buf + 1, intVal != 0);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002644 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002645 }
Sebastien Hertz8009f392014-09-01 17:07:11 +02002646 case JDWP::JT_BYTE: {
2647 CHECK_EQ(width, 1U);
2648 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002649 if (!visitor.GetVReg(m, vreg, kIntVReg, &intVal)) {
2650 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002651 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002652 VLOG(jdwp) << "get byte local " << vreg << " = " << intVal;
2653 JDWP::Set1(buf + 1, intVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002654 break;
2655 }
2656 case JDWP::JT_SHORT:
2657 case JDWP::JT_CHAR: {
2658 CHECK_EQ(width, 2U);
2659 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002660 if (!visitor.GetVReg(m, vreg, kIntVReg, &intVal)) {
2661 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002662 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002663 VLOG(jdwp) << "get short/char local " << vreg << " = " << intVal;
2664 JDWP::Set2BE(buf + 1, intVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002665 break;
2666 }
2667 case JDWP::JT_INT: {
2668 CHECK_EQ(width, 4U);
2669 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002670 if (!visitor.GetVReg(m, vreg, kIntVReg, &intVal)) {
2671 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002672 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002673 VLOG(jdwp) << "get int local " << vreg << " = " << intVal;
2674 JDWP::Set4BE(buf + 1, intVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002675 break;
2676 }
2677 case JDWP::JT_FLOAT: {
2678 CHECK_EQ(width, 4U);
2679 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002680 if (!visitor.GetVReg(m, vreg, kFloatVReg, &intVal)) {
2681 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002682 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002683 VLOG(jdwp) << "get float local " << vreg << " = " << intVal;
2684 JDWP::Set4BE(buf + 1, intVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002685 break;
2686 }
2687 case JDWP::JT_ARRAY:
2688 case JDWP::JT_CLASS_LOADER:
2689 case JDWP::JT_CLASS_OBJECT:
2690 case JDWP::JT_OBJECT:
2691 case JDWP::JT_STRING:
2692 case JDWP::JT_THREAD:
2693 case JDWP::JT_THREAD_GROUP: {
2694 CHECK_EQ(width, sizeof(JDWP::ObjectId));
2695 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002696 if (!visitor.GetVReg(m, vreg, kReferenceVReg, &intVal)) {
2697 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002698 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002699 mirror::Object* o = reinterpret_cast<mirror::Object*>(intVal);
2700 VLOG(jdwp) << "get " << tag << " object local " << vreg << " = " << o;
2701 if (!Runtime::Current()->GetHeap()->IsValidObjectAddress(o)) {
2702 LOG(FATAL) << StringPrintf("Found invalid object %#" PRIxPTR " in register v%u",
2703 reinterpret_cast<uintptr_t>(o), vreg)
2704 << GetStackContextAsString(visitor);
2705 UNREACHABLE();
2706 }
2707 tag = TagFromObject(soa, o);
2708 JDWP::SetObjectId(buf + 1, gRegistry->Add(o));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002709 break;
2710 }
2711 case JDWP::JT_DOUBLE: {
2712 CHECK_EQ(width, 8U);
2713 uint64_t longVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002714 if (!visitor.GetVRegPair(m, vreg, kDoubleLoVReg, kDoubleHiVReg, &longVal)) {
2715 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002716 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002717 VLOG(jdwp) << "get double local " << vreg << " = " << longVal;
2718 JDWP::Set8BE(buf + 1, longVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002719 break;
2720 }
2721 case JDWP::JT_LONG: {
2722 CHECK_EQ(width, 8U);
2723 uint64_t longVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002724 if (!visitor.GetVRegPair(m, vreg, kLongLoVReg, kLongHiVReg, &longVal)) {
2725 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002726 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002727 VLOG(jdwp) << "get long local " << vreg << " = " << longVal;
2728 JDWP::Set8BE(buf + 1, longVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002729 break;
2730 }
2731 default:
2732 LOG(FATAL) << "Unknown tag " << tag;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002733 UNREACHABLE();
Sebastien Hertz8009f392014-09-01 17:07:11 +02002734 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002735
Sebastien Hertz8009f392014-09-01 17:07:11 +02002736 // Prepend tag, which may have been updated.
2737 JDWP::Set1(buf, tag);
2738 return JDWP::ERR_NONE;
2739}
2740
2741JDWP::JdwpError Dbg::SetLocalValues(JDWP::Request* request) {
2742 JDWP::ObjectId thread_id = request->ReadThreadId();
2743 JDWP::FrameId frame_id = request->ReadFrameId();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002744
2745 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz69206392015-04-07 15:54:25 +02002746 JDWP::JdwpError error;
2747 Thread* thread = DecodeThread(soa, thread_id, &error);
2748 if (error != JDWP::ERR_NONE) {
2749 return error;
2750 }
2751 if (!IsSuspendedForDebugger(soa, thread)) {
2752 return JDWP::ERR_THREAD_NOT_SUSPENDED;
Elliott Hughes221229c2013-01-08 18:17:50 -08002753 }
Sebastien Hertz8009f392014-09-01 17:07:11 +02002754 // Find the frame with the given frame_id.
Ian Rogers700a4022014-05-19 16:49:03 -07002755 std::unique_ptr<Context> context(Context::Create());
Sebastien Hertz8009f392014-09-01 17:07:11 +02002756 FindFrameVisitor visitor(thread, context.get(), frame_id);
Ian Rogers0399dde2012-06-06 17:09:28 -07002757 visitor.WalkStack();
Sebastien Hertz8009f392014-09-01 17:07:11 +02002758 if (visitor.GetError() != JDWP::ERR_NONE) {
2759 return visitor.GetError();
2760 }
2761
2762 // Writes the values into visitor's context.
2763 int32_t slot_count = request->ReadSigned32("slot count");
2764 for (int32_t i = 0; i < slot_count; ++i) {
2765 uint32_t slot = request->ReadUnsigned32("slot");
2766 JDWP::JdwpTag sigByte = request->ReadTag();
2767 size_t width = Dbg::GetTagWidth(sigByte);
2768 uint64_t value = request->ReadValue(width);
2769
2770 VLOG(jdwp) << " --> slot " << slot << " " << sigByte << " " << value;
Mingyao Yang99170c62015-07-06 11:10:37 -07002771 error = Dbg::SetLocalValue(thread, visitor, slot, sigByte, value, width);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002772 if (error != JDWP::ERR_NONE) {
2773 return error;
2774 }
2775 }
2776 return JDWP::ERR_NONE;
2777}
2778
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002779template<typename T>
2780static JDWP::JdwpError FailSetLocalValue(const StackVisitor& visitor, uint16_t vreg,
2781 JDWP::JdwpTag tag, T value)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002782 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002783 LOG(ERROR) << "Failed to write " << tag << " local " << value
2784 << " (0x" << std::hex << value << ") into register v" << vreg
2785 << GetStackContextAsString(visitor);
2786 return kStackFrameLocalAccessError;
2787}
2788
Mingyao Yang99170c62015-07-06 11:10:37 -07002789JDWP::JdwpError Dbg::SetLocalValue(Thread* thread, StackVisitor& visitor, int slot,
2790 JDWP::JdwpTag tag, uint64_t value, size_t width) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002791 ArtMethod* m = visitor.GetMethod();
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002792 JDWP::JdwpError error = JDWP::ERR_NONE;
2793 uint16_t vreg = DemangleSlot(slot, m, &error);
2794 if (error != JDWP::ERR_NONE) {
2795 return error;
2796 }
Sebastien Hertz8009f392014-09-01 17:07:11 +02002797 // TODO: check that the tag is compatible with the actual type of the slot!
Sebastien Hertz8009f392014-09-01 17:07:11 +02002798 switch (tag) {
2799 case JDWP::JT_BOOLEAN:
2800 case JDWP::JT_BYTE:
2801 CHECK_EQ(width, 1U);
Mingyao Yang636b9252015-07-31 16:40:24 -07002802 if (!visitor.SetVReg(m, vreg, static_cast<uint32_t>(value), kIntVReg)) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002803 return FailSetLocalValue(visitor, vreg, tag, static_cast<uint32_t>(value));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002804 }
2805 break;
2806 case JDWP::JT_SHORT:
2807 case JDWP::JT_CHAR:
2808 CHECK_EQ(width, 2U);
Mingyao Yang636b9252015-07-31 16:40:24 -07002809 if (!visitor.SetVReg(m, vreg, static_cast<uint32_t>(value), kIntVReg)) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002810 return FailSetLocalValue(visitor, vreg, tag, static_cast<uint32_t>(value));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002811 }
2812 break;
2813 case JDWP::JT_INT:
2814 CHECK_EQ(width, 4U);
Mingyao Yang636b9252015-07-31 16:40:24 -07002815 if (!visitor.SetVReg(m, vreg, static_cast<uint32_t>(value), kIntVReg)) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002816 return FailSetLocalValue(visitor, vreg, tag, static_cast<uint32_t>(value));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002817 }
2818 break;
2819 case JDWP::JT_FLOAT:
2820 CHECK_EQ(width, 4U);
Mingyao Yang636b9252015-07-31 16:40:24 -07002821 if (!visitor.SetVReg(m, vreg, static_cast<uint32_t>(value), kFloatVReg)) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002822 return FailSetLocalValue(visitor, vreg, tag, static_cast<uint32_t>(value));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002823 }
2824 break;
2825 case JDWP::JT_ARRAY:
2826 case JDWP::JT_CLASS_LOADER:
2827 case JDWP::JT_CLASS_OBJECT:
2828 case JDWP::JT_OBJECT:
2829 case JDWP::JT_STRING:
2830 case JDWP::JT_THREAD:
2831 case JDWP::JT_THREAD_GROUP: {
2832 CHECK_EQ(width, sizeof(JDWP::ObjectId));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002833 mirror::Object* o = gRegistry->Get<mirror::Object*>(static_cast<JDWP::ObjectId>(value),
2834 &error);
2835 if (error != JDWP::ERR_NONE) {
2836 VLOG(jdwp) << tag << " object " << o << " is an invalid object";
2837 return JDWP::ERR_INVALID_OBJECT;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002838 }
Mingyao Yang636b9252015-07-31 16:40:24 -07002839 if (!visitor.SetVReg(m, vreg, static_cast<uint32_t>(reinterpret_cast<uintptr_t>(o)),
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002840 kReferenceVReg)) {
2841 return FailSetLocalValue(visitor, vreg, tag, reinterpret_cast<uintptr_t>(o));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002842 }
2843 break;
2844 }
2845 case JDWP::JT_DOUBLE: {
2846 CHECK_EQ(width, 8U);
Mingyao Yang636b9252015-07-31 16:40:24 -07002847 if (!visitor.SetVRegPair(m, vreg, value, kDoubleLoVReg, kDoubleHiVReg)) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002848 return FailSetLocalValue(visitor, vreg, tag, value);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002849 }
2850 break;
2851 }
2852 case JDWP::JT_LONG: {
2853 CHECK_EQ(width, 8U);
Mingyao Yang636b9252015-07-31 16:40:24 -07002854 if (!visitor.SetVRegPair(m, vreg, value, kLongLoVReg, kLongHiVReg)) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002855 return FailSetLocalValue(visitor, vreg, tag, value);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002856 }
2857 break;
2858 }
2859 default:
2860 LOG(FATAL) << "Unknown tag " << tag;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002861 UNREACHABLE();
Sebastien Hertz8009f392014-09-01 17:07:11 +02002862 }
Mingyao Yang99170c62015-07-06 11:10:37 -07002863
2864 // If we set the local variable in a compiled frame, we need to trigger a deoptimization of
2865 // the stack so we continue execution with the interpreter using the new value(s) of the updated
2866 // local variable(s). To achieve this, we install instrumentation exit stub on each method of the
2867 // thread's stack. The stub will cause the deoptimization to happen.
2868 if (!visitor.IsShadowFrame() && thread->HasDebuggerShadowFrames()) {
2869 Runtime::Current()->GetInstrumentation()->InstrumentThreadStack(thread);
2870 }
2871
Sebastien Hertz8009f392014-09-01 17:07:11 +02002872 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002873}
2874
Mathieu Chartiere401d142015-04-22 13:56:20 -07002875static void SetEventLocation(JDWP::EventLocation* location, ArtMethod* m, uint32_t dex_pc)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002876 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz6995c602014-09-09 12:10:13 +02002877 DCHECK(location != nullptr);
2878 if (m == nullptr) {
2879 memset(location, 0, sizeof(*location));
2880 } else {
Alex Light97e78032017-06-27 17:51:55 -07002881 location->method = m->GetCanonicalMethod(kRuntimePointerSize);
Sebastien Hertz6995c602014-09-09 12:10:13 +02002882 location->dex_pc = (m->IsNative() || m->IsProxyMethod()) ? static_cast<uint32_t>(-1) : dex_pc;
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002883 }
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002884}
2885
Mathieu Chartiere401d142015-04-22 13:56:20 -07002886void Dbg::PostLocationEvent(ArtMethod* m, int dex_pc, mirror::Object* this_object,
Jeff Hao579b0242013-11-18 13:16:49 -08002887 int event_flags, const JValue* return_value) {
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002888 if (!IsDebuggerActive()) {
2889 return;
2890 }
2891 DCHECK(m != nullptr);
2892 DCHECK_EQ(m->IsStatic(), this_object == nullptr);
Sebastien Hertz6995c602014-09-09 12:10:13 +02002893 JDWP::EventLocation location;
2894 SetEventLocation(&location, m, dex_pc);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002895
Sebastien Hertzde48aa62015-05-26 11:53:39 +02002896 // We need to be sure no exception is pending when calling JdwpState::PostLocationEvent.
2897 // This is required to be able to call JNI functions to create JDWP ids. To achieve this,
2898 // we temporarily clear the current thread's exception (if any) and will restore it after
2899 // the call.
2900 // Note: the only way to get a pending exception here is to suspend on a move-exception
2901 // instruction.
2902 Thread* const self = Thread::Current();
2903 StackHandleScope<1> hs(self);
2904 Handle<mirror::Throwable> pending_exception(hs.NewHandle(self->GetException()));
2905 self->ClearException();
Andreas Gampefa4333d2017-02-14 11:10:34 -08002906 if (kIsDebugBuild && pending_exception != nullptr) {
Sebastien Hertzde48aa62015-05-26 11:53:39 +02002907 const DexFile::CodeItem* code_item = location.method->GetCodeItem();
2908 const Instruction* instr = Instruction::At(&code_item->insns_[location.dex_pc]);
2909 CHECK_EQ(Instruction::MOVE_EXCEPTION, instr->Opcode());
2910 }
2911
Sebastien Hertz6995c602014-09-09 12:10:13 +02002912 gJdwpState->PostLocationEvent(&location, this_object, event_flags, return_value);
Sebastien Hertzde48aa62015-05-26 11:53:39 +02002913
Andreas Gampefa4333d2017-02-14 11:10:34 -08002914 if (pending_exception != nullptr) {
Sebastien Hertzde48aa62015-05-26 11:53:39 +02002915 self->SetException(pending_exception.Get());
2916 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002917}
2918
Mathieu Chartiere401d142015-04-22 13:56:20 -07002919void Dbg::PostFieldAccessEvent(ArtMethod* m, int dex_pc,
Mathieu Chartierc7853442015-03-27 14:35:38 -07002920 mirror::Object* this_object, ArtField* f) {
Alex Lighte00ec302017-06-16 08:56:43 -07002921 // TODO We should send events for native methods.
2922 if (!IsDebuggerActive() || m->IsNative()) {
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002923 return;
2924 }
2925 DCHECK(m != nullptr);
2926 DCHECK(f != nullptr);
Sebastien Hertz6995c602014-09-09 12:10:13 +02002927 JDWP::EventLocation location;
2928 SetEventLocation(&location, m, dex_pc);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002929
Sebastien Hertz6995c602014-09-09 12:10:13 +02002930 gJdwpState->PostFieldEvent(&location, f, this_object, nullptr, false);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002931}
2932
Mathieu Chartiere401d142015-04-22 13:56:20 -07002933void Dbg::PostFieldModificationEvent(ArtMethod* m, int dex_pc,
Mathieu Chartierc7853442015-03-27 14:35:38 -07002934 mirror::Object* this_object, ArtField* f,
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002935 const JValue* field_value) {
Alex Lighte00ec302017-06-16 08:56:43 -07002936 // TODO We should send events for native methods.
2937 if (!IsDebuggerActive() || m->IsNative()) {
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002938 return;
2939 }
2940 DCHECK(m != nullptr);
2941 DCHECK(f != nullptr);
2942 DCHECK(field_value != nullptr);
Sebastien Hertz6995c602014-09-09 12:10:13 +02002943 JDWP::EventLocation location;
2944 SetEventLocation(&location, m, dex_pc);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002945
Sebastien Hertz6995c602014-09-09 12:10:13 +02002946 gJdwpState->PostFieldEvent(&location, f, this_object, field_value, true);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002947}
2948
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002949/**
2950 * Finds the location where this exception will be caught. We search until we reach the top
2951 * frame, in which case this exception is considered uncaught.
2952 */
2953class CatchLocationFinder : public StackVisitor {
2954 public:
2955 CatchLocationFinder(Thread* self, const Handle<mirror::Throwable>& exception, Context* context)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002956 REQUIRES_SHARED(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01002957 : StackVisitor(self, context, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002958 exception_(exception),
2959 handle_scope_(self),
2960 this_at_throw_(handle_scope_.NewHandle<mirror::Object>(nullptr)),
Mathieu Chartiere401d142015-04-22 13:56:20 -07002961 catch_method_(nullptr),
2962 throw_method_(nullptr),
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002963 catch_dex_pc_(DexFile::kDexNoIndex),
2964 throw_dex_pc_(DexFile::kDexNoIndex) {
2965 }
2966
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002967 bool VisitFrame() OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002968 ArtMethod* method = GetMethod();
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002969 DCHECK(method != nullptr);
2970 if (method->IsRuntimeMethod()) {
2971 // Ignore callee save method.
2972 DCHECK(method->IsCalleeSaveMethod());
2973 return true;
2974 }
2975
2976 uint32_t dex_pc = GetDexPc();
Mathieu Chartiere401d142015-04-22 13:56:20 -07002977 if (throw_method_ == nullptr) {
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002978 // First Java method found. It is either the method that threw the exception,
2979 // or the Java native method that is reporting an exception thrown by
2980 // native code.
2981 this_at_throw_.Assign(GetThisObject());
Mathieu Chartiere401d142015-04-22 13:56:20 -07002982 throw_method_ = method;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002983 throw_dex_pc_ = dex_pc;
2984 }
2985
2986 if (dex_pc != DexFile::kDexNoIndex) {
Sebastien Hertz26f72862015-09-15 09:52:07 +02002987 StackHandleScope<1> hs(GetThread());
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002988 uint32_t found_dex_pc;
2989 Handle<mirror::Class> exception_class(hs.NewHandle(exception_->GetClass()));
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002990 bool unused_clear_exception;
Mathieu Chartiere401d142015-04-22 13:56:20 -07002991 found_dex_pc = method->FindCatchBlock(exception_class, dex_pc, &unused_clear_exception);
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002992 if (found_dex_pc != DexFile::kDexNoIndex) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002993 catch_method_ = method;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002994 catch_dex_pc_ = found_dex_pc;
2995 return false; // End stack walk.
2996 }
2997 }
2998 return true; // Continue stack walk.
2999 }
3000
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003001 ArtMethod* GetCatchMethod() REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003002 return catch_method_;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003003 }
3004
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003005 ArtMethod* GetThrowMethod() REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003006 return throw_method_;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003007 }
3008
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003009 mirror::Object* GetThisAtThrow() REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003010 return this_at_throw_.Get();
3011 }
3012
3013 uint32_t GetCatchDexPc() const {
3014 return catch_dex_pc_;
3015 }
3016
3017 uint32_t GetThrowDexPc() const {
3018 return throw_dex_pc_;
3019 }
3020
3021 private:
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003022 const Handle<mirror::Throwable>& exception_;
Mathieu Chartiere401d142015-04-22 13:56:20 -07003023 StackHandleScope<1> handle_scope_;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003024 MutableHandle<mirror::Object> this_at_throw_;
Mathieu Chartiere401d142015-04-22 13:56:20 -07003025 ArtMethod* catch_method_;
3026 ArtMethod* throw_method_;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003027 uint32_t catch_dex_pc_;
3028 uint32_t throw_dex_pc_;
3029
3030 DISALLOW_COPY_AND_ASSIGN(CatchLocationFinder);
3031};
3032
3033void Dbg::PostException(mirror::Throwable* exception_object) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07003034 if (!IsDebuggerActive()) {
Ian Rogers0ad5bb82011-12-07 10:16:32 -08003035 return;
3036 }
Sebastien Hertz261bc042015-04-08 09:36:07 +02003037 Thread* const self = Thread::Current();
3038 StackHandleScope<1> handle_scope(self);
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003039 Handle<mirror::Throwable> h_exception(handle_scope.NewHandle(exception_object));
3040 std::unique_ptr<Context> context(Context::Create());
Sebastien Hertz261bc042015-04-08 09:36:07 +02003041 CatchLocationFinder clf(self, h_exception, context.get());
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003042 clf.WalkStack(/* include_transitions */ false);
Sebastien Hertz6995c602014-09-09 12:10:13 +02003043 JDWP::EventLocation exception_throw_location;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003044 SetEventLocation(&exception_throw_location, clf.GetThrowMethod(), clf.GetThrowDexPc());
Sebastien Hertz6995c602014-09-09 12:10:13 +02003045 JDWP::EventLocation exception_catch_location;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003046 SetEventLocation(&exception_catch_location, clf.GetCatchMethod(), clf.GetCatchDexPc());
Elliott Hughes4740cdf2011-12-07 14:07:12 -08003047
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003048 gJdwpState->PostException(&exception_throw_location, h_exception.Get(), &exception_catch_location,
3049 clf.GetThisAtThrow());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003050}
3051
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003052void Dbg::PostClassPrepare(mirror::Class* c) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07003053 if (!IsDebuggerActive()) {
Elliott Hughes4740cdf2011-12-07 14:07:12 -08003054 return;
3055 }
Sebastien Hertz6995c602014-09-09 12:10:13 +02003056 gJdwpState->PostClassPrepare(c);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003057}
3058
Ian Rogers62d6c772013-02-27 08:32:07 -08003059void Dbg::UpdateDebugger(Thread* thread, mirror::Object* this_object,
Mathieu Chartiere401d142015-04-22 13:56:20 -07003060 ArtMethod* m, uint32_t dex_pc,
Sebastien Hertz8379b222014-02-24 17:38:15 +01003061 int event_flags, const JValue* return_value) {
Ian Rogers62d6c772013-02-27 08:32:07 -08003062 if (!IsDebuggerActive() || dex_pc == static_cast<uint32_t>(-2) /* fake method exit */) {
Elliott Hughes2aa2e392012-02-17 17:15:43 -08003063 return;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003064 }
3065
Elliott Hughes86964332012-02-15 19:37:42 -08003066 if (IsBreakpoint(m, dex_pc)) {
3067 event_flags |= kBreakpoint;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003068 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003069
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003070 // If the debugger is single-stepping one of our threads, check to
3071 // see if we're that thread and we've reached a step point.
3072 const SingleStepControl* single_step_control = thread->GetSingleStepControl();
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003073 if (single_step_control != nullptr) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003074 CHECK(!m->IsNative());
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003075 if (single_step_control->GetStepDepth() == JDWP::SD_INTO) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003076 // Step into method calls. We break when the line number
3077 // or method pointer changes. If we're in SS_MIN mode, we
3078 // always stop.
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003079 if (single_step_control->GetMethod() != m) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003080 event_flags |= kSingleStep;
3081 VLOG(jdwp) << "SS new method";
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003082 } else if (single_step_control->GetStepSize() == JDWP::SS_MIN) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003083 event_flags |= kSingleStep;
3084 VLOG(jdwp) << "SS new instruction";
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003085 } else if (single_step_control->ContainsDexPc(dex_pc)) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003086 event_flags |= kSingleStep;
3087 VLOG(jdwp) << "SS new line";
3088 }
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003089 } else if (single_step_control->GetStepDepth() == JDWP::SD_OVER) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003090 // Step over method calls. We break when the line number is
3091 // different and the frame depth is <= the original frame
3092 // depth. (We can't just compare on the method, because we
3093 // might get unrolled past it by an exception, and it's tricky
3094 // to identify recursion.)
3095
3096 int stack_depth = GetStackDepth(thread);
3097
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003098 if (stack_depth < single_step_control->GetStackDepth()) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003099 // Popped up one or more frames, always trigger.
3100 event_flags |= kSingleStep;
3101 VLOG(jdwp) << "SS method pop";
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003102 } else if (stack_depth == single_step_control->GetStackDepth()) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003103 // Same depth, see if we moved.
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003104 if (single_step_control->GetStepSize() == JDWP::SS_MIN) {
Elliott Hughes86964332012-02-15 19:37:42 -08003105 event_flags |= kSingleStep;
3106 VLOG(jdwp) << "SS new instruction";
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003107 } else if (single_step_control->ContainsDexPc(dex_pc)) {
Elliott Hughes2435a572012-02-17 16:07:41 -08003108 event_flags |= kSingleStep;
3109 VLOG(jdwp) << "SS new line";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003110 }
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003111 }
3112 } else {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003113 CHECK_EQ(single_step_control->GetStepDepth(), JDWP::SD_OUT);
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003114 // Return from the current method. We break when the frame
3115 // depth pops up.
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003116
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003117 // This differs from the "method exit" break in that it stops
3118 // with the PC at the next instruction in the returned-to
3119 // function, rather than the end of the returning function.
Elliott Hughes86964332012-02-15 19:37:42 -08003120
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003121 int stack_depth = GetStackDepth(thread);
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003122 if (stack_depth < single_step_control->GetStackDepth()) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003123 event_flags |= kSingleStep;
3124 VLOG(jdwp) << "SS method pop";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003125 }
3126 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003127 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003128
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003129 // If there's something interesting going on, see if it matches one
3130 // of the debugger filters.
3131 if (event_flags != 0) {
Sebastien Hertz8379b222014-02-24 17:38:15 +01003132 Dbg::PostLocationEvent(m, dex_pc, this_object, event_flags, return_value);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003133 }
3134}
3135
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003136size_t* Dbg::GetReferenceCounterForEvent(uint32_t instrumentation_event) {
3137 switch (instrumentation_event) {
3138 case instrumentation::Instrumentation::kMethodEntered:
3139 return &method_enter_event_ref_count_;
3140 case instrumentation::Instrumentation::kMethodExited:
3141 return &method_exit_event_ref_count_;
3142 case instrumentation::Instrumentation::kDexPcMoved:
3143 return &dex_pc_change_event_ref_count_;
3144 case instrumentation::Instrumentation::kFieldRead:
3145 return &field_read_event_ref_count_;
3146 case instrumentation::Instrumentation::kFieldWritten:
3147 return &field_write_event_ref_count_;
3148 case instrumentation::Instrumentation::kExceptionCaught:
3149 return &exception_catch_event_ref_count_;
3150 default:
3151 return nullptr;
3152 }
3153}
3154
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003155// Process request while all mutator threads are suspended.
3156void Dbg::ProcessDeoptimizationRequest(const DeoptimizationRequest& request) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003157 instrumentation::Instrumentation* instrumentation = Runtime::Current()->GetInstrumentation();
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003158 switch (request.GetKind()) {
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003159 case DeoptimizationRequest::kNothing:
3160 LOG(WARNING) << "Ignoring empty deoptimization request.";
3161 break;
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003162 case DeoptimizationRequest::kRegisterForEvent:
3163 VLOG(jdwp) << StringPrintf("Add debugger as listener for instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003164 request.InstrumentationEvent());
3165 instrumentation->AddListener(&gDebugInstrumentationListener, request.InstrumentationEvent());
3166 instrumentation_events_ |= request.InstrumentationEvent();
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003167 break;
3168 case DeoptimizationRequest::kUnregisterForEvent:
3169 VLOG(jdwp) << StringPrintf("Remove debugger as listener for instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003170 request.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003171 instrumentation->RemoveListener(&gDebugInstrumentationListener,
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003172 request.InstrumentationEvent());
3173 instrumentation_events_ &= ~request.InstrumentationEvent();
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003174 break;
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003175 case DeoptimizationRequest::kFullDeoptimization:
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003176 VLOG(jdwp) << "Deoptimize the world ...";
Sebastien Hertz0462c4c2015-04-01 16:34:17 +02003177 instrumentation->DeoptimizeEverything(kDbgInstrumentationKey);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003178 VLOG(jdwp) << "Deoptimize the world DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003179 break;
3180 case DeoptimizationRequest::kFullUndeoptimization:
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003181 VLOG(jdwp) << "Undeoptimize the world ...";
Sebastien Hertz0462c4c2015-04-01 16:34:17 +02003182 instrumentation->UndeoptimizeEverything(kDbgInstrumentationKey);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003183 VLOG(jdwp) << "Undeoptimize the world DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003184 break;
3185 case DeoptimizationRequest::kSelectiveDeoptimization:
David Sehr709b0702016-10-13 09:12:37 -07003186 VLOG(jdwp) << "Deoptimize method " << ArtMethod::PrettyMethod(request.Method()) << " ...";
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003187 instrumentation->Deoptimize(request.Method());
David Sehr709b0702016-10-13 09:12:37 -07003188 VLOG(jdwp) << "Deoptimize method " << ArtMethod::PrettyMethod(request.Method()) << " DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003189 break;
3190 case DeoptimizationRequest::kSelectiveUndeoptimization:
David Sehr709b0702016-10-13 09:12:37 -07003191 VLOG(jdwp) << "Undeoptimize method " << ArtMethod::PrettyMethod(request.Method()) << " ...";
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003192 instrumentation->Undeoptimize(request.Method());
David Sehr709b0702016-10-13 09:12:37 -07003193 VLOG(jdwp) << "Undeoptimize method " << ArtMethod::PrettyMethod(request.Method()) << " DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003194 break;
3195 default:
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003196 LOG(FATAL) << "Unsupported deoptimization request kind " << request.GetKind();
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003197 break;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003198 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003199}
3200
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003201void Dbg::RequestDeoptimization(const DeoptimizationRequest& req) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003202 if (req.GetKind() == DeoptimizationRequest::kNothing) {
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003203 // Nothing to do.
3204 return;
3205 }
Brian Carlstrom306db812014-09-05 13:01:41 -07003206 MutexLock mu(Thread::Current(), *Locks::deoptimization_lock_);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003207 RequestDeoptimizationLocked(req);
3208}
3209
3210void Dbg::RequestDeoptimizationLocked(const DeoptimizationRequest& req) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003211 switch (req.GetKind()) {
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003212 case DeoptimizationRequest::kRegisterForEvent: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003213 DCHECK_NE(req.InstrumentationEvent(), 0u);
3214 size_t* counter = GetReferenceCounterForEvent(req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003215 CHECK(counter != nullptr) << StringPrintf("No counter for instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003216 req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003217 if (*counter == 0) {
Sebastien Hertz7d2ae432014-05-15 11:26:34 +02003218 VLOG(jdwp) << StringPrintf("Queue request #%zd to start listening to instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003219 deoptimization_requests_.size(), req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003220 deoptimization_requests_.push_back(req);
3221 }
3222 *counter = *counter + 1;
3223 break;
3224 }
3225 case DeoptimizationRequest::kUnregisterForEvent: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003226 DCHECK_NE(req.InstrumentationEvent(), 0u);
3227 size_t* counter = GetReferenceCounterForEvent(req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003228 CHECK(counter != nullptr) << StringPrintf("No counter for instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003229 req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003230 *counter = *counter - 1;
3231 if (*counter == 0) {
Sebastien Hertz7d2ae432014-05-15 11:26:34 +02003232 VLOG(jdwp) << StringPrintf("Queue request #%zd to stop listening to instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003233 deoptimization_requests_.size(), req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003234 deoptimization_requests_.push_back(req);
3235 }
3236 break;
3237 }
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003238 case DeoptimizationRequest::kFullDeoptimization: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003239 DCHECK(req.Method() == nullptr);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003240 if (full_deoptimization_event_count_ == 0) {
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003241 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
3242 << " for full deoptimization";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003243 deoptimization_requests_.push_back(req);
3244 }
3245 ++full_deoptimization_event_count_;
3246 break;
3247 }
3248 case DeoptimizationRequest::kFullUndeoptimization: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003249 DCHECK(req.Method() == nullptr);
Sebastien Hertze713d932014-05-15 10:48:53 +02003250 DCHECK_GT(full_deoptimization_event_count_, 0U);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003251 --full_deoptimization_event_count_;
3252 if (full_deoptimization_event_count_ == 0) {
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003253 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
3254 << " for full undeoptimization";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003255 deoptimization_requests_.push_back(req);
3256 }
3257 break;
3258 }
3259 case DeoptimizationRequest::kSelectiveDeoptimization: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003260 DCHECK(req.Method() != nullptr);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003261 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
David Sehr709b0702016-10-13 09:12:37 -07003262 << " for deoptimization of " << req.Method()->PrettyMethod();
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003263 deoptimization_requests_.push_back(req);
3264 break;
3265 }
3266 case DeoptimizationRequest::kSelectiveUndeoptimization: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003267 DCHECK(req.Method() != nullptr);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003268 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
David Sehr709b0702016-10-13 09:12:37 -07003269 << " for undeoptimization of " << req.Method()->PrettyMethod();
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003270 deoptimization_requests_.push_back(req);
3271 break;
3272 }
3273 default: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003274 LOG(FATAL) << "Unknown deoptimization request kind " << req.GetKind();
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003275 break;
3276 }
3277 }
3278}
3279
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003280void Dbg::ManageDeoptimization() {
3281 Thread* const self = Thread::Current();
3282 {
3283 // Avoid suspend/resume if there is no pending request.
Brian Carlstrom306db812014-09-05 13:01:41 -07003284 MutexLock mu(self, *Locks::deoptimization_lock_);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003285 if (deoptimization_requests_.empty()) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003286 return;
3287 }
3288 }
3289 CHECK_EQ(self->GetState(), kRunnable);
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07003290 ScopedThreadSuspension sts(self, kWaitingForDeoptimization);
Mathieu Chartieraa516822015-10-02 15:53:37 -07003291 // Required for ProcessDeoptimizationRequest.
3292 gc::ScopedGCCriticalSection gcs(self,
3293 gc::kGcCauseInstrumentation,
3294 gc::kCollectorTypeInstrumentation);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003295 // We need to suspend mutator threads first.
Mathieu Chartier4f55e222015-09-04 13:26:21 -07003296 ScopedSuspendAll ssa(__FUNCTION__);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003297 const ThreadState old_state = self->SetStateUnsafe(kRunnable);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003298 {
Brian Carlstrom306db812014-09-05 13:01:41 -07003299 MutexLock mu(self, *Locks::deoptimization_lock_);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003300 size_t req_index = 0;
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003301 for (DeoptimizationRequest& request : deoptimization_requests_) {
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003302 VLOG(jdwp) << "Process deoptimization request #" << req_index++;
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003303 ProcessDeoptimizationRequest(request);
3304 }
3305 deoptimization_requests_.clear();
3306 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003307 CHECK_EQ(self->SetStateUnsafe(old_state), kRunnable);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003308}
3309
Mathieu Chartiere401d142015-04-22 13:56:20 -07003310static const Breakpoint* FindFirstBreakpointForMethod(ArtMethod* m)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003311 REQUIRES_SHARED(Locks::mutator_lock_, Locks::breakpoint_lock_) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003312 for (Breakpoint& breakpoint : gBreakpoints) {
Alex Light6c8467f2015-11-20 15:03:26 -08003313 if (breakpoint.IsInMethod(m)) {
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003314 return &breakpoint;
3315 }
3316 }
3317 return nullptr;
3318}
3319
Mathieu Chartiere401d142015-04-22 13:56:20 -07003320bool Dbg::MethodHasAnyBreakpoints(ArtMethod* method) {
Mathieu Chartierd8565452015-03-26 09:41:50 -07003321 ReaderMutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
3322 return FindFirstBreakpointForMethod(method) != nullptr;
3323}
3324
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003325// Sanity checks all existing breakpoints on the same method.
Mathieu Chartiere401d142015-04-22 13:56:20 -07003326static void SanityCheckExistingBreakpoints(ArtMethod* m,
Sebastien Hertzf3928792014-11-17 19:00:37 +01003327 DeoptimizationRequest::Kind deoptimization_kind)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003328 REQUIRES_SHARED(Locks::mutator_lock_, Locks::breakpoint_lock_) {
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003329 for (const Breakpoint& breakpoint : gBreakpoints) {
Alex Light6c8467f2015-11-20 15:03:26 -08003330 if (breakpoint.IsInMethod(m)) {
Sebastien Hertzf3928792014-11-17 19:00:37 +01003331 CHECK_EQ(deoptimization_kind, breakpoint.GetDeoptimizationKind());
3332 }
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003333 }
Sebastien Hertzf3928792014-11-17 19:00:37 +01003334 instrumentation::Instrumentation* instrumentation = Runtime::Current()->GetInstrumentation();
3335 if (deoptimization_kind == DeoptimizationRequest::kFullDeoptimization) {
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003336 // We should have deoptimized everything but not "selectively" deoptimized this method.
Sebastien Hertzf3928792014-11-17 19:00:37 +01003337 CHECK(instrumentation->AreAllMethodsDeoptimized());
3338 CHECK(!instrumentation->IsDeoptimized(m));
3339 } else if (deoptimization_kind == DeoptimizationRequest::kSelectiveDeoptimization) {
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003340 // We should have "selectively" deoptimized this method.
3341 // Note: while we have not deoptimized everything for this method, we may have done it for
3342 // another event.
Sebastien Hertzf3928792014-11-17 19:00:37 +01003343 CHECK(instrumentation->IsDeoptimized(m));
3344 } else {
3345 // This method does not require deoptimization.
3346 CHECK_EQ(deoptimization_kind, DeoptimizationRequest::kNothing);
3347 CHECK(!instrumentation->IsDeoptimized(m));
3348 }
3349}
3350
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003351// Returns the deoptimization kind required to set a breakpoint in a method.
3352// If a breakpoint has already been set, we also return the first breakpoint
3353// through the given 'existing_brkpt' pointer.
Sebastien Hertzf3928792014-11-17 19:00:37 +01003354static DeoptimizationRequest::Kind GetRequiredDeoptimizationKind(Thread* self,
Mathieu Chartiere401d142015-04-22 13:56:20 -07003355 ArtMethod* m,
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003356 const Breakpoint** existing_brkpt)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003357 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertzf3928792014-11-17 19:00:37 +01003358 if (!Dbg::RequiresDeoptimization()) {
3359 // We already run in interpreter-only mode so we don't need to deoptimize anything.
3360 VLOG(jdwp) << "No need for deoptimization when fully running with interpreter for method "
David Sehr709b0702016-10-13 09:12:37 -07003361 << ArtMethod::PrettyMethod(m);
Sebastien Hertzf3928792014-11-17 19:00:37 +01003362 return DeoptimizationRequest::kNothing;
3363 }
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003364 const Breakpoint* first_breakpoint;
Sebastien Hertzf3928792014-11-17 19:00:37 +01003365 {
3366 ReaderMutexLock mu(self, *Locks::breakpoint_lock_);
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003367 first_breakpoint = FindFirstBreakpointForMethod(m);
3368 *existing_brkpt = first_breakpoint;
Sebastien Hertzf3928792014-11-17 19:00:37 +01003369 }
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003370
3371 if (first_breakpoint == nullptr) {
Nicolas Geoffray6300fd72016-03-18 09:40:17 +00003372 // There is no breakpoint on this method yet: we need to deoptimize. If this method is default,
3373 // we deoptimize everything; otherwise we deoptimize only this method. We
Alex Light6c8467f2015-11-20 15:03:26 -08003374 // deoptimize with defaults because we do not know everywhere they are used. It is possible some
Nicolas Geoffray6300fd72016-03-18 09:40:17 +00003375 // of the copies could be missed.
Alex Light6c8467f2015-11-20 15:03:26 -08003376 // TODO Deoptimizing on default methods might not be necessary in all cases.
Nicolas Geoffray6300fd72016-03-18 09:40:17 +00003377 bool need_full_deoptimization = m->IsDefault();
Sebastien Hertzf3928792014-11-17 19:00:37 +01003378 if (need_full_deoptimization) {
Nicolas Geoffray6300fd72016-03-18 09:40:17 +00003379 VLOG(jdwp) << "Need full deoptimization because of copying of method "
David Sehr709b0702016-10-13 09:12:37 -07003380 << ArtMethod::PrettyMethod(m);
Sebastien Hertzf3928792014-11-17 19:00:37 +01003381 return DeoptimizationRequest::kFullDeoptimization;
3382 } else {
3383 // We don't need to deoptimize if the method has not been compiled.
Nicolas Geoffraya5891e82015-11-06 14:18:27 +00003384 const bool is_compiled = m->HasAnyCompiledCode();
Sebastien Hertzf3928792014-11-17 19:00:37 +01003385 if (is_compiled) {
David Sehr709b0702016-10-13 09:12:37 -07003386 VLOG(jdwp) << "Need selective deoptimization for compiled method "
3387 << ArtMethod::PrettyMethod(m);
Nicolas Geoffray6300fd72016-03-18 09:40:17 +00003388 return DeoptimizationRequest::kSelectiveDeoptimization;
Sebastien Hertzf3928792014-11-17 19:00:37 +01003389 } else {
3390 // Method is not compiled: we don't need to deoptimize.
David Sehr709b0702016-10-13 09:12:37 -07003391 VLOG(jdwp) << "No need for deoptimization for non-compiled method "
3392 << ArtMethod::PrettyMethod(m);
Sebastien Hertzf3928792014-11-17 19:00:37 +01003393 return DeoptimizationRequest::kNothing;
3394 }
3395 }
3396 } else {
3397 // There is at least one breakpoint for this method: we don't need to deoptimize.
3398 // Let's check that all breakpoints are configured the same way for deoptimization.
3399 VLOG(jdwp) << "Breakpoint already set: no deoptimization is required";
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003400 DeoptimizationRequest::Kind deoptimization_kind = first_breakpoint->GetDeoptimizationKind();
Sebastien Hertzf3928792014-11-17 19:00:37 +01003401 if (kIsDebugBuild) {
3402 ReaderMutexLock mu(self, *Locks::breakpoint_lock_);
3403 SanityCheckExistingBreakpoints(m, deoptimization_kind);
3404 }
3405 return DeoptimizationRequest::kNothing;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003406 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003407}
3408
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003409// Installs a breakpoint at the specified location. Also indicates through the deoptimization
3410// request if we need to deoptimize.
3411void Dbg::WatchLocation(const JDWP::JdwpLocation* location, DeoptimizationRequest* req) {
3412 Thread* const self = Thread::Current();
Mathieu Chartiere401d142015-04-22 13:56:20 -07003413 ArtMethod* m = FromMethodId(location->method_id);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003414 DCHECK(m != nullptr) << "No method for method id " << location->method_id;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003415
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003416 const Breakpoint* existing_breakpoint = nullptr;
3417 const DeoptimizationRequest::Kind deoptimization_kind =
3418 GetRequiredDeoptimizationKind(self, m, &existing_breakpoint);
Sebastien Hertzf3928792014-11-17 19:00:37 +01003419 req->SetKind(deoptimization_kind);
3420 if (deoptimization_kind == DeoptimizationRequest::kSelectiveDeoptimization) {
3421 req->SetMethod(m);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003422 } else {
Sebastien Hertzf3928792014-11-17 19:00:37 +01003423 CHECK(deoptimization_kind == DeoptimizationRequest::kNothing ||
3424 deoptimization_kind == DeoptimizationRequest::kFullDeoptimization);
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003425 req->SetMethod(nullptr);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003426 }
3427
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003428 {
3429 WriterMutexLock mu(self, *Locks::breakpoint_lock_);
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003430 // If there is at least one existing breakpoint on the same method, the new breakpoint
3431 // must have the same deoptimization kind than the existing breakpoint(s).
3432 DeoptimizationRequest::Kind breakpoint_deoptimization_kind;
3433 if (existing_breakpoint != nullptr) {
3434 breakpoint_deoptimization_kind = existing_breakpoint->GetDeoptimizationKind();
3435 } else {
3436 breakpoint_deoptimization_kind = deoptimization_kind;
3437 }
3438 gBreakpoints.push_back(Breakpoint(m, location->dex_pc, breakpoint_deoptimization_kind));
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003439 VLOG(jdwp) << "Set breakpoint #" << (gBreakpoints.size() - 1) << ": "
3440 << gBreakpoints[gBreakpoints.size() - 1];
3441 }
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003442}
3443
3444// Uninstalls a breakpoint at the specified location. Also indicates through the deoptimization
3445// request if we need to undeoptimize.
3446void Dbg::UnwatchLocation(const JDWP::JdwpLocation* location, DeoptimizationRequest* req) {
Sebastien Hertzed2be172014-08-19 15:33:43 +02003447 WriterMutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003448 ArtMethod* m = FromMethodId(location->method_id);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003449 DCHECK(m != nullptr) << "No method for method id " << location->method_id;
Sebastien Hertzf3928792014-11-17 19:00:37 +01003450 DeoptimizationRequest::Kind deoptimization_kind = DeoptimizationRequest::kNothing;
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003451 for (size_t i = 0, e = gBreakpoints.size(); i < e; ++i) {
Alex Light6c8467f2015-11-20 15:03:26 -08003452 if (gBreakpoints[i].DexPc() == location->dex_pc && gBreakpoints[i].IsInMethod(m)) {
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003453 VLOG(jdwp) << "Removed breakpoint #" << i << ": " << gBreakpoints[i];
Sebastien Hertzf3928792014-11-17 19:00:37 +01003454 deoptimization_kind = gBreakpoints[i].GetDeoptimizationKind();
3455 DCHECK_EQ(deoptimization_kind == DeoptimizationRequest::kSelectiveDeoptimization,
3456 Runtime::Current()->GetInstrumentation()->IsDeoptimized(m));
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003457 gBreakpoints.erase(gBreakpoints.begin() + i);
3458 break;
3459 }
3460 }
3461 const Breakpoint* const existing_breakpoint = FindFirstBreakpointForMethod(m);
3462 if (existing_breakpoint == nullptr) {
3463 // There is no more breakpoint on this method: we need to undeoptimize.
Sebastien Hertzf3928792014-11-17 19:00:37 +01003464 if (deoptimization_kind == DeoptimizationRequest::kFullDeoptimization) {
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003465 // This method required full deoptimization: we need to undeoptimize everything.
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003466 req->SetKind(DeoptimizationRequest::kFullUndeoptimization);
3467 req->SetMethod(nullptr);
Sebastien Hertzf3928792014-11-17 19:00:37 +01003468 } else if (deoptimization_kind == DeoptimizationRequest::kSelectiveDeoptimization) {
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003469 // This method required selective deoptimization: we need to undeoptimize only that method.
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003470 req->SetKind(DeoptimizationRequest::kSelectiveUndeoptimization);
3471 req->SetMethod(m);
Sebastien Hertzf3928792014-11-17 19:00:37 +01003472 } else {
3473 // This method had no need for deoptimization: do nothing.
3474 CHECK_EQ(deoptimization_kind, DeoptimizationRequest::kNothing);
3475 req->SetKind(DeoptimizationRequest::kNothing);
3476 req->SetMethod(nullptr);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003477 }
3478 } else {
3479 // There is at least one breakpoint for this method: we don't need to undeoptimize.
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003480 req->SetKind(DeoptimizationRequest::kNothing);
3481 req->SetMethod(nullptr);
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003482 if (kIsDebugBuild) {
Sebastien Hertzf3928792014-11-17 19:00:37 +01003483 SanityCheckExistingBreakpoints(m, deoptimization_kind);
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003484 }
Elliott Hughes86964332012-02-15 19:37:42 -08003485 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003486}
3487
Mathieu Chartiere401d142015-04-22 13:56:20 -07003488bool Dbg::IsForcedInterpreterNeededForCallingImpl(Thread* thread, ArtMethod* m) {
Daniel Mihalyieb076692014-08-22 17:33:31 +02003489 const SingleStepControl* const ssc = thread->GetSingleStepControl();
3490 if (ssc == nullptr) {
3491 // If we are not single-stepping, then we don't have to force interpreter.
3492 return false;
3493 }
3494 if (Runtime::Current()->GetInstrumentation()->InterpretOnly()) {
3495 // If we are in interpreter only mode, then we don't have to force interpreter.
3496 return false;
3497 }
3498
3499 if (!m->IsNative() && !m->IsProxyMethod()) {
3500 // If we want to step into a method, then we have to force interpreter on that call.
3501 if (ssc->GetStepDepth() == JDWP::SD_INTO) {
3502 return true;
3503 }
3504 }
3505 return false;
3506}
3507
Mathieu Chartiere401d142015-04-22 13:56:20 -07003508bool Dbg::IsForcedInterpreterNeededForResolutionImpl(Thread* thread, ArtMethod* m) {
Daniel Mihalyieb076692014-08-22 17:33:31 +02003509 instrumentation::Instrumentation* const instrumentation =
3510 Runtime::Current()->GetInstrumentation();
3511 // If we are in interpreter only mode, then we don't have to force interpreter.
3512 if (instrumentation->InterpretOnly()) {
3513 return false;
3514 }
3515 // We can only interpret pure Java method.
3516 if (m->IsNative() || m->IsProxyMethod()) {
3517 return false;
3518 }
3519 const SingleStepControl* const ssc = thread->GetSingleStepControl();
3520 if (ssc != nullptr) {
3521 // If we want to step into a method, then we have to force interpreter on that call.
3522 if (ssc->GetStepDepth() == JDWP::SD_INTO) {
3523 return true;
3524 }
3525 // If we are stepping out from a static initializer, by issuing a step
3526 // in or step over, that was implicitly invoked by calling a static method,
3527 // then we need to step into that method. Having a lower stack depth than
3528 // the one the single step control has indicates that the step originates
3529 // from the static initializer.
3530 if (ssc->GetStepDepth() != JDWP::SD_OUT &&
3531 ssc->GetStackDepth() > GetStackDepth(thread)) {
3532 return true;
3533 }
3534 }
3535 // There are cases where we have to force interpreter on deoptimized methods,
3536 // because in some cases the call will not be performed by invoking an entry
3537 // point that has been replaced by the deoptimization, but instead by directly
3538 // invoking the compiled code of the method, for example.
3539 return instrumentation->IsDeoptimized(m);
3540}
3541
Mathieu Chartiere401d142015-04-22 13:56:20 -07003542bool Dbg::IsForcedInstrumentationNeededForResolutionImpl(Thread* thread, ArtMethod* m) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07003543 // The upcall can be null and in that case we don't need to do anything.
Daniel Mihalyieb076692014-08-22 17:33:31 +02003544 if (m == nullptr) {
3545 return false;
3546 }
3547 instrumentation::Instrumentation* const instrumentation =
3548 Runtime::Current()->GetInstrumentation();
3549 // If we are in interpreter only mode, then we don't have to force interpreter.
3550 if (instrumentation->InterpretOnly()) {
3551 return false;
3552 }
3553 // We can only interpret pure Java method.
3554 if (m->IsNative() || m->IsProxyMethod()) {
3555 return false;
3556 }
3557 const SingleStepControl* const ssc = thread->GetSingleStepControl();
3558 if (ssc != nullptr) {
3559 // If we are stepping out from a static initializer, by issuing a step
3560 // out, that was implicitly invoked by calling a static method, then we
3561 // need to step into the caller of that method. Having a lower stack
3562 // depth than the one the single step control has indicates that the
3563 // step originates from the static initializer.
3564 if (ssc->GetStepDepth() == JDWP::SD_OUT &&
3565 ssc->GetStackDepth() > GetStackDepth(thread)) {
3566 return true;
3567 }
3568 }
3569 // If we are returning from a static intializer, that was implicitly
3570 // invoked by calling a static method and the caller is deoptimized,
3571 // then we have to deoptimize the stack without forcing interpreter
3572 // on the static method that was called originally. This problem can
3573 // be solved easily by forcing instrumentation on the called method,
3574 // because the instrumentation exit hook will recognise the need of
3575 // stack deoptimization by calling IsForcedInterpreterNeededForUpcall.
3576 return instrumentation->IsDeoptimized(m);
3577}
3578
Mathieu Chartiere401d142015-04-22 13:56:20 -07003579bool Dbg::IsForcedInterpreterNeededForUpcallImpl(Thread* thread, ArtMethod* m) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07003580 // The upcall can be null and in that case we don't need to do anything.
Daniel Mihalyieb076692014-08-22 17:33:31 +02003581 if (m == nullptr) {
3582 return false;
3583 }
3584 instrumentation::Instrumentation* const instrumentation =
3585 Runtime::Current()->GetInstrumentation();
3586 // If we are in interpreter only mode, then we don't have to force interpreter.
3587 if (instrumentation->InterpretOnly()) {
3588 return false;
3589 }
3590 // We can only interpret pure Java method.
3591 if (m->IsNative() || m->IsProxyMethod()) {
3592 return false;
3593 }
3594 const SingleStepControl* const ssc = thread->GetSingleStepControl();
3595 if (ssc != nullptr) {
3596 // The debugger is not interested in what is happening under the level
3597 // of the step, thus we only force interpreter when we are not below of
3598 // the step.
3599 if (ssc->GetStackDepth() >= GetStackDepth(thread)) {
3600 return true;
3601 }
3602 }
Mingyao Yang99170c62015-07-06 11:10:37 -07003603 if (thread->HasDebuggerShadowFrames()) {
3604 // We need to deoptimize the stack for the exception handling flow so that
3605 // we don't miss any deoptimization that should be done when there are
3606 // debugger shadow frames.
3607 return true;
3608 }
Daniel Mihalyieb076692014-08-22 17:33:31 +02003609 // We have to require stack deoptimization if the upcall is deoptimized.
3610 return instrumentation->IsDeoptimized(m);
3611}
3612
Mingyao Yang99170c62015-07-06 11:10:37 -07003613class NeedsDeoptimizationVisitor : public StackVisitor {
Sebastien Hertz520633b2015-09-08 17:03:36 +02003614 public:
3615 explicit NeedsDeoptimizationVisitor(Thread* self)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003616 REQUIRES_SHARED(Locks::mutator_lock_)
Sebastien Hertz520633b2015-09-08 17:03:36 +02003617 : StackVisitor(self, nullptr, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
3618 needs_deoptimization_(false) {}
3619
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003620 bool VisitFrame() OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz520633b2015-09-08 17:03:36 +02003621 // The visitor is meant to be used when handling exception from compiled code only.
David Sehr709b0702016-10-13 09:12:37 -07003622 CHECK(!IsShadowFrame()) << "We only expect to visit compiled frame: "
3623 << ArtMethod::PrettyMethod(GetMethod());
Sebastien Hertz520633b2015-09-08 17:03:36 +02003624 ArtMethod* method = GetMethod();
3625 if (method == nullptr) {
3626 // We reach an upcall and don't need to deoptimize this part of the stack (ManagedFragment)
3627 // so we can stop the visit.
3628 DCHECK(!needs_deoptimization_);
3629 return false;
3630 }
3631 if (Runtime::Current()->GetInstrumentation()->InterpretOnly()) {
3632 // We found a compiled frame in the stack but instrumentation is set to interpret
3633 // everything: we need to deoptimize.
3634 needs_deoptimization_ = true;
3635 return false;
3636 }
3637 if (Runtime::Current()->GetInstrumentation()->IsDeoptimized(method)) {
3638 // We found a deoptimized method in the stack.
3639 needs_deoptimization_ = true;
3640 return false;
3641 }
Mingyao Yang99170c62015-07-06 11:10:37 -07003642 ShadowFrame* frame = GetThread()->FindDebuggerShadowFrame(GetFrameId());
3643 if (frame != nullptr) {
3644 // The debugger allocated a ShadowFrame to update a variable in the stack: we need to
3645 // deoptimize the stack to execute (and deallocate) this frame.
3646 needs_deoptimization_ = true;
3647 return false;
3648 }
Sebastien Hertz520633b2015-09-08 17:03:36 +02003649 return true;
3650 }
3651
3652 bool NeedsDeoptimization() const {
3653 return needs_deoptimization_;
3654 }
3655
3656 private:
3657 // Do we need to deoptimize the stack?
3658 bool needs_deoptimization_;
3659
3660 DISALLOW_COPY_AND_ASSIGN(NeedsDeoptimizationVisitor);
3661};
3662
3663// Do we need to deoptimize the stack to handle an exception?
3664bool Dbg::IsForcedInterpreterNeededForExceptionImpl(Thread* thread) {
3665 const SingleStepControl* const ssc = thread->GetSingleStepControl();
3666 if (ssc != nullptr) {
3667 // We deopt to step into the catch handler.
3668 return true;
3669 }
3670 // Deoptimization is required if at least one method in the stack needs it. However we
3671 // skip frames that will be unwound (thus not executed).
3672 NeedsDeoptimizationVisitor visitor(thread);
3673 visitor.WalkStack(true); // includes upcall.
3674 return visitor.NeedsDeoptimization();
3675}
3676
Jeff Hao449db332013-04-12 18:30:52 -07003677// Scoped utility class to suspend a thread so that we may do tasks such as walk its stack. Doesn't
3678// cause suspension if the thread is the current thread.
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07003679class ScopedDebuggerThreadSuspension {
Jeff Hao449db332013-04-12 18:30:52 -07003680 public:
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07003681 ScopedDebuggerThreadSuspension(Thread* self, JDWP::ObjectId thread_id)
Mathieu Chartier90443472015-07-16 20:32:27 -07003682 REQUIRES(!Locks::thread_list_lock_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003683 REQUIRES_SHARED(Locks::mutator_lock_) :
Ian Rogersf3d874c2014-07-17 18:52:42 -07003684 thread_(nullptr),
Jeff Hao449db332013-04-12 18:30:52 -07003685 error_(JDWP::ERR_NONE),
3686 self_suspend_(false),
Ian Rogers33e95662013-05-20 20:29:14 -07003687 other_suspend_(false) {
Jeff Hao449db332013-04-12 18:30:52 -07003688 ScopedObjectAccessUnchecked soa(self);
Sebastien Hertz69206392015-04-07 15:54:25 +02003689 thread_ = DecodeThread(soa, thread_id, &error_);
Jeff Hao449db332013-04-12 18:30:52 -07003690 if (error_ == JDWP::ERR_NONE) {
3691 if (thread_ == soa.Self()) {
3692 self_suspend_ = true;
3693 } else {
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07003694 Thread* suspended_thread;
3695 {
3696 ScopedThreadSuspension sts(self, kWaitingForDebuggerSuspension);
3697 jobject thread_peer = Dbg::GetObjectRegistry()->GetJObject(thread_id);
3698 bool timed_out;
3699 ThreadList* const thread_list = Runtime::Current()->GetThreadList();
Sebastien Hertzcdd798d2017-04-18 18:28:51 +02003700 suspended_thread = thread_list->SuspendThreadByPeer(thread_peer,
3701 /* request_suspension */ true,
Alex Light46f93402017-06-29 11:59:50 -07003702 SuspendReason::kForDebugger,
Sebastien Hertzcdd798d2017-04-18 18:28:51 +02003703 &timed_out);
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07003704 }
Ian Rogersf3d874c2014-07-17 18:52:42 -07003705 if (suspended_thread == nullptr) {
Jeff Hao449db332013-04-12 18:30:52 -07003706 // Thread terminated from under us while suspending.
3707 error_ = JDWP::ERR_INVALID_THREAD;
3708 } else {
3709 CHECK_EQ(suspended_thread, thread_);
3710 other_suspend_ = true;
3711 }
3712 }
3713 }
Elliott Hughes2435a572012-02-17 16:07:41 -08003714 }
Elliott Hughes86964332012-02-15 19:37:42 -08003715
Jeff Hao449db332013-04-12 18:30:52 -07003716 Thread* GetThread() const {
3717 return thread_;
3718 }
3719
3720 JDWP::JdwpError GetError() const {
3721 return error_;
3722 }
3723
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07003724 ~ScopedDebuggerThreadSuspension() {
Jeff Hao449db332013-04-12 18:30:52 -07003725 if (other_suspend_) {
Alex Light88fd7202017-06-30 08:31:59 -07003726 bool resumed = Runtime::Current()->GetThreadList()->Resume(thread_,
3727 SuspendReason::kForDebugger);
3728 DCHECK(resumed);
Jeff Hao449db332013-04-12 18:30:52 -07003729 }
3730 }
3731
3732 private:
3733 Thread* thread_;
3734 JDWP::JdwpError error_;
3735 bool self_suspend_;
3736 bool other_suspend_;
3737};
3738
3739JDWP::JdwpError Dbg::ConfigureStep(JDWP::ObjectId thread_id, JDWP::JdwpStepSize step_size,
3740 JDWP::JdwpStepDepth step_depth) {
3741 Thread* self = Thread::Current();
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07003742 ScopedDebuggerThreadSuspension sts(self, thread_id);
Jeff Hao449db332013-04-12 18:30:52 -07003743 if (sts.GetError() != JDWP::ERR_NONE) {
3744 return sts.GetError();
3745 }
3746
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003747 // Work out what ArtMethod* we're in, the current line number, and how deep the stack currently
Elliott Hughes2435a572012-02-17 16:07:41 -08003748 // is for step-out.
Ian Rogers0399dde2012-06-06 17:09:28 -07003749 struct SingleStepStackVisitor : public StackVisitor {
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003750 explicit SingleStepStackVisitor(Thread* thread) REQUIRES_SHARED(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01003751 : StackVisitor(thread, nullptr, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
3752 stack_depth(0),
3753 method(nullptr),
3754 line_number(-1) {}
Ian Rogersca190662012-06-26 15:45:57 -07003755
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003756 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
3757 // annotalysis.
3758 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003759 ArtMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07003760 if (!m->IsRuntimeMethod()) {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003761 ++stack_depth;
3762 if (method == nullptr) {
Alex Light73376312017-04-06 10:10:51 -07003763 const DexFile* dex_file = m->GetDexFile();
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003764 method = m;
Alex Light73376312017-04-06 10:10:51 -07003765 if (dex_file != nullptr) {
David Sehr9323e6e2016-09-13 08:58:35 -07003766 line_number = annotations::GetLineNumFromPC(dex_file, m, GetDexPc());
Elliott Hughes2435a572012-02-17 16:07:41 -08003767 }
Elliott Hughes86964332012-02-15 19:37:42 -08003768 }
3769 }
Elliott Hughes530fa002012-03-12 11:44:49 -07003770 return true;
Elliott Hughes86964332012-02-15 19:37:42 -08003771 }
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003772
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003773 int stack_depth;
Mathieu Chartiere401d142015-04-22 13:56:20 -07003774 ArtMethod* method;
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003775 int32_t line_number;
Elliott Hughes86964332012-02-15 19:37:42 -08003776 };
Jeff Hao449db332013-04-12 18:30:52 -07003777
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003778 Thread* const thread = sts.GetThread();
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003779 SingleStepStackVisitor visitor(thread);
Ian Rogers0399dde2012-06-06 17:09:28 -07003780 visitor.WalkStack();
Elliott Hughes86964332012-02-15 19:37:42 -08003781
Elliott Hughes2435a572012-02-17 16:07:41 -08003782 // Find the dex_pc values that correspond to the current line, for line-based single-stepping.
Elliott Hughes2435a572012-02-17 16:07:41 -08003783 struct DebugCallbackContext {
Roland Levillain3887c462015-08-12 18:15:42 +01003784 DebugCallbackContext(SingleStepControl* single_step_control_cb,
3785 int32_t line_number_cb, const DexFile::CodeItem* code_item)
3786 : single_step_control_(single_step_control_cb), line_number_(line_number_cb),
3787 code_item_(code_item), last_pc_valid(false), last_pc(0) {
Elliott Hughes2435a572012-02-17 16:07:41 -08003788 }
3789
David Srbeckyb06e28e2015-12-10 13:15:00 +00003790 static bool Callback(void* raw_context, const DexFile::PositionInfo& entry) {
Elliott Hughes2435a572012-02-17 16:07:41 -08003791 DebugCallbackContext* context = reinterpret_cast<DebugCallbackContext*>(raw_context);
David Srbeckyb06e28e2015-12-10 13:15:00 +00003792 if (static_cast<int32_t>(entry.line_) == context->line_number_) {
Elliott Hughes2435a572012-02-17 16:07:41 -08003793 if (!context->last_pc_valid) {
3794 // Everything from this address until the next line change is ours.
David Srbeckyb06e28e2015-12-10 13:15:00 +00003795 context->last_pc = entry.address_;
Elliott Hughes2435a572012-02-17 16:07:41 -08003796 context->last_pc_valid = true;
3797 }
3798 // Otherwise, if we're already in a valid range for this line,
3799 // just keep going (shouldn't really happen)...
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003800 } else if (context->last_pc_valid) { // and the line number is new
Elliott Hughes2435a572012-02-17 16:07:41 -08003801 // Add everything from the last entry up until here to the set
David Srbeckyb06e28e2015-12-10 13:15:00 +00003802 for (uint32_t dex_pc = context->last_pc; dex_pc < entry.address_; ++dex_pc) {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003803 context->single_step_control_->AddDexPc(dex_pc);
Elliott Hughes2435a572012-02-17 16:07:41 -08003804 }
3805 context->last_pc_valid = false;
3806 }
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003807 return false; // There may be multiple entries for any given line.
Elliott Hughes2435a572012-02-17 16:07:41 -08003808 }
3809
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003810 ~DebugCallbackContext() {
Elliott Hughes2435a572012-02-17 16:07:41 -08003811 // If the line number was the last in the position table...
3812 if (last_pc_valid) {
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003813 size_t end = code_item_->insns_size_in_code_units_;
Elliott Hughes2435a572012-02-17 16:07:41 -08003814 for (uint32_t dex_pc = last_pc; dex_pc < end; ++dex_pc) {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003815 single_step_control_->AddDexPc(dex_pc);
Elliott Hughes2435a572012-02-17 16:07:41 -08003816 }
3817 }
3818 }
3819
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003820 SingleStepControl* const single_step_control_;
3821 const int32_t line_number_;
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003822 const DexFile::CodeItem* const code_item_;
Elliott Hughes2435a572012-02-17 16:07:41 -08003823 bool last_pc_valid;
3824 uint32_t last_pc;
3825 };
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003826
3827 // Allocate single step.
Sebastien Hertz1558b572015-02-25 15:05:59 +01003828 SingleStepControl* single_step_control =
3829 new (std::nothrow) SingleStepControl(step_size, step_depth,
3830 visitor.stack_depth, visitor.method);
3831 if (single_step_control == nullptr) {
3832 LOG(ERROR) << "Failed to allocate SingleStepControl";
3833 return JDWP::ERR_OUT_OF_MEMORY;
3834 }
3835
Mathieu Chartiere401d142015-04-22 13:56:20 -07003836 ArtMethod* m = single_step_control->GetMethod();
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003837 const int32_t line_number = visitor.line_number;
Sebastien Hertz52f5f932015-05-28 11:00:57 +02003838 // Note: if the thread is not running Java code (pure native thread), there is no "current"
3839 // method on the stack (and no line number either).
3840 if (m != nullptr && !m->IsNative()) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003841 const DexFile::CodeItem* const code_item = m->GetCodeItem();
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003842 DebugCallbackContext context(single_step_control, line_number, code_item);
David Srbeckyb06e28e2015-12-10 13:15:00 +00003843 m->GetDexFile()->DecodeDebugPositionInfo(code_item, DebugCallbackContext::Callback, &context);
Elliott Hughes3e2e1a22012-02-21 11:33:41 -08003844 }
Elliott Hughes2435a572012-02-17 16:07:41 -08003845
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003846 // Activate single-step in the thread.
3847 thread->ActivateSingleStepControl(single_step_control);
Elliott Hughes86964332012-02-15 19:37:42 -08003848
Elliott Hughes2435a572012-02-17 16:07:41 -08003849 if (VLOG_IS_ON(jdwp)) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003850 VLOG(jdwp) << "Single-step thread: " << *thread;
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003851 VLOG(jdwp) << "Single-step step size: " << single_step_control->GetStepSize();
3852 VLOG(jdwp) << "Single-step step depth: " << single_step_control->GetStepDepth();
David Sehr709b0702016-10-13 09:12:37 -07003853 VLOG(jdwp) << "Single-step current method: "
3854 << ArtMethod::PrettyMethod(single_step_control->GetMethod());
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003855 VLOG(jdwp) << "Single-step current line: " << line_number;
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003856 VLOG(jdwp) << "Single-step current stack depth: " << single_step_control->GetStackDepth();
Elliott Hughes2435a572012-02-17 16:07:41 -08003857 VLOG(jdwp) << "Single-step dex_pc values:";
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003858 for (uint32_t dex_pc : single_step_control->GetDexPcs()) {
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003859 VLOG(jdwp) << StringPrintf(" %#x", dex_pc);
Elliott Hughes2435a572012-02-17 16:07:41 -08003860 }
3861 }
3862
3863 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003864}
3865
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003866void Dbg::UnconfigureStep(JDWP::ObjectId thread_id) {
3867 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07003868 JDWP::JdwpError error;
3869 Thread* thread = DecodeThread(soa, thread_id, &error);
Sebastien Hertz87118ed2013-11-26 17:57:18 +01003870 if (error == JDWP::ERR_NONE) {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003871 thread->DeactivateSingleStepControl();
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003872 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003873}
3874
Elliott Hughes45651fd2012-02-21 15:48:20 -08003875static char JdwpTagToShortyChar(JDWP::JdwpTag tag) {
3876 switch (tag) {
3877 default:
3878 LOG(FATAL) << "unknown JDWP tag: " << PrintableChar(tag);
Ian Rogersfc787ec2014-10-09 21:56:44 -07003879 UNREACHABLE();
Elliott Hughes45651fd2012-02-21 15:48:20 -08003880
3881 // Primitives.
3882 case JDWP::JT_BYTE: return 'B';
3883 case JDWP::JT_CHAR: return 'C';
3884 case JDWP::JT_FLOAT: return 'F';
3885 case JDWP::JT_DOUBLE: return 'D';
3886 case JDWP::JT_INT: return 'I';
3887 case JDWP::JT_LONG: return 'J';
3888 case JDWP::JT_SHORT: return 'S';
3889 case JDWP::JT_VOID: return 'V';
3890 case JDWP::JT_BOOLEAN: return 'Z';
3891
3892 // Reference types.
3893 case JDWP::JT_ARRAY:
3894 case JDWP::JT_OBJECT:
3895 case JDWP::JT_STRING:
3896 case JDWP::JT_THREAD:
3897 case JDWP::JT_THREAD_GROUP:
3898 case JDWP::JT_CLASS_LOADER:
3899 case JDWP::JT_CLASS_OBJECT:
3900 return 'L';
3901 }
3902}
3903
Sebastien Hertzcbc50642015-06-01 17:33:12 +02003904JDWP::JdwpError Dbg::PrepareInvokeMethod(uint32_t request_id, JDWP::ObjectId thread_id,
3905 JDWP::ObjectId object_id, JDWP::RefTypeId class_id,
3906 JDWP::MethodId method_id, uint32_t arg_count,
3907 uint64_t arg_values[], JDWP::JdwpTag* arg_types,
3908 uint32_t options) {
3909 Thread* const self = Thread::Current();
3910 CHECK_EQ(self, GetDebugThread()) << "This must be called by the JDWP thread";
Sebastien Hertzd4032e42015-06-12 15:47:34 +02003911 const bool resume_all_threads = ((options & JDWP::INVOKE_SINGLE_THREADED) == 0);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003912
Sebastien Hertzcbc50642015-06-01 17:33:12 +02003913 ThreadList* thread_list = Runtime::Current()->GetThreadList();
Ian Rogersc0542af2014-09-03 16:16:56 -07003914 Thread* targetThread = nullptr;
Elliott Hughesd07986f2011-12-06 18:27:45 -08003915 {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003916 ScopedObjectAccessUnchecked soa(self);
Ian Rogersc0542af2014-09-03 16:16:56 -07003917 JDWP::JdwpError error;
3918 targetThread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08003919 if (error != JDWP::ERR_NONE) {
3920 LOG(ERROR) << "InvokeMethod request for invalid thread id " << thread_id;
3921 return error;
Elliott Hughesd07986f2011-12-06 18:27:45 -08003922 }
Sebastien Hertz1558b572015-02-25 15:05:59 +01003923 if (targetThread->GetInvokeReq() != nullptr) {
3924 // Thread is already invoking a method on behalf of the debugger.
3925 LOG(ERROR) << "InvokeMethod request for thread already invoking a method: " << *targetThread;
3926 return JDWP::ERR_ALREADY_INVOKING;
3927 }
3928 if (!targetThread->IsReadyForDebugInvoke()) {
3929 // Thread is not suspended by an event so it cannot invoke a method.
Elliott Hughesd07986f2011-12-06 18:27:45 -08003930 LOG(ERROR) << "InvokeMethod request for thread not stopped by event: " << *targetThread;
3931 return JDWP::ERR_INVALID_THREAD;
3932 }
3933
3934 /*
Sebastien Hertzd4032e42015-06-12 15:47:34 +02003935 * According to the JDWP specs, we are expected to resume all threads (or only the
3936 * target thread) once. So if a thread has been suspended more than once (either by
3937 * the debugger for an event or by the runtime for GC), it will remain suspended before
3938 * the invoke is executed. This means the debugger is responsible to properly resume all
3939 * the threads it has suspended so the target thread can execute the method.
Elliott Hughesd07986f2011-12-06 18:27:45 -08003940 *
Sebastien Hertzd4032e42015-06-12 15:47:34 +02003941 * However, for compatibility reason with older versions of debuggers (like Eclipse), we
3942 * fully resume all threads (by canceling *all* debugger suspensions) when the debugger
3943 * wants us to resume all threads. This is to avoid ending up in deadlock situation.
3944 *
3945 * On the other hand, if we are asked to only resume the target thread, then we follow the
3946 * JDWP specs by resuming that thread only once. This means the thread will remain suspended
3947 * if it has been suspended more than once before the invoke (and again, this is the
3948 * responsibility of the debugger to properly resume that thread before invoking a method).
Elliott Hughesd07986f2011-12-06 18:27:45 -08003949 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003950 int suspend_count;
3951 {
Ian Rogers50b35e22012-10-04 10:09:15 -07003952 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003953 suspend_count = targetThread->GetSuspendCount();
3954 }
Sebastien Hertzd4032e42015-06-12 15:47:34 +02003955 if (suspend_count > 1 && resume_all_threads) {
3956 // The target thread will remain suspended even after we resume it. Let's emit a warning
3957 // to indicate the invoke won't be executed until the thread is resumed.
3958 LOG(WARNING) << *targetThread << " suspended more than once (suspend count == "
3959 << suspend_count << "). This thread will invoke the method only once "
3960 << "it is fully resumed.";
Elliott Hughesd07986f2011-12-06 18:27:45 -08003961 }
3962
Ian Rogersc0542af2014-09-03 16:16:56 -07003963 mirror::Object* receiver = gRegistry->Get<mirror::Object*>(object_id, &error);
3964 if (error != JDWP::ERR_NONE) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08003965 return JDWP::ERR_INVALID_OBJECT;
3966 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003967
Sebastien Hertz1558b572015-02-25 15:05:59 +01003968 gRegistry->Get<mirror::Object*>(thread_id, &error);
Ian Rogersc0542af2014-09-03 16:16:56 -07003969 if (error != JDWP::ERR_NONE) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08003970 return JDWP::ERR_INVALID_OBJECT;
3971 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003972
Ian Rogersc0542af2014-09-03 16:16:56 -07003973 mirror::Class* c = DecodeClass(class_id, &error);
3974 if (c == nullptr) {
3975 return error;
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08003976 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003977
Mathieu Chartiere401d142015-04-22 13:56:20 -07003978 ArtMethod* m = FromMethodId(method_id);
Ian Rogersc0542af2014-09-03 16:16:56 -07003979 if (m->IsStatic() != (receiver == nullptr)) {
Elliott Hughes45651fd2012-02-21 15:48:20 -08003980 return JDWP::ERR_INVALID_METHODID;
3981 }
3982 if (m->IsStatic()) {
3983 if (m->GetDeclaringClass() != c) {
3984 return JDWP::ERR_INVALID_METHODID;
3985 }
3986 } else {
3987 if (!m->GetDeclaringClass()->IsAssignableFrom(c)) {
3988 return JDWP::ERR_INVALID_METHODID;
3989 }
3990 }
3991
3992 // Check the argument list matches the method.
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003993 uint32_t shorty_len = 0;
3994 const char* shorty = m->GetShorty(&shorty_len);
3995 if (shorty_len - 1 != arg_count) {
Elliott Hughes45651fd2012-02-21 15:48:20 -08003996 return JDWP::ERR_ILLEGAL_ARGUMENT;
3997 }
Elliott Hughes09201632013-04-15 15:50:07 -07003998
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003999 {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004000 StackHandleScope<2> hs(soa.Self());
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004001 HandleWrapper<mirror::Object> h_obj(hs.NewHandleWrapper(&receiver));
4002 HandleWrapper<mirror::Class> h_klass(hs.NewHandleWrapper(&c));
4003 const DexFile::TypeList* types = m->GetParameterTypeList();
4004 for (size_t i = 0; i < arg_count; ++i) {
4005 if (shorty[i + 1] != JdwpTagToShortyChar(arg_types[i])) {
Elliott Hughes09201632013-04-15 15:50:07 -07004006 return JDWP::ERR_ILLEGAL_ARGUMENT;
4007 }
4008
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004009 if (shorty[i + 1] == 'L') {
4010 // Did we really get an argument of an appropriate reference type?
Ian Rogersa0485602014-12-02 15:48:04 -08004011 mirror::Class* parameter_type =
Vladimir Marko942fd312017-01-16 20:52:19 +00004012 m->GetClassFromTypeIndex(types->GetTypeItem(i).type_idx_, true /* resolve */);
Ian Rogersc0542af2014-09-03 16:16:56 -07004013 mirror::Object* argument = gRegistry->Get<mirror::Object*>(arg_values[i], &error);
4014 if (error != JDWP::ERR_NONE) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004015 return JDWP::ERR_INVALID_OBJECT;
4016 }
Ian Rogersc0542af2014-09-03 16:16:56 -07004017 if (argument != nullptr && !argument->InstanceOf(parameter_type)) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004018 return JDWP::ERR_ILLEGAL_ARGUMENT;
4019 }
4020
4021 // Turn the on-the-wire ObjectId into a jobject.
4022 jvalue& v = reinterpret_cast<jvalue&>(arg_values[i]);
4023 v.l = gRegistry->GetJObject(arg_values[i]);
4024 }
Elliott Hughes09201632013-04-15 15:50:07 -07004025 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08004026 }
4027
Sebastien Hertz1558b572015-02-25 15:05:59 +01004028 // Allocates a DebugInvokeReq.
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004029 DebugInvokeReq* req = new (std::nothrow) DebugInvokeReq(request_id, thread_id, receiver, c, m,
4030 options, arg_values, arg_count);
4031 if (req == nullptr) {
Sebastien Hertz1558b572015-02-25 15:05:59 +01004032 LOG(ERROR) << "Failed to allocate DebugInvokeReq";
4033 return JDWP::ERR_OUT_OF_MEMORY;
4034 }
4035
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004036 // Attaches the DebugInvokeReq to the target thread so it executes the method when
4037 // it is resumed. Once the invocation completes, the target thread will delete it before
4038 // suspending itself (see ThreadList::SuspendSelfForDebugger).
4039 targetThread->SetDebugInvokeReq(req);
Elliott Hughesd07986f2011-12-06 18:27:45 -08004040 }
4041
4042 // 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 +02004043 // away we're sitting high and dry -- but we must release this before the UndoDebuggerSuspensions
4044 // call.
Sebastien Hertzd4032e42015-06-12 15:47:34 +02004045 if (resume_all_threads) {
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004046 VLOG(jdwp) << " Resuming all threads";
4047 thread_list->UndoDebuggerSuspensions();
4048 } else {
4049 VLOG(jdwp) << " Resuming event thread only";
Alex Light88fd7202017-06-30 08:31:59 -07004050 bool resumed = thread_list->Resume(targetThread, SuspendReason::kForDebugger);
4051 DCHECK(resumed);
Elliott Hughesd07986f2011-12-06 18:27:45 -08004052 }
4053
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004054 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004055}
4056
4057void Dbg::ExecuteMethod(DebugInvokeReq* pReq) {
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004058 Thread* const self = Thread::Current();
4059 CHECK_NE(self, GetDebugThread()) << "This must be called by the event thread";
4060
4061 ScopedObjectAccess soa(self);
Elliott Hughesd07986f2011-12-06 18:27:45 -08004062
Elliott Hughes81ff3182012-03-23 20:35:56 -07004063 // We can be called while an exception is pending. We need
Elliott Hughesd07986f2011-12-06 18:27:45 -08004064 // to preserve that across the method invocation.
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004065 StackHandleScope<1> hs(soa.Self());
4066 Handle<mirror::Throwable> old_exception = hs.NewHandle(soa.Self()->GetException());
Sebastien Hertz1558b572015-02-25 15:05:59 +01004067 soa.Self()->ClearException();
Elliott Hughesd07986f2011-12-06 18:27:45 -08004068
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004069 // Execute the method then sends reply to the debugger.
4070 ExecuteMethodWithoutPendingException(soa, pReq);
4071
4072 // If an exception was pending before the invoke, restore it now.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004073 if (old_exception != nullptr) {
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004074 soa.Self()->SetException(old_exception.Get());
4075 }
4076}
4077
4078// Helper function: write a variable-width value into the output input buffer.
4079static void WriteValue(JDWP::ExpandBuf* pReply, int width, uint64_t value) {
4080 switch (width) {
4081 case 1:
4082 expandBufAdd1(pReply, value);
4083 break;
4084 case 2:
4085 expandBufAdd2BE(pReply, value);
4086 break;
4087 case 4:
4088 expandBufAdd4BE(pReply, value);
4089 break;
4090 case 8:
4091 expandBufAdd8BE(pReply, value);
4092 break;
4093 default:
4094 LOG(FATAL) << width;
4095 UNREACHABLE();
4096 }
4097}
4098
4099void Dbg::ExecuteMethodWithoutPendingException(ScopedObjectAccess& soa, DebugInvokeReq* pReq) {
4100 soa.Self()->AssertNoPendingException();
4101
Elliott Hughesd07986f2011-12-06 18:27:45 -08004102 // Translate the method through the vtable, unless the debugger wants to suppress it.
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004103 ArtMethod* m = pReq->method;
Andreas Gampe542451c2016-07-26 09:02:02 -07004104 PointerSize image_pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
Sebastien Hertz1558b572015-02-25 15:05:59 +01004105 if ((pReq->options & JDWP::INVOKE_NONVIRTUAL) == 0 && pReq->receiver.Read() != nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004106 ArtMethod* actual_method =
4107 pReq->klass.Read()->FindVirtualMethodForVirtualOrInterface(m, image_pointer_size);
4108 if (actual_method != m) {
David Sehr709b0702016-10-13 09:12:37 -07004109 VLOG(jdwp) << "ExecuteMethod translated " << ArtMethod::PrettyMethod(m)
4110 << " to " << ArtMethod::PrettyMethod(actual_method);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004111 m = actual_method;
Elliott Hughes45651fd2012-02-21 15:48:20 -08004112 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08004113 }
David Sehr709b0702016-10-13 09:12:37 -07004114 VLOG(jdwp) << "ExecuteMethod " << ArtMethod::PrettyMethod(m)
Sebastien Hertz1558b572015-02-25 15:05:59 +01004115 << " receiver=" << pReq->receiver.Read()
Sebastien Hertzd38667a2013-11-25 15:43:54 +01004116 << " arg_count=" << pReq->arg_count;
Mathieu Chartiere401d142015-04-22 13:56:20 -07004117 CHECK(m != nullptr);
Elliott Hughesd07986f2011-12-06 18:27:45 -08004118
Roland Levillain33d69032015-06-18 18:20:59 +01004119 static_assert(sizeof(jvalue) == sizeof(uint64_t), "jvalue and uint64_t have different sizes.");
Elliott Hughesd07986f2011-12-06 18:27:45 -08004120
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004121 // Invoke the method.
Jeff Hao39b6c242015-05-19 20:30:23 -07004122 ScopedLocalRef<jobject> ref(soa.Env(), soa.AddLocalReference<jobject>(pReq->receiver.Read()));
Andreas Gampe13b27842016-11-07 16:48:23 -08004123 JValue result = InvokeWithJValues(soa, ref.get(), jni::EncodeArtMethod(m),
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004124 reinterpret_cast<jvalue*>(pReq->arg_values.get()));
Elliott Hughesd07986f2011-12-06 18:27:45 -08004125
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004126 // Prepare JDWP ids for the reply.
4127 JDWP::JdwpTag result_tag = BasicTagFromDescriptor(m->GetShorty());
4128 const bool is_object_result = (result_tag == JDWP::JT_OBJECT);
Jeff Hao064d24e2016-08-25 03:52:40 +00004129 StackHandleScope<3> hs(soa.Self());
Sebastien Hertz1558b572015-02-25 15:05:59 +01004130 Handle<mirror::Object> object_result = hs.NewHandle(is_object_result ? result.GetL() : nullptr);
4131 Handle<mirror::Throwable> exception = hs.NewHandle(soa.Self()->GetException());
4132 soa.Self()->ClearException();
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004133
4134 if (!IsDebuggerActive()) {
4135 // The debugger detached: we must not re-suspend threads. We also don't need to fill the reply
4136 // because it won't be sent either.
4137 return;
4138 }
4139
4140 JDWP::ObjectId exceptionObjectId = gRegistry->Add(exception);
4141 uint64_t result_value = 0;
4142 if (exceptionObjectId != 0) {
Sebastien Hertz1558b572015-02-25 15:05:59 +01004143 VLOG(jdwp) << " JDWP invocation returning with exception=" << exception.Get()
4144 << " " << exception->Dump();
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004145 result_value = 0;
Sebastien Hertz1558b572015-02-25 15:05:59 +01004146 } else if (is_object_result) {
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004147 /* if no exception was thrown, examine object result more closely */
Sebastien Hertz1558b572015-02-25 15:05:59 +01004148 JDWP::JdwpTag new_tag = TagFromObject(soa, object_result.Get());
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004149 if (new_tag != result_tag) {
4150 VLOG(jdwp) << " JDWP promoted result from " << result_tag << " to " << new_tag;
4151 result_tag = new_tag;
Elliott Hughesd07986f2011-12-06 18:27:45 -08004152 }
4153
Sebastien Hertz1558b572015-02-25 15:05:59 +01004154 // Register the object in the registry and reference its ObjectId. This ensures
4155 // GC safety and prevents from accessing stale reference if the object is moved.
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004156 result_value = gRegistry->Add(object_result.Get());
Sebastien Hertz1558b572015-02-25 15:05:59 +01004157 } else {
4158 // Primitive result.
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004159 DCHECK(IsPrimitiveTag(result_tag));
4160 result_value = result.GetJ();
4161 }
4162 const bool is_constructor = m->IsConstructor() && !m->IsStatic();
4163 if (is_constructor) {
4164 // If we invoked a constructor (which actually returns void), return the receiver,
4165 // unless we threw, in which case we return null.
Sebastien Hertza3e13772015-11-05 12:09:44 +01004166 DCHECK_EQ(JDWP::JT_VOID, result_tag);
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004167 if (exceptionObjectId == 0) {
Jeff Hao064d24e2016-08-25 03:52:40 +00004168 if (m->GetDeclaringClass()->IsStringClass()) {
4169 // For string constructors, the new string is remapped to the receiver (stored in ref).
4170 Handle<mirror::Object> decoded_ref = hs.NewHandle(soa.Self()->DecodeJObject(ref.get()));
4171 result_value = gRegistry->Add(decoded_ref);
4172 result_tag = TagFromObject(soa, decoded_ref.Get());
4173 } else {
4174 // TODO we could keep the receiver ObjectId in the DebugInvokeReq to avoid looking into the
4175 // object registry.
4176 result_value = GetObjectRegistry()->Add(pReq->receiver.Read());
4177 result_tag = TagFromObject(soa, pReq->receiver.Read());
4178 }
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004179 } else {
4180 result_value = 0;
Sebastien Hertza3e13772015-11-05 12:09:44 +01004181 result_tag = JDWP::JT_OBJECT;
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004182 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08004183 }
4184
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004185 // Suspend other threads if the invoke is not single-threaded.
4186 if ((pReq->options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07004187 ScopedThreadSuspension sts(soa.Self(), kWaitingForDebuggerSuspension);
Hiroshi Yamauchi8f95cf32016-04-19 11:14:06 -07004188 // Avoid a deadlock between GC and debugger where GC gets suspended during GC. b/25800335.
4189 gc::ScopedGCCriticalSection gcs(soa.Self(), gc::kGcCauseDebugger, gc::kCollectorTypeDebugger);
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004190 VLOG(jdwp) << " Suspending all threads";
4191 Runtime::Current()->GetThreadList()->SuspendAllForDebugger();
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004192 }
4193
4194 VLOG(jdwp) << " --> returned " << result_tag
4195 << StringPrintf(" %#" PRIx64 " (except=%#" PRIx64 ")", result_value,
4196 exceptionObjectId);
4197
4198 // Show detailed debug output.
4199 if (result_tag == JDWP::JT_STRING && exceptionObjectId == 0) {
4200 if (result_value != 0) {
4201 if (VLOG_IS_ON(jdwp)) {
4202 std::string result_string;
4203 JDWP::JdwpError error = Dbg::StringToUtf8(result_value, &result_string);
4204 CHECK_EQ(error, JDWP::ERR_NONE);
4205 VLOG(jdwp) << " string '" << result_string << "'";
4206 }
4207 } else {
4208 VLOG(jdwp) << " string (null)";
4209 }
4210 }
4211
4212 // Attach the reply to DebugInvokeReq so it can be sent to the debugger when the event thread
4213 // is ready to suspend.
4214 BuildInvokeReply(pReq->reply, pReq->request_id, result_tag, result_value, exceptionObjectId);
4215}
4216
4217void Dbg::BuildInvokeReply(JDWP::ExpandBuf* pReply, uint32_t request_id, JDWP::JdwpTag result_tag,
4218 uint64_t result_value, JDWP::ObjectId exception) {
4219 // Make room for the JDWP header since we do not know the size of the reply yet.
4220 JDWP::expandBufAddSpace(pReply, kJDWPHeaderLen);
4221
4222 size_t width = GetTagWidth(result_tag);
4223 JDWP::expandBufAdd1(pReply, result_tag);
4224 if (width != 0) {
4225 WriteValue(pReply, width, result_value);
4226 }
4227 JDWP::expandBufAdd1(pReply, JDWP::JT_OBJECT);
4228 JDWP::expandBufAddObjectId(pReply, exception);
4229
4230 // Now we know the size, we can complete the JDWP header.
4231 uint8_t* buf = expandBufGetBuffer(pReply);
4232 JDWP::Set4BE(buf + kJDWPHeaderSizeOffset, expandBufGetLength(pReply));
4233 JDWP::Set4BE(buf + kJDWPHeaderIdOffset, request_id);
4234 JDWP::Set1(buf + kJDWPHeaderFlagsOffset, kJDWPFlagReply); // flags
4235 JDWP::Set2BE(buf + kJDWPHeaderErrorCodeOffset, JDWP::ERR_NONE);
4236}
4237
4238void Dbg::FinishInvokeMethod(DebugInvokeReq* pReq) {
4239 CHECK_NE(Thread::Current(), GetDebugThread()) << "This must be called by the event thread";
4240
4241 JDWP::ExpandBuf* const pReply = pReq->reply;
4242 CHECK(pReply != nullptr) << "No reply attached to DebugInvokeReq";
4243
4244 // We need to prevent other threads (including JDWP thread) from interacting with the debugger
4245 // while we send the reply but are not yet suspended. The JDWP token will be released just before
4246 // we suspend ourself again (see ThreadList::SuspendSelfForDebugger).
4247 gJdwpState->AcquireJdwpTokenForEvent(pReq->thread_id);
4248
4249 // Send the reply unless the debugger detached before the completion of the method.
4250 if (IsDebuggerActive()) {
4251 const size_t replyDataLength = expandBufGetLength(pReply) - kJDWPHeaderLen;
4252 VLOG(jdwp) << StringPrintf("REPLY INVOKE id=0x%06x (length=%zu)",
4253 pReq->request_id, replyDataLength);
4254
4255 gJdwpState->SendRequest(pReply);
4256 } else {
4257 VLOG(jdwp) << "Not sending invoke reply because debugger detached";
Elliott Hughesd07986f2011-12-06 18:27:45 -08004258 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004259}
4260
Elliott Hughesd07986f2011-12-06 18:27:45 -08004261/*
Elliott Hughes4b9702c2013-02-20 18:13:24 -08004262 * "request" contains a full JDWP packet, possibly with multiple chunks. We
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004263 * need to process each, accumulate the replies, and ship the whole thing
4264 * back.
4265 *
4266 * Returns "true" if we have a reply. The reply buffer is newly allocated,
4267 * and includes the chunk type/length, followed by the data.
4268 *
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08004269 * OLD-TODO: we currently assume that the request and reply include a single
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004270 * chunk. If this becomes inconvenient we will need to adapt.
4271 */
Ian Rogersc0542af2014-09-03 16:16:56 -07004272bool Dbg::DdmHandlePacket(JDWP::Request* request, uint8_t** pReplyBuf, int* pReplyLen) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004273 Thread* self = Thread::Current();
4274 JNIEnv* env = self->GetJniEnv();
4275
Ian Rogersc0542af2014-09-03 16:16:56 -07004276 uint32_t type = request->ReadUnsigned32("type");
4277 uint32_t length = request->ReadUnsigned32("length");
Elliott Hughes4b9702c2013-02-20 18:13:24 -08004278
4279 // Create a byte[] corresponding to 'request'.
Ian Rogersc0542af2014-09-03 16:16:56 -07004280 size_t request_length = request->size();
Elliott Hughes4b9702c2013-02-20 18:13:24 -08004281 ScopedLocalRef<jbyteArray> dataArray(env, env->NewByteArray(request_length));
Ian Rogersc0542af2014-09-03 16:16:56 -07004282 if (dataArray.get() == nullptr) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08004283 LOG(WARNING) << "byte[] allocation failed: " << request_length;
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004284 env->ExceptionClear();
4285 return false;
4286 }
Ian Rogersc0542af2014-09-03 16:16:56 -07004287 env->SetByteArrayRegion(dataArray.get(), 0, request_length,
4288 reinterpret_cast<const jbyte*>(request->data()));
4289 request->Skip(request_length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004290
4291 // Run through and find all chunks. [Currently just find the first.]
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004292 ScopedByteArrayRO contents(env, dataArray.get());
Elliott Hughes4b9702c2013-02-20 18:13:24 -08004293 if (length != request_length) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08004294 LOG(WARNING) << StringPrintf("bad chunk found (len=%u pktLen=%zd)", length, request_length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004295 return false;
4296 }
4297
4298 // Call "private static Chunk dispatch(int type, byte[] data, int offset, int length)".
Elliott Hugheseac76672012-05-24 21:56:51 -07004299 ScopedLocalRef<jobject> chunk(env, env->CallStaticObjectMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
4300 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_dispatch,
Elliott Hughes4b9702c2013-02-20 18:13:24 -08004301 type, dataArray.get(), 0, length));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004302 if (env->ExceptionCheck()) {
4303 LOG(INFO) << StringPrintf("Exception thrown by dispatcher for 0x%08x", type);
4304 env->ExceptionDescribe();
4305 env->ExceptionClear();
4306 return false;
4307 }
4308
Ian Rogersc0542af2014-09-03 16:16:56 -07004309 if (chunk.get() == nullptr) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004310 return false;
4311 }
4312
4313 /*
4314 * Pull the pieces out of the chunk. We copy the results into a
4315 * newly-allocated buffer that the caller can free. We don't want to
4316 * continue using the Chunk object because nothing has a reference to it.
4317 *
4318 * We could avoid this by returning type/data/offset/length and having
4319 * the caller be aware of the object lifetime issues, but that
Elliott Hughes81ff3182012-03-23 20:35:56 -07004320 * integrates the JDWP code more tightly into the rest of the runtime, and doesn't work
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004321 * if we have responses for multiple chunks.
4322 *
4323 * So we're pretty much stuck with copying data around multiple times.
4324 */
Elliott Hugheseac76672012-05-24 21:56:51 -07004325 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 -08004326 jint offset = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_offset);
Elliott Hugheseac76672012-05-24 21:56:51 -07004327 length = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_length);
Elliott Hugheseac76672012-05-24 21:56:51 -07004328 type = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_type);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004329
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08004330 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 -07004331 if (length == 0 || replyData.get() == nullptr) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004332 return false;
4333 }
4334
Elliott Hughes4b9702c2013-02-20 18:13:24 -08004335 const int kChunkHdrLen = 8;
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004336 uint8_t* reply = new uint8_t[length + kChunkHdrLen];
Ian Rogersc0542af2014-09-03 16:16:56 -07004337 if (reply == nullptr) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004338 LOG(WARNING) << "malloc failed: " << (length + kChunkHdrLen);
4339 return false;
4340 }
Elliott Hughesf7c3b662011-10-27 12:04:56 -07004341 JDWP::Set4BE(reply + 0, type);
4342 JDWP::Set4BE(reply + 4, length);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004343 env->GetByteArrayRegion(replyData.get(), offset, length, reinterpret_cast<jbyte*>(reply + kChunkHdrLen));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004344
4345 *pReplyBuf = reply;
4346 *pReplyLen = length + kChunkHdrLen;
4347
Elliott Hughes4b9702c2013-02-20 18:13:24 -08004348 VLOG(jdwp) << StringPrintf("dvmHandleDdm returning type=%.4s %p len=%d", reinterpret_cast<char*>(reply), reply, length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004349 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004350}
4351
Elliott Hughesa2155262011-11-16 16:26:58 -08004352void Dbg::DdmBroadcast(bool connect) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08004353 VLOG(jdwp) << "Broadcasting DDM " << (connect ? "connect" : "disconnect") << "...";
Elliott Hughes47fce012011-10-25 18:37:19 -07004354
4355 Thread* self = Thread::Current();
Ian Rogers50b35e22012-10-04 10:09:15 -07004356 if (self->GetState() != kRunnable) {
4357 LOG(ERROR) << "DDM broadcast in thread state " << self->GetState();
4358 /* try anyway? */
Elliott Hughes47fce012011-10-25 18:37:19 -07004359 }
4360
4361 JNIEnv* env = self->GetJniEnv();
Elliott Hughes47fce012011-10-25 18:37:19 -07004362 jint event = connect ? 1 /*DdmServer.CONNECTED*/ : 2 /*DdmServer.DISCONNECTED*/;
Elliott Hugheseac76672012-05-24 21:56:51 -07004363 env->CallStaticVoidMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
4364 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_broadcast,
4365 event);
Elliott Hughes47fce012011-10-25 18:37:19 -07004366 if (env->ExceptionCheck()) {
4367 LOG(ERROR) << "DdmServer.broadcast " << event << " failed";
4368 env->ExceptionDescribe();
4369 env->ExceptionClear();
4370 }
4371}
4372
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004373void Dbg::DdmConnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08004374 Dbg::DdmBroadcast(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004375}
4376
4377void Dbg::DdmDisconnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08004378 Dbg::DdmBroadcast(false);
Elliott Hughes47fce012011-10-25 18:37:19 -07004379 gDdmThreadNotification = false;
4380}
4381
4382/*
Elliott Hughes82188472011-11-07 18:11:48 -08004383 * Send a notification when a thread starts, stops, or changes its name.
Elliott Hughes47fce012011-10-25 18:37:19 -07004384 *
4385 * Because we broadcast the full set of threads when the notifications are
4386 * first enabled, it's possible for "thread" to be actively executing.
4387 */
Elliott Hughes82188472011-11-07 18:11:48 -08004388void Dbg::DdmSendThreadNotification(Thread* t, uint32_t type) {
Elliott Hughes47fce012011-10-25 18:37:19 -07004389 if (!gDdmThreadNotification) {
4390 return;
4391 }
4392
Elliott Hughes82188472011-11-07 18:11:48 -08004393 if (type == CHUNK_TYPE("THDE")) {
Elliott Hughes47fce012011-10-25 18:37:19 -07004394 uint8_t buf[4];
Ian Rogersd9c4fc92013-10-01 19:45:43 -07004395 JDWP::Set4BE(&buf[0], t->GetThreadId());
Elliott Hughes47fce012011-10-25 18:37:19 -07004396 Dbg::DdmSendChunk(CHUNK_TYPE("THDE"), 4, buf);
Elliott Hughes82188472011-11-07 18:11:48 -08004397 } else {
4398 CHECK(type == CHUNK_TYPE("THCR") || type == CHUNK_TYPE("THNM")) << type;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004399 ScopedObjectAccessUnchecked soa(Thread::Current());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004400 StackHandleScope<1> hs(soa.Self());
Andreas Gampe08883de2016-11-08 13:20:52 -08004401 Handle<mirror::String> name(hs.NewHandle(t->GetThreadName()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004402 size_t char_count = (name != nullptr) ? name->GetLength() : 0;
4403 const jchar* chars = (name != nullptr) ? name->GetValue() : nullptr;
4404 bool is_compressed = (name != nullptr) ? name->IsCompressed() : false;
Elliott Hughes82188472011-11-07 18:11:48 -08004405
Elliott Hughes21f32d72011-11-09 17:44:13 -08004406 std::vector<uint8_t> bytes;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07004407 JDWP::Append4BE(bytes, t->GetThreadId());
jessicahandojo3aaa37b2016-07-29 14:46:37 -07004408 if (is_compressed) {
4409 const uint8_t* chars_compressed = name->GetValueCompressed();
4410 JDWP::AppendUtf16CompressedBE(bytes, chars_compressed, char_count);
4411 } else {
4412 JDWP::AppendUtf16BE(bytes, chars, char_count);
4413 }
Elliott Hughes21f32d72011-11-09 17:44:13 -08004414 CHECK_EQ(bytes.size(), char_count*2 + sizeof(uint32_t)*2);
4415 Dbg::DdmSendChunk(type, bytes);
Elliott Hughes47fce012011-10-25 18:37:19 -07004416 }
4417}
4418
Elliott Hughes47fce012011-10-25 18:37:19 -07004419void Dbg::DdmSetThreadNotification(bool enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004420 // Enable/disable thread notifications.
Elliott Hughes47fce012011-10-25 18:37:19 -07004421 gDdmThreadNotification = enable;
4422 if (enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004423 // Suspend the VM then post thread start notifications for all threads. Threads attaching will
4424 // see a suspension in progress and block until that ends. They then post their own start
4425 // notification.
4426 SuspendVM();
4427 std::list<Thread*> threads;
Ian Rogers50b35e22012-10-04 10:09:15 -07004428 Thread* self = Thread::Current();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004429 {
Ian Rogers50b35e22012-10-04 10:09:15 -07004430 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004431 threads = Runtime::Current()->GetThreadList()->GetList();
4432 }
4433 {
Ian Rogers50b35e22012-10-04 10:09:15 -07004434 ScopedObjectAccess soa(self);
Mathieu Chartier02e25112013-08-14 16:14:24 -07004435 for (Thread* thread : threads) {
4436 Dbg::DdmSendThreadNotification(thread, CHUNK_TYPE("THCR"));
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004437 }
4438 }
4439 ResumeVM();
Elliott Hughes47fce012011-10-25 18:37:19 -07004440 }
4441}
4442
Elliott Hughesa2155262011-11-16 16:26:58 -08004443void Dbg::PostThreadStartOrStop(Thread* t, uint32_t type) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07004444 if (IsDebuggerActive()) {
Sebastien Hertz6995c602014-09-09 12:10:13 +02004445 gJdwpState->PostThreadChange(t, type == CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07004446 }
Elliott Hughes82188472011-11-07 18:11:48 -08004447 Dbg::DdmSendThreadNotification(t, type);
Elliott Hughes47fce012011-10-25 18:37:19 -07004448}
4449
4450void Dbg::PostThreadStart(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004451 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07004452}
4453
4454void Dbg::PostThreadDeath(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004455 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THDE"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004456}
4457
Elliott Hughes82188472011-11-07 18:11:48 -08004458void Dbg::DdmSendChunk(uint32_t type, size_t byte_count, const uint8_t* buf) {
Ian Rogersc0542af2014-09-03 16:16:56 -07004459 CHECK(buf != nullptr);
Elliott Hughes3bb81562011-10-21 18:52:59 -07004460 iovec vec[1];
4461 vec[0].iov_base = reinterpret_cast<void*>(const_cast<uint8_t*>(buf));
4462 vec[0].iov_len = byte_count;
4463 Dbg::DdmSendChunkV(type, vec, 1);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004464}
4465
Elliott Hughes21f32d72011-11-09 17:44:13 -08004466void Dbg::DdmSendChunk(uint32_t type, const std::vector<uint8_t>& bytes) {
4467 DdmSendChunk(type, bytes.size(), &bytes[0]);
4468}
4469
Brian Carlstromf5293522013-07-19 00:24:00 -07004470void Dbg::DdmSendChunkV(uint32_t type, const iovec* iov, int iov_count) {
Ian Rogersc0542af2014-09-03 16:16:56 -07004471 if (gJdwpState == nullptr) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08004472 VLOG(jdwp) << "Debugger thread not active, ignoring DDM send: " << type;
Elliott Hughes3bb81562011-10-21 18:52:59 -07004473 } else {
Elliott Hughescccd84f2011-12-05 16:51:54 -08004474 gJdwpState->DdmSendChunkV(type, iov, iov_count);
Elliott Hughes3bb81562011-10-21 18:52:59 -07004475 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004476}
4477
Mathieu Chartierad466ad2015-01-08 16:28:08 -08004478JDWP::JdwpState* Dbg::GetJdwpState() {
4479 return gJdwpState;
4480}
4481
Elliott Hughes767a1472011-10-26 18:49:02 -07004482int Dbg::DdmHandleHpifChunk(HpifWhen when) {
4483 if (when == HPIF_WHEN_NOW) {
Elliott Hughes7162ad92011-10-27 14:08:42 -07004484 DdmSendHeapInfo(when);
Elliott Hughes767a1472011-10-26 18:49:02 -07004485 return true;
4486 }
4487
4488 if (when != HPIF_WHEN_NEVER && when != HPIF_WHEN_NEXT_GC && when != HPIF_WHEN_EVERY_GC) {
4489 LOG(ERROR) << "invalid HpifWhen value: " << static_cast<int>(when);
4490 return false;
4491 }
4492
4493 gDdmHpifWhen = when;
4494 return true;
4495}
4496
4497bool Dbg::DdmHandleHpsgNhsgChunk(Dbg::HpsgWhen when, Dbg::HpsgWhat what, bool native) {
4498 if (when != HPSG_WHEN_NEVER && when != HPSG_WHEN_EVERY_GC) {
4499 LOG(ERROR) << "invalid HpsgWhen value: " << static_cast<int>(when);
4500 return false;
4501 }
4502
4503 if (what != HPSG_WHAT_MERGED_OBJECTS && what != HPSG_WHAT_DISTINCT_OBJECTS) {
4504 LOG(ERROR) << "invalid HpsgWhat value: " << static_cast<int>(what);
4505 return false;
4506 }
4507
4508 if (native) {
4509 gDdmNhsgWhen = when;
4510 gDdmNhsgWhat = what;
4511 } else {
4512 gDdmHpsgWhen = when;
4513 gDdmHpsgWhat = what;
4514 }
4515 return true;
4516}
4517
Elliott Hughes7162ad92011-10-27 14:08:42 -07004518void Dbg::DdmSendHeapInfo(HpifWhen reason) {
4519 // If there's a one-shot 'when', reset it.
4520 if (reason == gDdmHpifWhen) {
4521 if (gDdmHpifWhen == HPIF_WHEN_NEXT_GC) {
4522 gDdmHpifWhen = HPIF_WHEN_NEVER;
4523 }
4524 }
4525
4526 /*
4527 * Chunk HPIF (client --> server)
4528 *
4529 * Heap Info. General information about the heap,
4530 * suitable for a summary display.
4531 *
4532 * [u4]: number of heaps
4533 *
4534 * For each heap:
4535 * [u4]: heap ID
4536 * [u8]: timestamp in ms since Unix epoch
4537 * [u1]: capture reason (same as 'when' value from server)
4538 * [u4]: max heap size in bytes (-Xmx)
4539 * [u4]: current heap size in bytes
4540 * [u4]: current number of bytes allocated
4541 * [u4]: current number of objects allocated
4542 */
4543 uint8_t heap_count = 1;
Ian Rogers1d54e732013-05-02 21:10:01 -07004544 gc::Heap* heap = Runtime::Current()->GetHeap();
Elliott Hughes21f32d72011-11-09 17:44:13 -08004545 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08004546 JDWP::Append4BE(bytes, heap_count);
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004547 JDWP::Append4BE(bytes, 1); // Heap id (bogus; we only have one heap).
Elliott Hughes545a0642011-11-08 19:10:03 -08004548 JDWP::Append8BE(bytes, MilliTime());
4549 JDWP::Append1BE(bytes, reason);
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004550 JDWP::Append4BE(bytes, heap->GetMaxMemory()); // Max allowed heap size in bytes.
4551 JDWP::Append4BE(bytes, heap->GetTotalMemory()); // Current heap size in bytes.
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08004552 JDWP::Append4BE(bytes, heap->GetBytesAllocated());
4553 JDWP::Append4BE(bytes, heap->GetObjectsAllocated());
Elliott Hughes21f32d72011-11-09 17:44:13 -08004554 CHECK_EQ(bytes.size(), 4U + (heap_count * (4 + 8 + 1 + 4 + 4 + 4 + 4)));
4555 Dbg::DdmSendChunk(CHUNK_TYPE("HPIF"), bytes);
Elliott Hughes767a1472011-10-26 18:49:02 -07004556}
4557
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004558enum HpsgSolidity {
4559 SOLIDITY_FREE = 0,
4560 SOLIDITY_HARD = 1,
4561 SOLIDITY_SOFT = 2,
4562 SOLIDITY_WEAK = 3,
4563 SOLIDITY_PHANTOM = 4,
4564 SOLIDITY_FINALIZABLE = 5,
4565 SOLIDITY_SWEEP = 6,
4566};
4567
4568enum HpsgKind {
4569 KIND_OBJECT = 0,
4570 KIND_CLASS_OBJECT = 1,
4571 KIND_ARRAY_1 = 2,
4572 KIND_ARRAY_2 = 3,
4573 KIND_ARRAY_4 = 4,
4574 KIND_ARRAY_8 = 5,
4575 KIND_UNKNOWN = 6,
4576 KIND_NATIVE = 7,
4577};
4578
4579#define HPSG_PARTIAL (1<<7)
4580#define HPSG_STATE(solidity, kind) ((uint8_t)((((kind) & 0x7) << 3) | ((solidity) & 0x7)))
4581
Ian Rogers30fab402012-01-23 15:43:46 -08004582class HeapChunkContext {
4583 public:
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004584 // Maximum chunk size. Obtain this from the formula:
4585 // (((maximum_heap_size / ALLOCATION_UNIT_SIZE) + 255) / 256) * 2
4586 HeapChunkContext(bool merge, bool native)
Ian Rogers30fab402012-01-23 15:43:46 -08004587 : buf_(16384 - 16),
4588 type_(0),
Mathieu Chartier36dab362014-07-30 14:59:56 -07004589 chunk_overhead_(0) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004590 Reset();
4591 if (native) {
Ian Rogers30fab402012-01-23 15:43:46 -08004592 type_ = CHUNK_TYPE("NHSG");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004593 } else {
Ian Rogers30fab402012-01-23 15:43:46 -08004594 type_ = merge ? CHUNK_TYPE("HPSG") : CHUNK_TYPE("HPSO");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004595 }
4596 }
4597
4598 ~HeapChunkContext() {
Ian Rogers30fab402012-01-23 15:43:46 -08004599 if (p_ > &buf_[0]) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004600 Flush();
4601 }
4602 }
4603
Mathieu Chartier36dab362014-07-30 14:59:56 -07004604 void SetChunkOverhead(size_t chunk_overhead) {
4605 chunk_overhead_ = chunk_overhead;
4606 }
4607
4608 void ResetStartOfNextChunk() {
4609 startOfNextMemoryChunk_ = nullptr;
4610 }
4611
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004612 void EnsureHeader(const void* chunk_ptr) {
Ian Rogers30fab402012-01-23 15:43:46 -08004613 if (!needHeader_) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004614 return;
4615 }
4616
4617 // Start a new HPSx chunk.
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004618 JDWP::Write4BE(&p_, 1); // Heap id (bogus; we only have one heap).
4619 JDWP::Write1BE(&p_, 8); // Size of allocation unit, in bytes.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004620
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004621 JDWP::Write4BE(&p_, reinterpret_cast<uintptr_t>(chunk_ptr)); // virtual address of segment start.
4622 JDWP::Write4BE(&p_, 0); // offset of this piece (relative to the virtual address).
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004623 // [u4]: length of piece, in allocation units
4624 // 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 -08004625 pieceLenField_ = p_;
4626 JDWP::Write4BE(&p_, 0x55555555);
4627 needHeader_ = false;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004628 }
4629
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004630 void Flush() REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -07004631 if (pieceLenField_ == nullptr) {
Ian Rogersd636b062013-01-18 17:51:18 -08004632 // Flush immediately post Reset (maybe back-to-back Flush). Ignore.
4633 CHECK(needHeader_);
4634 return;
4635 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004636 // Patch the "length of piece" field.
Ian Rogers30fab402012-01-23 15:43:46 -08004637 CHECK_LE(&buf_[0], pieceLenField_);
4638 CHECK_LE(pieceLenField_, p_);
4639 JDWP::Set4BE(pieceLenField_, totalAllocationUnits_);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004640
Ian Rogers30fab402012-01-23 15:43:46 -08004641 Dbg::DdmSendChunk(type_, p_ - &buf_[0], &buf_[0]);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004642 Reset();
4643 }
4644
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004645 static void HeapChunkJavaCallback(void* start, void* end, size_t used_bytes, void* arg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004646 REQUIRES_SHARED(Locks::heap_bitmap_lock_,
Ian Rogersb726dcb2012-09-05 08:57:23 -07004647 Locks::mutator_lock_) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004648 reinterpret_cast<HeapChunkContext*>(arg)->HeapChunkJavaCallback(start, end, used_bytes);
4649 }
4650
4651 static void HeapChunkNativeCallback(void* start, void* end, size_t used_bytes, void* arg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004652 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004653 reinterpret_cast<HeapChunkContext*>(arg)->HeapChunkNativeCallback(start, end, used_bytes);
Elliott Hughesa2155262011-11-16 16:26:58 -08004654 }
4655
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004656 private:
Elliott Hughesa2155262011-11-16 16:26:58 -08004657 enum { ALLOCATION_UNIT_SIZE = 8 };
4658
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004659 void Reset() {
Ian Rogers30fab402012-01-23 15:43:46 -08004660 p_ = &buf_[0];
Mathieu Chartier36dab362014-07-30 14:59:56 -07004661 ResetStartOfNextChunk();
Ian Rogers30fab402012-01-23 15:43:46 -08004662 totalAllocationUnits_ = 0;
4663 needHeader_ = true;
Ian Rogersc0542af2014-09-03 16:16:56 -07004664 pieceLenField_ = nullptr;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004665 }
4666
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004667 bool IsNative() const {
4668 return type_ == CHUNK_TYPE("NHSG");
4669 }
4670
4671 // Returns true if the object is not an empty chunk.
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004672 bool ProcessRecord(void* start, size_t used_bytes) REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers30fab402012-01-23 15:43:46 -08004673 // Note: heap call backs cannot manipulate the heap upon which they are crawling, care is taken
4674 // in the following code not to allocate memory, by ensuring buf_ is of the correct size
Ian Rogers15bf2d32012-08-28 17:33:04 -07004675 if (used_bytes == 0) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004676 if (start == nullptr) {
4677 // Reset for start of new heap.
4678 startOfNextMemoryChunk_ = nullptr;
4679 Flush();
4680 }
4681 // Only process in use memory so that free region information
4682 // also includes dlmalloc book keeping.
4683 return false;
Elliott Hughesa2155262011-11-16 16:26:58 -08004684 }
Ian Rogersc0542af2014-09-03 16:16:56 -07004685 if (startOfNextMemoryChunk_ != nullptr) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004686 // Transmit any pending free memory. Native free memory of over kMaxFreeLen could be because
4687 // of the use of mmaps, so don't report. If not free memory then start a new segment.
4688 bool flush = true;
4689 if (start > startOfNextMemoryChunk_) {
4690 const size_t kMaxFreeLen = 2 * kPageSize;
4691 void* free_start = startOfNextMemoryChunk_;
4692 void* free_end = start;
4693 const size_t free_len =
4694 reinterpret_cast<uintptr_t>(free_end) - reinterpret_cast<uintptr_t>(free_start);
4695 if (!IsNative() || free_len < kMaxFreeLen) {
4696 AppendChunk(HPSG_STATE(SOLIDITY_FREE, 0), free_start, free_len, IsNative());
4697 flush = false;
Ian Rogers15bf2d32012-08-28 17:33:04 -07004698 }
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004699 }
4700 if (flush) {
4701 startOfNextMemoryChunk_ = nullptr;
4702 Flush();
4703 }
Ian Rogers15bf2d32012-08-28 17:33:04 -07004704 }
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004705 return true;
Ian Rogers15bf2d32012-08-28 17:33:04 -07004706 }
Elliott Hughesa2155262011-11-16 16:26:58 -08004707
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004708 void HeapChunkNativeCallback(void* start, void* /*end*/, size_t used_bytes)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004709 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004710 if (ProcessRecord(start, used_bytes)) {
4711 uint8_t state = ExamineNativeObject(start);
4712 AppendChunk(state, start, used_bytes + chunk_overhead_, true /*is_native*/);
4713 startOfNextMemoryChunk_ = reinterpret_cast<char*>(start) + used_bytes + chunk_overhead_;
4714 }
4715 }
4716
4717 void HeapChunkJavaCallback(void* start, void* /*end*/, size_t used_bytes)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004718 REQUIRES_SHARED(Locks::heap_bitmap_lock_, Locks::mutator_lock_) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004719 if (ProcessRecord(start, used_bytes)) {
4720 // Determine the type of this chunk.
4721 // OLD-TODO: if context.merge, see if this chunk is different from the last chunk.
4722 // If it's the same, we should combine them.
4723 uint8_t state = ExamineJavaObject(reinterpret_cast<mirror::Object*>(start));
4724 AppendChunk(state, start, used_bytes + chunk_overhead_, false /*is_native*/);
4725 startOfNextMemoryChunk_ = reinterpret_cast<char*>(start) + used_bytes + chunk_overhead_;
4726 }
4727 }
4728
4729 void AppendChunk(uint8_t state, void* ptr, size_t length, bool is_native)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004730 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07004731 // Make sure there's enough room left in the buffer.
4732 // We need to use two bytes for every fractional 256 allocation units used by the chunk plus
4733 // 17 bytes for any header.
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004734 const size_t needed = ((RoundUp(length / ALLOCATION_UNIT_SIZE, 256) / 256) * 2) + 17;
4735 size_t byte_left = &buf_.back() - p_;
4736 if (byte_left < needed) {
4737 if (is_native) {
Pavel Vyssotski7522c742014-12-08 13:38:26 +06004738 // Cannot trigger memory allocation while walking native heap.
Pavel Vyssotski7522c742014-12-08 13:38:26 +06004739 return;
4740 }
Ian Rogers15bf2d32012-08-28 17:33:04 -07004741 Flush();
4742 }
4743
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004744 byte_left = &buf_.back() - p_;
4745 if (byte_left < needed) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07004746 LOG(WARNING) << "Chunk is too big to transmit (chunk_len=" << length << ", "
4747 << needed << " bytes)";
4748 return;
4749 }
4750 EnsureHeader(ptr);
Elliott Hughesa2155262011-11-16 16:26:58 -08004751 // Write out the chunk description.
Ian Rogers15bf2d32012-08-28 17:33:04 -07004752 length /= ALLOCATION_UNIT_SIZE; // Convert to allocation units.
4753 totalAllocationUnits_ += length;
4754 while (length > 256) {
Ian Rogers30fab402012-01-23 15:43:46 -08004755 *p_++ = state | HPSG_PARTIAL;
4756 *p_++ = 255; // length - 1
Ian Rogers15bf2d32012-08-28 17:33:04 -07004757 length -= 256;
Elliott Hughesa2155262011-11-16 16:26:58 -08004758 }
Ian Rogers30fab402012-01-23 15:43:46 -08004759 *p_++ = state;
Ian Rogers15bf2d32012-08-28 17:33:04 -07004760 *p_++ = length - 1;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004761 }
4762
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004763 uint8_t ExamineNativeObject(const void* p) REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004764 return p == nullptr ? HPSG_STATE(SOLIDITY_FREE, 0) : HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
4765 }
4766
4767 uint8_t ExamineJavaObject(mirror::Object* o)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004768 REQUIRES_SHARED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -07004769 if (o == nullptr) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004770 return HPSG_STATE(SOLIDITY_FREE, 0);
4771 }
Elliott Hughesa2155262011-11-16 16:26:58 -08004772 // It's an allocated chunk. Figure out what it is.
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004773 gc::Heap* heap = Runtime::Current()->GetHeap();
4774 if (!heap->IsLiveObjectLocked(o)) {
4775 LOG(ERROR) << "Invalid object in managed heap: " << o;
Elliott Hughesa2155262011-11-16 16:26:58 -08004776 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
4777 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004778 mirror::Class* c = o->GetClass();
Ian Rogersc0542af2014-09-03 16:16:56 -07004779 if (c == nullptr) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004780 // The object was probably just created but hasn't been initialized yet.
4781 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
4782 }
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004783 if (!heap->IsValidObjectAddress(c)) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07004784 LOG(ERROR) << "Invalid class for managed heap object: " << o << " " << c;
Elliott Hughesa2155262011-11-16 16:26:58 -08004785 return HPSG_STATE(SOLIDITY_HARD, KIND_UNKNOWN);
4786 }
Mathieu Chartierf26e1b32015-01-29 10:47:10 -08004787 if (c->GetClass() == nullptr) {
4788 LOG(ERROR) << "Null class of class " << c << " for object " << o;
4789 return HPSG_STATE(SOLIDITY_HARD, KIND_UNKNOWN);
4790 }
Elliott Hughesa2155262011-11-16 16:26:58 -08004791 if (c->IsClassClass()) {
4792 return HPSG_STATE(SOLIDITY_HARD, KIND_CLASS_OBJECT);
4793 }
Elliott Hughesa2155262011-11-16 16:26:58 -08004794 if (c->IsArrayClass()) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004795 switch (c->GetComponentSize()) {
4796 case 1: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_1);
4797 case 2: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_2);
4798 case 4: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
4799 case 8: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_8);
4800 }
4801 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004802 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
4803 }
4804
Ian Rogers30fab402012-01-23 15:43:46 -08004805 std::vector<uint8_t> buf_;
4806 uint8_t* p_;
4807 uint8_t* pieceLenField_;
Ian Rogers15bf2d32012-08-28 17:33:04 -07004808 void* startOfNextMemoryChunk_;
Ian Rogers30fab402012-01-23 15:43:46 -08004809 size_t totalAllocationUnits_;
4810 uint32_t type_;
Ian Rogers30fab402012-01-23 15:43:46 -08004811 bool needHeader_;
Mathieu Chartier36dab362014-07-30 14:59:56 -07004812 size_t chunk_overhead_;
Ian Rogers30fab402012-01-23 15:43:46 -08004813
Elliott Hughesa2155262011-11-16 16:26:58 -08004814 DISALLOW_COPY_AND_ASSIGN(HeapChunkContext);
4815};
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004816
4817void Dbg::DdmSendHeapSegments(bool native) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004818 Dbg::HpsgWhen when = native ? gDdmNhsgWhen : gDdmHpsgWhen;
4819 Dbg::HpsgWhat what = native ? gDdmNhsgWhat : gDdmHpsgWhat;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004820 if (when == HPSG_WHEN_NEVER) {
4821 return;
4822 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004823 // Figure out what kind of chunks we'll be sending.
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004824 CHECK(what == HPSG_WHAT_MERGED_OBJECTS || what == HPSG_WHAT_DISTINCT_OBJECTS)
4825 << static_cast<int>(what);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004826
4827 // First, send a heap start chunk.
4828 uint8_t heap_id[4];
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004829 JDWP::Set4BE(&heap_id[0], 1); // Heap id (bogus; we only have one heap).
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004830 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHST") : CHUNK_TYPE("HPST"), sizeof(heap_id), heap_id);
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07004831 Thread* self = Thread::Current();
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07004832 Locks::mutator_lock_->AssertSharedHeld(self);
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07004833
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004834 // Send a series of heap segment chunks.
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004835 HeapChunkContext context(what == HPSG_WHAT_MERGED_OBJECTS, native);
Andreas Gampe0c183382017-07-13 22:26:24 -07004836 auto bump_pointer_space_visitor = [&](mirror::Object* obj)
4837 REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
4838 const size_t size = RoundUp(obj->SizeOf(), kObjectAlignment);
4839 HeapChunkContext::HeapChunkJavaCallback(
4840 obj, reinterpret_cast<void*>(reinterpret_cast<uintptr_t>(obj) + size), size, &context);
4841 };
Elliott Hughesa2155262011-11-16 16:26:58 -08004842 if (native) {
Dimitry Ivanove6465bc2015-12-14 18:55:02 -08004843 UNIMPLEMENTED(WARNING) << "Native heap inspection is not supported";
Elliott Hughesa2155262011-11-16 16:26:58 -08004844 } else {
Ian Rogers1d54e732013-05-02 21:10:01 -07004845 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartier36dab362014-07-30 14:59:56 -07004846 for (const auto& space : heap->GetContinuousSpaces()) {
4847 if (space->IsDlMallocSpace()) {
Mathieu Chartier4c69d7f2014-10-10 12:45:50 -07004848 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004849 // dlmalloc's chunk header is 2 * sizeof(size_t), but if the previous chunk is in use for an
4850 // allocation then the first sizeof(size_t) may belong to it.
4851 context.SetChunkOverhead(sizeof(size_t));
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004852 space->AsDlMallocSpace()->Walk(HeapChunkContext::HeapChunkJavaCallback, &context);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004853 } else if (space->IsRosAllocSpace()) {
4854 context.SetChunkOverhead(0);
Mathieu Chartier4c69d7f2014-10-10 12:45:50 -07004855 // Need to acquire the mutator lock before the heap bitmap lock with exclusive access since
4856 // RosAlloc's internal logic doesn't know to release and reacquire the heap bitmap lock.
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07004857 ScopedThreadSuspension sts(self, kSuspended);
Mathieu Chartier4f55e222015-09-04 13:26:21 -07004858 ScopedSuspendAll ssa(__FUNCTION__);
4859 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
4860 space->AsRosAllocSpace()->Walk(HeapChunkContext::HeapChunkJavaCallback, &context);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004861 } else if (space->IsBumpPointerSpace()) {
Mathieu Chartier4c69d7f2014-10-10 12:45:50 -07004862 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004863 context.SetChunkOverhead(0);
Andreas Gampe0c183382017-07-13 22:26:24 -07004864 space->AsBumpPointerSpace()->Walk(bump_pointer_space_visitor);
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004865 HeapChunkContext::HeapChunkJavaCallback(nullptr, nullptr, 0, &context);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08004866 } else if (space->IsRegionSpace()) {
4867 heap->IncrementDisableMovingGC(self);
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07004868 {
4869 ScopedThreadSuspension sts(self, kSuspended);
Mathieu Chartier4f55e222015-09-04 13:26:21 -07004870 ScopedSuspendAll ssa(__FUNCTION__);
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07004871 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
4872 context.SetChunkOverhead(0);
Andreas Gampe0c183382017-07-13 22:26:24 -07004873 space->AsRegionSpace()->Walk(bump_pointer_space_visitor);
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07004874 HeapChunkContext::HeapChunkJavaCallback(nullptr, nullptr, 0, &context);
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07004875 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08004876 heap->DecrementDisableMovingGC(self);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004877 } else {
4878 UNIMPLEMENTED(WARNING) << "Not counting objects in space " << *space;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07004879 }
Mathieu Chartier36dab362014-07-30 14:59:56 -07004880 context.ResetStartOfNextChunk();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07004881 }
Mathieu Chartier4c69d7f2014-10-10 12:45:50 -07004882 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07004883 // Walk the large objects, these are not in the AllocSpace.
Mathieu Chartier36dab362014-07-30 14:59:56 -07004884 context.SetChunkOverhead(0);
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004885 heap->GetLargeObjectsSpace()->Walk(HeapChunkContext::HeapChunkJavaCallback, &context);
Elliott Hughesa2155262011-11-16 16:26:58 -08004886 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004887
4888 // Finally, send a heap end chunk.
4889 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHEN") : CHUNK_TYPE("HPEN"), sizeof(heap_id), heap_id);
Elliott Hughes767a1472011-10-26 18:49:02 -07004890}
4891
Brian Carlstrom306db812014-09-05 13:01:41 -07004892void Dbg::SetAllocTrackingEnabled(bool enable) {
Man Cao8c2ff642015-05-27 17:25:30 -07004893 gc::AllocRecordObjectMap::SetAllocTrackingEnabled(enable);
Elliott Hughes545a0642011-11-08 19:10:03 -08004894}
4895
4896void Dbg::DumpRecentAllocations() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004897 ScopedObjectAccess soa(Thread::Current());
Brian Carlstrom306db812014-09-05 13:01:41 -07004898 MutexLock mu(soa.Self(), *Locks::alloc_tracker_lock_);
Man Cao8c2ff642015-05-27 17:25:30 -07004899 if (!Runtime::Current()->GetHeap()->IsAllocTrackingEnabled()) {
Elliott Hughes545a0642011-11-08 19:10:03 -08004900 LOG(INFO) << "Not recording tracked allocations";
4901 return;
4902 }
Man Cao8c2ff642015-05-27 17:25:30 -07004903 gc::AllocRecordObjectMap* records = Runtime::Current()->GetHeap()->GetAllocationRecords();
4904 CHECK(records != nullptr);
Elliott Hughes545a0642011-11-08 19:10:03 -08004905
Man Cao1ed11b92015-06-11 22:47:35 -07004906 const uint16_t capped_count = CappedAllocRecordCount(records->GetRecentAllocationSize());
Brian Carlstrom306db812014-09-05 13:01:41 -07004907 uint16_t count = capped_count;
Elliott Hughes545a0642011-11-08 19:10:03 -08004908
Man Cao8c2ff642015-05-27 17:25:30 -07004909 LOG(INFO) << "Tracked allocations, (count=" << count << ")";
4910 for (auto it = records->RBegin(), end = records->REnd();
4911 count > 0 && it != end; count--, it++) {
Mathieu Chartier458b1052016-03-29 14:02:55 -07004912 const gc::AllocRecord* record = &it->second;
Elliott Hughes545a0642011-11-08 19:10:03 -08004913
Man Cao8c2ff642015-05-27 17:25:30 -07004914 LOG(INFO) << StringPrintf(" Thread %-2d %6zd bytes ", record->GetTid(), record->ByteCount())
David Sehr709b0702016-10-13 09:12:37 -07004915 << mirror::Class::PrettyClass(record->GetClass());
Elliott Hughes545a0642011-11-08 19:10:03 -08004916
Man Cao8c2ff642015-05-27 17:25:30 -07004917 for (size_t stack_frame = 0, depth = record->GetDepth(); stack_frame < depth; ++stack_frame) {
4918 const gc::AllocRecordStackTraceElement& stack_element = record->StackElement(stack_frame);
4919 ArtMethod* m = stack_element.GetMethod();
David Sehr709b0702016-10-13 09:12:37 -07004920 LOG(INFO) << " " << ArtMethod::PrettyMethod(m) << " line "
4921 << stack_element.ComputeLineNumber();
Elliott Hughes545a0642011-11-08 19:10:03 -08004922 }
4923
4924 // pause periodically to help logcat catch up
4925 if ((count % 5) == 0) {
4926 usleep(40000);
4927 }
Elliott Hughes545a0642011-11-08 19:10:03 -08004928 }
4929}
4930
4931class StringTable {
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07004932 private:
4933 struct Entry {
Andreas Gampe84eadb22017-07-07 15:08:01 -07004934 explicit Entry(const char* data_in)
4935 : data(data_in), hash(ComputeModifiedUtf8Hash(data_in)), index(0) {
4936 }
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07004937 Entry(const Entry& entry) = default;
4938 Entry(Entry&& entry) = default;
4939
4940 // Pointer to the actual string data.
4941 const char* data;
Andreas Gampe84eadb22017-07-07 15:08:01 -07004942
4943 // The hash of the data.
4944 const uint32_t hash;
4945
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07004946 // The index. This will be filled in on Finish and is not part of the ordering, so mark it
4947 // mutable.
4948 mutable uint32_t index;
4949
Andreas Gampe84eadb22017-07-07 15:08:01 -07004950 bool operator==(const Entry& other) const {
4951 return strcmp(data, other.data) == 0;
4952 }
4953 };
4954 struct EntryHash {
4955 size_t operator()(const Entry& entry) const {
4956 return entry.hash;
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07004957 }
4958 };
4959
Elliott Hughes545a0642011-11-08 19:10:03 -08004960 public:
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07004961 StringTable() : finished_(false) {
Elliott Hughes545a0642011-11-08 19:10:03 -08004962 }
4963
Andreas Gampef774a4e2017-07-06 22:15:18 -07004964 void Add(const char* str, bool copy_string) {
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07004965 DCHECK(!finished_);
Andreas Gampef774a4e2017-07-06 22:15:18 -07004966 if (UNLIKELY(copy_string)) {
4967 // Check whether it's already there.
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07004968 Entry entry(str);
4969 if (table_.find(entry) != table_.end()) {
Andreas Gampef774a4e2017-07-06 22:15:18 -07004970 return;
4971 }
Mathieu Chartier4345c462014-06-27 10:20:14 -07004972
Andreas Gampef774a4e2017-07-06 22:15:18 -07004973 // Make a copy.
4974 size_t str_len = strlen(str);
4975 char* copy = new char[str_len + 1];
4976 strlcpy(copy, str, str_len + 1);
4977 string_backup_.emplace_back(copy);
4978 str = copy;
4979 }
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07004980 Entry entry(str);
4981 table_.insert(entry);
4982 }
4983
4984 // Update all entries and give them an index. Note that this is likely not the insertion order,
4985 // as the set will with high likelihood reorder elements. Thus, Add must not be called after
4986 // Finish, and Finish must be called before IndexOf. In that case, WriteTo will walk in
4987 // the same order as Finish, and indices will agree. The order invariant, as well as indices,
4988 // are enforced through debug checks.
4989 void Finish() {
4990 DCHECK(!finished_);
4991 finished_ = true;
4992 uint32_t index = 0;
4993 for (auto& entry : table_) {
4994 entry.index = index;
4995 ++index;
4996 }
Elliott Hughes545a0642011-11-08 19:10:03 -08004997 }
4998
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004999 size_t IndexOf(const char* s) const {
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07005000 DCHECK(finished_);
5001 Entry entry(s);
5002 auto it = table_.find(entry);
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07005003 if (it == table_.end()) {
5004 LOG(FATAL) << "IndexOf(\"" << s << "\") failed";
5005 }
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07005006 return it->index;
Elliott Hughes545a0642011-11-08 19:10:03 -08005007 }
5008
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07005009 size_t Size() const {
Elliott Hughes545a0642011-11-08 19:10:03 -08005010 return table_.size();
5011 }
5012
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07005013 void WriteTo(std::vector<uint8_t>& bytes) const {
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07005014 DCHECK(finished_);
5015 uint32_t cur_index = 0;
5016 for (const auto& entry : table_) {
5017 DCHECK_EQ(cur_index++, entry.index);
5018
5019 size_t s_len = CountModifiedUtf8Chars(entry.data);
Christopher Ferris8a354052015-04-24 17:23:53 -07005020 std::unique_ptr<uint16_t[]> s_utf16(new uint16_t[s_len]);
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07005021 ConvertModifiedUtf8ToUtf16(s_utf16.get(), entry.data);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005022 JDWP::AppendUtf16BE(bytes, s_utf16.get(), s_len);
Elliott Hughes545a0642011-11-08 19:10:03 -08005023 }
5024 }
5025
5026 private:
Andreas Gampe84eadb22017-07-07 15:08:01 -07005027 std::unordered_set<Entry, EntryHash> table_;
Andreas Gampef774a4e2017-07-06 22:15:18 -07005028 std::vector<std::unique_ptr<char[]>> string_backup_;
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07005029
5030 bool finished_;
5031
Elliott Hughes545a0642011-11-08 19:10:03 -08005032 DISALLOW_COPY_AND_ASSIGN(StringTable);
5033};
5034
Mathieu Chartiere401d142015-04-22 13:56:20 -07005035static const char* GetMethodSourceFile(ArtMethod* method)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005036 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07005037 DCHECK(method != nullptr);
5038 const char* source_file = method->GetDeclaringClassSourceFile();
Sebastien Hertz280286a2014-04-28 09:26:50 +02005039 return (source_file != nullptr) ? source_file : "";
5040}
5041
Elliott Hughes545a0642011-11-08 19:10:03 -08005042/*
5043 * The data we send to DDMS contains everything we have recorded.
5044 *
5045 * Message header (all values big-endian):
5046 * (1b) message header len (to allow future expansion); includes itself
5047 * (1b) entry header len
5048 * (1b) stack frame len
5049 * (2b) number of entries
5050 * (4b) offset to string table from start of message
5051 * (2b) number of class name strings
5052 * (2b) number of method name strings
5053 * (2b) number of source file name strings
5054 * For each entry:
5055 * (4b) total allocation size
Elliott Hughes221229c2013-01-08 18:17:50 -08005056 * (2b) thread id
Elliott Hughes545a0642011-11-08 19:10:03 -08005057 * (2b) allocated object's class name index
5058 * (1b) stack depth
5059 * For each stack frame:
5060 * (2b) method's class name
5061 * (2b) method name
5062 * (2b) method source file
5063 * (2b) line number, clipped to 32767; -2 if native; -1 if no source
5064 * (xb) class name strings
5065 * (xb) method name strings
5066 * (xb) source file strings
5067 *
5068 * As with other DDM traffic, strings are sent as a 4-byte length
5069 * followed by UTF-16 data.
5070 *
5071 * We send up 16-bit unsigned indexes into string tables. In theory there
Brian Carlstrom306db812014-09-05 13:01:41 -07005072 * can be (kMaxAllocRecordStackDepth * alloc_record_max_) unique strings in
Elliott Hughes545a0642011-11-08 19:10:03 -08005073 * each table, but in practice there should be far fewer.
5074 *
5075 * The chief reason for using a string table here is to keep the size of
5076 * the DDMS message to a minimum. This is partly to make the protocol
5077 * efficient, but also because we have to form the whole thing up all at
5078 * once in a memory buffer.
5079 *
5080 * We use separate string tables for class names, method names, and source
5081 * files to keep the indexes small. There will generally be no overlap
5082 * between the contents of these tables.
5083 */
5084jbyteArray Dbg::GetRecentAllocations() {
Ian Rogerscf7f1912014-10-22 22:06:39 -07005085 if ((false)) {
Elliott Hughes545a0642011-11-08 19:10:03 -08005086 DumpRecentAllocations();
5087 }
5088
Ian Rogers50b35e22012-10-04 10:09:15 -07005089 Thread* self = Thread::Current();
Elliott Hughes545a0642011-11-08 19:10:03 -08005090 std::vector<uint8_t> bytes;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005091 {
Brian Carlstrom306db812014-09-05 13:01:41 -07005092 MutexLock mu(self, *Locks::alloc_tracker_lock_);
Man Cao8c2ff642015-05-27 17:25:30 -07005093 gc::AllocRecordObjectMap* records = Runtime::Current()->GetHeap()->GetAllocationRecords();
5094 // In case this method is called when allocation tracker is disabled,
5095 // we should still send some data back.
5096 gc::AllocRecordObjectMap dummy;
5097 if (records == nullptr) {
5098 CHECK(!Runtime::Current()->GetHeap()->IsAllocTrackingEnabled());
5099 records = &dummy;
5100 }
Man Cao41656de2015-07-06 18:53:15 -07005101 // We don't need to wait on the condition variable records->new_record_condition_, because this
5102 // function only reads the class objects, which are already marked so it doesn't change their
5103 // reachability.
Man Cao8c2ff642015-05-27 17:25:30 -07005104
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005105 //
5106 // Part 1: generate string tables.
5107 //
5108 StringTable class_names;
5109 StringTable method_names;
5110 StringTable filenames;
Elliott Hughes545a0642011-11-08 19:10:03 -08005111
Andreas Gampeff29cee2017-07-07 11:11:15 -07005112 VLOG(jdwp) << "Collecting StringTables.";
5113
Man Cao1ed11b92015-06-11 22:47:35 -07005114 const uint16_t capped_count = CappedAllocRecordCount(records->GetRecentAllocationSize());
Brian Carlstrom306db812014-09-05 13:01:41 -07005115 uint16_t count = capped_count;
Andreas Gamped0fc7682017-07-07 14:03:08 -07005116 size_t alloc_byte_count = 0;
Man Cao8c2ff642015-05-27 17:25:30 -07005117 for (auto it = records->RBegin(), end = records->REnd();
5118 count > 0 && it != end; count--, it++) {
Mathieu Chartier458b1052016-03-29 14:02:55 -07005119 const gc::AllocRecord* record = &it->second;
Ian Rogers1ff3c982014-08-12 02:30:58 -07005120 std::string temp;
Andreas Gampef774a4e2017-07-06 22:15:18 -07005121 const char* class_descr = record->GetClassDescriptor(&temp);
5122 class_names.Add(class_descr, !temp.empty());
Andreas Gamped0fc7682017-07-07 14:03:08 -07005123
5124 // Size + tid + class name index + stack depth.
5125 alloc_byte_count += 4u + 2u + 2u + 1u;
5126
Man Cao8c2ff642015-05-27 17:25:30 -07005127 for (size_t i = 0, depth = record->GetDepth(); i < depth; i++) {
5128 ArtMethod* m = record->StackElement(i).GetMethod();
Andreas Gampef774a4e2017-07-06 22:15:18 -07005129 class_names.Add(m->GetDeclaringClassDescriptor(), false);
5130 method_names.Add(m->GetName(), false);
5131 filenames.Add(GetMethodSourceFile(m), false);
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005132 }
Andreas Gamped0fc7682017-07-07 14:03:08 -07005133
5134 // Depth * (class index + method name index + file name index + line number).
5135 alloc_byte_count += record->GetDepth() * (2u + 2u + 2u + 2u);
Elliott Hughes545a0642011-11-08 19:10:03 -08005136 }
5137
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07005138 class_names.Finish();
5139 method_names.Finish();
5140 filenames.Finish();
Andreas Gampeff29cee2017-07-07 11:11:15 -07005141 VLOG(jdwp) << "Done collecting StringTables:" << std::endl
5142 << " ClassNames: " << class_names.Size() << std::endl
5143 << " MethodNames: " << method_names.Size() << std::endl
5144 << " Filenames: " << filenames.Size();
5145
Man Cao8c2ff642015-05-27 17:25:30 -07005146 LOG(INFO) << "recent allocation records: " << capped_count;
5147 LOG(INFO) << "allocation records all objects: " << records->Size();
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005148
5149 //
5150 // Part 2: Generate the output and store it in the buffer.
5151 //
5152
5153 // (1b) message header len (to allow future expansion); includes itself
5154 // (1b) entry header len
5155 // (1b) stack frame len
5156 const int kMessageHeaderLen = 15;
5157 const int kEntryHeaderLen = 9;
5158 const int kStackFrameLen = 8;
5159 JDWP::Append1BE(bytes, kMessageHeaderLen);
5160 JDWP::Append1BE(bytes, kEntryHeaderLen);
5161 JDWP::Append1BE(bytes, kStackFrameLen);
5162
5163 // (2b) number of entries
5164 // (4b) offset to string table from start of message
5165 // (2b) number of class name strings
5166 // (2b) number of method name strings
5167 // (2b) number of source file name strings
Brian Carlstrom306db812014-09-05 13:01:41 -07005168 JDWP::Append2BE(bytes, capped_count);
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005169 size_t string_table_offset = bytes.size();
Brian Carlstrom7934ac22013-07-26 10:54:15 -07005170 JDWP::Append4BE(bytes, 0); // We'll patch this later...
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005171 JDWP::Append2BE(bytes, class_names.Size());
5172 JDWP::Append2BE(bytes, method_names.Size());
5173 JDWP::Append2BE(bytes, filenames.Size());
5174
Andreas Gampeff29cee2017-07-07 11:11:15 -07005175 VLOG(jdwp) << "Dumping allocations with stacks";
5176
Andreas Gamped0fc7682017-07-07 14:03:08 -07005177 // Enlarge the vector for the allocation data.
5178 size_t reserve_size = bytes.size() + alloc_byte_count;
5179 bytes.reserve(reserve_size);
5180
Ian Rogers1ff3c982014-08-12 02:30:58 -07005181 std::string temp;
Man Cao8c2ff642015-05-27 17:25:30 -07005182 count = capped_count;
5183 // The last "count" number of allocation records in "records" are the most recent "count" number
5184 // of allocations. Reverse iterate to get them. The most recent allocation is sent first.
5185 for (auto it = records->RBegin(), end = records->REnd();
5186 count > 0 && it != end; count--, it++) {
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005187 // For each entry:
5188 // (4b) total allocation size
5189 // (2b) thread id
5190 // (2b) allocated object's class name index
5191 // (1b) stack depth
Mathieu Chartier458b1052016-03-29 14:02:55 -07005192 const gc::AllocRecord* record = &it->second;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005193 size_t stack_depth = record->GetDepth();
Mathieu Chartierf8322842014-05-16 10:59:25 -07005194 size_t allocated_object_class_name_index =
Man Cao41656de2015-07-06 18:53:15 -07005195 class_names.IndexOf(record->GetClassDescriptor(&temp));
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07005196 JDWP::Append4BE(bytes, record->ByteCount());
Man Cao8c2ff642015-05-27 17:25:30 -07005197 JDWP::Append2BE(bytes, static_cast<uint16_t>(record->GetTid()));
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005198 JDWP::Append2BE(bytes, allocated_object_class_name_index);
5199 JDWP::Append1BE(bytes, stack_depth);
5200
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005201 for (size_t stack_frame = 0; stack_frame < stack_depth; ++stack_frame) {
5202 // For each stack frame:
5203 // (2b) method's class name
5204 // (2b) method name
5205 // (2b) method source file
5206 // (2b) line number, clipped to 32767; -2 if native; -1 if no source
Man Cao8c2ff642015-05-27 17:25:30 -07005207 ArtMethod* m = record->StackElement(stack_frame).GetMethod();
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07005208 size_t class_name_index = class_names.IndexOf(m->GetDeclaringClassDescriptor());
5209 size_t method_name_index = method_names.IndexOf(m->GetName());
5210 size_t file_name_index = filenames.IndexOf(GetMethodSourceFile(m));
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005211 JDWP::Append2BE(bytes, class_name_index);
5212 JDWP::Append2BE(bytes, method_name_index);
5213 JDWP::Append2BE(bytes, file_name_index);
Man Cao8c2ff642015-05-27 17:25:30 -07005214 JDWP::Append2BE(bytes, record->StackElement(stack_frame).ComputeLineNumber());
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005215 }
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005216 }
5217
Andreas Gamped0fc7682017-07-07 14:03:08 -07005218 CHECK_EQ(bytes.size(), reserve_size);
Andreas Gampeff29cee2017-07-07 11:11:15 -07005219 VLOG(jdwp) << "Dumping tables.";
5220
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005221 // (xb) class name strings
5222 // (xb) method name strings
5223 // (xb) source file strings
5224 JDWP::Set4BE(&bytes[string_table_offset], bytes.size());
5225 class_names.WriteTo(bytes);
5226 method_names.WriteTo(bytes);
5227 filenames.WriteTo(bytes);
Andreas Gampeff29cee2017-07-07 11:11:15 -07005228
5229 VLOG(jdwp) << "GetRecentAllocations: data created. " << bytes.size();
Elliott Hughes545a0642011-11-08 19:10:03 -08005230 }
Ian Rogers50b35e22012-10-04 10:09:15 -07005231 JNIEnv* env = self->GetJniEnv();
Elliott Hughes545a0642011-11-08 19:10:03 -08005232 jbyteArray result = env->NewByteArray(bytes.size());
Ian Rogersc0542af2014-09-03 16:16:56 -07005233 if (result != nullptr) {
Elliott Hughes545a0642011-11-08 19:10:03 -08005234 env->SetByteArrayRegion(result, 0, bytes.size(), reinterpret_cast<const jbyte*>(&bytes[0]));
5235 }
5236 return result;
5237}
5238
Mathieu Chartiere401d142015-04-22 13:56:20 -07005239ArtMethod* DeoptimizationRequest::Method() const {
Andreas Gampe13b27842016-11-07 16:48:23 -08005240 return jni::DecodeArtMethod(method_);
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07005241}
5242
Mathieu Chartiere401d142015-04-22 13:56:20 -07005243void DeoptimizationRequest::SetMethod(ArtMethod* m) {
Andreas Gampe13b27842016-11-07 16:48:23 -08005244 method_ = jni::EncodeArtMethod(m);
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07005245}
5246
Mathieu Chartiera6b1ead2015-10-06 10:32:38 -07005247void Dbg::VisitRoots(RootVisitor* visitor) {
5248 // Visit breakpoint roots, used to prevent unloading of methods with breakpoints.
5249 ReaderMutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
5250 BufferedRootVisitor<128> root_visitor(visitor, RootInfo(kRootVMInternal));
5251 for (Breakpoint& breakpoint : gBreakpoints) {
Andreas Gampe542451c2016-07-26 09:02:02 -07005252 breakpoint.Method()->VisitRoots(root_visitor, kRuntimePointerSize);
Mathieu Chartiera6b1ead2015-10-06 10:32:38 -07005253 }
5254}
5255
Andreas Gampe04bbb5b2017-01-19 17:49:03 +00005256void Dbg::DbgThreadLifecycleCallback::ThreadStart(Thread* self) {
5257 Dbg::PostThreadStart(self);
5258}
5259
5260void Dbg::DbgThreadLifecycleCallback::ThreadDeath(Thread* self) {
5261 Dbg::PostThreadDeath(self);
5262}
5263
Andreas Gampe0f01b582017-01-18 15:22:37 -08005264void Dbg::DbgClassLoadCallback::ClassLoad(Handle<mirror::Class> klass ATTRIBUTE_UNUSED) {
5265 // Ignore ClassLoad;
5266}
5267void Dbg::DbgClassLoadCallback::ClassPrepare(Handle<mirror::Class> temp_klass ATTRIBUTE_UNUSED,
5268 Handle<mirror::Class> klass) {
5269 Dbg::PostClassPrepare(klass.Get());
5270}
5271
Elliott Hughes872d4ec2011-10-21 17:07:15 -07005272} // namespace art