blob: 541bd1da81bb7d289c97418619952660901ddb29 [file] [log] [blame]
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "debugger.h"
18
Elliott Hughes3bb81562011-10-21 18:52:59 -070019#include <sys/uio.h>
20
Alex Light8c2b9292017-11-09 13:21:01 -080021#include <functional>
Andreas Gampef774a4e2017-07-06 22:15:18 -070022#include <memory>
Elliott Hughes545a0642011-11-08 19:10:03 -080023#include <set>
Andreas Gampef774a4e2017-07-06 22:15:18 -070024#include <vector>
Elliott Hughes545a0642011-11-08 19:10:03 -080025
Andreas Gampe46ee31b2016-12-14 10:11:49 -080026#include "android-base/stringprintf.h"
27
Ian Rogers166db042013-07-26 12:05:57 -070028#include "arch/context.h"
Mathieu Chartierc7853442015-03-27 14:35:38 -070029#include "art_field-inl.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070030#include "art_method-inl.h"
Andreas Gampe542451c2016-07-26 09:02:02 -070031#include "base/enums.h"
Andreas Gampef774a4e2017-07-06 22:15:18 -070032#include "base/strlcpy.h"
Vladimir Marko80afd022015-05-19 18:08:00 +010033#include "base/time_utils.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080034#include "class_linker-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -070035#include "class_linker.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070036#include "dex_file-inl.h"
David Sehr9323e6e2016-09-13 08:58:35 -070037#include "dex_file_annotations.h"
Andreas Gampee2abbc62017-09-15 11:59:26 -070038#include "dex_file_types.h"
Ian Rogers776ac1f2012-04-13 23:36:36 -070039#include "dex_instruction.h"
Mingyao Yang6ea1a0e2016-01-29 12:12:49 -080040#include "entrypoints/runtime_asm_entrypoints.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070041#include "gc/accounting/card_table-inl.h"
Man Cao8c2ff642015-05-27 17:25:30 -070042#include "gc/allocation_record.h"
Mathieu Chartieraa516822015-10-02 15:53:37 -070043#include "gc/scoped_gc_critical_section.h"
Andreas Gampe0c183382017-07-13 22:26:24 -070044#include "gc/space/bump_pointer_space-walk-inl.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070045#include "gc/space/large_object_space.h"
46#include "gc/space/space-inl.h"
Andreas Gampe513061a2017-06-01 09:17:34 -070047#include "handle_scope-inl.h"
Sebastien Hertzcbc50642015-06-01 17:33:12 +020048#include "jdwp/jdwp_priv.h"
Elliott Hughes64f574f2013-02-20 14:57:12 -080049#include "jdwp/object_registry.h"
Andreas Gampe13b27842016-11-07 16:48:23 -080050#include "jni_internal.h"
Mathieu Chartier28bd2e42016-10-04 13:54:57 -070051#include "jvalue-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080052#include "mirror/class-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -070053#include "mirror/class.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080054#include "mirror/class_loader.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080055#include "mirror/object-inl.h"
56#include "mirror/object_array-inl.h"
Ian Rogersb0fa5dc2014-04-28 16:47:08 -070057#include "mirror/string-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080058#include "mirror/throwable.h"
Andreas Gampe373a9b52017-10-18 09:01:57 -070059#include "nativehelper/scoped_local_ref.h"
60#include "nativehelper/scoped_primitive_array.h"
Nicolas Geoffray58cc1cb2017-11-20 13:27:29 +000061#include "oat_file.h"
Mathieu Chartier3398c782016-09-30 10:27:43 -070062#include "obj_ptr-inl.h"
Ian Rogers53b8b092014-03-13 23:45:53 -070063#include "reflection.h"
Elliott Hughesa0e18062012-04-13 15:59:59 -070064#include "safe_map.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070065#include "scoped_thread_state_change-inl.h"
Andreas Gampe513061a2017-06-01 09:17:34 -070066#include "stack.h"
Elliott Hughes475fc232011-10-25 15:00:35 -070067#include "thread_list.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080068#include "utf.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070069#include "well_known_classes.h"
Elliott Hughes475fc232011-10-25 15:00:35 -070070
Elliott Hughes872d4ec2011-10-21 17:07:15 -070071namespace art {
72
Andreas Gampe46ee31b2016-12-14 10:11:49 -080073using android::base::StringPrintf;
74
Sebastien Hertz0462c4c2015-04-01 16:34:17 +020075// The key identifying the debugger to update instrumentation.
76static constexpr const char* kDbgInstrumentationKey = "Debugger";
77
Man Cao8c2ff642015-05-27 17:25:30 -070078// 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 -070079static uint16_t CappedAllocRecordCount(size_t alloc_record_count) {
Man Cao1ed11b92015-06-11 22:47:35 -070080 const size_t cap = 0xffff;
Man Cao8c2ff642015-05-27 17:25:30 -070081 if (alloc_record_count > cap) {
82 return cap;
Brian Carlstrom306db812014-09-05 13:01:41 -070083 }
84 return alloc_record_count;
85}
Elliott Hughes475fc232011-10-25 15:00:35 -070086
Mathieu Chartier41af5e52015-10-28 11:10:46 -070087class Breakpoint : public ValueObject {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -070088 public:
Mathieu Chartier41af5e52015-10-28 11:10:46 -070089 Breakpoint(ArtMethod* method, uint32_t dex_pc, DeoptimizationRequest::Kind deoptimization_kind)
Alex Light97e78032017-06-27 17:51:55 -070090 : method_(method->GetCanonicalMethod(kRuntimePointerSize)),
Mathieu Chartier41af5e52015-10-28 11:10:46 -070091 dex_pc_(dex_pc),
92 deoptimization_kind_(deoptimization_kind) {
Sebastien Hertzf3928792014-11-17 19:00:37 +010093 CHECK(deoptimization_kind_ == DeoptimizationRequest::kNothing ||
94 deoptimization_kind_ == DeoptimizationRequest::kSelectiveDeoptimization ||
95 deoptimization_kind_ == DeoptimizationRequest::kFullDeoptimization);
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -070096 }
97
Andreas Gampebdf7f1c2016-08-30 16:38:47 -070098 Breakpoint(const Breakpoint& other) REQUIRES_SHARED(Locks::mutator_lock_)
Mathieu Chartier41af5e52015-10-28 11:10:46 -070099 : method_(other.method_),
100 dex_pc_(other.dex_pc_),
101 deoptimization_kind_(other.deoptimization_kind_) {}
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700102
Mathieu Chartier41af5e52015-10-28 11:10:46 -0700103 // Method() is called from root visiting, do not use ScopedObjectAccess here or it can cause
104 // GC to deadlock if another thread tries to call SuspendAll while the GC is in a runnable state.
105 ArtMethod* Method() const {
106 return method_;
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700107 }
108
109 uint32_t DexPc() const {
110 return dex_pc_;
111 }
112
Sebastien Hertzf3928792014-11-17 19:00:37 +0100113 DeoptimizationRequest::Kind GetDeoptimizationKind() const {
114 return deoptimization_kind_;
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700115 }
116
Alex Light6c8467f2015-11-20 15:03:26 -0800117 // Returns true if the method of this breakpoint and the passed in method should be considered the
118 // same. That is, they are either the same method or they are copied from the same method.
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700119 bool IsInMethod(ArtMethod* m) const REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light97e78032017-06-27 17:51:55 -0700120 return method_ == m->GetCanonicalMethod(kRuntimePointerSize);
Alex Light6c8467f2015-11-20 15:03:26 -0800121 }
122
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700123 private:
Sebastien Hertza76a6d42014-03-20 16:40:17 +0100124 // The location of this breakpoint.
Mathieu Chartier41af5e52015-10-28 11:10:46 -0700125 ArtMethod* method_;
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700126 uint32_t dex_pc_;
Sebastien Hertza76a6d42014-03-20 16:40:17 +0100127
128 // Indicates whether breakpoint needs full deoptimization or selective deoptimization.
Sebastien Hertzf3928792014-11-17 19:00:37 +0100129 DeoptimizationRequest::Kind deoptimization_kind_;
Elliott Hughes86964332012-02-15 19:37:42 -0800130};
131
Sebastien Hertzed2be172014-08-19 15:33:43 +0200132static std::ostream& operator<<(std::ostream& os, const Breakpoint& rhs)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700133 REQUIRES_SHARED(Locks::mutator_lock_) {
David Sehr709b0702016-10-13 09:12:37 -0700134 os << StringPrintf("Breakpoint[%s @%#x]", ArtMethod::PrettyMethod(rhs.Method()).c_str(),
135 rhs.DexPc());
Elliott Hughes86964332012-02-15 19:37:42 -0800136 return os;
137}
138
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200139class DebugInstrumentationListener FINAL : public instrumentation::InstrumentationListener {
Ian Rogers62d6c772013-02-27 08:32:07 -0800140 public:
141 DebugInstrumentationListener() {}
142 virtual ~DebugInstrumentationListener() {}
143
Alex Lightd7661582017-05-01 13:48:16 -0700144 void MethodEntered(Thread* thread,
145 Handle<mirror::Object> this_object,
146 ArtMethod* method,
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200147 uint32_t dex_pc)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700148 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800149 if (method->IsNative()) {
150 // TODO: post location events is a suspension point and native method entry stubs aren't.
151 return;
152 }
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200153 if (IsListeningToDexPcMoved()) {
154 // We also listen to kDexPcMoved instrumentation event so we know the DexPcMoved method is
155 // going to be called right after us. To avoid sending JDWP events twice for this location,
156 // we report the event in DexPcMoved. However, we must remind this is method entry so we
157 // send the METHOD_ENTRY event. And we can also group it with other events for this location
158 // like BREAKPOINT or SINGLE_STEP (or even METHOD_EXIT if this is a RETURN instruction).
159 thread->SetDebugMethodEntry();
160 } else if (IsListeningToMethodExit() && IsReturn(method, dex_pc)) {
161 // We also listen to kMethodExited instrumentation event and the current instruction is a
162 // RETURN so we know the MethodExited method is going to be called right after us. To avoid
163 // sending JDWP events twice for this location, we report the event(s) in MethodExited.
164 // However, we must remind this is method entry so we send the METHOD_ENTRY event. And we can
165 // also group it with other events for this location like BREAKPOINT or SINGLE_STEP.
166 thread->SetDebugMethodEntry();
167 } else {
Alex Lightd7661582017-05-01 13:48:16 -0700168 Dbg::UpdateDebugger(thread, this_object.Get(), method, 0, Dbg::kMethodEntry, nullptr);
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200169 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800170 }
171
Alex Lightd7661582017-05-01 13:48:16 -0700172 void MethodExited(Thread* thread,
173 Handle<mirror::Object> this_object,
174 ArtMethod* method,
175 uint32_t dex_pc,
176 const JValue& return_value)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700177 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800178 if (method->IsNative()) {
179 // TODO: post location events is a suspension point and native method entry stubs aren't.
180 return;
181 }
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200182 uint32_t events = Dbg::kMethodExit;
183 if (thread->IsDebugMethodEntry()) {
184 // It is also the method entry.
185 DCHECK(IsReturn(method, dex_pc));
186 events |= Dbg::kMethodEntry;
187 thread->ClearDebugMethodEntry();
188 }
Alex Lightd7661582017-05-01 13:48:16 -0700189 Dbg::UpdateDebugger(thread, this_object.Get(), method, dex_pc, events, &return_value);
Ian Rogers62d6c772013-02-27 08:32:07 -0800190 }
191
Alex Lightd7661582017-05-01 13:48:16 -0700192 void MethodUnwind(Thread* thread ATTRIBUTE_UNUSED,
193 Handle<mirror::Object> this_object ATTRIBUTE_UNUSED,
194 ArtMethod* method,
195 uint32_t dex_pc)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700196 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800197 // We're not recorded to listen to this kind of event, so complain.
David Sehr709b0702016-10-13 09:12:37 -0700198 LOG(ERROR) << "Unexpected method unwind event in debugger " << ArtMethod::PrettyMethod(method)
Sebastien Hertz51db44a2013-11-19 10:00:29 +0100199 << " " << dex_pc;
Ian Rogers62d6c772013-02-27 08:32:07 -0800200 }
201
Alex Lightd7661582017-05-01 13:48:16 -0700202 void DexPcMoved(Thread* thread,
203 Handle<mirror::Object> this_object,
204 ArtMethod* method,
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200205 uint32_t new_dex_pc)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700206 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200207 if (IsListeningToMethodExit() && IsReturn(method, new_dex_pc)) {
208 // We also listen to kMethodExited instrumentation event and the current instruction is a
209 // RETURN so we know the MethodExited method is going to be called right after us. Like in
210 // MethodEntered, we delegate event reporting to MethodExited.
211 // Besides, if this RETURN instruction is the only one in the method, we can send multiple
212 // JDWP events in the same packet: METHOD_ENTRY, METHOD_EXIT, BREAKPOINT and/or SINGLE_STEP.
213 // Therefore, we must not clear the debug method entry flag here.
214 } else {
215 uint32_t events = 0;
216 if (thread->IsDebugMethodEntry()) {
217 // It is also the method entry.
218 events = Dbg::kMethodEntry;
219 thread->ClearDebugMethodEntry();
220 }
Alex Lightd7661582017-05-01 13:48:16 -0700221 Dbg::UpdateDebugger(thread, this_object.Get(), method, new_dex_pc, events, nullptr);
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200222 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800223 }
224
Alex Lightd7661582017-05-01 13:48:16 -0700225 void FieldRead(Thread* thread ATTRIBUTE_UNUSED,
226 Handle<mirror::Object> this_object,
227 ArtMethod* method,
228 uint32_t dex_pc,
229 ArtField* field)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700230 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Lightd7661582017-05-01 13:48:16 -0700231 Dbg::PostFieldAccessEvent(method, dex_pc, this_object.Get(), field);
Ian Rogers62d6c772013-02-27 08:32:07 -0800232 }
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200233
Alex Lightd7661582017-05-01 13:48:16 -0700234 void FieldWritten(Thread* thread ATTRIBUTE_UNUSED,
235 Handle<mirror::Object> this_object,
236 ArtMethod* method,
237 uint32_t dex_pc,
238 ArtField* field,
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700239 const JValue& field_value)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700240 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Lightd7661582017-05-01 13:48:16 -0700241 Dbg::PostFieldModificationEvent(method, dex_pc, this_object.Get(), field, &field_value);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200242 }
243
Alex Light6e1607e2017-08-23 10:06:18 -0700244 void ExceptionThrown(Thread* thread ATTRIBUTE_UNUSED,
Alex Lightd7661582017-05-01 13:48:16 -0700245 Handle<mirror::Throwable> exception_object)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700246 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Lightd7661582017-05-01 13:48:16 -0700247 Dbg::PostException(exception_object.Get());
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200248 }
249
Nicolas Geoffray81f0f952016-01-20 16:25:19 +0000250 // We only care about branches in the Jit.
251 void Branch(Thread* /*thread*/, ArtMethod* method, uint32_t dex_pc, int32_t dex_pc_offset)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700252 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
David Sehr709b0702016-10-13 09:12:37 -0700253 LOG(ERROR) << "Unexpected branch event in debugger " << ArtMethod::PrettyMethod(method)
Nicolas Geoffray81f0f952016-01-20 16:25:19 +0000254 << " " << dex_pc << ", " << dex_pc_offset;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800255 }
256
Nicolas Geoffray5550ca82015-08-21 18:38:30 +0100257 // We only care about invokes in the Jit.
258 void InvokeVirtualOrInterface(Thread* thread ATTRIBUTE_UNUSED,
Alex Lightd7661582017-05-01 13:48:16 -0700259 Handle<mirror::Object> this_object ATTRIBUTE_UNUSED,
Nicolas Geoffray5550ca82015-08-21 18:38:30 +0100260 ArtMethod* method,
261 uint32_t dex_pc,
Alex Lightd7661582017-05-01 13:48:16 -0700262 ArtMethod* target ATTRIBUTE_UNUSED)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700263 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
David Sehr709b0702016-10-13 09:12:37 -0700264 LOG(ERROR) << "Unexpected invoke event in debugger " << ArtMethod::PrettyMethod(method)
Nicolas Geoffray5550ca82015-08-21 18:38:30 +0100265 << " " << dex_pc;
266 }
267
Alex Light798eab02017-08-23 12:54:53 -0700268 // TODO Might be worth it to post ExceptionCatch event.
269 void ExceptionHandled(Thread* thread ATTRIBUTE_UNUSED,
270 Handle<mirror::Throwable> throwable ATTRIBUTE_UNUSED) OVERRIDE {
271 LOG(ERROR) << "Unexpected exception handled event in debugger";
272 }
273
Alex Light05f47742017-09-14 00:34:44 +0000274 // TODO Might be worth it to implement this.
275 void WatchedFramePop(Thread* thread ATTRIBUTE_UNUSED,
276 const ShadowFrame& frame ATTRIBUTE_UNUSED) OVERRIDE {
277 LOG(ERROR) << "Unexpected WatchedFramePop event in debugger";
278 }
Alex Light798eab02017-08-23 12:54:53 -0700279
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200280 private:
Mathieu Chartiere401d142015-04-22 13:56:20 -0700281 static bool IsReturn(ArtMethod* method, uint32_t dex_pc)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700282 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200283 const DexFile::CodeItem* code_item = method->GetCodeItem();
284 const Instruction* instruction = Instruction::At(&code_item->insns_[dex_pc]);
285 return instruction->IsReturn();
286 }
287
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700288 static bool IsListeningToDexPcMoved() REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200289 return IsListeningTo(instrumentation::Instrumentation::kDexPcMoved);
290 }
291
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700292 static bool IsListeningToMethodExit() REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200293 return IsListeningTo(instrumentation::Instrumentation::kMethodExited);
294 }
295
296 static bool IsListeningTo(instrumentation::Instrumentation::InstrumentationEvent event)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700297 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200298 return (Dbg::GetInstrumentationEvents() & event) != 0;
299 }
300
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200301 DISALLOW_COPY_AND_ASSIGN(DebugInstrumentationListener);
Ian Rogers62d6c772013-02-27 08:32:07 -0800302} gDebugInstrumentationListener;
303
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700304// JDWP is allowed unless the Zygote forbids it.
305static bool gJdwpAllowed = true;
306
Elliott Hughesc0f09332012-03-26 13:27:06 -0700307// Was there a -Xrunjdwp or -agentlib:jdwp= argument on the command line?
Elliott Hughes3bb81562011-10-21 18:52:59 -0700308static bool gJdwpConfigured = false;
309
Sebastien Hertzb3b173b2015-02-06 09:16:32 +0100310// JDWP options for debugging. Only valid if IsJdwpConfigured() is true.
311static JDWP::JdwpOptions gJdwpOptions;
312
Elliott Hughes3bb81562011-10-21 18:52:59 -0700313// Runtime JDWP state.
Ian Rogersc0542af2014-09-03 16:16:56 -0700314static JDWP::JdwpState* gJdwpState = nullptr;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700315static bool gDebuggerConnected; // debugger or DDMS is connected.
Elliott Hughes3bb81562011-10-21 18:52:59 -0700316
Elliott Hughes47fce012011-10-25 18:37:19 -0700317static bool gDdmThreadNotification = false;
318
Elliott Hughes767a1472011-10-26 18:49:02 -0700319// DDMS GC-related settings.
320static Dbg::HpifWhen gDdmHpifWhen = Dbg::HPIF_WHEN_NEVER;
321static Dbg::HpsgWhen gDdmHpsgWhen = Dbg::HPSG_WHEN_NEVER;
322static Dbg::HpsgWhat gDdmHpsgWhat;
323static Dbg::HpsgWhen gDdmNhsgWhen = Dbg::HPSG_WHEN_NEVER;
324static Dbg::HpsgWhat gDdmNhsgWhat;
325
Daniel Mihalyieb076692014-08-22 17:33:31 +0200326bool Dbg::gDebuggerActive = false;
Sebastien Hertz4e5b2082015-03-24 19:03:40 +0100327bool Dbg::gDisposed = false;
Sebastien Hertz6995c602014-09-09 12:10:13 +0200328ObjectRegistry* Dbg::gRegistry = nullptr;
Alex Light21611932017-09-26 13:07:39 -0700329DebuggerActiveMethodInspectionCallback Dbg::gDebugActiveCallback;
Alex Light8c2b9292017-11-09 13:21:01 -0800330DebuggerDdmCallback Dbg::gDebugDdmCallback;
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
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100367// Breakpoints.
jeffhao09bfc6a2012-12-11 18:11:43 -0800368static std::vector<Breakpoint> gBreakpoints GUARDED_BY(Locks::breakpoint_lock_);
Elliott Hughes86964332012-02-15 19:37:42 -0800369
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700370void DebugInvokeReq::VisitRoots(RootVisitor* visitor, const RootInfo& root_info) {
371 receiver.VisitRootIfNonNull(visitor, root_info); // null for static method call.
372 klass.VisitRoot(visitor, root_info);
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700373}
374
Sebastien Hertz597c4f02015-01-26 17:37:14 +0100375void SingleStepControl::AddDexPc(uint32_t dex_pc) {
376 dex_pcs_.insert(dex_pc);
Sebastien Hertzbb43b432014-04-14 11:59:08 +0200377}
378
Sebastien Hertz597c4f02015-01-26 17:37:14 +0100379bool SingleStepControl::ContainsDexPc(uint32_t dex_pc) const {
380 return dex_pcs_.find(dex_pc) == dex_pcs_.end();
Sebastien Hertzbb43b432014-04-14 11:59:08 +0200381}
382
Alex Light6c8467f2015-11-20 15:03:26 -0800383static bool IsBreakpoint(ArtMethod* m, uint32_t dex_pc)
Mathieu Chartier90443472015-07-16 20:32:27 -0700384 REQUIRES(!Locks::breakpoint_lock_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700385 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertzed2be172014-08-19 15:33:43 +0200386 ReaderMutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100387 for (size_t i = 0, e = gBreakpoints.size(); i < e; ++i) {
Alex Light6c8467f2015-11-20 15:03:26 -0800388 if (gBreakpoints[i].DexPc() == dex_pc && gBreakpoints[i].IsInMethod(m)) {
Elliott Hughes86964332012-02-15 19:37:42 -0800389 VLOG(jdwp) << "Hit breakpoint #" << i << ": " << gBreakpoints[i];
390 return true;
391 }
392 }
393 return false;
394}
395
Sebastien Hertz52d131d2014-03-13 16:17:40 +0100396static bool IsSuspendedForDebugger(ScopedObjectAccessUnchecked& soa, Thread* thread)
Mathieu Chartier90443472015-07-16 20:32:27 -0700397 REQUIRES(!Locks::thread_suspend_count_lock_) {
Elliott Hughes9e0c1752013-01-09 14:02:58 -0800398 MutexLock mu(soa.Self(), *Locks::thread_suspend_count_lock_);
399 // A thread may be suspended for GC; in this code, we really want to know whether
400 // there's a debugger suspension active.
401 return thread->IsSuspended() && thread->GetDebugSuspendCount() > 0;
402}
403
Ian Rogersc0542af2014-09-03 16:16:56 -0700404static mirror::Array* DecodeNonNullArray(JDWP::RefTypeId id, JDWP::JdwpError* error)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700405 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz6995c602014-09-09 12:10:13 +0200406 mirror::Object* o = Dbg::GetObjectRegistry()->Get<mirror::Object*>(id, error);
Ian Rogersc0542af2014-09-03 16:16:56 -0700407 if (o == nullptr) {
408 *error = JDWP::ERR_INVALID_OBJECT;
409 return nullptr;
Elliott Hughes436e3722012-02-17 20:01:47 -0800410 }
411 if (!o->IsArrayInstance()) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700412 *error = JDWP::ERR_INVALID_ARRAY;
413 return nullptr;
Elliott Hughes436e3722012-02-17 20:01:47 -0800414 }
Ian Rogersc0542af2014-09-03 16:16:56 -0700415 *error = JDWP::ERR_NONE;
Elliott Hughes436e3722012-02-17 20:01:47 -0800416 return o->AsArray();
417}
418
Ian Rogersc0542af2014-09-03 16:16:56 -0700419static mirror::Class* DecodeClass(JDWP::RefTypeId id, JDWP::JdwpError* error)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700420 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz6995c602014-09-09 12:10:13 +0200421 mirror::Object* o = Dbg::GetObjectRegistry()->Get<mirror::Object*>(id, error);
Ian Rogersc0542af2014-09-03 16:16:56 -0700422 if (o == nullptr) {
423 *error = JDWP::ERR_INVALID_OBJECT;
424 return nullptr;
Elliott Hughes436e3722012-02-17 20:01:47 -0800425 }
426 if (!o->IsClass()) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700427 *error = JDWP::ERR_INVALID_CLASS;
428 return nullptr;
Elliott Hughes436e3722012-02-17 20:01:47 -0800429 }
Ian Rogersc0542af2014-09-03 16:16:56 -0700430 *error = JDWP::ERR_NONE;
Elliott Hughes436e3722012-02-17 20:01:47 -0800431 return o->AsClass();
432}
433
Ian Rogersc0542af2014-09-03 16:16:56 -0700434static Thread* DecodeThread(ScopedObjectAccessUnchecked& soa, JDWP::ObjectId thread_id,
435 JDWP::JdwpError* error)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700436 REQUIRES_SHARED(Locks::mutator_lock_)
Mathieu Chartier90443472015-07-16 20:32:27 -0700437 REQUIRES(!Locks::thread_list_lock_, !Locks::thread_suspend_count_lock_) {
Sebastien Hertz6995c602014-09-09 12:10:13 +0200438 mirror::Object* thread_peer = Dbg::GetObjectRegistry()->Get<mirror::Object*>(thread_id, error);
Ian Rogersc0542af2014-09-03 16:16:56 -0700439 if (thread_peer == nullptr) {
Elliott Hughes221229c2013-01-08 18:17:50 -0800440 // This isn't even an object.
Ian Rogersc0542af2014-09-03 16:16:56 -0700441 *error = JDWP::ERR_INVALID_OBJECT;
442 return nullptr;
Elliott Hughes436e3722012-02-17 20:01:47 -0800443 }
Elliott Hughes221229c2013-01-08 18:17:50 -0800444
Mathieu Chartier0795f232016-09-27 18:43:30 -0700445 ObjPtr<mirror::Class> java_lang_Thread =
446 soa.Decode<mirror::Class>(WellKnownClasses::java_lang_Thread);
Elliott Hughes221229c2013-01-08 18:17:50 -0800447 if (!java_lang_Thread->IsAssignableFrom(thread_peer->GetClass())) {
448 // This isn't a thread.
Ian Rogersc0542af2014-09-03 16:16:56 -0700449 *error = JDWP::ERR_INVALID_THREAD;
450 return nullptr;
Elliott Hughes221229c2013-01-08 18:17:50 -0800451 }
452
Sebastien Hertz69206392015-04-07 15:54:25 +0200453 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogersc0542af2014-09-03 16:16:56 -0700454 Thread* thread = Thread::FromManagedThread(soa, thread_peer);
455 // If thread is null then this a java.lang.Thread without a Thread*. Must be a un-started or a
456 // zombie.
457 *error = (thread == nullptr) ? JDWP::ERR_THREAD_NOT_ALIVE : JDWP::ERR_NONE;
458 return thread;
Elliott Hughes436e3722012-02-17 20:01:47 -0800459}
460
Elliott Hughes24437992011-11-30 14:49:33 -0800461static JDWP::JdwpTag BasicTagFromDescriptor(const char* descriptor) {
462 // JDWP deliberately uses the descriptor characters' ASCII values for its enum.
463 // Note that by "basic" we mean that we don't get more specific than JT_OBJECT.
464 return static_cast<JDWP::JdwpTag>(descriptor[0]);
465}
466
Ian Rogers1ff3c982014-08-12 02:30:58 -0700467static JDWP::JdwpTag BasicTagFromClass(mirror::Class* klass)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700468 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers1ff3c982014-08-12 02:30:58 -0700469 std::string temp;
470 const char* descriptor = klass->GetDescriptor(&temp);
471 return BasicTagFromDescriptor(descriptor);
472}
473
Ian Rogers98379392014-02-24 16:53:16 -0800474static JDWP::JdwpTag TagFromClass(const ScopedObjectAccessUnchecked& soa, mirror::Class* c)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700475 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700476 CHECK(c != nullptr);
Elliott Hughes24437992011-11-30 14:49:33 -0800477 if (c->IsArrayClass()) {
478 return JDWP::JT_ARRAY;
479 }
Elliott Hughes24437992011-11-30 14:49:33 -0800480 if (c->IsStringClass()) {
481 return JDWP::JT_STRING;
Elliott Hughes24437992011-11-30 14:49:33 -0800482 }
Ian Rogers98379392014-02-24 16:53:16 -0800483 if (c->IsClassClass()) {
484 return JDWP::JT_CLASS_OBJECT;
485 }
486 {
Mathieu Chartier0795f232016-09-27 18:43:30 -0700487 ObjPtr<mirror::Class> thread_class =
488 soa.Decode<mirror::Class>(WellKnownClasses::java_lang_Thread);
Ian Rogers98379392014-02-24 16:53:16 -0800489 if (thread_class->IsAssignableFrom(c)) {
490 return JDWP::JT_THREAD;
491 }
492 }
493 {
Mathieu Chartier0795f232016-09-27 18:43:30 -0700494 ObjPtr<mirror::Class> thread_group_class =
495 soa.Decode<mirror::Class>(WellKnownClasses::java_lang_ThreadGroup);
Ian Rogers98379392014-02-24 16:53:16 -0800496 if (thread_group_class->IsAssignableFrom(c)) {
497 return JDWP::JT_THREAD_GROUP;
498 }
499 }
500 {
Mathieu Chartier0795f232016-09-27 18:43:30 -0700501 ObjPtr<mirror::Class> class_loader_class =
502 soa.Decode<mirror::Class>(WellKnownClasses::java_lang_ClassLoader);
Ian Rogers98379392014-02-24 16:53:16 -0800503 if (class_loader_class->IsAssignableFrom(c)) {
504 return JDWP::JT_CLASS_LOADER;
505 }
506 }
507 return JDWP::JT_OBJECT;
Elliott Hughes24437992011-11-30 14:49:33 -0800508}
509
510/*
511 * Objects declared to hold Object might actually hold a more specific
512 * type. The debugger may take a special interest in these (e.g. it
513 * wants to display the contents of Strings), so we want to return an
514 * appropriate tag.
515 *
516 * Null objects are tagged JT_OBJECT.
517 */
Sebastien Hertz6995c602014-09-09 12:10:13 +0200518JDWP::JdwpTag Dbg::TagFromObject(const ScopedObjectAccessUnchecked& soa, mirror::Object* o) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700519 return (o == nullptr) ? JDWP::JT_OBJECT : TagFromClass(soa, o->GetClass());
Elliott Hughes24437992011-11-30 14:49:33 -0800520}
521
522static bool IsPrimitiveTag(JDWP::JdwpTag tag) {
523 switch (tag) {
524 case JDWP::JT_BOOLEAN:
525 case JDWP::JT_BYTE:
526 case JDWP::JT_CHAR:
527 case JDWP::JT_FLOAT:
528 case JDWP::JT_DOUBLE:
529 case JDWP::JT_INT:
530 case JDWP::JT_LONG:
531 case JDWP::JT_SHORT:
532 case JDWP::JT_VOID:
533 return true;
534 default:
535 return false;
536 }
537}
538
Sebastien Hertzb3b173b2015-02-06 09:16:32 +0100539void Dbg::StartJdwp() {
Elliott Hughesc0f09332012-03-26 13:27:06 -0700540 if (!gJdwpAllowed || !IsJdwpConfigured()) {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700541 // No JDWP for you!
542 return;
543 }
544
Ian Rogers719d1a32014-03-06 12:13:39 -0800545 CHECK(gRegistry == nullptr);
Elliott Hughes475fc232011-10-25 15:00:35 -0700546 gRegistry = new ObjectRegistry;
547
Alex Light8c2b9292017-11-09 13:21:01 -0800548 {
549 // Setup the Ddm listener
550 ScopedObjectAccess soa(Thread::Current());
551 Runtime::Current()->GetRuntimeCallbacks()->AddDdmCallback(&gDebugDdmCallback);
552 }
553
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700554 // Init JDWP if the debugger is enabled. This may connect out to a
555 // debugger, passively listen for a debugger, or block waiting for a
556 // debugger.
Sebastien Hertzb3b173b2015-02-06 09:16:32 +0100557 gJdwpState = JDWP::JdwpState::Create(&gJdwpOptions);
Ian Rogersc0542af2014-09-03 16:16:56 -0700558 if (gJdwpState == nullptr) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -0800559 // We probably failed because some other process has the port already, which means that
560 // if we don't abort the user is likely to think they're talking to us when they're actually
561 // talking to that other process.
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800562 LOG(FATAL) << "Debugger thread failed to initialize";
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700563 }
564
565 // If a debugger has already attached, send the "welcome" message.
566 // This may cause us to suspend all threads.
Elliott Hughes376a7a02011-10-24 18:35:55 -0700567 if (gJdwpState->IsActive()) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700568 ScopedObjectAccess soa(Thread::Current());
Sebastien Hertz7d955652014-10-22 10:57:10 +0200569 gJdwpState->PostVMStart();
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700570 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700571}
572
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700573void Dbg::StopJdwp() {
Sebastien Hertzc6345ef2014-08-18 19:26:39 +0200574 // Post VM_DEATH event before the JDWP connection is closed (either by the JDWP thread or the
575 // destruction of gJdwpState).
576 if (gJdwpState != nullptr && gJdwpState->IsActive()) {
577 gJdwpState->PostVMDeath();
578 }
Sebastien Hertz0376e6b2014-02-06 18:12:59 +0100579 // Prevent the JDWP thread from processing JDWP incoming packets after we close the connection.
Sebastien Hertz4e5b2082015-03-24 19:03:40 +0100580 Dispose();
Elliott Hughes376a7a02011-10-24 18:35:55 -0700581 delete gJdwpState;
Ian Rogers719d1a32014-03-06 12:13:39 -0800582 gJdwpState = nullptr;
Elliott Hughes475fc232011-10-25 15:00:35 -0700583 delete gRegistry;
Ian Rogers719d1a32014-03-06 12:13:39 -0800584 gRegistry = nullptr;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700585}
586
Elliott Hughes767a1472011-10-26 18:49:02 -0700587void Dbg::GcDidFinish() {
588 if (gDdmHpifWhen != HPIF_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700589 ScopedObjectAccess soa(Thread::Current());
Brian Carlstrom4d466a82014-05-08 19:05:29 -0700590 VLOG(jdwp) << "Sending heap info to DDM";
Elliott Hughes7162ad92011-10-27 14:08:42 -0700591 DdmSendHeapInfo(gDdmHpifWhen);
Elliott Hughes767a1472011-10-26 18:49:02 -0700592 }
593 if (gDdmHpsgWhen != HPSG_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700594 ScopedObjectAccess soa(Thread::Current());
Brian Carlstrom4d466a82014-05-08 19:05:29 -0700595 VLOG(jdwp) << "Dumping heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700596 DdmSendHeapSegments(false);
Elliott Hughes767a1472011-10-26 18:49:02 -0700597 }
598 if (gDdmNhsgWhen != HPSG_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700599 ScopedObjectAccess soa(Thread::Current());
Brian Carlstrom4d466a82014-05-08 19:05:29 -0700600 VLOG(jdwp) << "Dumping native heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700601 DdmSendHeapSegments(true);
Elliott Hughes767a1472011-10-26 18:49:02 -0700602 }
603}
604
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700605void Dbg::SetJdwpAllowed(bool allowed) {
606 gJdwpAllowed = allowed;
607}
608
Leonard Mosescueb842212016-10-06 17:26:36 -0700609bool Dbg::IsJdwpAllowed() {
610 return gJdwpAllowed;
611}
612
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700613DebugInvokeReq* Dbg::GetInvokeReq() {
Elliott Hughes475fc232011-10-25 15:00:35 -0700614 return Thread::Current()->GetInvokeReq();
615}
616
617Thread* Dbg::GetDebugThread() {
Ian Rogersc0542af2014-09-03 16:16:56 -0700618 return (gJdwpState != nullptr) ? gJdwpState->GetDebugThread() : nullptr;
Elliott Hughes475fc232011-10-25 15:00:35 -0700619}
620
621void Dbg::ClearWaitForEventThread() {
Sebastien Hertz2bf93f42015-01-09 18:44:05 +0100622 gJdwpState->ReleaseJdwpTokenForEvent();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700623}
624
625void Dbg::Connected() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700626 CHECK(!gDebuggerConnected);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800627 VLOG(jdwp) << "JDWP has attached";
Elliott Hughes3bb81562011-10-21 18:52:59 -0700628 gDebuggerConnected = true;
Elliott Hughes86964332012-02-15 19:37:42 -0800629 gDisposed = false;
630}
631
Sebastien Hertzf3928792014-11-17 19:00:37 +0100632bool Dbg::RequiresDeoptimization() {
633 // We don't need deoptimization if everything runs with interpreter after
634 // enabling -Xint mode.
635 return !Runtime::Current()->GetInstrumentation()->IsForcedInterpretOnly();
636}
637
Elliott Hughesa2155262011-11-16 16:26:58 -0800638void Dbg::GoActive() {
639 // Enable all debugging features, including scans for breakpoints.
640 // This is a no-op if we're already active.
641 // Only called from the JDWP handler thread.
Daniel Mihalyieb076692014-08-22 17:33:31 +0200642 if (IsDebuggerActive()) {
Elliott Hughesa2155262011-11-16 16:26:58 -0800643 return;
644 }
645
Mathieu Chartieraa516822015-10-02 15:53:37 -0700646 Thread* const self = Thread::Current();
Elliott Hughesc0f09332012-03-26 13:27:06 -0700647 {
648 // TODO: dalvik only warned if there were breakpoints left over. clear in Dbg::Disconnected?
Mathieu Chartieraa516822015-10-02 15:53:37 -0700649 ReaderMutexLock mu(self, *Locks::breakpoint_lock_);
Elliott Hughesc0f09332012-03-26 13:27:06 -0700650 CHECK_EQ(gBreakpoints.size(), 0U);
651 }
Elliott Hughesa2155262011-11-16 16:26:58 -0800652
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100653 {
Mathieu Chartieraa516822015-10-02 15:53:37 -0700654 MutexLock mu(self, *Locks::deoptimization_lock_);
Sebastien Hertz4d25df32014-03-21 17:44:46 +0100655 CHECK_EQ(deoptimization_requests_.size(), 0U);
656 CHECK_EQ(full_deoptimization_event_count_, 0U);
Sebastien Hertz42cd43f2014-05-13 14:15:41 +0200657 CHECK_EQ(dex_pc_change_event_ref_count_, 0U);
658 CHECK_EQ(method_enter_event_ref_count_, 0U);
659 CHECK_EQ(method_exit_event_ref_count_, 0U);
660 CHECK_EQ(field_read_event_ref_count_, 0U);
661 CHECK_EQ(field_write_event_ref_count_, 0U);
662 CHECK_EQ(exception_catch_event_ref_count_, 0U);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100663 }
664
Ian Rogers62d6c772013-02-27 08:32:07 -0800665 Runtime* runtime = Runtime::Current();
Nicolas Geoffray433b79a2017-01-30 20:54:45 +0000666 // Best effort deoptimization if the runtime is non-Java debuggable. This happens when
667 // ro.debuggable is set, but the application is not debuggable, or when a standalone
668 // dalvikvm invocation is not passed the debuggable option (-Xcompiler-option --debuggable).
669 //
670 // The performance cost of this is non-negligible during native-debugging due to the
David Srbeckyf4480162016-03-16 00:06:24 +0000671 // forced JIT, so we keep the AOT code in that case in exchange for limited native debugging.
Nicolas Geoffray433b79a2017-01-30 20:54:45 +0000672 if (!runtime->IsJavaDebuggable() &&
673 !runtime->GetInstrumentation()->IsForcedInterpretOnly() &&
674 !runtime->IsNativeDebuggable()) {
675 runtime->DeoptimizeBootImage();
Mingyao Yang6ea1a0e2016-01-29 12:12:49 -0800676 }
677
Mathieu Chartier4f55e222015-09-04 13:26:21 -0700678 ScopedSuspendAll ssa(__FUNCTION__);
Sebastien Hertzf3928792014-11-17 19:00:37 +0100679 if (RequiresDeoptimization()) {
680 runtime->GetInstrumentation()->EnableDeoptimization();
681 }
Sebastien Hertz42cd43f2014-05-13 14:15:41 +0200682 instrumentation_events_ = 0;
Elliott Hughesa2155262011-11-16 16:26:58 -0800683 gDebuggerActive = true;
Alex Light21611932017-09-26 13:07:39 -0700684 Runtime::Current()->GetRuntimeCallbacks()->AddMethodInspectionCallback(&gDebugActiveCallback);
Ian Rogers62d6c772013-02-27 08:32:07 -0800685 LOG(INFO) << "Debugger is active";
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700686}
687
688void Dbg::Disconnected() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700689 CHECK(gDebuggerConnected);
690
Elliott Hughesc0f09332012-03-26 13:27:06 -0700691 LOG(INFO) << "Debugger is no longer active";
Elliott Hughes234ab152011-10-26 14:02:26 -0700692
Hiroshi Yamauchi98810e32016-05-24 14:55:40 -0700693 // Suspend all threads and exclusively acquire the mutator lock. Remove the debugger as a listener
Ian Rogers62d6c772013-02-27 08:32:07 -0800694 // and clear the object registry.
695 Runtime* runtime = Runtime::Current();
Ian Rogers62d6c772013-02-27 08:32:07 -0800696 Thread* self = Thread::Current();
Mathieu Chartier4f55e222015-09-04 13:26:21 -0700697 {
Mathieu Chartieraa516822015-10-02 15:53:37 -0700698 // Required for DisableDeoptimization.
699 gc::ScopedGCCriticalSection gcs(self,
700 gc::kGcCauseInstrumentation,
701 gc::kCollectorTypeInstrumentation);
Mathieu Chartier4f55e222015-09-04 13:26:21 -0700702 ScopedSuspendAll ssa(__FUNCTION__);
Mathieu Chartier4f55e222015-09-04 13:26:21 -0700703 // Debugger may not be active at this point.
704 if (IsDebuggerActive()) {
705 {
706 // Since we're going to disable deoptimization, we clear the deoptimization requests queue.
707 // This prevents us from having any pending deoptimization request when the debugger attaches
708 // to us again while no event has been requested yet.
Mathieu Chartiera6b1ead2015-10-06 10:32:38 -0700709 MutexLock mu(self, *Locks::deoptimization_lock_);
Mathieu Chartier4f55e222015-09-04 13:26:21 -0700710 deoptimization_requests_.clear();
711 full_deoptimization_event_count_ = 0U;
712 }
713 if (instrumentation_events_ != 0) {
714 runtime->GetInstrumentation()->RemoveListener(&gDebugInstrumentationListener,
715 instrumentation_events_);
716 instrumentation_events_ = 0;
717 }
718 if (RequiresDeoptimization()) {
719 runtime->GetInstrumentation()->DisableDeoptimization(kDbgInstrumentationKey);
720 }
721 gDebuggerActive = false;
Alex Light21611932017-09-26 13:07:39 -0700722 Runtime::Current()->GetRuntimeCallbacks()->RemoveMethodInspectionCallback(
723 &gDebugActiveCallback);
Sebastien Hertzaaea7342014-02-25 15:10:04 +0100724 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100725 }
Sebastien Hertz55f65342015-01-13 22:48:34 +0100726
727 {
728 ScopedObjectAccess soa(self);
729 gRegistry->Clear();
730 }
731
732 gDebuggerConnected = false;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700733}
734
Sebastien Hertzb3b173b2015-02-06 09:16:32 +0100735void Dbg::ConfigureJdwp(const JDWP::JdwpOptions& jdwp_options) {
736 CHECK_NE(jdwp_options.transport, JDWP::kJdwpTransportUnknown);
737 gJdwpOptions = jdwp_options;
738 gJdwpConfigured = true;
739}
740
Elliott Hughesc0f09332012-03-26 13:27:06 -0700741bool Dbg::IsJdwpConfigured() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700742 return gJdwpConfigured;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700743}
744
745int64_t Dbg::LastDebuggerActivity() {
Elliott Hughesca951522011-12-05 12:01:32 -0800746 return gJdwpState->LastDebuggerActivity();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700747}
748
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700749void Dbg::UndoDebuggerSuspensions() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700750 Runtime::Current()->GetThreadList()->UndoDebuggerSuspensions();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700751}
752
Elliott Hughes88d63092013-01-09 09:55:54 -0800753std::string Dbg::GetClassName(JDWP::RefTypeId class_id) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700754 JDWP::JdwpError error;
755 mirror::Object* o = gRegistry->Get<mirror::Object*>(class_id, &error);
756 if (o == nullptr) {
757 if (error == JDWP::ERR_NONE) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700758 return "null";
Ian Rogersc0542af2014-09-03 16:16:56 -0700759 } else {
760 return StringPrintf("invalid object %p", reinterpret_cast<void*>(class_id));
761 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800762 }
763 if (!o->IsClass()) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700764 return StringPrintf("non-class %p", o); // This is only used for debugging output anyway.
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800765 }
Sebastien Hertz6995c602014-09-09 12:10:13 +0200766 return GetClassName(o->AsClass());
767}
768
769std::string Dbg::GetClassName(mirror::Class* klass) {
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +0200770 if (klass == nullptr) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700771 return "null";
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +0200772 }
Ian Rogers1ff3c982014-08-12 02:30:58 -0700773 std::string temp;
Sebastien Hertz6995c602014-09-09 12:10:13 +0200774 return DescriptorToName(klass->GetDescriptor(&temp));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700775}
776
Ian Rogersc0542af2014-09-03 16:16:56 -0700777JDWP::JdwpError Dbg::GetClassObject(JDWP::RefTypeId id, JDWP::ObjectId* class_object_id) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800778 JDWP::JdwpError status;
Ian Rogersc0542af2014-09-03 16:16:56 -0700779 mirror::Class* c = DecodeClass(id, &status);
780 if (c == nullptr) {
781 *class_object_id = 0;
Elliott Hughes436e3722012-02-17 20:01:47 -0800782 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800783 }
Ian Rogersc0542af2014-09-03 16:16:56 -0700784 *class_object_id = gRegistry->Add(c);
Elliott Hughes436e3722012-02-17 20:01:47 -0800785 return JDWP::ERR_NONE;
Elliott Hughes86964332012-02-15 19:37:42 -0800786}
787
Ian Rogersc0542af2014-09-03 16:16:56 -0700788JDWP::JdwpError Dbg::GetSuperclass(JDWP::RefTypeId id, JDWP::RefTypeId* superclass_id) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800789 JDWP::JdwpError status;
Ian Rogersc0542af2014-09-03 16:16:56 -0700790 mirror::Class* c = DecodeClass(id, &status);
791 if (c == nullptr) {
792 *superclass_id = 0;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800793 return status;
794 }
795 if (c->IsInterface()) {
796 // http://code.google.com/p/android/issues/detail?id=20856
Ian Rogersc0542af2014-09-03 16:16:56 -0700797 *superclass_id = 0;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800798 } else {
Ian Rogersc0542af2014-09-03 16:16:56 -0700799 *superclass_id = gRegistry->Add(c->GetSuperClass());
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800800 }
801 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700802}
803
Elliott Hughes436e3722012-02-17 20:01:47 -0800804JDWP::JdwpError Dbg::GetClassLoader(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700805 JDWP::JdwpError error;
Andreas Gampe7929a482015-12-30 19:33:49 -0800806 mirror::Class* c = DecodeClass(id, &error);
807 if (c == nullptr) {
808 return error;
Elliott Hughes436e3722012-02-17 20:01:47 -0800809 }
Andreas Gampe7929a482015-12-30 19:33:49 -0800810 expandBufAddObjectId(pReply, gRegistry->Add(c->GetClassLoader()));
Elliott Hughes436e3722012-02-17 20:01:47 -0800811 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700812}
813
Elliott Hughes436e3722012-02-17 20:01:47 -0800814JDWP::JdwpError Dbg::GetModifiers(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700815 JDWP::JdwpError error;
816 mirror::Class* c = DecodeClass(id, &error);
817 if (c == nullptr) {
818 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800819 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800820
821 uint32_t access_flags = c->GetAccessFlags() & kAccJavaFlagsMask;
822
Yevgeny Roubande34eea2014-02-15 01:06:03 +0700823 // Set ACC_SUPER. Dex files don't contain this flag but only classes are supposed to have it set,
824 // not interfaces.
Elliott Hughes436e3722012-02-17 20:01:47 -0800825 // Class.getModifiers doesn't return it, but JDWP does, so we set it here.
Yevgeny Roubande34eea2014-02-15 01:06:03 +0700826 if ((access_flags & kAccInterface) == 0) {
827 access_flags |= kAccSuper;
828 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800829
830 expandBufAdd4BE(pReply, access_flags);
831
832 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700833}
834
Ian Rogersc0542af2014-09-03 16:16:56 -0700835JDWP::JdwpError Dbg::GetMonitorInfo(JDWP::ObjectId object_id, JDWP::ExpandBuf* reply) {
836 JDWP::JdwpError error;
837 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
838 if (o == nullptr) {
Elliott Hughesf327e072013-01-09 16:01:26 -0800839 return JDWP::ERR_INVALID_OBJECT;
840 }
841
842 // Ensure all threads are suspended while we read objects' lock words.
843 Thread* self = Thread::Current();
Sebastien Hertz54263242014-03-19 18:16:50 +0100844 CHECK_EQ(self->GetState(), kRunnable);
Elliott Hughesf327e072013-01-09 16:01:26 -0800845
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700846 MonitorInfo monitor_info;
847 {
848 ScopedThreadSuspension sts(self, kSuspended);
Mathieu Chartier4f55e222015-09-04 13:26:21 -0700849 ScopedSuspendAll ssa(__FUNCTION__);
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700850 monitor_info = MonitorInfo(o);
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700851 }
Ian Rogersc0542af2014-09-03 16:16:56 -0700852 if (monitor_info.owner_ != nullptr) {
Nicolas Geoffraycafa0812017-02-15 18:27:34 +0000853 expandBufAddObjectId(reply, gRegistry->Add(monitor_info.owner_->GetPeerFromOtherThread()));
Elliott Hughesf327e072013-01-09 16:01:26 -0800854 } else {
Ian Rogersc0542af2014-09-03 16:16:56 -0700855 expandBufAddObjectId(reply, gRegistry->Add(nullptr));
Elliott Hughesf327e072013-01-09 16:01:26 -0800856 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700857 expandBufAdd4BE(reply, monitor_info.entry_count_);
858 expandBufAdd4BE(reply, monitor_info.waiters_.size());
859 for (size_t i = 0; i < monitor_info.waiters_.size(); ++i) {
Nicolas Geoffraycafa0812017-02-15 18:27:34 +0000860 expandBufAddObjectId(reply, gRegistry->Add(monitor_info.waiters_[i]->GetPeerFromOtherThread()));
Elliott Hughesf327e072013-01-09 16:01:26 -0800861 }
862 return JDWP::ERR_NONE;
863}
864
Elliott Hughes734b8c62013-01-11 15:32:45 -0800865JDWP::JdwpError Dbg::GetOwnedMonitors(JDWP::ObjectId thread_id,
Ian Rogersc0542af2014-09-03 16:16:56 -0700866 std::vector<JDWP::ObjectId>* monitors,
867 std::vector<uint32_t>* stack_depths) {
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800868 struct OwnedMonitorVisitor : public StackVisitor {
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700869 OwnedMonitorVisitor(Thread* thread, Context* context,
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -0700870 std::vector<JDWP::ObjectId>* monitor_vector,
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700871 std::vector<uint32_t>* stack_depth_vector)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700872 REQUIRES_SHARED(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +0100873 : StackVisitor(thread, context, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
874 current_stack_depth(0),
875 monitors(monitor_vector),
876 stack_depths(stack_depth_vector) {}
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800877
878 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
879 // annotalysis.
880 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
881 if (!GetMethod()->IsRuntimeMethod()) {
882 Monitor::VisitLocks(this, AppendOwnedMonitors, this);
Elliott Hughes734b8c62013-01-11 15:32:45 -0800883 ++current_stack_depth;
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800884 }
885 return true;
886 }
887
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -0700888 static void AppendOwnedMonitors(mirror::Object* owned_monitor, void* arg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700889 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers7a22fa62013-01-23 12:16:16 -0800890 OwnedMonitorVisitor* visitor = reinterpret_cast<OwnedMonitorVisitor*>(arg);
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -0700891 visitor->monitors->push_back(gRegistry->Add(owned_monitor));
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700892 visitor->stack_depths->push_back(visitor->current_stack_depth);
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800893 }
894
Elliott Hughes734b8c62013-01-11 15:32:45 -0800895 size_t current_stack_depth;
Ian Rogersc0542af2014-09-03 16:16:56 -0700896 std::vector<JDWP::ObjectId>* const monitors;
897 std::vector<uint32_t>* const stack_depths;
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800898 };
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800899
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700900 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz69206392015-04-07 15:54:25 +0200901 JDWP::JdwpError error;
902 Thread* thread = DecodeThread(soa, thread_id, &error);
903 if (thread == nullptr) {
904 return error;
905 }
906 if (!IsSuspendedForDebugger(soa, thread)) {
907 return JDWP::ERR_THREAD_NOT_SUSPENDED;
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700908 }
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -0700909 std::unique_ptr<Context> context(Context::Create());
Ian Rogersc0542af2014-09-03 16:16:56 -0700910 OwnedMonitorVisitor visitor(thread, context.get(), monitors, stack_depths);
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -0700911 visitor.WalkStack();
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800912 return JDWP::ERR_NONE;
913}
914
Sebastien Hertz52d131d2014-03-13 16:17:40 +0100915JDWP::JdwpError Dbg::GetContendedMonitor(JDWP::ObjectId thread_id,
Ian Rogersc0542af2014-09-03 16:16:56 -0700916 JDWP::ObjectId* contended_monitor) {
Elliott Hughesf9501702013-01-11 11:22:27 -0800917 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -0700918 *contended_monitor = 0;
Sebastien Hertz69206392015-04-07 15:54:25 +0200919 JDWP::JdwpError error;
920 Thread* thread = DecodeThread(soa, thread_id, &error);
921 if (thread == nullptr) {
922 return error;
Elliott Hughesf9501702013-01-11 11:22:27 -0800923 }
Sebastien Hertz69206392015-04-07 15:54:25 +0200924 if (!IsSuspendedForDebugger(soa, thread)) {
925 return JDWP::ERR_THREAD_NOT_SUSPENDED;
926 }
927 mirror::Object* contended_monitor_obj = Monitor::GetContendedMonitor(thread);
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700928 // Add() requires the thread_list_lock_ not held to avoid the lock
929 // level violation.
Ian Rogersc0542af2014-09-03 16:16:56 -0700930 *contended_monitor = gRegistry->Add(contended_monitor_obj);
Elliott Hughesf9501702013-01-11 11:22:27 -0800931 return JDWP::ERR_NONE;
932}
933
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800934JDWP::JdwpError Dbg::GetInstanceCounts(const std::vector<JDWP::RefTypeId>& class_ids,
Ian Rogersc0542af2014-09-03 16:16:56 -0700935 std::vector<uint64_t>* counts) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800936 gc::Heap* heap = Runtime::Current()->GetHeap();
937 heap->CollectGarbage(false);
Mathieu Chartiere8a3c572016-10-11 16:52:17 -0700938 VariableSizedHandleScope hs(Thread::Current());
Mathieu Chartier9d156d52016-10-06 17:44:26 -0700939 std::vector<Handle<mirror::Class>> classes;
Ian Rogersc0542af2014-09-03 16:16:56 -0700940 counts->clear();
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800941 for (size_t i = 0; i < class_ids.size(); ++i) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700942 JDWP::JdwpError error;
Mathieu Chartier9d156d52016-10-06 17:44:26 -0700943 ObjPtr<mirror::Class> c = DecodeClass(class_ids[i], &error);
Ian Rogersc0542af2014-09-03 16:16:56 -0700944 if (c == nullptr) {
945 return error;
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800946 }
Mathieu Chartier9d156d52016-10-06 17:44:26 -0700947 classes.push_back(hs.NewHandle(c));
Ian Rogersc0542af2014-09-03 16:16:56 -0700948 counts->push_back(0);
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800949 }
Ian Rogersc0542af2014-09-03 16:16:56 -0700950 heap->CountInstances(classes, false, &(*counts)[0]);
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800951 return JDWP::ERR_NONE;
952}
953
Ian Rogersc0542af2014-09-03 16:16:56 -0700954JDWP::JdwpError Dbg::GetInstances(JDWP::RefTypeId class_id, int32_t max_count,
955 std::vector<JDWP::ObjectId>* instances) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800956 gc::Heap* heap = Runtime::Current()->GetHeap();
957 // We only want reachable instances, so do a GC.
958 heap->CollectGarbage(false);
Ian Rogersc0542af2014-09-03 16:16:56 -0700959 JDWP::JdwpError error;
Mathieu Chartier9d156d52016-10-06 17:44:26 -0700960 ObjPtr<mirror::Class> c = DecodeClass(class_id, &error);
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800961 if (c == nullptr) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700962 return error;
Elliott Hughes3b78c942013-01-15 17:35:41 -0800963 }
Mathieu Chartier2d855952016-10-12 19:37:59 -0700964 VariableSizedHandleScope hs(Thread::Current());
965 std::vector<Handle<mirror::Object>> raw_instances;
Richard Uhler660be6f2017-11-22 16:12:29 +0000966 Runtime::Current()->GetHeap()->GetInstances(hs,
967 hs.NewHandle(c),
968 /* use_is_assignable_from */ false,
969 max_count,
970 raw_instances);
Elliott Hughes3b78c942013-01-15 17:35:41 -0800971 for (size_t i = 0; i < raw_instances.size(); ++i) {
Mathieu Chartier2d855952016-10-12 19:37:59 -0700972 instances->push_back(gRegistry->Add(raw_instances[i].Get()));
Elliott Hughes3b78c942013-01-15 17:35:41 -0800973 }
974 return JDWP::ERR_NONE;
975}
976
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800977JDWP::JdwpError Dbg::GetReferringObjects(JDWP::ObjectId object_id, int32_t max_count,
Ian Rogersc0542af2014-09-03 16:16:56 -0700978 std::vector<JDWP::ObjectId>* referring_objects) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800979 gc::Heap* heap = Runtime::Current()->GetHeap();
980 heap->CollectGarbage(false);
Ian Rogersc0542af2014-09-03 16:16:56 -0700981 JDWP::JdwpError error;
Mathieu Chartier9d156d52016-10-06 17:44:26 -0700982 ObjPtr<mirror::Object> o = gRegistry->Get<mirror::Object*>(object_id, &error);
Ian Rogersc0542af2014-09-03 16:16:56 -0700983 if (o == nullptr) {
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800984 return JDWP::ERR_INVALID_OBJECT;
985 }
Mathieu Chartieraea9bfb2016-10-12 19:19:56 -0700986 VariableSizedHandleScope hs(Thread::Current());
987 std::vector<Handle<mirror::Object>> raw_instances;
988 heap->GetReferringObjects(hs, hs.NewHandle(o), max_count, raw_instances);
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800989 for (size_t i = 0; i < raw_instances.size(); ++i) {
Mathieu Chartieraea9bfb2016-10-12 19:19:56 -0700990 referring_objects->push_back(gRegistry->Add(raw_instances[i].Get()));
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800991 }
992 return JDWP::ERR_NONE;
993}
994
Ian Rogersc0542af2014-09-03 16:16:56 -0700995JDWP::JdwpError Dbg::DisableCollection(JDWP::ObjectId object_id) {
996 JDWP::JdwpError error;
997 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
998 if (o == nullptr) {
Sebastien Hertze96060a2013-12-11 12:06:28 +0100999 return JDWP::ERR_INVALID_OBJECT;
1000 }
Elliott Hughes64f574f2013-02-20 14:57:12 -08001001 gRegistry->DisableCollection(object_id);
1002 return JDWP::ERR_NONE;
1003}
1004
Ian Rogersc0542af2014-09-03 16:16:56 -07001005JDWP::JdwpError Dbg::EnableCollection(JDWP::ObjectId object_id) {
1006 JDWP::JdwpError error;
1007 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
Sebastien Hertze96060a2013-12-11 12:06:28 +01001008 // Unlike DisableCollection, JDWP specs do not state an invalid object causes an error. The RI
1009 // also ignores these cases and never return an error. However it's not obvious why this command
1010 // should behave differently from DisableCollection and IsCollected commands. So let's be more
1011 // strict and return an error if this happens.
Ian Rogersc0542af2014-09-03 16:16:56 -07001012 if (o == nullptr) {
Sebastien Hertze96060a2013-12-11 12:06:28 +01001013 return JDWP::ERR_INVALID_OBJECT;
1014 }
Elliott Hughes64f574f2013-02-20 14:57:12 -08001015 gRegistry->EnableCollection(object_id);
1016 return JDWP::ERR_NONE;
1017}
1018
Ian Rogersc0542af2014-09-03 16:16:56 -07001019JDWP::JdwpError Dbg::IsCollected(JDWP::ObjectId object_id, bool* is_collected) {
1020 *is_collected = true;
Sebastien Hertz65637eb2014-01-10 17:40:02 +01001021 if (object_id == 0) {
1022 // Null object id is invalid.
Sebastien Hertze96060a2013-12-11 12:06:28 +01001023 return JDWP::ERR_INVALID_OBJECT;
1024 }
Sebastien Hertz65637eb2014-01-10 17:40:02 +01001025 // JDWP specs state an INVALID_OBJECT error is returned if the object ID is not valid. However
1026 // the RI seems to ignore this and assume object has been collected.
Ian Rogersc0542af2014-09-03 16:16:56 -07001027 JDWP::JdwpError error;
1028 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
1029 if (o != nullptr) {
1030 *is_collected = gRegistry->IsCollected(object_id);
Sebastien Hertz65637eb2014-01-10 17:40:02 +01001031 }
Elliott Hughes64f574f2013-02-20 14:57:12 -08001032 return JDWP::ERR_NONE;
1033}
1034
Ian Rogersc0542af2014-09-03 16:16:56 -07001035void Dbg::DisposeObject(JDWP::ObjectId object_id, uint32_t reference_count) {
Elliott Hughes64f574f2013-02-20 14:57:12 -08001036 gRegistry->DisposeObject(object_id, reference_count);
1037}
1038
Mathieu Chartier3398c782016-09-30 10:27:43 -07001039JDWP::JdwpTypeTag Dbg::GetTypeTag(ObjPtr<mirror::Class> klass) {
Sebastien Hertz4d8fd492014-03-28 16:29:41 +01001040 DCHECK(klass != nullptr);
1041 if (klass->IsArrayClass()) {
1042 return JDWP::TT_ARRAY;
1043 } else if (klass->IsInterface()) {
1044 return JDWP::TT_INTERFACE;
1045 } else {
1046 return JDWP::TT_CLASS;
1047 }
1048}
1049
Elliott Hughes88d63092013-01-09 09:55:54 -08001050JDWP::JdwpError Dbg::GetReflectedType(JDWP::RefTypeId class_id, JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001051 JDWP::JdwpError error;
1052 mirror::Class* c = DecodeClass(class_id, &error);
1053 if (c == nullptr) {
1054 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001055 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001056
Sebastien Hertz4d8fd492014-03-28 16:29:41 +01001057 JDWP::JdwpTypeTag type_tag = GetTypeTag(c);
1058 expandBufAdd1(pReply, type_tag);
Elliott Hughes88d63092013-01-09 09:55:54 -08001059 expandBufAddRefTypeId(pReply, class_id);
Elliott Hughes436e3722012-02-17 20:01:47 -08001060 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001061}
1062
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001063// Get the complete list of reference classes (i.e. all classes except
1064// the primitive types).
1065// Returns a newly-allocated buffer full of RefTypeId values.
1066class ClassListCreator : public ClassVisitor {
1067 public:
1068 explicit ClassListCreator(std::vector<JDWP::RefTypeId>* classes) : classes_(classes) {}
1069
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001070 bool operator()(ObjPtr<mirror::Class> c) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001071 if (!c->IsPrimitive()) {
1072 classes_->push_back(Dbg::GetObjectRegistry()->AddRefType(c));
1073 }
1074 return true;
1075 }
1076
1077 private:
1078 std::vector<JDWP::RefTypeId>* const classes_;
1079};
1080
Ian Rogersc0542af2014-09-03 16:16:56 -07001081void Dbg::GetClassList(std::vector<JDWP::RefTypeId>* classes) {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001082 ClassListCreator clc(classes);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001083 Runtime::Current()->GetClassLinker()->VisitClassesWithoutClassesLock(&clc);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001084}
1085
Ian Rogers1ff3c982014-08-12 02:30:58 -07001086JDWP::JdwpError Dbg::GetClassInfo(JDWP::RefTypeId class_id, JDWP::JdwpTypeTag* pTypeTag,
1087 uint32_t* pStatus, std::string* pDescriptor) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001088 JDWP::JdwpError error;
1089 mirror::Class* c = DecodeClass(class_id, &error);
1090 if (c == nullptr) {
1091 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001092 }
1093
Elliott Hughesa2155262011-11-16 16:26:58 -08001094 if (c->IsArrayClass()) {
1095 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
1096 *pTypeTag = JDWP::TT_ARRAY;
1097 } else {
1098 if (c->IsErroneous()) {
1099 *pStatus = JDWP::CS_ERROR;
1100 } else {
1101 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED | JDWP::CS_INITIALIZED;
1102 }
1103 *pTypeTag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
1104 }
1105
Ian Rogersc0542af2014-09-03 16:16:56 -07001106 if (pDescriptor != nullptr) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07001107 std::string temp;
1108 *pDescriptor = c->GetDescriptor(&temp);
Elliott Hughesa2155262011-11-16 16:26:58 -08001109 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001110 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001111}
1112
Ian Rogersc0542af2014-09-03 16:16:56 -07001113void Dbg::FindLoadedClassBySignature(const char* descriptor, std::vector<JDWP::RefTypeId>* ids) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001114 std::vector<ObjPtr<mirror::Class>> classes;
Igor Murashkinb1d8c312015-08-04 11:18:43 -07001115 Runtime::Current()->GetClassLinker()->LookupClasses(descriptor, classes);
Ian Rogersc0542af2014-09-03 16:16:56 -07001116 ids->clear();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001117 for (ObjPtr<mirror::Class> c : classes) {
1118 ids->push_back(gRegistry->Add(c));
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001119 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001120}
1121
Ian Rogersc0542af2014-09-03 16:16:56 -07001122JDWP::JdwpError Dbg::GetReferenceType(JDWP::ObjectId object_id, JDWP::ExpandBuf* pReply) {
1123 JDWP::JdwpError error;
1124 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
1125 if (o == nullptr) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001126 return JDWP::ERR_INVALID_OBJECT;
Elliott Hughes499c5132011-11-17 14:55:11 -08001127 }
Elliott Hughes2435a572012-02-17 16:07:41 -08001128
Sebastien Hertz4d8fd492014-03-28 16:29:41 +01001129 JDWP::JdwpTypeTag type_tag = GetTypeTag(o->GetClass());
Elliott Hughes64f574f2013-02-20 14:57:12 -08001130 JDWP::RefTypeId type_id = gRegistry->AddRefType(o->GetClass());
Elliott Hughes2435a572012-02-17 16:07:41 -08001131
1132 expandBufAdd1(pReply, type_tag);
1133 expandBufAddRefTypeId(pReply, type_id);
1134
1135 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001136}
1137
Ian Rogersfc0e94b2013-09-23 23:51:32 -07001138JDWP::JdwpError Dbg::GetSignature(JDWP::RefTypeId class_id, std::string* signature) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001139 JDWP::JdwpError error;
1140 mirror::Class* c = DecodeClass(class_id, &error);
1141 if (c == nullptr) {
1142 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001143 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07001144 std::string temp;
1145 *signature = c->GetDescriptor(&temp);
Elliott Hughes1fe7afb2012-02-13 17:23:03 -08001146 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001147}
1148
Orion Hodson77d8a1c2017-04-24 14:53:19 +01001149JDWP::JdwpError Dbg::GetSourceDebugExtension(JDWP::RefTypeId class_id,
1150 std::string* extension_data) {
1151 JDWP::JdwpError error;
1152 mirror::Class* c = DecodeClass(class_id, &error);
1153 if (c == nullptr) {
1154 return error;
1155 }
1156 StackHandleScope<1> hs(Thread::Current());
1157 Handle<mirror::Class> klass(hs.NewHandle(c));
1158 const char* data = annotations::GetSourceDebugExtension(klass);
1159 if (data == nullptr) {
1160 return JDWP::ERR_ABSENT_INFORMATION;
1161 }
1162 *extension_data = data;
1163 return JDWP::ERR_NONE;
1164}
1165
Ian Rogersc0542af2014-09-03 16:16:56 -07001166JDWP::JdwpError Dbg::GetSourceFile(JDWP::RefTypeId class_id, std::string* result) {
1167 JDWP::JdwpError error;
1168 mirror::Class* c = DecodeClass(class_id, &error);
Sebastien Hertz4206eb52014-06-05 10:15:45 +02001169 if (c == nullptr) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001170 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001171 }
Sebastien Hertz4206eb52014-06-05 10:15:45 +02001172 const char* source_file = c->GetSourceFile();
1173 if (source_file == nullptr) {
Sebastien Hertzb7054ba2014-03-13 11:52:31 +01001174 return JDWP::ERR_ABSENT_INFORMATION;
1175 }
Ian Rogersc0542af2014-09-03 16:16:56 -07001176 *result = source_file;
Elliott Hughes436e3722012-02-17 20:01:47 -08001177 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001178}
1179
Ian Rogersc0542af2014-09-03 16:16:56 -07001180JDWP::JdwpError Dbg::GetObjectTag(JDWP::ObjectId object_id, uint8_t* tag) {
Ian Rogers98379392014-02-24 16:53:16 -08001181 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07001182 JDWP::JdwpError error;
1183 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
1184 if (error != JDWP::ERR_NONE) {
1185 *tag = JDWP::JT_VOID;
1186 return error;
Elliott Hughes546b9862012-06-20 16:06:13 -07001187 }
Ian Rogersc0542af2014-09-03 16:16:56 -07001188 *tag = TagFromObject(soa, o);
Elliott Hughes546b9862012-06-20 16:06:13 -07001189 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001190}
1191
Elliott Hughesaed4be92011-12-02 16:16:23 -08001192size_t Dbg::GetTagWidth(JDWP::JdwpTag tag) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001193 switch (tag) {
1194 case JDWP::JT_VOID:
1195 return 0;
1196 case JDWP::JT_BYTE:
1197 case JDWP::JT_BOOLEAN:
1198 return 1;
1199 case JDWP::JT_CHAR:
1200 case JDWP::JT_SHORT:
1201 return 2;
1202 case JDWP::JT_FLOAT:
1203 case JDWP::JT_INT:
1204 return 4;
1205 case JDWP::JT_ARRAY:
1206 case JDWP::JT_OBJECT:
1207 case JDWP::JT_STRING:
1208 case JDWP::JT_THREAD:
1209 case JDWP::JT_THREAD_GROUP:
1210 case JDWP::JT_CLASS_LOADER:
1211 case JDWP::JT_CLASS_OBJECT:
1212 return sizeof(JDWP::ObjectId);
1213 case JDWP::JT_DOUBLE:
1214 case JDWP::JT_LONG:
1215 return 8;
1216 default:
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001217 LOG(FATAL) << "Unknown tag " << tag;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001218 return -1;
1219 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001220}
1221
Ian Rogersc0542af2014-09-03 16:16:56 -07001222JDWP::JdwpError Dbg::GetArrayLength(JDWP::ObjectId array_id, int32_t* length) {
1223 JDWP::JdwpError error;
1224 mirror::Array* a = DecodeNonNullArray(array_id, &error);
1225 if (a == nullptr) {
1226 return error;
Elliott Hughes24437992011-11-30 14:49:33 -08001227 }
Ian Rogersc0542af2014-09-03 16:16:56 -07001228 *length = a->GetLength();
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001229 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001230}
1231
Elliott Hughes88d63092013-01-09 09:55:54 -08001232JDWP::JdwpError Dbg::OutputArray(JDWP::ObjectId array_id, int offset, int count, JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001233 JDWP::JdwpError error;
1234 mirror::Array* a = DecodeNonNullArray(array_id, &error);
Ian Rogers98379392014-02-24 16:53:16 -08001235 if (a == nullptr) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001236 return error;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001237 }
Elliott Hughes24437992011-11-30 14:49:33 -08001238
1239 if (offset < 0 || count < 0 || offset > a->GetLength() || a->GetLength() - offset < count) {
1240 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001241 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughes24437992011-11-30 14:49:33 -08001242 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07001243 JDWP::JdwpTag element_tag = BasicTagFromClass(a->GetClass()->GetComponentType());
1244 expandBufAdd1(pReply, element_tag);
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001245 expandBufAdd4BE(pReply, count);
1246
Ian Rogers1ff3c982014-08-12 02:30:58 -07001247 if (IsPrimitiveTag(element_tag)) {
1248 size_t width = GetTagWidth(element_tag);
Elliott Hughes24437992011-11-30 14:49:33 -08001249 uint8_t* dst = expandBufAddSpace(pReply, count * width);
1250 if (width == 8) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001251 const uint64_t* src8 = reinterpret_cast<uint64_t*>(a->GetRawData(sizeof(uint64_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001252 for (int i = 0; i < count; ++i) JDWP::Write8BE(&dst, src8[offset + i]);
1253 } else if (width == 4) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001254 const uint32_t* src4 = reinterpret_cast<uint32_t*>(a->GetRawData(sizeof(uint32_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001255 for (int i = 0; i < count; ++i) JDWP::Write4BE(&dst, src4[offset + i]);
1256 } else if (width == 2) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001257 const uint16_t* src2 = reinterpret_cast<uint16_t*>(a->GetRawData(sizeof(uint16_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001258 for (int i = 0; i < count; ++i) JDWP::Write2BE(&dst, src2[offset + i]);
1259 } else {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001260 const uint8_t* src = reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint8_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001261 memcpy(dst, &src[offset * width], count * width);
1262 }
1263 } else {
Ian Rogers98379392014-02-24 16:53:16 -08001264 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001265 mirror::ObjectArray<mirror::Object>* oa = a->AsObjectArray<mirror::Object>();
Elliott Hughes24437992011-11-30 14:49:33 -08001266 for (int i = 0; i < count; ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001267 mirror::Object* element = oa->Get(offset + i);
Ian Rogers98379392014-02-24 16:53:16 -08001268 JDWP::JdwpTag specific_tag = (element != nullptr) ? TagFromObject(soa, element)
Ian Rogers1ff3c982014-08-12 02:30:58 -07001269 : element_tag;
Elliott Hughes24437992011-11-30 14:49:33 -08001270 expandBufAdd1(pReply, specific_tag);
1271 expandBufAddObjectId(pReply, gRegistry->Add(element));
1272 }
1273 }
1274
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001275 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001276}
1277
Ian Rogersef7d42f2014-01-06 12:55:46 -08001278template <typename T>
Ian Rogersc0542af2014-09-03 16:16:56 -07001279static void CopyArrayData(mirror::Array* a, JDWP::Request* src, int offset, int count)
Ian Rogersef7d42f2014-01-06 12:55:46 -08001280 NO_THREAD_SAFETY_ANALYSIS {
1281 // TODO: fix when annotalysis correctly handles non-member functions.
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001282 DCHECK(a->GetClass()->IsPrimitiveArray());
1283
Ian Rogersef7d42f2014-01-06 12:55:46 -08001284 T* dst = reinterpret_cast<T*>(a->GetRawData(sizeof(T), offset));
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001285 for (int i = 0; i < count; ++i) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001286 *dst++ = src->ReadValue(sizeof(T));
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001287 }
1288}
1289
Elliott Hughes88d63092013-01-09 09:55:54 -08001290JDWP::JdwpError Dbg::SetArrayElements(JDWP::ObjectId array_id, int offset, int count,
Ian Rogersc0542af2014-09-03 16:16:56 -07001291 JDWP::Request* request) {
1292 JDWP::JdwpError error;
1293 mirror::Array* dst = DecodeNonNullArray(array_id, &error);
1294 if (dst == nullptr) {
1295 return error;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001296 }
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001297
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001298 if (offset < 0 || count < 0 || offset > dst->GetLength() || dst->GetLength() - offset < count) {
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001299 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001300 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001301 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07001302 JDWP::JdwpTag element_tag = BasicTagFromClass(dst->GetClass()->GetComponentType());
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001303
Ian Rogers1ff3c982014-08-12 02:30:58 -07001304 if (IsPrimitiveTag(element_tag)) {
1305 size_t width = GetTagWidth(element_tag);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001306 if (width == 8) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001307 CopyArrayData<uint64_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001308 } else if (width == 4) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001309 CopyArrayData<uint32_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001310 } else if (width == 2) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001311 CopyArrayData<uint16_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001312 } else {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001313 CopyArrayData<uint8_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001314 }
1315 } else {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001316 mirror::ObjectArray<mirror::Object>* oa = dst->AsObjectArray<mirror::Object>();
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001317 for (int i = 0; i < count; ++i) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001318 JDWP::ObjectId id = request->ReadObjectId();
Ian Rogersc0542af2014-09-03 16:16:56 -07001319 mirror::Object* o = gRegistry->Get<mirror::Object*>(id, &error);
1320 if (error != JDWP::ERR_NONE) {
1321 return error;
Elliott Hughes436e3722012-02-17 20:01:47 -08001322 }
Sebastien Hertz2e1c16d2015-08-28 11:57:49 +02001323 // Check if the object's type is compatible with the array's type.
1324 if (o != nullptr && !o->InstanceOf(oa->GetClass()->GetComponentType())) {
1325 return JDWP::ERR_TYPE_MISMATCH;
1326 }
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001327 oa->Set<false>(offset + i, o);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001328 }
1329 }
1330
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001331 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001332}
1333
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001334JDWP::JdwpError Dbg::CreateString(const std::string& str, JDWP::ObjectId* new_string_id) {
1335 Thread* self = Thread::Current();
1336 mirror::String* new_string = mirror::String::AllocFromModifiedUtf8(self, str.c_str());
1337 if (new_string == nullptr) {
1338 DCHECK(self->IsExceptionPending());
1339 self->ClearException();
1340 LOG(ERROR) << "Could not allocate string";
1341 *new_string_id = 0;
1342 return JDWP::ERR_OUT_OF_MEMORY;
1343 }
1344 *new_string_id = gRegistry->Add(new_string);
1345 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001346}
1347
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001348JDWP::JdwpError Dbg::CreateObject(JDWP::RefTypeId class_id, JDWP::ObjectId* new_object_id) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001349 JDWP::JdwpError error;
1350 mirror::Class* c = DecodeClass(class_id, &error);
1351 if (c == nullptr) {
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001352 *new_object_id = 0;
Ian Rogersc0542af2014-09-03 16:16:56 -07001353 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001354 }
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001355 Thread* self = Thread::Current();
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001356 ObjPtr<mirror::Object> new_object;
Sebastien Hertz56d5e502015-11-03 17:38:35 +01001357 if (c->IsStringClass()) {
1358 // Special case for java.lang.String.
1359 gc::AllocatorType allocator_type = Runtime::Current()->GetHeap()->GetCurrentAllocator();
jessicahandojo3aaa37b2016-07-29 14:46:37 -07001360 new_object = mirror::String::AllocEmptyString<true>(self, allocator_type);
Sebastien Hertz56d5e502015-11-03 17:38:35 +01001361 } else {
1362 new_object = c->AllocObject(self);
1363 }
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001364 if (new_object == nullptr) {
1365 DCHECK(self->IsExceptionPending());
1366 self->ClearException();
David Sehr709b0702016-10-13 09:12:37 -07001367 LOG(ERROR) << "Could not allocate object of type " << mirror::Class::PrettyDescriptor(c);
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001368 *new_object_id = 0;
1369 return JDWP::ERR_OUT_OF_MEMORY;
1370 }
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001371 *new_object_id = gRegistry->Add(new_object.Ptr());
Elliott Hughes436e3722012-02-17 20:01:47 -08001372 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001373}
1374
Elliott Hughesbf13d362011-12-08 15:51:37 -08001375/*
1376 * Used by Eclipse's "Display" view to evaluate "new byte[5]" to get "(byte[]) [0, 0, 0, 0, 0]".
1377 */
Elliott Hughes88d63092013-01-09 09:55:54 -08001378JDWP::JdwpError Dbg::CreateArrayObject(JDWP::RefTypeId array_class_id, uint32_t length,
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001379 JDWP::ObjectId* new_array_id) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001380 JDWP::JdwpError error;
1381 mirror::Class* c = DecodeClass(array_class_id, &error);
1382 if (c == nullptr) {
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001383 *new_array_id = 0;
Ian Rogersc0542af2014-09-03 16:16:56 -07001384 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001385 }
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001386 Thread* self = Thread::Current();
1387 gc::Heap* heap = Runtime::Current()->GetHeap();
1388 mirror::Array* new_array = mirror::Array::Alloc<true>(self, c, length,
1389 c->GetComponentSizeShift(),
1390 heap->GetCurrentAllocator());
1391 if (new_array == nullptr) {
1392 DCHECK(self->IsExceptionPending());
1393 self->ClearException();
David Sehr709b0702016-10-13 09:12:37 -07001394 LOG(ERROR) << "Could not allocate array of type " << mirror::Class::PrettyDescriptor(c);
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001395 *new_array_id = 0;
1396 return JDWP::ERR_OUT_OF_MEMORY;
1397 }
1398 *new_array_id = gRegistry->Add(new_array);
Elliott Hughes436e3722012-02-17 20:01:47 -08001399 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001400}
1401
Mathieu Chartierc7853442015-03-27 14:35:38 -07001402JDWP::FieldId Dbg::ToFieldId(const ArtField* f) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001403 return static_cast<JDWP::FieldId>(reinterpret_cast<uintptr_t>(f));
Elliott Hughes03181a82011-11-17 17:22:21 -08001404}
1405
Alex Light6c8467f2015-11-20 15:03:26 -08001406static JDWP::MethodId ToMethodId(ArtMethod* m)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001407 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light97e78032017-06-27 17:51:55 -07001408 return static_cast<JDWP::MethodId>(
1409 reinterpret_cast<uintptr_t>(m->GetCanonicalMethod(kRuntimePointerSize)));
Elliott Hughes03181a82011-11-17 17:22:21 -08001410}
1411
Mathieu Chartierc7853442015-03-27 14:35:38 -07001412static ArtField* FromFieldId(JDWP::FieldId fid)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001413 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001414 return reinterpret_cast<ArtField*>(static_cast<uintptr_t>(fid));
Elliott Hughesaed4be92011-12-02 16:16:23 -08001415}
1416
Mathieu Chartiere401d142015-04-22 13:56:20 -07001417static ArtMethod* FromMethodId(JDWP::MethodId mid)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001418 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001419 return reinterpret_cast<ArtMethod*>(static_cast<uintptr_t>(mid));
Elliott Hughes03181a82011-11-17 17:22:21 -08001420}
1421
Sebastien Hertz6995c602014-09-09 12:10:13 +02001422bool Dbg::MatchThread(JDWP::ObjectId expected_thread_id, Thread* event_thread) {
1423 CHECK(event_thread != nullptr);
1424 JDWP::JdwpError error;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001425 mirror::Object* expected_thread_peer = gRegistry->Get<mirror::Object*>(
1426 expected_thread_id, &error);
Nicolas Geoffraycafa0812017-02-15 18:27:34 +00001427 return expected_thread_peer == event_thread->GetPeerFromOtherThread();
Sebastien Hertz6995c602014-09-09 12:10:13 +02001428}
1429
1430bool Dbg::MatchLocation(const JDWP::JdwpLocation& expected_location,
1431 const JDWP::EventLocation& event_location) {
1432 if (expected_location.dex_pc != event_location.dex_pc) {
1433 return false;
1434 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001435 ArtMethod* m = FromMethodId(expected_location.method_id);
Sebastien Hertz6995c602014-09-09 12:10:13 +02001436 return m == event_location.method;
1437}
1438
Mathieu Chartier3398c782016-09-30 10:27:43 -07001439bool Dbg::MatchType(ObjPtr<mirror::Class> event_class, JDWP::RefTypeId class_id) {
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001440 if (event_class == nullptr) {
1441 return false;
1442 }
Sebastien Hertz6995c602014-09-09 12:10:13 +02001443 JDWP::JdwpError error;
Mathieu Chartier3398c782016-09-30 10:27:43 -07001444 ObjPtr<mirror::Class> expected_class = DecodeClass(class_id, &error);
Sebastien Hertz6995c602014-09-09 12:10:13 +02001445 CHECK(expected_class != nullptr);
1446 return expected_class->IsAssignableFrom(event_class);
1447}
1448
1449bool Dbg::MatchField(JDWP::RefTypeId expected_type_id, JDWP::FieldId expected_field_id,
Mathieu Chartierc7853442015-03-27 14:35:38 -07001450 ArtField* event_field) {
1451 ArtField* expected_field = FromFieldId(expected_field_id);
Sebastien Hertz6995c602014-09-09 12:10:13 +02001452 if (expected_field != event_field) {
1453 return false;
1454 }
1455 return Dbg::MatchType(event_field->GetDeclaringClass(), expected_type_id);
1456}
1457
1458bool Dbg::MatchInstance(JDWP::ObjectId expected_instance_id, mirror::Object* event_instance) {
1459 JDWP::JdwpError error;
1460 mirror::Object* modifier_instance = gRegistry->Get<mirror::Object*>(expected_instance_id, &error);
1461 return modifier_instance == event_instance;
1462}
1463
Mathieu Chartier90443472015-07-16 20:32:27 -07001464void Dbg::SetJdwpLocation(JDWP::JdwpLocation* location, ArtMethod* m, uint32_t dex_pc) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001465 if (m == nullptr) {
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001466 memset(location, 0, sizeof(*location));
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001467 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001468 mirror::Class* c = m->GetDeclaringClass();
Ian Rogersc0542af2014-09-03 16:16:56 -07001469 location->type_tag = GetTypeTag(c);
1470 location->class_id = gRegistry->AddRefType(c);
Alex Light73376312017-04-06 10:10:51 -07001471 // The RI Seems to return 0 for all obsolete methods. For compatibility we shall do the same.
1472 location->method_id = m->IsObsolete() ? 0 : ToMethodId(m);
Ian Rogersc0542af2014-09-03 16:16:56 -07001473 location->dex_pc = (m->IsNative() || m->IsProxyMethod()) ? static_cast<uint64_t>(-1) : dex_pc;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001474 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08001475}
1476
Ian Rogersc0542af2014-09-03 16:16:56 -07001477std::string Dbg::GetMethodName(JDWP::MethodId method_id) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001478 ArtMethod* m = FromMethodId(method_id);
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001479 if (m == nullptr) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001480 return "null";
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001481 }
Andreas Gampe542451c2016-07-26 09:02:02 -07001482 return m->GetInterfaceMethodIfProxy(kRuntimePointerSize)->GetName();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001483}
1484
Alex Light73376312017-04-06 10:10:51 -07001485bool Dbg::IsMethodObsolete(JDWP::MethodId method_id) {
1486 ArtMethod* m = FromMethodId(method_id);
1487 if (m == nullptr) {
1488 // NB Since we return 0 as MID for obsolete methods we want to default to true here.
1489 return true;
1490 }
1491 return m->IsObsolete();
1492}
1493
Ian Rogersc0542af2014-09-03 16:16:56 -07001494std::string Dbg::GetFieldName(JDWP::FieldId field_id) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001495 ArtField* f = FromFieldId(field_id);
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001496 if (f == nullptr) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001497 return "null";
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001498 }
1499 return f->GetName();
Elliott Hughesa96836a2013-01-17 12:27:49 -08001500}
1501
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001502/*
1503 * Augment the access flags for synthetic methods and fields by setting
1504 * the (as described by the spec) "0xf0000000 bit". Also, strip out any
1505 * flags not specified by the Java programming language.
1506 */
1507static uint32_t MangleAccessFlags(uint32_t accessFlags) {
1508 accessFlags &= kAccJavaFlagsMask;
1509 if ((accessFlags & kAccSynthetic) != 0) {
1510 accessFlags |= 0xf0000000;
1511 }
1512 return accessFlags;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001513}
1514
Elliott Hughesdbb40792011-11-18 17:05:22 -08001515/*
Jeff Haob7cefc72013-11-14 14:51:09 -08001516 * Circularly shifts registers so that arguments come first. Debuggers
1517 * expect slots to begin with arguments, but dex code places them at
1518 * the end.
Elliott Hughesdbb40792011-11-18 17:05:22 -08001519 */
Mathieu Chartiere401d142015-04-22 13:56:20 -07001520static uint16_t MangleSlot(uint16_t slot, ArtMethod* m)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001521 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001522 const DexFile::CodeItem* code_item = m->GetCodeItem();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001523 if (code_item == nullptr) {
1524 // We should not get here for a method without code (native, proxy or abstract). Log it and
1525 // return the slot as is since all registers are arguments.
David Sehr709b0702016-10-13 09:12:37 -07001526 LOG(WARNING) << "Trying to mangle slot for method without code " << m->PrettyMethod();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001527 return slot;
1528 }
Jeff Haob7cefc72013-11-14 14:51:09 -08001529 uint16_t ins_size = code_item->ins_size_;
1530 uint16_t locals_size = code_item->registers_size_ - ins_size;
1531 if (slot >= locals_size) {
1532 return slot - locals_size;
1533 } else {
1534 return slot + ins_size;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001535 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001536}
1537
Sebastien Hertzaef0c912016-08-08 10:20:28 +02001538static size_t GetMethodNumArgRegistersIncludingThis(ArtMethod* method)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001539 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertzaef0c912016-08-08 10:20:28 +02001540 uint32_t num_registers = ArtMethod::NumArgRegisters(method->GetShorty());
1541 if (!method->IsStatic()) {
1542 ++num_registers;
1543 }
1544 return num_registers;
1545}
1546
Jeff Haob7cefc72013-11-14 14:51:09 -08001547/*
1548 * Circularly shifts registers so that arguments come last. Reverts
1549 * slots to dex style argument placement.
1550 */
Mathieu Chartiere401d142015-04-22 13:56:20 -07001551static uint16_t DemangleSlot(uint16_t slot, ArtMethod* m, JDWP::JdwpError* error)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001552 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001553 const DexFile::CodeItem* code_item = m->GetCodeItem();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001554 if (code_item == nullptr) {
1555 // We should not get here for a method without code (native, proxy or abstract). Log it and
1556 // return the slot as is since all registers are arguments.
David Sehr709b0702016-10-13 09:12:37 -07001557 LOG(WARNING) << "Trying to demangle slot for method without code "
1558 << m->PrettyMethod();
Sebastien Hertzaef0c912016-08-08 10:20:28 +02001559 uint16_t vreg_count = GetMethodNumArgRegistersIncludingThis(m);
Sebastien Hertzabbabc82015-03-26 08:47:47 +01001560 if (slot < vreg_count) {
1561 *error = JDWP::ERR_NONE;
1562 return slot;
1563 }
Jeff Haob7cefc72013-11-14 14:51:09 -08001564 } else {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01001565 if (slot < code_item->registers_size_) {
1566 uint16_t ins_size = code_item->ins_size_;
1567 uint16_t locals_size = code_item->registers_size_ - ins_size;
1568 *error = JDWP::ERR_NONE;
1569 return (slot < ins_size) ? slot + locals_size : slot - ins_size;
1570 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001571 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01001572
1573 // Slot is invalid in the method.
David Sehr709b0702016-10-13 09:12:37 -07001574 LOG(ERROR) << "Invalid local slot " << slot << " for method " << m->PrettyMethod();
Sebastien Hertzabbabc82015-03-26 08:47:47 +01001575 *error = JDWP::ERR_INVALID_SLOT;
1576 return DexFile::kDexNoIndex16;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001577}
1578
Mathieu Chartier90443472015-07-16 20:32:27 -07001579JDWP::JdwpError Dbg::OutputDeclaredFields(JDWP::RefTypeId class_id, bool with_generic,
1580 JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001581 JDWP::JdwpError error;
1582 mirror::Class* c = DecodeClass(class_id, &error);
1583 if (c == nullptr) {
1584 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001585 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001586
1587 size_t instance_field_count = c->NumInstanceFields();
1588 size_t static_field_count = c->NumStaticFields();
1589
1590 expandBufAdd4BE(pReply, instance_field_count + static_field_count);
1591
1592 for (size_t i = 0; i < instance_field_count + static_field_count; ++i) {
Mathieu Chartier90443472015-07-16 20:32:27 -07001593 ArtField* f = (i < instance_field_count) ? c->GetInstanceField(i) :
1594 c->GetStaticField(i - instance_field_count);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001595 expandBufAddFieldId(pReply, ToFieldId(f));
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001596 expandBufAddUtf8String(pReply, f->GetName());
1597 expandBufAddUtf8String(pReply, f->GetTypeDescriptor());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001598 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001599 static const char genericSignature[1] = "";
1600 expandBufAddUtf8String(pReply, genericSignature);
1601 }
1602 expandBufAdd4BE(pReply, MangleAccessFlags(f->GetAccessFlags()));
1603 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001604 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001605}
1606
Elliott Hughes88d63092013-01-09 09:55:54 -08001607JDWP::JdwpError Dbg::OutputDeclaredMethods(JDWP::RefTypeId class_id, bool with_generic,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001608 JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001609 JDWP::JdwpError error;
1610 mirror::Class* c = DecodeClass(class_id, &error);
1611 if (c == nullptr) {
1612 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001613 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001614
Alex Light51a64d52015-12-17 13:55:59 -08001615 expandBufAdd4BE(pReply, c->NumMethods());
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001616
Mathieu Chartiere401d142015-04-22 13:56:20 -07001617 auto* cl = Runtime::Current()->GetClassLinker();
1618 auto ptr_size = cl->GetImagePointerSize();
Alex Light51a64d52015-12-17 13:55:59 -08001619 for (ArtMethod& m : c->GetMethods(ptr_size)) {
1620 expandBufAddMethodId(pReply, ToMethodId(&m));
Andreas Gampe542451c2016-07-26 09:02:02 -07001621 expandBufAddUtf8String(pReply, m.GetInterfaceMethodIfProxy(kRuntimePointerSize)->GetName());
1622 expandBufAddUtf8String(
1623 pReply, m.GetInterfaceMethodIfProxy(kRuntimePointerSize)->GetSignature().ToString());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001624 if (with_generic) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001625 const char* generic_signature = "";
1626 expandBufAddUtf8String(pReply, generic_signature);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001627 }
Alex Light51a64d52015-12-17 13:55:59 -08001628 expandBufAdd4BE(pReply, MangleAccessFlags(m.GetAccessFlags()));
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001629 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001630 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001631}
1632
Elliott Hughes88d63092013-01-09 09:55:54 -08001633JDWP::JdwpError Dbg::OutputDeclaredInterfaces(JDWP::RefTypeId class_id, JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001634 JDWP::JdwpError error;
Mathieu Chartierf8322842014-05-16 10:59:25 -07001635 Thread* self = Thread::Current();
Vladimir Marko19a4d372016-12-08 14:41:46 +00001636 ObjPtr<mirror::Class> c = DecodeClass(class_id, &error);
1637 if (c == nullptr) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001638 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001639 }
Mathieu Chartierf8322842014-05-16 10:59:25 -07001640 size_t interface_count = c->NumDirectInterfaces();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001641 expandBufAdd4BE(pReply, interface_count);
1642 for (size_t i = 0; i < interface_count; ++i) {
Vladimir Marko19a4d372016-12-08 14:41:46 +00001643 ObjPtr<mirror::Class> interface = mirror::Class::GetDirectInterface(self, c, i);
1644 DCHECK(interface != nullptr);
1645 expandBufAddRefTypeId(pReply, gRegistry->AddRefType(interface));
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001646 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001647 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001648}
1649
Ian Rogersc0542af2014-09-03 16:16:56 -07001650void Dbg::OutputLineTable(JDWP::RefTypeId, JDWP::MethodId method_id, JDWP::ExpandBuf* pReply) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001651 struct DebugCallbackContext {
1652 int numItems;
1653 JDWP::ExpandBuf* pReply;
1654
David Srbeckyb06e28e2015-12-10 13:15:00 +00001655 static bool Callback(void* context, const DexFile::PositionInfo& entry) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001656 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
David Srbeckyb06e28e2015-12-10 13:15:00 +00001657 expandBufAdd8BE(pContext->pReply, entry.address_);
1658 expandBufAdd4BE(pContext->pReply, entry.line_);
Elliott Hughes03181a82011-11-17 17:22:21 -08001659 pContext->numItems++;
Sebastien Hertzf2910ee2013-10-19 16:39:24 +02001660 return false;
Elliott Hughes03181a82011-11-17 17:22:21 -08001661 }
1662 };
Mathieu Chartiere401d142015-04-22 13:56:20 -07001663 ArtMethod* m = FromMethodId(method_id);
Mathieu Chartier31f4c9f2017-12-08 15:46:11 -08001664 CodeItemDebugInfoAccessor accessor(m);
Elliott Hughes03181a82011-11-17 17:22:21 -08001665 uint64_t start, end;
Mathieu Chartier31f4c9f2017-12-08 15:46:11 -08001666 if (!accessor.HasCodeItem()) {
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001667 DCHECK(m->IsNative() || m->IsProxyMethod());
Elliott Hughes03181a82011-11-17 17:22:21 -08001668 start = -1;
1669 end = -1;
1670 } else {
1671 start = 0;
jeffhao14f0db92012-12-14 17:50:42 -08001672 // Return the index of the last instruction
Mathieu Chartier31f4c9f2017-12-08 15:46:11 -08001673 end = accessor.InsnsSizeInCodeUnits() - 1;
Elliott Hughes03181a82011-11-17 17:22:21 -08001674 }
1675
1676 expandBufAdd8BE(pReply, start);
1677 expandBufAdd8BE(pReply, end);
1678
1679 // Add numLines later
1680 size_t numLinesOffset = expandBufGetLength(pReply);
1681 expandBufAdd4BE(pReply, 0);
1682
1683 DebugCallbackContext context;
1684 context.numItems = 0;
1685 context.pReply = pReply;
1686
Mathieu Chartier31f4c9f2017-12-08 15:46:11 -08001687 if (accessor.HasCodeItem()) {
1688 m->GetDexFile()->DecodeDebugPositionInfo(accessor.DebugInfoOffset(),
1689 DebugCallbackContext::Callback,
1690 &context);
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001691 }
Elliott Hughes03181a82011-11-17 17:22:21 -08001692
1693 JDWP::Set4BE(expandBufGetBuffer(pReply) + numLinesOffset, context.numItems);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001694}
1695
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001696void Dbg::OutputVariableTable(JDWP::RefTypeId, JDWP::MethodId method_id, bool with_generic,
1697 JDWP::ExpandBuf* pReply) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001698 struct DebugCallbackContext {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001699 ArtMethod* method;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001700 JDWP::ExpandBuf* pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001701 size_t variable_count;
1702 bool with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001703
David Srbeckyb06e28e2015-12-10 13:15:00 +00001704 static void Callback(void* context, const DexFile::LocalInfo& entry)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001705 REQUIRES_SHARED(Locks::mutator_lock_) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001706 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
1707
David Srbeckyb06e28e2015-12-10 13:15:00 +00001708 uint16_t slot = entry.reg_;
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001709 VLOG(jdwp) << StringPrintf(" %2zd: %d(%d) '%s' '%s' '%s' actual slot=%d mangled slot=%d",
David Srbeckyb06e28e2015-12-10 13:15:00 +00001710 pContext->variable_count, entry.start_address_,
1711 entry.end_address_ - entry.start_address_,
1712 entry.name_, entry.descriptor_, entry.signature_, slot,
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001713 MangleSlot(slot, pContext->method));
Elliott Hughesdbb40792011-11-18 17:05:22 -08001714
Jeff Haob7cefc72013-11-14 14:51:09 -08001715 slot = MangleSlot(slot, pContext->method);
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001716
David Srbeckyb06e28e2015-12-10 13:15:00 +00001717 expandBufAdd8BE(pContext->pReply, entry.start_address_);
1718 expandBufAddUtf8String(pContext->pReply, entry.name_);
1719 expandBufAddUtf8String(pContext->pReply, entry.descriptor_);
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001720 if (pContext->with_generic) {
David Srbeckyb06e28e2015-12-10 13:15:00 +00001721 expandBufAddUtf8String(pContext->pReply, entry.signature_);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001722 }
David Srbeckyb06e28e2015-12-10 13:15:00 +00001723 expandBufAdd4BE(pContext->pReply, entry.end_address_- entry.start_address_);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001724 expandBufAdd4BE(pContext->pReply, slot);
1725
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001726 ++pContext->variable_count;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001727 }
1728 };
Mathieu Chartiere401d142015-04-22 13:56:20 -07001729 ArtMethod* m = FromMethodId(method_id);
Mathieu Chartier31f4c9f2017-12-08 15:46:11 -08001730 CodeItemDebugInfoAccessor accessor(m);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001731
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001732 // arg_count considers doubles and longs to take 2 units.
1733 // variable_count considers everything to take 1 unit.
Sebastien Hertzaef0c912016-08-08 10:20:28 +02001734 expandBufAdd4BE(pReply, GetMethodNumArgRegistersIncludingThis(m));
Elliott Hughesdbb40792011-11-18 17:05:22 -08001735
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001736 // We don't know the total number of variables yet, so leave a blank and update it later.
1737 size_t variable_count_offset = expandBufGetLength(pReply);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001738 expandBufAdd4BE(pReply, 0);
1739
1740 DebugCallbackContext context;
Jeff Haob7cefc72013-11-14 14:51:09 -08001741 context.method = m;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001742 context.pReply = pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001743 context.variable_count = 0;
1744 context.with_generic = with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001745
Mathieu Chartier31f4c9f2017-12-08 15:46:11 -08001746 if (accessor.HasCodeItem()) {
1747 m->GetDexFile()->DecodeDebugLocalInfo(accessor.RegistersSize(),
1748 accessor.InsSize(),
1749 accessor.InsnsSizeInCodeUnits(),
1750 accessor.DebugInfoOffset(),
1751 m->IsStatic(),
1752 m->GetDexMethodIndex(),
1753 DebugCallbackContext::Callback,
1754 &context);
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001755 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001756
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001757 JDWP::Set4BE(expandBufGetBuffer(pReply) + variable_count_offset, context.variable_count);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001758}
1759
Jeff Hao579b0242013-11-18 13:16:49 -08001760void Dbg::OutputMethodReturnValue(JDWP::MethodId method_id, const JValue* return_value,
1761 JDWP::ExpandBuf* pReply) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001762 ArtMethod* m = FromMethodId(method_id);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001763 JDWP::JdwpTag tag = BasicTagFromDescriptor(m->GetShorty());
Jeff Hao579b0242013-11-18 13:16:49 -08001764 OutputJValue(tag, return_value, pReply);
1765}
1766
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02001767void Dbg::OutputFieldValue(JDWP::FieldId field_id, const JValue* field_value,
1768 JDWP::ExpandBuf* pReply) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001769 ArtField* f = FromFieldId(field_id);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001770 JDWP::JdwpTag tag = BasicTagFromDescriptor(f->GetTypeDescriptor());
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02001771 OutputJValue(tag, field_value, pReply);
1772}
1773
Elliott Hughes9777ba22013-01-17 09:04:19 -08001774JDWP::JdwpError Dbg::GetBytecodes(JDWP::RefTypeId, JDWP::MethodId method_id,
Ian Rogersc0542af2014-09-03 16:16:56 -07001775 std::vector<uint8_t>* bytecodes) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001776 ArtMethod* m = FromMethodId(method_id);
Ian Rogersc0542af2014-09-03 16:16:56 -07001777 if (m == nullptr) {
Elliott Hughes9777ba22013-01-17 09:04:19 -08001778 return JDWP::ERR_INVALID_METHODID;
1779 }
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001780 const DexFile::CodeItem* code_item = m->GetCodeItem();
Elliott Hughes9777ba22013-01-17 09:04:19 -08001781 size_t byte_count = code_item->insns_size_in_code_units_ * 2;
1782 const uint8_t* begin = reinterpret_cast<const uint8_t*>(code_item->insns_);
1783 const uint8_t* end = begin + byte_count;
1784 for (const uint8_t* p = begin; p != end; ++p) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001785 bytecodes->push_back(*p);
Elliott Hughes9777ba22013-01-17 09:04:19 -08001786 }
1787 return JDWP::ERR_NONE;
1788}
1789
Elliott Hughes88d63092013-01-09 09:55:54 -08001790JDWP::JdwpTag Dbg::GetFieldBasicTag(JDWP::FieldId field_id) {
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001791 return BasicTagFromDescriptor(FromFieldId(field_id)->GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001792}
1793
Elliott Hughes88d63092013-01-09 09:55:54 -08001794JDWP::JdwpTag Dbg::GetStaticFieldBasicTag(JDWP::FieldId field_id) {
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001795 return BasicTagFromDescriptor(FromFieldId(field_id)->GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001796}
1797
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001798static JValue GetArtFieldValue(ArtField* f, mirror::Object* o)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001799 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001800 Primitive::Type fieldType = f->GetTypeAsPrimitiveType();
1801 JValue field_value;
1802 switch (fieldType) {
1803 case Primitive::kPrimBoolean:
1804 field_value.SetZ(f->GetBoolean(o));
1805 return field_value;
1806
1807 case Primitive::kPrimByte:
1808 field_value.SetB(f->GetByte(o));
1809 return field_value;
1810
1811 case Primitive::kPrimChar:
1812 field_value.SetC(f->GetChar(o));
1813 return field_value;
1814
1815 case Primitive::kPrimShort:
1816 field_value.SetS(f->GetShort(o));
1817 return field_value;
1818
1819 case Primitive::kPrimInt:
1820 case Primitive::kPrimFloat:
1821 // Int and Float must be treated as 32-bit values in JDWP.
1822 field_value.SetI(f->GetInt(o));
1823 return field_value;
1824
1825 case Primitive::kPrimLong:
1826 case Primitive::kPrimDouble:
1827 // Long and Double must be treated as 64-bit values in JDWP.
1828 field_value.SetJ(f->GetLong(o));
1829 return field_value;
1830
1831 case Primitive::kPrimNot:
Mathieu Chartier1cc62e42016-10-03 18:01:28 -07001832 field_value.SetL(f->GetObject(o).Ptr());
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001833 return field_value;
1834
1835 case Primitive::kPrimVoid:
1836 LOG(FATAL) << "Attempt to read from field of type 'void'";
1837 UNREACHABLE();
1838 }
1839 LOG(FATAL) << "Attempt to read from field of unknown type";
1840 UNREACHABLE();
1841}
1842
Elliott Hughes88d63092013-01-09 09:55:54 -08001843static JDWP::JdwpError GetFieldValueImpl(JDWP::RefTypeId ref_type_id, JDWP::ObjectId object_id,
1844 JDWP::FieldId field_id, JDWP::ExpandBuf* pReply,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001845 bool is_static)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001846 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001847 JDWP::JdwpError error;
1848 mirror::Class* c = DecodeClass(ref_type_id, &error);
1849 if (ref_type_id != 0 && c == nullptr) {
1850 return error;
Elliott Hughes0cf74332012-02-23 23:14:00 -08001851 }
1852
Jeff Haode19a252016-09-14 15:56:35 -07001853 Thread* self = Thread::Current();
1854 StackHandleScope<2> hs(self);
1855 MutableHandle<mirror::Object>
1856 o(hs.NewHandle(Dbg::GetObjectRegistry()->Get<mirror::Object*>(object_id, &error)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08001857 if ((!is_static && o == nullptr) || error != JDWP::ERR_NONE) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001858 return JDWP::ERR_INVALID_OBJECT;
1859 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001860 ArtField* f = FromFieldId(field_id);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001861
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001862 mirror::Class* receiver_class = c;
Andreas Gampefa4333d2017-02-14 11:10:34 -08001863 if (receiver_class == nullptr && o != nullptr) {
Elliott Hughes0cf74332012-02-23 23:14:00 -08001864 receiver_class = o->GetClass();
1865 }
Jeff Haode19a252016-09-14 15:56:35 -07001866
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001867 // TODO: should we give up now if receiver_class is null?
Ian Rogersc0542af2014-09-03 16:16:56 -07001868 if (receiver_class != nullptr && !f->GetDeclaringClass()->IsAssignableFrom(receiver_class)) {
David Sehr709b0702016-10-13 09:12:37 -07001869 LOG(INFO) << "ERR_INVALID_FIELDID: " << f->PrettyField() << " "
1870 << receiver_class->PrettyClass();
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001871 return JDWP::ERR_INVALID_FIELDID;
1872 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001873
Jeff Haode19a252016-09-14 15:56:35 -07001874 // Ensure the field's class is initialized.
1875 Handle<mirror::Class> klass(hs.NewHandle(f->GetDeclaringClass()));
1876 if (!Runtime::Current()->GetClassLinker()->EnsureInitialized(self, klass, true, false)) {
David Sehr709b0702016-10-13 09:12:37 -07001877 LOG(WARNING) << "Not able to initialize class for SetValues: "
1878 << mirror::Class::PrettyClass(klass.Get());
Jeff Haode19a252016-09-14 15:56:35 -07001879 }
1880
Elliott Hughes0cf74332012-02-23 23:14:00 -08001881 // The RI only enforces the static/non-static mismatch in one direction.
1882 // TODO: should we change the tests and check both?
1883 if (is_static) {
1884 if (!f->IsStatic()) {
1885 return JDWP::ERR_INVALID_FIELDID;
1886 }
1887 } else {
1888 if (f->IsStatic()) {
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001889 LOG(WARNING) << "Ignoring non-nullptr receiver for ObjectReference.GetValues"
David Sehr709b0702016-10-13 09:12:37 -07001890 << " on static field " << f->PrettyField();
Elliott Hughes0cf74332012-02-23 23:14:00 -08001891 }
1892 }
jeffhao0dfbb7e2012-11-28 15:26:03 -08001893 if (f->IsStatic()) {
Jeff Haode19a252016-09-14 15:56:35 -07001894 o.Assign(f->GetDeclaringClass());
jeffhao0dfbb7e2012-11-28 15:26:03 -08001895 }
Elliott Hughes0cf74332012-02-23 23:14:00 -08001896
Jeff Haode19a252016-09-14 15:56:35 -07001897 JValue field_value(GetArtFieldValue(f, o.Get()));
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001898 JDWP::JdwpTag tag = BasicTagFromDescriptor(f->GetTypeDescriptor());
Jeff Hao579b0242013-11-18 13:16:49 -08001899 Dbg::OutputJValue(tag, &field_value, pReply);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001900 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001901}
1902
Elliott Hughes88d63092013-01-09 09:55:54 -08001903JDWP::JdwpError Dbg::GetFieldValue(JDWP::ObjectId object_id, JDWP::FieldId field_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001904 JDWP::ExpandBuf* pReply) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001905 return GetFieldValueImpl(0, object_id, field_id, pReply, false);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001906}
1907
Ian Rogersc0542af2014-09-03 16:16:56 -07001908JDWP::JdwpError Dbg::GetStaticFieldValue(JDWP::RefTypeId ref_type_id, JDWP::FieldId field_id,
1909 JDWP::ExpandBuf* pReply) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001910 return GetFieldValueImpl(ref_type_id, 0, field_id, pReply, true);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001911}
1912
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001913static JDWP::JdwpError SetArtFieldValue(ArtField* f, mirror::Object* o, uint64_t value, int width)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001914 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001915 Primitive::Type fieldType = f->GetTypeAsPrimitiveType();
1916 // Debugging only happens at runtime so we know we are not running in a transaction.
1917 static constexpr bool kNoTransactionMode = false;
1918 switch (fieldType) {
1919 case Primitive::kPrimBoolean:
1920 CHECK_EQ(width, 1);
1921 f->SetBoolean<kNoTransactionMode>(o, static_cast<uint8_t>(value));
1922 return JDWP::ERR_NONE;
1923
1924 case Primitive::kPrimByte:
1925 CHECK_EQ(width, 1);
1926 f->SetByte<kNoTransactionMode>(o, static_cast<uint8_t>(value));
1927 return JDWP::ERR_NONE;
1928
1929 case Primitive::kPrimChar:
1930 CHECK_EQ(width, 2);
1931 f->SetChar<kNoTransactionMode>(o, static_cast<uint16_t>(value));
1932 return JDWP::ERR_NONE;
1933
1934 case Primitive::kPrimShort:
1935 CHECK_EQ(width, 2);
1936 f->SetShort<kNoTransactionMode>(o, static_cast<int16_t>(value));
1937 return JDWP::ERR_NONE;
1938
1939 case Primitive::kPrimInt:
1940 case Primitive::kPrimFloat:
1941 CHECK_EQ(width, 4);
1942 // Int and Float must be treated as 32-bit values in JDWP.
1943 f->SetInt<kNoTransactionMode>(o, static_cast<int32_t>(value));
1944 return JDWP::ERR_NONE;
1945
1946 case Primitive::kPrimLong:
1947 case Primitive::kPrimDouble:
1948 CHECK_EQ(width, 8);
1949 // Long and Double must be treated as 64-bit values in JDWP.
1950 f->SetLong<kNoTransactionMode>(o, value);
1951 return JDWP::ERR_NONE;
1952
1953 case Primitive::kPrimNot: {
1954 JDWP::JdwpError error;
1955 mirror::Object* v = Dbg::GetObjectRegistry()->Get<mirror::Object*>(value, &error);
1956 if (error != JDWP::ERR_NONE) {
1957 return JDWP::ERR_INVALID_OBJECT;
1958 }
1959 if (v != nullptr) {
Mathieu Chartier3398c782016-09-30 10:27:43 -07001960 ObjPtr<mirror::Class> field_type;
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001961 {
1962 StackHandleScope<2> hs(Thread::Current());
1963 HandleWrapper<mirror::Object> h_v(hs.NewHandleWrapper(&v));
1964 HandleWrapper<mirror::Object> h_o(hs.NewHandleWrapper(&o));
Vladimir Marko4098a7a2017-11-06 16:00:51 +00001965 field_type = f->ResolveType();
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001966 }
1967 if (!field_type->IsAssignableFrom(v->GetClass())) {
1968 return JDWP::ERR_INVALID_OBJECT;
1969 }
1970 }
1971 f->SetObject<kNoTransactionMode>(o, v);
1972 return JDWP::ERR_NONE;
1973 }
1974
1975 case Primitive::kPrimVoid:
1976 LOG(FATAL) << "Attempt to write to field of type 'void'";
1977 UNREACHABLE();
1978 }
1979 LOG(FATAL) << "Attempt to write to field of unknown type";
1980 UNREACHABLE();
1981}
1982
Elliott Hughes88d63092013-01-09 09:55:54 -08001983static JDWP::JdwpError SetFieldValueImpl(JDWP::ObjectId object_id, JDWP::FieldId field_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001984 uint64_t value, int width, bool is_static)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001985 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001986 JDWP::JdwpError error;
Jeff Haode19a252016-09-14 15:56:35 -07001987 Thread* self = Thread::Current();
1988 StackHandleScope<2> hs(self);
1989 MutableHandle<mirror::Object>
1990 o(hs.NewHandle(Dbg::GetObjectRegistry()->Get<mirror::Object*>(object_id, &error)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08001991 if ((!is_static && o == nullptr) || error != JDWP::ERR_NONE) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001992 return JDWP::ERR_INVALID_OBJECT;
1993 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001994 ArtField* f = FromFieldId(field_id);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001995
Jeff Haode19a252016-09-14 15:56:35 -07001996 // Ensure the field's class is initialized.
1997 Handle<mirror::Class> klass(hs.NewHandle(f->GetDeclaringClass()));
1998 if (!Runtime::Current()->GetClassLinker()->EnsureInitialized(self, klass, true, false)) {
David Sehr709b0702016-10-13 09:12:37 -07001999 LOG(WARNING) << "Not able to initialize class for SetValues: "
2000 << mirror::Class::PrettyClass(klass.Get());
Jeff Haode19a252016-09-14 15:56:35 -07002001 }
2002
Elliott Hughes0cf74332012-02-23 23:14:00 -08002003 // The RI only enforces the static/non-static mismatch in one direction.
2004 // TODO: should we change the tests and check both?
2005 if (is_static) {
2006 if (!f->IsStatic()) {
2007 return JDWP::ERR_INVALID_FIELDID;
2008 }
2009 } else {
2010 if (f->IsStatic()) {
Sebastien Hertz05c26b32015-06-11 18:42:58 +02002011 LOG(WARNING) << "Ignoring non-nullptr receiver for ObjectReference.SetValues"
David Sehr709b0702016-10-13 09:12:37 -07002012 << " on static field " << f->PrettyField();
Elliott Hughes0cf74332012-02-23 23:14:00 -08002013 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002014 }
jeffhao0dfbb7e2012-11-28 15:26:03 -08002015 if (f->IsStatic()) {
Jeff Haode19a252016-09-14 15:56:35 -07002016 o.Assign(f->GetDeclaringClass());
jeffhao0dfbb7e2012-11-28 15:26:03 -08002017 }
Jeff Haode19a252016-09-14 15:56:35 -07002018 return SetArtFieldValue(f, o.Get(), value, width);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002019}
2020
Elliott Hughes88d63092013-01-09 09:55:54 -08002021JDWP::JdwpError Dbg::SetFieldValue(JDWP::ObjectId object_id, JDWP::FieldId field_id, uint64_t value,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002022 int width) {
Elliott Hughes88d63092013-01-09 09:55:54 -08002023 return SetFieldValueImpl(object_id, field_id, value, width, false);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002024}
2025
Elliott Hughes88d63092013-01-09 09:55:54 -08002026JDWP::JdwpError Dbg::SetStaticFieldValue(JDWP::FieldId field_id, uint64_t value, int width) {
2027 return SetFieldValueImpl(0, field_id, value, width, true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002028}
2029
Sebastien Hertzb0b0b492014-09-15 11:27:27 +02002030JDWP::JdwpError Dbg::StringToUtf8(JDWP::ObjectId string_id, std::string* str) {
Ian Rogersc0542af2014-09-03 16:16:56 -07002031 JDWP::JdwpError error;
Sebastien Hertzb0b0b492014-09-15 11:27:27 +02002032 mirror::Object* obj = gRegistry->Get<mirror::Object*>(string_id, &error);
2033 if (error != JDWP::ERR_NONE) {
2034 return error;
2035 }
2036 if (obj == nullptr) {
2037 return JDWP::ERR_INVALID_OBJECT;
2038 }
2039 {
2040 ScopedObjectAccessUnchecked soa(Thread::Current());
Mathieu Chartier0795f232016-09-27 18:43:30 -07002041 ObjPtr<mirror::Class> java_lang_String =
2042 soa.Decode<mirror::Class>(WellKnownClasses::java_lang_String);
Sebastien Hertzb0b0b492014-09-15 11:27:27 +02002043 if (!java_lang_String->IsAssignableFrom(obj->GetClass())) {
2044 // This isn't a string.
2045 return JDWP::ERR_INVALID_STRING;
2046 }
2047 }
2048 *str = obj->AsString()->ToModifiedUtf8();
2049 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002050}
2051
Jeff Hao579b0242013-11-18 13:16:49 -08002052void Dbg::OutputJValue(JDWP::JdwpTag tag, const JValue* return_value, JDWP::ExpandBuf* pReply) {
2053 if (IsPrimitiveTag(tag)) {
2054 expandBufAdd1(pReply, tag);
2055 if (tag == JDWP::JT_BOOLEAN || tag == JDWP::JT_BYTE) {
2056 expandBufAdd1(pReply, return_value->GetI());
2057 } else if (tag == JDWP::JT_CHAR || tag == JDWP::JT_SHORT) {
2058 expandBufAdd2BE(pReply, return_value->GetI());
2059 } else if (tag == JDWP::JT_FLOAT || tag == JDWP::JT_INT) {
2060 expandBufAdd4BE(pReply, return_value->GetI());
2061 } else if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
2062 expandBufAdd8BE(pReply, return_value->GetJ());
2063 } else {
2064 CHECK_EQ(tag, JDWP::JT_VOID);
2065 }
2066 } else {
Ian Rogers98379392014-02-24 16:53:16 -08002067 ScopedObjectAccessUnchecked soa(Thread::Current());
Jeff Hao579b0242013-11-18 13:16:49 -08002068 mirror::Object* value = return_value->GetL();
Ian Rogers98379392014-02-24 16:53:16 -08002069 expandBufAdd1(pReply, TagFromObject(soa, value));
Jeff Hao579b0242013-11-18 13:16:49 -08002070 expandBufAddObjectId(pReply, gRegistry->Add(value));
2071 }
2072}
2073
Ian Rogersc0542af2014-09-03 16:16:56 -07002074JDWP::JdwpError Dbg::GetThreadName(JDWP::ObjectId thread_id, std::string* name) {
jeffhaoa77f0f62012-12-05 17:19:31 -08002075 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002076 JDWP::JdwpError error;
Roland Levillain4b8f1ec2015-08-26 18:34:03 +01002077 DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002078 if (error != JDWP::ERR_NONE && error != JDWP::ERR_THREAD_NOT_ALIVE) {
2079 return error;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08002080 }
Elliott Hughes221229c2013-01-08 18:17:50 -08002081
2082 // We still need to report the zombie threads' names, so we can't just call Thread::GetThreadName.
Ian Rogersc0542af2014-09-03 16:16:56 -07002083 mirror::Object* thread_object = gRegistry->Get<mirror::Object*>(thread_id, &error);
2084 CHECK(thread_object != nullptr) << error;
Mathieu Chartierc7853442015-03-27 14:35:38 -07002085 ArtField* java_lang_Thread_name_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08002086 jni::DecodeArtField(WellKnownClasses::java_lang_Thread_name);
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07002087 ObjPtr<mirror::String> s(java_lang_Thread_name_field->GetObject(thread_object)->AsString());
Ian Rogersc0542af2014-09-03 16:16:56 -07002088 if (s != nullptr) {
2089 *name = s->ToModifiedUtf8();
Elliott Hughes221229c2013-01-08 18:17:50 -08002090 }
2091 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002092}
2093
Elliott Hughes221229c2013-01-08 18:17:50 -08002094JDWP::JdwpError Dbg::GetThreadGroup(JDWP::ObjectId thread_id, JDWP::ExpandBuf* pReply) {
Sebastien Hertza06430c2014-09-15 19:21:30 +02002095 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002096 JDWP::JdwpError error;
2097 mirror::Object* thread_object = gRegistry->Get<mirror::Object*>(thread_id, &error);
2098 if (error != JDWP::ERR_NONE) {
Elliott Hughes2435a572012-02-17 16:07:41 -08002099 return JDWP::ERR_INVALID_OBJECT;
2100 }
Mathieu Chartier268764d2016-09-13 12:09:38 -07002101 ScopedAssertNoThreadSuspension ants("Debugger: GetThreadGroup");
Elliott Hughes2435a572012-02-17 16:07:41 -08002102 // Okay, so it's an object, but is it actually a thread?
Roland Levillain4b8f1ec2015-08-26 18:34:03 +01002103 DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002104 if (error == JDWP::ERR_THREAD_NOT_ALIVE) {
2105 // Zombie threads are in the null group.
2106 expandBufAddObjectId(pReply, JDWP::ObjectId(0));
Sebastien Hertz52d131d2014-03-13 16:17:40 +01002107 error = JDWP::ERR_NONE;
2108 } else if (error == JDWP::ERR_NONE) {
Mathieu Chartier0795f232016-09-27 18:43:30 -07002109 ObjPtr<mirror::Class> c = soa.Decode<mirror::Class>(WellKnownClasses::java_lang_Thread);
Sebastien Hertz52d131d2014-03-13 16:17:40 +01002110 CHECK(c != nullptr);
Andreas Gampe08883de2016-11-08 13:20:52 -08002111 ArtField* f = jni::DecodeArtField(WellKnownClasses::java_lang_Thread_group);
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07002112 CHECK(f != nullptr);
Mathieu Chartier3398c782016-09-30 10:27:43 -07002113 ObjPtr<mirror::Object> group = f->GetObject(thread_object);
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07002114 CHECK(group != nullptr);
Sebastien Hertz52d131d2014-03-13 16:17:40 +01002115 JDWP::ObjectId thread_group_id = gRegistry->Add(group);
2116 expandBufAddObjectId(pReply, thread_group_id);
Elliott Hughes221229c2013-01-08 18:17:50 -08002117 }
Sebastien Hertz52d131d2014-03-13 16:17:40 +01002118 return error;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002119}
2120
Sebastien Hertza06430c2014-09-15 19:21:30 +02002121static mirror::Object* DecodeThreadGroup(ScopedObjectAccessUnchecked& soa,
2122 JDWP::ObjectId thread_group_id, JDWP::JdwpError* error)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002123 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz6995c602014-09-09 12:10:13 +02002124 mirror::Object* thread_group = Dbg::GetObjectRegistry()->Get<mirror::Object*>(thread_group_id,
2125 error);
Sebastien Hertza06430c2014-09-15 19:21:30 +02002126 if (*error != JDWP::ERR_NONE) {
2127 return nullptr;
2128 }
2129 if (thread_group == nullptr) {
2130 *error = JDWP::ERR_INVALID_OBJECT;
2131 return nullptr;
2132 }
Mathieu Chartier0795f232016-09-27 18:43:30 -07002133 ObjPtr<mirror::Class> c =
2134 soa.Decode<mirror::Class>(WellKnownClasses::java_lang_ThreadGroup);
Ian Rogers98379392014-02-24 16:53:16 -08002135 CHECK(c != nullptr);
Sebastien Hertza06430c2014-09-15 19:21:30 +02002136 if (!c->IsAssignableFrom(thread_group->GetClass())) {
2137 // This is not a java.lang.ThreadGroup.
2138 *error = JDWP::ERR_INVALID_THREAD_GROUP;
2139 return nullptr;
2140 }
2141 *error = JDWP::ERR_NONE;
2142 return thread_group;
2143}
2144
2145JDWP::JdwpError Dbg::GetThreadGroupName(JDWP::ObjectId thread_group_id, JDWP::ExpandBuf* pReply) {
2146 ScopedObjectAccessUnchecked soa(Thread::Current());
2147 JDWP::JdwpError error;
2148 mirror::Object* thread_group = DecodeThreadGroup(soa, thread_group_id, &error);
2149 if (error != JDWP::ERR_NONE) {
2150 return error;
2151 }
Mathieu Chartier268764d2016-09-13 12:09:38 -07002152 ScopedAssertNoThreadSuspension ants("Debugger: GetThreadGroupName");
Andreas Gampe08883de2016-11-08 13:20:52 -08002153 ArtField* f = jni::DecodeArtField(WellKnownClasses::java_lang_ThreadGroup_name);
Ian Rogersc0542af2014-09-03 16:16:56 -07002154 CHECK(f != nullptr);
Mathieu Chartier3398c782016-09-30 10:27:43 -07002155 ObjPtr<mirror::String> s = f->GetObject(thread_group)->AsString();
Sebastien Hertza06430c2014-09-15 19:21:30 +02002156
2157 std::string thread_group_name(s->ToModifiedUtf8());
2158 expandBufAddUtf8String(pReply, thread_group_name);
2159 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002160}
2161
Sebastien Hertza06430c2014-09-15 19:21:30 +02002162JDWP::JdwpError Dbg::GetThreadGroupParent(JDWP::ObjectId thread_group_id, JDWP::ExpandBuf* pReply) {
Ian Rogers98379392014-02-24 16:53:16 -08002163 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002164 JDWP::JdwpError error;
Sebastien Hertza06430c2014-09-15 19:21:30 +02002165 mirror::Object* thread_group = DecodeThreadGroup(soa, thread_group_id, &error);
2166 if (error != JDWP::ERR_NONE) {
2167 return error;
2168 }
Mathieu Chartier3398c782016-09-30 10:27:43 -07002169 ObjPtr<mirror::Object> parent;
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07002170 {
Mathieu Chartier268764d2016-09-13 12:09:38 -07002171 ScopedAssertNoThreadSuspension ants("Debugger: GetThreadGroupParent");
Andreas Gampe08883de2016-11-08 13:20:52 -08002172 ArtField* f = jni::DecodeArtField(WellKnownClasses::java_lang_ThreadGroup_parent);
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07002173 CHECK(f != nullptr);
2174 parent = f->GetObject(thread_group);
2175 }
Sebastien Hertza06430c2014-09-15 19:21:30 +02002176 JDWP::ObjectId parent_group_id = gRegistry->Add(parent);
2177 expandBufAddObjectId(pReply, parent_group_id);
2178 return JDWP::ERR_NONE;
2179}
2180
Andreas Gampe08883de2016-11-08 13:20:52 -08002181static void GetChildThreadGroups(mirror::Object* thread_group,
Sebastien Hertza06430c2014-09-15 19:21:30 +02002182 std::vector<JDWP::ObjectId>* child_thread_group_ids)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002183 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertza06430c2014-09-15 19:21:30 +02002184 CHECK(thread_group != nullptr);
2185
Przemyslaw Szczepaniak464595f2015-11-24 11:59:59 +00002186 // Get the int "ngroups" count of this thread group...
Andreas Gampe08883de2016-11-08 13:20:52 -08002187 ArtField* ngroups_field = jni::DecodeArtField(WellKnownClasses::java_lang_ThreadGroup_ngroups);
Przemyslaw Szczepaniak464595f2015-11-24 11:59:59 +00002188 CHECK(ngroups_field != nullptr);
2189 const int32_t size = ngroups_field->GetInt(thread_group);
2190 if (size == 0) {
2191 return;
Sebastien Hertze49e1952014-10-13 11:27:13 +02002192 }
Sebastien Hertza06430c2014-09-15 19:21:30 +02002193
Przemyslaw Szczepaniak464595f2015-11-24 11:59:59 +00002194 // Get the ThreadGroup[] "groups" out of this thread group...
Andreas Gampe08883de2016-11-08 13:20:52 -08002195 ArtField* groups_field = jni::DecodeArtField(WellKnownClasses::java_lang_ThreadGroup_groups);
Mathieu Chartier3398c782016-09-30 10:27:43 -07002196 ObjPtr<mirror::Object> groups_array = groups_field->GetObject(thread_group);
Przemyslaw Szczepaniak464595f2015-11-24 11:59:59 +00002197
2198 CHECK(groups_array != nullptr);
2199 CHECK(groups_array->IsObjectArray());
2200
Mathieu Chartier3398c782016-09-30 10:27:43 -07002201 ObjPtr<mirror::ObjectArray<mirror::Object>> groups_array_as_array =
Przemyslaw Szczepaniak464595f2015-11-24 11:59:59 +00002202 groups_array->AsObjectArray<mirror::Object>();
Sebastien Hertza06430c2014-09-15 19:21:30 +02002203
2204 // Copy the first 'size' elements out of the array into the result.
Sebastien Hertz6995c602014-09-09 12:10:13 +02002205 ObjectRegistry* registry = Dbg::GetObjectRegistry();
Sebastien Hertza06430c2014-09-15 19:21:30 +02002206 for (int32_t i = 0; i < size; ++i) {
Przemyslaw Szczepaniak464595f2015-11-24 11:59:59 +00002207 child_thread_group_ids->push_back(registry->Add(groups_array_as_array->Get(i)));
Sebastien Hertza06430c2014-09-15 19:21:30 +02002208 }
2209}
2210
2211JDWP::JdwpError Dbg::GetThreadGroupChildren(JDWP::ObjectId thread_group_id,
2212 JDWP::ExpandBuf* pReply) {
2213 ScopedObjectAccessUnchecked soa(Thread::Current());
2214 JDWP::JdwpError error;
2215 mirror::Object* thread_group = DecodeThreadGroup(soa, thread_group_id, &error);
2216 if (error != JDWP::ERR_NONE) {
2217 return error;
2218 }
2219
2220 // Add child threads.
2221 {
2222 std::vector<JDWP::ObjectId> child_thread_ids;
2223 GetThreads(thread_group, &child_thread_ids);
2224 expandBufAdd4BE(pReply, child_thread_ids.size());
2225 for (JDWP::ObjectId child_thread_id : child_thread_ids) {
2226 expandBufAddObjectId(pReply, child_thread_id);
2227 }
2228 }
2229
2230 // Add child thread groups.
2231 {
2232 std::vector<JDWP::ObjectId> child_thread_groups_ids;
Andreas Gampe08883de2016-11-08 13:20:52 -08002233 GetChildThreadGroups(thread_group, &child_thread_groups_ids);
Sebastien Hertza06430c2014-09-15 19:21:30 +02002234 expandBufAdd4BE(pReply, child_thread_groups_ids.size());
2235 for (JDWP::ObjectId child_thread_group_id : child_thread_groups_ids) {
2236 expandBufAddObjectId(pReply, child_thread_group_id);
2237 }
2238 }
2239
2240 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002241}
2242
2243JDWP::ObjectId Dbg::GetSystemThreadGroupId() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002244 ScopedObjectAccessUnchecked soa(Thread::Current());
Andreas Gampe08883de2016-11-08 13:20:52 -08002245 ArtField* f = jni::DecodeArtField(WellKnownClasses::java_lang_ThreadGroup_systemThreadGroup);
Mathieu Chartier3398c782016-09-30 10:27:43 -07002246 ObjPtr<mirror::Object> group = f->GetObject(f->GetDeclaringClass());
Ian Rogers365c1022012-06-22 15:05:28 -07002247 return gRegistry->Add(group);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002248}
2249
Jeff Hao920af3e2013-08-28 15:46:38 -07002250JDWP::JdwpThreadStatus Dbg::ToJdwpThreadStatus(ThreadState state) {
2251 switch (state) {
2252 case kBlocked:
2253 return JDWP::TS_MONITOR;
2254 case kNative:
2255 case kRunnable:
2256 case kSuspended:
2257 return JDWP::TS_RUNNING;
2258 case kSleeping:
2259 return JDWP::TS_SLEEPING;
2260 case kStarting:
2261 case kTerminated:
2262 return JDWP::TS_ZOMBIE;
2263 case kTimedWaiting:
Alex Light77fee872017-09-05 14:51:49 -07002264 case kWaitingForTaskProcessor:
2265 case kWaitingForLockInflation:
Sebastien Hertzbae182c2013-12-17 10:42:03 +01002266 case kWaitingForCheckPointsToRun:
Jeff Hao920af3e2013-08-28 15:46:38 -07002267 case kWaitingForDebuggerSend:
2268 case kWaitingForDebuggerSuspension:
2269 case kWaitingForDebuggerToAttach:
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002270 case kWaitingForDeoptimization:
Jeff Hao920af3e2013-08-28 15:46:38 -07002271 case kWaitingForGcToComplete:
Mathieu Chartierb43390c2015-05-12 10:47:11 -07002272 case kWaitingForGetObjectsAllocated:
Jeff Hao920af3e2013-08-28 15:46:38 -07002273 case kWaitingForJniOnLoad:
Sebastien Hertzbae182c2013-12-17 10:42:03 +01002274 case kWaitingForMethodTracingStart:
Jeff Hao920af3e2013-08-28 15:46:38 -07002275 case kWaitingForSignalCatcherOutput:
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -08002276 case kWaitingForVisitObjects:
Jeff Hao920af3e2013-08-28 15:46:38 -07002277 case kWaitingInMainDebuggerLoop:
2278 case kWaitingInMainSignalCatcherLoop:
2279 case kWaitingPerformingGc:
Mathieu Chartier90ef3db2015-08-04 15:19:41 -07002280 case kWaitingWeakGcRootRead:
Hiroshi Yamauchi76f55b02015-08-21 16:10:39 -07002281 case kWaitingForGcThreadFlip:
Jeff Hao920af3e2013-08-28 15:46:38 -07002282 case kWaiting:
2283 return JDWP::TS_WAIT;
2284 // Don't add a 'default' here so the compiler can spot incompatible enum changes.
2285 }
2286 LOG(FATAL) << "Unknown thread state: " << state;
2287 return JDWP::TS_ZOMBIE;
2288}
2289
Sebastien Hertz52d131d2014-03-13 16:17:40 +01002290JDWP::JdwpError Dbg::GetThreadStatus(JDWP::ObjectId thread_id, JDWP::JdwpThreadStatus* pThreadStatus,
2291 JDWP::JdwpSuspendStatus* pSuspendStatus) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002292 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes499c5132011-11-17 14:55:11 -08002293
Elliott Hughes9e0c1752013-01-09 14:02:58 -08002294 *pSuspendStatus = JDWP::SUSPEND_STATUS_NOT_SUSPENDED;
2295
Ian Rogersc0542af2014-09-03 16:16:56 -07002296 JDWP::JdwpError error;
2297 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002298 if (error != JDWP::ERR_NONE) {
2299 if (error == JDWP::ERR_THREAD_NOT_ALIVE) {
2300 *pThreadStatus = JDWP::TS_ZOMBIE;
Elliott Hughes221229c2013-01-08 18:17:50 -08002301 return JDWP::ERR_NONE;
2302 }
2303 return error;
Elliott Hughes499c5132011-11-17 14:55:11 -08002304 }
2305
Elliott Hughes9e0c1752013-01-09 14:02:58 -08002306 if (IsSuspendedForDebugger(soa, thread)) {
2307 *pSuspendStatus = JDWP::SUSPEND_STATUS_SUSPENDED;
Elliott Hughes499c5132011-11-17 14:55:11 -08002308 }
2309
Jeff Hao920af3e2013-08-28 15:46:38 -07002310 *pThreadStatus = ToJdwpThreadStatus(thread->GetState());
Elliott Hughes221229c2013-01-08 18:17:50 -08002311 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002312}
2313
Elliott Hughes221229c2013-01-08 18:17:50 -08002314JDWP::JdwpError Dbg::GetThreadDebugSuspendCount(JDWP::ObjectId thread_id, JDWP::ExpandBuf* pReply) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002315 ScopedObjectAccess soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002316 JDWP::JdwpError error;
2317 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002318 if (error != JDWP::ERR_NONE) {
2319 return error;
Elliott Hughes2435a572012-02-17 16:07:41 -08002320 }
Ian Rogers50b35e22012-10-04 10:09:15 -07002321 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002322 expandBufAdd4BE(pReply, thread->GetDebugSuspendCount());
Elliott Hughes2435a572012-02-17 16:07:41 -08002323 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002324}
2325
Elliott Hughesf9501702013-01-11 11:22:27 -08002326JDWP::JdwpError Dbg::Interrupt(JDWP::ObjectId thread_id) {
2327 ScopedObjectAccess soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002328 JDWP::JdwpError error;
2329 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughesf9501702013-01-11 11:22:27 -08002330 if (error != JDWP::ERR_NONE) {
2331 return error;
2332 }
Ian Rogersdd7624d2014-03-14 17:43:00 -07002333 thread->Interrupt(soa.Self());
Elliott Hughesf9501702013-01-11 11:22:27 -08002334 return JDWP::ERR_NONE;
2335}
2336
Andreas Gampe08883de2016-11-08 13:20:52 -08002337static bool IsInDesiredThreadGroup(mirror::Object* desired_thread_group, mirror::Object* peer)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002338 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz070f7322014-09-09 12:08:49 +02002339 // Do we want threads from all thread groups?
2340 if (desired_thread_group == nullptr) {
2341 return true;
2342 }
Andreas Gampe08883de2016-11-08 13:20:52 -08002343 ArtField* thread_group_field = jni::DecodeArtField(WellKnownClasses::java_lang_Thread_group);
Sebastien Hertz070f7322014-09-09 12:08:49 +02002344 DCHECK(thread_group_field != nullptr);
Mathieu Chartier3398c782016-09-30 10:27:43 -07002345 ObjPtr<mirror::Object> group = thread_group_field->GetObject(peer);
Sebastien Hertz070f7322014-09-09 12:08:49 +02002346 return (group == desired_thread_group);
2347}
2348
Sebastien Hertza06430c2014-09-15 19:21:30 +02002349void Dbg::GetThreads(mirror::Object* thread_group, std::vector<JDWP::ObjectId>* thread_ids) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002350 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz070f7322014-09-09 12:08:49 +02002351 std::list<Thread*> all_threads_list;
2352 {
2353 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
2354 all_threads_list = Runtime::Current()->GetThreadList()->GetList();
2355 }
2356 for (Thread* t : all_threads_list) {
2357 if (t == Dbg::GetDebugThread()) {
2358 // Skip the JDWP thread. Some debuggers get bent out of shape when they can't suspend and
2359 // query all threads, so it's easier if we just don't tell them about this thread.
2360 continue;
2361 }
2362 if (t->IsStillStarting()) {
2363 // This thread is being started (and has been registered in the thread list). However, it is
2364 // not completely started yet so we must ignore it.
2365 continue;
2366 }
Nicolas Geoffraycafa0812017-02-15 18:27:34 +00002367 mirror::Object* peer = t->GetPeerFromOtherThread();
Sebastien Hertz070f7322014-09-09 12:08:49 +02002368 if (peer == nullptr) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002369 // 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 +02002370 // this thread yet.
2371 // TODO: if we identified threads to the debugger by their Thread*
2372 // rather than their peer's mirror::Object*, we could fix this.
2373 // Doing so might help us report ZOMBIE threads too.
2374 continue;
2375 }
Andreas Gampe08883de2016-11-08 13:20:52 -08002376 if (IsInDesiredThreadGroup(thread_group, peer)) {
Sebastien Hertz070f7322014-09-09 12:08:49 +02002377 thread_ids->push_back(gRegistry->Add(peer));
2378 }
2379 }
Elliott Hughescaf76542012-06-28 16:08:22 -07002380}
Elliott Hughesa2155262011-11-16 16:26:58 -08002381
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002382static int GetStackDepth(Thread* thread) REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002383 struct CountStackDepthVisitor : public StackVisitor {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002384 explicit CountStackDepthVisitor(Thread* thread_in)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01002385 : StackVisitor(thread_in, nullptr, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
2386 depth(0) {}
Ian Rogers0399dde2012-06-06 17:09:28 -07002387
Elliott Hughes64f574f2013-02-20 14:57:12 -08002388 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2389 // annotalysis.
2390 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07002391 if (!GetMethod()->IsRuntimeMethod()) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -08002392 ++depth;
2393 }
Elliott Hughes530fa002012-03-12 11:44:49 -07002394 return true;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08002395 }
2396 size_t depth;
2397 };
Elliott Hughes08fc03a2012-06-26 17:34:00 -07002398
Ian Rogers7a22fa62013-01-23 12:16:16 -08002399 CountStackDepthVisitor visitor(thread);
Ian Rogers0399dde2012-06-06 17:09:28 -07002400 visitor.WalkStack();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08002401 return visitor.depth;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002402}
2403
Ian Rogersc0542af2014-09-03 16:16:56 -07002404JDWP::JdwpError Dbg::GetThreadFrameCount(JDWP::ObjectId thread_id, size_t* result) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002405 ScopedObjectAccess soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002406 JDWP::JdwpError error;
2407 *result = 0;
2408 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002409 if (error != JDWP::ERR_NONE) {
2410 return error;
2411 }
Elliott Hughesf15f4a02013-01-09 10:09:38 -08002412 if (!IsSuspendedForDebugger(soa, thread)) {
2413 return JDWP::ERR_THREAD_NOT_SUSPENDED;
2414 }
Ian Rogersc0542af2014-09-03 16:16:56 -07002415 *result = GetStackDepth(thread);
Elliott Hughes221229c2013-01-08 18:17:50 -08002416 return JDWP::ERR_NONE;
Elliott Hughes86964332012-02-15 19:37:42 -08002417}
2418
Ian Rogers306057f2012-11-26 12:45:53 -08002419JDWP::JdwpError Dbg::GetThreadFrames(JDWP::ObjectId thread_id, size_t start_frame,
2420 size_t frame_count, JDWP::ExpandBuf* buf) {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002421 class GetFrameVisitor : public StackVisitor {
2422 public:
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002423 GetFrameVisitor(Thread* thread, size_t start_frame_in, size_t frame_count_in,
2424 JDWP::ExpandBuf* buf_in)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002425 REQUIRES_SHARED(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01002426 : StackVisitor(thread, nullptr, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
2427 depth_(0),
2428 start_frame_(start_frame_in),
2429 frame_count_(frame_count_in),
2430 buf_(buf_in) {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002431 expandBufAdd4BE(buf_, frame_count_);
Elliott Hughes03181a82011-11-17 17:22:21 -08002432 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002433
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002434 bool VisitFrame() OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002435 if (GetMethod()->IsRuntimeMethod()) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07002436 return true; // The debugger can't do anything useful with a frame that has no Method*.
Elliott Hughes03181a82011-11-17 17:22:21 -08002437 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002438 if (depth_ >= start_frame_ + frame_count_) {
Elliott Hughes530fa002012-03-12 11:44:49 -07002439 return false;
Elliott Hughes03181a82011-11-17 17:22:21 -08002440 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002441 if (depth_ >= start_frame_) {
2442 JDWP::FrameId frame_id(GetFrameId());
2443 JDWP::JdwpLocation location;
Sebastien Hertz6995c602014-09-09 12:10:13 +02002444 SetJdwpLocation(&location, GetMethod(), GetDexPc());
Ian Rogersef7d42f2014-01-06 12:55:46 -08002445 VLOG(jdwp) << StringPrintf(" Frame %3zd: id=%3" PRIu64 " ", depth_, frame_id) << location;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002446 expandBufAdd8BE(buf_, frame_id);
2447 expandBufAddLocation(buf_, location);
2448 }
2449 ++depth_;
Elliott Hughes530fa002012-03-12 11:44:49 -07002450 return true;
Elliott Hughes03181a82011-11-17 17:22:21 -08002451 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002452
2453 private:
2454 size_t depth_;
2455 const size_t start_frame_;
2456 const size_t frame_count_;
2457 JDWP::ExpandBuf* buf_;
Elliott Hughes03181a82011-11-17 17:22:21 -08002458 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002459
2460 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002461 JDWP::JdwpError error;
2462 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002463 if (error != JDWP::ERR_NONE) {
2464 return error;
2465 }
Elliott Hughesf15f4a02013-01-09 10:09:38 -08002466 if (!IsSuspendedForDebugger(soa, thread)) {
2467 return JDWP::ERR_THREAD_NOT_SUSPENDED;
2468 }
Ian Rogers7a22fa62013-01-23 12:16:16 -08002469 GetFrameVisitor visitor(thread, start_frame, frame_count, buf);
Ian Rogers0399dde2012-06-06 17:09:28 -07002470 visitor.WalkStack();
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002471 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002472}
2473
2474JDWP::ObjectId Dbg::GetThreadSelfId() {
Sebastien Hertz6995c602014-09-09 12:10:13 +02002475 return GetThreadId(Thread::Current());
2476}
2477
2478JDWP::ObjectId Dbg::GetThreadId(Thread* thread) {
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07002479 ScopedObjectAccessUnchecked soa(Thread::Current());
Nicolas Geoffraycafa0812017-02-15 18:27:34 +00002480 return gRegistry->Add(thread->GetPeerFromOtherThread());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002481}
2482
Elliott Hughes475fc232011-10-25 15:00:35 -07002483void Dbg::SuspendVM() {
Hiroshi Yamauchi8f95cf32016-04-19 11:14:06 -07002484 // Avoid a deadlock between GC and debugger where GC gets suspended during GC. b/25800335.
2485 gc::ScopedGCCriticalSection gcs(Thread::Current(),
2486 gc::kGcCauseDebugger,
2487 gc::kCollectorTypeDebugger);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002488 Runtime::Current()->GetThreadList()->SuspendAllForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002489}
2490
2491void Dbg::ResumeVM() {
Sebastien Hertz253fa552014-10-14 17:27:15 +02002492 Runtime::Current()->GetThreadList()->ResumeAllForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002493}
2494
Elliott Hughes221229c2013-01-08 18:17:50 -08002495JDWP::JdwpError Dbg::SuspendThread(JDWP::ObjectId thread_id, bool request_suspension) {
Ian Rogersf3d874c2014-07-17 18:52:42 -07002496 Thread* self = Thread::Current();
Ian Rogersc0542af2014-09-03 16:16:56 -07002497 ScopedLocalRef<jobject> peer(self->GetJniEnv(), nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002498 {
Ian Rogersf3d874c2014-07-17 18:52:42 -07002499 ScopedObjectAccess soa(self);
Ian Rogersc0542af2014-09-03 16:16:56 -07002500 JDWP::JdwpError error;
2501 peer.reset(soa.AddLocalReference<jobject>(gRegistry->Get<mirror::Object*>(thread_id, &error)));
Elliott Hughes4e235312011-12-02 11:34:15 -08002502 }
Ian Rogersc0542af2014-09-03 16:16:56 -07002503 if (peer.get() == nullptr) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002504 return JDWP::ERR_THREAD_NOT_ALIVE;
2505 }
Ian Rogers4ad5cd32014-11-11 23:08:07 -08002506 // Suspend thread to build stack trace.
Elliott Hughesf327e072013-01-09 16:01:26 -08002507 bool timed_out;
Brian Carlstromba32de42014-08-27 23:43:46 -07002508 ThreadList* thread_list = Runtime::Current()->GetThreadList();
Sebastien Hertzcdd798d2017-04-18 18:28:51 +02002509 Thread* thread = thread_list->SuspendThreadByPeer(peer.get(),
2510 request_suspension,
Alex Light46f93402017-06-29 11:59:50 -07002511 SuspendReason::kForDebugger,
Brian Carlstromba32de42014-08-27 23:43:46 -07002512 &timed_out);
Ian Rogersc0542af2014-09-03 16:16:56 -07002513 if (thread != nullptr) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002514 return JDWP::ERR_NONE;
Elliott Hughesf327e072013-01-09 16:01:26 -08002515 } else if (timed_out) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002516 return JDWP::ERR_INTERNAL;
2517 } else {
2518 return JDWP::ERR_THREAD_NOT_ALIVE;
2519 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002520}
2521
Elliott Hughes221229c2013-01-08 18:17:50 -08002522void Dbg::ResumeThread(JDWP::ObjectId thread_id) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002523 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002524 JDWP::JdwpError error;
2525 mirror::Object* peer = gRegistry->Get<mirror::Object*>(thread_id, &error);
2526 CHECK(peer != nullptr) << error;
jeffhaoa77f0f62012-12-05 17:19:31 -08002527 Thread* thread;
2528 {
2529 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
2530 thread = Thread::FromManagedThread(soa, peer);
2531 }
Ian Rogersc0542af2014-09-03 16:16:56 -07002532 if (thread == nullptr) {
Elliott Hughes4e235312011-12-02 11:34:15 -08002533 LOG(WARNING) << "No such thread for resume: " << peer;
2534 return;
2535 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002536 bool needs_resume;
2537 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002538 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Sebastien Hertz70d60272017-04-14 14:18:36 +02002539 needs_resume = thread->GetDebugSuspendCount() > 0;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002540 }
2541 if (needs_resume) {
Alex Light88fd7202017-06-30 08:31:59 -07002542 bool resumed = Runtime::Current()->GetThreadList()->Resume(thread, SuspendReason::kForDebugger);
2543 DCHECK(resumed);
Elliott Hughes546b9862012-06-20 16:06:13 -07002544 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002545}
2546
2547void Dbg::SuspendSelf() {
Elliott Hughes475fc232011-10-25 15:00:35 -07002548 Runtime::Current()->GetThreadList()->SuspendSelfForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002549}
2550
Ian Rogers0399dde2012-06-06 17:09:28 -07002551struct GetThisVisitor : public StackVisitor {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002552 GetThisVisitor(Thread* thread, Context* context, JDWP::FrameId frame_id_in)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002553 REQUIRES_SHARED(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01002554 : StackVisitor(thread, context, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
2555 this_object(nullptr),
2556 frame_id(frame_id_in) {}
Ian Rogers0399dde2012-06-06 17:09:28 -07002557
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002558 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2559 // annotalysis.
2560 virtual bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002561 if (frame_id != GetFrameId()) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002562 return true; // continue
Ian Rogers0399dde2012-06-06 17:09:28 -07002563 } else {
Ian Rogers62d6c772013-02-27 08:32:07 -08002564 this_object = GetThisObject();
2565 return false;
Ian Rogers0399dde2012-06-06 17:09:28 -07002566 }
Elliott Hughes86b00102011-12-05 17:54:26 -08002567 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002568
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002569 mirror::Object* this_object;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002570 JDWP::FrameId frame_id;
Ian Rogers0399dde2012-06-06 17:09:28 -07002571};
2572
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002573JDWP::JdwpError Dbg::GetThisObject(JDWP::ObjectId thread_id, JDWP::FrameId frame_id,
2574 JDWP::ObjectId* result) {
2575 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz69206392015-04-07 15:54:25 +02002576 JDWP::JdwpError error;
2577 Thread* thread = DecodeThread(soa, thread_id, &error);
2578 if (error != JDWP::ERR_NONE) {
2579 return error;
2580 }
2581 if (!IsSuspendedForDebugger(soa, thread)) {
2582 return JDWP::ERR_THREAD_NOT_SUSPENDED;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002583 }
Ian Rogers700a4022014-05-19 16:49:03 -07002584 std::unique_ptr<Context> context(Context::Create());
Ian Rogers7a22fa62013-01-23 12:16:16 -08002585 GetThisVisitor visitor(thread, context.get(), frame_id);
Ian Rogers0399dde2012-06-06 17:09:28 -07002586 visitor.WalkStack();
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002587 *result = gRegistry->Add(visitor.this_object);
2588 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002589}
2590
Sebastien Hertz8009f392014-09-01 17:07:11 +02002591// Walks the stack until we find the frame with the given FrameId.
2592class FindFrameVisitor FINAL : public StackVisitor {
2593 public:
2594 FindFrameVisitor(Thread* thread, Context* context, JDWP::FrameId frame_id)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002595 REQUIRES_SHARED(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01002596 : StackVisitor(thread, context, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
2597 frame_id_(frame_id),
2598 error_(JDWP::ERR_INVALID_FRAMEID) {}
Ian Rogersca190662012-06-26 15:45:57 -07002599
Sebastien Hertz8009f392014-09-01 17:07:11 +02002600 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2601 // annotalysis.
2602 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
2603 if (GetFrameId() != frame_id_) {
2604 return true; // Not our frame, carry on.
Ian Rogers0399dde2012-06-06 17:09:28 -07002605 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07002606 ArtMethod* m = GetMethod();
Sebastien Hertz8009f392014-09-01 17:07:11 +02002607 if (m->IsNative()) {
2608 // We can't read/write local value from/into native method.
2609 error_ = JDWP::ERR_OPAQUE_FRAME;
2610 } else {
2611 // We found our frame.
2612 error_ = JDWP::ERR_NONE;
2613 }
2614 return false;
2615 }
2616
2617 JDWP::JdwpError GetError() const {
2618 return error_;
2619 }
2620
2621 private:
2622 const JDWP::FrameId frame_id_;
2623 JDWP::JdwpError error_;
Sebastien Hertz26f72862015-09-15 09:52:07 +02002624
2625 DISALLOW_COPY_AND_ASSIGN(FindFrameVisitor);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002626};
2627
2628JDWP::JdwpError Dbg::GetLocalValues(JDWP::Request* request, JDWP::ExpandBuf* pReply) {
2629 JDWP::ObjectId thread_id = request->ReadThreadId();
2630 JDWP::FrameId frame_id = request->ReadFrameId();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002631
2632 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz69206392015-04-07 15:54:25 +02002633 JDWP::JdwpError error;
2634 Thread* thread = DecodeThread(soa, thread_id, &error);
2635 if (error != JDWP::ERR_NONE) {
2636 return error;
2637 }
2638 if (!IsSuspendedForDebugger(soa, thread)) {
2639 return JDWP::ERR_THREAD_NOT_SUSPENDED;
Elliott Hughes221229c2013-01-08 18:17:50 -08002640 }
Sebastien Hertz8009f392014-09-01 17:07:11 +02002641 // Find the frame with the given frame_id.
Ian Rogers700a4022014-05-19 16:49:03 -07002642 std::unique_ptr<Context> context(Context::Create());
Sebastien Hertz8009f392014-09-01 17:07:11 +02002643 FindFrameVisitor visitor(thread, context.get(), frame_id);
Ian Rogers0399dde2012-06-06 17:09:28 -07002644 visitor.WalkStack();
Sebastien Hertz8009f392014-09-01 17:07:11 +02002645 if (visitor.GetError() != JDWP::ERR_NONE) {
2646 return visitor.GetError();
2647 }
2648
2649 // Read the values from visitor's context.
2650 int32_t slot_count = request->ReadSigned32("slot count");
2651 expandBufAdd4BE(pReply, slot_count); /* "int values" */
2652 for (int32_t i = 0; i < slot_count; ++i) {
2653 uint32_t slot = request->ReadUnsigned32("slot");
2654 JDWP::JdwpTag reqSigByte = request->ReadTag();
2655
2656 VLOG(jdwp) << " --> slot " << slot << " " << reqSigByte;
2657
2658 size_t width = Dbg::GetTagWidth(reqSigByte);
Sebastien Hertz7d955652014-10-22 10:57:10 +02002659 uint8_t* ptr = expandBufAddSpace(pReply, width + 1);
Sebastien Hertz69206392015-04-07 15:54:25 +02002660 error = Dbg::GetLocalValue(visitor, soa, slot, reqSigByte, ptr, width);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002661 if (error != JDWP::ERR_NONE) {
2662 return error;
2663 }
2664 }
2665 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002666}
2667
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002668constexpr JDWP::JdwpError kStackFrameLocalAccessError = JDWP::ERR_ABSENT_INFORMATION;
2669
2670static std::string GetStackContextAsString(const StackVisitor& visitor)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002671 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002672 return StringPrintf(" at DEX pc 0x%08x in method %s", visitor.GetDexPc(false),
David Sehr709b0702016-10-13 09:12:37 -07002673 ArtMethod::PrettyMethod(visitor.GetMethod()).c_str());
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002674}
2675
2676static JDWP::JdwpError FailGetLocalValue(const StackVisitor& visitor, uint16_t vreg,
2677 JDWP::JdwpTag tag)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002678 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002679 LOG(ERROR) << "Failed to read " << tag << " local from register v" << vreg
2680 << GetStackContextAsString(visitor);
2681 return kStackFrameLocalAccessError;
2682}
2683
Sebastien Hertz8009f392014-09-01 17:07:11 +02002684JDWP::JdwpError Dbg::GetLocalValue(const StackVisitor& visitor, ScopedObjectAccessUnchecked& soa,
2685 int slot, JDWP::JdwpTag tag, uint8_t* buf, size_t width) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002686 ArtMethod* m = visitor.GetMethod();
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002687 JDWP::JdwpError error = JDWP::ERR_NONE;
2688 uint16_t vreg = DemangleSlot(slot, m, &error);
2689 if (error != JDWP::ERR_NONE) {
2690 return error;
2691 }
Sebastien Hertz8009f392014-09-01 17:07:11 +02002692 // TODO: check that the tag is compatible with the actual type of the slot!
Sebastien Hertz8009f392014-09-01 17:07:11 +02002693 switch (tag) {
2694 case JDWP::JT_BOOLEAN: {
2695 CHECK_EQ(width, 1U);
2696 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002697 if (!visitor.GetVReg(m, vreg, kIntVReg, &intVal)) {
2698 return FailGetLocalValue(visitor, vreg, tag);
Ian Rogers0399dde2012-06-06 17:09:28 -07002699 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002700 VLOG(jdwp) << "get boolean local " << vreg << " = " << intVal;
2701 JDWP::Set1(buf + 1, intVal != 0);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002702 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002703 }
Sebastien Hertz8009f392014-09-01 17:07:11 +02002704 case JDWP::JT_BYTE: {
2705 CHECK_EQ(width, 1U);
2706 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002707 if (!visitor.GetVReg(m, vreg, kIntVReg, &intVal)) {
2708 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002709 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002710 VLOG(jdwp) << "get byte local " << vreg << " = " << intVal;
2711 JDWP::Set1(buf + 1, intVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002712 break;
2713 }
2714 case JDWP::JT_SHORT:
2715 case JDWP::JT_CHAR: {
2716 CHECK_EQ(width, 2U);
2717 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002718 if (!visitor.GetVReg(m, vreg, kIntVReg, &intVal)) {
2719 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002720 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002721 VLOG(jdwp) << "get short/char local " << vreg << " = " << intVal;
2722 JDWP::Set2BE(buf + 1, intVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002723 break;
2724 }
2725 case JDWP::JT_INT: {
2726 CHECK_EQ(width, 4U);
2727 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002728 if (!visitor.GetVReg(m, vreg, kIntVReg, &intVal)) {
2729 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002730 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002731 VLOG(jdwp) << "get int local " << vreg << " = " << intVal;
2732 JDWP::Set4BE(buf + 1, intVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002733 break;
2734 }
2735 case JDWP::JT_FLOAT: {
2736 CHECK_EQ(width, 4U);
2737 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002738 if (!visitor.GetVReg(m, vreg, kFloatVReg, &intVal)) {
2739 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002740 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002741 VLOG(jdwp) << "get float local " << vreg << " = " << intVal;
2742 JDWP::Set4BE(buf + 1, intVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002743 break;
2744 }
2745 case JDWP::JT_ARRAY:
2746 case JDWP::JT_CLASS_LOADER:
2747 case JDWP::JT_CLASS_OBJECT:
2748 case JDWP::JT_OBJECT:
2749 case JDWP::JT_STRING:
2750 case JDWP::JT_THREAD:
2751 case JDWP::JT_THREAD_GROUP: {
2752 CHECK_EQ(width, sizeof(JDWP::ObjectId));
2753 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002754 if (!visitor.GetVReg(m, vreg, kReferenceVReg, &intVal)) {
2755 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002756 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002757 mirror::Object* o = reinterpret_cast<mirror::Object*>(intVal);
2758 VLOG(jdwp) << "get " << tag << " object local " << vreg << " = " << o;
2759 if (!Runtime::Current()->GetHeap()->IsValidObjectAddress(o)) {
2760 LOG(FATAL) << StringPrintf("Found invalid object %#" PRIxPTR " in register v%u",
2761 reinterpret_cast<uintptr_t>(o), vreg)
2762 << GetStackContextAsString(visitor);
2763 UNREACHABLE();
2764 }
2765 tag = TagFromObject(soa, o);
2766 JDWP::SetObjectId(buf + 1, gRegistry->Add(o));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002767 break;
2768 }
2769 case JDWP::JT_DOUBLE: {
2770 CHECK_EQ(width, 8U);
2771 uint64_t longVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002772 if (!visitor.GetVRegPair(m, vreg, kDoubleLoVReg, kDoubleHiVReg, &longVal)) {
2773 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002774 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002775 VLOG(jdwp) << "get double local " << vreg << " = " << longVal;
2776 JDWP::Set8BE(buf + 1, longVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002777 break;
2778 }
2779 case JDWP::JT_LONG: {
2780 CHECK_EQ(width, 8U);
2781 uint64_t longVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002782 if (!visitor.GetVRegPair(m, vreg, kLongLoVReg, kLongHiVReg, &longVal)) {
2783 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002784 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002785 VLOG(jdwp) << "get long local " << vreg << " = " << longVal;
2786 JDWP::Set8BE(buf + 1, longVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002787 break;
2788 }
2789 default:
2790 LOG(FATAL) << "Unknown tag " << tag;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002791 UNREACHABLE();
Sebastien Hertz8009f392014-09-01 17:07:11 +02002792 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002793
Sebastien Hertz8009f392014-09-01 17:07:11 +02002794 // Prepend tag, which may have been updated.
2795 JDWP::Set1(buf, tag);
2796 return JDWP::ERR_NONE;
2797}
2798
2799JDWP::JdwpError Dbg::SetLocalValues(JDWP::Request* request) {
2800 JDWP::ObjectId thread_id = request->ReadThreadId();
2801 JDWP::FrameId frame_id = request->ReadFrameId();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002802
2803 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz69206392015-04-07 15:54:25 +02002804 JDWP::JdwpError error;
2805 Thread* thread = DecodeThread(soa, thread_id, &error);
2806 if (error != JDWP::ERR_NONE) {
2807 return error;
2808 }
2809 if (!IsSuspendedForDebugger(soa, thread)) {
2810 return JDWP::ERR_THREAD_NOT_SUSPENDED;
Elliott Hughes221229c2013-01-08 18:17:50 -08002811 }
Sebastien Hertz8009f392014-09-01 17:07:11 +02002812 // Find the frame with the given frame_id.
Ian Rogers700a4022014-05-19 16:49:03 -07002813 std::unique_ptr<Context> context(Context::Create());
Sebastien Hertz8009f392014-09-01 17:07:11 +02002814 FindFrameVisitor visitor(thread, context.get(), frame_id);
Ian Rogers0399dde2012-06-06 17:09:28 -07002815 visitor.WalkStack();
Sebastien Hertz8009f392014-09-01 17:07:11 +02002816 if (visitor.GetError() != JDWP::ERR_NONE) {
2817 return visitor.GetError();
2818 }
2819
2820 // Writes the values into visitor's context.
2821 int32_t slot_count = request->ReadSigned32("slot count");
2822 for (int32_t i = 0; i < slot_count; ++i) {
2823 uint32_t slot = request->ReadUnsigned32("slot");
2824 JDWP::JdwpTag sigByte = request->ReadTag();
2825 size_t width = Dbg::GetTagWidth(sigByte);
2826 uint64_t value = request->ReadValue(width);
2827
2828 VLOG(jdwp) << " --> slot " << slot << " " << sigByte << " " << value;
Mingyao Yang99170c62015-07-06 11:10:37 -07002829 error = Dbg::SetLocalValue(thread, visitor, slot, sigByte, value, width);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002830 if (error != JDWP::ERR_NONE) {
2831 return error;
2832 }
2833 }
2834 return JDWP::ERR_NONE;
2835}
2836
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002837template<typename T>
2838static JDWP::JdwpError FailSetLocalValue(const StackVisitor& visitor, uint16_t vreg,
2839 JDWP::JdwpTag tag, T value)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002840 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002841 LOG(ERROR) << "Failed to write " << tag << " local " << value
2842 << " (0x" << std::hex << value << ") into register v" << vreg
2843 << GetStackContextAsString(visitor);
2844 return kStackFrameLocalAccessError;
2845}
2846
Mingyao Yang99170c62015-07-06 11:10:37 -07002847JDWP::JdwpError Dbg::SetLocalValue(Thread* thread, StackVisitor& visitor, int slot,
2848 JDWP::JdwpTag tag, uint64_t value, size_t width) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002849 ArtMethod* m = visitor.GetMethod();
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002850 JDWP::JdwpError error = JDWP::ERR_NONE;
2851 uint16_t vreg = DemangleSlot(slot, m, &error);
2852 if (error != JDWP::ERR_NONE) {
2853 return error;
2854 }
Sebastien Hertz8009f392014-09-01 17:07:11 +02002855 // TODO: check that the tag is compatible with the actual type of the slot!
Sebastien Hertz8009f392014-09-01 17:07:11 +02002856 switch (tag) {
2857 case JDWP::JT_BOOLEAN:
2858 case JDWP::JT_BYTE:
2859 CHECK_EQ(width, 1U);
Mingyao Yang636b9252015-07-31 16:40:24 -07002860 if (!visitor.SetVReg(m, vreg, static_cast<uint32_t>(value), kIntVReg)) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002861 return FailSetLocalValue(visitor, vreg, tag, static_cast<uint32_t>(value));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002862 }
2863 break;
2864 case JDWP::JT_SHORT:
2865 case JDWP::JT_CHAR:
2866 CHECK_EQ(width, 2U);
Mingyao Yang636b9252015-07-31 16:40:24 -07002867 if (!visitor.SetVReg(m, vreg, static_cast<uint32_t>(value), kIntVReg)) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002868 return FailSetLocalValue(visitor, vreg, tag, static_cast<uint32_t>(value));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002869 }
2870 break;
2871 case JDWP::JT_INT:
2872 CHECK_EQ(width, 4U);
Mingyao Yang636b9252015-07-31 16:40:24 -07002873 if (!visitor.SetVReg(m, vreg, static_cast<uint32_t>(value), kIntVReg)) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002874 return FailSetLocalValue(visitor, vreg, tag, static_cast<uint32_t>(value));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002875 }
2876 break;
2877 case JDWP::JT_FLOAT:
2878 CHECK_EQ(width, 4U);
Mingyao Yang636b9252015-07-31 16:40:24 -07002879 if (!visitor.SetVReg(m, vreg, static_cast<uint32_t>(value), kFloatVReg)) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002880 return FailSetLocalValue(visitor, vreg, tag, static_cast<uint32_t>(value));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002881 }
2882 break;
2883 case JDWP::JT_ARRAY:
2884 case JDWP::JT_CLASS_LOADER:
2885 case JDWP::JT_CLASS_OBJECT:
2886 case JDWP::JT_OBJECT:
2887 case JDWP::JT_STRING:
2888 case JDWP::JT_THREAD:
2889 case JDWP::JT_THREAD_GROUP: {
2890 CHECK_EQ(width, sizeof(JDWP::ObjectId));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002891 mirror::Object* o = gRegistry->Get<mirror::Object*>(static_cast<JDWP::ObjectId>(value),
2892 &error);
2893 if (error != JDWP::ERR_NONE) {
2894 VLOG(jdwp) << tag << " object " << o << " is an invalid object";
2895 return JDWP::ERR_INVALID_OBJECT;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002896 }
Mingyao Yang636b9252015-07-31 16:40:24 -07002897 if (!visitor.SetVReg(m, vreg, static_cast<uint32_t>(reinterpret_cast<uintptr_t>(o)),
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002898 kReferenceVReg)) {
2899 return FailSetLocalValue(visitor, vreg, tag, reinterpret_cast<uintptr_t>(o));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002900 }
2901 break;
2902 }
2903 case JDWP::JT_DOUBLE: {
2904 CHECK_EQ(width, 8U);
Mingyao Yang636b9252015-07-31 16:40:24 -07002905 if (!visitor.SetVRegPair(m, vreg, value, kDoubleLoVReg, kDoubleHiVReg)) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002906 return FailSetLocalValue(visitor, vreg, tag, value);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002907 }
2908 break;
2909 }
2910 case JDWP::JT_LONG: {
2911 CHECK_EQ(width, 8U);
Mingyao Yang636b9252015-07-31 16:40:24 -07002912 if (!visitor.SetVRegPair(m, vreg, value, kLongLoVReg, kLongHiVReg)) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002913 return FailSetLocalValue(visitor, vreg, tag, value);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002914 }
2915 break;
2916 }
2917 default:
2918 LOG(FATAL) << "Unknown tag " << tag;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002919 UNREACHABLE();
Sebastien Hertz8009f392014-09-01 17:07:11 +02002920 }
Mingyao Yang99170c62015-07-06 11:10:37 -07002921
2922 // If we set the local variable in a compiled frame, we need to trigger a deoptimization of
2923 // the stack so we continue execution with the interpreter using the new value(s) of the updated
2924 // local variable(s). To achieve this, we install instrumentation exit stub on each method of the
2925 // thread's stack. The stub will cause the deoptimization to happen.
2926 if (!visitor.IsShadowFrame() && thread->HasDebuggerShadowFrames()) {
2927 Runtime::Current()->GetInstrumentation()->InstrumentThreadStack(thread);
2928 }
2929
Sebastien Hertz8009f392014-09-01 17:07:11 +02002930 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002931}
2932
Mathieu Chartiere401d142015-04-22 13:56:20 -07002933static void SetEventLocation(JDWP::EventLocation* location, ArtMethod* m, uint32_t dex_pc)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002934 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz6995c602014-09-09 12:10:13 +02002935 DCHECK(location != nullptr);
2936 if (m == nullptr) {
2937 memset(location, 0, sizeof(*location));
2938 } else {
Alex Light97e78032017-06-27 17:51:55 -07002939 location->method = m->GetCanonicalMethod(kRuntimePointerSize);
Sebastien Hertz6995c602014-09-09 12:10:13 +02002940 location->dex_pc = (m->IsNative() || m->IsProxyMethod()) ? static_cast<uint32_t>(-1) : dex_pc;
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002941 }
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002942}
2943
Mathieu Chartiere401d142015-04-22 13:56:20 -07002944void Dbg::PostLocationEvent(ArtMethod* m, int dex_pc, mirror::Object* this_object,
Jeff Hao579b0242013-11-18 13:16:49 -08002945 int event_flags, const JValue* return_value) {
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002946 if (!IsDebuggerActive()) {
2947 return;
2948 }
2949 DCHECK(m != nullptr);
2950 DCHECK_EQ(m->IsStatic(), this_object == nullptr);
Sebastien Hertz6995c602014-09-09 12:10:13 +02002951 JDWP::EventLocation location;
2952 SetEventLocation(&location, m, dex_pc);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002953
Sebastien Hertzde48aa62015-05-26 11:53:39 +02002954 // We need to be sure no exception is pending when calling JdwpState::PostLocationEvent.
2955 // This is required to be able to call JNI functions to create JDWP ids. To achieve this,
2956 // we temporarily clear the current thread's exception (if any) and will restore it after
2957 // the call.
2958 // Note: the only way to get a pending exception here is to suspend on a move-exception
2959 // instruction.
2960 Thread* const self = Thread::Current();
2961 StackHandleScope<1> hs(self);
2962 Handle<mirror::Throwable> pending_exception(hs.NewHandle(self->GetException()));
2963 self->ClearException();
Andreas Gampefa4333d2017-02-14 11:10:34 -08002964 if (kIsDebugBuild && pending_exception != nullptr) {
Sebastien Hertzde48aa62015-05-26 11:53:39 +02002965 const DexFile::CodeItem* code_item = location.method->GetCodeItem();
2966 const Instruction* instr = Instruction::At(&code_item->insns_[location.dex_pc]);
2967 CHECK_EQ(Instruction::MOVE_EXCEPTION, instr->Opcode());
2968 }
2969
Sebastien Hertz6995c602014-09-09 12:10:13 +02002970 gJdwpState->PostLocationEvent(&location, this_object, event_flags, return_value);
Sebastien Hertzde48aa62015-05-26 11:53:39 +02002971
Andreas Gampefa4333d2017-02-14 11:10:34 -08002972 if (pending_exception != nullptr) {
Sebastien Hertzde48aa62015-05-26 11:53:39 +02002973 self->SetException(pending_exception.Get());
2974 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002975}
2976
Mathieu Chartiere401d142015-04-22 13:56:20 -07002977void Dbg::PostFieldAccessEvent(ArtMethod* m, int dex_pc,
Mathieu Chartierc7853442015-03-27 14:35:38 -07002978 mirror::Object* this_object, ArtField* f) {
Alex Lighte00ec302017-06-16 08:56:43 -07002979 // TODO We should send events for native methods.
2980 if (!IsDebuggerActive() || m->IsNative()) {
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002981 return;
2982 }
2983 DCHECK(m != nullptr);
2984 DCHECK(f != nullptr);
Sebastien Hertz6995c602014-09-09 12:10:13 +02002985 JDWP::EventLocation location;
2986 SetEventLocation(&location, m, dex_pc);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002987
Sebastien Hertz6995c602014-09-09 12:10:13 +02002988 gJdwpState->PostFieldEvent(&location, f, this_object, nullptr, false);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002989}
2990
Mathieu Chartiere401d142015-04-22 13:56:20 -07002991void Dbg::PostFieldModificationEvent(ArtMethod* m, int dex_pc,
Mathieu Chartierc7853442015-03-27 14:35:38 -07002992 mirror::Object* this_object, ArtField* f,
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002993 const JValue* field_value) {
Alex Lighte00ec302017-06-16 08:56:43 -07002994 // TODO We should send events for native methods.
2995 if (!IsDebuggerActive() || m->IsNative()) {
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002996 return;
2997 }
2998 DCHECK(m != nullptr);
2999 DCHECK(f != nullptr);
3000 DCHECK(field_value != nullptr);
Sebastien Hertz6995c602014-09-09 12:10:13 +02003001 JDWP::EventLocation location;
3002 SetEventLocation(&location, m, dex_pc);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02003003
Sebastien Hertz6995c602014-09-09 12:10:13 +02003004 gJdwpState->PostFieldEvent(&location, f, this_object, field_value, true);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02003005}
3006
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003007/**
3008 * Finds the location where this exception will be caught. We search until we reach the top
3009 * frame, in which case this exception is considered uncaught.
3010 */
3011class CatchLocationFinder : public StackVisitor {
3012 public:
3013 CatchLocationFinder(Thread* self, const Handle<mirror::Throwable>& exception, Context* context)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003014 REQUIRES_SHARED(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01003015 : StackVisitor(self, context, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003016 exception_(exception),
3017 handle_scope_(self),
3018 this_at_throw_(handle_scope_.NewHandle<mirror::Object>(nullptr)),
Mathieu Chartiere401d142015-04-22 13:56:20 -07003019 catch_method_(nullptr),
3020 throw_method_(nullptr),
Andreas Gampee2abbc62017-09-15 11:59:26 -07003021 catch_dex_pc_(dex::kDexNoIndex),
3022 throw_dex_pc_(dex::kDexNoIndex) {
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003023 }
3024
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003025 bool VisitFrame() OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003026 ArtMethod* method = GetMethod();
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003027 DCHECK(method != nullptr);
3028 if (method->IsRuntimeMethod()) {
3029 // Ignore callee save method.
3030 DCHECK(method->IsCalleeSaveMethod());
3031 return true;
3032 }
3033
3034 uint32_t dex_pc = GetDexPc();
Mathieu Chartiere401d142015-04-22 13:56:20 -07003035 if (throw_method_ == nullptr) {
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003036 // First Java method found. It is either the method that threw the exception,
3037 // or the Java native method that is reporting an exception thrown by
3038 // native code.
3039 this_at_throw_.Assign(GetThisObject());
Mathieu Chartiere401d142015-04-22 13:56:20 -07003040 throw_method_ = method;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003041 throw_dex_pc_ = dex_pc;
3042 }
3043
Andreas Gampee2abbc62017-09-15 11:59:26 -07003044 if (dex_pc != dex::kDexNoIndex) {
Sebastien Hertz26f72862015-09-15 09:52:07 +02003045 StackHandleScope<1> hs(GetThread());
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003046 uint32_t found_dex_pc;
3047 Handle<mirror::Class> exception_class(hs.NewHandle(exception_->GetClass()));
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003048 bool unused_clear_exception;
Mathieu Chartiere401d142015-04-22 13:56:20 -07003049 found_dex_pc = method->FindCatchBlock(exception_class, dex_pc, &unused_clear_exception);
Andreas Gampee2abbc62017-09-15 11:59:26 -07003050 if (found_dex_pc != dex::kDexNoIndex) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003051 catch_method_ = method;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003052 catch_dex_pc_ = found_dex_pc;
3053 return false; // End stack walk.
3054 }
3055 }
3056 return true; // Continue stack walk.
3057 }
3058
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003059 ArtMethod* GetCatchMethod() REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003060 return catch_method_;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003061 }
3062
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003063 ArtMethod* GetThrowMethod() REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003064 return throw_method_;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003065 }
3066
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003067 mirror::Object* GetThisAtThrow() REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003068 return this_at_throw_.Get();
3069 }
3070
3071 uint32_t GetCatchDexPc() const {
3072 return catch_dex_pc_;
3073 }
3074
3075 uint32_t GetThrowDexPc() const {
3076 return throw_dex_pc_;
3077 }
3078
3079 private:
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003080 const Handle<mirror::Throwable>& exception_;
Mathieu Chartiere401d142015-04-22 13:56:20 -07003081 StackHandleScope<1> handle_scope_;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003082 MutableHandle<mirror::Object> this_at_throw_;
Mathieu Chartiere401d142015-04-22 13:56:20 -07003083 ArtMethod* catch_method_;
3084 ArtMethod* throw_method_;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003085 uint32_t catch_dex_pc_;
3086 uint32_t throw_dex_pc_;
3087
3088 DISALLOW_COPY_AND_ASSIGN(CatchLocationFinder);
3089};
3090
3091void Dbg::PostException(mirror::Throwable* exception_object) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07003092 if (!IsDebuggerActive()) {
Ian Rogers0ad5bb82011-12-07 10:16:32 -08003093 return;
3094 }
Sebastien Hertz261bc042015-04-08 09:36:07 +02003095 Thread* const self = Thread::Current();
3096 StackHandleScope<1> handle_scope(self);
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003097 Handle<mirror::Throwable> h_exception(handle_scope.NewHandle(exception_object));
3098 std::unique_ptr<Context> context(Context::Create());
Sebastien Hertz261bc042015-04-08 09:36:07 +02003099 CatchLocationFinder clf(self, h_exception, context.get());
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003100 clf.WalkStack(/* include_transitions */ false);
Sebastien Hertz6995c602014-09-09 12:10:13 +02003101 JDWP::EventLocation exception_throw_location;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003102 SetEventLocation(&exception_throw_location, clf.GetThrowMethod(), clf.GetThrowDexPc());
Sebastien Hertz6995c602014-09-09 12:10:13 +02003103 JDWP::EventLocation exception_catch_location;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003104 SetEventLocation(&exception_catch_location, clf.GetCatchMethod(), clf.GetCatchDexPc());
Elliott Hughes4740cdf2011-12-07 14:07:12 -08003105
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003106 gJdwpState->PostException(&exception_throw_location, h_exception.Get(), &exception_catch_location,
3107 clf.GetThisAtThrow());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003108}
3109
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003110void Dbg::PostClassPrepare(mirror::Class* c) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07003111 if (!IsDebuggerActive()) {
Elliott Hughes4740cdf2011-12-07 14:07:12 -08003112 return;
3113 }
Sebastien Hertz6995c602014-09-09 12:10:13 +02003114 gJdwpState->PostClassPrepare(c);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003115}
3116
Ian Rogers62d6c772013-02-27 08:32:07 -08003117void Dbg::UpdateDebugger(Thread* thread, mirror::Object* this_object,
Mathieu Chartiere401d142015-04-22 13:56:20 -07003118 ArtMethod* m, uint32_t dex_pc,
Sebastien Hertz8379b222014-02-24 17:38:15 +01003119 int event_flags, const JValue* return_value) {
Ian Rogers62d6c772013-02-27 08:32:07 -08003120 if (!IsDebuggerActive() || dex_pc == static_cast<uint32_t>(-2) /* fake method exit */) {
Elliott Hughes2aa2e392012-02-17 17:15:43 -08003121 return;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003122 }
3123
Elliott Hughes86964332012-02-15 19:37:42 -08003124 if (IsBreakpoint(m, dex_pc)) {
3125 event_flags |= kBreakpoint;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003126 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003127
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003128 // If the debugger is single-stepping one of our threads, check to
3129 // see if we're that thread and we've reached a step point.
3130 const SingleStepControl* single_step_control = thread->GetSingleStepControl();
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003131 if (single_step_control != nullptr) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003132 CHECK(!m->IsNative());
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003133 if (single_step_control->GetStepDepth() == JDWP::SD_INTO) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003134 // Step into method calls. We break when the line number
3135 // or method pointer changes. If we're in SS_MIN mode, we
3136 // always stop.
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003137 if (single_step_control->GetMethod() != m) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003138 event_flags |= kSingleStep;
3139 VLOG(jdwp) << "SS new method";
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003140 } else if (single_step_control->GetStepSize() == JDWP::SS_MIN) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003141 event_flags |= kSingleStep;
3142 VLOG(jdwp) << "SS new instruction";
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003143 } else if (single_step_control->ContainsDexPc(dex_pc)) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003144 event_flags |= kSingleStep;
3145 VLOG(jdwp) << "SS new line";
3146 }
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003147 } else if (single_step_control->GetStepDepth() == JDWP::SD_OVER) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003148 // Step over method calls. We break when the line number is
3149 // different and the frame depth is <= the original frame
3150 // depth. (We can't just compare on the method, because we
3151 // might get unrolled past it by an exception, and it's tricky
3152 // to identify recursion.)
3153
3154 int stack_depth = GetStackDepth(thread);
3155
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003156 if (stack_depth < single_step_control->GetStackDepth()) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003157 // Popped up one or more frames, always trigger.
3158 event_flags |= kSingleStep;
3159 VLOG(jdwp) << "SS method pop";
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003160 } else if (stack_depth == single_step_control->GetStackDepth()) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003161 // Same depth, see if we moved.
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003162 if (single_step_control->GetStepSize() == JDWP::SS_MIN) {
Elliott Hughes86964332012-02-15 19:37:42 -08003163 event_flags |= kSingleStep;
3164 VLOG(jdwp) << "SS new instruction";
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003165 } else if (single_step_control->ContainsDexPc(dex_pc)) {
Elliott Hughes2435a572012-02-17 16:07:41 -08003166 event_flags |= kSingleStep;
3167 VLOG(jdwp) << "SS new line";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003168 }
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003169 }
3170 } else {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003171 CHECK_EQ(single_step_control->GetStepDepth(), JDWP::SD_OUT);
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003172 // Return from the current method. We break when the frame
3173 // depth pops up.
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003174
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003175 // This differs from the "method exit" break in that it stops
3176 // with the PC at the next instruction in the returned-to
3177 // function, rather than the end of the returning function.
Elliott Hughes86964332012-02-15 19:37:42 -08003178
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003179 int stack_depth = GetStackDepth(thread);
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003180 if (stack_depth < single_step_control->GetStackDepth()) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003181 event_flags |= kSingleStep;
3182 VLOG(jdwp) << "SS method pop";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003183 }
3184 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003185 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003186
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003187 // If there's something interesting going on, see if it matches one
3188 // of the debugger filters.
3189 if (event_flags != 0) {
Sebastien Hertz8379b222014-02-24 17:38:15 +01003190 Dbg::PostLocationEvent(m, dex_pc, this_object, event_flags, return_value);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003191 }
3192}
3193
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003194size_t* Dbg::GetReferenceCounterForEvent(uint32_t instrumentation_event) {
3195 switch (instrumentation_event) {
3196 case instrumentation::Instrumentation::kMethodEntered:
3197 return &method_enter_event_ref_count_;
3198 case instrumentation::Instrumentation::kMethodExited:
3199 return &method_exit_event_ref_count_;
3200 case instrumentation::Instrumentation::kDexPcMoved:
3201 return &dex_pc_change_event_ref_count_;
3202 case instrumentation::Instrumentation::kFieldRead:
3203 return &field_read_event_ref_count_;
3204 case instrumentation::Instrumentation::kFieldWritten:
3205 return &field_write_event_ref_count_;
Alex Light6e1607e2017-08-23 10:06:18 -07003206 case instrumentation::Instrumentation::kExceptionThrown:
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003207 return &exception_catch_event_ref_count_;
3208 default:
3209 return nullptr;
3210 }
3211}
3212
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003213// Process request while all mutator threads are suspended.
3214void Dbg::ProcessDeoptimizationRequest(const DeoptimizationRequest& request) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003215 instrumentation::Instrumentation* instrumentation = Runtime::Current()->GetInstrumentation();
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003216 switch (request.GetKind()) {
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003217 case DeoptimizationRequest::kNothing:
3218 LOG(WARNING) << "Ignoring empty deoptimization request.";
3219 break;
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003220 case DeoptimizationRequest::kRegisterForEvent:
3221 VLOG(jdwp) << StringPrintf("Add debugger as listener for instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003222 request.InstrumentationEvent());
3223 instrumentation->AddListener(&gDebugInstrumentationListener, request.InstrumentationEvent());
3224 instrumentation_events_ |= request.InstrumentationEvent();
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003225 break;
3226 case DeoptimizationRequest::kUnregisterForEvent:
3227 VLOG(jdwp) << StringPrintf("Remove debugger as listener for instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003228 request.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003229 instrumentation->RemoveListener(&gDebugInstrumentationListener,
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003230 request.InstrumentationEvent());
3231 instrumentation_events_ &= ~request.InstrumentationEvent();
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003232 break;
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003233 case DeoptimizationRequest::kFullDeoptimization:
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003234 VLOG(jdwp) << "Deoptimize the world ...";
Sebastien Hertz0462c4c2015-04-01 16:34:17 +02003235 instrumentation->DeoptimizeEverything(kDbgInstrumentationKey);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003236 VLOG(jdwp) << "Deoptimize the world DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003237 break;
3238 case DeoptimizationRequest::kFullUndeoptimization:
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003239 VLOG(jdwp) << "Undeoptimize the world ...";
Sebastien Hertz0462c4c2015-04-01 16:34:17 +02003240 instrumentation->UndeoptimizeEverything(kDbgInstrumentationKey);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003241 VLOG(jdwp) << "Undeoptimize the world DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003242 break;
3243 case DeoptimizationRequest::kSelectiveDeoptimization:
David Sehr709b0702016-10-13 09:12:37 -07003244 VLOG(jdwp) << "Deoptimize method " << ArtMethod::PrettyMethod(request.Method()) << " ...";
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003245 instrumentation->Deoptimize(request.Method());
David Sehr709b0702016-10-13 09:12:37 -07003246 VLOG(jdwp) << "Deoptimize method " << ArtMethod::PrettyMethod(request.Method()) << " DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003247 break;
3248 case DeoptimizationRequest::kSelectiveUndeoptimization:
David Sehr709b0702016-10-13 09:12:37 -07003249 VLOG(jdwp) << "Undeoptimize method " << ArtMethod::PrettyMethod(request.Method()) << " ...";
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003250 instrumentation->Undeoptimize(request.Method());
David Sehr709b0702016-10-13 09:12:37 -07003251 VLOG(jdwp) << "Undeoptimize method " << ArtMethod::PrettyMethod(request.Method()) << " DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003252 break;
3253 default:
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003254 LOG(FATAL) << "Unsupported deoptimization request kind " << request.GetKind();
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003255 break;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003256 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003257}
3258
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003259void Dbg::RequestDeoptimization(const DeoptimizationRequest& req) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003260 if (req.GetKind() == DeoptimizationRequest::kNothing) {
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003261 // Nothing to do.
3262 return;
3263 }
Brian Carlstrom306db812014-09-05 13:01:41 -07003264 MutexLock mu(Thread::Current(), *Locks::deoptimization_lock_);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003265 RequestDeoptimizationLocked(req);
3266}
3267
3268void Dbg::RequestDeoptimizationLocked(const DeoptimizationRequest& req) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003269 switch (req.GetKind()) {
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003270 case DeoptimizationRequest::kRegisterForEvent: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003271 DCHECK_NE(req.InstrumentationEvent(), 0u);
3272 size_t* counter = GetReferenceCounterForEvent(req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003273 CHECK(counter != nullptr) << StringPrintf("No counter for instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003274 req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003275 if (*counter == 0) {
Sebastien Hertz7d2ae432014-05-15 11:26:34 +02003276 VLOG(jdwp) << StringPrintf("Queue request #%zd to start listening to instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003277 deoptimization_requests_.size(), req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003278 deoptimization_requests_.push_back(req);
3279 }
3280 *counter = *counter + 1;
3281 break;
3282 }
3283 case DeoptimizationRequest::kUnregisterForEvent: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003284 DCHECK_NE(req.InstrumentationEvent(), 0u);
3285 size_t* counter = GetReferenceCounterForEvent(req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003286 CHECK(counter != nullptr) << StringPrintf("No counter for instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003287 req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003288 *counter = *counter - 1;
3289 if (*counter == 0) {
Sebastien Hertz7d2ae432014-05-15 11:26:34 +02003290 VLOG(jdwp) << StringPrintf("Queue request #%zd to stop 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 break;
3295 }
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003296 case DeoptimizationRequest::kFullDeoptimization: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003297 DCHECK(req.Method() == nullptr);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003298 if (full_deoptimization_event_count_ == 0) {
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003299 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
3300 << " for full deoptimization";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003301 deoptimization_requests_.push_back(req);
3302 }
3303 ++full_deoptimization_event_count_;
3304 break;
3305 }
3306 case DeoptimizationRequest::kFullUndeoptimization: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003307 DCHECK(req.Method() == nullptr);
Sebastien Hertze713d932014-05-15 10:48:53 +02003308 DCHECK_GT(full_deoptimization_event_count_, 0U);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003309 --full_deoptimization_event_count_;
3310 if (full_deoptimization_event_count_ == 0) {
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003311 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
3312 << " for full undeoptimization";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003313 deoptimization_requests_.push_back(req);
3314 }
3315 break;
3316 }
3317 case DeoptimizationRequest::kSelectiveDeoptimization: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003318 DCHECK(req.Method() != nullptr);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003319 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
David Sehr709b0702016-10-13 09:12:37 -07003320 << " for deoptimization of " << req.Method()->PrettyMethod();
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003321 deoptimization_requests_.push_back(req);
3322 break;
3323 }
3324 case DeoptimizationRequest::kSelectiveUndeoptimization: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003325 DCHECK(req.Method() != nullptr);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003326 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
David Sehr709b0702016-10-13 09:12:37 -07003327 << " for undeoptimization of " << req.Method()->PrettyMethod();
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003328 deoptimization_requests_.push_back(req);
3329 break;
3330 }
3331 default: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003332 LOG(FATAL) << "Unknown deoptimization request kind " << req.GetKind();
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003333 break;
3334 }
3335 }
3336}
3337
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003338void Dbg::ManageDeoptimization() {
3339 Thread* const self = Thread::Current();
3340 {
3341 // Avoid suspend/resume if there is no pending request.
Brian Carlstrom306db812014-09-05 13:01:41 -07003342 MutexLock mu(self, *Locks::deoptimization_lock_);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003343 if (deoptimization_requests_.empty()) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003344 return;
3345 }
3346 }
3347 CHECK_EQ(self->GetState(), kRunnable);
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07003348 ScopedThreadSuspension sts(self, kWaitingForDeoptimization);
Mathieu Chartieraa516822015-10-02 15:53:37 -07003349 // Required for ProcessDeoptimizationRequest.
3350 gc::ScopedGCCriticalSection gcs(self,
3351 gc::kGcCauseInstrumentation,
3352 gc::kCollectorTypeInstrumentation);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003353 // We need to suspend mutator threads first.
Mathieu Chartier4f55e222015-09-04 13:26:21 -07003354 ScopedSuspendAll ssa(__FUNCTION__);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003355 const ThreadState old_state = self->SetStateUnsafe(kRunnable);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003356 {
Brian Carlstrom306db812014-09-05 13:01:41 -07003357 MutexLock mu(self, *Locks::deoptimization_lock_);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003358 size_t req_index = 0;
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003359 for (DeoptimizationRequest& request : deoptimization_requests_) {
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003360 VLOG(jdwp) << "Process deoptimization request #" << req_index++;
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003361 ProcessDeoptimizationRequest(request);
3362 }
3363 deoptimization_requests_.clear();
3364 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003365 CHECK_EQ(self->SetStateUnsafe(old_state), kRunnable);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003366}
3367
Mathieu Chartiere401d142015-04-22 13:56:20 -07003368static const Breakpoint* FindFirstBreakpointForMethod(ArtMethod* m)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003369 REQUIRES_SHARED(Locks::mutator_lock_, Locks::breakpoint_lock_) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003370 for (Breakpoint& breakpoint : gBreakpoints) {
Alex Light6c8467f2015-11-20 15:03:26 -08003371 if (breakpoint.IsInMethod(m)) {
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003372 return &breakpoint;
3373 }
3374 }
3375 return nullptr;
3376}
3377
Mathieu Chartiere401d142015-04-22 13:56:20 -07003378bool Dbg::MethodHasAnyBreakpoints(ArtMethod* method) {
Mathieu Chartierd8565452015-03-26 09:41:50 -07003379 ReaderMutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
3380 return FindFirstBreakpointForMethod(method) != nullptr;
3381}
3382
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003383// Sanity checks all existing breakpoints on the same method.
Mathieu Chartiere401d142015-04-22 13:56:20 -07003384static void SanityCheckExistingBreakpoints(ArtMethod* m,
Sebastien Hertzf3928792014-11-17 19:00:37 +01003385 DeoptimizationRequest::Kind deoptimization_kind)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003386 REQUIRES_SHARED(Locks::mutator_lock_, Locks::breakpoint_lock_) {
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003387 for (const Breakpoint& breakpoint : gBreakpoints) {
Alex Light6c8467f2015-11-20 15:03:26 -08003388 if (breakpoint.IsInMethod(m)) {
Sebastien Hertzf3928792014-11-17 19:00:37 +01003389 CHECK_EQ(deoptimization_kind, breakpoint.GetDeoptimizationKind());
3390 }
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003391 }
Sebastien Hertzf3928792014-11-17 19:00:37 +01003392 instrumentation::Instrumentation* instrumentation = Runtime::Current()->GetInstrumentation();
3393 if (deoptimization_kind == DeoptimizationRequest::kFullDeoptimization) {
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003394 // We should have deoptimized everything but not "selectively" deoptimized this method.
Sebastien Hertzf3928792014-11-17 19:00:37 +01003395 CHECK(instrumentation->AreAllMethodsDeoptimized());
3396 CHECK(!instrumentation->IsDeoptimized(m));
3397 } else if (deoptimization_kind == DeoptimizationRequest::kSelectiveDeoptimization) {
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003398 // We should have "selectively" deoptimized this method.
3399 // Note: while we have not deoptimized everything for this method, we may have done it for
3400 // another event.
Sebastien Hertzf3928792014-11-17 19:00:37 +01003401 CHECK(instrumentation->IsDeoptimized(m));
3402 } else {
3403 // This method does not require deoptimization.
3404 CHECK_EQ(deoptimization_kind, DeoptimizationRequest::kNothing);
3405 CHECK(!instrumentation->IsDeoptimized(m));
3406 }
3407}
3408
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003409// Returns the deoptimization kind required to set a breakpoint in a method.
3410// If a breakpoint has already been set, we also return the first breakpoint
3411// through the given 'existing_brkpt' pointer.
Sebastien Hertzf3928792014-11-17 19:00:37 +01003412static DeoptimizationRequest::Kind GetRequiredDeoptimizationKind(Thread* self,
Mathieu Chartiere401d142015-04-22 13:56:20 -07003413 ArtMethod* m,
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003414 const Breakpoint** existing_brkpt)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003415 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertzf3928792014-11-17 19:00:37 +01003416 if (!Dbg::RequiresDeoptimization()) {
3417 // We already run in interpreter-only mode so we don't need to deoptimize anything.
3418 VLOG(jdwp) << "No need for deoptimization when fully running with interpreter for method "
David Sehr709b0702016-10-13 09:12:37 -07003419 << ArtMethod::PrettyMethod(m);
Sebastien Hertzf3928792014-11-17 19:00:37 +01003420 return DeoptimizationRequest::kNothing;
3421 }
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003422 const Breakpoint* first_breakpoint;
Sebastien Hertzf3928792014-11-17 19:00:37 +01003423 {
3424 ReaderMutexLock mu(self, *Locks::breakpoint_lock_);
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003425 first_breakpoint = FindFirstBreakpointForMethod(m);
3426 *existing_brkpt = first_breakpoint;
Sebastien Hertzf3928792014-11-17 19:00:37 +01003427 }
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003428
3429 if (first_breakpoint == nullptr) {
Nicolas Geoffray6300fd72016-03-18 09:40:17 +00003430 // There is no breakpoint on this method yet: we need to deoptimize. If this method is default,
3431 // we deoptimize everything; otherwise we deoptimize only this method. We
Alex Light6c8467f2015-11-20 15:03:26 -08003432 // deoptimize with defaults because we do not know everywhere they are used. It is possible some
Nicolas Geoffray6300fd72016-03-18 09:40:17 +00003433 // of the copies could be missed.
Alex Light6c8467f2015-11-20 15:03:26 -08003434 // TODO Deoptimizing on default methods might not be necessary in all cases.
Nicolas Geoffray6300fd72016-03-18 09:40:17 +00003435 bool need_full_deoptimization = m->IsDefault();
Sebastien Hertzf3928792014-11-17 19:00:37 +01003436 if (need_full_deoptimization) {
Nicolas Geoffray6300fd72016-03-18 09:40:17 +00003437 VLOG(jdwp) << "Need full deoptimization because of copying of method "
David Sehr709b0702016-10-13 09:12:37 -07003438 << ArtMethod::PrettyMethod(m);
Sebastien Hertzf3928792014-11-17 19:00:37 +01003439 return DeoptimizationRequest::kFullDeoptimization;
3440 } else {
3441 // We don't need to deoptimize if the method has not been compiled.
Nicolas Geoffraya5891e82015-11-06 14:18:27 +00003442 const bool is_compiled = m->HasAnyCompiledCode();
Sebastien Hertzf3928792014-11-17 19:00:37 +01003443 if (is_compiled) {
David Sehr709b0702016-10-13 09:12:37 -07003444 VLOG(jdwp) << "Need selective deoptimization for compiled method "
3445 << ArtMethod::PrettyMethod(m);
Nicolas Geoffray6300fd72016-03-18 09:40:17 +00003446 return DeoptimizationRequest::kSelectiveDeoptimization;
Sebastien Hertzf3928792014-11-17 19:00:37 +01003447 } else {
3448 // Method is not compiled: we don't need to deoptimize.
David Sehr709b0702016-10-13 09:12:37 -07003449 VLOG(jdwp) << "No need for deoptimization for non-compiled method "
3450 << ArtMethod::PrettyMethod(m);
Sebastien Hertzf3928792014-11-17 19:00:37 +01003451 return DeoptimizationRequest::kNothing;
3452 }
3453 }
3454 } else {
3455 // There is at least one breakpoint for this method: we don't need to deoptimize.
3456 // Let's check that all breakpoints are configured the same way for deoptimization.
3457 VLOG(jdwp) << "Breakpoint already set: no deoptimization is required";
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003458 DeoptimizationRequest::Kind deoptimization_kind = first_breakpoint->GetDeoptimizationKind();
Sebastien Hertzf3928792014-11-17 19:00:37 +01003459 if (kIsDebugBuild) {
3460 ReaderMutexLock mu(self, *Locks::breakpoint_lock_);
3461 SanityCheckExistingBreakpoints(m, deoptimization_kind);
3462 }
3463 return DeoptimizationRequest::kNothing;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003464 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003465}
3466
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003467// Installs a breakpoint at the specified location. Also indicates through the deoptimization
3468// request if we need to deoptimize.
3469void Dbg::WatchLocation(const JDWP::JdwpLocation* location, DeoptimizationRequest* req) {
3470 Thread* const self = Thread::Current();
Mathieu Chartiere401d142015-04-22 13:56:20 -07003471 ArtMethod* m = FromMethodId(location->method_id);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003472 DCHECK(m != nullptr) << "No method for method id " << location->method_id;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003473
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003474 const Breakpoint* existing_breakpoint = nullptr;
3475 const DeoptimizationRequest::Kind deoptimization_kind =
3476 GetRequiredDeoptimizationKind(self, m, &existing_breakpoint);
Sebastien Hertzf3928792014-11-17 19:00:37 +01003477 req->SetKind(deoptimization_kind);
3478 if (deoptimization_kind == DeoptimizationRequest::kSelectiveDeoptimization) {
3479 req->SetMethod(m);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003480 } else {
Sebastien Hertzf3928792014-11-17 19:00:37 +01003481 CHECK(deoptimization_kind == DeoptimizationRequest::kNothing ||
3482 deoptimization_kind == DeoptimizationRequest::kFullDeoptimization);
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003483 req->SetMethod(nullptr);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003484 }
3485
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003486 {
3487 WriterMutexLock mu(self, *Locks::breakpoint_lock_);
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003488 // If there is at least one existing breakpoint on the same method, the new breakpoint
3489 // must have the same deoptimization kind than the existing breakpoint(s).
3490 DeoptimizationRequest::Kind breakpoint_deoptimization_kind;
3491 if (existing_breakpoint != nullptr) {
3492 breakpoint_deoptimization_kind = existing_breakpoint->GetDeoptimizationKind();
3493 } else {
3494 breakpoint_deoptimization_kind = deoptimization_kind;
3495 }
3496 gBreakpoints.push_back(Breakpoint(m, location->dex_pc, breakpoint_deoptimization_kind));
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003497 VLOG(jdwp) << "Set breakpoint #" << (gBreakpoints.size() - 1) << ": "
3498 << gBreakpoints[gBreakpoints.size() - 1];
3499 }
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003500}
3501
3502// Uninstalls a breakpoint at the specified location. Also indicates through the deoptimization
3503// request if we need to undeoptimize.
3504void Dbg::UnwatchLocation(const JDWP::JdwpLocation* location, DeoptimizationRequest* req) {
Sebastien Hertzed2be172014-08-19 15:33:43 +02003505 WriterMutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003506 ArtMethod* m = FromMethodId(location->method_id);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003507 DCHECK(m != nullptr) << "No method for method id " << location->method_id;
Sebastien Hertzf3928792014-11-17 19:00:37 +01003508 DeoptimizationRequest::Kind deoptimization_kind = DeoptimizationRequest::kNothing;
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003509 for (size_t i = 0, e = gBreakpoints.size(); i < e; ++i) {
Alex Light6c8467f2015-11-20 15:03:26 -08003510 if (gBreakpoints[i].DexPc() == location->dex_pc && gBreakpoints[i].IsInMethod(m)) {
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003511 VLOG(jdwp) << "Removed breakpoint #" << i << ": " << gBreakpoints[i];
Sebastien Hertzf3928792014-11-17 19:00:37 +01003512 deoptimization_kind = gBreakpoints[i].GetDeoptimizationKind();
3513 DCHECK_EQ(deoptimization_kind == DeoptimizationRequest::kSelectiveDeoptimization,
3514 Runtime::Current()->GetInstrumentation()->IsDeoptimized(m));
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003515 gBreakpoints.erase(gBreakpoints.begin() + i);
3516 break;
3517 }
3518 }
3519 const Breakpoint* const existing_breakpoint = FindFirstBreakpointForMethod(m);
3520 if (existing_breakpoint == nullptr) {
3521 // There is no more breakpoint on this method: we need to undeoptimize.
Sebastien Hertzf3928792014-11-17 19:00:37 +01003522 if (deoptimization_kind == DeoptimizationRequest::kFullDeoptimization) {
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003523 // This method required full deoptimization: we need to undeoptimize everything.
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003524 req->SetKind(DeoptimizationRequest::kFullUndeoptimization);
3525 req->SetMethod(nullptr);
Sebastien Hertzf3928792014-11-17 19:00:37 +01003526 } else if (deoptimization_kind == DeoptimizationRequest::kSelectiveDeoptimization) {
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003527 // This method required selective deoptimization: we need to undeoptimize only that method.
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003528 req->SetKind(DeoptimizationRequest::kSelectiveUndeoptimization);
3529 req->SetMethod(m);
Sebastien Hertzf3928792014-11-17 19:00:37 +01003530 } else {
3531 // This method had no need for deoptimization: do nothing.
3532 CHECK_EQ(deoptimization_kind, DeoptimizationRequest::kNothing);
3533 req->SetKind(DeoptimizationRequest::kNothing);
3534 req->SetMethod(nullptr);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003535 }
3536 } else {
3537 // There is at least one breakpoint for this method: we don't need to undeoptimize.
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003538 req->SetKind(DeoptimizationRequest::kNothing);
3539 req->SetMethod(nullptr);
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003540 if (kIsDebugBuild) {
Sebastien Hertzf3928792014-11-17 19:00:37 +01003541 SanityCheckExistingBreakpoints(m, deoptimization_kind);
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003542 }
Elliott Hughes86964332012-02-15 19:37:42 -08003543 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003544}
3545
Mathieu Chartiere401d142015-04-22 13:56:20 -07003546bool Dbg::IsForcedInterpreterNeededForCallingImpl(Thread* thread, ArtMethod* m) {
Daniel Mihalyieb076692014-08-22 17:33:31 +02003547 const SingleStepControl* const ssc = thread->GetSingleStepControl();
3548 if (ssc == nullptr) {
3549 // If we are not single-stepping, then we don't have to force interpreter.
3550 return false;
3551 }
3552 if (Runtime::Current()->GetInstrumentation()->InterpretOnly()) {
3553 // If we are in interpreter only mode, then we don't have to force interpreter.
3554 return false;
3555 }
3556
3557 if (!m->IsNative() && !m->IsProxyMethod()) {
3558 // If we want to step into a method, then we have to force interpreter on that call.
3559 if (ssc->GetStepDepth() == JDWP::SD_INTO) {
3560 return true;
3561 }
3562 }
3563 return false;
3564}
3565
Mathieu Chartiere401d142015-04-22 13:56:20 -07003566bool Dbg::IsForcedInterpreterNeededForResolutionImpl(Thread* thread, ArtMethod* m) {
Daniel Mihalyieb076692014-08-22 17:33:31 +02003567 instrumentation::Instrumentation* const instrumentation =
3568 Runtime::Current()->GetInstrumentation();
3569 // If we are in interpreter only mode, then we don't have to force interpreter.
3570 if (instrumentation->InterpretOnly()) {
3571 return false;
3572 }
3573 // We can only interpret pure Java method.
3574 if (m->IsNative() || m->IsProxyMethod()) {
3575 return false;
3576 }
3577 const SingleStepControl* const ssc = thread->GetSingleStepControl();
3578 if (ssc != nullptr) {
3579 // If we want to step into a method, then we have to force interpreter on that call.
3580 if (ssc->GetStepDepth() == JDWP::SD_INTO) {
3581 return true;
3582 }
3583 // If we are stepping out from a static initializer, by issuing a step
3584 // in or step over, that was implicitly invoked by calling a static method,
3585 // then we need to step into that method. Having a lower stack depth than
3586 // the one the single step control has indicates that the step originates
3587 // from the static initializer.
3588 if (ssc->GetStepDepth() != JDWP::SD_OUT &&
3589 ssc->GetStackDepth() > GetStackDepth(thread)) {
3590 return true;
3591 }
3592 }
3593 // There are cases where we have to force interpreter on deoptimized methods,
3594 // because in some cases the call will not be performed by invoking an entry
3595 // point that has been replaced by the deoptimization, but instead by directly
3596 // invoking the compiled code of the method, for example.
3597 return instrumentation->IsDeoptimized(m);
3598}
3599
Mathieu Chartiere401d142015-04-22 13:56:20 -07003600bool Dbg::IsForcedInstrumentationNeededForResolutionImpl(Thread* thread, ArtMethod* m) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07003601 // The upcall can be null and in that case we don't need to do anything.
Daniel Mihalyieb076692014-08-22 17:33:31 +02003602 if (m == nullptr) {
3603 return false;
3604 }
3605 instrumentation::Instrumentation* const instrumentation =
3606 Runtime::Current()->GetInstrumentation();
3607 // If we are in interpreter only mode, then we don't have to force interpreter.
3608 if (instrumentation->InterpretOnly()) {
3609 return false;
3610 }
3611 // We can only interpret pure Java method.
3612 if (m->IsNative() || m->IsProxyMethod()) {
3613 return false;
3614 }
3615 const SingleStepControl* const ssc = thread->GetSingleStepControl();
3616 if (ssc != nullptr) {
3617 // If we are stepping out from a static initializer, by issuing a step
3618 // out, that was implicitly invoked by calling a static method, then we
3619 // need to step into the caller of that method. Having a lower stack
3620 // depth than the one the single step control has indicates that the
3621 // step originates from the static initializer.
3622 if (ssc->GetStepDepth() == JDWP::SD_OUT &&
3623 ssc->GetStackDepth() > GetStackDepth(thread)) {
3624 return true;
3625 }
3626 }
3627 // If we are returning from a static intializer, that was implicitly
3628 // invoked by calling a static method and the caller is deoptimized,
3629 // then we have to deoptimize the stack without forcing interpreter
3630 // on the static method that was called originally. This problem can
3631 // be solved easily by forcing instrumentation on the called method,
3632 // because the instrumentation exit hook will recognise the need of
3633 // stack deoptimization by calling IsForcedInterpreterNeededForUpcall.
3634 return instrumentation->IsDeoptimized(m);
3635}
3636
Mathieu Chartiere401d142015-04-22 13:56:20 -07003637bool Dbg::IsForcedInterpreterNeededForUpcallImpl(Thread* thread, ArtMethod* m) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07003638 // The upcall can be null and in that case we don't need to do anything.
Daniel Mihalyieb076692014-08-22 17:33:31 +02003639 if (m == nullptr) {
3640 return false;
3641 }
3642 instrumentation::Instrumentation* const instrumentation =
3643 Runtime::Current()->GetInstrumentation();
3644 // If we are in interpreter only mode, then we don't have to force interpreter.
3645 if (instrumentation->InterpretOnly()) {
3646 return false;
3647 }
3648 // We can only interpret pure Java method.
3649 if (m->IsNative() || m->IsProxyMethod()) {
3650 return false;
3651 }
3652 const SingleStepControl* const ssc = thread->GetSingleStepControl();
3653 if (ssc != nullptr) {
3654 // The debugger is not interested in what is happening under the level
3655 // of the step, thus we only force interpreter when we are not below of
3656 // the step.
3657 if (ssc->GetStackDepth() >= GetStackDepth(thread)) {
3658 return true;
3659 }
3660 }
Mingyao Yang99170c62015-07-06 11:10:37 -07003661 if (thread->HasDebuggerShadowFrames()) {
3662 // We need to deoptimize the stack for the exception handling flow so that
3663 // we don't miss any deoptimization that should be done when there are
3664 // debugger shadow frames.
3665 return true;
3666 }
Daniel Mihalyieb076692014-08-22 17:33:31 +02003667 // We have to require stack deoptimization if the upcall is deoptimized.
3668 return instrumentation->IsDeoptimized(m);
3669}
3670
Mingyao Yang99170c62015-07-06 11:10:37 -07003671class NeedsDeoptimizationVisitor : public StackVisitor {
Sebastien Hertz520633b2015-09-08 17:03:36 +02003672 public:
3673 explicit NeedsDeoptimizationVisitor(Thread* self)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003674 REQUIRES_SHARED(Locks::mutator_lock_)
Sebastien Hertz520633b2015-09-08 17:03:36 +02003675 : StackVisitor(self, nullptr, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
3676 needs_deoptimization_(false) {}
3677
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003678 bool VisitFrame() OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz520633b2015-09-08 17:03:36 +02003679 // The visitor is meant to be used when handling exception from compiled code only.
David Sehr709b0702016-10-13 09:12:37 -07003680 CHECK(!IsShadowFrame()) << "We only expect to visit compiled frame: "
3681 << ArtMethod::PrettyMethod(GetMethod());
Sebastien Hertz520633b2015-09-08 17:03:36 +02003682 ArtMethod* method = GetMethod();
3683 if (method == nullptr) {
3684 // We reach an upcall and don't need to deoptimize this part of the stack (ManagedFragment)
3685 // so we can stop the visit.
3686 DCHECK(!needs_deoptimization_);
3687 return false;
3688 }
3689 if (Runtime::Current()->GetInstrumentation()->InterpretOnly()) {
3690 // We found a compiled frame in the stack but instrumentation is set to interpret
3691 // everything: we need to deoptimize.
3692 needs_deoptimization_ = true;
3693 return false;
3694 }
3695 if (Runtime::Current()->GetInstrumentation()->IsDeoptimized(method)) {
3696 // We found a deoptimized method in the stack.
3697 needs_deoptimization_ = true;
3698 return false;
3699 }
Mingyao Yang99170c62015-07-06 11:10:37 -07003700 ShadowFrame* frame = GetThread()->FindDebuggerShadowFrame(GetFrameId());
3701 if (frame != nullptr) {
3702 // The debugger allocated a ShadowFrame to update a variable in the stack: we need to
3703 // deoptimize the stack to execute (and deallocate) this frame.
3704 needs_deoptimization_ = true;
3705 return false;
3706 }
Sebastien Hertz520633b2015-09-08 17:03:36 +02003707 return true;
3708 }
3709
3710 bool NeedsDeoptimization() const {
3711 return needs_deoptimization_;
3712 }
3713
3714 private:
3715 // Do we need to deoptimize the stack?
3716 bool needs_deoptimization_;
3717
3718 DISALLOW_COPY_AND_ASSIGN(NeedsDeoptimizationVisitor);
3719};
3720
3721// Do we need to deoptimize the stack to handle an exception?
3722bool Dbg::IsForcedInterpreterNeededForExceptionImpl(Thread* thread) {
3723 const SingleStepControl* const ssc = thread->GetSingleStepControl();
3724 if (ssc != nullptr) {
3725 // We deopt to step into the catch handler.
3726 return true;
3727 }
3728 // Deoptimization is required if at least one method in the stack needs it. However we
3729 // skip frames that will be unwound (thus not executed).
3730 NeedsDeoptimizationVisitor visitor(thread);
3731 visitor.WalkStack(true); // includes upcall.
3732 return visitor.NeedsDeoptimization();
3733}
3734
Jeff Hao449db332013-04-12 18:30:52 -07003735// Scoped utility class to suspend a thread so that we may do tasks such as walk its stack. Doesn't
3736// cause suspension if the thread is the current thread.
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07003737class ScopedDebuggerThreadSuspension {
Jeff Hao449db332013-04-12 18:30:52 -07003738 public:
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07003739 ScopedDebuggerThreadSuspension(Thread* self, JDWP::ObjectId thread_id)
Mathieu Chartier90443472015-07-16 20:32:27 -07003740 REQUIRES(!Locks::thread_list_lock_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003741 REQUIRES_SHARED(Locks::mutator_lock_) :
Ian Rogersf3d874c2014-07-17 18:52:42 -07003742 thread_(nullptr),
Jeff Hao449db332013-04-12 18:30:52 -07003743 error_(JDWP::ERR_NONE),
3744 self_suspend_(false),
Ian Rogers33e95662013-05-20 20:29:14 -07003745 other_suspend_(false) {
Jeff Hao449db332013-04-12 18:30:52 -07003746 ScopedObjectAccessUnchecked soa(self);
Sebastien Hertz69206392015-04-07 15:54:25 +02003747 thread_ = DecodeThread(soa, thread_id, &error_);
Jeff Hao449db332013-04-12 18:30:52 -07003748 if (error_ == JDWP::ERR_NONE) {
3749 if (thread_ == soa.Self()) {
3750 self_suspend_ = true;
3751 } else {
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07003752 Thread* suspended_thread;
3753 {
3754 ScopedThreadSuspension sts(self, kWaitingForDebuggerSuspension);
3755 jobject thread_peer = Dbg::GetObjectRegistry()->GetJObject(thread_id);
3756 bool timed_out;
3757 ThreadList* const thread_list = Runtime::Current()->GetThreadList();
Sebastien Hertzcdd798d2017-04-18 18:28:51 +02003758 suspended_thread = thread_list->SuspendThreadByPeer(thread_peer,
3759 /* request_suspension */ true,
Alex Light46f93402017-06-29 11:59:50 -07003760 SuspendReason::kForDebugger,
Sebastien Hertzcdd798d2017-04-18 18:28:51 +02003761 &timed_out);
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07003762 }
Ian Rogersf3d874c2014-07-17 18:52:42 -07003763 if (suspended_thread == nullptr) {
Jeff Hao449db332013-04-12 18:30:52 -07003764 // Thread terminated from under us while suspending.
3765 error_ = JDWP::ERR_INVALID_THREAD;
3766 } else {
3767 CHECK_EQ(suspended_thread, thread_);
3768 other_suspend_ = true;
3769 }
3770 }
3771 }
Elliott Hughes2435a572012-02-17 16:07:41 -08003772 }
Elliott Hughes86964332012-02-15 19:37:42 -08003773
Jeff Hao449db332013-04-12 18:30:52 -07003774 Thread* GetThread() const {
3775 return thread_;
3776 }
3777
3778 JDWP::JdwpError GetError() const {
3779 return error_;
3780 }
3781
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07003782 ~ScopedDebuggerThreadSuspension() {
Jeff Hao449db332013-04-12 18:30:52 -07003783 if (other_suspend_) {
Alex Light88fd7202017-06-30 08:31:59 -07003784 bool resumed = Runtime::Current()->GetThreadList()->Resume(thread_,
3785 SuspendReason::kForDebugger);
3786 DCHECK(resumed);
Jeff Hao449db332013-04-12 18:30:52 -07003787 }
3788 }
3789
3790 private:
3791 Thread* thread_;
3792 JDWP::JdwpError error_;
3793 bool self_suspend_;
3794 bool other_suspend_;
3795};
3796
3797JDWP::JdwpError Dbg::ConfigureStep(JDWP::ObjectId thread_id, JDWP::JdwpStepSize step_size,
3798 JDWP::JdwpStepDepth step_depth) {
3799 Thread* self = Thread::Current();
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07003800 ScopedDebuggerThreadSuspension sts(self, thread_id);
Jeff Hao449db332013-04-12 18:30:52 -07003801 if (sts.GetError() != JDWP::ERR_NONE) {
3802 return sts.GetError();
3803 }
3804
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003805 // Work out what ArtMethod* we're in, the current line number, and how deep the stack currently
Elliott Hughes2435a572012-02-17 16:07:41 -08003806 // is for step-out.
Ian Rogers0399dde2012-06-06 17:09:28 -07003807 struct SingleStepStackVisitor : public StackVisitor {
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003808 explicit SingleStepStackVisitor(Thread* thread) REQUIRES_SHARED(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01003809 : StackVisitor(thread, nullptr, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
3810 stack_depth(0),
3811 method(nullptr),
3812 line_number(-1) {}
Ian Rogersca190662012-06-26 15:45:57 -07003813
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003814 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
3815 // annotalysis.
3816 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003817 ArtMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07003818 if (!m->IsRuntimeMethod()) {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003819 ++stack_depth;
3820 if (method == nullptr) {
Alex Light73376312017-04-06 10:10:51 -07003821 const DexFile* dex_file = m->GetDexFile();
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003822 method = m;
Alex Light73376312017-04-06 10:10:51 -07003823 if (dex_file != nullptr) {
David Sehr9323e6e2016-09-13 08:58:35 -07003824 line_number = annotations::GetLineNumFromPC(dex_file, m, GetDexPc());
Elliott Hughes2435a572012-02-17 16:07:41 -08003825 }
Elliott Hughes86964332012-02-15 19:37:42 -08003826 }
3827 }
Elliott Hughes530fa002012-03-12 11:44:49 -07003828 return true;
Elliott Hughes86964332012-02-15 19:37:42 -08003829 }
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003830
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003831 int stack_depth;
Mathieu Chartiere401d142015-04-22 13:56:20 -07003832 ArtMethod* method;
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003833 int32_t line_number;
Elliott Hughes86964332012-02-15 19:37:42 -08003834 };
Jeff Hao449db332013-04-12 18:30:52 -07003835
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003836 Thread* const thread = sts.GetThread();
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003837 SingleStepStackVisitor visitor(thread);
Ian Rogers0399dde2012-06-06 17:09:28 -07003838 visitor.WalkStack();
Elliott Hughes86964332012-02-15 19:37:42 -08003839
Elliott Hughes2435a572012-02-17 16:07:41 -08003840 // Find the dex_pc values that correspond to the current line, for line-based single-stepping.
Elliott Hughes2435a572012-02-17 16:07:41 -08003841 struct DebugCallbackContext {
Roland Levillain3887c462015-08-12 18:15:42 +01003842 DebugCallbackContext(SingleStepControl* single_step_control_cb,
Mathieu Chartier31f4c9f2017-12-08 15:46:11 -08003843 int32_t line_number_cb, uint32_t num_insns_in_code_units)
Roland Levillain3887c462015-08-12 18:15:42 +01003844 : single_step_control_(single_step_control_cb), line_number_(line_number_cb),
Mathieu Chartier31f4c9f2017-12-08 15:46:11 -08003845 num_insns_in_code_units_(num_insns_in_code_units), last_pc_valid(false), last_pc(0) {
Elliott Hughes2435a572012-02-17 16:07:41 -08003846 }
3847
David Srbeckyb06e28e2015-12-10 13:15:00 +00003848 static bool Callback(void* raw_context, const DexFile::PositionInfo& entry) {
Elliott Hughes2435a572012-02-17 16:07:41 -08003849 DebugCallbackContext* context = reinterpret_cast<DebugCallbackContext*>(raw_context);
David Srbeckyb06e28e2015-12-10 13:15:00 +00003850 if (static_cast<int32_t>(entry.line_) == context->line_number_) {
Elliott Hughes2435a572012-02-17 16:07:41 -08003851 if (!context->last_pc_valid) {
3852 // Everything from this address until the next line change is ours.
David Srbeckyb06e28e2015-12-10 13:15:00 +00003853 context->last_pc = entry.address_;
Elliott Hughes2435a572012-02-17 16:07:41 -08003854 context->last_pc_valid = true;
3855 }
3856 // Otherwise, if we're already in a valid range for this line,
3857 // just keep going (shouldn't really happen)...
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003858 } else if (context->last_pc_valid) { // and the line number is new
Elliott Hughes2435a572012-02-17 16:07:41 -08003859 // Add everything from the last entry up until here to the set
David Srbeckyb06e28e2015-12-10 13:15:00 +00003860 for (uint32_t dex_pc = context->last_pc; dex_pc < entry.address_; ++dex_pc) {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003861 context->single_step_control_->AddDexPc(dex_pc);
Elliott Hughes2435a572012-02-17 16:07:41 -08003862 }
3863 context->last_pc_valid = false;
3864 }
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003865 return false; // There may be multiple entries for any given line.
Elliott Hughes2435a572012-02-17 16:07:41 -08003866 }
3867
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003868 ~DebugCallbackContext() {
Elliott Hughes2435a572012-02-17 16:07:41 -08003869 // If the line number was the last in the position table...
3870 if (last_pc_valid) {
Mathieu Chartier31f4c9f2017-12-08 15:46:11 -08003871 for (uint32_t dex_pc = last_pc; dex_pc < num_insns_in_code_units_; ++dex_pc) {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003872 single_step_control_->AddDexPc(dex_pc);
Elliott Hughes2435a572012-02-17 16:07:41 -08003873 }
3874 }
3875 }
3876
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003877 SingleStepControl* const single_step_control_;
3878 const int32_t line_number_;
Mathieu Chartier31f4c9f2017-12-08 15:46:11 -08003879 const uint32_t num_insns_in_code_units_;
Elliott Hughes2435a572012-02-17 16:07:41 -08003880 bool last_pc_valid;
3881 uint32_t last_pc;
3882 };
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003883
3884 // Allocate single step.
Sebastien Hertz1558b572015-02-25 15:05:59 +01003885 SingleStepControl* single_step_control =
3886 new (std::nothrow) SingleStepControl(step_size, step_depth,
3887 visitor.stack_depth, visitor.method);
3888 if (single_step_control == nullptr) {
3889 LOG(ERROR) << "Failed to allocate SingleStepControl";
3890 return JDWP::ERR_OUT_OF_MEMORY;
3891 }
3892
Mathieu Chartiere401d142015-04-22 13:56:20 -07003893 ArtMethod* m = single_step_control->GetMethod();
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003894 const int32_t line_number = visitor.line_number;
Sebastien Hertz52f5f932015-05-28 11:00:57 +02003895 // Note: if the thread is not running Java code (pure native thread), there is no "current"
3896 // method on the stack (and no line number either).
3897 if (m != nullptr && !m->IsNative()) {
Mathieu Chartier31f4c9f2017-12-08 15:46:11 -08003898 CodeItemDebugInfoAccessor accessor(m);
3899 DebugCallbackContext context(single_step_control, line_number, accessor.InsnsSizeInCodeUnits());
3900 m->GetDexFile()->DecodeDebugPositionInfo(accessor.DebugInfoOffset(),
3901 DebugCallbackContext::Callback,
3902 &context);
Elliott Hughes3e2e1a22012-02-21 11:33:41 -08003903 }
Elliott Hughes2435a572012-02-17 16:07:41 -08003904
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003905 // Activate single-step in the thread.
3906 thread->ActivateSingleStepControl(single_step_control);
Elliott Hughes86964332012-02-15 19:37:42 -08003907
Elliott Hughes2435a572012-02-17 16:07:41 -08003908 if (VLOG_IS_ON(jdwp)) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003909 VLOG(jdwp) << "Single-step thread: " << *thread;
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003910 VLOG(jdwp) << "Single-step step size: " << single_step_control->GetStepSize();
3911 VLOG(jdwp) << "Single-step step depth: " << single_step_control->GetStepDepth();
David Sehr709b0702016-10-13 09:12:37 -07003912 VLOG(jdwp) << "Single-step current method: "
3913 << ArtMethod::PrettyMethod(single_step_control->GetMethod());
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003914 VLOG(jdwp) << "Single-step current line: " << line_number;
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003915 VLOG(jdwp) << "Single-step current stack depth: " << single_step_control->GetStackDepth();
Elliott Hughes2435a572012-02-17 16:07:41 -08003916 VLOG(jdwp) << "Single-step dex_pc values:";
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003917 for (uint32_t dex_pc : single_step_control->GetDexPcs()) {
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003918 VLOG(jdwp) << StringPrintf(" %#x", dex_pc);
Elliott Hughes2435a572012-02-17 16:07:41 -08003919 }
3920 }
3921
3922 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003923}
3924
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003925void Dbg::UnconfigureStep(JDWP::ObjectId thread_id) {
3926 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07003927 JDWP::JdwpError error;
3928 Thread* thread = DecodeThread(soa, thread_id, &error);
Sebastien Hertz87118ed2013-11-26 17:57:18 +01003929 if (error == JDWP::ERR_NONE) {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003930 thread->DeactivateSingleStepControl();
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003931 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003932}
3933
Elliott Hughes45651fd2012-02-21 15:48:20 -08003934static char JdwpTagToShortyChar(JDWP::JdwpTag tag) {
3935 switch (tag) {
3936 default:
3937 LOG(FATAL) << "unknown JDWP tag: " << PrintableChar(tag);
Ian Rogersfc787ec2014-10-09 21:56:44 -07003938 UNREACHABLE();
Elliott Hughes45651fd2012-02-21 15:48:20 -08003939
3940 // Primitives.
3941 case JDWP::JT_BYTE: return 'B';
3942 case JDWP::JT_CHAR: return 'C';
3943 case JDWP::JT_FLOAT: return 'F';
3944 case JDWP::JT_DOUBLE: return 'D';
3945 case JDWP::JT_INT: return 'I';
3946 case JDWP::JT_LONG: return 'J';
3947 case JDWP::JT_SHORT: return 'S';
3948 case JDWP::JT_VOID: return 'V';
3949 case JDWP::JT_BOOLEAN: return 'Z';
3950
3951 // Reference types.
3952 case JDWP::JT_ARRAY:
3953 case JDWP::JT_OBJECT:
3954 case JDWP::JT_STRING:
3955 case JDWP::JT_THREAD:
3956 case JDWP::JT_THREAD_GROUP:
3957 case JDWP::JT_CLASS_LOADER:
3958 case JDWP::JT_CLASS_OBJECT:
3959 return 'L';
3960 }
3961}
3962
Sebastien Hertzcbc50642015-06-01 17:33:12 +02003963JDWP::JdwpError Dbg::PrepareInvokeMethod(uint32_t request_id, JDWP::ObjectId thread_id,
3964 JDWP::ObjectId object_id, JDWP::RefTypeId class_id,
3965 JDWP::MethodId method_id, uint32_t arg_count,
3966 uint64_t arg_values[], JDWP::JdwpTag* arg_types,
3967 uint32_t options) {
3968 Thread* const self = Thread::Current();
3969 CHECK_EQ(self, GetDebugThread()) << "This must be called by the JDWP thread";
Sebastien Hertzd4032e42015-06-12 15:47:34 +02003970 const bool resume_all_threads = ((options & JDWP::INVOKE_SINGLE_THREADED) == 0);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003971
Sebastien Hertzcbc50642015-06-01 17:33:12 +02003972 ThreadList* thread_list = Runtime::Current()->GetThreadList();
Ian Rogersc0542af2014-09-03 16:16:56 -07003973 Thread* targetThread = nullptr;
Elliott Hughesd07986f2011-12-06 18:27:45 -08003974 {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003975 ScopedObjectAccessUnchecked soa(self);
Ian Rogersc0542af2014-09-03 16:16:56 -07003976 JDWP::JdwpError error;
3977 targetThread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08003978 if (error != JDWP::ERR_NONE) {
3979 LOG(ERROR) << "InvokeMethod request for invalid thread id " << thread_id;
3980 return error;
Elliott Hughesd07986f2011-12-06 18:27:45 -08003981 }
Sebastien Hertz1558b572015-02-25 15:05:59 +01003982 if (targetThread->GetInvokeReq() != nullptr) {
3983 // Thread is already invoking a method on behalf of the debugger.
3984 LOG(ERROR) << "InvokeMethod request for thread already invoking a method: " << *targetThread;
3985 return JDWP::ERR_ALREADY_INVOKING;
3986 }
3987 if (!targetThread->IsReadyForDebugInvoke()) {
3988 // Thread is not suspended by an event so it cannot invoke a method.
Elliott Hughesd07986f2011-12-06 18:27:45 -08003989 LOG(ERROR) << "InvokeMethod request for thread not stopped by event: " << *targetThread;
3990 return JDWP::ERR_INVALID_THREAD;
3991 }
3992
3993 /*
Sebastien Hertzd4032e42015-06-12 15:47:34 +02003994 * According to the JDWP specs, we are expected to resume all threads (or only the
3995 * target thread) once. So if a thread has been suspended more than once (either by
3996 * the debugger for an event or by the runtime for GC), it will remain suspended before
3997 * the invoke is executed. This means the debugger is responsible to properly resume all
3998 * the threads it has suspended so the target thread can execute the method.
Elliott Hughesd07986f2011-12-06 18:27:45 -08003999 *
Sebastien Hertzd4032e42015-06-12 15:47:34 +02004000 * However, for compatibility reason with older versions of debuggers (like Eclipse), we
4001 * fully resume all threads (by canceling *all* debugger suspensions) when the debugger
4002 * wants us to resume all threads. This is to avoid ending up in deadlock situation.
4003 *
4004 * On the other hand, if we are asked to only resume the target thread, then we follow the
4005 * JDWP specs by resuming that thread only once. This means the thread will remain suspended
4006 * if it has been suspended more than once before the invoke (and again, this is the
4007 * responsibility of the debugger to properly resume that thread before invoking a method).
Elliott Hughesd07986f2011-12-06 18:27:45 -08004008 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004009 int suspend_count;
4010 {
Ian Rogers50b35e22012-10-04 10:09:15 -07004011 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004012 suspend_count = targetThread->GetSuspendCount();
4013 }
Sebastien Hertzd4032e42015-06-12 15:47:34 +02004014 if (suspend_count > 1 && resume_all_threads) {
4015 // The target thread will remain suspended even after we resume it. Let's emit a warning
4016 // to indicate the invoke won't be executed until the thread is resumed.
4017 LOG(WARNING) << *targetThread << " suspended more than once (suspend count == "
4018 << suspend_count << "). This thread will invoke the method only once "
4019 << "it is fully resumed.";
Elliott Hughesd07986f2011-12-06 18:27:45 -08004020 }
4021
Ian Rogersc0542af2014-09-03 16:16:56 -07004022 mirror::Object* receiver = gRegistry->Get<mirror::Object*>(object_id, &error);
4023 if (error != JDWP::ERR_NONE) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08004024 return JDWP::ERR_INVALID_OBJECT;
4025 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08004026
Sebastien Hertz1558b572015-02-25 15:05:59 +01004027 gRegistry->Get<mirror::Object*>(thread_id, &error);
Ian Rogersc0542af2014-09-03 16:16:56 -07004028 if (error != JDWP::ERR_NONE) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08004029 return JDWP::ERR_INVALID_OBJECT;
4030 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08004031
Ian Rogersc0542af2014-09-03 16:16:56 -07004032 mirror::Class* c = DecodeClass(class_id, &error);
4033 if (c == nullptr) {
4034 return error;
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08004035 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08004036
Mathieu Chartiere401d142015-04-22 13:56:20 -07004037 ArtMethod* m = FromMethodId(method_id);
Ian Rogersc0542af2014-09-03 16:16:56 -07004038 if (m->IsStatic() != (receiver == nullptr)) {
Elliott Hughes45651fd2012-02-21 15:48:20 -08004039 return JDWP::ERR_INVALID_METHODID;
4040 }
4041 if (m->IsStatic()) {
4042 if (m->GetDeclaringClass() != c) {
4043 return JDWP::ERR_INVALID_METHODID;
4044 }
4045 } else {
4046 if (!m->GetDeclaringClass()->IsAssignableFrom(c)) {
4047 return JDWP::ERR_INVALID_METHODID;
4048 }
4049 }
4050
4051 // Check the argument list matches the method.
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004052 uint32_t shorty_len = 0;
4053 const char* shorty = m->GetShorty(&shorty_len);
4054 if (shorty_len - 1 != arg_count) {
Elliott Hughes45651fd2012-02-21 15:48:20 -08004055 return JDWP::ERR_ILLEGAL_ARGUMENT;
4056 }
Elliott Hughes09201632013-04-15 15:50:07 -07004057
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004058 {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004059 StackHandleScope<2> hs(soa.Self());
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004060 HandleWrapper<mirror::Object> h_obj(hs.NewHandleWrapper(&receiver));
4061 HandleWrapper<mirror::Class> h_klass(hs.NewHandleWrapper(&c));
4062 const DexFile::TypeList* types = m->GetParameterTypeList();
4063 for (size_t i = 0; i < arg_count; ++i) {
4064 if (shorty[i + 1] != JdwpTagToShortyChar(arg_types[i])) {
Elliott Hughes09201632013-04-15 15:50:07 -07004065 return JDWP::ERR_ILLEGAL_ARGUMENT;
4066 }
4067
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004068 if (shorty[i + 1] == 'L') {
4069 // Did we really get an argument of an appropriate reference type?
Vladimir Markob45528c2017-07-27 14:14:28 +01004070 ObjPtr<mirror::Class> parameter_type =
4071 m->ResolveClassFromTypeIndex(types->GetTypeItem(i).type_idx_);
Ian Rogersc0542af2014-09-03 16:16:56 -07004072 mirror::Object* argument = gRegistry->Get<mirror::Object*>(arg_values[i], &error);
4073 if (error != JDWP::ERR_NONE) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004074 return JDWP::ERR_INVALID_OBJECT;
4075 }
Ian Rogersc0542af2014-09-03 16:16:56 -07004076 if (argument != nullptr && !argument->InstanceOf(parameter_type)) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004077 return JDWP::ERR_ILLEGAL_ARGUMENT;
4078 }
4079
4080 // Turn the on-the-wire ObjectId into a jobject.
4081 jvalue& v = reinterpret_cast<jvalue&>(arg_values[i]);
4082 v.l = gRegistry->GetJObject(arg_values[i]);
4083 }
Elliott Hughes09201632013-04-15 15:50:07 -07004084 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08004085 }
4086
Sebastien Hertz1558b572015-02-25 15:05:59 +01004087 // Allocates a DebugInvokeReq.
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004088 DebugInvokeReq* req = new (std::nothrow) DebugInvokeReq(request_id, thread_id, receiver, c, m,
4089 options, arg_values, arg_count);
4090 if (req == nullptr) {
Sebastien Hertz1558b572015-02-25 15:05:59 +01004091 LOG(ERROR) << "Failed to allocate DebugInvokeReq";
4092 return JDWP::ERR_OUT_OF_MEMORY;
4093 }
4094
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004095 // Attaches the DebugInvokeReq to the target thread so it executes the method when
4096 // it is resumed. Once the invocation completes, the target thread will delete it before
4097 // suspending itself (see ThreadList::SuspendSelfForDebugger).
4098 targetThread->SetDebugInvokeReq(req);
Elliott Hughesd07986f2011-12-06 18:27:45 -08004099 }
4100
4101 // 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 +02004102 // away we're sitting high and dry -- but we must release this before the UndoDebuggerSuspensions
4103 // call.
Sebastien Hertzd4032e42015-06-12 15:47:34 +02004104 if (resume_all_threads) {
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004105 VLOG(jdwp) << " Resuming all threads";
4106 thread_list->UndoDebuggerSuspensions();
4107 } else {
4108 VLOG(jdwp) << " Resuming event thread only";
Alex Light88fd7202017-06-30 08:31:59 -07004109 bool resumed = thread_list->Resume(targetThread, SuspendReason::kForDebugger);
4110 DCHECK(resumed);
Elliott Hughesd07986f2011-12-06 18:27:45 -08004111 }
4112
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004113 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004114}
4115
4116void Dbg::ExecuteMethod(DebugInvokeReq* pReq) {
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004117 Thread* const self = Thread::Current();
4118 CHECK_NE(self, GetDebugThread()) << "This must be called by the event thread";
4119
4120 ScopedObjectAccess soa(self);
Elliott Hughesd07986f2011-12-06 18:27:45 -08004121
Elliott Hughes81ff3182012-03-23 20:35:56 -07004122 // We can be called while an exception is pending. We need
Elliott Hughesd07986f2011-12-06 18:27:45 -08004123 // to preserve that across the method invocation.
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004124 StackHandleScope<1> hs(soa.Self());
4125 Handle<mirror::Throwable> old_exception = hs.NewHandle(soa.Self()->GetException());
Sebastien Hertz1558b572015-02-25 15:05:59 +01004126 soa.Self()->ClearException();
Elliott Hughesd07986f2011-12-06 18:27:45 -08004127
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004128 // Execute the method then sends reply to the debugger.
4129 ExecuteMethodWithoutPendingException(soa, pReq);
4130
4131 // If an exception was pending before the invoke, restore it now.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004132 if (old_exception != nullptr) {
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004133 soa.Self()->SetException(old_exception.Get());
4134 }
4135}
4136
4137// Helper function: write a variable-width value into the output input buffer.
4138static void WriteValue(JDWP::ExpandBuf* pReply, int width, uint64_t value) {
4139 switch (width) {
4140 case 1:
4141 expandBufAdd1(pReply, value);
4142 break;
4143 case 2:
4144 expandBufAdd2BE(pReply, value);
4145 break;
4146 case 4:
4147 expandBufAdd4BE(pReply, value);
4148 break;
4149 case 8:
4150 expandBufAdd8BE(pReply, value);
4151 break;
4152 default:
4153 LOG(FATAL) << width;
4154 UNREACHABLE();
4155 }
4156}
4157
4158void Dbg::ExecuteMethodWithoutPendingException(ScopedObjectAccess& soa, DebugInvokeReq* pReq) {
4159 soa.Self()->AssertNoPendingException();
4160
Elliott Hughesd07986f2011-12-06 18:27:45 -08004161 // Translate the method through the vtable, unless the debugger wants to suppress it.
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004162 ArtMethod* m = pReq->method;
Andreas Gampe542451c2016-07-26 09:02:02 -07004163 PointerSize image_pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
Sebastien Hertz1558b572015-02-25 15:05:59 +01004164 if ((pReq->options & JDWP::INVOKE_NONVIRTUAL) == 0 && pReq->receiver.Read() != nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004165 ArtMethod* actual_method =
4166 pReq->klass.Read()->FindVirtualMethodForVirtualOrInterface(m, image_pointer_size);
4167 if (actual_method != m) {
David Sehr709b0702016-10-13 09:12:37 -07004168 VLOG(jdwp) << "ExecuteMethod translated " << ArtMethod::PrettyMethod(m)
4169 << " to " << ArtMethod::PrettyMethod(actual_method);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004170 m = actual_method;
Elliott Hughes45651fd2012-02-21 15:48:20 -08004171 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08004172 }
David Sehr709b0702016-10-13 09:12:37 -07004173 VLOG(jdwp) << "ExecuteMethod " << ArtMethod::PrettyMethod(m)
Sebastien Hertz1558b572015-02-25 15:05:59 +01004174 << " receiver=" << pReq->receiver.Read()
Sebastien Hertzd38667a2013-11-25 15:43:54 +01004175 << " arg_count=" << pReq->arg_count;
Mathieu Chartiere401d142015-04-22 13:56:20 -07004176 CHECK(m != nullptr);
Elliott Hughesd07986f2011-12-06 18:27:45 -08004177
Roland Levillain33d69032015-06-18 18:20:59 +01004178 static_assert(sizeof(jvalue) == sizeof(uint64_t), "jvalue and uint64_t have different sizes.");
Elliott Hughesd07986f2011-12-06 18:27:45 -08004179
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004180 // Invoke the method.
Jeff Hao39b6c242015-05-19 20:30:23 -07004181 ScopedLocalRef<jobject> ref(soa.Env(), soa.AddLocalReference<jobject>(pReq->receiver.Read()));
Andreas Gampe13b27842016-11-07 16:48:23 -08004182 JValue result = InvokeWithJValues(soa, ref.get(), jni::EncodeArtMethod(m),
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004183 reinterpret_cast<jvalue*>(pReq->arg_values.get()));
Elliott Hughesd07986f2011-12-06 18:27:45 -08004184
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004185 // Prepare JDWP ids for the reply.
4186 JDWP::JdwpTag result_tag = BasicTagFromDescriptor(m->GetShorty());
4187 const bool is_object_result = (result_tag == JDWP::JT_OBJECT);
Jeff Hao064d24e2016-08-25 03:52:40 +00004188 StackHandleScope<3> hs(soa.Self());
Sebastien Hertz1558b572015-02-25 15:05:59 +01004189 Handle<mirror::Object> object_result = hs.NewHandle(is_object_result ? result.GetL() : nullptr);
4190 Handle<mirror::Throwable> exception = hs.NewHandle(soa.Self()->GetException());
4191 soa.Self()->ClearException();
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004192
4193 if (!IsDebuggerActive()) {
4194 // The debugger detached: we must not re-suspend threads. We also don't need to fill the reply
4195 // because it won't be sent either.
4196 return;
4197 }
4198
4199 JDWP::ObjectId exceptionObjectId = gRegistry->Add(exception);
4200 uint64_t result_value = 0;
4201 if (exceptionObjectId != 0) {
Sebastien Hertz1558b572015-02-25 15:05:59 +01004202 VLOG(jdwp) << " JDWP invocation returning with exception=" << exception.Get()
4203 << " " << exception->Dump();
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004204 result_value = 0;
Sebastien Hertz1558b572015-02-25 15:05:59 +01004205 } else if (is_object_result) {
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004206 /* if no exception was thrown, examine object result more closely */
Sebastien Hertz1558b572015-02-25 15:05:59 +01004207 JDWP::JdwpTag new_tag = TagFromObject(soa, object_result.Get());
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004208 if (new_tag != result_tag) {
4209 VLOG(jdwp) << " JDWP promoted result from " << result_tag << " to " << new_tag;
4210 result_tag = new_tag;
Elliott Hughesd07986f2011-12-06 18:27:45 -08004211 }
4212
Sebastien Hertz1558b572015-02-25 15:05:59 +01004213 // Register the object in the registry and reference its ObjectId. This ensures
4214 // GC safety and prevents from accessing stale reference if the object is moved.
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004215 result_value = gRegistry->Add(object_result.Get());
Sebastien Hertz1558b572015-02-25 15:05:59 +01004216 } else {
4217 // Primitive result.
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004218 DCHECK(IsPrimitiveTag(result_tag));
4219 result_value = result.GetJ();
4220 }
4221 const bool is_constructor = m->IsConstructor() && !m->IsStatic();
4222 if (is_constructor) {
4223 // If we invoked a constructor (which actually returns void), return the receiver,
4224 // unless we threw, in which case we return null.
Sebastien Hertza3e13772015-11-05 12:09:44 +01004225 DCHECK_EQ(JDWP::JT_VOID, result_tag);
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004226 if (exceptionObjectId == 0) {
Jeff Hao064d24e2016-08-25 03:52:40 +00004227 if (m->GetDeclaringClass()->IsStringClass()) {
4228 // For string constructors, the new string is remapped to the receiver (stored in ref).
4229 Handle<mirror::Object> decoded_ref = hs.NewHandle(soa.Self()->DecodeJObject(ref.get()));
4230 result_value = gRegistry->Add(decoded_ref);
4231 result_tag = TagFromObject(soa, decoded_ref.Get());
4232 } else {
4233 // TODO we could keep the receiver ObjectId in the DebugInvokeReq to avoid looking into the
4234 // object registry.
4235 result_value = GetObjectRegistry()->Add(pReq->receiver.Read());
4236 result_tag = TagFromObject(soa, pReq->receiver.Read());
4237 }
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004238 } else {
4239 result_value = 0;
Sebastien Hertza3e13772015-11-05 12:09:44 +01004240 result_tag = JDWP::JT_OBJECT;
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004241 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08004242 }
4243
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004244 // Suspend other threads if the invoke is not single-threaded.
4245 if ((pReq->options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07004246 ScopedThreadSuspension sts(soa.Self(), kWaitingForDebuggerSuspension);
Hiroshi Yamauchi8f95cf32016-04-19 11:14:06 -07004247 // Avoid a deadlock between GC and debugger where GC gets suspended during GC. b/25800335.
4248 gc::ScopedGCCriticalSection gcs(soa.Self(), gc::kGcCauseDebugger, gc::kCollectorTypeDebugger);
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004249 VLOG(jdwp) << " Suspending all threads";
4250 Runtime::Current()->GetThreadList()->SuspendAllForDebugger();
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004251 }
4252
4253 VLOG(jdwp) << " --> returned " << result_tag
4254 << StringPrintf(" %#" PRIx64 " (except=%#" PRIx64 ")", result_value,
4255 exceptionObjectId);
4256
4257 // Show detailed debug output.
4258 if (result_tag == JDWP::JT_STRING && exceptionObjectId == 0) {
4259 if (result_value != 0) {
4260 if (VLOG_IS_ON(jdwp)) {
4261 std::string result_string;
4262 JDWP::JdwpError error = Dbg::StringToUtf8(result_value, &result_string);
4263 CHECK_EQ(error, JDWP::ERR_NONE);
4264 VLOG(jdwp) << " string '" << result_string << "'";
4265 }
4266 } else {
4267 VLOG(jdwp) << " string (null)";
4268 }
4269 }
4270
4271 // Attach the reply to DebugInvokeReq so it can be sent to the debugger when the event thread
4272 // is ready to suspend.
4273 BuildInvokeReply(pReq->reply, pReq->request_id, result_tag, result_value, exceptionObjectId);
4274}
4275
4276void Dbg::BuildInvokeReply(JDWP::ExpandBuf* pReply, uint32_t request_id, JDWP::JdwpTag result_tag,
4277 uint64_t result_value, JDWP::ObjectId exception) {
4278 // Make room for the JDWP header since we do not know the size of the reply yet.
4279 JDWP::expandBufAddSpace(pReply, kJDWPHeaderLen);
4280
4281 size_t width = GetTagWidth(result_tag);
4282 JDWP::expandBufAdd1(pReply, result_tag);
4283 if (width != 0) {
4284 WriteValue(pReply, width, result_value);
4285 }
4286 JDWP::expandBufAdd1(pReply, JDWP::JT_OBJECT);
4287 JDWP::expandBufAddObjectId(pReply, exception);
4288
4289 // Now we know the size, we can complete the JDWP header.
4290 uint8_t* buf = expandBufGetBuffer(pReply);
4291 JDWP::Set4BE(buf + kJDWPHeaderSizeOffset, expandBufGetLength(pReply));
4292 JDWP::Set4BE(buf + kJDWPHeaderIdOffset, request_id);
4293 JDWP::Set1(buf + kJDWPHeaderFlagsOffset, kJDWPFlagReply); // flags
4294 JDWP::Set2BE(buf + kJDWPHeaderErrorCodeOffset, JDWP::ERR_NONE);
4295}
4296
4297void Dbg::FinishInvokeMethod(DebugInvokeReq* pReq) {
4298 CHECK_NE(Thread::Current(), GetDebugThread()) << "This must be called by the event thread";
4299
4300 JDWP::ExpandBuf* const pReply = pReq->reply;
4301 CHECK(pReply != nullptr) << "No reply attached to DebugInvokeReq";
4302
4303 // We need to prevent other threads (including JDWP thread) from interacting with the debugger
4304 // while we send the reply but are not yet suspended. The JDWP token will be released just before
4305 // we suspend ourself again (see ThreadList::SuspendSelfForDebugger).
4306 gJdwpState->AcquireJdwpTokenForEvent(pReq->thread_id);
4307
4308 // Send the reply unless the debugger detached before the completion of the method.
4309 if (IsDebuggerActive()) {
4310 const size_t replyDataLength = expandBufGetLength(pReply) - kJDWPHeaderLen;
4311 VLOG(jdwp) << StringPrintf("REPLY INVOKE id=0x%06x (length=%zu)",
4312 pReq->request_id, replyDataLength);
4313
4314 gJdwpState->SendRequest(pReply);
4315 } else {
4316 VLOG(jdwp) << "Not sending invoke reply because debugger detached";
Elliott Hughesd07986f2011-12-06 18:27:45 -08004317 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004318}
4319
Alex Light8c2b9292017-11-09 13:21:01 -08004320bool Dbg::DdmHandleChunk(JNIEnv* env,
4321 uint32_t type,
4322 const ArrayRef<const jbyte>& data,
4323 /*out*/uint32_t* out_type,
4324 /*out*/std::vector<uint8_t>* out_data) {
4325 ScopedLocalRef<jbyteArray> dataArray(env, env->NewByteArray(data.size()));
Ian Rogersc0542af2014-09-03 16:16:56 -07004326 if (dataArray.get() == nullptr) {
Alex Light8c2b9292017-11-09 13:21:01 -08004327 LOG(WARNING) << "byte[] allocation failed: " << data.size();
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004328 env->ExceptionClear();
4329 return false;
4330 }
Alex Light8c2b9292017-11-09 13:21:01 -08004331 env->SetByteArrayRegion(dataArray.get(),
4332 0,
4333 data.size(),
4334 reinterpret_cast<const jbyte*>(data.data()));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004335 // Call "private static Chunk dispatch(int type, byte[] data, int offset, int length)".
Alex Light8c2b9292017-11-09 13:21:01 -08004336 ScopedLocalRef<jobject> chunk(
4337 env,
4338 env->CallStaticObjectMethod(
4339 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
4340 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_dispatch,
4341 type, dataArray.get(), 0, data.size()));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004342 if (env->ExceptionCheck()) {
4343 LOG(INFO) << StringPrintf("Exception thrown by dispatcher for 0x%08x", type);
4344 env->ExceptionDescribe();
4345 env->ExceptionClear();
4346 return false;
4347 }
4348
Ian Rogersc0542af2014-09-03 16:16:56 -07004349 if (chunk.get() == nullptr) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004350 return false;
4351 }
4352
4353 /*
4354 * Pull the pieces out of the chunk. We copy the results into a
4355 * newly-allocated buffer that the caller can free. We don't want to
4356 * continue using the Chunk object because nothing has a reference to it.
4357 *
4358 * We could avoid this by returning type/data/offset/length and having
4359 * the caller be aware of the object lifetime issues, but that
Elliott Hughes81ff3182012-03-23 20:35:56 -07004360 * integrates the JDWP code more tightly into the rest of the runtime, and doesn't work
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004361 * if we have responses for multiple chunks.
4362 *
4363 * So we're pretty much stuck with copying data around multiple times.
4364 */
Alex Light8c2b9292017-11-09 13:21:01 -08004365 ScopedLocalRef<jbyteArray> replyData(
4366 env,
4367 reinterpret_cast<jbyteArray>(
4368 env->GetObjectField(
4369 chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_data)));
4370 jint offset = env->GetIntField(chunk.get(),
4371 WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_offset);
4372 jint length = env->GetIntField(chunk.get(),
4373 WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_length);
4374 *out_type = env->GetIntField(chunk.get(),
4375 WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_type);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004376
Alex Light8c2b9292017-11-09 13:21:01 -08004377 VLOG(jdwp) << StringPrintf("DDM reply: type=0x%08x data=%p offset=%d length=%d",
4378 type,
4379 replyData.get(),
4380 offset,
4381 length);
Ian Rogersc0542af2014-09-03 16:16:56 -07004382 if (length == 0 || replyData.get() == nullptr) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004383 return false;
4384 }
4385
Alex Light8c2b9292017-11-09 13:21:01 -08004386 out_data->resize(length);
4387 env->GetByteArrayRegion(replyData.get(),
4388 offset,
4389 length,
4390 reinterpret_cast<jbyte*>(out_data->data()));
4391 return true;
4392}
4393
4394/*
4395 * "request" contains a full JDWP packet, possibly with multiple chunks. We
4396 * need to process each, accumulate the replies, and ship the whole thing
4397 * back.
4398 *
4399 * Returns "true" if we have a reply. The reply buffer is newly allocated,
4400 * and includes the chunk type/length, followed by the data.
4401 *
4402 * OLD-TODO: we currently assume that the request and reply include a single
4403 * chunk. If this becomes inconvenient we will need to adapt.
4404 */
4405bool Dbg::DdmHandlePacket(JDWP::Request* request, uint8_t** pReplyBuf, int* pReplyLen) {
4406 Thread* self = Thread::Current();
4407 JNIEnv* env = self->GetJniEnv();
4408
4409 uint32_t type = request->ReadUnsigned32("type");
4410 uint32_t length = request->ReadUnsigned32("length");
4411
4412 // Create a byte[] corresponding to 'request'.
4413 size_t request_length = request->size();
4414 // Run through and find all chunks. [Currently just find the first.]
4415 if (length != request_length) {
4416 LOG(WARNING) << StringPrintf("bad chunk found (len=%u pktLen=%zd)", length, request_length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004417 return false;
4418 }
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004419
Alex Light8c2b9292017-11-09 13:21:01 -08004420 ArrayRef<const jbyte> data(reinterpret_cast<const jbyte*>(request->data()), request_length);
4421 std::vector<uint8_t> out_data;
4422 uint32_t out_type = 0;
4423 request->Skip(request_length);
4424 if (!DdmHandleChunk(env, type, data, &out_type, &out_data)) {
4425 return false;
4426 }
4427 const uint32_t kDdmHeaderSize = 8;
4428 *pReplyLen = out_data.size() + kDdmHeaderSize;
4429 *pReplyBuf = new uint8_t[out_data.size() + kDdmHeaderSize];
4430 memcpy((*pReplyBuf) + kDdmHeaderSize, out_data.data(), out_data.size());
4431 JDWP::Set4BE(*pReplyBuf, out_type);
4432 JDWP::Set4BE((*pReplyBuf) + 4, static_cast<uint32_t>(out_data.size()));
4433 VLOG(jdwp)
4434 << StringPrintf("dvmHandleDdm returning type=%.4s", reinterpret_cast<char*>(*pReplyBuf))
4435 << "0x" << std::hex << reinterpret_cast<uintptr_t>(*pReplyBuf) << std::dec
4436 << " len= " << out_data.size();
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004437 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004438}
4439
Elliott Hughesa2155262011-11-16 16:26:58 -08004440void Dbg::DdmBroadcast(bool connect) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08004441 VLOG(jdwp) << "Broadcasting DDM " << (connect ? "connect" : "disconnect") << "...";
Elliott Hughes47fce012011-10-25 18:37:19 -07004442
4443 Thread* self = Thread::Current();
Ian Rogers50b35e22012-10-04 10:09:15 -07004444 if (self->GetState() != kRunnable) {
4445 LOG(ERROR) << "DDM broadcast in thread state " << self->GetState();
4446 /* try anyway? */
Elliott Hughes47fce012011-10-25 18:37:19 -07004447 }
4448
4449 JNIEnv* env = self->GetJniEnv();
Elliott Hughes47fce012011-10-25 18:37:19 -07004450 jint event = connect ? 1 /*DdmServer.CONNECTED*/ : 2 /*DdmServer.DISCONNECTED*/;
Elliott Hugheseac76672012-05-24 21:56:51 -07004451 env->CallStaticVoidMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
4452 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_broadcast,
4453 event);
Elliott Hughes47fce012011-10-25 18:37:19 -07004454 if (env->ExceptionCheck()) {
4455 LOG(ERROR) << "DdmServer.broadcast " << event << " failed";
4456 env->ExceptionDescribe();
4457 env->ExceptionClear();
4458 }
4459}
4460
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004461void Dbg::DdmConnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08004462 Dbg::DdmBroadcast(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004463}
4464
4465void Dbg::DdmDisconnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08004466 Dbg::DdmBroadcast(false);
Elliott Hughes47fce012011-10-25 18:37:19 -07004467 gDdmThreadNotification = false;
4468}
4469
4470/*
Elliott Hughes82188472011-11-07 18:11:48 -08004471 * Send a notification when a thread starts, stops, or changes its name.
Elliott Hughes47fce012011-10-25 18:37:19 -07004472 *
4473 * Because we broadcast the full set of threads when the notifications are
4474 * first enabled, it's possible for "thread" to be actively executing.
4475 */
Elliott Hughes82188472011-11-07 18:11:48 -08004476void Dbg::DdmSendThreadNotification(Thread* t, uint32_t type) {
Elliott Hughes47fce012011-10-25 18:37:19 -07004477 if (!gDdmThreadNotification) {
4478 return;
4479 }
4480
Alex Light772099a2017-11-21 14:05:04 -08004481 RuntimeCallbacks* cb = Runtime::Current()->GetRuntimeCallbacks();
Elliott Hughes82188472011-11-07 18:11:48 -08004482 if (type == CHUNK_TYPE("THDE")) {
Elliott Hughes47fce012011-10-25 18:37:19 -07004483 uint8_t buf[4];
Ian Rogersd9c4fc92013-10-01 19:45:43 -07004484 JDWP::Set4BE(&buf[0], t->GetThreadId());
Alex Light772099a2017-11-21 14:05:04 -08004485 cb->DdmPublishChunk(CHUNK_TYPE("THDE"), ArrayRef<const uint8_t>(buf));
Elliott Hughes82188472011-11-07 18:11:48 -08004486 } else {
4487 CHECK(type == CHUNK_TYPE("THCR") || type == CHUNK_TYPE("THNM")) << type;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004488 ScopedObjectAccessUnchecked soa(Thread::Current());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004489 StackHandleScope<1> hs(soa.Self());
Andreas Gampe08883de2016-11-08 13:20:52 -08004490 Handle<mirror::String> name(hs.NewHandle(t->GetThreadName()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004491 size_t char_count = (name != nullptr) ? name->GetLength() : 0;
4492 const jchar* chars = (name != nullptr) ? name->GetValue() : nullptr;
4493 bool is_compressed = (name != nullptr) ? name->IsCompressed() : false;
Elliott Hughes82188472011-11-07 18:11:48 -08004494
Elliott Hughes21f32d72011-11-09 17:44:13 -08004495 std::vector<uint8_t> bytes;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07004496 JDWP::Append4BE(bytes, t->GetThreadId());
jessicahandojo3aaa37b2016-07-29 14:46:37 -07004497 if (is_compressed) {
4498 const uint8_t* chars_compressed = name->GetValueCompressed();
4499 JDWP::AppendUtf16CompressedBE(bytes, chars_compressed, char_count);
4500 } else {
4501 JDWP::AppendUtf16BE(bytes, chars, char_count);
4502 }
Elliott Hughes21f32d72011-11-09 17:44:13 -08004503 CHECK_EQ(bytes.size(), char_count*2 + sizeof(uint32_t)*2);
Alex Light772099a2017-11-21 14:05:04 -08004504 cb->DdmPublishChunk(type, ArrayRef<const uint8_t>(bytes));
Elliott Hughes47fce012011-10-25 18:37:19 -07004505 }
4506}
4507
Elliott Hughes47fce012011-10-25 18:37:19 -07004508void Dbg::DdmSetThreadNotification(bool enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004509 // Enable/disable thread notifications.
Elliott Hughes47fce012011-10-25 18:37:19 -07004510 gDdmThreadNotification = enable;
4511 if (enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004512 // Suspend the VM then post thread start notifications for all threads. Threads attaching will
4513 // see a suspension in progress and block until that ends. They then post their own start
4514 // notification.
4515 SuspendVM();
4516 std::list<Thread*> threads;
Ian Rogers50b35e22012-10-04 10:09:15 -07004517 Thread* self = Thread::Current();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004518 {
Ian Rogers50b35e22012-10-04 10:09:15 -07004519 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004520 threads = Runtime::Current()->GetThreadList()->GetList();
4521 }
4522 {
Ian Rogers50b35e22012-10-04 10:09:15 -07004523 ScopedObjectAccess soa(self);
Mathieu Chartier02e25112013-08-14 16:14:24 -07004524 for (Thread* thread : threads) {
4525 Dbg::DdmSendThreadNotification(thread, CHUNK_TYPE("THCR"));
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004526 }
4527 }
4528 ResumeVM();
Elliott Hughes47fce012011-10-25 18:37:19 -07004529 }
4530}
4531
Elliott Hughesa2155262011-11-16 16:26:58 -08004532void Dbg::PostThreadStartOrStop(Thread* t, uint32_t type) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07004533 if (IsDebuggerActive()) {
Sebastien Hertz6995c602014-09-09 12:10:13 +02004534 gJdwpState->PostThreadChange(t, type == CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07004535 }
Elliott Hughes82188472011-11-07 18:11:48 -08004536 Dbg::DdmSendThreadNotification(t, type);
Elliott Hughes47fce012011-10-25 18:37:19 -07004537}
4538
4539void Dbg::PostThreadStart(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004540 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07004541}
4542
4543void Dbg::PostThreadDeath(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004544 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THDE"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004545}
4546
Mathieu Chartierad466ad2015-01-08 16:28:08 -08004547JDWP::JdwpState* Dbg::GetJdwpState() {
4548 return gJdwpState;
4549}
4550
Elliott Hughes767a1472011-10-26 18:49:02 -07004551int Dbg::DdmHandleHpifChunk(HpifWhen when) {
4552 if (when == HPIF_WHEN_NOW) {
Elliott Hughes7162ad92011-10-27 14:08:42 -07004553 DdmSendHeapInfo(when);
Elliott Hughes767a1472011-10-26 18:49:02 -07004554 return true;
4555 }
4556
4557 if (when != HPIF_WHEN_NEVER && when != HPIF_WHEN_NEXT_GC && when != HPIF_WHEN_EVERY_GC) {
4558 LOG(ERROR) << "invalid HpifWhen value: " << static_cast<int>(when);
4559 return false;
4560 }
4561
4562 gDdmHpifWhen = when;
4563 return true;
4564}
4565
4566bool Dbg::DdmHandleHpsgNhsgChunk(Dbg::HpsgWhen when, Dbg::HpsgWhat what, bool native) {
4567 if (when != HPSG_WHEN_NEVER && when != HPSG_WHEN_EVERY_GC) {
4568 LOG(ERROR) << "invalid HpsgWhen value: " << static_cast<int>(when);
4569 return false;
4570 }
4571
4572 if (what != HPSG_WHAT_MERGED_OBJECTS && what != HPSG_WHAT_DISTINCT_OBJECTS) {
4573 LOG(ERROR) << "invalid HpsgWhat value: " << static_cast<int>(what);
4574 return false;
4575 }
4576
4577 if (native) {
4578 gDdmNhsgWhen = when;
4579 gDdmNhsgWhat = what;
4580 } else {
4581 gDdmHpsgWhen = when;
4582 gDdmHpsgWhat = what;
4583 }
4584 return true;
4585}
4586
Elliott Hughes7162ad92011-10-27 14:08:42 -07004587void Dbg::DdmSendHeapInfo(HpifWhen reason) {
4588 // If there's a one-shot 'when', reset it.
4589 if (reason == gDdmHpifWhen) {
4590 if (gDdmHpifWhen == HPIF_WHEN_NEXT_GC) {
4591 gDdmHpifWhen = HPIF_WHEN_NEVER;
4592 }
4593 }
4594
4595 /*
4596 * Chunk HPIF (client --> server)
4597 *
4598 * Heap Info. General information about the heap,
4599 * suitable for a summary display.
4600 *
4601 * [u4]: number of heaps
4602 *
4603 * For each heap:
4604 * [u4]: heap ID
4605 * [u8]: timestamp in ms since Unix epoch
4606 * [u1]: capture reason (same as 'when' value from server)
4607 * [u4]: max heap size in bytes (-Xmx)
4608 * [u4]: current heap size in bytes
4609 * [u4]: current number of bytes allocated
4610 * [u4]: current number of objects allocated
4611 */
4612 uint8_t heap_count = 1;
Ian Rogers1d54e732013-05-02 21:10:01 -07004613 gc::Heap* heap = Runtime::Current()->GetHeap();
Elliott Hughes21f32d72011-11-09 17:44:13 -08004614 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08004615 JDWP::Append4BE(bytes, heap_count);
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004616 JDWP::Append4BE(bytes, 1); // Heap id (bogus; we only have one heap).
Elliott Hughes545a0642011-11-08 19:10:03 -08004617 JDWP::Append8BE(bytes, MilliTime());
4618 JDWP::Append1BE(bytes, reason);
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004619 JDWP::Append4BE(bytes, heap->GetMaxMemory()); // Max allowed heap size in bytes.
4620 JDWP::Append4BE(bytes, heap->GetTotalMemory()); // Current heap size in bytes.
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08004621 JDWP::Append4BE(bytes, heap->GetBytesAllocated());
4622 JDWP::Append4BE(bytes, heap->GetObjectsAllocated());
Elliott Hughes21f32d72011-11-09 17:44:13 -08004623 CHECK_EQ(bytes.size(), 4U + (heap_count * (4 + 8 + 1 + 4 + 4 + 4 + 4)));
Alex Light772099a2017-11-21 14:05:04 -08004624 Runtime::Current()->GetRuntimeCallbacks()->DdmPublishChunk(CHUNK_TYPE("HPIF"),
4625 ArrayRef<const uint8_t>(bytes));
Elliott Hughes767a1472011-10-26 18:49:02 -07004626}
4627
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004628enum HpsgSolidity {
4629 SOLIDITY_FREE = 0,
4630 SOLIDITY_HARD = 1,
4631 SOLIDITY_SOFT = 2,
4632 SOLIDITY_WEAK = 3,
4633 SOLIDITY_PHANTOM = 4,
4634 SOLIDITY_FINALIZABLE = 5,
4635 SOLIDITY_SWEEP = 6,
4636};
4637
4638enum HpsgKind {
4639 KIND_OBJECT = 0,
4640 KIND_CLASS_OBJECT = 1,
4641 KIND_ARRAY_1 = 2,
4642 KIND_ARRAY_2 = 3,
4643 KIND_ARRAY_4 = 4,
4644 KIND_ARRAY_8 = 5,
4645 KIND_UNKNOWN = 6,
4646 KIND_NATIVE = 7,
4647};
4648
4649#define HPSG_PARTIAL (1<<7)
4650#define HPSG_STATE(solidity, kind) ((uint8_t)((((kind) & 0x7) << 3) | ((solidity) & 0x7)))
4651
Ian Rogers30fab402012-01-23 15:43:46 -08004652class HeapChunkContext {
4653 public:
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004654 // Maximum chunk size. Obtain this from the formula:
4655 // (((maximum_heap_size / ALLOCATION_UNIT_SIZE) + 255) / 256) * 2
4656 HeapChunkContext(bool merge, bool native)
Ian Rogers30fab402012-01-23 15:43:46 -08004657 : buf_(16384 - 16),
4658 type_(0),
Mathieu Chartier36dab362014-07-30 14:59:56 -07004659 chunk_overhead_(0) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004660 Reset();
4661 if (native) {
Ian Rogers30fab402012-01-23 15:43:46 -08004662 type_ = CHUNK_TYPE("NHSG");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004663 } else {
Ian Rogers30fab402012-01-23 15:43:46 -08004664 type_ = merge ? CHUNK_TYPE("HPSG") : CHUNK_TYPE("HPSO");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004665 }
4666 }
4667
4668 ~HeapChunkContext() {
Ian Rogers30fab402012-01-23 15:43:46 -08004669 if (p_ > &buf_[0]) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004670 Flush();
4671 }
4672 }
4673
Mathieu Chartier36dab362014-07-30 14:59:56 -07004674 void SetChunkOverhead(size_t chunk_overhead) {
4675 chunk_overhead_ = chunk_overhead;
4676 }
4677
4678 void ResetStartOfNextChunk() {
4679 startOfNextMemoryChunk_ = nullptr;
4680 }
4681
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004682 void EnsureHeader(const void* chunk_ptr) {
Ian Rogers30fab402012-01-23 15:43:46 -08004683 if (!needHeader_) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004684 return;
4685 }
4686
4687 // Start a new HPSx chunk.
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004688 JDWP::Write4BE(&p_, 1); // Heap id (bogus; we only have one heap).
4689 JDWP::Write1BE(&p_, 8); // Size of allocation unit, in bytes.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004690
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004691 JDWP::Write4BE(&p_, reinterpret_cast<uintptr_t>(chunk_ptr)); // virtual address of segment start.
4692 JDWP::Write4BE(&p_, 0); // offset of this piece (relative to the virtual address).
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004693 // [u4]: length of piece, in allocation units
4694 // 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 -08004695 pieceLenField_ = p_;
4696 JDWP::Write4BE(&p_, 0x55555555);
4697 needHeader_ = false;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004698 }
4699
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004700 void Flush() REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -07004701 if (pieceLenField_ == nullptr) {
Ian Rogersd636b062013-01-18 17:51:18 -08004702 // Flush immediately post Reset (maybe back-to-back Flush). Ignore.
4703 CHECK(needHeader_);
4704 return;
4705 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004706 // Patch the "length of piece" field.
Ian Rogers30fab402012-01-23 15:43:46 -08004707 CHECK_LE(&buf_[0], pieceLenField_);
4708 CHECK_LE(pieceLenField_, p_);
4709 JDWP::Set4BE(pieceLenField_, totalAllocationUnits_);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004710
Alex Light772099a2017-11-21 14:05:04 -08004711 ArrayRef<const uint8_t> out(&buf_[0], p_ - &buf_[0]);
4712 Runtime::Current()->GetRuntimeCallbacks()->DdmPublishChunk(type_, out);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004713 Reset();
4714 }
4715
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004716 static void HeapChunkJavaCallback(void* start, void* end, size_t used_bytes, void* arg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004717 REQUIRES_SHARED(Locks::heap_bitmap_lock_,
Ian Rogersb726dcb2012-09-05 08:57:23 -07004718 Locks::mutator_lock_) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004719 reinterpret_cast<HeapChunkContext*>(arg)->HeapChunkJavaCallback(start, end, used_bytes);
4720 }
4721
4722 static void HeapChunkNativeCallback(void* start, void* end, size_t used_bytes, void* arg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004723 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004724 reinterpret_cast<HeapChunkContext*>(arg)->HeapChunkNativeCallback(start, end, used_bytes);
Elliott Hughesa2155262011-11-16 16:26:58 -08004725 }
4726
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004727 private:
Elliott Hughesa2155262011-11-16 16:26:58 -08004728 enum { ALLOCATION_UNIT_SIZE = 8 };
4729
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004730 void Reset() {
Ian Rogers30fab402012-01-23 15:43:46 -08004731 p_ = &buf_[0];
Mathieu Chartier36dab362014-07-30 14:59:56 -07004732 ResetStartOfNextChunk();
Ian Rogers30fab402012-01-23 15:43:46 -08004733 totalAllocationUnits_ = 0;
4734 needHeader_ = true;
Ian Rogersc0542af2014-09-03 16:16:56 -07004735 pieceLenField_ = nullptr;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004736 }
4737
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004738 bool IsNative() const {
4739 return type_ == CHUNK_TYPE("NHSG");
4740 }
4741
4742 // Returns true if the object is not an empty chunk.
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004743 bool ProcessRecord(void* start, size_t used_bytes) REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers30fab402012-01-23 15:43:46 -08004744 // Note: heap call backs cannot manipulate the heap upon which they are crawling, care is taken
4745 // in the following code not to allocate memory, by ensuring buf_ is of the correct size
Ian Rogers15bf2d32012-08-28 17:33:04 -07004746 if (used_bytes == 0) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004747 if (start == nullptr) {
4748 // Reset for start of new heap.
4749 startOfNextMemoryChunk_ = nullptr;
4750 Flush();
4751 }
4752 // Only process in use memory so that free region information
4753 // also includes dlmalloc book keeping.
4754 return false;
Elliott Hughesa2155262011-11-16 16:26:58 -08004755 }
Ian Rogersc0542af2014-09-03 16:16:56 -07004756 if (startOfNextMemoryChunk_ != nullptr) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004757 // Transmit any pending free memory. Native free memory of over kMaxFreeLen could be because
4758 // of the use of mmaps, so don't report. If not free memory then start a new segment.
4759 bool flush = true;
4760 if (start > startOfNextMemoryChunk_) {
4761 const size_t kMaxFreeLen = 2 * kPageSize;
4762 void* free_start = startOfNextMemoryChunk_;
4763 void* free_end = start;
4764 const size_t free_len =
4765 reinterpret_cast<uintptr_t>(free_end) - reinterpret_cast<uintptr_t>(free_start);
4766 if (!IsNative() || free_len < kMaxFreeLen) {
4767 AppendChunk(HPSG_STATE(SOLIDITY_FREE, 0), free_start, free_len, IsNative());
4768 flush = false;
Ian Rogers15bf2d32012-08-28 17:33:04 -07004769 }
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004770 }
4771 if (flush) {
4772 startOfNextMemoryChunk_ = nullptr;
4773 Flush();
4774 }
Ian Rogers15bf2d32012-08-28 17:33:04 -07004775 }
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004776 return true;
Ian Rogers15bf2d32012-08-28 17:33:04 -07004777 }
Elliott Hughesa2155262011-11-16 16:26:58 -08004778
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004779 void HeapChunkNativeCallback(void* start, void* /*end*/, size_t used_bytes)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004780 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004781 if (ProcessRecord(start, used_bytes)) {
4782 uint8_t state = ExamineNativeObject(start);
4783 AppendChunk(state, start, used_bytes + chunk_overhead_, true /*is_native*/);
4784 startOfNextMemoryChunk_ = reinterpret_cast<char*>(start) + used_bytes + chunk_overhead_;
4785 }
4786 }
4787
4788 void HeapChunkJavaCallback(void* start, void* /*end*/, size_t used_bytes)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004789 REQUIRES_SHARED(Locks::heap_bitmap_lock_, Locks::mutator_lock_) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004790 if (ProcessRecord(start, used_bytes)) {
4791 // Determine the type of this chunk.
4792 // OLD-TODO: if context.merge, see if this chunk is different from the last chunk.
4793 // If it's the same, we should combine them.
4794 uint8_t state = ExamineJavaObject(reinterpret_cast<mirror::Object*>(start));
4795 AppendChunk(state, start, used_bytes + chunk_overhead_, false /*is_native*/);
4796 startOfNextMemoryChunk_ = reinterpret_cast<char*>(start) + used_bytes + chunk_overhead_;
4797 }
4798 }
4799
4800 void AppendChunk(uint8_t state, void* ptr, size_t length, bool is_native)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004801 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07004802 // Make sure there's enough room left in the buffer.
4803 // We need to use two bytes for every fractional 256 allocation units used by the chunk plus
4804 // 17 bytes for any header.
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004805 const size_t needed = ((RoundUp(length / ALLOCATION_UNIT_SIZE, 256) / 256) * 2) + 17;
4806 size_t byte_left = &buf_.back() - p_;
4807 if (byte_left < needed) {
4808 if (is_native) {
Pavel Vyssotski7522c742014-12-08 13:38:26 +06004809 // Cannot trigger memory allocation while walking native heap.
Pavel Vyssotski7522c742014-12-08 13:38:26 +06004810 return;
4811 }
Ian Rogers15bf2d32012-08-28 17:33:04 -07004812 Flush();
4813 }
4814
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004815 byte_left = &buf_.back() - p_;
4816 if (byte_left < needed) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07004817 LOG(WARNING) << "Chunk is too big to transmit (chunk_len=" << length << ", "
4818 << needed << " bytes)";
4819 return;
4820 }
4821 EnsureHeader(ptr);
Elliott Hughesa2155262011-11-16 16:26:58 -08004822 // Write out the chunk description.
Ian Rogers15bf2d32012-08-28 17:33:04 -07004823 length /= ALLOCATION_UNIT_SIZE; // Convert to allocation units.
4824 totalAllocationUnits_ += length;
4825 while (length > 256) {
Ian Rogers30fab402012-01-23 15:43:46 -08004826 *p_++ = state | HPSG_PARTIAL;
4827 *p_++ = 255; // length - 1
Ian Rogers15bf2d32012-08-28 17:33:04 -07004828 length -= 256;
Elliott Hughesa2155262011-11-16 16:26:58 -08004829 }
Ian Rogers30fab402012-01-23 15:43:46 -08004830 *p_++ = state;
Ian Rogers15bf2d32012-08-28 17:33:04 -07004831 *p_++ = length - 1;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004832 }
4833
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004834 uint8_t ExamineNativeObject(const void* p) REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004835 return p == nullptr ? HPSG_STATE(SOLIDITY_FREE, 0) : HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
4836 }
4837
4838 uint8_t ExamineJavaObject(mirror::Object* o)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004839 REQUIRES_SHARED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -07004840 if (o == nullptr) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004841 return HPSG_STATE(SOLIDITY_FREE, 0);
4842 }
Elliott Hughesa2155262011-11-16 16:26:58 -08004843 // It's an allocated chunk. Figure out what it is.
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004844 gc::Heap* heap = Runtime::Current()->GetHeap();
4845 if (!heap->IsLiveObjectLocked(o)) {
4846 LOG(ERROR) << "Invalid object in managed heap: " << o;
Elliott Hughesa2155262011-11-16 16:26:58 -08004847 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
4848 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004849 mirror::Class* c = o->GetClass();
Ian Rogersc0542af2014-09-03 16:16:56 -07004850 if (c == nullptr) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004851 // The object was probably just created but hasn't been initialized yet.
4852 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
4853 }
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004854 if (!heap->IsValidObjectAddress(c)) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07004855 LOG(ERROR) << "Invalid class for managed heap object: " << o << " " << c;
Elliott Hughesa2155262011-11-16 16:26:58 -08004856 return HPSG_STATE(SOLIDITY_HARD, KIND_UNKNOWN);
4857 }
Mathieu Chartierf26e1b32015-01-29 10:47:10 -08004858 if (c->GetClass() == nullptr) {
4859 LOG(ERROR) << "Null class of class " << c << " for object " << o;
4860 return HPSG_STATE(SOLIDITY_HARD, KIND_UNKNOWN);
4861 }
Elliott Hughesa2155262011-11-16 16:26:58 -08004862 if (c->IsClassClass()) {
4863 return HPSG_STATE(SOLIDITY_HARD, KIND_CLASS_OBJECT);
4864 }
Elliott Hughesa2155262011-11-16 16:26:58 -08004865 if (c->IsArrayClass()) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004866 switch (c->GetComponentSize()) {
4867 case 1: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_1);
4868 case 2: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_2);
4869 case 4: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
4870 case 8: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_8);
4871 }
4872 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004873 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
4874 }
4875
Ian Rogers30fab402012-01-23 15:43:46 -08004876 std::vector<uint8_t> buf_;
4877 uint8_t* p_;
4878 uint8_t* pieceLenField_;
Ian Rogers15bf2d32012-08-28 17:33:04 -07004879 void* startOfNextMemoryChunk_;
Ian Rogers30fab402012-01-23 15:43:46 -08004880 size_t totalAllocationUnits_;
4881 uint32_t type_;
Ian Rogers30fab402012-01-23 15:43:46 -08004882 bool needHeader_;
Mathieu Chartier36dab362014-07-30 14:59:56 -07004883 size_t chunk_overhead_;
Ian Rogers30fab402012-01-23 15:43:46 -08004884
Elliott Hughesa2155262011-11-16 16:26:58 -08004885 DISALLOW_COPY_AND_ASSIGN(HeapChunkContext);
4886};
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004887
4888void Dbg::DdmSendHeapSegments(bool native) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004889 Dbg::HpsgWhen when = native ? gDdmNhsgWhen : gDdmHpsgWhen;
4890 Dbg::HpsgWhat what = native ? gDdmNhsgWhat : gDdmHpsgWhat;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004891 if (when == HPSG_WHEN_NEVER) {
4892 return;
4893 }
Alex Light772099a2017-11-21 14:05:04 -08004894 RuntimeCallbacks* cb = Runtime::Current()->GetRuntimeCallbacks();
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004895 // Figure out what kind of chunks we'll be sending.
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004896 CHECK(what == HPSG_WHAT_MERGED_OBJECTS || what == HPSG_WHAT_DISTINCT_OBJECTS)
4897 << static_cast<int>(what);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004898
4899 // First, send a heap start chunk.
4900 uint8_t heap_id[4];
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004901 JDWP::Set4BE(&heap_id[0], 1); // Heap id (bogus; we only have one heap).
Alex Light772099a2017-11-21 14:05:04 -08004902 cb->DdmPublishChunk(native ? CHUNK_TYPE("NHST") : CHUNK_TYPE("HPST"),
4903 ArrayRef<const uint8_t>(heap_id));
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07004904 Thread* self = Thread::Current();
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07004905 Locks::mutator_lock_->AssertSharedHeld(self);
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07004906
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004907 // Send a series of heap segment chunks.
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004908 HeapChunkContext context(what == HPSG_WHAT_MERGED_OBJECTS, native);
Andreas Gampe0c183382017-07-13 22:26:24 -07004909 auto bump_pointer_space_visitor = [&](mirror::Object* obj)
4910 REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
4911 const size_t size = RoundUp(obj->SizeOf(), kObjectAlignment);
4912 HeapChunkContext::HeapChunkJavaCallback(
4913 obj, reinterpret_cast<void*>(reinterpret_cast<uintptr_t>(obj) + size), size, &context);
4914 };
Elliott Hughesa2155262011-11-16 16:26:58 -08004915 if (native) {
Dimitry Ivanove6465bc2015-12-14 18:55:02 -08004916 UNIMPLEMENTED(WARNING) << "Native heap inspection is not supported";
Elliott Hughesa2155262011-11-16 16:26:58 -08004917 } else {
Ian Rogers1d54e732013-05-02 21:10:01 -07004918 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartier36dab362014-07-30 14:59:56 -07004919 for (const auto& space : heap->GetContinuousSpaces()) {
4920 if (space->IsDlMallocSpace()) {
Mathieu Chartier4c69d7f2014-10-10 12:45:50 -07004921 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004922 // dlmalloc's chunk header is 2 * sizeof(size_t), but if the previous chunk is in use for an
4923 // allocation then the first sizeof(size_t) may belong to it.
4924 context.SetChunkOverhead(sizeof(size_t));
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004925 space->AsDlMallocSpace()->Walk(HeapChunkContext::HeapChunkJavaCallback, &context);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004926 } else if (space->IsRosAllocSpace()) {
4927 context.SetChunkOverhead(0);
Mathieu Chartier4c69d7f2014-10-10 12:45:50 -07004928 // Need to acquire the mutator lock before the heap bitmap lock with exclusive access since
4929 // RosAlloc's internal logic doesn't know to release and reacquire the heap bitmap lock.
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07004930 ScopedThreadSuspension sts(self, kSuspended);
Mathieu Chartier4f55e222015-09-04 13:26:21 -07004931 ScopedSuspendAll ssa(__FUNCTION__);
4932 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
4933 space->AsRosAllocSpace()->Walk(HeapChunkContext::HeapChunkJavaCallback, &context);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004934 } else if (space->IsBumpPointerSpace()) {
Mathieu Chartier4c69d7f2014-10-10 12:45:50 -07004935 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004936 context.SetChunkOverhead(0);
Andreas Gampe0c183382017-07-13 22:26:24 -07004937 space->AsBumpPointerSpace()->Walk(bump_pointer_space_visitor);
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004938 HeapChunkContext::HeapChunkJavaCallback(nullptr, nullptr, 0, &context);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08004939 } else if (space->IsRegionSpace()) {
4940 heap->IncrementDisableMovingGC(self);
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07004941 {
4942 ScopedThreadSuspension sts(self, kSuspended);
Mathieu Chartier4f55e222015-09-04 13:26:21 -07004943 ScopedSuspendAll ssa(__FUNCTION__);
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07004944 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
4945 context.SetChunkOverhead(0);
Andreas Gampe0c183382017-07-13 22:26:24 -07004946 space->AsRegionSpace()->Walk(bump_pointer_space_visitor);
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07004947 HeapChunkContext::HeapChunkJavaCallback(nullptr, nullptr, 0, &context);
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07004948 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08004949 heap->DecrementDisableMovingGC(self);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004950 } else {
4951 UNIMPLEMENTED(WARNING) << "Not counting objects in space " << *space;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07004952 }
Mathieu Chartier36dab362014-07-30 14:59:56 -07004953 context.ResetStartOfNextChunk();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07004954 }
Mathieu Chartier4c69d7f2014-10-10 12:45:50 -07004955 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07004956 // Walk the large objects, these are not in the AllocSpace.
Mathieu Chartier36dab362014-07-30 14:59:56 -07004957 context.SetChunkOverhead(0);
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004958 heap->GetLargeObjectsSpace()->Walk(HeapChunkContext::HeapChunkJavaCallback, &context);
Elliott Hughesa2155262011-11-16 16:26:58 -08004959 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004960
4961 // Finally, send a heap end chunk.
Alex Light772099a2017-11-21 14:05:04 -08004962 cb->DdmPublishChunk(native ? CHUNK_TYPE("NHEN") : CHUNK_TYPE("HPEN"),
4963 ArrayRef<const uint8_t>(heap_id));
Elliott Hughes767a1472011-10-26 18:49:02 -07004964}
4965
Brian Carlstrom306db812014-09-05 13:01:41 -07004966void Dbg::SetAllocTrackingEnabled(bool enable) {
Man Cao8c2ff642015-05-27 17:25:30 -07004967 gc::AllocRecordObjectMap::SetAllocTrackingEnabled(enable);
Elliott Hughes545a0642011-11-08 19:10:03 -08004968}
4969
4970void Dbg::DumpRecentAllocations() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004971 ScopedObjectAccess soa(Thread::Current());
Brian Carlstrom306db812014-09-05 13:01:41 -07004972 MutexLock mu(soa.Self(), *Locks::alloc_tracker_lock_);
Man Cao8c2ff642015-05-27 17:25:30 -07004973 if (!Runtime::Current()->GetHeap()->IsAllocTrackingEnabled()) {
Elliott Hughes545a0642011-11-08 19:10:03 -08004974 LOG(INFO) << "Not recording tracked allocations";
4975 return;
4976 }
Man Cao8c2ff642015-05-27 17:25:30 -07004977 gc::AllocRecordObjectMap* records = Runtime::Current()->GetHeap()->GetAllocationRecords();
4978 CHECK(records != nullptr);
Elliott Hughes545a0642011-11-08 19:10:03 -08004979
Man Cao1ed11b92015-06-11 22:47:35 -07004980 const uint16_t capped_count = CappedAllocRecordCount(records->GetRecentAllocationSize());
Brian Carlstrom306db812014-09-05 13:01:41 -07004981 uint16_t count = capped_count;
Elliott Hughes545a0642011-11-08 19:10:03 -08004982
Man Cao8c2ff642015-05-27 17:25:30 -07004983 LOG(INFO) << "Tracked allocations, (count=" << count << ")";
4984 for (auto it = records->RBegin(), end = records->REnd();
4985 count > 0 && it != end; count--, it++) {
Mathieu Chartier458b1052016-03-29 14:02:55 -07004986 const gc::AllocRecord* record = &it->second;
Elliott Hughes545a0642011-11-08 19:10:03 -08004987
Man Cao8c2ff642015-05-27 17:25:30 -07004988 LOG(INFO) << StringPrintf(" Thread %-2d %6zd bytes ", record->GetTid(), record->ByteCount())
David Sehr709b0702016-10-13 09:12:37 -07004989 << mirror::Class::PrettyClass(record->GetClass());
Elliott Hughes545a0642011-11-08 19:10:03 -08004990
Man Cao8c2ff642015-05-27 17:25:30 -07004991 for (size_t stack_frame = 0, depth = record->GetDepth(); stack_frame < depth; ++stack_frame) {
4992 const gc::AllocRecordStackTraceElement& stack_element = record->StackElement(stack_frame);
4993 ArtMethod* m = stack_element.GetMethod();
David Sehr709b0702016-10-13 09:12:37 -07004994 LOG(INFO) << " " << ArtMethod::PrettyMethod(m) << " line "
4995 << stack_element.ComputeLineNumber();
Elliott Hughes545a0642011-11-08 19:10:03 -08004996 }
4997
4998 // pause periodically to help logcat catch up
4999 if ((count % 5) == 0) {
5000 usleep(40000);
5001 }
Elliott Hughes545a0642011-11-08 19:10:03 -08005002 }
5003}
5004
5005class StringTable {
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07005006 private:
5007 struct Entry {
Andreas Gampe84eadb22017-07-07 15:08:01 -07005008 explicit Entry(const char* data_in)
5009 : data(data_in), hash(ComputeModifiedUtf8Hash(data_in)), index(0) {
5010 }
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07005011 Entry(const Entry& entry) = default;
5012 Entry(Entry&& entry) = default;
5013
5014 // Pointer to the actual string data.
5015 const char* data;
Andreas Gampe84eadb22017-07-07 15:08:01 -07005016
5017 // The hash of the data.
5018 const uint32_t hash;
5019
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07005020 // The index. This will be filled in on Finish and is not part of the ordering, so mark it
5021 // mutable.
5022 mutable uint32_t index;
5023
Andreas Gampe84eadb22017-07-07 15:08:01 -07005024 bool operator==(const Entry& other) const {
5025 return strcmp(data, other.data) == 0;
5026 }
5027 };
5028 struct EntryHash {
5029 size_t operator()(const Entry& entry) const {
5030 return entry.hash;
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07005031 }
5032 };
5033
Elliott Hughes545a0642011-11-08 19:10:03 -08005034 public:
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07005035 StringTable() : finished_(false) {
Elliott Hughes545a0642011-11-08 19:10:03 -08005036 }
5037
Andreas Gampef774a4e2017-07-06 22:15:18 -07005038 void Add(const char* str, bool copy_string) {
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07005039 DCHECK(!finished_);
Andreas Gampef774a4e2017-07-06 22:15:18 -07005040 if (UNLIKELY(copy_string)) {
5041 // Check whether it's already there.
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07005042 Entry entry(str);
5043 if (table_.find(entry) != table_.end()) {
Andreas Gampef774a4e2017-07-06 22:15:18 -07005044 return;
5045 }
Mathieu Chartier4345c462014-06-27 10:20:14 -07005046
Andreas Gampef774a4e2017-07-06 22:15:18 -07005047 // Make a copy.
5048 size_t str_len = strlen(str);
5049 char* copy = new char[str_len + 1];
5050 strlcpy(copy, str, str_len + 1);
5051 string_backup_.emplace_back(copy);
5052 str = copy;
5053 }
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07005054 Entry entry(str);
5055 table_.insert(entry);
5056 }
5057
5058 // Update all entries and give them an index. Note that this is likely not the insertion order,
5059 // as the set will with high likelihood reorder elements. Thus, Add must not be called after
5060 // Finish, and Finish must be called before IndexOf. In that case, WriteTo will walk in
5061 // the same order as Finish, and indices will agree. The order invariant, as well as indices,
5062 // are enforced through debug checks.
5063 void Finish() {
5064 DCHECK(!finished_);
5065 finished_ = true;
5066 uint32_t index = 0;
5067 for (auto& entry : table_) {
5068 entry.index = index;
5069 ++index;
5070 }
Elliott Hughes545a0642011-11-08 19:10:03 -08005071 }
5072
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07005073 size_t IndexOf(const char* s) const {
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07005074 DCHECK(finished_);
5075 Entry entry(s);
5076 auto it = table_.find(entry);
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07005077 if (it == table_.end()) {
5078 LOG(FATAL) << "IndexOf(\"" << s << "\") failed";
5079 }
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07005080 return it->index;
Elliott Hughes545a0642011-11-08 19:10:03 -08005081 }
5082
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07005083 size_t Size() const {
Elliott Hughes545a0642011-11-08 19:10:03 -08005084 return table_.size();
5085 }
5086
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07005087 void WriteTo(std::vector<uint8_t>& bytes) const {
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07005088 DCHECK(finished_);
5089 uint32_t cur_index = 0;
5090 for (const auto& entry : table_) {
5091 DCHECK_EQ(cur_index++, entry.index);
5092
5093 size_t s_len = CountModifiedUtf8Chars(entry.data);
Christopher Ferris8a354052015-04-24 17:23:53 -07005094 std::unique_ptr<uint16_t[]> s_utf16(new uint16_t[s_len]);
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07005095 ConvertModifiedUtf8ToUtf16(s_utf16.get(), entry.data);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005096 JDWP::AppendUtf16BE(bytes, s_utf16.get(), s_len);
Elliott Hughes545a0642011-11-08 19:10:03 -08005097 }
5098 }
5099
5100 private:
Andreas Gampe84eadb22017-07-07 15:08:01 -07005101 std::unordered_set<Entry, EntryHash> table_;
Andreas Gampef774a4e2017-07-06 22:15:18 -07005102 std::vector<std::unique_ptr<char[]>> string_backup_;
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07005103
5104 bool finished_;
5105
Elliott Hughes545a0642011-11-08 19:10:03 -08005106 DISALLOW_COPY_AND_ASSIGN(StringTable);
5107};
5108
Mathieu Chartiere401d142015-04-22 13:56:20 -07005109static const char* GetMethodSourceFile(ArtMethod* method)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005110 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07005111 DCHECK(method != nullptr);
5112 const char* source_file = method->GetDeclaringClassSourceFile();
Sebastien Hertz280286a2014-04-28 09:26:50 +02005113 return (source_file != nullptr) ? source_file : "";
5114}
5115
Elliott Hughes545a0642011-11-08 19:10:03 -08005116/*
5117 * The data we send to DDMS contains everything we have recorded.
5118 *
5119 * Message header (all values big-endian):
5120 * (1b) message header len (to allow future expansion); includes itself
5121 * (1b) entry header len
5122 * (1b) stack frame len
5123 * (2b) number of entries
5124 * (4b) offset to string table from start of message
5125 * (2b) number of class name strings
5126 * (2b) number of method name strings
5127 * (2b) number of source file name strings
5128 * For each entry:
5129 * (4b) total allocation size
Elliott Hughes221229c2013-01-08 18:17:50 -08005130 * (2b) thread id
Elliott Hughes545a0642011-11-08 19:10:03 -08005131 * (2b) allocated object's class name index
5132 * (1b) stack depth
5133 * For each stack frame:
5134 * (2b) method's class name
5135 * (2b) method name
5136 * (2b) method source file
5137 * (2b) line number, clipped to 32767; -2 if native; -1 if no source
5138 * (xb) class name strings
5139 * (xb) method name strings
5140 * (xb) source file strings
5141 *
5142 * As with other DDM traffic, strings are sent as a 4-byte length
5143 * followed by UTF-16 data.
5144 *
5145 * We send up 16-bit unsigned indexes into string tables. In theory there
Brian Carlstrom306db812014-09-05 13:01:41 -07005146 * can be (kMaxAllocRecordStackDepth * alloc_record_max_) unique strings in
Elliott Hughes545a0642011-11-08 19:10:03 -08005147 * each table, but in practice there should be far fewer.
5148 *
5149 * The chief reason for using a string table here is to keep the size of
5150 * the DDMS message to a minimum. This is partly to make the protocol
5151 * efficient, but also because we have to form the whole thing up all at
5152 * once in a memory buffer.
5153 *
5154 * We use separate string tables for class names, method names, and source
5155 * files to keep the indexes small. There will generally be no overlap
5156 * between the contents of these tables.
5157 */
5158jbyteArray Dbg::GetRecentAllocations() {
Ian Rogerscf7f1912014-10-22 22:06:39 -07005159 if ((false)) {
Elliott Hughes545a0642011-11-08 19:10:03 -08005160 DumpRecentAllocations();
5161 }
5162
Ian Rogers50b35e22012-10-04 10:09:15 -07005163 Thread* self = Thread::Current();
Elliott Hughes545a0642011-11-08 19:10:03 -08005164 std::vector<uint8_t> bytes;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005165 {
Brian Carlstrom306db812014-09-05 13:01:41 -07005166 MutexLock mu(self, *Locks::alloc_tracker_lock_);
Man Cao8c2ff642015-05-27 17:25:30 -07005167 gc::AllocRecordObjectMap* records = Runtime::Current()->GetHeap()->GetAllocationRecords();
5168 // In case this method is called when allocation tracker is disabled,
5169 // we should still send some data back.
5170 gc::AllocRecordObjectMap dummy;
5171 if (records == nullptr) {
5172 CHECK(!Runtime::Current()->GetHeap()->IsAllocTrackingEnabled());
5173 records = &dummy;
5174 }
Man Cao41656de2015-07-06 18:53:15 -07005175 // We don't need to wait on the condition variable records->new_record_condition_, because this
5176 // function only reads the class objects, which are already marked so it doesn't change their
5177 // reachability.
Man Cao8c2ff642015-05-27 17:25:30 -07005178
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005179 //
5180 // Part 1: generate string tables.
5181 //
5182 StringTable class_names;
5183 StringTable method_names;
5184 StringTable filenames;
Elliott Hughes545a0642011-11-08 19:10:03 -08005185
Andreas Gampeff29cee2017-07-07 11:11:15 -07005186 VLOG(jdwp) << "Collecting StringTables.";
5187
Man Cao1ed11b92015-06-11 22:47:35 -07005188 const uint16_t capped_count = CappedAllocRecordCount(records->GetRecentAllocationSize());
Brian Carlstrom306db812014-09-05 13:01:41 -07005189 uint16_t count = capped_count;
Andreas Gamped0fc7682017-07-07 14:03:08 -07005190 size_t alloc_byte_count = 0;
Man Cao8c2ff642015-05-27 17:25:30 -07005191 for (auto it = records->RBegin(), end = records->REnd();
5192 count > 0 && it != end; count--, it++) {
Mathieu Chartier458b1052016-03-29 14:02:55 -07005193 const gc::AllocRecord* record = &it->second;
Ian Rogers1ff3c982014-08-12 02:30:58 -07005194 std::string temp;
Andreas Gampef774a4e2017-07-06 22:15:18 -07005195 const char* class_descr = record->GetClassDescriptor(&temp);
5196 class_names.Add(class_descr, !temp.empty());
Andreas Gamped0fc7682017-07-07 14:03:08 -07005197
5198 // Size + tid + class name index + stack depth.
5199 alloc_byte_count += 4u + 2u + 2u + 1u;
5200
Man Cao8c2ff642015-05-27 17:25:30 -07005201 for (size_t i = 0, depth = record->GetDepth(); i < depth; i++) {
5202 ArtMethod* m = record->StackElement(i).GetMethod();
Andreas Gampef774a4e2017-07-06 22:15:18 -07005203 class_names.Add(m->GetDeclaringClassDescriptor(), false);
5204 method_names.Add(m->GetName(), false);
5205 filenames.Add(GetMethodSourceFile(m), false);
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005206 }
Andreas Gamped0fc7682017-07-07 14:03:08 -07005207
5208 // Depth * (class index + method name index + file name index + line number).
5209 alloc_byte_count += record->GetDepth() * (2u + 2u + 2u + 2u);
Elliott Hughes545a0642011-11-08 19:10:03 -08005210 }
5211
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07005212 class_names.Finish();
5213 method_names.Finish();
5214 filenames.Finish();
Andreas Gampeff29cee2017-07-07 11:11:15 -07005215 VLOG(jdwp) << "Done collecting StringTables:" << std::endl
5216 << " ClassNames: " << class_names.Size() << std::endl
5217 << " MethodNames: " << method_names.Size() << std::endl
5218 << " Filenames: " << filenames.Size();
5219
Man Cao8c2ff642015-05-27 17:25:30 -07005220 LOG(INFO) << "recent allocation records: " << capped_count;
5221 LOG(INFO) << "allocation records all objects: " << records->Size();
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005222
5223 //
5224 // Part 2: Generate the output and store it in the buffer.
5225 //
5226
5227 // (1b) message header len (to allow future expansion); includes itself
5228 // (1b) entry header len
5229 // (1b) stack frame len
5230 const int kMessageHeaderLen = 15;
5231 const int kEntryHeaderLen = 9;
5232 const int kStackFrameLen = 8;
5233 JDWP::Append1BE(bytes, kMessageHeaderLen);
5234 JDWP::Append1BE(bytes, kEntryHeaderLen);
5235 JDWP::Append1BE(bytes, kStackFrameLen);
5236
5237 // (2b) number of entries
5238 // (4b) offset to string table from start of message
5239 // (2b) number of class name strings
5240 // (2b) number of method name strings
5241 // (2b) number of source file name strings
Brian Carlstrom306db812014-09-05 13:01:41 -07005242 JDWP::Append2BE(bytes, capped_count);
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005243 size_t string_table_offset = bytes.size();
Brian Carlstrom7934ac22013-07-26 10:54:15 -07005244 JDWP::Append4BE(bytes, 0); // We'll patch this later...
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005245 JDWP::Append2BE(bytes, class_names.Size());
5246 JDWP::Append2BE(bytes, method_names.Size());
5247 JDWP::Append2BE(bytes, filenames.Size());
5248
Andreas Gampeff29cee2017-07-07 11:11:15 -07005249 VLOG(jdwp) << "Dumping allocations with stacks";
5250
Andreas Gamped0fc7682017-07-07 14:03:08 -07005251 // Enlarge the vector for the allocation data.
5252 size_t reserve_size = bytes.size() + alloc_byte_count;
5253 bytes.reserve(reserve_size);
5254
Ian Rogers1ff3c982014-08-12 02:30:58 -07005255 std::string temp;
Man Cao8c2ff642015-05-27 17:25:30 -07005256 count = capped_count;
5257 // The last "count" number of allocation records in "records" are the most recent "count" number
5258 // of allocations. Reverse iterate to get them. The most recent allocation is sent first.
5259 for (auto it = records->RBegin(), end = records->REnd();
5260 count > 0 && it != end; count--, it++) {
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005261 // For each entry:
5262 // (4b) total allocation size
5263 // (2b) thread id
5264 // (2b) allocated object's class name index
5265 // (1b) stack depth
Mathieu Chartier458b1052016-03-29 14:02:55 -07005266 const gc::AllocRecord* record = &it->second;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005267 size_t stack_depth = record->GetDepth();
Mathieu Chartierf8322842014-05-16 10:59:25 -07005268 size_t allocated_object_class_name_index =
Man Cao41656de2015-07-06 18:53:15 -07005269 class_names.IndexOf(record->GetClassDescriptor(&temp));
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07005270 JDWP::Append4BE(bytes, record->ByteCount());
Man Cao8c2ff642015-05-27 17:25:30 -07005271 JDWP::Append2BE(bytes, static_cast<uint16_t>(record->GetTid()));
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005272 JDWP::Append2BE(bytes, allocated_object_class_name_index);
5273 JDWP::Append1BE(bytes, stack_depth);
5274
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005275 for (size_t stack_frame = 0; stack_frame < stack_depth; ++stack_frame) {
5276 // For each stack frame:
5277 // (2b) method's class name
5278 // (2b) method name
5279 // (2b) method source file
5280 // (2b) line number, clipped to 32767; -2 if native; -1 if no source
Man Cao8c2ff642015-05-27 17:25:30 -07005281 ArtMethod* m = record->StackElement(stack_frame).GetMethod();
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07005282 size_t class_name_index = class_names.IndexOf(m->GetDeclaringClassDescriptor());
5283 size_t method_name_index = method_names.IndexOf(m->GetName());
5284 size_t file_name_index = filenames.IndexOf(GetMethodSourceFile(m));
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005285 JDWP::Append2BE(bytes, class_name_index);
5286 JDWP::Append2BE(bytes, method_name_index);
5287 JDWP::Append2BE(bytes, file_name_index);
Man Cao8c2ff642015-05-27 17:25:30 -07005288 JDWP::Append2BE(bytes, record->StackElement(stack_frame).ComputeLineNumber());
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005289 }
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005290 }
5291
Andreas Gamped0fc7682017-07-07 14:03:08 -07005292 CHECK_EQ(bytes.size(), reserve_size);
Andreas Gampeff29cee2017-07-07 11:11:15 -07005293 VLOG(jdwp) << "Dumping tables.";
5294
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005295 // (xb) class name strings
5296 // (xb) method name strings
5297 // (xb) source file strings
5298 JDWP::Set4BE(&bytes[string_table_offset], bytes.size());
5299 class_names.WriteTo(bytes);
5300 method_names.WriteTo(bytes);
5301 filenames.WriteTo(bytes);
Andreas Gampeff29cee2017-07-07 11:11:15 -07005302
5303 VLOG(jdwp) << "GetRecentAllocations: data created. " << bytes.size();
Elliott Hughes545a0642011-11-08 19:10:03 -08005304 }
Ian Rogers50b35e22012-10-04 10:09:15 -07005305 JNIEnv* env = self->GetJniEnv();
Elliott Hughes545a0642011-11-08 19:10:03 -08005306 jbyteArray result = env->NewByteArray(bytes.size());
Ian Rogersc0542af2014-09-03 16:16:56 -07005307 if (result != nullptr) {
Elliott Hughes545a0642011-11-08 19:10:03 -08005308 env->SetByteArrayRegion(result, 0, bytes.size(), reinterpret_cast<const jbyte*>(&bytes[0]));
5309 }
5310 return result;
5311}
5312
Mathieu Chartiere401d142015-04-22 13:56:20 -07005313ArtMethod* DeoptimizationRequest::Method() const {
Andreas Gampe13b27842016-11-07 16:48:23 -08005314 return jni::DecodeArtMethod(method_);
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07005315}
5316
Mathieu Chartiere401d142015-04-22 13:56:20 -07005317void DeoptimizationRequest::SetMethod(ArtMethod* m) {
Andreas Gampe13b27842016-11-07 16:48:23 -08005318 method_ = jni::EncodeArtMethod(m);
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07005319}
5320
Mathieu Chartiera6b1ead2015-10-06 10:32:38 -07005321void Dbg::VisitRoots(RootVisitor* visitor) {
5322 // Visit breakpoint roots, used to prevent unloading of methods with breakpoints.
5323 ReaderMutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
5324 BufferedRootVisitor<128> root_visitor(visitor, RootInfo(kRootVMInternal));
5325 for (Breakpoint& breakpoint : gBreakpoints) {
Andreas Gampe542451c2016-07-26 09:02:02 -07005326 breakpoint.Method()->VisitRoots(root_visitor, kRuntimePointerSize);
Mathieu Chartiera6b1ead2015-10-06 10:32:38 -07005327 }
5328}
5329
Andreas Gampe04bbb5b2017-01-19 17:49:03 +00005330void Dbg::DbgThreadLifecycleCallback::ThreadStart(Thread* self) {
5331 Dbg::PostThreadStart(self);
5332}
5333
5334void Dbg::DbgThreadLifecycleCallback::ThreadDeath(Thread* self) {
5335 Dbg::PostThreadDeath(self);
5336}
5337
Andreas Gampe0f01b582017-01-18 15:22:37 -08005338void Dbg::DbgClassLoadCallback::ClassLoad(Handle<mirror::Class> klass ATTRIBUTE_UNUSED) {
5339 // Ignore ClassLoad;
5340}
5341void Dbg::DbgClassLoadCallback::ClassPrepare(Handle<mirror::Class> temp_klass ATTRIBUTE_UNUSED,
5342 Handle<mirror::Class> klass) {
5343 Dbg::PostClassPrepare(klass.Get());
5344}
5345
Elliott Hughes872d4ec2011-10-21 17:07:15 -07005346} // namespace art