blob: 914a7509b8218322c6374f0967f4327b2ab8e589 [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
Alex Light8c2b9292017-11-09 13:21:01 -080021#include <functional>
Andreas Gampef774a4e2017-07-06 22:15:18 -070022#include <memory>
Elliott Hughes545a0642011-11-08 19:10:03 -080023#include <set>
Andreas Gampef774a4e2017-07-06 22:15:18 -070024#include <vector>
Elliott Hughes545a0642011-11-08 19:10:03 -080025
Alex Lightb7c640d2019-03-20 15:52:13 -070026#include "android-base/macros.h"
Andreas Gampe46ee31b2016-12-14 10:11:49 -080027#include "android-base/stringprintf.h"
28
Ian Rogers166db042013-07-26 12:05:57 -070029#include "arch/context.h"
Mathieu Chartierc7853442015-03-27 14:35:38 -070030#include "art_field-inl.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070031#include "art_method-inl.h"
Andreas Gampe542451c2016-07-26 09:02:02 -070032#include "base/enums.h"
Alex Lightb7c640d2019-03-20 15:52:13 -070033#include "base/memory_tool.h"
David Sehr67bf42e2018-02-26 16:43:04 -080034#include "base/safe_map.h"
Andreas Gampef774a4e2017-07-06 22:15:18 -070035#include "base/strlcpy.h"
Vladimir Marko80afd022015-05-19 18:08:00 +010036#include "base/time_utils.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080037#include "class_linker-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -070038#include "class_linker.h"
David Sehrb2ec9f52018-02-21 13:20:31 -080039#include "dex/descriptors_names.h"
David Sehr9e734c72018-01-04 17:56:19 -080040#include "dex/dex_file-inl.h"
41#include "dex/dex_file_annotations.h"
42#include "dex/dex_file_types.h"
43#include "dex/dex_instruction.h"
David Sehr0225f8e2018-01-31 08:52:24 +000044#include "dex/utf.h"
Mingyao Yang6ea1a0e2016-01-29 12:12:49 -080045#include "entrypoints/runtime_asm_entrypoints.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070046#include "gc/accounting/card_table-inl.h"
Man Cao8c2ff642015-05-27 17:25:30 -070047#include "gc/allocation_record.h"
Andreas Gampe94c589d2017-12-27 12:43:01 -080048#include "gc/gc_cause.h"
Mathieu Chartieraa516822015-10-02 15:53:37 -070049#include "gc/scoped_gc_critical_section.h"
Andreas Gampe0c183382017-07-13 22:26:24 -070050#include "gc/space/bump_pointer_space-walk-inl.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070051#include "gc/space/large_object_space.h"
52#include "gc/space/space-inl.h"
Andreas Gampe513061a2017-06-01 09:17:34 -070053#include "handle_scope-inl.h"
Alex Lightb7c640d2019-03-20 15:52:13 -070054#include "instrumentation.h"
Sebastien Hertzcbc50642015-06-01 17:33:12 +020055#include "jdwp/jdwp_priv.h"
Vladimir Marko83114892019-04-11 13:05:50 +010056#include "jdwp/object_registry-inl.h"
Vladimir Markoa3ad0cd2018-05-04 10:06:38 +010057#include "jni/jni_internal.h"
Mathieu Chartier28bd2e42016-10-04 13:54:57 -070058#include "jvalue-inl.h"
Andreas Gampe8e0f0432018-10-24 13:38:03 -070059#include "mirror/array-alloc-inl.h"
Andreas Gampe70f5fd02018-10-24 19:58:37 -070060#include "mirror/class-alloc-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080061#include "mirror/class-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -070062#include "mirror/class.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080063#include "mirror/class_loader.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080064#include "mirror/object-inl.h"
65#include "mirror/object_array-inl.h"
Andreas Gampefd63bbf2018-10-29 12:55:35 -070066#include "mirror/string-alloc-inl.h"
Ian Rogersb0fa5dc2014-04-28 16:47:08 -070067#include "mirror/string-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080068#include "mirror/throwable.h"
Andreas Gampe373a9b52017-10-18 09:01:57 -070069#include "nativehelper/scoped_local_ref.h"
70#include "nativehelper/scoped_primitive_array.h"
Nicolas Geoffray58cc1cb2017-11-20 13:27:29 +000071#include "oat_file.h"
Mathieu Chartier3398c782016-09-30 10:27:43 -070072#include "obj_ptr-inl.h"
Ian Rogers53b8b092014-03-13 23:45:53 -070073#include "reflection.h"
David Srbecky28f6cff2018-10-16 15:07:28 +010074#include "runtime-inl.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070075#include "scoped_thread_state_change-inl.h"
Andreas Gampe513061a2017-06-01 09:17:34 -070076#include "stack.h"
Elliott Hughes475fc232011-10-25 15:00:35 -070077#include "thread_list.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070078#include "well_known_classes.h"
Elliott Hughes475fc232011-10-25 15:00:35 -070079
Elliott Hughes872d4ec2011-10-21 17:07:15 -070080namespace art {
81
Andreas Gampe46ee31b2016-12-14 10:11:49 -080082using android::base::StringPrintf;
83
Sebastien Hertz0462c4c2015-04-01 16:34:17 +020084// The key identifying the debugger to update instrumentation.
85static constexpr const char* kDbgInstrumentationKey = "Debugger";
86
Man Cao8c2ff642015-05-27 17:25:30 -070087// 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 -070088static uint16_t CappedAllocRecordCount(size_t alloc_record_count) {
Man Cao1ed11b92015-06-11 22:47:35 -070089 const size_t cap = 0xffff;
Man Cao8c2ff642015-05-27 17:25:30 -070090 if (alloc_record_count > cap) {
91 return cap;
Brian Carlstrom306db812014-09-05 13:01:41 -070092 }
93 return alloc_record_count;
94}
Elliott Hughes475fc232011-10-25 15:00:35 -070095
Mathieu Chartier41af5e52015-10-28 11:10:46 -070096class Breakpoint : public ValueObject {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -070097 public:
Mathieu Chartier41af5e52015-10-28 11:10:46 -070098 Breakpoint(ArtMethod* method, uint32_t dex_pc, DeoptimizationRequest::Kind deoptimization_kind)
Alex Light97e78032017-06-27 17:51:55 -070099 : method_(method->GetCanonicalMethod(kRuntimePointerSize)),
Mathieu Chartier41af5e52015-10-28 11:10:46 -0700100 dex_pc_(dex_pc),
101 deoptimization_kind_(deoptimization_kind) {
Sebastien Hertzf3928792014-11-17 19:00:37 +0100102 CHECK(deoptimization_kind_ == DeoptimizationRequest::kNothing ||
103 deoptimization_kind_ == DeoptimizationRequest::kSelectiveDeoptimization ||
104 deoptimization_kind_ == DeoptimizationRequest::kFullDeoptimization);
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700105 }
106
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700107 Breakpoint(const Breakpoint& other) REQUIRES_SHARED(Locks::mutator_lock_)
Mathieu Chartier41af5e52015-10-28 11:10:46 -0700108 : method_(other.method_),
109 dex_pc_(other.dex_pc_),
110 deoptimization_kind_(other.deoptimization_kind_) {}
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700111
Mathieu Chartier41af5e52015-10-28 11:10:46 -0700112 // Method() is called from root visiting, do not use ScopedObjectAccess here or it can cause
113 // GC to deadlock if another thread tries to call SuspendAll while the GC is in a runnable state.
114 ArtMethod* Method() const {
115 return method_;
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700116 }
117
118 uint32_t DexPc() const {
119 return dex_pc_;
120 }
121
Sebastien Hertzf3928792014-11-17 19:00:37 +0100122 DeoptimizationRequest::Kind GetDeoptimizationKind() const {
123 return deoptimization_kind_;
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700124 }
125
Alex Light6c8467f2015-11-20 15:03:26 -0800126 // Returns true if the method of this breakpoint and the passed in method should be considered the
127 // same. That is, they are either the same method or they are copied from the same method.
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700128 bool IsInMethod(ArtMethod* m) const REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light97e78032017-06-27 17:51:55 -0700129 return method_ == m->GetCanonicalMethod(kRuntimePointerSize);
Alex Light6c8467f2015-11-20 15:03:26 -0800130 }
131
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700132 private:
Sebastien Hertza76a6d42014-03-20 16:40:17 +0100133 // The location of this breakpoint.
Mathieu Chartier41af5e52015-10-28 11:10:46 -0700134 ArtMethod* method_;
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700135 uint32_t dex_pc_;
Sebastien Hertza76a6d42014-03-20 16:40:17 +0100136
137 // Indicates whether breakpoint needs full deoptimization or selective deoptimization.
Sebastien Hertzf3928792014-11-17 19:00:37 +0100138 DeoptimizationRequest::Kind deoptimization_kind_;
Elliott Hughes86964332012-02-15 19:37:42 -0800139};
140
Sebastien Hertzed2be172014-08-19 15:33:43 +0200141static std::ostream& operator<<(std::ostream& os, const Breakpoint& rhs)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700142 REQUIRES_SHARED(Locks::mutator_lock_) {
David Sehr709b0702016-10-13 09:12:37 -0700143 os << StringPrintf("Breakpoint[%s @%#x]", ArtMethod::PrettyMethod(rhs.Method()).c_str(),
144 rhs.DexPc());
Elliott Hughes86964332012-02-15 19:37:42 -0800145 return os;
146}
147
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100148class DebugInstrumentationListener final : public instrumentation::InstrumentationListener {
Ian Rogers62d6c772013-02-27 08:32:07 -0800149 public:
150 DebugInstrumentationListener() {}
151 virtual ~DebugInstrumentationListener() {}
152
Alex Lightd7661582017-05-01 13:48:16 -0700153 void MethodEntered(Thread* thread,
154 Handle<mirror::Object> this_object,
155 ArtMethod* method,
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200156 uint32_t dex_pc)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100157 override REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800158 if (method->IsNative()) {
159 // TODO: post location events is a suspension point and native method entry stubs aren't.
160 return;
161 }
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200162 if (IsListeningToDexPcMoved()) {
163 // We also listen to kDexPcMoved instrumentation event so we know the DexPcMoved method is
164 // going to be called right after us. To avoid sending JDWP events twice for this location,
165 // we report the event in DexPcMoved. However, we must remind this is method entry so we
166 // send the METHOD_ENTRY event. And we can also group it with other events for this location
167 // like BREAKPOINT or SINGLE_STEP (or even METHOD_EXIT if this is a RETURN instruction).
168 thread->SetDebugMethodEntry();
169 } else if (IsListeningToMethodExit() && IsReturn(method, dex_pc)) {
170 // We also listen to kMethodExited instrumentation event and the current instruction is a
171 // RETURN so we know the MethodExited method is going to be called right after us. To avoid
172 // sending JDWP events twice for this location, we report the event(s) in MethodExited.
173 // However, we must remind this is method entry so we send the METHOD_ENTRY event. And we can
174 // also group it with other events for this location like BREAKPOINT or SINGLE_STEP.
175 thread->SetDebugMethodEntry();
176 } else {
Alex Lightd7661582017-05-01 13:48:16 -0700177 Dbg::UpdateDebugger(thread, this_object.Get(), method, 0, Dbg::kMethodEntry, nullptr);
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200178 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800179 }
180
Alex Lightd7661582017-05-01 13:48:16 -0700181 void MethodExited(Thread* thread,
182 Handle<mirror::Object> this_object,
183 ArtMethod* method,
184 uint32_t dex_pc,
Alex Lightb7c640d2019-03-20 15:52:13 -0700185 instrumentation::OptionalFrame frame ATTRIBUTE_UNUSED,
186 JValue& return_value)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100187 override REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800188 if (method->IsNative()) {
189 // TODO: post location events is a suspension point and native method entry stubs aren't.
190 return;
191 }
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200192 uint32_t events = Dbg::kMethodExit;
193 if (thread->IsDebugMethodEntry()) {
194 // It is also the method entry.
195 DCHECK(IsReturn(method, dex_pc));
196 events |= Dbg::kMethodEntry;
197 thread->ClearDebugMethodEntry();
198 }
Alex Lightd7661582017-05-01 13:48:16 -0700199 Dbg::UpdateDebugger(thread, this_object.Get(), method, dex_pc, events, &return_value);
Ian Rogers62d6c772013-02-27 08:32:07 -0800200 }
201
Alex Lightd7661582017-05-01 13:48:16 -0700202 void MethodUnwind(Thread* thread ATTRIBUTE_UNUSED,
203 Handle<mirror::Object> this_object ATTRIBUTE_UNUSED,
204 ArtMethod* method,
205 uint32_t dex_pc)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100206 override REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800207 // We're not recorded to listen to this kind of event, so complain.
David Sehr709b0702016-10-13 09:12:37 -0700208 LOG(ERROR) << "Unexpected method unwind event in debugger " << ArtMethod::PrettyMethod(method)
Sebastien Hertz51db44a2013-11-19 10:00:29 +0100209 << " " << dex_pc;
Ian Rogers62d6c772013-02-27 08:32:07 -0800210 }
211
Alex Lightd7661582017-05-01 13:48:16 -0700212 void DexPcMoved(Thread* thread,
213 Handle<mirror::Object> this_object,
214 ArtMethod* method,
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200215 uint32_t new_dex_pc)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100216 override REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200217 if (IsListeningToMethodExit() && IsReturn(method, new_dex_pc)) {
218 // We also listen to kMethodExited instrumentation event and the current instruction is a
219 // RETURN so we know the MethodExited method is going to be called right after us. Like in
220 // MethodEntered, we delegate event reporting to MethodExited.
221 // Besides, if this RETURN instruction is the only one in the method, we can send multiple
222 // JDWP events in the same packet: METHOD_ENTRY, METHOD_EXIT, BREAKPOINT and/or SINGLE_STEP.
223 // Therefore, we must not clear the debug method entry flag here.
224 } else {
225 uint32_t events = 0;
226 if (thread->IsDebugMethodEntry()) {
227 // It is also the method entry.
228 events = Dbg::kMethodEntry;
229 thread->ClearDebugMethodEntry();
230 }
Alex Lightd7661582017-05-01 13:48:16 -0700231 Dbg::UpdateDebugger(thread, this_object.Get(), method, new_dex_pc, events, nullptr);
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200232 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800233 }
234
Alex Lightd7661582017-05-01 13:48:16 -0700235 void FieldRead(Thread* thread ATTRIBUTE_UNUSED,
236 Handle<mirror::Object> this_object,
237 ArtMethod* method,
238 uint32_t dex_pc,
239 ArtField* field)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100240 override REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Lightd7661582017-05-01 13:48:16 -0700241 Dbg::PostFieldAccessEvent(method, dex_pc, this_object.Get(), field);
Ian Rogers62d6c772013-02-27 08:32:07 -0800242 }
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200243
Alex Lightd7661582017-05-01 13:48:16 -0700244 void FieldWritten(Thread* thread ATTRIBUTE_UNUSED,
245 Handle<mirror::Object> this_object,
246 ArtMethod* method,
247 uint32_t dex_pc,
248 ArtField* field,
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700249 const JValue& field_value)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100250 override REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Lightd7661582017-05-01 13:48:16 -0700251 Dbg::PostFieldModificationEvent(method, dex_pc, this_object.Get(), field, &field_value);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200252 }
253
Alex Light6e1607e2017-08-23 10:06:18 -0700254 void ExceptionThrown(Thread* thread ATTRIBUTE_UNUSED,
Alex Lightd7661582017-05-01 13:48:16 -0700255 Handle<mirror::Throwable> exception_object)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100256 override REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Lightd7661582017-05-01 13:48:16 -0700257 Dbg::PostException(exception_object.Get());
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200258 }
259
Nicolas Geoffray81f0f952016-01-20 16:25:19 +0000260 // We only care about branches in the Jit.
261 void Branch(Thread* /*thread*/, ArtMethod* method, uint32_t dex_pc, int32_t dex_pc_offset)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100262 override REQUIRES_SHARED(Locks::mutator_lock_) {
David Sehr709b0702016-10-13 09:12:37 -0700263 LOG(ERROR) << "Unexpected branch event in debugger " << ArtMethod::PrettyMethod(method)
Nicolas Geoffray81f0f952016-01-20 16:25:19 +0000264 << " " << dex_pc << ", " << dex_pc_offset;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800265 }
266
Alex Light798eab02017-08-23 12:54:53 -0700267 // TODO Might be worth it to post ExceptionCatch event.
268 void ExceptionHandled(Thread* thread ATTRIBUTE_UNUSED,
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100269 Handle<mirror::Throwable> throwable ATTRIBUTE_UNUSED) override {
Alex Light798eab02017-08-23 12:54:53 -0700270 LOG(ERROR) << "Unexpected exception handled event in debugger";
271 }
272
Alex Light05f47742017-09-14 00:34:44 +0000273 // TODO Might be worth it to implement this.
274 void WatchedFramePop(Thread* thread ATTRIBUTE_UNUSED,
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100275 const ShadowFrame& frame ATTRIBUTE_UNUSED) override {
Alex Light05f47742017-09-14 00:34:44 +0000276 LOG(ERROR) << "Unexpected WatchedFramePop event in debugger";
277 }
Alex Light798eab02017-08-23 12:54:53 -0700278
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200279 private:
Mathieu Chartier808c7a52017-12-15 11:19:33 -0800280 static bool IsReturn(ArtMethod* method, uint32_t dex_pc) REQUIRES_SHARED(Locks::mutator_lock_) {
281 return method->DexInstructions().InstructionAt(dex_pc).IsReturn();
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200282 }
283
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700284 static bool IsListeningToDexPcMoved() REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200285 return IsListeningTo(instrumentation::Instrumentation::kDexPcMoved);
286 }
287
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700288 static bool IsListeningToMethodExit() REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200289 return IsListeningTo(instrumentation::Instrumentation::kMethodExited);
290 }
291
292 static bool IsListeningTo(instrumentation::Instrumentation::InstrumentationEvent event)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700293 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200294 return (Dbg::GetInstrumentationEvents() & event) != 0;
295 }
296
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200297 DISALLOW_COPY_AND_ASSIGN(DebugInstrumentationListener);
Ian Rogers62d6c772013-02-27 08:32:07 -0800298} gDebugInstrumentationListener;
299
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700300// JDWP is allowed unless the Zygote forbids it.
301static bool gJdwpAllowed = true;
302
Elliott Hughesc0f09332012-03-26 13:27:06 -0700303// Was there a -Xrunjdwp or -agentlib:jdwp= argument on the command line?
Elliott Hughes3bb81562011-10-21 18:52:59 -0700304static bool gJdwpConfigured = false;
305
Sebastien Hertzb3b173b2015-02-06 09:16:32 +0100306// JDWP options for debugging. Only valid if IsJdwpConfigured() is true.
307static JDWP::JdwpOptions gJdwpOptions;
308
Elliott Hughes3bb81562011-10-21 18:52:59 -0700309// Runtime JDWP state.
Ian Rogersc0542af2014-09-03 16:16:56 -0700310static JDWP::JdwpState* gJdwpState = nullptr;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700311static bool gDebuggerConnected; // debugger or DDMS is connected.
Elliott Hughes3bb81562011-10-21 18:52:59 -0700312
Elliott Hughes47fce012011-10-25 18:37:19 -0700313static bool gDdmThreadNotification = false;
314
Elliott Hughes767a1472011-10-26 18:49:02 -0700315// DDMS GC-related settings.
316static Dbg::HpifWhen gDdmHpifWhen = Dbg::HPIF_WHEN_NEVER;
317static Dbg::HpsgWhen gDdmHpsgWhen = Dbg::HPSG_WHEN_NEVER;
318static Dbg::HpsgWhat gDdmHpsgWhat;
319static Dbg::HpsgWhen gDdmNhsgWhen = Dbg::HPSG_WHEN_NEVER;
320static Dbg::HpsgWhat gDdmNhsgWhat;
321
Daniel Mihalyieb076692014-08-22 17:33:31 +0200322bool Dbg::gDebuggerActive = false;
Sebastien Hertz4e5b2082015-03-24 19:03:40 +0100323bool Dbg::gDisposed = false;
Sebastien Hertz6995c602014-09-09 12:10:13 +0200324ObjectRegistry* Dbg::gRegistry = nullptr;
Alex Light21611932017-09-26 13:07:39 -0700325DebuggerActiveMethodInspectionCallback Dbg::gDebugActiveCallback;
Alex Light8c2b9292017-11-09 13:21:01 -0800326DebuggerDdmCallback Dbg::gDebugDdmCallback;
Alex Light40320712017-12-14 11:52:04 -0800327InternalDebuggerControlCallback Dbg::gDebuggerControlCallback;
Elliott Hughes475fc232011-10-25 15:00:35 -0700328
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100329// Deoptimization support.
Sebastien Hertz4d25df32014-03-21 17:44:46 +0100330std::vector<DeoptimizationRequest> Dbg::deoptimization_requests_;
331size_t Dbg::full_deoptimization_event_count_ = 0;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100332
Sebastien Hertz42cd43f2014-05-13 14:15:41 +0200333// Instrumentation event reference counters.
334size_t Dbg::dex_pc_change_event_ref_count_ = 0;
335size_t Dbg::method_enter_event_ref_count_ = 0;
336size_t Dbg::method_exit_event_ref_count_ = 0;
337size_t Dbg::field_read_event_ref_count_ = 0;
338size_t Dbg::field_write_event_ref_count_ = 0;
339size_t Dbg::exception_catch_event_ref_count_ = 0;
340uint32_t Dbg::instrumentation_events_ = 0;
341
Andreas Gampe04bbb5b2017-01-19 17:49:03 +0000342Dbg::DbgThreadLifecycleCallback Dbg::thread_lifecycle_callback_;
Andreas Gampe0f01b582017-01-18 15:22:37 -0800343Dbg::DbgClassLoadCallback Dbg::class_load_callback_;
Andreas Gampe04bbb5b2017-01-19 17:49:03 +0000344
Alex Light8c2b9292017-11-09 13:21:01 -0800345void DebuggerDdmCallback::DdmPublishChunk(uint32_t type, const ArrayRef<const uint8_t>& data) {
Alex Light772099a2017-11-21 14:05:04 -0800346 if (gJdwpState == nullptr) {
347 VLOG(jdwp) << "Debugger thread not active, ignoring DDM send: " << type;
348 } else {
349 iovec vec[1];
350 vec[0].iov_base = reinterpret_cast<void*>(const_cast<uint8_t*>(data.data()));
351 vec[0].iov_len = data.size();
352 gJdwpState->DdmSendChunkV(type, vec, 1);
353 }
Alex Light8c2b9292017-11-09 13:21:01 -0800354}
355
Alex Light21611932017-09-26 13:07:39 -0700356bool DebuggerActiveMethodInspectionCallback::IsMethodBeingInspected(ArtMethod* m ATTRIBUTE_UNUSED) {
357 return Dbg::IsDebuggerActive();
358}
359
Alex Light0fa17862017-10-24 13:43:05 -0700360bool DebuggerActiveMethodInspectionCallback::IsMethodSafeToJit(ArtMethod* m) {
361 return !Dbg::MethodHasAnyBreakpoints(m);
362}
363
Alex Lightf2858632018-04-02 11:28:50 -0700364bool DebuggerActiveMethodInspectionCallback::MethodNeedsDebugVersion(
365 ArtMethod* m ATTRIBUTE_UNUSED) {
366 return Dbg::IsDebuggerActive();
367}
368
Alex Light40320712017-12-14 11:52:04 -0800369void InternalDebuggerControlCallback::StartDebugger() {
370 // Release the mutator lock.
371 ScopedThreadStateChange stsc(art::Thread::Current(), kNative);
372 Dbg::StartJdwp();
373}
374
375void InternalDebuggerControlCallback::StopDebugger() {
376 Dbg::StopJdwp();
377}
378
379bool InternalDebuggerControlCallback::IsDebuggerConfigured() {
380 return Dbg::IsJdwpConfigured();
381}
382
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100383// Breakpoints.
jeffhao09bfc6a2012-12-11 18:11:43 -0800384static std::vector<Breakpoint> gBreakpoints GUARDED_BY(Locks::breakpoint_lock_);
Elliott Hughes86964332012-02-15 19:37:42 -0800385
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700386void DebugInvokeReq::VisitRoots(RootVisitor* visitor, const RootInfo& root_info) {
387 receiver.VisitRootIfNonNull(visitor, root_info); // null for static method call.
388 klass.VisitRoot(visitor, root_info);
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700389}
390
Sebastien Hertz597c4f02015-01-26 17:37:14 +0100391void SingleStepControl::AddDexPc(uint32_t dex_pc) {
392 dex_pcs_.insert(dex_pc);
Sebastien Hertzbb43b432014-04-14 11:59:08 +0200393}
394
Sebastien Hertz597c4f02015-01-26 17:37:14 +0100395bool SingleStepControl::ContainsDexPc(uint32_t dex_pc) const {
396 return dex_pcs_.find(dex_pc) == dex_pcs_.end();
Sebastien Hertzbb43b432014-04-14 11:59:08 +0200397}
398
Alex Light6c8467f2015-11-20 15:03:26 -0800399static bool IsBreakpoint(ArtMethod* m, uint32_t dex_pc)
Mathieu Chartier90443472015-07-16 20:32:27 -0700400 REQUIRES(!Locks::breakpoint_lock_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700401 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertzed2be172014-08-19 15:33:43 +0200402 ReaderMutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100403 for (size_t i = 0, e = gBreakpoints.size(); i < e; ++i) {
Alex Light6c8467f2015-11-20 15:03:26 -0800404 if (gBreakpoints[i].DexPc() == dex_pc && gBreakpoints[i].IsInMethod(m)) {
Elliott Hughes86964332012-02-15 19:37:42 -0800405 VLOG(jdwp) << "Hit breakpoint #" << i << ": " << gBreakpoints[i];
406 return true;
407 }
408 }
409 return false;
410}
411
Sebastien Hertz52d131d2014-03-13 16:17:40 +0100412static bool IsSuspendedForDebugger(ScopedObjectAccessUnchecked& soa, Thread* thread)
Mathieu Chartier90443472015-07-16 20:32:27 -0700413 REQUIRES(!Locks::thread_suspend_count_lock_) {
Elliott Hughes9e0c1752013-01-09 14:02:58 -0800414 MutexLock mu(soa.Self(), *Locks::thread_suspend_count_lock_);
415 // A thread may be suspended for GC; in this code, we really want to know whether
416 // there's a debugger suspension active.
417 return thread->IsSuspended() && thread->GetDebugSuspendCount() > 0;
418}
419
Vladimir Marko4617d582019-03-28 13:48:31 +0000420static ObjPtr<mirror::Array> DecodeNonNullArray(JDWP::RefTypeId id, JDWP::JdwpError* error)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700421 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko83114892019-04-11 13:05:50 +0100422 ObjPtr<mirror::Object> o = Dbg::GetObjectRegistry()->Get<mirror::Object>(id, error);
Ian Rogersc0542af2014-09-03 16:16:56 -0700423 if (o == nullptr) {
424 *error = JDWP::ERR_INVALID_OBJECT;
425 return nullptr;
Elliott Hughes436e3722012-02-17 20:01:47 -0800426 }
427 if (!o->IsArrayInstance()) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700428 *error = JDWP::ERR_INVALID_ARRAY;
429 return nullptr;
Elliott Hughes436e3722012-02-17 20:01:47 -0800430 }
Ian Rogersc0542af2014-09-03 16:16:56 -0700431 *error = JDWP::ERR_NONE;
Elliott Hughes436e3722012-02-17 20:01:47 -0800432 return o->AsArray();
433}
434
Vladimir Marko4617d582019-03-28 13:48:31 +0000435static ObjPtr<mirror::Class> DecodeClass(JDWP::RefTypeId id, JDWP::JdwpError* error)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700436 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko83114892019-04-11 13:05:50 +0100437 ObjPtr<mirror::Object> o = Dbg::GetObjectRegistry()->Get<mirror::Object>(id, error);
Ian Rogersc0542af2014-09-03 16:16:56 -0700438 if (o == nullptr) {
439 *error = JDWP::ERR_INVALID_OBJECT;
440 return nullptr;
Elliott Hughes436e3722012-02-17 20:01:47 -0800441 }
442 if (!o->IsClass()) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700443 *error = JDWP::ERR_INVALID_CLASS;
444 return nullptr;
Elliott Hughes436e3722012-02-17 20:01:47 -0800445 }
Ian Rogersc0542af2014-09-03 16:16:56 -0700446 *error = JDWP::ERR_NONE;
Elliott Hughes436e3722012-02-17 20:01:47 -0800447 return o->AsClass();
448}
449
Ian Rogersc0542af2014-09-03 16:16:56 -0700450static Thread* DecodeThread(ScopedObjectAccessUnchecked& soa, JDWP::ObjectId thread_id,
451 JDWP::JdwpError* error)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700452 REQUIRES_SHARED(Locks::mutator_lock_)
Mathieu Chartier90443472015-07-16 20:32:27 -0700453 REQUIRES(!Locks::thread_list_lock_, !Locks::thread_suspend_count_lock_) {
Vladimir Marko4617d582019-03-28 13:48:31 +0000454 ObjPtr<mirror::Object> thread_peer =
Vladimir Marko83114892019-04-11 13:05:50 +0100455 Dbg::GetObjectRegistry()->Get<mirror::Object>(thread_id, error);
Ian Rogersc0542af2014-09-03 16:16:56 -0700456 if (thread_peer == nullptr) {
Elliott Hughes221229c2013-01-08 18:17:50 -0800457 // This isn't even an object.
Ian Rogersc0542af2014-09-03 16:16:56 -0700458 *error = JDWP::ERR_INVALID_OBJECT;
459 return nullptr;
Elliott Hughes436e3722012-02-17 20:01:47 -0800460 }
Elliott Hughes221229c2013-01-08 18:17:50 -0800461
Mathieu Chartier0795f232016-09-27 18:43:30 -0700462 ObjPtr<mirror::Class> java_lang_Thread =
463 soa.Decode<mirror::Class>(WellKnownClasses::java_lang_Thread);
Elliott Hughes221229c2013-01-08 18:17:50 -0800464 if (!java_lang_Thread->IsAssignableFrom(thread_peer->GetClass())) {
465 // This isn't a thread.
Ian Rogersc0542af2014-09-03 16:16:56 -0700466 *error = JDWP::ERR_INVALID_THREAD;
467 return nullptr;
Elliott Hughes221229c2013-01-08 18:17:50 -0800468 }
469
Sebastien Hertz69206392015-04-07 15:54:25 +0200470 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogersc0542af2014-09-03 16:16:56 -0700471 Thread* thread = Thread::FromManagedThread(soa, thread_peer);
472 // If thread is null then this a java.lang.Thread without a Thread*. Must be a un-started or a
473 // zombie.
474 *error = (thread == nullptr) ? JDWP::ERR_THREAD_NOT_ALIVE : JDWP::ERR_NONE;
475 return thread;
Elliott Hughes436e3722012-02-17 20:01:47 -0800476}
477
Elliott Hughes24437992011-11-30 14:49:33 -0800478static JDWP::JdwpTag BasicTagFromDescriptor(const char* descriptor) {
479 // JDWP deliberately uses the descriptor characters' ASCII values for its enum.
480 // Note that by "basic" we mean that we don't get more specific than JT_OBJECT.
481 return static_cast<JDWP::JdwpTag>(descriptor[0]);
482}
483
Vladimir Markoc524e9e2019-03-26 10:54:50 +0000484static JDWP::JdwpTag BasicTagFromClass(ObjPtr<mirror::Class> klass)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700485 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers1ff3c982014-08-12 02:30:58 -0700486 std::string temp;
487 const char* descriptor = klass->GetDescriptor(&temp);
488 return BasicTagFromDescriptor(descriptor);
489}
490
Vladimir Marko83114892019-04-11 13:05:50 +0100491static JDWP::JdwpTag TagFromClass(const ScopedObjectAccessUnchecked& soa, ObjPtr<mirror::Class> c)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700492 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700493 CHECK(c != nullptr);
Elliott Hughes24437992011-11-30 14:49:33 -0800494 if (c->IsArrayClass()) {
495 return JDWP::JT_ARRAY;
496 }
Elliott Hughes24437992011-11-30 14:49:33 -0800497 if (c->IsStringClass()) {
498 return JDWP::JT_STRING;
Elliott Hughes24437992011-11-30 14:49:33 -0800499 }
Ian Rogers98379392014-02-24 16:53:16 -0800500 if (c->IsClassClass()) {
501 return JDWP::JT_CLASS_OBJECT;
502 }
503 {
Mathieu Chartier0795f232016-09-27 18:43:30 -0700504 ObjPtr<mirror::Class> thread_class =
505 soa.Decode<mirror::Class>(WellKnownClasses::java_lang_Thread);
Ian Rogers98379392014-02-24 16:53:16 -0800506 if (thread_class->IsAssignableFrom(c)) {
507 return JDWP::JT_THREAD;
508 }
509 }
510 {
Mathieu Chartier0795f232016-09-27 18:43:30 -0700511 ObjPtr<mirror::Class> thread_group_class =
512 soa.Decode<mirror::Class>(WellKnownClasses::java_lang_ThreadGroup);
Ian Rogers98379392014-02-24 16:53:16 -0800513 if (thread_group_class->IsAssignableFrom(c)) {
514 return JDWP::JT_THREAD_GROUP;
515 }
516 }
517 {
Mathieu Chartier0795f232016-09-27 18:43:30 -0700518 ObjPtr<mirror::Class> class_loader_class =
519 soa.Decode<mirror::Class>(WellKnownClasses::java_lang_ClassLoader);
Ian Rogers98379392014-02-24 16:53:16 -0800520 if (class_loader_class->IsAssignableFrom(c)) {
521 return JDWP::JT_CLASS_LOADER;
522 }
523 }
524 return JDWP::JT_OBJECT;
Elliott Hughes24437992011-11-30 14:49:33 -0800525}
526
527/*
528 * Objects declared to hold Object might actually hold a more specific
529 * type. The debugger may take a special interest in these (e.g. it
530 * wants to display the contents of Strings), so we want to return an
531 * appropriate tag.
532 *
533 * Null objects are tagged JT_OBJECT.
534 */
Vladimir Marko423bebb2019-03-26 15:17:21 +0000535JDWP::JdwpTag Dbg::TagFromObject(const ScopedObjectAccessUnchecked& soa, ObjPtr<mirror::Object> o) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700536 return (o == nullptr) ? JDWP::JT_OBJECT : TagFromClass(soa, o->GetClass());
Elliott Hughes24437992011-11-30 14:49:33 -0800537}
538
539static bool IsPrimitiveTag(JDWP::JdwpTag tag) {
540 switch (tag) {
541 case JDWP::JT_BOOLEAN:
542 case JDWP::JT_BYTE:
543 case JDWP::JT_CHAR:
544 case JDWP::JT_FLOAT:
545 case JDWP::JT_DOUBLE:
546 case JDWP::JT_INT:
547 case JDWP::JT_LONG:
548 case JDWP::JT_SHORT:
549 case JDWP::JT_VOID:
550 return true;
551 default:
552 return false;
553 }
554}
555
Sebastien Hertzb3b173b2015-02-06 09:16:32 +0100556void Dbg::StartJdwp() {
Elliott Hughesc0f09332012-03-26 13:27:06 -0700557 if (!gJdwpAllowed || !IsJdwpConfigured()) {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700558 // No JDWP for you!
559 return;
560 }
561
Ian Rogers719d1a32014-03-06 12:13:39 -0800562 CHECK(gRegistry == nullptr);
Elliott Hughes475fc232011-10-25 15:00:35 -0700563 gRegistry = new ObjectRegistry;
564
Alex Light8c2b9292017-11-09 13:21:01 -0800565 {
566 // Setup the Ddm listener
567 ScopedObjectAccess soa(Thread::Current());
568 Runtime::Current()->GetRuntimeCallbacks()->AddDdmCallback(&gDebugDdmCallback);
569 }
570
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700571 // Init JDWP if the debugger is enabled. This may connect out to a
572 // debugger, passively listen for a debugger, or block waiting for a
573 // debugger.
Sebastien Hertzb3b173b2015-02-06 09:16:32 +0100574 gJdwpState = JDWP::JdwpState::Create(&gJdwpOptions);
Ian Rogersc0542af2014-09-03 16:16:56 -0700575 if (gJdwpState == nullptr) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -0800576 // We probably failed because some other process has the port already, which means that
577 // if we don't abort the user is likely to think they're talking to us when they're actually
578 // talking to that other process.
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800579 LOG(FATAL) << "Debugger thread failed to initialize";
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700580 }
581
582 // If a debugger has already attached, send the "welcome" message.
583 // This may cause us to suspend all threads.
Elliott Hughes376a7a02011-10-24 18:35:55 -0700584 if (gJdwpState->IsActive()) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700585 ScopedObjectAccess soa(Thread::Current());
Sebastien Hertz7d955652014-10-22 10:57:10 +0200586 gJdwpState->PostVMStart();
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700587 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700588}
589
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700590void Dbg::StopJdwp() {
Sebastien Hertzc6345ef2014-08-18 19:26:39 +0200591 // Post VM_DEATH event before the JDWP connection is closed (either by the JDWP thread or the
592 // destruction of gJdwpState).
593 if (gJdwpState != nullptr && gJdwpState->IsActive()) {
594 gJdwpState->PostVMDeath();
595 }
Sebastien Hertz0376e6b2014-02-06 18:12:59 +0100596 // Prevent the JDWP thread from processing JDWP incoming packets after we close the connection.
Sebastien Hertz4e5b2082015-03-24 19:03:40 +0100597 Dispose();
Elliott Hughes376a7a02011-10-24 18:35:55 -0700598 delete gJdwpState;
Ian Rogers719d1a32014-03-06 12:13:39 -0800599 gJdwpState = nullptr;
Elliott Hughes475fc232011-10-25 15:00:35 -0700600 delete gRegistry;
Ian Rogers719d1a32014-03-06 12:13:39 -0800601 gRegistry = nullptr;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700602}
603
Elliott Hughes767a1472011-10-26 18:49:02 -0700604void Dbg::GcDidFinish() {
605 if (gDdmHpifWhen != HPIF_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700606 ScopedObjectAccess soa(Thread::Current());
Brian Carlstrom4d466a82014-05-08 19:05:29 -0700607 VLOG(jdwp) << "Sending heap info to DDM";
Elliott Hughes7162ad92011-10-27 14:08:42 -0700608 DdmSendHeapInfo(gDdmHpifWhen);
Elliott Hughes767a1472011-10-26 18:49:02 -0700609 }
610 if (gDdmHpsgWhen != HPSG_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700611 ScopedObjectAccess soa(Thread::Current());
Brian Carlstrom4d466a82014-05-08 19:05:29 -0700612 VLOG(jdwp) << "Dumping heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700613 DdmSendHeapSegments(false);
Elliott Hughes767a1472011-10-26 18:49:02 -0700614 }
615 if (gDdmNhsgWhen != HPSG_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700616 ScopedObjectAccess soa(Thread::Current());
Brian Carlstrom4d466a82014-05-08 19:05:29 -0700617 VLOG(jdwp) << "Dumping native heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700618 DdmSendHeapSegments(true);
Elliott Hughes767a1472011-10-26 18:49:02 -0700619 }
620}
621
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700622void Dbg::SetJdwpAllowed(bool allowed) {
623 gJdwpAllowed = allowed;
624}
625
Leonard Mosescueb842212016-10-06 17:26:36 -0700626bool Dbg::IsJdwpAllowed() {
627 return gJdwpAllowed;
628}
629
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700630DebugInvokeReq* Dbg::GetInvokeReq() {
Elliott Hughes475fc232011-10-25 15:00:35 -0700631 return Thread::Current()->GetInvokeReq();
632}
633
634Thread* Dbg::GetDebugThread() {
Ian Rogersc0542af2014-09-03 16:16:56 -0700635 return (gJdwpState != nullptr) ? gJdwpState->GetDebugThread() : nullptr;
Elliott Hughes475fc232011-10-25 15:00:35 -0700636}
637
638void Dbg::ClearWaitForEventThread() {
Sebastien Hertz2bf93f42015-01-09 18:44:05 +0100639 gJdwpState->ReleaseJdwpTokenForEvent();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700640}
641
642void Dbg::Connected() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700643 CHECK(!gDebuggerConnected);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800644 VLOG(jdwp) << "JDWP has attached";
Elliott Hughes3bb81562011-10-21 18:52:59 -0700645 gDebuggerConnected = true;
Elliott Hughes86964332012-02-15 19:37:42 -0800646 gDisposed = false;
647}
648
Sebastien Hertzf3928792014-11-17 19:00:37 +0100649bool Dbg::RequiresDeoptimization() {
650 // We don't need deoptimization if everything runs with interpreter after
651 // enabling -Xint mode.
652 return !Runtime::Current()->GetInstrumentation()->IsForcedInterpretOnly();
653}
654
Elliott Hughesa2155262011-11-16 16:26:58 -0800655void Dbg::GoActive() {
656 // Enable all debugging features, including scans for breakpoints.
657 // This is a no-op if we're already active.
658 // Only called from the JDWP handler thread.
Daniel Mihalyieb076692014-08-22 17:33:31 +0200659 if (IsDebuggerActive()) {
Elliott Hughesa2155262011-11-16 16:26:58 -0800660 return;
661 }
662
Mathieu Chartieraa516822015-10-02 15:53:37 -0700663 Thread* const self = Thread::Current();
Elliott Hughesc0f09332012-03-26 13:27:06 -0700664 {
665 // TODO: dalvik only warned if there were breakpoints left over. clear in Dbg::Disconnected?
Mathieu Chartieraa516822015-10-02 15:53:37 -0700666 ReaderMutexLock mu(self, *Locks::breakpoint_lock_);
Elliott Hughesc0f09332012-03-26 13:27:06 -0700667 CHECK_EQ(gBreakpoints.size(), 0U);
668 }
Elliott Hughesa2155262011-11-16 16:26:58 -0800669
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100670 {
Mathieu Chartieraa516822015-10-02 15:53:37 -0700671 MutexLock mu(self, *Locks::deoptimization_lock_);
Sebastien Hertz4d25df32014-03-21 17:44:46 +0100672 CHECK_EQ(deoptimization_requests_.size(), 0U);
673 CHECK_EQ(full_deoptimization_event_count_, 0U);
Sebastien Hertz42cd43f2014-05-13 14:15:41 +0200674 CHECK_EQ(dex_pc_change_event_ref_count_, 0U);
675 CHECK_EQ(method_enter_event_ref_count_, 0U);
676 CHECK_EQ(method_exit_event_ref_count_, 0U);
677 CHECK_EQ(field_read_event_ref_count_, 0U);
678 CHECK_EQ(field_write_event_ref_count_, 0U);
679 CHECK_EQ(exception_catch_event_ref_count_, 0U);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100680 }
681
Ian Rogers62d6c772013-02-27 08:32:07 -0800682 Runtime* runtime = Runtime::Current();
Nicolas Geoffray433b79a2017-01-30 20:54:45 +0000683 // Best effort deoptimization if the runtime is non-Java debuggable. This happens when
684 // ro.debuggable is set, but the application is not debuggable, or when a standalone
685 // dalvikvm invocation is not passed the debuggable option (-Xcompiler-option --debuggable).
686 //
687 // The performance cost of this is non-negligible during native-debugging due to the
David Srbeckyf4480162016-03-16 00:06:24 +0000688 // forced JIT, so we keep the AOT code in that case in exchange for limited native debugging.
Nicolas Geoffray226805d2018-12-14 10:59:02 +0000689 ScopedSuspendAll ssa(__FUNCTION__);
Nicolas Geoffray433b79a2017-01-30 20:54:45 +0000690 if (!runtime->IsJavaDebuggable() &&
691 !runtime->GetInstrumentation()->IsForcedInterpretOnly() &&
692 !runtime->IsNativeDebuggable()) {
693 runtime->DeoptimizeBootImage();
Mingyao Yang6ea1a0e2016-01-29 12:12:49 -0800694 }
695
Sebastien Hertzf3928792014-11-17 19:00:37 +0100696 if (RequiresDeoptimization()) {
697 runtime->GetInstrumentation()->EnableDeoptimization();
698 }
Sebastien Hertz42cd43f2014-05-13 14:15:41 +0200699 instrumentation_events_ = 0;
David Srbecky28f6cff2018-10-16 15:07:28 +0100700 Runtime::DoAndMaybeSwitchInterpreter([=](){ gDebuggerActive = true; });
Alex Light21611932017-09-26 13:07:39 -0700701 Runtime::Current()->GetRuntimeCallbacks()->AddMethodInspectionCallback(&gDebugActiveCallback);
Ian Rogers62d6c772013-02-27 08:32:07 -0800702 LOG(INFO) << "Debugger is active";
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700703}
704
705void Dbg::Disconnected() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700706 CHECK(gDebuggerConnected);
707
Elliott Hughesc0f09332012-03-26 13:27:06 -0700708 LOG(INFO) << "Debugger is no longer active";
Elliott Hughes234ab152011-10-26 14:02:26 -0700709
Hiroshi Yamauchi98810e32016-05-24 14:55:40 -0700710 // Suspend all threads and exclusively acquire the mutator lock. Remove the debugger as a listener
Ian Rogers62d6c772013-02-27 08:32:07 -0800711 // and clear the object registry.
712 Runtime* runtime = Runtime::Current();
Ian Rogers62d6c772013-02-27 08:32:07 -0800713 Thread* self = Thread::Current();
Mathieu Chartier4f55e222015-09-04 13:26:21 -0700714 {
Mathieu Chartieraa516822015-10-02 15:53:37 -0700715 // Required for DisableDeoptimization.
716 gc::ScopedGCCriticalSection gcs(self,
717 gc::kGcCauseInstrumentation,
718 gc::kCollectorTypeInstrumentation);
Mathieu Chartier4f55e222015-09-04 13:26:21 -0700719 ScopedSuspendAll ssa(__FUNCTION__);
Mathieu Chartier4f55e222015-09-04 13:26:21 -0700720 // Debugger may not be active at this point.
721 if (IsDebuggerActive()) {
722 {
723 // Since we're going to disable deoptimization, we clear the deoptimization requests queue.
724 // This prevents us from having any pending deoptimization request when the debugger attaches
725 // to us again while no event has been requested yet.
Mathieu Chartiera6b1ead2015-10-06 10:32:38 -0700726 MutexLock mu(self, *Locks::deoptimization_lock_);
Mathieu Chartier4f55e222015-09-04 13:26:21 -0700727 deoptimization_requests_.clear();
728 full_deoptimization_event_count_ = 0U;
729 }
730 if (instrumentation_events_ != 0) {
731 runtime->GetInstrumentation()->RemoveListener(&gDebugInstrumentationListener,
732 instrumentation_events_);
733 instrumentation_events_ = 0;
734 }
735 if (RequiresDeoptimization()) {
736 runtime->GetInstrumentation()->DisableDeoptimization(kDbgInstrumentationKey);
737 }
David Srbecky28f6cff2018-10-16 15:07:28 +0100738 Runtime::DoAndMaybeSwitchInterpreter([=](){ gDebuggerActive = false; });
Alex Light21611932017-09-26 13:07:39 -0700739 Runtime::Current()->GetRuntimeCallbacks()->RemoveMethodInspectionCallback(
740 &gDebugActiveCallback);
Sebastien Hertzaaea7342014-02-25 15:10:04 +0100741 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100742 }
Sebastien Hertz55f65342015-01-13 22:48:34 +0100743
744 {
745 ScopedObjectAccess soa(self);
746 gRegistry->Clear();
747 }
748
749 gDebuggerConnected = false;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700750}
751
Sebastien Hertzb3b173b2015-02-06 09:16:32 +0100752void Dbg::ConfigureJdwp(const JDWP::JdwpOptions& jdwp_options) {
753 CHECK_NE(jdwp_options.transport, JDWP::kJdwpTransportUnknown);
754 gJdwpOptions = jdwp_options;
755 gJdwpConfigured = true;
Alex Light40320712017-12-14 11:52:04 -0800756 Runtime::Current()->GetRuntimeCallbacks()->AddDebuggerControlCallback(&gDebuggerControlCallback);
Sebastien Hertzb3b173b2015-02-06 09:16:32 +0100757}
758
Elliott Hughesc0f09332012-03-26 13:27:06 -0700759bool Dbg::IsJdwpConfigured() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700760 return gJdwpConfigured;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700761}
762
763int64_t Dbg::LastDebuggerActivity() {
Elliott Hughesca951522011-12-05 12:01:32 -0800764 return gJdwpState->LastDebuggerActivity();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700765}
766
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700767void Dbg::UndoDebuggerSuspensions() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700768 Runtime::Current()->GetThreadList()->UndoDebuggerSuspensions();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700769}
770
Elliott Hughes88d63092013-01-09 09:55:54 -0800771std::string Dbg::GetClassName(JDWP::RefTypeId class_id) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700772 JDWP::JdwpError error;
Vladimir Marko83114892019-04-11 13:05:50 +0100773 ObjPtr<mirror::Object> o = gRegistry->Get<mirror::Object>(class_id, &error);
Ian Rogersc0542af2014-09-03 16:16:56 -0700774 if (o == nullptr) {
775 if (error == JDWP::ERR_NONE) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700776 return "null";
Ian Rogersc0542af2014-09-03 16:16:56 -0700777 } else {
778 return StringPrintf("invalid object %p", reinterpret_cast<void*>(class_id));
779 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800780 }
781 if (!o->IsClass()) {
Vladimir Marko4617d582019-03-28 13:48:31 +0000782 return StringPrintf("non-class %p", o.Ptr()); // This is only used for debugging output anyway.
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800783 }
Sebastien Hertz6995c602014-09-09 12:10:13 +0200784 return GetClassName(o->AsClass());
785}
786
Vladimir Marko4617d582019-03-28 13:48:31 +0000787std::string Dbg::GetClassName(ObjPtr<mirror::Class> klass) {
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +0200788 if (klass == nullptr) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700789 return "null";
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +0200790 }
Ian Rogers1ff3c982014-08-12 02:30:58 -0700791 std::string temp;
Sebastien Hertz6995c602014-09-09 12:10:13 +0200792 return DescriptorToName(klass->GetDescriptor(&temp));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700793}
794
Ian Rogersc0542af2014-09-03 16:16:56 -0700795JDWP::JdwpError Dbg::GetClassObject(JDWP::RefTypeId id, JDWP::ObjectId* class_object_id) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800796 JDWP::JdwpError status;
Vladimir Marko4617d582019-03-28 13:48:31 +0000797 ObjPtr<mirror::Class> c = DecodeClass(id, &status);
Ian Rogersc0542af2014-09-03 16:16:56 -0700798 if (c == nullptr) {
799 *class_object_id = 0;
Elliott Hughes436e3722012-02-17 20:01:47 -0800800 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800801 }
Ian Rogersc0542af2014-09-03 16:16:56 -0700802 *class_object_id = gRegistry->Add(c);
Elliott Hughes436e3722012-02-17 20:01:47 -0800803 return JDWP::ERR_NONE;
Elliott Hughes86964332012-02-15 19:37:42 -0800804}
805
Ian Rogersc0542af2014-09-03 16:16:56 -0700806JDWP::JdwpError Dbg::GetSuperclass(JDWP::RefTypeId id, JDWP::RefTypeId* superclass_id) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800807 JDWP::JdwpError status;
Vladimir Marko4617d582019-03-28 13:48:31 +0000808 ObjPtr<mirror::Class> c = DecodeClass(id, &status);
Ian Rogersc0542af2014-09-03 16:16:56 -0700809 if (c == nullptr) {
810 *superclass_id = 0;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800811 return status;
812 }
813 if (c->IsInterface()) {
814 // http://code.google.com/p/android/issues/detail?id=20856
Ian Rogersc0542af2014-09-03 16:16:56 -0700815 *superclass_id = 0;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800816 } else {
Ian Rogersc0542af2014-09-03 16:16:56 -0700817 *superclass_id = gRegistry->Add(c->GetSuperClass());
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800818 }
819 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700820}
821
Elliott Hughes436e3722012-02-17 20:01:47 -0800822JDWP::JdwpError Dbg::GetClassLoader(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700823 JDWP::JdwpError error;
Vladimir Marko4617d582019-03-28 13:48:31 +0000824 ObjPtr<mirror::Class> c = DecodeClass(id, &error);
Andreas Gampe7929a482015-12-30 19:33:49 -0800825 if (c == nullptr) {
826 return error;
Elliott Hughes436e3722012-02-17 20:01:47 -0800827 }
Andreas Gampe7929a482015-12-30 19:33:49 -0800828 expandBufAddObjectId(pReply, gRegistry->Add(c->GetClassLoader()));
Elliott Hughes436e3722012-02-17 20:01:47 -0800829 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700830}
831
Elliott Hughes436e3722012-02-17 20:01:47 -0800832JDWP::JdwpError Dbg::GetModifiers(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700833 JDWP::JdwpError error;
Vladimir Marko4617d582019-03-28 13:48:31 +0000834 ObjPtr<mirror::Class> c = DecodeClass(id, &error);
Ian Rogersc0542af2014-09-03 16:16:56 -0700835 if (c == nullptr) {
836 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800837 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800838
839 uint32_t access_flags = c->GetAccessFlags() & kAccJavaFlagsMask;
840
Yevgeny Roubande34eea2014-02-15 01:06:03 +0700841 // Set ACC_SUPER. Dex files don't contain this flag but only classes are supposed to have it set,
842 // not interfaces.
Elliott Hughes436e3722012-02-17 20:01:47 -0800843 // Class.getModifiers doesn't return it, but JDWP does, so we set it here.
Yevgeny Roubande34eea2014-02-15 01:06:03 +0700844 if ((access_flags & kAccInterface) == 0) {
845 access_flags |= kAccSuper;
846 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800847
848 expandBufAdd4BE(pReply, access_flags);
849
850 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700851}
852
Ian Rogersc0542af2014-09-03 16:16:56 -0700853JDWP::JdwpError Dbg::GetMonitorInfo(JDWP::ObjectId object_id, JDWP::ExpandBuf* reply) {
854 JDWP::JdwpError error;
Vladimir Marko67f0e9c2019-03-29 14:00:12 +0000855 Thread* self = Thread::Current();
856 StackHandleScope<1u> hs(self);
Vladimir Marko83114892019-04-11 13:05:50 +0100857 Handle<mirror::Object> o = hs.NewHandle(gRegistry->Get<mirror::Object>(object_id, &error));
Ian Rogersc0542af2014-09-03 16:16:56 -0700858 if (o == nullptr) {
Elliott Hughesf327e072013-01-09 16:01:26 -0800859 return JDWP::ERR_INVALID_OBJECT;
860 }
861
862 // Ensure all threads are suspended while we read objects' lock words.
Sebastien Hertz54263242014-03-19 18:16:50 +0100863 CHECK_EQ(self->GetState(), kRunnable);
Elliott Hughesf327e072013-01-09 16:01:26 -0800864
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700865 MonitorInfo monitor_info;
866 {
867 ScopedThreadSuspension sts(self, kSuspended);
Mathieu Chartier4f55e222015-09-04 13:26:21 -0700868 ScopedSuspendAll ssa(__FUNCTION__);
Vladimir Marko67f0e9c2019-03-29 14:00:12 +0000869 monitor_info = MonitorInfo(o.Get());
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700870 }
Ian Rogersc0542af2014-09-03 16:16:56 -0700871 if (monitor_info.owner_ != nullptr) {
Nicolas Geoffraycafa0812017-02-15 18:27:34 +0000872 expandBufAddObjectId(reply, gRegistry->Add(monitor_info.owner_->GetPeerFromOtherThread()));
Elliott Hughesf327e072013-01-09 16:01:26 -0800873 } else {
Ian Rogersc0542af2014-09-03 16:16:56 -0700874 expandBufAddObjectId(reply, gRegistry->Add(nullptr));
Elliott Hughesf327e072013-01-09 16:01:26 -0800875 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700876 expandBufAdd4BE(reply, monitor_info.entry_count_);
877 expandBufAdd4BE(reply, monitor_info.waiters_.size());
878 for (size_t i = 0; i < monitor_info.waiters_.size(); ++i) {
Nicolas Geoffraycafa0812017-02-15 18:27:34 +0000879 expandBufAddObjectId(reply, gRegistry->Add(monitor_info.waiters_[i]->GetPeerFromOtherThread()));
Elliott Hughesf327e072013-01-09 16:01:26 -0800880 }
881 return JDWP::ERR_NONE;
882}
883
Elliott Hughes734b8c62013-01-11 15:32:45 -0800884JDWP::JdwpError Dbg::GetOwnedMonitors(JDWP::ObjectId thread_id,
Ian Rogersc0542af2014-09-03 16:16:56 -0700885 std::vector<JDWP::ObjectId>* monitors,
886 std::vector<uint32_t>* stack_depths) {
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800887 struct OwnedMonitorVisitor : public StackVisitor {
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700888 OwnedMonitorVisitor(Thread* thread, Context* context,
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -0700889 std::vector<JDWP::ObjectId>* monitor_vector,
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700890 std::vector<uint32_t>* stack_depth_vector)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700891 REQUIRES_SHARED(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +0100892 : StackVisitor(thread, context, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
893 current_stack_depth(0),
894 monitors(monitor_vector),
895 stack_depths(stack_depth_vector) {}
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800896
897 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
898 // annotalysis.
Andreas Gampefa6a1b02018-09-07 08:11:55 -0700899 bool VisitFrame() override NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800900 if (!GetMethod()->IsRuntimeMethod()) {
901 Monitor::VisitLocks(this, AppendOwnedMonitors, this);
Elliott Hughes734b8c62013-01-11 15:32:45 -0800902 ++current_stack_depth;
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800903 }
904 return true;
905 }
906
Vladimir Markof52d92f2019-03-29 12:33:02 +0000907 static void AppendOwnedMonitors(ObjPtr<mirror::Object> owned_monitor, void* arg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700908 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers7a22fa62013-01-23 12:16:16 -0800909 OwnedMonitorVisitor* visitor = reinterpret_cast<OwnedMonitorVisitor*>(arg);
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -0700910 visitor->monitors->push_back(gRegistry->Add(owned_monitor));
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700911 visitor->stack_depths->push_back(visitor->current_stack_depth);
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800912 }
913
Elliott Hughes734b8c62013-01-11 15:32:45 -0800914 size_t current_stack_depth;
Ian Rogersc0542af2014-09-03 16:16:56 -0700915 std::vector<JDWP::ObjectId>* const monitors;
916 std::vector<uint32_t>* const stack_depths;
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800917 };
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800918
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700919 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz69206392015-04-07 15:54:25 +0200920 JDWP::JdwpError error;
921 Thread* thread = DecodeThread(soa, thread_id, &error);
922 if (thread == nullptr) {
923 return error;
924 }
925 if (!IsSuspendedForDebugger(soa, thread)) {
926 return JDWP::ERR_THREAD_NOT_SUSPENDED;
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700927 }
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -0700928 std::unique_ptr<Context> context(Context::Create());
Ian Rogersc0542af2014-09-03 16:16:56 -0700929 OwnedMonitorVisitor visitor(thread, context.get(), monitors, stack_depths);
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -0700930 visitor.WalkStack();
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800931 return JDWP::ERR_NONE;
932}
933
Sebastien Hertz52d131d2014-03-13 16:17:40 +0100934JDWP::JdwpError Dbg::GetContendedMonitor(JDWP::ObjectId thread_id,
Ian Rogersc0542af2014-09-03 16:16:56 -0700935 JDWP::ObjectId* contended_monitor) {
Elliott Hughesf9501702013-01-11 11:22:27 -0800936 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -0700937 *contended_monitor = 0;
Sebastien Hertz69206392015-04-07 15:54:25 +0200938 JDWP::JdwpError error;
939 Thread* thread = DecodeThread(soa, thread_id, &error);
940 if (thread == nullptr) {
941 return error;
Elliott Hughesf9501702013-01-11 11:22:27 -0800942 }
Sebastien Hertz69206392015-04-07 15:54:25 +0200943 if (!IsSuspendedForDebugger(soa, thread)) {
944 return JDWP::ERR_THREAD_NOT_SUSPENDED;
945 }
Vladimir Markof52d92f2019-03-29 12:33:02 +0000946 ObjPtr<mirror::Object> contended_monitor_obj = Monitor::GetContendedMonitor(thread);
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700947 // Add() requires the thread_list_lock_ not held to avoid the lock
948 // level violation.
Ian Rogersc0542af2014-09-03 16:16:56 -0700949 *contended_monitor = gRegistry->Add(contended_monitor_obj);
Elliott Hughesf9501702013-01-11 11:22:27 -0800950 return JDWP::ERR_NONE;
951}
952
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800953JDWP::JdwpError Dbg::GetInstanceCounts(const std::vector<JDWP::RefTypeId>& class_ids,
Ian Rogersc0542af2014-09-03 16:16:56 -0700954 std::vector<uint64_t>* counts) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800955 gc::Heap* heap = Runtime::Current()->GetHeap();
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700956 heap->CollectGarbage(/* clear_soft_references= */ false, gc::GcCause::kGcCauseDebugger);
Mathieu Chartiere8a3c572016-10-11 16:52:17 -0700957 VariableSizedHandleScope hs(Thread::Current());
Mathieu Chartier9d156d52016-10-06 17:44:26 -0700958 std::vector<Handle<mirror::Class>> classes;
Ian Rogersc0542af2014-09-03 16:16:56 -0700959 counts->clear();
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800960 for (size_t i = 0; i < class_ids.size(); ++i) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700961 JDWP::JdwpError error;
Mathieu Chartier9d156d52016-10-06 17:44:26 -0700962 ObjPtr<mirror::Class> c = DecodeClass(class_ids[i], &error);
Ian Rogersc0542af2014-09-03 16:16:56 -0700963 if (c == nullptr) {
964 return error;
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800965 }
Mathieu Chartier9d156d52016-10-06 17:44:26 -0700966 classes.push_back(hs.NewHandle(c));
Ian Rogersc0542af2014-09-03 16:16:56 -0700967 counts->push_back(0);
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800968 }
Ian Rogersc0542af2014-09-03 16:16:56 -0700969 heap->CountInstances(classes, false, &(*counts)[0]);
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800970 return JDWP::ERR_NONE;
971}
972
Ian Rogersc0542af2014-09-03 16:16:56 -0700973JDWP::JdwpError Dbg::GetInstances(JDWP::RefTypeId class_id, int32_t max_count,
974 std::vector<JDWP::ObjectId>* instances) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800975 gc::Heap* heap = Runtime::Current()->GetHeap();
976 // We only want reachable instances, so do a GC.
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700977 heap->CollectGarbage(/* clear_soft_references= */ false, gc::GcCause::kGcCauseDebugger);
Ian Rogersc0542af2014-09-03 16:16:56 -0700978 JDWP::JdwpError error;
Mathieu Chartier9d156d52016-10-06 17:44:26 -0700979 ObjPtr<mirror::Class> c = DecodeClass(class_id, &error);
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800980 if (c == nullptr) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700981 return error;
Elliott Hughes3b78c942013-01-15 17:35:41 -0800982 }
Mathieu Chartier2d855952016-10-12 19:37:59 -0700983 VariableSizedHandleScope hs(Thread::Current());
984 std::vector<Handle<mirror::Object>> raw_instances;
Richard Uhler660be6f2017-11-22 16:12:29 +0000985 Runtime::Current()->GetHeap()->GetInstances(hs,
986 hs.NewHandle(c),
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700987 /* use_is_assignable_from= */ false,
Richard Uhler660be6f2017-11-22 16:12:29 +0000988 max_count,
989 raw_instances);
Elliott Hughes3b78c942013-01-15 17:35:41 -0800990 for (size_t i = 0; i < raw_instances.size(); ++i) {
Mathieu Chartier2d855952016-10-12 19:37:59 -0700991 instances->push_back(gRegistry->Add(raw_instances[i].Get()));
Elliott Hughes3b78c942013-01-15 17:35:41 -0800992 }
993 return JDWP::ERR_NONE;
994}
995
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800996JDWP::JdwpError Dbg::GetReferringObjects(JDWP::ObjectId object_id, int32_t max_count,
Ian Rogersc0542af2014-09-03 16:16:56 -0700997 std::vector<JDWP::ObjectId>* referring_objects) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800998 gc::Heap* heap = Runtime::Current()->GetHeap();
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700999 heap->CollectGarbage(/* clear_soft_references= */ false, gc::GcCause::kGcCauseDebugger);
Ian Rogersc0542af2014-09-03 16:16:56 -07001000 JDWP::JdwpError error;
Vladimir Marko83114892019-04-11 13:05:50 +01001001 ObjPtr<mirror::Object> o = gRegistry->Get<mirror::Object>(object_id, &error);
Ian Rogersc0542af2014-09-03 16:16:56 -07001002 if (o == nullptr) {
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001003 return JDWP::ERR_INVALID_OBJECT;
1004 }
Mathieu Chartieraea9bfb2016-10-12 19:19:56 -07001005 VariableSizedHandleScope hs(Thread::Current());
1006 std::vector<Handle<mirror::Object>> raw_instances;
1007 heap->GetReferringObjects(hs, hs.NewHandle(o), max_count, raw_instances);
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001008 for (size_t i = 0; i < raw_instances.size(); ++i) {
Mathieu Chartieraea9bfb2016-10-12 19:19:56 -07001009 referring_objects->push_back(gRegistry->Add(raw_instances[i].Get()));
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001010 }
1011 return JDWP::ERR_NONE;
1012}
1013
Ian Rogersc0542af2014-09-03 16:16:56 -07001014JDWP::JdwpError Dbg::DisableCollection(JDWP::ObjectId object_id) {
1015 JDWP::JdwpError error;
Vladimir Marko83114892019-04-11 13:05:50 +01001016 ObjPtr<mirror::Object> o = gRegistry->Get<mirror::Object>(object_id, &error);
Ian Rogersc0542af2014-09-03 16:16:56 -07001017 if (o == nullptr) {
Sebastien Hertze96060a2013-12-11 12:06:28 +01001018 return JDWP::ERR_INVALID_OBJECT;
1019 }
Elliott Hughes64f574f2013-02-20 14:57:12 -08001020 gRegistry->DisableCollection(object_id);
1021 return JDWP::ERR_NONE;
1022}
1023
Ian Rogersc0542af2014-09-03 16:16:56 -07001024JDWP::JdwpError Dbg::EnableCollection(JDWP::ObjectId object_id) {
1025 JDWP::JdwpError error;
Vladimir Marko83114892019-04-11 13:05:50 +01001026 ObjPtr<mirror::Object> o = gRegistry->Get<mirror::Object>(object_id, &error);
Sebastien Hertze96060a2013-12-11 12:06:28 +01001027 // Unlike DisableCollection, JDWP specs do not state an invalid object causes an error. The RI
1028 // also ignores these cases and never return an error. However it's not obvious why this command
1029 // should behave differently from DisableCollection and IsCollected commands. So let's be more
1030 // strict and return an error if this happens.
Ian Rogersc0542af2014-09-03 16:16:56 -07001031 if (o == nullptr) {
Sebastien Hertze96060a2013-12-11 12:06:28 +01001032 return JDWP::ERR_INVALID_OBJECT;
1033 }
Elliott Hughes64f574f2013-02-20 14:57:12 -08001034 gRegistry->EnableCollection(object_id);
1035 return JDWP::ERR_NONE;
1036}
1037
Ian Rogersc0542af2014-09-03 16:16:56 -07001038JDWP::JdwpError Dbg::IsCollected(JDWP::ObjectId object_id, bool* is_collected) {
1039 *is_collected = true;
Sebastien Hertz65637eb2014-01-10 17:40:02 +01001040 if (object_id == 0) {
1041 // Null object id is invalid.
Sebastien Hertze96060a2013-12-11 12:06:28 +01001042 return JDWP::ERR_INVALID_OBJECT;
1043 }
Sebastien Hertz65637eb2014-01-10 17:40:02 +01001044 // JDWP specs state an INVALID_OBJECT error is returned if the object ID is not valid. However
1045 // the RI seems to ignore this and assume object has been collected.
Ian Rogersc0542af2014-09-03 16:16:56 -07001046 JDWP::JdwpError error;
Vladimir Marko83114892019-04-11 13:05:50 +01001047 ObjPtr<mirror::Object> o = gRegistry->Get<mirror::Object>(object_id, &error);
Ian Rogersc0542af2014-09-03 16:16:56 -07001048 if (o != nullptr) {
1049 *is_collected = gRegistry->IsCollected(object_id);
Sebastien Hertz65637eb2014-01-10 17:40:02 +01001050 }
Elliott Hughes64f574f2013-02-20 14:57:12 -08001051 return JDWP::ERR_NONE;
1052}
1053
Ian Rogersc0542af2014-09-03 16:16:56 -07001054void Dbg::DisposeObject(JDWP::ObjectId object_id, uint32_t reference_count) {
Elliott Hughes64f574f2013-02-20 14:57:12 -08001055 gRegistry->DisposeObject(object_id, reference_count);
1056}
1057
Mathieu Chartier3398c782016-09-30 10:27:43 -07001058JDWP::JdwpTypeTag Dbg::GetTypeTag(ObjPtr<mirror::Class> klass) {
Sebastien Hertz4d8fd492014-03-28 16:29:41 +01001059 DCHECK(klass != nullptr);
1060 if (klass->IsArrayClass()) {
1061 return JDWP::TT_ARRAY;
1062 } else if (klass->IsInterface()) {
1063 return JDWP::TT_INTERFACE;
1064 } else {
1065 return JDWP::TT_CLASS;
1066 }
1067}
1068
Elliott Hughes88d63092013-01-09 09:55:54 -08001069JDWP::JdwpError Dbg::GetReflectedType(JDWP::RefTypeId class_id, JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001070 JDWP::JdwpError error;
Vladimir Marko4617d582019-03-28 13:48:31 +00001071 ObjPtr<mirror::Class> c = DecodeClass(class_id, &error);
Ian Rogersc0542af2014-09-03 16:16:56 -07001072 if (c == nullptr) {
1073 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001074 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001075
Sebastien Hertz4d8fd492014-03-28 16:29:41 +01001076 JDWP::JdwpTypeTag type_tag = GetTypeTag(c);
1077 expandBufAdd1(pReply, type_tag);
Elliott Hughes88d63092013-01-09 09:55:54 -08001078 expandBufAddRefTypeId(pReply, class_id);
Elliott Hughes436e3722012-02-17 20:01:47 -08001079 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001080}
1081
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001082// Get the complete list of reference classes (i.e. all classes except
1083// the primitive types).
1084// Returns a newly-allocated buffer full of RefTypeId values.
1085class ClassListCreator : public ClassVisitor {
1086 public:
1087 explicit ClassListCreator(std::vector<JDWP::RefTypeId>* classes) : classes_(classes) {}
1088
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01001089 bool operator()(ObjPtr<mirror::Class> c) override REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001090 if (!c->IsPrimitive()) {
1091 classes_->push_back(Dbg::GetObjectRegistry()->AddRefType(c));
1092 }
1093 return true;
1094 }
1095
1096 private:
1097 std::vector<JDWP::RefTypeId>* const classes_;
1098};
1099
Ian Rogersc0542af2014-09-03 16:16:56 -07001100void Dbg::GetClassList(std::vector<JDWP::RefTypeId>* classes) {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001101 ClassListCreator clc(classes);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001102 Runtime::Current()->GetClassLinker()->VisitClassesWithoutClassesLock(&clc);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001103}
1104
Ian Rogers1ff3c982014-08-12 02:30:58 -07001105JDWP::JdwpError Dbg::GetClassInfo(JDWP::RefTypeId class_id, JDWP::JdwpTypeTag* pTypeTag,
1106 uint32_t* pStatus, std::string* pDescriptor) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001107 JDWP::JdwpError error;
Vladimir Marko4617d582019-03-28 13:48:31 +00001108 ObjPtr<mirror::Class> c = DecodeClass(class_id, &error);
Ian Rogersc0542af2014-09-03 16:16:56 -07001109 if (c == nullptr) {
1110 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001111 }
1112
Elliott Hughesa2155262011-11-16 16:26:58 -08001113 if (c->IsArrayClass()) {
1114 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
1115 *pTypeTag = JDWP::TT_ARRAY;
1116 } else {
1117 if (c->IsErroneous()) {
1118 *pStatus = JDWP::CS_ERROR;
1119 } else {
1120 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED | JDWP::CS_INITIALIZED;
1121 }
1122 *pTypeTag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
1123 }
1124
Ian Rogersc0542af2014-09-03 16:16:56 -07001125 if (pDescriptor != nullptr) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07001126 std::string temp;
1127 *pDescriptor = c->GetDescriptor(&temp);
Elliott Hughesa2155262011-11-16 16:26:58 -08001128 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001129 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001130}
1131
Ian Rogersc0542af2014-09-03 16:16:56 -07001132void Dbg::FindLoadedClassBySignature(const char* descriptor, std::vector<JDWP::RefTypeId>* ids) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001133 std::vector<ObjPtr<mirror::Class>> classes;
Igor Murashkinb1d8c312015-08-04 11:18:43 -07001134 Runtime::Current()->GetClassLinker()->LookupClasses(descriptor, classes);
Ian Rogersc0542af2014-09-03 16:16:56 -07001135 ids->clear();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001136 for (ObjPtr<mirror::Class> c : classes) {
1137 ids->push_back(gRegistry->Add(c));
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001138 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001139}
1140
Ian Rogersc0542af2014-09-03 16:16:56 -07001141JDWP::JdwpError Dbg::GetReferenceType(JDWP::ObjectId object_id, JDWP::ExpandBuf* pReply) {
1142 JDWP::JdwpError error;
Vladimir Marko83114892019-04-11 13:05:50 +01001143 ObjPtr<mirror::Object> o = gRegistry->Get<mirror::Object>(object_id, &error);
Ian Rogersc0542af2014-09-03 16:16:56 -07001144 if (o == nullptr) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001145 return JDWP::ERR_INVALID_OBJECT;
Elliott Hughes499c5132011-11-17 14:55:11 -08001146 }
Elliott Hughes2435a572012-02-17 16:07:41 -08001147
Sebastien Hertz4d8fd492014-03-28 16:29:41 +01001148 JDWP::JdwpTypeTag type_tag = GetTypeTag(o->GetClass());
Elliott Hughes64f574f2013-02-20 14:57:12 -08001149 JDWP::RefTypeId type_id = gRegistry->AddRefType(o->GetClass());
Elliott Hughes2435a572012-02-17 16:07:41 -08001150
1151 expandBufAdd1(pReply, type_tag);
1152 expandBufAddRefTypeId(pReply, type_id);
1153
1154 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001155}
1156
Ian Rogersfc0e94b2013-09-23 23:51:32 -07001157JDWP::JdwpError Dbg::GetSignature(JDWP::RefTypeId class_id, std::string* signature) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001158 JDWP::JdwpError error;
Vladimir Marko4617d582019-03-28 13:48:31 +00001159 ObjPtr<mirror::Class> c = DecodeClass(class_id, &error);
Ian Rogersc0542af2014-09-03 16:16:56 -07001160 if (c == nullptr) {
1161 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001162 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07001163 std::string temp;
1164 *signature = c->GetDescriptor(&temp);
Elliott Hughes1fe7afb2012-02-13 17:23:03 -08001165 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001166}
1167
Orion Hodson77d8a1c2017-04-24 14:53:19 +01001168JDWP::JdwpError Dbg::GetSourceDebugExtension(JDWP::RefTypeId class_id,
1169 std::string* extension_data) {
1170 JDWP::JdwpError error;
Vladimir Marko4617d582019-03-28 13:48:31 +00001171 ObjPtr<mirror::Class> c = DecodeClass(class_id, &error);
Orion Hodson77d8a1c2017-04-24 14:53:19 +01001172 if (c == nullptr) {
1173 return error;
1174 }
1175 StackHandleScope<1> hs(Thread::Current());
1176 Handle<mirror::Class> klass(hs.NewHandle(c));
1177 const char* data = annotations::GetSourceDebugExtension(klass);
1178 if (data == nullptr) {
1179 return JDWP::ERR_ABSENT_INFORMATION;
1180 }
1181 *extension_data = data;
1182 return JDWP::ERR_NONE;
1183}
1184
Ian Rogersc0542af2014-09-03 16:16:56 -07001185JDWP::JdwpError Dbg::GetSourceFile(JDWP::RefTypeId class_id, std::string* result) {
1186 JDWP::JdwpError error;
Vladimir Marko4617d582019-03-28 13:48:31 +00001187 ObjPtr<mirror::Class> c = DecodeClass(class_id, &error);
Sebastien Hertz4206eb52014-06-05 10:15:45 +02001188 if (c == nullptr) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001189 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001190 }
Sebastien Hertz4206eb52014-06-05 10:15:45 +02001191 const char* source_file = c->GetSourceFile();
1192 if (source_file == nullptr) {
Sebastien Hertzb7054ba2014-03-13 11:52:31 +01001193 return JDWP::ERR_ABSENT_INFORMATION;
1194 }
Ian Rogersc0542af2014-09-03 16:16:56 -07001195 *result = source_file;
Elliott Hughes436e3722012-02-17 20:01:47 -08001196 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001197}
1198
Ian Rogersc0542af2014-09-03 16:16:56 -07001199JDWP::JdwpError Dbg::GetObjectTag(JDWP::ObjectId object_id, uint8_t* tag) {
Ian Rogers98379392014-02-24 16:53:16 -08001200 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07001201 JDWP::JdwpError error;
Vladimir Marko83114892019-04-11 13:05:50 +01001202 ObjPtr<mirror::Object> o = gRegistry->Get<mirror::Object>(object_id, &error);
Ian Rogersc0542af2014-09-03 16:16:56 -07001203 if (error != JDWP::ERR_NONE) {
1204 *tag = JDWP::JT_VOID;
1205 return error;
Elliott Hughes546b9862012-06-20 16:06:13 -07001206 }
Ian Rogersc0542af2014-09-03 16:16:56 -07001207 *tag = TagFromObject(soa, o);
Elliott Hughes546b9862012-06-20 16:06:13 -07001208 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001209}
1210
Elliott Hughesaed4be92011-12-02 16:16:23 -08001211size_t Dbg::GetTagWidth(JDWP::JdwpTag tag) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001212 switch (tag) {
1213 case JDWP::JT_VOID:
1214 return 0;
1215 case JDWP::JT_BYTE:
1216 case JDWP::JT_BOOLEAN:
1217 return 1;
1218 case JDWP::JT_CHAR:
1219 case JDWP::JT_SHORT:
1220 return 2;
1221 case JDWP::JT_FLOAT:
1222 case JDWP::JT_INT:
1223 return 4;
1224 case JDWP::JT_ARRAY:
1225 case JDWP::JT_OBJECT:
1226 case JDWP::JT_STRING:
1227 case JDWP::JT_THREAD:
1228 case JDWP::JT_THREAD_GROUP:
1229 case JDWP::JT_CLASS_LOADER:
1230 case JDWP::JT_CLASS_OBJECT:
1231 return sizeof(JDWP::ObjectId);
1232 case JDWP::JT_DOUBLE:
1233 case JDWP::JT_LONG:
1234 return 8;
1235 default:
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001236 LOG(FATAL) << "Unknown tag " << tag;
Elliott Hughesc1896c92018-11-29 11:33:18 -08001237 UNREACHABLE();
Elliott Hughesdbb40792011-11-18 17:05:22 -08001238 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001239}
1240
Ian Rogersc0542af2014-09-03 16:16:56 -07001241JDWP::JdwpError Dbg::GetArrayLength(JDWP::ObjectId array_id, int32_t* length) {
1242 JDWP::JdwpError error;
Vladimir Marko4617d582019-03-28 13:48:31 +00001243 ObjPtr<mirror::Array> a = DecodeNonNullArray(array_id, &error);
Ian Rogersc0542af2014-09-03 16:16:56 -07001244 if (a == nullptr) {
1245 return error;
Elliott Hughes24437992011-11-30 14:49:33 -08001246 }
Ian Rogersc0542af2014-09-03 16:16:56 -07001247 *length = a->GetLength();
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001248 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001249}
1250
Vladimir Marko4617d582019-03-28 13:48:31 +00001251JDWP::JdwpError Dbg::OutputArray(JDWP::ObjectId array_id,
1252 int offset,
1253 int count,
1254 JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001255 JDWP::JdwpError error;
Vladimir Marko4617d582019-03-28 13:48:31 +00001256 ObjPtr<mirror::Array> a = DecodeNonNullArray(array_id, &error);
Ian Rogers98379392014-02-24 16:53:16 -08001257 if (a == nullptr) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001258 return error;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001259 }
Elliott Hughes24437992011-11-30 14:49:33 -08001260
1261 if (offset < 0 || count < 0 || offset > a->GetLength() || a->GetLength() - offset < count) {
1262 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001263 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughes24437992011-11-30 14:49:33 -08001264 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07001265 JDWP::JdwpTag element_tag = BasicTagFromClass(a->GetClass()->GetComponentType());
1266 expandBufAdd1(pReply, element_tag);
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001267 expandBufAdd4BE(pReply, count);
1268
Ian Rogers1ff3c982014-08-12 02:30:58 -07001269 if (IsPrimitiveTag(element_tag)) {
1270 size_t width = GetTagWidth(element_tag);
Elliott Hughes24437992011-11-30 14:49:33 -08001271 uint8_t* dst = expandBufAddSpace(pReply, count * width);
1272 if (width == 8) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001273 const uint64_t* src8 = reinterpret_cast<uint64_t*>(a->GetRawData(sizeof(uint64_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001274 for (int i = 0; i < count; ++i) JDWP::Write8BE(&dst, src8[offset + i]);
1275 } else if (width == 4) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001276 const uint32_t* src4 = reinterpret_cast<uint32_t*>(a->GetRawData(sizeof(uint32_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001277 for (int i = 0; i < count; ++i) JDWP::Write4BE(&dst, src4[offset + i]);
1278 } else if (width == 2) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001279 const uint16_t* src2 = reinterpret_cast<uint16_t*>(a->GetRawData(sizeof(uint16_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001280 for (int i = 0; i < count; ++i) JDWP::Write2BE(&dst, src2[offset + i]);
1281 } else {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001282 const uint8_t* src = reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint8_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001283 memcpy(dst, &src[offset * width], count * width);
1284 }
1285 } else {
Ian Rogers98379392014-02-24 16:53:16 -08001286 ScopedObjectAccessUnchecked soa(Thread::Current());
Vladimir Marko4617d582019-03-28 13:48:31 +00001287 ObjPtr<mirror::ObjectArray<mirror::Object>> oa = a->AsObjectArray<mirror::Object>();
Elliott Hughes24437992011-11-30 14:49:33 -08001288 for (int i = 0; i < count; ++i) {
Vladimir Marko423bebb2019-03-26 15:17:21 +00001289 ObjPtr<mirror::Object> element = oa->Get(offset + i);
Ian Rogers98379392014-02-24 16:53:16 -08001290 JDWP::JdwpTag specific_tag = (element != nullptr) ? TagFromObject(soa, element)
Ian Rogers1ff3c982014-08-12 02:30:58 -07001291 : element_tag;
Elliott Hughes24437992011-11-30 14:49:33 -08001292 expandBufAdd1(pReply, specific_tag);
1293 expandBufAddObjectId(pReply, gRegistry->Add(element));
1294 }
1295 }
1296
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001297 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001298}
1299
Ian Rogersef7d42f2014-01-06 12:55:46 -08001300template <typename T>
Vladimir Marko4617d582019-03-28 13:48:31 +00001301static void CopyArrayData(ObjPtr<mirror::Array> a, JDWP::Request* src, int offset, int count)
Ian Rogersef7d42f2014-01-06 12:55:46 -08001302 NO_THREAD_SAFETY_ANALYSIS {
1303 // TODO: fix when annotalysis correctly handles non-member functions.
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001304 DCHECK(a->GetClass()->IsPrimitiveArray());
1305
Ian Rogersef7d42f2014-01-06 12:55:46 -08001306 T* dst = reinterpret_cast<T*>(a->GetRawData(sizeof(T), offset));
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001307 for (int i = 0; i < count; ++i) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001308 *dst++ = src->ReadValue(sizeof(T));
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001309 }
1310}
1311
Elliott Hughes88d63092013-01-09 09:55:54 -08001312JDWP::JdwpError Dbg::SetArrayElements(JDWP::ObjectId array_id, int offset, int count,
Ian Rogersc0542af2014-09-03 16:16:56 -07001313 JDWP::Request* request) {
1314 JDWP::JdwpError error;
Vladimir Marko4617d582019-03-28 13:48:31 +00001315 ObjPtr<mirror::Array> dst = DecodeNonNullArray(array_id, &error);
Ian Rogersc0542af2014-09-03 16:16:56 -07001316 if (dst == nullptr) {
1317 return error;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001318 }
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001319
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001320 if (offset < 0 || count < 0 || offset > dst->GetLength() || dst->GetLength() - offset < count) {
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001321 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001322 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001323 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07001324 JDWP::JdwpTag element_tag = BasicTagFromClass(dst->GetClass()->GetComponentType());
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001325
Ian Rogers1ff3c982014-08-12 02:30:58 -07001326 if (IsPrimitiveTag(element_tag)) {
1327 size_t width = GetTagWidth(element_tag);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001328 if (width == 8) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001329 CopyArrayData<uint64_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001330 } else if (width == 4) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001331 CopyArrayData<uint32_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001332 } else if (width == 2) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001333 CopyArrayData<uint16_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001334 } else {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001335 CopyArrayData<uint8_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001336 }
1337 } else {
Vladimir Marko4617d582019-03-28 13:48:31 +00001338 ObjPtr<mirror::ObjectArray<mirror::Object>> oa = dst->AsObjectArray<mirror::Object>();
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001339 for (int i = 0; i < count; ++i) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001340 JDWP::ObjectId id = request->ReadObjectId();
Vladimir Marko83114892019-04-11 13:05:50 +01001341 ObjPtr<mirror::Object> o = gRegistry->Get<mirror::Object>(id, &error);
Ian Rogersc0542af2014-09-03 16:16:56 -07001342 if (error != JDWP::ERR_NONE) {
1343 return error;
Elliott Hughes436e3722012-02-17 20:01:47 -08001344 }
Sebastien Hertz2e1c16d2015-08-28 11:57:49 +02001345 // Check if the object's type is compatible with the array's type.
1346 if (o != nullptr && !o->InstanceOf(oa->GetClass()->GetComponentType())) {
1347 return JDWP::ERR_TYPE_MISMATCH;
1348 }
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001349 oa->Set<false>(offset + i, o);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001350 }
1351 }
1352
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001353 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001354}
1355
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001356JDWP::JdwpError Dbg::CreateString(const std::string& str, JDWP::ObjectId* new_string_id) {
1357 Thread* self = Thread::Current();
Vladimir Marko179b7c62019-03-22 13:38:57 +00001358 ObjPtr<mirror::String> new_string = mirror::String::AllocFromModifiedUtf8(self, str.c_str());
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001359 if (new_string == nullptr) {
1360 DCHECK(self->IsExceptionPending());
1361 self->ClearException();
1362 LOG(ERROR) << "Could not allocate string";
1363 *new_string_id = 0;
1364 return JDWP::ERR_OUT_OF_MEMORY;
1365 }
1366 *new_string_id = gRegistry->Add(new_string);
1367 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001368}
1369
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001370JDWP::JdwpError Dbg::CreateObject(JDWP::RefTypeId class_id, JDWP::ObjectId* new_object_id) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001371 JDWP::JdwpError error;
Vladimir Marko4617d582019-03-28 13:48:31 +00001372 ObjPtr<mirror::Class> c = DecodeClass(class_id, &error);
Ian Rogersc0542af2014-09-03 16:16:56 -07001373 if (c == nullptr) {
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001374 *new_object_id = 0;
Ian Rogersc0542af2014-09-03 16:16:56 -07001375 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001376 }
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001377 Thread* self = Thread::Current();
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001378 ObjPtr<mirror::Object> new_object;
Sebastien Hertz56d5e502015-11-03 17:38:35 +01001379 if (c->IsStringClass()) {
1380 // Special case for java.lang.String.
1381 gc::AllocatorType allocator_type = Runtime::Current()->GetHeap()->GetCurrentAllocator();
Vladimir Marko9b81ac32019-05-16 16:47:08 +01001382 new_object = mirror::String::AllocEmptyString(self, allocator_type);
Sebastien Hertz56d5e502015-11-03 17:38:35 +01001383 } else {
1384 new_object = c->AllocObject(self);
1385 }
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001386 if (new_object == nullptr) {
1387 DCHECK(self->IsExceptionPending());
1388 self->ClearException();
David Sehr709b0702016-10-13 09:12:37 -07001389 LOG(ERROR) << "Could not allocate object of type " << mirror::Class::PrettyDescriptor(c);
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001390 *new_object_id = 0;
1391 return JDWP::ERR_OUT_OF_MEMORY;
1392 }
Vladimir Markobcf17522018-06-01 13:14:32 +01001393 *new_object_id = gRegistry->Add(new_object);
Elliott Hughes436e3722012-02-17 20:01:47 -08001394 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001395}
1396
Elliott Hughesbf13d362011-12-08 15:51:37 -08001397/*
1398 * Used by Eclipse's "Display" view to evaluate "new byte[5]" to get "(byte[]) [0, 0, 0, 0, 0]".
1399 */
Elliott Hughes88d63092013-01-09 09:55:54 -08001400JDWP::JdwpError Dbg::CreateArrayObject(JDWP::RefTypeId array_class_id, uint32_t length,
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001401 JDWP::ObjectId* new_array_id) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001402 JDWP::JdwpError error;
Vladimir Marko4617d582019-03-28 13:48:31 +00001403 ObjPtr<mirror::Class> c = DecodeClass(array_class_id, &error);
Ian Rogersc0542af2014-09-03 16:16:56 -07001404 if (c == nullptr) {
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001405 *new_array_id = 0;
Ian Rogersc0542af2014-09-03 16:16:56 -07001406 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001407 }
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001408 Thread* self = Thread::Current();
Vladimir Markobcf17522018-06-01 13:14:32 +01001409 gc::AllocatorType allocator_type = Runtime::Current()->GetHeap()->GetCurrentAllocator();
1410 ObjPtr<mirror::Array> new_array =
Vladimir Marko9b81ac32019-05-16 16:47:08 +01001411 mirror::Array::Alloc(self, c, length, c->GetComponentSizeShift(), allocator_type);
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001412 if (new_array == nullptr) {
1413 DCHECK(self->IsExceptionPending());
1414 self->ClearException();
David Sehr709b0702016-10-13 09:12:37 -07001415 LOG(ERROR) << "Could not allocate array of type " << mirror::Class::PrettyDescriptor(c);
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001416 *new_array_id = 0;
1417 return JDWP::ERR_OUT_OF_MEMORY;
1418 }
1419 *new_array_id = gRegistry->Add(new_array);
Elliott Hughes436e3722012-02-17 20:01:47 -08001420 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001421}
1422
Mathieu Chartierc7853442015-03-27 14:35:38 -07001423JDWP::FieldId Dbg::ToFieldId(const ArtField* f) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001424 return static_cast<JDWP::FieldId>(reinterpret_cast<uintptr_t>(f));
Elliott Hughes03181a82011-11-17 17:22:21 -08001425}
1426
Alex Light6c8467f2015-11-20 15:03:26 -08001427static JDWP::MethodId ToMethodId(ArtMethod* m)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001428 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light97e78032017-06-27 17:51:55 -07001429 return static_cast<JDWP::MethodId>(
1430 reinterpret_cast<uintptr_t>(m->GetCanonicalMethod(kRuntimePointerSize)));
Elliott Hughes03181a82011-11-17 17:22:21 -08001431}
1432
Mathieu Chartierc7853442015-03-27 14:35:38 -07001433static ArtField* FromFieldId(JDWP::FieldId fid)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001434 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001435 return reinterpret_cast<ArtField*>(static_cast<uintptr_t>(fid));
Elliott Hughesaed4be92011-12-02 16:16:23 -08001436}
1437
Mathieu Chartiere401d142015-04-22 13:56:20 -07001438static ArtMethod* FromMethodId(JDWP::MethodId mid)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001439 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001440 return reinterpret_cast<ArtMethod*>(static_cast<uintptr_t>(mid));
Elliott Hughes03181a82011-11-17 17:22:21 -08001441}
1442
Sebastien Hertz6995c602014-09-09 12:10:13 +02001443bool Dbg::MatchThread(JDWP::ObjectId expected_thread_id, Thread* event_thread) {
1444 CHECK(event_thread != nullptr);
1445 JDWP::JdwpError error;
Vladimir Marko83114892019-04-11 13:05:50 +01001446 ObjPtr<mirror::Object> expected_thread_peer = gRegistry->Get<mirror::Object>(
Mathieu Chartiere401d142015-04-22 13:56:20 -07001447 expected_thread_id, &error);
Nicolas Geoffraycafa0812017-02-15 18:27:34 +00001448 return expected_thread_peer == event_thread->GetPeerFromOtherThread();
Sebastien Hertz6995c602014-09-09 12:10:13 +02001449}
1450
1451bool Dbg::MatchLocation(const JDWP::JdwpLocation& expected_location,
1452 const JDWP::EventLocation& event_location) {
1453 if (expected_location.dex_pc != event_location.dex_pc) {
1454 return false;
1455 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001456 ArtMethod* m = FromMethodId(expected_location.method_id);
Sebastien Hertz6995c602014-09-09 12:10:13 +02001457 return m == event_location.method;
1458}
1459
Mathieu Chartier3398c782016-09-30 10:27:43 -07001460bool Dbg::MatchType(ObjPtr<mirror::Class> event_class, JDWP::RefTypeId class_id) {
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001461 if (event_class == nullptr) {
1462 return false;
1463 }
Sebastien Hertz6995c602014-09-09 12:10:13 +02001464 JDWP::JdwpError error;
Mathieu Chartier3398c782016-09-30 10:27:43 -07001465 ObjPtr<mirror::Class> expected_class = DecodeClass(class_id, &error);
Sebastien Hertz6995c602014-09-09 12:10:13 +02001466 CHECK(expected_class != nullptr);
1467 return expected_class->IsAssignableFrom(event_class);
1468}
1469
Vladimir Marko83114892019-04-11 13:05:50 +01001470bool Dbg::MatchField(JDWP::RefTypeId expected_type_id,
1471 JDWP::FieldId expected_field_id,
Mathieu Chartierc7853442015-03-27 14:35:38 -07001472 ArtField* event_field) {
1473 ArtField* expected_field = FromFieldId(expected_field_id);
Sebastien Hertz6995c602014-09-09 12:10:13 +02001474 if (expected_field != event_field) {
1475 return false;
1476 }
1477 return Dbg::MatchType(event_field->GetDeclaringClass(), expected_type_id);
1478}
1479
Vladimir Marko83114892019-04-11 13:05:50 +01001480bool Dbg::MatchInstance(JDWP::ObjectId expected_instance_id,
1481 ObjPtr<mirror::Object> event_instance) {
Sebastien Hertz6995c602014-09-09 12:10:13 +02001482 JDWP::JdwpError error;
Vladimir Marko83114892019-04-11 13:05:50 +01001483 ObjPtr<mirror::Object> modifier_instance =
1484 gRegistry->Get<mirror::Object>(expected_instance_id, &error);
Sebastien Hertz6995c602014-09-09 12:10:13 +02001485 return modifier_instance == event_instance;
1486}
1487
Mathieu Chartier90443472015-07-16 20:32:27 -07001488void Dbg::SetJdwpLocation(JDWP::JdwpLocation* location, ArtMethod* m, uint32_t dex_pc) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001489 if (m == nullptr) {
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001490 memset(location, 0, sizeof(*location));
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001491 } else {
Vladimir Markod93e3742018-07-18 10:58:13 +01001492 ObjPtr<mirror::Class> c = m->GetDeclaringClass();
Ian Rogersc0542af2014-09-03 16:16:56 -07001493 location->type_tag = GetTypeTag(c);
1494 location->class_id = gRegistry->AddRefType(c);
Alex Light73376312017-04-06 10:10:51 -07001495 // The RI Seems to return 0 for all obsolete methods. For compatibility we shall do the same.
1496 location->method_id = m->IsObsolete() ? 0 : ToMethodId(m);
Ian Rogersc0542af2014-09-03 16:16:56 -07001497 location->dex_pc = (m->IsNative() || m->IsProxyMethod()) ? static_cast<uint64_t>(-1) : dex_pc;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001498 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08001499}
1500
Ian Rogersc0542af2014-09-03 16:16:56 -07001501std::string Dbg::GetMethodName(JDWP::MethodId method_id) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001502 ArtMethod* m = FromMethodId(method_id);
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001503 if (m == nullptr) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001504 return "null";
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001505 }
Andreas Gampe542451c2016-07-26 09:02:02 -07001506 return m->GetInterfaceMethodIfProxy(kRuntimePointerSize)->GetName();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001507}
1508
Alex Light73376312017-04-06 10:10:51 -07001509bool Dbg::IsMethodObsolete(JDWP::MethodId method_id) {
1510 ArtMethod* m = FromMethodId(method_id);
1511 if (m == nullptr) {
1512 // NB Since we return 0 as MID for obsolete methods we want to default to true here.
1513 return true;
1514 }
1515 return m->IsObsolete();
1516}
1517
Ian Rogersc0542af2014-09-03 16:16:56 -07001518std::string Dbg::GetFieldName(JDWP::FieldId field_id) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001519 ArtField* f = FromFieldId(field_id);
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001520 if (f == nullptr) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001521 return "null";
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001522 }
1523 return f->GetName();
Elliott Hughesa96836a2013-01-17 12:27:49 -08001524}
1525
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001526/*
1527 * Augment the access flags for synthetic methods and fields by setting
1528 * the (as described by the spec) "0xf0000000 bit". Also, strip out any
1529 * flags not specified by the Java programming language.
1530 */
1531static uint32_t MangleAccessFlags(uint32_t accessFlags) {
1532 accessFlags &= kAccJavaFlagsMask;
1533 if ((accessFlags & kAccSynthetic) != 0) {
1534 accessFlags |= 0xf0000000;
1535 }
1536 return accessFlags;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001537}
1538
Elliott Hughesdbb40792011-11-18 17:05:22 -08001539/*
Jeff Haob7cefc72013-11-14 14:51:09 -08001540 * Circularly shifts registers so that arguments come first. Debuggers
1541 * expect slots to begin with arguments, but dex code places them at
1542 * the end.
Elliott Hughesdbb40792011-11-18 17:05:22 -08001543 */
Mathieu Chartiere401d142015-04-22 13:56:20 -07001544static uint16_t MangleSlot(uint16_t slot, ArtMethod* m)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001545 REQUIRES_SHARED(Locks::mutator_lock_) {
David Sehr0225f8e2018-01-31 08:52:24 +00001546 CodeItemDataAccessor accessor(m->DexInstructionData());
Mathieu Chartier808c7a52017-12-15 11:19:33 -08001547 if (!accessor.HasCodeItem()) {
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001548 // We should not get here for a method without code (native, proxy or abstract). Log it and
1549 // return the slot as is since all registers are arguments.
David Sehr709b0702016-10-13 09:12:37 -07001550 LOG(WARNING) << "Trying to mangle slot for method without code " << m->PrettyMethod();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001551 return slot;
1552 }
Mathieu Chartier808c7a52017-12-15 11:19:33 -08001553 uint16_t ins_size = accessor.InsSize();
1554 uint16_t locals_size = accessor.RegistersSize() - ins_size;
Jeff Haob7cefc72013-11-14 14:51:09 -08001555 if (slot >= locals_size) {
1556 return slot - locals_size;
1557 } else {
1558 return slot + ins_size;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001559 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001560}
1561
Sebastien Hertzaef0c912016-08-08 10:20:28 +02001562static size_t GetMethodNumArgRegistersIncludingThis(ArtMethod* method)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001563 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertzaef0c912016-08-08 10:20:28 +02001564 uint32_t num_registers = ArtMethod::NumArgRegisters(method->GetShorty());
1565 if (!method->IsStatic()) {
1566 ++num_registers;
1567 }
1568 return num_registers;
1569}
1570
Jeff Haob7cefc72013-11-14 14:51:09 -08001571/*
1572 * Circularly shifts registers so that arguments come last. Reverts
1573 * slots to dex style argument placement.
1574 */
Mathieu Chartiere401d142015-04-22 13:56:20 -07001575static uint16_t DemangleSlot(uint16_t slot, ArtMethod* m, JDWP::JdwpError* error)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001576 REQUIRES_SHARED(Locks::mutator_lock_) {
David Sehr0225f8e2018-01-31 08:52:24 +00001577 CodeItemDataAccessor accessor(m->DexInstructionData());
Mathieu Chartier808c7a52017-12-15 11:19:33 -08001578 if (!accessor.HasCodeItem()) {
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001579 // We should not get here for a method without code (native, proxy or abstract). Log it and
1580 // return the slot as is since all registers are arguments.
David Sehr709b0702016-10-13 09:12:37 -07001581 LOG(WARNING) << "Trying to demangle slot for method without code "
1582 << m->PrettyMethod();
Sebastien Hertzaef0c912016-08-08 10:20:28 +02001583 uint16_t vreg_count = GetMethodNumArgRegistersIncludingThis(m);
Sebastien Hertzabbabc82015-03-26 08:47:47 +01001584 if (slot < vreg_count) {
1585 *error = JDWP::ERR_NONE;
1586 return slot;
1587 }
Jeff Haob7cefc72013-11-14 14:51:09 -08001588 } else {
Mathieu Chartier808c7a52017-12-15 11:19:33 -08001589 if (slot < accessor.RegistersSize()) {
1590 uint16_t ins_size = accessor.InsSize();
1591 uint16_t locals_size = accessor.RegistersSize() - ins_size;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01001592 *error = JDWP::ERR_NONE;
1593 return (slot < ins_size) ? slot + locals_size : slot - ins_size;
1594 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001595 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01001596
1597 // Slot is invalid in the method.
David Sehr709b0702016-10-13 09:12:37 -07001598 LOG(ERROR) << "Invalid local slot " << slot << " for method " << m->PrettyMethod();
Sebastien Hertzabbabc82015-03-26 08:47:47 +01001599 *error = JDWP::ERR_INVALID_SLOT;
1600 return DexFile::kDexNoIndex16;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001601}
1602
Mathieu Chartier90443472015-07-16 20:32:27 -07001603JDWP::JdwpError Dbg::OutputDeclaredFields(JDWP::RefTypeId class_id, bool with_generic,
1604 JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001605 JDWP::JdwpError error;
Vladimir Marko4617d582019-03-28 13:48:31 +00001606 ObjPtr<mirror::Class> c = DecodeClass(class_id, &error);
Ian Rogersc0542af2014-09-03 16:16:56 -07001607 if (c == nullptr) {
1608 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001609 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001610
1611 size_t instance_field_count = c->NumInstanceFields();
1612 size_t static_field_count = c->NumStaticFields();
1613
1614 expandBufAdd4BE(pReply, instance_field_count + static_field_count);
1615
1616 for (size_t i = 0; i < instance_field_count + static_field_count; ++i) {
Mathieu Chartier90443472015-07-16 20:32:27 -07001617 ArtField* f = (i < instance_field_count) ? c->GetInstanceField(i) :
1618 c->GetStaticField(i - instance_field_count);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001619 expandBufAddFieldId(pReply, ToFieldId(f));
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001620 expandBufAddUtf8String(pReply, f->GetName());
1621 expandBufAddUtf8String(pReply, f->GetTypeDescriptor());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001622 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001623 static const char genericSignature[1] = "";
1624 expandBufAddUtf8String(pReply, genericSignature);
1625 }
1626 expandBufAdd4BE(pReply, MangleAccessFlags(f->GetAccessFlags()));
1627 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001628 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001629}
1630
Elliott Hughes88d63092013-01-09 09:55:54 -08001631JDWP::JdwpError Dbg::OutputDeclaredMethods(JDWP::RefTypeId class_id, bool with_generic,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001632 JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001633 JDWP::JdwpError error;
Vladimir Marko4617d582019-03-28 13:48:31 +00001634 ObjPtr<mirror::Class> c = DecodeClass(class_id, &error);
Ian Rogersc0542af2014-09-03 16:16:56 -07001635 if (c == nullptr) {
1636 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001637 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001638
Alex Light51a64d52015-12-17 13:55:59 -08001639 expandBufAdd4BE(pReply, c->NumMethods());
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001640
Mathieu Chartiere401d142015-04-22 13:56:20 -07001641 auto* cl = Runtime::Current()->GetClassLinker();
1642 auto ptr_size = cl->GetImagePointerSize();
Alex Light51a64d52015-12-17 13:55:59 -08001643 for (ArtMethod& m : c->GetMethods(ptr_size)) {
1644 expandBufAddMethodId(pReply, ToMethodId(&m));
Andreas Gampe542451c2016-07-26 09:02:02 -07001645 expandBufAddUtf8String(pReply, m.GetInterfaceMethodIfProxy(kRuntimePointerSize)->GetName());
1646 expandBufAddUtf8String(
1647 pReply, m.GetInterfaceMethodIfProxy(kRuntimePointerSize)->GetSignature().ToString());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001648 if (with_generic) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001649 const char* generic_signature = "";
1650 expandBufAddUtf8String(pReply, generic_signature);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001651 }
Alex Light51a64d52015-12-17 13:55:59 -08001652 expandBufAdd4BE(pReply, MangleAccessFlags(m.GetAccessFlags()));
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001653 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001654 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001655}
1656
Elliott Hughes88d63092013-01-09 09:55:54 -08001657JDWP::JdwpError Dbg::OutputDeclaredInterfaces(JDWP::RefTypeId class_id, JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001658 JDWP::JdwpError error;
Mathieu Chartierf8322842014-05-16 10:59:25 -07001659 Thread* self = Thread::Current();
Vladimir Marko19a4d372016-12-08 14:41:46 +00001660 ObjPtr<mirror::Class> c = DecodeClass(class_id, &error);
1661 if (c == nullptr) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001662 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001663 }
Mathieu Chartierf8322842014-05-16 10:59:25 -07001664 size_t interface_count = c->NumDirectInterfaces();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001665 expandBufAdd4BE(pReply, interface_count);
1666 for (size_t i = 0; i < interface_count; ++i) {
Vladimir Marko19a4d372016-12-08 14:41:46 +00001667 ObjPtr<mirror::Class> interface = mirror::Class::GetDirectInterface(self, c, i);
1668 DCHECK(interface != nullptr);
1669 expandBufAddRefTypeId(pReply, gRegistry->AddRefType(interface));
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001670 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001671 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001672}
1673
Ian Rogersc0542af2014-09-03 16:16:56 -07001674void Dbg::OutputLineTable(JDWP::RefTypeId, JDWP::MethodId method_id, JDWP::ExpandBuf* pReply) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001675 ArtMethod* m = FromMethodId(method_id);
David Sehr0225f8e2018-01-31 08:52:24 +00001676 CodeItemDebugInfoAccessor accessor(m->DexInstructionDebugInfo());
Elliott Hughes03181a82011-11-17 17:22:21 -08001677 uint64_t start, end;
Mathieu Chartier31f4c9f2017-12-08 15:46:11 -08001678 if (!accessor.HasCodeItem()) {
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001679 DCHECK(m->IsNative() || m->IsProxyMethod());
Elliott Hughes03181a82011-11-17 17:22:21 -08001680 start = -1;
1681 end = -1;
1682 } else {
1683 start = 0;
jeffhao14f0db92012-12-14 17:50:42 -08001684 // Return the index of the last instruction
Mathieu Chartier31f4c9f2017-12-08 15:46:11 -08001685 end = accessor.InsnsSizeInCodeUnits() - 1;
Elliott Hughes03181a82011-11-17 17:22:21 -08001686 }
1687
1688 expandBufAdd8BE(pReply, start);
1689 expandBufAdd8BE(pReply, end);
1690
1691 // Add numLines later
1692 size_t numLinesOffset = expandBufGetLength(pReply);
1693 expandBufAdd4BE(pReply, 0);
1694
Mathieu Chartier3e2e1232018-09-11 12:35:30 -07001695 int numItems = 0;
1696 accessor.DecodeDebugPositionInfo([&](const DexFile::PositionInfo& entry) {
1697 expandBufAdd8BE(pReply, entry.address_);
1698 expandBufAdd4BE(pReply, entry.line_);
1699 numItems++;
1700 return false;
1701 });
Elliott Hughes03181a82011-11-17 17:22:21 -08001702
Mathieu Chartier3e2e1232018-09-11 12:35:30 -07001703 JDWP::Set4BE(expandBufGetBuffer(pReply) + numLinesOffset, numItems);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001704}
1705
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001706void Dbg::OutputVariableTable(JDWP::RefTypeId, JDWP::MethodId method_id, bool with_generic,
1707 JDWP::ExpandBuf* pReply) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001708 ArtMethod* m = FromMethodId(method_id);
David Sehr0225f8e2018-01-31 08:52:24 +00001709 CodeItemDebugInfoAccessor accessor(m->DexInstructionDebugInfo());
Elliott Hughesdbb40792011-11-18 17:05:22 -08001710
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001711 // arg_count considers doubles and longs to take 2 units.
1712 // variable_count considers everything to take 1 unit.
Sebastien Hertzaef0c912016-08-08 10:20:28 +02001713 expandBufAdd4BE(pReply, GetMethodNumArgRegistersIncludingThis(m));
Elliott Hughesdbb40792011-11-18 17:05:22 -08001714
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001715 // We don't know the total number of variables yet, so leave a blank and update it later.
1716 size_t variable_count_offset = expandBufGetLength(pReply);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001717 expandBufAdd4BE(pReply, 0);
1718
Mathieu Chartiere5afbf32018-09-12 17:51:54 -07001719 size_t variable_count = 0;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001720
Mathieu Chartier31f4c9f2017-12-08 15:46:11 -08001721 if (accessor.HasCodeItem()) {
Mathieu Chartiere5afbf32018-09-12 17:51:54 -07001722 accessor.DecodeDebugLocalInfo(m->IsStatic(),
1723 m->GetDexMethodIndex(),
1724 [&](const DexFile::LocalInfo& entry)
1725 REQUIRES_SHARED(Locks::mutator_lock_) {
1726 uint16_t slot = entry.reg_;
1727 VLOG(jdwp) << StringPrintf(" %2zd: %d(%d) '%s' '%s' '%s' actual slot=%d mangled slot=%d",
1728 variable_count,
1729 entry.start_address_,
1730 entry.end_address_ - entry.start_address_,
1731 entry.name_,
1732 entry.descriptor_, entry.signature_,
1733 slot,
1734 MangleSlot(slot, m));
1735
1736 slot = MangleSlot(slot, m);
1737
1738 expandBufAdd8BE(pReply, entry.start_address_);
1739 expandBufAddUtf8String(pReply, entry.name_);
1740 expandBufAddUtf8String(pReply, entry.descriptor_);
1741 if (with_generic) {
1742 expandBufAddUtf8String(pReply, entry.signature_);
1743 }
1744 expandBufAdd4BE(pReply, entry.end_address_- entry.start_address_);
1745 expandBufAdd4BE(pReply, slot);
1746
1747 ++variable_count;
1748 });
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001749 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001750
Mathieu Chartiere5afbf32018-09-12 17:51:54 -07001751 JDWP::Set4BE(expandBufGetBuffer(pReply) + variable_count_offset, variable_count);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001752}
1753
Jeff Hao579b0242013-11-18 13:16:49 -08001754void Dbg::OutputMethodReturnValue(JDWP::MethodId method_id, const JValue* return_value,
1755 JDWP::ExpandBuf* pReply) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001756 ArtMethod* m = FromMethodId(method_id);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001757 JDWP::JdwpTag tag = BasicTagFromDescriptor(m->GetShorty());
Jeff Hao579b0242013-11-18 13:16:49 -08001758 OutputJValue(tag, return_value, pReply);
1759}
1760
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02001761void Dbg::OutputFieldValue(JDWP::FieldId field_id, const JValue* field_value,
1762 JDWP::ExpandBuf* pReply) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001763 ArtField* f = FromFieldId(field_id);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001764 JDWP::JdwpTag tag = BasicTagFromDescriptor(f->GetTypeDescriptor());
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02001765 OutputJValue(tag, field_value, pReply);
1766}
1767
Elliott Hughes9777ba22013-01-17 09:04:19 -08001768JDWP::JdwpError Dbg::GetBytecodes(JDWP::RefTypeId, JDWP::MethodId method_id,
Ian Rogersc0542af2014-09-03 16:16:56 -07001769 std::vector<uint8_t>* bytecodes) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001770 ArtMethod* m = FromMethodId(method_id);
Ian Rogersc0542af2014-09-03 16:16:56 -07001771 if (m == nullptr) {
Elliott Hughes9777ba22013-01-17 09:04:19 -08001772 return JDWP::ERR_INVALID_METHODID;
1773 }
David Sehr0225f8e2018-01-31 08:52:24 +00001774 CodeItemDataAccessor accessor(m->DexInstructionData());
Mathieu Chartier808c7a52017-12-15 11:19:33 -08001775 size_t byte_count = accessor.InsnsSizeInCodeUnits() * 2;
1776 const uint8_t* begin = reinterpret_cast<const uint8_t*>(accessor.Insns());
Elliott Hughes9777ba22013-01-17 09:04:19 -08001777 const uint8_t* end = begin + byte_count;
1778 for (const uint8_t* p = begin; p != end; ++p) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001779 bytecodes->push_back(*p);
Elliott Hughes9777ba22013-01-17 09:04:19 -08001780 }
1781 return JDWP::ERR_NONE;
1782}
1783
Elliott Hughes88d63092013-01-09 09:55:54 -08001784JDWP::JdwpTag Dbg::GetFieldBasicTag(JDWP::FieldId field_id) {
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001785 return BasicTagFromDescriptor(FromFieldId(field_id)->GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001786}
1787
Elliott Hughes88d63092013-01-09 09:55:54 -08001788JDWP::JdwpTag Dbg::GetStaticFieldBasicTag(JDWP::FieldId field_id) {
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001789 return BasicTagFromDescriptor(FromFieldId(field_id)->GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001790}
1791
Vladimir Marko83114892019-04-11 13:05:50 +01001792static JValue GetArtFieldValue(ArtField* f, ObjPtr<mirror::Object> o)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001793 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001794 Primitive::Type fieldType = f->GetTypeAsPrimitiveType();
1795 JValue field_value;
1796 switch (fieldType) {
1797 case Primitive::kPrimBoolean:
1798 field_value.SetZ(f->GetBoolean(o));
1799 return field_value;
1800
1801 case Primitive::kPrimByte:
1802 field_value.SetB(f->GetByte(o));
1803 return field_value;
1804
1805 case Primitive::kPrimChar:
1806 field_value.SetC(f->GetChar(o));
1807 return field_value;
1808
1809 case Primitive::kPrimShort:
1810 field_value.SetS(f->GetShort(o));
1811 return field_value;
1812
1813 case Primitive::kPrimInt:
1814 case Primitive::kPrimFloat:
1815 // Int and Float must be treated as 32-bit values in JDWP.
1816 field_value.SetI(f->GetInt(o));
1817 return field_value;
1818
1819 case Primitive::kPrimLong:
1820 case Primitive::kPrimDouble:
1821 // Long and Double must be treated as 64-bit values in JDWP.
1822 field_value.SetJ(f->GetLong(o));
1823 return field_value;
1824
1825 case Primitive::kPrimNot:
Vladimir Markobcf17522018-06-01 13:14:32 +01001826 field_value.SetL(f->GetObject(o));
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001827 return field_value;
1828
1829 case Primitive::kPrimVoid:
1830 LOG(FATAL) << "Attempt to read from field of type 'void'";
1831 UNREACHABLE();
1832 }
1833 LOG(FATAL) << "Attempt to read from field of unknown type";
1834 UNREACHABLE();
1835}
1836
Elliott Hughes88d63092013-01-09 09:55:54 -08001837static JDWP::JdwpError GetFieldValueImpl(JDWP::RefTypeId ref_type_id, JDWP::ObjectId object_id,
1838 JDWP::FieldId field_id, JDWP::ExpandBuf* pReply,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001839 bool is_static)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001840 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001841 JDWP::JdwpError error;
Vladimir Marko4617d582019-03-28 13:48:31 +00001842 ObjPtr<mirror::Class> c = DecodeClass(ref_type_id, &error);
Ian Rogersc0542af2014-09-03 16:16:56 -07001843 if (ref_type_id != 0 && c == nullptr) {
1844 return error;
Elliott Hughes0cf74332012-02-23 23:14:00 -08001845 }
1846
Jeff Haode19a252016-09-14 15:56:35 -07001847 Thread* self = Thread::Current();
1848 StackHandleScope<2> hs(self);
1849 MutableHandle<mirror::Object>
Vladimir Marko83114892019-04-11 13:05:50 +01001850 o(hs.NewHandle(Dbg::GetObjectRegistry()->Get<mirror::Object>(object_id, &error)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08001851 if ((!is_static && o == nullptr) || error != JDWP::ERR_NONE) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001852 return JDWP::ERR_INVALID_OBJECT;
1853 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001854 ArtField* f = FromFieldId(field_id);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001855
Vladimir Marko4617d582019-03-28 13:48:31 +00001856 ObjPtr<mirror::Class> receiver_class = c;
Andreas Gampefa4333d2017-02-14 11:10:34 -08001857 if (receiver_class == nullptr && o != nullptr) {
Elliott Hughes0cf74332012-02-23 23:14:00 -08001858 receiver_class = o->GetClass();
1859 }
Jeff Haode19a252016-09-14 15:56:35 -07001860
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001861 // TODO: should we give up now if receiver_class is null?
Ian Rogersc0542af2014-09-03 16:16:56 -07001862 if (receiver_class != nullptr && !f->GetDeclaringClass()->IsAssignableFrom(receiver_class)) {
David Sehr709b0702016-10-13 09:12:37 -07001863 LOG(INFO) << "ERR_INVALID_FIELDID: " << f->PrettyField() << " "
1864 << receiver_class->PrettyClass();
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001865 return JDWP::ERR_INVALID_FIELDID;
1866 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001867
Jeff Haode19a252016-09-14 15:56:35 -07001868 // Ensure the field's class is initialized.
1869 Handle<mirror::Class> klass(hs.NewHandle(f->GetDeclaringClass()));
1870 if (!Runtime::Current()->GetClassLinker()->EnsureInitialized(self, klass, true, false)) {
David Sehr709b0702016-10-13 09:12:37 -07001871 LOG(WARNING) << "Not able to initialize class for SetValues: "
1872 << mirror::Class::PrettyClass(klass.Get());
Jeff Haode19a252016-09-14 15:56:35 -07001873 }
1874
Elliott Hughes0cf74332012-02-23 23:14:00 -08001875 // The RI only enforces the static/non-static mismatch in one direction.
1876 // TODO: should we change the tests and check both?
1877 if (is_static) {
1878 if (!f->IsStatic()) {
1879 return JDWP::ERR_INVALID_FIELDID;
1880 }
1881 } else {
1882 if (f->IsStatic()) {
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001883 LOG(WARNING) << "Ignoring non-nullptr receiver for ObjectReference.GetValues"
David Sehr709b0702016-10-13 09:12:37 -07001884 << " on static field " << f->PrettyField();
Elliott Hughes0cf74332012-02-23 23:14:00 -08001885 }
1886 }
jeffhao0dfbb7e2012-11-28 15:26:03 -08001887 if (f->IsStatic()) {
Jeff Haode19a252016-09-14 15:56:35 -07001888 o.Assign(f->GetDeclaringClass());
jeffhao0dfbb7e2012-11-28 15:26:03 -08001889 }
Elliott Hughes0cf74332012-02-23 23:14:00 -08001890
Jeff Haode19a252016-09-14 15:56:35 -07001891 JValue field_value(GetArtFieldValue(f, o.Get()));
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001892 JDWP::JdwpTag tag = BasicTagFromDescriptor(f->GetTypeDescriptor());
Jeff Hao579b0242013-11-18 13:16:49 -08001893 Dbg::OutputJValue(tag, &field_value, pReply);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001894 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001895}
1896
Elliott Hughes88d63092013-01-09 09:55:54 -08001897JDWP::JdwpError Dbg::GetFieldValue(JDWP::ObjectId object_id, JDWP::FieldId field_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001898 JDWP::ExpandBuf* pReply) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001899 return GetFieldValueImpl(0, object_id, field_id, pReply, false);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001900}
1901
Ian Rogersc0542af2014-09-03 16:16:56 -07001902JDWP::JdwpError Dbg::GetStaticFieldValue(JDWP::RefTypeId ref_type_id, JDWP::FieldId field_id,
1903 JDWP::ExpandBuf* pReply) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001904 return GetFieldValueImpl(ref_type_id, 0, field_id, pReply, true);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001905}
1906
Vladimir Marko83114892019-04-11 13:05:50 +01001907static JDWP::JdwpError SetArtFieldValue(ArtField* f,
1908 ObjPtr<mirror::Object> o,
1909 uint64_t value,
1910 int width)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001911 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001912 Primitive::Type fieldType = f->GetTypeAsPrimitiveType();
1913 // Debugging only happens at runtime so we know we are not running in a transaction.
1914 static constexpr bool kNoTransactionMode = false;
1915 switch (fieldType) {
1916 case Primitive::kPrimBoolean:
1917 CHECK_EQ(width, 1);
1918 f->SetBoolean<kNoTransactionMode>(o, static_cast<uint8_t>(value));
1919 return JDWP::ERR_NONE;
1920
1921 case Primitive::kPrimByte:
1922 CHECK_EQ(width, 1);
1923 f->SetByte<kNoTransactionMode>(o, static_cast<uint8_t>(value));
1924 return JDWP::ERR_NONE;
1925
1926 case Primitive::kPrimChar:
1927 CHECK_EQ(width, 2);
1928 f->SetChar<kNoTransactionMode>(o, static_cast<uint16_t>(value));
1929 return JDWP::ERR_NONE;
1930
1931 case Primitive::kPrimShort:
1932 CHECK_EQ(width, 2);
1933 f->SetShort<kNoTransactionMode>(o, static_cast<int16_t>(value));
1934 return JDWP::ERR_NONE;
1935
1936 case Primitive::kPrimInt:
1937 case Primitive::kPrimFloat:
1938 CHECK_EQ(width, 4);
1939 // Int and Float must be treated as 32-bit values in JDWP.
1940 f->SetInt<kNoTransactionMode>(o, static_cast<int32_t>(value));
1941 return JDWP::ERR_NONE;
1942
1943 case Primitive::kPrimLong:
1944 case Primitive::kPrimDouble:
1945 CHECK_EQ(width, 8);
1946 // Long and Double must be treated as 64-bit values in JDWP.
1947 f->SetLong<kNoTransactionMode>(o, value);
1948 return JDWP::ERR_NONE;
1949
1950 case Primitive::kPrimNot: {
1951 JDWP::JdwpError error;
Vladimir Marko83114892019-04-11 13:05:50 +01001952 ObjPtr<mirror::Object> v = Dbg::GetObjectRegistry()->Get<mirror::Object>(value, &error);
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001953 if (error != JDWP::ERR_NONE) {
1954 return JDWP::ERR_INVALID_OBJECT;
1955 }
1956 if (v != nullptr) {
Mathieu Chartier3398c782016-09-30 10:27:43 -07001957 ObjPtr<mirror::Class> field_type;
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001958 {
1959 StackHandleScope<2> hs(Thread::Current());
Vladimir Marko83114892019-04-11 13:05:50 +01001960 HandleWrapperObjPtr<mirror::Object> h_v(hs.NewHandleWrapper(&v));
1961 HandleWrapperObjPtr<mirror::Object> h_o(hs.NewHandleWrapper(&o));
Vladimir Marko4098a7a2017-11-06 16:00:51 +00001962 field_type = f->ResolveType();
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001963 }
1964 if (!field_type->IsAssignableFrom(v->GetClass())) {
1965 return JDWP::ERR_INVALID_OBJECT;
1966 }
1967 }
1968 f->SetObject<kNoTransactionMode>(o, v);
1969 return JDWP::ERR_NONE;
1970 }
1971
1972 case Primitive::kPrimVoid:
1973 LOG(FATAL) << "Attempt to write to field of type 'void'";
1974 UNREACHABLE();
1975 }
1976 LOG(FATAL) << "Attempt to write to field of unknown type";
1977 UNREACHABLE();
1978}
1979
Elliott Hughes88d63092013-01-09 09:55:54 -08001980static JDWP::JdwpError SetFieldValueImpl(JDWP::ObjectId object_id, JDWP::FieldId field_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001981 uint64_t value, int width, bool is_static)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001982 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001983 JDWP::JdwpError error;
Jeff Haode19a252016-09-14 15:56:35 -07001984 Thread* self = Thread::Current();
1985 StackHandleScope<2> hs(self);
1986 MutableHandle<mirror::Object>
Vladimir Marko83114892019-04-11 13:05:50 +01001987 o(hs.NewHandle(Dbg::GetObjectRegistry()->Get<mirror::Object>(object_id, &error)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08001988 if ((!is_static && o == nullptr) || error != JDWP::ERR_NONE) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001989 return JDWP::ERR_INVALID_OBJECT;
1990 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001991 ArtField* f = FromFieldId(field_id);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001992
Jeff Haode19a252016-09-14 15:56:35 -07001993 // Ensure the field's class is initialized.
1994 Handle<mirror::Class> klass(hs.NewHandle(f->GetDeclaringClass()));
1995 if (!Runtime::Current()->GetClassLinker()->EnsureInitialized(self, klass, true, false)) {
David Sehr709b0702016-10-13 09:12:37 -07001996 LOG(WARNING) << "Not able to initialize class for SetValues: "
1997 << mirror::Class::PrettyClass(klass.Get());
Jeff Haode19a252016-09-14 15:56:35 -07001998 }
1999
Elliott Hughes0cf74332012-02-23 23:14:00 -08002000 // The RI only enforces the static/non-static mismatch in one direction.
2001 // TODO: should we change the tests and check both?
2002 if (is_static) {
2003 if (!f->IsStatic()) {
2004 return JDWP::ERR_INVALID_FIELDID;
2005 }
2006 } else {
2007 if (f->IsStatic()) {
Sebastien Hertz05c26b32015-06-11 18:42:58 +02002008 LOG(WARNING) << "Ignoring non-nullptr receiver for ObjectReference.SetValues"
David Sehr709b0702016-10-13 09:12:37 -07002009 << " on static field " << f->PrettyField();
Elliott Hughes0cf74332012-02-23 23:14:00 -08002010 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002011 }
jeffhao0dfbb7e2012-11-28 15:26:03 -08002012 if (f->IsStatic()) {
Jeff Haode19a252016-09-14 15:56:35 -07002013 o.Assign(f->GetDeclaringClass());
jeffhao0dfbb7e2012-11-28 15:26:03 -08002014 }
Jeff Haode19a252016-09-14 15:56:35 -07002015 return SetArtFieldValue(f, o.Get(), value, width);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002016}
2017
Elliott Hughes88d63092013-01-09 09:55:54 -08002018JDWP::JdwpError Dbg::SetFieldValue(JDWP::ObjectId object_id, JDWP::FieldId field_id, uint64_t value,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002019 int width) {
Elliott Hughes88d63092013-01-09 09:55:54 -08002020 return SetFieldValueImpl(object_id, field_id, value, width, false);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002021}
2022
Elliott Hughes88d63092013-01-09 09:55:54 -08002023JDWP::JdwpError Dbg::SetStaticFieldValue(JDWP::FieldId field_id, uint64_t value, int width) {
2024 return SetFieldValueImpl(0, field_id, value, width, true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002025}
2026
Sebastien Hertzb0b0b492014-09-15 11:27:27 +02002027JDWP::JdwpError Dbg::StringToUtf8(JDWP::ObjectId string_id, std::string* str) {
Ian Rogersc0542af2014-09-03 16:16:56 -07002028 JDWP::JdwpError error;
Vladimir Marko83114892019-04-11 13:05:50 +01002029 ObjPtr<mirror::Object> obj = gRegistry->Get<mirror::Object>(string_id, &error);
Sebastien Hertzb0b0b492014-09-15 11:27:27 +02002030 if (error != JDWP::ERR_NONE) {
2031 return error;
2032 }
2033 if (obj == nullptr) {
2034 return JDWP::ERR_INVALID_OBJECT;
2035 }
2036 {
2037 ScopedObjectAccessUnchecked soa(Thread::Current());
Mathieu Chartier0795f232016-09-27 18:43:30 -07002038 ObjPtr<mirror::Class> java_lang_String =
2039 soa.Decode<mirror::Class>(WellKnownClasses::java_lang_String);
Sebastien Hertzb0b0b492014-09-15 11:27:27 +02002040 if (!java_lang_String->IsAssignableFrom(obj->GetClass())) {
2041 // This isn't a string.
2042 return JDWP::ERR_INVALID_STRING;
2043 }
2044 }
2045 *str = obj->AsString()->ToModifiedUtf8();
2046 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002047}
2048
Jeff Hao579b0242013-11-18 13:16:49 -08002049void Dbg::OutputJValue(JDWP::JdwpTag tag, const JValue* return_value, JDWP::ExpandBuf* pReply) {
2050 if (IsPrimitiveTag(tag)) {
2051 expandBufAdd1(pReply, tag);
2052 if (tag == JDWP::JT_BOOLEAN || tag == JDWP::JT_BYTE) {
2053 expandBufAdd1(pReply, return_value->GetI());
2054 } else if (tag == JDWP::JT_CHAR || tag == JDWP::JT_SHORT) {
2055 expandBufAdd2BE(pReply, return_value->GetI());
2056 } else if (tag == JDWP::JT_FLOAT || tag == JDWP::JT_INT) {
2057 expandBufAdd4BE(pReply, return_value->GetI());
2058 } else if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
2059 expandBufAdd8BE(pReply, return_value->GetJ());
2060 } else {
2061 CHECK_EQ(tag, JDWP::JT_VOID);
2062 }
2063 } else {
Ian Rogers98379392014-02-24 16:53:16 -08002064 ScopedObjectAccessUnchecked soa(Thread::Current());
Vladimir Marko83114892019-04-11 13:05:50 +01002065 ObjPtr<mirror::Object> value = return_value->GetL();
Ian Rogers98379392014-02-24 16:53:16 -08002066 expandBufAdd1(pReply, TagFromObject(soa, value));
Jeff Hao579b0242013-11-18 13:16:49 -08002067 expandBufAddObjectId(pReply, gRegistry->Add(value));
2068 }
2069}
2070
Ian Rogersc0542af2014-09-03 16:16:56 -07002071JDWP::JdwpError Dbg::GetThreadName(JDWP::ObjectId thread_id, std::string* name) {
jeffhaoa77f0f62012-12-05 17:19:31 -08002072 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002073 JDWP::JdwpError error;
Roland Levillain4b8f1ec2015-08-26 18:34:03 +01002074 DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002075 if (error != JDWP::ERR_NONE && error != JDWP::ERR_THREAD_NOT_ALIVE) {
2076 return error;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08002077 }
Elliott Hughes221229c2013-01-08 18:17:50 -08002078
2079 // We still need to report the zombie threads' names, so we can't just call Thread::GetThreadName.
Vladimir Marko83114892019-04-11 13:05:50 +01002080 ObjPtr<mirror::Object> thread_object = gRegistry->Get<mirror::Object>(thread_id, &error);
Ian Rogersc0542af2014-09-03 16:16:56 -07002081 CHECK(thread_object != nullptr) << error;
Mathieu Chartierc7853442015-03-27 14:35:38 -07002082 ArtField* java_lang_Thread_name_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08002083 jni::DecodeArtField(WellKnownClasses::java_lang_Thread_name);
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07002084 ObjPtr<mirror::String> s(java_lang_Thread_name_field->GetObject(thread_object)->AsString());
Ian Rogersc0542af2014-09-03 16:16:56 -07002085 if (s != nullptr) {
2086 *name = s->ToModifiedUtf8();
Elliott Hughes221229c2013-01-08 18:17:50 -08002087 }
2088 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002089}
2090
Elliott Hughes221229c2013-01-08 18:17:50 -08002091JDWP::JdwpError Dbg::GetThreadGroup(JDWP::ObjectId thread_id, JDWP::ExpandBuf* pReply) {
Sebastien Hertza06430c2014-09-15 19:21:30 +02002092 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002093 JDWP::JdwpError error;
Vladimir Marko83114892019-04-11 13:05:50 +01002094 ObjPtr<mirror::Object> thread_object = gRegistry->Get<mirror::Object>(thread_id, &error);
Ian Rogersc0542af2014-09-03 16:16:56 -07002095 if (error != JDWP::ERR_NONE) {
Elliott Hughes2435a572012-02-17 16:07:41 -08002096 return JDWP::ERR_INVALID_OBJECT;
2097 }
Mathieu Chartier268764d2016-09-13 12:09:38 -07002098 ScopedAssertNoThreadSuspension ants("Debugger: GetThreadGroup");
Elliott Hughes2435a572012-02-17 16:07:41 -08002099 // Okay, so it's an object, but is it actually a thread?
Roland Levillain4b8f1ec2015-08-26 18:34:03 +01002100 DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002101 if (error == JDWP::ERR_THREAD_NOT_ALIVE) {
2102 // Zombie threads are in the null group.
2103 expandBufAddObjectId(pReply, JDWP::ObjectId(0));
Sebastien Hertz52d131d2014-03-13 16:17:40 +01002104 error = JDWP::ERR_NONE;
2105 } else if (error == JDWP::ERR_NONE) {
Mathieu Chartier0795f232016-09-27 18:43:30 -07002106 ObjPtr<mirror::Class> c = soa.Decode<mirror::Class>(WellKnownClasses::java_lang_Thread);
Sebastien Hertz52d131d2014-03-13 16:17:40 +01002107 CHECK(c != nullptr);
Andreas Gampe08883de2016-11-08 13:20:52 -08002108 ArtField* f = jni::DecodeArtField(WellKnownClasses::java_lang_Thread_group);
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07002109 CHECK(f != nullptr);
Mathieu Chartier3398c782016-09-30 10:27:43 -07002110 ObjPtr<mirror::Object> group = f->GetObject(thread_object);
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07002111 CHECK(group != nullptr);
Sebastien Hertz52d131d2014-03-13 16:17:40 +01002112 JDWP::ObjectId thread_group_id = gRegistry->Add(group);
2113 expandBufAddObjectId(pReply, thread_group_id);
Elliott Hughes221229c2013-01-08 18:17:50 -08002114 }
Sebastien Hertz52d131d2014-03-13 16:17:40 +01002115 return error;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002116}
2117
Vladimir Marko83114892019-04-11 13:05:50 +01002118static ObjPtr<mirror::Object> DecodeThreadGroup(ScopedObjectAccessUnchecked& soa,
2119 JDWP::ObjectId thread_group_id,
2120 JDWP::JdwpError* error)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002121 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko83114892019-04-11 13:05:50 +01002122 ObjPtr<mirror::Object> thread_group =
2123 Dbg::GetObjectRegistry()->Get<mirror::Object>(thread_group_id, error);
Sebastien Hertza06430c2014-09-15 19:21:30 +02002124 if (*error != JDWP::ERR_NONE) {
2125 return nullptr;
2126 }
2127 if (thread_group == nullptr) {
2128 *error = JDWP::ERR_INVALID_OBJECT;
2129 return nullptr;
2130 }
Mathieu Chartier0795f232016-09-27 18:43:30 -07002131 ObjPtr<mirror::Class> c =
2132 soa.Decode<mirror::Class>(WellKnownClasses::java_lang_ThreadGroup);
Ian Rogers98379392014-02-24 16:53:16 -08002133 CHECK(c != nullptr);
Sebastien Hertza06430c2014-09-15 19:21:30 +02002134 if (!c->IsAssignableFrom(thread_group->GetClass())) {
2135 // This is not a java.lang.ThreadGroup.
2136 *error = JDWP::ERR_INVALID_THREAD_GROUP;
2137 return nullptr;
2138 }
2139 *error = JDWP::ERR_NONE;
2140 return thread_group;
2141}
2142
2143JDWP::JdwpError Dbg::GetThreadGroupName(JDWP::ObjectId thread_group_id, JDWP::ExpandBuf* pReply) {
2144 ScopedObjectAccessUnchecked soa(Thread::Current());
2145 JDWP::JdwpError error;
Vladimir Marko83114892019-04-11 13:05:50 +01002146 ObjPtr<mirror::Object> thread_group = DecodeThreadGroup(soa, thread_group_id, &error);
Sebastien Hertza06430c2014-09-15 19:21:30 +02002147 if (error != JDWP::ERR_NONE) {
2148 return error;
2149 }
Mathieu Chartier268764d2016-09-13 12:09:38 -07002150 ScopedAssertNoThreadSuspension ants("Debugger: GetThreadGroupName");
Andreas Gampe08883de2016-11-08 13:20:52 -08002151 ArtField* f = jni::DecodeArtField(WellKnownClasses::java_lang_ThreadGroup_name);
Ian Rogersc0542af2014-09-03 16:16:56 -07002152 CHECK(f != nullptr);
Mathieu Chartier3398c782016-09-30 10:27:43 -07002153 ObjPtr<mirror::String> s = f->GetObject(thread_group)->AsString();
Sebastien Hertza06430c2014-09-15 19:21:30 +02002154
2155 std::string thread_group_name(s->ToModifiedUtf8());
2156 expandBufAddUtf8String(pReply, thread_group_name);
2157 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002158}
2159
Sebastien Hertza06430c2014-09-15 19:21:30 +02002160JDWP::JdwpError Dbg::GetThreadGroupParent(JDWP::ObjectId thread_group_id, JDWP::ExpandBuf* pReply) {
Ian Rogers98379392014-02-24 16:53:16 -08002161 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002162 JDWP::JdwpError error;
Vladimir Marko83114892019-04-11 13:05:50 +01002163 ObjPtr<mirror::Object> thread_group = DecodeThreadGroup(soa, thread_group_id, &error);
Sebastien Hertza06430c2014-09-15 19:21:30 +02002164 if (error != JDWP::ERR_NONE) {
2165 return error;
2166 }
Mathieu Chartier3398c782016-09-30 10:27:43 -07002167 ObjPtr<mirror::Object> parent;
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07002168 {
Mathieu Chartier268764d2016-09-13 12:09:38 -07002169 ScopedAssertNoThreadSuspension ants("Debugger: GetThreadGroupParent");
Andreas Gampe08883de2016-11-08 13:20:52 -08002170 ArtField* f = jni::DecodeArtField(WellKnownClasses::java_lang_ThreadGroup_parent);
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07002171 CHECK(f != nullptr);
2172 parent = f->GetObject(thread_group);
2173 }
Sebastien Hertza06430c2014-09-15 19:21:30 +02002174 JDWP::ObjectId parent_group_id = gRegistry->Add(parent);
2175 expandBufAddObjectId(pReply, parent_group_id);
2176 return JDWP::ERR_NONE;
2177}
2178
Vladimir Marko83114892019-04-11 13:05:50 +01002179static void GetChildThreadGroups(ObjPtr<mirror::Object> thread_group,
Sebastien Hertza06430c2014-09-15 19:21:30 +02002180 std::vector<JDWP::ObjectId>* child_thread_group_ids)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002181 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertza06430c2014-09-15 19:21:30 +02002182 CHECK(thread_group != nullptr);
2183
Przemyslaw Szczepaniak464595f2015-11-24 11:59:59 +00002184 // Get the int "ngroups" count of this thread group...
Andreas Gampe08883de2016-11-08 13:20:52 -08002185 ArtField* ngroups_field = jni::DecodeArtField(WellKnownClasses::java_lang_ThreadGroup_ngroups);
Przemyslaw Szczepaniak464595f2015-11-24 11:59:59 +00002186 CHECK(ngroups_field != nullptr);
2187 const int32_t size = ngroups_field->GetInt(thread_group);
2188 if (size == 0) {
2189 return;
Sebastien Hertze49e1952014-10-13 11:27:13 +02002190 }
Sebastien Hertza06430c2014-09-15 19:21:30 +02002191
Przemyslaw Szczepaniak464595f2015-11-24 11:59:59 +00002192 // Get the ThreadGroup[] "groups" out of this thread group...
Andreas Gampe08883de2016-11-08 13:20:52 -08002193 ArtField* groups_field = jni::DecodeArtField(WellKnownClasses::java_lang_ThreadGroup_groups);
Mathieu Chartier3398c782016-09-30 10:27:43 -07002194 ObjPtr<mirror::Object> groups_array = groups_field->GetObject(thread_group);
Przemyslaw Szczepaniak464595f2015-11-24 11:59:59 +00002195
2196 CHECK(groups_array != nullptr);
2197 CHECK(groups_array->IsObjectArray());
2198
Mathieu Chartier3398c782016-09-30 10:27:43 -07002199 ObjPtr<mirror::ObjectArray<mirror::Object>> groups_array_as_array =
Przemyslaw Szczepaniak464595f2015-11-24 11:59:59 +00002200 groups_array->AsObjectArray<mirror::Object>();
Sebastien Hertza06430c2014-09-15 19:21:30 +02002201
2202 // Copy the first 'size' elements out of the array into the result.
Sebastien Hertz6995c602014-09-09 12:10:13 +02002203 ObjectRegistry* registry = Dbg::GetObjectRegistry();
Sebastien Hertza06430c2014-09-15 19:21:30 +02002204 for (int32_t i = 0; i < size; ++i) {
Przemyslaw Szczepaniak464595f2015-11-24 11:59:59 +00002205 child_thread_group_ids->push_back(registry->Add(groups_array_as_array->Get(i)));
Sebastien Hertza06430c2014-09-15 19:21:30 +02002206 }
2207}
2208
2209JDWP::JdwpError Dbg::GetThreadGroupChildren(JDWP::ObjectId thread_group_id,
2210 JDWP::ExpandBuf* pReply) {
2211 ScopedObjectAccessUnchecked soa(Thread::Current());
2212 JDWP::JdwpError error;
Vladimir Marko83114892019-04-11 13:05:50 +01002213 ObjPtr<mirror::Object> thread_group = DecodeThreadGroup(soa, thread_group_id, &error);
Sebastien Hertza06430c2014-09-15 19:21:30 +02002214 if (error != JDWP::ERR_NONE) {
2215 return error;
2216 }
2217
2218 // Add child threads.
2219 {
2220 std::vector<JDWP::ObjectId> child_thread_ids;
2221 GetThreads(thread_group, &child_thread_ids);
2222 expandBufAdd4BE(pReply, child_thread_ids.size());
2223 for (JDWP::ObjectId child_thread_id : child_thread_ids) {
2224 expandBufAddObjectId(pReply, child_thread_id);
2225 }
2226 }
2227
2228 // Add child thread groups.
2229 {
2230 std::vector<JDWP::ObjectId> child_thread_groups_ids;
Andreas Gampe08883de2016-11-08 13:20:52 -08002231 GetChildThreadGroups(thread_group, &child_thread_groups_ids);
Sebastien Hertza06430c2014-09-15 19:21:30 +02002232 expandBufAdd4BE(pReply, child_thread_groups_ids.size());
2233 for (JDWP::ObjectId child_thread_group_id : child_thread_groups_ids) {
2234 expandBufAddObjectId(pReply, child_thread_group_id);
2235 }
2236 }
2237
2238 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002239}
2240
2241JDWP::ObjectId Dbg::GetSystemThreadGroupId() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002242 ScopedObjectAccessUnchecked soa(Thread::Current());
Andreas Gampe08883de2016-11-08 13:20:52 -08002243 ArtField* f = jni::DecodeArtField(WellKnownClasses::java_lang_ThreadGroup_systemThreadGroup);
Mathieu Chartier3398c782016-09-30 10:27:43 -07002244 ObjPtr<mirror::Object> group = f->GetObject(f->GetDeclaringClass());
Ian Rogers365c1022012-06-22 15:05:28 -07002245 return gRegistry->Add(group);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002246}
2247
Jeff Hao920af3e2013-08-28 15:46:38 -07002248JDWP::JdwpThreadStatus Dbg::ToJdwpThreadStatus(ThreadState state) {
2249 switch (state) {
2250 case kBlocked:
2251 return JDWP::TS_MONITOR;
2252 case kNative:
2253 case kRunnable:
2254 case kSuspended:
2255 return JDWP::TS_RUNNING;
2256 case kSleeping:
2257 return JDWP::TS_SLEEPING;
2258 case kStarting:
2259 case kTerminated:
2260 return JDWP::TS_ZOMBIE;
2261 case kTimedWaiting:
Alex Light77fee872017-09-05 14:51:49 -07002262 case kWaitingForTaskProcessor:
2263 case kWaitingForLockInflation:
Sebastien Hertzbae182c2013-12-17 10:42:03 +01002264 case kWaitingForCheckPointsToRun:
Jeff Hao920af3e2013-08-28 15:46:38 -07002265 case kWaitingForDebuggerSend:
2266 case kWaitingForDebuggerSuspension:
2267 case kWaitingForDebuggerToAttach:
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002268 case kWaitingForDeoptimization:
Jeff Hao920af3e2013-08-28 15:46:38 -07002269 case kWaitingForGcToComplete:
Mathieu Chartierb43390c2015-05-12 10:47:11 -07002270 case kWaitingForGetObjectsAllocated:
Jeff Hao920af3e2013-08-28 15:46:38 -07002271 case kWaitingForJniOnLoad:
Sebastien Hertzbae182c2013-12-17 10:42:03 +01002272 case kWaitingForMethodTracingStart:
Jeff Hao920af3e2013-08-28 15:46:38 -07002273 case kWaitingForSignalCatcherOutput:
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -08002274 case kWaitingForVisitObjects:
Jeff Hao920af3e2013-08-28 15:46:38 -07002275 case kWaitingInMainDebuggerLoop:
2276 case kWaitingInMainSignalCatcherLoop:
2277 case kWaitingPerformingGc:
Mathieu Chartier90ef3db2015-08-04 15:19:41 -07002278 case kWaitingWeakGcRootRead:
Hiroshi Yamauchi76f55b02015-08-21 16:10:39 -07002279 case kWaitingForGcThreadFlip:
Koji Fukui34857b52019-03-20 19:13:00 +09002280 case kNativeForAbort:
Jeff Hao920af3e2013-08-28 15:46:38 -07002281 case kWaiting:
2282 return JDWP::TS_WAIT;
2283 // Don't add a 'default' here so the compiler can spot incompatible enum changes.
2284 }
2285 LOG(FATAL) << "Unknown thread state: " << state;
Elliott Hughesc1896c92018-11-29 11:33:18 -08002286 UNREACHABLE();
Jeff Hao920af3e2013-08-28 15:46:38 -07002287}
2288
Sebastien Hertz52d131d2014-03-13 16:17:40 +01002289JDWP::JdwpError Dbg::GetThreadStatus(JDWP::ObjectId thread_id, JDWP::JdwpThreadStatus* pThreadStatus,
2290 JDWP::JdwpSuspendStatus* pSuspendStatus) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002291 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes499c5132011-11-17 14:55:11 -08002292
Elliott Hughes9e0c1752013-01-09 14:02:58 -08002293 *pSuspendStatus = JDWP::SUSPEND_STATUS_NOT_SUSPENDED;
2294
Ian Rogersc0542af2014-09-03 16:16:56 -07002295 JDWP::JdwpError error;
2296 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002297 if (error != JDWP::ERR_NONE) {
2298 if (error == JDWP::ERR_THREAD_NOT_ALIVE) {
2299 *pThreadStatus = JDWP::TS_ZOMBIE;
Elliott Hughes221229c2013-01-08 18:17:50 -08002300 return JDWP::ERR_NONE;
2301 }
2302 return error;
Elliott Hughes499c5132011-11-17 14:55:11 -08002303 }
2304
Elliott Hughes9e0c1752013-01-09 14:02:58 -08002305 if (IsSuspendedForDebugger(soa, thread)) {
2306 *pSuspendStatus = JDWP::SUSPEND_STATUS_SUSPENDED;
Elliott Hughes499c5132011-11-17 14:55:11 -08002307 }
2308
Jeff Hao920af3e2013-08-28 15:46:38 -07002309 *pThreadStatus = ToJdwpThreadStatus(thread->GetState());
Elliott Hughes221229c2013-01-08 18:17:50 -08002310 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002311}
2312
Elliott Hughes221229c2013-01-08 18:17:50 -08002313JDWP::JdwpError Dbg::GetThreadDebugSuspendCount(JDWP::ObjectId thread_id, JDWP::ExpandBuf* pReply) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002314 ScopedObjectAccess soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002315 JDWP::JdwpError error;
2316 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002317 if (error != JDWP::ERR_NONE) {
2318 return error;
Elliott Hughes2435a572012-02-17 16:07:41 -08002319 }
Ian Rogers50b35e22012-10-04 10:09:15 -07002320 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002321 expandBufAdd4BE(pReply, thread->GetDebugSuspendCount());
Elliott Hughes2435a572012-02-17 16:07:41 -08002322 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002323}
2324
Elliott Hughesf9501702013-01-11 11:22:27 -08002325JDWP::JdwpError Dbg::Interrupt(JDWP::ObjectId thread_id) {
2326 ScopedObjectAccess soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002327 JDWP::JdwpError error;
2328 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughesf9501702013-01-11 11:22:27 -08002329 if (error != JDWP::ERR_NONE) {
2330 return error;
2331 }
Ian Rogersdd7624d2014-03-14 17:43:00 -07002332 thread->Interrupt(soa.Self());
Elliott Hughesf9501702013-01-11 11:22:27 -08002333 return JDWP::ERR_NONE;
2334}
2335
Vladimir Marko83114892019-04-11 13:05:50 +01002336static bool IsInDesiredThreadGroup(ObjPtr<mirror::Object> desired_thread_group,
2337 ObjPtr<mirror::Object> peer)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002338 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz070f7322014-09-09 12:08:49 +02002339 // Do we want threads from all thread groups?
2340 if (desired_thread_group == nullptr) {
2341 return true;
2342 }
Andreas Gampe08883de2016-11-08 13:20:52 -08002343 ArtField* thread_group_field = jni::DecodeArtField(WellKnownClasses::java_lang_Thread_group);
Sebastien Hertz070f7322014-09-09 12:08:49 +02002344 DCHECK(thread_group_field != nullptr);
Mathieu Chartier3398c782016-09-30 10:27:43 -07002345 ObjPtr<mirror::Object> group = thread_group_field->GetObject(peer);
Sebastien Hertz070f7322014-09-09 12:08:49 +02002346 return (group == desired_thread_group);
2347}
2348
Vladimir Marko83114892019-04-11 13:05:50 +01002349void Dbg::GetThreads(ObjPtr<mirror::Object> thread_group, std::vector<JDWP::ObjectId>* thread_ids) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002350 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz070f7322014-09-09 12:08:49 +02002351 std::list<Thread*> all_threads_list;
2352 {
2353 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
2354 all_threads_list = Runtime::Current()->GetThreadList()->GetList();
2355 }
2356 for (Thread* t : all_threads_list) {
2357 if (t == Dbg::GetDebugThread()) {
2358 // Skip the JDWP thread. Some debuggers get bent out of shape when they can't suspend and
2359 // query all threads, so it's easier if we just don't tell them about this thread.
2360 continue;
2361 }
2362 if (t->IsStillStarting()) {
2363 // This thread is being started (and has been registered in the thread list). However, it is
2364 // not completely started yet so we must ignore it.
2365 continue;
2366 }
Vladimir Marko83114892019-04-11 13:05:50 +01002367 ObjPtr<mirror::Object> peer = t->GetPeerFromOtherThread();
Sebastien Hertz070f7322014-09-09 12:08:49 +02002368 if (peer == nullptr) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002369 // 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 +02002370 // this thread yet.
2371 // TODO: if we identified threads to the debugger by their Thread*
2372 // rather than their peer's mirror::Object*, we could fix this.
2373 // Doing so might help us report ZOMBIE threads too.
2374 continue;
2375 }
Andreas Gampe08883de2016-11-08 13:20:52 -08002376 if (IsInDesiredThreadGroup(thread_group, peer)) {
Sebastien Hertz070f7322014-09-09 12:08:49 +02002377 thread_ids->push_back(gRegistry->Add(peer));
2378 }
2379 }
Elliott Hughescaf76542012-06-28 16:08:22 -07002380}
Elliott Hughesa2155262011-11-16 16:26:58 -08002381
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002382static int GetStackDepth(Thread* thread) REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampec7d878d2018-11-19 18:42:06 +00002383 size_t depth = 0u;
2384 StackVisitor::WalkStack(
2385 [&depth](const StackVisitor* visitor) REQUIRES_SHARED(Locks::mutator_lock_) {
2386 if (!visitor->GetMethod()->IsRuntimeMethod()) {
2387 ++depth;
2388 }
2389 return true;
2390 },
2391 thread,
2392 /* context= */ nullptr,
2393 StackVisitor::StackWalkKind::kIncludeInlinedFrames);
2394 return depth;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002395}
2396
Ian Rogersc0542af2014-09-03 16:16:56 -07002397JDWP::JdwpError Dbg::GetThreadFrameCount(JDWP::ObjectId thread_id, size_t* result) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002398 ScopedObjectAccess soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002399 JDWP::JdwpError error;
2400 *result = 0;
2401 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002402 if (error != JDWP::ERR_NONE) {
2403 return error;
2404 }
Elliott Hughesf15f4a02013-01-09 10:09:38 -08002405 if (!IsSuspendedForDebugger(soa, thread)) {
2406 return JDWP::ERR_THREAD_NOT_SUSPENDED;
2407 }
Ian Rogersc0542af2014-09-03 16:16:56 -07002408 *result = GetStackDepth(thread);
Elliott Hughes221229c2013-01-08 18:17:50 -08002409 return JDWP::ERR_NONE;
Elliott Hughes86964332012-02-15 19:37:42 -08002410}
2411
Andreas Gampec7d878d2018-11-19 18:42:06 +00002412JDWP::JdwpError Dbg::GetThreadFrames(JDWP::ObjectId thread_id,
2413 const size_t start_frame,
2414 const size_t frame_count,
2415 JDWP::ExpandBuf* buf) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002416 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002417 JDWP::JdwpError error;
2418 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002419 if (error != JDWP::ERR_NONE) {
2420 return error;
2421 }
Elliott Hughesf15f4a02013-01-09 10:09:38 -08002422 if (!IsSuspendedForDebugger(soa, thread)) {
2423 return JDWP::ERR_THREAD_NOT_SUSPENDED;
2424 }
Andreas Gampec7d878d2018-11-19 18:42:06 +00002425
2426 expandBufAdd4BE(buf, frame_count);
2427
2428 size_t depth = 0u;
2429 StackVisitor::WalkStack(
2430 [&](StackVisitor* visitor) REQUIRES_SHARED(Locks::mutator_lock_) {
2431 if (visitor->GetMethod()->IsRuntimeMethod()) {
2432 return true; // The debugger can't do anything useful with a frame that has no Method*.
2433 }
2434 if (depth >= start_frame + frame_count) {
2435 return false;
2436 }
2437 if (depth >= start_frame) {
2438 JDWP::FrameId frame_id(visitor->GetFrameId());
2439 JDWP::JdwpLocation location;
2440 SetJdwpLocation(&location, visitor->GetMethod(), visitor->GetDexPc());
2441 VLOG(jdwp)
2442 << StringPrintf(" Frame %3zd: id=%3" PRIu64 " ", depth, frame_id) << location;
2443 expandBufAdd8BE(buf, frame_id);
2444 expandBufAddLocation(buf, location);
2445 }
2446 ++depth;
2447 return true;
2448 },
2449 thread,
2450 /* context= */ nullptr,
2451 StackVisitor::StackWalkKind::kIncludeInlinedFrames);
2452
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002453 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002454}
2455
2456JDWP::ObjectId Dbg::GetThreadSelfId() {
Sebastien Hertz6995c602014-09-09 12:10:13 +02002457 return GetThreadId(Thread::Current());
2458}
2459
2460JDWP::ObjectId Dbg::GetThreadId(Thread* thread) {
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07002461 ScopedObjectAccessUnchecked soa(Thread::Current());
Nicolas Geoffraycafa0812017-02-15 18:27:34 +00002462 return gRegistry->Add(thread->GetPeerFromOtherThread());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002463}
2464
Elliott Hughes475fc232011-10-25 15:00:35 -07002465void Dbg::SuspendVM() {
Hiroshi Yamauchi8f95cf32016-04-19 11:14:06 -07002466 // Avoid a deadlock between GC and debugger where GC gets suspended during GC. b/25800335.
2467 gc::ScopedGCCriticalSection gcs(Thread::Current(),
2468 gc::kGcCauseDebugger,
2469 gc::kCollectorTypeDebugger);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002470 Runtime::Current()->GetThreadList()->SuspendAllForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002471}
2472
2473void Dbg::ResumeVM() {
Sebastien Hertz253fa552014-10-14 17:27:15 +02002474 Runtime::Current()->GetThreadList()->ResumeAllForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002475}
2476
Elliott Hughes221229c2013-01-08 18:17:50 -08002477JDWP::JdwpError Dbg::SuspendThread(JDWP::ObjectId thread_id, bool request_suspension) {
Ian Rogersf3d874c2014-07-17 18:52:42 -07002478 Thread* self = Thread::Current();
Ian Rogersc0542af2014-09-03 16:16:56 -07002479 ScopedLocalRef<jobject> peer(self->GetJniEnv(), nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002480 {
Ian Rogersf3d874c2014-07-17 18:52:42 -07002481 ScopedObjectAccess soa(self);
Ian Rogersc0542af2014-09-03 16:16:56 -07002482 JDWP::JdwpError error;
Vladimir Marko83114892019-04-11 13:05:50 +01002483 peer.reset(soa.AddLocalReference<jobject>(gRegistry->Get<mirror::Object>(thread_id, &error)));
Elliott Hughes4e235312011-12-02 11:34:15 -08002484 }
Ian Rogersc0542af2014-09-03 16:16:56 -07002485 if (peer.get() == nullptr) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002486 return JDWP::ERR_THREAD_NOT_ALIVE;
2487 }
Ian Rogers4ad5cd32014-11-11 23:08:07 -08002488 // Suspend thread to build stack trace.
Elliott Hughesf327e072013-01-09 16:01:26 -08002489 bool timed_out;
Brian Carlstromba32de42014-08-27 23:43:46 -07002490 ThreadList* thread_list = Runtime::Current()->GetThreadList();
Sebastien Hertzcdd798d2017-04-18 18:28:51 +02002491 Thread* thread = thread_list->SuspendThreadByPeer(peer.get(),
2492 request_suspension,
Alex Light46f93402017-06-29 11:59:50 -07002493 SuspendReason::kForDebugger,
Brian Carlstromba32de42014-08-27 23:43:46 -07002494 &timed_out);
Ian Rogersc0542af2014-09-03 16:16:56 -07002495 if (thread != nullptr) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002496 return JDWP::ERR_NONE;
Elliott Hughesf327e072013-01-09 16:01:26 -08002497 } else if (timed_out) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002498 return JDWP::ERR_INTERNAL;
2499 } else {
2500 return JDWP::ERR_THREAD_NOT_ALIVE;
2501 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002502}
2503
Elliott Hughes221229c2013-01-08 18:17:50 -08002504void Dbg::ResumeThread(JDWP::ObjectId thread_id) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002505 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002506 JDWP::JdwpError error;
Vladimir Marko83114892019-04-11 13:05:50 +01002507 ObjPtr<mirror::Object> peer = gRegistry->Get<mirror::Object>(thread_id, &error);
Ian Rogersc0542af2014-09-03 16:16:56 -07002508 CHECK(peer != nullptr) << error;
jeffhaoa77f0f62012-12-05 17:19:31 -08002509 Thread* thread;
2510 {
2511 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
2512 thread = Thread::FromManagedThread(soa, peer);
2513 }
Ian Rogersc0542af2014-09-03 16:16:56 -07002514 if (thread == nullptr) {
Elliott Hughes4e235312011-12-02 11:34:15 -08002515 LOG(WARNING) << "No such thread for resume: " << peer;
2516 return;
2517 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002518 bool needs_resume;
2519 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002520 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Sebastien Hertz70d60272017-04-14 14:18:36 +02002521 needs_resume = thread->GetDebugSuspendCount() > 0;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002522 }
2523 if (needs_resume) {
Alex Light88fd7202017-06-30 08:31:59 -07002524 bool resumed = Runtime::Current()->GetThreadList()->Resume(thread, SuspendReason::kForDebugger);
2525 DCHECK(resumed);
Elliott Hughes546b9862012-06-20 16:06:13 -07002526 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002527}
2528
2529void Dbg::SuspendSelf() {
Elliott Hughes475fc232011-10-25 15:00:35 -07002530 Runtime::Current()->GetThreadList()->SuspendSelfForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002531}
2532
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002533JDWP::JdwpError Dbg::GetThisObject(JDWP::ObjectId thread_id, JDWP::FrameId frame_id,
2534 JDWP::ObjectId* result) {
2535 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz69206392015-04-07 15:54:25 +02002536 JDWP::JdwpError error;
2537 Thread* thread = DecodeThread(soa, thread_id, &error);
2538 if (error != JDWP::ERR_NONE) {
2539 return error;
2540 }
2541 if (!IsSuspendedForDebugger(soa, thread)) {
2542 return JDWP::ERR_THREAD_NOT_SUSPENDED;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002543 }
Ian Rogers700a4022014-05-19 16:49:03 -07002544 std::unique_ptr<Context> context(Context::Create());
Vladimir Marko83114892019-04-11 13:05:50 +01002545 ObjPtr<mirror::Object> this_object = nullptr;
Andreas Gampec7d878d2018-11-19 18:42:06 +00002546 StackVisitor::WalkStack(
2547 [&](art::StackVisitor* stack_visitor) REQUIRES_SHARED(Locks::mutator_lock_) {
2548 if (frame_id != stack_visitor->GetFrameId()) {
2549 return true; // continue
2550 } else {
2551 this_object = stack_visitor->GetThisObject();
2552 return false;
2553 }
2554 },
2555 thread,
2556 context.get(),
2557 art::StackVisitor::StackWalkKind::kIncludeInlinedFrames);
2558 *result = gRegistry->Add(this_object);
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002559 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002560}
2561
Andreas Gampec7d878d2018-11-19 18:42:06 +00002562template <typename FrameHandler>
2563static JDWP::JdwpError FindAndHandleNonNativeFrame(Thread* thread,
2564 JDWP::FrameId frame_id,
2565 const FrameHandler& handler)
2566 REQUIRES_SHARED(Locks::mutator_lock_) {
2567 JDWP::JdwpError result = JDWP::ERR_INVALID_FRAMEID;
2568 std::unique_ptr<Context> context(Context::Create());
2569 StackVisitor::WalkStack(
2570 [&](art::StackVisitor* stack_visitor) REQUIRES_SHARED(Locks::mutator_lock_) {
2571 if (stack_visitor->GetFrameId() != frame_id) {
2572 return true; // Not our frame, carry on.
2573 }
2574 ArtMethod* m = stack_visitor->GetMethod();
2575 if (m->IsNative()) {
2576 // We can't read/write local value from/into native method.
2577 result = JDWP::ERR_OPAQUE_FRAME;
2578 } else {
2579 // We found our frame.
2580 result = handler(stack_visitor);
2581 }
2582 return false;
2583 },
2584 thread,
2585 context.get(),
2586 art::StackVisitor::StackWalkKind::kIncludeInlinedFrames);
2587 return result;
2588}
Sebastien Hertz8009f392014-09-01 17:07:11 +02002589
2590JDWP::JdwpError Dbg::GetLocalValues(JDWP::Request* request, JDWP::ExpandBuf* pReply) {
2591 JDWP::ObjectId thread_id = request->ReadThreadId();
2592 JDWP::FrameId frame_id = request->ReadFrameId();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002593
2594 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz69206392015-04-07 15:54:25 +02002595 JDWP::JdwpError error;
2596 Thread* thread = DecodeThread(soa, thread_id, &error);
2597 if (error != JDWP::ERR_NONE) {
2598 return error;
2599 }
2600 if (!IsSuspendedForDebugger(soa, thread)) {
2601 return JDWP::ERR_THREAD_NOT_SUSPENDED;
Elliott Hughes221229c2013-01-08 18:17:50 -08002602 }
Sebastien Hertz8009f392014-09-01 17:07:11 +02002603
Andreas Gampec7d878d2018-11-19 18:42:06 +00002604 return FindAndHandleNonNativeFrame(
2605 thread,
2606 frame_id,
2607 [&](art::StackVisitor* stack_visitor) REQUIRES_SHARED(Locks::mutator_lock_) {
2608 // Read the values from visitor's context.
2609 int32_t slot_count = request->ReadSigned32("slot count");
2610 expandBufAdd4BE(pReply, slot_count); /* "int values" */
2611 for (int32_t i = 0; i < slot_count; ++i) {
2612 uint32_t slot = request->ReadUnsigned32("slot");
2613 JDWP::JdwpTag reqSigByte = request->ReadTag();
Sebastien Hertz8009f392014-09-01 17:07:11 +02002614
Andreas Gampec7d878d2018-11-19 18:42:06 +00002615 VLOG(jdwp) << " --> slot " << slot << " " << reqSigByte;
Sebastien Hertz8009f392014-09-01 17:07:11 +02002616
Andreas Gampec7d878d2018-11-19 18:42:06 +00002617 size_t width = Dbg::GetTagWidth(reqSigByte);
2618 uint8_t* ptr = expandBufAddSpace(pReply, width + 1);
2619 error = Dbg::GetLocalValue(*stack_visitor, soa, slot, reqSigByte, ptr, width);
2620 if (error != JDWP::ERR_NONE) {
2621 return error;
2622 }
2623 }
2624 return JDWP::ERR_NONE;
2625 });
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002626}
2627
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002628constexpr JDWP::JdwpError kStackFrameLocalAccessError = JDWP::ERR_ABSENT_INFORMATION;
2629
2630static std::string GetStackContextAsString(const StackVisitor& visitor)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002631 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002632 return StringPrintf(" at DEX pc 0x%08x in method %s", visitor.GetDexPc(false),
David Sehr709b0702016-10-13 09:12:37 -07002633 ArtMethod::PrettyMethod(visitor.GetMethod()).c_str());
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002634}
2635
2636static JDWP::JdwpError FailGetLocalValue(const StackVisitor& visitor, uint16_t vreg,
2637 JDWP::JdwpTag tag)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002638 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002639 LOG(ERROR) << "Failed to read " << tag << " local from register v" << vreg
2640 << GetStackContextAsString(visitor);
2641 return kStackFrameLocalAccessError;
2642}
2643
Sebastien Hertz8009f392014-09-01 17:07:11 +02002644JDWP::JdwpError Dbg::GetLocalValue(const StackVisitor& visitor, ScopedObjectAccessUnchecked& soa,
2645 int slot, JDWP::JdwpTag tag, uint8_t* buf, size_t width) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002646 ArtMethod* m = visitor.GetMethod();
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002647 JDWP::JdwpError error = JDWP::ERR_NONE;
2648 uint16_t vreg = DemangleSlot(slot, m, &error);
2649 if (error != JDWP::ERR_NONE) {
2650 return error;
2651 }
Sebastien Hertz8009f392014-09-01 17:07:11 +02002652 // TODO: check that the tag is compatible with the actual type of the slot!
Sebastien Hertz8009f392014-09-01 17:07:11 +02002653 switch (tag) {
2654 case JDWP::JT_BOOLEAN: {
2655 CHECK_EQ(width, 1U);
2656 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002657 if (!visitor.GetVReg(m, vreg, kIntVReg, &intVal)) {
2658 return FailGetLocalValue(visitor, vreg, tag);
Ian Rogers0399dde2012-06-06 17:09:28 -07002659 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002660 VLOG(jdwp) << "get boolean local " << vreg << " = " << intVal;
2661 JDWP::Set1(buf + 1, intVal != 0);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002662 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002663 }
Sebastien Hertz8009f392014-09-01 17:07:11 +02002664 case JDWP::JT_BYTE: {
2665 CHECK_EQ(width, 1U);
2666 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002667 if (!visitor.GetVReg(m, vreg, kIntVReg, &intVal)) {
2668 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002669 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002670 VLOG(jdwp) << "get byte local " << vreg << " = " << intVal;
2671 JDWP::Set1(buf + 1, intVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002672 break;
2673 }
2674 case JDWP::JT_SHORT:
2675 case JDWP::JT_CHAR: {
2676 CHECK_EQ(width, 2U);
2677 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002678 if (!visitor.GetVReg(m, vreg, kIntVReg, &intVal)) {
2679 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002680 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002681 VLOG(jdwp) << "get short/char local " << vreg << " = " << intVal;
2682 JDWP::Set2BE(buf + 1, intVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002683 break;
2684 }
2685 case JDWP::JT_INT: {
2686 CHECK_EQ(width, 4U);
2687 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002688 if (!visitor.GetVReg(m, vreg, kIntVReg, &intVal)) {
2689 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002690 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002691 VLOG(jdwp) << "get int local " << vreg << " = " << intVal;
2692 JDWP::Set4BE(buf + 1, intVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002693 break;
2694 }
2695 case JDWP::JT_FLOAT: {
2696 CHECK_EQ(width, 4U);
2697 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002698 if (!visitor.GetVReg(m, vreg, kFloatVReg, &intVal)) {
2699 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002700 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002701 VLOG(jdwp) << "get float local " << vreg << " = " << intVal;
2702 JDWP::Set4BE(buf + 1, intVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002703 break;
2704 }
2705 case JDWP::JT_ARRAY:
2706 case JDWP::JT_CLASS_LOADER:
2707 case JDWP::JT_CLASS_OBJECT:
2708 case JDWP::JT_OBJECT:
2709 case JDWP::JT_STRING:
2710 case JDWP::JT_THREAD:
2711 case JDWP::JT_THREAD_GROUP: {
2712 CHECK_EQ(width, sizeof(JDWP::ObjectId));
2713 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002714 if (!visitor.GetVReg(m, vreg, kReferenceVReg, &intVal)) {
2715 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002716 }
Vladimir Marko83114892019-04-11 13:05:50 +01002717 ObjPtr<mirror::Object> o = reinterpret_cast<mirror::Object*>(intVal);
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002718 VLOG(jdwp) << "get " << tag << " object local " << vreg << " = " << o;
Vladimir Marko83114892019-04-11 13:05:50 +01002719 if (!Runtime::Current()->GetHeap()->IsValidObjectAddress(o.Ptr())) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002720 LOG(FATAL) << StringPrintf("Found invalid object %#" PRIxPTR " in register v%u",
Vladimir Marko83114892019-04-11 13:05:50 +01002721 reinterpret_cast<uintptr_t>(o.Ptr()), vreg)
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002722 << GetStackContextAsString(visitor);
2723 UNREACHABLE();
2724 }
2725 tag = TagFromObject(soa, o);
2726 JDWP::SetObjectId(buf + 1, gRegistry->Add(o));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002727 break;
2728 }
2729 case JDWP::JT_DOUBLE: {
2730 CHECK_EQ(width, 8U);
2731 uint64_t longVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002732 if (!visitor.GetVRegPair(m, vreg, kDoubleLoVReg, kDoubleHiVReg, &longVal)) {
2733 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002734 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002735 VLOG(jdwp) << "get double local " << vreg << " = " << longVal;
2736 JDWP::Set8BE(buf + 1, longVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002737 break;
2738 }
2739 case JDWP::JT_LONG: {
2740 CHECK_EQ(width, 8U);
2741 uint64_t longVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002742 if (!visitor.GetVRegPair(m, vreg, kLongLoVReg, kLongHiVReg, &longVal)) {
2743 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002744 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002745 VLOG(jdwp) << "get long local " << vreg << " = " << longVal;
2746 JDWP::Set8BE(buf + 1, longVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002747 break;
2748 }
2749 default:
2750 LOG(FATAL) << "Unknown tag " << tag;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002751 UNREACHABLE();
Sebastien Hertz8009f392014-09-01 17:07:11 +02002752 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002753
Sebastien Hertz8009f392014-09-01 17:07:11 +02002754 // Prepend tag, which may have been updated.
2755 JDWP::Set1(buf, tag);
2756 return JDWP::ERR_NONE;
2757}
2758
2759JDWP::JdwpError Dbg::SetLocalValues(JDWP::Request* request) {
2760 JDWP::ObjectId thread_id = request->ReadThreadId();
2761 JDWP::FrameId frame_id = request->ReadFrameId();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002762
2763 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz69206392015-04-07 15:54:25 +02002764 JDWP::JdwpError error;
2765 Thread* thread = DecodeThread(soa, thread_id, &error);
2766 if (error != JDWP::ERR_NONE) {
2767 return error;
2768 }
2769 if (!IsSuspendedForDebugger(soa, thread)) {
2770 return JDWP::ERR_THREAD_NOT_SUSPENDED;
Elliott Hughes221229c2013-01-08 18:17:50 -08002771 }
Sebastien Hertz8009f392014-09-01 17:07:11 +02002772
Andreas Gampec7d878d2018-11-19 18:42:06 +00002773 return FindAndHandleNonNativeFrame(
2774 thread,
2775 frame_id,
2776 [&](art::StackVisitor* stack_visitor) REQUIRES_SHARED(Locks::mutator_lock_) {
2777 // Writes the values into visitor's context.
2778 int32_t slot_count = request->ReadSigned32("slot count");
2779 for (int32_t i = 0; i < slot_count; ++i) {
2780 uint32_t slot = request->ReadUnsigned32("slot");
2781 JDWP::JdwpTag sigByte = request->ReadTag();
2782 size_t width = Dbg::GetTagWidth(sigByte);
2783 uint64_t value = request->ReadValue(width);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002784
Andreas Gampec7d878d2018-11-19 18:42:06 +00002785 VLOG(jdwp) << " --> slot " << slot << " " << sigByte << " " << value;
2786 error = Dbg::SetLocalValue(thread, *stack_visitor, slot, sigByte, value, width);
2787 if (error != JDWP::ERR_NONE) {
2788 return error;
2789 }
2790 }
2791 return JDWP::ERR_NONE;
2792 });
Sebastien Hertz8009f392014-09-01 17:07:11 +02002793}
2794
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002795template<typename T>
2796static JDWP::JdwpError FailSetLocalValue(const StackVisitor& visitor, uint16_t vreg,
2797 JDWP::JdwpTag tag, T value)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002798 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002799 LOG(ERROR) << "Failed to write " << tag << " local " << value
2800 << " (0x" << std::hex << value << ") into register v" << vreg
2801 << GetStackContextAsString(visitor);
2802 return kStackFrameLocalAccessError;
2803}
2804
Mingyao Yang99170c62015-07-06 11:10:37 -07002805JDWP::JdwpError Dbg::SetLocalValue(Thread* thread, StackVisitor& visitor, int slot,
2806 JDWP::JdwpTag tag, uint64_t value, size_t width) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002807 ArtMethod* m = visitor.GetMethod();
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002808 JDWP::JdwpError error = JDWP::ERR_NONE;
2809 uint16_t vreg = DemangleSlot(slot, m, &error);
2810 if (error != JDWP::ERR_NONE) {
2811 return error;
2812 }
Sebastien Hertz8009f392014-09-01 17:07:11 +02002813 // TODO: check that the tag is compatible with the actual type of the slot!
Sebastien Hertz8009f392014-09-01 17:07:11 +02002814 switch (tag) {
2815 case JDWP::JT_BOOLEAN:
2816 case JDWP::JT_BYTE:
2817 CHECK_EQ(width, 1U);
Mingyao Yang636b9252015-07-31 16:40:24 -07002818 if (!visitor.SetVReg(m, vreg, static_cast<uint32_t>(value), kIntVReg)) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002819 return FailSetLocalValue(visitor, vreg, tag, static_cast<uint32_t>(value));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002820 }
2821 break;
2822 case JDWP::JT_SHORT:
2823 case JDWP::JT_CHAR:
2824 CHECK_EQ(width, 2U);
Mingyao Yang636b9252015-07-31 16:40:24 -07002825 if (!visitor.SetVReg(m, vreg, static_cast<uint32_t>(value), kIntVReg)) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002826 return FailSetLocalValue(visitor, vreg, tag, static_cast<uint32_t>(value));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002827 }
2828 break;
2829 case JDWP::JT_INT:
2830 CHECK_EQ(width, 4U);
Mingyao Yang636b9252015-07-31 16:40:24 -07002831 if (!visitor.SetVReg(m, vreg, static_cast<uint32_t>(value), kIntVReg)) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002832 return FailSetLocalValue(visitor, vreg, tag, static_cast<uint32_t>(value));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002833 }
2834 break;
2835 case JDWP::JT_FLOAT:
2836 CHECK_EQ(width, 4U);
Mingyao Yang636b9252015-07-31 16:40:24 -07002837 if (!visitor.SetVReg(m, vreg, static_cast<uint32_t>(value), kFloatVReg)) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002838 return FailSetLocalValue(visitor, vreg, tag, static_cast<uint32_t>(value));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002839 }
2840 break;
2841 case JDWP::JT_ARRAY:
2842 case JDWP::JT_CLASS_LOADER:
2843 case JDWP::JT_CLASS_OBJECT:
2844 case JDWP::JT_OBJECT:
2845 case JDWP::JT_STRING:
2846 case JDWP::JT_THREAD:
2847 case JDWP::JT_THREAD_GROUP: {
2848 CHECK_EQ(width, sizeof(JDWP::ObjectId));
Vladimir Marko83114892019-04-11 13:05:50 +01002849 ObjPtr<mirror::Object> o =
2850 gRegistry->Get<mirror::Object>(static_cast<JDWP::ObjectId>(value), &error);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002851 if (error != JDWP::ERR_NONE) {
2852 VLOG(jdwp) << tag << " object " << o << " is an invalid object";
2853 return JDWP::ERR_INVALID_OBJECT;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002854 }
Vladimir Marko439d1262019-04-12 14:45:07 +01002855 if (!visitor.SetVRegReference(m, vreg, o)) {
Vladimir Marko83114892019-04-11 13:05:50 +01002856 return FailSetLocalValue(visitor, vreg, tag, reinterpret_cast<uintptr_t>(o.Ptr()));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002857 }
2858 break;
2859 }
2860 case JDWP::JT_DOUBLE: {
2861 CHECK_EQ(width, 8U);
Mingyao Yang636b9252015-07-31 16:40:24 -07002862 if (!visitor.SetVRegPair(m, vreg, value, kDoubleLoVReg, kDoubleHiVReg)) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002863 return FailSetLocalValue(visitor, vreg, tag, value);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002864 }
2865 break;
2866 }
2867 case JDWP::JT_LONG: {
2868 CHECK_EQ(width, 8U);
Mingyao Yang636b9252015-07-31 16:40:24 -07002869 if (!visitor.SetVRegPair(m, vreg, value, kLongLoVReg, kLongHiVReg)) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002870 return FailSetLocalValue(visitor, vreg, tag, value);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002871 }
2872 break;
2873 }
2874 default:
2875 LOG(FATAL) << "Unknown tag " << tag;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002876 UNREACHABLE();
Sebastien Hertz8009f392014-09-01 17:07:11 +02002877 }
Mingyao Yang99170c62015-07-06 11:10:37 -07002878
2879 // If we set the local variable in a compiled frame, we need to trigger a deoptimization of
2880 // the stack so we continue execution with the interpreter using the new value(s) of the updated
2881 // local variable(s). To achieve this, we install instrumentation exit stub on each method of the
2882 // thread's stack. The stub will cause the deoptimization to happen.
2883 if (!visitor.IsShadowFrame() && thread->HasDebuggerShadowFrames()) {
2884 Runtime::Current()->GetInstrumentation()->InstrumentThreadStack(thread);
2885 }
2886
Sebastien Hertz8009f392014-09-01 17:07:11 +02002887 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002888}
2889
Mathieu Chartiere401d142015-04-22 13:56:20 -07002890static void SetEventLocation(JDWP::EventLocation* location, ArtMethod* m, uint32_t dex_pc)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002891 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz6995c602014-09-09 12:10:13 +02002892 DCHECK(location != nullptr);
2893 if (m == nullptr) {
2894 memset(location, 0, sizeof(*location));
2895 } else {
Alex Light97e78032017-06-27 17:51:55 -07002896 location->method = m->GetCanonicalMethod(kRuntimePointerSize);
Sebastien Hertz6995c602014-09-09 12:10:13 +02002897 location->dex_pc = (m->IsNative() || m->IsProxyMethod()) ? static_cast<uint32_t>(-1) : dex_pc;
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002898 }
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002899}
2900
Vladimir Marko83114892019-04-11 13:05:50 +01002901void Dbg::PostLocationEvent(ArtMethod* m,
2902 int dex_pc,
2903 ObjPtr<mirror::Object> this_object,
2904 int event_flags,
2905 const JValue* return_value) {
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002906 if (!IsDebuggerActive()) {
2907 return;
2908 }
2909 DCHECK(m != nullptr);
2910 DCHECK_EQ(m->IsStatic(), this_object == nullptr);
Sebastien Hertz6995c602014-09-09 12:10:13 +02002911 JDWP::EventLocation location;
2912 SetEventLocation(&location, m, dex_pc);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002913
Sebastien Hertzde48aa62015-05-26 11:53:39 +02002914 // We need to be sure no exception is pending when calling JdwpState::PostLocationEvent.
2915 // This is required to be able to call JNI functions to create JDWP ids. To achieve this,
2916 // we temporarily clear the current thread's exception (if any) and will restore it after
2917 // the call.
2918 // Note: the only way to get a pending exception here is to suspend on a move-exception
2919 // instruction.
2920 Thread* const self = Thread::Current();
2921 StackHandleScope<1> hs(self);
2922 Handle<mirror::Throwable> pending_exception(hs.NewHandle(self->GetException()));
2923 self->ClearException();
Andreas Gampefa4333d2017-02-14 11:10:34 -08002924 if (kIsDebugBuild && pending_exception != nullptr) {
Mathieu Chartier808c7a52017-12-15 11:19:33 -08002925 const Instruction& instr = location.method->DexInstructions().InstructionAt(location.dex_pc);
2926 CHECK_EQ(Instruction::MOVE_EXCEPTION, instr.Opcode());
Sebastien Hertzde48aa62015-05-26 11:53:39 +02002927 }
2928
Sebastien Hertz6995c602014-09-09 12:10:13 +02002929 gJdwpState->PostLocationEvent(&location, this_object, event_flags, return_value);
Sebastien Hertzde48aa62015-05-26 11:53:39 +02002930
Andreas Gampefa4333d2017-02-14 11:10:34 -08002931 if (pending_exception != nullptr) {
Sebastien Hertzde48aa62015-05-26 11:53:39 +02002932 self->SetException(pending_exception.Get());
2933 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002934}
2935
Vladimir Marko83114892019-04-11 13:05:50 +01002936void Dbg::PostFieldAccessEvent(ArtMethod* m,
2937 int dex_pc,
2938 ObjPtr<mirror::Object> this_object,
2939 ArtField* f) {
Alex Lighte00ec302017-06-16 08:56:43 -07002940 // TODO We should send events for native methods.
2941 if (!IsDebuggerActive() || m->IsNative()) {
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002942 return;
2943 }
2944 DCHECK(m != nullptr);
2945 DCHECK(f != nullptr);
Sebastien Hertz6995c602014-09-09 12:10:13 +02002946 JDWP::EventLocation location;
2947 SetEventLocation(&location, m, dex_pc);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002948
Sebastien Hertz6995c602014-09-09 12:10:13 +02002949 gJdwpState->PostFieldEvent(&location, f, this_object, nullptr, false);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002950}
2951
Vladimir Marko83114892019-04-11 13:05:50 +01002952void Dbg::PostFieldModificationEvent(ArtMethod* m,
2953 int dex_pc,
2954 ObjPtr<mirror::Object> this_object,
2955 ArtField* f,
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002956 const JValue* field_value) {
Alex Lighte00ec302017-06-16 08:56:43 -07002957 // TODO We should send events for native methods.
2958 if (!IsDebuggerActive() || m->IsNative()) {
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002959 return;
2960 }
2961 DCHECK(m != nullptr);
2962 DCHECK(f != nullptr);
2963 DCHECK(field_value != nullptr);
Sebastien Hertz6995c602014-09-09 12:10:13 +02002964 JDWP::EventLocation location;
2965 SetEventLocation(&location, m, dex_pc);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002966
Sebastien Hertz6995c602014-09-09 12:10:13 +02002967 gJdwpState->PostFieldEvent(&location, f, this_object, field_value, true);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002968}
2969
Vladimir Marko83114892019-04-11 13:05:50 +01002970void Dbg::PostException(ObjPtr<mirror::Throwable> exception_object) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002971 if (!IsDebuggerActive()) {
Ian Rogers0ad5bb82011-12-07 10:16:32 -08002972 return;
2973 }
Sebastien Hertz261bc042015-04-08 09:36:07 +02002974 Thread* const self = Thread::Current();
Andreas Gampec7d878d2018-11-19 18:42:06 +00002975 StackHandleScope<2> handle_scope(self);
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002976 Handle<mirror::Throwable> h_exception(handle_scope.NewHandle(exception_object));
Andreas Gampec7d878d2018-11-19 18:42:06 +00002977 MutableHandle<mirror::Object> this_at_throw = handle_scope.NewHandle<mirror::Object>(nullptr);
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002978 std::unique_ptr<Context> context(Context::Create());
Andreas Gampe3d477f32018-11-16 16:40:45 +00002979
Andreas Gampec7d878d2018-11-19 18:42:06 +00002980 ArtMethod* catch_method = nullptr;
2981 ArtMethod* throw_method = nullptr;
2982 uint32_t catch_dex_pc = dex::kDexNoIndex;
2983 uint32_t throw_dex_pc = dex::kDexNoIndex;
2984 StackVisitor::WalkStack(
2985 /**
2986 * Finds the location where this exception will be caught. We search until we reach the top
2987 * frame, in which case this exception is considered uncaught.
2988 */
2989 [&](const art::StackVisitor* stack_visitor) REQUIRES_SHARED(Locks::mutator_lock_) {
2990 ArtMethod* method = stack_visitor->GetMethod();
2991 DCHECK(method != nullptr);
2992 if (method->IsRuntimeMethod()) {
2993 // Ignore callee save method.
2994 DCHECK(method->IsCalleeSaveMethod());
2995 return true;
2996 }
2997
2998 uint32_t dex_pc = stack_visitor->GetDexPc();
2999 if (throw_method == nullptr) {
3000 // First Java method found. It is either the method that threw the exception,
3001 // or the Java native method that is reporting an exception thrown by
3002 // native code.
3003 this_at_throw.Assign(stack_visitor->GetThisObject());
3004 throw_method = method;
3005 throw_dex_pc = dex_pc;
3006 }
3007
3008 if (dex_pc != dex::kDexNoIndex) {
3009 StackHandleScope<1> hs(stack_visitor->GetThread());
3010 uint32_t found_dex_pc;
3011 Handle<mirror::Class> exception_class(hs.NewHandle(h_exception->GetClass()));
3012 bool unused_clear_exception;
3013 found_dex_pc = method->FindCatchBlock(exception_class, dex_pc, &unused_clear_exception);
3014 if (found_dex_pc != dex::kDexNoIndex) {
3015 catch_method = method;
3016 catch_dex_pc = found_dex_pc;
3017 return false; // End stack walk.
3018 }
3019 }
3020 return true; // Continue stack walk.
3021 },
3022 self,
3023 context.get(),
3024 art::StackVisitor::StackWalkKind::kIncludeInlinedFrames);
3025
3026 JDWP::EventLocation exception_throw_location;
3027 SetEventLocation(&exception_throw_location, throw_method, throw_dex_pc);
3028 JDWP::EventLocation exception_catch_location;
3029 SetEventLocation(&exception_catch_location, catch_method, catch_dex_pc);
3030
3031 gJdwpState->PostException(&exception_throw_location,
3032 h_exception.Get(),
3033 &exception_catch_location,
3034 this_at_throw.Get());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003035}
3036
Vladimir Marko83114892019-04-11 13:05:50 +01003037void Dbg::PostClassPrepare(ObjPtr<mirror::Class> c) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07003038 if (!IsDebuggerActive()) {
Elliott Hughes4740cdf2011-12-07 14:07:12 -08003039 return;
3040 }
Sebastien Hertz6995c602014-09-09 12:10:13 +02003041 gJdwpState->PostClassPrepare(c);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003042}
3043
Vladimir Marko83114892019-04-11 13:05:50 +01003044void Dbg::UpdateDebugger(Thread* thread,
3045 ObjPtr<mirror::Object> this_object,
3046 ArtMethod* m,
3047 uint32_t dex_pc,
3048 int event_flags,
3049 const JValue* return_value) {
Ian Rogers62d6c772013-02-27 08:32:07 -08003050 if (!IsDebuggerActive() || dex_pc == static_cast<uint32_t>(-2) /* fake method exit */) {
Elliott Hughes2aa2e392012-02-17 17:15:43 -08003051 return;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003052 }
3053
Elliott Hughes86964332012-02-15 19:37:42 -08003054 if (IsBreakpoint(m, dex_pc)) {
3055 event_flags |= kBreakpoint;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003056 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003057
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003058 // If the debugger is single-stepping one of our threads, check to
3059 // see if we're that thread and we've reached a step point.
3060 const SingleStepControl* single_step_control = thread->GetSingleStepControl();
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003061 if (single_step_control != nullptr) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003062 CHECK(!m->IsNative());
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003063 if (single_step_control->GetStepDepth() == JDWP::SD_INTO) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003064 // Step into method calls. We break when the line number
3065 // or method pointer changes. If we're in SS_MIN mode, we
3066 // always stop.
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003067 if (single_step_control->GetMethod() != m) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003068 event_flags |= kSingleStep;
3069 VLOG(jdwp) << "SS new method";
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003070 } else if (single_step_control->GetStepSize() == JDWP::SS_MIN) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003071 event_flags |= kSingleStep;
3072 VLOG(jdwp) << "SS new instruction";
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003073 } else if (single_step_control->ContainsDexPc(dex_pc)) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003074 event_flags |= kSingleStep;
3075 VLOG(jdwp) << "SS new line";
3076 }
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003077 } else if (single_step_control->GetStepDepth() == JDWP::SD_OVER) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003078 // Step over method calls. We break when the line number is
3079 // different and the frame depth is <= the original frame
3080 // depth. (We can't just compare on the method, because we
3081 // might get unrolled past it by an exception, and it's tricky
3082 // to identify recursion.)
3083
3084 int stack_depth = GetStackDepth(thread);
3085
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003086 if (stack_depth < single_step_control->GetStackDepth()) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003087 // Popped up one or more frames, always trigger.
3088 event_flags |= kSingleStep;
3089 VLOG(jdwp) << "SS method pop";
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003090 } else if (stack_depth == single_step_control->GetStackDepth()) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003091 // Same depth, see if we moved.
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003092 if (single_step_control->GetStepSize() == JDWP::SS_MIN) {
Elliott Hughes86964332012-02-15 19:37:42 -08003093 event_flags |= kSingleStep;
3094 VLOG(jdwp) << "SS new instruction";
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003095 } else if (single_step_control->ContainsDexPc(dex_pc)) {
Elliott Hughes2435a572012-02-17 16:07:41 -08003096 event_flags |= kSingleStep;
3097 VLOG(jdwp) << "SS new line";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003098 }
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003099 }
3100 } else {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003101 CHECK_EQ(single_step_control->GetStepDepth(), JDWP::SD_OUT);
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003102 // Return from the current method. We break when the frame
3103 // depth pops up.
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003104
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003105 // This differs from the "method exit" break in that it stops
3106 // with the PC at the next instruction in the returned-to
3107 // function, rather than the end of the returning function.
Elliott Hughes86964332012-02-15 19:37:42 -08003108
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003109 int stack_depth = GetStackDepth(thread);
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003110 if (stack_depth < single_step_control->GetStackDepth()) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003111 event_flags |= kSingleStep;
3112 VLOG(jdwp) << "SS method pop";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003113 }
3114 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003115 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003116
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003117 // If there's something interesting going on, see if it matches one
3118 // of the debugger filters.
3119 if (event_flags != 0) {
Sebastien Hertz8379b222014-02-24 17:38:15 +01003120 Dbg::PostLocationEvent(m, dex_pc, this_object, event_flags, return_value);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003121 }
3122}
3123
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003124size_t* Dbg::GetReferenceCounterForEvent(uint32_t instrumentation_event) {
3125 switch (instrumentation_event) {
3126 case instrumentation::Instrumentation::kMethodEntered:
3127 return &method_enter_event_ref_count_;
3128 case instrumentation::Instrumentation::kMethodExited:
3129 return &method_exit_event_ref_count_;
3130 case instrumentation::Instrumentation::kDexPcMoved:
3131 return &dex_pc_change_event_ref_count_;
3132 case instrumentation::Instrumentation::kFieldRead:
3133 return &field_read_event_ref_count_;
3134 case instrumentation::Instrumentation::kFieldWritten:
3135 return &field_write_event_ref_count_;
Alex Light6e1607e2017-08-23 10:06:18 -07003136 case instrumentation::Instrumentation::kExceptionThrown:
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003137 return &exception_catch_event_ref_count_;
3138 default:
3139 return nullptr;
3140 }
3141}
3142
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003143// Process request while all mutator threads are suspended.
3144void Dbg::ProcessDeoptimizationRequest(const DeoptimizationRequest& request) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003145 instrumentation::Instrumentation* instrumentation = Runtime::Current()->GetInstrumentation();
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003146 switch (request.GetKind()) {
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003147 case DeoptimizationRequest::kNothing:
3148 LOG(WARNING) << "Ignoring empty deoptimization request.";
3149 break;
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003150 case DeoptimizationRequest::kRegisterForEvent:
3151 VLOG(jdwp) << StringPrintf("Add debugger as listener for instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003152 request.InstrumentationEvent());
3153 instrumentation->AddListener(&gDebugInstrumentationListener, request.InstrumentationEvent());
3154 instrumentation_events_ |= request.InstrumentationEvent();
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003155 break;
3156 case DeoptimizationRequest::kUnregisterForEvent:
3157 VLOG(jdwp) << StringPrintf("Remove debugger as listener for instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003158 request.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003159 instrumentation->RemoveListener(&gDebugInstrumentationListener,
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003160 request.InstrumentationEvent());
3161 instrumentation_events_ &= ~request.InstrumentationEvent();
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003162 break;
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003163 case DeoptimizationRequest::kFullDeoptimization:
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003164 VLOG(jdwp) << "Deoptimize the world ...";
Sebastien Hertz0462c4c2015-04-01 16:34:17 +02003165 instrumentation->DeoptimizeEverything(kDbgInstrumentationKey);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003166 VLOG(jdwp) << "Deoptimize the world DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003167 break;
3168 case DeoptimizationRequest::kFullUndeoptimization:
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003169 VLOG(jdwp) << "Undeoptimize the world ...";
Sebastien Hertz0462c4c2015-04-01 16:34:17 +02003170 instrumentation->UndeoptimizeEverything(kDbgInstrumentationKey);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003171 VLOG(jdwp) << "Undeoptimize the world DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003172 break;
3173 case DeoptimizationRequest::kSelectiveDeoptimization:
David Sehr709b0702016-10-13 09:12:37 -07003174 VLOG(jdwp) << "Deoptimize method " << ArtMethod::PrettyMethod(request.Method()) << " ...";
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003175 instrumentation->Deoptimize(request.Method());
David Sehr709b0702016-10-13 09:12:37 -07003176 VLOG(jdwp) << "Deoptimize method " << ArtMethod::PrettyMethod(request.Method()) << " DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003177 break;
3178 case DeoptimizationRequest::kSelectiveUndeoptimization:
David Sehr709b0702016-10-13 09:12:37 -07003179 VLOG(jdwp) << "Undeoptimize method " << ArtMethod::PrettyMethod(request.Method()) << " ...";
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003180 instrumentation->Undeoptimize(request.Method());
David Sehr709b0702016-10-13 09:12:37 -07003181 VLOG(jdwp) << "Undeoptimize method " << ArtMethod::PrettyMethod(request.Method()) << " DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003182 break;
3183 default:
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003184 LOG(FATAL) << "Unsupported deoptimization request kind " << request.GetKind();
Elliott Hughesc1896c92018-11-29 11:33:18 -08003185 UNREACHABLE();
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003186 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003187}
3188
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003189void Dbg::RequestDeoptimization(const DeoptimizationRequest& req) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003190 if (req.GetKind() == DeoptimizationRequest::kNothing) {
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003191 // Nothing to do.
3192 return;
3193 }
Brian Carlstrom306db812014-09-05 13:01:41 -07003194 MutexLock mu(Thread::Current(), *Locks::deoptimization_lock_);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003195 RequestDeoptimizationLocked(req);
3196}
3197
3198void Dbg::RequestDeoptimizationLocked(const DeoptimizationRequest& req) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003199 switch (req.GetKind()) {
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003200 case DeoptimizationRequest::kRegisterForEvent: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003201 DCHECK_NE(req.InstrumentationEvent(), 0u);
3202 size_t* counter = GetReferenceCounterForEvent(req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003203 CHECK(counter != nullptr) << StringPrintf("No counter for instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003204 req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003205 if (*counter == 0) {
Sebastien Hertz7d2ae432014-05-15 11:26:34 +02003206 VLOG(jdwp) << StringPrintf("Queue request #%zd to start listening to instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003207 deoptimization_requests_.size(), req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003208 deoptimization_requests_.push_back(req);
3209 }
3210 *counter = *counter + 1;
3211 break;
3212 }
3213 case DeoptimizationRequest::kUnregisterForEvent: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003214 DCHECK_NE(req.InstrumentationEvent(), 0u);
3215 size_t* counter = GetReferenceCounterForEvent(req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003216 CHECK(counter != nullptr) << StringPrintf("No counter for instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003217 req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003218 *counter = *counter - 1;
3219 if (*counter == 0) {
Sebastien Hertz7d2ae432014-05-15 11:26:34 +02003220 VLOG(jdwp) << StringPrintf("Queue request #%zd to stop listening to instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003221 deoptimization_requests_.size(), req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003222 deoptimization_requests_.push_back(req);
3223 }
3224 break;
3225 }
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003226 case DeoptimizationRequest::kFullDeoptimization: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003227 DCHECK(req.Method() == nullptr);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003228 if (full_deoptimization_event_count_ == 0) {
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003229 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
3230 << " for full deoptimization";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003231 deoptimization_requests_.push_back(req);
3232 }
3233 ++full_deoptimization_event_count_;
3234 break;
3235 }
3236 case DeoptimizationRequest::kFullUndeoptimization: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003237 DCHECK(req.Method() == nullptr);
Sebastien Hertze713d932014-05-15 10:48:53 +02003238 DCHECK_GT(full_deoptimization_event_count_, 0U);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003239 --full_deoptimization_event_count_;
3240 if (full_deoptimization_event_count_ == 0) {
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003241 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
3242 << " for full undeoptimization";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003243 deoptimization_requests_.push_back(req);
3244 }
3245 break;
3246 }
3247 case DeoptimizationRequest::kSelectiveDeoptimization: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003248 DCHECK(req.Method() != nullptr);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003249 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
David Sehr709b0702016-10-13 09:12:37 -07003250 << " for deoptimization of " << req.Method()->PrettyMethod();
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003251 deoptimization_requests_.push_back(req);
3252 break;
3253 }
3254 case DeoptimizationRequest::kSelectiveUndeoptimization: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003255 DCHECK(req.Method() != nullptr);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003256 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
David Sehr709b0702016-10-13 09:12:37 -07003257 << " for undeoptimization of " << req.Method()->PrettyMethod();
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003258 deoptimization_requests_.push_back(req);
3259 break;
3260 }
3261 default: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003262 LOG(FATAL) << "Unknown deoptimization request kind " << req.GetKind();
Elliott Hughesc1896c92018-11-29 11:33:18 -08003263 UNREACHABLE();
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003264 }
3265 }
3266}
3267
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003268void Dbg::ManageDeoptimization() {
3269 Thread* const self = Thread::Current();
3270 {
3271 // Avoid suspend/resume if there is no pending request.
Brian Carlstrom306db812014-09-05 13:01:41 -07003272 MutexLock mu(self, *Locks::deoptimization_lock_);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003273 if (deoptimization_requests_.empty()) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003274 return;
3275 }
3276 }
3277 CHECK_EQ(self->GetState(), kRunnable);
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07003278 ScopedThreadSuspension sts(self, kWaitingForDeoptimization);
Mathieu Chartieraa516822015-10-02 15:53:37 -07003279 // Required for ProcessDeoptimizationRequest.
3280 gc::ScopedGCCriticalSection gcs(self,
3281 gc::kGcCauseInstrumentation,
3282 gc::kCollectorTypeInstrumentation);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003283 // We need to suspend mutator threads first.
Mathieu Chartier4f55e222015-09-04 13:26:21 -07003284 ScopedSuspendAll ssa(__FUNCTION__);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003285 const ThreadState old_state = self->SetStateUnsafe(kRunnable);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003286 {
Brian Carlstrom306db812014-09-05 13:01:41 -07003287 MutexLock mu(self, *Locks::deoptimization_lock_);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003288 size_t req_index = 0;
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003289 for (DeoptimizationRequest& request : deoptimization_requests_) {
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003290 VLOG(jdwp) << "Process deoptimization request #" << req_index++;
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003291 ProcessDeoptimizationRequest(request);
3292 }
3293 deoptimization_requests_.clear();
3294 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003295 CHECK_EQ(self->SetStateUnsafe(old_state), kRunnable);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003296}
3297
Mathieu Chartiere401d142015-04-22 13:56:20 -07003298static const Breakpoint* FindFirstBreakpointForMethod(ArtMethod* m)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003299 REQUIRES_SHARED(Locks::mutator_lock_, Locks::breakpoint_lock_) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003300 for (Breakpoint& breakpoint : gBreakpoints) {
Alex Light6c8467f2015-11-20 15:03:26 -08003301 if (breakpoint.IsInMethod(m)) {
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003302 return &breakpoint;
3303 }
3304 }
3305 return nullptr;
3306}
3307
Mathieu Chartiere401d142015-04-22 13:56:20 -07003308bool Dbg::MethodHasAnyBreakpoints(ArtMethod* method) {
Mathieu Chartierd8565452015-03-26 09:41:50 -07003309 ReaderMutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
3310 return FindFirstBreakpointForMethod(method) != nullptr;
3311}
3312
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003313// Sanity checks all existing breakpoints on the same method.
Mathieu Chartiere401d142015-04-22 13:56:20 -07003314static void SanityCheckExistingBreakpoints(ArtMethod* m,
Sebastien Hertzf3928792014-11-17 19:00:37 +01003315 DeoptimizationRequest::Kind deoptimization_kind)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003316 REQUIRES_SHARED(Locks::mutator_lock_, Locks::breakpoint_lock_) {
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003317 for (const Breakpoint& breakpoint : gBreakpoints) {
Alex Light6c8467f2015-11-20 15:03:26 -08003318 if (breakpoint.IsInMethod(m)) {
Sebastien Hertzf3928792014-11-17 19:00:37 +01003319 CHECK_EQ(deoptimization_kind, breakpoint.GetDeoptimizationKind());
3320 }
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003321 }
Sebastien Hertzf3928792014-11-17 19:00:37 +01003322 instrumentation::Instrumentation* instrumentation = Runtime::Current()->GetInstrumentation();
3323 if (deoptimization_kind == DeoptimizationRequest::kFullDeoptimization) {
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003324 // We should have deoptimized everything but not "selectively" deoptimized this method.
Sebastien Hertzf3928792014-11-17 19:00:37 +01003325 CHECK(instrumentation->AreAllMethodsDeoptimized());
3326 CHECK(!instrumentation->IsDeoptimized(m));
3327 } else if (deoptimization_kind == DeoptimizationRequest::kSelectiveDeoptimization) {
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003328 // We should have "selectively" deoptimized this method.
3329 // Note: while we have not deoptimized everything for this method, we may have done it for
3330 // another event.
Sebastien Hertzf3928792014-11-17 19:00:37 +01003331 CHECK(instrumentation->IsDeoptimized(m));
3332 } else {
3333 // This method does not require deoptimization.
3334 CHECK_EQ(deoptimization_kind, DeoptimizationRequest::kNothing);
3335 CHECK(!instrumentation->IsDeoptimized(m));
3336 }
3337}
3338
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003339// Returns the deoptimization kind required to set a breakpoint in a method.
3340// If a breakpoint has already been set, we also return the first breakpoint
3341// through the given 'existing_brkpt' pointer.
Sebastien Hertzf3928792014-11-17 19:00:37 +01003342static DeoptimizationRequest::Kind GetRequiredDeoptimizationKind(Thread* self,
Mathieu Chartiere401d142015-04-22 13:56:20 -07003343 ArtMethod* m,
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003344 const Breakpoint** existing_brkpt)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003345 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertzf3928792014-11-17 19:00:37 +01003346 if (!Dbg::RequiresDeoptimization()) {
3347 // We already run in interpreter-only mode so we don't need to deoptimize anything.
3348 VLOG(jdwp) << "No need for deoptimization when fully running with interpreter for method "
David Sehr709b0702016-10-13 09:12:37 -07003349 << ArtMethod::PrettyMethod(m);
Sebastien Hertzf3928792014-11-17 19:00:37 +01003350 return DeoptimizationRequest::kNothing;
3351 }
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003352 const Breakpoint* first_breakpoint;
Sebastien Hertzf3928792014-11-17 19:00:37 +01003353 {
3354 ReaderMutexLock mu(self, *Locks::breakpoint_lock_);
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003355 first_breakpoint = FindFirstBreakpointForMethod(m);
3356 *existing_brkpt = first_breakpoint;
Sebastien Hertzf3928792014-11-17 19:00:37 +01003357 }
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003358
3359 if (first_breakpoint == nullptr) {
Nicolas Geoffray6300fd72016-03-18 09:40:17 +00003360 // There is no breakpoint on this method yet: we need to deoptimize. If this method is default,
3361 // we deoptimize everything; otherwise we deoptimize only this method. We
Alex Light6c8467f2015-11-20 15:03:26 -08003362 // deoptimize with defaults because we do not know everywhere they are used. It is possible some
Nicolas Geoffray6300fd72016-03-18 09:40:17 +00003363 // of the copies could be missed.
Alex Light6c8467f2015-11-20 15:03:26 -08003364 // TODO Deoptimizing on default methods might not be necessary in all cases.
Nicolas Geoffray6300fd72016-03-18 09:40:17 +00003365 bool need_full_deoptimization = m->IsDefault();
Sebastien Hertzf3928792014-11-17 19:00:37 +01003366 if (need_full_deoptimization) {
Nicolas Geoffray6300fd72016-03-18 09:40:17 +00003367 VLOG(jdwp) << "Need full deoptimization because of copying of method "
David Sehr709b0702016-10-13 09:12:37 -07003368 << ArtMethod::PrettyMethod(m);
Sebastien Hertzf3928792014-11-17 19:00:37 +01003369 return DeoptimizationRequest::kFullDeoptimization;
3370 } else {
3371 // We don't need to deoptimize if the method has not been compiled.
Nicolas Geoffraya5891e82015-11-06 14:18:27 +00003372 const bool is_compiled = m->HasAnyCompiledCode();
Sebastien Hertzf3928792014-11-17 19:00:37 +01003373 if (is_compiled) {
David Sehr709b0702016-10-13 09:12:37 -07003374 VLOG(jdwp) << "Need selective deoptimization for compiled method "
3375 << ArtMethod::PrettyMethod(m);
Nicolas Geoffray6300fd72016-03-18 09:40:17 +00003376 return DeoptimizationRequest::kSelectiveDeoptimization;
Sebastien Hertzf3928792014-11-17 19:00:37 +01003377 } else {
3378 // Method is not compiled: we don't need to deoptimize.
David Sehr709b0702016-10-13 09:12:37 -07003379 VLOG(jdwp) << "No need for deoptimization for non-compiled method "
3380 << ArtMethod::PrettyMethod(m);
Sebastien Hertzf3928792014-11-17 19:00:37 +01003381 return DeoptimizationRequest::kNothing;
3382 }
3383 }
3384 } else {
3385 // There is at least one breakpoint for this method: we don't need to deoptimize.
3386 // Let's check that all breakpoints are configured the same way for deoptimization.
3387 VLOG(jdwp) << "Breakpoint already set: no deoptimization is required";
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003388 DeoptimizationRequest::Kind deoptimization_kind = first_breakpoint->GetDeoptimizationKind();
Sebastien Hertzf3928792014-11-17 19:00:37 +01003389 if (kIsDebugBuild) {
3390 ReaderMutexLock mu(self, *Locks::breakpoint_lock_);
3391 SanityCheckExistingBreakpoints(m, deoptimization_kind);
3392 }
3393 return DeoptimizationRequest::kNothing;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003394 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003395}
3396
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003397// Installs a breakpoint at the specified location. Also indicates through the deoptimization
3398// request if we need to deoptimize.
3399void Dbg::WatchLocation(const JDWP::JdwpLocation* location, DeoptimizationRequest* req) {
3400 Thread* const self = Thread::Current();
Mathieu Chartiere401d142015-04-22 13:56:20 -07003401 ArtMethod* m = FromMethodId(location->method_id);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003402 DCHECK(m != nullptr) << "No method for method id " << location->method_id;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003403
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003404 const Breakpoint* existing_breakpoint = nullptr;
3405 const DeoptimizationRequest::Kind deoptimization_kind =
3406 GetRequiredDeoptimizationKind(self, m, &existing_breakpoint);
Sebastien Hertzf3928792014-11-17 19:00:37 +01003407 req->SetKind(deoptimization_kind);
3408 if (deoptimization_kind == DeoptimizationRequest::kSelectiveDeoptimization) {
3409 req->SetMethod(m);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003410 } else {
Sebastien Hertzf3928792014-11-17 19:00:37 +01003411 CHECK(deoptimization_kind == DeoptimizationRequest::kNothing ||
3412 deoptimization_kind == DeoptimizationRequest::kFullDeoptimization);
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003413 req->SetMethod(nullptr);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003414 }
3415
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003416 {
3417 WriterMutexLock mu(self, *Locks::breakpoint_lock_);
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003418 // If there is at least one existing breakpoint on the same method, the new breakpoint
3419 // must have the same deoptimization kind than the existing breakpoint(s).
3420 DeoptimizationRequest::Kind breakpoint_deoptimization_kind;
3421 if (existing_breakpoint != nullptr) {
3422 breakpoint_deoptimization_kind = existing_breakpoint->GetDeoptimizationKind();
3423 } else {
3424 breakpoint_deoptimization_kind = deoptimization_kind;
3425 }
3426 gBreakpoints.push_back(Breakpoint(m, location->dex_pc, breakpoint_deoptimization_kind));
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003427 VLOG(jdwp) << "Set breakpoint #" << (gBreakpoints.size() - 1) << ": "
3428 << gBreakpoints[gBreakpoints.size() - 1];
3429 }
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003430}
3431
3432// Uninstalls a breakpoint at the specified location. Also indicates through the deoptimization
3433// request if we need to undeoptimize.
3434void Dbg::UnwatchLocation(const JDWP::JdwpLocation* location, DeoptimizationRequest* req) {
Sebastien Hertzed2be172014-08-19 15:33:43 +02003435 WriterMutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003436 ArtMethod* m = FromMethodId(location->method_id);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003437 DCHECK(m != nullptr) << "No method for method id " << location->method_id;
Sebastien Hertzf3928792014-11-17 19:00:37 +01003438 DeoptimizationRequest::Kind deoptimization_kind = DeoptimizationRequest::kNothing;
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003439 for (size_t i = 0, e = gBreakpoints.size(); i < e; ++i) {
Alex Light6c8467f2015-11-20 15:03:26 -08003440 if (gBreakpoints[i].DexPc() == location->dex_pc && gBreakpoints[i].IsInMethod(m)) {
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003441 VLOG(jdwp) << "Removed breakpoint #" << i << ": " << gBreakpoints[i];
Sebastien Hertzf3928792014-11-17 19:00:37 +01003442 deoptimization_kind = gBreakpoints[i].GetDeoptimizationKind();
3443 DCHECK_EQ(deoptimization_kind == DeoptimizationRequest::kSelectiveDeoptimization,
3444 Runtime::Current()->GetInstrumentation()->IsDeoptimized(m));
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003445 gBreakpoints.erase(gBreakpoints.begin() + i);
3446 break;
3447 }
3448 }
3449 const Breakpoint* const existing_breakpoint = FindFirstBreakpointForMethod(m);
3450 if (existing_breakpoint == nullptr) {
3451 // There is no more breakpoint on this method: we need to undeoptimize.
Sebastien Hertzf3928792014-11-17 19:00:37 +01003452 if (deoptimization_kind == DeoptimizationRequest::kFullDeoptimization) {
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003453 // This method required full deoptimization: we need to undeoptimize everything.
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003454 req->SetKind(DeoptimizationRequest::kFullUndeoptimization);
3455 req->SetMethod(nullptr);
Sebastien Hertzf3928792014-11-17 19:00:37 +01003456 } else if (deoptimization_kind == DeoptimizationRequest::kSelectiveDeoptimization) {
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003457 // This method required selective deoptimization: we need to undeoptimize only that method.
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003458 req->SetKind(DeoptimizationRequest::kSelectiveUndeoptimization);
3459 req->SetMethod(m);
Sebastien Hertzf3928792014-11-17 19:00:37 +01003460 } else {
3461 // This method had no need for deoptimization: do nothing.
3462 CHECK_EQ(deoptimization_kind, DeoptimizationRequest::kNothing);
3463 req->SetKind(DeoptimizationRequest::kNothing);
3464 req->SetMethod(nullptr);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003465 }
3466 } else {
3467 // There is at least one breakpoint for this method: we don't need to undeoptimize.
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003468 req->SetKind(DeoptimizationRequest::kNothing);
3469 req->SetMethod(nullptr);
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003470 if (kIsDebugBuild) {
Sebastien Hertzf3928792014-11-17 19:00:37 +01003471 SanityCheckExistingBreakpoints(m, deoptimization_kind);
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003472 }
Elliott Hughes86964332012-02-15 19:37:42 -08003473 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003474}
3475
Mathieu Chartiere401d142015-04-22 13:56:20 -07003476bool Dbg::IsForcedInterpreterNeededForCallingImpl(Thread* thread, ArtMethod* m) {
Daniel Mihalyieb076692014-08-22 17:33:31 +02003477 const SingleStepControl* const ssc = thread->GetSingleStepControl();
3478 if (ssc == nullptr) {
3479 // If we are not single-stepping, then we don't have to force interpreter.
3480 return false;
3481 }
3482 if (Runtime::Current()->GetInstrumentation()->InterpretOnly()) {
3483 // If we are in interpreter only mode, then we don't have to force interpreter.
3484 return false;
3485 }
3486
3487 if (!m->IsNative() && !m->IsProxyMethod()) {
3488 // If we want to step into a method, then we have to force interpreter on that call.
3489 if (ssc->GetStepDepth() == JDWP::SD_INTO) {
3490 return true;
3491 }
3492 }
3493 return false;
3494}
3495
Mathieu Chartiere401d142015-04-22 13:56:20 -07003496bool Dbg::IsForcedInterpreterNeededForResolutionImpl(Thread* thread, ArtMethod* m) {
Daniel Mihalyieb076692014-08-22 17:33:31 +02003497 instrumentation::Instrumentation* const instrumentation =
3498 Runtime::Current()->GetInstrumentation();
3499 // If we are in interpreter only mode, then we don't have to force interpreter.
3500 if (instrumentation->InterpretOnly()) {
3501 return false;
3502 }
3503 // We can only interpret pure Java method.
3504 if (m->IsNative() || m->IsProxyMethod()) {
3505 return false;
3506 }
3507 const SingleStepControl* const ssc = thread->GetSingleStepControl();
3508 if (ssc != nullptr) {
3509 // If we want to step into a method, then we have to force interpreter on that call.
3510 if (ssc->GetStepDepth() == JDWP::SD_INTO) {
3511 return true;
3512 }
3513 // If we are stepping out from a static initializer, by issuing a step
3514 // in or step over, that was implicitly invoked by calling a static method,
3515 // then we need to step into that method. Having a lower stack depth than
3516 // the one the single step control has indicates that the step originates
3517 // from the static initializer.
3518 if (ssc->GetStepDepth() != JDWP::SD_OUT &&
3519 ssc->GetStackDepth() > GetStackDepth(thread)) {
3520 return true;
3521 }
3522 }
3523 // There are cases where we have to force interpreter on deoptimized methods,
3524 // because in some cases the call will not be performed by invoking an entry
3525 // point that has been replaced by the deoptimization, but instead by directly
3526 // invoking the compiled code of the method, for example.
3527 return instrumentation->IsDeoptimized(m);
3528}
3529
Mathieu Chartiere401d142015-04-22 13:56:20 -07003530bool Dbg::IsForcedInstrumentationNeededForResolutionImpl(Thread* thread, ArtMethod* m) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07003531 // The upcall can be null and in that case we don't need to do anything.
Daniel Mihalyieb076692014-08-22 17:33:31 +02003532 if (m == nullptr) {
3533 return false;
3534 }
3535 instrumentation::Instrumentation* const instrumentation =
3536 Runtime::Current()->GetInstrumentation();
3537 // If we are in interpreter only mode, then we don't have to force interpreter.
3538 if (instrumentation->InterpretOnly()) {
3539 return false;
3540 }
3541 // We can only interpret pure Java method.
3542 if (m->IsNative() || m->IsProxyMethod()) {
3543 return false;
3544 }
3545 const SingleStepControl* const ssc = thread->GetSingleStepControl();
3546 if (ssc != nullptr) {
3547 // If we are stepping out from a static initializer, by issuing a step
3548 // out, that was implicitly invoked by calling a static method, then we
3549 // need to step into the caller of that method. Having a lower stack
3550 // depth than the one the single step control has indicates that the
3551 // step originates from the static initializer.
3552 if (ssc->GetStepDepth() == JDWP::SD_OUT &&
3553 ssc->GetStackDepth() > GetStackDepth(thread)) {
3554 return true;
3555 }
3556 }
3557 // If we are returning from a static intializer, that was implicitly
3558 // invoked by calling a static method and the caller is deoptimized,
3559 // then we have to deoptimize the stack without forcing interpreter
3560 // on the static method that was called originally. This problem can
3561 // be solved easily by forcing instrumentation on the called method,
3562 // because the instrumentation exit hook will recognise the need of
3563 // stack deoptimization by calling IsForcedInterpreterNeededForUpcall.
3564 return instrumentation->IsDeoptimized(m);
3565}
3566
Mathieu Chartiere401d142015-04-22 13:56:20 -07003567bool Dbg::IsForcedInterpreterNeededForUpcallImpl(Thread* thread, ArtMethod* m) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07003568 // The upcall can be null and in that case we don't need to do anything.
Daniel Mihalyieb076692014-08-22 17:33:31 +02003569 if (m == nullptr) {
3570 return false;
3571 }
3572 instrumentation::Instrumentation* const instrumentation =
3573 Runtime::Current()->GetInstrumentation();
3574 // If we are in interpreter only mode, then we don't have to force interpreter.
3575 if (instrumentation->InterpretOnly()) {
3576 return false;
3577 }
3578 // We can only interpret pure Java method.
3579 if (m->IsNative() || m->IsProxyMethod()) {
3580 return false;
3581 }
3582 const SingleStepControl* const ssc = thread->GetSingleStepControl();
3583 if (ssc != nullptr) {
3584 // The debugger is not interested in what is happening under the level
3585 // of the step, thus we only force interpreter when we are not below of
3586 // the step.
3587 if (ssc->GetStackDepth() >= GetStackDepth(thread)) {
3588 return true;
3589 }
3590 }
Mingyao Yang99170c62015-07-06 11:10:37 -07003591 if (thread->HasDebuggerShadowFrames()) {
3592 // We need to deoptimize the stack for the exception handling flow so that
3593 // we don't miss any deoptimization that should be done when there are
3594 // debugger shadow frames.
3595 return true;
3596 }
Daniel Mihalyieb076692014-08-22 17:33:31 +02003597 // We have to require stack deoptimization if the upcall is deoptimized.
3598 return instrumentation->IsDeoptimized(m);
3599}
3600
Sebastien Hertz520633b2015-09-08 17:03:36 +02003601// Do we need to deoptimize the stack to handle an exception?
3602bool Dbg::IsForcedInterpreterNeededForExceptionImpl(Thread* thread) {
3603 const SingleStepControl* const ssc = thread->GetSingleStepControl();
3604 if (ssc != nullptr) {
3605 // We deopt to step into the catch handler.
3606 return true;
3607 }
3608 // Deoptimization is required if at least one method in the stack needs it. However we
3609 // skip frames that will be unwound (thus not executed).
Andreas Gampec7d878d2018-11-19 18:42:06 +00003610 bool needs_deoptimization = false;
3611 StackVisitor::WalkStack(
3612 [&](art::StackVisitor* visitor) REQUIRES_SHARED(Locks::mutator_lock_) {
3613 // The visitor is meant to be used when handling exception from compiled code only.
3614 CHECK(!visitor->IsShadowFrame()) << "We only expect to visit compiled frame: "
3615 << ArtMethod::PrettyMethod(visitor->GetMethod());
3616 ArtMethod* method = visitor->GetMethod();
3617 if (method == nullptr) {
3618 // We reach an upcall and don't need to deoptimize this part of the stack (ManagedFragment)
3619 // so we can stop the visit.
3620 DCHECK(!needs_deoptimization);
3621 return false;
3622 }
3623 if (Runtime::Current()->GetInstrumentation()->InterpretOnly()) {
3624 // We found a compiled frame in the stack but instrumentation is set to interpret
3625 // everything: we need to deoptimize.
3626 needs_deoptimization = true;
3627 return false;
3628 }
3629 if (Runtime::Current()->GetInstrumentation()->IsDeoptimized(method)) {
3630 // We found a deoptimized method in the stack.
3631 needs_deoptimization = true;
3632 return false;
3633 }
3634 ShadowFrame* frame = visitor->GetThread()->FindDebuggerShadowFrame(visitor->GetFrameId());
3635 if (frame != nullptr) {
3636 // The debugger allocated a ShadowFrame to update a variable in the stack: we need to
3637 // deoptimize the stack to execute (and deallocate) this frame.
3638 needs_deoptimization = true;
3639 return false;
3640 }
3641 return true;
3642 },
3643 thread,
3644 /* context= */ nullptr,
3645 art::StackVisitor::StackWalkKind::kIncludeInlinedFrames,
3646 /* check_suspended */ true,
3647 /* include_transitions */ true);
3648 return needs_deoptimization;
Sebastien Hertz520633b2015-09-08 17:03:36 +02003649}
3650
Jeff Hao449db332013-04-12 18:30:52 -07003651// Scoped utility class to suspend a thread so that we may do tasks such as walk its stack. Doesn't
3652// cause suspension if the thread is the current thread.
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07003653class ScopedDebuggerThreadSuspension {
Jeff Hao449db332013-04-12 18:30:52 -07003654 public:
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07003655 ScopedDebuggerThreadSuspension(Thread* self, JDWP::ObjectId thread_id)
Mathieu Chartier90443472015-07-16 20:32:27 -07003656 REQUIRES(!Locks::thread_list_lock_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003657 REQUIRES_SHARED(Locks::mutator_lock_) :
Ian Rogersf3d874c2014-07-17 18:52:42 -07003658 thread_(nullptr),
Jeff Hao449db332013-04-12 18:30:52 -07003659 error_(JDWP::ERR_NONE),
3660 self_suspend_(false),
Ian Rogers33e95662013-05-20 20:29:14 -07003661 other_suspend_(false) {
Jeff Hao449db332013-04-12 18:30:52 -07003662 ScopedObjectAccessUnchecked soa(self);
Sebastien Hertz69206392015-04-07 15:54:25 +02003663 thread_ = DecodeThread(soa, thread_id, &error_);
Jeff Hao449db332013-04-12 18:30:52 -07003664 if (error_ == JDWP::ERR_NONE) {
3665 if (thread_ == soa.Self()) {
3666 self_suspend_ = true;
3667 } else {
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07003668 Thread* suspended_thread;
3669 {
3670 ScopedThreadSuspension sts(self, kWaitingForDebuggerSuspension);
3671 jobject thread_peer = Dbg::GetObjectRegistry()->GetJObject(thread_id);
3672 bool timed_out;
3673 ThreadList* const thread_list = Runtime::Current()->GetThreadList();
Sebastien Hertzcdd798d2017-04-18 18:28:51 +02003674 suspended_thread = thread_list->SuspendThreadByPeer(thread_peer,
Andreas Gampe98ea9d92018-10-19 14:06:15 -07003675 /* request_suspension= */ true,
Alex Light46f93402017-06-29 11:59:50 -07003676 SuspendReason::kForDebugger,
Sebastien Hertzcdd798d2017-04-18 18:28:51 +02003677 &timed_out);
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07003678 }
Ian Rogersf3d874c2014-07-17 18:52:42 -07003679 if (suspended_thread == nullptr) {
Jeff Hao449db332013-04-12 18:30:52 -07003680 // Thread terminated from under us while suspending.
3681 error_ = JDWP::ERR_INVALID_THREAD;
3682 } else {
3683 CHECK_EQ(suspended_thread, thread_);
3684 other_suspend_ = true;
3685 }
3686 }
3687 }
Elliott Hughes2435a572012-02-17 16:07:41 -08003688 }
Elliott Hughes86964332012-02-15 19:37:42 -08003689
Jeff Hao449db332013-04-12 18:30:52 -07003690 Thread* GetThread() const {
3691 return thread_;
3692 }
3693
3694 JDWP::JdwpError GetError() const {
3695 return error_;
3696 }
3697
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07003698 ~ScopedDebuggerThreadSuspension() {
Jeff Hao449db332013-04-12 18:30:52 -07003699 if (other_suspend_) {
Alex Light88fd7202017-06-30 08:31:59 -07003700 bool resumed = Runtime::Current()->GetThreadList()->Resume(thread_,
3701 SuspendReason::kForDebugger);
3702 DCHECK(resumed);
Jeff Hao449db332013-04-12 18:30:52 -07003703 }
3704 }
3705
3706 private:
3707 Thread* thread_;
3708 JDWP::JdwpError error_;
3709 bool self_suspend_;
3710 bool other_suspend_;
3711};
3712
3713JDWP::JdwpError Dbg::ConfigureStep(JDWP::ObjectId thread_id, JDWP::JdwpStepSize step_size,
3714 JDWP::JdwpStepDepth step_depth) {
3715 Thread* self = Thread::Current();
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07003716 ScopedDebuggerThreadSuspension sts(self, thread_id);
Jeff Hao449db332013-04-12 18:30:52 -07003717 if (sts.GetError() != JDWP::ERR_NONE) {
3718 return sts.GetError();
3719 }
3720
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003721 // Work out what ArtMethod* we're in, the current line number, and how deep the stack currently
Elliott Hughes2435a572012-02-17 16:07:41 -08003722 // is for step-out.
Ian Rogers0399dde2012-06-06 17:09:28 -07003723 struct SingleStepStackVisitor : public StackVisitor {
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003724 explicit SingleStepStackVisitor(Thread* thread) REQUIRES_SHARED(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01003725 : StackVisitor(thread, nullptr, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
3726 stack_depth(0),
3727 method(nullptr),
3728 line_number(-1) {}
Ian Rogersca190662012-06-26 15:45:57 -07003729
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003730 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
3731 // annotalysis.
Andreas Gampefa6a1b02018-09-07 08:11:55 -07003732 bool VisitFrame() override NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003733 ArtMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07003734 if (!m->IsRuntimeMethod()) {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003735 ++stack_depth;
3736 if (method == nullptr) {
Alex Light73376312017-04-06 10:10:51 -07003737 const DexFile* dex_file = m->GetDexFile();
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003738 method = m;
Alex Light73376312017-04-06 10:10:51 -07003739 if (dex_file != nullptr) {
David Sehr9323e6e2016-09-13 08:58:35 -07003740 line_number = annotations::GetLineNumFromPC(dex_file, m, GetDexPc());
Elliott Hughes2435a572012-02-17 16:07:41 -08003741 }
Elliott Hughes86964332012-02-15 19:37:42 -08003742 }
3743 }
Elliott Hughes530fa002012-03-12 11:44:49 -07003744 return true;
Elliott Hughes86964332012-02-15 19:37:42 -08003745 }
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003746
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003747 int stack_depth;
Mathieu Chartiere401d142015-04-22 13:56:20 -07003748 ArtMethod* method;
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003749 int32_t line_number;
Elliott Hughes86964332012-02-15 19:37:42 -08003750 };
Jeff Hao449db332013-04-12 18:30:52 -07003751
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003752 Thread* const thread = sts.GetThread();
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003753 SingleStepStackVisitor visitor(thread);
Ian Rogers0399dde2012-06-06 17:09:28 -07003754 visitor.WalkStack();
Elliott Hughes86964332012-02-15 19:37:42 -08003755
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003756 // Allocate single step.
Sebastien Hertz1558b572015-02-25 15:05:59 +01003757 SingleStepControl* single_step_control =
3758 new (std::nothrow) SingleStepControl(step_size, step_depth,
3759 visitor.stack_depth, visitor.method);
3760 if (single_step_control == nullptr) {
3761 LOG(ERROR) << "Failed to allocate SingleStepControl";
3762 return JDWP::ERR_OUT_OF_MEMORY;
3763 }
3764
Mathieu Chartiere401d142015-04-22 13:56:20 -07003765 ArtMethod* m = single_step_control->GetMethod();
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003766 const int32_t line_number = visitor.line_number;
Sebastien Hertz52f5f932015-05-28 11:00:57 +02003767 // Note: if the thread is not running Java code (pure native thread), there is no "current"
3768 // method on the stack (and no line number either).
3769 if (m != nullptr && !m->IsNative()) {
David Sehr0225f8e2018-01-31 08:52:24 +00003770 CodeItemDebugInfoAccessor accessor(m->DexInstructionDebugInfo());
Mathieu Chartier3e2e1232018-09-11 12:35:30 -07003771 bool last_pc_valid = false;
3772 uint32_t last_pc = 0u;
3773 // Find the dex_pc values that correspond to the current line, for line-based single-stepping.
3774 accessor.DecodeDebugPositionInfo([&](const DexFile::PositionInfo& entry) {
3775 if (static_cast<int32_t>(entry.line_) == line_number) {
3776 if (!last_pc_valid) {
3777 // Everything from this address until the next line change is ours.
3778 last_pc = entry.address_;
3779 last_pc_valid = true;
3780 }
3781 // Otherwise, if we're already in a valid range for this line,
3782 // just keep going (shouldn't really happen)...
3783 } else if (last_pc_valid) { // and the line number is new
3784 // Add everything from the last entry up until here to the set
3785 for (uint32_t dex_pc = last_pc; dex_pc < entry.address_; ++dex_pc) {
3786 single_step_control->AddDexPc(dex_pc);
3787 }
3788 last_pc_valid = false;
3789 }
3790 return false; // There may be multiple entries for any given line.
3791 });
3792 // If the line number was the last in the position table...
3793 if (last_pc_valid) {
3794 for (uint32_t dex_pc = last_pc; dex_pc < accessor.InsnsSizeInCodeUnits(); ++dex_pc) {
3795 single_step_control->AddDexPc(dex_pc);
3796 }
3797 }
Elliott Hughes3e2e1a22012-02-21 11:33:41 -08003798 }
Elliott Hughes2435a572012-02-17 16:07:41 -08003799
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003800 // Activate single-step in the thread.
3801 thread->ActivateSingleStepControl(single_step_control);
Elliott Hughes86964332012-02-15 19:37:42 -08003802
Elliott Hughes2435a572012-02-17 16:07:41 -08003803 if (VLOG_IS_ON(jdwp)) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003804 VLOG(jdwp) << "Single-step thread: " << *thread;
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003805 VLOG(jdwp) << "Single-step step size: " << single_step_control->GetStepSize();
3806 VLOG(jdwp) << "Single-step step depth: " << single_step_control->GetStepDepth();
David Sehr709b0702016-10-13 09:12:37 -07003807 VLOG(jdwp) << "Single-step current method: "
3808 << ArtMethod::PrettyMethod(single_step_control->GetMethod());
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003809 VLOG(jdwp) << "Single-step current line: " << line_number;
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003810 VLOG(jdwp) << "Single-step current stack depth: " << single_step_control->GetStackDepth();
Elliott Hughes2435a572012-02-17 16:07:41 -08003811 VLOG(jdwp) << "Single-step dex_pc values:";
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003812 for (uint32_t dex_pc : single_step_control->GetDexPcs()) {
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003813 VLOG(jdwp) << StringPrintf(" %#x", dex_pc);
Elliott Hughes2435a572012-02-17 16:07:41 -08003814 }
3815 }
3816
3817 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003818}
3819
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003820void Dbg::UnconfigureStep(JDWP::ObjectId thread_id) {
3821 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07003822 JDWP::JdwpError error;
3823 Thread* thread = DecodeThread(soa, thread_id, &error);
Sebastien Hertz87118ed2013-11-26 17:57:18 +01003824 if (error == JDWP::ERR_NONE) {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003825 thread->DeactivateSingleStepControl();
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003826 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003827}
3828
Elliott Hughes45651fd2012-02-21 15:48:20 -08003829static char JdwpTagToShortyChar(JDWP::JdwpTag tag) {
3830 switch (tag) {
3831 default:
3832 LOG(FATAL) << "unknown JDWP tag: " << PrintableChar(tag);
Ian Rogersfc787ec2014-10-09 21:56:44 -07003833 UNREACHABLE();
Elliott Hughes45651fd2012-02-21 15:48:20 -08003834
3835 // Primitives.
3836 case JDWP::JT_BYTE: return 'B';
3837 case JDWP::JT_CHAR: return 'C';
3838 case JDWP::JT_FLOAT: return 'F';
3839 case JDWP::JT_DOUBLE: return 'D';
3840 case JDWP::JT_INT: return 'I';
3841 case JDWP::JT_LONG: return 'J';
3842 case JDWP::JT_SHORT: return 'S';
3843 case JDWP::JT_VOID: return 'V';
3844 case JDWP::JT_BOOLEAN: return 'Z';
3845
3846 // Reference types.
3847 case JDWP::JT_ARRAY:
3848 case JDWP::JT_OBJECT:
3849 case JDWP::JT_STRING:
3850 case JDWP::JT_THREAD:
3851 case JDWP::JT_THREAD_GROUP:
3852 case JDWP::JT_CLASS_LOADER:
3853 case JDWP::JT_CLASS_OBJECT:
3854 return 'L';
3855 }
3856}
3857
Sebastien Hertzcbc50642015-06-01 17:33:12 +02003858JDWP::JdwpError Dbg::PrepareInvokeMethod(uint32_t request_id, JDWP::ObjectId thread_id,
3859 JDWP::ObjectId object_id, JDWP::RefTypeId class_id,
3860 JDWP::MethodId method_id, uint32_t arg_count,
3861 uint64_t arg_values[], JDWP::JdwpTag* arg_types,
3862 uint32_t options) {
3863 Thread* const self = Thread::Current();
3864 CHECK_EQ(self, GetDebugThread()) << "This must be called by the JDWP thread";
Sebastien Hertzd4032e42015-06-12 15:47:34 +02003865 const bool resume_all_threads = ((options & JDWP::INVOKE_SINGLE_THREADED) == 0);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003866
Sebastien Hertzcbc50642015-06-01 17:33:12 +02003867 ThreadList* thread_list = Runtime::Current()->GetThreadList();
Ian Rogersc0542af2014-09-03 16:16:56 -07003868 Thread* targetThread = nullptr;
Elliott Hughesd07986f2011-12-06 18:27:45 -08003869 {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003870 ScopedObjectAccessUnchecked soa(self);
Ian Rogersc0542af2014-09-03 16:16:56 -07003871 JDWP::JdwpError error;
3872 targetThread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08003873 if (error != JDWP::ERR_NONE) {
3874 LOG(ERROR) << "InvokeMethod request for invalid thread id " << thread_id;
3875 return error;
Elliott Hughesd07986f2011-12-06 18:27:45 -08003876 }
Sebastien Hertz1558b572015-02-25 15:05:59 +01003877 if (targetThread->GetInvokeReq() != nullptr) {
3878 // Thread is already invoking a method on behalf of the debugger.
3879 LOG(ERROR) << "InvokeMethod request for thread already invoking a method: " << *targetThread;
3880 return JDWP::ERR_ALREADY_INVOKING;
3881 }
3882 if (!targetThread->IsReadyForDebugInvoke()) {
3883 // Thread is not suspended by an event so it cannot invoke a method.
Elliott Hughesd07986f2011-12-06 18:27:45 -08003884 LOG(ERROR) << "InvokeMethod request for thread not stopped by event: " << *targetThread;
3885 return JDWP::ERR_INVALID_THREAD;
3886 }
3887
3888 /*
Sebastien Hertzd4032e42015-06-12 15:47:34 +02003889 * According to the JDWP specs, we are expected to resume all threads (or only the
3890 * target thread) once. So if a thread has been suspended more than once (either by
3891 * the debugger for an event or by the runtime for GC), it will remain suspended before
3892 * the invoke is executed. This means the debugger is responsible to properly resume all
3893 * the threads it has suspended so the target thread can execute the method.
Elliott Hughesd07986f2011-12-06 18:27:45 -08003894 *
Sebastien Hertzd4032e42015-06-12 15:47:34 +02003895 * However, for compatibility reason with older versions of debuggers (like Eclipse), we
3896 * fully resume all threads (by canceling *all* debugger suspensions) when the debugger
3897 * wants us to resume all threads. This is to avoid ending up in deadlock situation.
3898 *
3899 * On the other hand, if we are asked to only resume the target thread, then we follow the
3900 * JDWP specs by resuming that thread only once. This means the thread will remain suspended
3901 * if it has been suspended more than once before the invoke (and again, this is the
3902 * responsibility of the debugger to properly resume that thread before invoking a method).
Elliott Hughesd07986f2011-12-06 18:27:45 -08003903 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003904 int suspend_count;
3905 {
Ian Rogers50b35e22012-10-04 10:09:15 -07003906 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003907 suspend_count = targetThread->GetSuspendCount();
3908 }
Sebastien Hertzd4032e42015-06-12 15:47:34 +02003909 if (suspend_count > 1 && resume_all_threads) {
3910 // The target thread will remain suspended even after we resume it. Let's emit a warning
3911 // to indicate the invoke won't be executed until the thread is resumed.
3912 LOG(WARNING) << *targetThread << " suspended more than once (suspend count == "
3913 << suspend_count << "). This thread will invoke the method only once "
3914 << "it is fully resumed.";
Elliott Hughesd07986f2011-12-06 18:27:45 -08003915 }
3916
Vladimir Marko83114892019-04-11 13:05:50 +01003917 ObjPtr<mirror::Object> receiver = gRegistry->Get<mirror::Object>(object_id, &error);
Ian Rogersc0542af2014-09-03 16:16:56 -07003918 if (error != JDWP::ERR_NONE) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08003919 return JDWP::ERR_INVALID_OBJECT;
3920 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003921
Vladimir Marko83114892019-04-11 13:05:50 +01003922 gRegistry->Get<mirror::Object>(thread_id, &error);
Ian Rogersc0542af2014-09-03 16:16:56 -07003923 if (error != JDWP::ERR_NONE) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08003924 return JDWP::ERR_INVALID_OBJECT;
3925 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003926
Vladimir Marko4617d582019-03-28 13:48:31 +00003927 ObjPtr<mirror::Class> c = DecodeClass(class_id, &error);
Ian Rogersc0542af2014-09-03 16:16:56 -07003928 if (c == nullptr) {
3929 return error;
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08003930 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003931
Mathieu Chartiere401d142015-04-22 13:56:20 -07003932 ArtMethod* m = FromMethodId(method_id);
Ian Rogersc0542af2014-09-03 16:16:56 -07003933 if (m->IsStatic() != (receiver == nullptr)) {
Elliott Hughes45651fd2012-02-21 15:48:20 -08003934 return JDWP::ERR_INVALID_METHODID;
3935 }
3936 if (m->IsStatic()) {
3937 if (m->GetDeclaringClass() != c) {
3938 return JDWP::ERR_INVALID_METHODID;
3939 }
3940 } else {
3941 if (!m->GetDeclaringClass()->IsAssignableFrom(c)) {
3942 return JDWP::ERR_INVALID_METHODID;
3943 }
3944 }
3945
3946 // Check the argument list matches the method.
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003947 uint32_t shorty_len = 0;
3948 const char* shorty = m->GetShorty(&shorty_len);
3949 if (shorty_len - 1 != arg_count) {
Elliott Hughes45651fd2012-02-21 15:48:20 -08003950 return JDWP::ERR_ILLEGAL_ARGUMENT;
3951 }
Elliott Hughes09201632013-04-15 15:50:07 -07003952
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003953 {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003954 StackHandleScope<2> hs(soa.Self());
Vladimir Marko4617d582019-03-28 13:48:31 +00003955 HandleWrapperObjPtr<mirror::Object> h_obj(hs.NewHandleWrapper(&receiver));
3956 HandleWrapperObjPtr<mirror::Class> h_klass(hs.NewHandleWrapper(&c));
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003957 const dex::TypeList* types = m->GetParameterTypeList();
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003958 for (size_t i = 0; i < arg_count; ++i) {
3959 if (shorty[i + 1] != JdwpTagToShortyChar(arg_types[i])) {
Elliott Hughes09201632013-04-15 15:50:07 -07003960 return JDWP::ERR_ILLEGAL_ARGUMENT;
3961 }
3962
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003963 if (shorty[i + 1] == 'L') {
3964 // Did we really get an argument of an appropriate reference type?
Vladimir Markob45528c2017-07-27 14:14:28 +01003965 ObjPtr<mirror::Class> parameter_type =
3966 m->ResolveClassFromTypeIndex(types->GetTypeItem(i).type_idx_);
Vladimir Marko83114892019-04-11 13:05:50 +01003967 ObjPtr<mirror::Object> argument = gRegistry->Get<mirror::Object>(arg_values[i], &error);
Ian Rogersc0542af2014-09-03 16:16:56 -07003968 if (error != JDWP::ERR_NONE) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003969 return JDWP::ERR_INVALID_OBJECT;
3970 }
Ian Rogersc0542af2014-09-03 16:16:56 -07003971 if (argument != nullptr && !argument->InstanceOf(parameter_type)) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003972 return JDWP::ERR_ILLEGAL_ARGUMENT;
3973 }
3974
3975 // Turn the on-the-wire ObjectId into a jobject.
3976 jvalue& v = reinterpret_cast<jvalue&>(arg_values[i]);
3977 v.l = gRegistry->GetJObject(arg_values[i]);
3978 }
Elliott Hughes09201632013-04-15 15:50:07 -07003979 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003980 }
3981
Sebastien Hertz1558b572015-02-25 15:05:59 +01003982 // Allocates a DebugInvokeReq.
Vladimir Marko4617d582019-03-28 13:48:31 +00003983 DebugInvokeReq* req = new (std::nothrow) DebugInvokeReq(
3984 request_id, thread_id, receiver, c, m, options, arg_values, arg_count);
Sebastien Hertzcbc50642015-06-01 17:33:12 +02003985 if (req == nullptr) {
Sebastien Hertz1558b572015-02-25 15:05:59 +01003986 LOG(ERROR) << "Failed to allocate DebugInvokeReq";
3987 return JDWP::ERR_OUT_OF_MEMORY;
3988 }
3989
Sebastien Hertzcbc50642015-06-01 17:33:12 +02003990 // Attaches the DebugInvokeReq to the target thread so it executes the method when
3991 // it is resumed. Once the invocation completes, the target thread will delete it before
3992 // suspending itself (see ThreadList::SuspendSelfForDebugger).
3993 targetThread->SetDebugInvokeReq(req);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003994 }
3995
3996 // 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 +02003997 // away we're sitting high and dry -- but we must release this before the UndoDebuggerSuspensions
3998 // call.
Sebastien Hertzd4032e42015-06-12 15:47:34 +02003999 if (resume_all_threads) {
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004000 VLOG(jdwp) << " Resuming all threads";
4001 thread_list->UndoDebuggerSuspensions();
4002 } else {
4003 VLOG(jdwp) << " Resuming event thread only";
Alex Light88fd7202017-06-30 08:31:59 -07004004 bool resumed = thread_list->Resume(targetThread, SuspendReason::kForDebugger);
4005 DCHECK(resumed);
Elliott Hughesd07986f2011-12-06 18:27:45 -08004006 }
4007
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004008 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004009}
4010
4011void Dbg::ExecuteMethod(DebugInvokeReq* pReq) {
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004012 Thread* const self = Thread::Current();
4013 CHECK_NE(self, GetDebugThread()) << "This must be called by the event thread";
4014
4015 ScopedObjectAccess soa(self);
Elliott Hughesd07986f2011-12-06 18:27:45 -08004016
Elliott Hughes81ff3182012-03-23 20:35:56 -07004017 // We can be called while an exception is pending. We need
Elliott Hughesd07986f2011-12-06 18:27:45 -08004018 // to preserve that across the method invocation.
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004019 StackHandleScope<1> hs(soa.Self());
4020 Handle<mirror::Throwable> old_exception = hs.NewHandle(soa.Self()->GetException());
Sebastien Hertz1558b572015-02-25 15:05:59 +01004021 soa.Self()->ClearException();
Elliott Hughesd07986f2011-12-06 18:27:45 -08004022
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004023 // Execute the method then sends reply to the debugger.
4024 ExecuteMethodWithoutPendingException(soa, pReq);
4025
4026 // If an exception was pending before the invoke, restore it now.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004027 if (old_exception != nullptr) {
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004028 soa.Self()->SetException(old_exception.Get());
4029 }
4030}
4031
4032// Helper function: write a variable-width value into the output input buffer.
4033static void WriteValue(JDWP::ExpandBuf* pReply, int width, uint64_t value) {
4034 switch (width) {
4035 case 1:
4036 expandBufAdd1(pReply, value);
4037 break;
4038 case 2:
4039 expandBufAdd2BE(pReply, value);
4040 break;
4041 case 4:
4042 expandBufAdd4BE(pReply, value);
4043 break;
4044 case 8:
4045 expandBufAdd8BE(pReply, value);
4046 break;
4047 default:
4048 LOG(FATAL) << width;
4049 UNREACHABLE();
4050 }
4051}
4052
4053void Dbg::ExecuteMethodWithoutPendingException(ScopedObjectAccess& soa, DebugInvokeReq* pReq) {
4054 soa.Self()->AssertNoPendingException();
4055
Elliott Hughesd07986f2011-12-06 18:27:45 -08004056 // Translate the method through the vtable, unless the debugger wants to suppress it.
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004057 ArtMethod* m = pReq->method;
Andreas Gampe542451c2016-07-26 09:02:02 -07004058 PointerSize image_pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
Sebastien Hertz1558b572015-02-25 15:05:59 +01004059 if ((pReq->options & JDWP::INVOKE_NONVIRTUAL) == 0 && pReq->receiver.Read() != nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004060 ArtMethod* actual_method =
4061 pReq->klass.Read()->FindVirtualMethodForVirtualOrInterface(m, image_pointer_size);
4062 if (actual_method != m) {
David Sehr709b0702016-10-13 09:12:37 -07004063 VLOG(jdwp) << "ExecuteMethod translated " << ArtMethod::PrettyMethod(m)
4064 << " to " << ArtMethod::PrettyMethod(actual_method);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004065 m = actual_method;
Elliott Hughes45651fd2012-02-21 15:48:20 -08004066 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08004067 }
David Sehr709b0702016-10-13 09:12:37 -07004068 VLOG(jdwp) << "ExecuteMethod " << ArtMethod::PrettyMethod(m)
Sebastien Hertz1558b572015-02-25 15:05:59 +01004069 << " receiver=" << pReq->receiver.Read()
Sebastien Hertzd38667a2013-11-25 15:43:54 +01004070 << " arg_count=" << pReq->arg_count;
Mathieu Chartiere401d142015-04-22 13:56:20 -07004071 CHECK(m != nullptr);
Elliott Hughesd07986f2011-12-06 18:27:45 -08004072
Roland Levillain33d69032015-06-18 18:20:59 +01004073 static_assert(sizeof(jvalue) == sizeof(uint64_t), "jvalue and uint64_t have different sizes.");
Elliott Hughesd07986f2011-12-06 18:27:45 -08004074
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004075 // Invoke the method.
Jeff Hao39b6c242015-05-19 20:30:23 -07004076 ScopedLocalRef<jobject> ref(soa.Env(), soa.AddLocalReference<jobject>(pReq->receiver.Read()));
Andreas Gampe13b27842016-11-07 16:48:23 -08004077 JValue result = InvokeWithJValues(soa, ref.get(), jni::EncodeArtMethod(m),
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004078 reinterpret_cast<jvalue*>(pReq->arg_values.get()));
Elliott Hughesd07986f2011-12-06 18:27:45 -08004079
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004080 // Prepare JDWP ids for the reply.
4081 JDWP::JdwpTag result_tag = BasicTagFromDescriptor(m->GetShorty());
4082 const bool is_object_result = (result_tag == JDWP::JT_OBJECT);
Jeff Hao064d24e2016-08-25 03:52:40 +00004083 StackHandleScope<3> hs(soa.Self());
Sebastien Hertz1558b572015-02-25 15:05:59 +01004084 Handle<mirror::Object> object_result = hs.NewHandle(is_object_result ? result.GetL() : nullptr);
4085 Handle<mirror::Throwable> exception = hs.NewHandle(soa.Self()->GetException());
4086 soa.Self()->ClearException();
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004087
4088 if (!IsDebuggerActive()) {
4089 // The debugger detached: we must not re-suspend threads. We also don't need to fill the reply
4090 // because it won't be sent either.
4091 return;
4092 }
4093
4094 JDWP::ObjectId exceptionObjectId = gRegistry->Add(exception);
4095 uint64_t result_value = 0;
4096 if (exceptionObjectId != 0) {
Sebastien Hertz1558b572015-02-25 15:05:59 +01004097 VLOG(jdwp) << " JDWP invocation returning with exception=" << exception.Get()
4098 << " " << exception->Dump();
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004099 result_value = 0;
Sebastien Hertz1558b572015-02-25 15:05:59 +01004100 } else if (is_object_result) {
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004101 /* if no exception was thrown, examine object result more closely */
Sebastien Hertz1558b572015-02-25 15:05:59 +01004102 JDWP::JdwpTag new_tag = TagFromObject(soa, object_result.Get());
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004103 if (new_tag != result_tag) {
4104 VLOG(jdwp) << " JDWP promoted result from " << result_tag << " to " << new_tag;
4105 result_tag = new_tag;
Elliott Hughesd07986f2011-12-06 18:27:45 -08004106 }
4107
Sebastien Hertz1558b572015-02-25 15:05:59 +01004108 // Register the object in the registry and reference its ObjectId. This ensures
4109 // GC safety and prevents from accessing stale reference if the object is moved.
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004110 result_value = gRegistry->Add(object_result.Get());
Sebastien Hertz1558b572015-02-25 15:05:59 +01004111 } else {
4112 // Primitive result.
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004113 DCHECK(IsPrimitiveTag(result_tag));
4114 result_value = result.GetJ();
4115 }
4116 const bool is_constructor = m->IsConstructor() && !m->IsStatic();
4117 if (is_constructor) {
4118 // If we invoked a constructor (which actually returns void), return the receiver,
4119 // unless we threw, in which case we return null.
Sebastien Hertza3e13772015-11-05 12:09:44 +01004120 DCHECK_EQ(JDWP::JT_VOID, result_tag);
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004121 if (exceptionObjectId == 0) {
Jeff Hao064d24e2016-08-25 03:52:40 +00004122 if (m->GetDeclaringClass()->IsStringClass()) {
4123 // For string constructors, the new string is remapped to the receiver (stored in ref).
4124 Handle<mirror::Object> decoded_ref = hs.NewHandle(soa.Self()->DecodeJObject(ref.get()));
4125 result_value = gRegistry->Add(decoded_ref);
4126 result_tag = TagFromObject(soa, decoded_ref.Get());
4127 } else {
4128 // TODO we could keep the receiver ObjectId in the DebugInvokeReq to avoid looking into the
4129 // object registry.
4130 result_value = GetObjectRegistry()->Add(pReq->receiver.Read());
4131 result_tag = TagFromObject(soa, pReq->receiver.Read());
4132 }
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004133 } else {
4134 result_value = 0;
Sebastien Hertza3e13772015-11-05 12:09:44 +01004135 result_tag = JDWP::JT_OBJECT;
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004136 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08004137 }
4138
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004139 // Suspend other threads if the invoke is not single-threaded.
4140 if ((pReq->options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07004141 ScopedThreadSuspension sts(soa.Self(), kWaitingForDebuggerSuspension);
Hiroshi Yamauchi8f95cf32016-04-19 11:14:06 -07004142 // Avoid a deadlock between GC and debugger where GC gets suspended during GC. b/25800335.
4143 gc::ScopedGCCriticalSection gcs(soa.Self(), gc::kGcCauseDebugger, gc::kCollectorTypeDebugger);
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004144 VLOG(jdwp) << " Suspending all threads";
4145 Runtime::Current()->GetThreadList()->SuspendAllForDebugger();
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004146 }
4147
4148 VLOG(jdwp) << " --> returned " << result_tag
4149 << StringPrintf(" %#" PRIx64 " (except=%#" PRIx64 ")", result_value,
4150 exceptionObjectId);
4151
4152 // Show detailed debug output.
4153 if (result_tag == JDWP::JT_STRING && exceptionObjectId == 0) {
4154 if (result_value != 0) {
4155 if (VLOG_IS_ON(jdwp)) {
4156 std::string result_string;
4157 JDWP::JdwpError error = Dbg::StringToUtf8(result_value, &result_string);
4158 CHECK_EQ(error, JDWP::ERR_NONE);
4159 VLOG(jdwp) << " string '" << result_string << "'";
4160 }
4161 } else {
4162 VLOG(jdwp) << " string (null)";
4163 }
4164 }
4165
4166 // Attach the reply to DebugInvokeReq so it can be sent to the debugger when the event thread
4167 // is ready to suspend.
4168 BuildInvokeReply(pReq->reply, pReq->request_id, result_tag, result_value, exceptionObjectId);
4169}
4170
4171void Dbg::BuildInvokeReply(JDWP::ExpandBuf* pReply, uint32_t request_id, JDWP::JdwpTag result_tag,
4172 uint64_t result_value, JDWP::ObjectId exception) {
4173 // Make room for the JDWP header since we do not know the size of the reply yet.
4174 JDWP::expandBufAddSpace(pReply, kJDWPHeaderLen);
4175
4176 size_t width = GetTagWidth(result_tag);
4177 JDWP::expandBufAdd1(pReply, result_tag);
4178 if (width != 0) {
4179 WriteValue(pReply, width, result_value);
4180 }
4181 JDWP::expandBufAdd1(pReply, JDWP::JT_OBJECT);
4182 JDWP::expandBufAddObjectId(pReply, exception);
4183
4184 // Now we know the size, we can complete the JDWP header.
4185 uint8_t* buf = expandBufGetBuffer(pReply);
4186 JDWP::Set4BE(buf + kJDWPHeaderSizeOffset, expandBufGetLength(pReply));
4187 JDWP::Set4BE(buf + kJDWPHeaderIdOffset, request_id);
4188 JDWP::Set1(buf + kJDWPHeaderFlagsOffset, kJDWPFlagReply); // flags
4189 JDWP::Set2BE(buf + kJDWPHeaderErrorCodeOffset, JDWP::ERR_NONE);
4190}
4191
4192void Dbg::FinishInvokeMethod(DebugInvokeReq* pReq) {
4193 CHECK_NE(Thread::Current(), GetDebugThread()) << "This must be called by the event thread";
4194
4195 JDWP::ExpandBuf* const pReply = pReq->reply;
4196 CHECK(pReply != nullptr) << "No reply attached to DebugInvokeReq";
4197
4198 // We need to prevent other threads (including JDWP thread) from interacting with the debugger
4199 // while we send the reply but are not yet suspended. The JDWP token will be released just before
4200 // we suspend ourself again (see ThreadList::SuspendSelfForDebugger).
4201 gJdwpState->AcquireJdwpTokenForEvent(pReq->thread_id);
4202
4203 // Send the reply unless the debugger detached before the completion of the method.
4204 if (IsDebuggerActive()) {
4205 const size_t replyDataLength = expandBufGetLength(pReply) - kJDWPHeaderLen;
4206 VLOG(jdwp) << StringPrintf("REPLY INVOKE id=0x%06x (length=%zu)",
4207 pReq->request_id, replyDataLength);
4208
4209 gJdwpState->SendRequest(pReply);
4210 } else {
4211 VLOG(jdwp) << "Not sending invoke reply because debugger detached";
Elliott Hughesd07986f2011-12-06 18:27:45 -08004212 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004213}
4214
Alex Light8c2b9292017-11-09 13:21:01 -08004215bool Dbg::DdmHandleChunk(JNIEnv* env,
4216 uint32_t type,
4217 const ArrayRef<const jbyte>& data,
4218 /*out*/uint32_t* out_type,
4219 /*out*/std::vector<uint8_t>* out_data) {
4220 ScopedLocalRef<jbyteArray> dataArray(env, env->NewByteArray(data.size()));
Ian Rogersc0542af2014-09-03 16:16:56 -07004221 if (dataArray.get() == nullptr) {
Alex Light8c2b9292017-11-09 13:21:01 -08004222 LOG(WARNING) << "byte[] allocation failed: " << data.size();
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004223 env->ExceptionClear();
4224 return false;
4225 }
Alex Light8c2b9292017-11-09 13:21:01 -08004226 env->SetByteArrayRegion(dataArray.get(),
4227 0,
4228 data.size(),
4229 reinterpret_cast<const jbyte*>(data.data()));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004230 // Call "private static Chunk dispatch(int type, byte[] data, int offset, int length)".
Alex Light8c2b9292017-11-09 13:21:01 -08004231 ScopedLocalRef<jobject> chunk(
4232 env,
4233 env->CallStaticObjectMethod(
4234 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
4235 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_dispatch,
4236 type, dataArray.get(), 0, data.size()));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004237 if (env->ExceptionCheck()) {
Alex Light1eeefa62018-03-19 13:47:56 -07004238 Thread* self = Thread::Current();
4239 ScopedObjectAccess soa(self);
4240 LOG(INFO) << StringPrintf("Exception thrown by dispatcher for 0x%08x", type) << std::endl
4241 << self->GetException()->Dump();
4242 self->ClearException();
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004243 return false;
4244 }
4245
Ian Rogersc0542af2014-09-03 16:16:56 -07004246 if (chunk.get() == nullptr) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004247 return false;
4248 }
4249
4250 /*
4251 * Pull the pieces out of the chunk. We copy the results into a
4252 * newly-allocated buffer that the caller can free. We don't want to
4253 * continue using the Chunk object because nothing has a reference to it.
4254 *
4255 * We could avoid this by returning type/data/offset/length and having
4256 * the caller be aware of the object lifetime issues, but that
Elliott Hughes81ff3182012-03-23 20:35:56 -07004257 * integrates the JDWP code more tightly into the rest of the runtime, and doesn't work
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004258 * if we have responses for multiple chunks.
4259 *
4260 * So we're pretty much stuck with copying data around multiple times.
4261 */
Alex Light8c2b9292017-11-09 13:21:01 -08004262 ScopedLocalRef<jbyteArray> replyData(
4263 env,
4264 reinterpret_cast<jbyteArray>(
4265 env->GetObjectField(
4266 chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_data)));
4267 jint offset = env->GetIntField(chunk.get(),
4268 WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_offset);
4269 jint length = env->GetIntField(chunk.get(),
4270 WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_length);
4271 *out_type = env->GetIntField(chunk.get(),
4272 WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_type);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004273
Alex Light8c2b9292017-11-09 13:21:01 -08004274 VLOG(jdwp) << StringPrintf("DDM reply: type=0x%08x data=%p offset=%d length=%d",
4275 type,
4276 replyData.get(),
4277 offset,
4278 length);
Alex Light8c2b9292017-11-09 13:21:01 -08004279 out_data->resize(length);
4280 env->GetByteArrayRegion(replyData.get(),
4281 offset,
4282 length,
4283 reinterpret_cast<jbyte*>(out_data->data()));
Alex Light6f2a6342017-12-12 09:55:05 -08004284
Alex Lighte5463a82017-12-12 13:33:28 -08004285 if (env->ExceptionCheck()) {
Alex Light1eeefa62018-03-19 13:47:56 -07004286 Thread* self = Thread::Current();
4287 ScopedObjectAccess soa(self);
Alex Lighte5463a82017-12-12 13:33:28 -08004288 LOG(INFO) << StringPrintf("Exception thrown when reading response data from dispatcher 0x%08x",
Alex Light1eeefa62018-03-19 13:47:56 -07004289 type) << std::endl << self->GetException()->Dump();
4290 self->ClearException();
Alex Lighte5463a82017-12-12 13:33:28 -08004291 return false;
4292 }
4293
Alex Light8c2b9292017-11-09 13:21:01 -08004294 return true;
4295}
4296
4297/*
4298 * "request" contains a full JDWP packet, possibly with multiple chunks. We
4299 * need to process each, accumulate the replies, and ship the whole thing
4300 * back.
4301 *
4302 * Returns "true" if we have a reply. The reply buffer is newly allocated,
4303 * and includes the chunk type/length, followed by the data.
4304 *
4305 * OLD-TODO: we currently assume that the request and reply include a single
4306 * chunk. If this becomes inconvenient we will need to adapt.
4307 */
4308bool Dbg::DdmHandlePacket(JDWP::Request* request, uint8_t** pReplyBuf, int* pReplyLen) {
4309 Thread* self = Thread::Current();
4310 JNIEnv* env = self->GetJniEnv();
4311
4312 uint32_t type = request->ReadUnsigned32("type");
4313 uint32_t length = request->ReadUnsigned32("length");
4314
4315 // Create a byte[] corresponding to 'request'.
4316 size_t request_length = request->size();
4317 // Run through and find all chunks. [Currently just find the first.]
4318 if (length != request_length) {
4319 LOG(WARNING) << StringPrintf("bad chunk found (len=%u pktLen=%zd)", length, request_length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004320 return false;
4321 }
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004322
Alex Light8c2b9292017-11-09 13:21:01 -08004323 ArrayRef<const jbyte> data(reinterpret_cast<const jbyte*>(request->data()), request_length);
4324 std::vector<uint8_t> out_data;
4325 uint32_t out_type = 0;
4326 request->Skip(request_length);
Alex Light6f2a6342017-12-12 09:55:05 -08004327 if (!DdmHandleChunk(env, type, data, &out_type, &out_data) || out_data.empty()) {
Alex Light8c2b9292017-11-09 13:21:01 -08004328 return false;
4329 }
4330 const uint32_t kDdmHeaderSize = 8;
4331 *pReplyLen = out_data.size() + kDdmHeaderSize;
4332 *pReplyBuf = new uint8_t[out_data.size() + kDdmHeaderSize];
4333 memcpy((*pReplyBuf) + kDdmHeaderSize, out_data.data(), out_data.size());
4334 JDWP::Set4BE(*pReplyBuf, out_type);
4335 JDWP::Set4BE((*pReplyBuf) + 4, static_cast<uint32_t>(out_data.size()));
4336 VLOG(jdwp)
4337 << StringPrintf("dvmHandleDdm returning type=%.4s", reinterpret_cast<char*>(*pReplyBuf))
4338 << "0x" << std::hex << reinterpret_cast<uintptr_t>(*pReplyBuf) << std::dec
4339 << " len= " << out_data.size();
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004340 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004341}
4342
Elliott Hughesa2155262011-11-16 16:26:58 -08004343void Dbg::DdmBroadcast(bool connect) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08004344 VLOG(jdwp) << "Broadcasting DDM " << (connect ? "connect" : "disconnect") << "...";
Elliott Hughes47fce012011-10-25 18:37:19 -07004345
4346 Thread* self = Thread::Current();
Ian Rogers50b35e22012-10-04 10:09:15 -07004347 if (self->GetState() != kRunnable) {
4348 LOG(ERROR) << "DDM broadcast in thread state " << self->GetState();
4349 /* try anyway? */
Elliott Hughes47fce012011-10-25 18:37:19 -07004350 }
4351
4352 JNIEnv* env = self->GetJniEnv();
Elliott Hughes47fce012011-10-25 18:37:19 -07004353 jint event = connect ? 1 /*DdmServer.CONNECTED*/ : 2 /*DdmServer.DISCONNECTED*/;
Elliott Hugheseac76672012-05-24 21:56:51 -07004354 env->CallStaticVoidMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
4355 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_broadcast,
4356 event);
Elliott Hughes47fce012011-10-25 18:37:19 -07004357 if (env->ExceptionCheck()) {
4358 LOG(ERROR) << "DdmServer.broadcast " << event << " failed";
4359 env->ExceptionDescribe();
4360 env->ExceptionClear();
4361 }
4362}
4363
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004364void Dbg::DdmConnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08004365 Dbg::DdmBroadcast(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004366}
4367
4368void Dbg::DdmDisconnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08004369 Dbg::DdmBroadcast(false);
Elliott Hughes47fce012011-10-25 18:37:19 -07004370 gDdmThreadNotification = false;
4371}
4372
4373/*
Elliott Hughes82188472011-11-07 18:11:48 -08004374 * Send a notification when a thread starts, stops, or changes its name.
Elliott Hughes47fce012011-10-25 18:37:19 -07004375 *
4376 * Because we broadcast the full set of threads when the notifications are
4377 * first enabled, it's possible for "thread" to be actively executing.
4378 */
Elliott Hughes82188472011-11-07 18:11:48 -08004379void Dbg::DdmSendThreadNotification(Thread* t, uint32_t type) {
Elliott Hughes47fce012011-10-25 18:37:19 -07004380 if (!gDdmThreadNotification) {
4381 return;
4382 }
4383
Alex Light772099a2017-11-21 14:05:04 -08004384 RuntimeCallbacks* cb = Runtime::Current()->GetRuntimeCallbacks();
Elliott Hughes82188472011-11-07 18:11:48 -08004385 if (type == CHUNK_TYPE("THDE")) {
Elliott Hughes47fce012011-10-25 18:37:19 -07004386 uint8_t buf[4];
Ian Rogersd9c4fc92013-10-01 19:45:43 -07004387 JDWP::Set4BE(&buf[0], t->GetThreadId());
Alex Light772099a2017-11-21 14:05:04 -08004388 cb->DdmPublishChunk(CHUNK_TYPE("THDE"), ArrayRef<const uint8_t>(buf));
Elliott Hughes82188472011-11-07 18:11:48 -08004389 } else {
4390 CHECK(type == CHUNK_TYPE("THCR") || type == CHUNK_TYPE("THNM")) << type;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004391 ScopedObjectAccessUnchecked soa(Thread::Current());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004392 StackHandleScope<1> hs(soa.Self());
Andreas Gampe08883de2016-11-08 13:20:52 -08004393 Handle<mirror::String> name(hs.NewHandle(t->GetThreadName()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004394 size_t char_count = (name != nullptr) ? name->GetLength() : 0;
4395 const jchar* chars = (name != nullptr) ? name->GetValue() : nullptr;
4396 bool is_compressed = (name != nullptr) ? name->IsCompressed() : false;
Elliott Hughes82188472011-11-07 18:11:48 -08004397
Elliott Hughes21f32d72011-11-09 17:44:13 -08004398 std::vector<uint8_t> bytes;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07004399 JDWP::Append4BE(bytes, t->GetThreadId());
jessicahandojo3aaa37b2016-07-29 14:46:37 -07004400 if (is_compressed) {
4401 const uint8_t* chars_compressed = name->GetValueCompressed();
4402 JDWP::AppendUtf16CompressedBE(bytes, chars_compressed, char_count);
4403 } else {
4404 JDWP::AppendUtf16BE(bytes, chars, char_count);
4405 }
Elliott Hughes21f32d72011-11-09 17:44:13 -08004406 CHECK_EQ(bytes.size(), char_count*2 + sizeof(uint32_t)*2);
Alex Light772099a2017-11-21 14:05:04 -08004407 cb->DdmPublishChunk(type, ArrayRef<const uint8_t>(bytes));
Elliott Hughes47fce012011-10-25 18:37:19 -07004408 }
4409}
4410
Elliott Hughes47fce012011-10-25 18:37:19 -07004411void Dbg::DdmSetThreadNotification(bool enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004412 // Enable/disable thread notifications.
Elliott Hughes47fce012011-10-25 18:37:19 -07004413 gDdmThreadNotification = enable;
4414 if (enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004415 // Suspend the VM then post thread start notifications for all threads. Threads attaching will
4416 // see a suspension in progress and block until that ends. They then post their own start
4417 // notification.
4418 SuspendVM();
4419 std::list<Thread*> threads;
Ian Rogers50b35e22012-10-04 10:09:15 -07004420 Thread* self = Thread::Current();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004421 {
Ian Rogers50b35e22012-10-04 10:09:15 -07004422 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004423 threads = Runtime::Current()->GetThreadList()->GetList();
4424 }
4425 {
Ian Rogers50b35e22012-10-04 10:09:15 -07004426 ScopedObjectAccess soa(self);
Mathieu Chartier02e25112013-08-14 16:14:24 -07004427 for (Thread* thread : threads) {
4428 Dbg::DdmSendThreadNotification(thread, CHUNK_TYPE("THCR"));
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004429 }
4430 }
4431 ResumeVM();
Elliott Hughes47fce012011-10-25 18:37:19 -07004432 }
4433}
4434
Elliott Hughesa2155262011-11-16 16:26:58 -08004435void Dbg::PostThreadStartOrStop(Thread* t, uint32_t type) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07004436 if (IsDebuggerActive()) {
Sebastien Hertz6995c602014-09-09 12:10:13 +02004437 gJdwpState->PostThreadChange(t, type == CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07004438 }
Elliott Hughes82188472011-11-07 18:11:48 -08004439 Dbg::DdmSendThreadNotification(t, type);
Elliott Hughes47fce012011-10-25 18:37:19 -07004440}
4441
4442void Dbg::PostThreadStart(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004443 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07004444}
4445
4446void Dbg::PostThreadDeath(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004447 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THDE"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004448}
4449
Mathieu Chartierad466ad2015-01-08 16:28:08 -08004450JDWP::JdwpState* Dbg::GetJdwpState() {
4451 return gJdwpState;
4452}
4453
Elliott Hughes767a1472011-10-26 18:49:02 -07004454int Dbg::DdmHandleHpifChunk(HpifWhen when) {
4455 if (when == HPIF_WHEN_NOW) {
Elliott Hughes7162ad92011-10-27 14:08:42 -07004456 DdmSendHeapInfo(when);
Andreas Gampe7c5acbb2018-09-20 13:54:52 -07004457 return 1;
Elliott Hughes767a1472011-10-26 18:49:02 -07004458 }
4459
4460 if (when != HPIF_WHEN_NEVER && when != HPIF_WHEN_NEXT_GC && when != HPIF_WHEN_EVERY_GC) {
4461 LOG(ERROR) << "invalid HpifWhen value: " << static_cast<int>(when);
Andreas Gampe7c5acbb2018-09-20 13:54:52 -07004462 return 0;
Elliott Hughes767a1472011-10-26 18:49:02 -07004463 }
4464
4465 gDdmHpifWhen = when;
Andreas Gampe7c5acbb2018-09-20 13:54:52 -07004466 return 1;
Elliott Hughes767a1472011-10-26 18:49:02 -07004467}
4468
4469bool Dbg::DdmHandleHpsgNhsgChunk(Dbg::HpsgWhen when, Dbg::HpsgWhat what, bool native) {
4470 if (when != HPSG_WHEN_NEVER && when != HPSG_WHEN_EVERY_GC) {
4471 LOG(ERROR) << "invalid HpsgWhen value: " << static_cast<int>(when);
4472 return false;
4473 }
4474
4475 if (what != HPSG_WHAT_MERGED_OBJECTS && what != HPSG_WHAT_DISTINCT_OBJECTS) {
4476 LOG(ERROR) << "invalid HpsgWhat value: " << static_cast<int>(what);
4477 return false;
4478 }
4479
4480 if (native) {
4481 gDdmNhsgWhen = when;
4482 gDdmNhsgWhat = what;
4483 } else {
4484 gDdmHpsgWhen = when;
4485 gDdmHpsgWhat = what;
4486 }
4487 return true;
4488}
4489
Elliott Hughes7162ad92011-10-27 14:08:42 -07004490void Dbg::DdmSendHeapInfo(HpifWhen reason) {
4491 // If there's a one-shot 'when', reset it.
4492 if (reason == gDdmHpifWhen) {
4493 if (gDdmHpifWhen == HPIF_WHEN_NEXT_GC) {
4494 gDdmHpifWhen = HPIF_WHEN_NEVER;
4495 }
4496 }
4497
4498 /*
4499 * Chunk HPIF (client --> server)
4500 *
4501 * Heap Info. General information about the heap,
4502 * suitable for a summary display.
4503 *
4504 * [u4]: number of heaps
4505 *
4506 * For each heap:
4507 * [u4]: heap ID
4508 * [u8]: timestamp in ms since Unix epoch
4509 * [u1]: capture reason (same as 'when' value from server)
4510 * [u4]: max heap size in bytes (-Xmx)
4511 * [u4]: current heap size in bytes
4512 * [u4]: current number of bytes allocated
4513 * [u4]: current number of objects allocated
4514 */
4515 uint8_t heap_count = 1;
Ian Rogers1d54e732013-05-02 21:10:01 -07004516 gc::Heap* heap = Runtime::Current()->GetHeap();
Elliott Hughes21f32d72011-11-09 17:44:13 -08004517 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08004518 JDWP::Append4BE(bytes, heap_count);
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004519 JDWP::Append4BE(bytes, 1); // Heap id (bogus; we only have one heap).
Elliott Hughes545a0642011-11-08 19:10:03 -08004520 JDWP::Append8BE(bytes, MilliTime());
4521 JDWP::Append1BE(bytes, reason);
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004522 JDWP::Append4BE(bytes, heap->GetMaxMemory()); // Max allowed heap size in bytes.
4523 JDWP::Append4BE(bytes, heap->GetTotalMemory()); // Current heap size in bytes.
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08004524 JDWP::Append4BE(bytes, heap->GetBytesAllocated());
4525 JDWP::Append4BE(bytes, heap->GetObjectsAllocated());
Elliott Hughes21f32d72011-11-09 17:44:13 -08004526 CHECK_EQ(bytes.size(), 4U + (heap_count * (4 + 8 + 1 + 4 + 4 + 4 + 4)));
Alex Light772099a2017-11-21 14:05:04 -08004527 Runtime::Current()->GetRuntimeCallbacks()->DdmPublishChunk(CHUNK_TYPE("HPIF"),
4528 ArrayRef<const uint8_t>(bytes));
Elliott Hughes767a1472011-10-26 18:49:02 -07004529}
4530
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004531enum HpsgSolidity {
4532 SOLIDITY_FREE = 0,
4533 SOLIDITY_HARD = 1,
4534 SOLIDITY_SOFT = 2,
4535 SOLIDITY_WEAK = 3,
4536 SOLIDITY_PHANTOM = 4,
4537 SOLIDITY_FINALIZABLE = 5,
4538 SOLIDITY_SWEEP = 6,
4539};
4540
4541enum HpsgKind {
4542 KIND_OBJECT = 0,
4543 KIND_CLASS_OBJECT = 1,
4544 KIND_ARRAY_1 = 2,
4545 KIND_ARRAY_2 = 3,
4546 KIND_ARRAY_4 = 4,
4547 KIND_ARRAY_8 = 5,
4548 KIND_UNKNOWN = 6,
4549 KIND_NATIVE = 7,
4550};
4551
4552#define HPSG_PARTIAL (1<<7)
4553#define HPSG_STATE(solidity, kind) ((uint8_t)((((kind) & 0x7) << 3) | ((solidity) & 0x7)))
4554
Ian Rogers30fab402012-01-23 15:43:46 -08004555class HeapChunkContext {
4556 public:
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004557 // Maximum chunk size. Obtain this from the formula:
4558 // (((maximum_heap_size / ALLOCATION_UNIT_SIZE) + 255) / 256) * 2
4559 HeapChunkContext(bool merge, bool native)
Ian Rogers30fab402012-01-23 15:43:46 -08004560 : buf_(16384 - 16),
4561 type_(0),
Mathieu Chartier36dab362014-07-30 14:59:56 -07004562 chunk_overhead_(0) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004563 Reset();
4564 if (native) {
Ian Rogers30fab402012-01-23 15:43:46 -08004565 type_ = CHUNK_TYPE("NHSG");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004566 } else {
Ian Rogers30fab402012-01-23 15:43:46 -08004567 type_ = merge ? CHUNK_TYPE("HPSG") : CHUNK_TYPE("HPSO");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004568 }
4569 }
4570
4571 ~HeapChunkContext() {
Ian Rogers30fab402012-01-23 15:43:46 -08004572 if (p_ > &buf_[0]) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004573 Flush();
4574 }
4575 }
4576
Mathieu Chartier36dab362014-07-30 14:59:56 -07004577 void SetChunkOverhead(size_t chunk_overhead) {
4578 chunk_overhead_ = chunk_overhead;
4579 }
4580
4581 void ResetStartOfNextChunk() {
4582 startOfNextMemoryChunk_ = nullptr;
4583 }
4584
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004585 void EnsureHeader(const void* chunk_ptr) {
Ian Rogers30fab402012-01-23 15:43:46 -08004586 if (!needHeader_) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004587 return;
4588 }
4589
4590 // Start a new HPSx chunk.
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004591 JDWP::Write4BE(&p_, 1); // Heap id (bogus; we only have one heap).
4592 JDWP::Write1BE(&p_, 8); // Size of allocation unit, in bytes.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004593
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004594 JDWP::Write4BE(&p_, reinterpret_cast<uintptr_t>(chunk_ptr)); // virtual address of segment start.
4595 JDWP::Write4BE(&p_, 0); // offset of this piece (relative to the virtual address).
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004596 // [u4]: length of piece, in allocation units
4597 // 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 -08004598 pieceLenField_ = p_;
4599 JDWP::Write4BE(&p_, 0x55555555);
4600 needHeader_ = false;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004601 }
4602
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004603 void Flush() REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -07004604 if (pieceLenField_ == nullptr) {
Ian Rogersd636b062013-01-18 17:51:18 -08004605 // Flush immediately post Reset (maybe back-to-back Flush). Ignore.
4606 CHECK(needHeader_);
4607 return;
4608 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004609 // Patch the "length of piece" field.
Ian Rogers30fab402012-01-23 15:43:46 -08004610 CHECK_LE(&buf_[0], pieceLenField_);
4611 CHECK_LE(pieceLenField_, p_);
4612 JDWP::Set4BE(pieceLenField_, totalAllocationUnits_);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004613
Alex Light772099a2017-11-21 14:05:04 -08004614 ArrayRef<const uint8_t> out(&buf_[0], p_ - &buf_[0]);
4615 Runtime::Current()->GetRuntimeCallbacks()->DdmPublishChunk(type_, out);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004616 Reset();
4617 }
4618
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004619 static void HeapChunkJavaCallback(void* start, void* end, size_t used_bytes, void* arg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004620 REQUIRES_SHARED(Locks::heap_bitmap_lock_,
Ian Rogersb726dcb2012-09-05 08:57:23 -07004621 Locks::mutator_lock_) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004622 reinterpret_cast<HeapChunkContext*>(arg)->HeapChunkJavaCallback(start, end, used_bytes);
4623 }
4624
4625 static void HeapChunkNativeCallback(void* start, void* end, size_t used_bytes, void* arg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004626 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004627 reinterpret_cast<HeapChunkContext*>(arg)->HeapChunkNativeCallback(start, end, used_bytes);
Elliott Hughesa2155262011-11-16 16:26:58 -08004628 }
4629
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004630 private:
Elliott Hughesa2155262011-11-16 16:26:58 -08004631 enum { ALLOCATION_UNIT_SIZE = 8 };
4632
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004633 void Reset() {
Ian Rogers30fab402012-01-23 15:43:46 -08004634 p_ = &buf_[0];
Mathieu Chartier36dab362014-07-30 14:59:56 -07004635 ResetStartOfNextChunk();
Ian Rogers30fab402012-01-23 15:43:46 -08004636 totalAllocationUnits_ = 0;
4637 needHeader_ = true;
Ian Rogersc0542af2014-09-03 16:16:56 -07004638 pieceLenField_ = nullptr;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004639 }
4640
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004641 bool IsNative() const {
4642 return type_ == CHUNK_TYPE("NHSG");
4643 }
4644
4645 // Returns true if the object is not an empty chunk.
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004646 bool ProcessRecord(void* start, size_t used_bytes) REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers30fab402012-01-23 15:43:46 -08004647 // Note: heap call backs cannot manipulate the heap upon which they are crawling, care is taken
4648 // in the following code not to allocate memory, by ensuring buf_ is of the correct size
Ian Rogers15bf2d32012-08-28 17:33:04 -07004649 if (used_bytes == 0) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004650 if (start == nullptr) {
4651 // Reset for start of new heap.
4652 startOfNextMemoryChunk_ = nullptr;
4653 Flush();
4654 }
4655 // Only process in use memory so that free region information
4656 // also includes dlmalloc book keeping.
4657 return false;
Elliott Hughesa2155262011-11-16 16:26:58 -08004658 }
Ian Rogersc0542af2014-09-03 16:16:56 -07004659 if (startOfNextMemoryChunk_ != nullptr) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004660 // Transmit any pending free memory. Native free memory of over kMaxFreeLen could be because
4661 // of the use of mmaps, so don't report. If not free memory then start a new segment.
4662 bool flush = true;
4663 if (start > startOfNextMemoryChunk_) {
4664 const size_t kMaxFreeLen = 2 * kPageSize;
4665 void* free_start = startOfNextMemoryChunk_;
4666 void* free_end = start;
4667 const size_t free_len =
4668 reinterpret_cast<uintptr_t>(free_end) - reinterpret_cast<uintptr_t>(free_start);
4669 if (!IsNative() || free_len < kMaxFreeLen) {
4670 AppendChunk(HPSG_STATE(SOLIDITY_FREE, 0), free_start, free_len, IsNative());
4671 flush = false;
Ian Rogers15bf2d32012-08-28 17:33:04 -07004672 }
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004673 }
4674 if (flush) {
4675 startOfNextMemoryChunk_ = nullptr;
4676 Flush();
4677 }
Ian Rogers15bf2d32012-08-28 17:33:04 -07004678 }
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004679 return true;
Ian Rogers15bf2d32012-08-28 17:33:04 -07004680 }
Elliott Hughesa2155262011-11-16 16:26:58 -08004681
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004682 void HeapChunkNativeCallback(void* start, void* /*end*/, size_t used_bytes)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004683 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004684 if (ProcessRecord(start, used_bytes)) {
4685 uint8_t state = ExamineNativeObject(start);
Andreas Gampe98ea9d92018-10-19 14:06:15 -07004686 AppendChunk(state, start, used_bytes + chunk_overhead_, /*is_native=*/ true);
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004687 startOfNextMemoryChunk_ = reinterpret_cast<char*>(start) + used_bytes + chunk_overhead_;
4688 }
4689 }
4690
4691 void HeapChunkJavaCallback(void* start, void* /*end*/, size_t used_bytes)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004692 REQUIRES_SHARED(Locks::heap_bitmap_lock_, Locks::mutator_lock_) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004693 if (ProcessRecord(start, used_bytes)) {
4694 // Determine the type of this chunk.
4695 // OLD-TODO: if context.merge, see if this chunk is different from the last chunk.
4696 // If it's the same, we should combine them.
4697 uint8_t state = ExamineJavaObject(reinterpret_cast<mirror::Object*>(start));
Andreas Gampe98ea9d92018-10-19 14:06:15 -07004698 AppendChunk(state, start, used_bytes + chunk_overhead_, /*is_native=*/ false);
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004699 startOfNextMemoryChunk_ = reinterpret_cast<char*>(start) + used_bytes + chunk_overhead_;
4700 }
4701 }
4702
4703 void AppendChunk(uint8_t state, void* ptr, size_t length, bool is_native)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004704 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07004705 // Make sure there's enough room left in the buffer.
4706 // We need to use two bytes for every fractional 256 allocation units used by the chunk plus
4707 // 17 bytes for any header.
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004708 const size_t needed = ((RoundUp(length / ALLOCATION_UNIT_SIZE, 256) / 256) * 2) + 17;
4709 size_t byte_left = &buf_.back() - p_;
4710 if (byte_left < needed) {
4711 if (is_native) {
Pavel Vyssotski7522c742014-12-08 13:38:26 +06004712 // Cannot trigger memory allocation while walking native heap.
Pavel Vyssotski7522c742014-12-08 13:38:26 +06004713 return;
4714 }
Ian Rogers15bf2d32012-08-28 17:33:04 -07004715 Flush();
4716 }
4717
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004718 byte_left = &buf_.back() - p_;
4719 if (byte_left < needed) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07004720 LOG(WARNING) << "Chunk is too big to transmit (chunk_len=" << length << ", "
4721 << needed << " bytes)";
4722 return;
4723 }
4724 EnsureHeader(ptr);
Elliott Hughesa2155262011-11-16 16:26:58 -08004725 // Write out the chunk description.
Ian Rogers15bf2d32012-08-28 17:33:04 -07004726 length /= ALLOCATION_UNIT_SIZE; // Convert to allocation units.
4727 totalAllocationUnits_ += length;
4728 while (length > 256) {
Ian Rogers30fab402012-01-23 15:43:46 -08004729 *p_++ = state | HPSG_PARTIAL;
4730 *p_++ = 255; // length - 1
Ian Rogers15bf2d32012-08-28 17:33:04 -07004731 length -= 256;
Elliott Hughesa2155262011-11-16 16:26:58 -08004732 }
Ian Rogers30fab402012-01-23 15:43:46 -08004733 *p_++ = state;
Ian Rogers15bf2d32012-08-28 17:33:04 -07004734 *p_++ = length - 1;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004735 }
4736
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004737 uint8_t ExamineNativeObject(const void* p) REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004738 return p == nullptr ? HPSG_STATE(SOLIDITY_FREE, 0) : HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
4739 }
4740
Vladimir Marko83114892019-04-11 13:05:50 +01004741 uint8_t ExamineJavaObject(ObjPtr<mirror::Object> o)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004742 REQUIRES_SHARED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -07004743 if (o == nullptr) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004744 return HPSG_STATE(SOLIDITY_FREE, 0);
4745 }
Elliott Hughesa2155262011-11-16 16:26:58 -08004746 // It's an allocated chunk. Figure out what it is.
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004747 gc::Heap* heap = Runtime::Current()->GetHeap();
4748 if (!heap->IsLiveObjectLocked(o)) {
4749 LOG(ERROR) << "Invalid object in managed heap: " << o;
Elliott Hughesa2155262011-11-16 16:26:58 -08004750 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
4751 }
Vladimir Marko4617d582019-03-28 13:48:31 +00004752 ObjPtr<mirror::Class> c = o->GetClass();
Ian Rogersc0542af2014-09-03 16:16:56 -07004753 if (c == nullptr) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004754 // The object was probably just created but hasn't been initialized yet.
4755 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
4756 }
Vladimir Marko4617d582019-03-28 13:48:31 +00004757 if (!heap->IsValidObjectAddress(c.Ptr())) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07004758 LOG(ERROR) << "Invalid class for managed heap object: " << o << " " << c;
Elliott Hughesa2155262011-11-16 16:26:58 -08004759 return HPSG_STATE(SOLIDITY_HARD, KIND_UNKNOWN);
4760 }
Mathieu Chartierf26e1b32015-01-29 10:47:10 -08004761 if (c->GetClass() == nullptr) {
4762 LOG(ERROR) << "Null class of class " << c << " for object " << o;
4763 return HPSG_STATE(SOLIDITY_HARD, KIND_UNKNOWN);
4764 }
Elliott Hughesa2155262011-11-16 16:26:58 -08004765 if (c->IsClassClass()) {
4766 return HPSG_STATE(SOLIDITY_HARD, KIND_CLASS_OBJECT);
4767 }
Elliott Hughesa2155262011-11-16 16:26:58 -08004768 if (c->IsArrayClass()) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004769 switch (c->GetComponentSize()) {
4770 case 1: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_1);
4771 case 2: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_2);
4772 case 4: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
4773 case 8: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_8);
4774 }
4775 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004776 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
4777 }
4778
Ian Rogers30fab402012-01-23 15:43:46 -08004779 std::vector<uint8_t> buf_;
4780 uint8_t* p_;
4781 uint8_t* pieceLenField_;
Ian Rogers15bf2d32012-08-28 17:33:04 -07004782 void* startOfNextMemoryChunk_;
Ian Rogers30fab402012-01-23 15:43:46 -08004783 size_t totalAllocationUnits_;
4784 uint32_t type_;
Ian Rogers30fab402012-01-23 15:43:46 -08004785 bool needHeader_;
Mathieu Chartier36dab362014-07-30 14:59:56 -07004786 size_t chunk_overhead_;
Ian Rogers30fab402012-01-23 15:43:46 -08004787
Elliott Hughesa2155262011-11-16 16:26:58 -08004788 DISALLOW_COPY_AND_ASSIGN(HeapChunkContext);
4789};
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004790
4791void Dbg::DdmSendHeapSegments(bool native) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004792 Dbg::HpsgWhen when = native ? gDdmNhsgWhen : gDdmHpsgWhen;
4793 Dbg::HpsgWhat what = native ? gDdmNhsgWhat : gDdmHpsgWhat;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004794 if (when == HPSG_WHEN_NEVER) {
4795 return;
4796 }
Alex Light772099a2017-11-21 14:05:04 -08004797 RuntimeCallbacks* cb = Runtime::Current()->GetRuntimeCallbacks();
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004798 // Figure out what kind of chunks we'll be sending.
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004799 CHECK(what == HPSG_WHAT_MERGED_OBJECTS || what == HPSG_WHAT_DISTINCT_OBJECTS)
4800 << static_cast<int>(what);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004801
4802 // First, send a heap start chunk.
4803 uint8_t heap_id[4];
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004804 JDWP::Set4BE(&heap_id[0], 1); // Heap id (bogus; we only have one heap).
Alex Light772099a2017-11-21 14:05:04 -08004805 cb->DdmPublishChunk(native ? CHUNK_TYPE("NHST") : CHUNK_TYPE("HPST"),
4806 ArrayRef<const uint8_t>(heap_id));
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07004807 Thread* self = Thread::Current();
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07004808 Locks::mutator_lock_->AssertSharedHeld(self);
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07004809
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004810 // Send a series of heap segment chunks.
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004811 HeapChunkContext context(what == HPSG_WHAT_MERGED_OBJECTS, native);
Andreas Gampe0c183382017-07-13 22:26:24 -07004812 auto bump_pointer_space_visitor = [&](mirror::Object* obj)
4813 REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
4814 const size_t size = RoundUp(obj->SizeOf(), kObjectAlignment);
4815 HeapChunkContext::HeapChunkJavaCallback(
4816 obj, reinterpret_cast<void*>(reinterpret_cast<uintptr_t>(obj) + size), size, &context);
4817 };
Elliott Hughesa2155262011-11-16 16:26:58 -08004818 if (native) {
Dimitry Ivanove6465bc2015-12-14 18:55:02 -08004819 UNIMPLEMENTED(WARNING) << "Native heap inspection is not supported";
Elliott Hughesa2155262011-11-16 16:26:58 -08004820 } else {
Ian Rogers1d54e732013-05-02 21:10:01 -07004821 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartier36dab362014-07-30 14:59:56 -07004822 for (const auto& space : heap->GetContinuousSpaces()) {
4823 if (space->IsDlMallocSpace()) {
Mathieu Chartier4c69d7f2014-10-10 12:45:50 -07004824 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004825 // dlmalloc's chunk header is 2 * sizeof(size_t), but if the previous chunk is in use for an
4826 // allocation then the first sizeof(size_t) may belong to it.
4827 context.SetChunkOverhead(sizeof(size_t));
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004828 space->AsDlMallocSpace()->Walk(HeapChunkContext::HeapChunkJavaCallback, &context);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004829 } else if (space->IsRosAllocSpace()) {
4830 context.SetChunkOverhead(0);
Mathieu Chartier4c69d7f2014-10-10 12:45:50 -07004831 // Need to acquire the mutator lock before the heap bitmap lock with exclusive access since
4832 // RosAlloc's internal logic doesn't know to release and reacquire the heap bitmap lock.
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07004833 ScopedThreadSuspension sts(self, kSuspended);
Mathieu Chartier4f55e222015-09-04 13:26:21 -07004834 ScopedSuspendAll ssa(__FUNCTION__);
4835 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
4836 space->AsRosAllocSpace()->Walk(HeapChunkContext::HeapChunkJavaCallback, &context);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004837 } else if (space->IsBumpPointerSpace()) {
Mathieu Chartier4c69d7f2014-10-10 12:45:50 -07004838 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004839 context.SetChunkOverhead(0);
Andreas Gampe0c183382017-07-13 22:26:24 -07004840 space->AsBumpPointerSpace()->Walk(bump_pointer_space_visitor);
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004841 HeapChunkContext::HeapChunkJavaCallback(nullptr, nullptr, 0, &context);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08004842 } else if (space->IsRegionSpace()) {
4843 heap->IncrementDisableMovingGC(self);
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07004844 {
4845 ScopedThreadSuspension sts(self, kSuspended);
Mathieu Chartier4f55e222015-09-04 13:26:21 -07004846 ScopedSuspendAll ssa(__FUNCTION__);
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07004847 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
4848 context.SetChunkOverhead(0);
Andreas Gampe0c183382017-07-13 22:26:24 -07004849 space->AsRegionSpace()->Walk(bump_pointer_space_visitor);
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07004850 HeapChunkContext::HeapChunkJavaCallback(nullptr, nullptr, 0, &context);
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07004851 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08004852 heap->DecrementDisableMovingGC(self);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004853 } else {
4854 UNIMPLEMENTED(WARNING) << "Not counting objects in space " << *space;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07004855 }
Mathieu Chartier36dab362014-07-30 14:59:56 -07004856 context.ResetStartOfNextChunk();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07004857 }
Mathieu Chartier4c69d7f2014-10-10 12:45:50 -07004858 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07004859 // Walk the large objects, these are not in the AllocSpace.
Mathieu Chartier36dab362014-07-30 14:59:56 -07004860 context.SetChunkOverhead(0);
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004861 heap->GetLargeObjectsSpace()->Walk(HeapChunkContext::HeapChunkJavaCallback, &context);
Elliott Hughesa2155262011-11-16 16:26:58 -08004862 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004863
4864 // Finally, send a heap end chunk.
Alex Light772099a2017-11-21 14:05:04 -08004865 cb->DdmPublishChunk(native ? CHUNK_TYPE("NHEN") : CHUNK_TYPE("HPEN"),
4866 ArrayRef<const uint8_t>(heap_id));
Elliott Hughes767a1472011-10-26 18:49:02 -07004867}
4868
Brian Carlstrom306db812014-09-05 13:01:41 -07004869void Dbg::SetAllocTrackingEnabled(bool enable) {
Man Cao8c2ff642015-05-27 17:25:30 -07004870 gc::AllocRecordObjectMap::SetAllocTrackingEnabled(enable);
Elliott Hughes545a0642011-11-08 19:10:03 -08004871}
4872
4873void Dbg::DumpRecentAllocations() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004874 ScopedObjectAccess soa(Thread::Current());
Brian Carlstrom306db812014-09-05 13:01:41 -07004875 MutexLock mu(soa.Self(), *Locks::alloc_tracker_lock_);
Man Cao8c2ff642015-05-27 17:25:30 -07004876 if (!Runtime::Current()->GetHeap()->IsAllocTrackingEnabled()) {
Elliott Hughes545a0642011-11-08 19:10:03 -08004877 LOG(INFO) << "Not recording tracked allocations";
4878 return;
4879 }
Man Cao8c2ff642015-05-27 17:25:30 -07004880 gc::AllocRecordObjectMap* records = Runtime::Current()->GetHeap()->GetAllocationRecords();
4881 CHECK(records != nullptr);
Elliott Hughes545a0642011-11-08 19:10:03 -08004882
Man Cao1ed11b92015-06-11 22:47:35 -07004883 const uint16_t capped_count = CappedAllocRecordCount(records->GetRecentAllocationSize());
Brian Carlstrom306db812014-09-05 13:01:41 -07004884 uint16_t count = capped_count;
Elliott Hughes545a0642011-11-08 19:10:03 -08004885
Man Cao8c2ff642015-05-27 17:25:30 -07004886 LOG(INFO) << "Tracked allocations, (count=" << count << ")";
4887 for (auto it = records->RBegin(), end = records->REnd();
4888 count > 0 && it != end; count--, it++) {
Mathieu Chartier458b1052016-03-29 14:02:55 -07004889 const gc::AllocRecord* record = &it->second;
Elliott Hughes545a0642011-11-08 19:10:03 -08004890
Man Cao8c2ff642015-05-27 17:25:30 -07004891 LOG(INFO) << StringPrintf(" Thread %-2d %6zd bytes ", record->GetTid(), record->ByteCount())
David Sehr709b0702016-10-13 09:12:37 -07004892 << mirror::Class::PrettyClass(record->GetClass());
Elliott Hughes545a0642011-11-08 19:10:03 -08004893
Man Cao8c2ff642015-05-27 17:25:30 -07004894 for (size_t stack_frame = 0, depth = record->GetDepth(); stack_frame < depth; ++stack_frame) {
4895 const gc::AllocRecordStackTraceElement& stack_element = record->StackElement(stack_frame);
4896 ArtMethod* m = stack_element.GetMethod();
David Sehr709b0702016-10-13 09:12:37 -07004897 LOG(INFO) << " " << ArtMethod::PrettyMethod(m) << " line "
4898 << stack_element.ComputeLineNumber();
Elliott Hughes545a0642011-11-08 19:10:03 -08004899 }
4900
4901 // pause periodically to help logcat catch up
4902 if ((count % 5) == 0) {
4903 usleep(40000);
4904 }
Elliott Hughes545a0642011-11-08 19:10:03 -08004905 }
4906}
4907
4908class StringTable {
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07004909 private:
4910 struct Entry {
Andreas Gampe84eadb22017-07-07 15:08:01 -07004911 explicit Entry(const char* data_in)
4912 : data(data_in), hash(ComputeModifiedUtf8Hash(data_in)), index(0) {
4913 }
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07004914 Entry(const Entry& entry) = default;
4915 Entry(Entry&& entry) = default;
4916
4917 // Pointer to the actual string data.
4918 const char* data;
Andreas Gampe84eadb22017-07-07 15:08:01 -07004919
4920 // The hash of the data.
4921 const uint32_t hash;
4922
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07004923 // The index. This will be filled in on Finish and is not part of the ordering, so mark it
4924 // mutable.
4925 mutable uint32_t index;
4926
Andreas Gampe84eadb22017-07-07 15:08:01 -07004927 bool operator==(const Entry& other) const {
4928 return strcmp(data, other.data) == 0;
4929 }
4930 };
4931 struct EntryHash {
4932 size_t operator()(const Entry& entry) const {
4933 return entry.hash;
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07004934 }
4935 };
4936
Elliott Hughes545a0642011-11-08 19:10:03 -08004937 public:
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07004938 StringTable() : finished_(false) {
Elliott Hughes545a0642011-11-08 19:10:03 -08004939 }
4940
Andreas Gampef774a4e2017-07-06 22:15:18 -07004941 void Add(const char* str, bool copy_string) {
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07004942 DCHECK(!finished_);
Andreas Gampef774a4e2017-07-06 22:15:18 -07004943 if (UNLIKELY(copy_string)) {
4944 // Check whether it's already there.
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07004945 Entry entry(str);
4946 if (table_.find(entry) != table_.end()) {
Andreas Gampef774a4e2017-07-06 22:15:18 -07004947 return;
4948 }
Mathieu Chartier4345c462014-06-27 10:20:14 -07004949
Andreas Gampef774a4e2017-07-06 22:15:18 -07004950 // Make a copy.
4951 size_t str_len = strlen(str);
4952 char* copy = new char[str_len + 1];
4953 strlcpy(copy, str, str_len + 1);
4954 string_backup_.emplace_back(copy);
4955 str = copy;
4956 }
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07004957 Entry entry(str);
4958 table_.insert(entry);
4959 }
4960
4961 // Update all entries and give them an index. Note that this is likely not the insertion order,
4962 // as the set will with high likelihood reorder elements. Thus, Add must not be called after
4963 // Finish, and Finish must be called before IndexOf. In that case, WriteTo will walk in
4964 // the same order as Finish, and indices will agree. The order invariant, as well as indices,
4965 // are enforced through debug checks.
4966 void Finish() {
4967 DCHECK(!finished_);
4968 finished_ = true;
4969 uint32_t index = 0;
4970 for (auto& entry : table_) {
4971 entry.index = index;
4972 ++index;
4973 }
Elliott Hughes545a0642011-11-08 19:10:03 -08004974 }
4975
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004976 size_t IndexOf(const char* s) const {
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07004977 DCHECK(finished_);
4978 Entry entry(s);
4979 auto it = table_.find(entry);
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004980 if (it == table_.end()) {
4981 LOG(FATAL) << "IndexOf(\"" << s << "\") failed";
4982 }
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07004983 return it->index;
Elliott Hughes545a0642011-11-08 19:10:03 -08004984 }
4985
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004986 size_t Size() const {
Elliott Hughes545a0642011-11-08 19:10:03 -08004987 return table_.size();
4988 }
4989
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004990 void WriteTo(std::vector<uint8_t>& bytes) const {
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07004991 DCHECK(finished_);
4992 uint32_t cur_index = 0;
4993 for (const auto& entry : table_) {
4994 DCHECK_EQ(cur_index++, entry.index);
4995
4996 size_t s_len = CountModifiedUtf8Chars(entry.data);
Christopher Ferris8a354052015-04-24 17:23:53 -07004997 std::unique_ptr<uint16_t[]> s_utf16(new uint16_t[s_len]);
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07004998 ConvertModifiedUtf8ToUtf16(s_utf16.get(), entry.data);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004999 JDWP::AppendUtf16BE(bytes, s_utf16.get(), s_len);
Elliott Hughes545a0642011-11-08 19:10:03 -08005000 }
5001 }
5002
5003 private:
Andreas Gampe84eadb22017-07-07 15:08:01 -07005004 std::unordered_set<Entry, EntryHash> table_;
Andreas Gampef774a4e2017-07-06 22:15:18 -07005005 std::vector<std::unique_ptr<char[]>> string_backup_;
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07005006
5007 bool finished_;
5008
Elliott Hughes545a0642011-11-08 19:10:03 -08005009 DISALLOW_COPY_AND_ASSIGN(StringTable);
5010};
5011
Mathieu Chartiere401d142015-04-22 13:56:20 -07005012static const char* GetMethodSourceFile(ArtMethod* method)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005013 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07005014 DCHECK(method != nullptr);
5015 const char* source_file = method->GetDeclaringClassSourceFile();
Sebastien Hertz280286a2014-04-28 09:26:50 +02005016 return (source_file != nullptr) ? source_file : "";
5017}
5018
Elliott Hughes545a0642011-11-08 19:10:03 -08005019/*
5020 * The data we send to DDMS contains everything we have recorded.
5021 *
5022 * Message header (all values big-endian):
5023 * (1b) message header len (to allow future expansion); includes itself
5024 * (1b) entry header len
5025 * (1b) stack frame len
5026 * (2b) number of entries
5027 * (4b) offset to string table from start of message
5028 * (2b) number of class name strings
5029 * (2b) number of method name strings
5030 * (2b) number of source file name strings
5031 * For each entry:
5032 * (4b) total allocation size
Elliott Hughes221229c2013-01-08 18:17:50 -08005033 * (2b) thread id
Elliott Hughes545a0642011-11-08 19:10:03 -08005034 * (2b) allocated object's class name index
5035 * (1b) stack depth
5036 * For each stack frame:
5037 * (2b) method's class name
5038 * (2b) method name
5039 * (2b) method source file
5040 * (2b) line number, clipped to 32767; -2 if native; -1 if no source
5041 * (xb) class name strings
5042 * (xb) method name strings
5043 * (xb) source file strings
5044 *
5045 * As with other DDM traffic, strings are sent as a 4-byte length
5046 * followed by UTF-16 data.
5047 *
5048 * We send up 16-bit unsigned indexes into string tables. In theory there
Brian Carlstrom306db812014-09-05 13:01:41 -07005049 * can be (kMaxAllocRecordStackDepth * alloc_record_max_) unique strings in
Elliott Hughes545a0642011-11-08 19:10:03 -08005050 * each table, but in practice there should be far fewer.
5051 *
5052 * The chief reason for using a string table here is to keep the size of
5053 * the DDMS message to a minimum. This is partly to make the protocol
5054 * efficient, but also because we have to form the whole thing up all at
5055 * once in a memory buffer.
5056 *
5057 * We use separate string tables for class names, method names, and source
5058 * files to keep the indexes small. There will generally be no overlap
5059 * between the contents of these tables.
5060 */
5061jbyteArray Dbg::GetRecentAllocations() {
Ian Rogerscf7f1912014-10-22 22:06:39 -07005062 if ((false)) {
Elliott Hughes545a0642011-11-08 19:10:03 -08005063 DumpRecentAllocations();
5064 }
5065
Ian Rogers50b35e22012-10-04 10:09:15 -07005066 Thread* self = Thread::Current();
Elliott Hughes545a0642011-11-08 19:10:03 -08005067 std::vector<uint8_t> bytes;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005068 {
Brian Carlstrom306db812014-09-05 13:01:41 -07005069 MutexLock mu(self, *Locks::alloc_tracker_lock_);
Man Cao8c2ff642015-05-27 17:25:30 -07005070 gc::AllocRecordObjectMap* records = Runtime::Current()->GetHeap()->GetAllocationRecords();
5071 // In case this method is called when allocation tracker is disabled,
5072 // we should still send some data back.
5073 gc::AllocRecordObjectMap dummy;
5074 if (records == nullptr) {
5075 CHECK(!Runtime::Current()->GetHeap()->IsAllocTrackingEnabled());
5076 records = &dummy;
5077 }
Man Cao41656de2015-07-06 18:53:15 -07005078 // We don't need to wait on the condition variable records->new_record_condition_, because this
5079 // function only reads the class objects, which are already marked so it doesn't change their
5080 // reachability.
Man Cao8c2ff642015-05-27 17:25:30 -07005081
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005082 //
5083 // Part 1: generate string tables.
5084 //
5085 StringTable class_names;
5086 StringTable method_names;
5087 StringTable filenames;
Elliott Hughes545a0642011-11-08 19:10:03 -08005088
Andreas Gampeff29cee2017-07-07 11:11:15 -07005089 VLOG(jdwp) << "Collecting StringTables.";
5090
Man Cao1ed11b92015-06-11 22:47:35 -07005091 const uint16_t capped_count = CappedAllocRecordCount(records->GetRecentAllocationSize());
Brian Carlstrom306db812014-09-05 13:01:41 -07005092 uint16_t count = capped_count;
Andreas Gamped0fc7682017-07-07 14:03:08 -07005093 size_t alloc_byte_count = 0;
Man Cao8c2ff642015-05-27 17:25:30 -07005094 for (auto it = records->RBegin(), end = records->REnd();
5095 count > 0 && it != end; count--, it++) {
Mathieu Chartier458b1052016-03-29 14:02:55 -07005096 const gc::AllocRecord* record = &it->second;
Ian Rogers1ff3c982014-08-12 02:30:58 -07005097 std::string temp;
Andreas Gampef774a4e2017-07-06 22:15:18 -07005098 const char* class_descr = record->GetClassDescriptor(&temp);
5099 class_names.Add(class_descr, !temp.empty());
Andreas Gamped0fc7682017-07-07 14:03:08 -07005100
5101 // Size + tid + class name index + stack depth.
5102 alloc_byte_count += 4u + 2u + 2u + 1u;
5103
Man Cao8c2ff642015-05-27 17:25:30 -07005104 for (size_t i = 0, depth = record->GetDepth(); i < depth; i++) {
5105 ArtMethod* m = record->StackElement(i).GetMethod();
Andreas Gampef774a4e2017-07-06 22:15:18 -07005106 class_names.Add(m->GetDeclaringClassDescriptor(), false);
5107 method_names.Add(m->GetName(), false);
5108 filenames.Add(GetMethodSourceFile(m), false);
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005109 }
Andreas Gamped0fc7682017-07-07 14:03:08 -07005110
5111 // Depth * (class index + method name index + file name index + line number).
5112 alloc_byte_count += record->GetDepth() * (2u + 2u + 2u + 2u);
Elliott Hughes545a0642011-11-08 19:10:03 -08005113 }
5114
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07005115 class_names.Finish();
5116 method_names.Finish();
5117 filenames.Finish();
Andreas Gampeff29cee2017-07-07 11:11:15 -07005118 VLOG(jdwp) << "Done collecting StringTables:" << std::endl
5119 << " ClassNames: " << class_names.Size() << std::endl
5120 << " MethodNames: " << method_names.Size() << std::endl
5121 << " Filenames: " << filenames.Size();
5122
Man Cao8c2ff642015-05-27 17:25:30 -07005123 LOG(INFO) << "recent allocation records: " << capped_count;
5124 LOG(INFO) << "allocation records all objects: " << records->Size();
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005125
5126 //
5127 // Part 2: Generate the output and store it in the buffer.
5128 //
5129
5130 // (1b) message header len (to allow future expansion); includes itself
5131 // (1b) entry header len
5132 // (1b) stack frame len
5133 const int kMessageHeaderLen = 15;
5134 const int kEntryHeaderLen = 9;
5135 const int kStackFrameLen = 8;
5136 JDWP::Append1BE(bytes, kMessageHeaderLen);
5137 JDWP::Append1BE(bytes, kEntryHeaderLen);
5138 JDWP::Append1BE(bytes, kStackFrameLen);
5139
5140 // (2b) number of entries
5141 // (4b) offset to string table from start of message
5142 // (2b) number of class name strings
5143 // (2b) number of method name strings
5144 // (2b) number of source file name strings
Brian Carlstrom306db812014-09-05 13:01:41 -07005145 JDWP::Append2BE(bytes, capped_count);
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005146 size_t string_table_offset = bytes.size();
Brian Carlstrom7934ac22013-07-26 10:54:15 -07005147 JDWP::Append4BE(bytes, 0); // We'll patch this later...
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005148 JDWP::Append2BE(bytes, class_names.Size());
5149 JDWP::Append2BE(bytes, method_names.Size());
5150 JDWP::Append2BE(bytes, filenames.Size());
5151
Andreas Gampeff29cee2017-07-07 11:11:15 -07005152 VLOG(jdwp) << "Dumping allocations with stacks";
5153
Andreas Gamped0fc7682017-07-07 14:03:08 -07005154 // Enlarge the vector for the allocation data.
5155 size_t reserve_size = bytes.size() + alloc_byte_count;
5156 bytes.reserve(reserve_size);
5157
Ian Rogers1ff3c982014-08-12 02:30:58 -07005158 std::string temp;
Man Cao8c2ff642015-05-27 17:25:30 -07005159 count = capped_count;
5160 // The last "count" number of allocation records in "records" are the most recent "count" number
5161 // of allocations. Reverse iterate to get them. The most recent allocation is sent first.
5162 for (auto it = records->RBegin(), end = records->REnd();
5163 count > 0 && it != end; count--, it++) {
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005164 // For each entry:
5165 // (4b) total allocation size
5166 // (2b) thread id
5167 // (2b) allocated object's class name index
5168 // (1b) stack depth
Mathieu Chartier458b1052016-03-29 14:02:55 -07005169 const gc::AllocRecord* record = &it->second;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005170 size_t stack_depth = record->GetDepth();
Mathieu Chartierf8322842014-05-16 10:59:25 -07005171 size_t allocated_object_class_name_index =
Man Cao41656de2015-07-06 18:53:15 -07005172 class_names.IndexOf(record->GetClassDescriptor(&temp));
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07005173 JDWP::Append4BE(bytes, record->ByteCount());
Man Cao8c2ff642015-05-27 17:25:30 -07005174 JDWP::Append2BE(bytes, static_cast<uint16_t>(record->GetTid()));
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005175 JDWP::Append2BE(bytes, allocated_object_class_name_index);
5176 JDWP::Append1BE(bytes, stack_depth);
5177
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005178 for (size_t stack_frame = 0; stack_frame < stack_depth; ++stack_frame) {
5179 // For each stack frame:
5180 // (2b) method's class name
5181 // (2b) method name
5182 // (2b) method source file
5183 // (2b) line number, clipped to 32767; -2 if native; -1 if no source
Man Cao8c2ff642015-05-27 17:25:30 -07005184 ArtMethod* m = record->StackElement(stack_frame).GetMethod();
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07005185 size_t class_name_index = class_names.IndexOf(m->GetDeclaringClassDescriptor());
5186 size_t method_name_index = method_names.IndexOf(m->GetName());
5187 size_t file_name_index = filenames.IndexOf(GetMethodSourceFile(m));
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005188 JDWP::Append2BE(bytes, class_name_index);
5189 JDWP::Append2BE(bytes, method_name_index);
5190 JDWP::Append2BE(bytes, file_name_index);
Man Cao8c2ff642015-05-27 17:25:30 -07005191 JDWP::Append2BE(bytes, record->StackElement(stack_frame).ComputeLineNumber());
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005192 }
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005193 }
5194
Andreas Gamped0fc7682017-07-07 14:03:08 -07005195 CHECK_EQ(bytes.size(), reserve_size);
Andreas Gampeff29cee2017-07-07 11:11:15 -07005196 VLOG(jdwp) << "Dumping tables.";
5197
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005198 // (xb) class name strings
5199 // (xb) method name strings
5200 // (xb) source file strings
5201 JDWP::Set4BE(&bytes[string_table_offset], bytes.size());
5202 class_names.WriteTo(bytes);
5203 method_names.WriteTo(bytes);
5204 filenames.WriteTo(bytes);
Andreas Gampeff29cee2017-07-07 11:11:15 -07005205
5206 VLOG(jdwp) << "GetRecentAllocations: data created. " << bytes.size();
Elliott Hughes545a0642011-11-08 19:10:03 -08005207 }
Ian Rogers50b35e22012-10-04 10:09:15 -07005208 JNIEnv* env = self->GetJniEnv();
Elliott Hughes545a0642011-11-08 19:10:03 -08005209 jbyteArray result = env->NewByteArray(bytes.size());
Ian Rogersc0542af2014-09-03 16:16:56 -07005210 if (result != nullptr) {
Elliott Hughes545a0642011-11-08 19:10:03 -08005211 env->SetByteArrayRegion(result, 0, bytes.size(), reinterpret_cast<const jbyte*>(&bytes[0]));
5212 }
5213 return result;
5214}
5215
Mathieu Chartiere401d142015-04-22 13:56:20 -07005216ArtMethod* DeoptimizationRequest::Method() const {
Andreas Gampe13b27842016-11-07 16:48:23 -08005217 return jni::DecodeArtMethod(method_);
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07005218}
5219
Mathieu Chartiere401d142015-04-22 13:56:20 -07005220void DeoptimizationRequest::SetMethod(ArtMethod* m) {
Andreas Gampe13b27842016-11-07 16:48:23 -08005221 method_ = jni::EncodeArtMethod(m);
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07005222}
5223
Mathieu Chartiera6b1ead2015-10-06 10:32:38 -07005224void Dbg::VisitRoots(RootVisitor* visitor) {
5225 // Visit breakpoint roots, used to prevent unloading of methods with breakpoints.
5226 ReaderMutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
5227 BufferedRootVisitor<128> root_visitor(visitor, RootInfo(kRootVMInternal));
5228 for (Breakpoint& breakpoint : gBreakpoints) {
Andreas Gampe542451c2016-07-26 09:02:02 -07005229 breakpoint.Method()->VisitRoots(root_visitor, kRuntimePointerSize);
Mathieu Chartiera6b1ead2015-10-06 10:32:38 -07005230 }
5231}
5232
Andreas Gampe04bbb5b2017-01-19 17:49:03 +00005233void Dbg::DbgThreadLifecycleCallback::ThreadStart(Thread* self) {
5234 Dbg::PostThreadStart(self);
5235}
5236
5237void Dbg::DbgThreadLifecycleCallback::ThreadDeath(Thread* self) {
5238 Dbg::PostThreadDeath(self);
5239}
5240
Andreas Gampe0f01b582017-01-18 15:22:37 -08005241void Dbg::DbgClassLoadCallback::ClassLoad(Handle<mirror::Class> klass ATTRIBUTE_UNUSED) {
5242 // Ignore ClassLoad;
5243}
5244void Dbg::DbgClassLoadCallback::ClassPrepare(Handle<mirror::Class> temp_klass ATTRIBUTE_UNUSED,
5245 Handle<mirror::Class> klass) {
5246 Dbg::PostClassPrepare(klass.Get());
5247}
5248
Elliott Hughes872d4ec2011-10-21 17:07:15 -07005249} // namespace art