blob: 4a9449640b39101f8834d98dc342674a9f07cd6f [file] [log] [blame]
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "debugger.h"
18
Elliott Hughes3bb81562011-10-21 18:52:59 -070019#include <sys/uio.h>
20
Alex Light8c2b9292017-11-09 13:21:01 -080021#include <functional>
Andreas Gampef774a4e2017-07-06 22:15:18 -070022#include <memory>
Elliott Hughes545a0642011-11-08 19:10:03 -080023#include <set>
Andreas Gampef774a4e2017-07-06 22:15:18 -070024#include <vector>
Elliott Hughes545a0642011-11-08 19:10:03 -080025
Andreas Gampe46ee31b2016-12-14 10:11:49 -080026#include "android-base/stringprintf.h"
27
Ian Rogers166db042013-07-26 12:05:57 -070028#include "arch/context.h"
Mathieu Chartierc7853442015-03-27 14:35:38 -070029#include "art_field-inl.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070030#include "art_method-inl.h"
Andreas Gampe542451c2016-07-26 09:02:02 -070031#include "base/enums.h"
David Sehr67bf42e2018-02-26 16:43:04 -080032#include "base/safe_map.h"
Andreas Gampef774a4e2017-07-06 22:15:18 -070033#include "base/strlcpy.h"
Vladimir Marko80afd022015-05-19 18:08:00 +010034#include "base/time_utils.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080035#include "class_linker-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -070036#include "class_linker.h"
David Sehrb2ec9f52018-02-21 13:20:31 -080037#include "dex/descriptors_names.h"
David Sehr9e734c72018-01-04 17:56:19 -080038#include "dex/dex_file-inl.h"
39#include "dex/dex_file_annotations.h"
40#include "dex/dex_file_types.h"
41#include "dex/dex_instruction.h"
David Sehr0225f8e2018-01-31 08:52:24 +000042#include "dex/utf.h"
Mingyao Yang6ea1a0e2016-01-29 12:12:49 -080043#include "entrypoints/runtime_asm_entrypoints.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070044#include "gc/accounting/card_table-inl.h"
Man Cao8c2ff642015-05-27 17:25:30 -070045#include "gc/allocation_record.h"
Andreas Gampe94c589d2017-12-27 12:43:01 -080046#include "gc/gc_cause.h"
Mathieu Chartieraa516822015-10-02 15:53:37 -070047#include "gc/scoped_gc_critical_section.h"
Andreas Gampe0c183382017-07-13 22:26:24 -070048#include "gc/space/bump_pointer_space-walk-inl.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070049#include "gc/space/large_object_space.h"
50#include "gc/space/space-inl.h"
Andreas Gampe513061a2017-06-01 09:17:34 -070051#include "handle_scope-inl.h"
Sebastien Hertzcbc50642015-06-01 17:33:12 +020052#include "jdwp/jdwp_priv.h"
Elliott Hughes64f574f2013-02-20 14:57:12 -080053#include "jdwp/object_registry.h"
Andreas Gampe13b27842016-11-07 16:48:23 -080054#include "jni_internal.h"
Mathieu Chartier28bd2e42016-10-04 13:54:57 -070055#include "jvalue-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080056#include "mirror/class-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -070057#include "mirror/class.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080058#include "mirror/class_loader.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080059#include "mirror/object-inl.h"
60#include "mirror/object_array-inl.h"
Ian Rogersb0fa5dc2014-04-28 16:47:08 -070061#include "mirror/string-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080062#include "mirror/throwable.h"
Andreas Gampe373a9b52017-10-18 09:01:57 -070063#include "nativehelper/scoped_local_ref.h"
64#include "nativehelper/scoped_primitive_array.h"
Nicolas Geoffray58cc1cb2017-11-20 13:27:29 +000065#include "oat_file.h"
Mathieu Chartier3398c782016-09-30 10:27:43 -070066#include "obj_ptr-inl.h"
Ian Rogers53b8b092014-03-13 23:45:53 -070067#include "reflection.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070068#include "scoped_thread_state_change-inl.h"
Andreas Gampe513061a2017-06-01 09:17:34 -070069#include "stack.h"
Elliott Hughes475fc232011-10-25 15:00:35 -070070#include "thread_list.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070071#include "well_known_classes.h"
Elliott Hughes475fc232011-10-25 15:00:35 -070072
Elliott Hughes872d4ec2011-10-21 17:07:15 -070073namespace art {
74
Andreas Gampe46ee31b2016-12-14 10:11:49 -080075using android::base::StringPrintf;
76
Sebastien Hertz0462c4c2015-04-01 16:34:17 +020077// The key identifying the debugger to update instrumentation.
78static constexpr const char* kDbgInstrumentationKey = "Debugger";
79
Man Cao8c2ff642015-05-27 17:25:30 -070080// Limit alloc_record_count to the 2BE value (64k-1) that is the limit of the current protocol.
Brian Carlstrom306db812014-09-05 13:01:41 -070081static uint16_t CappedAllocRecordCount(size_t alloc_record_count) {
Man Cao1ed11b92015-06-11 22:47:35 -070082 const size_t cap = 0xffff;
Man Cao8c2ff642015-05-27 17:25:30 -070083 if (alloc_record_count > cap) {
84 return cap;
Brian Carlstrom306db812014-09-05 13:01:41 -070085 }
86 return alloc_record_count;
87}
Elliott Hughes475fc232011-10-25 15:00:35 -070088
Mathieu Chartier41af5e52015-10-28 11:10:46 -070089class Breakpoint : public ValueObject {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -070090 public:
Mathieu Chartier41af5e52015-10-28 11:10:46 -070091 Breakpoint(ArtMethod* method, uint32_t dex_pc, DeoptimizationRequest::Kind deoptimization_kind)
Alex Light97e78032017-06-27 17:51:55 -070092 : method_(method->GetCanonicalMethod(kRuntimePointerSize)),
Mathieu Chartier41af5e52015-10-28 11:10:46 -070093 dex_pc_(dex_pc),
94 deoptimization_kind_(deoptimization_kind) {
Sebastien Hertzf3928792014-11-17 19:00:37 +010095 CHECK(deoptimization_kind_ == DeoptimizationRequest::kNothing ||
96 deoptimization_kind_ == DeoptimizationRequest::kSelectiveDeoptimization ||
97 deoptimization_kind_ == DeoptimizationRequest::kFullDeoptimization);
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -070098 }
99
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700100 Breakpoint(const Breakpoint& other) REQUIRES_SHARED(Locks::mutator_lock_)
Mathieu Chartier41af5e52015-10-28 11:10:46 -0700101 : method_(other.method_),
102 dex_pc_(other.dex_pc_),
103 deoptimization_kind_(other.deoptimization_kind_) {}
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700104
Mathieu Chartier41af5e52015-10-28 11:10:46 -0700105 // Method() is called from root visiting, do not use ScopedObjectAccess here or it can cause
106 // GC to deadlock if another thread tries to call SuspendAll while the GC is in a runnable state.
107 ArtMethod* Method() const {
108 return method_;
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700109 }
110
111 uint32_t DexPc() const {
112 return dex_pc_;
113 }
114
Sebastien Hertzf3928792014-11-17 19:00:37 +0100115 DeoptimizationRequest::Kind GetDeoptimizationKind() const {
116 return deoptimization_kind_;
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700117 }
118
Alex Light6c8467f2015-11-20 15:03:26 -0800119 // Returns true if the method of this breakpoint and the passed in method should be considered the
120 // same. That is, they are either the same method or they are copied from the same method.
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700121 bool IsInMethod(ArtMethod* m) const REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light97e78032017-06-27 17:51:55 -0700122 return method_ == m->GetCanonicalMethod(kRuntimePointerSize);
Alex Light6c8467f2015-11-20 15:03:26 -0800123 }
124
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700125 private:
Sebastien Hertza76a6d42014-03-20 16:40:17 +0100126 // The location of this breakpoint.
Mathieu Chartier41af5e52015-10-28 11:10:46 -0700127 ArtMethod* method_;
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700128 uint32_t dex_pc_;
Sebastien Hertza76a6d42014-03-20 16:40:17 +0100129
130 // Indicates whether breakpoint needs full deoptimization or selective deoptimization.
Sebastien Hertzf3928792014-11-17 19:00:37 +0100131 DeoptimizationRequest::Kind deoptimization_kind_;
Elliott Hughes86964332012-02-15 19:37:42 -0800132};
133
Sebastien Hertzed2be172014-08-19 15:33:43 +0200134static std::ostream& operator<<(std::ostream& os, const Breakpoint& rhs)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700135 REQUIRES_SHARED(Locks::mutator_lock_) {
David Sehr709b0702016-10-13 09:12:37 -0700136 os << StringPrintf("Breakpoint[%s @%#x]", ArtMethod::PrettyMethod(rhs.Method()).c_str(),
137 rhs.DexPc());
Elliott Hughes86964332012-02-15 19:37:42 -0800138 return os;
139}
140
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200141class DebugInstrumentationListener FINAL : public instrumentation::InstrumentationListener {
Ian Rogers62d6c772013-02-27 08:32:07 -0800142 public:
143 DebugInstrumentationListener() {}
144 virtual ~DebugInstrumentationListener() {}
145
Alex Lightd7661582017-05-01 13:48:16 -0700146 void MethodEntered(Thread* thread,
147 Handle<mirror::Object> this_object,
148 ArtMethod* method,
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200149 uint32_t dex_pc)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700150 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800151 if (method->IsNative()) {
152 // TODO: post location events is a suspension point and native method entry stubs aren't.
153 return;
154 }
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200155 if (IsListeningToDexPcMoved()) {
156 // We also listen to kDexPcMoved instrumentation event so we know the DexPcMoved method is
157 // going to be called right after us. To avoid sending JDWP events twice for this location,
158 // we report the event in DexPcMoved. However, we must remind this is method entry so we
159 // send the METHOD_ENTRY event. And we can also group it with other events for this location
160 // like BREAKPOINT or SINGLE_STEP (or even METHOD_EXIT if this is a RETURN instruction).
161 thread->SetDebugMethodEntry();
162 } else if (IsListeningToMethodExit() && IsReturn(method, dex_pc)) {
163 // We also listen to kMethodExited instrumentation event and the current instruction is a
164 // RETURN so we know the MethodExited method is going to be called right after us. To avoid
165 // sending JDWP events twice for this location, we report the event(s) in MethodExited.
166 // However, we must remind this is method entry so we send the METHOD_ENTRY event. And we can
167 // also group it with other events for this location like BREAKPOINT or SINGLE_STEP.
168 thread->SetDebugMethodEntry();
169 } else {
Alex Lightd7661582017-05-01 13:48:16 -0700170 Dbg::UpdateDebugger(thread, this_object.Get(), method, 0, Dbg::kMethodEntry, nullptr);
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200171 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800172 }
173
Alex Lightd7661582017-05-01 13:48:16 -0700174 void MethodExited(Thread* thread,
175 Handle<mirror::Object> this_object,
176 ArtMethod* method,
177 uint32_t dex_pc,
178 const JValue& return_value)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700179 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800180 if (method->IsNative()) {
181 // TODO: post location events is a suspension point and native method entry stubs aren't.
182 return;
183 }
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200184 uint32_t events = Dbg::kMethodExit;
185 if (thread->IsDebugMethodEntry()) {
186 // It is also the method entry.
187 DCHECK(IsReturn(method, dex_pc));
188 events |= Dbg::kMethodEntry;
189 thread->ClearDebugMethodEntry();
190 }
Alex Lightd7661582017-05-01 13:48:16 -0700191 Dbg::UpdateDebugger(thread, this_object.Get(), method, dex_pc, events, &return_value);
Ian Rogers62d6c772013-02-27 08:32:07 -0800192 }
193
Alex Lightd7661582017-05-01 13:48:16 -0700194 void MethodUnwind(Thread* thread ATTRIBUTE_UNUSED,
195 Handle<mirror::Object> this_object ATTRIBUTE_UNUSED,
196 ArtMethod* method,
197 uint32_t dex_pc)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700198 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800199 // We're not recorded to listen to this kind of event, so complain.
David Sehr709b0702016-10-13 09:12:37 -0700200 LOG(ERROR) << "Unexpected method unwind event in debugger " << ArtMethod::PrettyMethod(method)
Sebastien Hertz51db44a2013-11-19 10:00:29 +0100201 << " " << dex_pc;
Ian Rogers62d6c772013-02-27 08:32:07 -0800202 }
203
Alex Lightd7661582017-05-01 13:48:16 -0700204 void DexPcMoved(Thread* thread,
205 Handle<mirror::Object> this_object,
206 ArtMethod* method,
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200207 uint32_t new_dex_pc)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700208 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200209 if (IsListeningToMethodExit() && IsReturn(method, new_dex_pc)) {
210 // We also listen to kMethodExited instrumentation event and the current instruction is a
211 // RETURN so we know the MethodExited method is going to be called right after us. Like in
212 // MethodEntered, we delegate event reporting to MethodExited.
213 // Besides, if this RETURN instruction is the only one in the method, we can send multiple
214 // JDWP events in the same packet: METHOD_ENTRY, METHOD_EXIT, BREAKPOINT and/or SINGLE_STEP.
215 // Therefore, we must not clear the debug method entry flag here.
216 } else {
217 uint32_t events = 0;
218 if (thread->IsDebugMethodEntry()) {
219 // It is also the method entry.
220 events = Dbg::kMethodEntry;
221 thread->ClearDebugMethodEntry();
222 }
Alex Lightd7661582017-05-01 13:48:16 -0700223 Dbg::UpdateDebugger(thread, this_object.Get(), method, new_dex_pc, events, nullptr);
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200224 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800225 }
226
Alex Lightd7661582017-05-01 13:48:16 -0700227 void FieldRead(Thread* thread ATTRIBUTE_UNUSED,
228 Handle<mirror::Object> this_object,
229 ArtMethod* method,
230 uint32_t dex_pc,
231 ArtField* field)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700232 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Lightd7661582017-05-01 13:48:16 -0700233 Dbg::PostFieldAccessEvent(method, dex_pc, this_object.Get(), field);
Ian Rogers62d6c772013-02-27 08:32:07 -0800234 }
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200235
Alex Lightd7661582017-05-01 13:48:16 -0700236 void FieldWritten(Thread* thread ATTRIBUTE_UNUSED,
237 Handle<mirror::Object> this_object,
238 ArtMethod* method,
239 uint32_t dex_pc,
240 ArtField* field,
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700241 const JValue& field_value)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700242 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Lightd7661582017-05-01 13:48:16 -0700243 Dbg::PostFieldModificationEvent(method, dex_pc, this_object.Get(), field, &field_value);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200244 }
245
Alex Light6e1607e2017-08-23 10:06:18 -0700246 void ExceptionThrown(Thread* thread ATTRIBUTE_UNUSED,
Alex Lightd7661582017-05-01 13:48:16 -0700247 Handle<mirror::Throwable> exception_object)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700248 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Lightd7661582017-05-01 13:48:16 -0700249 Dbg::PostException(exception_object.Get());
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200250 }
251
Nicolas Geoffray81f0f952016-01-20 16:25:19 +0000252 // We only care about branches in the Jit.
253 void Branch(Thread* /*thread*/, ArtMethod* method, uint32_t dex_pc, int32_t dex_pc_offset)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700254 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
David Sehr709b0702016-10-13 09:12:37 -0700255 LOG(ERROR) << "Unexpected branch event in debugger " << ArtMethod::PrettyMethod(method)
Nicolas Geoffray81f0f952016-01-20 16:25:19 +0000256 << " " << dex_pc << ", " << dex_pc_offset;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800257 }
258
Nicolas Geoffray5550ca82015-08-21 18:38:30 +0100259 // We only care about invokes in the Jit.
260 void InvokeVirtualOrInterface(Thread* thread ATTRIBUTE_UNUSED,
Alex Lightd7661582017-05-01 13:48:16 -0700261 Handle<mirror::Object> this_object ATTRIBUTE_UNUSED,
Nicolas Geoffray5550ca82015-08-21 18:38:30 +0100262 ArtMethod* method,
263 uint32_t dex_pc,
Alex Lightd7661582017-05-01 13:48:16 -0700264 ArtMethod* target ATTRIBUTE_UNUSED)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700265 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
David Sehr709b0702016-10-13 09:12:37 -0700266 LOG(ERROR) << "Unexpected invoke event in debugger " << ArtMethod::PrettyMethod(method)
Nicolas Geoffray5550ca82015-08-21 18:38:30 +0100267 << " " << dex_pc;
268 }
269
Alex Light798eab02017-08-23 12:54:53 -0700270 // TODO Might be worth it to post ExceptionCatch event.
271 void ExceptionHandled(Thread* thread ATTRIBUTE_UNUSED,
272 Handle<mirror::Throwable> throwable ATTRIBUTE_UNUSED) OVERRIDE {
273 LOG(ERROR) << "Unexpected exception handled event in debugger";
274 }
275
Alex Light05f47742017-09-14 00:34:44 +0000276 // TODO Might be worth it to implement this.
277 void WatchedFramePop(Thread* thread ATTRIBUTE_UNUSED,
278 const ShadowFrame& frame ATTRIBUTE_UNUSED) OVERRIDE {
279 LOG(ERROR) << "Unexpected WatchedFramePop event in debugger";
280 }
Alex Light798eab02017-08-23 12:54:53 -0700281
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200282 private:
Mathieu Chartier808c7a52017-12-15 11:19:33 -0800283 static bool IsReturn(ArtMethod* method, uint32_t dex_pc) REQUIRES_SHARED(Locks::mutator_lock_) {
284 return method->DexInstructions().InstructionAt(dex_pc).IsReturn();
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200285 }
286
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700287 static bool IsListeningToDexPcMoved() REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200288 return IsListeningTo(instrumentation::Instrumentation::kDexPcMoved);
289 }
290
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700291 static bool IsListeningToMethodExit() REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200292 return IsListeningTo(instrumentation::Instrumentation::kMethodExited);
293 }
294
295 static bool IsListeningTo(instrumentation::Instrumentation::InstrumentationEvent event)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700296 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200297 return (Dbg::GetInstrumentationEvents() & event) != 0;
298 }
299
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200300 DISALLOW_COPY_AND_ASSIGN(DebugInstrumentationListener);
Ian Rogers62d6c772013-02-27 08:32:07 -0800301} gDebugInstrumentationListener;
302
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700303// JDWP is allowed unless the Zygote forbids it.
304static bool gJdwpAllowed = true;
305
Elliott Hughesc0f09332012-03-26 13:27:06 -0700306// Was there a -Xrunjdwp or -agentlib:jdwp= argument on the command line?
Elliott Hughes3bb81562011-10-21 18:52:59 -0700307static bool gJdwpConfigured = false;
308
Sebastien Hertzb3b173b2015-02-06 09:16:32 +0100309// JDWP options for debugging. Only valid if IsJdwpConfigured() is true.
310static JDWP::JdwpOptions gJdwpOptions;
311
Elliott Hughes3bb81562011-10-21 18:52:59 -0700312// Runtime JDWP state.
Ian Rogersc0542af2014-09-03 16:16:56 -0700313static JDWP::JdwpState* gJdwpState = nullptr;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700314static bool gDebuggerConnected; // debugger or DDMS is connected.
Elliott Hughes3bb81562011-10-21 18:52:59 -0700315
Elliott Hughes47fce012011-10-25 18:37:19 -0700316static bool gDdmThreadNotification = false;
317
Elliott Hughes767a1472011-10-26 18:49:02 -0700318// DDMS GC-related settings.
319static Dbg::HpifWhen gDdmHpifWhen = Dbg::HPIF_WHEN_NEVER;
320static Dbg::HpsgWhen gDdmHpsgWhen = Dbg::HPSG_WHEN_NEVER;
321static Dbg::HpsgWhat gDdmHpsgWhat;
322static Dbg::HpsgWhen gDdmNhsgWhen = Dbg::HPSG_WHEN_NEVER;
323static Dbg::HpsgWhat gDdmNhsgWhat;
324
Daniel Mihalyieb076692014-08-22 17:33:31 +0200325bool Dbg::gDebuggerActive = false;
Sebastien Hertz4e5b2082015-03-24 19:03:40 +0100326bool Dbg::gDisposed = false;
Sebastien Hertz6995c602014-09-09 12:10:13 +0200327ObjectRegistry* Dbg::gRegistry = nullptr;
Alex Light21611932017-09-26 13:07:39 -0700328DebuggerActiveMethodInspectionCallback Dbg::gDebugActiveCallback;
Alex Light8c2b9292017-11-09 13:21:01 -0800329DebuggerDdmCallback Dbg::gDebugDdmCallback;
Alex Light40320712017-12-14 11:52:04 -0800330InternalDebuggerControlCallback Dbg::gDebuggerControlCallback;
Elliott Hughes475fc232011-10-25 15:00:35 -0700331
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100332// Deoptimization support.
Sebastien Hertz4d25df32014-03-21 17:44:46 +0100333std::vector<DeoptimizationRequest> Dbg::deoptimization_requests_;
334size_t Dbg::full_deoptimization_event_count_ = 0;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100335
Sebastien Hertz42cd43f2014-05-13 14:15:41 +0200336// Instrumentation event reference counters.
337size_t Dbg::dex_pc_change_event_ref_count_ = 0;
338size_t Dbg::method_enter_event_ref_count_ = 0;
339size_t Dbg::method_exit_event_ref_count_ = 0;
340size_t Dbg::field_read_event_ref_count_ = 0;
341size_t Dbg::field_write_event_ref_count_ = 0;
342size_t Dbg::exception_catch_event_ref_count_ = 0;
343uint32_t Dbg::instrumentation_events_ = 0;
344
Andreas Gampe04bbb5b2017-01-19 17:49:03 +0000345Dbg::DbgThreadLifecycleCallback Dbg::thread_lifecycle_callback_;
Andreas Gampe0f01b582017-01-18 15:22:37 -0800346Dbg::DbgClassLoadCallback Dbg::class_load_callback_;
Andreas Gampe04bbb5b2017-01-19 17:49:03 +0000347
Alex Light8c2b9292017-11-09 13:21:01 -0800348void DebuggerDdmCallback::DdmPublishChunk(uint32_t type, const ArrayRef<const uint8_t>& data) {
Alex Light772099a2017-11-21 14:05:04 -0800349 if (gJdwpState == nullptr) {
350 VLOG(jdwp) << "Debugger thread not active, ignoring DDM send: " << type;
351 } else {
352 iovec vec[1];
353 vec[0].iov_base = reinterpret_cast<void*>(const_cast<uint8_t*>(data.data()));
354 vec[0].iov_len = data.size();
355 gJdwpState->DdmSendChunkV(type, vec, 1);
356 }
Alex Light8c2b9292017-11-09 13:21:01 -0800357}
358
Alex Light21611932017-09-26 13:07:39 -0700359bool DebuggerActiveMethodInspectionCallback::IsMethodBeingInspected(ArtMethod* m ATTRIBUTE_UNUSED) {
360 return Dbg::IsDebuggerActive();
361}
362
Alex Light0fa17862017-10-24 13:43:05 -0700363bool DebuggerActiveMethodInspectionCallback::IsMethodSafeToJit(ArtMethod* m) {
364 return !Dbg::MethodHasAnyBreakpoints(m);
365}
366
Alex Light40320712017-12-14 11:52:04 -0800367void InternalDebuggerControlCallback::StartDebugger() {
368 // Release the mutator lock.
369 ScopedThreadStateChange stsc(art::Thread::Current(), kNative);
370 Dbg::StartJdwp();
371}
372
373void InternalDebuggerControlCallback::StopDebugger() {
374 Dbg::StopJdwp();
375}
376
377bool InternalDebuggerControlCallback::IsDebuggerConfigured() {
378 return Dbg::IsJdwpConfigured();
379}
380
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100381// Breakpoints.
jeffhao09bfc6a2012-12-11 18:11:43 -0800382static std::vector<Breakpoint> gBreakpoints GUARDED_BY(Locks::breakpoint_lock_);
Elliott Hughes86964332012-02-15 19:37:42 -0800383
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700384void DebugInvokeReq::VisitRoots(RootVisitor* visitor, const RootInfo& root_info) {
385 receiver.VisitRootIfNonNull(visitor, root_info); // null for static method call.
386 klass.VisitRoot(visitor, root_info);
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700387}
388
Sebastien Hertz597c4f02015-01-26 17:37:14 +0100389void SingleStepControl::AddDexPc(uint32_t dex_pc) {
390 dex_pcs_.insert(dex_pc);
Sebastien Hertzbb43b432014-04-14 11:59:08 +0200391}
392
Sebastien Hertz597c4f02015-01-26 17:37:14 +0100393bool SingleStepControl::ContainsDexPc(uint32_t dex_pc) const {
394 return dex_pcs_.find(dex_pc) == dex_pcs_.end();
Sebastien Hertzbb43b432014-04-14 11:59:08 +0200395}
396
Alex Light6c8467f2015-11-20 15:03:26 -0800397static bool IsBreakpoint(ArtMethod* m, uint32_t dex_pc)
Mathieu Chartier90443472015-07-16 20:32:27 -0700398 REQUIRES(!Locks::breakpoint_lock_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700399 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertzed2be172014-08-19 15:33:43 +0200400 ReaderMutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100401 for (size_t i = 0, e = gBreakpoints.size(); i < e; ++i) {
Alex Light6c8467f2015-11-20 15:03:26 -0800402 if (gBreakpoints[i].DexPc() == dex_pc && gBreakpoints[i].IsInMethod(m)) {
Elliott Hughes86964332012-02-15 19:37:42 -0800403 VLOG(jdwp) << "Hit breakpoint #" << i << ": " << gBreakpoints[i];
404 return true;
405 }
406 }
407 return false;
408}
409
Sebastien Hertz52d131d2014-03-13 16:17:40 +0100410static bool IsSuspendedForDebugger(ScopedObjectAccessUnchecked& soa, Thread* thread)
Mathieu Chartier90443472015-07-16 20:32:27 -0700411 REQUIRES(!Locks::thread_suspend_count_lock_) {
Elliott Hughes9e0c1752013-01-09 14:02:58 -0800412 MutexLock mu(soa.Self(), *Locks::thread_suspend_count_lock_);
413 // A thread may be suspended for GC; in this code, we really want to know whether
414 // there's a debugger suspension active.
415 return thread->IsSuspended() && thread->GetDebugSuspendCount() > 0;
416}
417
Ian Rogersc0542af2014-09-03 16:16:56 -0700418static mirror::Array* DecodeNonNullArray(JDWP::RefTypeId id, JDWP::JdwpError* error)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700419 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz6995c602014-09-09 12:10:13 +0200420 mirror::Object* o = Dbg::GetObjectRegistry()->Get<mirror::Object*>(id, error);
Ian Rogersc0542af2014-09-03 16:16:56 -0700421 if (o == nullptr) {
422 *error = JDWP::ERR_INVALID_OBJECT;
423 return nullptr;
Elliott Hughes436e3722012-02-17 20:01:47 -0800424 }
425 if (!o->IsArrayInstance()) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700426 *error = JDWP::ERR_INVALID_ARRAY;
427 return nullptr;
Elliott Hughes436e3722012-02-17 20:01:47 -0800428 }
Ian Rogersc0542af2014-09-03 16:16:56 -0700429 *error = JDWP::ERR_NONE;
Elliott Hughes436e3722012-02-17 20:01:47 -0800430 return o->AsArray();
431}
432
Ian Rogersc0542af2014-09-03 16:16:56 -0700433static mirror::Class* DecodeClass(JDWP::RefTypeId id, JDWP::JdwpError* error)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700434 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz6995c602014-09-09 12:10:13 +0200435 mirror::Object* o = Dbg::GetObjectRegistry()->Get<mirror::Object*>(id, error);
Ian Rogersc0542af2014-09-03 16:16:56 -0700436 if (o == nullptr) {
437 *error = JDWP::ERR_INVALID_OBJECT;
438 return nullptr;
Elliott Hughes436e3722012-02-17 20:01:47 -0800439 }
440 if (!o->IsClass()) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700441 *error = JDWP::ERR_INVALID_CLASS;
442 return nullptr;
Elliott Hughes436e3722012-02-17 20:01:47 -0800443 }
Ian Rogersc0542af2014-09-03 16:16:56 -0700444 *error = JDWP::ERR_NONE;
Elliott Hughes436e3722012-02-17 20:01:47 -0800445 return o->AsClass();
446}
447
Ian Rogersc0542af2014-09-03 16:16:56 -0700448static Thread* DecodeThread(ScopedObjectAccessUnchecked& soa, JDWP::ObjectId thread_id,
449 JDWP::JdwpError* error)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700450 REQUIRES_SHARED(Locks::mutator_lock_)
Mathieu Chartier90443472015-07-16 20:32:27 -0700451 REQUIRES(!Locks::thread_list_lock_, !Locks::thread_suspend_count_lock_) {
Sebastien Hertz6995c602014-09-09 12:10:13 +0200452 mirror::Object* thread_peer = Dbg::GetObjectRegistry()->Get<mirror::Object*>(thread_id, error);
Ian Rogersc0542af2014-09-03 16:16:56 -0700453 if (thread_peer == nullptr) {
Elliott Hughes221229c2013-01-08 18:17:50 -0800454 // This isn't even an object.
Ian Rogersc0542af2014-09-03 16:16:56 -0700455 *error = JDWP::ERR_INVALID_OBJECT;
456 return nullptr;
Elliott Hughes436e3722012-02-17 20:01:47 -0800457 }
Elliott Hughes221229c2013-01-08 18:17:50 -0800458
Mathieu Chartier0795f232016-09-27 18:43:30 -0700459 ObjPtr<mirror::Class> java_lang_Thread =
460 soa.Decode<mirror::Class>(WellKnownClasses::java_lang_Thread);
Elliott Hughes221229c2013-01-08 18:17:50 -0800461 if (!java_lang_Thread->IsAssignableFrom(thread_peer->GetClass())) {
462 // This isn't a thread.
Ian Rogersc0542af2014-09-03 16:16:56 -0700463 *error = JDWP::ERR_INVALID_THREAD;
464 return nullptr;
Elliott Hughes221229c2013-01-08 18:17:50 -0800465 }
466
Sebastien Hertz69206392015-04-07 15:54:25 +0200467 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogersc0542af2014-09-03 16:16:56 -0700468 Thread* thread = Thread::FromManagedThread(soa, thread_peer);
469 // If thread is null then this a java.lang.Thread without a Thread*. Must be a un-started or a
470 // zombie.
471 *error = (thread == nullptr) ? JDWP::ERR_THREAD_NOT_ALIVE : JDWP::ERR_NONE;
472 return thread;
Elliott Hughes436e3722012-02-17 20:01:47 -0800473}
474
Elliott Hughes24437992011-11-30 14:49:33 -0800475static JDWP::JdwpTag BasicTagFromDescriptor(const char* descriptor) {
476 // JDWP deliberately uses the descriptor characters' ASCII values for its enum.
477 // Note that by "basic" we mean that we don't get more specific than JT_OBJECT.
478 return static_cast<JDWP::JdwpTag>(descriptor[0]);
479}
480
Ian Rogers1ff3c982014-08-12 02:30:58 -0700481static JDWP::JdwpTag BasicTagFromClass(mirror::Class* klass)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700482 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers1ff3c982014-08-12 02:30:58 -0700483 std::string temp;
484 const char* descriptor = klass->GetDescriptor(&temp);
485 return BasicTagFromDescriptor(descriptor);
486}
487
Ian Rogers98379392014-02-24 16:53:16 -0800488static JDWP::JdwpTag TagFromClass(const ScopedObjectAccessUnchecked& soa, mirror::Class* c)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700489 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700490 CHECK(c != nullptr);
Elliott Hughes24437992011-11-30 14:49:33 -0800491 if (c->IsArrayClass()) {
492 return JDWP::JT_ARRAY;
493 }
Elliott Hughes24437992011-11-30 14:49:33 -0800494 if (c->IsStringClass()) {
495 return JDWP::JT_STRING;
Elliott Hughes24437992011-11-30 14:49:33 -0800496 }
Ian Rogers98379392014-02-24 16:53:16 -0800497 if (c->IsClassClass()) {
498 return JDWP::JT_CLASS_OBJECT;
499 }
500 {
Mathieu Chartier0795f232016-09-27 18:43:30 -0700501 ObjPtr<mirror::Class> thread_class =
502 soa.Decode<mirror::Class>(WellKnownClasses::java_lang_Thread);
Ian Rogers98379392014-02-24 16:53:16 -0800503 if (thread_class->IsAssignableFrom(c)) {
504 return JDWP::JT_THREAD;
505 }
506 }
507 {
Mathieu Chartier0795f232016-09-27 18:43:30 -0700508 ObjPtr<mirror::Class> thread_group_class =
509 soa.Decode<mirror::Class>(WellKnownClasses::java_lang_ThreadGroup);
Ian Rogers98379392014-02-24 16:53:16 -0800510 if (thread_group_class->IsAssignableFrom(c)) {
511 return JDWP::JT_THREAD_GROUP;
512 }
513 }
514 {
Mathieu Chartier0795f232016-09-27 18:43:30 -0700515 ObjPtr<mirror::Class> class_loader_class =
516 soa.Decode<mirror::Class>(WellKnownClasses::java_lang_ClassLoader);
Ian Rogers98379392014-02-24 16:53:16 -0800517 if (class_loader_class->IsAssignableFrom(c)) {
518 return JDWP::JT_CLASS_LOADER;
519 }
520 }
521 return JDWP::JT_OBJECT;
Elliott Hughes24437992011-11-30 14:49:33 -0800522}
523
524/*
525 * Objects declared to hold Object might actually hold a more specific
526 * type. The debugger may take a special interest in these (e.g. it
527 * wants to display the contents of Strings), so we want to return an
528 * appropriate tag.
529 *
530 * Null objects are tagged JT_OBJECT.
531 */
Sebastien Hertz6995c602014-09-09 12:10:13 +0200532JDWP::JdwpTag Dbg::TagFromObject(const ScopedObjectAccessUnchecked& soa, mirror::Object* o) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700533 return (o == nullptr) ? JDWP::JT_OBJECT : TagFromClass(soa, o->GetClass());
Elliott Hughes24437992011-11-30 14:49:33 -0800534}
535
536static bool IsPrimitiveTag(JDWP::JdwpTag tag) {
537 switch (tag) {
538 case JDWP::JT_BOOLEAN:
539 case JDWP::JT_BYTE:
540 case JDWP::JT_CHAR:
541 case JDWP::JT_FLOAT:
542 case JDWP::JT_DOUBLE:
543 case JDWP::JT_INT:
544 case JDWP::JT_LONG:
545 case JDWP::JT_SHORT:
546 case JDWP::JT_VOID:
547 return true;
548 default:
549 return false;
550 }
551}
552
Sebastien Hertzb3b173b2015-02-06 09:16:32 +0100553void Dbg::StartJdwp() {
Elliott Hughesc0f09332012-03-26 13:27:06 -0700554 if (!gJdwpAllowed || !IsJdwpConfigured()) {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700555 // No JDWP for you!
556 return;
557 }
558
Ian Rogers719d1a32014-03-06 12:13:39 -0800559 CHECK(gRegistry == nullptr);
Elliott Hughes475fc232011-10-25 15:00:35 -0700560 gRegistry = new ObjectRegistry;
561
Alex Light8c2b9292017-11-09 13:21:01 -0800562 {
563 // Setup the Ddm listener
564 ScopedObjectAccess soa(Thread::Current());
565 Runtime::Current()->GetRuntimeCallbacks()->AddDdmCallback(&gDebugDdmCallback);
566 }
567
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700568 // Init JDWP if the debugger is enabled. This may connect out to a
569 // debugger, passively listen for a debugger, or block waiting for a
570 // debugger.
Sebastien Hertzb3b173b2015-02-06 09:16:32 +0100571 gJdwpState = JDWP::JdwpState::Create(&gJdwpOptions);
Ian Rogersc0542af2014-09-03 16:16:56 -0700572 if (gJdwpState == nullptr) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -0800573 // We probably failed because some other process has the port already, which means that
574 // if we don't abort the user is likely to think they're talking to us when they're actually
575 // talking to that other process.
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800576 LOG(FATAL) << "Debugger thread failed to initialize";
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700577 }
578
579 // If a debugger has already attached, send the "welcome" message.
580 // This may cause us to suspend all threads.
Elliott Hughes376a7a02011-10-24 18:35:55 -0700581 if (gJdwpState->IsActive()) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700582 ScopedObjectAccess soa(Thread::Current());
Sebastien Hertz7d955652014-10-22 10:57:10 +0200583 gJdwpState->PostVMStart();
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700584 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700585}
586
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700587void Dbg::StopJdwp() {
Sebastien Hertzc6345ef2014-08-18 19:26:39 +0200588 // Post VM_DEATH event before the JDWP connection is closed (either by the JDWP thread or the
589 // destruction of gJdwpState).
590 if (gJdwpState != nullptr && gJdwpState->IsActive()) {
591 gJdwpState->PostVMDeath();
592 }
Sebastien Hertz0376e6b2014-02-06 18:12:59 +0100593 // Prevent the JDWP thread from processing JDWP incoming packets after we close the connection.
Sebastien Hertz4e5b2082015-03-24 19:03:40 +0100594 Dispose();
Elliott Hughes376a7a02011-10-24 18:35:55 -0700595 delete gJdwpState;
Ian Rogers719d1a32014-03-06 12:13:39 -0800596 gJdwpState = nullptr;
Elliott Hughes475fc232011-10-25 15:00:35 -0700597 delete gRegistry;
Ian Rogers719d1a32014-03-06 12:13:39 -0800598 gRegistry = nullptr;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700599}
600
Elliott Hughes767a1472011-10-26 18:49:02 -0700601void Dbg::GcDidFinish() {
602 if (gDdmHpifWhen != HPIF_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700603 ScopedObjectAccess soa(Thread::Current());
Brian Carlstrom4d466a82014-05-08 19:05:29 -0700604 VLOG(jdwp) << "Sending heap info to DDM";
Elliott Hughes7162ad92011-10-27 14:08:42 -0700605 DdmSendHeapInfo(gDdmHpifWhen);
Elliott Hughes767a1472011-10-26 18:49:02 -0700606 }
607 if (gDdmHpsgWhen != HPSG_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700608 ScopedObjectAccess soa(Thread::Current());
Brian Carlstrom4d466a82014-05-08 19:05:29 -0700609 VLOG(jdwp) << "Dumping heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700610 DdmSendHeapSegments(false);
Elliott Hughes767a1472011-10-26 18:49:02 -0700611 }
612 if (gDdmNhsgWhen != HPSG_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700613 ScopedObjectAccess soa(Thread::Current());
Brian Carlstrom4d466a82014-05-08 19:05:29 -0700614 VLOG(jdwp) << "Dumping native heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700615 DdmSendHeapSegments(true);
Elliott Hughes767a1472011-10-26 18:49:02 -0700616 }
617}
618
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700619void Dbg::SetJdwpAllowed(bool allowed) {
620 gJdwpAllowed = allowed;
621}
622
Leonard Mosescueb842212016-10-06 17:26:36 -0700623bool Dbg::IsJdwpAllowed() {
624 return gJdwpAllowed;
625}
626
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700627DebugInvokeReq* Dbg::GetInvokeReq() {
Elliott Hughes475fc232011-10-25 15:00:35 -0700628 return Thread::Current()->GetInvokeReq();
629}
630
631Thread* Dbg::GetDebugThread() {
Ian Rogersc0542af2014-09-03 16:16:56 -0700632 return (gJdwpState != nullptr) ? gJdwpState->GetDebugThread() : nullptr;
Elliott Hughes475fc232011-10-25 15:00:35 -0700633}
634
635void Dbg::ClearWaitForEventThread() {
Sebastien Hertz2bf93f42015-01-09 18:44:05 +0100636 gJdwpState->ReleaseJdwpTokenForEvent();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700637}
638
639void Dbg::Connected() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700640 CHECK(!gDebuggerConnected);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800641 VLOG(jdwp) << "JDWP has attached";
Elliott Hughes3bb81562011-10-21 18:52:59 -0700642 gDebuggerConnected = true;
Elliott Hughes86964332012-02-15 19:37:42 -0800643 gDisposed = false;
644}
645
Sebastien Hertzf3928792014-11-17 19:00:37 +0100646bool Dbg::RequiresDeoptimization() {
647 // We don't need deoptimization if everything runs with interpreter after
648 // enabling -Xint mode.
649 return !Runtime::Current()->GetInstrumentation()->IsForcedInterpretOnly();
650}
651
Elliott Hughesa2155262011-11-16 16:26:58 -0800652void Dbg::GoActive() {
653 // Enable all debugging features, including scans for breakpoints.
654 // This is a no-op if we're already active.
655 // Only called from the JDWP handler thread.
Daniel Mihalyieb076692014-08-22 17:33:31 +0200656 if (IsDebuggerActive()) {
Elliott Hughesa2155262011-11-16 16:26:58 -0800657 return;
658 }
659
Mathieu Chartieraa516822015-10-02 15:53:37 -0700660 Thread* const self = Thread::Current();
Elliott Hughesc0f09332012-03-26 13:27:06 -0700661 {
662 // TODO: dalvik only warned if there were breakpoints left over. clear in Dbg::Disconnected?
Mathieu Chartieraa516822015-10-02 15:53:37 -0700663 ReaderMutexLock mu(self, *Locks::breakpoint_lock_);
Elliott Hughesc0f09332012-03-26 13:27:06 -0700664 CHECK_EQ(gBreakpoints.size(), 0U);
665 }
Elliott Hughesa2155262011-11-16 16:26:58 -0800666
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100667 {
Mathieu Chartieraa516822015-10-02 15:53:37 -0700668 MutexLock mu(self, *Locks::deoptimization_lock_);
Sebastien Hertz4d25df32014-03-21 17:44:46 +0100669 CHECK_EQ(deoptimization_requests_.size(), 0U);
670 CHECK_EQ(full_deoptimization_event_count_, 0U);
Sebastien Hertz42cd43f2014-05-13 14:15:41 +0200671 CHECK_EQ(dex_pc_change_event_ref_count_, 0U);
672 CHECK_EQ(method_enter_event_ref_count_, 0U);
673 CHECK_EQ(method_exit_event_ref_count_, 0U);
674 CHECK_EQ(field_read_event_ref_count_, 0U);
675 CHECK_EQ(field_write_event_ref_count_, 0U);
676 CHECK_EQ(exception_catch_event_ref_count_, 0U);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100677 }
678
Ian Rogers62d6c772013-02-27 08:32:07 -0800679 Runtime* runtime = Runtime::Current();
Nicolas Geoffray433b79a2017-01-30 20:54:45 +0000680 // Best effort deoptimization if the runtime is non-Java debuggable. This happens when
681 // ro.debuggable is set, but the application is not debuggable, or when a standalone
682 // dalvikvm invocation is not passed the debuggable option (-Xcompiler-option --debuggable).
683 //
684 // The performance cost of this is non-negligible during native-debugging due to the
David Srbeckyf4480162016-03-16 00:06:24 +0000685 // forced JIT, so we keep the AOT code in that case in exchange for limited native debugging.
Nicolas Geoffray433b79a2017-01-30 20:54:45 +0000686 if (!runtime->IsJavaDebuggable() &&
687 !runtime->GetInstrumentation()->IsForcedInterpretOnly() &&
688 !runtime->IsNativeDebuggable()) {
689 runtime->DeoptimizeBootImage();
Mingyao Yang6ea1a0e2016-01-29 12:12:49 -0800690 }
691
Mathieu Chartier4f55e222015-09-04 13:26:21 -0700692 ScopedSuspendAll ssa(__FUNCTION__);
Sebastien Hertzf3928792014-11-17 19:00:37 +0100693 if (RequiresDeoptimization()) {
694 runtime->GetInstrumentation()->EnableDeoptimization();
695 }
Sebastien Hertz42cd43f2014-05-13 14:15:41 +0200696 instrumentation_events_ = 0;
Elliott Hughesa2155262011-11-16 16:26:58 -0800697 gDebuggerActive = true;
Alex Light21611932017-09-26 13:07:39 -0700698 Runtime::Current()->GetRuntimeCallbacks()->AddMethodInspectionCallback(&gDebugActiveCallback);
Ian Rogers62d6c772013-02-27 08:32:07 -0800699 LOG(INFO) << "Debugger is active";
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700700}
701
702void Dbg::Disconnected() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700703 CHECK(gDebuggerConnected);
704
Elliott Hughesc0f09332012-03-26 13:27:06 -0700705 LOG(INFO) << "Debugger is no longer active";
Elliott Hughes234ab152011-10-26 14:02:26 -0700706
Hiroshi Yamauchi98810e32016-05-24 14:55:40 -0700707 // Suspend all threads and exclusively acquire the mutator lock. Remove the debugger as a listener
Ian Rogers62d6c772013-02-27 08:32:07 -0800708 // and clear the object registry.
709 Runtime* runtime = Runtime::Current();
Ian Rogers62d6c772013-02-27 08:32:07 -0800710 Thread* self = Thread::Current();
Mathieu Chartier4f55e222015-09-04 13:26:21 -0700711 {
Mathieu Chartieraa516822015-10-02 15:53:37 -0700712 // Required for DisableDeoptimization.
713 gc::ScopedGCCriticalSection gcs(self,
714 gc::kGcCauseInstrumentation,
715 gc::kCollectorTypeInstrumentation);
Mathieu Chartier4f55e222015-09-04 13:26:21 -0700716 ScopedSuspendAll ssa(__FUNCTION__);
Mathieu Chartier4f55e222015-09-04 13:26:21 -0700717 // Debugger may not be active at this point.
718 if (IsDebuggerActive()) {
719 {
720 // Since we're going to disable deoptimization, we clear the deoptimization requests queue.
721 // This prevents us from having any pending deoptimization request when the debugger attaches
722 // to us again while no event has been requested yet.
Mathieu Chartiera6b1ead2015-10-06 10:32:38 -0700723 MutexLock mu(self, *Locks::deoptimization_lock_);
Mathieu Chartier4f55e222015-09-04 13:26:21 -0700724 deoptimization_requests_.clear();
725 full_deoptimization_event_count_ = 0U;
726 }
727 if (instrumentation_events_ != 0) {
728 runtime->GetInstrumentation()->RemoveListener(&gDebugInstrumentationListener,
729 instrumentation_events_);
730 instrumentation_events_ = 0;
731 }
732 if (RequiresDeoptimization()) {
733 runtime->GetInstrumentation()->DisableDeoptimization(kDbgInstrumentationKey);
734 }
735 gDebuggerActive = false;
Alex Light21611932017-09-26 13:07:39 -0700736 Runtime::Current()->GetRuntimeCallbacks()->RemoveMethodInspectionCallback(
737 &gDebugActiveCallback);
Sebastien Hertzaaea7342014-02-25 15:10:04 +0100738 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100739 }
Sebastien Hertz55f65342015-01-13 22:48:34 +0100740
741 {
742 ScopedObjectAccess soa(self);
743 gRegistry->Clear();
744 }
745
746 gDebuggerConnected = false;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700747}
748
Sebastien Hertzb3b173b2015-02-06 09:16:32 +0100749void Dbg::ConfigureJdwp(const JDWP::JdwpOptions& jdwp_options) {
750 CHECK_NE(jdwp_options.transport, JDWP::kJdwpTransportUnknown);
751 gJdwpOptions = jdwp_options;
752 gJdwpConfigured = true;
Alex Light40320712017-12-14 11:52:04 -0800753 Runtime::Current()->GetRuntimeCallbacks()->AddDebuggerControlCallback(&gDebuggerControlCallback);
Sebastien Hertzb3b173b2015-02-06 09:16:32 +0100754}
755
Elliott Hughesc0f09332012-03-26 13:27:06 -0700756bool Dbg::IsJdwpConfigured() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700757 return gJdwpConfigured;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700758}
759
760int64_t Dbg::LastDebuggerActivity() {
Elliott Hughesca951522011-12-05 12:01:32 -0800761 return gJdwpState->LastDebuggerActivity();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700762}
763
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700764void Dbg::UndoDebuggerSuspensions() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700765 Runtime::Current()->GetThreadList()->UndoDebuggerSuspensions();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700766}
767
Elliott Hughes88d63092013-01-09 09:55:54 -0800768std::string Dbg::GetClassName(JDWP::RefTypeId class_id) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700769 JDWP::JdwpError error;
770 mirror::Object* o = gRegistry->Get<mirror::Object*>(class_id, &error);
771 if (o == nullptr) {
772 if (error == JDWP::ERR_NONE) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700773 return "null";
Ian Rogersc0542af2014-09-03 16:16:56 -0700774 } else {
775 return StringPrintf("invalid object %p", reinterpret_cast<void*>(class_id));
776 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800777 }
778 if (!o->IsClass()) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700779 return StringPrintf("non-class %p", o); // This is only used for debugging output anyway.
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800780 }
Sebastien Hertz6995c602014-09-09 12:10:13 +0200781 return GetClassName(o->AsClass());
782}
783
784std::string Dbg::GetClassName(mirror::Class* klass) {
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +0200785 if (klass == nullptr) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700786 return "null";
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +0200787 }
Ian Rogers1ff3c982014-08-12 02:30:58 -0700788 std::string temp;
Sebastien Hertz6995c602014-09-09 12:10:13 +0200789 return DescriptorToName(klass->GetDescriptor(&temp));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700790}
791
Ian Rogersc0542af2014-09-03 16:16:56 -0700792JDWP::JdwpError Dbg::GetClassObject(JDWP::RefTypeId id, JDWP::ObjectId* class_object_id) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800793 JDWP::JdwpError status;
Ian Rogersc0542af2014-09-03 16:16:56 -0700794 mirror::Class* c = DecodeClass(id, &status);
795 if (c == nullptr) {
796 *class_object_id = 0;
Elliott Hughes436e3722012-02-17 20:01:47 -0800797 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800798 }
Ian Rogersc0542af2014-09-03 16:16:56 -0700799 *class_object_id = gRegistry->Add(c);
Elliott Hughes436e3722012-02-17 20:01:47 -0800800 return JDWP::ERR_NONE;
Elliott Hughes86964332012-02-15 19:37:42 -0800801}
802
Ian Rogersc0542af2014-09-03 16:16:56 -0700803JDWP::JdwpError Dbg::GetSuperclass(JDWP::RefTypeId id, JDWP::RefTypeId* superclass_id) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800804 JDWP::JdwpError status;
Ian Rogersc0542af2014-09-03 16:16:56 -0700805 mirror::Class* c = DecodeClass(id, &status);
806 if (c == nullptr) {
807 *superclass_id = 0;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800808 return status;
809 }
810 if (c->IsInterface()) {
811 // http://code.google.com/p/android/issues/detail?id=20856
Ian Rogersc0542af2014-09-03 16:16:56 -0700812 *superclass_id = 0;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800813 } else {
Ian Rogersc0542af2014-09-03 16:16:56 -0700814 *superclass_id = gRegistry->Add(c->GetSuperClass());
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800815 }
816 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700817}
818
Elliott Hughes436e3722012-02-17 20:01:47 -0800819JDWP::JdwpError Dbg::GetClassLoader(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700820 JDWP::JdwpError error;
Andreas Gampe7929a482015-12-30 19:33:49 -0800821 mirror::Class* c = DecodeClass(id, &error);
822 if (c == nullptr) {
823 return error;
Elliott Hughes436e3722012-02-17 20:01:47 -0800824 }
Andreas Gampe7929a482015-12-30 19:33:49 -0800825 expandBufAddObjectId(pReply, gRegistry->Add(c->GetClassLoader()));
Elliott Hughes436e3722012-02-17 20:01:47 -0800826 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700827}
828
Elliott Hughes436e3722012-02-17 20:01:47 -0800829JDWP::JdwpError Dbg::GetModifiers(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700830 JDWP::JdwpError error;
831 mirror::Class* c = DecodeClass(id, &error);
832 if (c == nullptr) {
833 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800834 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800835
836 uint32_t access_flags = c->GetAccessFlags() & kAccJavaFlagsMask;
837
Yevgeny Roubande34eea2014-02-15 01:06:03 +0700838 // Set ACC_SUPER. Dex files don't contain this flag but only classes are supposed to have it set,
839 // not interfaces.
Elliott Hughes436e3722012-02-17 20:01:47 -0800840 // Class.getModifiers doesn't return it, but JDWP does, so we set it here.
Yevgeny Roubande34eea2014-02-15 01:06:03 +0700841 if ((access_flags & kAccInterface) == 0) {
842 access_flags |= kAccSuper;
843 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800844
845 expandBufAdd4BE(pReply, access_flags);
846
847 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700848}
849
Ian Rogersc0542af2014-09-03 16:16:56 -0700850JDWP::JdwpError Dbg::GetMonitorInfo(JDWP::ObjectId object_id, JDWP::ExpandBuf* reply) {
851 JDWP::JdwpError error;
852 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
853 if (o == nullptr) {
Elliott Hughesf327e072013-01-09 16:01:26 -0800854 return JDWP::ERR_INVALID_OBJECT;
855 }
856
857 // Ensure all threads are suspended while we read objects' lock words.
858 Thread* self = Thread::Current();
Sebastien Hertz54263242014-03-19 18:16:50 +0100859 CHECK_EQ(self->GetState(), kRunnable);
Elliott Hughesf327e072013-01-09 16:01:26 -0800860
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700861 MonitorInfo monitor_info;
862 {
863 ScopedThreadSuspension sts(self, kSuspended);
Mathieu Chartier4f55e222015-09-04 13:26:21 -0700864 ScopedSuspendAll ssa(__FUNCTION__);
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700865 monitor_info = MonitorInfo(o);
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700866 }
Ian Rogersc0542af2014-09-03 16:16:56 -0700867 if (monitor_info.owner_ != nullptr) {
Nicolas Geoffraycafa0812017-02-15 18:27:34 +0000868 expandBufAddObjectId(reply, gRegistry->Add(monitor_info.owner_->GetPeerFromOtherThread()));
Elliott Hughesf327e072013-01-09 16:01:26 -0800869 } else {
Ian Rogersc0542af2014-09-03 16:16:56 -0700870 expandBufAddObjectId(reply, gRegistry->Add(nullptr));
Elliott Hughesf327e072013-01-09 16:01:26 -0800871 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700872 expandBufAdd4BE(reply, monitor_info.entry_count_);
873 expandBufAdd4BE(reply, monitor_info.waiters_.size());
874 for (size_t i = 0; i < monitor_info.waiters_.size(); ++i) {
Nicolas Geoffraycafa0812017-02-15 18:27:34 +0000875 expandBufAddObjectId(reply, gRegistry->Add(monitor_info.waiters_[i]->GetPeerFromOtherThread()));
Elliott Hughesf327e072013-01-09 16:01:26 -0800876 }
877 return JDWP::ERR_NONE;
878}
879
Elliott Hughes734b8c62013-01-11 15:32:45 -0800880JDWP::JdwpError Dbg::GetOwnedMonitors(JDWP::ObjectId thread_id,
Ian Rogersc0542af2014-09-03 16:16:56 -0700881 std::vector<JDWP::ObjectId>* monitors,
882 std::vector<uint32_t>* stack_depths) {
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800883 struct OwnedMonitorVisitor : public StackVisitor {
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700884 OwnedMonitorVisitor(Thread* thread, Context* context,
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -0700885 std::vector<JDWP::ObjectId>* monitor_vector,
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700886 std::vector<uint32_t>* stack_depth_vector)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700887 REQUIRES_SHARED(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +0100888 : StackVisitor(thread, context, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
889 current_stack_depth(0),
890 monitors(monitor_vector),
891 stack_depths(stack_depth_vector) {}
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800892
893 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
894 // annotalysis.
895 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
896 if (!GetMethod()->IsRuntimeMethod()) {
897 Monitor::VisitLocks(this, AppendOwnedMonitors, this);
Elliott Hughes734b8c62013-01-11 15:32:45 -0800898 ++current_stack_depth;
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800899 }
900 return true;
901 }
902
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -0700903 static void AppendOwnedMonitors(mirror::Object* owned_monitor, void* arg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700904 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers7a22fa62013-01-23 12:16:16 -0800905 OwnedMonitorVisitor* visitor = reinterpret_cast<OwnedMonitorVisitor*>(arg);
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -0700906 visitor->monitors->push_back(gRegistry->Add(owned_monitor));
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700907 visitor->stack_depths->push_back(visitor->current_stack_depth);
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800908 }
909
Elliott Hughes734b8c62013-01-11 15:32:45 -0800910 size_t current_stack_depth;
Ian Rogersc0542af2014-09-03 16:16:56 -0700911 std::vector<JDWP::ObjectId>* const monitors;
912 std::vector<uint32_t>* const stack_depths;
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800913 };
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800914
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700915 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz69206392015-04-07 15:54:25 +0200916 JDWP::JdwpError error;
917 Thread* thread = DecodeThread(soa, thread_id, &error);
918 if (thread == nullptr) {
919 return error;
920 }
921 if (!IsSuspendedForDebugger(soa, thread)) {
922 return JDWP::ERR_THREAD_NOT_SUSPENDED;
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700923 }
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -0700924 std::unique_ptr<Context> context(Context::Create());
Ian Rogersc0542af2014-09-03 16:16:56 -0700925 OwnedMonitorVisitor visitor(thread, context.get(), monitors, stack_depths);
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -0700926 visitor.WalkStack();
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800927 return JDWP::ERR_NONE;
928}
929
Sebastien Hertz52d131d2014-03-13 16:17:40 +0100930JDWP::JdwpError Dbg::GetContendedMonitor(JDWP::ObjectId thread_id,
Ian Rogersc0542af2014-09-03 16:16:56 -0700931 JDWP::ObjectId* contended_monitor) {
Elliott Hughesf9501702013-01-11 11:22:27 -0800932 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -0700933 *contended_monitor = 0;
Sebastien Hertz69206392015-04-07 15:54:25 +0200934 JDWP::JdwpError error;
935 Thread* thread = DecodeThread(soa, thread_id, &error);
936 if (thread == nullptr) {
937 return error;
Elliott Hughesf9501702013-01-11 11:22:27 -0800938 }
Sebastien Hertz69206392015-04-07 15:54:25 +0200939 if (!IsSuspendedForDebugger(soa, thread)) {
940 return JDWP::ERR_THREAD_NOT_SUSPENDED;
941 }
942 mirror::Object* contended_monitor_obj = Monitor::GetContendedMonitor(thread);
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700943 // Add() requires the thread_list_lock_ not held to avoid the lock
944 // level violation.
Ian Rogersc0542af2014-09-03 16:16:56 -0700945 *contended_monitor = gRegistry->Add(contended_monitor_obj);
Elliott Hughesf9501702013-01-11 11:22:27 -0800946 return JDWP::ERR_NONE;
947}
948
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800949JDWP::JdwpError Dbg::GetInstanceCounts(const std::vector<JDWP::RefTypeId>& class_ids,
Ian Rogersc0542af2014-09-03 16:16:56 -0700950 std::vector<uint64_t>* counts) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800951 gc::Heap* heap = Runtime::Current()->GetHeap();
Roland Levillainaf290312018-02-27 20:02:17 +0000952 heap->CollectGarbage(/* clear_soft_references */ false, gc::GcCause::kGcCauseDebugger);
Mathieu Chartiere8a3c572016-10-11 16:52:17 -0700953 VariableSizedHandleScope hs(Thread::Current());
Mathieu Chartier9d156d52016-10-06 17:44:26 -0700954 std::vector<Handle<mirror::Class>> classes;
Ian Rogersc0542af2014-09-03 16:16:56 -0700955 counts->clear();
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800956 for (size_t i = 0; i < class_ids.size(); ++i) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700957 JDWP::JdwpError error;
Mathieu Chartier9d156d52016-10-06 17:44:26 -0700958 ObjPtr<mirror::Class> c = DecodeClass(class_ids[i], &error);
Ian Rogersc0542af2014-09-03 16:16:56 -0700959 if (c == nullptr) {
960 return error;
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800961 }
Mathieu Chartier9d156d52016-10-06 17:44:26 -0700962 classes.push_back(hs.NewHandle(c));
Ian Rogersc0542af2014-09-03 16:16:56 -0700963 counts->push_back(0);
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800964 }
Ian Rogersc0542af2014-09-03 16:16:56 -0700965 heap->CountInstances(classes, false, &(*counts)[0]);
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800966 return JDWP::ERR_NONE;
967}
968
Ian Rogersc0542af2014-09-03 16:16:56 -0700969JDWP::JdwpError Dbg::GetInstances(JDWP::RefTypeId class_id, int32_t max_count,
970 std::vector<JDWP::ObjectId>* instances) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800971 gc::Heap* heap = Runtime::Current()->GetHeap();
972 // We only want reachable instances, so do a GC.
Roland Levillainaf290312018-02-27 20:02:17 +0000973 heap->CollectGarbage(/* clear_soft_references */ false, gc::GcCause::kGcCauseDebugger);
Ian Rogersc0542af2014-09-03 16:16:56 -0700974 JDWP::JdwpError error;
Mathieu Chartier9d156d52016-10-06 17:44:26 -0700975 ObjPtr<mirror::Class> c = DecodeClass(class_id, &error);
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800976 if (c == nullptr) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700977 return error;
Elliott Hughes3b78c942013-01-15 17:35:41 -0800978 }
Mathieu Chartier2d855952016-10-12 19:37:59 -0700979 VariableSizedHandleScope hs(Thread::Current());
980 std::vector<Handle<mirror::Object>> raw_instances;
Richard Uhler660be6f2017-11-22 16:12:29 +0000981 Runtime::Current()->GetHeap()->GetInstances(hs,
982 hs.NewHandle(c),
983 /* use_is_assignable_from */ false,
984 max_count,
985 raw_instances);
Elliott Hughes3b78c942013-01-15 17:35:41 -0800986 for (size_t i = 0; i < raw_instances.size(); ++i) {
Mathieu Chartier2d855952016-10-12 19:37:59 -0700987 instances->push_back(gRegistry->Add(raw_instances[i].Get()));
Elliott Hughes3b78c942013-01-15 17:35:41 -0800988 }
989 return JDWP::ERR_NONE;
990}
991
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800992JDWP::JdwpError Dbg::GetReferringObjects(JDWP::ObjectId object_id, int32_t max_count,
Ian Rogersc0542af2014-09-03 16:16:56 -0700993 std::vector<JDWP::ObjectId>* referring_objects) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800994 gc::Heap* heap = Runtime::Current()->GetHeap();
Roland Levillainaf290312018-02-27 20:02:17 +0000995 heap->CollectGarbage(/* clear_soft_references */ false, gc::GcCause::kGcCauseDebugger);
Ian Rogersc0542af2014-09-03 16:16:56 -0700996 JDWP::JdwpError error;
Mathieu Chartier9d156d52016-10-06 17:44:26 -0700997 ObjPtr<mirror::Object> o = gRegistry->Get<mirror::Object*>(object_id, &error);
Ian Rogersc0542af2014-09-03 16:16:56 -0700998 if (o == nullptr) {
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800999 return JDWP::ERR_INVALID_OBJECT;
1000 }
Mathieu Chartieraea9bfb2016-10-12 19:19:56 -07001001 VariableSizedHandleScope hs(Thread::Current());
1002 std::vector<Handle<mirror::Object>> raw_instances;
1003 heap->GetReferringObjects(hs, hs.NewHandle(o), max_count, raw_instances);
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001004 for (size_t i = 0; i < raw_instances.size(); ++i) {
Mathieu Chartieraea9bfb2016-10-12 19:19:56 -07001005 referring_objects->push_back(gRegistry->Add(raw_instances[i].Get()));
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001006 }
1007 return JDWP::ERR_NONE;
1008}
1009
Ian Rogersc0542af2014-09-03 16:16:56 -07001010JDWP::JdwpError Dbg::DisableCollection(JDWP::ObjectId object_id) {
1011 JDWP::JdwpError error;
1012 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
1013 if (o == nullptr) {
Sebastien Hertze96060a2013-12-11 12:06:28 +01001014 return JDWP::ERR_INVALID_OBJECT;
1015 }
Elliott Hughes64f574f2013-02-20 14:57:12 -08001016 gRegistry->DisableCollection(object_id);
1017 return JDWP::ERR_NONE;
1018}
1019
Ian Rogersc0542af2014-09-03 16:16:56 -07001020JDWP::JdwpError Dbg::EnableCollection(JDWP::ObjectId object_id) {
1021 JDWP::JdwpError error;
1022 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
Sebastien Hertze96060a2013-12-11 12:06:28 +01001023 // Unlike DisableCollection, JDWP specs do not state an invalid object causes an error. The RI
1024 // also ignores these cases and never return an error. However it's not obvious why this command
1025 // should behave differently from DisableCollection and IsCollected commands. So let's be more
1026 // strict and return an error if this happens.
Ian Rogersc0542af2014-09-03 16:16:56 -07001027 if (o == nullptr) {
Sebastien Hertze96060a2013-12-11 12:06:28 +01001028 return JDWP::ERR_INVALID_OBJECT;
1029 }
Elliott Hughes64f574f2013-02-20 14:57:12 -08001030 gRegistry->EnableCollection(object_id);
1031 return JDWP::ERR_NONE;
1032}
1033
Ian Rogersc0542af2014-09-03 16:16:56 -07001034JDWP::JdwpError Dbg::IsCollected(JDWP::ObjectId object_id, bool* is_collected) {
1035 *is_collected = true;
Sebastien Hertz65637eb2014-01-10 17:40:02 +01001036 if (object_id == 0) {
1037 // Null object id is invalid.
Sebastien Hertze96060a2013-12-11 12:06:28 +01001038 return JDWP::ERR_INVALID_OBJECT;
1039 }
Sebastien Hertz65637eb2014-01-10 17:40:02 +01001040 // JDWP specs state an INVALID_OBJECT error is returned if the object ID is not valid. However
1041 // the RI seems to ignore this and assume object has been collected.
Ian Rogersc0542af2014-09-03 16:16:56 -07001042 JDWP::JdwpError error;
1043 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
1044 if (o != nullptr) {
1045 *is_collected = gRegistry->IsCollected(object_id);
Sebastien Hertz65637eb2014-01-10 17:40:02 +01001046 }
Elliott Hughes64f574f2013-02-20 14:57:12 -08001047 return JDWP::ERR_NONE;
1048}
1049
Ian Rogersc0542af2014-09-03 16:16:56 -07001050void Dbg::DisposeObject(JDWP::ObjectId object_id, uint32_t reference_count) {
Elliott Hughes64f574f2013-02-20 14:57:12 -08001051 gRegistry->DisposeObject(object_id, reference_count);
1052}
1053
Mathieu Chartier3398c782016-09-30 10:27:43 -07001054JDWP::JdwpTypeTag Dbg::GetTypeTag(ObjPtr<mirror::Class> klass) {
Sebastien Hertz4d8fd492014-03-28 16:29:41 +01001055 DCHECK(klass != nullptr);
1056 if (klass->IsArrayClass()) {
1057 return JDWP::TT_ARRAY;
1058 } else if (klass->IsInterface()) {
1059 return JDWP::TT_INTERFACE;
1060 } else {
1061 return JDWP::TT_CLASS;
1062 }
1063}
1064
Elliott Hughes88d63092013-01-09 09:55:54 -08001065JDWP::JdwpError Dbg::GetReflectedType(JDWP::RefTypeId class_id, JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001066 JDWP::JdwpError error;
1067 mirror::Class* c = DecodeClass(class_id, &error);
1068 if (c == nullptr) {
1069 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001070 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001071
Sebastien Hertz4d8fd492014-03-28 16:29:41 +01001072 JDWP::JdwpTypeTag type_tag = GetTypeTag(c);
1073 expandBufAdd1(pReply, type_tag);
Elliott Hughes88d63092013-01-09 09:55:54 -08001074 expandBufAddRefTypeId(pReply, class_id);
Elliott Hughes436e3722012-02-17 20:01:47 -08001075 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001076}
1077
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001078// Get the complete list of reference classes (i.e. all classes except
1079// the primitive types).
1080// Returns a newly-allocated buffer full of RefTypeId values.
1081class ClassListCreator : public ClassVisitor {
1082 public:
1083 explicit ClassListCreator(std::vector<JDWP::RefTypeId>* classes) : classes_(classes) {}
1084
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001085 bool operator()(ObjPtr<mirror::Class> c) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001086 if (!c->IsPrimitive()) {
1087 classes_->push_back(Dbg::GetObjectRegistry()->AddRefType(c));
1088 }
1089 return true;
1090 }
1091
1092 private:
1093 std::vector<JDWP::RefTypeId>* const classes_;
1094};
1095
Ian Rogersc0542af2014-09-03 16:16:56 -07001096void Dbg::GetClassList(std::vector<JDWP::RefTypeId>* classes) {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001097 ClassListCreator clc(classes);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001098 Runtime::Current()->GetClassLinker()->VisitClassesWithoutClassesLock(&clc);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001099}
1100
Ian Rogers1ff3c982014-08-12 02:30:58 -07001101JDWP::JdwpError Dbg::GetClassInfo(JDWP::RefTypeId class_id, JDWP::JdwpTypeTag* pTypeTag,
1102 uint32_t* pStatus, std::string* pDescriptor) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001103 JDWP::JdwpError error;
1104 mirror::Class* c = DecodeClass(class_id, &error);
1105 if (c == nullptr) {
1106 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001107 }
1108
Elliott Hughesa2155262011-11-16 16:26:58 -08001109 if (c->IsArrayClass()) {
1110 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
1111 *pTypeTag = JDWP::TT_ARRAY;
1112 } else {
1113 if (c->IsErroneous()) {
1114 *pStatus = JDWP::CS_ERROR;
1115 } else {
1116 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED | JDWP::CS_INITIALIZED;
1117 }
1118 *pTypeTag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
1119 }
1120
Ian Rogersc0542af2014-09-03 16:16:56 -07001121 if (pDescriptor != nullptr) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07001122 std::string temp;
1123 *pDescriptor = c->GetDescriptor(&temp);
Elliott Hughesa2155262011-11-16 16:26:58 -08001124 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001125 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001126}
1127
Ian Rogersc0542af2014-09-03 16:16:56 -07001128void Dbg::FindLoadedClassBySignature(const char* descriptor, std::vector<JDWP::RefTypeId>* ids) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001129 std::vector<ObjPtr<mirror::Class>> classes;
Igor Murashkinb1d8c312015-08-04 11:18:43 -07001130 Runtime::Current()->GetClassLinker()->LookupClasses(descriptor, classes);
Ian Rogersc0542af2014-09-03 16:16:56 -07001131 ids->clear();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001132 for (ObjPtr<mirror::Class> c : classes) {
1133 ids->push_back(gRegistry->Add(c));
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001134 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001135}
1136
Ian Rogersc0542af2014-09-03 16:16:56 -07001137JDWP::JdwpError Dbg::GetReferenceType(JDWP::ObjectId object_id, JDWP::ExpandBuf* pReply) {
1138 JDWP::JdwpError error;
1139 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
1140 if (o == nullptr) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001141 return JDWP::ERR_INVALID_OBJECT;
Elliott Hughes499c5132011-11-17 14:55:11 -08001142 }
Elliott Hughes2435a572012-02-17 16:07:41 -08001143
Sebastien Hertz4d8fd492014-03-28 16:29:41 +01001144 JDWP::JdwpTypeTag type_tag = GetTypeTag(o->GetClass());
Elliott Hughes64f574f2013-02-20 14:57:12 -08001145 JDWP::RefTypeId type_id = gRegistry->AddRefType(o->GetClass());
Elliott Hughes2435a572012-02-17 16:07:41 -08001146
1147 expandBufAdd1(pReply, type_tag);
1148 expandBufAddRefTypeId(pReply, type_id);
1149
1150 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001151}
1152
Ian Rogersfc0e94b2013-09-23 23:51:32 -07001153JDWP::JdwpError Dbg::GetSignature(JDWP::RefTypeId class_id, std::string* signature) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001154 JDWP::JdwpError error;
1155 mirror::Class* c = DecodeClass(class_id, &error);
1156 if (c == nullptr) {
1157 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001158 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07001159 std::string temp;
1160 *signature = c->GetDescriptor(&temp);
Elliott Hughes1fe7afb2012-02-13 17:23:03 -08001161 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001162}
1163
Orion Hodson77d8a1c2017-04-24 14:53:19 +01001164JDWP::JdwpError Dbg::GetSourceDebugExtension(JDWP::RefTypeId class_id,
1165 std::string* extension_data) {
1166 JDWP::JdwpError error;
1167 mirror::Class* c = DecodeClass(class_id, &error);
1168 if (c == nullptr) {
1169 return error;
1170 }
1171 StackHandleScope<1> hs(Thread::Current());
1172 Handle<mirror::Class> klass(hs.NewHandle(c));
1173 const char* data = annotations::GetSourceDebugExtension(klass);
1174 if (data == nullptr) {
1175 return JDWP::ERR_ABSENT_INFORMATION;
1176 }
1177 *extension_data = data;
1178 return JDWP::ERR_NONE;
1179}
1180
Ian Rogersc0542af2014-09-03 16:16:56 -07001181JDWP::JdwpError Dbg::GetSourceFile(JDWP::RefTypeId class_id, std::string* result) {
1182 JDWP::JdwpError error;
1183 mirror::Class* c = DecodeClass(class_id, &error);
Sebastien Hertz4206eb52014-06-05 10:15:45 +02001184 if (c == nullptr) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001185 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001186 }
Sebastien Hertz4206eb52014-06-05 10:15:45 +02001187 const char* source_file = c->GetSourceFile();
1188 if (source_file == nullptr) {
Sebastien Hertzb7054ba2014-03-13 11:52:31 +01001189 return JDWP::ERR_ABSENT_INFORMATION;
1190 }
Ian Rogersc0542af2014-09-03 16:16:56 -07001191 *result = source_file;
Elliott Hughes436e3722012-02-17 20:01:47 -08001192 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001193}
1194
Ian Rogersc0542af2014-09-03 16:16:56 -07001195JDWP::JdwpError Dbg::GetObjectTag(JDWP::ObjectId object_id, uint8_t* tag) {
Ian Rogers98379392014-02-24 16:53:16 -08001196 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07001197 JDWP::JdwpError error;
1198 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
1199 if (error != JDWP::ERR_NONE) {
1200 *tag = JDWP::JT_VOID;
1201 return error;
Elliott Hughes546b9862012-06-20 16:06:13 -07001202 }
Ian Rogersc0542af2014-09-03 16:16:56 -07001203 *tag = TagFromObject(soa, o);
Elliott Hughes546b9862012-06-20 16:06:13 -07001204 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001205}
1206
Elliott Hughesaed4be92011-12-02 16:16:23 -08001207size_t Dbg::GetTagWidth(JDWP::JdwpTag tag) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001208 switch (tag) {
1209 case JDWP::JT_VOID:
1210 return 0;
1211 case JDWP::JT_BYTE:
1212 case JDWP::JT_BOOLEAN:
1213 return 1;
1214 case JDWP::JT_CHAR:
1215 case JDWP::JT_SHORT:
1216 return 2;
1217 case JDWP::JT_FLOAT:
1218 case JDWP::JT_INT:
1219 return 4;
1220 case JDWP::JT_ARRAY:
1221 case JDWP::JT_OBJECT:
1222 case JDWP::JT_STRING:
1223 case JDWP::JT_THREAD:
1224 case JDWP::JT_THREAD_GROUP:
1225 case JDWP::JT_CLASS_LOADER:
1226 case JDWP::JT_CLASS_OBJECT:
1227 return sizeof(JDWP::ObjectId);
1228 case JDWP::JT_DOUBLE:
1229 case JDWP::JT_LONG:
1230 return 8;
1231 default:
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001232 LOG(FATAL) << "Unknown tag " << tag;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001233 return -1;
1234 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001235}
1236
Ian Rogersc0542af2014-09-03 16:16:56 -07001237JDWP::JdwpError Dbg::GetArrayLength(JDWP::ObjectId array_id, int32_t* length) {
1238 JDWP::JdwpError error;
1239 mirror::Array* a = DecodeNonNullArray(array_id, &error);
1240 if (a == nullptr) {
1241 return error;
Elliott Hughes24437992011-11-30 14:49:33 -08001242 }
Ian Rogersc0542af2014-09-03 16:16:56 -07001243 *length = a->GetLength();
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001244 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001245}
1246
Elliott Hughes88d63092013-01-09 09:55:54 -08001247JDWP::JdwpError Dbg::OutputArray(JDWP::ObjectId array_id, int offset, int count, JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001248 JDWP::JdwpError error;
1249 mirror::Array* a = DecodeNonNullArray(array_id, &error);
Ian Rogers98379392014-02-24 16:53:16 -08001250 if (a == nullptr) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001251 return error;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001252 }
Elliott Hughes24437992011-11-30 14:49:33 -08001253
1254 if (offset < 0 || count < 0 || offset > a->GetLength() || a->GetLength() - offset < count) {
1255 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001256 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughes24437992011-11-30 14:49:33 -08001257 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07001258 JDWP::JdwpTag element_tag = BasicTagFromClass(a->GetClass()->GetComponentType());
1259 expandBufAdd1(pReply, element_tag);
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001260 expandBufAdd4BE(pReply, count);
1261
Ian Rogers1ff3c982014-08-12 02:30:58 -07001262 if (IsPrimitiveTag(element_tag)) {
1263 size_t width = GetTagWidth(element_tag);
Elliott Hughes24437992011-11-30 14:49:33 -08001264 uint8_t* dst = expandBufAddSpace(pReply, count * width);
1265 if (width == 8) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001266 const uint64_t* src8 = reinterpret_cast<uint64_t*>(a->GetRawData(sizeof(uint64_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001267 for (int i = 0; i < count; ++i) JDWP::Write8BE(&dst, src8[offset + i]);
1268 } else if (width == 4) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001269 const uint32_t* src4 = reinterpret_cast<uint32_t*>(a->GetRawData(sizeof(uint32_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001270 for (int i = 0; i < count; ++i) JDWP::Write4BE(&dst, src4[offset + i]);
1271 } else if (width == 2) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001272 const uint16_t* src2 = reinterpret_cast<uint16_t*>(a->GetRawData(sizeof(uint16_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001273 for (int i = 0; i < count; ++i) JDWP::Write2BE(&dst, src2[offset + i]);
1274 } else {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001275 const uint8_t* src = reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint8_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001276 memcpy(dst, &src[offset * width], count * width);
1277 }
1278 } else {
Ian Rogers98379392014-02-24 16:53:16 -08001279 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001280 mirror::ObjectArray<mirror::Object>* oa = a->AsObjectArray<mirror::Object>();
Elliott Hughes24437992011-11-30 14:49:33 -08001281 for (int i = 0; i < count; ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001282 mirror::Object* element = oa->Get(offset + i);
Ian Rogers98379392014-02-24 16:53:16 -08001283 JDWP::JdwpTag specific_tag = (element != nullptr) ? TagFromObject(soa, element)
Ian Rogers1ff3c982014-08-12 02:30:58 -07001284 : element_tag;
Elliott Hughes24437992011-11-30 14:49:33 -08001285 expandBufAdd1(pReply, specific_tag);
1286 expandBufAddObjectId(pReply, gRegistry->Add(element));
1287 }
1288 }
1289
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001290 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001291}
1292
Ian Rogersef7d42f2014-01-06 12:55:46 -08001293template <typename T>
Ian Rogersc0542af2014-09-03 16:16:56 -07001294static void CopyArrayData(mirror::Array* a, JDWP::Request* src, int offset, int count)
Ian Rogersef7d42f2014-01-06 12:55:46 -08001295 NO_THREAD_SAFETY_ANALYSIS {
1296 // TODO: fix when annotalysis correctly handles non-member functions.
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001297 DCHECK(a->GetClass()->IsPrimitiveArray());
1298
Ian Rogersef7d42f2014-01-06 12:55:46 -08001299 T* dst = reinterpret_cast<T*>(a->GetRawData(sizeof(T), offset));
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001300 for (int i = 0; i < count; ++i) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001301 *dst++ = src->ReadValue(sizeof(T));
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001302 }
1303}
1304
Elliott Hughes88d63092013-01-09 09:55:54 -08001305JDWP::JdwpError Dbg::SetArrayElements(JDWP::ObjectId array_id, int offset, int count,
Ian Rogersc0542af2014-09-03 16:16:56 -07001306 JDWP::Request* request) {
1307 JDWP::JdwpError error;
1308 mirror::Array* dst = DecodeNonNullArray(array_id, &error);
1309 if (dst == nullptr) {
1310 return error;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001311 }
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001312
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001313 if (offset < 0 || count < 0 || offset > dst->GetLength() || dst->GetLength() - offset < count) {
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001314 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001315 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001316 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07001317 JDWP::JdwpTag element_tag = BasicTagFromClass(dst->GetClass()->GetComponentType());
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001318
Ian Rogers1ff3c982014-08-12 02:30:58 -07001319 if (IsPrimitiveTag(element_tag)) {
1320 size_t width = GetTagWidth(element_tag);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001321 if (width == 8) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001322 CopyArrayData<uint64_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001323 } else if (width == 4) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001324 CopyArrayData<uint32_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001325 } else if (width == 2) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001326 CopyArrayData<uint16_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001327 } else {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001328 CopyArrayData<uint8_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001329 }
1330 } else {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001331 mirror::ObjectArray<mirror::Object>* oa = dst->AsObjectArray<mirror::Object>();
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001332 for (int i = 0; i < count; ++i) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001333 JDWP::ObjectId id = request->ReadObjectId();
Ian Rogersc0542af2014-09-03 16:16:56 -07001334 mirror::Object* o = gRegistry->Get<mirror::Object*>(id, &error);
1335 if (error != JDWP::ERR_NONE) {
1336 return error;
Elliott Hughes436e3722012-02-17 20:01:47 -08001337 }
Sebastien Hertz2e1c16d2015-08-28 11:57:49 +02001338 // Check if the object's type is compatible with the array's type.
1339 if (o != nullptr && !o->InstanceOf(oa->GetClass()->GetComponentType())) {
1340 return JDWP::ERR_TYPE_MISMATCH;
1341 }
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001342 oa->Set<false>(offset + i, o);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001343 }
1344 }
1345
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001346 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001347}
1348
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001349JDWP::JdwpError Dbg::CreateString(const std::string& str, JDWP::ObjectId* new_string_id) {
1350 Thread* self = Thread::Current();
1351 mirror::String* new_string = mirror::String::AllocFromModifiedUtf8(self, str.c_str());
1352 if (new_string == nullptr) {
1353 DCHECK(self->IsExceptionPending());
1354 self->ClearException();
1355 LOG(ERROR) << "Could not allocate string";
1356 *new_string_id = 0;
1357 return JDWP::ERR_OUT_OF_MEMORY;
1358 }
1359 *new_string_id = gRegistry->Add(new_string);
1360 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001361}
1362
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001363JDWP::JdwpError Dbg::CreateObject(JDWP::RefTypeId class_id, JDWP::ObjectId* new_object_id) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001364 JDWP::JdwpError error;
1365 mirror::Class* c = DecodeClass(class_id, &error);
1366 if (c == nullptr) {
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001367 *new_object_id = 0;
Ian Rogersc0542af2014-09-03 16:16:56 -07001368 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001369 }
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001370 Thread* self = Thread::Current();
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001371 ObjPtr<mirror::Object> new_object;
Sebastien Hertz56d5e502015-11-03 17:38:35 +01001372 if (c->IsStringClass()) {
1373 // Special case for java.lang.String.
1374 gc::AllocatorType allocator_type = Runtime::Current()->GetHeap()->GetCurrentAllocator();
jessicahandojo3aaa37b2016-07-29 14:46:37 -07001375 new_object = mirror::String::AllocEmptyString<true>(self, allocator_type);
Sebastien Hertz56d5e502015-11-03 17:38:35 +01001376 } else {
1377 new_object = c->AllocObject(self);
1378 }
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001379 if (new_object == nullptr) {
1380 DCHECK(self->IsExceptionPending());
1381 self->ClearException();
David Sehr709b0702016-10-13 09:12:37 -07001382 LOG(ERROR) << "Could not allocate object of type " << mirror::Class::PrettyDescriptor(c);
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001383 *new_object_id = 0;
1384 return JDWP::ERR_OUT_OF_MEMORY;
1385 }
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001386 *new_object_id = gRegistry->Add(new_object.Ptr());
Elliott Hughes436e3722012-02-17 20:01:47 -08001387 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001388}
1389
Elliott Hughesbf13d362011-12-08 15:51:37 -08001390/*
1391 * Used by Eclipse's "Display" view to evaluate "new byte[5]" to get "(byte[]) [0, 0, 0, 0, 0]".
1392 */
Elliott Hughes88d63092013-01-09 09:55:54 -08001393JDWP::JdwpError Dbg::CreateArrayObject(JDWP::RefTypeId array_class_id, uint32_t length,
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001394 JDWP::ObjectId* new_array_id) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001395 JDWP::JdwpError error;
1396 mirror::Class* c = DecodeClass(array_class_id, &error);
1397 if (c == nullptr) {
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001398 *new_array_id = 0;
Ian Rogersc0542af2014-09-03 16:16:56 -07001399 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001400 }
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001401 Thread* self = Thread::Current();
1402 gc::Heap* heap = Runtime::Current()->GetHeap();
1403 mirror::Array* new_array = mirror::Array::Alloc<true>(self, c, length,
1404 c->GetComponentSizeShift(),
1405 heap->GetCurrentAllocator());
1406 if (new_array == nullptr) {
1407 DCHECK(self->IsExceptionPending());
1408 self->ClearException();
David Sehr709b0702016-10-13 09:12:37 -07001409 LOG(ERROR) << "Could not allocate array of type " << mirror::Class::PrettyDescriptor(c);
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001410 *new_array_id = 0;
1411 return JDWP::ERR_OUT_OF_MEMORY;
1412 }
1413 *new_array_id = gRegistry->Add(new_array);
Elliott Hughes436e3722012-02-17 20:01:47 -08001414 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001415}
1416
Mathieu Chartierc7853442015-03-27 14:35:38 -07001417JDWP::FieldId Dbg::ToFieldId(const ArtField* f) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001418 return static_cast<JDWP::FieldId>(reinterpret_cast<uintptr_t>(f));
Elliott Hughes03181a82011-11-17 17:22:21 -08001419}
1420
Alex Light6c8467f2015-11-20 15:03:26 -08001421static JDWP::MethodId ToMethodId(ArtMethod* m)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001422 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light97e78032017-06-27 17:51:55 -07001423 return static_cast<JDWP::MethodId>(
1424 reinterpret_cast<uintptr_t>(m->GetCanonicalMethod(kRuntimePointerSize)));
Elliott Hughes03181a82011-11-17 17:22:21 -08001425}
1426
Mathieu Chartierc7853442015-03-27 14:35:38 -07001427static ArtField* FromFieldId(JDWP::FieldId fid)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001428 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001429 return reinterpret_cast<ArtField*>(static_cast<uintptr_t>(fid));
Elliott Hughesaed4be92011-12-02 16:16:23 -08001430}
1431
Mathieu Chartiere401d142015-04-22 13:56:20 -07001432static ArtMethod* FromMethodId(JDWP::MethodId mid)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001433 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001434 return reinterpret_cast<ArtMethod*>(static_cast<uintptr_t>(mid));
Elliott Hughes03181a82011-11-17 17:22:21 -08001435}
1436
Sebastien Hertz6995c602014-09-09 12:10:13 +02001437bool Dbg::MatchThread(JDWP::ObjectId expected_thread_id, Thread* event_thread) {
1438 CHECK(event_thread != nullptr);
1439 JDWP::JdwpError error;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001440 mirror::Object* expected_thread_peer = gRegistry->Get<mirror::Object*>(
1441 expected_thread_id, &error);
Nicolas Geoffraycafa0812017-02-15 18:27:34 +00001442 return expected_thread_peer == event_thread->GetPeerFromOtherThread();
Sebastien Hertz6995c602014-09-09 12:10:13 +02001443}
1444
1445bool Dbg::MatchLocation(const JDWP::JdwpLocation& expected_location,
1446 const JDWP::EventLocation& event_location) {
1447 if (expected_location.dex_pc != event_location.dex_pc) {
1448 return false;
1449 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001450 ArtMethod* m = FromMethodId(expected_location.method_id);
Sebastien Hertz6995c602014-09-09 12:10:13 +02001451 return m == event_location.method;
1452}
1453
Mathieu Chartier3398c782016-09-30 10:27:43 -07001454bool Dbg::MatchType(ObjPtr<mirror::Class> event_class, JDWP::RefTypeId class_id) {
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001455 if (event_class == nullptr) {
1456 return false;
1457 }
Sebastien Hertz6995c602014-09-09 12:10:13 +02001458 JDWP::JdwpError error;
Mathieu Chartier3398c782016-09-30 10:27:43 -07001459 ObjPtr<mirror::Class> expected_class = DecodeClass(class_id, &error);
Sebastien Hertz6995c602014-09-09 12:10:13 +02001460 CHECK(expected_class != nullptr);
1461 return expected_class->IsAssignableFrom(event_class);
1462}
1463
1464bool Dbg::MatchField(JDWP::RefTypeId expected_type_id, JDWP::FieldId expected_field_id,
Mathieu Chartierc7853442015-03-27 14:35:38 -07001465 ArtField* event_field) {
1466 ArtField* expected_field = FromFieldId(expected_field_id);
Sebastien Hertz6995c602014-09-09 12:10:13 +02001467 if (expected_field != event_field) {
1468 return false;
1469 }
1470 return Dbg::MatchType(event_field->GetDeclaringClass(), expected_type_id);
1471}
1472
1473bool Dbg::MatchInstance(JDWP::ObjectId expected_instance_id, mirror::Object* event_instance) {
1474 JDWP::JdwpError error;
1475 mirror::Object* modifier_instance = gRegistry->Get<mirror::Object*>(expected_instance_id, &error);
1476 return modifier_instance == event_instance;
1477}
1478
Mathieu Chartier90443472015-07-16 20:32:27 -07001479void Dbg::SetJdwpLocation(JDWP::JdwpLocation* location, ArtMethod* m, uint32_t dex_pc) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001480 if (m == nullptr) {
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001481 memset(location, 0, sizeof(*location));
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001482 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001483 mirror::Class* c = m->GetDeclaringClass();
Ian Rogersc0542af2014-09-03 16:16:56 -07001484 location->type_tag = GetTypeTag(c);
1485 location->class_id = gRegistry->AddRefType(c);
Alex Light73376312017-04-06 10:10:51 -07001486 // The RI Seems to return 0 for all obsolete methods. For compatibility we shall do the same.
1487 location->method_id = m->IsObsolete() ? 0 : ToMethodId(m);
Ian Rogersc0542af2014-09-03 16:16:56 -07001488 location->dex_pc = (m->IsNative() || m->IsProxyMethod()) ? static_cast<uint64_t>(-1) : dex_pc;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001489 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08001490}
1491
Ian Rogersc0542af2014-09-03 16:16:56 -07001492std::string Dbg::GetMethodName(JDWP::MethodId method_id) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001493 ArtMethod* m = FromMethodId(method_id);
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001494 if (m == nullptr) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001495 return "null";
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001496 }
Andreas Gampe542451c2016-07-26 09:02:02 -07001497 return m->GetInterfaceMethodIfProxy(kRuntimePointerSize)->GetName();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001498}
1499
Alex Light73376312017-04-06 10:10:51 -07001500bool Dbg::IsMethodObsolete(JDWP::MethodId method_id) {
1501 ArtMethod* m = FromMethodId(method_id);
1502 if (m == nullptr) {
1503 // NB Since we return 0 as MID for obsolete methods we want to default to true here.
1504 return true;
1505 }
1506 return m->IsObsolete();
1507}
1508
Ian Rogersc0542af2014-09-03 16:16:56 -07001509std::string Dbg::GetFieldName(JDWP::FieldId field_id) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001510 ArtField* f = FromFieldId(field_id);
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001511 if (f == nullptr) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001512 return "null";
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001513 }
1514 return f->GetName();
Elliott Hughesa96836a2013-01-17 12:27:49 -08001515}
1516
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001517/*
1518 * Augment the access flags for synthetic methods and fields by setting
1519 * the (as described by the spec) "0xf0000000 bit". Also, strip out any
1520 * flags not specified by the Java programming language.
1521 */
1522static uint32_t MangleAccessFlags(uint32_t accessFlags) {
1523 accessFlags &= kAccJavaFlagsMask;
1524 if ((accessFlags & kAccSynthetic) != 0) {
1525 accessFlags |= 0xf0000000;
1526 }
1527 return accessFlags;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001528}
1529
Elliott Hughesdbb40792011-11-18 17:05:22 -08001530/*
Jeff Haob7cefc72013-11-14 14:51:09 -08001531 * Circularly shifts registers so that arguments come first. Debuggers
1532 * expect slots to begin with arguments, but dex code places them at
1533 * the end.
Elliott Hughesdbb40792011-11-18 17:05:22 -08001534 */
Mathieu Chartiere401d142015-04-22 13:56:20 -07001535static uint16_t MangleSlot(uint16_t slot, ArtMethod* m)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001536 REQUIRES_SHARED(Locks::mutator_lock_) {
David Sehr0225f8e2018-01-31 08:52:24 +00001537 CodeItemDataAccessor accessor(m->DexInstructionData());
Mathieu Chartier808c7a52017-12-15 11:19:33 -08001538 if (!accessor.HasCodeItem()) {
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001539 // We should not get here for a method without code (native, proxy or abstract). Log it and
1540 // return the slot as is since all registers are arguments.
David Sehr709b0702016-10-13 09:12:37 -07001541 LOG(WARNING) << "Trying to mangle slot for method without code " << m->PrettyMethod();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001542 return slot;
1543 }
Mathieu Chartier808c7a52017-12-15 11:19:33 -08001544 uint16_t ins_size = accessor.InsSize();
1545 uint16_t locals_size = accessor.RegistersSize() - ins_size;
Jeff Haob7cefc72013-11-14 14:51:09 -08001546 if (slot >= locals_size) {
1547 return slot - locals_size;
1548 } else {
1549 return slot + ins_size;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001550 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001551}
1552
Sebastien Hertzaef0c912016-08-08 10:20:28 +02001553static size_t GetMethodNumArgRegistersIncludingThis(ArtMethod* method)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001554 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertzaef0c912016-08-08 10:20:28 +02001555 uint32_t num_registers = ArtMethod::NumArgRegisters(method->GetShorty());
1556 if (!method->IsStatic()) {
1557 ++num_registers;
1558 }
1559 return num_registers;
1560}
1561
Jeff Haob7cefc72013-11-14 14:51:09 -08001562/*
1563 * Circularly shifts registers so that arguments come last. Reverts
1564 * slots to dex style argument placement.
1565 */
Mathieu Chartiere401d142015-04-22 13:56:20 -07001566static uint16_t DemangleSlot(uint16_t slot, ArtMethod* m, JDWP::JdwpError* error)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001567 REQUIRES_SHARED(Locks::mutator_lock_) {
David Sehr0225f8e2018-01-31 08:52:24 +00001568 CodeItemDataAccessor accessor(m->DexInstructionData());
Mathieu Chartier808c7a52017-12-15 11:19:33 -08001569 if (!accessor.HasCodeItem()) {
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001570 // We should not get here for a method without code (native, proxy or abstract). Log it and
1571 // return the slot as is since all registers are arguments.
David Sehr709b0702016-10-13 09:12:37 -07001572 LOG(WARNING) << "Trying to demangle slot for method without code "
1573 << m->PrettyMethod();
Sebastien Hertzaef0c912016-08-08 10:20:28 +02001574 uint16_t vreg_count = GetMethodNumArgRegistersIncludingThis(m);
Sebastien Hertzabbabc82015-03-26 08:47:47 +01001575 if (slot < vreg_count) {
1576 *error = JDWP::ERR_NONE;
1577 return slot;
1578 }
Jeff Haob7cefc72013-11-14 14:51:09 -08001579 } else {
Mathieu Chartier808c7a52017-12-15 11:19:33 -08001580 if (slot < accessor.RegistersSize()) {
1581 uint16_t ins_size = accessor.InsSize();
1582 uint16_t locals_size = accessor.RegistersSize() - ins_size;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01001583 *error = JDWP::ERR_NONE;
1584 return (slot < ins_size) ? slot + locals_size : slot - ins_size;
1585 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001586 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01001587
1588 // Slot is invalid in the method.
David Sehr709b0702016-10-13 09:12:37 -07001589 LOG(ERROR) << "Invalid local slot " << slot << " for method " << m->PrettyMethod();
Sebastien Hertzabbabc82015-03-26 08:47:47 +01001590 *error = JDWP::ERR_INVALID_SLOT;
1591 return DexFile::kDexNoIndex16;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001592}
1593
Mathieu Chartier90443472015-07-16 20:32:27 -07001594JDWP::JdwpError Dbg::OutputDeclaredFields(JDWP::RefTypeId class_id, bool with_generic,
1595 JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001596 JDWP::JdwpError error;
1597 mirror::Class* c = DecodeClass(class_id, &error);
1598 if (c == nullptr) {
1599 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001600 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001601
1602 size_t instance_field_count = c->NumInstanceFields();
1603 size_t static_field_count = c->NumStaticFields();
1604
1605 expandBufAdd4BE(pReply, instance_field_count + static_field_count);
1606
1607 for (size_t i = 0; i < instance_field_count + static_field_count; ++i) {
Mathieu Chartier90443472015-07-16 20:32:27 -07001608 ArtField* f = (i < instance_field_count) ? c->GetInstanceField(i) :
1609 c->GetStaticField(i - instance_field_count);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001610 expandBufAddFieldId(pReply, ToFieldId(f));
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001611 expandBufAddUtf8String(pReply, f->GetName());
1612 expandBufAddUtf8String(pReply, f->GetTypeDescriptor());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001613 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001614 static const char genericSignature[1] = "";
1615 expandBufAddUtf8String(pReply, genericSignature);
1616 }
1617 expandBufAdd4BE(pReply, MangleAccessFlags(f->GetAccessFlags()));
1618 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001619 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001620}
1621
Elliott Hughes88d63092013-01-09 09:55:54 -08001622JDWP::JdwpError Dbg::OutputDeclaredMethods(JDWP::RefTypeId class_id, bool with_generic,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001623 JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001624 JDWP::JdwpError error;
1625 mirror::Class* c = DecodeClass(class_id, &error);
1626 if (c == nullptr) {
1627 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001628 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001629
Alex Light51a64d52015-12-17 13:55:59 -08001630 expandBufAdd4BE(pReply, c->NumMethods());
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001631
Mathieu Chartiere401d142015-04-22 13:56:20 -07001632 auto* cl = Runtime::Current()->GetClassLinker();
1633 auto ptr_size = cl->GetImagePointerSize();
Alex Light51a64d52015-12-17 13:55:59 -08001634 for (ArtMethod& m : c->GetMethods(ptr_size)) {
1635 expandBufAddMethodId(pReply, ToMethodId(&m));
Andreas Gampe542451c2016-07-26 09:02:02 -07001636 expandBufAddUtf8String(pReply, m.GetInterfaceMethodIfProxy(kRuntimePointerSize)->GetName());
1637 expandBufAddUtf8String(
1638 pReply, m.GetInterfaceMethodIfProxy(kRuntimePointerSize)->GetSignature().ToString());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001639 if (with_generic) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001640 const char* generic_signature = "";
1641 expandBufAddUtf8String(pReply, generic_signature);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001642 }
Alex Light51a64d52015-12-17 13:55:59 -08001643 expandBufAdd4BE(pReply, MangleAccessFlags(m.GetAccessFlags()));
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001644 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001645 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001646}
1647
Elliott Hughes88d63092013-01-09 09:55:54 -08001648JDWP::JdwpError Dbg::OutputDeclaredInterfaces(JDWP::RefTypeId class_id, JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001649 JDWP::JdwpError error;
Mathieu Chartierf8322842014-05-16 10:59:25 -07001650 Thread* self = Thread::Current();
Vladimir Marko19a4d372016-12-08 14:41:46 +00001651 ObjPtr<mirror::Class> c = DecodeClass(class_id, &error);
1652 if (c == nullptr) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001653 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001654 }
Mathieu Chartierf8322842014-05-16 10:59:25 -07001655 size_t interface_count = c->NumDirectInterfaces();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001656 expandBufAdd4BE(pReply, interface_count);
1657 for (size_t i = 0; i < interface_count; ++i) {
Vladimir Marko19a4d372016-12-08 14:41:46 +00001658 ObjPtr<mirror::Class> interface = mirror::Class::GetDirectInterface(self, c, i);
1659 DCHECK(interface != nullptr);
1660 expandBufAddRefTypeId(pReply, gRegistry->AddRefType(interface));
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001661 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001662 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001663}
1664
Ian Rogersc0542af2014-09-03 16:16:56 -07001665void Dbg::OutputLineTable(JDWP::RefTypeId, JDWP::MethodId method_id, JDWP::ExpandBuf* pReply) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001666 struct DebugCallbackContext {
1667 int numItems;
1668 JDWP::ExpandBuf* pReply;
1669
David Srbeckyb06e28e2015-12-10 13:15:00 +00001670 static bool Callback(void* context, const DexFile::PositionInfo& entry) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001671 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
David Srbeckyb06e28e2015-12-10 13:15:00 +00001672 expandBufAdd8BE(pContext->pReply, entry.address_);
1673 expandBufAdd4BE(pContext->pReply, entry.line_);
Elliott Hughes03181a82011-11-17 17:22:21 -08001674 pContext->numItems++;
Sebastien Hertzf2910ee2013-10-19 16:39:24 +02001675 return false;
Elliott Hughes03181a82011-11-17 17:22:21 -08001676 }
1677 };
Mathieu Chartiere401d142015-04-22 13:56:20 -07001678 ArtMethod* m = FromMethodId(method_id);
David Sehr0225f8e2018-01-31 08:52:24 +00001679 CodeItemDebugInfoAccessor accessor(m->DexInstructionDebugInfo());
Elliott Hughes03181a82011-11-17 17:22:21 -08001680 uint64_t start, end;
Mathieu Chartier31f4c9f2017-12-08 15:46:11 -08001681 if (!accessor.HasCodeItem()) {
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001682 DCHECK(m->IsNative() || m->IsProxyMethod());
Elliott Hughes03181a82011-11-17 17:22:21 -08001683 start = -1;
1684 end = -1;
1685 } else {
1686 start = 0;
jeffhao14f0db92012-12-14 17:50:42 -08001687 // Return the index of the last instruction
Mathieu Chartier31f4c9f2017-12-08 15:46:11 -08001688 end = accessor.InsnsSizeInCodeUnits() - 1;
Elliott Hughes03181a82011-11-17 17:22:21 -08001689 }
1690
1691 expandBufAdd8BE(pReply, start);
1692 expandBufAdd8BE(pReply, end);
1693
1694 // Add numLines later
1695 size_t numLinesOffset = expandBufGetLength(pReply);
1696 expandBufAdd4BE(pReply, 0);
1697
1698 DebugCallbackContext context;
1699 context.numItems = 0;
1700 context.pReply = pReply;
1701
Mathieu Chartier31f4c9f2017-12-08 15:46:11 -08001702 if (accessor.HasCodeItem()) {
1703 m->GetDexFile()->DecodeDebugPositionInfo(accessor.DebugInfoOffset(),
1704 DebugCallbackContext::Callback,
1705 &context);
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001706 }
Elliott Hughes03181a82011-11-17 17:22:21 -08001707
1708 JDWP::Set4BE(expandBufGetBuffer(pReply) + numLinesOffset, context.numItems);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001709}
1710
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001711void Dbg::OutputVariableTable(JDWP::RefTypeId, JDWP::MethodId method_id, bool with_generic,
1712 JDWP::ExpandBuf* pReply) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001713 struct DebugCallbackContext {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001714 ArtMethod* method;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001715 JDWP::ExpandBuf* pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001716 size_t variable_count;
1717 bool with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001718
David Srbeckyb06e28e2015-12-10 13:15:00 +00001719 static void Callback(void* context, const DexFile::LocalInfo& entry)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001720 REQUIRES_SHARED(Locks::mutator_lock_) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001721 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
1722
David Srbeckyb06e28e2015-12-10 13:15:00 +00001723 uint16_t slot = entry.reg_;
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001724 VLOG(jdwp) << StringPrintf(" %2zd: %d(%d) '%s' '%s' '%s' actual slot=%d mangled slot=%d",
David Srbeckyb06e28e2015-12-10 13:15:00 +00001725 pContext->variable_count, entry.start_address_,
1726 entry.end_address_ - entry.start_address_,
1727 entry.name_, entry.descriptor_, entry.signature_, slot,
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001728 MangleSlot(slot, pContext->method));
Elliott Hughesdbb40792011-11-18 17:05:22 -08001729
Jeff Haob7cefc72013-11-14 14:51:09 -08001730 slot = MangleSlot(slot, pContext->method);
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001731
David Srbeckyb06e28e2015-12-10 13:15:00 +00001732 expandBufAdd8BE(pContext->pReply, entry.start_address_);
1733 expandBufAddUtf8String(pContext->pReply, entry.name_);
1734 expandBufAddUtf8String(pContext->pReply, entry.descriptor_);
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001735 if (pContext->with_generic) {
David Srbeckyb06e28e2015-12-10 13:15:00 +00001736 expandBufAddUtf8String(pContext->pReply, entry.signature_);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001737 }
David Srbeckyb06e28e2015-12-10 13:15:00 +00001738 expandBufAdd4BE(pContext->pReply, entry.end_address_- entry.start_address_);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001739 expandBufAdd4BE(pContext->pReply, slot);
1740
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001741 ++pContext->variable_count;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001742 }
1743 };
Mathieu Chartiere401d142015-04-22 13:56:20 -07001744 ArtMethod* m = FromMethodId(method_id);
David Sehr0225f8e2018-01-31 08:52:24 +00001745 CodeItemDebugInfoAccessor accessor(m->DexInstructionDebugInfo());
Elliott Hughesdbb40792011-11-18 17:05:22 -08001746
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001747 // arg_count considers doubles and longs to take 2 units.
1748 // variable_count considers everything to take 1 unit.
Sebastien Hertzaef0c912016-08-08 10:20:28 +02001749 expandBufAdd4BE(pReply, GetMethodNumArgRegistersIncludingThis(m));
Elliott Hughesdbb40792011-11-18 17:05:22 -08001750
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001751 // We don't know the total number of variables yet, so leave a blank and update it later.
1752 size_t variable_count_offset = expandBufGetLength(pReply);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001753 expandBufAdd4BE(pReply, 0);
1754
1755 DebugCallbackContext context;
Jeff Haob7cefc72013-11-14 14:51:09 -08001756 context.method = m;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001757 context.pReply = pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001758 context.variable_count = 0;
1759 context.with_generic = with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001760
Mathieu Chartier31f4c9f2017-12-08 15:46:11 -08001761 if (accessor.HasCodeItem()) {
1762 m->GetDexFile()->DecodeDebugLocalInfo(accessor.RegistersSize(),
1763 accessor.InsSize(),
1764 accessor.InsnsSizeInCodeUnits(),
1765 accessor.DebugInfoOffset(),
1766 m->IsStatic(),
1767 m->GetDexMethodIndex(),
1768 DebugCallbackContext::Callback,
1769 &context);
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001770 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001771
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001772 JDWP::Set4BE(expandBufGetBuffer(pReply) + variable_count_offset, context.variable_count);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001773}
1774
Jeff Hao579b0242013-11-18 13:16:49 -08001775void Dbg::OutputMethodReturnValue(JDWP::MethodId method_id, const JValue* return_value,
1776 JDWP::ExpandBuf* pReply) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001777 ArtMethod* m = FromMethodId(method_id);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001778 JDWP::JdwpTag tag = BasicTagFromDescriptor(m->GetShorty());
Jeff Hao579b0242013-11-18 13:16:49 -08001779 OutputJValue(tag, return_value, pReply);
1780}
1781
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02001782void Dbg::OutputFieldValue(JDWP::FieldId field_id, const JValue* field_value,
1783 JDWP::ExpandBuf* pReply) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001784 ArtField* f = FromFieldId(field_id);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001785 JDWP::JdwpTag tag = BasicTagFromDescriptor(f->GetTypeDescriptor());
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02001786 OutputJValue(tag, field_value, pReply);
1787}
1788
Elliott Hughes9777ba22013-01-17 09:04:19 -08001789JDWP::JdwpError Dbg::GetBytecodes(JDWP::RefTypeId, JDWP::MethodId method_id,
Ian Rogersc0542af2014-09-03 16:16:56 -07001790 std::vector<uint8_t>* bytecodes) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001791 ArtMethod* m = FromMethodId(method_id);
Ian Rogersc0542af2014-09-03 16:16:56 -07001792 if (m == nullptr) {
Elliott Hughes9777ba22013-01-17 09:04:19 -08001793 return JDWP::ERR_INVALID_METHODID;
1794 }
David Sehr0225f8e2018-01-31 08:52:24 +00001795 CodeItemDataAccessor accessor(m->DexInstructionData());
Mathieu Chartier808c7a52017-12-15 11:19:33 -08001796 size_t byte_count = accessor.InsnsSizeInCodeUnits() * 2;
1797 const uint8_t* begin = reinterpret_cast<const uint8_t*>(accessor.Insns());
Elliott Hughes9777ba22013-01-17 09:04:19 -08001798 const uint8_t* end = begin + byte_count;
1799 for (const uint8_t* p = begin; p != end; ++p) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001800 bytecodes->push_back(*p);
Elliott Hughes9777ba22013-01-17 09:04:19 -08001801 }
1802 return JDWP::ERR_NONE;
1803}
1804
Elliott Hughes88d63092013-01-09 09:55:54 -08001805JDWP::JdwpTag Dbg::GetFieldBasicTag(JDWP::FieldId field_id) {
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001806 return BasicTagFromDescriptor(FromFieldId(field_id)->GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001807}
1808
Elliott Hughes88d63092013-01-09 09:55:54 -08001809JDWP::JdwpTag Dbg::GetStaticFieldBasicTag(JDWP::FieldId field_id) {
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001810 return BasicTagFromDescriptor(FromFieldId(field_id)->GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001811}
1812
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001813static JValue GetArtFieldValue(ArtField* f, mirror::Object* o)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001814 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001815 Primitive::Type fieldType = f->GetTypeAsPrimitiveType();
1816 JValue field_value;
1817 switch (fieldType) {
1818 case Primitive::kPrimBoolean:
1819 field_value.SetZ(f->GetBoolean(o));
1820 return field_value;
1821
1822 case Primitive::kPrimByte:
1823 field_value.SetB(f->GetByte(o));
1824 return field_value;
1825
1826 case Primitive::kPrimChar:
1827 field_value.SetC(f->GetChar(o));
1828 return field_value;
1829
1830 case Primitive::kPrimShort:
1831 field_value.SetS(f->GetShort(o));
1832 return field_value;
1833
1834 case Primitive::kPrimInt:
1835 case Primitive::kPrimFloat:
1836 // Int and Float must be treated as 32-bit values in JDWP.
1837 field_value.SetI(f->GetInt(o));
1838 return field_value;
1839
1840 case Primitive::kPrimLong:
1841 case Primitive::kPrimDouble:
1842 // Long and Double must be treated as 64-bit values in JDWP.
1843 field_value.SetJ(f->GetLong(o));
1844 return field_value;
1845
1846 case Primitive::kPrimNot:
Mathieu Chartier1cc62e42016-10-03 18:01:28 -07001847 field_value.SetL(f->GetObject(o).Ptr());
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001848 return field_value;
1849
1850 case Primitive::kPrimVoid:
1851 LOG(FATAL) << "Attempt to read from field of type 'void'";
1852 UNREACHABLE();
1853 }
1854 LOG(FATAL) << "Attempt to read from field of unknown type";
1855 UNREACHABLE();
1856}
1857
Elliott Hughes88d63092013-01-09 09:55:54 -08001858static JDWP::JdwpError GetFieldValueImpl(JDWP::RefTypeId ref_type_id, JDWP::ObjectId object_id,
1859 JDWP::FieldId field_id, JDWP::ExpandBuf* pReply,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001860 bool is_static)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001861 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001862 JDWP::JdwpError error;
1863 mirror::Class* c = DecodeClass(ref_type_id, &error);
1864 if (ref_type_id != 0 && c == nullptr) {
1865 return error;
Elliott Hughes0cf74332012-02-23 23:14:00 -08001866 }
1867
Jeff Haode19a252016-09-14 15:56:35 -07001868 Thread* self = Thread::Current();
1869 StackHandleScope<2> hs(self);
1870 MutableHandle<mirror::Object>
1871 o(hs.NewHandle(Dbg::GetObjectRegistry()->Get<mirror::Object*>(object_id, &error)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08001872 if ((!is_static && o == nullptr) || error != JDWP::ERR_NONE) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001873 return JDWP::ERR_INVALID_OBJECT;
1874 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001875 ArtField* f = FromFieldId(field_id);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001876
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001877 mirror::Class* receiver_class = c;
Andreas Gampefa4333d2017-02-14 11:10:34 -08001878 if (receiver_class == nullptr && o != nullptr) {
Elliott Hughes0cf74332012-02-23 23:14:00 -08001879 receiver_class = o->GetClass();
1880 }
Jeff Haode19a252016-09-14 15:56:35 -07001881
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001882 // TODO: should we give up now if receiver_class is null?
Ian Rogersc0542af2014-09-03 16:16:56 -07001883 if (receiver_class != nullptr && !f->GetDeclaringClass()->IsAssignableFrom(receiver_class)) {
David Sehr709b0702016-10-13 09:12:37 -07001884 LOG(INFO) << "ERR_INVALID_FIELDID: " << f->PrettyField() << " "
1885 << receiver_class->PrettyClass();
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001886 return JDWP::ERR_INVALID_FIELDID;
1887 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001888
Jeff Haode19a252016-09-14 15:56:35 -07001889 // Ensure the field's class is initialized.
1890 Handle<mirror::Class> klass(hs.NewHandle(f->GetDeclaringClass()));
1891 if (!Runtime::Current()->GetClassLinker()->EnsureInitialized(self, klass, true, false)) {
David Sehr709b0702016-10-13 09:12:37 -07001892 LOG(WARNING) << "Not able to initialize class for SetValues: "
1893 << mirror::Class::PrettyClass(klass.Get());
Jeff Haode19a252016-09-14 15:56:35 -07001894 }
1895
Elliott Hughes0cf74332012-02-23 23:14:00 -08001896 // The RI only enforces the static/non-static mismatch in one direction.
1897 // TODO: should we change the tests and check both?
1898 if (is_static) {
1899 if (!f->IsStatic()) {
1900 return JDWP::ERR_INVALID_FIELDID;
1901 }
1902 } else {
1903 if (f->IsStatic()) {
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001904 LOG(WARNING) << "Ignoring non-nullptr receiver for ObjectReference.GetValues"
David Sehr709b0702016-10-13 09:12:37 -07001905 << " on static field " << f->PrettyField();
Elliott Hughes0cf74332012-02-23 23:14:00 -08001906 }
1907 }
jeffhao0dfbb7e2012-11-28 15:26:03 -08001908 if (f->IsStatic()) {
Jeff Haode19a252016-09-14 15:56:35 -07001909 o.Assign(f->GetDeclaringClass());
jeffhao0dfbb7e2012-11-28 15:26:03 -08001910 }
Elliott Hughes0cf74332012-02-23 23:14:00 -08001911
Jeff Haode19a252016-09-14 15:56:35 -07001912 JValue field_value(GetArtFieldValue(f, o.Get()));
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001913 JDWP::JdwpTag tag = BasicTagFromDescriptor(f->GetTypeDescriptor());
Jeff Hao579b0242013-11-18 13:16:49 -08001914 Dbg::OutputJValue(tag, &field_value, pReply);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001915 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001916}
1917
Elliott Hughes88d63092013-01-09 09:55:54 -08001918JDWP::JdwpError Dbg::GetFieldValue(JDWP::ObjectId object_id, JDWP::FieldId field_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001919 JDWP::ExpandBuf* pReply) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001920 return GetFieldValueImpl(0, object_id, field_id, pReply, false);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001921}
1922
Ian Rogersc0542af2014-09-03 16:16:56 -07001923JDWP::JdwpError Dbg::GetStaticFieldValue(JDWP::RefTypeId ref_type_id, JDWP::FieldId field_id,
1924 JDWP::ExpandBuf* pReply) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001925 return GetFieldValueImpl(ref_type_id, 0, field_id, pReply, true);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001926}
1927
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001928static JDWP::JdwpError SetArtFieldValue(ArtField* f, mirror::Object* o, uint64_t value, int width)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001929 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001930 Primitive::Type fieldType = f->GetTypeAsPrimitiveType();
1931 // Debugging only happens at runtime so we know we are not running in a transaction.
1932 static constexpr bool kNoTransactionMode = false;
1933 switch (fieldType) {
1934 case Primitive::kPrimBoolean:
1935 CHECK_EQ(width, 1);
1936 f->SetBoolean<kNoTransactionMode>(o, static_cast<uint8_t>(value));
1937 return JDWP::ERR_NONE;
1938
1939 case Primitive::kPrimByte:
1940 CHECK_EQ(width, 1);
1941 f->SetByte<kNoTransactionMode>(o, static_cast<uint8_t>(value));
1942 return JDWP::ERR_NONE;
1943
1944 case Primitive::kPrimChar:
1945 CHECK_EQ(width, 2);
1946 f->SetChar<kNoTransactionMode>(o, static_cast<uint16_t>(value));
1947 return JDWP::ERR_NONE;
1948
1949 case Primitive::kPrimShort:
1950 CHECK_EQ(width, 2);
1951 f->SetShort<kNoTransactionMode>(o, static_cast<int16_t>(value));
1952 return JDWP::ERR_NONE;
1953
1954 case Primitive::kPrimInt:
1955 case Primitive::kPrimFloat:
1956 CHECK_EQ(width, 4);
1957 // Int and Float must be treated as 32-bit values in JDWP.
1958 f->SetInt<kNoTransactionMode>(o, static_cast<int32_t>(value));
1959 return JDWP::ERR_NONE;
1960
1961 case Primitive::kPrimLong:
1962 case Primitive::kPrimDouble:
1963 CHECK_EQ(width, 8);
1964 // Long and Double must be treated as 64-bit values in JDWP.
1965 f->SetLong<kNoTransactionMode>(o, value);
1966 return JDWP::ERR_NONE;
1967
1968 case Primitive::kPrimNot: {
1969 JDWP::JdwpError error;
1970 mirror::Object* v = Dbg::GetObjectRegistry()->Get<mirror::Object*>(value, &error);
1971 if (error != JDWP::ERR_NONE) {
1972 return JDWP::ERR_INVALID_OBJECT;
1973 }
1974 if (v != nullptr) {
Mathieu Chartier3398c782016-09-30 10:27:43 -07001975 ObjPtr<mirror::Class> field_type;
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001976 {
1977 StackHandleScope<2> hs(Thread::Current());
1978 HandleWrapper<mirror::Object> h_v(hs.NewHandleWrapper(&v));
1979 HandleWrapper<mirror::Object> h_o(hs.NewHandleWrapper(&o));
Vladimir Marko4098a7a2017-11-06 16:00:51 +00001980 field_type = f->ResolveType();
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001981 }
1982 if (!field_type->IsAssignableFrom(v->GetClass())) {
1983 return JDWP::ERR_INVALID_OBJECT;
1984 }
1985 }
1986 f->SetObject<kNoTransactionMode>(o, v);
1987 return JDWP::ERR_NONE;
1988 }
1989
1990 case Primitive::kPrimVoid:
1991 LOG(FATAL) << "Attempt to write to field of type 'void'";
1992 UNREACHABLE();
1993 }
1994 LOG(FATAL) << "Attempt to write to field of unknown type";
1995 UNREACHABLE();
1996}
1997
Elliott Hughes88d63092013-01-09 09:55:54 -08001998static JDWP::JdwpError SetFieldValueImpl(JDWP::ObjectId object_id, JDWP::FieldId field_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001999 uint64_t value, int width, bool is_static)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002000 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -07002001 JDWP::JdwpError error;
Jeff Haode19a252016-09-14 15:56:35 -07002002 Thread* self = Thread::Current();
2003 StackHandleScope<2> hs(self);
2004 MutableHandle<mirror::Object>
2005 o(hs.NewHandle(Dbg::GetObjectRegistry()->Get<mirror::Object*>(object_id, &error)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08002006 if ((!is_static && o == nullptr) || error != JDWP::ERR_NONE) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002007 return JDWP::ERR_INVALID_OBJECT;
2008 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07002009 ArtField* f = FromFieldId(field_id);
Elliott Hughes0cf74332012-02-23 23:14:00 -08002010
Jeff Haode19a252016-09-14 15:56:35 -07002011 // Ensure the field's class is initialized.
2012 Handle<mirror::Class> klass(hs.NewHandle(f->GetDeclaringClass()));
2013 if (!Runtime::Current()->GetClassLinker()->EnsureInitialized(self, klass, true, false)) {
David Sehr709b0702016-10-13 09:12:37 -07002014 LOG(WARNING) << "Not able to initialize class for SetValues: "
2015 << mirror::Class::PrettyClass(klass.Get());
Jeff Haode19a252016-09-14 15:56:35 -07002016 }
2017
Elliott Hughes0cf74332012-02-23 23:14:00 -08002018 // The RI only enforces the static/non-static mismatch in one direction.
2019 // TODO: should we change the tests and check both?
2020 if (is_static) {
2021 if (!f->IsStatic()) {
2022 return JDWP::ERR_INVALID_FIELDID;
2023 }
2024 } else {
2025 if (f->IsStatic()) {
Sebastien Hertz05c26b32015-06-11 18:42:58 +02002026 LOG(WARNING) << "Ignoring non-nullptr receiver for ObjectReference.SetValues"
David Sehr709b0702016-10-13 09:12:37 -07002027 << " on static field " << f->PrettyField();
Elliott Hughes0cf74332012-02-23 23:14:00 -08002028 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002029 }
jeffhao0dfbb7e2012-11-28 15:26:03 -08002030 if (f->IsStatic()) {
Jeff Haode19a252016-09-14 15:56:35 -07002031 o.Assign(f->GetDeclaringClass());
jeffhao0dfbb7e2012-11-28 15:26:03 -08002032 }
Jeff Haode19a252016-09-14 15:56:35 -07002033 return SetArtFieldValue(f, o.Get(), value, width);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002034}
2035
Elliott Hughes88d63092013-01-09 09:55:54 -08002036JDWP::JdwpError Dbg::SetFieldValue(JDWP::ObjectId object_id, JDWP::FieldId field_id, uint64_t value,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002037 int width) {
Elliott Hughes88d63092013-01-09 09:55:54 -08002038 return SetFieldValueImpl(object_id, field_id, value, width, false);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002039}
2040
Elliott Hughes88d63092013-01-09 09:55:54 -08002041JDWP::JdwpError Dbg::SetStaticFieldValue(JDWP::FieldId field_id, uint64_t value, int width) {
2042 return SetFieldValueImpl(0, field_id, value, width, true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002043}
2044
Sebastien Hertzb0b0b492014-09-15 11:27:27 +02002045JDWP::JdwpError Dbg::StringToUtf8(JDWP::ObjectId string_id, std::string* str) {
Ian Rogersc0542af2014-09-03 16:16:56 -07002046 JDWP::JdwpError error;
Sebastien Hertzb0b0b492014-09-15 11:27:27 +02002047 mirror::Object* obj = gRegistry->Get<mirror::Object*>(string_id, &error);
2048 if (error != JDWP::ERR_NONE) {
2049 return error;
2050 }
2051 if (obj == nullptr) {
2052 return JDWP::ERR_INVALID_OBJECT;
2053 }
2054 {
2055 ScopedObjectAccessUnchecked soa(Thread::Current());
Mathieu Chartier0795f232016-09-27 18:43:30 -07002056 ObjPtr<mirror::Class> java_lang_String =
2057 soa.Decode<mirror::Class>(WellKnownClasses::java_lang_String);
Sebastien Hertzb0b0b492014-09-15 11:27:27 +02002058 if (!java_lang_String->IsAssignableFrom(obj->GetClass())) {
2059 // This isn't a string.
2060 return JDWP::ERR_INVALID_STRING;
2061 }
2062 }
2063 *str = obj->AsString()->ToModifiedUtf8();
2064 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002065}
2066
Jeff Hao579b0242013-11-18 13:16:49 -08002067void Dbg::OutputJValue(JDWP::JdwpTag tag, const JValue* return_value, JDWP::ExpandBuf* pReply) {
2068 if (IsPrimitiveTag(tag)) {
2069 expandBufAdd1(pReply, tag);
2070 if (tag == JDWP::JT_BOOLEAN || tag == JDWP::JT_BYTE) {
2071 expandBufAdd1(pReply, return_value->GetI());
2072 } else if (tag == JDWP::JT_CHAR || tag == JDWP::JT_SHORT) {
2073 expandBufAdd2BE(pReply, return_value->GetI());
2074 } else if (tag == JDWP::JT_FLOAT || tag == JDWP::JT_INT) {
2075 expandBufAdd4BE(pReply, return_value->GetI());
2076 } else if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
2077 expandBufAdd8BE(pReply, return_value->GetJ());
2078 } else {
2079 CHECK_EQ(tag, JDWP::JT_VOID);
2080 }
2081 } else {
Ian Rogers98379392014-02-24 16:53:16 -08002082 ScopedObjectAccessUnchecked soa(Thread::Current());
Jeff Hao579b0242013-11-18 13:16:49 -08002083 mirror::Object* value = return_value->GetL();
Ian Rogers98379392014-02-24 16:53:16 -08002084 expandBufAdd1(pReply, TagFromObject(soa, value));
Jeff Hao579b0242013-11-18 13:16:49 -08002085 expandBufAddObjectId(pReply, gRegistry->Add(value));
2086 }
2087}
2088
Ian Rogersc0542af2014-09-03 16:16:56 -07002089JDWP::JdwpError Dbg::GetThreadName(JDWP::ObjectId thread_id, std::string* name) {
jeffhaoa77f0f62012-12-05 17:19:31 -08002090 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002091 JDWP::JdwpError error;
Roland Levillain4b8f1ec2015-08-26 18:34:03 +01002092 DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002093 if (error != JDWP::ERR_NONE && error != JDWP::ERR_THREAD_NOT_ALIVE) {
2094 return error;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08002095 }
Elliott Hughes221229c2013-01-08 18:17:50 -08002096
2097 // We still need to report the zombie threads' names, so we can't just call Thread::GetThreadName.
Ian Rogersc0542af2014-09-03 16:16:56 -07002098 mirror::Object* thread_object = gRegistry->Get<mirror::Object*>(thread_id, &error);
2099 CHECK(thread_object != nullptr) << error;
Mathieu Chartierc7853442015-03-27 14:35:38 -07002100 ArtField* java_lang_Thread_name_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08002101 jni::DecodeArtField(WellKnownClasses::java_lang_Thread_name);
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07002102 ObjPtr<mirror::String> s(java_lang_Thread_name_field->GetObject(thread_object)->AsString());
Ian Rogersc0542af2014-09-03 16:16:56 -07002103 if (s != nullptr) {
2104 *name = s->ToModifiedUtf8();
Elliott Hughes221229c2013-01-08 18:17:50 -08002105 }
2106 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002107}
2108
Elliott Hughes221229c2013-01-08 18:17:50 -08002109JDWP::JdwpError Dbg::GetThreadGroup(JDWP::ObjectId thread_id, JDWP::ExpandBuf* pReply) {
Sebastien Hertza06430c2014-09-15 19:21:30 +02002110 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002111 JDWP::JdwpError error;
2112 mirror::Object* thread_object = gRegistry->Get<mirror::Object*>(thread_id, &error);
2113 if (error != JDWP::ERR_NONE) {
Elliott Hughes2435a572012-02-17 16:07:41 -08002114 return JDWP::ERR_INVALID_OBJECT;
2115 }
Mathieu Chartier268764d2016-09-13 12:09:38 -07002116 ScopedAssertNoThreadSuspension ants("Debugger: GetThreadGroup");
Elliott Hughes2435a572012-02-17 16:07:41 -08002117 // Okay, so it's an object, but is it actually a thread?
Roland Levillain4b8f1ec2015-08-26 18:34:03 +01002118 DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002119 if (error == JDWP::ERR_THREAD_NOT_ALIVE) {
2120 // Zombie threads are in the null group.
2121 expandBufAddObjectId(pReply, JDWP::ObjectId(0));
Sebastien Hertz52d131d2014-03-13 16:17:40 +01002122 error = JDWP::ERR_NONE;
2123 } else if (error == JDWP::ERR_NONE) {
Mathieu Chartier0795f232016-09-27 18:43:30 -07002124 ObjPtr<mirror::Class> c = soa.Decode<mirror::Class>(WellKnownClasses::java_lang_Thread);
Sebastien Hertz52d131d2014-03-13 16:17:40 +01002125 CHECK(c != nullptr);
Andreas Gampe08883de2016-11-08 13:20:52 -08002126 ArtField* f = jni::DecodeArtField(WellKnownClasses::java_lang_Thread_group);
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07002127 CHECK(f != nullptr);
Mathieu Chartier3398c782016-09-30 10:27:43 -07002128 ObjPtr<mirror::Object> group = f->GetObject(thread_object);
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07002129 CHECK(group != nullptr);
Sebastien Hertz52d131d2014-03-13 16:17:40 +01002130 JDWP::ObjectId thread_group_id = gRegistry->Add(group);
2131 expandBufAddObjectId(pReply, thread_group_id);
Elliott Hughes221229c2013-01-08 18:17:50 -08002132 }
Sebastien Hertz52d131d2014-03-13 16:17:40 +01002133 return error;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002134}
2135
Sebastien Hertza06430c2014-09-15 19:21:30 +02002136static mirror::Object* DecodeThreadGroup(ScopedObjectAccessUnchecked& soa,
2137 JDWP::ObjectId thread_group_id, JDWP::JdwpError* error)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002138 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz6995c602014-09-09 12:10:13 +02002139 mirror::Object* thread_group = Dbg::GetObjectRegistry()->Get<mirror::Object*>(thread_group_id,
2140 error);
Sebastien Hertza06430c2014-09-15 19:21:30 +02002141 if (*error != JDWP::ERR_NONE) {
2142 return nullptr;
2143 }
2144 if (thread_group == nullptr) {
2145 *error = JDWP::ERR_INVALID_OBJECT;
2146 return nullptr;
2147 }
Mathieu Chartier0795f232016-09-27 18:43:30 -07002148 ObjPtr<mirror::Class> c =
2149 soa.Decode<mirror::Class>(WellKnownClasses::java_lang_ThreadGroup);
Ian Rogers98379392014-02-24 16:53:16 -08002150 CHECK(c != nullptr);
Sebastien Hertza06430c2014-09-15 19:21:30 +02002151 if (!c->IsAssignableFrom(thread_group->GetClass())) {
2152 // This is not a java.lang.ThreadGroup.
2153 *error = JDWP::ERR_INVALID_THREAD_GROUP;
2154 return nullptr;
2155 }
2156 *error = JDWP::ERR_NONE;
2157 return thread_group;
2158}
2159
2160JDWP::JdwpError Dbg::GetThreadGroupName(JDWP::ObjectId thread_group_id, JDWP::ExpandBuf* pReply) {
2161 ScopedObjectAccessUnchecked soa(Thread::Current());
2162 JDWP::JdwpError error;
2163 mirror::Object* thread_group = DecodeThreadGroup(soa, thread_group_id, &error);
2164 if (error != JDWP::ERR_NONE) {
2165 return error;
2166 }
Mathieu Chartier268764d2016-09-13 12:09:38 -07002167 ScopedAssertNoThreadSuspension ants("Debugger: GetThreadGroupName");
Andreas Gampe08883de2016-11-08 13:20:52 -08002168 ArtField* f = jni::DecodeArtField(WellKnownClasses::java_lang_ThreadGroup_name);
Ian Rogersc0542af2014-09-03 16:16:56 -07002169 CHECK(f != nullptr);
Mathieu Chartier3398c782016-09-30 10:27:43 -07002170 ObjPtr<mirror::String> s = f->GetObject(thread_group)->AsString();
Sebastien Hertza06430c2014-09-15 19:21:30 +02002171
2172 std::string thread_group_name(s->ToModifiedUtf8());
2173 expandBufAddUtf8String(pReply, thread_group_name);
2174 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002175}
2176
Sebastien Hertza06430c2014-09-15 19:21:30 +02002177JDWP::JdwpError Dbg::GetThreadGroupParent(JDWP::ObjectId thread_group_id, JDWP::ExpandBuf* pReply) {
Ian Rogers98379392014-02-24 16:53:16 -08002178 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002179 JDWP::JdwpError error;
Sebastien Hertza06430c2014-09-15 19:21:30 +02002180 mirror::Object* thread_group = DecodeThreadGroup(soa, thread_group_id, &error);
2181 if (error != JDWP::ERR_NONE) {
2182 return error;
2183 }
Mathieu Chartier3398c782016-09-30 10:27:43 -07002184 ObjPtr<mirror::Object> parent;
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07002185 {
Mathieu Chartier268764d2016-09-13 12:09:38 -07002186 ScopedAssertNoThreadSuspension ants("Debugger: GetThreadGroupParent");
Andreas Gampe08883de2016-11-08 13:20:52 -08002187 ArtField* f = jni::DecodeArtField(WellKnownClasses::java_lang_ThreadGroup_parent);
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07002188 CHECK(f != nullptr);
2189 parent = f->GetObject(thread_group);
2190 }
Sebastien Hertza06430c2014-09-15 19:21:30 +02002191 JDWP::ObjectId parent_group_id = gRegistry->Add(parent);
2192 expandBufAddObjectId(pReply, parent_group_id);
2193 return JDWP::ERR_NONE;
2194}
2195
Andreas Gampe08883de2016-11-08 13:20:52 -08002196static void GetChildThreadGroups(mirror::Object* thread_group,
Sebastien Hertza06430c2014-09-15 19:21:30 +02002197 std::vector<JDWP::ObjectId>* child_thread_group_ids)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002198 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertza06430c2014-09-15 19:21:30 +02002199 CHECK(thread_group != nullptr);
2200
Przemyslaw Szczepaniak464595f2015-11-24 11:59:59 +00002201 // Get the int "ngroups" count of this thread group...
Andreas Gampe08883de2016-11-08 13:20:52 -08002202 ArtField* ngroups_field = jni::DecodeArtField(WellKnownClasses::java_lang_ThreadGroup_ngroups);
Przemyslaw Szczepaniak464595f2015-11-24 11:59:59 +00002203 CHECK(ngroups_field != nullptr);
2204 const int32_t size = ngroups_field->GetInt(thread_group);
2205 if (size == 0) {
2206 return;
Sebastien Hertze49e1952014-10-13 11:27:13 +02002207 }
Sebastien Hertza06430c2014-09-15 19:21:30 +02002208
Przemyslaw Szczepaniak464595f2015-11-24 11:59:59 +00002209 // Get the ThreadGroup[] "groups" out of this thread group...
Andreas Gampe08883de2016-11-08 13:20:52 -08002210 ArtField* groups_field = jni::DecodeArtField(WellKnownClasses::java_lang_ThreadGroup_groups);
Mathieu Chartier3398c782016-09-30 10:27:43 -07002211 ObjPtr<mirror::Object> groups_array = groups_field->GetObject(thread_group);
Przemyslaw Szczepaniak464595f2015-11-24 11:59:59 +00002212
2213 CHECK(groups_array != nullptr);
2214 CHECK(groups_array->IsObjectArray());
2215
Mathieu Chartier3398c782016-09-30 10:27:43 -07002216 ObjPtr<mirror::ObjectArray<mirror::Object>> groups_array_as_array =
Przemyslaw Szczepaniak464595f2015-11-24 11:59:59 +00002217 groups_array->AsObjectArray<mirror::Object>();
Sebastien Hertza06430c2014-09-15 19:21:30 +02002218
2219 // Copy the first 'size' elements out of the array into the result.
Sebastien Hertz6995c602014-09-09 12:10:13 +02002220 ObjectRegistry* registry = Dbg::GetObjectRegistry();
Sebastien Hertza06430c2014-09-15 19:21:30 +02002221 for (int32_t i = 0; i < size; ++i) {
Przemyslaw Szczepaniak464595f2015-11-24 11:59:59 +00002222 child_thread_group_ids->push_back(registry->Add(groups_array_as_array->Get(i)));
Sebastien Hertza06430c2014-09-15 19:21:30 +02002223 }
2224}
2225
2226JDWP::JdwpError Dbg::GetThreadGroupChildren(JDWP::ObjectId thread_group_id,
2227 JDWP::ExpandBuf* pReply) {
2228 ScopedObjectAccessUnchecked soa(Thread::Current());
2229 JDWP::JdwpError error;
2230 mirror::Object* thread_group = DecodeThreadGroup(soa, thread_group_id, &error);
2231 if (error != JDWP::ERR_NONE) {
2232 return error;
2233 }
2234
2235 // Add child threads.
2236 {
2237 std::vector<JDWP::ObjectId> child_thread_ids;
2238 GetThreads(thread_group, &child_thread_ids);
2239 expandBufAdd4BE(pReply, child_thread_ids.size());
2240 for (JDWP::ObjectId child_thread_id : child_thread_ids) {
2241 expandBufAddObjectId(pReply, child_thread_id);
2242 }
2243 }
2244
2245 // Add child thread groups.
2246 {
2247 std::vector<JDWP::ObjectId> child_thread_groups_ids;
Andreas Gampe08883de2016-11-08 13:20:52 -08002248 GetChildThreadGroups(thread_group, &child_thread_groups_ids);
Sebastien Hertza06430c2014-09-15 19:21:30 +02002249 expandBufAdd4BE(pReply, child_thread_groups_ids.size());
2250 for (JDWP::ObjectId child_thread_group_id : child_thread_groups_ids) {
2251 expandBufAddObjectId(pReply, child_thread_group_id);
2252 }
2253 }
2254
2255 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002256}
2257
2258JDWP::ObjectId Dbg::GetSystemThreadGroupId() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002259 ScopedObjectAccessUnchecked soa(Thread::Current());
Andreas Gampe08883de2016-11-08 13:20:52 -08002260 ArtField* f = jni::DecodeArtField(WellKnownClasses::java_lang_ThreadGroup_systemThreadGroup);
Mathieu Chartier3398c782016-09-30 10:27:43 -07002261 ObjPtr<mirror::Object> group = f->GetObject(f->GetDeclaringClass());
Ian Rogers365c1022012-06-22 15:05:28 -07002262 return gRegistry->Add(group);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002263}
2264
Jeff Hao920af3e2013-08-28 15:46:38 -07002265JDWP::JdwpThreadStatus Dbg::ToJdwpThreadStatus(ThreadState state) {
2266 switch (state) {
2267 case kBlocked:
2268 return JDWP::TS_MONITOR;
2269 case kNative:
2270 case kRunnable:
2271 case kSuspended:
2272 return JDWP::TS_RUNNING;
2273 case kSleeping:
2274 return JDWP::TS_SLEEPING;
2275 case kStarting:
2276 case kTerminated:
2277 return JDWP::TS_ZOMBIE;
2278 case kTimedWaiting:
Alex Light77fee872017-09-05 14:51:49 -07002279 case kWaitingForTaskProcessor:
2280 case kWaitingForLockInflation:
Sebastien Hertzbae182c2013-12-17 10:42:03 +01002281 case kWaitingForCheckPointsToRun:
Jeff Hao920af3e2013-08-28 15:46:38 -07002282 case kWaitingForDebuggerSend:
2283 case kWaitingForDebuggerSuspension:
2284 case kWaitingForDebuggerToAttach:
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002285 case kWaitingForDeoptimization:
Jeff Hao920af3e2013-08-28 15:46:38 -07002286 case kWaitingForGcToComplete:
Mathieu Chartierb43390c2015-05-12 10:47:11 -07002287 case kWaitingForGetObjectsAllocated:
Jeff Hao920af3e2013-08-28 15:46:38 -07002288 case kWaitingForJniOnLoad:
Sebastien Hertzbae182c2013-12-17 10:42:03 +01002289 case kWaitingForMethodTracingStart:
Jeff Hao920af3e2013-08-28 15:46:38 -07002290 case kWaitingForSignalCatcherOutput:
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -08002291 case kWaitingForVisitObjects:
Jeff Hao920af3e2013-08-28 15:46:38 -07002292 case kWaitingInMainDebuggerLoop:
2293 case kWaitingInMainSignalCatcherLoop:
2294 case kWaitingPerformingGc:
Mathieu Chartier90ef3db2015-08-04 15:19:41 -07002295 case kWaitingWeakGcRootRead:
Hiroshi Yamauchi76f55b02015-08-21 16:10:39 -07002296 case kWaitingForGcThreadFlip:
Jeff Hao920af3e2013-08-28 15:46:38 -07002297 case kWaiting:
2298 return JDWP::TS_WAIT;
2299 // Don't add a 'default' here so the compiler can spot incompatible enum changes.
2300 }
2301 LOG(FATAL) << "Unknown thread state: " << state;
2302 return JDWP::TS_ZOMBIE;
2303}
2304
Sebastien Hertz52d131d2014-03-13 16:17:40 +01002305JDWP::JdwpError Dbg::GetThreadStatus(JDWP::ObjectId thread_id, JDWP::JdwpThreadStatus* pThreadStatus,
2306 JDWP::JdwpSuspendStatus* pSuspendStatus) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002307 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes499c5132011-11-17 14:55:11 -08002308
Elliott Hughes9e0c1752013-01-09 14:02:58 -08002309 *pSuspendStatus = JDWP::SUSPEND_STATUS_NOT_SUSPENDED;
2310
Ian Rogersc0542af2014-09-03 16:16:56 -07002311 JDWP::JdwpError error;
2312 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002313 if (error != JDWP::ERR_NONE) {
2314 if (error == JDWP::ERR_THREAD_NOT_ALIVE) {
2315 *pThreadStatus = JDWP::TS_ZOMBIE;
Elliott Hughes221229c2013-01-08 18:17:50 -08002316 return JDWP::ERR_NONE;
2317 }
2318 return error;
Elliott Hughes499c5132011-11-17 14:55:11 -08002319 }
2320
Elliott Hughes9e0c1752013-01-09 14:02:58 -08002321 if (IsSuspendedForDebugger(soa, thread)) {
2322 *pSuspendStatus = JDWP::SUSPEND_STATUS_SUSPENDED;
Elliott Hughes499c5132011-11-17 14:55:11 -08002323 }
2324
Jeff Hao920af3e2013-08-28 15:46:38 -07002325 *pThreadStatus = ToJdwpThreadStatus(thread->GetState());
Elliott Hughes221229c2013-01-08 18:17:50 -08002326 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002327}
2328
Elliott Hughes221229c2013-01-08 18:17:50 -08002329JDWP::JdwpError Dbg::GetThreadDebugSuspendCount(JDWP::ObjectId thread_id, JDWP::ExpandBuf* pReply) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002330 ScopedObjectAccess soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002331 JDWP::JdwpError error;
2332 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002333 if (error != JDWP::ERR_NONE) {
2334 return error;
Elliott Hughes2435a572012-02-17 16:07:41 -08002335 }
Ian Rogers50b35e22012-10-04 10:09:15 -07002336 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002337 expandBufAdd4BE(pReply, thread->GetDebugSuspendCount());
Elliott Hughes2435a572012-02-17 16:07:41 -08002338 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002339}
2340
Elliott Hughesf9501702013-01-11 11:22:27 -08002341JDWP::JdwpError Dbg::Interrupt(JDWP::ObjectId thread_id) {
2342 ScopedObjectAccess soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002343 JDWP::JdwpError error;
2344 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughesf9501702013-01-11 11:22:27 -08002345 if (error != JDWP::ERR_NONE) {
2346 return error;
2347 }
Ian Rogersdd7624d2014-03-14 17:43:00 -07002348 thread->Interrupt(soa.Self());
Elliott Hughesf9501702013-01-11 11:22:27 -08002349 return JDWP::ERR_NONE;
2350}
2351
Andreas Gampe08883de2016-11-08 13:20:52 -08002352static bool IsInDesiredThreadGroup(mirror::Object* desired_thread_group, mirror::Object* peer)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002353 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz070f7322014-09-09 12:08:49 +02002354 // Do we want threads from all thread groups?
2355 if (desired_thread_group == nullptr) {
2356 return true;
2357 }
Andreas Gampe08883de2016-11-08 13:20:52 -08002358 ArtField* thread_group_field = jni::DecodeArtField(WellKnownClasses::java_lang_Thread_group);
Sebastien Hertz070f7322014-09-09 12:08:49 +02002359 DCHECK(thread_group_field != nullptr);
Mathieu Chartier3398c782016-09-30 10:27:43 -07002360 ObjPtr<mirror::Object> group = thread_group_field->GetObject(peer);
Sebastien Hertz070f7322014-09-09 12:08:49 +02002361 return (group == desired_thread_group);
2362}
2363
Sebastien Hertza06430c2014-09-15 19:21:30 +02002364void Dbg::GetThreads(mirror::Object* thread_group, std::vector<JDWP::ObjectId>* thread_ids) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002365 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz070f7322014-09-09 12:08:49 +02002366 std::list<Thread*> all_threads_list;
2367 {
2368 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
2369 all_threads_list = Runtime::Current()->GetThreadList()->GetList();
2370 }
2371 for (Thread* t : all_threads_list) {
2372 if (t == Dbg::GetDebugThread()) {
2373 // Skip the JDWP thread. Some debuggers get bent out of shape when they can't suspend and
2374 // query all threads, so it's easier if we just don't tell them about this thread.
2375 continue;
2376 }
2377 if (t->IsStillStarting()) {
2378 // This thread is being started (and has been registered in the thread list). However, it is
2379 // not completely started yet so we must ignore it.
2380 continue;
2381 }
Nicolas Geoffraycafa0812017-02-15 18:27:34 +00002382 mirror::Object* peer = t->GetPeerFromOtherThread();
Sebastien Hertz070f7322014-09-09 12:08:49 +02002383 if (peer == nullptr) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002384 // 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 +02002385 // this thread yet.
2386 // TODO: if we identified threads to the debugger by their Thread*
2387 // rather than their peer's mirror::Object*, we could fix this.
2388 // Doing so might help us report ZOMBIE threads too.
2389 continue;
2390 }
Andreas Gampe08883de2016-11-08 13:20:52 -08002391 if (IsInDesiredThreadGroup(thread_group, peer)) {
Sebastien Hertz070f7322014-09-09 12:08:49 +02002392 thread_ids->push_back(gRegistry->Add(peer));
2393 }
2394 }
Elliott Hughescaf76542012-06-28 16:08:22 -07002395}
Elliott Hughesa2155262011-11-16 16:26:58 -08002396
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002397static int GetStackDepth(Thread* thread) REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002398 struct CountStackDepthVisitor : public StackVisitor {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002399 explicit CountStackDepthVisitor(Thread* thread_in)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01002400 : StackVisitor(thread_in, nullptr, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
2401 depth(0) {}
Ian Rogers0399dde2012-06-06 17:09:28 -07002402
Elliott Hughes64f574f2013-02-20 14:57:12 -08002403 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2404 // annotalysis.
2405 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07002406 if (!GetMethod()->IsRuntimeMethod()) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -08002407 ++depth;
2408 }
Elliott Hughes530fa002012-03-12 11:44:49 -07002409 return true;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08002410 }
2411 size_t depth;
2412 };
Elliott Hughes08fc03a2012-06-26 17:34:00 -07002413
Ian Rogers7a22fa62013-01-23 12:16:16 -08002414 CountStackDepthVisitor visitor(thread);
Ian Rogers0399dde2012-06-06 17:09:28 -07002415 visitor.WalkStack();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08002416 return visitor.depth;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002417}
2418
Ian Rogersc0542af2014-09-03 16:16:56 -07002419JDWP::JdwpError Dbg::GetThreadFrameCount(JDWP::ObjectId thread_id, size_t* result) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002420 ScopedObjectAccess soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002421 JDWP::JdwpError error;
2422 *result = 0;
2423 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002424 if (error != JDWP::ERR_NONE) {
2425 return error;
2426 }
Elliott Hughesf15f4a02013-01-09 10:09:38 -08002427 if (!IsSuspendedForDebugger(soa, thread)) {
2428 return JDWP::ERR_THREAD_NOT_SUSPENDED;
2429 }
Ian Rogersc0542af2014-09-03 16:16:56 -07002430 *result = GetStackDepth(thread);
Elliott Hughes221229c2013-01-08 18:17:50 -08002431 return JDWP::ERR_NONE;
Elliott Hughes86964332012-02-15 19:37:42 -08002432}
2433
Ian Rogers306057f2012-11-26 12:45:53 -08002434JDWP::JdwpError Dbg::GetThreadFrames(JDWP::ObjectId thread_id, size_t start_frame,
2435 size_t frame_count, JDWP::ExpandBuf* buf) {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002436 class GetFrameVisitor : public StackVisitor {
2437 public:
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002438 GetFrameVisitor(Thread* thread, size_t start_frame_in, size_t frame_count_in,
2439 JDWP::ExpandBuf* buf_in)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002440 REQUIRES_SHARED(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01002441 : StackVisitor(thread, nullptr, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
2442 depth_(0),
2443 start_frame_(start_frame_in),
2444 frame_count_(frame_count_in),
2445 buf_(buf_in) {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002446 expandBufAdd4BE(buf_, frame_count_);
Elliott Hughes03181a82011-11-17 17:22:21 -08002447 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002448
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002449 bool VisitFrame() OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002450 if (GetMethod()->IsRuntimeMethod()) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07002451 return true; // The debugger can't do anything useful with a frame that has no Method*.
Elliott Hughes03181a82011-11-17 17:22:21 -08002452 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002453 if (depth_ >= start_frame_ + frame_count_) {
Elliott Hughes530fa002012-03-12 11:44:49 -07002454 return false;
Elliott Hughes03181a82011-11-17 17:22:21 -08002455 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002456 if (depth_ >= start_frame_) {
2457 JDWP::FrameId frame_id(GetFrameId());
2458 JDWP::JdwpLocation location;
Sebastien Hertz6995c602014-09-09 12:10:13 +02002459 SetJdwpLocation(&location, GetMethod(), GetDexPc());
Ian Rogersef7d42f2014-01-06 12:55:46 -08002460 VLOG(jdwp) << StringPrintf(" Frame %3zd: id=%3" PRIu64 " ", depth_, frame_id) << location;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002461 expandBufAdd8BE(buf_, frame_id);
2462 expandBufAddLocation(buf_, location);
2463 }
2464 ++depth_;
Elliott Hughes530fa002012-03-12 11:44:49 -07002465 return true;
Elliott Hughes03181a82011-11-17 17:22:21 -08002466 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002467
2468 private:
2469 size_t depth_;
2470 const size_t start_frame_;
2471 const size_t frame_count_;
2472 JDWP::ExpandBuf* buf_;
Elliott Hughes03181a82011-11-17 17:22:21 -08002473 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002474
2475 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002476 JDWP::JdwpError error;
2477 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002478 if (error != JDWP::ERR_NONE) {
2479 return error;
2480 }
Elliott Hughesf15f4a02013-01-09 10:09:38 -08002481 if (!IsSuspendedForDebugger(soa, thread)) {
2482 return JDWP::ERR_THREAD_NOT_SUSPENDED;
2483 }
Ian Rogers7a22fa62013-01-23 12:16:16 -08002484 GetFrameVisitor visitor(thread, start_frame, frame_count, buf);
Ian Rogers0399dde2012-06-06 17:09:28 -07002485 visitor.WalkStack();
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002486 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002487}
2488
2489JDWP::ObjectId Dbg::GetThreadSelfId() {
Sebastien Hertz6995c602014-09-09 12:10:13 +02002490 return GetThreadId(Thread::Current());
2491}
2492
2493JDWP::ObjectId Dbg::GetThreadId(Thread* thread) {
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07002494 ScopedObjectAccessUnchecked soa(Thread::Current());
Nicolas Geoffraycafa0812017-02-15 18:27:34 +00002495 return gRegistry->Add(thread->GetPeerFromOtherThread());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002496}
2497
Elliott Hughes475fc232011-10-25 15:00:35 -07002498void Dbg::SuspendVM() {
Hiroshi Yamauchi8f95cf32016-04-19 11:14:06 -07002499 // Avoid a deadlock between GC and debugger where GC gets suspended during GC. b/25800335.
2500 gc::ScopedGCCriticalSection gcs(Thread::Current(),
2501 gc::kGcCauseDebugger,
2502 gc::kCollectorTypeDebugger);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002503 Runtime::Current()->GetThreadList()->SuspendAllForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002504}
2505
2506void Dbg::ResumeVM() {
Sebastien Hertz253fa552014-10-14 17:27:15 +02002507 Runtime::Current()->GetThreadList()->ResumeAllForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002508}
2509
Elliott Hughes221229c2013-01-08 18:17:50 -08002510JDWP::JdwpError Dbg::SuspendThread(JDWP::ObjectId thread_id, bool request_suspension) {
Ian Rogersf3d874c2014-07-17 18:52:42 -07002511 Thread* self = Thread::Current();
Ian Rogersc0542af2014-09-03 16:16:56 -07002512 ScopedLocalRef<jobject> peer(self->GetJniEnv(), nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002513 {
Ian Rogersf3d874c2014-07-17 18:52:42 -07002514 ScopedObjectAccess soa(self);
Ian Rogersc0542af2014-09-03 16:16:56 -07002515 JDWP::JdwpError error;
2516 peer.reset(soa.AddLocalReference<jobject>(gRegistry->Get<mirror::Object*>(thread_id, &error)));
Elliott Hughes4e235312011-12-02 11:34:15 -08002517 }
Ian Rogersc0542af2014-09-03 16:16:56 -07002518 if (peer.get() == nullptr) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002519 return JDWP::ERR_THREAD_NOT_ALIVE;
2520 }
Ian Rogers4ad5cd32014-11-11 23:08:07 -08002521 // Suspend thread to build stack trace.
Elliott Hughesf327e072013-01-09 16:01:26 -08002522 bool timed_out;
Brian Carlstromba32de42014-08-27 23:43:46 -07002523 ThreadList* thread_list = Runtime::Current()->GetThreadList();
Sebastien Hertzcdd798d2017-04-18 18:28:51 +02002524 Thread* thread = thread_list->SuspendThreadByPeer(peer.get(),
2525 request_suspension,
Alex Light46f93402017-06-29 11:59:50 -07002526 SuspendReason::kForDebugger,
Brian Carlstromba32de42014-08-27 23:43:46 -07002527 &timed_out);
Ian Rogersc0542af2014-09-03 16:16:56 -07002528 if (thread != nullptr) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002529 return JDWP::ERR_NONE;
Elliott Hughesf327e072013-01-09 16:01:26 -08002530 } else if (timed_out) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002531 return JDWP::ERR_INTERNAL;
2532 } else {
2533 return JDWP::ERR_THREAD_NOT_ALIVE;
2534 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002535}
2536
Elliott Hughes221229c2013-01-08 18:17:50 -08002537void Dbg::ResumeThread(JDWP::ObjectId thread_id) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002538 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002539 JDWP::JdwpError error;
2540 mirror::Object* peer = gRegistry->Get<mirror::Object*>(thread_id, &error);
2541 CHECK(peer != nullptr) << error;
jeffhaoa77f0f62012-12-05 17:19:31 -08002542 Thread* thread;
2543 {
2544 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
2545 thread = Thread::FromManagedThread(soa, peer);
2546 }
Ian Rogersc0542af2014-09-03 16:16:56 -07002547 if (thread == nullptr) {
Elliott Hughes4e235312011-12-02 11:34:15 -08002548 LOG(WARNING) << "No such thread for resume: " << peer;
2549 return;
2550 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002551 bool needs_resume;
2552 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002553 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Sebastien Hertz70d60272017-04-14 14:18:36 +02002554 needs_resume = thread->GetDebugSuspendCount() > 0;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002555 }
2556 if (needs_resume) {
Alex Light88fd7202017-06-30 08:31:59 -07002557 bool resumed = Runtime::Current()->GetThreadList()->Resume(thread, SuspendReason::kForDebugger);
2558 DCHECK(resumed);
Elliott Hughes546b9862012-06-20 16:06:13 -07002559 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002560}
2561
2562void Dbg::SuspendSelf() {
Elliott Hughes475fc232011-10-25 15:00:35 -07002563 Runtime::Current()->GetThreadList()->SuspendSelfForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002564}
2565
Ian Rogers0399dde2012-06-06 17:09:28 -07002566struct GetThisVisitor : public StackVisitor {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002567 GetThisVisitor(Thread* thread, Context* context, JDWP::FrameId frame_id_in)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002568 REQUIRES_SHARED(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01002569 : StackVisitor(thread, context, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
2570 this_object(nullptr),
2571 frame_id(frame_id_in) {}
Ian Rogers0399dde2012-06-06 17:09:28 -07002572
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002573 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2574 // annotalysis.
2575 virtual bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002576 if (frame_id != GetFrameId()) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002577 return true; // continue
Ian Rogers0399dde2012-06-06 17:09:28 -07002578 } else {
Ian Rogers62d6c772013-02-27 08:32:07 -08002579 this_object = GetThisObject();
2580 return false;
Ian Rogers0399dde2012-06-06 17:09:28 -07002581 }
Elliott Hughes86b00102011-12-05 17:54:26 -08002582 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002583
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002584 mirror::Object* this_object;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002585 JDWP::FrameId frame_id;
Ian Rogers0399dde2012-06-06 17:09:28 -07002586};
2587
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002588JDWP::JdwpError Dbg::GetThisObject(JDWP::ObjectId thread_id, JDWP::FrameId frame_id,
2589 JDWP::ObjectId* result) {
2590 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz69206392015-04-07 15:54:25 +02002591 JDWP::JdwpError error;
2592 Thread* thread = DecodeThread(soa, thread_id, &error);
2593 if (error != JDWP::ERR_NONE) {
2594 return error;
2595 }
2596 if (!IsSuspendedForDebugger(soa, thread)) {
2597 return JDWP::ERR_THREAD_NOT_SUSPENDED;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002598 }
Ian Rogers700a4022014-05-19 16:49:03 -07002599 std::unique_ptr<Context> context(Context::Create());
Ian Rogers7a22fa62013-01-23 12:16:16 -08002600 GetThisVisitor visitor(thread, context.get(), frame_id);
Ian Rogers0399dde2012-06-06 17:09:28 -07002601 visitor.WalkStack();
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002602 *result = gRegistry->Add(visitor.this_object);
2603 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002604}
2605
Sebastien Hertz8009f392014-09-01 17:07:11 +02002606// Walks the stack until we find the frame with the given FrameId.
2607class FindFrameVisitor FINAL : public StackVisitor {
2608 public:
2609 FindFrameVisitor(Thread* thread, Context* context, JDWP::FrameId frame_id)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002610 REQUIRES_SHARED(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01002611 : StackVisitor(thread, context, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
2612 frame_id_(frame_id),
2613 error_(JDWP::ERR_INVALID_FRAMEID) {}
Ian Rogersca190662012-06-26 15:45:57 -07002614
Sebastien Hertz8009f392014-09-01 17:07:11 +02002615 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2616 // annotalysis.
2617 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
2618 if (GetFrameId() != frame_id_) {
2619 return true; // Not our frame, carry on.
Ian Rogers0399dde2012-06-06 17:09:28 -07002620 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07002621 ArtMethod* m = GetMethod();
Sebastien Hertz8009f392014-09-01 17:07:11 +02002622 if (m->IsNative()) {
2623 // We can't read/write local value from/into native method.
2624 error_ = JDWP::ERR_OPAQUE_FRAME;
2625 } else {
2626 // We found our frame.
2627 error_ = JDWP::ERR_NONE;
2628 }
2629 return false;
2630 }
2631
2632 JDWP::JdwpError GetError() const {
2633 return error_;
2634 }
2635
2636 private:
2637 const JDWP::FrameId frame_id_;
2638 JDWP::JdwpError error_;
Sebastien Hertz26f72862015-09-15 09:52:07 +02002639
2640 DISALLOW_COPY_AND_ASSIGN(FindFrameVisitor);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002641};
2642
2643JDWP::JdwpError Dbg::GetLocalValues(JDWP::Request* request, JDWP::ExpandBuf* pReply) {
2644 JDWP::ObjectId thread_id = request->ReadThreadId();
2645 JDWP::FrameId frame_id = request->ReadFrameId();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002646
2647 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz69206392015-04-07 15:54:25 +02002648 JDWP::JdwpError error;
2649 Thread* thread = DecodeThread(soa, thread_id, &error);
2650 if (error != JDWP::ERR_NONE) {
2651 return error;
2652 }
2653 if (!IsSuspendedForDebugger(soa, thread)) {
2654 return JDWP::ERR_THREAD_NOT_SUSPENDED;
Elliott Hughes221229c2013-01-08 18:17:50 -08002655 }
Sebastien Hertz8009f392014-09-01 17:07:11 +02002656 // Find the frame with the given frame_id.
Ian Rogers700a4022014-05-19 16:49:03 -07002657 std::unique_ptr<Context> context(Context::Create());
Sebastien Hertz8009f392014-09-01 17:07:11 +02002658 FindFrameVisitor visitor(thread, context.get(), frame_id);
Ian Rogers0399dde2012-06-06 17:09:28 -07002659 visitor.WalkStack();
Sebastien Hertz8009f392014-09-01 17:07:11 +02002660 if (visitor.GetError() != JDWP::ERR_NONE) {
2661 return visitor.GetError();
2662 }
2663
2664 // Read the values from visitor's context.
2665 int32_t slot_count = request->ReadSigned32("slot count");
2666 expandBufAdd4BE(pReply, slot_count); /* "int values" */
2667 for (int32_t i = 0; i < slot_count; ++i) {
2668 uint32_t slot = request->ReadUnsigned32("slot");
2669 JDWP::JdwpTag reqSigByte = request->ReadTag();
2670
2671 VLOG(jdwp) << " --> slot " << slot << " " << reqSigByte;
2672
2673 size_t width = Dbg::GetTagWidth(reqSigByte);
Sebastien Hertz7d955652014-10-22 10:57:10 +02002674 uint8_t* ptr = expandBufAddSpace(pReply, width + 1);
Sebastien Hertz69206392015-04-07 15:54:25 +02002675 error = Dbg::GetLocalValue(visitor, soa, slot, reqSigByte, ptr, width);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002676 if (error != JDWP::ERR_NONE) {
2677 return error;
2678 }
2679 }
2680 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002681}
2682
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002683constexpr JDWP::JdwpError kStackFrameLocalAccessError = JDWP::ERR_ABSENT_INFORMATION;
2684
2685static std::string GetStackContextAsString(const StackVisitor& visitor)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002686 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002687 return StringPrintf(" at DEX pc 0x%08x in method %s", visitor.GetDexPc(false),
David Sehr709b0702016-10-13 09:12:37 -07002688 ArtMethod::PrettyMethod(visitor.GetMethod()).c_str());
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002689}
2690
2691static JDWP::JdwpError FailGetLocalValue(const StackVisitor& visitor, uint16_t vreg,
2692 JDWP::JdwpTag tag)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002693 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002694 LOG(ERROR) << "Failed to read " << tag << " local from register v" << vreg
2695 << GetStackContextAsString(visitor);
2696 return kStackFrameLocalAccessError;
2697}
2698
Sebastien Hertz8009f392014-09-01 17:07:11 +02002699JDWP::JdwpError Dbg::GetLocalValue(const StackVisitor& visitor, ScopedObjectAccessUnchecked& soa,
2700 int slot, JDWP::JdwpTag tag, uint8_t* buf, size_t width) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002701 ArtMethod* m = visitor.GetMethod();
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002702 JDWP::JdwpError error = JDWP::ERR_NONE;
2703 uint16_t vreg = DemangleSlot(slot, m, &error);
2704 if (error != JDWP::ERR_NONE) {
2705 return error;
2706 }
Sebastien Hertz8009f392014-09-01 17:07:11 +02002707 // TODO: check that the tag is compatible with the actual type of the slot!
Sebastien Hertz8009f392014-09-01 17:07:11 +02002708 switch (tag) {
2709 case JDWP::JT_BOOLEAN: {
2710 CHECK_EQ(width, 1U);
2711 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002712 if (!visitor.GetVReg(m, vreg, kIntVReg, &intVal)) {
2713 return FailGetLocalValue(visitor, vreg, tag);
Ian Rogers0399dde2012-06-06 17:09:28 -07002714 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002715 VLOG(jdwp) << "get boolean local " << vreg << " = " << intVal;
2716 JDWP::Set1(buf + 1, intVal != 0);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002717 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002718 }
Sebastien Hertz8009f392014-09-01 17:07:11 +02002719 case JDWP::JT_BYTE: {
2720 CHECK_EQ(width, 1U);
2721 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002722 if (!visitor.GetVReg(m, vreg, kIntVReg, &intVal)) {
2723 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002724 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002725 VLOG(jdwp) << "get byte local " << vreg << " = " << intVal;
2726 JDWP::Set1(buf + 1, intVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002727 break;
2728 }
2729 case JDWP::JT_SHORT:
2730 case JDWP::JT_CHAR: {
2731 CHECK_EQ(width, 2U);
2732 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002733 if (!visitor.GetVReg(m, vreg, kIntVReg, &intVal)) {
2734 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002735 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002736 VLOG(jdwp) << "get short/char local " << vreg << " = " << intVal;
2737 JDWP::Set2BE(buf + 1, intVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002738 break;
2739 }
2740 case JDWP::JT_INT: {
2741 CHECK_EQ(width, 4U);
2742 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002743 if (!visitor.GetVReg(m, vreg, kIntVReg, &intVal)) {
2744 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002745 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002746 VLOG(jdwp) << "get int local " << vreg << " = " << intVal;
2747 JDWP::Set4BE(buf + 1, intVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002748 break;
2749 }
2750 case JDWP::JT_FLOAT: {
2751 CHECK_EQ(width, 4U);
2752 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002753 if (!visitor.GetVReg(m, vreg, kFloatVReg, &intVal)) {
2754 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002755 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002756 VLOG(jdwp) << "get float local " << vreg << " = " << intVal;
2757 JDWP::Set4BE(buf + 1, intVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002758 break;
2759 }
2760 case JDWP::JT_ARRAY:
2761 case JDWP::JT_CLASS_LOADER:
2762 case JDWP::JT_CLASS_OBJECT:
2763 case JDWP::JT_OBJECT:
2764 case JDWP::JT_STRING:
2765 case JDWP::JT_THREAD:
2766 case JDWP::JT_THREAD_GROUP: {
2767 CHECK_EQ(width, sizeof(JDWP::ObjectId));
2768 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002769 if (!visitor.GetVReg(m, vreg, kReferenceVReg, &intVal)) {
2770 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002771 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002772 mirror::Object* o = reinterpret_cast<mirror::Object*>(intVal);
2773 VLOG(jdwp) << "get " << tag << " object local " << vreg << " = " << o;
2774 if (!Runtime::Current()->GetHeap()->IsValidObjectAddress(o)) {
2775 LOG(FATAL) << StringPrintf("Found invalid object %#" PRIxPTR " in register v%u",
2776 reinterpret_cast<uintptr_t>(o), vreg)
2777 << GetStackContextAsString(visitor);
2778 UNREACHABLE();
2779 }
2780 tag = TagFromObject(soa, o);
2781 JDWP::SetObjectId(buf + 1, gRegistry->Add(o));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002782 break;
2783 }
2784 case JDWP::JT_DOUBLE: {
2785 CHECK_EQ(width, 8U);
2786 uint64_t longVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002787 if (!visitor.GetVRegPair(m, vreg, kDoubleLoVReg, kDoubleHiVReg, &longVal)) {
2788 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002789 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002790 VLOG(jdwp) << "get double local " << vreg << " = " << longVal;
2791 JDWP::Set8BE(buf + 1, longVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002792 break;
2793 }
2794 case JDWP::JT_LONG: {
2795 CHECK_EQ(width, 8U);
2796 uint64_t longVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002797 if (!visitor.GetVRegPair(m, vreg, kLongLoVReg, kLongHiVReg, &longVal)) {
2798 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002799 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002800 VLOG(jdwp) << "get long local " << vreg << " = " << longVal;
2801 JDWP::Set8BE(buf + 1, longVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002802 break;
2803 }
2804 default:
2805 LOG(FATAL) << "Unknown tag " << tag;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002806 UNREACHABLE();
Sebastien Hertz8009f392014-09-01 17:07:11 +02002807 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002808
Sebastien Hertz8009f392014-09-01 17:07:11 +02002809 // Prepend tag, which may have been updated.
2810 JDWP::Set1(buf, tag);
2811 return JDWP::ERR_NONE;
2812}
2813
2814JDWP::JdwpError Dbg::SetLocalValues(JDWP::Request* request) {
2815 JDWP::ObjectId thread_id = request->ReadThreadId();
2816 JDWP::FrameId frame_id = request->ReadFrameId();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002817
2818 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz69206392015-04-07 15:54:25 +02002819 JDWP::JdwpError error;
2820 Thread* thread = DecodeThread(soa, thread_id, &error);
2821 if (error != JDWP::ERR_NONE) {
2822 return error;
2823 }
2824 if (!IsSuspendedForDebugger(soa, thread)) {
2825 return JDWP::ERR_THREAD_NOT_SUSPENDED;
Elliott Hughes221229c2013-01-08 18:17:50 -08002826 }
Sebastien Hertz8009f392014-09-01 17:07:11 +02002827 // Find the frame with the given frame_id.
Ian Rogers700a4022014-05-19 16:49:03 -07002828 std::unique_ptr<Context> context(Context::Create());
Sebastien Hertz8009f392014-09-01 17:07:11 +02002829 FindFrameVisitor visitor(thread, context.get(), frame_id);
Ian Rogers0399dde2012-06-06 17:09:28 -07002830 visitor.WalkStack();
Sebastien Hertz8009f392014-09-01 17:07:11 +02002831 if (visitor.GetError() != JDWP::ERR_NONE) {
2832 return visitor.GetError();
2833 }
2834
2835 // Writes the values into visitor's context.
2836 int32_t slot_count = request->ReadSigned32("slot count");
2837 for (int32_t i = 0; i < slot_count; ++i) {
2838 uint32_t slot = request->ReadUnsigned32("slot");
2839 JDWP::JdwpTag sigByte = request->ReadTag();
2840 size_t width = Dbg::GetTagWidth(sigByte);
2841 uint64_t value = request->ReadValue(width);
2842
2843 VLOG(jdwp) << " --> slot " << slot << " " << sigByte << " " << value;
Mingyao Yang99170c62015-07-06 11:10:37 -07002844 error = Dbg::SetLocalValue(thread, visitor, slot, sigByte, value, width);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002845 if (error != JDWP::ERR_NONE) {
2846 return error;
2847 }
2848 }
2849 return JDWP::ERR_NONE;
2850}
2851
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002852template<typename T>
2853static JDWP::JdwpError FailSetLocalValue(const StackVisitor& visitor, uint16_t vreg,
2854 JDWP::JdwpTag tag, T value)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002855 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002856 LOG(ERROR) << "Failed to write " << tag << " local " << value
2857 << " (0x" << std::hex << value << ") into register v" << vreg
2858 << GetStackContextAsString(visitor);
2859 return kStackFrameLocalAccessError;
2860}
2861
Mingyao Yang99170c62015-07-06 11:10:37 -07002862JDWP::JdwpError Dbg::SetLocalValue(Thread* thread, StackVisitor& visitor, int slot,
2863 JDWP::JdwpTag tag, uint64_t value, size_t width) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002864 ArtMethod* m = visitor.GetMethod();
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002865 JDWP::JdwpError error = JDWP::ERR_NONE;
2866 uint16_t vreg = DemangleSlot(slot, m, &error);
2867 if (error != JDWP::ERR_NONE) {
2868 return error;
2869 }
Sebastien Hertz8009f392014-09-01 17:07:11 +02002870 // TODO: check that the tag is compatible with the actual type of the slot!
Sebastien Hertz8009f392014-09-01 17:07:11 +02002871 switch (tag) {
2872 case JDWP::JT_BOOLEAN:
2873 case JDWP::JT_BYTE:
2874 CHECK_EQ(width, 1U);
Mingyao Yang636b9252015-07-31 16:40:24 -07002875 if (!visitor.SetVReg(m, vreg, static_cast<uint32_t>(value), kIntVReg)) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002876 return FailSetLocalValue(visitor, vreg, tag, static_cast<uint32_t>(value));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002877 }
2878 break;
2879 case JDWP::JT_SHORT:
2880 case JDWP::JT_CHAR:
2881 CHECK_EQ(width, 2U);
Mingyao Yang636b9252015-07-31 16:40:24 -07002882 if (!visitor.SetVReg(m, vreg, static_cast<uint32_t>(value), kIntVReg)) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002883 return FailSetLocalValue(visitor, vreg, tag, static_cast<uint32_t>(value));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002884 }
2885 break;
2886 case JDWP::JT_INT:
2887 CHECK_EQ(width, 4U);
Mingyao Yang636b9252015-07-31 16:40:24 -07002888 if (!visitor.SetVReg(m, vreg, static_cast<uint32_t>(value), kIntVReg)) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002889 return FailSetLocalValue(visitor, vreg, tag, static_cast<uint32_t>(value));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002890 }
2891 break;
2892 case JDWP::JT_FLOAT:
2893 CHECK_EQ(width, 4U);
Mingyao Yang636b9252015-07-31 16:40:24 -07002894 if (!visitor.SetVReg(m, vreg, static_cast<uint32_t>(value), kFloatVReg)) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002895 return FailSetLocalValue(visitor, vreg, tag, static_cast<uint32_t>(value));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002896 }
2897 break;
2898 case JDWP::JT_ARRAY:
2899 case JDWP::JT_CLASS_LOADER:
2900 case JDWP::JT_CLASS_OBJECT:
2901 case JDWP::JT_OBJECT:
2902 case JDWP::JT_STRING:
2903 case JDWP::JT_THREAD:
2904 case JDWP::JT_THREAD_GROUP: {
2905 CHECK_EQ(width, sizeof(JDWP::ObjectId));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002906 mirror::Object* o = gRegistry->Get<mirror::Object*>(static_cast<JDWP::ObjectId>(value),
2907 &error);
2908 if (error != JDWP::ERR_NONE) {
2909 VLOG(jdwp) << tag << " object " << o << " is an invalid object";
2910 return JDWP::ERR_INVALID_OBJECT;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002911 }
Mingyao Yang636b9252015-07-31 16:40:24 -07002912 if (!visitor.SetVReg(m, vreg, static_cast<uint32_t>(reinterpret_cast<uintptr_t>(o)),
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002913 kReferenceVReg)) {
2914 return FailSetLocalValue(visitor, vreg, tag, reinterpret_cast<uintptr_t>(o));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002915 }
2916 break;
2917 }
2918 case JDWP::JT_DOUBLE: {
2919 CHECK_EQ(width, 8U);
Mingyao Yang636b9252015-07-31 16:40:24 -07002920 if (!visitor.SetVRegPair(m, vreg, value, kDoubleLoVReg, kDoubleHiVReg)) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002921 return FailSetLocalValue(visitor, vreg, tag, value);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002922 }
2923 break;
2924 }
2925 case JDWP::JT_LONG: {
2926 CHECK_EQ(width, 8U);
Mingyao Yang636b9252015-07-31 16:40:24 -07002927 if (!visitor.SetVRegPair(m, vreg, value, kLongLoVReg, kLongHiVReg)) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002928 return FailSetLocalValue(visitor, vreg, tag, value);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002929 }
2930 break;
2931 }
2932 default:
2933 LOG(FATAL) << "Unknown tag " << tag;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002934 UNREACHABLE();
Sebastien Hertz8009f392014-09-01 17:07:11 +02002935 }
Mingyao Yang99170c62015-07-06 11:10:37 -07002936
2937 // If we set the local variable in a compiled frame, we need to trigger a deoptimization of
2938 // the stack so we continue execution with the interpreter using the new value(s) of the updated
2939 // local variable(s). To achieve this, we install instrumentation exit stub on each method of the
2940 // thread's stack. The stub will cause the deoptimization to happen.
2941 if (!visitor.IsShadowFrame() && thread->HasDebuggerShadowFrames()) {
2942 Runtime::Current()->GetInstrumentation()->InstrumentThreadStack(thread);
2943 }
2944
Sebastien Hertz8009f392014-09-01 17:07:11 +02002945 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002946}
2947
Mathieu Chartiere401d142015-04-22 13:56:20 -07002948static void SetEventLocation(JDWP::EventLocation* location, ArtMethod* m, uint32_t dex_pc)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002949 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz6995c602014-09-09 12:10:13 +02002950 DCHECK(location != nullptr);
2951 if (m == nullptr) {
2952 memset(location, 0, sizeof(*location));
2953 } else {
Alex Light97e78032017-06-27 17:51:55 -07002954 location->method = m->GetCanonicalMethod(kRuntimePointerSize);
Sebastien Hertz6995c602014-09-09 12:10:13 +02002955 location->dex_pc = (m->IsNative() || m->IsProxyMethod()) ? static_cast<uint32_t>(-1) : dex_pc;
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002956 }
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002957}
2958
Mathieu Chartiere401d142015-04-22 13:56:20 -07002959void Dbg::PostLocationEvent(ArtMethod* m, int dex_pc, mirror::Object* this_object,
Jeff Hao579b0242013-11-18 13:16:49 -08002960 int event_flags, const JValue* return_value) {
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002961 if (!IsDebuggerActive()) {
2962 return;
2963 }
2964 DCHECK(m != nullptr);
2965 DCHECK_EQ(m->IsStatic(), this_object == nullptr);
Sebastien Hertz6995c602014-09-09 12:10:13 +02002966 JDWP::EventLocation location;
2967 SetEventLocation(&location, m, dex_pc);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002968
Sebastien Hertzde48aa62015-05-26 11:53:39 +02002969 // We need to be sure no exception is pending when calling JdwpState::PostLocationEvent.
2970 // This is required to be able to call JNI functions to create JDWP ids. To achieve this,
2971 // we temporarily clear the current thread's exception (if any) and will restore it after
2972 // the call.
2973 // Note: the only way to get a pending exception here is to suspend on a move-exception
2974 // instruction.
2975 Thread* const self = Thread::Current();
2976 StackHandleScope<1> hs(self);
2977 Handle<mirror::Throwable> pending_exception(hs.NewHandle(self->GetException()));
2978 self->ClearException();
Andreas Gampefa4333d2017-02-14 11:10:34 -08002979 if (kIsDebugBuild && pending_exception != nullptr) {
Mathieu Chartier808c7a52017-12-15 11:19:33 -08002980 const Instruction& instr = location.method->DexInstructions().InstructionAt(location.dex_pc);
2981 CHECK_EQ(Instruction::MOVE_EXCEPTION, instr.Opcode());
Sebastien Hertzde48aa62015-05-26 11:53:39 +02002982 }
2983
Sebastien Hertz6995c602014-09-09 12:10:13 +02002984 gJdwpState->PostLocationEvent(&location, this_object, event_flags, return_value);
Sebastien Hertzde48aa62015-05-26 11:53:39 +02002985
Andreas Gampefa4333d2017-02-14 11:10:34 -08002986 if (pending_exception != nullptr) {
Sebastien Hertzde48aa62015-05-26 11:53:39 +02002987 self->SetException(pending_exception.Get());
2988 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002989}
2990
Mathieu Chartiere401d142015-04-22 13:56:20 -07002991void Dbg::PostFieldAccessEvent(ArtMethod* m, int dex_pc,
Mathieu Chartierc7853442015-03-27 14:35:38 -07002992 mirror::Object* this_object, ArtField* f) {
Alex Lighte00ec302017-06-16 08:56:43 -07002993 // TODO We should send events for native methods.
2994 if (!IsDebuggerActive() || m->IsNative()) {
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002995 return;
2996 }
2997 DCHECK(m != nullptr);
2998 DCHECK(f != nullptr);
Sebastien Hertz6995c602014-09-09 12:10:13 +02002999 JDWP::EventLocation location;
3000 SetEventLocation(&location, m, dex_pc);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02003001
Sebastien Hertz6995c602014-09-09 12:10:13 +02003002 gJdwpState->PostFieldEvent(&location, f, this_object, nullptr, false);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02003003}
3004
Mathieu Chartiere401d142015-04-22 13:56:20 -07003005void Dbg::PostFieldModificationEvent(ArtMethod* m, int dex_pc,
Mathieu Chartierc7853442015-03-27 14:35:38 -07003006 mirror::Object* this_object, ArtField* f,
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02003007 const JValue* field_value) {
Alex Lighte00ec302017-06-16 08:56:43 -07003008 // TODO We should send events for native methods.
3009 if (!IsDebuggerActive() || m->IsNative()) {
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02003010 return;
3011 }
3012 DCHECK(m != nullptr);
3013 DCHECK(f != nullptr);
3014 DCHECK(field_value != nullptr);
Sebastien Hertz6995c602014-09-09 12:10:13 +02003015 JDWP::EventLocation location;
3016 SetEventLocation(&location, m, dex_pc);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02003017
Sebastien Hertz6995c602014-09-09 12:10:13 +02003018 gJdwpState->PostFieldEvent(&location, f, this_object, field_value, true);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02003019}
3020
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003021/**
3022 * Finds the location where this exception will be caught. We search until we reach the top
3023 * frame, in which case this exception is considered uncaught.
3024 */
3025class CatchLocationFinder : public StackVisitor {
3026 public:
3027 CatchLocationFinder(Thread* self, const Handle<mirror::Throwable>& exception, Context* context)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003028 REQUIRES_SHARED(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01003029 : StackVisitor(self, context, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003030 exception_(exception),
3031 handle_scope_(self),
3032 this_at_throw_(handle_scope_.NewHandle<mirror::Object>(nullptr)),
Mathieu Chartiere401d142015-04-22 13:56:20 -07003033 catch_method_(nullptr),
3034 throw_method_(nullptr),
Andreas Gampee2abbc62017-09-15 11:59:26 -07003035 catch_dex_pc_(dex::kDexNoIndex),
3036 throw_dex_pc_(dex::kDexNoIndex) {
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003037 }
3038
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003039 bool VisitFrame() OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003040 ArtMethod* method = GetMethod();
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003041 DCHECK(method != nullptr);
3042 if (method->IsRuntimeMethod()) {
3043 // Ignore callee save method.
3044 DCHECK(method->IsCalleeSaveMethod());
3045 return true;
3046 }
3047
3048 uint32_t dex_pc = GetDexPc();
Mathieu Chartiere401d142015-04-22 13:56:20 -07003049 if (throw_method_ == nullptr) {
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003050 // First Java method found. It is either the method that threw the exception,
3051 // or the Java native method that is reporting an exception thrown by
3052 // native code.
3053 this_at_throw_.Assign(GetThisObject());
Mathieu Chartiere401d142015-04-22 13:56:20 -07003054 throw_method_ = method;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003055 throw_dex_pc_ = dex_pc;
3056 }
3057
Andreas Gampee2abbc62017-09-15 11:59:26 -07003058 if (dex_pc != dex::kDexNoIndex) {
Sebastien Hertz26f72862015-09-15 09:52:07 +02003059 StackHandleScope<1> hs(GetThread());
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003060 uint32_t found_dex_pc;
3061 Handle<mirror::Class> exception_class(hs.NewHandle(exception_->GetClass()));
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003062 bool unused_clear_exception;
Mathieu Chartiere401d142015-04-22 13:56:20 -07003063 found_dex_pc = method->FindCatchBlock(exception_class, dex_pc, &unused_clear_exception);
Andreas Gampee2abbc62017-09-15 11:59:26 -07003064 if (found_dex_pc != dex::kDexNoIndex) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003065 catch_method_ = method;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003066 catch_dex_pc_ = found_dex_pc;
3067 return false; // End stack walk.
3068 }
3069 }
3070 return true; // Continue stack walk.
3071 }
3072
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003073 ArtMethod* GetCatchMethod() REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003074 return catch_method_;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003075 }
3076
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003077 ArtMethod* GetThrowMethod() REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003078 return throw_method_;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003079 }
3080
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003081 mirror::Object* GetThisAtThrow() REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003082 return this_at_throw_.Get();
3083 }
3084
3085 uint32_t GetCatchDexPc() const {
3086 return catch_dex_pc_;
3087 }
3088
3089 uint32_t GetThrowDexPc() const {
3090 return throw_dex_pc_;
3091 }
3092
3093 private:
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003094 const Handle<mirror::Throwable>& exception_;
Mathieu Chartiere401d142015-04-22 13:56:20 -07003095 StackHandleScope<1> handle_scope_;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003096 MutableHandle<mirror::Object> this_at_throw_;
Mathieu Chartiere401d142015-04-22 13:56:20 -07003097 ArtMethod* catch_method_;
3098 ArtMethod* throw_method_;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003099 uint32_t catch_dex_pc_;
3100 uint32_t throw_dex_pc_;
3101
3102 DISALLOW_COPY_AND_ASSIGN(CatchLocationFinder);
3103};
3104
3105void Dbg::PostException(mirror::Throwable* exception_object) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07003106 if (!IsDebuggerActive()) {
Ian Rogers0ad5bb82011-12-07 10:16:32 -08003107 return;
3108 }
Sebastien Hertz261bc042015-04-08 09:36:07 +02003109 Thread* const self = Thread::Current();
3110 StackHandleScope<1> handle_scope(self);
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003111 Handle<mirror::Throwable> h_exception(handle_scope.NewHandle(exception_object));
3112 std::unique_ptr<Context> context(Context::Create());
Sebastien Hertz261bc042015-04-08 09:36:07 +02003113 CatchLocationFinder clf(self, h_exception, context.get());
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003114 clf.WalkStack(/* include_transitions */ false);
Sebastien Hertz6995c602014-09-09 12:10:13 +02003115 JDWP::EventLocation exception_throw_location;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003116 SetEventLocation(&exception_throw_location, clf.GetThrowMethod(), clf.GetThrowDexPc());
Sebastien Hertz6995c602014-09-09 12:10:13 +02003117 JDWP::EventLocation exception_catch_location;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003118 SetEventLocation(&exception_catch_location, clf.GetCatchMethod(), clf.GetCatchDexPc());
Elliott Hughes4740cdf2011-12-07 14:07:12 -08003119
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003120 gJdwpState->PostException(&exception_throw_location, h_exception.Get(), &exception_catch_location,
3121 clf.GetThisAtThrow());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003122}
3123
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003124void Dbg::PostClassPrepare(mirror::Class* c) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07003125 if (!IsDebuggerActive()) {
Elliott Hughes4740cdf2011-12-07 14:07:12 -08003126 return;
3127 }
Sebastien Hertz6995c602014-09-09 12:10:13 +02003128 gJdwpState->PostClassPrepare(c);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003129}
3130
Ian Rogers62d6c772013-02-27 08:32:07 -08003131void Dbg::UpdateDebugger(Thread* thread, mirror::Object* this_object,
Mathieu Chartiere401d142015-04-22 13:56:20 -07003132 ArtMethod* m, uint32_t dex_pc,
Sebastien Hertz8379b222014-02-24 17:38:15 +01003133 int event_flags, const JValue* return_value) {
Ian Rogers62d6c772013-02-27 08:32:07 -08003134 if (!IsDebuggerActive() || dex_pc == static_cast<uint32_t>(-2) /* fake method exit */) {
Elliott Hughes2aa2e392012-02-17 17:15:43 -08003135 return;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003136 }
3137
Elliott Hughes86964332012-02-15 19:37:42 -08003138 if (IsBreakpoint(m, dex_pc)) {
3139 event_flags |= kBreakpoint;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003140 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003141
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003142 // If the debugger is single-stepping one of our threads, check to
3143 // see if we're that thread and we've reached a step point.
3144 const SingleStepControl* single_step_control = thread->GetSingleStepControl();
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003145 if (single_step_control != nullptr) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003146 CHECK(!m->IsNative());
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003147 if (single_step_control->GetStepDepth() == JDWP::SD_INTO) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003148 // Step into method calls. We break when the line number
3149 // or method pointer changes. If we're in SS_MIN mode, we
3150 // always stop.
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003151 if (single_step_control->GetMethod() != m) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003152 event_flags |= kSingleStep;
3153 VLOG(jdwp) << "SS new method";
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003154 } else if (single_step_control->GetStepSize() == JDWP::SS_MIN) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003155 event_flags |= kSingleStep;
3156 VLOG(jdwp) << "SS new instruction";
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003157 } else if (single_step_control->ContainsDexPc(dex_pc)) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003158 event_flags |= kSingleStep;
3159 VLOG(jdwp) << "SS new line";
3160 }
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003161 } else if (single_step_control->GetStepDepth() == JDWP::SD_OVER) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003162 // Step over method calls. We break when the line number is
3163 // different and the frame depth is <= the original frame
3164 // depth. (We can't just compare on the method, because we
3165 // might get unrolled past it by an exception, and it's tricky
3166 // to identify recursion.)
3167
3168 int stack_depth = GetStackDepth(thread);
3169
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003170 if (stack_depth < single_step_control->GetStackDepth()) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003171 // Popped up one or more frames, always trigger.
3172 event_flags |= kSingleStep;
3173 VLOG(jdwp) << "SS method pop";
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003174 } else if (stack_depth == single_step_control->GetStackDepth()) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003175 // Same depth, see if we moved.
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003176 if (single_step_control->GetStepSize() == JDWP::SS_MIN) {
Elliott Hughes86964332012-02-15 19:37:42 -08003177 event_flags |= kSingleStep;
3178 VLOG(jdwp) << "SS new instruction";
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003179 } else if (single_step_control->ContainsDexPc(dex_pc)) {
Elliott Hughes2435a572012-02-17 16:07:41 -08003180 event_flags |= kSingleStep;
3181 VLOG(jdwp) << "SS new line";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003182 }
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003183 }
3184 } else {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003185 CHECK_EQ(single_step_control->GetStepDepth(), JDWP::SD_OUT);
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003186 // Return from the current method. We break when the frame
3187 // depth pops up.
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003188
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003189 // This differs from the "method exit" break in that it stops
3190 // with the PC at the next instruction in the returned-to
3191 // function, rather than the end of the returning function.
Elliott Hughes86964332012-02-15 19:37:42 -08003192
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003193 int stack_depth = GetStackDepth(thread);
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003194 if (stack_depth < single_step_control->GetStackDepth()) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003195 event_flags |= kSingleStep;
3196 VLOG(jdwp) << "SS method pop";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003197 }
3198 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003199 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003200
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003201 // If there's something interesting going on, see if it matches one
3202 // of the debugger filters.
3203 if (event_flags != 0) {
Sebastien Hertz8379b222014-02-24 17:38:15 +01003204 Dbg::PostLocationEvent(m, dex_pc, this_object, event_flags, return_value);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003205 }
3206}
3207
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003208size_t* Dbg::GetReferenceCounterForEvent(uint32_t instrumentation_event) {
3209 switch (instrumentation_event) {
3210 case instrumentation::Instrumentation::kMethodEntered:
3211 return &method_enter_event_ref_count_;
3212 case instrumentation::Instrumentation::kMethodExited:
3213 return &method_exit_event_ref_count_;
3214 case instrumentation::Instrumentation::kDexPcMoved:
3215 return &dex_pc_change_event_ref_count_;
3216 case instrumentation::Instrumentation::kFieldRead:
3217 return &field_read_event_ref_count_;
3218 case instrumentation::Instrumentation::kFieldWritten:
3219 return &field_write_event_ref_count_;
Alex Light6e1607e2017-08-23 10:06:18 -07003220 case instrumentation::Instrumentation::kExceptionThrown:
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003221 return &exception_catch_event_ref_count_;
3222 default:
3223 return nullptr;
3224 }
3225}
3226
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003227// Process request while all mutator threads are suspended.
3228void Dbg::ProcessDeoptimizationRequest(const DeoptimizationRequest& request) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003229 instrumentation::Instrumentation* instrumentation = Runtime::Current()->GetInstrumentation();
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003230 switch (request.GetKind()) {
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003231 case DeoptimizationRequest::kNothing:
3232 LOG(WARNING) << "Ignoring empty deoptimization request.";
3233 break;
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003234 case DeoptimizationRequest::kRegisterForEvent:
3235 VLOG(jdwp) << StringPrintf("Add debugger as listener for instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003236 request.InstrumentationEvent());
3237 instrumentation->AddListener(&gDebugInstrumentationListener, request.InstrumentationEvent());
3238 instrumentation_events_ |= request.InstrumentationEvent();
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003239 break;
3240 case DeoptimizationRequest::kUnregisterForEvent:
3241 VLOG(jdwp) << StringPrintf("Remove debugger as listener for instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003242 request.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003243 instrumentation->RemoveListener(&gDebugInstrumentationListener,
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003244 request.InstrumentationEvent());
3245 instrumentation_events_ &= ~request.InstrumentationEvent();
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003246 break;
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003247 case DeoptimizationRequest::kFullDeoptimization:
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003248 VLOG(jdwp) << "Deoptimize the world ...";
Sebastien Hertz0462c4c2015-04-01 16:34:17 +02003249 instrumentation->DeoptimizeEverything(kDbgInstrumentationKey);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003250 VLOG(jdwp) << "Deoptimize the world DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003251 break;
3252 case DeoptimizationRequest::kFullUndeoptimization:
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003253 VLOG(jdwp) << "Undeoptimize the world ...";
Sebastien Hertz0462c4c2015-04-01 16:34:17 +02003254 instrumentation->UndeoptimizeEverything(kDbgInstrumentationKey);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003255 VLOG(jdwp) << "Undeoptimize the world DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003256 break;
3257 case DeoptimizationRequest::kSelectiveDeoptimization:
David Sehr709b0702016-10-13 09:12:37 -07003258 VLOG(jdwp) << "Deoptimize method " << ArtMethod::PrettyMethod(request.Method()) << " ...";
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003259 instrumentation->Deoptimize(request.Method());
David Sehr709b0702016-10-13 09:12:37 -07003260 VLOG(jdwp) << "Deoptimize method " << ArtMethod::PrettyMethod(request.Method()) << " DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003261 break;
3262 case DeoptimizationRequest::kSelectiveUndeoptimization:
David Sehr709b0702016-10-13 09:12:37 -07003263 VLOG(jdwp) << "Undeoptimize method " << ArtMethod::PrettyMethod(request.Method()) << " ...";
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003264 instrumentation->Undeoptimize(request.Method());
David Sehr709b0702016-10-13 09:12:37 -07003265 VLOG(jdwp) << "Undeoptimize method " << ArtMethod::PrettyMethod(request.Method()) << " DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003266 break;
3267 default:
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003268 LOG(FATAL) << "Unsupported deoptimization request kind " << request.GetKind();
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003269 break;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003270 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003271}
3272
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003273void Dbg::RequestDeoptimization(const DeoptimizationRequest& req) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003274 if (req.GetKind() == DeoptimizationRequest::kNothing) {
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003275 // Nothing to do.
3276 return;
3277 }
Brian Carlstrom306db812014-09-05 13:01:41 -07003278 MutexLock mu(Thread::Current(), *Locks::deoptimization_lock_);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003279 RequestDeoptimizationLocked(req);
3280}
3281
3282void Dbg::RequestDeoptimizationLocked(const DeoptimizationRequest& req) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003283 switch (req.GetKind()) {
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003284 case DeoptimizationRequest::kRegisterForEvent: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003285 DCHECK_NE(req.InstrumentationEvent(), 0u);
3286 size_t* counter = GetReferenceCounterForEvent(req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003287 CHECK(counter != nullptr) << StringPrintf("No counter for instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003288 req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003289 if (*counter == 0) {
Sebastien Hertz7d2ae432014-05-15 11:26:34 +02003290 VLOG(jdwp) << StringPrintf("Queue request #%zd to start listening to instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003291 deoptimization_requests_.size(), req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003292 deoptimization_requests_.push_back(req);
3293 }
3294 *counter = *counter + 1;
3295 break;
3296 }
3297 case DeoptimizationRequest::kUnregisterForEvent: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003298 DCHECK_NE(req.InstrumentationEvent(), 0u);
3299 size_t* counter = GetReferenceCounterForEvent(req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003300 CHECK(counter != nullptr) << StringPrintf("No counter for instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003301 req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003302 *counter = *counter - 1;
3303 if (*counter == 0) {
Sebastien Hertz7d2ae432014-05-15 11:26:34 +02003304 VLOG(jdwp) << StringPrintf("Queue request #%zd to stop listening to instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003305 deoptimization_requests_.size(), req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003306 deoptimization_requests_.push_back(req);
3307 }
3308 break;
3309 }
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003310 case DeoptimizationRequest::kFullDeoptimization: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003311 DCHECK(req.Method() == nullptr);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003312 if (full_deoptimization_event_count_ == 0) {
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003313 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
3314 << " for full deoptimization";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003315 deoptimization_requests_.push_back(req);
3316 }
3317 ++full_deoptimization_event_count_;
3318 break;
3319 }
3320 case DeoptimizationRequest::kFullUndeoptimization: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003321 DCHECK(req.Method() == nullptr);
Sebastien Hertze713d932014-05-15 10:48:53 +02003322 DCHECK_GT(full_deoptimization_event_count_, 0U);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003323 --full_deoptimization_event_count_;
3324 if (full_deoptimization_event_count_ == 0) {
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003325 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
3326 << " for full undeoptimization";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003327 deoptimization_requests_.push_back(req);
3328 }
3329 break;
3330 }
3331 case DeoptimizationRequest::kSelectiveDeoptimization: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003332 DCHECK(req.Method() != nullptr);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003333 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
David Sehr709b0702016-10-13 09:12:37 -07003334 << " for deoptimization of " << req.Method()->PrettyMethod();
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003335 deoptimization_requests_.push_back(req);
3336 break;
3337 }
3338 case DeoptimizationRequest::kSelectiveUndeoptimization: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003339 DCHECK(req.Method() != nullptr);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003340 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
David Sehr709b0702016-10-13 09:12:37 -07003341 << " for undeoptimization of " << req.Method()->PrettyMethod();
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003342 deoptimization_requests_.push_back(req);
3343 break;
3344 }
3345 default: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003346 LOG(FATAL) << "Unknown deoptimization request kind " << req.GetKind();
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003347 break;
3348 }
3349 }
3350}
3351
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003352void Dbg::ManageDeoptimization() {
3353 Thread* const self = Thread::Current();
3354 {
3355 // Avoid suspend/resume if there is no pending request.
Brian Carlstrom306db812014-09-05 13:01:41 -07003356 MutexLock mu(self, *Locks::deoptimization_lock_);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003357 if (deoptimization_requests_.empty()) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003358 return;
3359 }
3360 }
3361 CHECK_EQ(self->GetState(), kRunnable);
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07003362 ScopedThreadSuspension sts(self, kWaitingForDeoptimization);
Mathieu Chartieraa516822015-10-02 15:53:37 -07003363 // Required for ProcessDeoptimizationRequest.
3364 gc::ScopedGCCriticalSection gcs(self,
3365 gc::kGcCauseInstrumentation,
3366 gc::kCollectorTypeInstrumentation);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003367 // We need to suspend mutator threads first.
Mathieu Chartier4f55e222015-09-04 13:26:21 -07003368 ScopedSuspendAll ssa(__FUNCTION__);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003369 const ThreadState old_state = self->SetStateUnsafe(kRunnable);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003370 {
Brian Carlstrom306db812014-09-05 13:01:41 -07003371 MutexLock mu(self, *Locks::deoptimization_lock_);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003372 size_t req_index = 0;
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003373 for (DeoptimizationRequest& request : deoptimization_requests_) {
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003374 VLOG(jdwp) << "Process deoptimization request #" << req_index++;
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003375 ProcessDeoptimizationRequest(request);
3376 }
3377 deoptimization_requests_.clear();
3378 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003379 CHECK_EQ(self->SetStateUnsafe(old_state), kRunnable);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003380}
3381
Mathieu Chartiere401d142015-04-22 13:56:20 -07003382static const Breakpoint* FindFirstBreakpointForMethod(ArtMethod* m)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003383 REQUIRES_SHARED(Locks::mutator_lock_, Locks::breakpoint_lock_) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003384 for (Breakpoint& breakpoint : gBreakpoints) {
Alex Light6c8467f2015-11-20 15:03:26 -08003385 if (breakpoint.IsInMethod(m)) {
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003386 return &breakpoint;
3387 }
3388 }
3389 return nullptr;
3390}
3391
Mathieu Chartiere401d142015-04-22 13:56:20 -07003392bool Dbg::MethodHasAnyBreakpoints(ArtMethod* method) {
Mathieu Chartierd8565452015-03-26 09:41:50 -07003393 ReaderMutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
3394 return FindFirstBreakpointForMethod(method) != nullptr;
3395}
3396
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003397// Sanity checks all existing breakpoints on the same method.
Mathieu Chartiere401d142015-04-22 13:56:20 -07003398static void SanityCheckExistingBreakpoints(ArtMethod* m,
Sebastien Hertzf3928792014-11-17 19:00:37 +01003399 DeoptimizationRequest::Kind deoptimization_kind)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003400 REQUIRES_SHARED(Locks::mutator_lock_, Locks::breakpoint_lock_) {
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003401 for (const Breakpoint& breakpoint : gBreakpoints) {
Alex Light6c8467f2015-11-20 15:03:26 -08003402 if (breakpoint.IsInMethod(m)) {
Sebastien Hertzf3928792014-11-17 19:00:37 +01003403 CHECK_EQ(deoptimization_kind, breakpoint.GetDeoptimizationKind());
3404 }
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003405 }
Sebastien Hertzf3928792014-11-17 19:00:37 +01003406 instrumentation::Instrumentation* instrumentation = Runtime::Current()->GetInstrumentation();
3407 if (deoptimization_kind == DeoptimizationRequest::kFullDeoptimization) {
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003408 // We should have deoptimized everything but not "selectively" deoptimized this method.
Sebastien Hertzf3928792014-11-17 19:00:37 +01003409 CHECK(instrumentation->AreAllMethodsDeoptimized());
3410 CHECK(!instrumentation->IsDeoptimized(m));
3411 } else if (deoptimization_kind == DeoptimizationRequest::kSelectiveDeoptimization) {
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003412 // We should have "selectively" deoptimized this method.
3413 // Note: while we have not deoptimized everything for this method, we may have done it for
3414 // another event.
Sebastien Hertzf3928792014-11-17 19:00:37 +01003415 CHECK(instrumentation->IsDeoptimized(m));
3416 } else {
3417 // This method does not require deoptimization.
3418 CHECK_EQ(deoptimization_kind, DeoptimizationRequest::kNothing);
3419 CHECK(!instrumentation->IsDeoptimized(m));
3420 }
3421}
3422
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003423// Returns the deoptimization kind required to set a breakpoint in a method.
3424// If a breakpoint has already been set, we also return the first breakpoint
3425// through the given 'existing_brkpt' pointer.
Sebastien Hertzf3928792014-11-17 19:00:37 +01003426static DeoptimizationRequest::Kind GetRequiredDeoptimizationKind(Thread* self,
Mathieu Chartiere401d142015-04-22 13:56:20 -07003427 ArtMethod* m,
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003428 const Breakpoint** existing_brkpt)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003429 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertzf3928792014-11-17 19:00:37 +01003430 if (!Dbg::RequiresDeoptimization()) {
3431 // We already run in interpreter-only mode so we don't need to deoptimize anything.
3432 VLOG(jdwp) << "No need for deoptimization when fully running with interpreter for method "
David Sehr709b0702016-10-13 09:12:37 -07003433 << ArtMethod::PrettyMethod(m);
Sebastien Hertzf3928792014-11-17 19:00:37 +01003434 return DeoptimizationRequest::kNothing;
3435 }
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003436 const Breakpoint* first_breakpoint;
Sebastien Hertzf3928792014-11-17 19:00:37 +01003437 {
3438 ReaderMutexLock mu(self, *Locks::breakpoint_lock_);
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003439 first_breakpoint = FindFirstBreakpointForMethod(m);
3440 *existing_brkpt = first_breakpoint;
Sebastien Hertzf3928792014-11-17 19:00:37 +01003441 }
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003442
3443 if (first_breakpoint == nullptr) {
Nicolas Geoffray6300fd72016-03-18 09:40:17 +00003444 // There is no breakpoint on this method yet: we need to deoptimize. If this method is default,
3445 // we deoptimize everything; otherwise we deoptimize only this method. We
Alex Light6c8467f2015-11-20 15:03:26 -08003446 // deoptimize with defaults because we do not know everywhere they are used. It is possible some
Nicolas Geoffray6300fd72016-03-18 09:40:17 +00003447 // of the copies could be missed.
Alex Light6c8467f2015-11-20 15:03:26 -08003448 // TODO Deoptimizing on default methods might not be necessary in all cases.
Nicolas Geoffray6300fd72016-03-18 09:40:17 +00003449 bool need_full_deoptimization = m->IsDefault();
Sebastien Hertzf3928792014-11-17 19:00:37 +01003450 if (need_full_deoptimization) {
Nicolas Geoffray6300fd72016-03-18 09:40:17 +00003451 VLOG(jdwp) << "Need full deoptimization because of copying of method "
David Sehr709b0702016-10-13 09:12:37 -07003452 << ArtMethod::PrettyMethod(m);
Sebastien Hertzf3928792014-11-17 19:00:37 +01003453 return DeoptimizationRequest::kFullDeoptimization;
3454 } else {
3455 // We don't need to deoptimize if the method has not been compiled.
Nicolas Geoffraya5891e82015-11-06 14:18:27 +00003456 const bool is_compiled = m->HasAnyCompiledCode();
Sebastien Hertzf3928792014-11-17 19:00:37 +01003457 if (is_compiled) {
David Sehr709b0702016-10-13 09:12:37 -07003458 VLOG(jdwp) << "Need selective deoptimization for compiled method "
3459 << ArtMethod::PrettyMethod(m);
Nicolas Geoffray6300fd72016-03-18 09:40:17 +00003460 return DeoptimizationRequest::kSelectiveDeoptimization;
Sebastien Hertzf3928792014-11-17 19:00:37 +01003461 } else {
3462 // Method is not compiled: we don't need to deoptimize.
David Sehr709b0702016-10-13 09:12:37 -07003463 VLOG(jdwp) << "No need for deoptimization for non-compiled method "
3464 << ArtMethod::PrettyMethod(m);
Sebastien Hertzf3928792014-11-17 19:00:37 +01003465 return DeoptimizationRequest::kNothing;
3466 }
3467 }
3468 } else {
3469 // There is at least one breakpoint for this method: we don't need to deoptimize.
3470 // Let's check that all breakpoints are configured the same way for deoptimization.
3471 VLOG(jdwp) << "Breakpoint already set: no deoptimization is required";
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003472 DeoptimizationRequest::Kind deoptimization_kind = first_breakpoint->GetDeoptimizationKind();
Sebastien Hertzf3928792014-11-17 19:00:37 +01003473 if (kIsDebugBuild) {
3474 ReaderMutexLock mu(self, *Locks::breakpoint_lock_);
3475 SanityCheckExistingBreakpoints(m, deoptimization_kind);
3476 }
3477 return DeoptimizationRequest::kNothing;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003478 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003479}
3480
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003481// Installs a breakpoint at the specified location. Also indicates through the deoptimization
3482// request if we need to deoptimize.
3483void Dbg::WatchLocation(const JDWP::JdwpLocation* location, DeoptimizationRequest* req) {
3484 Thread* const self = Thread::Current();
Mathieu Chartiere401d142015-04-22 13:56:20 -07003485 ArtMethod* m = FromMethodId(location->method_id);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003486 DCHECK(m != nullptr) << "No method for method id " << location->method_id;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003487
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003488 const Breakpoint* existing_breakpoint = nullptr;
3489 const DeoptimizationRequest::Kind deoptimization_kind =
3490 GetRequiredDeoptimizationKind(self, m, &existing_breakpoint);
Sebastien Hertzf3928792014-11-17 19:00:37 +01003491 req->SetKind(deoptimization_kind);
3492 if (deoptimization_kind == DeoptimizationRequest::kSelectiveDeoptimization) {
3493 req->SetMethod(m);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003494 } else {
Sebastien Hertzf3928792014-11-17 19:00:37 +01003495 CHECK(deoptimization_kind == DeoptimizationRequest::kNothing ||
3496 deoptimization_kind == DeoptimizationRequest::kFullDeoptimization);
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003497 req->SetMethod(nullptr);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003498 }
3499
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003500 {
3501 WriterMutexLock mu(self, *Locks::breakpoint_lock_);
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003502 // If there is at least one existing breakpoint on the same method, the new breakpoint
3503 // must have the same deoptimization kind than the existing breakpoint(s).
3504 DeoptimizationRequest::Kind breakpoint_deoptimization_kind;
3505 if (existing_breakpoint != nullptr) {
3506 breakpoint_deoptimization_kind = existing_breakpoint->GetDeoptimizationKind();
3507 } else {
3508 breakpoint_deoptimization_kind = deoptimization_kind;
3509 }
3510 gBreakpoints.push_back(Breakpoint(m, location->dex_pc, breakpoint_deoptimization_kind));
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003511 VLOG(jdwp) << "Set breakpoint #" << (gBreakpoints.size() - 1) << ": "
3512 << gBreakpoints[gBreakpoints.size() - 1];
3513 }
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003514}
3515
3516// Uninstalls a breakpoint at the specified location. Also indicates through the deoptimization
3517// request if we need to undeoptimize.
3518void Dbg::UnwatchLocation(const JDWP::JdwpLocation* location, DeoptimizationRequest* req) {
Sebastien Hertzed2be172014-08-19 15:33:43 +02003519 WriterMutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003520 ArtMethod* m = FromMethodId(location->method_id);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003521 DCHECK(m != nullptr) << "No method for method id " << location->method_id;
Sebastien Hertzf3928792014-11-17 19:00:37 +01003522 DeoptimizationRequest::Kind deoptimization_kind = DeoptimizationRequest::kNothing;
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003523 for (size_t i = 0, e = gBreakpoints.size(); i < e; ++i) {
Alex Light6c8467f2015-11-20 15:03:26 -08003524 if (gBreakpoints[i].DexPc() == location->dex_pc && gBreakpoints[i].IsInMethod(m)) {
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003525 VLOG(jdwp) << "Removed breakpoint #" << i << ": " << gBreakpoints[i];
Sebastien Hertzf3928792014-11-17 19:00:37 +01003526 deoptimization_kind = gBreakpoints[i].GetDeoptimizationKind();
3527 DCHECK_EQ(deoptimization_kind == DeoptimizationRequest::kSelectiveDeoptimization,
3528 Runtime::Current()->GetInstrumentation()->IsDeoptimized(m));
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003529 gBreakpoints.erase(gBreakpoints.begin() + i);
3530 break;
3531 }
3532 }
3533 const Breakpoint* const existing_breakpoint = FindFirstBreakpointForMethod(m);
3534 if (existing_breakpoint == nullptr) {
3535 // There is no more breakpoint on this method: we need to undeoptimize.
Sebastien Hertzf3928792014-11-17 19:00:37 +01003536 if (deoptimization_kind == DeoptimizationRequest::kFullDeoptimization) {
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003537 // This method required full deoptimization: we need to undeoptimize everything.
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003538 req->SetKind(DeoptimizationRequest::kFullUndeoptimization);
3539 req->SetMethod(nullptr);
Sebastien Hertzf3928792014-11-17 19:00:37 +01003540 } else if (deoptimization_kind == DeoptimizationRequest::kSelectiveDeoptimization) {
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003541 // This method required selective deoptimization: we need to undeoptimize only that method.
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003542 req->SetKind(DeoptimizationRequest::kSelectiveUndeoptimization);
3543 req->SetMethod(m);
Sebastien Hertzf3928792014-11-17 19:00:37 +01003544 } else {
3545 // This method had no need for deoptimization: do nothing.
3546 CHECK_EQ(deoptimization_kind, DeoptimizationRequest::kNothing);
3547 req->SetKind(DeoptimizationRequest::kNothing);
3548 req->SetMethod(nullptr);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003549 }
3550 } else {
3551 // There is at least one breakpoint for this method: we don't need to undeoptimize.
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003552 req->SetKind(DeoptimizationRequest::kNothing);
3553 req->SetMethod(nullptr);
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003554 if (kIsDebugBuild) {
Sebastien Hertzf3928792014-11-17 19:00:37 +01003555 SanityCheckExistingBreakpoints(m, deoptimization_kind);
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003556 }
Elliott Hughes86964332012-02-15 19:37:42 -08003557 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003558}
3559
Mathieu Chartiere401d142015-04-22 13:56:20 -07003560bool Dbg::IsForcedInterpreterNeededForCallingImpl(Thread* thread, ArtMethod* m) {
Daniel Mihalyieb076692014-08-22 17:33:31 +02003561 const SingleStepControl* const ssc = thread->GetSingleStepControl();
3562 if (ssc == nullptr) {
3563 // If we are not single-stepping, then we don't have to force interpreter.
3564 return false;
3565 }
3566 if (Runtime::Current()->GetInstrumentation()->InterpretOnly()) {
3567 // If we are in interpreter only mode, then we don't have to force interpreter.
3568 return false;
3569 }
3570
3571 if (!m->IsNative() && !m->IsProxyMethod()) {
3572 // If we want to step into a method, then we have to force interpreter on that call.
3573 if (ssc->GetStepDepth() == JDWP::SD_INTO) {
3574 return true;
3575 }
3576 }
3577 return false;
3578}
3579
Mathieu Chartiere401d142015-04-22 13:56:20 -07003580bool Dbg::IsForcedInterpreterNeededForResolutionImpl(Thread* thread, ArtMethod* m) {
Daniel Mihalyieb076692014-08-22 17:33:31 +02003581 instrumentation::Instrumentation* const instrumentation =
3582 Runtime::Current()->GetInstrumentation();
3583 // If we are in interpreter only mode, then we don't have to force interpreter.
3584 if (instrumentation->InterpretOnly()) {
3585 return false;
3586 }
3587 // We can only interpret pure Java method.
3588 if (m->IsNative() || m->IsProxyMethod()) {
3589 return false;
3590 }
3591 const SingleStepControl* const ssc = thread->GetSingleStepControl();
3592 if (ssc != nullptr) {
3593 // If we want to step into a method, then we have to force interpreter on that call.
3594 if (ssc->GetStepDepth() == JDWP::SD_INTO) {
3595 return true;
3596 }
3597 // If we are stepping out from a static initializer, by issuing a step
3598 // in or step over, that was implicitly invoked by calling a static method,
3599 // then we need to step into that method. Having a lower stack depth than
3600 // the one the single step control has indicates that the step originates
3601 // from the static initializer.
3602 if (ssc->GetStepDepth() != JDWP::SD_OUT &&
3603 ssc->GetStackDepth() > GetStackDepth(thread)) {
3604 return true;
3605 }
3606 }
3607 // There are cases where we have to force interpreter on deoptimized methods,
3608 // because in some cases the call will not be performed by invoking an entry
3609 // point that has been replaced by the deoptimization, but instead by directly
3610 // invoking the compiled code of the method, for example.
3611 return instrumentation->IsDeoptimized(m);
3612}
3613
Mathieu Chartiere401d142015-04-22 13:56:20 -07003614bool Dbg::IsForcedInstrumentationNeededForResolutionImpl(Thread* thread, ArtMethod* m) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07003615 // The upcall can be null and in that case we don't need to do anything.
Daniel Mihalyieb076692014-08-22 17:33:31 +02003616 if (m == nullptr) {
3617 return false;
3618 }
3619 instrumentation::Instrumentation* const instrumentation =
3620 Runtime::Current()->GetInstrumentation();
3621 // If we are in interpreter only mode, then we don't have to force interpreter.
3622 if (instrumentation->InterpretOnly()) {
3623 return false;
3624 }
3625 // We can only interpret pure Java method.
3626 if (m->IsNative() || m->IsProxyMethod()) {
3627 return false;
3628 }
3629 const SingleStepControl* const ssc = thread->GetSingleStepControl();
3630 if (ssc != nullptr) {
3631 // If we are stepping out from a static initializer, by issuing a step
3632 // out, that was implicitly invoked by calling a static method, then we
3633 // need to step into the caller of that method. Having a lower stack
3634 // depth than the one the single step control has indicates that the
3635 // step originates from the static initializer.
3636 if (ssc->GetStepDepth() == JDWP::SD_OUT &&
3637 ssc->GetStackDepth() > GetStackDepth(thread)) {
3638 return true;
3639 }
3640 }
3641 // If we are returning from a static intializer, that was implicitly
3642 // invoked by calling a static method and the caller is deoptimized,
3643 // then we have to deoptimize the stack without forcing interpreter
3644 // on the static method that was called originally. This problem can
3645 // be solved easily by forcing instrumentation on the called method,
3646 // because the instrumentation exit hook will recognise the need of
3647 // stack deoptimization by calling IsForcedInterpreterNeededForUpcall.
3648 return instrumentation->IsDeoptimized(m);
3649}
3650
Mathieu Chartiere401d142015-04-22 13:56:20 -07003651bool Dbg::IsForcedInterpreterNeededForUpcallImpl(Thread* thread, ArtMethod* m) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07003652 // The upcall can be null and in that case we don't need to do anything.
Daniel Mihalyieb076692014-08-22 17:33:31 +02003653 if (m == nullptr) {
3654 return false;
3655 }
3656 instrumentation::Instrumentation* const instrumentation =
3657 Runtime::Current()->GetInstrumentation();
3658 // If we are in interpreter only mode, then we don't have to force interpreter.
3659 if (instrumentation->InterpretOnly()) {
3660 return false;
3661 }
3662 // We can only interpret pure Java method.
3663 if (m->IsNative() || m->IsProxyMethod()) {
3664 return false;
3665 }
3666 const SingleStepControl* const ssc = thread->GetSingleStepControl();
3667 if (ssc != nullptr) {
3668 // The debugger is not interested in what is happening under the level
3669 // of the step, thus we only force interpreter when we are not below of
3670 // the step.
3671 if (ssc->GetStackDepth() >= GetStackDepth(thread)) {
3672 return true;
3673 }
3674 }
Mingyao Yang99170c62015-07-06 11:10:37 -07003675 if (thread->HasDebuggerShadowFrames()) {
3676 // We need to deoptimize the stack for the exception handling flow so that
3677 // we don't miss any deoptimization that should be done when there are
3678 // debugger shadow frames.
3679 return true;
3680 }
Daniel Mihalyieb076692014-08-22 17:33:31 +02003681 // We have to require stack deoptimization if the upcall is deoptimized.
3682 return instrumentation->IsDeoptimized(m);
3683}
3684
Mingyao Yang99170c62015-07-06 11:10:37 -07003685class NeedsDeoptimizationVisitor : public StackVisitor {
Sebastien Hertz520633b2015-09-08 17:03:36 +02003686 public:
3687 explicit NeedsDeoptimizationVisitor(Thread* self)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003688 REQUIRES_SHARED(Locks::mutator_lock_)
Sebastien Hertz520633b2015-09-08 17:03:36 +02003689 : StackVisitor(self, nullptr, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
3690 needs_deoptimization_(false) {}
3691
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003692 bool VisitFrame() OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz520633b2015-09-08 17:03:36 +02003693 // The visitor is meant to be used when handling exception from compiled code only.
David Sehr709b0702016-10-13 09:12:37 -07003694 CHECK(!IsShadowFrame()) << "We only expect to visit compiled frame: "
3695 << ArtMethod::PrettyMethod(GetMethod());
Sebastien Hertz520633b2015-09-08 17:03:36 +02003696 ArtMethod* method = GetMethod();
3697 if (method == nullptr) {
3698 // We reach an upcall and don't need to deoptimize this part of the stack (ManagedFragment)
3699 // so we can stop the visit.
3700 DCHECK(!needs_deoptimization_);
3701 return false;
3702 }
3703 if (Runtime::Current()->GetInstrumentation()->InterpretOnly()) {
3704 // We found a compiled frame in the stack but instrumentation is set to interpret
3705 // everything: we need to deoptimize.
3706 needs_deoptimization_ = true;
3707 return false;
3708 }
3709 if (Runtime::Current()->GetInstrumentation()->IsDeoptimized(method)) {
3710 // We found a deoptimized method in the stack.
3711 needs_deoptimization_ = true;
3712 return false;
3713 }
Mingyao Yang99170c62015-07-06 11:10:37 -07003714 ShadowFrame* frame = GetThread()->FindDebuggerShadowFrame(GetFrameId());
3715 if (frame != nullptr) {
3716 // The debugger allocated a ShadowFrame to update a variable in the stack: we need to
3717 // deoptimize the stack to execute (and deallocate) this frame.
3718 needs_deoptimization_ = true;
3719 return false;
3720 }
Sebastien Hertz520633b2015-09-08 17:03:36 +02003721 return true;
3722 }
3723
3724 bool NeedsDeoptimization() const {
3725 return needs_deoptimization_;
3726 }
3727
3728 private:
3729 // Do we need to deoptimize the stack?
3730 bool needs_deoptimization_;
3731
3732 DISALLOW_COPY_AND_ASSIGN(NeedsDeoptimizationVisitor);
3733};
3734
3735// Do we need to deoptimize the stack to handle an exception?
3736bool Dbg::IsForcedInterpreterNeededForExceptionImpl(Thread* thread) {
3737 const SingleStepControl* const ssc = thread->GetSingleStepControl();
3738 if (ssc != nullptr) {
3739 // We deopt to step into the catch handler.
3740 return true;
3741 }
3742 // Deoptimization is required if at least one method in the stack needs it. However we
3743 // skip frames that will be unwound (thus not executed).
3744 NeedsDeoptimizationVisitor visitor(thread);
3745 visitor.WalkStack(true); // includes upcall.
3746 return visitor.NeedsDeoptimization();
3747}
3748
Jeff Hao449db332013-04-12 18:30:52 -07003749// Scoped utility class to suspend a thread so that we may do tasks such as walk its stack. Doesn't
3750// cause suspension if the thread is the current thread.
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07003751class ScopedDebuggerThreadSuspension {
Jeff Hao449db332013-04-12 18:30:52 -07003752 public:
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07003753 ScopedDebuggerThreadSuspension(Thread* self, JDWP::ObjectId thread_id)
Mathieu Chartier90443472015-07-16 20:32:27 -07003754 REQUIRES(!Locks::thread_list_lock_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003755 REQUIRES_SHARED(Locks::mutator_lock_) :
Ian Rogersf3d874c2014-07-17 18:52:42 -07003756 thread_(nullptr),
Jeff Hao449db332013-04-12 18:30:52 -07003757 error_(JDWP::ERR_NONE),
3758 self_suspend_(false),
Ian Rogers33e95662013-05-20 20:29:14 -07003759 other_suspend_(false) {
Jeff Hao449db332013-04-12 18:30:52 -07003760 ScopedObjectAccessUnchecked soa(self);
Sebastien Hertz69206392015-04-07 15:54:25 +02003761 thread_ = DecodeThread(soa, thread_id, &error_);
Jeff Hao449db332013-04-12 18:30:52 -07003762 if (error_ == JDWP::ERR_NONE) {
3763 if (thread_ == soa.Self()) {
3764 self_suspend_ = true;
3765 } else {
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07003766 Thread* suspended_thread;
3767 {
3768 ScopedThreadSuspension sts(self, kWaitingForDebuggerSuspension);
3769 jobject thread_peer = Dbg::GetObjectRegistry()->GetJObject(thread_id);
3770 bool timed_out;
3771 ThreadList* const thread_list = Runtime::Current()->GetThreadList();
Sebastien Hertzcdd798d2017-04-18 18:28:51 +02003772 suspended_thread = thread_list->SuspendThreadByPeer(thread_peer,
3773 /* request_suspension */ true,
Alex Light46f93402017-06-29 11:59:50 -07003774 SuspendReason::kForDebugger,
Sebastien Hertzcdd798d2017-04-18 18:28:51 +02003775 &timed_out);
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07003776 }
Ian Rogersf3d874c2014-07-17 18:52:42 -07003777 if (suspended_thread == nullptr) {
Jeff Hao449db332013-04-12 18:30:52 -07003778 // Thread terminated from under us while suspending.
3779 error_ = JDWP::ERR_INVALID_THREAD;
3780 } else {
3781 CHECK_EQ(suspended_thread, thread_);
3782 other_suspend_ = true;
3783 }
3784 }
3785 }
Elliott Hughes2435a572012-02-17 16:07:41 -08003786 }
Elliott Hughes86964332012-02-15 19:37:42 -08003787
Jeff Hao449db332013-04-12 18:30:52 -07003788 Thread* GetThread() const {
3789 return thread_;
3790 }
3791
3792 JDWP::JdwpError GetError() const {
3793 return error_;
3794 }
3795
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07003796 ~ScopedDebuggerThreadSuspension() {
Jeff Hao449db332013-04-12 18:30:52 -07003797 if (other_suspend_) {
Alex Light88fd7202017-06-30 08:31:59 -07003798 bool resumed = Runtime::Current()->GetThreadList()->Resume(thread_,
3799 SuspendReason::kForDebugger);
3800 DCHECK(resumed);
Jeff Hao449db332013-04-12 18:30:52 -07003801 }
3802 }
3803
3804 private:
3805 Thread* thread_;
3806 JDWP::JdwpError error_;
3807 bool self_suspend_;
3808 bool other_suspend_;
3809};
3810
3811JDWP::JdwpError Dbg::ConfigureStep(JDWP::ObjectId thread_id, JDWP::JdwpStepSize step_size,
3812 JDWP::JdwpStepDepth step_depth) {
3813 Thread* self = Thread::Current();
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07003814 ScopedDebuggerThreadSuspension sts(self, thread_id);
Jeff Hao449db332013-04-12 18:30:52 -07003815 if (sts.GetError() != JDWP::ERR_NONE) {
3816 return sts.GetError();
3817 }
3818
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003819 // Work out what ArtMethod* we're in, the current line number, and how deep the stack currently
Elliott Hughes2435a572012-02-17 16:07:41 -08003820 // is for step-out.
Ian Rogers0399dde2012-06-06 17:09:28 -07003821 struct SingleStepStackVisitor : public StackVisitor {
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003822 explicit SingleStepStackVisitor(Thread* thread) REQUIRES_SHARED(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01003823 : StackVisitor(thread, nullptr, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
3824 stack_depth(0),
3825 method(nullptr),
3826 line_number(-1) {}
Ian Rogersca190662012-06-26 15:45:57 -07003827
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003828 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
3829 // annotalysis.
3830 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003831 ArtMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07003832 if (!m->IsRuntimeMethod()) {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003833 ++stack_depth;
3834 if (method == nullptr) {
Alex Light73376312017-04-06 10:10:51 -07003835 const DexFile* dex_file = m->GetDexFile();
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003836 method = m;
Alex Light73376312017-04-06 10:10:51 -07003837 if (dex_file != nullptr) {
David Sehr9323e6e2016-09-13 08:58:35 -07003838 line_number = annotations::GetLineNumFromPC(dex_file, m, GetDexPc());
Elliott Hughes2435a572012-02-17 16:07:41 -08003839 }
Elliott Hughes86964332012-02-15 19:37:42 -08003840 }
3841 }
Elliott Hughes530fa002012-03-12 11:44:49 -07003842 return true;
Elliott Hughes86964332012-02-15 19:37:42 -08003843 }
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003844
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003845 int stack_depth;
Mathieu Chartiere401d142015-04-22 13:56:20 -07003846 ArtMethod* method;
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003847 int32_t line_number;
Elliott Hughes86964332012-02-15 19:37:42 -08003848 };
Jeff Hao449db332013-04-12 18:30:52 -07003849
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003850 Thread* const thread = sts.GetThread();
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003851 SingleStepStackVisitor visitor(thread);
Ian Rogers0399dde2012-06-06 17:09:28 -07003852 visitor.WalkStack();
Elliott Hughes86964332012-02-15 19:37:42 -08003853
Elliott Hughes2435a572012-02-17 16:07:41 -08003854 // Find the dex_pc values that correspond to the current line, for line-based single-stepping.
Elliott Hughes2435a572012-02-17 16:07:41 -08003855 struct DebugCallbackContext {
Roland Levillain3887c462015-08-12 18:15:42 +01003856 DebugCallbackContext(SingleStepControl* single_step_control_cb,
Mathieu Chartier31f4c9f2017-12-08 15:46:11 -08003857 int32_t line_number_cb, uint32_t num_insns_in_code_units)
Roland Levillain3887c462015-08-12 18:15:42 +01003858 : single_step_control_(single_step_control_cb), line_number_(line_number_cb),
Mathieu Chartier31f4c9f2017-12-08 15:46:11 -08003859 num_insns_in_code_units_(num_insns_in_code_units), last_pc_valid(false), last_pc(0) {
Elliott Hughes2435a572012-02-17 16:07:41 -08003860 }
3861
David Srbeckyb06e28e2015-12-10 13:15:00 +00003862 static bool Callback(void* raw_context, const DexFile::PositionInfo& entry) {
Elliott Hughes2435a572012-02-17 16:07:41 -08003863 DebugCallbackContext* context = reinterpret_cast<DebugCallbackContext*>(raw_context);
David Srbeckyb06e28e2015-12-10 13:15:00 +00003864 if (static_cast<int32_t>(entry.line_) == context->line_number_) {
Elliott Hughes2435a572012-02-17 16:07:41 -08003865 if (!context->last_pc_valid) {
3866 // Everything from this address until the next line change is ours.
David Srbeckyb06e28e2015-12-10 13:15:00 +00003867 context->last_pc = entry.address_;
Elliott Hughes2435a572012-02-17 16:07:41 -08003868 context->last_pc_valid = true;
3869 }
3870 // Otherwise, if we're already in a valid range for this line,
3871 // just keep going (shouldn't really happen)...
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003872 } else if (context->last_pc_valid) { // and the line number is new
Elliott Hughes2435a572012-02-17 16:07:41 -08003873 // Add everything from the last entry up until here to the set
David Srbeckyb06e28e2015-12-10 13:15:00 +00003874 for (uint32_t dex_pc = context->last_pc; dex_pc < entry.address_; ++dex_pc) {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003875 context->single_step_control_->AddDexPc(dex_pc);
Elliott Hughes2435a572012-02-17 16:07:41 -08003876 }
3877 context->last_pc_valid = false;
3878 }
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003879 return false; // There may be multiple entries for any given line.
Elliott Hughes2435a572012-02-17 16:07:41 -08003880 }
3881
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003882 ~DebugCallbackContext() {
Elliott Hughes2435a572012-02-17 16:07:41 -08003883 // If the line number was the last in the position table...
3884 if (last_pc_valid) {
Mathieu Chartier31f4c9f2017-12-08 15:46:11 -08003885 for (uint32_t dex_pc = last_pc; dex_pc < num_insns_in_code_units_; ++dex_pc) {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003886 single_step_control_->AddDexPc(dex_pc);
Elliott Hughes2435a572012-02-17 16:07:41 -08003887 }
3888 }
3889 }
3890
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003891 SingleStepControl* const single_step_control_;
3892 const int32_t line_number_;
Mathieu Chartier31f4c9f2017-12-08 15:46:11 -08003893 const uint32_t num_insns_in_code_units_;
Elliott Hughes2435a572012-02-17 16:07:41 -08003894 bool last_pc_valid;
3895 uint32_t last_pc;
3896 };
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003897
3898 // Allocate single step.
Sebastien Hertz1558b572015-02-25 15:05:59 +01003899 SingleStepControl* single_step_control =
3900 new (std::nothrow) SingleStepControl(step_size, step_depth,
3901 visitor.stack_depth, visitor.method);
3902 if (single_step_control == nullptr) {
3903 LOG(ERROR) << "Failed to allocate SingleStepControl";
3904 return JDWP::ERR_OUT_OF_MEMORY;
3905 }
3906
Mathieu Chartiere401d142015-04-22 13:56:20 -07003907 ArtMethod* m = single_step_control->GetMethod();
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003908 const int32_t line_number = visitor.line_number;
Sebastien Hertz52f5f932015-05-28 11:00:57 +02003909 // Note: if the thread is not running Java code (pure native thread), there is no "current"
3910 // method on the stack (and no line number either).
3911 if (m != nullptr && !m->IsNative()) {
David Sehr0225f8e2018-01-31 08:52:24 +00003912 CodeItemDebugInfoAccessor accessor(m->DexInstructionDebugInfo());
Mathieu Chartier31f4c9f2017-12-08 15:46:11 -08003913 DebugCallbackContext context(single_step_control, line_number, accessor.InsnsSizeInCodeUnits());
3914 m->GetDexFile()->DecodeDebugPositionInfo(accessor.DebugInfoOffset(),
3915 DebugCallbackContext::Callback,
3916 &context);
Elliott Hughes3e2e1a22012-02-21 11:33:41 -08003917 }
Elliott Hughes2435a572012-02-17 16:07:41 -08003918
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003919 // Activate single-step in the thread.
3920 thread->ActivateSingleStepControl(single_step_control);
Elliott Hughes86964332012-02-15 19:37:42 -08003921
Elliott Hughes2435a572012-02-17 16:07:41 -08003922 if (VLOG_IS_ON(jdwp)) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003923 VLOG(jdwp) << "Single-step thread: " << *thread;
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003924 VLOG(jdwp) << "Single-step step size: " << single_step_control->GetStepSize();
3925 VLOG(jdwp) << "Single-step step depth: " << single_step_control->GetStepDepth();
David Sehr709b0702016-10-13 09:12:37 -07003926 VLOG(jdwp) << "Single-step current method: "
3927 << ArtMethod::PrettyMethod(single_step_control->GetMethod());
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003928 VLOG(jdwp) << "Single-step current line: " << line_number;
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003929 VLOG(jdwp) << "Single-step current stack depth: " << single_step_control->GetStackDepth();
Elliott Hughes2435a572012-02-17 16:07:41 -08003930 VLOG(jdwp) << "Single-step dex_pc values:";
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003931 for (uint32_t dex_pc : single_step_control->GetDexPcs()) {
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003932 VLOG(jdwp) << StringPrintf(" %#x", dex_pc);
Elliott Hughes2435a572012-02-17 16:07:41 -08003933 }
3934 }
3935
3936 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003937}
3938
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003939void Dbg::UnconfigureStep(JDWP::ObjectId thread_id) {
3940 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07003941 JDWP::JdwpError error;
3942 Thread* thread = DecodeThread(soa, thread_id, &error);
Sebastien Hertz87118ed2013-11-26 17:57:18 +01003943 if (error == JDWP::ERR_NONE) {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003944 thread->DeactivateSingleStepControl();
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003945 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003946}
3947
Elliott Hughes45651fd2012-02-21 15:48:20 -08003948static char JdwpTagToShortyChar(JDWP::JdwpTag tag) {
3949 switch (tag) {
3950 default:
3951 LOG(FATAL) << "unknown JDWP tag: " << PrintableChar(tag);
Ian Rogersfc787ec2014-10-09 21:56:44 -07003952 UNREACHABLE();
Elliott Hughes45651fd2012-02-21 15:48:20 -08003953
3954 // Primitives.
3955 case JDWP::JT_BYTE: return 'B';
3956 case JDWP::JT_CHAR: return 'C';
3957 case JDWP::JT_FLOAT: return 'F';
3958 case JDWP::JT_DOUBLE: return 'D';
3959 case JDWP::JT_INT: return 'I';
3960 case JDWP::JT_LONG: return 'J';
3961 case JDWP::JT_SHORT: return 'S';
3962 case JDWP::JT_VOID: return 'V';
3963 case JDWP::JT_BOOLEAN: return 'Z';
3964
3965 // Reference types.
3966 case JDWP::JT_ARRAY:
3967 case JDWP::JT_OBJECT:
3968 case JDWP::JT_STRING:
3969 case JDWP::JT_THREAD:
3970 case JDWP::JT_THREAD_GROUP:
3971 case JDWP::JT_CLASS_LOADER:
3972 case JDWP::JT_CLASS_OBJECT:
3973 return 'L';
3974 }
3975}
3976
Sebastien Hertzcbc50642015-06-01 17:33:12 +02003977JDWP::JdwpError Dbg::PrepareInvokeMethod(uint32_t request_id, JDWP::ObjectId thread_id,
3978 JDWP::ObjectId object_id, JDWP::RefTypeId class_id,
3979 JDWP::MethodId method_id, uint32_t arg_count,
3980 uint64_t arg_values[], JDWP::JdwpTag* arg_types,
3981 uint32_t options) {
3982 Thread* const self = Thread::Current();
3983 CHECK_EQ(self, GetDebugThread()) << "This must be called by the JDWP thread";
Sebastien Hertzd4032e42015-06-12 15:47:34 +02003984 const bool resume_all_threads = ((options & JDWP::INVOKE_SINGLE_THREADED) == 0);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003985
Sebastien Hertzcbc50642015-06-01 17:33:12 +02003986 ThreadList* thread_list = Runtime::Current()->GetThreadList();
Ian Rogersc0542af2014-09-03 16:16:56 -07003987 Thread* targetThread = nullptr;
Elliott Hughesd07986f2011-12-06 18:27:45 -08003988 {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003989 ScopedObjectAccessUnchecked soa(self);
Ian Rogersc0542af2014-09-03 16:16:56 -07003990 JDWP::JdwpError error;
3991 targetThread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08003992 if (error != JDWP::ERR_NONE) {
3993 LOG(ERROR) << "InvokeMethod request for invalid thread id " << thread_id;
3994 return error;
Elliott Hughesd07986f2011-12-06 18:27:45 -08003995 }
Sebastien Hertz1558b572015-02-25 15:05:59 +01003996 if (targetThread->GetInvokeReq() != nullptr) {
3997 // Thread is already invoking a method on behalf of the debugger.
3998 LOG(ERROR) << "InvokeMethod request for thread already invoking a method: " << *targetThread;
3999 return JDWP::ERR_ALREADY_INVOKING;
4000 }
4001 if (!targetThread->IsReadyForDebugInvoke()) {
4002 // Thread is not suspended by an event so it cannot invoke a method.
Elliott Hughesd07986f2011-12-06 18:27:45 -08004003 LOG(ERROR) << "InvokeMethod request for thread not stopped by event: " << *targetThread;
4004 return JDWP::ERR_INVALID_THREAD;
4005 }
4006
4007 /*
Sebastien Hertzd4032e42015-06-12 15:47:34 +02004008 * According to the JDWP specs, we are expected to resume all threads (or only the
4009 * target thread) once. So if a thread has been suspended more than once (either by
4010 * the debugger for an event or by the runtime for GC), it will remain suspended before
4011 * the invoke is executed. This means the debugger is responsible to properly resume all
4012 * the threads it has suspended so the target thread can execute the method.
Elliott Hughesd07986f2011-12-06 18:27:45 -08004013 *
Sebastien Hertzd4032e42015-06-12 15:47:34 +02004014 * However, for compatibility reason with older versions of debuggers (like Eclipse), we
4015 * fully resume all threads (by canceling *all* debugger suspensions) when the debugger
4016 * wants us to resume all threads. This is to avoid ending up in deadlock situation.
4017 *
4018 * On the other hand, if we are asked to only resume the target thread, then we follow the
4019 * JDWP specs by resuming that thread only once. This means the thread will remain suspended
4020 * if it has been suspended more than once before the invoke (and again, this is the
4021 * responsibility of the debugger to properly resume that thread before invoking a method).
Elliott Hughesd07986f2011-12-06 18:27:45 -08004022 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004023 int suspend_count;
4024 {
Ian Rogers50b35e22012-10-04 10:09:15 -07004025 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004026 suspend_count = targetThread->GetSuspendCount();
4027 }
Sebastien Hertzd4032e42015-06-12 15:47:34 +02004028 if (suspend_count > 1 && resume_all_threads) {
4029 // The target thread will remain suspended even after we resume it. Let's emit a warning
4030 // to indicate the invoke won't be executed until the thread is resumed.
4031 LOG(WARNING) << *targetThread << " suspended more than once (suspend count == "
4032 << suspend_count << "). This thread will invoke the method only once "
4033 << "it is fully resumed.";
Elliott Hughesd07986f2011-12-06 18:27:45 -08004034 }
4035
Ian Rogersc0542af2014-09-03 16:16:56 -07004036 mirror::Object* receiver = gRegistry->Get<mirror::Object*>(object_id, &error);
4037 if (error != JDWP::ERR_NONE) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08004038 return JDWP::ERR_INVALID_OBJECT;
4039 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08004040
Sebastien Hertz1558b572015-02-25 15:05:59 +01004041 gRegistry->Get<mirror::Object*>(thread_id, &error);
Ian Rogersc0542af2014-09-03 16:16:56 -07004042 if (error != JDWP::ERR_NONE) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08004043 return JDWP::ERR_INVALID_OBJECT;
4044 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08004045
Ian Rogersc0542af2014-09-03 16:16:56 -07004046 mirror::Class* c = DecodeClass(class_id, &error);
4047 if (c == nullptr) {
4048 return error;
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08004049 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08004050
Mathieu Chartiere401d142015-04-22 13:56:20 -07004051 ArtMethod* m = FromMethodId(method_id);
Ian Rogersc0542af2014-09-03 16:16:56 -07004052 if (m->IsStatic() != (receiver == nullptr)) {
Elliott Hughes45651fd2012-02-21 15:48:20 -08004053 return JDWP::ERR_INVALID_METHODID;
4054 }
4055 if (m->IsStatic()) {
4056 if (m->GetDeclaringClass() != c) {
4057 return JDWP::ERR_INVALID_METHODID;
4058 }
4059 } else {
4060 if (!m->GetDeclaringClass()->IsAssignableFrom(c)) {
4061 return JDWP::ERR_INVALID_METHODID;
4062 }
4063 }
4064
4065 // Check the argument list matches the method.
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004066 uint32_t shorty_len = 0;
4067 const char* shorty = m->GetShorty(&shorty_len);
4068 if (shorty_len - 1 != arg_count) {
Elliott Hughes45651fd2012-02-21 15:48:20 -08004069 return JDWP::ERR_ILLEGAL_ARGUMENT;
4070 }
Elliott Hughes09201632013-04-15 15:50:07 -07004071
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004072 {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004073 StackHandleScope<2> hs(soa.Self());
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004074 HandleWrapper<mirror::Object> h_obj(hs.NewHandleWrapper(&receiver));
4075 HandleWrapper<mirror::Class> h_klass(hs.NewHandleWrapper(&c));
4076 const DexFile::TypeList* types = m->GetParameterTypeList();
4077 for (size_t i = 0; i < arg_count; ++i) {
4078 if (shorty[i + 1] != JdwpTagToShortyChar(arg_types[i])) {
Elliott Hughes09201632013-04-15 15:50:07 -07004079 return JDWP::ERR_ILLEGAL_ARGUMENT;
4080 }
4081
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004082 if (shorty[i + 1] == 'L') {
4083 // Did we really get an argument of an appropriate reference type?
Vladimir Markob45528c2017-07-27 14:14:28 +01004084 ObjPtr<mirror::Class> parameter_type =
4085 m->ResolveClassFromTypeIndex(types->GetTypeItem(i).type_idx_);
Ian Rogersc0542af2014-09-03 16:16:56 -07004086 mirror::Object* argument = gRegistry->Get<mirror::Object*>(arg_values[i], &error);
4087 if (error != JDWP::ERR_NONE) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004088 return JDWP::ERR_INVALID_OBJECT;
4089 }
Ian Rogersc0542af2014-09-03 16:16:56 -07004090 if (argument != nullptr && !argument->InstanceOf(parameter_type)) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004091 return JDWP::ERR_ILLEGAL_ARGUMENT;
4092 }
4093
4094 // Turn the on-the-wire ObjectId into a jobject.
4095 jvalue& v = reinterpret_cast<jvalue&>(arg_values[i]);
4096 v.l = gRegistry->GetJObject(arg_values[i]);
4097 }
Elliott Hughes09201632013-04-15 15:50:07 -07004098 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08004099 }
4100
Sebastien Hertz1558b572015-02-25 15:05:59 +01004101 // Allocates a DebugInvokeReq.
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004102 DebugInvokeReq* req = new (std::nothrow) DebugInvokeReq(request_id, thread_id, receiver, c, m,
4103 options, arg_values, arg_count);
4104 if (req == nullptr) {
Sebastien Hertz1558b572015-02-25 15:05:59 +01004105 LOG(ERROR) << "Failed to allocate DebugInvokeReq";
4106 return JDWP::ERR_OUT_OF_MEMORY;
4107 }
4108
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004109 // Attaches the DebugInvokeReq to the target thread so it executes the method when
4110 // it is resumed. Once the invocation completes, the target thread will delete it before
4111 // suspending itself (see ThreadList::SuspendSelfForDebugger).
4112 targetThread->SetDebugInvokeReq(req);
Elliott Hughesd07986f2011-12-06 18:27:45 -08004113 }
4114
4115 // 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 +02004116 // away we're sitting high and dry -- but we must release this before the UndoDebuggerSuspensions
4117 // call.
Sebastien Hertzd4032e42015-06-12 15:47:34 +02004118 if (resume_all_threads) {
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004119 VLOG(jdwp) << " Resuming all threads";
4120 thread_list->UndoDebuggerSuspensions();
4121 } else {
4122 VLOG(jdwp) << " Resuming event thread only";
Alex Light88fd7202017-06-30 08:31:59 -07004123 bool resumed = thread_list->Resume(targetThread, SuspendReason::kForDebugger);
4124 DCHECK(resumed);
Elliott Hughesd07986f2011-12-06 18:27:45 -08004125 }
4126
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004127 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004128}
4129
4130void Dbg::ExecuteMethod(DebugInvokeReq* pReq) {
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004131 Thread* const self = Thread::Current();
4132 CHECK_NE(self, GetDebugThread()) << "This must be called by the event thread";
4133
4134 ScopedObjectAccess soa(self);
Elliott Hughesd07986f2011-12-06 18:27:45 -08004135
Elliott Hughes81ff3182012-03-23 20:35:56 -07004136 // We can be called while an exception is pending. We need
Elliott Hughesd07986f2011-12-06 18:27:45 -08004137 // to preserve that across the method invocation.
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004138 StackHandleScope<1> hs(soa.Self());
4139 Handle<mirror::Throwable> old_exception = hs.NewHandle(soa.Self()->GetException());
Sebastien Hertz1558b572015-02-25 15:05:59 +01004140 soa.Self()->ClearException();
Elliott Hughesd07986f2011-12-06 18:27:45 -08004141
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004142 // Execute the method then sends reply to the debugger.
4143 ExecuteMethodWithoutPendingException(soa, pReq);
4144
4145 // If an exception was pending before the invoke, restore it now.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004146 if (old_exception != nullptr) {
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004147 soa.Self()->SetException(old_exception.Get());
4148 }
4149}
4150
4151// Helper function: write a variable-width value into the output input buffer.
4152static void WriteValue(JDWP::ExpandBuf* pReply, int width, uint64_t value) {
4153 switch (width) {
4154 case 1:
4155 expandBufAdd1(pReply, value);
4156 break;
4157 case 2:
4158 expandBufAdd2BE(pReply, value);
4159 break;
4160 case 4:
4161 expandBufAdd4BE(pReply, value);
4162 break;
4163 case 8:
4164 expandBufAdd8BE(pReply, value);
4165 break;
4166 default:
4167 LOG(FATAL) << width;
4168 UNREACHABLE();
4169 }
4170}
4171
4172void Dbg::ExecuteMethodWithoutPendingException(ScopedObjectAccess& soa, DebugInvokeReq* pReq) {
4173 soa.Self()->AssertNoPendingException();
4174
Elliott Hughesd07986f2011-12-06 18:27:45 -08004175 // Translate the method through the vtable, unless the debugger wants to suppress it.
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004176 ArtMethod* m = pReq->method;
Andreas Gampe542451c2016-07-26 09:02:02 -07004177 PointerSize image_pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
Sebastien Hertz1558b572015-02-25 15:05:59 +01004178 if ((pReq->options & JDWP::INVOKE_NONVIRTUAL) == 0 && pReq->receiver.Read() != nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004179 ArtMethod* actual_method =
4180 pReq->klass.Read()->FindVirtualMethodForVirtualOrInterface(m, image_pointer_size);
4181 if (actual_method != m) {
David Sehr709b0702016-10-13 09:12:37 -07004182 VLOG(jdwp) << "ExecuteMethod translated " << ArtMethod::PrettyMethod(m)
4183 << " to " << ArtMethod::PrettyMethod(actual_method);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004184 m = actual_method;
Elliott Hughes45651fd2012-02-21 15:48:20 -08004185 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08004186 }
David Sehr709b0702016-10-13 09:12:37 -07004187 VLOG(jdwp) << "ExecuteMethod " << ArtMethod::PrettyMethod(m)
Sebastien Hertz1558b572015-02-25 15:05:59 +01004188 << " receiver=" << pReq->receiver.Read()
Sebastien Hertzd38667a2013-11-25 15:43:54 +01004189 << " arg_count=" << pReq->arg_count;
Mathieu Chartiere401d142015-04-22 13:56:20 -07004190 CHECK(m != nullptr);
Elliott Hughesd07986f2011-12-06 18:27:45 -08004191
Roland Levillain33d69032015-06-18 18:20:59 +01004192 static_assert(sizeof(jvalue) == sizeof(uint64_t), "jvalue and uint64_t have different sizes.");
Elliott Hughesd07986f2011-12-06 18:27:45 -08004193
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004194 // Invoke the method.
Jeff Hao39b6c242015-05-19 20:30:23 -07004195 ScopedLocalRef<jobject> ref(soa.Env(), soa.AddLocalReference<jobject>(pReq->receiver.Read()));
Andreas Gampe13b27842016-11-07 16:48:23 -08004196 JValue result = InvokeWithJValues(soa, ref.get(), jni::EncodeArtMethod(m),
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004197 reinterpret_cast<jvalue*>(pReq->arg_values.get()));
Elliott Hughesd07986f2011-12-06 18:27:45 -08004198
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004199 // Prepare JDWP ids for the reply.
4200 JDWP::JdwpTag result_tag = BasicTagFromDescriptor(m->GetShorty());
4201 const bool is_object_result = (result_tag == JDWP::JT_OBJECT);
Jeff Hao064d24e2016-08-25 03:52:40 +00004202 StackHandleScope<3> hs(soa.Self());
Sebastien Hertz1558b572015-02-25 15:05:59 +01004203 Handle<mirror::Object> object_result = hs.NewHandle(is_object_result ? result.GetL() : nullptr);
4204 Handle<mirror::Throwable> exception = hs.NewHandle(soa.Self()->GetException());
4205 soa.Self()->ClearException();
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004206
4207 if (!IsDebuggerActive()) {
4208 // The debugger detached: we must not re-suspend threads. We also don't need to fill the reply
4209 // because it won't be sent either.
4210 return;
4211 }
4212
4213 JDWP::ObjectId exceptionObjectId = gRegistry->Add(exception);
4214 uint64_t result_value = 0;
4215 if (exceptionObjectId != 0) {
Sebastien Hertz1558b572015-02-25 15:05:59 +01004216 VLOG(jdwp) << " JDWP invocation returning with exception=" << exception.Get()
4217 << " " << exception->Dump();
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004218 result_value = 0;
Sebastien Hertz1558b572015-02-25 15:05:59 +01004219 } else if (is_object_result) {
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004220 /* if no exception was thrown, examine object result more closely */
Sebastien Hertz1558b572015-02-25 15:05:59 +01004221 JDWP::JdwpTag new_tag = TagFromObject(soa, object_result.Get());
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004222 if (new_tag != result_tag) {
4223 VLOG(jdwp) << " JDWP promoted result from " << result_tag << " to " << new_tag;
4224 result_tag = new_tag;
Elliott Hughesd07986f2011-12-06 18:27:45 -08004225 }
4226
Sebastien Hertz1558b572015-02-25 15:05:59 +01004227 // Register the object in the registry and reference its ObjectId. This ensures
4228 // GC safety and prevents from accessing stale reference if the object is moved.
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004229 result_value = gRegistry->Add(object_result.Get());
Sebastien Hertz1558b572015-02-25 15:05:59 +01004230 } else {
4231 // Primitive result.
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004232 DCHECK(IsPrimitiveTag(result_tag));
4233 result_value = result.GetJ();
4234 }
4235 const bool is_constructor = m->IsConstructor() && !m->IsStatic();
4236 if (is_constructor) {
4237 // If we invoked a constructor (which actually returns void), return the receiver,
4238 // unless we threw, in which case we return null.
Sebastien Hertza3e13772015-11-05 12:09:44 +01004239 DCHECK_EQ(JDWP::JT_VOID, result_tag);
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004240 if (exceptionObjectId == 0) {
Jeff Hao064d24e2016-08-25 03:52:40 +00004241 if (m->GetDeclaringClass()->IsStringClass()) {
4242 // For string constructors, the new string is remapped to the receiver (stored in ref).
4243 Handle<mirror::Object> decoded_ref = hs.NewHandle(soa.Self()->DecodeJObject(ref.get()));
4244 result_value = gRegistry->Add(decoded_ref);
4245 result_tag = TagFromObject(soa, decoded_ref.Get());
4246 } else {
4247 // TODO we could keep the receiver ObjectId in the DebugInvokeReq to avoid looking into the
4248 // object registry.
4249 result_value = GetObjectRegistry()->Add(pReq->receiver.Read());
4250 result_tag = TagFromObject(soa, pReq->receiver.Read());
4251 }
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004252 } else {
4253 result_value = 0;
Sebastien Hertza3e13772015-11-05 12:09:44 +01004254 result_tag = JDWP::JT_OBJECT;
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004255 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08004256 }
4257
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004258 // Suspend other threads if the invoke is not single-threaded.
4259 if ((pReq->options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07004260 ScopedThreadSuspension sts(soa.Self(), kWaitingForDebuggerSuspension);
Hiroshi Yamauchi8f95cf32016-04-19 11:14:06 -07004261 // Avoid a deadlock between GC and debugger where GC gets suspended during GC. b/25800335.
4262 gc::ScopedGCCriticalSection gcs(soa.Self(), gc::kGcCauseDebugger, gc::kCollectorTypeDebugger);
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004263 VLOG(jdwp) << " Suspending all threads";
4264 Runtime::Current()->GetThreadList()->SuspendAllForDebugger();
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004265 }
4266
4267 VLOG(jdwp) << " --> returned " << result_tag
4268 << StringPrintf(" %#" PRIx64 " (except=%#" PRIx64 ")", result_value,
4269 exceptionObjectId);
4270
4271 // Show detailed debug output.
4272 if (result_tag == JDWP::JT_STRING && exceptionObjectId == 0) {
4273 if (result_value != 0) {
4274 if (VLOG_IS_ON(jdwp)) {
4275 std::string result_string;
4276 JDWP::JdwpError error = Dbg::StringToUtf8(result_value, &result_string);
4277 CHECK_EQ(error, JDWP::ERR_NONE);
4278 VLOG(jdwp) << " string '" << result_string << "'";
4279 }
4280 } else {
4281 VLOG(jdwp) << " string (null)";
4282 }
4283 }
4284
4285 // Attach the reply to DebugInvokeReq so it can be sent to the debugger when the event thread
4286 // is ready to suspend.
4287 BuildInvokeReply(pReq->reply, pReq->request_id, result_tag, result_value, exceptionObjectId);
4288}
4289
4290void Dbg::BuildInvokeReply(JDWP::ExpandBuf* pReply, uint32_t request_id, JDWP::JdwpTag result_tag,
4291 uint64_t result_value, JDWP::ObjectId exception) {
4292 // Make room for the JDWP header since we do not know the size of the reply yet.
4293 JDWP::expandBufAddSpace(pReply, kJDWPHeaderLen);
4294
4295 size_t width = GetTagWidth(result_tag);
4296 JDWP::expandBufAdd1(pReply, result_tag);
4297 if (width != 0) {
4298 WriteValue(pReply, width, result_value);
4299 }
4300 JDWP::expandBufAdd1(pReply, JDWP::JT_OBJECT);
4301 JDWP::expandBufAddObjectId(pReply, exception);
4302
4303 // Now we know the size, we can complete the JDWP header.
4304 uint8_t* buf = expandBufGetBuffer(pReply);
4305 JDWP::Set4BE(buf + kJDWPHeaderSizeOffset, expandBufGetLength(pReply));
4306 JDWP::Set4BE(buf + kJDWPHeaderIdOffset, request_id);
4307 JDWP::Set1(buf + kJDWPHeaderFlagsOffset, kJDWPFlagReply); // flags
4308 JDWP::Set2BE(buf + kJDWPHeaderErrorCodeOffset, JDWP::ERR_NONE);
4309}
4310
4311void Dbg::FinishInvokeMethod(DebugInvokeReq* pReq) {
4312 CHECK_NE(Thread::Current(), GetDebugThread()) << "This must be called by the event thread";
4313
4314 JDWP::ExpandBuf* const pReply = pReq->reply;
4315 CHECK(pReply != nullptr) << "No reply attached to DebugInvokeReq";
4316
4317 // We need to prevent other threads (including JDWP thread) from interacting with the debugger
4318 // while we send the reply but are not yet suspended. The JDWP token will be released just before
4319 // we suspend ourself again (see ThreadList::SuspendSelfForDebugger).
4320 gJdwpState->AcquireJdwpTokenForEvent(pReq->thread_id);
4321
4322 // Send the reply unless the debugger detached before the completion of the method.
4323 if (IsDebuggerActive()) {
4324 const size_t replyDataLength = expandBufGetLength(pReply) - kJDWPHeaderLen;
4325 VLOG(jdwp) << StringPrintf("REPLY INVOKE id=0x%06x (length=%zu)",
4326 pReq->request_id, replyDataLength);
4327
4328 gJdwpState->SendRequest(pReply);
4329 } else {
4330 VLOG(jdwp) << "Not sending invoke reply because debugger detached";
Elliott Hughesd07986f2011-12-06 18:27:45 -08004331 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004332}
4333
Alex Light8c2b9292017-11-09 13:21:01 -08004334bool Dbg::DdmHandleChunk(JNIEnv* env,
4335 uint32_t type,
4336 const ArrayRef<const jbyte>& data,
4337 /*out*/uint32_t* out_type,
4338 /*out*/std::vector<uint8_t>* out_data) {
4339 ScopedLocalRef<jbyteArray> dataArray(env, env->NewByteArray(data.size()));
Ian Rogersc0542af2014-09-03 16:16:56 -07004340 if (dataArray.get() == nullptr) {
Alex Light8c2b9292017-11-09 13:21:01 -08004341 LOG(WARNING) << "byte[] allocation failed: " << data.size();
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004342 env->ExceptionClear();
4343 return false;
4344 }
Alex Light8c2b9292017-11-09 13:21:01 -08004345 env->SetByteArrayRegion(dataArray.get(),
4346 0,
4347 data.size(),
4348 reinterpret_cast<const jbyte*>(data.data()));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004349 // Call "private static Chunk dispatch(int type, byte[] data, int offset, int length)".
Alex Light8c2b9292017-11-09 13:21:01 -08004350 ScopedLocalRef<jobject> chunk(
4351 env,
4352 env->CallStaticObjectMethod(
4353 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
4354 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_dispatch,
4355 type, dataArray.get(), 0, data.size()));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004356 if (env->ExceptionCheck()) {
Alex Light1eeefa62018-03-19 13:47:56 -07004357 Thread* self = Thread::Current();
4358 ScopedObjectAccess soa(self);
4359 LOG(INFO) << StringPrintf("Exception thrown by dispatcher for 0x%08x", type) << std::endl
4360 << self->GetException()->Dump();
4361 self->ClearException();
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004362 return false;
4363 }
4364
Ian Rogersc0542af2014-09-03 16:16:56 -07004365 if (chunk.get() == nullptr) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004366 return false;
4367 }
4368
4369 /*
4370 * Pull the pieces out of the chunk. We copy the results into a
4371 * newly-allocated buffer that the caller can free. We don't want to
4372 * continue using the Chunk object because nothing has a reference to it.
4373 *
4374 * We could avoid this by returning type/data/offset/length and having
4375 * the caller be aware of the object lifetime issues, but that
Elliott Hughes81ff3182012-03-23 20:35:56 -07004376 * integrates the JDWP code more tightly into the rest of the runtime, and doesn't work
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004377 * if we have responses for multiple chunks.
4378 *
4379 * So we're pretty much stuck with copying data around multiple times.
4380 */
Alex Light8c2b9292017-11-09 13:21:01 -08004381 ScopedLocalRef<jbyteArray> replyData(
4382 env,
4383 reinterpret_cast<jbyteArray>(
4384 env->GetObjectField(
4385 chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_data)));
4386 jint offset = env->GetIntField(chunk.get(),
4387 WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_offset);
4388 jint length = env->GetIntField(chunk.get(),
4389 WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_length);
4390 *out_type = env->GetIntField(chunk.get(),
4391 WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_type);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004392
Alex Light8c2b9292017-11-09 13:21:01 -08004393 VLOG(jdwp) << StringPrintf("DDM reply: type=0x%08x data=%p offset=%d length=%d",
4394 type,
4395 replyData.get(),
4396 offset,
4397 length);
Alex Light8c2b9292017-11-09 13:21:01 -08004398 out_data->resize(length);
4399 env->GetByteArrayRegion(replyData.get(),
4400 offset,
4401 length,
4402 reinterpret_cast<jbyte*>(out_data->data()));
Alex Light6f2a6342017-12-12 09:55:05 -08004403
Alex Lighte5463a82017-12-12 13:33:28 -08004404 if (env->ExceptionCheck()) {
Alex Light1eeefa62018-03-19 13:47:56 -07004405 Thread* self = Thread::Current();
4406 ScopedObjectAccess soa(self);
Alex Lighte5463a82017-12-12 13:33:28 -08004407 LOG(INFO) << StringPrintf("Exception thrown when reading response data from dispatcher 0x%08x",
Alex Light1eeefa62018-03-19 13:47:56 -07004408 type) << std::endl << self->GetException()->Dump();
4409 self->ClearException();
Alex Lighte5463a82017-12-12 13:33:28 -08004410 return false;
4411 }
4412
Alex Light8c2b9292017-11-09 13:21:01 -08004413 return true;
4414}
4415
4416/*
4417 * "request" contains a full JDWP packet, possibly with multiple chunks. We
4418 * need to process each, accumulate the replies, and ship the whole thing
4419 * back.
4420 *
4421 * Returns "true" if we have a reply. The reply buffer is newly allocated,
4422 * and includes the chunk type/length, followed by the data.
4423 *
4424 * OLD-TODO: we currently assume that the request and reply include a single
4425 * chunk. If this becomes inconvenient we will need to adapt.
4426 */
4427bool Dbg::DdmHandlePacket(JDWP::Request* request, uint8_t** pReplyBuf, int* pReplyLen) {
4428 Thread* self = Thread::Current();
4429 JNIEnv* env = self->GetJniEnv();
4430
4431 uint32_t type = request->ReadUnsigned32("type");
4432 uint32_t length = request->ReadUnsigned32("length");
4433
4434 // Create a byte[] corresponding to 'request'.
4435 size_t request_length = request->size();
4436 // Run through and find all chunks. [Currently just find the first.]
4437 if (length != request_length) {
4438 LOG(WARNING) << StringPrintf("bad chunk found (len=%u pktLen=%zd)", length, request_length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004439 return false;
4440 }
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004441
Alex Light8c2b9292017-11-09 13:21:01 -08004442 ArrayRef<const jbyte> data(reinterpret_cast<const jbyte*>(request->data()), request_length);
4443 std::vector<uint8_t> out_data;
4444 uint32_t out_type = 0;
4445 request->Skip(request_length);
Alex Light6f2a6342017-12-12 09:55:05 -08004446 if (!DdmHandleChunk(env, type, data, &out_type, &out_data) || out_data.empty()) {
Alex Light8c2b9292017-11-09 13:21:01 -08004447 return false;
4448 }
4449 const uint32_t kDdmHeaderSize = 8;
4450 *pReplyLen = out_data.size() + kDdmHeaderSize;
4451 *pReplyBuf = new uint8_t[out_data.size() + kDdmHeaderSize];
4452 memcpy((*pReplyBuf) + kDdmHeaderSize, out_data.data(), out_data.size());
4453 JDWP::Set4BE(*pReplyBuf, out_type);
4454 JDWP::Set4BE((*pReplyBuf) + 4, static_cast<uint32_t>(out_data.size()));
4455 VLOG(jdwp)
4456 << StringPrintf("dvmHandleDdm returning type=%.4s", reinterpret_cast<char*>(*pReplyBuf))
4457 << "0x" << std::hex << reinterpret_cast<uintptr_t>(*pReplyBuf) << std::dec
4458 << " len= " << out_data.size();
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004459 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004460}
4461
Elliott Hughesa2155262011-11-16 16:26:58 -08004462void Dbg::DdmBroadcast(bool connect) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08004463 VLOG(jdwp) << "Broadcasting DDM " << (connect ? "connect" : "disconnect") << "...";
Elliott Hughes47fce012011-10-25 18:37:19 -07004464
4465 Thread* self = Thread::Current();
Ian Rogers50b35e22012-10-04 10:09:15 -07004466 if (self->GetState() != kRunnable) {
4467 LOG(ERROR) << "DDM broadcast in thread state " << self->GetState();
4468 /* try anyway? */
Elliott Hughes47fce012011-10-25 18:37:19 -07004469 }
4470
4471 JNIEnv* env = self->GetJniEnv();
Elliott Hughes47fce012011-10-25 18:37:19 -07004472 jint event = connect ? 1 /*DdmServer.CONNECTED*/ : 2 /*DdmServer.DISCONNECTED*/;
Elliott Hugheseac76672012-05-24 21:56:51 -07004473 env->CallStaticVoidMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
4474 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_broadcast,
4475 event);
Elliott Hughes47fce012011-10-25 18:37:19 -07004476 if (env->ExceptionCheck()) {
4477 LOG(ERROR) << "DdmServer.broadcast " << event << " failed";
4478 env->ExceptionDescribe();
4479 env->ExceptionClear();
4480 }
4481}
4482
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004483void Dbg::DdmConnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08004484 Dbg::DdmBroadcast(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004485}
4486
4487void Dbg::DdmDisconnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08004488 Dbg::DdmBroadcast(false);
Elliott Hughes47fce012011-10-25 18:37:19 -07004489 gDdmThreadNotification = false;
4490}
4491
4492/*
Elliott Hughes82188472011-11-07 18:11:48 -08004493 * Send a notification when a thread starts, stops, or changes its name.
Elliott Hughes47fce012011-10-25 18:37:19 -07004494 *
4495 * Because we broadcast the full set of threads when the notifications are
4496 * first enabled, it's possible for "thread" to be actively executing.
4497 */
Elliott Hughes82188472011-11-07 18:11:48 -08004498void Dbg::DdmSendThreadNotification(Thread* t, uint32_t type) {
Elliott Hughes47fce012011-10-25 18:37:19 -07004499 if (!gDdmThreadNotification) {
4500 return;
4501 }
4502
Alex Light772099a2017-11-21 14:05:04 -08004503 RuntimeCallbacks* cb = Runtime::Current()->GetRuntimeCallbacks();
Elliott Hughes82188472011-11-07 18:11:48 -08004504 if (type == CHUNK_TYPE("THDE")) {
Elliott Hughes47fce012011-10-25 18:37:19 -07004505 uint8_t buf[4];
Ian Rogersd9c4fc92013-10-01 19:45:43 -07004506 JDWP::Set4BE(&buf[0], t->GetThreadId());
Alex Light772099a2017-11-21 14:05:04 -08004507 cb->DdmPublishChunk(CHUNK_TYPE("THDE"), ArrayRef<const uint8_t>(buf));
Elliott Hughes82188472011-11-07 18:11:48 -08004508 } else {
4509 CHECK(type == CHUNK_TYPE("THCR") || type == CHUNK_TYPE("THNM")) << type;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004510 ScopedObjectAccessUnchecked soa(Thread::Current());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004511 StackHandleScope<1> hs(soa.Self());
Andreas Gampe08883de2016-11-08 13:20:52 -08004512 Handle<mirror::String> name(hs.NewHandle(t->GetThreadName()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004513 size_t char_count = (name != nullptr) ? name->GetLength() : 0;
4514 const jchar* chars = (name != nullptr) ? name->GetValue() : nullptr;
4515 bool is_compressed = (name != nullptr) ? name->IsCompressed() : false;
Elliott Hughes82188472011-11-07 18:11:48 -08004516
Elliott Hughes21f32d72011-11-09 17:44:13 -08004517 std::vector<uint8_t> bytes;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07004518 JDWP::Append4BE(bytes, t->GetThreadId());
jessicahandojo3aaa37b2016-07-29 14:46:37 -07004519 if (is_compressed) {
4520 const uint8_t* chars_compressed = name->GetValueCompressed();
4521 JDWP::AppendUtf16CompressedBE(bytes, chars_compressed, char_count);
4522 } else {
4523 JDWP::AppendUtf16BE(bytes, chars, char_count);
4524 }
Elliott Hughes21f32d72011-11-09 17:44:13 -08004525 CHECK_EQ(bytes.size(), char_count*2 + sizeof(uint32_t)*2);
Alex Light772099a2017-11-21 14:05:04 -08004526 cb->DdmPublishChunk(type, ArrayRef<const uint8_t>(bytes));
Elliott Hughes47fce012011-10-25 18:37:19 -07004527 }
4528}
4529
Elliott Hughes47fce012011-10-25 18:37:19 -07004530void Dbg::DdmSetThreadNotification(bool enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004531 // Enable/disable thread notifications.
Elliott Hughes47fce012011-10-25 18:37:19 -07004532 gDdmThreadNotification = enable;
4533 if (enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004534 // Suspend the VM then post thread start notifications for all threads. Threads attaching will
4535 // see a suspension in progress and block until that ends. They then post their own start
4536 // notification.
4537 SuspendVM();
4538 std::list<Thread*> threads;
Ian Rogers50b35e22012-10-04 10:09:15 -07004539 Thread* self = Thread::Current();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004540 {
Ian Rogers50b35e22012-10-04 10:09:15 -07004541 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004542 threads = Runtime::Current()->GetThreadList()->GetList();
4543 }
4544 {
Ian Rogers50b35e22012-10-04 10:09:15 -07004545 ScopedObjectAccess soa(self);
Mathieu Chartier02e25112013-08-14 16:14:24 -07004546 for (Thread* thread : threads) {
4547 Dbg::DdmSendThreadNotification(thread, CHUNK_TYPE("THCR"));
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004548 }
4549 }
4550 ResumeVM();
Elliott Hughes47fce012011-10-25 18:37:19 -07004551 }
4552}
4553
Elliott Hughesa2155262011-11-16 16:26:58 -08004554void Dbg::PostThreadStartOrStop(Thread* t, uint32_t type) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07004555 if (IsDebuggerActive()) {
Sebastien Hertz6995c602014-09-09 12:10:13 +02004556 gJdwpState->PostThreadChange(t, type == CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07004557 }
Elliott Hughes82188472011-11-07 18:11:48 -08004558 Dbg::DdmSendThreadNotification(t, type);
Elliott Hughes47fce012011-10-25 18:37:19 -07004559}
4560
4561void Dbg::PostThreadStart(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004562 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07004563}
4564
4565void Dbg::PostThreadDeath(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004566 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THDE"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004567}
4568
Mathieu Chartierad466ad2015-01-08 16:28:08 -08004569JDWP::JdwpState* Dbg::GetJdwpState() {
4570 return gJdwpState;
4571}
4572
Elliott Hughes767a1472011-10-26 18:49:02 -07004573int Dbg::DdmHandleHpifChunk(HpifWhen when) {
4574 if (when == HPIF_WHEN_NOW) {
Elliott Hughes7162ad92011-10-27 14:08:42 -07004575 DdmSendHeapInfo(when);
Elliott Hughes767a1472011-10-26 18:49:02 -07004576 return true;
4577 }
4578
4579 if (when != HPIF_WHEN_NEVER && when != HPIF_WHEN_NEXT_GC && when != HPIF_WHEN_EVERY_GC) {
4580 LOG(ERROR) << "invalid HpifWhen value: " << static_cast<int>(when);
4581 return false;
4582 }
4583
4584 gDdmHpifWhen = when;
4585 return true;
4586}
4587
4588bool Dbg::DdmHandleHpsgNhsgChunk(Dbg::HpsgWhen when, Dbg::HpsgWhat what, bool native) {
4589 if (when != HPSG_WHEN_NEVER && when != HPSG_WHEN_EVERY_GC) {
4590 LOG(ERROR) << "invalid HpsgWhen value: " << static_cast<int>(when);
4591 return false;
4592 }
4593
4594 if (what != HPSG_WHAT_MERGED_OBJECTS && what != HPSG_WHAT_DISTINCT_OBJECTS) {
4595 LOG(ERROR) << "invalid HpsgWhat value: " << static_cast<int>(what);
4596 return false;
4597 }
4598
4599 if (native) {
4600 gDdmNhsgWhen = when;
4601 gDdmNhsgWhat = what;
4602 } else {
4603 gDdmHpsgWhen = when;
4604 gDdmHpsgWhat = what;
4605 }
4606 return true;
4607}
4608
Elliott Hughes7162ad92011-10-27 14:08:42 -07004609void Dbg::DdmSendHeapInfo(HpifWhen reason) {
4610 // If there's a one-shot 'when', reset it.
4611 if (reason == gDdmHpifWhen) {
4612 if (gDdmHpifWhen == HPIF_WHEN_NEXT_GC) {
4613 gDdmHpifWhen = HPIF_WHEN_NEVER;
4614 }
4615 }
4616
4617 /*
4618 * Chunk HPIF (client --> server)
4619 *
4620 * Heap Info. General information about the heap,
4621 * suitable for a summary display.
4622 *
4623 * [u4]: number of heaps
4624 *
4625 * For each heap:
4626 * [u4]: heap ID
4627 * [u8]: timestamp in ms since Unix epoch
4628 * [u1]: capture reason (same as 'when' value from server)
4629 * [u4]: max heap size in bytes (-Xmx)
4630 * [u4]: current heap size in bytes
4631 * [u4]: current number of bytes allocated
4632 * [u4]: current number of objects allocated
4633 */
4634 uint8_t heap_count = 1;
Ian Rogers1d54e732013-05-02 21:10:01 -07004635 gc::Heap* heap = Runtime::Current()->GetHeap();
Elliott Hughes21f32d72011-11-09 17:44:13 -08004636 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08004637 JDWP::Append4BE(bytes, heap_count);
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004638 JDWP::Append4BE(bytes, 1); // Heap id (bogus; we only have one heap).
Elliott Hughes545a0642011-11-08 19:10:03 -08004639 JDWP::Append8BE(bytes, MilliTime());
4640 JDWP::Append1BE(bytes, reason);
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004641 JDWP::Append4BE(bytes, heap->GetMaxMemory()); // Max allowed heap size in bytes.
4642 JDWP::Append4BE(bytes, heap->GetTotalMemory()); // Current heap size in bytes.
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08004643 JDWP::Append4BE(bytes, heap->GetBytesAllocated());
4644 JDWP::Append4BE(bytes, heap->GetObjectsAllocated());
Elliott Hughes21f32d72011-11-09 17:44:13 -08004645 CHECK_EQ(bytes.size(), 4U + (heap_count * (4 + 8 + 1 + 4 + 4 + 4 + 4)));
Alex Light772099a2017-11-21 14:05:04 -08004646 Runtime::Current()->GetRuntimeCallbacks()->DdmPublishChunk(CHUNK_TYPE("HPIF"),
4647 ArrayRef<const uint8_t>(bytes));
Elliott Hughes767a1472011-10-26 18:49:02 -07004648}
4649
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004650enum HpsgSolidity {
4651 SOLIDITY_FREE = 0,
4652 SOLIDITY_HARD = 1,
4653 SOLIDITY_SOFT = 2,
4654 SOLIDITY_WEAK = 3,
4655 SOLIDITY_PHANTOM = 4,
4656 SOLIDITY_FINALIZABLE = 5,
4657 SOLIDITY_SWEEP = 6,
4658};
4659
4660enum HpsgKind {
4661 KIND_OBJECT = 0,
4662 KIND_CLASS_OBJECT = 1,
4663 KIND_ARRAY_1 = 2,
4664 KIND_ARRAY_2 = 3,
4665 KIND_ARRAY_4 = 4,
4666 KIND_ARRAY_8 = 5,
4667 KIND_UNKNOWN = 6,
4668 KIND_NATIVE = 7,
4669};
4670
4671#define HPSG_PARTIAL (1<<7)
4672#define HPSG_STATE(solidity, kind) ((uint8_t)((((kind) & 0x7) << 3) | ((solidity) & 0x7)))
4673
Ian Rogers30fab402012-01-23 15:43:46 -08004674class HeapChunkContext {
4675 public:
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004676 // Maximum chunk size. Obtain this from the formula:
4677 // (((maximum_heap_size / ALLOCATION_UNIT_SIZE) + 255) / 256) * 2
4678 HeapChunkContext(bool merge, bool native)
Ian Rogers30fab402012-01-23 15:43:46 -08004679 : buf_(16384 - 16),
4680 type_(0),
Mathieu Chartier36dab362014-07-30 14:59:56 -07004681 chunk_overhead_(0) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004682 Reset();
4683 if (native) {
Ian Rogers30fab402012-01-23 15:43:46 -08004684 type_ = CHUNK_TYPE("NHSG");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004685 } else {
Ian Rogers30fab402012-01-23 15:43:46 -08004686 type_ = merge ? CHUNK_TYPE("HPSG") : CHUNK_TYPE("HPSO");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004687 }
4688 }
4689
4690 ~HeapChunkContext() {
Ian Rogers30fab402012-01-23 15:43:46 -08004691 if (p_ > &buf_[0]) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004692 Flush();
4693 }
4694 }
4695
Mathieu Chartier36dab362014-07-30 14:59:56 -07004696 void SetChunkOverhead(size_t chunk_overhead) {
4697 chunk_overhead_ = chunk_overhead;
4698 }
4699
4700 void ResetStartOfNextChunk() {
4701 startOfNextMemoryChunk_ = nullptr;
4702 }
4703
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004704 void EnsureHeader(const void* chunk_ptr) {
Ian Rogers30fab402012-01-23 15:43:46 -08004705 if (!needHeader_) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004706 return;
4707 }
4708
4709 // Start a new HPSx chunk.
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004710 JDWP::Write4BE(&p_, 1); // Heap id (bogus; we only have one heap).
4711 JDWP::Write1BE(&p_, 8); // Size of allocation unit, in bytes.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004712
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004713 JDWP::Write4BE(&p_, reinterpret_cast<uintptr_t>(chunk_ptr)); // virtual address of segment start.
4714 JDWP::Write4BE(&p_, 0); // offset of this piece (relative to the virtual address).
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004715 // [u4]: length of piece, in allocation units
4716 // 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 -08004717 pieceLenField_ = p_;
4718 JDWP::Write4BE(&p_, 0x55555555);
4719 needHeader_ = false;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004720 }
4721
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004722 void Flush() REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -07004723 if (pieceLenField_ == nullptr) {
Ian Rogersd636b062013-01-18 17:51:18 -08004724 // Flush immediately post Reset (maybe back-to-back Flush). Ignore.
4725 CHECK(needHeader_);
4726 return;
4727 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004728 // Patch the "length of piece" field.
Ian Rogers30fab402012-01-23 15:43:46 -08004729 CHECK_LE(&buf_[0], pieceLenField_);
4730 CHECK_LE(pieceLenField_, p_);
4731 JDWP::Set4BE(pieceLenField_, totalAllocationUnits_);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004732
Alex Light772099a2017-11-21 14:05:04 -08004733 ArrayRef<const uint8_t> out(&buf_[0], p_ - &buf_[0]);
4734 Runtime::Current()->GetRuntimeCallbacks()->DdmPublishChunk(type_, out);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004735 Reset();
4736 }
4737
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004738 static void HeapChunkJavaCallback(void* start, void* end, size_t used_bytes, void* arg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004739 REQUIRES_SHARED(Locks::heap_bitmap_lock_,
Ian Rogersb726dcb2012-09-05 08:57:23 -07004740 Locks::mutator_lock_) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004741 reinterpret_cast<HeapChunkContext*>(arg)->HeapChunkJavaCallback(start, end, used_bytes);
4742 }
4743
4744 static void HeapChunkNativeCallback(void* start, void* end, size_t used_bytes, void* arg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004745 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004746 reinterpret_cast<HeapChunkContext*>(arg)->HeapChunkNativeCallback(start, end, used_bytes);
Elliott Hughesa2155262011-11-16 16:26:58 -08004747 }
4748
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004749 private:
Elliott Hughesa2155262011-11-16 16:26:58 -08004750 enum { ALLOCATION_UNIT_SIZE = 8 };
4751
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004752 void Reset() {
Ian Rogers30fab402012-01-23 15:43:46 -08004753 p_ = &buf_[0];
Mathieu Chartier36dab362014-07-30 14:59:56 -07004754 ResetStartOfNextChunk();
Ian Rogers30fab402012-01-23 15:43:46 -08004755 totalAllocationUnits_ = 0;
4756 needHeader_ = true;
Ian Rogersc0542af2014-09-03 16:16:56 -07004757 pieceLenField_ = nullptr;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004758 }
4759
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004760 bool IsNative() const {
4761 return type_ == CHUNK_TYPE("NHSG");
4762 }
4763
4764 // Returns true if the object is not an empty chunk.
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004765 bool ProcessRecord(void* start, size_t used_bytes) REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers30fab402012-01-23 15:43:46 -08004766 // Note: heap call backs cannot manipulate the heap upon which they are crawling, care is taken
4767 // in the following code not to allocate memory, by ensuring buf_ is of the correct size
Ian Rogers15bf2d32012-08-28 17:33:04 -07004768 if (used_bytes == 0) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004769 if (start == nullptr) {
4770 // Reset for start of new heap.
4771 startOfNextMemoryChunk_ = nullptr;
4772 Flush();
4773 }
4774 // Only process in use memory so that free region information
4775 // also includes dlmalloc book keeping.
4776 return false;
Elliott Hughesa2155262011-11-16 16:26:58 -08004777 }
Ian Rogersc0542af2014-09-03 16:16:56 -07004778 if (startOfNextMemoryChunk_ != nullptr) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004779 // Transmit any pending free memory. Native free memory of over kMaxFreeLen could be because
4780 // of the use of mmaps, so don't report. If not free memory then start a new segment.
4781 bool flush = true;
4782 if (start > startOfNextMemoryChunk_) {
4783 const size_t kMaxFreeLen = 2 * kPageSize;
4784 void* free_start = startOfNextMemoryChunk_;
4785 void* free_end = start;
4786 const size_t free_len =
4787 reinterpret_cast<uintptr_t>(free_end) - reinterpret_cast<uintptr_t>(free_start);
4788 if (!IsNative() || free_len < kMaxFreeLen) {
4789 AppendChunk(HPSG_STATE(SOLIDITY_FREE, 0), free_start, free_len, IsNative());
4790 flush = false;
Ian Rogers15bf2d32012-08-28 17:33:04 -07004791 }
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004792 }
4793 if (flush) {
4794 startOfNextMemoryChunk_ = nullptr;
4795 Flush();
4796 }
Ian Rogers15bf2d32012-08-28 17:33:04 -07004797 }
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004798 return true;
Ian Rogers15bf2d32012-08-28 17:33:04 -07004799 }
Elliott Hughesa2155262011-11-16 16:26:58 -08004800
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004801 void HeapChunkNativeCallback(void* start, void* /*end*/, size_t used_bytes)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004802 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004803 if (ProcessRecord(start, used_bytes)) {
4804 uint8_t state = ExamineNativeObject(start);
4805 AppendChunk(state, start, used_bytes + chunk_overhead_, true /*is_native*/);
4806 startOfNextMemoryChunk_ = reinterpret_cast<char*>(start) + used_bytes + chunk_overhead_;
4807 }
4808 }
4809
4810 void HeapChunkJavaCallback(void* start, void* /*end*/, size_t used_bytes)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004811 REQUIRES_SHARED(Locks::heap_bitmap_lock_, Locks::mutator_lock_) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004812 if (ProcessRecord(start, used_bytes)) {
4813 // Determine the type of this chunk.
4814 // OLD-TODO: if context.merge, see if this chunk is different from the last chunk.
4815 // If it's the same, we should combine them.
4816 uint8_t state = ExamineJavaObject(reinterpret_cast<mirror::Object*>(start));
4817 AppendChunk(state, start, used_bytes + chunk_overhead_, false /*is_native*/);
4818 startOfNextMemoryChunk_ = reinterpret_cast<char*>(start) + used_bytes + chunk_overhead_;
4819 }
4820 }
4821
4822 void AppendChunk(uint8_t state, void* ptr, size_t length, bool is_native)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004823 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07004824 // Make sure there's enough room left in the buffer.
4825 // We need to use two bytes for every fractional 256 allocation units used by the chunk plus
4826 // 17 bytes for any header.
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004827 const size_t needed = ((RoundUp(length / ALLOCATION_UNIT_SIZE, 256) / 256) * 2) + 17;
4828 size_t byte_left = &buf_.back() - p_;
4829 if (byte_left < needed) {
4830 if (is_native) {
Pavel Vyssotski7522c742014-12-08 13:38:26 +06004831 // Cannot trigger memory allocation while walking native heap.
Pavel Vyssotski7522c742014-12-08 13:38:26 +06004832 return;
4833 }
Ian Rogers15bf2d32012-08-28 17:33:04 -07004834 Flush();
4835 }
4836
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004837 byte_left = &buf_.back() - p_;
4838 if (byte_left < needed) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07004839 LOG(WARNING) << "Chunk is too big to transmit (chunk_len=" << length << ", "
4840 << needed << " bytes)";
4841 return;
4842 }
4843 EnsureHeader(ptr);
Elliott Hughesa2155262011-11-16 16:26:58 -08004844 // Write out the chunk description.
Ian Rogers15bf2d32012-08-28 17:33:04 -07004845 length /= ALLOCATION_UNIT_SIZE; // Convert to allocation units.
4846 totalAllocationUnits_ += length;
4847 while (length > 256) {
Ian Rogers30fab402012-01-23 15:43:46 -08004848 *p_++ = state | HPSG_PARTIAL;
4849 *p_++ = 255; // length - 1
Ian Rogers15bf2d32012-08-28 17:33:04 -07004850 length -= 256;
Elliott Hughesa2155262011-11-16 16:26:58 -08004851 }
Ian Rogers30fab402012-01-23 15:43:46 -08004852 *p_++ = state;
Ian Rogers15bf2d32012-08-28 17:33:04 -07004853 *p_++ = length - 1;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004854 }
4855
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004856 uint8_t ExamineNativeObject(const void* p) REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004857 return p == nullptr ? HPSG_STATE(SOLIDITY_FREE, 0) : HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
4858 }
4859
4860 uint8_t ExamineJavaObject(mirror::Object* o)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004861 REQUIRES_SHARED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -07004862 if (o == nullptr) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004863 return HPSG_STATE(SOLIDITY_FREE, 0);
4864 }
Elliott Hughesa2155262011-11-16 16:26:58 -08004865 // It's an allocated chunk. Figure out what it is.
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004866 gc::Heap* heap = Runtime::Current()->GetHeap();
4867 if (!heap->IsLiveObjectLocked(o)) {
4868 LOG(ERROR) << "Invalid object in managed heap: " << o;
Elliott Hughesa2155262011-11-16 16:26:58 -08004869 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
4870 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004871 mirror::Class* c = o->GetClass();
Ian Rogersc0542af2014-09-03 16:16:56 -07004872 if (c == nullptr) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004873 // The object was probably just created but hasn't been initialized yet.
4874 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
4875 }
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004876 if (!heap->IsValidObjectAddress(c)) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07004877 LOG(ERROR) << "Invalid class for managed heap object: " << o << " " << c;
Elliott Hughesa2155262011-11-16 16:26:58 -08004878 return HPSG_STATE(SOLIDITY_HARD, KIND_UNKNOWN);
4879 }
Mathieu Chartierf26e1b32015-01-29 10:47:10 -08004880 if (c->GetClass() == nullptr) {
4881 LOG(ERROR) << "Null class of class " << c << " for object " << o;
4882 return HPSG_STATE(SOLIDITY_HARD, KIND_UNKNOWN);
4883 }
Elliott Hughesa2155262011-11-16 16:26:58 -08004884 if (c->IsClassClass()) {
4885 return HPSG_STATE(SOLIDITY_HARD, KIND_CLASS_OBJECT);
4886 }
Elliott Hughesa2155262011-11-16 16:26:58 -08004887 if (c->IsArrayClass()) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004888 switch (c->GetComponentSize()) {
4889 case 1: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_1);
4890 case 2: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_2);
4891 case 4: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
4892 case 8: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_8);
4893 }
4894 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004895 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
4896 }
4897
Ian Rogers30fab402012-01-23 15:43:46 -08004898 std::vector<uint8_t> buf_;
4899 uint8_t* p_;
4900 uint8_t* pieceLenField_;
Ian Rogers15bf2d32012-08-28 17:33:04 -07004901 void* startOfNextMemoryChunk_;
Ian Rogers30fab402012-01-23 15:43:46 -08004902 size_t totalAllocationUnits_;
4903 uint32_t type_;
Ian Rogers30fab402012-01-23 15:43:46 -08004904 bool needHeader_;
Mathieu Chartier36dab362014-07-30 14:59:56 -07004905 size_t chunk_overhead_;
Ian Rogers30fab402012-01-23 15:43:46 -08004906
Elliott Hughesa2155262011-11-16 16:26:58 -08004907 DISALLOW_COPY_AND_ASSIGN(HeapChunkContext);
4908};
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004909
4910void Dbg::DdmSendHeapSegments(bool native) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004911 Dbg::HpsgWhen when = native ? gDdmNhsgWhen : gDdmHpsgWhen;
4912 Dbg::HpsgWhat what = native ? gDdmNhsgWhat : gDdmHpsgWhat;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004913 if (when == HPSG_WHEN_NEVER) {
4914 return;
4915 }
Alex Light772099a2017-11-21 14:05:04 -08004916 RuntimeCallbacks* cb = Runtime::Current()->GetRuntimeCallbacks();
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004917 // Figure out what kind of chunks we'll be sending.
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004918 CHECK(what == HPSG_WHAT_MERGED_OBJECTS || what == HPSG_WHAT_DISTINCT_OBJECTS)
4919 << static_cast<int>(what);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004920
4921 // First, send a heap start chunk.
4922 uint8_t heap_id[4];
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004923 JDWP::Set4BE(&heap_id[0], 1); // Heap id (bogus; we only have one heap).
Alex Light772099a2017-11-21 14:05:04 -08004924 cb->DdmPublishChunk(native ? CHUNK_TYPE("NHST") : CHUNK_TYPE("HPST"),
4925 ArrayRef<const uint8_t>(heap_id));
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07004926 Thread* self = Thread::Current();
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07004927 Locks::mutator_lock_->AssertSharedHeld(self);
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07004928
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004929 // Send a series of heap segment chunks.
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004930 HeapChunkContext context(what == HPSG_WHAT_MERGED_OBJECTS, native);
Andreas Gampe0c183382017-07-13 22:26:24 -07004931 auto bump_pointer_space_visitor = [&](mirror::Object* obj)
4932 REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
4933 const size_t size = RoundUp(obj->SizeOf(), kObjectAlignment);
4934 HeapChunkContext::HeapChunkJavaCallback(
4935 obj, reinterpret_cast<void*>(reinterpret_cast<uintptr_t>(obj) + size), size, &context);
4936 };
Elliott Hughesa2155262011-11-16 16:26:58 -08004937 if (native) {
Dimitry Ivanove6465bc2015-12-14 18:55:02 -08004938 UNIMPLEMENTED(WARNING) << "Native heap inspection is not supported";
Elliott Hughesa2155262011-11-16 16:26:58 -08004939 } else {
Ian Rogers1d54e732013-05-02 21:10:01 -07004940 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartier36dab362014-07-30 14:59:56 -07004941 for (const auto& space : heap->GetContinuousSpaces()) {
4942 if (space->IsDlMallocSpace()) {
Mathieu Chartier4c69d7f2014-10-10 12:45:50 -07004943 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004944 // dlmalloc's chunk header is 2 * sizeof(size_t), but if the previous chunk is in use for an
4945 // allocation then the first sizeof(size_t) may belong to it.
4946 context.SetChunkOverhead(sizeof(size_t));
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004947 space->AsDlMallocSpace()->Walk(HeapChunkContext::HeapChunkJavaCallback, &context);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004948 } else if (space->IsRosAllocSpace()) {
4949 context.SetChunkOverhead(0);
Mathieu Chartier4c69d7f2014-10-10 12:45:50 -07004950 // Need to acquire the mutator lock before the heap bitmap lock with exclusive access since
4951 // RosAlloc's internal logic doesn't know to release and reacquire the heap bitmap lock.
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07004952 ScopedThreadSuspension sts(self, kSuspended);
Mathieu Chartier4f55e222015-09-04 13:26:21 -07004953 ScopedSuspendAll ssa(__FUNCTION__);
4954 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
4955 space->AsRosAllocSpace()->Walk(HeapChunkContext::HeapChunkJavaCallback, &context);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004956 } else if (space->IsBumpPointerSpace()) {
Mathieu Chartier4c69d7f2014-10-10 12:45:50 -07004957 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004958 context.SetChunkOverhead(0);
Andreas Gampe0c183382017-07-13 22:26:24 -07004959 space->AsBumpPointerSpace()->Walk(bump_pointer_space_visitor);
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004960 HeapChunkContext::HeapChunkJavaCallback(nullptr, nullptr, 0, &context);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08004961 } else if (space->IsRegionSpace()) {
4962 heap->IncrementDisableMovingGC(self);
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07004963 {
4964 ScopedThreadSuspension sts(self, kSuspended);
Mathieu Chartier4f55e222015-09-04 13:26:21 -07004965 ScopedSuspendAll ssa(__FUNCTION__);
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07004966 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
4967 context.SetChunkOverhead(0);
Andreas Gampe0c183382017-07-13 22:26:24 -07004968 space->AsRegionSpace()->Walk(bump_pointer_space_visitor);
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07004969 HeapChunkContext::HeapChunkJavaCallback(nullptr, nullptr, 0, &context);
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07004970 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08004971 heap->DecrementDisableMovingGC(self);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004972 } else {
4973 UNIMPLEMENTED(WARNING) << "Not counting objects in space " << *space;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07004974 }
Mathieu Chartier36dab362014-07-30 14:59:56 -07004975 context.ResetStartOfNextChunk();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07004976 }
Mathieu Chartier4c69d7f2014-10-10 12:45:50 -07004977 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07004978 // Walk the large objects, these are not in the AllocSpace.
Mathieu Chartier36dab362014-07-30 14:59:56 -07004979 context.SetChunkOverhead(0);
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004980 heap->GetLargeObjectsSpace()->Walk(HeapChunkContext::HeapChunkJavaCallback, &context);
Elliott Hughesa2155262011-11-16 16:26:58 -08004981 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004982
4983 // Finally, send a heap end chunk.
Alex Light772099a2017-11-21 14:05:04 -08004984 cb->DdmPublishChunk(native ? CHUNK_TYPE("NHEN") : CHUNK_TYPE("HPEN"),
4985 ArrayRef<const uint8_t>(heap_id));
Elliott Hughes767a1472011-10-26 18:49:02 -07004986}
4987
Brian Carlstrom306db812014-09-05 13:01:41 -07004988void Dbg::SetAllocTrackingEnabled(bool enable) {
Man Cao8c2ff642015-05-27 17:25:30 -07004989 gc::AllocRecordObjectMap::SetAllocTrackingEnabled(enable);
Elliott Hughes545a0642011-11-08 19:10:03 -08004990}
4991
4992void Dbg::DumpRecentAllocations() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004993 ScopedObjectAccess soa(Thread::Current());
Brian Carlstrom306db812014-09-05 13:01:41 -07004994 MutexLock mu(soa.Self(), *Locks::alloc_tracker_lock_);
Man Cao8c2ff642015-05-27 17:25:30 -07004995 if (!Runtime::Current()->GetHeap()->IsAllocTrackingEnabled()) {
Elliott Hughes545a0642011-11-08 19:10:03 -08004996 LOG(INFO) << "Not recording tracked allocations";
4997 return;
4998 }
Man Cao8c2ff642015-05-27 17:25:30 -07004999 gc::AllocRecordObjectMap* records = Runtime::Current()->GetHeap()->GetAllocationRecords();
5000 CHECK(records != nullptr);
Elliott Hughes545a0642011-11-08 19:10:03 -08005001
Man Cao1ed11b92015-06-11 22:47:35 -07005002 const uint16_t capped_count = CappedAllocRecordCount(records->GetRecentAllocationSize());
Brian Carlstrom306db812014-09-05 13:01:41 -07005003 uint16_t count = capped_count;
Elliott Hughes545a0642011-11-08 19:10:03 -08005004
Man Cao8c2ff642015-05-27 17:25:30 -07005005 LOG(INFO) << "Tracked allocations, (count=" << count << ")";
5006 for (auto it = records->RBegin(), end = records->REnd();
5007 count > 0 && it != end; count--, it++) {
Mathieu Chartier458b1052016-03-29 14:02:55 -07005008 const gc::AllocRecord* record = &it->second;
Elliott Hughes545a0642011-11-08 19:10:03 -08005009
Man Cao8c2ff642015-05-27 17:25:30 -07005010 LOG(INFO) << StringPrintf(" Thread %-2d %6zd bytes ", record->GetTid(), record->ByteCount())
David Sehr709b0702016-10-13 09:12:37 -07005011 << mirror::Class::PrettyClass(record->GetClass());
Elliott Hughes545a0642011-11-08 19:10:03 -08005012
Man Cao8c2ff642015-05-27 17:25:30 -07005013 for (size_t stack_frame = 0, depth = record->GetDepth(); stack_frame < depth; ++stack_frame) {
5014 const gc::AllocRecordStackTraceElement& stack_element = record->StackElement(stack_frame);
5015 ArtMethod* m = stack_element.GetMethod();
David Sehr709b0702016-10-13 09:12:37 -07005016 LOG(INFO) << " " << ArtMethod::PrettyMethod(m) << " line "
5017 << stack_element.ComputeLineNumber();
Elliott Hughes545a0642011-11-08 19:10:03 -08005018 }
5019
5020 // pause periodically to help logcat catch up
5021 if ((count % 5) == 0) {
5022 usleep(40000);
5023 }
Elliott Hughes545a0642011-11-08 19:10:03 -08005024 }
5025}
5026
5027class StringTable {
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07005028 private:
5029 struct Entry {
Andreas Gampe84eadb22017-07-07 15:08:01 -07005030 explicit Entry(const char* data_in)
5031 : data(data_in), hash(ComputeModifiedUtf8Hash(data_in)), index(0) {
5032 }
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07005033 Entry(const Entry& entry) = default;
5034 Entry(Entry&& entry) = default;
5035
5036 // Pointer to the actual string data.
5037 const char* data;
Andreas Gampe84eadb22017-07-07 15:08:01 -07005038
5039 // The hash of the data.
5040 const uint32_t hash;
5041
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07005042 // The index. This will be filled in on Finish and is not part of the ordering, so mark it
5043 // mutable.
5044 mutable uint32_t index;
5045
Andreas Gampe84eadb22017-07-07 15:08:01 -07005046 bool operator==(const Entry& other) const {
5047 return strcmp(data, other.data) == 0;
5048 }
5049 };
5050 struct EntryHash {
5051 size_t operator()(const Entry& entry) const {
5052 return entry.hash;
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07005053 }
5054 };
5055
Elliott Hughes545a0642011-11-08 19:10:03 -08005056 public:
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07005057 StringTable() : finished_(false) {
Elliott Hughes545a0642011-11-08 19:10:03 -08005058 }
5059
Andreas Gampef774a4e2017-07-06 22:15:18 -07005060 void Add(const char* str, bool copy_string) {
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07005061 DCHECK(!finished_);
Andreas Gampef774a4e2017-07-06 22:15:18 -07005062 if (UNLIKELY(copy_string)) {
5063 // Check whether it's already there.
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07005064 Entry entry(str);
5065 if (table_.find(entry) != table_.end()) {
Andreas Gampef774a4e2017-07-06 22:15:18 -07005066 return;
5067 }
Mathieu Chartier4345c462014-06-27 10:20:14 -07005068
Andreas Gampef774a4e2017-07-06 22:15:18 -07005069 // Make a copy.
5070 size_t str_len = strlen(str);
5071 char* copy = new char[str_len + 1];
5072 strlcpy(copy, str, str_len + 1);
5073 string_backup_.emplace_back(copy);
5074 str = copy;
5075 }
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07005076 Entry entry(str);
5077 table_.insert(entry);
5078 }
5079
5080 // Update all entries and give them an index. Note that this is likely not the insertion order,
5081 // as the set will with high likelihood reorder elements. Thus, Add must not be called after
5082 // Finish, and Finish must be called before IndexOf. In that case, WriteTo will walk in
5083 // the same order as Finish, and indices will agree. The order invariant, as well as indices,
5084 // are enforced through debug checks.
5085 void Finish() {
5086 DCHECK(!finished_);
5087 finished_ = true;
5088 uint32_t index = 0;
5089 for (auto& entry : table_) {
5090 entry.index = index;
5091 ++index;
5092 }
Elliott Hughes545a0642011-11-08 19:10:03 -08005093 }
5094
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07005095 size_t IndexOf(const char* s) const {
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07005096 DCHECK(finished_);
5097 Entry entry(s);
5098 auto it = table_.find(entry);
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07005099 if (it == table_.end()) {
5100 LOG(FATAL) << "IndexOf(\"" << s << "\") failed";
5101 }
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07005102 return it->index;
Elliott Hughes545a0642011-11-08 19:10:03 -08005103 }
5104
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07005105 size_t Size() const {
Elliott Hughes545a0642011-11-08 19:10:03 -08005106 return table_.size();
5107 }
5108
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07005109 void WriteTo(std::vector<uint8_t>& bytes) const {
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07005110 DCHECK(finished_);
5111 uint32_t cur_index = 0;
5112 for (const auto& entry : table_) {
5113 DCHECK_EQ(cur_index++, entry.index);
5114
5115 size_t s_len = CountModifiedUtf8Chars(entry.data);
Christopher Ferris8a354052015-04-24 17:23:53 -07005116 std::unique_ptr<uint16_t[]> s_utf16(new uint16_t[s_len]);
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07005117 ConvertModifiedUtf8ToUtf16(s_utf16.get(), entry.data);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005118 JDWP::AppendUtf16BE(bytes, s_utf16.get(), s_len);
Elliott Hughes545a0642011-11-08 19:10:03 -08005119 }
5120 }
5121
5122 private:
Andreas Gampe84eadb22017-07-07 15:08:01 -07005123 std::unordered_set<Entry, EntryHash> table_;
Andreas Gampef774a4e2017-07-06 22:15:18 -07005124 std::vector<std::unique_ptr<char[]>> string_backup_;
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07005125
5126 bool finished_;
5127
Elliott Hughes545a0642011-11-08 19:10:03 -08005128 DISALLOW_COPY_AND_ASSIGN(StringTable);
5129};
5130
Mathieu Chartiere401d142015-04-22 13:56:20 -07005131static const char* GetMethodSourceFile(ArtMethod* method)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005132 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07005133 DCHECK(method != nullptr);
5134 const char* source_file = method->GetDeclaringClassSourceFile();
Sebastien Hertz280286a2014-04-28 09:26:50 +02005135 return (source_file != nullptr) ? source_file : "";
5136}
5137
Elliott Hughes545a0642011-11-08 19:10:03 -08005138/*
5139 * The data we send to DDMS contains everything we have recorded.
5140 *
5141 * Message header (all values big-endian):
5142 * (1b) message header len (to allow future expansion); includes itself
5143 * (1b) entry header len
5144 * (1b) stack frame len
5145 * (2b) number of entries
5146 * (4b) offset to string table from start of message
5147 * (2b) number of class name strings
5148 * (2b) number of method name strings
5149 * (2b) number of source file name strings
5150 * For each entry:
5151 * (4b) total allocation size
Elliott Hughes221229c2013-01-08 18:17:50 -08005152 * (2b) thread id
Elliott Hughes545a0642011-11-08 19:10:03 -08005153 * (2b) allocated object's class name index
5154 * (1b) stack depth
5155 * For each stack frame:
5156 * (2b) method's class name
5157 * (2b) method name
5158 * (2b) method source file
5159 * (2b) line number, clipped to 32767; -2 if native; -1 if no source
5160 * (xb) class name strings
5161 * (xb) method name strings
5162 * (xb) source file strings
5163 *
5164 * As with other DDM traffic, strings are sent as a 4-byte length
5165 * followed by UTF-16 data.
5166 *
5167 * We send up 16-bit unsigned indexes into string tables. In theory there
Brian Carlstrom306db812014-09-05 13:01:41 -07005168 * can be (kMaxAllocRecordStackDepth * alloc_record_max_) unique strings in
Elliott Hughes545a0642011-11-08 19:10:03 -08005169 * each table, but in practice there should be far fewer.
5170 *
5171 * The chief reason for using a string table here is to keep the size of
5172 * the DDMS message to a minimum. This is partly to make the protocol
5173 * efficient, but also because we have to form the whole thing up all at
5174 * once in a memory buffer.
5175 *
5176 * We use separate string tables for class names, method names, and source
5177 * files to keep the indexes small. There will generally be no overlap
5178 * between the contents of these tables.
5179 */
5180jbyteArray Dbg::GetRecentAllocations() {
Ian Rogerscf7f1912014-10-22 22:06:39 -07005181 if ((false)) {
Elliott Hughes545a0642011-11-08 19:10:03 -08005182 DumpRecentAllocations();
5183 }
5184
Ian Rogers50b35e22012-10-04 10:09:15 -07005185 Thread* self = Thread::Current();
Elliott Hughes545a0642011-11-08 19:10:03 -08005186 std::vector<uint8_t> bytes;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005187 {
Brian Carlstrom306db812014-09-05 13:01:41 -07005188 MutexLock mu(self, *Locks::alloc_tracker_lock_);
Man Cao8c2ff642015-05-27 17:25:30 -07005189 gc::AllocRecordObjectMap* records = Runtime::Current()->GetHeap()->GetAllocationRecords();
5190 // In case this method is called when allocation tracker is disabled,
5191 // we should still send some data back.
5192 gc::AllocRecordObjectMap dummy;
5193 if (records == nullptr) {
5194 CHECK(!Runtime::Current()->GetHeap()->IsAllocTrackingEnabled());
5195 records = &dummy;
5196 }
Man Cao41656de2015-07-06 18:53:15 -07005197 // We don't need to wait on the condition variable records->new_record_condition_, because this
5198 // function only reads the class objects, which are already marked so it doesn't change their
5199 // reachability.
Man Cao8c2ff642015-05-27 17:25:30 -07005200
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005201 //
5202 // Part 1: generate string tables.
5203 //
5204 StringTable class_names;
5205 StringTable method_names;
5206 StringTable filenames;
Elliott Hughes545a0642011-11-08 19:10:03 -08005207
Andreas Gampeff29cee2017-07-07 11:11:15 -07005208 VLOG(jdwp) << "Collecting StringTables.";
5209
Man Cao1ed11b92015-06-11 22:47:35 -07005210 const uint16_t capped_count = CappedAllocRecordCount(records->GetRecentAllocationSize());
Brian Carlstrom306db812014-09-05 13:01:41 -07005211 uint16_t count = capped_count;
Andreas Gamped0fc7682017-07-07 14:03:08 -07005212 size_t alloc_byte_count = 0;
Man Cao8c2ff642015-05-27 17:25:30 -07005213 for (auto it = records->RBegin(), end = records->REnd();
5214 count > 0 && it != end; count--, it++) {
Mathieu Chartier458b1052016-03-29 14:02:55 -07005215 const gc::AllocRecord* record = &it->second;
Ian Rogers1ff3c982014-08-12 02:30:58 -07005216 std::string temp;
Andreas Gampef774a4e2017-07-06 22:15:18 -07005217 const char* class_descr = record->GetClassDescriptor(&temp);
5218 class_names.Add(class_descr, !temp.empty());
Andreas Gamped0fc7682017-07-07 14:03:08 -07005219
5220 // Size + tid + class name index + stack depth.
5221 alloc_byte_count += 4u + 2u + 2u + 1u;
5222
Man Cao8c2ff642015-05-27 17:25:30 -07005223 for (size_t i = 0, depth = record->GetDepth(); i < depth; i++) {
5224 ArtMethod* m = record->StackElement(i).GetMethod();
Andreas Gampef774a4e2017-07-06 22:15:18 -07005225 class_names.Add(m->GetDeclaringClassDescriptor(), false);
5226 method_names.Add(m->GetName(), false);
5227 filenames.Add(GetMethodSourceFile(m), false);
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005228 }
Andreas Gamped0fc7682017-07-07 14:03:08 -07005229
5230 // Depth * (class index + method name index + file name index + line number).
5231 alloc_byte_count += record->GetDepth() * (2u + 2u + 2u + 2u);
Elliott Hughes545a0642011-11-08 19:10:03 -08005232 }
5233
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07005234 class_names.Finish();
5235 method_names.Finish();
5236 filenames.Finish();
Andreas Gampeff29cee2017-07-07 11:11:15 -07005237 VLOG(jdwp) << "Done collecting StringTables:" << std::endl
5238 << " ClassNames: " << class_names.Size() << std::endl
5239 << " MethodNames: " << method_names.Size() << std::endl
5240 << " Filenames: " << filenames.Size();
5241
Man Cao8c2ff642015-05-27 17:25:30 -07005242 LOG(INFO) << "recent allocation records: " << capped_count;
5243 LOG(INFO) << "allocation records all objects: " << records->Size();
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005244
5245 //
5246 // Part 2: Generate the output and store it in the buffer.
5247 //
5248
5249 // (1b) message header len (to allow future expansion); includes itself
5250 // (1b) entry header len
5251 // (1b) stack frame len
5252 const int kMessageHeaderLen = 15;
5253 const int kEntryHeaderLen = 9;
5254 const int kStackFrameLen = 8;
5255 JDWP::Append1BE(bytes, kMessageHeaderLen);
5256 JDWP::Append1BE(bytes, kEntryHeaderLen);
5257 JDWP::Append1BE(bytes, kStackFrameLen);
5258
5259 // (2b) number of entries
5260 // (4b) offset to string table from start of message
5261 // (2b) number of class name strings
5262 // (2b) number of method name strings
5263 // (2b) number of source file name strings
Brian Carlstrom306db812014-09-05 13:01:41 -07005264 JDWP::Append2BE(bytes, capped_count);
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005265 size_t string_table_offset = bytes.size();
Brian Carlstrom7934ac22013-07-26 10:54:15 -07005266 JDWP::Append4BE(bytes, 0); // We'll patch this later...
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005267 JDWP::Append2BE(bytes, class_names.Size());
5268 JDWP::Append2BE(bytes, method_names.Size());
5269 JDWP::Append2BE(bytes, filenames.Size());
5270
Andreas Gampeff29cee2017-07-07 11:11:15 -07005271 VLOG(jdwp) << "Dumping allocations with stacks";
5272
Andreas Gamped0fc7682017-07-07 14:03:08 -07005273 // Enlarge the vector for the allocation data.
5274 size_t reserve_size = bytes.size() + alloc_byte_count;
5275 bytes.reserve(reserve_size);
5276
Ian Rogers1ff3c982014-08-12 02:30:58 -07005277 std::string temp;
Man Cao8c2ff642015-05-27 17:25:30 -07005278 count = capped_count;
5279 // The last "count" number of allocation records in "records" are the most recent "count" number
5280 // of allocations. Reverse iterate to get them. The most recent allocation is sent first.
5281 for (auto it = records->RBegin(), end = records->REnd();
5282 count > 0 && it != end; count--, it++) {
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005283 // For each entry:
5284 // (4b) total allocation size
5285 // (2b) thread id
5286 // (2b) allocated object's class name index
5287 // (1b) stack depth
Mathieu Chartier458b1052016-03-29 14:02:55 -07005288 const gc::AllocRecord* record = &it->second;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005289 size_t stack_depth = record->GetDepth();
Mathieu Chartierf8322842014-05-16 10:59:25 -07005290 size_t allocated_object_class_name_index =
Man Cao41656de2015-07-06 18:53:15 -07005291 class_names.IndexOf(record->GetClassDescriptor(&temp));
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07005292 JDWP::Append4BE(bytes, record->ByteCount());
Man Cao8c2ff642015-05-27 17:25:30 -07005293 JDWP::Append2BE(bytes, static_cast<uint16_t>(record->GetTid()));
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005294 JDWP::Append2BE(bytes, allocated_object_class_name_index);
5295 JDWP::Append1BE(bytes, stack_depth);
5296
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005297 for (size_t stack_frame = 0; stack_frame < stack_depth; ++stack_frame) {
5298 // For each stack frame:
5299 // (2b) method's class name
5300 // (2b) method name
5301 // (2b) method source file
5302 // (2b) line number, clipped to 32767; -2 if native; -1 if no source
Man Cao8c2ff642015-05-27 17:25:30 -07005303 ArtMethod* m = record->StackElement(stack_frame).GetMethod();
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07005304 size_t class_name_index = class_names.IndexOf(m->GetDeclaringClassDescriptor());
5305 size_t method_name_index = method_names.IndexOf(m->GetName());
5306 size_t file_name_index = filenames.IndexOf(GetMethodSourceFile(m));
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005307 JDWP::Append2BE(bytes, class_name_index);
5308 JDWP::Append2BE(bytes, method_name_index);
5309 JDWP::Append2BE(bytes, file_name_index);
Man Cao8c2ff642015-05-27 17:25:30 -07005310 JDWP::Append2BE(bytes, record->StackElement(stack_frame).ComputeLineNumber());
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005311 }
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005312 }
5313
Andreas Gamped0fc7682017-07-07 14:03:08 -07005314 CHECK_EQ(bytes.size(), reserve_size);
Andreas Gampeff29cee2017-07-07 11:11:15 -07005315 VLOG(jdwp) << "Dumping tables.";
5316
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005317 // (xb) class name strings
5318 // (xb) method name strings
5319 // (xb) source file strings
5320 JDWP::Set4BE(&bytes[string_table_offset], bytes.size());
5321 class_names.WriteTo(bytes);
5322 method_names.WriteTo(bytes);
5323 filenames.WriteTo(bytes);
Andreas Gampeff29cee2017-07-07 11:11:15 -07005324
5325 VLOG(jdwp) << "GetRecentAllocations: data created. " << bytes.size();
Elliott Hughes545a0642011-11-08 19:10:03 -08005326 }
Ian Rogers50b35e22012-10-04 10:09:15 -07005327 JNIEnv* env = self->GetJniEnv();
Elliott Hughes545a0642011-11-08 19:10:03 -08005328 jbyteArray result = env->NewByteArray(bytes.size());
Ian Rogersc0542af2014-09-03 16:16:56 -07005329 if (result != nullptr) {
Elliott Hughes545a0642011-11-08 19:10:03 -08005330 env->SetByteArrayRegion(result, 0, bytes.size(), reinterpret_cast<const jbyte*>(&bytes[0]));
5331 }
5332 return result;
5333}
5334
Mathieu Chartiere401d142015-04-22 13:56:20 -07005335ArtMethod* DeoptimizationRequest::Method() const {
Andreas Gampe13b27842016-11-07 16:48:23 -08005336 return jni::DecodeArtMethod(method_);
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07005337}
5338
Mathieu Chartiere401d142015-04-22 13:56:20 -07005339void DeoptimizationRequest::SetMethod(ArtMethod* m) {
Andreas Gampe13b27842016-11-07 16:48:23 -08005340 method_ = jni::EncodeArtMethod(m);
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07005341}
5342
Mathieu Chartiera6b1ead2015-10-06 10:32:38 -07005343void Dbg::VisitRoots(RootVisitor* visitor) {
5344 // Visit breakpoint roots, used to prevent unloading of methods with breakpoints.
5345 ReaderMutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
5346 BufferedRootVisitor<128> root_visitor(visitor, RootInfo(kRootVMInternal));
5347 for (Breakpoint& breakpoint : gBreakpoints) {
Andreas Gampe542451c2016-07-26 09:02:02 -07005348 breakpoint.Method()->VisitRoots(root_visitor, kRuntimePointerSize);
Mathieu Chartiera6b1ead2015-10-06 10:32:38 -07005349 }
5350}
5351
Andreas Gampe04bbb5b2017-01-19 17:49:03 +00005352void Dbg::DbgThreadLifecycleCallback::ThreadStart(Thread* self) {
5353 Dbg::PostThreadStart(self);
5354}
5355
5356void Dbg::DbgThreadLifecycleCallback::ThreadDeath(Thread* self) {
5357 Dbg::PostThreadDeath(self);
5358}
5359
Andreas Gampe0f01b582017-01-18 15:22:37 -08005360void Dbg::DbgClassLoadCallback::ClassLoad(Handle<mirror::Class> klass ATTRIBUTE_UNUSED) {
5361 // Ignore ClassLoad;
5362}
5363void Dbg::DbgClassLoadCallback::ClassPrepare(Handle<mirror::Class> temp_klass ATTRIBUTE_UNUSED,
5364 Handle<mirror::Class> klass) {
5365 Dbg::PostClassPrepare(klass.Get());
5366}
5367
Elliott Hughes872d4ec2011-10-21 17:07:15 -07005368} // namespace art