blob: f504d86f7628c7a8b583b6c95406ebd7992c80c5 [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"
Andreas Gampef774a4e2017-07-06 22:15:18 -070032#include "base/strlcpy.h"
Vladimir Marko80afd022015-05-19 18:08:00 +010033#include "base/time_utils.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080034#include "class_linker-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -070035#include "class_linker.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070036#include "dex_file-inl.h"
David Sehr9323e6e2016-09-13 08:58:35 -070037#include "dex_file_annotations.h"
Andreas Gampee2abbc62017-09-15 11:59:26 -070038#include "dex_file_types.h"
Ian Rogers776ac1f2012-04-13 23:36:36 -070039#include "dex_instruction.h"
Mingyao Yang6ea1a0e2016-01-29 12:12:49 -080040#include "entrypoints/runtime_asm_entrypoints.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070041#include "gc/accounting/card_table-inl.h"
Man Cao8c2ff642015-05-27 17:25:30 -070042#include "gc/allocation_record.h"
Andreas Gampe94c589d2017-12-27 12:43:01 -080043#include "gc/gc_cause.h"
Mathieu Chartieraa516822015-10-02 15:53:37 -070044#include "gc/scoped_gc_critical_section.h"
Andreas Gampe0c183382017-07-13 22:26:24 -070045#include "gc/space/bump_pointer_space-walk-inl.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070046#include "gc/space/large_object_space.h"
47#include "gc/space/space-inl.h"
Andreas Gampe513061a2017-06-01 09:17:34 -070048#include "handle_scope-inl.h"
Sebastien Hertzcbc50642015-06-01 17:33:12 +020049#include "jdwp/jdwp_priv.h"
Elliott Hughes64f574f2013-02-20 14:57:12 -080050#include "jdwp/object_registry.h"
Andreas Gampe13b27842016-11-07 16:48:23 -080051#include "jni_internal.h"
Mathieu Chartier28bd2e42016-10-04 13:54:57 -070052#include "jvalue-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080053#include "mirror/class-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -070054#include "mirror/class.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080055#include "mirror/class_loader.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080056#include "mirror/object-inl.h"
57#include "mirror/object_array-inl.h"
Ian Rogersb0fa5dc2014-04-28 16:47:08 -070058#include "mirror/string-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080059#include "mirror/throwable.h"
Andreas Gampe373a9b52017-10-18 09:01:57 -070060#include "nativehelper/scoped_local_ref.h"
61#include "nativehelper/scoped_primitive_array.h"
Nicolas Geoffray58cc1cb2017-11-20 13:27:29 +000062#include "oat_file.h"
Mathieu Chartier3398c782016-09-30 10:27:43 -070063#include "obj_ptr-inl.h"
Ian Rogers53b8b092014-03-13 23:45:53 -070064#include "reflection.h"
Elliott Hughesa0e18062012-04-13 15:59:59 -070065#include "safe_map.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070066#include "scoped_thread_state_change-inl.h"
Andreas Gampe513061a2017-06-01 09:17:34 -070067#include "stack.h"
Elliott Hughes475fc232011-10-25 15:00:35 -070068#include "thread_list.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080069#include "utf.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070070#include "well_known_classes.h"
Elliott Hughes475fc232011-10-25 15:00:35 -070071
Elliott Hughes872d4ec2011-10-21 17:07:15 -070072namespace art {
73
Andreas Gampe46ee31b2016-12-14 10:11:49 -080074using android::base::StringPrintf;
75
Sebastien Hertz0462c4c2015-04-01 16:34:17 +020076// The key identifying the debugger to update instrumentation.
77static constexpr const char* kDbgInstrumentationKey = "Debugger";
78
Man Cao8c2ff642015-05-27 17:25:30 -070079// 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 -070080static uint16_t CappedAllocRecordCount(size_t alloc_record_count) {
Man Cao1ed11b92015-06-11 22:47:35 -070081 const size_t cap = 0xffff;
Man Cao8c2ff642015-05-27 17:25:30 -070082 if (alloc_record_count > cap) {
83 return cap;
Brian Carlstrom306db812014-09-05 13:01:41 -070084 }
85 return alloc_record_count;
86}
Elliott Hughes475fc232011-10-25 15:00:35 -070087
Mathieu Chartier41af5e52015-10-28 11:10:46 -070088class Breakpoint : public ValueObject {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -070089 public:
Mathieu Chartier41af5e52015-10-28 11:10:46 -070090 Breakpoint(ArtMethod* method, uint32_t dex_pc, DeoptimizationRequest::Kind deoptimization_kind)
Alex Light97e78032017-06-27 17:51:55 -070091 : method_(method->GetCanonicalMethod(kRuntimePointerSize)),
Mathieu Chartier41af5e52015-10-28 11:10:46 -070092 dex_pc_(dex_pc),
93 deoptimization_kind_(deoptimization_kind) {
Sebastien Hertzf3928792014-11-17 19:00:37 +010094 CHECK(deoptimization_kind_ == DeoptimizationRequest::kNothing ||
95 deoptimization_kind_ == DeoptimizationRequest::kSelectiveDeoptimization ||
96 deoptimization_kind_ == DeoptimizationRequest::kFullDeoptimization);
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -070097 }
98
Andreas Gampebdf7f1c2016-08-30 16:38:47 -070099 Breakpoint(const Breakpoint& other) REQUIRES_SHARED(Locks::mutator_lock_)
Mathieu Chartier41af5e52015-10-28 11:10:46 -0700100 : method_(other.method_),
101 dex_pc_(other.dex_pc_),
102 deoptimization_kind_(other.deoptimization_kind_) {}
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700103
Mathieu Chartier41af5e52015-10-28 11:10:46 -0700104 // Method() is called from root visiting, do not use ScopedObjectAccess here or it can cause
105 // GC to deadlock if another thread tries to call SuspendAll while the GC is in a runnable state.
106 ArtMethod* Method() const {
107 return method_;
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700108 }
109
110 uint32_t DexPc() const {
111 return dex_pc_;
112 }
113
Sebastien Hertzf3928792014-11-17 19:00:37 +0100114 DeoptimizationRequest::Kind GetDeoptimizationKind() const {
115 return deoptimization_kind_;
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700116 }
117
Alex Light6c8467f2015-11-20 15:03:26 -0800118 // Returns true if the method of this breakpoint and the passed in method should be considered the
119 // same. That is, they are either the same method or they are copied from the same method.
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700120 bool IsInMethod(ArtMethod* m) const REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light97e78032017-06-27 17:51:55 -0700121 return method_ == m->GetCanonicalMethod(kRuntimePointerSize);
Alex Light6c8467f2015-11-20 15:03:26 -0800122 }
123
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700124 private:
Sebastien Hertza76a6d42014-03-20 16:40:17 +0100125 // The location of this breakpoint.
Mathieu Chartier41af5e52015-10-28 11:10:46 -0700126 ArtMethod* method_;
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700127 uint32_t dex_pc_;
Sebastien Hertza76a6d42014-03-20 16:40:17 +0100128
129 // Indicates whether breakpoint needs full deoptimization or selective deoptimization.
Sebastien Hertzf3928792014-11-17 19:00:37 +0100130 DeoptimizationRequest::Kind deoptimization_kind_;
Elliott Hughes86964332012-02-15 19:37:42 -0800131};
132
Sebastien Hertzed2be172014-08-19 15:33:43 +0200133static std::ostream& operator<<(std::ostream& os, const Breakpoint& rhs)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700134 REQUIRES_SHARED(Locks::mutator_lock_) {
David Sehr709b0702016-10-13 09:12:37 -0700135 os << StringPrintf("Breakpoint[%s @%#x]", ArtMethod::PrettyMethod(rhs.Method()).c_str(),
136 rhs.DexPc());
Elliott Hughes86964332012-02-15 19:37:42 -0800137 return os;
138}
139
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200140class DebugInstrumentationListener FINAL : public instrumentation::InstrumentationListener {
Ian Rogers62d6c772013-02-27 08:32:07 -0800141 public:
142 DebugInstrumentationListener() {}
143 virtual ~DebugInstrumentationListener() {}
144
Alex Lightd7661582017-05-01 13:48:16 -0700145 void MethodEntered(Thread* thread,
146 Handle<mirror::Object> this_object,
147 ArtMethod* method,
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200148 uint32_t dex_pc)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700149 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800150 if (method->IsNative()) {
151 // TODO: post location events is a suspension point and native method entry stubs aren't.
152 return;
153 }
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200154 if (IsListeningToDexPcMoved()) {
155 // We also listen to kDexPcMoved instrumentation event so we know the DexPcMoved method is
156 // going to be called right after us. To avoid sending JDWP events twice for this location,
157 // we report the event in DexPcMoved. However, we must remind this is method entry so we
158 // send the METHOD_ENTRY event. And we can also group it with other events for this location
159 // like BREAKPOINT or SINGLE_STEP (or even METHOD_EXIT if this is a RETURN instruction).
160 thread->SetDebugMethodEntry();
161 } else if (IsListeningToMethodExit() && IsReturn(method, dex_pc)) {
162 // We also listen to kMethodExited instrumentation event and the current instruction is a
163 // RETURN so we know the MethodExited method is going to be called right after us. To avoid
164 // sending JDWP events twice for this location, we report the event(s) in MethodExited.
165 // However, we must remind this is method entry so we send the METHOD_ENTRY event. And we can
166 // also group it with other events for this location like BREAKPOINT or SINGLE_STEP.
167 thread->SetDebugMethodEntry();
168 } else {
Alex Lightd7661582017-05-01 13:48:16 -0700169 Dbg::UpdateDebugger(thread, this_object.Get(), method, 0, Dbg::kMethodEntry, nullptr);
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200170 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800171 }
172
Alex Lightd7661582017-05-01 13:48:16 -0700173 void MethodExited(Thread* thread,
174 Handle<mirror::Object> this_object,
175 ArtMethod* method,
176 uint32_t dex_pc,
177 const JValue& return_value)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700178 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800179 if (method->IsNative()) {
180 // TODO: post location events is a suspension point and native method entry stubs aren't.
181 return;
182 }
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200183 uint32_t events = Dbg::kMethodExit;
184 if (thread->IsDebugMethodEntry()) {
185 // It is also the method entry.
186 DCHECK(IsReturn(method, dex_pc));
187 events |= Dbg::kMethodEntry;
188 thread->ClearDebugMethodEntry();
189 }
Alex Lightd7661582017-05-01 13:48:16 -0700190 Dbg::UpdateDebugger(thread, this_object.Get(), method, dex_pc, events, &return_value);
Ian Rogers62d6c772013-02-27 08:32:07 -0800191 }
192
Alex Lightd7661582017-05-01 13:48:16 -0700193 void MethodUnwind(Thread* thread ATTRIBUTE_UNUSED,
194 Handle<mirror::Object> this_object ATTRIBUTE_UNUSED,
195 ArtMethod* method,
196 uint32_t dex_pc)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700197 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800198 // We're not recorded to listen to this kind of event, so complain.
David Sehr709b0702016-10-13 09:12:37 -0700199 LOG(ERROR) << "Unexpected method unwind event in debugger " << ArtMethod::PrettyMethod(method)
Sebastien Hertz51db44a2013-11-19 10:00:29 +0100200 << " " << dex_pc;
Ian Rogers62d6c772013-02-27 08:32:07 -0800201 }
202
Alex Lightd7661582017-05-01 13:48:16 -0700203 void DexPcMoved(Thread* thread,
204 Handle<mirror::Object> this_object,
205 ArtMethod* method,
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200206 uint32_t new_dex_pc)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700207 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200208 if (IsListeningToMethodExit() && IsReturn(method, new_dex_pc)) {
209 // We also listen to kMethodExited instrumentation event and the current instruction is a
210 // RETURN so we know the MethodExited method is going to be called right after us. Like in
211 // MethodEntered, we delegate event reporting to MethodExited.
212 // Besides, if this RETURN instruction is the only one in the method, we can send multiple
213 // JDWP events in the same packet: METHOD_ENTRY, METHOD_EXIT, BREAKPOINT and/or SINGLE_STEP.
214 // Therefore, we must not clear the debug method entry flag here.
215 } else {
216 uint32_t events = 0;
217 if (thread->IsDebugMethodEntry()) {
218 // It is also the method entry.
219 events = Dbg::kMethodEntry;
220 thread->ClearDebugMethodEntry();
221 }
Alex Lightd7661582017-05-01 13:48:16 -0700222 Dbg::UpdateDebugger(thread, this_object.Get(), method, new_dex_pc, events, nullptr);
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200223 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800224 }
225
Alex Lightd7661582017-05-01 13:48:16 -0700226 void FieldRead(Thread* thread ATTRIBUTE_UNUSED,
227 Handle<mirror::Object> this_object,
228 ArtMethod* method,
229 uint32_t dex_pc,
230 ArtField* field)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700231 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Lightd7661582017-05-01 13:48:16 -0700232 Dbg::PostFieldAccessEvent(method, dex_pc, this_object.Get(), field);
Ian Rogers62d6c772013-02-27 08:32:07 -0800233 }
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200234
Alex Lightd7661582017-05-01 13:48:16 -0700235 void FieldWritten(Thread* thread ATTRIBUTE_UNUSED,
236 Handle<mirror::Object> this_object,
237 ArtMethod* method,
238 uint32_t dex_pc,
239 ArtField* field,
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700240 const JValue& field_value)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700241 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Lightd7661582017-05-01 13:48:16 -0700242 Dbg::PostFieldModificationEvent(method, dex_pc, this_object.Get(), field, &field_value);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200243 }
244
Alex Light6e1607e2017-08-23 10:06:18 -0700245 void ExceptionThrown(Thread* thread ATTRIBUTE_UNUSED,
Alex Lightd7661582017-05-01 13:48:16 -0700246 Handle<mirror::Throwable> exception_object)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700247 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Lightd7661582017-05-01 13:48:16 -0700248 Dbg::PostException(exception_object.Get());
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200249 }
250
Nicolas Geoffray81f0f952016-01-20 16:25:19 +0000251 // We only care about branches in the Jit.
252 void Branch(Thread* /*thread*/, ArtMethod* method, uint32_t dex_pc, int32_t dex_pc_offset)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700253 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
David Sehr709b0702016-10-13 09:12:37 -0700254 LOG(ERROR) << "Unexpected branch event in debugger " << ArtMethod::PrettyMethod(method)
Nicolas Geoffray81f0f952016-01-20 16:25:19 +0000255 << " " << dex_pc << ", " << dex_pc_offset;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800256 }
257
Nicolas Geoffray5550ca82015-08-21 18:38:30 +0100258 // We only care about invokes in the Jit.
259 void InvokeVirtualOrInterface(Thread* thread ATTRIBUTE_UNUSED,
Alex Lightd7661582017-05-01 13:48:16 -0700260 Handle<mirror::Object> this_object ATTRIBUTE_UNUSED,
Nicolas Geoffray5550ca82015-08-21 18:38:30 +0100261 ArtMethod* method,
262 uint32_t dex_pc,
Alex Lightd7661582017-05-01 13:48:16 -0700263 ArtMethod* target ATTRIBUTE_UNUSED)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700264 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
David Sehr709b0702016-10-13 09:12:37 -0700265 LOG(ERROR) << "Unexpected invoke event in debugger " << ArtMethod::PrettyMethod(method)
Nicolas Geoffray5550ca82015-08-21 18:38:30 +0100266 << " " << dex_pc;
267 }
268
Alex Light798eab02017-08-23 12:54:53 -0700269 // TODO Might be worth it to post ExceptionCatch event.
270 void ExceptionHandled(Thread* thread ATTRIBUTE_UNUSED,
271 Handle<mirror::Throwable> throwable ATTRIBUTE_UNUSED) OVERRIDE {
272 LOG(ERROR) << "Unexpected exception handled event in debugger";
273 }
274
Alex Light05f47742017-09-14 00:34:44 +0000275 // TODO Might be worth it to implement this.
276 void WatchedFramePop(Thread* thread ATTRIBUTE_UNUSED,
277 const ShadowFrame& frame ATTRIBUTE_UNUSED) OVERRIDE {
278 LOG(ERROR) << "Unexpected WatchedFramePop event in debugger";
279 }
Alex Light798eab02017-08-23 12:54:53 -0700280
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200281 private:
Mathieu Chartier808c7a52017-12-15 11:19:33 -0800282 static bool IsReturn(ArtMethod* method, uint32_t dex_pc) REQUIRES_SHARED(Locks::mutator_lock_) {
283 return method->DexInstructions().InstructionAt(dex_pc).IsReturn();
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200284 }
285
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700286 static bool IsListeningToDexPcMoved() REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200287 return IsListeningTo(instrumentation::Instrumentation::kDexPcMoved);
288 }
289
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700290 static bool IsListeningToMethodExit() REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200291 return IsListeningTo(instrumentation::Instrumentation::kMethodExited);
292 }
293
294 static bool IsListeningTo(instrumentation::Instrumentation::InstrumentationEvent event)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700295 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200296 return (Dbg::GetInstrumentationEvents() & event) != 0;
297 }
298
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200299 DISALLOW_COPY_AND_ASSIGN(DebugInstrumentationListener);
Ian Rogers62d6c772013-02-27 08:32:07 -0800300} gDebugInstrumentationListener;
301
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700302// JDWP is allowed unless the Zygote forbids it.
303static bool gJdwpAllowed = true;
304
Elliott Hughesc0f09332012-03-26 13:27:06 -0700305// Was there a -Xrunjdwp or -agentlib:jdwp= argument on the command line?
Elliott Hughes3bb81562011-10-21 18:52:59 -0700306static bool gJdwpConfigured = false;
307
Sebastien Hertzb3b173b2015-02-06 09:16:32 +0100308// JDWP options for debugging. Only valid if IsJdwpConfigured() is true.
309static JDWP::JdwpOptions gJdwpOptions;
310
Elliott Hughes3bb81562011-10-21 18:52:59 -0700311// Runtime JDWP state.
Ian Rogersc0542af2014-09-03 16:16:56 -0700312static JDWP::JdwpState* gJdwpState = nullptr;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700313static bool gDebuggerConnected; // debugger or DDMS is connected.
Elliott Hughes3bb81562011-10-21 18:52:59 -0700314
Elliott Hughes47fce012011-10-25 18:37:19 -0700315static bool gDdmThreadNotification = false;
316
Elliott Hughes767a1472011-10-26 18:49:02 -0700317// DDMS GC-related settings.
318static Dbg::HpifWhen gDdmHpifWhen = Dbg::HPIF_WHEN_NEVER;
319static Dbg::HpsgWhen gDdmHpsgWhen = Dbg::HPSG_WHEN_NEVER;
320static Dbg::HpsgWhat gDdmHpsgWhat;
321static Dbg::HpsgWhen gDdmNhsgWhen = Dbg::HPSG_WHEN_NEVER;
322static Dbg::HpsgWhat gDdmNhsgWhat;
323
Daniel Mihalyieb076692014-08-22 17:33:31 +0200324bool Dbg::gDebuggerActive = false;
Sebastien Hertz4e5b2082015-03-24 19:03:40 +0100325bool Dbg::gDisposed = false;
Sebastien Hertz6995c602014-09-09 12:10:13 +0200326ObjectRegistry* Dbg::gRegistry = nullptr;
Alex Light21611932017-09-26 13:07:39 -0700327DebuggerActiveMethodInspectionCallback Dbg::gDebugActiveCallback;
Alex Light8c2b9292017-11-09 13:21:01 -0800328DebuggerDdmCallback Dbg::gDebugDdmCallback;
Alex Light40320712017-12-14 11:52:04 -0800329InternalDebuggerControlCallback Dbg::gDebuggerControlCallback;
Elliott Hughes475fc232011-10-25 15:00:35 -0700330
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100331// Deoptimization support.
Sebastien Hertz4d25df32014-03-21 17:44:46 +0100332std::vector<DeoptimizationRequest> Dbg::deoptimization_requests_;
333size_t Dbg::full_deoptimization_event_count_ = 0;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100334
Sebastien Hertz42cd43f2014-05-13 14:15:41 +0200335// Instrumentation event reference counters.
336size_t Dbg::dex_pc_change_event_ref_count_ = 0;
337size_t Dbg::method_enter_event_ref_count_ = 0;
338size_t Dbg::method_exit_event_ref_count_ = 0;
339size_t Dbg::field_read_event_ref_count_ = 0;
340size_t Dbg::field_write_event_ref_count_ = 0;
341size_t Dbg::exception_catch_event_ref_count_ = 0;
342uint32_t Dbg::instrumentation_events_ = 0;
343
Andreas Gampe04bbb5b2017-01-19 17:49:03 +0000344Dbg::DbgThreadLifecycleCallback Dbg::thread_lifecycle_callback_;
Andreas Gampe0f01b582017-01-18 15:22:37 -0800345Dbg::DbgClassLoadCallback Dbg::class_load_callback_;
Andreas Gampe04bbb5b2017-01-19 17:49:03 +0000346
Alex Light8c2b9292017-11-09 13:21:01 -0800347void DebuggerDdmCallback::DdmPublishChunk(uint32_t type, const ArrayRef<const uint8_t>& data) {
Alex Light772099a2017-11-21 14:05:04 -0800348 if (gJdwpState == nullptr) {
349 VLOG(jdwp) << "Debugger thread not active, ignoring DDM send: " << type;
350 } else {
351 iovec vec[1];
352 vec[0].iov_base = reinterpret_cast<void*>(const_cast<uint8_t*>(data.data()));
353 vec[0].iov_len = data.size();
354 gJdwpState->DdmSendChunkV(type, vec, 1);
355 }
Alex Light8c2b9292017-11-09 13:21:01 -0800356}
357
Alex Light21611932017-09-26 13:07:39 -0700358bool DebuggerActiveMethodInspectionCallback::IsMethodBeingInspected(ArtMethod* m ATTRIBUTE_UNUSED) {
359 return Dbg::IsDebuggerActive();
360}
361
Alex Light0fa17862017-10-24 13:43:05 -0700362bool DebuggerActiveMethodInspectionCallback::IsMethodSafeToJit(ArtMethod* m) {
363 return !Dbg::MethodHasAnyBreakpoints(m);
364}
365
Alex Light40320712017-12-14 11:52:04 -0800366void InternalDebuggerControlCallback::StartDebugger() {
367 // Release the mutator lock.
368 ScopedThreadStateChange stsc(art::Thread::Current(), kNative);
369 Dbg::StartJdwp();
370}
371
372void InternalDebuggerControlCallback::StopDebugger() {
373 Dbg::StopJdwp();
374}
375
376bool InternalDebuggerControlCallback::IsDebuggerConfigured() {
377 return Dbg::IsJdwpConfigured();
378}
379
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100380// Breakpoints.
jeffhao09bfc6a2012-12-11 18:11:43 -0800381static std::vector<Breakpoint> gBreakpoints GUARDED_BY(Locks::breakpoint_lock_);
Elliott Hughes86964332012-02-15 19:37:42 -0800382
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700383void DebugInvokeReq::VisitRoots(RootVisitor* visitor, const RootInfo& root_info) {
384 receiver.VisitRootIfNonNull(visitor, root_info); // null for static method call.
385 klass.VisitRoot(visitor, root_info);
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700386}
387
Sebastien Hertz597c4f02015-01-26 17:37:14 +0100388void SingleStepControl::AddDexPc(uint32_t dex_pc) {
389 dex_pcs_.insert(dex_pc);
Sebastien Hertzbb43b432014-04-14 11:59:08 +0200390}
391
Sebastien Hertz597c4f02015-01-26 17:37:14 +0100392bool SingleStepControl::ContainsDexPc(uint32_t dex_pc) const {
393 return dex_pcs_.find(dex_pc) == dex_pcs_.end();
Sebastien Hertzbb43b432014-04-14 11:59:08 +0200394}
395
Alex Light6c8467f2015-11-20 15:03:26 -0800396static bool IsBreakpoint(ArtMethod* m, uint32_t dex_pc)
Mathieu Chartier90443472015-07-16 20:32:27 -0700397 REQUIRES(!Locks::breakpoint_lock_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700398 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertzed2be172014-08-19 15:33:43 +0200399 ReaderMutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100400 for (size_t i = 0, e = gBreakpoints.size(); i < e; ++i) {
Alex Light6c8467f2015-11-20 15:03:26 -0800401 if (gBreakpoints[i].DexPc() == dex_pc && gBreakpoints[i].IsInMethod(m)) {
Elliott Hughes86964332012-02-15 19:37:42 -0800402 VLOG(jdwp) << "Hit breakpoint #" << i << ": " << gBreakpoints[i];
403 return true;
404 }
405 }
406 return false;
407}
408
Sebastien Hertz52d131d2014-03-13 16:17:40 +0100409static bool IsSuspendedForDebugger(ScopedObjectAccessUnchecked& soa, Thread* thread)
Mathieu Chartier90443472015-07-16 20:32:27 -0700410 REQUIRES(!Locks::thread_suspend_count_lock_) {
Elliott Hughes9e0c1752013-01-09 14:02:58 -0800411 MutexLock mu(soa.Self(), *Locks::thread_suspend_count_lock_);
412 // A thread may be suspended for GC; in this code, we really want to know whether
413 // there's a debugger suspension active.
414 return thread->IsSuspended() && thread->GetDebugSuspendCount() > 0;
415}
416
Ian Rogersc0542af2014-09-03 16:16:56 -0700417static mirror::Array* DecodeNonNullArray(JDWP::RefTypeId id, JDWP::JdwpError* error)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700418 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz6995c602014-09-09 12:10:13 +0200419 mirror::Object* o = Dbg::GetObjectRegistry()->Get<mirror::Object*>(id, error);
Ian Rogersc0542af2014-09-03 16:16:56 -0700420 if (o == nullptr) {
421 *error = JDWP::ERR_INVALID_OBJECT;
422 return nullptr;
Elliott Hughes436e3722012-02-17 20:01:47 -0800423 }
424 if (!o->IsArrayInstance()) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700425 *error = JDWP::ERR_INVALID_ARRAY;
426 return nullptr;
Elliott Hughes436e3722012-02-17 20:01:47 -0800427 }
Ian Rogersc0542af2014-09-03 16:16:56 -0700428 *error = JDWP::ERR_NONE;
Elliott Hughes436e3722012-02-17 20:01:47 -0800429 return o->AsArray();
430}
431
Ian Rogersc0542af2014-09-03 16:16:56 -0700432static mirror::Class* DecodeClass(JDWP::RefTypeId id, JDWP::JdwpError* error)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700433 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz6995c602014-09-09 12:10:13 +0200434 mirror::Object* o = Dbg::GetObjectRegistry()->Get<mirror::Object*>(id, error);
Ian Rogersc0542af2014-09-03 16:16:56 -0700435 if (o == nullptr) {
436 *error = JDWP::ERR_INVALID_OBJECT;
437 return nullptr;
Elliott Hughes436e3722012-02-17 20:01:47 -0800438 }
439 if (!o->IsClass()) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700440 *error = JDWP::ERR_INVALID_CLASS;
441 return nullptr;
Elliott Hughes436e3722012-02-17 20:01:47 -0800442 }
Ian Rogersc0542af2014-09-03 16:16:56 -0700443 *error = JDWP::ERR_NONE;
Elliott Hughes436e3722012-02-17 20:01:47 -0800444 return o->AsClass();
445}
446
Ian Rogersc0542af2014-09-03 16:16:56 -0700447static Thread* DecodeThread(ScopedObjectAccessUnchecked& soa, JDWP::ObjectId thread_id,
448 JDWP::JdwpError* error)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700449 REQUIRES_SHARED(Locks::mutator_lock_)
Mathieu Chartier90443472015-07-16 20:32:27 -0700450 REQUIRES(!Locks::thread_list_lock_, !Locks::thread_suspend_count_lock_) {
Sebastien Hertz6995c602014-09-09 12:10:13 +0200451 mirror::Object* thread_peer = Dbg::GetObjectRegistry()->Get<mirror::Object*>(thread_id, error);
Ian Rogersc0542af2014-09-03 16:16:56 -0700452 if (thread_peer == nullptr) {
Elliott Hughes221229c2013-01-08 18:17:50 -0800453 // This isn't even an object.
Ian Rogersc0542af2014-09-03 16:16:56 -0700454 *error = JDWP::ERR_INVALID_OBJECT;
455 return nullptr;
Elliott Hughes436e3722012-02-17 20:01:47 -0800456 }
Elliott Hughes221229c2013-01-08 18:17:50 -0800457
Mathieu Chartier0795f232016-09-27 18:43:30 -0700458 ObjPtr<mirror::Class> java_lang_Thread =
459 soa.Decode<mirror::Class>(WellKnownClasses::java_lang_Thread);
Elliott Hughes221229c2013-01-08 18:17:50 -0800460 if (!java_lang_Thread->IsAssignableFrom(thread_peer->GetClass())) {
461 // This isn't a thread.
Ian Rogersc0542af2014-09-03 16:16:56 -0700462 *error = JDWP::ERR_INVALID_THREAD;
463 return nullptr;
Elliott Hughes221229c2013-01-08 18:17:50 -0800464 }
465
Sebastien Hertz69206392015-04-07 15:54:25 +0200466 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogersc0542af2014-09-03 16:16:56 -0700467 Thread* thread = Thread::FromManagedThread(soa, thread_peer);
468 // If thread is null then this a java.lang.Thread without a Thread*. Must be a un-started or a
469 // zombie.
470 *error = (thread == nullptr) ? JDWP::ERR_THREAD_NOT_ALIVE : JDWP::ERR_NONE;
471 return thread;
Elliott Hughes436e3722012-02-17 20:01:47 -0800472}
473
Elliott Hughes24437992011-11-30 14:49:33 -0800474static JDWP::JdwpTag BasicTagFromDescriptor(const char* descriptor) {
475 // JDWP deliberately uses the descriptor characters' ASCII values for its enum.
476 // Note that by "basic" we mean that we don't get more specific than JT_OBJECT.
477 return static_cast<JDWP::JdwpTag>(descriptor[0]);
478}
479
Ian Rogers1ff3c982014-08-12 02:30:58 -0700480static JDWP::JdwpTag BasicTagFromClass(mirror::Class* klass)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700481 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers1ff3c982014-08-12 02:30:58 -0700482 std::string temp;
483 const char* descriptor = klass->GetDescriptor(&temp);
484 return BasicTagFromDescriptor(descriptor);
485}
486
Ian Rogers98379392014-02-24 16:53:16 -0800487static JDWP::JdwpTag TagFromClass(const ScopedObjectAccessUnchecked& soa, mirror::Class* c)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700488 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700489 CHECK(c != nullptr);
Elliott Hughes24437992011-11-30 14:49:33 -0800490 if (c->IsArrayClass()) {
491 return JDWP::JT_ARRAY;
492 }
Elliott Hughes24437992011-11-30 14:49:33 -0800493 if (c->IsStringClass()) {
494 return JDWP::JT_STRING;
Elliott Hughes24437992011-11-30 14:49:33 -0800495 }
Ian Rogers98379392014-02-24 16:53:16 -0800496 if (c->IsClassClass()) {
497 return JDWP::JT_CLASS_OBJECT;
498 }
499 {
Mathieu Chartier0795f232016-09-27 18:43:30 -0700500 ObjPtr<mirror::Class> thread_class =
501 soa.Decode<mirror::Class>(WellKnownClasses::java_lang_Thread);
Ian Rogers98379392014-02-24 16:53:16 -0800502 if (thread_class->IsAssignableFrom(c)) {
503 return JDWP::JT_THREAD;
504 }
505 }
506 {
Mathieu Chartier0795f232016-09-27 18:43:30 -0700507 ObjPtr<mirror::Class> thread_group_class =
508 soa.Decode<mirror::Class>(WellKnownClasses::java_lang_ThreadGroup);
Ian Rogers98379392014-02-24 16:53:16 -0800509 if (thread_group_class->IsAssignableFrom(c)) {
510 return JDWP::JT_THREAD_GROUP;
511 }
512 }
513 {
Mathieu Chartier0795f232016-09-27 18:43:30 -0700514 ObjPtr<mirror::Class> class_loader_class =
515 soa.Decode<mirror::Class>(WellKnownClasses::java_lang_ClassLoader);
Ian Rogers98379392014-02-24 16:53:16 -0800516 if (class_loader_class->IsAssignableFrom(c)) {
517 return JDWP::JT_CLASS_LOADER;
518 }
519 }
520 return JDWP::JT_OBJECT;
Elliott Hughes24437992011-11-30 14:49:33 -0800521}
522
523/*
524 * Objects declared to hold Object might actually hold a more specific
525 * type. The debugger may take a special interest in these (e.g. it
526 * wants to display the contents of Strings), so we want to return an
527 * appropriate tag.
528 *
529 * Null objects are tagged JT_OBJECT.
530 */
Sebastien Hertz6995c602014-09-09 12:10:13 +0200531JDWP::JdwpTag Dbg::TagFromObject(const ScopedObjectAccessUnchecked& soa, mirror::Object* o) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700532 return (o == nullptr) ? JDWP::JT_OBJECT : TagFromClass(soa, o->GetClass());
Elliott Hughes24437992011-11-30 14:49:33 -0800533}
534
535static bool IsPrimitiveTag(JDWP::JdwpTag tag) {
536 switch (tag) {
537 case JDWP::JT_BOOLEAN:
538 case JDWP::JT_BYTE:
539 case JDWP::JT_CHAR:
540 case JDWP::JT_FLOAT:
541 case JDWP::JT_DOUBLE:
542 case JDWP::JT_INT:
543 case JDWP::JT_LONG:
544 case JDWP::JT_SHORT:
545 case JDWP::JT_VOID:
546 return true;
547 default:
548 return false;
549 }
550}
551
Sebastien Hertzb3b173b2015-02-06 09:16:32 +0100552void Dbg::StartJdwp() {
Elliott Hughesc0f09332012-03-26 13:27:06 -0700553 if (!gJdwpAllowed || !IsJdwpConfigured()) {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700554 // No JDWP for you!
555 return;
556 }
557
Ian Rogers719d1a32014-03-06 12:13:39 -0800558 CHECK(gRegistry == nullptr);
Elliott Hughes475fc232011-10-25 15:00:35 -0700559 gRegistry = new ObjectRegistry;
560
Alex Light8c2b9292017-11-09 13:21:01 -0800561 {
562 // Setup the Ddm listener
563 ScopedObjectAccess soa(Thread::Current());
564 Runtime::Current()->GetRuntimeCallbacks()->AddDdmCallback(&gDebugDdmCallback);
565 }
566
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700567 // Init JDWP if the debugger is enabled. This may connect out to a
568 // debugger, passively listen for a debugger, or block waiting for a
569 // debugger.
Sebastien Hertzb3b173b2015-02-06 09:16:32 +0100570 gJdwpState = JDWP::JdwpState::Create(&gJdwpOptions);
Ian Rogersc0542af2014-09-03 16:16:56 -0700571 if (gJdwpState == nullptr) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -0800572 // We probably failed because some other process has the port already, which means that
573 // if we don't abort the user is likely to think they're talking to us when they're actually
574 // talking to that other process.
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800575 LOG(FATAL) << "Debugger thread failed to initialize";
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700576 }
577
578 // If a debugger has already attached, send the "welcome" message.
579 // This may cause us to suspend all threads.
Elliott Hughes376a7a02011-10-24 18:35:55 -0700580 if (gJdwpState->IsActive()) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700581 ScopedObjectAccess soa(Thread::Current());
Sebastien Hertz7d955652014-10-22 10:57:10 +0200582 gJdwpState->PostVMStart();
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700583 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700584}
585
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700586void Dbg::StopJdwp() {
Sebastien Hertzc6345ef2014-08-18 19:26:39 +0200587 // Post VM_DEATH event before the JDWP connection is closed (either by the JDWP thread or the
588 // destruction of gJdwpState).
589 if (gJdwpState != nullptr && gJdwpState->IsActive()) {
590 gJdwpState->PostVMDeath();
591 }
Sebastien Hertz0376e6b2014-02-06 18:12:59 +0100592 // Prevent the JDWP thread from processing JDWP incoming packets after we close the connection.
Sebastien Hertz4e5b2082015-03-24 19:03:40 +0100593 Dispose();
Elliott Hughes376a7a02011-10-24 18:35:55 -0700594 delete gJdwpState;
Ian Rogers719d1a32014-03-06 12:13:39 -0800595 gJdwpState = nullptr;
Elliott Hughes475fc232011-10-25 15:00:35 -0700596 delete gRegistry;
Ian Rogers719d1a32014-03-06 12:13:39 -0800597 gRegistry = nullptr;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700598}
599
Elliott Hughes767a1472011-10-26 18:49:02 -0700600void Dbg::GcDidFinish() {
601 if (gDdmHpifWhen != HPIF_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700602 ScopedObjectAccess soa(Thread::Current());
Brian Carlstrom4d466a82014-05-08 19:05:29 -0700603 VLOG(jdwp) << "Sending heap info to DDM";
Elliott Hughes7162ad92011-10-27 14:08:42 -0700604 DdmSendHeapInfo(gDdmHpifWhen);
Elliott Hughes767a1472011-10-26 18:49:02 -0700605 }
606 if (gDdmHpsgWhen != HPSG_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700607 ScopedObjectAccess soa(Thread::Current());
Brian Carlstrom4d466a82014-05-08 19:05:29 -0700608 VLOG(jdwp) << "Dumping heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700609 DdmSendHeapSegments(false);
Elliott Hughes767a1472011-10-26 18:49:02 -0700610 }
611 if (gDdmNhsgWhen != HPSG_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700612 ScopedObjectAccess soa(Thread::Current());
Brian Carlstrom4d466a82014-05-08 19:05:29 -0700613 VLOG(jdwp) << "Dumping native heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700614 DdmSendHeapSegments(true);
Elliott Hughes767a1472011-10-26 18:49:02 -0700615 }
616}
617
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700618void Dbg::SetJdwpAllowed(bool allowed) {
619 gJdwpAllowed = allowed;
620}
621
Leonard Mosescueb842212016-10-06 17:26:36 -0700622bool Dbg::IsJdwpAllowed() {
623 return gJdwpAllowed;
624}
625
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700626DebugInvokeReq* Dbg::GetInvokeReq() {
Elliott Hughes475fc232011-10-25 15:00:35 -0700627 return Thread::Current()->GetInvokeReq();
628}
629
630Thread* Dbg::GetDebugThread() {
Ian Rogersc0542af2014-09-03 16:16:56 -0700631 return (gJdwpState != nullptr) ? gJdwpState->GetDebugThread() : nullptr;
Elliott Hughes475fc232011-10-25 15:00:35 -0700632}
633
634void Dbg::ClearWaitForEventThread() {
Sebastien Hertz2bf93f42015-01-09 18:44:05 +0100635 gJdwpState->ReleaseJdwpTokenForEvent();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700636}
637
638void Dbg::Connected() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700639 CHECK(!gDebuggerConnected);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800640 VLOG(jdwp) << "JDWP has attached";
Elliott Hughes3bb81562011-10-21 18:52:59 -0700641 gDebuggerConnected = true;
Elliott Hughes86964332012-02-15 19:37:42 -0800642 gDisposed = false;
643}
644
Sebastien Hertzf3928792014-11-17 19:00:37 +0100645bool Dbg::RequiresDeoptimization() {
646 // We don't need deoptimization if everything runs with interpreter after
647 // enabling -Xint mode.
648 return !Runtime::Current()->GetInstrumentation()->IsForcedInterpretOnly();
649}
650
Elliott Hughesa2155262011-11-16 16:26:58 -0800651void Dbg::GoActive() {
652 // Enable all debugging features, including scans for breakpoints.
653 // This is a no-op if we're already active.
654 // Only called from the JDWP handler thread.
Daniel Mihalyieb076692014-08-22 17:33:31 +0200655 if (IsDebuggerActive()) {
Elliott Hughesa2155262011-11-16 16:26:58 -0800656 return;
657 }
658
Mathieu Chartieraa516822015-10-02 15:53:37 -0700659 Thread* const self = Thread::Current();
Elliott Hughesc0f09332012-03-26 13:27:06 -0700660 {
661 // TODO: dalvik only warned if there were breakpoints left over. clear in Dbg::Disconnected?
Mathieu Chartieraa516822015-10-02 15:53:37 -0700662 ReaderMutexLock mu(self, *Locks::breakpoint_lock_);
Elliott Hughesc0f09332012-03-26 13:27:06 -0700663 CHECK_EQ(gBreakpoints.size(), 0U);
664 }
Elliott Hughesa2155262011-11-16 16:26:58 -0800665
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100666 {
Mathieu Chartieraa516822015-10-02 15:53:37 -0700667 MutexLock mu(self, *Locks::deoptimization_lock_);
Sebastien Hertz4d25df32014-03-21 17:44:46 +0100668 CHECK_EQ(deoptimization_requests_.size(), 0U);
669 CHECK_EQ(full_deoptimization_event_count_, 0U);
Sebastien Hertz42cd43f2014-05-13 14:15:41 +0200670 CHECK_EQ(dex_pc_change_event_ref_count_, 0U);
671 CHECK_EQ(method_enter_event_ref_count_, 0U);
672 CHECK_EQ(method_exit_event_ref_count_, 0U);
673 CHECK_EQ(field_read_event_ref_count_, 0U);
674 CHECK_EQ(field_write_event_ref_count_, 0U);
675 CHECK_EQ(exception_catch_event_ref_count_, 0U);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100676 }
677
Ian Rogers62d6c772013-02-27 08:32:07 -0800678 Runtime* runtime = Runtime::Current();
Nicolas Geoffray433b79a2017-01-30 20:54:45 +0000679 // Best effort deoptimization if the runtime is non-Java debuggable. This happens when
680 // ro.debuggable is set, but the application is not debuggable, or when a standalone
681 // dalvikvm invocation is not passed the debuggable option (-Xcompiler-option --debuggable).
682 //
683 // The performance cost of this is non-negligible during native-debugging due to the
David Srbeckyf4480162016-03-16 00:06:24 +0000684 // forced JIT, so we keep the AOT code in that case in exchange for limited native debugging.
Nicolas Geoffray433b79a2017-01-30 20:54:45 +0000685 if (!runtime->IsJavaDebuggable() &&
686 !runtime->GetInstrumentation()->IsForcedInterpretOnly() &&
687 !runtime->IsNativeDebuggable()) {
688 runtime->DeoptimizeBootImage();
Mingyao Yang6ea1a0e2016-01-29 12:12:49 -0800689 }
690
Mathieu Chartier4f55e222015-09-04 13:26:21 -0700691 ScopedSuspendAll ssa(__FUNCTION__);
Sebastien Hertzf3928792014-11-17 19:00:37 +0100692 if (RequiresDeoptimization()) {
693 runtime->GetInstrumentation()->EnableDeoptimization();
694 }
Sebastien Hertz42cd43f2014-05-13 14:15:41 +0200695 instrumentation_events_ = 0;
Elliott Hughesa2155262011-11-16 16:26:58 -0800696 gDebuggerActive = true;
Alex Light21611932017-09-26 13:07:39 -0700697 Runtime::Current()->GetRuntimeCallbacks()->AddMethodInspectionCallback(&gDebugActiveCallback);
Ian Rogers62d6c772013-02-27 08:32:07 -0800698 LOG(INFO) << "Debugger is active";
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700699}
700
701void Dbg::Disconnected() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700702 CHECK(gDebuggerConnected);
703
Elliott Hughesc0f09332012-03-26 13:27:06 -0700704 LOG(INFO) << "Debugger is no longer active";
Elliott Hughes234ab152011-10-26 14:02:26 -0700705
Hiroshi Yamauchi98810e32016-05-24 14:55:40 -0700706 // Suspend all threads and exclusively acquire the mutator lock. Remove the debugger as a listener
Ian Rogers62d6c772013-02-27 08:32:07 -0800707 // and clear the object registry.
708 Runtime* runtime = Runtime::Current();
Ian Rogers62d6c772013-02-27 08:32:07 -0800709 Thread* self = Thread::Current();
Mathieu Chartier4f55e222015-09-04 13:26:21 -0700710 {
Mathieu Chartieraa516822015-10-02 15:53:37 -0700711 // Required for DisableDeoptimization.
712 gc::ScopedGCCriticalSection gcs(self,
713 gc::kGcCauseInstrumentation,
714 gc::kCollectorTypeInstrumentation);
Mathieu Chartier4f55e222015-09-04 13:26:21 -0700715 ScopedSuspendAll ssa(__FUNCTION__);
Mathieu Chartier4f55e222015-09-04 13:26:21 -0700716 // Debugger may not be active at this point.
717 if (IsDebuggerActive()) {
718 {
719 // Since we're going to disable deoptimization, we clear the deoptimization requests queue.
720 // This prevents us from having any pending deoptimization request when the debugger attaches
721 // to us again while no event has been requested yet.
Mathieu Chartiera6b1ead2015-10-06 10:32:38 -0700722 MutexLock mu(self, *Locks::deoptimization_lock_);
Mathieu Chartier4f55e222015-09-04 13:26:21 -0700723 deoptimization_requests_.clear();
724 full_deoptimization_event_count_ = 0U;
725 }
726 if (instrumentation_events_ != 0) {
727 runtime->GetInstrumentation()->RemoveListener(&gDebugInstrumentationListener,
728 instrumentation_events_);
729 instrumentation_events_ = 0;
730 }
731 if (RequiresDeoptimization()) {
732 runtime->GetInstrumentation()->DisableDeoptimization(kDbgInstrumentationKey);
733 }
734 gDebuggerActive = false;
Alex Light21611932017-09-26 13:07:39 -0700735 Runtime::Current()->GetRuntimeCallbacks()->RemoveMethodInspectionCallback(
736 &gDebugActiveCallback);
Sebastien Hertzaaea7342014-02-25 15:10:04 +0100737 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100738 }
Sebastien Hertz55f65342015-01-13 22:48:34 +0100739
740 {
741 ScopedObjectAccess soa(self);
742 gRegistry->Clear();
743 }
744
745 gDebuggerConnected = false;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700746}
747
Sebastien Hertzb3b173b2015-02-06 09:16:32 +0100748void Dbg::ConfigureJdwp(const JDWP::JdwpOptions& jdwp_options) {
749 CHECK_NE(jdwp_options.transport, JDWP::kJdwpTransportUnknown);
750 gJdwpOptions = jdwp_options;
751 gJdwpConfigured = true;
Alex Light40320712017-12-14 11:52:04 -0800752 Runtime::Current()->GetRuntimeCallbacks()->AddDebuggerControlCallback(&gDebuggerControlCallback);
Sebastien Hertzb3b173b2015-02-06 09:16:32 +0100753}
754
Elliott Hughesc0f09332012-03-26 13:27:06 -0700755bool Dbg::IsJdwpConfigured() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700756 return gJdwpConfigured;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700757}
758
759int64_t Dbg::LastDebuggerActivity() {
Elliott Hughesca951522011-12-05 12:01:32 -0800760 return gJdwpState->LastDebuggerActivity();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700761}
762
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700763void Dbg::UndoDebuggerSuspensions() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700764 Runtime::Current()->GetThreadList()->UndoDebuggerSuspensions();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700765}
766
Elliott Hughes88d63092013-01-09 09:55:54 -0800767std::string Dbg::GetClassName(JDWP::RefTypeId class_id) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700768 JDWP::JdwpError error;
769 mirror::Object* o = gRegistry->Get<mirror::Object*>(class_id, &error);
770 if (o == nullptr) {
771 if (error == JDWP::ERR_NONE) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700772 return "null";
Ian Rogersc0542af2014-09-03 16:16:56 -0700773 } else {
774 return StringPrintf("invalid object %p", reinterpret_cast<void*>(class_id));
775 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800776 }
777 if (!o->IsClass()) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700778 return StringPrintf("non-class %p", o); // This is only used for debugging output anyway.
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800779 }
Sebastien Hertz6995c602014-09-09 12:10:13 +0200780 return GetClassName(o->AsClass());
781}
782
783std::string Dbg::GetClassName(mirror::Class* klass) {
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +0200784 if (klass == nullptr) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700785 return "null";
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +0200786 }
Ian Rogers1ff3c982014-08-12 02:30:58 -0700787 std::string temp;
Sebastien Hertz6995c602014-09-09 12:10:13 +0200788 return DescriptorToName(klass->GetDescriptor(&temp));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700789}
790
Ian Rogersc0542af2014-09-03 16:16:56 -0700791JDWP::JdwpError Dbg::GetClassObject(JDWP::RefTypeId id, JDWP::ObjectId* class_object_id) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800792 JDWP::JdwpError status;
Ian Rogersc0542af2014-09-03 16:16:56 -0700793 mirror::Class* c = DecodeClass(id, &status);
794 if (c == nullptr) {
795 *class_object_id = 0;
Elliott Hughes436e3722012-02-17 20:01:47 -0800796 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800797 }
Ian Rogersc0542af2014-09-03 16:16:56 -0700798 *class_object_id = gRegistry->Add(c);
Elliott Hughes436e3722012-02-17 20:01:47 -0800799 return JDWP::ERR_NONE;
Elliott Hughes86964332012-02-15 19:37:42 -0800800}
801
Ian Rogersc0542af2014-09-03 16:16:56 -0700802JDWP::JdwpError Dbg::GetSuperclass(JDWP::RefTypeId id, JDWP::RefTypeId* superclass_id) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800803 JDWP::JdwpError status;
Ian Rogersc0542af2014-09-03 16:16:56 -0700804 mirror::Class* c = DecodeClass(id, &status);
805 if (c == nullptr) {
806 *superclass_id = 0;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800807 return status;
808 }
809 if (c->IsInterface()) {
810 // http://code.google.com/p/android/issues/detail?id=20856
Ian Rogersc0542af2014-09-03 16:16:56 -0700811 *superclass_id = 0;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800812 } else {
Ian Rogersc0542af2014-09-03 16:16:56 -0700813 *superclass_id = gRegistry->Add(c->GetSuperClass());
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800814 }
815 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700816}
817
Elliott Hughes436e3722012-02-17 20:01:47 -0800818JDWP::JdwpError Dbg::GetClassLoader(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700819 JDWP::JdwpError error;
Andreas Gampe7929a482015-12-30 19:33:49 -0800820 mirror::Class* c = DecodeClass(id, &error);
821 if (c == nullptr) {
822 return error;
Elliott Hughes436e3722012-02-17 20:01:47 -0800823 }
Andreas Gampe7929a482015-12-30 19:33:49 -0800824 expandBufAddObjectId(pReply, gRegistry->Add(c->GetClassLoader()));
Elliott Hughes436e3722012-02-17 20:01:47 -0800825 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700826}
827
Elliott Hughes436e3722012-02-17 20:01:47 -0800828JDWP::JdwpError Dbg::GetModifiers(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700829 JDWP::JdwpError error;
830 mirror::Class* c = DecodeClass(id, &error);
831 if (c == nullptr) {
832 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800833 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800834
835 uint32_t access_flags = c->GetAccessFlags() & kAccJavaFlagsMask;
836
Yevgeny Roubande34eea2014-02-15 01:06:03 +0700837 // Set ACC_SUPER. Dex files don't contain this flag but only classes are supposed to have it set,
838 // not interfaces.
Elliott Hughes436e3722012-02-17 20:01:47 -0800839 // Class.getModifiers doesn't return it, but JDWP does, so we set it here.
Yevgeny Roubande34eea2014-02-15 01:06:03 +0700840 if ((access_flags & kAccInterface) == 0) {
841 access_flags |= kAccSuper;
842 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800843
844 expandBufAdd4BE(pReply, access_flags);
845
846 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700847}
848
Ian Rogersc0542af2014-09-03 16:16:56 -0700849JDWP::JdwpError Dbg::GetMonitorInfo(JDWP::ObjectId object_id, JDWP::ExpandBuf* reply) {
850 JDWP::JdwpError error;
851 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
852 if (o == nullptr) {
Elliott Hughesf327e072013-01-09 16:01:26 -0800853 return JDWP::ERR_INVALID_OBJECT;
854 }
855
856 // Ensure all threads are suspended while we read objects' lock words.
857 Thread* self = Thread::Current();
Sebastien Hertz54263242014-03-19 18:16:50 +0100858 CHECK_EQ(self->GetState(), kRunnable);
Elliott Hughesf327e072013-01-09 16:01:26 -0800859
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700860 MonitorInfo monitor_info;
861 {
862 ScopedThreadSuspension sts(self, kSuspended);
Mathieu Chartier4f55e222015-09-04 13:26:21 -0700863 ScopedSuspendAll ssa(__FUNCTION__);
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700864 monitor_info = MonitorInfo(o);
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700865 }
Ian Rogersc0542af2014-09-03 16:16:56 -0700866 if (monitor_info.owner_ != nullptr) {
Nicolas Geoffraycafa0812017-02-15 18:27:34 +0000867 expandBufAddObjectId(reply, gRegistry->Add(monitor_info.owner_->GetPeerFromOtherThread()));
Elliott Hughesf327e072013-01-09 16:01:26 -0800868 } else {
Ian Rogersc0542af2014-09-03 16:16:56 -0700869 expandBufAddObjectId(reply, gRegistry->Add(nullptr));
Elliott Hughesf327e072013-01-09 16:01:26 -0800870 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700871 expandBufAdd4BE(reply, monitor_info.entry_count_);
872 expandBufAdd4BE(reply, monitor_info.waiters_.size());
873 for (size_t i = 0; i < monitor_info.waiters_.size(); ++i) {
Nicolas Geoffraycafa0812017-02-15 18:27:34 +0000874 expandBufAddObjectId(reply, gRegistry->Add(monitor_info.waiters_[i]->GetPeerFromOtherThread()));
Elliott Hughesf327e072013-01-09 16:01:26 -0800875 }
876 return JDWP::ERR_NONE;
877}
878
Elliott Hughes734b8c62013-01-11 15:32:45 -0800879JDWP::JdwpError Dbg::GetOwnedMonitors(JDWP::ObjectId thread_id,
Ian Rogersc0542af2014-09-03 16:16:56 -0700880 std::vector<JDWP::ObjectId>* monitors,
881 std::vector<uint32_t>* stack_depths) {
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800882 struct OwnedMonitorVisitor : public StackVisitor {
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700883 OwnedMonitorVisitor(Thread* thread, Context* context,
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -0700884 std::vector<JDWP::ObjectId>* monitor_vector,
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700885 std::vector<uint32_t>* stack_depth_vector)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700886 REQUIRES_SHARED(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +0100887 : StackVisitor(thread, context, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
888 current_stack_depth(0),
889 monitors(monitor_vector),
890 stack_depths(stack_depth_vector) {}
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800891
892 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
893 // annotalysis.
894 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
895 if (!GetMethod()->IsRuntimeMethod()) {
896 Monitor::VisitLocks(this, AppendOwnedMonitors, this);
Elliott Hughes734b8c62013-01-11 15:32:45 -0800897 ++current_stack_depth;
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800898 }
899 return true;
900 }
901
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -0700902 static void AppendOwnedMonitors(mirror::Object* owned_monitor, void* arg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700903 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers7a22fa62013-01-23 12:16:16 -0800904 OwnedMonitorVisitor* visitor = reinterpret_cast<OwnedMonitorVisitor*>(arg);
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -0700905 visitor->monitors->push_back(gRegistry->Add(owned_monitor));
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700906 visitor->stack_depths->push_back(visitor->current_stack_depth);
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800907 }
908
Elliott Hughes734b8c62013-01-11 15:32:45 -0800909 size_t current_stack_depth;
Ian Rogersc0542af2014-09-03 16:16:56 -0700910 std::vector<JDWP::ObjectId>* const monitors;
911 std::vector<uint32_t>* const stack_depths;
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800912 };
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800913
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700914 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz69206392015-04-07 15:54:25 +0200915 JDWP::JdwpError error;
916 Thread* thread = DecodeThread(soa, thread_id, &error);
917 if (thread == nullptr) {
918 return error;
919 }
920 if (!IsSuspendedForDebugger(soa, thread)) {
921 return JDWP::ERR_THREAD_NOT_SUSPENDED;
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700922 }
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -0700923 std::unique_ptr<Context> context(Context::Create());
Ian Rogersc0542af2014-09-03 16:16:56 -0700924 OwnedMonitorVisitor visitor(thread, context.get(), monitors, stack_depths);
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -0700925 visitor.WalkStack();
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800926 return JDWP::ERR_NONE;
927}
928
Sebastien Hertz52d131d2014-03-13 16:17:40 +0100929JDWP::JdwpError Dbg::GetContendedMonitor(JDWP::ObjectId thread_id,
Ian Rogersc0542af2014-09-03 16:16:56 -0700930 JDWP::ObjectId* contended_monitor) {
Elliott Hughesf9501702013-01-11 11:22:27 -0800931 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -0700932 *contended_monitor = 0;
Sebastien Hertz69206392015-04-07 15:54:25 +0200933 JDWP::JdwpError error;
934 Thread* thread = DecodeThread(soa, thread_id, &error);
935 if (thread == nullptr) {
936 return error;
Elliott Hughesf9501702013-01-11 11:22:27 -0800937 }
Sebastien Hertz69206392015-04-07 15:54:25 +0200938 if (!IsSuspendedForDebugger(soa, thread)) {
939 return JDWP::ERR_THREAD_NOT_SUSPENDED;
940 }
941 mirror::Object* contended_monitor_obj = Monitor::GetContendedMonitor(thread);
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700942 // Add() requires the thread_list_lock_ not held to avoid the lock
943 // level violation.
Ian Rogersc0542af2014-09-03 16:16:56 -0700944 *contended_monitor = gRegistry->Add(contended_monitor_obj);
Elliott Hughesf9501702013-01-11 11:22:27 -0800945 return JDWP::ERR_NONE;
946}
947
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800948JDWP::JdwpError Dbg::GetInstanceCounts(const std::vector<JDWP::RefTypeId>& class_ids,
Ian Rogersc0542af2014-09-03 16:16:56 -0700949 std::vector<uint64_t>* counts) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800950 gc::Heap* heap = Runtime::Current()->GetHeap();
Andreas Gampe94c589d2017-12-27 12:43:01 -0800951 heap->CollectGarbage(false, gc::GcCause::kGcCauseDebugger);
Mathieu Chartiere8a3c572016-10-11 16:52:17 -0700952 VariableSizedHandleScope hs(Thread::Current());
Mathieu Chartier9d156d52016-10-06 17:44:26 -0700953 std::vector<Handle<mirror::Class>> classes;
Ian Rogersc0542af2014-09-03 16:16:56 -0700954 counts->clear();
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800955 for (size_t i = 0; i < class_ids.size(); ++i) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700956 JDWP::JdwpError error;
Mathieu Chartier9d156d52016-10-06 17:44:26 -0700957 ObjPtr<mirror::Class> c = DecodeClass(class_ids[i], &error);
Ian Rogersc0542af2014-09-03 16:16:56 -0700958 if (c == nullptr) {
959 return error;
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800960 }
Mathieu Chartier9d156d52016-10-06 17:44:26 -0700961 classes.push_back(hs.NewHandle(c));
Ian Rogersc0542af2014-09-03 16:16:56 -0700962 counts->push_back(0);
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800963 }
Ian Rogersc0542af2014-09-03 16:16:56 -0700964 heap->CountInstances(classes, false, &(*counts)[0]);
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800965 return JDWP::ERR_NONE;
966}
967
Ian Rogersc0542af2014-09-03 16:16:56 -0700968JDWP::JdwpError Dbg::GetInstances(JDWP::RefTypeId class_id, int32_t max_count,
969 std::vector<JDWP::ObjectId>* instances) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800970 gc::Heap* heap = Runtime::Current()->GetHeap();
971 // We only want reachable instances, so do a GC.
Andreas Gampe94c589d2017-12-27 12:43:01 -0800972 heap->CollectGarbage(false, gc::GcCause::kGcCauseDebugger);
Ian Rogersc0542af2014-09-03 16:16:56 -0700973 JDWP::JdwpError error;
Mathieu Chartier9d156d52016-10-06 17:44:26 -0700974 ObjPtr<mirror::Class> c = DecodeClass(class_id, &error);
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800975 if (c == nullptr) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700976 return error;
Elliott Hughes3b78c942013-01-15 17:35:41 -0800977 }
Mathieu Chartier2d855952016-10-12 19:37:59 -0700978 VariableSizedHandleScope hs(Thread::Current());
979 std::vector<Handle<mirror::Object>> raw_instances;
Richard Uhler660be6f2017-11-22 16:12:29 +0000980 Runtime::Current()->GetHeap()->GetInstances(hs,
981 hs.NewHandle(c),
982 /* use_is_assignable_from */ false,
983 max_count,
984 raw_instances);
Elliott Hughes3b78c942013-01-15 17:35:41 -0800985 for (size_t i = 0; i < raw_instances.size(); ++i) {
Mathieu Chartier2d855952016-10-12 19:37:59 -0700986 instances->push_back(gRegistry->Add(raw_instances[i].Get()));
Elliott Hughes3b78c942013-01-15 17:35:41 -0800987 }
988 return JDWP::ERR_NONE;
989}
990
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800991JDWP::JdwpError Dbg::GetReferringObjects(JDWP::ObjectId object_id, int32_t max_count,
Ian Rogersc0542af2014-09-03 16:16:56 -0700992 std::vector<JDWP::ObjectId>* referring_objects) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800993 gc::Heap* heap = Runtime::Current()->GetHeap();
Andreas Gampe94c589d2017-12-27 12:43:01 -0800994 heap->CollectGarbage(false, gc::GcCause::kGcCauseDebugger);
Ian Rogersc0542af2014-09-03 16:16:56 -0700995 JDWP::JdwpError error;
Mathieu Chartier9d156d52016-10-06 17:44:26 -0700996 ObjPtr<mirror::Object> o = gRegistry->Get<mirror::Object*>(object_id, &error);
Ian Rogersc0542af2014-09-03 16:16:56 -0700997 if (o == nullptr) {
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800998 return JDWP::ERR_INVALID_OBJECT;
999 }
Mathieu Chartieraea9bfb2016-10-12 19:19:56 -07001000 VariableSizedHandleScope hs(Thread::Current());
1001 std::vector<Handle<mirror::Object>> raw_instances;
1002 heap->GetReferringObjects(hs, hs.NewHandle(o), max_count, raw_instances);
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001003 for (size_t i = 0; i < raw_instances.size(); ++i) {
Mathieu Chartieraea9bfb2016-10-12 19:19:56 -07001004 referring_objects->push_back(gRegistry->Add(raw_instances[i].Get()));
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001005 }
1006 return JDWP::ERR_NONE;
1007}
1008
Ian Rogersc0542af2014-09-03 16:16:56 -07001009JDWP::JdwpError Dbg::DisableCollection(JDWP::ObjectId object_id) {
1010 JDWP::JdwpError error;
1011 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
1012 if (o == nullptr) {
Sebastien Hertze96060a2013-12-11 12:06:28 +01001013 return JDWP::ERR_INVALID_OBJECT;
1014 }
Elliott Hughes64f574f2013-02-20 14:57:12 -08001015 gRegistry->DisableCollection(object_id);
1016 return JDWP::ERR_NONE;
1017}
1018
Ian Rogersc0542af2014-09-03 16:16:56 -07001019JDWP::JdwpError Dbg::EnableCollection(JDWP::ObjectId object_id) {
1020 JDWP::JdwpError error;
1021 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
Sebastien Hertze96060a2013-12-11 12:06:28 +01001022 // Unlike DisableCollection, JDWP specs do not state an invalid object causes an error. The RI
1023 // also ignores these cases and never return an error. However it's not obvious why this command
1024 // should behave differently from DisableCollection and IsCollected commands. So let's be more
1025 // strict and return an error if this happens.
Ian Rogersc0542af2014-09-03 16:16:56 -07001026 if (o == nullptr) {
Sebastien Hertze96060a2013-12-11 12:06:28 +01001027 return JDWP::ERR_INVALID_OBJECT;
1028 }
Elliott Hughes64f574f2013-02-20 14:57:12 -08001029 gRegistry->EnableCollection(object_id);
1030 return JDWP::ERR_NONE;
1031}
1032
Ian Rogersc0542af2014-09-03 16:16:56 -07001033JDWP::JdwpError Dbg::IsCollected(JDWP::ObjectId object_id, bool* is_collected) {
1034 *is_collected = true;
Sebastien Hertz65637eb2014-01-10 17:40:02 +01001035 if (object_id == 0) {
1036 // Null object id is invalid.
Sebastien Hertze96060a2013-12-11 12:06:28 +01001037 return JDWP::ERR_INVALID_OBJECT;
1038 }
Sebastien Hertz65637eb2014-01-10 17:40:02 +01001039 // JDWP specs state an INVALID_OBJECT error is returned if the object ID is not valid. However
1040 // the RI seems to ignore this and assume object has been collected.
Ian Rogersc0542af2014-09-03 16:16:56 -07001041 JDWP::JdwpError error;
1042 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
1043 if (o != nullptr) {
1044 *is_collected = gRegistry->IsCollected(object_id);
Sebastien Hertz65637eb2014-01-10 17:40:02 +01001045 }
Elliott Hughes64f574f2013-02-20 14:57:12 -08001046 return JDWP::ERR_NONE;
1047}
1048
Ian Rogersc0542af2014-09-03 16:16:56 -07001049void Dbg::DisposeObject(JDWP::ObjectId object_id, uint32_t reference_count) {
Elliott Hughes64f574f2013-02-20 14:57:12 -08001050 gRegistry->DisposeObject(object_id, reference_count);
1051}
1052
Mathieu Chartier3398c782016-09-30 10:27:43 -07001053JDWP::JdwpTypeTag Dbg::GetTypeTag(ObjPtr<mirror::Class> klass) {
Sebastien Hertz4d8fd492014-03-28 16:29:41 +01001054 DCHECK(klass != nullptr);
1055 if (klass->IsArrayClass()) {
1056 return JDWP::TT_ARRAY;
1057 } else if (klass->IsInterface()) {
1058 return JDWP::TT_INTERFACE;
1059 } else {
1060 return JDWP::TT_CLASS;
1061 }
1062}
1063
Elliott Hughes88d63092013-01-09 09:55:54 -08001064JDWP::JdwpError Dbg::GetReflectedType(JDWP::RefTypeId class_id, JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001065 JDWP::JdwpError error;
1066 mirror::Class* c = DecodeClass(class_id, &error);
1067 if (c == nullptr) {
1068 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001069 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001070
Sebastien Hertz4d8fd492014-03-28 16:29:41 +01001071 JDWP::JdwpTypeTag type_tag = GetTypeTag(c);
1072 expandBufAdd1(pReply, type_tag);
Elliott Hughes88d63092013-01-09 09:55:54 -08001073 expandBufAddRefTypeId(pReply, class_id);
Elliott Hughes436e3722012-02-17 20:01:47 -08001074 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001075}
1076
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001077// Get the complete list of reference classes (i.e. all classes except
1078// the primitive types).
1079// Returns a newly-allocated buffer full of RefTypeId values.
1080class ClassListCreator : public ClassVisitor {
1081 public:
1082 explicit ClassListCreator(std::vector<JDWP::RefTypeId>* classes) : classes_(classes) {}
1083
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001084 bool operator()(ObjPtr<mirror::Class> c) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001085 if (!c->IsPrimitive()) {
1086 classes_->push_back(Dbg::GetObjectRegistry()->AddRefType(c));
1087 }
1088 return true;
1089 }
1090
1091 private:
1092 std::vector<JDWP::RefTypeId>* const classes_;
1093};
1094
Ian Rogersc0542af2014-09-03 16:16:56 -07001095void Dbg::GetClassList(std::vector<JDWP::RefTypeId>* classes) {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001096 ClassListCreator clc(classes);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001097 Runtime::Current()->GetClassLinker()->VisitClassesWithoutClassesLock(&clc);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001098}
1099
Ian Rogers1ff3c982014-08-12 02:30:58 -07001100JDWP::JdwpError Dbg::GetClassInfo(JDWP::RefTypeId class_id, JDWP::JdwpTypeTag* pTypeTag,
1101 uint32_t* pStatus, std::string* pDescriptor) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001102 JDWP::JdwpError error;
1103 mirror::Class* c = DecodeClass(class_id, &error);
1104 if (c == nullptr) {
1105 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001106 }
1107
Elliott Hughesa2155262011-11-16 16:26:58 -08001108 if (c->IsArrayClass()) {
1109 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
1110 *pTypeTag = JDWP::TT_ARRAY;
1111 } else {
1112 if (c->IsErroneous()) {
1113 *pStatus = JDWP::CS_ERROR;
1114 } else {
1115 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED | JDWP::CS_INITIALIZED;
1116 }
1117 *pTypeTag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
1118 }
1119
Ian Rogersc0542af2014-09-03 16:16:56 -07001120 if (pDescriptor != nullptr) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07001121 std::string temp;
1122 *pDescriptor = c->GetDescriptor(&temp);
Elliott Hughesa2155262011-11-16 16:26:58 -08001123 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001124 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001125}
1126
Ian Rogersc0542af2014-09-03 16:16:56 -07001127void Dbg::FindLoadedClassBySignature(const char* descriptor, std::vector<JDWP::RefTypeId>* ids) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001128 std::vector<ObjPtr<mirror::Class>> classes;
Igor Murashkinb1d8c312015-08-04 11:18:43 -07001129 Runtime::Current()->GetClassLinker()->LookupClasses(descriptor, classes);
Ian Rogersc0542af2014-09-03 16:16:56 -07001130 ids->clear();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001131 for (ObjPtr<mirror::Class> c : classes) {
1132 ids->push_back(gRegistry->Add(c));
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001133 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001134}
1135
Ian Rogersc0542af2014-09-03 16:16:56 -07001136JDWP::JdwpError Dbg::GetReferenceType(JDWP::ObjectId object_id, JDWP::ExpandBuf* pReply) {
1137 JDWP::JdwpError error;
1138 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
1139 if (o == nullptr) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001140 return JDWP::ERR_INVALID_OBJECT;
Elliott Hughes499c5132011-11-17 14:55:11 -08001141 }
Elliott Hughes2435a572012-02-17 16:07:41 -08001142
Sebastien Hertz4d8fd492014-03-28 16:29:41 +01001143 JDWP::JdwpTypeTag type_tag = GetTypeTag(o->GetClass());
Elliott Hughes64f574f2013-02-20 14:57:12 -08001144 JDWP::RefTypeId type_id = gRegistry->AddRefType(o->GetClass());
Elliott Hughes2435a572012-02-17 16:07:41 -08001145
1146 expandBufAdd1(pReply, type_tag);
1147 expandBufAddRefTypeId(pReply, type_id);
1148
1149 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001150}
1151
Ian Rogersfc0e94b2013-09-23 23:51:32 -07001152JDWP::JdwpError Dbg::GetSignature(JDWP::RefTypeId class_id, std::string* signature) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001153 JDWP::JdwpError error;
1154 mirror::Class* c = DecodeClass(class_id, &error);
1155 if (c == nullptr) {
1156 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001157 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07001158 std::string temp;
1159 *signature = c->GetDescriptor(&temp);
Elliott Hughes1fe7afb2012-02-13 17:23:03 -08001160 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001161}
1162
Orion Hodson77d8a1c2017-04-24 14:53:19 +01001163JDWP::JdwpError Dbg::GetSourceDebugExtension(JDWP::RefTypeId class_id,
1164 std::string* extension_data) {
1165 JDWP::JdwpError error;
1166 mirror::Class* c = DecodeClass(class_id, &error);
1167 if (c == nullptr) {
1168 return error;
1169 }
1170 StackHandleScope<1> hs(Thread::Current());
1171 Handle<mirror::Class> klass(hs.NewHandle(c));
1172 const char* data = annotations::GetSourceDebugExtension(klass);
1173 if (data == nullptr) {
1174 return JDWP::ERR_ABSENT_INFORMATION;
1175 }
1176 *extension_data = data;
1177 return JDWP::ERR_NONE;
1178}
1179
Ian Rogersc0542af2014-09-03 16:16:56 -07001180JDWP::JdwpError Dbg::GetSourceFile(JDWP::RefTypeId class_id, std::string* result) {
1181 JDWP::JdwpError error;
1182 mirror::Class* c = DecodeClass(class_id, &error);
Sebastien Hertz4206eb52014-06-05 10:15:45 +02001183 if (c == nullptr) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001184 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001185 }
Sebastien Hertz4206eb52014-06-05 10:15:45 +02001186 const char* source_file = c->GetSourceFile();
1187 if (source_file == nullptr) {
Sebastien Hertzb7054ba2014-03-13 11:52:31 +01001188 return JDWP::ERR_ABSENT_INFORMATION;
1189 }
Ian Rogersc0542af2014-09-03 16:16:56 -07001190 *result = source_file;
Elliott Hughes436e3722012-02-17 20:01:47 -08001191 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001192}
1193
Ian Rogersc0542af2014-09-03 16:16:56 -07001194JDWP::JdwpError Dbg::GetObjectTag(JDWP::ObjectId object_id, uint8_t* tag) {
Ian Rogers98379392014-02-24 16:53:16 -08001195 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07001196 JDWP::JdwpError error;
1197 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
1198 if (error != JDWP::ERR_NONE) {
1199 *tag = JDWP::JT_VOID;
1200 return error;
Elliott Hughes546b9862012-06-20 16:06:13 -07001201 }
Ian Rogersc0542af2014-09-03 16:16:56 -07001202 *tag = TagFromObject(soa, o);
Elliott Hughes546b9862012-06-20 16:06:13 -07001203 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001204}
1205
Elliott Hughesaed4be92011-12-02 16:16:23 -08001206size_t Dbg::GetTagWidth(JDWP::JdwpTag tag) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001207 switch (tag) {
1208 case JDWP::JT_VOID:
1209 return 0;
1210 case JDWP::JT_BYTE:
1211 case JDWP::JT_BOOLEAN:
1212 return 1;
1213 case JDWP::JT_CHAR:
1214 case JDWP::JT_SHORT:
1215 return 2;
1216 case JDWP::JT_FLOAT:
1217 case JDWP::JT_INT:
1218 return 4;
1219 case JDWP::JT_ARRAY:
1220 case JDWP::JT_OBJECT:
1221 case JDWP::JT_STRING:
1222 case JDWP::JT_THREAD:
1223 case JDWP::JT_THREAD_GROUP:
1224 case JDWP::JT_CLASS_LOADER:
1225 case JDWP::JT_CLASS_OBJECT:
1226 return sizeof(JDWP::ObjectId);
1227 case JDWP::JT_DOUBLE:
1228 case JDWP::JT_LONG:
1229 return 8;
1230 default:
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001231 LOG(FATAL) << "Unknown tag " << tag;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001232 return -1;
1233 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001234}
1235
Ian Rogersc0542af2014-09-03 16:16:56 -07001236JDWP::JdwpError Dbg::GetArrayLength(JDWP::ObjectId array_id, int32_t* length) {
1237 JDWP::JdwpError error;
1238 mirror::Array* a = DecodeNonNullArray(array_id, &error);
1239 if (a == nullptr) {
1240 return error;
Elliott Hughes24437992011-11-30 14:49:33 -08001241 }
Ian Rogersc0542af2014-09-03 16:16:56 -07001242 *length = a->GetLength();
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001243 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001244}
1245
Elliott Hughes88d63092013-01-09 09:55:54 -08001246JDWP::JdwpError Dbg::OutputArray(JDWP::ObjectId array_id, int offset, int count, JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001247 JDWP::JdwpError error;
1248 mirror::Array* a = DecodeNonNullArray(array_id, &error);
Ian Rogers98379392014-02-24 16:53:16 -08001249 if (a == nullptr) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001250 return error;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001251 }
Elliott Hughes24437992011-11-30 14:49:33 -08001252
1253 if (offset < 0 || count < 0 || offset > a->GetLength() || a->GetLength() - offset < count) {
1254 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001255 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughes24437992011-11-30 14:49:33 -08001256 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07001257 JDWP::JdwpTag element_tag = BasicTagFromClass(a->GetClass()->GetComponentType());
1258 expandBufAdd1(pReply, element_tag);
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001259 expandBufAdd4BE(pReply, count);
1260
Ian Rogers1ff3c982014-08-12 02:30:58 -07001261 if (IsPrimitiveTag(element_tag)) {
1262 size_t width = GetTagWidth(element_tag);
Elliott Hughes24437992011-11-30 14:49:33 -08001263 uint8_t* dst = expandBufAddSpace(pReply, count * width);
1264 if (width == 8) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001265 const uint64_t* src8 = reinterpret_cast<uint64_t*>(a->GetRawData(sizeof(uint64_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001266 for (int i = 0; i < count; ++i) JDWP::Write8BE(&dst, src8[offset + i]);
1267 } else if (width == 4) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001268 const uint32_t* src4 = reinterpret_cast<uint32_t*>(a->GetRawData(sizeof(uint32_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001269 for (int i = 0; i < count; ++i) JDWP::Write4BE(&dst, src4[offset + i]);
1270 } else if (width == 2) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001271 const uint16_t* src2 = reinterpret_cast<uint16_t*>(a->GetRawData(sizeof(uint16_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001272 for (int i = 0; i < count; ++i) JDWP::Write2BE(&dst, src2[offset + i]);
1273 } else {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001274 const uint8_t* src = reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint8_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001275 memcpy(dst, &src[offset * width], count * width);
1276 }
1277 } else {
Ian Rogers98379392014-02-24 16:53:16 -08001278 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001279 mirror::ObjectArray<mirror::Object>* oa = a->AsObjectArray<mirror::Object>();
Elliott Hughes24437992011-11-30 14:49:33 -08001280 for (int i = 0; i < count; ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001281 mirror::Object* element = oa->Get(offset + i);
Ian Rogers98379392014-02-24 16:53:16 -08001282 JDWP::JdwpTag specific_tag = (element != nullptr) ? TagFromObject(soa, element)
Ian Rogers1ff3c982014-08-12 02:30:58 -07001283 : element_tag;
Elliott Hughes24437992011-11-30 14:49:33 -08001284 expandBufAdd1(pReply, specific_tag);
1285 expandBufAddObjectId(pReply, gRegistry->Add(element));
1286 }
1287 }
1288
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001289 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001290}
1291
Ian Rogersef7d42f2014-01-06 12:55:46 -08001292template <typename T>
Ian Rogersc0542af2014-09-03 16:16:56 -07001293static void CopyArrayData(mirror::Array* a, JDWP::Request* src, int offset, int count)
Ian Rogersef7d42f2014-01-06 12:55:46 -08001294 NO_THREAD_SAFETY_ANALYSIS {
1295 // TODO: fix when annotalysis correctly handles non-member functions.
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001296 DCHECK(a->GetClass()->IsPrimitiveArray());
1297
Ian Rogersef7d42f2014-01-06 12:55:46 -08001298 T* dst = reinterpret_cast<T*>(a->GetRawData(sizeof(T), offset));
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001299 for (int i = 0; i < count; ++i) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001300 *dst++ = src->ReadValue(sizeof(T));
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001301 }
1302}
1303
Elliott Hughes88d63092013-01-09 09:55:54 -08001304JDWP::JdwpError Dbg::SetArrayElements(JDWP::ObjectId array_id, int offset, int count,
Ian Rogersc0542af2014-09-03 16:16:56 -07001305 JDWP::Request* request) {
1306 JDWP::JdwpError error;
1307 mirror::Array* dst = DecodeNonNullArray(array_id, &error);
1308 if (dst == nullptr) {
1309 return error;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001310 }
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001311
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001312 if (offset < 0 || count < 0 || offset > dst->GetLength() || dst->GetLength() - offset < count) {
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001313 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001314 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001315 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07001316 JDWP::JdwpTag element_tag = BasicTagFromClass(dst->GetClass()->GetComponentType());
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001317
Ian Rogers1ff3c982014-08-12 02:30:58 -07001318 if (IsPrimitiveTag(element_tag)) {
1319 size_t width = GetTagWidth(element_tag);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001320 if (width == 8) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001321 CopyArrayData<uint64_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001322 } else if (width == 4) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001323 CopyArrayData<uint32_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001324 } else if (width == 2) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001325 CopyArrayData<uint16_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001326 } else {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001327 CopyArrayData<uint8_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001328 }
1329 } else {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001330 mirror::ObjectArray<mirror::Object>* oa = dst->AsObjectArray<mirror::Object>();
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001331 for (int i = 0; i < count; ++i) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001332 JDWP::ObjectId id = request->ReadObjectId();
Ian Rogersc0542af2014-09-03 16:16:56 -07001333 mirror::Object* o = gRegistry->Get<mirror::Object*>(id, &error);
1334 if (error != JDWP::ERR_NONE) {
1335 return error;
Elliott Hughes436e3722012-02-17 20:01:47 -08001336 }
Sebastien Hertz2e1c16d2015-08-28 11:57:49 +02001337 // Check if the object's type is compatible with the array's type.
1338 if (o != nullptr && !o->InstanceOf(oa->GetClass()->GetComponentType())) {
1339 return JDWP::ERR_TYPE_MISMATCH;
1340 }
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001341 oa->Set<false>(offset + i, o);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001342 }
1343 }
1344
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001345 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001346}
1347
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001348JDWP::JdwpError Dbg::CreateString(const std::string& str, JDWP::ObjectId* new_string_id) {
1349 Thread* self = Thread::Current();
1350 mirror::String* new_string = mirror::String::AllocFromModifiedUtf8(self, str.c_str());
1351 if (new_string == nullptr) {
1352 DCHECK(self->IsExceptionPending());
1353 self->ClearException();
1354 LOG(ERROR) << "Could not allocate string";
1355 *new_string_id = 0;
1356 return JDWP::ERR_OUT_OF_MEMORY;
1357 }
1358 *new_string_id = gRegistry->Add(new_string);
1359 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001360}
1361
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001362JDWP::JdwpError Dbg::CreateObject(JDWP::RefTypeId class_id, JDWP::ObjectId* new_object_id) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001363 JDWP::JdwpError error;
1364 mirror::Class* c = DecodeClass(class_id, &error);
1365 if (c == nullptr) {
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001366 *new_object_id = 0;
Ian Rogersc0542af2014-09-03 16:16:56 -07001367 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001368 }
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001369 Thread* self = Thread::Current();
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001370 ObjPtr<mirror::Object> new_object;
Sebastien Hertz56d5e502015-11-03 17:38:35 +01001371 if (c->IsStringClass()) {
1372 // Special case for java.lang.String.
1373 gc::AllocatorType allocator_type = Runtime::Current()->GetHeap()->GetCurrentAllocator();
jessicahandojo3aaa37b2016-07-29 14:46:37 -07001374 new_object = mirror::String::AllocEmptyString<true>(self, allocator_type);
Sebastien Hertz56d5e502015-11-03 17:38:35 +01001375 } else {
1376 new_object = c->AllocObject(self);
1377 }
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001378 if (new_object == nullptr) {
1379 DCHECK(self->IsExceptionPending());
1380 self->ClearException();
David Sehr709b0702016-10-13 09:12:37 -07001381 LOG(ERROR) << "Could not allocate object of type " << mirror::Class::PrettyDescriptor(c);
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001382 *new_object_id = 0;
1383 return JDWP::ERR_OUT_OF_MEMORY;
1384 }
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001385 *new_object_id = gRegistry->Add(new_object.Ptr());
Elliott Hughes436e3722012-02-17 20:01:47 -08001386 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001387}
1388
Elliott Hughesbf13d362011-12-08 15:51:37 -08001389/*
1390 * Used by Eclipse's "Display" view to evaluate "new byte[5]" to get "(byte[]) [0, 0, 0, 0, 0]".
1391 */
Elliott Hughes88d63092013-01-09 09:55:54 -08001392JDWP::JdwpError Dbg::CreateArrayObject(JDWP::RefTypeId array_class_id, uint32_t length,
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001393 JDWP::ObjectId* new_array_id) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001394 JDWP::JdwpError error;
1395 mirror::Class* c = DecodeClass(array_class_id, &error);
1396 if (c == nullptr) {
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001397 *new_array_id = 0;
Ian Rogersc0542af2014-09-03 16:16:56 -07001398 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001399 }
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001400 Thread* self = Thread::Current();
1401 gc::Heap* heap = Runtime::Current()->GetHeap();
1402 mirror::Array* new_array = mirror::Array::Alloc<true>(self, c, length,
1403 c->GetComponentSizeShift(),
1404 heap->GetCurrentAllocator());
1405 if (new_array == nullptr) {
1406 DCHECK(self->IsExceptionPending());
1407 self->ClearException();
David Sehr709b0702016-10-13 09:12:37 -07001408 LOG(ERROR) << "Could not allocate array of type " << mirror::Class::PrettyDescriptor(c);
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001409 *new_array_id = 0;
1410 return JDWP::ERR_OUT_OF_MEMORY;
1411 }
1412 *new_array_id = gRegistry->Add(new_array);
Elliott Hughes436e3722012-02-17 20:01:47 -08001413 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001414}
1415
Mathieu Chartierc7853442015-03-27 14:35:38 -07001416JDWP::FieldId Dbg::ToFieldId(const ArtField* f) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001417 return static_cast<JDWP::FieldId>(reinterpret_cast<uintptr_t>(f));
Elliott Hughes03181a82011-11-17 17:22:21 -08001418}
1419
Alex Light6c8467f2015-11-20 15:03:26 -08001420static JDWP::MethodId ToMethodId(ArtMethod* m)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001421 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light97e78032017-06-27 17:51:55 -07001422 return static_cast<JDWP::MethodId>(
1423 reinterpret_cast<uintptr_t>(m->GetCanonicalMethod(kRuntimePointerSize)));
Elliott Hughes03181a82011-11-17 17:22:21 -08001424}
1425
Mathieu Chartierc7853442015-03-27 14:35:38 -07001426static ArtField* FromFieldId(JDWP::FieldId fid)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001427 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001428 return reinterpret_cast<ArtField*>(static_cast<uintptr_t>(fid));
Elliott Hughesaed4be92011-12-02 16:16:23 -08001429}
1430
Mathieu Chartiere401d142015-04-22 13:56:20 -07001431static ArtMethod* FromMethodId(JDWP::MethodId mid)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001432 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001433 return reinterpret_cast<ArtMethod*>(static_cast<uintptr_t>(mid));
Elliott Hughes03181a82011-11-17 17:22:21 -08001434}
1435
Sebastien Hertz6995c602014-09-09 12:10:13 +02001436bool Dbg::MatchThread(JDWP::ObjectId expected_thread_id, Thread* event_thread) {
1437 CHECK(event_thread != nullptr);
1438 JDWP::JdwpError error;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001439 mirror::Object* expected_thread_peer = gRegistry->Get<mirror::Object*>(
1440 expected_thread_id, &error);
Nicolas Geoffraycafa0812017-02-15 18:27:34 +00001441 return expected_thread_peer == event_thread->GetPeerFromOtherThread();
Sebastien Hertz6995c602014-09-09 12:10:13 +02001442}
1443
1444bool Dbg::MatchLocation(const JDWP::JdwpLocation& expected_location,
1445 const JDWP::EventLocation& event_location) {
1446 if (expected_location.dex_pc != event_location.dex_pc) {
1447 return false;
1448 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001449 ArtMethod* m = FromMethodId(expected_location.method_id);
Sebastien Hertz6995c602014-09-09 12:10:13 +02001450 return m == event_location.method;
1451}
1452
Mathieu Chartier3398c782016-09-30 10:27:43 -07001453bool Dbg::MatchType(ObjPtr<mirror::Class> event_class, JDWP::RefTypeId class_id) {
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001454 if (event_class == nullptr) {
1455 return false;
1456 }
Sebastien Hertz6995c602014-09-09 12:10:13 +02001457 JDWP::JdwpError error;
Mathieu Chartier3398c782016-09-30 10:27:43 -07001458 ObjPtr<mirror::Class> expected_class = DecodeClass(class_id, &error);
Sebastien Hertz6995c602014-09-09 12:10:13 +02001459 CHECK(expected_class != nullptr);
1460 return expected_class->IsAssignableFrom(event_class);
1461}
1462
1463bool Dbg::MatchField(JDWP::RefTypeId expected_type_id, JDWP::FieldId expected_field_id,
Mathieu Chartierc7853442015-03-27 14:35:38 -07001464 ArtField* event_field) {
1465 ArtField* expected_field = FromFieldId(expected_field_id);
Sebastien Hertz6995c602014-09-09 12:10:13 +02001466 if (expected_field != event_field) {
1467 return false;
1468 }
1469 return Dbg::MatchType(event_field->GetDeclaringClass(), expected_type_id);
1470}
1471
1472bool Dbg::MatchInstance(JDWP::ObjectId expected_instance_id, mirror::Object* event_instance) {
1473 JDWP::JdwpError error;
1474 mirror::Object* modifier_instance = gRegistry->Get<mirror::Object*>(expected_instance_id, &error);
1475 return modifier_instance == event_instance;
1476}
1477
Mathieu Chartier90443472015-07-16 20:32:27 -07001478void Dbg::SetJdwpLocation(JDWP::JdwpLocation* location, ArtMethod* m, uint32_t dex_pc) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001479 if (m == nullptr) {
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001480 memset(location, 0, sizeof(*location));
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001481 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001482 mirror::Class* c = m->GetDeclaringClass();
Ian Rogersc0542af2014-09-03 16:16:56 -07001483 location->type_tag = GetTypeTag(c);
1484 location->class_id = gRegistry->AddRefType(c);
Alex Light73376312017-04-06 10:10:51 -07001485 // The RI Seems to return 0 for all obsolete methods. For compatibility we shall do the same.
1486 location->method_id = m->IsObsolete() ? 0 : ToMethodId(m);
Ian Rogersc0542af2014-09-03 16:16:56 -07001487 location->dex_pc = (m->IsNative() || m->IsProxyMethod()) ? static_cast<uint64_t>(-1) : dex_pc;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001488 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08001489}
1490
Ian Rogersc0542af2014-09-03 16:16:56 -07001491std::string Dbg::GetMethodName(JDWP::MethodId method_id) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001492 ArtMethod* m = FromMethodId(method_id);
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001493 if (m == nullptr) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001494 return "null";
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001495 }
Andreas Gampe542451c2016-07-26 09:02:02 -07001496 return m->GetInterfaceMethodIfProxy(kRuntimePointerSize)->GetName();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001497}
1498
Alex Light73376312017-04-06 10:10:51 -07001499bool Dbg::IsMethodObsolete(JDWP::MethodId method_id) {
1500 ArtMethod* m = FromMethodId(method_id);
1501 if (m == nullptr) {
1502 // NB Since we return 0 as MID for obsolete methods we want to default to true here.
1503 return true;
1504 }
1505 return m->IsObsolete();
1506}
1507
Ian Rogersc0542af2014-09-03 16:16:56 -07001508std::string Dbg::GetFieldName(JDWP::FieldId field_id) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001509 ArtField* f = FromFieldId(field_id);
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001510 if (f == nullptr) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001511 return "null";
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001512 }
1513 return f->GetName();
Elliott Hughesa96836a2013-01-17 12:27:49 -08001514}
1515
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001516/*
1517 * Augment the access flags for synthetic methods and fields by setting
1518 * the (as described by the spec) "0xf0000000 bit". Also, strip out any
1519 * flags not specified by the Java programming language.
1520 */
1521static uint32_t MangleAccessFlags(uint32_t accessFlags) {
1522 accessFlags &= kAccJavaFlagsMask;
1523 if ((accessFlags & kAccSynthetic) != 0) {
1524 accessFlags |= 0xf0000000;
1525 }
1526 return accessFlags;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001527}
1528
Elliott Hughesdbb40792011-11-18 17:05:22 -08001529/*
Jeff Haob7cefc72013-11-14 14:51:09 -08001530 * Circularly shifts registers so that arguments come first. Debuggers
1531 * expect slots to begin with arguments, but dex code places them at
1532 * the end.
Elliott Hughesdbb40792011-11-18 17:05:22 -08001533 */
Mathieu Chartiere401d142015-04-22 13:56:20 -07001534static uint16_t MangleSlot(uint16_t slot, ArtMethod* m)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001535 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier808c7a52017-12-15 11:19:33 -08001536 CodeItemDataAccessor accessor(m);
1537 if (!accessor.HasCodeItem()) {
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001538 // We should not get here for a method without code (native, proxy or abstract). Log it and
1539 // return the slot as is since all registers are arguments.
David Sehr709b0702016-10-13 09:12:37 -07001540 LOG(WARNING) << "Trying to mangle slot for method without code " << m->PrettyMethod();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001541 return slot;
1542 }
Mathieu Chartier808c7a52017-12-15 11:19:33 -08001543 uint16_t ins_size = accessor.InsSize();
1544 uint16_t locals_size = accessor.RegistersSize() - ins_size;
Jeff Haob7cefc72013-11-14 14:51:09 -08001545 if (slot >= locals_size) {
1546 return slot - locals_size;
1547 } else {
1548 return slot + ins_size;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001549 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001550}
1551
Sebastien Hertzaef0c912016-08-08 10:20:28 +02001552static size_t GetMethodNumArgRegistersIncludingThis(ArtMethod* method)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001553 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertzaef0c912016-08-08 10:20:28 +02001554 uint32_t num_registers = ArtMethod::NumArgRegisters(method->GetShorty());
1555 if (!method->IsStatic()) {
1556 ++num_registers;
1557 }
1558 return num_registers;
1559}
1560
Jeff Haob7cefc72013-11-14 14:51:09 -08001561/*
1562 * Circularly shifts registers so that arguments come last. Reverts
1563 * slots to dex style argument placement.
1564 */
Mathieu Chartiere401d142015-04-22 13:56:20 -07001565static uint16_t DemangleSlot(uint16_t slot, ArtMethod* m, JDWP::JdwpError* error)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001566 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier808c7a52017-12-15 11:19:33 -08001567 CodeItemDataAccessor accessor(m);
1568 if (!accessor.HasCodeItem()) {
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001569 // We should not get here for a method without code (native, proxy or abstract). Log it and
1570 // return the slot as is since all registers are arguments.
David Sehr709b0702016-10-13 09:12:37 -07001571 LOG(WARNING) << "Trying to demangle slot for method without code "
1572 << m->PrettyMethod();
Sebastien Hertzaef0c912016-08-08 10:20:28 +02001573 uint16_t vreg_count = GetMethodNumArgRegistersIncludingThis(m);
Sebastien Hertzabbabc82015-03-26 08:47:47 +01001574 if (slot < vreg_count) {
1575 *error = JDWP::ERR_NONE;
1576 return slot;
1577 }
Jeff Haob7cefc72013-11-14 14:51:09 -08001578 } else {
Mathieu Chartier808c7a52017-12-15 11:19:33 -08001579 if (slot < accessor.RegistersSize()) {
1580 uint16_t ins_size = accessor.InsSize();
1581 uint16_t locals_size = accessor.RegistersSize() - ins_size;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01001582 *error = JDWP::ERR_NONE;
1583 return (slot < ins_size) ? slot + locals_size : slot - ins_size;
1584 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001585 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01001586
1587 // Slot is invalid in the method.
David Sehr709b0702016-10-13 09:12:37 -07001588 LOG(ERROR) << "Invalid local slot " << slot << " for method " << m->PrettyMethod();
Sebastien Hertzabbabc82015-03-26 08:47:47 +01001589 *error = JDWP::ERR_INVALID_SLOT;
1590 return DexFile::kDexNoIndex16;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001591}
1592
Mathieu Chartier90443472015-07-16 20:32:27 -07001593JDWP::JdwpError Dbg::OutputDeclaredFields(JDWP::RefTypeId class_id, bool with_generic,
1594 JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001595 JDWP::JdwpError error;
1596 mirror::Class* c = DecodeClass(class_id, &error);
1597 if (c == nullptr) {
1598 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001599 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001600
1601 size_t instance_field_count = c->NumInstanceFields();
1602 size_t static_field_count = c->NumStaticFields();
1603
1604 expandBufAdd4BE(pReply, instance_field_count + static_field_count);
1605
1606 for (size_t i = 0; i < instance_field_count + static_field_count; ++i) {
Mathieu Chartier90443472015-07-16 20:32:27 -07001607 ArtField* f = (i < instance_field_count) ? c->GetInstanceField(i) :
1608 c->GetStaticField(i - instance_field_count);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001609 expandBufAddFieldId(pReply, ToFieldId(f));
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001610 expandBufAddUtf8String(pReply, f->GetName());
1611 expandBufAddUtf8String(pReply, f->GetTypeDescriptor());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001612 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001613 static const char genericSignature[1] = "";
1614 expandBufAddUtf8String(pReply, genericSignature);
1615 }
1616 expandBufAdd4BE(pReply, MangleAccessFlags(f->GetAccessFlags()));
1617 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001618 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001619}
1620
Elliott Hughes88d63092013-01-09 09:55:54 -08001621JDWP::JdwpError Dbg::OutputDeclaredMethods(JDWP::RefTypeId class_id, bool with_generic,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001622 JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001623 JDWP::JdwpError error;
1624 mirror::Class* c = DecodeClass(class_id, &error);
1625 if (c == nullptr) {
1626 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001627 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001628
Alex Light51a64d52015-12-17 13:55:59 -08001629 expandBufAdd4BE(pReply, c->NumMethods());
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001630
Mathieu Chartiere401d142015-04-22 13:56:20 -07001631 auto* cl = Runtime::Current()->GetClassLinker();
1632 auto ptr_size = cl->GetImagePointerSize();
Alex Light51a64d52015-12-17 13:55:59 -08001633 for (ArtMethod& m : c->GetMethods(ptr_size)) {
1634 expandBufAddMethodId(pReply, ToMethodId(&m));
Andreas Gampe542451c2016-07-26 09:02:02 -07001635 expandBufAddUtf8String(pReply, m.GetInterfaceMethodIfProxy(kRuntimePointerSize)->GetName());
1636 expandBufAddUtf8String(
1637 pReply, m.GetInterfaceMethodIfProxy(kRuntimePointerSize)->GetSignature().ToString());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001638 if (with_generic) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001639 const char* generic_signature = "";
1640 expandBufAddUtf8String(pReply, generic_signature);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001641 }
Alex Light51a64d52015-12-17 13:55:59 -08001642 expandBufAdd4BE(pReply, MangleAccessFlags(m.GetAccessFlags()));
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001643 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001644 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001645}
1646
Elliott Hughes88d63092013-01-09 09:55:54 -08001647JDWP::JdwpError Dbg::OutputDeclaredInterfaces(JDWP::RefTypeId class_id, JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001648 JDWP::JdwpError error;
Mathieu Chartierf8322842014-05-16 10:59:25 -07001649 Thread* self = Thread::Current();
Vladimir Marko19a4d372016-12-08 14:41:46 +00001650 ObjPtr<mirror::Class> c = DecodeClass(class_id, &error);
1651 if (c == nullptr) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001652 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001653 }
Mathieu Chartierf8322842014-05-16 10:59:25 -07001654 size_t interface_count = c->NumDirectInterfaces();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001655 expandBufAdd4BE(pReply, interface_count);
1656 for (size_t i = 0; i < interface_count; ++i) {
Vladimir Marko19a4d372016-12-08 14:41:46 +00001657 ObjPtr<mirror::Class> interface = mirror::Class::GetDirectInterface(self, c, i);
1658 DCHECK(interface != nullptr);
1659 expandBufAddRefTypeId(pReply, gRegistry->AddRefType(interface));
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001660 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001661 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001662}
1663
Ian Rogersc0542af2014-09-03 16:16:56 -07001664void Dbg::OutputLineTable(JDWP::RefTypeId, JDWP::MethodId method_id, JDWP::ExpandBuf* pReply) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001665 struct DebugCallbackContext {
1666 int numItems;
1667 JDWP::ExpandBuf* pReply;
1668
David Srbeckyb06e28e2015-12-10 13:15:00 +00001669 static bool Callback(void* context, const DexFile::PositionInfo& entry) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001670 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
David Srbeckyb06e28e2015-12-10 13:15:00 +00001671 expandBufAdd8BE(pContext->pReply, entry.address_);
1672 expandBufAdd4BE(pContext->pReply, entry.line_);
Elliott Hughes03181a82011-11-17 17:22:21 -08001673 pContext->numItems++;
Sebastien Hertzf2910ee2013-10-19 16:39:24 +02001674 return false;
Elliott Hughes03181a82011-11-17 17:22:21 -08001675 }
1676 };
Mathieu Chartiere401d142015-04-22 13:56:20 -07001677 ArtMethod* m = FromMethodId(method_id);
Mathieu Chartier31f4c9f2017-12-08 15:46:11 -08001678 CodeItemDebugInfoAccessor accessor(m);
Elliott Hughes03181a82011-11-17 17:22:21 -08001679 uint64_t start, end;
Mathieu Chartier31f4c9f2017-12-08 15:46:11 -08001680 if (!accessor.HasCodeItem()) {
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001681 DCHECK(m->IsNative() || m->IsProxyMethod());
Elliott Hughes03181a82011-11-17 17:22:21 -08001682 start = -1;
1683 end = -1;
1684 } else {
1685 start = 0;
jeffhao14f0db92012-12-14 17:50:42 -08001686 // Return the index of the last instruction
Mathieu Chartier31f4c9f2017-12-08 15:46:11 -08001687 end = accessor.InsnsSizeInCodeUnits() - 1;
Elliott Hughes03181a82011-11-17 17:22:21 -08001688 }
1689
1690 expandBufAdd8BE(pReply, start);
1691 expandBufAdd8BE(pReply, end);
1692
1693 // Add numLines later
1694 size_t numLinesOffset = expandBufGetLength(pReply);
1695 expandBufAdd4BE(pReply, 0);
1696
1697 DebugCallbackContext context;
1698 context.numItems = 0;
1699 context.pReply = pReply;
1700
Mathieu Chartier31f4c9f2017-12-08 15:46:11 -08001701 if (accessor.HasCodeItem()) {
1702 m->GetDexFile()->DecodeDebugPositionInfo(accessor.DebugInfoOffset(),
1703 DebugCallbackContext::Callback,
1704 &context);
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001705 }
Elliott Hughes03181a82011-11-17 17:22:21 -08001706
1707 JDWP::Set4BE(expandBufGetBuffer(pReply) + numLinesOffset, context.numItems);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001708}
1709
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001710void Dbg::OutputVariableTable(JDWP::RefTypeId, JDWP::MethodId method_id, bool with_generic,
1711 JDWP::ExpandBuf* pReply) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001712 struct DebugCallbackContext {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001713 ArtMethod* method;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001714 JDWP::ExpandBuf* pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001715 size_t variable_count;
1716 bool with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001717
David Srbeckyb06e28e2015-12-10 13:15:00 +00001718 static void Callback(void* context, const DexFile::LocalInfo& entry)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001719 REQUIRES_SHARED(Locks::mutator_lock_) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001720 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
1721
David Srbeckyb06e28e2015-12-10 13:15:00 +00001722 uint16_t slot = entry.reg_;
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001723 VLOG(jdwp) << StringPrintf(" %2zd: %d(%d) '%s' '%s' '%s' actual slot=%d mangled slot=%d",
David Srbeckyb06e28e2015-12-10 13:15:00 +00001724 pContext->variable_count, entry.start_address_,
1725 entry.end_address_ - entry.start_address_,
1726 entry.name_, entry.descriptor_, entry.signature_, slot,
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001727 MangleSlot(slot, pContext->method));
Elliott Hughesdbb40792011-11-18 17:05:22 -08001728
Jeff Haob7cefc72013-11-14 14:51:09 -08001729 slot = MangleSlot(slot, pContext->method);
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001730
David Srbeckyb06e28e2015-12-10 13:15:00 +00001731 expandBufAdd8BE(pContext->pReply, entry.start_address_);
1732 expandBufAddUtf8String(pContext->pReply, entry.name_);
1733 expandBufAddUtf8String(pContext->pReply, entry.descriptor_);
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001734 if (pContext->with_generic) {
David Srbeckyb06e28e2015-12-10 13:15:00 +00001735 expandBufAddUtf8String(pContext->pReply, entry.signature_);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001736 }
David Srbeckyb06e28e2015-12-10 13:15:00 +00001737 expandBufAdd4BE(pContext->pReply, entry.end_address_- entry.start_address_);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001738 expandBufAdd4BE(pContext->pReply, slot);
1739
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001740 ++pContext->variable_count;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001741 }
1742 };
Mathieu Chartiere401d142015-04-22 13:56:20 -07001743 ArtMethod* m = FromMethodId(method_id);
Mathieu Chartier31f4c9f2017-12-08 15:46:11 -08001744 CodeItemDebugInfoAccessor accessor(m);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001745
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001746 // arg_count considers doubles and longs to take 2 units.
1747 // variable_count considers everything to take 1 unit.
Sebastien Hertzaef0c912016-08-08 10:20:28 +02001748 expandBufAdd4BE(pReply, GetMethodNumArgRegistersIncludingThis(m));
Elliott Hughesdbb40792011-11-18 17:05:22 -08001749
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001750 // We don't know the total number of variables yet, so leave a blank and update it later.
1751 size_t variable_count_offset = expandBufGetLength(pReply);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001752 expandBufAdd4BE(pReply, 0);
1753
1754 DebugCallbackContext context;
Jeff Haob7cefc72013-11-14 14:51:09 -08001755 context.method = m;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001756 context.pReply = pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001757 context.variable_count = 0;
1758 context.with_generic = with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001759
Mathieu Chartier31f4c9f2017-12-08 15:46:11 -08001760 if (accessor.HasCodeItem()) {
1761 m->GetDexFile()->DecodeDebugLocalInfo(accessor.RegistersSize(),
1762 accessor.InsSize(),
1763 accessor.InsnsSizeInCodeUnits(),
1764 accessor.DebugInfoOffset(),
1765 m->IsStatic(),
1766 m->GetDexMethodIndex(),
1767 DebugCallbackContext::Callback,
1768 &context);
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001769 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001770
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001771 JDWP::Set4BE(expandBufGetBuffer(pReply) + variable_count_offset, context.variable_count);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001772}
1773
Jeff Hao579b0242013-11-18 13:16:49 -08001774void Dbg::OutputMethodReturnValue(JDWP::MethodId method_id, const JValue* return_value,
1775 JDWP::ExpandBuf* pReply) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001776 ArtMethod* m = FromMethodId(method_id);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001777 JDWP::JdwpTag tag = BasicTagFromDescriptor(m->GetShorty());
Jeff Hao579b0242013-11-18 13:16:49 -08001778 OutputJValue(tag, return_value, pReply);
1779}
1780
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02001781void Dbg::OutputFieldValue(JDWP::FieldId field_id, const JValue* field_value,
1782 JDWP::ExpandBuf* pReply) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001783 ArtField* f = FromFieldId(field_id);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001784 JDWP::JdwpTag tag = BasicTagFromDescriptor(f->GetTypeDescriptor());
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02001785 OutputJValue(tag, field_value, pReply);
1786}
1787
Elliott Hughes9777ba22013-01-17 09:04:19 -08001788JDWP::JdwpError Dbg::GetBytecodes(JDWP::RefTypeId, JDWP::MethodId method_id,
Ian Rogersc0542af2014-09-03 16:16:56 -07001789 std::vector<uint8_t>* bytecodes) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001790 ArtMethod* m = FromMethodId(method_id);
Ian Rogersc0542af2014-09-03 16:16:56 -07001791 if (m == nullptr) {
Elliott Hughes9777ba22013-01-17 09:04:19 -08001792 return JDWP::ERR_INVALID_METHODID;
1793 }
Mathieu Chartier808c7a52017-12-15 11:19:33 -08001794 CodeItemDataAccessor accessor(m);
1795 size_t byte_count = accessor.InsnsSizeInCodeUnits() * 2;
1796 const uint8_t* begin = reinterpret_cast<const uint8_t*>(accessor.Insns());
Elliott Hughes9777ba22013-01-17 09:04:19 -08001797 const uint8_t* end = begin + byte_count;
1798 for (const uint8_t* p = begin; p != end; ++p) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001799 bytecodes->push_back(*p);
Elliott Hughes9777ba22013-01-17 09:04:19 -08001800 }
1801 return JDWP::ERR_NONE;
1802}
1803
Elliott Hughes88d63092013-01-09 09:55:54 -08001804JDWP::JdwpTag Dbg::GetFieldBasicTag(JDWP::FieldId field_id) {
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001805 return BasicTagFromDescriptor(FromFieldId(field_id)->GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001806}
1807
Elliott Hughes88d63092013-01-09 09:55:54 -08001808JDWP::JdwpTag Dbg::GetStaticFieldBasicTag(JDWP::FieldId field_id) {
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001809 return BasicTagFromDescriptor(FromFieldId(field_id)->GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001810}
1811
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001812static JValue GetArtFieldValue(ArtField* f, mirror::Object* o)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001813 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001814 Primitive::Type fieldType = f->GetTypeAsPrimitiveType();
1815 JValue field_value;
1816 switch (fieldType) {
1817 case Primitive::kPrimBoolean:
1818 field_value.SetZ(f->GetBoolean(o));
1819 return field_value;
1820
1821 case Primitive::kPrimByte:
1822 field_value.SetB(f->GetByte(o));
1823 return field_value;
1824
1825 case Primitive::kPrimChar:
1826 field_value.SetC(f->GetChar(o));
1827 return field_value;
1828
1829 case Primitive::kPrimShort:
1830 field_value.SetS(f->GetShort(o));
1831 return field_value;
1832
1833 case Primitive::kPrimInt:
1834 case Primitive::kPrimFloat:
1835 // Int and Float must be treated as 32-bit values in JDWP.
1836 field_value.SetI(f->GetInt(o));
1837 return field_value;
1838
1839 case Primitive::kPrimLong:
1840 case Primitive::kPrimDouble:
1841 // Long and Double must be treated as 64-bit values in JDWP.
1842 field_value.SetJ(f->GetLong(o));
1843 return field_value;
1844
1845 case Primitive::kPrimNot:
Mathieu Chartier1cc62e42016-10-03 18:01:28 -07001846 field_value.SetL(f->GetObject(o).Ptr());
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001847 return field_value;
1848
1849 case Primitive::kPrimVoid:
1850 LOG(FATAL) << "Attempt to read from field of type 'void'";
1851 UNREACHABLE();
1852 }
1853 LOG(FATAL) << "Attempt to read from field of unknown type";
1854 UNREACHABLE();
1855}
1856
Elliott Hughes88d63092013-01-09 09:55:54 -08001857static JDWP::JdwpError GetFieldValueImpl(JDWP::RefTypeId ref_type_id, JDWP::ObjectId object_id,
1858 JDWP::FieldId field_id, JDWP::ExpandBuf* pReply,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001859 bool is_static)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001860 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001861 JDWP::JdwpError error;
1862 mirror::Class* c = DecodeClass(ref_type_id, &error);
1863 if (ref_type_id != 0 && c == nullptr) {
1864 return error;
Elliott Hughes0cf74332012-02-23 23:14:00 -08001865 }
1866
Jeff Haode19a252016-09-14 15:56:35 -07001867 Thread* self = Thread::Current();
1868 StackHandleScope<2> hs(self);
1869 MutableHandle<mirror::Object>
1870 o(hs.NewHandle(Dbg::GetObjectRegistry()->Get<mirror::Object*>(object_id, &error)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08001871 if ((!is_static && o == nullptr) || error != JDWP::ERR_NONE) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001872 return JDWP::ERR_INVALID_OBJECT;
1873 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001874 ArtField* f = FromFieldId(field_id);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001875
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001876 mirror::Class* receiver_class = c;
Andreas Gampefa4333d2017-02-14 11:10:34 -08001877 if (receiver_class == nullptr && o != nullptr) {
Elliott Hughes0cf74332012-02-23 23:14:00 -08001878 receiver_class = o->GetClass();
1879 }
Jeff Haode19a252016-09-14 15:56:35 -07001880
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001881 // TODO: should we give up now if receiver_class is null?
Ian Rogersc0542af2014-09-03 16:16:56 -07001882 if (receiver_class != nullptr && !f->GetDeclaringClass()->IsAssignableFrom(receiver_class)) {
David Sehr709b0702016-10-13 09:12:37 -07001883 LOG(INFO) << "ERR_INVALID_FIELDID: " << f->PrettyField() << " "
1884 << receiver_class->PrettyClass();
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001885 return JDWP::ERR_INVALID_FIELDID;
1886 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001887
Jeff Haode19a252016-09-14 15:56:35 -07001888 // Ensure the field's class is initialized.
1889 Handle<mirror::Class> klass(hs.NewHandle(f->GetDeclaringClass()));
1890 if (!Runtime::Current()->GetClassLinker()->EnsureInitialized(self, klass, true, false)) {
David Sehr709b0702016-10-13 09:12:37 -07001891 LOG(WARNING) << "Not able to initialize class for SetValues: "
1892 << mirror::Class::PrettyClass(klass.Get());
Jeff Haode19a252016-09-14 15:56:35 -07001893 }
1894
Elliott Hughes0cf74332012-02-23 23:14:00 -08001895 // The RI only enforces the static/non-static mismatch in one direction.
1896 // TODO: should we change the tests and check both?
1897 if (is_static) {
1898 if (!f->IsStatic()) {
1899 return JDWP::ERR_INVALID_FIELDID;
1900 }
1901 } else {
1902 if (f->IsStatic()) {
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001903 LOG(WARNING) << "Ignoring non-nullptr receiver for ObjectReference.GetValues"
David Sehr709b0702016-10-13 09:12:37 -07001904 << " on static field " << f->PrettyField();
Elliott Hughes0cf74332012-02-23 23:14:00 -08001905 }
1906 }
jeffhao0dfbb7e2012-11-28 15:26:03 -08001907 if (f->IsStatic()) {
Jeff Haode19a252016-09-14 15:56:35 -07001908 o.Assign(f->GetDeclaringClass());
jeffhao0dfbb7e2012-11-28 15:26:03 -08001909 }
Elliott Hughes0cf74332012-02-23 23:14:00 -08001910
Jeff Haode19a252016-09-14 15:56:35 -07001911 JValue field_value(GetArtFieldValue(f, o.Get()));
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001912 JDWP::JdwpTag tag = BasicTagFromDescriptor(f->GetTypeDescriptor());
Jeff Hao579b0242013-11-18 13:16:49 -08001913 Dbg::OutputJValue(tag, &field_value, pReply);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001914 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001915}
1916
Elliott Hughes88d63092013-01-09 09:55:54 -08001917JDWP::JdwpError Dbg::GetFieldValue(JDWP::ObjectId object_id, JDWP::FieldId field_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001918 JDWP::ExpandBuf* pReply) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001919 return GetFieldValueImpl(0, object_id, field_id, pReply, false);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001920}
1921
Ian Rogersc0542af2014-09-03 16:16:56 -07001922JDWP::JdwpError Dbg::GetStaticFieldValue(JDWP::RefTypeId ref_type_id, JDWP::FieldId field_id,
1923 JDWP::ExpandBuf* pReply) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001924 return GetFieldValueImpl(ref_type_id, 0, field_id, pReply, true);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001925}
1926
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001927static JDWP::JdwpError SetArtFieldValue(ArtField* f, mirror::Object* o, uint64_t value, int width)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001928 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001929 Primitive::Type fieldType = f->GetTypeAsPrimitiveType();
1930 // Debugging only happens at runtime so we know we are not running in a transaction.
1931 static constexpr bool kNoTransactionMode = false;
1932 switch (fieldType) {
1933 case Primitive::kPrimBoolean:
1934 CHECK_EQ(width, 1);
1935 f->SetBoolean<kNoTransactionMode>(o, static_cast<uint8_t>(value));
1936 return JDWP::ERR_NONE;
1937
1938 case Primitive::kPrimByte:
1939 CHECK_EQ(width, 1);
1940 f->SetByte<kNoTransactionMode>(o, static_cast<uint8_t>(value));
1941 return JDWP::ERR_NONE;
1942
1943 case Primitive::kPrimChar:
1944 CHECK_EQ(width, 2);
1945 f->SetChar<kNoTransactionMode>(o, static_cast<uint16_t>(value));
1946 return JDWP::ERR_NONE;
1947
1948 case Primitive::kPrimShort:
1949 CHECK_EQ(width, 2);
1950 f->SetShort<kNoTransactionMode>(o, static_cast<int16_t>(value));
1951 return JDWP::ERR_NONE;
1952
1953 case Primitive::kPrimInt:
1954 case Primitive::kPrimFloat:
1955 CHECK_EQ(width, 4);
1956 // Int and Float must be treated as 32-bit values in JDWP.
1957 f->SetInt<kNoTransactionMode>(o, static_cast<int32_t>(value));
1958 return JDWP::ERR_NONE;
1959
1960 case Primitive::kPrimLong:
1961 case Primitive::kPrimDouble:
1962 CHECK_EQ(width, 8);
1963 // Long and Double must be treated as 64-bit values in JDWP.
1964 f->SetLong<kNoTransactionMode>(o, value);
1965 return JDWP::ERR_NONE;
1966
1967 case Primitive::kPrimNot: {
1968 JDWP::JdwpError error;
1969 mirror::Object* v = Dbg::GetObjectRegistry()->Get<mirror::Object*>(value, &error);
1970 if (error != JDWP::ERR_NONE) {
1971 return JDWP::ERR_INVALID_OBJECT;
1972 }
1973 if (v != nullptr) {
Mathieu Chartier3398c782016-09-30 10:27:43 -07001974 ObjPtr<mirror::Class> field_type;
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001975 {
1976 StackHandleScope<2> hs(Thread::Current());
1977 HandleWrapper<mirror::Object> h_v(hs.NewHandleWrapper(&v));
1978 HandleWrapper<mirror::Object> h_o(hs.NewHandleWrapper(&o));
Vladimir Marko4098a7a2017-11-06 16:00:51 +00001979 field_type = f->ResolveType();
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001980 }
1981 if (!field_type->IsAssignableFrom(v->GetClass())) {
1982 return JDWP::ERR_INVALID_OBJECT;
1983 }
1984 }
1985 f->SetObject<kNoTransactionMode>(o, v);
1986 return JDWP::ERR_NONE;
1987 }
1988
1989 case Primitive::kPrimVoid:
1990 LOG(FATAL) << "Attempt to write to field of type 'void'";
1991 UNREACHABLE();
1992 }
1993 LOG(FATAL) << "Attempt to write to field of unknown type";
1994 UNREACHABLE();
1995}
1996
Elliott Hughes88d63092013-01-09 09:55:54 -08001997static JDWP::JdwpError SetFieldValueImpl(JDWP::ObjectId object_id, JDWP::FieldId field_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001998 uint64_t value, int width, bool is_static)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001999 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -07002000 JDWP::JdwpError error;
Jeff Haode19a252016-09-14 15:56:35 -07002001 Thread* self = Thread::Current();
2002 StackHandleScope<2> hs(self);
2003 MutableHandle<mirror::Object>
2004 o(hs.NewHandle(Dbg::GetObjectRegistry()->Get<mirror::Object*>(object_id, &error)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08002005 if ((!is_static && o == nullptr) || error != JDWP::ERR_NONE) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002006 return JDWP::ERR_INVALID_OBJECT;
2007 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07002008 ArtField* f = FromFieldId(field_id);
Elliott Hughes0cf74332012-02-23 23:14:00 -08002009
Jeff Haode19a252016-09-14 15:56:35 -07002010 // Ensure the field's class is initialized.
2011 Handle<mirror::Class> klass(hs.NewHandle(f->GetDeclaringClass()));
2012 if (!Runtime::Current()->GetClassLinker()->EnsureInitialized(self, klass, true, false)) {
David Sehr709b0702016-10-13 09:12:37 -07002013 LOG(WARNING) << "Not able to initialize class for SetValues: "
2014 << mirror::Class::PrettyClass(klass.Get());
Jeff Haode19a252016-09-14 15:56:35 -07002015 }
2016
Elliott Hughes0cf74332012-02-23 23:14:00 -08002017 // The RI only enforces the static/non-static mismatch in one direction.
2018 // TODO: should we change the tests and check both?
2019 if (is_static) {
2020 if (!f->IsStatic()) {
2021 return JDWP::ERR_INVALID_FIELDID;
2022 }
2023 } else {
2024 if (f->IsStatic()) {
Sebastien Hertz05c26b32015-06-11 18:42:58 +02002025 LOG(WARNING) << "Ignoring non-nullptr receiver for ObjectReference.SetValues"
David Sehr709b0702016-10-13 09:12:37 -07002026 << " on static field " << f->PrettyField();
Elliott Hughes0cf74332012-02-23 23:14:00 -08002027 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002028 }
jeffhao0dfbb7e2012-11-28 15:26:03 -08002029 if (f->IsStatic()) {
Jeff Haode19a252016-09-14 15:56:35 -07002030 o.Assign(f->GetDeclaringClass());
jeffhao0dfbb7e2012-11-28 15:26:03 -08002031 }
Jeff Haode19a252016-09-14 15:56:35 -07002032 return SetArtFieldValue(f, o.Get(), value, width);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002033}
2034
Elliott Hughes88d63092013-01-09 09:55:54 -08002035JDWP::JdwpError Dbg::SetFieldValue(JDWP::ObjectId object_id, JDWP::FieldId field_id, uint64_t value,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002036 int width) {
Elliott Hughes88d63092013-01-09 09:55:54 -08002037 return SetFieldValueImpl(object_id, field_id, value, width, false);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002038}
2039
Elliott Hughes88d63092013-01-09 09:55:54 -08002040JDWP::JdwpError Dbg::SetStaticFieldValue(JDWP::FieldId field_id, uint64_t value, int width) {
2041 return SetFieldValueImpl(0, field_id, value, width, true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002042}
2043
Sebastien Hertzb0b0b492014-09-15 11:27:27 +02002044JDWP::JdwpError Dbg::StringToUtf8(JDWP::ObjectId string_id, std::string* str) {
Ian Rogersc0542af2014-09-03 16:16:56 -07002045 JDWP::JdwpError error;
Sebastien Hertzb0b0b492014-09-15 11:27:27 +02002046 mirror::Object* obj = gRegistry->Get<mirror::Object*>(string_id, &error);
2047 if (error != JDWP::ERR_NONE) {
2048 return error;
2049 }
2050 if (obj == nullptr) {
2051 return JDWP::ERR_INVALID_OBJECT;
2052 }
2053 {
2054 ScopedObjectAccessUnchecked soa(Thread::Current());
Mathieu Chartier0795f232016-09-27 18:43:30 -07002055 ObjPtr<mirror::Class> java_lang_String =
2056 soa.Decode<mirror::Class>(WellKnownClasses::java_lang_String);
Sebastien Hertzb0b0b492014-09-15 11:27:27 +02002057 if (!java_lang_String->IsAssignableFrom(obj->GetClass())) {
2058 // This isn't a string.
2059 return JDWP::ERR_INVALID_STRING;
2060 }
2061 }
2062 *str = obj->AsString()->ToModifiedUtf8();
2063 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002064}
2065
Jeff Hao579b0242013-11-18 13:16:49 -08002066void Dbg::OutputJValue(JDWP::JdwpTag tag, const JValue* return_value, JDWP::ExpandBuf* pReply) {
2067 if (IsPrimitiveTag(tag)) {
2068 expandBufAdd1(pReply, tag);
2069 if (tag == JDWP::JT_BOOLEAN || tag == JDWP::JT_BYTE) {
2070 expandBufAdd1(pReply, return_value->GetI());
2071 } else if (tag == JDWP::JT_CHAR || tag == JDWP::JT_SHORT) {
2072 expandBufAdd2BE(pReply, return_value->GetI());
2073 } else if (tag == JDWP::JT_FLOAT || tag == JDWP::JT_INT) {
2074 expandBufAdd4BE(pReply, return_value->GetI());
2075 } else if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
2076 expandBufAdd8BE(pReply, return_value->GetJ());
2077 } else {
2078 CHECK_EQ(tag, JDWP::JT_VOID);
2079 }
2080 } else {
Ian Rogers98379392014-02-24 16:53:16 -08002081 ScopedObjectAccessUnchecked soa(Thread::Current());
Jeff Hao579b0242013-11-18 13:16:49 -08002082 mirror::Object* value = return_value->GetL();
Ian Rogers98379392014-02-24 16:53:16 -08002083 expandBufAdd1(pReply, TagFromObject(soa, value));
Jeff Hao579b0242013-11-18 13:16:49 -08002084 expandBufAddObjectId(pReply, gRegistry->Add(value));
2085 }
2086}
2087
Ian Rogersc0542af2014-09-03 16:16:56 -07002088JDWP::JdwpError Dbg::GetThreadName(JDWP::ObjectId thread_id, std::string* name) {
jeffhaoa77f0f62012-12-05 17:19:31 -08002089 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002090 JDWP::JdwpError error;
Roland Levillain4b8f1ec2015-08-26 18:34:03 +01002091 DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002092 if (error != JDWP::ERR_NONE && error != JDWP::ERR_THREAD_NOT_ALIVE) {
2093 return error;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08002094 }
Elliott Hughes221229c2013-01-08 18:17:50 -08002095
2096 // We still need to report the zombie threads' names, so we can't just call Thread::GetThreadName.
Ian Rogersc0542af2014-09-03 16:16:56 -07002097 mirror::Object* thread_object = gRegistry->Get<mirror::Object*>(thread_id, &error);
2098 CHECK(thread_object != nullptr) << error;
Mathieu Chartierc7853442015-03-27 14:35:38 -07002099 ArtField* java_lang_Thread_name_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08002100 jni::DecodeArtField(WellKnownClasses::java_lang_Thread_name);
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07002101 ObjPtr<mirror::String> s(java_lang_Thread_name_field->GetObject(thread_object)->AsString());
Ian Rogersc0542af2014-09-03 16:16:56 -07002102 if (s != nullptr) {
2103 *name = s->ToModifiedUtf8();
Elliott Hughes221229c2013-01-08 18:17:50 -08002104 }
2105 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002106}
2107
Elliott Hughes221229c2013-01-08 18:17:50 -08002108JDWP::JdwpError Dbg::GetThreadGroup(JDWP::ObjectId thread_id, JDWP::ExpandBuf* pReply) {
Sebastien Hertza06430c2014-09-15 19:21:30 +02002109 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002110 JDWP::JdwpError error;
2111 mirror::Object* thread_object = gRegistry->Get<mirror::Object*>(thread_id, &error);
2112 if (error != JDWP::ERR_NONE) {
Elliott Hughes2435a572012-02-17 16:07:41 -08002113 return JDWP::ERR_INVALID_OBJECT;
2114 }
Mathieu Chartier268764d2016-09-13 12:09:38 -07002115 ScopedAssertNoThreadSuspension ants("Debugger: GetThreadGroup");
Elliott Hughes2435a572012-02-17 16:07:41 -08002116 // Okay, so it's an object, but is it actually a thread?
Roland Levillain4b8f1ec2015-08-26 18:34:03 +01002117 DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002118 if (error == JDWP::ERR_THREAD_NOT_ALIVE) {
2119 // Zombie threads are in the null group.
2120 expandBufAddObjectId(pReply, JDWP::ObjectId(0));
Sebastien Hertz52d131d2014-03-13 16:17:40 +01002121 error = JDWP::ERR_NONE;
2122 } else if (error == JDWP::ERR_NONE) {
Mathieu Chartier0795f232016-09-27 18:43:30 -07002123 ObjPtr<mirror::Class> c = soa.Decode<mirror::Class>(WellKnownClasses::java_lang_Thread);
Sebastien Hertz52d131d2014-03-13 16:17:40 +01002124 CHECK(c != nullptr);
Andreas Gampe08883de2016-11-08 13:20:52 -08002125 ArtField* f = jni::DecodeArtField(WellKnownClasses::java_lang_Thread_group);
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07002126 CHECK(f != nullptr);
Mathieu Chartier3398c782016-09-30 10:27:43 -07002127 ObjPtr<mirror::Object> group = f->GetObject(thread_object);
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07002128 CHECK(group != nullptr);
Sebastien Hertz52d131d2014-03-13 16:17:40 +01002129 JDWP::ObjectId thread_group_id = gRegistry->Add(group);
2130 expandBufAddObjectId(pReply, thread_group_id);
Elliott Hughes221229c2013-01-08 18:17:50 -08002131 }
Sebastien Hertz52d131d2014-03-13 16:17:40 +01002132 return error;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002133}
2134
Sebastien Hertza06430c2014-09-15 19:21:30 +02002135static mirror::Object* DecodeThreadGroup(ScopedObjectAccessUnchecked& soa,
2136 JDWP::ObjectId thread_group_id, JDWP::JdwpError* error)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002137 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz6995c602014-09-09 12:10:13 +02002138 mirror::Object* thread_group = Dbg::GetObjectRegistry()->Get<mirror::Object*>(thread_group_id,
2139 error);
Sebastien Hertza06430c2014-09-15 19:21:30 +02002140 if (*error != JDWP::ERR_NONE) {
2141 return nullptr;
2142 }
2143 if (thread_group == nullptr) {
2144 *error = JDWP::ERR_INVALID_OBJECT;
2145 return nullptr;
2146 }
Mathieu Chartier0795f232016-09-27 18:43:30 -07002147 ObjPtr<mirror::Class> c =
2148 soa.Decode<mirror::Class>(WellKnownClasses::java_lang_ThreadGroup);
Ian Rogers98379392014-02-24 16:53:16 -08002149 CHECK(c != nullptr);
Sebastien Hertza06430c2014-09-15 19:21:30 +02002150 if (!c->IsAssignableFrom(thread_group->GetClass())) {
2151 // This is not a java.lang.ThreadGroup.
2152 *error = JDWP::ERR_INVALID_THREAD_GROUP;
2153 return nullptr;
2154 }
2155 *error = JDWP::ERR_NONE;
2156 return thread_group;
2157}
2158
2159JDWP::JdwpError Dbg::GetThreadGroupName(JDWP::ObjectId thread_group_id, JDWP::ExpandBuf* pReply) {
2160 ScopedObjectAccessUnchecked soa(Thread::Current());
2161 JDWP::JdwpError error;
2162 mirror::Object* thread_group = DecodeThreadGroup(soa, thread_group_id, &error);
2163 if (error != JDWP::ERR_NONE) {
2164 return error;
2165 }
Mathieu Chartier268764d2016-09-13 12:09:38 -07002166 ScopedAssertNoThreadSuspension ants("Debugger: GetThreadGroupName");
Andreas Gampe08883de2016-11-08 13:20:52 -08002167 ArtField* f = jni::DecodeArtField(WellKnownClasses::java_lang_ThreadGroup_name);
Ian Rogersc0542af2014-09-03 16:16:56 -07002168 CHECK(f != nullptr);
Mathieu Chartier3398c782016-09-30 10:27:43 -07002169 ObjPtr<mirror::String> s = f->GetObject(thread_group)->AsString();
Sebastien Hertza06430c2014-09-15 19:21:30 +02002170
2171 std::string thread_group_name(s->ToModifiedUtf8());
2172 expandBufAddUtf8String(pReply, thread_group_name);
2173 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002174}
2175
Sebastien Hertza06430c2014-09-15 19:21:30 +02002176JDWP::JdwpError Dbg::GetThreadGroupParent(JDWP::ObjectId thread_group_id, JDWP::ExpandBuf* pReply) {
Ian Rogers98379392014-02-24 16:53:16 -08002177 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002178 JDWP::JdwpError error;
Sebastien Hertza06430c2014-09-15 19:21:30 +02002179 mirror::Object* thread_group = DecodeThreadGroup(soa, thread_group_id, &error);
2180 if (error != JDWP::ERR_NONE) {
2181 return error;
2182 }
Mathieu Chartier3398c782016-09-30 10:27:43 -07002183 ObjPtr<mirror::Object> parent;
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07002184 {
Mathieu Chartier268764d2016-09-13 12:09:38 -07002185 ScopedAssertNoThreadSuspension ants("Debugger: GetThreadGroupParent");
Andreas Gampe08883de2016-11-08 13:20:52 -08002186 ArtField* f = jni::DecodeArtField(WellKnownClasses::java_lang_ThreadGroup_parent);
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07002187 CHECK(f != nullptr);
2188 parent = f->GetObject(thread_group);
2189 }
Sebastien Hertza06430c2014-09-15 19:21:30 +02002190 JDWP::ObjectId parent_group_id = gRegistry->Add(parent);
2191 expandBufAddObjectId(pReply, parent_group_id);
2192 return JDWP::ERR_NONE;
2193}
2194
Andreas Gampe08883de2016-11-08 13:20:52 -08002195static void GetChildThreadGroups(mirror::Object* thread_group,
Sebastien Hertza06430c2014-09-15 19:21:30 +02002196 std::vector<JDWP::ObjectId>* child_thread_group_ids)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002197 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertza06430c2014-09-15 19:21:30 +02002198 CHECK(thread_group != nullptr);
2199
Przemyslaw Szczepaniak464595f2015-11-24 11:59:59 +00002200 // Get the int "ngroups" count of this thread group...
Andreas Gampe08883de2016-11-08 13:20:52 -08002201 ArtField* ngroups_field = jni::DecodeArtField(WellKnownClasses::java_lang_ThreadGroup_ngroups);
Przemyslaw Szczepaniak464595f2015-11-24 11:59:59 +00002202 CHECK(ngroups_field != nullptr);
2203 const int32_t size = ngroups_field->GetInt(thread_group);
2204 if (size == 0) {
2205 return;
Sebastien Hertze49e1952014-10-13 11:27:13 +02002206 }
Sebastien Hertza06430c2014-09-15 19:21:30 +02002207
Przemyslaw Szczepaniak464595f2015-11-24 11:59:59 +00002208 // Get the ThreadGroup[] "groups" out of this thread group...
Andreas Gampe08883de2016-11-08 13:20:52 -08002209 ArtField* groups_field = jni::DecodeArtField(WellKnownClasses::java_lang_ThreadGroup_groups);
Mathieu Chartier3398c782016-09-30 10:27:43 -07002210 ObjPtr<mirror::Object> groups_array = groups_field->GetObject(thread_group);
Przemyslaw Szczepaniak464595f2015-11-24 11:59:59 +00002211
2212 CHECK(groups_array != nullptr);
2213 CHECK(groups_array->IsObjectArray());
2214
Mathieu Chartier3398c782016-09-30 10:27:43 -07002215 ObjPtr<mirror::ObjectArray<mirror::Object>> groups_array_as_array =
Przemyslaw Szczepaniak464595f2015-11-24 11:59:59 +00002216 groups_array->AsObjectArray<mirror::Object>();
Sebastien Hertza06430c2014-09-15 19:21:30 +02002217
2218 // Copy the first 'size' elements out of the array into the result.
Sebastien Hertz6995c602014-09-09 12:10:13 +02002219 ObjectRegistry* registry = Dbg::GetObjectRegistry();
Sebastien Hertza06430c2014-09-15 19:21:30 +02002220 for (int32_t i = 0; i < size; ++i) {
Przemyslaw Szczepaniak464595f2015-11-24 11:59:59 +00002221 child_thread_group_ids->push_back(registry->Add(groups_array_as_array->Get(i)));
Sebastien Hertza06430c2014-09-15 19:21:30 +02002222 }
2223}
2224
2225JDWP::JdwpError Dbg::GetThreadGroupChildren(JDWP::ObjectId thread_group_id,
2226 JDWP::ExpandBuf* pReply) {
2227 ScopedObjectAccessUnchecked soa(Thread::Current());
2228 JDWP::JdwpError error;
2229 mirror::Object* thread_group = DecodeThreadGroup(soa, thread_group_id, &error);
2230 if (error != JDWP::ERR_NONE) {
2231 return error;
2232 }
2233
2234 // Add child threads.
2235 {
2236 std::vector<JDWP::ObjectId> child_thread_ids;
2237 GetThreads(thread_group, &child_thread_ids);
2238 expandBufAdd4BE(pReply, child_thread_ids.size());
2239 for (JDWP::ObjectId child_thread_id : child_thread_ids) {
2240 expandBufAddObjectId(pReply, child_thread_id);
2241 }
2242 }
2243
2244 // Add child thread groups.
2245 {
2246 std::vector<JDWP::ObjectId> child_thread_groups_ids;
Andreas Gampe08883de2016-11-08 13:20:52 -08002247 GetChildThreadGroups(thread_group, &child_thread_groups_ids);
Sebastien Hertza06430c2014-09-15 19:21:30 +02002248 expandBufAdd4BE(pReply, child_thread_groups_ids.size());
2249 for (JDWP::ObjectId child_thread_group_id : child_thread_groups_ids) {
2250 expandBufAddObjectId(pReply, child_thread_group_id);
2251 }
2252 }
2253
2254 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002255}
2256
2257JDWP::ObjectId Dbg::GetSystemThreadGroupId() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002258 ScopedObjectAccessUnchecked soa(Thread::Current());
Andreas Gampe08883de2016-11-08 13:20:52 -08002259 ArtField* f = jni::DecodeArtField(WellKnownClasses::java_lang_ThreadGroup_systemThreadGroup);
Mathieu Chartier3398c782016-09-30 10:27:43 -07002260 ObjPtr<mirror::Object> group = f->GetObject(f->GetDeclaringClass());
Ian Rogers365c1022012-06-22 15:05:28 -07002261 return gRegistry->Add(group);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002262}
2263
Jeff Hao920af3e2013-08-28 15:46:38 -07002264JDWP::JdwpThreadStatus Dbg::ToJdwpThreadStatus(ThreadState state) {
2265 switch (state) {
2266 case kBlocked:
2267 return JDWP::TS_MONITOR;
2268 case kNative:
2269 case kRunnable:
2270 case kSuspended:
2271 return JDWP::TS_RUNNING;
2272 case kSleeping:
2273 return JDWP::TS_SLEEPING;
2274 case kStarting:
2275 case kTerminated:
2276 return JDWP::TS_ZOMBIE;
2277 case kTimedWaiting:
Alex Light77fee872017-09-05 14:51:49 -07002278 case kWaitingForTaskProcessor:
2279 case kWaitingForLockInflation:
Sebastien Hertzbae182c2013-12-17 10:42:03 +01002280 case kWaitingForCheckPointsToRun:
Jeff Hao920af3e2013-08-28 15:46:38 -07002281 case kWaitingForDebuggerSend:
2282 case kWaitingForDebuggerSuspension:
2283 case kWaitingForDebuggerToAttach:
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002284 case kWaitingForDeoptimization:
Jeff Hao920af3e2013-08-28 15:46:38 -07002285 case kWaitingForGcToComplete:
Mathieu Chartierb43390c2015-05-12 10:47:11 -07002286 case kWaitingForGetObjectsAllocated:
Jeff Hao920af3e2013-08-28 15:46:38 -07002287 case kWaitingForJniOnLoad:
Sebastien Hertzbae182c2013-12-17 10:42:03 +01002288 case kWaitingForMethodTracingStart:
Jeff Hao920af3e2013-08-28 15:46:38 -07002289 case kWaitingForSignalCatcherOutput:
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -08002290 case kWaitingForVisitObjects:
Jeff Hao920af3e2013-08-28 15:46:38 -07002291 case kWaitingInMainDebuggerLoop:
2292 case kWaitingInMainSignalCatcherLoop:
2293 case kWaitingPerformingGc:
Mathieu Chartier90ef3db2015-08-04 15:19:41 -07002294 case kWaitingWeakGcRootRead:
Hiroshi Yamauchi76f55b02015-08-21 16:10:39 -07002295 case kWaitingForGcThreadFlip:
Jeff Hao920af3e2013-08-28 15:46:38 -07002296 case kWaiting:
2297 return JDWP::TS_WAIT;
2298 // Don't add a 'default' here so the compiler can spot incompatible enum changes.
2299 }
2300 LOG(FATAL) << "Unknown thread state: " << state;
2301 return JDWP::TS_ZOMBIE;
2302}
2303
Sebastien Hertz52d131d2014-03-13 16:17:40 +01002304JDWP::JdwpError Dbg::GetThreadStatus(JDWP::ObjectId thread_id, JDWP::JdwpThreadStatus* pThreadStatus,
2305 JDWP::JdwpSuspendStatus* pSuspendStatus) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002306 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes499c5132011-11-17 14:55:11 -08002307
Elliott Hughes9e0c1752013-01-09 14:02:58 -08002308 *pSuspendStatus = JDWP::SUSPEND_STATUS_NOT_SUSPENDED;
2309
Ian Rogersc0542af2014-09-03 16:16:56 -07002310 JDWP::JdwpError error;
2311 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002312 if (error != JDWP::ERR_NONE) {
2313 if (error == JDWP::ERR_THREAD_NOT_ALIVE) {
2314 *pThreadStatus = JDWP::TS_ZOMBIE;
Elliott Hughes221229c2013-01-08 18:17:50 -08002315 return JDWP::ERR_NONE;
2316 }
2317 return error;
Elliott Hughes499c5132011-11-17 14:55:11 -08002318 }
2319
Elliott Hughes9e0c1752013-01-09 14:02:58 -08002320 if (IsSuspendedForDebugger(soa, thread)) {
2321 *pSuspendStatus = JDWP::SUSPEND_STATUS_SUSPENDED;
Elliott Hughes499c5132011-11-17 14:55:11 -08002322 }
2323
Jeff Hao920af3e2013-08-28 15:46:38 -07002324 *pThreadStatus = ToJdwpThreadStatus(thread->GetState());
Elliott Hughes221229c2013-01-08 18:17:50 -08002325 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002326}
2327
Elliott Hughes221229c2013-01-08 18:17:50 -08002328JDWP::JdwpError Dbg::GetThreadDebugSuspendCount(JDWP::ObjectId thread_id, JDWP::ExpandBuf* pReply) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002329 ScopedObjectAccess soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002330 JDWP::JdwpError error;
2331 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002332 if (error != JDWP::ERR_NONE) {
2333 return error;
Elliott Hughes2435a572012-02-17 16:07:41 -08002334 }
Ian Rogers50b35e22012-10-04 10:09:15 -07002335 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002336 expandBufAdd4BE(pReply, thread->GetDebugSuspendCount());
Elliott Hughes2435a572012-02-17 16:07:41 -08002337 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002338}
2339
Elliott Hughesf9501702013-01-11 11:22:27 -08002340JDWP::JdwpError Dbg::Interrupt(JDWP::ObjectId thread_id) {
2341 ScopedObjectAccess soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002342 JDWP::JdwpError error;
2343 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughesf9501702013-01-11 11:22:27 -08002344 if (error != JDWP::ERR_NONE) {
2345 return error;
2346 }
Ian Rogersdd7624d2014-03-14 17:43:00 -07002347 thread->Interrupt(soa.Self());
Elliott Hughesf9501702013-01-11 11:22:27 -08002348 return JDWP::ERR_NONE;
2349}
2350
Andreas Gampe08883de2016-11-08 13:20:52 -08002351static bool IsInDesiredThreadGroup(mirror::Object* desired_thread_group, mirror::Object* peer)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002352 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz070f7322014-09-09 12:08:49 +02002353 // Do we want threads from all thread groups?
2354 if (desired_thread_group == nullptr) {
2355 return true;
2356 }
Andreas Gampe08883de2016-11-08 13:20:52 -08002357 ArtField* thread_group_field = jni::DecodeArtField(WellKnownClasses::java_lang_Thread_group);
Sebastien Hertz070f7322014-09-09 12:08:49 +02002358 DCHECK(thread_group_field != nullptr);
Mathieu Chartier3398c782016-09-30 10:27:43 -07002359 ObjPtr<mirror::Object> group = thread_group_field->GetObject(peer);
Sebastien Hertz070f7322014-09-09 12:08:49 +02002360 return (group == desired_thread_group);
2361}
2362
Sebastien Hertza06430c2014-09-15 19:21:30 +02002363void Dbg::GetThreads(mirror::Object* thread_group, std::vector<JDWP::ObjectId>* thread_ids) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002364 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz070f7322014-09-09 12:08:49 +02002365 std::list<Thread*> all_threads_list;
2366 {
2367 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
2368 all_threads_list = Runtime::Current()->GetThreadList()->GetList();
2369 }
2370 for (Thread* t : all_threads_list) {
2371 if (t == Dbg::GetDebugThread()) {
2372 // Skip the JDWP thread. Some debuggers get bent out of shape when they can't suspend and
2373 // query all threads, so it's easier if we just don't tell them about this thread.
2374 continue;
2375 }
2376 if (t->IsStillStarting()) {
2377 // This thread is being started (and has been registered in the thread list). However, it is
2378 // not completely started yet so we must ignore it.
2379 continue;
2380 }
Nicolas Geoffraycafa0812017-02-15 18:27:34 +00002381 mirror::Object* peer = t->GetPeerFromOtherThread();
Sebastien Hertz070f7322014-09-09 12:08:49 +02002382 if (peer == nullptr) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002383 // 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 +02002384 // this thread yet.
2385 // TODO: if we identified threads to the debugger by their Thread*
2386 // rather than their peer's mirror::Object*, we could fix this.
2387 // Doing so might help us report ZOMBIE threads too.
2388 continue;
2389 }
Andreas Gampe08883de2016-11-08 13:20:52 -08002390 if (IsInDesiredThreadGroup(thread_group, peer)) {
Sebastien Hertz070f7322014-09-09 12:08:49 +02002391 thread_ids->push_back(gRegistry->Add(peer));
2392 }
2393 }
Elliott Hughescaf76542012-06-28 16:08:22 -07002394}
Elliott Hughesa2155262011-11-16 16:26:58 -08002395
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002396static int GetStackDepth(Thread* thread) REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002397 struct CountStackDepthVisitor : public StackVisitor {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002398 explicit CountStackDepthVisitor(Thread* thread_in)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01002399 : StackVisitor(thread_in, nullptr, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
2400 depth(0) {}
Ian Rogers0399dde2012-06-06 17:09:28 -07002401
Elliott Hughes64f574f2013-02-20 14:57:12 -08002402 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2403 // annotalysis.
2404 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07002405 if (!GetMethod()->IsRuntimeMethod()) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -08002406 ++depth;
2407 }
Elliott Hughes530fa002012-03-12 11:44:49 -07002408 return true;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08002409 }
2410 size_t depth;
2411 };
Elliott Hughes08fc03a2012-06-26 17:34:00 -07002412
Ian Rogers7a22fa62013-01-23 12:16:16 -08002413 CountStackDepthVisitor visitor(thread);
Ian Rogers0399dde2012-06-06 17:09:28 -07002414 visitor.WalkStack();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08002415 return visitor.depth;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002416}
2417
Ian Rogersc0542af2014-09-03 16:16:56 -07002418JDWP::JdwpError Dbg::GetThreadFrameCount(JDWP::ObjectId thread_id, size_t* result) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002419 ScopedObjectAccess soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002420 JDWP::JdwpError error;
2421 *result = 0;
2422 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002423 if (error != JDWP::ERR_NONE) {
2424 return error;
2425 }
Elliott Hughesf15f4a02013-01-09 10:09:38 -08002426 if (!IsSuspendedForDebugger(soa, thread)) {
2427 return JDWP::ERR_THREAD_NOT_SUSPENDED;
2428 }
Ian Rogersc0542af2014-09-03 16:16:56 -07002429 *result = GetStackDepth(thread);
Elliott Hughes221229c2013-01-08 18:17:50 -08002430 return JDWP::ERR_NONE;
Elliott Hughes86964332012-02-15 19:37:42 -08002431}
2432
Ian Rogers306057f2012-11-26 12:45:53 -08002433JDWP::JdwpError Dbg::GetThreadFrames(JDWP::ObjectId thread_id, size_t start_frame,
2434 size_t frame_count, JDWP::ExpandBuf* buf) {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002435 class GetFrameVisitor : public StackVisitor {
2436 public:
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002437 GetFrameVisitor(Thread* thread, size_t start_frame_in, size_t frame_count_in,
2438 JDWP::ExpandBuf* buf_in)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002439 REQUIRES_SHARED(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01002440 : StackVisitor(thread, nullptr, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
2441 depth_(0),
2442 start_frame_(start_frame_in),
2443 frame_count_(frame_count_in),
2444 buf_(buf_in) {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002445 expandBufAdd4BE(buf_, frame_count_);
Elliott Hughes03181a82011-11-17 17:22:21 -08002446 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002447
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002448 bool VisitFrame() OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002449 if (GetMethod()->IsRuntimeMethod()) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07002450 return true; // The debugger can't do anything useful with a frame that has no Method*.
Elliott Hughes03181a82011-11-17 17:22:21 -08002451 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002452 if (depth_ >= start_frame_ + frame_count_) {
Elliott Hughes530fa002012-03-12 11:44:49 -07002453 return false;
Elliott Hughes03181a82011-11-17 17:22:21 -08002454 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002455 if (depth_ >= start_frame_) {
2456 JDWP::FrameId frame_id(GetFrameId());
2457 JDWP::JdwpLocation location;
Sebastien Hertz6995c602014-09-09 12:10:13 +02002458 SetJdwpLocation(&location, GetMethod(), GetDexPc());
Ian Rogersef7d42f2014-01-06 12:55:46 -08002459 VLOG(jdwp) << StringPrintf(" Frame %3zd: id=%3" PRIu64 " ", depth_, frame_id) << location;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002460 expandBufAdd8BE(buf_, frame_id);
2461 expandBufAddLocation(buf_, location);
2462 }
2463 ++depth_;
Elliott Hughes530fa002012-03-12 11:44:49 -07002464 return true;
Elliott Hughes03181a82011-11-17 17:22:21 -08002465 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002466
2467 private:
2468 size_t depth_;
2469 const size_t start_frame_;
2470 const size_t frame_count_;
2471 JDWP::ExpandBuf* buf_;
Elliott Hughes03181a82011-11-17 17:22:21 -08002472 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002473
2474 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002475 JDWP::JdwpError error;
2476 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002477 if (error != JDWP::ERR_NONE) {
2478 return error;
2479 }
Elliott Hughesf15f4a02013-01-09 10:09:38 -08002480 if (!IsSuspendedForDebugger(soa, thread)) {
2481 return JDWP::ERR_THREAD_NOT_SUSPENDED;
2482 }
Ian Rogers7a22fa62013-01-23 12:16:16 -08002483 GetFrameVisitor visitor(thread, start_frame, frame_count, buf);
Ian Rogers0399dde2012-06-06 17:09:28 -07002484 visitor.WalkStack();
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002485 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002486}
2487
2488JDWP::ObjectId Dbg::GetThreadSelfId() {
Sebastien Hertz6995c602014-09-09 12:10:13 +02002489 return GetThreadId(Thread::Current());
2490}
2491
2492JDWP::ObjectId Dbg::GetThreadId(Thread* thread) {
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07002493 ScopedObjectAccessUnchecked soa(Thread::Current());
Nicolas Geoffraycafa0812017-02-15 18:27:34 +00002494 return gRegistry->Add(thread->GetPeerFromOtherThread());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002495}
2496
Elliott Hughes475fc232011-10-25 15:00:35 -07002497void Dbg::SuspendVM() {
Hiroshi Yamauchi8f95cf32016-04-19 11:14:06 -07002498 // Avoid a deadlock between GC and debugger where GC gets suspended during GC. b/25800335.
2499 gc::ScopedGCCriticalSection gcs(Thread::Current(),
2500 gc::kGcCauseDebugger,
2501 gc::kCollectorTypeDebugger);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002502 Runtime::Current()->GetThreadList()->SuspendAllForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002503}
2504
2505void Dbg::ResumeVM() {
Sebastien Hertz253fa552014-10-14 17:27:15 +02002506 Runtime::Current()->GetThreadList()->ResumeAllForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002507}
2508
Elliott Hughes221229c2013-01-08 18:17:50 -08002509JDWP::JdwpError Dbg::SuspendThread(JDWP::ObjectId thread_id, bool request_suspension) {
Ian Rogersf3d874c2014-07-17 18:52:42 -07002510 Thread* self = Thread::Current();
Ian Rogersc0542af2014-09-03 16:16:56 -07002511 ScopedLocalRef<jobject> peer(self->GetJniEnv(), nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002512 {
Ian Rogersf3d874c2014-07-17 18:52:42 -07002513 ScopedObjectAccess soa(self);
Ian Rogersc0542af2014-09-03 16:16:56 -07002514 JDWP::JdwpError error;
2515 peer.reset(soa.AddLocalReference<jobject>(gRegistry->Get<mirror::Object*>(thread_id, &error)));
Elliott Hughes4e235312011-12-02 11:34:15 -08002516 }
Ian Rogersc0542af2014-09-03 16:16:56 -07002517 if (peer.get() == nullptr) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002518 return JDWP::ERR_THREAD_NOT_ALIVE;
2519 }
Ian Rogers4ad5cd32014-11-11 23:08:07 -08002520 // Suspend thread to build stack trace.
Elliott Hughesf327e072013-01-09 16:01:26 -08002521 bool timed_out;
Brian Carlstromba32de42014-08-27 23:43:46 -07002522 ThreadList* thread_list = Runtime::Current()->GetThreadList();
Sebastien Hertzcdd798d2017-04-18 18:28:51 +02002523 Thread* thread = thread_list->SuspendThreadByPeer(peer.get(),
2524 request_suspension,
Alex Light46f93402017-06-29 11:59:50 -07002525 SuspendReason::kForDebugger,
Brian Carlstromba32de42014-08-27 23:43:46 -07002526 &timed_out);
Ian Rogersc0542af2014-09-03 16:16:56 -07002527 if (thread != nullptr) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002528 return JDWP::ERR_NONE;
Elliott Hughesf327e072013-01-09 16:01:26 -08002529 } else if (timed_out) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002530 return JDWP::ERR_INTERNAL;
2531 } else {
2532 return JDWP::ERR_THREAD_NOT_ALIVE;
2533 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002534}
2535
Elliott Hughes221229c2013-01-08 18:17:50 -08002536void Dbg::ResumeThread(JDWP::ObjectId thread_id) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002537 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002538 JDWP::JdwpError error;
2539 mirror::Object* peer = gRegistry->Get<mirror::Object*>(thread_id, &error);
2540 CHECK(peer != nullptr) << error;
jeffhaoa77f0f62012-12-05 17:19:31 -08002541 Thread* thread;
2542 {
2543 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
2544 thread = Thread::FromManagedThread(soa, peer);
2545 }
Ian Rogersc0542af2014-09-03 16:16:56 -07002546 if (thread == nullptr) {
Elliott Hughes4e235312011-12-02 11:34:15 -08002547 LOG(WARNING) << "No such thread for resume: " << peer;
2548 return;
2549 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002550 bool needs_resume;
2551 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002552 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Sebastien Hertz70d60272017-04-14 14:18:36 +02002553 needs_resume = thread->GetDebugSuspendCount() > 0;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002554 }
2555 if (needs_resume) {
Alex Light88fd7202017-06-30 08:31:59 -07002556 bool resumed = Runtime::Current()->GetThreadList()->Resume(thread, SuspendReason::kForDebugger);
2557 DCHECK(resumed);
Elliott Hughes546b9862012-06-20 16:06:13 -07002558 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002559}
2560
2561void Dbg::SuspendSelf() {
Elliott Hughes475fc232011-10-25 15:00:35 -07002562 Runtime::Current()->GetThreadList()->SuspendSelfForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002563}
2564
Ian Rogers0399dde2012-06-06 17:09:28 -07002565struct GetThisVisitor : public StackVisitor {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002566 GetThisVisitor(Thread* thread, Context* context, JDWP::FrameId frame_id_in)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002567 REQUIRES_SHARED(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01002568 : StackVisitor(thread, context, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
2569 this_object(nullptr),
2570 frame_id(frame_id_in) {}
Ian Rogers0399dde2012-06-06 17:09:28 -07002571
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002572 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2573 // annotalysis.
2574 virtual bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002575 if (frame_id != GetFrameId()) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002576 return true; // continue
Ian Rogers0399dde2012-06-06 17:09:28 -07002577 } else {
Ian Rogers62d6c772013-02-27 08:32:07 -08002578 this_object = GetThisObject();
2579 return false;
Ian Rogers0399dde2012-06-06 17:09:28 -07002580 }
Elliott Hughes86b00102011-12-05 17:54:26 -08002581 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002582
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002583 mirror::Object* this_object;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002584 JDWP::FrameId frame_id;
Ian Rogers0399dde2012-06-06 17:09:28 -07002585};
2586
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002587JDWP::JdwpError Dbg::GetThisObject(JDWP::ObjectId thread_id, JDWP::FrameId frame_id,
2588 JDWP::ObjectId* result) {
2589 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz69206392015-04-07 15:54:25 +02002590 JDWP::JdwpError error;
2591 Thread* thread = DecodeThread(soa, thread_id, &error);
2592 if (error != JDWP::ERR_NONE) {
2593 return error;
2594 }
2595 if (!IsSuspendedForDebugger(soa, thread)) {
2596 return JDWP::ERR_THREAD_NOT_SUSPENDED;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002597 }
Ian Rogers700a4022014-05-19 16:49:03 -07002598 std::unique_ptr<Context> context(Context::Create());
Ian Rogers7a22fa62013-01-23 12:16:16 -08002599 GetThisVisitor visitor(thread, context.get(), frame_id);
Ian Rogers0399dde2012-06-06 17:09:28 -07002600 visitor.WalkStack();
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002601 *result = gRegistry->Add(visitor.this_object);
2602 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002603}
2604
Sebastien Hertz8009f392014-09-01 17:07:11 +02002605// Walks the stack until we find the frame with the given FrameId.
2606class FindFrameVisitor FINAL : public StackVisitor {
2607 public:
2608 FindFrameVisitor(Thread* thread, Context* context, JDWP::FrameId frame_id)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002609 REQUIRES_SHARED(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01002610 : StackVisitor(thread, context, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
2611 frame_id_(frame_id),
2612 error_(JDWP::ERR_INVALID_FRAMEID) {}
Ian Rogersca190662012-06-26 15:45:57 -07002613
Sebastien Hertz8009f392014-09-01 17:07:11 +02002614 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2615 // annotalysis.
2616 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
2617 if (GetFrameId() != frame_id_) {
2618 return true; // Not our frame, carry on.
Ian Rogers0399dde2012-06-06 17:09:28 -07002619 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07002620 ArtMethod* m = GetMethod();
Sebastien Hertz8009f392014-09-01 17:07:11 +02002621 if (m->IsNative()) {
2622 // We can't read/write local value from/into native method.
2623 error_ = JDWP::ERR_OPAQUE_FRAME;
2624 } else {
2625 // We found our frame.
2626 error_ = JDWP::ERR_NONE;
2627 }
2628 return false;
2629 }
2630
2631 JDWP::JdwpError GetError() const {
2632 return error_;
2633 }
2634
2635 private:
2636 const JDWP::FrameId frame_id_;
2637 JDWP::JdwpError error_;
Sebastien Hertz26f72862015-09-15 09:52:07 +02002638
2639 DISALLOW_COPY_AND_ASSIGN(FindFrameVisitor);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002640};
2641
2642JDWP::JdwpError Dbg::GetLocalValues(JDWP::Request* request, JDWP::ExpandBuf* pReply) {
2643 JDWP::ObjectId thread_id = request->ReadThreadId();
2644 JDWP::FrameId frame_id = request->ReadFrameId();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002645
2646 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz69206392015-04-07 15:54:25 +02002647 JDWP::JdwpError error;
2648 Thread* thread = DecodeThread(soa, thread_id, &error);
2649 if (error != JDWP::ERR_NONE) {
2650 return error;
2651 }
2652 if (!IsSuspendedForDebugger(soa, thread)) {
2653 return JDWP::ERR_THREAD_NOT_SUSPENDED;
Elliott Hughes221229c2013-01-08 18:17:50 -08002654 }
Sebastien Hertz8009f392014-09-01 17:07:11 +02002655 // Find the frame with the given frame_id.
Ian Rogers700a4022014-05-19 16:49:03 -07002656 std::unique_ptr<Context> context(Context::Create());
Sebastien Hertz8009f392014-09-01 17:07:11 +02002657 FindFrameVisitor visitor(thread, context.get(), frame_id);
Ian Rogers0399dde2012-06-06 17:09:28 -07002658 visitor.WalkStack();
Sebastien Hertz8009f392014-09-01 17:07:11 +02002659 if (visitor.GetError() != JDWP::ERR_NONE) {
2660 return visitor.GetError();
2661 }
2662
2663 // Read the values from visitor's context.
2664 int32_t slot_count = request->ReadSigned32("slot count");
2665 expandBufAdd4BE(pReply, slot_count); /* "int values" */
2666 for (int32_t i = 0; i < slot_count; ++i) {
2667 uint32_t slot = request->ReadUnsigned32("slot");
2668 JDWP::JdwpTag reqSigByte = request->ReadTag();
2669
2670 VLOG(jdwp) << " --> slot " << slot << " " << reqSigByte;
2671
2672 size_t width = Dbg::GetTagWidth(reqSigByte);
Sebastien Hertz7d955652014-10-22 10:57:10 +02002673 uint8_t* ptr = expandBufAddSpace(pReply, width + 1);
Sebastien Hertz69206392015-04-07 15:54:25 +02002674 error = Dbg::GetLocalValue(visitor, soa, slot, reqSigByte, ptr, width);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002675 if (error != JDWP::ERR_NONE) {
2676 return error;
2677 }
2678 }
2679 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002680}
2681
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002682constexpr JDWP::JdwpError kStackFrameLocalAccessError = JDWP::ERR_ABSENT_INFORMATION;
2683
2684static std::string GetStackContextAsString(const StackVisitor& visitor)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002685 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002686 return StringPrintf(" at DEX pc 0x%08x in method %s", visitor.GetDexPc(false),
David Sehr709b0702016-10-13 09:12:37 -07002687 ArtMethod::PrettyMethod(visitor.GetMethod()).c_str());
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002688}
2689
2690static JDWP::JdwpError FailGetLocalValue(const StackVisitor& visitor, uint16_t vreg,
2691 JDWP::JdwpTag tag)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002692 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002693 LOG(ERROR) << "Failed to read " << tag << " local from register v" << vreg
2694 << GetStackContextAsString(visitor);
2695 return kStackFrameLocalAccessError;
2696}
2697
Sebastien Hertz8009f392014-09-01 17:07:11 +02002698JDWP::JdwpError Dbg::GetLocalValue(const StackVisitor& visitor, ScopedObjectAccessUnchecked& soa,
2699 int slot, JDWP::JdwpTag tag, uint8_t* buf, size_t width) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002700 ArtMethod* m = visitor.GetMethod();
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002701 JDWP::JdwpError error = JDWP::ERR_NONE;
2702 uint16_t vreg = DemangleSlot(slot, m, &error);
2703 if (error != JDWP::ERR_NONE) {
2704 return error;
2705 }
Sebastien Hertz8009f392014-09-01 17:07:11 +02002706 // TODO: check that the tag is compatible with the actual type of the slot!
Sebastien Hertz8009f392014-09-01 17:07:11 +02002707 switch (tag) {
2708 case JDWP::JT_BOOLEAN: {
2709 CHECK_EQ(width, 1U);
2710 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002711 if (!visitor.GetVReg(m, vreg, kIntVReg, &intVal)) {
2712 return FailGetLocalValue(visitor, vreg, tag);
Ian Rogers0399dde2012-06-06 17:09:28 -07002713 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002714 VLOG(jdwp) << "get boolean local " << vreg << " = " << intVal;
2715 JDWP::Set1(buf + 1, intVal != 0);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002716 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002717 }
Sebastien Hertz8009f392014-09-01 17:07:11 +02002718 case JDWP::JT_BYTE: {
2719 CHECK_EQ(width, 1U);
2720 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002721 if (!visitor.GetVReg(m, vreg, kIntVReg, &intVal)) {
2722 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002723 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002724 VLOG(jdwp) << "get byte local " << vreg << " = " << intVal;
2725 JDWP::Set1(buf + 1, intVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002726 break;
2727 }
2728 case JDWP::JT_SHORT:
2729 case JDWP::JT_CHAR: {
2730 CHECK_EQ(width, 2U);
2731 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002732 if (!visitor.GetVReg(m, vreg, kIntVReg, &intVal)) {
2733 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002734 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002735 VLOG(jdwp) << "get short/char local " << vreg << " = " << intVal;
2736 JDWP::Set2BE(buf + 1, intVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002737 break;
2738 }
2739 case JDWP::JT_INT: {
2740 CHECK_EQ(width, 4U);
2741 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002742 if (!visitor.GetVReg(m, vreg, kIntVReg, &intVal)) {
2743 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002744 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002745 VLOG(jdwp) << "get int local " << vreg << " = " << intVal;
2746 JDWP::Set4BE(buf + 1, intVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002747 break;
2748 }
2749 case JDWP::JT_FLOAT: {
2750 CHECK_EQ(width, 4U);
2751 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002752 if (!visitor.GetVReg(m, vreg, kFloatVReg, &intVal)) {
2753 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002754 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002755 VLOG(jdwp) << "get float local " << vreg << " = " << intVal;
2756 JDWP::Set4BE(buf + 1, intVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002757 break;
2758 }
2759 case JDWP::JT_ARRAY:
2760 case JDWP::JT_CLASS_LOADER:
2761 case JDWP::JT_CLASS_OBJECT:
2762 case JDWP::JT_OBJECT:
2763 case JDWP::JT_STRING:
2764 case JDWP::JT_THREAD:
2765 case JDWP::JT_THREAD_GROUP: {
2766 CHECK_EQ(width, sizeof(JDWP::ObjectId));
2767 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002768 if (!visitor.GetVReg(m, vreg, kReferenceVReg, &intVal)) {
2769 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002770 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002771 mirror::Object* o = reinterpret_cast<mirror::Object*>(intVal);
2772 VLOG(jdwp) << "get " << tag << " object local " << vreg << " = " << o;
2773 if (!Runtime::Current()->GetHeap()->IsValidObjectAddress(o)) {
2774 LOG(FATAL) << StringPrintf("Found invalid object %#" PRIxPTR " in register v%u",
2775 reinterpret_cast<uintptr_t>(o), vreg)
2776 << GetStackContextAsString(visitor);
2777 UNREACHABLE();
2778 }
2779 tag = TagFromObject(soa, o);
2780 JDWP::SetObjectId(buf + 1, gRegistry->Add(o));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002781 break;
2782 }
2783 case JDWP::JT_DOUBLE: {
2784 CHECK_EQ(width, 8U);
2785 uint64_t longVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002786 if (!visitor.GetVRegPair(m, vreg, kDoubleLoVReg, kDoubleHiVReg, &longVal)) {
2787 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002788 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002789 VLOG(jdwp) << "get double local " << vreg << " = " << longVal;
2790 JDWP::Set8BE(buf + 1, longVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002791 break;
2792 }
2793 case JDWP::JT_LONG: {
2794 CHECK_EQ(width, 8U);
2795 uint64_t longVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002796 if (!visitor.GetVRegPair(m, vreg, kLongLoVReg, kLongHiVReg, &longVal)) {
2797 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002798 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002799 VLOG(jdwp) << "get long local " << vreg << " = " << longVal;
2800 JDWP::Set8BE(buf + 1, longVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002801 break;
2802 }
2803 default:
2804 LOG(FATAL) << "Unknown tag " << tag;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002805 UNREACHABLE();
Sebastien Hertz8009f392014-09-01 17:07:11 +02002806 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002807
Sebastien Hertz8009f392014-09-01 17:07:11 +02002808 // Prepend tag, which may have been updated.
2809 JDWP::Set1(buf, tag);
2810 return JDWP::ERR_NONE;
2811}
2812
2813JDWP::JdwpError Dbg::SetLocalValues(JDWP::Request* request) {
2814 JDWP::ObjectId thread_id = request->ReadThreadId();
2815 JDWP::FrameId frame_id = request->ReadFrameId();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002816
2817 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz69206392015-04-07 15:54:25 +02002818 JDWP::JdwpError error;
2819 Thread* thread = DecodeThread(soa, thread_id, &error);
2820 if (error != JDWP::ERR_NONE) {
2821 return error;
2822 }
2823 if (!IsSuspendedForDebugger(soa, thread)) {
2824 return JDWP::ERR_THREAD_NOT_SUSPENDED;
Elliott Hughes221229c2013-01-08 18:17:50 -08002825 }
Sebastien Hertz8009f392014-09-01 17:07:11 +02002826 // Find the frame with the given frame_id.
Ian Rogers700a4022014-05-19 16:49:03 -07002827 std::unique_ptr<Context> context(Context::Create());
Sebastien Hertz8009f392014-09-01 17:07:11 +02002828 FindFrameVisitor visitor(thread, context.get(), frame_id);
Ian Rogers0399dde2012-06-06 17:09:28 -07002829 visitor.WalkStack();
Sebastien Hertz8009f392014-09-01 17:07:11 +02002830 if (visitor.GetError() != JDWP::ERR_NONE) {
2831 return visitor.GetError();
2832 }
2833
2834 // Writes the values into visitor's context.
2835 int32_t slot_count = request->ReadSigned32("slot count");
2836 for (int32_t i = 0; i < slot_count; ++i) {
2837 uint32_t slot = request->ReadUnsigned32("slot");
2838 JDWP::JdwpTag sigByte = request->ReadTag();
2839 size_t width = Dbg::GetTagWidth(sigByte);
2840 uint64_t value = request->ReadValue(width);
2841
2842 VLOG(jdwp) << " --> slot " << slot << " " << sigByte << " " << value;
Mingyao Yang99170c62015-07-06 11:10:37 -07002843 error = Dbg::SetLocalValue(thread, visitor, slot, sigByte, value, width);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002844 if (error != JDWP::ERR_NONE) {
2845 return error;
2846 }
2847 }
2848 return JDWP::ERR_NONE;
2849}
2850
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002851template<typename T>
2852static JDWP::JdwpError FailSetLocalValue(const StackVisitor& visitor, uint16_t vreg,
2853 JDWP::JdwpTag tag, T value)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002854 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002855 LOG(ERROR) << "Failed to write " << tag << " local " << value
2856 << " (0x" << std::hex << value << ") into register v" << vreg
2857 << GetStackContextAsString(visitor);
2858 return kStackFrameLocalAccessError;
2859}
2860
Mingyao Yang99170c62015-07-06 11:10:37 -07002861JDWP::JdwpError Dbg::SetLocalValue(Thread* thread, StackVisitor& visitor, int slot,
2862 JDWP::JdwpTag tag, uint64_t value, size_t width) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002863 ArtMethod* m = visitor.GetMethod();
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002864 JDWP::JdwpError error = JDWP::ERR_NONE;
2865 uint16_t vreg = DemangleSlot(slot, m, &error);
2866 if (error != JDWP::ERR_NONE) {
2867 return error;
2868 }
Sebastien Hertz8009f392014-09-01 17:07:11 +02002869 // TODO: check that the tag is compatible with the actual type of the slot!
Sebastien Hertz8009f392014-09-01 17:07:11 +02002870 switch (tag) {
2871 case JDWP::JT_BOOLEAN:
2872 case JDWP::JT_BYTE:
2873 CHECK_EQ(width, 1U);
Mingyao Yang636b9252015-07-31 16:40:24 -07002874 if (!visitor.SetVReg(m, vreg, static_cast<uint32_t>(value), kIntVReg)) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002875 return FailSetLocalValue(visitor, vreg, tag, static_cast<uint32_t>(value));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002876 }
2877 break;
2878 case JDWP::JT_SHORT:
2879 case JDWP::JT_CHAR:
2880 CHECK_EQ(width, 2U);
Mingyao Yang636b9252015-07-31 16:40:24 -07002881 if (!visitor.SetVReg(m, vreg, static_cast<uint32_t>(value), kIntVReg)) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002882 return FailSetLocalValue(visitor, vreg, tag, static_cast<uint32_t>(value));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002883 }
2884 break;
2885 case JDWP::JT_INT:
2886 CHECK_EQ(width, 4U);
Mingyao Yang636b9252015-07-31 16:40:24 -07002887 if (!visitor.SetVReg(m, vreg, static_cast<uint32_t>(value), kIntVReg)) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002888 return FailSetLocalValue(visitor, vreg, tag, static_cast<uint32_t>(value));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002889 }
2890 break;
2891 case JDWP::JT_FLOAT:
2892 CHECK_EQ(width, 4U);
Mingyao Yang636b9252015-07-31 16:40:24 -07002893 if (!visitor.SetVReg(m, vreg, static_cast<uint32_t>(value), kFloatVReg)) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002894 return FailSetLocalValue(visitor, vreg, tag, static_cast<uint32_t>(value));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002895 }
2896 break;
2897 case JDWP::JT_ARRAY:
2898 case JDWP::JT_CLASS_LOADER:
2899 case JDWP::JT_CLASS_OBJECT:
2900 case JDWP::JT_OBJECT:
2901 case JDWP::JT_STRING:
2902 case JDWP::JT_THREAD:
2903 case JDWP::JT_THREAD_GROUP: {
2904 CHECK_EQ(width, sizeof(JDWP::ObjectId));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002905 mirror::Object* o = gRegistry->Get<mirror::Object*>(static_cast<JDWP::ObjectId>(value),
2906 &error);
2907 if (error != JDWP::ERR_NONE) {
2908 VLOG(jdwp) << tag << " object " << o << " is an invalid object";
2909 return JDWP::ERR_INVALID_OBJECT;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002910 }
Mingyao Yang636b9252015-07-31 16:40:24 -07002911 if (!visitor.SetVReg(m, vreg, static_cast<uint32_t>(reinterpret_cast<uintptr_t>(o)),
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002912 kReferenceVReg)) {
2913 return FailSetLocalValue(visitor, vreg, tag, reinterpret_cast<uintptr_t>(o));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002914 }
2915 break;
2916 }
2917 case JDWP::JT_DOUBLE: {
2918 CHECK_EQ(width, 8U);
Mingyao Yang636b9252015-07-31 16:40:24 -07002919 if (!visitor.SetVRegPair(m, vreg, value, kDoubleLoVReg, kDoubleHiVReg)) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002920 return FailSetLocalValue(visitor, vreg, tag, value);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002921 }
2922 break;
2923 }
2924 case JDWP::JT_LONG: {
2925 CHECK_EQ(width, 8U);
Mingyao Yang636b9252015-07-31 16:40:24 -07002926 if (!visitor.SetVRegPair(m, vreg, value, kLongLoVReg, kLongHiVReg)) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002927 return FailSetLocalValue(visitor, vreg, tag, value);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002928 }
2929 break;
2930 }
2931 default:
2932 LOG(FATAL) << "Unknown tag " << tag;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002933 UNREACHABLE();
Sebastien Hertz8009f392014-09-01 17:07:11 +02002934 }
Mingyao Yang99170c62015-07-06 11:10:37 -07002935
2936 // If we set the local variable in a compiled frame, we need to trigger a deoptimization of
2937 // the stack so we continue execution with the interpreter using the new value(s) of the updated
2938 // local variable(s). To achieve this, we install instrumentation exit stub on each method of the
2939 // thread's stack. The stub will cause the deoptimization to happen.
2940 if (!visitor.IsShadowFrame() && thread->HasDebuggerShadowFrames()) {
2941 Runtime::Current()->GetInstrumentation()->InstrumentThreadStack(thread);
2942 }
2943
Sebastien Hertz8009f392014-09-01 17:07:11 +02002944 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002945}
2946
Mathieu Chartiere401d142015-04-22 13:56:20 -07002947static void SetEventLocation(JDWP::EventLocation* location, ArtMethod* m, uint32_t dex_pc)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002948 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz6995c602014-09-09 12:10:13 +02002949 DCHECK(location != nullptr);
2950 if (m == nullptr) {
2951 memset(location, 0, sizeof(*location));
2952 } else {
Alex Light97e78032017-06-27 17:51:55 -07002953 location->method = m->GetCanonicalMethod(kRuntimePointerSize);
Sebastien Hertz6995c602014-09-09 12:10:13 +02002954 location->dex_pc = (m->IsNative() || m->IsProxyMethod()) ? static_cast<uint32_t>(-1) : dex_pc;
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002955 }
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002956}
2957
Mathieu Chartiere401d142015-04-22 13:56:20 -07002958void Dbg::PostLocationEvent(ArtMethod* m, int dex_pc, mirror::Object* this_object,
Jeff Hao579b0242013-11-18 13:16:49 -08002959 int event_flags, const JValue* return_value) {
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002960 if (!IsDebuggerActive()) {
2961 return;
2962 }
2963 DCHECK(m != nullptr);
2964 DCHECK_EQ(m->IsStatic(), this_object == nullptr);
Sebastien Hertz6995c602014-09-09 12:10:13 +02002965 JDWP::EventLocation location;
2966 SetEventLocation(&location, m, dex_pc);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002967
Sebastien Hertzde48aa62015-05-26 11:53:39 +02002968 // We need to be sure no exception is pending when calling JdwpState::PostLocationEvent.
2969 // This is required to be able to call JNI functions to create JDWP ids. To achieve this,
2970 // we temporarily clear the current thread's exception (if any) and will restore it after
2971 // the call.
2972 // Note: the only way to get a pending exception here is to suspend on a move-exception
2973 // instruction.
2974 Thread* const self = Thread::Current();
2975 StackHandleScope<1> hs(self);
2976 Handle<mirror::Throwable> pending_exception(hs.NewHandle(self->GetException()));
2977 self->ClearException();
Andreas Gampefa4333d2017-02-14 11:10:34 -08002978 if (kIsDebugBuild && pending_exception != nullptr) {
Mathieu Chartier808c7a52017-12-15 11:19:33 -08002979 const Instruction& instr = location.method->DexInstructions().InstructionAt(location.dex_pc);
2980 CHECK_EQ(Instruction::MOVE_EXCEPTION, instr.Opcode());
Sebastien Hertzde48aa62015-05-26 11:53:39 +02002981 }
2982
Sebastien Hertz6995c602014-09-09 12:10:13 +02002983 gJdwpState->PostLocationEvent(&location, this_object, event_flags, return_value);
Sebastien Hertzde48aa62015-05-26 11:53:39 +02002984
Andreas Gampefa4333d2017-02-14 11:10:34 -08002985 if (pending_exception != nullptr) {
Sebastien Hertzde48aa62015-05-26 11:53:39 +02002986 self->SetException(pending_exception.Get());
2987 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002988}
2989
Mathieu Chartiere401d142015-04-22 13:56:20 -07002990void Dbg::PostFieldAccessEvent(ArtMethod* m, int dex_pc,
Mathieu Chartierc7853442015-03-27 14:35:38 -07002991 mirror::Object* this_object, ArtField* f) {
Alex Lighte00ec302017-06-16 08:56:43 -07002992 // TODO We should send events for native methods.
2993 if (!IsDebuggerActive() || m->IsNative()) {
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002994 return;
2995 }
2996 DCHECK(m != nullptr);
2997 DCHECK(f != nullptr);
Sebastien Hertz6995c602014-09-09 12:10:13 +02002998 JDWP::EventLocation location;
2999 SetEventLocation(&location, m, dex_pc);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02003000
Sebastien Hertz6995c602014-09-09 12:10:13 +02003001 gJdwpState->PostFieldEvent(&location, f, this_object, nullptr, false);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02003002}
3003
Mathieu Chartiere401d142015-04-22 13:56:20 -07003004void Dbg::PostFieldModificationEvent(ArtMethod* m, int dex_pc,
Mathieu Chartierc7853442015-03-27 14:35:38 -07003005 mirror::Object* this_object, ArtField* f,
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02003006 const JValue* field_value) {
Alex Lighte00ec302017-06-16 08:56:43 -07003007 // TODO We should send events for native methods.
3008 if (!IsDebuggerActive() || m->IsNative()) {
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02003009 return;
3010 }
3011 DCHECK(m != nullptr);
3012 DCHECK(f != nullptr);
3013 DCHECK(field_value != nullptr);
Sebastien Hertz6995c602014-09-09 12:10:13 +02003014 JDWP::EventLocation location;
3015 SetEventLocation(&location, m, dex_pc);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02003016
Sebastien Hertz6995c602014-09-09 12:10:13 +02003017 gJdwpState->PostFieldEvent(&location, f, this_object, field_value, true);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02003018}
3019
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003020/**
3021 * Finds the location where this exception will be caught. We search until we reach the top
3022 * frame, in which case this exception is considered uncaught.
3023 */
3024class CatchLocationFinder : public StackVisitor {
3025 public:
3026 CatchLocationFinder(Thread* self, const Handle<mirror::Throwable>& exception, Context* context)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003027 REQUIRES_SHARED(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01003028 : StackVisitor(self, context, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003029 exception_(exception),
3030 handle_scope_(self),
3031 this_at_throw_(handle_scope_.NewHandle<mirror::Object>(nullptr)),
Mathieu Chartiere401d142015-04-22 13:56:20 -07003032 catch_method_(nullptr),
3033 throw_method_(nullptr),
Andreas Gampee2abbc62017-09-15 11:59:26 -07003034 catch_dex_pc_(dex::kDexNoIndex),
3035 throw_dex_pc_(dex::kDexNoIndex) {
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003036 }
3037
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003038 bool VisitFrame() OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003039 ArtMethod* method = GetMethod();
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003040 DCHECK(method != nullptr);
3041 if (method->IsRuntimeMethod()) {
3042 // Ignore callee save method.
3043 DCHECK(method->IsCalleeSaveMethod());
3044 return true;
3045 }
3046
3047 uint32_t dex_pc = GetDexPc();
Mathieu Chartiere401d142015-04-22 13:56:20 -07003048 if (throw_method_ == nullptr) {
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003049 // First Java method found. It is either the method that threw the exception,
3050 // or the Java native method that is reporting an exception thrown by
3051 // native code.
3052 this_at_throw_.Assign(GetThisObject());
Mathieu Chartiere401d142015-04-22 13:56:20 -07003053 throw_method_ = method;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003054 throw_dex_pc_ = dex_pc;
3055 }
3056
Andreas Gampee2abbc62017-09-15 11:59:26 -07003057 if (dex_pc != dex::kDexNoIndex) {
Sebastien Hertz26f72862015-09-15 09:52:07 +02003058 StackHandleScope<1> hs(GetThread());
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003059 uint32_t found_dex_pc;
3060 Handle<mirror::Class> exception_class(hs.NewHandle(exception_->GetClass()));
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003061 bool unused_clear_exception;
Mathieu Chartiere401d142015-04-22 13:56:20 -07003062 found_dex_pc = method->FindCatchBlock(exception_class, dex_pc, &unused_clear_exception);
Andreas Gampee2abbc62017-09-15 11:59:26 -07003063 if (found_dex_pc != dex::kDexNoIndex) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003064 catch_method_ = method;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003065 catch_dex_pc_ = found_dex_pc;
3066 return false; // End stack walk.
3067 }
3068 }
3069 return true; // Continue stack walk.
3070 }
3071
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003072 ArtMethod* GetCatchMethod() REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003073 return catch_method_;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003074 }
3075
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003076 ArtMethod* GetThrowMethod() REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003077 return throw_method_;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003078 }
3079
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003080 mirror::Object* GetThisAtThrow() REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003081 return this_at_throw_.Get();
3082 }
3083
3084 uint32_t GetCatchDexPc() const {
3085 return catch_dex_pc_;
3086 }
3087
3088 uint32_t GetThrowDexPc() const {
3089 return throw_dex_pc_;
3090 }
3091
3092 private:
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003093 const Handle<mirror::Throwable>& exception_;
Mathieu Chartiere401d142015-04-22 13:56:20 -07003094 StackHandleScope<1> handle_scope_;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003095 MutableHandle<mirror::Object> this_at_throw_;
Mathieu Chartiere401d142015-04-22 13:56:20 -07003096 ArtMethod* catch_method_;
3097 ArtMethod* throw_method_;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003098 uint32_t catch_dex_pc_;
3099 uint32_t throw_dex_pc_;
3100
3101 DISALLOW_COPY_AND_ASSIGN(CatchLocationFinder);
3102};
3103
3104void Dbg::PostException(mirror::Throwable* exception_object) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07003105 if (!IsDebuggerActive()) {
Ian Rogers0ad5bb82011-12-07 10:16:32 -08003106 return;
3107 }
Sebastien Hertz261bc042015-04-08 09:36:07 +02003108 Thread* const self = Thread::Current();
3109 StackHandleScope<1> handle_scope(self);
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003110 Handle<mirror::Throwable> h_exception(handle_scope.NewHandle(exception_object));
3111 std::unique_ptr<Context> context(Context::Create());
Sebastien Hertz261bc042015-04-08 09:36:07 +02003112 CatchLocationFinder clf(self, h_exception, context.get());
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003113 clf.WalkStack(/* include_transitions */ false);
Sebastien Hertz6995c602014-09-09 12:10:13 +02003114 JDWP::EventLocation exception_throw_location;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003115 SetEventLocation(&exception_throw_location, clf.GetThrowMethod(), clf.GetThrowDexPc());
Sebastien Hertz6995c602014-09-09 12:10:13 +02003116 JDWP::EventLocation exception_catch_location;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003117 SetEventLocation(&exception_catch_location, clf.GetCatchMethod(), clf.GetCatchDexPc());
Elliott Hughes4740cdf2011-12-07 14:07:12 -08003118
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003119 gJdwpState->PostException(&exception_throw_location, h_exception.Get(), &exception_catch_location,
3120 clf.GetThisAtThrow());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003121}
3122
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003123void Dbg::PostClassPrepare(mirror::Class* c) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07003124 if (!IsDebuggerActive()) {
Elliott Hughes4740cdf2011-12-07 14:07:12 -08003125 return;
3126 }
Sebastien Hertz6995c602014-09-09 12:10:13 +02003127 gJdwpState->PostClassPrepare(c);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003128}
3129
Ian Rogers62d6c772013-02-27 08:32:07 -08003130void Dbg::UpdateDebugger(Thread* thread, mirror::Object* this_object,
Mathieu Chartiere401d142015-04-22 13:56:20 -07003131 ArtMethod* m, uint32_t dex_pc,
Sebastien Hertz8379b222014-02-24 17:38:15 +01003132 int event_flags, const JValue* return_value) {
Ian Rogers62d6c772013-02-27 08:32:07 -08003133 if (!IsDebuggerActive() || dex_pc == static_cast<uint32_t>(-2) /* fake method exit */) {
Elliott Hughes2aa2e392012-02-17 17:15:43 -08003134 return;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003135 }
3136
Elliott Hughes86964332012-02-15 19:37:42 -08003137 if (IsBreakpoint(m, dex_pc)) {
3138 event_flags |= kBreakpoint;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003139 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003140
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003141 // If the debugger is single-stepping one of our threads, check to
3142 // see if we're that thread and we've reached a step point.
3143 const SingleStepControl* single_step_control = thread->GetSingleStepControl();
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003144 if (single_step_control != nullptr) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003145 CHECK(!m->IsNative());
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003146 if (single_step_control->GetStepDepth() == JDWP::SD_INTO) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003147 // Step into method calls. We break when the line number
3148 // or method pointer changes. If we're in SS_MIN mode, we
3149 // always stop.
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003150 if (single_step_control->GetMethod() != m) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003151 event_flags |= kSingleStep;
3152 VLOG(jdwp) << "SS new method";
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003153 } else if (single_step_control->GetStepSize() == JDWP::SS_MIN) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003154 event_flags |= kSingleStep;
3155 VLOG(jdwp) << "SS new instruction";
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003156 } else if (single_step_control->ContainsDexPc(dex_pc)) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003157 event_flags |= kSingleStep;
3158 VLOG(jdwp) << "SS new line";
3159 }
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003160 } else if (single_step_control->GetStepDepth() == JDWP::SD_OVER) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003161 // Step over method calls. We break when the line number is
3162 // different and the frame depth is <= the original frame
3163 // depth. (We can't just compare on the method, because we
3164 // might get unrolled past it by an exception, and it's tricky
3165 // to identify recursion.)
3166
3167 int stack_depth = GetStackDepth(thread);
3168
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003169 if (stack_depth < single_step_control->GetStackDepth()) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003170 // Popped up one or more frames, always trigger.
3171 event_flags |= kSingleStep;
3172 VLOG(jdwp) << "SS method pop";
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003173 } else if (stack_depth == single_step_control->GetStackDepth()) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003174 // Same depth, see if we moved.
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003175 if (single_step_control->GetStepSize() == JDWP::SS_MIN) {
Elliott Hughes86964332012-02-15 19:37:42 -08003176 event_flags |= kSingleStep;
3177 VLOG(jdwp) << "SS new instruction";
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003178 } else if (single_step_control->ContainsDexPc(dex_pc)) {
Elliott Hughes2435a572012-02-17 16:07:41 -08003179 event_flags |= kSingleStep;
3180 VLOG(jdwp) << "SS new line";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003181 }
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003182 }
3183 } else {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003184 CHECK_EQ(single_step_control->GetStepDepth(), JDWP::SD_OUT);
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003185 // Return from the current method. We break when the frame
3186 // depth pops up.
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003187
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003188 // This differs from the "method exit" break in that it stops
3189 // with the PC at the next instruction in the returned-to
3190 // function, rather than the end of the returning function.
Elliott Hughes86964332012-02-15 19:37:42 -08003191
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003192 int stack_depth = GetStackDepth(thread);
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003193 if (stack_depth < single_step_control->GetStackDepth()) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003194 event_flags |= kSingleStep;
3195 VLOG(jdwp) << "SS method pop";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003196 }
3197 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003198 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003199
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003200 // If there's something interesting going on, see if it matches one
3201 // of the debugger filters.
3202 if (event_flags != 0) {
Sebastien Hertz8379b222014-02-24 17:38:15 +01003203 Dbg::PostLocationEvent(m, dex_pc, this_object, event_flags, return_value);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003204 }
3205}
3206
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003207size_t* Dbg::GetReferenceCounterForEvent(uint32_t instrumentation_event) {
3208 switch (instrumentation_event) {
3209 case instrumentation::Instrumentation::kMethodEntered:
3210 return &method_enter_event_ref_count_;
3211 case instrumentation::Instrumentation::kMethodExited:
3212 return &method_exit_event_ref_count_;
3213 case instrumentation::Instrumentation::kDexPcMoved:
3214 return &dex_pc_change_event_ref_count_;
3215 case instrumentation::Instrumentation::kFieldRead:
3216 return &field_read_event_ref_count_;
3217 case instrumentation::Instrumentation::kFieldWritten:
3218 return &field_write_event_ref_count_;
Alex Light6e1607e2017-08-23 10:06:18 -07003219 case instrumentation::Instrumentation::kExceptionThrown:
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003220 return &exception_catch_event_ref_count_;
3221 default:
3222 return nullptr;
3223 }
3224}
3225
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003226// Process request while all mutator threads are suspended.
3227void Dbg::ProcessDeoptimizationRequest(const DeoptimizationRequest& request) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003228 instrumentation::Instrumentation* instrumentation = Runtime::Current()->GetInstrumentation();
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003229 switch (request.GetKind()) {
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003230 case DeoptimizationRequest::kNothing:
3231 LOG(WARNING) << "Ignoring empty deoptimization request.";
3232 break;
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003233 case DeoptimizationRequest::kRegisterForEvent:
3234 VLOG(jdwp) << StringPrintf("Add debugger as listener for instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003235 request.InstrumentationEvent());
3236 instrumentation->AddListener(&gDebugInstrumentationListener, request.InstrumentationEvent());
3237 instrumentation_events_ |= request.InstrumentationEvent();
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003238 break;
3239 case DeoptimizationRequest::kUnregisterForEvent:
3240 VLOG(jdwp) << StringPrintf("Remove debugger as listener for instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003241 request.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003242 instrumentation->RemoveListener(&gDebugInstrumentationListener,
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003243 request.InstrumentationEvent());
3244 instrumentation_events_ &= ~request.InstrumentationEvent();
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003245 break;
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003246 case DeoptimizationRequest::kFullDeoptimization:
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003247 VLOG(jdwp) << "Deoptimize the world ...";
Sebastien Hertz0462c4c2015-04-01 16:34:17 +02003248 instrumentation->DeoptimizeEverything(kDbgInstrumentationKey);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003249 VLOG(jdwp) << "Deoptimize the world DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003250 break;
3251 case DeoptimizationRequest::kFullUndeoptimization:
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003252 VLOG(jdwp) << "Undeoptimize the world ...";
Sebastien Hertz0462c4c2015-04-01 16:34:17 +02003253 instrumentation->UndeoptimizeEverything(kDbgInstrumentationKey);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003254 VLOG(jdwp) << "Undeoptimize the world DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003255 break;
3256 case DeoptimizationRequest::kSelectiveDeoptimization:
David Sehr709b0702016-10-13 09:12:37 -07003257 VLOG(jdwp) << "Deoptimize method " << ArtMethod::PrettyMethod(request.Method()) << " ...";
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003258 instrumentation->Deoptimize(request.Method());
David Sehr709b0702016-10-13 09:12:37 -07003259 VLOG(jdwp) << "Deoptimize method " << ArtMethod::PrettyMethod(request.Method()) << " DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003260 break;
3261 case DeoptimizationRequest::kSelectiveUndeoptimization:
David Sehr709b0702016-10-13 09:12:37 -07003262 VLOG(jdwp) << "Undeoptimize method " << ArtMethod::PrettyMethod(request.Method()) << " ...";
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003263 instrumentation->Undeoptimize(request.Method());
David Sehr709b0702016-10-13 09:12:37 -07003264 VLOG(jdwp) << "Undeoptimize method " << ArtMethod::PrettyMethod(request.Method()) << " DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003265 break;
3266 default:
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003267 LOG(FATAL) << "Unsupported deoptimization request kind " << request.GetKind();
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003268 break;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003269 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003270}
3271
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003272void Dbg::RequestDeoptimization(const DeoptimizationRequest& req) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003273 if (req.GetKind() == DeoptimizationRequest::kNothing) {
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003274 // Nothing to do.
3275 return;
3276 }
Brian Carlstrom306db812014-09-05 13:01:41 -07003277 MutexLock mu(Thread::Current(), *Locks::deoptimization_lock_);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003278 RequestDeoptimizationLocked(req);
3279}
3280
3281void Dbg::RequestDeoptimizationLocked(const DeoptimizationRequest& req) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003282 switch (req.GetKind()) {
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003283 case DeoptimizationRequest::kRegisterForEvent: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003284 DCHECK_NE(req.InstrumentationEvent(), 0u);
3285 size_t* counter = GetReferenceCounterForEvent(req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003286 CHECK(counter != nullptr) << StringPrintf("No counter for instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003287 req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003288 if (*counter == 0) {
Sebastien Hertz7d2ae432014-05-15 11:26:34 +02003289 VLOG(jdwp) << StringPrintf("Queue request #%zd to start listening to instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003290 deoptimization_requests_.size(), req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003291 deoptimization_requests_.push_back(req);
3292 }
3293 *counter = *counter + 1;
3294 break;
3295 }
3296 case DeoptimizationRequest::kUnregisterForEvent: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003297 DCHECK_NE(req.InstrumentationEvent(), 0u);
3298 size_t* counter = GetReferenceCounterForEvent(req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003299 CHECK(counter != nullptr) << StringPrintf("No counter for instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003300 req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003301 *counter = *counter - 1;
3302 if (*counter == 0) {
Sebastien Hertz7d2ae432014-05-15 11:26:34 +02003303 VLOG(jdwp) << StringPrintf("Queue request #%zd to stop listening to instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003304 deoptimization_requests_.size(), req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003305 deoptimization_requests_.push_back(req);
3306 }
3307 break;
3308 }
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003309 case DeoptimizationRequest::kFullDeoptimization: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003310 DCHECK(req.Method() == nullptr);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003311 if (full_deoptimization_event_count_ == 0) {
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003312 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
3313 << " for full deoptimization";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003314 deoptimization_requests_.push_back(req);
3315 }
3316 ++full_deoptimization_event_count_;
3317 break;
3318 }
3319 case DeoptimizationRequest::kFullUndeoptimization: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003320 DCHECK(req.Method() == nullptr);
Sebastien Hertze713d932014-05-15 10:48:53 +02003321 DCHECK_GT(full_deoptimization_event_count_, 0U);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003322 --full_deoptimization_event_count_;
3323 if (full_deoptimization_event_count_ == 0) {
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003324 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
3325 << " for full undeoptimization";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003326 deoptimization_requests_.push_back(req);
3327 }
3328 break;
3329 }
3330 case DeoptimizationRequest::kSelectiveDeoptimization: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003331 DCHECK(req.Method() != nullptr);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003332 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
David Sehr709b0702016-10-13 09:12:37 -07003333 << " for deoptimization of " << req.Method()->PrettyMethod();
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003334 deoptimization_requests_.push_back(req);
3335 break;
3336 }
3337 case DeoptimizationRequest::kSelectiveUndeoptimization: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003338 DCHECK(req.Method() != nullptr);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003339 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
David Sehr709b0702016-10-13 09:12:37 -07003340 << " for undeoptimization of " << req.Method()->PrettyMethod();
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003341 deoptimization_requests_.push_back(req);
3342 break;
3343 }
3344 default: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003345 LOG(FATAL) << "Unknown deoptimization request kind " << req.GetKind();
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003346 break;
3347 }
3348 }
3349}
3350
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003351void Dbg::ManageDeoptimization() {
3352 Thread* const self = Thread::Current();
3353 {
3354 // Avoid suspend/resume if there is no pending request.
Brian Carlstrom306db812014-09-05 13:01:41 -07003355 MutexLock mu(self, *Locks::deoptimization_lock_);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003356 if (deoptimization_requests_.empty()) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003357 return;
3358 }
3359 }
3360 CHECK_EQ(self->GetState(), kRunnable);
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07003361 ScopedThreadSuspension sts(self, kWaitingForDeoptimization);
Mathieu Chartieraa516822015-10-02 15:53:37 -07003362 // Required for ProcessDeoptimizationRequest.
3363 gc::ScopedGCCriticalSection gcs(self,
3364 gc::kGcCauseInstrumentation,
3365 gc::kCollectorTypeInstrumentation);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003366 // We need to suspend mutator threads first.
Mathieu Chartier4f55e222015-09-04 13:26:21 -07003367 ScopedSuspendAll ssa(__FUNCTION__);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003368 const ThreadState old_state = self->SetStateUnsafe(kRunnable);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003369 {
Brian Carlstrom306db812014-09-05 13:01:41 -07003370 MutexLock mu(self, *Locks::deoptimization_lock_);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003371 size_t req_index = 0;
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003372 for (DeoptimizationRequest& request : deoptimization_requests_) {
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003373 VLOG(jdwp) << "Process deoptimization request #" << req_index++;
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003374 ProcessDeoptimizationRequest(request);
3375 }
3376 deoptimization_requests_.clear();
3377 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003378 CHECK_EQ(self->SetStateUnsafe(old_state), kRunnable);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003379}
3380
Mathieu Chartiere401d142015-04-22 13:56:20 -07003381static const Breakpoint* FindFirstBreakpointForMethod(ArtMethod* m)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003382 REQUIRES_SHARED(Locks::mutator_lock_, Locks::breakpoint_lock_) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003383 for (Breakpoint& breakpoint : gBreakpoints) {
Alex Light6c8467f2015-11-20 15:03:26 -08003384 if (breakpoint.IsInMethod(m)) {
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003385 return &breakpoint;
3386 }
3387 }
3388 return nullptr;
3389}
3390
Mathieu Chartiere401d142015-04-22 13:56:20 -07003391bool Dbg::MethodHasAnyBreakpoints(ArtMethod* method) {
Mathieu Chartierd8565452015-03-26 09:41:50 -07003392 ReaderMutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
3393 return FindFirstBreakpointForMethod(method) != nullptr;
3394}
3395
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003396// Sanity checks all existing breakpoints on the same method.
Mathieu Chartiere401d142015-04-22 13:56:20 -07003397static void SanityCheckExistingBreakpoints(ArtMethod* m,
Sebastien Hertzf3928792014-11-17 19:00:37 +01003398 DeoptimizationRequest::Kind deoptimization_kind)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003399 REQUIRES_SHARED(Locks::mutator_lock_, Locks::breakpoint_lock_) {
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003400 for (const Breakpoint& breakpoint : gBreakpoints) {
Alex Light6c8467f2015-11-20 15:03:26 -08003401 if (breakpoint.IsInMethod(m)) {
Sebastien Hertzf3928792014-11-17 19:00:37 +01003402 CHECK_EQ(deoptimization_kind, breakpoint.GetDeoptimizationKind());
3403 }
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003404 }
Sebastien Hertzf3928792014-11-17 19:00:37 +01003405 instrumentation::Instrumentation* instrumentation = Runtime::Current()->GetInstrumentation();
3406 if (deoptimization_kind == DeoptimizationRequest::kFullDeoptimization) {
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003407 // We should have deoptimized everything but not "selectively" deoptimized this method.
Sebastien Hertzf3928792014-11-17 19:00:37 +01003408 CHECK(instrumentation->AreAllMethodsDeoptimized());
3409 CHECK(!instrumentation->IsDeoptimized(m));
3410 } else if (deoptimization_kind == DeoptimizationRequest::kSelectiveDeoptimization) {
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003411 // We should have "selectively" deoptimized this method.
3412 // Note: while we have not deoptimized everything for this method, we may have done it for
3413 // another event.
Sebastien Hertzf3928792014-11-17 19:00:37 +01003414 CHECK(instrumentation->IsDeoptimized(m));
3415 } else {
3416 // This method does not require deoptimization.
3417 CHECK_EQ(deoptimization_kind, DeoptimizationRequest::kNothing);
3418 CHECK(!instrumentation->IsDeoptimized(m));
3419 }
3420}
3421
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003422// Returns the deoptimization kind required to set a breakpoint in a method.
3423// If a breakpoint has already been set, we also return the first breakpoint
3424// through the given 'existing_brkpt' pointer.
Sebastien Hertzf3928792014-11-17 19:00:37 +01003425static DeoptimizationRequest::Kind GetRequiredDeoptimizationKind(Thread* self,
Mathieu Chartiere401d142015-04-22 13:56:20 -07003426 ArtMethod* m,
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003427 const Breakpoint** existing_brkpt)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003428 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertzf3928792014-11-17 19:00:37 +01003429 if (!Dbg::RequiresDeoptimization()) {
3430 // We already run in interpreter-only mode so we don't need to deoptimize anything.
3431 VLOG(jdwp) << "No need for deoptimization when fully running with interpreter for method "
David Sehr709b0702016-10-13 09:12:37 -07003432 << ArtMethod::PrettyMethod(m);
Sebastien Hertzf3928792014-11-17 19:00:37 +01003433 return DeoptimizationRequest::kNothing;
3434 }
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003435 const Breakpoint* first_breakpoint;
Sebastien Hertzf3928792014-11-17 19:00:37 +01003436 {
3437 ReaderMutexLock mu(self, *Locks::breakpoint_lock_);
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003438 first_breakpoint = FindFirstBreakpointForMethod(m);
3439 *existing_brkpt = first_breakpoint;
Sebastien Hertzf3928792014-11-17 19:00:37 +01003440 }
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003441
3442 if (first_breakpoint == nullptr) {
Nicolas Geoffray6300fd72016-03-18 09:40:17 +00003443 // There is no breakpoint on this method yet: we need to deoptimize. If this method is default,
3444 // we deoptimize everything; otherwise we deoptimize only this method. We
Alex Light6c8467f2015-11-20 15:03:26 -08003445 // deoptimize with defaults because we do not know everywhere they are used. It is possible some
Nicolas Geoffray6300fd72016-03-18 09:40:17 +00003446 // of the copies could be missed.
Alex Light6c8467f2015-11-20 15:03:26 -08003447 // TODO Deoptimizing on default methods might not be necessary in all cases.
Nicolas Geoffray6300fd72016-03-18 09:40:17 +00003448 bool need_full_deoptimization = m->IsDefault();
Sebastien Hertzf3928792014-11-17 19:00:37 +01003449 if (need_full_deoptimization) {
Nicolas Geoffray6300fd72016-03-18 09:40:17 +00003450 VLOG(jdwp) << "Need full deoptimization because of copying of method "
David Sehr709b0702016-10-13 09:12:37 -07003451 << ArtMethod::PrettyMethod(m);
Sebastien Hertzf3928792014-11-17 19:00:37 +01003452 return DeoptimizationRequest::kFullDeoptimization;
3453 } else {
3454 // We don't need to deoptimize if the method has not been compiled.
Nicolas Geoffraya5891e82015-11-06 14:18:27 +00003455 const bool is_compiled = m->HasAnyCompiledCode();
Sebastien Hertzf3928792014-11-17 19:00:37 +01003456 if (is_compiled) {
David Sehr709b0702016-10-13 09:12:37 -07003457 VLOG(jdwp) << "Need selective deoptimization for compiled method "
3458 << ArtMethod::PrettyMethod(m);
Nicolas Geoffray6300fd72016-03-18 09:40:17 +00003459 return DeoptimizationRequest::kSelectiveDeoptimization;
Sebastien Hertzf3928792014-11-17 19:00:37 +01003460 } else {
3461 // Method is not compiled: we don't need to deoptimize.
David Sehr709b0702016-10-13 09:12:37 -07003462 VLOG(jdwp) << "No need for deoptimization for non-compiled method "
3463 << ArtMethod::PrettyMethod(m);
Sebastien Hertzf3928792014-11-17 19:00:37 +01003464 return DeoptimizationRequest::kNothing;
3465 }
3466 }
3467 } else {
3468 // There is at least one breakpoint for this method: we don't need to deoptimize.
3469 // Let's check that all breakpoints are configured the same way for deoptimization.
3470 VLOG(jdwp) << "Breakpoint already set: no deoptimization is required";
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003471 DeoptimizationRequest::Kind deoptimization_kind = first_breakpoint->GetDeoptimizationKind();
Sebastien Hertzf3928792014-11-17 19:00:37 +01003472 if (kIsDebugBuild) {
3473 ReaderMutexLock mu(self, *Locks::breakpoint_lock_);
3474 SanityCheckExistingBreakpoints(m, deoptimization_kind);
3475 }
3476 return DeoptimizationRequest::kNothing;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003477 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003478}
3479
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003480// Installs a breakpoint at the specified location. Also indicates through the deoptimization
3481// request if we need to deoptimize.
3482void Dbg::WatchLocation(const JDWP::JdwpLocation* location, DeoptimizationRequest* req) {
3483 Thread* const self = Thread::Current();
Mathieu Chartiere401d142015-04-22 13:56:20 -07003484 ArtMethod* m = FromMethodId(location->method_id);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003485 DCHECK(m != nullptr) << "No method for method id " << location->method_id;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003486
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003487 const Breakpoint* existing_breakpoint = nullptr;
3488 const DeoptimizationRequest::Kind deoptimization_kind =
3489 GetRequiredDeoptimizationKind(self, m, &existing_breakpoint);
Sebastien Hertzf3928792014-11-17 19:00:37 +01003490 req->SetKind(deoptimization_kind);
3491 if (deoptimization_kind == DeoptimizationRequest::kSelectiveDeoptimization) {
3492 req->SetMethod(m);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003493 } else {
Sebastien Hertzf3928792014-11-17 19:00:37 +01003494 CHECK(deoptimization_kind == DeoptimizationRequest::kNothing ||
3495 deoptimization_kind == DeoptimizationRequest::kFullDeoptimization);
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003496 req->SetMethod(nullptr);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003497 }
3498
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003499 {
3500 WriterMutexLock mu(self, *Locks::breakpoint_lock_);
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003501 // If there is at least one existing breakpoint on the same method, the new breakpoint
3502 // must have the same deoptimization kind than the existing breakpoint(s).
3503 DeoptimizationRequest::Kind breakpoint_deoptimization_kind;
3504 if (existing_breakpoint != nullptr) {
3505 breakpoint_deoptimization_kind = existing_breakpoint->GetDeoptimizationKind();
3506 } else {
3507 breakpoint_deoptimization_kind = deoptimization_kind;
3508 }
3509 gBreakpoints.push_back(Breakpoint(m, location->dex_pc, breakpoint_deoptimization_kind));
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003510 VLOG(jdwp) << "Set breakpoint #" << (gBreakpoints.size() - 1) << ": "
3511 << gBreakpoints[gBreakpoints.size() - 1];
3512 }
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003513}
3514
3515// Uninstalls a breakpoint at the specified location. Also indicates through the deoptimization
3516// request if we need to undeoptimize.
3517void Dbg::UnwatchLocation(const JDWP::JdwpLocation* location, DeoptimizationRequest* req) {
Sebastien Hertzed2be172014-08-19 15:33:43 +02003518 WriterMutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003519 ArtMethod* m = FromMethodId(location->method_id);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003520 DCHECK(m != nullptr) << "No method for method id " << location->method_id;
Sebastien Hertzf3928792014-11-17 19:00:37 +01003521 DeoptimizationRequest::Kind deoptimization_kind = DeoptimizationRequest::kNothing;
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003522 for (size_t i = 0, e = gBreakpoints.size(); i < e; ++i) {
Alex Light6c8467f2015-11-20 15:03:26 -08003523 if (gBreakpoints[i].DexPc() == location->dex_pc && gBreakpoints[i].IsInMethod(m)) {
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003524 VLOG(jdwp) << "Removed breakpoint #" << i << ": " << gBreakpoints[i];
Sebastien Hertzf3928792014-11-17 19:00:37 +01003525 deoptimization_kind = gBreakpoints[i].GetDeoptimizationKind();
3526 DCHECK_EQ(deoptimization_kind == DeoptimizationRequest::kSelectiveDeoptimization,
3527 Runtime::Current()->GetInstrumentation()->IsDeoptimized(m));
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003528 gBreakpoints.erase(gBreakpoints.begin() + i);
3529 break;
3530 }
3531 }
3532 const Breakpoint* const existing_breakpoint = FindFirstBreakpointForMethod(m);
3533 if (existing_breakpoint == nullptr) {
3534 // There is no more breakpoint on this method: we need to undeoptimize.
Sebastien Hertzf3928792014-11-17 19:00:37 +01003535 if (deoptimization_kind == DeoptimizationRequest::kFullDeoptimization) {
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003536 // This method required full deoptimization: we need to undeoptimize everything.
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003537 req->SetKind(DeoptimizationRequest::kFullUndeoptimization);
3538 req->SetMethod(nullptr);
Sebastien Hertzf3928792014-11-17 19:00:37 +01003539 } else if (deoptimization_kind == DeoptimizationRequest::kSelectiveDeoptimization) {
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003540 // This method required selective deoptimization: we need to undeoptimize only that method.
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003541 req->SetKind(DeoptimizationRequest::kSelectiveUndeoptimization);
3542 req->SetMethod(m);
Sebastien Hertzf3928792014-11-17 19:00:37 +01003543 } else {
3544 // This method had no need for deoptimization: do nothing.
3545 CHECK_EQ(deoptimization_kind, DeoptimizationRequest::kNothing);
3546 req->SetKind(DeoptimizationRequest::kNothing);
3547 req->SetMethod(nullptr);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003548 }
3549 } else {
3550 // There is at least one breakpoint for this method: we don't need to undeoptimize.
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003551 req->SetKind(DeoptimizationRequest::kNothing);
3552 req->SetMethod(nullptr);
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003553 if (kIsDebugBuild) {
Sebastien Hertzf3928792014-11-17 19:00:37 +01003554 SanityCheckExistingBreakpoints(m, deoptimization_kind);
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003555 }
Elliott Hughes86964332012-02-15 19:37:42 -08003556 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003557}
3558
Mathieu Chartiere401d142015-04-22 13:56:20 -07003559bool Dbg::IsForcedInterpreterNeededForCallingImpl(Thread* thread, ArtMethod* m) {
Daniel Mihalyieb076692014-08-22 17:33:31 +02003560 const SingleStepControl* const ssc = thread->GetSingleStepControl();
3561 if (ssc == nullptr) {
3562 // If we are not single-stepping, then we don't have to force interpreter.
3563 return false;
3564 }
3565 if (Runtime::Current()->GetInstrumentation()->InterpretOnly()) {
3566 // If we are in interpreter only mode, then we don't have to force interpreter.
3567 return false;
3568 }
3569
3570 if (!m->IsNative() && !m->IsProxyMethod()) {
3571 // If we want to step into a method, then we have to force interpreter on that call.
3572 if (ssc->GetStepDepth() == JDWP::SD_INTO) {
3573 return true;
3574 }
3575 }
3576 return false;
3577}
3578
Mathieu Chartiere401d142015-04-22 13:56:20 -07003579bool Dbg::IsForcedInterpreterNeededForResolutionImpl(Thread* thread, ArtMethod* m) {
Daniel Mihalyieb076692014-08-22 17:33:31 +02003580 instrumentation::Instrumentation* const instrumentation =
3581 Runtime::Current()->GetInstrumentation();
3582 // If we are in interpreter only mode, then we don't have to force interpreter.
3583 if (instrumentation->InterpretOnly()) {
3584 return false;
3585 }
3586 // We can only interpret pure Java method.
3587 if (m->IsNative() || m->IsProxyMethod()) {
3588 return false;
3589 }
3590 const SingleStepControl* const ssc = thread->GetSingleStepControl();
3591 if (ssc != nullptr) {
3592 // If we want to step into a method, then we have to force interpreter on that call.
3593 if (ssc->GetStepDepth() == JDWP::SD_INTO) {
3594 return true;
3595 }
3596 // If we are stepping out from a static initializer, by issuing a step
3597 // in or step over, that was implicitly invoked by calling a static method,
3598 // then we need to step into that method. Having a lower stack depth than
3599 // the one the single step control has indicates that the step originates
3600 // from the static initializer.
3601 if (ssc->GetStepDepth() != JDWP::SD_OUT &&
3602 ssc->GetStackDepth() > GetStackDepth(thread)) {
3603 return true;
3604 }
3605 }
3606 // There are cases where we have to force interpreter on deoptimized methods,
3607 // because in some cases the call will not be performed by invoking an entry
3608 // point that has been replaced by the deoptimization, but instead by directly
3609 // invoking the compiled code of the method, for example.
3610 return instrumentation->IsDeoptimized(m);
3611}
3612
Mathieu Chartiere401d142015-04-22 13:56:20 -07003613bool Dbg::IsForcedInstrumentationNeededForResolutionImpl(Thread* thread, ArtMethod* m) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07003614 // The upcall can be null and in that case we don't need to do anything.
Daniel Mihalyieb076692014-08-22 17:33:31 +02003615 if (m == nullptr) {
3616 return false;
3617 }
3618 instrumentation::Instrumentation* const instrumentation =
3619 Runtime::Current()->GetInstrumentation();
3620 // If we are in interpreter only mode, then we don't have to force interpreter.
3621 if (instrumentation->InterpretOnly()) {
3622 return false;
3623 }
3624 // We can only interpret pure Java method.
3625 if (m->IsNative() || m->IsProxyMethod()) {
3626 return false;
3627 }
3628 const SingleStepControl* const ssc = thread->GetSingleStepControl();
3629 if (ssc != nullptr) {
3630 // If we are stepping out from a static initializer, by issuing a step
3631 // out, that was implicitly invoked by calling a static method, then we
3632 // need to step into the caller of that method. Having a lower stack
3633 // depth than the one the single step control has indicates that the
3634 // step originates from the static initializer.
3635 if (ssc->GetStepDepth() == JDWP::SD_OUT &&
3636 ssc->GetStackDepth() > GetStackDepth(thread)) {
3637 return true;
3638 }
3639 }
3640 // If we are returning from a static intializer, that was implicitly
3641 // invoked by calling a static method and the caller is deoptimized,
3642 // then we have to deoptimize the stack without forcing interpreter
3643 // on the static method that was called originally. This problem can
3644 // be solved easily by forcing instrumentation on the called method,
3645 // because the instrumentation exit hook will recognise the need of
3646 // stack deoptimization by calling IsForcedInterpreterNeededForUpcall.
3647 return instrumentation->IsDeoptimized(m);
3648}
3649
Mathieu Chartiere401d142015-04-22 13:56:20 -07003650bool Dbg::IsForcedInterpreterNeededForUpcallImpl(Thread* thread, ArtMethod* m) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07003651 // The upcall can be null and in that case we don't need to do anything.
Daniel Mihalyieb076692014-08-22 17:33:31 +02003652 if (m == nullptr) {
3653 return false;
3654 }
3655 instrumentation::Instrumentation* const instrumentation =
3656 Runtime::Current()->GetInstrumentation();
3657 // If we are in interpreter only mode, then we don't have to force interpreter.
3658 if (instrumentation->InterpretOnly()) {
3659 return false;
3660 }
3661 // We can only interpret pure Java method.
3662 if (m->IsNative() || m->IsProxyMethod()) {
3663 return false;
3664 }
3665 const SingleStepControl* const ssc = thread->GetSingleStepControl();
3666 if (ssc != nullptr) {
3667 // The debugger is not interested in what is happening under the level
3668 // of the step, thus we only force interpreter when we are not below of
3669 // the step.
3670 if (ssc->GetStackDepth() >= GetStackDepth(thread)) {
3671 return true;
3672 }
3673 }
Mingyao Yang99170c62015-07-06 11:10:37 -07003674 if (thread->HasDebuggerShadowFrames()) {
3675 // We need to deoptimize the stack for the exception handling flow so that
3676 // we don't miss any deoptimization that should be done when there are
3677 // debugger shadow frames.
3678 return true;
3679 }
Daniel Mihalyieb076692014-08-22 17:33:31 +02003680 // We have to require stack deoptimization if the upcall is deoptimized.
3681 return instrumentation->IsDeoptimized(m);
3682}
3683
Mingyao Yang99170c62015-07-06 11:10:37 -07003684class NeedsDeoptimizationVisitor : public StackVisitor {
Sebastien Hertz520633b2015-09-08 17:03:36 +02003685 public:
3686 explicit NeedsDeoptimizationVisitor(Thread* self)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003687 REQUIRES_SHARED(Locks::mutator_lock_)
Sebastien Hertz520633b2015-09-08 17:03:36 +02003688 : StackVisitor(self, nullptr, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
3689 needs_deoptimization_(false) {}
3690
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003691 bool VisitFrame() OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz520633b2015-09-08 17:03:36 +02003692 // The visitor is meant to be used when handling exception from compiled code only.
David Sehr709b0702016-10-13 09:12:37 -07003693 CHECK(!IsShadowFrame()) << "We only expect to visit compiled frame: "
3694 << ArtMethod::PrettyMethod(GetMethod());
Sebastien Hertz520633b2015-09-08 17:03:36 +02003695 ArtMethod* method = GetMethod();
3696 if (method == nullptr) {
3697 // We reach an upcall and don't need to deoptimize this part of the stack (ManagedFragment)
3698 // so we can stop the visit.
3699 DCHECK(!needs_deoptimization_);
3700 return false;
3701 }
3702 if (Runtime::Current()->GetInstrumentation()->InterpretOnly()) {
3703 // We found a compiled frame in the stack but instrumentation is set to interpret
3704 // everything: we need to deoptimize.
3705 needs_deoptimization_ = true;
3706 return false;
3707 }
3708 if (Runtime::Current()->GetInstrumentation()->IsDeoptimized(method)) {
3709 // We found a deoptimized method in the stack.
3710 needs_deoptimization_ = true;
3711 return false;
3712 }
Mingyao Yang99170c62015-07-06 11:10:37 -07003713 ShadowFrame* frame = GetThread()->FindDebuggerShadowFrame(GetFrameId());
3714 if (frame != nullptr) {
3715 // The debugger allocated a ShadowFrame to update a variable in the stack: we need to
3716 // deoptimize the stack to execute (and deallocate) this frame.
3717 needs_deoptimization_ = true;
3718 return false;
3719 }
Sebastien Hertz520633b2015-09-08 17:03:36 +02003720 return true;
3721 }
3722
3723 bool NeedsDeoptimization() const {
3724 return needs_deoptimization_;
3725 }
3726
3727 private:
3728 // Do we need to deoptimize the stack?
3729 bool needs_deoptimization_;
3730
3731 DISALLOW_COPY_AND_ASSIGN(NeedsDeoptimizationVisitor);
3732};
3733
3734// Do we need to deoptimize the stack to handle an exception?
3735bool Dbg::IsForcedInterpreterNeededForExceptionImpl(Thread* thread) {
3736 const SingleStepControl* const ssc = thread->GetSingleStepControl();
3737 if (ssc != nullptr) {
3738 // We deopt to step into the catch handler.
3739 return true;
3740 }
3741 // Deoptimization is required if at least one method in the stack needs it. However we
3742 // skip frames that will be unwound (thus not executed).
3743 NeedsDeoptimizationVisitor visitor(thread);
3744 visitor.WalkStack(true); // includes upcall.
3745 return visitor.NeedsDeoptimization();
3746}
3747
Jeff Hao449db332013-04-12 18:30:52 -07003748// Scoped utility class to suspend a thread so that we may do tasks such as walk its stack. Doesn't
3749// cause suspension if the thread is the current thread.
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07003750class ScopedDebuggerThreadSuspension {
Jeff Hao449db332013-04-12 18:30:52 -07003751 public:
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07003752 ScopedDebuggerThreadSuspension(Thread* self, JDWP::ObjectId thread_id)
Mathieu Chartier90443472015-07-16 20:32:27 -07003753 REQUIRES(!Locks::thread_list_lock_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003754 REQUIRES_SHARED(Locks::mutator_lock_) :
Ian Rogersf3d874c2014-07-17 18:52:42 -07003755 thread_(nullptr),
Jeff Hao449db332013-04-12 18:30:52 -07003756 error_(JDWP::ERR_NONE),
3757 self_suspend_(false),
Ian Rogers33e95662013-05-20 20:29:14 -07003758 other_suspend_(false) {
Jeff Hao449db332013-04-12 18:30:52 -07003759 ScopedObjectAccessUnchecked soa(self);
Sebastien Hertz69206392015-04-07 15:54:25 +02003760 thread_ = DecodeThread(soa, thread_id, &error_);
Jeff Hao449db332013-04-12 18:30:52 -07003761 if (error_ == JDWP::ERR_NONE) {
3762 if (thread_ == soa.Self()) {
3763 self_suspend_ = true;
3764 } else {
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07003765 Thread* suspended_thread;
3766 {
3767 ScopedThreadSuspension sts(self, kWaitingForDebuggerSuspension);
3768 jobject thread_peer = Dbg::GetObjectRegistry()->GetJObject(thread_id);
3769 bool timed_out;
3770 ThreadList* const thread_list = Runtime::Current()->GetThreadList();
Sebastien Hertzcdd798d2017-04-18 18:28:51 +02003771 suspended_thread = thread_list->SuspendThreadByPeer(thread_peer,
3772 /* request_suspension */ true,
Alex Light46f93402017-06-29 11:59:50 -07003773 SuspendReason::kForDebugger,
Sebastien Hertzcdd798d2017-04-18 18:28:51 +02003774 &timed_out);
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07003775 }
Ian Rogersf3d874c2014-07-17 18:52:42 -07003776 if (suspended_thread == nullptr) {
Jeff Hao449db332013-04-12 18:30:52 -07003777 // Thread terminated from under us while suspending.
3778 error_ = JDWP::ERR_INVALID_THREAD;
3779 } else {
3780 CHECK_EQ(suspended_thread, thread_);
3781 other_suspend_ = true;
3782 }
3783 }
3784 }
Elliott Hughes2435a572012-02-17 16:07:41 -08003785 }
Elliott Hughes86964332012-02-15 19:37:42 -08003786
Jeff Hao449db332013-04-12 18:30:52 -07003787 Thread* GetThread() const {
3788 return thread_;
3789 }
3790
3791 JDWP::JdwpError GetError() const {
3792 return error_;
3793 }
3794
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07003795 ~ScopedDebuggerThreadSuspension() {
Jeff Hao449db332013-04-12 18:30:52 -07003796 if (other_suspend_) {
Alex Light88fd7202017-06-30 08:31:59 -07003797 bool resumed = Runtime::Current()->GetThreadList()->Resume(thread_,
3798 SuspendReason::kForDebugger);
3799 DCHECK(resumed);
Jeff Hao449db332013-04-12 18:30:52 -07003800 }
3801 }
3802
3803 private:
3804 Thread* thread_;
3805 JDWP::JdwpError error_;
3806 bool self_suspend_;
3807 bool other_suspend_;
3808};
3809
3810JDWP::JdwpError Dbg::ConfigureStep(JDWP::ObjectId thread_id, JDWP::JdwpStepSize step_size,
3811 JDWP::JdwpStepDepth step_depth) {
3812 Thread* self = Thread::Current();
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07003813 ScopedDebuggerThreadSuspension sts(self, thread_id);
Jeff Hao449db332013-04-12 18:30:52 -07003814 if (sts.GetError() != JDWP::ERR_NONE) {
3815 return sts.GetError();
3816 }
3817
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003818 // Work out what ArtMethod* we're in, the current line number, and how deep the stack currently
Elliott Hughes2435a572012-02-17 16:07:41 -08003819 // is for step-out.
Ian Rogers0399dde2012-06-06 17:09:28 -07003820 struct SingleStepStackVisitor : public StackVisitor {
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003821 explicit SingleStepStackVisitor(Thread* thread) REQUIRES_SHARED(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01003822 : StackVisitor(thread, nullptr, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
3823 stack_depth(0),
3824 method(nullptr),
3825 line_number(-1) {}
Ian Rogersca190662012-06-26 15:45:57 -07003826
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003827 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
3828 // annotalysis.
3829 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003830 ArtMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07003831 if (!m->IsRuntimeMethod()) {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003832 ++stack_depth;
3833 if (method == nullptr) {
Alex Light73376312017-04-06 10:10:51 -07003834 const DexFile* dex_file = m->GetDexFile();
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003835 method = m;
Alex Light73376312017-04-06 10:10:51 -07003836 if (dex_file != nullptr) {
David Sehr9323e6e2016-09-13 08:58:35 -07003837 line_number = annotations::GetLineNumFromPC(dex_file, m, GetDexPc());
Elliott Hughes2435a572012-02-17 16:07:41 -08003838 }
Elliott Hughes86964332012-02-15 19:37:42 -08003839 }
3840 }
Elliott Hughes530fa002012-03-12 11:44:49 -07003841 return true;
Elliott Hughes86964332012-02-15 19:37:42 -08003842 }
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003843
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003844 int stack_depth;
Mathieu Chartiere401d142015-04-22 13:56:20 -07003845 ArtMethod* method;
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003846 int32_t line_number;
Elliott Hughes86964332012-02-15 19:37:42 -08003847 };
Jeff Hao449db332013-04-12 18:30:52 -07003848
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003849 Thread* const thread = sts.GetThread();
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003850 SingleStepStackVisitor visitor(thread);
Ian Rogers0399dde2012-06-06 17:09:28 -07003851 visitor.WalkStack();
Elliott Hughes86964332012-02-15 19:37:42 -08003852
Elliott Hughes2435a572012-02-17 16:07:41 -08003853 // Find the dex_pc values that correspond to the current line, for line-based single-stepping.
Elliott Hughes2435a572012-02-17 16:07:41 -08003854 struct DebugCallbackContext {
Roland Levillain3887c462015-08-12 18:15:42 +01003855 DebugCallbackContext(SingleStepControl* single_step_control_cb,
Mathieu Chartier31f4c9f2017-12-08 15:46:11 -08003856 int32_t line_number_cb, uint32_t num_insns_in_code_units)
Roland Levillain3887c462015-08-12 18:15:42 +01003857 : single_step_control_(single_step_control_cb), line_number_(line_number_cb),
Mathieu Chartier31f4c9f2017-12-08 15:46:11 -08003858 num_insns_in_code_units_(num_insns_in_code_units), last_pc_valid(false), last_pc(0) {
Elliott Hughes2435a572012-02-17 16:07:41 -08003859 }
3860
David Srbeckyb06e28e2015-12-10 13:15:00 +00003861 static bool Callback(void* raw_context, const DexFile::PositionInfo& entry) {
Elliott Hughes2435a572012-02-17 16:07:41 -08003862 DebugCallbackContext* context = reinterpret_cast<DebugCallbackContext*>(raw_context);
David Srbeckyb06e28e2015-12-10 13:15:00 +00003863 if (static_cast<int32_t>(entry.line_) == context->line_number_) {
Elliott Hughes2435a572012-02-17 16:07:41 -08003864 if (!context->last_pc_valid) {
3865 // Everything from this address until the next line change is ours.
David Srbeckyb06e28e2015-12-10 13:15:00 +00003866 context->last_pc = entry.address_;
Elliott Hughes2435a572012-02-17 16:07:41 -08003867 context->last_pc_valid = true;
3868 }
3869 // Otherwise, if we're already in a valid range for this line,
3870 // just keep going (shouldn't really happen)...
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003871 } else if (context->last_pc_valid) { // and the line number is new
Elliott Hughes2435a572012-02-17 16:07:41 -08003872 // Add everything from the last entry up until here to the set
David Srbeckyb06e28e2015-12-10 13:15:00 +00003873 for (uint32_t dex_pc = context->last_pc; dex_pc < entry.address_; ++dex_pc) {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003874 context->single_step_control_->AddDexPc(dex_pc);
Elliott Hughes2435a572012-02-17 16:07:41 -08003875 }
3876 context->last_pc_valid = false;
3877 }
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003878 return false; // There may be multiple entries for any given line.
Elliott Hughes2435a572012-02-17 16:07:41 -08003879 }
3880
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003881 ~DebugCallbackContext() {
Elliott Hughes2435a572012-02-17 16:07:41 -08003882 // If the line number was the last in the position table...
3883 if (last_pc_valid) {
Mathieu Chartier31f4c9f2017-12-08 15:46:11 -08003884 for (uint32_t dex_pc = last_pc; dex_pc < num_insns_in_code_units_; ++dex_pc) {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003885 single_step_control_->AddDexPc(dex_pc);
Elliott Hughes2435a572012-02-17 16:07:41 -08003886 }
3887 }
3888 }
3889
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003890 SingleStepControl* const single_step_control_;
3891 const int32_t line_number_;
Mathieu Chartier31f4c9f2017-12-08 15:46:11 -08003892 const uint32_t num_insns_in_code_units_;
Elliott Hughes2435a572012-02-17 16:07:41 -08003893 bool last_pc_valid;
3894 uint32_t last_pc;
3895 };
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003896
3897 // Allocate single step.
Sebastien Hertz1558b572015-02-25 15:05:59 +01003898 SingleStepControl* single_step_control =
3899 new (std::nothrow) SingleStepControl(step_size, step_depth,
3900 visitor.stack_depth, visitor.method);
3901 if (single_step_control == nullptr) {
3902 LOG(ERROR) << "Failed to allocate SingleStepControl";
3903 return JDWP::ERR_OUT_OF_MEMORY;
3904 }
3905
Mathieu Chartiere401d142015-04-22 13:56:20 -07003906 ArtMethod* m = single_step_control->GetMethod();
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003907 const int32_t line_number = visitor.line_number;
Sebastien Hertz52f5f932015-05-28 11:00:57 +02003908 // Note: if the thread is not running Java code (pure native thread), there is no "current"
3909 // method on the stack (and no line number either).
3910 if (m != nullptr && !m->IsNative()) {
Mathieu Chartier31f4c9f2017-12-08 15:46:11 -08003911 CodeItemDebugInfoAccessor accessor(m);
3912 DebugCallbackContext context(single_step_control, line_number, accessor.InsnsSizeInCodeUnits());
3913 m->GetDexFile()->DecodeDebugPositionInfo(accessor.DebugInfoOffset(),
3914 DebugCallbackContext::Callback,
3915 &context);
Elliott Hughes3e2e1a22012-02-21 11:33:41 -08003916 }
Elliott Hughes2435a572012-02-17 16:07:41 -08003917
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003918 // Activate single-step in the thread.
3919 thread->ActivateSingleStepControl(single_step_control);
Elliott Hughes86964332012-02-15 19:37:42 -08003920
Elliott Hughes2435a572012-02-17 16:07:41 -08003921 if (VLOG_IS_ON(jdwp)) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003922 VLOG(jdwp) << "Single-step thread: " << *thread;
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003923 VLOG(jdwp) << "Single-step step size: " << single_step_control->GetStepSize();
3924 VLOG(jdwp) << "Single-step step depth: " << single_step_control->GetStepDepth();
David Sehr709b0702016-10-13 09:12:37 -07003925 VLOG(jdwp) << "Single-step current method: "
3926 << ArtMethod::PrettyMethod(single_step_control->GetMethod());
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003927 VLOG(jdwp) << "Single-step current line: " << line_number;
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003928 VLOG(jdwp) << "Single-step current stack depth: " << single_step_control->GetStackDepth();
Elliott Hughes2435a572012-02-17 16:07:41 -08003929 VLOG(jdwp) << "Single-step dex_pc values:";
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003930 for (uint32_t dex_pc : single_step_control->GetDexPcs()) {
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003931 VLOG(jdwp) << StringPrintf(" %#x", dex_pc);
Elliott Hughes2435a572012-02-17 16:07:41 -08003932 }
3933 }
3934
3935 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003936}
3937
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003938void Dbg::UnconfigureStep(JDWP::ObjectId thread_id) {
3939 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07003940 JDWP::JdwpError error;
3941 Thread* thread = DecodeThread(soa, thread_id, &error);
Sebastien Hertz87118ed2013-11-26 17:57:18 +01003942 if (error == JDWP::ERR_NONE) {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003943 thread->DeactivateSingleStepControl();
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003944 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003945}
3946
Elliott Hughes45651fd2012-02-21 15:48:20 -08003947static char JdwpTagToShortyChar(JDWP::JdwpTag tag) {
3948 switch (tag) {
3949 default:
3950 LOG(FATAL) << "unknown JDWP tag: " << PrintableChar(tag);
Ian Rogersfc787ec2014-10-09 21:56:44 -07003951 UNREACHABLE();
Elliott Hughes45651fd2012-02-21 15:48:20 -08003952
3953 // Primitives.
3954 case JDWP::JT_BYTE: return 'B';
3955 case JDWP::JT_CHAR: return 'C';
3956 case JDWP::JT_FLOAT: return 'F';
3957 case JDWP::JT_DOUBLE: return 'D';
3958 case JDWP::JT_INT: return 'I';
3959 case JDWP::JT_LONG: return 'J';
3960 case JDWP::JT_SHORT: return 'S';
3961 case JDWP::JT_VOID: return 'V';
3962 case JDWP::JT_BOOLEAN: return 'Z';
3963
3964 // Reference types.
3965 case JDWP::JT_ARRAY:
3966 case JDWP::JT_OBJECT:
3967 case JDWP::JT_STRING:
3968 case JDWP::JT_THREAD:
3969 case JDWP::JT_THREAD_GROUP:
3970 case JDWP::JT_CLASS_LOADER:
3971 case JDWP::JT_CLASS_OBJECT:
3972 return 'L';
3973 }
3974}
3975
Sebastien Hertzcbc50642015-06-01 17:33:12 +02003976JDWP::JdwpError Dbg::PrepareInvokeMethod(uint32_t request_id, JDWP::ObjectId thread_id,
3977 JDWP::ObjectId object_id, JDWP::RefTypeId class_id,
3978 JDWP::MethodId method_id, uint32_t arg_count,
3979 uint64_t arg_values[], JDWP::JdwpTag* arg_types,
3980 uint32_t options) {
3981 Thread* const self = Thread::Current();
3982 CHECK_EQ(self, GetDebugThread()) << "This must be called by the JDWP thread";
Sebastien Hertzd4032e42015-06-12 15:47:34 +02003983 const bool resume_all_threads = ((options & JDWP::INVOKE_SINGLE_THREADED) == 0);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003984
Sebastien Hertzcbc50642015-06-01 17:33:12 +02003985 ThreadList* thread_list = Runtime::Current()->GetThreadList();
Ian Rogersc0542af2014-09-03 16:16:56 -07003986 Thread* targetThread = nullptr;
Elliott Hughesd07986f2011-12-06 18:27:45 -08003987 {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003988 ScopedObjectAccessUnchecked soa(self);
Ian Rogersc0542af2014-09-03 16:16:56 -07003989 JDWP::JdwpError error;
3990 targetThread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08003991 if (error != JDWP::ERR_NONE) {
3992 LOG(ERROR) << "InvokeMethod request for invalid thread id " << thread_id;
3993 return error;
Elliott Hughesd07986f2011-12-06 18:27:45 -08003994 }
Sebastien Hertz1558b572015-02-25 15:05:59 +01003995 if (targetThread->GetInvokeReq() != nullptr) {
3996 // Thread is already invoking a method on behalf of the debugger.
3997 LOG(ERROR) << "InvokeMethod request for thread already invoking a method: " << *targetThread;
3998 return JDWP::ERR_ALREADY_INVOKING;
3999 }
4000 if (!targetThread->IsReadyForDebugInvoke()) {
4001 // Thread is not suspended by an event so it cannot invoke a method.
Elliott Hughesd07986f2011-12-06 18:27:45 -08004002 LOG(ERROR) << "InvokeMethod request for thread not stopped by event: " << *targetThread;
4003 return JDWP::ERR_INVALID_THREAD;
4004 }
4005
4006 /*
Sebastien Hertzd4032e42015-06-12 15:47:34 +02004007 * According to the JDWP specs, we are expected to resume all threads (or only the
4008 * target thread) once. So if a thread has been suspended more than once (either by
4009 * the debugger for an event or by the runtime for GC), it will remain suspended before
4010 * the invoke is executed. This means the debugger is responsible to properly resume all
4011 * the threads it has suspended so the target thread can execute the method.
Elliott Hughesd07986f2011-12-06 18:27:45 -08004012 *
Sebastien Hertzd4032e42015-06-12 15:47:34 +02004013 * However, for compatibility reason with older versions of debuggers (like Eclipse), we
4014 * fully resume all threads (by canceling *all* debugger suspensions) when the debugger
4015 * wants us to resume all threads. This is to avoid ending up in deadlock situation.
4016 *
4017 * On the other hand, if we are asked to only resume the target thread, then we follow the
4018 * JDWP specs by resuming that thread only once. This means the thread will remain suspended
4019 * if it has been suspended more than once before the invoke (and again, this is the
4020 * responsibility of the debugger to properly resume that thread before invoking a method).
Elliott Hughesd07986f2011-12-06 18:27:45 -08004021 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004022 int suspend_count;
4023 {
Ian Rogers50b35e22012-10-04 10:09:15 -07004024 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004025 suspend_count = targetThread->GetSuspendCount();
4026 }
Sebastien Hertzd4032e42015-06-12 15:47:34 +02004027 if (suspend_count > 1 && resume_all_threads) {
4028 // The target thread will remain suspended even after we resume it. Let's emit a warning
4029 // to indicate the invoke won't be executed until the thread is resumed.
4030 LOG(WARNING) << *targetThread << " suspended more than once (suspend count == "
4031 << suspend_count << "). This thread will invoke the method only once "
4032 << "it is fully resumed.";
Elliott Hughesd07986f2011-12-06 18:27:45 -08004033 }
4034
Ian Rogersc0542af2014-09-03 16:16:56 -07004035 mirror::Object* receiver = gRegistry->Get<mirror::Object*>(object_id, &error);
4036 if (error != JDWP::ERR_NONE) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08004037 return JDWP::ERR_INVALID_OBJECT;
4038 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08004039
Sebastien Hertz1558b572015-02-25 15:05:59 +01004040 gRegistry->Get<mirror::Object*>(thread_id, &error);
Ian Rogersc0542af2014-09-03 16:16:56 -07004041 if (error != JDWP::ERR_NONE) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08004042 return JDWP::ERR_INVALID_OBJECT;
4043 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08004044
Ian Rogersc0542af2014-09-03 16:16:56 -07004045 mirror::Class* c = DecodeClass(class_id, &error);
4046 if (c == nullptr) {
4047 return error;
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08004048 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08004049
Mathieu Chartiere401d142015-04-22 13:56:20 -07004050 ArtMethod* m = FromMethodId(method_id);
Ian Rogersc0542af2014-09-03 16:16:56 -07004051 if (m->IsStatic() != (receiver == nullptr)) {
Elliott Hughes45651fd2012-02-21 15:48:20 -08004052 return JDWP::ERR_INVALID_METHODID;
4053 }
4054 if (m->IsStatic()) {
4055 if (m->GetDeclaringClass() != c) {
4056 return JDWP::ERR_INVALID_METHODID;
4057 }
4058 } else {
4059 if (!m->GetDeclaringClass()->IsAssignableFrom(c)) {
4060 return JDWP::ERR_INVALID_METHODID;
4061 }
4062 }
4063
4064 // Check the argument list matches the method.
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004065 uint32_t shorty_len = 0;
4066 const char* shorty = m->GetShorty(&shorty_len);
4067 if (shorty_len - 1 != arg_count) {
Elliott Hughes45651fd2012-02-21 15:48:20 -08004068 return JDWP::ERR_ILLEGAL_ARGUMENT;
4069 }
Elliott Hughes09201632013-04-15 15:50:07 -07004070
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004071 {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004072 StackHandleScope<2> hs(soa.Self());
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004073 HandleWrapper<mirror::Object> h_obj(hs.NewHandleWrapper(&receiver));
4074 HandleWrapper<mirror::Class> h_klass(hs.NewHandleWrapper(&c));
4075 const DexFile::TypeList* types = m->GetParameterTypeList();
4076 for (size_t i = 0; i < arg_count; ++i) {
4077 if (shorty[i + 1] != JdwpTagToShortyChar(arg_types[i])) {
Elliott Hughes09201632013-04-15 15:50:07 -07004078 return JDWP::ERR_ILLEGAL_ARGUMENT;
4079 }
4080
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004081 if (shorty[i + 1] == 'L') {
4082 // Did we really get an argument of an appropriate reference type?
Vladimir Markob45528c2017-07-27 14:14:28 +01004083 ObjPtr<mirror::Class> parameter_type =
4084 m->ResolveClassFromTypeIndex(types->GetTypeItem(i).type_idx_);
Ian Rogersc0542af2014-09-03 16:16:56 -07004085 mirror::Object* argument = gRegistry->Get<mirror::Object*>(arg_values[i], &error);
4086 if (error != JDWP::ERR_NONE) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004087 return JDWP::ERR_INVALID_OBJECT;
4088 }
Ian Rogersc0542af2014-09-03 16:16:56 -07004089 if (argument != nullptr && !argument->InstanceOf(parameter_type)) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004090 return JDWP::ERR_ILLEGAL_ARGUMENT;
4091 }
4092
4093 // Turn the on-the-wire ObjectId into a jobject.
4094 jvalue& v = reinterpret_cast<jvalue&>(arg_values[i]);
4095 v.l = gRegistry->GetJObject(arg_values[i]);
4096 }
Elliott Hughes09201632013-04-15 15:50:07 -07004097 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08004098 }
4099
Sebastien Hertz1558b572015-02-25 15:05:59 +01004100 // Allocates a DebugInvokeReq.
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004101 DebugInvokeReq* req = new (std::nothrow) DebugInvokeReq(request_id, thread_id, receiver, c, m,
4102 options, arg_values, arg_count);
4103 if (req == nullptr) {
Sebastien Hertz1558b572015-02-25 15:05:59 +01004104 LOG(ERROR) << "Failed to allocate DebugInvokeReq";
4105 return JDWP::ERR_OUT_OF_MEMORY;
4106 }
4107
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004108 // Attaches the DebugInvokeReq to the target thread so it executes the method when
4109 // it is resumed. Once the invocation completes, the target thread will delete it before
4110 // suspending itself (see ThreadList::SuspendSelfForDebugger).
4111 targetThread->SetDebugInvokeReq(req);
Elliott Hughesd07986f2011-12-06 18:27:45 -08004112 }
4113
4114 // 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 +02004115 // away we're sitting high and dry -- but we must release this before the UndoDebuggerSuspensions
4116 // call.
Sebastien Hertzd4032e42015-06-12 15:47:34 +02004117 if (resume_all_threads) {
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004118 VLOG(jdwp) << " Resuming all threads";
4119 thread_list->UndoDebuggerSuspensions();
4120 } else {
4121 VLOG(jdwp) << " Resuming event thread only";
Alex Light88fd7202017-06-30 08:31:59 -07004122 bool resumed = thread_list->Resume(targetThread, SuspendReason::kForDebugger);
4123 DCHECK(resumed);
Elliott Hughesd07986f2011-12-06 18:27:45 -08004124 }
4125
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004126 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004127}
4128
4129void Dbg::ExecuteMethod(DebugInvokeReq* pReq) {
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004130 Thread* const self = Thread::Current();
4131 CHECK_NE(self, GetDebugThread()) << "This must be called by the event thread";
4132
4133 ScopedObjectAccess soa(self);
Elliott Hughesd07986f2011-12-06 18:27:45 -08004134
Elliott Hughes81ff3182012-03-23 20:35:56 -07004135 // We can be called while an exception is pending. We need
Elliott Hughesd07986f2011-12-06 18:27:45 -08004136 // to preserve that across the method invocation.
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004137 StackHandleScope<1> hs(soa.Self());
4138 Handle<mirror::Throwable> old_exception = hs.NewHandle(soa.Self()->GetException());
Sebastien Hertz1558b572015-02-25 15:05:59 +01004139 soa.Self()->ClearException();
Elliott Hughesd07986f2011-12-06 18:27:45 -08004140
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004141 // Execute the method then sends reply to the debugger.
4142 ExecuteMethodWithoutPendingException(soa, pReq);
4143
4144 // If an exception was pending before the invoke, restore it now.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004145 if (old_exception != nullptr) {
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004146 soa.Self()->SetException(old_exception.Get());
4147 }
4148}
4149
4150// Helper function: write a variable-width value into the output input buffer.
4151static void WriteValue(JDWP::ExpandBuf* pReply, int width, uint64_t value) {
4152 switch (width) {
4153 case 1:
4154 expandBufAdd1(pReply, value);
4155 break;
4156 case 2:
4157 expandBufAdd2BE(pReply, value);
4158 break;
4159 case 4:
4160 expandBufAdd4BE(pReply, value);
4161 break;
4162 case 8:
4163 expandBufAdd8BE(pReply, value);
4164 break;
4165 default:
4166 LOG(FATAL) << width;
4167 UNREACHABLE();
4168 }
4169}
4170
4171void Dbg::ExecuteMethodWithoutPendingException(ScopedObjectAccess& soa, DebugInvokeReq* pReq) {
4172 soa.Self()->AssertNoPendingException();
4173
Elliott Hughesd07986f2011-12-06 18:27:45 -08004174 // Translate the method through the vtable, unless the debugger wants to suppress it.
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004175 ArtMethod* m = pReq->method;
Andreas Gampe542451c2016-07-26 09:02:02 -07004176 PointerSize image_pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
Sebastien Hertz1558b572015-02-25 15:05:59 +01004177 if ((pReq->options & JDWP::INVOKE_NONVIRTUAL) == 0 && pReq->receiver.Read() != nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004178 ArtMethod* actual_method =
4179 pReq->klass.Read()->FindVirtualMethodForVirtualOrInterface(m, image_pointer_size);
4180 if (actual_method != m) {
David Sehr709b0702016-10-13 09:12:37 -07004181 VLOG(jdwp) << "ExecuteMethod translated " << ArtMethod::PrettyMethod(m)
4182 << " to " << ArtMethod::PrettyMethod(actual_method);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004183 m = actual_method;
Elliott Hughes45651fd2012-02-21 15:48:20 -08004184 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08004185 }
David Sehr709b0702016-10-13 09:12:37 -07004186 VLOG(jdwp) << "ExecuteMethod " << ArtMethod::PrettyMethod(m)
Sebastien Hertz1558b572015-02-25 15:05:59 +01004187 << " receiver=" << pReq->receiver.Read()
Sebastien Hertzd38667a2013-11-25 15:43:54 +01004188 << " arg_count=" << pReq->arg_count;
Mathieu Chartiere401d142015-04-22 13:56:20 -07004189 CHECK(m != nullptr);
Elliott Hughesd07986f2011-12-06 18:27:45 -08004190
Roland Levillain33d69032015-06-18 18:20:59 +01004191 static_assert(sizeof(jvalue) == sizeof(uint64_t), "jvalue and uint64_t have different sizes.");
Elliott Hughesd07986f2011-12-06 18:27:45 -08004192
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004193 // Invoke the method.
Jeff Hao39b6c242015-05-19 20:30:23 -07004194 ScopedLocalRef<jobject> ref(soa.Env(), soa.AddLocalReference<jobject>(pReq->receiver.Read()));
Andreas Gampe13b27842016-11-07 16:48:23 -08004195 JValue result = InvokeWithJValues(soa, ref.get(), jni::EncodeArtMethod(m),
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004196 reinterpret_cast<jvalue*>(pReq->arg_values.get()));
Elliott Hughesd07986f2011-12-06 18:27:45 -08004197
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004198 // Prepare JDWP ids for the reply.
4199 JDWP::JdwpTag result_tag = BasicTagFromDescriptor(m->GetShorty());
4200 const bool is_object_result = (result_tag == JDWP::JT_OBJECT);
Jeff Hao064d24e2016-08-25 03:52:40 +00004201 StackHandleScope<3> hs(soa.Self());
Sebastien Hertz1558b572015-02-25 15:05:59 +01004202 Handle<mirror::Object> object_result = hs.NewHandle(is_object_result ? result.GetL() : nullptr);
4203 Handle<mirror::Throwable> exception = hs.NewHandle(soa.Self()->GetException());
4204 soa.Self()->ClearException();
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004205
4206 if (!IsDebuggerActive()) {
4207 // The debugger detached: we must not re-suspend threads. We also don't need to fill the reply
4208 // because it won't be sent either.
4209 return;
4210 }
4211
4212 JDWP::ObjectId exceptionObjectId = gRegistry->Add(exception);
4213 uint64_t result_value = 0;
4214 if (exceptionObjectId != 0) {
Sebastien Hertz1558b572015-02-25 15:05:59 +01004215 VLOG(jdwp) << " JDWP invocation returning with exception=" << exception.Get()
4216 << " " << exception->Dump();
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004217 result_value = 0;
Sebastien Hertz1558b572015-02-25 15:05:59 +01004218 } else if (is_object_result) {
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004219 /* if no exception was thrown, examine object result more closely */
Sebastien Hertz1558b572015-02-25 15:05:59 +01004220 JDWP::JdwpTag new_tag = TagFromObject(soa, object_result.Get());
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004221 if (new_tag != result_tag) {
4222 VLOG(jdwp) << " JDWP promoted result from " << result_tag << " to " << new_tag;
4223 result_tag = new_tag;
Elliott Hughesd07986f2011-12-06 18:27:45 -08004224 }
4225
Sebastien Hertz1558b572015-02-25 15:05:59 +01004226 // Register the object in the registry and reference its ObjectId. This ensures
4227 // GC safety and prevents from accessing stale reference if the object is moved.
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004228 result_value = gRegistry->Add(object_result.Get());
Sebastien Hertz1558b572015-02-25 15:05:59 +01004229 } else {
4230 // Primitive result.
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004231 DCHECK(IsPrimitiveTag(result_tag));
4232 result_value = result.GetJ();
4233 }
4234 const bool is_constructor = m->IsConstructor() && !m->IsStatic();
4235 if (is_constructor) {
4236 // If we invoked a constructor (which actually returns void), return the receiver,
4237 // unless we threw, in which case we return null.
Sebastien Hertza3e13772015-11-05 12:09:44 +01004238 DCHECK_EQ(JDWP::JT_VOID, result_tag);
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004239 if (exceptionObjectId == 0) {
Jeff Hao064d24e2016-08-25 03:52:40 +00004240 if (m->GetDeclaringClass()->IsStringClass()) {
4241 // For string constructors, the new string is remapped to the receiver (stored in ref).
4242 Handle<mirror::Object> decoded_ref = hs.NewHandle(soa.Self()->DecodeJObject(ref.get()));
4243 result_value = gRegistry->Add(decoded_ref);
4244 result_tag = TagFromObject(soa, decoded_ref.Get());
4245 } else {
4246 // TODO we could keep the receiver ObjectId in the DebugInvokeReq to avoid looking into the
4247 // object registry.
4248 result_value = GetObjectRegistry()->Add(pReq->receiver.Read());
4249 result_tag = TagFromObject(soa, pReq->receiver.Read());
4250 }
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004251 } else {
4252 result_value = 0;
Sebastien Hertza3e13772015-11-05 12:09:44 +01004253 result_tag = JDWP::JT_OBJECT;
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004254 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08004255 }
4256
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004257 // Suspend other threads if the invoke is not single-threaded.
4258 if ((pReq->options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07004259 ScopedThreadSuspension sts(soa.Self(), kWaitingForDebuggerSuspension);
Hiroshi Yamauchi8f95cf32016-04-19 11:14:06 -07004260 // Avoid a deadlock between GC and debugger where GC gets suspended during GC. b/25800335.
4261 gc::ScopedGCCriticalSection gcs(soa.Self(), gc::kGcCauseDebugger, gc::kCollectorTypeDebugger);
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004262 VLOG(jdwp) << " Suspending all threads";
4263 Runtime::Current()->GetThreadList()->SuspendAllForDebugger();
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004264 }
4265
4266 VLOG(jdwp) << " --> returned " << result_tag
4267 << StringPrintf(" %#" PRIx64 " (except=%#" PRIx64 ")", result_value,
4268 exceptionObjectId);
4269
4270 // Show detailed debug output.
4271 if (result_tag == JDWP::JT_STRING && exceptionObjectId == 0) {
4272 if (result_value != 0) {
4273 if (VLOG_IS_ON(jdwp)) {
4274 std::string result_string;
4275 JDWP::JdwpError error = Dbg::StringToUtf8(result_value, &result_string);
4276 CHECK_EQ(error, JDWP::ERR_NONE);
4277 VLOG(jdwp) << " string '" << result_string << "'";
4278 }
4279 } else {
4280 VLOG(jdwp) << " string (null)";
4281 }
4282 }
4283
4284 // Attach the reply to DebugInvokeReq so it can be sent to the debugger when the event thread
4285 // is ready to suspend.
4286 BuildInvokeReply(pReq->reply, pReq->request_id, result_tag, result_value, exceptionObjectId);
4287}
4288
4289void Dbg::BuildInvokeReply(JDWP::ExpandBuf* pReply, uint32_t request_id, JDWP::JdwpTag result_tag,
4290 uint64_t result_value, JDWP::ObjectId exception) {
4291 // Make room for the JDWP header since we do not know the size of the reply yet.
4292 JDWP::expandBufAddSpace(pReply, kJDWPHeaderLen);
4293
4294 size_t width = GetTagWidth(result_tag);
4295 JDWP::expandBufAdd1(pReply, result_tag);
4296 if (width != 0) {
4297 WriteValue(pReply, width, result_value);
4298 }
4299 JDWP::expandBufAdd1(pReply, JDWP::JT_OBJECT);
4300 JDWP::expandBufAddObjectId(pReply, exception);
4301
4302 // Now we know the size, we can complete the JDWP header.
4303 uint8_t* buf = expandBufGetBuffer(pReply);
4304 JDWP::Set4BE(buf + kJDWPHeaderSizeOffset, expandBufGetLength(pReply));
4305 JDWP::Set4BE(buf + kJDWPHeaderIdOffset, request_id);
4306 JDWP::Set1(buf + kJDWPHeaderFlagsOffset, kJDWPFlagReply); // flags
4307 JDWP::Set2BE(buf + kJDWPHeaderErrorCodeOffset, JDWP::ERR_NONE);
4308}
4309
4310void Dbg::FinishInvokeMethod(DebugInvokeReq* pReq) {
4311 CHECK_NE(Thread::Current(), GetDebugThread()) << "This must be called by the event thread";
4312
4313 JDWP::ExpandBuf* const pReply = pReq->reply;
4314 CHECK(pReply != nullptr) << "No reply attached to DebugInvokeReq";
4315
4316 // We need to prevent other threads (including JDWP thread) from interacting with the debugger
4317 // while we send the reply but are not yet suspended. The JDWP token will be released just before
4318 // we suspend ourself again (see ThreadList::SuspendSelfForDebugger).
4319 gJdwpState->AcquireJdwpTokenForEvent(pReq->thread_id);
4320
4321 // Send the reply unless the debugger detached before the completion of the method.
4322 if (IsDebuggerActive()) {
4323 const size_t replyDataLength = expandBufGetLength(pReply) - kJDWPHeaderLen;
4324 VLOG(jdwp) << StringPrintf("REPLY INVOKE id=0x%06x (length=%zu)",
4325 pReq->request_id, replyDataLength);
4326
4327 gJdwpState->SendRequest(pReply);
4328 } else {
4329 VLOG(jdwp) << "Not sending invoke reply because debugger detached";
Elliott Hughesd07986f2011-12-06 18:27:45 -08004330 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004331}
4332
Alex Light8c2b9292017-11-09 13:21:01 -08004333bool Dbg::DdmHandleChunk(JNIEnv* env,
4334 uint32_t type,
4335 const ArrayRef<const jbyte>& data,
4336 /*out*/uint32_t* out_type,
4337 /*out*/std::vector<uint8_t>* out_data) {
4338 ScopedLocalRef<jbyteArray> dataArray(env, env->NewByteArray(data.size()));
Ian Rogersc0542af2014-09-03 16:16:56 -07004339 if (dataArray.get() == nullptr) {
Alex Light8c2b9292017-11-09 13:21:01 -08004340 LOG(WARNING) << "byte[] allocation failed: " << data.size();
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004341 env->ExceptionClear();
4342 return false;
4343 }
Alex Light8c2b9292017-11-09 13:21:01 -08004344 env->SetByteArrayRegion(dataArray.get(),
4345 0,
4346 data.size(),
4347 reinterpret_cast<const jbyte*>(data.data()));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004348 // Call "private static Chunk dispatch(int type, byte[] data, int offset, int length)".
Alex Light8c2b9292017-11-09 13:21:01 -08004349 ScopedLocalRef<jobject> chunk(
4350 env,
4351 env->CallStaticObjectMethod(
4352 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
4353 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_dispatch,
4354 type, dataArray.get(), 0, data.size()));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004355 if (env->ExceptionCheck()) {
4356 LOG(INFO) << StringPrintf("Exception thrown by dispatcher for 0x%08x", type);
4357 env->ExceptionDescribe();
4358 env->ExceptionClear();
4359 return false;
4360 }
4361
Ian Rogersc0542af2014-09-03 16:16:56 -07004362 if (chunk.get() == nullptr) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004363 return false;
4364 }
4365
4366 /*
4367 * Pull the pieces out of the chunk. We copy the results into a
4368 * newly-allocated buffer that the caller can free. We don't want to
4369 * continue using the Chunk object because nothing has a reference to it.
4370 *
4371 * We could avoid this by returning type/data/offset/length and having
4372 * the caller be aware of the object lifetime issues, but that
Elliott Hughes81ff3182012-03-23 20:35:56 -07004373 * integrates the JDWP code more tightly into the rest of the runtime, and doesn't work
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004374 * if we have responses for multiple chunks.
4375 *
4376 * So we're pretty much stuck with copying data around multiple times.
4377 */
Alex Light8c2b9292017-11-09 13:21:01 -08004378 ScopedLocalRef<jbyteArray> replyData(
4379 env,
4380 reinterpret_cast<jbyteArray>(
4381 env->GetObjectField(
4382 chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_data)));
4383 jint offset = env->GetIntField(chunk.get(),
4384 WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_offset);
4385 jint length = env->GetIntField(chunk.get(),
4386 WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_length);
4387 *out_type = env->GetIntField(chunk.get(),
4388 WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_type);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004389
Alex Light8c2b9292017-11-09 13:21:01 -08004390 VLOG(jdwp) << StringPrintf("DDM reply: type=0x%08x data=%p offset=%d length=%d",
4391 type,
4392 replyData.get(),
4393 offset,
4394 length);
Alex Light8c2b9292017-11-09 13:21:01 -08004395 out_data->resize(length);
4396 env->GetByteArrayRegion(replyData.get(),
4397 offset,
4398 length,
4399 reinterpret_cast<jbyte*>(out_data->data()));
Alex Light6f2a6342017-12-12 09:55:05 -08004400
Alex Lighte5463a82017-12-12 13:33:28 -08004401 if (env->ExceptionCheck()) {
4402 LOG(INFO) << StringPrintf("Exception thrown when reading response data from dispatcher 0x%08x",
4403 type);
4404 env->ExceptionDescribe();
4405 env->ExceptionClear();
4406 return false;
4407 }
4408
Alex Light8c2b9292017-11-09 13:21:01 -08004409 return true;
4410}
4411
4412/*
4413 * "request" contains a full JDWP packet, possibly with multiple chunks. We
4414 * need to process each, accumulate the replies, and ship the whole thing
4415 * back.
4416 *
4417 * Returns "true" if we have a reply. The reply buffer is newly allocated,
4418 * and includes the chunk type/length, followed by the data.
4419 *
4420 * OLD-TODO: we currently assume that the request and reply include a single
4421 * chunk. If this becomes inconvenient we will need to adapt.
4422 */
4423bool Dbg::DdmHandlePacket(JDWP::Request* request, uint8_t** pReplyBuf, int* pReplyLen) {
4424 Thread* self = Thread::Current();
4425 JNIEnv* env = self->GetJniEnv();
4426
4427 uint32_t type = request->ReadUnsigned32("type");
4428 uint32_t length = request->ReadUnsigned32("length");
4429
4430 // Create a byte[] corresponding to 'request'.
4431 size_t request_length = request->size();
4432 // Run through and find all chunks. [Currently just find the first.]
4433 if (length != request_length) {
4434 LOG(WARNING) << StringPrintf("bad chunk found (len=%u pktLen=%zd)", length, request_length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004435 return false;
4436 }
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004437
Alex Light8c2b9292017-11-09 13:21:01 -08004438 ArrayRef<const jbyte> data(reinterpret_cast<const jbyte*>(request->data()), request_length);
4439 std::vector<uint8_t> out_data;
4440 uint32_t out_type = 0;
4441 request->Skip(request_length);
Alex Light6f2a6342017-12-12 09:55:05 -08004442 if (!DdmHandleChunk(env, type, data, &out_type, &out_data) || out_data.empty()) {
Alex Light8c2b9292017-11-09 13:21:01 -08004443 return false;
4444 }
4445 const uint32_t kDdmHeaderSize = 8;
4446 *pReplyLen = out_data.size() + kDdmHeaderSize;
4447 *pReplyBuf = new uint8_t[out_data.size() + kDdmHeaderSize];
4448 memcpy((*pReplyBuf) + kDdmHeaderSize, out_data.data(), out_data.size());
4449 JDWP::Set4BE(*pReplyBuf, out_type);
4450 JDWP::Set4BE((*pReplyBuf) + 4, static_cast<uint32_t>(out_data.size()));
4451 VLOG(jdwp)
4452 << StringPrintf("dvmHandleDdm returning type=%.4s", reinterpret_cast<char*>(*pReplyBuf))
4453 << "0x" << std::hex << reinterpret_cast<uintptr_t>(*pReplyBuf) << std::dec
4454 << " len= " << out_data.size();
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004455 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004456}
4457
Elliott Hughesa2155262011-11-16 16:26:58 -08004458void Dbg::DdmBroadcast(bool connect) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08004459 VLOG(jdwp) << "Broadcasting DDM " << (connect ? "connect" : "disconnect") << "...";
Elliott Hughes47fce012011-10-25 18:37:19 -07004460
4461 Thread* self = Thread::Current();
Ian Rogers50b35e22012-10-04 10:09:15 -07004462 if (self->GetState() != kRunnable) {
4463 LOG(ERROR) << "DDM broadcast in thread state " << self->GetState();
4464 /* try anyway? */
Elliott Hughes47fce012011-10-25 18:37:19 -07004465 }
4466
4467 JNIEnv* env = self->GetJniEnv();
Elliott Hughes47fce012011-10-25 18:37:19 -07004468 jint event = connect ? 1 /*DdmServer.CONNECTED*/ : 2 /*DdmServer.DISCONNECTED*/;
Elliott Hugheseac76672012-05-24 21:56:51 -07004469 env->CallStaticVoidMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
4470 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_broadcast,
4471 event);
Elliott Hughes47fce012011-10-25 18:37:19 -07004472 if (env->ExceptionCheck()) {
4473 LOG(ERROR) << "DdmServer.broadcast " << event << " failed";
4474 env->ExceptionDescribe();
4475 env->ExceptionClear();
4476 }
4477}
4478
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004479void Dbg::DdmConnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08004480 Dbg::DdmBroadcast(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004481}
4482
4483void Dbg::DdmDisconnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08004484 Dbg::DdmBroadcast(false);
Elliott Hughes47fce012011-10-25 18:37:19 -07004485 gDdmThreadNotification = false;
4486}
4487
4488/*
Elliott Hughes82188472011-11-07 18:11:48 -08004489 * Send a notification when a thread starts, stops, or changes its name.
Elliott Hughes47fce012011-10-25 18:37:19 -07004490 *
4491 * Because we broadcast the full set of threads when the notifications are
4492 * first enabled, it's possible for "thread" to be actively executing.
4493 */
Elliott Hughes82188472011-11-07 18:11:48 -08004494void Dbg::DdmSendThreadNotification(Thread* t, uint32_t type) {
Elliott Hughes47fce012011-10-25 18:37:19 -07004495 if (!gDdmThreadNotification) {
4496 return;
4497 }
4498
Alex Light772099a2017-11-21 14:05:04 -08004499 RuntimeCallbacks* cb = Runtime::Current()->GetRuntimeCallbacks();
Elliott Hughes82188472011-11-07 18:11:48 -08004500 if (type == CHUNK_TYPE("THDE")) {
Elliott Hughes47fce012011-10-25 18:37:19 -07004501 uint8_t buf[4];
Ian Rogersd9c4fc92013-10-01 19:45:43 -07004502 JDWP::Set4BE(&buf[0], t->GetThreadId());
Alex Light772099a2017-11-21 14:05:04 -08004503 cb->DdmPublishChunk(CHUNK_TYPE("THDE"), ArrayRef<const uint8_t>(buf));
Elliott Hughes82188472011-11-07 18:11:48 -08004504 } else {
4505 CHECK(type == CHUNK_TYPE("THCR") || type == CHUNK_TYPE("THNM")) << type;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004506 ScopedObjectAccessUnchecked soa(Thread::Current());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004507 StackHandleScope<1> hs(soa.Self());
Andreas Gampe08883de2016-11-08 13:20:52 -08004508 Handle<mirror::String> name(hs.NewHandle(t->GetThreadName()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004509 size_t char_count = (name != nullptr) ? name->GetLength() : 0;
4510 const jchar* chars = (name != nullptr) ? name->GetValue() : nullptr;
4511 bool is_compressed = (name != nullptr) ? name->IsCompressed() : false;
Elliott Hughes82188472011-11-07 18:11:48 -08004512
Elliott Hughes21f32d72011-11-09 17:44:13 -08004513 std::vector<uint8_t> bytes;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07004514 JDWP::Append4BE(bytes, t->GetThreadId());
jessicahandojo3aaa37b2016-07-29 14:46:37 -07004515 if (is_compressed) {
4516 const uint8_t* chars_compressed = name->GetValueCompressed();
4517 JDWP::AppendUtf16CompressedBE(bytes, chars_compressed, char_count);
4518 } else {
4519 JDWP::AppendUtf16BE(bytes, chars, char_count);
4520 }
Elliott Hughes21f32d72011-11-09 17:44:13 -08004521 CHECK_EQ(bytes.size(), char_count*2 + sizeof(uint32_t)*2);
Alex Light772099a2017-11-21 14:05:04 -08004522 cb->DdmPublishChunk(type, ArrayRef<const uint8_t>(bytes));
Elliott Hughes47fce012011-10-25 18:37:19 -07004523 }
4524}
4525
Elliott Hughes47fce012011-10-25 18:37:19 -07004526void Dbg::DdmSetThreadNotification(bool enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004527 // Enable/disable thread notifications.
Elliott Hughes47fce012011-10-25 18:37:19 -07004528 gDdmThreadNotification = enable;
4529 if (enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004530 // Suspend the VM then post thread start notifications for all threads. Threads attaching will
4531 // see a suspension in progress and block until that ends. They then post their own start
4532 // notification.
4533 SuspendVM();
4534 std::list<Thread*> threads;
Ian Rogers50b35e22012-10-04 10:09:15 -07004535 Thread* self = Thread::Current();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004536 {
Ian Rogers50b35e22012-10-04 10:09:15 -07004537 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004538 threads = Runtime::Current()->GetThreadList()->GetList();
4539 }
4540 {
Ian Rogers50b35e22012-10-04 10:09:15 -07004541 ScopedObjectAccess soa(self);
Mathieu Chartier02e25112013-08-14 16:14:24 -07004542 for (Thread* thread : threads) {
4543 Dbg::DdmSendThreadNotification(thread, CHUNK_TYPE("THCR"));
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004544 }
4545 }
4546 ResumeVM();
Elliott Hughes47fce012011-10-25 18:37:19 -07004547 }
4548}
4549
Elliott Hughesa2155262011-11-16 16:26:58 -08004550void Dbg::PostThreadStartOrStop(Thread* t, uint32_t type) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07004551 if (IsDebuggerActive()) {
Sebastien Hertz6995c602014-09-09 12:10:13 +02004552 gJdwpState->PostThreadChange(t, type == CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07004553 }
Elliott Hughes82188472011-11-07 18:11:48 -08004554 Dbg::DdmSendThreadNotification(t, type);
Elliott Hughes47fce012011-10-25 18:37:19 -07004555}
4556
4557void Dbg::PostThreadStart(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004558 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07004559}
4560
4561void Dbg::PostThreadDeath(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004562 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THDE"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004563}
4564
Mathieu Chartierad466ad2015-01-08 16:28:08 -08004565JDWP::JdwpState* Dbg::GetJdwpState() {
4566 return gJdwpState;
4567}
4568
Elliott Hughes767a1472011-10-26 18:49:02 -07004569int Dbg::DdmHandleHpifChunk(HpifWhen when) {
4570 if (when == HPIF_WHEN_NOW) {
Elliott Hughes7162ad92011-10-27 14:08:42 -07004571 DdmSendHeapInfo(when);
Elliott Hughes767a1472011-10-26 18:49:02 -07004572 return true;
4573 }
4574
4575 if (when != HPIF_WHEN_NEVER && when != HPIF_WHEN_NEXT_GC && when != HPIF_WHEN_EVERY_GC) {
4576 LOG(ERROR) << "invalid HpifWhen value: " << static_cast<int>(when);
4577 return false;
4578 }
4579
4580 gDdmHpifWhen = when;
4581 return true;
4582}
4583
4584bool Dbg::DdmHandleHpsgNhsgChunk(Dbg::HpsgWhen when, Dbg::HpsgWhat what, bool native) {
4585 if (when != HPSG_WHEN_NEVER && when != HPSG_WHEN_EVERY_GC) {
4586 LOG(ERROR) << "invalid HpsgWhen value: " << static_cast<int>(when);
4587 return false;
4588 }
4589
4590 if (what != HPSG_WHAT_MERGED_OBJECTS && what != HPSG_WHAT_DISTINCT_OBJECTS) {
4591 LOG(ERROR) << "invalid HpsgWhat value: " << static_cast<int>(what);
4592 return false;
4593 }
4594
4595 if (native) {
4596 gDdmNhsgWhen = when;
4597 gDdmNhsgWhat = what;
4598 } else {
4599 gDdmHpsgWhen = when;
4600 gDdmHpsgWhat = what;
4601 }
4602 return true;
4603}
4604
Elliott Hughes7162ad92011-10-27 14:08:42 -07004605void Dbg::DdmSendHeapInfo(HpifWhen reason) {
4606 // If there's a one-shot 'when', reset it.
4607 if (reason == gDdmHpifWhen) {
4608 if (gDdmHpifWhen == HPIF_WHEN_NEXT_GC) {
4609 gDdmHpifWhen = HPIF_WHEN_NEVER;
4610 }
4611 }
4612
4613 /*
4614 * Chunk HPIF (client --> server)
4615 *
4616 * Heap Info. General information about the heap,
4617 * suitable for a summary display.
4618 *
4619 * [u4]: number of heaps
4620 *
4621 * For each heap:
4622 * [u4]: heap ID
4623 * [u8]: timestamp in ms since Unix epoch
4624 * [u1]: capture reason (same as 'when' value from server)
4625 * [u4]: max heap size in bytes (-Xmx)
4626 * [u4]: current heap size in bytes
4627 * [u4]: current number of bytes allocated
4628 * [u4]: current number of objects allocated
4629 */
4630 uint8_t heap_count = 1;
Ian Rogers1d54e732013-05-02 21:10:01 -07004631 gc::Heap* heap = Runtime::Current()->GetHeap();
Elliott Hughes21f32d72011-11-09 17:44:13 -08004632 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08004633 JDWP::Append4BE(bytes, heap_count);
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004634 JDWP::Append4BE(bytes, 1); // Heap id (bogus; we only have one heap).
Elliott Hughes545a0642011-11-08 19:10:03 -08004635 JDWP::Append8BE(bytes, MilliTime());
4636 JDWP::Append1BE(bytes, reason);
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004637 JDWP::Append4BE(bytes, heap->GetMaxMemory()); // Max allowed heap size in bytes.
4638 JDWP::Append4BE(bytes, heap->GetTotalMemory()); // Current heap size in bytes.
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08004639 JDWP::Append4BE(bytes, heap->GetBytesAllocated());
4640 JDWP::Append4BE(bytes, heap->GetObjectsAllocated());
Elliott Hughes21f32d72011-11-09 17:44:13 -08004641 CHECK_EQ(bytes.size(), 4U + (heap_count * (4 + 8 + 1 + 4 + 4 + 4 + 4)));
Alex Light772099a2017-11-21 14:05:04 -08004642 Runtime::Current()->GetRuntimeCallbacks()->DdmPublishChunk(CHUNK_TYPE("HPIF"),
4643 ArrayRef<const uint8_t>(bytes));
Elliott Hughes767a1472011-10-26 18:49:02 -07004644}
4645
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004646enum HpsgSolidity {
4647 SOLIDITY_FREE = 0,
4648 SOLIDITY_HARD = 1,
4649 SOLIDITY_SOFT = 2,
4650 SOLIDITY_WEAK = 3,
4651 SOLIDITY_PHANTOM = 4,
4652 SOLIDITY_FINALIZABLE = 5,
4653 SOLIDITY_SWEEP = 6,
4654};
4655
4656enum HpsgKind {
4657 KIND_OBJECT = 0,
4658 KIND_CLASS_OBJECT = 1,
4659 KIND_ARRAY_1 = 2,
4660 KIND_ARRAY_2 = 3,
4661 KIND_ARRAY_4 = 4,
4662 KIND_ARRAY_8 = 5,
4663 KIND_UNKNOWN = 6,
4664 KIND_NATIVE = 7,
4665};
4666
4667#define HPSG_PARTIAL (1<<7)
4668#define HPSG_STATE(solidity, kind) ((uint8_t)((((kind) & 0x7) << 3) | ((solidity) & 0x7)))
4669
Ian Rogers30fab402012-01-23 15:43:46 -08004670class HeapChunkContext {
4671 public:
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004672 // Maximum chunk size. Obtain this from the formula:
4673 // (((maximum_heap_size / ALLOCATION_UNIT_SIZE) + 255) / 256) * 2
4674 HeapChunkContext(bool merge, bool native)
Ian Rogers30fab402012-01-23 15:43:46 -08004675 : buf_(16384 - 16),
4676 type_(0),
Mathieu Chartier36dab362014-07-30 14:59:56 -07004677 chunk_overhead_(0) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004678 Reset();
4679 if (native) {
Ian Rogers30fab402012-01-23 15:43:46 -08004680 type_ = CHUNK_TYPE("NHSG");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004681 } else {
Ian Rogers30fab402012-01-23 15:43:46 -08004682 type_ = merge ? CHUNK_TYPE("HPSG") : CHUNK_TYPE("HPSO");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004683 }
4684 }
4685
4686 ~HeapChunkContext() {
Ian Rogers30fab402012-01-23 15:43:46 -08004687 if (p_ > &buf_[0]) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004688 Flush();
4689 }
4690 }
4691
Mathieu Chartier36dab362014-07-30 14:59:56 -07004692 void SetChunkOverhead(size_t chunk_overhead) {
4693 chunk_overhead_ = chunk_overhead;
4694 }
4695
4696 void ResetStartOfNextChunk() {
4697 startOfNextMemoryChunk_ = nullptr;
4698 }
4699
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004700 void EnsureHeader(const void* chunk_ptr) {
Ian Rogers30fab402012-01-23 15:43:46 -08004701 if (!needHeader_) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004702 return;
4703 }
4704
4705 // Start a new HPSx chunk.
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004706 JDWP::Write4BE(&p_, 1); // Heap id (bogus; we only have one heap).
4707 JDWP::Write1BE(&p_, 8); // Size of allocation unit, in bytes.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004708
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004709 JDWP::Write4BE(&p_, reinterpret_cast<uintptr_t>(chunk_ptr)); // virtual address of segment start.
4710 JDWP::Write4BE(&p_, 0); // offset of this piece (relative to the virtual address).
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004711 // [u4]: length of piece, in allocation units
4712 // 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 -08004713 pieceLenField_ = p_;
4714 JDWP::Write4BE(&p_, 0x55555555);
4715 needHeader_ = false;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004716 }
4717
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004718 void Flush() REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -07004719 if (pieceLenField_ == nullptr) {
Ian Rogersd636b062013-01-18 17:51:18 -08004720 // Flush immediately post Reset (maybe back-to-back Flush). Ignore.
4721 CHECK(needHeader_);
4722 return;
4723 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004724 // Patch the "length of piece" field.
Ian Rogers30fab402012-01-23 15:43:46 -08004725 CHECK_LE(&buf_[0], pieceLenField_);
4726 CHECK_LE(pieceLenField_, p_);
4727 JDWP::Set4BE(pieceLenField_, totalAllocationUnits_);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004728
Alex Light772099a2017-11-21 14:05:04 -08004729 ArrayRef<const uint8_t> out(&buf_[0], p_ - &buf_[0]);
4730 Runtime::Current()->GetRuntimeCallbacks()->DdmPublishChunk(type_, out);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004731 Reset();
4732 }
4733
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004734 static void HeapChunkJavaCallback(void* start, void* end, size_t used_bytes, void* arg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004735 REQUIRES_SHARED(Locks::heap_bitmap_lock_,
Ian Rogersb726dcb2012-09-05 08:57:23 -07004736 Locks::mutator_lock_) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004737 reinterpret_cast<HeapChunkContext*>(arg)->HeapChunkJavaCallback(start, end, used_bytes);
4738 }
4739
4740 static void HeapChunkNativeCallback(void* start, void* end, size_t used_bytes, void* arg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004741 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004742 reinterpret_cast<HeapChunkContext*>(arg)->HeapChunkNativeCallback(start, end, used_bytes);
Elliott Hughesa2155262011-11-16 16:26:58 -08004743 }
4744
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004745 private:
Elliott Hughesa2155262011-11-16 16:26:58 -08004746 enum { ALLOCATION_UNIT_SIZE = 8 };
4747
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004748 void Reset() {
Ian Rogers30fab402012-01-23 15:43:46 -08004749 p_ = &buf_[0];
Mathieu Chartier36dab362014-07-30 14:59:56 -07004750 ResetStartOfNextChunk();
Ian Rogers30fab402012-01-23 15:43:46 -08004751 totalAllocationUnits_ = 0;
4752 needHeader_ = true;
Ian Rogersc0542af2014-09-03 16:16:56 -07004753 pieceLenField_ = nullptr;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004754 }
4755
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004756 bool IsNative() const {
4757 return type_ == CHUNK_TYPE("NHSG");
4758 }
4759
4760 // Returns true if the object is not an empty chunk.
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004761 bool ProcessRecord(void* start, size_t used_bytes) REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers30fab402012-01-23 15:43:46 -08004762 // Note: heap call backs cannot manipulate the heap upon which they are crawling, care is taken
4763 // in the following code not to allocate memory, by ensuring buf_ is of the correct size
Ian Rogers15bf2d32012-08-28 17:33:04 -07004764 if (used_bytes == 0) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004765 if (start == nullptr) {
4766 // Reset for start of new heap.
4767 startOfNextMemoryChunk_ = nullptr;
4768 Flush();
4769 }
4770 // Only process in use memory so that free region information
4771 // also includes dlmalloc book keeping.
4772 return false;
Elliott Hughesa2155262011-11-16 16:26:58 -08004773 }
Ian Rogersc0542af2014-09-03 16:16:56 -07004774 if (startOfNextMemoryChunk_ != nullptr) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004775 // Transmit any pending free memory. Native free memory of over kMaxFreeLen could be because
4776 // of the use of mmaps, so don't report. If not free memory then start a new segment.
4777 bool flush = true;
4778 if (start > startOfNextMemoryChunk_) {
4779 const size_t kMaxFreeLen = 2 * kPageSize;
4780 void* free_start = startOfNextMemoryChunk_;
4781 void* free_end = start;
4782 const size_t free_len =
4783 reinterpret_cast<uintptr_t>(free_end) - reinterpret_cast<uintptr_t>(free_start);
4784 if (!IsNative() || free_len < kMaxFreeLen) {
4785 AppendChunk(HPSG_STATE(SOLIDITY_FREE, 0), free_start, free_len, IsNative());
4786 flush = false;
Ian Rogers15bf2d32012-08-28 17:33:04 -07004787 }
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004788 }
4789 if (flush) {
4790 startOfNextMemoryChunk_ = nullptr;
4791 Flush();
4792 }
Ian Rogers15bf2d32012-08-28 17:33:04 -07004793 }
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004794 return true;
Ian Rogers15bf2d32012-08-28 17:33:04 -07004795 }
Elliott Hughesa2155262011-11-16 16:26:58 -08004796
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004797 void HeapChunkNativeCallback(void* start, void* /*end*/, size_t used_bytes)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004798 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004799 if (ProcessRecord(start, used_bytes)) {
4800 uint8_t state = ExamineNativeObject(start);
4801 AppendChunk(state, start, used_bytes + chunk_overhead_, true /*is_native*/);
4802 startOfNextMemoryChunk_ = reinterpret_cast<char*>(start) + used_bytes + chunk_overhead_;
4803 }
4804 }
4805
4806 void HeapChunkJavaCallback(void* start, void* /*end*/, size_t used_bytes)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004807 REQUIRES_SHARED(Locks::heap_bitmap_lock_, Locks::mutator_lock_) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004808 if (ProcessRecord(start, used_bytes)) {
4809 // Determine the type of this chunk.
4810 // OLD-TODO: if context.merge, see if this chunk is different from the last chunk.
4811 // If it's the same, we should combine them.
4812 uint8_t state = ExamineJavaObject(reinterpret_cast<mirror::Object*>(start));
4813 AppendChunk(state, start, used_bytes + chunk_overhead_, false /*is_native*/);
4814 startOfNextMemoryChunk_ = reinterpret_cast<char*>(start) + used_bytes + chunk_overhead_;
4815 }
4816 }
4817
4818 void AppendChunk(uint8_t state, void* ptr, size_t length, bool is_native)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004819 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07004820 // Make sure there's enough room left in the buffer.
4821 // We need to use two bytes for every fractional 256 allocation units used by the chunk plus
4822 // 17 bytes for any header.
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004823 const size_t needed = ((RoundUp(length / ALLOCATION_UNIT_SIZE, 256) / 256) * 2) + 17;
4824 size_t byte_left = &buf_.back() - p_;
4825 if (byte_left < needed) {
4826 if (is_native) {
Pavel Vyssotski7522c742014-12-08 13:38:26 +06004827 // Cannot trigger memory allocation while walking native heap.
Pavel Vyssotski7522c742014-12-08 13:38:26 +06004828 return;
4829 }
Ian Rogers15bf2d32012-08-28 17:33:04 -07004830 Flush();
4831 }
4832
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004833 byte_left = &buf_.back() - p_;
4834 if (byte_left < needed) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07004835 LOG(WARNING) << "Chunk is too big to transmit (chunk_len=" << length << ", "
4836 << needed << " bytes)";
4837 return;
4838 }
4839 EnsureHeader(ptr);
Elliott Hughesa2155262011-11-16 16:26:58 -08004840 // Write out the chunk description.
Ian Rogers15bf2d32012-08-28 17:33:04 -07004841 length /= ALLOCATION_UNIT_SIZE; // Convert to allocation units.
4842 totalAllocationUnits_ += length;
4843 while (length > 256) {
Ian Rogers30fab402012-01-23 15:43:46 -08004844 *p_++ = state | HPSG_PARTIAL;
4845 *p_++ = 255; // length - 1
Ian Rogers15bf2d32012-08-28 17:33:04 -07004846 length -= 256;
Elliott Hughesa2155262011-11-16 16:26:58 -08004847 }
Ian Rogers30fab402012-01-23 15:43:46 -08004848 *p_++ = state;
Ian Rogers15bf2d32012-08-28 17:33:04 -07004849 *p_++ = length - 1;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004850 }
4851
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004852 uint8_t ExamineNativeObject(const void* p) REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004853 return p == nullptr ? HPSG_STATE(SOLIDITY_FREE, 0) : HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
4854 }
4855
4856 uint8_t ExamineJavaObject(mirror::Object* o)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004857 REQUIRES_SHARED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -07004858 if (o == nullptr) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004859 return HPSG_STATE(SOLIDITY_FREE, 0);
4860 }
Elliott Hughesa2155262011-11-16 16:26:58 -08004861 // It's an allocated chunk. Figure out what it is.
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004862 gc::Heap* heap = Runtime::Current()->GetHeap();
4863 if (!heap->IsLiveObjectLocked(o)) {
4864 LOG(ERROR) << "Invalid object in managed heap: " << o;
Elliott Hughesa2155262011-11-16 16:26:58 -08004865 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
4866 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004867 mirror::Class* c = o->GetClass();
Ian Rogersc0542af2014-09-03 16:16:56 -07004868 if (c == nullptr) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004869 // The object was probably just created but hasn't been initialized yet.
4870 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
4871 }
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004872 if (!heap->IsValidObjectAddress(c)) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07004873 LOG(ERROR) << "Invalid class for managed heap object: " << o << " " << c;
Elliott Hughesa2155262011-11-16 16:26:58 -08004874 return HPSG_STATE(SOLIDITY_HARD, KIND_UNKNOWN);
4875 }
Mathieu Chartierf26e1b32015-01-29 10:47:10 -08004876 if (c->GetClass() == nullptr) {
4877 LOG(ERROR) << "Null class of class " << c << " for object " << o;
4878 return HPSG_STATE(SOLIDITY_HARD, KIND_UNKNOWN);
4879 }
Elliott Hughesa2155262011-11-16 16:26:58 -08004880 if (c->IsClassClass()) {
4881 return HPSG_STATE(SOLIDITY_HARD, KIND_CLASS_OBJECT);
4882 }
Elliott Hughesa2155262011-11-16 16:26:58 -08004883 if (c->IsArrayClass()) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004884 switch (c->GetComponentSize()) {
4885 case 1: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_1);
4886 case 2: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_2);
4887 case 4: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
4888 case 8: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_8);
4889 }
4890 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004891 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
4892 }
4893
Ian Rogers30fab402012-01-23 15:43:46 -08004894 std::vector<uint8_t> buf_;
4895 uint8_t* p_;
4896 uint8_t* pieceLenField_;
Ian Rogers15bf2d32012-08-28 17:33:04 -07004897 void* startOfNextMemoryChunk_;
Ian Rogers30fab402012-01-23 15:43:46 -08004898 size_t totalAllocationUnits_;
4899 uint32_t type_;
Ian Rogers30fab402012-01-23 15:43:46 -08004900 bool needHeader_;
Mathieu Chartier36dab362014-07-30 14:59:56 -07004901 size_t chunk_overhead_;
Ian Rogers30fab402012-01-23 15:43:46 -08004902
Elliott Hughesa2155262011-11-16 16:26:58 -08004903 DISALLOW_COPY_AND_ASSIGN(HeapChunkContext);
4904};
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004905
4906void Dbg::DdmSendHeapSegments(bool native) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004907 Dbg::HpsgWhen when = native ? gDdmNhsgWhen : gDdmHpsgWhen;
4908 Dbg::HpsgWhat what = native ? gDdmNhsgWhat : gDdmHpsgWhat;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004909 if (when == HPSG_WHEN_NEVER) {
4910 return;
4911 }
Alex Light772099a2017-11-21 14:05:04 -08004912 RuntimeCallbacks* cb = Runtime::Current()->GetRuntimeCallbacks();
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004913 // Figure out what kind of chunks we'll be sending.
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004914 CHECK(what == HPSG_WHAT_MERGED_OBJECTS || what == HPSG_WHAT_DISTINCT_OBJECTS)
4915 << static_cast<int>(what);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004916
4917 // First, send a heap start chunk.
4918 uint8_t heap_id[4];
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004919 JDWP::Set4BE(&heap_id[0], 1); // Heap id (bogus; we only have one heap).
Alex Light772099a2017-11-21 14:05:04 -08004920 cb->DdmPublishChunk(native ? CHUNK_TYPE("NHST") : CHUNK_TYPE("HPST"),
4921 ArrayRef<const uint8_t>(heap_id));
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07004922 Thread* self = Thread::Current();
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07004923 Locks::mutator_lock_->AssertSharedHeld(self);
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07004924
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004925 // Send a series of heap segment chunks.
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004926 HeapChunkContext context(what == HPSG_WHAT_MERGED_OBJECTS, native);
Andreas Gampe0c183382017-07-13 22:26:24 -07004927 auto bump_pointer_space_visitor = [&](mirror::Object* obj)
4928 REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
4929 const size_t size = RoundUp(obj->SizeOf(), kObjectAlignment);
4930 HeapChunkContext::HeapChunkJavaCallback(
4931 obj, reinterpret_cast<void*>(reinterpret_cast<uintptr_t>(obj) + size), size, &context);
4932 };
Elliott Hughesa2155262011-11-16 16:26:58 -08004933 if (native) {
Dimitry Ivanove6465bc2015-12-14 18:55:02 -08004934 UNIMPLEMENTED(WARNING) << "Native heap inspection is not supported";
Elliott Hughesa2155262011-11-16 16:26:58 -08004935 } else {
Ian Rogers1d54e732013-05-02 21:10:01 -07004936 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartier36dab362014-07-30 14:59:56 -07004937 for (const auto& space : heap->GetContinuousSpaces()) {
4938 if (space->IsDlMallocSpace()) {
Mathieu Chartier4c69d7f2014-10-10 12:45:50 -07004939 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004940 // dlmalloc's chunk header is 2 * sizeof(size_t), but if the previous chunk is in use for an
4941 // allocation then the first sizeof(size_t) may belong to it.
4942 context.SetChunkOverhead(sizeof(size_t));
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004943 space->AsDlMallocSpace()->Walk(HeapChunkContext::HeapChunkJavaCallback, &context);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004944 } else if (space->IsRosAllocSpace()) {
4945 context.SetChunkOverhead(0);
Mathieu Chartier4c69d7f2014-10-10 12:45:50 -07004946 // Need to acquire the mutator lock before the heap bitmap lock with exclusive access since
4947 // RosAlloc's internal logic doesn't know to release and reacquire the heap bitmap lock.
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07004948 ScopedThreadSuspension sts(self, kSuspended);
Mathieu Chartier4f55e222015-09-04 13:26:21 -07004949 ScopedSuspendAll ssa(__FUNCTION__);
4950 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
4951 space->AsRosAllocSpace()->Walk(HeapChunkContext::HeapChunkJavaCallback, &context);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004952 } else if (space->IsBumpPointerSpace()) {
Mathieu Chartier4c69d7f2014-10-10 12:45:50 -07004953 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004954 context.SetChunkOverhead(0);
Andreas Gampe0c183382017-07-13 22:26:24 -07004955 space->AsBumpPointerSpace()->Walk(bump_pointer_space_visitor);
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004956 HeapChunkContext::HeapChunkJavaCallback(nullptr, nullptr, 0, &context);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08004957 } else if (space->IsRegionSpace()) {
4958 heap->IncrementDisableMovingGC(self);
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07004959 {
4960 ScopedThreadSuspension sts(self, kSuspended);
Mathieu Chartier4f55e222015-09-04 13:26:21 -07004961 ScopedSuspendAll ssa(__FUNCTION__);
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07004962 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
4963 context.SetChunkOverhead(0);
Andreas Gampe0c183382017-07-13 22:26:24 -07004964 space->AsRegionSpace()->Walk(bump_pointer_space_visitor);
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07004965 HeapChunkContext::HeapChunkJavaCallback(nullptr, nullptr, 0, &context);
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07004966 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08004967 heap->DecrementDisableMovingGC(self);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004968 } else {
4969 UNIMPLEMENTED(WARNING) << "Not counting objects in space " << *space;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07004970 }
Mathieu Chartier36dab362014-07-30 14:59:56 -07004971 context.ResetStartOfNextChunk();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07004972 }
Mathieu Chartier4c69d7f2014-10-10 12:45:50 -07004973 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07004974 // Walk the large objects, these are not in the AllocSpace.
Mathieu Chartier36dab362014-07-30 14:59:56 -07004975 context.SetChunkOverhead(0);
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004976 heap->GetLargeObjectsSpace()->Walk(HeapChunkContext::HeapChunkJavaCallback, &context);
Elliott Hughesa2155262011-11-16 16:26:58 -08004977 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004978
4979 // Finally, send a heap end chunk.
Alex Light772099a2017-11-21 14:05:04 -08004980 cb->DdmPublishChunk(native ? CHUNK_TYPE("NHEN") : CHUNK_TYPE("HPEN"),
4981 ArrayRef<const uint8_t>(heap_id));
Elliott Hughes767a1472011-10-26 18:49:02 -07004982}
4983
Brian Carlstrom306db812014-09-05 13:01:41 -07004984void Dbg::SetAllocTrackingEnabled(bool enable) {
Man Cao8c2ff642015-05-27 17:25:30 -07004985 gc::AllocRecordObjectMap::SetAllocTrackingEnabled(enable);
Elliott Hughes545a0642011-11-08 19:10:03 -08004986}
4987
4988void Dbg::DumpRecentAllocations() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004989 ScopedObjectAccess soa(Thread::Current());
Brian Carlstrom306db812014-09-05 13:01:41 -07004990 MutexLock mu(soa.Self(), *Locks::alloc_tracker_lock_);
Man Cao8c2ff642015-05-27 17:25:30 -07004991 if (!Runtime::Current()->GetHeap()->IsAllocTrackingEnabled()) {
Elliott Hughes545a0642011-11-08 19:10:03 -08004992 LOG(INFO) << "Not recording tracked allocations";
4993 return;
4994 }
Man Cao8c2ff642015-05-27 17:25:30 -07004995 gc::AllocRecordObjectMap* records = Runtime::Current()->GetHeap()->GetAllocationRecords();
4996 CHECK(records != nullptr);
Elliott Hughes545a0642011-11-08 19:10:03 -08004997
Man Cao1ed11b92015-06-11 22:47:35 -07004998 const uint16_t capped_count = CappedAllocRecordCount(records->GetRecentAllocationSize());
Brian Carlstrom306db812014-09-05 13:01:41 -07004999 uint16_t count = capped_count;
Elliott Hughes545a0642011-11-08 19:10:03 -08005000
Man Cao8c2ff642015-05-27 17:25:30 -07005001 LOG(INFO) << "Tracked allocations, (count=" << count << ")";
5002 for (auto it = records->RBegin(), end = records->REnd();
5003 count > 0 && it != end; count--, it++) {
Mathieu Chartier458b1052016-03-29 14:02:55 -07005004 const gc::AllocRecord* record = &it->second;
Elliott Hughes545a0642011-11-08 19:10:03 -08005005
Man Cao8c2ff642015-05-27 17:25:30 -07005006 LOG(INFO) << StringPrintf(" Thread %-2d %6zd bytes ", record->GetTid(), record->ByteCount())
David Sehr709b0702016-10-13 09:12:37 -07005007 << mirror::Class::PrettyClass(record->GetClass());
Elliott Hughes545a0642011-11-08 19:10:03 -08005008
Man Cao8c2ff642015-05-27 17:25:30 -07005009 for (size_t stack_frame = 0, depth = record->GetDepth(); stack_frame < depth; ++stack_frame) {
5010 const gc::AllocRecordStackTraceElement& stack_element = record->StackElement(stack_frame);
5011 ArtMethod* m = stack_element.GetMethod();
David Sehr709b0702016-10-13 09:12:37 -07005012 LOG(INFO) << " " << ArtMethod::PrettyMethod(m) << " line "
5013 << stack_element.ComputeLineNumber();
Elliott Hughes545a0642011-11-08 19:10:03 -08005014 }
5015
5016 // pause periodically to help logcat catch up
5017 if ((count % 5) == 0) {
5018 usleep(40000);
5019 }
Elliott Hughes545a0642011-11-08 19:10:03 -08005020 }
5021}
5022
5023class StringTable {
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07005024 private:
5025 struct Entry {
Andreas Gampe84eadb22017-07-07 15:08:01 -07005026 explicit Entry(const char* data_in)
5027 : data(data_in), hash(ComputeModifiedUtf8Hash(data_in)), index(0) {
5028 }
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07005029 Entry(const Entry& entry) = default;
5030 Entry(Entry&& entry) = default;
5031
5032 // Pointer to the actual string data.
5033 const char* data;
Andreas Gampe84eadb22017-07-07 15:08:01 -07005034
5035 // The hash of the data.
5036 const uint32_t hash;
5037
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07005038 // The index. This will be filled in on Finish and is not part of the ordering, so mark it
5039 // mutable.
5040 mutable uint32_t index;
5041
Andreas Gampe84eadb22017-07-07 15:08:01 -07005042 bool operator==(const Entry& other) const {
5043 return strcmp(data, other.data) == 0;
5044 }
5045 };
5046 struct EntryHash {
5047 size_t operator()(const Entry& entry) const {
5048 return entry.hash;
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07005049 }
5050 };
5051
Elliott Hughes545a0642011-11-08 19:10:03 -08005052 public:
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07005053 StringTable() : finished_(false) {
Elliott Hughes545a0642011-11-08 19:10:03 -08005054 }
5055
Andreas Gampef774a4e2017-07-06 22:15:18 -07005056 void Add(const char* str, bool copy_string) {
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07005057 DCHECK(!finished_);
Andreas Gampef774a4e2017-07-06 22:15:18 -07005058 if (UNLIKELY(copy_string)) {
5059 // Check whether it's already there.
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07005060 Entry entry(str);
5061 if (table_.find(entry) != table_.end()) {
Andreas Gampef774a4e2017-07-06 22:15:18 -07005062 return;
5063 }
Mathieu Chartier4345c462014-06-27 10:20:14 -07005064
Andreas Gampef774a4e2017-07-06 22:15:18 -07005065 // Make a copy.
5066 size_t str_len = strlen(str);
5067 char* copy = new char[str_len + 1];
5068 strlcpy(copy, str, str_len + 1);
5069 string_backup_.emplace_back(copy);
5070 str = copy;
5071 }
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07005072 Entry entry(str);
5073 table_.insert(entry);
5074 }
5075
5076 // Update all entries and give them an index. Note that this is likely not the insertion order,
5077 // as the set will with high likelihood reorder elements. Thus, Add must not be called after
5078 // Finish, and Finish must be called before IndexOf. In that case, WriteTo will walk in
5079 // the same order as Finish, and indices will agree. The order invariant, as well as indices,
5080 // are enforced through debug checks.
5081 void Finish() {
5082 DCHECK(!finished_);
5083 finished_ = true;
5084 uint32_t index = 0;
5085 for (auto& entry : table_) {
5086 entry.index = index;
5087 ++index;
5088 }
Elliott Hughes545a0642011-11-08 19:10:03 -08005089 }
5090
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07005091 size_t IndexOf(const char* s) const {
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07005092 DCHECK(finished_);
5093 Entry entry(s);
5094 auto it = table_.find(entry);
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07005095 if (it == table_.end()) {
5096 LOG(FATAL) << "IndexOf(\"" << s << "\") failed";
5097 }
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07005098 return it->index;
Elliott Hughes545a0642011-11-08 19:10:03 -08005099 }
5100
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07005101 size_t Size() const {
Elliott Hughes545a0642011-11-08 19:10:03 -08005102 return table_.size();
5103 }
5104
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07005105 void WriteTo(std::vector<uint8_t>& bytes) const {
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07005106 DCHECK(finished_);
5107 uint32_t cur_index = 0;
5108 for (const auto& entry : table_) {
5109 DCHECK_EQ(cur_index++, entry.index);
5110
5111 size_t s_len = CountModifiedUtf8Chars(entry.data);
Christopher Ferris8a354052015-04-24 17:23:53 -07005112 std::unique_ptr<uint16_t[]> s_utf16(new uint16_t[s_len]);
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07005113 ConvertModifiedUtf8ToUtf16(s_utf16.get(), entry.data);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005114 JDWP::AppendUtf16BE(bytes, s_utf16.get(), s_len);
Elliott Hughes545a0642011-11-08 19:10:03 -08005115 }
5116 }
5117
5118 private:
Andreas Gampe84eadb22017-07-07 15:08:01 -07005119 std::unordered_set<Entry, EntryHash> table_;
Andreas Gampef774a4e2017-07-06 22:15:18 -07005120 std::vector<std::unique_ptr<char[]>> string_backup_;
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07005121
5122 bool finished_;
5123
Elliott Hughes545a0642011-11-08 19:10:03 -08005124 DISALLOW_COPY_AND_ASSIGN(StringTable);
5125};
5126
Mathieu Chartiere401d142015-04-22 13:56:20 -07005127static const char* GetMethodSourceFile(ArtMethod* method)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005128 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07005129 DCHECK(method != nullptr);
5130 const char* source_file = method->GetDeclaringClassSourceFile();
Sebastien Hertz280286a2014-04-28 09:26:50 +02005131 return (source_file != nullptr) ? source_file : "";
5132}
5133
Elliott Hughes545a0642011-11-08 19:10:03 -08005134/*
5135 * The data we send to DDMS contains everything we have recorded.
5136 *
5137 * Message header (all values big-endian):
5138 * (1b) message header len (to allow future expansion); includes itself
5139 * (1b) entry header len
5140 * (1b) stack frame len
5141 * (2b) number of entries
5142 * (4b) offset to string table from start of message
5143 * (2b) number of class name strings
5144 * (2b) number of method name strings
5145 * (2b) number of source file name strings
5146 * For each entry:
5147 * (4b) total allocation size
Elliott Hughes221229c2013-01-08 18:17:50 -08005148 * (2b) thread id
Elliott Hughes545a0642011-11-08 19:10:03 -08005149 * (2b) allocated object's class name index
5150 * (1b) stack depth
5151 * For each stack frame:
5152 * (2b) method's class name
5153 * (2b) method name
5154 * (2b) method source file
5155 * (2b) line number, clipped to 32767; -2 if native; -1 if no source
5156 * (xb) class name strings
5157 * (xb) method name strings
5158 * (xb) source file strings
5159 *
5160 * As with other DDM traffic, strings are sent as a 4-byte length
5161 * followed by UTF-16 data.
5162 *
5163 * We send up 16-bit unsigned indexes into string tables. In theory there
Brian Carlstrom306db812014-09-05 13:01:41 -07005164 * can be (kMaxAllocRecordStackDepth * alloc_record_max_) unique strings in
Elliott Hughes545a0642011-11-08 19:10:03 -08005165 * each table, but in practice there should be far fewer.
5166 *
5167 * The chief reason for using a string table here is to keep the size of
5168 * the DDMS message to a minimum. This is partly to make the protocol
5169 * efficient, but also because we have to form the whole thing up all at
5170 * once in a memory buffer.
5171 *
5172 * We use separate string tables for class names, method names, and source
5173 * files to keep the indexes small. There will generally be no overlap
5174 * between the contents of these tables.
5175 */
5176jbyteArray Dbg::GetRecentAllocations() {
Ian Rogerscf7f1912014-10-22 22:06:39 -07005177 if ((false)) {
Elliott Hughes545a0642011-11-08 19:10:03 -08005178 DumpRecentAllocations();
5179 }
5180
Ian Rogers50b35e22012-10-04 10:09:15 -07005181 Thread* self = Thread::Current();
Elliott Hughes545a0642011-11-08 19:10:03 -08005182 std::vector<uint8_t> bytes;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005183 {
Brian Carlstrom306db812014-09-05 13:01:41 -07005184 MutexLock mu(self, *Locks::alloc_tracker_lock_);
Man Cao8c2ff642015-05-27 17:25:30 -07005185 gc::AllocRecordObjectMap* records = Runtime::Current()->GetHeap()->GetAllocationRecords();
5186 // In case this method is called when allocation tracker is disabled,
5187 // we should still send some data back.
5188 gc::AllocRecordObjectMap dummy;
5189 if (records == nullptr) {
5190 CHECK(!Runtime::Current()->GetHeap()->IsAllocTrackingEnabled());
5191 records = &dummy;
5192 }
Man Cao41656de2015-07-06 18:53:15 -07005193 // We don't need to wait on the condition variable records->new_record_condition_, because this
5194 // function only reads the class objects, which are already marked so it doesn't change their
5195 // reachability.
Man Cao8c2ff642015-05-27 17:25:30 -07005196
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005197 //
5198 // Part 1: generate string tables.
5199 //
5200 StringTable class_names;
5201 StringTable method_names;
5202 StringTable filenames;
Elliott Hughes545a0642011-11-08 19:10:03 -08005203
Andreas Gampeff29cee2017-07-07 11:11:15 -07005204 VLOG(jdwp) << "Collecting StringTables.";
5205
Man Cao1ed11b92015-06-11 22:47:35 -07005206 const uint16_t capped_count = CappedAllocRecordCount(records->GetRecentAllocationSize());
Brian Carlstrom306db812014-09-05 13:01:41 -07005207 uint16_t count = capped_count;
Andreas Gamped0fc7682017-07-07 14:03:08 -07005208 size_t alloc_byte_count = 0;
Man Cao8c2ff642015-05-27 17:25:30 -07005209 for (auto it = records->RBegin(), end = records->REnd();
5210 count > 0 && it != end; count--, it++) {
Mathieu Chartier458b1052016-03-29 14:02:55 -07005211 const gc::AllocRecord* record = &it->second;
Ian Rogers1ff3c982014-08-12 02:30:58 -07005212 std::string temp;
Andreas Gampef774a4e2017-07-06 22:15:18 -07005213 const char* class_descr = record->GetClassDescriptor(&temp);
5214 class_names.Add(class_descr, !temp.empty());
Andreas Gamped0fc7682017-07-07 14:03:08 -07005215
5216 // Size + tid + class name index + stack depth.
5217 alloc_byte_count += 4u + 2u + 2u + 1u;
5218
Man Cao8c2ff642015-05-27 17:25:30 -07005219 for (size_t i = 0, depth = record->GetDepth(); i < depth; i++) {
5220 ArtMethod* m = record->StackElement(i).GetMethod();
Andreas Gampef774a4e2017-07-06 22:15:18 -07005221 class_names.Add(m->GetDeclaringClassDescriptor(), false);
5222 method_names.Add(m->GetName(), false);
5223 filenames.Add(GetMethodSourceFile(m), false);
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005224 }
Andreas Gamped0fc7682017-07-07 14:03:08 -07005225
5226 // Depth * (class index + method name index + file name index + line number).
5227 alloc_byte_count += record->GetDepth() * (2u + 2u + 2u + 2u);
Elliott Hughes545a0642011-11-08 19:10:03 -08005228 }
5229
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07005230 class_names.Finish();
5231 method_names.Finish();
5232 filenames.Finish();
Andreas Gampeff29cee2017-07-07 11:11:15 -07005233 VLOG(jdwp) << "Done collecting StringTables:" << std::endl
5234 << " ClassNames: " << class_names.Size() << std::endl
5235 << " MethodNames: " << method_names.Size() << std::endl
5236 << " Filenames: " << filenames.Size();
5237
Man Cao8c2ff642015-05-27 17:25:30 -07005238 LOG(INFO) << "recent allocation records: " << capped_count;
5239 LOG(INFO) << "allocation records all objects: " << records->Size();
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005240
5241 //
5242 // Part 2: Generate the output and store it in the buffer.
5243 //
5244
5245 // (1b) message header len (to allow future expansion); includes itself
5246 // (1b) entry header len
5247 // (1b) stack frame len
5248 const int kMessageHeaderLen = 15;
5249 const int kEntryHeaderLen = 9;
5250 const int kStackFrameLen = 8;
5251 JDWP::Append1BE(bytes, kMessageHeaderLen);
5252 JDWP::Append1BE(bytes, kEntryHeaderLen);
5253 JDWP::Append1BE(bytes, kStackFrameLen);
5254
5255 // (2b) number of entries
5256 // (4b) offset to string table from start of message
5257 // (2b) number of class name strings
5258 // (2b) number of method name strings
5259 // (2b) number of source file name strings
Brian Carlstrom306db812014-09-05 13:01:41 -07005260 JDWP::Append2BE(bytes, capped_count);
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005261 size_t string_table_offset = bytes.size();
Brian Carlstrom7934ac22013-07-26 10:54:15 -07005262 JDWP::Append4BE(bytes, 0); // We'll patch this later...
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005263 JDWP::Append2BE(bytes, class_names.Size());
5264 JDWP::Append2BE(bytes, method_names.Size());
5265 JDWP::Append2BE(bytes, filenames.Size());
5266
Andreas Gampeff29cee2017-07-07 11:11:15 -07005267 VLOG(jdwp) << "Dumping allocations with stacks";
5268
Andreas Gamped0fc7682017-07-07 14:03:08 -07005269 // Enlarge the vector for the allocation data.
5270 size_t reserve_size = bytes.size() + alloc_byte_count;
5271 bytes.reserve(reserve_size);
5272
Ian Rogers1ff3c982014-08-12 02:30:58 -07005273 std::string temp;
Man Cao8c2ff642015-05-27 17:25:30 -07005274 count = capped_count;
5275 // The last "count" number of allocation records in "records" are the most recent "count" number
5276 // of allocations. Reverse iterate to get them. The most recent allocation is sent first.
5277 for (auto it = records->RBegin(), end = records->REnd();
5278 count > 0 && it != end; count--, it++) {
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005279 // For each entry:
5280 // (4b) total allocation size
5281 // (2b) thread id
5282 // (2b) allocated object's class name index
5283 // (1b) stack depth
Mathieu Chartier458b1052016-03-29 14:02:55 -07005284 const gc::AllocRecord* record = &it->second;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005285 size_t stack_depth = record->GetDepth();
Mathieu Chartierf8322842014-05-16 10:59:25 -07005286 size_t allocated_object_class_name_index =
Man Cao41656de2015-07-06 18:53:15 -07005287 class_names.IndexOf(record->GetClassDescriptor(&temp));
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07005288 JDWP::Append4BE(bytes, record->ByteCount());
Man Cao8c2ff642015-05-27 17:25:30 -07005289 JDWP::Append2BE(bytes, static_cast<uint16_t>(record->GetTid()));
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005290 JDWP::Append2BE(bytes, allocated_object_class_name_index);
5291 JDWP::Append1BE(bytes, stack_depth);
5292
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005293 for (size_t stack_frame = 0; stack_frame < stack_depth; ++stack_frame) {
5294 // For each stack frame:
5295 // (2b) method's class name
5296 // (2b) method name
5297 // (2b) method source file
5298 // (2b) line number, clipped to 32767; -2 if native; -1 if no source
Man Cao8c2ff642015-05-27 17:25:30 -07005299 ArtMethod* m = record->StackElement(stack_frame).GetMethod();
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07005300 size_t class_name_index = class_names.IndexOf(m->GetDeclaringClassDescriptor());
5301 size_t method_name_index = method_names.IndexOf(m->GetName());
5302 size_t file_name_index = filenames.IndexOf(GetMethodSourceFile(m));
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005303 JDWP::Append2BE(bytes, class_name_index);
5304 JDWP::Append2BE(bytes, method_name_index);
5305 JDWP::Append2BE(bytes, file_name_index);
Man Cao8c2ff642015-05-27 17:25:30 -07005306 JDWP::Append2BE(bytes, record->StackElement(stack_frame).ComputeLineNumber());
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005307 }
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005308 }
5309
Andreas Gamped0fc7682017-07-07 14:03:08 -07005310 CHECK_EQ(bytes.size(), reserve_size);
Andreas Gampeff29cee2017-07-07 11:11:15 -07005311 VLOG(jdwp) << "Dumping tables.";
5312
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005313 // (xb) class name strings
5314 // (xb) method name strings
5315 // (xb) source file strings
5316 JDWP::Set4BE(&bytes[string_table_offset], bytes.size());
5317 class_names.WriteTo(bytes);
5318 method_names.WriteTo(bytes);
5319 filenames.WriteTo(bytes);
Andreas Gampeff29cee2017-07-07 11:11:15 -07005320
5321 VLOG(jdwp) << "GetRecentAllocations: data created. " << bytes.size();
Elliott Hughes545a0642011-11-08 19:10:03 -08005322 }
Ian Rogers50b35e22012-10-04 10:09:15 -07005323 JNIEnv* env = self->GetJniEnv();
Elliott Hughes545a0642011-11-08 19:10:03 -08005324 jbyteArray result = env->NewByteArray(bytes.size());
Ian Rogersc0542af2014-09-03 16:16:56 -07005325 if (result != nullptr) {
Elliott Hughes545a0642011-11-08 19:10:03 -08005326 env->SetByteArrayRegion(result, 0, bytes.size(), reinterpret_cast<const jbyte*>(&bytes[0]));
5327 }
5328 return result;
5329}
5330
Mathieu Chartiere401d142015-04-22 13:56:20 -07005331ArtMethod* DeoptimizationRequest::Method() const {
Andreas Gampe13b27842016-11-07 16:48:23 -08005332 return jni::DecodeArtMethod(method_);
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07005333}
5334
Mathieu Chartiere401d142015-04-22 13:56:20 -07005335void DeoptimizationRequest::SetMethod(ArtMethod* m) {
Andreas Gampe13b27842016-11-07 16:48:23 -08005336 method_ = jni::EncodeArtMethod(m);
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07005337}
5338
Mathieu Chartiera6b1ead2015-10-06 10:32:38 -07005339void Dbg::VisitRoots(RootVisitor* visitor) {
5340 // Visit breakpoint roots, used to prevent unloading of methods with breakpoints.
5341 ReaderMutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
5342 BufferedRootVisitor<128> root_visitor(visitor, RootInfo(kRootVMInternal));
5343 for (Breakpoint& breakpoint : gBreakpoints) {
Andreas Gampe542451c2016-07-26 09:02:02 -07005344 breakpoint.Method()->VisitRoots(root_visitor, kRuntimePointerSize);
Mathieu Chartiera6b1ead2015-10-06 10:32:38 -07005345 }
5346}
5347
Andreas Gampe04bbb5b2017-01-19 17:49:03 +00005348void Dbg::DbgThreadLifecycleCallback::ThreadStart(Thread* self) {
5349 Dbg::PostThreadStart(self);
5350}
5351
5352void Dbg::DbgThreadLifecycleCallback::ThreadDeath(Thread* self) {
5353 Dbg::PostThreadDeath(self);
5354}
5355
Andreas Gampe0f01b582017-01-18 15:22:37 -08005356void Dbg::DbgClassLoadCallback::ClassLoad(Handle<mirror::Class> klass ATTRIBUTE_UNUSED) {
5357 // Ignore ClassLoad;
5358}
5359void Dbg::DbgClassLoadCallback::ClassPrepare(Handle<mirror::Class> temp_klass ATTRIBUTE_UNUSED,
5360 Handle<mirror::Class> klass) {
5361 Dbg::PostClassPrepare(klass.Get());
5362}
5363
Elliott Hughes872d4ec2011-10-21 17:07:15 -07005364} // namespace art