blob: 9b5b84a5482f0b7277a4e63343a676a27cd85a5d [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"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080056#include "mirror/class-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -070057#include "mirror/class.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080058#include "mirror/class_loader.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080059#include "mirror/object-inl.h"
60#include "mirror/object_array-inl.h"
Ian Rogersb0fa5dc2014-04-28 16:47:08 -070061#include "mirror/string-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080062#include "mirror/throwable.h"
Andreas Gampe373a9b52017-10-18 09:01:57 -070063#include "nativehelper/scoped_local_ref.h"
64#include "nativehelper/scoped_primitive_array.h"
Nicolas Geoffray58cc1cb2017-11-20 13:27:29 +000065#include "oat_file.h"
Mathieu Chartier3398c782016-09-30 10:27:43 -070066#include "obj_ptr-inl.h"
Ian Rogers53b8b092014-03-13 23:45:53 -070067#include "reflection.h"
David Srbecky28f6cff2018-10-16 15:07:28 +010068#include "runtime-inl.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070069#include "scoped_thread_state_change-inl.h"
Andreas Gampe513061a2017-06-01 09:17:34 -070070#include "stack.h"
Elliott Hughes475fc232011-10-25 15:00:35 -070071#include "thread_list.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070072#include "well_known_classes.h"
Elliott Hughes475fc232011-10-25 15:00:35 -070073
Elliott Hughes872d4ec2011-10-21 17:07:15 -070074namespace art {
75
Andreas Gampe46ee31b2016-12-14 10:11:49 -080076using android::base::StringPrintf;
77
Sebastien Hertz0462c4c2015-04-01 16:34:17 +020078// The key identifying the debugger to update instrumentation.
79static constexpr const char* kDbgInstrumentationKey = "Debugger";
80
Man Cao8c2ff642015-05-27 17:25:30 -070081// 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 -070082static uint16_t CappedAllocRecordCount(size_t alloc_record_count) {
Man Cao1ed11b92015-06-11 22:47:35 -070083 const size_t cap = 0xffff;
Man Cao8c2ff642015-05-27 17:25:30 -070084 if (alloc_record_count > cap) {
85 return cap;
Brian Carlstrom306db812014-09-05 13:01:41 -070086 }
87 return alloc_record_count;
88}
Elliott Hughes475fc232011-10-25 15:00:35 -070089
Mathieu Chartier41af5e52015-10-28 11:10:46 -070090class Breakpoint : public ValueObject {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -070091 public:
Mathieu Chartier41af5e52015-10-28 11:10:46 -070092 Breakpoint(ArtMethod* method, uint32_t dex_pc, DeoptimizationRequest::Kind deoptimization_kind)
Alex Light97e78032017-06-27 17:51:55 -070093 : method_(method->GetCanonicalMethod(kRuntimePointerSize)),
Mathieu Chartier41af5e52015-10-28 11:10:46 -070094 dex_pc_(dex_pc),
95 deoptimization_kind_(deoptimization_kind) {
Sebastien Hertzf3928792014-11-17 19:00:37 +010096 CHECK(deoptimization_kind_ == DeoptimizationRequest::kNothing ||
97 deoptimization_kind_ == DeoptimizationRequest::kSelectiveDeoptimization ||
98 deoptimization_kind_ == DeoptimizationRequest::kFullDeoptimization);
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -070099 }
100
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700101 Breakpoint(const Breakpoint& other) REQUIRES_SHARED(Locks::mutator_lock_)
Mathieu Chartier41af5e52015-10-28 11:10:46 -0700102 : method_(other.method_),
103 dex_pc_(other.dex_pc_),
104 deoptimization_kind_(other.deoptimization_kind_) {}
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700105
Mathieu Chartier41af5e52015-10-28 11:10:46 -0700106 // Method() is called from root visiting, do not use ScopedObjectAccess here or it can cause
107 // GC to deadlock if another thread tries to call SuspendAll while the GC is in a runnable state.
108 ArtMethod* Method() const {
109 return method_;
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700110 }
111
112 uint32_t DexPc() const {
113 return dex_pc_;
114 }
115
Sebastien Hertzf3928792014-11-17 19:00:37 +0100116 DeoptimizationRequest::Kind GetDeoptimizationKind() const {
117 return deoptimization_kind_;
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700118 }
119
Alex Light6c8467f2015-11-20 15:03:26 -0800120 // Returns true if the method of this breakpoint and the passed in method should be considered the
121 // same. That is, they are either the same method or they are copied from the same method.
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700122 bool IsInMethod(ArtMethod* m) const REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light97e78032017-06-27 17:51:55 -0700123 return method_ == m->GetCanonicalMethod(kRuntimePointerSize);
Alex Light6c8467f2015-11-20 15:03:26 -0800124 }
125
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700126 private:
Sebastien Hertza76a6d42014-03-20 16:40:17 +0100127 // The location of this breakpoint.
Mathieu Chartier41af5e52015-10-28 11:10:46 -0700128 ArtMethod* method_;
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700129 uint32_t dex_pc_;
Sebastien Hertza76a6d42014-03-20 16:40:17 +0100130
131 // Indicates whether breakpoint needs full deoptimization or selective deoptimization.
Sebastien Hertzf3928792014-11-17 19:00:37 +0100132 DeoptimizationRequest::Kind deoptimization_kind_;
Elliott Hughes86964332012-02-15 19:37:42 -0800133};
134
Sebastien Hertzed2be172014-08-19 15:33:43 +0200135static std::ostream& operator<<(std::ostream& os, const Breakpoint& rhs)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700136 REQUIRES_SHARED(Locks::mutator_lock_) {
David Sehr709b0702016-10-13 09:12:37 -0700137 os << StringPrintf("Breakpoint[%s @%#x]", ArtMethod::PrettyMethod(rhs.Method()).c_str(),
138 rhs.DexPc());
Elliott Hughes86964332012-02-15 19:37:42 -0800139 return os;
140}
141
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100142class DebugInstrumentationListener final : public instrumentation::InstrumentationListener {
Ian Rogers62d6c772013-02-27 08:32:07 -0800143 public:
144 DebugInstrumentationListener() {}
145 virtual ~DebugInstrumentationListener() {}
146
Alex Lightd7661582017-05-01 13:48:16 -0700147 void MethodEntered(Thread* thread,
148 Handle<mirror::Object> this_object,
149 ArtMethod* method,
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200150 uint32_t dex_pc)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100151 override REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800152 if (method->IsNative()) {
153 // TODO: post location events is a suspension point and native method entry stubs aren't.
154 return;
155 }
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200156 if (IsListeningToDexPcMoved()) {
157 // We also listen to kDexPcMoved instrumentation event so we know the DexPcMoved method is
158 // going to be called right after us. To avoid sending JDWP events twice for this location,
159 // we report the event in DexPcMoved. However, we must remind this is method entry so we
160 // send the METHOD_ENTRY event. And we can also group it with other events for this location
161 // like BREAKPOINT or SINGLE_STEP (or even METHOD_EXIT if this is a RETURN instruction).
162 thread->SetDebugMethodEntry();
163 } else if (IsListeningToMethodExit() && IsReturn(method, dex_pc)) {
164 // We also listen to kMethodExited instrumentation event and the current instruction is a
165 // RETURN so we know the MethodExited method is going to be called right after us. To avoid
166 // sending JDWP events twice for this location, we report the event(s) in MethodExited.
167 // However, we must remind this is method entry so we send the METHOD_ENTRY event. And we can
168 // also group it with other events for this location like BREAKPOINT or SINGLE_STEP.
169 thread->SetDebugMethodEntry();
170 } else {
Alex Lightd7661582017-05-01 13:48:16 -0700171 Dbg::UpdateDebugger(thread, this_object.Get(), method, 0, Dbg::kMethodEntry, nullptr);
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200172 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800173 }
174
Alex Lightd7661582017-05-01 13:48:16 -0700175 void MethodExited(Thread* thread,
176 Handle<mirror::Object> this_object,
177 ArtMethod* method,
178 uint32_t dex_pc,
179 const JValue& return_value)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100180 override REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800181 if (method->IsNative()) {
182 // TODO: post location events is a suspension point and native method entry stubs aren't.
183 return;
184 }
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200185 uint32_t events = Dbg::kMethodExit;
186 if (thread->IsDebugMethodEntry()) {
187 // It is also the method entry.
188 DCHECK(IsReturn(method, dex_pc));
189 events |= Dbg::kMethodEntry;
190 thread->ClearDebugMethodEntry();
191 }
Alex Lightd7661582017-05-01 13:48:16 -0700192 Dbg::UpdateDebugger(thread, this_object.Get(), method, dex_pc, events, &return_value);
Ian Rogers62d6c772013-02-27 08:32:07 -0800193 }
194
Alex Lightd7661582017-05-01 13:48:16 -0700195 void MethodUnwind(Thread* thread ATTRIBUTE_UNUSED,
196 Handle<mirror::Object> this_object ATTRIBUTE_UNUSED,
197 ArtMethod* method,
198 uint32_t dex_pc)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100199 override REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800200 // We're not recorded to listen to this kind of event, so complain.
David Sehr709b0702016-10-13 09:12:37 -0700201 LOG(ERROR) << "Unexpected method unwind event in debugger " << ArtMethod::PrettyMethod(method)
Sebastien Hertz51db44a2013-11-19 10:00:29 +0100202 << " " << dex_pc;
Ian Rogers62d6c772013-02-27 08:32:07 -0800203 }
204
Alex Lightd7661582017-05-01 13:48:16 -0700205 void DexPcMoved(Thread* thread,
206 Handle<mirror::Object> this_object,
207 ArtMethod* method,
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200208 uint32_t new_dex_pc)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100209 override REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200210 if (IsListeningToMethodExit() && IsReturn(method, new_dex_pc)) {
211 // We also listen to kMethodExited instrumentation event and the current instruction is a
212 // RETURN so we know the MethodExited method is going to be called right after us. Like in
213 // MethodEntered, we delegate event reporting to MethodExited.
214 // Besides, if this RETURN instruction is the only one in the method, we can send multiple
215 // JDWP events in the same packet: METHOD_ENTRY, METHOD_EXIT, BREAKPOINT and/or SINGLE_STEP.
216 // Therefore, we must not clear the debug method entry flag here.
217 } else {
218 uint32_t events = 0;
219 if (thread->IsDebugMethodEntry()) {
220 // It is also the method entry.
221 events = Dbg::kMethodEntry;
222 thread->ClearDebugMethodEntry();
223 }
Alex Lightd7661582017-05-01 13:48:16 -0700224 Dbg::UpdateDebugger(thread, this_object.Get(), method, new_dex_pc, events, nullptr);
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200225 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800226 }
227
Alex Lightd7661582017-05-01 13:48:16 -0700228 void FieldRead(Thread* thread ATTRIBUTE_UNUSED,
229 Handle<mirror::Object> this_object,
230 ArtMethod* method,
231 uint32_t dex_pc,
232 ArtField* field)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100233 override REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Lightd7661582017-05-01 13:48:16 -0700234 Dbg::PostFieldAccessEvent(method, dex_pc, this_object.Get(), field);
Ian Rogers62d6c772013-02-27 08:32:07 -0800235 }
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200236
Alex Lightd7661582017-05-01 13:48:16 -0700237 void FieldWritten(Thread* thread ATTRIBUTE_UNUSED,
238 Handle<mirror::Object> this_object,
239 ArtMethod* method,
240 uint32_t dex_pc,
241 ArtField* field,
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700242 const JValue& field_value)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100243 override REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Lightd7661582017-05-01 13:48:16 -0700244 Dbg::PostFieldModificationEvent(method, dex_pc, this_object.Get(), field, &field_value);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200245 }
246
Alex Light6e1607e2017-08-23 10:06:18 -0700247 void ExceptionThrown(Thread* thread ATTRIBUTE_UNUSED,
Alex Lightd7661582017-05-01 13:48:16 -0700248 Handle<mirror::Throwable> exception_object)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100249 override REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Lightd7661582017-05-01 13:48:16 -0700250 Dbg::PostException(exception_object.Get());
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200251 }
252
Nicolas Geoffray81f0f952016-01-20 16:25:19 +0000253 // We only care about branches in the Jit.
254 void Branch(Thread* /*thread*/, ArtMethod* method, uint32_t dex_pc, int32_t dex_pc_offset)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100255 override REQUIRES_SHARED(Locks::mutator_lock_) {
David Sehr709b0702016-10-13 09:12:37 -0700256 LOG(ERROR) << "Unexpected branch event in debugger " << ArtMethod::PrettyMethod(method)
Nicolas Geoffray81f0f952016-01-20 16:25:19 +0000257 << " " << dex_pc << ", " << dex_pc_offset;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800258 }
259
Alex Light798eab02017-08-23 12:54:53 -0700260 // TODO Might be worth it to post ExceptionCatch event.
261 void ExceptionHandled(Thread* thread ATTRIBUTE_UNUSED,
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100262 Handle<mirror::Throwable> throwable ATTRIBUTE_UNUSED) override {
Alex Light798eab02017-08-23 12:54:53 -0700263 LOG(ERROR) << "Unexpected exception handled event in debugger";
264 }
265
Alex Light05f47742017-09-14 00:34:44 +0000266 // TODO Might be worth it to implement this.
267 void WatchedFramePop(Thread* thread ATTRIBUTE_UNUSED,
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100268 const ShadowFrame& frame ATTRIBUTE_UNUSED) override {
Alex Light05f47742017-09-14 00:34:44 +0000269 LOG(ERROR) << "Unexpected WatchedFramePop event in debugger";
270 }
Alex Light798eab02017-08-23 12:54:53 -0700271
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200272 private:
Mathieu Chartier808c7a52017-12-15 11:19:33 -0800273 static bool IsReturn(ArtMethod* method, uint32_t dex_pc) REQUIRES_SHARED(Locks::mutator_lock_) {
274 return method->DexInstructions().InstructionAt(dex_pc).IsReturn();
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200275 }
276
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700277 static bool IsListeningToDexPcMoved() REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200278 return IsListeningTo(instrumentation::Instrumentation::kDexPcMoved);
279 }
280
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700281 static bool IsListeningToMethodExit() REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200282 return IsListeningTo(instrumentation::Instrumentation::kMethodExited);
283 }
284
285 static bool IsListeningTo(instrumentation::Instrumentation::InstrumentationEvent event)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700286 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200287 return (Dbg::GetInstrumentationEvents() & event) != 0;
288 }
289
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200290 DISALLOW_COPY_AND_ASSIGN(DebugInstrumentationListener);
Ian Rogers62d6c772013-02-27 08:32:07 -0800291} gDebugInstrumentationListener;
292
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700293// JDWP is allowed unless the Zygote forbids it.
294static bool gJdwpAllowed = true;
295
Elliott Hughesc0f09332012-03-26 13:27:06 -0700296// Was there a -Xrunjdwp or -agentlib:jdwp= argument on the command line?
Elliott Hughes3bb81562011-10-21 18:52:59 -0700297static bool gJdwpConfigured = false;
298
Sebastien Hertzb3b173b2015-02-06 09:16:32 +0100299// JDWP options for debugging. Only valid if IsJdwpConfigured() is true.
300static JDWP::JdwpOptions gJdwpOptions;
301
Elliott Hughes3bb81562011-10-21 18:52:59 -0700302// Runtime JDWP state.
Ian Rogersc0542af2014-09-03 16:16:56 -0700303static JDWP::JdwpState* gJdwpState = nullptr;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700304static bool gDebuggerConnected; // debugger or DDMS is connected.
Elliott Hughes3bb81562011-10-21 18:52:59 -0700305
Elliott Hughes47fce012011-10-25 18:37:19 -0700306static bool gDdmThreadNotification = false;
307
Elliott Hughes767a1472011-10-26 18:49:02 -0700308// DDMS GC-related settings.
309static Dbg::HpifWhen gDdmHpifWhen = Dbg::HPIF_WHEN_NEVER;
310static Dbg::HpsgWhen gDdmHpsgWhen = Dbg::HPSG_WHEN_NEVER;
311static Dbg::HpsgWhat gDdmHpsgWhat;
312static Dbg::HpsgWhen gDdmNhsgWhen = Dbg::HPSG_WHEN_NEVER;
313static Dbg::HpsgWhat gDdmNhsgWhat;
314
Daniel Mihalyieb076692014-08-22 17:33:31 +0200315bool Dbg::gDebuggerActive = false;
Sebastien Hertz4e5b2082015-03-24 19:03:40 +0100316bool Dbg::gDisposed = false;
Sebastien Hertz6995c602014-09-09 12:10:13 +0200317ObjectRegistry* Dbg::gRegistry = nullptr;
Alex Light21611932017-09-26 13:07:39 -0700318DebuggerActiveMethodInspectionCallback Dbg::gDebugActiveCallback;
Alex Light8c2b9292017-11-09 13:21:01 -0800319DebuggerDdmCallback Dbg::gDebugDdmCallback;
Alex Light40320712017-12-14 11:52:04 -0800320InternalDebuggerControlCallback Dbg::gDebuggerControlCallback;
Elliott Hughes475fc232011-10-25 15:00:35 -0700321
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100322// Deoptimization support.
Sebastien Hertz4d25df32014-03-21 17:44:46 +0100323std::vector<DeoptimizationRequest> Dbg::deoptimization_requests_;
324size_t Dbg::full_deoptimization_event_count_ = 0;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100325
Sebastien Hertz42cd43f2014-05-13 14:15:41 +0200326// Instrumentation event reference counters.
327size_t Dbg::dex_pc_change_event_ref_count_ = 0;
328size_t Dbg::method_enter_event_ref_count_ = 0;
329size_t Dbg::method_exit_event_ref_count_ = 0;
330size_t Dbg::field_read_event_ref_count_ = 0;
331size_t Dbg::field_write_event_ref_count_ = 0;
332size_t Dbg::exception_catch_event_ref_count_ = 0;
333uint32_t Dbg::instrumentation_events_ = 0;
334
Andreas Gampe04bbb5b2017-01-19 17:49:03 +0000335Dbg::DbgThreadLifecycleCallback Dbg::thread_lifecycle_callback_;
Andreas Gampe0f01b582017-01-18 15:22:37 -0800336Dbg::DbgClassLoadCallback Dbg::class_load_callback_;
Andreas Gampe04bbb5b2017-01-19 17:49:03 +0000337
Alex Light8c2b9292017-11-09 13:21:01 -0800338void DebuggerDdmCallback::DdmPublishChunk(uint32_t type, const ArrayRef<const uint8_t>& data) {
Alex Light772099a2017-11-21 14:05:04 -0800339 if (gJdwpState == nullptr) {
340 VLOG(jdwp) << "Debugger thread not active, ignoring DDM send: " << type;
341 } else {
342 iovec vec[1];
343 vec[0].iov_base = reinterpret_cast<void*>(const_cast<uint8_t*>(data.data()));
344 vec[0].iov_len = data.size();
345 gJdwpState->DdmSendChunkV(type, vec, 1);
346 }
Alex Light8c2b9292017-11-09 13:21:01 -0800347}
348
Alex Light21611932017-09-26 13:07:39 -0700349bool DebuggerActiveMethodInspectionCallback::IsMethodBeingInspected(ArtMethod* m ATTRIBUTE_UNUSED) {
350 return Dbg::IsDebuggerActive();
351}
352
Alex Light0fa17862017-10-24 13:43:05 -0700353bool DebuggerActiveMethodInspectionCallback::IsMethodSafeToJit(ArtMethod* m) {
354 return !Dbg::MethodHasAnyBreakpoints(m);
355}
356
Alex Lightf2858632018-04-02 11:28:50 -0700357bool DebuggerActiveMethodInspectionCallback::MethodNeedsDebugVersion(
358 ArtMethod* m ATTRIBUTE_UNUSED) {
359 return Dbg::IsDebuggerActive();
360}
361
Alex Light40320712017-12-14 11:52:04 -0800362void InternalDebuggerControlCallback::StartDebugger() {
363 // Release the mutator lock.
364 ScopedThreadStateChange stsc(art::Thread::Current(), kNative);
365 Dbg::StartJdwp();
366}
367
368void InternalDebuggerControlCallback::StopDebugger() {
369 Dbg::StopJdwp();
370}
371
372bool InternalDebuggerControlCallback::IsDebuggerConfigured() {
373 return Dbg::IsJdwpConfigured();
374}
375
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100376// Breakpoints.
jeffhao09bfc6a2012-12-11 18:11:43 -0800377static std::vector<Breakpoint> gBreakpoints GUARDED_BY(Locks::breakpoint_lock_);
Elliott Hughes86964332012-02-15 19:37:42 -0800378
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700379void DebugInvokeReq::VisitRoots(RootVisitor* visitor, const RootInfo& root_info) {
380 receiver.VisitRootIfNonNull(visitor, root_info); // null for static method call.
381 klass.VisitRoot(visitor, root_info);
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700382}
383
Sebastien Hertz597c4f02015-01-26 17:37:14 +0100384void SingleStepControl::AddDexPc(uint32_t dex_pc) {
385 dex_pcs_.insert(dex_pc);
Sebastien Hertzbb43b432014-04-14 11:59:08 +0200386}
387
Sebastien Hertz597c4f02015-01-26 17:37:14 +0100388bool SingleStepControl::ContainsDexPc(uint32_t dex_pc) const {
389 return dex_pcs_.find(dex_pc) == dex_pcs_.end();
Sebastien Hertzbb43b432014-04-14 11:59:08 +0200390}
391
Alex Light6c8467f2015-11-20 15:03:26 -0800392static bool IsBreakpoint(ArtMethod* m, uint32_t dex_pc)
Mathieu Chartier90443472015-07-16 20:32:27 -0700393 REQUIRES(!Locks::breakpoint_lock_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700394 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertzed2be172014-08-19 15:33:43 +0200395 ReaderMutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100396 for (size_t i = 0, e = gBreakpoints.size(); i < e; ++i) {
Alex Light6c8467f2015-11-20 15:03:26 -0800397 if (gBreakpoints[i].DexPc() == dex_pc && gBreakpoints[i].IsInMethod(m)) {
Elliott Hughes86964332012-02-15 19:37:42 -0800398 VLOG(jdwp) << "Hit breakpoint #" << i << ": " << gBreakpoints[i];
399 return true;
400 }
401 }
402 return false;
403}
404
Sebastien Hertz52d131d2014-03-13 16:17:40 +0100405static bool IsSuspendedForDebugger(ScopedObjectAccessUnchecked& soa, Thread* thread)
Mathieu Chartier90443472015-07-16 20:32:27 -0700406 REQUIRES(!Locks::thread_suspend_count_lock_) {
Elliott Hughes9e0c1752013-01-09 14:02:58 -0800407 MutexLock mu(soa.Self(), *Locks::thread_suspend_count_lock_);
408 // A thread may be suspended for GC; in this code, we really want to know whether
409 // there's a debugger suspension active.
410 return thread->IsSuspended() && thread->GetDebugSuspendCount() > 0;
411}
412
Ian Rogersc0542af2014-09-03 16:16:56 -0700413static mirror::Array* DecodeNonNullArray(JDWP::RefTypeId id, JDWP::JdwpError* error)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700414 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz6995c602014-09-09 12:10:13 +0200415 mirror::Object* o = Dbg::GetObjectRegistry()->Get<mirror::Object*>(id, error);
Ian Rogersc0542af2014-09-03 16:16:56 -0700416 if (o == nullptr) {
417 *error = JDWP::ERR_INVALID_OBJECT;
418 return nullptr;
Elliott Hughes436e3722012-02-17 20:01:47 -0800419 }
420 if (!o->IsArrayInstance()) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700421 *error = JDWP::ERR_INVALID_ARRAY;
422 return nullptr;
Elliott Hughes436e3722012-02-17 20:01:47 -0800423 }
Ian Rogersc0542af2014-09-03 16:16:56 -0700424 *error = JDWP::ERR_NONE;
Elliott Hughes436e3722012-02-17 20:01:47 -0800425 return o->AsArray();
426}
427
Ian Rogersc0542af2014-09-03 16:16:56 -0700428static mirror::Class* DecodeClass(JDWP::RefTypeId id, JDWP::JdwpError* error)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700429 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz6995c602014-09-09 12:10:13 +0200430 mirror::Object* o = Dbg::GetObjectRegistry()->Get<mirror::Object*>(id, error);
Ian Rogersc0542af2014-09-03 16:16:56 -0700431 if (o == nullptr) {
432 *error = JDWP::ERR_INVALID_OBJECT;
433 return nullptr;
Elliott Hughes436e3722012-02-17 20:01:47 -0800434 }
435 if (!o->IsClass()) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700436 *error = JDWP::ERR_INVALID_CLASS;
437 return nullptr;
Elliott Hughes436e3722012-02-17 20:01:47 -0800438 }
Ian Rogersc0542af2014-09-03 16:16:56 -0700439 *error = JDWP::ERR_NONE;
Elliott Hughes436e3722012-02-17 20:01:47 -0800440 return o->AsClass();
441}
442
Ian Rogersc0542af2014-09-03 16:16:56 -0700443static Thread* DecodeThread(ScopedObjectAccessUnchecked& soa, JDWP::ObjectId thread_id,
444 JDWP::JdwpError* error)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700445 REQUIRES_SHARED(Locks::mutator_lock_)
Mathieu Chartier90443472015-07-16 20:32:27 -0700446 REQUIRES(!Locks::thread_list_lock_, !Locks::thread_suspend_count_lock_) {
Sebastien Hertz6995c602014-09-09 12:10:13 +0200447 mirror::Object* thread_peer = Dbg::GetObjectRegistry()->Get<mirror::Object*>(thread_id, error);
Ian Rogersc0542af2014-09-03 16:16:56 -0700448 if (thread_peer == nullptr) {
Elliott Hughes221229c2013-01-08 18:17:50 -0800449 // This isn't even an object.
Ian Rogersc0542af2014-09-03 16:16:56 -0700450 *error = JDWP::ERR_INVALID_OBJECT;
451 return nullptr;
Elliott Hughes436e3722012-02-17 20:01:47 -0800452 }
Elliott Hughes221229c2013-01-08 18:17:50 -0800453
Mathieu Chartier0795f232016-09-27 18:43:30 -0700454 ObjPtr<mirror::Class> java_lang_Thread =
455 soa.Decode<mirror::Class>(WellKnownClasses::java_lang_Thread);
Elliott Hughes221229c2013-01-08 18:17:50 -0800456 if (!java_lang_Thread->IsAssignableFrom(thread_peer->GetClass())) {
457 // This isn't a thread.
Ian Rogersc0542af2014-09-03 16:16:56 -0700458 *error = JDWP::ERR_INVALID_THREAD;
459 return nullptr;
Elliott Hughes221229c2013-01-08 18:17:50 -0800460 }
461
Sebastien Hertz69206392015-04-07 15:54:25 +0200462 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogersc0542af2014-09-03 16:16:56 -0700463 Thread* thread = Thread::FromManagedThread(soa, thread_peer);
464 // If thread is null then this a java.lang.Thread without a Thread*. Must be a un-started or a
465 // zombie.
466 *error = (thread == nullptr) ? JDWP::ERR_THREAD_NOT_ALIVE : JDWP::ERR_NONE;
467 return thread;
Elliott Hughes436e3722012-02-17 20:01:47 -0800468}
469
Elliott Hughes24437992011-11-30 14:49:33 -0800470static JDWP::JdwpTag BasicTagFromDescriptor(const char* descriptor) {
471 // JDWP deliberately uses the descriptor characters' ASCII values for its enum.
472 // Note that by "basic" we mean that we don't get more specific than JT_OBJECT.
473 return static_cast<JDWP::JdwpTag>(descriptor[0]);
474}
475
Ian Rogers1ff3c982014-08-12 02:30:58 -0700476static JDWP::JdwpTag BasicTagFromClass(mirror::Class* klass)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700477 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers1ff3c982014-08-12 02:30:58 -0700478 std::string temp;
479 const char* descriptor = klass->GetDescriptor(&temp);
480 return BasicTagFromDescriptor(descriptor);
481}
482
Ian Rogers98379392014-02-24 16:53:16 -0800483static JDWP::JdwpTag TagFromClass(const ScopedObjectAccessUnchecked& soa, mirror::Class* c)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700484 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700485 CHECK(c != nullptr);
Elliott Hughes24437992011-11-30 14:49:33 -0800486 if (c->IsArrayClass()) {
487 return JDWP::JT_ARRAY;
488 }
Elliott Hughes24437992011-11-30 14:49:33 -0800489 if (c->IsStringClass()) {
490 return JDWP::JT_STRING;
Elliott Hughes24437992011-11-30 14:49:33 -0800491 }
Ian Rogers98379392014-02-24 16:53:16 -0800492 if (c->IsClassClass()) {
493 return JDWP::JT_CLASS_OBJECT;
494 }
495 {
Mathieu Chartier0795f232016-09-27 18:43:30 -0700496 ObjPtr<mirror::Class> thread_class =
497 soa.Decode<mirror::Class>(WellKnownClasses::java_lang_Thread);
Ian Rogers98379392014-02-24 16:53:16 -0800498 if (thread_class->IsAssignableFrom(c)) {
499 return JDWP::JT_THREAD;
500 }
501 }
502 {
Mathieu Chartier0795f232016-09-27 18:43:30 -0700503 ObjPtr<mirror::Class> thread_group_class =
504 soa.Decode<mirror::Class>(WellKnownClasses::java_lang_ThreadGroup);
Ian Rogers98379392014-02-24 16:53:16 -0800505 if (thread_group_class->IsAssignableFrom(c)) {
506 return JDWP::JT_THREAD_GROUP;
507 }
508 }
509 {
Mathieu Chartier0795f232016-09-27 18:43:30 -0700510 ObjPtr<mirror::Class> class_loader_class =
511 soa.Decode<mirror::Class>(WellKnownClasses::java_lang_ClassLoader);
Ian Rogers98379392014-02-24 16:53:16 -0800512 if (class_loader_class->IsAssignableFrom(c)) {
513 return JDWP::JT_CLASS_LOADER;
514 }
515 }
516 return JDWP::JT_OBJECT;
Elliott Hughes24437992011-11-30 14:49:33 -0800517}
518
519/*
520 * Objects declared to hold Object might actually hold a more specific
521 * type. The debugger may take a special interest in these (e.g. it
522 * wants to display the contents of Strings), so we want to return an
523 * appropriate tag.
524 *
525 * Null objects are tagged JT_OBJECT.
526 */
Sebastien Hertz6995c602014-09-09 12:10:13 +0200527JDWP::JdwpTag Dbg::TagFromObject(const ScopedObjectAccessUnchecked& soa, mirror::Object* o) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700528 return (o == nullptr) ? JDWP::JT_OBJECT : TagFromClass(soa, o->GetClass());
Elliott Hughes24437992011-11-30 14:49:33 -0800529}
530
531static bool IsPrimitiveTag(JDWP::JdwpTag tag) {
532 switch (tag) {
533 case JDWP::JT_BOOLEAN:
534 case JDWP::JT_BYTE:
535 case JDWP::JT_CHAR:
536 case JDWP::JT_FLOAT:
537 case JDWP::JT_DOUBLE:
538 case JDWP::JT_INT:
539 case JDWP::JT_LONG:
540 case JDWP::JT_SHORT:
541 case JDWP::JT_VOID:
542 return true;
543 default:
544 return false;
545 }
546}
547
Sebastien Hertzb3b173b2015-02-06 09:16:32 +0100548void Dbg::StartJdwp() {
Elliott Hughesc0f09332012-03-26 13:27:06 -0700549 if (!gJdwpAllowed || !IsJdwpConfigured()) {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700550 // No JDWP for you!
551 return;
552 }
553
Ian Rogers719d1a32014-03-06 12:13:39 -0800554 CHECK(gRegistry == nullptr);
Elliott Hughes475fc232011-10-25 15:00:35 -0700555 gRegistry = new ObjectRegistry;
556
Alex Light8c2b9292017-11-09 13:21:01 -0800557 {
558 // Setup the Ddm listener
559 ScopedObjectAccess soa(Thread::Current());
560 Runtime::Current()->GetRuntimeCallbacks()->AddDdmCallback(&gDebugDdmCallback);
561 }
562
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700563 // Init JDWP if the debugger is enabled. This may connect out to a
564 // debugger, passively listen for a debugger, or block waiting for a
565 // debugger.
Sebastien Hertzb3b173b2015-02-06 09:16:32 +0100566 gJdwpState = JDWP::JdwpState::Create(&gJdwpOptions);
Ian Rogersc0542af2014-09-03 16:16:56 -0700567 if (gJdwpState == nullptr) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -0800568 // We probably failed because some other process has the port already, which means that
569 // if we don't abort the user is likely to think they're talking to us when they're actually
570 // talking to that other process.
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800571 LOG(FATAL) << "Debugger thread failed to initialize";
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700572 }
573
574 // If a debugger has already attached, send the "welcome" message.
575 // This may cause us to suspend all threads.
Elliott Hughes376a7a02011-10-24 18:35:55 -0700576 if (gJdwpState->IsActive()) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700577 ScopedObjectAccess soa(Thread::Current());
Sebastien Hertz7d955652014-10-22 10:57:10 +0200578 gJdwpState->PostVMStart();
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700579 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700580}
581
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700582void Dbg::StopJdwp() {
Sebastien Hertzc6345ef2014-08-18 19:26:39 +0200583 // Post VM_DEATH event before the JDWP connection is closed (either by the JDWP thread or the
584 // destruction of gJdwpState).
585 if (gJdwpState != nullptr && gJdwpState->IsActive()) {
586 gJdwpState->PostVMDeath();
587 }
Sebastien Hertz0376e6b2014-02-06 18:12:59 +0100588 // Prevent the JDWP thread from processing JDWP incoming packets after we close the connection.
Sebastien Hertz4e5b2082015-03-24 19:03:40 +0100589 Dispose();
Elliott Hughes376a7a02011-10-24 18:35:55 -0700590 delete gJdwpState;
Ian Rogers719d1a32014-03-06 12:13:39 -0800591 gJdwpState = nullptr;
Elliott Hughes475fc232011-10-25 15:00:35 -0700592 delete gRegistry;
Ian Rogers719d1a32014-03-06 12:13:39 -0800593 gRegistry = nullptr;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700594}
595
Elliott Hughes767a1472011-10-26 18:49:02 -0700596void Dbg::GcDidFinish() {
597 if (gDdmHpifWhen != HPIF_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700598 ScopedObjectAccess soa(Thread::Current());
Brian Carlstrom4d466a82014-05-08 19:05:29 -0700599 VLOG(jdwp) << "Sending heap info to DDM";
Elliott Hughes7162ad92011-10-27 14:08:42 -0700600 DdmSendHeapInfo(gDdmHpifWhen);
Elliott Hughes767a1472011-10-26 18:49:02 -0700601 }
602 if (gDdmHpsgWhen != HPSG_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700603 ScopedObjectAccess soa(Thread::Current());
Brian Carlstrom4d466a82014-05-08 19:05:29 -0700604 VLOG(jdwp) << "Dumping heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700605 DdmSendHeapSegments(false);
Elliott Hughes767a1472011-10-26 18:49:02 -0700606 }
607 if (gDdmNhsgWhen != HPSG_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700608 ScopedObjectAccess soa(Thread::Current());
Brian Carlstrom4d466a82014-05-08 19:05:29 -0700609 VLOG(jdwp) << "Dumping native heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700610 DdmSendHeapSegments(true);
Elliott Hughes767a1472011-10-26 18:49:02 -0700611 }
612}
613
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700614void Dbg::SetJdwpAllowed(bool allowed) {
615 gJdwpAllowed = allowed;
616}
617
Leonard Mosescueb842212016-10-06 17:26:36 -0700618bool Dbg::IsJdwpAllowed() {
619 return gJdwpAllowed;
620}
621
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700622DebugInvokeReq* Dbg::GetInvokeReq() {
Elliott Hughes475fc232011-10-25 15:00:35 -0700623 return Thread::Current()->GetInvokeReq();
624}
625
626Thread* Dbg::GetDebugThread() {
Ian Rogersc0542af2014-09-03 16:16:56 -0700627 return (gJdwpState != nullptr) ? gJdwpState->GetDebugThread() : nullptr;
Elliott Hughes475fc232011-10-25 15:00:35 -0700628}
629
630void Dbg::ClearWaitForEventThread() {
Sebastien Hertz2bf93f42015-01-09 18:44:05 +0100631 gJdwpState->ReleaseJdwpTokenForEvent();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700632}
633
634void Dbg::Connected() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700635 CHECK(!gDebuggerConnected);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800636 VLOG(jdwp) << "JDWP has attached";
Elliott Hughes3bb81562011-10-21 18:52:59 -0700637 gDebuggerConnected = true;
Elliott Hughes86964332012-02-15 19:37:42 -0800638 gDisposed = false;
639}
640
Sebastien Hertzf3928792014-11-17 19:00:37 +0100641bool Dbg::RequiresDeoptimization() {
642 // We don't need deoptimization if everything runs with interpreter after
643 // enabling -Xint mode.
644 return !Runtime::Current()->GetInstrumentation()->IsForcedInterpretOnly();
645}
646
Elliott Hughesa2155262011-11-16 16:26:58 -0800647void Dbg::GoActive() {
648 // Enable all debugging features, including scans for breakpoints.
649 // This is a no-op if we're already active.
650 // Only called from the JDWP handler thread.
Daniel Mihalyieb076692014-08-22 17:33:31 +0200651 if (IsDebuggerActive()) {
Elliott Hughesa2155262011-11-16 16:26:58 -0800652 return;
653 }
654
Mathieu Chartieraa516822015-10-02 15:53:37 -0700655 Thread* const self = Thread::Current();
Elliott Hughesc0f09332012-03-26 13:27:06 -0700656 {
657 // TODO: dalvik only warned if there were breakpoints left over. clear in Dbg::Disconnected?
Mathieu Chartieraa516822015-10-02 15:53:37 -0700658 ReaderMutexLock mu(self, *Locks::breakpoint_lock_);
Elliott Hughesc0f09332012-03-26 13:27:06 -0700659 CHECK_EQ(gBreakpoints.size(), 0U);
660 }
Elliott Hughesa2155262011-11-16 16:26:58 -0800661
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100662 {
Mathieu Chartieraa516822015-10-02 15:53:37 -0700663 MutexLock mu(self, *Locks::deoptimization_lock_);
Sebastien Hertz4d25df32014-03-21 17:44:46 +0100664 CHECK_EQ(deoptimization_requests_.size(), 0U);
665 CHECK_EQ(full_deoptimization_event_count_, 0U);
Sebastien Hertz42cd43f2014-05-13 14:15:41 +0200666 CHECK_EQ(dex_pc_change_event_ref_count_, 0U);
667 CHECK_EQ(method_enter_event_ref_count_, 0U);
668 CHECK_EQ(method_exit_event_ref_count_, 0U);
669 CHECK_EQ(field_read_event_ref_count_, 0U);
670 CHECK_EQ(field_write_event_ref_count_, 0U);
671 CHECK_EQ(exception_catch_event_ref_count_, 0U);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100672 }
673
Ian Rogers62d6c772013-02-27 08:32:07 -0800674 Runtime* runtime = Runtime::Current();
Nicolas Geoffray433b79a2017-01-30 20:54:45 +0000675 // Best effort deoptimization if the runtime is non-Java debuggable. This happens when
676 // ro.debuggable is set, but the application is not debuggable, or when a standalone
677 // dalvikvm invocation is not passed the debuggable option (-Xcompiler-option --debuggable).
678 //
679 // The performance cost of this is non-negligible during native-debugging due to the
David Srbeckyf4480162016-03-16 00:06:24 +0000680 // forced JIT, so we keep the AOT code in that case in exchange for limited native debugging.
Nicolas Geoffray433b79a2017-01-30 20:54:45 +0000681 if (!runtime->IsJavaDebuggable() &&
682 !runtime->GetInstrumentation()->IsForcedInterpretOnly() &&
683 !runtime->IsNativeDebuggable()) {
684 runtime->DeoptimizeBootImage();
Mingyao Yang6ea1a0e2016-01-29 12:12:49 -0800685 }
686
Mathieu Chartier4f55e222015-09-04 13:26:21 -0700687 ScopedSuspendAll ssa(__FUNCTION__);
Sebastien Hertzf3928792014-11-17 19:00:37 +0100688 if (RequiresDeoptimization()) {
689 runtime->GetInstrumentation()->EnableDeoptimization();
690 }
Sebastien Hertz42cd43f2014-05-13 14:15:41 +0200691 instrumentation_events_ = 0;
David Srbecky28f6cff2018-10-16 15:07:28 +0100692 Runtime::DoAndMaybeSwitchInterpreter([=](){ gDebuggerActive = true; });
Alex Light21611932017-09-26 13:07:39 -0700693 Runtime::Current()->GetRuntimeCallbacks()->AddMethodInspectionCallback(&gDebugActiveCallback);
Ian Rogers62d6c772013-02-27 08:32:07 -0800694 LOG(INFO) << "Debugger is active";
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700695}
696
697void Dbg::Disconnected() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700698 CHECK(gDebuggerConnected);
699
Elliott Hughesc0f09332012-03-26 13:27:06 -0700700 LOG(INFO) << "Debugger is no longer active";
Elliott Hughes234ab152011-10-26 14:02:26 -0700701
Hiroshi Yamauchi98810e32016-05-24 14:55:40 -0700702 // Suspend all threads and exclusively acquire the mutator lock. Remove the debugger as a listener
Ian Rogers62d6c772013-02-27 08:32:07 -0800703 // and clear the object registry.
704 Runtime* runtime = Runtime::Current();
Ian Rogers62d6c772013-02-27 08:32:07 -0800705 Thread* self = Thread::Current();
Mathieu Chartier4f55e222015-09-04 13:26:21 -0700706 {
Mathieu Chartieraa516822015-10-02 15:53:37 -0700707 // Required for DisableDeoptimization.
708 gc::ScopedGCCriticalSection gcs(self,
709 gc::kGcCauseInstrumentation,
710 gc::kCollectorTypeInstrumentation);
Mathieu Chartier4f55e222015-09-04 13:26:21 -0700711 ScopedSuspendAll ssa(__FUNCTION__);
Mathieu Chartier4f55e222015-09-04 13:26:21 -0700712 // Debugger may not be active at this point.
713 if (IsDebuggerActive()) {
714 {
715 // Since we're going to disable deoptimization, we clear the deoptimization requests queue.
716 // This prevents us from having any pending deoptimization request when the debugger attaches
717 // to us again while no event has been requested yet.
Mathieu Chartiera6b1ead2015-10-06 10:32:38 -0700718 MutexLock mu(self, *Locks::deoptimization_lock_);
Mathieu Chartier4f55e222015-09-04 13:26:21 -0700719 deoptimization_requests_.clear();
720 full_deoptimization_event_count_ = 0U;
721 }
722 if (instrumentation_events_ != 0) {
723 runtime->GetInstrumentation()->RemoveListener(&gDebugInstrumentationListener,
724 instrumentation_events_);
725 instrumentation_events_ = 0;
726 }
727 if (RequiresDeoptimization()) {
728 runtime->GetInstrumentation()->DisableDeoptimization(kDbgInstrumentationKey);
729 }
David Srbecky28f6cff2018-10-16 15:07:28 +0100730 Runtime::DoAndMaybeSwitchInterpreter([=](){ gDebuggerActive = false; });
Alex Light21611932017-09-26 13:07:39 -0700731 Runtime::Current()->GetRuntimeCallbacks()->RemoveMethodInspectionCallback(
732 &gDebugActiveCallback);
Sebastien Hertzaaea7342014-02-25 15:10:04 +0100733 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100734 }
Sebastien Hertz55f65342015-01-13 22:48:34 +0100735
736 {
737 ScopedObjectAccess soa(self);
738 gRegistry->Clear();
739 }
740
741 gDebuggerConnected = false;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700742}
743
Sebastien Hertzb3b173b2015-02-06 09:16:32 +0100744void Dbg::ConfigureJdwp(const JDWP::JdwpOptions& jdwp_options) {
745 CHECK_NE(jdwp_options.transport, JDWP::kJdwpTransportUnknown);
746 gJdwpOptions = jdwp_options;
747 gJdwpConfigured = true;
Alex Light40320712017-12-14 11:52:04 -0800748 Runtime::Current()->GetRuntimeCallbacks()->AddDebuggerControlCallback(&gDebuggerControlCallback);
Sebastien Hertzb3b173b2015-02-06 09:16:32 +0100749}
750
Elliott Hughesc0f09332012-03-26 13:27:06 -0700751bool Dbg::IsJdwpConfigured() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700752 return gJdwpConfigured;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700753}
754
755int64_t Dbg::LastDebuggerActivity() {
Elliott Hughesca951522011-12-05 12:01:32 -0800756 return gJdwpState->LastDebuggerActivity();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700757}
758
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700759void Dbg::UndoDebuggerSuspensions() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700760 Runtime::Current()->GetThreadList()->UndoDebuggerSuspensions();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700761}
762
Elliott Hughes88d63092013-01-09 09:55:54 -0800763std::string Dbg::GetClassName(JDWP::RefTypeId class_id) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700764 JDWP::JdwpError error;
765 mirror::Object* o = gRegistry->Get<mirror::Object*>(class_id, &error);
766 if (o == nullptr) {
767 if (error == JDWP::ERR_NONE) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700768 return "null";
Ian Rogersc0542af2014-09-03 16:16:56 -0700769 } else {
770 return StringPrintf("invalid object %p", reinterpret_cast<void*>(class_id));
771 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800772 }
773 if (!o->IsClass()) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700774 return StringPrintf("non-class %p", o); // This is only used for debugging output anyway.
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800775 }
Sebastien Hertz6995c602014-09-09 12:10:13 +0200776 return GetClassName(o->AsClass());
777}
778
779std::string Dbg::GetClassName(mirror::Class* klass) {
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +0200780 if (klass == nullptr) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700781 return "null";
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +0200782 }
Ian Rogers1ff3c982014-08-12 02:30:58 -0700783 std::string temp;
Sebastien Hertz6995c602014-09-09 12:10:13 +0200784 return DescriptorToName(klass->GetDescriptor(&temp));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700785}
786
Ian Rogersc0542af2014-09-03 16:16:56 -0700787JDWP::JdwpError Dbg::GetClassObject(JDWP::RefTypeId id, JDWP::ObjectId* class_object_id) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800788 JDWP::JdwpError status;
Ian Rogersc0542af2014-09-03 16:16:56 -0700789 mirror::Class* c = DecodeClass(id, &status);
790 if (c == nullptr) {
791 *class_object_id = 0;
Elliott Hughes436e3722012-02-17 20:01:47 -0800792 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800793 }
Ian Rogersc0542af2014-09-03 16:16:56 -0700794 *class_object_id = gRegistry->Add(c);
Elliott Hughes436e3722012-02-17 20:01:47 -0800795 return JDWP::ERR_NONE;
Elliott Hughes86964332012-02-15 19:37:42 -0800796}
797
Ian Rogersc0542af2014-09-03 16:16:56 -0700798JDWP::JdwpError Dbg::GetSuperclass(JDWP::RefTypeId id, JDWP::RefTypeId* superclass_id) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800799 JDWP::JdwpError status;
Ian Rogersc0542af2014-09-03 16:16:56 -0700800 mirror::Class* c = DecodeClass(id, &status);
801 if (c == nullptr) {
802 *superclass_id = 0;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800803 return status;
804 }
805 if (c->IsInterface()) {
806 // http://code.google.com/p/android/issues/detail?id=20856
Ian Rogersc0542af2014-09-03 16:16:56 -0700807 *superclass_id = 0;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800808 } else {
Ian Rogersc0542af2014-09-03 16:16:56 -0700809 *superclass_id = gRegistry->Add(c->GetSuperClass());
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800810 }
811 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700812}
813
Elliott Hughes436e3722012-02-17 20:01:47 -0800814JDWP::JdwpError Dbg::GetClassLoader(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700815 JDWP::JdwpError error;
Andreas Gampe7929a482015-12-30 19:33:49 -0800816 mirror::Class* c = DecodeClass(id, &error);
817 if (c == nullptr) {
818 return error;
Elliott Hughes436e3722012-02-17 20:01:47 -0800819 }
Andreas Gampe7929a482015-12-30 19:33:49 -0800820 expandBufAddObjectId(pReply, gRegistry->Add(c->GetClassLoader()));
Elliott Hughes436e3722012-02-17 20:01:47 -0800821 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700822}
823
Elliott Hughes436e3722012-02-17 20:01:47 -0800824JDWP::JdwpError Dbg::GetModifiers(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700825 JDWP::JdwpError error;
826 mirror::Class* c = DecodeClass(id, &error);
827 if (c == nullptr) {
828 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800829 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800830
831 uint32_t access_flags = c->GetAccessFlags() & kAccJavaFlagsMask;
832
Yevgeny Roubande34eea2014-02-15 01:06:03 +0700833 // Set ACC_SUPER. Dex files don't contain this flag but only classes are supposed to have it set,
834 // not interfaces.
Elliott Hughes436e3722012-02-17 20:01:47 -0800835 // Class.getModifiers doesn't return it, but JDWP does, so we set it here.
Yevgeny Roubande34eea2014-02-15 01:06:03 +0700836 if ((access_flags & kAccInterface) == 0) {
837 access_flags |= kAccSuper;
838 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800839
840 expandBufAdd4BE(pReply, access_flags);
841
842 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700843}
844
Ian Rogersc0542af2014-09-03 16:16:56 -0700845JDWP::JdwpError Dbg::GetMonitorInfo(JDWP::ObjectId object_id, JDWP::ExpandBuf* reply) {
846 JDWP::JdwpError error;
847 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
848 if (o == nullptr) {
Elliott Hughesf327e072013-01-09 16:01:26 -0800849 return JDWP::ERR_INVALID_OBJECT;
850 }
851
852 // Ensure all threads are suspended while we read objects' lock words.
853 Thread* self = Thread::Current();
Sebastien Hertz54263242014-03-19 18:16:50 +0100854 CHECK_EQ(self->GetState(), kRunnable);
Elliott Hughesf327e072013-01-09 16:01:26 -0800855
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700856 MonitorInfo monitor_info;
857 {
858 ScopedThreadSuspension sts(self, kSuspended);
Mathieu Chartier4f55e222015-09-04 13:26:21 -0700859 ScopedSuspendAll ssa(__FUNCTION__);
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700860 monitor_info = MonitorInfo(o);
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700861 }
Ian Rogersc0542af2014-09-03 16:16:56 -0700862 if (monitor_info.owner_ != nullptr) {
Nicolas Geoffraycafa0812017-02-15 18:27:34 +0000863 expandBufAddObjectId(reply, gRegistry->Add(monitor_info.owner_->GetPeerFromOtherThread()));
Elliott Hughesf327e072013-01-09 16:01:26 -0800864 } else {
Ian Rogersc0542af2014-09-03 16:16:56 -0700865 expandBufAddObjectId(reply, gRegistry->Add(nullptr));
Elliott Hughesf327e072013-01-09 16:01:26 -0800866 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700867 expandBufAdd4BE(reply, monitor_info.entry_count_);
868 expandBufAdd4BE(reply, monitor_info.waiters_.size());
869 for (size_t i = 0; i < monitor_info.waiters_.size(); ++i) {
Nicolas Geoffraycafa0812017-02-15 18:27:34 +0000870 expandBufAddObjectId(reply, gRegistry->Add(monitor_info.waiters_[i]->GetPeerFromOtherThread()));
Elliott Hughesf327e072013-01-09 16:01:26 -0800871 }
872 return JDWP::ERR_NONE;
873}
874
Elliott Hughes734b8c62013-01-11 15:32:45 -0800875JDWP::JdwpError Dbg::GetOwnedMonitors(JDWP::ObjectId thread_id,
Ian Rogersc0542af2014-09-03 16:16:56 -0700876 std::vector<JDWP::ObjectId>* monitors,
877 std::vector<uint32_t>* stack_depths) {
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800878 struct OwnedMonitorVisitor : public StackVisitor {
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700879 OwnedMonitorVisitor(Thread* thread, Context* context,
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -0700880 std::vector<JDWP::ObjectId>* monitor_vector,
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700881 std::vector<uint32_t>* stack_depth_vector)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700882 REQUIRES_SHARED(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +0100883 : StackVisitor(thread, context, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
884 current_stack_depth(0),
885 monitors(monitor_vector),
886 stack_depths(stack_depth_vector) {}
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800887
888 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
889 // annotalysis.
Andreas Gampefa6a1b02018-09-07 08:11:55 -0700890 bool VisitFrame() override NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800891 if (!GetMethod()->IsRuntimeMethod()) {
892 Monitor::VisitLocks(this, AppendOwnedMonitors, this);
Elliott Hughes734b8c62013-01-11 15:32:45 -0800893 ++current_stack_depth;
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800894 }
895 return true;
896 }
897
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -0700898 static void AppendOwnedMonitors(mirror::Object* owned_monitor, void* arg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700899 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers7a22fa62013-01-23 12:16:16 -0800900 OwnedMonitorVisitor* visitor = reinterpret_cast<OwnedMonitorVisitor*>(arg);
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -0700901 visitor->monitors->push_back(gRegistry->Add(owned_monitor));
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700902 visitor->stack_depths->push_back(visitor->current_stack_depth);
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800903 }
904
Elliott Hughes734b8c62013-01-11 15:32:45 -0800905 size_t current_stack_depth;
Ian Rogersc0542af2014-09-03 16:16:56 -0700906 std::vector<JDWP::ObjectId>* const monitors;
907 std::vector<uint32_t>* const stack_depths;
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800908 };
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800909
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700910 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz69206392015-04-07 15:54:25 +0200911 JDWP::JdwpError error;
912 Thread* thread = DecodeThread(soa, thread_id, &error);
913 if (thread == nullptr) {
914 return error;
915 }
916 if (!IsSuspendedForDebugger(soa, thread)) {
917 return JDWP::ERR_THREAD_NOT_SUSPENDED;
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700918 }
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -0700919 std::unique_ptr<Context> context(Context::Create());
Ian Rogersc0542af2014-09-03 16:16:56 -0700920 OwnedMonitorVisitor visitor(thread, context.get(), monitors, stack_depths);
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -0700921 visitor.WalkStack();
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800922 return JDWP::ERR_NONE;
923}
924
Sebastien Hertz52d131d2014-03-13 16:17:40 +0100925JDWP::JdwpError Dbg::GetContendedMonitor(JDWP::ObjectId thread_id,
Ian Rogersc0542af2014-09-03 16:16:56 -0700926 JDWP::ObjectId* contended_monitor) {
Elliott Hughesf9501702013-01-11 11:22:27 -0800927 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -0700928 *contended_monitor = 0;
Sebastien Hertz69206392015-04-07 15:54:25 +0200929 JDWP::JdwpError error;
930 Thread* thread = DecodeThread(soa, thread_id, &error);
931 if (thread == nullptr) {
932 return error;
Elliott Hughesf9501702013-01-11 11:22:27 -0800933 }
Sebastien Hertz69206392015-04-07 15:54:25 +0200934 if (!IsSuspendedForDebugger(soa, thread)) {
935 return JDWP::ERR_THREAD_NOT_SUSPENDED;
936 }
937 mirror::Object* contended_monitor_obj = Monitor::GetContendedMonitor(thread);
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700938 // Add() requires the thread_list_lock_ not held to avoid the lock
939 // level violation.
Ian Rogersc0542af2014-09-03 16:16:56 -0700940 *contended_monitor = gRegistry->Add(contended_monitor_obj);
Elliott Hughesf9501702013-01-11 11:22:27 -0800941 return JDWP::ERR_NONE;
942}
943
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800944JDWP::JdwpError Dbg::GetInstanceCounts(const std::vector<JDWP::RefTypeId>& class_ids,
Ian Rogersc0542af2014-09-03 16:16:56 -0700945 std::vector<uint64_t>* counts) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800946 gc::Heap* heap = Runtime::Current()->GetHeap();
Roland Levillainaf290312018-02-27 20:02:17 +0000947 heap->CollectGarbage(/* clear_soft_references */ false, gc::GcCause::kGcCauseDebugger);
Mathieu Chartiere8a3c572016-10-11 16:52:17 -0700948 VariableSizedHandleScope hs(Thread::Current());
Mathieu Chartier9d156d52016-10-06 17:44:26 -0700949 std::vector<Handle<mirror::Class>> classes;
Ian Rogersc0542af2014-09-03 16:16:56 -0700950 counts->clear();
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800951 for (size_t i = 0; i < class_ids.size(); ++i) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700952 JDWP::JdwpError error;
Mathieu Chartier9d156d52016-10-06 17:44:26 -0700953 ObjPtr<mirror::Class> c = DecodeClass(class_ids[i], &error);
Ian Rogersc0542af2014-09-03 16:16:56 -0700954 if (c == nullptr) {
955 return error;
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800956 }
Mathieu Chartier9d156d52016-10-06 17:44:26 -0700957 classes.push_back(hs.NewHandle(c));
Ian Rogersc0542af2014-09-03 16:16:56 -0700958 counts->push_back(0);
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800959 }
Ian Rogersc0542af2014-09-03 16:16:56 -0700960 heap->CountInstances(classes, false, &(*counts)[0]);
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800961 return JDWP::ERR_NONE;
962}
963
Ian Rogersc0542af2014-09-03 16:16:56 -0700964JDWP::JdwpError Dbg::GetInstances(JDWP::RefTypeId class_id, int32_t max_count,
965 std::vector<JDWP::ObjectId>* instances) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800966 gc::Heap* heap = Runtime::Current()->GetHeap();
967 // We only want reachable instances, so do a GC.
Roland Levillainaf290312018-02-27 20:02:17 +0000968 heap->CollectGarbage(/* clear_soft_references */ false, gc::GcCause::kGcCauseDebugger);
Ian Rogersc0542af2014-09-03 16:16:56 -0700969 JDWP::JdwpError error;
Mathieu Chartier9d156d52016-10-06 17:44:26 -0700970 ObjPtr<mirror::Class> c = DecodeClass(class_id, &error);
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800971 if (c == nullptr) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700972 return error;
Elliott Hughes3b78c942013-01-15 17:35:41 -0800973 }
Mathieu Chartier2d855952016-10-12 19:37:59 -0700974 VariableSizedHandleScope hs(Thread::Current());
975 std::vector<Handle<mirror::Object>> raw_instances;
Richard Uhler660be6f2017-11-22 16:12:29 +0000976 Runtime::Current()->GetHeap()->GetInstances(hs,
977 hs.NewHandle(c),
978 /* use_is_assignable_from */ false,
979 max_count,
980 raw_instances);
Elliott Hughes3b78c942013-01-15 17:35:41 -0800981 for (size_t i = 0; i < raw_instances.size(); ++i) {
Mathieu Chartier2d855952016-10-12 19:37:59 -0700982 instances->push_back(gRegistry->Add(raw_instances[i].Get()));
Elliott Hughes3b78c942013-01-15 17:35:41 -0800983 }
984 return JDWP::ERR_NONE;
985}
986
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800987JDWP::JdwpError Dbg::GetReferringObjects(JDWP::ObjectId object_id, int32_t max_count,
Ian Rogersc0542af2014-09-03 16:16:56 -0700988 std::vector<JDWP::ObjectId>* referring_objects) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800989 gc::Heap* heap = Runtime::Current()->GetHeap();
Roland Levillainaf290312018-02-27 20:02:17 +0000990 heap->CollectGarbage(/* clear_soft_references */ false, gc::GcCause::kGcCauseDebugger);
Ian Rogersc0542af2014-09-03 16:16:56 -0700991 JDWP::JdwpError error;
Mathieu Chartier9d156d52016-10-06 17:44:26 -0700992 ObjPtr<mirror::Object> o = gRegistry->Get<mirror::Object*>(object_id, &error);
Ian Rogersc0542af2014-09-03 16:16:56 -0700993 if (o == nullptr) {
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800994 return JDWP::ERR_INVALID_OBJECT;
995 }
Mathieu Chartieraea9bfb2016-10-12 19:19:56 -0700996 VariableSizedHandleScope hs(Thread::Current());
997 std::vector<Handle<mirror::Object>> raw_instances;
998 heap->GetReferringObjects(hs, hs.NewHandle(o), max_count, raw_instances);
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800999 for (size_t i = 0; i < raw_instances.size(); ++i) {
Mathieu Chartieraea9bfb2016-10-12 19:19:56 -07001000 referring_objects->push_back(gRegistry->Add(raw_instances[i].Get()));
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001001 }
1002 return JDWP::ERR_NONE;
1003}
1004
Ian Rogersc0542af2014-09-03 16:16:56 -07001005JDWP::JdwpError Dbg::DisableCollection(JDWP::ObjectId object_id) {
1006 JDWP::JdwpError error;
1007 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
1008 if (o == nullptr) {
Sebastien Hertze96060a2013-12-11 12:06:28 +01001009 return JDWP::ERR_INVALID_OBJECT;
1010 }
Elliott Hughes64f574f2013-02-20 14:57:12 -08001011 gRegistry->DisableCollection(object_id);
1012 return JDWP::ERR_NONE;
1013}
1014
Ian Rogersc0542af2014-09-03 16:16:56 -07001015JDWP::JdwpError Dbg::EnableCollection(JDWP::ObjectId object_id) {
1016 JDWP::JdwpError error;
1017 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
Sebastien Hertze96060a2013-12-11 12:06:28 +01001018 // Unlike DisableCollection, JDWP specs do not state an invalid object causes an error. The RI
1019 // also ignores these cases and never return an error. However it's not obvious why this command
1020 // should behave differently from DisableCollection and IsCollected commands. So let's be more
1021 // strict and return an error if this happens.
Ian Rogersc0542af2014-09-03 16:16:56 -07001022 if (o == nullptr) {
Sebastien Hertze96060a2013-12-11 12:06:28 +01001023 return JDWP::ERR_INVALID_OBJECT;
1024 }
Elliott Hughes64f574f2013-02-20 14:57:12 -08001025 gRegistry->EnableCollection(object_id);
1026 return JDWP::ERR_NONE;
1027}
1028
Ian Rogersc0542af2014-09-03 16:16:56 -07001029JDWP::JdwpError Dbg::IsCollected(JDWP::ObjectId object_id, bool* is_collected) {
1030 *is_collected = true;
Sebastien Hertz65637eb2014-01-10 17:40:02 +01001031 if (object_id == 0) {
1032 // Null object id is invalid.
Sebastien Hertze96060a2013-12-11 12:06:28 +01001033 return JDWP::ERR_INVALID_OBJECT;
1034 }
Sebastien Hertz65637eb2014-01-10 17:40:02 +01001035 // JDWP specs state an INVALID_OBJECT error is returned if the object ID is not valid. However
1036 // the RI seems to ignore this and assume object has been collected.
Ian Rogersc0542af2014-09-03 16:16:56 -07001037 JDWP::JdwpError error;
1038 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
1039 if (o != nullptr) {
1040 *is_collected = gRegistry->IsCollected(object_id);
Sebastien Hertz65637eb2014-01-10 17:40:02 +01001041 }
Elliott Hughes64f574f2013-02-20 14:57:12 -08001042 return JDWP::ERR_NONE;
1043}
1044
Ian Rogersc0542af2014-09-03 16:16:56 -07001045void Dbg::DisposeObject(JDWP::ObjectId object_id, uint32_t reference_count) {
Elliott Hughes64f574f2013-02-20 14:57:12 -08001046 gRegistry->DisposeObject(object_id, reference_count);
1047}
1048
Mathieu Chartier3398c782016-09-30 10:27:43 -07001049JDWP::JdwpTypeTag Dbg::GetTypeTag(ObjPtr<mirror::Class> klass) {
Sebastien Hertz4d8fd492014-03-28 16:29:41 +01001050 DCHECK(klass != nullptr);
1051 if (klass->IsArrayClass()) {
1052 return JDWP::TT_ARRAY;
1053 } else if (klass->IsInterface()) {
1054 return JDWP::TT_INTERFACE;
1055 } else {
1056 return JDWP::TT_CLASS;
1057 }
1058}
1059
Elliott Hughes88d63092013-01-09 09:55:54 -08001060JDWP::JdwpError Dbg::GetReflectedType(JDWP::RefTypeId class_id, JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001061 JDWP::JdwpError error;
1062 mirror::Class* c = DecodeClass(class_id, &error);
1063 if (c == nullptr) {
1064 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001065 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001066
Sebastien Hertz4d8fd492014-03-28 16:29:41 +01001067 JDWP::JdwpTypeTag type_tag = GetTypeTag(c);
1068 expandBufAdd1(pReply, type_tag);
Elliott Hughes88d63092013-01-09 09:55:54 -08001069 expandBufAddRefTypeId(pReply, class_id);
Elliott Hughes436e3722012-02-17 20:01:47 -08001070 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001071}
1072
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001073// Get the complete list of reference classes (i.e. all classes except
1074// the primitive types).
1075// Returns a newly-allocated buffer full of RefTypeId values.
1076class ClassListCreator : public ClassVisitor {
1077 public:
1078 explicit ClassListCreator(std::vector<JDWP::RefTypeId>* classes) : classes_(classes) {}
1079
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01001080 bool operator()(ObjPtr<mirror::Class> c) override REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001081 if (!c->IsPrimitive()) {
1082 classes_->push_back(Dbg::GetObjectRegistry()->AddRefType(c));
1083 }
1084 return true;
1085 }
1086
1087 private:
1088 std::vector<JDWP::RefTypeId>* const classes_;
1089};
1090
Ian Rogersc0542af2014-09-03 16:16:56 -07001091void Dbg::GetClassList(std::vector<JDWP::RefTypeId>* classes) {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001092 ClassListCreator clc(classes);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001093 Runtime::Current()->GetClassLinker()->VisitClassesWithoutClassesLock(&clc);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001094}
1095
Ian Rogers1ff3c982014-08-12 02:30:58 -07001096JDWP::JdwpError Dbg::GetClassInfo(JDWP::RefTypeId class_id, JDWP::JdwpTypeTag* pTypeTag,
1097 uint32_t* pStatus, std::string* pDescriptor) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001098 JDWP::JdwpError error;
1099 mirror::Class* c = DecodeClass(class_id, &error);
1100 if (c == nullptr) {
1101 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001102 }
1103
Elliott Hughesa2155262011-11-16 16:26:58 -08001104 if (c->IsArrayClass()) {
1105 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
1106 *pTypeTag = JDWP::TT_ARRAY;
1107 } else {
1108 if (c->IsErroneous()) {
1109 *pStatus = JDWP::CS_ERROR;
1110 } else {
1111 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED | JDWP::CS_INITIALIZED;
1112 }
1113 *pTypeTag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
1114 }
1115
Ian Rogersc0542af2014-09-03 16:16:56 -07001116 if (pDescriptor != nullptr) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07001117 std::string temp;
1118 *pDescriptor = c->GetDescriptor(&temp);
Elliott Hughesa2155262011-11-16 16:26:58 -08001119 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001120 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001121}
1122
Ian Rogersc0542af2014-09-03 16:16:56 -07001123void Dbg::FindLoadedClassBySignature(const char* descriptor, std::vector<JDWP::RefTypeId>* ids) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001124 std::vector<ObjPtr<mirror::Class>> classes;
Igor Murashkinb1d8c312015-08-04 11:18:43 -07001125 Runtime::Current()->GetClassLinker()->LookupClasses(descriptor, classes);
Ian Rogersc0542af2014-09-03 16:16:56 -07001126 ids->clear();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001127 for (ObjPtr<mirror::Class> c : classes) {
1128 ids->push_back(gRegistry->Add(c));
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001129 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001130}
1131
Ian Rogersc0542af2014-09-03 16:16:56 -07001132JDWP::JdwpError Dbg::GetReferenceType(JDWP::ObjectId object_id, JDWP::ExpandBuf* pReply) {
1133 JDWP::JdwpError error;
1134 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
1135 if (o == nullptr) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001136 return JDWP::ERR_INVALID_OBJECT;
Elliott Hughes499c5132011-11-17 14:55:11 -08001137 }
Elliott Hughes2435a572012-02-17 16:07:41 -08001138
Sebastien Hertz4d8fd492014-03-28 16:29:41 +01001139 JDWP::JdwpTypeTag type_tag = GetTypeTag(o->GetClass());
Elliott Hughes64f574f2013-02-20 14:57:12 -08001140 JDWP::RefTypeId type_id = gRegistry->AddRefType(o->GetClass());
Elliott Hughes2435a572012-02-17 16:07:41 -08001141
1142 expandBufAdd1(pReply, type_tag);
1143 expandBufAddRefTypeId(pReply, type_id);
1144
1145 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001146}
1147
Ian Rogersfc0e94b2013-09-23 23:51:32 -07001148JDWP::JdwpError Dbg::GetSignature(JDWP::RefTypeId class_id, std::string* signature) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001149 JDWP::JdwpError error;
1150 mirror::Class* c = DecodeClass(class_id, &error);
1151 if (c == nullptr) {
1152 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001153 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07001154 std::string temp;
1155 *signature = c->GetDescriptor(&temp);
Elliott Hughes1fe7afb2012-02-13 17:23:03 -08001156 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001157}
1158
Orion Hodson77d8a1c2017-04-24 14:53:19 +01001159JDWP::JdwpError Dbg::GetSourceDebugExtension(JDWP::RefTypeId class_id,
1160 std::string* extension_data) {
1161 JDWP::JdwpError error;
1162 mirror::Class* c = DecodeClass(class_id, &error);
1163 if (c == nullptr) {
1164 return error;
1165 }
1166 StackHandleScope<1> hs(Thread::Current());
1167 Handle<mirror::Class> klass(hs.NewHandle(c));
1168 const char* data = annotations::GetSourceDebugExtension(klass);
1169 if (data == nullptr) {
1170 return JDWP::ERR_ABSENT_INFORMATION;
1171 }
1172 *extension_data = data;
1173 return JDWP::ERR_NONE;
1174}
1175
Ian Rogersc0542af2014-09-03 16:16:56 -07001176JDWP::JdwpError Dbg::GetSourceFile(JDWP::RefTypeId class_id, std::string* result) {
1177 JDWP::JdwpError error;
1178 mirror::Class* c = DecodeClass(class_id, &error);
Sebastien Hertz4206eb52014-06-05 10:15:45 +02001179 if (c == nullptr) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001180 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001181 }
Sebastien Hertz4206eb52014-06-05 10:15:45 +02001182 const char* source_file = c->GetSourceFile();
1183 if (source_file == nullptr) {
Sebastien Hertzb7054ba2014-03-13 11:52:31 +01001184 return JDWP::ERR_ABSENT_INFORMATION;
1185 }
Ian Rogersc0542af2014-09-03 16:16:56 -07001186 *result = source_file;
Elliott Hughes436e3722012-02-17 20:01:47 -08001187 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001188}
1189
Ian Rogersc0542af2014-09-03 16:16:56 -07001190JDWP::JdwpError Dbg::GetObjectTag(JDWP::ObjectId object_id, uint8_t* tag) {
Ian Rogers98379392014-02-24 16:53:16 -08001191 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07001192 JDWP::JdwpError error;
1193 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
1194 if (error != JDWP::ERR_NONE) {
1195 *tag = JDWP::JT_VOID;
1196 return error;
Elliott Hughes546b9862012-06-20 16:06:13 -07001197 }
Ian Rogersc0542af2014-09-03 16:16:56 -07001198 *tag = TagFromObject(soa, o);
Elliott Hughes546b9862012-06-20 16:06:13 -07001199 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001200}
1201
Elliott Hughesaed4be92011-12-02 16:16:23 -08001202size_t Dbg::GetTagWidth(JDWP::JdwpTag tag) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001203 switch (tag) {
1204 case JDWP::JT_VOID:
1205 return 0;
1206 case JDWP::JT_BYTE:
1207 case JDWP::JT_BOOLEAN:
1208 return 1;
1209 case JDWP::JT_CHAR:
1210 case JDWP::JT_SHORT:
1211 return 2;
1212 case JDWP::JT_FLOAT:
1213 case JDWP::JT_INT:
1214 return 4;
1215 case JDWP::JT_ARRAY:
1216 case JDWP::JT_OBJECT:
1217 case JDWP::JT_STRING:
1218 case JDWP::JT_THREAD:
1219 case JDWP::JT_THREAD_GROUP:
1220 case JDWP::JT_CLASS_LOADER:
1221 case JDWP::JT_CLASS_OBJECT:
1222 return sizeof(JDWP::ObjectId);
1223 case JDWP::JT_DOUBLE:
1224 case JDWP::JT_LONG:
1225 return 8;
1226 default:
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001227 LOG(FATAL) << "Unknown tag " << tag;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001228 return -1;
1229 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001230}
1231
Ian Rogersc0542af2014-09-03 16:16:56 -07001232JDWP::JdwpError Dbg::GetArrayLength(JDWP::ObjectId array_id, int32_t* length) {
1233 JDWP::JdwpError error;
1234 mirror::Array* a = DecodeNonNullArray(array_id, &error);
1235 if (a == nullptr) {
1236 return error;
Elliott Hughes24437992011-11-30 14:49:33 -08001237 }
Ian Rogersc0542af2014-09-03 16:16:56 -07001238 *length = a->GetLength();
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001239 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001240}
1241
Elliott Hughes88d63092013-01-09 09:55:54 -08001242JDWP::JdwpError Dbg::OutputArray(JDWP::ObjectId array_id, int offset, int count, JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001243 JDWP::JdwpError error;
1244 mirror::Array* a = DecodeNonNullArray(array_id, &error);
Ian Rogers98379392014-02-24 16:53:16 -08001245 if (a == nullptr) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001246 return error;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001247 }
Elliott Hughes24437992011-11-30 14:49:33 -08001248
1249 if (offset < 0 || count < 0 || offset > a->GetLength() || a->GetLength() - offset < count) {
1250 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001251 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughes24437992011-11-30 14:49:33 -08001252 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07001253 JDWP::JdwpTag element_tag = BasicTagFromClass(a->GetClass()->GetComponentType());
1254 expandBufAdd1(pReply, element_tag);
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001255 expandBufAdd4BE(pReply, count);
1256
Ian Rogers1ff3c982014-08-12 02:30:58 -07001257 if (IsPrimitiveTag(element_tag)) {
1258 size_t width = GetTagWidth(element_tag);
Elliott Hughes24437992011-11-30 14:49:33 -08001259 uint8_t* dst = expandBufAddSpace(pReply, count * width);
1260 if (width == 8) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001261 const uint64_t* src8 = reinterpret_cast<uint64_t*>(a->GetRawData(sizeof(uint64_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001262 for (int i = 0; i < count; ++i) JDWP::Write8BE(&dst, src8[offset + i]);
1263 } else if (width == 4) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001264 const uint32_t* src4 = reinterpret_cast<uint32_t*>(a->GetRawData(sizeof(uint32_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001265 for (int i = 0; i < count; ++i) JDWP::Write4BE(&dst, src4[offset + i]);
1266 } else if (width == 2) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001267 const uint16_t* src2 = reinterpret_cast<uint16_t*>(a->GetRawData(sizeof(uint16_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001268 for (int i = 0; i < count; ++i) JDWP::Write2BE(&dst, src2[offset + i]);
1269 } else {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001270 const uint8_t* src = reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint8_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001271 memcpy(dst, &src[offset * width], count * width);
1272 }
1273 } else {
Ian Rogers98379392014-02-24 16:53:16 -08001274 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001275 mirror::ObjectArray<mirror::Object>* oa = a->AsObjectArray<mirror::Object>();
Elliott Hughes24437992011-11-30 14:49:33 -08001276 for (int i = 0; i < count; ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001277 mirror::Object* element = oa->Get(offset + i);
Ian Rogers98379392014-02-24 16:53:16 -08001278 JDWP::JdwpTag specific_tag = (element != nullptr) ? TagFromObject(soa, element)
Ian Rogers1ff3c982014-08-12 02:30:58 -07001279 : element_tag;
Elliott Hughes24437992011-11-30 14:49:33 -08001280 expandBufAdd1(pReply, specific_tag);
1281 expandBufAddObjectId(pReply, gRegistry->Add(element));
1282 }
1283 }
1284
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001285 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001286}
1287
Ian Rogersef7d42f2014-01-06 12:55:46 -08001288template <typename T>
Ian Rogersc0542af2014-09-03 16:16:56 -07001289static void CopyArrayData(mirror::Array* a, JDWP::Request* src, int offset, int count)
Ian Rogersef7d42f2014-01-06 12:55:46 -08001290 NO_THREAD_SAFETY_ANALYSIS {
1291 // TODO: fix when annotalysis correctly handles non-member functions.
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001292 DCHECK(a->GetClass()->IsPrimitiveArray());
1293
Ian Rogersef7d42f2014-01-06 12:55:46 -08001294 T* dst = reinterpret_cast<T*>(a->GetRawData(sizeof(T), offset));
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001295 for (int i = 0; i < count; ++i) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001296 *dst++ = src->ReadValue(sizeof(T));
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001297 }
1298}
1299
Elliott Hughes88d63092013-01-09 09:55:54 -08001300JDWP::JdwpError Dbg::SetArrayElements(JDWP::ObjectId array_id, int offset, int count,
Ian Rogersc0542af2014-09-03 16:16:56 -07001301 JDWP::Request* request) {
1302 JDWP::JdwpError error;
1303 mirror::Array* dst = DecodeNonNullArray(array_id, &error);
1304 if (dst == nullptr) {
1305 return error;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001306 }
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001307
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001308 if (offset < 0 || count < 0 || offset > dst->GetLength() || dst->GetLength() - offset < count) {
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001309 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001310 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001311 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07001312 JDWP::JdwpTag element_tag = BasicTagFromClass(dst->GetClass()->GetComponentType());
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001313
Ian Rogers1ff3c982014-08-12 02:30:58 -07001314 if (IsPrimitiveTag(element_tag)) {
1315 size_t width = GetTagWidth(element_tag);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001316 if (width == 8) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001317 CopyArrayData<uint64_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001318 } else if (width == 4) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001319 CopyArrayData<uint32_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001320 } else if (width == 2) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001321 CopyArrayData<uint16_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001322 } else {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001323 CopyArrayData<uint8_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001324 }
1325 } else {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001326 mirror::ObjectArray<mirror::Object>* oa = dst->AsObjectArray<mirror::Object>();
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001327 for (int i = 0; i < count; ++i) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001328 JDWP::ObjectId id = request->ReadObjectId();
Ian Rogersc0542af2014-09-03 16:16:56 -07001329 mirror::Object* o = gRegistry->Get<mirror::Object*>(id, &error);
1330 if (error != JDWP::ERR_NONE) {
1331 return error;
Elliott Hughes436e3722012-02-17 20:01:47 -08001332 }
Sebastien Hertz2e1c16d2015-08-28 11:57:49 +02001333 // Check if the object's type is compatible with the array's type.
1334 if (o != nullptr && !o->InstanceOf(oa->GetClass()->GetComponentType())) {
1335 return JDWP::ERR_TYPE_MISMATCH;
1336 }
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001337 oa->Set<false>(offset + i, o);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001338 }
1339 }
1340
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001341 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001342}
1343
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001344JDWP::JdwpError Dbg::CreateString(const std::string& str, JDWP::ObjectId* new_string_id) {
1345 Thread* self = Thread::Current();
1346 mirror::String* new_string = mirror::String::AllocFromModifiedUtf8(self, str.c_str());
1347 if (new_string == nullptr) {
1348 DCHECK(self->IsExceptionPending());
1349 self->ClearException();
1350 LOG(ERROR) << "Could not allocate string";
1351 *new_string_id = 0;
1352 return JDWP::ERR_OUT_OF_MEMORY;
1353 }
1354 *new_string_id = gRegistry->Add(new_string);
1355 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001356}
1357
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001358JDWP::JdwpError Dbg::CreateObject(JDWP::RefTypeId class_id, JDWP::ObjectId* new_object_id) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001359 JDWP::JdwpError error;
1360 mirror::Class* c = DecodeClass(class_id, &error);
1361 if (c == nullptr) {
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001362 *new_object_id = 0;
Ian Rogersc0542af2014-09-03 16:16:56 -07001363 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001364 }
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001365 Thread* self = Thread::Current();
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001366 ObjPtr<mirror::Object> new_object;
Sebastien Hertz56d5e502015-11-03 17:38:35 +01001367 if (c->IsStringClass()) {
1368 // Special case for java.lang.String.
1369 gc::AllocatorType allocator_type = Runtime::Current()->GetHeap()->GetCurrentAllocator();
jessicahandojo3aaa37b2016-07-29 14:46:37 -07001370 new_object = mirror::String::AllocEmptyString<true>(self, allocator_type);
Sebastien Hertz56d5e502015-11-03 17:38:35 +01001371 } else {
1372 new_object = c->AllocObject(self);
1373 }
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001374 if (new_object == nullptr) {
1375 DCHECK(self->IsExceptionPending());
1376 self->ClearException();
David Sehr709b0702016-10-13 09:12:37 -07001377 LOG(ERROR) << "Could not allocate object of type " << mirror::Class::PrettyDescriptor(c);
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001378 *new_object_id = 0;
1379 return JDWP::ERR_OUT_OF_MEMORY;
1380 }
Vladimir Markobcf17522018-06-01 13:14:32 +01001381 *new_object_id = gRegistry->Add(new_object);
Elliott Hughes436e3722012-02-17 20:01:47 -08001382 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001383}
1384
Elliott Hughesbf13d362011-12-08 15:51:37 -08001385/*
1386 * Used by Eclipse's "Display" view to evaluate "new byte[5]" to get "(byte[]) [0, 0, 0, 0, 0]".
1387 */
Elliott Hughes88d63092013-01-09 09:55:54 -08001388JDWP::JdwpError Dbg::CreateArrayObject(JDWP::RefTypeId array_class_id, uint32_t length,
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001389 JDWP::ObjectId* new_array_id) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001390 JDWP::JdwpError error;
1391 mirror::Class* c = DecodeClass(array_class_id, &error);
1392 if (c == nullptr) {
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001393 *new_array_id = 0;
Ian Rogersc0542af2014-09-03 16:16:56 -07001394 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001395 }
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001396 Thread* self = Thread::Current();
Vladimir Markobcf17522018-06-01 13:14:32 +01001397 gc::AllocatorType allocator_type = Runtime::Current()->GetHeap()->GetCurrentAllocator();
1398 ObjPtr<mirror::Array> new_array =
1399 mirror::Array::Alloc<true>(self, c, length, c->GetComponentSizeShift(), allocator_type);
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001400 if (new_array == nullptr) {
1401 DCHECK(self->IsExceptionPending());
1402 self->ClearException();
David Sehr709b0702016-10-13 09:12:37 -07001403 LOG(ERROR) << "Could not allocate array of type " << mirror::Class::PrettyDescriptor(c);
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001404 *new_array_id = 0;
1405 return JDWP::ERR_OUT_OF_MEMORY;
1406 }
1407 *new_array_id = gRegistry->Add(new_array);
Elliott Hughes436e3722012-02-17 20:01:47 -08001408 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001409}
1410
Mathieu Chartierc7853442015-03-27 14:35:38 -07001411JDWP::FieldId Dbg::ToFieldId(const ArtField* f) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001412 return static_cast<JDWP::FieldId>(reinterpret_cast<uintptr_t>(f));
Elliott Hughes03181a82011-11-17 17:22:21 -08001413}
1414
Alex Light6c8467f2015-11-20 15:03:26 -08001415static JDWP::MethodId ToMethodId(ArtMethod* m)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001416 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light97e78032017-06-27 17:51:55 -07001417 return static_cast<JDWP::MethodId>(
1418 reinterpret_cast<uintptr_t>(m->GetCanonicalMethod(kRuntimePointerSize)));
Elliott Hughes03181a82011-11-17 17:22:21 -08001419}
1420
Mathieu Chartierc7853442015-03-27 14:35:38 -07001421static ArtField* FromFieldId(JDWP::FieldId fid)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001422 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001423 return reinterpret_cast<ArtField*>(static_cast<uintptr_t>(fid));
Elliott Hughesaed4be92011-12-02 16:16:23 -08001424}
1425
Mathieu Chartiere401d142015-04-22 13:56:20 -07001426static ArtMethod* FromMethodId(JDWP::MethodId mid)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001427 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001428 return reinterpret_cast<ArtMethod*>(static_cast<uintptr_t>(mid));
Elliott Hughes03181a82011-11-17 17:22:21 -08001429}
1430
Sebastien Hertz6995c602014-09-09 12:10:13 +02001431bool Dbg::MatchThread(JDWP::ObjectId expected_thread_id, Thread* event_thread) {
1432 CHECK(event_thread != nullptr);
1433 JDWP::JdwpError error;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001434 mirror::Object* expected_thread_peer = gRegistry->Get<mirror::Object*>(
1435 expected_thread_id, &error);
Nicolas Geoffraycafa0812017-02-15 18:27:34 +00001436 return expected_thread_peer == event_thread->GetPeerFromOtherThread();
Sebastien Hertz6995c602014-09-09 12:10:13 +02001437}
1438
1439bool Dbg::MatchLocation(const JDWP::JdwpLocation& expected_location,
1440 const JDWP::EventLocation& event_location) {
1441 if (expected_location.dex_pc != event_location.dex_pc) {
1442 return false;
1443 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001444 ArtMethod* m = FromMethodId(expected_location.method_id);
Sebastien Hertz6995c602014-09-09 12:10:13 +02001445 return m == event_location.method;
1446}
1447
Mathieu Chartier3398c782016-09-30 10:27:43 -07001448bool Dbg::MatchType(ObjPtr<mirror::Class> event_class, JDWP::RefTypeId class_id) {
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001449 if (event_class == nullptr) {
1450 return false;
1451 }
Sebastien Hertz6995c602014-09-09 12:10:13 +02001452 JDWP::JdwpError error;
Mathieu Chartier3398c782016-09-30 10:27:43 -07001453 ObjPtr<mirror::Class> expected_class = DecodeClass(class_id, &error);
Sebastien Hertz6995c602014-09-09 12:10:13 +02001454 CHECK(expected_class != nullptr);
1455 return expected_class->IsAssignableFrom(event_class);
1456}
1457
1458bool Dbg::MatchField(JDWP::RefTypeId expected_type_id, JDWP::FieldId expected_field_id,
Mathieu Chartierc7853442015-03-27 14:35:38 -07001459 ArtField* event_field) {
1460 ArtField* expected_field = FromFieldId(expected_field_id);
Sebastien Hertz6995c602014-09-09 12:10:13 +02001461 if (expected_field != event_field) {
1462 return false;
1463 }
1464 return Dbg::MatchType(event_field->GetDeclaringClass(), expected_type_id);
1465}
1466
1467bool Dbg::MatchInstance(JDWP::ObjectId expected_instance_id, mirror::Object* event_instance) {
1468 JDWP::JdwpError error;
1469 mirror::Object* modifier_instance = gRegistry->Get<mirror::Object*>(expected_instance_id, &error);
1470 return modifier_instance == event_instance;
1471}
1472
Mathieu Chartier90443472015-07-16 20:32:27 -07001473void Dbg::SetJdwpLocation(JDWP::JdwpLocation* location, ArtMethod* m, uint32_t dex_pc) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001474 if (m == nullptr) {
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001475 memset(location, 0, sizeof(*location));
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001476 } else {
Vladimir Markod93e3742018-07-18 10:58:13 +01001477 ObjPtr<mirror::Class> c = m->GetDeclaringClass();
Ian Rogersc0542af2014-09-03 16:16:56 -07001478 location->type_tag = GetTypeTag(c);
1479 location->class_id = gRegistry->AddRefType(c);
Alex Light73376312017-04-06 10:10:51 -07001480 // The RI Seems to return 0 for all obsolete methods. For compatibility we shall do the same.
1481 location->method_id = m->IsObsolete() ? 0 : ToMethodId(m);
Ian Rogersc0542af2014-09-03 16:16:56 -07001482 location->dex_pc = (m->IsNative() || m->IsProxyMethod()) ? static_cast<uint64_t>(-1) : dex_pc;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001483 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08001484}
1485
Ian Rogersc0542af2014-09-03 16:16:56 -07001486std::string Dbg::GetMethodName(JDWP::MethodId method_id) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001487 ArtMethod* m = FromMethodId(method_id);
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001488 if (m == nullptr) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001489 return "null";
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001490 }
Andreas Gampe542451c2016-07-26 09:02:02 -07001491 return m->GetInterfaceMethodIfProxy(kRuntimePointerSize)->GetName();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001492}
1493
Alex Light73376312017-04-06 10:10:51 -07001494bool Dbg::IsMethodObsolete(JDWP::MethodId method_id) {
1495 ArtMethod* m = FromMethodId(method_id);
1496 if (m == nullptr) {
1497 // NB Since we return 0 as MID for obsolete methods we want to default to true here.
1498 return true;
1499 }
1500 return m->IsObsolete();
1501}
1502
Ian Rogersc0542af2014-09-03 16:16:56 -07001503std::string Dbg::GetFieldName(JDWP::FieldId field_id) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001504 ArtField* f = FromFieldId(field_id);
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001505 if (f == nullptr) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001506 return "null";
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001507 }
1508 return f->GetName();
Elliott Hughesa96836a2013-01-17 12:27:49 -08001509}
1510
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001511/*
1512 * Augment the access flags for synthetic methods and fields by setting
1513 * the (as described by the spec) "0xf0000000 bit". Also, strip out any
1514 * flags not specified by the Java programming language.
1515 */
1516static uint32_t MangleAccessFlags(uint32_t accessFlags) {
1517 accessFlags &= kAccJavaFlagsMask;
1518 if ((accessFlags & kAccSynthetic) != 0) {
1519 accessFlags |= 0xf0000000;
1520 }
1521 return accessFlags;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001522}
1523
Elliott Hughesdbb40792011-11-18 17:05:22 -08001524/*
Jeff Haob7cefc72013-11-14 14:51:09 -08001525 * Circularly shifts registers so that arguments come first. Debuggers
1526 * expect slots to begin with arguments, but dex code places them at
1527 * the end.
Elliott Hughesdbb40792011-11-18 17:05:22 -08001528 */
Mathieu Chartiere401d142015-04-22 13:56:20 -07001529static uint16_t MangleSlot(uint16_t slot, ArtMethod* m)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001530 REQUIRES_SHARED(Locks::mutator_lock_) {
David Sehr0225f8e2018-01-31 08:52:24 +00001531 CodeItemDataAccessor accessor(m->DexInstructionData());
Mathieu Chartier808c7a52017-12-15 11:19:33 -08001532 if (!accessor.HasCodeItem()) {
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001533 // We should not get here for a method without code (native, proxy or abstract). Log it and
1534 // return the slot as is since all registers are arguments.
David Sehr709b0702016-10-13 09:12:37 -07001535 LOG(WARNING) << "Trying to mangle slot for method without code " << m->PrettyMethod();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001536 return slot;
1537 }
Mathieu Chartier808c7a52017-12-15 11:19:33 -08001538 uint16_t ins_size = accessor.InsSize();
1539 uint16_t locals_size = accessor.RegistersSize() - ins_size;
Jeff Haob7cefc72013-11-14 14:51:09 -08001540 if (slot >= locals_size) {
1541 return slot - locals_size;
1542 } else {
1543 return slot + ins_size;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001544 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001545}
1546
Sebastien Hertzaef0c912016-08-08 10:20:28 +02001547static size_t GetMethodNumArgRegistersIncludingThis(ArtMethod* method)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001548 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertzaef0c912016-08-08 10:20:28 +02001549 uint32_t num_registers = ArtMethod::NumArgRegisters(method->GetShorty());
1550 if (!method->IsStatic()) {
1551 ++num_registers;
1552 }
1553 return num_registers;
1554}
1555
Jeff Haob7cefc72013-11-14 14:51:09 -08001556/*
1557 * Circularly shifts registers so that arguments come last. Reverts
1558 * slots to dex style argument placement.
1559 */
Mathieu Chartiere401d142015-04-22 13:56:20 -07001560static uint16_t DemangleSlot(uint16_t slot, ArtMethod* m, JDWP::JdwpError* error)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001561 REQUIRES_SHARED(Locks::mutator_lock_) {
David Sehr0225f8e2018-01-31 08:52:24 +00001562 CodeItemDataAccessor accessor(m->DexInstructionData());
Mathieu Chartier808c7a52017-12-15 11:19:33 -08001563 if (!accessor.HasCodeItem()) {
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001564 // We should not get here for a method without code (native, proxy or abstract). Log it and
1565 // return the slot as is since all registers are arguments.
David Sehr709b0702016-10-13 09:12:37 -07001566 LOG(WARNING) << "Trying to demangle slot for method without code "
1567 << m->PrettyMethod();
Sebastien Hertzaef0c912016-08-08 10:20:28 +02001568 uint16_t vreg_count = GetMethodNumArgRegistersIncludingThis(m);
Sebastien Hertzabbabc82015-03-26 08:47:47 +01001569 if (slot < vreg_count) {
1570 *error = JDWP::ERR_NONE;
1571 return slot;
1572 }
Jeff Haob7cefc72013-11-14 14:51:09 -08001573 } else {
Mathieu Chartier808c7a52017-12-15 11:19:33 -08001574 if (slot < accessor.RegistersSize()) {
1575 uint16_t ins_size = accessor.InsSize();
1576 uint16_t locals_size = accessor.RegistersSize() - ins_size;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01001577 *error = JDWP::ERR_NONE;
1578 return (slot < ins_size) ? slot + locals_size : slot - ins_size;
1579 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001580 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01001581
1582 // Slot is invalid in the method.
David Sehr709b0702016-10-13 09:12:37 -07001583 LOG(ERROR) << "Invalid local slot " << slot << " for method " << m->PrettyMethod();
Sebastien Hertzabbabc82015-03-26 08:47:47 +01001584 *error = JDWP::ERR_INVALID_SLOT;
1585 return DexFile::kDexNoIndex16;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001586}
1587
Mathieu Chartier90443472015-07-16 20:32:27 -07001588JDWP::JdwpError Dbg::OutputDeclaredFields(JDWP::RefTypeId class_id, bool with_generic,
1589 JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001590 JDWP::JdwpError error;
1591 mirror::Class* c = DecodeClass(class_id, &error);
1592 if (c == nullptr) {
1593 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001594 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001595
1596 size_t instance_field_count = c->NumInstanceFields();
1597 size_t static_field_count = c->NumStaticFields();
1598
1599 expandBufAdd4BE(pReply, instance_field_count + static_field_count);
1600
1601 for (size_t i = 0; i < instance_field_count + static_field_count; ++i) {
Mathieu Chartier90443472015-07-16 20:32:27 -07001602 ArtField* f = (i < instance_field_count) ? c->GetInstanceField(i) :
1603 c->GetStaticField(i - instance_field_count);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001604 expandBufAddFieldId(pReply, ToFieldId(f));
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001605 expandBufAddUtf8String(pReply, f->GetName());
1606 expandBufAddUtf8String(pReply, f->GetTypeDescriptor());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001607 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001608 static const char genericSignature[1] = "";
1609 expandBufAddUtf8String(pReply, genericSignature);
1610 }
1611 expandBufAdd4BE(pReply, MangleAccessFlags(f->GetAccessFlags()));
1612 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001613 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001614}
1615
Elliott Hughes88d63092013-01-09 09:55:54 -08001616JDWP::JdwpError Dbg::OutputDeclaredMethods(JDWP::RefTypeId class_id, bool with_generic,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001617 JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001618 JDWP::JdwpError error;
1619 mirror::Class* c = DecodeClass(class_id, &error);
1620 if (c == nullptr) {
1621 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001622 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001623
Alex Light51a64d52015-12-17 13:55:59 -08001624 expandBufAdd4BE(pReply, c->NumMethods());
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001625
Mathieu Chartiere401d142015-04-22 13:56:20 -07001626 auto* cl = Runtime::Current()->GetClassLinker();
1627 auto ptr_size = cl->GetImagePointerSize();
Alex Light51a64d52015-12-17 13:55:59 -08001628 for (ArtMethod& m : c->GetMethods(ptr_size)) {
1629 expandBufAddMethodId(pReply, ToMethodId(&m));
Andreas Gampe542451c2016-07-26 09:02:02 -07001630 expandBufAddUtf8String(pReply, m.GetInterfaceMethodIfProxy(kRuntimePointerSize)->GetName());
1631 expandBufAddUtf8String(
1632 pReply, m.GetInterfaceMethodIfProxy(kRuntimePointerSize)->GetSignature().ToString());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001633 if (with_generic) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001634 const char* generic_signature = "";
1635 expandBufAddUtf8String(pReply, generic_signature);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001636 }
Alex Light51a64d52015-12-17 13:55:59 -08001637 expandBufAdd4BE(pReply, MangleAccessFlags(m.GetAccessFlags()));
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001638 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001639 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001640}
1641
Elliott Hughes88d63092013-01-09 09:55:54 -08001642JDWP::JdwpError Dbg::OutputDeclaredInterfaces(JDWP::RefTypeId class_id, JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001643 JDWP::JdwpError error;
Mathieu Chartierf8322842014-05-16 10:59:25 -07001644 Thread* self = Thread::Current();
Vladimir Marko19a4d372016-12-08 14:41:46 +00001645 ObjPtr<mirror::Class> c = DecodeClass(class_id, &error);
1646 if (c == nullptr) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001647 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001648 }
Mathieu Chartierf8322842014-05-16 10:59:25 -07001649 size_t interface_count = c->NumDirectInterfaces();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001650 expandBufAdd4BE(pReply, interface_count);
1651 for (size_t i = 0; i < interface_count; ++i) {
Vladimir Marko19a4d372016-12-08 14:41:46 +00001652 ObjPtr<mirror::Class> interface = mirror::Class::GetDirectInterface(self, c, i);
1653 DCHECK(interface != nullptr);
1654 expandBufAddRefTypeId(pReply, gRegistry->AddRefType(interface));
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001655 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001656 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001657}
1658
Ian Rogersc0542af2014-09-03 16:16:56 -07001659void Dbg::OutputLineTable(JDWP::RefTypeId, JDWP::MethodId method_id, JDWP::ExpandBuf* pReply) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001660 ArtMethod* m = FromMethodId(method_id);
David Sehr0225f8e2018-01-31 08:52:24 +00001661 CodeItemDebugInfoAccessor accessor(m->DexInstructionDebugInfo());
Elliott Hughes03181a82011-11-17 17:22:21 -08001662 uint64_t start, end;
Mathieu Chartier31f4c9f2017-12-08 15:46:11 -08001663 if (!accessor.HasCodeItem()) {
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001664 DCHECK(m->IsNative() || m->IsProxyMethod());
Elliott Hughes03181a82011-11-17 17:22:21 -08001665 start = -1;
1666 end = -1;
1667 } else {
1668 start = 0;
jeffhao14f0db92012-12-14 17:50:42 -08001669 // Return the index of the last instruction
Mathieu Chartier31f4c9f2017-12-08 15:46:11 -08001670 end = accessor.InsnsSizeInCodeUnits() - 1;
Elliott Hughes03181a82011-11-17 17:22:21 -08001671 }
1672
1673 expandBufAdd8BE(pReply, start);
1674 expandBufAdd8BE(pReply, end);
1675
1676 // Add numLines later
1677 size_t numLinesOffset = expandBufGetLength(pReply);
1678 expandBufAdd4BE(pReply, 0);
1679
Mathieu Chartier3e2e1232018-09-11 12:35:30 -07001680 int numItems = 0;
1681 accessor.DecodeDebugPositionInfo([&](const DexFile::PositionInfo& entry) {
1682 expandBufAdd8BE(pReply, entry.address_);
1683 expandBufAdd4BE(pReply, entry.line_);
1684 numItems++;
1685 return false;
1686 });
Elliott Hughes03181a82011-11-17 17:22:21 -08001687
Mathieu Chartier3e2e1232018-09-11 12:35:30 -07001688 JDWP::Set4BE(expandBufGetBuffer(pReply) + numLinesOffset, numItems);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001689}
1690
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001691void Dbg::OutputVariableTable(JDWP::RefTypeId, JDWP::MethodId method_id, bool with_generic,
1692 JDWP::ExpandBuf* pReply) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001693 ArtMethod* m = FromMethodId(method_id);
David Sehr0225f8e2018-01-31 08:52:24 +00001694 CodeItemDebugInfoAccessor accessor(m->DexInstructionDebugInfo());
Elliott Hughesdbb40792011-11-18 17:05:22 -08001695
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001696 // arg_count considers doubles and longs to take 2 units.
1697 // variable_count considers everything to take 1 unit.
Sebastien Hertzaef0c912016-08-08 10:20:28 +02001698 expandBufAdd4BE(pReply, GetMethodNumArgRegistersIncludingThis(m));
Elliott Hughesdbb40792011-11-18 17:05:22 -08001699
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001700 // We don't know the total number of variables yet, so leave a blank and update it later.
1701 size_t variable_count_offset = expandBufGetLength(pReply);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001702 expandBufAdd4BE(pReply, 0);
1703
Mathieu Chartiere5afbf32018-09-12 17:51:54 -07001704 size_t variable_count = 0;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001705
Mathieu Chartier31f4c9f2017-12-08 15:46:11 -08001706 if (accessor.HasCodeItem()) {
Mathieu Chartiere5afbf32018-09-12 17:51:54 -07001707 accessor.DecodeDebugLocalInfo(m->IsStatic(),
1708 m->GetDexMethodIndex(),
1709 [&](const DexFile::LocalInfo& entry)
1710 REQUIRES_SHARED(Locks::mutator_lock_) {
1711 uint16_t slot = entry.reg_;
1712 VLOG(jdwp) << StringPrintf(" %2zd: %d(%d) '%s' '%s' '%s' actual slot=%d mangled slot=%d",
1713 variable_count,
1714 entry.start_address_,
1715 entry.end_address_ - entry.start_address_,
1716 entry.name_,
1717 entry.descriptor_, entry.signature_,
1718 slot,
1719 MangleSlot(slot, m));
1720
1721 slot = MangleSlot(slot, m);
1722
1723 expandBufAdd8BE(pReply, entry.start_address_);
1724 expandBufAddUtf8String(pReply, entry.name_);
1725 expandBufAddUtf8String(pReply, entry.descriptor_);
1726 if (with_generic) {
1727 expandBufAddUtf8String(pReply, entry.signature_);
1728 }
1729 expandBufAdd4BE(pReply, entry.end_address_- entry.start_address_);
1730 expandBufAdd4BE(pReply, slot);
1731
1732 ++variable_count;
1733 });
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001734 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001735
Mathieu Chartiere5afbf32018-09-12 17:51:54 -07001736 JDWP::Set4BE(expandBufGetBuffer(pReply) + variable_count_offset, variable_count);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001737}
1738
Jeff Hao579b0242013-11-18 13:16:49 -08001739void Dbg::OutputMethodReturnValue(JDWP::MethodId method_id, const JValue* return_value,
1740 JDWP::ExpandBuf* pReply) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001741 ArtMethod* m = FromMethodId(method_id);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001742 JDWP::JdwpTag tag = BasicTagFromDescriptor(m->GetShorty());
Jeff Hao579b0242013-11-18 13:16:49 -08001743 OutputJValue(tag, return_value, pReply);
1744}
1745
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02001746void Dbg::OutputFieldValue(JDWP::FieldId field_id, const JValue* field_value,
1747 JDWP::ExpandBuf* pReply) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001748 ArtField* f = FromFieldId(field_id);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001749 JDWP::JdwpTag tag = BasicTagFromDescriptor(f->GetTypeDescriptor());
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02001750 OutputJValue(tag, field_value, pReply);
1751}
1752
Elliott Hughes9777ba22013-01-17 09:04:19 -08001753JDWP::JdwpError Dbg::GetBytecodes(JDWP::RefTypeId, JDWP::MethodId method_id,
Ian Rogersc0542af2014-09-03 16:16:56 -07001754 std::vector<uint8_t>* bytecodes) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001755 ArtMethod* m = FromMethodId(method_id);
Ian Rogersc0542af2014-09-03 16:16:56 -07001756 if (m == nullptr) {
Elliott Hughes9777ba22013-01-17 09:04:19 -08001757 return JDWP::ERR_INVALID_METHODID;
1758 }
David Sehr0225f8e2018-01-31 08:52:24 +00001759 CodeItemDataAccessor accessor(m->DexInstructionData());
Mathieu Chartier808c7a52017-12-15 11:19:33 -08001760 size_t byte_count = accessor.InsnsSizeInCodeUnits() * 2;
1761 const uint8_t* begin = reinterpret_cast<const uint8_t*>(accessor.Insns());
Elliott Hughes9777ba22013-01-17 09:04:19 -08001762 const uint8_t* end = begin + byte_count;
1763 for (const uint8_t* p = begin; p != end; ++p) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001764 bytecodes->push_back(*p);
Elliott Hughes9777ba22013-01-17 09:04:19 -08001765 }
1766 return JDWP::ERR_NONE;
1767}
1768
Elliott Hughes88d63092013-01-09 09:55:54 -08001769JDWP::JdwpTag Dbg::GetFieldBasicTag(JDWP::FieldId field_id) {
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001770 return BasicTagFromDescriptor(FromFieldId(field_id)->GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001771}
1772
Elliott Hughes88d63092013-01-09 09:55:54 -08001773JDWP::JdwpTag Dbg::GetStaticFieldBasicTag(JDWP::FieldId field_id) {
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001774 return BasicTagFromDescriptor(FromFieldId(field_id)->GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001775}
1776
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001777static JValue GetArtFieldValue(ArtField* f, mirror::Object* o)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001778 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001779 Primitive::Type fieldType = f->GetTypeAsPrimitiveType();
1780 JValue field_value;
1781 switch (fieldType) {
1782 case Primitive::kPrimBoolean:
1783 field_value.SetZ(f->GetBoolean(o));
1784 return field_value;
1785
1786 case Primitive::kPrimByte:
1787 field_value.SetB(f->GetByte(o));
1788 return field_value;
1789
1790 case Primitive::kPrimChar:
1791 field_value.SetC(f->GetChar(o));
1792 return field_value;
1793
1794 case Primitive::kPrimShort:
1795 field_value.SetS(f->GetShort(o));
1796 return field_value;
1797
1798 case Primitive::kPrimInt:
1799 case Primitive::kPrimFloat:
1800 // Int and Float must be treated as 32-bit values in JDWP.
1801 field_value.SetI(f->GetInt(o));
1802 return field_value;
1803
1804 case Primitive::kPrimLong:
1805 case Primitive::kPrimDouble:
1806 // Long and Double must be treated as 64-bit values in JDWP.
1807 field_value.SetJ(f->GetLong(o));
1808 return field_value;
1809
1810 case Primitive::kPrimNot:
Vladimir Markobcf17522018-06-01 13:14:32 +01001811 field_value.SetL(f->GetObject(o));
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001812 return field_value;
1813
1814 case Primitive::kPrimVoid:
1815 LOG(FATAL) << "Attempt to read from field of type 'void'";
1816 UNREACHABLE();
1817 }
1818 LOG(FATAL) << "Attempt to read from field of unknown type";
1819 UNREACHABLE();
1820}
1821
Elliott Hughes88d63092013-01-09 09:55:54 -08001822static JDWP::JdwpError GetFieldValueImpl(JDWP::RefTypeId ref_type_id, JDWP::ObjectId object_id,
1823 JDWP::FieldId field_id, JDWP::ExpandBuf* pReply,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001824 bool is_static)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001825 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001826 JDWP::JdwpError error;
1827 mirror::Class* c = DecodeClass(ref_type_id, &error);
1828 if (ref_type_id != 0 && c == nullptr) {
1829 return error;
Elliott Hughes0cf74332012-02-23 23:14:00 -08001830 }
1831
Jeff Haode19a252016-09-14 15:56:35 -07001832 Thread* self = Thread::Current();
1833 StackHandleScope<2> hs(self);
1834 MutableHandle<mirror::Object>
1835 o(hs.NewHandle(Dbg::GetObjectRegistry()->Get<mirror::Object*>(object_id, &error)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08001836 if ((!is_static && o == nullptr) || error != JDWP::ERR_NONE) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001837 return JDWP::ERR_INVALID_OBJECT;
1838 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001839 ArtField* f = FromFieldId(field_id);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001840
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001841 mirror::Class* receiver_class = c;
Andreas Gampefa4333d2017-02-14 11:10:34 -08001842 if (receiver_class == nullptr && o != nullptr) {
Elliott Hughes0cf74332012-02-23 23:14:00 -08001843 receiver_class = o->GetClass();
1844 }
Jeff Haode19a252016-09-14 15:56:35 -07001845
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001846 // TODO: should we give up now if receiver_class is null?
Ian Rogersc0542af2014-09-03 16:16:56 -07001847 if (receiver_class != nullptr && !f->GetDeclaringClass()->IsAssignableFrom(receiver_class)) {
David Sehr709b0702016-10-13 09:12:37 -07001848 LOG(INFO) << "ERR_INVALID_FIELDID: " << f->PrettyField() << " "
1849 << receiver_class->PrettyClass();
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001850 return JDWP::ERR_INVALID_FIELDID;
1851 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001852
Jeff Haode19a252016-09-14 15:56:35 -07001853 // Ensure the field's class is initialized.
1854 Handle<mirror::Class> klass(hs.NewHandle(f->GetDeclaringClass()));
1855 if (!Runtime::Current()->GetClassLinker()->EnsureInitialized(self, klass, true, false)) {
David Sehr709b0702016-10-13 09:12:37 -07001856 LOG(WARNING) << "Not able to initialize class for SetValues: "
1857 << mirror::Class::PrettyClass(klass.Get());
Jeff Haode19a252016-09-14 15:56:35 -07001858 }
1859
Elliott Hughes0cf74332012-02-23 23:14:00 -08001860 // The RI only enforces the static/non-static mismatch in one direction.
1861 // TODO: should we change the tests and check both?
1862 if (is_static) {
1863 if (!f->IsStatic()) {
1864 return JDWP::ERR_INVALID_FIELDID;
1865 }
1866 } else {
1867 if (f->IsStatic()) {
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001868 LOG(WARNING) << "Ignoring non-nullptr receiver for ObjectReference.GetValues"
David Sehr709b0702016-10-13 09:12:37 -07001869 << " on static field " << f->PrettyField();
Elliott Hughes0cf74332012-02-23 23:14:00 -08001870 }
1871 }
jeffhao0dfbb7e2012-11-28 15:26:03 -08001872 if (f->IsStatic()) {
Jeff Haode19a252016-09-14 15:56:35 -07001873 o.Assign(f->GetDeclaringClass());
jeffhao0dfbb7e2012-11-28 15:26:03 -08001874 }
Elliott Hughes0cf74332012-02-23 23:14:00 -08001875
Jeff Haode19a252016-09-14 15:56:35 -07001876 JValue field_value(GetArtFieldValue(f, o.Get()));
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001877 JDWP::JdwpTag tag = BasicTagFromDescriptor(f->GetTypeDescriptor());
Jeff Hao579b0242013-11-18 13:16:49 -08001878 Dbg::OutputJValue(tag, &field_value, pReply);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001879 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001880}
1881
Elliott Hughes88d63092013-01-09 09:55:54 -08001882JDWP::JdwpError Dbg::GetFieldValue(JDWP::ObjectId object_id, JDWP::FieldId field_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001883 JDWP::ExpandBuf* pReply) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001884 return GetFieldValueImpl(0, object_id, field_id, pReply, false);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001885}
1886
Ian Rogersc0542af2014-09-03 16:16:56 -07001887JDWP::JdwpError Dbg::GetStaticFieldValue(JDWP::RefTypeId ref_type_id, JDWP::FieldId field_id,
1888 JDWP::ExpandBuf* pReply) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001889 return GetFieldValueImpl(ref_type_id, 0, field_id, pReply, true);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001890}
1891
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001892static JDWP::JdwpError SetArtFieldValue(ArtField* f, mirror::Object* o, uint64_t value, int width)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001893 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001894 Primitive::Type fieldType = f->GetTypeAsPrimitiveType();
1895 // Debugging only happens at runtime so we know we are not running in a transaction.
1896 static constexpr bool kNoTransactionMode = false;
1897 switch (fieldType) {
1898 case Primitive::kPrimBoolean:
1899 CHECK_EQ(width, 1);
1900 f->SetBoolean<kNoTransactionMode>(o, static_cast<uint8_t>(value));
1901 return JDWP::ERR_NONE;
1902
1903 case Primitive::kPrimByte:
1904 CHECK_EQ(width, 1);
1905 f->SetByte<kNoTransactionMode>(o, static_cast<uint8_t>(value));
1906 return JDWP::ERR_NONE;
1907
1908 case Primitive::kPrimChar:
1909 CHECK_EQ(width, 2);
1910 f->SetChar<kNoTransactionMode>(o, static_cast<uint16_t>(value));
1911 return JDWP::ERR_NONE;
1912
1913 case Primitive::kPrimShort:
1914 CHECK_EQ(width, 2);
1915 f->SetShort<kNoTransactionMode>(o, static_cast<int16_t>(value));
1916 return JDWP::ERR_NONE;
1917
1918 case Primitive::kPrimInt:
1919 case Primitive::kPrimFloat:
1920 CHECK_EQ(width, 4);
1921 // Int and Float must be treated as 32-bit values in JDWP.
1922 f->SetInt<kNoTransactionMode>(o, static_cast<int32_t>(value));
1923 return JDWP::ERR_NONE;
1924
1925 case Primitive::kPrimLong:
1926 case Primitive::kPrimDouble:
1927 CHECK_EQ(width, 8);
1928 // Long and Double must be treated as 64-bit values in JDWP.
1929 f->SetLong<kNoTransactionMode>(o, value);
1930 return JDWP::ERR_NONE;
1931
1932 case Primitive::kPrimNot: {
1933 JDWP::JdwpError error;
1934 mirror::Object* v = Dbg::GetObjectRegistry()->Get<mirror::Object*>(value, &error);
1935 if (error != JDWP::ERR_NONE) {
1936 return JDWP::ERR_INVALID_OBJECT;
1937 }
1938 if (v != nullptr) {
Mathieu Chartier3398c782016-09-30 10:27:43 -07001939 ObjPtr<mirror::Class> field_type;
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001940 {
1941 StackHandleScope<2> hs(Thread::Current());
1942 HandleWrapper<mirror::Object> h_v(hs.NewHandleWrapper(&v));
1943 HandleWrapper<mirror::Object> h_o(hs.NewHandleWrapper(&o));
Vladimir Marko4098a7a2017-11-06 16:00:51 +00001944 field_type = f->ResolveType();
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001945 }
1946 if (!field_type->IsAssignableFrom(v->GetClass())) {
1947 return JDWP::ERR_INVALID_OBJECT;
1948 }
1949 }
1950 f->SetObject<kNoTransactionMode>(o, v);
1951 return JDWP::ERR_NONE;
1952 }
1953
1954 case Primitive::kPrimVoid:
1955 LOG(FATAL) << "Attempt to write to field of type 'void'";
1956 UNREACHABLE();
1957 }
1958 LOG(FATAL) << "Attempt to write to field of unknown type";
1959 UNREACHABLE();
1960}
1961
Elliott Hughes88d63092013-01-09 09:55:54 -08001962static JDWP::JdwpError SetFieldValueImpl(JDWP::ObjectId object_id, JDWP::FieldId field_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001963 uint64_t value, int width, bool is_static)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001964 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001965 JDWP::JdwpError error;
Jeff Haode19a252016-09-14 15:56:35 -07001966 Thread* self = Thread::Current();
1967 StackHandleScope<2> hs(self);
1968 MutableHandle<mirror::Object>
1969 o(hs.NewHandle(Dbg::GetObjectRegistry()->Get<mirror::Object*>(object_id, &error)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08001970 if ((!is_static && o == nullptr) || error != JDWP::ERR_NONE) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001971 return JDWP::ERR_INVALID_OBJECT;
1972 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001973 ArtField* f = FromFieldId(field_id);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001974
Jeff Haode19a252016-09-14 15:56:35 -07001975 // Ensure the field's class is initialized.
1976 Handle<mirror::Class> klass(hs.NewHandle(f->GetDeclaringClass()));
1977 if (!Runtime::Current()->GetClassLinker()->EnsureInitialized(self, klass, true, false)) {
David Sehr709b0702016-10-13 09:12:37 -07001978 LOG(WARNING) << "Not able to initialize class for SetValues: "
1979 << mirror::Class::PrettyClass(klass.Get());
Jeff Haode19a252016-09-14 15:56:35 -07001980 }
1981
Elliott Hughes0cf74332012-02-23 23:14:00 -08001982 // The RI only enforces the static/non-static mismatch in one direction.
1983 // TODO: should we change the tests and check both?
1984 if (is_static) {
1985 if (!f->IsStatic()) {
1986 return JDWP::ERR_INVALID_FIELDID;
1987 }
1988 } else {
1989 if (f->IsStatic()) {
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001990 LOG(WARNING) << "Ignoring non-nullptr receiver for ObjectReference.SetValues"
David Sehr709b0702016-10-13 09:12:37 -07001991 << " on static field " << f->PrettyField();
Elliott Hughes0cf74332012-02-23 23:14:00 -08001992 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001993 }
jeffhao0dfbb7e2012-11-28 15:26:03 -08001994 if (f->IsStatic()) {
Jeff Haode19a252016-09-14 15:56:35 -07001995 o.Assign(f->GetDeclaringClass());
jeffhao0dfbb7e2012-11-28 15:26:03 -08001996 }
Jeff Haode19a252016-09-14 15:56:35 -07001997 return SetArtFieldValue(f, o.Get(), value, width);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001998}
1999
Elliott Hughes88d63092013-01-09 09:55:54 -08002000JDWP::JdwpError Dbg::SetFieldValue(JDWP::ObjectId object_id, JDWP::FieldId field_id, uint64_t value,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002001 int width) {
Elliott Hughes88d63092013-01-09 09:55:54 -08002002 return SetFieldValueImpl(object_id, field_id, value, width, false);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002003}
2004
Elliott Hughes88d63092013-01-09 09:55:54 -08002005JDWP::JdwpError Dbg::SetStaticFieldValue(JDWP::FieldId field_id, uint64_t value, int width) {
2006 return SetFieldValueImpl(0, field_id, value, width, true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002007}
2008
Sebastien Hertzb0b0b492014-09-15 11:27:27 +02002009JDWP::JdwpError Dbg::StringToUtf8(JDWP::ObjectId string_id, std::string* str) {
Ian Rogersc0542af2014-09-03 16:16:56 -07002010 JDWP::JdwpError error;
Sebastien Hertzb0b0b492014-09-15 11:27:27 +02002011 mirror::Object* obj = gRegistry->Get<mirror::Object*>(string_id, &error);
2012 if (error != JDWP::ERR_NONE) {
2013 return error;
2014 }
2015 if (obj == nullptr) {
2016 return JDWP::ERR_INVALID_OBJECT;
2017 }
2018 {
2019 ScopedObjectAccessUnchecked soa(Thread::Current());
Mathieu Chartier0795f232016-09-27 18:43:30 -07002020 ObjPtr<mirror::Class> java_lang_String =
2021 soa.Decode<mirror::Class>(WellKnownClasses::java_lang_String);
Sebastien Hertzb0b0b492014-09-15 11:27:27 +02002022 if (!java_lang_String->IsAssignableFrom(obj->GetClass())) {
2023 // This isn't a string.
2024 return JDWP::ERR_INVALID_STRING;
2025 }
2026 }
2027 *str = obj->AsString()->ToModifiedUtf8();
2028 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002029}
2030
Jeff Hao579b0242013-11-18 13:16:49 -08002031void Dbg::OutputJValue(JDWP::JdwpTag tag, const JValue* return_value, JDWP::ExpandBuf* pReply) {
2032 if (IsPrimitiveTag(tag)) {
2033 expandBufAdd1(pReply, tag);
2034 if (tag == JDWP::JT_BOOLEAN || tag == JDWP::JT_BYTE) {
2035 expandBufAdd1(pReply, return_value->GetI());
2036 } else if (tag == JDWP::JT_CHAR || tag == JDWP::JT_SHORT) {
2037 expandBufAdd2BE(pReply, return_value->GetI());
2038 } else if (tag == JDWP::JT_FLOAT || tag == JDWP::JT_INT) {
2039 expandBufAdd4BE(pReply, return_value->GetI());
2040 } else if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
2041 expandBufAdd8BE(pReply, return_value->GetJ());
2042 } else {
2043 CHECK_EQ(tag, JDWP::JT_VOID);
2044 }
2045 } else {
Ian Rogers98379392014-02-24 16:53:16 -08002046 ScopedObjectAccessUnchecked soa(Thread::Current());
Jeff Hao579b0242013-11-18 13:16:49 -08002047 mirror::Object* value = return_value->GetL();
Ian Rogers98379392014-02-24 16:53:16 -08002048 expandBufAdd1(pReply, TagFromObject(soa, value));
Jeff Hao579b0242013-11-18 13:16:49 -08002049 expandBufAddObjectId(pReply, gRegistry->Add(value));
2050 }
2051}
2052
Ian Rogersc0542af2014-09-03 16:16:56 -07002053JDWP::JdwpError Dbg::GetThreadName(JDWP::ObjectId thread_id, std::string* name) {
jeffhaoa77f0f62012-12-05 17:19:31 -08002054 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002055 JDWP::JdwpError error;
Roland Levillain4b8f1ec2015-08-26 18:34:03 +01002056 DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002057 if (error != JDWP::ERR_NONE && error != JDWP::ERR_THREAD_NOT_ALIVE) {
2058 return error;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08002059 }
Elliott Hughes221229c2013-01-08 18:17:50 -08002060
2061 // We still need to report the zombie threads' names, so we can't just call Thread::GetThreadName.
Ian Rogersc0542af2014-09-03 16:16:56 -07002062 mirror::Object* thread_object = gRegistry->Get<mirror::Object*>(thread_id, &error);
2063 CHECK(thread_object != nullptr) << error;
Mathieu Chartierc7853442015-03-27 14:35:38 -07002064 ArtField* java_lang_Thread_name_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08002065 jni::DecodeArtField(WellKnownClasses::java_lang_Thread_name);
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07002066 ObjPtr<mirror::String> s(java_lang_Thread_name_field->GetObject(thread_object)->AsString());
Ian Rogersc0542af2014-09-03 16:16:56 -07002067 if (s != nullptr) {
2068 *name = s->ToModifiedUtf8();
Elliott Hughes221229c2013-01-08 18:17:50 -08002069 }
2070 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002071}
2072
Elliott Hughes221229c2013-01-08 18:17:50 -08002073JDWP::JdwpError Dbg::GetThreadGroup(JDWP::ObjectId thread_id, JDWP::ExpandBuf* pReply) {
Sebastien Hertza06430c2014-09-15 19:21:30 +02002074 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002075 JDWP::JdwpError error;
2076 mirror::Object* thread_object = gRegistry->Get<mirror::Object*>(thread_id, &error);
2077 if (error != JDWP::ERR_NONE) {
Elliott Hughes2435a572012-02-17 16:07:41 -08002078 return JDWP::ERR_INVALID_OBJECT;
2079 }
Mathieu Chartier268764d2016-09-13 12:09:38 -07002080 ScopedAssertNoThreadSuspension ants("Debugger: GetThreadGroup");
Elliott Hughes2435a572012-02-17 16:07:41 -08002081 // Okay, so it's an object, but is it actually a thread?
Roland Levillain4b8f1ec2015-08-26 18:34:03 +01002082 DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002083 if (error == JDWP::ERR_THREAD_NOT_ALIVE) {
2084 // Zombie threads are in the null group.
2085 expandBufAddObjectId(pReply, JDWP::ObjectId(0));
Sebastien Hertz52d131d2014-03-13 16:17:40 +01002086 error = JDWP::ERR_NONE;
2087 } else if (error == JDWP::ERR_NONE) {
Mathieu Chartier0795f232016-09-27 18:43:30 -07002088 ObjPtr<mirror::Class> c = soa.Decode<mirror::Class>(WellKnownClasses::java_lang_Thread);
Sebastien Hertz52d131d2014-03-13 16:17:40 +01002089 CHECK(c != nullptr);
Andreas Gampe08883de2016-11-08 13:20:52 -08002090 ArtField* f = jni::DecodeArtField(WellKnownClasses::java_lang_Thread_group);
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07002091 CHECK(f != nullptr);
Mathieu Chartier3398c782016-09-30 10:27:43 -07002092 ObjPtr<mirror::Object> group = f->GetObject(thread_object);
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07002093 CHECK(group != nullptr);
Sebastien Hertz52d131d2014-03-13 16:17:40 +01002094 JDWP::ObjectId thread_group_id = gRegistry->Add(group);
2095 expandBufAddObjectId(pReply, thread_group_id);
Elliott Hughes221229c2013-01-08 18:17:50 -08002096 }
Sebastien Hertz52d131d2014-03-13 16:17:40 +01002097 return error;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002098}
2099
Sebastien Hertza06430c2014-09-15 19:21:30 +02002100static mirror::Object* DecodeThreadGroup(ScopedObjectAccessUnchecked& soa,
2101 JDWP::ObjectId thread_group_id, JDWP::JdwpError* error)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002102 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz6995c602014-09-09 12:10:13 +02002103 mirror::Object* thread_group = Dbg::GetObjectRegistry()->Get<mirror::Object*>(thread_group_id,
2104 error);
Sebastien Hertza06430c2014-09-15 19:21:30 +02002105 if (*error != JDWP::ERR_NONE) {
2106 return nullptr;
2107 }
2108 if (thread_group == nullptr) {
2109 *error = JDWP::ERR_INVALID_OBJECT;
2110 return nullptr;
2111 }
Mathieu Chartier0795f232016-09-27 18:43:30 -07002112 ObjPtr<mirror::Class> c =
2113 soa.Decode<mirror::Class>(WellKnownClasses::java_lang_ThreadGroup);
Ian Rogers98379392014-02-24 16:53:16 -08002114 CHECK(c != nullptr);
Sebastien Hertza06430c2014-09-15 19:21:30 +02002115 if (!c->IsAssignableFrom(thread_group->GetClass())) {
2116 // This is not a java.lang.ThreadGroup.
2117 *error = JDWP::ERR_INVALID_THREAD_GROUP;
2118 return nullptr;
2119 }
2120 *error = JDWP::ERR_NONE;
2121 return thread_group;
2122}
2123
2124JDWP::JdwpError Dbg::GetThreadGroupName(JDWP::ObjectId thread_group_id, JDWP::ExpandBuf* pReply) {
2125 ScopedObjectAccessUnchecked soa(Thread::Current());
2126 JDWP::JdwpError error;
2127 mirror::Object* thread_group = DecodeThreadGroup(soa, thread_group_id, &error);
2128 if (error != JDWP::ERR_NONE) {
2129 return error;
2130 }
Mathieu Chartier268764d2016-09-13 12:09:38 -07002131 ScopedAssertNoThreadSuspension ants("Debugger: GetThreadGroupName");
Andreas Gampe08883de2016-11-08 13:20:52 -08002132 ArtField* f = jni::DecodeArtField(WellKnownClasses::java_lang_ThreadGroup_name);
Ian Rogersc0542af2014-09-03 16:16:56 -07002133 CHECK(f != nullptr);
Mathieu Chartier3398c782016-09-30 10:27:43 -07002134 ObjPtr<mirror::String> s = f->GetObject(thread_group)->AsString();
Sebastien Hertza06430c2014-09-15 19:21:30 +02002135
2136 std::string thread_group_name(s->ToModifiedUtf8());
2137 expandBufAddUtf8String(pReply, thread_group_name);
2138 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002139}
2140
Sebastien Hertza06430c2014-09-15 19:21:30 +02002141JDWP::JdwpError Dbg::GetThreadGroupParent(JDWP::ObjectId thread_group_id, JDWP::ExpandBuf* pReply) {
Ian Rogers98379392014-02-24 16:53:16 -08002142 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002143 JDWP::JdwpError error;
Sebastien Hertza06430c2014-09-15 19:21:30 +02002144 mirror::Object* thread_group = DecodeThreadGroup(soa, thread_group_id, &error);
2145 if (error != JDWP::ERR_NONE) {
2146 return error;
2147 }
Mathieu Chartier3398c782016-09-30 10:27:43 -07002148 ObjPtr<mirror::Object> parent;
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07002149 {
Mathieu Chartier268764d2016-09-13 12:09:38 -07002150 ScopedAssertNoThreadSuspension ants("Debugger: GetThreadGroupParent");
Andreas Gampe08883de2016-11-08 13:20:52 -08002151 ArtField* f = jni::DecodeArtField(WellKnownClasses::java_lang_ThreadGroup_parent);
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07002152 CHECK(f != nullptr);
2153 parent = f->GetObject(thread_group);
2154 }
Sebastien Hertza06430c2014-09-15 19:21:30 +02002155 JDWP::ObjectId parent_group_id = gRegistry->Add(parent);
2156 expandBufAddObjectId(pReply, parent_group_id);
2157 return JDWP::ERR_NONE;
2158}
2159
Andreas Gampe08883de2016-11-08 13:20:52 -08002160static void GetChildThreadGroups(mirror::Object* thread_group,
Sebastien Hertza06430c2014-09-15 19:21:30 +02002161 std::vector<JDWP::ObjectId>* child_thread_group_ids)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002162 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertza06430c2014-09-15 19:21:30 +02002163 CHECK(thread_group != nullptr);
2164
Przemyslaw Szczepaniak464595f2015-11-24 11:59:59 +00002165 // Get the int "ngroups" count of this thread group...
Andreas Gampe08883de2016-11-08 13:20:52 -08002166 ArtField* ngroups_field = jni::DecodeArtField(WellKnownClasses::java_lang_ThreadGroup_ngroups);
Przemyslaw Szczepaniak464595f2015-11-24 11:59:59 +00002167 CHECK(ngroups_field != nullptr);
2168 const int32_t size = ngroups_field->GetInt(thread_group);
2169 if (size == 0) {
2170 return;
Sebastien Hertze49e1952014-10-13 11:27:13 +02002171 }
Sebastien Hertza06430c2014-09-15 19:21:30 +02002172
Przemyslaw Szczepaniak464595f2015-11-24 11:59:59 +00002173 // Get the ThreadGroup[] "groups" out of this thread group...
Andreas Gampe08883de2016-11-08 13:20:52 -08002174 ArtField* groups_field = jni::DecodeArtField(WellKnownClasses::java_lang_ThreadGroup_groups);
Mathieu Chartier3398c782016-09-30 10:27:43 -07002175 ObjPtr<mirror::Object> groups_array = groups_field->GetObject(thread_group);
Przemyslaw Szczepaniak464595f2015-11-24 11:59:59 +00002176
2177 CHECK(groups_array != nullptr);
2178 CHECK(groups_array->IsObjectArray());
2179
Mathieu Chartier3398c782016-09-30 10:27:43 -07002180 ObjPtr<mirror::ObjectArray<mirror::Object>> groups_array_as_array =
Przemyslaw Szczepaniak464595f2015-11-24 11:59:59 +00002181 groups_array->AsObjectArray<mirror::Object>();
Sebastien Hertza06430c2014-09-15 19:21:30 +02002182
2183 // Copy the first 'size' elements out of the array into the result.
Sebastien Hertz6995c602014-09-09 12:10:13 +02002184 ObjectRegistry* registry = Dbg::GetObjectRegistry();
Sebastien Hertza06430c2014-09-15 19:21:30 +02002185 for (int32_t i = 0; i < size; ++i) {
Przemyslaw Szczepaniak464595f2015-11-24 11:59:59 +00002186 child_thread_group_ids->push_back(registry->Add(groups_array_as_array->Get(i)));
Sebastien Hertza06430c2014-09-15 19:21:30 +02002187 }
2188}
2189
2190JDWP::JdwpError Dbg::GetThreadGroupChildren(JDWP::ObjectId thread_group_id,
2191 JDWP::ExpandBuf* pReply) {
2192 ScopedObjectAccessUnchecked soa(Thread::Current());
2193 JDWP::JdwpError error;
2194 mirror::Object* thread_group = DecodeThreadGroup(soa, thread_group_id, &error);
2195 if (error != JDWP::ERR_NONE) {
2196 return error;
2197 }
2198
2199 // Add child threads.
2200 {
2201 std::vector<JDWP::ObjectId> child_thread_ids;
2202 GetThreads(thread_group, &child_thread_ids);
2203 expandBufAdd4BE(pReply, child_thread_ids.size());
2204 for (JDWP::ObjectId child_thread_id : child_thread_ids) {
2205 expandBufAddObjectId(pReply, child_thread_id);
2206 }
2207 }
2208
2209 // Add child thread groups.
2210 {
2211 std::vector<JDWP::ObjectId> child_thread_groups_ids;
Andreas Gampe08883de2016-11-08 13:20:52 -08002212 GetChildThreadGroups(thread_group, &child_thread_groups_ids);
Sebastien Hertza06430c2014-09-15 19:21:30 +02002213 expandBufAdd4BE(pReply, child_thread_groups_ids.size());
2214 for (JDWP::ObjectId child_thread_group_id : child_thread_groups_ids) {
2215 expandBufAddObjectId(pReply, child_thread_group_id);
2216 }
2217 }
2218
2219 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002220}
2221
2222JDWP::ObjectId Dbg::GetSystemThreadGroupId() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002223 ScopedObjectAccessUnchecked soa(Thread::Current());
Andreas Gampe08883de2016-11-08 13:20:52 -08002224 ArtField* f = jni::DecodeArtField(WellKnownClasses::java_lang_ThreadGroup_systemThreadGroup);
Mathieu Chartier3398c782016-09-30 10:27:43 -07002225 ObjPtr<mirror::Object> group = f->GetObject(f->GetDeclaringClass());
Ian Rogers365c1022012-06-22 15:05:28 -07002226 return gRegistry->Add(group);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002227}
2228
Jeff Hao920af3e2013-08-28 15:46:38 -07002229JDWP::JdwpThreadStatus Dbg::ToJdwpThreadStatus(ThreadState state) {
2230 switch (state) {
2231 case kBlocked:
2232 return JDWP::TS_MONITOR;
2233 case kNative:
2234 case kRunnable:
2235 case kSuspended:
2236 return JDWP::TS_RUNNING;
2237 case kSleeping:
2238 return JDWP::TS_SLEEPING;
2239 case kStarting:
2240 case kTerminated:
2241 return JDWP::TS_ZOMBIE;
2242 case kTimedWaiting:
Alex Light77fee872017-09-05 14:51:49 -07002243 case kWaitingForTaskProcessor:
2244 case kWaitingForLockInflation:
Sebastien Hertzbae182c2013-12-17 10:42:03 +01002245 case kWaitingForCheckPointsToRun:
Jeff Hao920af3e2013-08-28 15:46:38 -07002246 case kWaitingForDebuggerSend:
2247 case kWaitingForDebuggerSuspension:
2248 case kWaitingForDebuggerToAttach:
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002249 case kWaitingForDeoptimization:
Jeff Hao920af3e2013-08-28 15:46:38 -07002250 case kWaitingForGcToComplete:
Mathieu Chartierb43390c2015-05-12 10:47:11 -07002251 case kWaitingForGetObjectsAllocated:
Jeff Hao920af3e2013-08-28 15:46:38 -07002252 case kWaitingForJniOnLoad:
Sebastien Hertzbae182c2013-12-17 10:42:03 +01002253 case kWaitingForMethodTracingStart:
Jeff Hao920af3e2013-08-28 15:46:38 -07002254 case kWaitingForSignalCatcherOutput:
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -08002255 case kWaitingForVisitObjects:
Jeff Hao920af3e2013-08-28 15:46:38 -07002256 case kWaitingInMainDebuggerLoop:
2257 case kWaitingInMainSignalCatcherLoop:
2258 case kWaitingPerformingGc:
Mathieu Chartier90ef3db2015-08-04 15:19:41 -07002259 case kWaitingWeakGcRootRead:
Hiroshi Yamauchi76f55b02015-08-21 16:10:39 -07002260 case kWaitingForGcThreadFlip:
Jeff Hao920af3e2013-08-28 15:46:38 -07002261 case kWaiting:
2262 return JDWP::TS_WAIT;
2263 // Don't add a 'default' here so the compiler can spot incompatible enum changes.
2264 }
2265 LOG(FATAL) << "Unknown thread state: " << state;
2266 return JDWP::TS_ZOMBIE;
2267}
2268
Sebastien Hertz52d131d2014-03-13 16:17:40 +01002269JDWP::JdwpError Dbg::GetThreadStatus(JDWP::ObjectId thread_id, JDWP::JdwpThreadStatus* pThreadStatus,
2270 JDWP::JdwpSuspendStatus* pSuspendStatus) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002271 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes499c5132011-11-17 14:55:11 -08002272
Elliott Hughes9e0c1752013-01-09 14:02:58 -08002273 *pSuspendStatus = JDWP::SUSPEND_STATUS_NOT_SUSPENDED;
2274
Ian Rogersc0542af2014-09-03 16:16:56 -07002275 JDWP::JdwpError error;
2276 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002277 if (error != JDWP::ERR_NONE) {
2278 if (error == JDWP::ERR_THREAD_NOT_ALIVE) {
2279 *pThreadStatus = JDWP::TS_ZOMBIE;
Elliott Hughes221229c2013-01-08 18:17:50 -08002280 return JDWP::ERR_NONE;
2281 }
2282 return error;
Elliott Hughes499c5132011-11-17 14:55:11 -08002283 }
2284
Elliott Hughes9e0c1752013-01-09 14:02:58 -08002285 if (IsSuspendedForDebugger(soa, thread)) {
2286 *pSuspendStatus = JDWP::SUSPEND_STATUS_SUSPENDED;
Elliott Hughes499c5132011-11-17 14:55:11 -08002287 }
2288
Jeff Hao920af3e2013-08-28 15:46:38 -07002289 *pThreadStatus = ToJdwpThreadStatus(thread->GetState());
Elliott Hughes221229c2013-01-08 18:17:50 -08002290 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002291}
2292
Elliott Hughes221229c2013-01-08 18:17:50 -08002293JDWP::JdwpError Dbg::GetThreadDebugSuspendCount(JDWP::ObjectId thread_id, JDWP::ExpandBuf* pReply) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002294 ScopedObjectAccess soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002295 JDWP::JdwpError error;
2296 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002297 if (error != JDWP::ERR_NONE) {
2298 return error;
Elliott Hughes2435a572012-02-17 16:07:41 -08002299 }
Ian Rogers50b35e22012-10-04 10:09:15 -07002300 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002301 expandBufAdd4BE(pReply, thread->GetDebugSuspendCount());
Elliott Hughes2435a572012-02-17 16:07:41 -08002302 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002303}
2304
Elliott Hughesf9501702013-01-11 11:22:27 -08002305JDWP::JdwpError Dbg::Interrupt(JDWP::ObjectId thread_id) {
2306 ScopedObjectAccess soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002307 JDWP::JdwpError error;
2308 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughesf9501702013-01-11 11:22:27 -08002309 if (error != JDWP::ERR_NONE) {
2310 return error;
2311 }
Ian Rogersdd7624d2014-03-14 17:43:00 -07002312 thread->Interrupt(soa.Self());
Elliott Hughesf9501702013-01-11 11:22:27 -08002313 return JDWP::ERR_NONE;
2314}
2315
Andreas Gampe08883de2016-11-08 13:20:52 -08002316static bool IsInDesiredThreadGroup(mirror::Object* desired_thread_group, mirror::Object* peer)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002317 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz070f7322014-09-09 12:08:49 +02002318 // Do we want threads from all thread groups?
2319 if (desired_thread_group == nullptr) {
2320 return true;
2321 }
Andreas Gampe08883de2016-11-08 13:20:52 -08002322 ArtField* thread_group_field = jni::DecodeArtField(WellKnownClasses::java_lang_Thread_group);
Sebastien Hertz070f7322014-09-09 12:08:49 +02002323 DCHECK(thread_group_field != nullptr);
Mathieu Chartier3398c782016-09-30 10:27:43 -07002324 ObjPtr<mirror::Object> group = thread_group_field->GetObject(peer);
Sebastien Hertz070f7322014-09-09 12:08:49 +02002325 return (group == desired_thread_group);
2326}
2327
Sebastien Hertza06430c2014-09-15 19:21:30 +02002328void Dbg::GetThreads(mirror::Object* thread_group, std::vector<JDWP::ObjectId>* thread_ids) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002329 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz070f7322014-09-09 12:08:49 +02002330 std::list<Thread*> all_threads_list;
2331 {
2332 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
2333 all_threads_list = Runtime::Current()->GetThreadList()->GetList();
2334 }
2335 for (Thread* t : all_threads_list) {
2336 if (t == Dbg::GetDebugThread()) {
2337 // Skip the JDWP thread. Some debuggers get bent out of shape when they can't suspend and
2338 // query all threads, so it's easier if we just don't tell them about this thread.
2339 continue;
2340 }
2341 if (t->IsStillStarting()) {
2342 // This thread is being started (and has been registered in the thread list). However, it is
2343 // not completely started yet so we must ignore it.
2344 continue;
2345 }
Nicolas Geoffraycafa0812017-02-15 18:27:34 +00002346 mirror::Object* peer = t->GetPeerFromOtherThread();
Sebastien Hertz070f7322014-09-09 12:08:49 +02002347 if (peer == nullptr) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002348 // 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 +02002349 // this thread yet.
2350 // TODO: if we identified threads to the debugger by their Thread*
2351 // rather than their peer's mirror::Object*, we could fix this.
2352 // Doing so might help us report ZOMBIE threads too.
2353 continue;
2354 }
Andreas Gampe08883de2016-11-08 13:20:52 -08002355 if (IsInDesiredThreadGroup(thread_group, peer)) {
Sebastien Hertz070f7322014-09-09 12:08:49 +02002356 thread_ids->push_back(gRegistry->Add(peer));
2357 }
2358 }
Elliott Hughescaf76542012-06-28 16:08:22 -07002359}
Elliott Hughesa2155262011-11-16 16:26:58 -08002360
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002361static int GetStackDepth(Thread* thread) REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002362 struct CountStackDepthVisitor : public StackVisitor {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002363 explicit CountStackDepthVisitor(Thread* thread_in)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01002364 : StackVisitor(thread_in, nullptr, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
2365 depth(0) {}
Ian Rogers0399dde2012-06-06 17:09:28 -07002366
Elliott Hughes64f574f2013-02-20 14:57:12 -08002367 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2368 // annotalysis.
Andreas Gampefa6a1b02018-09-07 08:11:55 -07002369 bool VisitFrame() override NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07002370 if (!GetMethod()->IsRuntimeMethod()) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -08002371 ++depth;
2372 }
Elliott Hughes530fa002012-03-12 11:44:49 -07002373 return true;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08002374 }
2375 size_t depth;
2376 };
Elliott Hughes08fc03a2012-06-26 17:34:00 -07002377
Ian Rogers7a22fa62013-01-23 12:16:16 -08002378 CountStackDepthVisitor visitor(thread);
Ian Rogers0399dde2012-06-06 17:09:28 -07002379 visitor.WalkStack();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08002380 return visitor.depth;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002381}
2382
Ian Rogersc0542af2014-09-03 16:16:56 -07002383JDWP::JdwpError Dbg::GetThreadFrameCount(JDWP::ObjectId thread_id, size_t* result) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002384 ScopedObjectAccess soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002385 JDWP::JdwpError error;
2386 *result = 0;
2387 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002388 if (error != JDWP::ERR_NONE) {
2389 return error;
2390 }
Elliott Hughesf15f4a02013-01-09 10:09:38 -08002391 if (!IsSuspendedForDebugger(soa, thread)) {
2392 return JDWP::ERR_THREAD_NOT_SUSPENDED;
2393 }
Ian Rogersc0542af2014-09-03 16:16:56 -07002394 *result = GetStackDepth(thread);
Elliott Hughes221229c2013-01-08 18:17:50 -08002395 return JDWP::ERR_NONE;
Elliott Hughes86964332012-02-15 19:37:42 -08002396}
2397
Ian Rogers306057f2012-11-26 12:45:53 -08002398JDWP::JdwpError Dbg::GetThreadFrames(JDWP::ObjectId thread_id, size_t start_frame,
2399 size_t frame_count, JDWP::ExpandBuf* buf) {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002400 class GetFrameVisitor : public StackVisitor {
2401 public:
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002402 GetFrameVisitor(Thread* thread, size_t start_frame_in, size_t frame_count_in,
2403 JDWP::ExpandBuf* buf_in)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002404 REQUIRES_SHARED(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01002405 : StackVisitor(thread, nullptr, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
2406 depth_(0),
2407 start_frame_(start_frame_in),
2408 frame_count_(frame_count_in),
2409 buf_(buf_in) {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002410 expandBufAdd4BE(buf_, frame_count_);
Elliott Hughes03181a82011-11-17 17:22:21 -08002411 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002412
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01002413 bool VisitFrame() override REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002414 if (GetMethod()->IsRuntimeMethod()) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07002415 return true; // The debugger can't do anything useful with a frame that has no Method*.
Elliott Hughes03181a82011-11-17 17:22:21 -08002416 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002417 if (depth_ >= start_frame_ + frame_count_) {
Elliott Hughes530fa002012-03-12 11:44:49 -07002418 return false;
Elliott Hughes03181a82011-11-17 17:22:21 -08002419 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002420 if (depth_ >= start_frame_) {
2421 JDWP::FrameId frame_id(GetFrameId());
2422 JDWP::JdwpLocation location;
Sebastien Hertz6995c602014-09-09 12:10:13 +02002423 SetJdwpLocation(&location, GetMethod(), GetDexPc());
Ian Rogersef7d42f2014-01-06 12:55:46 -08002424 VLOG(jdwp) << StringPrintf(" Frame %3zd: id=%3" PRIu64 " ", depth_, frame_id) << location;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002425 expandBufAdd8BE(buf_, frame_id);
2426 expandBufAddLocation(buf_, location);
2427 }
2428 ++depth_;
Elliott Hughes530fa002012-03-12 11:44:49 -07002429 return true;
Elliott Hughes03181a82011-11-17 17:22:21 -08002430 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002431
2432 private:
2433 size_t depth_;
2434 const size_t start_frame_;
2435 const size_t frame_count_;
2436 JDWP::ExpandBuf* buf_;
Elliott Hughes03181a82011-11-17 17:22:21 -08002437 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002438
2439 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002440 JDWP::JdwpError error;
2441 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002442 if (error != JDWP::ERR_NONE) {
2443 return error;
2444 }
Elliott Hughesf15f4a02013-01-09 10:09:38 -08002445 if (!IsSuspendedForDebugger(soa, thread)) {
2446 return JDWP::ERR_THREAD_NOT_SUSPENDED;
2447 }
Ian Rogers7a22fa62013-01-23 12:16:16 -08002448 GetFrameVisitor visitor(thread, start_frame, frame_count, buf);
Ian Rogers0399dde2012-06-06 17:09:28 -07002449 visitor.WalkStack();
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002450 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002451}
2452
2453JDWP::ObjectId Dbg::GetThreadSelfId() {
Sebastien Hertz6995c602014-09-09 12:10:13 +02002454 return GetThreadId(Thread::Current());
2455}
2456
2457JDWP::ObjectId Dbg::GetThreadId(Thread* thread) {
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07002458 ScopedObjectAccessUnchecked soa(Thread::Current());
Nicolas Geoffraycafa0812017-02-15 18:27:34 +00002459 return gRegistry->Add(thread->GetPeerFromOtherThread());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002460}
2461
Elliott Hughes475fc232011-10-25 15:00:35 -07002462void Dbg::SuspendVM() {
Hiroshi Yamauchi8f95cf32016-04-19 11:14:06 -07002463 // Avoid a deadlock between GC and debugger where GC gets suspended during GC. b/25800335.
2464 gc::ScopedGCCriticalSection gcs(Thread::Current(),
2465 gc::kGcCauseDebugger,
2466 gc::kCollectorTypeDebugger);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002467 Runtime::Current()->GetThreadList()->SuspendAllForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002468}
2469
2470void Dbg::ResumeVM() {
Sebastien Hertz253fa552014-10-14 17:27:15 +02002471 Runtime::Current()->GetThreadList()->ResumeAllForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002472}
2473
Elliott Hughes221229c2013-01-08 18:17:50 -08002474JDWP::JdwpError Dbg::SuspendThread(JDWP::ObjectId thread_id, bool request_suspension) {
Ian Rogersf3d874c2014-07-17 18:52:42 -07002475 Thread* self = Thread::Current();
Ian Rogersc0542af2014-09-03 16:16:56 -07002476 ScopedLocalRef<jobject> peer(self->GetJniEnv(), nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002477 {
Ian Rogersf3d874c2014-07-17 18:52:42 -07002478 ScopedObjectAccess soa(self);
Ian Rogersc0542af2014-09-03 16:16:56 -07002479 JDWP::JdwpError error;
2480 peer.reset(soa.AddLocalReference<jobject>(gRegistry->Get<mirror::Object*>(thread_id, &error)));
Elliott Hughes4e235312011-12-02 11:34:15 -08002481 }
Ian Rogersc0542af2014-09-03 16:16:56 -07002482 if (peer.get() == nullptr) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002483 return JDWP::ERR_THREAD_NOT_ALIVE;
2484 }
Ian Rogers4ad5cd32014-11-11 23:08:07 -08002485 // Suspend thread to build stack trace.
Elliott Hughesf327e072013-01-09 16:01:26 -08002486 bool timed_out;
Brian Carlstromba32de42014-08-27 23:43:46 -07002487 ThreadList* thread_list = Runtime::Current()->GetThreadList();
Sebastien Hertzcdd798d2017-04-18 18:28:51 +02002488 Thread* thread = thread_list->SuspendThreadByPeer(peer.get(),
2489 request_suspension,
Alex Light46f93402017-06-29 11:59:50 -07002490 SuspendReason::kForDebugger,
Brian Carlstromba32de42014-08-27 23:43:46 -07002491 &timed_out);
Ian Rogersc0542af2014-09-03 16:16:56 -07002492 if (thread != nullptr) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002493 return JDWP::ERR_NONE;
Elliott Hughesf327e072013-01-09 16:01:26 -08002494 } else if (timed_out) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002495 return JDWP::ERR_INTERNAL;
2496 } else {
2497 return JDWP::ERR_THREAD_NOT_ALIVE;
2498 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002499}
2500
Elliott Hughes221229c2013-01-08 18:17:50 -08002501void Dbg::ResumeThread(JDWP::ObjectId thread_id) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002502 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002503 JDWP::JdwpError error;
2504 mirror::Object* peer = gRegistry->Get<mirror::Object*>(thread_id, &error);
2505 CHECK(peer != nullptr) << error;
jeffhaoa77f0f62012-12-05 17:19:31 -08002506 Thread* thread;
2507 {
2508 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
2509 thread = Thread::FromManagedThread(soa, peer);
2510 }
Ian Rogersc0542af2014-09-03 16:16:56 -07002511 if (thread == nullptr) {
Elliott Hughes4e235312011-12-02 11:34:15 -08002512 LOG(WARNING) << "No such thread for resume: " << peer;
2513 return;
2514 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002515 bool needs_resume;
2516 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002517 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Sebastien Hertz70d60272017-04-14 14:18:36 +02002518 needs_resume = thread->GetDebugSuspendCount() > 0;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002519 }
2520 if (needs_resume) {
Alex Light88fd7202017-06-30 08:31:59 -07002521 bool resumed = Runtime::Current()->GetThreadList()->Resume(thread, SuspendReason::kForDebugger);
2522 DCHECK(resumed);
Elliott Hughes546b9862012-06-20 16:06:13 -07002523 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002524}
2525
2526void Dbg::SuspendSelf() {
Elliott Hughes475fc232011-10-25 15:00:35 -07002527 Runtime::Current()->GetThreadList()->SuspendSelfForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002528}
2529
Ian Rogers0399dde2012-06-06 17:09:28 -07002530struct GetThisVisitor : public StackVisitor {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002531 GetThisVisitor(Thread* thread, Context* context, JDWP::FrameId frame_id_in)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002532 REQUIRES_SHARED(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01002533 : StackVisitor(thread, context, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
2534 this_object(nullptr),
2535 frame_id(frame_id_in) {}
Ian Rogers0399dde2012-06-06 17:09:28 -07002536
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002537 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2538 // annotalysis.
Andreas Gampefa6a1b02018-09-07 08:11:55 -07002539 bool VisitFrame() override NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002540 if (frame_id != GetFrameId()) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002541 return true; // continue
Ian Rogers0399dde2012-06-06 17:09:28 -07002542 } else {
Ian Rogers62d6c772013-02-27 08:32:07 -08002543 this_object = GetThisObject();
2544 return false;
Ian Rogers0399dde2012-06-06 17:09:28 -07002545 }
Elliott Hughes86b00102011-12-05 17:54:26 -08002546 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002547
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002548 mirror::Object* this_object;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002549 JDWP::FrameId frame_id;
Ian Rogers0399dde2012-06-06 17:09:28 -07002550};
2551
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002552JDWP::JdwpError Dbg::GetThisObject(JDWP::ObjectId thread_id, JDWP::FrameId frame_id,
2553 JDWP::ObjectId* result) {
2554 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz69206392015-04-07 15:54:25 +02002555 JDWP::JdwpError error;
2556 Thread* thread = DecodeThread(soa, thread_id, &error);
2557 if (error != JDWP::ERR_NONE) {
2558 return error;
2559 }
2560 if (!IsSuspendedForDebugger(soa, thread)) {
2561 return JDWP::ERR_THREAD_NOT_SUSPENDED;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002562 }
Ian Rogers700a4022014-05-19 16:49:03 -07002563 std::unique_ptr<Context> context(Context::Create());
Ian Rogers7a22fa62013-01-23 12:16:16 -08002564 GetThisVisitor visitor(thread, context.get(), frame_id);
Ian Rogers0399dde2012-06-06 17:09:28 -07002565 visitor.WalkStack();
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002566 *result = gRegistry->Add(visitor.this_object);
2567 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002568}
2569
Sebastien Hertz8009f392014-09-01 17:07:11 +02002570// Walks the stack until we find the frame with the given FrameId.
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01002571class FindFrameVisitor final : public StackVisitor {
Sebastien Hertz8009f392014-09-01 17:07:11 +02002572 public:
2573 FindFrameVisitor(Thread* thread, Context* context, JDWP::FrameId frame_id)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002574 REQUIRES_SHARED(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01002575 : StackVisitor(thread, context, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
2576 frame_id_(frame_id),
2577 error_(JDWP::ERR_INVALID_FRAMEID) {}
Ian Rogersca190662012-06-26 15:45:57 -07002578
Sebastien Hertz8009f392014-09-01 17:07:11 +02002579 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2580 // annotalysis.
Andreas Gampefa6a1b02018-09-07 08:11:55 -07002581 bool VisitFrame() override NO_THREAD_SAFETY_ANALYSIS {
Sebastien Hertz8009f392014-09-01 17:07:11 +02002582 if (GetFrameId() != frame_id_) {
2583 return true; // Not our frame, carry on.
Ian Rogers0399dde2012-06-06 17:09:28 -07002584 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07002585 ArtMethod* m = GetMethod();
Sebastien Hertz8009f392014-09-01 17:07:11 +02002586 if (m->IsNative()) {
2587 // We can't read/write local value from/into native method.
2588 error_ = JDWP::ERR_OPAQUE_FRAME;
2589 } else {
2590 // We found our frame.
2591 error_ = JDWP::ERR_NONE;
2592 }
2593 return false;
2594 }
2595
2596 JDWP::JdwpError GetError() const {
2597 return error_;
2598 }
2599
2600 private:
2601 const JDWP::FrameId frame_id_;
2602 JDWP::JdwpError error_;
Sebastien Hertz26f72862015-09-15 09:52:07 +02002603
2604 DISALLOW_COPY_AND_ASSIGN(FindFrameVisitor);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002605};
2606
2607JDWP::JdwpError Dbg::GetLocalValues(JDWP::Request* request, JDWP::ExpandBuf* pReply) {
2608 JDWP::ObjectId thread_id = request->ReadThreadId();
2609 JDWP::FrameId frame_id = request->ReadFrameId();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002610
2611 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz69206392015-04-07 15:54:25 +02002612 JDWP::JdwpError error;
2613 Thread* thread = DecodeThread(soa, thread_id, &error);
2614 if (error != JDWP::ERR_NONE) {
2615 return error;
2616 }
2617 if (!IsSuspendedForDebugger(soa, thread)) {
2618 return JDWP::ERR_THREAD_NOT_SUSPENDED;
Elliott Hughes221229c2013-01-08 18:17:50 -08002619 }
Sebastien Hertz8009f392014-09-01 17:07:11 +02002620 // Find the frame with the given frame_id.
Ian Rogers700a4022014-05-19 16:49:03 -07002621 std::unique_ptr<Context> context(Context::Create());
Sebastien Hertz8009f392014-09-01 17:07:11 +02002622 FindFrameVisitor visitor(thread, context.get(), frame_id);
Ian Rogers0399dde2012-06-06 17:09:28 -07002623 visitor.WalkStack();
Sebastien Hertz8009f392014-09-01 17:07:11 +02002624 if (visitor.GetError() != JDWP::ERR_NONE) {
2625 return visitor.GetError();
2626 }
2627
2628 // Read the values from visitor's context.
2629 int32_t slot_count = request->ReadSigned32("slot count");
2630 expandBufAdd4BE(pReply, slot_count); /* "int values" */
2631 for (int32_t i = 0; i < slot_count; ++i) {
2632 uint32_t slot = request->ReadUnsigned32("slot");
2633 JDWP::JdwpTag reqSigByte = request->ReadTag();
2634
2635 VLOG(jdwp) << " --> slot " << slot << " " << reqSigByte;
2636
2637 size_t width = Dbg::GetTagWidth(reqSigByte);
Sebastien Hertz7d955652014-10-22 10:57:10 +02002638 uint8_t* ptr = expandBufAddSpace(pReply, width + 1);
Sebastien Hertz69206392015-04-07 15:54:25 +02002639 error = Dbg::GetLocalValue(visitor, soa, slot, reqSigByte, ptr, width);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002640 if (error != JDWP::ERR_NONE) {
2641 return error;
2642 }
2643 }
2644 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002645}
2646
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002647constexpr JDWP::JdwpError kStackFrameLocalAccessError = JDWP::ERR_ABSENT_INFORMATION;
2648
2649static std::string GetStackContextAsString(const StackVisitor& visitor)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002650 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002651 return StringPrintf(" at DEX pc 0x%08x in method %s", visitor.GetDexPc(false),
David Sehr709b0702016-10-13 09:12:37 -07002652 ArtMethod::PrettyMethod(visitor.GetMethod()).c_str());
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002653}
2654
2655static JDWP::JdwpError FailGetLocalValue(const StackVisitor& visitor, uint16_t vreg,
2656 JDWP::JdwpTag tag)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002657 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002658 LOG(ERROR) << "Failed to read " << tag << " local from register v" << vreg
2659 << GetStackContextAsString(visitor);
2660 return kStackFrameLocalAccessError;
2661}
2662
Sebastien Hertz8009f392014-09-01 17:07:11 +02002663JDWP::JdwpError Dbg::GetLocalValue(const StackVisitor& visitor, ScopedObjectAccessUnchecked& soa,
2664 int slot, JDWP::JdwpTag tag, uint8_t* buf, size_t width) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002665 ArtMethod* m = visitor.GetMethod();
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002666 JDWP::JdwpError error = JDWP::ERR_NONE;
2667 uint16_t vreg = DemangleSlot(slot, m, &error);
2668 if (error != JDWP::ERR_NONE) {
2669 return error;
2670 }
Sebastien Hertz8009f392014-09-01 17:07:11 +02002671 // TODO: check that the tag is compatible with the actual type of the slot!
Sebastien Hertz8009f392014-09-01 17:07:11 +02002672 switch (tag) {
2673 case JDWP::JT_BOOLEAN: {
2674 CHECK_EQ(width, 1U);
2675 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002676 if (!visitor.GetVReg(m, vreg, kIntVReg, &intVal)) {
2677 return FailGetLocalValue(visitor, vreg, tag);
Ian Rogers0399dde2012-06-06 17:09:28 -07002678 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002679 VLOG(jdwp) << "get boolean local " << vreg << " = " << intVal;
2680 JDWP::Set1(buf + 1, intVal != 0);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002681 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002682 }
Sebastien Hertz8009f392014-09-01 17:07:11 +02002683 case JDWP::JT_BYTE: {
2684 CHECK_EQ(width, 1U);
2685 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002686 if (!visitor.GetVReg(m, vreg, kIntVReg, &intVal)) {
2687 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002688 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002689 VLOG(jdwp) << "get byte local " << vreg << " = " << intVal;
2690 JDWP::Set1(buf + 1, intVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002691 break;
2692 }
2693 case JDWP::JT_SHORT:
2694 case JDWP::JT_CHAR: {
2695 CHECK_EQ(width, 2U);
2696 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002697 if (!visitor.GetVReg(m, vreg, kIntVReg, &intVal)) {
2698 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002699 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002700 VLOG(jdwp) << "get short/char local " << vreg << " = " << intVal;
2701 JDWP::Set2BE(buf + 1, intVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002702 break;
2703 }
2704 case JDWP::JT_INT: {
2705 CHECK_EQ(width, 4U);
2706 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002707 if (!visitor.GetVReg(m, vreg, kIntVReg, &intVal)) {
2708 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002709 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002710 VLOG(jdwp) << "get int local " << vreg << " = " << intVal;
2711 JDWP::Set4BE(buf + 1, intVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002712 break;
2713 }
2714 case JDWP::JT_FLOAT: {
2715 CHECK_EQ(width, 4U);
2716 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002717 if (!visitor.GetVReg(m, vreg, kFloatVReg, &intVal)) {
2718 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002719 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002720 VLOG(jdwp) << "get float local " << vreg << " = " << intVal;
2721 JDWP::Set4BE(buf + 1, intVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002722 break;
2723 }
2724 case JDWP::JT_ARRAY:
2725 case JDWP::JT_CLASS_LOADER:
2726 case JDWP::JT_CLASS_OBJECT:
2727 case JDWP::JT_OBJECT:
2728 case JDWP::JT_STRING:
2729 case JDWP::JT_THREAD:
2730 case JDWP::JT_THREAD_GROUP: {
2731 CHECK_EQ(width, sizeof(JDWP::ObjectId));
2732 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002733 if (!visitor.GetVReg(m, vreg, kReferenceVReg, &intVal)) {
2734 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002735 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002736 mirror::Object* o = reinterpret_cast<mirror::Object*>(intVal);
2737 VLOG(jdwp) << "get " << tag << " object local " << vreg << " = " << o;
2738 if (!Runtime::Current()->GetHeap()->IsValidObjectAddress(o)) {
2739 LOG(FATAL) << StringPrintf("Found invalid object %#" PRIxPTR " in register v%u",
2740 reinterpret_cast<uintptr_t>(o), vreg)
2741 << GetStackContextAsString(visitor);
2742 UNREACHABLE();
2743 }
2744 tag = TagFromObject(soa, o);
2745 JDWP::SetObjectId(buf + 1, gRegistry->Add(o));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002746 break;
2747 }
2748 case JDWP::JT_DOUBLE: {
2749 CHECK_EQ(width, 8U);
2750 uint64_t longVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002751 if (!visitor.GetVRegPair(m, vreg, kDoubleLoVReg, kDoubleHiVReg, &longVal)) {
2752 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002753 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002754 VLOG(jdwp) << "get double local " << vreg << " = " << longVal;
2755 JDWP::Set8BE(buf + 1, longVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002756 break;
2757 }
2758 case JDWP::JT_LONG: {
2759 CHECK_EQ(width, 8U);
2760 uint64_t longVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002761 if (!visitor.GetVRegPair(m, vreg, kLongLoVReg, kLongHiVReg, &longVal)) {
2762 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002763 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002764 VLOG(jdwp) << "get long local " << vreg << " = " << longVal;
2765 JDWP::Set8BE(buf + 1, longVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002766 break;
2767 }
2768 default:
2769 LOG(FATAL) << "Unknown tag " << tag;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002770 UNREACHABLE();
Sebastien Hertz8009f392014-09-01 17:07:11 +02002771 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002772
Sebastien Hertz8009f392014-09-01 17:07:11 +02002773 // Prepend tag, which may have been updated.
2774 JDWP::Set1(buf, tag);
2775 return JDWP::ERR_NONE;
2776}
2777
2778JDWP::JdwpError Dbg::SetLocalValues(JDWP::Request* request) {
2779 JDWP::ObjectId thread_id = request->ReadThreadId();
2780 JDWP::FrameId frame_id = request->ReadFrameId();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002781
2782 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz69206392015-04-07 15:54:25 +02002783 JDWP::JdwpError error;
2784 Thread* thread = DecodeThread(soa, thread_id, &error);
2785 if (error != JDWP::ERR_NONE) {
2786 return error;
2787 }
2788 if (!IsSuspendedForDebugger(soa, thread)) {
2789 return JDWP::ERR_THREAD_NOT_SUSPENDED;
Elliott Hughes221229c2013-01-08 18:17:50 -08002790 }
Sebastien Hertz8009f392014-09-01 17:07:11 +02002791 // Find the frame with the given frame_id.
Ian Rogers700a4022014-05-19 16:49:03 -07002792 std::unique_ptr<Context> context(Context::Create());
Sebastien Hertz8009f392014-09-01 17:07:11 +02002793 FindFrameVisitor visitor(thread, context.get(), frame_id);
Ian Rogers0399dde2012-06-06 17:09:28 -07002794 visitor.WalkStack();
Sebastien Hertz8009f392014-09-01 17:07:11 +02002795 if (visitor.GetError() != JDWP::ERR_NONE) {
2796 return visitor.GetError();
2797 }
2798
2799 // Writes the values into visitor's context.
2800 int32_t slot_count = request->ReadSigned32("slot count");
2801 for (int32_t i = 0; i < slot_count; ++i) {
2802 uint32_t slot = request->ReadUnsigned32("slot");
2803 JDWP::JdwpTag sigByte = request->ReadTag();
2804 size_t width = Dbg::GetTagWidth(sigByte);
2805 uint64_t value = request->ReadValue(width);
2806
2807 VLOG(jdwp) << " --> slot " << slot << " " << sigByte << " " << value;
Mingyao Yang99170c62015-07-06 11:10:37 -07002808 error = Dbg::SetLocalValue(thread, visitor, slot, sigByte, value, width);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002809 if (error != JDWP::ERR_NONE) {
2810 return error;
2811 }
2812 }
2813 return JDWP::ERR_NONE;
2814}
2815
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002816template<typename T>
2817static JDWP::JdwpError FailSetLocalValue(const StackVisitor& visitor, uint16_t vreg,
2818 JDWP::JdwpTag tag, T value)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002819 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002820 LOG(ERROR) << "Failed to write " << tag << " local " << value
2821 << " (0x" << std::hex << value << ") into register v" << vreg
2822 << GetStackContextAsString(visitor);
2823 return kStackFrameLocalAccessError;
2824}
2825
Mingyao Yang99170c62015-07-06 11:10:37 -07002826JDWP::JdwpError Dbg::SetLocalValue(Thread* thread, StackVisitor& visitor, int slot,
2827 JDWP::JdwpTag tag, uint64_t value, size_t width) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002828 ArtMethod* m = visitor.GetMethod();
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002829 JDWP::JdwpError error = JDWP::ERR_NONE;
2830 uint16_t vreg = DemangleSlot(slot, m, &error);
2831 if (error != JDWP::ERR_NONE) {
2832 return error;
2833 }
Sebastien Hertz8009f392014-09-01 17:07:11 +02002834 // TODO: check that the tag is compatible with the actual type of the slot!
Sebastien Hertz8009f392014-09-01 17:07:11 +02002835 switch (tag) {
2836 case JDWP::JT_BOOLEAN:
2837 case JDWP::JT_BYTE:
2838 CHECK_EQ(width, 1U);
Mingyao Yang636b9252015-07-31 16:40:24 -07002839 if (!visitor.SetVReg(m, vreg, static_cast<uint32_t>(value), kIntVReg)) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002840 return FailSetLocalValue(visitor, vreg, tag, static_cast<uint32_t>(value));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002841 }
2842 break;
2843 case JDWP::JT_SHORT:
2844 case JDWP::JT_CHAR:
2845 CHECK_EQ(width, 2U);
Mingyao Yang636b9252015-07-31 16:40:24 -07002846 if (!visitor.SetVReg(m, vreg, static_cast<uint32_t>(value), kIntVReg)) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002847 return FailSetLocalValue(visitor, vreg, tag, static_cast<uint32_t>(value));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002848 }
2849 break;
2850 case JDWP::JT_INT:
2851 CHECK_EQ(width, 4U);
Mingyao Yang636b9252015-07-31 16:40:24 -07002852 if (!visitor.SetVReg(m, vreg, static_cast<uint32_t>(value), kIntVReg)) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002853 return FailSetLocalValue(visitor, vreg, tag, static_cast<uint32_t>(value));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002854 }
2855 break;
2856 case JDWP::JT_FLOAT:
2857 CHECK_EQ(width, 4U);
Mingyao Yang636b9252015-07-31 16:40:24 -07002858 if (!visitor.SetVReg(m, vreg, static_cast<uint32_t>(value), kFloatVReg)) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002859 return FailSetLocalValue(visitor, vreg, tag, static_cast<uint32_t>(value));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002860 }
2861 break;
2862 case JDWP::JT_ARRAY:
2863 case JDWP::JT_CLASS_LOADER:
2864 case JDWP::JT_CLASS_OBJECT:
2865 case JDWP::JT_OBJECT:
2866 case JDWP::JT_STRING:
2867 case JDWP::JT_THREAD:
2868 case JDWP::JT_THREAD_GROUP: {
2869 CHECK_EQ(width, sizeof(JDWP::ObjectId));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002870 mirror::Object* o = gRegistry->Get<mirror::Object*>(static_cast<JDWP::ObjectId>(value),
2871 &error);
2872 if (error != JDWP::ERR_NONE) {
2873 VLOG(jdwp) << tag << " object " << o << " is an invalid object";
2874 return JDWP::ERR_INVALID_OBJECT;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002875 }
Mingyao Yang636b9252015-07-31 16:40:24 -07002876 if (!visitor.SetVReg(m, vreg, static_cast<uint32_t>(reinterpret_cast<uintptr_t>(o)),
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002877 kReferenceVReg)) {
2878 return FailSetLocalValue(visitor, vreg, tag, reinterpret_cast<uintptr_t>(o));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002879 }
2880 break;
2881 }
2882 case JDWP::JT_DOUBLE: {
2883 CHECK_EQ(width, 8U);
Mingyao Yang636b9252015-07-31 16:40:24 -07002884 if (!visitor.SetVRegPair(m, vreg, value, kDoubleLoVReg, kDoubleHiVReg)) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002885 return FailSetLocalValue(visitor, vreg, tag, value);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002886 }
2887 break;
2888 }
2889 case JDWP::JT_LONG: {
2890 CHECK_EQ(width, 8U);
Mingyao Yang636b9252015-07-31 16:40:24 -07002891 if (!visitor.SetVRegPair(m, vreg, value, kLongLoVReg, kLongHiVReg)) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002892 return FailSetLocalValue(visitor, vreg, tag, value);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002893 }
2894 break;
2895 }
2896 default:
2897 LOG(FATAL) << "Unknown tag " << tag;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002898 UNREACHABLE();
Sebastien Hertz8009f392014-09-01 17:07:11 +02002899 }
Mingyao Yang99170c62015-07-06 11:10:37 -07002900
2901 // If we set the local variable in a compiled frame, we need to trigger a deoptimization of
2902 // the stack so we continue execution with the interpreter using the new value(s) of the updated
2903 // local variable(s). To achieve this, we install instrumentation exit stub on each method of the
2904 // thread's stack. The stub will cause the deoptimization to happen.
2905 if (!visitor.IsShadowFrame() && thread->HasDebuggerShadowFrames()) {
2906 Runtime::Current()->GetInstrumentation()->InstrumentThreadStack(thread);
2907 }
2908
Sebastien Hertz8009f392014-09-01 17:07:11 +02002909 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002910}
2911
Mathieu Chartiere401d142015-04-22 13:56:20 -07002912static void SetEventLocation(JDWP::EventLocation* location, ArtMethod* m, uint32_t dex_pc)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002913 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz6995c602014-09-09 12:10:13 +02002914 DCHECK(location != nullptr);
2915 if (m == nullptr) {
2916 memset(location, 0, sizeof(*location));
2917 } else {
Alex Light97e78032017-06-27 17:51:55 -07002918 location->method = m->GetCanonicalMethod(kRuntimePointerSize);
Sebastien Hertz6995c602014-09-09 12:10:13 +02002919 location->dex_pc = (m->IsNative() || m->IsProxyMethod()) ? static_cast<uint32_t>(-1) : dex_pc;
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002920 }
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002921}
2922
Mathieu Chartiere401d142015-04-22 13:56:20 -07002923void Dbg::PostLocationEvent(ArtMethod* m, int dex_pc, mirror::Object* this_object,
Jeff Hao579b0242013-11-18 13:16:49 -08002924 int event_flags, const JValue* return_value) {
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002925 if (!IsDebuggerActive()) {
2926 return;
2927 }
2928 DCHECK(m != nullptr);
2929 DCHECK_EQ(m->IsStatic(), this_object == nullptr);
Sebastien Hertz6995c602014-09-09 12:10:13 +02002930 JDWP::EventLocation location;
2931 SetEventLocation(&location, m, dex_pc);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002932
Sebastien Hertzde48aa62015-05-26 11:53:39 +02002933 // We need to be sure no exception is pending when calling JdwpState::PostLocationEvent.
2934 // This is required to be able to call JNI functions to create JDWP ids. To achieve this,
2935 // we temporarily clear the current thread's exception (if any) and will restore it after
2936 // the call.
2937 // Note: the only way to get a pending exception here is to suspend on a move-exception
2938 // instruction.
2939 Thread* const self = Thread::Current();
2940 StackHandleScope<1> hs(self);
2941 Handle<mirror::Throwable> pending_exception(hs.NewHandle(self->GetException()));
2942 self->ClearException();
Andreas Gampefa4333d2017-02-14 11:10:34 -08002943 if (kIsDebugBuild && pending_exception != nullptr) {
Mathieu Chartier808c7a52017-12-15 11:19:33 -08002944 const Instruction& instr = location.method->DexInstructions().InstructionAt(location.dex_pc);
2945 CHECK_EQ(Instruction::MOVE_EXCEPTION, instr.Opcode());
Sebastien Hertzde48aa62015-05-26 11:53:39 +02002946 }
2947
Sebastien Hertz6995c602014-09-09 12:10:13 +02002948 gJdwpState->PostLocationEvent(&location, this_object, event_flags, return_value);
Sebastien Hertzde48aa62015-05-26 11:53:39 +02002949
Andreas Gampefa4333d2017-02-14 11:10:34 -08002950 if (pending_exception != nullptr) {
Sebastien Hertzde48aa62015-05-26 11:53:39 +02002951 self->SetException(pending_exception.Get());
2952 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002953}
2954
Mathieu Chartiere401d142015-04-22 13:56:20 -07002955void Dbg::PostFieldAccessEvent(ArtMethod* m, int dex_pc,
Mathieu Chartierc7853442015-03-27 14:35:38 -07002956 mirror::Object* this_object, ArtField* f) {
Alex Lighte00ec302017-06-16 08:56:43 -07002957 // TODO We should send events for native methods.
2958 if (!IsDebuggerActive() || m->IsNative()) {
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002959 return;
2960 }
2961 DCHECK(m != nullptr);
2962 DCHECK(f != nullptr);
Sebastien Hertz6995c602014-09-09 12:10:13 +02002963 JDWP::EventLocation location;
2964 SetEventLocation(&location, m, dex_pc);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002965
Sebastien Hertz6995c602014-09-09 12:10:13 +02002966 gJdwpState->PostFieldEvent(&location, f, this_object, nullptr, false);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002967}
2968
Mathieu Chartiere401d142015-04-22 13:56:20 -07002969void Dbg::PostFieldModificationEvent(ArtMethod* m, int dex_pc,
Mathieu Chartierc7853442015-03-27 14:35:38 -07002970 mirror::Object* this_object, ArtField* f,
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002971 const JValue* field_value) {
Alex Lighte00ec302017-06-16 08:56:43 -07002972 // TODO We should send events for native methods.
2973 if (!IsDebuggerActive() || m->IsNative()) {
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002974 return;
2975 }
2976 DCHECK(m != nullptr);
2977 DCHECK(f != nullptr);
2978 DCHECK(field_value != nullptr);
Sebastien Hertz6995c602014-09-09 12:10:13 +02002979 JDWP::EventLocation location;
2980 SetEventLocation(&location, m, dex_pc);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002981
Sebastien Hertz6995c602014-09-09 12:10:13 +02002982 gJdwpState->PostFieldEvent(&location, f, this_object, field_value, true);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002983}
2984
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002985/**
2986 * Finds the location where this exception will be caught. We search until we reach the top
2987 * frame, in which case this exception is considered uncaught.
2988 */
2989class CatchLocationFinder : public StackVisitor {
2990 public:
2991 CatchLocationFinder(Thread* self, const Handle<mirror::Throwable>& exception, Context* context)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002992 REQUIRES_SHARED(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01002993 : StackVisitor(self, context, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002994 exception_(exception),
2995 handle_scope_(self),
2996 this_at_throw_(handle_scope_.NewHandle<mirror::Object>(nullptr)),
Mathieu Chartiere401d142015-04-22 13:56:20 -07002997 catch_method_(nullptr),
2998 throw_method_(nullptr),
Andreas Gampee2abbc62017-09-15 11:59:26 -07002999 catch_dex_pc_(dex::kDexNoIndex),
3000 throw_dex_pc_(dex::kDexNoIndex) {
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003001 }
3002
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01003003 bool VisitFrame() override REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003004 ArtMethod* method = GetMethod();
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003005 DCHECK(method != nullptr);
3006 if (method->IsRuntimeMethod()) {
3007 // Ignore callee save method.
3008 DCHECK(method->IsCalleeSaveMethod());
3009 return true;
3010 }
3011
3012 uint32_t dex_pc = GetDexPc();
Mathieu Chartiere401d142015-04-22 13:56:20 -07003013 if (throw_method_ == nullptr) {
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003014 // First Java method found. It is either the method that threw the exception,
3015 // or the Java native method that is reporting an exception thrown by
3016 // native code.
3017 this_at_throw_.Assign(GetThisObject());
Mathieu Chartiere401d142015-04-22 13:56:20 -07003018 throw_method_ = method;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003019 throw_dex_pc_ = dex_pc;
3020 }
3021
Andreas Gampee2abbc62017-09-15 11:59:26 -07003022 if (dex_pc != dex::kDexNoIndex) {
Sebastien Hertz26f72862015-09-15 09:52:07 +02003023 StackHandleScope<1> hs(GetThread());
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003024 uint32_t found_dex_pc;
3025 Handle<mirror::Class> exception_class(hs.NewHandle(exception_->GetClass()));
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003026 bool unused_clear_exception;
Mathieu Chartiere401d142015-04-22 13:56:20 -07003027 found_dex_pc = method->FindCatchBlock(exception_class, dex_pc, &unused_clear_exception);
Andreas Gampee2abbc62017-09-15 11:59:26 -07003028 if (found_dex_pc != dex::kDexNoIndex) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003029 catch_method_ = method;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003030 catch_dex_pc_ = found_dex_pc;
3031 return false; // End stack walk.
3032 }
3033 }
3034 return true; // Continue stack walk.
3035 }
3036
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003037 ArtMethod* GetCatchMethod() REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003038 return catch_method_;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003039 }
3040
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003041 ArtMethod* GetThrowMethod() REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003042 return throw_method_;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003043 }
3044
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003045 mirror::Object* GetThisAtThrow() REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003046 return this_at_throw_.Get();
3047 }
3048
3049 uint32_t GetCatchDexPc() const {
3050 return catch_dex_pc_;
3051 }
3052
3053 uint32_t GetThrowDexPc() const {
3054 return throw_dex_pc_;
3055 }
3056
3057 private:
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003058 const Handle<mirror::Throwable>& exception_;
Mathieu Chartiere401d142015-04-22 13:56:20 -07003059 StackHandleScope<1> handle_scope_;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003060 MutableHandle<mirror::Object> this_at_throw_;
Mathieu Chartiere401d142015-04-22 13:56:20 -07003061 ArtMethod* catch_method_;
3062 ArtMethod* throw_method_;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003063 uint32_t catch_dex_pc_;
3064 uint32_t throw_dex_pc_;
3065
3066 DISALLOW_COPY_AND_ASSIGN(CatchLocationFinder);
3067};
3068
3069void Dbg::PostException(mirror::Throwable* exception_object) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07003070 if (!IsDebuggerActive()) {
Ian Rogers0ad5bb82011-12-07 10:16:32 -08003071 return;
3072 }
Sebastien Hertz261bc042015-04-08 09:36:07 +02003073 Thread* const self = Thread::Current();
3074 StackHandleScope<1> handle_scope(self);
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003075 Handle<mirror::Throwable> h_exception(handle_scope.NewHandle(exception_object));
3076 std::unique_ptr<Context> context(Context::Create());
Sebastien Hertz261bc042015-04-08 09:36:07 +02003077 CatchLocationFinder clf(self, h_exception, context.get());
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003078 clf.WalkStack(/* include_transitions */ false);
Sebastien Hertz6995c602014-09-09 12:10:13 +02003079 JDWP::EventLocation exception_throw_location;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003080 SetEventLocation(&exception_throw_location, clf.GetThrowMethod(), clf.GetThrowDexPc());
Sebastien Hertz6995c602014-09-09 12:10:13 +02003081 JDWP::EventLocation exception_catch_location;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003082 SetEventLocation(&exception_catch_location, clf.GetCatchMethod(), clf.GetCatchDexPc());
Elliott Hughes4740cdf2011-12-07 14:07:12 -08003083
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003084 gJdwpState->PostException(&exception_throw_location, h_exception.Get(), &exception_catch_location,
3085 clf.GetThisAtThrow());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003086}
3087
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003088void Dbg::PostClassPrepare(mirror::Class* c) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07003089 if (!IsDebuggerActive()) {
Elliott Hughes4740cdf2011-12-07 14:07:12 -08003090 return;
3091 }
Sebastien Hertz6995c602014-09-09 12:10:13 +02003092 gJdwpState->PostClassPrepare(c);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003093}
3094
Ian Rogers62d6c772013-02-27 08:32:07 -08003095void Dbg::UpdateDebugger(Thread* thread, mirror::Object* this_object,
Mathieu Chartiere401d142015-04-22 13:56:20 -07003096 ArtMethod* m, uint32_t dex_pc,
Sebastien Hertz8379b222014-02-24 17:38:15 +01003097 int event_flags, const JValue* return_value) {
Ian Rogers62d6c772013-02-27 08:32:07 -08003098 if (!IsDebuggerActive() || dex_pc == static_cast<uint32_t>(-2) /* fake method exit */) {
Elliott Hughes2aa2e392012-02-17 17:15:43 -08003099 return;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003100 }
3101
Elliott Hughes86964332012-02-15 19:37:42 -08003102 if (IsBreakpoint(m, dex_pc)) {
3103 event_flags |= kBreakpoint;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003104 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003105
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003106 // If the debugger is single-stepping one of our threads, check to
3107 // see if we're that thread and we've reached a step point.
3108 const SingleStepControl* single_step_control = thread->GetSingleStepControl();
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003109 if (single_step_control != nullptr) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003110 CHECK(!m->IsNative());
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003111 if (single_step_control->GetStepDepth() == JDWP::SD_INTO) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003112 // Step into method calls. We break when the line number
3113 // or method pointer changes. If we're in SS_MIN mode, we
3114 // always stop.
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003115 if (single_step_control->GetMethod() != m) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003116 event_flags |= kSingleStep;
3117 VLOG(jdwp) << "SS new method";
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003118 } else if (single_step_control->GetStepSize() == JDWP::SS_MIN) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003119 event_flags |= kSingleStep;
3120 VLOG(jdwp) << "SS new instruction";
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003121 } else if (single_step_control->ContainsDexPc(dex_pc)) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003122 event_flags |= kSingleStep;
3123 VLOG(jdwp) << "SS new line";
3124 }
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003125 } else if (single_step_control->GetStepDepth() == JDWP::SD_OVER) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003126 // Step over method calls. We break when the line number is
3127 // different and the frame depth is <= the original frame
3128 // depth. (We can't just compare on the method, because we
3129 // might get unrolled past it by an exception, and it's tricky
3130 // to identify recursion.)
3131
3132 int stack_depth = GetStackDepth(thread);
3133
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003134 if (stack_depth < single_step_control->GetStackDepth()) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003135 // Popped up one or more frames, always trigger.
3136 event_flags |= kSingleStep;
3137 VLOG(jdwp) << "SS method pop";
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003138 } else if (stack_depth == single_step_control->GetStackDepth()) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003139 // Same depth, see if we moved.
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003140 if (single_step_control->GetStepSize() == JDWP::SS_MIN) {
Elliott Hughes86964332012-02-15 19:37:42 -08003141 event_flags |= kSingleStep;
3142 VLOG(jdwp) << "SS new instruction";
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003143 } else if (single_step_control->ContainsDexPc(dex_pc)) {
Elliott Hughes2435a572012-02-17 16:07:41 -08003144 event_flags |= kSingleStep;
3145 VLOG(jdwp) << "SS new line";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003146 }
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003147 }
3148 } else {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003149 CHECK_EQ(single_step_control->GetStepDepth(), JDWP::SD_OUT);
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003150 // Return from the current method. We break when the frame
3151 // depth pops up.
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003152
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003153 // This differs from the "method exit" break in that it stops
3154 // with the PC at the next instruction in the returned-to
3155 // function, rather than the end of the returning function.
Elliott Hughes86964332012-02-15 19:37:42 -08003156
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003157 int stack_depth = GetStackDepth(thread);
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003158 if (stack_depth < single_step_control->GetStackDepth()) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003159 event_flags |= kSingleStep;
3160 VLOG(jdwp) << "SS method pop";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003161 }
3162 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003163 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003164
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003165 // If there's something interesting going on, see if it matches one
3166 // of the debugger filters.
3167 if (event_flags != 0) {
Sebastien Hertz8379b222014-02-24 17:38:15 +01003168 Dbg::PostLocationEvent(m, dex_pc, this_object, event_flags, return_value);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003169 }
3170}
3171
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003172size_t* Dbg::GetReferenceCounterForEvent(uint32_t instrumentation_event) {
3173 switch (instrumentation_event) {
3174 case instrumentation::Instrumentation::kMethodEntered:
3175 return &method_enter_event_ref_count_;
3176 case instrumentation::Instrumentation::kMethodExited:
3177 return &method_exit_event_ref_count_;
3178 case instrumentation::Instrumentation::kDexPcMoved:
3179 return &dex_pc_change_event_ref_count_;
3180 case instrumentation::Instrumentation::kFieldRead:
3181 return &field_read_event_ref_count_;
3182 case instrumentation::Instrumentation::kFieldWritten:
3183 return &field_write_event_ref_count_;
Alex Light6e1607e2017-08-23 10:06:18 -07003184 case instrumentation::Instrumentation::kExceptionThrown:
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003185 return &exception_catch_event_ref_count_;
3186 default:
3187 return nullptr;
3188 }
3189}
3190
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003191// Process request while all mutator threads are suspended.
3192void Dbg::ProcessDeoptimizationRequest(const DeoptimizationRequest& request) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003193 instrumentation::Instrumentation* instrumentation = Runtime::Current()->GetInstrumentation();
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003194 switch (request.GetKind()) {
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003195 case DeoptimizationRequest::kNothing:
3196 LOG(WARNING) << "Ignoring empty deoptimization request.";
3197 break;
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003198 case DeoptimizationRequest::kRegisterForEvent:
3199 VLOG(jdwp) << StringPrintf("Add debugger as listener for instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003200 request.InstrumentationEvent());
3201 instrumentation->AddListener(&gDebugInstrumentationListener, request.InstrumentationEvent());
3202 instrumentation_events_ |= request.InstrumentationEvent();
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003203 break;
3204 case DeoptimizationRequest::kUnregisterForEvent:
3205 VLOG(jdwp) << StringPrintf("Remove debugger as listener for instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003206 request.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003207 instrumentation->RemoveListener(&gDebugInstrumentationListener,
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003208 request.InstrumentationEvent());
3209 instrumentation_events_ &= ~request.InstrumentationEvent();
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003210 break;
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003211 case DeoptimizationRequest::kFullDeoptimization:
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003212 VLOG(jdwp) << "Deoptimize the world ...";
Sebastien Hertz0462c4c2015-04-01 16:34:17 +02003213 instrumentation->DeoptimizeEverything(kDbgInstrumentationKey);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003214 VLOG(jdwp) << "Deoptimize the world DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003215 break;
3216 case DeoptimizationRequest::kFullUndeoptimization:
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003217 VLOG(jdwp) << "Undeoptimize the world ...";
Sebastien Hertz0462c4c2015-04-01 16:34:17 +02003218 instrumentation->UndeoptimizeEverything(kDbgInstrumentationKey);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003219 VLOG(jdwp) << "Undeoptimize the world DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003220 break;
3221 case DeoptimizationRequest::kSelectiveDeoptimization:
David Sehr709b0702016-10-13 09:12:37 -07003222 VLOG(jdwp) << "Deoptimize method " << ArtMethod::PrettyMethod(request.Method()) << " ...";
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003223 instrumentation->Deoptimize(request.Method());
David Sehr709b0702016-10-13 09:12:37 -07003224 VLOG(jdwp) << "Deoptimize method " << ArtMethod::PrettyMethod(request.Method()) << " DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003225 break;
3226 case DeoptimizationRequest::kSelectiveUndeoptimization:
David Sehr709b0702016-10-13 09:12:37 -07003227 VLOG(jdwp) << "Undeoptimize method " << ArtMethod::PrettyMethod(request.Method()) << " ...";
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003228 instrumentation->Undeoptimize(request.Method());
David Sehr709b0702016-10-13 09:12:37 -07003229 VLOG(jdwp) << "Undeoptimize method " << ArtMethod::PrettyMethod(request.Method()) << " DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003230 break;
3231 default:
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003232 LOG(FATAL) << "Unsupported deoptimization request kind " << request.GetKind();
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003233 break;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003234 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003235}
3236
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003237void Dbg::RequestDeoptimization(const DeoptimizationRequest& req) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003238 if (req.GetKind() == DeoptimizationRequest::kNothing) {
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003239 // Nothing to do.
3240 return;
3241 }
Brian Carlstrom306db812014-09-05 13:01:41 -07003242 MutexLock mu(Thread::Current(), *Locks::deoptimization_lock_);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003243 RequestDeoptimizationLocked(req);
3244}
3245
3246void Dbg::RequestDeoptimizationLocked(const DeoptimizationRequest& req) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003247 switch (req.GetKind()) {
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003248 case DeoptimizationRequest::kRegisterForEvent: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003249 DCHECK_NE(req.InstrumentationEvent(), 0u);
3250 size_t* counter = GetReferenceCounterForEvent(req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003251 CHECK(counter != nullptr) << StringPrintf("No counter for instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003252 req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003253 if (*counter == 0) {
Sebastien Hertz7d2ae432014-05-15 11:26:34 +02003254 VLOG(jdwp) << StringPrintf("Queue request #%zd to start listening to instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003255 deoptimization_requests_.size(), req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003256 deoptimization_requests_.push_back(req);
3257 }
3258 *counter = *counter + 1;
3259 break;
3260 }
3261 case DeoptimizationRequest::kUnregisterForEvent: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003262 DCHECK_NE(req.InstrumentationEvent(), 0u);
3263 size_t* counter = GetReferenceCounterForEvent(req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003264 CHECK(counter != nullptr) << StringPrintf("No counter for instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003265 req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003266 *counter = *counter - 1;
3267 if (*counter == 0) {
Sebastien Hertz7d2ae432014-05-15 11:26:34 +02003268 VLOG(jdwp) << StringPrintf("Queue request #%zd to stop listening to instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003269 deoptimization_requests_.size(), req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003270 deoptimization_requests_.push_back(req);
3271 }
3272 break;
3273 }
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003274 case DeoptimizationRequest::kFullDeoptimization: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003275 DCHECK(req.Method() == nullptr);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003276 if (full_deoptimization_event_count_ == 0) {
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003277 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
3278 << " for full deoptimization";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003279 deoptimization_requests_.push_back(req);
3280 }
3281 ++full_deoptimization_event_count_;
3282 break;
3283 }
3284 case DeoptimizationRequest::kFullUndeoptimization: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003285 DCHECK(req.Method() == nullptr);
Sebastien Hertze713d932014-05-15 10:48:53 +02003286 DCHECK_GT(full_deoptimization_event_count_, 0U);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003287 --full_deoptimization_event_count_;
3288 if (full_deoptimization_event_count_ == 0) {
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003289 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
3290 << " for full undeoptimization";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003291 deoptimization_requests_.push_back(req);
3292 }
3293 break;
3294 }
3295 case DeoptimizationRequest::kSelectiveDeoptimization: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003296 DCHECK(req.Method() != nullptr);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003297 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
David Sehr709b0702016-10-13 09:12:37 -07003298 << " for deoptimization of " << req.Method()->PrettyMethod();
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003299 deoptimization_requests_.push_back(req);
3300 break;
3301 }
3302 case DeoptimizationRequest::kSelectiveUndeoptimization: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003303 DCHECK(req.Method() != nullptr);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003304 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
David Sehr709b0702016-10-13 09:12:37 -07003305 << " for undeoptimization of " << req.Method()->PrettyMethod();
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003306 deoptimization_requests_.push_back(req);
3307 break;
3308 }
3309 default: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003310 LOG(FATAL) << "Unknown deoptimization request kind " << req.GetKind();
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003311 break;
3312 }
3313 }
3314}
3315
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003316void Dbg::ManageDeoptimization() {
3317 Thread* const self = Thread::Current();
3318 {
3319 // Avoid suspend/resume if there is no pending request.
Brian Carlstrom306db812014-09-05 13:01:41 -07003320 MutexLock mu(self, *Locks::deoptimization_lock_);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003321 if (deoptimization_requests_.empty()) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003322 return;
3323 }
3324 }
3325 CHECK_EQ(self->GetState(), kRunnable);
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07003326 ScopedThreadSuspension sts(self, kWaitingForDeoptimization);
Mathieu Chartieraa516822015-10-02 15:53:37 -07003327 // Required for ProcessDeoptimizationRequest.
3328 gc::ScopedGCCriticalSection gcs(self,
3329 gc::kGcCauseInstrumentation,
3330 gc::kCollectorTypeInstrumentation);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003331 // We need to suspend mutator threads first.
Mathieu Chartier4f55e222015-09-04 13:26:21 -07003332 ScopedSuspendAll ssa(__FUNCTION__);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003333 const ThreadState old_state = self->SetStateUnsafe(kRunnable);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003334 {
Brian Carlstrom306db812014-09-05 13:01:41 -07003335 MutexLock mu(self, *Locks::deoptimization_lock_);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003336 size_t req_index = 0;
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003337 for (DeoptimizationRequest& request : deoptimization_requests_) {
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003338 VLOG(jdwp) << "Process deoptimization request #" << req_index++;
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003339 ProcessDeoptimizationRequest(request);
3340 }
3341 deoptimization_requests_.clear();
3342 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003343 CHECK_EQ(self->SetStateUnsafe(old_state), kRunnable);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003344}
3345
Mathieu Chartiere401d142015-04-22 13:56:20 -07003346static const Breakpoint* FindFirstBreakpointForMethod(ArtMethod* m)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003347 REQUIRES_SHARED(Locks::mutator_lock_, Locks::breakpoint_lock_) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003348 for (Breakpoint& breakpoint : gBreakpoints) {
Alex Light6c8467f2015-11-20 15:03:26 -08003349 if (breakpoint.IsInMethod(m)) {
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003350 return &breakpoint;
3351 }
3352 }
3353 return nullptr;
3354}
3355
Mathieu Chartiere401d142015-04-22 13:56:20 -07003356bool Dbg::MethodHasAnyBreakpoints(ArtMethod* method) {
Mathieu Chartierd8565452015-03-26 09:41:50 -07003357 ReaderMutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
3358 return FindFirstBreakpointForMethod(method) != nullptr;
3359}
3360
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003361// Sanity checks all existing breakpoints on the same method.
Mathieu Chartiere401d142015-04-22 13:56:20 -07003362static void SanityCheckExistingBreakpoints(ArtMethod* m,
Sebastien Hertzf3928792014-11-17 19:00:37 +01003363 DeoptimizationRequest::Kind deoptimization_kind)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003364 REQUIRES_SHARED(Locks::mutator_lock_, Locks::breakpoint_lock_) {
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003365 for (const Breakpoint& breakpoint : gBreakpoints) {
Alex Light6c8467f2015-11-20 15:03:26 -08003366 if (breakpoint.IsInMethod(m)) {
Sebastien Hertzf3928792014-11-17 19:00:37 +01003367 CHECK_EQ(deoptimization_kind, breakpoint.GetDeoptimizationKind());
3368 }
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003369 }
Sebastien Hertzf3928792014-11-17 19:00:37 +01003370 instrumentation::Instrumentation* instrumentation = Runtime::Current()->GetInstrumentation();
3371 if (deoptimization_kind == DeoptimizationRequest::kFullDeoptimization) {
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003372 // We should have deoptimized everything but not "selectively" deoptimized this method.
Sebastien Hertzf3928792014-11-17 19:00:37 +01003373 CHECK(instrumentation->AreAllMethodsDeoptimized());
3374 CHECK(!instrumentation->IsDeoptimized(m));
3375 } else if (deoptimization_kind == DeoptimizationRequest::kSelectiveDeoptimization) {
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003376 // We should have "selectively" deoptimized this method.
3377 // Note: while we have not deoptimized everything for this method, we may have done it for
3378 // another event.
Sebastien Hertzf3928792014-11-17 19:00:37 +01003379 CHECK(instrumentation->IsDeoptimized(m));
3380 } else {
3381 // This method does not require deoptimization.
3382 CHECK_EQ(deoptimization_kind, DeoptimizationRequest::kNothing);
3383 CHECK(!instrumentation->IsDeoptimized(m));
3384 }
3385}
3386
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003387// Returns the deoptimization kind required to set a breakpoint in a method.
3388// If a breakpoint has already been set, we also return the first breakpoint
3389// through the given 'existing_brkpt' pointer.
Sebastien Hertzf3928792014-11-17 19:00:37 +01003390static DeoptimizationRequest::Kind GetRequiredDeoptimizationKind(Thread* self,
Mathieu Chartiere401d142015-04-22 13:56:20 -07003391 ArtMethod* m,
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003392 const Breakpoint** existing_brkpt)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003393 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertzf3928792014-11-17 19:00:37 +01003394 if (!Dbg::RequiresDeoptimization()) {
3395 // We already run in interpreter-only mode so we don't need to deoptimize anything.
3396 VLOG(jdwp) << "No need for deoptimization when fully running with interpreter for method "
David Sehr709b0702016-10-13 09:12:37 -07003397 << ArtMethod::PrettyMethod(m);
Sebastien Hertzf3928792014-11-17 19:00:37 +01003398 return DeoptimizationRequest::kNothing;
3399 }
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003400 const Breakpoint* first_breakpoint;
Sebastien Hertzf3928792014-11-17 19:00:37 +01003401 {
3402 ReaderMutexLock mu(self, *Locks::breakpoint_lock_);
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003403 first_breakpoint = FindFirstBreakpointForMethod(m);
3404 *existing_brkpt = first_breakpoint;
Sebastien Hertzf3928792014-11-17 19:00:37 +01003405 }
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003406
3407 if (first_breakpoint == nullptr) {
Nicolas Geoffray6300fd72016-03-18 09:40:17 +00003408 // There is no breakpoint on this method yet: we need to deoptimize. If this method is default,
3409 // we deoptimize everything; otherwise we deoptimize only this method. We
Alex Light6c8467f2015-11-20 15:03:26 -08003410 // deoptimize with defaults because we do not know everywhere they are used. It is possible some
Nicolas Geoffray6300fd72016-03-18 09:40:17 +00003411 // of the copies could be missed.
Alex Light6c8467f2015-11-20 15:03:26 -08003412 // TODO Deoptimizing on default methods might not be necessary in all cases.
Nicolas Geoffray6300fd72016-03-18 09:40:17 +00003413 bool need_full_deoptimization = m->IsDefault();
Sebastien Hertzf3928792014-11-17 19:00:37 +01003414 if (need_full_deoptimization) {
Nicolas Geoffray6300fd72016-03-18 09:40:17 +00003415 VLOG(jdwp) << "Need full deoptimization because of copying of method "
David Sehr709b0702016-10-13 09:12:37 -07003416 << ArtMethod::PrettyMethod(m);
Sebastien Hertzf3928792014-11-17 19:00:37 +01003417 return DeoptimizationRequest::kFullDeoptimization;
3418 } else {
3419 // We don't need to deoptimize if the method has not been compiled.
Nicolas Geoffraya5891e82015-11-06 14:18:27 +00003420 const bool is_compiled = m->HasAnyCompiledCode();
Sebastien Hertzf3928792014-11-17 19:00:37 +01003421 if (is_compiled) {
David Sehr709b0702016-10-13 09:12:37 -07003422 VLOG(jdwp) << "Need selective deoptimization for compiled method "
3423 << ArtMethod::PrettyMethod(m);
Nicolas Geoffray6300fd72016-03-18 09:40:17 +00003424 return DeoptimizationRequest::kSelectiveDeoptimization;
Sebastien Hertzf3928792014-11-17 19:00:37 +01003425 } else {
3426 // Method is not compiled: we don't need to deoptimize.
David Sehr709b0702016-10-13 09:12:37 -07003427 VLOG(jdwp) << "No need for deoptimization for non-compiled method "
3428 << ArtMethod::PrettyMethod(m);
Sebastien Hertzf3928792014-11-17 19:00:37 +01003429 return DeoptimizationRequest::kNothing;
3430 }
3431 }
3432 } else {
3433 // There is at least one breakpoint for this method: we don't need to deoptimize.
3434 // Let's check that all breakpoints are configured the same way for deoptimization.
3435 VLOG(jdwp) << "Breakpoint already set: no deoptimization is required";
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003436 DeoptimizationRequest::Kind deoptimization_kind = first_breakpoint->GetDeoptimizationKind();
Sebastien Hertzf3928792014-11-17 19:00:37 +01003437 if (kIsDebugBuild) {
3438 ReaderMutexLock mu(self, *Locks::breakpoint_lock_);
3439 SanityCheckExistingBreakpoints(m, deoptimization_kind);
3440 }
3441 return DeoptimizationRequest::kNothing;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003442 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003443}
3444
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003445// Installs a breakpoint at the specified location. Also indicates through the deoptimization
3446// request if we need to deoptimize.
3447void Dbg::WatchLocation(const JDWP::JdwpLocation* location, DeoptimizationRequest* req) {
3448 Thread* const self = Thread::Current();
Mathieu Chartiere401d142015-04-22 13:56:20 -07003449 ArtMethod* m = FromMethodId(location->method_id);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003450 DCHECK(m != nullptr) << "No method for method id " << location->method_id;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003451
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003452 const Breakpoint* existing_breakpoint = nullptr;
3453 const DeoptimizationRequest::Kind deoptimization_kind =
3454 GetRequiredDeoptimizationKind(self, m, &existing_breakpoint);
Sebastien Hertzf3928792014-11-17 19:00:37 +01003455 req->SetKind(deoptimization_kind);
3456 if (deoptimization_kind == DeoptimizationRequest::kSelectiveDeoptimization) {
3457 req->SetMethod(m);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003458 } else {
Sebastien Hertzf3928792014-11-17 19:00:37 +01003459 CHECK(deoptimization_kind == DeoptimizationRequest::kNothing ||
3460 deoptimization_kind == DeoptimizationRequest::kFullDeoptimization);
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003461 req->SetMethod(nullptr);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003462 }
3463
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003464 {
3465 WriterMutexLock mu(self, *Locks::breakpoint_lock_);
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003466 // If there is at least one existing breakpoint on the same method, the new breakpoint
3467 // must have the same deoptimization kind than the existing breakpoint(s).
3468 DeoptimizationRequest::Kind breakpoint_deoptimization_kind;
3469 if (existing_breakpoint != nullptr) {
3470 breakpoint_deoptimization_kind = existing_breakpoint->GetDeoptimizationKind();
3471 } else {
3472 breakpoint_deoptimization_kind = deoptimization_kind;
3473 }
3474 gBreakpoints.push_back(Breakpoint(m, location->dex_pc, breakpoint_deoptimization_kind));
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003475 VLOG(jdwp) << "Set breakpoint #" << (gBreakpoints.size() - 1) << ": "
3476 << gBreakpoints[gBreakpoints.size() - 1];
3477 }
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003478}
3479
3480// Uninstalls a breakpoint at the specified location. Also indicates through the deoptimization
3481// request if we need to undeoptimize.
3482void Dbg::UnwatchLocation(const JDWP::JdwpLocation* location, DeoptimizationRequest* req) {
Sebastien Hertzed2be172014-08-19 15:33:43 +02003483 WriterMutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003484 ArtMethod* m = FromMethodId(location->method_id);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003485 DCHECK(m != nullptr) << "No method for method id " << location->method_id;
Sebastien Hertzf3928792014-11-17 19:00:37 +01003486 DeoptimizationRequest::Kind deoptimization_kind = DeoptimizationRequest::kNothing;
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003487 for (size_t i = 0, e = gBreakpoints.size(); i < e; ++i) {
Alex Light6c8467f2015-11-20 15:03:26 -08003488 if (gBreakpoints[i].DexPc() == location->dex_pc && gBreakpoints[i].IsInMethod(m)) {
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003489 VLOG(jdwp) << "Removed breakpoint #" << i << ": " << gBreakpoints[i];
Sebastien Hertzf3928792014-11-17 19:00:37 +01003490 deoptimization_kind = gBreakpoints[i].GetDeoptimizationKind();
3491 DCHECK_EQ(deoptimization_kind == DeoptimizationRequest::kSelectiveDeoptimization,
3492 Runtime::Current()->GetInstrumentation()->IsDeoptimized(m));
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003493 gBreakpoints.erase(gBreakpoints.begin() + i);
3494 break;
3495 }
3496 }
3497 const Breakpoint* const existing_breakpoint = FindFirstBreakpointForMethod(m);
3498 if (existing_breakpoint == nullptr) {
3499 // There is no more breakpoint on this method: we need to undeoptimize.
Sebastien Hertzf3928792014-11-17 19:00:37 +01003500 if (deoptimization_kind == DeoptimizationRequest::kFullDeoptimization) {
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003501 // This method required full deoptimization: we need to undeoptimize everything.
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003502 req->SetKind(DeoptimizationRequest::kFullUndeoptimization);
3503 req->SetMethod(nullptr);
Sebastien Hertzf3928792014-11-17 19:00:37 +01003504 } else if (deoptimization_kind == DeoptimizationRequest::kSelectiveDeoptimization) {
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003505 // This method required selective deoptimization: we need to undeoptimize only that method.
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003506 req->SetKind(DeoptimizationRequest::kSelectiveUndeoptimization);
3507 req->SetMethod(m);
Sebastien Hertzf3928792014-11-17 19:00:37 +01003508 } else {
3509 // This method had no need for deoptimization: do nothing.
3510 CHECK_EQ(deoptimization_kind, DeoptimizationRequest::kNothing);
3511 req->SetKind(DeoptimizationRequest::kNothing);
3512 req->SetMethod(nullptr);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003513 }
3514 } else {
3515 // There is at least one breakpoint for this method: we don't need to undeoptimize.
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003516 req->SetKind(DeoptimizationRequest::kNothing);
3517 req->SetMethod(nullptr);
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003518 if (kIsDebugBuild) {
Sebastien Hertzf3928792014-11-17 19:00:37 +01003519 SanityCheckExistingBreakpoints(m, deoptimization_kind);
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003520 }
Elliott Hughes86964332012-02-15 19:37:42 -08003521 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003522}
3523
Mathieu Chartiere401d142015-04-22 13:56:20 -07003524bool Dbg::IsForcedInterpreterNeededForCallingImpl(Thread* thread, ArtMethod* m) {
Daniel Mihalyieb076692014-08-22 17:33:31 +02003525 const SingleStepControl* const ssc = thread->GetSingleStepControl();
3526 if (ssc == nullptr) {
3527 // If we are not single-stepping, then we don't have to force interpreter.
3528 return false;
3529 }
3530 if (Runtime::Current()->GetInstrumentation()->InterpretOnly()) {
3531 // If we are in interpreter only mode, then we don't have to force interpreter.
3532 return false;
3533 }
3534
3535 if (!m->IsNative() && !m->IsProxyMethod()) {
3536 // If we want to step into a method, then we have to force interpreter on that call.
3537 if (ssc->GetStepDepth() == JDWP::SD_INTO) {
3538 return true;
3539 }
3540 }
3541 return false;
3542}
3543
Mathieu Chartiere401d142015-04-22 13:56:20 -07003544bool Dbg::IsForcedInterpreterNeededForResolutionImpl(Thread* thread, ArtMethod* m) {
Daniel Mihalyieb076692014-08-22 17:33:31 +02003545 instrumentation::Instrumentation* const instrumentation =
3546 Runtime::Current()->GetInstrumentation();
3547 // If we are in interpreter only mode, then we don't have to force interpreter.
3548 if (instrumentation->InterpretOnly()) {
3549 return false;
3550 }
3551 // We can only interpret pure Java method.
3552 if (m->IsNative() || m->IsProxyMethod()) {
3553 return false;
3554 }
3555 const SingleStepControl* const ssc = thread->GetSingleStepControl();
3556 if (ssc != nullptr) {
3557 // If we want to step into a method, then we have to force interpreter on that call.
3558 if (ssc->GetStepDepth() == JDWP::SD_INTO) {
3559 return true;
3560 }
3561 // If we are stepping out from a static initializer, by issuing a step
3562 // in or step over, that was implicitly invoked by calling a static method,
3563 // then we need to step into that method. Having a lower stack depth than
3564 // the one the single step control has indicates that the step originates
3565 // from the static initializer.
3566 if (ssc->GetStepDepth() != JDWP::SD_OUT &&
3567 ssc->GetStackDepth() > GetStackDepth(thread)) {
3568 return true;
3569 }
3570 }
3571 // There are cases where we have to force interpreter on deoptimized methods,
3572 // because in some cases the call will not be performed by invoking an entry
3573 // point that has been replaced by the deoptimization, but instead by directly
3574 // invoking the compiled code of the method, for example.
3575 return instrumentation->IsDeoptimized(m);
3576}
3577
Mathieu Chartiere401d142015-04-22 13:56:20 -07003578bool Dbg::IsForcedInstrumentationNeededForResolutionImpl(Thread* thread, ArtMethod* m) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07003579 // The upcall can be null and in that case we don't need to do anything.
Daniel Mihalyieb076692014-08-22 17:33:31 +02003580 if (m == nullptr) {
3581 return false;
3582 }
3583 instrumentation::Instrumentation* const instrumentation =
3584 Runtime::Current()->GetInstrumentation();
3585 // If we are in interpreter only mode, then we don't have to force interpreter.
3586 if (instrumentation->InterpretOnly()) {
3587 return false;
3588 }
3589 // We can only interpret pure Java method.
3590 if (m->IsNative() || m->IsProxyMethod()) {
3591 return false;
3592 }
3593 const SingleStepControl* const ssc = thread->GetSingleStepControl();
3594 if (ssc != nullptr) {
3595 // If we are stepping out from a static initializer, by issuing a step
3596 // out, that was implicitly invoked by calling a static method, then we
3597 // need to step into the caller of that method. Having a lower stack
3598 // depth than the one the single step control has indicates that the
3599 // step originates from the static initializer.
3600 if (ssc->GetStepDepth() == JDWP::SD_OUT &&
3601 ssc->GetStackDepth() > GetStackDepth(thread)) {
3602 return true;
3603 }
3604 }
3605 // If we are returning from a static intializer, that was implicitly
3606 // invoked by calling a static method and the caller is deoptimized,
3607 // then we have to deoptimize the stack without forcing interpreter
3608 // on the static method that was called originally. This problem can
3609 // be solved easily by forcing instrumentation on the called method,
3610 // because the instrumentation exit hook will recognise the need of
3611 // stack deoptimization by calling IsForcedInterpreterNeededForUpcall.
3612 return instrumentation->IsDeoptimized(m);
3613}
3614
Mathieu Chartiere401d142015-04-22 13:56:20 -07003615bool Dbg::IsForcedInterpreterNeededForUpcallImpl(Thread* thread, ArtMethod* m) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07003616 // The upcall can be null and in that case we don't need to do anything.
Daniel Mihalyieb076692014-08-22 17:33:31 +02003617 if (m == nullptr) {
3618 return false;
3619 }
3620 instrumentation::Instrumentation* const instrumentation =
3621 Runtime::Current()->GetInstrumentation();
3622 // If we are in interpreter only mode, then we don't have to force interpreter.
3623 if (instrumentation->InterpretOnly()) {
3624 return false;
3625 }
3626 // We can only interpret pure Java method.
3627 if (m->IsNative() || m->IsProxyMethod()) {
3628 return false;
3629 }
3630 const SingleStepControl* const ssc = thread->GetSingleStepControl();
3631 if (ssc != nullptr) {
3632 // The debugger is not interested in what is happening under the level
3633 // of the step, thus we only force interpreter when we are not below of
3634 // the step.
3635 if (ssc->GetStackDepth() >= GetStackDepth(thread)) {
3636 return true;
3637 }
3638 }
Mingyao Yang99170c62015-07-06 11:10:37 -07003639 if (thread->HasDebuggerShadowFrames()) {
3640 // We need to deoptimize the stack for the exception handling flow so that
3641 // we don't miss any deoptimization that should be done when there are
3642 // debugger shadow frames.
3643 return true;
3644 }
Daniel Mihalyieb076692014-08-22 17:33:31 +02003645 // We have to require stack deoptimization if the upcall is deoptimized.
3646 return instrumentation->IsDeoptimized(m);
3647}
3648
Mingyao Yang99170c62015-07-06 11:10:37 -07003649class NeedsDeoptimizationVisitor : public StackVisitor {
Sebastien Hertz520633b2015-09-08 17:03:36 +02003650 public:
3651 explicit NeedsDeoptimizationVisitor(Thread* self)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003652 REQUIRES_SHARED(Locks::mutator_lock_)
Sebastien Hertz520633b2015-09-08 17:03:36 +02003653 : StackVisitor(self, nullptr, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
3654 needs_deoptimization_(false) {}
3655
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01003656 bool VisitFrame() override REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz520633b2015-09-08 17:03:36 +02003657 // The visitor is meant to be used when handling exception from compiled code only.
David Sehr709b0702016-10-13 09:12:37 -07003658 CHECK(!IsShadowFrame()) << "We only expect to visit compiled frame: "
3659 << ArtMethod::PrettyMethod(GetMethod());
Sebastien Hertz520633b2015-09-08 17:03:36 +02003660 ArtMethod* method = GetMethod();
3661 if (method == nullptr) {
3662 // We reach an upcall and don't need to deoptimize this part of the stack (ManagedFragment)
3663 // so we can stop the visit.
3664 DCHECK(!needs_deoptimization_);
3665 return false;
3666 }
3667 if (Runtime::Current()->GetInstrumentation()->InterpretOnly()) {
3668 // We found a compiled frame in the stack but instrumentation is set to interpret
3669 // everything: we need to deoptimize.
3670 needs_deoptimization_ = true;
3671 return false;
3672 }
3673 if (Runtime::Current()->GetInstrumentation()->IsDeoptimized(method)) {
3674 // We found a deoptimized method in the stack.
3675 needs_deoptimization_ = true;
3676 return false;
3677 }
Mingyao Yang99170c62015-07-06 11:10:37 -07003678 ShadowFrame* frame = GetThread()->FindDebuggerShadowFrame(GetFrameId());
3679 if (frame != nullptr) {
3680 // The debugger allocated a ShadowFrame to update a variable in the stack: we need to
3681 // deoptimize the stack to execute (and deallocate) this frame.
3682 needs_deoptimization_ = true;
3683 return false;
3684 }
Sebastien Hertz520633b2015-09-08 17:03:36 +02003685 return true;
3686 }
3687
3688 bool NeedsDeoptimization() const {
3689 return needs_deoptimization_;
3690 }
3691
3692 private:
3693 // Do we need to deoptimize the stack?
3694 bool needs_deoptimization_;
3695
3696 DISALLOW_COPY_AND_ASSIGN(NeedsDeoptimizationVisitor);
3697};
3698
3699// Do we need to deoptimize the stack to handle an exception?
3700bool Dbg::IsForcedInterpreterNeededForExceptionImpl(Thread* thread) {
3701 const SingleStepControl* const ssc = thread->GetSingleStepControl();
3702 if (ssc != nullptr) {
3703 // We deopt to step into the catch handler.
3704 return true;
3705 }
3706 // Deoptimization is required if at least one method in the stack needs it. However we
3707 // skip frames that will be unwound (thus not executed).
3708 NeedsDeoptimizationVisitor visitor(thread);
3709 visitor.WalkStack(true); // includes upcall.
3710 return visitor.NeedsDeoptimization();
3711}
3712
Jeff Hao449db332013-04-12 18:30:52 -07003713// Scoped utility class to suspend a thread so that we may do tasks such as walk its stack. Doesn't
3714// cause suspension if the thread is the current thread.
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07003715class ScopedDebuggerThreadSuspension {
Jeff Hao449db332013-04-12 18:30:52 -07003716 public:
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07003717 ScopedDebuggerThreadSuspension(Thread* self, JDWP::ObjectId thread_id)
Mathieu Chartier90443472015-07-16 20:32:27 -07003718 REQUIRES(!Locks::thread_list_lock_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003719 REQUIRES_SHARED(Locks::mutator_lock_) :
Ian Rogersf3d874c2014-07-17 18:52:42 -07003720 thread_(nullptr),
Jeff Hao449db332013-04-12 18:30:52 -07003721 error_(JDWP::ERR_NONE),
3722 self_suspend_(false),
Ian Rogers33e95662013-05-20 20:29:14 -07003723 other_suspend_(false) {
Jeff Hao449db332013-04-12 18:30:52 -07003724 ScopedObjectAccessUnchecked soa(self);
Sebastien Hertz69206392015-04-07 15:54:25 +02003725 thread_ = DecodeThread(soa, thread_id, &error_);
Jeff Hao449db332013-04-12 18:30:52 -07003726 if (error_ == JDWP::ERR_NONE) {
3727 if (thread_ == soa.Self()) {
3728 self_suspend_ = true;
3729 } else {
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07003730 Thread* suspended_thread;
3731 {
3732 ScopedThreadSuspension sts(self, kWaitingForDebuggerSuspension);
3733 jobject thread_peer = Dbg::GetObjectRegistry()->GetJObject(thread_id);
3734 bool timed_out;
3735 ThreadList* const thread_list = Runtime::Current()->GetThreadList();
Sebastien Hertzcdd798d2017-04-18 18:28:51 +02003736 suspended_thread = thread_list->SuspendThreadByPeer(thread_peer,
3737 /* request_suspension */ true,
Alex Light46f93402017-06-29 11:59:50 -07003738 SuspendReason::kForDebugger,
Sebastien Hertzcdd798d2017-04-18 18:28:51 +02003739 &timed_out);
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07003740 }
Ian Rogersf3d874c2014-07-17 18:52:42 -07003741 if (suspended_thread == nullptr) {
Jeff Hao449db332013-04-12 18:30:52 -07003742 // Thread terminated from under us while suspending.
3743 error_ = JDWP::ERR_INVALID_THREAD;
3744 } else {
3745 CHECK_EQ(suspended_thread, thread_);
3746 other_suspend_ = true;
3747 }
3748 }
3749 }
Elliott Hughes2435a572012-02-17 16:07:41 -08003750 }
Elliott Hughes86964332012-02-15 19:37:42 -08003751
Jeff Hao449db332013-04-12 18:30:52 -07003752 Thread* GetThread() const {
3753 return thread_;
3754 }
3755
3756 JDWP::JdwpError GetError() const {
3757 return error_;
3758 }
3759
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07003760 ~ScopedDebuggerThreadSuspension() {
Jeff Hao449db332013-04-12 18:30:52 -07003761 if (other_suspend_) {
Alex Light88fd7202017-06-30 08:31:59 -07003762 bool resumed = Runtime::Current()->GetThreadList()->Resume(thread_,
3763 SuspendReason::kForDebugger);
3764 DCHECK(resumed);
Jeff Hao449db332013-04-12 18:30:52 -07003765 }
3766 }
3767
3768 private:
3769 Thread* thread_;
3770 JDWP::JdwpError error_;
3771 bool self_suspend_;
3772 bool other_suspend_;
3773};
3774
3775JDWP::JdwpError Dbg::ConfigureStep(JDWP::ObjectId thread_id, JDWP::JdwpStepSize step_size,
3776 JDWP::JdwpStepDepth step_depth) {
3777 Thread* self = Thread::Current();
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07003778 ScopedDebuggerThreadSuspension sts(self, thread_id);
Jeff Hao449db332013-04-12 18:30:52 -07003779 if (sts.GetError() != JDWP::ERR_NONE) {
3780 return sts.GetError();
3781 }
3782
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003783 // Work out what ArtMethod* we're in, the current line number, and how deep the stack currently
Elliott Hughes2435a572012-02-17 16:07:41 -08003784 // is for step-out.
Ian Rogers0399dde2012-06-06 17:09:28 -07003785 struct SingleStepStackVisitor : public StackVisitor {
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003786 explicit SingleStepStackVisitor(Thread* thread) REQUIRES_SHARED(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01003787 : StackVisitor(thread, nullptr, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
3788 stack_depth(0),
3789 method(nullptr),
3790 line_number(-1) {}
Ian Rogersca190662012-06-26 15:45:57 -07003791
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003792 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
3793 // annotalysis.
Andreas Gampefa6a1b02018-09-07 08:11:55 -07003794 bool VisitFrame() override NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003795 ArtMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07003796 if (!m->IsRuntimeMethod()) {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003797 ++stack_depth;
3798 if (method == nullptr) {
Alex Light73376312017-04-06 10:10:51 -07003799 const DexFile* dex_file = m->GetDexFile();
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003800 method = m;
Alex Light73376312017-04-06 10:10:51 -07003801 if (dex_file != nullptr) {
David Sehr9323e6e2016-09-13 08:58:35 -07003802 line_number = annotations::GetLineNumFromPC(dex_file, m, GetDexPc());
Elliott Hughes2435a572012-02-17 16:07:41 -08003803 }
Elliott Hughes86964332012-02-15 19:37:42 -08003804 }
3805 }
Elliott Hughes530fa002012-03-12 11:44:49 -07003806 return true;
Elliott Hughes86964332012-02-15 19:37:42 -08003807 }
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003808
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003809 int stack_depth;
Mathieu Chartiere401d142015-04-22 13:56:20 -07003810 ArtMethod* method;
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003811 int32_t line_number;
Elliott Hughes86964332012-02-15 19:37:42 -08003812 };
Jeff Hao449db332013-04-12 18:30:52 -07003813
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003814 Thread* const thread = sts.GetThread();
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003815 SingleStepStackVisitor visitor(thread);
Ian Rogers0399dde2012-06-06 17:09:28 -07003816 visitor.WalkStack();
Elliott Hughes86964332012-02-15 19:37:42 -08003817
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003818 // Allocate single step.
Sebastien Hertz1558b572015-02-25 15:05:59 +01003819 SingleStepControl* single_step_control =
3820 new (std::nothrow) SingleStepControl(step_size, step_depth,
3821 visitor.stack_depth, visitor.method);
3822 if (single_step_control == nullptr) {
3823 LOG(ERROR) << "Failed to allocate SingleStepControl";
3824 return JDWP::ERR_OUT_OF_MEMORY;
3825 }
3826
Mathieu Chartiere401d142015-04-22 13:56:20 -07003827 ArtMethod* m = single_step_control->GetMethod();
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003828 const int32_t line_number = visitor.line_number;
Sebastien Hertz52f5f932015-05-28 11:00:57 +02003829 // Note: if the thread is not running Java code (pure native thread), there is no "current"
3830 // method on the stack (and no line number either).
3831 if (m != nullptr && !m->IsNative()) {
David Sehr0225f8e2018-01-31 08:52:24 +00003832 CodeItemDebugInfoAccessor accessor(m->DexInstructionDebugInfo());
Mathieu Chartier3e2e1232018-09-11 12:35:30 -07003833 bool last_pc_valid = false;
3834 uint32_t last_pc = 0u;
3835 // Find the dex_pc values that correspond to the current line, for line-based single-stepping.
3836 accessor.DecodeDebugPositionInfo([&](const DexFile::PositionInfo& entry) {
3837 if (static_cast<int32_t>(entry.line_) == line_number) {
3838 if (!last_pc_valid) {
3839 // Everything from this address until the next line change is ours.
3840 last_pc = entry.address_;
3841 last_pc_valid = true;
3842 }
3843 // Otherwise, if we're already in a valid range for this line,
3844 // just keep going (shouldn't really happen)...
3845 } else if (last_pc_valid) { // and the line number is new
3846 // Add everything from the last entry up until here to the set
3847 for (uint32_t dex_pc = last_pc; dex_pc < entry.address_; ++dex_pc) {
3848 single_step_control->AddDexPc(dex_pc);
3849 }
3850 last_pc_valid = false;
3851 }
3852 return false; // There may be multiple entries for any given line.
3853 });
3854 // If the line number was the last in the position table...
3855 if (last_pc_valid) {
3856 for (uint32_t dex_pc = last_pc; dex_pc < accessor.InsnsSizeInCodeUnits(); ++dex_pc) {
3857 single_step_control->AddDexPc(dex_pc);
3858 }
3859 }
Elliott Hughes3e2e1a22012-02-21 11:33:41 -08003860 }
Elliott Hughes2435a572012-02-17 16:07:41 -08003861
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003862 // Activate single-step in the thread.
3863 thread->ActivateSingleStepControl(single_step_control);
Elliott Hughes86964332012-02-15 19:37:42 -08003864
Elliott Hughes2435a572012-02-17 16:07:41 -08003865 if (VLOG_IS_ON(jdwp)) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003866 VLOG(jdwp) << "Single-step thread: " << *thread;
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003867 VLOG(jdwp) << "Single-step step size: " << single_step_control->GetStepSize();
3868 VLOG(jdwp) << "Single-step step depth: " << single_step_control->GetStepDepth();
David Sehr709b0702016-10-13 09:12:37 -07003869 VLOG(jdwp) << "Single-step current method: "
3870 << ArtMethod::PrettyMethod(single_step_control->GetMethod());
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003871 VLOG(jdwp) << "Single-step current line: " << line_number;
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003872 VLOG(jdwp) << "Single-step current stack depth: " << single_step_control->GetStackDepth();
Elliott Hughes2435a572012-02-17 16:07:41 -08003873 VLOG(jdwp) << "Single-step dex_pc values:";
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003874 for (uint32_t dex_pc : single_step_control->GetDexPcs()) {
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003875 VLOG(jdwp) << StringPrintf(" %#x", dex_pc);
Elliott Hughes2435a572012-02-17 16:07:41 -08003876 }
3877 }
3878
3879 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003880}
3881
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003882void Dbg::UnconfigureStep(JDWP::ObjectId thread_id) {
3883 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07003884 JDWP::JdwpError error;
3885 Thread* thread = DecodeThread(soa, thread_id, &error);
Sebastien Hertz87118ed2013-11-26 17:57:18 +01003886 if (error == JDWP::ERR_NONE) {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003887 thread->DeactivateSingleStepControl();
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003888 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003889}
3890
Elliott Hughes45651fd2012-02-21 15:48:20 -08003891static char JdwpTagToShortyChar(JDWP::JdwpTag tag) {
3892 switch (tag) {
3893 default:
3894 LOG(FATAL) << "unknown JDWP tag: " << PrintableChar(tag);
Ian Rogersfc787ec2014-10-09 21:56:44 -07003895 UNREACHABLE();
Elliott Hughes45651fd2012-02-21 15:48:20 -08003896
3897 // Primitives.
3898 case JDWP::JT_BYTE: return 'B';
3899 case JDWP::JT_CHAR: return 'C';
3900 case JDWP::JT_FLOAT: return 'F';
3901 case JDWP::JT_DOUBLE: return 'D';
3902 case JDWP::JT_INT: return 'I';
3903 case JDWP::JT_LONG: return 'J';
3904 case JDWP::JT_SHORT: return 'S';
3905 case JDWP::JT_VOID: return 'V';
3906 case JDWP::JT_BOOLEAN: return 'Z';
3907
3908 // Reference types.
3909 case JDWP::JT_ARRAY:
3910 case JDWP::JT_OBJECT:
3911 case JDWP::JT_STRING:
3912 case JDWP::JT_THREAD:
3913 case JDWP::JT_THREAD_GROUP:
3914 case JDWP::JT_CLASS_LOADER:
3915 case JDWP::JT_CLASS_OBJECT:
3916 return 'L';
3917 }
3918}
3919
Sebastien Hertzcbc50642015-06-01 17:33:12 +02003920JDWP::JdwpError Dbg::PrepareInvokeMethod(uint32_t request_id, JDWP::ObjectId thread_id,
3921 JDWP::ObjectId object_id, JDWP::RefTypeId class_id,
3922 JDWP::MethodId method_id, uint32_t arg_count,
3923 uint64_t arg_values[], JDWP::JdwpTag* arg_types,
3924 uint32_t options) {
3925 Thread* const self = Thread::Current();
3926 CHECK_EQ(self, GetDebugThread()) << "This must be called by the JDWP thread";
Sebastien Hertzd4032e42015-06-12 15:47:34 +02003927 const bool resume_all_threads = ((options & JDWP::INVOKE_SINGLE_THREADED) == 0);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003928
Sebastien Hertzcbc50642015-06-01 17:33:12 +02003929 ThreadList* thread_list = Runtime::Current()->GetThreadList();
Ian Rogersc0542af2014-09-03 16:16:56 -07003930 Thread* targetThread = nullptr;
Elliott Hughesd07986f2011-12-06 18:27:45 -08003931 {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003932 ScopedObjectAccessUnchecked soa(self);
Ian Rogersc0542af2014-09-03 16:16:56 -07003933 JDWP::JdwpError error;
3934 targetThread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08003935 if (error != JDWP::ERR_NONE) {
3936 LOG(ERROR) << "InvokeMethod request for invalid thread id " << thread_id;
3937 return error;
Elliott Hughesd07986f2011-12-06 18:27:45 -08003938 }
Sebastien Hertz1558b572015-02-25 15:05:59 +01003939 if (targetThread->GetInvokeReq() != nullptr) {
3940 // Thread is already invoking a method on behalf of the debugger.
3941 LOG(ERROR) << "InvokeMethod request for thread already invoking a method: " << *targetThread;
3942 return JDWP::ERR_ALREADY_INVOKING;
3943 }
3944 if (!targetThread->IsReadyForDebugInvoke()) {
3945 // Thread is not suspended by an event so it cannot invoke a method.
Elliott Hughesd07986f2011-12-06 18:27:45 -08003946 LOG(ERROR) << "InvokeMethod request for thread not stopped by event: " << *targetThread;
3947 return JDWP::ERR_INVALID_THREAD;
3948 }
3949
3950 /*
Sebastien Hertzd4032e42015-06-12 15:47:34 +02003951 * According to the JDWP specs, we are expected to resume all threads (or only the
3952 * target thread) once. So if a thread has been suspended more than once (either by
3953 * the debugger for an event or by the runtime for GC), it will remain suspended before
3954 * the invoke is executed. This means the debugger is responsible to properly resume all
3955 * the threads it has suspended so the target thread can execute the method.
Elliott Hughesd07986f2011-12-06 18:27:45 -08003956 *
Sebastien Hertzd4032e42015-06-12 15:47:34 +02003957 * However, for compatibility reason with older versions of debuggers (like Eclipse), we
3958 * fully resume all threads (by canceling *all* debugger suspensions) when the debugger
3959 * wants us to resume all threads. This is to avoid ending up in deadlock situation.
3960 *
3961 * On the other hand, if we are asked to only resume the target thread, then we follow the
3962 * JDWP specs by resuming that thread only once. This means the thread will remain suspended
3963 * if it has been suspended more than once before the invoke (and again, this is the
3964 * responsibility of the debugger to properly resume that thread before invoking a method).
Elliott Hughesd07986f2011-12-06 18:27:45 -08003965 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003966 int suspend_count;
3967 {
Ian Rogers50b35e22012-10-04 10:09:15 -07003968 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003969 suspend_count = targetThread->GetSuspendCount();
3970 }
Sebastien Hertzd4032e42015-06-12 15:47:34 +02003971 if (suspend_count > 1 && resume_all_threads) {
3972 // The target thread will remain suspended even after we resume it. Let's emit a warning
3973 // to indicate the invoke won't be executed until the thread is resumed.
3974 LOG(WARNING) << *targetThread << " suspended more than once (suspend count == "
3975 << suspend_count << "). This thread will invoke the method only once "
3976 << "it is fully resumed.";
Elliott Hughesd07986f2011-12-06 18:27:45 -08003977 }
3978
Ian Rogersc0542af2014-09-03 16:16:56 -07003979 mirror::Object* receiver = gRegistry->Get<mirror::Object*>(object_id, &error);
3980 if (error != JDWP::ERR_NONE) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08003981 return JDWP::ERR_INVALID_OBJECT;
3982 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003983
Sebastien Hertz1558b572015-02-25 15:05:59 +01003984 gRegistry->Get<mirror::Object*>(thread_id, &error);
Ian Rogersc0542af2014-09-03 16:16:56 -07003985 if (error != JDWP::ERR_NONE) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08003986 return JDWP::ERR_INVALID_OBJECT;
3987 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003988
Ian Rogersc0542af2014-09-03 16:16:56 -07003989 mirror::Class* c = DecodeClass(class_id, &error);
3990 if (c == nullptr) {
3991 return error;
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08003992 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003993
Mathieu Chartiere401d142015-04-22 13:56:20 -07003994 ArtMethod* m = FromMethodId(method_id);
Ian Rogersc0542af2014-09-03 16:16:56 -07003995 if (m->IsStatic() != (receiver == nullptr)) {
Elliott Hughes45651fd2012-02-21 15:48:20 -08003996 return JDWP::ERR_INVALID_METHODID;
3997 }
3998 if (m->IsStatic()) {
3999 if (m->GetDeclaringClass() != c) {
4000 return JDWP::ERR_INVALID_METHODID;
4001 }
4002 } else {
4003 if (!m->GetDeclaringClass()->IsAssignableFrom(c)) {
4004 return JDWP::ERR_INVALID_METHODID;
4005 }
4006 }
4007
4008 // Check the argument list matches the method.
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004009 uint32_t shorty_len = 0;
4010 const char* shorty = m->GetShorty(&shorty_len);
4011 if (shorty_len - 1 != arg_count) {
Elliott Hughes45651fd2012-02-21 15:48:20 -08004012 return JDWP::ERR_ILLEGAL_ARGUMENT;
4013 }
Elliott Hughes09201632013-04-15 15:50:07 -07004014
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004015 {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004016 StackHandleScope<2> hs(soa.Self());
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004017 HandleWrapper<mirror::Object> h_obj(hs.NewHandleWrapper(&receiver));
4018 HandleWrapper<mirror::Class> h_klass(hs.NewHandleWrapper(&c));
4019 const DexFile::TypeList* types = m->GetParameterTypeList();
4020 for (size_t i = 0; i < arg_count; ++i) {
4021 if (shorty[i + 1] != JdwpTagToShortyChar(arg_types[i])) {
Elliott Hughes09201632013-04-15 15:50:07 -07004022 return JDWP::ERR_ILLEGAL_ARGUMENT;
4023 }
4024
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004025 if (shorty[i + 1] == 'L') {
4026 // Did we really get an argument of an appropriate reference type?
Vladimir Markob45528c2017-07-27 14:14:28 +01004027 ObjPtr<mirror::Class> parameter_type =
4028 m->ResolveClassFromTypeIndex(types->GetTypeItem(i).type_idx_);
Ian Rogersc0542af2014-09-03 16:16:56 -07004029 mirror::Object* argument = gRegistry->Get<mirror::Object*>(arg_values[i], &error);
4030 if (error != JDWP::ERR_NONE) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004031 return JDWP::ERR_INVALID_OBJECT;
4032 }
Ian Rogersc0542af2014-09-03 16:16:56 -07004033 if (argument != nullptr && !argument->InstanceOf(parameter_type)) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004034 return JDWP::ERR_ILLEGAL_ARGUMENT;
4035 }
4036
4037 // Turn the on-the-wire ObjectId into a jobject.
4038 jvalue& v = reinterpret_cast<jvalue&>(arg_values[i]);
4039 v.l = gRegistry->GetJObject(arg_values[i]);
4040 }
Elliott Hughes09201632013-04-15 15:50:07 -07004041 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08004042 }
4043
Sebastien Hertz1558b572015-02-25 15:05:59 +01004044 // Allocates a DebugInvokeReq.
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004045 DebugInvokeReq* req = new (std::nothrow) DebugInvokeReq(request_id, thread_id, receiver, c, m,
4046 options, arg_values, arg_count);
4047 if (req == nullptr) {
Sebastien Hertz1558b572015-02-25 15:05:59 +01004048 LOG(ERROR) << "Failed to allocate DebugInvokeReq";
4049 return JDWP::ERR_OUT_OF_MEMORY;
4050 }
4051
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004052 // Attaches the DebugInvokeReq to the target thread so it executes the method when
4053 // it is resumed. Once the invocation completes, the target thread will delete it before
4054 // suspending itself (see ThreadList::SuspendSelfForDebugger).
4055 targetThread->SetDebugInvokeReq(req);
Elliott Hughesd07986f2011-12-06 18:27:45 -08004056 }
4057
4058 // 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 +02004059 // away we're sitting high and dry -- but we must release this before the UndoDebuggerSuspensions
4060 // call.
Sebastien Hertzd4032e42015-06-12 15:47:34 +02004061 if (resume_all_threads) {
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004062 VLOG(jdwp) << " Resuming all threads";
4063 thread_list->UndoDebuggerSuspensions();
4064 } else {
4065 VLOG(jdwp) << " Resuming event thread only";
Alex Light88fd7202017-06-30 08:31:59 -07004066 bool resumed = thread_list->Resume(targetThread, SuspendReason::kForDebugger);
4067 DCHECK(resumed);
Elliott Hughesd07986f2011-12-06 18:27:45 -08004068 }
4069
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004070 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004071}
4072
4073void Dbg::ExecuteMethod(DebugInvokeReq* pReq) {
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004074 Thread* const self = Thread::Current();
4075 CHECK_NE(self, GetDebugThread()) << "This must be called by the event thread";
4076
4077 ScopedObjectAccess soa(self);
Elliott Hughesd07986f2011-12-06 18:27:45 -08004078
Elliott Hughes81ff3182012-03-23 20:35:56 -07004079 // We can be called while an exception is pending. We need
Elliott Hughesd07986f2011-12-06 18:27:45 -08004080 // to preserve that across the method invocation.
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004081 StackHandleScope<1> hs(soa.Self());
4082 Handle<mirror::Throwable> old_exception = hs.NewHandle(soa.Self()->GetException());
Sebastien Hertz1558b572015-02-25 15:05:59 +01004083 soa.Self()->ClearException();
Elliott Hughesd07986f2011-12-06 18:27:45 -08004084
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004085 // Execute the method then sends reply to the debugger.
4086 ExecuteMethodWithoutPendingException(soa, pReq);
4087
4088 // If an exception was pending before the invoke, restore it now.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004089 if (old_exception != nullptr) {
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004090 soa.Self()->SetException(old_exception.Get());
4091 }
4092}
4093
4094// Helper function: write a variable-width value into the output input buffer.
4095static void WriteValue(JDWP::ExpandBuf* pReply, int width, uint64_t value) {
4096 switch (width) {
4097 case 1:
4098 expandBufAdd1(pReply, value);
4099 break;
4100 case 2:
4101 expandBufAdd2BE(pReply, value);
4102 break;
4103 case 4:
4104 expandBufAdd4BE(pReply, value);
4105 break;
4106 case 8:
4107 expandBufAdd8BE(pReply, value);
4108 break;
4109 default:
4110 LOG(FATAL) << width;
4111 UNREACHABLE();
4112 }
4113}
4114
4115void Dbg::ExecuteMethodWithoutPendingException(ScopedObjectAccess& soa, DebugInvokeReq* pReq) {
4116 soa.Self()->AssertNoPendingException();
4117
Elliott Hughesd07986f2011-12-06 18:27:45 -08004118 // Translate the method through the vtable, unless the debugger wants to suppress it.
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004119 ArtMethod* m = pReq->method;
Andreas Gampe542451c2016-07-26 09:02:02 -07004120 PointerSize image_pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
Sebastien Hertz1558b572015-02-25 15:05:59 +01004121 if ((pReq->options & JDWP::INVOKE_NONVIRTUAL) == 0 && pReq->receiver.Read() != nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004122 ArtMethod* actual_method =
4123 pReq->klass.Read()->FindVirtualMethodForVirtualOrInterface(m, image_pointer_size);
4124 if (actual_method != m) {
David Sehr709b0702016-10-13 09:12:37 -07004125 VLOG(jdwp) << "ExecuteMethod translated " << ArtMethod::PrettyMethod(m)
4126 << " to " << ArtMethod::PrettyMethod(actual_method);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004127 m = actual_method;
Elliott Hughes45651fd2012-02-21 15:48:20 -08004128 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08004129 }
David Sehr709b0702016-10-13 09:12:37 -07004130 VLOG(jdwp) << "ExecuteMethod " << ArtMethod::PrettyMethod(m)
Sebastien Hertz1558b572015-02-25 15:05:59 +01004131 << " receiver=" << pReq->receiver.Read()
Sebastien Hertzd38667a2013-11-25 15:43:54 +01004132 << " arg_count=" << pReq->arg_count;
Mathieu Chartiere401d142015-04-22 13:56:20 -07004133 CHECK(m != nullptr);
Elliott Hughesd07986f2011-12-06 18:27:45 -08004134
Roland Levillain33d69032015-06-18 18:20:59 +01004135 static_assert(sizeof(jvalue) == sizeof(uint64_t), "jvalue and uint64_t have different sizes.");
Elliott Hughesd07986f2011-12-06 18:27:45 -08004136
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004137 // Invoke the method.
Jeff Hao39b6c242015-05-19 20:30:23 -07004138 ScopedLocalRef<jobject> ref(soa.Env(), soa.AddLocalReference<jobject>(pReq->receiver.Read()));
Andreas Gampe13b27842016-11-07 16:48:23 -08004139 JValue result = InvokeWithJValues(soa, ref.get(), jni::EncodeArtMethod(m),
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004140 reinterpret_cast<jvalue*>(pReq->arg_values.get()));
Elliott Hughesd07986f2011-12-06 18:27:45 -08004141
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004142 // Prepare JDWP ids for the reply.
4143 JDWP::JdwpTag result_tag = BasicTagFromDescriptor(m->GetShorty());
4144 const bool is_object_result = (result_tag == JDWP::JT_OBJECT);
Jeff Hao064d24e2016-08-25 03:52:40 +00004145 StackHandleScope<3> hs(soa.Self());
Sebastien Hertz1558b572015-02-25 15:05:59 +01004146 Handle<mirror::Object> object_result = hs.NewHandle(is_object_result ? result.GetL() : nullptr);
4147 Handle<mirror::Throwable> exception = hs.NewHandle(soa.Self()->GetException());
4148 soa.Self()->ClearException();
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004149
4150 if (!IsDebuggerActive()) {
4151 // The debugger detached: we must not re-suspend threads. We also don't need to fill the reply
4152 // because it won't be sent either.
4153 return;
4154 }
4155
4156 JDWP::ObjectId exceptionObjectId = gRegistry->Add(exception);
4157 uint64_t result_value = 0;
4158 if (exceptionObjectId != 0) {
Sebastien Hertz1558b572015-02-25 15:05:59 +01004159 VLOG(jdwp) << " JDWP invocation returning with exception=" << exception.Get()
4160 << " " << exception->Dump();
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004161 result_value = 0;
Sebastien Hertz1558b572015-02-25 15:05:59 +01004162 } else if (is_object_result) {
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004163 /* if no exception was thrown, examine object result more closely */
Sebastien Hertz1558b572015-02-25 15:05:59 +01004164 JDWP::JdwpTag new_tag = TagFromObject(soa, object_result.Get());
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004165 if (new_tag != result_tag) {
4166 VLOG(jdwp) << " JDWP promoted result from " << result_tag << " to " << new_tag;
4167 result_tag = new_tag;
Elliott Hughesd07986f2011-12-06 18:27:45 -08004168 }
4169
Sebastien Hertz1558b572015-02-25 15:05:59 +01004170 // Register the object in the registry and reference its ObjectId. This ensures
4171 // GC safety and prevents from accessing stale reference if the object is moved.
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004172 result_value = gRegistry->Add(object_result.Get());
Sebastien Hertz1558b572015-02-25 15:05:59 +01004173 } else {
4174 // Primitive result.
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004175 DCHECK(IsPrimitiveTag(result_tag));
4176 result_value = result.GetJ();
4177 }
4178 const bool is_constructor = m->IsConstructor() && !m->IsStatic();
4179 if (is_constructor) {
4180 // If we invoked a constructor (which actually returns void), return the receiver,
4181 // unless we threw, in which case we return null.
Sebastien Hertza3e13772015-11-05 12:09:44 +01004182 DCHECK_EQ(JDWP::JT_VOID, result_tag);
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004183 if (exceptionObjectId == 0) {
Jeff Hao064d24e2016-08-25 03:52:40 +00004184 if (m->GetDeclaringClass()->IsStringClass()) {
4185 // For string constructors, the new string is remapped to the receiver (stored in ref).
4186 Handle<mirror::Object> decoded_ref = hs.NewHandle(soa.Self()->DecodeJObject(ref.get()));
4187 result_value = gRegistry->Add(decoded_ref);
4188 result_tag = TagFromObject(soa, decoded_ref.Get());
4189 } else {
4190 // TODO we could keep the receiver ObjectId in the DebugInvokeReq to avoid looking into the
4191 // object registry.
4192 result_value = GetObjectRegistry()->Add(pReq->receiver.Read());
4193 result_tag = TagFromObject(soa, pReq->receiver.Read());
4194 }
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004195 } else {
4196 result_value = 0;
Sebastien Hertza3e13772015-11-05 12:09:44 +01004197 result_tag = JDWP::JT_OBJECT;
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004198 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08004199 }
4200
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004201 // Suspend other threads if the invoke is not single-threaded.
4202 if ((pReq->options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07004203 ScopedThreadSuspension sts(soa.Self(), kWaitingForDebuggerSuspension);
Hiroshi Yamauchi8f95cf32016-04-19 11:14:06 -07004204 // Avoid a deadlock between GC and debugger where GC gets suspended during GC. b/25800335.
4205 gc::ScopedGCCriticalSection gcs(soa.Self(), gc::kGcCauseDebugger, gc::kCollectorTypeDebugger);
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004206 VLOG(jdwp) << " Suspending all threads";
4207 Runtime::Current()->GetThreadList()->SuspendAllForDebugger();
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004208 }
4209
4210 VLOG(jdwp) << " --> returned " << result_tag
4211 << StringPrintf(" %#" PRIx64 " (except=%#" PRIx64 ")", result_value,
4212 exceptionObjectId);
4213
4214 // Show detailed debug output.
4215 if (result_tag == JDWP::JT_STRING && exceptionObjectId == 0) {
4216 if (result_value != 0) {
4217 if (VLOG_IS_ON(jdwp)) {
4218 std::string result_string;
4219 JDWP::JdwpError error = Dbg::StringToUtf8(result_value, &result_string);
4220 CHECK_EQ(error, JDWP::ERR_NONE);
4221 VLOG(jdwp) << " string '" << result_string << "'";
4222 }
4223 } else {
4224 VLOG(jdwp) << " string (null)";
4225 }
4226 }
4227
4228 // Attach the reply to DebugInvokeReq so it can be sent to the debugger when the event thread
4229 // is ready to suspend.
4230 BuildInvokeReply(pReq->reply, pReq->request_id, result_tag, result_value, exceptionObjectId);
4231}
4232
4233void Dbg::BuildInvokeReply(JDWP::ExpandBuf* pReply, uint32_t request_id, JDWP::JdwpTag result_tag,
4234 uint64_t result_value, JDWP::ObjectId exception) {
4235 // Make room for the JDWP header since we do not know the size of the reply yet.
4236 JDWP::expandBufAddSpace(pReply, kJDWPHeaderLen);
4237
4238 size_t width = GetTagWidth(result_tag);
4239 JDWP::expandBufAdd1(pReply, result_tag);
4240 if (width != 0) {
4241 WriteValue(pReply, width, result_value);
4242 }
4243 JDWP::expandBufAdd1(pReply, JDWP::JT_OBJECT);
4244 JDWP::expandBufAddObjectId(pReply, exception);
4245
4246 // Now we know the size, we can complete the JDWP header.
4247 uint8_t* buf = expandBufGetBuffer(pReply);
4248 JDWP::Set4BE(buf + kJDWPHeaderSizeOffset, expandBufGetLength(pReply));
4249 JDWP::Set4BE(buf + kJDWPHeaderIdOffset, request_id);
4250 JDWP::Set1(buf + kJDWPHeaderFlagsOffset, kJDWPFlagReply); // flags
4251 JDWP::Set2BE(buf + kJDWPHeaderErrorCodeOffset, JDWP::ERR_NONE);
4252}
4253
4254void Dbg::FinishInvokeMethod(DebugInvokeReq* pReq) {
4255 CHECK_NE(Thread::Current(), GetDebugThread()) << "This must be called by the event thread";
4256
4257 JDWP::ExpandBuf* const pReply = pReq->reply;
4258 CHECK(pReply != nullptr) << "No reply attached to DebugInvokeReq";
4259
4260 // We need to prevent other threads (including JDWP thread) from interacting with the debugger
4261 // while we send the reply but are not yet suspended. The JDWP token will be released just before
4262 // we suspend ourself again (see ThreadList::SuspendSelfForDebugger).
4263 gJdwpState->AcquireJdwpTokenForEvent(pReq->thread_id);
4264
4265 // Send the reply unless the debugger detached before the completion of the method.
4266 if (IsDebuggerActive()) {
4267 const size_t replyDataLength = expandBufGetLength(pReply) - kJDWPHeaderLen;
4268 VLOG(jdwp) << StringPrintf("REPLY INVOKE id=0x%06x (length=%zu)",
4269 pReq->request_id, replyDataLength);
4270
4271 gJdwpState->SendRequest(pReply);
4272 } else {
4273 VLOG(jdwp) << "Not sending invoke reply because debugger detached";
Elliott Hughesd07986f2011-12-06 18:27:45 -08004274 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004275}
4276
Alex Light8c2b9292017-11-09 13:21:01 -08004277bool Dbg::DdmHandleChunk(JNIEnv* env,
4278 uint32_t type,
4279 const ArrayRef<const jbyte>& data,
4280 /*out*/uint32_t* out_type,
4281 /*out*/std::vector<uint8_t>* out_data) {
4282 ScopedLocalRef<jbyteArray> dataArray(env, env->NewByteArray(data.size()));
Ian Rogersc0542af2014-09-03 16:16:56 -07004283 if (dataArray.get() == nullptr) {
Alex Light8c2b9292017-11-09 13:21:01 -08004284 LOG(WARNING) << "byte[] allocation failed: " << data.size();
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004285 env->ExceptionClear();
4286 return false;
4287 }
Alex Light8c2b9292017-11-09 13:21:01 -08004288 env->SetByteArrayRegion(dataArray.get(),
4289 0,
4290 data.size(),
4291 reinterpret_cast<const jbyte*>(data.data()));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004292 // Call "private static Chunk dispatch(int type, byte[] data, int offset, int length)".
Alex Light8c2b9292017-11-09 13:21:01 -08004293 ScopedLocalRef<jobject> chunk(
4294 env,
4295 env->CallStaticObjectMethod(
4296 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
4297 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_dispatch,
4298 type, dataArray.get(), 0, data.size()));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004299 if (env->ExceptionCheck()) {
Alex Light1eeefa62018-03-19 13:47:56 -07004300 Thread* self = Thread::Current();
4301 ScopedObjectAccess soa(self);
4302 LOG(INFO) << StringPrintf("Exception thrown by dispatcher for 0x%08x", type) << std::endl
4303 << self->GetException()->Dump();
4304 self->ClearException();
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004305 return false;
4306 }
4307
Ian Rogersc0542af2014-09-03 16:16:56 -07004308 if (chunk.get() == nullptr) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004309 return false;
4310 }
4311
4312 /*
4313 * Pull the pieces out of the chunk. We copy the results into a
4314 * newly-allocated buffer that the caller can free. We don't want to
4315 * continue using the Chunk object because nothing has a reference to it.
4316 *
4317 * We could avoid this by returning type/data/offset/length and having
4318 * the caller be aware of the object lifetime issues, but that
Elliott Hughes81ff3182012-03-23 20:35:56 -07004319 * integrates the JDWP code more tightly into the rest of the runtime, and doesn't work
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004320 * if we have responses for multiple chunks.
4321 *
4322 * So we're pretty much stuck with copying data around multiple times.
4323 */
Alex Light8c2b9292017-11-09 13:21:01 -08004324 ScopedLocalRef<jbyteArray> replyData(
4325 env,
4326 reinterpret_cast<jbyteArray>(
4327 env->GetObjectField(
4328 chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_data)));
4329 jint offset = env->GetIntField(chunk.get(),
4330 WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_offset);
4331 jint length = env->GetIntField(chunk.get(),
4332 WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_length);
4333 *out_type = env->GetIntField(chunk.get(),
4334 WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_type);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004335
Alex Light8c2b9292017-11-09 13:21:01 -08004336 VLOG(jdwp) << StringPrintf("DDM reply: type=0x%08x data=%p offset=%d length=%d",
4337 type,
4338 replyData.get(),
4339 offset,
4340 length);
Alex Light8c2b9292017-11-09 13:21:01 -08004341 out_data->resize(length);
4342 env->GetByteArrayRegion(replyData.get(),
4343 offset,
4344 length,
4345 reinterpret_cast<jbyte*>(out_data->data()));
Alex Light6f2a6342017-12-12 09:55:05 -08004346
Alex Lighte5463a82017-12-12 13:33:28 -08004347 if (env->ExceptionCheck()) {
Alex Light1eeefa62018-03-19 13:47:56 -07004348 Thread* self = Thread::Current();
4349 ScopedObjectAccess soa(self);
Alex Lighte5463a82017-12-12 13:33:28 -08004350 LOG(INFO) << StringPrintf("Exception thrown when reading response data from dispatcher 0x%08x",
Alex Light1eeefa62018-03-19 13:47:56 -07004351 type) << std::endl << self->GetException()->Dump();
4352 self->ClearException();
Alex Lighte5463a82017-12-12 13:33:28 -08004353 return false;
4354 }
4355
Alex Light8c2b9292017-11-09 13:21:01 -08004356 return true;
4357}
4358
4359/*
4360 * "request" contains a full JDWP packet, possibly with multiple chunks. We
4361 * need to process each, accumulate the replies, and ship the whole thing
4362 * back.
4363 *
4364 * Returns "true" if we have a reply. The reply buffer is newly allocated,
4365 * and includes the chunk type/length, followed by the data.
4366 *
4367 * OLD-TODO: we currently assume that the request and reply include a single
4368 * chunk. If this becomes inconvenient we will need to adapt.
4369 */
4370bool Dbg::DdmHandlePacket(JDWP::Request* request, uint8_t** pReplyBuf, int* pReplyLen) {
4371 Thread* self = Thread::Current();
4372 JNIEnv* env = self->GetJniEnv();
4373
4374 uint32_t type = request->ReadUnsigned32("type");
4375 uint32_t length = request->ReadUnsigned32("length");
4376
4377 // Create a byte[] corresponding to 'request'.
4378 size_t request_length = request->size();
4379 // Run through and find all chunks. [Currently just find the first.]
4380 if (length != request_length) {
4381 LOG(WARNING) << StringPrintf("bad chunk found (len=%u pktLen=%zd)", length, request_length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004382 return false;
4383 }
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004384
Alex Light8c2b9292017-11-09 13:21:01 -08004385 ArrayRef<const jbyte> data(reinterpret_cast<const jbyte*>(request->data()), request_length);
4386 std::vector<uint8_t> out_data;
4387 uint32_t out_type = 0;
4388 request->Skip(request_length);
Alex Light6f2a6342017-12-12 09:55:05 -08004389 if (!DdmHandleChunk(env, type, data, &out_type, &out_data) || out_data.empty()) {
Alex Light8c2b9292017-11-09 13:21:01 -08004390 return false;
4391 }
4392 const uint32_t kDdmHeaderSize = 8;
4393 *pReplyLen = out_data.size() + kDdmHeaderSize;
4394 *pReplyBuf = new uint8_t[out_data.size() + kDdmHeaderSize];
4395 memcpy((*pReplyBuf) + kDdmHeaderSize, out_data.data(), out_data.size());
4396 JDWP::Set4BE(*pReplyBuf, out_type);
4397 JDWP::Set4BE((*pReplyBuf) + 4, static_cast<uint32_t>(out_data.size()));
4398 VLOG(jdwp)
4399 << StringPrintf("dvmHandleDdm returning type=%.4s", reinterpret_cast<char*>(*pReplyBuf))
4400 << "0x" << std::hex << reinterpret_cast<uintptr_t>(*pReplyBuf) << std::dec
4401 << " len= " << out_data.size();
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004402 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004403}
4404
Elliott Hughesa2155262011-11-16 16:26:58 -08004405void Dbg::DdmBroadcast(bool connect) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08004406 VLOG(jdwp) << "Broadcasting DDM " << (connect ? "connect" : "disconnect") << "...";
Elliott Hughes47fce012011-10-25 18:37:19 -07004407
4408 Thread* self = Thread::Current();
Ian Rogers50b35e22012-10-04 10:09:15 -07004409 if (self->GetState() != kRunnable) {
4410 LOG(ERROR) << "DDM broadcast in thread state " << self->GetState();
4411 /* try anyway? */
Elliott Hughes47fce012011-10-25 18:37:19 -07004412 }
4413
4414 JNIEnv* env = self->GetJniEnv();
Elliott Hughes47fce012011-10-25 18:37:19 -07004415 jint event = connect ? 1 /*DdmServer.CONNECTED*/ : 2 /*DdmServer.DISCONNECTED*/;
Elliott Hugheseac76672012-05-24 21:56:51 -07004416 env->CallStaticVoidMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
4417 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_broadcast,
4418 event);
Elliott Hughes47fce012011-10-25 18:37:19 -07004419 if (env->ExceptionCheck()) {
4420 LOG(ERROR) << "DdmServer.broadcast " << event << " failed";
4421 env->ExceptionDescribe();
4422 env->ExceptionClear();
4423 }
4424}
4425
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004426void Dbg::DdmConnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08004427 Dbg::DdmBroadcast(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004428}
4429
4430void Dbg::DdmDisconnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08004431 Dbg::DdmBroadcast(false);
Elliott Hughes47fce012011-10-25 18:37:19 -07004432 gDdmThreadNotification = false;
4433}
4434
4435/*
Elliott Hughes82188472011-11-07 18:11:48 -08004436 * Send a notification when a thread starts, stops, or changes its name.
Elliott Hughes47fce012011-10-25 18:37:19 -07004437 *
4438 * Because we broadcast the full set of threads when the notifications are
4439 * first enabled, it's possible for "thread" to be actively executing.
4440 */
Elliott Hughes82188472011-11-07 18:11:48 -08004441void Dbg::DdmSendThreadNotification(Thread* t, uint32_t type) {
Elliott Hughes47fce012011-10-25 18:37:19 -07004442 if (!gDdmThreadNotification) {
4443 return;
4444 }
4445
Alex Light772099a2017-11-21 14:05:04 -08004446 RuntimeCallbacks* cb = Runtime::Current()->GetRuntimeCallbacks();
Elliott Hughes82188472011-11-07 18:11:48 -08004447 if (type == CHUNK_TYPE("THDE")) {
Elliott Hughes47fce012011-10-25 18:37:19 -07004448 uint8_t buf[4];
Ian Rogersd9c4fc92013-10-01 19:45:43 -07004449 JDWP::Set4BE(&buf[0], t->GetThreadId());
Alex Light772099a2017-11-21 14:05:04 -08004450 cb->DdmPublishChunk(CHUNK_TYPE("THDE"), ArrayRef<const uint8_t>(buf));
Elliott Hughes82188472011-11-07 18:11:48 -08004451 } else {
4452 CHECK(type == CHUNK_TYPE("THCR") || type == CHUNK_TYPE("THNM")) << type;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004453 ScopedObjectAccessUnchecked soa(Thread::Current());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004454 StackHandleScope<1> hs(soa.Self());
Andreas Gampe08883de2016-11-08 13:20:52 -08004455 Handle<mirror::String> name(hs.NewHandle(t->GetThreadName()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004456 size_t char_count = (name != nullptr) ? name->GetLength() : 0;
4457 const jchar* chars = (name != nullptr) ? name->GetValue() : nullptr;
4458 bool is_compressed = (name != nullptr) ? name->IsCompressed() : false;
Elliott Hughes82188472011-11-07 18:11:48 -08004459
Elliott Hughes21f32d72011-11-09 17:44:13 -08004460 std::vector<uint8_t> bytes;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07004461 JDWP::Append4BE(bytes, t->GetThreadId());
jessicahandojo3aaa37b2016-07-29 14:46:37 -07004462 if (is_compressed) {
4463 const uint8_t* chars_compressed = name->GetValueCompressed();
4464 JDWP::AppendUtf16CompressedBE(bytes, chars_compressed, char_count);
4465 } else {
4466 JDWP::AppendUtf16BE(bytes, chars, char_count);
4467 }
Elliott Hughes21f32d72011-11-09 17:44:13 -08004468 CHECK_EQ(bytes.size(), char_count*2 + sizeof(uint32_t)*2);
Alex Light772099a2017-11-21 14:05:04 -08004469 cb->DdmPublishChunk(type, ArrayRef<const uint8_t>(bytes));
Elliott Hughes47fce012011-10-25 18:37:19 -07004470 }
4471}
4472
Elliott Hughes47fce012011-10-25 18:37:19 -07004473void Dbg::DdmSetThreadNotification(bool enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004474 // Enable/disable thread notifications.
Elliott Hughes47fce012011-10-25 18:37:19 -07004475 gDdmThreadNotification = enable;
4476 if (enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004477 // Suspend the VM then post thread start notifications for all threads. Threads attaching will
4478 // see a suspension in progress and block until that ends. They then post their own start
4479 // notification.
4480 SuspendVM();
4481 std::list<Thread*> threads;
Ian Rogers50b35e22012-10-04 10:09:15 -07004482 Thread* self = Thread::Current();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004483 {
Ian Rogers50b35e22012-10-04 10:09:15 -07004484 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004485 threads = Runtime::Current()->GetThreadList()->GetList();
4486 }
4487 {
Ian Rogers50b35e22012-10-04 10:09:15 -07004488 ScopedObjectAccess soa(self);
Mathieu Chartier02e25112013-08-14 16:14:24 -07004489 for (Thread* thread : threads) {
4490 Dbg::DdmSendThreadNotification(thread, CHUNK_TYPE("THCR"));
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004491 }
4492 }
4493 ResumeVM();
Elliott Hughes47fce012011-10-25 18:37:19 -07004494 }
4495}
4496
Elliott Hughesa2155262011-11-16 16:26:58 -08004497void Dbg::PostThreadStartOrStop(Thread* t, uint32_t type) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07004498 if (IsDebuggerActive()) {
Sebastien Hertz6995c602014-09-09 12:10:13 +02004499 gJdwpState->PostThreadChange(t, type == CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07004500 }
Elliott Hughes82188472011-11-07 18:11:48 -08004501 Dbg::DdmSendThreadNotification(t, type);
Elliott Hughes47fce012011-10-25 18:37:19 -07004502}
4503
4504void Dbg::PostThreadStart(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004505 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07004506}
4507
4508void Dbg::PostThreadDeath(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004509 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THDE"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004510}
4511
Mathieu Chartierad466ad2015-01-08 16:28:08 -08004512JDWP::JdwpState* Dbg::GetJdwpState() {
4513 return gJdwpState;
4514}
4515
Elliott Hughes767a1472011-10-26 18:49:02 -07004516int Dbg::DdmHandleHpifChunk(HpifWhen when) {
4517 if (when == HPIF_WHEN_NOW) {
Elliott Hughes7162ad92011-10-27 14:08:42 -07004518 DdmSendHeapInfo(when);
Elliott Hughes767a1472011-10-26 18:49:02 -07004519 return true;
4520 }
4521
4522 if (when != HPIF_WHEN_NEVER && when != HPIF_WHEN_NEXT_GC && when != HPIF_WHEN_EVERY_GC) {
4523 LOG(ERROR) << "invalid HpifWhen value: " << static_cast<int>(when);
4524 return false;
4525 }
4526
4527 gDdmHpifWhen = when;
4528 return true;
4529}
4530
4531bool Dbg::DdmHandleHpsgNhsgChunk(Dbg::HpsgWhen when, Dbg::HpsgWhat what, bool native) {
4532 if (when != HPSG_WHEN_NEVER && when != HPSG_WHEN_EVERY_GC) {
4533 LOG(ERROR) << "invalid HpsgWhen value: " << static_cast<int>(when);
4534 return false;
4535 }
4536
4537 if (what != HPSG_WHAT_MERGED_OBJECTS && what != HPSG_WHAT_DISTINCT_OBJECTS) {
4538 LOG(ERROR) << "invalid HpsgWhat value: " << static_cast<int>(what);
4539 return false;
4540 }
4541
4542 if (native) {
4543 gDdmNhsgWhen = when;
4544 gDdmNhsgWhat = what;
4545 } else {
4546 gDdmHpsgWhen = when;
4547 gDdmHpsgWhat = what;
4548 }
4549 return true;
4550}
4551
Elliott Hughes7162ad92011-10-27 14:08:42 -07004552void Dbg::DdmSendHeapInfo(HpifWhen reason) {
4553 // If there's a one-shot 'when', reset it.
4554 if (reason == gDdmHpifWhen) {
4555 if (gDdmHpifWhen == HPIF_WHEN_NEXT_GC) {
4556 gDdmHpifWhen = HPIF_WHEN_NEVER;
4557 }
4558 }
4559
4560 /*
4561 * Chunk HPIF (client --> server)
4562 *
4563 * Heap Info. General information about the heap,
4564 * suitable for a summary display.
4565 *
4566 * [u4]: number of heaps
4567 *
4568 * For each heap:
4569 * [u4]: heap ID
4570 * [u8]: timestamp in ms since Unix epoch
4571 * [u1]: capture reason (same as 'when' value from server)
4572 * [u4]: max heap size in bytes (-Xmx)
4573 * [u4]: current heap size in bytes
4574 * [u4]: current number of bytes allocated
4575 * [u4]: current number of objects allocated
4576 */
4577 uint8_t heap_count = 1;
Ian Rogers1d54e732013-05-02 21:10:01 -07004578 gc::Heap* heap = Runtime::Current()->GetHeap();
Elliott Hughes21f32d72011-11-09 17:44:13 -08004579 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08004580 JDWP::Append4BE(bytes, heap_count);
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004581 JDWP::Append4BE(bytes, 1); // Heap id (bogus; we only have one heap).
Elliott Hughes545a0642011-11-08 19:10:03 -08004582 JDWP::Append8BE(bytes, MilliTime());
4583 JDWP::Append1BE(bytes, reason);
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004584 JDWP::Append4BE(bytes, heap->GetMaxMemory()); // Max allowed heap size in bytes.
4585 JDWP::Append4BE(bytes, heap->GetTotalMemory()); // Current heap size in bytes.
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08004586 JDWP::Append4BE(bytes, heap->GetBytesAllocated());
4587 JDWP::Append4BE(bytes, heap->GetObjectsAllocated());
Elliott Hughes21f32d72011-11-09 17:44:13 -08004588 CHECK_EQ(bytes.size(), 4U + (heap_count * (4 + 8 + 1 + 4 + 4 + 4 + 4)));
Alex Light772099a2017-11-21 14:05:04 -08004589 Runtime::Current()->GetRuntimeCallbacks()->DdmPublishChunk(CHUNK_TYPE("HPIF"),
4590 ArrayRef<const uint8_t>(bytes));
Elliott Hughes767a1472011-10-26 18:49:02 -07004591}
4592
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004593enum HpsgSolidity {
4594 SOLIDITY_FREE = 0,
4595 SOLIDITY_HARD = 1,
4596 SOLIDITY_SOFT = 2,
4597 SOLIDITY_WEAK = 3,
4598 SOLIDITY_PHANTOM = 4,
4599 SOLIDITY_FINALIZABLE = 5,
4600 SOLIDITY_SWEEP = 6,
4601};
4602
4603enum HpsgKind {
4604 KIND_OBJECT = 0,
4605 KIND_CLASS_OBJECT = 1,
4606 KIND_ARRAY_1 = 2,
4607 KIND_ARRAY_2 = 3,
4608 KIND_ARRAY_4 = 4,
4609 KIND_ARRAY_8 = 5,
4610 KIND_UNKNOWN = 6,
4611 KIND_NATIVE = 7,
4612};
4613
4614#define HPSG_PARTIAL (1<<7)
4615#define HPSG_STATE(solidity, kind) ((uint8_t)((((kind) & 0x7) << 3) | ((solidity) & 0x7)))
4616
Ian Rogers30fab402012-01-23 15:43:46 -08004617class HeapChunkContext {
4618 public:
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004619 // Maximum chunk size. Obtain this from the formula:
4620 // (((maximum_heap_size / ALLOCATION_UNIT_SIZE) + 255) / 256) * 2
4621 HeapChunkContext(bool merge, bool native)
Ian Rogers30fab402012-01-23 15:43:46 -08004622 : buf_(16384 - 16),
4623 type_(0),
Mathieu Chartier36dab362014-07-30 14:59:56 -07004624 chunk_overhead_(0) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004625 Reset();
4626 if (native) {
Ian Rogers30fab402012-01-23 15:43:46 -08004627 type_ = CHUNK_TYPE("NHSG");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004628 } else {
Ian Rogers30fab402012-01-23 15:43:46 -08004629 type_ = merge ? CHUNK_TYPE("HPSG") : CHUNK_TYPE("HPSO");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004630 }
4631 }
4632
4633 ~HeapChunkContext() {
Ian Rogers30fab402012-01-23 15:43:46 -08004634 if (p_ > &buf_[0]) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004635 Flush();
4636 }
4637 }
4638
Mathieu Chartier36dab362014-07-30 14:59:56 -07004639 void SetChunkOverhead(size_t chunk_overhead) {
4640 chunk_overhead_ = chunk_overhead;
4641 }
4642
4643 void ResetStartOfNextChunk() {
4644 startOfNextMemoryChunk_ = nullptr;
4645 }
4646
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004647 void EnsureHeader(const void* chunk_ptr) {
Ian Rogers30fab402012-01-23 15:43:46 -08004648 if (!needHeader_) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004649 return;
4650 }
4651
4652 // Start a new HPSx chunk.
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004653 JDWP::Write4BE(&p_, 1); // Heap id (bogus; we only have one heap).
4654 JDWP::Write1BE(&p_, 8); // Size of allocation unit, in bytes.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004655
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004656 JDWP::Write4BE(&p_, reinterpret_cast<uintptr_t>(chunk_ptr)); // virtual address of segment start.
4657 JDWP::Write4BE(&p_, 0); // offset of this piece (relative to the virtual address).
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004658 // [u4]: length of piece, in allocation units
4659 // 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 -08004660 pieceLenField_ = p_;
4661 JDWP::Write4BE(&p_, 0x55555555);
4662 needHeader_ = false;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004663 }
4664
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004665 void Flush() REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -07004666 if (pieceLenField_ == nullptr) {
Ian Rogersd636b062013-01-18 17:51:18 -08004667 // Flush immediately post Reset (maybe back-to-back Flush). Ignore.
4668 CHECK(needHeader_);
4669 return;
4670 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004671 // Patch the "length of piece" field.
Ian Rogers30fab402012-01-23 15:43:46 -08004672 CHECK_LE(&buf_[0], pieceLenField_);
4673 CHECK_LE(pieceLenField_, p_);
4674 JDWP::Set4BE(pieceLenField_, totalAllocationUnits_);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004675
Alex Light772099a2017-11-21 14:05:04 -08004676 ArrayRef<const uint8_t> out(&buf_[0], p_ - &buf_[0]);
4677 Runtime::Current()->GetRuntimeCallbacks()->DdmPublishChunk(type_, out);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004678 Reset();
4679 }
4680
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004681 static void HeapChunkJavaCallback(void* start, void* end, size_t used_bytes, void* arg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004682 REQUIRES_SHARED(Locks::heap_bitmap_lock_,
Ian Rogersb726dcb2012-09-05 08:57:23 -07004683 Locks::mutator_lock_) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004684 reinterpret_cast<HeapChunkContext*>(arg)->HeapChunkJavaCallback(start, end, used_bytes);
4685 }
4686
4687 static void HeapChunkNativeCallback(void* start, void* end, size_t used_bytes, void* arg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004688 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004689 reinterpret_cast<HeapChunkContext*>(arg)->HeapChunkNativeCallback(start, end, used_bytes);
Elliott Hughesa2155262011-11-16 16:26:58 -08004690 }
4691
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004692 private:
Elliott Hughesa2155262011-11-16 16:26:58 -08004693 enum { ALLOCATION_UNIT_SIZE = 8 };
4694
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004695 void Reset() {
Ian Rogers30fab402012-01-23 15:43:46 -08004696 p_ = &buf_[0];
Mathieu Chartier36dab362014-07-30 14:59:56 -07004697 ResetStartOfNextChunk();
Ian Rogers30fab402012-01-23 15:43:46 -08004698 totalAllocationUnits_ = 0;
4699 needHeader_ = true;
Ian Rogersc0542af2014-09-03 16:16:56 -07004700 pieceLenField_ = nullptr;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004701 }
4702
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004703 bool IsNative() const {
4704 return type_ == CHUNK_TYPE("NHSG");
4705 }
4706
4707 // Returns true if the object is not an empty chunk.
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004708 bool ProcessRecord(void* start, size_t used_bytes) REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers30fab402012-01-23 15:43:46 -08004709 // Note: heap call backs cannot manipulate the heap upon which they are crawling, care is taken
4710 // in the following code not to allocate memory, by ensuring buf_ is of the correct size
Ian Rogers15bf2d32012-08-28 17:33:04 -07004711 if (used_bytes == 0) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004712 if (start == nullptr) {
4713 // Reset for start of new heap.
4714 startOfNextMemoryChunk_ = nullptr;
4715 Flush();
4716 }
4717 // Only process in use memory so that free region information
4718 // also includes dlmalloc book keeping.
4719 return false;
Elliott Hughesa2155262011-11-16 16:26:58 -08004720 }
Ian Rogersc0542af2014-09-03 16:16:56 -07004721 if (startOfNextMemoryChunk_ != nullptr) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004722 // Transmit any pending free memory. Native free memory of over kMaxFreeLen could be because
4723 // of the use of mmaps, so don't report. If not free memory then start a new segment.
4724 bool flush = true;
4725 if (start > startOfNextMemoryChunk_) {
4726 const size_t kMaxFreeLen = 2 * kPageSize;
4727 void* free_start = startOfNextMemoryChunk_;
4728 void* free_end = start;
4729 const size_t free_len =
4730 reinterpret_cast<uintptr_t>(free_end) - reinterpret_cast<uintptr_t>(free_start);
4731 if (!IsNative() || free_len < kMaxFreeLen) {
4732 AppendChunk(HPSG_STATE(SOLIDITY_FREE, 0), free_start, free_len, IsNative());
4733 flush = false;
Ian Rogers15bf2d32012-08-28 17:33:04 -07004734 }
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004735 }
4736 if (flush) {
4737 startOfNextMemoryChunk_ = nullptr;
4738 Flush();
4739 }
Ian Rogers15bf2d32012-08-28 17:33:04 -07004740 }
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004741 return true;
Ian Rogers15bf2d32012-08-28 17:33:04 -07004742 }
Elliott Hughesa2155262011-11-16 16:26:58 -08004743
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004744 void HeapChunkNativeCallback(void* start, void* /*end*/, size_t used_bytes)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004745 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004746 if (ProcessRecord(start, used_bytes)) {
4747 uint8_t state = ExamineNativeObject(start);
4748 AppendChunk(state, start, used_bytes + chunk_overhead_, true /*is_native*/);
4749 startOfNextMemoryChunk_ = reinterpret_cast<char*>(start) + used_bytes + chunk_overhead_;
4750 }
4751 }
4752
4753 void HeapChunkJavaCallback(void* start, void* /*end*/, size_t used_bytes)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004754 REQUIRES_SHARED(Locks::heap_bitmap_lock_, Locks::mutator_lock_) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004755 if (ProcessRecord(start, used_bytes)) {
4756 // Determine the type of this chunk.
4757 // OLD-TODO: if context.merge, see if this chunk is different from the last chunk.
4758 // If it's the same, we should combine them.
4759 uint8_t state = ExamineJavaObject(reinterpret_cast<mirror::Object*>(start));
4760 AppendChunk(state, start, used_bytes + chunk_overhead_, false /*is_native*/);
4761 startOfNextMemoryChunk_ = reinterpret_cast<char*>(start) + used_bytes + chunk_overhead_;
4762 }
4763 }
4764
4765 void AppendChunk(uint8_t state, void* ptr, size_t length, bool is_native)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004766 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07004767 // Make sure there's enough room left in the buffer.
4768 // We need to use two bytes for every fractional 256 allocation units used by the chunk plus
4769 // 17 bytes for any header.
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004770 const size_t needed = ((RoundUp(length / ALLOCATION_UNIT_SIZE, 256) / 256) * 2) + 17;
4771 size_t byte_left = &buf_.back() - p_;
4772 if (byte_left < needed) {
4773 if (is_native) {
Pavel Vyssotski7522c742014-12-08 13:38:26 +06004774 // Cannot trigger memory allocation while walking native heap.
Pavel Vyssotski7522c742014-12-08 13:38:26 +06004775 return;
4776 }
Ian Rogers15bf2d32012-08-28 17:33:04 -07004777 Flush();
4778 }
4779
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004780 byte_left = &buf_.back() - p_;
4781 if (byte_left < needed) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07004782 LOG(WARNING) << "Chunk is too big to transmit (chunk_len=" << length << ", "
4783 << needed << " bytes)";
4784 return;
4785 }
4786 EnsureHeader(ptr);
Elliott Hughesa2155262011-11-16 16:26:58 -08004787 // Write out the chunk description.
Ian Rogers15bf2d32012-08-28 17:33:04 -07004788 length /= ALLOCATION_UNIT_SIZE; // Convert to allocation units.
4789 totalAllocationUnits_ += length;
4790 while (length > 256) {
Ian Rogers30fab402012-01-23 15:43:46 -08004791 *p_++ = state | HPSG_PARTIAL;
4792 *p_++ = 255; // length - 1
Ian Rogers15bf2d32012-08-28 17:33:04 -07004793 length -= 256;
Elliott Hughesa2155262011-11-16 16:26:58 -08004794 }
Ian Rogers30fab402012-01-23 15:43:46 -08004795 *p_++ = state;
Ian Rogers15bf2d32012-08-28 17:33:04 -07004796 *p_++ = length - 1;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004797 }
4798
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004799 uint8_t ExamineNativeObject(const void* p) REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004800 return p == nullptr ? HPSG_STATE(SOLIDITY_FREE, 0) : HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
4801 }
4802
4803 uint8_t ExamineJavaObject(mirror::Object* o)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004804 REQUIRES_SHARED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -07004805 if (o == nullptr) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004806 return HPSG_STATE(SOLIDITY_FREE, 0);
4807 }
Elliott Hughesa2155262011-11-16 16:26:58 -08004808 // It's an allocated chunk. Figure out what it is.
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004809 gc::Heap* heap = Runtime::Current()->GetHeap();
4810 if (!heap->IsLiveObjectLocked(o)) {
4811 LOG(ERROR) << "Invalid object in managed heap: " << o;
Elliott Hughesa2155262011-11-16 16:26:58 -08004812 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
4813 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004814 mirror::Class* c = o->GetClass();
Ian Rogersc0542af2014-09-03 16:16:56 -07004815 if (c == nullptr) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004816 // The object was probably just created but hasn't been initialized yet.
4817 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
4818 }
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004819 if (!heap->IsValidObjectAddress(c)) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07004820 LOG(ERROR) << "Invalid class for managed heap object: " << o << " " << c;
Elliott Hughesa2155262011-11-16 16:26:58 -08004821 return HPSG_STATE(SOLIDITY_HARD, KIND_UNKNOWN);
4822 }
Mathieu Chartierf26e1b32015-01-29 10:47:10 -08004823 if (c->GetClass() == nullptr) {
4824 LOG(ERROR) << "Null class of class " << c << " for object " << o;
4825 return HPSG_STATE(SOLIDITY_HARD, KIND_UNKNOWN);
4826 }
Elliott Hughesa2155262011-11-16 16:26:58 -08004827 if (c->IsClassClass()) {
4828 return HPSG_STATE(SOLIDITY_HARD, KIND_CLASS_OBJECT);
4829 }
Elliott Hughesa2155262011-11-16 16:26:58 -08004830 if (c->IsArrayClass()) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004831 switch (c->GetComponentSize()) {
4832 case 1: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_1);
4833 case 2: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_2);
4834 case 4: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
4835 case 8: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_8);
4836 }
4837 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004838 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
4839 }
4840
Ian Rogers30fab402012-01-23 15:43:46 -08004841 std::vector<uint8_t> buf_;
4842 uint8_t* p_;
4843 uint8_t* pieceLenField_;
Ian Rogers15bf2d32012-08-28 17:33:04 -07004844 void* startOfNextMemoryChunk_;
Ian Rogers30fab402012-01-23 15:43:46 -08004845 size_t totalAllocationUnits_;
4846 uint32_t type_;
Ian Rogers30fab402012-01-23 15:43:46 -08004847 bool needHeader_;
Mathieu Chartier36dab362014-07-30 14:59:56 -07004848 size_t chunk_overhead_;
Ian Rogers30fab402012-01-23 15:43:46 -08004849
Elliott Hughesa2155262011-11-16 16:26:58 -08004850 DISALLOW_COPY_AND_ASSIGN(HeapChunkContext);
4851};
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004852
4853void Dbg::DdmSendHeapSegments(bool native) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004854 Dbg::HpsgWhen when = native ? gDdmNhsgWhen : gDdmHpsgWhen;
4855 Dbg::HpsgWhat what = native ? gDdmNhsgWhat : gDdmHpsgWhat;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004856 if (when == HPSG_WHEN_NEVER) {
4857 return;
4858 }
Alex Light772099a2017-11-21 14:05:04 -08004859 RuntimeCallbacks* cb = Runtime::Current()->GetRuntimeCallbacks();
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004860 // Figure out what kind of chunks we'll be sending.
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004861 CHECK(what == HPSG_WHAT_MERGED_OBJECTS || what == HPSG_WHAT_DISTINCT_OBJECTS)
4862 << static_cast<int>(what);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004863
4864 // First, send a heap start chunk.
4865 uint8_t heap_id[4];
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004866 JDWP::Set4BE(&heap_id[0], 1); // Heap id (bogus; we only have one heap).
Alex Light772099a2017-11-21 14:05:04 -08004867 cb->DdmPublishChunk(native ? CHUNK_TYPE("NHST") : CHUNK_TYPE("HPST"),
4868 ArrayRef<const uint8_t>(heap_id));
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07004869 Thread* self = Thread::Current();
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07004870 Locks::mutator_lock_->AssertSharedHeld(self);
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07004871
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004872 // Send a series of heap segment chunks.
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004873 HeapChunkContext context(what == HPSG_WHAT_MERGED_OBJECTS, native);
Andreas Gampe0c183382017-07-13 22:26:24 -07004874 auto bump_pointer_space_visitor = [&](mirror::Object* obj)
4875 REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
4876 const size_t size = RoundUp(obj->SizeOf(), kObjectAlignment);
4877 HeapChunkContext::HeapChunkJavaCallback(
4878 obj, reinterpret_cast<void*>(reinterpret_cast<uintptr_t>(obj) + size), size, &context);
4879 };
Elliott Hughesa2155262011-11-16 16:26:58 -08004880 if (native) {
Dimitry Ivanove6465bc2015-12-14 18:55:02 -08004881 UNIMPLEMENTED(WARNING) << "Native heap inspection is not supported";
Elliott Hughesa2155262011-11-16 16:26:58 -08004882 } else {
Ian Rogers1d54e732013-05-02 21:10:01 -07004883 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartier36dab362014-07-30 14:59:56 -07004884 for (const auto& space : heap->GetContinuousSpaces()) {
4885 if (space->IsDlMallocSpace()) {
Mathieu Chartier4c69d7f2014-10-10 12:45:50 -07004886 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004887 // dlmalloc's chunk header is 2 * sizeof(size_t), but if the previous chunk is in use for an
4888 // allocation then the first sizeof(size_t) may belong to it.
4889 context.SetChunkOverhead(sizeof(size_t));
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004890 space->AsDlMallocSpace()->Walk(HeapChunkContext::HeapChunkJavaCallback, &context);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004891 } else if (space->IsRosAllocSpace()) {
4892 context.SetChunkOverhead(0);
Mathieu Chartier4c69d7f2014-10-10 12:45:50 -07004893 // Need to acquire the mutator lock before the heap bitmap lock with exclusive access since
4894 // RosAlloc's internal logic doesn't know to release and reacquire the heap bitmap lock.
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07004895 ScopedThreadSuspension sts(self, kSuspended);
Mathieu Chartier4f55e222015-09-04 13:26:21 -07004896 ScopedSuspendAll ssa(__FUNCTION__);
4897 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
4898 space->AsRosAllocSpace()->Walk(HeapChunkContext::HeapChunkJavaCallback, &context);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004899 } else if (space->IsBumpPointerSpace()) {
Mathieu Chartier4c69d7f2014-10-10 12:45:50 -07004900 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004901 context.SetChunkOverhead(0);
Andreas Gampe0c183382017-07-13 22:26:24 -07004902 space->AsBumpPointerSpace()->Walk(bump_pointer_space_visitor);
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004903 HeapChunkContext::HeapChunkJavaCallback(nullptr, nullptr, 0, &context);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08004904 } else if (space->IsRegionSpace()) {
4905 heap->IncrementDisableMovingGC(self);
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07004906 {
4907 ScopedThreadSuspension sts(self, kSuspended);
Mathieu Chartier4f55e222015-09-04 13:26:21 -07004908 ScopedSuspendAll ssa(__FUNCTION__);
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07004909 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
4910 context.SetChunkOverhead(0);
Andreas Gampe0c183382017-07-13 22:26:24 -07004911 space->AsRegionSpace()->Walk(bump_pointer_space_visitor);
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07004912 HeapChunkContext::HeapChunkJavaCallback(nullptr, nullptr, 0, &context);
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07004913 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08004914 heap->DecrementDisableMovingGC(self);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004915 } else {
4916 UNIMPLEMENTED(WARNING) << "Not counting objects in space " << *space;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07004917 }
Mathieu Chartier36dab362014-07-30 14:59:56 -07004918 context.ResetStartOfNextChunk();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07004919 }
Mathieu Chartier4c69d7f2014-10-10 12:45:50 -07004920 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07004921 // Walk the large objects, these are not in the AllocSpace.
Mathieu Chartier36dab362014-07-30 14:59:56 -07004922 context.SetChunkOverhead(0);
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004923 heap->GetLargeObjectsSpace()->Walk(HeapChunkContext::HeapChunkJavaCallback, &context);
Elliott Hughesa2155262011-11-16 16:26:58 -08004924 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004925
4926 // Finally, send a heap end chunk.
Alex Light772099a2017-11-21 14:05:04 -08004927 cb->DdmPublishChunk(native ? CHUNK_TYPE("NHEN") : CHUNK_TYPE("HPEN"),
4928 ArrayRef<const uint8_t>(heap_id));
Elliott Hughes767a1472011-10-26 18:49:02 -07004929}
4930
Brian Carlstrom306db812014-09-05 13:01:41 -07004931void Dbg::SetAllocTrackingEnabled(bool enable) {
Man Cao8c2ff642015-05-27 17:25:30 -07004932 gc::AllocRecordObjectMap::SetAllocTrackingEnabled(enable);
Elliott Hughes545a0642011-11-08 19:10:03 -08004933}
4934
4935void Dbg::DumpRecentAllocations() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004936 ScopedObjectAccess soa(Thread::Current());
Brian Carlstrom306db812014-09-05 13:01:41 -07004937 MutexLock mu(soa.Self(), *Locks::alloc_tracker_lock_);
Man Cao8c2ff642015-05-27 17:25:30 -07004938 if (!Runtime::Current()->GetHeap()->IsAllocTrackingEnabled()) {
Elliott Hughes545a0642011-11-08 19:10:03 -08004939 LOG(INFO) << "Not recording tracked allocations";
4940 return;
4941 }
Man Cao8c2ff642015-05-27 17:25:30 -07004942 gc::AllocRecordObjectMap* records = Runtime::Current()->GetHeap()->GetAllocationRecords();
4943 CHECK(records != nullptr);
Elliott Hughes545a0642011-11-08 19:10:03 -08004944
Man Cao1ed11b92015-06-11 22:47:35 -07004945 const uint16_t capped_count = CappedAllocRecordCount(records->GetRecentAllocationSize());
Brian Carlstrom306db812014-09-05 13:01:41 -07004946 uint16_t count = capped_count;
Elliott Hughes545a0642011-11-08 19:10:03 -08004947
Man Cao8c2ff642015-05-27 17:25:30 -07004948 LOG(INFO) << "Tracked allocations, (count=" << count << ")";
4949 for (auto it = records->RBegin(), end = records->REnd();
4950 count > 0 && it != end; count--, it++) {
Mathieu Chartier458b1052016-03-29 14:02:55 -07004951 const gc::AllocRecord* record = &it->second;
Elliott Hughes545a0642011-11-08 19:10:03 -08004952
Man Cao8c2ff642015-05-27 17:25:30 -07004953 LOG(INFO) << StringPrintf(" Thread %-2d %6zd bytes ", record->GetTid(), record->ByteCount())
David Sehr709b0702016-10-13 09:12:37 -07004954 << mirror::Class::PrettyClass(record->GetClass());
Elliott Hughes545a0642011-11-08 19:10:03 -08004955
Man Cao8c2ff642015-05-27 17:25:30 -07004956 for (size_t stack_frame = 0, depth = record->GetDepth(); stack_frame < depth; ++stack_frame) {
4957 const gc::AllocRecordStackTraceElement& stack_element = record->StackElement(stack_frame);
4958 ArtMethod* m = stack_element.GetMethod();
David Sehr709b0702016-10-13 09:12:37 -07004959 LOG(INFO) << " " << ArtMethod::PrettyMethod(m) << " line "
4960 << stack_element.ComputeLineNumber();
Elliott Hughes545a0642011-11-08 19:10:03 -08004961 }
4962
4963 // pause periodically to help logcat catch up
4964 if ((count % 5) == 0) {
4965 usleep(40000);
4966 }
Elliott Hughes545a0642011-11-08 19:10:03 -08004967 }
4968}
4969
4970class StringTable {
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07004971 private:
4972 struct Entry {
Andreas Gampe84eadb22017-07-07 15:08:01 -07004973 explicit Entry(const char* data_in)
4974 : data(data_in), hash(ComputeModifiedUtf8Hash(data_in)), index(0) {
4975 }
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07004976 Entry(const Entry& entry) = default;
4977 Entry(Entry&& entry) = default;
4978
4979 // Pointer to the actual string data.
4980 const char* data;
Andreas Gampe84eadb22017-07-07 15:08:01 -07004981
4982 // The hash of the data.
4983 const uint32_t hash;
4984
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07004985 // The index. This will be filled in on Finish and is not part of the ordering, so mark it
4986 // mutable.
4987 mutable uint32_t index;
4988
Andreas Gampe84eadb22017-07-07 15:08:01 -07004989 bool operator==(const Entry& other) const {
4990 return strcmp(data, other.data) == 0;
4991 }
4992 };
4993 struct EntryHash {
4994 size_t operator()(const Entry& entry) const {
4995 return entry.hash;
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07004996 }
4997 };
4998
Elliott Hughes545a0642011-11-08 19:10:03 -08004999 public:
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07005000 StringTable() : finished_(false) {
Elliott Hughes545a0642011-11-08 19:10:03 -08005001 }
5002
Andreas Gampef774a4e2017-07-06 22:15:18 -07005003 void Add(const char* str, bool copy_string) {
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07005004 DCHECK(!finished_);
Andreas Gampef774a4e2017-07-06 22:15:18 -07005005 if (UNLIKELY(copy_string)) {
5006 // Check whether it's already there.
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07005007 Entry entry(str);
5008 if (table_.find(entry) != table_.end()) {
Andreas Gampef774a4e2017-07-06 22:15:18 -07005009 return;
5010 }
Mathieu Chartier4345c462014-06-27 10:20:14 -07005011
Andreas Gampef774a4e2017-07-06 22:15:18 -07005012 // Make a copy.
5013 size_t str_len = strlen(str);
5014 char* copy = new char[str_len + 1];
5015 strlcpy(copy, str, str_len + 1);
5016 string_backup_.emplace_back(copy);
5017 str = copy;
5018 }
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07005019 Entry entry(str);
5020 table_.insert(entry);
5021 }
5022
5023 // Update all entries and give them an index. Note that this is likely not the insertion order,
5024 // as the set will with high likelihood reorder elements. Thus, Add must not be called after
5025 // Finish, and Finish must be called before IndexOf. In that case, WriteTo will walk in
5026 // the same order as Finish, and indices will agree. The order invariant, as well as indices,
5027 // are enforced through debug checks.
5028 void Finish() {
5029 DCHECK(!finished_);
5030 finished_ = true;
5031 uint32_t index = 0;
5032 for (auto& entry : table_) {
5033 entry.index = index;
5034 ++index;
5035 }
Elliott Hughes545a0642011-11-08 19:10:03 -08005036 }
5037
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07005038 size_t IndexOf(const char* s) const {
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07005039 DCHECK(finished_);
5040 Entry entry(s);
5041 auto it = table_.find(entry);
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07005042 if (it == table_.end()) {
5043 LOG(FATAL) << "IndexOf(\"" << s << "\") failed";
5044 }
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07005045 return it->index;
Elliott Hughes545a0642011-11-08 19:10:03 -08005046 }
5047
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07005048 size_t Size() const {
Elliott Hughes545a0642011-11-08 19:10:03 -08005049 return table_.size();
5050 }
5051
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07005052 void WriteTo(std::vector<uint8_t>& bytes) const {
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07005053 DCHECK(finished_);
5054 uint32_t cur_index = 0;
5055 for (const auto& entry : table_) {
5056 DCHECK_EQ(cur_index++, entry.index);
5057
5058 size_t s_len = CountModifiedUtf8Chars(entry.data);
Christopher Ferris8a354052015-04-24 17:23:53 -07005059 std::unique_ptr<uint16_t[]> s_utf16(new uint16_t[s_len]);
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07005060 ConvertModifiedUtf8ToUtf16(s_utf16.get(), entry.data);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005061 JDWP::AppendUtf16BE(bytes, s_utf16.get(), s_len);
Elliott Hughes545a0642011-11-08 19:10:03 -08005062 }
5063 }
5064
5065 private:
Andreas Gampe84eadb22017-07-07 15:08:01 -07005066 std::unordered_set<Entry, EntryHash> table_;
Andreas Gampef774a4e2017-07-06 22:15:18 -07005067 std::vector<std::unique_ptr<char[]>> string_backup_;
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07005068
5069 bool finished_;
5070
Elliott Hughes545a0642011-11-08 19:10:03 -08005071 DISALLOW_COPY_AND_ASSIGN(StringTable);
5072};
5073
Mathieu Chartiere401d142015-04-22 13:56:20 -07005074static const char* GetMethodSourceFile(ArtMethod* method)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005075 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07005076 DCHECK(method != nullptr);
5077 const char* source_file = method->GetDeclaringClassSourceFile();
Sebastien Hertz280286a2014-04-28 09:26:50 +02005078 return (source_file != nullptr) ? source_file : "";
5079}
5080
Elliott Hughes545a0642011-11-08 19:10:03 -08005081/*
5082 * The data we send to DDMS contains everything we have recorded.
5083 *
5084 * Message header (all values big-endian):
5085 * (1b) message header len (to allow future expansion); includes itself
5086 * (1b) entry header len
5087 * (1b) stack frame len
5088 * (2b) number of entries
5089 * (4b) offset to string table from start of message
5090 * (2b) number of class name strings
5091 * (2b) number of method name strings
5092 * (2b) number of source file name strings
5093 * For each entry:
5094 * (4b) total allocation size
Elliott Hughes221229c2013-01-08 18:17:50 -08005095 * (2b) thread id
Elliott Hughes545a0642011-11-08 19:10:03 -08005096 * (2b) allocated object's class name index
5097 * (1b) stack depth
5098 * For each stack frame:
5099 * (2b) method's class name
5100 * (2b) method name
5101 * (2b) method source file
5102 * (2b) line number, clipped to 32767; -2 if native; -1 if no source
5103 * (xb) class name strings
5104 * (xb) method name strings
5105 * (xb) source file strings
5106 *
5107 * As with other DDM traffic, strings are sent as a 4-byte length
5108 * followed by UTF-16 data.
5109 *
5110 * We send up 16-bit unsigned indexes into string tables. In theory there
Brian Carlstrom306db812014-09-05 13:01:41 -07005111 * can be (kMaxAllocRecordStackDepth * alloc_record_max_) unique strings in
Elliott Hughes545a0642011-11-08 19:10:03 -08005112 * each table, but in practice there should be far fewer.
5113 *
5114 * The chief reason for using a string table here is to keep the size of
5115 * the DDMS message to a minimum. This is partly to make the protocol
5116 * efficient, but also because we have to form the whole thing up all at
5117 * once in a memory buffer.
5118 *
5119 * We use separate string tables for class names, method names, and source
5120 * files to keep the indexes small. There will generally be no overlap
5121 * between the contents of these tables.
5122 */
5123jbyteArray Dbg::GetRecentAllocations() {
Ian Rogerscf7f1912014-10-22 22:06:39 -07005124 if ((false)) {
Elliott Hughes545a0642011-11-08 19:10:03 -08005125 DumpRecentAllocations();
5126 }
5127
Ian Rogers50b35e22012-10-04 10:09:15 -07005128 Thread* self = Thread::Current();
Elliott Hughes545a0642011-11-08 19:10:03 -08005129 std::vector<uint8_t> bytes;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005130 {
Brian Carlstrom306db812014-09-05 13:01:41 -07005131 MutexLock mu(self, *Locks::alloc_tracker_lock_);
Man Cao8c2ff642015-05-27 17:25:30 -07005132 gc::AllocRecordObjectMap* records = Runtime::Current()->GetHeap()->GetAllocationRecords();
5133 // In case this method is called when allocation tracker is disabled,
5134 // we should still send some data back.
5135 gc::AllocRecordObjectMap dummy;
5136 if (records == nullptr) {
5137 CHECK(!Runtime::Current()->GetHeap()->IsAllocTrackingEnabled());
5138 records = &dummy;
5139 }
Man Cao41656de2015-07-06 18:53:15 -07005140 // We don't need to wait on the condition variable records->new_record_condition_, because this
5141 // function only reads the class objects, which are already marked so it doesn't change their
5142 // reachability.
Man Cao8c2ff642015-05-27 17:25:30 -07005143
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005144 //
5145 // Part 1: generate string tables.
5146 //
5147 StringTable class_names;
5148 StringTable method_names;
5149 StringTable filenames;
Elliott Hughes545a0642011-11-08 19:10:03 -08005150
Andreas Gampeff29cee2017-07-07 11:11:15 -07005151 VLOG(jdwp) << "Collecting StringTables.";
5152
Man Cao1ed11b92015-06-11 22:47:35 -07005153 const uint16_t capped_count = CappedAllocRecordCount(records->GetRecentAllocationSize());
Brian Carlstrom306db812014-09-05 13:01:41 -07005154 uint16_t count = capped_count;
Andreas Gamped0fc7682017-07-07 14:03:08 -07005155 size_t alloc_byte_count = 0;
Man Cao8c2ff642015-05-27 17:25:30 -07005156 for (auto it = records->RBegin(), end = records->REnd();
5157 count > 0 && it != end; count--, it++) {
Mathieu Chartier458b1052016-03-29 14:02:55 -07005158 const gc::AllocRecord* record = &it->second;
Ian Rogers1ff3c982014-08-12 02:30:58 -07005159 std::string temp;
Andreas Gampef774a4e2017-07-06 22:15:18 -07005160 const char* class_descr = record->GetClassDescriptor(&temp);
5161 class_names.Add(class_descr, !temp.empty());
Andreas Gamped0fc7682017-07-07 14:03:08 -07005162
5163 // Size + tid + class name index + stack depth.
5164 alloc_byte_count += 4u + 2u + 2u + 1u;
5165
Man Cao8c2ff642015-05-27 17:25:30 -07005166 for (size_t i = 0, depth = record->GetDepth(); i < depth; i++) {
5167 ArtMethod* m = record->StackElement(i).GetMethod();
Andreas Gampef774a4e2017-07-06 22:15:18 -07005168 class_names.Add(m->GetDeclaringClassDescriptor(), false);
5169 method_names.Add(m->GetName(), false);
5170 filenames.Add(GetMethodSourceFile(m), false);
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005171 }
Andreas Gamped0fc7682017-07-07 14:03:08 -07005172
5173 // Depth * (class index + method name index + file name index + line number).
5174 alloc_byte_count += record->GetDepth() * (2u + 2u + 2u + 2u);
Elliott Hughes545a0642011-11-08 19:10:03 -08005175 }
5176
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07005177 class_names.Finish();
5178 method_names.Finish();
5179 filenames.Finish();
Andreas Gampeff29cee2017-07-07 11:11:15 -07005180 VLOG(jdwp) << "Done collecting StringTables:" << std::endl
5181 << " ClassNames: " << class_names.Size() << std::endl
5182 << " MethodNames: " << method_names.Size() << std::endl
5183 << " Filenames: " << filenames.Size();
5184
Man Cao8c2ff642015-05-27 17:25:30 -07005185 LOG(INFO) << "recent allocation records: " << capped_count;
5186 LOG(INFO) << "allocation records all objects: " << records->Size();
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005187
5188 //
5189 // Part 2: Generate the output and store it in the buffer.
5190 //
5191
5192 // (1b) message header len (to allow future expansion); includes itself
5193 // (1b) entry header len
5194 // (1b) stack frame len
5195 const int kMessageHeaderLen = 15;
5196 const int kEntryHeaderLen = 9;
5197 const int kStackFrameLen = 8;
5198 JDWP::Append1BE(bytes, kMessageHeaderLen);
5199 JDWP::Append1BE(bytes, kEntryHeaderLen);
5200 JDWP::Append1BE(bytes, kStackFrameLen);
5201
5202 // (2b) number of entries
5203 // (4b) offset to string table from start of message
5204 // (2b) number of class name strings
5205 // (2b) number of method name strings
5206 // (2b) number of source file name strings
Brian Carlstrom306db812014-09-05 13:01:41 -07005207 JDWP::Append2BE(bytes, capped_count);
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005208 size_t string_table_offset = bytes.size();
Brian Carlstrom7934ac22013-07-26 10:54:15 -07005209 JDWP::Append4BE(bytes, 0); // We'll patch this later...
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005210 JDWP::Append2BE(bytes, class_names.Size());
5211 JDWP::Append2BE(bytes, method_names.Size());
5212 JDWP::Append2BE(bytes, filenames.Size());
5213
Andreas Gampeff29cee2017-07-07 11:11:15 -07005214 VLOG(jdwp) << "Dumping allocations with stacks";
5215
Andreas Gamped0fc7682017-07-07 14:03:08 -07005216 // Enlarge the vector for the allocation data.
5217 size_t reserve_size = bytes.size() + alloc_byte_count;
5218 bytes.reserve(reserve_size);
5219
Ian Rogers1ff3c982014-08-12 02:30:58 -07005220 std::string temp;
Man Cao8c2ff642015-05-27 17:25:30 -07005221 count = capped_count;
5222 // The last "count" number of allocation records in "records" are the most recent "count" number
5223 // of allocations. Reverse iterate to get them. The most recent allocation is sent first.
5224 for (auto it = records->RBegin(), end = records->REnd();
5225 count > 0 && it != end; count--, it++) {
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005226 // For each entry:
5227 // (4b) total allocation size
5228 // (2b) thread id
5229 // (2b) allocated object's class name index
5230 // (1b) stack depth
Mathieu Chartier458b1052016-03-29 14:02:55 -07005231 const gc::AllocRecord* record = &it->second;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005232 size_t stack_depth = record->GetDepth();
Mathieu Chartierf8322842014-05-16 10:59:25 -07005233 size_t allocated_object_class_name_index =
Man Cao41656de2015-07-06 18:53:15 -07005234 class_names.IndexOf(record->GetClassDescriptor(&temp));
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07005235 JDWP::Append4BE(bytes, record->ByteCount());
Man Cao8c2ff642015-05-27 17:25:30 -07005236 JDWP::Append2BE(bytes, static_cast<uint16_t>(record->GetTid()));
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005237 JDWP::Append2BE(bytes, allocated_object_class_name_index);
5238 JDWP::Append1BE(bytes, stack_depth);
5239
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005240 for (size_t stack_frame = 0; stack_frame < stack_depth; ++stack_frame) {
5241 // For each stack frame:
5242 // (2b) method's class name
5243 // (2b) method name
5244 // (2b) method source file
5245 // (2b) line number, clipped to 32767; -2 if native; -1 if no source
Man Cao8c2ff642015-05-27 17:25:30 -07005246 ArtMethod* m = record->StackElement(stack_frame).GetMethod();
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07005247 size_t class_name_index = class_names.IndexOf(m->GetDeclaringClassDescriptor());
5248 size_t method_name_index = method_names.IndexOf(m->GetName());
5249 size_t file_name_index = filenames.IndexOf(GetMethodSourceFile(m));
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005250 JDWP::Append2BE(bytes, class_name_index);
5251 JDWP::Append2BE(bytes, method_name_index);
5252 JDWP::Append2BE(bytes, file_name_index);
Man Cao8c2ff642015-05-27 17:25:30 -07005253 JDWP::Append2BE(bytes, record->StackElement(stack_frame).ComputeLineNumber());
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005254 }
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005255 }
5256
Andreas Gamped0fc7682017-07-07 14:03:08 -07005257 CHECK_EQ(bytes.size(), reserve_size);
Andreas Gampeff29cee2017-07-07 11:11:15 -07005258 VLOG(jdwp) << "Dumping tables.";
5259
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005260 // (xb) class name strings
5261 // (xb) method name strings
5262 // (xb) source file strings
5263 JDWP::Set4BE(&bytes[string_table_offset], bytes.size());
5264 class_names.WriteTo(bytes);
5265 method_names.WriteTo(bytes);
5266 filenames.WriteTo(bytes);
Andreas Gampeff29cee2017-07-07 11:11:15 -07005267
5268 VLOG(jdwp) << "GetRecentAllocations: data created. " << bytes.size();
Elliott Hughes545a0642011-11-08 19:10:03 -08005269 }
Ian Rogers50b35e22012-10-04 10:09:15 -07005270 JNIEnv* env = self->GetJniEnv();
Elliott Hughes545a0642011-11-08 19:10:03 -08005271 jbyteArray result = env->NewByteArray(bytes.size());
Ian Rogersc0542af2014-09-03 16:16:56 -07005272 if (result != nullptr) {
Elliott Hughes545a0642011-11-08 19:10:03 -08005273 env->SetByteArrayRegion(result, 0, bytes.size(), reinterpret_cast<const jbyte*>(&bytes[0]));
5274 }
5275 return result;
5276}
5277
Mathieu Chartiere401d142015-04-22 13:56:20 -07005278ArtMethod* DeoptimizationRequest::Method() const {
Andreas Gampe13b27842016-11-07 16:48:23 -08005279 return jni::DecodeArtMethod(method_);
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07005280}
5281
Mathieu Chartiere401d142015-04-22 13:56:20 -07005282void DeoptimizationRequest::SetMethod(ArtMethod* m) {
Andreas Gampe13b27842016-11-07 16:48:23 -08005283 method_ = jni::EncodeArtMethod(m);
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07005284}
5285
Mathieu Chartiera6b1ead2015-10-06 10:32:38 -07005286void Dbg::VisitRoots(RootVisitor* visitor) {
5287 // Visit breakpoint roots, used to prevent unloading of methods with breakpoints.
5288 ReaderMutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
5289 BufferedRootVisitor<128> root_visitor(visitor, RootInfo(kRootVMInternal));
5290 for (Breakpoint& breakpoint : gBreakpoints) {
Andreas Gampe542451c2016-07-26 09:02:02 -07005291 breakpoint.Method()->VisitRoots(root_visitor, kRuntimePointerSize);
Mathieu Chartiera6b1ead2015-10-06 10:32:38 -07005292 }
5293}
5294
Andreas Gampe04bbb5b2017-01-19 17:49:03 +00005295void Dbg::DbgThreadLifecycleCallback::ThreadStart(Thread* self) {
5296 Dbg::PostThreadStart(self);
5297}
5298
5299void Dbg::DbgThreadLifecycleCallback::ThreadDeath(Thread* self) {
5300 Dbg::PostThreadDeath(self);
5301}
5302
Andreas Gampe0f01b582017-01-18 15:22:37 -08005303void Dbg::DbgClassLoadCallback::ClassLoad(Handle<mirror::Class> klass ATTRIBUTE_UNUSED) {
5304 // Ignore ClassLoad;
5305}
5306void Dbg::DbgClassLoadCallback::ClassPrepare(Handle<mirror::Class> temp_klass ATTRIBUTE_UNUSED,
5307 Handle<mirror::Class> klass) {
5308 Dbg::PostClassPrepare(klass.Get());
5309}
5310
Elliott Hughes872d4ec2011-10-21 17:07:15 -07005311} // namespace art