blob: f2402cca264323f0423c9bef3288561da173bd01 [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 Marko4617d582019-03-28 13:48:31 +0000851 ObjPtr<mirror::Object> o = gRegistry->Get<mirror::Object*>(object_id, &error);
Ian Rogersc0542af2014-09-03 16:16:56 -0700852 if (o == nullptr) {
Elliott Hughesf327e072013-01-09 16:01:26 -0800853 return JDWP::ERR_INVALID_OBJECT;
854 }
855
856 // Ensure all threads are suspended while we read objects' lock words.
857 Thread* self = Thread::Current();
Sebastien Hertz54263242014-03-19 18:16:50 +0100858 CHECK_EQ(self->GetState(), kRunnable);
Elliott Hughesf327e072013-01-09 16:01:26 -0800859
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700860 MonitorInfo monitor_info;
861 {
862 ScopedThreadSuspension sts(self, kSuspended);
Mathieu Chartier4f55e222015-09-04 13:26:21 -0700863 ScopedSuspendAll ssa(__FUNCTION__);
Vladimir Marko4617d582019-03-28 13:48:31 +0000864 monitor_info = MonitorInfo(o.Ptr());
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700865 }
Ian Rogersc0542af2014-09-03 16:16:56 -0700866 if (monitor_info.owner_ != nullptr) {
Nicolas Geoffraycafa0812017-02-15 18:27:34 +0000867 expandBufAddObjectId(reply, gRegistry->Add(monitor_info.owner_->GetPeerFromOtherThread()));
Elliott Hughesf327e072013-01-09 16:01:26 -0800868 } else {
Ian Rogersc0542af2014-09-03 16:16:56 -0700869 expandBufAddObjectId(reply, gRegistry->Add(nullptr));
Elliott Hughesf327e072013-01-09 16:01:26 -0800870 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700871 expandBufAdd4BE(reply, monitor_info.entry_count_);
872 expandBufAdd4BE(reply, monitor_info.waiters_.size());
873 for (size_t i = 0; i < monitor_info.waiters_.size(); ++i) {
Nicolas Geoffraycafa0812017-02-15 18:27:34 +0000874 expandBufAddObjectId(reply, gRegistry->Add(monitor_info.waiters_[i]->GetPeerFromOtherThread()));
Elliott Hughesf327e072013-01-09 16:01:26 -0800875 }
876 return JDWP::ERR_NONE;
877}
878
Elliott Hughes734b8c62013-01-11 15:32:45 -0800879JDWP::JdwpError Dbg::GetOwnedMonitors(JDWP::ObjectId thread_id,
Ian Rogersc0542af2014-09-03 16:16:56 -0700880 std::vector<JDWP::ObjectId>* monitors,
881 std::vector<uint32_t>* stack_depths) {
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800882 struct OwnedMonitorVisitor : public StackVisitor {
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700883 OwnedMonitorVisitor(Thread* thread, Context* context,
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -0700884 std::vector<JDWP::ObjectId>* monitor_vector,
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700885 std::vector<uint32_t>* stack_depth_vector)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700886 REQUIRES_SHARED(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +0100887 : StackVisitor(thread, context, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
888 current_stack_depth(0),
889 monitors(monitor_vector),
890 stack_depths(stack_depth_vector) {}
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800891
892 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
893 // annotalysis.
Andreas Gampefa6a1b02018-09-07 08:11:55 -0700894 bool VisitFrame() override NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800895 if (!GetMethod()->IsRuntimeMethod()) {
896 Monitor::VisitLocks(this, AppendOwnedMonitors, this);
Elliott Hughes734b8c62013-01-11 15:32:45 -0800897 ++current_stack_depth;
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800898 }
899 return true;
900 }
901
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -0700902 static void AppendOwnedMonitors(mirror::Object* owned_monitor, void* arg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700903 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers7a22fa62013-01-23 12:16:16 -0800904 OwnedMonitorVisitor* visitor = reinterpret_cast<OwnedMonitorVisitor*>(arg);
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -0700905 visitor->monitors->push_back(gRegistry->Add(owned_monitor));
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700906 visitor->stack_depths->push_back(visitor->current_stack_depth);
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800907 }
908
Elliott Hughes734b8c62013-01-11 15:32:45 -0800909 size_t current_stack_depth;
Ian Rogersc0542af2014-09-03 16:16:56 -0700910 std::vector<JDWP::ObjectId>* const monitors;
911 std::vector<uint32_t>* const stack_depths;
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800912 };
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800913
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700914 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz69206392015-04-07 15:54:25 +0200915 JDWP::JdwpError error;
916 Thread* thread = DecodeThread(soa, thread_id, &error);
917 if (thread == nullptr) {
918 return error;
919 }
920 if (!IsSuspendedForDebugger(soa, thread)) {
921 return JDWP::ERR_THREAD_NOT_SUSPENDED;
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700922 }
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -0700923 std::unique_ptr<Context> context(Context::Create());
Ian Rogersc0542af2014-09-03 16:16:56 -0700924 OwnedMonitorVisitor visitor(thread, context.get(), monitors, stack_depths);
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -0700925 visitor.WalkStack();
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800926 return JDWP::ERR_NONE;
927}
928
Sebastien Hertz52d131d2014-03-13 16:17:40 +0100929JDWP::JdwpError Dbg::GetContendedMonitor(JDWP::ObjectId thread_id,
Ian Rogersc0542af2014-09-03 16:16:56 -0700930 JDWP::ObjectId* contended_monitor) {
Elliott Hughesf9501702013-01-11 11:22:27 -0800931 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -0700932 *contended_monitor = 0;
Sebastien Hertz69206392015-04-07 15:54:25 +0200933 JDWP::JdwpError error;
934 Thread* thread = DecodeThread(soa, thread_id, &error);
935 if (thread == nullptr) {
936 return error;
Elliott Hughesf9501702013-01-11 11:22:27 -0800937 }
Sebastien Hertz69206392015-04-07 15:54:25 +0200938 if (!IsSuspendedForDebugger(soa, thread)) {
939 return JDWP::ERR_THREAD_NOT_SUSPENDED;
940 }
941 mirror::Object* contended_monitor_obj = Monitor::GetContendedMonitor(thread);
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700942 // Add() requires the thread_list_lock_ not held to avoid the lock
943 // level violation.
Ian Rogersc0542af2014-09-03 16:16:56 -0700944 *contended_monitor = gRegistry->Add(contended_monitor_obj);
Elliott Hughesf9501702013-01-11 11:22:27 -0800945 return JDWP::ERR_NONE;
946}
947
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800948JDWP::JdwpError Dbg::GetInstanceCounts(const std::vector<JDWP::RefTypeId>& class_ids,
Ian Rogersc0542af2014-09-03 16:16:56 -0700949 std::vector<uint64_t>* counts) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800950 gc::Heap* heap = Runtime::Current()->GetHeap();
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700951 heap->CollectGarbage(/* clear_soft_references= */ false, gc::GcCause::kGcCauseDebugger);
Mathieu Chartiere8a3c572016-10-11 16:52:17 -0700952 VariableSizedHandleScope hs(Thread::Current());
Mathieu Chartier9d156d52016-10-06 17:44:26 -0700953 std::vector<Handle<mirror::Class>> classes;
Ian Rogersc0542af2014-09-03 16:16:56 -0700954 counts->clear();
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800955 for (size_t i = 0; i < class_ids.size(); ++i) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700956 JDWP::JdwpError error;
Mathieu Chartier9d156d52016-10-06 17:44:26 -0700957 ObjPtr<mirror::Class> c = DecodeClass(class_ids[i], &error);
Ian Rogersc0542af2014-09-03 16:16:56 -0700958 if (c == nullptr) {
959 return error;
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800960 }
Mathieu Chartier9d156d52016-10-06 17:44:26 -0700961 classes.push_back(hs.NewHandle(c));
Ian Rogersc0542af2014-09-03 16:16:56 -0700962 counts->push_back(0);
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800963 }
Ian Rogersc0542af2014-09-03 16:16:56 -0700964 heap->CountInstances(classes, false, &(*counts)[0]);
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800965 return JDWP::ERR_NONE;
966}
967
Ian Rogersc0542af2014-09-03 16:16:56 -0700968JDWP::JdwpError Dbg::GetInstances(JDWP::RefTypeId class_id, int32_t max_count,
969 std::vector<JDWP::ObjectId>* instances) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800970 gc::Heap* heap = Runtime::Current()->GetHeap();
971 // We only want reachable instances, so do a GC.
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700972 heap->CollectGarbage(/* clear_soft_references= */ false, gc::GcCause::kGcCauseDebugger);
Ian Rogersc0542af2014-09-03 16:16:56 -0700973 JDWP::JdwpError error;
Mathieu Chartier9d156d52016-10-06 17:44:26 -0700974 ObjPtr<mirror::Class> c = DecodeClass(class_id, &error);
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800975 if (c == nullptr) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700976 return error;
Elliott Hughes3b78c942013-01-15 17:35:41 -0800977 }
Mathieu Chartier2d855952016-10-12 19:37:59 -0700978 VariableSizedHandleScope hs(Thread::Current());
979 std::vector<Handle<mirror::Object>> raw_instances;
Richard Uhler660be6f2017-11-22 16:12:29 +0000980 Runtime::Current()->GetHeap()->GetInstances(hs,
981 hs.NewHandle(c),
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700982 /* use_is_assignable_from= */ false,
Richard Uhler660be6f2017-11-22 16:12:29 +0000983 max_count,
984 raw_instances);
Elliott Hughes3b78c942013-01-15 17:35:41 -0800985 for (size_t i = 0; i < raw_instances.size(); ++i) {
Mathieu Chartier2d855952016-10-12 19:37:59 -0700986 instances->push_back(gRegistry->Add(raw_instances[i].Get()));
Elliott Hughes3b78c942013-01-15 17:35:41 -0800987 }
988 return JDWP::ERR_NONE;
989}
990
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800991JDWP::JdwpError Dbg::GetReferringObjects(JDWP::ObjectId object_id, int32_t max_count,
Ian Rogersc0542af2014-09-03 16:16:56 -0700992 std::vector<JDWP::ObjectId>* referring_objects) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800993 gc::Heap* heap = Runtime::Current()->GetHeap();
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700994 heap->CollectGarbage(/* clear_soft_references= */ false, gc::GcCause::kGcCauseDebugger);
Ian Rogersc0542af2014-09-03 16:16:56 -0700995 JDWP::JdwpError error;
Mathieu Chartier9d156d52016-10-06 17:44:26 -0700996 ObjPtr<mirror::Object> o = gRegistry->Get<mirror::Object*>(object_id, &error);
Ian Rogersc0542af2014-09-03 16:16:56 -0700997 if (o == nullptr) {
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800998 return JDWP::ERR_INVALID_OBJECT;
999 }
Mathieu Chartieraea9bfb2016-10-12 19:19:56 -07001000 VariableSizedHandleScope hs(Thread::Current());
1001 std::vector<Handle<mirror::Object>> raw_instances;
1002 heap->GetReferringObjects(hs, hs.NewHandle(o), max_count, raw_instances);
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001003 for (size_t i = 0; i < raw_instances.size(); ++i) {
Mathieu Chartieraea9bfb2016-10-12 19:19:56 -07001004 referring_objects->push_back(gRegistry->Add(raw_instances[i].Get()));
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001005 }
1006 return JDWP::ERR_NONE;
1007}
1008
Ian Rogersc0542af2014-09-03 16:16:56 -07001009JDWP::JdwpError Dbg::DisableCollection(JDWP::ObjectId object_id) {
1010 JDWP::JdwpError error;
1011 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
1012 if (o == nullptr) {
Sebastien Hertze96060a2013-12-11 12:06:28 +01001013 return JDWP::ERR_INVALID_OBJECT;
1014 }
Elliott Hughes64f574f2013-02-20 14:57:12 -08001015 gRegistry->DisableCollection(object_id);
1016 return JDWP::ERR_NONE;
1017}
1018
Ian Rogersc0542af2014-09-03 16:16:56 -07001019JDWP::JdwpError Dbg::EnableCollection(JDWP::ObjectId object_id) {
1020 JDWP::JdwpError error;
1021 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
Sebastien Hertze96060a2013-12-11 12:06:28 +01001022 // Unlike DisableCollection, JDWP specs do not state an invalid object causes an error. The RI
1023 // also ignores these cases and never return an error. However it's not obvious why this command
1024 // should behave differently from DisableCollection and IsCollected commands. So let's be more
1025 // strict and return an error if this happens.
Ian Rogersc0542af2014-09-03 16:16:56 -07001026 if (o == nullptr) {
Sebastien Hertze96060a2013-12-11 12:06:28 +01001027 return JDWP::ERR_INVALID_OBJECT;
1028 }
Elliott Hughes64f574f2013-02-20 14:57:12 -08001029 gRegistry->EnableCollection(object_id);
1030 return JDWP::ERR_NONE;
1031}
1032
Ian Rogersc0542af2014-09-03 16:16:56 -07001033JDWP::JdwpError Dbg::IsCollected(JDWP::ObjectId object_id, bool* is_collected) {
1034 *is_collected = true;
Sebastien Hertz65637eb2014-01-10 17:40:02 +01001035 if (object_id == 0) {
1036 // Null object id is invalid.
Sebastien Hertze96060a2013-12-11 12:06:28 +01001037 return JDWP::ERR_INVALID_OBJECT;
1038 }
Sebastien Hertz65637eb2014-01-10 17:40:02 +01001039 // JDWP specs state an INVALID_OBJECT error is returned if the object ID is not valid. However
1040 // the RI seems to ignore this and assume object has been collected.
Ian Rogersc0542af2014-09-03 16:16:56 -07001041 JDWP::JdwpError error;
1042 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
1043 if (o != nullptr) {
1044 *is_collected = gRegistry->IsCollected(object_id);
Sebastien Hertz65637eb2014-01-10 17:40:02 +01001045 }
Elliott Hughes64f574f2013-02-20 14:57:12 -08001046 return JDWP::ERR_NONE;
1047}
1048
Ian Rogersc0542af2014-09-03 16:16:56 -07001049void Dbg::DisposeObject(JDWP::ObjectId object_id, uint32_t reference_count) {
Elliott Hughes64f574f2013-02-20 14:57:12 -08001050 gRegistry->DisposeObject(object_id, reference_count);
1051}
1052
Mathieu Chartier3398c782016-09-30 10:27:43 -07001053JDWP::JdwpTypeTag Dbg::GetTypeTag(ObjPtr<mirror::Class> klass) {
Sebastien Hertz4d8fd492014-03-28 16:29:41 +01001054 DCHECK(klass != nullptr);
1055 if (klass->IsArrayClass()) {
1056 return JDWP::TT_ARRAY;
1057 } else if (klass->IsInterface()) {
1058 return JDWP::TT_INTERFACE;
1059 } else {
1060 return JDWP::TT_CLASS;
1061 }
1062}
1063
Elliott Hughes88d63092013-01-09 09:55:54 -08001064JDWP::JdwpError Dbg::GetReflectedType(JDWP::RefTypeId class_id, JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001065 JDWP::JdwpError error;
Vladimir Marko4617d582019-03-28 13:48:31 +00001066 ObjPtr<mirror::Class> c = DecodeClass(class_id, &error);
Ian Rogersc0542af2014-09-03 16:16:56 -07001067 if (c == nullptr) {
1068 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001069 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001070
Sebastien Hertz4d8fd492014-03-28 16:29:41 +01001071 JDWP::JdwpTypeTag type_tag = GetTypeTag(c);
1072 expandBufAdd1(pReply, type_tag);
Elliott Hughes88d63092013-01-09 09:55:54 -08001073 expandBufAddRefTypeId(pReply, class_id);
Elliott Hughes436e3722012-02-17 20:01:47 -08001074 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001075}
1076
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001077// Get the complete list of reference classes (i.e. all classes except
1078// the primitive types).
1079// Returns a newly-allocated buffer full of RefTypeId values.
1080class ClassListCreator : public ClassVisitor {
1081 public:
1082 explicit ClassListCreator(std::vector<JDWP::RefTypeId>* classes) : classes_(classes) {}
1083
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01001084 bool operator()(ObjPtr<mirror::Class> c) override REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001085 if (!c->IsPrimitive()) {
1086 classes_->push_back(Dbg::GetObjectRegistry()->AddRefType(c));
1087 }
1088 return true;
1089 }
1090
1091 private:
1092 std::vector<JDWP::RefTypeId>* const classes_;
1093};
1094
Ian Rogersc0542af2014-09-03 16:16:56 -07001095void Dbg::GetClassList(std::vector<JDWP::RefTypeId>* classes) {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001096 ClassListCreator clc(classes);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001097 Runtime::Current()->GetClassLinker()->VisitClassesWithoutClassesLock(&clc);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001098}
1099
Ian Rogers1ff3c982014-08-12 02:30:58 -07001100JDWP::JdwpError Dbg::GetClassInfo(JDWP::RefTypeId class_id, JDWP::JdwpTypeTag* pTypeTag,
1101 uint32_t* pStatus, std::string* pDescriptor) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001102 JDWP::JdwpError error;
Vladimir Marko4617d582019-03-28 13:48:31 +00001103 ObjPtr<mirror::Class> c = DecodeClass(class_id, &error);
Ian Rogersc0542af2014-09-03 16:16:56 -07001104 if (c == nullptr) {
1105 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001106 }
1107
Elliott Hughesa2155262011-11-16 16:26:58 -08001108 if (c->IsArrayClass()) {
1109 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
1110 *pTypeTag = JDWP::TT_ARRAY;
1111 } else {
1112 if (c->IsErroneous()) {
1113 *pStatus = JDWP::CS_ERROR;
1114 } else {
1115 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED | JDWP::CS_INITIALIZED;
1116 }
1117 *pTypeTag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
1118 }
1119
Ian Rogersc0542af2014-09-03 16:16:56 -07001120 if (pDescriptor != nullptr) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07001121 std::string temp;
1122 *pDescriptor = c->GetDescriptor(&temp);
Elliott Hughesa2155262011-11-16 16:26:58 -08001123 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001124 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001125}
1126
Ian Rogersc0542af2014-09-03 16:16:56 -07001127void Dbg::FindLoadedClassBySignature(const char* descriptor, std::vector<JDWP::RefTypeId>* ids) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001128 std::vector<ObjPtr<mirror::Class>> classes;
Igor Murashkinb1d8c312015-08-04 11:18:43 -07001129 Runtime::Current()->GetClassLinker()->LookupClasses(descriptor, classes);
Ian Rogersc0542af2014-09-03 16:16:56 -07001130 ids->clear();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001131 for (ObjPtr<mirror::Class> c : classes) {
1132 ids->push_back(gRegistry->Add(c));
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001133 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001134}
1135
Ian Rogersc0542af2014-09-03 16:16:56 -07001136JDWP::JdwpError Dbg::GetReferenceType(JDWP::ObjectId object_id, JDWP::ExpandBuf* pReply) {
1137 JDWP::JdwpError error;
1138 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
1139 if (o == nullptr) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001140 return JDWP::ERR_INVALID_OBJECT;
Elliott Hughes499c5132011-11-17 14:55:11 -08001141 }
Elliott Hughes2435a572012-02-17 16:07:41 -08001142
Sebastien Hertz4d8fd492014-03-28 16:29:41 +01001143 JDWP::JdwpTypeTag type_tag = GetTypeTag(o->GetClass());
Elliott Hughes64f574f2013-02-20 14:57:12 -08001144 JDWP::RefTypeId type_id = gRegistry->AddRefType(o->GetClass());
Elliott Hughes2435a572012-02-17 16:07:41 -08001145
1146 expandBufAdd1(pReply, type_tag);
1147 expandBufAddRefTypeId(pReply, type_id);
1148
1149 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001150}
1151
Ian Rogersfc0e94b2013-09-23 23:51:32 -07001152JDWP::JdwpError Dbg::GetSignature(JDWP::RefTypeId class_id, std::string* signature) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001153 JDWP::JdwpError error;
Vladimir Marko4617d582019-03-28 13:48:31 +00001154 ObjPtr<mirror::Class> c = DecodeClass(class_id, &error);
Ian Rogersc0542af2014-09-03 16:16:56 -07001155 if (c == nullptr) {
1156 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001157 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07001158 std::string temp;
1159 *signature = c->GetDescriptor(&temp);
Elliott Hughes1fe7afb2012-02-13 17:23:03 -08001160 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001161}
1162
Orion Hodson77d8a1c2017-04-24 14:53:19 +01001163JDWP::JdwpError Dbg::GetSourceDebugExtension(JDWP::RefTypeId class_id,
1164 std::string* extension_data) {
1165 JDWP::JdwpError error;
Vladimir Marko4617d582019-03-28 13:48:31 +00001166 ObjPtr<mirror::Class> c = DecodeClass(class_id, &error);
Orion Hodson77d8a1c2017-04-24 14:53:19 +01001167 if (c == nullptr) {
1168 return error;
1169 }
1170 StackHandleScope<1> hs(Thread::Current());
1171 Handle<mirror::Class> klass(hs.NewHandle(c));
1172 const char* data = annotations::GetSourceDebugExtension(klass);
1173 if (data == nullptr) {
1174 return JDWP::ERR_ABSENT_INFORMATION;
1175 }
1176 *extension_data = data;
1177 return JDWP::ERR_NONE;
1178}
1179
Ian Rogersc0542af2014-09-03 16:16:56 -07001180JDWP::JdwpError Dbg::GetSourceFile(JDWP::RefTypeId class_id, std::string* result) {
1181 JDWP::JdwpError error;
Vladimir Marko4617d582019-03-28 13:48:31 +00001182 ObjPtr<mirror::Class> c = DecodeClass(class_id, &error);
Sebastien Hertz4206eb52014-06-05 10:15:45 +02001183 if (c == nullptr) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001184 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001185 }
Sebastien Hertz4206eb52014-06-05 10:15:45 +02001186 const char* source_file = c->GetSourceFile();
1187 if (source_file == nullptr) {
Sebastien Hertzb7054ba2014-03-13 11:52:31 +01001188 return JDWP::ERR_ABSENT_INFORMATION;
1189 }
Ian Rogersc0542af2014-09-03 16:16:56 -07001190 *result = source_file;
Elliott Hughes436e3722012-02-17 20:01:47 -08001191 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001192}
1193
Ian Rogersc0542af2014-09-03 16:16:56 -07001194JDWP::JdwpError Dbg::GetObjectTag(JDWP::ObjectId object_id, uint8_t* tag) {
Ian Rogers98379392014-02-24 16:53:16 -08001195 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07001196 JDWP::JdwpError error;
1197 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
1198 if (error != JDWP::ERR_NONE) {
1199 *tag = JDWP::JT_VOID;
1200 return error;
Elliott Hughes546b9862012-06-20 16:06:13 -07001201 }
Ian Rogersc0542af2014-09-03 16:16:56 -07001202 *tag = TagFromObject(soa, o);
Elliott Hughes546b9862012-06-20 16:06:13 -07001203 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001204}
1205
Elliott Hughesaed4be92011-12-02 16:16:23 -08001206size_t Dbg::GetTagWidth(JDWP::JdwpTag tag) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001207 switch (tag) {
1208 case JDWP::JT_VOID:
1209 return 0;
1210 case JDWP::JT_BYTE:
1211 case JDWP::JT_BOOLEAN:
1212 return 1;
1213 case JDWP::JT_CHAR:
1214 case JDWP::JT_SHORT:
1215 return 2;
1216 case JDWP::JT_FLOAT:
1217 case JDWP::JT_INT:
1218 return 4;
1219 case JDWP::JT_ARRAY:
1220 case JDWP::JT_OBJECT:
1221 case JDWP::JT_STRING:
1222 case JDWP::JT_THREAD:
1223 case JDWP::JT_THREAD_GROUP:
1224 case JDWP::JT_CLASS_LOADER:
1225 case JDWP::JT_CLASS_OBJECT:
1226 return sizeof(JDWP::ObjectId);
1227 case JDWP::JT_DOUBLE:
1228 case JDWP::JT_LONG:
1229 return 8;
1230 default:
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001231 LOG(FATAL) << "Unknown tag " << tag;
Elliott Hughesc1896c92018-11-29 11:33:18 -08001232 UNREACHABLE();
Elliott Hughesdbb40792011-11-18 17:05:22 -08001233 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001234}
1235
Ian Rogersc0542af2014-09-03 16:16:56 -07001236JDWP::JdwpError Dbg::GetArrayLength(JDWP::ObjectId array_id, int32_t* length) {
1237 JDWP::JdwpError error;
Vladimir Marko4617d582019-03-28 13:48:31 +00001238 ObjPtr<mirror::Array> a = DecodeNonNullArray(array_id, &error);
Ian Rogersc0542af2014-09-03 16:16:56 -07001239 if (a == nullptr) {
1240 return error;
Elliott Hughes24437992011-11-30 14:49:33 -08001241 }
Ian Rogersc0542af2014-09-03 16:16:56 -07001242 *length = a->GetLength();
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001243 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001244}
1245
Vladimir Marko4617d582019-03-28 13:48:31 +00001246JDWP::JdwpError Dbg::OutputArray(JDWP::ObjectId array_id,
1247 int offset,
1248 int count,
1249 JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001250 JDWP::JdwpError error;
Vladimir Marko4617d582019-03-28 13:48:31 +00001251 ObjPtr<mirror::Array> a = DecodeNonNullArray(array_id, &error);
Ian Rogers98379392014-02-24 16:53:16 -08001252 if (a == nullptr) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001253 return error;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001254 }
Elliott Hughes24437992011-11-30 14:49:33 -08001255
1256 if (offset < 0 || count < 0 || offset > a->GetLength() || a->GetLength() - offset < count) {
1257 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001258 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughes24437992011-11-30 14:49:33 -08001259 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07001260 JDWP::JdwpTag element_tag = BasicTagFromClass(a->GetClass()->GetComponentType());
1261 expandBufAdd1(pReply, element_tag);
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001262 expandBufAdd4BE(pReply, count);
1263
Ian Rogers1ff3c982014-08-12 02:30:58 -07001264 if (IsPrimitiveTag(element_tag)) {
1265 size_t width = GetTagWidth(element_tag);
Elliott Hughes24437992011-11-30 14:49:33 -08001266 uint8_t* dst = expandBufAddSpace(pReply, count * width);
1267 if (width == 8) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001268 const uint64_t* src8 = reinterpret_cast<uint64_t*>(a->GetRawData(sizeof(uint64_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001269 for (int i = 0; i < count; ++i) JDWP::Write8BE(&dst, src8[offset + i]);
1270 } else if (width == 4) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001271 const uint32_t* src4 = reinterpret_cast<uint32_t*>(a->GetRawData(sizeof(uint32_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001272 for (int i = 0; i < count; ++i) JDWP::Write4BE(&dst, src4[offset + i]);
1273 } else if (width == 2) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001274 const uint16_t* src2 = reinterpret_cast<uint16_t*>(a->GetRawData(sizeof(uint16_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001275 for (int i = 0; i < count; ++i) JDWP::Write2BE(&dst, src2[offset + i]);
1276 } else {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001277 const uint8_t* src = reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint8_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001278 memcpy(dst, &src[offset * width], count * width);
1279 }
1280 } else {
Ian Rogers98379392014-02-24 16:53:16 -08001281 ScopedObjectAccessUnchecked soa(Thread::Current());
Vladimir Marko4617d582019-03-28 13:48:31 +00001282 ObjPtr<mirror::ObjectArray<mirror::Object>> oa = a->AsObjectArray<mirror::Object>();
Elliott Hughes24437992011-11-30 14:49:33 -08001283 for (int i = 0; i < count; ++i) {
Vladimir Marko423bebb2019-03-26 15:17:21 +00001284 ObjPtr<mirror::Object> element = oa->Get(offset + i);
Ian Rogers98379392014-02-24 16:53:16 -08001285 JDWP::JdwpTag specific_tag = (element != nullptr) ? TagFromObject(soa, element)
Ian Rogers1ff3c982014-08-12 02:30:58 -07001286 : element_tag;
Elliott Hughes24437992011-11-30 14:49:33 -08001287 expandBufAdd1(pReply, specific_tag);
1288 expandBufAddObjectId(pReply, gRegistry->Add(element));
1289 }
1290 }
1291
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001292 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001293}
1294
Ian Rogersef7d42f2014-01-06 12:55:46 -08001295template <typename T>
Vladimir Marko4617d582019-03-28 13:48:31 +00001296static void CopyArrayData(ObjPtr<mirror::Array> a, JDWP::Request* src, int offset, int count)
Ian Rogersef7d42f2014-01-06 12:55:46 -08001297 NO_THREAD_SAFETY_ANALYSIS {
1298 // TODO: fix when annotalysis correctly handles non-member functions.
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001299 DCHECK(a->GetClass()->IsPrimitiveArray());
1300
Ian Rogersef7d42f2014-01-06 12:55:46 -08001301 T* dst = reinterpret_cast<T*>(a->GetRawData(sizeof(T), offset));
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001302 for (int i = 0; i < count; ++i) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001303 *dst++ = src->ReadValue(sizeof(T));
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001304 }
1305}
1306
Elliott Hughes88d63092013-01-09 09:55:54 -08001307JDWP::JdwpError Dbg::SetArrayElements(JDWP::ObjectId array_id, int offset, int count,
Ian Rogersc0542af2014-09-03 16:16:56 -07001308 JDWP::Request* request) {
1309 JDWP::JdwpError error;
Vladimir Marko4617d582019-03-28 13:48:31 +00001310 ObjPtr<mirror::Array> dst = DecodeNonNullArray(array_id, &error);
Ian Rogersc0542af2014-09-03 16:16:56 -07001311 if (dst == nullptr) {
1312 return error;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001313 }
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001314
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001315 if (offset < 0 || count < 0 || offset > dst->GetLength() || dst->GetLength() - offset < count) {
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001316 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001317 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001318 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07001319 JDWP::JdwpTag element_tag = BasicTagFromClass(dst->GetClass()->GetComponentType());
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001320
Ian Rogers1ff3c982014-08-12 02:30:58 -07001321 if (IsPrimitiveTag(element_tag)) {
1322 size_t width = GetTagWidth(element_tag);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001323 if (width == 8) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001324 CopyArrayData<uint64_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001325 } else if (width == 4) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001326 CopyArrayData<uint32_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001327 } else if (width == 2) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001328 CopyArrayData<uint16_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001329 } else {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001330 CopyArrayData<uint8_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001331 }
1332 } else {
Vladimir Marko4617d582019-03-28 13:48:31 +00001333 ObjPtr<mirror::ObjectArray<mirror::Object>> oa = dst->AsObjectArray<mirror::Object>();
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001334 for (int i = 0; i < count; ++i) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001335 JDWP::ObjectId id = request->ReadObjectId();
Vladimir Marko4617d582019-03-28 13:48:31 +00001336 ObjPtr<mirror::Object> o = gRegistry->Get<mirror::Object*>(id, &error);
Ian Rogersc0542af2014-09-03 16:16:56 -07001337 if (error != JDWP::ERR_NONE) {
1338 return error;
Elliott Hughes436e3722012-02-17 20:01:47 -08001339 }
Sebastien Hertz2e1c16d2015-08-28 11:57:49 +02001340 // Check if the object's type is compatible with the array's type.
1341 if (o != nullptr && !o->InstanceOf(oa->GetClass()->GetComponentType())) {
1342 return JDWP::ERR_TYPE_MISMATCH;
1343 }
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001344 oa->Set<false>(offset + i, o);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001345 }
1346 }
1347
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001348 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001349}
1350
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001351JDWP::JdwpError Dbg::CreateString(const std::string& str, JDWP::ObjectId* new_string_id) {
1352 Thread* self = Thread::Current();
Vladimir Marko179b7c62019-03-22 13:38:57 +00001353 ObjPtr<mirror::String> new_string = mirror::String::AllocFromModifiedUtf8(self, str.c_str());
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001354 if (new_string == nullptr) {
1355 DCHECK(self->IsExceptionPending());
1356 self->ClearException();
1357 LOG(ERROR) << "Could not allocate string";
1358 *new_string_id = 0;
1359 return JDWP::ERR_OUT_OF_MEMORY;
1360 }
1361 *new_string_id = gRegistry->Add(new_string);
1362 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001363}
1364
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001365JDWP::JdwpError Dbg::CreateObject(JDWP::RefTypeId class_id, JDWP::ObjectId* new_object_id) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001366 JDWP::JdwpError error;
Vladimir Marko4617d582019-03-28 13:48:31 +00001367 ObjPtr<mirror::Class> c = DecodeClass(class_id, &error);
Ian Rogersc0542af2014-09-03 16:16:56 -07001368 if (c == nullptr) {
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001369 *new_object_id = 0;
Ian Rogersc0542af2014-09-03 16:16:56 -07001370 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001371 }
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001372 Thread* self = Thread::Current();
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001373 ObjPtr<mirror::Object> new_object;
Sebastien Hertz56d5e502015-11-03 17:38:35 +01001374 if (c->IsStringClass()) {
1375 // Special case for java.lang.String.
1376 gc::AllocatorType allocator_type = Runtime::Current()->GetHeap()->GetCurrentAllocator();
jessicahandojo3aaa37b2016-07-29 14:46:37 -07001377 new_object = mirror::String::AllocEmptyString<true>(self, allocator_type);
Sebastien Hertz56d5e502015-11-03 17:38:35 +01001378 } else {
1379 new_object = c->AllocObject(self);
1380 }
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001381 if (new_object == nullptr) {
1382 DCHECK(self->IsExceptionPending());
1383 self->ClearException();
David Sehr709b0702016-10-13 09:12:37 -07001384 LOG(ERROR) << "Could not allocate object of type " << mirror::Class::PrettyDescriptor(c);
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001385 *new_object_id = 0;
1386 return JDWP::ERR_OUT_OF_MEMORY;
1387 }
Vladimir Markobcf17522018-06-01 13:14:32 +01001388 *new_object_id = gRegistry->Add(new_object);
Elliott Hughes436e3722012-02-17 20:01:47 -08001389 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001390}
1391
Elliott Hughesbf13d362011-12-08 15:51:37 -08001392/*
1393 * Used by Eclipse's "Display" view to evaluate "new byte[5]" to get "(byte[]) [0, 0, 0, 0, 0]".
1394 */
Elliott Hughes88d63092013-01-09 09:55:54 -08001395JDWP::JdwpError Dbg::CreateArrayObject(JDWP::RefTypeId array_class_id, uint32_t length,
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001396 JDWP::ObjectId* new_array_id) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001397 JDWP::JdwpError error;
Vladimir Marko4617d582019-03-28 13:48:31 +00001398 ObjPtr<mirror::Class> c = DecodeClass(array_class_id, &error);
Ian Rogersc0542af2014-09-03 16:16:56 -07001399 if (c == nullptr) {
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001400 *new_array_id = 0;
Ian Rogersc0542af2014-09-03 16:16:56 -07001401 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001402 }
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001403 Thread* self = Thread::Current();
Vladimir Markobcf17522018-06-01 13:14:32 +01001404 gc::AllocatorType allocator_type = Runtime::Current()->GetHeap()->GetCurrentAllocator();
1405 ObjPtr<mirror::Array> new_array =
1406 mirror::Array::Alloc<true>(self, c, length, c->GetComponentSizeShift(), allocator_type);
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001407 if (new_array == nullptr) {
1408 DCHECK(self->IsExceptionPending());
1409 self->ClearException();
David Sehr709b0702016-10-13 09:12:37 -07001410 LOG(ERROR) << "Could not allocate array of type " << mirror::Class::PrettyDescriptor(c);
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001411 *new_array_id = 0;
1412 return JDWP::ERR_OUT_OF_MEMORY;
1413 }
1414 *new_array_id = gRegistry->Add(new_array);
Elliott Hughes436e3722012-02-17 20:01:47 -08001415 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001416}
1417
Mathieu Chartierc7853442015-03-27 14:35:38 -07001418JDWP::FieldId Dbg::ToFieldId(const ArtField* f) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001419 return static_cast<JDWP::FieldId>(reinterpret_cast<uintptr_t>(f));
Elliott Hughes03181a82011-11-17 17:22:21 -08001420}
1421
Alex Light6c8467f2015-11-20 15:03:26 -08001422static JDWP::MethodId ToMethodId(ArtMethod* m)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001423 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light97e78032017-06-27 17:51:55 -07001424 return static_cast<JDWP::MethodId>(
1425 reinterpret_cast<uintptr_t>(m->GetCanonicalMethod(kRuntimePointerSize)));
Elliott Hughes03181a82011-11-17 17:22:21 -08001426}
1427
Mathieu Chartierc7853442015-03-27 14:35:38 -07001428static ArtField* FromFieldId(JDWP::FieldId fid)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001429 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001430 return reinterpret_cast<ArtField*>(static_cast<uintptr_t>(fid));
Elliott Hughesaed4be92011-12-02 16:16:23 -08001431}
1432
Mathieu Chartiere401d142015-04-22 13:56:20 -07001433static ArtMethod* FromMethodId(JDWP::MethodId mid)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001434 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001435 return reinterpret_cast<ArtMethod*>(static_cast<uintptr_t>(mid));
Elliott Hughes03181a82011-11-17 17:22:21 -08001436}
1437
Sebastien Hertz6995c602014-09-09 12:10:13 +02001438bool Dbg::MatchThread(JDWP::ObjectId expected_thread_id, Thread* event_thread) {
1439 CHECK(event_thread != nullptr);
1440 JDWP::JdwpError error;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001441 mirror::Object* expected_thread_peer = gRegistry->Get<mirror::Object*>(
1442 expected_thread_id, &error);
Nicolas Geoffraycafa0812017-02-15 18:27:34 +00001443 return expected_thread_peer == event_thread->GetPeerFromOtherThread();
Sebastien Hertz6995c602014-09-09 12:10:13 +02001444}
1445
1446bool Dbg::MatchLocation(const JDWP::JdwpLocation& expected_location,
1447 const JDWP::EventLocation& event_location) {
1448 if (expected_location.dex_pc != event_location.dex_pc) {
1449 return false;
1450 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001451 ArtMethod* m = FromMethodId(expected_location.method_id);
Sebastien Hertz6995c602014-09-09 12:10:13 +02001452 return m == event_location.method;
1453}
1454
Mathieu Chartier3398c782016-09-30 10:27:43 -07001455bool Dbg::MatchType(ObjPtr<mirror::Class> event_class, JDWP::RefTypeId class_id) {
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001456 if (event_class == nullptr) {
1457 return false;
1458 }
Sebastien Hertz6995c602014-09-09 12:10:13 +02001459 JDWP::JdwpError error;
Mathieu Chartier3398c782016-09-30 10:27:43 -07001460 ObjPtr<mirror::Class> expected_class = DecodeClass(class_id, &error);
Sebastien Hertz6995c602014-09-09 12:10:13 +02001461 CHECK(expected_class != nullptr);
1462 return expected_class->IsAssignableFrom(event_class);
1463}
1464
1465bool Dbg::MatchField(JDWP::RefTypeId expected_type_id, JDWP::FieldId expected_field_id,
Mathieu Chartierc7853442015-03-27 14:35:38 -07001466 ArtField* event_field) {
1467 ArtField* expected_field = FromFieldId(expected_field_id);
Sebastien Hertz6995c602014-09-09 12:10:13 +02001468 if (expected_field != event_field) {
1469 return false;
1470 }
1471 return Dbg::MatchType(event_field->GetDeclaringClass(), expected_type_id);
1472}
1473
1474bool Dbg::MatchInstance(JDWP::ObjectId expected_instance_id, mirror::Object* event_instance) {
1475 JDWP::JdwpError error;
1476 mirror::Object* modifier_instance = gRegistry->Get<mirror::Object*>(expected_instance_id, &error);
1477 return modifier_instance == event_instance;
1478}
1479
Mathieu Chartier90443472015-07-16 20:32:27 -07001480void Dbg::SetJdwpLocation(JDWP::JdwpLocation* location, ArtMethod* m, uint32_t dex_pc) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001481 if (m == nullptr) {
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001482 memset(location, 0, sizeof(*location));
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001483 } else {
Vladimir Markod93e3742018-07-18 10:58:13 +01001484 ObjPtr<mirror::Class> c = m->GetDeclaringClass();
Ian Rogersc0542af2014-09-03 16:16:56 -07001485 location->type_tag = GetTypeTag(c);
1486 location->class_id = gRegistry->AddRefType(c);
Alex Light73376312017-04-06 10:10:51 -07001487 // The RI Seems to return 0 for all obsolete methods. For compatibility we shall do the same.
1488 location->method_id = m->IsObsolete() ? 0 : ToMethodId(m);
Ian Rogersc0542af2014-09-03 16:16:56 -07001489 location->dex_pc = (m->IsNative() || m->IsProxyMethod()) ? static_cast<uint64_t>(-1) : dex_pc;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001490 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08001491}
1492
Ian Rogersc0542af2014-09-03 16:16:56 -07001493std::string Dbg::GetMethodName(JDWP::MethodId method_id) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001494 ArtMethod* m = FromMethodId(method_id);
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001495 if (m == nullptr) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001496 return "null";
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001497 }
Andreas Gampe542451c2016-07-26 09:02:02 -07001498 return m->GetInterfaceMethodIfProxy(kRuntimePointerSize)->GetName();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001499}
1500
Alex Light73376312017-04-06 10:10:51 -07001501bool Dbg::IsMethodObsolete(JDWP::MethodId method_id) {
1502 ArtMethod* m = FromMethodId(method_id);
1503 if (m == nullptr) {
1504 // NB Since we return 0 as MID for obsolete methods we want to default to true here.
1505 return true;
1506 }
1507 return m->IsObsolete();
1508}
1509
Ian Rogersc0542af2014-09-03 16:16:56 -07001510std::string Dbg::GetFieldName(JDWP::FieldId field_id) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001511 ArtField* f = FromFieldId(field_id);
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001512 if (f == nullptr) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001513 return "null";
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001514 }
1515 return f->GetName();
Elliott Hughesa96836a2013-01-17 12:27:49 -08001516}
1517
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001518/*
1519 * Augment the access flags for synthetic methods and fields by setting
1520 * the (as described by the spec) "0xf0000000 bit". Also, strip out any
1521 * flags not specified by the Java programming language.
1522 */
1523static uint32_t MangleAccessFlags(uint32_t accessFlags) {
1524 accessFlags &= kAccJavaFlagsMask;
1525 if ((accessFlags & kAccSynthetic) != 0) {
1526 accessFlags |= 0xf0000000;
1527 }
1528 return accessFlags;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001529}
1530
Elliott Hughesdbb40792011-11-18 17:05:22 -08001531/*
Jeff Haob7cefc72013-11-14 14:51:09 -08001532 * Circularly shifts registers so that arguments come first. Debuggers
1533 * expect slots to begin with arguments, but dex code places them at
1534 * the end.
Elliott Hughesdbb40792011-11-18 17:05:22 -08001535 */
Mathieu Chartiere401d142015-04-22 13:56:20 -07001536static uint16_t MangleSlot(uint16_t slot, ArtMethod* m)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001537 REQUIRES_SHARED(Locks::mutator_lock_) {
David Sehr0225f8e2018-01-31 08:52:24 +00001538 CodeItemDataAccessor accessor(m->DexInstructionData());
Mathieu Chartier808c7a52017-12-15 11:19:33 -08001539 if (!accessor.HasCodeItem()) {
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001540 // We should not get here for a method without code (native, proxy or abstract). Log it and
1541 // return the slot as is since all registers are arguments.
David Sehr709b0702016-10-13 09:12:37 -07001542 LOG(WARNING) << "Trying to mangle slot for method without code " << m->PrettyMethod();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001543 return slot;
1544 }
Mathieu Chartier808c7a52017-12-15 11:19:33 -08001545 uint16_t ins_size = accessor.InsSize();
1546 uint16_t locals_size = accessor.RegistersSize() - ins_size;
Jeff Haob7cefc72013-11-14 14:51:09 -08001547 if (slot >= locals_size) {
1548 return slot - locals_size;
1549 } else {
1550 return slot + ins_size;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001551 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001552}
1553
Sebastien Hertzaef0c912016-08-08 10:20:28 +02001554static size_t GetMethodNumArgRegistersIncludingThis(ArtMethod* method)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001555 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertzaef0c912016-08-08 10:20:28 +02001556 uint32_t num_registers = ArtMethod::NumArgRegisters(method->GetShorty());
1557 if (!method->IsStatic()) {
1558 ++num_registers;
1559 }
1560 return num_registers;
1561}
1562
Jeff Haob7cefc72013-11-14 14:51:09 -08001563/*
1564 * Circularly shifts registers so that arguments come last. Reverts
1565 * slots to dex style argument placement.
1566 */
Mathieu Chartiere401d142015-04-22 13:56:20 -07001567static uint16_t DemangleSlot(uint16_t slot, ArtMethod* m, JDWP::JdwpError* error)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001568 REQUIRES_SHARED(Locks::mutator_lock_) {
David Sehr0225f8e2018-01-31 08:52:24 +00001569 CodeItemDataAccessor accessor(m->DexInstructionData());
Mathieu Chartier808c7a52017-12-15 11:19:33 -08001570 if (!accessor.HasCodeItem()) {
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001571 // We should not get here for a method without code (native, proxy or abstract). Log it and
1572 // return the slot as is since all registers are arguments.
David Sehr709b0702016-10-13 09:12:37 -07001573 LOG(WARNING) << "Trying to demangle slot for method without code "
1574 << m->PrettyMethod();
Sebastien Hertzaef0c912016-08-08 10:20:28 +02001575 uint16_t vreg_count = GetMethodNumArgRegistersIncludingThis(m);
Sebastien Hertzabbabc82015-03-26 08:47:47 +01001576 if (slot < vreg_count) {
1577 *error = JDWP::ERR_NONE;
1578 return slot;
1579 }
Jeff Haob7cefc72013-11-14 14:51:09 -08001580 } else {
Mathieu Chartier808c7a52017-12-15 11:19:33 -08001581 if (slot < accessor.RegistersSize()) {
1582 uint16_t ins_size = accessor.InsSize();
1583 uint16_t locals_size = accessor.RegistersSize() - ins_size;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01001584 *error = JDWP::ERR_NONE;
1585 return (slot < ins_size) ? slot + locals_size : slot - ins_size;
1586 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001587 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01001588
1589 // Slot is invalid in the method.
David Sehr709b0702016-10-13 09:12:37 -07001590 LOG(ERROR) << "Invalid local slot " << slot << " for method " << m->PrettyMethod();
Sebastien Hertzabbabc82015-03-26 08:47:47 +01001591 *error = JDWP::ERR_INVALID_SLOT;
1592 return DexFile::kDexNoIndex16;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001593}
1594
Mathieu Chartier90443472015-07-16 20:32:27 -07001595JDWP::JdwpError Dbg::OutputDeclaredFields(JDWP::RefTypeId class_id, bool with_generic,
1596 JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001597 JDWP::JdwpError error;
Vladimir Marko4617d582019-03-28 13:48:31 +00001598 ObjPtr<mirror::Class> c = DecodeClass(class_id, &error);
Ian Rogersc0542af2014-09-03 16:16:56 -07001599 if (c == nullptr) {
1600 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001601 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001602
1603 size_t instance_field_count = c->NumInstanceFields();
1604 size_t static_field_count = c->NumStaticFields();
1605
1606 expandBufAdd4BE(pReply, instance_field_count + static_field_count);
1607
1608 for (size_t i = 0; i < instance_field_count + static_field_count; ++i) {
Mathieu Chartier90443472015-07-16 20:32:27 -07001609 ArtField* f = (i < instance_field_count) ? c->GetInstanceField(i) :
1610 c->GetStaticField(i - instance_field_count);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001611 expandBufAddFieldId(pReply, ToFieldId(f));
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001612 expandBufAddUtf8String(pReply, f->GetName());
1613 expandBufAddUtf8String(pReply, f->GetTypeDescriptor());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001614 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001615 static const char genericSignature[1] = "";
1616 expandBufAddUtf8String(pReply, genericSignature);
1617 }
1618 expandBufAdd4BE(pReply, MangleAccessFlags(f->GetAccessFlags()));
1619 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001620 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001621}
1622
Elliott Hughes88d63092013-01-09 09:55:54 -08001623JDWP::JdwpError Dbg::OutputDeclaredMethods(JDWP::RefTypeId class_id, bool with_generic,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001624 JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001625 JDWP::JdwpError error;
Vladimir Marko4617d582019-03-28 13:48:31 +00001626 ObjPtr<mirror::Class> c = DecodeClass(class_id, &error);
Ian Rogersc0542af2014-09-03 16:16:56 -07001627 if (c == nullptr) {
1628 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001629 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001630
Alex Light51a64d52015-12-17 13:55:59 -08001631 expandBufAdd4BE(pReply, c->NumMethods());
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001632
Mathieu Chartiere401d142015-04-22 13:56:20 -07001633 auto* cl = Runtime::Current()->GetClassLinker();
1634 auto ptr_size = cl->GetImagePointerSize();
Alex Light51a64d52015-12-17 13:55:59 -08001635 for (ArtMethod& m : c->GetMethods(ptr_size)) {
1636 expandBufAddMethodId(pReply, ToMethodId(&m));
Andreas Gampe542451c2016-07-26 09:02:02 -07001637 expandBufAddUtf8String(pReply, m.GetInterfaceMethodIfProxy(kRuntimePointerSize)->GetName());
1638 expandBufAddUtf8String(
1639 pReply, m.GetInterfaceMethodIfProxy(kRuntimePointerSize)->GetSignature().ToString());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001640 if (with_generic) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001641 const char* generic_signature = "";
1642 expandBufAddUtf8String(pReply, generic_signature);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001643 }
Alex Light51a64d52015-12-17 13:55:59 -08001644 expandBufAdd4BE(pReply, MangleAccessFlags(m.GetAccessFlags()));
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001645 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001646 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001647}
1648
Elliott Hughes88d63092013-01-09 09:55:54 -08001649JDWP::JdwpError Dbg::OutputDeclaredInterfaces(JDWP::RefTypeId class_id, JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001650 JDWP::JdwpError error;
Mathieu Chartierf8322842014-05-16 10:59:25 -07001651 Thread* self = Thread::Current();
Vladimir Marko19a4d372016-12-08 14:41:46 +00001652 ObjPtr<mirror::Class> c = DecodeClass(class_id, &error);
1653 if (c == nullptr) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001654 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001655 }
Mathieu Chartierf8322842014-05-16 10:59:25 -07001656 size_t interface_count = c->NumDirectInterfaces();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001657 expandBufAdd4BE(pReply, interface_count);
1658 for (size_t i = 0; i < interface_count; ++i) {
Vladimir Marko19a4d372016-12-08 14:41:46 +00001659 ObjPtr<mirror::Class> interface = mirror::Class::GetDirectInterface(self, c, i);
1660 DCHECK(interface != nullptr);
1661 expandBufAddRefTypeId(pReply, gRegistry->AddRefType(interface));
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001662 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001663 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001664}
1665
Ian Rogersc0542af2014-09-03 16:16:56 -07001666void Dbg::OutputLineTable(JDWP::RefTypeId, JDWP::MethodId method_id, JDWP::ExpandBuf* pReply) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001667 ArtMethod* m = FromMethodId(method_id);
David Sehr0225f8e2018-01-31 08:52:24 +00001668 CodeItemDebugInfoAccessor accessor(m->DexInstructionDebugInfo());
Elliott Hughes03181a82011-11-17 17:22:21 -08001669 uint64_t start, end;
Mathieu Chartier31f4c9f2017-12-08 15:46:11 -08001670 if (!accessor.HasCodeItem()) {
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001671 DCHECK(m->IsNative() || m->IsProxyMethod());
Elliott Hughes03181a82011-11-17 17:22:21 -08001672 start = -1;
1673 end = -1;
1674 } else {
1675 start = 0;
jeffhao14f0db92012-12-14 17:50:42 -08001676 // Return the index of the last instruction
Mathieu Chartier31f4c9f2017-12-08 15:46:11 -08001677 end = accessor.InsnsSizeInCodeUnits() - 1;
Elliott Hughes03181a82011-11-17 17:22:21 -08001678 }
1679
1680 expandBufAdd8BE(pReply, start);
1681 expandBufAdd8BE(pReply, end);
1682
1683 // Add numLines later
1684 size_t numLinesOffset = expandBufGetLength(pReply);
1685 expandBufAdd4BE(pReply, 0);
1686
Mathieu Chartier3e2e1232018-09-11 12:35:30 -07001687 int numItems = 0;
1688 accessor.DecodeDebugPositionInfo([&](const DexFile::PositionInfo& entry) {
1689 expandBufAdd8BE(pReply, entry.address_);
1690 expandBufAdd4BE(pReply, entry.line_);
1691 numItems++;
1692 return false;
1693 });
Elliott Hughes03181a82011-11-17 17:22:21 -08001694
Mathieu Chartier3e2e1232018-09-11 12:35:30 -07001695 JDWP::Set4BE(expandBufGetBuffer(pReply) + numLinesOffset, numItems);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001696}
1697
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001698void Dbg::OutputVariableTable(JDWP::RefTypeId, JDWP::MethodId method_id, bool with_generic,
1699 JDWP::ExpandBuf* pReply) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001700 ArtMethod* m = FromMethodId(method_id);
David Sehr0225f8e2018-01-31 08:52:24 +00001701 CodeItemDebugInfoAccessor accessor(m->DexInstructionDebugInfo());
Elliott Hughesdbb40792011-11-18 17:05:22 -08001702
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001703 // arg_count considers doubles and longs to take 2 units.
1704 // variable_count considers everything to take 1 unit.
Sebastien Hertzaef0c912016-08-08 10:20:28 +02001705 expandBufAdd4BE(pReply, GetMethodNumArgRegistersIncludingThis(m));
Elliott Hughesdbb40792011-11-18 17:05:22 -08001706
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001707 // We don't know the total number of variables yet, so leave a blank and update it later.
1708 size_t variable_count_offset = expandBufGetLength(pReply);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001709 expandBufAdd4BE(pReply, 0);
1710
Mathieu Chartiere5afbf32018-09-12 17:51:54 -07001711 size_t variable_count = 0;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001712
Mathieu Chartier31f4c9f2017-12-08 15:46:11 -08001713 if (accessor.HasCodeItem()) {
Mathieu Chartiere5afbf32018-09-12 17:51:54 -07001714 accessor.DecodeDebugLocalInfo(m->IsStatic(),
1715 m->GetDexMethodIndex(),
1716 [&](const DexFile::LocalInfo& entry)
1717 REQUIRES_SHARED(Locks::mutator_lock_) {
1718 uint16_t slot = entry.reg_;
1719 VLOG(jdwp) << StringPrintf(" %2zd: %d(%d) '%s' '%s' '%s' actual slot=%d mangled slot=%d",
1720 variable_count,
1721 entry.start_address_,
1722 entry.end_address_ - entry.start_address_,
1723 entry.name_,
1724 entry.descriptor_, entry.signature_,
1725 slot,
1726 MangleSlot(slot, m));
1727
1728 slot = MangleSlot(slot, m);
1729
1730 expandBufAdd8BE(pReply, entry.start_address_);
1731 expandBufAddUtf8String(pReply, entry.name_);
1732 expandBufAddUtf8String(pReply, entry.descriptor_);
1733 if (with_generic) {
1734 expandBufAddUtf8String(pReply, entry.signature_);
1735 }
1736 expandBufAdd4BE(pReply, entry.end_address_- entry.start_address_);
1737 expandBufAdd4BE(pReply, slot);
1738
1739 ++variable_count;
1740 });
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001741 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001742
Mathieu Chartiere5afbf32018-09-12 17:51:54 -07001743 JDWP::Set4BE(expandBufGetBuffer(pReply) + variable_count_offset, variable_count);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001744}
1745
Jeff Hao579b0242013-11-18 13:16:49 -08001746void Dbg::OutputMethodReturnValue(JDWP::MethodId method_id, const JValue* return_value,
1747 JDWP::ExpandBuf* pReply) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001748 ArtMethod* m = FromMethodId(method_id);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001749 JDWP::JdwpTag tag = BasicTagFromDescriptor(m->GetShorty());
Jeff Hao579b0242013-11-18 13:16:49 -08001750 OutputJValue(tag, return_value, pReply);
1751}
1752
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02001753void Dbg::OutputFieldValue(JDWP::FieldId field_id, const JValue* field_value,
1754 JDWP::ExpandBuf* pReply) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001755 ArtField* f = FromFieldId(field_id);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001756 JDWP::JdwpTag tag = BasicTagFromDescriptor(f->GetTypeDescriptor());
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02001757 OutputJValue(tag, field_value, pReply);
1758}
1759
Elliott Hughes9777ba22013-01-17 09:04:19 -08001760JDWP::JdwpError Dbg::GetBytecodes(JDWP::RefTypeId, JDWP::MethodId method_id,
Ian Rogersc0542af2014-09-03 16:16:56 -07001761 std::vector<uint8_t>* bytecodes) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001762 ArtMethod* m = FromMethodId(method_id);
Ian Rogersc0542af2014-09-03 16:16:56 -07001763 if (m == nullptr) {
Elliott Hughes9777ba22013-01-17 09:04:19 -08001764 return JDWP::ERR_INVALID_METHODID;
1765 }
David Sehr0225f8e2018-01-31 08:52:24 +00001766 CodeItemDataAccessor accessor(m->DexInstructionData());
Mathieu Chartier808c7a52017-12-15 11:19:33 -08001767 size_t byte_count = accessor.InsnsSizeInCodeUnits() * 2;
1768 const uint8_t* begin = reinterpret_cast<const uint8_t*>(accessor.Insns());
Elliott Hughes9777ba22013-01-17 09:04:19 -08001769 const uint8_t* end = begin + byte_count;
1770 for (const uint8_t* p = begin; p != end; ++p) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001771 bytecodes->push_back(*p);
Elliott Hughes9777ba22013-01-17 09:04:19 -08001772 }
1773 return JDWP::ERR_NONE;
1774}
1775
Elliott Hughes88d63092013-01-09 09:55:54 -08001776JDWP::JdwpTag Dbg::GetFieldBasicTag(JDWP::FieldId field_id) {
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001777 return BasicTagFromDescriptor(FromFieldId(field_id)->GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001778}
1779
Elliott Hughes88d63092013-01-09 09:55:54 -08001780JDWP::JdwpTag Dbg::GetStaticFieldBasicTag(JDWP::FieldId field_id) {
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001781 return BasicTagFromDescriptor(FromFieldId(field_id)->GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001782}
1783
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001784static JValue GetArtFieldValue(ArtField* f, mirror::Object* o)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001785 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001786 Primitive::Type fieldType = f->GetTypeAsPrimitiveType();
1787 JValue field_value;
1788 switch (fieldType) {
1789 case Primitive::kPrimBoolean:
1790 field_value.SetZ(f->GetBoolean(o));
1791 return field_value;
1792
1793 case Primitive::kPrimByte:
1794 field_value.SetB(f->GetByte(o));
1795 return field_value;
1796
1797 case Primitive::kPrimChar:
1798 field_value.SetC(f->GetChar(o));
1799 return field_value;
1800
1801 case Primitive::kPrimShort:
1802 field_value.SetS(f->GetShort(o));
1803 return field_value;
1804
1805 case Primitive::kPrimInt:
1806 case Primitive::kPrimFloat:
1807 // Int and Float must be treated as 32-bit values in JDWP.
1808 field_value.SetI(f->GetInt(o));
1809 return field_value;
1810
1811 case Primitive::kPrimLong:
1812 case Primitive::kPrimDouble:
1813 // Long and Double must be treated as 64-bit values in JDWP.
1814 field_value.SetJ(f->GetLong(o));
1815 return field_value;
1816
1817 case Primitive::kPrimNot:
Vladimir Markobcf17522018-06-01 13:14:32 +01001818 field_value.SetL(f->GetObject(o));
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001819 return field_value;
1820
1821 case Primitive::kPrimVoid:
1822 LOG(FATAL) << "Attempt to read from field of type 'void'";
1823 UNREACHABLE();
1824 }
1825 LOG(FATAL) << "Attempt to read from field of unknown type";
1826 UNREACHABLE();
1827}
1828
Elliott Hughes88d63092013-01-09 09:55:54 -08001829static JDWP::JdwpError GetFieldValueImpl(JDWP::RefTypeId ref_type_id, JDWP::ObjectId object_id,
1830 JDWP::FieldId field_id, JDWP::ExpandBuf* pReply,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001831 bool is_static)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001832 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001833 JDWP::JdwpError error;
Vladimir Marko4617d582019-03-28 13:48:31 +00001834 ObjPtr<mirror::Class> c = DecodeClass(ref_type_id, &error);
Ian Rogersc0542af2014-09-03 16:16:56 -07001835 if (ref_type_id != 0 && c == nullptr) {
1836 return error;
Elliott Hughes0cf74332012-02-23 23:14:00 -08001837 }
1838
Jeff Haode19a252016-09-14 15:56:35 -07001839 Thread* self = Thread::Current();
1840 StackHandleScope<2> hs(self);
1841 MutableHandle<mirror::Object>
1842 o(hs.NewHandle(Dbg::GetObjectRegistry()->Get<mirror::Object*>(object_id, &error)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08001843 if ((!is_static && o == nullptr) || error != JDWP::ERR_NONE) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001844 return JDWP::ERR_INVALID_OBJECT;
1845 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001846 ArtField* f = FromFieldId(field_id);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001847
Vladimir Marko4617d582019-03-28 13:48:31 +00001848 ObjPtr<mirror::Class> receiver_class = c;
Andreas Gampefa4333d2017-02-14 11:10:34 -08001849 if (receiver_class == nullptr && o != nullptr) {
Elliott Hughes0cf74332012-02-23 23:14:00 -08001850 receiver_class = o->GetClass();
1851 }
Jeff Haode19a252016-09-14 15:56:35 -07001852
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001853 // TODO: should we give up now if receiver_class is null?
Ian Rogersc0542af2014-09-03 16:16:56 -07001854 if (receiver_class != nullptr && !f->GetDeclaringClass()->IsAssignableFrom(receiver_class)) {
David Sehr709b0702016-10-13 09:12:37 -07001855 LOG(INFO) << "ERR_INVALID_FIELDID: " << f->PrettyField() << " "
1856 << receiver_class->PrettyClass();
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001857 return JDWP::ERR_INVALID_FIELDID;
1858 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001859
Jeff Haode19a252016-09-14 15:56:35 -07001860 // Ensure the field's class is initialized.
1861 Handle<mirror::Class> klass(hs.NewHandle(f->GetDeclaringClass()));
1862 if (!Runtime::Current()->GetClassLinker()->EnsureInitialized(self, klass, true, false)) {
David Sehr709b0702016-10-13 09:12:37 -07001863 LOG(WARNING) << "Not able to initialize class for SetValues: "
1864 << mirror::Class::PrettyClass(klass.Get());
Jeff Haode19a252016-09-14 15:56:35 -07001865 }
1866
Elliott Hughes0cf74332012-02-23 23:14:00 -08001867 // The RI only enforces the static/non-static mismatch in one direction.
1868 // TODO: should we change the tests and check both?
1869 if (is_static) {
1870 if (!f->IsStatic()) {
1871 return JDWP::ERR_INVALID_FIELDID;
1872 }
1873 } else {
1874 if (f->IsStatic()) {
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001875 LOG(WARNING) << "Ignoring non-nullptr receiver for ObjectReference.GetValues"
David Sehr709b0702016-10-13 09:12:37 -07001876 << " on static field " << f->PrettyField();
Elliott Hughes0cf74332012-02-23 23:14:00 -08001877 }
1878 }
jeffhao0dfbb7e2012-11-28 15:26:03 -08001879 if (f->IsStatic()) {
Jeff Haode19a252016-09-14 15:56:35 -07001880 o.Assign(f->GetDeclaringClass());
jeffhao0dfbb7e2012-11-28 15:26:03 -08001881 }
Elliott Hughes0cf74332012-02-23 23:14:00 -08001882
Jeff Haode19a252016-09-14 15:56:35 -07001883 JValue field_value(GetArtFieldValue(f, o.Get()));
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001884 JDWP::JdwpTag tag = BasicTagFromDescriptor(f->GetTypeDescriptor());
Jeff Hao579b0242013-11-18 13:16:49 -08001885 Dbg::OutputJValue(tag, &field_value, pReply);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001886 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001887}
1888
Elliott Hughes88d63092013-01-09 09:55:54 -08001889JDWP::JdwpError Dbg::GetFieldValue(JDWP::ObjectId object_id, JDWP::FieldId field_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001890 JDWP::ExpandBuf* pReply) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001891 return GetFieldValueImpl(0, object_id, field_id, pReply, false);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001892}
1893
Ian Rogersc0542af2014-09-03 16:16:56 -07001894JDWP::JdwpError Dbg::GetStaticFieldValue(JDWP::RefTypeId ref_type_id, JDWP::FieldId field_id,
1895 JDWP::ExpandBuf* pReply) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001896 return GetFieldValueImpl(ref_type_id, 0, field_id, pReply, true);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001897}
1898
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001899static JDWP::JdwpError SetArtFieldValue(ArtField* f, mirror::Object* o, uint64_t value, int width)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001900 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001901 Primitive::Type fieldType = f->GetTypeAsPrimitiveType();
1902 // Debugging only happens at runtime so we know we are not running in a transaction.
1903 static constexpr bool kNoTransactionMode = false;
1904 switch (fieldType) {
1905 case Primitive::kPrimBoolean:
1906 CHECK_EQ(width, 1);
1907 f->SetBoolean<kNoTransactionMode>(o, static_cast<uint8_t>(value));
1908 return JDWP::ERR_NONE;
1909
1910 case Primitive::kPrimByte:
1911 CHECK_EQ(width, 1);
1912 f->SetByte<kNoTransactionMode>(o, static_cast<uint8_t>(value));
1913 return JDWP::ERR_NONE;
1914
1915 case Primitive::kPrimChar:
1916 CHECK_EQ(width, 2);
1917 f->SetChar<kNoTransactionMode>(o, static_cast<uint16_t>(value));
1918 return JDWP::ERR_NONE;
1919
1920 case Primitive::kPrimShort:
1921 CHECK_EQ(width, 2);
1922 f->SetShort<kNoTransactionMode>(o, static_cast<int16_t>(value));
1923 return JDWP::ERR_NONE;
1924
1925 case Primitive::kPrimInt:
1926 case Primitive::kPrimFloat:
1927 CHECK_EQ(width, 4);
1928 // Int and Float must be treated as 32-bit values in JDWP.
1929 f->SetInt<kNoTransactionMode>(o, static_cast<int32_t>(value));
1930 return JDWP::ERR_NONE;
1931
1932 case Primitive::kPrimLong:
1933 case Primitive::kPrimDouble:
1934 CHECK_EQ(width, 8);
1935 // Long and Double must be treated as 64-bit values in JDWP.
1936 f->SetLong<kNoTransactionMode>(o, value);
1937 return JDWP::ERR_NONE;
1938
1939 case Primitive::kPrimNot: {
1940 JDWP::JdwpError error;
1941 mirror::Object* v = Dbg::GetObjectRegistry()->Get<mirror::Object*>(value, &error);
1942 if (error != JDWP::ERR_NONE) {
1943 return JDWP::ERR_INVALID_OBJECT;
1944 }
1945 if (v != nullptr) {
Mathieu Chartier3398c782016-09-30 10:27:43 -07001946 ObjPtr<mirror::Class> field_type;
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001947 {
1948 StackHandleScope<2> hs(Thread::Current());
1949 HandleWrapper<mirror::Object> h_v(hs.NewHandleWrapper(&v));
1950 HandleWrapper<mirror::Object> h_o(hs.NewHandleWrapper(&o));
Vladimir Marko4098a7a2017-11-06 16:00:51 +00001951 field_type = f->ResolveType();
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001952 }
1953 if (!field_type->IsAssignableFrom(v->GetClass())) {
1954 return JDWP::ERR_INVALID_OBJECT;
1955 }
1956 }
1957 f->SetObject<kNoTransactionMode>(o, v);
1958 return JDWP::ERR_NONE;
1959 }
1960
1961 case Primitive::kPrimVoid:
1962 LOG(FATAL) << "Attempt to write to field of type 'void'";
1963 UNREACHABLE();
1964 }
1965 LOG(FATAL) << "Attempt to write to field of unknown type";
1966 UNREACHABLE();
1967}
1968
Elliott Hughes88d63092013-01-09 09:55:54 -08001969static JDWP::JdwpError SetFieldValueImpl(JDWP::ObjectId object_id, JDWP::FieldId field_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001970 uint64_t value, int width, bool is_static)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001971 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001972 JDWP::JdwpError error;
Jeff Haode19a252016-09-14 15:56:35 -07001973 Thread* self = Thread::Current();
1974 StackHandleScope<2> hs(self);
1975 MutableHandle<mirror::Object>
1976 o(hs.NewHandle(Dbg::GetObjectRegistry()->Get<mirror::Object*>(object_id, &error)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08001977 if ((!is_static && o == nullptr) || error != JDWP::ERR_NONE) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001978 return JDWP::ERR_INVALID_OBJECT;
1979 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001980 ArtField* f = FromFieldId(field_id);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001981
Jeff Haode19a252016-09-14 15:56:35 -07001982 // Ensure the field's class is initialized.
1983 Handle<mirror::Class> klass(hs.NewHandle(f->GetDeclaringClass()));
1984 if (!Runtime::Current()->GetClassLinker()->EnsureInitialized(self, klass, true, false)) {
David Sehr709b0702016-10-13 09:12:37 -07001985 LOG(WARNING) << "Not able to initialize class for SetValues: "
1986 << mirror::Class::PrettyClass(klass.Get());
Jeff Haode19a252016-09-14 15:56:35 -07001987 }
1988
Elliott Hughes0cf74332012-02-23 23:14:00 -08001989 // The RI only enforces the static/non-static mismatch in one direction.
1990 // TODO: should we change the tests and check both?
1991 if (is_static) {
1992 if (!f->IsStatic()) {
1993 return JDWP::ERR_INVALID_FIELDID;
1994 }
1995 } else {
1996 if (f->IsStatic()) {
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001997 LOG(WARNING) << "Ignoring non-nullptr receiver for ObjectReference.SetValues"
David Sehr709b0702016-10-13 09:12:37 -07001998 << " on static field " << f->PrettyField();
Elliott Hughes0cf74332012-02-23 23:14:00 -08001999 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002000 }
jeffhao0dfbb7e2012-11-28 15:26:03 -08002001 if (f->IsStatic()) {
Jeff Haode19a252016-09-14 15:56:35 -07002002 o.Assign(f->GetDeclaringClass());
jeffhao0dfbb7e2012-11-28 15:26:03 -08002003 }
Jeff Haode19a252016-09-14 15:56:35 -07002004 return SetArtFieldValue(f, o.Get(), value, width);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002005}
2006
Elliott Hughes88d63092013-01-09 09:55:54 -08002007JDWP::JdwpError Dbg::SetFieldValue(JDWP::ObjectId object_id, JDWP::FieldId field_id, uint64_t value,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002008 int width) {
Elliott Hughes88d63092013-01-09 09:55:54 -08002009 return SetFieldValueImpl(object_id, field_id, value, width, false);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002010}
2011
Elliott Hughes88d63092013-01-09 09:55:54 -08002012JDWP::JdwpError Dbg::SetStaticFieldValue(JDWP::FieldId field_id, uint64_t value, int width) {
2013 return SetFieldValueImpl(0, field_id, value, width, true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002014}
2015
Sebastien Hertzb0b0b492014-09-15 11:27:27 +02002016JDWP::JdwpError Dbg::StringToUtf8(JDWP::ObjectId string_id, std::string* str) {
Ian Rogersc0542af2014-09-03 16:16:56 -07002017 JDWP::JdwpError error;
Sebastien Hertzb0b0b492014-09-15 11:27:27 +02002018 mirror::Object* obj = gRegistry->Get<mirror::Object*>(string_id, &error);
2019 if (error != JDWP::ERR_NONE) {
2020 return error;
2021 }
2022 if (obj == nullptr) {
2023 return JDWP::ERR_INVALID_OBJECT;
2024 }
2025 {
2026 ScopedObjectAccessUnchecked soa(Thread::Current());
Mathieu Chartier0795f232016-09-27 18:43:30 -07002027 ObjPtr<mirror::Class> java_lang_String =
2028 soa.Decode<mirror::Class>(WellKnownClasses::java_lang_String);
Sebastien Hertzb0b0b492014-09-15 11:27:27 +02002029 if (!java_lang_String->IsAssignableFrom(obj->GetClass())) {
2030 // This isn't a string.
2031 return JDWP::ERR_INVALID_STRING;
2032 }
2033 }
2034 *str = obj->AsString()->ToModifiedUtf8();
2035 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002036}
2037
Jeff Hao579b0242013-11-18 13:16:49 -08002038void Dbg::OutputJValue(JDWP::JdwpTag tag, const JValue* return_value, JDWP::ExpandBuf* pReply) {
2039 if (IsPrimitiveTag(tag)) {
2040 expandBufAdd1(pReply, tag);
2041 if (tag == JDWP::JT_BOOLEAN || tag == JDWP::JT_BYTE) {
2042 expandBufAdd1(pReply, return_value->GetI());
2043 } else if (tag == JDWP::JT_CHAR || tag == JDWP::JT_SHORT) {
2044 expandBufAdd2BE(pReply, return_value->GetI());
2045 } else if (tag == JDWP::JT_FLOAT || tag == JDWP::JT_INT) {
2046 expandBufAdd4BE(pReply, return_value->GetI());
2047 } else if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
2048 expandBufAdd8BE(pReply, return_value->GetJ());
2049 } else {
2050 CHECK_EQ(tag, JDWP::JT_VOID);
2051 }
2052 } else {
Ian Rogers98379392014-02-24 16:53:16 -08002053 ScopedObjectAccessUnchecked soa(Thread::Current());
Jeff Hao579b0242013-11-18 13:16:49 -08002054 mirror::Object* value = return_value->GetL();
Ian Rogers98379392014-02-24 16:53:16 -08002055 expandBufAdd1(pReply, TagFromObject(soa, value));
Jeff Hao579b0242013-11-18 13:16:49 -08002056 expandBufAddObjectId(pReply, gRegistry->Add(value));
2057 }
2058}
2059
Ian Rogersc0542af2014-09-03 16:16:56 -07002060JDWP::JdwpError Dbg::GetThreadName(JDWP::ObjectId thread_id, std::string* name) {
jeffhaoa77f0f62012-12-05 17:19:31 -08002061 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002062 JDWP::JdwpError error;
Roland Levillain4b8f1ec2015-08-26 18:34:03 +01002063 DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002064 if (error != JDWP::ERR_NONE && error != JDWP::ERR_THREAD_NOT_ALIVE) {
2065 return error;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08002066 }
Elliott Hughes221229c2013-01-08 18:17:50 -08002067
2068 // We still need to report the zombie threads' names, so we can't just call Thread::GetThreadName.
Ian Rogersc0542af2014-09-03 16:16:56 -07002069 mirror::Object* thread_object = gRegistry->Get<mirror::Object*>(thread_id, &error);
2070 CHECK(thread_object != nullptr) << error;
Mathieu Chartierc7853442015-03-27 14:35:38 -07002071 ArtField* java_lang_Thread_name_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08002072 jni::DecodeArtField(WellKnownClasses::java_lang_Thread_name);
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07002073 ObjPtr<mirror::String> s(java_lang_Thread_name_field->GetObject(thread_object)->AsString());
Ian Rogersc0542af2014-09-03 16:16:56 -07002074 if (s != nullptr) {
2075 *name = s->ToModifiedUtf8();
Elliott Hughes221229c2013-01-08 18:17:50 -08002076 }
2077 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002078}
2079
Elliott Hughes221229c2013-01-08 18:17:50 -08002080JDWP::JdwpError Dbg::GetThreadGroup(JDWP::ObjectId thread_id, JDWP::ExpandBuf* pReply) {
Sebastien Hertza06430c2014-09-15 19:21:30 +02002081 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002082 JDWP::JdwpError error;
2083 mirror::Object* thread_object = gRegistry->Get<mirror::Object*>(thread_id, &error);
2084 if (error != JDWP::ERR_NONE) {
Elliott Hughes2435a572012-02-17 16:07:41 -08002085 return JDWP::ERR_INVALID_OBJECT;
2086 }
Mathieu Chartier268764d2016-09-13 12:09:38 -07002087 ScopedAssertNoThreadSuspension ants("Debugger: GetThreadGroup");
Elliott Hughes2435a572012-02-17 16:07:41 -08002088 // Okay, so it's an object, but is it actually a thread?
Roland Levillain4b8f1ec2015-08-26 18:34:03 +01002089 DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002090 if (error == JDWP::ERR_THREAD_NOT_ALIVE) {
2091 // Zombie threads are in the null group.
2092 expandBufAddObjectId(pReply, JDWP::ObjectId(0));
Sebastien Hertz52d131d2014-03-13 16:17:40 +01002093 error = JDWP::ERR_NONE;
2094 } else if (error == JDWP::ERR_NONE) {
Mathieu Chartier0795f232016-09-27 18:43:30 -07002095 ObjPtr<mirror::Class> c = soa.Decode<mirror::Class>(WellKnownClasses::java_lang_Thread);
Sebastien Hertz52d131d2014-03-13 16:17:40 +01002096 CHECK(c != nullptr);
Andreas Gampe08883de2016-11-08 13:20:52 -08002097 ArtField* f = jni::DecodeArtField(WellKnownClasses::java_lang_Thread_group);
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07002098 CHECK(f != nullptr);
Mathieu Chartier3398c782016-09-30 10:27:43 -07002099 ObjPtr<mirror::Object> group = f->GetObject(thread_object);
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07002100 CHECK(group != nullptr);
Sebastien Hertz52d131d2014-03-13 16:17:40 +01002101 JDWP::ObjectId thread_group_id = gRegistry->Add(group);
2102 expandBufAddObjectId(pReply, thread_group_id);
Elliott Hughes221229c2013-01-08 18:17:50 -08002103 }
Sebastien Hertz52d131d2014-03-13 16:17:40 +01002104 return error;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002105}
2106
Sebastien Hertza06430c2014-09-15 19:21:30 +02002107static mirror::Object* DecodeThreadGroup(ScopedObjectAccessUnchecked& soa,
2108 JDWP::ObjectId thread_group_id, JDWP::JdwpError* error)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002109 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz6995c602014-09-09 12:10:13 +02002110 mirror::Object* thread_group = Dbg::GetObjectRegistry()->Get<mirror::Object*>(thread_group_id,
2111 error);
Sebastien Hertza06430c2014-09-15 19:21:30 +02002112 if (*error != JDWP::ERR_NONE) {
2113 return nullptr;
2114 }
2115 if (thread_group == nullptr) {
2116 *error = JDWP::ERR_INVALID_OBJECT;
2117 return nullptr;
2118 }
Mathieu Chartier0795f232016-09-27 18:43:30 -07002119 ObjPtr<mirror::Class> c =
2120 soa.Decode<mirror::Class>(WellKnownClasses::java_lang_ThreadGroup);
Ian Rogers98379392014-02-24 16:53:16 -08002121 CHECK(c != nullptr);
Sebastien Hertza06430c2014-09-15 19:21:30 +02002122 if (!c->IsAssignableFrom(thread_group->GetClass())) {
2123 // This is not a java.lang.ThreadGroup.
2124 *error = JDWP::ERR_INVALID_THREAD_GROUP;
2125 return nullptr;
2126 }
2127 *error = JDWP::ERR_NONE;
2128 return thread_group;
2129}
2130
2131JDWP::JdwpError Dbg::GetThreadGroupName(JDWP::ObjectId thread_group_id, JDWP::ExpandBuf* pReply) {
2132 ScopedObjectAccessUnchecked soa(Thread::Current());
2133 JDWP::JdwpError error;
2134 mirror::Object* thread_group = DecodeThreadGroup(soa, thread_group_id, &error);
2135 if (error != JDWP::ERR_NONE) {
2136 return error;
2137 }
Mathieu Chartier268764d2016-09-13 12:09:38 -07002138 ScopedAssertNoThreadSuspension ants("Debugger: GetThreadGroupName");
Andreas Gampe08883de2016-11-08 13:20:52 -08002139 ArtField* f = jni::DecodeArtField(WellKnownClasses::java_lang_ThreadGroup_name);
Ian Rogersc0542af2014-09-03 16:16:56 -07002140 CHECK(f != nullptr);
Mathieu Chartier3398c782016-09-30 10:27:43 -07002141 ObjPtr<mirror::String> s = f->GetObject(thread_group)->AsString();
Sebastien Hertza06430c2014-09-15 19:21:30 +02002142
2143 std::string thread_group_name(s->ToModifiedUtf8());
2144 expandBufAddUtf8String(pReply, thread_group_name);
2145 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002146}
2147
Sebastien Hertza06430c2014-09-15 19:21:30 +02002148JDWP::JdwpError Dbg::GetThreadGroupParent(JDWP::ObjectId thread_group_id, JDWP::ExpandBuf* pReply) {
Ian Rogers98379392014-02-24 16:53:16 -08002149 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002150 JDWP::JdwpError error;
Sebastien Hertza06430c2014-09-15 19:21:30 +02002151 mirror::Object* thread_group = DecodeThreadGroup(soa, thread_group_id, &error);
2152 if (error != JDWP::ERR_NONE) {
2153 return error;
2154 }
Mathieu Chartier3398c782016-09-30 10:27:43 -07002155 ObjPtr<mirror::Object> parent;
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07002156 {
Mathieu Chartier268764d2016-09-13 12:09:38 -07002157 ScopedAssertNoThreadSuspension ants("Debugger: GetThreadGroupParent");
Andreas Gampe08883de2016-11-08 13:20:52 -08002158 ArtField* f = jni::DecodeArtField(WellKnownClasses::java_lang_ThreadGroup_parent);
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07002159 CHECK(f != nullptr);
2160 parent = f->GetObject(thread_group);
2161 }
Sebastien Hertza06430c2014-09-15 19:21:30 +02002162 JDWP::ObjectId parent_group_id = gRegistry->Add(parent);
2163 expandBufAddObjectId(pReply, parent_group_id);
2164 return JDWP::ERR_NONE;
2165}
2166
Andreas Gampe08883de2016-11-08 13:20:52 -08002167static void GetChildThreadGroups(mirror::Object* thread_group,
Sebastien Hertza06430c2014-09-15 19:21:30 +02002168 std::vector<JDWP::ObjectId>* child_thread_group_ids)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002169 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertza06430c2014-09-15 19:21:30 +02002170 CHECK(thread_group != nullptr);
2171
Przemyslaw Szczepaniak464595f2015-11-24 11:59:59 +00002172 // Get the int "ngroups" count of this thread group...
Andreas Gampe08883de2016-11-08 13:20:52 -08002173 ArtField* ngroups_field = jni::DecodeArtField(WellKnownClasses::java_lang_ThreadGroup_ngroups);
Przemyslaw Szczepaniak464595f2015-11-24 11:59:59 +00002174 CHECK(ngroups_field != nullptr);
2175 const int32_t size = ngroups_field->GetInt(thread_group);
2176 if (size == 0) {
2177 return;
Sebastien Hertze49e1952014-10-13 11:27:13 +02002178 }
Sebastien Hertza06430c2014-09-15 19:21:30 +02002179
Przemyslaw Szczepaniak464595f2015-11-24 11:59:59 +00002180 // Get the ThreadGroup[] "groups" out of this thread group...
Andreas Gampe08883de2016-11-08 13:20:52 -08002181 ArtField* groups_field = jni::DecodeArtField(WellKnownClasses::java_lang_ThreadGroup_groups);
Mathieu Chartier3398c782016-09-30 10:27:43 -07002182 ObjPtr<mirror::Object> groups_array = groups_field->GetObject(thread_group);
Przemyslaw Szczepaniak464595f2015-11-24 11:59:59 +00002183
2184 CHECK(groups_array != nullptr);
2185 CHECK(groups_array->IsObjectArray());
2186
Mathieu Chartier3398c782016-09-30 10:27:43 -07002187 ObjPtr<mirror::ObjectArray<mirror::Object>> groups_array_as_array =
Przemyslaw Szczepaniak464595f2015-11-24 11:59:59 +00002188 groups_array->AsObjectArray<mirror::Object>();
Sebastien Hertza06430c2014-09-15 19:21:30 +02002189
2190 // Copy the first 'size' elements out of the array into the result.
Sebastien Hertz6995c602014-09-09 12:10:13 +02002191 ObjectRegistry* registry = Dbg::GetObjectRegistry();
Sebastien Hertza06430c2014-09-15 19:21:30 +02002192 for (int32_t i = 0; i < size; ++i) {
Przemyslaw Szczepaniak464595f2015-11-24 11:59:59 +00002193 child_thread_group_ids->push_back(registry->Add(groups_array_as_array->Get(i)));
Sebastien Hertza06430c2014-09-15 19:21:30 +02002194 }
2195}
2196
2197JDWP::JdwpError Dbg::GetThreadGroupChildren(JDWP::ObjectId thread_group_id,
2198 JDWP::ExpandBuf* pReply) {
2199 ScopedObjectAccessUnchecked soa(Thread::Current());
2200 JDWP::JdwpError error;
2201 mirror::Object* thread_group = DecodeThreadGroup(soa, thread_group_id, &error);
2202 if (error != JDWP::ERR_NONE) {
2203 return error;
2204 }
2205
2206 // Add child threads.
2207 {
2208 std::vector<JDWP::ObjectId> child_thread_ids;
2209 GetThreads(thread_group, &child_thread_ids);
2210 expandBufAdd4BE(pReply, child_thread_ids.size());
2211 for (JDWP::ObjectId child_thread_id : child_thread_ids) {
2212 expandBufAddObjectId(pReply, child_thread_id);
2213 }
2214 }
2215
2216 // Add child thread groups.
2217 {
2218 std::vector<JDWP::ObjectId> child_thread_groups_ids;
Andreas Gampe08883de2016-11-08 13:20:52 -08002219 GetChildThreadGroups(thread_group, &child_thread_groups_ids);
Sebastien Hertza06430c2014-09-15 19:21:30 +02002220 expandBufAdd4BE(pReply, child_thread_groups_ids.size());
2221 for (JDWP::ObjectId child_thread_group_id : child_thread_groups_ids) {
2222 expandBufAddObjectId(pReply, child_thread_group_id);
2223 }
2224 }
2225
2226 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002227}
2228
2229JDWP::ObjectId Dbg::GetSystemThreadGroupId() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002230 ScopedObjectAccessUnchecked soa(Thread::Current());
Andreas Gampe08883de2016-11-08 13:20:52 -08002231 ArtField* f = jni::DecodeArtField(WellKnownClasses::java_lang_ThreadGroup_systemThreadGroup);
Mathieu Chartier3398c782016-09-30 10:27:43 -07002232 ObjPtr<mirror::Object> group = f->GetObject(f->GetDeclaringClass());
Ian Rogers365c1022012-06-22 15:05:28 -07002233 return gRegistry->Add(group);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002234}
2235
Jeff Hao920af3e2013-08-28 15:46:38 -07002236JDWP::JdwpThreadStatus Dbg::ToJdwpThreadStatus(ThreadState state) {
2237 switch (state) {
2238 case kBlocked:
2239 return JDWP::TS_MONITOR;
2240 case kNative:
2241 case kRunnable:
2242 case kSuspended:
2243 return JDWP::TS_RUNNING;
2244 case kSleeping:
2245 return JDWP::TS_SLEEPING;
2246 case kStarting:
2247 case kTerminated:
2248 return JDWP::TS_ZOMBIE;
2249 case kTimedWaiting:
Alex Light77fee872017-09-05 14:51:49 -07002250 case kWaitingForTaskProcessor:
2251 case kWaitingForLockInflation:
Sebastien Hertzbae182c2013-12-17 10:42:03 +01002252 case kWaitingForCheckPointsToRun:
Jeff Hao920af3e2013-08-28 15:46:38 -07002253 case kWaitingForDebuggerSend:
2254 case kWaitingForDebuggerSuspension:
2255 case kWaitingForDebuggerToAttach:
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002256 case kWaitingForDeoptimization:
Jeff Hao920af3e2013-08-28 15:46:38 -07002257 case kWaitingForGcToComplete:
Mathieu Chartierb43390c2015-05-12 10:47:11 -07002258 case kWaitingForGetObjectsAllocated:
Jeff Hao920af3e2013-08-28 15:46:38 -07002259 case kWaitingForJniOnLoad:
Sebastien Hertzbae182c2013-12-17 10:42:03 +01002260 case kWaitingForMethodTracingStart:
Jeff Hao920af3e2013-08-28 15:46:38 -07002261 case kWaitingForSignalCatcherOutput:
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -08002262 case kWaitingForVisitObjects:
Jeff Hao920af3e2013-08-28 15:46:38 -07002263 case kWaitingInMainDebuggerLoop:
2264 case kWaitingInMainSignalCatcherLoop:
2265 case kWaitingPerformingGc:
Mathieu Chartier90ef3db2015-08-04 15:19:41 -07002266 case kWaitingWeakGcRootRead:
Hiroshi Yamauchi76f55b02015-08-21 16:10:39 -07002267 case kWaitingForGcThreadFlip:
Koji Fukui34857b52019-03-20 19:13:00 +09002268 case kNativeForAbort:
Jeff Hao920af3e2013-08-28 15:46:38 -07002269 case kWaiting:
2270 return JDWP::TS_WAIT;
2271 // Don't add a 'default' here so the compiler can spot incompatible enum changes.
2272 }
2273 LOG(FATAL) << "Unknown thread state: " << state;
Elliott Hughesc1896c92018-11-29 11:33:18 -08002274 UNREACHABLE();
Jeff Hao920af3e2013-08-28 15:46:38 -07002275}
2276
Sebastien Hertz52d131d2014-03-13 16:17:40 +01002277JDWP::JdwpError Dbg::GetThreadStatus(JDWP::ObjectId thread_id, JDWP::JdwpThreadStatus* pThreadStatus,
2278 JDWP::JdwpSuspendStatus* pSuspendStatus) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002279 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes499c5132011-11-17 14:55:11 -08002280
Elliott Hughes9e0c1752013-01-09 14:02:58 -08002281 *pSuspendStatus = JDWP::SUSPEND_STATUS_NOT_SUSPENDED;
2282
Ian Rogersc0542af2014-09-03 16:16:56 -07002283 JDWP::JdwpError error;
2284 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002285 if (error != JDWP::ERR_NONE) {
2286 if (error == JDWP::ERR_THREAD_NOT_ALIVE) {
2287 *pThreadStatus = JDWP::TS_ZOMBIE;
Elliott Hughes221229c2013-01-08 18:17:50 -08002288 return JDWP::ERR_NONE;
2289 }
2290 return error;
Elliott Hughes499c5132011-11-17 14:55:11 -08002291 }
2292
Elliott Hughes9e0c1752013-01-09 14:02:58 -08002293 if (IsSuspendedForDebugger(soa, thread)) {
2294 *pSuspendStatus = JDWP::SUSPEND_STATUS_SUSPENDED;
Elliott Hughes499c5132011-11-17 14:55:11 -08002295 }
2296
Jeff Hao920af3e2013-08-28 15:46:38 -07002297 *pThreadStatus = ToJdwpThreadStatus(thread->GetState());
Elliott Hughes221229c2013-01-08 18:17:50 -08002298 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002299}
2300
Elliott Hughes221229c2013-01-08 18:17:50 -08002301JDWP::JdwpError Dbg::GetThreadDebugSuspendCount(JDWP::ObjectId thread_id, JDWP::ExpandBuf* pReply) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002302 ScopedObjectAccess soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002303 JDWP::JdwpError error;
2304 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002305 if (error != JDWP::ERR_NONE) {
2306 return error;
Elliott Hughes2435a572012-02-17 16:07:41 -08002307 }
Ian Rogers50b35e22012-10-04 10:09:15 -07002308 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002309 expandBufAdd4BE(pReply, thread->GetDebugSuspendCount());
Elliott Hughes2435a572012-02-17 16:07:41 -08002310 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002311}
2312
Elliott Hughesf9501702013-01-11 11:22:27 -08002313JDWP::JdwpError Dbg::Interrupt(JDWP::ObjectId thread_id) {
2314 ScopedObjectAccess soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002315 JDWP::JdwpError error;
2316 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughesf9501702013-01-11 11:22:27 -08002317 if (error != JDWP::ERR_NONE) {
2318 return error;
2319 }
Ian Rogersdd7624d2014-03-14 17:43:00 -07002320 thread->Interrupt(soa.Self());
Elliott Hughesf9501702013-01-11 11:22:27 -08002321 return JDWP::ERR_NONE;
2322}
2323
Andreas Gampe08883de2016-11-08 13:20:52 -08002324static bool IsInDesiredThreadGroup(mirror::Object* desired_thread_group, mirror::Object* peer)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002325 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz070f7322014-09-09 12:08:49 +02002326 // Do we want threads from all thread groups?
2327 if (desired_thread_group == nullptr) {
2328 return true;
2329 }
Andreas Gampe08883de2016-11-08 13:20:52 -08002330 ArtField* thread_group_field = jni::DecodeArtField(WellKnownClasses::java_lang_Thread_group);
Sebastien Hertz070f7322014-09-09 12:08:49 +02002331 DCHECK(thread_group_field != nullptr);
Mathieu Chartier3398c782016-09-30 10:27:43 -07002332 ObjPtr<mirror::Object> group = thread_group_field->GetObject(peer);
Sebastien Hertz070f7322014-09-09 12:08:49 +02002333 return (group == desired_thread_group);
2334}
2335
Sebastien Hertza06430c2014-09-15 19:21:30 +02002336void Dbg::GetThreads(mirror::Object* thread_group, std::vector<JDWP::ObjectId>* thread_ids) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002337 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz070f7322014-09-09 12:08:49 +02002338 std::list<Thread*> all_threads_list;
2339 {
2340 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
2341 all_threads_list = Runtime::Current()->GetThreadList()->GetList();
2342 }
2343 for (Thread* t : all_threads_list) {
2344 if (t == Dbg::GetDebugThread()) {
2345 // Skip the JDWP thread. Some debuggers get bent out of shape when they can't suspend and
2346 // query all threads, so it's easier if we just don't tell them about this thread.
2347 continue;
2348 }
2349 if (t->IsStillStarting()) {
2350 // This thread is being started (and has been registered in the thread list). However, it is
2351 // not completely started yet so we must ignore it.
2352 continue;
2353 }
Nicolas Geoffraycafa0812017-02-15 18:27:34 +00002354 mirror::Object* peer = t->GetPeerFromOtherThread();
Sebastien Hertz070f7322014-09-09 12:08:49 +02002355 if (peer == nullptr) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002356 // 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 +02002357 // this thread yet.
2358 // TODO: if we identified threads to the debugger by their Thread*
2359 // rather than their peer's mirror::Object*, we could fix this.
2360 // Doing so might help us report ZOMBIE threads too.
2361 continue;
2362 }
Andreas Gampe08883de2016-11-08 13:20:52 -08002363 if (IsInDesiredThreadGroup(thread_group, peer)) {
Sebastien Hertz070f7322014-09-09 12:08:49 +02002364 thread_ids->push_back(gRegistry->Add(peer));
2365 }
2366 }
Elliott Hughescaf76542012-06-28 16:08:22 -07002367}
Elliott Hughesa2155262011-11-16 16:26:58 -08002368
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002369static int GetStackDepth(Thread* thread) REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampec7d878d2018-11-19 18:42:06 +00002370 size_t depth = 0u;
2371 StackVisitor::WalkStack(
2372 [&depth](const StackVisitor* visitor) REQUIRES_SHARED(Locks::mutator_lock_) {
2373 if (!visitor->GetMethod()->IsRuntimeMethod()) {
2374 ++depth;
2375 }
2376 return true;
2377 },
2378 thread,
2379 /* context= */ nullptr,
2380 StackVisitor::StackWalkKind::kIncludeInlinedFrames);
2381 return depth;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002382}
2383
Ian Rogersc0542af2014-09-03 16:16:56 -07002384JDWP::JdwpError Dbg::GetThreadFrameCount(JDWP::ObjectId thread_id, size_t* result) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002385 ScopedObjectAccess soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002386 JDWP::JdwpError error;
2387 *result = 0;
2388 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002389 if (error != JDWP::ERR_NONE) {
2390 return error;
2391 }
Elliott Hughesf15f4a02013-01-09 10:09:38 -08002392 if (!IsSuspendedForDebugger(soa, thread)) {
2393 return JDWP::ERR_THREAD_NOT_SUSPENDED;
2394 }
Ian Rogersc0542af2014-09-03 16:16:56 -07002395 *result = GetStackDepth(thread);
Elliott Hughes221229c2013-01-08 18:17:50 -08002396 return JDWP::ERR_NONE;
Elliott Hughes86964332012-02-15 19:37:42 -08002397}
2398
Andreas Gampec7d878d2018-11-19 18:42:06 +00002399JDWP::JdwpError Dbg::GetThreadFrames(JDWP::ObjectId thread_id,
2400 const size_t start_frame,
2401 const size_t frame_count,
2402 JDWP::ExpandBuf* buf) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002403 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002404 JDWP::JdwpError error;
2405 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002406 if (error != JDWP::ERR_NONE) {
2407 return error;
2408 }
Elliott Hughesf15f4a02013-01-09 10:09:38 -08002409 if (!IsSuspendedForDebugger(soa, thread)) {
2410 return JDWP::ERR_THREAD_NOT_SUSPENDED;
2411 }
Andreas Gampec7d878d2018-11-19 18:42:06 +00002412
2413 expandBufAdd4BE(buf, frame_count);
2414
2415 size_t depth = 0u;
2416 StackVisitor::WalkStack(
2417 [&](StackVisitor* visitor) REQUIRES_SHARED(Locks::mutator_lock_) {
2418 if (visitor->GetMethod()->IsRuntimeMethod()) {
2419 return true; // The debugger can't do anything useful with a frame that has no Method*.
2420 }
2421 if (depth >= start_frame + frame_count) {
2422 return false;
2423 }
2424 if (depth >= start_frame) {
2425 JDWP::FrameId frame_id(visitor->GetFrameId());
2426 JDWP::JdwpLocation location;
2427 SetJdwpLocation(&location, visitor->GetMethod(), visitor->GetDexPc());
2428 VLOG(jdwp)
2429 << StringPrintf(" Frame %3zd: id=%3" PRIu64 " ", depth, frame_id) << location;
2430 expandBufAdd8BE(buf, frame_id);
2431 expandBufAddLocation(buf, location);
2432 }
2433 ++depth;
2434 return true;
2435 },
2436 thread,
2437 /* context= */ nullptr,
2438 StackVisitor::StackWalkKind::kIncludeInlinedFrames);
2439
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002440 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002441}
2442
2443JDWP::ObjectId Dbg::GetThreadSelfId() {
Sebastien Hertz6995c602014-09-09 12:10:13 +02002444 return GetThreadId(Thread::Current());
2445}
2446
2447JDWP::ObjectId Dbg::GetThreadId(Thread* thread) {
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07002448 ScopedObjectAccessUnchecked soa(Thread::Current());
Nicolas Geoffraycafa0812017-02-15 18:27:34 +00002449 return gRegistry->Add(thread->GetPeerFromOtherThread());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002450}
2451
Elliott Hughes475fc232011-10-25 15:00:35 -07002452void Dbg::SuspendVM() {
Hiroshi Yamauchi8f95cf32016-04-19 11:14:06 -07002453 // Avoid a deadlock between GC and debugger where GC gets suspended during GC. b/25800335.
2454 gc::ScopedGCCriticalSection gcs(Thread::Current(),
2455 gc::kGcCauseDebugger,
2456 gc::kCollectorTypeDebugger);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002457 Runtime::Current()->GetThreadList()->SuspendAllForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002458}
2459
2460void Dbg::ResumeVM() {
Sebastien Hertz253fa552014-10-14 17:27:15 +02002461 Runtime::Current()->GetThreadList()->ResumeAllForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002462}
2463
Elliott Hughes221229c2013-01-08 18:17:50 -08002464JDWP::JdwpError Dbg::SuspendThread(JDWP::ObjectId thread_id, bool request_suspension) {
Ian Rogersf3d874c2014-07-17 18:52:42 -07002465 Thread* self = Thread::Current();
Ian Rogersc0542af2014-09-03 16:16:56 -07002466 ScopedLocalRef<jobject> peer(self->GetJniEnv(), nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002467 {
Ian Rogersf3d874c2014-07-17 18:52:42 -07002468 ScopedObjectAccess soa(self);
Ian Rogersc0542af2014-09-03 16:16:56 -07002469 JDWP::JdwpError error;
2470 peer.reset(soa.AddLocalReference<jobject>(gRegistry->Get<mirror::Object*>(thread_id, &error)));
Elliott Hughes4e235312011-12-02 11:34:15 -08002471 }
Ian Rogersc0542af2014-09-03 16:16:56 -07002472 if (peer.get() == nullptr) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002473 return JDWP::ERR_THREAD_NOT_ALIVE;
2474 }
Ian Rogers4ad5cd32014-11-11 23:08:07 -08002475 // Suspend thread to build stack trace.
Elliott Hughesf327e072013-01-09 16:01:26 -08002476 bool timed_out;
Brian Carlstromba32de42014-08-27 23:43:46 -07002477 ThreadList* thread_list = Runtime::Current()->GetThreadList();
Sebastien Hertzcdd798d2017-04-18 18:28:51 +02002478 Thread* thread = thread_list->SuspendThreadByPeer(peer.get(),
2479 request_suspension,
Alex Light46f93402017-06-29 11:59:50 -07002480 SuspendReason::kForDebugger,
Brian Carlstromba32de42014-08-27 23:43:46 -07002481 &timed_out);
Ian Rogersc0542af2014-09-03 16:16:56 -07002482 if (thread != nullptr) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002483 return JDWP::ERR_NONE;
Elliott Hughesf327e072013-01-09 16:01:26 -08002484 } else if (timed_out) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002485 return JDWP::ERR_INTERNAL;
2486 } else {
2487 return JDWP::ERR_THREAD_NOT_ALIVE;
2488 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002489}
2490
Elliott Hughes221229c2013-01-08 18:17:50 -08002491void Dbg::ResumeThread(JDWP::ObjectId thread_id) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002492 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002493 JDWP::JdwpError error;
2494 mirror::Object* peer = gRegistry->Get<mirror::Object*>(thread_id, &error);
2495 CHECK(peer != nullptr) << error;
jeffhaoa77f0f62012-12-05 17:19:31 -08002496 Thread* thread;
2497 {
2498 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
2499 thread = Thread::FromManagedThread(soa, peer);
2500 }
Ian Rogersc0542af2014-09-03 16:16:56 -07002501 if (thread == nullptr) {
Elliott Hughes4e235312011-12-02 11:34:15 -08002502 LOG(WARNING) << "No such thread for resume: " << peer;
2503 return;
2504 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002505 bool needs_resume;
2506 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002507 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Sebastien Hertz70d60272017-04-14 14:18:36 +02002508 needs_resume = thread->GetDebugSuspendCount() > 0;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002509 }
2510 if (needs_resume) {
Alex Light88fd7202017-06-30 08:31:59 -07002511 bool resumed = Runtime::Current()->GetThreadList()->Resume(thread, SuspendReason::kForDebugger);
2512 DCHECK(resumed);
Elliott Hughes546b9862012-06-20 16:06:13 -07002513 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002514}
2515
2516void Dbg::SuspendSelf() {
Elliott Hughes475fc232011-10-25 15:00:35 -07002517 Runtime::Current()->GetThreadList()->SuspendSelfForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002518}
2519
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002520JDWP::JdwpError Dbg::GetThisObject(JDWP::ObjectId thread_id, JDWP::FrameId frame_id,
2521 JDWP::ObjectId* result) {
2522 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz69206392015-04-07 15:54:25 +02002523 JDWP::JdwpError error;
2524 Thread* thread = DecodeThread(soa, thread_id, &error);
2525 if (error != JDWP::ERR_NONE) {
2526 return error;
2527 }
2528 if (!IsSuspendedForDebugger(soa, thread)) {
2529 return JDWP::ERR_THREAD_NOT_SUSPENDED;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002530 }
Ian Rogers700a4022014-05-19 16:49:03 -07002531 std::unique_ptr<Context> context(Context::Create());
Andreas Gampec7d878d2018-11-19 18:42:06 +00002532 mirror::Object* this_object = nullptr;
2533 StackVisitor::WalkStack(
2534 [&](art::StackVisitor* stack_visitor) REQUIRES_SHARED(Locks::mutator_lock_) {
2535 if (frame_id != stack_visitor->GetFrameId()) {
2536 return true; // continue
2537 } else {
2538 this_object = stack_visitor->GetThisObject();
2539 return false;
2540 }
2541 },
2542 thread,
2543 context.get(),
2544 art::StackVisitor::StackWalkKind::kIncludeInlinedFrames);
2545 *result = gRegistry->Add(this_object);
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002546 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002547}
2548
Andreas Gampec7d878d2018-11-19 18:42:06 +00002549template <typename FrameHandler>
2550static JDWP::JdwpError FindAndHandleNonNativeFrame(Thread* thread,
2551 JDWP::FrameId frame_id,
2552 const FrameHandler& handler)
2553 REQUIRES_SHARED(Locks::mutator_lock_) {
2554 JDWP::JdwpError result = JDWP::ERR_INVALID_FRAMEID;
2555 std::unique_ptr<Context> context(Context::Create());
2556 StackVisitor::WalkStack(
2557 [&](art::StackVisitor* stack_visitor) REQUIRES_SHARED(Locks::mutator_lock_) {
2558 if (stack_visitor->GetFrameId() != frame_id) {
2559 return true; // Not our frame, carry on.
2560 }
2561 ArtMethod* m = stack_visitor->GetMethod();
2562 if (m->IsNative()) {
2563 // We can't read/write local value from/into native method.
2564 result = JDWP::ERR_OPAQUE_FRAME;
2565 } else {
2566 // We found our frame.
2567 result = handler(stack_visitor);
2568 }
2569 return false;
2570 },
2571 thread,
2572 context.get(),
2573 art::StackVisitor::StackWalkKind::kIncludeInlinedFrames);
2574 return result;
2575}
Sebastien Hertz8009f392014-09-01 17:07:11 +02002576
2577JDWP::JdwpError Dbg::GetLocalValues(JDWP::Request* request, JDWP::ExpandBuf* pReply) {
2578 JDWP::ObjectId thread_id = request->ReadThreadId();
2579 JDWP::FrameId frame_id = request->ReadFrameId();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002580
2581 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz69206392015-04-07 15:54:25 +02002582 JDWP::JdwpError error;
2583 Thread* thread = DecodeThread(soa, thread_id, &error);
2584 if (error != JDWP::ERR_NONE) {
2585 return error;
2586 }
2587 if (!IsSuspendedForDebugger(soa, thread)) {
2588 return JDWP::ERR_THREAD_NOT_SUSPENDED;
Elliott Hughes221229c2013-01-08 18:17:50 -08002589 }
Sebastien Hertz8009f392014-09-01 17:07:11 +02002590
Andreas Gampec7d878d2018-11-19 18:42:06 +00002591 return FindAndHandleNonNativeFrame(
2592 thread,
2593 frame_id,
2594 [&](art::StackVisitor* stack_visitor) REQUIRES_SHARED(Locks::mutator_lock_) {
2595 // Read the values from visitor's context.
2596 int32_t slot_count = request->ReadSigned32("slot count");
2597 expandBufAdd4BE(pReply, slot_count); /* "int values" */
2598 for (int32_t i = 0; i < slot_count; ++i) {
2599 uint32_t slot = request->ReadUnsigned32("slot");
2600 JDWP::JdwpTag reqSigByte = request->ReadTag();
Sebastien Hertz8009f392014-09-01 17:07:11 +02002601
Andreas Gampec7d878d2018-11-19 18:42:06 +00002602 VLOG(jdwp) << " --> slot " << slot << " " << reqSigByte;
Sebastien Hertz8009f392014-09-01 17:07:11 +02002603
Andreas Gampec7d878d2018-11-19 18:42:06 +00002604 size_t width = Dbg::GetTagWidth(reqSigByte);
2605 uint8_t* ptr = expandBufAddSpace(pReply, width + 1);
2606 error = Dbg::GetLocalValue(*stack_visitor, soa, slot, reqSigByte, ptr, width);
2607 if (error != JDWP::ERR_NONE) {
2608 return error;
2609 }
2610 }
2611 return JDWP::ERR_NONE;
2612 });
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002613}
2614
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002615constexpr JDWP::JdwpError kStackFrameLocalAccessError = JDWP::ERR_ABSENT_INFORMATION;
2616
2617static std::string GetStackContextAsString(const StackVisitor& visitor)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002618 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002619 return StringPrintf(" at DEX pc 0x%08x in method %s", visitor.GetDexPc(false),
David Sehr709b0702016-10-13 09:12:37 -07002620 ArtMethod::PrettyMethod(visitor.GetMethod()).c_str());
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002621}
2622
2623static JDWP::JdwpError FailGetLocalValue(const StackVisitor& visitor, uint16_t vreg,
2624 JDWP::JdwpTag tag)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002625 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002626 LOG(ERROR) << "Failed to read " << tag << " local from register v" << vreg
2627 << GetStackContextAsString(visitor);
2628 return kStackFrameLocalAccessError;
2629}
2630
Sebastien Hertz8009f392014-09-01 17:07:11 +02002631JDWP::JdwpError Dbg::GetLocalValue(const StackVisitor& visitor, ScopedObjectAccessUnchecked& soa,
2632 int slot, JDWP::JdwpTag tag, uint8_t* buf, size_t width) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002633 ArtMethod* m = visitor.GetMethod();
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002634 JDWP::JdwpError error = JDWP::ERR_NONE;
2635 uint16_t vreg = DemangleSlot(slot, m, &error);
2636 if (error != JDWP::ERR_NONE) {
2637 return error;
2638 }
Sebastien Hertz8009f392014-09-01 17:07:11 +02002639 // TODO: check that the tag is compatible with the actual type of the slot!
Sebastien Hertz8009f392014-09-01 17:07:11 +02002640 switch (tag) {
2641 case JDWP::JT_BOOLEAN: {
2642 CHECK_EQ(width, 1U);
2643 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002644 if (!visitor.GetVReg(m, vreg, kIntVReg, &intVal)) {
2645 return FailGetLocalValue(visitor, vreg, tag);
Ian Rogers0399dde2012-06-06 17:09:28 -07002646 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002647 VLOG(jdwp) << "get boolean local " << vreg << " = " << intVal;
2648 JDWP::Set1(buf + 1, intVal != 0);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002649 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002650 }
Sebastien Hertz8009f392014-09-01 17:07:11 +02002651 case JDWP::JT_BYTE: {
2652 CHECK_EQ(width, 1U);
2653 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002654 if (!visitor.GetVReg(m, vreg, kIntVReg, &intVal)) {
2655 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002656 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002657 VLOG(jdwp) << "get byte local " << vreg << " = " << intVal;
2658 JDWP::Set1(buf + 1, intVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002659 break;
2660 }
2661 case JDWP::JT_SHORT:
2662 case JDWP::JT_CHAR: {
2663 CHECK_EQ(width, 2U);
2664 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002665 if (!visitor.GetVReg(m, vreg, kIntVReg, &intVal)) {
2666 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002667 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002668 VLOG(jdwp) << "get short/char local " << vreg << " = " << intVal;
2669 JDWP::Set2BE(buf + 1, intVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002670 break;
2671 }
2672 case JDWP::JT_INT: {
2673 CHECK_EQ(width, 4U);
2674 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002675 if (!visitor.GetVReg(m, vreg, kIntVReg, &intVal)) {
2676 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002677 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002678 VLOG(jdwp) << "get int local " << vreg << " = " << intVal;
2679 JDWP::Set4BE(buf + 1, intVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002680 break;
2681 }
2682 case JDWP::JT_FLOAT: {
2683 CHECK_EQ(width, 4U);
2684 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002685 if (!visitor.GetVReg(m, vreg, kFloatVReg, &intVal)) {
2686 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002687 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002688 VLOG(jdwp) << "get float local " << vreg << " = " << intVal;
2689 JDWP::Set4BE(buf + 1, intVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002690 break;
2691 }
2692 case JDWP::JT_ARRAY:
2693 case JDWP::JT_CLASS_LOADER:
2694 case JDWP::JT_CLASS_OBJECT:
2695 case JDWP::JT_OBJECT:
2696 case JDWP::JT_STRING:
2697 case JDWP::JT_THREAD:
2698 case JDWP::JT_THREAD_GROUP: {
2699 CHECK_EQ(width, sizeof(JDWP::ObjectId));
2700 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002701 if (!visitor.GetVReg(m, vreg, kReferenceVReg, &intVal)) {
2702 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002703 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002704 mirror::Object* o = reinterpret_cast<mirror::Object*>(intVal);
2705 VLOG(jdwp) << "get " << tag << " object local " << vreg << " = " << o;
2706 if (!Runtime::Current()->GetHeap()->IsValidObjectAddress(o)) {
2707 LOG(FATAL) << StringPrintf("Found invalid object %#" PRIxPTR " in register v%u",
2708 reinterpret_cast<uintptr_t>(o), vreg)
2709 << GetStackContextAsString(visitor);
2710 UNREACHABLE();
2711 }
2712 tag = TagFromObject(soa, o);
2713 JDWP::SetObjectId(buf + 1, gRegistry->Add(o));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002714 break;
2715 }
2716 case JDWP::JT_DOUBLE: {
2717 CHECK_EQ(width, 8U);
2718 uint64_t longVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002719 if (!visitor.GetVRegPair(m, vreg, kDoubleLoVReg, kDoubleHiVReg, &longVal)) {
2720 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002721 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002722 VLOG(jdwp) << "get double local " << vreg << " = " << longVal;
2723 JDWP::Set8BE(buf + 1, longVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002724 break;
2725 }
2726 case JDWP::JT_LONG: {
2727 CHECK_EQ(width, 8U);
2728 uint64_t longVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002729 if (!visitor.GetVRegPair(m, vreg, kLongLoVReg, kLongHiVReg, &longVal)) {
2730 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002731 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002732 VLOG(jdwp) << "get long local " << vreg << " = " << longVal;
2733 JDWP::Set8BE(buf + 1, longVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002734 break;
2735 }
2736 default:
2737 LOG(FATAL) << "Unknown tag " << tag;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002738 UNREACHABLE();
Sebastien Hertz8009f392014-09-01 17:07:11 +02002739 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002740
Sebastien Hertz8009f392014-09-01 17:07:11 +02002741 // Prepend tag, which may have been updated.
2742 JDWP::Set1(buf, tag);
2743 return JDWP::ERR_NONE;
2744}
2745
2746JDWP::JdwpError Dbg::SetLocalValues(JDWP::Request* request) {
2747 JDWP::ObjectId thread_id = request->ReadThreadId();
2748 JDWP::FrameId frame_id = request->ReadFrameId();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002749
2750 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz69206392015-04-07 15:54:25 +02002751 JDWP::JdwpError error;
2752 Thread* thread = DecodeThread(soa, thread_id, &error);
2753 if (error != JDWP::ERR_NONE) {
2754 return error;
2755 }
2756 if (!IsSuspendedForDebugger(soa, thread)) {
2757 return JDWP::ERR_THREAD_NOT_SUSPENDED;
Elliott Hughes221229c2013-01-08 18:17:50 -08002758 }
Sebastien Hertz8009f392014-09-01 17:07:11 +02002759
Andreas Gampec7d878d2018-11-19 18:42:06 +00002760 return FindAndHandleNonNativeFrame(
2761 thread,
2762 frame_id,
2763 [&](art::StackVisitor* stack_visitor) REQUIRES_SHARED(Locks::mutator_lock_) {
2764 // Writes the values into visitor's context.
2765 int32_t slot_count = request->ReadSigned32("slot count");
2766 for (int32_t i = 0; i < slot_count; ++i) {
2767 uint32_t slot = request->ReadUnsigned32("slot");
2768 JDWP::JdwpTag sigByte = request->ReadTag();
2769 size_t width = Dbg::GetTagWidth(sigByte);
2770 uint64_t value = request->ReadValue(width);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002771
Andreas Gampec7d878d2018-11-19 18:42:06 +00002772 VLOG(jdwp) << " --> slot " << slot << " " << sigByte << " " << value;
2773 error = Dbg::SetLocalValue(thread, *stack_visitor, slot, sigByte, value, width);
2774 if (error != JDWP::ERR_NONE) {
2775 return error;
2776 }
2777 }
2778 return JDWP::ERR_NONE;
2779 });
Sebastien Hertz8009f392014-09-01 17:07:11 +02002780}
2781
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002782template<typename T>
2783static JDWP::JdwpError FailSetLocalValue(const StackVisitor& visitor, uint16_t vreg,
2784 JDWP::JdwpTag tag, T value)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002785 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002786 LOG(ERROR) << "Failed to write " << tag << " local " << value
2787 << " (0x" << std::hex << value << ") into register v" << vreg
2788 << GetStackContextAsString(visitor);
2789 return kStackFrameLocalAccessError;
2790}
2791
Mingyao Yang99170c62015-07-06 11:10:37 -07002792JDWP::JdwpError Dbg::SetLocalValue(Thread* thread, StackVisitor& visitor, int slot,
2793 JDWP::JdwpTag tag, uint64_t value, size_t width) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002794 ArtMethod* m = visitor.GetMethod();
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002795 JDWP::JdwpError error = JDWP::ERR_NONE;
2796 uint16_t vreg = DemangleSlot(slot, m, &error);
2797 if (error != JDWP::ERR_NONE) {
2798 return error;
2799 }
Sebastien Hertz8009f392014-09-01 17:07:11 +02002800 // TODO: check that the tag is compatible with the actual type of the slot!
Sebastien Hertz8009f392014-09-01 17:07:11 +02002801 switch (tag) {
2802 case JDWP::JT_BOOLEAN:
2803 case JDWP::JT_BYTE:
2804 CHECK_EQ(width, 1U);
Mingyao Yang636b9252015-07-31 16:40:24 -07002805 if (!visitor.SetVReg(m, vreg, static_cast<uint32_t>(value), kIntVReg)) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002806 return FailSetLocalValue(visitor, vreg, tag, static_cast<uint32_t>(value));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002807 }
2808 break;
2809 case JDWP::JT_SHORT:
2810 case JDWP::JT_CHAR:
2811 CHECK_EQ(width, 2U);
Mingyao Yang636b9252015-07-31 16:40:24 -07002812 if (!visitor.SetVReg(m, vreg, static_cast<uint32_t>(value), kIntVReg)) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002813 return FailSetLocalValue(visitor, vreg, tag, static_cast<uint32_t>(value));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002814 }
2815 break;
2816 case JDWP::JT_INT:
2817 CHECK_EQ(width, 4U);
Mingyao Yang636b9252015-07-31 16:40:24 -07002818 if (!visitor.SetVReg(m, vreg, static_cast<uint32_t>(value), kIntVReg)) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002819 return FailSetLocalValue(visitor, vreg, tag, static_cast<uint32_t>(value));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002820 }
2821 break;
2822 case JDWP::JT_FLOAT:
2823 CHECK_EQ(width, 4U);
Mingyao Yang636b9252015-07-31 16:40:24 -07002824 if (!visitor.SetVReg(m, vreg, static_cast<uint32_t>(value), kFloatVReg)) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002825 return FailSetLocalValue(visitor, vreg, tag, static_cast<uint32_t>(value));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002826 }
2827 break;
2828 case JDWP::JT_ARRAY:
2829 case JDWP::JT_CLASS_LOADER:
2830 case JDWP::JT_CLASS_OBJECT:
2831 case JDWP::JT_OBJECT:
2832 case JDWP::JT_STRING:
2833 case JDWP::JT_THREAD:
2834 case JDWP::JT_THREAD_GROUP: {
2835 CHECK_EQ(width, sizeof(JDWP::ObjectId));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002836 mirror::Object* o = gRegistry->Get<mirror::Object*>(static_cast<JDWP::ObjectId>(value),
2837 &error);
2838 if (error != JDWP::ERR_NONE) {
2839 VLOG(jdwp) << tag << " object " << o << " is an invalid object";
2840 return JDWP::ERR_INVALID_OBJECT;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002841 }
Mingyao Yang636b9252015-07-31 16:40:24 -07002842 if (!visitor.SetVReg(m, vreg, static_cast<uint32_t>(reinterpret_cast<uintptr_t>(o)),
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002843 kReferenceVReg)) {
2844 return FailSetLocalValue(visitor, vreg, tag, reinterpret_cast<uintptr_t>(o));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002845 }
2846 break;
2847 }
2848 case JDWP::JT_DOUBLE: {
2849 CHECK_EQ(width, 8U);
Mingyao Yang636b9252015-07-31 16:40:24 -07002850 if (!visitor.SetVRegPair(m, vreg, value, kDoubleLoVReg, kDoubleHiVReg)) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002851 return FailSetLocalValue(visitor, vreg, tag, value);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002852 }
2853 break;
2854 }
2855 case JDWP::JT_LONG: {
2856 CHECK_EQ(width, 8U);
Mingyao Yang636b9252015-07-31 16:40:24 -07002857 if (!visitor.SetVRegPair(m, vreg, value, kLongLoVReg, kLongHiVReg)) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002858 return FailSetLocalValue(visitor, vreg, tag, value);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002859 }
2860 break;
2861 }
2862 default:
2863 LOG(FATAL) << "Unknown tag " << tag;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002864 UNREACHABLE();
Sebastien Hertz8009f392014-09-01 17:07:11 +02002865 }
Mingyao Yang99170c62015-07-06 11:10:37 -07002866
2867 // If we set the local variable in a compiled frame, we need to trigger a deoptimization of
2868 // the stack so we continue execution with the interpreter using the new value(s) of the updated
2869 // local variable(s). To achieve this, we install instrumentation exit stub on each method of the
2870 // thread's stack. The stub will cause the deoptimization to happen.
2871 if (!visitor.IsShadowFrame() && thread->HasDebuggerShadowFrames()) {
2872 Runtime::Current()->GetInstrumentation()->InstrumentThreadStack(thread);
2873 }
2874
Sebastien Hertz8009f392014-09-01 17:07:11 +02002875 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002876}
2877
Mathieu Chartiere401d142015-04-22 13:56:20 -07002878static void SetEventLocation(JDWP::EventLocation* location, ArtMethod* m, uint32_t dex_pc)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002879 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz6995c602014-09-09 12:10:13 +02002880 DCHECK(location != nullptr);
2881 if (m == nullptr) {
2882 memset(location, 0, sizeof(*location));
2883 } else {
Alex Light97e78032017-06-27 17:51:55 -07002884 location->method = m->GetCanonicalMethod(kRuntimePointerSize);
Sebastien Hertz6995c602014-09-09 12:10:13 +02002885 location->dex_pc = (m->IsNative() || m->IsProxyMethod()) ? static_cast<uint32_t>(-1) : dex_pc;
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002886 }
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002887}
2888
Mathieu Chartiere401d142015-04-22 13:56:20 -07002889void Dbg::PostLocationEvent(ArtMethod* m, int dex_pc, mirror::Object* this_object,
Jeff Hao579b0242013-11-18 13:16:49 -08002890 int event_flags, const JValue* return_value) {
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002891 if (!IsDebuggerActive()) {
2892 return;
2893 }
2894 DCHECK(m != nullptr);
2895 DCHECK_EQ(m->IsStatic(), this_object == nullptr);
Sebastien Hertz6995c602014-09-09 12:10:13 +02002896 JDWP::EventLocation location;
2897 SetEventLocation(&location, m, dex_pc);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002898
Sebastien Hertzde48aa62015-05-26 11:53:39 +02002899 // We need to be sure no exception is pending when calling JdwpState::PostLocationEvent.
2900 // This is required to be able to call JNI functions to create JDWP ids. To achieve this,
2901 // we temporarily clear the current thread's exception (if any) and will restore it after
2902 // the call.
2903 // Note: the only way to get a pending exception here is to suspend on a move-exception
2904 // instruction.
2905 Thread* const self = Thread::Current();
2906 StackHandleScope<1> hs(self);
2907 Handle<mirror::Throwable> pending_exception(hs.NewHandle(self->GetException()));
2908 self->ClearException();
Andreas Gampefa4333d2017-02-14 11:10:34 -08002909 if (kIsDebugBuild && pending_exception != nullptr) {
Mathieu Chartier808c7a52017-12-15 11:19:33 -08002910 const Instruction& instr = location.method->DexInstructions().InstructionAt(location.dex_pc);
2911 CHECK_EQ(Instruction::MOVE_EXCEPTION, instr.Opcode());
Sebastien Hertzde48aa62015-05-26 11:53:39 +02002912 }
2913
Sebastien Hertz6995c602014-09-09 12:10:13 +02002914 gJdwpState->PostLocationEvent(&location, this_object, event_flags, return_value);
Sebastien Hertzde48aa62015-05-26 11:53:39 +02002915
Andreas Gampefa4333d2017-02-14 11:10:34 -08002916 if (pending_exception != nullptr) {
Sebastien Hertzde48aa62015-05-26 11:53:39 +02002917 self->SetException(pending_exception.Get());
2918 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002919}
2920
Mathieu Chartiere401d142015-04-22 13:56:20 -07002921void Dbg::PostFieldAccessEvent(ArtMethod* m, int dex_pc,
Mathieu Chartierc7853442015-03-27 14:35:38 -07002922 mirror::Object* this_object, ArtField* f) {
Alex Lighte00ec302017-06-16 08:56:43 -07002923 // TODO We should send events for native methods.
2924 if (!IsDebuggerActive() || m->IsNative()) {
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002925 return;
2926 }
2927 DCHECK(m != nullptr);
2928 DCHECK(f != nullptr);
Sebastien Hertz6995c602014-09-09 12:10:13 +02002929 JDWP::EventLocation location;
2930 SetEventLocation(&location, m, dex_pc);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002931
Sebastien Hertz6995c602014-09-09 12:10:13 +02002932 gJdwpState->PostFieldEvent(&location, f, this_object, nullptr, false);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002933}
2934
Mathieu Chartiere401d142015-04-22 13:56:20 -07002935void Dbg::PostFieldModificationEvent(ArtMethod* m, int dex_pc,
Mathieu Chartierc7853442015-03-27 14:35:38 -07002936 mirror::Object* this_object, ArtField* f,
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002937 const JValue* field_value) {
Alex Lighte00ec302017-06-16 08:56:43 -07002938 // TODO We should send events for native methods.
2939 if (!IsDebuggerActive() || m->IsNative()) {
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002940 return;
2941 }
2942 DCHECK(m != nullptr);
2943 DCHECK(f != nullptr);
2944 DCHECK(field_value != nullptr);
Sebastien Hertz6995c602014-09-09 12:10:13 +02002945 JDWP::EventLocation location;
2946 SetEventLocation(&location, m, dex_pc);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002947
Sebastien Hertz6995c602014-09-09 12:10:13 +02002948 gJdwpState->PostFieldEvent(&location, f, this_object, field_value, true);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002949}
2950
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002951void Dbg::PostException(mirror::Throwable* exception_object) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002952 if (!IsDebuggerActive()) {
Ian Rogers0ad5bb82011-12-07 10:16:32 -08002953 return;
2954 }
Sebastien Hertz261bc042015-04-08 09:36:07 +02002955 Thread* const self = Thread::Current();
Andreas Gampec7d878d2018-11-19 18:42:06 +00002956 StackHandleScope<2> handle_scope(self);
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002957 Handle<mirror::Throwable> h_exception(handle_scope.NewHandle(exception_object));
Andreas Gampec7d878d2018-11-19 18:42:06 +00002958 MutableHandle<mirror::Object> this_at_throw = handle_scope.NewHandle<mirror::Object>(nullptr);
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002959 std::unique_ptr<Context> context(Context::Create());
Andreas Gampe3d477f32018-11-16 16:40:45 +00002960
Andreas Gampec7d878d2018-11-19 18:42:06 +00002961 ArtMethod* catch_method = nullptr;
2962 ArtMethod* throw_method = nullptr;
2963 uint32_t catch_dex_pc = dex::kDexNoIndex;
2964 uint32_t throw_dex_pc = dex::kDexNoIndex;
2965 StackVisitor::WalkStack(
2966 /**
2967 * Finds the location where this exception will be caught. We search until we reach the top
2968 * frame, in which case this exception is considered uncaught.
2969 */
2970 [&](const art::StackVisitor* stack_visitor) REQUIRES_SHARED(Locks::mutator_lock_) {
2971 ArtMethod* method = stack_visitor->GetMethod();
2972 DCHECK(method != nullptr);
2973 if (method->IsRuntimeMethod()) {
2974 // Ignore callee save method.
2975 DCHECK(method->IsCalleeSaveMethod());
2976 return true;
2977 }
2978
2979 uint32_t dex_pc = stack_visitor->GetDexPc();
2980 if (throw_method == nullptr) {
2981 // First Java method found. It is either the method that threw the exception,
2982 // or the Java native method that is reporting an exception thrown by
2983 // native code.
2984 this_at_throw.Assign(stack_visitor->GetThisObject());
2985 throw_method = method;
2986 throw_dex_pc = dex_pc;
2987 }
2988
2989 if (dex_pc != dex::kDexNoIndex) {
2990 StackHandleScope<1> hs(stack_visitor->GetThread());
2991 uint32_t found_dex_pc;
2992 Handle<mirror::Class> exception_class(hs.NewHandle(h_exception->GetClass()));
2993 bool unused_clear_exception;
2994 found_dex_pc = method->FindCatchBlock(exception_class, dex_pc, &unused_clear_exception);
2995 if (found_dex_pc != dex::kDexNoIndex) {
2996 catch_method = method;
2997 catch_dex_pc = found_dex_pc;
2998 return false; // End stack walk.
2999 }
3000 }
3001 return true; // Continue stack walk.
3002 },
3003 self,
3004 context.get(),
3005 art::StackVisitor::StackWalkKind::kIncludeInlinedFrames);
3006
3007 JDWP::EventLocation exception_throw_location;
3008 SetEventLocation(&exception_throw_location, throw_method, throw_dex_pc);
3009 JDWP::EventLocation exception_catch_location;
3010 SetEventLocation(&exception_catch_location, catch_method, catch_dex_pc);
3011
3012 gJdwpState->PostException(&exception_throw_location,
3013 h_exception.Get(),
3014 &exception_catch_location,
3015 this_at_throw.Get());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003016}
3017
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003018void Dbg::PostClassPrepare(mirror::Class* c) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07003019 if (!IsDebuggerActive()) {
Elliott Hughes4740cdf2011-12-07 14:07:12 -08003020 return;
3021 }
Sebastien Hertz6995c602014-09-09 12:10:13 +02003022 gJdwpState->PostClassPrepare(c);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003023}
3024
Ian Rogers62d6c772013-02-27 08:32:07 -08003025void Dbg::UpdateDebugger(Thread* thread, mirror::Object* this_object,
Mathieu Chartiere401d142015-04-22 13:56:20 -07003026 ArtMethod* m, uint32_t dex_pc,
Sebastien Hertz8379b222014-02-24 17:38:15 +01003027 int event_flags, const JValue* return_value) {
Ian Rogers62d6c772013-02-27 08:32:07 -08003028 if (!IsDebuggerActive() || dex_pc == static_cast<uint32_t>(-2) /* fake method exit */) {
Elliott Hughes2aa2e392012-02-17 17:15:43 -08003029 return;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003030 }
3031
Elliott Hughes86964332012-02-15 19:37:42 -08003032 if (IsBreakpoint(m, dex_pc)) {
3033 event_flags |= kBreakpoint;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003034 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003035
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003036 // If the debugger is single-stepping one of our threads, check to
3037 // see if we're that thread and we've reached a step point.
3038 const SingleStepControl* single_step_control = thread->GetSingleStepControl();
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003039 if (single_step_control != nullptr) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003040 CHECK(!m->IsNative());
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003041 if (single_step_control->GetStepDepth() == JDWP::SD_INTO) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003042 // Step into method calls. We break when the line number
3043 // or method pointer changes. If we're in SS_MIN mode, we
3044 // always stop.
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003045 if (single_step_control->GetMethod() != m) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003046 event_flags |= kSingleStep;
3047 VLOG(jdwp) << "SS new method";
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003048 } else if (single_step_control->GetStepSize() == JDWP::SS_MIN) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003049 event_flags |= kSingleStep;
3050 VLOG(jdwp) << "SS new instruction";
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003051 } else if (single_step_control->ContainsDexPc(dex_pc)) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003052 event_flags |= kSingleStep;
3053 VLOG(jdwp) << "SS new line";
3054 }
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003055 } else if (single_step_control->GetStepDepth() == JDWP::SD_OVER) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003056 // Step over method calls. We break when the line number is
3057 // different and the frame depth is <= the original frame
3058 // depth. (We can't just compare on the method, because we
3059 // might get unrolled past it by an exception, and it's tricky
3060 // to identify recursion.)
3061
3062 int stack_depth = GetStackDepth(thread);
3063
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003064 if (stack_depth < single_step_control->GetStackDepth()) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003065 // Popped up one or more frames, always trigger.
3066 event_flags |= kSingleStep;
3067 VLOG(jdwp) << "SS method pop";
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003068 } else if (stack_depth == single_step_control->GetStackDepth()) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003069 // Same depth, see if we moved.
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003070 if (single_step_control->GetStepSize() == JDWP::SS_MIN) {
Elliott Hughes86964332012-02-15 19:37:42 -08003071 event_flags |= kSingleStep;
3072 VLOG(jdwp) << "SS new instruction";
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003073 } else if (single_step_control->ContainsDexPc(dex_pc)) {
Elliott Hughes2435a572012-02-17 16:07:41 -08003074 event_flags |= kSingleStep;
3075 VLOG(jdwp) << "SS new line";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003076 }
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003077 }
3078 } else {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003079 CHECK_EQ(single_step_control->GetStepDepth(), JDWP::SD_OUT);
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003080 // Return from the current method. We break when the frame
3081 // depth pops up.
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003082
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003083 // This differs from the "method exit" break in that it stops
3084 // with the PC at the next instruction in the returned-to
3085 // function, rather than the end of the returning function.
Elliott Hughes86964332012-02-15 19:37:42 -08003086
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003087 int stack_depth = GetStackDepth(thread);
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003088 if (stack_depth < single_step_control->GetStackDepth()) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003089 event_flags |= kSingleStep;
3090 VLOG(jdwp) << "SS method pop";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003091 }
3092 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003093 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003094
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003095 // If there's something interesting going on, see if it matches one
3096 // of the debugger filters.
3097 if (event_flags != 0) {
Sebastien Hertz8379b222014-02-24 17:38:15 +01003098 Dbg::PostLocationEvent(m, dex_pc, this_object, event_flags, return_value);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003099 }
3100}
3101
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003102size_t* Dbg::GetReferenceCounterForEvent(uint32_t instrumentation_event) {
3103 switch (instrumentation_event) {
3104 case instrumentation::Instrumentation::kMethodEntered:
3105 return &method_enter_event_ref_count_;
3106 case instrumentation::Instrumentation::kMethodExited:
3107 return &method_exit_event_ref_count_;
3108 case instrumentation::Instrumentation::kDexPcMoved:
3109 return &dex_pc_change_event_ref_count_;
3110 case instrumentation::Instrumentation::kFieldRead:
3111 return &field_read_event_ref_count_;
3112 case instrumentation::Instrumentation::kFieldWritten:
3113 return &field_write_event_ref_count_;
Alex Light6e1607e2017-08-23 10:06:18 -07003114 case instrumentation::Instrumentation::kExceptionThrown:
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003115 return &exception_catch_event_ref_count_;
3116 default:
3117 return nullptr;
3118 }
3119}
3120
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003121// Process request while all mutator threads are suspended.
3122void Dbg::ProcessDeoptimizationRequest(const DeoptimizationRequest& request) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003123 instrumentation::Instrumentation* instrumentation = Runtime::Current()->GetInstrumentation();
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003124 switch (request.GetKind()) {
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003125 case DeoptimizationRequest::kNothing:
3126 LOG(WARNING) << "Ignoring empty deoptimization request.";
3127 break;
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003128 case DeoptimizationRequest::kRegisterForEvent:
3129 VLOG(jdwp) << StringPrintf("Add debugger as listener for instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003130 request.InstrumentationEvent());
3131 instrumentation->AddListener(&gDebugInstrumentationListener, request.InstrumentationEvent());
3132 instrumentation_events_ |= request.InstrumentationEvent();
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003133 break;
3134 case DeoptimizationRequest::kUnregisterForEvent:
3135 VLOG(jdwp) << StringPrintf("Remove debugger as listener for instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003136 request.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003137 instrumentation->RemoveListener(&gDebugInstrumentationListener,
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003138 request.InstrumentationEvent());
3139 instrumentation_events_ &= ~request.InstrumentationEvent();
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003140 break;
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003141 case DeoptimizationRequest::kFullDeoptimization:
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003142 VLOG(jdwp) << "Deoptimize the world ...";
Sebastien Hertz0462c4c2015-04-01 16:34:17 +02003143 instrumentation->DeoptimizeEverything(kDbgInstrumentationKey);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003144 VLOG(jdwp) << "Deoptimize the world DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003145 break;
3146 case DeoptimizationRequest::kFullUndeoptimization:
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003147 VLOG(jdwp) << "Undeoptimize the world ...";
Sebastien Hertz0462c4c2015-04-01 16:34:17 +02003148 instrumentation->UndeoptimizeEverything(kDbgInstrumentationKey);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003149 VLOG(jdwp) << "Undeoptimize the world DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003150 break;
3151 case DeoptimizationRequest::kSelectiveDeoptimization:
David Sehr709b0702016-10-13 09:12:37 -07003152 VLOG(jdwp) << "Deoptimize method " << ArtMethod::PrettyMethod(request.Method()) << " ...";
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003153 instrumentation->Deoptimize(request.Method());
David Sehr709b0702016-10-13 09:12:37 -07003154 VLOG(jdwp) << "Deoptimize method " << ArtMethod::PrettyMethod(request.Method()) << " DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003155 break;
3156 case DeoptimizationRequest::kSelectiveUndeoptimization:
David Sehr709b0702016-10-13 09:12:37 -07003157 VLOG(jdwp) << "Undeoptimize method " << ArtMethod::PrettyMethod(request.Method()) << " ...";
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003158 instrumentation->Undeoptimize(request.Method());
David Sehr709b0702016-10-13 09:12:37 -07003159 VLOG(jdwp) << "Undeoptimize method " << ArtMethod::PrettyMethod(request.Method()) << " DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003160 break;
3161 default:
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003162 LOG(FATAL) << "Unsupported deoptimization request kind " << request.GetKind();
Elliott Hughesc1896c92018-11-29 11:33:18 -08003163 UNREACHABLE();
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003164 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003165}
3166
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003167void Dbg::RequestDeoptimization(const DeoptimizationRequest& req) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003168 if (req.GetKind() == DeoptimizationRequest::kNothing) {
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003169 // Nothing to do.
3170 return;
3171 }
Brian Carlstrom306db812014-09-05 13:01:41 -07003172 MutexLock mu(Thread::Current(), *Locks::deoptimization_lock_);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003173 RequestDeoptimizationLocked(req);
3174}
3175
3176void Dbg::RequestDeoptimizationLocked(const DeoptimizationRequest& req) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003177 switch (req.GetKind()) {
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003178 case DeoptimizationRequest::kRegisterForEvent: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003179 DCHECK_NE(req.InstrumentationEvent(), 0u);
3180 size_t* counter = GetReferenceCounterForEvent(req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003181 CHECK(counter != nullptr) << StringPrintf("No counter for instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003182 req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003183 if (*counter == 0) {
Sebastien Hertz7d2ae432014-05-15 11:26:34 +02003184 VLOG(jdwp) << StringPrintf("Queue request #%zd to start listening to instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003185 deoptimization_requests_.size(), req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003186 deoptimization_requests_.push_back(req);
3187 }
3188 *counter = *counter + 1;
3189 break;
3190 }
3191 case DeoptimizationRequest::kUnregisterForEvent: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003192 DCHECK_NE(req.InstrumentationEvent(), 0u);
3193 size_t* counter = GetReferenceCounterForEvent(req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003194 CHECK(counter != nullptr) << StringPrintf("No counter for instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003195 req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003196 *counter = *counter - 1;
3197 if (*counter == 0) {
Sebastien Hertz7d2ae432014-05-15 11:26:34 +02003198 VLOG(jdwp) << StringPrintf("Queue request #%zd to stop listening to instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003199 deoptimization_requests_.size(), req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003200 deoptimization_requests_.push_back(req);
3201 }
3202 break;
3203 }
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003204 case DeoptimizationRequest::kFullDeoptimization: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003205 DCHECK(req.Method() == nullptr);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003206 if (full_deoptimization_event_count_ == 0) {
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003207 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
3208 << " for full deoptimization";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003209 deoptimization_requests_.push_back(req);
3210 }
3211 ++full_deoptimization_event_count_;
3212 break;
3213 }
3214 case DeoptimizationRequest::kFullUndeoptimization: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003215 DCHECK(req.Method() == nullptr);
Sebastien Hertze713d932014-05-15 10:48:53 +02003216 DCHECK_GT(full_deoptimization_event_count_, 0U);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003217 --full_deoptimization_event_count_;
3218 if (full_deoptimization_event_count_ == 0) {
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003219 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
3220 << " for full undeoptimization";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003221 deoptimization_requests_.push_back(req);
3222 }
3223 break;
3224 }
3225 case DeoptimizationRequest::kSelectiveDeoptimization: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003226 DCHECK(req.Method() != nullptr);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003227 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
David Sehr709b0702016-10-13 09:12:37 -07003228 << " for deoptimization of " << req.Method()->PrettyMethod();
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003229 deoptimization_requests_.push_back(req);
3230 break;
3231 }
3232 case DeoptimizationRequest::kSelectiveUndeoptimization: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003233 DCHECK(req.Method() != nullptr);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003234 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
David Sehr709b0702016-10-13 09:12:37 -07003235 << " for undeoptimization of " << req.Method()->PrettyMethod();
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003236 deoptimization_requests_.push_back(req);
3237 break;
3238 }
3239 default: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003240 LOG(FATAL) << "Unknown deoptimization request kind " << req.GetKind();
Elliott Hughesc1896c92018-11-29 11:33:18 -08003241 UNREACHABLE();
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003242 }
3243 }
3244}
3245
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003246void Dbg::ManageDeoptimization() {
3247 Thread* const self = Thread::Current();
3248 {
3249 // Avoid suspend/resume if there is no pending request.
Brian Carlstrom306db812014-09-05 13:01:41 -07003250 MutexLock mu(self, *Locks::deoptimization_lock_);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003251 if (deoptimization_requests_.empty()) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003252 return;
3253 }
3254 }
3255 CHECK_EQ(self->GetState(), kRunnable);
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07003256 ScopedThreadSuspension sts(self, kWaitingForDeoptimization);
Mathieu Chartieraa516822015-10-02 15:53:37 -07003257 // Required for ProcessDeoptimizationRequest.
3258 gc::ScopedGCCriticalSection gcs(self,
3259 gc::kGcCauseInstrumentation,
3260 gc::kCollectorTypeInstrumentation);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003261 // We need to suspend mutator threads first.
Mathieu Chartier4f55e222015-09-04 13:26:21 -07003262 ScopedSuspendAll ssa(__FUNCTION__);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003263 const ThreadState old_state = self->SetStateUnsafe(kRunnable);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003264 {
Brian Carlstrom306db812014-09-05 13:01:41 -07003265 MutexLock mu(self, *Locks::deoptimization_lock_);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003266 size_t req_index = 0;
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003267 for (DeoptimizationRequest& request : deoptimization_requests_) {
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003268 VLOG(jdwp) << "Process deoptimization request #" << req_index++;
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003269 ProcessDeoptimizationRequest(request);
3270 }
3271 deoptimization_requests_.clear();
3272 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003273 CHECK_EQ(self->SetStateUnsafe(old_state), kRunnable);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003274}
3275
Mathieu Chartiere401d142015-04-22 13:56:20 -07003276static const Breakpoint* FindFirstBreakpointForMethod(ArtMethod* m)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003277 REQUIRES_SHARED(Locks::mutator_lock_, Locks::breakpoint_lock_) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003278 for (Breakpoint& breakpoint : gBreakpoints) {
Alex Light6c8467f2015-11-20 15:03:26 -08003279 if (breakpoint.IsInMethod(m)) {
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003280 return &breakpoint;
3281 }
3282 }
3283 return nullptr;
3284}
3285
Mathieu Chartiere401d142015-04-22 13:56:20 -07003286bool Dbg::MethodHasAnyBreakpoints(ArtMethod* method) {
Mathieu Chartierd8565452015-03-26 09:41:50 -07003287 ReaderMutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
3288 return FindFirstBreakpointForMethod(method) != nullptr;
3289}
3290
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003291// Sanity checks all existing breakpoints on the same method.
Mathieu Chartiere401d142015-04-22 13:56:20 -07003292static void SanityCheckExistingBreakpoints(ArtMethod* m,
Sebastien Hertzf3928792014-11-17 19:00:37 +01003293 DeoptimizationRequest::Kind deoptimization_kind)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003294 REQUIRES_SHARED(Locks::mutator_lock_, Locks::breakpoint_lock_) {
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003295 for (const Breakpoint& breakpoint : gBreakpoints) {
Alex Light6c8467f2015-11-20 15:03:26 -08003296 if (breakpoint.IsInMethod(m)) {
Sebastien Hertzf3928792014-11-17 19:00:37 +01003297 CHECK_EQ(deoptimization_kind, breakpoint.GetDeoptimizationKind());
3298 }
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003299 }
Sebastien Hertzf3928792014-11-17 19:00:37 +01003300 instrumentation::Instrumentation* instrumentation = Runtime::Current()->GetInstrumentation();
3301 if (deoptimization_kind == DeoptimizationRequest::kFullDeoptimization) {
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003302 // We should have deoptimized everything but not "selectively" deoptimized this method.
Sebastien Hertzf3928792014-11-17 19:00:37 +01003303 CHECK(instrumentation->AreAllMethodsDeoptimized());
3304 CHECK(!instrumentation->IsDeoptimized(m));
3305 } else if (deoptimization_kind == DeoptimizationRequest::kSelectiveDeoptimization) {
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003306 // We should have "selectively" deoptimized this method.
3307 // Note: while we have not deoptimized everything for this method, we may have done it for
3308 // another event.
Sebastien Hertzf3928792014-11-17 19:00:37 +01003309 CHECK(instrumentation->IsDeoptimized(m));
3310 } else {
3311 // This method does not require deoptimization.
3312 CHECK_EQ(deoptimization_kind, DeoptimizationRequest::kNothing);
3313 CHECK(!instrumentation->IsDeoptimized(m));
3314 }
3315}
3316
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003317// Returns the deoptimization kind required to set a breakpoint in a method.
3318// If a breakpoint has already been set, we also return the first breakpoint
3319// through the given 'existing_brkpt' pointer.
Sebastien Hertzf3928792014-11-17 19:00:37 +01003320static DeoptimizationRequest::Kind GetRequiredDeoptimizationKind(Thread* self,
Mathieu Chartiere401d142015-04-22 13:56:20 -07003321 ArtMethod* m,
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003322 const Breakpoint** existing_brkpt)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003323 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertzf3928792014-11-17 19:00:37 +01003324 if (!Dbg::RequiresDeoptimization()) {
3325 // We already run in interpreter-only mode so we don't need to deoptimize anything.
3326 VLOG(jdwp) << "No need for deoptimization when fully running with interpreter for method "
David Sehr709b0702016-10-13 09:12:37 -07003327 << ArtMethod::PrettyMethod(m);
Sebastien Hertzf3928792014-11-17 19:00:37 +01003328 return DeoptimizationRequest::kNothing;
3329 }
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003330 const Breakpoint* first_breakpoint;
Sebastien Hertzf3928792014-11-17 19:00:37 +01003331 {
3332 ReaderMutexLock mu(self, *Locks::breakpoint_lock_);
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003333 first_breakpoint = FindFirstBreakpointForMethod(m);
3334 *existing_brkpt = first_breakpoint;
Sebastien Hertzf3928792014-11-17 19:00:37 +01003335 }
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003336
3337 if (first_breakpoint == nullptr) {
Nicolas Geoffray6300fd72016-03-18 09:40:17 +00003338 // There is no breakpoint on this method yet: we need to deoptimize. If this method is default,
3339 // we deoptimize everything; otherwise we deoptimize only this method. We
Alex Light6c8467f2015-11-20 15:03:26 -08003340 // deoptimize with defaults because we do not know everywhere they are used. It is possible some
Nicolas Geoffray6300fd72016-03-18 09:40:17 +00003341 // of the copies could be missed.
Alex Light6c8467f2015-11-20 15:03:26 -08003342 // TODO Deoptimizing on default methods might not be necessary in all cases.
Nicolas Geoffray6300fd72016-03-18 09:40:17 +00003343 bool need_full_deoptimization = m->IsDefault();
Sebastien Hertzf3928792014-11-17 19:00:37 +01003344 if (need_full_deoptimization) {
Nicolas Geoffray6300fd72016-03-18 09:40:17 +00003345 VLOG(jdwp) << "Need full deoptimization because of copying of method "
David Sehr709b0702016-10-13 09:12:37 -07003346 << ArtMethod::PrettyMethod(m);
Sebastien Hertzf3928792014-11-17 19:00:37 +01003347 return DeoptimizationRequest::kFullDeoptimization;
3348 } else {
3349 // We don't need to deoptimize if the method has not been compiled.
Nicolas Geoffraya5891e82015-11-06 14:18:27 +00003350 const bool is_compiled = m->HasAnyCompiledCode();
Sebastien Hertzf3928792014-11-17 19:00:37 +01003351 if (is_compiled) {
David Sehr709b0702016-10-13 09:12:37 -07003352 VLOG(jdwp) << "Need selective deoptimization for compiled method "
3353 << ArtMethod::PrettyMethod(m);
Nicolas Geoffray6300fd72016-03-18 09:40:17 +00003354 return DeoptimizationRequest::kSelectiveDeoptimization;
Sebastien Hertzf3928792014-11-17 19:00:37 +01003355 } else {
3356 // Method is not compiled: we don't need to deoptimize.
David Sehr709b0702016-10-13 09:12:37 -07003357 VLOG(jdwp) << "No need for deoptimization for non-compiled method "
3358 << ArtMethod::PrettyMethod(m);
Sebastien Hertzf3928792014-11-17 19:00:37 +01003359 return DeoptimizationRequest::kNothing;
3360 }
3361 }
3362 } else {
3363 // There is at least one breakpoint for this method: we don't need to deoptimize.
3364 // Let's check that all breakpoints are configured the same way for deoptimization.
3365 VLOG(jdwp) << "Breakpoint already set: no deoptimization is required";
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003366 DeoptimizationRequest::Kind deoptimization_kind = first_breakpoint->GetDeoptimizationKind();
Sebastien Hertzf3928792014-11-17 19:00:37 +01003367 if (kIsDebugBuild) {
3368 ReaderMutexLock mu(self, *Locks::breakpoint_lock_);
3369 SanityCheckExistingBreakpoints(m, deoptimization_kind);
3370 }
3371 return DeoptimizationRequest::kNothing;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003372 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003373}
3374
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003375// Installs a breakpoint at the specified location. Also indicates through the deoptimization
3376// request if we need to deoptimize.
3377void Dbg::WatchLocation(const JDWP::JdwpLocation* location, DeoptimizationRequest* req) {
3378 Thread* const self = Thread::Current();
Mathieu Chartiere401d142015-04-22 13:56:20 -07003379 ArtMethod* m = FromMethodId(location->method_id);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003380 DCHECK(m != nullptr) << "No method for method id " << location->method_id;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003381
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003382 const Breakpoint* existing_breakpoint = nullptr;
3383 const DeoptimizationRequest::Kind deoptimization_kind =
3384 GetRequiredDeoptimizationKind(self, m, &existing_breakpoint);
Sebastien Hertzf3928792014-11-17 19:00:37 +01003385 req->SetKind(deoptimization_kind);
3386 if (deoptimization_kind == DeoptimizationRequest::kSelectiveDeoptimization) {
3387 req->SetMethod(m);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003388 } else {
Sebastien Hertzf3928792014-11-17 19:00:37 +01003389 CHECK(deoptimization_kind == DeoptimizationRequest::kNothing ||
3390 deoptimization_kind == DeoptimizationRequest::kFullDeoptimization);
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003391 req->SetMethod(nullptr);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003392 }
3393
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003394 {
3395 WriterMutexLock mu(self, *Locks::breakpoint_lock_);
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003396 // If there is at least one existing breakpoint on the same method, the new breakpoint
3397 // must have the same deoptimization kind than the existing breakpoint(s).
3398 DeoptimizationRequest::Kind breakpoint_deoptimization_kind;
3399 if (existing_breakpoint != nullptr) {
3400 breakpoint_deoptimization_kind = existing_breakpoint->GetDeoptimizationKind();
3401 } else {
3402 breakpoint_deoptimization_kind = deoptimization_kind;
3403 }
3404 gBreakpoints.push_back(Breakpoint(m, location->dex_pc, breakpoint_deoptimization_kind));
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003405 VLOG(jdwp) << "Set breakpoint #" << (gBreakpoints.size() - 1) << ": "
3406 << gBreakpoints[gBreakpoints.size() - 1];
3407 }
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003408}
3409
3410// Uninstalls a breakpoint at the specified location. Also indicates through the deoptimization
3411// request if we need to undeoptimize.
3412void Dbg::UnwatchLocation(const JDWP::JdwpLocation* location, DeoptimizationRequest* req) {
Sebastien Hertzed2be172014-08-19 15:33:43 +02003413 WriterMutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003414 ArtMethod* m = FromMethodId(location->method_id);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003415 DCHECK(m != nullptr) << "No method for method id " << location->method_id;
Sebastien Hertzf3928792014-11-17 19:00:37 +01003416 DeoptimizationRequest::Kind deoptimization_kind = DeoptimizationRequest::kNothing;
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003417 for (size_t i = 0, e = gBreakpoints.size(); i < e; ++i) {
Alex Light6c8467f2015-11-20 15:03:26 -08003418 if (gBreakpoints[i].DexPc() == location->dex_pc && gBreakpoints[i].IsInMethod(m)) {
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003419 VLOG(jdwp) << "Removed breakpoint #" << i << ": " << gBreakpoints[i];
Sebastien Hertzf3928792014-11-17 19:00:37 +01003420 deoptimization_kind = gBreakpoints[i].GetDeoptimizationKind();
3421 DCHECK_EQ(deoptimization_kind == DeoptimizationRequest::kSelectiveDeoptimization,
3422 Runtime::Current()->GetInstrumentation()->IsDeoptimized(m));
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003423 gBreakpoints.erase(gBreakpoints.begin() + i);
3424 break;
3425 }
3426 }
3427 const Breakpoint* const existing_breakpoint = FindFirstBreakpointForMethod(m);
3428 if (existing_breakpoint == nullptr) {
3429 // There is no more breakpoint on this method: we need to undeoptimize.
Sebastien Hertzf3928792014-11-17 19:00:37 +01003430 if (deoptimization_kind == DeoptimizationRequest::kFullDeoptimization) {
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003431 // This method required full deoptimization: we need to undeoptimize everything.
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003432 req->SetKind(DeoptimizationRequest::kFullUndeoptimization);
3433 req->SetMethod(nullptr);
Sebastien Hertzf3928792014-11-17 19:00:37 +01003434 } else if (deoptimization_kind == DeoptimizationRequest::kSelectiveDeoptimization) {
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003435 // This method required selective deoptimization: we need to undeoptimize only that method.
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003436 req->SetKind(DeoptimizationRequest::kSelectiveUndeoptimization);
3437 req->SetMethod(m);
Sebastien Hertzf3928792014-11-17 19:00:37 +01003438 } else {
3439 // This method had no need for deoptimization: do nothing.
3440 CHECK_EQ(deoptimization_kind, DeoptimizationRequest::kNothing);
3441 req->SetKind(DeoptimizationRequest::kNothing);
3442 req->SetMethod(nullptr);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003443 }
3444 } else {
3445 // There is at least one breakpoint for this method: we don't need to undeoptimize.
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003446 req->SetKind(DeoptimizationRequest::kNothing);
3447 req->SetMethod(nullptr);
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003448 if (kIsDebugBuild) {
Sebastien Hertzf3928792014-11-17 19:00:37 +01003449 SanityCheckExistingBreakpoints(m, deoptimization_kind);
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003450 }
Elliott Hughes86964332012-02-15 19:37:42 -08003451 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003452}
3453
Mathieu Chartiere401d142015-04-22 13:56:20 -07003454bool Dbg::IsForcedInterpreterNeededForCallingImpl(Thread* thread, ArtMethod* m) {
Daniel Mihalyieb076692014-08-22 17:33:31 +02003455 const SingleStepControl* const ssc = thread->GetSingleStepControl();
3456 if (ssc == nullptr) {
3457 // If we are not single-stepping, then we don't have to force interpreter.
3458 return false;
3459 }
3460 if (Runtime::Current()->GetInstrumentation()->InterpretOnly()) {
3461 // If we are in interpreter only mode, then we don't have to force interpreter.
3462 return false;
3463 }
3464
3465 if (!m->IsNative() && !m->IsProxyMethod()) {
3466 // If we want to step into a method, then we have to force interpreter on that call.
3467 if (ssc->GetStepDepth() == JDWP::SD_INTO) {
3468 return true;
3469 }
3470 }
3471 return false;
3472}
3473
Mathieu Chartiere401d142015-04-22 13:56:20 -07003474bool Dbg::IsForcedInterpreterNeededForResolutionImpl(Thread* thread, ArtMethod* m) {
Daniel Mihalyieb076692014-08-22 17:33:31 +02003475 instrumentation::Instrumentation* const instrumentation =
3476 Runtime::Current()->GetInstrumentation();
3477 // If we are in interpreter only mode, then we don't have to force interpreter.
3478 if (instrumentation->InterpretOnly()) {
3479 return false;
3480 }
3481 // We can only interpret pure Java method.
3482 if (m->IsNative() || m->IsProxyMethod()) {
3483 return false;
3484 }
3485 const SingleStepControl* const ssc = thread->GetSingleStepControl();
3486 if (ssc != nullptr) {
3487 // If we want to step into a method, then we have to force interpreter on that call.
3488 if (ssc->GetStepDepth() == JDWP::SD_INTO) {
3489 return true;
3490 }
3491 // If we are stepping out from a static initializer, by issuing a step
3492 // in or step over, that was implicitly invoked by calling a static method,
3493 // then we need to step into that method. Having a lower stack depth than
3494 // the one the single step control has indicates that the step originates
3495 // from the static initializer.
3496 if (ssc->GetStepDepth() != JDWP::SD_OUT &&
3497 ssc->GetStackDepth() > GetStackDepth(thread)) {
3498 return true;
3499 }
3500 }
3501 // There are cases where we have to force interpreter on deoptimized methods,
3502 // because in some cases the call will not be performed by invoking an entry
3503 // point that has been replaced by the deoptimization, but instead by directly
3504 // invoking the compiled code of the method, for example.
3505 return instrumentation->IsDeoptimized(m);
3506}
3507
Mathieu Chartiere401d142015-04-22 13:56:20 -07003508bool Dbg::IsForcedInstrumentationNeededForResolutionImpl(Thread* thread, ArtMethod* m) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07003509 // The upcall can be null and in that case we don't need to do anything.
Daniel Mihalyieb076692014-08-22 17:33:31 +02003510 if (m == nullptr) {
3511 return false;
3512 }
3513 instrumentation::Instrumentation* const instrumentation =
3514 Runtime::Current()->GetInstrumentation();
3515 // If we are in interpreter only mode, then we don't have to force interpreter.
3516 if (instrumentation->InterpretOnly()) {
3517 return false;
3518 }
3519 // We can only interpret pure Java method.
3520 if (m->IsNative() || m->IsProxyMethod()) {
3521 return false;
3522 }
3523 const SingleStepControl* const ssc = thread->GetSingleStepControl();
3524 if (ssc != nullptr) {
3525 // If we are stepping out from a static initializer, by issuing a step
3526 // out, that was implicitly invoked by calling a static method, then we
3527 // need to step into the caller of that method. Having a lower stack
3528 // depth than the one the single step control has indicates that the
3529 // step originates from the static initializer.
3530 if (ssc->GetStepDepth() == JDWP::SD_OUT &&
3531 ssc->GetStackDepth() > GetStackDepth(thread)) {
3532 return true;
3533 }
3534 }
3535 // If we are returning from a static intializer, that was implicitly
3536 // invoked by calling a static method and the caller is deoptimized,
3537 // then we have to deoptimize the stack without forcing interpreter
3538 // on the static method that was called originally. This problem can
3539 // be solved easily by forcing instrumentation on the called method,
3540 // because the instrumentation exit hook will recognise the need of
3541 // stack deoptimization by calling IsForcedInterpreterNeededForUpcall.
3542 return instrumentation->IsDeoptimized(m);
3543}
3544
Mathieu Chartiere401d142015-04-22 13:56:20 -07003545bool Dbg::IsForcedInterpreterNeededForUpcallImpl(Thread* thread, ArtMethod* m) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07003546 // The upcall can be null and in that case we don't need to do anything.
Daniel Mihalyieb076692014-08-22 17:33:31 +02003547 if (m == nullptr) {
3548 return false;
3549 }
3550 instrumentation::Instrumentation* const instrumentation =
3551 Runtime::Current()->GetInstrumentation();
3552 // If we are in interpreter only mode, then we don't have to force interpreter.
3553 if (instrumentation->InterpretOnly()) {
3554 return false;
3555 }
3556 // We can only interpret pure Java method.
3557 if (m->IsNative() || m->IsProxyMethod()) {
3558 return false;
3559 }
3560 const SingleStepControl* const ssc = thread->GetSingleStepControl();
3561 if (ssc != nullptr) {
3562 // The debugger is not interested in what is happening under the level
3563 // of the step, thus we only force interpreter when we are not below of
3564 // the step.
3565 if (ssc->GetStackDepth() >= GetStackDepth(thread)) {
3566 return true;
3567 }
3568 }
Mingyao Yang99170c62015-07-06 11:10:37 -07003569 if (thread->HasDebuggerShadowFrames()) {
3570 // We need to deoptimize the stack for the exception handling flow so that
3571 // we don't miss any deoptimization that should be done when there are
3572 // debugger shadow frames.
3573 return true;
3574 }
Daniel Mihalyieb076692014-08-22 17:33:31 +02003575 // We have to require stack deoptimization if the upcall is deoptimized.
3576 return instrumentation->IsDeoptimized(m);
3577}
3578
Sebastien Hertz520633b2015-09-08 17:03:36 +02003579// Do we need to deoptimize the stack to handle an exception?
3580bool Dbg::IsForcedInterpreterNeededForExceptionImpl(Thread* thread) {
3581 const SingleStepControl* const ssc = thread->GetSingleStepControl();
3582 if (ssc != nullptr) {
3583 // We deopt to step into the catch handler.
3584 return true;
3585 }
3586 // Deoptimization is required if at least one method in the stack needs it. However we
3587 // skip frames that will be unwound (thus not executed).
Andreas Gampec7d878d2018-11-19 18:42:06 +00003588 bool needs_deoptimization = false;
3589 StackVisitor::WalkStack(
3590 [&](art::StackVisitor* visitor) REQUIRES_SHARED(Locks::mutator_lock_) {
3591 // The visitor is meant to be used when handling exception from compiled code only.
3592 CHECK(!visitor->IsShadowFrame()) << "We only expect to visit compiled frame: "
3593 << ArtMethod::PrettyMethod(visitor->GetMethod());
3594 ArtMethod* method = visitor->GetMethod();
3595 if (method == nullptr) {
3596 // We reach an upcall and don't need to deoptimize this part of the stack (ManagedFragment)
3597 // so we can stop the visit.
3598 DCHECK(!needs_deoptimization);
3599 return false;
3600 }
3601 if (Runtime::Current()->GetInstrumentation()->InterpretOnly()) {
3602 // We found a compiled frame in the stack but instrumentation is set to interpret
3603 // everything: we need to deoptimize.
3604 needs_deoptimization = true;
3605 return false;
3606 }
3607 if (Runtime::Current()->GetInstrumentation()->IsDeoptimized(method)) {
3608 // We found a deoptimized method in the stack.
3609 needs_deoptimization = true;
3610 return false;
3611 }
3612 ShadowFrame* frame = visitor->GetThread()->FindDebuggerShadowFrame(visitor->GetFrameId());
3613 if (frame != nullptr) {
3614 // The debugger allocated a ShadowFrame to update a variable in the stack: we need to
3615 // deoptimize the stack to execute (and deallocate) this frame.
3616 needs_deoptimization = true;
3617 return false;
3618 }
3619 return true;
3620 },
3621 thread,
3622 /* context= */ nullptr,
3623 art::StackVisitor::StackWalkKind::kIncludeInlinedFrames,
3624 /* check_suspended */ true,
3625 /* include_transitions */ true);
3626 return needs_deoptimization;
Sebastien Hertz520633b2015-09-08 17:03:36 +02003627}
3628
Jeff Hao449db332013-04-12 18:30:52 -07003629// Scoped utility class to suspend a thread so that we may do tasks such as walk its stack. Doesn't
3630// cause suspension if the thread is the current thread.
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07003631class ScopedDebuggerThreadSuspension {
Jeff Hao449db332013-04-12 18:30:52 -07003632 public:
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07003633 ScopedDebuggerThreadSuspension(Thread* self, JDWP::ObjectId thread_id)
Mathieu Chartier90443472015-07-16 20:32:27 -07003634 REQUIRES(!Locks::thread_list_lock_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003635 REQUIRES_SHARED(Locks::mutator_lock_) :
Ian Rogersf3d874c2014-07-17 18:52:42 -07003636 thread_(nullptr),
Jeff Hao449db332013-04-12 18:30:52 -07003637 error_(JDWP::ERR_NONE),
3638 self_suspend_(false),
Ian Rogers33e95662013-05-20 20:29:14 -07003639 other_suspend_(false) {
Jeff Hao449db332013-04-12 18:30:52 -07003640 ScopedObjectAccessUnchecked soa(self);
Sebastien Hertz69206392015-04-07 15:54:25 +02003641 thread_ = DecodeThread(soa, thread_id, &error_);
Jeff Hao449db332013-04-12 18:30:52 -07003642 if (error_ == JDWP::ERR_NONE) {
3643 if (thread_ == soa.Self()) {
3644 self_suspend_ = true;
3645 } else {
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07003646 Thread* suspended_thread;
3647 {
3648 ScopedThreadSuspension sts(self, kWaitingForDebuggerSuspension);
3649 jobject thread_peer = Dbg::GetObjectRegistry()->GetJObject(thread_id);
3650 bool timed_out;
3651 ThreadList* const thread_list = Runtime::Current()->GetThreadList();
Sebastien Hertzcdd798d2017-04-18 18:28:51 +02003652 suspended_thread = thread_list->SuspendThreadByPeer(thread_peer,
Andreas Gampe98ea9d92018-10-19 14:06:15 -07003653 /* request_suspension= */ true,
Alex Light46f93402017-06-29 11:59:50 -07003654 SuspendReason::kForDebugger,
Sebastien Hertzcdd798d2017-04-18 18:28:51 +02003655 &timed_out);
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07003656 }
Ian Rogersf3d874c2014-07-17 18:52:42 -07003657 if (suspended_thread == nullptr) {
Jeff Hao449db332013-04-12 18:30:52 -07003658 // Thread terminated from under us while suspending.
3659 error_ = JDWP::ERR_INVALID_THREAD;
3660 } else {
3661 CHECK_EQ(suspended_thread, thread_);
3662 other_suspend_ = true;
3663 }
3664 }
3665 }
Elliott Hughes2435a572012-02-17 16:07:41 -08003666 }
Elliott Hughes86964332012-02-15 19:37:42 -08003667
Jeff Hao449db332013-04-12 18:30:52 -07003668 Thread* GetThread() const {
3669 return thread_;
3670 }
3671
3672 JDWP::JdwpError GetError() const {
3673 return error_;
3674 }
3675
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07003676 ~ScopedDebuggerThreadSuspension() {
Jeff Hao449db332013-04-12 18:30:52 -07003677 if (other_suspend_) {
Alex Light88fd7202017-06-30 08:31:59 -07003678 bool resumed = Runtime::Current()->GetThreadList()->Resume(thread_,
3679 SuspendReason::kForDebugger);
3680 DCHECK(resumed);
Jeff Hao449db332013-04-12 18:30:52 -07003681 }
3682 }
3683
3684 private:
3685 Thread* thread_;
3686 JDWP::JdwpError error_;
3687 bool self_suspend_;
3688 bool other_suspend_;
3689};
3690
3691JDWP::JdwpError Dbg::ConfigureStep(JDWP::ObjectId thread_id, JDWP::JdwpStepSize step_size,
3692 JDWP::JdwpStepDepth step_depth) {
3693 Thread* self = Thread::Current();
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07003694 ScopedDebuggerThreadSuspension sts(self, thread_id);
Jeff Hao449db332013-04-12 18:30:52 -07003695 if (sts.GetError() != JDWP::ERR_NONE) {
3696 return sts.GetError();
3697 }
3698
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003699 // Work out what ArtMethod* we're in, the current line number, and how deep the stack currently
Elliott Hughes2435a572012-02-17 16:07:41 -08003700 // is for step-out.
Ian Rogers0399dde2012-06-06 17:09:28 -07003701 struct SingleStepStackVisitor : public StackVisitor {
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003702 explicit SingleStepStackVisitor(Thread* thread) REQUIRES_SHARED(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01003703 : StackVisitor(thread, nullptr, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
3704 stack_depth(0),
3705 method(nullptr),
3706 line_number(-1) {}
Ian Rogersca190662012-06-26 15:45:57 -07003707
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003708 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
3709 // annotalysis.
Andreas Gampefa6a1b02018-09-07 08:11:55 -07003710 bool VisitFrame() override NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003711 ArtMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07003712 if (!m->IsRuntimeMethod()) {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003713 ++stack_depth;
3714 if (method == nullptr) {
Alex Light73376312017-04-06 10:10:51 -07003715 const DexFile* dex_file = m->GetDexFile();
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003716 method = m;
Alex Light73376312017-04-06 10:10:51 -07003717 if (dex_file != nullptr) {
David Sehr9323e6e2016-09-13 08:58:35 -07003718 line_number = annotations::GetLineNumFromPC(dex_file, m, GetDexPc());
Elliott Hughes2435a572012-02-17 16:07:41 -08003719 }
Elliott Hughes86964332012-02-15 19:37:42 -08003720 }
3721 }
Elliott Hughes530fa002012-03-12 11:44:49 -07003722 return true;
Elliott Hughes86964332012-02-15 19:37:42 -08003723 }
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003724
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003725 int stack_depth;
Mathieu Chartiere401d142015-04-22 13:56:20 -07003726 ArtMethod* method;
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003727 int32_t line_number;
Elliott Hughes86964332012-02-15 19:37:42 -08003728 };
Jeff Hao449db332013-04-12 18:30:52 -07003729
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003730 Thread* const thread = sts.GetThread();
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003731 SingleStepStackVisitor visitor(thread);
Ian Rogers0399dde2012-06-06 17:09:28 -07003732 visitor.WalkStack();
Elliott Hughes86964332012-02-15 19:37:42 -08003733
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003734 // Allocate single step.
Sebastien Hertz1558b572015-02-25 15:05:59 +01003735 SingleStepControl* single_step_control =
3736 new (std::nothrow) SingleStepControl(step_size, step_depth,
3737 visitor.stack_depth, visitor.method);
3738 if (single_step_control == nullptr) {
3739 LOG(ERROR) << "Failed to allocate SingleStepControl";
3740 return JDWP::ERR_OUT_OF_MEMORY;
3741 }
3742
Mathieu Chartiere401d142015-04-22 13:56:20 -07003743 ArtMethod* m = single_step_control->GetMethod();
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003744 const int32_t line_number = visitor.line_number;
Sebastien Hertz52f5f932015-05-28 11:00:57 +02003745 // Note: if the thread is not running Java code (pure native thread), there is no "current"
3746 // method on the stack (and no line number either).
3747 if (m != nullptr && !m->IsNative()) {
David Sehr0225f8e2018-01-31 08:52:24 +00003748 CodeItemDebugInfoAccessor accessor(m->DexInstructionDebugInfo());
Mathieu Chartier3e2e1232018-09-11 12:35:30 -07003749 bool last_pc_valid = false;
3750 uint32_t last_pc = 0u;
3751 // Find the dex_pc values that correspond to the current line, for line-based single-stepping.
3752 accessor.DecodeDebugPositionInfo([&](const DexFile::PositionInfo& entry) {
3753 if (static_cast<int32_t>(entry.line_) == line_number) {
3754 if (!last_pc_valid) {
3755 // Everything from this address until the next line change is ours.
3756 last_pc = entry.address_;
3757 last_pc_valid = true;
3758 }
3759 // Otherwise, if we're already in a valid range for this line,
3760 // just keep going (shouldn't really happen)...
3761 } else if (last_pc_valid) { // and the line number is new
3762 // Add everything from the last entry up until here to the set
3763 for (uint32_t dex_pc = last_pc; dex_pc < entry.address_; ++dex_pc) {
3764 single_step_control->AddDexPc(dex_pc);
3765 }
3766 last_pc_valid = false;
3767 }
3768 return false; // There may be multiple entries for any given line.
3769 });
3770 // If the line number was the last in the position table...
3771 if (last_pc_valid) {
3772 for (uint32_t dex_pc = last_pc; dex_pc < accessor.InsnsSizeInCodeUnits(); ++dex_pc) {
3773 single_step_control->AddDexPc(dex_pc);
3774 }
3775 }
Elliott Hughes3e2e1a22012-02-21 11:33:41 -08003776 }
Elliott Hughes2435a572012-02-17 16:07:41 -08003777
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003778 // Activate single-step in the thread.
3779 thread->ActivateSingleStepControl(single_step_control);
Elliott Hughes86964332012-02-15 19:37:42 -08003780
Elliott Hughes2435a572012-02-17 16:07:41 -08003781 if (VLOG_IS_ON(jdwp)) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003782 VLOG(jdwp) << "Single-step thread: " << *thread;
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003783 VLOG(jdwp) << "Single-step step size: " << single_step_control->GetStepSize();
3784 VLOG(jdwp) << "Single-step step depth: " << single_step_control->GetStepDepth();
David Sehr709b0702016-10-13 09:12:37 -07003785 VLOG(jdwp) << "Single-step current method: "
3786 << ArtMethod::PrettyMethod(single_step_control->GetMethod());
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003787 VLOG(jdwp) << "Single-step current line: " << line_number;
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003788 VLOG(jdwp) << "Single-step current stack depth: " << single_step_control->GetStackDepth();
Elliott Hughes2435a572012-02-17 16:07:41 -08003789 VLOG(jdwp) << "Single-step dex_pc values:";
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003790 for (uint32_t dex_pc : single_step_control->GetDexPcs()) {
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003791 VLOG(jdwp) << StringPrintf(" %#x", dex_pc);
Elliott Hughes2435a572012-02-17 16:07:41 -08003792 }
3793 }
3794
3795 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003796}
3797
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003798void Dbg::UnconfigureStep(JDWP::ObjectId thread_id) {
3799 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07003800 JDWP::JdwpError error;
3801 Thread* thread = DecodeThread(soa, thread_id, &error);
Sebastien Hertz87118ed2013-11-26 17:57:18 +01003802 if (error == JDWP::ERR_NONE) {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003803 thread->DeactivateSingleStepControl();
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003804 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003805}
3806
Elliott Hughes45651fd2012-02-21 15:48:20 -08003807static char JdwpTagToShortyChar(JDWP::JdwpTag tag) {
3808 switch (tag) {
3809 default:
3810 LOG(FATAL) << "unknown JDWP tag: " << PrintableChar(tag);
Ian Rogersfc787ec2014-10-09 21:56:44 -07003811 UNREACHABLE();
Elliott Hughes45651fd2012-02-21 15:48:20 -08003812
3813 // Primitives.
3814 case JDWP::JT_BYTE: return 'B';
3815 case JDWP::JT_CHAR: return 'C';
3816 case JDWP::JT_FLOAT: return 'F';
3817 case JDWP::JT_DOUBLE: return 'D';
3818 case JDWP::JT_INT: return 'I';
3819 case JDWP::JT_LONG: return 'J';
3820 case JDWP::JT_SHORT: return 'S';
3821 case JDWP::JT_VOID: return 'V';
3822 case JDWP::JT_BOOLEAN: return 'Z';
3823
3824 // Reference types.
3825 case JDWP::JT_ARRAY:
3826 case JDWP::JT_OBJECT:
3827 case JDWP::JT_STRING:
3828 case JDWP::JT_THREAD:
3829 case JDWP::JT_THREAD_GROUP:
3830 case JDWP::JT_CLASS_LOADER:
3831 case JDWP::JT_CLASS_OBJECT:
3832 return 'L';
3833 }
3834}
3835
Sebastien Hertzcbc50642015-06-01 17:33:12 +02003836JDWP::JdwpError Dbg::PrepareInvokeMethod(uint32_t request_id, JDWP::ObjectId thread_id,
3837 JDWP::ObjectId object_id, JDWP::RefTypeId class_id,
3838 JDWP::MethodId method_id, uint32_t arg_count,
3839 uint64_t arg_values[], JDWP::JdwpTag* arg_types,
3840 uint32_t options) {
3841 Thread* const self = Thread::Current();
3842 CHECK_EQ(self, GetDebugThread()) << "This must be called by the JDWP thread";
Sebastien Hertzd4032e42015-06-12 15:47:34 +02003843 const bool resume_all_threads = ((options & JDWP::INVOKE_SINGLE_THREADED) == 0);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003844
Sebastien Hertzcbc50642015-06-01 17:33:12 +02003845 ThreadList* thread_list = Runtime::Current()->GetThreadList();
Ian Rogersc0542af2014-09-03 16:16:56 -07003846 Thread* targetThread = nullptr;
Elliott Hughesd07986f2011-12-06 18:27:45 -08003847 {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003848 ScopedObjectAccessUnchecked soa(self);
Ian Rogersc0542af2014-09-03 16:16:56 -07003849 JDWP::JdwpError error;
3850 targetThread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08003851 if (error != JDWP::ERR_NONE) {
3852 LOG(ERROR) << "InvokeMethod request for invalid thread id " << thread_id;
3853 return error;
Elliott Hughesd07986f2011-12-06 18:27:45 -08003854 }
Sebastien Hertz1558b572015-02-25 15:05:59 +01003855 if (targetThread->GetInvokeReq() != nullptr) {
3856 // Thread is already invoking a method on behalf of the debugger.
3857 LOG(ERROR) << "InvokeMethod request for thread already invoking a method: " << *targetThread;
3858 return JDWP::ERR_ALREADY_INVOKING;
3859 }
3860 if (!targetThread->IsReadyForDebugInvoke()) {
3861 // Thread is not suspended by an event so it cannot invoke a method.
Elliott Hughesd07986f2011-12-06 18:27:45 -08003862 LOG(ERROR) << "InvokeMethod request for thread not stopped by event: " << *targetThread;
3863 return JDWP::ERR_INVALID_THREAD;
3864 }
3865
3866 /*
Sebastien Hertzd4032e42015-06-12 15:47:34 +02003867 * According to the JDWP specs, we are expected to resume all threads (or only the
3868 * target thread) once. So if a thread has been suspended more than once (either by
3869 * the debugger for an event or by the runtime for GC), it will remain suspended before
3870 * the invoke is executed. This means the debugger is responsible to properly resume all
3871 * the threads it has suspended so the target thread can execute the method.
Elliott Hughesd07986f2011-12-06 18:27:45 -08003872 *
Sebastien Hertzd4032e42015-06-12 15:47:34 +02003873 * However, for compatibility reason with older versions of debuggers (like Eclipse), we
3874 * fully resume all threads (by canceling *all* debugger suspensions) when the debugger
3875 * wants us to resume all threads. This is to avoid ending up in deadlock situation.
3876 *
3877 * On the other hand, if we are asked to only resume the target thread, then we follow the
3878 * JDWP specs by resuming that thread only once. This means the thread will remain suspended
3879 * if it has been suspended more than once before the invoke (and again, this is the
3880 * responsibility of the debugger to properly resume that thread before invoking a method).
Elliott Hughesd07986f2011-12-06 18:27:45 -08003881 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003882 int suspend_count;
3883 {
Ian Rogers50b35e22012-10-04 10:09:15 -07003884 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003885 suspend_count = targetThread->GetSuspendCount();
3886 }
Sebastien Hertzd4032e42015-06-12 15:47:34 +02003887 if (suspend_count > 1 && resume_all_threads) {
3888 // The target thread will remain suspended even after we resume it. Let's emit a warning
3889 // to indicate the invoke won't be executed until the thread is resumed.
3890 LOG(WARNING) << *targetThread << " suspended more than once (suspend count == "
3891 << suspend_count << "). This thread will invoke the method only once "
3892 << "it is fully resumed.";
Elliott Hughesd07986f2011-12-06 18:27:45 -08003893 }
3894
Vladimir Marko4617d582019-03-28 13:48:31 +00003895 ObjPtr<mirror::Object> receiver = gRegistry->Get<mirror::Object*>(object_id, &error);
Ian Rogersc0542af2014-09-03 16:16:56 -07003896 if (error != JDWP::ERR_NONE) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08003897 return JDWP::ERR_INVALID_OBJECT;
3898 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003899
Sebastien Hertz1558b572015-02-25 15:05:59 +01003900 gRegistry->Get<mirror::Object*>(thread_id, &error);
Ian Rogersc0542af2014-09-03 16:16:56 -07003901 if (error != JDWP::ERR_NONE) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08003902 return JDWP::ERR_INVALID_OBJECT;
3903 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003904
Vladimir Marko4617d582019-03-28 13:48:31 +00003905 ObjPtr<mirror::Class> c = DecodeClass(class_id, &error);
Ian Rogersc0542af2014-09-03 16:16:56 -07003906 if (c == nullptr) {
3907 return error;
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08003908 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003909
Mathieu Chartiere401d142015-04-22 13:56:20 -07003910 ArtMethod* m = FromMethodId(method_id);
Ian Rogersc0542af2014-09-03 16:16:56 -07003911 if (m->IsStatic() != (receiver == nullptr)) {
Elliott Hughes45651fd2012-02-21 15:48:20 -08003912 return JDWP::ERR_INVALID_METHODID;
3913 }
3914 if (m->IsStatic()) {
3915 if (m->GetDeclaringClass() != c) {
3916 return JDWP::ERR_INVALID_METHODID;
3917 }
3918 } else {
3919 if (!m->GetDeclaringClass()->IsAssignableFrom(c)) {
3920 return JDWP::ERR_INVALID_METHODID;
3921 }
3922 }
3923
3924 // Check the argument list matches the method.
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003925 uint32_t shorty_len = 0;
3926 const char* shorty = m->GetShorty(&shorty_len);
3927 if (shorty_len - 1 != arg_count) {
Elliott Hughes45651fd2012-02-21 15:48:20 -08003928 return JDWP::ERR_ILLEGAL_ARGUMENT;
3929 }
Elliott Hughes09201632013-04-15 15:50:07 -07003930
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003931 {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003932 StackHandleScope<2> hs(soa.Self());
Vladimir Marko4617d582019-03-28 13:48:31 +00003933 HandleWrapperObjPtr<mirror::Object> h_obj(hs.NewHandleWrapper(&receiver));
3934 HandleWrapperObjPtr<mirror::Class> h_klass(hs.NewHandleWrapper(&c));
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003935 const dex::TypeList* types = m->GetParameterTypeList();
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003936 for (size_t i = 0; i < arg_count; ++i) {
3937 if (shorty[i + 1] != JdwpTagToShortyChar(arg_types[i])) {
Elliott Hughes09201632013-04-15 15:50:07 -07003938 return JDWP::ERR_ILLEGAL_ARGUMENT;
3939 }
3940
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003941 if (shorty[i + 1] == 'L') {
3942 // Did we really get an argument of an appropriate reference type?
Vladimir Markob45528c2017-07-27 14:14:28 +01003943 ObjPtr<mirror::Class> parameter_type =
3944 m->ResolveClassFromTypeIndex(types->GetTypeItem(i).type_idx_);
Ian Rogersc0542af2014-09-03 16:16:56 -07003945 mirror::Object* argument = gRegistry->Get<mirror::Object*>(arg_values[i], &error);
3946 if (error != JDWP::ERR_NONE) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003947 return JDWP::ERR_INVALID_OBJECT;
3948 }
Ian Rogersc0542af2014-09-03 16:16:56 -07003949 if (argument != nullptr && !argument->InstanceOf(parameter_type)) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003950 return JDWP::ERR_ILLEGAL_ARGUMENT;
3951 }
3952
3953 // Turn the on-the-wire ObjectId into a jobject.
3954 jvalue& v = reinterpret_cast<jvalue&>(arg_values[i]);
3955 v.l = gRegistry->GetJObject(arg_values[i]);
3956 }
Elliott Hughes09201632013-04-15 15:50:07 -07003957 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003958 }
3959
Sebastien Hertz1558b572015-02-25 15:05:59 +01003960 // Allocates a DebugInvokeReq.
Vladimir Marko4617d582019-03-28 13:48:31 +00003961 DebugInvokeReq* req = new (std::nothrow) DebugInvokeReq(
3962 request_id, thread_id, receiver, c, m, options, arg_values, arg_count);
Sebastien Hertzcbc50642015-06-01 17:33:12 +02003963 if (req == nullptr) {
Sebastien Hertz1558b572015-02-25 15:05:59 +01003964 LOG(ERROR) << "Failed to allocate DebugInvokeReq";
3965 return JDWP::ERR_OUT_OF_MEMORY;
3966 }
3967
Sebastien Hertzcbc50642015-06-01 17:33:12 +02003968 // Attaches the DebugInvokeReq to the target thread so it executes the method when
3969 // it is resumed. Once the invocation completes, the target thread will delete it before
3970 // suspending itself (see ThreadList::SuspendSelfForDebugger).
3971 targetThread->SetDebugInvokeReq(req);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003972 }
3973
3974 // 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 +02003975 // away we're sitting high and dry -- but we must release this before the UndoDebuggerSuspensions
3976 // call.
Sebastien Hertzd4032e42015-06-12 15:47:34 +02003977 if (resume_all_threads) {
Sebastien Hertzcbc50642015-06-01 17:33:12 +02003978 VLOG(jdwp) << " Resuming all threads";
3979 thread_list->UndoDebuggerSuspensions();
3980 } else {
3981 VLOG(jdwp) << " Resuming event thread only";
Alex Light88fd7202017-06-30 08:31:59 -07003982 bool resumed = thread_list->Resume(targetThread, SuspendReason::kForDebugger);
3983 DCHECK(resumed);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003984 }
3985
Sebastien Hertzcbc50642015-06-01 17:33:12 +02003986 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003987}
3988
3989void Dbg::ExecuteMethod(DebugInvokeReq* pReq) {
Sebastien Hertzcbc50642015-06-01 17:33:12 +02003990 Thread* const self = Thread::Current();
3991 CHECK_NE(self, GetDebugThread()) << "This must be called by the event thread";
3992
3993 ScopedObjectAccess soa(self);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003994
Elliott Hughes81ff3182012-03-23 20:35:56 -07003995 // We can be called while an exception is pending. We need
Elliott Hughesd07986f2011-12-06 18:27:45 -08003996 // to preserve that across the method invocation.
Sebastien Hertzcbc50642015-06-01 17:33:12 +02003997 StackHandleScope<1> hs(soa.Self());
3998 Handle<mirror::Throwable> old_exception = hs.NewHandle(soa.Self()->GetException());
Sebastien Hertz1558b572015-02-25 15:05:59 +01003999 soa.Self()->ClearException();
Elliott Hughesd07986f2011-12-06 18:27:45 -08004000
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004001 // Execute the method then sends reply to the debugger.
4002 ExecuteMethodWithoutPendingException(soa, pReq);
4003
4004 // If an exception was pending before the invoke, restore it now.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004005 if (old_exception != nullptr) {
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004006 soa.Self()->SetException(old_exception.Get());
4007 }
4008}
4009
4010// Helper function: write a variable-width value into the output input buffer.
4011static void WriteValue(JDWP::ExpandBuf* pReply, int width, uint64_t value) {
4012 switch (width) {
4013 case 1:
4014 expandBufAdd1(pReply, value);
4015 break;
4016 case 2:
4017 expandBufAdd2BE(pReply, value);
4018 break;
4019 case 4:
4020 expandBufAdd4BE(pReply, value);
4021 break;
4022 case 8:
4023 expandBufAdd8BE(pReply, value);
4024 break;
4025 default:
4026 LOG(FATAL) << width;
4027 UNREACHABLE();
4028 }
4029}
4030
4031void Dbg::ExecuteMethodWithoutPendingException(ScopedObjectAccess& soa, DebugInvokeReq* pReq) {
4032 soa.Self()->AssertNoPendingException();
4033
Elliott Hughesd07986f2011-12-06 18:27:45 -08004034 // Translate the method through the vtable, unless the debugger wants to suppress it.
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004035 ArtMethod* m = pReq->method;
Andreas Gampe542451c2016-07-26 09:02:02 -07004036 PointerSize image_pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
Sebastien Hertz1558b572015-02-25 15:05:59 +01004037 if ((pReq->options & JDWP::INVOKE_NONVIRTUAL) == 0 && pReq->receiver.Read() != nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004038 ArtMethod* actual_method =
4039 pReq->klass.Read()->FindVirtualMethodForVirtualOrInterface(m, image_pointer_size);
4040 if (actual_method != m) {
David Sehr709b0702016-10-13 09:12:37 -07004041 VLOG(jdwp) << "ExecuteMethod translated " << ArtMethod::PrettyMethod(m)
4042 << " to " << ArtMethod::PrettyMethod(actual_method);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004043 m = actual_method;
Elliott Hughes45651fd2012-02-21 15:48:20 -08004044 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08004045 }
David Sehr709b0702016-10-13 09:12:37 -07004046 VLOG(jdwp) << "ExecuteMethod " << ArtMethod::PrettyMethod(m)
Sebastien Hertz1558b572015-02-25 15:05:59 +01004047 << " receiver=" << pReq->receiver.Read()
Sebastien Hertzd38667a2013-11-25 15:43:54 +01004048 << " arg_count=" << pReq->arg_count;
Mathieu Chartiere401d142015-04-22 13:56:20 -07004049 CHECK(m != nullptr);
Elliott Hughesd07986f2011-12-06 18:27:45 -08004050
Roland Levillain33d69032015-06-18 18:20:59 +01004051 static_assert(sizeof(jvalue) == sizeof(uint64_t), "jvalue and uint64_t have different sizes.");
Elliott Hughesd07986f2011-12-06 18:27:45 -08004052
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004053 // Invoke the method.
Jeff Hao39b6c242015-05-19 20:30:23 -07004054 ScopedLocalRef<jobject> ref(soa.Env(), soa.AddLocalReference<jobject>(pReq->receiver.Read()));
Andreas Gampe13b27842016-11-07 16:48:23 -08004055 JValue result = InvokeWithJValues(soa, ref.get(), jni::EncodeArtMethod(m),
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004056 reinterpret_cast<jvalue*>(pReq->arg_values.get()));
Elliott Hughesd07986f2011-12-06 18:27:45 -08004057
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004058 // Prepare JDWP ids for the reply.
4059 JDWP::JdwpTag result_tag = BasicTagFromDescriptor(m->GetShorty());
4060 const bool is_object_result = (result_tag == JDWP::JT_OBJECT);
Jeff Hao064d24e2016-08-25 03:52:40 +00004061 StackHandleScope<3> hs(soa.Self());
Sebastien Hertz1558b572015-02-25 15:05:59 +01004062 Handle<mirror::Object> object_result = hs.NewHandle(is_object_result ? result.GetL() : nullptr);
4063 Handle<mirror::Throwable> exception = hs.NewHandle(soa.Self()->GetException());
4064 soa.Self()->ClearException();
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004065
4066 if (!IsDebuggerActive()) {
4067 // The debugger detached: we must not re-suspend threads. We also don't need to fill the reply
4068 // because it won't be sent either.
4069 return;
4070 }
4071
4072 JDWP::ObjectId exceptionObjectId = gRegistry->Add(exception);
4073 uint64_t result_value = 0;
4074 if (exceptionObjectId != 0) {
Sebastien Hertz1558b572015-02-25 15:05:59 +01004075 VLOG(jdwp) << " JDWP invocation returning with exception=" << exception.Get()
4076 << " " << exception->Dump();
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004077 result_value = 0;
Sebastien Hertz1558b572015-02-25 15:05:59 +01004078 } else if (is_object_result) {
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004079 /* if no exception was thrown, examine object result more closely */
Sebastien Hertz1558b572015-02-25 15:05:59 +01004080 JDWP::JdwpTag new_tag = TagFromObject(soa, object_result.Get());
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004081 if (new_tag != result_tag) {
4082 VLOG(jdwp) << " JDWP promoted result from " << result_tag << " to " << new_tag;
4083 result_tag = new_tag;
Elliott Hughesd07986f2011-12-06 18:27:45 -08004084 }
4085
Sebastien Hertz1558b572015-02-25 15:05:59 +01004086 // Register the object in the registry and reference its ObjectId. This ensures
4087 // GC safety and prevents from accessing stale reference if the object is moved.
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004088 result_value = gRegistry->Add(object_result.Get());
Sebastien Hertz1558b572015-02-25 15:05:59 +01004089 } else {
4090 // Primitive result.
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004091 DCHECK(IsPrimitiveTag(result_tag));
4092 result_value = result.GetJ();
4093 }
4094 const bool is_constructor = m->IsConstructor() && !m->IsStatic();
4095 if (is_constructor) {
4096 // If we invoked a constructor (which actually returns void), return the receiver,
4097 // unless we threw, in which case we return null.
Sebastien Hertza3e13772015-11-05 12:09:44 +01004098 DCHECK_EQ(JDWP::JT_VOID, result_tag);
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004099 if (exceptionObjectId == 0) {
Jeff Hao064d24e2016-08-25 03:52:40 +00004100 if (m->GetDeclaringClass()->IsStringClass()) {
4101 // For string constructors, the new string is remapped to the receiver (stored in ref).
4102 Handle<mirror::Object> decoded_ref = hs.NewHandle(soa.Self()->DecodeJObject(ref.get()));
4103 result_value = gRegistry->Add(decoded_ref);
4104 result_tag = TagFromObject(soa, decoded_ref.Get());
4105 } else {
4106 // TODO we could keep the receiver ObjectId in the DebugInvokeReq to avoid looking into the
4107 // object registry.
4108 result_value = GetObjectRegistry()->Add(pReq->receiver.Read());
4109 result_tag = TagFromObject(soa, pReq->receiver.Read());
4110 }
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004111 } else {
4112 result_value = 0;
Sebastien Hertza3e13772015-11-05 12:09:44 +01004113 result_tag = JDWP::JT_OBJECT;
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004114 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08004115 }
4116
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004117 // Suspend other threads if the invoke is not single-threaded.
4118 if ((pReq->options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07004119 ScopedThreadSuspension sts(soa.Self(), kWaitingForDebuggerSuspension);
Hiroshi Yamauchi8f95cf32016-04-19 11:14:06 -07004120 // Avoid a deadlock between GC and debugger where GC gets suspended during GC. b/25800335.
4121 gc::ScopedGCCriticalSection gcs(soa.Self(), gc::kGcCauseDebugger, gc::kCollectorTypeDebugger);
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004122 VLOG(jdwp) << " Suspending all threads";
4123 Runtime::Current()->GetThreadList()->SuspendAllForDebugger();
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004124 }
4125
4126 VLOG(jdwp) << " --> returned " << result_tag
4127 << StringPrintf(" %#" PRIx64 " (except=%#" PRIx64 ")", result_value,
4128 exceptionObjectId);
4129
4130 // Show detailed debug output.
4131 if (result_tag == JDWP::JT_STRING && exceptionObjectId == 0) {
4132 if (result_value != 0) {
4133 if (VLOG_IS_ON(jdwp)) {
4134 std::string result_string;
4135 JDWP::JdwpError error = Dbg::StringToUtf8(result_value, &result_string);
4136 CHECK_EQ(error, JDWP::ERR_NONE);
4137 VLOG(jdwp) << " string '" << result_string << "'";
4138 }
4139 } else {
4140 VLOG(jdwp) << " string (null)";
4141 }
4142 }
4143
4144 // Attach the reply to DebugInvokeReq so it can be sent to the debugger when the event thread
4145 // is ready to suspend.
4146 BuildInvokeReply(pReq->reply, pReq->request_id, result_tag, result_value, exceptionObjectId);
4147}
4148
4149void Dbg::BuildInvokeReply(JDWP::ExpandBuf* pReply, uint32_t request_id, JDWP::JdwpTag result_tag,
4150 uint64_t result_value, JDWP::ObjectId exception) {
4151 // Make room for the JDWP header since we do not know the size of the reply yet.
4152 JDWP::expandBufAddSpace(pReply, kJDWPHeaderLen);
4153
4154 size_t width = GetTagWidth(result_tag);
4155 JDWP::expandBufAdd1(pReply, result_tag);
4156 if (width != 0) {
4157 WriteValue(pReply, width, result_value);
4158 }
4159 JDWP::expandBufAdd1(pReply, JDWP::JT_OBJECT);
4160 JDWP::expandBufAddObjectId(pReply, exception);
4161
4162 // Now we know the size, we can complete the JDWP header.
4163 uint8_t* buf = expandBufGetBuffer(pReply);
4164 JDWP::Set4BE(buf + kJDWPHeaderSizeOffset, expandBufGetLength(pReply));
4165 JDWP::Set4BE(buf + kJDWPHeaderIdOffset, request_id);
4166 JDWP::Set1(buf + kJDWPHeaderFlagsOffset, kJDWPFlagReply); // flags
4167 JDWP::Set2BE(buf + kJDWPHeaderErrorCodeOffset, JDWP::ERR_NONE);
4168}
4169
4170void Dbg::FinishInvokeMethod(DebugInvokeReq* pReq) {
4171 CHECK_NE(Thread::Current(), GetDebugThread()) << "This must be called by the event thread";
4172
4173 JDWP::ExpandBuf* const pReply = pReq->reply;
4174 CHECK(pReply != nullptr) << "No reply attached to DebugInvokeReq";
4175
4176 // We need to prevent other threads (including JDWP thread) from interacting with the debugger
4177 // while we send the reply but are not yet suspended. The JDWP token will be released just before
4178 // we suspend ourself again (see ThreadList::SuspendSelfForDebugger).
4179 gJdwpState->AcquireJdwpTokenForEvent(pReq->thread_id);
4180
4181 // Send the reply unless the debugger detached before the completion of the method.
4182 if (IsDebuggerActive()) {
4183 const size_t replyDataLength = expandBufGetLength(pReply) - kJDWPHeaderLen;
4184 VLOG(jdwp) << StringPrintf("REPLY INVOKE id=0x%06x (length=%zu)",
4185 pReq->request_id, replyDataLength);
4186
4187 gJdwpState->SendRequest(pReply);
4188 } else {
4189 VLOG(jdwp) << "Not sending invoke reply because debugger detached";
Elliott Hughesd07986f2011-12-06 18:27:45 -08004190 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004191}
4192
Alex Light8c2b9292017-11-09 13:21:01 -08004193bool Dbg::DdmHandleChunk(JNIEnv* env,
4194 uint32_t type,
4195 const ArrayRef<const jbyte>& data,
4196 /*out*/uint32_t* out_type,
4197 /*out*/std::vector<uint8_t>* out_data) {
4198 ScopedLocalRef<jbyteArray> dataArray(env, env->NewByteArray(data.size()));
Ian Rogersc0542af2014-09-03 16:16:56 -07004199 if (dataArray.get() == nullptr) {
Alex Light8c2b9292017-11-09 13:21:01 -08004200 LOG(WARNING) << "byte[] allocation failed: " << data.size();
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004201 env->ExceptionClear();
4202 return false;
4203 }
Alex Light8c2b9292017-11-09 13:21:01 -08004204 env->SetByteArrayRegion(dataArray.get(),
4205 0,
4206 data.size(),
4207 reinterpret_cast<const jbyte*>(data.data()));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004208 // Call "private static Chunk dispatch(int type, byte[] data, int offset, int length)".
Alex Light8c2b9292017-11-09 13:21:01 -08004209 ScopedLocalRef<jobject> chunk(
4210 env,
4211 env->CallStaticObjectMethod(
4212 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
4213 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_dispatch,
4214 type, dataArray.get(), 0, data.size()));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004215 if (env->ExceptionCheck()) {
Alex Light1eeefa62018-03-19 13:47:56 -07004216 Thread* self = Thread::Current();
4217 ScopedObjectAccess soa(self);
4218 LOG(INFO) << StringPrintf("Exception thrown by dispatcher for 0x%08x", type) << std::endl
4219 << self->GetException()->Dump();
4220 self->ClearException();
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004221 return false;
4222 }
4223
Ian Rogersc0542af2014-09-03 16:16:56 -07004224 if (chunk.get() == nullptr) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004225 return false;
4226 }
4227
4228 /*
4229 * Pull the pieces out of the chunk. We copy the results into a
4230 * newly-allocated buffer that the caller can free. We don't want to
4231 * continue using the Chunk object because nothing has a reference to it.
4232 *
4233 * We could avoid this by returning type/data/offset/length and having
4234 * the caller be aware of the object lifetime issues, but that
Elliott Hughes81ff3182012-03-23 20:35:56 -07004235 * integrates the JDWP code more tightly into the rest of the runtime, and doesn't work
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004236 * if we have responses for multiple chunks.
4237 *
4238 * So we're pretty much stuck with copying data around multiple times.
4239 */
Alex Light8c2b9292017-11-09 13:21:01 -08004240 ScopedLocalRef<jbyteArray> replyData(
4241 env,
4242 reinterpret_cast<jbyteArray>(
4243 env->GetObjectField(
4244 chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_data)));
4245 jint offset = env->GetIntField(chunk.get(),
4246 WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_offset);
4247 jint length = env->GetIntField(chunk.get(),
4248 WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_length);
4249 *out_type = env->GetIntField(chunk.get(),
4250 WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_type);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004251
Alex Light8c2b9292017-11-09 13:21:01 -08004252 VLOG(jdwp) << StringPrintf("DDM reply: type=0x%08x data=%p offset=%d length=%d",
4253 type,
4254 replyData.get(),
4255 offset,
4256 length);
Alex Light8c2b9292017-11-09 13:21:01 -08004257 out_data->resize(length);
4258 env->GetByteArrayRegion(replyData.get(),
4259 offset,
4260 length,
4261 reinterpret_cast<jbyte*>(out_data->data()));
Alex Light6f2a6342017-12-12 09:55:05 -08004262
Alex Lighte5463a82017-12-12 13:33:28 -08004263 if (env->ExceptionCheck()) {
Alex Light1eeefa62018-03-19 13:47:56 -07004264 Thread* self = Thread::Current();
4265 ScopedObjectAccess soa(self);
Alex Lighte5463a82017-12-12 13:33:28 -08004266 LOG(INFO) << StringPrintf("Exception thrown when reading response data from dispatcher 0x%08x",
Alex Light1eeefa62018-03-19 13:47:56 -07004267 type) << std::endl << self->GetException()->Dump();
4268 self->ClearException();
Alex Lighte5463a82017-12-12 13:33:28 -08004269 return false;
4270 }
4271
Alex Light8c2b9292017-11-09 13:21:01 -08004272 return true;
4273}
4274
4275/*
4276 * "request" contains a full JDWP packet, possibly with multiple chunks. We
4277 * need to process each, accumulate the replies, and ship the whole thing
4278 * back.
4279 *
4280 * Returns "true" if we have a reply. The reply buffer is newly allocated,
4281 * and includes the chunk type/length, followed by the data.
4282 *
4283 * OLD-TODO: we currently assume that the request and reply include a single
4284 * chunk. If this becomes inconvenient we will need to adapt.
4285 */
4286bool Dbg::DdmHandlePacket(JDWP::Request* request, uint8_t** pReplyBuf, int* pReplyLen) {
4287 Thread* self = Thread::Current();
4288 JNIEnv* env = self->GetJniEnv();
4289
4290 uint32_t type = request->ReadUnsigned32("type");
4291 uint32_t length = request->ReadUnsigned32("length");
4292
4293 // Create a byte[] corresponding to 'request'.
4294 size_t request_length = request->size();
4295 // Run through and find all chunks. [Currently just find the first.]
4296 if (length != request_length) {
4297 LOG(WARNING) << StringPrintf("bad chunk found (len=%u pktLen=%zd)", length, request_length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004298 return false;
4299 }
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004300
Alex Light8c2b9292017-11-09 13:21:01 -08004301 ArrayRef<const jbyte> data(reinterpret_cast<const jbyte*>(request->data()), request_length);
4302 std::vector<uint8_t> out_data;
4303 uint32_t out_type = 0;
4304 request->Skip(request_length);
Alex Light6f2a6342017-12-12 09:55:05 -08004305 if (!DdmHandleChunk(env, type, data, &out_type, &out_data) || out_data.empty()) {
Alex Light8c2b9292017-11-09 13:21:01 -08004306 return false;
4307 }
4308 const uint32_t kDdmHeaderSize = 8;
4309 *pReplyLen = out_data.size() + kDdmHeaderSize;
4310 *pReplyBuf = new uint8_t[out_data.size() + kDdmHeaderSize];
4311 memcpy((*pReplyBuf) + kDdmHeaderSize, out_data.data(), out_data.size());
4312 JDWP::Set4BE(*pReplyBuf, out_type);
4313 JDWP::Set4BE((*pReplyBuf) + 4, static_cast<uint32_t>(out_data.size()));
4314 VLOG(jdwp)
4315 << StringPrintf("dvmHandleDdm returning type=%.4s", reinterpret_cast<char*>(*pReplyBuf))
4316 << "0x" << std::hex << reinterpret_cast<uintptr_t>(*pReplyBuf) << std::dec
4317 << " len= " << out_data.size();
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004318 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004319}
4320
Elliott Hughesa2155262011-11-16 16:26:58 -08004321void Dbg::DdmBroadcast(bool connect) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08004322 VLOG(jdwp) << "Broadcasting DDM " << (connect ? "connect" : "disconnect") << "...";
Elliott Hughes47fce012011-10-25 18:37:19 -07004323
4324 Thread* self = Thread::Current();
Ian Rogers50b35e22012-10-04 10:09:15 -07004325 if (self->GetState() != kRunnable) {
4326 LOG(ERROR) << "DDM broadcast in thread state " << self->GetState();
4327 /* try anyway? */
Elliott Hughes47fce012011-10-25 18:37:19 -07004328 }
4329
4330 JNIEnv* env = self->GetJniEnv();
Elliott Hughes47fce012011-10-25 18:37:19 -07004331 jint event = connect ? 1 /*DdmServer.CONNECTED*/ : 2 /*DdmServer.DISCONNECTED*/;
Elliott Hugheseac76672012-05-24 21:56:51 -07004332 env->CallStaticVoidMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
4333 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_broadcast,
4334 event);
Elliott Hughes47fce012011-10-25 18:37:19 -07004335 if (env->ExceptionCheck()) {
4336 LOG(ERROR) << "DdmServer.broadcast " << event << " failed";
4337 env->ExceptionDescribe();
4338 env->ExceptionClear();
4339 }
4340}
4341
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004342void Dbg::DdmConnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08004343 Dbg::DdmBroadcast(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004344}
4345
4346void Dbg::DdmDisconnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08004347 Dbg::DdmBroadcast(false);
Elliott Hughes47fce012011-10-25 18:37:19 -07004348 gDdmThreadNotification = false;
4349}
4350
4351/*
Elliott Hughes82188472011-11-07 18:11:48 -08004352 * Send a notification when a thread starts, stops, or changes its name.
Elliott Hughes47fce012011-10-25 18:37:19 -07004353 *
4354 * Because we broadcast the full set of threads when the notifications are
4355 * first enabled, it's possible for "thread" to be actively executing.
4356 */
Elliott Hughes82188472011-11-07 18:11:48 -08004357void Dbg::DdmSendThreadNotification(Thread* t, uint32_t type) {
Elliott Hughes47fce012011-10-25 18:37:19 -07004358 if (!gDdmThreadNotification) {
4359 return;
4360 }
4361
Alex Light772099a2017-11-21 14:05:04 -08004362 RuntimeCallbacks* cb = Runtime::Current()->GetRuntimeCallbacks();
Elliott Hughes82188472011-11-07 18:11:48 -08004363 if (type == CHUNK_TYPE("THDE")) {
Elliott Hughes47fce012011-10-25 18:37:19 -07004364 uint8_t buf[4];
Ian Rogersd9c4fc92013-10-01 19:45:43 -07004365 JDWP::Set4BE(&buf[0], t->GetThreadId());
Alex Light772099a2017-11-21 14:05:04 -08004366 cb->DdmPublishChunk(CHUNK_TYPE("THDE"), ArrayRef<const uint8_t>(buf));
Elliott Hughes82188472011-11-07 18:11:48 -08004367 } else {
4368 CHECK(type == CHUNK_TYPE("THCR") || type == CHUNK_TYPE("THNM")) << type;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004369 ScopedObjectAccessUnchecked soa(Thread::Current());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004370 StackHandleScope<1> hs(soa.Self());
Andreas Gampe08883de2016-11-08 13:20:52 -08004371 Handle<mirror::String> name(hs.NewHandle(t->GetThreadName()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004372 size_t char_count = (name != nullptr) ? name->GetLength() : 0;
4373 const jchar* chars = (name != nullptr) ? name->GetValue() : nullptr;
4374 bool is_compressed = (name != nullptr) ? name->IsCompressed() : false;
Elliott Hughes82188472011-11-07 18:11:48 -08004375
Elliott Hughes21f32d72011-11-09 17:44:13 -08004376 std::vector<uint8_t> bytes;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07004377 JDWP::Append4BE(bytes, t->GetThreadId());
jessicahandojo3aaa37b2016-07-29 14:46:37 -07004378 if (is_compressed) {
4379 const uint8_t* chars_compressed = name->GetValueCompressed();
4380 JDWP::AppendUtf16CompressedBE(bytes, chars_compressed, char_count);
4381 } else {
4382 JDWP::AppendUtf16BE(bytes, chars, char_count);
4383 }
Elliott Hughes21f32d72011-11-09 17:44:13 -08004384 CHECK_EQ(bytes.size(), char_count*2 + sizeof(uint32_t)*2);
Alex Light772099a2017-11-21 14:05:04 -08004385 cb->DdmPublishChunk(type, ArrayRef<const uint8_t>(bytes));
Elliott Hughes47fce012011-10-25 18:37:19 -07004386 }
4387}
4388
Elliott Hughes47fce012011-10-25 18:37:19 -07004389void Dbg::DdmSetThreadNotification(bool enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004390 // Enable/disable thread notifications.
Elliott Hughes47fce012011-10-25 18:37:19 -07004391 gDdmThreadNotification = enable;
4392 if (enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004393 // Suspend the VM then post thread start notifications for all threads. Threads attaching will
4394 // see a suspension in progress and block until that ends. They then post their own start
4395 // notification.
4396 SuspendVM();
4397 std::list<Thread*> threads;
Ian Rogers50b35e22012-10-04 10:09:15 -07004398 Thread* self = Thread::Current();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004399 {
Ian Rogers50b35e22012-10-04 10:09:15 -07004400 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004401 threads = Runtime::Current()->GetThreadList()->GetList();
4402 }
4403 {
Ian Rogers50b35e22012-10-04 10:09:15 -07004404 ScopedObjectAccess soa(self);
Mathieu Chartier02e25112013-08-14 16:14:24 -07004405 for (Thread* thread : threads) {
4406 Dbg::DdmSendThreadNotification(thread, CHUNK_TYPE("THCR"));
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004407 }
4408 }
4409 ResumeVM();
Elliott Hughes47fce012011-10-25 18:37:19 -07004410 }
4411}
4412
Elliott Hughesa2155262011-11-16 16:26:58 -08004413void Dbg::PostThreadStartOrStop(Thread* t, uint32_t type) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07004414 if (IsDebuggerActive()) {
Sebastien Hertz6995c602014-09-09 12:10:13 +02004415 gJdwpState->PostThreadChange(t, type == CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07004416 }
Elliott Hughes82188472011-11-07 18:11:48 -08004417 Dbg::DdmSendThreadNotification(t, type);
Elliott Hughes47fce012011-10-25 18:37:19 -07004418}
4419
4420void Dbg::PostThreadStart(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004421 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07004422}
4423
4424void Dbg::PostThreadDeath(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004425 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THDE"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004426}
4427
Mathieu Chartierad466ad2015-01-08 16:28:08 -08004428JDWP::JdwpState* Dbg::GetJdwpState() {
4429 return gJdwpState;
4430}
4431
Elliott Hughes767a1472011-10-26 18:49:02 -07004432int Dbg::DdmHandleHpifChunk(HpifWhen when) {
4433 if (when == HPIF_WHEN_NOW) {
Elliott Hughes7162ad92011-10-27 14:08:42 -07004434 DdmSendHeapInfo(when);
Elliott Hughes767a1472011-10-26 18:49:02 -07004435 return true;
4436 }
4437
4438 if (when != HPIF_WHEN_NEVER && when != HPIF_WHEN_NEXT_GC && when != HPIF_WHEN_EVERY_GC) {
4439 LOG(ERROR) << "invalid HpifWhen value: " << static_cast<int>(when);
4440 return false;
4441 }
4442
4443 gDdmHpifWhen = when;
4444 return true;
4445}
4446
4447bool Dbg::DdmHandleHpsgNhsgChunk(Dbg::HpsgWhen when, Dbg::HpsgWhat what, bool native) {
4448 if (when != HPSG_WHEN_NEVER && when != HPSG_WHEN_EVERY_GC) {
4449 LOG(ERROR) << "invalid HpsgWhen value: " << static_cast<int>(when);
4450 return false;
4451 }
4452
4453 if (what != HPSG_WHAT_MERGED_OBJECTS && what != HPSG_WHAT_DISTINCT_OBJECTS) {
4454 LOG(ERROR) << "invalid HpsgWhat value: " << static_cast<int>(what);
4455 return false;
4456 }
4457
4458 if (native) {
4459 gDdmNhsgWhen = when;
4460 gDdmNhsgWhat = what;
4461 } else {
4462 gDdmHpsgWhen = when;
4463 gDdmHpsgWhat = what;
4464 }
4465 return true;
4466}
4467
Elliott Hughes7162ad92011-10-27 14:08:42 -07004468void Dbg::DdmSendHeapInfo(HpifWhen reason) {
4469 // If there's a one-shot 'when', reset it.
4470 if (reason == gDdmHpifWhen) {
4471 if (gDdmHpifWhen == HPIF_WHEN_NEXT_GC) {
4472 gDdmHpifWhen = HPIF_WHEN_NEVER;
4473 }
4474 }
4475
4476 /*
4477 * Chunk HPIF (client --> server)
4478 *
4479 * Heap Info. General information about the heap,
4480 * suitable for a summary display.
4481 *
4482 * [u4]: number of heaps
4483 *
4484 * For each heap:
4485 * [u4]: heap ID
4486 * [u8]: timestamp in ms since Unix epoch
4487 * [u1]: capture reason (same as 'when' value from server)
4488 * [u4]: max heap size in bytes (-Xmx)
4489 * [u4]: current heap size in bytes
4490 * [u4]: current number of bytes allocated
4491 * [u4]: current number of objects allocated
4492 */
4493 uint8_t heap_count = 1;
Ian Rogers1d54e732013-05-02 21:10:01 -07004494 gc::Heap* heap = Runtime::Current()->GetHeap();
Elliott Hughes21f32d72011-11-09 17:44:13 -08004495 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08004496 JDWP::Append4BE(bytes, heap_count);
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004497 JDWP::Append4BE(bytes, 1); // Heap id (bogus; we only have one heap).
Elliott Hughes545a0642011-11-08 19:10:03 -08004498 JDWP::Append8BE(bytes, MilliTime());
4499 JDWP::Append1BE(bytes, reason);
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004500 JDWP::Append4BE(bytes, heap->GetMaxMemory()); // Max allowed heap size in bytes.
4501 JDWP::Append4BE(bytes, heap->GetTotalMemory()); // Current heap size in bytes.
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08004502 JDWP::Append4BE(bytes, heap->GetBytesAllocated());
4503 JDWP::Append4BE(bytes, heap->GetObjectsAllocated());
Elliott Hughes21f32d72011-11-09 17:44:13 -08004504 CHECK_EQ(bytes.size(), 4U + (heap_count * (4 + 8 + 1 + 4 + 4 + 4 + 4)));
Alex Light772099a2017-11-21 14:05:04 -08004505 Runtime::Current()->GetRuntimeCallbacks()->DdmPublishChunk(CHUNK_TYPE("HPIF"),
4506 ArrayRef<const uint8_t>(bytes));
Elliott Hughes767a1472011-10-26 18:49:02 -07004507}
4508
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004509enum HpsgSolidity {
4510 SOLIDITY_FREE = 0,
4511 SOLIDITY_HARD = 1,
4512 SOLIDITY_SOFT = 2,
4513 SOLIDITY_WEAK = 3,
4514 SOLIDITY_PHANTOM = 4,
4515 SOLIDITY_FINALIZABLE = 5,
4516 SOLIDITY_SWEEP = 6,
4517};
4518
4519enum HpsgKind {
4520 KIND_OBJECT = 0,
4521 KIND_CLASS_OBJECT = 1,
4522 KIND_ARRAY_1 = 2,
4523 KIND_ARRAY_2 = 3,
4524 KIND_ARRAY_4 = 4,
4525 KIND_ARRAY_8 = 5,
4526 KIND_UNKNOWN = 6,
4527 KIND_NATIVE = 7,
4528};
4529
4530#define HPSG_PARTIAL (1<<7)
4531#define HPSG_STATE(solidity, kind) ((uint8_t)((((kind) & 0x7) << 3) | ((solidity) & 0x7)))
4532
Ian Rogers30fab402012-01-23 15:43:46 -08004533class HeapChunkContext {
4534 public:
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004535 // Maximum chunk size. Obtain this from the formula:
4536 // (((maximum_heap_size / ALLOCATION_UNIT_SIZE) + 255) / 256) * 2
4537 HeapChunkContext(bool merge, bool native)
Ian Rogers30fab402012-01-23 15:43:46 -08004538 : buf_(16384 - 16),
4539 type_(0),
Mathieu Chartier36dab362014-07-30 14:59:56 -07004540 chunk_overhead_(0) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004541 Reset();
4542 if (native) {
Ian Rogers30fab402012-01-23 15:43:46 -08004543 type_ = CHUNK_TYPE("NHSG");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004544 } else {
Ian Rogers30fab402012-01-23 15:43:46 -08004545 type_ = merge ? CHUNK_TYPE("HPSG") : CHUNK_TYPE("HPSO");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004546 }
4547 }
4548
4549 ~HeapChunkContext() {
Ian Rogers30fab402012-01-23 15:43:46 -08004550 if (p_ > &buf_[0]) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004551 Flush();
4552 }
4553 }
4554
Mathieu Chartier36dab362014-07-30 14:59:56 -07004555 void SetChunkOverhead(size_t chunk_overhead) {
4556 chunk_overhead_ = chunk_overhead;
4557 }
4558
4559 void ResetStartOfNextChunk() {
4560 startOfNextMemoryChunk_ = nullptr;
4561 }
4562
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004563 void EnsureHeader(const void* chunk_ptr) {
Ian Rogers30fab402012-01-23 15:43:46 -08004564 if (!needHeader_) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004565 return;
4566 }
4567
4568 // Start a new HPSx chunk.
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004569 JDWP::Write4BE(&p_, 1); // Heap id (bogus; we only have one heap).
4570 JDWP::Write1BE(&p_, 8); // Size of allocation unit, in bytes.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004571
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004572 JDWP::Write4BE(&p_, reinterpret_cast<uintptr_t>(chunk_ptr)); // virtual address of segment start.
4573 JDWP::Write4BE(&p_, 0); // offset of this piece (relative to the virtual address).
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004574 // [u4]: length of piece, in allocation units
4575 // 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 -08004576 pieceLenField_ = p_;
4577 JDWP::Write4BE(&p_, 0x55555555);
4578 needHeader_ = false;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004579 }
4580
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004581 void Flush() REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -07004582 if (pieceLenField_ == nullptr) {
Ian Rogersd636b062013-01-18 17:51:18 -08004583 // Flush immediately post Reset (maybe back-to-back Flush). Ignore.
4584 CHECK(needHeader_);
4585 return;
4586 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004587 // Patch the "length of piece" field.
Ian Rogers30fab402012-01-23 15:43:46 -08004588 CHECK_LE(&buf_[0], pieceLenField_);
4589 CHECK_LE(pieceLenField_, p_);
4590 JDWP::Set4BE(pieceLenField_, totalAllocationUnits_);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004591
Alex Light772099a2017-11-21 14:05:04 -08004592 ArrayRef<const uint8_t> out(&buf_[0], p_ - &buf_[0]);
4593 Runtime::Current()->GetRuntimeCallbacks()->DdmPublishChunk(type_, out);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004594 Reset();
4595 }
4596
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004597 static void HeapChunkJavaCallback(void* start, void* end, size_t used_bytes, void* arg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004598 REQUIRES_SHARED(Locks::heap_bitmap_lock_,
Ian Rogersb726dcb2012-09-05 08:57:23 -07004599 Locks::mutator_lock_) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004600 reinterpret_cast<HeapChunkContext*>(arg)->HeapChunkJavaCallback(start, end, used_bytes);
4601 }
4602
4603 static void HeapChunkNativeCallback(void* start, void* end, size_t used_bytes, void* arg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004604 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004605 reinterpret_cast<HeapChunkContext*>(arg)->HeapChunkNativeCallback(start, end, used_bytes);
Elliott Hughesa2155262011-11-16 16:26:58 -08004606 }
4607
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004608 private:
Elliott Hughesa2155262011-11-16 16:26:58 -08004609 enum { ALLOCATION_UNIT_SIZE = 8 };
4610
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004611 void Reset() {
Ian Rogers30fab402012-01-23 15:43:46 -08004612 p_ = &buf_[0];
Mathieu Chartier36dab362014-07-30 14:59:56 -07004613 ResetStartOfNextChunk();
Ian Rogers30fab402012-01-23 15:43:46 -08004614 totalAllocationUnits_ = 0;
4615 needHeader_ = true;
Ian Rogersc0542af2014-09-03 16:16:56 -07004616 pieceLenField_ = nullptr;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004617 }
4618
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004619 bool IsNative() const {
4620 return type_ == CHUNK_TYPE("NHSG");
4621 }
4622
4623 // Returns true if the object is not an empty chunk.
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004624 bool ProcessRecord(void* start, size_t used_bytes) REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers30fab402012-01-23 15:43:46 -08004625 // Note: heap call backs cannot manipulate the heap upon which they are crawling, care is taken
4626 // in the following code not to allocate memory, by ensuring buf_ is of the correct size
Ian Rogers15bf2d32012-08-28 17:33:04 -07004627 if (used_bytes == 0) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004628 if (start == nullptr) {
4629 // Reset for start of new heap.
4630 startOfNextMemoryChunk_ = nullptr;
4631 Flush();
4632 }
4633 // Only process in use memory so that free region information
4634 // also includes dlmalloc book keeping.
4635 return false;
Elliott Hughesa2155262011-11-16 16:26:58 -08004636 }
Ian Rogersc0542af2014-09-03 16:16:56 -07004637 if (startOfNextMemoryChunk_ != nullptr) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004638 // Transmit any pending free memory. Native free memory of over kMaxFreeLen could be because
4639 // of the use of mmaps, so don't report. If not free memory then start a new segment.
4640 bool flush = true;
4641 if (start > startOfNextMemoryChunk_) {
4642 const size_t kMaxFreeLen = 2 * kPageSize;
4643 void* free_start = startOfNextMemoryChunk_;
4644 void* free_end = start;
4645 const size_t free_len =
4646 reinterpret_cast<uintptr_t>(free_end) - reinterpret_cast<uintptr_t>(free_start);
4647 if (!IsNative() || free_len < kMaxFreeLen) {
4648 AppendChunk(HPSG_STATE(SOLIDITY_FREE, 0), free_start, free_len, IsNative());
4649 flush = false;
Ian Rogers15bf2d32012-08-28 17:33:04 -07004650 }
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004651 }
4652 if (flush) {
4653 startOfNextMemoryChunk_ = nullptr;
4654 Flush();
4655 }
Ian Rogers15bf2d32012-08-28 17:33:04 -07004656 }
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004657 return true;
Ian Rogers15bf2d32012-08-28 17:33:04 -07004658 }
Elliott Hughesa2155262011-11-16 16:26:58 -08004659
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004660 void HeapChunkNativeCallback(void* start, void* /*end*/, size_t used_bytes)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004661 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004662 if (ProcessRecord(start, used_bytes)) {
4663 uint8_t state = ExamineNativeObject(start);
Andreas Gampe98ea9d92018-10-19 14:06:15 -07004664 AppendChunk(state, start, used_bytes + chunk_overhead_, /*is_native=*/ true);
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004665 startOfNextMemoryChunk_ = reinterpret_cast<char*>(start) + used_bytes + chunk_overhead_;
4666 }
4667 }
4668
4669 void HeapChunkJavaCallback(void* start, void* /*end*/, size_t used_bytes)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004670 REQUIRES_SHARED(Locks::heap_bitmap_lock_, Locks::mutator_lock_) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004671 if (ProcessRecord(start, used_bytes)) {
4672 // Determine the type of this chunk.
4673 // OLD-TODO: if context.merge, see if this chunk is different from the last chunk.
4674 // If it's the same, we should combine them.
4675 uint8_t state = ExamineJavaObject(reinterpret_cast<mirror::Object*>(start));
Andreas Gampe98ea9d92018-10-19 14:06:15 -07004676 AppendChunk(state, start, used_bytes + chunk_overhead_, /*is_native=*/ false);
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004677 startOfNextMemoryChunk_ = reinterpret_cast<char*>(start) + used_bytes + chunk_overhead_;
4678 }
4679 }
4680
4681 void AppendChunk(uint8_t state, void* ptr, size_t length, bool is_native)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004682 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07004683 // Make sure there's enough room left in the buffer.
4684 // We need to use two bytes for every fractional 256 allocation units used by the chunk plus
4685 // 17 bytes for any header.
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004686 const size_t needed = ((RoundUp(length / ALLOCATION_UNIT_SIZE, 256) / 256) * 2) + 17;
4687 size_t byte_left = &buf_.back() - p_;
4688 if (byte_left < needed) {
4689 if (is_native) {
Pavel Vyssotski7522c742014-12-08 13:38:26 +06004690 // Cannot trigger memory allocation while walking native heap.
Pavel Vyssotski7522c742014-12-08 13:38:26 +06004691 return;
4692 }
Ian Rogers15bf2d32012-08-28 17:33:04 -07004693 Flush();
4694 }
4695
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004696 byte_left = &buf_.back() - p_;
4697 if (byte_left < needed) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07004698 LOG(WARNING) << "Chunk is too big to transmit (chunk_len=" << length << ", "
4699 << needed << " bytes)";
4700 return;
4701 }
4702 EnsureHeader(ptr);
Elliott Hughesa2155262011-11-16 16:26:58 -08004703 // Write out the chunk description.
Ian Rogers15bf2d32012-08-28 17:33:04 -07004704 length /= ALLOCATION_UNIT_SIZE; // Convert to allocation units.
4705 totalAllocationUnits_ += length;
4706 while (length > 256) {
Ian Rogers30fab402012-01-23 15:43:46 -08004707 *p_++ = state | HPSG_PARTIAL;
4708 *p_++ = 255; // length - 1
Ian Rogers15bf2d32012-08-28 17:33:04 -07004709 length -= 256;
Elliott Hughesa2155262011-11-16 16:26:58 -08004710 }
Ian Rogers30fab402012-01-23 15:43:46 -08004711 *p_++ = state;
Ian Rogers15bf2d32012-08-28 17:33:04 -07004712 *p_++ = length - 1;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004713 }
4714
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004715 uint8_t ExamineNativeObject(const void* p) REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004716 return p == nullptr ? HPSG_STATE(SOLIDITY_FREE, 0) : HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
4717 }
4718
4719 uint8_t ExamineJavaObject(mirror::Object* o)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004720 REQUIRES_SHARED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -07004721 if (o == nullptr) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004722 return HPSG_STATE(SOLIDITY_FREE, 0);
4723 }
Elliott Hughesa2155262011-11-16 16:26:58 -08004724 // It's an allocated chunk. Figure out what it is.
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004725 gc::Heap* heap = Runtime::Current()->GetHeap();
4726 if (!heap->IsLiveObjectLocked(o)) {
4727 LOG(ERROR) << "Invalid object in managed heap: " << o;
Elliott Hughesa2155262011-11-16 16:26:58 -08004728 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
4729 }
Vladimir Marko4617d582019-03-28 13:48:31 +00004730 ObjPtr<mirror::Class> c = o->GetClass();
Ian Rogersc0542af2014-09-03 16:16:56 -07004731 if (c == nullptr) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004732 // The object was probably just created but hasn't been initialized yet.
4733 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
4734 }
Vladimir Marko4617d582019-03-28 13:48:31 +00004735 if (!heap->IsValidObjectAddress(c.Ptr())) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07004736 LOG(ERROR) << "Invalid class for managed heap object: " << o << " " << c;
Elliott Hughesa2155262011-11-16 16:26:58 -08004737 return HPSG_STATE(SOLIDITY_HARD, KIND_UNKNOWN);
4738 }
Mathieu Chartierf26e1b32015-01-29 10:47:10 -08004739 if (c->GetClass() == nullptr) {
4740 LOG(ERROR) << "Null class of class " << c << " for object " << o;
4741 return HPSG_STATE(SOLIDITY_HARD, KIND_UNKNOWN);
4742 }
Elliott Hughesa2155262011-11-16 16:26:58 -08004743 if (c->IsClassClass()) {
4744 return HPSG_STATE(SOLIDITY_HARD, KIND_CLASS_OBJECT);
4745 }
Elliott Hughesa2155262011-11-16 16:26:58 -08004746 if (c->IsArrayClass()) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004747 switch (c->GetComponentSize()) {
4748 case 1: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_1);
4749 case 2: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_2);
4750 case 4: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
4751 case 8: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_8);
4752 }
4753 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004754 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
4755 }
4756
Ian Rogers30fab402012-01-23 15:43:46 -08004757 std::vector<uint8_t> buf_;
4758 uint8_t* p_;
4759 uint8_t* pieceLenField_;
Ian Rogers15bf2d32012-08-28 17:33:04 -07004760 void* startOfNextMemoryChunk_;
Ian Rogers30fab402012-01-23 15:43:46 -08004761 size_t totalAllocationUnits_;
4762 uint32_t type_;
Ian Rogers30fab402012-01-23 15:43:46 -08004763 bool needHeader_;
Mathieu Chartier36dab362014-07-30 14:59:56 -07004764 size_t chunk_overhead_;
Ian Rogers30fab402012-01-23 15:43:46 -08004765
Elliott Hughesa2155262011-11-16 16:26:58 -08004766 DISALLOW_COPY_AND_ASSIGN(HeapChunkContext);
4767};
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004768
4769void Dbg::DdmSendHeapSegments(bool native) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004770 Dbg::HpsgWhen when = native ? gDdmNhsgWhen : gDdmHpsgWhen;
4771 Dbg::HpsgWhat what = native ? gDdmNhsgWhat : gDdmHpsgWhat;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004772 if (when == HPSG_WHEN_NEVER) {
4773 return;
4774 }
Alex Light772099a2017-11-21 14:05:04 -08004775 RuntimeCallbacks* cb = Runtime::Current()->GetRuntimeCallbacks();
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004776 // Figure out what kind of chunks we'll be sending.
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004777 CHECK(what == HPSG_WHAT_MERGED_OBJECTS || what == HPSG_WHAT_DISTINCT_OBJECTS)
4778 << static_cast<int>(what);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004779
4780 // First, send a heap start chunk.
4781 uint8_t heap_id[4];
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004782 JDWP::Set4BE(&heap_id[0], 1); // Heap id (bogus; we only have one heap).
Alex Light772099a2017-11-21 14:05:04 -08004783 cb->DdmPublishChunk(native ? CHUNK_TYPE("NHST") : CHUNK_TYPE("HPST"),
4784 ArrayRef<const uint8_t>(heap_id));
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07004785 Thread* self = Thread::Current();
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07004786 Locks::mutator_lock_->AssertSharedHeld(self);
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07004787
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004788 // Send a series of heap segment chunks.
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004789 HeapChunkContext context(what == HPSG_WHAT_MERGED_OBJECTS, native);
Andreas Gampe0c183382017-07-13 22:26:24 -07004790 auto bump_pointer_space_visitor = [&](mirror::Object* obj)
4791 REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
4792 const size_t size = RoundUp(obj->SizeOf(), kObjectAlignment);
4793 HeapChunkContext::HeapChunkJavaCallback(
4794 obj, reinterpret_cast<void*>(reinterpret_cast<uintptr_t>(obj) + size), size, &context);
4795 };
Elliott Hughesa2155262011-11-16 16:26:58 -08004796 if (native) {
Dimitry Ivanove6465bc2015-12-14 18:55:02 -08004797 UNIMPLEMENTED(WARNING) << "Native heap inspection is not supported";
Elliott Hughesa2155262011-11-16 16:26:58 -08004798 } else {
Ian Rogers1d54e732013-05-02 21:10:01 -07004799 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartier36dab362014-07-30 14:59:56 -07004800 for (const auto& space : heap->GetContinuousSpaces()) {
4801 if (space->IsDlMallocSpace()) {
Mathieu Chartier4c69d7f2014-10-10 12:45:50 -07004802 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004803 // dlmalloc's chunk header is 2 * sizeof(size_t), but if the previous chunk is in use for an
4804 // allocation then the first sizeof(size_t) may belong to it.
4805 context.SetChunkOverhead(sizeof(size_t));
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004806 space->AsDlMallocSpace()->Walk(HeapChunkContext::HeapChunkJavaCallback, &context);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004807 } else if (space->IsRosAllocSpace()) {
4808 context.SetChunkOverhead(0);
Mathieu Chartier4c69d7f2014-10-10 12:45:50 -07004809 // Need to acquire the mutator lock before the heap bitmap lock with exclusive access since
4810 // RosAlloc's internal logic doesn't know to release and reacquire the heap bitmap lock.
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07004811 ScopedThreadSuspension sts(self, kSuspended);
Mathieu Chartier4f55e222015-09-04 13:26:21 -07004812 ScopedSuspendAll ssa(__FUNCTION__);
4813 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
4814 space->AsRosAllocSpace()->Walk(HeapChunkContext::HeapChunkJavaCallback, &context);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004815 } else if (space->IsBumpPointerSpace()) {
Mathieu Chartier4c69d7f2014-10-10 12:45:50 -07004816 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004817 context.SetChunkOverhead(0);
Andreas Gampe0c183382017-07-13 22:26:24 -07004818 space->AsBumpPointerSpace()->Walk(bump_pointer_space_visitor);
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004819 HeapChunkContext::HeapChunkJavaCallback(nullptr, nullptr, 0, &context);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08004820 } else if (space->IsRegionSpace()) {
4821 heap->IncrementDisableMovingGC(self);
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07004822 {
4823 ScopedThreadSuspension sts(self, kSuspended);
Mathieu Chartier4f55e222015-09-04 13:26:21 -07004824 ScopedSuspendAll ssa(__FUNCTION__);
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07004825 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
4826 context.SetChunkOverhead(0);
Andreas Gampe0c183382017-07-13 22:26:24 -07004827 space->AsRegionSpace()->Walk(bump_pointer_space_visitor);
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07004828 HeapChunkContext::HeapChunkJavaCallback(nullptr, nullptr, 0, &context);
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07004829 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08004830 heap->DecrementDisableMovingGC(self);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004831 } else {
4832 UNIMPLEMENTED(WARNING) << "Not counting objects in space " << *space;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07004833 }
Mathieu Chartier36dab362014-07-30 14:59:56 -07004834 context.ResetStartOfNextChunk();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07004835 }
Mathieu Chartier4c69d7f2014-10-10 12:45:50 -07004836 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07004837 // Walk the large objects, these are not in the AllocSpace.
Mathieu Chartier36dab362014-07-30 14:59:56 -07004838 context.SetChunkOverhead(0);
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004839 heap->GetLargeObjectsSpace()->Walk(HeapChunkContext::HeapChunkJavaCallback, &context);
Elliott Hughesa2155262011-11-16 16:26:58 -08004840 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004841
4842 // Finally, send a heap end chunk.
Alex Light772099a2017-11-21 14:05:04 -08004843 cb->DdmPublishChunk(native ? CHUNK_TYPE("NHEN") : CHUNK_TYPE("HPEN"),
4844 ArrayRef<const uint8_t>(heap_id));
Elliott Hughes767a1472011-10-26 18:49:02 -07004845}
4846
Brian Carlstrom306db812014-09-05 13:01:41 -07004847void Dbg::SetAllocTrackingEnabled(bool enable) {
Man Cao8c2ff642015-05-27 17:25:30 -07004848 gc::AllocRecordObjectMap::SetAllocTrackingEnabled(enable);
Elliott Hughes545a0642011-11-08 19:10:03 -08004849}
4850
4851void Dbg::DumpRecentAllocations() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004852 ScopedObjectAccess soa(Thread::Current());
Brian Carlstrom306db812014-09-05 13:01:41 -07004853 MutexLock mu(soa.Self(), *Locks::alloc_tracker_lock_);
Man Cao8c2ff642015-05-27 17:25:30 -07004854 if (!Runtime::Current()->GetHeap()->IsAllocTrackingEnabled()) {
Elliott Hughes545a0642011-11-08 19:10:03 -08004855 LOG(INFO) << "Not recording tracked allocations";
4856 return;
4857 }
Man Cao8c2ff642015-05-27 17:25:30 -07004858 gc::AllocRecordObjectMap* records = Runtime::Current()->GetHeap()->GetAllocationRecords();
4859 CHECK(records != nullptr);
Elliott Hughes545a0642011-11-08 19:10:03 -08004860
Man Cao1ed11b92015-06-11 22:47:35 -07004861 const uint16_t capped_count = CappedAllocRecordCount(records->GetRecentAllocationSize());
Brian Carlstrom306db812014-09-05 13:01:41 -07004862 uint16_t count = capped_count;
Elliott Hughes545a0642011-11-08 19:10:03 -08004863
Man Cao8c2ff642015-05-27 17:25:30 -07004864 LOG(INFO) << "Tracked allocations, (count=" << count << ")";
4865 for (auto it = records->RBegin(), end = records->REnd();
4866 count > 0 && it != end; count--, it++) {
Mathieu Chartier458b1052016-03-29 14:02:55 -07004867 const gc::AllocRecord* record = &it->second;
Elliott Hughes545a0642011-11-08 19:10:03 -08004868
Man Cao8c2ff642015-05-27 17:25:30 -07004869 LOG(INFO) << StringPrintf(" Thread %-2d %6zd bytes ", record->GetTid(), record->ByteCount())
David Sehr709b0702016-10-13 09:12:37 -07004870 << mirror::Class::PrettyClass(record->GetClass());
Elliott Hughes545a0642011-11-08 19:10:03 -08004871
Man Cao8c2ff642015-05-27 17:25:30 -07004872 for (size_t stack_frame = 0, depth = record->GetDepth(); stack_frame < depth; ++stack_frame) {
4873 const gc::AllocRecordStackTraceElement& stack_element = record->StackElement(stack_frame);
4874 ArtMethod* m = stack_element.GetMethod();
David Sehr709b0702016-10-13 09:12:37 -07004875 LOG(INFO) << " " << ArtMethod::PrettyMethod(m) << " line "
4876 << stack_element.ComputeLineNumber();
Elliott Hughes545a0642011-11-08 19:10:03 -08004877 }
4878
4879 // pause periodically to help logcat catch up
4880 if ((count % 5) == 0) {
4881 usleep(40000);
4882 }
Elliott Hughes545a0642011-11-08 19:10:03 -08004883 }
4884}
4885
4886class StringTable {
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07004887 private:
4888 struct Entry {
Andreas Gampe84eadb22017-07-07 15:08:01 -07004889 explicit Entry(const char* data_in)
4890 : data(data_in), hash(ComputeModifiedUtf8Hash(data_in)), index(0) {
4891 }
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07004892 Entry(const Entry& entry) = default;
4893 Entry(Entry&& entry) = default;
4894
4895 // Pointer to the actual string data.
4896 const char* data;
Andreas Gampe84eadb22017-07-07 15:08:01 -07004897
4898 // The hash of the data.
4899 const uint32_t hash;
4900
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07004901 // The index. This will be filled in on Finish and is not part of the ordering, so mark it
4902 // mutable.
4903 mutable uint32_t index;
4904
Andreas Gampe84eadb22017-07-07 15:08:01 -07004905 bool operator==(const Entry& other) const {
4906 return strcmp(data, other.data) == 0;
4907 }
4908 };
4909 struct EntryHash {
4910 size_t operator()(const Entry& entry) const {
4911 return entry.hash;
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07004912 }
4913 };
4914
Elliott Hughes545a0642011-11-08 19:10:03 -08004915 public:
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07004916 StringTable() : finished_(false) {
Elliott Hughes545a0642011-11-08 19:10:03 -08004917 }
4918
Andreas Gampef774a4e2017-07-06 22:15:18 -07004919 void Add(const char* str, bool copy_string) {
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07004920 DCHECK(!finished_);
Andreas Gampef774a4e2017-07-06 22:15:18 -07004921 if (UNLIKELY(copy_string)) {
4922 // Check whether it's already there.
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07004923 Entry entry(str);
4924 if (table_.find(entry) != table_.end()) {
Andreas Gampef774a4e2017-07-06 22:15:18 -07004925 return;
4926 }
Mathieu Chartier4345c462014-06-27 10:20:14 -07004927
Andreas Gampef774a4e2017-07-06 22:15:18 -07004928 // Make a copy.
4929 size_t str_len = strlen(str);
4930 char* copy = new char[str_len + 1];
4931 strlcpy(copy, str, str_len + 1);
4932 string_backup_.emplace_back(copy);
4933 str = copy;
4934 }
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07004935 Entry entry(str);
4936 table_.insert(entry);
4937 }
4938
4939 // Update all entries and give them an index. Note that this is likely not the insertion order,
4940 // as the set will with high likelihood reorder elements. Thus, Add must not be called after
4941 // Finish, and Finish must be called before IndexOf. In that case, WriteTo will walk in
4942 // the same order as Finish, and indices will agree. The order invariant, as well as indices,
4943 // are enforced through debug checks.
4944 void Finish() {
4945 DCHECK(!finished_);
4946 finished_ = true;
4947 uint32_t index = 0;
4948 for (auto& entry : table_) {
4949 entry.index = index;
4950 ++index;
4951 }
Elliott Hughes545a0642011-11-08 19:10:03 -08004952 }
4953
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004954 size_t IndexOf(const char* s) const {
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07004955 DCHECK(finished_);
4956 Entry entry(s);
4957 auto it = table_.find(entry);
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004958 if (it == table_.end()) {
4959 LOG(FATAL) << "IndexOf(\"" << s << "\") failed";
4960 }
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07004961 return it->index;
Elliott Hughes545a0642011-11-08 19:10:03 -08004962 }
4963
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004964 size_t Size() const {
Elliott Hughes545a0642011-11-08 19:10:03 -08004965 return table_.size();
4966 }
4967
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004968 void WriteTo(std::vector<uint8_t>& bytes) const {
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07004969 DCHECK(finished_);
4970 uint32_t cur_index = 0;
4971 for (const auto& entry : table_) {
4972 DCHECK_EQ(cur_index++, entry.index);
4973
4974 size_t s_len = CountModifiedUtf8Chars(entry.data);
Christopher Ferris8a354052015-04-24 17:23:53 -07004975 std::unique_ptr<uint16_t[]> s_utf16(new uint16_t[s_len]);
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07004976 ConvertModifiedUtf8ToUtf16(s_utf16.get(), entry.data);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004977 JDWP::AppendUtf16BE(bytes, s_utf16.get(), s_len);
Elliott Hughes545a0642011-11-08 19:10:03 -08004978 }
4979 }
4980
4981 private:
Andreas Gampe84eadb22017-07-07 15:08:01 -07004982 std::unordered_set<Entry, EntryHash> table_;
Andreas Gampef774a4e2017-07-06 22:15:18 -07004983 std::vector<std::unique_ptr<char[]>> string_backup_;
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07004984
4985 bool finished_;
4986
Elliott Hughes545a0642011-11-08 19:10:03 -08004987 DISALLOW_COPY_AND_ASSIGN(StringTable);
4988};
4989
Mathieu Chartiere401d142015-04-22 13:56:20 -07004990static const char* GetMethodSourceFile(ArtMethod* method)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004991 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004992 DCHECK(method != nullptr);
4993 const char* source_file = method->GetDeclaringClassSourceFile();
Sebastien Hertz280286a2014-04-28 09:26:50 +02004994 return (source_file != nullptr) ? source_file : "";
4995}
4996
Elliott Hughes545a0642011-11-08 19:10:03 -08004997/*
4998 * The data we send to DDMS contains everything we have recorded.
4999 *
5000 * Message header (all values big-endian):
5001 * (1b) message header len (to allow future expansion); includes itself
5002 * (1b) entry header len
5003 * (1b) stack frame len
5004 * (2b) number of entries
5005 * (4b) offset to string table from start of message
5006 * (2b) number of class name strings
5007 * (2b) number of method name strings
5008 * (2b) number of source file name strings
5009 * For each entry:
5010 * (4b) total allocation size
Elliott Hughes221229c2013-01-08 18:17:50 -08005011 * (2b) thread id
Elliott Hughes545a0642011-11-08 19:10:03 -08005012 * (2b) allocated object's class name index
5013 * (1b) stack depth
5014 * For each stack frame:
5015 * (2b) method's class name
5016 * (2b) method name
5017 * (2b) method source file
5018 * (2b) line number, clipped to 32767; -2 if native; -1 if no source
5019 * (xb) class name strings
5020 * (xb) method name strings
5021 * (xb) source file strings
5022 *
5023 * As with other DDM traffic, strings are sent as a 4-byte length
5024 * followed by UTF-16 data.
5025 *
5026 * We send up 16-bit unsigned indexes into string tables. In theory there
Brian Carlstrom306db812014-09-05 13:01:41 -07005027 * can be (kMaxAllocRecordStackDepth * alloc_record_max_) unique strings in
Elliott Hughes545a0642011-11-08 19:10:03 -08005028 * each table, but in practice there should be far fewer.
5029 *
5030 * The chief reason for using a string table here is to keep the size of
5031 * the DDMS message to a minimum. This is partly to make the protocol
5032 * efficient, but also because we have to form the whole thing up all at
5033 * once in a memory buffer.
5034 *
5035 * We use separate string tables for class names, method names, and source
5036 * files to keep the indexes small. There will generally be no overlap
5037 * between the contents of these tables.
5038 */
5039jbyteArray Dbg::GetRecentAllocations() {
Ian Rogerscf7f1912014-10-22 22:06:39 -07005040 if ((false)) {
Elliott Hughes545a0642011-11-08 19:10:03 -08005041 DumpRecentAllocations();
5042 }
5043
Ian Rogers50b35e22012-10-04 10:09:15 -07005044 Thread* self = Thread::Current();
Elliott Hughes545a0642011-11-08 19:10:03 -08005045 std::vector<uint8_t> bytes;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005046 {
Brian Carlstrom306db812014-09-05 13:01:41 -07005047 MutexLock mu(self, *Locks::alloc_tracker_lock_);
Man Cao8c2ff642015-05-27 17:25:30 -07005048 gc::AllocRecordObjectMap* records = Runtime::Current()->GetHeap()->GetAllocationRecords();
5049 // In case this method is called when allocation tracker is disabled,
5050 // we should still send some data back.
5051 gc::AllocRecordObjectMap dummy;
5052 if (records == nullptr) {
5053 CHECK(!Runtime::Current()->GetHeap()->IsAllocTrackingEnabled());
5054 records = &dummy;
5055 }
Man Cao41656de2015-07-06 18:53:15 -07005056 // We don't need to wait on the condition variable records->new_record_condition_, because this
5057 // function only reads the class objects, which are already marked so it doesn't change their
5058 // reachability.
Man Cao8c2ff642015-05-27 17:25:30 -07005059
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005060 //
5061 // Part 1: generate string tables.
5062 //
5063 StringTable class_names;
5064 StringTable method_names;
5065 StringTable filenames;
Elliott Hughes545a0642011-11-08 19:10:03 -08005066
Andreas Gampeff29cee2017-07-07 11:11:15 -07005067 VLOG(jdwp) << "Collecting StringTables.";
5068
Man Cao1ed11b92015-06-11 22:47:35 -07005069 const uint16_t capped_count = CappedAllocRecordCount(records->GetRecentAllocationSize());
Brian Carlstrom306db812014-09-05 13:01:41 -07005070 uint16_t count = capped_count;
Andreas Gamped0fc7682017-07-07 14:03:08 -07005071 size_t alloc_byte_count = 0;
Man Cao8c2ff642015-05-27 17:25:30 -07005072 for (auto it = records->RBegin(), end = records->REnd();
5073 count > 0 && it != end; count--, it++) {
Mathieu Chartier458b1052016-03-29 14:02:55 -07005074 const gc::AllocRecord* record = &it->second;
Ian Rogers1ff3c982014-08-12 02:30:58 -07005075 std::string temp;
Andreas Gampef774a4e2017-07-06 22:15:18 -07005076 const char* class_descr = record->GetClassDescriptor(&temp);
5077 class_names.Add(class_descr, !temp.empty());
Andreas Gamped0fc7682017-07-07 14:03:08 -07005078
5079 // Size + tid + class name index + stack depth.
5080 alloc_byte_count += 4u + 2u + 2u + 1u;
5081
Man Cao8c2ff642015-05-27 17:25:30 -07005082 for (size_t i = 0, depth = record->GetDepth(); i < depth; i++) {
5083 ArtMethod* m = record->StackElement(i).GetMethod();
Andreas Gampef774a4e2017-07-06 22:15:18 -07005084 class_names.Add(m->GetDeclaringClassDescriptor(), false);
5085 method_names.Add(m->GetName(), false);
5086 filenames.Add(GetMethodSourceFile(m), false);
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005087 }
Andreas Gamped0fc7682017-07-07 14:03:08 -07005088
5089 // Depth * (class index + method name index + file name index + line number).
5090 alloc_byte_count += record->GetDepth() * (2u + 2u + 2u + 2u);
Elliott Hughes545a0642011-11-08 19:10:03 -08005091 }
5092
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07005093 class_names.Finish();
5094 method_names.Finish();
5095 filenames.Finish();
Andreas Gampeff29cee2017-07-07 11:11:15 -07005096 VLOG(jdwp) << "Done collecting StringTables:" << std::endl
5097 << " ClassNames: " << class_names.Size() << std::endl
5098 << " MethodNames: " << method_names.Size() << std::endl
5099 << " Filenames: " << filenames.Size();
5100
Man Cao8c2ff642015-05-27 17:25:30 -07005101 LOG(INFO) << "recent allocation records: " << capped_count;
5102 LOG(INFO) << "allocation records all objects: " << records->Size();
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005103
5104 //
5105 // Part 2: Generate the output and store it in the buffer.
5106 //
5107
5108 // (1b) message header len (to allow future expansion); includes itself
5109 // (1b) entry header len
5110 // (1b) stack frame len
5111 const int kMessageHeaderLen = 15;
5112 const int kEntryHeaderLen = 9;
5113 const int kStackFrameLen = 8;
5114 JDWP::Append1BE(bytes, kMessageHeaderLen);
5115 JDWP::Append1BE(bytes, kEntryHeaderLen);
5116 JDWP::Append1BE(bytes, kStackFrameLen);
5117
5118 // (2b) number of entries
5119 // (4b) offset to string table from start of message
5120 // (2b) number of class name strings
5121 // (2b) number of method name strings
5122 // (2b) number of source file name strings
Brian Carlstrom306db812014-09-05 13:01:41 -07005123 JDWP::Append2BE(bytes, capped_count);
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005124 size_t string_table_offset = bytes.size();
Brian Carlstrom7934ac22013-07-26 10:54:15 -07005125 JDWP::Append4BE(bytes, 0); // We'll patch this later...
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005126 JDWP::Append2BE(bytes, class_names.Size());
5127 JDWP::Append2BE(bytes, method_names.Size());
5128 JDWP::Append2BE(bytes, filenames.Size());
5129
Andreas Gampeff29cee2017-07-07 11:11:15 -07005130 VLOG(jdwp) << "Dumping allocations with stacks";
5131
Andreas Gamped0fc7682017-07-07 14:03:08 -07005132 // Enlarge the vector for the allocation data.
5133 size_t reserve_size = bytes.size() + alloc_byte_count;
5134 bytes.reserve(reserve_size);
5135
Ian Rogers1ff3c982014-08-12 02:30:58 -07005136 std::string temp;
Man Cao8c2ff642015-05-27 17:25:30 -07005137 count = capped_count;
5138 // The last "count" number of allocation records in "records" are the most recent "count" number
5139 // of allocations. Reverse iterate to get them. The most recent allocation is sent first.
5140 for (auto it = records->RBegin(), end = records->REnd();
5141 count > 0 && it != end; count--, it++) {
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005142 // For each entry:
5143 // (4b) total allocation size
5144 // (2b) thread id
5145 // (2b) allocated object's class name index
5146 // (1b) stack depth
Mathieu Chartier458b1052016-03-29 14:02:55 -07005147 const gc::AllocRecord* record = &it->second;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005148 size_t stack_depth = record->GetDepth();
Mathieu Chartierf8322842014-05-16 10:59:25 -07005149 size_t allocated_object_class_name_index =
Man Cao41656de2015-07-06 18:53:15 -07005150 class_names.IndexOf(record->GetClassDescriptor(&temp));
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07005151 JDWP::Append4BE(bytes, record->ByteCount());
Man Cao8c2ff642015-05-27 17:25:30 -07005152 JDWP::Append2BE(bytes, static_cast<uint16_t>(record->GetTid()));
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005153 JDWP::Append2BE(bytes, allocated_object_class_name_index);
5154 JDWP::Append1BE(bytes, stack_depth);
5155
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005156 for (size_t stack_frame = 0; stack_frame < stack_depth; ++stack_frame) {
5157 // For each stack frame:
5158 // (2b) method's class name
5159 // (2b) method name
5160 // (2b) method source file
5161 // (2b) line number, clipped to 32767; -2 if native; -1 if no source
Man Cao8c2ff642015-05-27 17:25:30 -07005162 ArtMethod* m = record->StackElement(stack_frame).GetMethod();
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07005163 size_t class_name_index = class_names.IndexOf(m->GetDeclaringClassDescriptor());
5164 size_t method_name_index = method_names.IndexOf(m->GetName());
5165 size_t file_name_index = filenames.IndexOf(GetMethodSourceFile(m));
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005166 JDWP::Append2BE(bytes, class_name_index);
5167 JDWP::Append2BE(bytes, method_name_index);
5168 JDWP::Append2BE(bytes, file_name_index);
Man Cao8c2ff642015-05-27 17:25:30 -07005169 JDWP::Append2BE(bytes, record->StackElement(stack_frame).ComputeLineNumber());
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005170 }
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005171 }
5172
Andreas Gamped0fc7682017-07-07 14:03:08 -07005173 CHECK_EQ(bytes.size(), reserve_size);
Andreas Gampeff29cee2017-07-07 11:11:15 -07005174 VLOG(jdwp) << "Dumping tables.";
5175
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005176 // (xb) class name strings
5177 // (xb) method name strings
5178 // (xb) source file strings
5179 JDWP::Set4BE(&bytes[string_table_offset], bytes.size());
5180 class_names.WriteTo(bytes);
5181 method_names.WriteTo(bytes);
5182 filenames.WriteTo(bytes);
Andreas Gampeff29cee2017-07-07 11:11:15 -07005183
5184 VLOG(jdwp) << "GetRecentAllocations: data created. " << bytes.size();
Elliott Hughes545a0642011-11-08 19:10:03 -08005185 }
Ian Rogers50b35e22012-10-04 10:09:15 -07005186 JNIEnv* env = self->GetJniEnv();
Elliott Hughes545a0642011-11-08 19:10:03 -08005187 jbyteArray result = env->NewByteArray(bytes.size());
Ian Rogersc0542af2014-09-03 16:16:56 -07005188 if (result != nullptr) {
Elliott Hughes545a0642011-11-08 19:10:03 -08005189 env->SetByteArrayRegion(result, 0, bytes.size(), reinterpret_cast<const jbyte*>(&bytes[0]));
5190 }
5191 return result;
5192}
5193
Mathieu Chartiere401d142015-04-22 13:56:20 -07005194ArtMethod* DeoptimizationRequest::Method() const {
Andreas Gampe13b27842016-11-07 16:48:23 -08005195 return jni::DecodeArtMethod(method_);
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07005196}
5197
Mathieu Chartiere401d142015-04-22 13:56:20 -07005198void DeoptimizationRequest::SetMethod(ArtMethod* m) {
Andreas Gampe13b27842016-11-07 16:48:23 -08005199 method_ = jni::EncodeArtMethod(m);
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07005200}
5201
Mathieu Chartiera6b1ead2015-10-06 10:32:38 -07005202void Dbg::VisitRoots(RootVisitor* visitor) {
5203 // Visit breakpoint roots, used to prevent unloading of methods with breakpoints.
5204 ReaderMutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
5205 BufferedRootVisitor<128> root_visitor(visitor, RootInfo(kRootVMInternal));
5206 for (Breakpoint& breakpoint : gBreakpoints) {
Andreas Gampe542451c2016-07-26 09:02:02 -07005207 breakpoint.Method()->VisitRoots(root_visitor, kRuntimePointerSize);
Mathieu Chartiera6b1ead2015-10-06 10:32:38 -07005208 }
5209}
5210
Andreas Gampe04bbb5b2017-01-19 17:49:03 +00005211void Dbg::DbgThreadLifecycleCallback::ThreadStart(Thread* self) {
5212 Dbg::PostThreadStart(self);
5213}
5214
5215void Dbg::DbgThreadLifecycleCallback::ThreadDeath(Thread* self) {
5216 Dbg::PostThreadDeath(self);
5217}
5218
Andreas Gampe0f01b582017-01-18 15:22:37 -08005219void Dbg::DbgClassLoadCallback::ClassLoad(Handle<mirror::Class> klass ATTRIBUTE_UNUSED) {
5220 // Ignore ClassLoad;
5221}
5222void Dbg::DbgClassLoadCallback::ClassPrepare(Handle<mirror::Class> temp_klass ATTRIBUTE_UNUSED,
5223 Handle<mirror::Class> klass) {
5224 Dbg::PostClassPrepare(klass.Get());
5225}
5226
Elliott Hughes872d4ec2011-10-21 17:07:15 -07005227} // namespace art