blob: 02fb5b6da43bf80cdac70dd469b364d0e3ad9ad9 [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
Andreas Gampe46ee31b2016-12-14 10:11:49 -080026#include "android-base/stringprintf.h"
27
Ian Rogers166db042013-07-26 12:05:57 -070028#include "arch/context.h"
Mathieu Chartierc7853442015-03-27 14:35:38 -070029#include "art_field-inl.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070030#include "art_method-inl.h"
Andreas Gampe542451c2016-07-26 09:02:02 -070031#include "base/enums.h"
David Sehr67bf42e2018-02-26 16:43:04 -080032#include "base/safe_map.h"
Andreas Gampef774a4e2017-07-06 22:15:18 -070033#include "base/strlcpy.h"
Vladimir Marko80afd022015-05-19 18:08:00 +010034#include "base/time_utils.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080035#include "class_linker-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -070036#include "class_linker.h"
David Sehrb2ec9f52018-02-21 13:20:31 -080037#include "dex/descriptors_names.h"
David Sehr9e734c72018-01-04 17:56:19 -080038#include "dex/dex_file-inl.h"
39#include "dex/dex_file_annotations.h"
40#include "dex/dex_file_types.h"
41#include "dex/dex_instruction.h"
David Sehr0225f8e2018-01-31 08:52:24 +000042#include "dex/utf.h"
Mingyao Yang6ea1a0e2016-01-29 12:12:49 -080043#include "entrypoints/runtime_asm_entrypoints.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070044#include "gc/accounting/card_table-inl.h"
Man Cao8c2ff642015-05-27 17:25:30 -070045#include "gc/allocation_record.h"
Andreas Gampe94c589d2017-12-27 12:43:01 -080046#include "gc/gc_cause.h"
Mathieu Chartieraa516822015-10-02 15:53:37 -070047#include "gc/scoped_gc_critical_section.h"
Andreas Gampe0c183382017-07-13 22:26:24 -070048#include "gc/space/bump_pointer_space-walk-inl.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070049#include "gc/space/large_object_space.h"
50#include "gc/space/space-inl.h"
Andreas Gampe513061a2017-06-01 09:17:34 -070051#include "handle_scope-inl.h"
Sebastien Hertzcbc50642015-06-01 17:33:12 +020052#include "jdwp/jdwp_priv.h"
Vladimir Marko83114892019-04-11 13:05:50 +010053#include "jdwp/object_registry-inl.h"
Vladimir Markoa3ad0cd2018-05-04 10:06:38 +010054#include "jni/jni_internal.h"
Mathieu Chartier28bd2e42016-10-04 13:54:57 -070055#include "jvalue-inl.h"
Andreas Gampe8e0f0432018-10-24 13:38:03 -070056#include "mirror/array-alloc-inl.h"
Andreas Gampe70f5fd02018-10-24 19:58:37 -070057#include "mirror/class-alloc-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080058#include "mirror/class-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -070059#include "mirror/class.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080060#include "mirror/class_loader.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080061#include "mirror/object-inl.h"
62#include "mirror/object_array-inl.h"
Andreas Gampefd63bbf2018-10-29 12:55:35 -070063#include "mirror/string-alloc-inl.h"
Ian Rogersb0fa5dc2014-04-28 16:47:08 -070064#include "mirror/string-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080065#include "mirror/throwable.h"
Andreas Gampe373a9b52017-10-18 09:01:57 -070066#include "nativehelper/scoped_local_ref.h"
67#include "nativehelper/scoped_primitive_array.h"
Nicolas Geoffray58cc1cb2017-11-20 13:27:29 +000068#include "oat_file.h"
Mathieu Chartier3398c782016-09-30 10:27:43 -070069#include "obj_ptr-inl.h"
Ian Rogers53b8b092014-03-13 23:45:53 -070070#include "reflection.h"
David Srbecky28f6cff2018-10-16 15:07:28 +010071#include "runtime-inl.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070072#include "scoped_thread_state_change-inl.h"
Andreas Gampe513061a2017-06-01 09:17:34 -070073#include "stack.h"
Elliott Hughes475fc232011-10-25 15:00:35 -070074#include "thread_list.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070075#include "well_known_classes.h"
Elliott Hughes475fc232011-10-25 15:00:35 -070076
Elliott Hughes872d4ec2011-10-21 17:07:15 -070077namespace art {
78
Andreas Gampe46ee31b2016-12-14 10:11:49 -080079using android::base::StringPrintf;
80
Sebastien Hertz0462c4c2015-04-01 16:34:17 +020081// The key identifying the debugger to update instrumentation.
82static constexpr const char* kDbgInstrumentationKey = "Debugger";
83
Man Cao8c2ff642015-05-27 17:25:30 -070084// 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 -070085static uint16_t CappedAllocRecordCount(size_t alloc_record_count) {
Man Cao1ed11b92015-06-11 22:47:35 -070086 const size_t cap = 0xffff;
Man Cao8c2ff642015-05-27 17:25:30 -070087 if (alloc_record_count > cap) {
88 return cap;
Brian Carlstrom306db812014-09-05 13:01:41 -070089 }
90 return alloc_record_count;
91}
Elliott Hughes475fc232011-10-25 15:00:35 -070092
Mathieu Chartier41af5e52015-10-28 11:10:46 -070093class Breakpoint : public ValueObject {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -070094 public:
Mathieu Chartier41af5e52015-10-28 11:10:46 -070095 Breakpoint(ArtMethod* method, uint32_t dex_pc, DeoptimizationRequest::Kind deoptimization_kind)
Alex Light97e78032017-06-27 17:51:55 -070096 : method_(method->GetCanonicalMethod(kRuntimePointerSize)),
Mathieu Chartier41af5e52015-10-28 11:10:46 -070097 dex_pc_(dex_pc),
98 deoptimization_kind_(deoptimization_kind) {
Sebastien Hertzf3928792014-11-17 19:00:37 +010099 CHECK(deoptimization_kind_ == DeoptimizationRequest::kNothing ||
100 deoptimization_kind_ == DeoptimizationRequest::kSelectiveDeoptimization ||
101 deoptimization_kind_ == DeoptimizationRequest::kFullDeoptimization);
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700102 }
103
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700104 Breakpoint(const Breakpoint& other) REQUIRES_SHARED(Locks::mutator_lock_)
Mathieu Chartier41af5e52015-10-28 11:10:46 -0700105 : method_(other.method_),
106 dex_pc_(other.dex_pc_),
107 deoptimization_kind_(other.deoptimization_kind_) {}
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700108
Mathieu Chartier41af5e52015-10-28 11:10:46 -0700109 // Method() is called from root visiting, do not use ScopedObjectAccess here or it can cause
110 // GC to deadlock if another thread tries to call SuspendAll while the GC is in a runnable state.
111 ArtMethod* Method() const {
112 return method_;
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700113 }
114
115 uint32_t DexPc() const {
116 return dex_pc_;
117 }
118
Sebastien Hertzf3928792014-11-17 19:00:37 +0100119 DeoptimizationRequest::Kind GetDeoptimizationKind() const {
120 return deoptimization_kind_;
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700121 }
122
Alex Light6c8467f2015-11-20 15:03:26 -0800123 // Returns true if the method of this breakpoint and the passed in method should be considered the
124 // same. That is, they are either the same method or they are copied from the same method.
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700125 bool IsInMethod(ArtMethod* m) const REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light97e78032017-06-27 17:51:55 -0700126 return method_ == m->GetCanonicalMethod(kRuntimePointerSize);
Alex Light6c8467f2015-11-20 15:03:26 -0800127 }
128
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700129 private:
Sebastien Hertza76a6d42014-03-20 16:40:17 +0100130 // The location of this breakpoint.
Mathieu Chartier41af5e52015-10-28 11:10:46 -0700131 ArtMethod* method_;
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700132 uint32_t dex_pc_;
Sebastien Hertza76a6d42014-03-20 16:40:17 +0100133
134 // Indicates whether breakpoint needs full deoptimization or selective deoptimization.
Sebastien Hertzf3928792014-11-17 19:00:37 +0100135 DeoptimizationRequest::Kind deoptimization_kind_;
Elliott Hughes86964332012-02-15 19:37:42 -0800136};
137
Sebastien Hertzed2be172014-08-19 15:33:43 +0200138static std::ostream& operator<<(std::ostream& os, const Breakpoint& rhs)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700139 REQUIRES_SHARED(Locks::mutator_lock_) {
David Sehr709b0702016-10-13 09:12:37 -0700140 os << StringPrintf("Breakpoint[%s @%#x]", ArtMethod::PrettyMethod(rhs.Method()).c_str(),
141 rhs.DexPc());
Elliott Hughes86964332012-02-15 19:37:42 -0800142 return os;
143}
144
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100145class DebugInstrumentationListener final : public instrumentation::InstrumentationListener {
Ian Rogers62d6c772013-02-27 08:32:07 -0800146 public:
147 DebugInstrumentationListener() {}
148 virtual ~DebugInstrumentationListener() {}
149
Alex Lightd7661582017-05-01 13:48:16 -0700150 void MethodEntered(Thread* thread,
151 Handle<mirror::Object> this_object,
152 ArtMethod* method,
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200153 uint32_t dex_pc)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100154 override REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800155 if (method->IsNative()) {
156 // TODO: post location events is a suspension point and native method entry stubs aren't.
157 return;
158 }
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200159 if (IsListeningToDexPcMoved()) {
160 // We also listen to kDexPcMoved instrumentation event so we know the DexPcMoved method is
161 // going to be called right after us. To avoid sending JDWP events twice for this location,
162 // we report the event in DexPcMoved. However, we must remind this is method entry so we
163 // send the METHOD_ENTRY event. And we can also group it with other events for this location
164 // like BREAKPOINT or SINGLE_STEP (or even METHOD_EXIT if this is a RETURN instruction).
165 thread->SetDebugMethodEntry();
166 } else if (IsListeningToMethodExit() && IsReturn(method, dex_pc)) {
167 // We also listen to kMethodExited instrumentation event and the current instruction is a
168 // RETURN so we know the MethodExited method is going to be called right after us. To avoid
169 // sending JDWP events twice for this location, we report the event(s) in MethodExited.
170 // However, we must remind this is method entry so we send the METHOD_ENTRY event. And we can
171 // also group it with other events for this location like BREAKPOINT or SINGLE_STEP.
172 thread->SetDebugMethodEntry();
173 } else {
Alex Lightd7661582017-05-01 13:48:16 -0700174 Dbg::UpdateDebugger(thread, this_object.Get(), method, 0, Dbg::kMethodEntry, nullptr);
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200175 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800176 }
177
Alex Lightd7661582017-05-01 13:48:16 -0700178 void MethodExited(Thread* thread,
179 Handle<mirror::Object> this_object,
180 ArtMethod* method,
181 uint32_t dex_pc,
182 const JValue& return_value)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100183 override REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800184 if (method->IsNative()) {
185 // TODO: post location events is a suspension point and native method entry stubs aren't.
186 return;
187 }
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200188 uint32_t events = Dbg::kMethodExit;
189 if (thread->IsDebugMethodEntry()) {
190 // It is also the method entry.
191 DCHECK(IsReturn(method, dex_pc));
192 events |= Dbg::kMethodEntry;
193 thread->ClearDebugMethodEntry();
194 }
Alex Lightd7661582017-05-01 13:48:16 -0700195 Dbg::UpdateDebugger(thread, this_object.Get(), method, dex_pc, events, &return_value);
Ian Rogers62d6c772013-02-27 08:32:07 -0800196 }
197
Alex Lightd7661582017-05-01 13:48:16 -0700198 void MethodUnwind(Thread* thread ATTRIBUTE_UNUSED,
199 Handle<mirror::Object> this_object ATTRIBUTE_UNUSED,
200 ArtMethod* method,
201 uint32_t dex_pc)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100202 override REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800203 // We're not recorded to listen to this kind of event, so complain.
David Sehr709b0702016-10-13 09:12:37 -0700204 LOG(ERROR) << "Unexpected method unwind event in debugger " << ArtMethod::PrettyMethod(method)
Sebastien Hertz51db44a2013-11-19 10:00:29 +0100205 << " " << dex_pc;
Ian Rogers62d6c772013-02-27 08:32:07 -0800206 }
207
Alex Lightd7661582017-05-01 13:48:16 -0700208 void DexPcMoved(Thread* thread,
209 Handle<mirror::Object> this_object,
210 ArtMethod* method,
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200211 uint32_t new_dex_pc)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100212 override REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200213 if (IsListeningToMethodExit() && IsReturn(method, new_dex_pc)) {
214 // We also listen to kMethodExited instrumentation event and the current instruction is a
215 // RETURN so we know the MethodExited method is going to be called right after us. Like in
216 // MethodEntered, we delegate event reporting to MethodExited.
217 // Besides, if this RETURN instruction is the only one in the method, we can send multiple
218 // JDWP events in the same packet: METHOD_ENTRY, METHOD_EXIT, BREAKPOINT and/or SINGLE_STEP.
219 // Therefore, we must not clear the debug method entry flag here.
220 } else {
221 uint32_t events = 0;
222 if (thread->IsDebugMethodEntry()) {
223 // It is also the method entry.
224 events = Dbg::kMethodEntry;
225 thread->ClearDebugMethodEntry();
226 }
Alex Lightd7661582017-05-01 13:48:16 -0700227 Dbg::UpdateDebugger(thread, this_object.Get(), method, new_dex_pc, events, nullptr);
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200228 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800229 }
230
Alex Lightd7661582017-05-01 13:48:16 -0700231 void FieldRead(Thread* thread ATTRIBUTE_UNUSED,
232 Handle<mirror::Object> this_object,
233 ArtMethod* method,
234 uint32_t dex_pc,
235 ArtField* field)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100236 override REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Lightd7661582017-05-01 13:48:16 -0700237 Dbg::PostFieldAccessEvent(method, dex_pc, this_object.Get(), field);
Ian Rogers62d6c772013-02-27 08:32:07 -0800238 }
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200239
Alex Lightd7661582017-05-01 13:48:16 -0700240 void FieldWritten(Thread* thread ATTRIBUTE_UNUSED,
241 Handle<mirror::Object> this_object,
242 ArtMethod* method,
243 uint32_t dex_pc,
244 ArtField* field,
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700245 const JValue& field_value)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100246 override REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Lightd7661582017-05-01 13:48:16 -0700247 Dbg::PostFieldModificationEvent(method, dex_pc, this_object.Get(), field, &field_value);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200248 }
249
Alex Light6e1607e2017-08-23 10:06:18 -0700250 void ExceptionThrown(Thread* thread ATTRIBUTE_UNUSED,
Alex Lightd7661582017-05-01 13:48:16 -0700251 Handle<mirror::Throwable> exception_object)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100252 override REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Lightd7661582017-05-01 13:48:16 -0700253 Dbg::PostException(exception_object.Get());
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200254 }
255
Nicolas Geoffray81f0f952016-01-20 16:25:19 +0000256 // We only care about branches in the Jit.
257 void Branch(Thread* /*thread*/, ArtMethod* method, uint32_t dex_pc, int32_t dex_pc_offset)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100258 override REQUIRES_SHARED(Locks::mutator_lock_) {
David Sehr709b0702016-10-13 09:12:37 -0700259 LOG(ERROR) << "Unexpected branch event in debugger " << ArtMethod::PrettyMethod(method)
Nicolas Geoffray81f0f952016-01-20 16:25:19 +0000260 << " " << dex_pc << ", " << dex_pc_offset;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800261 }
262
Alex Light798eab02017-08-23 12:54:53 -0700263 // TODO Might be worth it to post ExceptionCatch event.
264 void ExceptionHandled(Thread* thread ATTRIBUTE_UNUSED,
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100265 Handle<mirror::Throwable> throwable ATTRIBUTE_UNUSED) override {
Alex Light798eab02017-08-23 12:54:53 -0700266 LOG(ERROR) << "Unexpected exception handled event in debugger";
267 }
268
Alex Light05f47742017-09-14 00:34:44 +0000269 // TODO Might be worth it to implement this.
270 void WatchedFramePop(Thread* thread ATTRIBUTE_UNUSED,
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100271 const ShadowFrame& frame ATTRIBUTE_UNUSED) override {
Alex Light05f47742017-09-14 00:34:44 +0000272 LOG(ERROR) << "Unexpected WatchedFramePop event in debugger";
273 }
Alex Light798eab02017-08-23 12:54:53 -0700274
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200275 private:
Mathieu Chartier808c7a52017-12-15 11:19:33 -0800276 static bool IsReturn(ArtMethod* method, uint32_t dex_pc) REQUIRES_SHARED(Locks::mutator_lock_) {
277 return method->DexInstructions().InstructionAt(dex_pc).IsReturn();
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200278 }
279
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700280 static bool IsListeningToDexPcMoved() REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200281 return IsListeningTo(instrumentation::Instrumentation::kDexPcMoved);
282 }
283
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700284 static bool IsListeningToMethodExit() REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200285 return IsListeningTo(instrumentation::Instrumentation::kMethodExited);
286 }
287
288 static bool IsListeningTo(instrumentation::Instrumentation::InstrumentationEvent event)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700289 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200290 return (Dbg::GetInstrumentationEvents() & event) != 0;
291 }
292
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200293 DISALLOW_COPY_AND_ASSIGN(DebugInstrumentationListener);
Ian Rogers62d6c772013-02-27 08:32:07 -0800294} gDebugInstrumentationListener;
295
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700296// JDWP is allowed unless the Zygote forbids it.
297static bool gJdwpAllowed = true;
298
Elliott Hughesc0f09332012-03-26 13:27:06 -0700299// Was there a -Xrunjdwp or -agentlib:jdwp= argument on the command line?
Elliott Hughes3bb81562011-10-21 18:52:59 -0700300static bool gJdwpConfigured = false;
301
Sebastien Hertzb3b173b2015-02-06 09:16:32 +0100302// JDWP options for debugging. Only valid if IsJdwpConfigured() is true.
303static JDWP::JdwpOptions gJdwpOptions;
304
Elliott Hughes3bb81562011-10-21 18:52:59 -0700305// Runtime JDWP state.
Ian Rogersc0542af2014-09-03 16:16:56 -0700306static JDWP::JdwpState* gJdwpState = nullptr;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700307static bool gDebuggerConnected; // debugger or DDMS is connected.
Elliott Hughes3bb81562011-10-21 18:52:59 -0700308
Elliott Hughes47fce012011-10-25 18:37:19 -0700309static bool gDdmThreadNotification = false;
310
Elliott Hughes767a1472011-10-26 18:49:02 -0700311// DDMS GC-related settings.
312static Dbg::HpifWhen gDdmHpifWhen = Dbg::HPIF_WHEN_NEVER;
313static Dbg::HpsgWhen gDdmHpsgWhen = Dbg::HPSG_WHEN_NEVER;
314static Dbg::HpsgWhat gDdmHpsgWhat;
315static Dbg::HpsgWhen gDdmNhsgWhen = Dbg::HPSG_WHEN_NEVER;
316static Dbg::HpsgWhat gDdmNhsgWhat;
317
Daniel Mihalyieb076692014-08-22 17:33:31 +0200318bool Dbg::gDebuggerActive = false;
Sebastien Hertz4e5b2082015-03-24 19:03:40 +0100319bool Dbg::gDisposed = false;
Sebastien Hertz6995c602014-09-09 12:10:13 +0200320ObjectRegistry* Dbg::gRegistry = nullptr;
Alex Light21611932017-09-26 13:07:39 -0700321DebuggerActiveMethodInspectionCallback Dbg::gDebugActiveCallback;
Alex Light8c2b9292017-11-09 13:21:01 -0800322DebuggerDdmCallback Dbg::gDebugDdmCallback;
Alex Light40320712017-12-14 11:52:04 -0800323InternalDebuggerControlCallback Dbg::gDebuggerControlCallback;
Elliott Hughes475fc232011-10-25 15:00:35 -0700324
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100325// Deoptimization support.
Sebastien Hertz4d25df32014-03-21 17:44:46 +0100326std::vector<DeoptimizationRequest> Dbg::deoptimization_requests_;
327size_t Dbg::full_deoptimization_event_count_ = 0;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100328
Sebastien Hertz42cd43f2014-05-13 14:15:41 +0200329// Instrumentation event reference counters.
330size_t Dbg::dex_pc_change_event_ref_count_ = 0;
331size_t Dbg::method_enter_event_ref_count_ = 0;
332size_t Dbg::method_exit_event_ref_count_ = 0;
333size_t Dbg::field_read_event_ref_count_ = 0;
334size_t Dbg::field_write_event_ref_count_ = 0;
335size_t Dbg::exception_catch_event_ref_count_ = 0;
336uint32_t Dbg::instrumentation_events_ = 0;
337
Andreas Gampe04bbb5b2017-01-19 17:49:03 +0000338Dbg::DbgThreadLifecycleCallback Dbg::thread_lifecycle_callback_;
Andreas Gampe0f01b582017-01-18 15:22:37 -0800339Dbg::DbgClassLoadCallback Dbg::class_load_callback_;
Andreas Gampe04bbb5b2017-01-19 17:49:03 +0000340
Alex Light8c2b9292017-11-09 13:21:01 -0800341void DebuggerDdmCallback::DdmPublishChunk(uint32_t type, const ArrayRef<const uint8_t>& data) {
Alex Light772099a2017-11-21 14:05:04 -0800342 if (gJdwpState == nullptr) {
343 VLOG(jdwp) << "Debugger thread not active, ignoring DDM send: " << type;
344 } else {
345 iovec vec[1];
346 vec[0].iov_base = reinterpret_cast<void*>(const_cast<uint8_t*>(data.data()));
347 vec[0].iov_len = data.size();
348 gJdwpState->DdmSendChunkV(type, vec, 1);
349 }
Alex Light8c2b9292017-11-09 13:21:01 -0800350}
351
Alex Light21611932017-09-26 13:07:39 -0700352bool DebuggerActiveMethodInspectionCallback::IsMethodBeingInspected(ArtMethod* m ATTRIBUTE_UNUSED) {
353 return Dbg::IsDebuggerActive();
354}
355
Alex Light0fa17862017-10-24 13:43:05 -0700356bool DebuggerActiveMethodInspectionCallback::IsMethodSafeToJit(ArtMethod* m) {
357 return !Dbg::MethodHasAnyBreakpoints(m);
358}
359
Alex Lightf2858632018-04-02 11:28:50 -0700360bool DebuggerActiveMethodInspectionCallback::MethodNeedsDebugVersion(
361 ArtMethod* m ATTRIBUTE_UNUSED) {
362 return Dbg::IsDebuggerActive();
363}
364
Alex Light40320712017-12-14 11:52:04 -0800365void InternalDebuggerControlCallback::StartDebugger() {
366 // Release the mutator lock.
367 ScopedThreadStateChange stsc(art::Thread::Current(), kNative);
368 Dbg::StartJdwp();
369}
370
371void InternalDebuggerControlCallback::StopDebugger() {
372 Dbg::StopJdwp();
373}
374
375bool InternalDebuggerControlCallback::IsDebuggerConfigured() {
376 return Dbg::IsJdwpConfigured();
377}
378
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100379// Breakpoints.
jeffhao09bfc6a2012-12-11 18:11:43 -0800380static std::vector<Breakpoint> gBreakpoints GUARDED_BY(Locks::breakpoint_lock_);
Elliott Hughes86964332012-02-15 19:37:42 -0800381
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700382void DebugInvokeReq::VisitRoots(RootVisitor* visitor, const RootInfo& root_info) {
383 receiver.VisitRootIfNonNull(visitor, root_info); // null for static method call.
384 klass.VisitRoot(visitor, root_info);
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700385}
386
Sebastien Hertz597c4f02015-01-26 17:37:14 +0100387void SingleStepControl::AddDexPc(uint32_t dex_pc) {
388 dex_pcs_.insert(dex_pc);
Sebastien Hertzbb43b432014-04-14 11:59:08 +0200389}
390
Sebastien Hertz597c4f02015-01-26 17:37:14 +0100391bool SingleStepControl::ContainsDexPc(uint32_t dex_pc) const {
392 return dex_pcs_.find(dex_pc) == dex_pcs_.end();
Sebastien Hertzbb43b432014-04-14 11:59:08 +0200393}
394
Alex Light6c8467f2015-11-20 15:03:26 -0800395static bool IsBreakpoint(ArtMethod* m, uint32_t dex_pc)
Mathieu Chartier90443472015-07-16 20:32:27 -0700396 REQUIRES(!Locks::breakpoint_lock_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700397 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertzed2be172014-08-19 15:33:43 +0200398 ReaderMutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100399 for (size_t i = 0, e = gBreakpoints.size(); i < e; ++i) {
Alex Light6c8467f2015-11-20 15:03:26 -0800400 if (gBreakpoints[i].DexPc() == dex_pc && gBreakpoints[i].IsInMethod(m)) {
Elliott Hughes86964332012-02-15 19:37:42 -0800401 VLOG(jdwp) << "Hit breakpoint #" << i << ": " << gBreakpoints[i];
402 return true;
403 }
404 }
405 return false;
406}
407
Sebastien Hertz52d131d2014-03-13 16:17:40 +0100408static bool IsSuspendedForDebugger(ScopedObjectAccessUnchecked& soa, Thread* thread)
Mathieu Chartier90443472015-07-16 20:32:27 -0700409 REQUIRES(!Locks::thread_suspend_count_lock_) {
Elliott Hughes9e0c1752013-01-09 14:02:58 -0800410 MutexLock mu(soa.Self(), *Locks::thread_suspend_count_lock_);
411 // A thread may be suspended for GC; in this code, we really want to know whether
412 // there's a debugger suspension active.
413 return thread->IsSuspended() && thread->GetDebugSuspendCount() > 0;
414}
415
Vladimir Marko4617d582019-03-28 13:48:31 +0000416static ObjPtr<mirror::Array> DecodeNonNullArray(JDWP::RefTypeId id, JDWP::JdwpError* error)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700417 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko83114892019-04-11 13:05:50 +0100418 ObjPtr<mirror::Object> o = Dbg::GetObjectRegistry()->Get<mirror::Object>(id, error);
Ian Rogersc0542af2014-09-03 16:16:56 -0700419 if (o == nullptr) {
420 *error = JDWP::ERR_INVALID_OBJECT;
421 return nullptr;
Elliott Hughes436e3722012-02-17 20:01:47 -0800422 }
423 if (!o->IsArrayInstance()) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700424 *error = JDWP::ERR_INVALID_ARRAY;
425 return nullptr;
Elliott Hughes436e3722012-02-17 20:01:47 -0800426 }
Ian Rogersc0542af2014-09-03 16:16:56 -0700427 *error = JDWP::ERR_NONE;
Elliott Hughes436e3722012-02-17 20:01:47 -0800428 return o->AsArray();
429}
430
Vladimir Marko4617d582019-03-28 13:48:31 +0000431static ObjPtr<mirror::Class> DecodeClass(JDWP::RefTypeId id, JDWP::JdwpError* error)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700432 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko83114892019-04-11 13:05:50 +0100433 ObjPtr<mirror::Object> o = Dbg::GetObjectRegistry()->Get<mirror::Object>(id, error);
Ian Rogersc0542af2014-09-03 16:16:56 -0700434 if (o == nullptr) {
435 *error = JDWP::ERR_INVALID_OBJECT;
436 return nullptr;
Elliott Hughes436e3722012-02-17 20:01:47 -0800437 }
438 if (!o->IsClass()) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700439 *error = JDWP::ERR_INVALID_CLASS;
440 return nullptr;
Elliott Hughes436e3722012-02-17 20:01:47 -0800441 }
Ian Rogersc0542af2014-09-03 16:16:56 -0700442 *error = JDWP::ERR_NONE;
Elliott Hughes436e3722012-02-17 20:01:47 -0800443 return o->AsClass();
444}
445
Ian Rogersc0542af2014-09-03 16:16:56 -0700446static Thread* DecodeThread(ScopedObjectAccessUnchecked& soa, JDWP::ObjectId thread_id,
447 JDWP::JdwpError* error)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700448 REQUIRES_SHARED(Locks::mutator_lock_)
Mathieu Chartier90443472015-07-16 20:32:27 -0700449 REQUIRES(!Locks::thread_list_lock_, !Locks::thread_suspend_count_lock_) {
Vladimir Marko4617d582019-03-28 13:48:31 +0000450 ObjPtr<mirror::Object> thread_peer =
Vladimir Marko83114892019-04-11 13:05:50 +0100451 Dbg::GetObjectRegistry()->Get<mirror::Object>(thread_id, error);
Ian Rogersc0542af2014-09-03 16:16:56 -0700452 if (thread_peer == nullptr) {
Elliott Hughes221229c2013-01-08 18:17:50 -0800453 // This isn't even an object.
Ian Rogersc0542af2014-09-03 16:16:56 -0700454 *error = JDWP::ERR_INVALID_OBJECT;
455 return nullptr;
Elliott Hughes436e3722012-02-17 20:01:47 -0800456 }
Elliott Hughes221229c2013-01-08 18:17:50 -0800457
Mathieu Chartier0795f232016-09-27 18:43:30 -0700458 ObjPtr<mirror::Class> java_lang_Thread =
459 soa.Decode<mirror::Class>(WellKnownClasses::java_lang_Thread);
Elliott Hughes221229c2013-01-08 18:17:50 -0800460 if (!java_lang_Thread->IsAssignableFrom(thread_peer->GetClass())) {
461 // This isn't a thread.
Ian Rogersc0542af2014-09-03 16:16:56 -0700462 *error = JDWP::ERR_INVALID_THREAD;
463 return nullptr;
Elliott Hughes221229c2013-01-08 18:17:50 -0800464 }
465
Sebastien Hertz69206392015-04-07 15:54:25 +0200466 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogersc0542af2014-09-03 16:16:56 -0700467 Thread* thread = Thread::FromManagedThread(soa, thread_peer);
468 // If thread is null then this a java.lang.Thread without a Thread*. Must be a un-started or a
469 // zombie.
470 *error = (thread == nullptr) ? JDWP::ERR_THREAD_NOT_ALIVE : JDWP::ERR_NONE;
471 return thread;
Elliott Hughes436e3722012-02-17 20:01:47 -0800472}
473
Elliott Hughes24437992011-11-30 14:49:33 -0800474static JDWP::JdwpTag BasicTagFromDescriptor(const char* descriptor) {
475 // JDWP deliberately uses the descriptor characters' ASCII values for its enum.
476 // Note that by "basic" we mean that we don't get more specific than JT_OBJECT.
477 return static_cast<JDWP::JdwpTag>(descriptor[0]);
478}
479
Vladimir Markoc524e9e2019-03-26 10:54:50 +0000480static JDWP::JdwpTag BasicTagFromClass(ObjPtr<mirror::Class> klass)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700481 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers1ff3c982014-08-12 02:30:58 -0700482 std::string temp;
483 const char* descriptor = klass->GetDescriptor(&temp);
484 return BasicTagFromDescriptor(descriptor);
485}
486
Vladimir Marko83114892019-04-11 13:05:50 +0100487static JDWP::JdwpTag TagFromClass(const ScopedObjectAccessUnchecked& soa, ObjPtr<mirror::Class> c)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700488 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700489 CHECK(c != nullptr);
Elliott Hughes24437992011-11-30 14:49:33 -0800490 if (c->IsArrayClass()) {
491 return JDWP::JT_ARRAY;
492 }
Elliott Hughes24437992011-11-30 14:49:33 -0800493 if (c->IsStringClass()) {
494 return JDWP::JT_STRING;
Elliott Hughes24437992011-11-30 14:49:33 -0800495 }
Ian Rogers98379392014-02-24 16:53:16 -0800496 if (c->IsClassClass()) {
497 return JDWP::JT_CLASS_OBJECT;
498 }
499 {
Mathieu Chartier0795f232016-09-27 18:43:30 -0700500 ObjPtr<mirror::Class> thread_class =
501 soa.Decode<mirror::Class>(WellKnownClasses::java_lang_Thread);
Ian Rogers98379392014-02-24 16:53:16 -0800502 if (thread_class->IsAssignableFrom(c)) {
503 return JDWP::JT_THREAD;
504 }
505 }
506 {
Mathieu Chartier0795f232016-09-27 18:43:30 -0700507 ObjPtr<mirror::Class> thread_group_class =
508 soa.Decode<mirror::Class>(WellKnownClasses::java_lang_ThreadGroup);
Ian Rogers98379392014-02-24 16:53:16 -0800509 if (thread_group_class->IsAssignableFrom(c)) {
510 return JDWP::JT_THREAD_GROUP;
511 }
512 }
513 {
Mathieu Chartier0795f232016-09-27 18:43:30 -0700514 ObjPtr<mirror::Class> class_loader_class =
515 soa.Decode<mirror::Class>(WellKnownClasses::java_lang_ClassLoader);
Ian Rogers98379392014-02-24 16:53:16 -0800516 if (class_loader_class->IsAssignableFrom(c)) {
517 return JDWP::JT_CLASS_LOADER;
518 }
519 }
520 return JDWP::JT_OBJECT;
Elliott Hughes24437992011-11-30 14:49:33 -0800521}
522
523/*
524 * Objects declared to hold Object might actually hold a more specific
525 * type. The debugger may take a special interest in these (e.g. it
526 * wants to display the contents of Strings), so we want to return an
527 * appropriate tag.
528 *
529 * Null objects are tagged JT_OBJECT.
530 */
Vladimir Marko423bebb2019-03-26 15:17:21 +0000531JDWP::JdwpTag Dbg::TagFromObject(const ScopedObjectAccessUnchecked& soa, ObjPtr<mirror::Object> o) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700532 return (o == nullptr) ? JDWP::JT_OBJECT : TagFromClass(soa, o->GetClass());
Elliott Hughes24437992011-11-30 14:49:33 -0800533}
534
535static bool IsPrimitiveTag(JDWP::JdwpTag tag) {
536 switch (tag) {
537 case JDWP::JT_BOOLEAN:
538 case JDWP::JT_BYTE:
539 case JDWP::JT_CHAR:
540 case JDWP::JT_FLOAT:
541 case JDWP::JT_DOUBLE:
542 case JDWP::JT_INT:
543 case JDWP::JT_LONG:
544 case JDWP::JT_SHORT:
545 case JDWP::JT_VOID:
546 return true;
547 default:
548 return false;
549 }
550}
551
Sebastien Hertzb3b173b2015-02-06 09:16:32 +0100552void Dbg::StartJdwp() {
Elliott Hughesc0f09332012-03-26 13:27:06 -0700553 if (!gJdwpAllowed || !IsJdwpConfigured()) {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700554 // No JDWP for you!
555 return;
556 }
557
Ian Rogers719d1a32014-03-06 12:13:39 -0800558 CHECK(gRegistry == nullptr);
Elliott Hughes475fc232011-10-25 15:00:35 -0700559 gRegistry = new ObjectRegistry;
560
Alex Light8c2b9292017-11-09 13:21:01 -0800561 {
562 // Setup the Ddm listener
563 ScopedObjectAccess soa(Thread::Current());
564 Runtime::Current()->GetRuntimeCallbacks()->AddDdmCallback(&gDebugDdmCallback);
565 }
566
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700567 // Init JDWP if the debugger is enabled. This may connect out to a
568 // debugger, passively listen for a debugger, or block waiting for a
569 // debugger.
Sebastien Hertzb3b173b2015-02-06 09:16:32 +0100570 gJdwpState = JDWP::JdwpState::Create(&gJdwpOptions);
Ian Rogersc0542af2014-09-03 16:16:56 -0700571 if (gJdwpState == nullptr) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -0800572 // We probably failed because some other process has the port already, which means that
573 // if we don't abort the user is likely to think they're talking to us when they're actually
574 // talking to that other process.
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800575 LOG(FATAL) << "Debugger thread failed to initialize";
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700576 }
577
578 // If a debugger has already attached, send the "welcome" message.
579 // This may cause us to suspend all threads.
Elliott Hughes376a7a02011-10-24 18:35:55 -0700580 if (gJdwpState->IsActive()) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700581 ScopedObjectAccess soa(Thread::Current());
Sebastien Hertz7d955652014-10-22 10:57:10 +0200582 gJdwpState->PostVMStart();
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700583 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700584}
585
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700586void Dbg::StopJdwp() {
Sebastien Hertzc6345ef2014-08-18 19:26:39 +0200587 // Post VM_DEATH event before the JDWP connection is closed (either by the JDWP thread or the
588 // destruction of gJdwpState).
589 if (gJdwpState != nullptr && gJdwpState->IsActive()) {
590 gJdwpState->PostVMDeath();
591 }
Sebastien Hertz0376e6b2014-02-06 18:12:59 +0100592 // Prevent the JDWP thread from processing JDWP incoming packets after we close the connection.
Sebastien Hertz4e5b2082015-03-24 19:03:40 +0100593 Dispose();
Elliott Hughes376a7a02011-10-24 18:35:55 -0700594 delete gJdwpState;
Ian Rogers719d1a32014-03-06 12:13:39 -0800595 gJdwpState = nullptr;
Elliott Hughes475fc232011-10-25 15:00:35 -0700596 delete gRegistry;
Ian Rogers719d1a32014-03-06 12:13:39 -0800597 gRegistry = nullptr;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700598}
599
Elliott Hughes767a1472011-10-26 18:49:02 -0700600void Dbg::GcDidFinish() {
601 if (gDdmHpifWhen != HPIF_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700602 ScopedObjectAccess soa(Thread::Current());
Brian Carlstrom4d466a82014-05-08 19:05:29 -0700603 VLOG(jdwp) << "Sending heap info to DDM";
Elliott Hughes7162ad92011-10-27 14:08:42 -0700604 DdmSendHeapInfo(gDdmHpifWhen);
Elliott Hughes767a1472011-10-26 18:49:02 -0700605 }
606 if (gDdmHpsgWhen != HPSG_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700607 ScopedObjectAccess soa(Thread::Current());
Brian Carlstrom4d466a82014-05-08 19:05:29 -0700608 VLOG(jdwp) << "Dumping heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700609 DdmSendHeapSegments(false);
Elliott Hughes767a1472011-10-26 18:49:02 -0700610 }
611 if (gDdmNhsgWhen != HPSG_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700612 ScopedObjectAccess soa(Thread::Current());
Brian Carlstrom4d466a82014-05-08 19:05:29 -0700613 VLOG(jdwp) << "Dumping native heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700614 DdmSendHeapSegments(true);
Elliott Hughes767a1472011-10-26 18:49:02 -0700615 }
616}
617
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700618void Dbg::SetJdwpAllowed(bool allowed) {
619 gJdwpAllowed = allowed;
620}
621
Leonard Mosescueb842212016-10-06 17:26:36 -0700622bool Dbg::IsJdwpAllowed() {
623 return gJdwpAllowed;
624}
625
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700626DebugInvokeReq* Dbg::GetInvokeReq() {
Elliott Hughes475fc232011-10-25 15:00:35 -0700627 return Thread::Current()->GetInvokeReq();
628}
629
630Thread* Dbg::GetDebugThread() {
Ian Rogersc0542af2014-09-03 16:16:56 -0700631 return (gJdwpState != nullptr) ? gJdwpState->GetDebugThread() : nullptr;
Elliott Hughes475fc232011-10-25 15:00:35 -0700632}
633
634void Dbg::ClearWaitForEventThread() {
Sebastien Hertz2bf93f42015-01-09 18:44:05 +0100635 gJdwpState->ReleaseJdwpTokenForEvent();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700636}
637
638void Dbg::Connected() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700639 CHECK(!gDebuggerConnected);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800640 VLOG(jdwp) << "JDWP has attached";
Elliott Hughes3bb81562011-10-21 18:52:59 -0700641 gDebuggerConnected = true;
Elliott Hughes86964332012-02-15 19:37:42 -0800642 gDisposed = false;
643}
644
Sebastien Hertzf3928792014-11-17 19:00:37 +0100645bool Dbg::RequiresDeoptimization() {
646 // We don't need deoptimization if everything runs with interpreter after
647 // enabling -Xint mode.
648 return !Runtime::Current()->GetInstrumentation()->IsForcedInterpretOnly();
649}
650
Elliott Hughesa2155262011-11-16 16:26:58 -0800651void Dbg::GoActive() {
652 // Enable all debugging features, including scans for breakpoints.
653 // This is a no-op if we're already active.
654 // Only called from the JDWP handler thread.
Daniel Mihalyieb076692014-08-22 17:33:31 +0200655 if (IsDebuggerActive()) {
Elliott Hughesa2155262011-11-16 16:26:58 -0800656 return;
657 }
658
Mathieu Chartieraa516822015-10-02 15:53:37 -0700659 Thread* const self = Thread::Current();
Elliott Hughesc0f09332012-03-26 13:27:06 -0700660 {
661 // TODO: dalvik only warned if there were breakpoints left over. clear in Dbg::Disconnected?
Mathieu Chartieraa516822015-10-02 15:53:37 -0700662 ReaderMutexLock mu(self, *Locks::breakpoint_lock_);
Elliott Hughesc0f09332012-03-26 13:27:06 -0700663 CHECK_EQ(gBreakpoints.size(), 0U);
664 }
Elliott Hughesa2155262011-11-16 16:26:58 -0800665
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100666 {
Mathieu Chartieraa516822015-10-02 15:53:37 -0700667 MutexLock mu(self, *Locks::deoptimization_lock_);
Sebastien Hertz4d25df32014-03-21 17:44:46 +0100668 CHECK_EQ(deoptimization_requests_.size(), 0U);
669 CHECK_EQ(full_deoptimization_event_count_, 0U);
Sebastien Hertz42cd43f2014-05-13 14:15:41 +0200670 CHECK_EQ(dex_pc_change_event_ref_count_, 0U);
671 CHECK_EQ(method_enter_event_ref_count_, 0U);
672 CHECK_EQ(method_exit_event_ref_count_, 0U);
673 CHECK_EQ(field_read_event_ref_count_, 0U);
674 CHECK_EQ(field_write_event_ref_count_, 0U);
675 CHECK_EQ(exception_catch_event_ref_count_, 0U);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100676 }
677
Ian Rogers62d6c772013-02-27 08:32:07 -0800678 Runtime* runtime = Runtime::Current();
Nicolas Geoffray433b79a2017-01-30 20:54:45 +0000679 // Best effort deoptimization if the runtime is non-Java debuggable. This happens when
680 // ro.debuggable is set, but the application is not debuggable, or when a standalone
681 // dalvikvm invocation is not passed the debuggable option (-Xcompiler-option --debuggable).
682 //
683 // The performance cost of this is non-negligible during native-debugging due to the
David Srbeckyf4480162016-03-16 00:06:24 +0000684 // forced JIT, so we keep the AOT code in that case in exchange for limited native debugging.
Nicolas Geoffray226805d2018-12-14 10:59:02 +0000685 ScopedSuspendAll ssa(__FUNCTION__);
Nicolas Geoffray433b79a2017-01-30 20:54:45 +0000686 if (!runtime->IsJavaDebuggable() &&
687 !runtime->GetInstrumentation()->IsForcedInterpretOnly() &&
688 !runtime->IsNativeDebuggable()) {
689 runtime->DeoptimizeBootImage();
Mingyao Yang6ea1a0e2016-01-29 12:12:49 -0800690 }
691
Sebastien Hertzf3928792014-11-17 19:00:37 +0100692 if (RequiresDeoptimization()) {
693 runtime->GetInstrumentation()->EnableDeoptimization();
694 }
Sebastien Hertz42cd43f2014-05-13 14:15:41 +0200695 instrumentation_events_ = 0;
David Srbecky28f6cff2018-10-16 15:07:28 +0100696 Runtime::DoAndMaybeSwitchInterpreter([=](){ gDebuggerActive = true; });
Alex Light21611932017-09-26 13:07:39 -0700697 Runtime::Current()->GetRuntimeCallbacks()->AddMethodInspectionCallback(&gDebugActiveCallback);
Ian Rogers62d6c772013-02-27 08:32:07 -0800698 LOG(INFO) << "Debugger is active";
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700699}
700
701void Dbg::Disconnected() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700702 CHECK(gDebuggerConnected);
703
Elliott Hughesc0f09332012-03-26 13:27:06 -0700704 LOG(INFO) << "Debugger is no longer active";
Elliott Hughes234ab152011-10-26 14:02:26 -0700705
Hiroshi Yamauchi98810e32016-05-24 14:55:40 -0700706 // Suspend all threads and exclusively acquire the mutator lock. Remove the debugger as a listener
Ian Rogers62d6c772013-02-27 08:32:07 -0800707 // and clear the object registry.
708 Runtime* runtime = Runtime::Current();
Ian Rogers62d6c772013-02-27 08:32:07 -0800709 Thread* self = Thread::Current();
Mathieu Chartier4f55e222015-09-04 13:26:21 -0700710 {
Mathieu Chartieraa516822015-10-02 15:53:37 -0700711 // Required for DisableDeoptimization.
712 gc::ScopedGCCriticalSection gcs(self,
713 gc::kGcCauseInstrumentation,
714 gc::kCollectorTypeInstrumentation);
Mathieu Chartier4f55e222015-09-04 13:26:21 -0700715 ScopedSuspendAll ssa(__FUNCTION__);
Mathieu Chartier4f55e222015-09-04 13:26:21 -0700716 // Debugger may not be active at this point.
717 if (IsDebuggerActive()) {
718 {
719 // Since we're going to disable deoptimization, we clear the deoptimization requests queue.
720 // This prevents us from having any pending deoptimization request when the debugger attaches
721 // to us again while no event has been requested yet.
Mathieu Chartiera6b1ead2015-10-06 10:32:38 -0700722 MutexLock mu(self, *Locks::deoptimization_lock_);
Mathieu Chartier4f55e222015-09-04 13:26:21 -0700723 deoptimization_requests_.clear();
724 full_deoptimization_event_count_ = 0U;
725 }
726 if (instrumentation_events_ != 0) {
727 runtime->GetInstrumentation()->RemoveListener(&gDebugInstrumentationListener,
728 instrumentation_events_);
729 instrumentation_events_ = 0;
730 }
731 if (RequiresDeoptimization()) {
732 runtime->GetInstrumentation()->DisableDeoptimization(kDbgInstrumentationKey);
733 }
David Srbecky28f6cff2018-10-16 15:07:28 +0100734 Runtime::DoAndMaybeSwitchInterpreter([=](){ gDebuggerActive = false; });
Alex Light21611932017-09-26 13:07:39 -0700735 Runtime::Current()->GetRuntimeCallbacks()->RemoveMethodInspectionCallback(
736 &gDebugActiveCallback);
Sebastien Hertzaaea7342014-02-25 15:10:04 +0100737 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100738 }
Sebastien Hertz55f65342015-01-13 22:48:34 +0100739
740 {
741 ScopedObjectAccess soa(self);
742 gRegistry->Clear();
743 }
744
745 gDebuggerConnected = false;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700746}
747
Sebastien Hertzb3b173b2015-02-06 09:16:32 +0100748void Dbg::ConfigureJdwp(const JDWP::JdwpOptions& jdwp_options) {
749 CHECK_NE(jdwp_options.transport, JDWP::kJdwpTransportUnknown);
750 gJdwpOptions = jdwp_options;
751 gJdwpConfigured = true;
Alex Light40320712017-12-14 11:52:04 -0800752 Runtime::Current()->GetRuntimeCallbacks()->AddDebuggerControlCallback(&gDebuggerControlCallback);
Sebastien Hertzb3b173b2015-02-06 09:16:32 +0100753}
754
Elliott Hughesc0f09332012-03-26 13:27:06 -0700755bool Dbg::IsJdwpConfigured() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700756 return gJdwpConfigured;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700757}
758
759int64_t Dbg::LastDebuggerActivity() {
Elliott Hughesca951522011-12-05 12:01:32 -0800760 return gJdwpState->LastDebuggerActivity();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700761}
762
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700763void Dbg::UndoDebuggerSuspensions() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700764 Runtime::Current()->GetThreadList()->UndoDebuggerSuspensions();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700765}
766
Elliott Hughes88d63092013-01-09 09:55:54 -0800767std::string Dbg::GetClassName(JDWP::RefTypeId class_id) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700768 JDWP::JdwpError error;
Vladimir Marko83114892019-04-11 13:05:50 +0100769 ObjPtr<mirror::Object> o = gRegistry->Get<mirror::Object>(class_id, &error);
Ian Rogersc0542af2014-09-03 16:16:56 -0700770 if (o == nullptr) {
771 if (error == JDWP::ERR_NONE) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700772 return "null";
Ian Rogersc0542af2014-09-03 16:16:56 -0700773 } else {
774 return StringPrintf("invalid object %p", reinterpret_cast<void*>(class_id));
775 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800776 }
777 if (!o->IsClass()) {
Vladimir Marko4617d582019-03-28 13:48:31 +0000778 return StringPrintf("non-class %p", o.Ptr()); // This is only used for debugging output anyway.
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800779 }
Sebastien Hertz6995c602014-09-09 12:10:13 +0200780 return GetClassName(o->AsClass());
781}
782
Vladimir Marko4617d582019-03-28 13:48:31 +0000783std::string Dbg::GetClassName(ObjPtr<mirror::Class> klass) {
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +0200784 if (klass == nullptr) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700785 return "null";
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +0200786 }
Ian Rogers1ff3c982014-08-12 02:30:58 -0700787 std::string temp;
Sebastien Hertz6995c602014-09-09 12:10:13 +0200788 return DescriptorToName(klass->GetDescriptor(&temp));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700789}
790
Ian Rogersc0542af2014-09-03 16:16:56 -0700791JDWP::JdwpError Dbg::GetClassObject(JDWP::RefTypeId id, JDWP::ObjectId* class_object_id) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800792 JDWP::JdwpError status;
Vladimir Marko4617d582019-03-28 13:48:31 +0000793 ObjPtr<mirror::Class> c = DecodeClass(id, &status);
Ian Rogersc0542af2014-09-03 16:16:56 -0700794 if (c == nullptr) {
795 *class_object_id = 0;
Elliott Hughes436e3722012-02-17 20:01:47 -0800796 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800797 }
Ian Rogersc0542af2014-09-03 16:16:56 -0700798 *class_object_id = gRegistry->Add(c);
Elliott Hughes436e3722012-02-17 20:01:47 -0800799 return JDWP::ERR_NONE;
Elliott Hughes86964332012-02-15 19:37:42 -0800800}
801
Ian Rogersc0542af2014-09-03 16:16:56 -0700802JDWP::JdwpError Dbg::GetSuperclass(JDWP::RefTypeId id, JDWP::RefTypeId* superclass_id) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800803 JDWP::JdwpError status;
Vladimir Marko4617d582019-03-28 13:48:31 +0000804 ObjPtr<mirror::Class> c = DecodeClass(id, &status);
Ian Rogersc0542af2014-09-03 16:16:56 -0700805 if (c == nullptr) {
806 *superclass_id = 0;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800807 return status;
808 }
809 if (c->IsInterface()) {
810 // http://code.google.com/p/android/issues/detail?id=20856
Ian Rogersc0542af2014-09-03 16:16:56 -0700811 *superclass_id = 0;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800812 } else {
Ian Rogersc0542af2014-09-03 16:16:56 -0700813 *superclass_id = gRegistry->Add(c->GetSuperClass());
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800814 }
815 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700816}
817
Elliott Hughes436e3722012-02-17 20:01:47 -0800818JDWP::JdwpError Dbg::GetClassLoader(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700819 JDWP::JdwpError error;
Vladimir Marko4617d582019-03-28 13:48:31 +0000820 ObjPtr<mirror::Class> c = DecodeClass(id, &error);
Andreas Gampe7929a482015-12-30 19:33:49 -0800821 if (c == nullptr) {
822 return error;
Elliott Hughes436e3722012-02-17 20:01:47 -0800823 }
Andreas Gampe7929a482015-12-30 19:33:49 -0800824 expandBufAddObjectId(pReply, gRegistry->Add(c->GetClassLoader()));
Elliott Hughes436e3722012-02-17 20:01:47 -0800825 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700826}
827
Elliott Hughes436e3722012-02-17 20:01:47 -0800828JDWP::JdwpError Dbg::GetModifiers(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700829 JDWP::JdwpError error;
Vladimir Marko4617d582019-03-28 13:48:31 +0000830 ObjPtr<mirror::Class> c = DecodeClass(id, &error);
Ian Rogersc0542af2014-09-03 16:16:56 -0700831 if (c == nullptr) {
832 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800833 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800834
835 uint32_t access_flags = c->GetAccessFlags() & kAccJavaFlagsMask;
836
Yevgeny Roubande34eea2014-02-15 01:06:03 +0700837 // Set ACC_SUPER. Dex files don't contain this flag but only classes are supposed to have it set,
838 // not interfaces.
Elliott Hughes436e3722012-02-17 20:01:47 -0800839 // Class.getModifiers doesn't return it, but JDWP does, so we set it here.
Yevgeny Roubande34eea2014-02-15 01:06:03 +0700840 if ((access_flags & kAccInterface) == 0) {
841 access_flags |= kAccSuper;
842 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800843
844 expandBufAdd4BE(pReply, access_flags);
845
846 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700847}
848
Ian Rogersc0542af2014-09-03 16:16:56 -0700849JDWP::JdwpError Dbg::GetMonitorInfo(JDWP::ObjectId object_id, JDWP::ExpandBuf* reply) {
850 JDWP::JdwpError error;
Vladimir Marko67f0e9c2019-03-29 14:00:12 +0000851 Thread* self = Thread::Current();
852 StackHandleScope<1u> hs(self);
Vladimir Marko83114892019-04-11 13:05:50 +0100853 Handle<mirror::Object> o = hs.NewHandle(gRegistry->Get<mirror::Object>(object_id, &error));
Ian Rogersc0542af2014-09-03 16:16:56 -0700854 if (o == nullptr) {
Elliott Hughesf327e072013-01-09 16:01:26 -0800855 return JDWP::ERR_INVALID_OBJECT;
856 }
857
858 // Ensure all threads are suspended while we read objects' lock words.
Sebastien Hertz54263242014-03-19 18:16:50 +0100859 CHECK_EQ(self->GetState(), kRunnable);
Elliott Hughesf327e072013-01-09 16:01:26 -0800860
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700861 MonitorInfo monitor_info;
862 {
863 ScopedThreadSuspension sts(self, kSuspended);
Mathieu Chartier4f55e222015-09-04 13:26:21 -0700864 ScopedSuspendAll ssa(__FUNCTION__);
Vladimir Marko67f0e9c2019-03-29 14:00:12 +0000865 monitor_info = MonitorInfo(o.Get());
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700866 }
Ian Rogersc0542af2014-09-03 16:16:56 -0700867 if (monitor_info.owner_ != nullptr) {
Nicolas Geoffraycafa0812017-02-15 18:27:34 +0000868 expandBufAddObjectId(reply, gRegistry->Add(monitor_info.owner_->GetPeerFromOtherThread()));
Elliott Hughesf327e072013-01-09 16:01:26 -0800869 } else {
Ian Rogersc0542af2014-09-03 16:16:56 -0700870 expandBufAddObjectId(reply, gRegistry->Add(nullptr));
Elliott Hughesf327e072013-01-09 16:01:26 -0800871 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700872 expandBufAdd4BE(reply, monitor_info.entry_count_);
873 expandBufAdd4BE(reply, monitor_info.waiters_.size());
874 for (size_t i = 0; i < monitor_info.waiters_.size(); ++i) {
Nicolas Geoffraycafa0812017-02-15 18:27:34 +0000875 expandBufAddObjectId(reply, gRegistry->Add(monitor_info.waiters_[i]->GetPeerFromOtherThread()));
Elliott Hughesf327e072013-01-09 16:01:26 -0800876 }
877 return JDWP::ERR_NONE;
878}
879
Elliott Hughes734b8c62013-01-11 15:32:45 -0800880JDWP::JdwpError Dbg::GetOwnedMonitors(JDWP::ObjectId thread_id,
Ian Rogersc0542af2014-09-03 16:16:56 -0700881 std::vector<JDWP::ObjectId>* monitors,
882 std::vector<uint32_t>* stack_depths) {
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800883 struct OwnedMonitorVisitor : public StackVisitor {
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700884 OwnedMonitorVisitor(Thread* thread, Context* context,
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -0700885 std::vector<JDWP::ObjectId>* monitor_vector,
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700886 std::vector<uint32_t>* stack_depth_vector)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700887 REQUIRES_SHARED(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +0100888 : StackVisitor(thread, context, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
889 current_stack_depth(0),
890 monitors(monitor_vector),
891 stack_depths(stack_depth_vector) {}
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800892
893 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
894 // annotalysis.
Andreas Gampefa6a1b02018-09-07 08:11:55 -0700895 bool VisitFrame() override NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800896 if (!GetMethod()->IsRuntimeMethod()) {
897 Monitor::VisitLocks(this, AppendOwnedMonitors, this);
Elliott Hughes734b8c62013-01-11 15:32:45 -0800898 ++current_stack_depth;
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800899 }
900 return true;
901 }
902
Vladimir Markof52d92f2019-03-29 12:33:02 +0000903 static void AppendOwnedMonitors(ObjPtr<mirror::Object> owned_monitor, void* arg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700904 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers7a22fa62013-01-23 12:16:16 -0800905 OwnedMonitorVisitor* visitor = reinterpret_cast<OwnedMonitorVisitor*>(arg);
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -0700906 visitor->monitors->push_back(gRegistry->Add(owned_monitor));
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700907 visitor->stack_depths->push_back(visitor->current_stack_depth);
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800908 }
909
Elliott Hughes734b8c62013-01-11 15:32:45 -0800910 size_t current_stack_depth;
Ian Rogersc0542af2014-09-03 16:16:56 -0700911 std::vector<JDWP::ObjectId>* const monitors;
912 std::vector<uint32_t>* const stack_depths;
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800913 };
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800914
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700915 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz69206392015-04-07 15:54:25 +0200916 JDWP::JdwpError error;
917 Thread* thread = DecodeThread(soa, thread_id, &error);
918 if (thread == nullptr) {
919 return error;
920 }
921 if (!IsSuspendedForDebugger(soa, thread)) {
922 return JDWP::ERR_THREAD_NOT_SUSPENDED;
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700923 }
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -0700924 std::unique_ptr<Context> context(Context::Create());
Ian Rogersc0542af2014-09-03 16:16:56 -0700925 OwnedMonitorVisitor visitor(thread, context.get(), monitors, stack_depths);
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -0700926 visitor.WalkStack();
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800927 return JDWP::ERR_NONE;
928}
929
Sebastien Hertz52d131d2014-03-13 16:17:40 +0100930JDWP::JdwpError Dbg::GetContendedMonitor(JDWP::ObjectId thread_id,
Ian Rogersc0542af2014-09-03 16:16:56 -0700931 JDWP::ObjectId* contended_monitor) {
Elliott Hughesf9501702013-01-11 11:22:27 -0800932 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -0700933 *contended_monitor = 0;
Sebastien Hertz69206392015-04-07 15:54:25 +0200934 JDWP::JdwpError error;
935 Thread* thread = DecodeThread(soa, thread_id, &error);
936 if (thread == nullptr) {
937 return error;
Elliott Hughesf9501702013-01-11 11:22:27 -0800938 }
Sebastien Hertz69206392015-04-07 15:54:25 +0200939 if (!IsSuspendedForDebugger(soa, thread)) {
940 return JDWP::ERR_THREAD_NOT_SUSPENDED;
941 }
Vladimir Markof52d92f2019-03-29 12:33:02 +0000942 ObjPtr<mirror::Object> contended_monitor_obj = Monitor::GetContendedMonitor(thread);
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700943 // Add() requires the thread_list_lock_ not held to avoid the lock
944 // level violation.
Ian Rogersc0542af2014-09-03 16:16:56 -0700945 *contended_monitor = gRegistry->Add(contended_monitor_obj);
Elliott Hughesf9501702013-01-11 11:22:27 -0800946 return JDWP::ERR_NONE;
947}
948
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800949JDWP::JdwpError Dbg::GetInstanceCounts(const std::vector<JDWP::RefTypeId>& class_ids,
Ian Rogersc0542af2014-09-03 16:16:56 -0700950 std::vector<uint64_t>* counts) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800951 gc::Heap* heap = Runtime::Current()->GetHeap();
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700952 heap->CollectGarbage(/* clear_soft_references= */ false, gc::GcCause::kGcCauseDebugger);
Mathieu Chartiere8a3c572016-10-11 16:52:17 -0700953 VariableSizedHandleScope hs(Thread::Current());
Mathieu Chartier9d156d52016-10-06 17:44:26 -0700954 std::vector<Handle<mirror::Class>> classes;
Ian Rogersc0542af2014-09-03 16:16:56 -0700955 counts->clear();
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800956 for (size_t i = 0; i < class_ids.size(); ++i) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700957 JDWP::JdwpError error;
Mathieu Chartier9d156d52016-10-06 17:44:26 -0700958 ObjPtr<mirror::Class> c = DecodeClass(class_ids[i], &error);
Ian Rogersc0542af2014-09-03 16:16:56 -0700959 if (c == nullptr) {
960 return error;
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800961 }
Mathieu Chartier9d156d52016-10-06 17:44:26 -0700962 classes.push_back(hs.NewHandle(c));
Ian Rogersc0542af2014-09-03 16:16:56 -0700963 counts->push_back(0);
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800964 }
Ian Rogersc0542af2014-09-03 16:16:56 -0700965 heap->CountInstances(classes, false, &(*counts)[0]);
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800966 return JDWP::ERR_NONE;
967}
968
Ian Rogersc0542af2014-09-03 16:16:56 -0700969JDWP::JdwpError Dbg::GetInstances(JDWP::RefTypeId class_id, int32_t max_count,
970 std::vector<JDWP::ObjectId>* instances) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800971 gc::Heap* heap = Runtime::Current()->GetHeap();
972 // We only want reachable instances, so do a GC.
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700973 heap->CollectGarbage(/* clear_soft_references= */ false, gc::GcCause::kGcCauseDebugger);
Ian Rogersc0542af2014-09-03 16:16:56 -0700974 JDWP::JdwpError error;
Mathieu Chartier9d156d52016-10-06 17:44:26 -0700975 ObjPtr<mirror::Class> c = DecodeClass(class_id, &error);
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800976 if (c == nullptr) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700977 return error;
Elliott Hughes3b78c942013-01-15 17:35:41 -0800978 }
Mathieu Chartier2d855952016-10-12 19:37:59 -0700979 VariableSizedHandleScope hs(Thread::Current());
980 std::vector<Handle<mirror::Object>> raw_instances;
Richard Uhler660be6f2017-11-22 16:12:29 +0000981 Runtime::Current()->GetHeap()->GetInstances(hs,
982 hs.NewHandle(c),
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700983 /* use_is_assignable_from= */ false,
Richard Uhler660be6f2017-11-22 16:12:29 +0000984 max_count,
985 raw_instances);
Elliott Hughes3b78c942013-01-15 17:35:41 -0800986 for (size_t i = 0; i < raw_instances.size(); ++i) {
Mathieu Chartier2d855952016-10-12 19:37:59 -0700987 instances->push_back(gRegistry->Add(raw_instances[i].Get()));
Elliott Hughes3b78c942013-01-15 17:35:41 -0800988 }
989 return JDWP::ERR_NONE;
990}
991
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800992JDWP::JdwpError Dbg::GetReferringObjects(JDWP::ObjectId object_id, int32_t max_count,
Ian Rogersc0542af2014-09-03 16:16:56 -0700993 std::vector<JDWP::ObjectId>* referring_objects) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800994 gc::Heap* heap = Runtime::Current()->GetHeap();
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700995 heap->CollectGarbage(/* clear_soft_references= */ false, gc::GcCause::kGcCauseDebugger);
Ian Rogersc0542af2014-09-03 16:16:56 -0700996 JDWP::JdwpError error;
Vladimir Marko83114892019-04-11 13:05:50 +0100997 ObjPtr<mirror::Object> o = gRegistry->Get<mirror::Object>(object_id, &error);
Ian Rogersc0542af2014-09-03 16:16:56 -0700998 if (o == nullptr) {
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800999 return JDWP::ERR_INVALID_OBJECT;
1000 }
Mathieu Chartieraea9bfb2016-10-12 19:19:56 -07001001 VariableSizedHandleScope hs(Thread::Current());
1002 std::vector<Handle<mirror::Object>> raw_instances;
1003 heap->GetReferringObjects(hs, hs.NewHandle(o), max_count, raw_instances);
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001004 for (size_t i = 0; i < raw_instances.size(); ++i) {
Mathieu Chartieraea9bfb2016-10-12 19:19:56 -07001005 referring_objects->push_back(gRegistry->Add(raw_instances[i].Get()));
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001006 }
1007 return JDWP::ERR_NONE;
1008}
1009
Ian Rogersc0542af2014-09-03 16:16:56 -07001010JDWP::JdwpError Dbg::DisableCollection(JDWP::ObjectId object_id) {
1011 JDWP::JdwpError error;
Vladimir Marko83114892019-04-11 13:05:50 +01001012 ObjPtr<mirror::Object> o = gRegistry->Get<mirror::Object>(object_id, &error);
Ian Rogersc0542af2014-09-03 16:16:56 -07001013 if (o == nullptr) {
Sebastien Hertze96060a2013-12-11 12:06:28 +01001014 return JDWP::ERR_INVALID_OBJECT;
1015 }
Elliott Hughes64f574f2013-02-20 14:57:12 -08001016 gRegistry->DisableCollection(object_id);
1017 return JDWP::ERR_NONE;
1018}
1019
Ian Rogersc0542af2014-09-03 16:16:56 -07001020JDWP::JdwpError Dbg::EnableCollection(JDWP::ObjectId object_id) {
1021 JDWP::JdwpError error;
Vladimir Marko83114892019-04-11 13:05:50 +01001022 ObjPtr<mirror::Object> o = gRegistry->Get<mirror::Object>(object_id, &error);
Sebastien Hertze96060a2013-12-11 12:06:28 +01001023 // Unlike DisableCollection, JDWP specs do not state an invalid object causes an error. The RI
1024 // also ignores these cases and never return an error. However it's not obvious why this command
1025 // should behave differently from DisableCollection and IsCollected commands. So let's be more
1026 // strict and return an error if this happens.
Ian Rogersc0542af2014-09-03 16:16:56 -07001027 if (o == nullptr) {
Sebastien Hertze96060a2013-12-11 12:06:28 +01001028 return JDWP::ERR_INVALID_OBJECT;
1029 }
Elliott Hughes64f574f2013-02-20 14:57:12 -08001030 gRegistry->EnableCollection(object_id);
1031 return JDWP::ERR_NONE;
1032}
1033
Ian Rogersc0542af2014-09-03 16:16:56 -07001034JDWP::JdwpError Dbg::IsCollected(JDWP::ObjectId object_id, bool* is_collected) {
1035 *is_collected = true;
Sebastien Hertz65637eb2014-01-10 17:40:02 +01001036 if (object_id == 0) {
1037 // Null object id is invalid.
Sebastien Hertze96060a2013-12-11 12:06:28 +01001038 return JDWP::ERR_INVALID_OBJECT;
1039 }
Sebastien Hertz65637eb2014-01-10 17:40:02 +01001040 // JDWP specs state an INVALID_OBJECT error is returned if the object ID is not valid. However
1041 // the RI seems to ignore this and assume object has been collected.
Ian Rogersc0542af2014-09-03 16:16:56 -07001042 JDWP::JdwpError error;
Vladimir Marko83114892019-04-11 13:05:50 +01001043 ObjPtr<mirror::Object> o = gRegistry->Get<mirror::Object>(object_id, &error);
Ian Rogersc0542af2014-09-03 16:16:56 -07001044 if (o != nullptr) {
1045 *is_collected = gRegistry->IsCollected(object_id);
Sebastien Hertz65637eb2014-01-10 17:40:02 +01001046 }
Elliott Hughes64f574f2013-02-20 14:57:12 -08001047 return JDWP::ERR_NONE;
1048}
1049
Ian Rogersc0542af2014-09-03 16:16:56 -07001050void Dbg::DisposeObject(JDWP::ObjectId object_id, uint32_t reference_count) {
Elliott Hughes64f574f2013-02-20 14:57:12 -08001051 gRegistry->DisposeObject(object_id, reference_count);
1052}
1053
Mathieu Chartier3398c782016-09-30 10:27:43 -07001054JDWP::JdwpTypeTag Dbg::GetTypeTag(ObjPtr<mirror::Class> klass) {
Sebastien Hertz4d8fd492014-03-28 16:29:41 +01001055 DCHECK(klass != nullptr);
1056 if (klass->IsArrayClass()) {
1057 return JDWP::TT_ARRAY;
1058 } else if (klass->IsInterface()) {
1059 return JDWP::TT_INTERFACE;
1060 } else {
1061 return JDWP::TT_CLASS;
1062 }
1063}
1064
Elliott Hughes88d63092013-01-09 09:55:54 -08001065JDWP::JdwpError Dbg::GetReflectedType(JDWP::RefTypeId class_id, JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001066 JDWP::JdwpError error;
Vladimir Marko4617d582019-03-28 13:48:31 +00001067 ObjPtr<mirror::Class> c = DecodeClass(class_id, &error);
Ian Rogersc0542af2014-09-03 16:16:56 -07001068 if (c == nullptr) {
1069 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001070 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001071
Sebastien Hertz4d8fd492014-03-28 16:29:41 +01001072 JDWP::JdwpTypeTag type_tag = GetTypeTag(c);
1073 expandBufAdd1(pReply, type_tag);
Elliott Hughes88d63092013-01-09 09:55:54 -08001074 expandBufAddRefTypeId(pReply, class_id);
Elliott Hughes436e3722012-02-17 20:01:47 -08001075 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001076}
1077
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001078// Get the complete list of reference classes (i.e. all classes except
1079// the primitive types).
1080// Returns a newly-allocated buffer full of RefTypeId values.
1081class ClassListCreator : public ClassVisitor {
1082 public:
1083 explicit ClassListCreator(std::vector<JDWP::RefTypeId>* classes) : classes_(classes) {}
1084
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01001085 bool operator()(ObjPtr<mirror::Class> c) override REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001086 if (!c->IsPrimitive()) {
1087 classes_->push_back(Dbg::GetObjectRegistry()->AddRefType(c));
1088 }
1089 return true;
1090 }
1091
1092 private:
1093 std::vector<JDWP::RefTypeId>* const classes_;
1094};
1095
Ian Rogersc0542af2014-09-03 16:16:56 -07001096void Dbg::GetClassList(std::vector<JDWP::RefTypeId>* classes) {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001097 ClassListCreator clc(classes);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001098 Runtime::Current()->GetClassLinker()->VisitClassesWithoutClassesLock(&clc);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001099}
1100
Ian Rogers1ff3c982014-08-12 02:30:58 -07001101JDWP::JdwpError Dbg::GetClassInfo(JDWP::RefTypeId class_id, JDWP::JdwpTypeTag* pTypeTag,
1102 uint32_t* pStatus, std::string* pDescriptor) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001103 JDWP::JdwpError error;
Vladimir Marko4617d582019-03-28 13:48:31 +00001104 ObjPtr<mirror::Class> c = DecodeClass(class_id, &error);
Ian Rogersc0542af2014-09-03 16:16:56 -07001105 if (c == nullptr) {
1106 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001107 }
1108
Elliott Hughesa2155262011-11-16 16:26:58 -08001109 if (c->IsArrayClass()) {
1110 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
1111 *pTypeTag = JDWP::TT_ARRAY;
1112 } else {
1113 if (c->IsErroneous()) {
1114 *pStatus = JDWP::CS_ERROR;
1115 } else {
1116 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED | JDWP::CS_INITIALIZED;
1117 }
1118 *pTypeTag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
1119 }
1120
Ian Rogersc0542af2014-09-03 16:16:56 -07001121 if (pDescriptor != nullptr) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07001122 std::string temp;
1123 *pDescriptor = c->GetDescriptor(&temp);
Elliott Hughesa2155262011-11-16 16:26:58 -08001124 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001125 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001126}
1127
Ian Rogersc0542af2014-09-03 16:16:56 -07001128void Dbg::FindLoadedClassBySignature(const char* descriptor, std::vector<JDWP::RefTypeId>* ids) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001129 std::vector<ObjPtr<mirror::Class>> classes;
Igor Murashkinb1d8c312015-08-04 11:18:43 -07001130 Runtime::Current()->GetClassLinker()->LookupClasses(descriptor, classes);
Ian Rogersc0542af2014-09-03 16:16:56 -07001131 ids->clear();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001132 for (ObjPtr<mirror::Class> c : classes) {
1133 ids->push_back(gRegistry->Add(c));
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001134 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001135}
1136
Ian Rogersc0542af2014-09-03 16:16:56 -07001137JDWP::JdwpError Dbg::GetReferenceType(JDWP::ObjectId object_id, JDWP::ExpandBuf* pReply) {
1138 JDWP::JdwpError error;
Vladimir Marko83114892019-04-11 13:05:50 +01001139 ObjPtr<mirror::Object> o = gRegistry->Get<mirror::Object>(object_id, &error);
Ian Rogersc0542af2014-09-03 16:16:56 -07001140 if (o == nullptr) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001141 return JDWP::ERR_INVALID_OBJECT;
Elliott Hughes499c5132011-11-17 14:55:11 -08001142 }
Elliott Hughes2435a572012-02-17 16:07:41 -08001143
Sebastien Hertz4d8fd492014-03-28 16:29:41 +01001144 JDWP::JdwpTypeTag type_tag = GetTypeTag(o->GetClass());
Elliott Hughes64f574f2013-02-20 14:57:12 -08001145 JDWP::RefTypeId type_id = gRegistry->AddRefType(o->GetClass());
Elliott Hughes2435a572012-02-17 16:07:41 -08001146
1147 expandBufAdd1(pReply, type_tag);
1148 expandBufAddRefTypeId(pReply, type_id);
1149
1150 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001151}
1152
Ian Rogersfc0e94b2013-09-23 23:51:32 -07001153JDWP::JdwpError Dbg::GetSignature(JDWP::RefTypeId class_id, std::string* signature) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001154 JDWP::JdwpError error;
Vladimir Marko4617d582019-03-28 13:48:31 +00001155 ObjPtr<mirror::Class> c = DecodeClass(class_id, &error);
Ian Rogersc0542af2014-09-03 16:16:56 -07001156 if (c == nullptr) {
1157 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001158 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07001159 std::string temp;
1160 *signature = c->GetDescriptor(&temp);
Elliott Hughes1fe7afb2012-02-13 17:23:03 -08001161 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001162}
1163
Orion Hodson77d8a1c2017-04-24 14:53:19 +01001164JDWP::JdwpError Dbg::GetSourceDebugExtension(JDWP::RefTypeId class_id,
1165 std::string* extension_data) {
1166 JDWP::JdwpError error;
Vladimir Marko4617d582019-03-28 13:48:31 +00001167 ObjPtr<mirror::Class> c = DecodeClass(class_id, &error);
Orion Hodson77d8a1c2017-04-24 14:53:19 +01001168 if (c == nullptr) {
1169 return error;
1170 }
1171 StackHandleScope<1> hs(Thread::Current());
1172 Handle<mirror::Class> klass(hs.NewHandle(c));
1173 const char* data = annotations::GetSourceDebugExtension(klass);
1174 if (data == nullptr) {
1175 return JDWP::ERR_ABSENT_INFORMATION;
1176 }
1177 *extension_data = data;
1178 return JDWP::ERR_NONE;
1179}
1180
Ian Rogersc0542af2014-09-03 16:16:56 -07001181JDWP::JdwpError Dbg::GetSourceFile(JDWP::RefTypeId class_id, std::string* result) {
1182 JDWP::JdwpError error;
Vladimir Marko4617d582019-03-28 13:48:31 +00001183 ObjPtr<mirror::Class> c = DecodeClass(class_id, &error);
Sebastien Hertz4206eb52014-06-05 10:15:45 +02001184 if (c == nullptr) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001185 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001186 }
Sebastien Hertz4206eb52014-06-05 10:15:45 +02001187 const char* source_file = c->GetSourceFile();
1188 if (source_file == nullptr) {
Sebastien Hertzb7054ba2014-03-13 11:52:31 +01001189 return JDWP::ERR_ABSENT_INFORMATION;
1190 }
Ian Rogersc0542af2014-09-03 16:16:56 -07001191 *result = source_file;
Elliott Hughes436e3722012-02-17 20:01:47 -08001192 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001193}
1194
Ian Rogersc0542af2014-09-03 16:16:56 -07001195JDWP::JdwpError Dbg::GetObjectTag(JDWP::ObjectId object_id, uint8_t* tag) {
Ian Rogers98379392014-02-24 16:53:16 -08001196 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07001197 JDWP::JdwpError error;
Vladimir Marko83114892019-04-11 13:05:50 +01001198 ObjPtr<mirror::Object> o = gRegistry->Get<mirror::Object>(object_id, &error);
Ian Rogersc0542af2014-09-03 16:16:56 -07001199 if (error != JDWP::ERR_NONE) {
1200 *tag = JDWP::JT_VOID;
1201 return error;
Elliott Hughes546b9862012-06-20 16:06:13 -07001202 }
Ian Rogersc0542af2014-09-03 16:16:56 -07001203 *tag = TagFromObject(soa, o);
Elliott Hughes546b9862012-06-20 16:06:13 -07001204 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001205}
1206
Elliott Hughesaed4be92011-12-02 16:16:23 -08001207size_t Dbg::GetTagWidth(JDWP::JdwpTag tag) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001208 switch (tag) {
1209 case JDWP::JT_VOID:
1210 return 0;
1211 case JDWP::JT_BYTE:
1212 case JDWP::JT_BOOLEAN:
1213 return 1;
1214 case JDWP::JT_CHAR:
1215 case JDWP::JT_SHORT:
1216 return 2;
1217 case JDWP::JT_FLOAT:
1218 case JDWP::JT_INT:
1219 return 4;
1220 case JDWP::JT_ARRAY:
1221 case JDWP::JT_OBJECT:
1222 case JDWP::JT_STRING:
1223 case JDWP::JT_THREAD:
1224 case JDWP::JT_THREAD_GROUP:
1225 case JDWP::JT_CLASS_LOADER:
1226 case JDWP::JT_CLASS_OBJECT:
1227 return sizeof(JDWP::ObjectId);
1228 case JDWP::JT_DOUBLE:
1229 case JDWP::JT_LONG:
1230 return 8;
1231 default:
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001232 LOG(FATAL) << "Unknown tag " << tag;
Elliott Hughesc1896c92018-11-29 11:33:18 -08001233 UNREACHABLE();
Elliott Hughesdbb40792011-11-18 17:05:22 -08001234 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001235}
1236
Ian Rogersc0542af2014-09-03 16:16:56 -07001237JDWP::JdwpError Dbg::GetArrayLength(JDWP::ObjectId array_id, int32_t* length) {
1238 JDWP::JdwpError error;
Vladimir Marko4617d582019-03-28 13:48:31 +00001239 ObjPtr<mirror::Array> a = DecodeNonNullArray(array_id, &error);
Ian Rogersc0542af2014-09-03 16:16:56 -07001240 if (a == nullptr) {
1241 return error;
Elliott Hughes24437992011-11-30 14:49:33 -08001242 }
Ian Rogersc0542af2014-09-03 16:16:56 -07001243 *length = a->GetLength();
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001244 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001245}
1246
Vladimir Marko4617d582019-03-28 13:48:31 +00001247JDWP::JdwpError Dbg::OutputArray(JDWP::ObjectId array_id,
1248 int offset,
1249 int count,
1250 JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001251 JDWP::JdwpError error;
Vladimir Marko4617d582019-03-28 13:48:31 +00001252 ObjPtr<mirror::Array> a = DecodeNonNullArray(array_id, &error);
Ian Rogers98379392014-02-24 16:53:16 -08001253 if (a == nullptr) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001254 return error;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001255 }
Elliott Hughes24437992011-11-30 14:49:33 -08001256
1257 if (offset < 0 || count < 0 || offset > a->GetLength() || a->GetLength() - offset < count) {
1258 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001259 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughes24437992011-11-30 14:49:33 -08001260 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07001261 JDWP::JdwpTag element_tag = BasicTagFromClass(a->GetClass()->GetComponentType());
1262 expandBufAdd1(pReply, element_tag);
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001263 expandBufAdd4BE(pReply, count);
1264
Ian Rogers1ff3c982014-08-12 02:30:58 -07001265 if (IsPrimitiveTag(element_tag)) {
1266 size_t width = GetTagWidth(element_tag);
Elliott Hughes24437992011-11-30 14:49:33 -08001267 uint8_t* dst = expandBufAddSpace(pReply, count * width);
1268 if (width == 8) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001269 const uint64_t* src8 = reinterpret_cast<uint64_t*>(a->GetRawData(sizeof(uint64_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001270 for (int i = 0; i < count; ++i) JDWP::Write8BE(&dst, src8[offset + i]);
1271 } else if (width == 4) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001272 const uint32_t* src4 = reinterpret_cast<uint32_t*>(a->GetRawData(sizeof(uint32_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001273 for (int i = 0; i < count; ++i) JDWP::Write4BE(&dst, src4[offset + i]);
1274 } else if (width == 2) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001275 const uint16_t* src2 = reinterpret_cast<uint16_t*>(a->GetRawData(sizeof(uint16_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001276 for (int i = 0; i < count; ++i) JDWP::Write2BE(&dst, src2[offset + i]);
1277 } else {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001278 const uint8_t* src = reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint8_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001279 memcpy(dst, &src[offset * width], count * width);
1280 }
1281 } else {
Ian Rogers98379392014-02-24 16:53:16 -08001282 ScopedObjectAccessUnchecked soa(Thread::Current());
Vladimir Marko4617d582019-03-28 13:48:31 +00001283 ObjPtr<mirror::ObjectArray<mirror::Object>> oa = a->AsObjectArray<mirror::Object>();
Elliott Hughes24437992011-11-30 14:49:33 -08001284 for (int i = 0; i < count; ++i) {
Vladimir Marko423bebb2019-03-26 15:17:21 +00001285 ObjPtr<mirror::Object> element = oa->Get(offset + i);
Ian Rogers98379392014-02-24 16:53:16 -08001286 JDWP::JdwpTag specific_tag = (element != nullptr) ? TagFromObject(soa, element)
Ian Rogers1ff3c982014-08-12 02:30:58 -07001287 : element_tag;
Elliott Hughes24437992011-11-30 14:49:33 -08001288 expandBufAdd1(pReply, specific_tag);
1289 expandBufAddObjectId(pReply, gRegistry->Add(element));
1290 }
1291 }
1292
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001293 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001294}
1295
Ian Rogersef7d42f2014-01-06 12:55:46 -08001296template <typename T>
Vladimir Marko4617d582019-03-28 13:48:31 +00001297static void CopyArrayData(ObjPtr<mirror::Array> a, JDWP::Request* src, int offset, int count)
Ian Rogersef7d42f2014-01-06 12:55:46 -08001298 NO_THREAD_SAFETY_ANALYSIS {
1299 // TODO: fix when annotalysis correctly handles non-member functions.
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001300 DCHECK(a->GetClass()->IsPrimitiveArray());
1301
Ian Rogersef7d42f2014-01-06 12:55:46 -08001302 T* dst = reinterpret_cast<T*>(a->GetRawData(sizeof(T), offset));
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001303 for (int i = 0; i < count; ++i) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001304 *dst++ = src->ReadValue(sizeof(T));
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001305 }
1306}
1307
Elliott Hughes88d63092013-01-09 09:55:54 -08001308JDWP::JdwpError Dbg::SetArrayElements(JDWP::ObjectId array_id, int offset, int count,
Ian Rogersc0542af2014-09-03 16:16:56 -07001309 JDWP::Request* request) {
1310 JDWP::JdwpError error;
Vladimir Marko4617d582019-03-28 13:48:31 +00001311 ObjPtr<mirror::Array> dst = DecodeNonNullArray(array_id, &error);
Ian Rogersc0542af2014-09-03 16:16:56 -07001312 if (dst == nullptr) {
1313 return error;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001314 }
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001315
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001316 if (offset < 0 || count < 0 || offset > dst->GetLength() || dst->GetLength() - offset < count) {
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001317 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001318 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001319 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07001320 JDWP::JdwpTag element_tag = BasicTagFromClass(dst->GetClass()->GetComponentType());
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001321
Ian Rogers1ff3c982014-08-12 02:30:58 -07001322 if (IsPrimitiveTag(element_tag)) {
1323 size_t width = GetTagWidth(element_tag);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001324 if (width == 8) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001325 CopyArrayData<uint64_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001326 } else if (width == 4) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001327 CopyArrayData<uint32_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001328 } else if (width == 2) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001329 CopyArrayData<uint16_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001330 } else {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001331 CopyArrayData<uint8_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001332 }
1333 } else {
Vladimir Marko4617d582019-03-28 13:48:31 +00001334 ObjPtr<mirror::ObjectArray<mirror::Object>> oa = dst->AsObjectArray<mirror::Object>();
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001335 for (int i = 0; i < count; ++i) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001336 JDWP::ObjectId id = request->ReadObjectId();
Vladimir Marko83114892019-04-11 13:05:50 +01001337 ObjPtr<mirror::Object> o = gRegistry->Get<mirror::Object>(id, &error);
Ian Rogersc0542af2014-09-03 16:16:56 -07001338 if (error != JDWP::ERR_NONE) {
1339 return error;
Elliott Hughes436e3722012-02-17 20:01:47 -08001340 }
Sebastien Hertz2e1c16d2015-08-28 11:57:49 +02001341 // Check if the object's type is compatible with the array's type.
1342 if (o != nullptr && !o->InstanceOf(oa->GetClass()->GetComponentType())) {
1343 return JDWP::ERR_TYPE_MISMATCH;
1344 }
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001345 oa->Set<false>(offset + i, o);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001346 }
1347 }
1348
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001349 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001350}
1351
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001352JDWP::JdwpError Dbg::CreateString(const std::string& str, JDWP::ObjectId* new_string_id) {
1353 Thread* self = Thread::Current();
Vladimir Marko179b7c62019-03-22 13:38:57 +00001354 ObjPtr<mirror::String> new_string = mirror::String::AllocFromModifiedUtf8(self, str.c_str());
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001355 if (new_string == nullptr) {
1356 DCHECK(self->IsExceptionPending());
1357 self->ClearException();
1358 LOG(ERROR) << "Could not allocate string";
1359 *new_string_id = 0;
1360 return JDWP::ERR_OUT_OF_MEMORY;
1361 }
1362 *new_string_id = gRegistry->Add(new_string);
1363 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001364}
1365
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001366JDWP::JdwpError Dbg::CreateObject(JDWP::RefTypeId class_id, JDWP::ObjectId* new_object_id) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001367 JDWP::JdwpError error;
Vladimir Marko4617d582019-03-28 13:48:31 +00001368 ObjPtr<mirror::Class> c = DecodeClass(class_id, &error);
Ian Rogersc0542af2014-09-03 16:16:56 -07001369 if (c == nullptr) {
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001370 *new_object_id = 0;
Ian Rogersc0542af2014-09-03 16:16:56 -07001371 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001372 }
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001373 Thread* self = Thread::Current();
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001374 ObjPtr<mirror::Object> new_object;
Sebastien Hertz56d5e502015-11-03 17:38:35 +01001375 if (c->IsStringClass()) {
1376 // Special case for java.lang.String.
1377 gc::AllocatorType allocator_type = Runtime::Current()->GetHeap()->GetCurrentAllocator();
Vladimir Marko9b81ac32019-05-16 16:47:08 +01001378 new_object = mirror::String::AllocEmptyString(self, allocator_type);
Sebastien Hertz56d5e502015-11-03 17:38:35 +01001379 } else {
1380 new_object = c->AllocObject(self);
1381 }
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001382 if (new_object == nullptr) {
1383 DCHECK(self->IsExceptionPending());
1384 self->ClearException();
David Sehr709b0702016-10-13 09:12:37 -07001385 LOG(ERROR) << "Could not allocate object of type " << mirror::Class::PrettyDescriptor(c);
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001386 *new_object_id = 0;
1387 return JDWP::ERR_OUT_OF_MEMORY;
1388 }
Vladimir Markobcf17522018-06-01 13:14:32 +01001389 *new_object_id = gRegistry->Add(new_object);
Elliott Hughes436e3722012-02-17 20:01:47 -08001390 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001391}
1392
Elliott Hughesbf13d362011-12-08 15:51:37 -08001393/*
1394 * Used by Eclipse's "Display" view to evaluate "new byte[5]" to get "(byte[]) [0, 0, 0, 0, 0]".
1395 */
Elliott Hughes88d63092013-01-09 09:55:54 -08001396JDWP::JdwpError Dbg::CreateArrayObject(JDWP::RefTypeId array_class_id, uint32_t length,
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001397 JDWP::ObjectId* new_array_id) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001398 JDWP::JdwpError error;
Vladimir Marko4617d582019-03-28 13:48:31 +00001399 ObjPtr<mirror::Class> c = DecodeClass(array_class_id, &error);
Ian Rogersc0542af2014-09-03 16:16:56 -07001400 if (c == nullptr) {
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001401 *new_array_id = 0;
Ian Rogersc0542af2014-09-03 16:16:56 -07001402 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001403 }
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001404 Thread* self = Thread::Current();
Vladimir Markobcf17522018-06-01 13:14:32 +01001405 gc::AllocatorType allocator_type = Runtime::Current()->GetHeap()->GetCurrentAllocator();
1406 ObjPtr<mirror::Array> new_array =
Vladimir Marko9b81ac32019-05-16 16:47:08 +01001407 mirror::Array::Alloc(self, c, length, c->GetComponentSizeShift(), allocator_type);
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001408 if (new_array == nullptr) {
1409 DCHECK(self->IsExceptionPending());
1410 self->ClearException();
David Sehr709b0702016-10-13 09:12:37 -07001411 LOG(ERROR) << "Could not allocate array of type " << mirror::Class::PrettyDescriptor(c);
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001412 *new_array_id = 0;
1413 return JDWP::ERR_OUT_OF_MEMORY;
1414 }
1415 *new_array_id = gRegistry->Add(new_array);
Elliott Hughes436e3722012-02-17 20:01:47 -08001416 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001417}
1418
Mathieu Chartierc7853442015-03-27 14:35:38 -07001419JDWP::FieldId Dbg::ToFieldId(const ArtField* f) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001420 return static_cast<JDWP::FieldId>(reinterpret_cast<uintptr_t>(f));
Elliott Hughes03181a82011-11-17 17:22:21 -08001421}
1422
Alex Light6c8467f2015-11-20 15:03:26 -08001423static JDWP::MethodId ToMethodId(ArtMethod* m)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001424 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light97e78032017-06-27 17:51:55 -07001425 return static_cast<JDWP::MethodId>(
1426 reinterpret_cast<uintptr_t>(m->GetCanonicalMethod(kRuntimePointerSize)));
Elliott Hughes03181a82011-11-17 17:22:21 -08001427}
1428
Mathieu Chartierc7853442015-03-27 14:35:38 -07001429static ArtField* FromFieldId(JDWP::FieldId fid)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001430 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001431 return reinterpret_cast<ArtField*>(static_cast<uintptr_t>(fid));
Elliott Hughesaed4be92011-12-02 16:16:23 -08001432}
1433
Mathieu Chartiere401d142015-04-22 13:56:20 -07001434static ArtMethod* FromMethodId(JDWP::MethodId mid)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001435 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001436 return reinterpret_cast<ArtMethod*>(static_cast<uintptr_t>(mid));
Elliott Hughes03181a82011-11-17 17:22:21 -08001437}
1438
Sebastien Hertz6995c602014-09-09 12:10:13 +02001439bool Dbg::MatchThread(JDWP::ObjectId expected_thread_id, Thread* event_thread) {
1440 CHECK(event_thread != nullptr);
1441 JDWP::JdwpError error;
Vladimir Marko83114892019-04-11 13:05:50 +01001442 ObjPtr<mirror::Object> expected_thread_peer = gRegistry->Get<mirror::Object>(
Mathieu Chartiere401d142015-04-22 13:56:20 -07001443 expected_thread_id, &error);
Nicolas Geoffraycafa0812017-02-15 18:27:34 +00001444 return expected_thread_peer == event_thread->GetPeerFromOtherThread();
Sebastien Hertz6995c602014-09-09 12:10:13 +02001445}
1446
1447bool Dbg::MatchLocation(const JDWP::JdwpLocation& expected_location,
1448 const JDWP::EventLocation& event_location) {
1449 if (expected_location.dex_pc != event_location.dex_pc) {
1450 return false;
1451 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001452 ArtMethod* m = FromMethodId(expected_location.method_id);
Sebastien Hertz6995c602014-09-09 12:10:13 +02001453 return m == event_location.method;
1454}
1455
Mathieu Chartier3398c782016-09-30 10:27:43 -07001456bool Dbg::MatchType(ObjPtr<mirror::Class> event_class, JDWP::RefTypeId class_id) {
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001457 if (event_class == nullptr) {
1458 return false;
1459 }
Sebastien Hertz6995c602014-09-09 12:10:13 +02001460 JDWP::JdwpError error;
Mathieu Chartier3398c782016-09-30 10:27:43 -07001461 ObjPtr<mirror::Class> expected_class = DecodeClass(class_id, &error);
Sebastien Hertz6995c602014-09-09 12:10:13 +02001462 CHECK(expected_class != nullptr);
1463 return expected_class->IsAssignableFrom(event_class);
1464}
1465
Vladimir Marko83114892019-04-11 13:05:50 +01001466bool Dbg::MatchField(JDWP::RefTypeId expected_type_id,
1467 JDWP::FieldId expected_field_id,
Mathieu Chartierc7853442015-03-27 14:35:38 -07001468 ArtField* event_field) {
1469 ArtField* expected_field = FromFieldId(expected_field_id);
Sebastien Hertz6995c602014-09-09 12:10:13 +02001470 if (expected_field != event_field) {
1471 return false;
1472 }
1473 return Dbg::MatchType(event_field->GetDeclaringClass(), expected_type_id);
1474}
1475
Vladimir Marko83114892019-04-11 13:05:50 +01001476bool Dbg::MatchInstance(JDWP::ObjectId expected_instance_id,
1477 ObjPtr<mirror::Object> event_instance) {
Sebastien Hertz6995c602014-09-09 12:10:13 +02001478 JDWP::JdwpError error;
Vladimir Marko83114892019-04-11 13:05:50 +01001479 ObjPtr<mirror::Object> modifier_instance =
1480 gRegistry->Get<mirror::Object>(expected_instance_id, &error);
Sebastien Hertz6995c602014-09-09 12:10:13 +02001481 return modifier_instance == event_instance;
1482}
1483
Mathieu Chartier90443472015-07-16 20:32:27 -07001484void Dbg::SetJdwpLocation(JDWP::JdwpLocation* location, ArtMethod* m, uint32_t dex_pc) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001485 if (m == nullptr) {
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001486 memset(location, 0, sizeof(*location));
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001487 } else {
Vladimir Markod93e3742018-07-18 10:58:13 +01001488 ObjPtr<mirror::Class> c = m->GetDeclaringClass();
Ian Rogersc0542af2014-09-03 16:16:56 -07001489 location->type_tag = GetTypeTag(c);
1490 location->class_id = gRegistry->AddRefType(c);
Alex Light73376312017-04-06 10:10:51 -07001491 // The RI Seems to return 0 for all obsolete methods. For compatibility we shall do the same.
1492 location->method_id = m->IsObsolete() ? 0 : ToMethodId(m);
Ian Rogersc0542af2014-09-03 16:16:56 -07001493 location->dex_pc = (m->IsNative() || m->IsProxyMethod()) ? static_cast<uint64_t>(-1) : dex_pc;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001494 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08001495}
1496
Ian Rogersc0542af2014-09-03 16:16:56 -07001497std::string Dbg::GetMethodName(JDWP::MethodId method_id) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001498 ArtMethod* m = FromMethodId(method_id);
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001499 if (m == nullptr) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001500 return "null";
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001501 }
Andreas Gampe542451c2016-07-26 09:02:02 -07001502 return m->GetInterfaceMethodIfProxy(kRuntimePointerSize)->GetName();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001503}
1504
Alex Light73376312017-04-06 10:10:51 -07001505bool Dbg::IsMethodObsolete(JDWP::MethodId method_id) {
1506 ArtMethod* m = FromMethodId(method_id);
1507 if (m == nullptr) {
1508 // NB Since we return 0 as MID for obsolete methods we want to default to true here.
1509 return true;
1510 }
1511 return m->IsObsolete();
1512}
1513
Ian Rogersc0542af2014-09-03 16:16:56 -07001514std::string Dbg::GetFieldName(JDWP::FieldId field_id) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001515 ArtField* f = FromFieldId(field_id);
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001516 if (f == nullptr) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001517 return "null";
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001518 }
1519 return f->GetName();
Elliott Hughesa96836a2013-01-17 12:27:49 -08001520}
1521
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001522/*
1523 * Augment the access flags for synthetic methods and fields by setting
1524 * the (as described by the spec) "0xf0000000 bit". Also, strip out any
1525 * flags not specified by the Java programming language.
1526 */
1527static uint32_t MangleAccessFlags(uint32_t accessFlags) {
1528 accessFlags &= kAccJavaFlagsMask;
1529 if ((accessFlags & kAccSynthetic) != 0) {
1530 accessFlags |= 0xf0000000;
1531 }
1532 return accessFlags;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001533}
1534
Elliott Hughesdbb40792011-11-18 17:05:22 -08001535/*
Jeff Haob7cefc72013-11-14 14:51:09 -08001536 * Circularly shifts registers so that arguments come first. Debuggers
1537 * expect slots to begin with arguments, but dex code places them at
1538 * the end.
Elliott Hughesdbb40792011-11-18 17:05:22 -08001539 */
Mathieu Chartiere401d142015-04-22 13:56:20 -07001540static uint16_t MangleSlot(uint16_t slot, ArtMethod* m)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001541 REQUIRES_SHARED(Locks::mutator_lock_) {
David Sehr0225f8e2018-01-31 08:52:24 +00001542 CodeItemDataAccessor accessor(m->DexInstructionData());
Mathieu Chartier808c7a52017-12-15 11:19:33 -08001543 if (!accessor.HasCodeItem()) {
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001544 // We should not get here for a method without code (native, proxy or abstract). Log it and
1545 // return the slot as is since all registers are arguments.
David Sehr709b0702016-10-13 09:12:37 -07001546 LOG(WARNING) << "Trying to mangle slot for method without code " << m->PrettyMethod();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001547 return slot;
1548 }
Mathieu Chartier808c7a52017-12-15 11:19:33 -08001549 uint16_t ins_size = accessor.InsSize();
1550 uint16_t locals_size = accessor.RegistersSize() - ins_size;
Jeff Haob7cefc72013-11-14 14:51:09 -08001551 if (slot >= locals_size) {
1552 return slot - locals_size;
1553 } else {
1554 return slot + ins_size;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001555 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001556}
1557
Sebastien Hertzaef0c912016-08-08 10:20:28 +02001558static size_t GetMethodNumArgRegistersIncludingThis(ArtMethod* method)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001559 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertzaef0c912016-08-08 10:20:28 +02001560 uint32_t num_registers = ArtMethod::NumArgRegisters(method->GetShorty());
1561 if (!method->IsStatic()) {
1562 ++num_registers;
1563 }
1564 return num_registers;
1565}
1566
Jeff Haob7cefc72013-11-14 14:51:09 -08001567/*
1568 * Circularly shifts registers so that arguments come last. Reverts
1569 * slots to dex style argument placement.
1570 */
Mathieu Chartiere401d142015-04-22 13:56:20 -07001571static uint16_t DemangleSlot(uint16_t slot, ArtMethod* m, JDWP::JdwpError* error)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001572 REQUIRES_SHARED(Locks::mutator_lock_) {
David Sehr0225f8e2018-01-31 08:52:24 +00001573 CodeItemDataAccessor accessor(m->DexInstructionData());
Mathieu Chartier808c7a52017-12-15 11:19:33 -08001574 if (!accessor.HasCodeItem()) {
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001575 // We should not get here for a method without code (native, proxy or abstract). Log it and
1576 // return the slot as is since all registers are arguments.
David Sehr709b0702016-10-13 09:12:37 -07001577 LOG(WARNING) << "Trying to demangle slot for method without code "
1578 << m->PrettyMethod();
Sebastien Hertzaef0c912016-08-08 10:20:28 +02001579 uint16_t vreg_count = GetMethodNumArgRegistersIncludingThis(m);
Sebastien Hertzabbabc82015-03-26 08:47:47 +01001580 if (slot < vreg_count) {
1581 *error = JDWP::ERR_NONE;
1582 return slot;
1583 }
Jeff Haob7cefc72013-11-14 14:51:09 -08001584 } else {
Mathieu Chartier808c7a52017-12-15 11:19:33 -08001585 if (slot < accessor.RegistersSize()) {
1586 uint16_t ins_size = accessor.InsSize();
1587 uint16_t locals_size = accessor.RegistersSize() - ins_size;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01001588 *error = JDWP::ERR_NONE;
1589 return (slot < ins_size) ? slot + locals_size : slot - ins_size;
1590 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001591 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01001592
1593 // Slot is invalid in the method.
David Sehr709b0702016-10-13 09:12:37 -07001594 LOG(ERROR) << "Invalid local slot " << slot << " for method " << m->PrettyMethod();
Sebastien Hertzabbabc82015-03-26 08:47:47 +01001595 *error = JDWP::ERR_INVALID_SLOT;
1596 return DexFile::kDexNoIndex16;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001597}
1598
Mathieu Chartier90443472015-07-16 20:32:27 -07001599JDWP::JdwpError Dbg::OutputDeclaredFields(JDWP::RefTypeId class_id, bool with_generic,
1600 JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001601 JDWP::JdwpError error;
Vladimir Marko4617d582019-03-28 13:48:31 +00001602 ObjPtr<mirror::Class> c = DecodeClass(class_id, &error);
Ian Rogersc0542af2014-09-03 16:16:56 -07001603 if (c == nullptr) {
1604 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001605 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001606
1607 size_t instance_field_count = c->NumInstanceFields();
1608 size_t static_field_count = c->NumStaticFields();
1609
1610 expandBufAdd4BE(pReply, instance_field_count + static_field_count);
1611
1612 for (size_t i = 0; i < instance_field_count + static_field_count; ++i) {
Mathieu Chartier90443472015-07-16 20:32:27 -07001613 ArtField* f = (i < instance_field_count) ? c->GetInstanceField(i) :
1614 c->GetStaticField(i - instance_field_count);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001615 expandBufAddFieldId(pReply, ToFieldId(f));
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001616 expandBufAddUtf8String(pReply, f->GetName());
1617 expandBufAddUtf8String(pReply, f->GetTypeDescriptor());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001618 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001619 static const char genericSignature[1] = "";
1620 expandBufAddUtf8String(pReply, genericSignature);
1621 }
1622 expandBufAdd4BE(pReply, MangleAccessFlags(f->GetAccessFlags()));
1623 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001624 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001625}
1626
Elliott Hughes88d63092013-01-09 09:55:54 -08001627JDWP::JdwpError Dbg::OutputDeclaredMethods(JDWP::RefTypeId class_id, bool with_generic,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001628 JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001629 JDWP::JdwpError error;
Vladimir Marko4617d582019-03-28 13:48:31 +00001630 ObjPtr<mirror::Class> c = DecodeClass(class_id, &error);
Ian Rogersc0542af2014-09-03 16:16:56 -07001631 if (c == nullptr) {
1632 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001633 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001634
Alex Light51a64d52015-12-17 13:55:59 -08001635 expandBufAdd4BE(pReply, c->NumMethods());
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001636
Mathieu Chartiere401d142015-04-22 13:56:20 -07001637 auto* cl = Runtime::Current()->GetClassLinker();
1638 auto ptr_size = cl->GetImagePointerSize();
Alex Light51a64d52015-12-17 13:55:59 -08001639 for (ArtMethod& m : c->GetMethods(ptr_size)) {
1640 expandBufAddMethodId(pReply, ToMethodId(&m));
Andreas Gampe542451c2016-07-26 09:02:02 -07001641 expandBufAddUtf8String(pReply, m.GetInterfaceMethodIfProxy(kRuntimePointerSize)->GetName());
1642 expandBufAddUtf8String(
1643 pReply, m.GetInterfaceMethodIfProxy(kRuntimePointerSize)->GetSignature().ToString());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001644 if (with_generic) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001645 const char* generic_signature = "";
1646 expandBufAddUtf8String(pReply, generic_signature);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001647 }
Alex Light51a64d52015-12-17 13:55:59 -08001648 expandBufAdd4BE(pReply, MangleAccessFlags(m.GetAccessFlags()));
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001649 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001650 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001651}
1652
Elliott Hughes88d63092013-01-09 09:55:54 -08001653JDWP::JdwpError Dbg::OutputDeclaredInterfaces(JDWP::RefTypeId class_id, JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001654 JDWP::JdwpError error;
Mathieu Chartierf8322842014-05-16 10:59:25 -07001655 Thread* self = Thread::Current();
Vladimir Marko19a4d372016-12-08 14:41:46 +00001656 ObjPtr<mirror::Class> c = DecodeClass(class_id, &error);
1657 if (c == nullptr) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001658 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001659 }
Mathieu Chartierf8322842014-05-16 10:59:25 -07001660 size_t interface_count = c->NumDirectInterfaces();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001661 expandBufAdd4BE(pReply, interface_count);
1662 for (size_t i = 0; i < interface_count; ++i) {
Vladimir Marko19a4d372016-12-08 14:41:46 +00001663 ObjPtr<mirror::Class> interface = mirror::Class::GetDirectInterface(self, c, i);
1664 DCHECK(interface != nullptr);
1665 expandBufAddRefTypeId(pReply, gRegistry->AddRefType(interface));
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001666 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001667 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001668}
1669
Ian Rogersc0542af2014-09-03 16:16:56 -07001670void Dbg::OutputLineTable(JDWP::RefTypeId, JDWP::MethodId method_id, JDWP::ExpandBuf* pReply) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001671 ArtMethod* m = FromMethodId(method_id);
David Sehr0225f8e2018-01-31 08:52:24 +00001672 CodeItemDebugInfoAccessor accessor(m->DexInstructionDebugInfo());
Elliott Hughes03181a82011-11-17 17:22:21 -08001673 uint64_t start, end;
Mathieu Chartier31f4c9f2017-12-08 15:46:11 -08001674 if (!accessor.HasCodeItem()) {
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001675 DCHECK(m->IsNative() || m->IsProxyMethod());
Elliott Hughes03181a82011-11-17 17:22:21 -08001676 start = -1;
1677 end = -1;
1678 } else {
1679 start = 0;
jeffhao14f0db92012-12-14 17:50:42 -08001680 // Return the index of the last instruction
Mathieu Chartier31f4c9f2017-12-08 15:46:11 -08001681 end = accessor.InsnsSizeInCodeUnits() - 1;
Elliott Hughes03181a82011-11-17 17:22:21 -08001682 }
1683
1684 expandBufAdd8BE(pReply, start);
1685 expandBufAdd8BE(pReply, end);
1686
1687 // Add numLines later
1688 size_t numLinesOffset = expandBufGetLength(pReply);
1689 expandBufAdd4BE(pReply, 0);
1690
Mathieu Chartier3e2e1232018-09-11 12:35:30 -07001691 int numItems = 0;
1692 accessor.DecodeDebugPositionInfo([&](const DexFile::PositionInfo& entry) {
1693 expandBufAdd8BE(pReply, entry.address_);
1694 expandBufAdd4BE(pReply, entry.line_);
1695 numItems++;
1696 return false;
1697 });
Elliott Hughes03181a82011-11-17 17:22:21 -08001698
Mathieu Chartier3e2e1232018-09-11 12:35:30 -07001699 JDWP::Set4BE(expandBufGetBuffer(pReply) + numLinesOffset, numItems);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001700}
1701
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001702void Dbg::OutputVariableTable(JDWP::RefTypeId, JDWP::MethodId method_id, bool with_generic,
1703 JDWP::ExpandBuf* pReply) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001704 ArtMethod* m = FromMethodId(method_id);
David Sehr0225f8e2018-01-31 08:52:24 +00001705 CodeItemDebugInfoAccessor accessor(m->DexInstructionDebugInfo());
Elliott Hughesdbb40792011-11-18 17:05:22 -08001706
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001707 // arg_count considers doubles and longs to take 2 units.
1708 // variable_count considers everything to take 1 unit.
Sebastien Hertzaef0c912016-08-08 10:20:28 +02001709 expandBufAdd4BE(pReply, GetMethodNumArgRegistersIncludingThis(m));
Elliott Hughesdbb40792011-11-18 17:05:22 -08001710
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001711 // We don't know the total number of variables yet, so leave a blank and update it later.
1712 size_t variable_count_offset = expandBufGetLength(pReply);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001713 expandBufAdd4BE(pReply, 0);
1714
Mathieu Chartiere5afbf32018-09-12 17:51:54 -07001715 size_t variable_count = 0;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001716
Mathieu Chartier31f4c9f2017-12-08 15:46:11 -08001717 if (accessor.HasCodeItem()) {
Mathieu Chartiere5afbf32018-09-12 17:51:54 -07001718 accessor.DecodeDebugLocalInfo(m->IsStatic(),
1719 m->GetDexMethodIndex(),
1720 [&](const DexFile::LocalInfo& entry)
1721 REQUIRES_SHARED(Locks::mutator_lock_) {
1722 uint16_t slot = entry.reg_;
1723 VLOG(jdwp) << StringPrintf(" %2zd: %d(%d) '%s' '%s' '%s' actual slot=%d mangled slot=%d",
1724 variable_count,
1725 entry.start_address_,
1726 entry.end_address_ - entry.start_address_,
1727 entry.name_,
1728 entry.descriptor_, entry.signature_,
1729 slot,
1730 MangleSlot(slot, m));
1731
1732 slot = MangleSlot(slot, m);
1733
1734 expandBufAdd8BE(pReply, entry.start_address_);
1735 expandBufAddUtf8String(pReply, entry.name_);
1736 expandBufAddUtf8String(pReply, entry.descriptor_);
1737 if (with_generic) {
1738 expandBufAddUtf8String(pReply, entry.signature_);
1739 }
1740 expandBufAdd4BE(pReply, entry.end_address_- entry.start_address_);
1741 expandBufAdd4BE(pReply, slot);
1742
1743 ++variable_count;
1744 });
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001745 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001746
Mathieu Chartiere5afbf32018-09-12 17:51:54 -07001747 JDWP::Set4BE(expandBufGetBuffer(pReply) + variable_count_offset, variable_count);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001748}
1749
Jeff Hao579b0242013-11-18 13:16:49 -08001750void Dbg::OutputMethodReturnValue(JDWP::MethodId method_id, const JValue* return_value,
1751 JDWP::ExpandBuf* pReply) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001752 ArtMethod* m = FromMethodId(method_id);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001753 JDWP::JdwpTag tag = BasicTagFromDescriptor(m->GetShorty());
Jeff Hao579b0242013-11-18 13:16:49 -08001754 OutputJValue(tag, return_value, pReply);
1755}
1756
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02001757void Dbg::OutputFieldValue(JDWP::FieldId field_id, const JValue* field_value,
1758 JDWP::ExpandBuf* pReply) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001759 ArtField* f = FromFieldId(field_id);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001760 JDWP::JdwpTag tag = BasicTagFromDescriptor(f->GetTypeDescriptor());
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02001761 OutputJValue(tag, field_value, pReply);
1762}
1763
Elliott Hughes9777ba22013-01-17 09:04:19 -08001764JDWP::JdwpError Dbg::GetBytecodes(JDWP::RefTypeId, JDWP::MethodId method_id,
Ian Rogersc0542af2014-09-03 16:16:56 -07001765 std::vector<uint8_t>* bytecodes) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001766 ArtMethod* m = FromMethodId(method_id);
Ian Rogersc0542af2014-09-03 16:16:56 -07001767 if (m == nullptr) {
Elliott Hughes9777ba22013-01-17 09:04:19 -08001768 return JDWP::ERR_INVALID_METHODID;
1769 }
David Sehr0225f8e2018-01-31 08:52:24 +00001770 CodeItemDataAccessor accessor(m->DexInstructionData());
Mathieu Chartier808c7a52017-12-15 11:19:33 -08001771 size_t byte_count = accessor.InsnsSizeInCodeUnits() * 2;
1772 const uint8_t* begin = reinterpret_cast<const uint8_t*>(accessor.Insns());
Elliott Hughes9777ba22013-01-17 09:04:19 -08001773 const uint8_t* end = begin + byte_count;
1774 for (const uint8_t* p = begin; p != end; ++p) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001775 bytecodes->push_back(*p);
Elliott Hughes9777ba22013-01-17 09:04:19 -08001776 }
1777 return JDWP::ERR_NONE;
1778}
1779
Elliott Hughes88d63092013-01-09 09:55:54 -08001780JDWP::JdwpTag Dbg::GetFieldBasicTag(JDWP::FieldId field_id) {
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001781 return BasicTagFromDescriptor(FromFieldId(field_id)->GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001782}
1783
Elliott Hughes88d63092013-01-09 09:55:54 -08001784JDWP::JdwpTag Dbg::GetStaticFieldBasicTag(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
Vladimir Marko83114892019-04-11 13:05:50 +01001788static JValue GetArtFieldValue(ArtField* f, ObjPtr<mirror::Object> o)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001789 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001790 Primitive::Type fieldType = f->GetTypeAsPrimitiveType();
1791 JValue field_value;
1792 switch (fieldType) {
1793 case Primitive::kPrimBoolean:
1794 field_value.SetZ(f->GetBoolean(o));
1795 return field_value;
1796
1797 case Primitive::kPrimByte:
1798 field_value.SetB(f->GetByte(o));
1799 return field_value;
1800
1801 case Primitive::kPrimChar:
1802 field_value.SetC(f->GetChar(o));
1803 return field_value;
1804
1805 case Primitive::kPrimShort:
1806 field_value.SetS(f->GetShort(o));
1807 return field_value;
1808
1809 case Primitive::kPrimInt:
1810 case Primitive::kPrimFloat:
1811 // Int and Float must be treated as 32-bit values in JDWP.
1812 field_value.SetI(f->GetInt(o));
1813 return field_value;
1814
1815 case Primitive::kPrimLong:
1816 case Primitive::kPrimDouble:
1817 // Long and Double must be treated as 64-bit values in JDWP.
1818 field_value.SetJ(f->GetLong(o));
1819 return field_value;
1820
1821 case Primitive::kPrimNot:
Vladimir Markobcf17522018-06-01 13:14:32 +01001822 field_value.SetL(f->GetObject(o));
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001823 return field_value;
1824
1825 case Primitive::kPrimVoid:
1826 LOG(FATAL) << "Attempt to read from field of type 'void'";
1827 UNREACHABLE();
1828 }
1829 LOG(FATAL) << "Attempt to read from field of unknown type";
1830 UNREACHABLE();
1831}
1832
Elliott Hughes88d63092013-01-09 09:55:54 -08001833static JDWP::JdwpError GetFieldValueImpl(JDWP::RefTypeId ref_type_id, JDWP::ObjectId object_id,
1834 JDWP::FieldId field_id, JDWP::ExpandBuf* pReply,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001835 bool is_static)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001836 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001837 JDWP::JdwpError error;
Vladimir Marko4617d582019-03-28 13:48:31 +00001838 ObjPtr<mirror::Class> c = DecodeClass(ref_type_id, &error);
Ian Rogersc0542af2014-09-03 16:16:56 -07001839 if (ref_type_id != 0 && c == nullptr) {
1840 return error;
Elliott Hughes0cf74332012-02-23 23:14:00 -08001841 }
1842
Jeff Haode19a252016-09-14 15:56:35 -07001843 Thread* self = Thread::Current();
1844 StackHandleScope<2> hs(self);
1845 MutableHandle<mirror::Object>
Vladimir Marko83114892019-04-11 13:05:50 +01001846 o(hs.NewHandle(Dbg::GetObjectRegistry()->Get<mirror::Object>(object_id, &error)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08001847 if ((!is_static && o == nullptr) || error != JDWP::ERR_NONE) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001848 return JDWP::ERR_INVALID_OBJECT;
1849 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001850 ArtField* f = FromFieldId(field_id);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001851
Vladimir Marko4617d582019-03-28 13:48:31 +00001852 ObjPtr<mirror::Class> receiver_class = c;
Andreas Gampefa4333d2017-02-14 11:10:34 -08001853 if (receiver_class == nullptr && o != nullptr) {
Elliott Hughes0cf74332012-02-23 23:14:00 -08001854 receiver_class = o->GetClass();
1855 }
Jeff Haode19a252016-09-14 15:56:35 -07001856
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001857 // TODO: should we give up now if receiver_class is null?
Ian Rogersc0542af2014-09-03 16:16:56 -07001858 if (receiver_class != nullptr && !f->GetDeclaringClass()->IsAssignableFrom(receiver_class)) {
David Sehr709b0702016-10-13 09:12:37 -07001859 LOG(INFO) << "ERR_INVALID_FIELDID: " << f->PrettyField() << " "
1860 << receiver_class->PrettyClass();
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001861 return JDWP::ERR_INVALID_FIELDID;
1862 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001863
Jeff Haode19a252016-09-14 15:56:35 -07001864 // Ensure the field's class is initialized.
1865 Handle<mirror::Class> klass(hs.NewHandle(f->GetDeclaringClass()));
1866 if (!Runtime::Current()->GetClassLinker()->EnsureInitialized(self, klass, true, false)) {
David Sehr709b0702016-10-13 09:12:37 -07001867 LOG(WARNING) << "Not able to initialize class for SetValues: "
1868 << mirror::Class::PrettyClass(klass.Get());
Jeff Haode19a252016-09-14 15:56:35 -07001869 }
1870
Elliott Hughes0cf74332012-02-23 23:14:00 -08001871 // The RI only enforces the static/non-static mismatch in one direction.
1872 // TODO: should we change the tests and check both?
1873 if (is_static) {
1874 if (!f->IsStatic()) {
1875 return JDWP::ERR_INVALID_FIELDID;
1876 }
1877 } else {
1878 if (f->IsStatic()) {
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001879 LOG(WARNING) << "Ignoring non-nullptr receiver for ObjectReference.GetValues"
David Sehr709b0702016-10-13 09:12:37 -07001880 << " on static field " << f->PrettyField();
Elliott Hughes0cf74332012-02-23 23:14:00 -08001881 }
1882 }
jeffhao0dfbb7e2012-11-28 15:26:03 -08001883 if (f->IsStatic()) {
Jeff Haode19a252016-09-14 15:56:35 -07001884 o.Assign(f->GetDeclaringClass());
jeffhao0dfbb7e2012-11-28 15:26:03 -08001885 }
Elliott Hughes0cf74332012-02-23 23:14:00 -08001886
Jeff Haode19a252016-09-14 15:56:35 -07001887 JValue field_value(GetArtFieldValue(f, o.Get()));
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001888 JDWP::JdwpTag tag = BasicTagFromDescriptor(f->GetTypeDescriptor());
Jeff Hao579b0242013-11-18 13:16:49 -08001889 Dbg::OutputJValue(tag, &field_value, pReply);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001890 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001891}
1892
Elliott Hughes88d63092013-01-09 09:55:54 -08001893JDWP::JdwpError Dbg::GetFieldValue(JDWP::ObjectId object_id, JDWP::FieldId field_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001894 JDWP::ExpandBuf* pReply) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001895 return GetFieldValueImpl(0, object_id, field_id, pReply, false);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001896}
1897
Ian Rogersc0542af2014-09-03 16:16:56 -07001898JDWP::JdwpError Dbg::GetStaticFieldValue(JDWP::RefTypeId ref_type_id, JDWP::FieldId field_id,
1899 JDWP::ExpandBuf* pReply) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001900 return GetFieldValueImpl(ref_type_id, 0, field_id, pReply, true);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001901}
1902
Vladimir Marko83114892019-04-11 13:05:50 +01001903static JDWP::JdwpError SetArtFieldValue(ArtField* f,
1904 ObjPtr<mirror::Object> o,
1905 uint64_t value,
1906 int width)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001907 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001908 Primitive::Type fieldType = f->GetTypeAsPrimitiveType();
1909 // Debugging only happens at runtime so we know we are not running in a transaction.
1910 static constexpr bool kNoTransactionMode = false;
1911 switch (fieldType) {
1912 case Primitive::kPrimBoolean:
1913 CHECK_EQ(width, 1);
1914 f->SetBoolean<kNoTransactionMode>(o, static_cast<uint8_t>(value));
1915 return JDWP::ERR_NONE;
1916
1917 case Primitive::kPrimByte:
1918 CHECK_EQ(width, 1);
1919 f->SetByte<kNoTransactionMode>(o, static_cast<uint8_t>(value));
1920 return JDWP::ERR_NONE;
1921
1922 case Primitive::kPrimChar:
1923 CHECK_EQ(width, 2);
1924 f->SetChar<kNoTransactionMode>(o, static_cast<uint16_t>(value));
1925 return JDWP::ERR_NONE;
1926
1927 case Primitive::kPrimShort:
1928 CHECK_EQ(width, 2);
1929 f->SetShort<kNoTransactionMode>(o, static_cast<int16_t>(value));
1930 return JDWP::ERR_NONE;
1931
1932 case Primitive::kPrimInt:
1933 case Primitive::kPrimFloat:
1934 CHECK_EQ(width, 4);
1935 // Int and Float must be treated as 32-bit values in JDWP.
1936 f->SetInt<kNoTransactionMode>(o, static_cast<int32_t>(value));
1937 return JDWP::ERR_NONE;
1938
1939 case Primitive::kPrimLong:
1940 case Primitive::kPrimDouble:
1941 CHECK_EQ(width, 8);
1942 // Long and Double must be treated as 64-bit values in JDWP.
1943 f->SetLong<kNoTransactionMode>(o, value);
1944 return JDWP::ERR_NONE;
1945
1946 case Primitive::kPrimNot: {
1947 JDWP::JdwpError error;
Vladimir Marko83114892019-04-11 13:05:50 +01001948 ObjPtr<mirror::Object> v = Dbg::GetObjectRegistry()->Get<mirror::Object>(value, &error);
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001949 if (error != JDWP::ERR_NONE) {
1950 return JDWP::ERR_INVALID_OBJECT;
1951 }
1952 if (v != nullptr) {
Mathieu Chartier3398c782016-09-30 10:27:43 -07001953 ObjPtr<mirror::Class> field_type;
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001954 {
1955 StackHandleScope<2> hs(Thread::Current());
Vladimir Marko83114892019-04-11 13:05:50 +01001956 HandleWrapperObjPtr<mirror::Object> h_v(hs.NewHandleWrapper(&v));
1957 HandleWrapperObjPtr<mirror::Object> h_o(hs.NewHandleWrapper(&o));
Vladimir Marko4098a7a2017-11-06 16:00:51 +00001958 field_type = f->ResolveType();
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001959 }
1960 if (!field_type->IsAssignableFrom(v->GetClass())) {
1961 return JDWP::ERR_INVALID_OBJECT;
1962 }
1963 }
1964 f->SetObject<kNoTransactionMode>(o, v);
1965 return JDWP::ERR_NONE;
1966 }
1967
1968 case Primitive::kPrimVoid:
1969 LOG(FATAL) << "Attempt to write to field of type 'void'";
1970 UNREACHABLE();
1971 }
1972 LOG(FATAL) << "Attempt to write to field of unknown type";
1973 UNREACHABLE();
1974}
1975
Elliott Hughes88d63092013-01-09 09:55:54 -08001976static JDWP::JdwpError SetFieldValueImpl(JDWP::ObjectId object_id, JDWP::FieldId field_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001977 uint64_t value, int width, bool is_static)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001978 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001979 JDWP::JdwpError error;
Jeff Haode19a252016-09-14 15:56:35 -07001980 Thread* self = Thread::Current();
1981 StackHandleScope<2> hs(self);
1982 MutableHandle<mirror::Object>
Vladimir Marko83114892019-04-11 13:05:50 +01001983 o(hs.NewHandle(Dbg::GetObjectRegistry()->Get<mirror::Object>(object_id, &error)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08001984 if ((!is_static && o == nullptr) || error != JDWP::ERR_NONE) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001985 return JDWP::ERR_INVALID_OBJECT;
1986 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001987 ArtField* f = FromFieldId(field_id);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001988
Jeff Haode19a252016-09-14 15:56:35 -07001989 // Ensure the field's class is initialized.
1990 Handle<mirror::Class> klass(hs.NewHandle(f->GetDeclaringClass()));
1991 if (!Runtime::Current()->GetClassLinker()->EnsureInitialized(self, klass, true, false)) {
David Sehr709b0702016-10-13 09:12:37 -07001992 LOG(WARNING) << "Not able to initialize class for SetValues: "
1993 << mirror::Class::PrettyClass(klass.Get());
Jeff Haode19a252016-09-14 15:56:35 -07001994 }
1995
Elliott Hughes0cf74332012-02-23 23:14:00 -08001996 // The RI only enforces the static/non-static mismatch in one direction.
1997 // TODO: should we change the tests and check both?
1998 if (is_static) {
1999 if (!f->IsStatic()) {
2000 return JDWP::ERR_INVALID_FIELDID;
2001 }
2002 } else {
2003 if (f->IsStatic()) {
Sebastien Hertz05c26b32015-06-11 18:42:58 +02002004 LOG(WARNING) << "Ignoring non-nullptr receiver for ObjectReference.SetValues"
David Sehr709b0702016-10-13 09:12:37 -07002005 << " on static field " << f->PrettyField();
Elliott Hughes0cf74332012-02-23 23:14:00 -08002006 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002007 }
jeffhao0dfbb7e2012-11-28 15:26:03 -08002008 if (f->IsStatic()) {
Jeff Haode19a252016-09-14 15:56:35 -07002009 o.Assign(f->GetDeclaringClass());
jeffhao0dfbb7e2012-11-28 15:26:03 -08002010 }
Jeff Haode19a252016-09-14 15:56:35 -07002011 return SetArtFieldValue(f, o.Get(), value, width);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002012}
2013
Elliott Hughes88d63092013-01-09 09:55:54 -08002014JDWP::JdwpError Dbg::SetFieldValue(JDWP::ObjectId object_id, JDWP::FieldId field_id, uint64_t value,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002015 int width) {
Elliott Hughes88d63092013-01-09 09:55:54 -08002016 return SetFieldValueImpl(object_id, field_id, value, width, false);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002017}
2018
Elliott Hughes88d63092013-01-09 09:55:54 -08002019JDWP::JdwpError Dbg::SetStaticFieldValue(JDWP::FieldId field_id, uint64_t value, int width) {
2020 return SetFieldValueImpl(0, field_id, value, width, true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002021}
2022
Sebastien Hertzb0b0b492014-09-15 11:27:27 +02002023JDWP::JdwpError Dbg::StringToUtf8(JDWP::ObjectId string_id, std::string* str) {
Ian Rogersc0542af2014-09-03 16:16:56 -07002024 JDWP::JdwpError error;
Vladimir Marko83114892019-04-11 13:05:50 +01002025 ObjPtr<mirror::Object> obj = gRegistry->Get<mirror::Object>(string_id, &error);
Sebastien Hertzb0b0b492014-09-15 11:27:27 +02002026 if (error != JDWP::ERR_NONE) {
2027 return error;
2028 }
2029 if (obj == nullptr) {
2030 return JDWP::ERR_INVALID_OBJECT;
2031 }
2032 {
2033 ScopedObjectAccessUnchecked soa(Thread::Current());
Mathieu Chartier0795f232016-09-27 18:43:30 -07002034 ObjPtr<mirror::Class> java_lang_String =
2035 soa.Decode<mirror::Class>(WellKnownClasses::java_lang_String);
Sebastien Hertzb0b0b492014-09-15 11:27:27 +02002036 if (!java_lang_String->IsAssignableFrom(obj->GetClass())) {
2037 // This isn't a string.
2038 return JDWP::ERR_INVALID_STRING;
2039 }
2040 }
2041 *str = obj->AsString()->ToModifiedUtf8();
2042 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002043}
2044
Jeff Hao579b0242013-11-18 13:16:49 -08002045void Dbg::OutputJValue(JDWP::JdwpTag tag, const JValue* return_value, JDWP::ExpandBuf* pReply) {
2046 if (IsPrimitiveTag(tag)) {
2047 expandBufAdd1(pReply, tag);
2048 if (tag == JDWP::JT_BOOLEAN || tag == JDWP::JT_BYTE) {
2049 expandBufAdd1(pReply, return_value->GetI());
2050 } else if (tag == JDWP::JT_CHAR || tag == JDWP::JT_SHORT) {
2051 expandBufAdd2BE(pReply, return_value->GetI());
2052 } else if (tag == JDWP::JT_FLOAT || tag == JDWP::JT_INT) {
2053 expandBufAdd4BE(pReply, return_value->GetI());
2054 } else if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
2055 expandBufAdd8BE(pReply, return_value->GetJ());
2056 } else {
2057 CHECK_EQ(tag, JDWP::JT_VOID);
2058 }
2059 } else {
Ian Rogers98379392014-02-24 16:53:16 -08002060 ScopedObjectAccessUnchecked soa(Thread::Current());
Vladimir Marko83114892019-04-11 13:05:50 +01002061 ObjPtr<mirror::Object> value = return_value->GetL();
Ian Rogers98379392014-02-24 16:53:16 -08002062 expandBufAdd1(pReply, TagFromObject(soa, value));
Jeff Hao579b0242013-11-18 13:16:49 -08002063 expandBufAddObjectId(pReply, gRegistry->Add(value));
2064 }
2065}
2066
Ian Rogersc0542af2014-09-03 16:16:56 -07002067JDWP::JdwpError Dbg::GetThreadName(JDWP::ObjectId thread_id, std::string* name) {
jeffhaoa77f0f62012-12-05 17:19:31 -08002068 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002069 JDWP::JdwpError error;
Roland Levillain4b8f1ec2015-08-26 18:34:03 +01002070 DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002071 if (error != JDWP::ERR_NONE && error != JDWP::ERR_THREAD_NOT_ALIVE) {
2072 return error;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08002073 }
Elliott Hughes221229c2013-01-08 18:17:50 -08002074
2075 // We still need to report the zombie threads' names, so we can't just call Thread::GetThreadName.
Vladimir Marko83114892019-04-11 13:05:50 +01002076 ObjPtr<mirror::Object> thread_object = gRegistry->Get<mirror::Object>(thread_id, &error);
Ian Rogersc0542af2014-09-03 16:16:56 -07002077 CHECK(thread_object != nullptr) << error;
Mathieu Chartierc7853442015-03-27 14:35:38 -07002078 ArtField* java_lang_Thread_name_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08002079 jni::DecodeArtField(WellKnownClasses::java_lang_Thread_name);
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07002080 ObjPtr<mirror::String> s(java_lang_Thread_name_field->GetObject(thread_object)->AsString());
Ian Rogersc0542af2014-09-03 16:16:56 -07002081 if (s != nullptr) {
2082 *name = s->ToModifiedUtf8();
Elliott Hughes221229c2013-01-08 18:17:50 -08002083 }
2084 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002085}
2086
Elliott Hughes221229c2013-01-08 18:17:50 -08002087JDWP::JdwpError Dbg::GetThreadGroup(JDWP::ObjectId thread_id, JDWP::ExpandBuf* pReply) {
Sebastien Hertza06430c2014-09-15 19:21:30 +02002088 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002089 JDWP::JdwpError error;
Vladimir Marko83114892019-04-11 13:05:50 +01002090 ObjPtr<mirror::Object> thread_object = gRegistry->Get<mirror::Object>(thread_id, &error);
Ian Rogersc0542af2014-09-03 16:16:56 -07002091 if (error != JDWP::ERR_NONE) {
Elliott Hughes2435a572012-02-17 16:07:41 -08002092 return JDWP::ERR_INVALID_OBJECT;
2093 }
Mathieu Chartier268764d2016-09-13 12:09:38 -07002094 ScopedAssertNoThreadSuspension ants("Debugger: GetThreadGroup");
Elliott Hughes2435a572012-02-17 16:07:41 -08002095 // Okay, so it's an object, but is it actually a thread?
Roland Levillain4b8f1ec2015-08-26 18:34:03 +01002096 DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002097 if (error == JDWP::ERR_THREAD_NOT_ALIVE) {
2098 // Zombie threads are in the null group.
2099 expandBufAddObjectId(pReply, JDWP::ObjectId(0));
Sebastien Hertz52d131d2014-03-13 16:17:40 +01002100 error = JDWP::ERR_NONE;
2101 } else if (error == JDWP::ERR_NONE) {
Mathieu Chartier0795f232016-09-27 18:43:30 -07002102 ObjPtr<mirror::Class> c = soa.Decode<mirror::Class>(WellKnownClasses::java_lang_Thread);
Sebastien Hertz52d131d2014-03-13 16:17:40 +01002103 CHECK(c != nullptr);
Andreas Gampe08883de2016-11-08 13:20:52 -08002104 ArtField* f = jni::DecodeArtField(WellKnownClasses::java_lang_Thread_group);
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07002105 CHECK(f != nullptr);
Mathieu Chartier3398c782016-09-30 10:27:43 -07002106 ObjPtr<mirror::Object> group = f->GetObject(thread_object);
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07002107 CHECK(group != nullptr);
Sebastien Hertz52d131d2014-03-13 16:17:40 +01002108 JDWP::ObjectId thread_group_id = gRegistry->Add(group);
2109 expandBufAddObjectId(pReply, thread_group_id);
Elliott Hughes221229c2013-01-08 18:17:50 -08002110 }
Sebastien Hertz52d131d2014-03-13 16:17:40 +01002111 return error;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002112}
2113
Vladimir Marko83114892019-04-11 13:05:50 +01002114static ObjPtr<mirror::Object> DecodeThreadGroup(ScopedObjectAccessUnchecked& soa,
2115 JDWP::ObjectId thread_group_id,
2116 JDWP::JdwpError* error)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002117 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko83114892019-04-11 13:05:50 +01002118 ObjPtr<mirror::Object> thread_group =
2119 Dbg::GetObjectRegistry()->Get<mirror::Object>(thread_group_id, error);
Sebastien Hertza06430c2014-09-15 19:21:30 +02002120 if (*error != JDWP::ERR_NONE) {
2121 return nullptr;
2122 }
2123 if (thread_group == nullptr) {
2124 *error = JDWP::ERR_INVALID_OBJECT;
2125 return nullptr;
2126 }
Mathieu Chartier0795f232016-09-27 18:43:30 -07002127 ObjPtr<mirror::Class> c =
2128 soa.Decode<mirror::Class>(WellKnownClasses::java_lang_ThreadGroup);
Ian Rogers98379392014-02-24 16:53:16 -08002129 CHECK(c != nullptr);
Sebastien Hertza06430c2014-09-15 19:21:30 +02002130 if (!c->IsAssignableFrom(thread_group->GetClass())) {
2131 // This is not a java.lang.ThreadGroup.
2132 *error = JDWP::ERR_INVALID_THREAD_GROUP;
2133 return nullptr;
2134 }
2135 *error = JDWP::ERR_NONE;
2136 return thread_group;
2137}
2138
2139JDWP::JdwpError Dbg::GetThreadGroupName(JDWP::ObjectId thread_group_id, JDWP::ExpandBuf* pReply) {
2140 ScopedObjectAccessUnchecked soa(Thread::Current());
2141 JDWP::JdwpError error;
Vladimir Marko83114892019-04-11 13:05:50 +01002142 ObjPtr<mirror::Object> thread_group = DecodeThreadGroup(soa, thread_group_id, &error);
Sebastien Hertza06430c2014-09-15 19:21:30 +02002143 if (error != JDWP::ERR_NONE) {
2144 return error;
2145 }
Mathieu Chartier268764d2016-09-13 12:09:38 -07002146 ScopedAssertNoThreadSuspension ants("Debugger: GetThreadGroupName");
Andreas Gampe08883de2016-11-08 13:20:52 -08002147 ArtField* f = jni::DecodeArtField(WellKnownClasses::java_lang_ThreadGroup_name);
Ian Rogersc0542af2014-09-03 16:16:56 -07002148 CHECK(f != nullptr);
Mathieu Chartier3398c782016-09-30 10:27:43 -07002149 ObjPtr<mirror::String> s = f->GetObject(thread_group)->AsString();
Sebastien Hertza06430c2014-09-15 19:21:30 +02002150
2151 std::string thread_group_name(s->ToModifiedUtf8());
2152 expandBufAddUtf8String(pReply, thread_group_name);
2153 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002154}
2155
Sebastien Hertza06430c2014-09-15 19:21:30 +02002156JDWP::JdwpError Dbg::GetThreadGroupParent(JDWP::ObjectId thread_group_id, JDWP::ExpandBuf* pReply) {
Ian Rogers98379392014-02-24 16:53:16 -08002157 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002158 JDWP::JdwpError error;
Vladimir Marko83114892019-04-11 13:05:50 +01002159 ObjPtr<mirror::Object> thread_group = DecodeThreadGroup(soa, thread_group_id, &error);
Sebastien Hertza06430c2014-09-15 19:21:30 +02002160 if (error != JDWP::ERR_NONE) {
2161 return error;
2162 }
Mathieu Chartier3398c782016-09-30 10:27:43 -07002163 ObjPtr<mirror::Object> parent;
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07002164 {
Mathieu Chartier268764d2016-09-13 12:09:38 -07002165 ScopedAssertNoThreadSuspension ants("Debugger: GetThreadGroupParent");
Andreas Gampe08883de2016-11-08 13:20:52 -08002166 ArtField* f = jni::DecodeArtField(WellKnownClasses::java_lang_ThreadGroup_parent);
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07002167 CHECK(f != nullptr);
2168 parent = f->GetObject(thread_group);
2169 }
Sebastien Hertza06430c2014-09-15 19:21:30 +02002170 JDWP::ObjectId parent_group_id = gRegistry->Add(parent);
2171 expandBufAddObjectId(pReply, parent_group_id);
2172 return JDWP::ERR_NONE;
2173}
2174
Vladimir Marko83114892019-04-11 13:05:50 +01002175static void GetChildThreadGroups(ObjPtr<mirror::Object> thread_group,
Sebastien Hertza06430c2014-09-15 19:21:30 +02002176 std::vector<JDWP::ObjectId>* child_thread_group_ids)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002177 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertza06430c2014-09-15 19:21:30 +02002178 CHECK(thread_group != nullptr);
2179
Przemyslaw Szczepaniak464595f2015-11-24 11:59:59 +00002180 // Get the int "ngroups" count of this thread group...
Andreas Gampe08883de2016-11-08 13:20:52 -08002181 ArtField* ngroups_field = jni::DecodeArtField(WellKnownClasses::java_lang_ThreadGroup_ngroups);
Przemyslaw Szczepaniak464595f2015-11-24 11:59:59 +00002182 CHECK(ngroups_field != nullptr);
2183 const int32_t size = ngroups_field->GetInt(thread_group);
2184 if (size == 0) {
2185 return;
Sebastien Hertze49e1952014-10-13 11:27:13 +02002186 }
Sebastien Hertza06430c2014-09-15 19:21:30 +02002187
Przemyslaw Szczepaniak464595f2015-11-24 11:59:59 +00002188 // Get the ThreadGroup[] "groups" out of this thread group...
Andreas Gampe08883de2016-11-08 13:20:52 -08002189 ArtField* groups_field = jni::DecodeArtField(WellKnownClasses::java_lang_ThreadGroup_groups);
Mathieu Chartier3398c782016-09-30 10:27:43 -07002190 ObjPtr<mirror::Object> groups_array = groups_field->GetObject(thread_group);
Przemyslaw Szczepaniak464595f2015-11-24 11:59:59 +00002191
2192 CHECK(groups_array != nullptr);
2193 CHECK(groups_array->IsObjectArray());
2194
Mathieu Chartier3398c782016-09-30 10:27:43 -07002195 ObjPtr<mirror::ObjectArray<mirror::Object>> groups_array_as_array =
Przemyslaw Szczepaniak464595f2015-11-24 11:59:59 +00002196 groups_array->AsObjectArray<mirror::Object>();
Sebastien Hertza06430c2014-09-15 19:21:30 +02002197
2198 // Copy the first 'size' elements out of the array into the result.
Sebastien Hertz6995c602014-09-09 12:10:13 +02002199 ObjectRegistry* registry = Dbg::GetObjectRegistry();
Sebastien Hertza06430c2014-09-15 19:21:30 +02002200 for (int32_t i = 0; i < size; ++i) {
Przemyslaw Szczepaniak464595f2015-11-24 11:59:59 +00002201 child_thread_group_ids->push_back(registry->Add(groups_array_as_array->Get(i)));
Sebastien Hertza06430c2014-09-15 19:21:30 +02002202 }
2203}
2204
2205JDWP::JdwpError Dbg::GetThreadGroupChildren(JDWP::ObjectId thread_group_id,
2206 JDWP::ExpandBuf* pReply) {
2207 ScopedObjectAccessUnchecked soa(Thread::Current());
2208 JDWP::JdwpError error;
Vladimir Marko83114892019-04-11 13:05:50 +01002209 ObjPtr<mirror::Object> thread_group = DecodeThreadGroup(soa, thread_group_id, &error);
Sebastien Hertza06430c2014-09-15 19:21:30 +02002210 if (error != JDWP::ERR_NONE) {
2211 return error;
2212 }
2213
2214 // Add child threads.
2215 {
2216 std::vector<JDWP::ObjectId> child_thread_ids;
2217 GetThreads(thread_group, &child_thread_ids);
2218 expandBufAdd4BE(pReply, child_thread_ids.size());
2219 for (JDWP::ObjectId child_thread_id : child_thread_ids) {
2220 expandBufAddObjectId(pReply, child_thread_id);
2221 }
2222 }
2223
2224 // Add child thread groups.
2225 {
2226 std::vector<JDWP::ObjectId> child_thread_groups_ids;
Andreas Gampe08883de2016-11-08 13:20:52 -08002227 GetChildThreadGroups(thread_group, &child_thread_groups_ids);
Sebastien Hertza06430c2014-09-15 19:21:30 +02002228 expandBufAdd4BE(pReply, child_thread_groups_ids.size());
2229 for (JDWP::ObjectId child_thread_group_id : child_thread_groups_ids) {
2230 expandBufAddObjectId(pReply, child_thread_group_id);
2231 }
2232 }
2233
2234 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002235}
2236
2237JDWP::ObjectId Dbg::GetSystemThreadGroupId() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002238 ScopedObjectAccessUnchecked soa(Thread::Current());
Andreas Gampe08883de2016-11-08 13:20:52 -08002239 ArtField* f = jni::DecodeArtField(WellKnownClasses::java_lang_ThreadGroup_systemThreadGroup);
Mathieu Chartier3398c782016-09-30 10:27:43 -07002240 ObjPtr<mirror::Object> group = f->GetObject(f->GetDeclaringClass());
Ian Rogers365c1022012-06-22 15:05:28 -07002241 return gRegistry->Add(group);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002242}
2243
Jeff Hao920af3e2013-08-28 15:46:38 -07002244JDWP::JdwpThreadStatus Dbg::ToJdwpThreadStatus(ThreadState state) {
2245 switch (state) {
2246 case kBlocked:
2247 return JDWP::TS_MONITOR;
2248 case kNative:
2249 case kRunnable:
2250 case kSuspended:
2251 return JDWP::TS_RUNNING;
2252 case kSleeping:
2253 return JDWP::TS_SLEEPING;
2254 case kStarting:
2255 case kTerminated:
2256 return JDWP::TS_ZOMBIE;
2257 case kTimedWaiting:
Alex Light77fee872017-09-05 14:51:49 -07002258 case kWaitingForTaskProcessor:
2259 case kWaitingForLockInflation:
Sebastien Hertzbae182c2013-12-17 10:42:03 +01002260 case kWaitingForCheckPointsToRun:
Jeff Hao920af3e2013-08-28 15:46:38 -07002261 case kWaitingForDebuggerSend:
2262 case kWaitingForDebuggerSuspension:
2263 case kWaitingForDebuggerToAttach:
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002264 case kWaitingForDeoptimization:
Jeff Hao920af3e2013-08-28 15:46:38 -07002265 case kWaitingForGcToComplete:
Mathieu Chartierb43390c2015-05-12 10:47:11 -07002266 case kWaitingForGetObjectsAllocated:
Jeff Hao920af3e2013-08-28 15:46:38 -07002267 case kWaitingForJniOnLoad:
Sebastien Hertzbae182c2013-12-17 10:42:03 +01002268 case kWaitingForMethodTracingStart:
Jeff Hao920af3e2013-08-28 15:46:38 -07002269 case kWaitingForSignalCatcherOutput:
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -08002270 case kWaitingForVisitObjects:
Jeff Hao920af3e2013-08-28 15:46:38 -07002271 case kWaitingInMainDebuggerLoop:
2272 case kWaitingInMainSignalCatcherLoop:
2273 case kWaitingPerformingGc:
Mathieu Chartier90ef3db2015-08-04 15:19:41 -07002274 case kWaitingWeakGcRootRead:
Hiroshi Yamauchi76f55b02015-08-21 16:10:39 -07002275 case kWaitingForGcThreadFlip:
Koji Fukui34857b52019-03-20 19:13:00 +09002276 case kNativeForAbort:
Jeff Hao920af3e2013-08-28 15:46:38 -07002277 case kWaiting:
2278 return JDWP::TS_WAIT;
2279 // Don't add a 'default' here so the compiler can spot incompatible enum changes.
2280 }
2281 LOG(FATAL) << "Unknown thread state: " << state;
Elliott Hughesc1896c92018-11-29 11:33:18 -08002282 UNREACHABLE();
Jeff Hao920af3e2013-08-28 15:46:38 -07002283}
2284
Sebastien Hertz52d131d2014-03-13 16:17:40 +01002285JDWP::JdwpError Dbg::GetThreadStatus(JDWP::ObjectId thread_id, JDWP::JdwpThreadStatus* pThreadStatus,
2286 JDWP::JdwpSuspendStatus* pSuspendStatus) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002287 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes499c5132011-11-17 14:55:11 -08002288
Elliott Hughes9e0c1752013-01-09 14:02:58 -08002289 *pSuspendStatus = JDWP::SUSPEND_STATUS_NOT_SUSPENDED;
2290
Ian Rogersc0542af2014-09-03 16:16:56 -07002291 JDWP::JdwpError error;
2292 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002293 if (error != JDWP::ERR_NONE) {
2294 if (error == JDWP::ERR_THREAD_NOT_ALIVE) {
2295 *pThreadStatus = JDWP::TS_ZOMBIE;
Elliott Hughes221229c2013-01-08 18:17:50 -08002296 return JDWP::ERR_NONE;
2297 }
2298 return error;
Elliott Hughes499c5132011-11-17 14:55:11 -08002299 }
2300
Elliott Hughes9e0c1752013-01-09 14:02:58 -08002301 if (IsSuspendedForDebugger(soa, thread)) {
2302 *pSuspendStatus = JDWP::SUSPEND_STATUS_SUSPENDED;
Elliott Hughes499c5132011-11-17 14:55:11 -08002303 }
2304
Jeff Hao920af3e2013-08-28 15:46:38 -07002305 *pThreadStatus = ToJdwpThreadStatus(thread->GetState());
Elliott Hughes221229c2013-01-08 18:17:50 -08002306 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002307}
2308
Elliott Hughes221229c2013-01-08 18:17:50 -08002309JDWP::JdwpError Dbg::GetThreadDebugSuspendCount(JDWP::ObjectId thread_id, JDWP::ExpandBuf* pReply) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002310 ScopedObjectAccess soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002311 JDWP::JdwpError error;
2312 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002313 if (error != JDWP::ERR_NONE) {
2314 return error;
Elliott Hughes2435a572012-02-17 16:07:41 -08002315 }
Ian Rogers50b35e22012-10-04 10:09:15 -07002316 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002317 expandBufAdd4BE(pReply, thread->GetDebugSuspendCount());
Elliott Hughes2435a572012-02-17 16:07:41 -08002318 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002319}
2320
Elliott Hughesf9501702013-01-11 11:22:27 -08002321JDWP::JdwpError Dbg::Interrupt(JDWP::ObjectId thread_id) {
2322 ScopedObjectAccess soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002323 JDWP::JdwpError error;
2324 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughesf9501702013-01-11 11:22:27 -08002325 if (error != JDWP::ERR_NONE) {
2326 return error;
2327 }
Ian Rogersdd7624d2014-03-14 17:43:00 -07002328 thread->Interrupt(soa.Self());
Elliott Hughesf9501702013-01-11 11:22:27 -08002329 return JDWP::ERR_NONE;
2330}
2331
Vladimir Marko83114892019-04-11 13:05:50 +01002332static bool IsInDesiredThreadGroup(ObjPtr<mirror::Object> desired_thread_group,
2333 ObjPtr<mirror::Object> peer)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002334 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz070f7322014-09-09 12:08:49 +02002335 // Do we want threads from all thread groups?
2336 if (desired_thread_group == nullptr) {
2337 return true;
2338 }
Andreas Gampe08883de2016-11-08 13:20:52 -08002339 ArtField* thread_group_field = jni::DecodeArtField(WellKnownClasses::java_lang_Thread_group);
Sebastien Hertz070f7322014-09-09 12:08:49 +02002340 DCHECK(thread_group_field != nullptr);
Mathieu Chartier3398c782016-09-30 10:27:43 -07002341 ObjPtr<mirror::Object> group = thread_group_field->GetObject(peer);
Sebastien Hertz070f7322014-09-09 12:08:49 +02002342 return (group == desired_thread_group);
2343}
2344
Vladimir Marko83114892019-04-11 13:05:50 +01002345void Dbg::GetThreads(ObjPtr<mirror::Object> thread_group, std::vector<JDWP::ObjectId>* thread_ids) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002346 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz070f7322014-09-09 12:08:49 +02002347 std::list<Thread*> all_threads_list;
2348 {
2349 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
2350 all_threads_list = Runtime::Current()->GetThreadList()->GetList();
2351 }
2352 for (Thread* t : all_threads_list) {
2353 if (t == Dbg::GetDebugThread()) {
2354 // Skip the JDWP thread. Some debuggers get bent out of shape when they can't suspend and
2355 // query all threads, so it's easier if we just don't tell them about this thread.
2356 continue;
2357 }
2358 if (t->IsStillStarting()) {
2359 // This thread is being started (and has been registered in the thread list). However, it is
2360 // not completely started yet so we must ignore it.
2361 continue;
2362 }
Vladimir Marko83114892019-04-11 13:05:50 +01002363 ObjPtr<mirror::Object> peer = t->GetPeerFromOtherThread();
Sebastien Hertz070f7322014-09-09 12:08:49 +02002364 if (peer == nullptr) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002365 // 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 +02002366 // this thread yet.
2367 // TODO: if we identified threads to the debugger by their Thread*
2368 // rather than their peer's mirror::Object*, we could fix this.
2369 // Doing so might help us report ZOMBIE threads too.
2370 continue;
2371 }
Andreas Gampe08883de2016-11-08 13:20:52 -08002372 if (IsInDesiredThreadGroup(thread_group, peer)) {
Sebastien Hertz070f7322014-09-09 12:08:49 +02002373 thread_ids->push_back(gRegistry->Add(peer));
2374 }
2375 }
Elliott Hughescaf76542012-06-28 16:08:22 -07002376}
Elliott Hughesa2155262011-11-16 16:26:58 -08002377
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002378static int GetStackDepth(Thread* thread) REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampec7d878d2018-11-19 18:42:06 +00002379 size_t depth = 0u;
2380 StackVisitor::WalkStack(
2381 [&depth](const StackVisitor* visitor) REQUIRES_SHARED(Locks::mutator_lock_) {
2382 if (!visitor->GetMethod()->IsRuntimeMethod()) {
2383 ++depth;
2384 }
2385 return true;
2386 },
2387 thread,
2388 /* context= */ nullptr,
2389 StackVisitor::StackWalkKind::kIncludeInlinedFrames);
2390 return depth;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002391}
2392
Ian Rogersc0542af2014-09-03 16:16:56 -07002393JDWP::JdwpError Dbg::GetThreadFrameCount(JDWP::ObjectId thread_id, size_t* result) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002394 ScopedObjectAccess soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002395 JDWP::JdwpError error;
2396 *result = 0;
2397 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002398 if (error != JDWP::ERR_NONE) {
2399 return error;
2400 }
Elliott Hughesf15f4a02013-01-09 10:09:38 -08002401 if (!IsSuspendedForDebugger(soa, thread)) {
2402 return JDWP::ERR_THREAD_NOT_SUSPENDED;
2403 }
Ian Rogersc0542af2014-09-03 16:16:56 -07002404 *result = GetStackDepth(thread);
Elliott Hughes221229c2013-01-08 18:17:50 -08002405 return JDWP::ERR_NONE;
Elliott Hughes86964332012-02-15 19:37:42 -08002406}
2407
Andreas Gampec7d878d2018-11-19 18:42:06 +00002408JDWP::JdwpError Dbg::GetThreadFrames(JDWP::ObjectId thread_id,
2409 const size_t start_frame,
2410 const size_t frame_count,
2411 JDWP::ExpandBuf* buf) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002412 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002413 JDWP::JdwpError error;
2414 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002415 if (error != JDWP::ERR_NONE) {
2416 return error;
2417 }
Elliott Hughesf15f4a02013-01-09 10:09:38 -08002418 if (!IsSuspendedForDebugger(soa, thread)) {
2419 return JDWP::ERR_THREAD_NOT_SUSPENDED;
2420 }
Andreas Gampec7d878d2018-11-19 18:42:06 +00002421
2422 expandBufAdd4BE(buf, frame_count);
2423
2424 size_t depth = 0u;
2425 StackVisitor::WalkStack(
2426 [&](StackVisitor* visitor) REQUIRES_SHARED(Locks::mutator_lock_) {
2427 if (visitor->GetMethod()->IsRuntimeMethod()) {
2428 return true; // The debugger can't do anything useful with a frame that has no Method*.
2429 }
2430 if (depth >= start_frame + frame_count) {
2431 return false;
2432 }
2433 if (depth >= start_frame) {
2434 JDWP::FrameId frame_id(visitor->GetFrameId());
2435 JDWP::JdwpLocation location;
2436 SetJdwpLocation(&location, visitor->GetMethod(), visitor->GetDexPc());
2437 VLOG(jdwp)
2438 << StringPrintf(" Frame %3zd: id=%3" PRIu64 " ", depth, frame_id) << location;
2439 expandBufAdd8BE(buf, frame_id);
2440 expandBufAddLocation(buf, location);
2441 }
2442 ++depth;
2443 return true;
2444 },
2445 thread,
2446 /* context= */ nullptr,
2447 StackVisitor::StackWalkKind::kIncludeInlinedFrames);
2448
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002449 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002450}
2451
2452JDWP::ObjectId Dbg::GetThreadSelfId() {
Sebastien Hertz6995c602014-09-09 12:10:13 +02002453 return GetThreadId(Thread::Current());
2454}
2455
2456JDWP::ObjectId Dbg::GetThreadId(Thread* thread) {
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07002457 ScopedObjectAccessUnchecked soa(Thread::Current());
Nicolas Geoffraycafa0812017-02-15 18:27:34 +00002458 return gRegistry->Add(thread->GetPeerFromOtherThread());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002459}
2460
Elliott Hughes475fc232011-10-25 15:00:35 -07002461void Dbg::SuspendVM() {
Hiroshi Yamauchi8f95cf32016-04-19 11:14:06 -07002462 // Avoid a deadlock between GC and debugger where GC gets suspended during GC. b/25800335.
2463 gc::ScopedGCCriticalSection gcs(Thread::Current(),
2464 gc::kGcCauseDebugger,
2465 gc::kCollectorTypeDebugger);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002466 Runtime::Current()->GetThreadList()->SuspendAllForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002467}
2468
2469void Dbg::ResumeVM() {
Sebastien Hertz253fa552014-10-14 17:27:15 +02002470 Runtime::Current()->GetThreadList()->ResumeAllForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002471}
2472
Elliott Hughes221229c2013-01-08 18:17:50 -08002473JDWP::JdwpError Dbg::SuspendThread(JDWP::ObjectId thread_id, bool request_suspension) {
Ian Rogersf3d874c2014-07-17 18:52:42 -07002474 Thread* self = Thread::Current();
Ian Rogersc0542af2014-09-03 16:16:56 -07002475 ScopedLocalRef<jobject> peer(self->GetJniEnv(), nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002476 {
Ian Rogersf3d874c2014-07-17 18:52:42 -07002477 ScopedObjectAccess soa(self);
Ian Rogersc0542af2014-09-03 16:16:56 -07002478 JDWP::JdwpError error;
Vladimir Marko83114892019-04-11 13:05:50 +01002479 peer.reset(soa.AddLocalReference<jobject>(gRegistry->Get<mirror::Object>(thread_id, &error)));
Elliott Hughes4e235312011-12-02 11:34:15 -08002480 }
Ian Rogersc0542af2014-09-03 16:16:56 -07002481 if (peer.get() == nullptr) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002482 return JDWP::ERR_THREAD_NOT_ALIVE;
2483 }
Ian Rogers4ad5cd32014-11-11 23:08:07 -08002484 // Suspend thread to build stack trace.
Elliott Hughesf327e072013-01-09 16:01:26 -08002485 bool timed_out;
Brian Carlstromba32de42014-08-27 23:43:46 -07002486 ThreadList* thread_list = Runtime::Current()->GetThreadList();
Sebastien Hertzcdd798d2017-04-18 18:28:51 +02002487 Thread* thread = thread_list->SuspendThreadByPeer(peer.get(),
2488 request_suspension,
Alex Light46f93402017-06-29 11:59:50 -07002489 SuspendReason::kForDebugger,
Brian Carlstromba32de42014-08-27 23:43:46 -07002490 &timed_out);
Ian Rogersc0542af2014-09-03 16:16:56 -07002491 if (thread != nullptr) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002492 return JDWP::ERR_NONE;
Elliott Hughesf327e072013-01-09 16:01:26 -08002493 } else if (timed_out) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002494 return JDWP::ERR_INTERNAL;
2495 } else {
2496 return JDWP::ERR_THREAD_NOT_ALIVE;
2497 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002498}
2499
Elliott Hughes221229c2013-01-08 18:17:50 -08002500void Dbg::ResumeThread(JDWP::ObjectId thread_id) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002501 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002502 JDWP::JdwpError error;
Vladimir Marko83114892019-04-11 13:05:50 +01002503 ObjPtr<mirror::Object> peer = gRegistry->Get<mirror::Object>(thread_id, &error);
Ian Rogersc0542af2014-09-03 16:16:56 -07002504 CHECK(peer != nullptr) << error;
jeffhaoa77f0f62012-12-05 17:19:31 -08002505 Thread* thread;
2506 {
2507 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
2508 thread = Thread::FromManagedThread(soa, peer);
2509 }
Ian Rogersc0542af2014-09-03 16:16:56 -07002510 if (thread == nullptr) {
Elliott Hughes4e235312011-12-02 11:34:15 -08002511 LOG(WARNING) << "No such thread for resume: " << peer;
2512 return;
2513 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002514 bool needs_resume;
2515 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002516 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Sebastien Hertz70d60272017-04-14 14:18:36 +02002517 needs_resume = thread->GetDebugSuspendCount() > 0;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002518 }
2519 if (needs_resume) {
Alex Light88fd7202017-06-30 08:31:59 -07002520 bool resumed = Runtime::Current()->GetThreadList()->Resume(thread, SuspendReason::kForDebugger);
2521 DCHECK(resumed);
Elliott Hughes546b9862012-06-20 16:06:13 -07002522 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002523}
2524
2525void Dbg::SuspendSelf() {
Elliott Hughes475fc232011-10-25 15:00:35 -07002526 Runtime::Current()->GetThreadList()->SuspendSelfForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002527}
2528
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002529JDWP::JdwpError Dbg::GetThisObject(JDWP::ObjectId thread_id, JDWP::FrameId frame_id,
2530 JDWP::ObjectId* result) {
2531 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz69206392015-04-07 15:54:25 +02002532 JDWP::JdwpError error;
2533 Thread* thread = DecodeThread(soa, thread_id, &error);
2534 if (error != JDWP::ERR_NONE) {
2535 return error;
2536 }
2537 if (!IsSuspendedForDebugger(soa, thread)) {
2538 return JDWP::ERR_THREAD_NOT_SUSPENDED;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002539 }
Ian Rogers700a4022014-05-19 16:49:03 -07002540 std::unique_ptr<Context> context(Context::Create());
Vladimir Marko83114892019-04-11 13:05:50 +01002541 ObjPtr<mirror::Object> this_object = nullptr;
Andreas Gampec7d878d2018-11-19 18:42:06 +00002542 StackVisitor::WalkStack(
2543 [&](art::StackVisitor* stack_visitor) REQUIRES_SHARED(Locks::mutator_lock_) {
2544 if (frame_id != stack_visitor->GetFrameId()) {
2545 return true; // continue
2546 } else {
2547 this_object = stack_visitor->GetThisObject();
2548 return false;
2549 }
2550 },
2551 thread,
2552 context.get(),
2553 art::StackVisitor::StackWalkKind::kIncludeInlinedFrames);
2554 *result = gRegistry->Add(this_object);
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002555 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002556}
2557
Andreas Gampec7d878d2018-11-19 18:42:06 +00002558template <typename FrameHandler>
2559static JDWP::JdwpError FindAndHandleNonNativeFrame(Thread* thread,
2560 JDWP::FrameId frame_id,
2561 const FrameHandler& handler)
2562 REQUIRES_SHARED(Locks::mutator_lock_) {
2563 JDWP::JdwpError result = JDWP::ERR_INVALID_FRAMEID;
2564 std::unique_ptr<Context> context(Context::Create());
2565 StackVisitor::WalkStack(
2566 [&](art::StackVisitor* stack_visitor) REQUIRES_SHARED(Locks::mutator_lock_) {
2567 if (stack_visitor->GetFrameId() != frame_id) {
2568 return true; // Not our frame, carry on.
2569 }
2570 ArtMethod* m = stack_visitor->GetMethod();
2571 if (m->IsNative()) {
2572 // We can't read/write local value from/into native method.
2573 result = JDWP::ERR_OPAQUE_FRAME;
2574 } else {
2575 // We found our frame.
2576 result = handler(stack_visitor);
2577 }
2578 return false;
2579 },
2580 thread,
2581 context.get(),
2582 art::StackVisitor::StackWalkKind::kIncludeInlinedFrames);
2583 return result;
2584}
Sebastien Hertz8009f392014-09-01 17:07:11 +02002585
2586JDWP::JdwpError Dbg::GetLocalValues(JDWP::Request* request, JDWP::ExpandBuf* pReply) {
2587 JDWP::ObjectId thread_id = request->ReadThreadId();
2588 JDWP::FrameId frame_id = request->ReadFrameId();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002589
2590 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz69206392015-04-07 15:54:25 +02002591 JDWP::JdwpError error;
2592 Thread* thread = DecodeThread(soa, thread_id, &error);
2593 if (error != JDWP::ERR_NONE) {
2594 return error;
2595 }
2596 if (!IsSuspendedForDebugger(soa, thread)) {
2597 return JDWP::ERR_THREAD_NOT_SUSPENDED;
Elliott Hughes221229c2013-01-08 18:17:50 -08002598 }
Sebastien Hertz8009f392014-09-01 17:07:11 +02002599
Andreas Gampec7d878d2018-11-19 18:42:06 +00002600 return FindAndHandleNonNativeFrame(
2601 thread,
2602 frame_id,
2603 [&](art::StackVisitor* stack_visitor) REQUIRES_SHARED(Locks::mutator_lock_) {
2604 // Read the values from visitor's context.
2605 int32_t slot_count = request->ReadSigned32("slot count");
2606 expandBufAdd4BE(pReply, slot_count); /* "int values" */
2607 for (int32_t i = 0; i < slot_count; ++i) {
2608 uint32_t slot = request->ReadUnsigned32("slot");
2609 JDWP::JdwpTag reqSigByte = request->ReadTag();
Sebastien Hertz8009f392014-09-01 17:07:11 +02002610
Andreas Gampec7d878d2018-11-19 18:42:06 +00002611 VLOG(jdwp) << " --> slot " << slot << " " << reqSigByte;
Sebastien Hertz8009f392014-09-01 17:07:11 +02002612
Andreas Gampec7d878d2018-11-19 18:42:06 +00002613 size_t width = Dbg::GetTagWidth(reqSigByte);
2614 uint8_t* ptr = expandBufAddSpace(pReply, width + 1);
2615 error = Dbg::GetLocalValue(*stack_visitor, soa, slot, reqSigByte, ptr, width);
2616 if (error != JDWP::ERR_NONE) {
2617 return error;
2618 }
2619 }
2620 return JDWP::ERR_NONE;
2621 });
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002622}
2623
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002624constexpr JDWP::JdwpError kStackFrameLocalAccessError = JDWP::ERR_ABSENT_INFORMATION;
2625
2626static std::string GetStackContextAsString(const StackVisitor& visitor)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002627 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002628 return StringPrintf(" at DEX pc 0x%08x in method %s", visitor.GetDexPc(false),
David Sehr709b0702016-10-13 09:12:37 -07002629 ArtMethod::PrettyMethod(visitor.GetMethod()).c_str());
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002630}
2631
2632static JDWP::JdwpError FailGetLocalValue(const StackVisitor& visitor, uint16_t vreg,
2633 JDWP::JdwpTag tag)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002634 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002635 LOG(ERROR) << "Failed to read " << tag << " local from register v" << vreg
2636 << GetStackContextAsString(visitor);
2637 return kStackFrameLocalAccessError;
2638}
2639
Sebastien Hertz8009f392014-09-01 17:07:11 +02002640JDWP::JdwpError Dbg::GetLocalValue(const StackVisitor& visitor, ScopedObjectAccessUnchecked& soa,
2641 int slot, JDWP::JdwpTag tag, uint8_t* buf, size_t width) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002642 ArtMethod* m = visitor.GetMethod();
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002643 JDWP::JdwpError error = JDWP::ERR_NONE;
2644 uint16_t vreg = DemangleSlot(slot, m, &error);
2645 if (error != JDWP::ERR_NONE) {
2646 return error;
2647 }
Sebastien Hertz8009f392014-09-01 17:07:11 +02002648 // TODO: check that the tag is compatible with the actual type of the slot!
Sebastien Hertz8009f392014-09-01 17:07:11 +02002649 switch (tag) {
2650 case JDWP::JT_BOOLEAN: {
2651 CHECK_EQ(width, 1U);
2652 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002653 if (!visitor.GetVReg(m, vreg, kIntVReg, &intVal)) {
2654 return FailGetLocalValue(visitor, vreg, tag);
Ian Rogers0399dde2012-06-06 17:09:28 -07002655 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002656 VLOG(jdwp) << "get boolean local " << vreg << " = " << intVal;
2657 JDWP::Set1(buf + 1, intVal != 0);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002658 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002659 }
Sebastien Hertz8009f392014-09-01 17:07:11 +02002660 case JDWP::JT_BYTE: {
2661 CHECK_EQ(width, 1U);
2662 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002663 if (!visitor.GetVReg(m, vreg, kIntVReg, &intVal)) {
2664 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002665 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002666 VLOG(jdwp) << "get byte local " << vreg << " = " << intVal;
2667 JDWP::Set1(buf + 1, intVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002668 break;
2669 }
2670 case JDWP::JT_SHORT:
2671 case JDWP::JT_CHAR: {
2672 CHECK_EQ(width, 2U);
2673 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002674 if (!visitor.GetVReg(m, vreg, kIntVReg, &intVal)) {
2675 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002676 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002677 VLOG(jdwp) << "get short/char local " << vreg << " = " << intVal;
2678 JDWP::Set2BE(buf + 1, intVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002679 break;
2680 }
2681 case JDWP::JT_INT: {
2682 CHECK_EQ(width, 4U);
2683 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002684 if (!visitor.GetVReg(m, vreg, kIntVReg, &intVal)) {
2685 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002686 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002687 VLOG(jdwp) << "get int local " << vreg << " = " << intVal;
2688 JDWP::Set4BE(buf + 1, intVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002689 break;
2690 }
2691 case JDWP::JT_FLOAT: {
2692 CHECK_EQ(width, 4U);
2693 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002694 if (!visitor.GetVReg(m, vreg, kFloatVReg, &intVal)) {
2695 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002696 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002697 VLOG(jdwp) << "get float local " << vreg << " = " << intVal;
2698 JDWP::Set4BE(buf + 1, intVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002699 break;
2700 }
2701 case JDWP::JT_ARRAY:
2702 case JDWP::JT_CLASS_LOADER:
2703 case JDWP::JT_CLASS_OBJECT:
2704 case JDWP::JT_OBJECT:
2705 case JDWP::JT_STRING:
2706 case JDWP::JT_THREAD:
2707 case JDWP::JT_THREAD_GROUP: {
2708 CHECK_EQ(width, sizeof(JDWP::ObjectId));
2709 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002710 if (!visitor.GetVReg(m, vreg, kReferenceVReg, &intVal)) {
2711 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002712 }
Vladimir Marko83114892019-04-11 13:05:50 +01002713 ObjPtr<mirror::Object> o = reinterpret_cast<mirror::Object*>(intVal);
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002714 VLOG(jdwp) << "get " << tag << " object local " << vreg << " = " << o;
Vladimir Marko83114892019-04-11 13:05:50 +01002715 if (!Runtime::Current()->GetHeap()->IsValidObjectAddress(o.Ptr())) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002716 LOG(FATAL) << StringPrintf("Found invalid object %#" PRIxPTR " in register v%u",
Vladimir Marko83114892019-04-11 13:05:50 +01002717 reinterpret_cast<uintptr_t>(o.Ptr()), vreg)
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002718 << GetStackContextAsString(visitor);
2719 UNREACHABLE();
2720 }
2721 tag = TagFromObject(soa, o);
2722 JDWP::SetObjectId(buf + 1, gRegistry->Add(o));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002723 break;
2724 }
2725 case JDWP::JT_DOUBLE: {
2726 CHECK_EQ(width, 8U);
2727 uint64_t longVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002728 if (!visitor.GetVRegPair(m, vreg, kDoubleLoVReg, kDoubleHiVReg, &longVal)) {
2729 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002730 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002731 VLOG(jdwp) << "get double local " << vreg << " = " << longVal;
2732 JDWP::Set8BE(buf + 1, longVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002733 break;
2734 }
2735 case JDWP::JT_LONG: {
2736 CHECK_EQ(width, 8U);
2737 uint64_t longVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002738 if (!visitor.GetVRegPair(m, vreg, kLongLoVReg, kLongHiVReg, &longVal)) {
2739 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002740 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002741 VLOG(jdwp) << "get long local " << vreg << " = " << longVal;
2742 JDWP::Set8BE(buf + 1, longVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002743 break;
2744 }
2745 default:
2746 LOG(FATAL) << "Unknown tag " << tag;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002747 UNREACHABLE();
Sebastien Hertz8009f392014-09-01 17:07:11 +02002748 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002749
Sebastien Hertz8009f392014-09-01 17:07:11 +02002750 // Prepend tag, which may have been updated.
2751 JDWP::Set1(buf, tag);
2752 return JDWP::ERR_NONE;
2753}
2754
2755JDWP::JdwpError Dbg::SetLocalValues(JDWP::Request* request) {
2756 JDWP::ObjectId thread_id = request->ReadThreadId();
2757 JDWP::FrameId frame_id = request->ReadFrameId();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002758
2759 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz69206392015-04-07 15:54:25 +02002760 JDWP::JdwpError error;
2761 Thread* thread = DecodeThread(soa, thread_id, &error);
2762 if (error != JDWP::ERR_NONE) {
2763 return error;
2764 }
2765 if (!IsSuspendedForDebugger(soa, thread)) {
2766 return JDWP::ERR_THREAD_NOT_SUSPENDED;
Elliott Hughes221229c2013-01-08 18:17:50 -08002767 }
Sebastien Hertz8009f392014-09-01 17:07:11 +02002768
Andreas Gampec7d878d2018-11-19 18:42:06 +00002769 return FindAndHandleNonNativeFrame(
2770 thread,
2771 frame_id,
2772 [&](art::StackVisitor* stack_visitor) REQUIRES_SHARED(Locks::mutator_lock_) {
2773 // Writes the values into visitor's context.
2774 int32_t slot_count = request->ReadSigned32("slot count");
2775 for (int32_t i = 0; i < slot_count; ++i) {
2776 uint32_t slot = request->ReadUnsigned32("slot");
2777 JDWP::JdwpTag sigByte = request->ReadTag();
2778 size_t width = Dbg::GetTagWidth(sigByte);
2779 uint64_t value = request->ReadValue(width);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002780
Andreas Gampec7d878d2018-11-19 18:42:06 +00002781 VLOG(jdwp) << " --> slot " << slot << " " << sigByte << " " << value;
2782 error = Dbg::SetLocalValue(thread, *stack_visitor, slot, sigByte, value, width);
2783 if (error != JDWP::ERR_NONE) {
2784 return error;
2785 }
2786 }
2787 return JDWP::ERR_NONE;
2788 });
Sebastien Hertz8009f392014-09-01 17:07:11 +02002789}
2790
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002791template<typename T>
2792static JDWP::JdwpError FailSetLocalValue(const StackVisitor& visitor, uint16_t vreg,
2793 JDWP::JdwpTag tag, T value)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002794 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002795 LOG(ERROR) << "Failed to write " << tag << " local " << value
2796 << " (0x" << std::hex << value << ") into register v" << vreg
2797 << GetStackContextAsString(visitor);
2798 return kStackFrameLocalAccessError;
2799}
2800
Mingyao Yang99170c62015-07-06 11:10:37 -07002801JDWP::JdwpError Dbg::SetLocalValue(Thread* thread, StackVisitor& visitor, int slot,
2802 JDWP::JdwpTag tag, uint64_t value, size_t width) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002803 ArtMethod* m = visitor.GetMethod();
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002804 JDWP::JdwpError error = JDWP::ERR_NONE;
2805 uint16_t vreg = DemangleSlot(slot, m, &error);
2806 if (error != JDWP::ERR_NONE) {
2807 return error;
2808 }
Sebastien Hertz8009f392014-09-01 17:07:11 +02002809 // TODO: check that the tag is compatible with the actual type of the slot!
Sebastien Hertz8009f392014-09-01 17:07:11 +02002810 switch (tag) {
2811 case JDWP::JT_BOOLEAN:
2812 case JDWP::JT_BYTE:
2813 CHECK_EQ(width, 1U);
Mingyao Yang636b9252015-07-31 16:40:24 -07002814 if (!visitor.SetVReg(m, vreg, static_cast<uint32_t>(value), kIntVReg)) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002815 return FailSetLocalValue(visitor, vreg, tag, static_cast<uint32_t>(value));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002816 }
2817 break;
2818 case JDWP::JT_SHORT:
2819 case JDWP::JT_CHAR:
2820 CHECK_EQ(width, 2U);
Mingyao Yang636b9252015-07-31 16:40:24 -07002821 if (!visitor.SetVReg(m, vreg, static_cast<uint32_t>(value), kIntVReg)) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002822 return FailSetLocalValue(visitor, vreg, tag, static_cast<uint32_t>(value));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002823 }
2824 break;
2825 case JDWP::JT_INT:
2826 CHECK_EQ(width, 4U);
Mingyao Yang636b9252015-07-31 16:40:24 -07002827 if (!visitor.SetVReg(m, vreg, static_cast<uint32_t>(value), kIntVReg)) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002828 return FailSetLocalValue(visitor, vreg, tag, static_cast<uint32_t>(value));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002829 }
2830 break;
2831 case JDWP::JT_FLOAT:
2832 CHECK_EQ(width, 4U);
Mingyao Yang636b9252015-07-31 16:40:24 -07002833 if (!visitor.SetVReg(m, vreg, static_cast<uint32_t>(value), kFloatVReg)) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002834 return FailSetLocalValue(visitor, vreg, tag, static_cast<uint32_t>(value));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002835 }
2836 break;
2837 case JDWP::JT_ARRAY:
2838 case JDWP::JT_CLASS_LOADER:
2839 case JDWP::JT_CLASS_OBJECT:
2840 case JDWP::JT_OBJECT:
2841 case JDWP::JT_STRING:
2842 case JDWP::JT_THREAD:
2843 case JDWP::JT_THREAD_GROUP: {
2844 CHECK_EQ(width, sizeof(JDWP::ObjectId));
Vladimir Marko83114892019-04-11 13:05:50 +01002845 ObjPtr<mirror::Object> o =
2846 gRegistry->Get<mirror::Object>(static_cast<JDWP::ObjectId>(value), &error);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002847 if (error != JDWP::ERR_NONE) {
2848 VLOG(jdwp) << tag << " object " << o << " is an invalid object";
2849 return JDWP::ERR_INVALID_OBJECT;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002850 }
Vladimir Marko439d1262019-04-12 14:45:07 +01002851 if (!visitor.SetVRegReference(m, vreg, o)) {
Vladimir Marko83114892019-04-11 13:05:50 +01002852 return FailSetLocalValue(visitor, vreg, tag, reinterpret_cast<uintptr_t>(o.Ptr()));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002853 }
2854 break;
2855 }
2856 case JDWP::JT_DOUBLE: {
2857 CHECK_EQ(width, 8U);
Mingyao Yang636b9252015-07-31 16:40:24 -07002858 if (!visitor.SetVRegPair(m, vreg, value, kDoubleLoVReg, kDoubleHiVReg)) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002859 return FailSetLocalValue(visitor, vreg, tag, value);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002860 }
2861 break;
2862 }
2863 case JDWP::JT_LONG: {
2864 CHECK_EQ(width, 8U);
Mingyao Yang636b9252015-07-31 16:40:24 -07002865 if (!visitor.SetVRegPair(m, vreg, value, kLongLoVReg, kLongHiVReg)) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002866 return FailSetLocalValue(visitor, vreg, tag, value);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002867 }
2868 break;
2869 }
2870 default:
2871 LOG(FATAL) << "Unknown tag " << tag;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002872 UNREACHABLE();
Sebastien Hertz8009f392014-09-01 17:07:11 +02002873 }
Mingyao Yang99170c62015-07-06 11:10:37 -07002874
2875 // If we set the local variable in a compiled frame, we need to trigger a deoptimization of
2876 // the stack so we continue execution with the interpreter using the new value(s) of the updated
2877 // local variable(s). To achieve this, we install instrumentation exit stub on each method of the
2878 // thread's stack. The stub will cause the deoptimization to happen.
2879 if (!visitor.IsShadowFrame() && thread->HasDebuggerShadowFrames()) {
2880 Runtime::Current()->GetInstrumentation()->InstrumentThreadStack(thread);
2881 }
2882
Sebastien Hertz8009f392014-09-01 17:07:11 +02002883 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002884}
2885
Mathieu Chartiere401d142015-04-22 13:56:20 -07002886static void SetEventLocation(JDWP::EventLocation* location, ArtMethod* m, uint32_t dex_pc)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002887 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz6995c602014-09-09 12:10:13 +02002888 DCHECK(location != nullptr);
2889 if (m == nullptr) {
2890 memset(location, 0, sizeof(*location));
2891 } else {
Alex Light97e78032017-06-27 17:51:55 -07002892 location->method = m->GetCanonicalMethod(kRuntimePointerSize);
Sebastien Hertz6995c602014-09-09 12:10:13 +02002893 location->dex_pc = (m->IsNative() || m->IsProxyMethod()) ? static_cast<uint32_t>(-1) : dex_pc;
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002894 }
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002895}
2896
Vladimir Marko83114892019-04-11 13:05:50 +01002897void Dbg::PostLocationEvent(ArtMethod* m,
2898 int dex_pc,
2899 ObjPtr<mirror::Object> this_object,
2900 int event_flags,
2901 const JValue* return_value) {
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002902 if (!IsDebuggerActive()) {
2903 return;
2904 }
2905 DCHECK(m != nullptr);
2906 DCHECK_EQ(m->IsStatic(), this_object == nullptr);
Sebastien Hertz6995c602014-09-09 12:10:13 +02002907 JDWP::EventLocation location;
2908 SetEventLocation(&location, m, dex_pc);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002909
Sebastien Hertzde48aa62015-05-26 11:53:39 +02002910 // We need to be sure no exception is pending when calling JdwpState::PostLocationEvent.
2911 // This is required to be able to call JNI functions to create JDWP ids. To achieve this,
2912 // we temporarily clear the current thread's exception (if any) and will restore it after
2913 // the call.
2914 // Note: the only way to get a pending exception here is to suspend on a move-exception
2915 // instruction.
2916 Thread* const self = Thread::Current();
2917 StackHandleScope<1> hs(self);
2918 Handle<mirror::Throwable> pending_exception(hs.NewHandle(self->GetException()));
2919 self->ClearException();
Andreas Gampefa4333d2017-02-14 11:10:34 -08002920 if (kIsDebugBuild && pending_exception != nullptr) {
Mathieu Chartier808c7a52017-12-15 11:19:33 -08002921 const Instruction& instr = location.method->DexInstructions().InstructionAt(location.dex_pc);
2922 CHECK_EQ(Instruction::MOVE_EXCEPTION, instr.Opcode());
Sebastien Hertzde48aa62015-05-26 11:53:39 +02002923 }
2924
Sebastien Hertz6995c602014-09-09 12:10:13 +02002925 gJdwpState->PostLocationEvent(&location, this_object, event_flags, return_value);
Sebastien Hertzde48aa62015-05-26 11:53:39 +02002926
Andreas Gampefa4333d2017-02-14 11:10:34 -08002927 if (pending_exception != nullptr) {
Sebastien Hertzde48aa62015-05-26 11:53:39 +02002928 self->SetException(pending_exception.Get());
2929 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002930}
2931
Vladimir Marko83114892019-04-11 13:05:50 +01002932void Dbg::PostFieldAccessEvent(ArtMethod* m,
2933 int dex_pc,
2934 ObjPtr<mirror::Object> this_object,
2935 ArtField* f) {
Alex Lighte00ec302017-06-16 08:56:43 -07002936 // TODO We should send events for native methods.
2937 if (!IsDebuggerActive() || m->IsNative()) {
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002938 return;
2939 }
2940 DCHECK(m != nullptr);
2941 DCHECK(f != nullptr);
Sebastien Hertz6995c602014-09-09 12:10:13 +02002942 JDWP::EventLocation location;
2943 SetEventLocation(&location, m, dex_pc);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002944
Sebastien Hertz6995c602014-09-09 12:10:13 +02002945 gJdwpState->PostFieldEvent(&location, f, this_object, nullptr, false);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002946}
2947
Vladimir Marko83114892019-04-11 13:05:50 +01002948void Dbg::PostFieldModificationEvent(ArtMethod* m,
2949 int dex_pc,
2950 ObjPtr<mirror::Object> this_object,
2951 ArtField* f,
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002952 const JValue* field_value) {
Alex Lighte00ec302017-06-16 08:56:43 -07002953 // TODO We should send events for native methods.
2954 if (!IsDebuggerActive() || m->IsNative()) {
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002955 return;
2956 }
2957 DCHECK(m != nullptr);
2958 DCHECK(f != nullptr);
2959 DCHECK(field_value != nullptr);
Sebastien Hertz6995c602014-09-09 12:10:13 +02002960 JDWP::EventLocation location;
2961 SetEventLocation(&location, m, dex_pc);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002962
Sebastien Hertz6995c602014-09-09 12:10:13 +02002963 gJdwpState->PostFieldEvent(&location, f, this_object, field_value, true);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002964}
2965
Vladimir Marko83114892019-04-11 13:05:50 +01002966void Dbg::PostException(ObjPtr<mirror::Throwable> exception_object) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002967 if (!IsDebuggerActive()) {
Ian Rogers0ad5bb82011-12-07 10:16:32 -08002968 return;
2969 }
Sebastien Hertz261bc042015-04-08 09:36:07 +02002970 Thread* const self = Thread::Current();
Andreas Gampec7d878d2018-11-19 18:42:06 +00002971 StackHandleScope<2> handle_scope(self);
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002972 Handle<mirror::Throwable> h_exception(handle_scope.NewHandle(exception_object));
Andreas Gampec7d878d2018-11-19 18:42:06 +00002973 MutableHandle<mirror::Object> this_at_throw = handle_scope.NewHandle<mirror::Object>(nullptr);
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002974 std::unique_ptr<Context> context(Context::Create());
Andreas Gampe3d477f32018-11-16 16:40:45 +00002975
Andreas Gampec7d878d2018-11-19 18:42:06 +00002976 ArtMethod* catch_method = nullptr;
2977 ArtMethod* throw_method = nullptr;
2978 uint32_t catch_dex_pc = dex::kDexNoIndex;
2979 uint32_t throw_dex_pc = dex::kDexNoIndex;
2980 StackVisitor::WalkStack(
2981 /**
2982 * Finds the location where this exception will be caught. We search until we reach the top
2983 * frame, in which case this exception is considered uncaught.
2984 */
2985 [&](const art::StackVisitor* stack_visitor) REQUIRES_SHARED(Locks::mutator_lock_) {
2986 ArtMethod* method = stack_visitor->GetMethod();
2987 DCHECK(method != nullptr);
2988 if (method->IsRuntimeMethod()) {
2989 // Ignore callee save method.
2990 DCHECK(method->IsCalleeSaveMethod());
2991 return true;
2992 }
2993
2994 uint32_t dex_pc = stack_visitor->GetDexPc();
2995 if (throw_method == nullptr) {
2996 // First Java method found. It is either the method that threw the exception,
2997 // or the Java native method that is reporting an exception thrown by
2998 // native code.
2999 this_at_throw.Assign(stack_visitor->GetThisObject());
3000 throw_method = method;
3001 throw_dex_pc = dex_pc;
3002 }
3003
3004 if (dex_pc != dex::kDexNoIndex) {
3005 StackHandleScope<1> hs(stack_visitor->GetThread());
3006 uint32_t found_dex_pc;
3007 Handle<mirror::Class> exception_class(hs.NewHandle(h_exception->GetClass()));
3008 bool unused_clear_exception;
3009 found_dex_pc = method->FindCatchBlock(exception_class, dex_pc, &unused_clear_exception);
3010 if (found_dex_pc != dex::kDexNoIndex) {
3011 catch_method = method;
3012 catch_dex_pc = found_dex_pc;
3013 return false; // End stack walk.
3014 }
3015 }
3016 return true; // Continue stack walk.
3017 },
3018 self,
3019 context.get(),
3020 art::StackVisitor::StackWalkKind::kIncludeInlinedFrames);
3021
3022 JDWP::EventLocation exception_throw_location;
3023 SetEventLocation(&exception_throw_location, throw_method, throw_dex_pc);
3024 JDWP::EventLocation exception_catch_location;
3025 SetEventLocation(&exception_catch_location, catch_method, catch_dex_pc);
3026
3027 gJdwpState->PostException(&exception_throw_location,
3028 h_exception.Get(),
3029 &exception_catch_location,
3030 this_at_throw.Get());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003031}
3032
Vladimir Marko83114892019-04-11 13:05:50 +01003033void Dbg::PostClassPrepare(ObjPtr<mirror::Class> c) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07003034 if (!IsDebuggerActive()) {
Elliott Hughes4740cdf2011-12-07 14:07:12 -08003035 return;
3036 }
Sebastien Hertz6995c602014-09-09 12:10:13 +02003037 gJdwpState->PostClassPrepare(c);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003038}
3039
Vladimir Marko83114892019-04-11 13:05:50 +01003040void Dbg::UpdateDebugger(Thread* thread,
3041 ObjPtr<mirror::Object> this_object,
3042 ArtMethod* m,
3043 uint32_t dex_pc,
3044 int event_flags,
3045 const JValue* return_value) {
Ian Rogers62d6c772013-02-27 08:32:07 -08003046 if (!IsDebuggerActive() || dex_pc == static_cast<uint32_t>(-2) /* fake method exit */) {
Elliott Hughes2aa2e392012-02-17 17:15:43 -08003047 return;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003048 }
3049
Elliott Hughes86964332012-02-15 19:37:42 -08003050 if (IsBreakpoint(m, dex_pc)) {
3051 event_flags |= kBreakpoint;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003052 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003053
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003054 // If the debugger is single-stepping one of our threads, check to
3055 // see if we're that thread and we've reached a step point.
3056 const SingleStepControl* single_step_control = thread->GetSingleStepControl();
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003057 if (single_step_control != nullptr) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003058 CHECK(!m->IsNative());
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003059 if (single_step_control->GetStepDepth() == JDWP::SD_INTO) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003060 // Step into method calls. We break when the line number
3061 // or method pointer changes. If we're in SS_MIN mode, we
3062 // always stop.
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003063 if (single_step_control->GetMethod() != m) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003064 event_flags |= kSingleStep;
3065 VLOG(jdwp) << "SS new method";
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003066 } else if (single_step_control->GetStepSize() == JDWP::SS_MIN) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003067 event_flags |= kSingleStep;
3068 VLOG(jdwp) << "SS new instruction";
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003069 } else if (single_step_control->ContainsDexPc(dex_pc)) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003070 event_flags |= kSingleStep;
3071 VLOG(jdwp) << "SS new line";
3072 }
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003073 } else if (single_step_control->GetStepDepth() == JDWP::SD_OVER) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003074 // Step over method calls. We break when the line number is
3075 // different and the frame depth is <= the original frame
3076 // depth. (We can't just compare on the method, because we
3077 // might get unrolled past it by an exception, and it's tricky
3078 // to identify recursion.)
3079
3080 int stack_depth = GetStackDepth(thread);
3081
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003082 if (stack_depth < single_step_control->GetStackDepth()) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003083 // Popped up one or more frames, always trigger.
3084 event_flags |= kSingleStep;
3085 VLOG(jdwp) << "SS method pop";
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003086 } else if (stack_depth == single_step_control->GetStackDepth()) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003087 // Same depth, see if we moved.
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003088 if (single_step_control->GetStepSize() == JDWP::SS_MIN) {
Elliott Hughes86964332012-02-15 19:37:42 -08003089 event_flags |= kSingleStep;
3090 VLOG(jdwp) << "SS new instruction";
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003091 } else if (single_step_control->ContainsDexPc(dex_pc)) {
Elliott Hughes2435a572012-02-17 16:07:41 -08003092 event_flags |= kSingleStep;
3093 VLOG(jdwp) << "SS new line";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003094 }
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003095 }
3096 } else {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003097 CHECK_EQ(single_step_control->GetStepDepth(), JDWP::SD_OUT);
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003098 // Return from the current method. We break when the frame
3099 // depth pops up.
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003100
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003101 // This differs from the "method exit" break in that it stops
3102 // with the PC at the next instruction in the returned-to
3103 // function, rather than the end of the returning function.
Elliott Hughes86964332012-02-15 19:37:42 -08003104
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003105 int stack_depth = GetStackDepth(thread);
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003106 if (stack_depth < single_step_control->GetStackDepth()) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003107 event_flags |= kSingleStep;
3108 VLOG(jdwp) << "SS method pop";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003109 }
3110 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003111 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003112
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003113 // If there's something interesting going on, see if it matches one
3114 // of the debugger filters.
3115 if (event_flags != 0) {
Sebastien Hertz8379b222014-02-24 17:38:15 +01003116 Dbg::PostLocationEvent(m, dex_pc, this_object, event_flags, return_value);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003117 }
3118}
3119
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003120size_t* Dbg::GetReferenceCounterForEvent(uint32_t instrumentation_event) {
3121 switch (instrumentation_event) {
3122 case instrumentation::Instrumentation::kMethodEntered:
3123 return &method_enter_event_ref_count_;
3124 case instrumentation::Instrumentation::kMethodExited:
3125 return &method_exit_event_ref_count_;
3126 case instrumentation::Instrumentation::kDexPcMoved:
3127 return &dex_pc_change_event_ref_count_;
3128 case instrumentation::Instrumentation::kFieldRead:
3129 return &field_read_event_ref_count_;
3130 case instrumentation::Instrumentation::kFieldWritten:
3131 return &field_write_event_ref_count_;
Alex Light6e1607e2017-08-23 10:06:18 -07003132 case instrumentation::Instrumentation::kExceptionThrown:
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003133 return &exception_catch_event_ref_count_;
3134 default:
3135 return nullptr;
3136 }
3137}
3138
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003139// Process request while all mutator threads are suspended.
3140void Dbg::ProcessDeoptimizationRequest(const DeoptimizationRequest& request) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003141 instrumentation::Instrumentation* instrumentation = Runtime::Current()->GetInstrumentation();
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003142 switch (request.GetKind()) {
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003143 case DeoptimizationRequest::kNothing:
3144 LOG(WARNING) << "Ignoring empty deoptimization request.";
3145 break;
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003146 case DeoptimizationRequest::kRegisterForEvent:
3147 VLOG(jdwp) << StringPrintf("Add debugger as listener for instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003148 request.InstrumentationEvent());
3149 instrumentation->AddListener(&gDebugInstrumentationListener, request.InstrumentationEvent());
3150 instrumentation_events_ |= request.InstrumentationEvent();
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003151 break;
3152 case DeoptimizationRequest::kUnregisterForEvent:
3153 VLOG(jdwp) << StringPrintf("Remove debugger as listener for instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003154 request.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003155 instrumentation->RemoveListener(&gDebugInstrumentationListener,
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003156 request.InstrumentationEvent());
3157 instrumentation_events_ &= ~request.InstrumentationEvent();
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003158 break;
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003159 case DeoptimizationRequest::kFullDeoptimization:
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003160 VLOG(jdwp) << "Deoptimize the world ...";
Sebastien Hertz0462c4c2015-04-01 16:34:17 +02003161 instrumentation->DeoptimizeEverything(kDbgInstrumentationKey);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003162 VLOG(jdwp) << "Deoptimize the world DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003163 break;
3164 case DeoptimizationRequest::kFullUndeoptimization:
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003165 VLOG(jdwp) << "Undeoptimize the world ...";
Sebastien Hertz0462c4c2015-04-01 16:34:17 +02003166 instrumentation->UndeoptimizeEverything(kDbgInstrumentationKey);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003167 VLOG(jdwp) << "Undeoptimize the world DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003168 break;
3169 case DeoptimizationRequest::kSelectiveDeoptimization:
David Sehr709b0702016-10-13 09:12:37 -07003170 VLOG(jdwp) << "Deoptimize method " << ArtMethod::PrettyMethod(request.Method()) << " ...";
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003171 instrumentation->Deoptimize(request.Method());
David Sehr709b0702016-10-13 09:12:37 -07003172 VLOG(jdwp) << "Deoptimize method " << ArtMethod::PrettyMethod(request.Method()) << " DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003173 break;
3174 case DeoptimizationRequest::kSelectiveUndeoptimization:
David Sehr709b0702016-10-13 09:12:37 -07003175 VLOG(jdwp) << "Undeoptimize method " << ArtMethod::PrettyMethod(request.Method()) << " ...";
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003176 instrumentation->Undeoptimize(request.Method());
David Sehr709b0702016-10-13 09:12:37 -07003177 VLOG(jdwp) << "Undeoptimize method " << ArtMethod::PrettyMethod(request.Method()) << " DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003178 break;
3179 default:
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003180 LOG(FATAL) << "Unsupported deoptimization request kind " << request.GetKind();
Elliott Hughesc1896c92018-11-29 11:33:18 -08003181 UNREACHABLE();
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003182 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003183}
3184
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003185void Dbg::RequestDeoptimization(const DeoptimizationRequest& req) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003186 if (req.GetKind() == DeoptimizationRequest::kNothing) {
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003187 // Nothing to do.
3188 return;
3189 }
Brian Carlstrom306db812014-09-05 13:01:41 -07003190 MutexLock mu(Thread::Current(), *Locks::deoptimization_lock_);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003191 RequestDeoptimizationLocked(req);
3192}
3193
3194void Dbg::RequestDeoptimizationLocked(const DeoptimizationRequest& req) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003195 switch (req.GetKind()) {
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003196 case DeoptimizationRequest::kRegisterForEvent: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003197 DCHECK_NE(req.InstrumentationEvent(), 0u);
3198 size_t* counter = GetReferenceCounterForEvent(req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003199 CHECK(counter != nullptr) << StringPrintf("No counter for instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003200 req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003201 if (*counter == 0) {
Sebastien Hertz7d2ae432014-05-15 11:26:34 +02003202 VLOG(jdwp) << StringPrintf("Queue request #%zd to start listening to instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003203 deoptimization_requests_.size(), req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003204 deoptimization_requests_.push_back(req);
3205 }
3206 *counter = *counter + 1;
3207 break;
3208 }
3209 case DeoptimizationRequest::kUnregisterForEvent: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003210 DCHECK_NE(req.InstrumentationEvent(), 0u);
3211 size_t* counter = GetReferenceCounterForEvent(req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003212 CHECK(counter != nullptr) << StringPrintf("No counter for instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003213 req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003214 *counter = *counter - 1;
3215 if (*counter == 0) {
Sebastien Hertz7d2ae432014-05-15 11:26:34 +02003216 VLOG(jdwp) << StringPrintf("Queue request #%zd to stop listening to instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003217 deoptimization_requests_.size(), req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003218 deoptimization_requests_.push_back(req);
3219 }
3220 break;
3221 }
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003222 case DeoptimizationRequest::kFullDeoptimization: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003223 DCHECK(req.Method() == nullptr);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003224 if (full_deoptimization_event_count_ == 0) {
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003225 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
3226 << " for full deoptimization";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003227 deoptimization_requests_.push_back(req);
3228 }
3229 ++full_deoptimization_event_count_;
3230 break;
3231 }
3232 case DeoptimizationRequest::kFullUndeoptimization: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003233 DCHECK(req.Method() == nullptr);
Sebastien Hertze713d932014-05-15 10:48:53 +02003234 DCHECK_GT(full_deoptimization_event_count_, 0U);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003235 --full_deoptimization_event_count_;
3236 if (full_deoptimization_event_count_ == 0) {
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003237 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
3238 << " for full undeoptimization";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003239 deoptimization_requests_.push_back(req);
3240 }
3241 break;
3242 }
3243 case DeoptimizationRequest::kSelectiveDeoptimization: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003244 DCHECK(req.Method() != nullptr);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003245 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
David Sehr709b0702016-10-13 09:12:37 -07003246 << " for deoptimization of " << req.Method()->PrettyMethod();
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003247 deoptimization_requests_.push_back(req);
3248 break;
3249 }
3250 case DeoptimizationRequest::kSelectiveUndeoptimization: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003251 DCHECK(req.Method() != nullptr);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003252 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
David Sehr709b0702016-10-13 09:12:37 -07003253 << " for undeoptimization of " << req.Method()->PrettyMethod();
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003254 deoptimization_requests_.push_back(req);
3255 break;
3256 }
3257 default: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003258 LOG(FATAL) << "Unknown deoptimization request kind " << req.GetKind();
Elliott Hughesc1896c92018-11-29 11:33:18 -08003259 UNREACHABLE();
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003260 }
3261 }
3262}
3263
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003264void Dbg::ManageDeoptimization() {
3265 Thread* const self = Thread::Current();
3266 {
3267 // Avoid suspend/resume if there is no pending request.
Brian Carlstrom306db812014-09-05 13:01:41 -07003268 MutexLock mu(self, *Locks::deoptimization_lock_);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003269 if (deoptimization_requests_.empty()) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003270 return;
3271 }
3272 }
3273 CHECK_EQ(self->GetState(), kRunnable);
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07003274 ScopedThreadSuspension sts(self, kWaitingForDeoptimization);
Mathieu Chartieraa516822015-10-02 15:53:37 -07003275 // Required for ProcessDeoptimizationRequest.
3276 gc::ScopedGCCriticalSection gcs(self,
3277 gc::kGcCauseInstrumentation,
3278 gc::kCollectorTypeInstrumentation);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003279 // We need to suspend mutator threads first.
Mathieu Chartier4f55e222015-09-04 13:26:21 -07003280 ScopedSuspendAll ssa(__FUNCTION__);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003281 const ThreadState old_state = self->SetStateUnsafe(kRunnable);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003282 {
Brian Carlstrom306db812014-09-05 13:01:41 -07003283 MutexLock mu(self, *Locks::deoptimization_lock_);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003284 size_t req_index = 0;
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003285 for (DeoptimizationRequest& request : deoptimization_requests_) {
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003286 VLOG(jdwp) << "Process deoptimization request #" << req_index++;
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003287 ProcessDeoptimizationRequest(request);
3288 }
3289 deoptimization_requests_.clear();
3290 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003291 CHECK_EQ(self->SetStateUnsafe(old_state), kRunnable);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003292}
3293
Mathieu Chartiere401d142015-04-22 13:56:20 -07003294static const Breakpoint* FindFirstBreakpointForMethod(ArtMethod* m)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003295 REQUIRES_SHARED(Locks::mutator_lock_, Locks::breakpoint_lock_) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003296 for (Breakpoint& breakpoint : gBreakpoints) {
Alex Light6c8467f2015-11-20 15:03:26 -08003297 if (breakpoint.IsInMethod(m)) {
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003298 return &breakpoint;
3299 }
3300 }
3301 return nullptr;
3302}
3303
Mathieu Chartiere401d142015-04-22 13:56:20 -07003304bool Dbg::MethodHasAnyBreakpoints(ArtMethod* method) {
Mathieu Chartierd8565452015-03-26 09:41:50 -07003305 ReaderMutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
3306 return FindFirstBreakpointForMethod(method) != nullptr;
3307}
3308
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003309// Sanity checks all existing breakpoints on the same method.
Mathieu Chartiere401d142015-04-22 13:56:20 -07003310static void SanityCheckExistingBreakpoints(ArtMethod* m,
Sebastien Hertzf3928792014-11-17 19:00:37 +01003311 DeoptimizationRequest::Kind deoptimization_kind)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003312 REQUIRES_SHARED(Locks::mutator_lock_, Locks::breakpoint_lock_) {
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003313 for (const Breakpoint& breakpoint : gBreakpoints) {
Alex Light6c8467f2015-11-20 15:03:26 -08003314 if (breakpoint.IsInMethod(m)) {
Sebastien Hertzf3928792014-11-17 19:00:37 +01003315 CHECK_EQ(deoptimization_kind, breakpoint.GetDeoptimizationKind());
3316 }
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003317 }
Sebastien Hertzf3928792014-11-17 19:00:37 +01003318 instrumentation::Instrumentation* instrumentation = Runtime::Current()->GetInstrumentation();
3319 if (deoptimization_kind == DeoptimizationRequest::kFullDeoptimization) {
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003320 // We should have deoptimized everything but not "selectively" deoptimized this method.
Sebastien Hertzf3928792014-11-17 19:00:37 +01003321 CHECK(instrumentation->AreAllMethodsDeoptimized());
3322 CHECK(!instrumentation->IsDeoptimized(m));
3323 } else if (deoptimization_kind == DeoptimizationRequest::kSelectiveDeoptimization) {
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003324 // We should have "selectively" deoptimized this method.
3325 // Note: while we have not deoptimized everything for this method, we may have done it for
3326 // another event.
Sebastien Hertzf3928792014-11-17 19:00:37 +01003327 CHECK(instrumentation->IsDeoptimized(m));
3328 } else {
3329 // This method does not require deoptimization.
3330 CHECK_EQ(deoptimization_kind, DeoptimizationRequest::kNothing);
3331 CHECK(!instrumentation->IsDeoptimized(m));
3332 }
3333}
3334
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003335// Returns the deoptimization kind required to set a breakpoint in a method.
3336// If a breakpoint has already been set, we also return the first breakpoint
3337// through the given 'existing_brkpt' pointer.
Sebastien Hertzf3928792014-11-17 19:00:37 +01003338static DeoptimizationRequest::Kind GetRequiredDeoptimizationKind(Thread* self,
Mathieu Chartiere401d142015-04-22 13:56:20 -07003339 ArtMethod* m,
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003340 const Breakpoint** existing_brkpt)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003341 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertzf3928792014-11-17 19:00:37 +01003342 if (!Dbg::RequiresDeoptimization()) {
3343 // We already run in interpreter-only mode so we don't need to deoptimize anything.
3344 VLOG(jdwp) << "No need for deoptimization when fully running with interpreter for method "
David Sehr709b0702016-10-13 09:12:37 -07003345 << ArtMethod::PrettyMethod(m);
Sebastien Hertzf3928792014-11-17 19:00:37 +01003346 return DeoptimizationRequest::kNothing;
3347 }
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003348 const Breakpoint* first_breakpoint;
Sebastien Hertzf3928792014-11-17 19:00:37 +01003349 {
3350 ReaderMutexLock mu(self, *Locks::breakpoint_lock_);
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003351 first_breakpoint = FindFirstBreakpointForMethod(m);
3352 *existing_brkpt = first_breakpoint;
Sebastien Hertzf3928792014-11-17 19:00:37 +01003353 }
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003354
3355 if (first_breakpoint == nullptr) {
Nicolas Geoffray6300fd72016-03-18 09:40:17 +00003356 // There is no breakpoint on this method yet: we need to deoptimize. If this method is default,
3357 // we deoptimize everything; otherwise we deoptimize only this method. We
Alex Light6c8467f2015-11-20 15:03:26 -08003358 // deoptimize with defaults because we do not know everywhere they are used. It is possible some
Nicolas Geoffray6300fd72016-03-18 09:40:17 +00003359 // of the copies could be missed.
Alex Light6c8467f2015-11-20 15:03:26 -08003360 // TODO Deoptimizing on default methods might not be necessary in all cases.
Nicolas Geoffray6300fd72016-03-18 09:40:17 +00003361 bool need_full_deoptimization = m->IsDefault();
Sebastien Hertzf3928792014-11-17 19:00:37 +01003362 if (need_full_deoptimization) {
Nicolas Geoffray6300fd72016-03-18 09:40:17 +00003363 VLOG(jdwp) << "Need full deoptimization because of copying of method "
David Sehr709b0702016-10-13 09:12:37 -07003364 << ArtMethod::PrettyMethod(m);
Sebastien Hertzf3928792014-11-17 19:00:37 +01003365 return DeoptimizationRequest::kFullDeoptimization;
3366 } else {
3367 // We don't need to deoptimize if the method has not been compiled.
Nicolas Geoffraya5891e82015-11-06 14:18:27 +00003368 const bool is_compiled = m->HasAnyCompiledCode();
Sebastien Hertzf3928792014-11-17 19:00:37 +01003369 if (is_compiled) {
David Sehr709b0702016-10-13 09:12:37 -07003370 VLOG(jdwp) << "Need selective deoptimization for compiled method "
3371 << ArtMethod::PrettyMethod(m);
Nicolas Geoffray6300fd72016-03-18 09:40:17 +00003372 return DeoptimizationRequest::kSelectiveDeoptimization;
Sebastien Hertzf3928792014-11-17 19:00:37 +01003373 } else {
3374 // Method is not compiled: we don't need to deoptimize.
David Sehr709b0702016-10-13 09:12:37 -07003375 VLOG(jdwp) << "No need for deoptimization for non-compiled method "
3376 << ArtMethod::PrettyMethod(m);
Sebastien Hertzf3928792014-11-17 19:00:37 +01003377 return DeoptimizationRequest::kNothing;
3378 }
3379 }
3380 } else {
3381 // There is at least one breakpoint for this method: we don't need to deoptimize.
3382 // Let's check that all breakpoints are configured the same way for deoptimization.
3383 VLOG(jdwp) << "Breakpoint already set: no deoptimization is required";
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003384 DeoptimizationRequest::Kind deoptimization_kind = first_breakpoint->GetDeoptimizationKind();
Sebastien Hertzf3928792014-11-17 19:00:37 +01003385 if (kIsDebugBuild) {
3386 ReaderMutexLock mu(self, *Locks::breakpoint_lock_);
3387 SanityCheckExistingBreakpoints(m, deoptimization_kind);
3388 }
3389 return DeoptimizationRequest::kNothing;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003390 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003391}
3392
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003393// Installs a breakpoint at the specified location. Also indicates through the deoptimization
3394// request if we need to deoptimize.
3395void Dbg::WatchLocation(const JDWP::JdwpLocation* location, DeoptimizationRequest* req) {
3396 Thread* const self = Thread::Current();
Mathieu Chartiere401d142015-04-22 13:56:20 -07003397 ArtMethod* m = FromMethodId(location->method_id);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003398 DCHECK(m != nullptr) << "No method for method id " << location->method_id;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003399
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003400 const Breakpoint* existing_breakpoint = nullptr;
3401 const DeoptimizationRequest::Kind deoptimization_kind =
3402 GetRequiredDeoptimizationKind(self, m, &existing_breakpoint);
Sebastien Hertzf3928792014-11-17 19:00:37 +01003403 req->SetKind(deoptimization_kind);
3404 if (deoptimization_kind == DeoptimizationRequest::kSelectiveDeoptimization) {
3405 req->SetMethod(m);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003406 } else {
Sebastien Hertzf3928792014-11-17 19:00:37 +01003407 CHECK(deoptimization_kind == DeoptimizationRequest::kNothing ||
3408 deoptimization_kind == DeoptimizationRequest::kFullDeoptimization);
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003409 req->SetMethod(nullptr);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003410 }
3411
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003412 {
3413 WriterMutexLock mu(self, *Locks::breakpoint_lock_);
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003414 // If there is at least one existing breakpoint on the same method, the new breakpoint
3415 // must have the same deoptimization kind than the existing breakpoint(s).
3416 DeoptimizationRequest::Kind breakpoint_deoptimization_kind;
3417 if (existing_breakpoint != nullptr) {
3418 breakpoint_deoptimization_kind = existing_breakpoint->GetDeoptimizationKind();
3419 } else {
3420 breakpoint_deoptimization_kind = deoptimization_kind;
3421 }
3422 gBreakpoints.push_back(Breakpoint(m, location->dex_pc, breakpoint_deoptimization_kind));
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003423 VLOG(jdwp) << "Set breakpoint #" << (gBreakpoints.size() - 1) << ": "
3424 << gBreakpoints[gBreakpoints.size() - 1];
3425 }
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003426}
3427
3428// Uninstalls a breakpoint at the specified location. Also indicates through the deoptimization
3429// request if we need to undeoptimize.
3430void Dbg::UnwatchLocation(const JDWP::JdwpLocation* location, DeoptimizationRequest* req) {
Sebastien Hertzed2be172014-08-19 15:33:43 +02003431 WriterMutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003432 ArtMethod* m = FromMethodId(location->method_id);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003433 DCHECK(m != nullptr) << "No method for method id " << location->method_id;
Sebastien Hertzf3928792014-11-17 19:00:37 +01003434 DeoptimizationRequest::Kind deoptimization_kind = DeoptimizationRequest::kNothing;
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003435 for (size_t i = 0, e = gBreakpoints.size(); i < e; ++i) {
Alex Light6c8467f2015-11-20 15:03:26 -08003436 if (gBreakpoints[i].DexPc() == location->dex_pc && gBreakpoints[i].IsInMethod(m)) {
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003437 VLOG(jdwp) << "Removed breakpoint #" << i << ": " << gBreakpoints[i];
Sebastien Hertzf3928792014-11-17 19:00:37 +01003438 deoptimization_kind = gBreakpoints[i].GetDeoptimizationKind();
3439 DCHECK_EQ(deoptimization_kind == DeoptimizationRequest::kSelectiveDeoptimization,
3440 Runtime::Current()->GetInstrumentation()->IsDeoptimized(m));
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003441 gBreakpoints.erase(gBreakpoints.begin() + i);
3442 break;
3443 }
3444 }
3445 const Breakpoint* const existing_breakpoint = FindFirstBreakpointForMethod(m);
3446 if (existing_breakpoint == nullptr) {
3447 // There is no more breakpoint on this method: we need to undeoptimize.
Sebastien Hertzf3928792014-11-17 19:00:37 +01003448 if (deoptimization_kind == DeoptimizationRequest::kFullDeoptimization) {
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003449 // This method required full deoptimization: we need to undeoptimize everything.
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003450 req->SetKind(DeoptimizationRequest::kFullUndeoptimization);
3451 req->SetMethod(nullptr);
Sebastien Hertzf3928792014-11-17 19:00:37 +01003452 } else if (deoptimization_kind == DeoptimizationRequest::kSelectiveDeoptimization) {
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003453 // This method required selective deoptimization: we need to undeoptimize only that method.
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003454 req->SetKind(DeoptimizationRequest::kSelectiveUndeoptimization);
3455 req->SetMethod(m);
Sebastien Hertzf3928792014-11-17 19:00:37 +01003456 } else {
3457 // This method had no need for deoptimization: do nothing.
3458 CHECK_EQ(deoptimization_kind, DeoptimizationRequest::kNothing);
3459 req->SetKind(DeoptimizationRequest::kNothing);
3460 req->SetMethod(nullptr);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003461 }
3462 } else {
3463 // There is at least one breakpoint for this method: we don't need to undeoptimize.
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003464 req->SetKind(DeoptimizationRequest::kNothing);
3465 req->SetMethod(nullptr);
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003466 if (kIsDebugBuild) {
Sebastien Hertzf3928792014-11-17 19:00:37 +01003467 SanityCheckExistingBreakpoints(m, deoptimization_kind);
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003468 }
Elliott Hughes86964332012-02-15 19:37:42 -08003469 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003470}
3471
Mathieu Chartiere401d142015-04-22 13:56:20 -07003472bool Dbg::IsForcedInterpreterNeededForCallingImpl(Thread* thread, ArtMethod* m) {
Daniel Mihalyieb076692014-08-22 17:33:31 +02003473 const SingleStepControl* const ssc = thread->GetSingleStepControl();
3474 if (ssc == nullptr) {
3475 // If we are not single-stepping, then we don't have to force interpreter.
3476 return false;
3477 }
3478 if (Runtime::Current()->GetInstrumentation()->InterpretOnly()) {
3479 // If we are in interpreter only mode, then we don't have to force interpreter.
3480 return false;
3481 }
3482
3483 if (!m->IsNative() && !m->IsProxyMethod()) {
3484 // If we want to step into a method, then we have to force interpreter on that call.
3485 if (ssc->GetStepDepth() == JDWP::SD_INTO) {
3486 return true;
3487 }
3488 }
3489 return false;
3490}
3491
Mathieu Chartiere401d142015-04-22 13:56:20 -07003492bool Dbg::IsForcedInterpreterNeededForResolutionImpl(Thread* thread, ArtMethod* m) {
Daniel Mihalyieb076692014-08-22 17:33:31 +02003493 instrumentation::Instrumentation* const instrumentation =
3494 Runtime::Current()->GetInstrumentation();
3495 // If we are in interpreter only mode, then we don't have to force interpreter.
3496 if (instrumentation->InterpretOnly()) {
3497 return false;
3498 }
3499 // We can only interpret pure Java method.
3500 if (m->IsNative() || m->IsProxyMethod()) {
3501 return false;
3502 }
3503 const SingleStepControl* const ssc = thread->GetSingleStepControl();
3504 if (ssc != nullptr) {
3505 // If we want to step into a method, then we have to force interpreter on that call.
3506 if (ssc->GetStepDepth() == JDWP::SD_INTO) {
3507 return true;
3508 }
3509 // If we are stepping out from a static initializer, by issuing a step
3510 // in or step over, that was implicitly invoked by calling a static method,
3511 // then we need to step into that method. Having a lower stack depth than
3512 // the one the single step control has indicates that the step originates
3513 // from the static initializer.
3514 if (ssc->GetStepDepth() != JDWP::SD_OUT &&
3515 ssc->GetStackDepth() > GetStackDepth(thread)) {
3516 return true;
3517 }
3518 }
3519 // There are cases where we have to force interpreter on deoptimized methods,
3520 // because in some cases the call will not be performed by invoking an entry
3521 // point that has been replaced by the deoptimization, but instead by directly
3522 // invoking the compiled code of the method, for example.
3523 return instrumentation->IsDeoptimized(m);
3524}
3525
Mathieu Chartiere401d142015-04-22 13:56:20 -07003526bool Dbg::IsForcedInstrumentationNeededForResolutionImpl(Thread* thread, ArtMethod* m) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07003527 // The upcall can be null and in that case we don't need to do anything.
Daniel Mihalyieb076692014-08-22 17:33:31 +02003528 if (m == nullptr) {
3529 return false;
3530 }
3531 instrumentation::Instrumentation* const instrumentation =
3532 Runtime::Current()->GetInstrumentation();
3533 // If we are in interpreter only mode, then we don't have to force interpreter.
3534 if (instrumentation->InterpretOnly()) {
3535 return false;
3536 }
3537 // We can only interpret pure Java method.
3538 if (m->IsNative() || m->IsProxyMethod()) {
3539 return false;
3540 }
3541 const SingleStepControl* const ssc = thread->GetSingleStepControl();
3542 if (ssc != nullptr) {
3543 // If we are stepping out from a static initializer, by issuing a step
3544 // out, that was implicitly invoked by calling a static method, then we
3545 // need to step into the caller of that method. Having a lower stack
3546 // depth than the one the single step control has indicates that the
3547 // step originates from the static initializer.
3548 if (ssc->GetStepDepth() == JDWP::SD_OUT &&
3549 ssc->GetStackDepth() > GetStackDepth(thread)) {
3550 return true;
3551 }
3552 }
3553 // If we are returning from a static intializer, that was implicitly
3554 // invoked by calling a static method and the caller is deoptimized,
3555 // then we have to deoptimize the stack without forcing interpreter
3556 // on the static method that was called originally. This problem can
3557 // be solved easily by forcing instrumentation on the called method,
3558 // because the instrumentation exit hook will recognise the need of
3559 // stack deoptimization by calling IsForcedInterpreterNeededForUpcall.
3560 return instrumentation->IsDeoptimized(m);
3561}
3562
Mathieu Chartiere401d142015-04-22 13:56:20 -07003563bool Dbg::IsForcedInterpreterNeededForUpcallImpl(Thread* thread, ArtMethod* m) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07003564 // The upcall can be null and in that case we don't need to do anything.
Daniel Mihalyieb076692014-08-22 17:33:31 +02003565 if (m == nullptr) {
3566 return false;
3567 }
3568 instrumentation::Instrumentation* const instrumentation =
3569 Runtime::Current()->GetInstrumentation();
3570 // If we are in interpreter only mode, then we don't have to force interpreter.
3571 if (instrumentation->InterpretOnly()) {
3572 return false;
3573 }
3574 // We can only interpret pure Java method.
3575 if (m->IsNative() || m->IsProxyMethod()) {
3576 return false;
3577 }
3578 const SingleStepControl* const ssc = thread->GetSingleStepControl();
3579 if (ssc != nullptr) {
3580 // The debugger is not interested in what is happening under the level
3581 // of the step, thus we only force interpreter when we are not below of
3582 // the step.
3583 if (ssc->GetStackDepth() >= GetStackDepth(thread)) {
3584 return true;
3585 }
3586 }
Mingyao Yang99170c62015-07-06 11:10:37 -07003587 if (thread->HasDebuggerShadowFrames()) {
3588 // We need to deoptimize the stack for the exception handling flow so that
3589 // we don't miss any deoptimization that should be done when there are
3590 // debugger shadow frames.
3591 return true;
3592 }
Daniel Mihalyieb076692014-08-22 17:33:31 +02003593 // We have to require stack deoptimization if the upcall is deoptimized.
3594 return instrumentation->IsDeoptimized(m);
3595}
3596
Sebastien Hertz520633b2015-09-08 17:03:36 +02003597// Do we need to deoptimize the stack to handle an exception?
3598bool Dbg::IsForcedInterpreterNeededForExceptionImpl(Thread* thread) {
3599 const SingleStepControl* const ssc = thread->GetSingleStepControl();
3600 if (ssc != nullptr) {
3601 // We deopt to step into the catch handler.
3602 return true;
3603 }
3604 // Deoptimization is required if at least one method in the stack needs it. However we
3605 // skip frames that will be unwound (thus not executed).
Andreas Gampec7d878d2018-11-19 18:42:06 +00003606 bool needs_deoptimization = false;
3607 StackVisitor::WalkStack(
3608 [&](art::StackVisitor* visitor) REQUIRES_SHARED(Locks::mutator_lock_) {
3609 // The visitor is meant to be used when handling exception from compiled code only.
3610 CHECK(!visitor->IsShadowFrame()) << "We only expect to visit compiled frame: "
3611 << ArtMethod::PrettyMethod(visitor->GetMethod());
3612 ArtMethod* method = visitor->GetMethod();
3613 if (method == nullptr) {
3614 // We reach an upcall and don't need to deoptimize this part of the stack (ManagedFragment)
3615 // so we can stop the visit.
3616 DCHECK(!needs_deoptimization);
3617 return false;
3618 }
3619 if (Runtime::Current()->GetInstrumentation()->InterpretOnly()) {
3620 // We found a compiled frame in the stack but instrumentation is set to interpret
3621 // everything: we need to deoptimize.
3622 needs_deoptimization = true;
3623 return false;
3624 }
3625 if (Runtime::Current()->GetInstrumentation()->IsDeoptimized(method)) {
3626 // We found a deoptimized method in the stack.
3627 needs_deoptimization = true;
3628 return false;
3629 }
3630 ShadowFrame* frame = visitor->GetThread()->FindDebuggerShadowFrame(visitor->GetFrameId());
3631 if (frame != nullptr) {
3632 // The debugger allocated a ShadowFrame to update a variable in the stack: we need to
3633 // deoptimize the stack to execute (and deallocate) this frame.
3634 needs_deoptimization = true;
3635 return false;
3636 }
3637 return true;
3638 },
3639 thread,
3640 /* context= */ nullptr,
3641 art::StackVisitor::StackWalkKind::kIncludeInlinedFrames,
3642 /* check_suspended */ true,
3643 /* include_transitions */ true);
3644 return needs_deoptimization;
Sebastien Hertz520633b2015-09-08 17:03:36 +02003645}
3646
Jeff Hao449db332013-04-12 18:30:52 -07003647// Scoped utility class to suspend a thread so that we may do tasks such as walk its stack. Doesn't
3648// cause suspension if the thread is the current thread.
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07003649class ScopedDebuggerThreadSuspension {
Jeff Hao449db332013-04-12 18:30:52 -07003650 public:
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07003651 ScopedDebuggerThreadSuspension(Thread* self, JDWP::ObjectId thread_id)
Mathieu Chartier90443472015-07-16 20:32:27 -07003652 REQUIRES(!Locks::thread_list_lock_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003653 REQUIRES_SHARED(Locks::mutator_lock_) :
Ian Rogersf3d874c2014-07-17 18:52:42 -07003654 thread_(nullptr),
Jeff Hao449db332013-04-12 18:30:52 -07003655 error_(JDWP::ERR_NONE),
3656 self_suspend_(false),
Ian Rogers33e95662013-05-20 20:29:14 -07003657 other_suspend_(false) {
Jeff Hao449db332013-04-12 18:30:52 -07003658 ScopedObjectAccessUnchecked soa(self);
Sebastien Hertz69206392015-04-07 15:54:25 +02003659 thread_ = DecodeThread(soa, thread_id, &error_);
Jeff Hao449db332013-04-12 18:30:52 -07003660 if (error_ == JDWP::ERR_NONE) {
3661 if (thread_ == soa.Self()) {
3662 self_suspend_ = true;
3663 } else {
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07003664 Thread* suspended_thread;
3665 {
3666 ScopedThreadSuspension sts(self, kWaitingForDebuggerSuspension);
3667 jobject thread_peer = Dbg::GetObjectRegistry()->GetJObject(thread_id);
3668 bool timed_out;
3669 ThreadList* const thread_list = Runtime::Current()->GetThreadList();
Sebastien Hertzcdd798d2017-04-18 18:28:51 +02003670 suspended_thread = thread_list->SuspendThreadByPeer(thread_peer,
Andreas Gampe98ea9d92018-10-19 14:06:15 -07003671 /* request_suspension= */ true,
Alex Light46f93402017-06-29 11:59:50 -07003672 SuspendReason::kForDebugger,
Sebastien Hertzcdd798d2017-04-18 18:28:51 +02003673 &timed_out);
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07003674 }
Ian Rogersf3d874c2014-07-17 18:52:42 -07003675 if (suspended_thread == nullptr) {
Jeff Hao449db332013-04-12 18:30:52 -07003676 // Thread terminated from under us while suspending.
3677 error_ = JDWP::ERR_INVALID_THREAD;
3678 } else {
3679 CHECK_EQ(suspended_thread, thread_);
3680 other_suspend_ = true;
3681 }
3682 }
3683 }
Elliott Hughes2435a572012-02-17 16:07:41 -08003684 }
Elliott Hughes86964332012-02-15 19:37:42 -08003685
Jeff Hao449db332013-04-12 18:30:52 -07003686 Thread* GetThread() const {
3687 return thread_;
3688 }
3689
3690 JDWP::JdwpError GetError() const {
3691 return error_;
3692 }
3693
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07003694 ~ScopedDebuggerThreadSuspension() {
Jeff Hao449db332013-04-12 18:30:52 -07003695 if (other_suspend_) {
Alex Light88fd7202017-06-30 08:31:59 -07003696 bool resumed = Runtime::Current()->GetThreadList()->Resume(thread_,
3697 SuspendReason::kForDebugger);
3698 DCHECK(resumed);
Jeff Hao449db332013-04-12 18:30:52 -07003699 }
3700 }
3701
3702 private:
3703 Thread* thread_;
3704 JDWP::JdwpError error_;
3705 bool self_suspend_;
3706 bool other_suspend_;
3707};
3708
3709JDWP::JdwpError Dbg::ConfigureStep(JDWP::ObjectId thread_id, JDWP::JdwpStepSize step_size,
3710 JDWP::JdwpStepDepth step_depth) {
3711 Thread* self = Thread::Current();
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07003712 ScopedDebuggerThreadSuspension sts(self, thread_id);
Jeff Hao449db332013-04-12 18:30:52 -07003713 if (sts.GetError() != JDWP::ERR_NONE) {
3714 return sts.GetError();
3715 }
3716
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003717 // Work out what ArtMethod* we're in, the current line number, and how deep the stack currently
Elliott Hughes2435a572012-02-17 16:07:41 -08003718 // is for step-out.
Ian Rogers0399dde2012-06-06 17:09:28 -07003719 struct SingleStepStackVisitor : public StackVisitor {
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003720 explicit SingleStepStackVisitor(Thread* thread) REQUIRES_SHARED(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01003721 : StackVisitor(thread, nullptr, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
3722 stack_depth(0),
3723 method(nullptr),
3724 line_number(-1) {}
Ian Rogersca190662012-06-26 15:45:57 -07003725
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003726 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
3727 // annotalysis.
Andreas Gampefa6a1b02018-09-07 08:11:55 -07003728 bool VisitFrame() override NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003729 ArtMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07003730 if (!m->IsRuntimeMethod()) {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003731 ++stack_depth;
3732 if (method == nullptr) {
Alex Light73376312017-04-06 10:10:51 -07003733 const DexFile* dex_file = m->GetDexFile();
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003734 method = m;
Alex Light73376312017-04-06 10:10:51 -07003735 if (dex_file != nullptr) {
David Sehr9323e6e2016-09-13 08:58:35 -07003736 line_number = annotations::GetLineNumFromPC(dex_file, m, GetDexPc());
Elliott Hughes2435a572012-02-17 16:07:41 -08003737 }
Elliott Hughes86964332012-02-15 19:37:42 -08003738 }
3739 }
Elliott Hughes530fa002012-03-12 11:44:49 -07003740 return true;
Elliott Hughes86964332012-02-15 19:37:42 -08003741 }
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003742
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003743 int stack_depth;
Mathieu Chartiere401d142015-04-22 13:56:20 -07003744 ArtMethod* method;
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003745 int32_t line_number;
Elliott Hughes86964332012-02-15 19:37:42 -08003746 };
Jeff Hao449db332013-04-12 18:30:52 -07003747
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003748 Thread* const thread = sts.GetThread();
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003749 SingleStepStackVisitor visitor(thread);
Ian Rogers0399dde2012-06-06 17:09:28 -07003750 visitor.WalkStack();
Elliott Hughes86964332012-02-15 19:37:42 -08003751
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003752 // Allocate single step.
Sebastien Hertz1558b572015-02-25 15:05:59 +01003753 SingleStepControl* single_step_control =
3754 new (std::nothrow) SingleStepControl(step_size, step_depth,
3755 visitor.stack_depth, visitor.method);
3756 if (single_step_control == nullptr) {
3757 LOG(ERROR) << "Failed to allocate SingleStepControl";
3758 return JDWP::ERR_OUT_OF_MEMORY;
3759 }
3760
Mathieu Chartiere401d142015-04-22 13:56:20 -07003761 ArtMethod* m = single_step_control->GetMethod();
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003762 const int32_t line_number = visitor.line_number;
Sebastien Hertz52f5f932015-05-28 11:00:57 +02003763 // Note: if the thread is not running Java code (pure native thread), there is no "current"
3764 // method on the stack (and no line number either).
3765 if (m != nullptr && !m->IsNative()) {
David Sehr0225f8e2018-01-31 08:52:24 +00003766 CodeItemDebugInfoAccessor accessor(m->DexInstructionDebugInfo());
Mathieu Chartier3e2e1232018-09-11 12:35:30 -07003767 bool last_pc_valid = false;
3768 uint32_t last_pc = 0u;
3769 // Find the dex_pc values that correspond to the current line, for line-based single-stepping.
3770 accessor.DecodeDebugPositionInfo([&](const DexFile::PositionInfo& entry) {
3771 if (static_cast<int32_t>(entry.line_) == line_number) {
3772 if (!last_pc_valid) {
3773 // Everything from this address until the next line change is ours.
3774 last_pc = entry.address_;
3775 last_pc_valid = true;
3776 }
3777 // Otherwise, if we're already in a valid range for this line,
3778 // just keep going (shouldn't really happen)...
3779 } else if (last_pc_valid) { // and the line number is new
3780 // Add everything from the last entry up until here to the set
3781 for (uint32_t dex_pc = last_pc; dex_pc < entry.address_; ++dex_pc) {
3782 single_step_control->AddDexPc(dex_pc);
3783 }
3784 last_pc_valid = false;
3785 }
3786 return false; // There may be multiple entries for any given line.
3787 });
3788 // If the line number was the last in the position table...
3789 if (last_pc_valid) {
3790 for (uint32_t dex_pc = last_pc; dex_pc < accessor.InsnsSizeInCodeUnits(); ++dex_pc) {
3791 single_step_control->AddDexPc(dex_pc);
3792 }
3793 }
Elliott Hughes3e2e1a22012-02-21 11:33:41 -08003794 }
Elliott Hughes2435a572012-02-17 16:07:41 -08003795
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003796 // Activate single-step in the thread.
3797 thread->ActivateSingleStepControl(single_step_control);
Elliott Hughes86964332012-02-15 19:37:42 -08003798
Elliott Hughes2435a572012-02-17 16:07:41 -08003799 if (VLOG_IS_ON(jdwp)) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003800 VLOG(jdwp) << "Single-step thread: " << *thread;
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003801 VLOG(jdwp) << "Single-step step size: " << single_step_control->GetStepSize();
3802 VLOG(jdwp) << "Single-step step depth: " << single_step_control->GetStepDepth();
David Sehr709b0702016-10-13 09:12:37 -07003803 VLOG(jdwp) << "Single-step current method: "
3804 << ArtMethod::PrettyMethod(single_step_control->GetMethod());
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003805 VLOG(jdwp) << "Single-step current line: " << line_number;
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003806 VLOG(jdwp) << "Single-step current stack depth: " << single_step_control->GetStackDepth();
Elliott Hughes2435a572012-02-17 16:07:41 -08003807 VLOG(jdwp) << "Single-step dex_pc values:";
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003808 for (uint32_t dex_pc : single_step_control->GetDexPcs()) {
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003809 VLOG(jdwp) << StringPrintf(" %#x", dex_pc);
Elliott Hughes2435a572012-02-17 16:07:41 -08003810 }
3811 }
3812
3813 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003814}
3815
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003816void Dbg::UnconfigureStep(JDWP::ObjectId thread_id) {
3817 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07003818 JDWP::JdwpError error;
3819 Thread* thread = DecodeThread(soa, thread_id, &error);
Sebastien Hertz87118ed2013-11-26 17:57:18 +01003820 if (error == JDWP::ERR_NONE) {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003821 thread->DeactivateSingleStepControl();
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003822 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003823}
3824
Elliott Hughes45651fd2012-02-21 15:48:20 -08003825static char JdwpTagToShortyChar(JDWP::JdwpTag tag) {
3826 switch (tag) {
3827 default:
3828 LOG(FATAL) << "unknown JDWP tag: " << PrintableChar(tag);
Ian Rogersfc787ec2014-10-09 21:56:44 -07003829 UNREACHABLE();
Elliott Hughes45651fd2012-02-21 15:48:20 -08003830
3831 // Primitives.
3832 case JDWP::JT_BYTE: return 'B';
3833 case JDWP::JT_CHAR: return 'C';
3834 case JDWP::JT_FLOAT: return 'F';
3835 case JDWP::JT_DOUBLE: return 'D';
3836 case JDWP::JT_INT: return 'I';
3837 case JDWP::JT_LONG: return 'J';
3838 case JDWP::JT_SHORT: return 'S';
3839 case JDWP::JT_VOID: return 'V';
3840 case JDWP::JT_BOOLEAN: return 'Z';
3841
3842 // Reference types.
3843 case JDWP::JT_ARRAY:
3844 case JDWP::JT_OBJECT:
3845 case JDWP::JT_STRING:
3846 case JDWP::JT_THREAD:
3847 case JDWP::JT_THREAD_GROUP:
3848 case JDWP::JT_CLASS_LOADER:
3849 case JDWP::JT_CLASS_OBJECT:
3850 return 'L';
3851 }
3852}
3853
Sebastien Hertzcbc50642015-06-01 17:33:12 +02003854JDWP::JdwpError Dbg::PrepareInvokeMethod(uint32_t request_id, JDWP::ObjectId thread_id,
3855 JDWP::ObjectId object_id, JDWP::RefTypeId class_id,
3856 JDWP::MethodId method_id, uint32_t arg_count,
3857 uint64_t arg_values[], JDWP::JdwpTag* arg_types,
3858 uint32_t options) {
3859 Thread* const self = Thread::Current();
3860 CHECK_EQ(self, GetDebugThread()) << "This must be called by the JDWP thread";
Sebastien Hertzd4032e42015-06-12 15:47:34 +02003861 const bool resume_all_threads = ((options & JDWP::INVOKE_SINGLE_THREADED) == 0);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003862
Sebastien Hertzcbc50642015-06-01 17:33:12 +02003863 ThreadList* thread_list = Runtime::Current()->GetThreadList();
Ian Rogersc0542af2014-09-03 16:16:56 -07003864 Thread* targetThread = nullptr;
Elliott Hughesd07986f2011-12-06 18:27:45 -08003865 {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003866 ScopedObjectAccessUnchecked soa(self);
Ian Rogersc0542af2014-09-03 16:16:56 -07003867 JDWP::JdwpError error;
3868 targetThread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08003869 if (error != JDWP::ERR_NONE) {
3870 LOG(ERROR) << "InvokeMethod request for invalid thread id " << thread_id;
3871 return error;
Elliott Hughesd07986f2011-12-06 18:27:45 -08003872 }
Sebastien Hertz1558b572015-02-25 15:05:59 +01003873 if (targetThread->GetInvokeReq() != nullptr) {
3874 // Thread is already invoking a method on behalf of the debugger.
3875 LOG(ERROR) << "InvokeMethod request for thread already invoking a method: " << *targetThread;
3876 return JDWP::ERR_ALREADY_INVOKING;
3877 }
3878 if (!targetThread->IsReadyForDebugInvoke()) {
3879 // Thread is not suspended by an event so it cannot invoke a method.
Elliott Hughesd07986f2011-12-06 18:27:45 -08003880 LOG(ERROR) << "InvokeMethod request for thread not stopped by event: " << *targetThread;
3881 return JDWP::ERR_INVALID_THREAD;
3882 }
3883
3884 /*
Sebastien Hertzd4032e42015-06-12 15:47:34 +02003885 * According to the JDWP specs, we are expected to resume all threads (or only the
3886 * target thread) once. So if a thread has been suspended more than once (either by
3887 * the debugger for an event or by the runtime for GC), it will remain suspended before
3888 * the invoke is executed. This means the debugger is responsible to properly resume all
3889 * the threads it has suspended so the target thread can execute the method.
Elliott Hughesd07986f2011-12-06 18:27:45 -08003890 *
Sebastien Hertzd4032e42015-06-12 15:47:34 +02003891 * However, for compatibility reason with older versions of debuggers (like Eclipse), we
3892 * fully resume all threads (by canceling *all* debugger suspensions) when the debugger
3893 * wants us to resume all threads. This is to avoid ending up in deadlock situation.
3894 *
3895 * On the other hand, if we are asked to only resume the target thread, then we follow the
3896 * JDWP specs by resuming that thread only once. This means the thread will remain suspended
3897 * if it has been suspended more than once before the invoke (and again, this is the
3898 * responsibility of the debugger to properly resume that thread before invoking a method).
Elliott Hughesd07986f2011-12-06 18:27:45 -08003899 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003900 int suspend_count;
3901 {
Ian Rogers50b35e22012-10-04 10:09:15 -07003902 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003903 suspend_count = targetThread->GetSuspendCount();
3904 }
Sebastien Hertzd4032e42015-06-12 15:47:34 +02003905 if (suspend_count > 1 && resume_all_threads) {
3906 // The target thread will remain suspended even after we resume it. Let's emit a warning
3907 // to indicate the invoke won't be executed until the thread is resumed.
3908 LOG(WARNING) << *targetThread << " suspended more than once (suspend count == "
3909 << suspend_count << "). This thread will invoke the method only once "
3910 << "it is fully resumed.";
Elliott Hughesd07986f2011-12-06 18:27:45 -08003911 }
3912
Vladimir Marko83114892019-04-11 13:05:50 +01003913 ObjPtr<mirror::Object> receiver = gRegistry->Get<mirror::Object>(object_id, &error);
Ian Rogersc0542af2014-09-03 16:16:56 -07003914 if (error != JDWP::ERR_NONE) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08003915 return JDWP::ERR_INVALID_OBJECT;
3916 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003917
Vladimir Marko83114892019-04-11 13:05:50 +01003918 gRegistry->Get<mirror::Object>(thread_id, &error);
Ian Rogersc0542af2014-09-03 16:16:56 -07003919 if (error != JDWP::ERR_NONE) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08003920 return JDWP::ERR_INVALID_OBJECT;
3921 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003922
Vladimir Marko4617d582019-03-28 13:48:31 +00003923 ObjPtr<mirror::Class> c = DecodeClass(class_id, &error);
Ian Rogersc0542af2014-09-03 16:16:56 -07003924 if (c == nullptr) {
3925 return error;
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08003926 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003927
Mathieu Chartiere401d142015-04-22 13:56:20 -07003928 ArtMethod* m = FromMethodId(method_id);
Ian Rogersc0542af2014-09-03 16:16:56 -07003929 if (m->IsStatic() != (receiver == nullptr)) {
Elliott Hughes45651fd2012-02-21 15:48:20 -08003930 return JDWP::ERR_INVALID_METHODID;
3931 }
3932 if (m->IsStatic()) {
3933 if (m->GetDeclaringClass() != c) {
3934 return JDWP::ERR_INVALID_METHODID;
3935 }
3936 } else {
3937 if (!m->GetDeclaringClass()->IsAssignableFrom(c)) {
3938 return JDWP::ERR_INVALID_METHODID;
3939 }
3940 }
3941
3942 // Check the argument list matches the method.
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003943 uint32_t shorty_len = 0;
3944 const char* shorty = m->GetShorty(&shorty_len);
3945 if (shorty_len - 1 != arg_count) {
Elliott Hughes45651fd2012-02-21 15:48:20 -08003946 return JDWP::ERR_ILLEGAL_ARGUMENT;
3947 }
Elliott Hughes09201632013-04-15 15:50:07 -07003948
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003949 {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003950 StackHandleScope<2> hs(soa.Self());
Vladimir Marko4617d582019-03-28 13:48:31 +00003951 HandleWrapperObjPtr<mirror::Object> h_obj(hs.NewHandleWrapper(&receiver));
3952 HandleWrapperObjPtr<mirror::Class> h_klass(hs.NewHandleWrapper(&c));
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003953 const dex::TypeList* types = m->GetParameterTypeList();
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003954 for (size_t i = 0; i < arg_count; ++i) {
3955 if (shorty[i + 1] != JdwpTagToShortyChar(arg_types[i])) {
Elliott Hughes09201632013-04-15 15:50:07 -07003956 return JDWP::ERR_ILLEGAL_ARGUMENT;
3957 }
3958
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003959 if (shorty[i + 1] == 'L') {
3960 // Did we really get an argument of an appropriate reference type?
Vladimir Markob45528c2017-07-27 14:14:28 +01003961 ObjPtr<mirror::Class> parameter_type =
3962 m->ResolveClassFromTypeIndex(types->GetTypeItem(i).type_idx_);
Vladimir Marko83114892019-04-11 13:05:50 +01003963 ObjPtr<mirror::Object> argument = gRegistry->Get<mirror::Object>(arg_values[i], &error);
Ian Rogersc0542af2014-09-03 16:16:56 -07003964 if (error != JDWP::ERR_NONE) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003965 return JDWP::ERR_INVALID_OBJECT;
3966 }
Ian Rogersc0542af2014-09-03 16:16:56 -07003967 if (argument != nullptr && !argument->InstanceOf(parameter_type)) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003968 return JDWP::ERR_ILLEGAL_ARGUMENT;
3969 }
3970
3971 // Turn the on-the-wire ObjectId into a jobject.
3972 jvalue& v = reinterpret_cast<jvalue&>(arg_values[i]);
3973 v.l = gRegistry->GetJObject(arg_values[i]);
3974 }
Elliott Hughes09201632013-04-15 15:50:07 -07003975 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003976 }
3977
Sebastien Hertz1558b572015-02-25 15:05:59 +01003978 // Allocates a DebugInvokeReq.
Vladimir Marko4617d582019-03-28 13:48:31 +00003979 DebugInvokeReq* req = new (std::nothrow) DebugInvokeReq(
3980 request_id, thread_id, receiver, c, m, options, arg_values, arg_count);
Sebastien Hertzcbc50642015-06-01 17:33:12 +02003981 if (req == nullptr) {
Sebastien Hertz1558b572015-02-25 15:05:59 +01003982 LOG(ERROR) << "Failed to allocate DebugInvokeReq";
3983 return JDWP::ERR_OUT_OF_MEMORY;
3984 }
3985
Sebastien Hertzcbc50642015-06-01 17:33:12 +02003986 // Attaches the DebugInvokeReq to the target thread so it executes the method when
3987 // it is resumed. Once the invocation completes, the target thread will delete it before
3988 // suspending itself (see ThreadList::SuspendSelfForDebugger).
3989 targetThread->SetDebugInvokeReq(req);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003990 }
3991
3992 // 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 +02003993 // away we're sitting high and dry -- but we must release this before the UndoDebuggerSuspensions
3994 // call.
Sebastien Hertzd4032e42015-06-12 15:47:34 +02003995 if (resume_all_threads) {
Sebastien Hertzcbc50642015-06-01 17:33:12 +02003996 VLOG(jdwp) << " Resuming all threads";
3997 thread_list->UndoDebuggerSuspensions();
3998 } else {
3999 VLOG(jdwp) << " Resuming event thread only";
Alex Light88fd7202017-06-30 08:31:59 -07004000 bool resumed = thread_list->Resume(targetThread, SuspendReason::kForDebugger);
4001 DCHECK(resumed);
Elliott Hughesd07986f2011-12-06 18:27:45 -08004002 }
4003
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004004 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004005}
4006
4007void Dbg::ExecuteMethod(DebugInvokeReq* pReq) {
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004008 Thread* const self = Thread::Current();
4009 CHECK_NE(self, GetDebugThread()) << "This must be called by the event thread";
4010
4011 ScopedObjectAccess soa(self);
Elliott Hughesd07986f2011-12-06 18:27:45 -08004012
Elliott Hughes81ff3182012-03-23 20:35:56 -07004013 // We can be called while an exception is pending. We need
Elliott Hughesd07986f2011-12-06 18:27:45 -08004014 // to preserve that across the method invocation.
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004015 StackHandleScope<1> hs(soa.Self());
4016 Handle<mirror::Throwable> old_exception = hs.NewHandle(soa.Self()->GetException());
Sebastien Hertz1558b572015-02-25 15:05:59 +01004017 soa.Self()->ClearException();
Elliott Hughesd07986f2011-12-06 18:27:45 -08004018
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004019 // Execute the method then sends reply to the debugger.
4020 ExecuteMethodWithoutPendingException(soa, pReq);
4021
4022 // If an exception was pending before the invoke, restore it now.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004023 if (old_exception != nullptr) {
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004024 soa.Self()->SetException(old_exception.Get());
4025 }
4026}
4027
4028// Helper function: write a variable-width value into the output input buffer.
4029static void WriteValue(JDWP::ExpandBuf* pReply, int width, uint64_t value) {
4030 switch (width) {
4031 case 1:
4032 expandBufAdd1(pReply, value);
4033 break;
4034 case 2:
4035 expandBufAdd2BE(pReply, value);
4036 break;
4037 case 4:
4038 expandBufAdd4BE(pReply, value);
4039 break;
4040 case 8:
4041 expandBufAdd8BE(pReply, value);
4042 break;
4043 default:
4044 LOG(FATAL) << width;
4045 UNREACHABLE();
4046 }
4047}
4048
4049void Dbg::ExecuteMethodWithoutPendingException(ScopedObjectAccess& soa, DebugInvokeReq* pReq) {
4050 soa.Self()->AssertNoPendingException();
4051
Elliott Hughesd07986f2011-12-06 18:27:45 -08004052 // Translate the method through the vtable, unless the debugger wants to suppress it.
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004053 ArtMethod* m = pReq->method;
Andreas Gampe542451c2016-07-26 09:02:02 -07004054 PointerSize image_pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
Sebastien Hertz1558b572015-02-25 15:05:59 +01004055 if ((pReq->options & JDWP::INVOKE_NONVIRTUAL) == 0 && pReq->receiver.Read() != nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004056 ArtMethod* actual_method =
4057 pReq->klass.Read()->FindVirtualMethodForVirtualOrInterface(m, image_pointer_size);
4058 if (actual_method != m) {
David Sehr709b0702016-10-13 09:12:37 -07004059 VLOG(jdwp) << "ExecuteMethod translated " << ArtMethod::PrettyMethod(m)
4060 << " to " << ArtMethod::PrettyMethod(actual_method);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004061 m = actual_method;
Elliott Hughes45651fd2012-02-21 15:48:20 -08004062 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08004063 }
David Sehr709b0702016-10-13 09:12:37 -07004064 VLOG(jdwp) << "ExecuteMethod " << ArtMethod::PrettyMethod(m)
Sebastien Hertz1558b572015-02-25 15:05:59 +01004065 << " receiver=" << pReq->receiver.Read()
Sebastien Hertzd38667a2013-11-25 15:43:54 +01004066 << " arg_count=" << pReq->arg_count;
Mathieu Chartiere401d142015-04-22 13:56:20 -07004067 CHECK(m != nullptr);
Elliott Hughesd07986f2011-12-06 18:27:45 -08004068
Roland Levillain33d69032015-06-18 18:20:59 +01004069 static_assert(sizeof(jvalue) == sizeof(uint64_t), "jvalue and uint64_t have different sizes.");
Elliott Hughesd07986f2011-12-06 18:27:45 -08004070
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004071 // Invoke the method.
Jeff Hao39b6c242015-05-19 20:30:23 -07004072 ScopedLocalRef<jobject> ref(soa.Env(), soa.AddLocalReference<jobject>(pReq->receiver.Read()));
Andreas Gampe13b27842016-11-07 16:48:23 -08004073 JValue result = InvokeWithJValues(soa, ref.get(), jni::EncodeArtMethod(m),
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004074 reinterpret_cast<jvalue*>(pReq->arg_values.get()));
Elliott Hughesd07986f2011-12-06 18:27:45 -08004075
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004076 // Prepare JDWP ids for the reply.
4077 JDWP::JdwpTag result_tag = BasicTagFromDescriptor(m->GetShorty());
4078 const bool is_object_result = (result_tag == JDWP::JT_OBJECT);
Jeff Hao064d24e2016-08-25 03:52:40 +00004079 StackHandleScope<3> hs(soa.Self());
Sebastien Hertz1558b572015-02-25 15:05:59 +01004080 Handle<mirror::Object> object_result = hs.NewHandle(is_object_result ? result.GetL() : nullptr);
4081 Handle<mirror::Throwable> exception = hs.NewHandle(soa.Self()->GetException());
4082 soa.Self()->ClearException();
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004083
4084 if (!IsDebuggerActive()) {
4085 // The debugger detached: we must not re-suspend threads. We also don't need to fill the reply
4086 // because it won't be sent either.
4087 return;
4088 }
4089
4090 JDWP::ObjectId exceptionObjectId = gRegistry->Add(exception);
4091 uint64_t result_value = 0;
4092 if (exceptionObjectId != 0) {
Sebastien Hertz1558b572015-02-25 15:05:59 +01004093 VLOG(jdwp) << " JDWP invocation returning with exception=" << exception.Get()
4094 << " " << exception->Dump();
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004095 result_value = 0;
Sebastien Hertz1558b572015-02-25 15:05:59 +01004096 } else if (is_object_result) {
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004097 /* if no exception was thrown, examine object result more closely */
Sebastien Hertz1558b572015-02-25 15:05:59 +01004098 JDWP::JdwpTag new_tag = TagFromObject(soa, object_result.Get());
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004099 if (new_tag != result_tag) {
4100 VLOG(jdwp) << " JDWP promoted result from " << result_tag << " to " << new_tag;
4101 result_tag = new_tag;
Elliott Hughesd07986f2011-12-06 18:27:45 -08004102 }
4103
Sebastien Hertz1558b572015-02-25 15:05:59 +01004104 // Register the object in the registry and reference its ObjectId. This ensures
4105 // GC safety and prevents from accessing stale reference if the object is moved.
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004106 result_value = gRegistry->Add(object_result.Get());
Sebastien Hertz1558b572015-02-25 15:05:59 +01004107 } else {
4108 // Primitive result.
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004109 DCHECK(IsPrimitiveTag(result_tag));
4110 result_value = result.GetJ();
4111 }
4112 const bool is_constructor = m->IsConstructor() && !m->IsStatic();
4113 if (is_constructor) {
4114 // If we invoked a constructor (which actually returns void), return the receiver,
4115 // unless we threw, in which case we return null.
Sebastien Hertza3e13772015-11-05 12:09:44 +01004116 DCHECK_EQ(JDWP::JT_VOID, result_tag);
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004117 if (exceptionObjectId == 0) {
Jeff Hao064d24e2016-08-25 03:52:40 +00004118 if (m->GetDeclaringClass()->IsStringClass()) {
4119 // For string constructors, the new string is remapped to the receiver (stored in ref).
4120 Handle<mirror::Object> decoded_ref = hs.NewHandle(soa.Self()->DecodeJObject(ref.get()));
4121 result_value = gRegistry->Add(decoded_ref);
4122 result_tag = TagFromObject(soa, decoded_ref.Get());
4123 } else {
4124 // TODO we could keep the receiver ObjectId in the DebugInvokeReq to avoid looking into the
4125 // object registry.
4126 result_value = GetObjectRegistry()->Add(pReq->receiver.Read());
4127 result_tag = TagFromObject(soa, pReq->receiver.Read());
4128 }
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004129 } else {
4130 result_value = 0;
Sebastien Hertza3e13772015-11-05 12:09:44 +01004131 result_tag = JDWP::JT_OBJECT;
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004132 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08004133 }
4134
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004135 // Suspend other threads if the invoke is not single-threaded.
4136 if ((pReq->options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07004137 ScopedThreadSuspension sts(soa.Self(), kWaitingForDebuggerSuspension);
Hiroshi Yamauchi8f95cf32016-04-19 11:14:06 -07004138 // Avoid a deadlock between GC and debugger where GC gets suspended during GC. b/25800335.
4139 gc::ScopedGCCriticalSection gcs(soa.Self(), gc::kGcCauseDebugger, gc::kCollectorTypeDebugger);
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004140 VLOG(jdwp) << " Suspending all threads";
4141 Runtime::Current()->GetThreadList()->SuspendAllForDebugger();
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004142 }
4143
4144 VLOG(jdwp) << " --> returned " << result_tag
4145 << StringPrintf(" %#" PRIx64 " (except=%#" PRIx64 ")", result_value,
4146 exceptionObjectId);
4147
4148 // Show detailed debug output.
4149 if (result_tag == JDWP::JT_STRING && exceptionObjectId == 0) {
4150 if (result_value != 0) {
4151 if (VLOG_IS_ON(jdwp)) {
4152 std::string result_string;
4153 JDWP::JdwpError error = Dbg::StringToUtf8(result_value, &result_string);
4154 CHECK_EQ(error, JDWP::ERR_NONE);
4155 VLOG(jdwp) << " string '" << result_string << "'";
4156 }
4157 } else {
4158 VLOG(jdwp) << " string (null)";
4159 }
4160 }
4161
4162 // Attach the reply to DebugInvokeReq so it can be sent to the debugger when the event thread
4163 // is ready to suspend.
4164 BuildInvokeReply(pReq->reply, pReq->request_id, result_tag, result_value, exceptionObjectId);
4165}
4166
4167void Dbg::BuildInvokeReply(JDWP::ExpandBuf* pReply, uint32_t request_id, JDWP::JdwpTag result_tag,
4168 uint64_t result_value, JDWP::ObjectId exception) {
4169 // Make room for the JDWP header since we do not know the size of the reply yet.
4170 JDWP::expandBufAddSpace(pReply, kJDWPHeaderLen);
4171
4172 size_t width = GetTagWidth(result_tag);
4173 JDWP::expandBufAdd1(pReply, result_tag);
4174 if (width != 0) {
4175 WriteValue(pReply, width, result_value);
4176 }
4177 JDWP::expandBufAdd1(pReply, JDWP::JT_OBJECT);
4178 JDWP::expandBufAddObjectId(pReply, exception);
4179
4180 // Now we know the size, we can complete the JDWP header.
4181 uint8_t* buf = expandBufGetBuffer(pReply);
4182 JDWP::Set4BE(buf + kJDWPHeaderSizeOffset, expandBufGetLength(pReply));
4183 JDWP::Set4BE(buf + kJDWPHeaderIdOffset, request_id);
4184 JDWP::Set1(buf + kJDWPHeaderFlagsOffset, kJDWPFlagReply); // flags
4185 JDWP::Set2BE(buf + kJDWPHeaderErrorCodeOffset, JDWP::ERR_NONE);
4186}
4187
4188void Dbg::FinishInvokeMethod(DebugInvokeReq* pReq) {
4189 CHECK_NE(Thread::Current(), GetDebugThread()) << "This must be called by the event thread";
4190
4191 JDWP::ExpandBuf* const pReply = pReq->reply;
4192 CHECK(pReply != nullptr) << "No reply attached to DebugInvokeReq";
4193
4194 // We need to prevent other threads (including JDWP thread) from interacting with the debugger
4195 // while we send the reply but are not yet suspended. The JDWP token will be released just before
4196 // we suspend ourself again (see ThreadList::SuspendSelfForDebugger).
4197 gJdwpState->AcquireJdwpTokenForEvent(pReq->thread_id);
4198
4199 // Send the reply unless the debugger detached before the completion of the method.
4200 if (IsDebuggerActive()) {
4201 const size_t replyDataLength = expandBufGetLength(pReply) - kJDWPHeaderLen;
4202 VLOG(jdwp) << StringPrintf("REPLY INVOKE id=0x%06x (length=%zu)",
4203 pReq->request_id, replyDataLength);
4204
4205 gJdwpState->SendRequest(pReply);
4206 } else {
4207 VLOG(jdwp) << "Not sending invoke reply because debugger detached";
Elliott Hughesd07986f2011-12-06 18:27:45 -08004208 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004209}
4210
Alex Light8c2b9292017-11-09 13:21:01 -08004211bool Dbg::DdmHandleChunk(JNIEnv* env,
4212 uint32_t type,
4213 const ArrayRef<const jbyte>& data,
4214 /*out*/uint32_t* out_type,
4215 /*out*/std::vector<uint8_t>* out_data) {
4216 ScopedLocalRef<jbyteArray> dataArray(env, env->NewByteArray(data.size()));
Ian Rogersc0542af2014-09-03 16:16:56 -07004217 if (dataArray.get() == nullptr) {
Alex Light8c2b9292017-11-09 13:21:01 -08004218 LOG(WARNING) << "byte[] allocation failed: " << data.size();
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004219 env->ExceptionClear();
4220 return false;
4221 }
Alex Light8c2b9292017-11-09 13:21:01 -08004222 env->SetByteArrayRegion(dataArray.get(),
4223 0,
4224 data.size(),
4225 reinterpret_cast<const jbyte*>(data.data()));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004226 // Call "private static Chunk dispatch(int type, byte[] data, int offset, int length)".
Alex Light8c2b9292017-11-09 13:21:01 -08004227 ScopedLocalRef<jobject> chunk(
4228 env,
4229 env->CallStaticObjectMethod(
4230 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
4231 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_dispatch,
4232 type, dataArray.get(), 0, data.size()));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004233 if (env->ExceptionCheck()) {
Alex Light1eeefa62018-03-19 13:47:56 -07004234 Thread* self = Thread::Current();
4235 ScopedObjectAccess soa(self);
4236 LOG(INFO) << StringPrintf("Exception thrown by dispatcher for 0x%08x", type) << std::endl
4237 << self->GetException()->Dump();
4238 self->ClearException();
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004239 return false;
4240 }
4241
Ian Rogersc0542af2014-09-03 16:16:56 -07004242 if (chunk.get() == nullptr) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004243 return false;
4244 }
4245
4246 /*
4247 * Pull the pieces out of the chunk. We copy the results into a
4248 * newly-allocated buffer that the caller can free. We don't want to
4249 * continue using the Chunk object because nothing has a reference to it.
4250 *
4251 * We could avoid this by returning type/data/offset/length and having
4252 * the caller be aware of the object lifetime issues, but that
Elliott Hughes81ff3182012-03-23 20:35:56 -07004253 * integrates the JDWP code more tightly into the rest of the runtime, and doesn't work
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004254 * if we have responses for multiple chunks.
4255 *
4256 * So we're pretty much stuck with copying data around multiple times.
4257 */
Alex Light8c2b9292017-11-09 13:21:01 -08004258 ScopedLocalRef<jbyteArray> replyData(
4259 env,
4260 reinterpret_cast<jbyteArray>(
4261 env->GetObjectField(
4262 chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_data)));
4263 jint offset = env->GetIntField(chunk.get(),
4264 WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_offset);
4265 jint length = env->GetIntField(chunk.get(),
4266 WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_length);
4267 *out_type = env->GetIntField(chunk.get(),
4268 WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_type);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004269
Alex Light8c2b9292017-11-09 13:21:01 -08004270 VLOG(jdwp) << StringPrintf("DDM reply: type=0x%08x data=%p offset=%d length=%d",
4271 type,
4272 replyData.get(),
4273 offset,
4274 length);
Alex Light8c2b9292017-11-09 13:21:01 -08004275 out_data->resize(length);
4276 env->GetByteArrayRegion(replyData.get(),
4277 offset,
4278 length,
4279 reinterpret_cast<jbyte*>(out_data->data()));
Alex Light6f2a6342017-12-12 09:55:05 -08004280
Alex Lighte5463a82017-12-12 13:33:28 -08004281 if (env->ExceptionCheck()) {
Alex Light1eeefa62018-03-19 13:47:56 -07004282 Thread* self = Thread::Current();
4283 ScopedObjectAccess soa(self);
Alex Lighte5463a82017-12-12 13:33:28 -08004284 LOG(INFO) << StringPrintf("Exception thrown when reading response data from dispatcher 0x%08x",
Alex Light1eeefa62018-03-19 13:47:56 -07004285 type) << std::endl << self->GetException()->Dump();
4286 self->ClearException();
Alex Lighte5463a82017-12-12 13:33:28 -08004287 return false;
4288 }
4289
Alex Light8c2b9292017-11-09 13:21:01 -08004290 return true;
4291}
4292
4293/*
4294 * "request" contains a full JDWP packet, possibly with multiple chunks. We
4295 * need to process each, accumulate the replies, and ship the whole thing
4296 * back.
4297 *
4298 * Returns "true" if we have a reply. The reply buffer is newly allocated,
4299 * and includes the chunk type/length, followed by the data.
4300 *
4301 * OLD-TODO: we currently assume that the request and reply include a single
4302 * chunk. If this becomes inconvenient we will need to adapt.
4303 */
4304bool Dbg::DdmHandlePacket(JDWP::Request* request, uint8_t** pReplyBuf, int* pReplyLen) {
4305 Thread* self = Thread::Current();
4306 JNIEnv* env = self->GetJniEnv();
4307
4308 uint32_t type = request->ReadUnsigned32("type");
4309 uint32_t length = request->ReadUnsigned32("length");
4310
4311 // Create a byte[] corresponding to 'request'.
4312 size_t request_length = request->size();
4313 // Run through and find all chunks. [Currently just find the first.]
4314 if (length != request_length) {
4315 LOG(WARNING) << StringPrintf("bad chunk found (len=%u pktLen=%zd)", length, request_length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004316 return false;
4317 }
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004318
Alex Light8c2b9292017-11-09 13:21:01 -08004319 ArrayRef<const jbyte> data(reinterpret_cast<const jbyte*>(request->data()), request_length);
4320 std::vector<uint8_t> out_data;
4321 uint32_t out_type = 0;
4322 request->Skip(request_length);
Alex Light6f2a6342017-12-12 09:55:05 -08004323 if (!DdmHandleChunk(env, type, data, &out_type, &out_data) || out_data.empty()) {
Alex Light8c2b9292017-11-09 13:21:01 -08004324 return false;
4325 }
4326 const uint32_t kDdmHeaderSize = 8;
4327 *pReplyLen = out_data.size() + kDdmHeaderSize;
4328 *pReplyBuf = new uint8_t[out_data.size() + kDdmHeaderSize];
4329 memcpy((*pReplyBuf) + kDdmHeaderSize, out_data.data(), out_data.size());
4330 JDWP::Set4BE(*pReplyBuf, out_type);
4331 JDWP::Set4BE((*pReplyBuf) + 4, static_cast<uint32_t>(out_data.size()));
4332 VLOG(jdwp)
4333 << StringPrintf("dvmHandleDdm returning type=%.4s", reinterpret_cast<char*>(*pReplyBuf))
4334 << "0x" << std::hex << reinterpret_cast<uintptr_t>(*pReplyBuf) << std::dec
4335 << " len= " << out_data.size();
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004336 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004337}
4338
Elliott Hughesa2155262011-11-16 16:26:58 -08004339void Dbg::DdmBroadcast(bool connect) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08004340 VLOG(jdwp) << "Broadcasting DDM " << (connect ? "connect" : "disconnect") << "...";
Elliott Hughes47fce012011-10-25 18:37:19 -07004341
4342 Thread* self = Thread::Current();
Ian Rogers50b35e22012-10-04 10:09:15 -07004343 if (self->GetState() != kRunnable) {
4344 LOG(ERROR) << "DDM broadcast in thread state " << self->GetState();
4345 /* try anyway? */
Elliott Hughes47fce012011-10-25 18:37:19 -07004346 }
4347
4348 JNIEnv* env = self->GetJniEnv();
Elliott Hughes47fce012011-10-25 18:37:19 -07004349 jint event = connect ? 1 /*DdmServer.CONNECTED*/ : 2 /*DdmServer.DISCONNECTED*/;
Elliott Hugheseac76672012-05-24 21:56:51 -07004350 env->CallStaticVoidMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
4351 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_broadcast,
4352 event);
Elliott Hughes47fce012011-10-25 18:37:19 -07004353 if (env->ExceptionCheck()) {
4354 LOG(ERROR) << "DdmServer.broadcast " << event << " failed";
4355 env->ExceptionDescribe();
4356 env->ExceptionClear();
4357 }
4358}
4359
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004360void Dbg::DdmConnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08004361 Dbg::DdmBroadcast(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004362}
4363
4364void Dbg::DdmDisconnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08004365 Dbg::DdmBroadcast(false);
Elliott Hughes47fce012011-10-25 18:37:19 -07004366 gDdmThreadNotification = false;
4367}
4368
4369/*
Elliott Hughes82188472011-11-07 18:11:48 -08004370 * Send a notification when a thread starts, stops, or changes its name.
Elliott Hughes47fce012011-10-25 18:37:19 -07004371 *
4372 * Because we broadcast the full set of threads when the notifications are
4373 * first enabled, it's possible for "thread" to be actively executing.
4374 */
Elliott Hughes82188472011-11-07 18:11:48 -08004375void Dbg::DdmSendThreadNotification(Thread* t, uint32_t type) {
Elliott Hughes47fce012011-10-25 18:37:19 -07004376 if (!gDdmThreadNotification) {
4377 return;
4378 }
4379
Alex Light772099a2017-11-21 14:05:04 -08004380 RuntimeCallbacks* cb = Runtime::Current()->GetRuntimeCallbacks();
Elliott Hughes82188472011-11-07 18:11:48 -08004381 if (type == CHUNK_TYPE("THDE")) {
Elliott Hughes47fce012011-10-25 18:37:19 -07004382 uint8_t buf[4];
Ian Rogersd9c4fc92013-10-01 19:45:43 -07004383 JDWP::Set4BE(&buf[0], t->GetThreadId());
Alex Light772099a2017-11-21 14:05:04 -08004384 cb->DdmPublishChunk(CHUNK_TYPE("THDE"), ArrayRef<const uint8_t>(buf));
Elliott Hughes82188472011-11-07 18:11:48 -08004385 } else {
4386 CHECK(type == CHUNK_TYPE("THCR") || type == CHUNK_TYPE("THNM")) << type;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004387 ScopedObjectAccessUnchecked soa(Thread::Current());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004388 StackHandleScope<1> hs(soa.Self());
Andreas Gampe08883de2016-11-08 13:20:52 -08004389 Handle<mirror::String> name(hs.NewHandle(t->GetThreadName()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004390 size_t char_count = (name != nullptr) ? name->GetLength() : 0;
4391 const jchar* chars = (name != nullptr) ? name->GetValue() : nullptr;
4392 bool is_compressed = (name != nullptr) ? name->IsCompressed() : false;
Elliott Hughes82188472011-11-07 18:11:48 -08004393
Elliott Hughes21f32d72011-11-09 17:44:13 -08004394 std::vector<uint8_t> bytes;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07004395 JDWP::Append4BE(bytes, t->GetThreadId());
jessicahandojo3aaa37b2016-07-29 14:46:37 -07004396 if (is_compressed) {
4397 const uint8_t* chars_compressed = name->GetValueCompressed();
4398 JDWP::AppendUtf16CompressedBE(bytes, chars_compressed, char_count);
4399 } else {
4400 JDWP::AppendUtf16BE(bytes, chars, char_count);
4401 }
Elliott Hughes21f32d72011-11-09 17:44:13 -08004402 CHECK_EQ(bytes.size(), char_count*2 + sizeof(uint32_t)*2);
Alex Light772099a2017-11-21 14:05:04 -08004403 cb->DdmPublishChunk(type, ArrayRef<const uint8_t>(bytes));
Elliott Hughes47fce012011-10-25 18:37:19 -07004404 }
4405}
4406
Elliott Hughes47fce012011-10-25 18:37:19 -07004407void Dbg::DdmSetThreadNotification(bool enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004408 // Enable/disable thread notifications.
Elliott Hughes47fce012011-10-25 18:37:19 -07004409 gDdmThreadNotification = enable;
4410 if (enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004411 // Suspend the VM then post thread start notifications for all threads. Threads attaching will
4412 // see a suspension in progress and block until that ends. They then post their own start
4413 // notification.
4414 SuspendVM();
4415 std::list<Thread*> threads;
Ian Rogers50b35e22012-10-04 10:09:15 -07004416 Thread* self = Thread::Current();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004417 {
Ian Rogers50b35e22012-10-04 10:09:15 -07004418 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004419 threads = Runtime::Current()->GetThreadList()->GetList();
4420 }
4421 {
Ian Rogers50b35e22012-10-04 10:09:15 -07004422 ScopedObjectAccess soa(self);
Mathieu Chartier02e25112013-08-14 16:14:24 -07004423 for (Thread* thread : threads) {
4424 Dbg::DdmSendThreadNotification(thread, CHUNK_TYPE("THCR"));
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004425 }
4426 }
4427 ResumeVM();
Elliott Hughes47fce012011-10-25 18:37:19 -07004428 }
4429}
4430
Elliott Hughesa2155262011-11-16 16:26:58 -08004431void Dbg::PostThreadStartOrStop(Thread* t, uint32_t type) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07004432 if (IsDebuggerActive()) {
Sebastien Hertz6995c602014-09-09 12:10:13 +02004433 gJdwpState->PostThreadChange(t, type == CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07004434 }
Elliott Hughes82188472011-11-07 18:11:48 -08004435 Dbg::DdmSendThreadNotification(t, type);
Elliott Hughes47fce012011-10-25 18:37:19 -07004436}
4437
4438void Dbg::PostThreadStart(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004439 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07004440}
4441
4442void Dbg::PostThreadDeath(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004443 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THDE"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004444}
4445
Mathieu Chartierad466ad2015-01-08 16:28:08 -08004446JDWP::JdwpState* Dbg::GetJdwpState() {
4447 return gJdwpState;
4448}
4449
Elliott Hughes767a1472011-10-26 18:49:02 -07004450int Dbg::DdmHandleHpifChunk(HpifWhen when) {
4451 if (when == HPIF_WHEN_NOW) {
Elliott Hughes7162ad92011-10-27 14:08:42 -07004452 DdmSendHeapInfo(when);
Andreas Gampe7c5acbb2018-09-20 13:54:52 -07004453 return 1;
Elliott Hughes767a1472011-10-26 18:49:02 -07004454 }
4455
4456 if (when != HPIF_WHEN_NEVER && when != HPIF_WHEN_NEXT_GC && when != HPIF_WHEN_EVERY_GC) {
4457 LOG(ERROR) << "invalid HpifWhen value: " << static_cast<int>(when);
Andreas Gampe7c5acbb2018-09-20 13:54:52 -07004458 return 0;
Elliott Hughes767a1472011-10-26 18:49:02 -07004459 }
4460
4461 gDdmHpifWhen = when;
Andreas Gampe7c5acbb2018-09-20 13:54:52 -07004462 return 1;
Elliott Hughes767a1472011-10-26 18:49:02 -07004463}
4464
4465bool Dbg::DdmHandleHpsgNhsgChunk(Dbg::HpsgWhen when, Dbg::HpsgWhat what, bool native) {
4466 if (when != HPSG_WHEN_NEVER && when != HPSG_WHEN_EVERY_GC) {
4467 LOG(ERROR) << "invalid HpsgWhen value: " << static_cast<int>(when);
4468 return false;
4469 }
4470
4471 if (what != HPSG_WHAT_MERGED_OBJECTS && what != HPSG_WHAT_DISTINCT_OBJECTS) {
4472 LOG(ERROR) << "invalid HpsgWhat value: " << static_cast<int>(what);
4473 return false;
4474 }
4475
4476 if (native) {
4477 gDdmNhsgWhen = when;
4478 gDdmNhsgWhat = what;
4479 } else {
4480 gDdmHpsgWhen = when;
4481 gDdmHpsgWhat = what;
4482 }
4483 return true;
4484}
4485
Elliott Hughes7162ad92011-10-27 14:08:42 -07004486void Dbg::DdmSendHeapInfo(HpifWhen reason) {
4487 // If there's a one-shot 'when', reset it.
4488 if (reason == gDdmHpifWhen) {
4489 if (gDdmHpifWhen == HPIF_WHEN_NEXT_GC) {
4490 gDdmHpifWhen = HPIF_WHEN_NEVER;
4491 }
4492 }
4493
4494 /*
4495 * Chunk HPIF (client --> server)
4496 *
4497 * Heap Info. General information about the heap,
4498 * suitable for a summary display.
4499 *
4500 * [u4]: number of heaps
4501 *
4502 * For each heap:
4503 * [u4]: heap ID
4504 * [u8]: timestamp in ms since Unix epoch
4505 * [u1]: capture reason (same as 'when' value from server)
4506 * [u4]: max heap size in bytes (-Xmx)
4507 * [u4]: current heap size in bytes
4508 * [u4]: current number of bytes allocated
4509 * [u4]: current number of objects allocated
4510 */
4511 uint8_t heap_count = 1;
Ian Rogers1d54e732013-05-02 21:10:01 -07004512 gc::Heap* heap = Runtime::Current()->GetHeap();
Elliott Hughes21f32d72011-11-09 17:44:13 -08004513 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08004514 JDWP::Append4BE(bytes, heap_count);
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004515 JDWP::Append4BE(bytes, 1); // Heap id (bogus; we only have one heap).
Elliott Hughes545a0642011-11-08 19:10:03 -08004516 JDWP::Append8BE(bytes, MilliTime());
4517 JDWP::Append1BE(bytes, reason);
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004518 JDWP::Append4BE(bytes, heap->GetMaxMemory()); // Max allowed heap size in bytes.
4519 JDWP::Append4BE(bytes, heap->GetTotalMemory()); // Current heap size in bytes.
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08004520 JDWP::Append4BE(bytes, heap->GetBytesAllocated());
4521 JDWP::Append4BE(bytes, heap->GetObjectsAllocated());
Elliott Hughes21f32d72011-11-09 17:44:13 -08004522 CHECK_EQ(bytes.size(), 4U + (heap_count * (4 + 8 + 1 + 4 + 4 + 4 + 4)));
Alex Light772099a2017-11-21 14:05:04 -08004523 Runtime::Current()->GetRuntimeCallbacks()->DdmPublishChunk(CHUNK_TYPE("HPIF"),
4524 ArrayRef<const uint8_t>(bytes));
Elliott Hughes767a1472011-10-26 18:49:02 -07004525}
4526
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004527enum HpsgSolidity {
4528 SOLIDITY_FREE = 0,
4529 SOLIDITY_HARD = 1,
4530 SOLIDITY_SOFT = 2,
4531 SOLIDITY_WEAK = 3,
4532 SOLIDITY_PHANTOM = 4,
4533 SOLIDITY_FINALIZABLE = 5,
4534 SOLIDITY_SWEEP = 6,
4535};
4536
4537enum HpsgKind {
4538 KIND_OBJECT = 0,
4539 KIND_CLASS_OBJECT = 1,
4540 KIND_ARRAY_1 = 2,
4541 KIND_ARRAY_2 = 3,
4542 KIND_ARRAY_4 = 4,
4543 KIND_ARRAY_8 = 5,
4544 KIND_UNKNOWN = 6,
4545 KIND_NATIVE = 7,
4546};
4547
4548#define HPSG_PARTIAL (1<<7)
4549#define HPSG_STATE(solidity, kind) ((uint8_t)((((kind) & 0x7) << 3) | ((solidity) & 0x7)))
4550
Ian Rogers30fab402012-01-23 15:43:46 -08004551class HeapChunkContext {
4552 public:
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004553 // Maximum chunk size. Obtain this from the formula:
4554 // (((maximum_heap_size / ALLOCATION_UNIT_SIZE) + 255) / 256) * 2
4555 HeapChunkContext(bool merge, bool native)
Ian Rogers30fab402012-01-23 15:43:46 -08004556 : buf_(16384 - 16),
4557 type_(0),
Mathieu Chartier36dab362014-07-30 14:59:56 -07004558 chunk_overhead_(0) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004559 Reset();
4560 if (native) {
Ian Rogers30fab402012-01-23 15:43:46 -08004561 type_ = CHUNK_TYPE("NHSG");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004562 } else {
Ian Rogers30fab402012-01-23 15:43:46 -08004563 type_ = merge ? CHUNK_TYPE("HPSG") : CHUNK_TYPE("HPSO");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004564 }
4565 }
4566
4567 ~HeapChunkContext() {
Ian Rogers30fab402012-01-23 15:43:46 -08004568 if (p_ > &buf_[0]) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004569 Flush();
4570 }
4571 }
4572
Mathieu Chartier36dab362014-07-30 14:59:56 -07004573 void SetChunkOverhead(size_t chunk_overhead) {
4574 chunk_overhead_ = chunk_overhead;
4575 }
4576
4577 void ResetStartOfNextChunk() {
4578 startOfNextMemoryChunk_ = nullptr;
4579 }
4580
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004581 void EnsureHeader(const void* chunk_ptr) {
Ian Rogers30fab402012-01-23 15:43:46 -08004582 if (!needHeader_) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004583 return;
4584 }
4585
4586 // Start a new HPSx chunk.
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004587 JDWP::Write4BE(&p_, 1); // Heap id (bogus; we only have one heap).
4588 JDWP::Write1BE(&p_, 8); // Size of allocation unit, in bytes.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004589
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004590 JDWP::Write4BE(&p_, reinterpret_cast<uintptr_t>(chunk_ptr)); // virtual address of segment start.
4591 JDWP::Write4BE(&p_, 0); // offset of this piece (relative to the virtual address).
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004592 // [u4]: length of piece, in allocation units
4593 // 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 -08004594 pieceLenField_ = p_;
4595 JDWP::Write4BE(&p_, 0x55555555);
4596 needHeader_ = false;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004597 }
4598
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004599 void Flush() REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -07004600 if (pieceLenField_ == nullptr) {
Ian Rogersd636b062013-01-18 17:51:18 -08004601 // Flush immediately post Reset (maybe back-to-back Flush). Ignore.
4602 CHECK(needHeader_);
4603 return;
4604 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004605 // Patch the "length of piece" field.
Ian Rogers30fab402012-01-23 15:43:46 -08004606 CHECK_LE(&buf_[0], pieceLenField_);
4607 CHECK_LE(pieceLenField_, p_);
4608 JDWP::Set4BE(pieceLenField_, totalAllocationUnits_);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004609
Alex Light772099a2017-11-21 14:05:04 -08004610 ArrayRef<const uint8_t> out(&buf_[0], p_ - &buf_[0]);
4611 Runtime::Current()->GetRuntimeCallbacks()->DdmPublishChunk(type_, out);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004612 Reset();
4613 }
4614
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004615 static void HeapChunkJavaCallback(void* start, void* end, size_t used_bytes, void* arg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004616 REQUIRES_SHARED(Locks::heap_bitmap_lock_,
Ian Rogersb726dcb2012-09-05 08:57:23 -07004617 Locks::mutator_lock_) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004618 reinterpret_cast<HeapChunkContext*>(arg)->HeapChunkJavaCallback(start, end, used_bytes);
4619 }
4620
4621 static void HeapChunkNativeCallback(void* start, void* end, size_t used_bytes, void* arg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004622 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004623 reinterpret_cast<HeapChunkContext*>(arg)->HeapChunkNativeCallback(start, end, used_bytes);
Elliott Hughesa2155262011-11-16 16:26:58 -08004624 }
4625
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004626 private:
Elliott Hughesa2155262011-11-16 16:26:58 -08004627 enum { ALLOCATION_UNIT_SIZE = 8 };
4628
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004629 void Reset() {
Ian Rogers30fab402012-01-23 15:43:46 -08004630 p_ = &buf_[0];
Mathieu Chartier36dab362014-07-30 14:59:56 -07004631 ResetStartOfNextChunk();
Ian Rogers30fab402012-01-23 15:43:46 -08004632 totalAllocationUnits_ = 0;
4633 needHeader_ = true;
Ian Rogersc0542af2014-09-03 16:16:56 -07004634 pieceLenField_ = nullptr;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004635 }
4636
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004637 bool IsNative() const {
4638 return type_ == CHUNK_TYPE("NHSG");
4639 }
4640
4641 // Returns true if the object is not an empty chunk.
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004642 bool ProcessRecord(void* start, size_t used_bytes) REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers30fab402012-01-23 15:43:46 -08004643 // Note: heap call backs cannot manipulate the heap upon which they are crawling, care is taken
4644 // in the following code not to allocate memory, by ensuring buf_ is of the correct size
Ian Rogers15bf2d32012-08-28 17:33:04 -07004645 if (used_bytes == 0) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004646 if (start == nullptr) {
4647 // Reset for start of new heap.
4648 startOfNextMemoryChunk_ = nullptr;
4649 Flush();
4650 }
4651 // Only process in use memory so that free region information
4652 // also includes dlmalloc book keeping.
4653 return false;
Elliott Hughesa2155262011-11-16 16:26:58 -08004654 }
Ian Rogersc0542af2014-09-03 16:16:56 -07004655 if (startOfNextMemoryChunk_ != nullptr) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004656 // Transmit any pending free memory. Native free memory of over kMaxFreeLen could be because
4657 // of the use of mmaps, so don't report. If not free memory then start a new segment.
4658 bool flush = true;
4659 if (start > startOfNextMemoryChunk_) {
4660 const size_t kMaxFreeLen = 2 * kPageSize;
4661 void* free_start = startOfNextMemoryChunk_;
4662 void* free_end = start;
4663 const size_t free_len =
4664 reinterpret_cast<uintptr_t>(free_end) - reinterpret_cast<uintptr_t>(free_start);
4665 if (!IsNative() || free_len < kMaxFreeLen) {
4666 AppendChunk(HPSG_STATE(SOLIDITY_FREE, 0), free_start, free_len, IsNative());
4667 flush = false;
Ian Rogers15bf2d32012-08-28 17:33:04 -07004668 }
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004669 }
4670 if (flush) {
4671 startOfNextMemoryChunk_ = nullptr;
4672 Flush();
4673 }
Ian Rogers15bf2d32012-08-28 17:33:04 -07004674 }
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004675 return true;
Ian Rogers15bf2d32012-08-28 17:33:04 -07004676 }
Elliott Hughesa2155262011-11-16 16:26:58 -08004677
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004678 void HeapChunkNativeCallback(void* start, void* /*end*/, size_t used_bytes)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004679 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004680 if (ProcessRecord(start, used_bytes)) {
4681 uint8_t state = ExamineNativeObject(start);
Andreas Gampe98ea9d92018-10-19 14:06:15 -07004682 AppendChunk(state, start, used_bytes + chunk_overhead_, /*is_native=*/ true);
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004683 startOfNextMemoryChunk_ = reinterpret_cast<char*>(start) + used_bytes + chunk_overhead_;
4684 }
4685 }
4686
4687 void HeapChunkJavaCallback(void* start, void* /*end*/, size_t used_bytes)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004688 REQUIRES_SHARED(Locks::heap_bitmap_lock_, Locks::mutator_lock_) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004689 if (ProcessRecord(start, used_bytes)) {
4690 // Determine the type of this chunk.
4691 // OLD-TODO: if context.merge, see if this chunk is different from the last chunk.
4692 // If it's the same, we should combine them.
4693 uint8_t state = ExamineJavaObject(reinterpret_cast<mirror::Object*>(start));
Andreas Gampe98ea9d92018-10-19 14:06:15 -07004694 AppendChunk(state, start, used_bytes + chunk_overhead_, /*is_native=*/ false);
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004695 startOfNextMemoryChunk_ = reinterpret_cast<char*>(start) + used_bytes + chunk_overhead_;
4696 }
4697 }
4698
4699 void AppendChunk(uint8_t state, void* ptr, size_t length, bool is_native)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004700 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07004701 // Make sure there's enough room left in the buffer.
4702 // We need to use two bytes for every fractional 256 allocation units used by the chunk plus
4703 // 17 bytes for any header.
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004704 const size_t needed = ((RoundUp(length / ALLOCATION_UNIT_SIZE, 256) / 256) * 2) + 17;
4705 size_t byte_left = &buf_.back() - p_;
4706 if (byte_left < needed) {
4707 if (is_native) {
Pavel Vyssotski7522c742014-12-08 13:38:26 +06004708 // Cannot trigger memory allocation while walking native heap.
Pavel Vyssotski7522c742014-12-08 13:38:26 +06004709 return;
4710 }
Ian Rogers15bf2d32012-08-28 17:33:04 -07004711 Flush();
4712 }
4713
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004714 byte_left = &buf_.back() - p_;
4715 if (byte_left < needed) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07004716 LOG(WARNING) << "Chunk is too big to transmit (chunk_len=" << length << ", "
4717 << needed << " bytes)";
4718 return;
4719 }
4720 EnsureHeader(ptr);
Elliott Hughesa2155262011-11-16 16:26:58 -08004721 // Write out the chunk description.
Ian Rogers15bf2d32012-08-28 17:33:04 -07004722 length /= ALLOCATION_UNIT_SIZE; // Convert to allocation units.
4723 totalAllocationUnits_ += length;
4724 while (length > 256) {
Ian Rogers30fab402012-01-23 15:43:46 -08004725 *p_++ = state | HPSG_PARTIAL;
4726 *p_++ = 255; // length - 1
Ian Rogers15bf2d32012-08-28 17:33:04 -07004727 length -= 256;
Elliott Hughesa2155262011-11-16 16:26:58 -08004728 }
Ian Rogers30fab402012-01-23 15:43:46 -08004729 *p_++ = state;
Ian Rogers15bf2d32012-08-28 17:33:04 -07004730 *p_++ = length - 1;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004731 }
4732
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004733 uint8_t ExamineNativeObject(const void* p) REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004734 return p == nullptr ? HPSG_STATE(SOLIDITY_FREE, 0) : HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
4735 }
4736
Vladimir Marko83114892019-04-11 13:05:50 +01004737 uint8_t ExamineJavaObject(ObjPtr<mirror::Object> o)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004738 REQUIRES_SHARED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -07004739 if (o == nullptr) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004740 return HPSG_STATE(SOLIDITY_FREE, 0);
4741 }
Elliott Hughesa2155262011-11-16 16:26:58 -08004742 // It's an allocated chunk. Figure out what it is.
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004743 gc::Heap* heap = Runtime::Current()->GetHeap();
4744 if (!heap->IsLiveObjectLocked(o)) {
4745 LOG(ERROR) << "Invalid object in managed heap: " << o;
Elliott Hughesa2155262011-11-16 16:26:58 -08004746 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
4747 }
Vladimir Marko4617d582019-03-28 13:48:31 +00004748 ObjPtr<mirror::Class> c = o->GetClass();
Ian Rogersc0542af2014-09-03 16:16:56 -07004749 if (c == nullptr) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004750 // The object was probably just created but hasn't been initialized yet.
4751 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
4752 }
Vladimir Marko4617d582019-03-28 13:48:31 +00004753 if (!heap->IsValidObjectAddress(c.Ptr())) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07004754 LOG(ERROR) << "Invalid class for managed heap object: " << o << " " << c;
Elliott Hughesa2155262011-11-16 16:26:58 -08004755 return HPSG_STATE(SOLIDITY_HARD, KIND_UNKNOWN);
4756 }
Mathieu Chartierf26e1b32015-01-29 10:47:10 -08004757 if (c->GetClass() == nullptr) {
4758 LOG(ERROR) << "Null class of class " << c << " for object " << o;
4759 return HPSG_STATE(SOLIDITY_HARD, KIND_UNKNOWN);
4760 }
Elliott Hughesa2155262011-11-16 16:26:58 -08004761 if (c->IsClassClass()) {
4762 return HPSG_STATE(SOLIDITY_HARD, KIND_CLASS_OBJECT);
4763 }
Elliott Hughesa2155262011-11-16 16:26:58 -08004764 if (c->IsArrayClass()) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004765 switch (c->GetComponentSize()) {
4766 case 1: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_1);
4767 case 2: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_2);
4768 case 4: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
4769 case 8: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_8);
4770 }
4771 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004772 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
4773 }
4774
Ian Rogers30fab402012-01-23 15:43:46 -08004775 std::vector<uint8_t> buf_;
4776 uint8_t* p_;
4777 uint8_t* pieceLenField_;
Ian Rogers15bf2d32012-08-28 17:33:04 -07004778 void* startOfNextMemoryChunk_;
Ian Rogers30fab402012-01-23 15:43:46 -08004779 size_t totalAllocationUnits_;
4780 uint32_t type_;
Ian Rogers30fab402012-01-23 15:43:46 -08004781 bool needHeader_;
Mathieu Chartier36dab362014-07-30 14:59:56 -07004782 size_t chunk_overhead_;
Ian Rogers30fab402012-01-23 15:43:46 -08004783
Elliott Hughesa2155262011-11-16 16:26:58 -08004784 DISALLOW_COPY_AND_ASSIGN(HeapChunkContext);
4785};
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004786
4787void Dbg::DdmSendHeapSegments(bool native) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004788 Dbg::HpsgWhen when = native ? gDdmNhsgWhen : gDdmHpsgWhen;
4789 Dbg::HpsgWhat what = native ? gDdmNhsgWhat : gDdmHpsgWhat;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004790 if (when == HPSG_WHEN_NEVER) {
4791 return;
4792 }
Alex Light772099a2017-11-21 14:05:04 -08004793 RuntimeCallbacks* cb = Runtime::Current()->GetRuntimeCallbacks();
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004794 // Figure out what kind of chunks we'll be sending.
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004795 CHECK(what == HPSG_WHAT_MERGED_OBJECTS || what == HPSG_WHAT_DISTINCT_OBJECTS)
4796 << static_cast<int>(what);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004797
4798 // First, send a heap start chunk.
4799 uint8_t heap_id[4];
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004800 JDWP::Set4BE(&heap_id[0], 1); // Heap id (bogus; we only have one heap).
Alex Light772099a2017-11-21 14:05:04 -08004801 cb->DdmPublishChunk(native ? CHUNK_TYPE("NHST") : CHUNK_TYPE("HPST"),
4802 ArrayRef<const uint8_t>(heap_id));
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07004803 Thread* self = Thread::Current();
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07004804 Locks::mutator_lock_->AssertSharedHeld(self);
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07004805
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004806 // Send a series of heap segment chunks.
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004807 HeapChunkContext context(what == HPSG_WHAT_MERGED_OBJECTS, native);
Andreas Gampe0c183382017-07-13 22:26:24 -07004808 auto bump_pointer_space_visitor = [&](mirror::Object* obj)
4809 REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
4810 const size_t size = RoundUp(obj->SizeOf(), kObjectAlignment);
4811 HeapChunkContext::HeapChunkJavaCallback(
4812 obj, reinterpret_cast<void*>(reinterpret_cast<uintptr_t>(obj) + size), size, &context);
4813 };
Elliott Hughesa2155262011-11-16 16:26:58 -08004814 if (native) {
Dimitry Ivanove6465bc2015-12-14 18:55:02 -08004815 UNIMPLEMENTED(WARNING) << "Native heap inspection is not supported";
Elliott Hughesa2155262011-11-16 16:26:58 -08004816 } else {
Ian Rogers1d54e732013-05-02 21:10:01 -07004817 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartier36dab362014-07-30 14:59:56 -07004818 for (const auto& space : heap->GetContinuousSpaces()) {
4819 if (space->IsDlMallocSpace()) {
Mathieu Chartier4c69d7f2014-10-10 12:45:50 -07004820 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004821 // dlmalloc's chunk header is 2 * sizeof(size_t), but if the previous chunk is in use for an
4822 // allocation then the first sizeof(size_t) may belong to it.
4823 context.SetChunkOverhead(sizeof(size_t));
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004824 space->AsDlMallocSpace()->Walk(HeapChunkContext::HeapChunkJavaCallback, &context);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004825 } else if (space->IsRosAllocSpace()) {
4826 context.SetChunkOverhead(0);
Mathieu Chartier4c69d7f2014-10-10 12:45:50 -07004827 // Need to acquire the mutator lock before the heap bitmap lock with exclusive access since
4828 // RosAlloc's internal logic doesn't know to release and reacquire the heap bitmap lock.
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07004829 ScopedThreadSuspension sts(self, kSuspended);
Mathieu Chartier4f55e222015-09-04 13:26:21 -07004830 ScopedSuspendAll ssa(__FUNCTION__);
4831 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
4832 space->AsRosAllocSpace()->Walk(HeapChunkContext::HeapChunkJavaCallback, &context);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004833 } else if (space->IsBumpPointerSpace()) {
Mathieu Chartier4c69d7f2014-10-10 12:45:50 -07004834 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004835 context.SetChunkOverhead(0);
Andreas Gampe0c183382017-07-13 22:26:24 -07004836 space->AsBumpPointerSpace()->Walk(bump_pointer_space_visitor);
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004837 HeapChunkContext::HeapChunkJavaCallback(nullptr, nullptr, 0, &context);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08004838 } else if (space->IsRegionSpace()) {
4839 heap->IncrementDisableMovingGC(self);
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07004840 {
4841 ScopedThreadSuspension sts(self, kSuspended);
Mathieu Chartier4f55e222015-09-04 13:26:21 -07004842 ScopedSuspendAll ssa(__FUNCTION__);
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07004843 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
4844 context.SetChunkOverhead(0);
Andreas Gampe0c183382017-07-13 22:26:24 -07004845 space->AsRegionSpace()->Walk(bump_pointer_space_visitor);
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07004846 HeapChunkContext::HeapChunkJavaCallback(nullptr, nullptr, 0, &context);
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07004847 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08004848 heap->DecrementDisableMovingGC(self);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004849 } else {
4850 UNIMPLEMENTED(WARNING) << "Not counting objects in space " << *space;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07004851 }
Mathieu Chartier36dab362014-07-30 14:59:56 -07004852 context.ResetStartOfNextChunk();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07004853 }
Mathieu Chartier4c69d7f2014-10-10 12:45:50 -07004854 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07004855 // Walk the large objects, these are not in the AllocSpace.
Mathieu Chartier36dab362014-07-30 14:59:56 -07004856 context.SetChunkOverhead(0);
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004857 heap->GetLargeObjectsSpace()->Walk(HeapChunkContext::HeapChunkJavaCallback, &context);
Elliott Hughesa2155262011-11-16 16:26:58 -08004858 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004859
4860 // Finally, send a heap end chunk.
Alex Light772099a2017-11-21 14:05:04 -08004861 cb->DdmPublishChunk(native ? CHUNK_TYPE("NHEN") : CHUNK_TYPE("HPEN"),
4862 ArrayRef<const uint8_t>(heap_id));
Elliott Hughes767a1472011-10-26 18:49:02 -07004863}
4864
Brian Carlstrom306db812014-09-05 13:01:41 -07004865void Dbg::SetAllocTrackingEnabled(bool enable) {
Man Cao8c2ff642015-05-27 17:25:30 -07004866 gc::AllocRecordObjectMap::SetAllocTrackingEnabled(enable);
Elliott Hughes545a0642011-11-08 19:10:03 -08004867}
4868
4869void Dbg::DumpRecentAllocations() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004870 ScopedObjectAccess soa(Thread::Current());
Brian Carlstrom306db812014-09-05 13:01:41 -07004871 MutexLock mu(soa.Self(), *Locks::alloc_tracker_lock_);
Man Cao8c2ff642015-05-27 17:25:30 -07004872 if (!Runtime::Current()->GetHeap()->IsAllocTrackingEnabled()) {
Elliott Hughes545a0642011-11-08 19:10:03 -08004873 LOG(INFO) << "Not recording tracked allocations";
4874 return;
4875 }
Man Cao8c2ff642015-05-27 17:25:30 -07004876 gc::AllocRecordObjectMap* records = Runtime::Current()->GetHeap()->GetAllocationRecords();
4877 CHECK(records != nullptr);
Elliott Hughes545a0642011-11-08 19:10:03 -08004878
Man Cao1ed11b92015-06-11 22:47:35 -07004879 const uint16_t capped_count = CappedAllocRecordCount(records->GetRecentAllocationSize());
Brian Carlstrom306db812014-09-05 13:01:41 -07004880 uint16_t count = capped_count;
Elliott Hughes545a0642011-11-08 19:10:03 -08004881
Man Cao8c2ff642015-05-27 17:25:30 -07004882 LOG(INFO) << "Tracked allocations, (count=" << count << ")";
4883 for (auto it = records->RBegin(), end = records->REnd();
4884 count > 0 && it != end; count--, it++) {
Mathieu Chartier458b1052016-03-29 14:02:55 -07004885 const gc::AllocRecord* record = &it->second;
Elliott Hughes545a0642011-11-08 19:10:03 -08004886
Man Cao8c2ff642015-05-27 17:25:30 -07004887 LOG(INFO) << StringPrintf(" Thread %-2d %6zd bytes ", record->GetTid(), record->ByteCount())
David Sehr709b0702016-10-13 09:12:37 -07004888 << mirror::Class::PrettyClass(record->GetClass());
Elliott Hughes545a0642011-11-08 19:10:03 -08004889
Man Cao8c2ff642015-05-27 17:25:30 -07004890 for (size_t stack_frame = 0, depth = record->GetDepth(); stack_frame < depth; ++stack_frame) {
4891 const gc::AllocRecordStackTraceElement& stack_element = record->StackElement(stack_frame);
4892 ArtMethod* m = stack_element.GetMethod();
David Sehr709b0702016-10-13 09:12:37 -07004893 LOG(INFO) << " " << ArtMethod::PrettyMethod(m) << " line "
4894 << stack_element.ComputeLineNumber();
Elliott Hughes545a0642011-11-08 19:10:03 -08004895 }
4896
4897 // pause periodically to help logcat catch up
4898 if ((count % 5) == 0) {
4899 usleep(40000);
4900 }
Elliott Hughes545a0642011-11-08 19:10:03 -08004901 }
4902}
4903
4904class StringTable {
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07004905 private:
4906 struct Entry {
Andreas Gampe84eadb22017-07-07 15:08:01 -07004907 explicit Entry(const char* data_in)
4908 : data(data_in), hash(ComputeModifiedUtf8Hash(data_in)), index(0) {
4909 }
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07004910 Entry(const Entry& entry) = default;
4911 Entry(Entry&& entry) = default;
4912
4913 // Pointer to the actual string data.
4914 const char* data;
Andreas Gampe84eadb22017-07-07 15:08:01 -07004915
4916 // The hash of the data.
4917 const uint32_t hash;
4918
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07004919 // The index. This will be filled in on Finish and is not part of the ordering, so mark it
4920 // mutable.
4921 mutable uint32_t index;
4922
Andreas Gampe84eadb22017-07-07 15:08:01 -07004923 bool operator==(const Entry& other) const {
4924 return strcmp(data, other.data) == 0;
4925 }
4926 };
4927 struct EntryHash {
4928 size_t operator()(const Entry& entry) const {
4929 return entry.hash;
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07004930 }
4931 };
4932
Elliott Hughes545a0642011-11-08 19:10:03 -08004933 public:
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07004934 StringTable() : finished_(false) {
Elliott Hughes545a0642011-11-08 19:10:03 -08004935 }
4936
Andreas Gampef774a4e2017-07-06 22:15:18 -07004937 void Add(const char* str, bool copy_string) {
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07004938 DCHECK(!finished_);
Andreas Gampef774a4e2017-07-06 22:15:18 -07004939 if (UNLIKELY(copy_string)) {
4940 // Check whether it's already there.
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07004941 Entry entry(str);
4942 if (table_.find(entry) != table_.end()) {
Andreas Gampef774a4e2017-07-06 22:15:18 -07004943 return;
4944 }
Mathieu Chartier4345c462014-06-27 10:20:14 -07004945
Andreas Gampef774a4e2017-07-06 22:15:18 -07004946 // Make a copy.
4947 size_t str_len = strlen(str);
4948 char* copy = new char[str_len + 1];
4949 strlcpy(copy, str, str_len + 1);
4950 string_backup_.emplace_back(copy);
4951 str = copy;
4952 }
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07004953 Entry entry(str);
4954 table_.insert(entry);
4955 }
4956
4957 // Update all entries and give them an index. Note that this is likely not the insertion order,
4958 // as the set will with high likelihood reorder elements. Thus, Add must not be called after
4959 // Finish, and Finish must be called before IndexOf. In that case, WriteTo will walk in
4960 // the same order as Finish, and indices will agree. The order invariant, as well as indices,
4961 // are enforced through debug checks.
4962 void Finish() {
4963 DCHECK(!finished_);
4964 finished_ = true;
4965 uint32_t index = 0;
4966 for (auto& entry : table_) {
4967 entry.index = index;
4968 ++index;
4969 }
Elliott Hughes545a0642011-11-08 19:10:03 -08004970 }
4971
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004972 size_t IndexOf(const char* s) const {
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07004973 DCHECK(finished_);
4974 Entry entry(s);
4975 auto it = table_.find(entry);
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004976 if (it == table_.end()) {
4977 LOG(FATAL) << "IndexOf(\"" << s << "\") failed";
4978 }
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07004979 return it->index;
Elliott Hughes545a0642011-11-08 19:10:03 -08004980 }
4981
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004982 size_t Size() const {
Elliott Hughes545a0642011-11-08 19:10:03 -08004983 return table_.size();
4984 }
4985
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004986 void WriteTo(std::vector<uint8_t>& bytes) const {
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07004987 DCHECK(finished_);
4988 uint32_t cur_index = 0;
4989 for (const auto& entry : table_) {
4990 DCHECK_EQ(cur_index++, entry.index);
4991
4992 size_t s_len = CountModifiedUtf8Chars(entry.data);
Christopher Ferris8a354052015-04-24 17:23:53 -07004993 std::unique_ptr<uint16_t[]> s_utf16(new uint16_t[s_len]);
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07004994 ConvertModifiedUtf8ToUtf16(s_utf16.get(), entry.data);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004995 JDWP::AppendUtf16BE(bytes, s_utf16.get(), s_len);
Elliott Hughes545a0642011-11-08 19:10:03 -08004996 }
4997 }
4998
4999 private:
Andreas Gampe84eadb22017-07-07 15:08:01 -07005000 std::unordered_set<Entry, EntryHash> table_;
Andreas Gampef774a4e2017-07-06 22:15:18 -07005001 std::vector<std::unique_ptr<char[]>> string_backup_;
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07005002
5003 bool finished_;
5004
Elliott Hughes545a0642011-11-08 19:10:03 -08005005 DISALLOW_COPY_AND_ASSIGN(StringTable);
5006};
5007
Mathieu Chartiere401d142015-04-22 13:56:20 -07005008static const char* GetMethodSourceFile(ArtMethod* method)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005009 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07005010 DCHECK(method != nullptr);
5011 const char* source_file = method->GetDeclaringClassSourceFile();
Sebastien Hertz280286a2014-04-28 09:26:50 +02005012 return (source_file != nullptr) ? source_file : "";
5013}
5014
Elliott Hughes545a0642011-11-08 19:10:03 -08005015/*
5016 * The data we send to DDMS contains everything we have recorded.
5017 *
5018 * Message header (all values big-endian):
5019 * (1b) message header len (to allow future expansion); includes itself
5020 * (1b) entry header len
5021 * (1b) stack frame len
5022 * (2b) number of entries
5023 * (4b) offset to string table from start of message
5024 * (2b) number of class name strings
5025 * (2b) number of method name strings
5026 * (2b) number of source file name strings
5027 * For each entry:
5028 * (4b) total allocation size
Elliott Hughes221229c2013-01-08 18:17:50 -08005029 * (2b) thread id
Elliott Hughes545a0642011-11-08 19:10:03 -08005030 * (2b) allocated object's class name index
5031 * (1b) stack depth
5032 * For each stack frame:
5033 * (2b) method's class name
5034 * (2b) method name
5035 * (2b) method source file
5036 * (2b) line number, clipped to 32767; -2 if native; -1 if no source
5037 * (xb) class name strings
5038 * (xb) method name strings
5039 * (xb) source file strings
5040 *
5041 * As with other DDM traffic, strings are sent as a 4-byte length
5042 * followed by UTF-16 data.
5043 *
5044 * We send up 16-bit unsigned indexes into string tables. In theory there
Brian Carlstrom306db812014-09-05 13:01:41 -07005045 * can be (kMaxAllocRecordStackDepth * alloc_record_max_) unique strings in
Elliott Hughes545a0642011-11-08 19:10:03 -08005046 * each table, but in practice there should be far fewer.
5047 *
5048 * The chief reason for using a string table here is to keep the size of
5049 * the DDMS message to a minimum. This is partly to make the protocol
5050 * efficient, but also because we have to form the whole thing up all at
5051 * once in a memory buffer.
5052 *
5053 * We use separate string tables for class names, method names, and source
5054 * files to keep the indexes small. There will generally be no overlap
5055 * between the contents of these tables.
5056 */
5057jbyteArray Dbg::GetRecentAllocations() {
Ian Rogerscf7f1912014-10-22 22:06:39 -07005058 if ((false)) {
Elliott Hughes545a0642011-11-08 19:10:03 -08005059 DumpRecentAllocations();
5060 }
5061
Ian Rogers50b35e22012-10-04 10:09:15 -07005062 Thread* self = Thread::Current();
Elliott Hughes545a0642011-11-08 19:10:03 -08005063 std::vector<uint8_t> bytes;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005064 {
Brian Carlstrom306db812014-09-05 13:01:41 -07005065 MutexLock mu(self, *Locks::alloc_tracker_lock_);
Man Cao8c2ff642015-05-27 17:25:30 -07005066 gc::AllocRecordObjectMap* records = Runtime::Current()->GetHeap()->GetAllocationRecords();
5067 // In case this method is called when allocation tracker is disabled,
5068 // we should still send some data back.
5069 gc::AllocRecordObjectMap dummy;
5070 if (records == nullptr) {
5071 CHECK(!Runtime::Current()->GetHeap()->IsAllocTrackingEnabled());
5072 records = &dummy;
5073 }
Man Cao41656de2015-07-06 18:53:15 -07005074 // We don't need to wait on the condition variable records->new_record_condition_, because this
5075 // function only reads the class objects, which are already marked so it doesn't change their
5076 // reachability.
Man Cao8c2ff642015-05-27 17:25:30 -07005077
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005078 //
5079 // Part 1: generate string tables.
5080 //
5081 StringTable class_names;
5082 StringTable method_names;
5083 StringTable filenames;
Elliott Hughes545a0642011-11-08 19:10:03 -08005084
Andreas Gampeff29cee2017-07-07 11:11:15 -07005085 VLOG(jdwp) << "Collecting StringTables.";
5086
Man Cao1ed11b92015-06-11 22:47:35 -07005087 const uint16_t capped_count = CappedAllocRecordCount(records->GetRecentAllocationSize());
Brian Carlstrom306db812014-09-05 13:01:41 -07005088 uint16_t count = capped_count;
Andreas Gamped0fc7682017-07-07 14:03:08 -07005089 size_t alloc_byte_count = 0;
Man Cao8c2ff642015-05-27 17:25:30 -07005090 for (auto it = records->RBegin(), end = records->REnd();
5091 count > 0 && it != end; count--, it++) {
Mathieu Chartier458b1052016-03-29 14:02:55 -07005092 const gc::AllocRecord* record = &it->second;
Ian Rogers1ff3c982014-08-12 02:30:58 -07005093 std::string temp;
Andreas Gampef774a4e2017-07-06 22:15:18 -07005094 const char* class_descr = record->GetClassDescriptor(&temp);
5095 class_names.Add(class_descr, !temp.empty());
Andreas Gamped0fc7682017-07-07 14:03:08 -07005096
5097 // Size + tid + class name index + stack depth.
5098 alloc_byte_count += 4u + 2u + 2u + 1u;
5099
Man Cao8c2ff642015-05-27 17:25:30 -07005100 for (size_t i = 0, depth = record->GetDepth(); i < depth; i++) {
5101 ArtMethod* m = record->StackElement(i).GetMethod();
Andreas Gampef774a4e2017-07-06 22:15:18 -07005102 class_names.Add(m->GetDeclaringClassDescriptor(), false);
5103 method_names.Add(m->GetName(), false);
5104 filenames.Add(GetMethodSourceFile(m), false);
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005105 }
Andreas Gamped0fc7682017-07-07 14:03:08 -07005106
5107 // Depth * (class index + method name index + file name index + line number).
5108 alloc_byte_count += record->GetDepth() * (2u + 2u + 2u + 2u);
Elliott Hughes545a0642011-11-08 19:10:03 -08005109 }
5110
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07005111 class_names.Finish();
5112 method_names.Finish();
5113 filenames.Finish();
Andreas Gampeff29cee2017-07-07 11:11:15 -07005114 VLOG(jdwp) << "Done collecting StringTables:" << std::endl
5115 << " ClassNames: " << class_names.Size() << std::endl
5116 << " MethodNames: " << method_names.Size() << std::endl
5117 << " Filenames: " << filenames.Size();
5118
Man Cao8c2ff642015-05-27 17:25:30 -07005119 LOG(INFO) << "recent allocation records: " << capped_count;
5120 LOG(INFO) << "allocation records all objects: " << records->Size();
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005121
5122 //
5123 // Part 2: Generate the output and store it in the buffer.
5124 //
5125
5126 // (1b) message header len (to allow future expansion); includes itself
5127 // (1b) entry header len
5128 // (1b) stack frame len
5129 const int kMessageHeaderLen = 15;
5130 const int kEntryHeaderLen = 9;
5131 const int kStackFrameLen = 8;
5132 JDWP::Append1BE(bytes, kMessageHeaderLen);
5133 JDWP::Append1BE(bytes, kEntryHeaderLen);
5134 JDWP::Append1BE(bytes, kStackFrameLen);
5135
5136 // (2b) number of entries
5137 // (4b) offset to string table from start of message
5138 // (2b) number of class name strings
5139 // (2b) number of method name strings
5140 // (2b) number of source file name strings
Brian Carlstrom306db812014-09-05 13:01:41 -07005141 JDWP::Append2BE(bytes, capped_count);
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005142 size_t string_table_offset = bytes.size();
Brian Carlstrom7934ac22013-07-26 10:54:15 -07005143 JDWP::Append4BE(bytes, 0); // We'll patch this later...
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005144 JDWP::Append2BE(bytes, class_names.Size());
5145 JDWP::Append2BE(bytes, method_names.Size());
5146 JDWP::Append2BE(bytes, filenames.Size());
5147
Andreas Gampeff29cee2017-07-07 11:11:15 -07005148 VLOG(jdwp) << "Dumping allocations with stacks";
5149
Andreas Gamped0fc7682017-07-07 14:03:08 -07005150 // Enlarge the vector for the allocation data.
5151 size_t reserve_size = bytes.size() + alloc_byte_count;
5152 bytes.reserve(reserve_size);
5153
Ian Rogers1ff3c982014-08-12 02:30:58 -07005154 std::string temp;
Man Cao8c2ff642015-05-27 17:25:30 -07005155 count = capped_count;
5156 // The last "count" number of allocation records in "records" are the most recent "count" number
5157 // of allocations. Reverse iterate to get them. The most recent allocation is sent first.
5158 for (auto it = records->RBegin(), end = records->REnd();
5159 count > 0 && it != end; count--, it++) {
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005160 // For each entry:
5161 // (4b) total allocation size
5162 // (2b) thread id
5163 // (2b) allocated object's class name index
5164 // (1b) stack depth
Mathieu Chartier458b1052016-03-29 14:02:55 -07005165 const gc::AllocRecord* record = &it->second;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005166 size_t stack_depth = record->GetDepth();
Mathieu Chartierf8322842014-05-16 10:59:25 -07005167 size_t allocated_object_class_name_index =
Man Cao41656de2015-07-06 18:53:15 -07005168 class_names.IndexOf(record->GetClassDescriptor(&temp));
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07005169 JDWP::Append4BE(bytes, record->ByteCount());
Man Cao8c2ff642015-05-27 17:25:30 -07005170 JDWP::Append2BE(bytes, static_cast<uint16_t>(record->GetTid()));
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005171 JDWP::Append2BE(bytes, allocated_object_class_name_index);
5172 JDWP::Append1BE(bytes, stack_depth);
5173
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005174 for (size_t stack_frame = 0; stack_frame < stack_depth; ++stack_frame) {
5175 // For each stack frame:
5176 // (2b) method's class name
5177 // (2b) method name
5178 // (2b) method source file
5179 // (2b) line number, clipped to 32767; -2 if native; -1 if no source
Man Cao8c2ff642015-05-27 17:25:30 -07005180 ArtMethod* m = record->StackElement(stack_frame).GetMethod();
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07005181 size_t class_name_index = class_names.IndexOf(m->GetDeclaringClassDescriptor());
5182 size_t method_name_index = method_names.IndexOf(m->GetName());
5183 size_t file_name_index = filenames.IndexOf(GetMethodSourceFile(m));
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005184 JDWP::Append2BE(bytes, class_name_index);
5185 JDWP::Append2BE(bytes, method_name_index);
5186 JDWP::Append2BE(bytes, file_name_index);
Man Cao8c2ff642015-05-27 17:25:30 -07005187 JDWP::Append2BE(bytes, record->StackElement(stack_frame).ComputeLineNumber());
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005188 }
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005189 }
5190
Andreas Gamped0fc7682017-07-07 14:03:08 -07005191 CHECK_EQ(bytes.size(), reserve_size);
Andreas Gampeff29cee2017-07-07 11:11:15 -07005192 VLOG(jdwp) << "Dumping tables.";
5193
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005194 // (xb) class name strings
5195 // (xb) method name strings
5196 // (xb) source file strings
5197 JDWP::Set4BE(&bytes[string_table_offset], bytes.size());
5198 class_names.WriteTo(bytes);
5199 method_names.WriteTo(bytes);
5200 filenames.WriteTo(bytes);
Andreas Gampeff29cee2017-07-07 11:11:15 -07005201
5202 VLOG(jdwp) << "GetRecentAllocations: data created. " << bytes.size();
Elliott Hughes545a0642011-11-08 19:10:03 -08005203 }
Ian Rogers50b35e22012-10-04 10:09:15 -07005204 JNIEnv* env = self->GetJniEnv();
Elliott Hughes545a0642011-11-08 19:10:03 -08005205 jbyteArray result = env->NewByteArray(bytes.size());
Ian Rogersc0542af2014-09-03 16:16:56 -07005206 if (result != nullptr) {
Elliott Hughes545a0642011-11-08 19:10:03 -08005207 env->SetByteArrayRegion(result, 0, bytes.size(), reinterpret_cast<const jbyte*>(&bytes[0]));
5208 }
5209 return result;
5210}
5211
Mathieu Chartiere401d142015-04-22 13:56:20 -07005212ArtMethod* DeoptimizationRequest::Method() const {
Andreas Gampe13b27842016-11-07 16:48:23 -08005213 return jni::DecodeArtMethod(method_);
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07005214}
5215
Mathieu Chartiere401d142015-04-22 13:56:20 -07005216void DeoptimizationRequest::SetMethod(ArtMethod* m) {
Andreas Gampe13b27842016-11-07 16:48:23 -08005217 method_ = jni::EncodeArtMethod(m);
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07005218}
5219
Mathieu Chartiera6b1ead2015-10-06 10:32:38 -07005220void Dbg::VisitRoots(RootVisitor* visitor) {
5221 // Visit breakpoint roots, used to prevent unloading of methods with breakpoints.
5222 ReaderMutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
5223 BufferedRootVisitor<128> root_visitor(visitor, RootInfo(kRootVMInternal));
5224 for (Breakpoint& breakpoint : gBreakpoints) {
Andreas Gampe542451c2016-07-26 09:02:02 -07005225 breakpoint.Method()->VisitRoots(root_visitor, kRuntimePointerSize);
Mathieu Chartiera6b1ead2015-10-06 10:32:38 -07005226 }
5227}
5228
Andreas Gampe04bbb5b2017-01-19 17:49:03 +00005229void Dbg::DbgThreadLifecycleCallback::ThreadStart(Thread* self) {
5230 Dbg::PostThreadStart(self);
5231}
5232
5233void Dbg::DbgThreadLifecycleCallback::ThreadDeath(Thread* self) {
5234 Dbg::PostThreadDeath(self);
5235}
5236
Andreas Gampe0f01b582017-01-18 15:22:37 -08005237void Dbg::DbgClassLoadCallback::ClassLoad(Handle<mirror::Class> klass ATTRIBUTE_UNUSED) {
5238 // Ignore ClassLoad;
5239}
5240void Dbg::DbgClassLoadCallback::ClassPrepare(Handle<mirror::Class> temp_klass ATTRIBUTE_UNUSED,
5241 Handle<mirror::Class> klass) {
5242 Dbg::PostClassPrepare(klass.Get());
5243}
5244
Elliott Hughes872d4ec2011-10-21 17:07:15 -07005245} // namespace art