blob: 1dcd935eeab24d7f84f8e1d09e23cb62aae958fe [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;
966 Runtime::Current()->GetHeap()->GetInstances(hs, hs.NewHandle(c), max_count, raw_instances);
Elliott Hughes3b78c942013-01-15 17:35:41 -0800967 for (size_t i = 0; i < raw_instances.size(); ++i) {
Mathieu Chartier2d855952016-10-12 19:37:59 -0700968 instances->push_back(gRegistry->Add(raw_instances[i].Get()));
Elliott Hughes3b78c942013-01-15 17:35:41 -0800969 }
970 return JDWP::ERR_NONE;
971}
972
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800973JDWP::JdwpError Dbg::GetReferringObjects(JDWP::ObjectId object_id, int32_t max_count,
Ian Rogersc0542af2014-09-03 16:16:56 -0700974 std::vector<JDWP::ObjectId>* referring_objects) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800975 gc::Heap* heap = Runtime::Current()->GetHeap();
976 heap->CollectGarbage(false);
Ian Rogersc0542af2014-09-03 16:16:56 -0700977 JDWP::JdwpError error;
Mathieu Chartier9d156d52016-10-06 17:44:26 -0700978 ObjPtr<mirror::Object> o = gRegistry->Get<mirror::Object*>(object_id, &error);
Ian Rogersc0542af2014-09-03 16:16:56 -0700979 if (o == nullptr) {
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800980 return JDWP::ERR_INVALID_OBJECT;
981 }
Mathieu Chartieraea9bfb2016-10-12 19:19:56 -0700982 VariableSizedHandleScope hs(Thread::Current());
983 std::vector<Handle<mirror::Object>> raw_instances;
984 heap->GetReferringObjects(hs, hs.NewHandle(o), max_count, raw_instances);
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800985 for (size_t i = 0; i < raw_instances.size(); ++i) {
Mathieu Chartieraea9bfb2016-10-12 19:19:56 -0700986 referring_objects->push_back(gRegistry->Add(raw_instances[i].Get()));
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800987 }
988 return JDWP::ERR_NONE;
989}
990
Ian Rogersc0542af2014-09-03 16:16:56 -0700991JDWP::JdwpError Dbg::DisableCollection(JDWP::ObjectId object_id) {
992 JDWP::JdwpError error;
993 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
994 if (o == nullptr) {
Sebastien Hertze96060a2013-12-11 12:06:28 +0100995 return JDWP::ERR_INVALID_OBJECT;
996 }
Elliott Hughes64f574f2013-02-20 14:57:12 -0800997 gRegistry->DisableCollection(object_id);
998 return JDWP::ERR_NONE;
999}
1000
Ian Rogersc0542af2014-09-03 16:16:56 -07001001JDWP::JdwpError Dbg::EnableCollection(JDWP::ObjectId object_id) {
1002 JDWP::JdwpError error;
1003 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
Sebastien Hertze96060a2013-12-11 12:06:28 +01001004 // Unlike DisableCollection, JDWP specs do not state an invalid object causes an error. The RI
1005 // also ignores these cases and never return an error. However it's not obvious why this command
1006 // should behave differently from DisableCollection and IsCollected commands. So let's be more
1007 // strict and return an error if this happens.
Ian Rogersc0542af2014-09-03 16:16:56 -07001008 if (o == nullptr) {
Sebastien Hertze96060a2013-12-11 12:06:28 +01001009 return JDWP::ERR_INVALID_OBJECT;
1010 }
Elliott Hughes64f574f2013-02-20 14:57:12 -08001011 gRegistry->EnableCollection(object_id);
1012 return JDWP::ERR_NONE;
1013}
1014
Ian Rogersc0542af2014-09-03 16:16:56 -07001015JDWP::JdwpError Dbg::IsCollected(JDWP::ObjectId object_id, bool* is_collected) {
1016 *is_collected = true;
Sebastien Hertz65637eb2014-01-10 17:40:02 +01001017 if (object_id == 0) {
1018 // Null object id is invalid.
Sebastien Hertze96060a2013-12-11 12:06:28 +01001019 return JDWP::ERR_INVALID_OBJECT;
1020 }
Sebastien Hertz65637eb2014-01-10 17:40:02 +01001021 // JDWP specs state an INVALID_OBJECT error is returned if the object ID is not valid. However
1022 // the RI seems to ignore this and assume object has been collected.
Ian Rogersc0542af2014-09-03 16:16:56 -07001023 JDWP::JdwpError error;
1024 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
1025 if (o != nullptr) {
1026 *is_collected = gRegistry->IsCollected(object_id);
Sebastien Hertz65637eb2014-01-10 17:40:02 +01001027 }
Elliott Hughes64f574f2013-02-20 14:57:12 -08001028 return JDWP::ERR_NONE;
1029}
1030
Ian Rogersc0542af2014-09-03 16:16:56 -07001031void Dbg::DisposeObject(JDWP::ObjectId object_id, uint32_t reference_count) {
Elliott Hughes64f574f2013-02-20 14:57:12 -08001032 gRegistry->DisposeObject(object_id, reference_count);
1033}
1034
Mathieu Chartier3398c782016-09-30 10:27:43 -07001035JDWP::JdwpTypeTag Dbg::GetTypeTag(ObjPtr<mirror::Class> klass) {
Sebastien Hertz4d8fd492014-03-28 16:29:41 +01001036 DCHECK(klass != nullptr);
1037 if (klass->IsArrayClass()) {
1038 return JDWP::TT_ARRAY;
1039 } else if (klass->IsInterface()) {
1040 return JDWP::TT_INTERFACE;
1041 } else {
1042 return JDWP::TT_CLASS;
1043 }
1044}
1045
Elliott Hughes88d63092013-01-09 09:55:54 -08001046JDWP::JdwpError Dbg::GetReflectedType(JDWP::RefTypeId class_id, JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001047 JDWP::JdwpError error;
1048 mirror::Class* c = DecodeClass(class_id, &error);
1049 if (c == nullptr) {
1050 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001051 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001052
Sebastien Hertz4d8fd492014-03-28 16:29:41 +01001053 JDWP::JdwpTypeTag type_tag = GetTypeTag(c);
1054 expandBufAdd1(pReply, type_tag);
Elliott Hughes88d63092013-01-09 09:55:54 -08001055 expandBufAddRefTypeId(pReply, class_id);
Elliott Hughes436e3722012-02-17 20:01:47 -08001056 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001057}
1058
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001059// Get the complete list of reference classes (i.e. all classes except
1060// the primitive types).
1061// Returns a newly-allocated buffer full of RefTypeId values.
1062class ClassListCreator : public ClassVisitor {
1063 public:
1064 explicit ClassListCreator(std::vector<JDWP::RefTypeId>* classes) : classes_(classes) {}
1065
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001066 bool operator()(ObjPtr<mirror::Class> c) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001067 if (!c->IsPrimitive()) {
1068 classes_->push_back(Dbg::GetObjectRegistry()->AddRefType(c));
1069 }
1070 return true;
1071 }
1072
1073 private:
1074 std::vector<JDWP::RefTypeId>* const classes_;
1075};
1076
Ian Rogersc0542af2014-09-03 16:16:56 -07001077void Dbg::GetClassList(std::vector<JDWP::RefTypeId>* classes) {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001078 ClassListCreator clc(classes);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001079 Runtime::Current()->GetClassLinker()->VisitClassesWithoutClassesLock(&clc);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001080}
1081
Ian Rogers1ff3c982014-08-12 02:30:58 -07001082JDWP::JdwpError Dbg::GetClassInfo(JDWP::RefTypeId class_id, JDWP::JdwpTypeTag* pTypeTag,
1083 uint32_t* pStatus, std::string* pDescriptor) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001084 JDWP::JdwpError error;
1085 mirror::Class* c = DecodeClass(class_id, &error);
1086 if (c == nullptr) {
1087 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001088 }
1089
Elliott Hughesa2155262011-11-16 16:26:58 -08001090 if (c->IsArrayClass()) {
1091 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
1092 *pTypeTag = JDWP::TT_ARRAY;
1093 } else {
1094 if (c->IsErroneous()) {
1095 *pStatus = JDWP::CS_ERROR;
1096 } else {
1097 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED | JDWP::CS_INITIALIZED;
1098 }
1099 *pTypeTag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
1100 }
1101
Ian Rogersc0542af2014-09-03 16:16:56 -07001102 if (pDescriptor != nullptr) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07001103 std::string temp;
1104 *pDescriptor = c->GetDescriptor(&temp);
Elliott Hughesa2155262011-11-16 16:26:58 -08001105 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001106 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001107}
1108
Ian Rogersc0542af2014-09-03 16:16:56 -07001109void Dbg::FindLoadedClassBySignature(const char* descriptor, std::vector<JDWP::RefTypeId>* ids) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001110 std::vector<ObjPtr<mirror::Class>> classes;
Igor Murashkinb1d8c312015-08-04 11:18:43 -07001111 Runtime::Current()->GetClassLinker()->LookupClasses(descriptor, classes);
Ian Rogersc0542af2014-09-03 16:16:56 -07001112 ids->clear();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001113 for (ObjPtr<mirror::Class> c : classes) {
1114 ids->push_back(gRegistry->Add(c));
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001115 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001116}
1117
Ian Rogersc0542af2014-09-03 16:16:56 -07001118JDWP::JdwpError Dbg::GetReferenceType(JDWP::ObjectId object_id, JDWP::ExpandBuf* pReply) {
1119 JDWP::JdwpError error;
1120 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
1121 if (o == nullptr) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001122 return JDWP::ERR_INVALID_OBJECT;
Elliott Hughes499c5132011-11-17 14:55:11 -08001123 }
Elliott Hughes2435a572012-02-17 16:07:41 -08001124
Sebastien Hertz4d8fd492014-03-28 16:29:41 +01001125 JDWP::JdwpTypeTag type_tag = GetTypeTag(o->GetClass());
Elliott Hughes64f574f2013-02-20 14:57:12 -08001126 JDWP::RefTypeId type_id = gRegistry->AddRefType(o->GetClass());
Elliott Hughes2435a572012-02-17 16:07:41 -08001127
1128 expandBufAdd1(pReply, type_tag);
1129 expandBufAddRefTypeId(pReply, type_id);
1130
1131 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001132}
1133
Ian Rogersfc0e94b2013-09-23 23:51:32 -07001134JDWP::JdwpError Dbg::GetSignature(JDWP::RefTypeId class_id, std::string* signature) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001135 JDWP::JdwpError error;
1136 mirror::Class* c = DecodeClass(class_id, &error);
1137 if (c == nullptr) {
1138 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001139 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07001140 std::string temp;
1141 *signature = c->GetDescriptor(&temp);
Elliott Hughes1fe7afb2012-02-13 17:23:03 -08001142 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001143}
1144
Orion Hodson77d8a1c2017-04-24 14:53:19 +01001145JDWP::JdwpError Dbg::GetSourceDebugExtension(JDWP::RefTypeId class_id,
1146 std::string* extension_data) {
1147 JDWP::JdwpError error;
1148 mirror::Class* c = DecodeClass(class_id, &error);
1149 if (c == nullptr) {
1150 return error;
1151 }
1152 StackHandleScope<1> hs(Thread::Current());
1153 Handle<mirror::Class> klass(hs.NewHandle(c));
1154 const char* data = annotations::GetSourceDebugExtension(klass);
1155 if (data == nullptr) {
1156 return JDWP::ERR_ABSENT_INFORMATION;
1157 }
1158 *extension_data = data;
1159 return JDWP::ERR_NONE;
1160}
1161
Ian Rogersc0542af2014-09-03 16:16:56 -07001162JDWP::JdwpError Dbg::GetSourceFile(JDWP::RefTypeId class_id, std::string* result) {
1163 JDWP::JdwpError error;
1164 mirror::Class* c = DecodeClass(class_id, &error);
Sebastien Hertz4206eb52014-06-05 10:15:45 +02001165 if (c == nullptr) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001166 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001167 }
Sebastien Hertz4206eb52014-06-05 10:15:45 +02001168 const char* source_file = c->GetSourceFile();
1169 if (source_file == nullptr) {
Sebastien Hertzb7054ba2014-03-13 11:52:31 +01001170 return JDWP::ERR_ABSENT_INFORMATION;
1171 }
Ian Rogersc0542af2014-09-03 16:16:56 -07001172 *result = source_file;
Elliott Hughes436e3722012-02-17 20:01:47 -08001173 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001174}
1175
Ian Rogersc0542af2014-09-03 16:16:56 -07001176JDWP::JdwpError Dbg::GetObjectTag(JDWP::ObjectId object_id, uint8_t* tag) {
Ian Rogers98379392014-02-24 16:53:16 -08001177 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07001178 JDWP::JdwpError error;
1179 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
1180 if (error != JDWP::ERR_NONE) {
1181 *tag = JDWP::JT_VOID;
1182 return error;
Elliott Hughes546b9862012-06-20 16:06:13 -07001183 }
Ian Rogersc0542af2014-09-03 16:16:56 -07001184 *tag = TagFromObject(soa, o);
Elliott Hughes546b9862012-06-20 16:06:13 -07001185 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001186}
1187
Elliott Hughesaed4be92011-12-02 16:16:23 -08001188size_t Dbg::GetTagWidth(JDWP::JdwpTag tag) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001189 switch (tag) {
1190 case JDWP::JT_VOID:
1191 return 0;
1192 case JDWP::JT_BYTE:
1193 case JDWP::JT_BOOLEAN:
1194 return 1;
1195 case JDWP::JT_CHAR:
1196 case JDWP::JT_SHORT:
1197 return 2;
1198 case JDWP::JT_FLOAT:
1199 case JDWP::JT_INT:
1200 return 4;
1201 case JDWP::JT_ARRAY:
1202 case JDWP::JT_OBJECT:
1203 case JDWP::JT_STRING:
1204 case JDWP::JT_THREAD:
1205 case JDWP::JT_THREAD_GROUP:
1206 case JDWP::JT_CLASS_LOADER:
1207 case JDWP::JT_CLASS_OBJECT:
1208 return sizeof(JDWP::ObjectId);
1209 case JDWP::JT_DOUBLE:
1210 case JDWP::JT_LONG:
1211 return 8;
1212 default:
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001213 LOG(FATAL) << "Unknown tag " << tag;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001214 return -1;
1215 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001216}
1217
Ian Rogersc0542af2014-09-03 16:16:56 -07001218JDWP::JdwpError Dbg::GetArrayLength(JDWP::ObjectId array_id, int32_t* length) {
1219 JDWP::JdwpError error;
1220 mirror::Array* a = DecodeNonNullArray(array_id, &error);
1221 if (a == nullptr) {
1222 return error;
Elliott Hughes24437992011-11-30 14:49:33 -08001223 }
Ian Rogersc0542af2014-09-03 16:16:56 -07001224 *length = a->GetLength();
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001225 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001226}
1227
Elliott Hughes88d63092013-01-09 09:55:54 -08001228JDWP::JdwpError Dbg::OutputArray(JDWP::ObjectId array_id, int offset, int count, JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001229 JDWP::JdwpError error;
1230 mirror::Array* a = DecodeNonNullArray(array_id, &error);
Ian Rogers98379392014-02-24 16:53:16 -08001231 if (a == nullptr) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001232 return error;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001233 }
Elliott Hughes24437992011-11-30 14:49:33 -08001234
1235 if (offset < 0 || count < 0 || offset > a->GetLength() || a->GetLength() - offset < count) {
1236 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001237 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughes24437992011-11-30 14:49:33 -08001238 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07001239 JDWP::JdwpTag element_tag = BasicTagFromClass(a->GetClass()->GetComponentType());
1240 expandBufAdd1(pReply, element_tag);
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001241 expandBufAdd4BE(pReply, count);
1242
Ian Rogers1ff3c982014-08-12 02:30:58 -07001243 if (IsPrimitiveTag(element_tag)) {
1244 size_t width = GetTagWidth(element_tag);
Elliott Hughes24437992011-11-30 14:49:33 -08001245 uint8_t* dst = expandBufAddSpace(pReply, count * width);
1246 if (width == 8) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001247 const uint64_t* src8 = reinterpret_cast<uint64_t*>(a->GetRawData(sizeof(uint64_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001248 for (int i = 0; i < count; ++i) JDWP::Write8BE(&dst, src8[offset + i]);
1249 } else if (width == 4) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001250 const uint32_t* src4 = reinterpret_cast<uint32_t*>(a->GetRawData(sizeof(uint32_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001251 for (int i = 0; i < count; ++i) JDWP::Write4BE(&dst, src4[offset + i]);
1252 } else if (width == 2) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001253 const uint16_t* src2 = reinterpret_cast<uint16_t*>(a->GetRawData(sizeof(uint16_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001254 for (int i = 0; i < count; ++i) JDWP::Write2BE(&dst, src2[offset + i]);
1255 } else {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001256 const uint8_t* src = reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint8_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001257 memcpy(dst, &src[offset * width], count * width);
1258 }
1259 } else {
Ian Rogers98379392014-02-24 16:53:16 -08001260 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001261 mirror::ObjectArray<mirror::Object>* oa = a->AsObjectArray<mirror::Object>();
Elliott Hughes24437992011-11-30 14:49:33 -08001262 for (int i = 0; i < count; ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001263 mirror::Object* element = oa->Get(offset + i);
Ian Rogers98379392014-02-24 16:53:16 -08001264 JDWP::JdwpTag specific_tag = (element != nullptr) ? TagFromObject(soa, element)
Ian Rogers1ff3c982014-08-12 02:30:58 -07001265 : element_tag;
Elliott Hughes24437992011-11-30 14:49:33 -08001266 expandBufAdd1(pReply, specific_tag);
1267 expandBufAddObjectId(pReply, gRegistry->Add(element));
1268 }
1269 }
1270
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001271 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001272}
1273
Ian Rogersef7d42f2014-01-06 12:55:46 -08001274template <typename T>
Ian Rogersc0542af2014-09-03 16:16:56 -07001275static void CopyArrayData(mirror::Array* a, JDWP::Request* src, int offset, int count)
Ian Rogersef7d42f2014-01-06 12:55:46 -08001276 NO_THREAD_SAFETY_ANALYSIS {
1277 // TODO: fix when annotalysis correctly handles non-member functions.
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001278 DCHECK(a->GetClass()->IsPrimitiveArray());
1279
Ian Rogersef7d42f2014-01-06 12:55:46 -08001280 T* dst = reinterpret_cast<T*>(a->GetRawData(sizeof(T), offset));
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001281 for (int i = 0; i < count; ++i) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001282 *dst++ = src->ReadValue(sizeof(T));
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001283 }
1284}
1285
Elliott Hughes88d63092013-01-09 09:55:54 -08001286JDWP::JdwpError Dbg::SetArrayElements(JDWP::ObjectId array_id, int offset, int count,
Ian Rogersc0542af2014-09-03 16:16:56 -07001287 JDWP::Request* request) {
1288 JDWP::JdwpError error;
1289 mirror::Array* dst = DecodeNonNullArray(array_id, &error);
1290 if (dst == nullptr) {
1291 return error;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001292 }
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001293
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001294 if (offset < 0 || count < 0 || offset > dst->GetLength() || dst->GetLength() - offset < count) {
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001295 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001296 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001297 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07001298 JDWP::JdwpTag element_tag = BasicTagFromClass(dst->GetClass()->GetComponentType());
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001299
Ian Rogers1ff3c982014-08-12 02:30:58 -07001300 if (IsPrimitiveTag(element_tag)) {
1301 size_t width = GetTagWidth(element_tag);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001302 if (width == 8) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001303 CopyArrayData<uint64_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001304 } else if (width == 4) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001305 CopyArrayData<uint32_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001306 } else if (width == 2) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001307 CopyArrayData<uint16_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001308 } else {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001309 CopyArrayData<uint8_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001310 }
1311 } else {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001312 mirror::ObjectArray<mirror::Object>* oa = dst->AsObjectArray<mirror::Object>();
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001313 for (int i = 0; i < count; ++i) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001314 JDWP::ObjectId id = request->ReadObjectId();
Ian Rogersc0542af2014-09-03 16:16:56 -07001315 mirror::Object* o = gRegistry->Get<mirror::Object*>(id, &error);
1316 if (error != JDWP::ERR_NONE) {
1317 return error;
Elliott Hughes436e3722012-02-17 20:01:47 -08001318 }
Sebastien Hertz2e1c16d2015-08-28 11:57:49 +02001319 // Check if the object's type is compatible with the array's type.
1320 if (o != nullptr && !o->InstanceOf(oa->GetClass()->GetComponentType())) {
1321 return JDWP::ERR_TYPE_MISMATCH;
1322 }
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001323 oa->Set<false>(offset + i, o);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001324 }
1325 }
1326
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001327 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001328}
1329
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001330JDWP::JdwpError Dbg::CreateString(const std::string& str, JDWP::ObjectId* new_string_id) {
1331 Thread* self = Thread::Current();
1332 mirror::String* new_string = mirror::String::AllocFromModifiedUtf8(self, str.c_str());
1333 if (new_string == nullptr) {
1334 DCHECK(self->IsExceptionPending());
1335 self->ClearException();
1336 LOG(ERROR) << "Could not allocate string";
1337 *new_string_id = 0;
1338 return JDWP::ERR_OUT_OF_MEMORY;
1339 }
1340 *new_string_id = gRegistry->Add(new_string);
1341 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001342}
1343
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001344JDWP::JdwpError Dbg::CreateObject(JDWP::RefTypeId class_id, JDWP::ObjectId* new_object_id) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001345 JDWP::JdwpError error;
1346 mirror::Class* c = DecodeClass(class_id, &error);
1347 if (c == nullptr) {
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001348 *new_object_id = 0;
Ian Rogersc0542af2014-09-03 16:16:56 -07001349 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001350 }
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001351 Thread* self = Thread::Current();
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001352 ObjPtr<mirror::Object> new_object;
Sebastien Hertz56d5e502015-11-03 17:38:35 +01001353 if (c->IsStringClass()) {
1354 // Special case for java.lang.String.
1355 gc::AllocatorType allocator_type = Runtime::Current()->GetHeap()->GetCurrentAllocator();
jessicahandojo3aaa37b2016-07-29 14:46:37 -07001356 new_object = mirror::String::AllocEmptyString<true>(self, allocator_type);
Sebastien Hertz56d5e502015-11-03 17:38:35 +01001357 } else {
1358 new_object = c->AllocObject(self);
1359 }
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001360 if (new_object == nullptr) {
1361 DCHECK(self->IsExceptionPending());
1362 self->ClearException();
David Sehr709b0702016-10-13 09:12:37 -07001363 LOG(ERROR) << "Could not allocate object of type " << mirror::Class::PrettyDescriptor(c);
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001364 *new_object_id = 0;
1365 return JDWP::ERR_OUT_OF_MEMORY;
1366 }
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001367 *new_object_id = gRegistry->Add(new_object.Ptr());
Elliott Hughes436e3722012-02-17 20:01:47 -08001368 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001369}
1370
Elliott Hughesbf13d362011-12-08 15:51:37 -08001371/*
1372 * Used by Eclipse's "Display" view to evaluate "new byte[5]" to get "(byte[]) [0, 0, 0, 0, 0]".
1373 */
Elliott Hughes88d63092013-01-09 09:55:54 -08001374JDWP::JdwpError Dbg::CreateArrayObject(JDWP::RefTypeId array_class_id, uint32_t length,
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001375 JDWP::ObjectId* new_array_id) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001376 JDWP::JdwpError error;
1377 mirror::Class* c = DecodeClass(array_class_id, &error);
1378 if (c == nullptr) {
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001379 *new_array_id = 0;
Ian Rogersc0542af2014-09-03 16:16:56 -07001380 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001381 }
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001382 Thread* self = Thread::Current();
1383 gc::Heap* heap = Runtime::Current()->GetHeap();
1384 mirror::Array* new_array = mirror::Array::Alloc<true>(self, c, length,
1385 c->GetComponentSizeShift(),
1386 heap->GetCurrentAllocator());
1387 if (new_array == nullptr) {
1388 DCHECK(self->IsExceptionPending());
1389 self->ClearException();
David Sehr709b0702016-10-13 09:12:37 -07001390 LOG(ERROR) << "Could not allocate array of type " << mirror::Class::PrettyDescriptor(c);
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001391 *new_array_id = 0;
1392 return JDWP::ERR_OUT_OF_MEMORY;
1393 }
1394 *new_array_id = gRegistry->Add(new_array);
Elliott Hughes436e3722012-02-17 20:01:47 -08001395 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001396}
1397
Mathieu Chartierc7853442015-03-27 14:35:38 -07001398JDWP::FieldId Dbg::ToFieldId(const ArtField* f) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001399 return static_cast<JDWP::FieldId>(reinterpret_cast<uintptr_t>(f));
Elliott Hughes03181a82011-11-17 17:22:21 -08001400}
1401
Alex Light6c8467f2015-11-20 15:03:26 -08001402static JDWP::MethodId ToMethodId(ArtMethod* m)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001403 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light97e78032017-06-27 17:51:55 -07001404 return static_cast<JDWP::MethodId>(
1405 reinterpret_cast<uintptr_t>(m->GetCanonicalMethod(kRuntimePointerSize)));
Elliott Hughes03181a82011-11-17 17:22:21 -08001406}
1407
Mathieu Chartierc7853442015-03-27 14:35:38 -07001408static ArtField* FromFieldId(JDWP::FieldId fid)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001409 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001410 return reinterpret_cast<ArtField*>(static_cast<uintptr_t>(fid));
Elliott Hughesaed4be92011-12-02 16:16:23 -08001411}
1412
Mathieu Chartiere401d142015-04-22 13:56:20 -07001413static ArtMethod* FromMethodId(JDWP::MethodId mid)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001414 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001415 return reinterpret_cast<ArtMethod*>(static_cast<uintptr_t>(mid));
Elliott Hughes03181a82011-11-17 17:22:21 -08001416}
1417
Sebastien Hertz6995c602014-09-09 12:10:13 +02001418bool Dbg::MatchThread(JDWP::ObjectId expected_thread_id, Thread* event_thread) {
1419 CHECK(event_thread != nullptr);
1420 JDWP::JdwpError error;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001421 mirror::Object* expected_thread_peer = gRegistry->Get<mirror::Object*>(
1422 expected_thread_id, &error);
Nicolas Geoffraycafa0812017-02-15 18:27:34 +00001423 return expected_thread_peer == event_thread->GetPeerFromOtherThread();
Sebastien Hertz6995c602014-09-09 12:10:13 +02001424}
1425
1426bool Dbg::MatchLocation(const JDWP::JdwpLocation& expected_location,
1427 const JDWP::EventLocation& event_location) {
1428 if (expected_location.dex_pc != event_location.dex_pc) {
1429 return false;
1430 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001431 ArtMethod* m = FromMethodId(expected_location.method_id);
Sebastien Hertz6995c602014-09-09 12:10:13 +02001432 return m == event_location.method;
1433}
1434
Mathieu Chartier3398c782016-09-30 10:27:43 -07001435bool Dbg::MatchType(ObjPtr<mirror::Class> event_class, JDWP::RefTypeId class_id) {
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001436 if (event_class == nullptr) {
1437 return false;
1438 }
Sebastien Hertz6995c602014-09-09 12:10:13 +02001439 JDWP::JdwpError error;
Mathieu Chartier3398c782016-09-30 10:27:43 -07001440 ObjPtr<mirror::Class> expected_class = DecodeClass(class_id, &error);
Sebastien Hertz6995c602014-09-09 12:10:13 +02001441 CHECK(expected_class != nullptr);
1442 return expected_class->IsAssignableFrom(event_class);
1443}
1444
1445bool Dbg::MatchField(JDWP::RefTypeId expected_type_id, JDWP::FieldId expected_field_id,
Mathieu Chartierc7853442015-03-27 14:35:38 -07001446 ArtField* event_field) {
1447 ArtField* expected_field = FromFieldId(expected_field_id);
Sebastien Hertz6995c602014-09-09 12:10:13 +02001448 if (expected_field != event_field) {
1449 return false;
1450 }
1451 return Dbg::MatchType(event_field->GetDeclaringClass(), expected_type_id);
1452}
1453
1454bool Dbg::MatchInstance(JDWP::ObjectId expected_instance_id, mirror::Object* event_instance) {
1455 JDWP::JdwpError error;
1456 mirror::Object* modifier_instance = gRegistry->Get<mirror::Object*>(expected_instance_id, &error);
1457 return modifier_instance == event_instance;
1458}
1459
Mathieu Chartier90443472015-07-16 20:32:27 -07001460void Dbg::SetJdwpLocation(JDWP::JdwpLocation* location, ArtMethod* m, uint32_t dex_pc) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001461 if (m == nullptr) {
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001462 memset(location, 0, sizeof(*location));
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001463 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001464 mirror::Class* c = m->GetDeclaringClass();
Ian Rogersc0542af2014-09-03 16:16:56 -07001465 location->type_tag = GetTypeTag(c);
1466 location->class_id = gRegistry->AddRefType(c);
Alex Light73376312017-04-06 10:10:51 -07001467 // The RI Seems to return 0 for all obsolete methods. For compatibility we shall do the same.
1468 location->method_id = m->IsObsolete() ? 0 : ToMethodId(m);
Ian Rogersc0542af2014-09-03 16:16:56 -07001469 location->dex_pc = (m->IsNative() || m->IsProxyMethod()) ? static_cast<uint64_t>(-1) : dex_pc;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001470 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08001471}
1472
Ian Rogersc0542af2014-09-03 16:16:56 -07001473std::string Dbg::GetMethodName(JDWP::MethodId method_id) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001474 ArtMethod* m = FromMethodId(method_id);
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001475 if (m == nullptr) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001476 return "null";
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001477 }
Andreas Gampe542451c2016-07-26 09:02:02 -07001478 return m->GetInterfaceMethodIfProxy(kRuntimePointerSize)->GetName();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001479}
1480
Alex Light73376312017-04-06 10:10:51 -07001481bool Dbg::IsMethodObsolete(JDWP::MethodId method_id) {
1482 ArtMethod* m = FromMethodId(method_id);
1483 if (m == nullptr) {
1484 // NB Since we return 0 as MID for obsolete methods we want to default to true here.
1485 return true;
1486 }
1487 return m->IsObsolete();
1488}
1489
Ian Rogersc0542af2014-09-03 16:16:56 -07001490std::string Dbg::GetFieldName(JDWP::FieldId field_id) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001491 ArtField* f = FromFieldId(field_id);
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001492 if (f == nullptr) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001493 return "null";
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001494 }
1495 return f->GetName();
Elliott Hughesa96836a2013-01-17 12:27:49 -08001496}
1497
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001498/*
1499 * Augment the access flags for synthetic methods and fields by setting
1500 * the (as described by the spec) "0xf0000000 bit". Also, strip out any
1501 * flags not specified by the Java programming language.
1502 */
1503static uint32_t MangleAccessFlags(uint32_t accessFlags) {
1504 accessFlags &= kAccJavaFlagsMask;
1505 if ((accessFlags & kAccSynthetic) != 0) {
1506 accessFlags |= 0xf0000000;
1507 }
1508 return accessFlags;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001509}
1510
Elliott Hughesdbb40792011-11-18 17:05:22 -08001511/*
Jeff Haob7cefc72013-11-14 14:51:09 -08001512 * Circularly shifts registers so that arguments come first. Debuggers
1513 * expect slots to begin with arguments, but dex code places them at
1514 * the end.
Elliott Hughesdbb40792011-11-18 17:05:22 -08001515 */
Mathieu Chartiere401d142015-04-22 13:56:20 -07001516static uint16_t MangleSlot(uint16_t slot, ArtMethod* m)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001517 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001518 const DexFile::CodeItem* code_item = m->GetCodeItem();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001519 if (code_item == nullptr) {
1520 // We should not get here for a method without code (native, proxy or abstract). Log it and
1521 // return the slot as is since all registers are arguments.
David Sehr709b0702016-10-13 09:12:37 -07001522 LOG(WARNING) << "Trying to mangle slot for method without code " << m->PrettyMethod();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001523 return slot;
1524 }
Jeff Haob7cefc72013-11-14 14:51:09 -08001525 uint16_t ins_size = code_item->ins_size_;
1526 uint16_t locals_size = code_item->registers_size_ - ins_size;
1527 if (slot >= locals_size) {
1528 return slot - locals_size;
1529 } else {
1530 return slot + ins_size;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001531 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001532}
1533
Sebastien Hertzaef0c912016-08-08 10:20:28 +02001534static size_t GetMethodNumArgRegistersIncludingThis(ArtMethod* method)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001535 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertzaef0c912016-08-08 10:20:28 +02001536 uint32_t num_registers = ArtMethod::NumArgRegisters(method->GetShorty());
1537 if (!method->IsStatic()) {
1538 ++num_registers;
1539 }
1540 return num_registers;
1541}
1542
Jeff Haob7cefc72013-11-14 14:51:09 -08001543/*
1544 * Circularly shifts registers so that arguments come last. Reverts
1545 * slots to dex style argument placement.
1546 */
Mathieu Chartiere401d142015-04-22 13:56:20 -07001547static uint16_t DemangleSlot(uint16_t slot, ArtMethod* m, JDWP::JdwpError* error)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001548 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001549 const DexFile::CodeItem* code_item = m->GetCodeItem();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001550 if (code_item == nullptr) {
1551 // We should not get here for a method without code (native, proxy or abstract). Log it and
1552 // return the slot as is since all registers are arguments.
David Sehr709b0702016-10-13 09:12:37 -07001553 LOG(WARNING) << "Trying to demangle slot for method without code "
1554 << m->PrettyMethod();
Sebastien Hertzaef0c912016-08-08 10:20:28 +02001555 uint16_t vreg_count = GetMethodNumArgRegistersIncludingThis(m);
Sebastien Hertzabbabc82015-03-26 08:47:47 +01001556 if (slot < vreg_count) {
1557 *error = JDWP::ERR_NONE;
1558 return slot;
1559 }
Jeff Haob7cefc72013-11-14 14:51:09 -08001560 } else {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01001561 if (slot < code_item->registers_size_) {
1562 uint16_t ins_size = code_item->ins_size_;
1563 uint16_t locals_size = code_item->registers_size_ - ins_size;
1564 *error = JDWP::ERR_NONE;
1565 return (slot < ins_size) ? slot + locals_size : slot - ins_size;
1566 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001567 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01001568
1569 // Slot is invalid in the method.
David Sehr709b0702016-10-13 09:12:37 -07001570 LOG(ERROR) << "Invalid local slot " << slot << " for method " << m->PrettyMethod();
Sebastien Hertzabbabc82015-03-26 08:47:47 +01001571 *error = JDWP::ERR_INVALID_SLOT;
1572 return DexFile::kDexNoIndex16;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001573}
1574
Mathieu Chartier90443472015-07-16 20:32:27 -07001575JDWP::JdwpError Dbg::OutputDeclaredFields(JDWP::RefTypeId class_id, bool with_generic,
1576 JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001577 JDWP::JdwpError error;
1578 mirror::Class* c = DecodeClass(class_id, &error);
1579 if (c == nullptr) {
1580 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001581 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001582
1583 size_t instance_field_count = c->NumInstanceFields();
1584 size_t static_field_count = c->NumStaticFields();
1585
1586 expandBufAdd4BE(pReply, instance_field_count + static_field_count);
1587
1588 for (size_t i = 0; i < instance_field_count + static_field_count; ++i) {
Mathieu Chartier90443472015-07-16 20:32:27 -07001589 ArtField* f = (i < instance_field_count) ? c->GetInstanceField(i) :
1590 c->GetStaticField(i - instance_field_count);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001591 expandBufAddFieldId(pReply, ToFieldId(f));
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001592 expandBufAddUtf8String(pReply, f->GetName());
1593 expandBufAddUtf8String(pReply, f->GetTypeDescriptor());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001594 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001595 static const char genericSignature[1] = "";
1596 expandBufAddUtf8String(pReply, genericSignature);
1597 }
1598 expandBufAdd4BE(pReply, MangleAccessFlags(f->GetAccessFlags()));
1599 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001600 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001601}
1602
Elliott Hughes88d63092013-01-09 09:55:54 -08001603JDWP::JdwpError Dbg::OutputDeclaredMethods(JDWP::RefTypeId class_id, bool with_generic,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001604 JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001605 JDWP::JdwpError error;
1606 mirror::Class* c = DecodeClass(class_id, &error);
1607 if (c == nullptr) {
1608 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001609 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001610
Alex Light51a64d52015-12-17 13:55:59 -08001611 expandBufAdd4BE(pReply, c->NumMethods());
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001612
Mathieu Chartiere401d142015-04-22 13:56:20 -07001613 auto* cl = Runtime::Current()->GetClassLinker();
1614 auto ptr_size = cl->GetImagePointerSize();
Alex Light51a64d52015-12-17 13:55:59 -08001615 for (ArtMethod& m : c->GetMethods(ptr_size)) {
1616 expandBufAddMethodId(pReply, ToMethodId(&m));
Andreas Gampe542451c2016-07-26 09:02:02 -07001617 expandBufAddUtf8String(pReply, m.GetInterfaceMethodIfProxy(kRuntimePointerSize)->GetName());
1618 expandBufAddUtf8String(
1619 pReply, m.GetInterfaceMethodIfProxy(kRuntimePointerSize)->GetSignature().ToString());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001620 if (with_generic) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001621 const char* generic_signature = "";
1622 expandBufAddUtf8String(pReply, generic_signature);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001623 }
Alex Light51a64d52015-12-17 13:55:59 -08001624 expandBufAdd4BE(pReply, MangleAccessFlags(m.GetAccessFlags()));
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001625 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001626 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001627}
1628
Elliott Hughes88d63092013-01-09 09:55:54 -08001629JDWP::JdwpError Dbg::OutputDeclaredInterfaces(JDWP::RefTypeId class_id, JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001630 JDWP::JdwpError error;
Mathieu Chartierf8322842014-05-16 10:59:25 -07001631 Thread* self = Thread::Current();
Vladimir Marko19a4d372016-12-08 14:41:46 +00001632 ObjPtr<mirror::Class> c = DecodeClass(class_id, &error);
1633 if (c == nullptr) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001634 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001635 }
Mathieu Chartierf8322842014-05-16 10:59:25 -07001636 size_t interface_count = c->NumDirectInterfaces();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001637 expandBufAdd4BE(pReply, interface_count);
1638 for (size_t i = 0; i < interface_count; ++i) {
Vladimir Marko19a4d372016-12-08 14:41:46 +00001639 ObjPtr<mirror::Class> interface = mirror::Class::GetDirectInterface(self, c, i);
1640 DCHECK(interface != nullptr);
1641 expandBufAddRefTypeId(pReply, gRegistry->AddRefType(interface));
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001642 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001643 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001644}
1645
Ian Rogersc0542af2014-09-03 16:16:56 -07001646void Dbg::OutputLineTable(JDWP::RefTypeId, JDWP::MethodId method_id, JDWP::ExpandBuf* pReply) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001647 struct DebugCallbackContext {
1648 int numItems;
1649 JDWP::ExpandBuf* pReply;
1650
David Srbeckyb06e28e2015-12-10 13:15:00 +00001651 static bool Callback(void* context, const DexFile::PositionInfo& entry) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001652 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
David Srbeckyb06e28e2015-12-10 13:15:00 +00001653 expandBufAdd8BE(pContext->pReply, entry.address_);
1654 expandBufAdd4BE(pContext->pReply, entry.line_);
Elliott Hughes03181a82011-11-17 17:22:21 -08001655 pContext->numItems++;
Sebastien Hertzf2910ee2013-10-19 16:39:24 +02001656 return false;
Elliott Hughes03181a82011-11-17 17:22:21 -08001657 }
1658 };
Mathieu Chartiere401d142015-04-22 13:56:20 -07001659 ArtMethod* m = FromMethodId(method_id);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001660 const DexFile::CodeItem* code_item = m->GetCodeItem();
Elliott Hughes03181a82011-11-17 17:22:21 -08001661 uint64_t start, end;
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001662 if (code_item == nullptr) {
1663 DCHECK(m->IsNative() || m->IsProxyMethod());
Elliott Hughes03181a82011-11-17 17:22:21 -08001664 start = -1;
1665 end = -1;
1666 } else {
1667 start = 0;
jeffhao14f0db92012-12-14 17:50:42 -08001668 // Return the index of the last instruction
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001669 end = code_item->insns_size_in_code_units_ - 1;
Elliott Hughes03181a82011-11-17 17:22:21 -08001670 }
1671
1672 expandBufAdd8BE(pReply, start);
1673 expandBufAdd8BE(pReply, end);
1674
1675 // Add numLines later
1676 size_t numLinesOffset = expandBufGetLength(pReply);
1677 expandBufAdd4BE(pReply, 0);
1678
1679 DebugCallbackContext context;
1680 context.numItems = 0;
1681 context.pReply = pReply;
1682
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001683 if (code_item != nullptr) {
Nicolas Geoffray58cc1cb2017-11-20 13:27:29 +00001684 uint32_t debug_info_offset = OatFile::GetDebugInfoOffset(*(m->GetDexFile()), code_item);
1685 m->GetDexFile()->DecodeDebugPositionInfo(
1686 code_item, debug_info_offset, DebugCallbackContext::Callback, &context);
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001687 }
Elliott Hughes03181a82011-11-17 17:22:21 -08001688
1689 JDWP::Set4BE(expandBufGetBuffer(pReply) + numLinesOffset, context.numItems);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001690}
1691
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001692void Dbg::OutputVariableTable(JDWP::RefTypeId, JDWP::MethodId method_id, bool with_generic,
1693 JDWP::ExpandBuf* pReply) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001694 struct DebugCallbackContext {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001695 ArtMethod* method;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001696 JDWP::ExpandBuf* pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001697 size_t variable_count;
1698 bool with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001699
David Srbeckyb06e28e2015-12-10 13:15:00 +00001700 static void Callback(void* context, const DexFile::LocalInfo& entry)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001701 REQUIRES_SHARED(Locks::mutator_lock_) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001702 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
1703
David Srbeckyb06e28e2015-12-10 13:15:00 +00001704 uint16_t slot = entry.reg_;
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001705 VLOG(jdwp) << StringPrintf(" %2zd: %d(%d) '%s' '%s' '%s' actual slot=%d mangled slot=%d",
David Srbeckyb06e28e2015-12-10 13:15:00 +00001706 pContext->variable_count, entry.start_address_,
1707 entry.end_address_ - entry.start_address_,
1708 entry.name_, entry.descriptor_, entry.signature_, slot,
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001709 MangleSlot(slot, pContext->method));
Elliott Hughesdbb40792011-11-18 17:05:22 -08001710
Jeff Haob7cefc72013-11-14 14:51:09 -08001711 slot = MangleSlot(slot, pContext->method);
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001712
David Srbeckyb06e28e2015-12-10 13:15:00 +00001713 expandBufAdd8BE(pContext->pReply, entry.start_address_);
1714 expandBufAddUtf8String(pContext->pReply, entry.name_);
1715 expandBufAddUtf8String(pContext->pReply, entry.descriptor_);
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001716 if (pContext->with_generic) {
David Srbeckyb06e28e2015-12-10 13:15:00 +00001717 expandBufAddUtf8String(pContext->pReply, entry.signature_);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001718 }
David Srbeckyb06e28e2015-12-10 13:15:00 +00001719 expandBufAdd4BE(pContext->pReply, entry.end_address_- entry.start_address_);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001720 expandBufAdd4BE(pContext->pReply, slot);
1721
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001722 ++pContext->variable_count;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001723 }
1724 };
Mathieu Chartiere401d142015-04-22 13:56:20 -07001725 ArtMethod* m = FromMethodId(method_id);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001726
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001727 // arg_count considers doubles and longs to take 2 units.
1728 // variable_count considers everything to take 1 unit.
Sebastien Hertzaef0c912016-08-08 10:20:28 +02001729 expandBufAdd4BE(pReply, GetMethodNumArgRegistersIncludingThis(m));
Elliott Hughesdbb40792011-11-18 17:05:22 -08001730
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001731 // We don't know the total number of variables yet, so leave a blank and update it later.
1732 size_t variable_count_offset = expandBufGetLength(pReply);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001733 expandBufAdd4BE(pReply, 0);
1734
1735 DebugCallbackContext context;
Jeff Haob7cefc72013-11-14 14:51:09 -08001736 context.method = m;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001737 context.pReply = pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001738 context.variable_count = 0;
1739 context.with_generic = with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001740
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001741 const DexFile::CodeItem* code_item = m->GetCodeItem();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001742 if (code_item != nullptr) {
Nicolas Geoffray58cc1cb2017-11-20 13:27:29 +00001743 uint32_t debug_info_offset = OatFile::GetDebugInfoOffset(*(m->GetDexFile()), code_item);
David Srbeckyb06e28e2015-12-10 13:15:00 +00001744 m->GetDexFile()->DecodeDebugLocalInfo(
Nicolas Geoffray58cc1cb2017-11-20 13:27:29 +00001745 code_item, debug_info_offset, m->IsStatic(), m->GetDexMethodIndex(),
1746 DebugCallbackContext::Callback, &context);
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001747 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001748
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001749 JDWP::Set4BE(expandBufGetBuffer(pReply) + variable_count_offset, context.variable_count);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001750}
1751
Jeff Hao579b0242013-11-18 13:16:49 -08001752void Dbg::OutputMethodReturnValue(JDWP::MethodId method_id, const JValue* return_value,
1753 JDWP::ExpandBuf* pReply) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001754 ArtMethod* m = FromMethodId(method_id);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001755 JDWP::JdwpTag tag = BasicTagFromDescriptor(m->GetShorty());
Jeff Hao579b0242013-11-18 13:16:49 -08001756 OutputJValue(tag, return_value, pReply);
1757}
1758
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02001759void Dbg::OutputFieldValue(JDWP::FieldId field_id, const JValue* field_value,
1760 JDWP::ExpandBuf* pReply) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001761 ArtField* f = FromFieldId(field_id);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001762 JDWP::JdwpTag tag = BasicTagFromDescriptor(f->GetTypeDescriptor());
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02001763 OutputJValue(tag, field_value, pReply);
1764}
1765
Elliott Hughes9777ba22013-01-17 09:04:19 -08001766JDWP::JdwpError Dbg::GetBytecodes(JDWP::RefTypeId, JDWP::MethodId method_id,
Ian Rogersc0542af2014-09-03 16:16:56 -07001767 std::vector<uint8_t>* bytecodes) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001768 ArtMethod* m = FromMethodId(method_id);
Ian Rogersc0542af2014-09-03 16:16:56 -07001769 if (m == nullptr) {
Elliott Hughes9777ba22013-01-17 09:04:19 -08001770 return JDWP::ERR_INVALID_METHODID;
1771 }
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001772 const DexFile::CodeItem* code_item = m->GetCodeItem();
Elliott Hughes9777ba22013-01-17 09:04:19 -08001773 size_t byte_count = code_item->insns_size_in_code_units_ * 2;
1774 const uint8_t* begin = reinterpret_cast<const uint8_t*>(code_item->insns_);
1775 const uint8_t* end = begin + byte_count;
1776 for (const uint8_t* p = begin; p != end; ++p) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001777 bytecodes->push_back(*p);
Elliott Hughes9777ba22013-01-17 09:04:19 -08001778 }
1779 return JDWP::ERR_NONE;
1780}
1781
Elliott Hughes88d63092013-01-09 09:55:54 -08001782JDWP::JdwpTag Dbg::GetFieldBasicTag(JDWP::FieldId field_id) {
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001783 return BasicTagFromDescriptor(FromFieldId(field_id)->GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001784}
1785
Elliott Hughes88d63092013-01-09 09:55:54 -08001786JDWP::JdwpTag Dbg::GetStaticFieldBasicTag(JDWP::FieldId field_id) {
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001787 return BasicTagFromDescriptor(FromFieldId(field_id)->GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001788}
1789
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001790static JValue GetArtFieldValue(ArtField* f, mirror::Object* o)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001791 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001792 Primitive::Type fieldType = f->GetTypeAsPrimitiveType();
1793 JValue field_value;
1794 switch (fieldType) {
1795 case Primitive::kPrimBoolean:
1796 field_value.SetZ(f->GetBoolean(o));
1797 return field_value;
1798
1799 case Primitive::kPrimByte:
1800 field_value.SetB(f->GetByte(o));
1801 return field_value;
1802
1803 case Primitive::kPrimChar:
1804 field_value.SetC(f->GetChar(o));
1805 return field_value;
1806
1807 case Primitive::kPrimShort:
1808 field_value.SetS(f->GetShort(o));
1809 return field_value;
1810
1811 case Primitive::kPrimInt:
1812 case Primitive::kPrimFloat:
1813 // Int and Float must be treated as 32-bit values in JDWP.
1814 field_value.SetI(f->GetInt(o));
1815 return field_value;
1816
1817 case Primitive::kPrimLong:
1818 case Primitive::kPrimDouble:
1819 // Long and Double must be treated as 64-bit values in JDWP.
1820 field_value.SetJ(f->GetLong(o));
1821 return field_value;
1822
1823 case Primitive::kPrimNot:
Mathieu Chartier1cc62e42016-10-03 18:01:28 -07001824 field_value.SetL(f->GetObject(o).Ptr());
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001825 return field_value;
1826
1827 case Primitive::kPrimVoid:
1828 LOG(FATAL) << "Attempt to read from field of type 'void'";
1829 UNREACHABLE();
1830 }
1831 LOG(FATAL) << "Attempt to read from field of unknown type";
1832 UNREACHABLE();
1833}
1834
Elliott Hughes88d63092013-01-09 09:55:54 -08001835static JDWP::JdwpError GetFieldValueImpl(JDWP::RefTypeId ref_type_id, JDWP::ObjectId object_id,
1836 JDWP::FieldId field_id, JDWP::ExpandBuf* pReply,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001837 bool is_static)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001838 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001839 JDWP::JdwpError error;
1840 mirror::Class* c = DecodeClass(ref_type_id, &error);
1841 if (ref_type_id != 0 && c == nullptr) {
1842 return error;
Elliott Hughes0cf74332012-02-23 23:14:00 -08001843 }
1844
Jeff Haode19a252016-09-14 15:56:35 -07001845 Thread* self = Thread::Current();
1846 StackHandleScope<2> hs(self);
1847 MutableHandle<mirror::Object>
1848 o(hs.NewHandle(Dbg::GetObjectRegistry()->Get<mirror::Object*>(object_id, &error)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08001849 if ((!is_static && o == nullptr) || error != JDWP::ERR_NONE) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001850 return JDWP::ERR_INVALID_OBJECT;
1851 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001852 ArtField* f = FromFieldId(field_id);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001853
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001854 mirror::Class* receiver_class = c;
Andreas Gampefa4333d2017-02-14 11:10:34 -08001855 if (receiver_class == nullptr && o != nullptr) {
Elliott Hughes0cf74332012-02-23 23:14:00 -08001856 receiver_class = o->GetClass();
1857 }
Jeff Haode19a252016-09-14 15:56:35 -07001858
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001859 // TODO: should we give up now if receiver_class is null?
Ian Rogersc0542af2014-09-03 16:16:56 -07001860 if (receiver_class != nullptr && !f->GetDeclaringClass()->IsAssignableFrom(receiver_class)) {
David Sehr709b0702016-10-13 09:12:37 -07001861 LOG(INFO) << "ERR_INVALID_FIELDID: " << f->PrettyField() << " "
1862 << receiver_class->PrettyClass();
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001863 return JDWP::ERR_INVALID_FIELDID;
1864 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001865
Jeff Haode19a252016-09-14 15:56:35 -07001866 // Ensure the field's class is initialized.
1867 Handle<mirror::Class> klass(hs.NewHandle(f->GetDeclaringClass()));
1868 if (!Runtime::Current()->GetClassLinker()->EnsureInitialized(self, klass, true, false)) {
David Sehr709b0702016-10-13 09:12:37 -07001869 LOG(WARNING) << "Not able to initialize class for SetValues: "
1870 << mirror::Class::PrettyClass(klass.Get());
Jeff Haode19a252016-09-14 15:56:35 -07001871 }
1872
Elliott Hughes0cf74332012-02-23 23:14:00 -08001873 // The RI only enforces the static/non-static mismatch in one direction.
1874 // TODO: should we change the tests and check both?
1875 if (is_static) {
1876 if (!f->IsStatic()) {
1877 return JDWP::ERR_INVALID_FIELDID;
1878 }
1879 } else {
1880 if (f->IsStatic()) {
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001881 LOG(WARNING) << "Ignoring non-nullptr receiver for ObjectReference.GetValues"
David Sehr709b0702016-10-13 09:12:37 -07001882 << " on static field " << f->PrettyField();
Elliott Hughes0cf74332012-02-23 23:14:00 -08001883 }
1884 }
jeffhao0dfbb7e2012-11-28 15:26:03 -08001885 if (f->IsStatic()) {
Jeff Haode19a252016-09-14 15:56:35 -07001886 o.Assign(f->GetDeclaringClass());
jeffhao0dfbb7e2012-11-28 15:26:03 -08001887 }
Elliott Hughes0cf74332012-02-23 23:14:00 -08001888
Jeff Haode19a252016-09-14 15:56:35 -07001889 JValue field_value(GetArtFieldValue(f, o.Get()));
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001890 JDWP::JdwpTag tag = BasicTagFromDescriptor(f->GetTypeDescriptor());
Jeff Hao579b0242013-11-18 13:16:49 -08001891 Dbg::OutputJValue(tag, &field_value, pReply);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001892 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001893}
1894
Elliott Hughes88d63092013-01-09 09:55:54 -08001895JDWP::JdwpError Dbg::GetFieldValue(JDWP::ObjectId object_id, JDWP::FieldId field_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001896 JDWP::ExpandBuf* pReply) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001897 return GetFieldValueImpl(0, object_id, field_id, pReply, false);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001898}
1899
Ian Rogersc0542af2014-09-03 16:16:56 -07001900JDWP::JdwpError Dbg::GetStaticFieldValue(JDWP::RefTypeId ref_type_id, JDWP::FieldId field_id,
1901 JDWP::ExpandBuf* pReply) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001902 return GetFieldValueImpl(ref_type_id, 0, field_id, pReply, true);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001903}
1904
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001905static JDWP::JdwpError SetArtFieldValue(ArtField* f, mirror::Object* o, uint64_t value, int width)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001906 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001907 Primitive::Type fieldType = f->GetTypeAsPrimitiveType();
1908 // Debugging only happens at runtime so we know we are not running in a transaction.
1909 static constexpr bool kNoTransactionMode = false;
1910 switch (fieldType) {
1911 case Primitive::kPrimBoolean:
1912 CHECK_EQ(width, 1);
1913 f->SetBoolean<kNoTransactionMode>(o, static_cast<uint8_t>(value));
1914 return JDWP::ERR_NONE;
1915
1916 case Primitive::kPrimByte:
1917 CHECK_EQ(width, 1);
1918 f->SetByte<kNoTransactionMode>(o, static_cast<uint8_t>(value));
1919 return JDWP::ERR_NONE;
1920
1921 case Primitive::kPrimChar:
1922 CHECK_EQ(width, 2);
1923 f->SetChar<kNoTransactionMode>(o, static_cast<uint16_t>(value));
1924 return JDWP::ERR_NONE;
1925
1926 case Primitive::kPrimShort:
1927 CHECK_EQ(width, 2);
1928 f->SetShort<kNoTransactionMode>(o, static_cast<int16_t>(value));
1929 return JDWP::ERR_NONE;
1930
1931 case Primitive::kPrimInt:
1932 case Primitive::kPrimFloat:
1933 CHECK_EQ(width, 4);
1934 // Int and Float must be treated as 32-bit values in JDWP.
1935 f->SetInt<kNoTransactionMode>(o, static_cast<int32_t>(value));
1936 return JDWP::ERR_NONE;
1937
1938 case Primitive::kPrimLong:
1939 case Primitive::kPrimDouble:
1940 CHECK_EQ(width, 8);
1941 // Long and Double must be treated as 64-bit values in JDWP.
1942 f->SetLong<kNoTransactionMode>(o, value);
1943 return JDWP::ERR_NONE;
1944
1945 case Primitive::kPrimNot: {
1946 JDWP::JdwpError error;
1947 mirror::Object* v = Dbg::GetObjectRegistry()->Get<mirror::Object*>(value, &error);
1948 if (error != JDWP::ERR_NONE) {
1949 return JDWP::ERR_INVALID_OBJECT;
1950 }
1951 if (v != nullptr) {
Mathieu Chartier3398c782016-09-30 10:27:43 -07001952 ObjPtr<mirror::Class> field_type;
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001953 {
1954 StackHandleScope<2> hs(Thread::Current());
1955 HandleWrapper<mirror::Object> h_v(hs.NewHandleWrapper(&v));
1956 HandleWrapper<mirror::Object> h_o(hs.NewHandleWrapper(&o));
Vladimir Marko4098a7a2017-11-06 16:00:51 +00001957 field_type = f->ResolveType();
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001958 }
1959 if (!field_type->IsAssignableFrom(v->GetClass())) {
1960 return JDWP::ERR_INVALID_OBJECT;
1961 }
1962 }
1963 f->SetObject<kNoTransactionMode>(o, v);
1964 return JDWP::ERR_NONE;
1965 }
1966
1967 case Primitive::kPrimVoid:
1968 LOG(FATAL) << "Attempt to write to field of type 'void'";
1969 UNREACHABLE();
1970 }
1971 LOG(FATAL) << "Attempt to write to field of unknown type";
1972 UNREACHABLE();
1973}
1974
Elliott Hughes88d63092013-01-09 09:55:54 -08001975static JDWP::JdwpError SetFieldValueImpl(JDWP::ObjectId object_id, JDWP::FieldId field_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001976 uint64_t value, int width, bool is_static)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001977 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001978 JDWP::JdwpError error;
Jeff Haode19a252016-09-14 15:56:35 -07001979 Thread* self = Thread::Current();
1980 StackHandleScope<2> hs(self);
1981 MutableHandle<mirror::Object>
1982 o(hs.NewHandle(Dbg::GetObjectRegistry()->Get<mirror::Object*>(object_id, &error)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08001983 if ((!is_static && o == nullptr) || error != JDWP::ERR_NONE) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001984 return JDWP::ERR_INVALID_OBJECT;
1985 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001986 ArtField* f = FromFieldId(field_id);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001987
Jeff Haode19a252016-09-14 15:56:35 -07001988 // Ensure the field's class is initialized.
1989 Handle<mirror::Class> klass(hs.NewHandle(f->GetDeclaringClass()));
1990 if (!Runtime::Current()->GetClassLinker()->EnsureInitialized(self, klass, true, false)) {
David Sehr709b0702016-10-13 09:12:37 -07001991 LOG(WARNING) << "Not able to initialize class for SetValues: "
1992 << mirror::Class::PrettyClass(klass.Get());
Jeff Haode19a252016-09-14 15:56:35 -07001993 }
1994
Elliott Hughes0cf74332012-02-23 23:14:00 -08001995 // The RI only enforces the static/non-static mismatch in one direction.
1996 // TODO: should we change the tests and check both?
1997 if (is_static) {
1998 if (!f->IsStatic()) {
1999 return JDWP::ERR_INVALID_FIELDID;
2000 }
2001 } else {
2002 if (f->IsStatic()) {
Sebastien Hertz05c26b32015-06-11 18:42:58 +02002003 LOG(WARNING) << "Ignoring non-nullptr receiver for ObjectReference.SetValues"
David Sehr709b0702016-10-13 09:12:37 -07002004 << " on static field " << f->PrettyField();
Elliott Hughes0cf74332012-02-23 23:14:00 -08002005 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002006 }
jeffhao0dfbb7e2012-11-28 15:26:03 -08002007 if (f->IsStatic()) {
Jeff Haode19a252016-09-14 15:56:35 -07002008 o.Assign(f->GetDeclaringClass());
jeffhao0dfbb7e2012-11-28 15:26:03 -08002009 }
Jeff Haode19a252016-09-14 15:56:35 -07002010 return SetArtFieldValue(f, o.Get(), value, width);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002011}
2012
Elliott Hughes88d63092013-01-09 09:55:54 -08002013JDWP::JdwpError Dbg::SetFieldValue(JDWP::ObjectId object_id, JDWP::FieldId field_id, uint64_t value,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002014 int width) {
Elliott Hughes88d63092013-01-09 09:55:54 -08002015 return SetFieldValueImpl(object_id, field_id, value, width, false);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002016}
2017
Elliott Hughes88d63092013-01-09 09:55:54 -08002018JDWP::JdwpError Dbg::SetStaticFieldValue(JDWP::FieldId field_id, uint64_t value, int width) {
2019 return SetFieldValueImpl(0, field_id, value, width, true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002020}
2021
Sebastien Hertzb0b0b492014-09-15 11:27:27 +02002022JDWP::JdwpError Dbg::StringToUtf8(JDWP::ObjectId string_id, std::string* str) {
Ian Rogersc0542af2014-09-03 16:16:56 -07002023 JDWP::JdwpError error;
Sebastien Hertzb0b0b492014-09-15 11:27:27 +02002024 mirror::Object* obj = gRegistry->Get<mirror::Object*>(string_id, &error);
2025 if (error != JDWP::ERR_NONE) {
2026 return error;
2027 }
2028 if (obj == nullptr) {
2029 return JDWP::ERR_INVALID_OBJECT;
2030 }
2031 {
2032 ScopedObjectAccessUnchecked soa(Thread::Current());
Mathieu Chartier0795f232016-09-27 18:43:30 -07002033 ObjPtr<mirror::Class> java_lang_String =
2034 soa.Decode<mirror::Class>(WellKnownClasses::java_lang_String);
Sebastien Hertzb0b0b492014-09-15 11:27:27 +02002035 if (!java_lang_String->IsAssignableFrom(obj->GetClass())) {
2036 // This isn't a string.
2037 return JDWP::ERR_INVALID_STRING;
2038 }
2039 }
2040 *str = obj->AsString()->ToModifiedUtf8();
2041 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002042}
2043
Jeff Hao579b0242013-11-18 13:16:49 -08002044void Dbg::OutputJValue(JDWP::JdwpTag tag, const JValue* return_value, JDWP::ExpandBuf* pReply) {
2045 if (IsPrimitiveTag(tag)) {
2046 expandBufAdd1(pReply, tag);
2047 if (tag == JDWP::JT_BOOLEAN || tag == JDWP::JT_BYTE) {
2048 expandBufAdd1(pReply, return_value->GetI());
2049 } else if (tag == JDWP::JT_CHAR || tag == JDWP::JT_SHORT) {
2050 expandBufAdd2BE(pReply, return_value->GetI());
2051 } else if (tag == JDWP::JT_FLOAT || tag == JDWP::JT_INT) {
2052 expandBufAdd4BE(pReply, return_value->GetI());
2053 } else if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
2054 expandBufAdd8BE(pReply, return_value->GetJ());
2055 } else {
2056 CHECK_EQ(tag, JDWP::JT_VOID);
2057 }
2058 } else {
Ian Rogers98379392014-02-24 16:53:16 -08002059 ScopedObjectAccessUnchecked soa(Thread::Current());
Jeff Hao579b0242013-11-18 13:16:49 -08002060 mirror::Object* value = return_value->GetL();
Ian Rogers98379392014-02-24 16:53:16 -08002061 expandBufAdd1(pReply, TagFromObject(soa, value));
Jeff Hao579b0242013-11-18 13:16:49 -08002062 expandBufAddObjectId(pReply, gRegistry->Add(value));
2063 }
2064}
2065
Ian Rogersc0542af2014-09-03 16:16:56 -07002066JDWP::JdwpError Dbg::GetThreadName(JDWP::ObjectId thread_id, std::string* name) {
jeffhaoa77f0f62012-12-05 17:19:31 -08002067 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002068 JDWP::JdwpError error;
Roland Levillain4b8f1ec2015-08-26 18:34:03 +01002069 DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002070 if (error != JDWP::ERR_NONE && error != JDWP::ERR_THREAD_NOT_ALIVE) {
2071 return error;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08002072 }
Elliott Hughes221229c2013-01-08 18:17:50 -08002073
2074 // We still need to report the zombie threads' names, so we can't just call Thread::GetThreadName.
Ian Rogersc0542af2014-09-03 16:16:56 -07002075 mirror::Object* thread_object = gRegistry->Get<mirror::Object*>(thread_id, &error);
2076 CHECK(thread_object != nullptr) << error;
Mathieu Chartierc7853442015-03-27 14:35:38 -07002077 ArtField* java_lang_Thread_name_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08002078 jni::DecodeArtField(WellKnownClasses::java_lang_Thread_name);
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07002079 ObjPtr<mirror::String> s(java_lang_Thread_name_field->GetObject(thread_object)->AsString());
Ian Rogersc0542af2014-09-03 16:16:56 -07002080 if (s != nullptr) {
2081 *name = s->ToModifiedUtf8();
Elliott Hughes221229c2013-01-08 18:17:50 -08002082 }
2083 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002084}
2085
Elliott Hughes221229c2013-01-08 18:17:50 -08002086JDWP::JdwpError Dbg::GetThreadGroup(JDWP::ObjectId thread_id, JDWP::ExpandBuf* pReply) {
Sebastien Hertza06430c2014-09-15 19:21:30 +02002087 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002088 JDWP::JdwpError error;
2089 mirror::Object* thread_object = gRegistry->Get<mirror::Object*>(thread_id, &error);
2090 if (error != JDWP::ERR_NONE) {
Elliott Hughes2435a572012-02-17 16:07:41 -08002091 return JDWP::ERR_INVALID_OBJECT;
2092 }
Mathieu Chartier268764d2016-09-13 12:09:38 -07002093 ScopedAssertNoThreadSuspension ants("Debugger: GetThreadGroup");
Elliott Hughes2435a572012-02-17 16:07:41 -08002094 // Okay, so it's an object, but is it actually a thread?
Roland Levillain4b8f1ec2015-08-26 18:34:03 +01002095 DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002096 if (error == JDWP::ERR_THREAD_NOT_ALIVE) {
2097 // Zombie threads are in the null group.
2098 expandBufAddObjectId(pReply, JDWP::ObjectId(0));
Sebastien Hertz52d131d2014-03-13 16:17:40 +01002099 error = JDWP::ERR_NONE;
2100 } else if (error == JDWP::ERR_NONE) {
Mathieu Chartier0795f232016-09-27 18:43:30 -07002101 ObjPtr<mirror::Class> c = soa.Decode<mirror::Class>(WellKnownClasses::java_lang_Thread);
Sebastien Hertz52d131d2014-03-13 16:17:40 +01002102 CHECK(c != nullptr);
Andreas Gampe08883de2016-11-08 13:20:52 -08002103 ArtField* f = jni::DecodeArtField(WellKnownClasses::java_lang_Thread_group);
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07002104 CHECK(f != nullptr);
Mathieu Chartier3398c782016-09-30 10:27:43 -07002105 ObjPtr<mirror::Object> group = f->GetObject(thread_object);
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07002106 CHECK(group != nullptr);
Sebastien Hertz52d131d2014-03-13 16:17:40 +01002107 JDWP::ObjectId thread_group_id = gRegistry->Add(group);
2108 expandBufAddObjectId(pReply, thread_group_id);
Elliott Hughes221229c2013-01-08 18:17:50 -08002109 }
Sebastien Hertz52d131d2014-03-13 16:17:40 +01002110 return error;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002111}
2112
Sebastien Hertza06430c2014-09-15 19:21:30 +02002113static mirror::Object* DecodeThreadGroup(ScopedObjectAccessUnchecked& soa,
2114 JDWP::ObjectId thread_group_id, JDWP::JdwpError* error)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002115 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz6995c602014-09-09 12:10:13 +02002116 mirror::Object* thread_group = Dbg::GetObjectRegistry()->Get<mirror::Object*>(thread_group_id,
2117 error);
Sebastien Hertza06430c2014-09-15 19:21:30 +02002118 if (*error != JDWP::ERR_NONE) {
2119 return nullptr;
2120 }
2121 if (thread_group == nullptr) {
2122 *error = JDWP::ERR_INVALID_OBJECT;
2123 return nullptr;
2124 }
Mathieu Chartier0795f232016-09-27 18:43:30 -07002125 ObjPtr<mirror::Class> c =
2126 soa.Decode<mirror::Class>(WellKnownClasses::java_lang_ThreadGroup);
Ian Rogers98379392014-02-24 16:53:16 -08002127 CHECK(c != nullptr);
Sebastien Hertza06430c2014-09-15 19:21:30 +02002128 if (!c->IsAssignableFrom(thread_group->GetClass())) {
2129 // This is not a java.lang.ThreadGroup.
2130 *error = JDWP::ERR_INVALID_THREAD_GROUP;
2131 return nullptr;
2132 }
2133 *error = JDWP::ERR_NONE;
2134 return thread_group;
2135}
2136
2137JDWP::JdwpError Dbg::GetThreadGroupName(JDWP::ObjectId thread_group_id, JDWP::ExpandBuf* pReply) {
2138 ScopedObjectAccessUnchecked soa(Thread::Current());
2139 JDWP::JdwpError error;
2140 mirror::Object* thread_group = DecodeThreadGroup(soa, thread_group_id, &error);
2141 if (error != JDWP::ERR_NONE) {
2142 return error;
2143 }
Mathieu Chartier268764d2016-09-13 12:09:38 -07002144 ScopedAssertNoThreadSuspension ants("Debugger: GetThreadGroupName");
Andreas Gampe08883de2016-11-08 13:20:52 -08002145 ArtField* f = jni::DecodeArtField(WellKnownClasses::java_lang_ThreadGroup_name);
Ian Rogersc0542af2014-09-03 16:16:56 -07002146 CHECK(f != nullptr);
Mathieu Chartier3398c782016-09-30 10:27:43 -07002147 ObjPtr<mirror::String> s = f->GetObject(thread_group)->AsString();
Sebastien Hertza06430c2014-09-15 19:21:30 +02002148
2149 std::string thread_group_name(s->ToModifiedUtf8());
2150 expandBufAddUtf8String(pReply, thread_group_name);
2151 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002152}
2153
Sebastien Hertza06430c2014-09-15 19:21:30 +02002154JDWP::JdwpError Dbg::GetThreadGroupParent(JDWP::ObjectId thread_group_id, JDWP::ExpandBuf* pReply) {
Ian Rogers98379392014-02-24 16:53:16 -08002155 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002156 JDWP::JdwpError error;
Sebastien Hertza06430c2014-09-15 19:21:30 +02002157 mirror::Object* thread_group = DecodeThreadGroup(soa, thread_group_id, &error);
2158 if (error != JDWP::ERR_NONE) {
2159 return error;
2160 }
Mathieu Chartier3398c782016-09-30 10:27:43 -07002161 ObjPtr<mirror::Object> parent;
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07002162 {
Mathieu Chartier268764d2016-09-13 12:09:38 -07002163 ScopedAssertNoThreadSuspension ants("Debugger: GetThreadGroupParent");
Andreas Gampe08883de2016-11-08 13:20:52 -08002164 ArtField* f = jni::DecodeArtField(WellKnownClasses::java_lang_ThreadGroup_parent);
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07002165 CHECK(f != nullptr);
2166 parent = f->GetObject(thread_group);
2167 }
Sebastien Hertza06430c2014-09-15 19:21:30 +02002168 JDWP::ObjectId parent_group_id = gRegistry->Add(parent);
2169 expandBufAddObjectId(pReply, parent_group_id);
2170 return JDWP::ERR_NONE;
2171}
2172
Andreas Gampe08883de2016-11-08 13:20:52 -08002173static void GetChildThreadGroups(mirror::Object* thread_group,
Sebastien Hertza06430c2014-09-15 19:21:30 +02002174 std::vector<JDWP::ObjectId>* child_thread_group_ids)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002175 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertza06430c2014-09-15 19:21:30 +02002176 CHECK(thread_group != nullptr);
2177
Przemyslaw Szczepaniak464595f2015-11-24 11:59:59 +00002178 // Get the int "ngroups" count of this thread group...
Andreas Gampe08883de2016-11-08 13:20:52 -08002179 ArtField* ngroups_field = jni::DecodeArtField(WellKnownClasses::java_lang_ThreadGroup_ngroups);
Przemyslaw Szczepaniak464595f2015-11-24 11:59:59 +00002180 CHECK(ngroups_field != nullptr);
2181 const int32_t size = ngroups_field->GetInt(thread_group);
2182 if (size == 0) {
2183 return;
Sebastien Hertze49e1952014-10-13 11:27:13 +02002184 }
Sebastien Hertza06430c2014-09-15 19:21:30 +02002185
Przemyslaw Szczepaniak464595f2015-11-24 11:59:59 +00002186 // Get the ThreadGroup[] "groups" out of this thread group...
Andreas Gampe08883de2016-11-08 13:20:52 -08002187 ArtField* groups_field = jni::DecodeArtField(WellKnownClasses::java_lang_ThreadGroup_groups);
Mathieu Chartier3398c782016-09-30 10:27:43 -07002188 ObjPtr<mirror::Object> groups_array = groups_field->GetObject(thread_group);
Przemyslaw Szczepaniak464595f2015-11-24 11:59:59 +00002189
2190 CHECK(groups_array != nullptr);
2191 CHECK(groups_array->IsObjectArray());
2192
Mathieu Chartier3398c782016-09-30 10:27:43 -07002193 ObjPtr<mirror::ObjectArray<mirror::Object>> groups_array_as_array =
Przemyslaw Szczepaniak464595f2015-11-24 11:59:59 +00002194 groups_array->AsObjectArray<mirror::Object>();
Sebastien Hertza06430c2014-09-15 19:21:30 +02002195
2196 // Copy the first 'size' elements out of the array into the result.
Sebastien Hertz6995c602014-09-09 12:10:13 +02002197 ObjectRegistry* registry = Dbg::GetObjectRegistry();
Sebastien Hertza06430c2014-09-15 19:21:30 +02002198 for (int32_t i = 0; i < size; ++i) {
Przemyslaw Szczepaniak464595f2015-11-24 11:59:59 +00002199 child_thread_group_ids->push_back(registry->Add(groups_array_as_array->Get(i)));
Sebastien Hertza06430c2014-09-15 19:21:30 +02002200 }
2201}
2202
2203JDWP::JdwpError Dbg::GetThreadGroupChildren(JDWP::ObjectId thread_group_id,
2204 JDWP::ExpandBuf* pReply) {
2205 ScopedObjectAccessUnchecked soa(Thread::Current());
2206 JDWP::JdwpError error;
2207 mirror::Object* thread_group = DecodeThreadGroup(soa, thread_group_id, &error);
2208 if (error != JDWP::ERR_NONE) {
2209 return error;
2210 }
2211
2212 // Add child threads.
2213 {
2214 std::vector<JDWP::ObjectId> child_thread_ids;
2215 GetThreads(thread_group, &child_thread_ids);
2216 expandBufAdd4BE(pReply, child_thread_ids.size());
2217 for (JDWP::ObjectId child_thread_id : child_thread_ids) {
2218 expandBufAddObjectId(pReply, child_thread_id);
2219 }
2220 }
2221
2222 // Add child thread groups.
2223 {
2224 std::vector<JDWP::ObjectId> child_thread_groups_ids;
Andreas Gampe08883de2016-11-08 13:20:52 -08002225 GetChildThreadGroups(thread_group, &child_thread_groups_ids);
Sebastien Hertza06430c2014-09-15 19:21:30 +02002226 expandBufAdd4BE(pReply, child_thread_groups_ids.size());
2227 for (JDWP::ObjectId child_thread_group_id : child_thread_groups_ids) {
2228 expandBufAddObjectId(pReply, child_thread_group_id);
2229 }
2230 }
2231
2232 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002233}
2234
2235JDWP::ObjectId Dbg::GetSystemThreadGroupId() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002236 ScopedObjectAccessUnchecked soa(Thread::Current());
Andreas Gampe08883de2016-11-08 13:20:52 -08002237 ArtField* f = jni::DecodeArtField(WellKnownClasses::java_lang_ThreadGroup_systemThreadGroup);
Mathieu Chartier3398c782016-09-30 10:27:43 -07002238 ObjPtr<mirror::Object> group = f->GetObject(f->GetDeclaringClass());
Ian Rogers365c1022012-06-22 15:05:28 -07002239 return gRegistry->Add(group);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002240}
2241
Jeff Hao920af3e2013-08-28 15:46:38 -07002242JDWP::JdwpThreadStatus Dbg::ToJdwpThreadStatus(ThreadState state) {
2243 switch (state) {
2244 case kBlocked:
2245 return JDWP::TS_MONITOR;
2246 case kNative:
2247 case kRunnable:
2248 case kSuspended:
2249 return JDWP::TS_RUNNING;
2250 case kSleeping:
2251 return JDWP::TS_SLEEPING;
2252 case kStarting:
2253 case kTerminated:
2254 return JDWP::TS_ZOMBIE;
2255 case kTimedWaiting:
Alex Light77fee872017-09-05 14:51:49 -07002256 case kWaitingForTaskProcessor:
2257 case kWaitingForLockInflation:
Sebastien Hertzbae182c2013-12-17 10:42:03 +01002258 case kWaitingForCheckPointsToRun:
Jeff Hao920af3e2013-08-28 15:46:38 -07002259 case kWaitingForDebuggerSend:
2260 case kWaitingForDebuggerSuspension:
2261 case kWaitingForDebuggerToAttach:
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002262 case kWaitingForDeoptimization:
Jeff Hao920af3e2013-08-28 15:46:38 -07002263 case kWaitingForGcToComplete:
Mathieu Chartierb43390c2015-05-12 10:47:11 -07002264 case kWaitingForGetObjectsAllocated:
Jeff Hao920af3e2013-08-28 15:46:38 -07002265 case kWaitingForJniOnLoad:
Sebastien Hertzbae182c2013-12-17 10:42:03 +01002266 case kWaitingForMethodTracingStart:
Jeff Hao920af3e2013-08-28 15:46:38 -07002267 case kWaitingForSignalCatcherOutput:
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -08002268 case kWaitingForVisitObjects:
Jeff Hao920af3e2013-08-28 15:46:38 -07002269 case kWaitingInMainDebuggerLoop:
2270 case kWaitingInMainSignalCatcherLoop:
2271 case kWaitingPerformingGc:
Mathieu Chartier90ef3db2015-08-04 15:19:41 -07002272 case kWaitingWeakGcRootRead:
Hiroshi Yamauchi76f55b02015-08-21 16:10:39 -07002273 case kWaitingForGcThreadFlip:
Jeff Hao920af3e2013-08-28 15:46:38 -07002274 case kWaiting:
2275 return JDWP::TS_WAIT;
2276 // Don't add a 'default' here so the compiler can spot incompatible enum changes.
2277 }
2278 LOG(FATAL) << "Unknown thread state: " << state;
2279 return JDWP::TS_ZOMBIE;
2280}
2281
Sebastien Hertz52d131d2014-03-13 16:17:40 +01002282JDWP::JdwpError Dbg::GetThreadStatus(JDWP::ObjectId thread_id, JDWP::JdwpThreadStatus* pThreadStatus,
2283 JDWP::JdwpSuspendStatus* pSuspendStatus) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002284 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes499c5132011-11-17 14:55:11 -08002285
Elliott Hughes9e0c1752013-01-09 14:02:58 -08002286 *pSuspendStatus = JDWP::SUSPEND_STATUS_NOT_SUSPENDED;
2287
Ian Rogersc0542af2014-09-03 16:16:56 -07002288 JDWP::JdwpError error;
2289 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002290 if (error != JDWP::ERR_NONE) {
2291 if (error == JDWP::ERR_THREAD_NOT_ALIVE) {
2292 *pThreadStatus = JDWP::TS_ZOMBIE;
Elliott Hughes221229c2013-01-08 18:17:50 -08002293 return JDWP::ERR_NONE;
2294 }
2295 return error;
Elliott Hughes499c5132011-11-17 14:55:11 -08002296 }
2297
Elliott Hughes9e0c1752013-01-09 14:02:58 -08002298 if (IsSuspendedForDebugger(soa, thread)) {
2299 *pSuspendStatus = JDWP::SUSPEND_STATUS_SUSPENDED;
Elliott Hughes499c5132011-11-17 14:55:11 -08002300 }
2301
Jeff Hao920af3e2013-08-28 15:46:38 -07002302 *pThreadStatus = ToJdwpThreadStatus(thread->GetState());
Elliott Hughes221229c2013-01-08 18:17:50 -08002303 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002304}
2305
Elliott Hughes221229c2013-01-08 18:17:50 -08002306JDWP::JdwpError Dbg::GetThreadDebugSuspendCount(JDWP::ObjectId thread_id, JDWP::ExpandBuf* pReply) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002307 ScopedObjectAccess soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002308 JDWP::JdwpError error;
2309 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002310 if (error != JDWP::ERR_NONE) {
2311 return error;
Elliott Hughes2435a572012-02-17 16:07:41 -08002312 }
Ian Rogers50b35e22012-10-04 10:09:15 -07002313 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002314 expandBufAdd4BE(pReply, thread->GetDebugSuspendCount());
Elliott Hughes2435a572012-02-17 16:07:41 -08002315 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002316}
2317
Elliott Hughesf9501702013-01-11 11:22:27 -08002318JDWP::JdwpError Dbg::Interrupt(JDWP::ObjectId thread_id) {
2319 ScopedObjectAccess soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002320 JDWP::JdwpError error;
2321 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughesf9501702013-01-11 11:22:27 -08002322 if (error != JDWP::ERR_NONE) {
2323 return error;
2324 }
Ian Rogersdd7624d2014-03-14 17:43:00 -07002325 thread->Interrupt(soa.Self());
Elliott Hughesf9501702013-01-11 11:22:27 -08002326 return JDWP::ERR_NONE;
2327}
2328
Andreas Gampe08883de2016-11-08 13:20:52 -08002329static bool IsInDesiredThreadGroup(mirror::Object* desired_thread_group, mirror::Object* peer)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002330 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz070f7322014-09-09 12:08:49 +02002331 // Do we want threads from all thread groups?
2332 if (desired_thread_group == nullptr) {
2333 return true;
2334 }
Andreas Gampe08883de2016-11-08 13:20:52 -08002335 ArtField* thread_group_field = jni::DecodeArtField(WellKnownClasses::java_lang_Thread_group);
Sebastien Hertz070f7322014-09-09 12:08:49 +02002336 DCHECK(thread_group_field != nullptr);
Mathieu Chartier3398c782016-09-30 10:27:43 -07002337 ObjPtr<mirror::Object> group = thread_group_field->GetObject(peer);
Sebastien Hertz070f7322014-09-09 12:08:49 +02002338 return (group == desired_thread_group);
2339}
2340
Sebastien Hertza06430c2014-09-15 19:21:30 +02002341void Dbg::GetThreads(mirror::Object* thread_group, std::vector<JDWP::ObjectId>* thread_ids) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002342 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz070f7322014-09-09 12:08:49 +02002343 std::list<Thread*> all_threads_list;
2344 {
2345 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
2346 all_threads_list = Runtime::Current()->GetThreadList()->GetList();
2347 }
2348 for (Thread* t : all_threads_list) {
2349 if (t == Dbg::GetDebugThread()) {
2350 // Skip the JDWP thread. Some debuggers get bent out of shape when they can't suspend and
2351 // query all threads, so it's easier if we just don't tell them about this thread.
2352 continue;
2353 }
2354 if (t->IsStillStarting()) {
2355 // This thread is being started (and has been registered in the thread list). However, it is
2356 // not completely started yet so we must ignore it.
2357 continue;
2358 }
Nicolas Geoffraycafa0812017-02-15 18:27:34 +00002359 mirror::Object* peer = t->GetPeerFromOtherThread();
Sebastien Hertz070f7322014-09-09 12:08:49 +02002360 if (peer == nullptr) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002361 // 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 +02002362 // this thread yet.
2363 // TODO: if we identified threads to the debugger by their Thread*
2364 // rather than their peer's mirror::Object*, we could fix this.
2365 // Doing so might help us report ZOMBIE threads too.
2366 continue;
2367 }
Andreas Gampe08883de2016-11-08 13:20:52 -08002368 if (IsInDesiredThreadGroup(thread_group, peer)) {
Sebastien Hertz070f7322014-09-09 12:08:49 +02002369 thread_ids->push_back(gRegistry->Add(peer));
2370 }
2371 }
Elliott Hughescaf76542012-06-28 16:08:22 -07002372}
Elliott Hughesa2155262011-11-16 16:26:58 -08002373
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002374static int GetStackDepth(Thread* thread) REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002375 struct CountStackDepthVisitor : public StackVisitor {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002376 explicit CountStackDepthVisitor(Thread* thread_in)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01002377 : StackVisitor(thread_in, nullptr, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
2378 depth(0) {}
Ian Rogers0399dde2012-06-06 17:09:28 -07002379
Elliott Hughes64f574f2013-02-20 14:57:12 -08002380 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2381 // annotalysis.
2382 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07002383 if (!GetMethod()->IsRuntimeMethod()) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -08002384 ++depth;
2385 }
Elliott Hughes530fa002012-03-12 11:44:49 -07002386 return true;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08002387 }
2388 size_t depth;
2389 };
Elliott Hughes08fc03a2012-06-26 17:34:00 -07002390
Ian Rogers7a22fa62013-01-23 12:16:16 -08002391 CountStackDepthVisitor visitor(thread);
Ian Rogers0399dde2012-06-06 17:09:28 -07002392 visitor.WalkStack();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08002393 return visitor.depth;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002394}
2395
Ian Rogersc0542af2014-09-03 16:16:56 -07002396JDWP::JdwpError Dbg::GetThreadFrameCount(JDWP::ObjectId thread_id, size_t* result) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002397 ScopedObjectAccess soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002398 JDWP::JdwpError error;
2399 *result = 0;
2400 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002401 if (error != JDWP::ERR_NONE) {
2402 return error;
2403 }
Elliott Hughesf15f4a02013-01-09 10:09:38 -08002404 if (!IsSuspendedForDebugger(soa, thread)) {
2405 return JDWP::ERR_THREAD_NOT_SUSPENDED;
2406 }
Ian Rogersc0542af2014-09-03 16:16:56 -07002407 *result = GetStackDepth(thread);
Elliott Hughes221229c2013-01-08 18:17:50 -08002408 return JDWP::ERR_NONE;
Elliott Hughes86964332012-02-15 19:37:42 -08002409}
2410
Ian Rogers306057f2012-11-26 12:45:53 -08002411JDWP::JdwpError Dbg::GetThreadFrames(JDWP::ObjectId thread_id, size_t start_frame,
2412 size_t frame_count, JDWP::ExpandBuf* buf) {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002413 class GetFrameVisitor : public StackVisitor {
2414 public:
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002415 GetFrameVisitor(Thread* thread, size_t start_frame_in, size_t frame_count_in,
2416 JDWP::ExpandBuf* buf_in)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002417 REQUIRES_SHARED(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01002418 : StackVisitor(thread, nullptr, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
2419 depth_(0),
2420 start_frame_(start_frame_in),
2421 frame_count_(frame_count_in),
2422 buf_(buf_in) {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002423 expandBufAdd4BE(buf_, frame_count_);
Elliott Hughes03181a82011-11-17 17:22:21 -08002424 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002425
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002426 bool VisitFrame() OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002427 if (GetMethod()->IsRuntimeMethod()) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07002428 return true; // The debugger can't do anything useful with a frame that has no Method*.
Elliott Hughes03181a82011-11-17 17:22:21 -08002429 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002430 if (depth_ >= start_frame_ + frame_count_) {
Elliott Hughes530fa002012-03-12 11:44:49 -07002431 return false;
Elliott Hughes03181a82011-11-17 17:22:21 -08002432 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002433 if (depth_ >= start_frame_) {
2434 JDWP::FrameId frame_id(GetFrameId());
2435 JDWP::JdwpLocation location;
Sebastien Hertz6995c602014-09-09 12:10:13 +02002436 SetJdwpLocation(&location, GetMethod(), GetDexPc());
Ian Rogersef7d42f2014-01-06 12:55:46 -08002437 VLOG(jdwp) << StringPrintf(" Frame %3zd: id=%3" PRIu64 " ", depth_, frame_id) << location;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002438 expandBufAdd8BE(buf_, frame_id);
2439 expandBufAddLocation(buf_, location);
2440 }
2441 ++depth_;
Elliott Hughes530fa002012-03-12 11:44:49 -07002442 return true;
Elliott Hughes03181a82011-11-17 17:22:21 -08002443 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002444
2445 private:
2446 size_t depth_;
2447 const size_t start_frame_;
2448 const size_t frame_count_;
2449 JDWP::ExpandBuf* buf_;
Elliott Hughes03181a82011-11-17 17:22:21 -08002450 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002451
2452 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002453 JDWP::JdwpError error;
2454 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002455 if (error != JDWP::ERR_NONE) {
2456 return error;
2457 }
Elliott Hughesf15f4a02013-01-09 10:09:38 -08002458 if (!IsSuspendedForDebugger(soa, thread)) {
2459 return JDWP::ERR_THREAD_NOT_SUSPENDED;
2460 }
Ian Rogers7a22fa62013-01-23 12:16:16 -08002461 GetFrameVisitor visitor(thread, start_frame, frame_count, buf);
Ian Rogers0399dde2012-06-06 17:09:28 -07002462 visitor.WalkStack();
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002463 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002464}
2465
2466JDWP::ObjectId Dbg::GetThreadSelfId() {
Sebastien Hertz6995c602014-09-09 12:10:13 +02002467 return GetThreadId(Thread::Current());
2468}
2469
2470JDWP::ObjectId Dbg::GetThreadId(Thread* thread) {
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07002471 ScopedObjectAccessUnchecked soa(Thread::Current());
Nicolas Geoffraycafa0812017-02-15 18:27:34 +00002472 return gRegistry->Add(thread->GetPeerFromOtherThread());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002473}
2474
Elliott Hughes475fc232011-10-25 15:00:35 -07002475void Dbg::SuspendVM() {
Hiroshi Yamauchi8f95cf32016-04-19 11:14:06 -07002476 // Avoid a deadlock between GC and debugger where GC gets suspended during GC. b/25800335.
2477 gc::ScopedGCCriticalSection gcs(Thread::Current(),
2478 gc::kGcCauseDebugger,
2479 gc::kCollectorTypeDebugger);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002480 Runtime::Current()->GetThreadList()->SuspendAllForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002481}
2482
2483void Dbg::ResumeVM() {
Sebastien Hertz253fa552014-10-14 17:27:15 +02002484 Runtime::Current()->GetThreadList()->ResumeAllForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002485}
2486
Elliott Hughes221229c2013-01-08 18:17:50 -08002487JDWP::JdwpError Dbg::SuspendThread(JDWP::ObjectId thread_id, bool request_suspension) {
Ian Rogersf3d874c2014-07-17 18:52:42 -07002488 Thread* self = Thread::Current();
Ian Rogersc0542af2014-09-03 16:16:56 -07002489 ScopedLocalRef<jobject> peer(self->GetJniEnv(), nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002490 {
Ian Rogersf3d874c2014-07-17 18:52:42 -07002491 ScopedObjectAccess soa(self);
Ian Rogersc0542af2014-09-03 16:16:56 -07002492 JDWP::JdwpError error;
2493 peer.reset(soa.AddLocalReference<jobject>(gRegistry->Get<mirror::Object*>(thread_id, &error)));
Elliott Hughes4e235312011-12-02 11:34:15 -08002494 }
Ian Rogersc0542af2014-09-03 16:16:56 -07002495 if (peer.get() == nullptr) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002496 return JDWP::ERR_THREAD_NOT_ALIVE;
2497 }
Ian Rogers4ad5cd32014-11-11 23:08:07 -08002498 // Suspend thread to build stack trace.
Elliott Hughesf327e072013-01-09 16:01:26 -08002499 bool timed_out;
Brian Carlstromba32de42014-08-27 23:43:46 -07002500 ThreadList* thread_list = Runtime::Current()->GetThreadList();
Sebastien Hertzcdd798d2017-04-18 18:28:51 +02002501 Thread* thread = thread_list->SuspendThreadByPeer(peer.get(),
2502 request_suspension,
Alex Light46f93402017-06-29 11:59:50 -07002503 SuspendReason::kForDebugger,
Brian Carlstromba32de42014-08-27 23:43:46 -07002504 &timed_out);
Ian Rogersc0542af2014-09-03 16:16:56 -07002505 if (thread != nullptr) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002506 return JDWP::ERR_NONE;
Elliott Hughesf327e072013-01-09 16:01:26 -08002507 } else if (timed_out) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002508 return JDWP::ERR_INTERNAL;
2509 } else {
2510 return JDWP::ERR_THREAD_NOT_ALIVE;
2511 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002512}
2513
Elliott Hughes221229c2013-01-08 18:17:50 -08002514void Dbg::ResumeThread(JDWP::ObjectId thread_id) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002515 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002516 JDWP::JdwpError error;
2517 mirror::Object* peer = gRegistry->Get<mirror::Object*>(thread_id, &error);
2518 CHECK(peer != nullptr) << error;
jeffhaoa77f0f62012-12-05 17:19:31 -08002519 Thread* thread;
2520 {
2521 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
2522 thread = Thread::FromManagedThread(soa, peer);
2523 }
Ian Rogersc0542af2014-09-03 16:16:56 -07002524 if (thread == nullptr) {
Elliott Hughes4e235312011-12-02 11:34:15 -08002525 LOG(WARNING) << "No such thread for resume: " << peer;
2526 return;
2527 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002528 bool needs_resume;
2529 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002530 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Sebastien Hertz70d60272017-04-14 14:18:36 +02002531 needs_resume = thread->GetDebugSuspendCount() > 0;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002532 }
2533 if (needs_resume) {
Alex Light88fd7202017-06-30 08:31:59 -07002534 bool resumed = Runtime::Current()->GetThreadList()->Resume(thread, SuspendReason::kForDebugger);
2535 DCHECK(resumed);
Elliott Hughes546b9862012-06-20 16:06:13 -07002536 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002537}
2538
2539void Dbg::SuspendSelf() {
Elliott Hughes475fc232011-10-25 15:00:35 -07002540 Runtime::Current()->GetThreadList()->SuspendSelfForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002541}
2542
Ian Rogers0399dde2012-06-06 17:09:28 -07002543struct GetThisVisitor : public StackVisitor {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002544 GetThisVisitor(Thread* thread, Context* context, JDWP::FrameId frame_id_in)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002545 REQUIRES_SHARED(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01002546 : StackVisitor(thread, context, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
2547 this_object(nullptr),
2548 frame_id(frame_id_in) {}
Ian Rogers0399dde2012-06-06 17:09:28 -07002549
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002550 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2551 // annotalysis.
2552 virtual bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002553 if (frame_id != GetFrameId()) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002554 return true; // continue
Ian Rogers0399dde2012-06-06 17:09:28 -07002555 } else {
Ian Rogers62d6c772013-02-27 08:32:07 -08002556 this_object = GetThisObject();
2557 return false;
Ian Rogers0399dde2012-06-06 17:09:28 -07002558 }
Elliott Hughes86b00102011-12-05 17:54:26 -08002559 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002560
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002561 mirror::Object* this_object;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002562 JDWP::FrameId frame_id;
Ian Rogers0399dde2012-06-06 17:09:28 -07002563};
2564
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002565JDWP::JdwpError Dbg::GetThisObject(JDWP::ObjectId thread_id, JDWP::FrameId frame_id,
2566 JDWP::ObjectId* result) {
2567 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz69206392015-04-07 15:54:25 +02002568 JDWP::JdwpError error;
2569 Thread* thread = DecodeThread(soa, thread_id, &error);
2570 if (error != JDWP::ERR_NONE) {
2571 return error;
2572 }
2573 if (!IsSuspendedForDebugger(soa, thread)) {
2574 return JDWP::ERR_THREAD_NOT_SUSPENDED;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002575 }
Ian Rogers700a4022014-05-19 16:49:03 -07002576 std::unique_ptr<Context> context(Context::Create());
Ian Rogers7a22fa62013-01-23 12:16:16 -08002577 GetThisVisitor visitor(thread, context.get(), frame_id);
Ian Rogers0399dde2012-06-06 17:09:28 -07002578 visitor.WalkStack();
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002579 *result = gRegistry->Add(visitor.this_object);
2580 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002581}
2582
Sebastien Hertz8009f392014-09-01 17:07:11 +02002583// Walks the stack until we find the frame with the given FrameId.
2584class FindFrameVisitor FINAL : public StackVisitor {
2585 public:
2586 FindFrameVisitor(Thread* thread, Context* context, JDWP::FrameId frame_id)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002587 REQUIRES_SHARED(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01002588 : StackVisitor(thread, context, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
2589 frame_id_(frame_id),
2590 error_(JDWP::ERR_INVALID_FRAMEID) {}
Ian Rogersca190662012-06-26 15:45:57 -07002591
Sebastien Hertz8009f392014-09-01 17:07:11 +02002592 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2593 // annotalysis.
2594 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
2595 if (GetFrameId() != frame_id_) {
2596 return true; // Not our frame, carry on.
Ian Rogers0399dde2012-06-06 17:09:28 -07002597 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07002598 ArtMethod* m = GetMethod();
Sebastien Hertz8009f392014-09-01 17:07:11 +02002599 if (m->IsNative()) {
2600 // We can't read/write local value from/into native method.
2601 error_ = JDWP::ERR_OPAQUE_FRAME;
2602 } else {
2603 // We found our frame.
2604 error_ = JDWP::ERR_NONE;
2605 }
2606 return false;
2607 }
2608
2609 JDWP::JdwpError GetError() const {
2610 return error_;
2611 }
2612
2613 private:
2614 const JDWP::FrameId frame_id_;
2615 JDWP::JdwpError error_;
Sebastien Hertz26f72862015-09-15 09:52:07 +02002616
2617 DISALLOW_COPY_AND_ASSIGN(FindFrameVisitor);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002618};
2619
2620JDWP::JdwpError Dbg::GetLocalValues(JDWP::Request* request, JDWP::ExpandBuf* pReply) {
2621 JDWP::ObjectId thread_id = request->ReadThreadId();
2622 JDWP::FrameId frame_id = request->ReadFrameId();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002623
2624 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz69206392015-04-07 15:54:25 +02002625 JDWP::JdwpError error;
2626 Thread* thread = DecodeThread(soa, thread_id, &error);
2627 if (error != JDWP::ERR_NONE) {
2628 return error;
2629 }
2630 if (!IsSuspendedForDebugger(soa, thread)) {
2631 return JDWP::ERR_THREAD_NOT_SUSPENDED;
Elliott Hughes221229c2013-01-08 18:17:50 -08002632 }
Sebastien Hertz8009f392014-09-01 17:07:11 +02002633 // Find the frame with the given frame_id.
Ian Rogers700a4022014-05-19 16:49:03 -07002634 std::unique_ptr<Context> context(Context::Create());
Sebastien Hertz8009f392014-09-01 17:07:11 +02002635 FindFrameVisitor visitor(thread, context.get(), frame_id);
Ian Rogers0399dde2012-06-06 17:09:28 -07002636 visitor.WalkStack();
Sebastien Hertz8009f392014-09-01 17:07:11 +02002637 if (visitor.GetError() != JDWP::ERR_NONE) {
2638 return visitor.GetError();
2639 }
2640
2641 // Read the values from visitor's context.
2642 int32_t slot_count = request->ReadSigned32("slot count");
2643 expandBufAdd4BE(pReply, slot_count); /* "int values" */
2644 for (int32_t i = 0; i < slot_count; ++i) {
2645 uint32_t slot = request->ReadUnsigned32("slot");
2646 JDWP::JdwpTag reqSigByte = request->ReadTag();
2647
2648 VLOG(jdwp) << " --> slot " << slot << " " << reqSigByte;
2649
2650 size_t width = Dbg::GetTagWidth(reqSigByte);
Sebastien Hertz7d955652014-10-22 10:57:10 +02002651 uint8_t* ptr = expandBufAddSpace(pReply, width + 1);
Sebastien Hertz69206392015-04-07 15:54:25 +02002652 error = Dbg::GetLocalValue(visitor, soa, slot, reqSigByte, ptr, width);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002653 if (error != JDWP::ERR_NONE) {
2654 return error;
2655 }
2656 }
2657 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002658}
2659
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002660constexpr JDWP::JdwpError kStackFrameLocalAccessError = JDWP::ERR_ABSENT_INFORMATION;
2661
2662static std::string GetStackContextAsString(const StackVisitor& visitor)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002663 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002664 return StringPrintf(" at DEX pc 0x%08x in method %s", visitor.GetDexPc(false),
David Sehr709b0702016-10-13 09:12:37 -07002665 ArtMethod::PrettyMethod(visitor.GetMethod()).c_str());
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002666}
2667
2668static JDWP::JdwpError FailGetLocalValue(const StackVisitor& visitor, uint16_t vreg,
2669 JDWP::JdwpTag tag)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002670 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002671 LOG(ERROR) << "Failed to read " << tag << " local from register v" << vreg
2672 << GetStackContextAsString(visitor);
2673 return kStackFrameLocalAccessError;
2674}
2675
Sebastien Hertz8009f392014-09-01 17:07:11 +02002676JDWP::JdwpError Dbg::GetLocalValue(const StackVisitor& visitor, ScopedObjectAccessUnchecked& soa,
2677 int slot, JDWP::JdwpTag tag, uint8_t* buf, size_t width) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002678 ArtMethod* m = visitor.GetMethod();
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002679 JDWP::JdwpError error = JDWP::ERR_NONE;
2680 uint16_t vreg = DemangleSlot(slot, m, &error);
2681 if (error != JDWP::ERR_NONE) {
2682 return error;
2683 }
Sebastien Hertz8009f392014-09-01 17:07:11 +02002684 // TODO: check that the tag is compatible with the actual type of the slot!
Sebastien Hertz8009f392014-09-01 17:07:11 +02002685 switch (tag) {
2686 case JDWP::JT_BOOLEAN: {
2687 CHECK_EQ(width, 1U);
2688 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002689 if (!visitor.GetVReg(m, vreg, kIntVReg, &intVal)) {
2690 return FailGetLocalValue(visitor, vreg, tag);
Ian Rogers0399dde2012-06-06 17:09:28 -07002691 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002692 VLOG(jdwp) << "get boolean local " << vreg << " = " << intVal;
2693 JDWP::Set1(buf + 1, intVal != 0);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002694 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002695 }
Sebastien Hertz8009f392014-09-01 17:07:11 +02002696 case JDWP::JT_BYTE: {
2697 CHECK_EQ(width, 1U);
2698 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002699 if (!visitor.GetVReg(m, vreg, kIntVReg, &intVal)) {
2700 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002701 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002702 VLOG(jdwp) << "get byte local " << vreg << " = " << intVal;
2703 JDWP::Set1(buf + 1, intVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002704 break;
2705 }
2706 case JDWP::JT_SHORT:
2707 case JDWP::JT_CHAR: {
2708 CHECK_EQ(width, 2U);
2709 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002710 if (!visitor.GetVReg(m, vreg, kIntVReg, &intVal)) {
2711 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002712 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002713 VLOG(jdwp) << "get short/char local " << vreg << " = " << intVal;
2714 JDWP::Set2BE(buf + 1, intVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002715 break;
2716 }
2717 case JDWP::JT_INT: {
2718 CHECK_EQ(width, 4U);
2719 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002720 if (!visitor.GetVReg(m, vreg, kIntVReg, &intVal)) {
2721 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002722 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002723 VLOG(jdwp) << "get int local " << vreg << " = " << intVal;
2724 JDWP::Set4BE(buf + 1, intVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002725 break;
2726 }
2727 case JDWP::JT_FLOAT: {
2728 CHECK_EQ(width, 4U);
2729 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002730 if (!visitor.GetVReg(m, vreg, kFloatVReg, &intVal)) {
2731 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002732 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002733 VLOG(jdwp) << "get float local " << vreg << " = " << intVal;
2734 JDWP::Set4BE(buf + 1, intVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002735 break;
2736 }
2737 case JDWP::JT_ARRAY:
2738 case JDWP::JT_CLASS_LOADER:
2739 case JDWP::JT_CLASS_OBJECT:
2740 case JDWP::JT_OBJECT:
2741 case JDWP::JT_STRING:
2742 case JDWP::JT_THREAD:
2743 case JDWP::JT_THREAD_GROUP: {
2744 CHECK_EQ(width, sizeof(JDWP::ObjectId));
2745 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002746 if (!visitor.GetVReg(m, vreg, kReferenceVReg, &intVal)) {
2747 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002748 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002749 mirror::Object* o = reinterpret_cast<mirror::Object*>(intVal);
2750 VLOG(jdwp) << "get " << tag << " object local " << vreg << " = " << o;
2751 if (!Runtime::Current()->GetHeap()->IsValidObjectAddress(o)) {
2752 LOG(FATAL) << StringPrintf("Found invalid object %#" PRIxPTR " in register v%u",
2753 reinterpret_cast<uintptr_t>(o), vreg)
2754 << GetStackContextAsString(visitor);
2755 UNREACHABLE();
2756 }
2757 tag = TagFromObject(soa, o);
2758 JDWP::SetObjectId(buf + 1, gRegistry->Add(o));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002759 break;
2760 }
2761 case JDWP::JT_DOUBLE: {
2762 CHECK_EQ(width, 8U);
2763 uint64_t longVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002764 if (!visitor.GetVRegPair(m, vreg, kDoubleLoVReg, kDoubleHiVReg, &longVal)) {
2765 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002766 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002767 VLOG(jdwp) << "get double local " << vreg << " = " << longVal;
2768 JDWP::Set8BE(buf + 1, longVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002769 break;
2770 }
2771 case JDWP::JT_LONG: {
2772 CHECK_EQ(width, 8U);
2773 uint64_t longVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002774 if (!visitor.GetVRegPair(m, vreg, kLongLoVReg, kLongHiVReg, &longVal)) {
2775 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002776 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002777 VLOG(jdwp) << "get long local " << vreg << " = " << longVal;
2778 JDWP::Set8BE(buf + 1, longVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002779 break;
2780 }
2781 default:
2782 LOG(FATAL) << "Unknown tag " << tag;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002783 UNREACHABLE();
Sebastien Hertz8009f392014-09-01 17:07:11 +02002784 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002785
Sebastien Hertz8009f392014-09-01 17:07:11 +02002786 // Prepend tag, which may have been updated.
2787 JDWP::Set1(buf, tag);
2788 return JDWP::ERR_NONE;
2789}
2790
2791JDWP::JdwpError Dbg::SetLocalValues(JDWP::Request* request) {
2792 JDWP::ObjectId thread_id = request->ReadThreadId();
2793 JDWP::FrameId frame_id = request->ReadFrameId();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002794
2795 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz69206392015-04-07 15:54:25 +02002796 JDWP::JdwpError error;
2797 Thread* thread = DecodeThread(soa, thread_id, &error);
2798 if (error != JDWP::ERR_NONE) {
2799 return error;
2800 }
2801 if (!IsSuspendedForDebugger(soa, thread)) {
2802 return JDWP::ERR_THREAD_NOT_SUSPENDED;
Elliott Hughes221229c2013-01-08 18:17:50 -08002803 }
Sebastien Hertz8009f392014-09-01 17:07:11 +02002804 // Find the frame with the given frame_id.
Ian Rogers700a4022014-05-19 16:49:03 -07002805 std::unique_ptr<Context> context(Context::Create());
Sebastien Hertz8009f392014-09-01 17:07:11 +02002806 FindFrameVisitor visitor(thread, context.get(), frame_id);
Ian Rogers0399dde2012-06-06 17:09:28 -07002807 visitor.WalkStack();
Sebastien Hertz8009f392014-09-01 17:07:11 +02002808 if (visitor.GetError() != JDWP::ERR_NONE) {
2809 return visitor.GetError();
2810 }
2811
2812 // Writes the values into visitor's context.
2813 int32_t slot_count = request->ReadSigned32("slot count");
2814 for (int32_t i = 0; i < slot_count; ++i) {
2815 uint32_t slot = request->ReadUnsigned32("slot");
2816 JDWP::JdwpTag sigByte = request->ReadTag();
2817 size_t width = Dbg::GetTagWidth(sigByte);
2818 uint64_t value = request->ReadValue(width);
2819
2820 VLOG(jdwp) << " --> slot " << slot << " " << sigByte << " " << value;
Mingyao Yang99170c62015-07-06 11:10:37 -07002821 error = Dbg::SetLocalValue(thread, visitor, slot, sigByte, value, width);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002822 if (error != JDWP::ERR_NONE) {
2823 return error;
2824 }
2825 }
2826 return JDWP::ERR_NONE;
2827}
2828
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002829template<typename T>
2830static JDWP::JdwpError FailSetLocalValue(const StackVisitor& visitor, uint16_t vreg,
2831 JDWP::JdwpTag tag, T value)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002832 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002833 LOG(ERROR) << "Failed to write " << tag << " local " << value
2834 << " (0x" << std::hex << value << ") into register v" << vreg
2835 << GetStackContextAsString(visitor);
2836 return kStackFrameLocalAccessError;
2837}
2838
Mingyao Yang99170c62015-07-06 11:10:37 -07002839JDWP::JdwpError Dbg::SetLocalValue(Thread* thread, StackVisitor& visitor, int slot,
2840 JDWP::JdwpTag tag, uint64_t value, size_t width) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002841 ArtMethod* m = visitor.GetMethod();
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002842 JDWP::JdwpError error = JDWP::ERR_NONE;
2843 uint16_t vreg = DemangleSlot(slot, m, &error);
2844 if (error != JDWP::ERR_NONE) {
2845 return error;
2846 }
Sebastien Hertz8009f392014-09-01 17:07:11 +02002847 // TODO: check that the tag is compatible with the actual type of the slot!
Sebastien Hertz8009f392014-09-01 17:07:11 +02002848 switch (tag) {
2849 case JDWP::JT_BOOLEAN:
2850 case JDWP::JT_BYTE:
2851 CHECK_EQ(width, 1U);
Mingyao Yang636b9252015-07-31 16:40:24 -07002852 if (!visitor.SetVReg(m, vreg, static_cast<uint32_t>(value), kIntVReg)) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002853 return FailSetLocalValue(visitor, vreg, tag, static_cast<uint32_t>(value));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002854 }
2855 break;
2856 case JDWP::JT_SHORT:
2857 case JDWP::JT_CHAR:
2858 CHECK_EQ(width, 2U);
Mingyao Yang636b9252015-07-31 16:40:24 -07002859 if (!visitor.SetVReg(m, vreg, static_cast<uint32_t>(value), kIntVReg)) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002860 return FailSetLocalValue(visitor, vreg, tag, static_cast<uint32_t>(value));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002861 }
2862 break;
2863 case JDWP::JT_INT:
2864 CHECK_EQ(width, 4U);
Mingyao Yang636b9252015-07-31 16:40:24 -07002865 if (!visitor.SetVReg(m, vreg, static_cast<uint32_t>(value), kIntVReg)) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002866 return FailSetLocalValue(visitor, vreg, tag, static_cast<uint32_t>(value));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002867 }
2868 break;
2869 case JDWP::JT_FLOAT:
2870 CHECK_EQ(width, 4U);
Mingyao Yang636b9252015-07-31 16:40:24 -07002871 if (!visitor.SetVReg(m, vreg, static_cast<uint32_t>(value), kFloatVReg)) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002872 return FailSetLocalValue(visitor, vreg, tag, static_cast<uint32_t>(value));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002873 }
2874 break;
2875 case JDWP::JT_ARRAY:
2876 case JDWP::JT_CLASS_LOADER:
2877 case JDWP::JT_CLASS_OBJECT:
2878 case JDWP::JT_OBJECT:
2879 case JDWP::JT_STRING:
2880 case JDWP::JT_THREAD:
2881 case JDWP::JT_THREAD_GROUP: {
2882 CHECK_EQ(width, sizeof(JDWP::ObjectId));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002883 mirror::Object* o = gRegistry->Get<mirror::Object*>(static_cast<JDWP::ObjectId>(value),
2884 &error);
2885 if (error != JDWP::ERR_NONE) {
2886 VLOG(jdwp) << tag << " object " << o << " is an invalid object";
2887 return JDWP::ERR_INVALID_OBJECT;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002888 }
Mingyao Yang636b9252015-07-31 16:40:24 -07002889 if (!visitor.SetVReg(m, vreg, static_cast<uint32_t>(reinterpret_cast<uintptr_t>(o)),
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002890 kReferenceVReg)) {
2891 return FailSetLocalValue(visitor, vreg, tag, reinterpret_cast<uintptr_t>(o));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002892 }
2893 break;
2894 }
2895 case JDWP::JT_DOUBLE: {
2896 CHECK_EQ(width, 8U);
Mingyao Yang636b9252015-07-31 16:40:24 -07002897 if (!visitor.SetVRegPair(m, vreg, value, kDoubleLoVReg, kDoubleHiVReg)) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002898 return FailSetLocalValue(visitor, vreg, tag, value);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002899 }
2900 break;
2901 }
2902 case JDWP::JT_LONG: {
2903 CHECK_EQ(width, 8U);
Mingyao Yang636b9252015-07-31 16:40:24 -07002904 if (!visitor.SetVRegPair(m, vreg, value, kLongLoVReg, kLongHiVReg)) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002905 return FailSetLocalValue(visitor, vreg, tag, value);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002906 }
2907 break;
2908 }
2909 default:
2910 LOG(FATAL) << "Unknown tag " << tag;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002911 UNREACHABLE();
Sebastien Hertz8009f392014-09-01 17:07:11 +02002912 }
Mingyao Yang99170c62015-07-06 11:10:37 -07002913
2914 // If we set the local variable in a compiled frame, we need to trigger a deoptimization of
2915 // the stack so we continue execution with the interpreter using the new value(s) of the updated
2916 // local variable(s). To achieve this, we install instrumentation exit stub on each method of the
2917 // thread's stack. The stub will cause the deoptimization to happen.
2918 if (!visitor.IsShadowFrame() && thread->HasDebuggerShadowFrames()) {
2919 Runtime::Current()->GetInstrumentation()->InstrumentThreadStack(thread);
2920 }
2921
Sebastien Hertz8009f392014-09-01 17:07:11 +02002922 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002923}
2924
Mathieu Chartiere401d142015-04-22 13:56:20 -07002925static void SetEventLocation(JDWP::EventLocation* location, ArtMethod* m, uint32_t dex_pc)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002926 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz6995c602014-09-09 12:10:13 +02002927 DCHECK(location != nullptr);
2928 if (m == nullptr) {
2929 memset(location, 0, sizeof(*location));
2930 } else {
Alex Light97e78032017-06-27 17:51:55 -07002931 location->method = m->GetCanonicalMethod(kRuntimePointerSize);
Sebastien Hertz6995c602014-09-09 12:10:13 +02002932 location->dex_pc = (m->IsNative() || m->IsProxyMethod()) ? static_cast<uint32_t>(-1) : dex_pc;
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002933 }
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002934}
2935
Mathieu Chartiere401d142015-04-22 13:56:20 -07002936void Dbg::PostLocationEvent(ArtMethod* m, int dex_pc, mirror::Object* this_object,
Jeff Hao579b0242013-11-18 13:16:49 -08002937 int event_flags, const JValue* return_value) {
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002938 if (!IsDebuggerActive()) {
2939 return;
2940 }
2941 DCHECK(m != nullptr);
2942 DCHECK_EQ(m->IsStatic(), this_object == nullptr);
Sebastien Hertz6995c602014-09-09 12:10:13 +02002943 JDWP::EventLocation location;
2944 SetEventLocation(&location, m, dex_pc);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002945
Sebastien Hertzde48aa62015-05-26 11:53:39 +02002946 // We need to be sure no exception is pending when calling JdwpState::PostLocationEvent.
2947 // This is required to be able to call JNI functions to create JDWP ids. To achieve this,
2948 // we temporarily clear the current thread's exception (if any) and will restore it after
2949 // the call.
2950 // Note: the only way to get a pending exception here is to suspend on a move-exception
2951 // instruction.
2952 Thread* const self = Thread::Current();
2953 StackHandleScope<1> hs(self);
2954 Handle<mirror::Throwable> pending_exception(hs.NewHandle(self->GetException()));
2955 self->ClearException();
Andreas Gampefa4333d2017-02-14 11:10:34 -08002956 if (kIsDebugBuild && pending_exception != nullptr) {
Sebastien Hertzde48aa62015-05-26 11:53:39 +02002957 const DexFile::CodeItem* code_item = location.method->GetCodeItem();
2958 const Instruction* instr = Instruction::At(&code_item->insns_[location.dex_pc]);
2959 CHECK_EQ(Instruction::MOVE_EXCEPTION, instr->Opcode());
2960 }
2961
Sebastien Hertz6995c602014-09-09 12:10:13 +02002962 gJdwpState->PostLocationEvent(&location, this_object, event_flags, return_value);
Sebastien Hertzde48aa62015-05-26 11:53:39 +02002963
Andreas Gampefa4333d2017-02-14 11:10:34 -08002964 if (pending_exception != nullptr) {
Sebastien Hertzde48aa62015-05-26 11:53:39 +02002965 self->SetException(pending_exception.Get());
2966 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002967}
2968
Mathieu Chartiere401d142015-04-22 13:56:20 -07002969void Dbg::PostFieldAccessEvent(ArtMethod* m, int dex_pc,
Mathieu Chartierc7853442015-03-27 14:35:38 -07002970 mirror::Object* this_object, ArtField* f) {
Alex Lighte00ec302017-06-16 08:56:43 -07002971 // TODO We should send events for native methods.
2972 if (!IsDebuggerActive() || m->IsNative()) {
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002973 return;
2974 }
2975 DCHECK(m != nullptr);
2976 DCHECK(f != nullptr);
Sebastien Hertz6995c602014-09-09 12:10:13 +02002977 JDWP::EventLocation location;
2978 SetEventLocation(&location, m, dex_pc);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002979
Sebastien Hertz6995c602014-09-09 12:10:13 +02002980 gJdwpState->PostFieldEvent(&location, f, this_object, nullptr, false);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002981}
2982
Mathieu Chartiere401d142015-04-22 13:56:20 -07002983void Dbg::PostFieldModificationEvent(ArtMethod* m, int dex_pc,
Mathieu Chartierc7853442015-03-27 14:35:38 -07002984 mirror::Object* this_object, ArtField* f,
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002985 const JValue* field_value) {
Alex Lighte00ec302017-06-16 08:56:43 -07002986 // TODO We should send events for native methods.
2987 if (!IsDebuggerActive() || m->IsNative()) {
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002988 return;
2989 }
2990 DCHECK(m != nullptr);
2991 DCHECK(f != nullptr);
2992 DCHECK(field_value != nullptr);
Sebastien Hertz6995c602014-09-09 12:10:13 +02002993 JDWP::EventLocation location;
2994 SetEventLocation(&location, m, dex_pc);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002995
Sebastien Hertz6995c602014-09-09 12:10:13 +02002996 gJdwpState->PostFieldEvent(&location, f, this_object, field_value, true);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002997}
2998
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002999/**
3000 * Finds the location where this exception will be caught. We search until we reach the top
3001 * frame, in which case this exception is considered uncaught.
3002 */
3003class CatchLocationFinder : public StackVisitor {
3004 public:
3005 CatchLocationFinder(Thread* self, const Handle<mirror::Throwable>& exception, Context* context)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003006 REQUIRES_SHARED(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01003007 : StackVisitor(self, context, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003008 exception_(exception),
3009 handle_scope_(self),
3010 this_at_throw_(handle_scope_.NewHandle<mirror::Object>(nullptr)),
Mathieu Chartiere401d142015-04-22 13:56:20 -07003011 catch_method_(nullptr),
3012 throw_method_(nullptr),
Andreas Gampee2abbc62017-09-15 11:59:26 -07003013 catch_dex_pc_(dex::kDexNoIndex),
3014 throw_dex_pc_(dex::kDexNoIndex) {
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003015 }
3016
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003017 bool VisitFrame() OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003018 ArtMethod* method = GetMethod();
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003019 DCHECK(method != nullptr);
3020 if (method->IsRuntimeMethod()) {
3021 // Ignore callee save method.
3022 DCHECK(method->IsCalleeSaveMethod());
3023 return true;
3024 }
3025
3026 uint32_t dex_pc = GetDexPc();
Mathieu Chartiere401d142015-04-22 13:56:20 -07003027 if (throw_method_ == nullptr) {
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003028 // First Java method found. It is either the method that threw the exception,
3029 // or the Java native method that is reporting an exception thrown by
3030 // native code.
3031 this_at_throw_.Assign(GetThisObject());
Mathieu Chartiere401d142015-04-22 13:56:20 -07003032 throw_method_ = method;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003033 throw_dex_pc_ = dex_pc;
3034 }
3035
Andreas Gampee2abbc62017-09-15 11:59:26 -07003036 if (dex_pc != dex::kDexNoIndex) {
Sebastien Hertz26f72862015-09-15 09:52:07 +02003037 StackHandleScope<1> hs(GetThread());
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003038 uint32_t found_dex_pc;
3039 Handle<mirror::Class> exception_class(hs.NewHandle(exception_->GetClass()));
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003040 bool unused_clear_exception;
Mathieu Chartiere401d142015-04-22 13:56:20 -07003041 found_dex_pc = method->FindCatchBlock(exception_class, dex_pc, &unused_clear_exception);
Andreas Gampee2abbc62017-09-15 11:59:26 -07003042 if (found_dex_pc != dex::kDexNoIndex) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003043 catch_method_ = method;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003044 catch_dex_pc_ = found_dex_pc;
3045 return false; // End stack walk.
3046 }
3047 }
3048 return true; // Continue stack walk.
3049 }
3050
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003051 ArtMethod* GetCatchMethod() REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003052 return catch_method_;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003053 }
3054
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003055 ArtMethod* GetThrowMethod() REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003056 return throw_method_;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003057 }
3058
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003059 mirror::Object* GetThisAtThrow() REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003060 return this_at_throw_.Get();
3061 }
3062
3063 uint32_t GetCatchDexPc() const {
3064 return catch_dex_pc_;
3065 }
3066
3067 uint32_t GetThrowDexPc() const {
3068 return throw_dex_pc_;
3069 }
3070
3071 private:
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003072 const Handle<mirror::Throwable>& exception_;
Mathieu Chartiere401d142015-04-22 13:56:20 -07003073 StackHandleScope<1> handle_scope_;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003074 MutableHandle<mirror::Object> this_at_throw_;
Mathieu Chartiere401d142015-04-22 13:56:20 -07003075 ArtMethod* catch_method_;
3076 ArtMethod* throw_method_;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003077 uint32_t catch_dex_pc_;
3078 uint32_t throw_dex_pc_;
3079
3080 DISALLOW_COPY_AND_ASSIGN(CatchLocationFinder);
3081};
3082
3083void Dbg::PostException(mirror::Throwable* exception_object) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07003084 if (!IsDebuggerActive()) {
Ian Rogers0ad5bb82011-12-07 10:16:32 -08003085 return;
3086 }
Sebastien Hertz261bc042015-04-08 09:36:07 +02003087 Thread* const self = Thread::Current();
3088 StackHandleScope<1> handle_scope(self);
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003089 Handle<mirror::Throwable> h_exception(handle_scope.NewHandle(exception_object));
3090 std::unique_ptr<Context> context(Context::Create());
Sebastien Hertz261bc042015-04-08 09:36:07 +02003091 CatchLocationFinder clf(self, h_exception, context.get());
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003092 clf.WalkStack(/* include_transitions */ false);
Sebastien Hertz6995c602014-09-09 12:10:13 +02003093 JDWP::EventLocation exception_throw_location;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003094 SetEventLocation(&exception_throw_location, clf.GetThrowMethod(), clf.GetThrowDexPc());
Sebastien Hertz6995c602014-09-09 12:10:13 +02003095 JDWP::EventLocation exception_catch_location;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003096 SetEventLocation(&exception_catch_location, clf.GetCatchMethod(), clf.GetCatchDexPc());
Elliott Hughes4740cdf2011-12-07 14:07:12 -08003097
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003098 gJdwpState->PostException(&exception_throw_location, h_exception.Get(), &exception_catch_location,
3099 clf.GetThisAtThrow());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003100}
3101
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003102void Dbg::PostClassPrepare(mirror::Class* c) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07003103 if (!IsDebuggerActive()) {
Elliott Hughes4740cdf2011-12-07 14:07:12 -08003104 return;
3105 }
Sebastien Hertz6995c602014-09-09 12:10:13 +02003106 gJdwpState->PostClassPrepare(c);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003107}
3108
Ian Rogers62d6c772013-02-27 08:32:07 -08003109void Dbg::UpdateDebugger(Thread* thread, mirror::Object* this_object,
Mathieu Chartiere401d142015-04-22 13:56:20 -07003110 ArtMethod* m, uint32_t dex_pc,
Sebastien Hertz8379b222014-02-24 17:38:15 +01003111 int event_flags, const JValue* return_value) {
Ian Rogers62d6c772013-02-27 08:32:07 -08003112 if (!IsDebuggerActive() || dex_pc == static_cast<uint32_t>(-2) /* fake method exit */) {
Elliott Hughes2aa2e392012-02-17 17:15:43 -08003113 return;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003114 }
3115
Elliott Hughes86964332012-02-15 19:37:42 -08003116 if (IsBreakpoint(m, dex_pc)) {
3117 event_flags |= kBreakpoint;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003118 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003119
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003120 // If the debugger is single-stepping one of our threads, check to
3121 // see if we're that thread and we've reached a step point.
3122 const SingleStepControl* single_step_control = thread->GetSingleStepControl();
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003123 if (single_step_control != nullptr) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003124 CHECK(!m->IsNative());
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003125 if (single_step_control->GetStepDepth() == JDWP::SD_INTO) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003126 // Step into method calls. We break when the line number
3127 // or method pointer changes. If we're in SS_MIN mode, we
3128 // always stop.
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003129 if (single_step_control->GetMethod() != m) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003130 event_flags |= kSingleStep;
3131 VLOG(jdwp) << "SS new method";
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003132 } else if (single_step_control->GetStepSize() == JDWP::SS_MIN) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003133 event_flags |= kSingleStep;
3134 VLOG(jdwp) << "SS new instruction";
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003135 } else if (single_step_control->ContainsDexPc(dex_pc)) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003136 event_flags |= kSingleStep;
3137 VLOG(jdwp) << "SS new line";
3138 }
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003139 } else if (single_step_control->GetStepDepth() == JDWP::SD_OVER) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003140 // Step over method calls. We break when the line number is
3141 // different and the frame depth is <= the original frame
3142 // depth. (We can't just compare on the method, because we
3143 // might get unrolled past it by an exception, and it's tricky
3144 // to identify recursion.)
3145
3146 int stack_depth = GetStackDepth(thread);
3147
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003148 if (stack_depth < single_step_control->GetStackDepth()) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003149 // Popped up one or more frames, always trigger.
3150 event_flags |= kSingleStep;
3151 VLOG(jdwp) << "SS method pop";
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003152 } else if (stack_depth == single_step_control->GetStackDepth()) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003153 // Same depth, see if we moved.
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003154 if (single_step_control->GetStepSize() == JDWP::SS_MIN) {
Elliott Hughes86964332012-02-15 19:37:42 -08003155 event_flags |= kSingleStep;
3156 VLOG(jdwp) << "SS new instruction";
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003157 } else if (single_step_control->ContainsDexPc(dex_pc)) {
Elliott Hughes2435a572012-02-17 16:07:41 -08003158 event_flags |= kSingleStep;
3159 VLOG(jdwp) << "SS new line";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003160 }
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003161 }
3162 } else {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003163 CHECK_EQ(single_step_control->GetStepDepth(), JDWP::SD_OUT);
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003164 // Return from the current method. We break when the frame
3165 // depth pops up.
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003166
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003167 // This differs from the "method exit" break in that it stops
3168 // with the PC at the next instruction in the returned-to
3169 // function, rather than the end of the returning function.
Elliott Hughes86964332012-02-15 19:37:42 -08003170
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003171 int stack_depth = GetStackDepth(thread);
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003172 if (stack_depth < single_step_control->GetStackDepth()) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003173 event_flags |= kSingleStep;
3174 VLOG(jdwp) << "SS method pop";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003175 }
3176 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003177 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003178
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003179 // If there's something interesting going on, see if it matches one
3180 // of the debugger filters.
3181 if (event_flags != 0) {
Sebastien Hertz8379b222014-02-24 17:38:15 +01003182 Dbg::PostLocationEvent(m, dex_pc, this_object, event_flags, return_value);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003183 }
3184}
3185
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003186size_t* Dbg::GetReferenceCounterForEvent(uint32_t instrumentation_event) {
3187 switch (instrumentation_event) {
3188 case instrumentation::Instrumentation::kMethodEntered:
3189 return &method_enter_event_ref_count_;
3190 case instrumentation::Instrumentation::kMethodExited:
3191 return &method_exit_event_ref_count_;
3192 case instrumentation::Instrumentation::kDexPcMoved:
3193 return &dex_pc_change_event_ref_count_;
3194 case instrumentation::Instrumentation::kFieldRead:
3195 return &field_read_event_ref_count_;
3196 case instrumentation::Instrumentation::kFieldWritten:
3197 return &field_write_event_ref_count_;
Alex Light6e1607e2017-08-23 10:06:18 -07003198 case instrumentation::Instrumentation::kExceptionThrown:
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003199 return &exception_catch_event_ref_count_;
3200 default:
3201 return nullptr;
3202 }
3203}
3204
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003205// Process request while all mutator threads are suspended.
3206void Dbg::ProcessDeoptimizationRequest(const DeoptimizationRequest& request) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003207 instrumentation::Instrumentation* instrumentation = Runtime::Current()->GetInstrumentation();
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003208 switch (request.GetKind()) {
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003209 case DeoptimizationRequest::kNothing:
3210 LOG(WARNING) << "Ignoring empty deoptimization request.";
3211 break;
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003212 case DeoptimizationRequest::kRegisterForEvent:
3213 VLOG(jdwp) << StringPrintf("Add debugger as listener for instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003214 request.InstrumentationEvent());
3215 instrumentation->AddListener(&gDebugInstrumentationListener, request.InstrumentationEvent());
3216 instrumentation_events_ |= request.InstrumentationEvent();
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003217 break;
3218 case DeoptimizationRequest::kUnregisterForEvent:
3219 VLOG(jdwp) << StringPrintf("Remove debugger as listener for instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003220 request.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003221 instrumentation->RemoveListener(&gDebugInstrumentationListener,
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003222 request.InstrumentationEvent());
3223 instrumentation_events_ &= ~request.InstrumentationEvent();
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003224 break;
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003225 case DeoptimizationRequest::kFullDeoptimization:
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003226 VLOG(jdwp) << "Deoptimize the world ...";
Sebastien Hertz0462c4c2015-04-01 16:34:17 +02003227 instrumentation->DeoptimizeEverything(kDbgInstrumentationKey);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003228 VLOG(jdwp) << "Deoptimize the world DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003229 break;
3230 case DeoptimizationRequest::kFullUndeoptimization:
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003231 VLOG(jdwp) << "Undeoptimize the world ...";
Sebastien Hertz0462c4c2015-04-01 16:34:17 +02003232 instrumentation->UndeoptimizeEverything(kDbgInstrumentationKey);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003233 VLOG(jdwp) << "Undeoptimize the world DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003234 break;
3235 case DeoptimizationRequest::kSelectiveDeoptimization:
David Sehr709b0702016-10-13 09:12:37 -07003236 VLOG(jdwp) << "Deoptimize method " << ArtMethod::PrettyMethod(request.Method()) << " ...";
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003237 instrumentation->Deoptimize(request.Method());
David Sehr709b0702016-10-13 09:12:37 -07003238 VLOG(jdwp) << "Deoptimize method " << ArtMethod::PrettyMethod(request.Method()) << " DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003239 break;
3240 case DeoptimizationRequest::kSelectiveUndeoptimization:
David Sehr709b0702016-10-13 09:12:37 -07003241 VLOG(jdwp) << "Undeoptimize method " << ArtMethod::PrettyMethod(request.Method()) << " ...";
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003242 instrumentation->Undeoptimize(request.Method());
David Sehr709b0702016-10-13 09:12:37 -07003243 VLOG(jdwp) << "Undeoptimize method " << ArtMethod::PrettyMethod(request.Method()) << " DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003244 break;
3245 default:
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003246 LOG(FATAL) << "Unsupported deoptimization request kind " << request.GetKind();
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003247 break;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003248 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003249}
3250
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003251void Dbg::RequestDeoptimization(const DeoptimizationRequest& req) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003252 if (req.GetKind() == DeoptimizationRequest::kNothing) {
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003253 // Nothing to do.
3254 return;
3255 }
Brian Carlstrom306db812014-09-05 13:01:41 -07003256 MutexLock mu(Thread::Current(), *Locks::deoptimization_lock_);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003257 RequestDeoptimizationLocked(req);
3258}
3259
3260void Dbg::RequestDeoptimizationLocked(const DeoptimizationRequest& req) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003261 switch (req.GetKind()) {
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003262 case DeoptimizationRequest::kRegisterForEvent: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003263 DCHECK_NE(req.InstrumentationEvent(), 0u);
3264 size_t* counter = GetReferenceCounterForEvent(req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003265 CHECK(counter != nullptr) << StringPrintf("No counter for instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003266 req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003267 if (*counter == 0) {
Sebastien Hertz7d2ae432014-05-15 11:26:34 +02003268 VLOG(jdwp) << StringPrintf("Queue request #%zd to start listening to instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003269 deoptimization_requests_.size(), req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003270 deoptimization_requests_.push_back(req);
3271 }
3272 *counter = *counter + 1;
3273 break;
3274 }
3275 case DeoptimizationRequest::kUnregisterForEvent: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003276 DCHECK_NE(req.InstrumentationEvent(), 0u);
3277 size_t* counter = GetReferenceCounterForEvent(req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003278 CHECK(counter != nullptr) << StringPrintf("No counter for instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003279 req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003280 *counter = *counter - 1;
3281 if (*counter == 0) {
Sebastien Hertz7d2ae432014-05-15 11:26:34 +02003282 VLOG(jdwp) << StringPrintf("Queue request #%zd to stop listening to instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003283 deoptimization_requests_.size(), req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003284 deoptimization_requests_.push_back(req);
3285 }
3286 break;
3287 }
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003288 case DeoptimizationRequest::kFullDeoptimization: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003289 DCHECK(req.Method() == nullptr);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003290 if (full_deoptimization_event_count_ == 0) {
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003291 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
3292 << " for full deoptimization";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003293 deoptimization_requests_.push_back(req);
3294 }
3295 ++full_deoptimization_event_count_;
3296 break;
3297 }
3298 case DeoptimizationRequest::kFullUndeoptimization: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003299 DCHECK(req.Method() == nullptr);
Sebastien Hertze713d932014-05-15 10:48:53 +02003300 DCHECK_GT(full_deoptimization_event_count_, 0U);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003301 --full_deoptimization_event_count_;
3302 if (full_deoptimization_event_count_ == 0) {
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003303 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
3304 << " for full undeoptimization";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003305 deoptimization_requests_.push_back(req);
3306 }
3307 break;
3308 }
3309 case DeoptimizationRequest::kSelectiveDeoptimization: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003310 DCHECK(req.Method() != nullptr);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003311 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
David Sehr709b0702016-10-13 09:12:37 -07003312 << " for deoptimization of " << req.Method()->PrettyMethod();
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003313 deoptimization_requests_.push_back(req);
3314 break;
3315 }
3316 case DeoptimizationRequest::kSelectiveUndeoptimization: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003317 DCHECK(req.Method() != nullptr);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003318 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
David Sehr709b0702016-10-13 09:12:37 -07003319 << " for undeoptimization of " << req.Method()->PrettyMethod();
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003320 deoptimization_requests_.push_back(req);
3321 break;
3322 }
3323 default: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003324 LOG(FATAL) << "Unknown deoptimization request kind " << req.GetKind();
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003325 break;
3326 }
3327 }
3328}
3329
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003330void Dbg::ManageDeoptimization() {
3331 Thread* const self = Thread::Current();
3332 {
3333 // Avoid suspend/resume if there is no pending request.
Brian Carlstrom306db812014-09-05 13:01:41 -07003334 MutexLock mu(self, *Locks::deoptimization_lock_);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003335 if (deoptimization_requests_.empty()) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003336 return;
3337 }
3338 }
3339 CHECK_EQ(self->GetState(), kRunnable);
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07003340 ScopedThreadSuspension sts(self, kWaitingForDeoptimization);
Mathieu Chartieraa516822015-10-02 15:53:37 -07003341 // Required for ProcessDeoptimizationRequest.
3342 gc::ScopedGCCriticalSection gcs(self,
3343 gc::kGcCauseInstrumentation,
3344 gc::kCollectorTypeInstrumentation);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003345 // We need to suspend mutator threads first.
Mathieu Chartier4f55e222015-09-04 13:26:21 -07003346 ScopedSuspendAll ssa(__FUNCTION__);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003347 const ThreadState old_state = self->SetStateUnsafe(kRunnable);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003348 {
Brian Carlstrom306db812014-09-05 13:01:41 -07003349 MutexLock mu(self, *Locks::deoptimization_lock_);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003350 size_t req_index = 0;
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003351 for (DeoptimizationRequest& request : deoptimization_requests_) {
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003352 VLOG(jdwp) << "Process deoptimization request #" << req_index++;
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003353 ProcessDeoptimizationRequest(request);
3354 }
3355 deoptimization_requests_.clear();
3356 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003357 CHECK_EQ(self->SetStateUnsafe(old_state), kRunnable);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003358}
3359
Mathieu Chartiere401d142015-04-22 13:56:20 -07003360static const Breakpoint* FindFirstBreakpointForMethod(ArtMethod* m)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003361 REQUIRES_SHARED(Locks::mutator_lock_, Locks::breakpoint_lock_) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003362 for (Breakpoint& breakpoint : gBreakpoints) {
Alex Light6c8467f2015-11-20 15:03:26 -08003363 if (breakpoint.IsInMethod(m)) {
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003364 return &breakpoint;
3365 }
3366 }
3367 return nullptr;
3368}
3369
Mathieu Chartiere401d142015-04-22 13:56:20 -07003370bool Dbg::MethodHasAnyBreakpoints(ArtMethod* method) {
Mathieu Chartierd8565452015-03-26 09:41:50 -07003371 ReaderMutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
3372 return FindFirstBreakpointForMethod(method) != nullptr;
3373}
3374
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003375// Sanity checks all existing breakpoints on the same method.
Mathieu Chartiere401d142015-04-22 13:56:20 -07003376static void SanityCheckExistingBreakpoints(ArtMethod* m,
Sebastien Hertzf3928792014-11-17 19:00:37 +01003377 DeoptimizationRequest::Kind deoptimization_kind)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003378 REQUIRES_SHARED(Locks::mutator_lock_, Locks::breakpoint_lock_) {
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003379 for (const Breakpoint& breakpoint : gBreakpoints) {
Alex Light6c8467f2015-11-20 15:03:26 -08003380 if (breakpoint.IsInMethod(m)) {
Sebastien Hertzf3928792014-11-17 19:00:37 +01003381 CHECK_EQ(deoptimization_kind, breakpoint.GetDeoptimizationKind());
3382 }
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003383 }
Sebastien Hertzf3928792014-11-17 19:00:37 +01003384 instrumentation::Instrumentation* instrumentation = Runtime::Current()->GetInstrumentation();
3385 if (deoptimization_kind == DeoptimizationRequest::kFullDeoptimization) {
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003386 // We should have deoptimized everything but not "selectively" deoptimized this method.
Sebastien Hertzf3928792014-11-17 19:00:37 +01003387 CHECK(instrumentation->AreAllMethodsDeoptimized());
3388 CHECK(!instrumentation->IsDeoptimized(m));
3389 } else if (deoptimization_kind == DeoptimizationRequest::kSelectiveDeoptimization) {
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003390 // We should have "selectively" deoptimized this method.
3391 // Note: while we have not deoptimized everything for this method, we may have done it for
3392 // another event.
Sebastien Hertzf3928792014-11-17 19:00:37 +01003393 CHECK(instrumentation->IsDeoptimized(m));
3394 } else {
3395 // This method does not require deoptimization.
3396 CHECK_EQ(deoptimization_kind, DeoptimizationRequest::kNothing);
3397 CHECK(!instrumentation->IsDeoptimized(m));
3398 }
3399}
3400
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003401// Returns the deoptimization kind required to set a breakpoint in a method.
3402// If a breakpoint has already been set, we also return the first breakpoint
3403// through the given 'existing_brkpt' pointer.
Sebastien Hertzf3928792014-11-17 19:00:37 +01003404static DeoptimizationRequest::Kind GetRequiredDeoptimizationKind(Thread* self,
Mathieu Chartiere401d142015-04-22 13:56:20 -07003405 ArtMethod* m,
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003406 const Breakpoint** existing_brkpt)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003407 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertzf3928792014-11-17 19:00:37 +01003408 if (!Dbg::RequiresDeoptimization()) {
3409 // We already run in interpreter-only mode so we don't need to deoptimize anything.
3410 VLOG(jdwp) << "No need for deoptimization when fully running with interpreter for method "
David Sehr709b0702016-10-13 09:12:37 -07003411 << ArtMethod::PrettyMethod(m);
Sebastien Hertzf3928792014-11-17 19:00:37 +01003412 return DeoptimizationRequest::kNothing;
3413 }
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003414 const Breakpoint* first_breakpoint;
Sebastien Hertzf3928792014-11-17 19:00:37 +01003415 {
3416 ReaderMutexLock mu(self, *Locks::breakpoint_lock_);
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003417 first_breakpoint = FindFirstBreakpointForMethod(m);
3418 *existing_brkpt = first_breakpoint;
Sebastien Hertzf3928792014-11-17 19:00:37 +01003419 }
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003420
3421 if (first_breakpoint == nullptr) {
Nicolas Geoffray6300fd72016-03-18 09:40:17 +00003422 // There is no breakpoint on this method yet: we need to deoptimize. If this method is default,
3423 // we deoptimize everything; otherwise we deoptimize only this method. We
Alex Light6c8467f2015-11-20 15:03:26 -08003424 // deoptimize with defaults because we do not know everywhere they are used. It is possible some
Nicolas Geoffray6300fd72016-03-18 09:40:17 +00003425 // of the copies could be missed.
Alex Light6c8467f2015-11-20 15:03:26 -08003426 // TODO Deoptimizing on default methods might not be necessary in all cases.
Nicolas Geoffray6300fd72016-03-18 09:40:17 +00003427 bool need_full_deoptimization = m->IsDefault();
Sebastien Hertzf3928792014-11-17 19:00:37 +01003428 if (need_full_deoptimization) {
Nicolas Geoffray6300fd72016-03-18 09:40:17 +00003429 VLOG(jdwp) << "Need full deoptimization because of copying of method "
David Sehr709b0702016-10-13 09:12:37 -07003430 << ArtMethod::PrettyMethod(m);
Sebastien Hertzf3928792014-11-17 19:00:37 +01003431 return DeoptimizationRequest::kFullDeoptimization;
3432 } else {
3433 // We don't need to deoptimize if the method has not been compiled.
Nicolas Geoffraya5891e82015-11-06 14:18:27 +00003434 const bool is_compiled = m->HasAnyCompiledCode();
Sebastien Hertzf3928792014-11-17 19:00:37 +01003435 if (is_compiled) {
David Sehr709b0702016-10-13 09:12:37 -07003436 VLOG(jdwp) << "Need selective deoptimization for compiled method "
3437 << ArtMethod::PrettyMethod(m);
Nicolas Geoffray6300fd72016-03-18 09:40:17 +00003438 return DeoptimizationRequest::kSelectiveDeoptimization;
Sebastien Hertzf3928792014-11-17 19:00:37 +01003439 } else {
3440 // Method is not compiled: we don't need to deoptimize.
David Sehr709b0702016-10-13 09:12:37 -07003441 VLOG(jdwp) << "No need for deoptimization for non-compiled method "
3442 << ArtMethod::PrettyMethod(m);
Sebastien Hertzf3928792014-11-17 19:00:37 +01003443 return DeoptimizationRequest::kNothing;
3444 }
3445 }
3446 } else {
3447 // There is at least one breakpoint for this method: we don't need to deoptimize.
3448 // Let's check that all breakpoints are configured the same way for deoptimization.
3449 VLOG(jdwp) << "Breakpoint already set: no deoptimization is required";
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003450 DeoptimizationRequest::Kind deoptimization_kind = first_breakpoint->GetDeoptimizationKind();
Sebastien Hertzf3928792014-11-17 19:00:37 +01003451 if (kIsDebugBuild) {
3452 ReaderMutexLock mu(self, *Locks::breakpoint_lock_);
3453 SanityCheckExistingBreakpoints(m, deoptimization_kind);
3454 }
3455 return DeoptimizationRequest::kNothing;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003456 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003457}
3458
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003459// Installs a breakpoint at the specified location. Also indicates through the deoptimization
3460// request if we need to deoptimize.
3461void Dbg::WatchLocation(const JDWP::JdwpLocation* location, DeoptimizationRequest* req) {
3462 Thread* const self = Thread::Current();
Mathieu Chartiere401d142015-04-22 13:56:20 -07003463 ArtMethod* m = FromMethodId(location->method_id);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003464 DCHECK(m != nullptr) << "No method for method id " << location->method_id;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003465
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003466 const Breakpoint* existing_breakpoint = nullptr;
3467 const DeoptimizationRequest::Kind deoptimization_kind =
3468 GetRequiredDeoptimizationKind(self, m, &existing_breakpoint);
Sebastien Hertzf3928792014-11-17 19:00:37 +01003469 req->SetKind(deoptimization_kind);
3470 if (deoptimization_kind == DeoptimizationRequest::kSelectiveDeoptimization) {
3471 req->SetMethod(m);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003472 } else {
Sebastien Hertzf3928792014-11-17 19:00:37 +01003473 CHECK(deoptimization_kind == DeoptimizationRequest::kNothing ||
3474 deoptimization_kind == DeoptimizationRequest::kFullDeoptimization);
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003475 req->SetMethod(nullptr);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003476 }
3477
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003478 {
3479 WriterMutexLock mu(self, *Locks::breakpoint_lock_);
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003480 // If there is at least one existing breakpoint on the same method, the new breakpoint
3481 // must have the same deoptimization kind than the existing breakpoint(s).
3482 DeoptimizationRequest::Kind breakpoint_deoptimization_kind;
3483 if (existing_breakpoint != nullptr) {
3484 breakpoint_deoptimization_kind = existing_breakpoint->GetDeoptimizationKind();
3485 } else {
3486 breakpoint_deoptimization_kind = deoptimization_kind;
3487 }
3488 gBreakpoints.push_back(Breakpoint(m, location->dex_pc, breakpoint_deoptimization_kind));
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003489 VLOG(jdwp) << "Set breakpoint #" << (gBreakpoints.size() - 1) << ": "
3490 << gBreakpoints[gBreakpoints.size() - 1];
3491 }
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003492}
3493
3494// Uninstalls a breakpoint at the specified location. Also indicates through the deoptimization
3495// request if we need to undeoptimize.
3496void Dbg::UnwatchLocation(const JDWP::JdwpLocation* location, DeoptimizationRequest* req) {
Sebastien Hertzed2be172014-08-19 15:33:43 +02003497 WriterMutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003498 ArtMethod* m = FromMethodId(location->method_id);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003499 DCHECK(m != nullptr) << "No method for method id " << location->method_id;
Sebastien Hertzf3928792014-11-17 19:00:37 +01003500 DeoptimizationRequest::Kind deoptimization_kind = DeoptimizationRequest::kNothing;
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003501 for (size_t i = 0, e = gBreakpoints.size(); i < e; ++i) {
Alex Light6c8467f2015-11-20 15:03:26 -08003502 if (gBreakpoints[i].DexPc() == location->dex_pc && gBreakpoints[i].IsInMethod(m)) {
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003503 VLOG(jdwp) << "Removed breakpoint #" << i << ": " << gBreakpoints[i];
Sebastien Hertzf3928792014-11-17 19:00:37 +01003504 deoptimization_kind = gBreakpoints[i].GetDeoptimizationKind();
3505 DCHECK_EQ(deoptimization_kind == DeoptimizationRequest::kSelectiveDeoptimization,
3506 Runtime::Current()->GetInstrumentation()->IsDeoptimized(m));
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003507 gBreakpoints.erase(gBreakpoints.begin() + i);
3508 break;
3509 }
3510 }
3511 const Breakpoint* const existing_breakpoint = FindFirstBreakpointForMethod(m);
3512 if (existing_breakpoint == nullptr) {
3513 // There is no more breakpoint on this method: we need to undeoptimize.
Sebastien Hertzf3928792014-11-17 19:00:37 +01003514 if (deoptimization_kind == DeoptimizationRequest::kFullDeoptimization) {
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003515 // This method required full deoptimization: we need to undeoptimize everything.
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003516 req->SetKind(DeoptimizationRequest::kFullUndeoptimization);
3517 req->SetMethod(nullptr);
Sebastien Hertzf3928792014-11-17 19:00:37 +01003518 } else if (deoptimization_kind == DeoptimizationRequest::kSelectiveDeoptimization) {
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003519 // This method required selective deoptimization: we need to undeoptimize only that method.
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003520 req->SetKind(DeoptimizationRequest::kSelectiveUndeoptimization);
3521 req->SetMethod(m);
Sebastien Hertzf3928792014-11-17 19:00:37 +01003522 } else {
3523 // This method had no need for deoptimization: do nothing.
3524 CHECK_EQ(deoptimization_kind, DeoptimizationRequest::kNothing);
3525 req->SetKind(DeoptimizationRequest::kNothing);
3526 req->SetMethod(nullptr);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003527 }
3528 } else {
3529 // There is at least one breakpoint for this method: we don't need to undeoptimize.
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003530 req->SetKind(DeoptimizationRequest::kNothing);
3531 req->SetMethod(nullptr);
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003532 if (kIsDebugBuild) {
Sebastien Hertzf3928792014-11-17 19:00:37 +01003533 SanityCheckExistingBreakpoints(m, deoptimization_kind);
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003534 }
Elliott Hughes86964332012-02-15 19:37:42 -08003535 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003536}
3537
Mathieu Chartiere401d142015-04-22 13:56:20 -07003538bool Dbg::IsForcedInterpreterNeededForCallingImpl(Thread* thread, ArtMethod* m) {
Daniel Mihalyieb076692014-08-22 17:33:31 +02003539 const SingleStepControl* const ssc = thread->GetSingleStepControl();
3540 if (ssc == nullptr) {
3541 // If we are not single-stepping, then we don't have to force interpreter.
3542 return false;
3543 }
3544 if (Runtime::Current()->GetInstrumentation()->InterpretOnly()) {
3545 // If we are in interpreter only mode, then we don't have to force interpreter.
3546 return false;
3547 }
3548
3549 if (!m->IsNative() && !m->IsProxyMethod()) {
3550 // If we want to step into a method, then we have to force interpreter on that call.
3551 if (ssc->GetStepDepth() == JDWP::SD_INTO) {
3552 return true;
3553 }
3554 }
3555 return false;
3556}
3557
Mathieu Chartiere401d142015-04-22 13:56:20 -07003558bool Dbg::IsForcedInterpreterNeededForResolutionImpl(Thread* thread, ArtMethod* m) {
Daniel Mihalyieb076692014-08-22 17:33:31 +02003559 instrumentation::Instrumentation* const instrumentation =
3560 Runtime::Current()->GetInstrumentation();
3561 // If we are in interpreter only mode, then we don't have to force interpreter.
3562 if (instrumentation->InterpretOnly()) {
3563 return false;
3564 }
3565 // We can only interpret pure Java method.
3566 if (m->IsNative() || m->IsProxyMethod()) {
3567 return false;
3568 }
3569 const SingleStepControl* const ssc = thread->GetSingleStepControl();
3570 if (ssc != nullptr) {
3571 // If we want to step into a method, then we have to force interpreter on that call.
3572 if (ssc->GetStepDepth() == JDWP::SD_INTO) {
3573 return true;
3574 }
3575 // If we are stepping out from a static initializer, by issuing a step
3576 // in or step over, that was implicitly invoked by calling a static method,
3577 // then we need to step into that method. Having a lower stack depth than
3578 // the one the single step control has indicates that the step originates
3579 // from the static initializer.
3580 if (ssc->GetStepDepth() != JDWP::SD_OUT &&
3581 ssc->GetStackDepth() > GetStackDepth(thread)) {
3582 return true;
3583 }
3584 }
3585 // There are cases where we have to force interpreter on deoptimized methods,
3586 // because in some cases the call will not be performed by invoking an entry
3587 // point that has been replaced by the deoptimization, but instead by directly
3588 // invoking the compiled code of the method, for example.
3589 return instrumentation->IsDeoptimized(m);
3590}
3591
Mathieu Chartiere401d142015-04-22 13:56:20 -07003592bool Dbg::IsForcedInstrumentationNeededForResolutionImpl(Thread* thread, ArtMethod* m) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07003593 // The upcall can be null and in that case we don't need to do anything.
Daniel Mihalyieb076692014-08-22 17:33:31 +02003594 if (m == nullptr) {
3595 return false;
3596 }
3597 instrumentation::Instrumentation* const instrumentation =
3598 Runtime::Current()->GetInstrumentation();
3599 // If we are in interpreter only mode, then we don't have to force interpreter.
3600 if (instrumentation->InterpretOnly()) {
3601 return false;
3602 }
3603 // We can only interpret pure Java method.
3604 if (m->IsNative() || m->IsProxyMethod()) {
3605 return false;
3606 }
3607 const SingleStepControl* const ssc = thread->GetSingleStepControl();
3608 if (ssc != nullptr) {
3609 // If we are stepping out from a static initializer, by issuing a step
3610 // out, that was implicitly invoked by calling a static method, then we
3611 // need to step into the caller of that method. Having a lower stack
3612 // depth than the one the single step control has indicates that the
3613 // step originates from the static initializer.
3614 if (ssc->GetStepDepth() == JDWP::SD_OUT &&
3615 ssc->GetStackDepth() > GetStackDepth(thread)) {
3616 return true;
3617 }
3618 }
3619 // If we are returning from a static intializer, that was implicitly
3620 // invoked by calling a static method and the caller is deoptimized,
3621 // then we have to deoptimize the stack without forcing interpreter
3622 // on the static method that was called originally. This problem can
3623 // be solved easily by forcing instrumentation on the called method,
3624 // because the instrumentation exit hook will recognise the need of
3625 // stack deoptimization by calling IsForcedInterpreterNeededForUpcall.
3626 return instrumentation->IsDeoptimized(m);
3627}
3628
Mathieu Chartiere401d142015-04-22 13:56:20 -07003629bool Dbg::IsForcedInterpreterNeededForUpcallImpl(Thread* thread, ArtMethod* m) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07003630 // The upcall can be null and in that case we don't need to do anything.
Daniel Mihalyieb076692014-08-22 17:33:31 +02003631 if (m == nullptr) {
3632 return false;
3633 }
3634 instrumentation::Instrumentation* const instrumentation =
3635 Runtime::Current()->GetInstrumentation();
3636 // If we are in interpreter only mode, then we don't have to force interpreter.
3637 if (instrumentation->InterpretOnly()) {
3638 return false;
3639 }
3640 // We can only interpret pure Java method.
3641 if (m->IsNative() || m->IsProxyMethod()) {
3642 return false;
3643 }
3644 const SingleStepControl* const ssc = thread->GetSingleStepControl();
3645 if (ssc != nullptr) {
3646 // The debugger is not interested in what is happening under the level
3647 // of the step, thus we only force interpreter when we are not below of
3648 // the step.
3649 if (ssc->GetStackDepth() >= GetStackDepth(thread)) {
3650 return true;
3651 }
3652 }
Mingyao Yang99170c62015-07-06 11:10:37 -07003653 if (thread->HasDebuggerShadowFrames()) {
3654 // We need to deoptimize the stack for the exception handling flow so that
3655 // we don't miss any deoptimization that should be done when there are
3656 // debugger shadow frames.
3657 return true;
3658 }
Daniel Mihalyieb076692014-08-22 17:33:31 +02003659 // We have to require stack deoptimization if the upcall is deoptimized.
3660 return instrumentation->IsDeoptimized(m);
3661}
3662
Mingyao Yang99170c62015-07-06 11:10:37 -07003663class NeedsDeoptimizationVisitor : public StackVisitor {
Sebastien Hertz520633b2015-09-08 17:03:36 +02003664 public:
3665 explicit NeedsDeoptimizationVisitor(Thread* self)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003666 REQUIRES_SHARED(Locks::mutator_lock_)
Sebastien Hertz520633b2015-09-08 17:03:36 +02003667 : StackVisitor(self, nullptr, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
3668 needs_deoptimization_(false) {}
3669
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003670 bool VisitFrame() OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz520633b2015-09-08 17:03:36 +02003671 // The visitor is meant to be used when handling exception from compiled code only.
David Sehr709b0702016-10-13 09:12:37 -07003672 CHECK(!IsShadowFrame()) << "We only expect to visit compiled frame: "
3673 << ArtMethod::PrettyMethod(GetMethod());
Sebastien Hertz520633b2015-09-08 17:03:36 +02003674 ArtMethod* method = GetMethod();
3675 if (method == nullptr) {
3676 // We reach an upcall and don't need to deoptimize this part of the stack (ManagedFragment)
3677 // so we can stop the visit.
3678 DCHECK(!needs_deoptimization_);
3679 return false;
3680 }
3681 if (Runtime::Current()->GetInstrumentation()->InterpretOnly()) {
3682 // We found a compiled frame in the stack but instrumentation is set to interpret
3683 // everything: we need to deoptimize.
3684 needs_deoptimization_ = true;
3685 return false;
3686 }
3687 if (Runtime::Current()->GetInstrumentation()->IsDeoptimized(method)) {
3688 // We found a deoptimized method in the stack.
3689 needs_deoptimization_ = true;
3690 return false;
3691 }
Mingyao Yang99170c62015-07-06 11:10:37 -07003692 ShadowFrame* frame = GetThread()->FindDebuggerShadowFrame(GetFrameId());
3693 if (frame != nullptr) {
3694 // The debugger allocated a ShadowFrame to update a variable in the stack: we need to
3695 // deoptimize the stack to execute (and deallocate) this frame.
3696 needs_deoptimization_ = true;
3697 return false;
3698 }
Sebastien Hertz520633b2015-09-08 17:03:36 +02003699 return true;
3700 }
3701
3702 bool NeedsDeoptimization() const {
3703 return needs_deoptimization_;
3704 }
3705
3706 private:
3707 // Do we need to deoptimize the stack?
3708 bool needs_deoptimization_;
3709
3710 DISALLOW_COPY_AND_ASSIGN(NeedsDeoptimizationVisitor);
3711};
3712
3713// Do we need to deoptimize the stack to handle an exception?
3714bool Dbg::IsForcedInterpreterNeededForExceptionImpl(Thread* thread) {
3715 const SingleStepControl* const ssc = thread->GetSingleStepControl();
3716 if (ssc != nullptr) {
3717 // We deopt to step into the catch handler.
3718 return true;
3719 }
3720 // Deoptimization is required if at least one method in the stack needs it. However we
3721 // skip frames that will be unwound (thus not executed).
3722 NeedsDeoptimizationVisitor visitor(thread);
3723 visitor.WalkStack(true); // includes upcall.
3724 return visitor.NeedsDeoptimization();
3725}
3726
Jeff Hao449db332013-04-12 18:30:52 -07003727// Scoped utility class to suspend a thread so that we may do tasks such as walk its stack. Doesn't
3728// cause suspension if the thread is the current thread.
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07003729class ScopedDebuggerThreadSuspension {
Jeff Hao449db332013-04-12 18:30:52 -07003730 public:
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07003731 ScopedDebuggerThreadSuspension(Thread* self, JDWP::ObjectId thread_id)
Mathieu Chartier90443472015-07-16 20:32:27 -07003732 REQUIRES(!Locks::thread_list_lock_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003733 REQUIRES_SHARED(Locks::mutator_lock_) :
Ian Rogersf3d874c2014-07-17 18:52:42 -07003734 thread_(nullptr),
Jeff Hao449db332013-04-12 18:30:52 -07003735 error_(JDWP::ERR_NONE),
3736 self_suspend_(false),
Ian Rogers33e95662013-05-20 20:29:14 -07003737 other_suspend_(false) {
Jeff Hao449db332013-04-12 18:30:52 -07003738 ScopedObjectAccessUnchecked soa(self);
Sebastien Hertz69206392015-04-07 15:54:25 +02003739 thread_ = DecodeThread(soa, thread_id, &error_);
Jeff Hao449db332013-04-12 18:30:52 -07003740 if (error_ == JDWP::ERR_NONE) {
3741 if (thread_ == soa.Self()) {
3742 self_suspend_ = true;
3743 } else {
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07003744 Thread* suspended_thread;
3745 {
3746 ScopedThreadSuspension sts(self, kWaitingForDebuggerSuspension);
3747 jobject thread_peer = Dbg::GetObjectRegistry()->GetJObject(thread_id);
3748 bool timed_out;
3749 ThreadList* const thread_list = Runtime::Current()->GetThreadList();
Sebastien Hertzcdd798d2017-04-18 18:28:51 +02003750 suspended_thread = thread_list->SuspendThreadByPeer(thread_peer,
3751 /* request_suspension */ true,
Alex Light46f93402017-06-29 11:59:50 -07003752 SuspendReason::kForDebugger,
Sebastien Hertzcdd798d2017-04-18 18:28:51 +02003753 &timed_out);
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07003754 }
Ian Rogersf3d874c2014-07-17 18:52:42 -07003755 if (suspended_thread == nullptr) {
Jeff Hao449db332013-04-12 18:30:52 -07003756 // Thread terminated from under us while suspending.
3757 error_ = JDWP::ERR_INVALID_THREAD;
3758 } else {
3759 CHECK_EQ(suspended_thread, thread_);
3760 other_suspend_ = true;
3761 }
3762 }
3763 }
Elliott Hughes2435a572012-02-17 16:07:41 -08003764 }
Elliott Hughes86964332012-02-15 19:37:42 -08003765
Jeff Hao449db332013-04-12 18:30:52 -07003766 Thread* GetThread() const {
3767 return thread_;
3768 }
3769
3770 JDWP::JdwpError GetError() const {
3771 return error_;
3772 }
3773
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07003774 ~ScopedDebuggerThreadSuspension() {
Jeff Hao449db332013-04-12 18:30:52 -07003775 if (other_suspend_) {
Alex Light88fd7202017-06-30 08:31:59 -07003776 bool resumed = Runtime::Current()->GetThreadList()->Resume(thread_,
3777 SuspendReason::kForDebugger);
3778 DCHECK(resumed);
Jeff Hao449db332013-04-12 18:30:52 -07003779 }
3780 }
3781
3782 private:
3783 Thread* thread_;
3784 JDWP::JdwpError error_;
3785 bool self_suspend_;
3786 bool other_suspend_;
3787};
3788
3789JDWP::JdwpError Dbg::ConfigureStep(JDWP::ObjectId thread_id, JDWP::JdwpStepSize step_size,
3790 JDWP::JdwpStepDepth step_depth) {
3791 Thread* self = Thread::Current();
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07003792 ScopedDebuggerThreadSuspension sts(self, thread_id);
Jeff Hao449db332013-04-12 18:30:52 -07003793 if (sts.GetError() != JDWP::ERR_NONE) {
3794 return sts.GetError();
3795 }
3796
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003797 // Work out what ArtMethod* we're in, the current line number, and how deep the stack currently
Elliott Hughes2435a572012-02-17 16:07:41 -08003798 // is for step-out.
Ian Rogers0399dde2012-06-06 17:09:28 -07003799 struct SingleStepStackVisitor : public StackVisitor {
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003800 explicit SingleStepStackVisitor(Thread* thread) REQUIRES_SHARED(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01003801 : StackVisitor(thread, nullptr, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
3802 stack_depth(0),
3803 method(nullptr),
3804 line_number(-1) {}
Ian Rogersca190662012-06-26 15:45:57 -07003805
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003806 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
3807 // annotalysis.
3808 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003809 ArtMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07003810 if (!m->IsRuntimeMethod()) {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003811 ++stack_depth;
3812 if (method == nullptr) {
Alex Light73376312017-04-06 10:10:51 -07003813 const DexFile* dex_file = m->GetDexFile();
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003814 method = m;
Alex Light73376312017-04-06 10:10:51 -07003815 if (dex_file != nullptr) {
David Sehr9323e6e2016-09-13 08:58:35 -07003816 line_number = annotations::GetLineNumFromPC(dex_file, m, GetDexPc());
Elliott Hughes2435a572012-02-17 16:07:41 -08003817 }
Elliott Hughes86964332012-02-15 19:37:42 -08003818 }
3819 }
Elliott Hughes530fa002012-03-12 11:44:49 -07003820 return true;
Elliott Hughes86964332012-02-15 19:37:42 -08003821 }
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003822
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003823 int stack_depth;
Mathieu Chartiere401d142015-04-22 13:56:20 -07003824 ArtMethod* method;
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003825 int32_t line_number;
Elliott Hughes86964332012-02-15 19:37:42 -08003826 };
Jeff Hao449db332013-04-12 18:30:52 -07003827
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003828 Thread* const thread = sts.GetThread();
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003829 SingleStepStackVisitor visitor(thread);
Ian Rogers0399dde2012-06-06 17:09:28 -07003830 visitor.WalkStack();
Elliott Hughes86964332012-02-15 19:37:42 -08003831
Elliott Hughes2435a572012-02-17 16:07:41 -08003832 // Find the dex_pc values that correspond to the current line, for line-based single-stepping.
Elliott Hughes2435a572012-02-17 16:07:41 -08003833 struct DebugCallbackContext {
Roland Levillain3887c462015-08-12 18:15:42 +01003834 DebugCallbackContext(SingleStepControl* single_step_control_cb,
3835 int32_t line_number_cb, const DexFile::CodeItem* code_item)
3836 : single_step_control_(single_step_control_cb), line_number_(line_number_cb),
3837 code_item_(code_item), last_pc_valid(false), last_pc(0) {
Elliott Hughes2435a572012-02-17 16:07:41 -08003838 }
3839
David Srbeckyb06e28e2015-12-10 13:15:00 +00003840 static bool Callback(void* raw_context, const DexFile::PositionInfo& entry) {
Elliott Hughes2435a572012-02-17 16:07:41 -08003841 DebugCallbackContext* context = reinterpret_cast<DebugCallbackContext*>(raw_context);
David Srbeckyb06e28e2015-12-10 13:15:00 +00003842 if (static_cast<int32_t>(entry.line_) == context->line_number_) {
Elliott Hughes2435a572012-02-17 16:07:41 -08003843 if (!context->last_pc_valid) {
3844 // Everything from this address until the next line change is ours.
David Srbeckyb06e28e2015-12-10 13:15:00 +00003845 context->last_pc = entry.address_;
Elliott Hughes2435a572012-02-17 16:07:41 -08003846 context->last_pc_valid = true;
3847 }
3848 // Otherwise, if we're already in a valid range for this line,
3849 // just keep going (shouldn't really happen)...
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003850 } else if (context->last_pc_valid) { // and the line number is new
Elliott Hughes2435a572012-02-17 16:07:41 -08003851 // Add everything from the last entry up until here to the set
David Srbeckyb06e28e2015-12-10 13:15:00 +00003852 for (uint32_t dex_pc = context->last_pc; dex_pc < entry.address_; ++dex_pc) {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003853 context->single_step_control_->AddDexPc(dex_pc);
Elliott Hughes2435a572012-02-17 16:07:41 -08003854 }
3855 context->last_pc_valid = false;
3856 }
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003857 return false; // There may be multiple entries for any given line.
Elliott Hughes2435a572012-02-17 16:07:41 -08003858 }
3859
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003860 ~DebugCallbackContext() {
Elliott Hughes2435a572012-02-17 16:07:41 -08003861 // If the line number was the last in the position table...
3862 if (last_pc_valid) {
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003863 size_t end = code_item_->insns_size_in_code_units_;
Elliott Hughes2435a572012-02-17 16:07:41 -08003864 for (uint32_t dex_pc = last_pc; dex_pc < end; ++dex_pc) {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003865 single_step_control_->AddDexPc(dex_pc);
Elliott Hughes2435a572012-02-17 16:07:41 -08003866 }
3867 }
3868 }
3869
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003870 SingleStepControl* const single_step_control_;
3871 const int32_t line_number_;
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003872 const DexFile::CodeItem* const code_item_;
Elliott Hughes2435a572012-02-17 16:07:41 -08003873 bool last_pc_valid;
3874 uint32_t last_pc;
3875 };
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003876
3877 // Allocate single step.
Sebastien Hertz1558b572015-02-25 15:05:59 +01003878 SingleStepControl* single_step_control =
3879 new (std::nothrow) SingleStepControl(step_size, step_depth,
3880 visitor.stack_depth, visitor.method);
3881 if (single_step_control == nullptr) {
3882 LOG(ERROR) << "Failed to allocate SingleStepControl";
3883 return JDWP::ERR_OUT_OF_MEMORY;
3884 }
3885
Mathieu Chartiere401d142015-04-22 13:56:20 -07003886 ArtMethod* m = single_step_control->GetMethod();
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003887 const int32_t line_number = visitor.line_number;
Sebastien Hertz52f5f932015-05-28 11:00:57 +02003888 // Note: if the thread is not running Java code (pure native thread), there is no "current"
3889 // method on the stack (and no line number either).
3890 if (m != nullptr && !m->IsNative()) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003891 const DexFile::CodeItem* const code_item = m->GetCodeItem();
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003892 DebugCallbackContext context(single_step_control, line_number, code_item);
Nicolas Geoffray58cc1cb2017-11-20 13:27:29 +00003893 uint32_t debug_info_offset = OatFile::GetDebugInfoOffset(*(m->GetDexFile()), code_item);
3894 m->GetDexFile()->DecodeDebugPositionInfo(
3895 code_item, debug_info_offset, DebugCallbackContext::Callback, &context);
Elliott Hughes3e2e1a22012-02-21 11:33:41 -08003896 }
Elliott Hughes2435a572012-02-17 16:07:41 -08003897
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003898 // Activate single-step in the thread.
3899 thread->ActivateSingleStepControl(single_step_control);
Elliott Hughes86964332012-02-15 19:37:42 -08003900
Elliott Hughes2435a572012-02-17 16:07:41 -08003901 if (VLOG_IS_ON(jdwp)) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003902 VLOG(jdwp) << "Single-step thread: " << *thread;
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003903 VLOG(jdwp) << "Single-step step size: " << single_step_control->GetStepSize();
3904 VLOG(jdwp) << "Single-step step depth: " << single_step_control->GetStepDepth();
David Sehr709b0702016-10-13 09:12:37 -07003905 VLOG(jdwp) << "Single-step current method: "
3906 << ArtMethod::PrettyMethod(single_step_control->GetMethod());
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003907 VLOG(jdwp) << "Single-step current line: " << line_number;
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003908 VLOG(jdwp) << "Single-step current stack depth: " << single_step_control->GetStackDepth();
Elliott Hughes2435a572012-02-17 16:07:41 -08003909 VLOG(jdwp) << "Single-step dex_pc values:";
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003910 for (uint32_t dex_pc : single_step_control->GetDexPcs()) {
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003911 VLOG(jdwp) << StringPrintf(" %#x", dex_pc);
Elliott Hughes2435a572012-02-17 16:07:41 -08003912 }
3913 }
3914
3915 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003916}
3917
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003918void Dbg::UnconfigureStep(JDWP::ObjectId thread_id) {
3919 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07003920 JDWP::JdwpError error;
3921 Thread* thread = DecodeThread(soa, thread_id, &error);
Sebastien Hertz87118ed2013-11-26 17:57:18 +01003922 if (error == JDWP::ERR_NONE) {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003923 thread->DeactivateSingleStepControl();
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003924 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003925}
3926
Elliott Hughes45651fd2012-02-21 15:48:20 -08003927static char JdwpTagToShortyChar(JDWP::JdwpTag tag) {
3928 switch (tag) {
3929 default:
3930 LOG(FATAL) << "unknown JDWP tag: " << PrintableChar(tag);
Ian Rogersfc787ec2014-10-09 21:56:44 -07003931 UNREACHABLE();
Elliott Hughes45651fd2012-02-21 15:48:20 -08003932
3933 // Primitives.
3934 case JDWP::JT_BYTE: return 'B';
3935 case JDWP::JT_CHAR: return 'C';
3936 case JDWP::JT_FLOAT: return 'F';
3937 case JDWP::JT_DOUBLE: return 'D';
3938 case JDWP::JT_INT: return 'I';
3939 case JDWP::JT_LONG: return 'J';
3940 case JDWP::JT_SHORT: return 'S';
3941 case JDWP::JT_VOID: return 'V';
3942 case JDWP::JT_BOOLEAN: return 'Z';
3943
3944 // Reference types.
3945 case JDWP::JT_ARRAY:
3946 case JDWP::JT_OBJECT:
3947 case JDWP::JT_STRING:
3948 case JDWP::JT_THREAD:
3949 case JDWP::JT_THREAD_GROUP:
3950 case JDWP::JT_CLASS_LOADER:
3951 case JDWP::JT_CLASS_OBJECT:
3952 return 'L';
3953 }
3954}
3955
Sebastien Hertzcbc50642015-06-01 17:33:12 +02003956JDWP::JdwpError Dbg::PrepareInvokeMethod(uint32_t request_id, JDWP::ObjectId thread_id,
3957 JDWP::ObjectId object_id, JDWP::RefTypeId class_id,
3958 JDWP::MethodId method_id, uint32_t arg_count,
3959 uint64_t arg_values[], JDWP::JdwpTag* arg_types,
3960 uint32_t options) {
3961 Thread* const self = Thread::Current();
3962 CHECK_EQ(self, GetDebugThread()) << "This must be called by the JDWP thread";
Sebastien Hertzd4032e42015-06-12 15:47:34 +02003963 const bool resume_all_threads = ((options & JDWP::INVOKE_SINGLE_THREADED) == 0);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003964
Sebastien Hertzcbc50642015-06-01 17:33:12 +02003965 ThreadList* thread_list = Runtime::Current()->GetThreadList();
Ian Rogersc0542af2014-09-03 16:16:56 -07003966 Thread* targetThread = nullptr;
Elliott Hughesd07986f2011-12-06 18:27:45 -08003967 {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003968 ScopedObjectAccessUnchecked soa(self);
Ian Rogersc0542af2014-09-03 16:16:56 -07003969 JDWP::JdwpError error;
3970 targetThread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08003971 if (error != JDWP::ERR_NONE) {
3972 LOG(ERROR) << "InvokeMethod request for invalid thread id " << thread_id;
3973 return error;
Elliott Hughesd07986f2011-12-06 18:27:45 -08003974 }
Sebastien Hertz1558b572015-02-25 15:05:59 +01003975 if (targetThread->GetInvokeReq() != nullptr) {
3976 // Thread is already invoking a method on behalf of the debugger.
3977 LOG(ERROR) << "InvokeMethod request for thread already invoking a method: " << *targetThread;
3978 return JDWP::ERR_ALREADY_INVOKING;
3979 }
3980 if (!targetThread->IsReadyForDebugInvoke()) {
3981 // Thread is not suspended by an event so it cannot invoke a method.
Elliott Hughesd07986f2011-12-06 18:27:45 -08003982 LOG(ERROR) << "InvokeMethod request for thread not stopped by event: " << *targetThread;
3983 return JDWP::ERR_INVALID_THREAD;
3984 }
3985
3986 /*
Sebastien Hertzd4032e42015-06-12 15:47:34 +02003987 * According to the JDWP specs, we are expected to resume all threads (or only the
3988 * target thread) once. So if a thread has been suspended more than once (either by
3989 * the debugger for an event or by the runtime for GC), it will remain suspended before
3990 * the invoke is executed. This means the debugger is responsible to properly resume all
3991 * the threads it has suspended so the target thread can execute the method.
Elliott Hughesd07986f2011-12-06 18:27:45 -08003992 *
Sebastien Hertzd4032e42015-06-12 15:47:34 +02003993 * However, for compatibility reason with older versions of debuggers (like Eclipse), we
3994 * fully resume all threads (by canceling *all* debugger suspensions) when the debugger
3995 * wants us to resume all threads. This is to avoid ending up in deadlock situation.
3996 *
3997 * On the other hand, if we are asked to only resume the target thread, then we follow the
3998 * JDWP specs by resuming that thread only once. This means the thread will remain suspended
3999 * if it has been suspended more than once before the invoke (and again, this is the
4000 * responsibility of the debugger to properly resume that thread before invoking a method).
Elliott Hughesd07986f2011-12-06 18:27:45 -08004001 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004002 int suspend_count;
4003 {
Ian Rogers50b35e22012-10-04 10:09:15 -07004004 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004005 suspend_count = targetThread->GetSuspendCount();
4006 }
Sebastien Hertzd4032e42015-06-12 15:47:34 +02004007 if (suspend_count > 1 && resume_all_threads) {
4008 // The target thread will remain suspended even after we resume it. Let's emit a warning
4009 // to indicate the invoke won't be executed until the thread is resumed.
4010 LOG(WARNING) << *targetThread << " suspended more than once (suspend count == "
4011 << suspend_count << "). This thread will invoke the method only once "
4012 << "it is fully resumed.";
Elliott Hughesd07986f2011-12-06 18:27:45 -08004013 }
4014
Ian Rogersc0542af2014-09-03 16:16:56 -07004015 mirror::Object* receiver = gRegistry->Get<mirror::Object*>(object_id, &error);
4016 if (error != JDWP::ERR_NONE) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08004017 return JDWP::ERR_INVALID_OBJECT;
4018 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08004019
Sebastien Hertz1558b572015-02-25 15:05:59 +01004020 gRegistry->Get<mirror::Object*>(thread_id, &error);
Ian Rogersc0542af2014-09-03 16:16:56 -07004021 if (error != JDWP::ERR_NONE) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08004022 return JDWP::ERR_INVALID_OBJECT;
4023 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08004024
Ian Rogersc0542af2014-09-03 16:16:56 -07004025 mirror::Class* c = DecodeClass(class_id, &error);
4026 if (c == nullptr) {
4027 return error;
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08004028 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08004029
Mathieu Chartiere401d142015-04-22 13:56:20 -07004030 ArtMethod* m = FromMethodId(method_id);
Ian Rogersc0542af2014-09-03 16:16:56 -07004031 if (m->IsStatic() != (receiver == nullptr)) {
Elliott Hughes45651fd2012-02-21 15:48:20 -08004032 return JDWP::ERR_INVALID_METHODID;
4033 }
4034 if (m->IsStatic()) {
4035 if (m->GetDeclaringClass() != c) {
4036 return JDWP::ERR_INVALID_METHODID;
4037 }
4038 } else {
4039 if (!m->GetDeclaringClass()->IsAssignableFrom(c)) {
4040 return JDWP::ERR_INVALID_METHODID;
4041 }
4042 }
4043
4044 // Check the argument list matches the method.
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004045 uint32_t shorty_len = 0;
4046 const char* shorty = m->GetShorty(&shorty_len);
4047 if (shorty_len - 1 != arg_count) {
Elliott Hughes45651fd2012-02-21 15:48:20 -08004048 return JDWP::ERR_ILLEGAL_ARGUMENT;
4049 }
Elliott Hughes09201632013-04-15 15:50:07 -07004050
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004051 {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004052 StackHandleScope<2> hs(soa.Self());
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004053 HandleWrapper<mirror::Object> h_obj(hs.NewHandleWrapper(&receiver));
4054 HandleWrapper<mirror::Class> h_klass(hs.NewHandleWrapper(&c));
4055 const DexFile::TypeList* types = m->GetParameterTypeList();
4056 for (size_t i = 0; i < arg_count; ++i) {
4057 if (shorty[i + 1] != JdwpTagToShortyChar(arg_types[i])) {
Elliott Hughes09201632013-04-15 15:50:07 -07004058 return JDWP::ERR_ILLEGAL_ARGUMENT;
4059 }
4060
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004061 if (shorty[i + 1] == 'L') {
4062 // Did we really get an argument of an appropriate reference type?
Vladimir Markob45528c2017-07-27 14:14:28 +01004063 ObjPtr<mirror::Class> parameter_type =
4064 m->ResolveClassFromTypeIndex(types->GetTypeItem(i).type_idx_);
Ian Rogersc0542af2014-09-03 16:16:56 -07004065 mirror::Object* argument = gRegistry->Get<mirror::Object*>(arg_values[i], &error);
4066 if (error != JDWP::ERR_NONE) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004067 return JDWP::ERR_INVALID_OBJECT;
4068 }
Ian Rogersc0542af2014-09-03 16:16:56 -07004069 if (argument != nullptr && !argument->InstanceOf(parameter_type)) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004070 return JDWP::ERR_ILLEGAL_ARGUMENT;
4071 }
4072
4073 // Turn the on-the-wire ObjectId into a jobject.
4074 jvalue& v = reinterpret_cast<jvalue&>(arg_values[i]);
4075 v.l = gRegistry->GetJObject(arg_values[i]);
4076 }
Elliott Hughes09201632013-04-15 15:50:07 -07004077 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08004078 }
4079
Sebastien Hertz1558b572015-02-25 15:05:59 +01004080 // Allocates a DebugInvokeReq.
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004081 DebugInvokeReq* req = new (std::nothrow) DebugInvokeReq(request_id, thread_id, receiver, c, m,
4082 options, arg_values, arg_count);
4083 if (req == nullptr) {
Sebastien Hertz1558b572015-02-25 15:05:59 +01004084 LOG(ERROR) << "Failed to allocate DebugInvokeReq";
4085 return JDWP::ERR_OUT_OF_MEMORY;
4086 }
4087
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004088 // Attaches the DebugInvokeReq to the target thread so it executes the method when
4089 // it is resumed. Once the invocation completes, the target thread will delete it before
4090 // suspending itself (see ThreadList::SuspendSelfForDebugger).
4091 targetThread->SetDebugInvokeReq(req);
Elliott Hughesd07986f2011-12-06 18:27:45 -08004092 }
4093
4094 // 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 +02004095 // away we're sitting high and dry -- but we must release this before the UndoDebuggerSuspensions
4096 // call.
Sebastien Hertzd4032e42015-06-12 15:47:34 +02004097 if (resume_all_threads) {
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004098 VLOG(jdwp) << " Resuming all threads";
4099 thread_list->UndoDebuggerSuspensions();
4100 } else {
4101 VLOG(jdwp) << " Resuming event thread only";
Alex Light88fd7202017-06-30 08:31:59 -07004102 bool resumed = thread_list->Resume(targetThread, SuspendReason::kForDebugger);
4103 DCHECK(resumed);
Elliott Hughesd07986f2011-12-06 18:27:45 -08004104 }
4105
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004106 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004107}
4108
4109void Dbg::ExecuteMethod(DebugInvokeReq* pReq) {
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004110 Thread* const self = Thread::Current();
4111 CHECK_NE(self, GetDebugThread()) << "This must be called by the event thread";
4112
4113 ScopedObjectAccess soa(self);
Elliott Hughesd07986f2011-12-06 18:27:45 -08004114
Elliott Hughes81ff3182012-03-23 20:35:56 -07004115 // We can be called while an exception is pending. We need
Elliott Hughesd07986f2011-12-06 18:27:45 -08004116 // to preserve that across the method invocation.
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004117 StackHandleScope<1> hs(soa.Self());
4118 Handle<mirror::Throwable> old_exception = hs.NewHandle(soa.Self()->GetException());
Sebastien Hertz1558b572015-02-25 15:05:59 +01004119 soa.Self()->ClearException();
Elliott Hughesd07986f2011-12-06 18:27:45 -08004120
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004121 // Execute the method then sends reply to the debugger.
4122 ExecuteMethodWithoutPendingException(soa, pReq);
4123
4124 // If an exception was pending before the invoke, restore it now.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004125 if (old_exception != nullptr) {
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004126 soa.Self()->SetException(old_exception.Get());
4127 }
4128}
4129
4130// Helper function: write a variable-width value into the output input buffer.
4131static void WriteValue(JDWP::ExpandBuf* pReply, int width, uint64_t value) {
4132 switch (width) {
4133 case 1:
4134 expandBufAdd1(pReply, value);
4135 break;
4136 case 2:
4137 expandBufAdd2BE(pReply, value);
4138 break;
4139 case 4:
4140 expandBufAdd4BE(pReply, value);
4141 break;
4142 case 8:
4143 expandBufAdd8BE(pReply, value);
4144 break;
4145 default:
4146 LOG(FATAL) << width;
4147 UNREACHABLE();
4148 }
4149}
4150
4151void Dbg::ExecuteMethodWithoutPendingException(ScopedObjectAccess& soa, DebugInvokeReq* pReq) {
4152 soa.Self()->AssertNoPendingException();
4153
Elliott Hughesd07986f2011-12-06 18:27:45 -08004154 // Translate the method through the vtable, unless the debugger wants to suppress it.
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004155 ArtMethod* m = pReq->method;
Andreas Gampe542451c2016-07-26 09:02:02 -07004156 PointerSize image_pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
Sebastien Hertz1558b572015-02-25 15:05:59 +01004157 if ((pReq->options & JDWP::INVOKE_NONVIRTUAL) == 0 && pReq->receiver.Read() != nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004158 ArtMethod* actual_method =
4159 pReq->klass.Read()->FindVirtualMethodForVirtualOrInterface(m, image_pointer_size);
4160 if (actual_method != m) {
David Sehr709b0702016-10-13 09:12:37 -07004161 VLOG(jdwp) << "ExecuteMethod translated " << ArtMethod::PrettyMethod(m)
4162 << " to " << ArtMethod::PrettyMethod(actual_method);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004163 m = actual_method;
Elliott Hughes45651fd2012-02-21 15:48:20 -08004164 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08004165 }
David Sehr709b0702016-10-13 09:12:37 -07004166 VLOG(jdwp) << "ExecuteMethod " << ArtMethod::PrettyMethod(m)
Sebastien Hertz1558b572015-02-25 15:05:59 +01004167 << " receiver=" << pReq->receiver.Read()
Sebastien Hertzd38667a2013-11-25 15:43:54 +01004168 << " arg_count=" << pReq->arg_count;
Mathieu Chartiere401d142015-04-22 13:56:20 -07004169 CHECK(m != nullptr);
Elliott Hughesd07986f2011-12-06 18:27:45 -08004170
Roland Levillain33d69032015-06-18 18:20:59 +01004171 static_assert(sizeof(jvalue) == sizeof(uint64_t), "jvalue and uint64_t have different sizes.");
Elliott Hughesd07986f2011-12-06 18:27:45 -08004172
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004173 // Invoke the method.
Jeff Hao39b6c242015-05-19 20:30:23 -07004174 ScopedLocalRef<jobject> ref(soa.Env(), soa.AddLocalReference<jobject>(pReq->receiver.Read()));
Andreas Gampe13b27842016-11-07 16:48:23 -08004175 JValue result = InvokeWithJValues(soa, ref.get(), jni::EncodeArtMethod(m),
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004176 reinterpret_cast<jvalue*>(pReq->arg_values.get()));
Elliott Hughesd07986f2011-12-06 18:27:45 -08004177
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004178 // Prepare JDWP ids for the reply.
4179 JDWP::JdwpTag result_tag = BasicTagFromDescriptor(m->GetShorty());
4180 const bool is_object_result = (result_tag == JDWP::JT_OBJECT);
Jeff Hao064d24e2016-08-25 03:52:40 +00004181 StackHandleScope<3> hs(soa.Self());
Sebastien Hertz1558b572015-02-25 15:05:59 +01004182 Handle<mirror::Object> object_result = hs.NewHandle(is_object_result ? result.GetL() : nullptr);
4183 Handle<mirror::Throwable> exception = hs.NewHandle(soa.Self()->GetException());
4184 soa.Self()->ClearException();
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004185
4186 if (!IsDebuggerActive()) {
4187 // The debugger detached: we must not re-suspend threads. We also don't need to fill the reply
4188 // because it won't be sent either.
4189 return;
4190 }
4191
4192 JDWP::ObjectId exceptionObjectId = gRegistry->Add(exception);
4193 uint64_t result_value = 0;
4194 if (exceptionObjectId != 0) {
Sebastien Hertz1558b572015-02-25 15:05:59 +01004195 VLOG(jdwp) << " JDWP invocation returning with exception=" << exception.Get()
4196 << " " << exception->Dump();
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004197 result_value = 0;
Sebastien Hertz1558b572015-02-25 15:05:59 +01004198 } else if (is_object_result) {
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004199 /* if no exception was thrown, examine object result more closely */
Sebastien Hertz1558b572015-02-25 15:05:59 +01004200 JDWP::JdwpTag new_tag = TagFromObject(soa, object_result.Get());
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004201 if (new_tag != result_tag) {
4202 VLOG(jdwp) << " JDWP promoted result from " << result_tag << " to " << new_tag;
4203 result_tag = new_tag;
Elliott Hughesd07986f2011-12-06 18:27:45 -08004204 }
4205
Sebastien Hertz1558b572015-02-25 15:05:59 +01004206 // Register the object in the registry and reference its ObjectId. This ensures
4207 // GC safety and prevents from accessing stale reference if the object is moved.
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004208 result_value = gRegistry->Add(object_result.Get());
Sebastien Hertz1558b572015-02-25 15:05:59 +01004209 } else {
4210 // Primitive result.
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004211 DCHECK(IsPrimitiveTag(result_tag));
4212 result_value = result.GetJ();
4213 }
4214 const bool is_constructor = m->IsConstructor() && !m->IsStatic();
4215 if (is_constructor) {
4216 // If we invoked a constructor (which actually returns void), return the receiver,
4217 // unless we threw, in which case we return null.
Sebastien Hertza3e13772015-11-05 12:09:44 +01004218 DCHECK_EQ(JDWP::JT_VOID, result_tag);
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004219 if (exceptionObjectId == 0) {
Jeff Hao064d24e2016-08-25 03:52:40 +00004220 if (m->GetDeclaringClass()->IsStringClass()) {
4221 // For string constructors, the new string is remapped to the receiver (stored in ref).
4222 Handle<mirror::Object> decoded_ref = hs.NewHandle(soa.Self()->DecodeJObject(ref.get()));
4223 result_value = gRegistry->Add(decoded_ref);
4224 result_tag = TagFromObject(soa, decoded_ref.Get());
4225 } else {
4226 // TODO we could keep the receiver ObjectId in the DebugInvokeReq to avoid looking into the
4227 // object registry.
4228 result_value = GetObjectRegistry()->Add(pReq->receiver.Read());
4229 result_tag = TagFromObject(soa, pReq->receiver.Read());
4230 }
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004231 } else {
4232 result_value = 0;
Sebastien Hertza3e13772015-11-05 12:09:44 +01004233 result_tag = JDWP::JT_OBJECT;
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004234 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08004235 }
4236
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004237 // Suspend other threads if the invoke is not single-threaded.
4238 if ((pReq->options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07004239 ScopedThreadSuspension sts(soa.Self(), kWaitingForDebuggerSuspension);
Hiroshi Yamauchi8f95cf32016-04-19 11:14:06 -07004240 // Avoid a deadlock between GC and debugger where GC gets suspended during GC. b/25800335.
4241 gc::ScopedGCCriticalSection gcs(soa.Self(), gc::kGcCauseDebugger, gc::kCollectorTypeDebugger);
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004242 VLOG(jdwp) << " Suspending all threads";
4243 Runtime::Current()->GetThreadList()->SuspendAllForDebugger();
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004244 }
4245
4246 VLOG(jdwp) << " --> returned " << result_tag
4247 << StringPrintf(" %#" PRIx64 " (except=%#" PRIx64 ")", result_value,
4248 exceptionObjectId);
4249
4250 // Show detailed debug output.
4251 if (result_tag == JDWP::JT_STRING && exceptionObjectId == 0) {
4252 if (result_value != 0) {
4253 if (VLOG_IS_ON(jdwp)) {
4254 std::string result_string;
4255 JDWP::JdwpError error = Dbg::StringToUtf8(result_value, &result_string);
4256 CHECK_EQ(error, JDWP::ERR_NONE);
4257 VLOG(jdwp) << " string '" << result_string << "'";
4258 }
4259 } else {
4260 VLOG(jdwp) << " string (null)";
4261 }
4262 }
4263
4264 // Attach the reply to DebugInvokeReq so it can be sent to the debugger when the event thread
4265 // is ready to suspend.
4266 BuildInvokeReply(pReq->reply, pReq->request_id, result_tag, result_value, exceptionObjectId);
4267}
4268
4269void Dbg::BuildInvokeReply(JDWP::ExpandBuf* pReply, uint32_t request_id, JDWP::JdwpTag result_tag,
4270 uint64_t result_value, JDWP::ObjectId exception) {
4271 // Make room for the JDWP header since we do not know the size of the reply yet.
4272 JDWP::expandBufAddSpace(pReply, kJDWPHeaderLen);
4273
4274 size_t width = GetTagWidth(result_tag);
4275 JDWP::expandBufAdd1(pReply, result_tag);
4276 if (width != 0) {
4277 WriteValue(pReply, width, result_value);
4278 }
4279 JDWP::expandBufAdd1(pReply, JDWP::JT_OBJECT);
4280 JDWP::expandBufAddObjectId(pReply, exception);
4281
4282 // Now we know the size, we can complete the JDWP header.
4283 uint8_t* buf = expandBufGetBuffer(pReply);
4284 JDWP::Set4BE(buf + kJDWPHeaderSizeOffset, expandBufGetLength(pReply));
4285 JDWP::Set4BE(buf + kJDWPHeaderIdOffset, request_id);
4286 JDWP::Set1(buf + kJDWPHeaderFlagsOffset, kJDWPFlagReply); // flags
4287 JDWP::Set2BE(buf + kJDWPHeaderErrorCodeOffset, JDWP::ERR_NONE);
4288}
4289
4290void Dbg::FinishInvokeMethod(DebugInvokeReq* pReq) {
4291 CHECK_NE(Thread::Current(), GetDebugThread()) << "This must be called by the event thread";
4292
4293 JDWP::ExpandBuf* const pReply = pReq->reply;
4294 CHECK(pReply != nullptr) << "No reply attached to DebugInvokeReq";
4295
4296 // We need to prevent other threads (including JDWP thread) from interacting with the debugger
4297 // while we send the reply but are not yet suspended. The JDWP token will be released just before
4298 // we suspend ourself again (see ThreadList::SuspendSelfForDebugger).
4299 gJdwpState->AcquireJdwpTokenForEvent(pReq->thread_id);
4300
4301 // Send the reply unless the debugger detached before the completion of the method.
4302 if (IsDebuggerActive()) {
4303 const size_t replyDataLength = expandBufGetLength(pReply) - kJDWPHeaderLen;
4304 VLOG(jdwp) << StringPrintf("REPLY INVOKE id=0x%06x (length=%zu)",
4305 pReq->request_id, replyDataLength);
4306
4307 gJdwpState->SendRequest(pReply);
4308 } else {
4309 VLOG(jdwp) << "Not sending invoke reply because debugger detached";
Elliott Hughesd07986f2011-12-06 18:27:45 -08004310 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004311}
4312
Alex Light8c2b9292017-11-09 13:21:01 -08004313bool Dbg::DdmHandleChunk(JNIEnv* env,
4314 uint32_t type,
4315 const ArrayRef<const jbyte>& data,
4316 /*out*/uint32_t* out_type,
4317 /*out*/std::vector<uint8_t>* out_data) {
4318 ScopedLocalRef<jbyteArray> dataArray(env, env->NewByteArray(data.size()));
Ian Rogersc0542af2014-09-03 16:16:56 -07004319 if (dataArray.get() == nullptr) {
Alex Light8c2b9292017-11-09 13:21:01 -08004320 LOG(WARNING) << "byte[] allocation failed: " << data.size();
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004321 env->ExceptionClear();
4322 return false;
4323 }
Alex Light8c2b9292017-11-09 13:21:01 -08004324 env->SetByteArrayRegion(dataArray.get(),
4325 0,
4326 data.size(),
4327 reinterpret_cast<const jbyte*>(data.data()));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004328 // Call "private static Chunk dispatch(int type, byte[] data, int offset, int length)".
Alex Light8c2b9292017-11-09 13:21:01 -08004329 ScopedLocalRef<jobject> chunk(
4330 env,
4331 env->CallStaticObjectMethod(
4332 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
4333 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_dispatch,
4334 type, dataArray.get(), 0, data.size()));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004335 if (env->ExceptionCheck()) {
4336 LOG(INFO) << StringPrintf("Exception thrown by dispatcher for 0x%08x", type);
4337 env->ExceptionDescribe();
4338 env->ExceptionClear();
4339 return false;
4340 }
4341
Ian Rogersc0542af2014-09-03 16:16:56 -07004342 if (chunk.get() == nullptr) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004343 return false;
4344 }
4345
4346 /*
4347 * Pull the pieces out of the chunk. We copy the results into a
4348 * newly-allocated buffer that the caller can free. We don't want to
4349 * continue using the Chunk object because nothing has a reference to it.
4350 *
4351 * We could avoid this by returning type/data/offset/length and having
4352 * the caller be aware of the object lifetime issues, but that
Elliott Hughes81ff3182012-03-23 20:35:56 -07004353 * integrates the JDWP code more tightly into the rest of the runtime, and doesn't work
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004354 * if we have responses for multiple chunks.
4355 *
4356 * So we're pretty much stuck with copying data around multiple times.
4357 */
Alex Light8c2b9292017-11-09 13:21:01 -08004358 ScopedLocalRef<jbyteArray> replyData(
4359 env,
4360 reinterpret_cast<jbyteArray>(
4361 env->GetObjectField(
4362 chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_data)));
4363 jint offset = env->GetIntField(chunk.get(),
4364 WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_offset);
4365 jint length = env->GetIntField(chunk.get(),
4366 WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_length);
4367 *out_type = env->GetIntField(chunk.get(),
4368 WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_type);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004369
Alex Light8c2b9292017-11-09 13:21:01 -08004370 VLOG(jdwp) << StringPrintf("DDM reply: type=0x%08x data=%p offset=%d length=%d",
4371 type,
4372 replyData.get(),
4373 offset,
4374 length);
Ian Rogersc0542af2014-09-03 16:16:56 -07004375 if (length == 0 || replyData.get() == nullptr) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004376 return false;
4377 }
4378
Alex Light8c2b9292017-11-09 13:21:01 -08004379 out_data->resize(length);
4380 env->GetByteArrayRegion(replyData.get(),
4381 offset,
4382 length,
4383 reinterpret_cast<jbyte*>(out_data->data()));
4384 return true;
4385}
4386
4387/*
4388 * "request" contains a full JDWP packet, possibly with multiple chunks. We
4389 * need to process each, accumulate the replies, and ship the whole thing
4390 * back.
4391 *
4392 * Returns "true" if we have a reply. The reply buffer is newly allocated,
4393 * and includes the chunk type/length, followed by the data.
4394 *
4395 * OLD-TODO: we currently assume that the request and reply include a single
4396 * chunk. If this becomes inconvenient we will need to adapt.
4397 */
4398bool Dbg::DdmHandlePacket(JDWP::Request* request, uint8_t** pReplyBuf, int* pReplyLen) {
4399 Thread* self = Thread::Current();
4400 JNIEnv* env = self->GetJniEnv();
4401
4402 uint32_t type = request->ReadUnsigned32("type");
4403 uint32_t length = request->ReadUnsigned32("length");
4404
4405 // Create a byte[] corresponding to 'request'.
4406 size_t request_length = request->size();
4407 // Run through and find all chunks. [Currently just find the first.]
4408 if (length != request_length) {
4409 LOG(WARNING) << StringPrintf("bad chunk found (len=%u pktLen=%zd)", length, request_length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004410 return false;
4411 }
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004412
Alex Light8c2b9292017-11-09 13:21:01 -08004413 ArrayRef<const jbyte> data(reinterpret_cast<const jbyte*>(request->data()), request_length);
4414 std::vector<uint8_t> out_data;
4415 uint32_t out_type = 0;
4416 request->Skip(request_length);
4417 if (!DdmHandleChunk(env, type, data, &out_type, &out_data)) {
4418 return false;
4419 }
4420 const uint32_t kDdmHeaderSize = 8;
4421 *pReplyLen = out_data.size() + kDdmHeaderSize;
4422 *pReplyBuf = new uint8_t[out_data.size() + kDdmHeaderSize];
4423 memcpy((*pReplyBuf) + kDdmHeaderSize, out_data.data(), out_data.size());
4424 JDWP::Set4BE(*pReplyBuf, out_type);
4425 JDWP::Set4BE((*pReplyBuf) + 4, static_cast<uint32_t>(out_data.size()));
4426 VLOG(jdwp)
4427 << StringPrintf("dvmHandleDdm returning type=%.4s", reinterpret_cast<char*>(*pReplyBuf))
4428 << "0x" << std::hex << reinterpret_cast<uintptr_t>(*pReplyBuf) << std::dec
4429 << " len= " << out_data.size();
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004430 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004431}
4432
Elliott Hughesa2155262011-11-16 16:26:58 -08004433void Dbg::DdmBroadcast(bool connect) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08004434 VLOG(jdwp) << "Broadcasting DDM " << (connect ? "connect" : "disconnect") << "...";
Elliott Hughes47fce012011-10-25 18:37:19 -07004435
4436 Thread* self = Thread::Current();
Ian Rogers50b35e22012-10-04 10:09:15 -07004437 if (self->GetState() != kRunnable) {
4438 LOG(ERROR) << "DDM broadcast in thread state " << self->GetState();
4439 /* try anyway? */
Elliott Hughes47fce012011-10-25 18:37:19 -07004440 }
4441
4442 JNIEnv* env = self->GetJniEnv();
Elliott Hughes47fce012011-10-25 18:37:19 -07004443 jint event = connect ? 1 /*DdmServer.CONNECTED*/ : 2 /*DdmServer.DISCONNECTED*/;
Elliott Hugheseac76672012-05-24 21:56:51 -07004444 env->CallStaticVoidMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
4445 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_broadcast,
4446 event);
Elliott Hughes47fce012011-10-25 18:37:19 -07004447 if (env->ExceptionCheck()) {
4448 LOG(ERROR) << "DdmServer.broadcast " << event << " failed";
4449 env->ExceptionDescribe();
4450 env->ExceptionClear();
4451 }
4452}
4453
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004454void Dbg::DdmConnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08004455 Dbg::DdmBroadcast(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004456}
4457
4458void Dbg::DdmDisconnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08004459 Dbg::DdmBroadcast(false);
Elliott Hughes47fce012011-10-25 18:37:19 -07004460 gDdmThreadNotification = false;
4461}
4462
4463/*
Elliott Hughes82188472011-11-07 18:11:48 -08004464 * Send a notification when a thread starts, stops, or changes its name.
Elliott Hughes47fce012011-10-25 18:37:19 -07004465 *
4466 * Because we broadcast the full set of threads when the notifications are
4467 * first enabled, it's possible for "thread" to be actively executing.
4468 */
Elliott Hughes82188472011-11-07 18:11:48 -08004469void Dbg::DdmSendThreadNotification(Thread* t, uint32_t type) {
Elliott Hughes47fce012011-10-25 18:37:19 -07004470 if (!gDdmThreadNotification) {
4471 return;
4472 }
4473
Alex Light772099a2017-11-21 14:05:04 -08004474 RuntimeCallbacks* cb = Runtime::Current()->GetRuntimeCallbacks();
Elliott Hughes82188472011-11-07 18:11:48 -08004475 if (type == CHUNK_TYPE("THDE")) {
Elliott Hughes47fce012011-10-25 18:37:19 -07004476 uint8_t buf[4];
Ian Rogersd9c4fc92013-10-01 19:45:43 -07004477 JDWP::Set4BE(&buf[0], t->GetThreadId());
Alex Light772099a2017-11-21 14:05:04 -08004478 cb->DdmPublishChunk(CHUNK_TYPE("THDE"), ArrayRef<const uint8_t>(buf));
Elliott Hughes82188472011-11-07 18:11:48 -08004479 } else {
4480 CHECK(type == CHUNK_TYPE("THCR") || type == CHUNK_TYPE("THNM")) << type;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004481 ScopedObjectAccessUnchecked soa(Thread::Current());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004482 StackHandleScope<1> hs(soa.Self());
Andreas Gampe08883de2016-11-08 13:20:52 -08004483 Handle<mirror::String> name(hs.NewHandle(t->GetThreadName()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004484 size_t char_count = (name != nullptr) ? name->GetLength() : 0;
4485 const jchar* chars = (name != nullptr) ? name->GetValue() : nullptr;
4486 bool is_compressed = (name != nullptr) ? name->IsCompressed() : false;
Elliott Hughes82188472011-11-07 18:11:48 -08004487
Elliott Hughes21f32d72011-11-09 17:44:13 -08004488 std::vector<uint8_t> bytes;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07004489 JDWP::Append4BE(bytes, t->GetThreadId());
jessicahandojo3aaa37b2016-07-29 14:46:37 -07004490 if (is_compressed) {
4491 const uint8_t* chars_compressed = name->GetValueCompressed();
4492 JDWP::AppendUtf16CompressedBE(bytes, chars_compressed, char_count);
4493 } else {
4494 JDWP::AppendUtf16BE(bytes, chars, char_count);
4495 }
Elliott Hughes21f32d72011-11-09 17:44:13 -08004496 CHECK_EQ(bytes.size(), char_count*2 + sizeof(uint32_t)*2);
Alex Light772099a2017-11-21 14:05:04 -08004497 cb->DdmPublishChunk(type, ArrayRef<const uint8_t>(bytes));
Elliott Hughes47fce012011-10-25 18:37:19 -07004498 }
4499}
4500
Elliott Hughes47fce012011-10-25 18:37:19 -07004501void Dbg::DdmSetThreadNotification(bool enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004502 // Enable/disable thread notifications.
Elliott Hughes47fce012011-10-25 18:37:19 -07004503 gDdmThreadNotification = enable;
4504 if (enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004505 // Suspend the VM then post thread start notifications for all threads. Threads attaching will
4506 // see a suspension in progress and block until that ends. They then post their own start
4507 // notification.
4508 SuspendVM();
4509 std::list<Thread*> threads;
Ian Rogers50b35e22012-10-04 10:09:15 -07004510 Thread* self = Thread::Current();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004511 {
Ian Rogers50b35e22012-10-04 10:09:15 -07004512 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004513 threads = Runtime::Current()->GetThreadList()->GetList();
4514 }
4515 {
Ian Rogers50b35e22012-10-04 10:09:15 -07004516 ScopedObjectAccess soa(self);
Mathieu Chartier02e25112013-08-14 16:14:24 -07004517 for (Thread* thread : threads) {
4518 Dbg::DdmSendThreadNotification(thread, CHUNK_TYPE("THCR"));
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004519 }
4520 }
4521 ResumeVM();
Elliott Hughes47fce012011-10-25 18:37:19 -07004522 }
4523}
4524
Elliott Hughesa2155262011-11-16 16:26:58 -08004525void Dbg::PostThreadStartOrStop(Thread* t, uint32_t type) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07004526 if (IsDebuggerActive()) {
Sebastien Hertz6995c602014-09-09 12:10:13 +02004527 gJdwpState->PostThreadChange(t, type == CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07004528 }
Elliott Hughes82188472011-11-07 18:11:48 -08004529 Dbg::DdmSendThreadNotification(t, type);
Elliott Hughes47fce012011-10-25 18:37:19 -07004530}
4531
4532void Dbg::PostThreadStart(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004533 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07004534}
4535
4536void Dbg::PostThreadDeath(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004537 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THDE"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004538}
4539
Mathieu Chartierad466ad2015-01-08 16:28:08 -08004540JDWP::JdwpState* Dbg::GetJdwpState() {
4541 return gJdwpState;
4542}
4543
Elliott Hughes767a1472011-10-26 18:49:02 -07004544int Dbg::DdmHandleHpifChunk(HpifWhen when) {
4545 if (when == HPIF_WHEN_NOW) {
Elliott Hughes7162ad92011-10-27 14:08:42 -07004546 DdmSendHeapInfo(when);
Elliott Hughes767a1472011-10-26 18:49:02 -07004547 return true;
4548 }
4549
4550 if (when != HPIF_WHEN_NEVER && when != HPIF_WHEN_NEXT_GC && when != HPIF_WHEN_EVERY_GC) {
4551 LOG(ERROR) << "invalid HpifWhen value: " << static_cast<int>(when);
4552 return false;
4553 }
4554
4555 gDdmHpifWhen = when;
4556 return true;
4557}
4558
4559bool Dbg::DdmHandleHpsgNhsgChunk(Dbg::HpsgWhen when, Dbg::HpsgWhat what, bool native) {
4560 if (when != HPSG_WHEN_NEVER && when != HPSG_WHEN_EVERY_GC) {
4561 LOG(ERROR) << "invalid HpsgWhen value: " << static_cast<int>(when);
4562 return false;
4563 }
4564
4565 if (what != HPSG_WHAT_MERGED_OBJECTS && what != HPSG_WHAT_DISTINCT_OBJECTS) {
4566 LOG(ERROR) << "invalid HpsgWhat value: " << static_cast<int>(what);
4567 return false;
4568 }
4569
4570 if (native) {
4571 gDdmNhsgWhen = when;
4572 gDdmNhsgWhat = what;
4573 } else {
4574 gDdmHpsgWhen = when;
4575 gDdmHpsgWhat = what;
4576 }
4577 return true;
4578}
4579
Elliott Hughes7162ad92011-10-27 14:08:42 -07004580void Dbg::DdmSendHeapInfo(HpifWhen reason) {
4581 // If there's a one-shot 'when', reset it.
4582 if (reason == gDdmHpifWhen) {
4583 if (gDdmHpifWhen == HPIF_WHEN_NEXT_GC) {
4584 gDdmHpifWhen = HPIF_WHEN_NEVER;
4585 }
4586 }
4587
4588 /*
4589 * Chunk HPIF (client --> server)
4590 *
4591 * Heap Info. General information about the heap,
4592 * suitable for a summary display.
4593 *
4594 * [u4]: number of heaps
4595 *
4596 * For each heap:
4597 * [u4]: heap ID
4598 * [u8]: timestamp in ms since Unix epoch
4599 * [u1]: capture reason (same as 'when' value from server)
4600 * [u4]: max heap size in bytes (-Xmx)
4601 * [u4]: current heap size in bytes
4602 * [u4]: current number of bytes allocated
4603 * [u4]: current number of objects allocated
4604 */
4605 uint8_t heap_count = 1;
Ian Rogers1d54e732013-05-02 21:10:01 -07004606 gc::Heap* heap = Runtime::Current()->GetHeap();
Elliott Hughes21f32d72011-11-09 17:44:13 -08004607 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08004608 JDWP::Append4BE(bytes, heap_count);
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004609 JDWP::Append4BE(bytes, 1); // Heap id (bogus; we only have one heap).
Elliott Hughes545a0642011-11-08 19:10:03 -08004610 JDWP::Append8BE(bytes, MilliTime());
4611 JDWP::Append1BE(bytes, reason);
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004612 JDWP::Append4BE(bytes, heap->GetMaxMemory()); // Max allowed heap size in bytes.
4613 JDWP::Append4BE(bytes, heap->GetTotalMemory()); // Current heap size in bytes.
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08004614 JDWP::Append4BE(bytes, heap->GetBytesAllocated());
4615 JDWP::Append4BE(bytes, heap->GetObjectsAllocated());
Elliott Hughes21f32d72011-11-09 17:44:13 -08004616 CHECK_EQ(bytes.size(), 4U + (heap_count * (4 + 8 + 1 + 4 + 4 + 4 + 4)));
Alex Light772099a2017-11-21 14:05:04 -08004617 Runtime::Current()->GetRuntimeCallbacks()->DdmPublishChunk(CHUNK_TYPE("HPIF"),
4618 ArrayRef<const uint8_t>(bytes));
Elliott Hughes767a1472011-10-26 18:49:02 -07004619}
4620
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004621enum HpsgSolidity {
4622 SOLIDITY_FREE = 0,
4623 SOLIDITY_HARD = 1,
4624 SOLIDITY_SOFT = 2,
4625 SOLIDITY_WEAK = 3,
4626 SOLIDITY_PHANTOM = 4,
4627 SOLIDITY_FINALIZABLE = 5,
4628 SOLIDITY_SWEEP = 6,
4629};
4630
4631enum HpsgKind {
4632 KIND_OBJECT = 0,
4633 KIND_CLASS_OBJECT = 1,
4634 KIND_ARRAY_1 = 2,
4635 KIND_ARRAY_2 = 3,
4636 KIND_ARRAY_4 = 4,
4637 KIND_ARRAY_8 = 5,
4638 KIND_UNKNOWN = 6,
4639 KIND_NATIVE = 7,
4640};
4641
4642#define HPSG_PARTIAL (1<<7)
4643#define HPSG_STATE(solidity, kind) ((uint8_t)((((kind) & 0x7) << 3) | ((solidity) & 0x7)))
4644
Ian Rogers30fab402012-01-23 15:43:46 -08004645class HeapChunkContext {
4646 public:
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004647 // Maximum chunk size. Obtain this from the formula:
4648 // (((maximum_heap_size / ALLOCATION_UNIT_SIZE) + 255) / 256) * 2
4649 HeapChunkContext(bool merge, bool native)
Ian Rogers30fab402012-01-23 15:43:46 -08004650 : buf_(16384 - 16),
4651 type_(0),
Mathieu Chartier36dab362014-07-30 14:59:56 -07004652 chunk_overhead_(0) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004653 Reset();
4654 if (native) {
Ian Rogers30fab402012-01-23 15:43:46 -08004655 type_ = CHUNK_TYPE("NHSG");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004656 } else {
Ian Rogers30fab402012-01-23 15:43:46 -08004657 type_ = merge ? CHUNK_TYPE("HPSG") : CHUNK_TYPE("HPSO");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004658 }
4659 }
4660
4661 ~HeapChunkContext() {
Ian Rogers30fab402012-01-23 15:43:46 -08004662 if (p_ > &buf_[0]) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004663 Flush();
4664 }
4665 }
4666
Mathieu Chartier36dab362014-07-30 14:59:56 -07004667 void SetChunkOverhead(size_t chunk_overhead) {
4668 chunk_overhead_ = chunk_overhead;
4669 }
4670
4671 void ResetStartOfNextChunk() {
4672 startOfNextMemoryChunk_ = nullptr;
4673 }
4674
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004675 void EnsureHeader(const void* chunk_ptr) {
Ian Rogers30fab402012-01-23 15:43:46 -08004676 if (!needHeader_) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004677 return;
4678 }
4679
4680 // Start a new HPSx chunk.
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004681 JDWP::Write4BE(&p_, 1); // Heap id (bogus; we only have one heap).
4682 JDWP::Write1BE(&p_, 8); // Size of allocation unit, in bytes.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004683
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004684 JDWP::Write4BE(&p_, reinterpret_cast<uintptr_t>(chunk_ptr)); // virtual address of segment start.
4685 JDWP::Write4BE(&p_, 0); // offset of this piece (relative to the virtual address).
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004686 // [u4]: length of piece, in allocation units
4687 // 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 -08004688 pieceLenField_ = p_;
4689 JDWP::Write4BE(&p_, 0x55555555);
4690 needHeader_ = false;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004691 }
4692
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004693 void Flush() REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -07004694 if (pieceLenField_ == nullptr) {
Ian Rogersd636b062013-01-18 17:51:18 -08004695 // Flush immediately post Reset (maybe back-to-back Flush). Ignore.
4696 CHECK(needHeader_);
4697 return;
4698 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004699 // Patch the "length of piece" field.
Ian Rogers30fab402012-01-23 15:43:46 -08004700 CHECK_LE(&buf_[0], pieceLenField_);
4701 CHECK_LE(pieceLenField_, p_);
4702 JDWP::Set4BE(pieceLenField_, totalAllocationUnits_);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004703
Alex Light772099a2017-11-21 14:05:04 -08004704 ArrayRef<const uint8_t> out(&buf_[0], p_ - &buf_[0]);
4705 Runtime::Current()->GetRuntimeCallbacks()->DdmPublishChunk(type_, out);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004706 Reset();
4707 }
4708
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004709 static void HeapChunkJavaCallback(void* start, void* end, size_t used_bytes, void* arg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004710 REQUIRES_SHARED(Locks::heap_bitmap_lock_,
Ian Rogersb726dcb2012-09-05 08:57:23 -07004711 Locks::mutator_lock_) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004712 reinterpret_cast<HeapChunkContext*>(arg)->HeapChunkJavaCallback(start, end, used_bytes);
4713 }
4714
4715 static void HeapChunkNativeCallback(void* start, void* end, size_t used_bytes, void* arg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004716 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004717 reinterpret_cast<HeapChunkContext*>(arg)->HeapChunkNativeCallback(start, end, used_bytes);
Elliott Hughesa2155262011-11-16 16:26:58 -08004718 }
4719
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004720 private:
Elliott Hughesa2155262011-11-16 16:26:58 -08004721 enum { ALLOCATION_UNIT_SIZE = 8 };
4722
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004723 void Reset() {
Ian Rogers30fab402012-01-23 15:43:46 -08004724 p_ = &buf_[0];
Mathieu Chartier36dab362014-07-30 14:59:56 -07004725 ResetStartOfNextChunk();
Ian Rogers30fab402012-01-23 15:43:46 -08004726 totalAllocationUnits_ = 0;
4727 needHeader_ = true;
Ian Rogersc0542af2014-09-03 16:16:56 -07004728 pieceLenField_ = nullptr;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004729 }
4730
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004731 bool IsNative() const {
4732 return type_ == CHUNK_TYPE("NHSG");
4733 }
4734
4735 // Returns true if the object is not an empty chunk.
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004736 bool ProcessRecord(void* start, size_t used_bytes) REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers30fab402012-01-23 15:43:46 -08004737 // Note: heap call backs cannot manipulate the heap upon which they are crawling, care is taken
4738 // in the following code not to allocate memory, by ensuring buf_ is of the correct size
Ian Rogers15bf2d32012-08-28 17:33:04 -07004739 if (used_bytes == 0) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004740 if (start == nullptr) {
4741 // Reset for start of new heap.
4742 startOfNextMemoryChunk_ = nullptr;
4743 Flush();
4744 }
4745 // Only process in use memory so that free region information
4746 // also includes dlmalloc book keeping.
4747 return false;
Elliott Hughesa2155262011-11-16 16:26:58 -08004748 }
Ian Rogersc0542af2014-09-03 16:16:56 -07004749 if (startOfNextMemoryChunk_ != nullptr) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004750 // Transmit any pending free memory. Native free memory of over kMaxFreeLen could be because
4751 // of the use of mmaps, so don't report. If not free memory then start a new segment.
4752 bool flush = true;
4753 if (start > startOfNextMemoryChunk_) {
4754 const size_t kMaxFreeLen = 2 * kPageSize;
4755 void* free_start = startOfNextMemoryChunk_;
4756 void* free_end = start;
4757 const size_t free_len =
4758 reinterpret_cast<uintptr_t>(free_end) - reinterpret_cast<uintptr_t>(free_start);
4759 if (!IsNative() || free_len < kMaxFreeLen) {
4760 AppendChunk(HPSG_STATE(SOLIDITY_FREE, 0), free_start, free_len, IsNative());
4761 flush = false;
Ian Rogers15bf2d32012-08-28 17:33:04 -07004762 }
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004763 }
4764 if (flush) {
4765 startOfNextMemoryChunk_ = nullptr;
4766 Flush();
4767 }
Ian Rogers15bf2d32012-08-28 17:33:04 -07004768 }
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004769 return true;
Ian Rogers15bf2d32012-08-28 17:33:04 -07004770 }
Elliott Hughesa2155262011-11-16 16:26:58 -08004771
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004772 void HeapChunkNativeCallback(void* start, void* /*end*/, size_t used_bytes)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004773 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004774 if (ProcessRecord(start, used_bytes)) {
4775 uint8_t state = ExamineNativeObject(start);
4776 AppendChunk(state, start, used_bytes + chunk_overhead_, true /*is_native*/);
4777 startOfNextMemoryChunk_ = reinterpret_cast<char*>(start) + used_bytes + chunk_overhead_;
4778 }
4779 }
4780
4781 void HeapChunkJavaCallback(void* start, void* /*end*/, size_t used_bytes)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004782 REQUIRES_SHARED(Locks::heap_bitmap_lock_, Locks::mutator_lock_) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004783 if (ProcessRecord(start, used_bytes)) {
4784 // Determine the type of this chunk.
4785 // OLD-TODO: if context.merge, see if this chunk is different from the last chunk.
4786 // If it's the same, we should combine them.
4787 uint8_t state = ExamineJavaObject(reinterpret_cast<mirror::Object*>(start));
4788 AppendChunk(state, start, used_bytes + chunk_overhead_, false /*is_native*/);
4789 startOfNextMemoryChunk_ = reinterpret_cast<char*>(start) + used_bytes + chunk_overhead_;
4790 }
4791 }
4792
4793 void AppendChunk(uint8_t state, void* ptr, size_t length, bool is_native)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004794 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07004795 // Make sure there's enough room left in the buffer.
4796 // We need to use two bytes for every fractional 256 allocation units used by the chunk plus
4797 // 17 bytes for any header.
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004798 const size_t needed = ((RoundUp(length / ALLOCATION_UNIT_SIZE, 256) / 256) * 2) + 17;
4799 size_t byte_left = &buf_.back() - p_;
4800 if (byte_left < needed) {
4801 if (is_native) {
Pavel Vyssotski7522c742014-12-08 13:38:26 +06004802 // Cannot trigger memory allocation while walking native heap.
Pavel Vyssotski7522c742014-12-08 13:38:26 +06004803 return;
4804 }
Ian Rogers15bf2d32012-08-28 17:33:04 -07004805 Flush();
4806 }
4807
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004808 byte_left = &buf_.back() - p_;
4809 if (byte_left < needed) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07004810 LOG(WARNING) << "Chunk is too big to transmit (chunk_len=" << length << ", "
4811 << needed << " bytes)";
4812 return;
4813 }
4814 EnsureHeader(ptr);
Elliott Hughesa2155262011-11-16 16:26:58 -08004815 // Write out the chunk description.
Ian Rogers15bf2d32012-08-28 17:33:04 -07004816 length /= ALLOCATION_UNIT_SIZE; // Convert to allocation units.
4817 totalAllocationUnits_ += length;
4818 while (length > 256) {
Ian Rogers30fab402012-01-23 15:43:46 -08004819 *p_++ = state | HPSG_PARTIAL;
4820 *p_++ = 255; // length - 1
Ian Rogers15bf2d32012-08-28 17:33:04 -07004821 length -= 256;
Elliott Hughesa2155262011-11-16 16:26:58 -08004822 }
Ian Rogers30fab402012-01-23 15:43:46 -08004823 *p_++ = state;
Ian Rogers15bf2d32012-08-28 17:33:04 -07004824 *p_++ = length - 1;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004825 }
4826
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004827 uint8_t ExamineNativeObject(const void* p) REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004828 return p == nullptr ? HPSG_STATE(SOLIDITY_FREE, 0) : HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
4829 }
4830
4831 uint8_t ExamineJavaObject(mirror::Object* o)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004832 REQUIRES_SHARED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -07004833 if (o == nullptr) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004834 return HPSG_STATE(SOLIDITY_FREE, 0);
4835 }
Elliott Hughesa2155262011-11-16 16:26:58 -08004836 // It's an allocated chunk. Figure out what it is.
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004837 gc::Heap* heap = Runtime::Current()->GetHeap();
4838 if (!heap->IsLiveObjectLocked(o)) {
4839 LOG(ERROR) << "Invalid object in managed heap: " << o;
Elliott Hughesa2155262011-11-16 16:26:58 -08004840 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
4841 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004842 mirror::Class* c = o->GetClass();
Ian Rogersc0542af2014-09-03 16:16:56 -07004843 if (c == nullptr) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004844 // The object was probably just created but hasn't been initialized yet.
4845 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
4846 }
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004847 if (!heap->IsValidObjectAddress(c)) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07004848 LOG(ERROR) << "Invalid class for managed heap object: " << o << " " << c;
Elliott Hughesa2155262011-11-16 16:26:58 -08004849 return HPSG_STATE(SOLIDITY_HARD, KIND_UNKNOWN);
4850 }
Mathieu Chartierf26e1b32015-01-29 10:47:10 -08004851 if (c->GetClass() == nullptr) {
4852 LOG(ERROR) << "Null class of class " << c << " for object " << o;
4853 return HPSG_STATE(SOLIDITY_HARD, KIND_UNKNOWN);
4854 }
Elliott Hughesa2155262011-11-16 16:26:58 -08004855 if (c->IsClassClass()) {
4856 return HPSG_STATE(SOLIDITY_HARD, KIND_CLASS_OBJECT);
4857 }
Elliott Hughesa2155262011-11-16 16:26:58 -08004858 if (c->IsArrayClass()) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004859 switch (c->GetComponentSize()) {
4860 case 1: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_1);
4861 case 2: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_2);
4862 case 4: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
4863 case 8: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_8);
4864 }
4865 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004866 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
4867 }
4868
Ian Rogers30fab402012-01-23 15:43:46 -08004869 std::vector<uint8_t> buf_;
4870 uint8_t* p_;
4871 uint8_t* pieceLenField_;
Ian Rogers15bf2d32012-08-28 17:33:04 -07004872 void* startOfNextMemoryChunk_;
Ian Rogers30fab402012-01-23 15:43:46 -08004873 size_t totalAllocationUnits_;
4874 uint32_t type_;
Ian Rogers30fab402012-01-23 15:43:46 -08004875 bool needHeader_;
Mathieu Chartier36dab362014-07-30 14:59:56 -07004876 size_t chunk_overhead_;
Ian Rogers30fab402012-01-23 15:43:46 -08004877
Elliott Hughesa2155262011-11-16 16:26:58 -08004878 DISALLOW_COPY_AND_ASSIGN(HeapChunkContext);
4879};
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004880
4881void Dbg::DdmSendHeapSegments(bool native) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004882 Dbg::HpsgWhen when = native ? gDdmNhsgWhen : gDdmHpsgWhen;
4883 Dbg::HpsgWhat what = native ? gDdmNhsgWhat : gDdmHpsgWhat;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004884 if (when == HPSG_WHEN_NEVER) {
4885 return;
4886 }
Alex Light772099a2017-11-21 14:05:04 -08004887 RuntimeCallbacks* cb = Runtime::Current()->GetRuntimeCallbacks();
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004888 // Figure out what kind of chunks we'll be sending.
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004889 CHECK(what == HPSG_WHAT_MERGED_OBJECTS || what == HPSG_WHAT_DISTINCT_OBJECTS)
4890 << static_cast<int>(what);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004891
4892 // First, send a heap start chunk.
4893 uint8_t heap_id[4];
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004894 JDWP::Set4BE(&heap_id[0], 1); // Heap id (bogus; we only have one heap).
Alex Light772099a2017-11-21 14:05:04 -08004895 cb->DdmPublishChunk(native ? CHUNK_TYPE("NHST") : CHUNK_TYPE("HPST"),
4896 ArrayRef<const uint8_t>(heap_id));
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07004897 Thread* self = Thread::Current();
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07004898 Locks::mutator_lock_->AssertSharedHeld(self);
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07004899
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004900 // Send a series of heap segment chunks.
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004901 HeapChunkContext context(what == HPSG_WHAT_MERGED_OBJECTS, native);
Andreas Gampe0c183382017-07-13 22:26:24 -07004902 auto bump_pointer_space_visitor = [&](mirror::Object* obj)
4903 REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
4904 const size_t size = RoundUp(obj->SizeOf(), kObjectAlignment);
4905 HeapChunkContext::HeapChunkJavaCallback(
4906 obj, reinterpret_cast<void*>(reinterpret_cast<uintptr_t>(obj) + size), size, &context);
4907 };
Elliott Hughesa2155262011-11-16 16:26:58 -08004908 if (native) {
Dimitry Ivanove6465bc2015-12-14 18:55:02 -08004909 UNIMPLEMENTED(WARNING) << "Native heap inspection is not supported";
Elliott Hughesa2155262011-11-16 16:26:58 -08004910 } else {
Ian Rogers1d54e732013-05-02 21:10:01 -07004911 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartier36dab362014-07-30 14:59:56 -07004912 for (const auto& space : heap->GetContinuousSpaces()) {
4913 if (space->IsDlMallocSpace()) {
Mathieu Chartier4c69d7f2014-10-10 12:45:50 -07004914 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004915 // dlmalloc's chunk header is 2 * sizeof(size_t), but if the previous chunk is in use for an
4916 // allocation then the first sizeof(size_t) may belong to it.
4917 context.SetChunkOverhead(sizeof(size_t));
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004918 space->AsDlMallocSpace()->Walk(HeapChunkContext::HeapChunkJavaCallback, &context);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004919 } else if (space->IsRosAllocSpace()) {
4920 context.SetChunkOverhead(0);
Mathieu Chartier4c69d7f2014-10-10 12:45:50 -07004921 // Need to acquire the mutator lock before the heap bitmap lock with exclusive access since
4922 // RosAlloc's internal logic doesn't know to release and reacquire the heap bitmap lock.
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07004923 ScopedThreadSuspension sts(self, kSuspended);
Mathieu Chartier4f55e222015-09-04 13:26:21 -07004924 ScopedSuspendAll ssa(__FUNCTION__);
4925 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
4926 space->AsRosAllocSpace()->Walk(HeapChunkContext::HeapChunkJavaCallback, &context);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004927 } else if (space->IsBumpPointerSpace()) {
Mathieu Chartier4c69d7f2014-10-10 12:45:50 -07004928 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004929 context.SetChunkOverhead(0);
Andreas Gampe0c183382017-07-13 22:26:24 -07004930 space->AsBumpPointerSpace()->Walk(bump_pointer_space_visitor);
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004931 HeapChunkContext::HeapChunkJavaCallback(nullptr, nullptr, 0, &context);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08004932 } else if (space->IsRegionSpace()) {
4933 heap->IncrementDisableMovingGC(self);
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07004934 {
4935 ScopedThreadSuspension sts(self, kSuspended);
Mathieu Chartier4f55e222015-09-04 13:26:21 -07004936 ScopedSuspendAll ssa(__FUNCTION__);
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07004937 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
4938 context.SetChunkOverhead(0);
Andreas Gampe0c183382017-07-13 22:26:24 -07004939 space->AsRegionSpace()->Walk(bump_pointer_space_visitor);
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07004940 HeapChunkContext::HeapChunkJavaCallback(nullptr, nullptr, 0, &context);
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07004941 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08004942 heap->DecrementDisableMovingGC(self);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004943 } else {
4944 UNIMPLEMENTED(WARNING) << "Not counting objects in space " << *space;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07004945 }
Mathieu Chartier36dab362014-07-30 14:59:56 -07004946 context.ResetStartOfNextChunk();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07004947 }
Mathieu Chartier4c69d7f2014-10-10 12:45:50 -07004948 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07004949 // Walk the large objects, these are not in the AllocSpace.
Mathieu Chartier36dab362014-07-30 14:59:56 -07004950 context.SetChunkOverhead(0);
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004951 heap->GetLargeObjectsSpace()->Walk(HeapChunkContext::HeapChunkJavaCallback, &context);
Elliott Hughesa2155262011-11-16 16:26:58 -08004952 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004953
4954 // Finally, send a heap end chunk.
Alex Light772099a2017-11-21 14:05:04 -08004955 cb->DdmPublishChunk(native ? CHUNK_TYPE("NHEN") : CHUNK_TYPE("HPEN"),
4956 ArrayRef<const uint8_t>(heap_id));
Elliott Hughes767a1472011-10-26 18:49:02 -07004957}
4958
Brian Carlstrom306db812014-09-05 13:01:41 -07004959void Dbg::SetAllocTrackingEnabled(bool enable) {
Man Cao8c2ff642015-05-27 17:25:30 -07004960 gc::AllocRecordObjectMap::SetAllocTrackingEnabled(enable);
Elliott Hughes545a0642011-11-08 19:10:03 -08004961}
4962
4963void Dbg::DumpRecentAllocations() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004964 ScopedObjectAccess soa(Thread::Current());
Brian Carlstrom306db812014-09-05 13:01:41 -07004965 MutexLock mu(soa.Self(), *Locks::alloc_tracker_lock_);
Man Cao8c2ff642015-05-27 17:25:30 -07004966 if (!Runtime::Current()->GetHeap()->IsAllocTrackingEnabled()) {
Elliott Hughes545a0642011-11-08 19:10:03 -08004967 LOG(INFO) << "Not recording tracked allocations";
4968 return;
4969 }
Man Cao8c2ff642015-05-27 17:25:30 -07004970 gc::AllocRecordObjectMap* records = Runtime::Current()->GetHeap()->GetAllocationRecords();
4971 CHECK(records != nullptr);
Elliott Hughes545a0642011-11-08 19:10:03 -08004972
Man Cao1ed11b92015-06-11 22:47:35 -07004973 const uint16_t capped_count = CappedAllocRecordCount(records->GetRecentAllocationSize());
Brian Carlstrom306db812014-09-05 13:01:41 -07004974 uint16_t count = capped_count;
Elliott Hughes545a0642011-11-08 19:10:03 -08004975
Man Cao8c2ff642015-05-27 17:25:30 -07004976 LOG(INFO) << "Tracked allocations, (count=" << count << ")";
4977 for (auto it = records->RBegin(), end = records->REnd();
4978 count > 0 && it != end; count--, it++) {
Mathieu Chartier458b1052016-03-29 14:02:55 -07004979 const gc::AllocRecord* record = &it->second;
Elliott Hughes545a0642011-11-08 19:10:03 -08004980
Man Cao8c2ff642015-05-27 17:25:30 -07004981 LOG(INFO) << StringPrintf(" Thread %-2d %6zd bytes ", record->GetTid(), record->ByteCount())
David Sehr709b0702016-10-13 09:12:37 -07004982 << mirror::Class::PrettyClass(record->GetClass());
Elliott Hughes545a0642011-11-08 19:10:03 -08004983
Man Cao8c2ff642015-05-27 17:25:30 -07004984 for (size_t stack_frame = 0, depth = record->GetDepth(); stack_frame < depth; ++stack_frame) {
4985 const gc::AllocRecordStackTraceElement& stack_element = record->StackElement(stack_frame);
4986 ArtMethod* m = stack_element.GetMethod();
David Sehr709b0702016-10-13 09:12:37 -07004987 LOG(INFO) << " " << ArtMethod::PrettyMethod(m) << " line "
4988 << stack_element.ComputeLineNumber();
Elliott Hughes545a0642011-11-08 19:10:03 -08004989 }
4990
4991 // pause periodically to help logcat catch up
4992 if ((count % 5) == 0) {
4993 usleep(40000);
4994 }
Elliott Hughes545a0642011-11-08 19:10:03 -08004995 }
4996}
4997
4998class StringTable {
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07004999 private:
5000 struct Entry {
Andreas Gampe84eadb22017-07-07 15:08:01 -07005001 explicit Entry(const char* data_in)
5002 : data(data_in), hash(ComputeModifiedUtf8Hash(data_in)), index(0) {
5003 }
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07005004 Entry(const Entry& entry) = default;
5005 Entry(Entry&& entry) = default;
5006
5007 // Pointer to the actual string data.
5008 const char* data;
Andreas Gampe84eadb22017-07-07 15:08:01 -07005009
5010 // The hash of the data.
5011 const uint32_t hash;
5012
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07005013 // The index. This will be filled in on Finish and is not part of the ordering, so mark it
5014 // mutable.
5015 mutable uint32_t index;
5016
Andreas Gampe84eadb22017-07-07 15:08:01 -07005017 bool operator==(const Entry& other) const {
5018 return strcmp(data, other.data) == 0;
5019 }
5020 };
5021 struct EntryHash {
5022 size_t operator()(const Entry& entry) const {
5023 return entry.hash;
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07005024 }
5025 };
5026
Elliott Hughes545a0642011-11-08 19:10:03 -08005027 public:
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07005028 StringTable() : finished_(false) {
Elliott Hughes545a0642011-11-08 19:10:03 -08005029 }
5030
Andreas Gampef774a4e2017-07-06 22:15:18 -07005031 void Add(const char* str, bool copy_string) {
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07005032 DCHECK(!finished_);
Andreas Gampef774a4e2017-07-06 22:15:18 -07005033 if (UNLIKELY(copy_string)) {
5034 // Check whether it's already there.
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07005035 Entry entry(str);
5036 if (table_.find(entry) != table_.end()) {
Andreas Gampef774a4e2017-07-06 22:15:18 -07005037 return;
5038 }
Mathieu Chartier4345c462014-06-27 10:20:14 -07005039
Andreas Gampef774a4e2017-07-06 22:15:18 -07005040 // Make a copy.
5041 size_t str_len = strlen(str);
5042 char* copy = new char[str_len + 1];
5043 strlcpy(copy, str, str_len + 1);
5044 string_backup_.emplace_back(copy);
5045 str = copy;
5046 }
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07005047 Entry entry(str);
5048 table_.insert(entry);
5049 }
5050
5051 // Update all entries and give them an index. Note that this is likely not the insertion order,
5052 // as the set will with high likelihood reorder elements. Thus, Add must not be called after
5053 // Finish, and Finish must be called before IndexOf. In that case, WriteTo will walk in
5054 // the same order as Finish, and indices will agree. The order invariant, as well as indices,
5055 // are enforced through debug checks.
5056 void Finish() {
5057 DCHECK(!finished_);
5058 finished_ = true;
5059 uint32_t index = 0;
5060 for (auto& entry : table_) {
5061 entry.index = index;
5062 ++index;
5063 }
Elliott Hughes545a0642011-11-08 19:10:03 -08005064 }
5065
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07005066 size_t IndexOf(const char* s) const {
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07005067 DCHECK(finished_);
5068 Entry entry(s);
5069 auto it = table_.find(entry);
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07005070 if (it == table_.end()) {
5071 LOG(FATAL) << "IndexOf(\"" << s << "\") failed";
5072 }
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07005073 return it->index;
Elliott Hughes545a0642011-11-08 19:10:03 -08005074 }
5075
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07005076 size_t Size() const {
Elliott Hughes545a0642011-11-08 19:10:03 -08005077 return table_.size();
5078 }
5079
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07005080 void WriteTo(std::vector<uint8_t>& bytes) const {
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07005081 DCHECK(finished_);
5082 uint32_t cur_index = 0;
5083 for (const auto& entry : table_) {
5084 DCHECK_EQ(cur_index++, entry.index);
5085
5086 size_t s_len = CountModifiedUtf8Chars(entry.data);
Christopher Ferris8a354052015-04-24 17:23:53 -07005087 std::unique_ptr<uint16_t[]> s_utf16(new uint16_t[s_len]);
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07005088 ConvertModifiedUtf8ToUtf16(s_utf16.get(), entry.data);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005089 JDWP::AppendUtf16BE(bytes, s_utf16.get(), s_len);
Elliott Hughes545a0642011-11-08 19:10:03 -08005090 }
5091 }
5092
5093 private:
Andreas Gampe84eadb22017-07-07 15:08:01 -07005094 std::unordered_set<Entry, EntryHash> table_;
Andreas Gampef774a4e2017-07-06 22:15:18 -07005095 std::vector<std::unique_ptr<char[]>> string_backup_;
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07005096
5097 bool finished_;
5098
Elliott Hughes545a0642011-11-08 19:10:03 -08005099 DISALLOW_COPY_AND_ASSIGN(StringTable);
5100};
5101
Mathieu Chartiere401d142015-04-22 13:56:20 -07005102static const char* GetMethodSourceFile(ArtMethod* method)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005103 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07005104 DCHECK(method != nullptr);
5105 const char* source_file = method->GetDeclaringClassSourceFile();
Sebastien Hertz280286a2014-04-28 09:26:50 +02005106 return (source_file != nullptr) ? source_file : "";
5107}
5108
Elliott Hughes545a0642011-11-08 19:10:03 -08005109/*
5110 * The data we send to DDMS contains everything we have recorded.
5111 *
5112 * Message header (all values big-endian):
5113 * (1b) message header len (to allow future expansion); includes itself
5114 * (1b) entry header len
5115 * (1b) stack frame len
5116 * (2b) number of entries
5117 * (4b) offset to string table from start of message
5118 * (2b) number of class name strings
5119 * (2b) number of method name strings
5120 * (2b) number of source file name strings
5121 * For each entry:
5122 * (4b) total allocation size
Elliott Hughes221229c2013-01-08 18:17:50 -08005123 * (2b) thread id
Elliott Hughes545a0642011-11-08 19:10:03 -08005124 * (2b) allocated object's class name index
5125 * (1b) stack depth
5126 * For each stack frame:
5127 * (2b) method's class name
5128 * (2b) method name
5129 * (2b) method source file
5130 * (2b) line number, clipped to 32767; -2 if native; -1 if no source
5131 * (xb) class name strings
5132 * (xb) method name strings
5133 * (xb) source file strings
5134 *
5135 * As with other DDM traffic, strings are sent as a 4-byte length
5136 * followed by UTF-16 data.
5137 *
5138 * We send up 16-bit unsigned indexes into string tables. In theory there
Brian Carlstrom306db812014-09-05 13:01:41 -07005139 * can be (kMaxAllocRecordStackDepth * alloc_record_max_) unique strings in
Elliott Hughes545a0642011-11-08 19:10:03 -08005140 * each table, but in practice there should be far fewer.
5141 *
5142 * The chief reason for using a string table here is to keep the size of
5143 * the DDMS message to a minimum. This is partly to make the protocol
5144 * efficient, but also because we have to form the whole thing up all at
5145 * once in a memory buffer.
5146 *
5147 * We use separate string tables for class names, method names, and source
5148 * files to keep the indexes small. There will generally be no overlap
5149 * between the contents of these tables.
5150 */
5151jbyteArray Dbg::GetRecentAllocations() {
Ian Rogerscf7f1912014-10-22 22:06:39 -07005152 if ((false)) {
Elliott Hughes545a0642011-11-08 19:10:03 -08005153 DumpRecentAllocations();
5154 }
5155
Ian Rogers50b35e22012-10-04 10:09:15 -07005156 Thread* self = Thread::Current();
Elliott Hughes545a0642011-11-08 19:10:03 -08005157 std::vector<uint8_t> bytes;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005158 {
Brian Carlstrom306db812014-09-05 13:01:41 -07005159 MutexLock mu(self, *Locks::alloc_tracker_lock_);
Man Cao8c2ff642015-05-27 17:25:30 -07005160 gc::AllocRecordObjectMap* records = Runtime::Current()->GetHeap()->GetAllocationRecords();
5161 // In case this method is called when allocation tracker is disabled,
5162 // we should still send some data back.
5163 gc::AllocRecordObjectMap dummy;
5164 if (records == nullptr) {
5165 CHECK(!Runtime::Current()->GetHeap()->IsAllocTrackingEnabled());
5166 records = &dummy;
5167 }
Man Cao41656de2015-07-06 18:53:15 -07005168 // We don't need to wait on the condition variable records->new_record_condition_, because this
5169 // function only reads the class objects, which are already marked so it doesn't change their
5170 // reachability.
Man Cao8c2ff642015-05-27 17:25:30 -07005171
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005172 //
5173 // Part 1: generate string tables.
5174 //
5175 StringTable class_names;
5176 StringTable method_names;
5177 StringTable filenames;
Elliott Hughes545a0642011-11-08 19:10:03 -08005178
Andreas Gampeff29cee2017-07-07 11:11:15 -07005179 VLOG(jdwp) << "Collecting StringTables.";
5180
Man Cao1ed11b92015-06-11 22:47:35 -07005181 const uint16_t capped_count = CappedAllocRecordCount(records->GetRecentAllocationSize());
Brian Carlstrom306db812014-09-05 13:01:41 -07005182 uint16_t count = capped_count;
Andreas Gamped0fc7682017-07-07 14:03:08 -07005183 size_t alloc_byte_count = 0;
Man Cao8c2ff642015-05-27 17:25:30 -07005184 for (auto it = records->RBegin(), end = records->REnd();
5185 count > 0 && it != end; count--, it++) {
Mathieu Chartier458b1052016-03-29 14:02:55 -07005186 const gc::AllocRecord* record = &it->second;
Ian Rogers1ff3c982014-08-12 02:30:58 -07005187 std::string temp;
Andreas Gampef774a4e2017-07-06 22:15:18 -07005188 const char* class_descr = record->GetClassDescriptor(&temp);
5189 class_names.Add(class_descr, !temp.empty());
Andreas Gamped0fc7682017-07-07 14:03:08 -07005190
5191 // Size + tid + class name index + stack depth.
5192 alloc_byte_count += 4u + 2u + 2u + 1u;
5193
Man Cao8c2ff642015-05-27 17:25:30 -07005194 for (size_t i = 0, depth = record->GetDepth(); i < depth; i++) {
5195 ArtMethod* m = record->StackElement(i).GetMethod();
Andreas Gampef774a4e2017-07-06 22:15:18 -07005196 class_names.Add(m->GetDeclaringClassDescriptor(), false);
5197 method_names.Add(m->GetName(), false);
5198 filenames.Add(GetMethodSourceFile(m), false);
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005199 }
Andreas Gamped0fc7682017-07-07 14:03:08 -07005200
5201 // Depth * (class index + method name index + file name index + line number).
5202 alloc_byte_count += record->GetDepth() * (2u + 2u + 2u + 2u);
Elliott Hughes545a0642011-11-08 19:10:03 -08005203 }
5204
Andreas Gampe2eeb01a2017-07-07 14:09:46 -07005205 class_names.Finish();
5206 method_names.Finish();
5207 filenames.Finish();
Andreas Gampeff29cee2017-07-07 11:11:15 -07005208 VLOG(jdwp) << "Done collecting StringTables:" << std::endl
5209 << " ClassNames: " << class_names.Size() << std::endl
5210 << " MethodNames: " << method_names.Size() << std::endl
5211 << " Filenames: " << filenames.Size();
5212
Man Cao8c2ff642015-05-27 17:25:30 -07005213 LOG(INFO) << "recent allocation records: " << capped_count;
5214 LOG(INFO) << "allocation records all objects: " << records->Size();
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005215
5216 //
5217 // Part 2: Generate the output and store it in the buffer.
5218 //
5219
5220 // (1b) message header len (to allow future expansion); includes itself
5221 // (1b) entry header len
5222 // (1b) stack frame len
5223 const int kMessageHeaderLen = 15;
5224 const int kEntryHeaderLen = 9;
5225 const int kStackFrameLen = 8;
5226 JDWP::Append1BE(bytes, kMessageHeaderLen);
5227 JDWP::Append1BE(bytes, kEntryHeaderLen);
5228 JDWP::Append1BE(bytes, kStackFrameLen);
5229
5230 // (2b) number of entries
5231 // (4b) offset to string table from start of message
5232 // (2b) number of class name strings
5233 // (2b) number of method name strings
5234 // (2b) number of source file name strings
Brian Carlstrom306db812014-09-05 13:01:41 -07005235 JDWP::Append2BE(bytes, capped_count);
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005236 size_t string_table_offset = bytes.size();
Brian Carlstrom7934ac22013-07-26 10:54:15 -07005237 JDWP::Append4BE(bytes, 0); // We'll patch this later...
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005238 JDWP::Append2BE(bytes, class_names.Size());
5239 JDWP::Append2BE(bytes, method_names.Size());
5240 JDWP::Append2BE(bytes, filenames.Size());
5241
Andreas Gampeff29cee2017-07-07 11:11:15 -07005242 VLOG(jdwp) << "Dumping allocations with stacks";
5243
Andreas Gamped0fc7682017-07-07 14:03:08 -07005244 // Enlarge the vector for the allocation data.
5245 size_t reserve_size = bytes.size() + alloc_byte_count;
5246 bytes.reserve(reserve_size);
5247
Ian Rogers1ff3c982014-08-12 02:30:58 -07005248 std::string temp;
Man Cao8c2ff642015-05-27 17:25:30 -07005249 count = capped_count;
5250 // The last "count" number of allocation records in "records" are the most recent "count" number
5251 // of allocations. Reverse iterate to get them. The most recent allocation is sent first.
5252 for (auto it = records->RBegin(), end = records->REnd();
5253 count > 0 && it != end; count--, it++) {
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005254 // For each entry:
5255 // (4b) total allocation size
5256 // (2b) thread id
5257 // (2b) allocated object's class name index
5258 // (1b) stack depth
Mathieu Chartier458b1052016-03-29 14:02:55 -07005259 const gc::AllocRecord* record = &it->second;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005260 size_t stack_depth = record->GetDepth();
Mathieu Chartierf8322842014-05-16 10:59:25 -07005261 size_t allocated_object_class_name_index =
Man Cao41656de2015-07-06 18:53:15 -07005262 class_names.IndexOf(record->GetClassDescriptor(&temp));
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07005263 JDWP::Append4BE(bytes, record->ByteCount());
Man Cao8c2ff642015-05-27 17:25:30 -07005264 JDWP::Append2BE(bytes, static_cast<uint16_t>(record->GetTid()));
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005265 JDWP::Append2BE(bytes, allocated_object_class_name_index);
5266 JDWP::Append1BE(bytes, stack_depth);
5267
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005268 for (size_t stack_frame = 0; stack_frame < stack_depth; ++stack_frame) {
5269 // For each stack frame:
5270 // (2b) method's class name
5271 // (2b) method name
5272 // (2b) method source file
5273 // (2b) line number, clipped to 32767; -2 if native; -1 if no source
Man Cao8c2ff642015-05-27 17:25:30 -07005274 ArtMethod* m = record->StackElement(stack_frame).GetMethod();
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07005275 size_t class_name_index = class_names.IndexOf(m->GetDeclaringClassDescriptor());
5276 size_t method_name_index = method_names.IndexOf(m->GetName());
5277 size_t file_name_index = filenames.IndexOf(GetMethodSourceFile(m));
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005278 JDWP::Append2BE(bytes, class_name_index);
5279 JDWP::Append2BE(bytes, method_name_index);
5280 JDWP::Append2BE(bytes, file_name_index);
Man Cao8c2ff642015-05-27 17:25:30 -07005281 JDWP::Append2BE(bytes, record->StackElement(stack_frame).ComputeLineNumber());
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005282 }
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005283 }
5284
Andreas Gamped0fc7682017-07-07 14:03:08 -07005285 CHECK_EQ(bytes.size(), reserve_size);
Andreas Gampeff29cee2017-07-07 11:11:15 -07005286 VLOG(jdwp) << "Dumping tables.";
5287
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005288 // (xb) class name strings
5289 // (xb) method name strings
5290 // (xb) source file strings
5291 JDWP::Set4BE(&bytes[string_table_offset], bytes.size());
5292 class_names.WriteTo(bytes);
5293 method_names.WriteTo(bytes);
5294 filenames.WriteTo(bytes);
Andreas Gampeff29cee2017-07-07 11:11:15 -07005295
5296 VLOG(jdwp) << "GetRecentAllocations: data created. " << bytes.size();
Elliott Hughes545a0642011-11-08 19:10:03 -08005297 }
Ian Rogers50b35e22012-10-04 10:09:15 -07005298 JNIEnv* env = self->GetJniEnv();
Elliott Hughes545a0642011-11-08 19:10:03 -08005299 jbyteArray result = env->NewByteArray(bytes.size());
Ian Rogersc0542af2014-09-03 16:16:56 -07005300 if (result != nullptr) {
Elliott Hughes545a0642011-11-08 19:10:03 -08005301 env->SetByteArrayRegion(result, 0, bytes.size(), reinterpret_cast<const jbyte*>(&bytes[0]));
5302 }
5303 return result;
5304}
5305
Mathieu Chartiere401d142015-04-22 13:56:20 -07005306ArtMethod* DeoptimizationRequest::Method() const {
Andreas Gampe13b27842016-11-07 16:48:23 -08005307 return jni::DecodeArtMethod(method_);
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07005308}
5309
Mathieu Chartiere401d142015-04-22 13:56:20 -07005310void DeoptimizationRequest::SetMethod(ArtMethod* m) {
Andreas Gampe13b27842016-11-07 16:48:23 -08005311 method_ = jni::EncodeArtMethod(m);
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07005312}
5313
Mathieu Chartiera6b1ead2015-10-06 10:32:38 -07005314void Dbg::VisitRoots(RootVisitor* visitor) {
5315 // Visit breakpoint roots, used to prevent unloading of methods with breakpoints.
5316 ReaderMutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
5317 BufferedRootVisitor<128> root_visitor(visitor, RootInfo(kRootVMInternal));
5318 for (Breakpoint& breakpoint : gBreakpoints) {
Andreas Gampe542451c2016-07-26 09:02:02 -07005319 breakpoint.Method()->VisitRoots(root_visitor, kRuntimePointerSize);
Mathieu Chartiera6b1ead2015-10-06 10:32:38 -07005320 }
5321}
5322
Andreas Gampe04bbb5b2017-01-19 17:49:03 +00005323void Dbg::DbgThreadLifecycleCallback::ThreadStart(Thread* self) {
5324 Dbg::PostThreadStart(self);
5325}
5326
5327void Dbg::DbgThreadLifecycleCallback::ThreadDeath(Thread* self) {
5328 Dbg::PostThreadDeath(self);
5329}
5330
Andreas Gampe0f01b582017-01-18 15:22:37 -08005331void Dbg::DbgClassLoadCallback::ClassLoad(Handle<mirror::Class> klass ATTRIBUTE_UNUSED) {
5332 // Ignore ClassLoad;
5333}
5334void Dbg::DbgClassLoadCallback::ClassPrepare(Handle<mirror::Class> temp_klass ATTRIBUTE_UNUSED,
5335 Handle<mirror::Class> klass) {
5336 Dbg::PostClassPrepare(klass.Get());
5337}
5338
Elliott Hughes872d4ec2011-10-21 17:07:15 -07005339} // namespace art