blob: b108920482a2ba23a780d8f274bb88b31d99599f [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"
Mathieu Chartier0795f232016-09-27 18:43:30 -070068#include "scoped_thread_state_change-inl.h"
Andreas Gampe513061a2017-06-01 09:17:34 -070069#include "stack.h"
Elliott Hughes475fc232011-10-25 15:00:35 -070070#include "thread_list.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070071#include "well_known_classes.h"
Elliott Hughes475fc232011-10-25 15:00:35 -070072
Elliott Hughes872d4ec2011-10-21 17:07:15 -070073namespace art {
74
Andreas Gampe46ee31b2016-12-14 10:11:49 -080075using android::base::StringPrintf;
76
Sebastien Hertz0462c4c2015-04-01 16:34:17 +020077// The key identifying the debugger to update instrumentation.
78static constexpr const char* kDbgInstrumentationKey = "Debugger";
79
Man Cao8c2ff642015-05-27 17:25:30 -070080// 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 -070081static uint16_t CappedAllocRecordCount(size_t alloc_record_count) {
Man Cao1ed11b92015-06-11 22:47:35 -070082 const size_t cap = 0xffff;
Man Cao8c2ff642015-05-27 17:25:30 -070083 if (alloc_record_count > cap) {
84 return cap;
Brian Carlstrom306db812014-09-05 13:01:41 -070085 }
86 return alloc_record_count;
87}
Elliott Hughes475fc232011-10-25 15:00:35 -070088
Mathieu Chartier41af5e52015-10-28 11:10:46 -070089class Breakpoint : public ValueObject {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -070090 public:
Mathieu Chartier41af5e52015-10-28 11:10:46 -070091 Breakpoint(ArtMethod* method, uint32_t dex_pc, DeoptimizationRequest::Kind deoptimization_kind)
Alex Light97e78032017-06-27 17:51:55 -070092 : method_(method->GetCanonicalMethod(kRuntimePointerSize)),
Mathieu Chartier41af5e52015-10-28 11:10:46 -070093 dex_pc_(dex_pc),
94 deoptimization_kind_(deoptimization_kind) {
Sebastien Hertzf3928792014-11-17 19:00:37 +010095 CHECK(deoptimization_kind_ == DeoptimizationRequest::kNothing ||
96 deoptimization_kind_ == DeoptimizationRequest::kSelectiveDeoptimization ||
97 deoptimization_kind_ == DeoptimizationRequest::kFullDeoptimization);
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -070098 }
99
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700100 Breakpoint(const Breakpoint& other) REQUIRES_SHARED(Locks::mutator_lock_)
Mathieu Chartier41af5e52015-10-28 11:10:46 -0700101 : method_(other.method_),
102 dex_pc_(other.dex_pc_),
103 deoptimization_kind_(other.deoptimization_kind_) {}
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700104
Mathieu Chartier41af5e52015-10-28 11:10:46 -0700105 // Method() is called from root visiting, do not use ScopedObjectAccess here or it can cause
106 // GC to deadlock if another thread tries to call SuspendAll while the GC is in a runnable state.
107 ArtMethod* Method() const {
108 return method_;
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700109 }
110
111 uint32_t DexPc() const {
112 return dex_pc_;
113 }
114
Sebastien Hertzf3928792014-11-17 19:00:37 +0100115 DeoptimizationRequest::Kind GetDeoptimizationKind() const {
116 return deoptimization_kind_;
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700117 }
118
Alex Light6c8467f2015-11-20 15:03:26 -0800119 // Returns true if the method of this breakpoint and the passed in method should be considered the
120 // same. That is, they are either the same method or they are copied from the same method.
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700121 bool IsInMethod(ArtMethod* m) const REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light97e78032017-06-27 17:51:55 -0700122 return method_ == m->GetCanonicalMethod(kRuntimePointerSize);
Alex Light6c8467f2015-11-20 15:03:26 -0800123 }
124
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700125 private:
Sebastien Hertza76a6d42014-03-20 16:40:17 +0100126 // The location of this breakpoint.
Mathieu Chartier41af5e52015-10-28 11:10:46 -0700127 ArtMethod* method_;
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700128 uint32_t dex_pc_;
Sebastien Hertza76a6d42014-03-20 16:40:17 +0100129
130 // Indicates whether breakpoint needs full deoptimization or selective deoptimization.
Sebastien Hertzf3928792014-11-17 19:00:37 +0100131 DeoptimizationRequest::Kind deoptimization_kind_;
Elliott Hughes86964332012-02-15 19:37:42 -0800132};
133
Sebastien Hertzed2be172014-08-19 15:33:43 +0200134static std::ostream& operator<<(std::ostream& os, const Breakpoint& rhs)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700135 REQUIRES_SHARED(Locks::mutator_lock_) {
David Sehr709b0702016-10-13 09:12:37 -0700136 os << StringPrintf("Breakpoint[%s @%#x]", ArtMethod::PrettyMethod(rhs.Method()).c_str(),
137 rhs.DexPc());
Elliott Hughes86964332012-02-15 19:37:42 -0800138 return os;
139}
140
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100141class DebugInstrumentationListener final : public instrumentation::InstrumentationListener {
Ian Rogers62d6c772013-02-27 08:32:07 -0800142 public:
143 DebugInstrumentationListener() {}
144 virtual ~DebugInstrumentationListener() {}
145
Alex Lightd7661582017-05-01 13:48:16 -0700146 void MethodEntered(Thread* thread,
147 Handle<mirror::Object> this_object,
148 ArtMethod* method,
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200149 uint32_t dex_pc)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100150 override REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800151 if (method->IsNative()) {
152 // TODO: post location events is a suspension point and native method entry stubs aren't.
153 return;
154 }
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200155 if (IsListeningToDexPcMoved()) {
156 // We also listen to kDexPcMoved instrumentation event so we know the DexPcMoved method is
157 // going to be called right after us. To avoid sending JDWP events twice for this location,
158 // we report the event in DexPcMoved. However, we must remind this is method entry so we
159 // send the METHOD_ENTRY event. And we can also group it with other events for this location
160 // like BREAKPOINT or SINGLE_STEP (or even METHOD_EXIT if this is a RETURN instruction).
161 thread->SetDebugMethodEntry();
162 } else if (IsListeningToMethodExit() && IsReturn(method, dex_pc)) {
163 // We also listen to kMethodExited instrumentation event and the current instruction is a
164 // RETURN so we know the MethodExited method is going to be called right after us. To avoid
165 // sending JDWP events twice for this location, we report the event(s) in MethodExited.
166 // However, we must remind this is method entry so we send the METHOD_ENTRY event. And we can
167 // also group it with other events for this location like BREAKPOINT or SINGLE_STEP.
168 thread->SetDebugMethodEntry();
169 } else {
Alex Lightd7661582017-05-01 13:48:16 -0700170 Dbg::UpdateDebugger(thread, this_object.Get(), method, 0, Dbg::kMethodEntry, nullptr);
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200171 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800172 }
173
Alex Lightd7661582017-05-01 13:48:16 -0700174 void MethodExited(Thread* thread,
175 Handle<mirror::Object> this_object,
176 ArtMethod* method,
177 uint32_t dex_pc,
178 const JValue& return_value)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100179 override REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800180 if (method->IsNative()) {
181 // TODO: post location events is a suspension point and native method entry stubs aren't.
182 return;
183 }
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200184 uint32_t events = Dbg::kMethodExit;
185 if (thread->IsDebugMethodEntry()) {
186 // It is also the method entry.
187 DCHECK(IsReturn(method, dex_pc));
188 events |= Dbg::kMethodEntry;
189 thread->ClearDebugMethodEntry();
190 }
Alex Lightd7661582017-05-01 13:48:16 -0700191 Dbg::UpdateDebugger(thread, this_object.Get(), method, dex_pc, events, &return_value);
Ian Rogers62d6c772013-02-27 08:32:07 -0800192 }
193
Alex Lightd7661582017-05-01 13:48:16 -0700194 void MethodUnwind(Thread* thread ATTRIBUTE_UNUSED,
195 Handle<mirror::Object> this_object ATTRIBUTE_UNUSED,
196 ArtMethod* method,
197 uint32_t dex_pc)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100198 override REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800199 // We're not recorded to listen to this kind of event, so complain.
David Sehr709b0702016-10-13 09:12:37 -0700200 LOG(ERROR) << "Unexpected method unwind event in debugger " << ArtMethod::PrettyMethod(method)
Sebastien Hertz51db44a2013-11-19 10:00:29 +0100201 << " " << dex_pc;
Ian Rogers62d6c772013-02-27 08:32:07 -0800202 }
203
Alex Lightd7661582017-05-01 13:48:16 -0700204 void DexPcMoved(Thread* thread,
205 Handle<mirror::Object> this_object,
206 ArtMethod* method,
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200207 uint32_t new_dex_pc)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100208 override REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200209 if (IsListeningToMethodExit() && IsReturn(method, new_dex_pc)) {
210 // We also listen to kMethodExited instrumentation event and the current instruction is a
211 // RETURN so we know the MethodExited method is going to be called right after us. Like in
212 // MethodEntered, we delegate event reporting to MethodExited.
213 // Besides, if this RETURN instruction is the only one in the method, we can send multiple
214 // JDWP events in the same packet: METHOD_ENTRY, METHOD_EXIT, BREAKPOINT and/or SINGLE_STEP.
215 // Therefore, we must not clear the debug method entry flag here.
216 } else {
217 uint32_t events = 0;
218 if (thread->IsDebugMethodEntry()) {
219 // It is also the method entry.
220 events = Dbg::kMethodEntry;
221 thread->ClearDebugMethodEntry();
222 }
Alex Lightd7661582017-05-01 13:48:16 -0700223 Dbg::UpdateDebugger(thread, this_object.Get(), method, new_dex_pc, events, nullptr);
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200224 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800225 }
226
Alex Lightd7661582017-05-01 13:48:16 -0700227 void FieldRead(Thread* thread ATTRIBUTE_UNUSED,
228 Handle<mirror::Object> this_object,
229 ArtMethod* method,
230 uint32_t dex_pc,
231 ArtField* field)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100232 override REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Lightd7661582017-05-01 13:48:16 -0700233 Dbg::PostFieldAccessEvent(method, dex_pc, this_object.Get(), field);
Ian Rogers62d6c772013-02-27 08:32:07 -0800234 }
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200235
Alex Lightd7661582017-05-01 13:48:16 -0700236 void FieldWritten(Thread* thread ATTRIBUTE_UNUSED,
237 Handle<mirror::Object> this_object,
238 ArtMethod* method,
239 uint32_t dex_pc,
240 ArtField* field,
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700241 const JValue& field_value)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100242 override REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Lightd7661582017-05-01 13:48:16 -0700243 Dbg::PostFieldModificationEvent(method, dex_pc, this_object.Get(), field, &field_value);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200244 }
245
Alex Light6e1607e2017-08-23 10:06:18 -0700246 void ExceptionThrown(Thread* thread ATTRIBUTE_UNUSED,
Alex Lightd7661582017-05-01 13:48:16 -0700247 Handle<mirror::Throwable> exception_object)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100248 override REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Lightd7661582017-05-01 13:48:16 -0700249 Dbg::PostException(exception_object.Get());
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200250 }
251
Nicolas Geoffray81f0f952016-01-20 16:25:19 +0000252 // We only care about branches in the Jit.
253 void Branch(Thread* /*thread*/, ArtMethod* method, uint32_t dex_pc, int32_t dex_pc_offset)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100254 override REQUIRES_SHARED(Locks::mutator_lock_) {
David Sehr709b0702016-10-13 09:12:37 -0700255 LOG(ERROR) << "Unexpected branch event in debugger " << ArtMethod::PrettyMethod(method)
Nicolas Geoffray81f0f952016-01-20 16:25:19 +0000256 << " " << dex_pc << ", " << dex_pc_offset;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800257 }
258
Nicolas Geoffray5550ca82015-08-21 18:38:30 +0100259 // We only care about invokes in the Jit.
260 void InvokeVirtualOrInterface(Thread* thread ATTRIBUTE_UNUSED,
Alex Lightd7661582017-05-01 13:48:16 -0700261 Handle<mirror::Object> this_object ATTRIBUTE_UNUSED,
Nicolas Geoffray5550ca82015-08-21 18:38:30 +0100262 ArtMethod* method,
263 uint32_t dex_pc,
Alex Lightd7661582017-05-01 13:48:16 -0700264 ArtMethod* target ATTRIBUTE_UNUSED)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100265 override REQUIRES_SHARED(Locks::mutator_lock_) {
David Sehr709b0702016-10-13 09:12:37 -0700266 LOG(ERROR) << "Unexpected invoke event in debugger " << ArtMethod::PrettyMethod(method)
Nicolas Geoffray5550ca82015-08-21 18:38:30 +0100267 << " " << dex_pc;
268 }
269
Alex Light798eab02017-08-23 12:54:53 -0700270 // TODO Might be worth it to post ExceptionCatch event.
271 void ExceptionHandled(Thread* thread ATTRIBUTE_UNUSED,
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100272 Handle<mirror::Throwable> throwable ATTRIBUTE_UNUSED) override {
Alex Light798eab02017-08-23 12:54:53 -0700273 LOG(ERROR) << "Unexpected exception handled event in debugger";
274 }
275
Alex Light05f47742017-09-14 00:34:44 +0000276 // TODO Might be worth it to implement this.
277 void WatchedFramePop(Thread* thread ATTRIBUTE_UNUSED,
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100278 const ShadowFrame& frame ATTRIBUTE_UNUSED) override {
Alex Light05f47742017-09-14 00:34:44 +0000279 LOG(ERROR) << "Unexpected WatchedFramePop event in debugger";
280 }
Alex Light798eab02017-08-23 12:54:53 -0700281
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200282 private:
Mathieu Chartier808c7a52017-12-15 11:19:33 -0800283 static bool IsReturn(ArtMethod* method, uint32_t dex_pc) REQUIRES_SHARED(Locks::mutator_lock_) {
284 return method->DexInstructions().InstructionAt(dex_pc).IsReturn();
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200285 }
286
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700287 static bool IsListeningToDexPcMoved() REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200288 return IsListeningTo(instrumentation::Instrumentation::kDexPcMoved);
289 }
290
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700291 static bool IsListeningToMethodExit() REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200292 return IsListeningTo(instrumentation::Instrumentation::kMethodExited);
293 }
294
295 static bool IsListeningTo(instrumentation::Instrumentation::InstrumentationEvent event)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700296 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200297 return (Dbg::GetInstrumentationEvents() & event) != 0;
298 }
299
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200300 DISALLOW_COPY_AND_ASSIGN(DebugInstrumentationListener);
Ian Rogers62d6c772013-02-27 08:32:07 -0800301} gDebugInstrumentationListener;
302
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700303// JDWP is allowed unless the Zygote forbids it.
304static bool gJdwpAllowed = true;
305
Elliott Hughesc0f09332012-03-26 13:27:06 -0700306// Was there a -Xrunjdwp or -agentlib:jdwp= argument on the command line?
Elliott Hughes3bb81562011-10-21 18:52:59 -0700307static bool gJdwpConfigured = false;
308
Sebastien Hertzb3b173b2015-02-06 09:16:32 +0100309// JDWP options for debugging. Only valid if IsJdwpConfigured() is true.
310static JDWP::JdwpOptions gJdwpOptions;
311
Elliott Hughes3bb81562011-10-21 18:52:59 -0700312// Runtime JDWP state.
Ian Rogersc0542af2014-09-03 16:16:56 -0700313static JDWP::JdwpState* gJdwpState = nullptr;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700314static bool gDebuggerConnected; // debugger or DDMS is connected.
Elliott Hughes3bb81562011-10-21 18:52:59 -0700315
Elliott Hughes47fce012011-10-25 18:37:19 -0700316static bool gDdmThreadNotification = false;
317
Elliott Hughes767a1472011-10-26 18:49:02 -0700318// DDMS GC-related settings.
319static Dbg::HpifWhen gDdmHpifWhen = Dbg::HPIF_WHEN_NEVER;
320static Dbg::HpsgWhen gDdmHpsgWhen = Dbg::HPSG_WHEN_NEVER;
321static Dbg::HpsgWhat gDdmHpsgWhat;
322static Dbg::HpsgWhen gDdmNhsgWhen = Dbg::HPSG_WHEN_NEVER;
323static Dbg::HpsgWhat gDdmNhsgWhat;
324
Daniel Mihalyieb076692014-08-22 17:33:31 +0200325bool Dbg::gDebuggerActive = false;
Sebastien Hertz4e5b2082015-03-24 19:03:40 +0100326bool Dbg::gDisposed = false;
Sebastien Hertz6995c602014-09-09 12:10:13 +0200327ObjectRegistry* Dbg::gRegistry = nullptr;
Alex Light21611932017-09-26 13:07:39 -0700328DebuggerActiveMethodInspectionCallback Dbg::gDebugActiveCallback;
Alex Light8c2b9292017-11-09 13:21:01 -0800329DebuggerDdmCallback Dbg::gDebugDdmCallback;
Alex Light40320712017-12-14 11:52:04 -0800330InternalDebuggerControlCallback Dbg::gDebuggerControlCallback;
Elliott Hughes475fc232011-10-25 15:00:35 -0700331
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100332// Deoptimization support.
Sebastien Hertz4d25df32014-03-21 17:44:46 +0100333std::vector<DeoptimizationRequest> Dbg::deoptimization_requests_;
334size_t Dbg::full_deoptimization_event_count_ = 0;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100335
Sebastien Hertz42cd43f2014-05-13 14:15:41 +0200336// Instrumentation event reference counters.
337size_t Dbg::dex_pc_change_event_ref_count_ = 0;
338size_t Dbg::method_enter_event_ref_count_ = 0;
339size_t Dbg::method_exit_event_ref_count_ = 0;
340size_t Dbg::field_read_event_ref_count_ = 0;
341size_t Dbg::field_write_event_ref_count_ = 0;
342size_t Dbg::exception_catch_event_ref_count_ = 0;
343uint32_t Dbg::instrumentation_events_ = 0;
344
Andreas Gampe04bbb5b2017-01-19 17:49:03 +0000345Dbg::DbgThreadLifecycleCallback Dbg::thread_lifecycle_callback_;
Andreas Gampe0f01b582017-01-18 15:22:37 -0800346Dbg::DbgClassLoadCallback Dbg::class_load_callback_;
Andreas Gampe04bbb5b2017-01-19 17:49:03 +0000347
Alex Light8c2b9292017-11-09 13:21:01 -0800348void DebuggerDdmCallback::DdmPublishChunk(uint32_t type, const ArrayRef<const uint8_t>& data) {
Alex Light772099a2017-11-21 14:05:04 -0800349 if (gJdwpState == nullptr) {
350 VLOG(jdwp) << "Debugger thread not active, ignoring DDM send: " << type;
351 } else {
352 iovec vec[1];
353 vec[0].iov_base = reinterpret_cast<void*>(const_cast<uint8_t*>(data.data()));
354 vec[0].iov_len = data.size();
355 gJdwpState->DdmSendChunkV(type, vec, 1);
356 }
Alex Light8c2b9292017-11-09 13:21:01 -0800357}
358
Alex Light21611932017-09-26 13:07:39 -0700359bool DebuggerActiveMethodInspectionCallback::IsMethodBeingInspected(ArtMethod* m ATTRIBUTE_UNUSED) {
360 return Dbg::IsDebuggerActive();
361}
362
Alex Light0fa17862017-10-24 13:43:05 -0700363bool DebuggerActiveMethodInspectionCallback::IsMethodSafeToJit(ArtMethod* m) {
364 return !Dbg::MethodHasAnyBreakpoints(m);
365}
366
Alex Lightf2858632018-04-02 11:28:50 -0700367bool DebuggerActiveMethodInspectionCallback::MethodNeedsDebugVersion(
368 ArtMethod* m ATTRIBUTE_UNUSED) {
369 return Dbg::IsDebuggerActive();
370}
371
Alex Light40320712017-12-14 11:52:04 -0800372void InternalDebuggerControlCallback::StartDebugger() {
373 // Release the mutator lock.
374 ScopedThreadStateChange stsc(art::Thread::Current(), kNative);
375 Dbg::StartJdwp();
376}
377
378void InternalDebuggerControlCallback::StopDebugger() {
379 Dbg::StopJdwp();
380}
381
382bool InternalDebuggerControlCallback::IsDebuggerConfigured() {
383 return Dbg::IsJdwpConfigured();
384}
385
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100386// Breakpoints.
jeffhao09bfc6a2012-12-11 18:11:43 -0800387static std::vector<Breakpoint> gBreakpoints GUARDED_BY(Locks::breakpoint_lock_);
Elliott Hughes86964332012-02-15 19:37:42 -0800388
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700389void DebugInvokeReq::VisitRoots(RootVisitor* visitor, const RootInfo& root_info) {
390 receiver.VisitRootIfNonNull(visitor, root_info); // null for static method call.
391 klass.VisitRoot(visitor, root_info);
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700392}
393
Sebastien Hertz597c4f02015-01-26 17:37:14 +0100394void SingleStepControl::AddDexPc(uint32_t dex_pc) {
395 dex_pcs_.insert(dex_pc);
Sebastien Hertzbb43b432014-04-14 11:59:08 +0200396}
397
Sebastien Hertz597c4f02015-01-26 17:37:14 +0100398bool SingleStepControl::ContainsDexPc(uint32_t dex_pc) const {
399 return dex_pcs_.find(dex_pc) == dex_pcs_.end();
Sebastien Hertzbb43b432014-04-14 11:59:08 +0200400}
401
Alex Light6c8467f2015-11-20 15:03:26 -0800402static bool IsBreakpoint(ArtMethod* m, uint32_t dex_pc)
Mathieu Chartier90443472015-07-16 20:32:27 -0700403 REQUIRES(!Locks::breakpoint_lock_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700404 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertzed2be172014-08-19 15:33:43 +0200405 ReaderMutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100406 for (size_t i = 0, e = gBreakpoints.size(); i < e; ++i) {
Alex Light6c8467f2015-11-20 15:03:26 -0800407 if (gBreakpoints[i].DexPc() == dex_pc && gBreakpoints[i].IsInMethod(m)) {
Elliott Hughes86964332012-02-15 19:37:42 -0800408 VLOG(jdwp) << "Hit breakpoint #" << i << ": " << gBreakpoints[i];
409 return true;
410 }
411 }
412 return false;
413}
414
Sebastien Hertz52d131d2014-03-13 16:17:40 +0100415static bool IsSuspendedForDebugger(ScopedObjectAccessUnchecked& soa, Thread* thread)
Mathieu Chartier90443472015-07-16 20:32:27 -0700416 REQUIRES(!Locks::thread_suspend_count_lock_) {
Elliott Hughes9e0c1752013-01-09 14:02:58 -0800417 MutexLock mu(soa.Self(), *Locks::thread_suspend_count_lock_);
418 // A thread may be suspended for GC; in this code, we really want to know whether
419 // there's a debugger suspension active.
420 return thread->IsSuspended() && thread->GetDebugSuspendCount() > 0;
421}
422
Ian Rogersc0542af2014-09-03 16:16:56 -0700423static mirror::Array* DecodeNonNullArray(JDWP::RefTypeId id, JDWP::JdwpError* error)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700424 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz6995c602014-09-09 12:10:13 +0200425 mirror::Object* o = Dbg::GetObjectRegistry()->Get<mirror::Object*>(id, error);
Ian Rogersc0542af2014-09-03 16:16:56 -0700426 if (o == nullptr) {
427 *error = JDWP::ERR_INVALID_OBJECT;
428 return nullptr;
Elliott Hughes436e3722012-02-17 20:01:47 -0800429 }
430 if (!o->IsArrayInstance()) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700431 *error = JDWP::ERR_INVALID_ARRAY;
432 return nullptr;
Elliott Hughes436e3722012-02-17 20:01:47 -0800433 }
Ian Rogersc0542af2014-09-03 16:16:56 -0700434 *error = JDWP::ERR_NONE;
Elliott Hughes436e3722012-02-17 20:01:47 -0800435 return o->AsArray();
436}
437
Ian Rogersc0542af2014-09-03 16:16:56 -0700438static mirror::Class* DecodeClass(JDWP::RefTypeId id, JDWP::JdwpError* error)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700439 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz6995c602014-09-09 12:10:13 +0200440 mirror::Object* o = Dbg::GetObjectRegistry()->Get<mirror::Object*>(id, error);
Ian Rogersc0542af2014-09-03 16:16:56 -0700441 if (o == nullptr) {
442 *error = JDWP::ERR_INVALID_OBJECT;
443 return nullptr;
Elliott Hughes436e3722012-02-17 20:01:47 -0800444 }
445 if (!o->IsClass()) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700446 *error = JDWP::ERR_INVALID_CLASS;
447 return nullptr;
Elliott Hughes436e3722012-02-17 20:01:47 -0800448 }
Ian Rogersc0542af2014-09-03 16:16:56 -0700449 *error = JDWP::ERR_NONE;
Elliott Hughes436e3722012-02-17 20:01:47 -0800450 return o->AsClass();
451}
452
Ian Rogersc0542af2014-09-03 16:16:56 -0700453static Thread* DecodeThread(ScopedObjectAccessUnchecked& soa, JDWP::ObjectId thread_id,
454 JDWP::JdwpError* error)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700455 REQUIRES_SHARED(Locks::mutator_lock_)
Mathieu Chartier90443472015-07-16 20:32:27 -0700456 REQUIRES(!Locks::thread_list_lock_, !Locks::thread_suspend_count_lock_) {
Sebastien Hertz6995c602014-09-09 12:10:13 +0200457 mirror::Object* thread_peer = Dbg::GetObjectRegistry()->Get<mirror::Object*>(thread_id, error);
Ian Rogersc0542af2014-09-03 16:16:56 -0700458 if (thread_peer == nullptr) {
Elliott Hughes221229c2013-01-08 18:17:50 -0800459 // This isn't even an object.
Ian Rogersc0542af2014-09-03 16:16:56 -0700460 *error = JDWP::ERR_INVALID_OBJECT;
461 return nullptr;
Elliott Hughes436e3722012-02-17 20:01:47 -0800462 }
Elliott Hughes221229c2013-01-08 18:17:50 -0800463
Mathieu Chartier0795f232016-09-27 18:43:30 -0700464 ObjPtr<mirror::Class> java_lang_Thread =
465 soa.Decode<mirror::Class>(WellKnownClasses::java_lang_Thread);
Elliott Hughes221229c2013-01-08 18:17:50 -0800466 if (!java_lang_Thread->IsAssignableFrom(thread_peer->GetClass())) {
467 // This isn't a thread.
Ian Rogersc0542af2014-09-03 16:16:56 -0700468 *error = JDWP::ERR_INVALID_THREAD;
469 return nullptr;
Elliott Hughes221229c2013-01-08 18:17:50 -0800470 }
471
Sebastien Hertz69206392015-04-07 15:54:25 +0200472 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogersc0542af2014-09-03 16:16:56 -0700473 Thread* thread = Thread::FromManagedThread(soa, thread_peer);
474 // If thread is null then this a java.lang.Thread without a Thread*. Must be a un-started or a
475 // zombie.
476 *error = (thread == nullptr) ? JDWP::ERR_THREAD_NOT_ALIVE : JDWP::ERR_NONE;
477 return thread;
Elliott Hughes436e3722012-02-17 20:01:47 -0800478}
479
Elliott Hughes24437992011-11-30 14:49:33 -0800480static JDWP::JdwpTag BasicTagFromDescriptor(const char* descriptor) {
481 // JDWP deliberately uses the descriptor characters' ASCII values for its enum.
482 // Note that by "basic" we mean that we don't get more specific than JT_OBJECT.
483 return static_cast<JDWP::JdwpTag>(descriptor[0]);
484}
485
Ian Rogers1ff3c982014-08-12 02:30:58 -0700486static JDWP::JdwpTag BasicTagFromClass(mirror::Class* klass)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700487 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers1ff3c982014-08-12 02:30:58 -0700488 std::string temp;
489 const char* descriptor = klass->GetDescriptor(&temp);
490 return BasicTagFromDescriptor(descriptor);
491}
492
Ian Rogers98379392014-02-24 16:53:16 -0800493static JDWP::JdwpTag TagFromClass(const ScopedObjectAccessUnchecked& soa, mirror::Class* c)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700494 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700495 CHECK(c != nullptr);
Elliott Hughes24437992011-11-30 14:49:33 -0800496 if (c->IsArrayClass()) {
497 return JDWP::JT_ARRAY;
498 }
Elliott Hughes24437992011-11-30 14:49:33 -0800499 if (c->IsStringClass()) {
500 return JDWP::JT_STRING;
Elliott Hughes24437992011-11-30 14:49:33 -0800501 }
Ian Rogers98379392014-02-24 16:53:16 -0800502 if (c->IsClassClass()) {
503 return JDWP::JT_CLASS_OBJECT;
504 }
505 {
Mathieu Chartier0795f232016-09-27 18:43:30 -0700506 ObjPtr<mirror::Class> thread_class =
507 soa.Decode<mirror::Class>(WellKnownClasses::java_lang_Thread);
Ian Rogers98379392014-02-24 16:53:16 -0800508 if (thread_class->IsAssignableFrom(c)) {
509 return JDWP::JT_THREAD;
510 }
511 }
512 {
Mathieu Chartier0795f232016-09-27 18:43:30 -0700513 ObjPtr<mirror::Class> thread_group_class =
514 soa.Decode<mirror::Class>(WellKnownClasses::java_lang_ThreadGroup);
Ian Rogers98379392014-02-24 16:53:16 -0800515 if (thread_group_class->IsAssignableFrom(c)) {
516 return JDWP::JT_THREAD_GROUP;
517 }
518 }
519 {
Mathieu Chartier0795f232016-09-27 18:43:30 -0700520 ObjPtr<mirror::Class> class_loader_class =
521 soa.Decode<mirror::Class>(WellKnownClasses::java_lang_ClassLoader);
Ian Rogers98379392014-02-24 16:53:16 -0800522 if (class_loader_class->IsAssignableFrom(c)) {
523 return JDWP::JT_CLASS_LOADER;
524 }
525 }
526 return JDWP::JT_OBJECT;
Elliott Hughes24437992011-11-30 14:49:33 -0800527}
528
529/*
530 * Objects declared to hold Object might actually hold a more specific
531 * type. The debugger may take a special interest in these (e.g. it
532 * wants to display the contents of Strings), so we want to return an
533 * appropriate tag.
534 *
535 * Null objects are tagged JT_OBJECT.
536 */
Sebastien Hertz6995c602014-09-09 12:10:13 +0200537JDWP::JdwpTag Dbg::TagFromObject(const ScopedObjectAccessUnchecked& soa, mirror::Object* o) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700538 return (o == nullptr) ? JDWP::JT_OBJECT : TagFromClass(soa, o->GetClass());
Elliott Hughes24437992011-11-30 14:49:33 -0800539}
540
541static bool IsPrimitiveTag(JDWP::JdwpTag tag) {
542 switch (tag) {
543 case JDWP::JT_BOOLEAN:
544 case JDWP::JT_BYTE:
545 case JDWP::JT_CHAR:
546 case JDWP::JT_FLOAT:
547 case JDWP::JT_DOUBLE:
548 case JDWP::JT_INT:
549 case JDWP::JT_LONG:
550 case JDWP::JT_SHORT:
551 case JDWP::JT_VOID:
552 return true;
553 default:
554 return false;
555 }
556}
557
Sebastien Hertzb3b173b2015-02-06 09:16:32 +0100558void Dbg::StartJdwp() {
Elliott Hughesc0f09332012-03-26 13:27:06 -0700559 if (!gJdwpAllowed || !IsJdwpConfigured()) {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700560 // No JDWP for you!
561 return;
562 }
563
Ian Rogers719d1a32014-03-06 12:13:39 -0800564 CHECK(gRegistry == nullptr);
Elliott Hughes475fc232011-10-25 15:00:35 -0700565 gRegistry = new ObjectRegistry;
566
Alex Light8c2b9292017-11-09 13:21:01 -0800567 {
568 // Setup the Ddm listener
569 ScopedObjectAccess soa(Thread::Current());
570 Runtime::Current()->GetRuntimeCallbacks()->AddDdmCallback(&gDebugDdmCallback);
571 }
572
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700573 // Init JDWP if the debugger is enabled. This may connect out to a
574 // debugger, passively listen for a debugger, or block waiting for a
575 // debugger.
Sebastien Hertzb3b173b2015-02-06 09:16:32 +0100576 gJdwpState = JDWP::JdwpState::Create(&gJdwpOptions);
Ian Rogersc0542af2014-09-03 16:16:56 -0700577 if (gJdwpState == nullptr) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -0800578 // We probably failed because some other process has the port already, which means that
579 // if we don't abort the user is likely to think they're talking to us when they're actually
580 // talking to that other process.
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800581 LOG(FATAL) << "Debugger thread failed to initialize";
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700582 }
583
584 // If a debugger has already attached, send the "welcome" message.
585 // This may cause us to suspend all threads.
Elliott Hughes376a7a02011-10-24 18:35:55 -0700586 if (gJdwpState->IsActive()) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700587 ScopedObjectAccess soa(Thread::Current());
Sebastien Hertz7d955652014-10-22 10:57:10 +0200588 gJdwpState->PostVMStart();
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700589 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700590}
591
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700592void Dbg::StopJdwp() {
Sebastien Hertzc6345ef2014-08-18 19:26:39 +0200593 // Post VM_DEATH event before the JDWP connection is closed (either by the JDWP thread or the
594 // destruction of gJdwpState).
595 if (gJdwpState != nullptr && gJdwpState->IsActive()) {
596 gJdwpState->PostVMDeath();
597 }
Sebastien Hertz0376e6b2014-02-06 18:12:59 +0100598 // Prevent the JDWP thread from processing JDWP incoming packets after we close the connection.
Sebastien Hertz4e5b2082015-03-24 19:03:40 +0100599 Dispose();
Elliott Hughes376a7a02011-10-24 18:35:55 -0700600 delete gJdwpState;
Ian Rogers719d1a32014-03-06 12:13:39 -0800601 gJdwpState = nullptr;
Elliott Hughes475fc232011-10-25 15:00:35 -0700602 delete gRegistry;
Ian Rogers719d1a32014-03-06 12:13:39 -0800603 gRegistry = nullptr;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700604}
605
Elliott Hughes767a1472011-10-26 18:49:02 -0700606void Dbg::GcDidFinish() {
607 if (gDdmHpifWhen != HPIF_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700608 ScopedObjectAccess soa(Thread::Current());
Brian Carlstrom4d466a82014-05-08 19:05:29 -0700609 VLOG(jdwp) << "Sending heap info to DDM";
Elliott Hughes7162ad92011-10-27 14:08:42 -0700610 DdmSendHeapInfo(gDdmHpifWhen);
Elliott Hughes767a1472011-10-26 18:49:02 -0700611 }
612 if (gDdmHpsgWhen != HPSG_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700613 ScopedObjectAccess soa(Thread::Current());
Brian Carlstrom4d466a82014-05-08 19:05:29 -0700614 VLOG(jdwp) << "Dumping heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700615 DdmSendHeapSegments(false);
Elliott Hughes767a1472011-10-26 18:49:02 -0700616 }
617 if (gDdmNhsgWhen != HPSG_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700618 ScopedObjectAccess soa(Thread::Current());
Brian Carlstrom4d466a82014-05-08 19:05:29 -0700619 VLOG(jdwp) << "Dumping native heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700620 DdmSendHeapSegments(true);
Elliott Hughes767a1472011-10-26 18:49:02 -0700621 }
622}
623
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700624void Dbg::SetJdwpAllowed(bool allowed) {
625 gJdwpAllowed = allowed;
626}
627
Leonard Mosescueb842212016-10-06 17:26:36 -0700628bool Dbg::IsJdwpAllowed() {
629 return gJdwpAllowed;
630}
631
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700632DebugInvokeReq* Dbg::GetInvokeReq() {
Elliott Hughes475fc232011-10-25 15:00:35 -0700633 return Thread::Current()->GetInvokeReq();
634}
635
636Thread* Dbg::GetDebugThread() {
Ian Rogersc0542af2014-09-03 16:16:56 -0700637 return (gJdwpState != nullptr) ? gJdwpState->GetDebugThread() : nullptr;
Elliott Hughes475fc232011-10-25 15:00:35 -0700638}
639
640void Dbg::ClearWaitForEventThread() {
Sebastien Hertz2bf93f42015-01-09 18:44:05 +0100641 gJdwpState->ReleaseJdwpTokenForEvent();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700642}
643
644void Dbg::Connected() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700645 CHECK(!gDebuggerConnected);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800646 VLOG(jdwp) << "JDWP has attached";
Elliott Hughes3bb81562011-10-21 18:52:59 -0700647 gDebuggerConnected = true;
Elliott Hughes86964332012-02-15 19:37:42 -0800648 gDisposed = false;
649}
650
Sebastien Hertzf3928792014-11-17 19:00:37 +0100651bool Dbg::RequiresDeoptimization() {
652 // We don't need deoptimization if everything runs with interpreter after
653 // enabling -Xint mode.
654 return !Runtime::Current()->GetInstrumentation()->IsForcedInterpretOnly();
655}
656
Elliott Hughesa2155262011-11-16 16:26:58 -0800657void Dbg::GoActive() {
658 // Enable all debugging features, including scans for breakpoints.
659 // This is a no-op if we're already active.
660 // Only called from the JDWP handler thread.
Daniel Mihalyieb076692014-08-22 17:33:31 +0200661 if (IsDebuggerActive()) {
Elliott Hughesa2155262011-11-16 16:26:58 -0800662 return;
663 }
664
Mathieu Chartieraa516822015-10-02 15:53:37 -0700665 Thread* const self = Thread::Current();
Elliott Hughesc0f09332012-03-26 13:27:06 -0700666 {
667 // TODO: dalvik only warned if there were breakpoints left over. clear in Dbg::Disconnected?
Mathieu Chartieraa516822015-10-02 15:53:37 -0700668 ReaderMutexLock mu(self, *Locks::breakpoint_lock_);
Elliott Hughesc0f09332012-03-26 13:27:06 -0700669 CHECK_EQ(gBreakpoints.size(), 0U);
670 }
Elliott Hughesa2155262011-11-16 16:26:58 -0800671
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100672 {
Mathieu Chartieraa516822015-10-02 15:53:37 -0700673 MutexLock mu(self, *Locks::deoptimization_lock_);
Sebastien Hertz4d25df32014-03-21 17:44:46 +0100674 CHECK_EQ(deoptimization_requests_.size(), 0U);
675 CHECK_EQ(full_deoptimization_event_count_, 0U);
Sebastien Hertz42cd43f2014-05-13 14:15:41 +0200676 CHECK_EQ(dex_pc_change_event_ref_count_, 0U);
677 CHECK_EQ(method_enter_event_ref_count_, 0U);
678 CHECK_EQ(method_exit_event_ref_count_, 0U);
679 CHECK_EQ(field_read_event_ref_count_, 0U);
680 CHECK_EQ(field_write_event_ref_count_, 0U);
681 CHECK_EQ(exception_catch_event_ref_count_, 0U);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100682 }
683
Ian Rogers62d6c772013-02-27 08:32:07 -0800684 Runtime* runtime = Runtime::Current();
Nicolas Geoffray433b79a2017-01-30 20:54:45 +0000685 // Best effort deoptimization if the runtime is non-Java debuggable. This happens when
686 // ro.debuggable is set, but the application is not debuggable, or when a standalone
687 // dalvikvm invocation is not passed the debuggable option (-Xcompiler-option --debuggable).
688 //
689 // The performance cost of this is non-negligible during native-debugging due to the
David Srbeckyf4480162016-03-16 00:06:24 +0000690 // forced JIT, so we keep the AOT code in that case in exchange for limited native debugging.
Nicolas Geoffray433b79a2017-01-30 20:54:45 +0000691 if (!runtime->IsJavaDebuggable() &&
692 !runtime->GetInstrumentation()->IsForcedInterpretOnly() &&
693 !runtime->IsNativeDebuggable()) {
694 runtime->DeoptimizeBootImage();
Mingyao Yang6ea1a0e2016-01-29 12:12:49 -0800695 }
696
Mathieu Chartier4f55e222015-09-04 13:26:21 -0700697 ScopedSuspendAll ssa(__FUNCTION__);
Sebastien Hertzf3928792014-11-17 19:00:37 +0100698 if (RequiresDeoptimization()) {
699 runtime->GetInstrumentation()->EnableDeoptimization();
700 }
Sebastien Hertz42cd43f2014-05-13 14:15:41 +0200701 instrumentation_events_ = 0;
Elliott Hughesa2155262011-11-16 16:26:58 -0800702 gDebuggerActive = true;
Alex Light21611932017-09-26 13:07:39 -0700703 Runtime::Current()->GetRuntimeCallbacks()->AddMethodInspectionCallback(&gDebugActiveCallback);
Ian Rogers62d6c772013-02-27 08:32:07 -0800704 LOG(INFO) << "Debugger is active";
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700705}
706
707void Dbg::Disconnected() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700708 CHECK(gDebuggerConnected);
709
Elliott Hughesc0f09332012-03-26 13:27:06 -0700710 LOG(INFO) << "Debugger is no longer active";
Elliott Hughes234ab152011-10-26 14:02:26 -0700711
Hiroshi Yamauchi98810e32016-05-24 14:55:40 -0700712 // Suspend all threads and exclusively acquire the mutator lock. Remove the debugger as a listener
Ian Rogers62d6c772013-02-27 08:32:07 -0800713 // and clear the object registry.
714 Runtime* runtime = Runtime::Current();
Ian Rogers62d6c772013-02-27 08:32:07 -0800715 Thread* self = Thread::Current();
Mathieu Chartier4f55e222015-09-04 13:26:21 -0700716 {
Mathieu Chartieraa516822015-10-02 15:53:37 -0700717 // Required for DisableDeoptimization.
718 gc::ScopedGCCriticalSection gcs(self,
719 gc::kGcCauseInstrumentation,
720 gc::kCollectorTypeInstrumentation);
Mathieu Chartier4f55e222015-09-04 13:26:21 -0700721 ScopedSuspendAll ssa(__FUNCTION__);
Mathieu Chartier4f55e222015-09-04 13:26:21 -0700722 // Debugger may not be active at this point.
723 if (IsDebuggerActive()) {
724 {
725 // Since we're going to disable deoptimization, we clear the deoptimization requests queue.
726 // This prevents us from having any pending deoptimization request when the debugger attaches
727 // to us again while no event has been requested yet.
Mathieu Chartiera6b1ead2015-10-06 10:32:38 -0700728 MutexLock mu(self, *Locks::deoptimization_lock_);
Mathieu Chartier4f55e222015-09-04 13:26:21 -0700729 deoptimization_requests_.clear();
730 full_deoptimization_event_count_ = 0U;
731 }
732 if (instrumentation_events_ != 0) {
733 runtime->GetInstrumentation()->RemoveListener(&gDebugInstrumentationListener,
734 instrumentation_events_);
735 instrumentation_events_ = 0;
736 }
737 if (RequiresDeoptimization()) {
738 runtime->GetInstrumentation()->DisableDeoptimization(kDbgInstrumentationKey);
739 }
740 gDebuggerActive = false;
Alex Light21611932017-09-26 13:07:39 -0700741 Runtime::Current()->GetRuntimeCallbacks()->RemoveMethodInspectionCallback(
742 &gDebugActiveCallback);
Sebastien Hertzaaea7342014-02-25 15:10:04 +0100743 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100744 }
Sebastien Hertz55f65342015-01-13 22:48:34 +0100745
746 {
747 ScopedObjectAccess soa(self);
748 gRegistry->Clear();
749 }
750
751 gDebuggerConnected = false;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700752}
753
Sebastien Hertzb3b173b2015-02-06 09:16:32 +0100754void Dbg::ConfigureJdwp(const JDWP::JdwpOptions& jdwp_options) {
755 CHECK_NE(jdwp_options.transport, JDWP::kJdwpTransportUnknown);
756 gJdwpOptions = jdwp_options;
757 gJdwpConfigured = true;
Alex Light40320712017-12-14 11:52:04 -0800758 Runtime::Current()->GetRuntimeCallbacks()->AddDebuggerControlCallback(&gDebuggerControlCallback);
Sebastien Hertzb3b173b2015-02-06 09:16:32 +0100759}
760
Elliott Hughesc0f09332012-03-26 13:27:06 -0700761bool Dbg::IsJdwpConfigured() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700762 return gJdwpConfigured;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700763}
764
765int64_t Dbg::LastDebuggerActivity() {
Elliott Hughesca951522011-12-05 12:01:32 -0800766 return gJdwpState->LastDebuggerActivity();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700767}
768
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700769void Dbg::UndoDebuggerSuspensions() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700770 Runtime::Current()->GetThreadList()->UndoDebuggerSuspensions();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700771}
772
Elliott Hughes88d63092013-01-09 09:55:54 -0800773std::string Dbg::GetClassName(JDWP::RefTypeId class_id) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700774 JDWP::JdwpError error;
775 mirror::Object* o = gRegistry->Get<mirror::Object*>(class_id, &error);
776 if (o == nullptr) {
777 if (error == JDWP::ERR_NONE) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700778 return "null";
Ian Rogersc0542af2014-09-03 16:16:56 -0700779 } else {
780 return StringPrintf("invalid object %p", reinterpret_cast<void*>(class_id));
781 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800782 }
783 if (!o->IsClass()) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700784 return StringPrintf("non-class %p", o); // This is only used for debugging output anyway.
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800785 }
Sebastien Hertz6995c602014-09-09 12:10:13 +0200786 return GetClassName(o->AsClass());
787}
788
789std::string Dbg::GetClassName(mirror::Class* klass) {
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +0200790 if (klass == nullptr) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700791 return "null";
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +0200792 }
Ian Rogers1ff3c982014-08-12 02:30:58 -0700793 std::string temp;
Sebastien Hertz6995c602014-09-09 12:10:13 +0200794 return DescriptorToName(klass->GetDescriptor(&temp));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700795}
796
Ian Rogersc0542af2014-09-03 16:16:56 -0700797JDWP::JdwpError Dbg::GetClassObject(JDWP::RefTypeId id, JDWP::ObjectId* class_object_id) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800798 JDWP::JdwpError status;
Ian Rogersc0542af2014-09-03 16:16:56 -0700799 mirror::Class* c = DecodeClass(id, &status);
800 if (c == nullptr) {
801 *class_object_id = 0;
Elliott Hughes436e3722012-02-17 20:01:47 -0800802 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800803 }
Ian Rogersc0542af2014-09-03 16:16:56 -0700804 *class_object_id = gRegistry->Add(c);
Elliott Hughes436e3722012-02-17 20:01:47 -0800805 return JDWP::ERR_NONE;
Elliott Hughes86964332012-02-15 19:37:42 -0800806}
807
Ian Rogersc0542af2014-09-03 16:16:56 -0700808JDWP::JdwpError Dbg::GetSuperclass(JDWP::RefTypeId id, JDWP::RefTypeId* superclass_id) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800809 JDWP::JdwpError status;
Ian Rogersc0542af2014-09-03 16:16:56 -0700810 mirror::Class* c = DecodeClass(id, &status);
811 if (c == nullptr) {
812 *superclass_id = 0;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800813 return status;
814 }
815 if (c->IsInterface()) {
816 // http://code.google.com/p/android/issues/detail?id=20856
Ian Rogersc0542af2014-09-03 16:16:56 -0700817 *superclass_id = 0;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800818 } else {
Ian Rogersc0542af2014-09-03 16:16:56 -0700819 *superclass_id = gRegistry->Add(c->GetSuperClass());
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800820 }
821 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700822}
823
Elliott Hughes436e3722012-02-17 20:01:47 -0800824JDWP::JdwpError Dbg::GetClassLoader(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700825 JDWP::JdwpError error;
Andreas Gampe7929a482015-12-30 19:33:49 -0800826 mirror::Class* c = DecodeClass(id, &error);
827 if (c == nullptr) {
828 return error;
Elliott Hughes436e3722012-02-17 20:01:47 -0800829 }
Andreas Gampe7929a482015-12-30 19:33:49 -0800830 expandBufAddObjectId(pReply, gRegistry->Add(c->GetClassLoader()));
Elliott Hughes436e3722012-02-17 20:01:47 -0800831 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700832}
833
Elliott Hughes436e3722012-02-17 20:01:47 -0800834JDWP::JdwpError Dbg::GetModifiers(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700835 JDWP::JdwpError error;
836 mirror::Class* c = DecodeClass(id, &error);
837 if (c == nullptr) {
838 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800839 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800840
841 uint32_t access_flags = c->GetAccessFlags() & kAccJavaFlagsMask;
842
Yevgeny Roubande34eea2014-02-15 01:06:03 +0700843 // Set ACC_SUPER. Dex files don't contain this flag but only classes are supposed to have it set,
844 // not interfaces.
Elliott Hughes436e3722012-02-17 20:01:47 -0800845 // Class.getModifiers doesn't return it, but JDWP does, so we set it here.
Yevgeny Roubande34eea2014-02-15 01:06:03 +0700846 if ((access_flags & kAccInterface) == 0) {
847 access_flags |= kAccSuper;
848 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800849
850 expandBufAdd4BE(pReply, access_flags);
851
852 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700853}
854
Ian Rogersc0542af2014-09-03 16:16:56 -0700855JDWP::JdwpError Dbg::GetMonitorInfo(JDWP::ObjectId object_id, JDWP::ExpandBuf* reply) {
856 JDWP::JdwpError error;
857 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
858 if (o == nullptr) {
Elliott Hughesf327e072013-01-09 16:01:26 -0800859 return JDWP::ERR_INVALID_OBJECT;
860 }
861
862 // Ensure all threads are suspended while we read objects' lock words.
863 Thread* self = Thread::Current();
Sebastien Hertz54263242014-03-19 18:16:50 +0100864 CHECK_EQ(self->GetState(), kRunnable);
Elliott Hughesf327e072013-01-09 16:01:26 -0800865
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700866 MonitorInfo monitor_info;
867 {
868 ScopedThreadSuspension sts(self, kSuspended);
Mathieu Chartier4f55e222015-09-04 13:26:21 -0700869 ScopedSuspendAll ssa(__FUNCTION__);
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700870 monitor_info = MonitorInfo(o);
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700871 }
Ian Rogersc0542af2014-09-03 16:16:56 -0700872 if (monitor_info.owner_ != nullptr) {
Nicolas Geoffraycafa0812017-02-15 18:27:34 +0000873 expandBufAddObjectId(reply, gRegistry->Add(monitor_info.owner_->GetPeerFromOtherThread()));
Elliott Hughesf327e072013-01-09 16:01:26 -0800874 } else {
Ian Rogersc0542af2014-09-03 16:16:56 -0700875 expandBufAddObjectId(reply, gRegistry->Add(nullptr));
Elliott Hughesf327e072013-01-09 16:01:26 -0800876 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700877 expandBufAdd4BE(reply, monitor_info.entry_count_);
878 expandBufAdd4BE(reply, monitor_info.waiters_.size());
879 for (size_t i = 0; i < monitor_info.waiters_.size(); ++i) {
Nicolas Geoffraycafa0812017-02-15 18:27:34 +0000880 expandBufAddObjectId(reply, gRegistry->Add(monitor_info.waiters_[i]->GetPeerFromOtherThread()));
Elliott Hughesf327e072013-01-09 16:01:26 -0800881 }
882 return JDWP::ERR_NONE;
883}
884
Elliott Hughes734b8c62013-01-11 15:32:45 -0800885JDWP::JdwpError Dbg::GetOwnedMonitors(JDWP::ObjectId thread_id,
Ian Rogersc0542af2014-09-03 16:16:56 -0700886 std::vector<JDWP::ObjectId>* monitors,
887 std::vector<uint32_t>* stack_depths) {
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800888 struct OwnedMonitorVisitor : public StackVisitor {
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700889 OwnedMonitorVisitor(Thread* thread, Context* context,
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -0700890 std::vector<JDWP::ObjectId>* monitor_vector,
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700891 std::vector<uint32_t>* stack_depth_vector)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700892 REQUIRES_SHARED(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +0100893 : StackVisitor(thread, context, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
894 current_stack_depth(0),
895 monitors(monitor_vector),
896 stack_depths(stack_depth_vector) {}
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800897
898 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
899 // annotalysis.
Andreas Gampefa6a1b02018-09-07 08:11:55 -0700900 bool VisitFrame() override NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800901 if (!GetMethod()->IsRuntimeMethod()) {
902 Monitor::VisitLocks(this, AppendOwnedMonitors, this);
Elliott Hughes734b8c62013-01-11 15:32:45 -0800903 ++current_stack_depth;
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800904 }
905 return true;
906 }
907
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -0700908 static void AppendOwnedMonitors(mirror::Object* owned_monitor, void* arg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700909 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers7a22fa62013-01-23 12:16:16 -0800910 OwnedMonitorVisitor* visitor = reinterpret_cast<OwnedMonitorVisitor*>(arg);
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -0700911 visitor->monitors->push_back(gRegistry->Add(owned_monitor));
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700912 visitor->stack_depths->push_back(visitor->current_stack_depth);
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800913 }
914
Elliott Hughes734b8c62013-01-11 15:32:45 -0800915 size_t current_stack_depth;
Ian Rogersc0542af2014-09-03 16:16:56 -0700916 std::vector<JDWP::ObjectId>* const monitors;
917 std::vector<uint32_t>* const stack_depths;
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800918 };
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800919
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700920 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz69206392015-04-07 15:54:25 +0200921 JDWP::JdwpError error;
922 Thread* thread = DecodeThread(soa, thread_id, &error);
923 if (thread == nullptr) {
924 return error;
925 }
926 if (!IsSuspendedForDebugger(soa, thread)) {
927 return JDWP::ERR_THREAD_NOT_SUSPENDED;
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700928 }
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -0700929 std::unique_ptr<Context> context(Context::Create());
Ian Rogersc0542af2014-09-03 16:16:56 -0700930 OwnedMonitorVisitor visitor(thread, context.get(), monitors, stack_depths);
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -0700931 visitor.WalkStack();
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800932 return JDWP::ERR_NONE;
933}
934
Sebastien Hertz52d131d2014-03-13 16:17:40 +0100935JDWP::JdwpError Dbg::GetContendedMonitor(JDWP::ObjectId thread_id,
Ian Rogersc0542af2014-09-03 16:16:56 -0700936 JDWP::ObjectId* contended_monitor) {
Elliott Hughesf9501702013-01-11 11:22:27 -0800937 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -0700938 *contended_monitor = 0;
Sebastien Hertz69206392015-04-07 15:54:25 +0200939 JDWP::JdwpError error;
940 Thread* thread = DecodeThread(soa, thread_id, &error);
941 if (thread == nullptr) {
942 return error;
Elliott Hughesf9501702013-01-11 11:22:27 -0800943 }
Sebastien Hertz69206392015-04-07 15:54:25 +0200944 if (!IsSuspendedForDebugger(soa, thread)) {
945 return JDWP::ERR_THREAD_NOT_SUSPENDED;
946 }
947 mirror::Object* contended_monitor_obj = Monitor::GetContendedMonitor(thread);
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700948 // Add() requires the thread_list_lock_ not held to avoid the lock
949 // level violation.
Ian Rogersc0542af2014-09-03 16:16:56 -0700950 *contended_monitor = gRegistry->Add(contended_monitor_obj);
Elliott Hughesf9501702013-01-11 11:22:27 -0800951 return JDWP::ERR_NONE;
952}
953
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800954JDWP::JdwpError Dbg::GetInstanceCounts(const std::vector<JDWP::RefTypeId>& class_ids,
Ian Rogersc0542af2014-09-03 16:16:56 -0700955 std::vector<uint64_t>* counts) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800956 gc::Heap* heap = Runtime::Current()->GetHeap();
Roland Levillainaf290312018-02-27 20:02:17 +0000957 heap->CollectGarbage(/* clear_soft_references */ false, gc::GcCause::kGcCauseDebugger);
Mathieu Chartiere8a3c572016-10-11 16:52:17 -0700958 VariableSizedHandleScope hs(Thread::Current());
Mathieu Chartier9d156d52016-10-06 17:44:26 -0700959 std::vector<Handle<mirror::Class>> classes;
Ian Rogersc0542af2014-09-03 16:16:56 -0700960 counts->clear();
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800961 for (size_t i = 0; i < class_ids.size(); ++i) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700962 JDWP::JdwpError error;
Mathieu Chartier9d156d52016-10-06 17:44:26 -0700963 ObjPtr<mirror::Class> c = DecodeClass(class_ids[i], &error);
Ian Rogersc0542af2014-09-03 16:16:56 -0700964 if (c == nullptr) {
965 return error;
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800966 }
Mathieu Chartier9d156d52016-10-06 17:44:26 -0700967 classes.push_back(hs.NewHandle(c));
Ian Rogersc0542af2014-09-03 16:16:56 -0700968 counts->push_back(0);
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800969 }
Ian Rogersc0542af2014-09-03 16:16:56 -0700970 heap->CountInstances(classes, false, &(*counts)[0]);
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800971 return JDWP::ERR_NONE;
972}
973
Ian Rogersc0542af2014-09-03 16:16:56 -0700974JDWP::JdwpError Dbg::GetInstances(JDWP::RefTypeId class_id, int32_t max_count,
975 std::vector<JDWP::ObjectId>* instances) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800976 gc::Heap* heap = Runtime::Current()->GetHeap();
977 // We only want reachable instances, so do a GC.
Roland Levillainaf290312018-02-27 20:02:17 +0000978 heap->CollectGarbage(/* clear_soft_references */ false, gc::GcCause::kGcCauseDebugger);
Ian Rogersc0542af2014-09-03 16:16:56 -0700979 JDWP::JdwpError error;
Mathieu Chartier9d156d52016-10-06 17:44:26 -0700980 ObjPtr<mirror::Class> c = DecodeClass(class_id, &error);
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800981 if (c == nullptr) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700982 return error;
Elliott Hughes3b78c942013-01-15 17:35:41 -0800983 }
Mathieu Chartier2d855952016-10-12 19:37:59 -0700984 VariableSizedHandleScope hs(Thread::Current());
985 std::vector<Handle<mirror::Object>> raw_instances;
Richard Uhler660be6f2017-11-22 16:12:29 +0000986 Runtime::Current()->GetHeap()->GetInstances(hs,
987 hs.NewHandle(c),
988 /* use_is_assignable_from */ false,
989 max_count,
990 raw_instances);
Elliott Hughes3b78c942013-01-15 17:35:41 -0800991 for (size_t i = 0; i < raw_instances.size(); ++i) {
Mathieu Chartier2d855952016-10-12 19:37:59 -0700992 instances->push_back(gRegistry->Add(raw_instances[i].Get()));
Elliott Hughes3b78c942013-01-15 17:35:41 -0800993 }
994 return JDWP::ERR_NONE;
995}
996
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800997JDWP::JdwpError Dbg::GetReferringObjects(JDWP::ObjectId object_id, int32_t max_count,
Ian Rogersc0542af2014-09-03 16:16:56 -0700998 std::vector<JDWP::ObjectId>* referring_objects) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800999 gc::Heap* heap = Runtime::Current()->GetHeap();
Roland Levillainaf290312018-02-27 20:02:17 +00001000 heap->CollectGarbage(/* clear_soft_references */ false, gc::GcCause::kGcCauseDebugger);
Ian Rogersc0542af2014-09-03 16:16:56 -07001001 JDWP::JdwpError error;
Mathieu Chartier9d156d52016-10-06 17:44:26 -07001002 ObjPtr<mirror::Object> o = gRegistry->Get<mirror::Object*>(object_id, &error);
Ian Rogersc0542af2014-09-03 16:16:56 -07001003 if (o == nullptr) {
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001004 return JDWP::ERR_INVALID_OBJECT;
1005 }
Mathieu Chartieraea9bfb2016-10-12 19:19:56 -07001006 VariableSizedHandleScope hs(Thread::Current());
1007 std::vector<Handle<mirror::Object>> raw_instances;
1008 heap->GetReferringObjects(hs, hs.NewHandle(o), max_count, raw_instances);
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001009 for (size_t i = 0; i < raw_instances.size(); ++i) {
Mathieu Chartieraea9bfb2016-10-12 19:19:56 -07001010 referring_objects->push_back(gRegistry->Add(raw_instances[i].Get()));
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001011 }
1012 return JDWP::ERR_NONE;
1013}
1014
Ian Rogersc0542af2014-09-03 16:16:56 -07001015JDWP::JdwpError Dbg::DisableCollection(JDWP::ObjectId object_id) {
1016 JDWP::JdwpError error;
1017 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
1018 if (o == nullptr) {
Sebastien Hertze96060a2013-12-11 12:06:28 +01001019 return JDWP::ERR_INVALID_OBJECT;
1020 }
Elliott Hughes64f574f2013-02-20 14:57:12 -08001021 gRegistry->DisableCollection(object_id);
1022 return JDWP::ERR_NONE;
1023}
1024
Ian Rogersc0542af2014-09-03 16:16:56 -07001025JDWP::JdwpError Dbg::EnableCollection(JDWP::ObjectId object_id) {
1026 JDWP::JdwpError error;
1027 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
Sebastien Hertze96060a2013-12-11 12:06:28 +01001028 // Unlike DisableCollection, JDWP specs do not state an invalid object causes an error. The RI
1029 // also ignores these cases and never return an error. However it's not obvious why this command
1030 // should behave differently from DisableCollection and IsCollected commands. So let's be more
1031 // strict and return an error if this happens.
Ian Rogersc0542af2014-09-03 16:16:56 -07001032 if (o == nullptr) {
Sebastien Hertze96060a2013-12-11 12:06:28 +01001033 return JDWP::ERR_INVALID_OBJECT;
1034 }
Elliott Hughes64f574f2013-02-20 14:57:12 -08001035 gRegistry->EnableCollection(object_id);
1036 return JDWP::ERR_NONE;
1037}
1038
Ian Rogersc0542af2014-09-03 16:16:56 -07001039JDWP::JdwpError Dbg::IsCollected(JDWP::ObjectId object_id, bool* is_collected) {
1040 *is_collected = true;
Sebastien Hertz65637eb2014-01-10 17:40:02 +01001041 if (object_id == 0) {
1042 // Null object id is invalid.
Sebastien Hertze96060a2013-12-11 12:06:28 +01001043 return JDWP::ERR_INVALID_OBJECT;
1044 }
Sebastien Hertz65637eb2014-01-10 17:40:02 +01001045 // JDWP specs state an INVALID_OBJECT error is returned if the object ID is not valid. However
1046 // the RI seems to ignore this and assume object has been collected.
Ian Rogersc0542af2014-09-03 16:16:56 -07001047 JDWP::JdwpError error;
1048 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
1049 if (o != nullptr) {
1050 *is_collected = gRegistry->IsCollected(object_id);
Sebastien Hertz65637eb2014-01-10 17:40:02 +01001051 }
Elliott Hughes64f574f2013-02-20 14:57:12 -08001052 return JDWP::ERR_NONE;
1053}
1054
Ian Rogersc0542af2014-09-03 16:16:56 -07001055void Dbg::DisposeObject(JDWP::ObjectId object_id, uint32_t reference_count) {
Elliott Hughes64f574f2013-02-20 14:57:12 -08001056 gRegistry->DisposeObject(object_id, reference_count);
1057}
1058
Mathieu Chartier3398c782016-09-30 10:27:43 -07001059JDWP::JdwpTypeTag Dbg::GetTypeTag(ObjPtr<mirror::Class> klass) {
Sebastien Hertz4d8fd492014-03-28 16:29:41 +01001060 DCHECK(klass != nullptr);
1061 if (klass->IsArrayClass()) {
1062 return JDWP::TT_ARRAY;
1063 } else if (klass->IsInterface()) {
1064 return JDWP::TT_INTERFACE;
1065 } else {
1066 return JDWP::TT_CLASS;
1067 }
1068}
1069
Elliott Hughes88d63092013-01-09 09:55:54 -08001070JDWP::JdwpError Dbg::GetReflectedType(JDWP::RefTypeId class_id, JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001071 JDWP::JdwpError error;
1072 mirror::Class* c = DecodeClass(class_id, &error);
1073 if (c == nullptr) {
1074 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001075 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001076
Sebastien Hertz4d8fd492014-03-28 16:29:41 +01001077 JDWP::JdwpTypeTag type_tag = GetTypeTag(c);
1078 expandBufAdd1(pReply, type_tag);
Elliott Hughes88d63092013-01-09 09:55:54 -08001079 expandBufAddRefTypeId(pReply, class_id);
Elliott Hughes436e3722012-02-17 20:01:47 -08001080 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001081}
1082
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001083// Get the complete list of reference classes (i.e. all classes except
1084// the primitive types).
1085// Returns a newly-allocated buffer full of RefTypeId values.
1086class ClassListCreator : public ClassVisitor {
1087 public:
1088 explicit ClassListCreator(std::vector<JDWP::RefTypeId>* classes) : classes_(classes) {}
1089
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01001090 bool operator()(ObjPtr<mirror::Class> c) override REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001091 if (!c->IsPrimitive()) {
1092 classes_->push_back(Dbg::GetObjectRegistry()->AddRefType(c));
1093 }
1094 return true;
1095 }
1096
1097 private:
1098 std::vector<JDWP::RefTypeId>* const classes_;
1099};
1100
Ian Rogersc0542af2014-09-03 16:16:56 -07001101void Dbg::GetClassList(std::vector<JDWP::RefTypeId>* classes) {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001102 ClassListCreator clc(classes);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001103 Runtime::Current()->GetClassLinker()->VisitClassesWithoutClassesLock(&clc);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001104}
1105
Ian Rogers1ff3c982014-08-12 02:30:58 -07001106JDWP::JdwpError Dbg::GetClassInfo(JDWP::RefTypeId class_id, JDWP::JdwpTypeTag* pTypeTag,
1107 uint32_t* pStatus, std::string* pDescriptor) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001108 JDWP::JdwpError error;
1109 mirror::Class* c = DecodeClass(class_id, &error);
1110 if (c == nullptr) {
1111 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001112 }
1113
Elliott Hughesa2155262011-11-16 16:26:58 -08001114 if (c->IsArrayClass()) {
1115 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
1116 *pTypeTag = JDWP::TT_ARRAY;
1117 } else {
1118 if (c->IsErroneous()) {
1119 *pStatus = JDWP::CS_ERROR;
1120 } else {
1121 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED | JDWP::CS_INITIALIZED;
1122 }
1123 *pTypeTag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
1124 }
1125
Ian Rogersc0542af2014-09-03 16:16:56 -07001126 if (pDescriptor != nullptr) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07001127 std::string temp;
1128 *pDescriptor = c->GetDescriptor(&temp);
Elliott Hughesa2155262011-11-16 16:26:58 -08001129 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001130 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001131}
1132
Ian Rogersc0542af2014-09-03 16:16:56 -07001133void Dbg::FindLoadedClassBySignature(const char* descriptor, std::vector<JDWP::RefTypeId>* ids) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001134 std::vector<ObjPtr<mirror::Class>> classes;
Igor Murashkinb1d8c312015-08-04 11:18:43 -07001135 Runtime::Current()->GetClassLinker()->LookupClasses(descriptor, classes);
Ian Rogersc0542af2014-09-03 16:16:56 -07001136 ids->clear();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001137 for (ObjPtr<mirror::Class> c : classes) {
1138 ids->push_back(gRegistry->Add(c));
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001139 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001140}
1141
Ian Rogersc0542af2014-09-03 16:16:56 -07001142JDWP::JdwpError Dbg::GetReferenceType(JDWP::ObjectId object_id, JDWP::ExpandBuf* pReply) {
1143 JDWP::JdwpError error;
1144 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
1145 if (o == nullptr) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001146 return JDWP::ERR_INVALID_OBJECT;
Elliott Hughes499c5132011-11-17 14:55:11 -08001147 }
Elliott Hughes2435a572012-02-17 16:07:41 -08001148
Sebastien Hertz4d8fd492014-03-28 16:29:41 +01001149 JDWP::JdwpTypeTag type_tag = GetTypeTag(o->GetClass());
Elliott Hughes64f574f2013-02-20 14:57:12 -08001150 JDWP::RefTypeId type_id = gRegistry->AddRefType(o->GetClass());
Elliott Hughes2435a572012-02-17 16:07:41 -08001151
1152 expandBufAdd1(pReply, type_tag);
1153 expandBufAddRefTypeId(pReply, type_id);
1154
1155 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001156}
1157
Ian Rogersfc0e94b2013-09-23 23:51:32 -07001158JDWP::JdwpError Dbg::GetSignature(JDWP::RefTypeId class_id, std::string* signature) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001159 JDWP::JdwpError error;
1160 mirror::Class* c = DecodeClass(class_id, &error);
1161 if (c == nullptr) {
1162 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001163 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07001164 std::string temp;
1165 *signature = c->GetDescriptor(&temp);
Elliott Hughes1fe7afb2012-02-13 17:23:03 -08001166 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001167}
1168
Orion Hodson77d8a1c2017-04-24 14:53:19 +01001169JDWP::JdwpError Dbg::GetSourceDebugExtension(JDWP::RefTypeId class_id,
1170 std::string* extension_data) {
1171 JDWP::JdwpError error;
1172 mirror::Class* c = DecodeClass(class_id, &error);
1173 if (c == nullptr) {
1174 return error;
1175 }
1176 StackHandleScope<1> hs(Thread::Current());
1177 Handle<mirror::Class> klass(hs.NewHandle(c));
1178 const char* data = annotations::GetSourceDebugExtension(klass);
1179 if (data == nullptr) {
1180 return JDWP::ERR_ABSENT_INFORMATION;
1181 }
1182 *extension_data = data;
1183 return JDWP::ERR_NONE;
1184}
1185
Ian Rogersc0542af2014-09-03 16:16:56 -07001186JDWP::JdwpError Dbg::GetSourceFile(JDWP::RefTypeId class_id, std::string* result) {
1187 JDWP::JdwpError error;
1188 mirror::Class* c = DecodeClass(class_id, &error);
Sebastien Hertz4206eb52014-06-05 10:15:45 +02001189 if (c == nullptr) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001190 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001191 }
Sebastien Hertz4206eb52014-06-05 10:15:45 +02001192 const char* source_file = c->GetSourceFile();
1193 if (source_file == nullptr) {
Sebastien Hertzb7054ba2014-03-13 11:52:31 +01001194 return JDWP::ERR_ABSENT_INFORMATION;
1195 }
Ian Rogersc0542af2014-09-03 16:16:56 -07001196 *result = source_file;
Elliott Hughes436e3722012-02-17 20:01:47 -08001197 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001198}
1199
Ian Rogersc0542af2014-09-03 16:16:56 -07001200JDWP::JdwpError Dbg::GetObjectTag(JDWP::ObjectId object_id, uint8_t* tag) {
Ian Rogers98379392014-02-24 16:53:16 -08001201 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07001202 JDWP::JdwpError error;
1203 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
1204 if (error != JDWP::ERR_NONE) {
1205 *tag = JDWP::JT_VOID;
1206 return error;
Elliott Hughes546b9862012-06-20 16:06:13 -07001207 }
Ian Rogersc0542af2014-09-03 16:16:56 -07001208 *tag = TagFromObject(soa, o);
Elliott Hughes546b9862012-06-20 16:06:13 -07001209 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001210}
1211
Elliott Hughesaed4be92011-12-02 16:16:23 -08001212size_t Dbg::GetTagWidth(JDWP::JdwpTag tag) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001213 switch (tag) {
1214 case JDWP::JT_VOID:
1215 return 0;
1216 case JDWP::JT_BYTE:
1217 case JDWP::JT_BOOLEAN:
1218 return 1;
1219 case JDWP::JT_CHAR:
1220 case JDWP::JT_SHORT:
1221 return 2;
1222 case JDWP::JT_FLOAT:
1223 case JDWP::JT_INT:
1224 return 4;
1225 case JDWP::JT_ARRAY:
1226 case JDWP::JT_OBJECT:
1227 case JDWP::JT_STRING:
1228 case JDWP::JT_THREAD:
1229 case JDWP::JT_THREAD_GROUP:
1230 case JDWP::JT_CLASS_LOADER:
1231 case JDWP::JT_CLASS_OBJECT:
1232 return sizeof(JDWP::ObjectId);
1233 case JDWP::JT_DOUBLE:
1234 case JDWP::JT_LONG:
1235 return 8;
1236 default:
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001237 LOG(FATAL) << "Unknown tag " << tag;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001238 return -1;
1239 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001240}
1241
Ian Rogersc0542af2014-09-03 16:16:56 -07001242JDWP::JdwpError Dbg::GetArrayLength(JDWP::ObjectId array_id, int32_t* length) {
1243 JDWP::JdwpError error;
1244 mirror::Array* a = DecodeNonNullArray(array_id, &error);
1245 if (a == nullptr) {
1246 return error;
Elliott Hughes24437992011-11-30 14:49:33 -08001247 }
Ian Rogersc0542af2014-09-03 16:16:56 -07001248 *length = a->GetLength();
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001249 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001250}
1251
Elliott Hughes88d63092013-01-09 09:55:54 -08001252JDWP::JdwpError Dbg::OutputArray(JDWP::ObjectId array_id, int offset, int count, JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001253 JDWP::JdwpError error;
1254 mirror::Array* a = DecodeNonNullArray(array_id, &error);
Ian Rogers98379392014-02-24 16:53:16 -08001255 if (a == nullptr) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001256 return error;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001257 }
Elliott Hughes24437992011-11-30 14:49:33 -08001258
1259 if (offset < 0 || count < 0 || offset > a->GetLength() || a->GetLength() - offset < count) {
1260 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001261 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughes24437992011-11-30 14:49:33 -08001262 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07001263 JDWP::JdwpTag element_tag = BasicTagFromClass(a->GetClass()->GetComponentType());
1264 expandBufAdd1(pReply, element_tag);
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001265 expandBufAdd4BE(pReply, count);
1266
Ian Rogers1ff3c982014-08-12 02:30:58 -07001267 if (IsPrimitiveTag(element_tag)) {
1268 size_t width = GetTagWidth(element_tag);
Elliott Hughes24437992011-11-30 14:49:33 -08001269 uint8_t* dst = expandBufAddSpace(pReply, count * width);
1270 if (width == 8) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001271 const uint64_t* src8 = reinterpret_cast<uint64_t*>(a->GetRawData(sizeof(uint64_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001272 for (int i = 0; i < count; ++i) JDWP::Write8BE(&dst, src8[offset + i]);
1273 } else if (width == 4) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001274 const uint32_t* src4 = reinterpret_cast<uint32_t*>(a->GetRawData(sizeof(uint32_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001275 for (int i = 0; i < count; ++i) JDWP::Write4BE(&dst, src4[offset + i]);
1276 } else if (width == 2) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001277 const uint16_t* src2 = reinterpret_cast<uint16_t*>(a->GetRawData(sizeof(uint16_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001278 for (int i = 0; i < count; ++i) JDWP::Write2BE(&dst, src2[offset + i]);
1279 } else {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001280 const uint8_t* src = reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint8_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001281 memcpy(dst, &src[offset * width], count * width);
1282 }
1283 } else {
Ian Rogers98379392014-02-24 16:53:16 -08001284 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001285 mirror::ObjectArray<mirror::Object>* oa = a->AsObjectArray<mirror::Object>();
Elliott Hughes24437992011-11-30 14:49:33 -08001286 for (int i = 0; i < count; ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001287 mirror::Object* element = oa->Get(offset + i);
Ian Rogers98379392014-02-24 16:53:16 -08001288 JDWP::JdwpTag specific_tag = (element != nullptr) ? TagFromObject(soa, element)
Ian Rogers1ff3c982014-08-12 02:30:58 -07001289 : element_tag;
Elliott Hughes24437992011-11-30 14:49:33 -08001290 expandBufAdd1(pReply, specific_tag);
1291 expandBufAddObjectId(pReply, gRegistry->Add(element));
1292 }
1293 }
1294
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001295 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001296}
1297
Ian Rogersef7d42f2014-01-06 12:55:46 -08001298template <typename T>
Ian Rogersc0542af2014-09-03 16:16:56 -07001299static void CopyArrayData(mirror::Array* a, JDWP::Request* src, int offset, int count)
Ian Rogersef7d42f2014-01-06 12:55:46 -08001300 NO_THREAD_SAFETY_ANALYSIS {
1301 // TODO: fix when annotalysis correctly handles non-member functions.
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001302 DCHECK(a->GetClass()->IsPrimitiveArray());
1303
Ian Rogersef7d42f2014-01-06 12:55:46 -08001304 T* dst = reinterpret_cast<T*>(a->GetRawData(sizeof(T), offset));
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001305 for (int i = 0; i < count; ++i) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001306 *dst++ = src->ReadValue(sizeof(T));
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001307 }
1308}
1309
Elliott Hughes88d63092013-01-09 09:55:54 -08001310JDWP::JdwpError Dbg::SetArrayElements(JDWP::ObjectId array_id, int offset, int count,
Ian Rogersc0542af2014-09-03 16:16:56 -07001311 JDWP::Request* request) {
1312 JDWP::JdwpError error;
1313 mirror::Array* dst = DecodeNonNullArray(array_id, &error);
1314 if (dst == nullptr) {
1315 return error;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001316 }
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001317
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001318 if (offset < 0 || count < 0 || offset > dst->GetLength() || dst->GetLength() - offset < count) {
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001319 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001320 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001321 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07001322 JDWP::JdwpTag element_tag = BasicTagFromClass(dst->GetClass()->GetComponentType());
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001323
Ian Rogers1ff3c982014-08-12 02:30:58 -07001324 if (IsPrimitiveTag(element_tag)) {
1325 size_t width = GetTagWidth(element_tag);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001326 if (width == 8) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001327 CopyArrayData<uint64_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001328 } else if (width == 4) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001329 CopyArrayData<uint32_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001330 } else if (width == 2) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001331 CopyArrayData<uint16_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001332 } else {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001333 CopyArrayData<uint8_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001334 }
1335 } else {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001336 mirror::ObjectArray<mirror::Object>* oa = dst->AsObjectArray<mirror::Object>();
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001337 for (int i = 0; i < count; ++i) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001338 JDWP::ObjectId id = request->ReadObjectId();
Ian Rogersc0542af2014-09-03 16:16:56 -07001339 mirror::Object* o = gRegistry->Get<mirror::Object*>(id, &error);
1340 if (error != JDWP::ERR_NONE) {
1341 return error;
Elliott Hughes436e3722012-02-17 20:01:47 -08001342 }
Sebastien Hertz2e1c16d2015-08-28 11:57:49 +02001343 // Check if the object's type is compatible with the array's type.
1344 if (o != nullptr && !o->InstanceOf(oa->GetClass()->GetComponentType())) {
1345 return JDWP::ERR_TYPE_MISMATCH;
1346 }
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001347 oa->Set<false>(offset + i, o);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001348 }
1349 }
1350
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001351 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001352}
1353
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001354JDWP::JdwpError Dbg::CreateString(const std::string& str, JDWP::ObjectId* new_string_id) {
1355 Thread* self = Thread::Current();
1356 mirror::String* new_string = mirror::String::AllocFromModifiedUtf8(self, str.c_str());
1357 if (new_string == nullptr) {
1358 DCHECK(self->IsExceptionPending());
1359 self->ClearException();
1360 LOG(ERROR) << "Could not allocate string";
1361 *new_string_id = 0;
1362 return JDWP::ERR_OUT_OF_MEMORY;
1363 }
1364 *new_string_id = gRegistry->Add(new_string);
1365 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001366}
1367
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001368JDWP::JdwpError Dbg::CreateObject(JDWP::RefTypeId class_id, JDWP::ObjectId* new_object_id) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001369 JDWP::JdwpError error;
1370 mirror::Class* c = DecodeClass(class_id, &error);
1371 if (c == nullptr) {
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001372 *new_object_id = 0;
Ian Rogersc0542af2014-09-03 16:16:56 -07001373 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001374 }
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001375 Thread* self = Thread::Current();
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001376 ObjPtr<mirror::Object> new_object;
Sebastien Hertz56d5e502015-11-03 17:38:35 +01001377 if (c->IsStringClass()) {
1378 // Special case for java.lang.String.
1379 gc::AllocatorType allocator_type = Runtime::Current()->GetHeap()->GetCurrentAllocator();
jessicahandojo3aaa37b2016-07-29 14:46:37 -07001380 new_object = mirror::String::AllocEmptyString<true>(self, allocator_type);
Sebastien Hertz56d5e502015-11-03 17:38:35 +01001381 } else {
1382 new_object = c->AllocObject(self);
1383 }
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001384 if (new_object == nullptr) {
1385 DCHECK(self->IsExceptionPending());
1386 self->ClearException();
David Sehr709b0702016-10-13 09:12:37 -07001387 LOG(ERROR) << "Could not allocate object of type " << mirror::Class::PrettyDescriptor(c);
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001388 *new_object_id = 0;
1389 return JDWP::ERR_OUT_OF_MEMORY;
1390 }
Vladimir Markobcf17522018-06-01 13:14:32 +01001391 *new_object_id = gRegistry->Add(new_object);
Elliott Hughes436e3722012-02-17 20:01:47 -08001392 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001393}
1394
Elliott Hughesbf13d362011-12-08 15:51:37 -08001395/*
1396 * Used by Eclipse's "Display" view to evaluate "new byte[5]" to get "(byte[]) [0, 0, 0, 0, 0]".
1397 */
Elliott Hughes88d63092013-01-09 09:55:54 -08001398JDWP::JdwpError Dbg::CreateArrayObject(JDWP::RefTypeId array_class_id, uint32_t length,
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001399 JDWP::ObjectId* new_array_id) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001400 JDWP::JdwpError error;
1401 mirror::Class* c = DecodeClass(array_class_id, &error);
1402 if (c == nullptr) {
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001403 *new_array_id = 0;
Ian Rogersc0542af2014-09-03 16:16:56 -07001404 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001405 }
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001406 Thread* self = Thread::Current();
Vladimir Markobcf17522018-06-01 13:14:32 +01001407 gc::AllocatorType allocator_type = Runtime::Current()->GetHeap()->GetCurrentAllocator();
1408 ObjPtr<mirror::Array> new_array =
1409 mirror::Array::Alloc<true>(self, c, length, c->GetComponentSizeShift(), allocator_type);
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001410 if (new_array == nullptr) {
1411 DCHECK(self->IsExceptionPending());
1412 self->ClearException();
David Sehr709b0702016-10-13 09:12:37 -07001413 LOG(ERROR) << "Could not allocate array of type " << mirror::Class::PrettyDescriptor(c);
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001414 *new_array_id = 0;
1415 return JDWP::ERR_OUT_OF_MEMORY;
1416 }
1417 *new_array_id = gRegistry->Add(new_array);
Elliott Hughes436e3722012-02-17 20:01:47 -08001418 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001419}
1420
Mathieu Chartierc7853442015-03-27 14:35:38 -07001421JDWP::FieldId Dbg::ToFieldId(const ArtField* f) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001422 return static_cast<JDWP::FieldId>(reinterpret_cast<uintptr_t>(f));
Elliott Hughes03181a82011-11-17 17:22:21 -08001423}
1424
Alex Light6c8467f2015-11-20 15:03:26 -08001425static JDWP::MethodId ToMethodId(ArtMethod* m)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001426 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light97e78032017-06-27 17:51:55 -07001427 return static_cast<JDWP::MethodId>(
1428 reinterpret_cast<uintptr_t>(m->GetCanonicalMethod(kRuntimePointerSize)));
Elliott Hughes03181a82011-11-17 17:22:21 -08001429}
1430
Mathieu Chartierc7853442015-03-27 14:35:38 -07001431static ArtField* FromFieldId(JDWP::FieldId fid)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001432 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001433 return reinterpret_cast<ArtField*>(static_cast<uintptr_t>(fid));
Elliott Hughesaed4be92011-12-02 16:16:23 -08001434}
1435
Mathieu Chartiere401d142015-04-22 13:56:20 -07001436static ArtMethod* FromMethodId(JDWP::MethodId mid)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001437 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001438 return reinterpret_cast<ArtMethod*>(static_cast<uintptr_t>(mid));
Elliott Hughes03181a82011-11-17 17:22:21 -08001439}
1440
Sebastien Hertz6995c602014-09-09 12:10:13 +02001441bool Dbg::MatchThread(JDWP::ObjectId expected_thread_id, Thread* event_thread) {
1442 CHECK(event_thread != nullptr);
1443 JDWP::JdwpError error;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001444 mirror::Object* expected_thread_peer = gRegistry->Get<mirror::Object*>(
1445 expected_thread_id, &error);
Nicolas Geoffraycafa0812017-02-15 18:27:34 +00001446 return expected_thread_peer == event_thread->GetPeerFromOtherThread();
Sebastien Hertz6995c602014-09-09 12:10:13 +02001447}
1448
1449bool Dbg::MatchLocation(const JDWP::JdwpLocation& expected_location,
1450 const JDWP::EventLocation& event_location) {
1451 if (expected_location.dex_pc != event_location.dex_pc) {
1452 return false;
1453 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001454 ArtMethod* m = FromMethodId(expected_location.method_id);
Sebastien Hertz6995c602014-09-09 12:10:13 +02001455 return m == event_location.method;
1456}
1457
Mathieu Chartier3398c782016-09-30 10:27:43 -07001458bool Dbg::MatchType(ObjPtr<mirror::Class> event_class, JDWP::RefTypeId class_id) {
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001459 if (event_class == nullptr) {
1460 return false;
1461 }
Sebastien Hertz6995c602014-09-09 12:10:13 +02001462 JDWP::JdwpError error;
Mathieu Chartier3398c782016-09-30 10:27:43 -07001463 ObjPtr<mirror::Class> expected_class = DecodeClass(class_id, &error);
Sebastien Hertz6995c602014-09-09 12:10:13 +02001464 CHECK(expected_class != nullptr);
1465 return expected_class->IsAssignableFrom(event_class);
1466}
1467
1468bool Dbg::MatchField(JDWP::RefTypeId expected_type_id, JDWP::FieldId expected_field_id,
Mathieu Chartierc7853442015-03-27 14:35:38 -07001469 ArtField* event_field) {
1470 ArtField* expected_field = FromFieldId(expected_field_id);
Sebastien Hertz6995c602014-09-09 12:10:13 +02001471 if (expected_field != event_field) {
1472 return false;
1473 }
1474 return Dbg::MatchType(event_field->GetDeclaringClass(), expected_type_id);
1475}
1476
1477bool Dbg::MatchInstance(JDWP::ObjectId expected_instance_id, mirror::Object* event_instance) {
1478 JDWP::JdwpError error;
1479 mirror::Object* modifier_instance = gRegistry->Get<mirror::Object*>(expected_instance_id, &error);
1480 return modifier_instance == event_instance;
1481}
1482
Mathieu Chartier90443472015-07-16 20:32:27 -07001483void Dbg::SetJdwpLocation(JDWP::JdwpLocation* location, ArtMethod* m, uint32_t dex_pc) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001484 if (m == nullptr) {
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001485 memset(location, 0, sizeof(*location));
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001486 } else {
Vladimir Markod93e3742018-07-18 10:58:13 +01001487 ObjPtr<mirror::Class> c = m->GetDeclaringClass();
Ian Rogersc0542af2014-09-03 16:16:56 -07001488 location->type_tag = GetTypeTag(c);
1489 location->class_id = gRegistry->AddRefType(c);
Alex Light73376312017-04-06 10:10:51 -07001490 // The RI Seems to return 0 for all obsolete methods. For compatibility we shall do the same.
1491 location->method_id = m->IsObsolete() ? 0 : ToMethodId(m);
Ian Rogersc0542af2014-09-03 16:16:56 -07001492 location->dex_pc = (m->IsNative() || m->IsProxyMethod()) ? static_cast<uint64_t>(-1) : dex_pc;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001493 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08001494}
1495
Ian Rogersc0542af2014-09-03 16:16:56 -07001496std::string Dbg::GetMethodName(JDWP::MethodId method_id) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001497 ArtMethod* m = FromMethodId(method_id);
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001498 if (m == nullptr) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001499 return "null";
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001500 }
Andreas Gampe542451c2016-07-26 09:02:02 -07001501 return m->GetInterfaceMethodIfProxy(kRuntimePointerSize)->GetName();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001502}
1503
Alex Light73376312017-04-06 10:10:51 -07001504bool Dbg::IsMethodObsolete(JDWP::MethodId method_id) {
1505 ArtMethod* m = FromMethodId(method_id);
1506 if (m == nullptr) {
1507 // NB Since we return 0 as MID for obsolete methods we want to default to true here.
1508 return true;
1509 }
1510 return m->IsObsolete();
1511}
1512
Ian Rogersc0542af2014-09-03 16:16:56 -07001513std::string Dbg::GetFieldName(JDWP::FieldId field_id) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001514 ArtField* f = FromFieldId(field_id);
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001515 if (f == nullptr) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001516 return "null";
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001517 }
1518 return f->GetName();
Elliott Hughesa96836a2013-01-17 12:27:49 -08001519}
1520
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001521/*
1522 * Augment the access flags for synthetic methods and fields by setting
1523 * the (as described by the spec) "0xf0000000 bit". Also, strip out any
1524 * flags not specified by the Java programming language.
1525 */
1526static uint32_t MangleAccessFlags(uint32_t accessFlags) {
1527 accessFlags &= kAccJavaFlagsMask;
1528 if ((accessFlags & kAccSynthetic) != 0) {
1529 accessFlags |= 0xf0000000;
1530 }
1531 return accessFlags;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001532}
1533
Elliott Hughesdbb40792011-11-18 17:05:22 -08001534/*
Jeff Haob7cefc72013-11-14 14:51:09 -08001535 * Circularly shifts registers so that arguments come first. Debuggers
1536 * expect slots to begin with arguments, but dex code places them at
1537 * the end.
Elliott Hughesdbb40792011-11-18 17:05:22 -08001538 */
Mathieu Chartiere401d142015-04-22 13:56:20 -07001539static uint16_t MangleSlot(uint16_t slot, ArtMethod* m)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001540 REQUIRES_SHARED(Locks::mutator_lock_) {
David Sehr0225f8e2018-01-31 08:52:24 +00001541 CodeItemDataAccessor accessor(m->DexInstructionData());
Mathieu Chartier808c7a52017-12-15 11:19:33 -08001542 if (!accessor.HasCodeItem()) {
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001543 // We should not get here for a method without code (native, proxy or abstract). Log it and
1544 // return the slot as is since all registers are arguments.
David Sehr709b0702016-10-13 09:12:37 -07001545 LOG(WARNING) << "Trying to mangle slot for method without code " << m->PrettyMethod();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001546 return slot;
1547 }
Mathieu Chartier808c7a52017-12-15 11:19:33 -08001548 uint16_t ins_size = accessor.InsSize();
1549 uint16_t locals_size = accessor.RegistersSize() - ins_size;
Jeff Haob7cefc72013-11-14 14:51:09 -08001550 if (slot >= locals_size) {
1551 return slot - locals_size;
1552 } else {
1553 return slot + ins_size;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001554 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001555}
1556
Sebastien Hertzaef0c912016-08-08 10:20:28 +02001557static size_t GetMethodNumArgRegistersIncludingThis(ArtMethod* method)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001558 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertzaef0c912016-08-08 10:20:28 +02001559 uint32_t num_registers = ArtMethod::NumArgRegisters(method->GetShorty());
1560 if (!method->IsStatic()) {
1561 ++num_registers;
1562 }
1563 return num_registers;
1564}
1565
Jeff Haob7cefc72013-11-14 14:51:09 -08001566/*
1567 * Circularly shifts registers so that arguments come last. Reverts
1568 * slots to dex style argument placement.
1569 */
Mathieu Chartiere401d142015-04-22 13:56:20 -07001570static uint16_t DemangleSlot(uint16_t slot, ArtMethod* m, JDWP::JdwpError* error)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001571 REQUIRES_SHARED(Locks::mutator_lock_) {
David Sehr0225f8e2018-01-31 08:52:24 +00001572 CodeItemDataAccessor accessor(m->DexInstructionData());
Mathieu Chartier808c7a52017-12-15 11:19:33 -08001573 if (!accessor.HasCodeItem()) {
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001574 // We should not get here for a method without code (native, proxy or abstract). Log it and
1575 // return the slot as is since all registers are arguments.
David Sehr709b0702016-10-13 09:12:37 -07001576 LOG(WARNING) << "Trying to demangle slot for method without code "
1577 << m->PrettyMethod();
Sebastien Hertzaef0c912016-08-08 10:20:28 +02001578 uint16_t vreg_count = GetMethodNumArgRegistersIncludingThis(m);
Sebastien Hertzabbabc82015-03-26 08:47:47 +01001579 if (slot < vreg_count) {
1580 *error = JDWP::ERR_NONE;
1581 return slot;
1582 }
Jeff Haob7cefc72013-11-14 14:51:09 -08001583 } else {
Mathieu Chartier808c7a52017-12-15 11:19:33 -08001584 if (slot < accessor.RegistersSize()) {
1585 uint16_t ins_size = accessor.InsSize();
1586 uint16_t locals_size = accessor.RegistersSize() - ins_size;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01001587 *error = JDWP::ERR_NONE;
1588 return (slot < ins_size) ? slot + locals_size : slot - ins_size;
1589 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001590 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01001591
1592 // Slot is invalid in the method.
David Sehr709b0702016-10-13 09:12:37 -07001593 LOG(ERROR) << "Invalid local slot " << slot << " for method " << m->PrettyMethod();
Sebastien Hertzabbabc82015-03-26 08:47:47 +01001594 *error = JDWP::ERR_INVALID_SLOT;
1595 return DexFile::kDexNoIndex16;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001596}
1597
Mathieu Chartier90443472015-07-16 20:32:27 -07001598JDWP::JdwpError Dbg::OutputDeclaredFields(JDWP::RefTypeId class_id, bool with_generic,
1599 JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001600 JDWP::JdwpError error;
1601 mirror::Class* c = DecodeClass(class_id, &error);
1602 if (c == nullptr) {
1603 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001604 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001605
1606 size_t instance_field_count = c->NumInstanceFields();
1607 size_t static_field_count = c->NumStaticFields();
1608
1609 expandBufAdd4BE(pReply, instance_field_count + static_field_count);
1610
1611 for (size_t i = 0; i < instance_field_count + static_field_count; ++i) {
Mathieu Chartier90443472015-07-16 20:32:27 -07001612 ArtField* f = (i < instance_field_count) ? c->GetInstanceField(i) :
1613 c->GetStaticField(i - instance_field_count);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001614 expandBufAddFieldId(pReply, ToFieldId(f));
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001615 expandBufAddUtf8String(pReply, f->GetName());
1616 expandBufAddUtf8String(pReply, f->GetTypeDescriptor());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001617 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001618 static const char genericSignature[1] = "";
1619 expandBufAddUtf8String(pReply, genericSignature);
1620 }
1621 expandBufAdd4BE(pReply, MangleAccessFlags(f->GetAccessFlags()));
1622 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001623 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001624}
1625
Elliott Hughes88d63092013-01-09 09:55:54 -08001626JDWP::JdwpError Dbg::OutputDeclaredMethods(JDWP::RefTypeId class_id, bool with_generic,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001627 JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001628 JDWP::JdwpError error;
1629 mirror::Class* c = DecodeClass(class_id, &error);
1630 if (c == nullptr) {
1631 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001632 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001633
Alex Light51a64d52015-12-17 13:55:59 -08001634 expandBufAdd4BE(pReply, c->NumMethods());
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001635
Mathieu Chartiere401d142015-04-22 13:56:20 -07001636 auto* cl = Runtime::Current()->GetClassLinker();
1637 auto ptr_size = cl->GetImagePointerSize();
Alex Light51a64d52015-12-17 13:55:59 -08001638 for (ArtMethod& m : c->GetMethods(ptr_size)) {
1639 expandBufAddMethodId(pReply, ToMethodId(&m));
Andreas Gampe542451c2016-07-26 09:02:02 -07001640 expandBufAddUtf8String(pReply, m.GetInterfaceMethodIfProxy(kRuntimePointerSize)->GetName());
1641 expandBufAddUtf8String(
1642 pReply, m.GetInterfaceMethodIfProxy(kRuntimePointerSize)->GetSignature().ToString());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001643 if (with_generic) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001644 const char* generic_signature = "";
1645 expandBufAddUtf8String(pReply, generic_signature);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001646 }
Alex Light51a64d52015-12-17 13:55:59 -08001647 expandBufAdd4BE(pReply, MangleAccessFlags(m.GetAccessFlags()));
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001648 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001649 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001650}
1651
Elliott Hughes88d63092013-01-09 09:55:54 -08001652JDWP::JdwpError Dbg::OutputDeclaredInterfaces(JDWP::RefTypeId class_id, JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001653 JDWP::JdwpError error;
Mathieu Chartierf8322842014-05-16 10:59:25 -07001654 Thread* self = Thread::Current();
Vladimir Marko19a4d372016-12-08 14:41:46 +00001655 ObjPtr<mirror::Class> c = DecodeClass(class_id, &error);
1656 if (c == nullptr) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001657 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001658 }
Mathieu Chartierf8322842014-05-16 10:59:25 -07001659 size_t interface_count = c->NumDirectInterfaces();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001660 expandBufAdd4BE(pReply, interface_count);
1661 for (size_t i = 0; i < interface_count; ++i) {
Vladimir Marko19a4d372016-12-08 14:41:46 +00001662 ObjPtr<mirror::Class> interface = mirror::Class::GetDirectInterface(self, c, i);
1663 DCHECK(interface != nullptr);
1664 expandBufAddRefTypeId(pReply, gRegistry->AddRefType(interface));
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001665 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001666 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001667}
1668
Ian Rogersc0542af2014-09-03 16:16:56 -07001669void Dbg::OutputLineTable(JDWP::RefTypeId, JDWP::MethodId method_id, JDWP::ExpandBuf* pReply) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001670 ArtMethod* m = FromMethodId(method_id);
David Sehr0225f8e2018-01-31 08:52:24 +00001671 CodeItemDebugInfoAccessor accessor(m->DexInstructionDebugInfo());
Elliott Hughes03181a82011-11-17 17:22:21 -08001672 uint64_t start, end;
Mathieu Chartier31f4c9f2017-12-08 15:46:11 -08001673 if (!accessor.HasCodeItem()) {
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001674 DCHECK(m->IsNative() || m->IsProxyMethod());
Elliott Hughes03181a82011-11-17 17:22:21 -08001675 start = -1;
1676 end = -1;
1677 } else {
1678 start = 0;
jeffhao14f0db92012-12-14 17:50:42 -08001679 // Return the index of the last instruction
Mathieu Chartier31f4c9f2017-12-08 15:46:11 -08001680 end = accessor.InsnsSizeInCodeUnits() - 1;
Elliott Hughes03181a82011-11-17 17:22:21 -08001681 }
1682
1683 expandBufAdd8BE(pReply, start);
1684 expandBufAdd8BE(pReply, end);
1685
1686 // Add numLines later
1687 size_t numLinesOffset = expandBufGetLength(pReply);
1688 expandBufAdd4BE(pReply, 0);
1689
Mathieu Chartier3e2e1232018-09-11 12:35:30 -07001690 int numItems = 0;
1691 accessor.DecodeDebugPositionInfo([&](const DexFile::PositionInfo& entry) {
1692 expandBufAdd8BE(pReply, entry.address_);
1693 expandBufAdd4BE(pReply, entry.line_);
1694 numItems++;
1695 return false;
1696 });
Elliott Hughes03181a82011-11-17 17:22:21 -08001697
Mathieu Chartier3e2e1232018-09-11 12:35:30 -07001698 JDWP::Set4BE(expandBufGetBuffer(pReply) + numLinesOffset, numItems);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001699}
1700
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001701void Dbg::OutputVariableTable(JDWP::RefTypeId, JDWP::MethodId method_id, bool with_generic,
1702 JDWP::ExpandBuf* pReply) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001703 ArtMethod* m = FromMethodId(method_id);
David Sehr0225f8e2018-01-31 08:52:24 +00001704 CodeItemDebugInfoAccessor accessor(m->DexInstructionDebugInfo());
Elliott Hughesdbb40792011-11-18 17:05:22 -08001705
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001706 // arg_count considers doubles and longs to take 2 units.
1707 // variable_count considers everything to take 1 unit.
Sebastien Hertzaef0c912016-08-08 10:20:28 +02001708 expandBufAdd4BE(pReply, GetMethodNumArgRegistersIncludingThis(m));
Elliott Hughesdbb40792011-11-18 17:05:22 -08001709
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001710 // We don't know the total number of variables yet, so leave a blank and update it later.
1711 size_t variable_count_offset = expandBufGetLength(pReply);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001712 expandBufAdd4BE(pReply, 0);
1713
Mathieu Chartiere5afbf32018-09-12 17:51:54 -07001714 size_t variable_count = 0;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001715
Mathieu Chartier31f4c9f2017-12-08 15:46:11 -08001716 if (accessor.HasCodeItem()) {
Mathieu Chartiere5afbf32018-09-12 17:51:54 -07001717 accessor.DecodeDebugLocalInfo(m->IsStatic(),
1718 m->GetDexMethodIndex(),
1719 [&](const DexFile::LocalInfo& entry)
1720 REQUIRES_SHARED(Locks::mutator_lock_) {
1721 uint16_t slot = entry.reg_;
1722 VLOG(jdwp) << StringPrintf(" %2zd: %d(%d) '%s' '%s' '%s' actual slot=%d mangled slot=%d",
1723 variable_count,
1724 entry.start_address_,
1725 entry.end_address_ - entry.start_address_,
1726 entry.name_,
1727 entry.descriptor_, entry.signature_,
1728 slot,
1729 MangleSlot(slot, m));
1730
1731 slot = MangleSlot(slot, m);
1732
1733 expandBufAdd8BE(pReply, entry.start_address_);
1734 expandBufAddUtf8String(pReply, entry.name_);
1735 expandBufAddUtf8String(pReply, entry.descriptor_);
1736 if (with_generic) {
1737 expandBufAddUtf8String(pReply, entry.signature_);
1738 }
1739 expandBufAdd4BE(pReply, entry.end_address_- entry.start_address_);
1740 expandBufAdd4BE(pReply, slot);
1741
1742 ++variable_count;
1743 });
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001744 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001745
Mathieu Chartiere5afbf32018-09-12 17:51:54 -07001746 JDWP::Set4BE(expandBufGetBuffer(pReply) + variable_count_offset, variable_count);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001747}
1748
Jeff Hao579b0242013-11-18 13:16:49 -08001749void Dbg::OutputMethodReturnValue(JDWP::MethodId method_id, const JValue* return_value,
1750 JDWP::ExpandBuf* pReply) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001751 ArtMethod* m = FromMethodId(method_id);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001752 JDWP::JdwpTag tag = BasicTagFromDescriptor(m->GetShorty());
Jeff Hao579b0242013-11-18 13:16:49 -08001753 OutputJValue(tag, return_value, pReply);
1754}
1755
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02001756void Dbg::OutputFieldValue(JDWP::FieldId field_id, const JValue* field_value,
1757 JDWP::ExpandBuf* pReply) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001758 ArtField* f = FromFieldId(field_id);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001759 JDWP::JdwpTag tag = BasicTagFromDescriptor(f->GetTypeDescriptor());
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02001760 OutputJValue(tag, field_value, pReply);
1761}
1762
Elliott Hughes9777ba22013-01-17 09:04:19 -08001763JDWP::JdwpError Dbg::GetBytecodes(JDWP::RefTypeId, JDWP::MethodId method_id,
Ian Rogersc0542af2014-09-03 16:16:56 -07001764 std::vector<uint8_t>* bytecodes) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001765 ArtMethod* m = FromMethodId(method_id);
Ian Rogersc0542af2014-09-03 16:16:56 -07001766 if (m == nullptr) {
Elliott Hughes9777ba22013-01-17 09:04:19 -08001767 return JDWP::ERR_INVALID_METHODID;
1768 }
David Sehr0225f8e2018-01-31 08:52:24 +00001769 CodeItemDataAccessor accessor(m->DexInstructionData());
Mathieu Chartier808c7a52017-12-15 11:19:33 -08001770 size_t byte_count = accessor.InsnsSizeInCodeUnits() * 2;
1771 const uint8_t* begin = reinterpret_cast<const uint8_t*>(accessor.Insns());
Elliott Hughes9777ba22013-01-17 09:04:19 -08001772 const uint8_t* end = begin + byte_count;
1773 for (const uint8_t* p = begin; p != end; ++p) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001774 bytecodes->push_back(*p);
Elliott Hughes9777ba22013-01-17 09:04:19 -08001775 }
1776 return JDWP::ERR_NONE;
1777}
1778
Elliott Hughes88d63092013-01-09 09:55:54 -08001779JDWP::JdwpTag Dbg::GetFieldBasicTag(JDWP::FieldId field_id) {
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001780 return BasicTagFromDescriptor(FromFieldId(field_id)->GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001781}
1782
Elliott Hughes88d63092013-01-09 09:55:54 -08001783JDWP::JdwpTag Dbg::GetStaticFieldBasicTag(JDWP::FieldId field_id) {
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001784 return BasicTagFromDescriptor(FromFieldId(field_id)->GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001785}
1786
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001787static JValue GetArtFieldValue(ArtField* f, mirror::Object* o)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001788 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001789 Primitive::Type fieldType = f->GetTypeAsPrimitiveType();
1790 JValue field_value;
1791 switch (fieldType) {
1792 case Primitive::kPrimBoolean:
1793 field_value.SetZ(f->GetBoolean(o));
1794 return field_value;
1795
1796 case Primitive::kPrimByte:
1797 field_value.SetB(f->GetByte(o));
1798 return field_value;
1799
1800 case Primitive::kPrimChar:
1801 field_value.SetC(f->GetChar(o));
1802 return field_value;
1803
1804 case Primitive::kPrimShort:
1805 field_value.SetS(f->GetShort(o));
1806 return field_value;
1807
1808 case Primitive::kPrimInt:
1809 case Primitive::kPrimFloat:
1810 // Int and Float must be treated as 32-bit values in JDWP.
1811 field_value.SetI(f->GetInt(o));
1812 return field_value;
1813
1814 case Primitive::kPrimLong:
1815 case Primitive::kPrimDouble:
1816 // Long and Double must be treated as 64-bit values in JDWP.
1817 field_value.SetJ(f->GetLong(o));
1818 return field_value;
1819
1820 case Primitive::kPrimNot:
Vladimir Markobcf17522018-06-01 13:14:32 +01001821 field_value.SetL(f->GetObject(o));
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001822 return field_value;
1823
1824 case Primitive::kPrimVoid:
1825 LOG(FATAL) << "Attempt to read from field of type 'void'";
1826 UNREACHABLE();
1827 }
1828 LOG(FATAL) << "Attempt to read from field of unknown type";
1829 UNREACHABLE();
1830}
1831
Elliott Hughes88d63092013-01-09 09:55:54 -08001832static JDWP::JdwpError GetFieldValueImpl(JDWP::RefTypeId ref_type_id, JDWP::ObjectId object_id,
1833 JDWP::FieldId field_id, JDWP::ExpandBuf* pReply,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001834 bool is_static)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001835 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001836 JDWP::JdwpError error;
1837 mirror::Class* c = DecodeClass(ref_type_id, &error);
1838 if (ref_type_id != 0 && c == nullptr) {
1839 return error;
Elliott Hughes0cf74332012-02-23 23:14:00 -08001840 }
1841
Jeff Haode19a252016-09-14 15:56:35 -07001842 Thread* self = Thread::Current();
1843 StackHandleScope<2> hs(self);
1844 MutableHandle<mirror::Object>
1845 o(hs.NewHandle(Dbg::GetObjectRegistry()->Get<mirror::Object*>(object_id, &error)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08001846 if ((!is_static && o == nullptr) || error != JDWP::ERR_NONE) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001847 return JDWP::ERR_INVALID_OBJECT;
1848 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001849 ArtField* f = FromFieldId(field_id);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001850
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001851 mirror::Class* receiver_class = c;
Andreas Gampefa4333d2017-02-14 11:10:34 -08001852 if (receiver_class == nullptr && o != nullptr) {
Elliott Hughes0cf74332012-02-23 23:14:00 -08001853 receiver_class = o->GetClass();
1854 }
Jeff Haode19a252016-09-14 15:56:35 -07001855
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001856 // TODO: should we give up now if receiver_class is null?
Ian Rogersc0542af2014-09-03 16:16:56 -07001857 if (receiver_class != nullptr && !f->GetDeclaringClass()->IsAssignableFrom(receiver_class)) {
David Sehr709b0702016-10-13 09:12:37 -07001858 LOG(INFO) << "ERR_INVALID_FIELDID: " << f->PrettyField() << " "
1859 << receiver_class->PrettyClass();
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001860 return JDWP::ERR_INVALID_FIELDID;
1861 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001862
Jeff Haode19a252016-09-14 15:56:35 -07001863 // Ensure the field's class is initialized.
1864 Handle<mirror::Class> klass(hs.NewHandle(f->GetDeclaringClass()));
1865 if (!Runtime::Current()->GetClassLinker()->EnsureInitialized(self, klass, true, false)) {
David Sehr709b0702016-10-13 09:12:37 -07001866 LOG(WARNING) << "Not able to initialize class for SetValues: "
1867 << mirror::Class::PrettyClass(klass.Get());
Jeff Haode19a252016-09-14 15:56:35 -07001868 }
1869
Elliott Hughes0cf74332012-02-23 23:14:00 -08001870 // The RI only enforces the static/non-static mismatch in one direction.
1871 // TODO: should we change the tests and check both?
1872 if (is_static) {
1873 if (!f->IsStatic()) {
1874 return JDWP::ERR_INVALID_FIELDID;
1875 }
1876 } else {
1877 if (f->IsStatic()) {
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001878 LOG(WARNING) << "Ignoring non-nullptr receiver for ObjectReference.GetValues"
David Sehr709b0702016-10-13 09:12:37 -07001879 << " on static field " << f->PrettyField();
Elliott Hughes0cf74332012-02-23 23:14:00 -08001880 }
1881 }
jeffhao0dfbb7e2012-11-28 15:26:03 -08001882 if (f->IsStatic()) {
Jeff Haode19a252016-09-14 15:56:35 -07001883 o.Assign(f->GetDeclaringClass());
jeffhao0dfbb7e2012-11-28 15:26:03 -08001884 }
Elliott Hughes0cf74332012-02-23 23:14:00 -08001885
Jeff Haode19a252016-09-14 15:56:35 -07001886 JValue field_value(GetArtFieldValue(f, o.Get()));
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001887 JDWP::JdwpTag tag = BasicTagFromDescriptor(f->GetTypeDescriptor());
Jeff Hao579b0242013-11-18 13:16:49 -08001888 Dbg::OutputJValue(tag, &field_value, pReply);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001889 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001890}
1891
Elliott Hughes88d63092013-01-09 09:55:54 -08001892JDWP::JdwpError Dbg::GetFieldValue(JDWP::ObjectId object_id, JDWP::FieldId field_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001893 JDWP::ExpandBuf* pReply) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001894 return GetFieldValueImpl(0, object_id, field_id, pReply, false);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001895}
1896
Ian Rogersc0542af2014-09-03 16:16:56 -07001897JDWP::JdwpError Dbg::GetStaticFieldValue(JDWP::RefTypeId ref_type_id, JDWP::FieldId field_id,
1898 JDWP::ExpandBuf* pReply) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001899 return GetFieldValueImpl(ref_type_id, 0, field_id, pReply, true);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001900}
1901
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001902static JDWP::JdwpError SetArtFieldValue(ArtField* f, mirror::Object* o, uint64_t value, int width)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001903 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001904 Primitive::Type fieldType = f->GetTypeAsPrimitiveType();
1905 // Debugging only happens at runtime so we know we are not running in a transaction.
1906 static constexpr bool kNoTransactionMode = false;
1907 switch (fieldType) {
1908 case Primitive::kPrimBoolean:
1909 CHECK_EQ(width, 1);
1910 f->SetBoolean<kNoTransactionMode>(o, static_cast<uint8_t>(value));
1911 return JDWP::ERR_NONE;
1912
1913 case Primitive::kPrimByte:
1914 CHECK_EQ(width, 1);
1915 f->SetByte<kNoTransactionMode>(o, static_cast<uint8_t>(value));
1916 return JDWP::ERR_NONE;
1917
1918 case Primitive::kPrimChar:
1919 CHECK_EQ(width, 2);
1920 f->SetChar<kNoTransactionMode>(o, static_cast<uint16_t>(value));
1921 return JDWP::ERR_NONE;
1922
1923 case Primitive::kPrimShort:
1924 CHECK_EQ(width, 2);
1925 f->SetShort<kNoTransactionMode>(o, static_cast<int16_t>(value));
1926 return JDWP::ERR_NONE;
1927
1928 case Primitive::kPrimInt:
1929 case Primitive::kPrimFloat:
1930 CHECK_EQ(width, 4);
1931 // Int and Float must be treated as 32-bit values in JDWP.
1932 f->SetInt<kNoTransactionMode>(o, static_cast<int32_t>(value));
1933 return JDWP::ERR_NONE;
1934
1935 case Primitive::kPrimLong:
1936 case Primitive::kPrimDouble:
1937 CHECK_EQ(width, 8);
1938 // Long and Double must be treated as 64-bit values in JDWP.
1939 f->SetLong<kNoTransactionMode>(o, value);
1940 return JDWP::ERR_NONE;
1941
1942 case Primitive::kPrimNot: {
1943 JDWP::JdwpError error;
1944 mirror::Object* v = Dbg::GetObjectRegistry()->Get<mirror::Object*>(value, &error);
1945 if (error != JDWP::ERR_NONE) {
1946 return JDWP::ERR_INVALID_OBJECT;
1947 }
1948 if (v != nullptr) {
Mathieu Chartier3398c782016-09-30 10:27:43 -07001949 ObjPtr<mirror::Class> field_type;
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001950 {
1951 StackHandleScope<2> hs(Thread::Current());
1952 HandleWrapper<mirror::Object> h_v(hs.NewHandleWrapper(&v));
1953 HandleWrapper<mirror::Object> h_o(hs.NewHandleWrapper(&o));
Vladimir Marko4098a7a2017-11-06 16:00:51 +00001954 field_type = f->ResolveType();
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001955 }
1956 if (!field_type->IsAssignableFrom(v->GetClass())) {
1957 return JDWP::ERR_INVALID_OBJECT;
1958 }
1959 }
1960 f->SetObject<kNoTransactionMode>(o, v);
1961 return JDWP::ERR_NONE;
1962 }
1963
1964 case Primitive::kPrimVoid:
1965 LOG(FATAL) << "Attempt to write to field of type 'void'";
1966 UNREACHABLE();
1967 }
1968 LOG(FATAL) << "Attempt to write to field of unknown type";
1969 UNREACHABLE();
1970}
1971
Elliott Hughes88d63092013-01-09 09:55:54 -08001972static JDWP::JdwpError SetFieldValueImpl(JDWP::ObjectId object_id, JDWP::FieldId field_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001973 uint64_t value, int width, bool is_static)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001974 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001975 JDWP::JdwpError error;
Jeff Haode19a252016-09-14 15:56:35 -07001976 Thread* self = Thread::Current();
1977 StackHandleScope<2> hs(self);
1978 MutableHandle<mirror::Object>
1979 o(hs.NewHandle(Dbg::GetObjectRegistry()->Get<mirror::Object*>(object_id, &error)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08001980 if ((!is_static && o == nullptr) || error != JDWP::ERR_NONE) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001981 return JDWP::ERR_INVALID_OBJECT;
1982 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001983 ArtField* f = FromFieldId(field_id);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001984
Jeff Haode19a252016-09-14 15:56:35 -07001985 // Ensure the field's class is initialized.
1986 Handle<mirror::Class> klass(hs.NewHandle(f->GetDeclaringClass()));
1987 if (!Runtime::Current()->GetClassLinker()->EnsureInitialized(self, klass, true, false)) {
David Sehr709b0702016-10-13 09:12:37 -07001988 LOG(WARNING) << "Not able to initialize class for SetValues: "
1989 << mirror::Class::PrettyClass(klass.Get());
Jeff Haode19a252016-09-14 15:56:35 -07001990 }
1991
Elliott Hughes0cf74332012-02-23 23:14:00 -08001992 // The RI only enforces the static/non-static mismatch in one direction.
1993 // TODO: should we change the tests and check both?
1994 if (is_static) {
1995 if (!f->IsStatic()) {
1996 return JDWP::ERR_INVALID_FIELDID;
1997 }
1998 } else {
1999 if (f->IsStatic()) {
Sebastien Hertz05c26b32015-06-11 18:42:58 +02002000 LOG(WARNING) << "Ignoring non-nullptr receiver for ObjectReference.SetValues"
David Sehr709b0702016-10-13 09:12:37 -07002001 << " on static field " << f->PrettyField();
Elliott Hughes0cf74332012-02-23 23:14:00 -08002002 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002003 }
jeffhao0dfbb7e2012-11-28 15:26:03 -08002004 if (f->IsStatic()) {
Jeff Haode19a252016-09-14 15:56:35 -07002005 o.Assign(f->GetDeclaringClass());
jeffhao0dfbb7e2012-11-28 15:26:03 -08002006 }
Jeff Haode19a252016-09-14 15:56:35 -07002007 return SetArtFieldValue(f, o.Get(), value, width);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002008}
2009
Elliott Hughes88d63092013-01-09 09:55:54 -08002010JDWP::JdwpError Dbg::SetFieldValue(JDWP::ObjectId object_id, JDWP::FieldId field_id, uint64_t value,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002011 int width) {
Elliott Hughes88d63092013-01-09 09:55:54 -08002012 return SetFieldValueImpl(object_id, field_id, value, width, false);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002013}
2014
Elliott Hughes88d63092013-01-09 09:55:54 -08002015JDWP::JdwpError Dbg::SetStaticFieldValue(JDWP::FieldId field_id, uint64_t value, int width) {
2016 return SetFieldValueImpl(0, field_id, value, width, true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002017}
2018
Sebastien Hertzb0b0b492014-09-15 11:27:27 +02002019JDWP::JdwpError Dbg::StringToUtf8(JDWP::ObjectId string_id, std::string* str) {
Ian Rogersc0542af2014-09-03 16:16:56 -07002020 JDWP::JdwpError error;
Sebastien Hertzb0b0b492014-09-15 11:27:27 +02002021 mirror::Object* obj = gRegistry->Get<mirror::Object*>(string_id, &error);
2022 if (error != JDWP::ERR_NONE) {
2023 return error;
2024 }
2025 if (obj == nullptr) {
2026 return JDWP::ERR_INVALID_OBJECT;
2027 }
2028 {
2029 ScopedObjectAccessUnchecked soa(Thread::Current());
Mathieu Chartier0795f232016-09-27 18:43:30 -07002030 ObjPtr<mirror::Class> java_lang_String =
2031 soa.Decode<mirror::Class>(WellKnownClasses::java_lang_String);
Sebastien Hertzb0b0b492014-09-15 11:27:27 +02002032 if (!java_lang_String->IsAssignableFrom(obj->GetClass())) {
2033 // This isn't a string.
2034 return JDWP::ERR_INVALID_STRING;
2035 }
2036 }
2037 *str = obj->AsString()->ToModifiedUtf8();
2038 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002039}
2040
Jeff Hao579b0242013-11-18 13:16:49 -08002041void Dbg::OutputJValue(JDWP::JdwpTag tag, const JValue* return_value, JDWP::ExpandBuf* pReply) {
2042 if (IsPrimitiveTag(tag)) {
2043 expandBufAdd1(pReply, tag);
2044 if (tag == JDWP::JT_BOOLEAN || tag == JDWP::JT_BYTE) {
2045 expandBufAdd1(pReply, return_value->GetI());
2046 } else if (tag == JDWP::JT_CHAR || tag == JDWP::JT_SHORT) {
2047 expandBufAdd2BE(pReply, return_value->GetI());
2048 } else if (tag == JDWP::JT_FLOAT || tag == JDWP::JT_INT) {
2049 expandBufAdd4BE(pReply, return_value->GetI());
2050 } else if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
2051 expandBufAdd8BE(pReply, return_value->GetJ());
2052 } else {
2053 CHECK_EQ(tag, JDWP::JT_VOID);
2054 }
2055 } else {
Ian Rogers98379392014-02-24 16:53:16 -08002056 ScopedObjectAccessUnchecked soa(Thread::Current());
Jeff Hao579b0242013-11-18 13:16:49 -08002057 mirror::Object* value = return_value->GetL();
Ian Rogers98379392014-02-24 16:53:16 -08002058 expandBufAdd1(pReply, TagFromObject(soa, value));
Jeff Hao579b0242013-11-18 13:16:49 -08002059 expandBufAddObjectId(pReply, gRegistry->Add(value));
2060 }
2061}
2062
Ian Rogersc0542af2014-09-03 16:16:56 -07002063JDWP::JdwpError Dbg::GetThreadName(JDWP::ObjectId thread_id, std::string* name) {
jeffhaoa77f0f62012-12-05 17:19:31 -08002064 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002065 JDWP::JdwpError error;
Roland Levillain4b8f1ec2015-08-26 18:34:03 +01002066 DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002067 if (error != JDWP::ERR_NONE && error != JDWP::ERR_THREAD_NOT_ALIVE) {
2068 return error;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08002069 }
Elliott Hughes221229c2013-01-08 18:17:50 -08002070
2071 // We still need to report the zombie threads' names, so we can't just call Thread::GetThreadName.
Ian Rogersc0542af2014-09-03 16:16:56 -07002072 mirror::Object* thread_object = gRegistry->Get<mirror::Object*>(thread_id, &error);
2073 CHECK(thread_object != nullptr) << error;
Mathieu Chartierc7853442015-03-27 14:35:38 -07002074 ArtField* java_lang_Thread_name_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08002075 jni::DecodeArtField(WellKnownClasses::java_lang_Thread_name);
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07002076 ObjPtr<mirror::String> s(java_lang_Thread_name_field->GetObject(thread_object)->AsString());
Ian Rogersc0542af2014-09-03 16:16:56 -07002077 if (s != nullptr) {
2078 *name = s->ToModifiedUtf8();
Elliott Hughes221229c2013-01-08 18:17:50 -08002079 }
2080 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002081}
2082
Elliott Hughes221229c2013-01-08 18:17:50 -08002083JDWP::JdwpError Dbg::GetThreadGroup(JDWP::ObjectId thread_id, JDWP::ExpandBuf* pReply) {
Sebastien Hertza06430c2014-09-15 19:21:30 +02002084 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002085 JDWP::JdwpError error;
2086 mirror::Object* thread_object = gRegistry->Get<mirror::Object*>(thread_id, &error);
2087 if (error != JDWP::ERR_NONE) {
Elliott Hughes2435a572012-02-17 16:07:41 -08002088 return JDWP::ERR_INVALID_OBJECT;
2089 }
Mathieu Chartier268764d2016-09-13 12:09:38 -07002090 ScopedAssertNoThreadSuspension ants("Debugger: GetThreadGroup");
Elliott Hughes2435a572012-02-17 16:07:41 -08002091 // Okay, so it's an object, but is it actually a thread?
Roland Levillain4b8f1ec2015-08-26 18:34:03 +01002092 DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002093 if (error == JDWP::ERR_THREAD_NOT_ALIVE) {
2094 // Zombie threads are in the null group.
2095 expandBufAddObjectId(pReply, JDWP::ObjectId(0));
Sebastien Hertz52d131d2014-03-13 16:17:40 +01002096 error = JDWP::ERR_NONE;
2097 } else if (error == JDWP::ERR_NONE) {
Mathieu Chartier0795f232016-09-27 18:43:30 -07002098 ObjPtr<mirror::Class> c = soa.Decode<mirror::Class>(WellKnownClasses::java_lang_Thread);
Sebastien Hertz52d131d2014-03-13 16:17:40 +01002099 CHECK(c != nullptr);
Andreas Gampe08883de2016-11-08 13:20:52 -08002100 ArtField* f = jni::DecodeArtField(WellKnownClasses::java_lang_Thread_group);
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07002101 CHECK(f != nullptr);
Mathieu Chartier3398c782016-09-30 10:27:43 -07002102 ObjPtr<mirror::Object> group = f->GetObject(thread_object);
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07002103 CHECK(group != nullptr);
Sebastien Hertz52d131d2014-03-13 16:17:40 +01002104 JDWP::ObjectId thread_group_id = gRegistry->Add(group);
2105 expandBufAddObjectId(pReply, thread_group_id);
Elliott Hughes221229c2013-01-08 18:17:50 -08002106 }
Sebastien Hertz52d131d2014-03-13 16:17:40 +01002107 return error;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002108}
2109
Sebastien Hertza06430c2014-09-15 19:21:30 +02002110static mirror::Object* DecodeThreadGroup(ScopedObjectAccessUnchecked& soa,
2111 JDWP::ObjectId thread_group_id, JDWP::JdwpError* error)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002112 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz6995c602014-09-09 12:10:13 +02002113 mirror::Object* thread_group = Dbg::GetObjectRegistry()->Get<mirror::Object*>(thread_group_id,
2114 error);
Sebastien Hertza06430c2014-09-15 19:21:30 +02002115 if (*error != JDWP::ERR_NONE) {
2116 return nullptr;
2117 }
2118 if (thread_group == nullptr) {
2119 *error = JDWP::ERR_INVALID_OBJECT;
2120 return nullptr;
2121 }
Mathieu Chartier0795f232016-09-27 18:43:30 -07002122 ObjPtr<mirror::Class> c =
2123 soa.Decode<mirror::Class>(WellKnownClasses::java_lang_ThreadGroup);
Ian Rogers98379392014-02-24 16:53:16 -08002124 CHECK(c != nullptr);
Sebastien Hertza06430c2014-09-15 19:21:30 +02002125 if (!c->IsAssignableFrom(thread_group->GetClass())) {
2126 // This is not a java.lang.ThreadGroup.
2127 *error = JDWP::ERR_INVALID_THREAD_GROUP;
2128 return nullptr;
2129 }
2130 *error = JDWP::ERR_NONE;
2131 return thread_group;
2132}
2133
2134JDWP::JdwpError Dbg::GetThreadGroupName(JDWP::ObjectId thread_group_id, JDWP::ExpandBuf* pReply) {
2135 ScopedObjectAccessUnchecked soa(Thread::Current());
2136 JDWP::JdwpError error;
2137 mirror::Object* thread_group = DecodeThreadGroup(soa, thread_group_id, &error);
2138 if (error != JDWP::ERR_NONE) {
2139 return error;
2140 }
Mathieu Chartier268764d2016-09-13 12:09:38 -07002141 ScopedAssertNoThreadSuspension ants("Debugger: GetThreadGroupName");
Andreas Gampe08883de2016-11-08 13:20:52 -08002142 ArtField* f = jni::DecodeArtField(WellKnownClasses::java_lang_ThreadGroup_name);
Ian Rogersc0542af2014-09-03 16:16:56 -07002143 CHECK(f != nullptr);
Mathieu Chartier3398c782016-09-30 10:27:43 -07002144 ObjPtr<mirror::String> s = f->GetObject(thread_group)->AsString();
Sebastien Hertza06430c2014-09-15 19:21:30 +02002145
2146 std::string thread_group_name(s->ToModifiedUtf8());
2147 expandBufAddUtf8String(pReply, thread_group_name);
2148 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002149}
2150
Sebastien Hertza06430c2014-09-15 19:21:30 +02002151JDWP::JdwpError Dbg::GetThreadGroupParent(JDWP::ObjectId thread_group_id, JDWP::ExpandBuf* pReply) {
Ian Rogers98379392014-02-24 16:53:16 -08002152 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002153 JDWP::JdwpError error;
Sebastien Hertza06430c2014-09-15 19:21:30 +02002154 mirror::Object* thread_group = DecodeThreadGroup(soa, thread_group_id, &error);
2155 if (error != JDWP::ERR_NONE) {
2156 return error;
2157 }
Mathieu Chartier3398c782016-09-30 10:27:43 -07002158 ObjPtr<mirror::Object> parent;
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07002159 {
Mathieu Chartier268764d2016-09-13 12:09:38 -07002160 ScopedAssertNoThreadSuspension ants("Debugger: GetThreadGroupParent");
Andreas Gampe08883de2016-11-08 13:20:52 -08002161 ArtField* f = jni::DecodeArtField(WellKnownClasses::java_lang_ThreadGroup_parent);
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07002162 CHECK(f != nullptr);
2163 parent = f->GetObject(thread_group);
2164 }
Sebastien Hertza06430c2014-09-15 19:21:30 +02002165 JDWP::ObjectId parent_group_id = gRegistry->Add(parent);
2166 expandBufAddObjectId(pReply, parent_group_id);
2167 return JDWP::ERR_NONE;
2168}
2169
Andreas Gampe08883de2016-11-08 13:20:52 -08002170static void GetChildThreadGroups(mirror::Object* thread_group,
Sebastien Hertza06430c2014-09-15 19:21:30 +02002171 std::vector<JDWP::ObjectId>* child_thread_group_ids)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002172 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertza06430c2014-09-15 19:21:30 +02002173 CHECK(thread_group != nullptr);
2174
Przemyslaw Szczepaniak464595f2015-11-24 11:59:59 +00002175 // Get the int "ngroups" count of this thread group...
Andreas Gampe08883de2016-11-08 13:20:52 -08002176 ArtField* ngroups_field = jni::DecodeArtField(WellKnownClasses::java_lang_ThreadGroup_ngroups);
Przemyslaw Szczepaniak464595f2015-11-24 11:59:59 +00002177 CHECK(ngroups_field != nullptr);
2178 const int32_t size = ngroups_field->GetInt(thread_group);
2179 if (size == 0) {
2180 return;
Sebastien Hertze49e1952014-10-13 11:27:13 +02002181 }
Sebastien Hertza06430c2014-09-15 19:21:30 +02002182
Przemyslaw Szczepaniak464595f2015-11-24 11:59:59 +00002183 // Get the ThreadGroup[] "groups" out of this thread group...
Andreas Gampe08883de2016-11-08 13:20:52 -08002184 ArtField* groups_field = jni::DecodeArtField(WellKnownClasses::java_lang_ThreadGroup_groups);
Mathieu Chartier3398c782016-09-30 10:27:43 -07002185 ObjPtr<mirror::Object> groups_array = groups_field->GetObject(thread_group);
Przemyslaw Szczepaniak464595f2015-11-24 11:59:59 +00002186
2187 CHECK(groups_array != nullptr);
2188 CHECK(groups_array->IsObjectArray());
2189
Mathieu Chartier3398c782016-09-30 10:27:43 -07002190 ObjPtr<mirror::ObjectArray<mirror::Object>> groups_array_as_array =
Przemyslaw Szczepaniak464595f2015-11-24 11:59:59 +00002191 groups_array->AsObjectArray<mirror::Object>();
Sebastien Hertza06430c2014-09-15 19:21:30 +02002192
2193 // Copy the first 'size' elements out of the array into the result.
Sebastien Hertz6995c602014-09-09 12:10:13 +02002194 ObjectRegistry* registry = Dbg::GetObjectRegistry();
Sebastien Hertza06430c2014-09-15 19:21:30 +02002195 for (int32_t i = 0; i < size; ++i) {
Przemyslaw Szczepaniak464595f2015-11-24 11:59:59 +00002196 child_thread_group_ids->push_back(registry->Add(groups_array_as_array->Get(i)));
Sebastien Hertza06430c2014-09-15 19:21:30 +02002197 }
2198}
2199
2200JDWP::JdwpError Dbg::GetThreadGroupChildren(JDWP::ObjectId thread_group_id,
2201 JDWP::ExpandBuf* pReply) {
2202 ScopedObjectAccessUnchecked soa(Thread::Current());
2203 JDWP::JdwpError error;
2204 mirror::Object* thread_group = DecodeThreadGroup(soa, thread_group_id, &error);
2205 if (error != JDWP::ERR_NONE) {
2206 return error;
2207 }
2208
2209 // Add child threads.
2210 {
2211 std::vector<JDWP::ObjectId> child_thread_ids;
2212 GetThreads(thread_group, &child_thread_ids);
2213 expandBufAdd4BE(pReply, child_thread_ids.size());
2214 for (JDWP::ObjectId child_thread_id : child_thread_ids) {
2215 expandBufAddObjectId(pReply, child_thread_id);
2216 }
2217 }
2218
2219 // Add child thread groups.
2220 {
2221 std::vector<JDWP::ObjectId> child_thread_groups_ids;
Andreas Gampe08883de2016-11-08 13:20:52 -08002222 GetChildThreadGroups(thread_group, &child_thread_groups_ids);
Sebastien Hertza06430c2014-09-15 19:21:30 +02002223 expandBufAdd4BE(pReply, child_thread_groups_ids.size());
2224 for (JDWP::ObjectId child_thread_group_id : child_thread_groups_ids) {
2225 expandBufAddObjectId(pReply, child_thread_group_id);
2226 }
2227 }
2228
2229 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002230}
2231
2232JDWP::ObjectId Dbg::GetSystemThreadGroupId() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002233 ScopedObjectAccessUnchecked soa(Thread::Current());
Andreas Gampe08883de2016-11-08 13:20:52 -08002234 ArtField* f = jni::DecodeArtField(WellKnownClasses::java_lang_ThreadGroup_systemThreadGroup);
Mathieu Chartier3398c782016-09-30 10:27:43 -07002235 ObjPtr<mirror::Object> group = f->GetObject(f->GetDeclaringClass());
Ian Rogers365c1022012-06-22 15:05:28 -07002236 return gRegistry->Add(group);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002237}
2238
Jeff Hao920af3e2013-08-28 15:46:38 -07002239JDWP::JdwpThreadStatus Dbg::ToJdwpThreadStatus(ThreadState state) {
2240 switch (state) {
2241 case kBlocked:
2242 return JDWP::TS_MONITOR;
2243 case kNative:
2244 case kRunnable:
2245 case kSuspended:
2246 return JDWP::TS_RUNNING;
2247 case kSleeping:
2248 return JDWP::TS_SLEEPING;
2249 case kStarting:
2250 case kTerminated:
2251 return JDWP::TS_ZOMBIE;
2252 case kTimedWaiting:
Alex Light77fee872017-09-05 14:51:49 -07002253 case kWaitingForTaskProcessor:
2254 case kWaitingForLockInflation:
Sebastien Hertzbae182c2013-12-17 10:42:03 +01002255 case kWaitingForCheckPointsToRun:
Jeff Hao920af3e2013-08-28 15:46:38 -07002256 case kWaitingForDebuggerSend:
2257 case kWaitingForDebuggerSuspension:
2258 case kWaitingForDebuggerToAttach:
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002259 case kWaitingForDeoptimization:
Jeff Hao920af3e2013-08-28 15:46:38 -07002260 case kWaitingForGcToComplete:
Mathieu Chartierb43390c2015-05-12 10:47:11 -07002261 case kWaitingForGetObjectsAllocated:
Jeff Hao920af3e2013-08-28 15:46:38 -07002262 case kWaitingForJniOnLoad:
Sebastien Hertzbae182c2013-12-17 10:42:03 +01002263 case kWaitingForMethodTracingStart:
Jeff Hao920af3e2013-08-28 15:46:38 -07002264 case kWaitingForSignalCatcherOutput:
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -08002265 case kWaitingForVisitObjects:
Jeff Hao920af3e2013-08-28 15:46:38 -07002266 case kWaitingInMainDebuggerLoop:
2267 case kWaitingInMainSignalCatcherLoop:
2268 case kWaitingPerformingGc:
Mathieu Chartier90ef3db2015-08-04 15:19:41 -07002269 case kWaitingWeakGcRootRead:
Hiroshi Yamauchi76f55b02015-08-21 16:10:39 -07002270 case kWaitingForGcThreadFlip:
Jeff Hao920af3e2013-08-28 15:46:38 -07002271 case kWaiting:
2272 return JDWP::TS_WAIT;
2273 // Don't add a 'default' here so the compiler can spot incompatible enum changes.
2274 }
2275 LOG(FATAL) << "Unknown thread state: " << state;
2276 return JDWP::TS_ZOMBIE;
2277}
2278
Sebastien Hertz52d131d2014-03-13 16:17:40 +01002279JDWP::JdwpError Dbg::GetThreadStatus(JDWP::ObjectId thread_id, JDWP::JdwpThreadStatus* pThreadStatus,
2280 JDWP::JdwpSuspendStatus* pSuspendStatus) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002281 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes499c5132011-11-17 14:55:11 -08002282
Elliott Hughes9e0c1752013-01-09 14:02:58 -08002283 *pSuspendStatus = JDWP::SUSPEND_STATUS_NOT_SUSPENDED;
2284
Ian Rogersc0542af2014-09-03 16:16:56 -07002285 JDWP::JdwpError error;
2286 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002287 if (error != JDWP::ERR_NONE) {
2288 if (error == JDWP::ERR_THREAD_NOT_ALIVE) {
2289 *pThreadStatus = JDWP::TS_ZOMBIE;
Elliott Hughes221229c2013-01-08 18:17:50 -08002290 return JDWP::ERR_NONE;
2291 }
2292 return error;
Elliott Hughes499c5132011-11-17 14:55:11 -08002293 }
2294
Elliott Hughes9e0c1752013-01-09 14:02:58 -08002295 if (IsSuspendedForDebugger(soa, thread)) {
2296 *pSuspendStatus = JDWP::SUSPEND_STATUS_SUSPENDED;
Elliott Hughes499c5132011-11-17 14:55:11 -08002297 }
2298
Jeff Hao920af3e2013-08-28 15:46:38 -07002299 *pThreadStatus = ToJdwpThreadStatus(thread->GetState());
Elliott Hughes221229c2013-01-08 18:17:50 -08002300 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002301}
2302
Elliott Hughes221229c2013-01-08 18:17:50 -08002303JDWP::JdwpError Dbg::GetThreadDebugSuspendCount(JDWP::ObjectId thread_id, JDWP::ExpandBuf* pReply) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002304 ScopedObjectAccess soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002305 JDWP::JdwpError error;
2306 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002307 if (error != JDWP::ERR_NONE) {
2308 return error;
Elliott Hughes2435a572012-02-17 16:07:41 -08002309 }
Ian Rogers50b35e22012-10-04 10:09:15 -07002310 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002311 expandBufAdd4BE(pReply, thread->GetDebugSuspendCount());
Elliott Hughes2435a572012-02-17 16:07:41 -08002312 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002313}
2314
Elliott Hughesf9501702013-01-11 11:22:27 -08002315JDWP::JdwpError Dbg::Interrupt(JDWP::ObjectId thread_id) {
2316 ScopedObjectAccess soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002317 JDWP::JdwpError error;
2318 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughesf9501702013-01-11 11:22:27 -08002319 if (error != JDWP::ERR_NONE) {
2320 return error;
2321 }
Ian Rogersdd7624d2014-03-14 17:43:00 -07002322 thread->Interrupt(soa.Self());
Elliott Hughesf9501702013-01-11 11:22:27 -08002323 return JDWP::ERR_NONE;
2324}
2325
Andreas Gampe08883de2016-11-08 13:20:52 -08002326static bool IsInDesiredThreadGroup(mirror::Object* desired_thread_group, mirror::Object* peer)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002327 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz070f7322014-09-09 12:08:49 +02002328 // Do we want threads from all thread groups?
2329 if (desired_thread_group == nullptr) {
2330 return true;
2331 }
Andreas Gampe08883de2016-11-08 13:20:52 -08002332 ArtField* thread_group_field = jni::DecodeArtField(WellKnownClasses::java_lang_Thread_group);
Sebastien Hertz070f7322014-09-09 12:08:49 +02002333 DCHECK(thread_group_field != nullptr);
Mathieu Chartier3398c782016-09-30 10:27:43 -07002334 ObjPtr<mirror::Object> group = thread_group_field->GetObject(peer);
Sebastien Hertz070f7322014-09-09 12:08:49 +02002335 return (group == desired_thread_group);
2336}
2337
Sebastien Hertza06430c2014-09-15 19:21:30 +02002338void Dbg::GetThreads(mirror::Object* thread_group, std::vector<JDWP::ObjectId>* thread_ids) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002339 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz070f7322014-09-09 12:08:49 +02002340 std::list<Thread*> all_threads_list;
2341 {
2342 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
2343 all_threads_list = Runtime::Current()->GetThreadList()->GetList();
2344 }
2345 for (Thread* t : all_threads_list) {
2346 if (t == Dbg::GetDebugThread()) {
2347 // Skip the JDWP thread. Some debuggers get bent out of shape when they can't suspend and
2348 // query all threads, so it's easier if we just don't tell them about this thread.
2349 continue;
2350 }
2351 if (t->IsStillStarting()) {
2352 // This thread is being started (and has been registered in the thread list). However, it is
2353 // not completely started yet so we must ignore it.
2354 continue;
2355 }
Nicolas Geoffraycafa0812017-02-15 18:27:34 +00002356 mirror::Object* peer = t->GetPeerFromOtherThread();
Sebastien Hertz070f7322014-09-09 12:08:49 +02002357 if (peer == nullptr) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002358 // 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 +02002359 // this thread yet.
2360 // TODO: if we identified threads to the debugger by their Thread*
2361 // rather than their peer's mirror::Object*, we could fix this.
2362 // Doing so might help us report ZOMBIE threads too.
2363 continue;
2364 }
Andreas Gampe08883de2016-11-08 13:20:52 -08002365 if (IsInDesiredThreadGroup(thread_group, peer)) {
Sebastien Hertz070f7322014-09-09 12:08:49 +02002366 thread_ids->push_back(gRegistry->Add(peer));
2367 }
2368 }
Elliott Hughescaf76542012-06-28 16:08:22 -07002369}
Elliott Hughesa2155262011-11-16 16:26:58 -08002370
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002371static int GetStackDepth(Thread* thread) REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002372 struct CountStackDepthVisitor : public StackVisitor {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002373 explicit CountStackDepthVisitor(Thread* thread_in)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01002374 : StackVisitor(thread_in, nullptr, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
2375 depth(0) {}
Ian Rogers0399dde2012-06-06 17:09:28 -07002376
Elliott Hughes64f574f2013-02-20 14:57:12 -08002377 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2378 // annotalysis.
Andreas Gampefa6a1b02018-09-07 08:11:55 -07002379 bool VisitFrame() override NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07002380 if (!GetMethod()->IsRuntimeMethod()) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -08002381 ++depth;
2382 }
Elliott Hughes530fa002012-03-12 11:44:49 -07002383 return true;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08002384 }
2385 size_t depth;
2386 };
Elliott Hughes08fc03a2012-06-26 17:34:00 -07002387
Ian Rogers7a22fa62013-01-23 12:16:16 -08002388 CountStackDepthVisitor visitor(thread);
Ian Rogers0399dde2012-06-06 17:09:28 -07002389 visitor.WalkStack();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08002390 return visitor.depth;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002391}
2392
Ian Rogersc0542af2014-09-03 16:16:56 -07002393JDWP::JdwpError Dbg::GetThreadFrameCount(JDWP::ObjectId thread_id, size_t* result) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002394 ScopedObjectAccess soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002395 JDWP::JdwpError error;
2396 *result = 0;
2397 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002398 if (error != JDWP::ERR_NONE) {
2399 return error;
2400 }
Elliott Hughesf15f4a02013-01-09 10:09:38 -08002401 if (!IsSuspendedForDebugger(soa, thread)) {
2402 return JDWP::ERR_THREAD_NOT_SUSPENDED;
2403 }
Ian Rogersc0542af2014-09-03 16:16:56 -07002404 *result = GetStackDepth(thread);
Elliott Hughes221229c2013-01-08 18:17:50 -08002405 return JDWP::ERR_NONE;
Elliott Hughes86964332012-02-15 19:37:42 -08002406}
2407
Ian Rogers306057f2012-11-26 12:45:53 -08002408JDWP::JdwpError Dbg::GetThreadFrames(JDWP::ObjectId thread_id, size_t start_frame,
2409 size_t frame_count, JDWP::ExpandBuf* buf) {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002410 class GetFrameVisitor : public StackVisitor {
2411 public:
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002412 GetFrameVisitor(Thread* thread, size_t start_frame_in, size_t frame_count_in,
2413 JDWP::ExpandBuf* buf_in)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002414 REQUIRES_SHARED(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01002415 : StackVisitor(thread, nullptr, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
2416 depth_(0),
2417 start_frame_(start_frame_in),
2418 frame_count_(frame_count_in),
2419 buf_(buf_in) {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002420 expandBufAdd4BE(buf_, frame_count_);
Elliott Hughes03181a82011-11-17 17:22:21 -08002421 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002422
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01002423 bool VisitFrame() override REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002424 if (GetMethod()->IsRuntimeMethod()) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07002425 return true; // The debugger can't do anything useful with a frame that has no Method*.
Elliott Hughes03181a82011-11-17 17:22:21 -08002426 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002427 if (depth_ >= start_frame_ + frame_count_) {
Elliott Hughes530fa002012-03-12 11:44:49 -07002428 return false;
Elliott Hughes03181a82011-11-17 17:22:21 -08002429 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002430 if (depth_ >= start_frame_) {
2431 JDWP::FrameId frame_id(GetFrameId());
2432 JDWP::JdwpLocation location;
Sebastien Hertz6995c602014-09-09 12:10:13 +02002433 SetJdwpLocation(&location, GetMethod(), GetDexPc());
Ian Rogersef7d42f2014-01-06 12:55:46 -08002434 VLOG(jdwp) << StringPrintf(" Frame %3zd: id=%3" PRIu64 " ", depth_, frame_id) << location;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002435 expandBufAdd8BE(buf_, frame_id);
2436 expandBufAddLocation(buf_, location);
2437 }
2438 ++depth_;
Elliott Hughes530fa002012-03-12 11:44:49 -07002439 return true;
Elliott Hughes03181a82011-11-17 17:22:21 -08002440 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002441
2442 private:
2443 size_t depth_;
2444 const size_t start_frame_;
2445 const size_t frame_count_;
2446 JDWP::ExpandBuf* buf_;
Elliott Hughes03181a82011-11-17 17:22:21 -08002447 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002448
2449 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002450 JDWP::JdwpError error;
2451 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002452 if (error != JDWP::ERR_NONE) {
2453 return error;
2454 }
Elliott Hughesf15f4a02013-01-09 10:09:38 -08002455 if (!IsSuspendedForDebugger(soa, thread)) {
2456 return JDWP::ERR_THREAD_NOT_SUSPENDED;
2457 }
Ian Rogers7a22fa62013-01-23 12:16:16 -08002458 GetFrameVisitor visitor(thread, start_frame, frame_count, buf);
Ian Rogers0399dde2012-06-06 17:09:28 -07002459 visitor.WalkStack();
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002460 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002461}
2462
2463JDWP::ObjectId Dbg::GetThreadSelfId() {
Sebastien Hertz6995c602014-09-09 12:10:13 +02002464 return GetThreadId(Thread::Current());
2465}
2466
2467JDWP::ObjectId Dbg::GetThreadId(Thread* thread) {
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07002468 ScopedObjectAccessUnchecked soa(Thread::Current());
Nicolas Geoffraycafa0812017-02-15 18:27:34 +00002469 return gRegistry->Add(thread->GetPeerFromOtherThread());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002470}
2471
Elliott Hughes475fc232011-10-25 15:00:35 -07002472void Dbg::SuspendVM() {
Hiroshi Yamauchi8f95cf32016-04-19 11:14:06 -07002473 // Avoid a deadlock between GC and debugger where GC gets suspended during GC. b/25800335.
2474 gc::ScopedGCCriticalSection gcs(Thread::Current(),
2475 gc::kGcCauseDebugger,
2476 gc::kCollectorTypeDebugger);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002477 Runtime::Current()->GetThreadList()->SuspendAllForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002478}
2479
2480void Dbg::ResumeVM() {
Sebastien Hertz253fa552014-10-14 17:27:15 +02002481 Runtime::Current()->GetThreadList()->ResumeAllForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002482}
2483
Elliott Hughes221229c2013-01-08 18:17:50 -08002484JDWP::JdwpError Dbg::SuspendThread(JDWP::ObjectId thread_id, bool request_suspension) {
Ian Rogersf3d874c2014-07-17 18:52:42 -07002485 Thread* self = Thread::Current();
Ian Rogersc0542af2014-09-03 16:16:56 -07002486 ScopedLocalRef<jobject> peer(self->GetJniEnv(), nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002487 {
Ian Rogersf3d874c2014-07-17 18:52:42 -07002488 ScopedObjectAccess soa(self);
Ian Rogersc0542af2014-09-03 16:16:56 -07002489 JDWP::JdwpError error;
2490 peer.reset(soa.AddLocalReference<jobject>(gRegistry->Get<mirror::Object*>(thread_id, &error)));
Elliott Hughes4e235312011-12-02 11:34:15 -08002491 }
Ian Rogersc0542af2014-09-03 16:16:56 -07002492 if (peer.get() == nullptr) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002493 return JDWP::ERR_THREAD_NOT_ALIVE;
2494 }
Ian Rogers4ad5cd32014-11-11 23:08:07 -08002495 // Suspend thread to build stack trace.
Elliott Hughesf327e072013-01-09 16:01:26 -08002496 bool timed_out;
Brian Carlstromba32de42014-08-27 23:43:46 -07002497 ThreadList* thread_list = Runtime::Current()->GetThreadList();
Sebastien Hertzcdd798d2017-04-18 18:28:51 +02002498 Thread* thread = thread_list->SuspendThreadByPeer(peer.get(),
2499 request_suspension,
Alex Light46f93402017-06-29 11:59:50 -07002500 SuspendReason::kForDebugger,
Brian Carlstromba32de42014-08-27 23:43:46 -07002501 &timed_out);
Ian Rogersc0542af2014-09-03 16:16:56 -07002502 if (thread != nullptr) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002503 return JDWP::ERR_NONE;
Elliott Hughesf327e072013-01-09 16:01:26 -08002504 } else if (timed_out) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002505 return JDWP::ERR_INTERNAL;
2506 } else {
2507 return JDWP::ERR_THREAD_NOT_ALIVE;
2508 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002509}
2510
Elliott Hughes221229c2013-01-08 18:17:50 -08002511void Dbg::ResumeThread(JDWP::ObjectId thread_id) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002512 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002513 JDWP::JdwpError error;
2514 mirror::Object* peer = gRegistry->Get<mirror::Object*>(thread_id, &error);
2515 CHECK(peer != nullptr) << error;
jeffhaoa77f0f62012-12-05 17:19:31 -08002516 Thread* thread;
2517 {
2518 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
2519 thread = Thread::FromManagedThread(soa, peer);
2520 }
Ian Rogersc0542af2014-09-03 16:16:56 -07002521 if (thread == nullptr) {
Elliott Hughes4e235312011-12-02 11:34:15 -08002522 LOG(WARNING) << "No such thread for resume: " << peer;
2523 return;
2524 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002525 bool needs_resume;
2526 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002527 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Sebastien Hertz70d60272017-04-14 14:18:36 +02002528 needs_resume = thread->GetDebugSuspendCount() > 0;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002529 }
2530 if (needs_resume) {
Alex Light88fd7202017-06-30 08:31:59 -07002531 bool resumed = Runtime::Current()->GetThreadList()->Resume(thread, SuspendReason::kForDebugger);
2532 DCHECK(resumed);
Elliott Hughes546b9862012-06-20 16:06:13 -07002533 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002534}
2535
2536void Dbg::SuspendSelf() {
Elliott Hughes475fc232011-10-25 15:00:35 -07002537 Runtime::Current()->GetThreadList()->SuspendSelfForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002538}
2539
Ian Rogers0399dde2012-06-06 17:09:28 -07002540struct GetThisVisitor : public StackVisitor {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002541 GetThisVisitor(Thread* thread, Context* context, JDWP::FrameId frame_id_in)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002542 REQUIRES_SHARED(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01002543 : StackVisitor(thread, context, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
2544 this_object(nullptr),
2545 frame_id(frame_id_in) {}
Ian Rogers0399dde2012-06-06 17:09:28 -07002546
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002547 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2548 // annotalysis.
Andreas Gampefa6a1b02018-09-07 08:11:55 -07002549 bool VisitFrame() override NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002550 if (frame_id != GetFrameId()) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002551 return true; // continue
Ian Rogers0399dde2012-06-06 17:09:28 -07002552 } else {
Ian Rogers62d6c772013-02-27 08:32:07 -08002553 this_object = GetThisObject();
2554 return false;
Ian Rogers0399dde2012-06-06 17:09:28 -07002555 }
Elliott Hughes86b00102011-12-05 17:54:26 -08002556 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002557
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002558 mirror::Object* this_object;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002559 JDWP::FrameId frame_id;
Ian Rogers0399dde2012-06-06 17:09:28 -07002560};
2561
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002562JDWP::JdwpError Dbg::GetThisObject(JDWP::ObjectId thread_id, JDWP::FrameId frame_id,
2563 JDWP::ObjectId* result) {
2564 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz69206392015-04-07 15:54:25 +02002565 JDWP::JdwpError error;
2566 Thread* thread = DecodeThread(soa, thread_id, &error);
2567 if (error != JDWP::ERR_NONE) {
2568 return error;
2569 }
2570 if (!IsSuspendedForDebugger(soa, thread)) {
2571 return JDWP::ERR_THREAD_NOT_SUSPENDED;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002572 }
Ian Rogers700a4022014-05-19 16:49:03 -07002573 std::unique_ptr<Context> context(Context::Create());
Ian Rogers7a22fa62013-01-23 12:16:16 -08002574 GetThisVisitor visitor(thread, context.get(), frame_id);
Ian Rogers0399dde2012-06-06 17:09:28 -07002575 visitor.WalkStack();
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002576 *result = gRegistry->Add(visitor.this_object);
2577 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002578}
2579
Sebastien Hertz8009f392014-09-01 17:07:11 +02002580// Walks the stack until we find the frame with the given FrameId.
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01002581class FindFrameVisitor final : public StackVisitor {
Sebastien Hertz8009f392014-09-01 17:07:11 +02002582 public:
2583 FindFrameVisitor(Thread* thread, Context* context, JDWP::FrameId frame_id)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002584 REQUIRES_SHARED(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01002585 : StackVisitor(thread, context, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
2586 frame_id_(frame_id),
2587 error_(JDWP::ERR_INVALID_FRAMEID) {}
Ian Rogersca190662012-06-26 15:45:57 -07002588
Sebastien Hertz8009f392014-09-01 17:07:11 +02002589 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2590 // annotalysis.
Andreas Gampefa6a1b02018-09-07 08:11:55 -07002591 bool VisitFrame() override NO_THREAD_SAFETY_ANALYSIS {
Sebastien Hertz8009f392014-09-01 17:07:11 +02002592 if (GetFrameId() != frame_id_) {
2593 return true; // Not our frame, carry on.
Ian Rogers0399dde2012-06-06 17:09:28 -07002594 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07002595 ArtMethod* m = GetMethod();
Sebastien Hertz8009f392014-09-01 17:07:11 +02002596 if (m->IsNative()) {
2597 // We can't read/write local value from/into native method.
2598 error_ = JDWP::ERR_OPAQUE_FRAME;
2599 } else {
2600 // We found our frame.
2601 error_ = JDWP::ERR_NONE;
2602 }
2603 return false;
2604 }
2605
2606 JDWP::JdwpError GetError() const {
2607 return error_;
2608 }
2609
2610 private:
2611 const JDWP::FrameId frame_id_;
2612 JDWP::JdwpError error_;
Sebastien Hertz26f72862015-09-15 09:52:07 +02002613
2614 DISALLOW_COPY_AND_ASSIGN(FindFrameVisitor);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002615};
2616
2617JDWP::JdwpError Dbg::GetLocalValues(JDWP::Request* request, JDWP::ExpandBuf* pReply) {
2618 JDWP::ObjectId thread_id = request->ReadThreadId();
2619 JDWP::FrameId frame_id = request->ReadFrameId();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002620
2621 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz69206392015-04-07 15:54:25 +02002622 JDWP::JdwpError error;
2623 Thread* thread = DecodeThread(soa, thread_id, &error);
2624 if (error != JDWP::ERR_NONE) {
2625 return error;
2626 }
2627 if (!IsSuspendedForDebugger(soa, thread)) {
2628 return JDWP::ERR_THREAD_NOT_SUSPENDED;
Elliott Hughes221229c2013-01-08 18:17:50 -08002629 }
Sebastien Hertz8009f392014-09-01 17:07:11 +02002630 // Find the frame with the given frame_id.
Ian Rogers700a4022014-05-19 16:49:03 -07002631 std::unique_ptr<Context> context(Context::Create());
Sebastien Hertz8009f392014-09-01 17:07:11 +02002632 FindFrameVisitor visitor(thread, context.get(), frame_id);
Ian Rogers0399dde2012-06-06 17:09:28 -07002633 visitor.WalkStack();
Sebastien Hertz8009f392014-09-01 17:07:11 +02002634 if (visitor.GetError() != JDWP::ERR_NONE) {
2635 return visitor.GetError();
2636 }
2637
2638 // Read the values from visitor's context.
2639 int32_t slot_count = request->ReadSigned32("slot count");
2640 expandBufAdd4BE(pReply, slot_count); /* "int values" */
2641 for (int32_t i = 0; i < slot_count; ++i) {
2642 uint32_t slot = request->ReadUnsigned32("slot");
2643 JDWP::JdwpTag reqSigByte = request->ReadTag();
2644
2645 VLOG(jdwp) << " --> slot " << slot << " " << reqSigByte;
2646
2647 size_t width = Dbg::GetTagWidth(reqSigByte);
Sebastien Hertz7d955652014-10-22 10:57:10 +02002648 uint8_t* ptr = expandBufAddSpace(pReply, width + 1);
Sebastien Hertz69206392015-04-07 15:54:25 +02002649 error = Dbg::GetLocalValue(visitor, soa, slot, reqSigByte, ptr, width);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002650 if (error != JDWP::ERR_NONE) {
2651 return error;
2652 }
2653 }
2654 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002655}
2656
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002657constexpr JDWP::JdwpError kStackFrameLocalAccessError = JDWP::ERR_ABSENT_INFORMATION;
2658
2659static std::string GetStackContextAsString(const StackVisitor& visitor)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002660 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002661 return StringPrintf(" at DEX pc 0x%08x in method %s", visitor.GetDexPc(false),
David Sehr709b0702016-10-13 09:12:37 -07002662 ArtMethod::PrettyMethod(visitor.GetMethod()).c_str());
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002663}
2664
2665static JDWP::JdwpError FailGetLocalValue(const StackVisitor& visitor, uint16_t vreg,
2666 JDWP::JdwpTag tag)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002667 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002668 LOG(ERROR) << "Failed to read " << tag << " local from register v" << vreg
2669 << GetStackContextAsString(visitor);
2670 return kStackFrameLocalAccessError;
2671}
2672
Sebastien Hertz8009f392014-09-01 17:07:11 +02002673JDWP::JdwpError Dbg::GetLocalValue(const StackVisitor& visitor, ScopedObjectAccessUnchecked& soa,
2674 int slot, JDWP::JdwpTag tag, uint8_t* buf, size_t width) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002675 ArtMethod* m = visitor.GetMethod();
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002676 JDWP::JdwpError error = JDWP::ERR_NONE;
2677 uint16_t vreg = DemangleSlot(slot, m, &error);
2678 if (error != JDWP::ERR_NONE) {
2679 return error;
2680 }
Sebastien Hertz8009f392014-09-01 17:07:11 +02002681 // TODO: check that the tag is compatible with the actual type of the slot!
Sebastien Hertz8009f392014-09-01 17:07:11 +02002682 switch (tag) {
2683 case JDWP::JT_BOOLEAN: {
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);
Ian Rogers0399dde2012-06-06 17:09:28 -07002688 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002689 VLOG(jdwp) << "get boolean local " << vreg << " = " << intVal;
2690 JDWP::Set1(buf + 1, intVal != 0);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002691 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002692 }
Sebastien Hertz8009f392014-09-01 17:07:11 +02002693 case JDWP::JT_BYTE: {
2694 CHECK_EQ(width, 1U);
2695 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002696 if (!visitor.GetVReg(m, vreg, kIntVReg, &intVal)) {
2697 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002698 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002699 VLOG(jdwp) << "get byte local " << vreg << " = " << intVal;
2700 JDWP::Set1(buf + 1, intVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002701 break;
2702 }
2703 case JDWP::JT_SHORT:
2704 case JDWP::JT_CHAR: {
2705 CHECK_EQ(width, 2U);
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 short/char local " << vreg << " = " << intVal;
2711 JDWP::Set2BE(buf + 1, intVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002712 break;
2713 }
2714 case JDWP::JT_INT: {
2715 CHECK_EQ(width, 4U);
2716 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002717 if (!visitor.GetVReg(m, vreg, kIntVReg, &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 int local " << vreg << " = " << intVal;
2721 JDWP::Set4BE(buf + 1, intVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002722 break;
2723 }
2724 case JDWP::JT_FLOAT: {
2725 CHECK_EQ(width, 4U);
2726 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002727 if (!visitor.GetVReg(m, vreg, kFloatVReg, &intVal)) {
2728 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002729 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002730 VLOG(jdwp) << "get float local " << vreg << " = " << intVal;
2731 JDWP::Set4BE(buf + 1, intVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002732 break;
2733 }
2734 case JDWP::JT_ARRAY:
2735 case JDWP::JT_CLASS_LOADER:
2736 case JDWP::JT_CLASS_OBJECT:
2737 case JDWP::JT_OBJECT:
2738 case JDWP::JT_STRING:
2739 case JDWP::JT_THREAD:
2740 case JDWP::JT_THREAD_GROUP: {
2741 CHECK_EQ(width, sizeof(JDWP::ObjectId));
2742 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002743 if (!visitor.GetVReg(m, vreg, kReferenceVReg, &intVal)) {
2744 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002745 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002746 mirror::Object* o = reinterpret_cast<mirror::Object*>(intVal);
2747 VLOG(jdwp) << "get " << tag << " object local " << vreg << " = " << o;
2748 if (!Runtime::Current()->GetHeap()->IsValidObjectAddress(o)) {
2749 LOG(FATAL) << StringPrintf("Found invalid object %#" PRIxPTR " in register v%u",
2750 reinterpret_cast<uintptr_t>(o), vreg)
2751 << GetStackContextAsString(visitor);
2752 UNREACHABLE();
2753 }
2754 tag = TagFromObject(soa, o);
2755 JDWP::SetObjectId(buf + 1, gRegistry->Add(o));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002756 break;
2757 }
2758 case JDWP::JT_DOUBLE: {
2759 CHECK_EQ(width, 8U);
2760 uint64_t longVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002761 if (!visitor.GetVRegPair(m, vreg, kDoubleLoVReg, kDoubleHiVReg, &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 double local " << vreg << " = " << longVal;
2765 JDWP::Set8BE(buf + 1, longVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002766 break;
2767 }
2768 case JDWP::JT_LONG: {
2769 CHECK_EQ(width, 8U);
2770 uint64_t longVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002771 if (!visitor.GetVRegPair(m, vreg, kLongLoVReg, kLongHiVReg, &longVal)) {
2772 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002773 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002774 VLOG(jdwp) << "get long local " << vreg << " = " << longVal;
2775 JDWP::Set8BE(buf + 1, longVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002776 break;
2777 }
2778 default:
2779 LOG(FATAL) << "Unknown tag " << tag;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002780 UNREACHABLE();
Sebastien Hertz8009f392014-09-01 17:07:11 +02002781 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002782
Sebastien Hertz8009f392014-09-01 17:07:11 +02002783 // Prepend tag, which may have been updated.
2784 JDWP::Set1(buf, tag);
2785 return JDWP::ERR_NONE;
2786}
2787
2788JDWP::JdwpError Dbg::SetLocalValues(JDWP::Request* request) {
2789 JDWP::ObjectId thread_id = request->ReadThreadId();
2790 JDWP::FrameId frame_id = request->ReadFrameId();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002791
2792 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz69206392015-04-07 15:54:25 +02002793 JDWP::JdwpError error;
2794 Thread* thread = DecodeThread(soa, thread_id, &error);
2795 if (error != JDWP::ERR_NONE) {
2796 return error;
2797 }
2798 if (!IsSuspendedForDebugger(soa, thread)) {
2799 return JDWP::ERR_THREAD_NOT_SUSPENDED;
Elliott Hughes221229c2013-01-08 18:17:50 -08002800 }
Sebastien Hertz8009f392014-09-01 17:07:11 +02002801 // Find the frame with the given frame_id.
Ian Rogers700a4022014-05-19 16:49:03 -07002802 std::unique_ptr<Context> context(Context::Create());
Sebastien Hertz8009f392014-09-01 17:07:11 +02002803 FindFrameVisitor visitor(thread, context.get(), frame_id);
Ian Rogers0399dde2012-06-06 17:09:28 -07002804 visitor.WalkStack();
Sebastien Hertz8009f392014-09-01 17:07:11 +02002805 if (visitor.GetError() != JDWP::ERR_NONE) {
2806 return visitor.GetError();
2807 }
2808
2809 // Writes the values into visitor's context.
2810 int32_t slot_count = request->ReadSigned32("slot count");
2811 for (int32_t i = 0; i < slot_count; ++i) {
2812 uint32_t slot = request->ReadUnsigned32("slot");
2813 JDWP::JdwpTag sigByte = request->ReadTag();
2814 size_t width = Dbg::GetTagWidth(sigByte);
2815 uint64_t value = request->ReadValue(width);
2816
2817 VLOG(jdwp) << " --> slot " << slot << " " << sigByte << " " << value;
Mingyao Yang99170c62015-07-06 11:10:37 -07002818 error = Dbg::SetLocalValue(thread, visitor, slot, sigByte, value, width);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002819 if (error != JDWP::ERR_NONE) {
2820 return error;
2821 }
2822 }
2823 return JDWP::ERR_NONE;
2824}
2825
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002826template<typename T>
2827static JDWP::JdwpError FailSetLocalValue(const StackVisitor& visitor, uint16_t vreg,
2828 JDWP::JdwpTag tag, T value)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002829 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002830 LOG(ERROR) << "Failed to write " << tag << " local " << value
2831 << " (0x" << std::hex << value << ") into register v" << vreg
2832 << GetStackContextAsString(visitor);
2833 return kStackFrameLocalAccessError;
2834}
2835
Mingyao Yang99170c62015-07-06 11:10:37 -07002836JDWP::JdwpError Dbg::SetLocalValue(Thread* thread, StackVisitor& visitor, int slot,
2837 JDWP::JdwpTag tag, uint64_t value, size_t width) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002838 ArtMethod* m = visitor.GetMethod();
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002839 JDWP::JdwpError error = JDWP::ERR_NONE;
2840 uint16_t vreg = DemangleSlot(slot, m, &error);
2841 if (error != JDWP::ERR_NONE) {
2842 return error;
2843 }
Sebastien Hertz8009f392014-09-01 17:07:11 +02002844 // TODO: check that the tag is compatible with the actual type of the slot!
Sebastien Hertz8009f392014-09-01 17:07:11 +02002845 switch (tag) {
2846 case JDWP::JT_BOOLEAN:
2847 case JDWP::JT_BYTE:
2848 CHECK_EQ(width, 1U);
Mingyao Yang636b9252015-07-31 16:40:24 -07002849 if (!visitor.SetVReg(m, vreg, static_cast<uint32_t>(value), kIntVReg)) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002850 return FailSetLocalValue(visitor, vreg, tag, static_cast<uint32_t>(value));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002851 }
2852 break;
2853 case JDWP::JT_SHORT:
2854 case JDWP::JT_CHAR:
2855 CHECK_EQ(width, 2U);
Mingyao Yang636b9252015-07-31 16:40:24 -07002856 if (!visitor.SetVReg(m, vreg, static_cast<uint32_t>(value), kIntVReg)) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002857 return FailSetLocalValue(visitor, vreg, tag, static_cast<uint32_t>(value));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002858 }
2859 break;
2860 case JDWP::JT_INT:
2861 CHECK_EQ(width, 4U);
Mingyao Yang636b9252015-07-31 16:40:24 -07002862 if (!visitor.SetVReg(m, vreg, static_cast<uint32_t>(value), kIntVReg)) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002863 return FailSetLocalValue(visitor, vreg, tag, static_cast<uint32_t>(value));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002864 }
2865 break;
2866 case JDWP::JT_FLOAT:
2867 CHECK_EQ(width, 4U);
Mingyao Yang636b9252015-07-31 16:40:24 -07002868 if (!visitor.SetVReg(m, vreg, static_cast<uint32_t>(value), kFloatVReg)) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002869 return FailSetLocalValue(visitor, vreg, tag, static_cast<uint32_t>(value));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002870 }
2871 break;
2872 case JDWP::JT_ARRAY:
2873 case JDWP::JT_CLASS_LOADER:
2874 case JDWP::JT_CLASS_OBJECT:
2875 case JDWP::JT_OBJECT:
2876 case JDWP::JT_STRING:
2877 case JDWP::JT_THREAD:
2878 case JDWP::JT_THREAD_GROUP: {
2879 CHECK_EQ(width, sizeof(JDWP::ObjectId));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002880 mirror::Object* o = gRegistry->Get<mirror::Object*>(static_cast<JDWP::ObjectId>(value),
2881 &error);
2882 if (error != JDWP::ERR_NONE) {
2883 VLOG(jdwp) << tag << " object " << o << " is an invalid object";
2884 return JDWP::ERR_INVALID_OBJECT;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002885 }
Mingyao Yang636b9252015-07-31 16:40:24 -07002886 if (!visitor.SetVReg(m, vreg, static_cast<uint32_t>(reinterpret_cast<uintptr_t>(o)),
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002887 kReferenceVReg)) {
2888 return FailSetLocalValue(visitor, vreg, tag, reinterpret_cast<uintptr_t>(o));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002889 }
2890 break;
2891 }
2892 case JDWP::JT_DOUBLE: {
2893 CHECK_EQ(width, 8U);
Mingyao Yang636b9252015-07-31 16:40:24 -07002894 if (!visitor.SetVRegPair(m, vreg, value, kDoubleLoVReg, kDoubleHiVReg)) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002895 return FailSetLocalValue(visitor, vreg, tag, value);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002896 }
2897 break;
2898 }
2899 case JDWP::JT_LONG: {
2900 CHECK_EQ(width, 8U);
Mingyao Yang636b9252015-07-31 16:40:24 -07002901 if (!visitor.SetVRegPair(m, vreg, value, kLongLoVReg, kLongHiVReg)) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002902 return FailSetLocalValue(visitor, vreg, tag, value);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002903 }
2904 break;
2905 }
2906 default:
2907 LOG(FATAL) << "Unknown tag " << tag;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002908 UNREACHABLE();
Sebastien Hertz8009f392014-09-01 17:07:11 +02002909 }
Mingyao Yang99170c62015-07-06 11:10:37 -07002910
2911 // If we set the local variable in a compiled frame, we need to trigger a deoptimization of
2912 // the stack so we continue execution with the interpreter using the new value(s) of the updated
2913 // local variable(s). To achieve this, we install instrumentation exit stub on each method of the
2914 // thread's stack. The stub will cause the deoptimization to happen.
2915 if (!visitor.IsShadowFrame() && thread->HasDebuggerShadowFrames()) {
2916 Runtime::Current()->GetInstrumentation()->InstrumentThreadStack(thread);
2917 }
2918
Sebastien Hertz8009f392014-09-01 17:07:11 +02002919 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002920}
2921
Mathieu Chartiere401d142015-04-22 13:56:20 -07002922static void SetEventLocation(JDWP::EventLocation* location, ArtMethod* m, uint32_t dex_pc)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002923 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz6995c602014-09-09 12:10:13 +02002924 DCHECK(location != nullptr);
2925 if (m == nullptr) {
2926 memset(location, 0, sizeof(*location));
2927 } else {
Alex Light97e78032017-06-27 17:51:55 -07002928 location->method = m->GetCanonicalMethod(kRuntimePointerSize);
Sebastien Hertz6995c602014-09-09 12:10:13 +02002929 location->dex_pc = (m->IsNative() || m->IsProxyMethod()) ? static_cast<uint32_t>(-1) : dex_pc;
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002930 }
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002931}
2932
Mathieu Chartiere401d142015-04-22 13:56:20 -07002933void Dbg::PostLocationEvent(ArtMethod* m, int dex_pc, mirror::Object* this_object,
Jeff Hao579b0242013-11-18 13:16:49 -08002934 int event_flags, const JValue* return_value) {
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002935 if (!IsDebuggerActive()) {
2936 return;
2937 }
2938 DCHECK(m != nullptr);
2939 DCHECK_EQ(m->IsStatic(), this_object == nullptr);
Sebastien Hertz6995c602014-09-09 12:10:13 +02002940 JDWP::EventLocation location;
2941 SetEventLocation(&location, m, dex_pc);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002942
Sebastien Hertzde48aa62015-05-26 11:53:39 +02002943 // We need to be sure no exception is pending when calling JdwpState::PostLocationEvent.
2944 // This is required to be able to call JNI functions to create JDWP ids. To achieve this,
2945 // we temporarily clear the current thread's exception (if any) and will restore it after
2946 // the call.
2947 // Note: the only way to get a pending exception here is to suspend on a move-exception
2948 // instruction.
2949 Thread* const self = Thread::Current();
2950 StackHandleScope<1> hs(self);
2951 Handle<mirror::Throwable> pending_exception(hs.NewHandle(self->GetException()));
2952 self->ClearException();
Andreas Gampefa4333d2017-02-14 11:10:34 -08002953 if (kIsDebugBuild && pending_exception != nullptr) {
Mathieu Chartier808c7a52017-12-15 11:19:33 -08002954 const Instruction& instr = location.method->DexInstructions().InstructionAt(location.dex_pc);
2955 CHECK_EQ(Instruction::MOVE_EXCEPTION, instr.Opcode());
Sebastien Hertzde48aa62015-05-26 11:53:39 +02002956 }
2957
Sebastien Hertz6995c602014-09-09 12:10:13 +02002958 gJdwpState->PostLocationEvent(&location, this_object, event_flags, return_value);
Sebastien Hertzde48aa62015-05-26 11:53:39 +02002959
Andreas Gampefa4333d2017-02-14 11:10:34 -08002960 if (pending_exception != nullptr) {
Sebastien Hertzde48aa62015-05-26 11:53:39 +02002961 self->SetException(pending_exception.Get());
2962 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002963}
2964
Mathieu Chartiere401d142015-04-22 13:56:20 -07002965void Dbg::PostFieldAccessEvent(ArtMethod* m, int dex_pc,
Mathieu Chartierc7853442015-03-27 14:35:38 -07002966 mirror::Object* this_object, ArtField* f) {
Alex Lighte00ec302017-06-16 08:56:43 -07002967 // TODO We should send events for native methods.
2968 if (!IsDebuggerActive() || m->IsNative()) {
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002969 return;
2970 }
2971 DCHECK(m != nullptr);
2972 DCHECK(f != nullptr);
Sebastien Hertz6995c602014-09-09 12:10:13 +02002973 JDWP::EventLocation location;
2974 SetEventLocation(&location, m, dex_pc);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002975
Sebastien Hertz6995c602014-09-09 12:10:13 +02002976 gJdwpState->PostFieldEvent(&location, f, this_object, nullptr, false);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002977}
2978
Mathieu Chartiere401d142015-04-22 13:56:20 -07002979void Dbg::PostFieldModificationEvent(ArtMethod* m, int dex_pc,
Mathieu Chartierc7853442015-03-27 14:35:38 -07002980 mirror::Object* this_object, ArtField* f,
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002981 const JValue* field_value) {
Alex Lighte00ec302017-06-16 08:56:43 -07002982 // TODO We should send events for native methods.
2983 if (!IsDebuggerActive() || m->IsNative()) {
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002984 return;
2985 }
2986 DCHECK(m != nullptr);
2987 DCHECK(f != nullptr);
2988 DCHECK(field_value != nullptr);
Sebastien Hertz6995c602014-09-09 12:10:13 +02002989 JDWP::EventLocation location;
2990 SetEventLocation(&location, m, dex_pc);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002991
Sebastien Hertz6995c602014-09-09 12:10:13 +02002992 gJdwpState->PostFieldEvent(&location, f, this_object, field_value, true);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002993}
2994
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002995/**
2996 * Finds the location where this exception will be caught. We search until we reach the top
2997 * frame, in which case this exception is considered uncaught.
2998 */
2999class CatchLocationFinder : public StackVisitor {
3000 public:
3001 CatchLocationFinder(Thread* self, const Handle<mirror::Throwable>& exception, Context* context)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003002 REQUIRES_SHARED(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01003003 : StackVisitor(self, context, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003004 exception_(exception),
3005 handle_scope_(self),
3006 this_at_throw_(handle_scope_.NewHandle<mirror::Object>(nullptr)),
Mathieu Chartiere401d142015-04-22 13:56:20 -07003007 catch_method_(nullptr),
3008 throw_method_(nullptr),
Andreas Gampee2abbc62017-09-15 11:59:26 -07003009 catch_dex_pc_(dex::kDexNoIndex),
3010 throw_dex_pc_(dex::kDexNoIndex) {
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003011 }
3012
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01003013 bool VisitFrame() override REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003014 ArtMethod* method = GetMethod();
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003015 DCHECK(method != nullptr);
3016 if (method->IsRuntimeMethod()) {
3017 // Ignore callee save method.
3018 DCHECK(method->IsCalleeSaveMethod());
3019 return true;
3020 }
3021
3022 uint32_t dex_pc = GetDexPc();
Mathieu Chartiere401d142015-04-22 13:56:20 -07003023 if (throw_method_ == nullptr) {
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003024 // First Java method found. It is either the method that threw the exception,
3025 // or the Java native method that is reporting an exception thrown by
3026 // native code.
3027 this_at_throw_.Assign(GetThisObject());
Mathieu Chartiere401d142015-04-22 13:56:20 -07003028 throw_method_ = method;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003029 throw_dex_pc_ = dex_pc;
3030 }
3031
Andreas Gampee2abbc62017-09-15 11:59:26 -07003032 if (dex_pc != dex::kDexNoIndex) {
Sebastien Hertz26f72862015-09-15 09:52:07 +02003033 StackHandleScope<1> hs(GetThread());
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003034 uint32_t found_dex_pc;
3035 Handle<mirror::Class> exception_class(hs.NewHandle(exception_->GetClass()));
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003036 bool unused_clear_exception;
Mathieu Chartiere401d142015-04-22 13:56:20 -07003037 found_dex_pc = method->FindCatchBlock(exception_class, dex_pc, &unused_clear_exception);
Andreas Gampee2abbc62017-09-15 11:59:26 -07003038 if (found_dex_pc != dex::kDexNoIndex) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003039 catch_method_ = method;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003040 catch_dex_pc_ = found_dex_pc;
3041 return false; // End stack walk.
3042 }
3043 }
3044 return true; // Continue stack walk.
3045 }
3046
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003047 ArtMethod* GetCatchMethod() REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003048 return catch_method_;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003049 }
3050
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003051 ArtMethod* GetThrowMethod() REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003052 return throw_method_;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003053 }
3054
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003055 mirror::Object* GetThisAtThrow() REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003056 return this_at_throw_.Get();
3057 }
3058
3059 uint32_t GetCatchDexPc() const {
3060 return catch_dex_pc_;
3061 }
3062
3063 uint32_t GetThrowDexPc() const {
3064 return throw_dex_pc_;
3065 }
3066
3067 private:
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003068 const Handle<mirror::Throwable>& exception_;
Mathieu Chartiere401d142015-04-22 13:56:20 -07003069 StackHandleScope<1> handle_scope_;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003070 MutableHandle<mirror::Object> this_at_throw_;
Mathieu Chartiere401d142015-04-22 13:56:20 -07003071 ArtMethod* catch_method_;
3072 ArtMethod* throw_method_;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003073 uint32_t catch_dex_pc_;
3074 uint32_t throw_dex_pc_;
3075
3076 DISALLOW_COPY_AND_ASSIGN(CatchLocationFinder);
3077};
3078
3079void Dbg::PostException(mirror::Throwable* exception_object) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07003080 if (!IsDebuggerActive()) {
Ian Rogers0ad5bb82011-12-07 10:16:32 -08003081 return;
3082 }
Sebastien Hertz261bc042015-04-08 09:36:07 +02003083 Thread* const self = Thread::Current();
3084 StackHandleScope<1> handle_scope(self);
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003085 Handle<mirror::Throwable> h_exception(handle_scope.NewHandle(exception_object));
3086 std::unique_ptr<Context> context(Context::Create());
Sebastien Hertz261bc042015-04-08 09:36:07 +02003087 CatchLocationFinder clf(self, h_exception, context.get());
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003088 clf.WalkStack(/* include_transitions */ false);
Sebastien Hertz6995c602014-09-09 12:10:13 +02003089 JDWP::EventLocation exception_throw_location;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003090 SetEventLocation(&exception_throw_location, clf.GetThrowMethod(), clf.GetThrowDexPc());
Sebastien Hertz6995c602014-09-09 12:10:13 +02003091 JDWP::EventLocation exception_catch_location;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003092 SetEventLocation(&exception_catch_location, clf.GetCatchMethod(), clf.GetCatchDexPc());
Elliott Hughes4740cdf2011-12-07 14:07:12 -08003093
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003094 gJdwpState->PostException(&exception_throw_location, h_exception.Get(), &exception_catch_location,
3095 clf.GetThisAtThrow());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003096}
3097
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003098void Dbg::PostClassPrepare(mirror::Class* c) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07003099 if (!IsDebuggerActive()) {
Elliott Hughes4740cdf2011-12-07 14:07:12 -08003100 return;
3101 }
Sebastien Hertz6995c602014-09-09 12:10:13 +02003102 gJdwpState->PostClassPrepare(c);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003103}
3104
Ian Rogers62d6c772013-02-27 08:32:07 -08003105void Dbg::UpdateDebugger(Thread* thread, mirror::Object* this_object,
Mathieu Chartiere401d142015-04-22 13:56:20 -07003106 ArtMethod* m, uint32_t dex_pc,
Sebastien Hertz8379b222014-02-24 17:38:15 +01003107 int event_flags, const JValue* return_value) {
Ian Rogers62d6c772013-02-27 08:32:07 -08003108 if (!IsDebuggerActive() || dex_pc == static_cast<uint32_t>(-2) /* fake method exit */) {
Elliott Hughes2aa2e392012-02-17 17:15:43 -08003109 return;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003110 }
3111
Elliott Hughes86964332012-02-15 19:37:42 -08003112 if (IsBreakpoint(m, dex_pc)) {
3113 event_flags |= kBreakpoint;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003114 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003115
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003116 // If the debugger is single-stepping one of our threads, check to
3117 // see if we're that thread and we've reached a step point.
3118 const SingleStepControl* single_step_control = thread->GetSingleStepControl();
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003119 if (single_step_control != nullptr) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003120 CHECK(!m->IsNative());
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003121 if (single_step_control->GetStepDepth() == JDWP::SD_INTO) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003122 // Step into method calls. We break when the line number
3123 // or method pointer changes. If we're in SS_MIN mode, we
3124 // always stop.
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003125 if (single_step_control->GetMethod() != m) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003126 event_flags |= kSingleStep;
3127 VLOG(jdwp) << "SS new method";
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003128 } else if (single_step_control->GetStepSize() == JDWP::SS_MIN) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003129 event_flags |= kSingleStep;
3130 VLOG(jdwp) << "SS new instruction";
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003131 } else if (single_step_control->ContainsDexPc(dex_pc)) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003132 event_flags |= kSingleStep;
3133 VLOG(jdwp) << "SS new line";
3134 }
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003135 } else if (single_step_control->GetStepDepth() == JDWP::SD_OVER) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003136 // Step over method calls. We break when the line number is
3137 // different and the frame depth is <= the original frame
3138 // depth. (We can't just compare on the method, because we
3139 // might get unrolled past it by an exception, and it's tricky
3140 // to identify recursion.)
3141
3142 int stack_depth = GetStackDepth(thread);
3143
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003144 if (stack_depth < single_step_control->GetStackDepth()) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003145 // Popped up one or more frames, always trigger.
3146 event_flags |= kSingleStep;
3147 VLOG(jdwp) << "SS method pop";
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003148 } else if (stack_depth == single_step_control->GetStackDepth()) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003149 // Same depth, see if we moved.
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003150 if (single_step_control->GetStepSize() == JDWP::SS_MIN) {
Elliott Hughes86964332012-02-15 19:37:42 -08003151 event_flags |= kSingleStep;
3152 VLOG(jdwp) << "SS new instruction";
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003153 } else if (single_step_control->ContainsDexPc(dex_pc)) {
Elliott Hughes2435a572012-02-17 16:07:41 -08003154 event_flags |= kSingleStep;
3155 VLOG(jdwp) << "SS new line";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003156 }
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003157 }
3158 } else {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003159 CHECK_EQ(single_step_control->GetStepDepth(), JDWP::SD_OUT);
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003160 // Return from the current method. We break when the frame
3161 // depth pops up.
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003162
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003163 // This differs from the "method exit" break in that it stops
3164 // with the PC at the next instruction in the returned-to
3165 // function, rather than the end of the returning function.
Elliott Hughes86964332012-02-15 19:37:42 -08003166
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003167 int stack_depth = GetStackDepth(thread);
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003168 if (stack_depth < single_step_control->GetStackDepth()) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003169 event_flags |= kSingleStep;
3170 VLOG(jdwp) << "SS method pop";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003171 }
3172 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003173 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003174
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003175 // If there's something interesting going on, see if it matches one
3176 // of the debugger filters.
3177 if (event_flags != 0) {
Sebastien Hertz8379b222014-02-24 17:38:15 +01003178 Dbg::PostLocationEvent(m, dex_pc, this_object, event_flags, return_value);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003179 }
3180}
3181
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003182size_t* Dbg::GetReferenceCounterForEvent(uint32_t instrumentation_event) {
3183 switch (instrumentation_event) {
3184 case instrumentation::Instrumentation::kMethodEntered:
3185 return &method_enter_event_ref_count_;
3186 case instrumentation::Instrumentation::kMethodExited:
3187 return &method_exit_event_ref_count_;
3188 case instrumentation::Instrumentation::kDexPcMoved:
3189 return &dex_pc_change_event_ref_count_;
3190 case instrumentation::Instrumentation::kFieldRead:
3191 return &field_read_event_ref_count_;
3192 case instrumentation::Instrumentation::kFieldWritten:
3193 return &field_write_event_ref_count_;
Alex Light6e1607e2017-08-23 10:06:18 -07003194 case instrumentation::Instrumentation::kExceptionThrown:
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003195 return &exception_catch_event_ref_count_;
3196 default:
3197 return nullptr;
3198 }
3199}
3200
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003201// Process request while all mutator threads are suspended.
3202void Dbg::ProcessDeoptimizationRequest(const DeoptimizationRequest& request) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003203 instrumentation::Instrumentation* instrumentation = Runtime::Current()->GetInstrumentation();
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003204 switch (request.GetKind()) {
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003205 case DeoptimizationRequest::kNothing:
3206 LOG(WARNING) << "Ignoring empty deoptimization request.";
3207 break;
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003208 case DeoptimizationRequest::kRegisterForEvent:
3209 VLOG(jdwp) << StringPrintf("Add debugger as listener for instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003210 request.InstrumentationEvent());
3211 instrumentation->AddListener(&gDebugInstrumentationListener, request.InstrumentationEvent());
3212 instrumentation_events_ |= request.InstrumentationEvent();
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003213 break;
3214 case DeoptimizationRequest::kUnregisterForEvent:
3215 VLOG(jdwp) << StringPrintf("Remove debugger as listener for instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003216 request.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003217 instrumentation->RemoveListener(&gDebugInstrumentationListener,
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003218 request.InstrumentationEvent());
3219 instrumentation_events_ &= ~request.InstrumentationEvent();
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003220 break;
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003221 case DeoptimizationRequest::kFullDeoptimization:
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003222 VLOG(jdwp) << "Deoptimize the world ...";
Sebastien Hertz0462c4c2015-04-01 16:34:17 +02003223 instrumentation->DeoptimizeEverything(kDbgInstrumentationKey);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003224 VLOG(jdwp) << "Deoptimize the world DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003225 break;
3226 case DeoptimizationRequest::kFullUndeoptimization:
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003227 VLOG(jdwp) << "Undeoptimize the world ...";
Sebastien Hertz0462c4c2015-04-01 16:34:17 +02003228 instrumentation->UndeoptimizeEverything(kDbgInstrumentationKey);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003229 VLOG(jdwp) << "Undeoptimize the world DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003230 break;
3231 case DeoptimizationRequest::kSelectiveDeoptimization:
David Sehr709b0702016-10-13 09:12:37 -07003232 VLOG(jdwp) << "Deoptimize method " << ArtMethod::PrettyMethod(request.Method()) << " ...";
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003233 instrumentation->Deoptimize(request.Method());
David Sehr709b0702016-10-13 09:12:37 -07003234 VLOG(jdwp) << "Deoptimize method " << ArtMethod::PrettyMethod(request.Method()) << " DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003235 break;
3236 case DeoptimizationRequest::kSelectiveUndeoptimization:
David Sehr709b0702016-10-13 09:12:37 -07003237 VLOG(jdwp) << "Undeoptimize method " << ArtMethod::PrettyMethod(request.Method()) << " ...";
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003238 instrumentation->Undeoptimize(request.Method());
David Sehr709b0702016-10-13 09:12:37 -07003239 VLOG(jdwp) << "Undeoptimize method " << ArtMethod::PrettyMethod(request.Method()) << " DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003240 break;
3241 default:
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003242 LOG(FATAL) << "Unsupported deoptimization request kind " << request.GetKind();
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003243 break;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003244 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003245}
3246
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003247void Dbg::RequestDeoptimization(const DeoptimizationRequest& req) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003248 if (req.GetKind() == DeoptimizationRequest::kNothing) {
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003249 // Nothing to do.
3250 return;
3251 }
Brian Carlstrom306db812014-09-05 13:01:41 -07003252 MutexLock mu(Thread::Current(), *Locks::deoptimization_lock_);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003253 RequestDeoptimizationLocked(req);
3254}
3255
3256void Dbg::RequestDeoptimizationLocked(const DeoptimizationRequest& req) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003257 switch (req.GetKind()) {
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003258 case DeoptimizationRequest::kRegisterForEvent: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003259 DCHECK_NE(req.InstrumentationEvent(), 0u);
3260 size_t* counter = GetReferenceCounterForEvent(req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003261 CHECK(counter != nullptr) << StringPrintf("No counter for instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003262 req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003263 if (*counter == 0) {
Sebastien Hertz7d2ae432014-05-15 11:26:34 +02003264 VLOG(jdwp) << StringPrintf("Queue request #%zd to start listening to instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003265 deoptimization_requests_.size(), req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003266 deoptimization_requests_.push_back(req);
3267 }
3268 *counter = *counter + 1;
3269 break;
3270 }
3271 case DeoptimizationRequest::kUnregisterForEvent: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003272 DCHECK_NE(req.InstrumentationEvent(), 0u);
3273 size_t* counter = GetReferenceCounterForEvent(req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003274 CHECK(counter != nullptr) << StringPrintf("No counter for instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003275 req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003276 *counter = *counter - 1;
3277 if (*counter == 0) {
Sebastien Hertz7d2ae432014-05-15 11:26:34 +02003278 VLOG(jdwp) << StringPrintf("Queue request #%zd to stop listening to instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003279 deoptimization_requests_.size(), req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003280 deoptimization_requests_.push_back(req);
3281 }
3282 break;
3283 }
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003284 case DeoptimizationRequest::kFullDeoptimization: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003285 DCHECK(req.Method() == nullptr);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003286 if (full_deoptimization_event_count_ == 0) {
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003287 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
3288 << " for full deoptimization";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003289 deoptimization_requests_.push_back(req);
3290 }
3291 ++full_deoptimization_event_count_;
3292 break;
3293 }
3294 case DeoptimizationRequest::kFullUndeoptimization: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003295 DCHECK(req.Method() == nullptr);
Sebastien Hertze713d932014-05-15 10:48:53 +02003296 DCHECK_GT(full_deoptimization_event_count_, 0U);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003297 --full_deoptimization_event_count_;
3298 if (full_deoptimization_event_count_ == 0) {
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003299 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
3300 << " for full undeoptimization";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003301 deoptimization_requests_.push_back(req);
3302 }
3303 break;
3304 }
3305 case DeoptimizationRequest::kSelectiveDeoptimization: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003306 DCHECK(req.Method() != nullptr);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003307 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
David Sehr709b0702016-10-13 09:12:37 -07003308 << " for deoptimization of " << req.Method()->PrettyMethod();
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003309 deoptimization_requests_.push_back(req);
3310 break;
3311 }
3312 case DeoptimizationRequest::kSelectiveUndeoptimization: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003313 DCHECK(req.Method() != nullptr);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003314 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
David Sehr709b0702016-10-13 09:12:37 -07003315 << " for undeoptimization of " << req.Method()->PrettyMethod();
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003316 deoptimization_requests_.push_back(req);
3317 break;
3318 }
3319 default: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003320 LOG(FATAL) << "Unknown deoptimization request kind " << req.GetKind();
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003321 break;
3322 }
3323 }
3324}
3325
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003326void Dbg::ManageDeoptimization() {
3327 Thread* const self = Thread::Current();
3328 {
3329 // Avoid suspend/resume if there is no pending request.
Brian Carlstrom306db812014-09-05 13:01:41 -07003330 MutexLock mu(self, *Locks::deoptimization_lock_);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003331 if (deoptimization_requests_.empty()) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003332 return;
3333 }
3334 }
3335 CHECK_EQ(self->GetState(), kRunnable);
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07003336 ScopedThreadSuspension sts(self, kWaitingForDeoptimization);
Mathieu Chartieraa516822015-10-02 15:53:37 -07003337 // Required for ProcessDeoptimizationRequest.
3338 gc::ScopedGCCriticalSection gcs(self,
3339 gc::kGcCauseInstrumentation,
3340 gc::kCollectorTypeInstrumentation);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003341 // We need to suspend mutator threads first.
Mathieu Chartier4f55e222015-09-04 13:26:21 -07003342 ScopedSuspendAll ssa(__FUNCTION__);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003343 const ThreadState old_state = self->SetStateUnsafe(kRunnable);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003344 {
Brian Carlstrom306db812014-09-05 13:01:41 -07003345 MutexLock mu(self, *Locks::deoptimization_lock_);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003346 size_t req_index = 0;
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003347 for (DeoptimizationRequest& request : deoptimization_requests_) {
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003348 VLOG(jdwp) << "Process deoptimization request #" << req_index++;
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003349 ProcessDeoptimizationRequest(request);
3350 }
3351 deoptimization_requests_.clear();
3352 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003353 CHECK_EQ(self->SetStateUnsafe(old_state), kRunnable);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003354}
3355
Mathieu Chartiere401d142015-04-22 13:56:20 -07003356static const Breakpoint* FindFirstBreakpointForMethod(ArtMethod* m)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003357 REQUIRES_SHARED(Locks::mutator_lock_, Locks::breakpoint_lock_) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003358 for (Breakpoint& breakpoint : gBreakpoints) {
Alex Light6c8467f2015-11-20 15:03:26 -08003359 if (breakpoint.IsInMethod(m)) {
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003360 return &breakpoint;
3361 }
3362 }
3363 return nullptr;
3364}
3365
Mathieu Chartiere401d142015-04-22 13:56:20 -07003366bool Dbg::MethodHasAnyBreakpoints(ArtMethod* method) {
Mathieu Chartierd8565452015-03-26 09:41:50 -07003367 ReaderMutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
3368 return FindFirstBreakpointForMethod(method) != nullptr;
3369}
3370
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003371// Sanity checks all existing breakpoints on the same method.
Mathieu Chartiere401d142015-04-22 13:56:20 -07003372static void SanityCheckExistingBreakpoints(ArtMethod* m,
Sebastien Hertzf3928792014-11-17 19:00:37 +01003373 DeoptimizationRequest::Kind deoptimization_kind)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003374 REQUIRES_SHARED(Locks::mutator_lock_, Locks::breakpoint_lock_) {
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003375 for (const Breakpoint& breakpoint : gBreakpoints) {
Alex Light6c8467f2015-11-20 15:03:26 -08003376 if (breakpoint.IsInMethod(m)) {
Sebastien Hertzf3928792014-11-17 19:00:37 +01003377 CHECK_EQ(deoptimization_kind, breakpoint.GetDeoptimizationKind());
3378 }
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003379 }
Sebastien Hertzf3928792014-11-17 19:00:37 +01003380 instrumentation::Instrumentation* instrumentation = Runtime::Current()->GetInstrumentation();
3381 if (deoptimization_kind == DeoptimizationRequest::kFullDeoptimization) {
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003382 // We should have deoptimized everything but not "selectively" deoptimized this method.
Sebastien Hertzf3928792014-11-17 19:00:37 +01003383 CHECK(instrumentation->AreAllMethodsDeoptimized());
3384 CHECK(!instrumentation->IsDeoptimized(m));
3385 } else if (deoptimization_kind == DeoptimizationRequest::kSelectiveDeoptimization) {
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003386 // We should have "selectively" deoptimized this method.
3387 // Note: while we have not deoptimized everything for this method, we may have done it for
3388 // another event.
Sebastien Hertzf3928792014-11-17 19:00:37 +01003389 CHECK(instrumentation->IsDeoptimized(m));
3390 } else {
3391 // This method does not require deoptimization.
3392 CHECK_EQ(deoptimization_kind, DeoptimizationRequest::kNothing);
3393 CHECK(!instrumentation->IsDeoptimized(m));
3394 }
3395}
3396
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003397// Returns the deoptimization kind required to set a breakpoint in a method.
3398// If a breakpoint has already been set, we also return the first breakpoint
3399// through the given 'existing_brkpt' pointer.
Sebastien Hertzf3928792014-11-17 19:00:37 +01003400static DeoptimizationRequest::Kind GetRequiredDeoptimizationKind(Thread* self,
Mathieu Chartiere401d142015-04-22 13:56:20 -07003401 ArtMethod* m,
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003402 const Breakpoint** existing_brkpt)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003403 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertzf3928792014-11-17 19:00:37 +01003404 if (!Dbg::RequiresDeoptimization()) {
3405 // We already run in interpreter-only mode so we don't need to deoptimize anything.
3406 VLOG(jdwp) << "No need for deoptimization when fully running with interpreter for method "
David Sehr709b0702016-10-13 09:12:37 -07003407 << ArtMethod::PrettyMethod(m);
Sebastien Hertzf3928792014-11-17 19:00:37 +01003408 return DeoptimizationRequest::kNothing;
3409 }
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003410 const Breakpoint* first_breakpoint;
Sebastien Hertzf3928792014-11-17 19:00:37 +01003411 {
3412 ReaderMutexLock mu(self, *Locks::breakpoint_lock_);
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003413 first_breakpoint = FindFirstBreakpointForMethod(m);
3414 *existing_brkpt = first_breakpoint;
Sebastien Hertzf3928792014-11-17 19:00:37 +01003415 }
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003416
3417 if (first_breakpoint == nullptr) {
Nicolas Geoffray6300fd72016-03-18 09:40:17 +00003418 // There is no breakpoint on this method yet: we need to deoptimize. If this method is default,
3419 // we deoptimize everything; otherwise we deoptimize only this method. We
Alex Light6c8467f2015-11-20 15:03:26 -08003420 // deoptimize with defaults because we do not know everywhere they are used. It is possible some
Nicolas Geoffray6300fd72016-03-18 09:40:17 +00003421 // of the copies could be missed.
Alex Light6c8467f2015-11-20 15:03:26 -08003422 // TODO Deoptimizing on default methods might not be necessary in all cases.
Nicolas Geoffray6300fd72016-03-18 09:40:17 +00003423 bool need_full_deoptimization = m->IsDefault();
Sebastien Hertzf3928792014-11-17 19:00:37 +01003424 if (need_full_deoptimization) {
Nicolas Geoffray6300fd72016-03-18 09:40:17 +00003425 VLOG(jdwp) << "Need full deoptimization because of copying of method "
David Sehr709b0702016-10-13 09:12:37 -07003426 << ArtMethod::PrettyMethod(m);
Sebastien Hertzf3928792014-11-17 19:00:37 +01003427 return DeoptimizationRequest::kFullDeoptimization;
3428 } else {
3429 // We don't need to deoptimize if the method has not been compiled.
Nicolas Geoffraya5891e82015-11-06 14:18:27 +00003430 const bool is_compiled = m->HasAnyCompiledCode();
Sebastien Hertzf3928792014-11-17 19:00:37 +01003431 if (is_compiled) {
David Sehr709b0702016-10-13 09:12:37 -07003432 VLOG(jdwp) << "Need selective deoptimization for compiled method "
3433 << ArtMethod::PrettyMethod(m);
Nicolas Geoffray6300fd72016-03-18 09:40:17 +00003434 return DeoptimizationRequest::kSelectiveDeoptimization;
Sebastien Hertzf3928792014-11-17 19:00:37 +01003435 } else {
3436 // Method is not compiled: we don't need to deoptimize.
David Sehr709b0702016-10-13 09:12:37 -07003437 VLOG(jdwp) << "No need for deoptimization for non-compiled method "
3438 << ArtMethod::PrettyMethod(m);
Sebastien Hertzf3928792014-11-17 19:00:37 +01003439 return DeoptimizationRequest::kNothing;
3440 }
3441 }
3442 } else {
3443 // There is at least one breakpoint for this method: we don't need to deoptimize.
3444 // Let's check that all breakpoints are configured the same way for deoptimization.
3445 VLOG(jdwp) << "Breakpoint already set: no deoptimization is required";
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003446 DeoptimizationRequest::Kind deoptimization_kind = first_breakpoint->GetDeoptimizationKind();
Sebastien Hertzf3928792014-11-17 19:00:37 +01003447 if (kIsDebugBuild) {
3448 ReaderMutexLock mu(self, *Locks::breakpoint_lock_);
3449 SanityCheckExistingBreakpoints(m, deoptimization_kind);
3450 }
3451 return DeoptimizationRequest::kNothing;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003452 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003453}
3454
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003455// Installs a breakpoint at the specified location. Also indicates through the deoptimization
3456// request if we need to deoptimize.
3457void Dbg::WatchLocation(const JDWP::JdwpLocation* location, DeoptimizationRequest* req) {
3458 Thread* const self = Thread::Current();
Mathieu Chartiere401d142015-04-22 13:56:20 -07003459 ArtMethod* m = FromMethodId(location->method_id);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003460 DCHECK(m != nullptr) << "No method for method id " << location->method_id;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003461
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003462 const Breakpoint* existing_breakpoint = nullptr;
3463 const DeoptimizationRequest::Kind deoptimization_kind =
3464 GetRequiredDeoptimizationKind(self, m, &existing_breakpoint);
Sebastien Hertzf3928792014-11-17 19:00:37 +01003465 req->SetKind(deoptimization_kind);
3466 if (deoptimization_kind == DeoptimizationRequest::kSelectiveDeoptimization) {
3467 req->SetMethod(m);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003468 } else {
Sebastien Hertzf3928792014-11-17 19:00:37 +01003469 CHECK(deoptimization_kind == DeoptimizationRequest::kNothing ||
3470 deoptimization_kind == DeoptimizationRequest::kFullDeoptimization);
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003471 req->SetMethod(nullptr);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003472 }
3473
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003474 {
3475 WriterMutexLock mu(self, *Locks::breakpoint_lock_);
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003476 // If there is at least one existing breakpoint on the same method, the new breakpoint
3477 // must have the same deoptimization kind than the existing breakpoint(s).
3478 DeoptimizationRequest::Kind breakpoint_deoptimization_kind;
3479 if (existing_breakpoint != nullptr) {
3480 breakpoint_deoptimization_kind = existing_breakpoint->GetDeoptimizationKind();
3481 } else {
3482 breakpoint_deoptimization_kind = deoptimization_kind;
3483 }
3484 gBreakpoints.push_back(Breakpoint(m, location->dex_pc, breakpoint_deoptimization_kind));
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003485 VLOG(jdwp) << "Set breakpoint #" << (gBreakpoints.size() - 1) << ": "
3486 << gBreakpoints[gBreakpoints.size() - 1];
3487 }
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003488}
3489
3490// Uninstalls a breakpoint at the specified location. Also indicates through the deoptimization
3491// request if we need to undeoptimize.
3492void Dbg::UnwatchLocation(const JDWP::JdwpLocation* location, DeoptimizationRequest* req) {
Sebastien Hertzed2be172014-08-19 15:33:43 +02003493 WriterMutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003494 ArtMethod* m = FromMethodId(location->method_id);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003495 DCHECK(m != nullptr) << "No method for method id " << location->method_id;
Sebastien Hertzf3928792014-11-17 19:00:37 +01003496 DeoptimizationRequest::Kind deoptimization_kind = DeoptimizationRequest::kNothing;
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003497 for (size_t i = 0, e = gBreakpoints.size(); i < e; ++i) {
Alex Light6c8467f2015-11-20 15:03:26 -08003498 if (gBreakpoints[i].DexPc() == location->dex_pc && gBreakpoints[i].IsInMethod(m)) {
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003499 VLOG(jdwp) << "Removed breakpoint #" << i << ": " << gBreakpoints[i];
Sebastien Hertzf3928792014-11-17 19:00:37 +01003500 deoptimization_kind = gBreakpoints[i].GetDeoptimizationKind();
3501 DCHECK_EQ(deoptimization_kind == DeoptimizationRequest::kSelectiveDeoptimization,
3502 Runtime::Current()->GetInstrumentation()->IsDeoptimized(m));
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003503 gBreakpoints.erase(gBreakpoints.begin() + i);
3504 break;
3505 }
3506 }
3507 const Breakpoint* const existing_breakpoint = FindFirstBreakpointForMethod(m);
3508 if (existing_breakpoint == nullptr) {
3509 // There is no more breakpoint on this method: we need to undeoptimize.
Sebastien Hertzf3928792014-11-17 19:00:37 +01003510 if (deoptimization_kind == DeoptimizationRequest::kFullDeoptimization) {
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003511 // This method required full deoptimization: we need to undeoptimize everything.
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003512 req->SetKind(DeoptimizationRequest::kFullUndeoptimization);
3513 req->SetMethod(nullptr);
Sebastien Hertzf3928792014-11-17 19:00:37 +01003514 } else if (deoptimization_kind == DeoptimizationRequest::kSelectiveDeoptimization) {
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003515 // This method required selective deoptimization: we need to undeoptimize only that method.
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003516 req->SetKind(DeoptimizationRequest::kSelectiveUndeoptimization);
3517 req->SetMethod(m);
Sebastien Hertzf3928792014-11-17 19:00:37 +01003518 } else {
3519 // This method had no need for deoptimization: do nothing.
3520 CHECK_EQ(deoptimization_kind, DeoptimizationRequest::kNothing);
3521 req->SetKind(DeoptimizationRequest::kNothing);
3522 req->SetMethod(nullptr);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003523 }
3524 } else {
3525 // There is at least one breakpoint for this method: we don't need to undeoptimize.
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003526 req->SetKind(DeoptimizationRequest::kNothing);
3527 req->SetMethod(nullptr);
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003528 if (kIsDebugBuild) {
Sebastien Hertzf3928792014-11-17 19:00:37 +01003529 SanityCheckExistingBreakpoints(m, deoptimization_kind);
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003530 }
Elliott Hughes86964332012-02-15 19:37:42 -08003531 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003532}
3533
Mathieu Chartiere401d142015-04-22 13:56:20 -07003534bool Dbg::IsForcedInterpreterNeededForCallingImpl(Thread* thread, ArtMethod* m) {
Daniel Mihalyieb076692014-08-22 17:33:31 +02003535 const SingleStepControl* const ssc = thread->GetSingleStepControl();
3536 if (ssc == nullptr) {
3537 // If we are not single-stepping, then we don't have to force interpreter.
3538 return false;
3539 }
3540 if (Runtime::Current()->GetInstrumentation()->InterpretOnly()) {
3541 // If we are in interpreter only mode, then we don't have to force interpreter.
3542 return false;
3543 }
3544
3545 if (!m->IsNative() && !m->IsProxyMethod()) {
3546 // If we want to step into a method, then we have to force interpreter on that call.
3547 if (ssc->GetStepDepth() == JDWP::SD_INTO) {
3548 return true;
3549 }
3550 }
3551 return false;
3552}
3553
Mathieu Chartiere401d142015-04-22 13:56:20 -07003554bool Dbg::IsForcedInterpreterNeededForResolutionImpl(Thread* thread, ArtMethod* m) {
Daniel Mihalyieb076692014-08-22 17:33:31 +02003555 instrumentation::Instrumentation* const instrumentation =
3556 Runtime::Current()->GetInstrumentation();
3557 // If we are in interpreter only mode, then we don't have to force interpreter.
3558 if (instrumentation->InterpretOnly()) {
3559 return false;
3560 }
3561 // We can only interpret pure Java method.
3562 if (m->IsNative() || m->IsProxyMethod()) {
3563 return false;
3564 }
3565 const SingleStepControl* const ssc = thread->GetSingleStepControl();
3566 if (ssc != nullptr) {
3567 // If we want to step into a method, then we have to force interpreter on that call.
3568 if (ssc->GetStepDepth() == JDWP::SD_INTO) {
3569 return true;
3570 }
3571 // If we are stepping out from a static initializer, by issuing a step
3572 // in or step over, that was implicitly invoked by calling a static method,
3573 // then we need to step into that method. Having a lower stack depth than
3574 // the one the single step control has indicates that the step originates
3575 // from the static initializer.
3576 if (ssc->GetStepDepth() != JDWP::SD_OUT &&
3577 ssc->GetStackDepth() > GetStackDepth(thread)) {
3578 return true;
3579 }
3580 }
3581 // There are cases where we have to force interpreter on deoptimized methods,
3582 // because in some cases the call will not be performed by invoking an entry
3583 // point that has been replaced by the deoptimization, but instead by directly
3584 // invoking the compiled code of the method, for example.
3585 return instrumentation->IsDeoptimized(m);
3586}
3587
Mathieu Chartiere401d142015-04-22 13:56:20 -07003588bool Dbg::IsForcedInstrumentationNeededForResolutionImpl(Thread* thread, ArtMethod* m) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07003589 // The upcall can be null and in that case we don't need to do anything.
Daniel Mihalyieb076692014-08-22 17:33:31 +02003590 if (m == nullptr) {
3591 return false;
3592 }
3593 instrumentation::Instrumentation* const instrumentation =
3594 Runtime::Current()->GetInstrumentation();
3595 // If we are in interpreter only mode, then we don't have to force interpreter.
3596 if (instrumentation->InterpretOnly()) {
3597 return false;
3598 }
3599 // We can only interpret pure Java method.
3600 if (m->IsNative() || m->IsProxyMethod()) {
3601 return false;
3602 }
3603 const SingleStepControl* const ssc = thread->GetSingleStepControl();
3604 if (ssc != nullptr) {
3605 // If we are stepping out from a static initializer, by issuing a step
3606 // out, that was implicitly invoked by calling a static method, then we
3607 // need to step into the caller of that method. Having a lower stack
3608 // depth than the one the single step control has indicates that the
3609 // step originates from the static initializer.
3610 if (ssc->GetStepDepth() == JDWP::SD_OUT &&
3611 ssc->GetStackDepth() > GetStackDepth(thread)) {
3612 return true;
3613 }
3614 }
3615 // If we are returning from a static intializer, that was implicitly
3616 // invoked by calling a static method and the caller is deoptimized,
3617 // then we have to deoptimize the stack without forcing interpreter
3618 // on the static method that was called originally. This problem can
3619 // be solved easily by forcing instrumentation on the called method,
3620 // because the instrumentation exit hook will recognise the need of
3621 // stack deoptimization by calling IsForcedInterpreterNeededForUpcall.
3622 return instrumentation->IsDeoptimized(m);
3623}
3624
Mathieu Chartiere401d142015-04-22 13:56:20 -07003625bool Dbg::IsForcedInterpreterNeededForUpcallImpl(Thread* thread, ArtMethod* m) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07003626 // The upcall can be null and in that case we don't need to do anything.
Daniel Mihalyieb076692014-08-22 17:33:31 +02003627 if (m == nullptr) {
3628 return false;
3629 }
3630 instrumentation::Instrumentation* const instrumentation =
3631 Runtime::Current()->GetInstrumentation();
3632 // If we are in interpreter only mode, then we don't have to force interpreter.
3633 if (instrumentation->InterpretOnly()) {
3634 return false;
3635 }
3636 // We can only interpret pure Java method.
3637 if (m->IsNative() || m->IsProxyMethod()) {
3638 return false;
3639 }
3640 const SingleStepControl* const ssc = thread->GetSingleStepControl();
3641 if (ssc != nullptr) {
3642 // The debugger is not interested in what is happening under the level
3643 // of the step, thus we only force interpreter when we are not below of
3644 // the step.
3645 if (ssc->GetStackDepth() >= GetStackDepth(thread)) {
3646 return true;
3647 }
3648 }
Mingyao Yang99170c62015-07-06 11:10:37 -07003649 if (thread->HasDebuggerShadowFrames()) {
3650 // We need to deoptimize the stack for the exception handling flow so that
3651 // we don't miss any deoptimization that should be done when there are
3652 // debugger shadow frames.
3653 return true;
3654 }
Daniel Mihalyieb076692014-08-22 17:33:31 +02003655 // We have to require stack deoptimization if the upcall is deoptimized.
3656 return instrumentation->IsDeoptimized(m);
3657}
3658
Mingyao Yang99170c62015-07-06 11:10:37 -07003659class NeedsDeoptimizationVisitor : public StackVisitor {
Sebastien Hertz520633b2015-09-08 17:03:36 +02003660 public:
3661 explicit NeedsDeoptimizationVisitor(Thread* self)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003662 REQUIRES_SHARED(Locks::mutator_lock_)
Sebastien Hertz520633b2015-09-08 17:03:36 +02003663 : StackVisitor(self, nullptr, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
3664 needs_deoptimization_(false) {}
3665
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01003666 bool VisitFrame() override REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz520633b2015-09-08 17:03:36 +02003667 // The visitor is meant to be used when handling exception from compiled code only.
David Sehr709b0702016-10-13 09:12:37 -07003668 CHECK(!IsShadowFrame()) << "We only expect to visit compiled frame: "
3669 << ArtMethod::PrettyMethod(GetMethod());
Sebastien Hertz520633b2015-09-08 17:03:36 +02003670 ArtMethod* method = GetMethod();
3671 if (method == nullptr) {
3672 // We reach an upcall and don't need to deoptimize this part of the stack (ManagedFragment)
3673 // so we can stop the visit.
3674 DCHECK(!needs_deoptimization_);
3675 return false;
3676 }
3677 if (Runtime::Current()->GetInstrumentation()->InterpretOnly()) {
3678 // We found a compiled frame in the stack but instrumentation is set to interpret
3679 // everything: we need to deoptimize.
3680 needs_deoptimization_ = true;
3681 return false;
3682 }
3683 if (Runtime::Current()->GetInstrumentation()->IsDeoptimized(method)) {
3684 // We found a deoptimized method in the stack.
3685 needs_deoptimization_ = true;
3686 return false;
3687 }
Mingyao Yang99170c62015-07-06 11:10:37 -07003688 ShadowFrame* frame = GetThread()->FindDebuggerShadowFrame(GetFrameId());
3689 if (frame != nullptr) {
3690 // The debugger allocated a ShadowFrame to update a variable in the stack: we need to
3691 // deoptimize the stack to execute (and deallocate) this frame.
3692 needs_deoptimization_ = true;
3693 return false;
3694 }
Sebastien Hertz520633b2015-09-08 17:03:36 +02003695 return true;
3696 }
3697
3698 bool NeedsDeoptimization() const {
3699 return needs_deoptimization_;
3700 }
3701
3702 private:
3703 // Do we need to deoptimize the stack?
3704 bool needs_deoptimization_;
3705
3706 DISALLOW_COPY_AND_ASSIGN(NeedsDeoptimizationVisitor);
3707};
3708
3709// Do we need to deoptimize the stack to handle an exception?
3710bool Dbg::IsForcedInterpreterNeededForExceptionImpl(Thread* thread) {
3711 const SingleStepControl* const ssc = thread->GetSingleStepControl();
3712 if (ssc != nullptr) {
3713 // We deopt to step into the catch handler.
3714 return true;
3715 }
3716 // Deoptimization is required if at least one method in the stack needs it. However we
3717 // skip frames that will be unwound (thus not executed).
3718 NeedsDeoptimizationVisitor visitor(thread);
3719 visitor.WalkStack(true); // includes upcall.
3720 return visitor.NeedsDeoptimization();
3721}
3722
Jeff Hao449db332013-04-12 18:30:52 -07003723// Scoped utility class to suspend a thread so that we may do tasks such as walk its stack. Doesn't
3724// cause suspension if the thread is the current thread.
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07003725class ScopedDebuggerThreadSuspension {
Jeff Hao449db332013-04-12 18:30:52 -07003726 public:
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07003727 ScopedDebuggerThreadSuspension(Thread* self, JDWP::ObjectId thread_id)
Mathieu Chartier90443472015-07-16 20:32:27 -07003728 REQUIRES(!Locks::thread_list_lock_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003729 REQUIRES_SHARED(Locks::mutator_lock_) :
Ian Rogersf3d874c2014-07-17 18:52:42 -07003730 thread_(nullptr),
Jeff Hao449db332013-04-12 18:30:52 -07003731 error_(JDWP::ERR_NONE),
3732 self_suspend_(false),
Ian Rogers33e95662013-05-20 20:29:14 -07003733 other_suspend_(false) {
Jeff Hao449db332013-04-12 18:30:52 -07003734 ScopedObjectAccessUnchecked soa(self);
Sebastien Hertz69206392015-04-07 15:54:25 +02003735 thread_ = DecodeThread(soa, thread_id, &error_);
Jeff Hao449db332013-04-12 18:30:52 -07003736 if (error_ == JDWP::ERR_NONE) {
3737 if (thread_ == soa.Self()) {
3738 self_suspend_ = true;
3739 } else {
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07003740 Thread* suspended_thread;
3741 {
3742 ScopedThreadSuspension sts(self, kWaitingForDebuggerSuspension);
3743 jobject thread_peer = Dbg::GetObjectRegistry()->GetJObject(thread_id);
3744 bool timed_out;
3745 ThreadList* const thread_list = Runtime::Current()->GetThreadList();
Sebastien Hertzcdd798d2017-04-18 18:28:51 +02003746 suspended_thread = thread_list->SuspendThreadByPeer(thread_peer,
3747 /* request_suspension */ true,
Alex Light46f93402017-06-29 11:59:50 -07003748 SuspendReason::kForDebugger,
Sebastien Hertzcdd798d2017-04-18 18:28:51 +02003749 &timed_out);
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07003750 }
Ian Rogersf3d874c2014-07-17 18:52:42 -07003751 if (suspended_thread == nullptr) {
Jeff Hao449db332013-04-12 18:30:52 -07003752 // Thread terminated from under us while suspending.
3753 error_ = JDWP::ERR_INVALID_THREAD;
3754 } else {
3755 CHECK_EQ(suspended_thread, thread_);
3756 other_suspend_ = true;
3757 }
3758 }
3759 }
Elliott Hughes2435a572012-02-17 16:07:41 -08003760 }
Elliott Hughes86964332012-02-15 19:37:42 -08003761
Jeff Hao449db332013-04-12 18:30:52 -07003762 Thread* GetThread() const {
3763 return thread_;
3764 }
3765
3766 JDWP::JdwpError GetError() const {
3767 return error_;
3768 }
3769
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07003770 ~ScopedDebuggerThreadSuspension() {
Jeff Hao449db332013-04-12 18:30:52 -07003771 if (other_suspend_) {
Alex Light88fd7202017-06-30 08:31:59 -07003772 bool resumed = Runtime::Current()->GetThreadList()->Resume(thread_,
3773 SuspendReason::kForDebugger);
3774 DCHECK(resumed);
Jeff Hao449db332013-04-12 18:30:52 -07003775 }
3776 }
3777
3778 private:
3779 Thread* thread_;
3780 JDWP::JdwpError error_;
3781 bool self_suspend_;
3782 bool other_suspend_;
3783};
3784
3785JDWP::JdwpError Dbg::ConfigureStep(JDWP::ObjectId thread_id, JDWP::JdwpStepSize step_size,
3786 JDWP::JdwpStepDepth step_depth) {
3787 Thread* self = Thread::Current();
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07003788 ScopedDebuggerThreadSuspension sts(self, thread_id);
Jeff Hao449db332013-04-12 18:30:52 -07003789 if (sts.GetError() != JDWP::ERR_NONE) {
3790 return sts.GetError();
3791 }
3792
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003793 // Work out what ArtMethod* we're in, the current line number, and how deep the stack currently
Elliott Hughes2435a572012-02-17 16:07:41 -08003794 // is for step-out.
Ian Rogers0399dde2012-06-06 17:09:28 -07003795 struct SingleStepStackVisitor : public StackVisitor {
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003796 explicit SingleStepStackVisitor(Thread* thread) REQUIRES_SHARED(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01003797 : StackVisitor(thread, nullptr, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
3798 stack_depth(0),
3799 method(nullptr),
3800 line_number(-1) {}
Ian Rogersca190662012-06-26 15:45:57 -07003801
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003802 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
3803 // annotalysis.
Andreas Gampefa6a1b02018-09-07 08:11:55 -07003804 bool VisitFrame() override NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003805 ArtMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07003806 if (!m->IsRuntimeMethod()) {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003807 ++stack_depth;
3808 if (method == nullptr) {
Alex Light73376312017-04-06 10:10:51 -07003809 const DexFile* dex_file = m->GetDexFile();
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003810 method = m;
Alex Light73376312017-04-06 10:10:51 -07003811 if (dex_file != nullptr) {
David Sehr9323e6e2016-09-13 08:58:35 -07003812 line_number = annotations::GetLineNumFromPC(dex_file, m, GetDexPc());
Elliott Hughes2435a572012-02-17 16:07:41 -08003813 }
Elliott Hughes86964332012-02-15 19:37:42 -08003814 }
3815 }
Elliott Hughes530fa002012-03-12 11:44:49 -07003816 return true;
Elliott Hughes86964332012-02-15 19:37:42 -08003817 }
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003818
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003819 int stack_depth;
Mathieu Chartiere401d142015-04-22 13:56:20 -07003820 ArtMethod* method;
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003821 int32_t line_number;
Elliott Hughes86964332012-02-15 19:37:42 -08003822 };
Jeff Hao449db332013-04-12 18:30:52 -07003823
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003824 Thread* const thread = sts.GetThread();
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003825 SingleStepStackVisitor visitor(thread);
Ian Rogers0399dde2012-06-06 17:09:28 -07003826 visitor.WalkStack();
Elliott Hughes86964332012-02-15 19:37:42 -08003827
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003828 // Allocate single step.
Sebastien Hertz1558b572015-02-25 15:05:59 +01003829 SingleStepControl* single_step_control =
3830 new (std::nothrow) SingleStepControl(step_size, step_depth,
3831 visitor.stack_depth, visitor.method);
3832 if (single_step_control == nullptr) {
3833 LOG(ERROR) << "Failed to allocate SingleStepControl";
3834 return JDWP::ERR_OUT_OF_MEMORY;
3835 }
3836
Mathieu Chartiere401d142015-04-22 13:56:20 -07003837 ArtMethod* m = single_step_control->GetMethod();
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003838 const int32_t line_number = visitor.line_number;
Sebastien Hertz52f5f932015-05-28 11:00:57 +02003839 // Note: if the thread is not running Java code (pure native thread), there is no "current"
3840 // method on the stack (and no line number either).
3841 if (m != nullptr && !m->IsNative()) {
David Sehr0225f8e2018-01-31 08:52:24 +00003842 CodeItemDebugInfoAccessor accessor(m->DexInstructionDebugInfo());
Mathieu Chartier3e2e1232018-09-11 12:35:30 -07003843 bool last_pc_valid = false;
3844 uint32_t last_pc = 0u;
3845 // Find the dex_pc values that correspond to the current line, for line-based single-stepping.
3846 accessor.DecodeDebugPositionInfo([&](const DexFile::PositionInfo& entry) {
3847 if (static_cast<int32_t>(entry.line_) == line_number) {
3848 if (!last_pc_valid) {
3849 // Everything from this address until the next line change is ours.
3850 last_pc = entry.address_;
3851 last_pc_valid = true;
3852 }
3853 // Otherwise, if we're already in a valid range for this line,
3854 // just keep going (shouldn't really happen)...
3855 } else if (last_pc_valid) { // and the line number is new
3856 // Add everything from the last entry up until here to the set
3857 for (uint32_t dex_pc = last_pc; dex_pc < entry.address_; ++dex_pc) {
3858 single_step_control->AddDexPc(dex_pc);
3859 }
3860 last_pc_valid = false;
3861 }
3862 return false; // There may be multiple entries for any given line.
3863 });
3864 // If the line number was the last in the position table...
3865 if (last_pc_valid) {
3866 for (uint32_t dex_pc = last_pc; dex_pc < accessor.InsnsSizeInCodeUnits(); ++dex_pc) {
3867 single_step_control->AddDexPc(dex_pc);
3868 }
3869 }
Elliott Hughes3e2e1a22012-02-21 11:33:41 -08003870 }
Elliott Hughes2435a572012-02-17 16:07:41 -08003871
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003872 // Activate single-step in the thread.
3873 thread->ActivateSingleStepControl(single_step_control);
Elliott Hughes86964332012-02-15 19:37:42 -08003874
Elliott Hughes2435a572012-02-17 16:07:41 -08003875 if (VLOG_IS_ON(jdwp)) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003876 VLOG(jdwp) << "Single-step thread: " << *thread;
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003877 VLOG(jdwp) << "Single-step step size: " << single_step_control->GetStepSize();
3878 VLOG(jdwp) << "Single-step step depth: " << single_step_control->GetStepDepth();
David Sehr709b0702016-10-13 09:12:37 -07003879 VLOG(jdwp) << "Single-step current method: "
3880 << ArtMethod::PrettyMethod(single_step_control->GetMethod());
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003881 VLOG(jdwp) << "Single-step current line: " << line_number;
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003882 VLOG(jdwp) << "Single-step current stack depth: " << single_step_control->GetStackDepth();
Elliott Hughes2435a572012-02-17 16:07:41 -08003883 VLOG(jdwp) << "Single-step dex_pc values:";
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003884 for (uint32_t dex_pc : single_step_control->GetDexPcs()) {
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003885 VLOG(jdwp) << StringPrintf(" %#x", dex_pc);
Elliott Hughes2435a572012-02-17 16:07:41 -08003886 }
3887 }
3888
3889 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003890}
3891
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003892void Dbg::UnconfigureStep(JDWP::ObjectId thread_id) {
3893 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07003894 JDWP::JdwpError error;
3895 Thread* thread = DecodeThread(soa, thread_id, &error);
Sebastien Hertz87118ed2013-11-26 17:57:18 +01003896 if (error == JDWP::ERR_NONE) {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003897 thread->DeactivateSingleStepControl();
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003898 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003899}
3900
Elliott Hughes45651fd2012-02-21 15:48:20 -08003901static char JdwpTagToShortyChar(JDWP::JdwpTag tag) {
3902 switch (tag) {
3903 default:
3904 LOG(FATAL) << "unknown JDWP tag: " << PrintableChar(tag);
Ian Rogersfc787ec2014-10-09 21:56:44 -07003905 UNREACHABLE();
Elliott Hughes45651fd2012-02-21 15:48:20 -08003906
3907 // Primitives.
3908 case JDWP::JT_BYTE: return 'B';
3909 case JDWP::JT_CHAR: return 'C';
3910 case JDWP::JT_FLOAT: return 'F';
3911 case JDWP::JT_DOUBLE: return 'D';
3912 case JDWP::JT_INT: return 'I';
3913 case JDWP::JT_LONG: return 'J';
3914 case JDWP::JT_SHORT: return 'S';
3915 case JDWP::JT_VOID: return 'V';
3916 case JDWP::JT_BOOLEAN: return 'Z';
3917
3918 // Reference types.
3919 case JDWP::JT_ARRAY:
3920 case JDWP::JT_OBJECT:
3921 case JDWP::JT_STRING:
3922 case JDWP::JT_THREAD:
3923 case JDWP::JT_THREAD_GROUP:
3924 case JDWP::JT_CLASS_LOADER:
3925 case JDWP::JT_CLASS_OBJECT:
3926 return 'L';
3927 }
3928}
3929
Sebastien Hertzcbc50642015-06-01 17:33:12 +02003930JDWP::JdwpError Dbg::PrepareInvokeMethod(uint32_t request_id, JDWP::ObjectId thread_id,
3931 JDWP::ObjectId object_id, JDWP::RefTypeId class_id,
3932 JDWP::MethodId method_id, uint32_t arg_count,
3933 uint64_t arg_values[], JDWP::JdwpTag* arg_types,
3934 uint32_t options) {
3935 Thread* const self = Thread::Current();
3936 CHECK_EQ(self, GetDebugThread()) << "This must be called by the JDWP thread";
Sebastien Hertzd4032e42015-06-12 15:47:34 +02003937 const bool resume_all_threads = ((options & JDWP::INVOKE_SINGLE_THREADED) == 0);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003938
Sebastien Hertzcbc50642015-06-01 17:33:12 +02003939 ThreadList* thread_list = Runtime::Current()->GetThreadList();
Ian Rogersc0542af2014-09-03 16:16:56 -07003940 Thread* targetThread = nullptr;
Elliott Hughesd07986f2011-12-06 18:27:45 -08003941 {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003942 ScopedObjectAccessUnchecked soa(self);
Ian Rogersc0542af2014-09-03 16:16:56 -07003943 JDWP::JdwpError error;
3944 targetThread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08003945 if (error != JDWP::ERR_NONE) {
3946 LOG(ERROR) << "InvokeMethod request for invalid thread id " << thread_id;
3947 return error;
Elliott Hughesd07986f2011-12-06 18:27:45 -08003948 }
Sebastien Hertz1558b572015-02-25 15:05:59 +01003949 if (targetThread->GetInvokeReq() != nullptr) {
3950 // Thread is already invoking a method on behalf of the debugger.
3951 LOG(ERROR) << "InvokeMethod request for thread already invoking a method: " << *targetThread;
3952 return JDWP::ERR_ALREADY_INVOKING;
3953 }
3954 if (!targetThread->IsReadyForDebugInvoke()) {
3955 // Thread is not suspended by an event so it cannot invoke a method.
Elliott Hughesd07986f2011-12-06 18:27:45 -08003956 LOG(ERROR) << "InvokeMethod request for thread not stopped by event: " << *targetThread;
3957 return JDWP::ERR_INVALID_THREAD;
3958 }
3959
3960 /*
Sebastien Hertzd4032e42015-06-12 15:47:34 +02003961 * According to the JDWP specs, we are expected to resume all threads (or only the
3962 * target thread) once. So if a thread has been suspended more than once (either by
3963 * the debugger for an event or by the runtime for GC), it will remain suspended before
3964 * the invoke is executed. This means the debugger is responsible to properly resume all
3965 * the threads it has suspended so the target thread can execute the method.
Elliott Hughesd07986f2011-12-06 18:27:45 -08003966 *
Sebastien Hertzd4032e42015-06-12 15:47:34 +02003967 * However, for compatibility reason with older versions of debuggers (like Eclipse), we
3968 * fully resume all threads (by canceling *all* debugger suspensions) when the debugger
3969 * wants us to resume all threads. This is to avoid ending up in deadlock situation.
3970 *
3971 * On the other hand, if we are asked to only resume the target thread, then we follow the
3972 * JDWP specs by resuming that thread only once. This means the thread will remain suspended
3973 * if it has been suspended more than once before the invoke (and again, this is the
3974 * responsibility of the debugger to properly resume that thread before invoking a method).
Elliott Hughesd07986f2011-12-06 18:27:45 -08003975 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003976 int suspend_count;
3977 {
Ian Rogers50b35e22012-10-04 10:09:15 -07003978 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003979 suspend_count = targetThread->GetSuspendCount();
3980 }
Sebastien Hertzd4032e42015-06-12 15:47:34 +02003981 if (suspend_count > 1 && resume_all_threads) {
3982 // The target thread will remain suspended even after we resume it. Let's emit a warning
3983 // to indicate the invoke won't be executed until the thread is resumed.
3984 LOG(WARNING) << *targetThread << " suspended more than once (suspend count == "
3985 << suspend_count << "). This thread will invoke the method only once "
3986 << "it is fully resumed.";
Elliott Hughesd07986f2011-12-06 18:27:45 -08003987 }
3988
Ian Rogersc0542af2014-09-03 16:16:56 -07003989 mirror::Object* receiver = gRegistry->Get<mirror::Object*>(object_id, &error);
3990 if (error != JDWP::ERR_NONE) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08003991 return JDWP::ERR_INVALID_OBJECT;
3992 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003993
Sebastien Hertz1558b572015-02-25 15:05:59 +01003994 gRegistry->Get<mirror::Object*>(thread_id, &error);
Ian Rogersc0542af2014-09-03 16:16:56 -07003995 if (error != JDWP::ERR_NONE) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08003996 return JDWP::ERR_INVALID_OBJECT;
3997 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003998
Ian Rogersc0542af2014-09-03 16:16:56 -07003999 mirror::Class* c = DecodeClass(class_id, &error);
4000 if (c == nullptr) {
4001 return error;
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08004002 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08004003
Mathieu Chartiere401d142015-04-22 13:56:20 -07004004 ArtMethod* m = FromMethodId(method_id);
Ian Rogersc0542af2014-09-03 16:16:56 -07004005 if (m->IsStatic() != (receiver == nullptr)) {
Elliott Hughes45651fd2012-02-21 15:48:20 -08004006 return JDWP::ERR_INVALID_METHODID;
4007 }
4008 if (m->IsStatic()) {
4009 if (m->GetDeclaringClass() != c) {
4010 return JDWP::ERR_INVALID_METHODID;
4011 }
4012 } else {
4013 if (!m->GetDeclaringClass()->IsAssignableFrom(c)) {
4014 return JDWP::ERR_INVALID_METHODID;
4015 }
4016 }
4017
4018 // Check the argument list matches the method.
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004019 uint32_t shorty_len = 0;
4020 const char* shorty = m->GetShorty(&shorty_len);
4021 if (shorty_len - 1 != arg_count) {
Elliott Hughes45651fd2012-02-21 15:48:20 -08004022 return JDWP::ERR_ILLEGAL_ARGUMENT;
4023 }
Elliott Hughes09201632013-04-15 15:50:07 -07004024
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004025 {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004026 StackHandleScope<2> hs(soa.Self());
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004027 HandleWrapper<mirror::Object> h_obj(hs.NewHandleWrapper(&receiver));
4028 HandleWrapper<mirror::Class> h_klass(hs.NewHandleWrapper(&c));
4029 const DexFile::TypeList* types = m->GetParameterTypeList();
4030 for (size_t i = 0; i < arg_count; ++i) {
4031 if (shorty[i + 1] != JdwpTagToShortyChar(arg_types[i])) {
Elliott Hughes09201632013-04-15 15:50:07 -07004032 return JDWP::ERR_ILLEGAL_ARGUMENT;
4033 }
4034
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004035 if (shorty[i + 1] == 'L') {
4036 // Did we really get an argument of an appropriate reference type?
Vladimir Markob45528c2017-07-27 14:14:28 +01004037 ObjPtr<mirror::Class> parameter_type =
4038 m->ResolveClassFromTypeIndex(types->GetTypeItem(i).type_idx_);
Ian Rogersc0542af2014-09-03 16:16:56 -07004039 mirror::Object* argument = gRegistry->Get<mirror::Object*>(arg_values[i], &error);
4040 if (error != JDWP::ERR_NONE) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004041 return JDWP::ERR_INVALID_OBJECT;
4042 }
Ian Rogersc0542af2014-09-03 16:16:56 -07004043 if (argument != nullptr && !argument->InstanceOf(parameter_type)) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004044 return JDWP::ERR_ILLEGAL_ARGUMENT;
4045 }
4046
4047 // Turn the on-the-wire ObjectId into a jobject.
4048 jvalue& v = reinterpret_cast<jvalue&>(arg_values[i]);
4049 v.l = gRegistry->GetJObject(arg_values[i]);
4050 }
Elliott Hughes09201632013-04-15 15:50:07 -07004051 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08004052 }
4053
Sebastien Hertz1558b572015-02-25 15:05:59 +01004054 // Allocates a DebugInvokeReq.
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004055 DebugInvokeReq* req = new (std::nothrow) DebugInvokeReq(request_id, thread_id, receiver, c, m,
4056 options, arg_values, arg_count);
4057 if (req == nullptr) {
Sebastien Hertz1558b572015-02-25 15:05:59 +01004058 LOG(ERROR) << "Failed to allocate DebugInvokeReq";
4059 return JDWP::ERR_OUT_OF_MEMORY;
4060 }
4061
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004062 // Attaches the DebugInvokeReq to the target thread so it executes the method when
4063 // it is resumed. Once the invocation completes, the target thread will delete it before
4064 // suspending itself (see ThreadList::SuspendSelfForDebugger).
4065 targetThread->SetDebugInvokeReq(req);
Elliott Hughesd07986f2011-12-06 18:27:45 -08004066 }
4067
4068 // 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 +02004069 // away we're sitting high and dry -- but we must release this before the UndoDebuggerSuspensions
4070 // call.
Sebastien Hertzd4032e42015-06-12 15:47:34 +02004071 if (resume_all_threads) {
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004072 VLOG(jdwp) << " Resuming all threads";
4073 thread_list->UndoDebuggerSuspensions();
4074 } else {
4075 VLOG(jdwp) << " Resuming event thread only";
Alex Light88fd7202017-06-30 08:31:59 -07004076 bool resumed = thread_list->Resume(targetThread, SuspendReason::kForDebugger);
4077 DCHECK(resumed);
Elliott Hughesd07986f2011-12-06 18:27:45 -08004078 }
4079
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004080 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004081}
4082
4083void Dbg::ExecuteMethod(DebugInvokeReq* pReq) {
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004084 Thread* const self = Thread::Current();
4085 CHECK_NE(self, GetDebugThread()) << "This must be called by the event thread";
4086
4087 ScopedObjectAccess soa(self);
Elliott Hughesd07986f2011-12-06 18:27:45 -08004088
Elliott Hughes81ff3182012-03-23 20:35:56 -07004089 // We can be called while an exception is pending. We need
Elliott Hughesd07986f2011-12-06 18:27:45 -08004090 // to preserve that across the method invocation.
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004091 StackHandleScope<1> hs(soa.Self());
4092 Handle<mirror::Throwable> old_exception = hs.NewHandle(soa.Self()->GetException());
Sebastien Hertz1558b572015-02-25 15:05:59 +01004093 soa.Self()->ClearException();
Elliott Hughesd07986f2011-12-06 18:27:45 -08004094
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004095 // Execute the method then sends reply to the debugger.
4096 ExecuteMethodWithoutPendingException(soa, pReq);
4097
4098 // If an exception was pending before the invoke, restore it now.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004099 if (old_exception != nullptr) {
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004100 soa.Self()->SetException(old_exception.Get());
4101 }
4102}
4103
4104// Helper function: write a variable-width value into the output input buffer.
4105static void WriteValue(JDWP::ExpandBuf* pReply, int width, uint64_t value) {
4106 switch (width) {
4107 case 1:
4108 expandBufAdd1(pReply, value);
4109 break;
4110 case 2:
4111 expandBufAdd2BE(pReply, value);
4112 break;
4113 case 4:
4114 expandBufAdd4BE(pReply, value);
4115 break;
4116 case 8:
4117 expandBufAdd8BE(pReply, value);
4118 break;
4119 default:
4120 LOG(FATAL) << width;
4121 UNREACHABLE();
4122 }
4123}
4124
4125void Dbg::ExecuteMethodWithoutPendingException(ScopedObjectAccess& soa, DebugInvokeReq* pReq) {
4126 soa.Self()->AssertNoPendingException();
4127
Elliott Hughesd07986f2011-12-06 18:27:45 -08004128 // Translate the method through the vtable, unless the debugger wants to suppress it.
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004129 ArtMethod* m = pReq->method;
Andreas Gampe542451c2016-07-26 09:02:02 -07004130 PointerSize image_pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
Sebastien Hertz1558b572015-02-25 15:05:59 +01004131 if ((pReq->options & JDWP::INVOKE_NONVIRTUAL) == 0 && pReq->receiver.Read() != nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004132 ArtMethod* actual_method =
4133 pReq->klass.Read()->FindVirtualMethodForVirtualOrInterface(m, image_pointer_size);
4134 if (actual_method != m) {
David Sehr709b0702016-10-13 09:12:37 -07004135 VLOG(jdwp) << "ExecuteMethod translated " << ArtMethod::PrettyMethod(m)
4136 << " to " << ArtMethod::PrettyMethod(actual_method);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004137 m = actual_method;
Elliott Hughes45651fd2012-02-21 15:48:20 -08004138 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08004139 }
David Sehr709b0702016-10-13 09:12:37 -07004140 VLOG(jdwp) << "ExecuteMethod " << ArtMethod::PrettyMethod(m)
Sebastien Hertz1558b572015-02-25 15:05:59 +01004141 << " receiver=" << pReq->receiver.Read()
Sebastien Hertzd38667a2013-11-25 15:43:54 +01004142 << " arg_count=" << pReq->arg_count;
Mathieu Chartiere401d142015-04-22 13:56:20 -07004143 CHECK(m != nullptr);
Elliott Hughesd07986f2011-12-06 18:27:45 -08004144
Roland Levillain33d69032015-06-18 18:20:59 +01004145 static_assert(sizeof(jvalue) == sizeof(uint64_t), "jvalue and uint64_t have different sizes.");
Elliott Hughesd07986f2011-12-06 18:27:45 -08004146
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004147 // Invoke the method.
Jeff Hao39b6c242015-05-19 20:30:23 -07004148 ScopedLocalRef<jobject> ref(soa.Env(), soa.AddLocalReference<jobject>(pReq->receiver.Read()));
Andreas Gampe13b27842016-11-07 16:48:23 -08004149 JValue result = InvokeWithJValues(soa, ref.get(), jni::EncodeArtMethod(m),
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004150 reinterpret_cast<jvalue*>(pReq->arg_values.get()));
Elliott Hughesd07986f2011-12-06 18:27:45 -08004151
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004152 // Prepare JDWP ids for the reply.
4153 JDWP::JdwpTag result_tag = BasicTagFromDescriptor(m->GetShorty());
4154 const bool is_object_result = (result_tag == JDWP::JT_OBJECT);
Jeff Hao064d24e2016-08-25 03:52:40 +00004155 StackHandleScope<3> hs(soa.Self());
Sebastien Hertz1558b572015-02-25 15:05:59 +01004156 Handle<mirror::Object> object_result = hs.NewHandle(is_object_result ? result.GetL() : nullptr);
4157 Handle<mirror::Throwable> exception = hs.NewHandle(soa.Self()->GetException());
4158 soa.Self()->ClearException();
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004159
4160 if (!IsDebuggerActive()) {
4161 // The debugger detached: we must not re-suspend threads. We also don't need to fill the reply
4162 // because it won't be sent either.
4163 return;
4164 }
4165
4166 JDWP::ObjectId exceptionObjectId = gRegistry->Add(exception);
4167 uint64_t result_value = 0;
4168 if (exceptionObjectId != 0) {
Sebastien Hertz1558b572015-02-25 15:05:59 +01004169 VLOG(jdwp) << " JDWP invocation returning with exception=" << exception.Get()
4170 << " " << exception->Dump();
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004171 result_value = 0;
Sebastien Hertz1558b572015-02-25 15:05:59 +01004172 } else if (is_object_result) {
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004173 /* if no exception was thrown, examine object result more closely */
Sebastien Hertz1558b572015-02-25 15:05:59 +01004174 JDWP::JdwpTag new_tag = TagFromObject(soa, object_result.Get());
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004175 if (new_tag != result_tag) {
4176 VLOG(jdwp) << " JDWP promoted result from " << result_tag << " to " << new_tag;
4177 result_tag = new_tag;
Elliott Hughesd07986f2011-12-06 18:27:45 -08004178 }
4179
Sebastien Hertz1558b572015-02-25 15:05:59 +01004180 // Register the object in the registry and reference its ObjectId. This ensures
4181 // GC safety and prevents from accessing stale reference if the object is moved.
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004182 result_value = gRegistry->Add(object_result.Get());
Sebastien Hertz1558b572015-02-25 15:05:59 +01004183 } else {
4184 // Primitive result.
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004185 DCHECK(IsPrimitiveTag(result_tag));
4186 result_value = result.GetJ();
4187 }
4188 const bool is_constructor = m->IsConstructor() && !m->IsStatic();
4189 if (is_constructor) {
4190 // If we invoked a constructor (which actually returns void), return the receiver,
4191 // unless we threw, in which case we return null.
Sebastien Hertza3e13772015-11-05 12:09:44 +01004192 DCHECK_EQ(JDWP::JT_VOID, result_tag);
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004193 if (exceptionObjectId == 0) {
Jeff Hao064d24e2016-08-25 03:52:40 +00004194 if (m->GetDeclaringClass()->IsStringClass()) {
4195 // For string constructors, the new string is remapped to the receiver (stored in ref).
4196 Handle<mirror::Object> decoded_ref = hs.NewHandle(soa.Self()->DecodeJObject(ref.get()));
4197 result_value = gRegistry->Add(decoded_ref);
4198 result_tag = TagFromObject(soa, decoded_ref.Get());
4199 } else {
4200 // TODO we could keep the receiver ObjectId in the DebugInvokeReq to avoid looking into the
4201 // object registry.
4202 result_value = GetObjectRegistry()->Add(pReq->receiver.Read());
4203 result_tag = TagFromObject(soa, pReq->receiver.Read());
4204 }
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004205 } else {
4206 result_value = 0;
Sebastien Hertza3e13772015-11-05 12:09:44 +01004207 result_tag = JDWP::JT_OBJECT;
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004208 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08004209 }
4210
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004211 // Suspend other threads if the invoke is not single-threaded.
4212 if ((pReq->options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07004213 ScopedThreadSuspension sts(soa.Self(), kWaitingForDebuggerSuspension);
Hiroshi Yamauchi8f95cf32016-04-19 11:14:06 -07004214 // Avoid a deadlock between GC and debugger where GC gets suspended during GC. b/25800335.
4215 gc::ScopedGCCriticalSection gcs(soa.Self(), gc::kGcCauseDebugger, gc::kCollectorTypeDebugger);
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004216 VLOG(jdwp) << " Suspending all threads";
4217 Runtime::Current()->GetThreadList()->SuspendAllForDebugger();
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004218 }
4219
4220 VLOG(jdwp) << " --> returned " << result_tag
4221 << StringPrintf(" %#" PRIx64 " (except=%#" PRIx64 ")", result_value,
4222 exceptionObjectId);
4223
4224 // Show detailed debug output.
4225 if (result_tag == JDWP::JT_STRING && exceptionObjectId == 0) {
4226 if (result_value != 0) {
4227 if (VLOG_IS_ON(jdwp)) {
4228 std::string result_string;
4229 JDWP::JdwpError error = Dbg::StringToUtf8(result_value, &result_string);
4230 CHECK_EQ(error, JDWP::ERR_NONE);
4231 VLOG(jdwp) << " string '" << result_string << "'";
4232 }
4233 } else {
4234 VLOG(jdwp) << " string (null)";
4235 }
4236 }
4237
4238 // Attach the reply to DebugInvokeReq so it can be sent to the debugger when the event thread
4239 // is ready to suspend.
4240 BuildInvokeReply(pReq->reply, pReq->request_id, result_tag, result_value, exceptionObjectId);
4241}
4242
4243void Dbg::BuildInvokeReply(JDWP::ExpandBuf* pReply, uint32_t request_id, JDWP::JdwpTag result_tag,
4244 uint64_t result_value, JDWP::ObjectId exception) {
4245 // Make room for the JDWP header since we do not know the size of the reply yet.
4246 JDWP::expandBufAddSpace(pReply, kJDWPHeaderLen);
4247
4248 size_t width = GetTagWidth(result_tag);
4249 JDWP::expandBufAdd1(pReply, result_tag);
4250 if (width != 0) {
4251 WriteValue(pReply, width, result_value);
4252 }
4253 JDWP::expandBufAdd1(pReply, JDWP::JT_OBJECT);
4254 JDWP::expandBufAddObjectId(pReply, exception);
4255
4256 // Now we know the size, we can complete the JDWP header.
4257 uint8_t* buf = expandBufGetBuffer(pReply);
4258 JDWP::Set4BE(buf + kJDWPHeaderSizeOffset, expandBufGetLength(pReply));
4259 JDWP::Set4BE(buf + kJDWPHeaderIdOffset, request_id);
4260 JDWP::Set1(buf + kJDWPHeaderFlagsOffset, kJDWPFlagReply); // flags
4261 JDWP::Set2BE(buf + kJDWPHeaderErrorCodeOffset, JDWP::ERR_NONE);
4262}
4263
4264void Dbg::FinishInvokeMethod(DebugInvokeReq* pReq) {
4265 CHECK_NE(Thread::Current(), GetDebugThread()) << "This must be called by the event thread";
4266
4267 JDWP::ExpandBuf* const pReply = pReq->reply;
4268 CHECK(pReply != nullptr) << "No reply attached to DebugInvokeReq";
4269
4270 // We need to prevent other threads (including JDWP thread) from interacting with the debugger
4271 // while we send the reply but are not yet suspended. The JDWP token will be released just before
4272 // we suspend ourself again (see ThreadList::SuspendSelfForDebugger).
4273 gJdwpState->AcquireJdwpTokenForEvent(pReq->thread_id);
4274
4275 // Send the reply unless the debugger detached before the completion of the method.
4276 if (IsDebuggerActive()) {
4277 const size_t replyDataLength = expandBufGetLength(pReply) - kJDWPHeaderLen;
4278 VLOG(jdwp) << StringPrintf("REPLY INVOKE id=0x%06x (length=%zu)",
4279 pReq->request_id, replyDataLength);
4280
4281 gJdwpState->SendRequest(pReply);
4282 } else {
4283 VLOG(jdwp) << "Not sending invoke reply because debugger detached";
Elliott Hughesd07986f2011-12-06 18:27:45 -08004284 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004285}
4286
Alex Light8c2b9292017-11-09 13:21:01 -08004287bool Dbg::DdmHandleChunk(JNIEnv* env,
4288 uint32_t type,
4289 const ArrayRef<const jbyte>& data,
4290 /*out*/uint32_t* out_type,
4291 /*out*/std::vector<uint8_t>* out_data) {
4292 ScopedLocalRef<jbyteArray> dataArray(env, env->NewByteArray(data.size()));
Ian Rogersc0542af2014-09-03 16:16:56 -07004293 if (dataArray.get() == nullptr) {
Alex Light8c2b9292017-11-09 13:21:01 -08004294 LOG(WARNING) << "byte[] allocation failed: " << data.size();
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004295 env->ExceptionClear();
4296 return false;
4297 }
Alex Light8c2b9292017-11-09 13:21:01 -08004298 env->SetByteArrayRegion(dataArray.get(),
4299 0,
4300 data.size(),
4301 reinterpret_cast<const jbyte*>(data.data()));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004302 // Call "private static Chunk dispatch(int type, byte[] data, int offset, int length)".
Alex Light8c2b9292017-11-09 13:21:01 -08004303 ScopedLocalRef<jobject> chunk(
4304 env,
4305 env->CallStaticObjectMethod(
4306 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
4307 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_dispatch,
4308 type, dataArray.get(), 0, data.size()));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004309 if (env->ExceptionCheck()) {
Alex Light1eeefa62018-03-19 13:47:56 -07004310 Thread* self = Thread::Current();
4311 ScopedObjectAccess soa(self);
4312 LOG(INFO) << StringPrintf("Exception thrown by dispatcher for 0x%08x", type) << std::endl
4313 << self->GetException()->Dump();
4314 self->ClearException();
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004315 return false;
4316 }
4317
Ian Rogersc0542af2014-09-03 16:16:56 -07004318 if (chunk.get() == nullptr) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004319 return false;
4320 }
4321
4322 /*
4323 * Pull the pieces out of the chunk. We copy the results into a
4324 * newly-allocated buffer that the caller can free. We don't want to
4325 * continue using the Chunk object because nothing has a reference to it.
4326 *
4327 * We could avoid this by returning type/data/offset/length and having
4328 * the caller be aware of the object lifetime issues, but that
Elliott Hughes81ff3182012-03-23 20:35:56 -07004329 * integrates the JDWP code more tightly into the rest of the runtime, and doesn't work
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004330 * if we have responses for multiple chunks.
4331 *
4332 * So we're pretty much stuck with copying data around multiple times.
4333 */
Alex Light8c2b9292017-11-09 13:21:01 -08004334 ScopedLocalRef<jbyteArray> replyData(
4335 env,
4336 reinterpret_cast<jbyteArray>(
4337 env->GetObjectField(
4338 chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_data)));
4339 jint offset = env->GetIntField(chunk.get(),
4340 WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_offset);
4341 jint length = env->GetIntField(chunk.get(),
4342 WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_length);
4343 *out_type = env->GetIntField(chunk.get(),
4344 WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_type);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004345
Alex Light8c2b9292017-11-09 13:21:01 -08004346 VLOG(jdwp) << StringPrintf("DDM reply: type=0x%08x data=%p offset=%d length=%d",
4347 type,
4348 replyData.get(),
4349 offset,
4350 length);
Alex Light8c2b9292017-11-09 13:21:01 -08004351 out_data->resize(length);
4352 env->GetByteArrayRegion(replyData.get(),
4353 offset,
4354 length,
4355 reinterpret_cast<jbyte*>(out_data->data()));
Alex Light6f2a6342017-12-12 09:55:05 -08004356
Alex Lighte5463a82017-12-12 13:33:28 -08004357 if (env->ExceptionCheck()) {
Alex Light1eeefa62018-03-19 13:47:56 -07004358 Thread* self = Thread::Current();
4359 ScopedObjectAccess soa(self);
Alex Lighte5463a82017-12-12 13:33:28 -08004360 LOG(INFO) << StringPrintf("Exception thrown when reading response data from dispatcher 0x%08x",
Alex Light1eeefa62018-03-19 13:47:56 -07004361 type) << std::endl << self->GetException()->Dump();
4362 self->ClearException();
Alex Lighte5463a82017-12-12 13:33:28 -08004363 return false;
4364 }
4365
Alex Light8c2b9292017-11-09 13:21:01 -08004366 return true;
4367}
4368
4369/*
4370 * "request" contains a full JDWP packet, possibly with multiple chunks. We
4371 * need to process each, accumulate the replies, and ship the whole thing
4372 * back.
4373 *
4374 * Returns "true" if we have a reply. The reply buffer is newly allocated,
4375 * and includes the chunk type/length, followed by the data.
4376 *
4377 * OLD-TODO: we currently assume that the request and reply include a single
4378 * chunk. If this becomes inconvenient we will need to adapt.
4379 */
4380bool Dbg::DdmHandlePacket(JDWP::Request* request, uint8_t** pReplyBuf, int* pReplyLen) {
4381 Thread* self = Thread::Current();
4382 JNIEnv* env = self->GetJniEnv();
4383
4384 uint32_t type = request->ReadUnsigned32("type");
4385 uint32_t length = request->ReadUnsigned32("length");
4386
4387 // Create a byte[] corresponding to 'request'.
4388 size_t request_length = request->size();
4389 // Run through and find all chunks. [Currently just find the first.]
4390 if (length != request_length) {
4391 LOG(WARNING) << StringPrintf("bad chunk found (len=%u pktLen=%zd)", length, request_length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004392 return false;
4393 }
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004394
Alex Light8c2b9292017-11-09 13:21:01 -08004395 ArrayRef<const jbyte> data(reinterpret_cast<const jbyte*>(request->data()), request_length);
4396 std::vector<uint8_t> out_data;
4397 uint32_t out_type = 0;
4398 request->Skip(request_length);
Alex Light6f2a6342017-12-12 09:55:05 -08004399 if (!DdmHandleChunk(env, type, data, &out_type, &out_data) || out_data.empty()) {
Alex Light8c2b9292017-11-09 13:21:01 -08004400 return false;
4401 }
4402 const uint32_t kDdmHeaderSize = 8;
4403 *pReplyLen = out_data.size() + kDdmHeaderSize;
4404 *pReplyBuf = new uint8_t[out_data.size() + kDdmHeaderSize];
4405 memcpy((*pReplyBuf) + kDdmHeaderSize, out_data.data(), out_data.size());
4406 JDWP::Set4BE(*pReplyBuf, out_type);
4407 JDWP::Set4BE((*pReplyBuf) + 4, static_cast<uint32_t>(out_data.size()));
4408 VLOG(jdwp)
4409 << StringPrintf("dvmHandleDdm returning type=%.4s", reinterpret_cast<char*>(*pReplyBuf))
4410 << "0x" << std::hex << reinterpret_cast<uintptr_t>(*pReplyBuf) << std::dec
4411 << " len= " << out_data.size();
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004412 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004413}
4414
Elliott Hughesa2155262011-11-16 16:26:58 -08004415void Dbg::DdmBroadcast(bool connect) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08004416 VLOG(jdwp) << "Broadcasting DDM " << (connect ? "connect" : "disconnect") << "...";
Elliott Hughes47fce012011-10-25 18:37:19 -07004417
4418 Thread* self = Thread::Current();
Ian Rogers50b35e22012-10-04 10:09:15 -07004419 if (self->GetState() != kRunnable) {
4420 LOG(ERROR) << "DDM broadcast in thread state " << self->GetState();
4421 /* try anyway? */
Elliott Hughes47fce012011-10-25 18:37:19 -07004422 }
4423
4424 JNIEnv* env = self->GetJniEnv();
Elliott Hughes47fce012011-10-25 18:37:19 -07004425 jint event = connect ? 1 /*DdmServer.CONNECTED*/ : 2 /*DdmServer.DISCONNECTED*/;
Elliott Hugheseac76672012-05-24 21:56:51 -07004426 env->CallStaticVoidMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
4427 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_broadcast,
4428 event);
Elliott Hughes47fce012011-10-25 18:37:19 -07004429 if (env->ExceptionCheck()) {
4430 LOG(ERROR) << "DdmServer.broadcast " << event << " failed";
4431 env->ExceptionDescribe();
4432 env->ExceptionClear();
4433 }
4434}
4435
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004436void Dbg::DdmConnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08004437 Dbg::DdmBroadcast(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004438}
4439
4440void Dbg::DdmDisconnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08004441 Dbg::DdmBroadcast(false);
Elliott Hughes47fce012011-10-25 18:37:19 -07004442 gDdmThreadNotification = false;
4443}
4444
4445/*
Elliott Hughes82188472011-11-07 18:11:48 -08004446 * Send a notification when a thread starts, stops, or changes its name.
Elliott Hughes47fce012011-10-25 18:37:19 -07004447 *
4448 * Because we broadcast the full set of threads when the notifications are
4449 * first enabled, it's possible for "thread" to be actively executing.
4450 */
Elliott Hughes82188472011-11-07 18:11:48 -08004451void Dbg::DdmSendThreadNotification(Thread* t, uint32_t type) {
Elliott Hughes47fce012011-10-25 18:37:19 -07004452 if (!gDdmThreadNotification) {
4453 return;
4454 }
4455
Alex Light772099a2017-11-21 14:05:04 -08004456 RuntimeCallbacks* cb = Runtime::Current()->GetRuntimeCallbacks();
Elliott Hughes82188472011-11-07 18:11:48 -08004457 if (type == CHUNK_TYPE("THDE")) {
Elliott Hughes47fce012011-10-25 18:37:19 -07004458 uint8_t buf[4];
Ian Rogersd9c4fc92013-10-01 19:45:43 -07004459 JDWP::Set4BE(&buf[0], t->GetThreadId());
Alex Light772099a2017-11-21 14:05:04 -08004460 cb->DdmPublishChunk(CHUNK_TYPE("THDE"), ArrayRef<const uint8_t>(buf));
Elliott Hughes82188472011-11-07 18:11:48 -08004461 } else {
4462 CHECK(type == CHUNK_TYPE("THCR") || type == CHUNK_TYPE("THNM")) << type;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004463 ScopedObjectAccessUnchecked soa(Thread::Current());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004464 StackHandleScope<1> hs(soa.Self());
Andreas Gampe08883de2016-11-08 13:20:52 -08004465 Handle<mirror::String> name(hs.NewHandle(t->GetThreadName()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004466 size_t char_count = (name != nullptr) ? name->GetLength() : 0;
4467 const jchar* chars = (name != nullptr) ? name->GetValue() : nullptr;
4468 bool is_compressed = (name != nullptr) ? name->IsCompressed() : false;
Elliott Hughes82188472011-11-07 18:11:48 -08004469
Elliott Hughes21f32d72011-11-09 17:44:13 -08004470 std::vector<uint8_t> bytes;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07004471 JDWP::Append4BE(bytes, t->GetThreadId());
jessicahandojo3aaa37b2016-07-29 14:46:37 -07004472 if (is_compressed) {
4473 const uint8_t* chars_compressed = name->GetValueCompressed();
4474 JDWP::AppendUtf16CompressedBE(bytes, chars_compressed, char_count);
4475 } else {
4476 JDWP::AppendUtf16BE(bytes, chars, char_count);
4477 }
Elliott Hughes21f32d72011-11-09 17:44:13 -08004478 CHECK_EQ(bytes.size(), char_count*2 + sizeof(uint32_t)*2);
Alex Light772099a2017-11-21 14:05:04 -08004479 cb->DdmPublishChunk(type, ArrayRef<const uint8_t>(bytes));
Elliott Hughes47fce012011-10-25 18:37:19 -07004480 }
4481}
4482
Elliott Hughes47fce012011-10-25 18:37:19 -07004483void Dbg::DdmSetThreadNotification(bool enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004484 // Enable/disable thread notifications.
Elliott Hughes47fce012011-10-25 18:37:19 -07004485 gDdmThreadNotification = enable;
4486 if (enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004487 // Suspend the VM then post thread start notifications for all threads. Threads attaching will
4488 // see a suspension in progress and block until that ends. They then post their own start
4489 // notification.
4490 SuspendVM();
4491 std::list<Thread*> threads;
Ian Rogers50b35e22012-10-04 10:09:15 -07004492 Thread* self = Thread::Current();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004493 {
Ian Rogers50b35e22012-10-04 10:09:15 -07004494 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004495 threads = Runtime::Current()->GetThreadList()->GetList();
4496 }
4497 {
Ian Rogers50b35e22012-10-04 10:09:15 -07004498 ScopedObjectAccess soa(self);
Mathieu Chartier02e25112013-08-14 16:14:24 -07004499 for (Thread* thread : threads) {
4500 Dbg::DdmSendThreadNotification(thread, CHUNK_TYPE("THCR"));
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004501 }
4502 }
4503 ResumeVM();
Elliott Hughes47fce012011-10-25 18:37:19 -07004504 }
4505}
4506
Elliott Hughesa2155262011-11-16 16:26:58 -08004507void Dbg::PostThreadStartOrStop(Thread* t, uint32_t type) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07004508 if (IsDebuggerActive()) {
Sebastien Hertz6995c602014-09-09 12:10:13 +02004509 gJdwpState->PostThreadChange(t, type == CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07004510 }
Elliott Hughes82188472011-11-07 18:11:48 -08004511 Dbg::DdmSendThreadNotification(t, type);
Elliott Hughes47fce012011-10-25 18:37:19 -07004512}
4513
4514void Dbg::PostThreadStart(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004515 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07004516}
4517
4518void Dbg::PostThreadDeath(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004519 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THDE"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004520}
4521
Mathieu Chartierad466ad2015-01-08 16:28:08 -08004522JDWP::JdwpState* Dbg::GetJdwpState() {
4523 return gJdwpState;
4524}
4525
Elliott Hughes767a1472011-10-26 18:49:02 -07004526int Dbg::DdmHandleHpifChunk(HpifWhen when) {
4527 if (when == HPIF_WHEN_NOW) {
Elliott Hughes7162ad92011-10-27 14:08:42 -07004528 DdmSendHeapInfo(when);
Elliott Hughes767a1472011-10-26 18:49:02 -07004529 return true;
4530 }
4531
4532 if (when != HPIF_WHEN_NEVER && when != HPIF_WHEN_NEXT_GC && when != HPIF_WHEN_EVERY_GC) {
4533 LOG(ERROR) << "invalid HpifWhen value: " << static_cast<int>(when);
4534 return false;
4535 }
4536
4537 gDdmHpifWhen = when;
4538 return true;
4539}
4540
4541bool Dbg::DdmHandleHpsgNhsgChunk(Dbg::HpsgWhen when, Dbg::HpsgWhat what, bool native) {
4542 if (when != HPSG_WHEN_NEVER && when != HPSG_WHEN_EVERY_GC) {
4543 LOG(ERROR) << "invalid HpsgWhen value: " << static_cast<int>(when);
4544 return false;
4545 }
4546
4547 if (what != HPSG_WHAT_MERGED_OBJECTS && what != HPSG_WHAT_DISTINCT_OBJECTS) {
4548 LOG(ERROR) << "invalid HpsgWhat value: " << static_cast<int>(what);
4549 return false;
4550 }
4551
4552 if (native) {
4553 gDdmNhsgWhen = when;
4554 gDdmNhsgWhat = what;
4555 } else {
4556 gDdmHpsgWhen = when;
4557 gDdmHpsgWhat = what;
4558 }
4559 return true;
4560}
4561
Elliott Hughes7162ad92011-10-27 14:08:42 -07004562void Dbg::DdmSendHeapInfo(HpifWhen reason) {
4563 // If there's a one-shot 'when', reset it.
4564 if (reason == gDdmHpifWhen) {
4565 if (gDdmHpifWhen == HPIF_WHEN_NEXT_GC) {
4566 gDdmHpifWhen = HPIF_WHEN_NEVER;
4567 }
4568 }
4569
4570 /*
4571 * Chunk HPIF (client --> server)
4572 *
4573 * Heap Info. General information about the heap,
4574 * suitable for a summary display.
4575 *
4576 * [u4]: number of heaps
4577 *
4578 * For each heap:
4579 * [u4]: heap ID
4580 * [u8]: timestamp in ms since Unix epoch
4581 * [u1]: capture reason (same as 'when' value from server)
4582 * [u4]: max heap size in bytes (-Xmx)
4583 * [u4]: current heap size in bytes
4584 * [u4]: current number of bytes allocated
4585 * [u4]: current number of objects allocated
4586 */
4587 uint8_t heap_count = 1;
Ian Rogers1d54e732013-05-02 21:10:01 -07004588 gc::Heap* heap = Runtime::Current()->GetHeap();
Elliott Hughes21f32d72011-11-09 17:44:13 -08004589 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08004590 JDWP::Append4BE(bytes, heap_count);
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004591 JDWP::Append4BE(bytes, 1); // Heap id (bogus; we only have one heap).
Elliott Hughes545a0642011-11-08 19:10:03 -08004592 JDWP::Append8BE(bytes, MilliTime());
4593 JDWP::Append1BE(bytes, reason);
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004594 JDWP::Append4BE(bytes, heap->GetMaxMemory()); // Max allowed heap size in bytes.
4595 JDWP::Append4BE(bytes, heap->GetTotalMemory()); // Current heap size in bytes.
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08004596 JDWP::Append4BE(bytes, heap->GetBytesAllocated());
4597 JDWP::Append4BE(bytes, heap->GetObjectsAllocated());
Elliott Hughes21f32d72011-11-09 17:44:13 -08004598 CHECK_EQ(bytes.size(), 4U + (heap_count * (4 + 8 + 1 + 4 + 4 + 4 + 4)));
Alex Light772099a2017-11-21 14:05:04 -08004599 Runtime::Current()->GetRuntimeCallbacks()->DdmPublishChunk(CHUNK_TYPE("HPIF"),
4600 ArrayRef<const uint8_t>(bytes));
Elliott Hughes767a1472011-10-26 18:49:02 -07004601}
4602
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004603enum HpsgSolidity {
4604 SOLIDITY_FREE = 0,
4605 SOLIDITY_HARD = 1,
4606 SOLIDITY_SOFT = 2,
4607 SOLIDITY_WEAK = 3,
4608 SOLIDITY_PHANTOM = 4,
4609 SOLIDITY_FINALIZABLE = 5,
4610 SOLIDITY_SWEEP = 6,
4611};
4612
4613enum HpsgKind {
4614 KIND_OBJECT = 0,
4615 KIND_CLASS_OBJECT = 1,
4616 KIND_ARRAY_1 = 2,
4617 KIND_ARRAY_2 = 3,
4618 KIND_ARRAY_4 = 4,
4619 KIND_ARRAY_8 = 5,
4620 KIND_UNKNOWN = 6,
4621 KIND_NATIVE = 7,
4622};
4623
4624#define HPSG_PARTIAL (1<<7)
4625#define HPSG_STATE(solidity, kind) ((uint8_t)((((kind) & 0x7) << 3) | ((solidity) & 0x7)))
4626
Ian Rogers30fab402012-01-23 15:43:46 -08004627class HeapChunkContext {
4628 public:
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004629 // Maximum chunk size. Obtain this from the formula:
4630 // (((maximum_heap_size / ALLOCATION_UNIT_SIZE) + 255) / 256) * 2
4631 HeapChunkContext(bool merge, bool native)
Ian Rogers30fab402012-01-23 15:43:46 -08004632 : buf_(16384 - 16),
4633 type_(0),
Mathieu Chartier36dab362014-07-30 14:59:56 -07004634 chunk_overhead_(0) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004635 Reset();
4636 if (native) {
Ian Rogers30fab402012-01-23 15:43:46 -08004637 type_ = CHUNK_TYPE("NHSG");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004638 } else {
Ian Rogers30fab402012-01-23 15:43:46 -08004639 type_ = merge ? CHUNK_TYPE("HPSG") : CHUNK_TYPE("HPSO");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004640 }
4641 }
4642
4643 ~HeapChunkContext() {
Ian Rogers30fab402012-01-23 15:43:46 -08004644 if (p_ > &buf_[0]) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004645 Flush();
4646 }
4647 }
4648
Mathieu Chartier36dab362014-07-30 14:59:56 -07004649 void SetChunkOverhead(size_t chunk_overhead) {
4650 chunk_overhead_ = chunk_overhead;
4651 }
4652
4653 void ResetStartOfNextChunk() {
4654 startOfNextMemoryChunk_ = nullptr;
4655 }
4656
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004657 void EnsureHeader(const void* chunk_ptr) {
Ian Rogers30fab402012-01-23 15:43:46 -08004658 if (!needHeader_) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004659 return;
4660 }
4661
4662 // Start a new HPSx chunk.
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004663 JDWP::Write4BE(&p_, 1); // Heap id (bogus; we only have one heap).
4664 JDWP::Write1BE(&p_, 8); // Size of allocation unit, in bytes.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004665
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004666 JDWP::Write4BE(&p_, reinterpret_cast<uintptr_t>(chunk_ptr)); // virtual address of segment start.
4667 JDWP::Write4BE(&p_, 0); // offset of this piece (relative to the virtual address).
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004668 // [u4]: length of piece, in allocation units
4669 // 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 -08004670 pieceLenField_ = p_;
4671 JDWP::Write4BE(&p_, 0x55555555);
4672 needHeader_ = false;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004673 }
4674
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004675 void Flush() REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -07004676 if (pieceLenField_ == nullptr) {
Ian Rogersd636b062013-01-18 17:51:18 -08004677 // Flush immediately post Reset (maybe back-to-back Flush). Ignore.
4678 CHECK(needHeader_);
4679 return;
4680 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004681 // Patch the "length of piece" field.
Ian Rogers30fab402012-01-23 15:43:46 -08004682 CHECK_LE(&buf_[0], pieceLenField_);
4683 CHECK_LE(pieceLenField_, p_);
4684 JDWP::Set4BE(pieceLenField_, totalAllocationUnits_);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004685
Alex Light772099a2017-11-21 14:05:04 -08004686 ArrayRef<const uint8_t> out(&buf_[0], p_ - &buf_[0]);
4687 Runtime::Current()->GetRuntimeCallbacks()->DdmPublishChunk(type_, out);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004688 Reset();
4689 }
4690
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004691 static void HeapChunkJavaCallback(void* start, void* end, size_t used_bytes, void* arg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004692 REQUIRES_SHARED(Locks::heap_bitmap_lock_,
Ian Rogersb726dcb2012-09-05 08:57:23 -07004693 Locks::mutator_lock_) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004694 reinterpret_cast<HeapChunkContext*>(arg)->HeapChunkJavaCallback(start, end, used_bytes);
4695 }
4696
4697 static void HeapChunkNativeCallback(void* start, void* end, size_t used_bytes, void* arg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004698 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004699 reinterpret_cast<HeapChunkContext*>(arg)->HeapChunkNativeCallback(start, end, used_bytes);
Elliott Hughesa2155262011-11-16 16:26:58 -08004700 }
4701
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004702 private:
Elliott Hughesa2155262011-11-16 16:26:58 -08004703 enum { ALLOCATION_UNIT_SIZE = 8 };
4704
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004705 void Reset() {
Ian Rogers30fab402012-01-23 15:43:46 -08004706 p_ = &buf_[0];
Mathieu Chartier36dab362014-07-30 14:59:56 -07004707 ResetStartOfNextChunk();
Ian Rogers30fab402012-01-23 15:43:46 -08004708 totalAllocationUnits_ = 0;
4709 needHeader_ = true;
Ian Rogersc0542af2014-09-03 16:16:56 -07004710 pieceLenField_ = nullptr;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004711 }
4712
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004713 bool IsNative() const {
4714 return type_ == CHUNK_TYPE("NHSG");
4715 }
4716
4717 // Returns true if the object is not an empty chunk.
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004718 bool ProcessRecord(void* start, size_t used_bytes) REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers30fab402012-01-23 15:43:46 -08004719 // Note: heap call backs cannot manipulate the heap upon which they are crawling, care is taken
4720 // in the following code not to allocate memory, by ensuring buf_ is of the correct size
Ian Rogers15bf2d32012-08-28 17:33:04 -07004721 if (used_bytes == 0) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004722 if (start == nullptr) {
4723 // Reset for start of new heap.
4724 startOfNextMemoryChunk_ = nullptr;
4725 Flush();
4726 }
4727 // Only process in use memory so that free region information
4728 // also includes dlmalloc book keeping.
4729 return false;
Elliott Hughesa2155262011-11-16 16:26:58 -08004730 }
Ian Rogersc0542af2014-09-03 16:16:56 -07004731 if (startOfNextMemoryChunk_ != nullptr) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004732 // Transmit any pending free memory. Native free memory of over kMaxFreeLen could be because
4733 // of the use of mmaps, so don't report. If not free memory then start a new segment.
4734 bool flush = true;
4735 if (start > startOfNextMemoryChunk_) {
4736 const size_t kMaxFreeLen = 2 * kPageSize;
4737 void* free_start = startOfNextMemoryChunk_;
4738 void* free_end = start;
4739 const size_t free_len =
4740 reinterpret_cast<uintptr_t>(free_end) - reinterpret_cast<uintptr_t>(free_start);
4741 if (!IsNative() || free_len < kMaxFreeLen) {
4742 AppendChunk(HPSG_STATE(SOLIDITY_FREE, 0), free_start, free_len, IsNative());
4743 flush = false;
Ian Rogers15bf2d32012-08-28 17:33:04 -07004744 }
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004745 }
4746 if (flush) {
4747 startOfNextMemoryChunk_ = nullptr;
4748 Flush();
4749 }
Ian Rogers15bf2d32012-08-28 17:33:04 -07004750 }
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004751 return true;
Ian Rogers15bf2d32012-08-28 17:33:04 -07004752 }
Elliott Hughesa2155262011-11-16 16:26:58 -08004753
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004754 void HeapChunkNativeCallback(void* start, void* /*end*/, size_t used_bytes)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004755 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004756 if (ProcessRecord(start, used_bytes)) {
4757 uint8_t state = ExamineNativeObject(start);
4758 AppendChunk(state, start, used_bytes + chunk_overhead_, true /*is_native*/);
4759 startOfNextMemoryChunk_ = reinterpret_cast<char*>(start) + used_bytes + chunk_overhead_;
4760 }
4761 }
4762
4763 void HeapChunkJavaCallback(void* start, void* /*end*/, size_t used_bytes)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004764 REQUIRES_SHARED(Locks::heap_bitmap_lock_, Locks::mutator_lock_) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004765 if (ProcessRecord(start, used_bytes)) {
4766 // Determine the type of this chunk.
4767 // OLD-TODO: if context.merge, see if this chunk is different from the last chunk.
4768 // If it's the same, we should combine them.
4769 uint8_t state = ExamineJavaObject(reinterpret_cast<mirror::Object*>(start));
4770 AppendChunk(state, start, used_bytes + chunk_overhead_, false /*is_native*/);
4771 startOfNextMemoryChunk_ = reinterpret_cast<char*>(start) + used_bytes + chunk_overhead_;
4772 }
4773 }
4774
4775 void AppendChunk(uint8_t state, void* ptr, size_t length, bool is_native)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004776 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07004777 // Make sure there's enough room left in the buffer.
4778 // We need to use two bytes for every fractional 256 allocation units used by the chunk plus
4779 // 17 bytes for any header.
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004780 const size_t needed = ((RoundUp(length / ALLOCATION_UNIT_SIZE, 256) / 256) * 2) + 17;
4781 size_t byte_left = &buf_.back() - p_;
4782 if (byte_left < needed) {
4783 if (is_native) {
Pavel Vyssotski7522c742014-12-08 13:38:26 +06004784 // Cannot trigger memory allocation while walking native heap.
Pavel Vyssotski7522c742014-12-08 13:38:26 +06004785 return;
4786 }
Ian Rogers15bf2d32012-08-28 17:33:04 -07004787 Flush();
4788 }
4789
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004790 byte_left = &buf_.back() - p_;
4791 if (byte_left < needed) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07004792 LOG(WARNING) << "Chunk is too big to transmit (chunk_len=" << length << ", "
4793 << needed << " bytes)";
4794 return;
4795 }
4796 EnsureHeader(ptr);
Elliott Hughesa2155262011-11-16 16:26:58 -08004797 // Write out the chunk description.
Ian Rogers15bf2d32012-08-28 17:33:04 -07004798 length /= ALLOCATION_UNIT_SIZE; // Convert to allocation units.
4799 totalAllocationUnits_ += length;
4800 while (length > 256) {
Ian Rogers30fab402012-01-23 15:43:46 -08004801 *p_++ = state | HPSG_PARTIAL;
4802 *p_++ = 255; // length - 1
Ian Rogers15bf2d32012-08-28 17:33:04 -07004803 length -= 256;
Elliott Hughesa2155262011-11-16 16:26:58 -08004804 }
Ian Rogers30fab402012-01-23 15:43:46 -08004805 *p_++ = state;
Ian Rogers15bf2d32012-08-28 17:33:04 -07004806 *p_++ = length - 1;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004807 }
4808
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004809 uint8_t ExamineNativeObject(const void* p) REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004810 return p == nullptr ? HPSG_STATE(SOLIDITY_FREE, 0) : HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
4811 }
4812
4813 uint8_t ExamineJavaObject(mirror::Object* o)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004814 REQUIRES_SHARED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -07004815 if (o == nullptr) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004816 return HPSG_STATE(SOLIDITY_FREE, 0);
4817 }
Elliott Hughesa2155262011-11-16 16:26:58 -08004818 // It's an allocated chunk. Figure out what it is.
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004819 gc::Heap* heap = Runtime::Current()->GetHeap();
4820 if (!heap->IsLiveObjectLocked(o)) {
4821 LOG(ERROR) << "Invalid object in managed heap: " << o;
Elliott Hughesa2155262011-11-16 16:26:58 -08004822 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
4823 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004824 mirror::Class* c = o->GetClass();
Ian Rogersc0542af2014-09-03 16:16:56 -07004825 if (c == nullptr) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004826 // The object was probably just created but hasn't been initialized yet.
4827 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
4828 }
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004829 if (!heap->IsValidObjectAddress(c)) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07004830 LOG(ERROR) << "Invalid class for managed heap object: " << o << " " << c;
Elliott Hughesa2155262011-11-16 16:26:58 -08004831 return HPSG_STATE(SOLIDITY_HARD, KIND_UNKNOWN);
4832 }
Mathieu Chartierf26e1b32015-01-29 10:47:10 -08004833 if (c->GetClass() == nullptr) {
4834 LOG(ERROR) << "Null class of class " << c << " for object " << o;
4835 return HPSG_STATE(SOLIDITY_HARD, KIND_UNKNOWN);
4836 }
Elliott Hughesa2155262011-11-16 16:26:58 -08004837 if (c->IsClassClass()) {
4838 return HPSG_STATE(SOLIDITY_HARD, KIND_CLASS_OBJECT);
4839 }
Elliott Hughesa2155262011-11-16 16:26:58 -08004840 if (c->IsArrayClass()) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004841 switch (c->GetComponentSize()) {
4842 case 1: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_1);
4843 case 2: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_2);
4844 case 4: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
4845 case 8: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_8);
4846 }
4847 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004848 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
4849 }
4850
Ian Rogers30fab402012-01-23 15:43:46 -08004851 std::vector<uint8_t> buf_;
4852 uint8_t* p_;
4853 uint8_t* pieceLenField_;
Ian Rogers15bf2d32012-08-28 17:33:04 -07004854 void* startOfNextMemoryChunk_;
Ian Rogers30fab402012-01-23 15:43:46 -08004855 size_t totalAllocationUnits_;
4856 uint32_t type_;
Ian Rogers30fab402012-01-23 15:43:46 -08004857 bool needHeader_;
Mathieu Chartier36dab362014-07-30 14:59:56 -07004858 size_t chunk_overhead_;
Ian Rogers30fab402012-01-23 15:43:46 -08004859
Elliott Hughesa2155262011-11-16 16:26:58 -08004860 DISALLOW_COPY_AND_ASSIGN(HeapChunkContext);
4861};
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004862
4863void Dbg::DdmSendHeapSegments(bool native) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004864 Dbg::HpsgWhen when = native ? gDdmNhsgWhen : gDdmHpsgWhen;
4865 Dbg::HpsgWhat what = native ? gDdmNhsgWhat : gDdmHpsgWhat;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004866 if (when == HPSG_WHEN_NEVER) {
4867 return;
4868 }
Alex Light772099a2017-11-21 14:05:04 -08004869 RuntimeCallbacks* cb = Runtime::Current()->GetRuntimeCallbacks();
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004870 // Figure out what kind of chunks we'll be sending.
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004871 CHECK(what == HPSG_WHAT_MERGED_OBJECTS || what == HPSG_WHAT_DISTINCT_OBJECTS)
4872 << static_cast<int>(what);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004873
4874 // First, send a heap start chunk.
4875 uint8_t heap_id[4];
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004876 JDWP::Set4BE(&heap_id[0], 1); // Heap id (bogus; we only have one heap).
Alex Light772099a2017-11-21 14:05:04 -08004877 cb->DdmPublishChunk(native ? CHUNK_TYPE("NHST") : CHUNK_TYPE("HPST"),
4878 ArrayRef<const uint8_t>(heap_id));
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07004879 Thread* self = Thread::Current();
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07004880 Locks::mutator_lock_->AssertSharedHeld(self);
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07004881
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004882 // Send a series of heap segment chunks.
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004883 HeapChunkContext context(what == HPSG_WHAT_MERGED_OBJECTS, native);
Andreas Gampe0c183382017-07-13 22:26:24 -07004884 auto bump_pointer_space_visitor = [&](mirror::Object* obj)
4885 REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
4886 const size_t size = RoundUp(obj->SizeOf(), kObjectAlignment);
4887 HeapChunkContext::HeapChunkJavaCallback(
4888 obj, reinterpret_cast<void*>(reinterpret_cast<uintptr_t>(obj) + size), size, &context);
4889 };
Elliott Hughesa2155262011-11-16 16:26:58 -08004890 if (native) {
Dimitry Ivanove6465bc2015-12-14 18:55:02 -08004891 UNIMPLEMENTED(WARNING) << "Native heap inspection is not supported";
Elliott Hughesa2155262011-11-16 16:26:58 -08004892 } else {
Ian Rogers1d54e732013-05-02 21:10:01 -07004893 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartier36dab362014-07-30 14:59:56 -07004894 for (const auto& space : heap->GetContinuousSpaces()) {
4895 if (space->IsDlMallocSpace()) {
Mathieu Chartier4c69d7f2014-10-10 12:45:50 -07004896 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004897 // dlmalloc's chunk header is 2 * sizeof(size_t), but if the previous chunk is in use for an
4898 // allocation then the first sizeof(size_t) may belong to it.
4899 context.SetChunkOverhead(sizeof(size_t));
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004900 space->AsDlMallocSpace()->Walk(HeapChunkContext::HeapChunkJavaCallback, &context);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004901 } else if (space->IsRosAllocSpace()) {
4902 context.SetChunkOverhead(0);
Mathieu Chartier4c69d7f2014-10-10 12:45:50 -07004903 // Need to acquire the mutator lock before the heap bitmap lock with exclusive access since
4904 // RosAlloc's internal logic doesn't know to release and reacquire the heap bitmap lock.
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07004905 ScopedThreadSuspension sts(self, kSuspended);
Mathieu Chartier4f55e222015-09-04 13:26:21 -07004906 ScopedSuspendAll ssa(__FUNCTION__);
4907 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
4908 space->AsRosAllocSpace()->Walk(HeapChunkContext::HeapChunkJavaCallback, &context);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004909 } else if (space->IsBumpPointerSpace()) {
Mathieu Chartier4c69d7f2014-10-10 12:45:50 -07004910 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004911 context.SetChunkOverhead(0);
Andreas Gampe0c183382017-07-13 22:26:24 -07004912 space->AsBumpPointerSpace()->Walk(bump_pointer_space_visitor);
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004913 HeapChunkContext::HeapChunkJavaCallback(nullptr, nullptr, 0, &context);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08004914 } else if (space->IsRegionSpace()) {
4915 heap->IncrementDisableMovingGC(self);
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07004916 {
4917 ScopedThreadSuspension sts(self, kSuspended);
Mathieu Chartier4f55e222015-09-04 13:26:21 -07004918 ScopedSuspendAll ssa(__FUNCTION__);
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07004919 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
4920 context.SetChunkOverhead(0);
Andreas Gampe0c183382017-07-13 22:26:24 -07004921 space->AsRegionSpace()->Walk(bump_pointer_space_visitor);
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07004922 HeapChunkContext::HeapChunkJavaCallback(nullptr, nullptr, 0, &context);
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07004923 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08004924 heap->DecrementDisableMovingGC(self);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004925 } else {
4926 UNIMPLEMENTED(WARNING) << "Not counting objects in space " << *space;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07004927 }
Mathieu Chartier36dab362014-07-30 14:59:56 -07004928 context.ResetStartOfNextChunk();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07004929 }
Mathieu Chartier4c69d7f2014-10-10 12:45:50 -07004930 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07004931 // Walk the large objects, these are not in the AllocSpace.
Mathieu Chartier36dab362014-07-30 14:59:56 -07004932 context.SetChunkOverhead(0);
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004933 heap->GetLargeObjectsSpace()->Walk(HeapChunkContext::HeapChunkJavaCallback, &context);
Elliott Hughesa2155262011-11-16 16:26:58 -08004934 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004935
4936 // Finally, send a heap end chunk.
Alex Light772099a2017-11-21 14:05:04 -08004937 cb->DdmPublishChunk(native ? CHUNK_TYPE("NHEN") : CHUNK_TYPE("HPEN"),
4938 ArrayRef<const uint8_t>(heap_id));
Elliott Hughes767a1472011-10-26 18:49:02 -07004939}
4940
Brian Carlstrom306db812014-09-05 13:01:41 -07004941void Dbg::SetAllocTrackingEnabled(bool enable) {
Man Cao8c2ff642015-05-27 17:25:30 -07004942 gc::AllocRecordObjectMap::SetAllocTrackingEnabled(enable);
Elliott Hughes545a0642011-11-08 19:10:03 -08004943}
4944
4945void Dbg::DumpRecentAllocations() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004946 ScopedObjectAccess soa(Thread::Current());
Brian Carlstrom306db812014-09-05 13:01:41 -07004947 MutexLock mu(soa.Self(), *Locks::alloc_tracker_lock_);
Man Cao8c2ff642015-05-27 17:25:30 -07004948 if (!Runtime::Current()->GetHeap()->IsAllocTrackingEnabled()) {
Elliott Hughes545a0642011-11-08 19:10:03 -08004949 LOG(INFO) << "Not recording tracked allocations";
4950 return;
4951 }
Man Cao8c2ff642015-05-27 17:25:30 -07004952 gc::AllocRecordObjectMap* records = Runtime::Current()->GetHeap()->GetAllocationRecords();
4953 CHECK(records != nullptr);
Elliott Hughes545a0642011-11-08 19:10:03 -08004954
Man Cao1ed11b92015-06-11 22:47:35 -07004955 const uint16_t capped_count = CappedAllocRecordCount(records->GetRecentAllocationSize());
Brian Carlstrom306db812014-09-05 13:01:41 -07004956 uint16_t count = capped_count;
Elliott Hughes545a0642011-11-08 19:10:03 -08004957
Man Cao8c2ff642015-05-27 17:25:30 -07004958 LOG(INFO) << "Tracked allocations, (count=" << count << ")";
4959 for (auto it = records->RBegin(), end = records->REnd();
4960 count > 0 && it != end; count--, it++) {
Mathieu Chartier458b1052016-03-29 14:02:55 -07004961 const gc::AllocRecord* record = &it->second;
Elliott Hughes545a0642011-11-08 19:10:03 -08004962
Man Cao8c2ff642015-05-27 17:25:30 -07004963 LOG(INFO) << StringPrintf(" Thread %-2d %6zd bytes ", record->GetTid(), record->ByteCount())
David Sehr709b0702016-10-13 09:12:37 -07004964 << mirror::Class::PrettyClass(record->GetClass());
Elliott Hughes545a0642011-11-08 19:10:03 -08004965
Man Cao8c2ff642015-05-27 17:25:30 -07004966 for (size_t stack_frame = 0, depth = record->GetDepth(); stack_frame < depth; ++stack_frame) {
4967 const gc::AllocRecordStackTraceElement& stack_element = record->StackElement(stack_frame);
4968 ArtMethod* m = stack_element.GetMethod();
David Sehr709b0702016-10-13 09:12:37 -07004969 LOG(INFO) << " " << ArtMethod::PrettyMethod(m) << " line "
4970 << stack_element.ComputeLineNumber();
Elliott Hughes545a0642011-11-08 19:10:03 -08004971 }
4972
4973 // pause periodically to help logcat catch up
4974 if ((count % 5) == 0) {
4975 usleep(40000);
4976 }
Elliott Hughes545a0642011-11-08 19:10:03 -08004977 }
4978}
4979
4980class StringTable {
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07004981 private:
4982 struct Entry {
Andreas Gampe84eadb22017-07-07 15:08:01 -07004983 explicit Entry(const char* data_in)
4984 : data(data_in), hash(ComputeModifiedUtf8Hash(data_in)), index(0) {
4985 }
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07004986 Entry(const Entry& entry) = default;
4987 Entry(Entry&& entry) = default;
4988
4989 // Pointer to the actual string data.
4990 const char* data;
Andreas Gampe84eadb22017-07-07 15:08:01 -07004991
4992 // The hash of the data.
4993 const uint32_t hash;
4994
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07004995 // The index. This will be filled in on Finish and is not part of the ordering, so mark it
4996 // mutable.
4997 mutable uint32_t index;
4998
Andreas Gampe84eadb22017-07-07 15:08:01 -07004999 bool operator==(const Entry& other) const {
5000 return strcmp(data, other.data) == 0;
5001 }
5002 };
5003 struct EntryHash {
5004 size_t operator()(const Entry& entry) const {
5005 return entry.hash;
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07005006 }
5007 };
5008
Elliott Hughes545a0642011-11-08 19:10:03 -08005009 public:
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07005010 StringTable() : finished_(false) {
Elliott Hughes545a0642011-11-08 19:10:03 -08005011 }
5012
Andreas Gampef774a4e2017-07-06 22:15:18 -07005013 void Add(const char* str, bool copy_string) {
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07005014 DCHECK(!finished_);
Andreas Gampef774a4e2017-07-06 22:15:18 -07005015 if (UNLIKELY(copy_string)) {
5016 // Check whether it's already there.
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07005017 Entry entry(str);
5018 if (table_.find(entry) != table_.end()) {
Andreas Gampef774a4e2017-07-06 22:15:18 -07005019 return;
5020 }
Mathieu Chartier4345c462014-06-27 10:20:14 -07005021
Andreas Gampef774a4e2017-07-06 22:15:18 -07005022 // Make a copy.
5023 size_t str_len = strlen(str);
5024 char* copy = new char[str_len + 1];
5025 strlcpy(copy, str, str_len + 1);
5026 string_backup_.emplace_back(copy);
5027 str = copy;
5028 }
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07005029 Entry entry(str);
5030 table_.insert(entry);
5031 }
5032
5033 // Update all entries and give them an index. Note that this is likely not the insertion order,
5034 // as the set will with high likelihood reorder elements. Thus, Add must not be called after
5035 // Finish, and Finish must be called before IndexOf. In that case, WriteTo will walk in
5036 // the same order as Finish, and indices will agree. The order invariant, as well as indices,
5037 // are enforced through debug checks.
5038 void Finish() {
5039 DCHECK(!finished_);
5040 finished_ = true;
5041 uint32_t index = 0;
5042 for (auto& entry : table_) {
5043 entry.index = index;
5044 ++index;
5045 }
Elliott Hughes545a0642011-11-08 19:10:03 -08005046 }
5047
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07005048 size_t IndexOf(const char* s) const {
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07005049 DCHECK(finished_);
5050 Entry entry(s);
5051 auto it = table_.find(entry);
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07005052 if (it == table_.end()) {
5053 LOG(FATAL) << "IndexOf(\"" << s << "\") failed";
5054 }
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07005055 return it->index;
Elliott Hughes545a0642011-11-08 19:10:03 -08005056 }
5057
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07005058 size_t Size() const {
Elliott Hughes545a0642011-11-08 19:10:03 -08005059 return table_.size();
5060 }
5061
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07005062 void WriteTo(std::vector<uint8_t>& bytes) const {
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07005063 DCHECK(finished_);
5064 uint32_t cur_index = 0;
5065 for (const auto& entry : table_) {
5066 DCHECK_EQ(cur_index++, entry.index);
5067
5068 size_t s_len = CountModifiedUtf8Chars(entry.data);
Christopher Ferris8a354052015-04-24 17:23:53 -07005069 std::unique_ptr<uint16_t[]> s_utf16(new uint16_t[s_len]);
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07005070 ConvertModifiedUtf8ToUtf16(s_utf16.get(), entry.data);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005071 JDWP::AppendUtf16BE(bytes, s_utf16.get(), s_len);
Elliott Hughes545a0642011-11-08 19:10:03 -08005072 }
5073 }
5074
5075 private:
Andreas Gampe84eadb22017-07-07 15:08:01 -07005076 std::unordered_set<Entry, EntryHash> table_;
Andreas Gampef774a4e2017-07-06 22:15:18 -07005077 std::vector<std::unique_ptr<char[]>> string_backup_;
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07005078
5079 bool finished_;
5080
Elliott Hughes545a0642011-11-08 19:10:03 -08005081 DISALLOW_COPY_AND_ASSIGN(StringTable);
5082};
5083
Mathieu Chartiere401d142015-04-22 13:56:20 -07005084static const char* GetMethodSourceFile(ArtMethod* method)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005085 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07005086 DCHECK(method != nullptr);
5087 const char* source_file = method->GetDeclaringClassSourceFile();
Sebastien Hertz280286a2014-04-28 09:26:50 +02005088 return (source_file != nullptr) ? source_file : "";
5089}
5090
Elliott Hughes545a0642011-11-08 19:10:03 -08005091/*
5092 * The data we send to DDMS contains everything we have recorded.
5093 *
5094 * Message header (all values big-endian):
5095 * (1b) message header len (to allow future expansion); includes itself
5096 * (1b) entry header len
5097 * (1b) stack frame len
5098 * (2b) number of entries
5099 * (4b) offset to string table from start of message
5100 * (2b) number of class name strings
5101 * (2b) number of method name strings
5102 * (2b) number of source file name strings
5103 * For each entry:
5104 * (4b) total allocation size
Elliott Hughes221229c2013-01-08 18:17:50 -08005105 * (2b) thread id
Elliott Hughes545a0642011-11-08 19:10:03 -08005106 * (2b) allocated object's class name index
5107 * (1b) stack depth
5108 * For each stack frame:
5109 * (2b) method's class name
5110 * (2b) method name
5111 * (2b) method source file
5112 * (2b) line number, clipped to 32767; -2 if native; -1 if no source
5113 * (xb) class name strings
5114 * (xb) method name strings
5115 * (xb) source file strings
5116 *
5117 * As with other DDM traffic, strings are sent as a 4-byte length
5118 * followed by UTF-16 data.
5119 *
5120 * We send up 16-bit unsigned indexes into string tables. In theory there
Brian Carlstrom306db812014-09-05 13:01:41 -07005121 * can be (kMaxAllocRecordStackDepth * alloc_record_max_) unique strings in
Elliott Hughes545a0642011-11-08 19:10:03 -08005122 * each table, but in practice there should be far fewer.
5123 *
5124 * The chief reason for using a string table here is to keep the size of
5125 * the DDMS message to a minimum. This is partly to make the protocol
5126 * efficient, but also because we have to form the whole thing up all at
5127 * once in a memory buffer.
5128 *
5129 * We use separate string tables for class names, method names, and source
5130 * files to keep the indexes small. There will generally be no overlap
5131 * between the contents of these tables.
5132 */
5133jbyteArray Dbg::GetRecentAllocations() {
Ian Rogerscf7f1912014-10-22 22:06:39 -07005134 if ((false)) {
Elliott Hughes545a0642011-11-08 19:10:03 -08005135 DumpRecentAllocations();
5136 }
5137
Ian Rogers50b35e22012-10-04 10:09:15 -07005138 Thread* self = Thread::Current();
Elliott Hughes545a0642011-11-08 19:10:03 -08005139 std::vector<uint8_t> bytes;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005140 {
Brian Carlstrom306db812014-09-05 13:01:41 -07005141 MutexLock mu(self, *Locks::alloc_tracker_lock_);
Man Cao8c2ff642015-05-27 17:25:30 -07005142 gc::AllocRecordObjectMap* records = Runtime::Current()->GetHeap()->GetAllocationRecords();
5143 // In case this method is called when allocation tracker is disabled,
5144 // we should still send some data back.
5145 gc::AllocRecordObjectMap dummy;
5146 if (records == nullptr) {
5147 CHECK(!Runtime::Current()->GetHeap()->IsAllocTrackingEnabled());
5148 records = &dummy;
5149 }
Man Cao41656de2015-07-06 18:53:15 -07005150 // We don't need to wait on the condition variable records->new_record_condition_, because this
5151 // function only reads the class objects, which are already marked so it doesn't change their
5152 // reachability.
Man Cao8c2ff642015-05-27 17:25:30 -07005153
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005154 //
5155 // Part 1: generate string tables.
5156 //
5157 StringTable class_names;
5158 StringTable method_names;
5159 StringTable filenames;
Elliott Hughes545a0642011-11-08 19:10:03 -08005160
Andreas Gampeff29cee2017-07-07 11:11:15 -07005161 VLOG(jdwp) << "Collecting StringTables.";
5162
Man Cao1ed11b92015-06-11 22:47:35 -07005163 const uint16_t capped_count = CappedAllocRecordCount(records->GetRecentAllocationSize());
Brian Carlstrom306db812014-09-05 13:01:41 -07005164 uint16_t count = capped_count;
Andreas Gamped0fc7682017-07-07 14:03:08 -07005165 size_t alloc_byte_count = 0;
Man Cao8c2ff642015-05-27 17:25:30 -07005166 for (auto it = records->RBegin(), end = records->REnd();
5167 count > 0 && it != end; count--, it++) {
Mathieu Chartier458b1052016-03-29 14:02:55 -07005168 const gc::AllocRecord* record = &it->second;
Ian Rogers1ff3c982014-08-12 02:30:58 -07005169 std::string temp;
Andreas Gampef774a4e2017-07-06 22:15:18 -07005170 const char* class_descr = record->GetClassDescriptor(&temp);
5171 class_names.Add(class_descr, !temp.empty());
Andreas Gamped0fc7682017-07-07 14:03:08 -07005172
5173 // Size + tid + class name index + stack depth.
5174 alloc_byte_count += 4u + 2u + 2u + 1u;
5175
Man Cao8c2ff642015-05-27 17:25:30 -07005176 for (size_t i = 0, depth = record->GetDepth(); i < depth; i++) {
5177 ArtMethod* m = record->StackElement(i).GetMethod();
Andreas Gampef774a4e2017-07-06 22:15:18 -07005178 class_names.Add(m->GetDeclaringClassDescriptor(), false);
5179 method_names.Add(m->GetName(), false);
5180 filenames.Add(GetMethodSourceFile(m), false);
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005181 }
Andreas Gamped0fc7682017-07-07 14:03:08 -07005182
5183 // Depth * (class index + method name index + file name index + line number).
5184 alloc_byte_count += record->GetDepth() * (2u + 2u + 2u + 2u);
Elliott Hughes545a0642011-11-08 19:10:03 -08005185 }
5186
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07005187 class_names.Finish();
5188 method_names.Finish();
5189 filenames.Finish();
Andreas Gampeff29cee2017-07-07 11:11:15 -07005190 VLOG(jdwp) << "Done collecting StringTables:" << std::endl
5191 << " ClassNames: " << class_names.Size() << std::endl
5192 << " MethodNames: " << method_names.Size() << std::endl
5193 << " Filenames: " << filenames.Size();
5194
Man Cao8c2ff642015-05-27 17:25:30 -07005195 LOG(INFO) << "recent allocation records: " << capped_count;
5196 LOG(INFO) << "allocation records all objects: " << records->Size();
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005197
5198 //
5199 // Part 2: Generate the output and store it in the buffer.
5200 //
5201
5202 // (1b) message header len (to allow future expansion); includes itself
5203 // (1b) entry header len
5204 // (1b) stack frame len
5205 const int kMessageHeaderLen = 15;
5206 const int kEntryHeaderLen = 9;
5207 const int kStackFrameLen = 8;
5208 JDWP::Append1BE(bytes, kMessageHeaderLen);
5209 JDWP::Append1BE(bytes, kEntryHeaderLen);
5210 JDWP::Append1BE(bytes, kStackFrameLen);
5211
5212 // (2b) number of entries
5213 // (4b) offset to string table from start of message
5214 // (2b) number of class name strings
5215 // (2b) number of method name strings
5216 // (2b) number of source file name strings
Brian Carlstrom306db812014-09-05 13:01:41 -07005217 JDWP::Append2BE(bytes, capped_count);
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005218 size_t string_table_offset = bytes.size();
Brian Carlstrom7934ac22013-07-26 10:54:15 -07005219 JDWP::Append4BE(bytes, 0); // We'll patch this later...
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005220 JDWP::Append2BE(bytes, class_names.Size());
5221 JDWP::Append2BE(bytes, method_names.Size());
5222 JDWP::Append2BE(bytes, filenames.Size());
5223
Andreas Gampeff29cee2017-07-07 11:11:15 -07005224 VLOG(jdwp) << "Dumping allocations with stacks";
5225
Andreas Gamped0fc7682017-07-07 14:03:08 -07005226 // Enlarge the vector for the allocation data.
5227 size_t reserve_size = bytes.size() + alloc_byte_count;
5228 bytes.reserve(reserve_size);
5229
Ian Rogers1ff3c982014-08-12 02:30:58 -07005230 std::string temp;
Man Cao8c2ff642015-05-27 17:25:30 -07005231 count = capped_count;
5232 // The last "count" number of allocation records in "records" are the most recent "count" number
5233 // of allocations. Reverse iterate to get them. The most recent allocation is sent first.
5234 for (auto it = records->RBegin(), end = records->REnd();
5235 count > 0 && it != end; count--, it++) {
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005236 // For each entry:
5237 // (4b) total allocation size
5238 // (2b) thread id
5239 // (2b) allocated object's class name index
5240 // (1b) stack depth
Mathieu Chartier458b1052016-03-29 14:02:55 -07005241 const gc::AllocRecord* record = &it->second;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005242 size_t stack_depth = record->GetDepth();
Mathieu Chartierf8322842014-05-16 10:59:25 -07005243 size_t allocated_object_class_name_index =
Man Cao41656de2015-07-06 18:53:15 -07005244 class_names.IndexOf(record->GetClassDescriptor(&temp));
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07005245 JDWP::Append4BE(bytes, record->ByteCount());
Man Cao8c2ff642015-05-27 17:25:30 -07005246 JDWP::Append2BE(bytes, static_cast<uint16_t>(record->GetTid()));
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005247 JDWP::Append2BE(bytes, allocated_object_class_name_index);
5248 JDWP::Append1BE(bytes, stack_depth);
5249
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005250 for (size_t stack_frame = 0; stack_frame < stack_depth; ++stack_frame) {
5251 // For each stack frame:
5252 // (2b) method's class name
5253 // (2b) method name
5254 // (2b) method source file
5255 // (2b) line number, clipped to 32767; -2 if native; -1 if no source
Man Cao8c2ff642015-05-27 17:25:30 -07005256 ArtMethod* m = record->StackElement(stack_frame).GetMethod();
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07005257 size_t class_name_index = class_names.IndexOf(m->GetDeclaringClassDescriptor());
5258 size_t method_name_index = method_names.IndexOf(m->GetName());
5259 size_t file_name_index = filenames.IndexOf(GetMethodSourceFile(m));
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005260 JDWP::Append2BE(bytes, class_name_index);
5261 JDWP::Append2BE(bytes, method_name_index);
5262 JDWP::Append2BE(bytes, file_name_index);
Man Cao8c2ff642015-05-27 17:25:30 -07005263 JDWP::Append2BE(bytes, record->StackElement(stack_frame).ComputeLineNumber());
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005264 }
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005265 }
5266
Andreas Gamped0fc7682017-07-07 14:03:08 -07005267 CHECK_EQ(bytes.size(), reserve_size);
Andreas Gampeff29cee2017-07-07 11:11:15 -07005268 VLOG(jdwp) << "Dumping tables.";
5269
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005270 // (xb) class name strings
5271 // (xb) method name strings
5272 // (xb) source file strings
5273 JDWP::Set4BE(&bytes[string_table_offset], bytes.size());
5274 class_names.WriteTo(bytes);
5275 method_names.WriteTo(bytes);
5276 filenames.WriteTo(bytes);
Andreas Gampeff29cee2017-07-07 11:11:15 -07005277
5278 VLOG(jdwp) << "GetRecentAllocations: data created. " << bytes.size();
Elliott Hughes545a0642011-11-08 19:10:03 -08005279 }
Ian Rogers50b35e22012-10-04 10:09:15 -07005280 JNIEnv* env = self->GetJniEnv();
Elliott Hughes545a0642011-11-08 19:10:03 -08005281 jbyteArray result = env->NewByteArray(bytes.size());
Ian Rogersc0542af2014-09-03 16:16:56 -07005282 if (result != nullptr) {
Elliott Hughes545a0642011-11-08 19:10:03 -08005283 env->SetByteArrayRegion(result, 0, bytes.size(), reinterpret_cast<const jbyte*>(&bytes[0]));
5284 }
5285 return result;
5286}
5287
Mathieu Chartiere401d142015-04-22 13:56:20 -07005288ArtMethod* DeoptimizationRequest::Method() const {
Andreas Gampe13b27842016-11-07 16:48:23 -08005289 return jni::DecodeArtMethod(method_);
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07005290}
5291
Mathieu Chartiere401d142015-04-22 13:56:20 -07005292void DeoptimizationRequest::SetMethod(ArtMethod* m) {
Andreas Gampe13b27842016-11-07 16:48:23 -08005293 method_ = jni::EncodeArtMethod(m);
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07005294}
5295
Mathieu Chartiera6b1ead2015-10-06 10:32:38 -07005296void Dbg::VisitRoots(RootVisitor* visitor) {
5297 // Visit breakpoint roots, used to prevent unloading of methods with breakpoints.
5298 ReaderMutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
5299 BufferedRootVisitor<128> root_visitor(visitor, RootInfo(kRootVMInternal));
5300 for (Breakpoint& breakpoint : gBreakpoints) {
Andreas Gampe542451c2016-07-26 09:02:02 -07005301 breakpoint.Method()->VisitRoots(root_visitor, kRuntimePointerSize);
Mathieu Chartiera6b1ead2015-10-06 10:32:38 -07005302 }
5303}
5304
Andreas Gampe04bbb5b2017-01-19 17:49:03 +00005305void Dbg::DbgThreadLifecycleCallback::ThreadStart(Thread* self) {
5306 Dbg::PostThreadStart(self);
5307}
5308
5309void Dbg::DbgThreadLifecycleCallback::ThreadDeath(Thread* self) {
5310 Dbg::PostThreadDeath(self);
5311}
5312
Andreas Gampe0f01b582017-01-18 15:22:37 -08005313void Dbg::DbgClassLoadCallback::ClassLoad(Handle<mirror::Class> klass ATTRIBUTE_UNUSED) {
5314 // Ignore ClassLoad;
5315}
5316void Dbg::DbgClassLoadCallback::ClassPrepare(Handle<mirror::Class> temp_klass ATTRIBUTE_UNUSED,
5317 Handle<mirror::Class> klass) {
5318 Dbg::PostClassPrepare(klass.Get());
5319}
5320
Elliott Hughes872d4ec2011-10-21 17:07:15 -07005321} // namespace art