blob: c5b111f804ddeff34ed7b9180c6e4c0b6a45ba6c [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"
Elliott Hughes64f574f2013-02-20 14:57:12 -080053#include "jdwp/object_registry.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 Marko4617d582019-03-28 13:48:31 +0000418 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 Marko4617d582019-03-28 13:48:31 +0000433 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 =
451 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
Ian Rogers98379392014-02-24 16:53:16 -0800487static JDWP::JdwpTag TagFromClass(const ScopedObjectAccessUnchecked& soa, 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 Marko4617d582019-03-28 13:48:31 +0000769 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);
853 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;
Mathieu Chartier9d156d52016-10-06 17:44:26 -0700997 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;
1012 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
1013 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;
1022 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;
1043 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
1044 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;
1139 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
1140 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;
1198 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
1199 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 Marko4617d582019-03-28 13:48:31 +00001337 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();
jessicahandojo3aaa37b2016-07-29 14:46:37 -07001378 new_object = mirror::String::AllocEmptyString<true>(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 =
1407 mirror::Array::Alloc<true>(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;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001442 mirror::Object* expected_thread_peer = gRegistry->Get<mirror::Object*>(
1443 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
1466bool Dbg::MatchField(JDWP::RefTypeId expected_type_id, JDWP::FieldId expected_field_id,
Mathieu Chartierc7853442015-03-27 14:35:38 -07001467 ArtField* event_field) {
1468 ArtField* expected_field = FromFieldId(expected_field_id);
Sebastien Hertz6995c602014-09-09 12:10:13 +02001469 if (expected_field != event_field) {
1470 return false;
1471 }
1472 return Dbg::MatchType(event_field->GetDeclaringClass(), expected_type_id);
1473}
1474
1475bool Dbg::MatchInstance(JDWP::ObjectId expected_instance_id, mirror::Object* event_instance) {
1476 JDWP::JdwpError error;
1477 mirror::Object* modifier_instance = gRegistry->Get<mirror::Object*>(expected_instance_id, &error);
1478 return modifier_instance == event_instance;
1479}
1480
Mathieu Chartier90443472015-07-16 20:32:27 -07001481void Dbg::SetJdwpLocation(JDWP::JdwpLocation* location, ArtMethod* m, uint32_t dex_pc) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001482 if (m == nullptr) {
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001483 memset(location, 0, sizeof(*location));
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001484 } else {
Vladimir Markod93e3742018-07-18 10:58:13 +01001485 ObjPtr<mirror::Class> c = m->GetDeclaringClass();
Ian Rogersc0542af2014-09-03 16:16:56 -07001486 location->type_tag = GetTypeTag(c);
1487 location->class_id = gRegistry->AddRefType(c);
Alex Light73376312017-04-06 10:10:51 -07001488 // The RI Seems to return 0 for all obsolete methods. For compatibility we shall do the same.
1489 location->method_id = m->IsObsolete() ? 0 : ToMethodId(m);
Ian Rogersc0542af2014-09-03 16:16:56 -07001490 location->dex_pc = (m->IsNative() || m->IsProxyMethod()) ? static_cast<uint64_t>(-1) : dex_pc;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001491 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08001492}
1493
Ian Rogersc0542af2014-09-03 16:16:56 -07001494std::string Dbg::GetMethodName(JDWP::MethodId method_id) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001495 ArtMethod* m = FromMethodId(method_id);
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001496 if (m == nullptr) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001497 return "null";
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001498 }
Andreas Gampe542451c2016-07-26 09:02:02 -07001499 return m->GetInterfaceMethodIfProxy(kRuntimePointerSize)->GetName();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001500}
1501
Alex Light73376312017-04-06 10:10:51 -07001502bool Dbg::IsMethodObsolete(JDWP::MethodId method_id) {
1503 ArtMethod* m = FromMethodId(method_id);
1504 if (m == nullptr) {
1505 // NB Since we return 0 as MID for obsolete methods we want to default to true here.
1506 return true;
1507 }
1508 return m->IsObsolete();
1509}
1510
Ian Rogersc0542af2014-09-03 16:16:56 -07001511std::string Dbg::GetFieldName(JDWP::FieldId field_id) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001512 ArtField* f = FromFieldId(field_id);
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001513 if (f == nullptr) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001514 return "null";
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001515 }
1516 return f->GetName();
Elliott Hughesa96836a2013-01-17 12:27:49 -08001517}
1518
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001519/*
1520 * Augment the access flags for synthetic methods and fields by setting
1521 * the (as described by the spec) "0xf0000000 bit". Also, strip out any
1522 * flags not specified by the Java programming language.
1523 */
1524static uint32_t MangleAccessFlags(uint32_t accessFlags) {
1525 accessFlags &= kAccJavaFlagsMask;
1526 if ((accessFlags & kAccSynthetic) != 0) {
1527 accessFlags |= 0xf0000000;
1528 }
1529 return accessFlags;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001530}
1531
Elliott Hughesdbb40792011-11-18 17:05:22 -08001532/*
Jeff Haob7cefc72013-11-14 14:51:09 -08001533 * Circularly shifts registers so that arguments come first. Debuggers
1534 * expect slots to begin with arguments, but dex code places them at
1535 * the end.
Elliott Hughesdbb40792011-11-18 17:05:22 -08001536 */
Mathieu Chartiere401d142015-04-22 13:56:20 -07001537static uint16_t MangleSlot(uint16_t slot, ArtMethod* m)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001538 REQUIRES_SHARED(Locks::mutator_lock_) {
David Sehr0225f8e2018-01-31 08:52:24 +00001539 CodeItemDataAccessor accessor(m->DexInstructionData());
Mathieu Chartier808c7a52017-12-15 11:19:33 -08001540 if (!accessor.HasCodeItem()) {
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001541 // We should not get here for a method without code (native, proxy or abstract). Log it and
1542 // return the slot as is since all registers are arguments.
David Sehr709b0702016-10-13 09:12:37 -07001543 LOG(WARNING) << "Trying to mangle slot for method without code " << m->PrettyMethod();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001544 return slot;
1545 }
Mathieu Chartier808c7a52017-12-15 11:19:33 -08001546 uint16_t ins_size = accessor.InsSize();
1547 uint16_t locals_size = accessor.RegistersSize() - ins_size;
Jeff Haob7cefc72013-11-14 14:51:09 -08001548 if (slot >= locals_size) {
1549 return slot - locals_size;
1550 } else {
1551 return slot + ins_size;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001552 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001553}
1554
Sebastien Hertzaef0c912016-08-08 10:20:28 +02001555static size_t GetMethodNumArgRegistersIncludingThis(ArtMethod* method)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001556 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertzaef0c912016-08-08 10:20:28 +02001557 uint32_t num_registers = ArtMethod::NumArgRegisters(method->GetShorty());
1558 if (!method->IsStatic()) {
1559 ++num_registers;
1560 }
1561 return num_registers;
1562}
1563
Jeff Haob7cefc72013-11-14 14:51:09 -08001564/*
1565 * Circularly shifts registers so that arguments come last. Reverts
1566 * slots to dex style argument placement.
1567 */
Mathieu Chartiere401d142015-04-22 13:56:20 -07001568static uint16_t DemangleSlot(uint16_t slot, ArtMethod* m, JDWP::JdwpError* error)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001569 REQUIRES_SHARED(Locks::mutator_lock_) {
David Sehr0225f8e2018-01-31 08:52:24 +00001570 CodeItemDataAccessor accessor(m->DexInstructionData());
Mathieu Chartier808c7a52017-12-15 11:19:33 -08001571 if (!accessor.HasCodeItem()) {
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001572 // We should not get here for a method without code (native, proxy or abstract). Log it and
1573 // return the slot as is since all registers are arguments.
David Sehr709b0702016-10-13 09:12:37 -07001574 LOG(WARNING) << "Trying to demangle slot for method without code "
1575 << m->PrettyMethod();
Sebastien Hertzaef0c912016-08-08 10:20:28 +02001576 uint16_t vreg_count = GetMethodNumArgRegistersIncludingThis(m);
Sebastien Hertzabbabc82015-03-26 08:47:47 +01001577 if (slot < vreg_count) {
1578 *error = JDWP::ERR_NONE;
1579 return slot;
1580 }
Jeff Haob7cefc72013-11-14 14:51:09 -08001581 } else {
Mathieu Chartier808c7a52017-12-15 11:19:33 -08001582 if (slot < accessor.RegistersSize()) {
1583 uint16_t ins_size = accessor.InsSize();
1584 uint16_t locals_size = accessor.RegistersSize() - ins_size;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01001585 *error = JDWP::ERR_NONE;
1586 return (slot < ins_size) ? slot + locals_size : slot - ins_size;
1587 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001588 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01001589
1590 // Slot is invalid in the method.
David Sehr709b0702016-10-13 09:12:37 -07001591 LOG(ERROR) << "Invalid local slot " << slot << " for method " << m->PrettyMethod();
Sebastien Hertzabbabc82015-03-26 08:47:47 +01001592 *error = JDWP::ERR_INVALID_SLOT;
1593 return DexFile::kDexNoIndex16;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001594}
1595
Mathieu Chartier90443472015-07-16 20:32:27 -07001596JDWP::JdwpError Dbg::OutputDeclaredFields(JDWP::RefTypeId class_id, bool with_generic,
1597 JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001598 JDWP::JdwpError error;
Vladimir Marko4617d582019-03-28 13:48:31 +00001599 ObjPtr<mirror::Class> c = DecodeClass(class_id, &error);
Ian Rogersc0542af2014-09-03 16:16:56 -07001600 if (c == nullptr) {
1601 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001602 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001603
1604 size_t instance_field_count = c->NumInstanceFields();
1605 size_t static_field_count = c->NumStaticFields();
1606
1607 expandBufAdd4BE(pReply, instance_field_count + static_field_count);
1608
1609 for (size_t i = 0; i < instance_field_count + static_field_count; ++i) {
Mathieu Chartier90443472015-07-16 20:32:27 -07001610 ArtField* f = (i < instance_field_count) ? c->GetInstanceField(i) :
1611 c->GetStaticField(i - instance_field_count);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001612 expandBufAddFieldId(pReply, ToFieldId(f));
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001613 expandBufAddUtf8String(pReply, f->GetName());
1614 expandBufAddUtf8String(pReply, f->GetTypeDescriptor());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001615 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001616 static const char genericSignature[1] = "";
1617 expandBufAddUtf8String(pReply, genericSignature);
1618 }
1619 expandBufAdd4BE(pReply, MangleAccessFlags(f->GetAccessFlags()));
1620 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001621 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001622}
1623
Elliott Hughes88d63092013-01-09 09:55:54 -08001624JDWP::JdwpError Dbg::OutputDeclaredMethods(JDWP::RefTypeId class_id, bool with_generic,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001625 JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001626 JDWP::JdwpError error;
Vladimir Marko4617d582019-03-28 13:48:31 +00001627 ObjPtr<mirror::Class> c = DecodeClass(class_id, &error);
Ian Rogersc0542af2014-09-03 16:16:56 -07001628 if (c == nullptr) {
1629 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001630 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001631
Alex Light51a64d52015-12-17 13:55:59 -08001632 expandBufAdd4BE(pReply, c->NumMethods());
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001633
Mathieu Chartiere401d142015-04-22 13:56:20 -07001634 auto* cl = Runtime::Current()->GetClassLinker();
1635 auto ptr_size = cl->GetImagePointerSize();
Alex Light51a64d52015-12-17 13:55:59 -08001636 for (ArtMethod& m : c->GetMethods(ptr_size)) {
1637 expandBufAddMethodId(pReply, ToMethodId(&m));
Andreas Gampe542451c2016-07-26 09:02:02 -07001638 expandBufAddUtf8String(pReply, m.GetInterfaceMethodIfProxy(kRuntimePointerSize)->GetName());
1639 expandBufAddUtf8String(
1640 pReply, m.GetInterfaceMethodIfProxy(kRuntimePointerSize)->GetSignature().ToString());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001641 if (with_generic) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001642 const char* generic_signature = "";
1643 expandBufAddUtf8String(pReply, generic_signature);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001644 }
Alex Light51a64d52015-12-17 13:55:59 -08001645 expandBufAdd4BE(pReply, MangleAccessFlags(m.GetAccessFlags()));
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001646 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001647 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001648}
1649
Elliott Hughes88d63092013-01-09 09:55:54 -08001650JDWP::JdwpError Dbg::OutputDeclaredInterfaces(JDWP::RefTypeId class_id, JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001651 JDWP::JdwpError error;
Mathieu Chartierf8322842014-05-16 10:59:25 -07001652 Thread* self = Thread::Current();
Vladimir Marko19a4d372016-12-08 14:41:46 +00001653 ObjPtr<mirror::Class> c = DecodeClass(class_id, &error);
1654 if (c == nullptr) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001655 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001656 }
Mathieu Chartierf8322842014-05-16 10:59:25 -07001657 size_t interface_count = c->NumDirectInterfaces();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001658 expandBufAdd4BE(pReply, interface_count);
1659 for (size_t i = 0; i < interface_count; ++i) {
Vladimir Marko19a4d372016-12-08 14:41:46 +00001660 ObjPtr<mirror::Class> interface = mirror::Class::GetDirectInterface(self, c, i);
1661 DCHECK(interface != nullptr);
1662 expandBufAddRefTypeId(pReply, gRegistry->AddRefType(interface));
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001663 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001664 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001665}
1666
Ian Rogersc0542af2014-09-03 16:16:56 -07001667void Dbg::OutputLineTable(JDWP::RefTypeId, JDWP::MethodId method_id, JDWP::ExpandBuf* pReply) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001668 ArtMethod* m = FromMethodId(method_id);
David Sehr0225f8e2018-01-31 08:52:24 +00001669 CodeItemDebugInfoAccessor accessor(m->DexInstructionDebugInfo());
Elliott Hughes03181a82011-11-17 17:22:21 -08001670 uint64_t start, end;
Mathieu Chartier31f4c9f2017-12-08 15:46:11 -08001671 if (!accessor.HasCodeItem()) {
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001672 DCHECK(m->IsNative() || m->IsProxyMethod());
Elliott Hughes03181a82011-11-17 17:22:21 -08001673 start = -1;
1674 end = -1;
1675 } else {
1676 start = 0;
jeffhao14f0db92012-12-14 17:50:42 -08001677 // Return the index of the last instruction
Mathieu Chartier31f4c9f2017-12-08 15:46:11 -08001678 end = accessor.InsnsSizeInCodeUnits() - 1;
Elliott Hughes03181a82011-11-17 17:22:21 -08001679 }
1680
1681 expandBufAdd8BE(pReply, start);
1682 expandBufAdd8BE(pReply, end);
1683
1684 // Add numLines later
1685 size_t numLinesOffset = expandBufGetLength(pReply);
1686 expandBufAdd4BE(pReply, 0);
1687
Mathieu Chartier3e2e1232018-09-11 12:35:30 -07001688 int numItems = 0;
1689 accessor.DecodeDebugPositionInfo([&](const DexFile::PositionInfo& entry) {
1690 expandBufAdd8BE(pReply, entry.address_);
1691 expandBufAdd4BE(pReply, entry.line_);
1692 numItems++;
1693 return false;
1694 });
Elliott Hughes03181a82011-11-17 17:22:21 -08001695
Mathieu Chartier3e2e1232018-09-11 12:35:30 -07001696 JDWP::Set4BE(expandBufGetBuffer(pReply) + numLinesOffset, numItems);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001697}
1698
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001699void Dbg::OutputVariableTable(JDWP::RefTypeId, JDWP::MethodId method_id, bool with_generic,
1700 JDWP::ExpandBuf* pReply) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001701 ArtMethod* m = FromMethodId(method_id);
David Sehr0225f8e2018-01-31 08:52:24 +00001702 CodeItemDebugInfoAccessor accessor(m->DexInstructionDebugInfo());
Elliott Hughesdbb40792011-11-18 17:05:22 -08001703
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001704 // arg_count considers doubles and longs to take 2 units.
1705 // variable_count considers everything to take 1 unit.
Sebastien Hertzaef0c912016-08-08 10:20:28 +02001706 expandBufAdd4BE(pReply, GetMethodNumArgRegistersIncludingThis(m));
Elliott Hughesdbb40792011-11-18 17:05:22 -08001707
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001708 // We don't know the total number of variables yet, so leave a blank and update it later.
1709 size_t variable_count_offset = expandBufGetLength(pReply);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001710 expandBufAdd4BE(pReply, 0);
1711
Mathieu Chartiere5afbf32018-09-12 17:51:54 -07001712 size_t variable_count = 0;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001713
Mathieu Chartier31f4c9f2017-12-08 15:46:11 -08001714 if (accessor.HasCodeItem()) {
Mathieu Chartiere5afbf32018-09-12 17:51:54 -07001715 accessor.DecodeDebugLocalInfo(m->IsStatic(),
1716 m->GetDexMethodIndex(),
1717 [&](const DexFile::LocalInfo& entry)
1718 REQUIRES_SHARED(Locks::mutator_lock_) {
1719 uint16_t slot = entry.reg_;
1720 VLOG(jdwp) << StringPrintf(" %2zd: %d(%d) '%s' '%s' '%s' actual slot=%d mangled slot=%d",
1721 variable_count,
1722 entry.start_address_,
1723 entry.end_address_ - entry.start_address_,
1724 entry.name_,
1725 entry.descriptor_, entry.signature_,
1726 slot,
1727 MangleSlot(slot, m));
1728
1729 slot = MangleSlot(slot, m);
1730
1731 expandBufAdd8BE(pReply, entry.start_address_);
1732 expandBufAddUtf8String(pReply, entry.name_);
1733 expandBufAddUtf8String(pReply, entry.descriptor_);
1734 if (with_generic) {
1735 expandBufAddUtf8String(pReply, entry.signature_);
1736 }
1737 expandBufAdd4BE(pReply, entry.end_address_- entry.start_address_);
1738 expandBufAdd4BE(pReply, slot);
1739
1740 ++variable_count;
1741 });
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001742 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001743
Mathieu Chartiere5afbf32018-09-12 17:51:54 -07001744 JDWP::Set4BE(expandBufGetBuffer(pReply) + variable_count_offset, variable_count);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001745}
1746
Jeff Hao579b0242013-11-18 13:16:49 -08001747void Dbg::OutputMethodReturnValue(JDWP::MethodId method_id, const JValue* return_value,
1748 JDWP::ExpandBuf* pReply) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001749 ArtMethod* m = FromMethodId(method_id);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001750 JDWP::JdwpTag tag = BasicTagFromDescriptor(m->GetShorty());
Jeff Hao579b0242013-11-18 13:16:49 -08001751 OutputJValue(tag, return_value, pReply);
1752}
1753
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02001754void Dbg::OutputFieldValue(JDWP::FieldId field_id, const JValue* field_value,
1755 JDWP::ExpandBuf* pReply) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001756 ArtField* f = FromFieldId(field_id);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001757 JDWP::JdwpTag tag = BasicTagFromDescriptor(f->GetTypeDescriptor());
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02001758 OutputJValue(tag, field_value, pReply);
1759}
1760
Elliott Hughes9777ba22013-01-17 09:04:19 -08001761JDWP::JdwpError Dbg::GetBytecodes(JDWP::RefTypeId, JDWP::MethodId method_id,
Ian Rogersc0542af2014-09-03 16:16:56 -07001762 std::vector<uint8_t>* bytecodes) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001763 ArtMethod* m = FromMethodId(method_id);
Ian Rogersc0542af2014-09-03 16:16:56 -07001764 if (m == nullptr) {
Elliott Hughes9777ba22013-01-17 09:04:19 -08001765 return JDWP::ERR_INVALID_METHODID;
1766 }
David Sehr0225f8e2018-01-31 08:52:24 +00001767 CodeItemDataAccessor accessor(m->DexInstructionData());
Mathieu Chartier808c7a52017-12-15 11:19:33 -08001768 size_t byte_count = accessor.InsnsSizeInCodeUnits() * 2;
1769 const uint8_t* begin = reinterpret_cast<const uint8_t*>(accessor.Insns());
Elliott Hughes9777ba22013-01-17 09:04:19 -08001770 const uint8_t* end = begin + byte_count;
1771 for (const uint8_t* p = begin; p != end; ++p) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001772 bytecodes->push_back(*p);
Elliott Hughes9777ba22013-01-17 09:04:19 -08001773 }
1774 return JDWP::ERR_NONE;
1775}
1776
Elliott Hughes88d63092013-01-09 09:55:54 -08001777JDWP::JdwpTag Dbg::GetFieldBasicTag(JDWP::FieldId field_id) {
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001778 return BasicTagFromDescriptor(FromFieldId(field_id)->GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001779}
1780
Elliott Hughes88d63092013-01-09 09:55:54 -08001781JDWP::JdwpTag Dbg::GetStaticFieldBasicTag(JDWP::FieldId field_id) {
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001782 return BasicTagFromDescriptor(FromFieldId(field_id)->GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001783}
1784
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001785static JValue GetArtFieldValue(ArtField* f, mirror::Object* o)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001786 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001787 Primitive::Type fieldType = f->GetTypeAsPrimitiveType();
1788 JValue field_value;
1789 switch (fieldType) {
1790 case Primitive::kPrimBoolean:
1791 field_value.SetZ(f->GetBoolean(o));
1792 return field_value;
1793
1794 case Primitive::kPrimByte:
1795 field_value.SetB(f->GetByte(o));
1796 return field_value;
1797
1798 case Primitive::kPrimChar:
1799 field_value.SetC(f->GetChar(o));
1800 return field_value;
1801
1802 case Primitive::kPrimShort:
1803 field_value.SetS(f->GetShort(o));
1804 return field_value;
1805
1806 case Primitive::kPrimInt:
1807 case Primitive::kPrimFloat:
1808 // Int and Float must be treated as 32-bit values in JDWP.
1809 field_value.SetI(f->GetInt(o));
1810 return field_value;
1811
1812 case Primitive::kPrimLong:
1813 case Primitive::kPrimDouble:
1814 // Long and Double must be treated as 64-bit values in JDWP.
1815 field_value.SetJ(f->GetLong(o));
1816 return field_value;
1817
1818 case Primitive::kPrimNot:
Vladimir Markobcf17522018-06-01 13:14:32 +01001819 field_value.SetL(f->GetObject(o));
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001820 return field_value;
1821
1822 case Primitive::kPrimVoid:
1823 LOG(FATAL) << "Attempt to read from field of type 'void'";
1824 UNREACHABLE();
1825 }
1826 LOG(FATAL) << "Attempt to read from field of unknown type";
1827 UNREACHABLE();
1828}
1829
Elliott Hughes88d63092013-01-09 09:55:54 -08001830static JDWP::JdwpError GetFieldValueImpl(JDWP::RefTypeId ref_type_id, JDWP::ObjectId object_id,
1831 JDWP::FieldId field_id, JDWP::ExpandBuf* pReply,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001832 bool is_static)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001833 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001834 JDWP::JdwpError error;
Vladimir Marko4617d582019-03-28 13:48:31 +00001835 ObjPtr<mirror::Class> c = DecodeClass(ref_type_id, &error);
Ian Rogersc0542af2014-09-03 16:16:56 -07001836 if (ref_type_id != 0 && c == nullptr) {
1837 return error;
Elliott Hughes0cf74332012-02-23 23:14:00 -08001838 }
1839
Jeff Haode19a252016-09-14 15:56:35 -07001840 Thread* self = Thread::Current();
1841 StackHandleScope<2> hs(self);
1842 MutableHandle<mirror::Object>
1843 o(hs.NewHandle(Dbg::GetObjectRegistry()->Get<mirror::Object*>(object_id, &error)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08001844 if ((!is_static && o == nullptr) || error != JDWP::ERR_NONE) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001845 return JDWP::ERR_INVALID_OBJECT;
1846 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001847 ArtField* f = FromFieldId(field_id);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001848
Vladimir Marko4617d582019-03-28 13:48:31 +00001849 ObjPtr<mirror::Class> receiver_class = c;
Andreas Gampefa4333d2017-02-14 11:10:34 -08001850 if (receiver_class == nullptr && o != nullptr) {
Elliott Hughes0cf74332012-02-23 23:14:00 -08001851 receiver_class = o->GetClass();
1852 }
Jeff Haode19a252016-09-14 15:56:35 -07001853
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001854 // TODO: should we give up now if receiver_class is null?
Ian Rogersc0542af2014-09-03 16:16:56 -07001855 if (receiver_class != nullptr && !f->GetDeclaringClass()->IsAssignableFrom(receiver_class)) {
David Sehr709b0702016-10-13 09:12:37 -07001856 LOG(INFO) << "ERR_INVALID_FIELDID: " << f->PrettyField() << " "
1857 << receiver_class->PrettyClass();
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001858 return JDWP::ERR_INVALID_FIELDID;
1859 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001860
Jeff Haode19a252016-09-14 15:56:35 -07001861 // Ensure the field's class is initialized.
1862 Handle<mirror::Class> klass(hs.NewHandle(f->GetDeclaringClass()));
1863 if (!Runtime::Current()->GetClassLinker()->EnsureInitialized(self, klass, true, false)) {
David Sehr709b0702016-10-13 09:12:37 -07001864 LOG(WARNING) << "Not able to initialize class for SetValues: "
1865 << mirror::Class::PrettyClass(klass.Get());
Jeff Haode19a252016-09-14 15:56:35 -07001866 }
1867
Elliott Hughes0cf74332012-02-23 23:14:00 -08001868 // The RI only enforces the static/non-static mismatch in one direction.
1869 // TODO: should we change the tests and check both?
1870 if (is_static) {
1871 if (!f->IsStatic()) {
1872 return JDWP::ERR_INVALID_FIELDID;
1873 }
1874 } else {
1875 if (f->IsStatic()) {
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001876 LOG(WARNING) << "Ignoring non-nullptr receiver for ObjectReference.GetValues"
David Sehr709b0702016-10-13 09:12:37 -07001877 << " on static field " << f->PrettyField();
Elliott Hughes0cf74332012-02-23 23:14:00 -08001878 }
1879 }
jeffhao0dfbb7e2012-11-28 15:26:03 -08001880 if (f->IsStatic()) {
Jeff Haode19a252016-09-14 15:56:35 -07001881 o.Assign(f->GetDeclaringClass());
jeffhao0dfbb7e2012-11-28 15:26:03 -08001882 }
Elliott Hughes0cf74332012-02-23 23:14:00 -08001883
Jeff Haode19a252016-09-14 15:56:35 -07001884 JValue field_value(GetArtFieldValue(f, o.Get()));
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001885 JDWP::JdwpTag tag = BasicTagFromDescriptor(f->GetTypeDescriptor());
Jeff Hao579b0242013-11-18 13:16:49 -08001886 Dbg::OutputJValue(tag, &field_value, pReply);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001887 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001888}
1889
Elliott Hughes88d63092013-01-09 09:55:54 -08001890JDWP::JdwpError Dbg::GetFieldValue(JDWP::ObjectId object_id, JDWP::FieldId field_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001891 JDWP::ExpandBuf* pReply) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001892 return GetFieldValueImpl(0, object_id, field_id, pReply, false);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001893}
1894
Ian Rogersc0542af2014-09-03 16:16:56 -07001895JDWP::JdwpError Dbg::GetStaticFieldValue(JDWP::RefTypeId ref_type_id, JDWP::FieldId field_id,
1896 JDWP::ExpandBuf* pReply) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001897 return GetFieldValueImpl(ref_type_id, 0, field_id, pReply, true);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001898}
1899
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001900static JDWP::JdwpError SetArtFieldValue(ArtField* f, mirror::Object* o, uint64_t value, int width)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001901 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001902 Primitive::Type fieldType = f->GetTypeAsPrimitiveType();
1903 // Debugging only happens at runtime so we know we are not running in a transaction.
1904 static constexpr bool kNoTransactionMode = false;
1905 switch (fieldType) {
1906 case Primitive::kPrimBoolean:
1907 CHECK_EQ(width, 1);
1908 f->SetBoolean<kNoTransactionMode>(o, static_cast<uint8_t>(value));
1909 return JDWP::ERR_NONE;
1910
1911 case Primitive::kPrimByte:
1912 CHECK_EQ(width, 1);
1913 f->SetByte<kNoTransactionMode>(o, static_cast<uint8_t>(value));
1914 return JDWP::ERR_NONE;
1915
1916 case Primitive::kPrimChar:
1917 CHECK_EQ(width, 2);
1918 f->SetChar<kNoTransactionMode>(o, static_cast<uint16_t>(value));
1919 return JDWP::ERR_NONE;
1920
1921 case Primitive::kPrimShort:
1922 CHECK_EQ(width, 2);
1923 f->SetShort<kNoTransactionMode>(o, static_cast<int16_t>(value));
1924 return JDWP::ERR_NONE;
1925
1926 case Primitive::kPrimInt:
1927 case Primitive::kPrimFloat:
1928 CHECK_EQ(width, 4);
1929 // Int and Float must be treated as 32-bit values in JDWP.
1930 f->SetInt<kNoTransactionMode>(o, static_cast<int32_t>(value));
1931 return JDWP::ERR_NONE;
1932
1933 case Primitive::kPrimLong:
1934 case Primitive::kPrimDouble:
1935 CHECK_EQ(width, 8);
1936 // Long and Double must be treated as 64-bit values in JDWP.
1937 f->SetLong<kNoTransactionMode>(o, value);
1938 return JDWP::ERR_NONE;
1939
1940 case Primitive::kPrimNot: {
1941 JDWP::JdwpError error;
1942 mirror::Object* v = Dbg::GetObjectRegistry()->Get<mirror::Object*>(value, &error);
1943 if (error != JDWP::ERR_NONE) {
1944 return JDWP::ERR_INVALID_OBJECT;
1945 }
1946 if (v != nullptr) {
Mathieu Chartier3398c782016-09-30 10:27:43 -07001947 ObjPtr<mirror::Class> field_type;
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001948 {
1949 StackHandleScope<2> hs(Thread::Current());
1950 HandleWrapper<mirror::Object> h_v(hs.NewHandleWrapper(&v));
1951 HandleWrapper<mirror::Object> h_o(hs.NewHandleWrapper(&o));
Vladimir Marko4098a7a2017-11-06 16:00:51 +00001952 field_type = f->ResolveType();
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001953 }
1954 if (!field_type->IsAssignableFrom(v->GetClass())) {
1955 return JDWP::ERR_INVALID_OBJECT;
1956 }
1957 }
1958 f->SetObject<kNoTransactionMode>(o, v);
1959 return JDWP::ERR_NONE;
1960 }
1961
1962 case Primitive::kPrimVoid:
1963 LOG(FATAL) << "Attempt to write to field of type 'void'";
1964 UNREACHABLE();
1965 }
1966 LOG(FATAL) << "Attempt to write to field of unknown type";
1967 UNREACHABLE();
1968}
1969
Elliott Hughes88d63092013-01-09 09:55:54 -08001970static JDWP::JdwpError SetFieldValueImpl(JDWP::ObjectId object_id, JDWP::FieldId field_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001971 uint64_t value, int width, bool is_static)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001972 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001973 JDWP::JdwpError error;
Jeff Haode19a252016-09-14 15:56:35 -07001974 Thread* self = Thread::Current();
1975 StackHandleScope<2> hs(self);
1976 MutableHandle<mirror::Object>
1977 o(hs.NewHandle(Dbg::GetObjectRegistry()->Get<mirror::Object*>(object_id, &error)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08001978 if ((!is_static && o == nullptr) || error != JDWP::ERR_NONE) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001979 return JDWP::ERR_INVALID_OBJECT;
1980 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001981 ArtField* f = FromFieldId(field_id);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001982
Jeff Haode19a252016-09-14 15:56:35 -07001983 // Ensure the field's class is initialized.
1984 Handle<mirror::Class> klass(hs.NewHandle(f->GetDeclaringClass()));
1985 if (!Runtime::Current()->GetClassLinker()->EnsureInitialized(self, klass, true, false)) {
David Sehr709b0702016-10-13 09:12:37 -07001986 LOG(WARNING) << "Not able to initialize class for SetValues: "
1987 << mirror::Class::PrettyClass(klass.Get());
Jeff Haode19a252016-09-14 15:56:35 -07001988 }
1989
Elliott Hughes0cf74332012-02-23 23:14:00 -08001990 // The RI only enforces the static/non-static mismatch in one direction.
1991 // TODO: should we change the tests and check both?
1992 if (is_static) {
1993 if (!f->IsStatic()) {
1994 return JDWP::ERR_INVALID_FIELDID;
1995 }
1996 } else {
1997 if (f->IsStatic()) {
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001998 LOG(WARNING) << "Ignoring non-nullptr receiver for ObjectReference.SetValues"
David Sehr709b0702016-10-13 09:12:37 -07001999 << " on static field " << f->PrettyField();
Elliott Hughes0cf74332012-02-23 23:14:00 -08002000 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002001 }
jeffhao0dfbb7e2012-11-28 15:26:03 -08002002 if (f->IsStatic()) {
Jeff Haode19a252016-09-14 15:56:35 -07002003 o.Assign(f->GetDeclaringClass());
jeffhao0dfbb7e2012-11-28 15:26:03 -08002004 }
Jeff Haode19a252016-09-14 15:56:35 -07002005 return SetArtFieldValue(f, o.Get(), value, width);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002006}
2007
Elliott Hughes88d63092013-01-09 09:55:54 -08002008JDWP::JdwpError Dbg::SetFieldValue(JDWP::ObjectId object_id, JDWP::FieldId field_id, uint64_t value,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002009 int width) {
Elliott Hughes88d63092013-01-09 09:55:54 -08002010 return SetFieldValueImpl(object_id, field_id, value, width, false);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002011}
2012
Elliott Hughes88d63092013-01-09 09:55:54 -08002013JDWP::JdwpError Dbg::SetStaticFieldValue(JDWP::FieldId field_id, uint64_t value, int width) {
2014 return SetFieldValueImpl(0, field_id, value, width, true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002015}
2016
Sebastien Hertzb0b0b492014-09-15 11:27:27 +02002017JDWP::JdwpError Dbg::StringToUtf8(JDWP::ObjectId string_id, std::string* str) {
Ian Rogersc0542af2014-09-03 16:16:56 -07002018 JDWP::JdwpError error;
Sebastien Hertzb0b0b492014-09-15 11:27:27 +02002019 mirror::Object* obj = gRegistry->Get<mirror::Object*>(string_id, &error);
2020 if (error != JDWP::ERR_NONE) {
2021 return error;
2022 }
2023 if (obj == nullptr) {
2024 return JDWP::ERR_INVALID_OBJECT;
2025 }
2026 {
2027 ScopedObjectAccessUnchecked soa(Thread::Current());
Mathieu Chartier0795f232016-09-27 18:43:30 -07002028 ObjPtr<mirror::Class> java_lang_String =
2029 soa.Decode<mirror::Class>(WellKnownClasses::java_lang_String);
Sebastien Hertzb0b0b492014-09-15 11:27:27 +02002030 if (!java_lang_String->IsAssignableFrom(obj->GetClass())) {
2031 // This isn't a string.
2032 return JDWP::ERR_INVALID_STRING;
2033 }
2034 }
2035 *str = obj->AsString()->ToModifiedUtf8();
2036 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002037}
2038
Jeff Hao579b0242013-11-18 13:16:49 -08002039void Dbg::OutputJValue(JDWP::JdwpTag tag, const JValue* return_value, JDWP::ExpandBuf* pReply) {
2040 if (IsPrimitiveTag(tag)) {
2041 expandBufAdd1(pReply, tag);
2042 if (tag == JDWP::JT_BOOLEAN || tag == JDWP::JT_BYTE) {
2043 expandBufAdd1(pReply, return_value->GetI());
2044 } else if (tag == JDWP::JT_CHAR || tag == JDWP::JT_SHORT) {
2045 expandBufAdd2BE(pReply, return_value->GetI());
2046 } else if (tag == JDWP::JT_FLOAT || tag == JDWP::JT_INT) {
2047 expandBufAdd4BE(pReply, return_value->GetI());
2048 } else if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
2049 expandBufAdd8BE(pReply, return_value->GetJ());
2050 } else {
2051 CHECK_EQ(tag, JDWP::JT_VOID);
2052 }
2053 } else {
Ian Rogers98379392014-02-24 16:53:16 -08002054 ScopedObjectAccessUnchecked soa(Thread::Current());
Jeff Hao579b0242013-11-18 13:16:49 -08002055 mirror::Object* value = return_value->GetL();
Ian Rogers98379392014-02-24 16:53:16 -08002056 expandBufAdd1(pReply, TagFromObject(soa, value));
Jeff Hao579b0242013-11-18 13:16:49 -08002057 expandBufAddObjectId(pReply, gRegistry->Add(value));
2058 }
2059}
2060
Ian Rogersc0542af2014-09-03 16:16:56 -07002061JDWP::JdwpError Dbg::GetThreadName(JDWP::ObjectId thread_id, std::string* name) {
jeffhaoa77f0f62012-12-05 17:19:31 -08002062 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002063 JDWP::JdwpError error;
Roland Levillain4b8f1ec2015-08-26 18:34:03 +01002064 DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002065 if (error != JDWP::ERR_NONE && error != JDWP::ERR_THREAD_NOT_ALIVE) {
2066 return error;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08002067 }
Elliott Hughes221229c2013-01-08 18:17:50 -08002068
2069 // We still need to report the zombie threads' names, so we can't just call Thread::GetThreadName.
Ian Rogersc0542af2014-09-03 16:16:56 -07002070 mirror::Object* thread_object = gRegistry->Get<mirror::Object*>(thread_id, &error);
2071 CHECK(thread_object != nullptr) << error;
Mathieu Chartierc7853442015-03-27 14:35:38 -07002072 ArtField* java_lang_Thread_name_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08002073 jni::DecodeArtField(WellKnownClasses::java_lang_Thread_name);
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07002074 ObjPtr<mirror::String> s(java_lang_Thread_name_field->GetObject(thread_object)->AsString());
Ian Rogersc0542af2014-09-03 16:16:56 -07002075 if (s != nullptr) {
2076 *name = s->ToModifiedUtf8();
Elliott Hughes221229c2013-01-08 18:17:50 -08002077 }
2078 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002079}
2080
Elliott Hughes221229c2013-01-08 18:17:50 -08002081JDWP::JdwpError Dbg::GetThreadGroup(JDWP::ObjectId thread_id, JDWP::ExpandBuf* pReply) {
Sebastien Hertza06430c2014-09-15 19:21:30 +02002082 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002083 JDWP::JdwpError error;
2084 mirror::Object* thread_object = gRegistry->Get<mirror::Object*>(thread_id, &error);
2085 if (error != JDWP::ERR_NONE) {
Elliott Hughes2435a572012-02-17 16:07:41 -08002086 return JDWP::ERR_INVALID_OBJECT;
2087 }
Mathieu Chartier268764d2016-09-13 12:09:38 -07002088 ScopedAssertNoThreadSuspension ants("Debugger: GetThreadGroup");
Elliott Hughes2435a572012-02-17 16:07:41 -08002089 // Okay, so it's an object, but is it actually a thread?
Roland Levillain4b8f1ec2015-08-26 18:34:03 +01002090 DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002091 if (error == JDWP::ERR_THREAD_NOT_ALIVE) {
2092 // Zombie threads are in the null group.
2093 expandBufAddObjectId(pReply, JDWP::ObjectId(0));
Sebastien Hertz52d131d2014-03-13 16:17:40 +01002094 error = JDWP::ERR_NONE;
2095 } else if (error == JDWP::ERR_NONE) {
Mathieu Chartier0795f232016-09-27 18:43:30 -07002096 ObjPtr<mirror::Class> c = soa.Decode<mirror::Class>(WellKnownClasses::java_lang_Thread);
Sebastien Hertz52d131d2014-03-13 16:17:40 +01002097 CHECK(c != nullptr);
Andreas Gampe08883de2016-11-08 13:20:52 -08002098 ArtField* f = jni::DecodeArtField(WellKnownClasses::java_lang_Thread_group);
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07002099 CHECK(f != nullptr);
Mathieu Chartier3398c782016-09-30 10:27:43 -07002100 ObjPtr<mirror::Object> group = f->GetObject(thread_object);
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07002101 CHECK(group != nullptr);
Sebastien Hertz52d131d2014-03-13 16:17:40 +01002102 JDWP::ObjectId thread_group_id = gRegistry->Add(group);
2103 expandBufAddObjectId(pReply, thread_group_id);
Elliott Hughes221229c2013-01-08 18:17:50 -08002104 }
Sebastien Hertz52d131d2014-03-13 16:17:40 +01002105 return error;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002106}
2107
Sebastien Hertza06430c2014-09-15 19:21:30 +02002108static mirror::Object* DecodeThreadGroup(ScopedObjectAccessUnchecked& soa,
2109 JDWP::ObjectId thread_group_id, JDWP::JdwpError* error)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002110 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz6995c602014-09-09 12:10:13 +02002111 mirror::Object* thread_group = Dbg::GetObjectRegistry()->Get<mirror::Object*>(thread_group_id,
2112 error);
Sebastien Hertza06430c2014-09-15 19:21:30 +02002113 if (*error != JDWP::ERR_NONE) {
2114 return nullptr;
2115 }
2116 if (thread_group == nullptr) {
2117 *error = JDWP::ERR_INVALID_OBJECT;
2118 return nullptr;
2119 }
Mathieu Chartier0795f232016-09-27 18:43:30 -07002120 ObjPtr<mirror::Class> c =
2121 soa.Decode<mirror::Class>(WellKnownClasses::java_lang_ThreadGroup);
Ian Rogers98379392014-02-24 16:53:16 -08002122 CHECK(c != nullptr);
Sebastien Hertza06430c2014-09-15 19:21:30 +02002123 if (!c->IsAssignableFrom(thread_group->GetClass())) {
2124 // This is not a java.lang.ThreadGroup.
2125 *error = JDWP::ERR_INVALID_THREAD_GROUP;
2126 return nullptr;
2127 }
2128 *error = JDWP::ERR_NONE;
2129 return thread_group;
2130}
2131
2132JDWP::JdwpError Dbg::GetThreadGroupName(JDWP::ObjectId thread_group_id, JDWP::ExpandBuf* pReply) {
2133 ScopedObjectAccessUnchecked soa(Thread::Current());
2134 JDWP::JdwpError error;
2135 mirror::Object* thread_group = DecodeThreadGroup(soa, thread_group_id, &error);
2136 if (error != JDWP::ERR_NONE) {
2137 return error;
2138 }
Mathieu Chartier268764d2016-09-13 12:09:38 -07002139 ScopedAssertNoThreadSuspension ants("Debugger: GetThreadGroupName");
Andreas Gampe08883de2016-11-08 13:20:52 -08002140 ArtField* f = jni::DecodeArtField(WellKnownClasses::java_lang_ThreadGroup_name);
Ian Rogersc0542af2014-09-03 16:16:56 -07002141 CHECK(f != nullptr);
Mathieu Chartier3398c782016-09-30 10:27:43 -07002142 ObjPtr<mirror::String> s = f->GetObject(thread_group)->AsString();
Sebastien Hertza06430c2014-09-15 19:21:30 +02002143
2144 std::string thread_group_name(s->ToModifiedUtf8());
2145 expandBufAddUtf8String(pReply, thread_group_name);
2146 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002147}
2148
Sebastien Hertza06430c2014-09-15 19:21:30 +02002149JDWP::JdwpError Dbg::GetThreadGroupParent(JDWP::ObjectId thread_group_id, JDWP::ExpandBuf* pReply) {
Ian Rogers98379392014-02-24 16:53:16 -08002150 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002151 JDWP::JdwpError error;
Sebastien Hertza06430c2014-09-15 19:21:30 +02002152 mirror::Object* thread_group = DecodeThreadGroup(soa, thread_group_id, &error);
2153 if (error != JDWP::ERR_NONE) {
2154 return error;
2155 }
Mathieu Chartier3398c782016-09-30 10:27:43 -07002156 ObjPtr<mirror::Object> parent;
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07002157 {
Mathieu Chartier268764d2016-09-13 12:09:38 -07002158 ScopedAssertNoThreadSuspension ants("Debugger: GetThreadGroupParent");
Andreas Gampe08883de2016-11-08 13:20:52 -08002159 ArtField* f = jni::DecodeArtField(WellKnownClasses::java_lang_ThreadGroup_parent);
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07002160 CHECK(f != nullptr);
2161 parent = f->GetObject(thread_group);
2162 }
Sebastien Hertza06430c2014-09-15 19:21:30 +02002163 JDWP::ObjectId parent_group_id = gRegistry->Add(parent);
2164 expandBufAddObjectId(pReply, parent_group_id);
2165 return JDWP::ERR_NONE;
2166}
2167
Andreas Gampe08883de2016-11-08 13:20:52 -08002168static void GetChildThreadGroups(mirror::Object* thread_group,
Sebastien Hertza06430c2014-09-15 19:21:30 +02002169 std::vector<JDWP::ObjectId>* child_thread_group_ids)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002170 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertza06430c2014-09-15 19:21:30 +02002171 CHECK(thread_group != nullptr);
2172
Przemyslaw Szczepaniak464595f2015-11-24 11:59:59 +00002173 // Get the int "ngroups" count of this thread group...
Andreas Gampe08883de2016-11-08 13:20:52 -08002174 ArtField* ngroups_field = jni::DecodeArtField(WellKnownClasses::java_lang_ThreadGroup_ngroups);
Przemyslaw Szczepaniak464595f2015-11-24 11:59:59 +00002175 CHECK(ngroups_field != nullptr);
2176 const int32_t size = ngroups_field->GetInt(thread_group);
2177 if (size == 0) {
2178 return;
Sebastien Hertze49e1952014-10-13 11:27:13 +02002179 }
Sebastien Hertza06430c2014-09-15 19:21:30 +02002180
Przemyslaw Szczepaniak464595f2015-11-24 11:59:59 +00002181 // Get the ThreadGroup[] "groups" out of this thread group...
Andreas Gampe08883de2016-11-08 13:20:52 -08002182 ArtField* groups_field = jni::DecodeArtField(WellKnownClasses::java_lang_ThreadGroup_groups);
Mathieu Chartier3398c782016-09-30 10:27:43 -07002183 ObjPtr<mirror::Object> groups_array = groups_field->GetObject(thread_group);
Przemyslaw Szczepaniak464595f2015-11-24 11:59:59 +00002184
2185 CHECK(groups_array != nullptr);
2186 CHECK(groups_array->IsObjectArray());
2187
Mathieu Chartier3398c782016-09-30 10:27:43 -07002188 ObjPtr<mirror::ObjectArray<mirror::Object>> groups_array_as_array =
Przemyslaw Szczepaniak464595f2015-11-24 11:59:59 +00002189 groups_array->AsObjectArray<mirror::Object>();
Sebastien Hertza06430c2014-09-15 19:21:30 +02002190
2191 // Copy the first 'size' elements out of the array into the result.
Sebastien Hertz6995c602014-09-09 12:10:13 +02002192 ObjectRegistry* registry = Dbg::GetObjectRegistry();
Sebastien Hertza06430c2014-09-15 19:21:30 +02002193 for (int32_t i = 0; i < size; ++i) {
Przemyslaw Szczepaniak464595f2015-11-24 11:59:59 +00002194 child_thread_group_ids->push_back(registry->Add(groups_array_as_array->Get(i)));
Sebastien Hertza06430c2014-09-15 19:21:30 +02002195 }
2196}
2197
2198JDWP::JdwpError Dbg::GetThreadGroupChildren(JDWP::ObjectId thread_group_id,
2199 JDWP::ExpandBuf* pReply) {
2200 ScopedObjectAccessUnchecked soa(Thread::Current());
2201 JDWP::JdwpError error;
2202 mirror::Object* thread_group = DecodeThreadGroup(soa, thread_group_id, &error);
2203 if (error != JDWP::ERR_NONE) {
2204 return error;
2205 }
2206
2207 // Add child threads.
2208 {
2209 std::vector<JDWP::ObjectId> child_thread_ids;
2210 GetThreads(thread_group, &child_thread_ids);
2211 expandBufAdd4BE(pReply, child_thread_ids.size());
2212 for (JDWP::ObjectId child_thread_id : child_thread_ids) {
2213 expandBufAddObjectId(pReply, child_thread_id);
2214 }
2215 }
2216
2217 // Add child thread groups.
2218 {
2219 std::vector<JDWP::ObjectId> child_thread_groups_ids;
Andreas Gampe08883de2016-11-08 13:20:52 -08002220 GetChildThreadGroups(thread_group, &child_thread_groups_ids);
Sebastien Hertza06430c2014-09-15 19:21:30 +02002221 expandBufAdd4BE(pReply, child_thread_groups_ids.size());
2222 for (JDWP::ObjectId child_thread_group_id : child_thread_groups_ids) {
2223 expandBufAddObjectId(pReply, child_thread_group_id);
2224 }
2225 }
2226
2227 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002228}
2229
2230JDWP::ObjectId Dbg::GetSystemThreadGroupId() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002231 ScopedObjectAccessUnchecked soa(Thread::Current());
Andreas Gampe08883de2016-11-08 13:20:52 -08002232 ArtField* f = jni::DecodeArtField(WellKnownClasses::java_lang_ThreadGroup_systemThreadGroup);
Mathieu Chartier3398c782016-09-30 10:27:43 -07002233 ObjPtr<mirror::Object> group = f->GetObject(f->GetDeclaringClass());
Ian Rogers365c1022012-06-22 15:05:28 -07002234 return gRegistry->Add(group);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002235}
2236
Jeff Hao920af3e2013-08-28 15:46:38 -07002237JDWP::JdwpThreadStatus Dbg::ToJdwpThreadStatus(ThreadState state) {
2238 switch (state) {
2239 case kBlocked:
2240 return JDWP::TS_MONITOR;
2241 case kNative:
2242 case kRunnable:
2243 case kSuspended:
2244 return JDWP::TS_RUNNING;
2245 case kSleeping:
2246 return JDWP::TS_SLEEPING;
2247 case kStarting:
2248 case kTerminated:
2249 return JDWP::TS_ZOMBIE;
2250 case kTimedWaiting:
Alex Light77fee872017-09-05 14:51:49 -07002251 case kWaitingForTaskProcessor:
2252 case kWaitingForLockInflation:
Sebastien Hertzbae182c2013-12-17 10:42:03 +01002253 case kWaitingForCheckPointsToRun:
Jeff Hao920af3e2013-08-28 15:46:38 -07002254 case kWaitingForDebuggerSend:
2255 case kWaitingForDebuggerSuspension:
2256 case kWaitingForDebuggerToAttach:
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002257 case kWaitingForDeoptimization:
Jeff Hao920af3e2013-08-28 15:46:38 -07002258 case kWaitingForGcToComplete:
Mathieu Chartierb43390c2015-05-12 10:47:11 -07002259 case kWaitingForGetObjectsAllocated:
Jeff Hao920af3e2013-08-28 15:46:38 -07002260 case kWaitingForJniOnLoad:
Sebastien Hertzbae182c2013-12-17 10:42:03 +01002261 case kWaitingForMethodTracingStart:
Jeff Hao920af3e2013-08-28 15:46:38 -07002262 case kWaitingForSignalCatcherOutput:
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -08002263 case kWaitingForVisitObjects:
Jeff Hao920af3e2013-08-28 15:46:38 -07002264 case kWaitingInMainDebuggerLoop:
2265 case kWaitingInMainSignalCatcherLoop:
2266 case kWaitingPerformingGc:
Mathieu Chartier90ef3db2015-08-04 15:19:41 -07002267 case kWaitingWeakGcRootRead:
Hiroshi Yamauchi76f55b02015-08-21 16:10:39 -07002268 case kWaitingForGcThreadFlip:
Koji Fukui34857b52019-03-20 19:13:00 +09002269 case kNativeForAbort:
Jeff Hao920af3e2013-08-28 15:46:38 -07002270 case kWaiting:
2271 return JDWP::TS_WAIT;
2272 // Don't add a 'default' here so the compiler can spot incompatible enum changes.
2273 }
2274 LOG(FATAL) << "Unknown thread state: " << state;
Elliott Hughesc1896c92018-11-29 11:33:18 -08002275 UNREACHABLE();
Jeff Hao920af3e2013-08-28 15:46:38 -07002276}
2277
Sebastien Hertz52d131d2014-03-13 16:17:40 +01002278JDWP::JdwpError Dbg::GetThreadStatus(JDWP::ObjectId thread_id, JDWP::JdwpThreadStatus* pThreadStatus,
2279 JDWP::JdwpSuspendStatus* pSuspendStatus) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002280 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes499c5132011-11-17 14:55:11 -08002281
Elliott Hughes9e0c1752013-01-09 14:02:58 -08002282 *pSuspendStatus = JDWP::SUSPEND_STATUS_NOT_SUSPENDED;
2283
Ian Rogersc0542af2014-09-03 16:16:56 -07002284 JDWP::JdwpError error;
2285 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002286 if (error != JDWP::ERR_NONE) {
2287 if (error == JDWP::ERR_THREAD_NOT_ALIVE) {
2288 *pThreadStatus = JDWP::TS_ZOMBIE;
Elliott Hughes221229c2013-01-08 18:17:50 -08002289 return JDWP::ERR_NONE;
2290 }
2291 return error;
Elliott Hughes499c5132011-11-17 14:55:11 -08002292 }
2293
Elliott Hughes9e0c1752013-01-09 14:02:58 -08002294 if (IsSuspendedForDebugger(soa, thread)) {
2295 *pSuspendStatus = JDWP::SUSPEND_STATUS_SUSPENDED;
Elliott Hughes499c5132011-11-17 14:55:11 -08002296 }
2297
Jeff Hao920af3e2013-08-28 15:46:38 -07002298 *pThreadStatus = ToJdwpThreadStatus(thread->GetState());
Elliott Hughes221229c2013-01-08 18:17:50 -08002299 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002300}
2301
Elliott Hughes221229c2013-01-08 18:17:50 -08002302JDWP::JdwpError Dbg::GetThreadDebugSuspendCount(JDWP::ObjectId thread_id, JDWP::ExpandBuf* pReply) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002303 ScopedObjectAccess soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002304 JDWP::JdwpError error;
2305 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002306 if (error != JDWP::ERR_NONE) {
2307 return error;
Elliott Hughes2435a572012-02-17 16:07:41 -08002308 }
Ian Rogers50b35e22012-10-04 10:09:15 -07002309 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002310 expandBufAdd4BE(pReply, thread->GetDebugSuspendCount());
Elliott Hughes2435a572012-02-17 16:07:41 -08002311 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002312}
2313
Elliott Hughesf9501702013-01-11 11:22:27 -08002314JDWP::JdwpError Dbg::Interrupt(JDWP::ObjectId thread_id) {
2315 ScopedObjectAccess soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002316 JDWP::JdwpError error;
2317 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughesf9501702013-01-11 11:22:27 -08002318 if (error != JDWP::ERR_NONE) {
2319 return error;
2320 }
Ian Rogersdd7624d2014-03-14 17:43:00 -07002321 thread->Interrupt(soa.Self());
Elliott Hughesf9501702013-01-11 11:22:27 -08002322 return JDWP::ERR_NONE;
2323}
2324
Andreas Gampe08883de2016-11-08 13:20:52 -08002325static bool IsInDesiredThreadGroup(mirror::Object* desired_thread_group, mirror::Object* peer)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002326 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz070f7322014-09-09 12:08:49 +02002327 // Do we want threads from all thread groups?
2328 if (desired_thread_group == nullptr) {
2329 return true;
2330 }
Andreas Gampe08883de2016-11-08 13:20:52 -08002331 ArtField* thread_group_field = jni::DecodeArtField(WellKnownClasses::java_lang_Thread_group);
Sebastien Hertz070f7322014-09-09 12:08:49 +02002332 DCHECK(thread_group_field != nullptr);
Mathieu Chartier3398c782016-09-30 10:27:43 -07002333 ObjPtr<mirror::Object> group = thread_group_field->GetObject(peer);
Sebastien Hertz070f7322014-09-09 12:08:49 +02002334 return (group == desired_thread_group);
2335}
2336
Sebastien Hertza06430c2014-09-15 19:21:30 +02002337void Dbg::GetThreads(mirror::Object* thread_group, std::vector<JDWP::ObjectId>* thread_ids) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002338 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz070f7322014-09-09 12:08:49 +02002339 std::list<Thread*> all_threads_list;
2340 {
2341 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
2342 all_threads_list = Runtime::Current()->GetThreadList()->GetList();
2343 }
2344 for (Thread* t : all_threads_list) {
2345 if (t == Dbg::GetDebugThread()) {
2346 // Skip the JDWP thread. Some debuggers get bent out of shape when they can't suspend and
2347 // query all threads, so it's easier if we just don't tell them about this thread.
2348 continue;
2349 }
2350 if (t->IsStillStarting()) {
2351 // This thread is being started (and has been registered in the thread list). However, it is
2352 // not completely started yet so we must ignore it.
2353 continue;
2354 }
Nicolas Geoffraycafa0812017-02-15 18:27:34 +00002355 mirror::Object* peer = t->GetPeerFromOtherThread();
Sebastien Hertz070f7322014-09-09 12:08:49 +02002356 if (peer == nullptr) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002357 // 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 +02002358 // this thread yet.
2359 // TODO: if we identified threads to the debugger by their Thread*
2360 // rather than their peer's mirror::Object*, we could fix this.
2361 // Doing so might help us report ZOMBIE threads too.
2362 continue;
2363 }
Andreas Gampe08883de2016-11-08 13:20:52 -08002364 if (IsInDesiredThreadGroup(thread_group, peer)) {
Sebastien Hertz070f7322014-09-09 12:08:49 +02002365 thread_ids->push_back(gRegistry->Add(peer));
2366 }
2367 }
Elliott Hughescaf76542012-06-28 16:08:22 -07002368}
Elliott Hughesa2155262011-11-16 16:26:58 -08002369
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002370static int GetStackDepth(Thread* thread) REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampec7d878d2018-11-19 18:42:06 +00002371 size_t depth = 0u;
2372 StackVisitor::WalkStack(
2373 [&depth](const StackVisitor* visitor) REQUIRES_SHARED(Locks::mutator_lock_) {
2374 if (!visitor->GetMethod()->IsRuntimeMethod()) {
2375 ++depth;
2376 }
2377 return true;
2378 },
2379 thread,
2380 /* context= */ nullptr,
2381 StackVisitor::StackWalkKind::kIncludeInlinedFrames);
2382 return depth;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002383}
2384
Ian Rogersc0542af2014-09-03 16:16:56 -07002385JDWP::JdwpError Dbg::GetThreadFrameCount(JDWP::ObjectId thread_id, size_t* result) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002386 ScopedObjectAccess soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002387 JDWP::JdwpError error;
2388 *result = 0;
2389 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002390 if (error != JDWP::ERR_NONE) {
2391 return error;
2392 }
Elliott Hughesf15f4a02013-01-09 10:09:38 -08002393 if (!IsSuspendedForDebugger(soa, thread)) {
2394 return JDWP::ERR_THREAD_NOT_SUSPENDED;
2395 }
Ian Rogersc0542af2014-09-03 16:16:56 -07002396 *result = GetStackDepth(thread);
Elliott Hughes221229c2013-01-08 18:17:50 -08002397 return JDWP::ERR_NONE;
Elliott Hughes86964332012-02-15 19:37:42 -08002398}
2399
Andreas Gampec7d878d2018-11-19 18:42:06 +00002400JDWP::JdwpError Dbg::GetThreadFrames(JDWP::ObjectId thread_id,
2401 const size_t start_frame,
2402 const size_t frame_count,
2403 JDWP::ExpandBuf* buf) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002404 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002405 JDWP::JdwpError error;
2406 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002407 if (error != JDWP::ERR_NONE) {
2408 return error;
2409 }
Elliott Hughesf15f4a02013-01-09 10:09:38 -08002410 if (!IsSuspendedForDebugger(soa, thread)) {
2411 return JDWP::ERR_THREAD_NOT_SUSPENDED;
2412 }
Andreas Gampec7d878d2018-11-19 18:42:06 +00002413
2414 expandBufAdd4BE(buf, frame_count);
2415
2416 size_t depth = 0u;
2417 StackVisitor::WalkStack(
2418 [&](StackVisitor* visitor) REQUIRES_SHARED(Locks::mutator_lock_) {
2419 if (visitor->GetMethod()->IsRuntimeMethod()) {
2420 return true; // The debugger can't do anything useful with a frame that has no Method*.
2421 }
2422 if (depth >= start_frame + frame_count) {
2423 return false;
2424 }
2425 if (depth >= start_frame) {
2426 JDWP::FrameId frame_id(visitor->GetFrameId());
2427 JDWP::JdwpLocation location;
2428 SetJdwpLocation(&location, visitor->GetMethod(), visitor->GetDexPc());
2429 VLOG(jdwp)
2430 << StringPrintf(" Frame %3zd: id=%3" PRIu64 " ", depth, frame_id) << location;
2431 expandBufAdd8BE(buf, frame_id);
2432 expandBufAddLocation(buf, location);
2433 }
2434 ++depth;
2435 return true;
2436 },
2437 thread,
2438 /* context= */ nullptr,
2439 StackVisitor::StackWalkKind::kIncludeInlinedFrames);
2440
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002441 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002442}
2443
2444JDWP::ObjectId Dbg::GetThreadSelfId() {
Sebastien Hertz6995c602014-09-09 12:10:13 +02002445 return GetThreadId(Thread::Current());
2446}
2447
2448JDWP::ObjectId Dbg::GetThreadId(Thread* thread) {
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07002449 ScopedObjectAccessUnchecked soa(Thread::Current());
Nicolas Geoffraycafa0812017-02-15 18:27:34 +00002450 return gRegistry->Add(thread->GetPeerFromOtherThread());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002451}
2452
Elliott Hughes475fc232011-10-25 15:00:35 -07002453void Dbg::SuspendVM() {
Hiroshi Yamauchi8f95cf32016-04-19 11:14:06 -07002454 // Avoid a deadlock between GC and debugger where GC gets suspended during GC. b/25800335.
2455 gc::ScopedGCCriticalSection gcs(Thread::Current(),
2456 gc::kGcCauseDebugger,
2457 gc::kCollectorTypeDebugger);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002458 Runtime::Current()->GetThreadList()->SuspendAllForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002459}
2460
2461void Dbg::ResumeVM() {
Sebastien Hertz253fa552014-10-14 17:27:15 +02002462 Runtime::Current()->GetThreadList()->ResumeAllForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002463}
2464
Elliott Hughes221229c2013-01-08 18:17:50 -08002465JDWP::JdwpError Dbg::SuspendThread(JDWP::ObjectId thread_id, bool request_suspension) {
Ian Rogersf3d874c2014-07-17 18:52:42 -07002466 Thread* self = Thread::Current();
Ian Rogersc0542af2014-09-03 16:16:56 -07002467 ScopedLocalRef<jobject> peer(self->GetJniEnv(), nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002468 {
Ian Rogersf3d874c2014-07-17 18:52:42 -07002469 ScopedObjectAccess soa(self);
Ian Rogersc0542af2014-09-03 16:16:56 -07002470 JDWP::JdwpError error;
2471 peer.reset(soa.AddLocalReference<jobject>(gRegistry->Get<mirror::Object*>(thread_id, &error)));
Elliott Hughes4e235312011-12-02 11:34:15 -08002472 }
Ian Rogersc0542af2014-09-03 16:16:56 -07002473 if (peer.get() == nullptr) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002474 return JDWP::ERR_THREAD_NOT_ALIVE;
2475 }
Ian Rogers4ad5cd32014-11-11 23:08:07 -08002476 // Suspend thread to build stack trace.
Elliott Hughesf327e072013-01-09 16:01:26 -08002477 bool timed_out;
Brian Carlstromba32de42014-08-27 23:43:46 -07002478 ThreadList* thread_list = Runtime::Current()->GetThreadList();
Sebastien Hertzcdd798d2017-04-18 18:28:51 +02002479 Thread* thread = thread_list->SuspendThreadByPeer(peer.get(),
2480 request_suspension,
Alex Light46f93402017-06-29 11:59:50 -07002481 SuspendReason::kForDebugger,
Brian Carlstromba32de42014-08-27 23:43:46 -07002482 &timed_out);
Ian Rogersc0542af2014-09-03 16:16:56 -07002483 if (thread != nullptr) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002484 return JDWP::ERR_NONE;
Elliott Hughesf327e072013-01-09 16:01:26 -08002485 } else if (timed_out) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002486 return JDWP::ERR_INTERNAL;
2487 } else {
2488 return JDWP::ERR_THREAD_NOT_ALIVE;
2489 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002490}
2491
Elliott Hughes221229c2013-01-08 18:17:50 -08002492void Dbg::ResumeThread(JDWP::ObjectId thread_id) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002493 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002494 JDWP::JdwpError error;
2495 mirror::Object* peer = gRegistry->Get<mirror::Object*>(thread_id, &error);
2496 CHECK(peer != nullptr) << error;
jeffhaoa77f0f62012-12-05 17:19:31 -08002497 Thread* thread;
2498 {
2499 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
2500 thread = Thread::FromManagedThread(soa, peer);
2501 }
Ian Rogersc0542af2014-09-03 16:16:56 -07002502 if (thread == nullptr) {
Elliott Hughes4e235312011-12-02 11:34:15 -08002503 LOG(WARNING) << "No such thread for resume: " << peer;
2504 return;
2505 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002506 bool needs_resume;
2507 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002508 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Sebastien Hertz70d60272017-04-14 14:18:36 +02002509 needs_resume = thread->GetDebugSuspendCount() > 0;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002510 }
2511 if (needs_resume) {
Alex Light88fd7202017-06-30 08:31:59 -07002512 bool resumed = Runtime::Current()->GetThreadList()->Resume(thread, SuspendReason::kForDebugger);
2513 DCHECK(resumed);
Elliott Hughes546b9862012-06-20 16:06:13 -07002514 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002515}
2516
2517void Dbg::SuspendSelf() {
Elliott Hughes475fc232011-10-25 15:00:35 -07002518 Runtime::Current()->GetThreadList()->SuspendSelfForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002519}
2520
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002521JDWP::JdwpError Dbg::GetThisObject(JDWP::ObjectId thread_id, JDWP::FrameId frame_id,
2522 JDWP::ObjectId* result) {
2523 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz69206392015-04-07 15:54:25 +02002524 JDWP::JdwpError error;
2525 Thread* thread = DecodeThread(soa, thread_id, &error);
2526 if (error != JDWP::ERR_NONE) {
2527 return error;
2528 }
2529 if (!IsSuspendedForDebugger(soa, thread)) {
2530 return JDWP::ERR_THREAD_NOT_SUSPENDED;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002531 }
Ian Rogers700a4022014-05-19 16:49:03 -07002532 std::unique_ptr<Context> context(Context::Create());
Andreas Gampec7d878d2018-11-19 18:42:06 +00002533 mirror::Object* this_object = nullptr;
2534 StackVisitor::WalkStack(
2535 [&](art::StackVisitor* stack_visitor) REQUIRES_SHARED(Locks::mutator_lock_) {
2536 if (frame_id != stack_visitor->GetFrameId()) {
2537 return true; // continue
2538 } else {
2539 this_object = stack_visitor->GetThisObject();
2540 return false;
2541 }
2542 },
2543 thread,
2544 context.get(),
2545 art::StackVisitor::StackWalkKind::kIncludeInlinedFrames);
2546 *result = gRegistry->Add(this_object);
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002547 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002548}
2549
Andreas Gampec7d878d2018-11-19 18:42:06 +00002550template <typename FrameHandler>
2551static JDWP::JdwpError FindAndHandleNonNativeFrame(Thread* thread,
2552 JDWP::FrameId frame_id,
2553 const FrameHandler& handler)
2554 REQUIRES_SHARED(Locks::mutator_lock_) {
2555 JDWP::JdwpError result = JDWP::ERR_INVALID_FRAMEID;
2556 std::unique_ptr<Context> context(Context::Create());
2557 StackVisitor::WalkStack(
2558 [&](art::StackVisitor* stack_visitor) REQUIRES_SHARED(Locks::mutator_lock_) {
2559 if (stack_visitor->GetFrameId() != frame_id) {
2560 return true; // Not our frame, carry on.
2561 }
2562 ArtMethod* m = stack_visitor->GetMethod();
2563 if (m->IsNative()) {
2564 // We can't read/write local value from/into native method.
2565 result = JDWP::ERR_OPAQUE_FRAME;
2566 } else {
2567 // We found our frame.
2568 result = handler(stack_visitor);
2569 }
2570 return false;
2571 },
2572 thread,
2573 context.get(),
2574 art::StackVisitor::StackWalkKind::kIncludeInlinedFrames);
2575 return result;
2576}
Sebastien Hertz8009f392014-09-01 17:07:11 +02002577
2578JDWP::JdwpError Dbg::GetLocalValues(JDWP::Request* request, JDWP::ExpandBuf* pReply) {
2579 JDWP::ObjectId thread_id = request->ReadThreadId();
2580 JDWP::FrameId frame_id = request->ReadFrameId();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002581
2582 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz69206392015-04-07 15:54:25 +02002583 JDWP::JdwpError error;
2584 Thread* thread = DecodeThread(soa, thread_id, &error);
2585 if (error != JDWP::ERR_NONE) {
2586 return error;
2587 }
2588 if (!IsSuspendedForDebugger(soa, thread)) {
2589 return JDWP::ERR_THREAD_NOT_SUSPENDED;
Elliott Hughes221229c2013-01-08 18:17:50 -08002590 }
Sebastien Hertz8009f392014-09-01 17:07:11 +02002591
Andreas Gampec7d878d2018-11-19 18:42:06 +00002592 return FindAndHandleNonNativeFrame(
2593 thread,
2594 frame_id,
2595 [&](art::StackVisitor* stack_visitor) REQUIRES_SHARED(Locks::mutator_lock_) {
2596 // Read the values from visitor's context.
2597 int32_t slot_count = request->ReadSigned32("slot count");
2598 expandBufAdd4BE(pReply, slot_count); /* "int values" */
2599 for (int32_t i = 0; i < slot_count; ++i) {
2600 uint32_t slot = request->ReadUnsigned32("slot");
2601 JDWP::JdwpTag reqSigByte = request->ReadTag();
Sebastien Hertz8009f392014-09-01 17:07:11 +02002602
Andreas Gampec7d878d2018-11-19 18:42:06 +00002603 VLOG(jdwp) << " --> slot " << slot << " " << reqSigByte;
Sebastien Hertz8009f392014-09-01 17:07:11 +02002604
Andreas Gampec7d878d2018-11-19 18:42:06 +00002605 size_t width = Dbg::GetTagWidth(reqSigByte);
2606 uint8_t* ptr = expandBufAddSpace(pReply, width + 1);
2607 error = Dbg::GetLocalValue(*stack_visitor, soa, slot, reqSigByte, ptr, width);
2608 if (error != JDWP::ERR_NONE) {
2609 return error;
2610 }
2611 }
2612 return JDWP::ERR_NONE;
2613 });
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002614}
2615
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002616constexpr JDWP::JdwpError kStackFrameLocalAccessError = JDWP::ERR_ABSENT_INFORMATION;
2617
2618static std::string GetStackContextAsString(const StackVisitor& visitor)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002619 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002620 return StringPrintf(" at DEX pc 0x%08x in method %s", visitor.GetDexPc(false),
David Sehr709b0702016-10-13 09:12:37 -07002621 ArtMethod::PrettyMethod(visitor.GetMethod()).c_str());
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002622}
2623
2624static JDWP::JdwpError FailGetLocalValue(const StackVisitor& visitor, uint16_t vreg,
2625 JDWP::JdwpTag tag)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002626 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002627 LOG(ERROR) << "Failed to read " << tag << " local from register v" << vreg
2628 << GetStackContextAsString(visitor);
2629 return kStackFrameLocalAccessError;
2630}
2631
Sebastien Hertz8009f392014-09-01 17:07:11 +02002632JDWP::JdwpError Dbg::GetLocalValue(const StackVisitor& visitor, ScopedObjectAccessUnchecked& soa,
2633 int slot, JDWP::JdwpTag tag, uint8_t* buf, size_t width) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002634 ArtMethod* m = visitor.GetMethod();
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002635 JDWP::JdwpError error = JDWP::ERR_NONE;
2636 uint16_t vreg = DemangleSlot(slot, m, &error);
2637 if (error != JDWP::ERR_NONE) {
2638 return error;
2639 }
Sebastien Hertz8009f392014-09-01 17:07:11 +02002640 // TODO: check that the tag is compatible with the actual type of the slot!
Sebastien Hertz8009f392014-09-01 17:07:11 +02002641 switch (tag) {
2642 case JDWP::JT_BOOLEAN: {
2643 CHECK_EQ(width, 1U);
2644 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002645 if (!visitor.GetVReg(m, vreg, kIntVReg, &intVal)) {
2646 return FailGetLocalValue(visitor, vreg, tag);
Ian Rogers0399dde2012-06-06 17:09:28 -07002647 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002648 VLOG(jdwp) << "get boolean local " << vreg << " = " << intVal;
2649 JDWP::Set1(buf + 1, intVal != 0);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002650 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002651 }
Sebastien Hertz8009f392014-09-01 17:07:11 +02002652 case JDWP::JT_BYTE: {
2653 CHECK_EQ(width, 1U);
2654 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002655 if (!visitor.GetVReg(m, vreg, kIntVReg, &intVal)) {
2656 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002657 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002658 VLOG(jdwp) << "get byte local " << vreg << " = " << intVal;
2659 JDWP::Set1(buf + 1, intVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002660 break;
2661 }
2662 case JDWP::JT_SHORT:
2663 case JDWP::JT_CHAR: {
2664 CHECK_EQ(width, 2U);
2665 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002666 if (!visitor.GetVReg(m, vreg, kIntVReg, &intVal)) {
2667 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002668 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002669 VLOG(jdwp) << "get short/char local " << vreg << " = " << intVal;
2670 JDWP::Set2BE(buf + 1, intVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002671 break;
2672 }
2673 case JDWP::JT_INT: {
2674 CHECK_EQ(width, 4U);
2675 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002676 if (!visitor.GetVReg(m, vreg, kIntVReg, &intVal)) {
2677 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002678 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002679 VLOG(jdwp) << "get int local " << vreg << " = " << intVal;
2680 JDWP::Set4BE(buf + 1, intVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002681 break;
2682 }
2683 case JDWP::JT_FLOAT: {
2684 CHECK_EQ(width, 4U);
2685 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002686 if (!visitor.GetVReg(m, vreg, kFloatVReg, &intVal)) {
2687 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002688 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002689 VLOG(jdwp) << "get float local " << vreg << " = " << intVal;
2690 JDWP::Set4BE(buf + 1, intVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002691 break;
2692 }
2693 case JDWP::JT_ARRAY:
2694 case JDWP::JT_CLASS_LOADER:
2695 case JDWP::JT_CLASS_OBJECT:
2696 case JDWP::JT_OBJECT:
2697 case JDWP::JT_STRING:
2698 case JDWP::JT_THREAD:
2699 case JDWP::JT_THREAD_GROUP: {
2700 CHECK_EQ(width, sizeof(JDWP::ObjectId));
2701 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002702 if (!visitor.GetVReg(m, vreg, kReferenceVReg, &intVal)) {
2703 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002704 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002705 mirror::Object* o = reinterpret_cast<mirror::Object*>(intVal);
2706 VLOG(jdwp) << "get " << tag << " object local " << vreg << " = " << o;
2707 if (!Runtime::Current()->GetHeap()->IsValidObjectAddress(o)) {
2708 LOG(FATAL) << StringPrintf("Found invalid object %#" PRIxPTR " in register v%u",
2709 reinterpret_cast<uintptr_t>(o), vreg)
2710 << GetStackContextAsString(visitor);
2711 UNREACHABLE();
2712 }
2713 tag = TagFromObject(soa, o);
2714 JDWP::SetObjectId(buf + 1, gRegistry->Add(o));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002715 break;
2716 }
2717 case JDWP::JT_DOUBLE: {
2718 CHECK_EQ(width, 8U);
2719 uint64_t longVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002720 if (!visitor.GetVRegPair(m, vreg, kDoubleLoVReg, kDoubleHiVReg, &longVal)) {
2721 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002722 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002723 VLOG(jdwp) << "get double local " << vreg << " = " << longVal;
2724 JDWP::Set8BE(buf + 1, longVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002725 break;
2726 }
2727 case JDWP::JT_LONG: {
2728 CHECK_EQ(width, 8U);
2729 uint64_t longVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002730 if (!visitor.GetVRegPair(m, vreg, kLongLoVReg, kLongHiVReg, &longVal)) {
2731 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002732 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002733 VLOG(jdwp) << "get long local " << vreg << " = " << longVal;
2734 JDWP::Set8BE(buf + 1, longVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002735 break;
2736 }
2737 default:
2738 LOG(FATAL) << "Unknown tag " << tag;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002739 UNREACHABLE();
Sebastien Hertz8009f392014-09-01 17:07:11 +02002740 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002741
Sebastien Hertz8009f392014-09-01 17:07:11 +02002742 // Prepend tag, which may have been updated.
2743 JDWP::Set1(buf, tag);
2744 return JDWP::ERR_NONE;
2745}
2746
2747JDWP::JdwpError Dbg::SetLocalValues(JDWP::Request* request) {
2748 JDWP::ObjectId thread_id = request->ReadThreadId();
2749 JDWP::FrameId frame_id = request->ReadFrameId();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002750
2751 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz69206392015-04-07 15:54:25 +02002752 JDWP::JdwpError error;
2753 Thread* thread = DecodeThread(soa, thread_id, &error);
2754 if (error != JDWP::ERR_NONE) {
2755 return error;
2756 }
2757 if (!IsSuspendedForDebugger(soa, thread)) {
2758 return JDWP::ERR_THREAD_NOT_SUSPENDED;
Elliott Hughes221229c2013-01-08 18:17:50 -08002759 }
Sebastien Hertz8009f392014-09-01 17:07:11 +02002760
Andreas Gampec7d878d2018-11-19 18:42:06 +00002761 return FindAndHandleNonNativeFrame(
2762 thread,
2763 frame_id,
2764 [&](art::StackVisitor* stack_visitor) REQUIRES_SHARED(Locks::mutator_lock_) {
2765 // Writes the values into visitor's context.
2766 int32_t slot_count = request->ReadSigned32("slot count");
2767 for (int32_t i = 0; i < slot_count; ++i) {
2768 uint32_t slot = request->ReadUnsigned32("slot");
2769 JDWP::JdwpTag sigByte = request->ReadTag();
2770 size_t width = Dbg::GetTagWidth(sigByte);
2771 uint64_t value = request->ReadValue(width);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002772
Andreas Gampec7d878d2018-11-19 18:42:06 +00002773 VLOG(jdwp) << " --> slot " << slot << " " << sigByte << " " << value;
2774 error = Dbg::SetLocalValue(thread, *stack_visitor, slot, sigByte, value, width);
2775 if (error != JDWP::ERR_NONE) {
2776 return error;
2777 }
2778 }
2779 return JDWP::ERR_NONE;
2780 });
Sebastien Hertz8009f392014-09-01 17:07:11 +02002781}
2782
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002783template<typename T>
2784static JDWP::JdwpError FailSetLocalValue(const StackVisitor& visitor, uint16_t vreg,
2785 JDWP::JdwpTag tag, T value)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002786 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002787 LOG(ERROR) << "Failed to write " << tag << " local " << value
2788 << " (0x" << std::hex << value << ") into register v" << vreg
2789 << GetStackContextAsString(visitor);
2790 return kStackFrameLocalAccessError;
2791}
2792
Mingyao Yang99170c62015-07-06 11:10:37 -07002793JDWP::JdwpError Dbg::SetLocalValue(Thread* thread, StackVisitor& visitor, int slot,
2794 JDWP::JdwpTag tag, uint64_t value, size_t width) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002795 ArtMethod* m = visitor.GetMethod();
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002796 JDWP::JdwpError error = JDWP::ERR_NONE;
2797 uint16_t vreg = DemangleSlot(slot, m, &error);
2798 if (error != JDWP::ERR_NONE) {
2799 return error;
2800 }
Sebastien Hertz8009f392014-09-01 17:07:11 +02002801 // TODO: check that the tag is compatible with the actual type of the slot!
Sebastien Hertz8009f392014-09-01 17:07:11 +02002802 switch (tag) {
2803 case JDWP::JT_BOOLEAN:
2804 case JDWP::JT_BYTE:
2805 CHECK_EQ(width, 1U);
Mingyao Yang636b9252015-07-31 16:40:24 -07002806 if (!visitor.SetVReg(m, vreg, static_cast<uint32_t>(value), kIntVReg)) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002807 return FailSetLocalValue(visitor, vreg, tag, static_cast<uint32_t>(value));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002808 }
2809 break;
2810 case JDWP::JT_SHORT:
2811 case JDWP::JT_CHAR:
2812 CHECK_EQ(width, 2U);
Mingyao Yang636b9252015-07-31 16:40:24 -07002813 if (!visitor.SetVReg(m, vreg, static_cast<uint32_t>(value), kIntVReg)) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002814 return FailSetLocalValue(visitor, vreg, tag, static_cast<uint32_t>(value));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002815 }
2816 break;
2817 case JDWP::JT_INT:
2818 CHECK_EQ(width, 4U);
Mingyao Yang636b9252015-07-31 16:40:24 -07002819 if (!visitor.SetVReg(m, vreg, static_cast<uint32_t>(value), kIntVReg)) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002820 return FailSetLocalValue(visitor, vreg, tag, static_cast<uint32_t>(value));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002821 }
2822 break;
2823 case JDWP::JT_FLOAT:
2824 CHECK_EQ(width, 4U);
Mingyao Yang636b9252015-07-31 16:40:24 -07002825 if (!visitor.SetVReg(m, vreg, static_cast<uint32_t>(value), kFloatVReg)) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002826 return FailSetLocalValue(visitor, vreg, tag, static_cast<uint32_t>(value));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002827 }
2828 break;
2829 case JDWP::JT_ARRAY:
2830 case JDWP::JT_CLASS_LOADER:
2831 case JDWP::JT_CLASS_OBJECT:
2832 case JDWP::JT_OBJECT:
2833 case JDWP::JT_STRING:
2834 case JDWP::JT_THREAD:
2835 case JDWP::JT_THREAD_GROUP: {
2836 CHECK_EQ(width, sizeof(JDWP::ObjectId));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002837 mirror::Object* o = gRegistry->Get<mirror::Object*>(static_cast<JDWP::ObjectId>(value),
2838 &error);
2839 if (error != JDWP::ERR_NONE) {
2840 VLOG(jdwp) << tag << " object " << o << " is an invalid object";
2841 return JDWP::ERR_INVALID_OBJECT;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002842 }
Mingyao Yang636b9252015-07-31 16:40:24 -07002843 if (!visitor.SetVReg(m, vreg, static_cast<uint32_t>(reinterpret_cast<uintptr_t>(o)),
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002844 kReferenceVReg)) {
2845 return FailSetLocalValue(visitor, vreg, tag, reinterpret_cast<uintptr_t>(o));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002846 }
2847 break;
2848 }
2849 case JDWP::JT_DOUBLE: {
2850 CHECK_EQ(width, 8U);
Mingyao Yang636b9252015-07-31 16:40:24 -07002851 if (!visitor.SetVRegPair(m, vreg, value, kDoubleLoVReg, kDoubleHiVReg)) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002852 return FailSetLocalValue(visitor, vreg, tag, value);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002853 }
2854 break;
2855 }
2856 case JDWP::JT_LONG: {
2857 CHECK_EQ(width, 8U);
Mingyao Yang636b9252015-07-31 16:40:24 -07002858 if (!visitor.SetVRegPair(m, vreg, value, kLongLoVReg, kLongHiVReg)) {
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 default:
2864 LOG(FATAL) << "Unknown tag " << tag;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002865 UNREACHABLE();
Sebastien Hertz8009f392014-09-01 17:07:11 +02002866 }
Mingyao Yang99170c62015-07-06 11:10:37 -07002867
2868 // If we set the local variable in a compiled frame, we need to trigger a deoptimization of
2869 // the stack so we continue execution with the interpreter using the new value(s) of the updated
2870 // local variable(s). To achieve this, we install instrumentation exit stub on each method of the
2871 // thread's stack. The stub will cause the deoptimization to happen.
2872 if (!visitor.IsShadowFrame() && thread->HasDebuggerShadowFrames()) {
2873 Runtime::Current()->GetInstrumentation()->InstrumentThreadStack(thread);
2874 }
2875
Sebastien Hertz8009f392014-09-01 17:07:11 +02002876 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002877}
2878
Mathieu Chartiere401d142015-04-22 13:56:20 -07002879static void SetEventLocation(JDWP::EventLocation* location, ArtMethod* m, uint32_t dex_pc)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002880 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz6995c602014-09-09 12:10:13 +02002881 DCHECK(location != nullptr);
2882 if (m == nullptr) {
2883 memset(location, 0, sizeof(*location));
2884 } else {
Alex Light97e78032017-06-27 17:51:55 -07002885 location->method = m->GetCanonicalMethod(kRuntimePointerSize);
Sebastien Hertz6995c602014-09-09 12:10:13 +02002886 location->dex_pc = (m->IsNative() || m->IsProxyMethod()) ? static_cast<uint32_t>(-1) : dex_pc;
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002887 }
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002888}
2889
Mathieu Chartiere401d142015-04-22 13:56:20 -07002890void Dbg::PostLocationEvent(ArtMethod* m, int dex_pc, mirror::Object* this_object,
Jeff Hao579b0242013-11-18 13:16:49 -08002891 int event_flags, const JValue* return_value) {
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002892 if (!IsDebuggerActive()) {
2893 return;
2894 }
2895 DCHECK(m != nullptr);
2896 DCHECK_EQ(m->IsStatic(), this_object == nullptr);
Sebastien Hertz6995c602014-09-09 12:10:13 +02002897 JDWP::EventLocation location;
2898 SetEventLocation(&location, m, dex_pc);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002899
Sebastien Hertzde48aa62015-05-26 11:53:39 +02002900 // We need to be sure no exception is pending when calling JdwpState::PostLocationEvent.
2901 // This is required to be able to call JNI functions to create JDWP ids. To achieve this,
2902 // we temporarily clear the current thread's exception (if any) and will restore it after
2903 // the call.
2904 // Note: the only way to get a pending exception here is to suspend on a move-exception
2905 // instruction.
2906 Thread* const self = Thread::Current();
2907 StackHandleScope<1> hs(self);
2908 Handle<mirror::Throwable> pending_exception(hs.NewHandle(self->GetException()));
2909 self->ClearException();
Andreas Gampefa4333d2017-02-14 11:10:34 -08002910 if (kIsDebugBuild && pending_exception != nullptr) {
Mathieu Chartier808c7a52017-12-15 11:19:33 -08002911 const Instruction& instr = location.method->DexInstructions().InstructionAt(location.dex_pc);
2912 CHECK_EQ(Instruction::MOVE_EXCEPTION, instr.Opcode());
Sebastien Hertzde48aa62015-05-26 11:53:39 +02002913 }
2914
Sebastien Hertz6995c602014-09-09 12:10:13 +02002915 gJdwpState->PostLocationEvent(&location, this_object, event_flags, return_value);
Sebastien Hertzde48aa62015-05-26 11:53:39 +02002916
Andreas Gampefa4333d2017-02-14 11:10:34 -08002917 if (pending_exception != nullptr) {
Sebastien Hertzde48aa62015-05-26 11:53:39 +02002918 self->SetException(pending_exception.Get());
2919 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002920}
2921
Mathieu Chartiere401d142015-04-22 13:56:20 -07002922void Dbg::PostFieldAccessEvent(ArtMethod* m, int dex_pc,
Mathieu Chartierc7853442015-03-27 14:35:38 -07002923 mirror::Object* this_object, ArtField* f) {
Alex Lighte00ec302017-06-16 08:56:43 -07002924 // TODO We should send events for native methods.
2925 if (!IsDebuggerActive() || m->IsNative()) {
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002926 return;
2927 }
2928 DCHECK(m != nullptr);
2929 DCHECK(f != nullptr);
Sebastien Hertz6995c602014-09-09 12:10:13 +02002930 JDWP::EventLocation location;
2931 SetEventLocation(&location, m, dex_pc);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002932
Sebastien Hertz6995c602014-09-09 12:10:13 +02002933 gJdwpState->PostFieldEvent(&location, f, this_object, nullptr, false);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002934}
2935
Mathieu Chartiere401d142015-04-22 13:56:20 -07002936void Dbg::PostFieldModificationEvent(ArtMethod* m, int dex_pc,
Mathieu Chartierc7853442015-03-27 14:35:38 -07002937 mirror::Object* this_object, ArtField* f,
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002938 const JValue* field_value) {
Alex Lighte00ec302017-06-16 08:56:43 -07002939 // TODO We should send events for native methods.
2940 if (!IsDebuggerActive() || m->IsNative()) {
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002941 return;
2942 }
2943 DCHECK(m != nullptr);
2944 DCHECK(f != nullptr);
2945 DCHECK(field_value != nullptr);
Sebastien Hertz6995c602014-09-09 12:10:13 +02002946 JDWP::EventLocation location;
2947 SetEventLocation(&location, m, dex_pc);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002948
Sebastien Hertz6995c602014-09-09 12:10:13 +02002949 gJdwpState->PostFieldEvent(&location, f, this_object, field_value, true);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002950}
2951
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002952void Dbg::PostException(mirror::Throwable* exception_object) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002953 if (!IsDebuggerActive()) {
Ian Rogers0ad5bb82011-12-07 10:16:32 -08002954 return;
2955 }
Sebastien Hertz261bc042015-04-08 09:36:07 +02002956 Thread* const self = Thread::Current();
Andreas Gampec7d878d2018-11-19 18:42:06 +00002957 StackHandleScope<2> handle_scope(self);
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002958 Handle<mirror::Throwable> h_exception(handle_scope.NewHandle(exception_object));
Andreas Gampec7d878d2018-11-19 18:42:06 +00002959 MutableHandle<mirror::Object> this_at_throw = handle_scope.NewHandle<mirror::Object>(nullptr);
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002960 std::unique_ptr<Context> context(Context::Create());
Andreas Gampe3d477f32018-11-16 16:40:45 +00002961
Andreas Gampec7d878d2018-11-19 18:42:06 +00002962 ArtMethod* catch_method = nullptr;
2963 ArtMethod* throw_method = nullptr;
2964 uint32_t catch_dex_pc = dex::kDexNoIndex;
2965 uint32_t throw_dex_pc = dex::kDexNoIndex;
2966 StackVisitor::WalkStack(
2967 /**
2968 * Finds the location where this exception will be caught. We search until we reach the top
2969 * frame, in which case this exception is considered uncaught.
2970 */
2971 [&](const art::StackVisitor* stack_visitor) REQUIRES_SHARED(Locks::mutator_lock_) {
2972 ArtMethod* method = stack_visitor->GetMethod();
2973 DCHECK(method != nullptr);
2974 if (method->IsRuntimeMethod()) {
2975 // Ignore callee save method.
2976 DCHECK(method->IsCalleeSaveMethod());
2977 return true;
2978 }
2979
2980 uint32_t dex_pc = stack_visitor->GetDexPc();
2981 if (throw_method == nullptr) {
2982 // First Java method found. It is either the method that threw the exception,
2983 // or the Java native method that is reporting an exception thrown by
2984 // native code.
2985 this_at_throw.Assign(stack_visitor->GetThisObject());
2986 throw_method = method;
2987 throw_dex_pc = dex_pc;
2988 }
2989
2990 if (dex_pc != dex::kDexNoIndex) {
2991 StackHandleScope<1> hs(stack_visitor->GetThread());
2992 uint32_t found_dex_pc;
2993 Handle<mirror::Class> exception_class(hs.NewHandle(h_exception->GetClass()));
2994 bool unused_clear_exception;
2995 found_dex_pc = method->FindCatchBlock(exception_class, dex_pc, &unused_clear_exception);
2996 if (found_dex_pc != dex::kDexNoIndex) {
2997 catch_method = method;
2998 catch_dex_pc = found_dex_pc;
2999 return false; // End stack walk.
3000 }
3001 }
3002 return true; // Continue stack walk.
3003 },
3004 self,
3005 context.get(),
3006 art::StackVisitor::StackWalkKind::kIncludeInlinedFrames);
3007
3008 JDWP::EventLocation exception_throw_location;
3009 SetEventLocation(&exception_throw_location, throw_method, throw_dex_pc);
3010 JDWP::EventLocation exception_catch_location;
3011 SetEventLocation(&exception_catch_location, catch_method, catch_dex_pc);
3012
3013 gJdwpState->PostException(&exception_throw_location,
3014 h_exception.Get(),
3015 &exception_catch_location,
3016 this_at_throw.Get());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003017}
3018
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003019void Dbg::PostClassPrepare(mirror::Class* c) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07003020 if (!IsDebuggerActive()) {
Elliott Hughes4740cdf2011-12-07 14:07:12 -08003021 return;
3022 }
Sebastien Hertz6995c602014-09-09 12:10:13 +02003023 gJdwpState->PostClassPrepare(c);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003024}
3025
Ian Rogers62d6c772013-02-27 08:32:07 -08003026void Dbg::UpdateDebugger(Thread* thread, mirror::Object* this_object,
Mathieu Chartiere401d142015-04-22 13:56:20 -07003027 ArtMethod* m, uint32_t dex_pc,
Sebastien Hertz8379b222014-02-24 17:38:15 +01003028 int event_flags, const JValue* return_value) {
Ian Rogers62d6c772013-02-27 08:32:07 -08003029 if (!IsDebuggerActive() || dex_pc == static_cast<uint32_t>(-2) /* fake method exit */) {
Elliott Hughes2aa2e392012-02-17 17:15:43 -08003030 return;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003031 }
3032
Elliott Hughes86964332012-02-15 19:37:42 -08003033 if (IsBreakpoint(m, dex_pc)) {
3034 event_flags |= kBreakpoint;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003035 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003036
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003037 // If the debugger is single-stepping one of our threads, check to
3038 // see if we're that thread and we've reached a step point.
3039 const SingleStepControl* single_step_control = thread->GetSingleStepControl();
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003040 if (single_step_control != nullptr) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003041 CHECK(!m->IsNative());
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003042 if (single_step_control->GetStepDepth() == JDWP::SD_INTO) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003043 // Step into method calls. We break when the line number
3044 // or method pointer changes. If we're in SS_MIN mode, we
3045 // always stop.
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003046 if (single_step_control->GetMethod() != m) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003047 event_flags |= kSingleStep;
3048 VLOG(jdwp) << "SS new method";
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003049 } else if (single_step_control->GetStepSize() == JDWP::SS_MIN) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003050 event_flags |= kSingleStep;
3051 VLOG(jdwp) << "SS new instruction";
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003052 } else if (single_step_control->ContainsDexPc(dex_pc)) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003053 event_flags |= kSingleStep;
3054 VLOG(jdwp) << "SS new line";
3055 }
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003056 } else if (single_step_control->GetStepDepth() == JDWP::SD_OVER) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003057 // Step over method calls. We break when the line number is
3058 // different and the frame depth is <= the original frame
3059 // depth. (We can't just compare on the method, because we
3060 // might get unrolled past it by an exception, and it's tricky
3061 // to identify recursion.)
3062
3063 int stack_depth = GetStackDepth(thread);
3064
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003065 if (stack_depth < single_step_control->GetStackDepth()) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003066 // Popped up one or more frames, always trigger.
3067 event_flags |= kSingleStep;
3068 VLOG(jdwp) << "SS method pop";
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003069 } else if (stack_depth == single_step_control->GetStackDepth()) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003070 // Same depth, see if we moved.
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003071 if (single_step_control->GetStepSize() == JDWP::SS_MIN) {
Elliott Hughes86964332012-02-15 19:37:42 -08003072 event_flags |= kSingleStep;
3073 VLOG(jdwp) << "SS new instruction";
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003074 } else if (single_step_control->ContainsDexPc(dex_pc)) {
Elliott Hughes2435a572012-02-17 16:07:41 -08003075 event_flags |= kSingleStep;
3076 VLOG(jdwp) << "SS new line";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003077 }
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003078 }
3079 } else {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003080 CHECK_EQ(single_step_control->GetStepDepth(), JDWP::SD_OUT);
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003081 // Return from the current method. We break when the frame
3082 // depth pops up.
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003083
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003084 // This differs from the "method exit" break in that it stops
3085 // with the PC at the next instruction in the returned-to
3086 // function, rather than the end of the returning function.
Elliott Hughes86964332012-02-15 19:37:42 -08003087
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003088 int stack_depth = GetStackDepth(thread);
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003089 if (stack_depth < single_step_control->GetStackDepth()) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003090 event_flags |= kSingleStep;
3091 VLOG(jdwp) << "SS method pop";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003092 }
3093 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003094 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003095
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003096 // If there's something interesting going on, see if it matches one
3097 // of the debugger filters.
3098 if (event_flags != 0) {
Sebastien Hertz8379b222014-02-24 17:38:15 +01003099 Dbg::PostLocationEvent(m, dex_pc, this_object, event_flags, return_value);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003100 }
3101}
3102
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003103size_t* Dbg::GetReferenceCounterForEvent(uint32_t instrumentation_event) {
3104 switch (instrumentation_event) {
3105 case instrumentation::Instrumentation::kMethodEntered:
3106 return &method_enter_event_ref_count_;
3107 case instrumentation::Instrumentation::kMethodExited:
3108 return &method_exit_event_ref_count_;
3109 case instrumentation::Instrumentation::kDexPcMoved:
3110 return &dex_pc_change_event_ref_count_;
3111 case instrumentation::Instrumentation::kFieldRead:
3112 return &field_read_event_ref_count_;
3113 case instrumentation::Instrumentation::kFieldWritten:
3114 return &field_write_event_ref_count_;
Alex Light6e1607e2017-08-23 10:06:18 -07003115 case instrumentation::Instrumentation::kExceptionThrown:
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003116 return &exception_catch_event_ref_count_;
3117 default:
3118 return nullptr;
3119 }
3120}
3121
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003122// Process request while all mutator threads are suspended.
3123void Dbg::ProcessDeoptimizationRequest(const DeoptimizationRequest& request) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003124 instrumentation::Instrumentation* instrumentation = Runtime::Current()->GetInstrumentation();
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003125 switch (request.GetKind()) {
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003126 case DeoptimizationRequest::kNothing:
3127 LOG(WARNING) << "Ignoring empty deoptimization request.";
3128 break;
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003129 case DeoptimizationRequest::kRegisterForEvent:
3130 VLOG(jdwp) << StringPrintf("Add debugger as listener for instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003131 request.InstrumentationEvent());
3132 instrumentation->AddListener(&gDebugInstrumentationListener, request.InstrumentationEvent());
3133 instrumentation_events_ |= request.InstrumentationEvent();
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003134 break;
3135 case DeoptimizationRequest::kUnregisterForEvent:
3136 VLOG(jdwp) << StringPrintf("Remove debugger as listener for instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003137 request.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003138 instrumentation->RemoveListener(&gDebugInstrumentationListener,
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003139 request.InstrumentationEvent());
3140 instrumentation_events_ &= ~request.InstrumentationEvent();
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003141 break;
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003142 case DeoptimizationRequest::kFullDeoptimization:
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003143 VLOG(jdwp) << "Deoptimize the world ...";
Sebastien Hertz0462c4c2015-04-01 16:34:17 +02003144 instrumentation->DeoptimizeEverything(kDbgInstrumentationKey);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003145 VLOG(jdwp) << "Deoptimize the world DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003146 break;
3147 case DeoptimizationRequest::kFullUndeoptimization:
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003148 VLOG(jdwp) << "Undeoptimize the world ...";
Sebastien Hertz0462c4c2015-04-01 16:34:17 +02003149 instrumentation->UndeoptimizeEverything(kDbgInstrumentationKey);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003150 VLOG(jdwp) << "Undeoptimize the world DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003151 break;
3152 case DeoptimizationRequest::kSelectiveDeoptimization:
David Sehr709b0702016-10-13 09:12:37 -07003153 VLOG(jdwp) << "Deoptimize method " << ArtMethod::PrettyMethod(request.Method()) << " ...";
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003154 instrumentation->Deoptimize(request.Method());
David Sehr709b0702016-10-13 09:12:37 -07003155 VLOG(jdwp) << "Deoptimize method " << ArtMethod::PrettyMethod(request.Method()) << " DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003156 break;
3157 case DeoptimizationRequest::kSelectiveUndeoptimization:
David Sehr709b0702016-10-13 09:12:37 -07003158 VLOG(jdwp) << "Undeoptimize method " << ArtMethod::PrettyMethod(request.Method()) << " ...";
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003159 instrumentation->Undeoptimize(request.Method());
David Sehr709b0702016-10-13 09:12:37 -07003160 VLOG(jdwp) << "Undeoptimize method " << ArtMethod::PrettyMethod(request.Method()) << " DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003161 break;
3162 default:
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003163 LOG(FATAL) << "Unsupported deoptimization request kind " << request.GetKind();
Elliott Hughesc1896c92018-11-29 11:33:18 -08003164 UNREACHABLE();
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003165 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003166}
3167
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003168void Dbg::RequestDeoptimization(const DeoptimizationRequest& req) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003169 if (req.GetKind() == DeoptimizationRequest::kNothing) {
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003170 // Nothing to do.
3171 return;
3172 }
Brian Carlstrom306db812014-09-05 13:01:41 -07003173 MutexLock mu(Thread::Current(), *Locks::deoptimization_lock_);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003174 RequestDeoptimizationLocked(req);
3175}
3176
3177void Dbg::RequestDeoptimizationLocked(const DeoptimizationRequest& req) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003178 switch (req.GetKind()) {
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003179 case DeoptimizationRequest::kRegisterForEvent: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003180 DCHECK_NE(req.InstrumentationEvent(), 0u);
3181 size_t* counter = GetReferenceCounterForEvent(req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003182 CHECK(counter != nullptr) << StringPrintf("No counter for instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003183 req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003184 if (*counter == 0) {
Sebastien Hertz7d2ae432014-05-15 11:26:34 +02003185 VLOG(jdwp) << StringPrintf("Queue request #%zd to start listening to instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003186 deoptimization_requests_.size(), req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003187 deoptimization_requests_.push_back(req);
3188 }
3189 *counter = *counter + 1;
3190 break;
3191 }
3192 case DeoptimizationRequest::kUnregisterForEvent: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003193 DCHECK_NE(req.InstrumentationEvent(), 0u);
3194 size_t* counter = GetReferenceCounterForEvent(req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003195 CHECK(counter != nullptr) << StringPrintf("No counter for instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003196 req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003197 *counter = *counter - 1;
3198 if (*counter == 0) {
Sebastien Hertz7d2ae432014-05-15 11:26:34 +02003199 VLOG(jdwp) << StringPrintf("Queue request #%zd to stop listening to instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003200 deoptimization_requests_.size(), req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003201 deoptimization_requests_.push_back(req);
3202 }
3203 break;
3204 }
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003205 case DeoptimizationRequest::kFullDeoptimization: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003206 DCHECK(req.Method() == nullptr);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003207 if (full_deoptimization_event_count_ == 0) {
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003208 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
3209 << " for full deoptimization";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003210 deoptimization_requests_.push_back(req);
3211 }
3212 ++full_deoptimization_event_count_;
3213 break;
3214 }
3215 case DeoptimizationRequest::kFullUndeoptimization: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003216 DCHECK(req.Method() == nullptr);
Sebastien Hertze713d932014-05-15 10:48:53 +02003217 DCHECK_GT(full_deoptimization_event_count_, 0U);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003218 --full_deoptimization_event_count_;
3219 if (full_deoptimization_event_count_ == 0) {
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003220 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
3221 << " for full undeoptimization";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003222 deoptimization_requests_.push_back(req);
3223 }
3224 break;
3225 }
3226 case DeoptimizationRequest::kSelectiveDeoptimization: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003227 DCHECK(req.Method() != nullptr);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003228 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
David Sehr709b0702016-10-13 09:12:37 -07003229 << " for deoptimization of " << req.Method()->PrettyMethod();
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003230 deoptimization_requests_.push_back(req);
3231 break;
3232 }
3233 case DeoptimizationRequest::kSelectiveUndeoptimization: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003234 DCHECK(req.Method() != nullptr);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003235 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
David Sehr709b0702016-10-13 09:12:37 -07003236 << " for undeoptimization of " << req.Method()->PrettyMethod();
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003237 deoptimization_requests_.push_back(req);
3238 break;
3239 }
3240 default: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003241 LOG(FATAL) << "Unknown deoptimization request kind " << req.GetKind();
Elliott Hughesc1896c92018-11-29 11:33:18 -08003242 UNREACHABLE();
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003243 }
3244 }
3245}
3246
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003247void Dbg::ManageDeoptimization() {
3248 Thread* const self = Thread::Current();
3249 {
3250 // Avoid suspend/resume if there is no pending request.
Brian Carlstrom306db812014-09-05 13:01:41 -07003251 MutexLock mu(self, *Locks::deoptimization_lock_);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003252 if (deoptimization_requests_.empty()) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003253 return;
3254 }
3255 }
3256 CHECK_EQ(self->GetState(), kRunnable);
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07003257 ScopedThreadSuspension sts(self, kWaitingForDeoptimization);
Mathieu Chartieraa516822015-10-02 15:53:37 -07003258 // Required for ProcessDeoptimizationRequest.
3259 gc::ScopedGCCriticalSection gcs(self,
3260 gc::kGcCauseInstrumentation,
3261 gc::kCollectorTypeInstrumentation);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003262 // We need to suspend mutator threads first.
Mathieu Chartier4f55e222015-09-04 13:26:21 -07003263 ScopedSuspendAll ssa(__FUNCTION__);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003264 const ThreadState old_state = self->SetStateUnsafe(kRunnable);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003265 {
Brian Carlstrom306db812014-09-05 13:01:41 -07003266 MutexLock mu(self, *Locks::deoptimization_lock_);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003267 size_t req_index = 0;
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003268 for (DeoptimizationRequest& request : deoptimization_requests_) {
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003269 VLOG(jdwp) << "Process deoptimization request #" << req_index++;
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003270 ProcessDeoptimizationRequest(request);
3271 }
3272 deoptimization_requests_.clear();
3273 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003274 CHECK_EQ(self->SetStateUnsafe(old_state), kRunnable);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003275}
3276
Mathieu Chartiere401d142015-04-22 13:56:20 -07003277static const Breakpoint* FindFirstBreakpointForMethod(ArtMethod* m)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003278 REQUIRES_SHARED(Locks::mutator_lock_, Locks::breakpoint_lock_) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003279 for (Breakpoint& breakpoint : gBreakpoints) {
Alex Light6c8467f2015-11-20 15:03:26 -08003280 if (breakpoint.IsInMethod(m)) {
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003281 return &breakpoint;
3282 }
3283 }
3284 return nullptr;
3285}
3286
Mathieu Chartiere401d142015-04-22 13:56:20 -07003287bool Dbg::MethodHasAnyBreakpoints(ArtMethod* method) {
Mathieu Chartierd8565452015-03-26 09:41:50 -07003288 ReaderMutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
3289 return FindFirstBreakpointForMethod(method) != nullptr;
3290}
3291
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003292// Sanity checks all existing breakpoints on the same method.
Mathieu Chartiere401d142015-04-22 13:56:20 -07003293static void SanityCheckExistingBreakpoints(ArtMethod* m,
Sebastien Hertzf3928792014-11-17 19:00:37 +01003294 DeoptimizationRequest::Kind deoptimization_kind)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003295 REQUIRES_SHARED(Locks::mutator_lock_, Locks::breakpoint_lock_) {
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003296 for (const Breakpoint& breakpoint : gBreakpoints) {
Alex Light6c8467f2015-11-20 15:03:26 -08003297 if (breakpoint.IsInMethod(m)) {
Sebastien Hertzf3928792014-11-17 19:00:37 +01003298 CHECK_EQ(deoptimization_kind, breakpoint.GetDeoptimizationKind());
3299 }
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003300 }
Sebastien Hertzf3928792014-11-17 19:00:37 +01003301 instrumentation::Instrumentation* instrumentation = Runtime::Current()->GetInstrumentation();
3302 if (deoptimization_kind == DeoptimizationRequest::kFullDeoptimization) {
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003303 // We should have deoptimized everything but not "selectively" deoptimized this method.
Sebastien Hertzf3928792014-11-17 19:00:37 +01003304 CHECK(instrumentation->AreAllMethodsDeoptimized());
3305 CHECK(!instrumentation->IsDeoptimized(m));
3306 } else if (deoptimization_kind == DeoptimizationRequest::kSelectiveDeoptimization) {
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003307 // We should have "selectively" deoptimized this method.
3308 // Note: while we have not deoptimized everything for this method, we may have done it for
3309 // another event.
Sebastien Hertzf3928792014-11-17 19:00:37 +01003310 CHECK(instrumentation->IsDeoptimized(m));
3311 } else {
3312 // This method does not require deoptimization.
3313 CHECK_EQ(deoptimization_kind, DeoptimizationRequest::kNothing);
3314 CHECK(!instrumentation->IsDeoptimized(m));
3315 }
3316}
3317
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003318// Returns the deoptimization kind required to set a breakpoint in a method.
3319// If a breakpoint has already been set, we also return the first breakpoint
3320// through the given 'existing_brkpt' pointer.
Sebastien Hertzf3928792014-11-17 19:00:37 +01003321static DeoptimizationRequest::Kind GetRequiredDeoptimizationKind(Thread* self,
Mathieu Chartiere401d142015-04-22 13:56:20 -07003322 ArtMethod* m,
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003323 const Breakpoint** existing_brkpt)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003324 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertzf3928792014-11-17 19:00:37 +01003325 if (!Dbg::RequiresDeoptimization()) {
3326 // We already run in interpreter-only mode so we don't need to deoptimize anything.
3327 VLOG(jdwp) << "No need for deoptimization when fully running with interpreter for method "
David Sehr709b0702016-10-13 09:12:37 -07003328 << ArtMethod::PrettyMethod(m);
Sebastien Hertzf3928792014-11-17 19:00:37 +01003329 return DeoptimizationRequest::kNothing;
3330 }
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003331 const Breakpoint* first_breakpoint;
Sebastien Hertzf3928792014-11-17 19:00:37 +01003332 {
3333 ReaderMutexLock mu(self, *Locks::breakpoint_lock_);
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003334 first_breakpoint = FindFirstBreakpointForMethod(m);
3335 *existing_brkpt = first_breakpoint;
Sebastien Hertzf3928792014-11-17 19:00:37 +01003336 }
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003337
3338 if (first_breakpoint == nullptr) {
Nicolas Geoffray6300fd72016-03-18 09:40:17 +00003339 // There is no breakpoint on this method yet: we need to deoptimize. If this method is default,
3340 // we deoptimize everything; otherwise we deoptimize only this method. We
Alex Light6c8467f2015-11-20 15:03:26 -08003341 // deoptimize with defaults because we do not know everywhere they are used. It is possible some
Nicolas Geoffray6300fd72016-03-18 09:40:17 +00003342 // of the copies could be missed.
Alex Light6c8467f2015-11-20 15:03:26 -08003343 // TODO Deoptimizing on default methods might not be necessary in all cases.
Nicolas Geoffray6300fd72016-03-18 09:40:17 +00003344 bool need_full_deoptimization = m->IsDefault();
Sebastien Hertzf3928792014-11-17 19:00:37 +01003345 if (need_full_deoptimization) {
Nicolas Geoffray6300fd72016-03-18 09:40:17 +00003346 VLOG(jdwp) << "Need full deoptimization because of copying of method "
David Sehr709b0702016-10-13 09:12:37 -07003347 << ArtMethod::PrettyMethod(m);
Sebastien Hertzf3928792014-11-17 19:00:37 +01003348 return DeoptimizationRequest::kFullDeoptimization;
3349 } else {
3350 // We don't need to deoptimize if the method has not been compiled.
Nicolas Geoffraya5891e82015-11-06 14:18:27 +00003351 const bool is_compiled = m->HasAnyCompiledCode();
Sebastien Hertzf3928792014-11-17 19:00:37 +01003352 if (is_compiled) {
David Sehr709b0702016-10-13 09:12:37 -07003353 VLOG(jdwp) << "Need selective deoptimization for compiled method "
3354 << ArtMethod::PrettyMethod(m);
Nicolas Geoffray6300fd72016-03-18 09:40:17 +00003355 return DeoptimizationRequest::kSelectiveDeoptimization;
Sebastien Hertzf3928792014-11-17 19:00:37 +01003356 } else {
3357 // Method is not compiled: we don't need to deoptimize.
David Sehr709b0702016-10-13 09:12:37 -07003358 VLOG(jdwp) << "No need for deoptimization for non-compiled method "
3359 << ArtMethod::PrettyMethod(m);
Sebastien Hertzf3928792014-11-17 19:00:37 +01003360 return DeoptimizationRequest::kNothing;
3361 }
3362 }
3363 } else {
3364 // There is at least one breakpoint for this method: we don't need to deoptimize.
3365 // Let's check that all breakpoints are configured the same way for deoptimization.
3366 VLOG(jdwp) << "Breakpoint already set: no deoptimization is required";
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003367 DeoptimizationRequest::Kind deoptimization_kind = first_breakpoint->GetDeoptimizationKind();
Sebastien Hertzf3928792014-11-17 19:00:37 +01003368 if (kIsDebugBuild) {
3369 ReaderMutexLock mu(self, *Locks::breakpoint_lock_);
3370 SanityCheckExistingBreakpoints(m, deoptimization_kind);
3371 }
3372 return DeoptimizationRequest::kNothing;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003373 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003374}
3375
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003376// Installs a breakpoint at the specified location. Also indicates through the deoptimization
3377// request if we need to deoptimize.
3378void Dbg::WatchLocation(const JDWP::JdwpLocation* location, DeoptimizationRequest* req) {
3379 Thread* const self = Thread::Current();
Mathieu Chartiere401d142015-04-22 13:56:20 -07003380 ArtMethod* m = FromMethodId(location->method_id);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003381 DCHECK(m != nullptr) << "No method for method id " << location->method_id;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003382
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003383 const Breakpoint* existing_breakpoint = nullptr;
3384 const DeoptimizationRequest::Kind deoptimization_kind =
3385 GetRequiredDeoptimizationKind(self, m, &existing_breakpoint);
Sebastien Hertzf3928792014-11-17 19:00:37 +01003386 req->SetKind(deoptimization_kind);
3387 if (deoptimization_kind == DeoptimizationRequest::kSelectiveDeoptimization) {
3388 req->SetMethod(m);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003389 } else {
Sebastien Hertzf3928792014-11-17 19:00:37 +01003390 CHECK(deoptimization_kind == DeoptimizationRequest::kNothing ||
3391 deoptimization_kind == DeoptimizationRequest::kFullDeoptimization);
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003392 req->SetMethod(nullptr);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003393 }
3394
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003395 {
3396 WriterMutexLock mu(self, *Locks::breakpoint_lock_);
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003397 // If there is at least one existing breakpoint on the same method, the new breakpoint
3398 // must have the same deoptimization kind than the existing breakpoint(s).
3399 DeoptimizationRequest::Kind breakpoint_deoptimization_kind;
3400 if (existing_breakpoint != nullptr) {
3401 breakpoint_deoptimization_kind = existing_breakpoint->GetDeoptimizationKind();
3402 } else {
3403 breakpoint_deoptimization_kind = deoptimization_kind;
3404 }
3405 gBreakpoints.push_back(Breakpoint(m, location->dex_pc, breakpoint_deoptimization_kind));
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003406 VLOG(jdwp) << "Set breakpoint #" << (gBreakpoints.size() - 1) << ": "
3407 << gBreakpoints[gBreakpoints.size() - 1];
3408 }
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003409}
3410
3411// Uninstalls a breakpoint at the specified location. Also indicates through the deoptimization
3412// request if we need to undeoptimize.
3413void Dbg::UnwatchLocation(const JDWP::JdwpLocation* location, DeoptimizationRequest* req) {
Sebastien Hertzed2be172014-08-19 15:33:43 +02003414 WriterMutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003415 ArtMethod* m = FromMethodId(location->method_id);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003416 DCHECK(m != nullptr) << "No method for method id " << location->method_id;
Sebastien Hertzf3928792014-11-17 19:00:37 +01003417 DeoptimizationRequest::Kind deoptimization_kind = DeoptimizationRequest::kNothing;
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003418 for (size_t i = 0, e = gBreakpoints.size(); i < e; ++i) {
Alex Light6c8467f2015-11-20 15:03:26 -08003419 if (gBreakpoints[i].DexPc() == location->dex_pc && gBreakpoints[i].IsInMethod(m)) {
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003420 VLOG(jdwp) << "Removed breakpoint #" << i << ": " << gBreakpoints[i];
Sebastien Hertzf3928792014-11-17 19:00:37 +01003421 deoptimization_kind = gBreakpoints[i].GetDeoptimizationKind();
3422 DCHECK_EQ(deoptimization_kind == DeoptimizationRequest::kSelectiveDeoptimization,
3423 Runtime::Current()->GetInstrumentation()->IsDeoptimized(m));
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003424 gBreakpoints.erase(gBreakpoints.begin() + i);
3425 break;
3426 }
3427 }
3428 const Breakpoint* const existing_breakpoint = FindFirstBreakpointForMethod(m);
3429 if (existing_breakpoint == nullptr) {
3430 // There is no more breakpoint on this method: we need to undeoptimize.
Sebastien Hertzf3928792014-11-17 19:00:37 +01003431 if (deoptimization_kind == DeoptimizationRequest::kFullDeoptimization) {
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003432 // This method required full deoptimization: we need to undeoptimize everything.
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003433 req->SetKind(DeoptimizationRequest::kFullUndeoptimization);
3434 req->SetMethod(nullptr);
Sebastien Hertzf3928792014-11-17 19:00:37 +01003435 } else if (deoptimization_kind == DeoptimizationRequest::kSelectiveDeoptimization) {
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003436 // This method required selective deoptimization: we need to undeoptimize only that method.
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003437 req->SetKind(DeoptimizationRequest::kSelectiveUndeoptimization);
3438 req->SetMethod(m);
Sebastien Hertzf3928792014-11-17 19:00:37 +01003439 } else {
3440 // This method had no need for deoptimization: do nothing.
3441 CHECK_EQ(deoptimization_kind, DeoptimizationRequest::kNothing);
3442 req->SetKind(DeoptimizationRequest::kNothing);
3443 req->SetMethod(nullptr);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003444 }
3445 } else {
3446 // There is at least one breakpoint for this method: we don't need to undeoptimize.
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003447 req->SetKind(DeoptimizationRequest::kNothing);
3448 req->SetMethod(nullptr);
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003449 if (kIsDebugBuild) {
Sebastien Hertzf3928792014-11-17 19:00:37 +01003450 SanityCheckExistingBreakpoints(m, deoptimization_kind);
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003451 }
Elliott Hughes86964332012-02-15 19:37:42 -08003452 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003453}
3454
Mathieu Chartiere401d142015-04-22 13:56:20 -07003455bool Dbg::IsForcedInterpreterNeededForCallingImpl(Thread* thread, ArtMethod* m) {
Daniel Mihalyieb076692014-08-22 17:33:31 +02003456 const SingleStepControl* const ssc = thread->GetSingleStepControl();
3457 if (ssc == nullptr) {
3458 // If we are not single-stepping, then we don't have to force interpreter.
3459 return false;
3460 }
3461 if (Runtime::Current()->GetInstrumentation()->InterpretOnly()) {
3462 // If we are in interpreter only mode, then we don't have to force interpreter.
3463 return false;
3464 }
3465
3466 if (!m->IsNative() && !m->IsProxyMethod()) {
3467 // If we want to step into a method, then we have to force interpreter on that call.
3468 if (ssc->GetStepDepth() == JDWP::SD_INTO) {
3469 return true;
3470 }
3471 }
3472 return false;
3473}
3474
Mathieu Chartiere401d142015-04-22 13:56:20 -07003475bool Dbg::IsForcedInterpreterNeededForResolutionImpl(Thread* thread, ArtMethod* m) {
Daniel Mihalyieb076692014-08-22 17:33:31 +02003476 instrumentation::Instrumentation* const instrumentation =
3477 Runtime::Current()->GetInstrumentation();
3478 // If we are in interpreter only mode, then we don't have to force interpreter.
3479 if (instrumentation->InterpretOnly()) {
3480 return false;
3481 }
3482 // We can only interpret pure Java method.
3483 if (m->IsNative() || m->IsProxyMethod()) {
3484 return false;
3485 }
3486 const SingleStepControl* const ssc = thread->GetSingleStepControl();
3487 if (ssc != nullptr) {
3488 // If we want to step into a method, then we have to force interpreter on that call.
3489 if (ssc->GetStepDepth() == JDWP::SD_INTO) {
3490 return true;
3491 }
3492 // If we are stepping out from a static initializer, by issuing a step
3493 // in or step over, that was implicitly invoked by calling a static method,
3494 // then we need to step into that method. Having a lower stack depth than
3495 // the one the single step control has indicates that the step originates
3496 // from the static initializer.
3497 if (ssc->GetStepDepth() != JDWP::SD_OUT &&
3498 ssc->GetStackDepth() > GetStackDepth(thread)) {
3499 return true;
3500 }
3501 }
3502 // There are cases where we have to force interpreter on deoptimized methods,
3503 // because in some cases the call will not be performed by invoking an entry
3504 // point that has been replaced by the deoptimization, but instead by directly
3505 // invoking the compiled code of the method, for example.
3506 return instrumentation->IsDeoptimized(m);
3507}
3508
Mathieu Chartiere401d142015-04-22 13:56:20 -07003509bool Dbg::IsForcedInstrumentationNeededForResolutionImpl(Thread* thread, ArtMethod* m) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07003510 // The upcall can be null and in that case we don't need to do anything.
Daniel Mihalyieb076692014-08-22 17:33:31 +02003511 if (m == nullptr) {
3512 return false;
3513 }
3514 instrumentation::Instrumentation* const instrumentation =
3515 Runtime::Current()->GetInstrumentation();
3516 // If we are in interpreter only mode, then we don't have to force interpreter.
3517 if (instrumentation->InterpretOnly()) {
3518 return false;
3519 }
3520 // We can only interpret pure Java method.
3521 if (m->IsNative() || m->IsProxyMethod()) {
3522 return false;
3523 }
3524 const SingleStepControl* const ssc = thread->GetSingleStepControl();
3525 if (ssc != nullptr) {
3526 // If we are stepping out from a static initializer, by issuing a step
3527 // out, that was implicitly invoked by calling a static method, then we
3528 // need to step into the caller of that method. Having a lower stack
3529 // depth than the one the single step control has indicates that the
3530 // step originates from the static initializer.
3531 if (ssc->GetStepDepth() == JDWP::SD_OUT &&
3532 ssc->GetStackDepth() > GetStackDepth(thread)) {
3533 return true;
3534 }
3535 }
3536 // If we are returning from a static intializer, that was implicitly
3537 // invoked by calling a static method and the caller is deoptimized,
3538 // then we have to deoptimize the stack without forcing interpreter
3539 // on the static method that was called originally. This problem can
3540 // be solved easily by forcing instrumentation on the called method,
3541 // because the instrumentation exit hook will recognise the need of
3542 // stack deoptimization by calling IsForcedInterpreterNeededForUpcall.
3543 return instrumentation->IsDeoptimized(m);
3544}
3545
Mathieu Chartiere401d142015-04-22 13:56:20 -07003546bool Dbg::IsForcedInterpreterNeededForUpcallImpl(Thread* thread, ArtMethod* m) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07003547 // The upcall can be null and in that case we don't need to do anything.
Daniel Mihalyieb076692014-08-22 17:33:31 +02003548 if (m == nullptr) {
3549 return false;
3550 }
3551 instrumentation::Instrumentation* const instrumentation =
3552 Runtime::Current()->GetInstrumentation();
3553 // If we are in interpreter only mode, then we don't have to force interpreter.
3554 if (instrumentation->InterpretOnly()) {
3555 return false;
3556 }
3557 // We can only interpret pure Java method.
3558 if (m->IsNative() || m->IsProxyMethod()) {
3559 return false;
3560 }
3561 const SingleStepControl* const ssc = thread->GetSingleStepControl();
3562 if (ssc != nullptr) {
3563 // The debugger is not interested in what is happening under the level
3564 // of the step, thus we only force interpreter when we are not below of
3565 // the step.
3566 if (ssc->GetStackDepth() >= GetStackDepth(thread)) {
3567 return true;
3568 }
3569 }
Mingyao Yang99170c62015-07-06 11:10:37 -07003570 if (thread->HasDebuggerShadowFrames()) {
3571 // We need to deoptimize the stack for the exception handling flow so that
3572 // we don't miss any deoptimization that should be done when there are
3573 // debugger shadow frames.
3574 return true;
3575 }
Daniel Mihalyieb076692014-08-22 17:33:31 +02003576 // We have to require stack deoptimization if the upcall is deoptimized.
3577 return instrumentation->IsDeoptimized(m);
3578}
3579
Sebastien Hertz520633b2015-09-08 17:03:36 +02003580// Do we need to deoptimize the stack to handle an exception?
3581bool Dbg::IsForcedInterpreterNeededForExceptionImpl(Thread* thread) {
3582 const SingleStepControl* const ssc = thread->GetSingleStepControl();
3583 if (ssc != nullptr) {
3584 // We deopt to step into the catch handler.
3585 return true;
3586 }
3587 // Deoptimization is required if at least one method in the stack needs it. However we
3588 // skip frames that will be unwound (thus not executed).
Andreas Gampec7d878d2018-11-19 18:42:06 +00003589 bool needs_deoptimization = false;
3590 StackVisitor::WalkStack(
3591 [&](art::StackVisitor* visitor) REQUIRES_SHARED(Locks::mutator_lock_) {
3592 // The visitor is meant to be used when handling exception from compiled code only.
3593 CHECK(!visitor->IsShadowFrame()) << "We only expect to visit compiled frame: "
3594 << ArtMethod::PrettyMethod(visitor->GetMethod());
3595 ArtMethod* method = visitor->GetMethod();
3596 if (method == nullptr) {
3597 // We reach an upcall and don't need to deoptimize this part of the stack (ManagedFragment)
3598 // so we can stop the visit.
3599 DCHECK(!needs_deoptimization);
3600 return false;
3601 }
3602 if (Runtime::Current()->GetInstrumentation()->InterpretOnly()) {
3603 // We found a compiled frame in the stack but instrumentation is set to interpret
3604 // everything: we need to deoptimize.
3605 needs_deoptimization = true;
3606 return false;
3607 }
3608 if (Runtime::Current()->GetInstrumentation()->IsDeoptimized(method)) {
3609 // We found a deoptimized method in the stack.
3610 needs_deoptimization = true;
3611 return false;
3612 }
3613 ShadowFrame* frame = visitor->GetThread()->FindDebuggerShadowFrame(visitor->GetFrameId());
3614 if (frame != nullptr) {
3615 // The debugger allocated a ShadowFrame to update a variable in the stack: we need to
3616 // deoptimize the stack to execute (and deallocate) this frame.
3617 needs_deoptimization = true;
3618 return false;
3619 }
3620 return true;
3621 },
3622 thread,
3623 /* context= */ nullptr,
3624 art::StackVisitor::StackWalkKind::kIncludeInlinedFrames,
3625 /* check_suspended */ true,
3626 /* include_transitions */ true);
3627 return needs_deoptimization;
Sebastien Hertz520633b2015-09-08 17:03:36 +02003628}
3629
Jeff Hao449db332013-04-12 18:30:52 -07003630// Scoped utility class to suspend a thread so that we may do tasks such as walk its stack. Doesn't
3631// cause suspension if the thread is the current thread.
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07003632class ScopedDebuggerThreadSuspension {
Jeff Hao449db332013-04-12 18:30:52 -07003633 public:
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07003634 ScopedDebuggerThreadSuspension(Thread* self, JDWP::ObjectId thread_id)
Mathieu Chartier90443472015-07-16 20:32:27 -07003635 REQUIRES(!Locks::thread_list_lock_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003636 REQUIRES_SHARED(Locks::mutator_lock_) :
Ian Rogersf3d874c2014-07-17 18:52:42 -07003637 thread_(nullptr),
Jeff Hao449db332013-04-12 18:30:52 -07003638 error_(JDWP::ERR_NONE),
3639 self_suspend_(false),
Ian Rogers33e95662013-05-20 20:29:14 -07003640 other_suspend_(false) {
Jeff Hao449db332013-04-12 18:30:52 -07003641 ScopedObjectAccessUnchecked soa(self);
Sebastien Hertz69206392015-04-07 15:54:25 +02003642 thread_ = DecodeThread(soa, thread_id, &error_);
Jeff Hao449db332013-04-12 18:30:52 -07003643 if (error_ == JDWP::ERR_NONE) {
3644 if (thread_ == soa.Self()) {
3645 self_suspend_ = true;
3646 } else {
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07003647 Thread* suspended_thread;
3648 {
3649 ScopedThreadSuspension sts(self, kWaitingForDebuggerSuspension);
3650 jobject thread_peer = Dbg::GetObjectRegistry()->GetJObject(thread_id);
3651 bool timed_out;
3652 ThreadList* const thread_list = Runtime::Current()->GetThreadList();
Sebastien Hertzcdd798d2017-04-18 18:28:51 +02003653 suspended_thread = thread_list->SuspendThreadByPeer(thread_peer,
Andreas Gampe98ea9d92018-10-19 14:06:15 -07003654 /* request_suspension= */ true,
Alex Light46f93402017-06-29 11:59:50 -07003655 SuspendReason::kForDebugger,
Sebastien Hertzcdd798d2017-04-18 18:28:51 +02003656 &timed_out);
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07003657 }
Ian Rogersf3d874c2014-07-17 18:52:42 -07003658 if (suspended_thread == nullptr) {
Jeff Hao449db332013-04-12 18:30:52 -07003659 // Thread terminated from under us while suspending.
3660 error_ = JDWP::ERR_INVALID_THREAD;
3661 } else {
3662 CHECK_EQ(suspended_thread, thread_);
3663 other_suspend_ = true;
3664 }
3665 }
3666 }
Elliott Hughes2435a572012-02-17 16:07:41 -08003667 }
Elliott Hughes86964332012-02-15 19:37:42 -08003668
Jeff Hao449db332013-04-12 18:30:52 -07003669 Thread* GetThread() const {
3670 return thread_;
3671 }
3672
3673 JDWP::JdwpError GetError() const {
3674 return error_;
3675 }
3676
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07003677 ~ScopedDebuggerThreadSuspension() {
Jeff Hao449db332013-04-12 18:30:52 -07003678 if (other_suspend_) {
Alex Light88fd7202017-06-30 08:31:59 -07003679 bool resumed = Runtime::Current()->GetThreadList()->Resume(thread_,
3680 SuspendReason::kForDebugger);
3681 DCHECK(resumed);
Jeff Hao449db332013-04-12 18:30:52 -07003682 }
3683 }
3684
3685 private:
3686 Thread* thread_;
3687 JDWP::JdwpError error_;
3688 bool self_suspend_;
3689 bool other_suspend_;
3690};
3691
3692JDWP::JdwpError Dbg::ConfigureStep(JDWP::ObjectId thread_id, JDWP::JdwpStepSize step_size,
3693 JDWP::JdwpStepDepth step_depth) {
3694 Thread* self = Thread::Current();
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07003695 ScopedDebuggerThreadSuspension sts(self, thread_id);
Jeff Hao449db332013-04-12 18:30:52 -07003696 if (sts.GetError() != JDWP::ERR_NONE) {
3697 return sts.GetError();
3698 }
3699
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003700 // Work out what ArtMethod* we're in, the current line number, and how deep the stack currently
Elliott Hughes2435a572012-02-17 16:07:41 -08003701 // is for step-out.
Ian Rogers0399dde2012-06-06 17:09:28 -07003702 struct SingleStepStackVisitor : public StackVisitor {
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003703 explicit SingleStepStackVisitor(Thread* thread) REQUIRES_SHARED(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01003704 : StackVisitor(thread, nullptr, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
3705 stack_depth(0),
3706 method(nullptr),
3707 line_number(-1) {}
Ian Rogersca190662012-06-26 15:45:57 -07003708
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003709 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
3710 // annotalysis.
Andreas Gampefa6a1b02018-09-07 08:11:55 -07003711 bool VisitFrame() override NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003712 ArtMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07003713 if (!m->IsRuntimeMethod()) {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003714 ++stack_depth;
3715 if (method == nullptr) {
Alex Light73376312017-04-06 10:10:51 -07003716 const DexFile* dex_file = m->GetDexFile();
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003717 method = m;
Alex Light73376312017-04-06 10:10:51 -07003718 if (dex_file != nullptr) {
David Sehr9323e6e2016-09-13 08:58:35 -07003719 line_number = annotations::GetLineNumFromPC(dex_file, m, GetDexPc());
Elliott Hughes2435a572012-02-17 16:07:41 -08003720 }
Elliott Hughes86964332012-02-15 19:37:42 -08003721 }
3722 }
Elliott Hughes530fa002012-03-12 11:44:49 -07003723 return true;
Elliott Hughes86964332012-02-15 19:37:42 -08003724 }
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003725
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003726 int stack_depth;
Mathieu Chartiere401d142015-04-22 13:56:20 -07003727 ArtMethod* method;
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003728 int32_t line_number;
Elliott Hughes86964332012-02-15 19:37:42 -08003729 };
Jeff Hao449db332013-04-12 18:30:52 -07003730
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003731 Thread* const thread = sts.GetThread();
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003732 SingleStepStackVisitor visitor(thread);
Ian Rogers0399dde2012-06-06 17:09:28 -07003733 visitor.WalkStack();
Elliott Hughes86964332012-02-15 19:37:42 -08003734
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003735 // Allocate single step.
Sebastien Hertz1558b572015-02-25 15:05:59 +01003736 SingleStepControl* single_step_control =
3737 new (std::nothrow) SingleStepControl(step_size, step_depth,
3738 visitor.stack_depth, visitor.method);
3739 if (single_step_control == nullptr) {
3740 LOG(ERROR) << "Failed to allocate SingleStepControl";
3741 return JDWP::ERR_OUT_OF_MEMORY;
3742 }
3743
Mathieu Chartiere401d142015-04-22 13:56:20 -07003744 ArtMethod* m = single_step_control->GetMethod();
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003745 const int32_t line_number = visitor.line_number;
Sebastien Hertz52f5f932015-05-28 11:00:57 +02003746 // Note: if the thread is not running Java code (pure native thread), there is no "current"
3747 // method on the stack (and no line number either).
3748 if (m != nullptr && !m->IsNative()) {
David Sehr0225f8e2018-01-31 08:52:24 +00003749 CodeItemDebugInfoAccessor accessor(m->DexInstructionDebugInfo());
Mathieu Chartier3e2e1232018-09-11 12:35:30 -07003750 bool last_pc_valid = false;
3751 uint32_t last_pc = 0u;
3752 // Find the dex_pc values that correspond to the current line, for line-based single-stepping.
3753 accessor.DecodeDebugPositionInfo([&](const DexFile::PositionInfo& entry) {
3754 if (static_cast<int32_t>(entry.line_) == line_number) {
3755 if (!last_pc_valid) {
3756 // Everything from this address until the next line change is ours.
3757 last_pc = entry.address_;
3758 last_pc_valid = true;
3759 }
3760 // Otherwise, if we're already in a valid range for this line,
3761 // just keep going (shouldn't really happen)...
3762 } else if (last_pc_valid) { // and the line number is new
3763 // Add everything from the last entry up until here to the set
3764 for (uint32_t dex_pc = last_pc; dex_pc < entry.address_; ++dex_pc) {
3765 single_step_control->AddDexPc(dex_pc);
3766 }
3767 last_pc_valid = false;
3768 }
3769 return false; // There may be multiple entries for any given line.
3770 });
3771 // If the line number was the last in the position table...
3772 if (last_pc_valid) {
3773 for (uint32_t dex_pc = last_pc; dex_pc < accessor.InsnsSizeInCodeUnits(); ++dex_pc) {
3774 single_step_control->AddDexPc(dex_pc);
3775 }
3776 }
Elliott Hughes3e2e1a22012-02-21 11:33:41 -08003777 }
Elliott Hughes2435a572012-02-17 16:07:41 -08003778
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003779 // Activate single-step in the thread.
3780 thread->ActivateSingleStepControl(single_step_control);
Elliott Hughes86964332012-02-15 19:37:42 -08003781
Elliott Hughes2435a572012-02-17 16:07:41 -08003782 if (VLOG_IS_ON(jdwp)) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003783 VLOG(jdwp) << "Single-step thread: " << *thread;
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003784 VLOG(jdwp) << "Single-step step size: " << single_step_control->GetStepSize();
3785 VLOG(jdwp) << "Single-step step depth: " << single_step_control->GetStepDepth();
David Sehr709b0702016-10-13 09:12:37 -07003786 VLOG(jdwp) << "Single-step current method: "
3787 << ArtMethod::PrettyMethod(single_step_control->GetMethod());
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003788 VLOG(jdwp) << "Single-step current line: " << line_number;
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003789 VLOG(jdwp) << "Single-step current stack depth: " << single_step_control->GetStackDepth();
Elliott Hughes2435a572012-02-17 16:07:41 -08003790 VLOG(jdwp) << "Single-step dex_pc values:";
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003791 for (uint32_t dex_pc : single_step_control->GetDexPcs()) {
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003792 VLOG(jdwp) << StringPrintf(" %#x", dex_pc);
Elliott Hughes2435a572012-02-17 16:07:41 -08003793 }
3794 }
3795
3796 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003797}
3798
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003799void Dbg::UnconfigureStep(JDWP::ObjectId thread_id) {
3800 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07003801 JDWP::JdwpError error;
3802 Thread* thread = DecodeThread(soa, thread_id, &error);
Sebastien Hertz87118ed2013-11-26 17:57:18 +01003803 if (error == JDWP::ERR_NONE) {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003804 thread->DeactivateSingleStepControl();
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003805 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003806}
3807
Elliott Hughes45651fd2012-02-21 15:48:20 -08003808static char JdwpTagToShortyChar(JDWP::JdwpTag tag) {
3809 switch (tag) {
3810 default:
3811 LOG(FATAL) << "unknown JDWP tag: " << PrintableChar(tag);
Ian Rogersfc787ec2014-10-09 21:56:44 -07003812 UNREACHABLE();
Elliott Hughes45651fd2012-02-21 15:48:20 -08003813
3814 // Primitives.
3815 case JDWP::JT_BYTE: return 'B';
3816 case JDWP::JT_CHAR: return 'C';
3817 case JDWP::JT_FLOAT: return 'F';
3818 case JDWP::JT_DOUBLE: return 'D';
3819 case JDWP::JT_INT: return 'I';
3820 case JDWP::JT_LONG: return 'J';
3821 case JDWP::JT_SHORT: return 'S';
3822 case JDWP::JT_VOID: return 'V';
3823 case JDWP::JT_BOOLEAN: return 'Z';
3824
3825 // Reference types.
3826 case JDWP::JT_ARRAY:
3827 case JDWP::JT_OBJECT:
3828 case JDWP::JT_STRING:
3829 case JDWP::JT_THREAD:
3830 case JDWP::JT_THREAD_GROUP:
3831 case JDWP::JT_CLASS_LOADER:
3832 case JDWP::JT_CLASS_OBJECT:
3833 return 'L';
3834 }
3835}
3836
Sebastien Hertzcbc50642015-06-01 17:33:12 +02003837JDWP::JdwpError Dbg::PrepareInvokeMethod(uint32_t request_id, JDWP::ObjectId thread_id,
3838 JDWP::ObjectId object_id, JDWP::RefTypeId class_id,
3839 JDWP::MethodId method_id, uint32_t arg_count,
3840 uint64_t arg_values[], JDWP::JdwpTag* arg_types,
3841 uint32_t options) {
3842 Thread* const self = Thread::Current();
3843 CHECK_EQ(self, GetDebugThread()) << "This must be called by the JDWP thread";
Sebastien Hertzd4032e42015-06-12 15:47:34 +02003844 const bool resume_all_threads = ((options & JDWP::INVOKE_SINGLE_THREADED) == 0);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003845
Sebastien Hertzcbc50642015-06-01 17:33:12 +02003846 ThreadList* thread_list = Runtime::Current()->GetThreadList();
Ian Rogersc0542af2014-09-03 16:16:56 -07003847 Thread* targetThread = nullptr;
Elliott Hughesd07986f2011-12-06 18:27:45 -08003848 {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003849 ScopedObjectAccessUnchecked soa(self);
Ian Rogersc0542af2014-09-03 16:16:56 -07003850 JDWP::JdwpError error;
3851 targetThread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08003852 if (error != JDWP::ERR_NONE) {
3853 LOG(ERROR) << "InvokeMethod request for invalid thread id " << thread_id;
3854 return error;
Elliott Hughesd07986f2011-12-06 18:27:45 -08003855 }
Sebastien Hertz1558b572015-02-25 15:05:59 +01003856 if (targetThread->GetInvokeReq() != nullptr) {
3857 // Thread is already invoking a method on behalf of the debugger.
3858 LOG(ERROR) << "InvokeMethod request for thread already invoking a method: " << *targetThread;
3859 return JDWP::ERR_ALREADY_INVOKING;
3860 }
3861 if (!targetThread->IsReadyForDebugInvoke()) {
3862 // Thread is not suspended by an event so it cannot invoke a method.
Elliott Hughesd07986f2011-12-06 18:27:45 -08003863 LOG(ERROR) << "InvokeMethod request for thread not stopped by event: " << *targetThread;
3864 return JDWP::ERR_INVALID_THREAD;
3865 }
3866
3867 /*
Sebastien Hertzd4032e42015-06-12 15:47:34 +02003868 * According to the JDWP specs, we are expected to resume all threads (or only the
3869 * target thread) once. So if a thread has been suspended more than once (either by
3870 * the debugger for an event or by the runtime for GC), it will remain suspended before
3871 * the invoke is executed. This means the debugger is responsible to properly resume all
3872 * the threads it has suspended so the target thread can execute the method.
Elliott Hughesd07986f2011-12-06 18:27:45 -08003873 *
Sebastien Hertzd4032e42015-06-12 15:47:34 +02003874 * However, for compatibility reason with older versions of debuggers (like Eclipse), we
3875 * fully resume all threads (by canceling *all* debugger suspensions) when the debugger
3876 * wants us to resume all threads. This is to avoid ending up in deadlock situation.
3877 *
3878 * On the other hand, if we are asked to only resume the target thread, then we follow the
3879 * JDWP specs by resuming that thread only once. This means the thread will remain suspended
3880 * if it has been suspended more than once before the invoke (and again, this is the
3881 * responsibility of the debugger to properly resume that thread before invoking a method).
Elliott Hughesd07986f2011-12-06 18:27:45 -08003882 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003883 int suspend_count;
3884 {
Ian Rogers50b35e22012-10-04 10:09:15 -07003885 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003886 suspend_count = targetThread->GetSuspendCount();
3887 }
Sebastien Hertzd4032e42015-06-12 15:47:34 +02003888 if (suspend_count > 1 && resume_all_threads) {
3889 // The target thread will remain suspended even after we resume it. Let's emit a warning
3890 // to indicate the invoke won't be executed until the thread is resumed.
3891 LOG(WARNING) << *targetThread << " suspended more than once (suspend count == "
3892 << suspend_count << "). This thread will invoke the method only once "
3893 << "it is fully resumed.";
Elliott Hughesd07986f2011-12-06 18:27:45 -08003894 }
3895
Vladimir Marko4617d582019-03-28 13:48:31 +00003896 ObjPtr<mirror::Object> receiver = gRegistry->Get<mirror::Object*>(object_id, &error);
Ian Rogersc0542af2014-09-03 16:16:56 -07003897 if (error != JDWP::ERR_NONE) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08003898 return JDWP::ERR_INVALID_OBJECT;
3899 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003900
Sebastien Hertz1558b572015-02-25 15:05:59 +01003901 gRegistry->Get<mirror::Object*>(thread_id, &error);
Ian Rogersc0542af2014-09-03 16:16:56 -07003902 if (error != JDWP::ERR_NONE) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08003903 return JDWP::ERR_INVALID_OBJECT;
3904 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003905
Vladimir Marko4617d582019-03-28 13:48:31 +00003906 ObjPtr<mirror::Class> c = DecodeClass(class_id, &error);
Ian Rogersc0542af2014-09-03 16:16:56 -07003907 if (c == nullptr) {
3908 return error;
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08003909 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003910
Mathieu Chartiere401d142015-04-22 13:56:20 -07003911 ArtMethod* m = FromMethodId(method_id);
Ian Rogersc0542af2014-09-03 16:16:56 -07003912 if (m->IsStatic() != (receiver == nullptr)) {
Elliott Hughes45651fd2012-02-21 15:48:20 -08003913 return JDWP::ERR_INVALID_METHODID;
3914 }
3915 if (m->IsStatic()) {
3916 if (m->GetDeclaringClass() != c) {
3917 return JDWP::ERR_INVALID_METHODID;
3918 }
3919 } else {
3920 if (!m->GetDeclaringClass()->IsAssignableFrom(c)) {
3921 return JDWP::ERR_INVALID_METHODID;
3922 }
3923 }
3924
3925 // Check the argument list matches the method.
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003926 uint32_t shorty_len = 0;
3927 const char* shorty = m->GetShorty(&shorty_len);
3928 if (shorty_len - 1 != arg_count) {
Elliott Hughes45651fd2012-02-21 15:48:20 -08003929 return JDWP::ERR_ILLEGAL_ARGUMENT;
3930 }
Elliott Hughes09201632013-04-15 15:50:07 -07003931
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003932 {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003933 StackHandleScope<2> hs(soa.Self());
Vladimir Marko4617d582019-03-28 13:48:31 +00003934 HandleWrapperObjPtr<mirror::Object> h_obj(hs.NewHandleWrapper(&receiver));
3935 HandleWrapperObjPtr<mirror::Class> h_klass(hs.NewHandleWrapper(&c));
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003936 const dex::TypeList* types = m->GetParameterTypeList();
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003937 for (size_t i = 0; i < arg_count; ++i) {
3938 if (shorty[i + 1] != JdwpTagToShortyChar(arg_types[i])) {
Elliott Hughes09201632013-04-15 15:50:07 -07003939 return JDWP::ERR_ILLEGAL_ARGUMENT;
3940 }
3941
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003942 if (shorty[i + 1] == 'L') {
3943 // Did we really get an argument of an appropriate reference type?
Vladimir Markob45528c2017-07-27 14:14:28 +01003944 ObjPtr<mirror::Class> parameter_type =
3945 m->ResolveClassFromTypeIndex(types->GetTypeItem(i).type_idx_);
Ian Rogersc0542af2014-09-03 16:16:56 -07003946 mirror::Object* argument = gRegistry->Get<mirror::Object*>(arg_values[i], &error);
3947 if (error != JDWP::ERR_NONE) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003948 return JDWP::ERR_INVALID_OBJECT;
3949 }
Ian Rogersc0542af2014-09-03 16:16:56 -07003950 if (argument != nullptr && !argument->InstanceOf(parameter_type)) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003951 return JDWP::ERR_ILLEGAL_ARGUMENT;
3952 }
3953
3954 // Turn the on-the-wire ObjectId into a jobject.
3955 jvalue& v = reinterpret_cast<jvalue&>(arg_values[i]);
3956 v.l = gRegistry->GetJObject(arg_values[i]);
3957 }
Elliott Hughes09201632013-04-15 15:50:07 -07003958 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003959 }
3960
Sebastien Hertz1558b572015-02-25 15:05:59 +01003961 // Allocates a DebugInvokeReq.
Vladimir Marko4617d582019-03-28 13:48:31 +00003962 DebugInvokeReq* req = new (std::nothrow) DebugInvokeReq(
3963 request_id, thread_id, receiver, c, m, options, arg_values, arg_count);
Sebastien Hertzcbc50642015-06-01 17:33:12 +02003964 if (req == nullptr) {
Sebastien Hertz1558b572015-02-25 15:05:59 +01003965 LOG(ERROR) << "Failed to allocate DebugInvokeReq";
3966 return JDWP::ERR_OUT_OF_MEMORY;
3967 }
3968
Sebastien Hertzcbc50642015-06-01 17:33:12 +02003969 // Attaches the DebugInvokeReq to the target thread so it executes the method when
3970 // it is resumed. Once the invocation completes, the target thread will delete it before
3971 // suspending itself (see ThreadList::SuspendSelfForDebugger).
3972 targetThread->SetDebugInvokeReq(req);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003973 }
3974
3975 // 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 +02003976 // away we're sitting high and dry -- but we must release this before the UndoDebuggerSuspensions
3977 // call.
Sebastien Hertzd4032e42015-06-12 15:47:34 +02003978 if (resume_all_threads) {
Sebastien Hertzcbc50642015-06-01 17:33:12 +02003979 VLOG(jdwp) << " Resuming all threads";
3980 thread_list->UndoDebuggerSuspensions();
3981 } else {
3982 VLOG(jdwp) << " Resuming event thread only";
Alex Light88fd7202017-06-30 08:31:59 -07003983 bool resumed = thread_list->Resume(targetThread, SuspendReason::kForDebugger);
3984 DCHECK(resumed);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003985 }
3986
Sebastien Hertzcbc50642015-06-01 17:33:12 +02003987 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003988}
3989
3990void Dbg::ExecuteMethod(DebugInvokeReq* pReq) {
Sebastien Hertzcbc50642015-06-01 17:33:12 +02003991 Thread* const self = Thread::Current();
3992 CHECK_NE(self, GetDebugThread()) << "This must be called by the event thread";
3993
3994 ScopedObjectAccess soa(self);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003995
Elliott Hughes81ff3182012-03-23 20:35:56 -07003996 // We can be called while an exception is pending. We need
Elliott Hughesd07986f2011-12-06 18:27:45 -08003997 // to preserve that across the method invocation.
Sebastien Hertzcbc50642015-06-01 17:33:12 +02003998 StackHandleScope<1> hs(soa.Self());
3999 Handle<mirror::Throwable> old_exception = hs.NewHandle(soa.Self()->GetException());
Sebastien Hertz1558b572015-02-25 15:05:59 +01004000 soa.Self()->ClearException();
Elliott Hughesd07986f2011-12-06 18:27:45 -08004001
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004002 // Execute the method then sends reply to the debugger.
4003 ExecuteMethodWithoutPendingException(soa, pReq);
4004
4005 // If an exception was pending before the invoke, restore it now.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004006 if (old_exception != nullptr) {
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004007 soa.Self()->SetException(old_exception.Get());
4008 }
4009}
4010
4011// Helper function: write a variable-width value into the output input buffer.
4012static void WriteValue(JDWP::ExpandBuf* pReply, int width, uint64_t value) {
4013 switch (width) {
4014 case 1:
4015 expandBufAdd1(pReply, value);
4016 break;
4017 case 2:
4018 expandBufAdd2BE(pReply, value);
4019 break;
4020 case 4:
4021 expandBufAdd4BE(pReply, value);
4022 break;
4023 case 8:
4024 expandBufAdd8BE(pReply, value);
4025 break;
4026 default:
4027 LOG(FATAL) << width;
4028 UNREACHABLE();
4029 }
4030}
4031
4032void Dbg::ExecuteMethodWithoutPendingException(ScopedObjectAccess& soa, DebugInvokeReq* pReq) {
4033 soa.Self()->AssertNoPendingException();
4034
Elliott Hughesd07986f2011-12-06 18:27:45 -08004035 // Translate the method through the vtable, unless the debugger wants to suppress it.
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004036 ArtMethod* m = pReq->method;
Andreas Gampe542451c2016-07-26 09:02:02 -07004037 PointerSize image_pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
Sebastien Hertz1558b572015-02-25 15:05:59 +01004038 if ((pReq->options & JDWP::INVOKE_NONVIRTUAL) == 0 && pReq->receiver.Read() != nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004039 ArtMethod* actual_method =
4040 pReq->klass.Read()->FindVirtualMethodForVirtualOrInterface(m, image_pointer_size);
4041 if (actual_method != m) {
David Sehr709b0702016-10-13 09:12:37 -07004042 VLOG(jdwp) << "ExecuteMethod translated " << ArtMethod::PrettyMethod(m)
4043 << " to " << ArtMethod::PrettyMethod(actual_method);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004044 m = actual_method;
Elliott Hughes45651fd2012-02-21 15:48:20 -08004045 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08004046 }
David Sehr709b0702016-10-13 09:12:37 -07004047 VLOG(jdwp) << "ExecuteMethod " << ArtMethod::PrettyMethod(m)
Sebastien Hertz1558b572015-02-25 15:05:59 +01004048 << " receiver=" << pReq->receiver.Read()
Sebastien Hertzd38667a2013-11-25 15:43:54 +01004049 << " arg_count=" << pReq->arg_count;
Mathieu Chartiere401d142015-04-22 13:56:20 -07004050 CHECK(m != nullptr);
Elliott Hughesd07986f2011-12-06 18:27:45 -08004051
Roland Levillain33d69032015-06-18 18:20:59 +01004052 static_assert(sizeof(jvalue) == sizeof(uint64_t), "jvalue and uint64_t have different sizes.");
Elliott Hughesd07986f2011-12-06 18:27:45 -08004053
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004054 // Invoke the method.
Jeff Hao39b6c242015-05-19 20:30:23 -07004055 ScopedLocalRef<jobject> ref(soa.Env(), soa.AddLocalReference<jobject>(pReq->receiver.Read()));
Andreas Gampe13b27842016-11-07 16:48:23 -08004056 JValue result = InvokeWithJValues(soa, ref.get(), jni::EncodeArtMethod(m),
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004057 reinterpret_cast<jvalue*>(pReq->arg_values.get()));
Elliott Hughesd07986f2011-12-06 18:27:45 -08004058
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004059 // Prepare JDWP ids for the reply.
4060 JDWP::JdwpTag result_tag = BasicTagFromDescriptor(m->GetShorty());
4061 const bool is_object_result = (result_tag == JDWP::JT_OBJECT);
Jeff Hao064d24e2016-08-25 03:52:40 +00004062 StackHandleScope<3> hs(soa.Self());
Sebastien Hertz1558b572015-02-25 15:05:59 +01004063 Handle<mirror::Object> object_result = hs.NewHandle(is_object_result ? result.GetL() : nullptr);
4064 Handle<mirror::Throwable> exception = hs.NewHandle(soa.Self()->GetException());
4065 soa.Self()->ClearException();
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004066
4067 if (!IsDebuggerActive()) {
4068 // The debugger detached: we must not re-suspend threads. We also don't need to fill the reply
4069 // because it won't be sent either.
4070 return;
4071 }
4072
4073 JDWP::ObjectId exceptionObjectId = gRegistry->Add(exception);
4074 uint64_t result_value = 0;
4075 if (exceptionObjectId != 0) {
Sebastien Hertz1558b572015-02-25 15:05:59 +01004076 VLOG(jdwp) << " JDWP invocation returning with exception=" << exception.Get()
4077 << " " << exception->Dump();
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004078 result_value = 0;
Sebastien Hertz1558b572015-02-25 15:05:59 +01004079 } else if (is_object_result) {
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004080 /* if no exception was thrown, examine object result more closely */
Sebastien Hertz1558b572015-02-25 15:05:59 +01004081 JDWP::JdwpTag new_tag = TagFromObject(soa, object_result.Get());
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004082 if (new_tag != result_tag) {
4083 VLOG(jdwp) << " JDWP promoted result from " << result_tag << " to " << new_tag;
4084 result_tag = new_tag;
Elliott Hughesd07986f2011-12-06 18:27:45 -08004085 }
4086
Sebastien Hertz1558b572015-02-25 15:05:59 +01004087 // Register the object in the registry and reference its ObjectId. This ensures
4088 // GC safety and prevents from accessing stale reference if the object is moved.
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004089 result_value = gRegistry->Add(object_result.Get());
Sebastien Hertz1558b572015-02-25 15:05:59 +01004090 } else {
4091 // Primitive result.
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004092 DCHECK(IsPrimitiveTag(result_tag));
4093 result_value = result.GetJ();
4094 }
4095 const bool is_constructor = m->IsConstructor() && !m->IsStatic();
4096 if (is_constructor) {
4097 // If we invoked a constructor (which actually returns void), return the receiver,
4098 // unless we threw, in which case we return null.
Sebastien Hertza3e13772015-11-05 12:09:44 +01004099 DCHECK_EQ(JDWP::JT_VOID, result_tag);
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004100 if (exceptionObjectId == 0) {
Jeff Hao064d24e2016-08-25 03:52:40 +00004101 if (m->GetDeclaringClass()->IsStringClass()) {
4102 // For string constructors, the new string is remapped to the receiver (stored in ref).
4103 Handle<mirror::Object> decoded_ref = hs.NewHandle(soa.Self()->DecodeJObject(ref.get()));
4104 result_value = gRegistry->Add(decoded_ref);
4105 result_tag = TagFromObject(soa, decoded_ref.Get());
4106 } else {
4107 // TODO we could keep the receiver ObjectId in the DebugInvokeReq to avoid looking into the
4108 // object registry.
4109 result_value = GetObjectRegistry()->Add(pReq->receiver.Read());
4110 result_tag = TagFromObject(soa, pReq->receiver.Read());
4111 }
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004112 } else {
4113 result_value = 0;
Sebastien Hertza3e13772015-11-05 12:09:44 +01004114 result_tag = JDWP::JT_OBJECT;
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004115 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08004116 }
4117
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004118 // Suspend other threads if the invoke is not single-threaded.
4119 if ((pReq->options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07004120 ScopedThreadSuspension sts(soa.Self(), kWaitingForDebuggerSuspension);
Hiroshi Yamauchi8f95cf32016-04-19 11:14:06 -07004121 // Avoid a deadlock between GC and debugger where GC gets suspended during GC. b/25800335.
4122 gc::ScopedGCCriticalSection gcs(soa.Self(), gc::kGcCauseDebugger, gc::kCollectorTypeDebugger);
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004123 VLOG(jdwp) << " Suspending all threads";
4124 Runtime::Current()->GetThreadList()->SuspendAllForDebugger();
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004125 }
4126
4127 VLOG(jdwp) << " --> returned " << result_tag
4128 << StringPrintf(" %#" PRIx64 " (except=%#" PRIx64 ")", result_value,
4129 exceptionObjectId);
4130
4131 // Show detailed debug output.
4132 if (result_tag == JDWP::JT_STRING && exceptionObjectId == 0) {
4133 if (result_value != 0) {
4134 if (VLOG_IS_ON(jdwp)) {
4135 std::string result_string;
4136 JDWP::JdwpError error = Dbg::StringToUtf8(result_value, &result_string);
4137 CHECK_EQ(error, JDWP::ERR_NONE);
4138 VLOG(jdwp) << " string '" << result_string << "'";
4139 }
4140 } else {
4141 VLOG(jdwp) << " string (null)";
4142 }
4143 }
4144
4145 // Attach the reply to DebugInvokeReq so it can be sent to the debugger when the event thread
4146 // is ready to suspend.
4147 BuildInvokeReply(pReq->reply, pReq->request_id, result_tag, result_value, exceptionObjectId);
4148}
4149
4150void Dbg::BuildInvokeReply(JDWP::ExpandBuf* pReply, uint32_t request_id, JDWP::JdwpTag result_tag,
4151 uint64_t result_value, JDWP::ObjectId exception) {
4152 // Make room for the JDWP header since we do not know the size of the reply yet.
4153 JDWP::expandBufAddSpace(pReply, kJDWPHeaderLen);
4154
4155 size_t width = GetTagWidth(result_tag);
4156 JDWP::expandBufAdd1(pReply, result_tag);
4157 if (width != 0) {
4158 WriteValue(pReply, width, result_value);
4159 }
4160 JDWP::expandBufAdd1(pReply, JDWP::JT_OBJECT);
4161 JDWP::expandBufAddObjectId(pReply, exception);
4162
4163 // Now we know the size, we can complete the JDWP header.
4164 uint8_t* buf = expandBufGetBuffer(pReply);
4165 JDWP::Set4BE(buf + kJDWPHeaderSizeOffset, expandBufGetLength(pReply));
4166 JDWP::Set4BE(buf + kJDWPHeaderIdOffset, request_id);
4167 JDWP::Set1(buf + kJDWPHeaderFlagsOffset, kJDWPFlagReply); // flags
4168 JDWP::Set2BE(buf + kJDWPHeaderErrorCodeOffset, JDWP::ERR_NONE);
4169}
4170
4171void Dbg::FinishInvokeMethod(DebugInvokeReq* pReq) {
4172 CHECK_NE(Thread::Current(), GetDebugThread()) << "This must be called by the event thread";
4173
4174 JDWP::ExpandBuf* const pReply = pReq->reply;
4175 CHECK(pReply != nullptr) << "No reply attached to DebugInvokeReq";
4176
4177 // We need to prevent other threads (including JDWP thread) from interacting with the debugger
4178 // while we send the reply but are not yet suspended. The JDWP token will be released just before
4179 // we suspend ourself again (see ThreadList::SuspendSelfForDebugger).
4180 gJdwpState->AcquireJdwpTokenForEvent(pReq->thread_id);
4181
4182 // Send the reply unless the debugger detached before the completion of the method.
4183 if (IsDebuggerActive()) {
4184 const size_t replyDataLength = expandBufGetLength(pReply) - kJDWPHeaderLen;
4185 VLOG(jdwp) << StringPrintf("REPLY INVOKE id=0x%06x (length=%zu)",
4186 pReq->request_id, replyDataLength);
4187
4188 gJdwpState->SendRequest(pReply);
4189 } else {
4190 VLOG(jdwp) << "Not sending invoke reply because debugger detached";
Elliott Hughesd07986f2011-12-06 18:27:45 -08004191 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004192}
4193
Alex Light8c2b9292017-11-09 13:21:01 -08004194bool Dbg::DdmHandleChunk(JNIEnv* env,
4195 uint32_t type,
4196 const ArrayRef<const jbyte>& data,
4197 /*out*/uint32_t* out_type,
4198 /*out*/std::vector<uint8_t>* out_data) {
4199 ScopedLocalRef<jbyteArray> dataArray(env, env->NewByteArray(data.size()));
Ian Rogersc0542af2014-09-03 16:16:56 -07004200 if (dataArray.get() == nullptr) {
Alex Light8c2b9292017-11-09 13:21:01 -08004201 LOG(WARNING) << "byte[] allocation failed: " << data.size();
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004202 env->ExceptionClear();
4203 return false;
4204 }
Alex Light8c2b9292017-11-09 13:21:01 -08004205 env->SetByteArrayRegion(dataArray.get(),
4206 0,
4207 data.size(),
4208 reinterpret_cast<const jbyte*>(data.data()));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004209 // Call "private static Chunk dispatch(int type, byte[] data, int offset, int length)".
Alex Light8c2b9292017-11-09 13:21:01 -08004210 ScopedLocalRef<jobject> chunk(
4211 env,
4212 env->CallStaticObjectMethod(
4213 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
4214 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_dispatch,
4215 type, dataArray.get(), 0, data.size()));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004216 if (env->ExceptionCheck()) {
Alex Light1eeefa62018-03-19 13:47:56 -07004217 Thread* self = Thread::Current();
4218 ScopedObjectAccess soa(self);
4219 LOG(INFO) << StringPrintf("Exception thrown by dispatcher for 0x%08x", type) << std::endl
4220 << self->GetException()->Dump();
4221 self->ClearException();
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004222 return false;
4223 }
4224
Ian Rogersc0542af2014-09-03 16:16:56 -07004225 if (chunk.get() == nullptr) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004226 return false;
4227 }
4228
4229 /*
4230 * Pull the pieces out of the chunk. We copy the results into a
4231 * newly-allocated buffer that the caller can free. We don't want to
4232 * continue using the Chunk object because nothing has a reference to it.
4233 *
4234 * We could avoid this by returning type/data/offset/length and having
4235 * the caller be aware of the object lifetime issues, but that
Elliott Hughes81ff3182012-03-23 20:35:56 -07004236 * integrates the JDWP code more tightly into the rest of the runtime, and doesn't work
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004237 * if we have responses for multiple chunks.
4238 *
4239 * So we're pretty much stuck with copying data around multiple times.
4240 */
Alex Light8c2b9292017-11-09 13:21:01 -08004241 ScopedLocalRef<jbyteArray> replyData(
4242 env,
4243 reinterpret_cast<jbyteArray>(
4244 env->GetObjectField(
4245 chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_data)));
4246 jint offset = env->GetIntField(chunk.get(),
4247 WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_offset);
4248 jint length = env->GetIntField(chunk.get(),
4249 WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_length);
4250 *out_type = env->GetIntField(chunk.get(),
4251 WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_type);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004252
Alex Light8c2b9292017-11-09 13:21:01 -08004253 VLOG(jdwp) << StringPrintf("DDM reply: type=0x%08x data=%p offset=%d length=%d",
4254 type,
4255 replyData.get(),
4256 offset,
4257 length);
Alex Light8c2b9292017-11-09 13:21:01 -08004258 out_data->resize(length);
4259 env->GetByteArrayRegion(replyData.get(),
4260 offset,
4261 length,
4262 reinterpret_cast<jbyte*>(out_data->data()));
Alex Light6f2a6342017-12-12 09:55:05 -08004263
Alex Lighte5463a82017-12-12 13:33:28 -08004264 if (env->ExceptionCheck()) {
Alex Light1eeefa62018-03-19 13:47:56 -07004265 Thread* self = Thread::Current();
4266 ScopedObjectAccess soa(self);
Alex Lighte5463a82017-12-12 13:33:28 -08004267 LOG(INFO) << StringPrintf("Exception thrown when reading response data from dispatcher 0x%08x",
Alex Light1eeefa62018-03-19 13:47:56 -07004268 type) << std::endl << self->GetException()->Dump();
4269 self->ClearException();
Alex Lighte5463a82017-12-12 13:33:28 -08004270 return false;
4271 }
4272
Alex Light8c2b9292017-11-09 13:21:01 -08004273 return true;
4274}
4275
4276/*
4277 * "request" contains a full JDWP packet, possibly with multiple chunks. We
4278 * need to process each, accumulate the replies, and ship the whole thing
4279 * back.
4280 *
4281 * Returns "true" if we have a reply. The reply buffer is newly allocated,
4282 * and includes the chunk type/length, followed by the data.
4283 *
4284 * OLD-TODO: we currently assume that the request and reply include a single
4285 * chunk. If this becomes inconvenient we will need to adapt.
4286 */
4287bool Dbg::DdmHandlePacket(JDWP::Request* request, uint8_t** pReplyBuf, int* pReplyLen) {
4288 Thread* self = Thread::Current();
4289 JNIEnv* env = self->GetJniEnv();
4290
4291 uint32_t type = request->ReadUnsigned32("type");
4292 uint32_t length = request->ReadUnsigned32("length");
4293
4294 // Create a byte[] corresponding to 'request'.
4295 size_t request_length = request->size();
4296 // Run through and find all chunks. [Currently just find the first.]
4297 if (length != request_length) {
4298 LOG(WARNING) << StringPrintf("bad chunk found (len=%u pktLen=%zd)", length, request_length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004299 return false;
4300 }
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004301
Alex Light8c2b9292017-11-09 13:21:01 -08004302 ArrayRef<const jbyte> data(reinterpret_cast<const jbyte*>(request->data()), request_length);
4303 std::vector<uint8_t> out_data;
4304 uint32_t out_type = 0;
4305 request->Skip(request_length);
Alex Light6f2a6342017-12-12 09:55:05 -08004306 if (!DdmHandleChunk(env, type, data, &out_type, &out_data) || out_data.empty()) {
Alex Light8c2b9292017-11-09 13:21:01 -08004307 return false;
4308 }
4309 const uint32_t kDdmHeaderSize = 8;
4310 *pReplyLen = out_data.size() + kDdmHeaderSize;
4311 *pReplyBuf = new uint8_t[out_data.size() + kDdmHeaderSize];
4312 memcpy((*pReplyBuf) + kDdmHeaderSize, out_data.data(), out_data.size());
4313 JDWP::Set4BE(*pReplyBuf, out_type);
4314 JDWP::Set4BE((*pReplyBuf) + 4, static_cast<uint32_t>(out_data.size()));
4315 VLOG(jdwp)
4316 << StringPrintf("dvmHandleDdm returning type=%.4s", reinterpret_cast<char*>(*pReplyBuf))
4317 << "0x" << std::hex << reinterpret_cast<uintptr_t>(*pReplyBuf) << std::dec
4318 << " len= " << out_data.size();
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004319 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004320}
4321
Elliott Hughesa2155262011-11-16 16:26:58 -08004322void Dbg::DdmBroadcast(bool connect) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08004323 VLOG(jdwp) << "Broadcasting DDM " << (connect ? "connect" : "disconnect") << "...";
Elliott Hughes47fce012011-10-25 18:37:19 -07004324
4325 Thread* self = Thread::Current();
Ian Rogers50b35e22012-10-04 10:09:15 -07004326 if (self->GetState() != kRunnable) {
4327 LOG(ERROR) << "DDM broadcast in thread state " << self->GetState();
4328 /* try anyway? */
Elliott Hughes47fce012011-10-25 18:37:19 -07004329 }
4330
4331 JNIEnv* env = self->GetJniEnv();
Elliott Hughes47fce012011-10-25 18:37:19 -07004332 jint event = connect ? 1 /*DdmServer.CONNECTED*/ : 2 /*DdmServer.DISCONNECTED*/;
Elliott Hugheseac76672012-05-24 21:56:51 -07004333 env->CallStaticVoidMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
4334 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_broadcast,
4335 event);
Elliott Hughes47fce012011-10-25 18:37:19 -07004336 if (env->ExceptionCheck()) {
4337 LOG(ERROR) << "DdmServer.broadcast " << event << " failed";
4338 env->ExceptionDescribe();
4339 env->ExceptionClear();
4340 }
4341}
4342
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004343void Dbg::DdmConnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08004344 Dbg::DdmBroadcast(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004345}
4346
4347void Dbg::DdmDisconnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08004348 Dbg::DdmBroadcast(false);
Elliott Hughes47fce012011-10-25 18:37:19 -07004349 gDdmThreadNotification = false;
4350}
4351
4352/*
Elliott Hughes82188472011-11-07 18:11:48 -08004353 * Send a notification when a thread starts, stops, or changes its name.
Elliott Hughes47fce012011-10-25 18:37:19 -07004354 *
4355 * Because we broadcast the full set of threads when the notifications are
4356 * first enabled, it's possible for "thread" to be actively executing.
4357 */
Elliott Hughes82188472011-11-07 18:11:48 -08004358void Dbg::DdmSendThreadNotification(Thread* t, uint32_t type) {
Elliott Hughes47fce012011-10-25 18:37:19 -07004359 if (!gDdmThreadNotification) {
4360 return;
4361 }
4362
Alex Light772099a2017-11-21 14:05:04 -08004363 RuntimeCallbacks* cb = Runtime::Current()->GetRuntimeCallbacks();
Elliott Hughes82188472011-11-07 18:11:48 -08004364 if (type == CHUNK_TYPE("THDE")) {
Elliott Hughes47fce012011-10-25 18:37:19 -07004365 uint8_t buf[4];
Ian Rogersd9c4fc92013-10-01 19:45:43 -07004366 JDWP::Set4BE(&buf[0], t->GetThreadId());
Alex Light772099a2017-11-21 14:05:04 -08004367 cb->DdmPublishChunk(CHUNK_TYPE("THDE"), ArrayRef<const uint8_t>(buf));
Elliott Hughes82188472011-11-07 18:11:48 -08004368 } else {
4369 CHECK(type == CHUNK_TYPE("THCR") || type == CHUNK_TYPE("THNM")) << type;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004370 ScopedObjectAccessUnchecked soa(Thread::Current());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004371 StackHandleScope<1> hs(soa.Self());
Andreas Gampe08883de2016-11-08 13:20:52 -08004372 Handle<mirror::String> name(hs.NewHandle(t->GetThreadName()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004373 size_t char_count = (name != nullptr) ? name->GetLength() : 0;
4374 const jchar* chars = (name != nullptr) ? name->GetValue() : nullptr;
4375 bool is_compressed = (name != nullptr) ? name->IsCompressed() : false;
Elliott Hughes82188472011-11-07 18:11:48 -08004376
Elliott Hughes21f32d72011-11-09 17:44:13 -08004377 std::vector<uint8_t> bytes;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07004378 JDWP::Append4BE(bytes, t->GetThreadId());
jessicahandojo3aaa37b2016-07-29 14:46:37 -07004379 if (is_compressed) {
4380 const uint8_t* chars_compressed = name->GetValueCompressed();
4381 JDWP::AppendUtf16CompressedBE(bytes, chars_compressed, char_count);
4382 } else {
4383 JDWP::AppendUtf16BE(bytes, chars, char_count);
4384 }
Elliott Hughes21f32d72011-11-09 17:44:13 -08004385 CHECK_EQ(bytes.size(), char_count*2 + sizeof(uint32_t)*2);
Alex Light772099a2017-11-21 14:05:04 -08004386 cb->DdmPublishChunk(type, ArrayRef<const uint8_t>(bytes));
Elliott Hughes47fce012011-10-25 18:37:19 -07004387 }
4388}
4389
Elliott Hughes47fce012011-10-25 18:37:19 -07004390void Dbg::DdmSetThreadNotification(bool enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004391 // Enable/disable thread notifications.
Elliott Hughes47fce012011-10-25 18:37:19 -07004392 gDdmThreadNotification = enable;
4393 if (enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004394 // Suspend the VM then post thread start notifications for all threads. Threads attaching will
4395 // see a suspension in progress and block until that ends. They then post their own start
4396 // notification.
4397 SuspendVM();
4398 std::list<Thread*> threads;
Ian Rogers50b35e22012-10-04 10:09:15 -07004399 Thread* self = Thread::Current();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004400 {
Ian Rogers50b35e22012-10-04 10:09:15 -07004401 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004402 threads = Runtime::Current()->GetThreadList()->GetList();
4403 }
4404 {
Ian Rogers50b35e22012-10-04 10:09:15 -07004405 ScopedObjectAccess soa(self);
Mathieu Chartier02e25112013-08-14 16:14:24 -07004406 for (Thread* thread : threads) {
4407 Dbg::DdmSendThreadNotification(thread, CHUNK_TYPE("THCR"));
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004408 }
4409 }
4410 ResumeVM();
Elliott Hughes47fce012011-10-25 18:37:19 -07004411 }
4412}
4413
Elliott Hughesa2155262011-11-16 16:26:58 -08004414void Dbg::PostThreadStartOrStop(Thread* t, uint32_t type) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07004415 if (IsDebuggerActive()) {
Sebastien Hertz6995c602014-09-09 12:10:13 +02004416 gJdwpState->PostThreadChange(t, type == CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07004417 }
Elliott Hughes82188472011-11-07 18:11:48 -08004418 Dbg::DdmSendThreadNotification(t, type);
Elliott Hughes47fce012011-10-25 18:37:19 -07004419}
4420
4421void Dbg::PostThreadStart(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004422 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07004423}
4424
4425void Dbg::PostThreadDeath(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004426 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THDE"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004427}
4428
Mathieu Chartierad466ad2015-01-08 16:28:08 -08004429JDWP::JdwpState* Dbg::GetJdwpState() {
4430 return gJdwpState;
4431}
4432
Elliott Hughes767a1472011-10-26 18:49:02 -07004433int Dbg::DdmHandleHpifChunk(HpifWhen when) {
4434 if (when == HPIF_WHEN_NOW) {
Elliott Hughes7162ad92011-10-27 14:08:42 -07004435 DdmSendHeapInfo(when);
Elliott Hughes767a1472011-10-26 18:49:02 -07004436 return true;
4437 }
4438
4439 if (when != HPIF_WHEN_NEVER && when != HPIF_WHEN_NEXT_GC && when != HPIF_WHEN_EVERY_GC) {
4440 LOG(ERROR) << "invalid HpifWhen value: " << static_cast<int>(when);
4441 return false;
4442 }
4443
4444 gDdmHpifWhen = when;
4445 return true;
4446}
4447
4448bool Dbg::DdmHandleHpsgNhsgChunk(Dbg::HpsgWhen when, Dbg::HpsgWhat what, bool native) {
4449 if (when != HPSG_WHEN_NEVER && when != HPSG_WHEN_EVERY_GC) {
4450 LOG(ERROR) << "invalid HpsgWhen value: " << static_cast<int>(when);
4451 return false;
4452 }
4453
4454 if (what != HPSG_WHAT_MERGED_OBJECTS && what != HPSG_WHAT_DISTINCT_OBJECTS) {
4455 LOG(ERROR) << "invalid HpsgWhat value: " << static_cast<int>(what);
4456 return false;
4457 }
4458
4459 if (native) {
4460 gDdmNhsgWhen = when;
4461 gDdmNhsgWhat = what;
4462 } else {
4463 gDdmHpsgWhen = when;
4464 gDdmHpsgWhat = what;
4465 }
4466 return true;
4467}
4468
Elliott Hughes7162ad92011-10-27 14:08:42 -07004469void Dbg::DdmSendHeapInfo(HpifWhen reason) {
4470 // If there's a one-shot 'when', reset it.
4471 if (reason == gDdmHpifWhen) {
4472 if (gDdmHpifWhen == HPIF_WHEN_NEXT_GC) {
4473 gDdmHpifWhen = HPIF_WHEN_NEVER;
4474 }
4475 }
4476
4477 /*
4478 * Chunk HPIF (client --> server)
4479 *
4480 * Heap Info. General information about the heap,
4481 * suitable for a summary display.
4482 *
4483 * [u4]: number of heaps
4484 *
4485 * For each heap:
4486 * [u4]: heap ID
4487 * [u8]: timestamp in ms since Unix epoch
4488 * [u1]: capture reason (same as 'when' value from server)
4489 * [u4]: max heap size in bytes (-Xmx)
4490 * [u4]: current heap size in bytes
4491 * [u4]: current number of bytes allocated
4492 * [u4]: current number of objects allocated
4493 */
4494 uint8_t heap_count = 1;
Ian Rogers1d54e732013-05-02 21:10:01 -07004495 gc::Heap* heap = Runtime::Current()->GetHeap();
Elliott Hughes21f32d72011-11-09 17:44:13 -08004496 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08004497 JDWP::Append4BE(bytes, heap_count);
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004498 JDWP::Append4BE(bytes, 1); // Heap id (bogus; we only have one heap).
Elliott Hughes545a0642011-11-08 19:10:03 -08004499 JDWP::Append8BE(bytes, MilliTime());
4500 JDWP::Append1BE(bytes, reason);
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004501 JDWP::Append4BE(bytes, heap->GetMaxMemory()); // Max allowed heap size in bytes.
4502 JDWP::Append4BE(bytes, heap->GetTotalMemory()); // Current heap size in bytes.
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08004503 JDWP::Append4BE(bytes, heap->GetBytesAllocated());
4504 JDWP::Append4BE(bytes, heap->GetObjectsAllocated());
Elliott Hughes21f32d72011-11-09 17:44:13 -08004505 CHECK_EQ(bytes.size(), 4U + (heap_count * (4 + 8 + 1 + 4 + 4 + 4 + 4)));
Alex Light772099a2017-11-21 14:05:04 -08004506 Runtime::Current()->GetRuntimeCallbacks()->DdmPublishChunk(CHUNK_TYPE("HPIF"),
4507 ArrayRef<const uint8_t>(bytes));
Elliott Hughes767a1472011-10-26 18:49:02 -07004508}
4509
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004510enum HpsgSolidity {
4511 SOLIDITY_FREE = 0,
4512 SOLIDITY_HARD = 1,
4513 SOLIDITY_SOFT = 2,
4514 SOLIDITY_WEAK = 3,
4515 SOLIDITY_PHANTOM = 4,
4516 SOLIDITY_FINALIZABLE = 5,
4517 SOLIDITY_SWEEP = 6,
4518};
4519
4520enum HpsgKind {
4521 KIND_OBJECT = 0,
4522 KIND_CLASS_OBJECT = 1,
4523 KIND_ARRAY_1 = 2,
4524 KIND_ARRAY_2 = 3,
4525 KIND_ARRAY_4 = 4,
4526 KIND_ARRAY_8 = 5,
4527 KIND_UNKNOWN = 6,
4528 KIND_NATIVE = 7,
4529};
4530
4531#define HPSG_PARTIAL (1<<7)
4532#define HPSG_STATE(solidity, kind) ((uint8_t)((((kind) & 0x7) << 3) | ((solidity) & 0x7)))
4533
Ian Rogers30fab402012-01-23 15:43:46 -08004534class HeapChunkContext {
4535 public:
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004536 // Maximum chunk size. Obtain this from the formula:
4537 // (((maximum_heap_size / ALLOCATION_UNIT_SIZE) + 255) / 256) * 2
4538 HeapChunkContext(bool merge, bool native)
Ian Rogers30fab402012-01-23 15:43:46 -08004539 : buf_(16384 - 16),
4540 type_(0),
Mathieu Chartier36dab362014-07-30 14:59:56 -07004541 chunk_overhead_(0) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004542 Reset();
4543 if (native) {
Ian Rogers30fab402012-01-23 15:43:46 -08004544 type_ = CHUNK_TYPE("NHSG");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004545 } else {
Ian Rogers30fab402012-01-23 15:43:46 -08004546 type_ = merge ? CHUNK_TYPE("HPSG") : CHUNK_TYPE("HPSO");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004547 }
4548 }
4549
4550 ~HeapChunkContext() {
Ian Rogers30fab402012-01-23 15:43:46 -08004551 if (p_ > &buf_[0]) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004552 Flush();
4553 }
4554 }
4555
Mathieu Chartier36dab362014-07-30 14:59:56 -07004556 void SetChunkOverhead(size_t chunk_overhead) {
4557 chunk_overhead_ = chunk_overhead;
4558 }
4559
4560 void ResetStartOfNextChunk() {
4561 startOfNextMemoryChunk_ = nullptr;
4562 }
4563
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004564 void EnsureHeader(const void* chunk_ptr) {
Ian Rogers30fab402012-01-23 15:43:46 -08004565 if (!needHeader_) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004566 return;
4567 }
4568
4569 // Start a new HPSx chunk.
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004570 JDWP::Write4BE(&p_, 1); // Heap id (bogus; we only have one heap).
4571 JDWP::Write1BE(&p_, 8); // Size of allocation unit, in bytes.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004572
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004573 JDWP::Write4BE(&p_, reinterpret_cast<uintptr_t>(chunk_ptr)); // virtual address of segment start.
4574 JDWP::Write4BE(&p_, 0); // offset of this piece (relative to the virtual address).
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004575 // [u4]: length of piece, in allocation units
4576 // 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 -08004577 pieceLenField_ = p_;
4578 JDWP::Write4BE(&p_, 0x55555555);
4579 needHeader_ = false;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004580 }
4581
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004582 void Flush() REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -07004583 if (pieceLenField_ == nullptr) {
Ian Rogersd636b062013-01-18 17:51:18 -08004584 // Flush immediately post Reset (maybe back-to-back Flush). Ignore.
4585 CHECK(needHeader_);
4586 return;
4587 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004588 // Patch the "length of piece" field.
Ian Rogers30fab402012-01-23 15:43:46 -08004589 CHECK_LE(&buf_[0], pieceLenField_);
4590 CHECK_LE(pieceLenField_, p_);
4591 JDWP::Set4BE(pieceLenField_, totalAllocationUnits_);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004592
Alex Light772099a2017-11-21 14:05:04 -08004593 ArrayRef<const uint8_t> out(&buf_[0], p_ - &buf_[0]);
4594 Runtime::Current()->GetRuntimeCallbacks()->DdmPublishChunk(type_, out);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004595 Reset();
4596 }
4597
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004598 static void HeapChunkJavaCallback(void* start, void* end, size_t used_bytes, void* arg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004599 REQUIRES_SHARED(Locks::heap_bitmap_lock_,
Ian Rogersb726dcb2012-09-05 08:57:23 -07004600 Locks::mutator_lock_) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004601 reinterpret_cast<HeapChunkContext*>(arg)->HeapChunkJavaCallback(start, end, used_bytes);
4602 }
4603
4604 static void HeapChunkNativeCallback(void* start, void* end, size_t used_bytes, void* arg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004605 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004606 reinterpret_cast<HeapChunkContext*>(arg)->HeapChunkNativeCallback(start, end, used_bytes);
Elliott Hughesa2155262011-11-16 16:26:58 -08004607 }
4608
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004609 private:
Elliott Hughesa2155262011-11-16 16:26:58 -08004610 enum { ALLOCATION_UNIT_SIZE = 8 };
4611
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004612 void Reset() {
Ian Rogers30fab402012-01-23 15:43:46 -08004613 p_ = &buf_[0];
Mathieu Chartier36dab362014-07-30 14:59:56 -07004614 ResetStartOfNextChunk();
Ian Rogers30fab402012-01-23 15:43:46 -08004615 totalAllocationUnits_ = 0;
4616 needHeader_ = true;
Ian Rogersc0542af2014-09-03 16:16:56 -07004617 pieceLenField_ = nullptr;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004618 }
4619
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004620 bool IsNative() const {
4621 return type_ == CHUNK_TYPE("NHSG");
4622 }
4623
4624 // Returns true if the object is not an empty chunk.
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004625 bool ProcessRecord(void* start, size_t used_bytes) REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers30fab402012-01-23 15:43:46 -08004626 // Note: heap call backs cannot manipulate the heap upon which they are crawling, care is taken
4627 // in the following code not to allocate memory, by ensuring buf_ is of the correct size
Ian Rogers15bf2d32012-08-28 17:33:04 -07004628 if (used_bytes == 0) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004629 if (start == nullptr) {
4630 // Reset for start of new heap.
4631 startOfNextMemoryChunk_ = nullptr;
4632 Flush();
4633 }
4634 // Only process in use memory so that free region information
4635 // also includes dlmalloc book keeping.
4636 return false;
Elliott Hughesa2155262011-11-16 16:26:58 -08004637 }
Ian Rogersc0542af2014-09-03 16:16:56 -07004638 if (startOfNextMemoryChunk_ != nullptr) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004639 // Transmit any pending free memory. Native free memory of over kMaxFreeLen could be because
4640 // of the use of mmaps, so don't report. If not free memory then start a new segment.
4641 bool flush = true;
4642 if (start > startOfNextMemoryChunk_) {
4643 const size_t kMaxFreeLen = 2 * kPageSize;
4644 void* free_start = startOfNextMemoryChunk_;
4645 void* free_end = start;
4646 const size_t free_len =
4647 reinterpret_cast<uintptr_t>(free_end) - reinterpret_cast<uintptr_t>(free_start);
4648 if (!IsNative() || free_len < kMaxFreeLen) {
4649 AppendChunk(HPSG_STATE(SOLIDITY_FREE, 0), free_start, free_len, IsNative());
4650 flush = false;
Ian Rogers15bf2d32012-08-28 17:33:04 -07004651 }
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004652 }
4653 if (flush) {
4654 startOfNextMemoryChunk_ = nullptr;
4655 Flush();
4656 }
Ian Rogers15bf2d32012-08-28 17:33:04 -07004657 }
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004658 return true;
Ian Rogers15bf2d32012-08-28 17:33:04 -07004659 }
Elliott Hughesa2155262011-11-16 16:26:58 -08004660
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004661 void HeapChunkNativeCallback(void* start, void* /*end*/, size_t used_bytes)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004662 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004663 if (ProcessRecord(start, used_bytes)) {
4664 uint8_t state = ExamineNativeObject(start);
Andreas Gampe98ea9d92018-10-19 14:06:15 -07004665 AppendChunk(state, start, used_bytes + chunk_overhead_, /*is_native=*/ true);
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004666 startOfNextMemoryChunk_ = reinterpret_cast<char*>(start) + used_bytes + chunk_overhead_;
4667 }
4668 }
4669
4670 void HeapChunkJavaCallback(void* start, void* /*end*/, size_t used_bytes)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004671 REQUIRES_SHARED(Locks::heap_bitmap_lock_, Locks::mutator_lock_) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004672 if (ProcessRecord(start, used_bytes)) {
4673 // Determine the type of this chunk.
4674 // OLD-TODO: if context.merge, see if this chunk is different from the last chunk.
4675 // If it's the same, we should combine them.
4676 uint8_t state = ExamineJavaObject(reinterpret_cast<mirror::Object*>(start));
Andreas Gampe98ea9d92018-10-19 14:06:15 -07004677 AppendChunk(state, start, used_bytes + chunk_overhead_, /*is_native=*/ false);
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004678 startOfNextMemoryChunk_ = reinterpret_cast<char*>(start) + used_bytes + chunk_overhead_;
4679 }
4680 }
4681
4682 void AppendChunk(uint8_t state, void* ptr, size_t length, bool is_native)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004683 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07004684 // Make sure there's enough room left in the buffer.
4685 // We need to use two bytes for every fractional 256 allocation units used by the chunk plus
4686 // 17 bytes for any header.
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004687 const size_t needed = ((RoundUp(length / ALLOCATION_UNIT_SIZE, 256) / 256) * 2) + 17;
4688 size_t byte_left = &buf_.back() - p_;
4689 if (byte_left < needed) {
4690 if (is_native) {
Pavel Vyssotski7522c742014-12-08 13:38:26 +06004691 // Cannot trigger memory allocation while walking native heap.
Pavel Vyssotski7522c742014-12-08 13:38:26 +06004692 return;
4693 }
Ian Rogers15bf2d32012-08-28 17:33:04 -07004694 Flush();
4695 }
4696
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004697 byte_left = &buf_.back() - p_;
4698 if (byte_left < needed) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07004699 LOG(WARNING) << "Chunk is too big to transmit (chunk_len=" << length << ", "
4700 << needed << " bytes)";
4701 return;
4702 }
4703 EnsureHeader(ptr);
Elliott Hughesa2155262011-11-16 16:26:58 -08004704 // Write out the chunk description.
Ian Rogers15bf2d32012-08-28 17:33:04 -07004705 length /= ALLOCATION_UNIT_SIZE; // Convert to allocation units.
4706 totalAllocationUnits_ += length;
4707 while (length > 256) {
Ian Rogers30fab402012-01-23 15:43:46 -08004708 *p_++ = state | HPSG_PARTIAL;
4709 *p_++ = 255; // length - 1
Ian Rogers15bf2d32012-08-28 17:33:04 -07004710 length -= 256;
Elliott Hughesa2155262011-11-16 16:26:58 -08004711 }
Ian Rogers30fab402012-01-23 15:43:46 -08004712 *p_++ = state;
Ian Rogers15bf2d32012-08-28 17:33:04 -07004713 *p_++ = length - 1;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004714 }
4715
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004716 uint8_t ExamineNativeObject(const void* p) REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004717 return p == nullptr ? HPSG_STATE(SOLIDITY_FREE, 0) : HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
4718 }
4719
4720 uint8_t ExamineJavaObject(mirror::Object* o)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004721 REQUIRES_SHARED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -07004722 if (o == nullptr) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004723 return HPSG_STATE(SOLIDITY_FREE, 0);
4724 }
Elliott Hughesa2155262011-11-16 16:26:58 -08004725 // It's an allocated chunk. Figure out what it is.
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004726 gc::Heap* heap = Runtime::Current()->GetHeap();
4727 if (!heap->IsLiveObjectLocked(o)) {
4728 LOG(ERROR) << "Invalid object in managed heap: " << o;
Elliott Hughesa2155262011-11-16 16:26:58 -08004729 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
4730 }
Vladimir Marko4617d582019-03-28 13:48:31 +00004731 ObjPtr<mirror::Class> c = o->GetClass();
Ian Rogersc0542af2014-09-03 16:16:56 -07004732 if (c == nullptr) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004733 // The object was probably just created but hasn't been initialized yet.
4734 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
4735 }
Vladimir Marko4617d582019-03-28 13:48:31 +00004736 if (!heap->IsValidObjectAddress(c.Ptr())) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07004737 LOG(ERROR) << "Invalid class for managed heap object: " << o << " " << c;
Elliott Hughesa2155262011-11-16 16:26:58 -08004738 return HPSG_STATE(SOLIDITY_HARD, KIND_UNKNOWN);
4739 }
Mathieu Chartierf26e1b32015-01-29 10:47:10 -08004740 if (c->GetClass() == nullptr) {
4741 LOG(ERROR) << "Null class of class " << c << " for object " << o;
4742 return HPSG_STATE(SOLIDITY_HARD, KIND_UNKNOWN);
4743 }
Elliott Hughesa2155262011-11-16 16:26:58 -08004744 if (c->IsClassClass()) {
4745 return HPSG_STATE(SOLIDITY_HARD, KIND_CLASS_OBJECT);
4746 }
Elliott Hughesa2155262011-11-16 16:26:58 -08004747 if (c->IsArrayClass()) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004748 switch (c->GetComponentSize()) {
4749 case 1: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_1);
4750 case 2: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_2);
4751 case 4: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
4752 case 8: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_8);
4753 }
4754 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004755 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
4756 }
4757
Ian Rogers30fab402012-01-23 15:43:46 -08004758 std::vector<uint8_t> buf_;
4759 uint8_t* p_;
4760 uint8_t* pieceLenField_;
Ian Rogers15bf2d32012-08-28 17:33:04 -07004761 void* startOfNextMemoryChunk_;
Ian Rogers30fab402012-01-23 15:43:46 -08004762 size_t totalAllocationUnits_;
4763 uint32_t type_;
Ian Rogers30fab402012-01-23 15:43:46 -08004764 bool needHeader_;
Mathieu Chartier36dab362014-07-30 14:59:56 -07004765 size_t chunk_overhead_;
Ian Rogers30fab402012-01-23 15:43:46 -08004766
Elliott Hughesa2155262011-11-16 16:26:58 -08004767 DISALLOW_COPY_AND_ASSIGN(HeapChunkContext);
4768};
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004769
4770void Dbg::DdmSendHeapSegments(bool native) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004771 Dbg::HpsgWhen when = native ? gDdmNhsgWhen : gDdmHpsgWhen;
4772 Dbg::HpsgWhat what = native ? gDdmNhsgWhat : gDdmHpsgWhat;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004773 if (when == HPSG_WHEN_NEVER) {
4774 return;
4775 }
Alex Light772099a2017-11-21 14:05:04 -08004776 RuntimeCallbacks* cb = Runtime::Current()->GetRuntimeCallbacks();
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004777 // Figure out what kind of chunks we'll be sending.
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004778 CHECK(what == HPSG_WHAT_MERGED_OBJECTS || what == HPSG_WHAT_DISTINCT_OBJECTS)
4779 << static_cast<int>(what);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004780
4781 // First, send a heap start chunk.
4782 uint8_t heap_id[4];
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004783 JDWP::Set4BE(&heap_id[0], 1); // Heap id (bogus; we only have one heap).
Alex Light772099a2017-11-21 14:05:04 -08004784 cb->DdmPublishChunk(native ? CHUNK_TYPE("NHST") : CHUNK_TYPE("HPST"),
4785 ArrayRef<const uint8_t>(heap_id));
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07004786 Thread* self = Thread::Current();
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07004787 Locks::mutator_lock_->AssertSharedHeld(self);
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07004788
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004789 // Send a series of heap segment chunks.
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004790 HeapChunkContext context(what == HPSG_WHAT_MERGED_OBJECTS, native);
Andreas Gampe0c183382017-07-13 22:26:24 -07004791 auto bump_pointer_space_visitor = [&](mirror::Object* obj)
4792 REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
4793 const size_t size = RoundUp(obj->SizeOf(), kObjectAlignment);
4794 HeapChunkContext::HeapChunkJavaCallback(
4795 obj, reinterpret_cast<void*>(reinterpret_cast<uintptr_t>(obj) + size), size, &context);
4796 };
Elliott Hughesa2155262011-11-16 16:26:58 -08004797 if (native) {
Dimitry Ivanove6465bc2015-12-14 18:55:02 -08004798 UNIMPLEMENTED(WARNING) << "Native heap inspection is not supported";
Elliott Hughesa2155262011-11-16 16:26:58 -08004799 } else {
Ian Rogers1d54e732013-05-02 21:10:01 -07004800 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartier36dab362014-07-30 14:59:56 -07004801 for (const auto& space : heap->GetContinuousSpaces()) {
4802 if (space->IsDlMallocSpace()) {
Mathieu Chartier4c69d7f2014-10-10 12:45:50 -07004803 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004804 // dlmalloc's chunk header is 2 * sizeof(size_t), but if the previous chunk is in use for an
4805 // allocation then the first sizeof(size_t) may belong to it.
4806 context.SetChunkOverhead(sizeof(size_t));
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004807 space->AsDlMallocSpace()->Walk(HeapChunkContext::HeapChunkJavaCallback, &context);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004808 } else if (space->IsRosAllocSpace()) {
4809 context.SetChunkOverhead(0);
Mathieu Chartier4c69d7f2014-10-10 12:45:50 -07004810 // Need to acquire the mutator lock before the heap bitmap lock with exclusive access since
4811 // RosAlloc's internal logic doesn't know to release and reacquire the heap bitmap lock.
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07004812 ScopedThreadSuspension sts(self, kSuspended);
Mathieu Chartier4f55e222015-09-04 13:26:21 -07004813 ScopedSuspendAll ssa(__FUNCTION__);
4814 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
4815 space->AsRosAllocSpace()->Walk(HeapChunkContext::HeapChunkJavaCallback, &context);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004816 } else if (space->IsBumpPointerSpace()) {
Mathieu Chartier4c69d7f2014-10-10 12:45:50 -07004817 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004818 context.SetChunkOverhead(0);
Andreas Gampe0c183382017-07-13 22:26:24 -07004819 space->AsBumpPointerSpace()->Walk(bump_pointer_space_visitor);
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004820 HeapChunkContext::HeapChunkJavaCallback(nullptr, nullptr, 0, &context);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08004821 } else if (space->IsRegionSpace()) {
4822 heap->IncrementDisableMovingGC(self);
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07004823 {
4824 ScopedThreadSuspension sts(self, kSuspended);
Mathieu Chartier4f55e222015-09-04 13:26:21 -07004825 ScopedSuspendAll ssa(__FUNCTION__);
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07004826 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
4827 context.SetChunkOverhead(0);
Andreas Gampe0c183382017-07-13 22:26:24 -07004828 space->AsRegionSpace()->Walk(bump_pointer_space_visitor);
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07004829 HeapChunkContext::HeapChunkJavaCallback(nullptr, nullptr, 0, &context);
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07004830 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08004831 heap->DecrementDisableMovingGC(self);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004832 } else {
4833 UNIMPLEMENTED(WARNING) << "Not counting objects in space " << *space;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07004834 }
Mathieu Chartier36dab362014-07-30 14:59:56 -07004835 context.ResetStartOfNextChunk();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07004836 }
Mathieu Chartier4c69d7f2014-10-10 12:45:50 -07004837 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07004838 // Walk the large objects, these are not in the AllocSpace.
Mathieu Chartier36dab362014-07-30 14:59:56 -07004839 context.SetChunkOverhead(0);
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004840 heap->GetLargeObjectsSpace()->Walk(HeapChunkContext::HeapChunkJavaCallback, &context);
Elliott Hughesa2155262011-11-16 16:26:58 -08004841 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004842
4843 // Finally, send a heap end chunk.
Alex Light772099a2017-11-21 14:05:04 -08004844 cb->DdmPublishChunk(native ? CHUNK_TYPE("NHEN") : CHUNK_TYPE("HPEN"),
4845 ArrayRef<const uint8_t>(heap_id));
Elliott Hughes767a1472011-10-26 18:49:02 -07004846}
4847
Brian Carlstrom306db812014-09-05 13:01:41 -07004848void Dbg::SetAllocTrackingEnabled(bool enable) {
Man Cao8c2ff642015-05-27 17:25:30 -07004849 gc::AllocRecordObjectMap::SetAllocTrackingEnabled(enable);
Elliott Hughes545a0642011-11-08 19:10:03 -08004850}
4851
4852void Dbg::DumpRecentAllocations() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004853 ScopedObjectAccess soa(Thread::Current());
Brian Carlstrom306db812014-09-05 13:01:41 -07004854 MutexLock mu(soa.Self(), *Locks::alloc_tracker_lock_);
Man Cao8c2ff642015-05-27 17:25:30 -07004855 if (!Runtime::Current()->GetHeap()->IsAllocTrackingEnabled()) {
Elliott Hughes545a0642011-11-08 19:10:03 -08004856 LOG(INFO) << "Not recording tracked allocations";
4857 return;
4858 }
Man Cao8c2ff642015-05-27 17:25:30 -07004859 gc::AllocRecordObjectMap* records = Runtime::Current()->GetHeap()->GetAllocationRecords();
4860 CHECK(records != nullptr);
Elliott Hughes545a0642011-11-08 19:10:03 -08004861
Man Cao1ed11b92015-06-11 22:47:35 -07004862 const uint16_t capped_count = CappedAllocRecordCount(records->GetRecentAllocationSize());
Brian Carlstrom306db812014-09-05 13:01:41 -07004863 uint16_t count = capped_count;
Elliott Hughes545a0642011-11-08 19:10:03 -08004864
Man Cao8c2ff642015-05-27 17:25:30 -07004865 LOG(INFO) << "Tracked allocations, (count=" << count << ")";
4866 for (auto it = records->RBegin(), end = records->REnd();
4867 count > 0 && it != end; count--, it++) {
Mathieu Chartier458b1052016-03-29 14:02:55 -07004868 const gc::AllocRecord* record = &it->second;
Elliott Hughes545a0642011-11-08 19:10:03 -08004869
Man Cao8c2ff642015-05-27 17:25:30 -07004870 LOG(INFO) << StringPrintf(" Thread %-2d %6zd bytes ", record->GetTid(), record->ByteCount())
David Sehr709b0702016-10-13 09:12:37 -07004871 << mirror::Class::PrettyClass(record->GetClass());
Elliott Hughes545a0642011-11-08 19:10:03 -08004872
Man Cao8c2ff642015-05-27 17:25:30 -07004873 for (size_t stack_frame = 0, depth = record->GetDepth(); stack_frame < depth; ++stack_frame) {
4874 const gc::AllocRecordStackTraceElement& stack_element = record->StackElement(stack_frame);
4875 ArtMethod* m = stack_element.GetMethod();
David Sehr709b0702016-10-13 09:12:37 -07004876 LOG(INFO) << " " << ArtMethod::PrettyMethod(m) << " line "
4877 << stack_element.ComputeLineNumber();
Elliott Hughes545a0642011-11-08 19:10:03 -08004878 }
4879
4880 // pause periodically to help logcat catch up
4881 if ((count % 5) == 0) {
4882 usleep(40000);
4883 }
Elliott Hughes545a0642011-11-08 19:10:03 -08004884 }
4885}
4886
4887class StringTable {
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07004888 private:
4889 struct Entry {
Andreas Gampe84eadb22017-07-07 15:08:01 -07004890 explicit Entry(const char* data_in)
4891 : data(data_in), hash(ComputeModifiedUtf8Hash(data_in)), index(0) {
4892 }
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07004893 Entry(const Entry& entry) = default;
4894 Entry(Entry&& entry) = default;
4895
4896 // Pointer to the actual string data.
4897 const char* data;
Andreas Gampe84eadb22017-07-07 15:08:01 -07004898
4899 // The hash of the data.
4900 const uint32_t hash;
4901
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07004902 // The index. This will be filled in on Finish and is not part of the ordering, so mark it
4903 // mutable.
4904 mutable uint32_t index;
4905
Andreas Gampe84eadb22017-07-07 15:08:01 -07004906 bool operator==(const Entry& other) const {
4907 return strcmp(data, other.data) == 0;
4908 }
4909 };
4910 struct EntryHash {
4911 size_t operator()(const Entry& entry) const {
4912 return entry.hash;
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07004913 }
4914 };
4915
Elliott Hughes545a0642011-11-08 19:10:03 -08004916 public:
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07004917 StringTable() : finished_(false) {
Elliott Hughes545a0642011-11-08 19:10:03 -08004918 }
4919
Andreas Gampef774a4e2017-07-06 22:15:18 -07004920 void Add(const char* str, bool copy_string) {
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07004921 DCHECK(!finished_);
Andreas Gampef774a4e2017-07-06 22:15:18 -07004922 if (UNLIKELY(copy_string)) {
4923 // Check whether it's already there.
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07004924 Entry entry(str);
4925 if (table_.find(entry) != table_.end()) {
Andreas Gampef774a4e2017-07-06 22:15:18 -07004926 return;
4927 }
Mathieu Chartier4345c462014-06-27 10:20:14 -07004928
Andreas Gampef774a4e2017-07-06 22:15:18 -07004929 // Make a copy.
4930 size_t str_len = strlen(str);
4931 char* copy = new char[str_len + 1];
4932 strlcpy(copy, str, str_len + 1);
4933 string_backup_.emplace_back(copy);
4934 str = copy;
4935 }
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07004936 Entry entry(str);
4937 table_.insert(entry);
4938 }
4939
4940 // Update all entries and give them an index. Note that this is likely not the insertion order,
4941 // as the set will with high likelihood reorder elements. Thus, Add must not be called after
4942 // Finish, and Finish must be called before IndexOf. In that case, WriteTo will walk in
4943 // the same order as Finish, and indices will agree. The order invariant, as well as indices,
4944 // are enforced through debug checks.
4945 void Finish() {
4946 DCHECK(!finished_);
4947 finished_ = true;
4948 uint32_t index = 0;
4949 for (auto& entry : table_) {
4950 entry.index = index;
4951 ++index;
4952 }
Elliott Hughes545a0642011-11-08 19:10:03 -08004953 }
4954
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004955 size_t IndexOf(const char* s) const {
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07004956 DCHECK(finished_);
4957 Entry entry(s);
4958 auto it = table_.find(entry);
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004959 if (it == table_.end()) {
4960 LOG(FATAL) << "IndexOf(\"" << s << "\") failed";
4961 }
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07004962 return it->index;
Elliott Hughes545a0642011-11-08 19:10:03 -08004963 }
4964
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004965 size_t Size() const {
Elliott Hughes545a0642011-11-08 19:10:03 -08004966 return table_.size();
4967 }
4968
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004969 void WriteTo(std::vector<uint8_t>& bytes) const {
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07004970 DCHECK(finished_);
4971 uint32_t cur_index = 0;
4972 for (const auto& entry : table_) {
4973 DCHECK_EQ(cur_index++, entry.index);
4974
4975 size_t s_len = CountModifiedUtf8Chars(entry.data);
Christopher Ferris8a354052015-04-24 17:23:53 -07004976 std::unique_ptr<uint16_t[]> s_utf16(new uint16_t[s_len]);
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07004977 ConvertModifiedUtf8ToUtf16(s_utf16.get(), entry.data);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004978 JDWP::AppendUtf16BE(bytes, s_utf16.get(), s_len);
Elliott Hughes545a0642011-11-08 19:10:03 -08004979 }
4980 }
4981
4982 private:
Andreas Gampe84eadb22017-07-07 15:08:01 -07004983 std::unordered_set<Entry, EntryHash> table_;
Andreas Gampef774a4e2017-07-06 22:15:18 -07004984 std::vector<std::unique_ptr<char[]>> string_backup_;
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07004985
4986 bool finished_;
4987
Elliott Hughes545a0642011-11-08 19:10:03 -08004988 DISALLOW_COPY_AND_ASSIGN(StringTable);
4989};
4990
Mathieu Chartiere401d142015-04-22 13:56:20 -07004991static const char* GetMethodSourceFile(ArtMethod* method)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004992 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004993 DCHECK(method != nullptr);
4994 const char* source_file = method->GetDeclaringClassSourceFile();
Sebastien Hertz280286a2014-04-28 09:26:50 +02004995 return (source_file != nullptr) ? source_file : "";
4996}
4997
Elliott Hughes545a0642011-11-08 19:10:03 -08004998/*
4999 * The data we send to DDMS contains everything we have recorded.
5000 *
5001 * Message header (all values big-endian):
5002 * (1b) message header len (to allow future expansion); includes itself
5003 * (1b) entry header len
5004 * (1b) stack frame len
5005 * (2b) number of entries
5006 * (4b) offset to string table from start of message
5007 * (2b) number of class name strings
5008 * (2b) number of method name strings
5009 * (2b) number of source file name strings
5010 * For each entry:
5011 * (4b) total allocation size
Elliott Hughes221229c2013-01-08 18:17:50 -08005012 * (2b) thread id
Elliott Hughes545a0642011-11-08 19:10:03 -08005013 * (2b) allocated object's class name index
5014 * (1b) stack depth
5015 * For each stack frame:
5016 * (2b) method's class name
5017 * (2b) method name
5018 * (2b) method source file
5019 * (2b) line number, clipped to 32767; -2 if native; -1 if no source
5020 * (xb) class name strings
5021 * (xb) method name strings
5022 * (xb) source file strings
5023 *
5024 * As with other DDM traffic, strings are sent as a 4-byte length
5025 * followed by UTF-16 data.
5026 *
5027 * We send up 16-bit unsigned indexes into string tables. In theory there
Brian Carlstrom306db812014-09-05 13:01:41 -07005028 * can be (kMaxAllocRecordStackDepth * alloc_record_max_) unique strings in
Elliott Hughes545a0642011-11-08 19:10:03 -08005029 * each table, but in practice there should be far fewer.
5030 *
5031 * The chief reason for using a string table here is to keep the size of
5032 * the DDMS message to a minimum. This is partly to make the protocol
5033 * efficient, but also because we have to form the whole thing up all at
5034 * once in a memory buffer.
5035 *
5036 * We use separate string tables for class names, method names, and source
5037 * files to keep the indexes small. There will generally be no overlap
5038 * between the contents of these tables.
5039 */
5040jbyteArray Dbg::GetRecentAllocations() {
Ian Rogerscf7f1912014-10-22 22:06:39 -07005041 if ((false)) {
Elliott Hughes545a0642011-11-08 19:10:03 -08005042 DumpRecentAllocations();
5043 }
5044
Ian Rogers50b35e22012-10-04 10:09:15 -07005045 Thread* self = Thread::Current();
Elliott Hughes545a0642011-11-08 19:10:03 -08005046 std::vector<uint8_t> bytes;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005047 {
Brian Carlstrom306db812014-09-05 13:01:41 -07005048 MutexLock mu(self, *Locks::alloc_tracker_lock_);
Man Cao8c2ff642015-05-27 17:25:30 -07005049 gc::AllocRecordObjectMap* records = Runtime::Current()->GetHeap()->GetAllocationRecords();
5050 // In case this method is called when allocation tracker is disabled,
5051 // we should still send some data back.
5052 gc::AllocRecordObjectMap dummy;
5053 if (records == nullptr) {
5054 CHECK(!Runtime::Current()->GetHeap()->IsAllocTrackingEnabled());
5055 records = &dummy;
5056 }
Man Cao41656de2015-07-06 18:53:15 -07005057 // We don't need to wait on the condition variable records->new_record_condition_, because this
5058 // function only reads the class objects, which are already marked so it doesn't change their
5059 // reachability.
Man Cao8c2ff642015-05-27 17:25:30 -07005060
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005061 //
5062 // Part 1: generate string tables.
5063 //
5064 StringTable class_names;
5065 StringTable method_names;
5066 StringTable filenames;
Elliott Hughes545a0642011-11-08 19:10:03 -08005067
Andreas Gampeff29cee2017-07-07 11:11:15 -07005068 VLOG(jdwp) << "Collecting StringTables.";
5069
Man Cao1ed11b92015-06-11 22:47:35 -07005070 const uint16_t capped_count = CappedAllocRecordCount(records->GetRecentAllocationSize());
Brian Carlstrom306db812014-09-05 13:01:41 -07005071 uint16_t count = capped_count;
Andreas Gamped0fc7682017-07-07 14:03:08 -07005072 size_t alloc_byte_count = 0;
Man Cao8c2ff642015-05-27 17:25:30 -07005073 for (auto it = records->RBegin(), end = records->REnd();
5074 count > 0 && it != end; count--, it++) {
Mathieu Chartier458b1052016-03-29 14:02:55 -07005075 const gc::AllocRecord* record = &it->second;
Ian Rogers1ff3c982014-08-12 02:30:58 -07005076 std::string temp;
Andreas Gampef774a4e2017-07-06 22:15:18 -07005077 const char* class_descr = record->GetClassDescriptor(&temp);
5078 class_names.Add(class_descr, !temp.empty());
Andreas Gamped0fc7682017-07-07 14:03:08 -07005079
5080 // Size + tid + class name index + stack depth.
5081 alloc_byte_count += 4u + 2u + 2u + 1u;
5082
Man Cao8c2ff642015-05-27 17:25:30 -07005083 for (size_t i = 0, depth = record->GetDepth(); i < depth; i++) {
5084 ArtMethod* m = record->StackElement(i).GetMethod();
Andreas Gampef774a4e2017-07-06 22:15:18 -07005085 class_names.Add(m->GetDeclaringClassDescriptor(), false);
5086 method_names.Add(m->GetName(), false);
5087 filenames.Add(GetMethodSourceFile(m), false);
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005088 }
Andreas Gamped0fc7682017-07-07 14:03:08 -07005089
5090 // Depth * (class index + method name index + file name index + line number).
5091 alloc_byte_count += record->GetDepth() * (2u + 2u + 2u + 2u);
Elliott Hughes545a0642011-11-08 19:10:03 -08005092 }
5093
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07005094 class_names.Finish();
5095 method_names.Finish();
5096 filenames.Finish();
Andreas Gampeff29cee2017-07-07 11:11:15 -07005097 VLOG(jdwp) << "Done collecting StringTables:" << std::endl
5098 << " ClassNames: " << class_names.Size() << std::endl
5099 << " MethodNames: " << method_names.Size() << std::endl
5100 << " Filenames: " << filenames.Size();
5101
Man Cao8c2ff642015-05-27 17:25:30 -07005102 LOG(INFO) << "recent allocation records: " << capped_count;
5103 LOG(INFO) << "allocation records all objects: " << records->Size();
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005104
5105 //
5106 // Part 2: Generate the output and store it in the buffer.
5107 //
5108
5109 // (1b) message header len (to allow future expansion); includes itself
5110 // (1b) entry header len
5111 // (1b) stack frame len
5112 const int kMessageHeaderLen = 15;
5113 const int kEntryHeaderLen = 9;
5114 const int kStackFrameLen = 8;
5115 JDWP::Append1BE(bytes, kMessageHeaderLen);
5116 JDWP::Append1BE(bytes, kEntryHeaderLen);
5117 JDWP::Append1BE(bytes, kStackFrameLen);
5118
5119 // (2b) number of entries
5120 // (4b) offset to string table from start of message
5121 // (2b) number of class name strings
5122 // (2b) number of method name strings
5123 // (2b) number of source file name strings
Brian Carlstrom306db812014-09-05 13:01:41 -07005124 JDWP::Append2BE(bytes, capped_count);
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005125 size_t string_table_offset = bytes.size();
Brian Carlstrom7934ac22013-07-26 10:54:15 -07005126 JDWP::Append4BE(bytes, 0); // We'll patch this later...
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005127 JDWP::Append2BE(bytes, class_names.Size());
5128 JDWP::Append2BE(bytes, method_names.Size());
5129 JDWP::Append2BE(bytes, filenames.Size());
5130
Andreas Gampeff29cee2017-07-07 11:11:15 -07005131 VLOG(jdwp) << "Dumping allocations with stacks";
5132
Andreas Gamped0fc7682017-07-07 14:03:08 -07005133 // Enlarge the vector for the allocation data.
5134 size_t reserve_size = bytes.size() + alloc_byte_count;
5135 bytes.reserve(reserve_size);
5136
Ian Rogers1ff3c982014-08-12 02:30:58 -07005137 std::string temp;
Man Cao8c2ff642015-05-27 17:25:30 -07005138 count = capped_count;
5139 // The last "count" number of allocation records in "records" are the most recent "count" number
5140 // of allocations. Reverse iterate to get them. The most recent allocation is sent first.
5141 for (auto it = records->RBegin(), end = records->REnd();
5142 count > 0 && it != end; count--, it++) {
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005143 // For each entry:
5144 // (4b) total allocation size
5145 // (2b) thread id
5146 // (2b) allocated object's class name index
5147 // (1b) stack depth
Mathieu Chartier458b1052016-03-29 14:02:55 -07005148 const gc::AllocRecord* record = &it->second;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005149 size_t stack_depth = record->GetDepth();
Mathieu Chartierf8322842014-05-16 10:59:25 -07005150 size_t allocated_object_class_name_index =
Man Cao41656de2015-07-06 18:53:15 -07005151 class_names.IndexOf(record->GetClassDescriptor(&temp));
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07005152 JDWP::Append4BE(bytes, record->ByteCount());
Man Cao8c2ff642015-05-27 17:25:30 -07005153 JDWP::Append2BE(bytes, static_cast<uint16_t>(record->GetTid()));
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005154 JDWP::Append2BE(bytes, allocated_object_class_name_index);
5155 JDWP::Append1BE(bytes, stack_depth);
5156
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005157 for (size_t stack_frame = 0; stack_frame < stack_depth; ++stack_frame) {
5158 // For each stack frame:
5159 // (2b) method's class name
5160 // (2b) method name
5161 // (2b) method source file
5162 // (2b) line number, clipped to 32767; -2 if native; -1 if no source
Man Cao8c2ff642015-05-27 17:25:30 -07005163 ArtMethod* m = record->StackElement(stack_frame).GetMethod();
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07005164 size_t class_name_index = class_names.IndexOf(m->GetDeclaringClassDescriptor());
5165 size_t method_name_index = method_names.IndexOf(m->GetName());
5166 size_t file_name_index = filenames.IndexOf(GetMethodSourceFile(m));
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005167 JDWP::Append2BE(bytes, class_name_index);
5168 JDWP::Append2BE(bytes, method_name_index);
5169 JDWP::Append2BE(bytes, file_name_index);
Man Cao8c2ff642015-05-27 17:25:30 -07005170 JDWP::Append2BE(bytes, record->StackElement(stack_frame).ComputeLineNumber());
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005171 }
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005172 }
5173
Andreas Gamped0fc7682017-07-07 14:03:08 -07005174 CHECK_EQ(bytes.size(), reserve_size);
Andreas Gampeff29cee2017-07-07 11:11:15 -07005175 VLOG(jdwp) << "Dumping tables.";
5176
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005177 // (xb) class name strings
5178 // (xb) method name strings
5179 // (xb) source file strings
5180 JDWP::Set4BE(&bytes[string_table_offset], bytes.size());
5181 class_names.WriteTo(bytes);
5182 method_names.WriteTo(bytes);
5183 filenames.WriteTo(bytes);
Andreas Gampeff29cee2017-07-07 11:11:15 -07005184
5185 VLOG(jdwp) << "GetRecentAllocations: data created. " << bytes.size();
Elliott Hughes545a0642011-11-08 19:10:03 -08005186 }
Ian Rogers50b35e22012-10-04 10:09:15 -07005187 JNIEnv* env = self->GetJniEnv();
Elliott Hughes545a0642011-11-08 19:10:03 -08005188 jbyteArray result = env->NewByteArray(bytes.size());
Ian Rogersc0542af2014-09-03 16:16:56 -07005189 if (result != nullptr) {
Elliott Hughes545a0642011-11-08 19:10:03 -08005190 env->SetByteArrayRegion(result, 0, bytes.size(), reinterpret_cast<const jbyte*>(&bytes[0]));
5191 }
5192 return result;
5193}
5194
Mathieu Chartiere401d142015-04-22 13:56:20 -07005195ArtMethod* DeoptimizationRequest::Method() const {
Andreas Gampe13b27842016-11-07 16:48:23 -08005196 return jni::DecodeArtMethod(method_);
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07005197}
5198
Mathieu Chartiere401d142015-04-22 13:56:20 -07005199void DeoptimizationRequest::SetMethod(ArtMethod* m) {
Andreas Gampe13b27842016-11-07 16:48:23 -08005200 method_ = jni::EncodeArtMethod(m);
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07005201}
5202
Mathieu Chartiera6b1ead2015-10-06 10:32:38 -07005203void Dbg::VisitRoots(RootVisitor* visitor) {
5204 // Visit breakpoint roots, used to prevent unloading of methods with breakpoints.
5205 ReaderMutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
5206 BufferedRootVisitor<128> root_visitor(visitor, RootInfo(kRootVMInternal));
5207 for (Breakpoint& breakpoint : gBreakpoints) {
Andreas Gampe542451c2016-07-26 09:02:02 -07005208 breakpoint.Method()->VisitRoots(root_visitor, kRuntimePointerSize);
Mathieu Chartiera6b1ead2015-10-06 10:32:38 -07005209 }
5210}
5211
Andreas Gampe04bbb5b2017-01-19 17:49:03 +00005212void Dbg::DbgThreadLifecycleCallback::ThreadStart(Thread* self) {
5213 Dbg::PostThreadStart(self);
5214}
5215
5216void Dbg::DbgThreadLifecycleCallback::ThreadDeath(Thread* self) {
5217 Dbg::PostThreadDeath(self);
5218}
5219
Andreas Gampe0f01b582017-01-18 15:22:37 -08005220void Dbg::DbgClassLoadCallback::ClassLoad(Handle<mirror::Class> klass ATTRIBUTE_UNUSED) {
5221 // Ignore ClassLoad;
5222}
5223void Dbg::DbgClassLoadCallback::ClassPrepare(Handle<mirror::Class> temp_klass ATTRIBUTE_UNUSED,
5224 Handle<mirror::Class> klass) {
5225 Dbg::PostClassPrepare(klass.Get());
5226}
5227
Elliott Hughes872d4ec2011-10-21 17:07:15 -07005228} // namespace art