blob: 502ce4b76d243c6e3f11941a2042f75eefd86797 [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
Elliott Hughes545a0642011-11-08 19:10:03 -080021#include <set>
22
Ian Rogers166db042013-07-26 12:05:57 -070023#include "arch/context.h"
Mathieu Chartierc7853442015-03-27 14:35:38 -070024#include "art_field-inl.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070025#include "art_method-inl.h"
Andreas Gampe542451c2016-07-26 09:02:02 -070026#include "base/enums.h"
Vladimir Marko80afd022015-05-19 18:08:00 +010027#include "base/time_utils.h"
Elliott Hughes545a0642011-11-08 19:10:03 -080028#include "class_linker.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080029#include "class_linker-inl.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070030#include "dex_file-inl.h"
David Sehr9323e6e2016-09-13 08:58:35 -070031#include "dex_file_annotations.h"
Ian Rogers776ac1f2012-04-13 23:36:36 -070032#include "dex_instruction.h"
Mingyao Yang6ea1a0e2016-01-29 12:12:49 -080033#include "entrypoints/runtime_asm_entrypoints.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070034#include "gc/accounting/card_table-inl.h"
Man Cao8c2ff642015-05-27 17:25:30 -070035#include "gc/allocation_record.h"
Mathieu Chartieraa516822015-10-02 15:53:37 -070036#include "gc/scoped_gc_critical_section.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070037#include "gc/space/large_object_space.h"
38#include "gc/space/space-inl.h"
Mathieu Chartiereb8167a2014-05-07 15:43:14 -070039#include "handle_scope.h"
Sebastien Hertzcbc50642015-06-01 17:33:12 +020040#include "jdwp/jdwp_priv.h"
Elliott Hughes64f574f2013-02-20 14:57:12 -080041#include "jdwp/object_registry.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080042#include "mirror/class.h"
43#include "mirror/class-inl.h"
44#include "mirror/class_loader.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080045#include "mirror/object-inl.h"
46#include "mirror/object_array-inl.h"
Ian Rogersb0fa5dc2014-04-28 16:47:08 -070047#include "mirror/string-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080048#include "mirror/throwable.h"
Mathieu Chartier3398c782016-09-30 10:27:43 -070049#include "obj_ptr-inl.h"
Ian Rogers53b8b092014-03-13 23:45:53 -070050#include "reflection.h"
Elliott Hughesa0e18062012-04-13 15:59:59 -070051#include "safe_map.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070052#include "scoped_thread_state_change-inl.h"
Elliott Hughes6a5bd492011-10-28 14:33:57 -070053#include "ScopedLocalRef.h"
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -070054#include "ScopedPrimitiveArray.h"
Mathieu Chartiereb8167a2014-05-07 15:43:14 -070055#include "handle_scope-inl.h"
Elliott Hughes475fc232011-10-25 15:00:35 -070056#include "thread_list.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080057#include "utf.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070058#include "well_known_classes.h"
Elliott Hughes475fc232011-10-25 15:00:35 -070059
Elliott Hughes872d4ec2011-10-21 17:07:15 -070060namespace art {
61
Sebastien Hertz0462c4c2015-04-01 16:34:17 +020062// The key identifying the debugger to update instrumentation.
63static constexpr const char* kDbgInstrumentationKey = "Debugger";
64
Man Cao8c2ff642015-05-27 17:25:30 -070065// 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 -070066static uint16_t CappedAllocRecordCount(size_t alloc_record_count) {
Man Cao1ed11b92015-06-11 22:47:35 -070067 const size_t cap = 0xffff;
Man Cao8c2ff642015-05-27 17:25:30 -070068 if (alloc_record_count > cap) {
69 return cap;
Brian Carlstrom306db812014-09-05 13:01:41 -070070 }
71 return alloc_record_count;
72}
Elliott Hughes475fc232011-10-25 15:00:35 -070073
Alex Light6c8467f2015-11-20 15:03:26 -080074// Takes a method and returns a 'canonical' one if the method is default (and therefore potentially
75// copied from some other class). This ensures that the debugger does not get confused as to which
76// method we are in.
77static ArtMethod* GetCanonicalMethod(ArtMethod* m)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -070078 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light6c8467f2015-11-20 15:03:26 -080079 if (LIKELY(!m->IsDefault())) {
80 return m;
81 } else {
82 mirror::Class* declaring_class = m->GetDeclaringClass();
83 return declaring_class->FindDeclaredVirtualMethod(declaring_class->GetDexCache(),
84 m->GetDexMethodIndex(),
Andreas Gampe542451c2016-07-26 09:02:02 -070085 kRuntimePointerSize);
Alex Light6c8467f2015-11-20 15:03:26 -080086 }
87}
88
Mathieu Chartier41af5e52015-10-28 11:10:46 -070089class Breakpoint : public ValueObject {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -070090 public:
Mathieu Chartier41af5e52015-10-28 11:10:46 -070091 Breakpoint(ArtMethod* method, uint32_t dex_pc, DeoptimizationRequest::Kind deoptimization_kind)
Alex Light6c8467f2015-11-20 15:03:26 -080092 : method_(GetCanonicalMethod(method)),
Mathieu Chartier41af5e52015-10-28 11:10:46 -070093 dex_pc_(dex_pc),
94 deoptimization_kind_(deoptimization_kind) {
Sebastien Hertzf3928792014-11-17 19:00:37 +010095 CHECK(deoptimization_kind_ == DeoptimizationRequest::kNothing ||
96 deoptimization_kind_ == DeoptimizationRequest::kSelectiveDeoptimization ||
97 deoptimization_kind_ == DeoptimizationRequest::kFullDeoptimization);
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -070098 }
99
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700100 Breakpoint(const Breakpoint& other) REQUIRES_SHARED(Locks::mutator_lock_)
Mathieu Chartier41af5e52015-10-28 11:10:46 -0700101 : method_(other.method_),
102 dex_pc_(other.dex_pc_),
103 deoptimization_kind_(other.deoptimization_kind_) {}
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700104
Mathieu Chartier41af5e52015-10-28 11:10:46 -0700105 // Method() is called from root visiting, do not use ScopedObjectAccess here or it can cause
106 // GC to deadlock if another thread tries to call SuspendAll while the GC is in a runnable state.
107 ArtMethod* Method() const {
108 return method_;
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700109 }
110
111 uint32_t DexPc() const {
112 return dex_pc_;
113 }
114
Sebastien Hertzf3928792014-11-17 19:00:37 +0100115 DeoptimizationRequest::Kind GetDeoptimizationKind() const {
116 return deoptimization_kind_;
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700117 }
118
Alex Light6c8467f2015-11-20 15:03:26 -0800119 // Returns true if the method of this breakpoint and the passed in method should be considered the
120 // same. That is, they are either the same method or they are copied from the same method.
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700121 bool IsInMethod(ArtMethod* m) const REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light6c8467f2015-11-20 15:03:26 -0800122 return method_ == GetCanonicalMethod(m);
123 }
124
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700125 private:
Sebastien Hertza76a6d42014-03-20 16:40:17 +0100126 // The location of this breakpoint.
Mathieu Chartier41af5e52015-10-28 11:10:46 -0700127 ArtMethod* method_;
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700128 uint32_t dex_pc_;
Sebastien Hertza76a6d42014-03-20 16:40:17 +0100129
130 // Indicates whether breakpoint needs full deoptimization or selective deoptimization.
Sebastien Hertzf3928792014-11-17 19:00:37 +0100131 DeoptimizationRequest::Kind deoptimization_kind_;
Elliott Hughes86964332012-02-15 19:37:42 -0800132};
133
Sebastien Hertzed2be172014-08-19 15:33:43 +0200134static std::ostream& operator<<(std::ostream& os, const Breakpoint& rhs)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700135 REQUIRES_SHARED(Locks::mutator_lock_) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700136 os << StringPrintf("Breakpoint[%s @%#x]", PrettyMethod(rhs.Method()).c_str(), rhs.DexPc());
Elliott Hughes86964332012-02-15 19:37:42 -0800137 return os;
138}
139
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200140class DebugInstrumentationListener FINAL : public instrumentation::InstrumentationListener {
Ian Rogers62d6c772013-02-27 08:32:07 -0800141 public:
142 DebugInstrumentationListener() {}
143 virtual ~DebugInstrumentationListener() {}
144
Mathieu Chartiere401d142015-04-22 13:56:20 -0700145 void MethodEntered(Thread* thread, mirror::Object* this_object, ArtMethod* method,
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200146 uint32_t dex_pc)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700147 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800148 if (method->IsNative()) {
149 // TODO: post location events is a suspension point and native method entry stubs aren't.
150 return;
151 }
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200152 if (IsListeningToDexPcMoved()) {
153 // We also listen to kDexPcMoved instrumentation event so we know the DexPcMoved method is
154 // going to be called right after us. To avoid sending JDWP events twice for this location,
155 // we report the event in DexPcMoved. However, we must remind this is method entry so we
156 // send the METHOD_ENTRY event. And we can also group it with other events for this location
157 // like BREAKPOINT or SINGLE_STEP (or even METHOD_EXIT if this is a RETURN instruction).
158 thread->SetDebugMethodEntry();
159 } else if (IsListeningToMethodExit() && IsReturn(method, dex_pc)) {
160 // We also listen to kMethodExited instrumentation event and the current instruction is a
161 // RETURN so we know the MethodExited method is going to be called right after us. To avoid
162 // sending JDWP events twice for this location, we report the event(s) in MethodExited.
163 // However, we must remind this is method entry so we send the METHOD_ENTRY event. And we can
164 // also group it with other events for this location like BREAKPOINT or SINGLE_STEP.
165 thread->SetDebugMethodEntry();
166 } else {
167 Dbg::UpdateDebugger(thread, this_object, method, 0, Dbg::kMethodEntry, nullptr);
168 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800169 }
170
Mathieu Chartiere401d142015-04-22 13:56:20 -0700171 void MethodExited(Thread* thread, mirror::Object* this_object, ArtMethod* method,
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200172 uint32_t dex_pc, const JValue& return_value)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700173 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800174 if (method->IsNative()) {
175 // TODO: post location events is a suspension point and native method entry stubs aren't.
176 return;
177 }
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200178 uint32_t events = Dbg::kMethodExit;
179 if (thread->IsDebugMethodEntry()) {
180 // It is also the method entry.
181 DCHECK(IsReturn(method, dex_pc));
182 events |= Dbg::kMethodEntry;
183 thread->ClearDebugMethodEntry();
184 }
185 Dbg::UpdateDebugger(thread, this_object, method, dex_pc, events, &return_value);
Ian Rogers62d6c772013-02-27 08:32:07 -0800186 }
187
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200188 void MethodUnwind(Thread* thread ATTRIBUTE_UNUSED, mirror::Object* this_object ATTRIBUTE_UNUSED,
Mathieu Chartiere401d142015-04-22 13:56:20 -0700189 ArtMethod* method, uint32_t dex_pc)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700190 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800191 // We're not recorded to listen to this kind of event, so complain.
192 LOG(ERROR) << "Unexpected method unwind event in debugger " << PrettyMethod(method)
Sebastien Hertz51db44a2013-11-19 10:00:29 +0100193 << " " << dex_pc;
Ian Rogers62d6c772013-02-27 08:32:07 -0800194 }
195
Mathieu Chartiere401d142015-04-22 13:56:20 -0700196 void DexPcMoved(Thread* thread, mirror::Object* this_object, ArtMethod* method,
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200197 uint32_t new_dex_pc)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700198 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200199 if (IsListeningToMethodExit() && IsReturn(method, new_dex_pc)) {
200 // We also listen to kMethodExited instrumentation event and the current instruction is a
201 // RETURN so we know the MethodExited method is going to be called right after us. Like in
202 // MethodEntered, we delegate event reporting to MethodExited.
203 // Besides, if this RETURN instruction is the only one in the method, we can send multiple
204 // JDWP events in the same packet: METHOD_ENTRY, METHOD_EXIT, BREAKPOINT and/or SINGLE_STEP.
205 // Therefore, we must not clear the debug method entry flag here.
206 } else {
207 uint32_t events = 0;
208 if (thread->IsDebugMethodEntry()) {
209 // It is also the method entry.
210 events = Dbg::kMethodEntry;
211 thread->ClearDebugMethodEntry();
212 }
213 Dbg::UpdateDebugger(thread, this_object, method, new_dex_pc, events, nullptr);
214 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800215 }
216
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200217 void FieldRead(Thread* thread ATTRIBUTE_UNUSED, mirror::Object* this_object,
Mathieu Chartiere401d142015-04-22 13:56:20 -0700218 ArtMethod* method, uint32_t dex_pc, ArtField* field)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700219 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200220 Dbg::PostFieldAccessEvent(method, dex_pc, this_object, field);
Ian Rogers62d6c772013-02-27 08:32:07 -0800221 }
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200222
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700223 void FieldWritten(Thread* thread ATTRIBUTE_UNUSED, mirror::Object* this_object,
Mathieu Chartiere401d142015-04-22 13:56:20 -0700224 ArtMethod* method, uint32_t dex_pc, ArtField* field,
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700225 const JValue& field_value)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700226 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200227 Dbg::PostFieldModificationEvent(method, dex_pc, this_object, field, &field_value);
228 }
229
Nicolas Geoffray14691c52015-03-05 10:40:17 +0000230 void ExceptionCaught(Thread* thread ATTRIBUTE_UNUSED, mirror::Throwable* exception_object)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700231 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray14691c52015-03-05 10:40:17 +0000232 Dbg::PostException(exception_object);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200233 }
234
Nicolas Geoffray81f0f952016-01-20 16:25:19 +0000235 // We only care about branches in the Jit.
236 void Branch(Thread* /*thread*/, ArtMethod* method, uint32_t dex_pc, int32_t dex_pc_offset)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700237 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray81f0f952016-01-20 16:25:19 +0000238 LOG(ERROR) << "Unexpected branch event in debugger " << PrettyMethod(method)
239 << " " << dex_pc << ", " << dex_pc_offset;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800240 }
241
Nicolas Geoffray5550ca82015-08-21 18:38:30 +0100242 // We only care about invokes in the Jit.
243 void InvokeVirtualOrInterface(Thread* thread ATTRIBUTE_UNUSED,
244 mirror::Object*,
245 ArtMethod* method,
246 uint32_t dex_pc,
247 ArtMethod*)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700248 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray5550ca82015-08-21 18:38:30 +0100249 LOG(ERROR) << "Unexpected invoke event in debugger " << PrettyMethod(method)
250 << " " << dex_pc;
251 }
252
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200253 private:
Mathieu Chartiere401d142015-04-22 13:56:20 -0700254 static bool IsReturn(ArtMethod* method, uint32_t dex_pc)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700255 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200256 const DexFile::CodeItem* code_item = method->GetCodeItem();
257 const Instruction* instruction = Instruction::At(&code_item->insns_[dex_pc]);
258 return instruction->IsReturn();
259 }
260
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700261 static bool IsListeningToDexPcMoved() REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200262 return IsListeningTo(instrumentation::Instrumentation::kDexPcMoved);
263 }
264
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700265 static bool IsListeningToMethodExit() REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200266 return IsListeningTo(instrumentation::Instrumentation::kMethodExited);
267 }
268
269 static bool IsListeningTo(instrumentation::Instrumentation::InstrumentationEvent event)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700270 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200271 return (Dbg::GetInstrumentationEvents() & event) != 0;
272 }
273
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200274 DISALLOW_COPY_AND_ASSIGN(DebugInstrumentationListener);
Ian Rogers62d6c772013-02-27 08:32:07 -0800275} gDebugInstrumentationListener;
276
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700277// JDWP is allowed unless the Zygote forbids it.
278static bool gJdwpAllowed = true;
279
Elliott Hughesc0f09332012-03-26 13:27:06 -0700280// Was there a -Xrunjdwp or -agentlib:jdwp= argument on the command line?
Elliott Hughes3bb81562011-10-21 18:52:59 -0700281static bool gJdwpConfigured = false;
282
Sebastien Hertzb3b173b2015-02-06 09:16:32 +0100283// JDWP options for debugging. Only valid if IsJdwpConfigured() is true.
284static JDWP::JdwpOptions gJdwpOptions;
285
Elliott Hughes3bb81562011-10-21 18:52:59 -0700286// Runtime JDWP state.
Ian Rogersc0542af2014-09-03 16:16:56 -0700287static JDWP::JdwpState* gJdwpState = nullptr;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700288static bool gDebuggerConnected; // debugger or DDMS is connected.
Elliott Hughes3bb81562011-10-21 18:52:59 -0700289
Elliott Hughes47fce012011-10-25 18:37:19 -0700290static bool gDdmThreadNotification = false;
291
Elliott Hughes767a1472011-10-26 18:49:02 -0700292// DDMS GC-related settings.
293static Dbg::HpifWhen gDdmHpifWhen = Dbg::HPIF_WHEN_NEVER;
294static Dbg::HpsgWhen gDdmHpsgWhen = Dbg::HPSG_WHEN_NEVER;
295static Dbg::HpsgWhat gDdmHpsgWhat;
296static Dbg::HpsgWhen gDdmNhsgWhen = Dbg::HPSG_WHEN_NEVER;
297static Dbg::HpsgWhat gDdmNhsgWhat;
298
Daniel Mihalyieb076692014-08-22 17:33:31 +0200299bool Dbg::gDebuggerActive = false;
Sebastien Hertz4e5b2082015-03-24 19:03:40 +0100300bool Dbg::gDisposed = false;
Sebastien Hertz6995c602014-09-09 12:10:13 +0200301ObjectRegistry* Dbg::gRegistry = nullptr;
Elliott Hughes475fc232011-10-25 15:00:35 -0700302
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100303// Deoptimization support.
Sebastien Hertz4d25df32014-03-21 17:44:46 +0100304std::vector<DeoptimizationRequest> Dbg::deoptimization_requests_;
305size_t Dbg::full_deoptimization_event_count_ = 0;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100306
Sebastien Hertz42cd43f2014-05-13 14:15:41 +0200307// Instrumentation event reference counters.
308size_t Dbg::dex_pc_change_event_ref_count_ = 0;
309size_t Dbg::method_enter_event_ref_count_ = 0;
310size_t Dbg::method_exit_event_ref_count_ = 0;
311size_t Dbg::field_read_event_ref_count_ = 0;
312size_t Dbg::field_write_event_ref_count_ = 0;
313size_t Dbg::exception_catch_event_ref_count_ = 0;
314uint32_t Dbg::instrumentation_events_ = 0;
315
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100316// Breakpoints.
jeffhao09bfc6a2012-12-11 18:11:43 -0800317static std::vector<Breakpoint> gBreakpoints GUARDED_BY(Locks::breakpoint_lock_);
Elliott Hughes86964332012-02-15 19:37:42 -0800318
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700319void DebugInvokeReq::VisitRoots(RootVisitor* visitor, const RootInfo& root_info) {
320 receiver.VisitRootIfNonNull(visitor, root_info); // null for static method call.
321 klass.VisitRoot(visitor, root_info);
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700322}
323
Sebastien Hertz597c4f02015-01-26 17:37:14 +0100324void SingleStepControl::AddDexPc(uint32_t dex_pc) {
325 dex_pcs_.insert(dex_pc);
Sebastien Hertzbb43b432014-04-14 11:59:08 +0200326}
327
Sebastien Hertz597c4f02015-01-26 17:37:14 +0100328bool SingleStepControl::ContainsDexPc(uint32_t dex_pc) const {
329 return dex_pcs_.find(dex_pc) == dex_pcs_.end();
Sebastien Hertzbb43b432014-04-14 11:59:08 +0200330}
331
Alex Light6c8467f2015-11-20 15:03:26 -0800332static bool IsBreakpoint(ArtMethod* m, uint32_t dex_pc)
Mathieu Chartier90443472015-07-16 20:32:27 -0700333 REQUIRES(!Locks::breakpoint_lock_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700334 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertzed2be172014-08-19 15:33:43 +0200335 ReaderMutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100336 for (size_t i = 0, e = gBreakpoints.size(); i < e; ++i) {
Alex Light6c8467f2015-11-20 15:03:26 -0800337 if (gBreakpoints[i].DexPc() == dex_pc && gBreakpoints[i].IsInMethod(m)) {
Elliott Hughes86964332012-02-15 19:37:42 -0800338 VLOG(jdwp) << "Hit breakpoint #" << i << ": " << gBreakpoints[i];
339 return true;
340 }
341 }
342 return false;
343}
344
Sebastien Hertz52d131d2014-03-13 16:17:40 +0100345static bool IsSuspendedForDebugger(ScopedObjectAccessUnchecked& soa, Thread* thread)
Mathieu Chartier90443472015-07-16 20:32:27 -0700346 REQUIRES(!Locks::thread_suspend_count_lock_) {
Elliott Hughes9e0c1752013-01-09 14:02:58 -0800347 MutexLock mu(soa.Self(), *Locks::thread_suspend_count_lock_);
348 // A thread may be suspended for GC; in this code, we really want to know whether
349 // there's a debugger suspension active.
350 return thread->IsSuspended() && thread->GetDebugSuspendCount() > 0;
351}
352
Ian Rogersc0542af2014-09-03 16:16:56 -0700353static mirror::Array* DecodeNonNullArray(JDWP::RefTypeId id, JDWP::JdwpError* error)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700354 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz6995c602014-09-09 12:10:13 +0200355 mirror::Object* o = Dbg::GetObjectRegistry()->Get<mirror::Object*>(id, error);
Ian Rogersc0542af2014-09-03 16:16:56 -0700356 if (o == nullptr) {
357 *error = JDWP::ERR_INVALID_OBJECT;
358 return nullptr;
Elliott Hughes436e3722012-02-17 20:01:47 -0800359 }
360 if (!o->IsArrayInstance()) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700361 *error = JDWP::ERR_INVALID_ARRAY;
362 return nullptr;
Elliott Hughes436e3722012-02-17 20:01:47 -0800363 }
Ian Rogersc0542af2014-09-03 16:16:56 -0700364 *error = JDWP::ERR_NONE;
Elliott Hughes436e3722012-02-17 20:01:47 -0800365 return o->AsArray();
366}
367
Ian Rogersc0542af2014-09-03 16:16:56 -0700368static mirror::Class* DecodeClass(JDWP::RefTypeId id, JDWP::JdwpError* error)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700369 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz6995c602014-09-09 12:10:13 +0200370 mirror::Object* o = Dbg::GetObjectRegistry()->Get<mirror::Object*>(id, error);
Ian Rogersc0542af2014-09-03 16:16:56 -0700371 if (o == nullptr) {
372 *error = JDWP::ERR_INVALID_OBJECT;
373 return nullptr;
Elliott Hughes436e3722012-02-17 20:01:47 -0800374 }
375 if (!o->IsClass()) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700376 *error = JDWP::ERR_INVALID_CLASS;
377 return nullptr;
Elliott Hughes436e3722012-02-17 20:01:47 -0800378 }
Ian Rogersc0542af2014-09-03 16:16:56 -0700379 *error = JDWP::ERR_NONE;
Elliott Hughes436e3722012-02-17 20:01:47 -0800380 return o->AsClass();
381}
382
Ian Rogersc0542af2014-09-03 16:16:56 -0700383static Thread* DecodeThread(ScopedObjectAccessUnchecked& soa, JDWP::ObjectId thread_id,
384 JDWP::JdwpError* error)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700385 REQUIRES_SHARED(Locks::mutator_lock_)
Mathieu Chartier90443472015-07-16 20:32:27 -0700386 REQUIRES(!Locks::thread_list_lock_, !Locks::thread_suspend_count_lock_) {
Sebastien Hertz6995c602014-09-09 12:10:13 +0200387 mirror::Object* thread_peer = Dbg::GetObjectRegistry()->Get<mirror::Object*>(thread_id, error);
Ian Rogersc0542af2014-09-03 16:16:56 -0700388 if (thread_peer == nullptr) {
Elliott Hughes221229c2013-01-08 18:17:50 -0800389 // This isn't even an object.
Ian Rogersc0542af2014-09-03 16:16:56 -0700390 *error = JDWP::ERR_INVALID_OBJECT;
391 return nullptr;
Elliott Hughes436e3722012-02-17 20:01:47 -0800392 }
Elliott Hughes221229c2013-01-08 18:17:50 -0800393
Mathieu Chartier0795f232016-09-27 18:43:30 -0700394 ObjPtr<mirror::Class> java_lang_Thread =
395 soa.Decode<mirror::Class>(WellKnownClasses::java_lang_Thread);
Elliott Hughes221229c2013-01-08 18:17:50 -0800396 if (!java_lang_Thread->IsAssignableFrom(thread_peer->GetClass())) {
397 // This isn't a thread.
Ian Rogersc0542af2014-09-03 16:16:56 -0700398 *error = JDWP::ERR_INVALID_THREAD;
399 return nullptr;
Elliott Hughes221229c2013-01-08 18:17:50 -0800400 }
401
Sebastien Hertz69206392015-04-07 15:54:25 +0200402 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogersc0542af2014-09-03 16:16:56 -0700403 Thread* thread = Thread::FromManagedThread(soa, thread_peer);
404 // If thread is null then this a java.lang.Thread without a Thread*. Must be a un-started or a
405 // zombie.
406 *error = (thread == nullptr) ? JDWP::ERR_THREAD_NOT_ALIVE : JDWP::ERR_NONE;
407 return thread;
Elliott Hughes436e3722012-02-17 20:01:47 -0800408}
409
Elliott Hughes24437992011-11-30 14:49:33 -0800410static JDWP::JdwpTag BasicTagFromDescriptor(const char* descriptor) {
411 // JDWP deliberately uses the descriptor characters' ASCII values for its enum.
412 // Note that by "basic" we mean that we don't get more specific than JT_OBJECT.
413 return static_cast<JDWP::JdwpTag>(descriptor[0]);
414}
415
Ian Rogers1ff3c982014-08-12 02:30:58 -0700416static JDWP::JdwpTag BasicTagFromClass(mirror::Class* klass)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700417 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers1ff3c982014-08-12 02:30:58 -0700418 std::string temp;
419 const char* descriptor = klass->GetDescriptor(&temp);
420 return BasicTagFromDescriptor(descriptor);
421}
422
Ian Rogers98379392014-02-24 16:53:16 -0800423static JDWP::JdwpTag TagFromClass(const ScopedObjectAccessUnchecked& soa, mirror::Class* c)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700424 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700425 CHECK(c != nullptr);
Elliott Hughes24437992011-11-30 14:49:33 -0800426 if (c->IsArrayClass()) {
427 return JDWP::JT_ARRAY;
428 }
Elliott Hughes24437992011-11-30 14:49:33 -0800429 if (c->IsStringClass()) {
430 return JDWP::JT_STRING;
Elliott Hughes24437992011-11-30 14:49:33 -0800431 }
Ian Rogers98379392014-02-24 16:53:16 -0800432 if (c->IsClassClass()) {
433 return JDWP::JT_CLASS_OBJECT;
434 }
435 {
Mathieu Chartier0795f232016-09-27 18:43:30 -0700436 ObjPtr<mirror::Class> thread_class =
437 soa.Decode<mirror::Class>(WellKnownClasses::java_lang_Thread);
Ian Rogers98379392014-02-24 16:53:16 -0800438 if (thread_class->IsAssignableFrom(c)) {
439 return JDWP::JT_THREAD;
440 }
441 }
442 {
Mathieu Chartier0795f232016-09-27 18:43:30 -0700443 ObjPtr<mirror::Class> thread_group_class =
444 soa.Decode<mirror::Class>(WellKnownClasses::java_lang_ThreadGroup);
Ian Rogers98379392014-02-24 16:53:16 -0800445 if (thread_group_class->IsAssignableFrom(c)) {
446 return JDWP::JT_THREAD_GROUP;
447 }
448 }
449 {
Mathieu Chartier0795f232016-09-27 18:43:30 -0700450 ObjPtr<mirror::Class> class_loader_class =
451 soa.Decode<mirror::Class>(WellKnownClasses::java_lang_ClassLoader);
Ian Rogers98379392014-02-24 16:53:16 -0800452 if (class_loader_class->IsAssignableFrom(c)) {
453 return JDWP::JT_CLASS_LOADER;
454 }
455 }
456 return JDWP::JT_OBJECT;
Elliott Hughes24437992011-11-30 14:49:33 -0800457}
458
459/*
460 * Objects declared to hold Object might actually hold a more specific
461 * type. The debugger may take a special interest in these (e.g. it
462 * wants to display the contents of Strings), so we want to return an
463 * appropriate tag.
464 *
465 * Null objects are tagged JT_OBJECT.
466 */
Sebastien Hertz6995c602014-09-09 12:10:13 +0200467JDWP::JdwpTag Dbg::TagFromObject(const ScopedObjectAccessUnchecked& soa, mirror::Object* o) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700468 return (o == nullptr) ? JDWP::JT_OBJECT : TagFromClass(soa, o->GetClass());
Elliott Hughes24437992011-11-30 14:49:33 -0800469}
470
471static bool IsPrimitiveTag(JDWP::JdwpTag tag) {
472 switch (tag) {
473 case JDWP::JT_BOOLEAN:
474 case JDWP::JT_BYTE:
475 case JDWP::JT_CHAR:
476 case JDWP::JT_FLOAT:
477 case JDWP::JT_DOUBLE:
478 case JDWP::JT_INT:
479 case JDWP::JT_LONG:
480 case JDWP::JT_SHORT:
481 case JDWP::JT_VOID:
482 return true;
483 default:
484 return false;
485 }
486}
487
Sebastien Hertzb3b173b2015-02-06 09:16:32 +0100488void Dbg::StartJdwp() {
Elliott Hughesc0f09332012-03-26 13:27:06 -0700489 if (!gJdwpAllowed || !IsJdwpConfigured()) {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700490 // No JDWP for you!
491 return;
492 }
493
Ian Rogers719d1a32014-03-06 12:13:39 -0800494 CHECK(gRegistry == nullptr);
Elliott Hughes475fc232011-10-25 15:00:35 -0700495 gRegistry = new ObjectRegistry;
496
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700497 // Init JDWP if the debugger is enabled. This may connect out to a
498 // debugger, passively listen for a debugger, or block waiting for a
499 // debugger.
Sebastien Hertzb3b173b2015-02-06 09:16:32 +0100500 gJdwpState = JDWP::JdwpState::Create(&gJdwpOptions);
Ian Rogersc0542af2014-09-03 16:16:56 -0700501 if (gJdwpState == nullptr) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -0800502 // We probably failed because some other process has the port already, which means that
503 // if we don't abort the user is likely to think they're talking to us when they're actually
504 // talking to that other process.
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800505 LOG(FATAL) << "Debugger thread failed to initialize";
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700506 }
507
508 // If a debugger has already attached, send the "welcome" message.
509 // This may cause us to suspend all threads.
Elliott Hughes376a7a02011-10-24 18:35:55 -0700510 if (gJdwpState->IsActive()) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700511 ScopedObjectAccess soa(Thread::Current());
Sebastien Hertz7d955652014-10-22 10:57:10 +0200512 gJdwpState->PostVMStart();
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700513 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700514}
515
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700516void Dbg::StopJdwp() {
Sebastien Hertzc6345ef2014-08-18 19:26:39 +0200517 // Post VM_DEATH event before the JDWP connection is closed (either by the JDWP thread or the
518 // destruction of gJdwpState).
519 if (gJdwpState != nullptr && gJdwpState->IsActive()) {
520 gJdwpState->PostVMDeath();
521 }
Sebastien Hertz0376e6b2014-02-06 18:12:59 +0100522 // Prevent the JDWP thread from processing JDWP incoming packets after we close the connection.
Sebastien Hertz4e5b2082015-03-24 19:03:40 +0100523 Dispose();
Elliott Hughes376a7a02011-10-24 18:35:55 -0700524 delete gJdwpState;
Ian Rogers719d1a32014-03-06 12:13:39 -0800525 gJdwpState = nullptr;
Elliott Hughes475fc232011-10-25 15:00:35 -0700526 delete gRegistry;
Ian Rogers719d1a32014-03-06 12:13:39 -0800527 gRegistry = nullptr;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700528}
529
Elliott Hughes767a1472011-10-26 18:49:02 -0700530void Dbg::GcDidFinish() {
531 if (gDdmHpifWhen != HPIF_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700532 ScopedObjectAccess soa(Thread::Current());
Brian Carlstrom4d466a82014-05-08 19:05:29 -0700533 VLOG(jdwp) << "Sending heap info to DDM";
Elliott Hughes7162ad92011-10-27 14:08:42 -0700534 DdmSendHeapInfo(gDdmHpifWhen);
Elliott Hughes767a1472011-10-26 18:49:02 -0700535 }
536 if (gDdmHpsgWhen != HPSG_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700537 ScopedObjectAccess soa(Thread::Current());
Brian Carlstrom4d466a82014-05-08 19:05:29 -0700538 VLOG(jdwp) << "Dumping heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700539 DdmSendHeapSegments(false);
Elliott Hughes767a1472011-10-26 18:49:02 -0700540 }
541 if (gDdmNhsgWhen != HPSG_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700542 ScopedObjectAccess soa(Thread::Current());
Brian Carlstrom4d466a82014-05-08 19:05:29 -0700543 VLOG(jdwp) << "Dumping native heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700544 DdmSendHeapSegments(true);
Elliott Hughes767a1472011-10-26 18:49:02 -0700545 }
546}
547
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700548void Dbg::SetJdwpAllowed(bool allowed) {
549 gJdwpAllowed = allowed;
550}
551
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700552DebugInvokeReq* Dbg::GetInvokeReq() {
Elliott Hughes475fc232011-10-25 15:00:35 -0700553 return Thread::Current()->GetInvokeReq();
554}
555
556Thread* Dbg::GetDebugThread() {
Ian Rogersc0542af2014-09-03 16:16:56 -0700557 return (gJdwpState != nullptr) ? gJdwpState->GetDebugThread() : nullptr;
Elliott Hughes475fc232011-10-25 15:00:35 -0700558}
559
560void Dbg::ClearWaitForEventThread() {
Sebastien Hertz2bf93f42015-01-09 18:44:05 +0100561 gJdwpState->ReleaseJdwpTokenForEvent();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700562}
563
564void Dbg::Connected() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700565 CHECK(!gDebuggerConnected);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800566 VLOG(jdwp) << "JDWP has attached";
Elliott Hughes3bb81562011-10-21 18:52:59 -0700567 gDebuggerConnected = true;
Elliott Hughes86964332012-02-15 19:37:42 -0800568 gDisposed = false;
569}
570
Sebastien Hertzf3928792014-11-17 19:00:37 +0100571bool Dbg::RequiresDeoptimization() {
572 // We don't need deoptimization if everything runs with interpreter after
573 // enabling -Xint mode.
574 return !Runtime::Current()->GetInstrumentation()->IsForcedInterpretOnly();
575}
576
Mingyao Yang6ea1a0e2016-01-29 12:12:49 -0800577// Used to patch boot image method entry point to interpreter bridge.
578class UpdateEntryPointsClassVisitor : public ClassVisitor {
579 public:
580 explicit UpdateEntryPointsClassVisitor(instrumentation::Instrumentation* instrumentation)
581 : instrumentation_(instrumentation) {}
582
583 bool operator()(mirror::Class* klass) OVERRIDE REQUIRES(Locks::mutator_lock_) {
584 auto pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
585 for (auto& m : klass->GetMethods(pointer_size)) {
586 const void* code = m.GetEntryPointFromQuickCompiledCode();
587 if (Runtime::Current()->GetHeap()->IsInBootImageOatFile(code) &&
588 !m.IsNative() &&
589 !m.IsProxyMethod()) {
Mingyao Yang3fd448a2016-05-10 14:30:41 -0700590 instrumentation_->UpdateMethodsCodeFromDebugger(&m, GetQuickToInterpreterBridge());
Mingyao Yang6ea1a0e2016-01-29 12:12:49 -0800591 }
592 }
593 return true;
594 }
595
596 private:
597 instrumentation::Instrumentation* const instrumentation_;
598};
599
Elliott Hughesa2155262011-11-16 16:26:58 -0800600void Dbg::GoActive() {
601 // Enable all debugging features, including scans for breakpoints.
602 // This is a no-op if we're already active.
603 // Only called from the JDWP handler thread.
Daniel Mihalyieb076692014-08-22 17:33:31 +0200604 if (IsDebuggerActive()) {
Elliott Hughesa2155262011-11-16 16:26:58 -0800605 return;
606 }
607
Mathieu Chartieraa516822015-10-02 15:53:37 -0700608 Thread* const self = Thread::Current();
Elliott Hughesc0f09332012-03-26 13:27:06 -0700609 {
610 // TODO: dalvik only warned if there were breakpoints left over. clear in Dbg::Disconnected?
Mathieu Chartieraa516822015-10-02 15:53:37 -0700611 ReaderMutexLock mu(self, *Locks::breakpoint_lock_);
Elliott Hughesc0f09332012-03-26 13:27:06 -0700612 CHECK_EQ(gBreakpoints.size(), 0U);
613 }
Elliott Hughesa2155262011-11-16 16:26:58 -0800614
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100615 {
Mathieu Chartieraa516822015-10-02 15:53:37 -0700616 MutexLock mu(self, *Locks::deoptimization_lock_);
Sebastien Hertz4d25df32014-03-21 17:44:46 +0100617 CHECK_EQ(deoptimization_requests_.size(), 0U);
618 CHECK_EQ(full_deoptimization_event_count_, 0U);
Sebastien Hertz42cd43f2014-05-13 14:15:41 +0200619 CHECK_EQ(dex_pc_change_event_ref_count_, 0U);
620 CHECK_EQ(method_enter_event_ref_count_, 0U);
621 CHECK_EQ(method_exit_event_ref_count_, 0U);
622 CHECK_EQ(field_read_event_ref_count_, 0U);
623 CHECK_EQ(field_write_event_ref_count_, 0U);
624 CHECK_EQ(exception_catch_event_ref_count_, 0U);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100625 }
626
Ian Rogers62d6c772013-02-27 08:32:07 -0800627 Runtime* runtime = Runtime::Current();
David Srbeckyf4480162016-03-16 00:06:24 +0000628 // Since boot image code may be AOT compiled as not debuggable, we need to patch
Mingyao Yang6ea1a0e2016-01-29 12:12:49 -0800629 // entry points of methods in boot image to interpreter bridge.
David Srbeckyf4480162016-03-16 00:06:24 +0000630 // However, the performance cost of this is non-negligible during native-debugging due to the
631 // forced JIT, so we keep the AOT code in that case in exchange for limited native debugging.
632 if (!runtime->GetInstrumentation()->IsForcedInterpretOnly() && !runtime->IsNativeDebuggable()) {
Mingyao Yang6ea1a0e2016-01-29 12:12:49 -0800633 ScopedObjectAccess soa(self);
634 UpdateEntryPointsClassVisitor visitor(runtime->GetInstrumentation());
635 runtime->GetClassLinker()->VisitClasses(&visitor);
636 }
637
Mathieu Chartier4f55e222015-09-04 13:26:21 -0700638 ScopedSuspendAll ssa(__FUNCTION__);
Sebastien Hertzf3928792014-11-17 19:00:37 +0100639 if (RequiresDeoptimization()) {
640 runtime->GetInstrumentation()->EnableDeoptimization();
641 }
Sebastien Hertz42cd43f2014-05-13 14:15:41 +0200642 instrumentation_events_ = 0;
Elliott Hughesa2155262011-11-16 16:26:58 -0800643 gDebuggerActive = true;
Ian Rogers62d6c772013-02-27 08:32:07 -0800644 LOG(INFO) << "Debugger is active";
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700645}
646
647void Dbg::Disconnected() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700648 CHECK(gDebuggerConnected);
649
Elliott Hughesc0f09332012-03-26 13:27:06 -0700650 LOG(INFO) << "Debugger is no longer active";
Elliott Hughes234ab152011-10-26 14:02:26 -0700651
Hiroshi Yamauchi98810e32016-05-24 14:55:40 -0700652 // Suspend all threads and exclusively acquire the mutator lock. Remove the debugger as a listener
Ian Rogers62d6c772013-02-27 08:32:07 -0800653 // and clear the object registry.
654 Runtime* runtime = Runtime::Current();
Ian Rogers62d6c772013-02-27 08:32:07 -0800655 Thread* self = Thread::Current();
Mathieu Chartier4f55e222015-09-04 13:26:21 -0700656 {
Mathieu Chartieraa516822015-10-02 15:53:37 -0700657 // Required for DisableDeoptimization.
658 gc::ScopedGCCriticalSection gcs(self,
659 gc::kGcCauseInstrumentation,
660 gc::kCollectorTypeInstrumentation);
Mathieu Chartier4f55e222015-09-04 13:26:21 -0700661 ScopedSuspendAll ssa(__FUNCTION__);
Mathieu Chartier4f55e222015-09-04 13:26:21 -0700662 // Debugger may not be active at this point.
663 if (IsDebuggerActive()) {
664 {
665 // Since we're going to disable deoptimization, we clear the deoptimization requests queue.
666 // This prevents us from having any pending deoptimization request when the debugger attaches
667 // to us again while no event has been requested yet.
Mathieu Chartiera6b1ead2015-10-06 10:32:38 -0700668 MutexLock mu(self, *Locks::deoptimization_lock_);
Mathieu Chartier4f55e222015-09-04 13:26:21 -0700669 deoptimization_requests_.clear();
670 full_deoptimization_event_count_ = 0U;
671 }
672 if (instrumentation_events_ != 0) {
673 runtime->GetInstrumentation()->RemoveListener(&gDebugInstrumentationListener,
674 instrumentation_events_);
675 instrumentation_events_ = 0;
676 }
677 if (RequiresDeoptimization()) {
678 runtime->GetInstrumentation()->DisableDeoptimization(kDbgInstrumentationKey);
679 }
680 gDebuggerActive = false;
Sebastien Hertzaaea7342014-02-25 15:10:04 +0100681 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100682 }
Sebastien Hertz55f65342015-01-13 22:48:34 +0100683
684 {
685 ScopedObjectAccess soa(self);
686 gRegistry->Clear();
687 }
688
689 gDebuggerConnected = false;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700690}
691
Sebastien Hertzb3b173b2015-02-06 09:16:32 +0100692void Dbg::ConfigureJdwp(const JDWP::JdwpOptions& jdwp_options) {
693 CHECK_NE(jdwp_options.transport, JDWP::kJdwpTransportUnknown);
694 gJdwpOptions = jdwp_options;
695 gJdwpConfigured = true;
696}
697
Elliott Hughesc0f09332012-03-26 13:27:06 -0700698bool Dbg::IsJdwpConfigured() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700699 return gJdwpConfigured;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700700}
701
702int64_t Dbg::LastDebuggerActivity() {
Elliott Hughesca951522011-12-05 12:01:32 -0800703 return gJdwpState->LastDebuggerActivity();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700704}
705
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700706void Dbg::UndoDebuggerSuspensions() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700707 Runtime::Current()->GetThreadList()->UndoDebuggerSuspensions();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700708}
709
Elliott Hughes88d63092013-01-09 09:55:54 -0800710std::string Dbg::GetClassName(JDWP::RefTypeId class_id) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700711 JDWP::JdwpError error;
712 mirror::Object* o = gRegistry->Get<mirror::Object*>(class_id, &error);
713 if (o == nullptr) {
714 if (error == JDWP::ERR_NONE) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700715 return "null";
Ian Rogersc0542af2014-09-03 16:16:56 -0700716 } else {
717 return StringPrintf("invalid object %p", reinterpret_cast<void*>(class_id));
718 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800719 }
720 if (!o->IsClass()) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700721 return StringPrintf("non-class %p", o); // This is only used for debugging output anyway.
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800722 }
Sebastien Hertz6995c602014-09-09 12:10:13 +0200723 return GetClassName(o->AsClass());
724}
725
726std::string Dbg::GetClassName(mirror::Class* klass) {
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +0200727 if (klass == nullptr) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700728 return "null";
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +0200729 }
Ian Rogers1ff3c982014-08-12 02:30:58 -0700730 std::string temp;
Sebastien Hertz6995c602014-09-09 12:10:13 +0200731 return DescriptorToName(klass->GetDescriptor(&temp));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700732}
733
Ian Rogersc0542af2014-09-03 16:16:56 -0700734JDWP::JdwpError Dbg::GetClassObject(JDWP::RefTypeId id, JDWP::ObjectId* class_object_id) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800735 JDWP::JdwpError status;
Ian Rogersc0542af2014-09-03 16:16:56 -0700736 mirror::Class* c = DecodeClass(id, &status);
737 if (c == nullptr) {
738 *class_object_id = 0;
Elliott Hughes436e3722012-02-17 20:01:47 -0800739 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800740 }
Ian Rogersc0542af2014-09-03 16:16:56 -0700741 *class_object_id = gRegistry->Add(c);
Elliott Hughes436e3722012-02-17 20:01:47 -0800742 return JDWP::ERR_NONE;
Elliott Hughes86964332012-02-15 19:37:42 -0800743}
744
Ian Rogersc0542af2014-09-03 16:16:56 -0700745JDWP::JdwpError Dbg::GetSuperclass(JDWP::RefTypeId id, JDWP::RefTypeId* superclass_id) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800746 JDWP::JdwpError status;
Ian Rogersc0542af2014-09-03 16:16:56 -0700747 mirror::Class* c = DecodeClass(id, &status);
748 if (c == nullptr) {
749 *superclass_id = 0;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800750 return status;
751 }
752 if (c->IsInterface()) {
753 // http://code.google.com/p/android/issues/detail?id=20856
Ian Rogersc0542af2014-09-03 16:16:56 -0700754 *superclass_id = 0;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800755 } else {
Ian Rogersc0542af2014-09-03 16:16:56 -0700756 *superclass_id = gRegistry->Add(c->GetSuperClass());
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800757 }
758 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700759}
760
Elliott Hughes436e3722012-02-17 20:01:47 -0800761JDWP::JdwpError Dbg::GetClassLoader(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700762 JDWP::JdwpError error;
Andreas Gampe7929a482015-12-30 19:33:49 -0800763 mirror::Class* c = DecodeClass(id, &error);
764 if (c == nullptr) {
765 return error;
Elliott Hughes436e3722012-02-17 20:01:47 -0800766 }
Andreas Gampe7929a482015-12-30 19:33:49 -0800767 expandBufAddObjectId(pReply, gRegistry->Add(c->GetClassLoader()));
Elliott Hughes436e3722012-02-17 20:01:47 -0800768 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700769}
770
Elliott Hughes436e3722012-02-17 20:01:47 -0800771JDWP::JdwpError Dbg::GetModifiers(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700772 JDWP::JdwpError error;
773 mirror::Class* c = DecodeClass(id, &error);
774 if (c == nullptr) {
775 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800776 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800777
778 uint32_t access_flags = c->GetAccessFlags() & kAccJavaFlagsMask;
779
Yevgeny Roubande34eea2014-02-15 01:06:03 +0700780 // Set ACC_SUPER. Dex files don't contain this flag but only classes are supposed to have it set,
781 // not interfaces.
Elliott Hughes436e3722012-02-17 20:01:47 -0800782 // Class.getModifiers doesn't return it, but JDWP does, so we set it here.
Yevgeny Roubande34eea2014-02-15 01:06:03 +0700783 if ((access_flags & kAccInterface) == 0) {
784 access_flags |= kAccSuper;
785 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800786
787 expandBufAdd4BE(pReply, access_flags);
788
789 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700790}
791
Ian Rogersc0542af2014-09-03 16:16:56 -0700792JDWP::JdwpError Dbg::GetMonitorInfo(JDWP::ObjectId object_id, JDWP::ExpandBuf* reply) {
793 JDWP::JdwpError error;
794 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
795 if (o == nullptr) {
Elliott Hughesf327e072013-01-09 16:01:26 -0800796 return JDWP::ERR_INVALID_OBJECT;
797 }
798
799 // Ensure all threads are suspended while we read objects' lock words.
800 Thread* self = Thread::Current();
Sebastien Hertz54263242014-03-19 18:16:50 +0100801 CHECK_EQ(self->GetState(), kRunnable);
Elliott Hughesf327e072013-01-09 16:01:26 -0800802
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700803 MonitorInfo monitor_info;
804 {
805 ScopedThreadSuspension sts(self, kSuspended);
Mathieu Chartier4f55e222015-09-04 13:26:21 -0700806 ScopedSuspendAll ssa(__FUNCTION__);
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700807 monitor_info = MonitorInfo(o);
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700808 }
Ian Rogersc0542af2014-09-03 16:16:56 -0700809 if (monitor_info.owner_ != nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700810 expandBufAddObjectId(reply, gRegistry->Add(monitor_info.owner_->GetPeer()));
Elliott Hughesf327e072013-01-09 16:01:26 -0800811 } else {
Ian Rogersc0542af2014-09-03 16:16:56 -0700812 expandBufAddObjectId(reply, gRegistry->Add(nullptr));
Elliott Hughesf327e072013-01-09 16:01:26 -0800813 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700814 expandBufAdd4BE(reply, monitor_info.entry_count_);
815 expandBufAdd4BE(reply, monitor_info.waiters_.size());
816 for (size_t i = 0; i < monitor_info.waiters_.size(); ++i) {
817 expandBufAddObjectId(reply, gRegistry->Add(monitor_info.waiters_[i]->GetPeer()));
Elliott Hughesf327e072013-01-09 16:01:26 -0800818 }
819 return JDWP::ERR_NONE;
820}
821
Elliott Hughes734b8c62013-01-11 15:32:45 -0800822JDWP::JdwpError Dbg::GetOwnedMonitors(JDWP::ObjectId thread_id,
Ian Rogersc0542af2014-09-03 16:16:56 -0700823 std::vector<JDWP::ObjectId>* monitors,
824 std::vector<uint32_t>* stack_depths) {
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800825 struct OwnedMonitorVisitor : public StackVisitor {
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700826 OwnedMonitorVisitor(Thread* thread, Context* context,
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -0700827 std::vector<JDWP::ObjectId>* monitor_vector,
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700828 std::vector<uint32_t>* stack_depth_vector)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700829 REQUIRES_SHARED(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +0100830 : StackVisitor(thread, context, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
831 current_stack_depth(0),
832 monitors(monitor_vector),
833 stack_depths(stack_depth_vector) {}
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800834
835 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
836 // annotalysis.
837 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
838 if (!GetMethod()->IsRuntimeMethod()) {
839 Monitor::VisitLocks(this, AppendOwnedMonitors, this);
Elliott Hughes734b8c62013-01-11 15:32:45 -0800840 ++current_stack_depth;
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800841 }
842 return true;
843 }
844
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -0700845 static void AppendOwnedMonitors(mirror::Object* owned_monitor, void* arg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700846 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers7a22fa62013-01-23 12:16:16 -0800847 OwnedMonitorVisitor* visitor = reinterpret_cast<OwnedMonitorVisitor*>(arg);
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -0700848 visitor->monitors->push_back(gRegistry->Add(owned_monitor));
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700849 visitor->stack_depths->push_back(visitor->current_stack_depth);
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800850 }
851
Elliott Hughes734b8c62013-01-11 15:32:45 -0800852 size_t current_stack_depth;
Ian Rogersc0542af2014-09-03 16:16:56 -0700853 std::vector<JDWP::ObjectId>* const monitors;
854 std::vector<uint32_t>* const stack_depths;
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800855 };
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800856
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700857 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz69206392015-04-07 15:54:25 +0200858 JDWP::JdwpError error;
859 Thread* thread = DecodeThread(soa, thread_id, &error);
860 if (thread == nullptr) {
861 return error;
862 }
863 if (!IsSuspendedForDebugger(soa, thread)) {
864 return JDWP::ERR_THREAD_NOT_SUSPENDED;
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700865 }
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -0700866 std::unique_ptr<Context> context(Context::Create());
Ian Rogersc0542af2014-09-03 16:16:56 -0700867 OwnedMonitorVisitor visitor(thread, context.get(), monitors, stack_depths);
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -0700868 visitor.WalkStack();
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800869 return JDWP::ERR_NONE;
870}
871
Sebastien Hertz52d131d2014-03-13 16:17:40 +0100872JDWP::JdwpError Dbg::GetContendedMonitor(JDWP::ObjectId thread_id,
Ian Rogersc0542af2014-09-03 16:16:56 -0700873 JDWP::ObjectId* contended_monitor) {
Elliott Hughesf9501702013-01-11 11:22:27 -0800874 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -0700875 *contended_monitor = 0;
Sebastien Hertz69206392015-04-07 15:54:25 +0200876 JDWP::JdwpError error;
877 Thread* thread = DecodeThread(soa, thread_id, &error);
878 if (thread == nullptr) {
879 return error;
Elliott Hughesf9501702013-01-11 11:22:27 -0800880 }
Sebastien Hertz69206392015-04-07 15:54:25 +0200881 if (!IsSuspendedForDebugger(soa, thread)) {
882 return JDWP::ERR_THREAD_NOT_SUSPENDED;
883 }
884 mirror::Object* contended_monitor_obj = Monitor::GetContendedMonitor(thread);
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700885 // Add() requires the thread_list_lock_ not held to avoid the lock
886 // level violation.
Ian Rogersc0542af2014-09-03 16:16:56 -0700887 *contended_monitor = gRegistry->Add(contended_monitor_obj);
Elliott Hughesf9501702013-01-11 11:22:27 -0800888 return JDWP::ERR_NONE;
889}
890
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800891JDWP::JdwpError Dbg::GetInstanceCounts(const std::vector<JDWP::RefTypeId>& class_ids,
Ian Rogersc0542af2014-09-03 16:16:56 -0700892 std::vector<uint64_t>* counts) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800893 gc::Heap* heap = Runtime::Current()->GetHeap();
894 heap->CollectGarbage(false);
Mathieu Chartiere8a3c572016-10-11 16:52:17 -0700895 VariableSizedHandleScope hs(Thread::Current());
Mathieu Chartier9d156d52016-10-06 17:44:26 -0700896 std::vector<Handle<mirror::Class>> classes;
Ian Rogersc0542af2014-09-03 16:16:56 -0700897 counts->clear();
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800898 for (size_t i = 0; i < class_ids.size(); ++i) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700899 JDWP::JdwpError error;
Mathieu Chartier9d156d52016-10-06 17:44:26 -0700900 ObjPtr<mirror::Class> c = DecodeClass(class_ids[i], &error);
Ian Rogersc0542af2014-09-03 16:16:56 -0700901 if (c == nullptr) {
902 return error;
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800903 }
Mathieu Chartier9d156d52016-10-06 17:44:26 -0700904 classes.push_back(hs.NewHandle(c));
Ian Rogersc0542af2014-09-03 16:16:56 -0700905 counts->push_back(0);
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800906 }
Ian Rogersc0542af2014-09-03 16:16:56 -0700907 heap->CountInstances(classes, false, &(*counts)[0]);
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800908 return JDWP::ERR_NONE;
909}
910
Ian Rogersc0542af2014-09-03 16:16:56 -0700911JDWP::JdwpError Dbg::GetInstances(JDWP::RefTypeId class_id, int32_t max_count,
912 std::vector<JDWP::ObjectId>* instances) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800913 gc::Heap* heap = Runtime::Current()->GetHeap();
914 // We only want reachable instances, so do a GC.
915 heap->CollectGarbage(false);
Ian Rogersc0542af2014-09-03 16:16:56 -0700916 JDWP::JdwpError error;
Mathieu Chartier9d156d52016-10-06 17:44:26 -0700917 ObjPtr<mirror::Class> c = DecodeClass(class_id, &error);
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800918 if (c == nullptr) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700919 return error;
Elliott Hughes3b78c942013-01-15 17:35:41 -0800920 }
Mathieu Chartier9d156d52016-10-06 17:44:26 -0700921 std::vector<ObjPtr<mirror::Object>> raw_instances;
922 StackHandleScope<1> hs(Thread::Current());
923 Runtime::Current()->GetHeap()->GetInstances(hs.NewHandle(c), max_count, raw_instances);
Elliott Hughes3b78c942013-01-15 17:35:41 -0800924 for (size_t i = 0; i < raw_instances.size(); ++i) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700925 instances->push_back(gRegistry->Add(raw_instances[i]));
Elliott Hughes3b78c942013-01-15 17:35:41 -0800926 }
927 return JDWP::ERR_NONE;
928}
929
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800930JDWP::JdwpError Dbg::GetReferringObjects(JDWP::ObjectId object_id, int32_t max_count,
Ian Rogersc0542af2014-09-03 16:16:56 -0700931 std::vector<JDWP::ObjectId>* referring_objects) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800932 gc::Heap* heap = Runtime::Current()->GetHeap();
933 heap->CollectGarbage(false);
Ian Rogersc0542af2014-09-03 16:16:56 -0700934 JDWP::JdwpError error;
Mathieu Chartier9d156d52016-10-06 17:44:26 -0700935 ObjPtr<mirror::Object> o = gRegistry->Get<mirror::Object*>(object_id, &error);
Ian Rogersc0542af2014-09-03 16:16:56 -0700936 if (o == nullptr) {
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800937 return JDWP::ERR_INVALID_OBJECT;
938 }
Mathieu Chartier9d156d52016-10-06 17:44:26 -0700939 std::vector<ObjPtr<mirror::Object>> raw_instances;
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800940 heap->GetReferringObjects(o, max_count, raw_instances);
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800941 for (size_t i = 0; i < raw_instances.size(); ++i) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700942 referring_objects->push_back(gRegistry->Add(raw_instances[i]));
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800943 }
944 return JDWP::ERR_NONE;
945}
946
Ian Rogersc0542af2014-09-03 16:16:56 -0700947JDWP::JdwpError Dbg::DisableCollection(JDWP::ObjectId object_id) {
948 JDWP::JdwpError error;
949 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
950 if (o == nullptr) {
Sebastien Hertze96060a2013-12-11 12:06:28 +0100951 return JDWP::ERR_INVALID_OBJECT;
952 }
Elliott Hughes64f574f2013-02-20 14:57:12 -0800953 gRegistry->DisableCollection(object_id);
954 return JDWP::ERR_NONE;
955}
956
Ian Rogersc0542af2014-09-03 16:16:56 -0700957JDWP::JdwpError Dbg::EnableCollection(JDWP::ObjectId object_id) {
958 JDWP::JdwpError error;
959 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
Sebastien Hertze96060a2013-12-11 12:06:28 +0100960 // Unlike DisableCollection, JDWP specs do not state an invalid object causes an error. The RI
961 // also ignores these cases and never return an error. However it's not obvious why this command
962 // should behave differently from DisableCollection and IsCollected commands. So let's be more
963 // strict and return an error if this happens.
Ian Rogersc0542af2014-09-03 16:16:56 -0700964 if (o == nullptr) {
Sebastien Hertze96060a2013-12-11 12:06:28 +0100965 return JDWP::ERR_INVALID_OBJECT;
966 }
Elliott Hughes64f574f2013-02-20 14:57:12 -0800967 gRegistry->EnableCollection(object_id);
968 return JDWP::ERR_NONE;
969}
970
Ian Rogersc0542af2014-09-03 16:16:56 -0700971JDWP::JdwpError Dbg::IsCollected(JDWP::ObjectId object_id, bool* is_collected) {
972 *is_collected = true;
Sebastien Hertz65637eb2014-01-10 17:40:02 +0100973 if (object_id == 0) {
974 // Null object id is invalid.
Sebastien Hertze96060a2013-12-11 12:06:28 +0100975 return JDWP::ERR_INVALID_OBJECT;
976 }
Sebastien Hertz65637eb2014-01-10 17:40:02 +0100977 // JDWP specs state an INVALID_OBJECT error is returned if the object ID is not valid. However
978 // the RI seems to ignore this and assume object has been collected.
Ian Rogersc0542af2014-09-03 16:16:56 -0700979 JDWP::JdwpError error;
980 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
981 if (o != nullptr) {
982 *is_collected = gRegistry->IsCollected(object_id);
Sebastien Hertz65637eb2014-01-10 17:40:02 +0100983 }
Elliott Hughes64f574f2013-02-20 14:57:12 -0800984 return JDWP::ERR_NONE;
985}
986
Ian Rogersc0542af2014-09-03 16:16:56 -0700987void Dbg::DisposeObject(JDWP::ObjectId object_id, uint32_t reference_count) {
Elliott Hughes64f574f2013-02-20 14:57:12 -0800988 gRegistry->DisposeObject(object_id, reference_count);
989}
990
Mathieu Chartier3398c782016-09-30 10:27:43 -0700991JDWP::JdwpTypeTag Dbg::GetTypeTag(ObjPtr<mirror::Class> klass) {
Sebastien Hertz4d8fd492014-03-28 16:29:41 +0100992 DCHECK(klass != nullptr);
993 if (klass->IsArrayClass()) {
994 return JDWP::TT_ARRAY;
995 } else if (klass->IsInterface()) {
996 return JDWP::TT_INTERFACE;
997 } else {
998 return JDWP::TT_CLASS;
999 }
1000}
1001
Elliott Hughes88d63092013-01-09 09:55:54 -08001002JDWP::JdwpError Dbg::GetReflectedType(JDWP::RefTypeId class_id, JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001003 JDWP::JdwpError error;
1004 mirror::Class* c = DecodeClass(class_id, &error);
1005 if (c == nullptr) {
1006 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001007 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001008
Sebastien Hertz4d8fd492014-03-28 16:29:41 +01001009 JDWP::JdwpTypeTag type_tag = GetTypeTag(c);
1010 expandBufAdd1(pReply, type_tag);
Elliott Hughes88d63092013-01-09 09:55:54 -08001011 expandBufAddRefTypeId(pReply, class_id);
Elliott Hughes436e3722012-02-17 20:01:47 -08001012 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001013}
1014
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001015// Get the complete list of reference classes (i.e. all classes except
1016// the primitive types).
1017// Returns a newly-allocated buffer full of RefTypeId values.
1018class ClassListCreator : public ClassVisitor {
1019 public:
1020 explicit ClassListCreator(std::vector<JDWP::RefTypeId>* classes) : classes_(classes) {}
1021
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001022 bool operator()(mirror::Class* c) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001023 if (!c->IsPrimitive()) {
1024 classes_->push_back(Dbg::GetObjectRegistry()->AddRefType(c));
1025 }
1026 return true;
1027 }
1028
1029 private:
1030 std::vector<JDWP::RefTypeId>* const classes_;
1031};
1032
Ian Rogersc0542af2014-09-03 16:16:56 -07001033void Dbg::GetClassList(std::vector<JDWP::RefTypeId>* classes) {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001034 ClassListCreator clc(classes);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001035 Runtime::Current()->GetClassLinker()->VisitClassesWithoutClassesLock(&clc);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001036}
1037
Ian Rogers1ff3c982014-08-12 02:30:58 -07001038JDWP::JdwpError Dbg::GetClassInfo(JDWP::RefTypeId class_id, JDWP::JdwpTypeTag* pTypeTag,
1039 uint32_t* pStatus, std::string* pDescriptor) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001040 JDWP::JdwpError error;
1041 mirror::Class* c = DecodeClass(class_id, &error);
1042 if (c == nullptr) {
1043 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001044 }
1045
Elliott Hughesa2155262011-11-16 16:26:58 -08001046 if (c->IsArrayClass()) {
1047 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
1048 *pTypeTag = JDWP::TT_ARRAY;
1049 } else {
1050 if (c->IsErroneous()) {
1051 *pStatus = JDWP::CS_ERROR;
1052 } else {
1053 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED | JDWP::CS_INITIALIZED;
1054 }
1055 *pTypeTag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
1056 }
1057
Ian Rogersc0542af2014-09-03 16:16:56 -07001058 if (pDescriptor != nullptr) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07001059 std::string temp;
1060 *pDescriptor = c->GetDescriptor(&temp);
Elliott Hughesa2155262011-11-16 16:26:58 -08001061 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001062 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001063}
1064
Ian Rogersc0542af2014-09-03 16:16:56 -07001065void Dbg::FindLoadedClassBySignature(const char* descriptor, std::vector<JDWP::RefTypeId>* ids) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001066 std::vector<mirror::Class*> classes;
Igor Murashkinb1d8c312015-08-04 11:18:43 -07001067 Runtime::Current()->GetClassLinker()->LookupClasses(descriptor, classes);
Ian Rogersc0542af2014-09-03 16:16:56 -07001068 ids->clear();
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001069 for (size_t i = 0; i < classes.size(); ++i) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001070 ids->push_back(gRegistry->Add(classes[i]));
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001071 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001072}
1073
Ian Rogersc0542af2014-09-03 16:16:56 -07001074JDWP::JdwpError Dbg::GetReferenceType(JDWP::ObjectId object_id, JDWP::ExpandBuf* pReply) {
1075 JDWP::JdwpError error;
1076 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
1077 if (o == nullptr) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001078 return JDWP::ERR_INVALID_OBJECT;
Elliott Hughes499c5132011-11-17 14:55:11 -08001079 }
Elliott Hughes2435a572012-02-17 16:07:41 -08001080
Sebastien Hertz4d8fd492014-03-28 16:29:41 +01001081 JDWP::JdwpTypeTag type_tag = GetTypeTag(o->GetClass());
Elliott Hughes64f574f2013-02-20 14:57:12 -08001082 JDWP::RefTypeId type_id = gRegistry->AddRefType(o->GetClass());
Elliott Hughes2435a572012-02-17 16:07:41 -08001083
1084 expandBufAdd1(pReply, type_tag);
1085 expandBufAddRefTypeId(pReply, type_id);
1086
1087 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001088}
1089
Ian Rogersfc0e94b2013-09-23 23:51:32 -07001090JDWP::JdwpError Dbg::GetSignature(JDWP::RefTypeId class_id, std::string* signature) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001091 JDWP::JdwpError error;
1092 mirror::Class* c = DecodeClass(class_id, &error);
1093 if (c == nullptr) {
1094 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001095 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07001096 std::string temp;
1097 *signature = c->GetDescriptor(&temp);
Elliott Hughes1fe7afb2012-02-13 17:23:03 -08001098 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001099}
1100
Ian Rogersc0542af2014-09-03 16:16:56 -07001101JDWP::JdwpError Dbg::GetSourceFile(JDWP::RefTypeId class_id, std::string* result) {
1102 JDWP::JdwpError error;
1103 mirror::Class* c = DecodeClass(class_id, &error);
Sebastien Hertz4206eb52014-06-05 10:15:45 +02001104 if (c == nullptr) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001105 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001106 }
Sebastien Hertz4206eb52014-06-05 10:15:45 +02001107 const char* source_file = c->GetSourceFile();
1108 if (source_file == nullptr) {
Sebastien Hertzb7054ba2014-03-13 11:52:31 +01001109 return JDWP::ERR_ABSENT_INFORMATION;
1110 }
Ian Rogersc0542af2014-09-03 16:16:56 -07001111 *result = source_file;
Elliott Hughes436e3722012-02-17 20:01:47 -08001112 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001113}
1114
Ian Rogersc0542af2014-09-03 16:16:56 -07001115JDWP::JdwpError Dbg::GetObjectTag(JDWP::ObjectId object_id, uint8_t* tag) {
Ian Rogers98379392014-02-24 16:53:16 -08001116 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07001117 JDWP::JdwpError error;
1118 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
1119 if (error != JDWP::ERR_NONE) {
1120 *tag = JDWP::JT_VOID;
1121 return error;
Elliott Hughes546b9862012-06-20 16:06:13 -07001122 }
Ian Rogersc0542af2014-09-03 16:16:56 -07001123 *tag = TagFromObject(soa, o);
Elliott Hughes546b9862012-06-20 16:06:13 -07001124 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001125}
1126
Elliott Hughesaed4be92011-12-02 16:16:23 -08001127size_t Dbg::GetTagWidth(JDWP::JdwpTag tag) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001128 switch (tag) {
1129 case JDWP::JT_VOID:
1130 return 0;
1131 case JDWP::JT_BYTE:
1132 case JDWP::JT_BOOLEAN:
1133 return 1;
1134 case JDWP::JT_CHAR:
1135 case JDWP::JT_SHORT:
1136 return 2;
1137 case JDWP::JT_FLOAT:
1138 case JDWP::JT_INT:
1139 return 4;
1140 case JDWP::JT_ARRAY:
1141 case JDWP::JT_OBJECT:
1142 case JDWP::JT_STRING:
1143 case JDWP::JT_THREAD:
1144 case JDWP::JT_THREAD_GROUP:
1145 case JDWP::JT_CLASS_LOADER:
1146 case JDWP::JT_CLASS_OBJECT:
1147 return sizeof(JDWP::ObjectId);
1148 case JDWP::JT_DOUBLE:
1149 case JDWP::JT_LONG:
1150 return 8;
1151 default:
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001152 LOG(FATAL) << "Unknown tag " << tag;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001153 return -1;
1154 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001155}
1156
Ian Rogersc0542af2014-09-03 16:16:56 -07001157JDWP::JdwpError Dbg::GetArrayLength(JDWP::ObjectId array_id, int32_t* length) {
1158 JDWP::JdwpError error;
1159 mirror::Array* a = DecodeNonNullArray(array_id, &error);
1160 if (a == nullptr) {
1161 return error;
Elliott Hughes24437992011-11-30 14:49:33 -08001162 }
Ian Rogersc0542af2014-09-03 16:16:56 -07001163 *length = a->GetLength();
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001164 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001165}
1166
Elliott Hughes88d63092013-01-09 09:55:54 -08001167JDWP::JdwpError Dbg::OutputArray(JDWP::ObjectId array_id, int offset, int count, JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001168 JDWP::JdwpError error;
1169 mirror::Array* a = DecodeNonNullArray(array_id, &error);
Ian Rogers98379392014-02-24 16:53:16 -08001170 if (a == nullptr) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001171 return error;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001172 }
Elliott Hughes24437992011-11-30 14:49:33 -08001173
1174 if (offset < 0 || count < 0 || offset > a->GetLength() || a->GetLength() - offset < count) {
1175 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001176 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughes24437992011-11-30 14:49:33 -08001177 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07001178 JDWP::JdwpTag element_tag = BasicTagFromClass(a->GetClass()->GetComponentType());
1179 expandBufAdd1(pReply, element_tag);
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001180 expandBufAdd4BE(pReply, count);
1181
Ian Rogers1ff3c982014-08-12 02:30:58 -07001182 if (IsPrimitiveTag(element_tag)) {
1183 size_t width = GetTagWidth(element_tag);
Elliott Hughes24437992011-11-30 14:49:33 -08001184 uint8_t* dst = expandBufAddSpace(pReply, count * width);
1185 if (width == 8) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001186 const uint64_t* src8 = reinterpret_cast<uint64_t*>(a->GetRawData(sizeof(uint64_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001187 for (int i = 0; i < count; ++i) JDWP::Write8BE(&dst, src8[offset + i]);
1188 } else if (width == 4) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001189 const uint32_t* src4 = reinterpret_cast<uint32_t*>(a->GetRawData(sizeof(uint32_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001190 for (int i = 0; i < count; ++i) JDWP::Write4BE(&dst, src4[offset + i]);
1191 } else if (width == 2) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001192 const uint16_t* src2 = reinterpret_cast<uint16_t*>(a->GetRawData(sizeof(uint16_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001193 for (int i = 0; i < count; ++i) JDWP::Write2BE(&dst, src2[offset + i]);
1194 } else {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001195 const uint8_t* src = reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint8_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001196 memcpy(dst, &src[offset * width], count * width);
1197 }
1198 } else {
Ian Rogers98379392014-02-24 16:53:16 -08001199 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001200 mirror::ObjectArray<mirror::Object>* oa = a->AsObjectArray<mirror::Object>();
Elliott Hughes24437992011-11-30 14:49:33 -08001201 for (int i = 0; i < count; ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001202 mirror::Object* element = oa->Get(offset + i);
Ian Rogers98379392014-02-24 16:53:16 -08001203 JDWP::JdwpTag specific_tag = (element != nullptr) ? TagFromObject(soa, element)
Ian Rogers1ff3c982014-08-12 02:30:58 -07001204 : element_tag;
Elliott Hughes24437992011-11-30 14:49:33 -08001205 expandBufAdd1(pReply, specific_tag);
1206 expandBufAddObjectId(pReply, gRegistry->Add(element));
1207 }
1208 }
1209
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001210 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001211}
1212
Ian Rogersef7d42f2014-01-06 12:55:46 -08001213template <typename T>
Ian Rogersc0542af2014-09-03 16:16:56 -07001214static void CopyArrayData(mirror::Array* a, JDWP::Request* src, int offset, int count)
Ian Rogersef7d42f2014-01-06 12:55:46 -08001215 NO_THREAD_SAFETY_ANALYSIS {
1216 // TODO: fix when annotalysis correctly handles non-member functions.
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001217 DCHECK(a->GetClass()->IsPrimitiveArray());
1218
Ian Rogersef7d42f2014-01-06 12:55:46 -08001219 T* dst = reinterpret_cast<T*>(a->GetRawData(sizeof(T), offset));
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001220 for (int i = 0; i < count; ++i) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001221 *dst++ = src->ReadValue(sizeof(T));
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001222 }
1223}
1224
Elliott Hughes88d63092013-01-09 09:55:54 -08001225JDWP::JdwpError Dbg::SetArrayElements(JDWP::ObjectId array_id, int offset, int count,
Ian Rogersc0542af2014-09-03 16:16:56 -07001226 JDWP::Request* request) {
1227 JDWP::JdwpError error;
1228 mirror::Array* dst = DecodeNonNullArray(array_id, &error);
1229 if (dst == nullptr) {
1230 return error;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001231 }
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001232
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001233 if (offset < 0 || count < 0 || offset > dst->GetLength() || dst->GetLength() - offset < count) {
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001234 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001235 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001236 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07001237 JDWP::JdwpTag element_tag = BasicTagFromClass(dst->GetClass()->GetComponentType());
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001238
Ian Rogers1ff3c982014-08-12 02:30:58 -07001239 if (IsPrimitiveTag(element_tag)) {
1240 size_t width = GetTagWidth(element_tag);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001241 if (width == 8) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001242 CopyArrayData<uint64_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001243 } else if (width == 4) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001244 CopyArrayData<uint32_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001245 } else if (width == 2) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001246 CopyArrayData<uint16_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001247 } else {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001248 CopyArrayData<uint8_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001249 }
1250 } else {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001251 mirror::ObjectArray<mirror::Object>* oa = dst->AsObjectArray<mirror::Object>();
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001252 for (int i = 0; i < count; ++i) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001253 JDWP::ObjectId id = request->ReadObjectId();
Ian Rogersc0542af2014-09-03 16:16:56 -07001254 mirror::Object* o = gRegistry->Get<mirror::Object*>(id, &error);
1255 if (error != JDWP::ERR_NONE) {
1256 return error;
Elliott Hughes436e3722012-02-17 20:01:47 -08001257 }
Sebastien Hertz2e1c16d2015-08-28 11:57:49 +02001258 // Check if the object's type is compatible with the array's type.
1259 if (o != nullptr && !o->InstanceOf(oa->GetClass()->GetComponentType())) {
1260 return JDWP::ERR_TYPE_MISMATCH;
1261 }
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001262 oa->Set<false>(offset + i, o);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001263 }
1264 }
1265
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001266 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001267}
1268
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001269JDWP::JdwpError Dbg::CreateString(const std::string& str, JDWP::ObjectId* new_string_id) {
1270 Thread* self = Thread::Current();
1271 mirror::String* new_string = mirror::String::AllocFromModifiedUtf8(self, str.c_str());
1272 if (new_string == nullptr) {
1273 DCHECK(self->IsExceptionPending());
1274 self->ClearException();
1275 LOG(ERROR) << "Could not allocate string";
1276 *new_string_id = 0;
1277 return JDWP::ERR_OUT_OF_MEMORY;
1278 }
1279 *new_string_id = gRegistry->Add(new_string);
1280 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001281}
1282
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001283JDWP::JdwpError Dbg::CreateObject(JDWP::RefTypeId class_id, JDWP::ObjectId* new_object_id) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001284 JDWP::JdwpError error;
1285 mirror::Class* c = DecodeClass(class_id, &error);
1286 if (c == nullptr) {
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001287 *new_object_id = 0;
Ian Rogersc0542af2014-09-03 16:16:56 -07001288 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001289 }
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001290 Thread* self = Thread::Current();
Sebastien Hertz56d5e502015-11-03 17:38:35 +01001291 mirror::Object* new_object;
1292 if (c->IsStringClass()) {
1293 // Special case for java.lang.String.
1294 gc::AllocatorType allocator_type = Runtime::Current()->GetHeap()->GetCurrentAllocator();
jessicahandojo3aaa37b2016-07-29 14:46:37 -07001295 new_object = mirror::String::AllocEmptyString<true>(self, allocator_type);
Sebastien Hertz56d5e502015-11-03 17:38:35 +01001296 } else {
1297 new_object = c->AllocObject(self);
1298 }
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001299 if (new_object == nullptr) {
1300 DCHECK(self->IsExceptionPending());
1301 self->ClearException();
1302 LOG(ERROR) << "Could not allocate object of type " << PrettyDescriptor(c);
1303 *new_object_id = 0;
1304 return JDWP::ERR_OUT_OF_MEMORY;
1305 }
1306 *new_object_id = gRegistry->Add(new_object);
Elliott Hughes436e3722012-02-17 20:01:47 -08001307 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001308}
1309
Elliott Hughesbf13d362011-12-08 15:51:37 -08001310/*
1311 * Used by Eclipse's "Display" view to evaluate "new byte[5]" to get "(byte[]) [0, 0, 0, 0, 0]".
1312 */
Elliott Hughes88d63092013-01-09 09:55:54 -08001313JDWP::JdwpError Dbg::CreateArrayObject(JDWP::RefTypeId array_class_id, uint32_t length,
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001314 JDWP::ObjectId* new_array_id) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001315 JDWP::JdwpError error;
1316 mirror::Class* c = DecodeClass(array_class_id, &error);
1317 if (c == nullptr) {
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001318 *new_array_id = 0;
Ian Rogersc0542af2014-09-03 16:16:56 -07001319 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001320 }
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001321 Thread* self = Thread::Current();
1322 gc::Heap* heap = Runtime::Current()->GetHeap();
1323 mirror::Array* new_array = mirror::Array::Alloc<true>(self, c, length,
1324 c->GetComponentSizeShift(),
1325 heap->GetCurrentAllocator());
1326 if (new_array == nullptr) {
1327 DCHECK(self->IsExceptionPending());
1328 self->ClearException();
1329 LOG(ERROR) << "Could not allocate array of type " << PrettyDescriptor(c);
1330 *new_array_id = 0;
1331 return JDWP::ERR_OUT_OF_MEMORY;
1332 }
1333 *new_array_id = gRegistry->Add(new_array);
Elliott Hughes436e3722012-02-17 20:01:47 -08001334 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001335}
1336
Mathieu Chartierc7853442015-03-27 14:35:38 -07001337JDWP::FieldId Dbg::ToFieldId(const ArtField* f) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001338 return static_cast<JDWP::FieldId>(reinterpret_cast<uintptr_t>(f));
Elliott Hughes03181a82011-11-17 17:22:21 -08001339}
1340
Alex Light6c8467f2015-11-20 15:03:26 -08001341static JDWP::MethodId ToMethodId(ArtMethod* m)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001342 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light6c8467f2015-11-20 15:03:26 -08001343 return static_cast<JDWP::MethodId>(reinterpret_cast<uintptr_t>(GetCanonicalMethod(m)));
Elliott Hughes03181a82011-11-17 17:22:21 -08001344}
1345
Mathieu Chartierc7853442015-03-27 14:35:38 -07001346static ArtField* FromFieldId(JDWP::FieldId fid)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001347 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001348 return reinterpret_cast<ArtField*>(static_cast<uintptr_t>(fid));
Elliott Hughesaed4be92011-12-02 16:16:23 -08001349}
1350
Mathieu Chartiere401d142015-04-22 13:56:20 -07001351static ArtMethod* FromMethodId(JDWP::MethodId mid)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001352 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001353 return reinterpret_cast<ArtMethod*>(static_cast<uintptr_t>(mid));
Elliott Hughes03181a82011-11-17 17:22:21 -08001354}
1355
Sebastien Hertz6995c602014-09-09 12:10:13 +02001356bool Dbg::MatchThread(JDWP::ObjectId expected_thread_id, Thread* event_thread) {
1357 CHECK(event_thread != nullptr);
1358 JDWP::JdwpError error;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001359 mirror::Object* expected_thread_peer = gRegistry->Get<mirror::Object*>(
1360 expected_thread_id, &error);
Sebastien Hertz6995c602014-09-09 12:10:13 +02001361 return expected_thread_peer == event_thread->GetPeer();
1362}
1363
1364bool Dbg::MatchLocation(const JDWP::JdwpLocation& expected_location,
1365 const JDWP::EventLocation& event_location) {
1366 if (expected_location.dex_pc != event_location.dex_pc) {
1367 return false;
1368 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001369 ArtMethod* m = FromMethodId(expected_location.method_id);
Sebastien Hertz6995c602014-09-09 12:10:13 +02001370 return m == event_location.method;
1371}
1372
Mathieu Chartier3398c782016-09-30 10:27:43 -07001373bool Dbg::MatchType(ObjPtr<mirror::Class> event_class, JDWP::RefTypeId class_id) {
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001374 if (event_class == nullptr) {
1375 return false;
1376 }
Sebastien Hertz6995c602014-09-09 12:10:13 +02001377 JDWP::JdwpError error;
Mathieu Chartier3398c782016-09-30 10:27:43 -07001378 ObjPtr<mirror::Class> expected_class = DecodeClass(class_id, &error);
Sebastien Hertz6995c602014-09-09 12:10:13 +02001379 CHECK(expected_class != nullptr);
1380 return expected_class->IsAssignableFrom(event_class);
1381}
1382
1383bool Dbg::MatchField(JDWP::RefTypeId expected_type_id, JDWP::FieldId expected_field_id,
Mathieu Chartierc7853442015-03-27 14:35:38 -07001384 ArtField* event_field) {
1385 ArtField* expected_field = FromFieldId(expected_field_id);
Sebastien Hertz6995c602014-09-09 12:10:13 +02001386 if (expected_field != event_field) {
1387 return false;
1388 }
1389 return Dbg::MatchType(event_field->GetDeclaringClass(), expected_type_id);
1390}
1391
1392bool Dbg::MatchInstance(JDWP::ObjectId expected_instance_id, mirror::Object* event_instance) {
1393 JDWP::JdwpError error;
1394 mirror::Object* modifier_instance = gRegistry->Get<mirror::Object*>(expected_instance_id, &error);
1395 return modifier_instance == event_instance;
1396}
1397
Mathieu Chartier90443472015-07-16 20:32:27 -07001398void Dbg::SetJdwpLocation(JDWP::JdwpLocation* location, ArtMethod* m, uint32_t dex_pc) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001399 if (m == nullptr) {
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001400 memset(location, 0, sizeof(*location));
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001401 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001402 mirror::Class* c = m->GetDeclaringClass();
Ian Rogersc0542af2014-09-03 16:16:56 -07001403 location->type_tag = GetTypeTag(c);
1404 location->class_id = gRegistry->AddRefType(c);
1405 location->method_id = ToMethodId(m);
1406 location->dex_pc = (m->IsNative() || m->IsProxyMethod()) ? static_cast<uint64_t>(-1) : dex_pc;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001407 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08001408}
1409
Ian Rogersc0542af2014-09-03 16:16:56 -07001410std::string Dbg::GetMethodName(JDWP::MethodId method_id) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001411 ArtMethod* m = FromMethodId(method_id);
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001412 if (m == nullptr) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001413 return "null";
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001414 }
Andreas Gampe542451c2016-07-26 09:02:02 -07001415 return m->GetInterfaceMethodIfProxy(kRuntimePointerSize)->GetName();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001416}
1417
Ian Rogersc0542af2014-09-03 16:16:56 -07001418std::string Dbg::GetFieldName(JDWP::FieldId field_id) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001419 ArtField* f = FromFieldId(field_id);
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001420 if (f == nullptr) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001421 return "null";
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001422 }
1423 return f->GetName();
Elliott Hughesa96836a2013-01-17 12:27:49 -08001424}
1425
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001426/*
1427 * Augment the access flags for synthetic methods and fields by setting
1428 * the (as described by the spec) "0xf0000000 bit". Also, strip out any
1429 * flags not specified by the Java programming language.
1430 */
1431static uint32_t MangleAccessFlags(uint32_t accessFlags) {
1432 accessFlags &= kAccJavaFlagsMask;
1433 if ((accessFlags & kAccSynthetic) != 0) {
1434 accessFlags |= 0xf0000000;
1435 }
1436 return accessFlags;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001437}
1438
Elliott Hughesdbb40792011-11-18 17:05:22 -08001439/*
Jeff Haob7cefc72013-11-14 14:51:09 -08001440 * Circularly shifts registers so that arguments come first. Debuggers
1441 * expect slots to begin with arguments, but dex code places them at
1442 * the end.
Elliott Hughesdbb40792011-11-18 17:05:22 -08001443 */
Mathieu Chartiere401d142015-04-22 13:56:20 -07001444static uint16_t MangleSlot(uint16_t slot, ArtMethod* m)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001445 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001446 const DexFile::CodeItem* code_item = m->GetCodeItem();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001447 if (code_item == nullptr) {
1448 // We should not get here for a method without code (native, proxy or abstract). Log it and
1449 // return the slot as is since all registers are arguments.
1450 LOG(WARNING) << "Trying to mangle slot for method without code " << PrettyMethod(m);
1451 return slot;
1452 }
Jeff Haob7cefc72013-11-14 14:51:09 -08001453 uint16_t ins_size = code_item->ins_size_;
1454 uint16_t locals_size = code_item->registers_size_ - ins_size;
1455 if (slot >= locals_size) {
1456 return slot - locals_size;
1457 } else {
1458 return slot + ins_size;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001459 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001460}
1461
Sebastien Hertzaef0c912016-08-08 10:20:28 +02001462static size_t GetMethodNumArgRegistersIncludingThis(ArtMethod* method)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001463 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertzaef0c912016-08-08 10:20:28 +02001464 uint32_t num_registers = ArtMethod::NumArgRegisters(method->GetShorty());
1465 if (!method->IsStatic()) {
1466 ++num_registers;
1467 }
1468 return num_registers;
1469}
1470
Jeff Haob7cefc72013-11-14 14:51:09 -08001471/*
1472 * Circularly shifts registers so that arguments come last. Reverts
1473 * slots to dex style argument placement.
1474 */
Mathieu Chartiere401d142015-04-22 13:56:20 -07001475static uint16_t DemangleSlot(uint16_t slot, ArtMethod* m, JDWP::JdwpError* error)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001476 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001477 const DexFile::CodeItem* code_item = m->GetCodeItem();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001478 if (code_item == nullptr) {
1479 // We should not get here for a method without code (native, proxy or abstract). Log it and
1480 // return the slot as is since all registers are arguments.
1481 LOG(WARNING) << "Trying to demangle slot for method without code " << PrettyMethod(m);
Sebastien Hertzaef0c912016-08-08 10:20:28 +02001482 uint16_t vreg_count = GetMethodNumArgRegistersIncludingThis(m);
Sebastien Hertzabbabc82015-03-26 08:47:47 +01001483 if (slot < vreg_count) {
1484 *error = JDWP::ERR_NONE;
1485 return slot;
1486 }
Jeff Haob7cefc72013-11-14 14:51:09 -08001487 } else {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01001488 if (slot < code_item->registers_size_) {
1489 uint16_t ins_size = code_item->ins_size_;
1490 uint16_t locals_size = code_item->registers_size_ - ins_size;
1491 *error = JDWP::ERR_NONE;
1492 return (slot < ins_size) ? slot + locals_size : slot - ins_size;
1493 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001494 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01001495
1496 // Slot is invalid in the method.
1497 LOG(ERROR) << "Invalid local slot " << slot << " for method " << PrettyMethod(m);
1498 *error = JDWP::ERR_INVALID_SLOT;
1499 return DexFile::kDexNoIndex16;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001500}
1501
Mathieu Chartier90443472015-07-16 20:32:27 -07001502JDWP::JdwpError Dbg::OutputDeclaredFields(JDWP::RefTypeId class_id, bool with_generic,
1503 JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001504 JDWP::JdwpError error;
1505 mirror::Class* c = DecodeClass(class_id, &error);
1506 if (c == nullptr) {
1507 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001508 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001509
1510 size_t instance_field_count = c->NumInstanceFields();
1511 size_t static_field_count = c->NumStaticFields();
1512
1513 expandBufAdd4BE(pReply, instance_field_count + static_field_count);
1514
1515 for (size_t i = 0; i < instance_field_count + static_field_count; ++i) {
Mathieu Chartier90443472015-07-16 20:32:27 -07001516 ArtField* f = (i < instance_field_count) ? c->GetInstanceField(i) :
1517 c->GetStaticField(i - instance_field_count);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001518 expandBufAddFieldId(pReply, ToFieldId(f));
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001519 expandBufAddUtf8String(pReply, f->GetName());
1520 expandBufAddUtf8String(pReply, f->GetTypeDescriptor());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001521 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001522 static const char genericSignature[1] = "";
1523 expandBufAddUtf8String(pReply, genericSignature);
1524 }
1525 expandBufAdd4BE(pReply, MangleAccessFlags(f->GetAccessFlags()));
1526 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001527 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001528}
1529
Elliott Hughes88d63092013-01-09 09:55:54 -08001530JDWP::JdwpError Dbg::OutputDeclaredMethods(JDWP::RefTypeId class_id, bool with_generic,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001531 JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001532 JDWP::JdwpError error;
1533 mirror::Class* c = DecodeClass(class_id, &error);
1534 if (c == nullptr) {
1535 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001536 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001537
Alex Light51a64d52015-12-17 13:55:59 -08001538 expandBufAdd4BE(pReply, c->NumMethods());
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001539
Mathieu Chartiere401d142015-04-22 13:56:20 -07001540 auto* cl = Runtime::Current()->GetClassLinker();
1541 auto ptr_size = cl->GetImagePointerSize();
Alex Light51a64d52015-12-17 13:55:59 -08001542 for (ArtMethod& m : c->GetMethods(ptr_size)) {
1543 expandBufAddMethodId(pReply, ToMethodId(&m));
Andreas Gampe542451c2016-07-26 09:02:02 -07001544 expandBufAddUtf8String(pReply, m.GetInterfaceMethodIfProxy(kRuntimePointerSize)->GetName());
1545 expandBufAddUtf8String(
1546 pReply, m.GetInterfaceMethodIfProxy(kRuntimePointerSize)->GetSignature().ToString());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001547 if (with_generic) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001548 const char* generic_signature = "";
1549 expandBufAddUtf8String(pReply, generic_signature);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001550 }
Alex Light51a64d52015-12-17 13:55:59 -08001551 expandBufAdd4BE(pReply, MangleAccessFlags(m.GetAccessFlags()));
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001552 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001553 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001554}
1555
Elliott Hughes88d63092013-01-09 09:55:54 -08001556JDWP::JdwpError Dbg::OutputDeclaredInterfaces(JDWP::RefTypeId class_id, JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001557 JDWP::JdwpError error;
Mathieu Chartierf8322842014-05-16 10:59:25 -07001558 Thread* self = Thread::Current();
1559 StackHandleScope<1> hs(self);
Ian Rogersc0542af2014-09-03 16:16:56 -07001560 Handle<mirror::Class> c(hs.NewHandle(DecodeClass(class_id, &error)));
Mathieu Chartierf8322842014-05-16 10:59:25 -07001561 if (c.Get() == nullptr) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001562 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001563 }
Mathieu Chartierf8322842014-05-16 10:59:25 -07001564 size_t interface_count = c->NumDirectInterfaces();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001565 expandBufAdd4BE(pReply, interface_count);
1566 for (size_t i = 0; i < interface_count; ++i) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07001567 expandBufAddRefTypeId(pReply,
1568 gRegistry->AddRefType(mirror::Class::GetDirectInterface(self, c, i)));
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001569 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001570 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001571}
1572
Ian Rogersc0542af2014-09-03 16:16:56 -07001573void Dbg::OutputLineTable(JDWP::RefTypeId, JDWP::MethodId method_id, JDWP::ExpandBuf* pReply) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001574 struct DebugCallbackContext {
1575 int numItems;
1576 JDWP::ExpandBuf* pReply;
1577
David Srbeckyb06e28e2015-12-10 13:15:00 +00001578 static bool Callback(void* context, const DexFile::PositionInfo& entry) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001579 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
David Srbeckyb06e28e2015-12-10 13:15:00 +00001580 expandBufAdd8BE(pContext->pReply, entry.address_);
1581 expandBufAdd4BE(pContext->pReply, entry.line_);
Elliott Hughes03181a82011-11-17 17:22:21 -08001582 pContext->numItems++;
Sebastien Hertzf2910ee2013-10-19 16:39:24 +02001583 return false;
Elliott Hughes03181a82011-11-17 17:22:21 -08001584 }
1585 };
Mathieu Chartiere401d142015-04-22 13:56:20 -07001586 ArtMethod* m = FromMethodId(method_id);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001587 const DexFile::CodeItem* code_item = m->GetCodeItem();
Elliott Hughes03181a82011-11-17 17:22:21 -08001588 uint64_t start, end;
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001589 if (code_item == nullptr) {
1590 DCHECK(m->IsNative() || m->IsProxyMethod());
Elliott Hughes03181a82011-11-17 17:22:21 -08001591 start = -1;
1592 end = -1;
1593 } else {
1594 start = 0;
jeffhao14f0db92012-12-14 17:50:42 -08001595 // Return the index of the last instruction
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001596 end = code_item->insns_size_in_code_units_ - 1;
Elliott Hughes03181a82011-11-17 17:22:21 -08001597 }
1598
1599 expandBufAdd8BE(pReply, start);
1600 expandBufAdd8BE(pReply, end);
1601
1602 // Add numLines later
1603 size_t numLinesOffset = expandBufGetLength(pReply);
1604 expandBufAdd4BE(pReply, 0);
1605
1606 DebugCallbackContext context;
1607 context.numItems = 0;
1608 context.pReply = pReply;
1609
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001610 if (code_item != nullptr) {
David Srbeckyb06e28e2015-12-10 13:15:00 +00001611 m->GetDexFile()->DecodeDebugPositionInfo(code_item, DebugCallbackContext::Callback, &context);
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001612 }
Elliott Hughes03181a82011-11-17 17:22:21 -08001613
1614 JDWP::Set4BE(expandBufGetBuffer(pReply) + numLinesOffset, context.numItems);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001615}
1616
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001617void Dbg::OutputVariableTable(JDWP::RefTypeId, JDWP::MethodId method_id, bool with_generic,
1618 JDWP::ExpandBuf* pReply) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001619 struct DebugCallbackContext {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001620 ArtMethod* method;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001621 JDWP::ExpandBuf* pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001622 size_t variable_count;
1623 bool with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001624
David Srbeckyb06e28e2015-12-10 13:15:00 +00001625 static void Callback(void* context, const DexFile::LocalInfo& entry)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001626 REQUIRES_SHARED(Locks::mutator_lock_) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001627 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
1628
David Srbeckyb06e28e2015-12-10 13:15:00 +00001629 uint16_t slot = entry.reg_;
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001630 VLOG(jdwp) << StringPrintf(" %2zd: %d(%d) '%s' '%s' '%s' actual slot=%d mangled slot=%d",
David Srbeckyb06e28e2015-12-10 13:15:00 +00001631 pContext->variable_count, entry.start_address_,
1632 entry.end_address_ - entry.start_address_,
1633 entry.name_, entry.descriptor_, entry.signature_, slot,
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001634 MangleSlot(slot, pContext->method));
Elliott Hughesdbb40792011-11-18 17:05:22 -08001635
Jeff Haob7cefc72013-11-14 14:51:09 -08001636 slot = MangleSlot(slot, pContext->method);
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001637
David Srbeckyb06e28e2015-12-10 13:15:00 +00001638 expandBufAdd8BE(pContext->pReply, entry.start_address_);
1639 expandBufAddUtf8String(pContext->pReply, entry.name_);
1640 expandBufAddUtf8String(pContext->pReply, entry.descriptor_);
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001641 if (pContext->with_generic) {
David Srbeckyb06e28e2015-12-10 13:15:00 +00001642 expandBufAddUtf8String(pContext->pReply, entry.signature_);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001643 }
David Srbeckyb06e28e2015-12-10 13:15:00 +00001644 expandBufAdd4BE(pContext->pReply, entry.end_address_- entry.start_address_);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001645 expandBufAdd4BE(pContext->pReply, slot);
1646
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001647 ++pContext->variable_count;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001648 }
1649 };
Mathieu Chartiere401d142015-04-22 13:56:20 -07001650 ArtMethod* m = FromMethodId(method_id);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001651
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001652 // arg_count considers doubles and longs to take 2 units.
1653 // variable_count considers everything to take 1 unit.
Sebastien Hertzaef0c912016-08-08 10:20:28 +02001654 expandBufAdd4BE(pReply, GetMethodNumArgRegistersIncludingThis(m));
Elliott Hughesdbb40792011-11-18 17:05:22 -08001655
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001656 // We don't know the total number of variables yet, so leave a blank and update it later.
1657 size_t variable_count_offset = expandBufGetLength(pReply);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001658 expandBufAdd4BE(pReply, 0);
1659
1660 DebugCallbackContext context;
Jeff Haob7cefc72013-11-14 14:51:09 -08001661 context.method = m;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001662 context.pReply = pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001663 context.variable_count = 0;
1664 context.with_generic = with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001665
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001666 const DexFile::CodeItem* code_item = m->GetCodeItem();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001667 if (code_item != nullptr) {
David Srbeckyb06e28e2015-12-10 13:15:00 +00001668 m->GetDexFile()->DecodeDebugLocalInfo(
1669 code_item, m->IsStatic(), m->GetDexMethodIndex(), DebugCallbackContext::Callback,
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001670 &context);
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001671 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001672
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001673 JDWP::Set4BE(expandBufGetBuffer(pReply) + variable_count_offset, context.variable_count);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001674}
1675
Jeff Hao579b0242013-11-18 13:16:49 -08001676void Dbg::OutputMethodReturnValue(JDWP::MethodId method_id, const JValue* return_value,
1677 JDWP::ExpandBuf* pReply) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001678 ArtMethod* m = FromMethodId(method_id);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001679 JDWP::JdwpTag tag = BasicTagFromDescriptor(m->GetShorty());
Jeff Hao579b0242013-11-18 13:16:49 -08001680 OutputJValue(tag, return_value, pReply);
1681}
1682
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02001683void Dbg::OutputFieldValue(JDWP::FieldId field_id, const JValue* field_value,
1684 JDWP::ExpandBuf* pReply) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001685 ArtField* f = FromFieldId(field_id);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001686 JDWP::JdwpTag tag = BasicTagFromDescriptor(f->GetTypeDescriptor());
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02001687 OutputJValue(tag, field_value, pReply);
1688}
1689
Elliott Hughes9777ba22013-01-17 09:04:19 -08001690JDWP::JdwpError Dbg::GetBytecodes(JDWP::RefTypeId, JDWP::MethodId method_id,
Ian Rogersc0542af2014-09-03 16:16:56 -07001691 std::vector<uint8_t>* bytecodes) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001692 ArtMethod* m = FromMethodId(method_id);
Ian Rogersc0542af2014-09-03 16:16:56 -07001693 if (m == nullptr) {
Elliott Hughes9777ba22013-01-17 09:04:19 -08001694 return JDWP::ERR_INVALID_METHODID;
1695 }
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001696 const DexFile::CodeItem* code_item = m->GetCodeItem();
Elliott Hughes9777ba22013-01-17 09:04:19 -08001697 size_t byte_count = code_item->insns_size_in_code_units_ * 2;
1698 const uint8_t* begin = reinterpret_cast<const uint8_t*>(code_item->insns_);
1699 const uint8_t* end = begin + byte_count;
1700 for (const uint8_t* p = begin; p != end; ++p) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001701 bytecodes->push_back(*p);
Elliott Hughes9777ba22013-01-17 09:04:19 -08001702 }
1703 return JDWP::ERR_NONE;
1704}
1705
Elliott Hughes88d63092013-01-09 09:55:54 -08001706JDWP::JdwpTag Dbg::GetFieldBasicTag(JDWP::FieldId field_id) {
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001707 return BasicTagFromDescriptor(FromFieldId(field_id)->GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001708}
1709
Elliott Hughes88d63092013-01-09 09:55:54 -08001710JDWP::JdwpTag Dbg::GetStaticFieldBasicTag(JDWP::FieldId field_id) {
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001711 return BasicTagFromDescriptor(FromFieldId(field_id)->GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001712}
1713
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001714static JValue GetArtFieldValue(ArtField* f, mirror::Object* o)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001715 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001716 Primitive::Type fieldType = f->GetTypeAsPrimitiveType();
1717 JValue field_value;
1718 switch (fieldType) {
1719 case Primitive::kPrimBoolean:
1720 field_value.SetZ(f->GetBoolean(o));
1721 return field_value;
1722
1723 case Primitive::kPrimByte:
1724 field_value.SetB(f->GetByte(o));
1725 return field_value;
1726
1727 case Primitive::kPrimChar:
1728 field_value.SetC(f->GetChar(o));
1729 return field_value;
1730
1731 case Primitive::kPrimShort:
1732 field_value.SetS(f->GetShort(o));
1733 return field_value;
1734
1735 case Primitive::kPrimInt:
1736 case Primitive::kPrimFloat:
1737 // Int and Float must be treated as 32-bit values in JDWP.
1738 field_value.SetI(f->GetInt(o));
1739 return field_value;
1740
1741 case Primitive::kPrimLong:
1742 case Primitive::kPrimDouble:
1743 // Long and Double must be treated as 64-bit values in JDWP.
1744 field_value.SetJ(f->GetLong(o));
1745 return field_value;
1746
1747 case Primitive::kPrimNot:
Mathieu Chartier1cc62e42016-10-03 18:01:28 -07001748 field_value.SetL(f->GetObject(o).Ptr());
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001749 return field_value;
1750
1751 case Primitive::kPrimVoid:
1752 LOG(FATAL) << "Attempt to read from field of type 'void'";
1753 UNREACHABLE();
1754 }
1755 LOG(FATAL) << "Attempt to read from field of unknown type";
1756 UNREACHABLE();
1757}
1758
Elliott Hughes88d63092013-01-09 09:55:54 -08001759static JDWP::JdwpError GetFieldValueImpl(JDWP::RefTypeId ref_type_id, JDWP::ObjectId object_id,
1760 JDWP::FieldId field_id, JDWP::ExpandBuf* pReply,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001761 bool is_static)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001762 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001763 JDWP::JdwpError error;
1764 mirror::Class* c = DecodeClass(ref_type_id, &error);
1765 if (ref_type_id != 0 && c == nullptr) {
1766 return error;
Elliott Hughes0cf74332012-02-23 23:14:00 -08001767 }
1768
Jeff Haode19a252016-09-14 15:56:35 -07001769 Thread* self = Thread::Current();
1770 StackHandleScope<2> hs(self);
1771 MutableHandle<mirror::Object>
1772 o(hs.NewHandle(Dbg::GetObjectRegistry()->Get<mirror::Object*>(object_id, &error)));
1773 if ((!is_static && o.Get() == nullptr) || error != JDWP::ERR_NONE) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001774 return JDWP::ERR_INVALID_OBJECT;
1775 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001776 ArtField* f = FromFieldId(field_id);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001777
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001778 mirror::Class* receiver_class = c;
Jeff Haode19a252016-09-14 15:56:35 -07001779 if (receiver_class == nullptr && o.Get() != nullptr) {
Elliott Hughes0cf74332012-02-23 23:14:00 -08001780 receiver_class = o->GetClass();
1781 }
Jeff Haode19a252016-09-14 15:56:35 -07001782
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001783 // TODO: should we give up now if receiver_class is null?
Ian Rogersc0542af2014-09-03 16:16:56 -07001784 if (receiver_class != nullptr && !f->GetDeclaringClass()->IsAssignableFrom(receiver_class)) {
Elliott Hughes0cf74332012-02-23 23:14:00 -08001785 LOG(INFO) << "ERR_INVALID_FIELDID: " << PrettyField(f) << " " << PrettyClass(receiver_class);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001786 return JDWP::ERR_INVALID_FIELDID;
1787 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001788
Jeff Haode19a252016-09-14 15:56:35 -07001789 // Ensure the field's class is initialized.
1790 Handle<mirror::Class> klass(hs.NewHandle(f->GetDeclaringClass()));
1791 if (!Runtime::Current()->GetClassLinker()->EnsureInitialized(self, klass, true, false)) {
1792 LOG(WARNING) << "Not able to initialize class for SetValues: " << PrettyClass(klass.Get());
1793 }
1794
Elliott Hughes0cf74332012-02-23 23:14:00 -08001795 // The RI only enforces the static/non-static mismatch in one direction.
1796 // TODO: should we change the tests and check both?
1797 if (is_static) {
1798 if (!f->IsStatic()) {
1799 return JDWP::ERR_INVALID_FIELDID;
1800 }
1801 } else {
1802 if (f->IsStatic()) {
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001803 LOG(WARNING) << "Ignoring non-nullptr receiver for ObjectReference.GetValues"
1804 << " on static field " << PrettyField(f);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001805 }
1806 }
jeffhao0dfbb7e2012-11-28 15:26:03 -08001807 if (f->IsStatic()) {
Jeff Haode19a252016-09-14 15:56:35 -07001808 o.Assign(f->GetDeclaringClass());
jeffhao0dfbb7e2012-11-28 15:26:03 -08001809 }
Elliott Hughes0cf74332012-02-23 23:14:00 -08001810
Jeff Haode19a252016-09-14 15:56:35 -07001811 JValue field_value(GetArtFieldValue(f, o.Get()));
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001812 JDWP::JdwpTag tag = BasicTagFromDescriptor(f->GetTypeDescriptor());
Jeff Hao579b0242013-11-18 13:16:49 -08001813 Dbg::OutputJValue(tag, &field_value, pReply);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001814 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001815}
1816
Elliott Hughes88d63092013-01-09 09:55:54 -08001817JDWP::JdwpError Dbg::GetFieldValue(JDWP::ObjectId object_id, JDWP::FieldId field_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001818 JDWP::ExpandBuf* pReply) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001819 return GetFieldValueImpl(0, object_id, field_id, pReply, false);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001820}
1821
Ian Rogersc0542af2014-09-03 16:16:56 -07001822JDWP::JdwpError Dbg::GetStaticFieldValue(JDWP::RefTypeId ref_type_id, JDWP::FieldId field_id,
1823 JDWP::ExpandBuf* pReply) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001824 return GetFieldValueImpl(ref_type_id, 0, field_id, pReply, true);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001825}
1826
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001827static JDWP::JdwpError SetArtFieldValue(ArtField* f, mirror::Object* o, uint64_t value, int width)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001828 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001829 Primitive::Type fieldType = f->GetTypeAsPrimitiveType();
1830 // Debugging only happens at runtime so we know we are not running in a transaction.
1831 static constexpr bool kNoTransactionMode = false;
1832 switch (fieldType) {
1833 case Primitive::kPrimBoolean:
1834 CHECK_EQ(width, 1);
1835 f->SetBoolean<kNoTransactionMode>(o, static_cast<uint8_t>(value));
1836 return JDWP::ERR_NONE;
1837
1838 case Primitive::kPrimByte:
1839 CHECK_EQ(width, 1);
1840 f->SetByte<kNoTransactionMode>(o, static_cast<uint8_t>(value));
1841 return JDWP::ERR_NONE;
1842
1843 case Primitive::kPrimChar:
1844 CHECK_EQ(width, 2);
1845 f->SetChar<kNoTransactionMode>(o, static_cast<uint16_t>(value));
1846 return JDWP::ERR_NONE;
1847
1848 case Primitive::kPrimShort:
1849 CHECK_EQ(width, 2);
1850 f->SetShort<kNoTransactionMode>(o, static_cast<int16_t>(value));
1851 return JDWP::ERR_NONE;
1852
1853 case Primitive::kPrimInt:
1854 case Primitive::kPrimFloat:
1855 CHECK_EQ(width, 4);
1856 // Int and Float must be treated as 32-bit values in JDWP.
1857 f->SetInt<kNoTransactionMode>(o, static_cast<int32_t>(value));
1858 return JDWP::ERR_NONE;
1859
1860 case Primitive::kPrimLong:
1861 case Primitive::kPrimDouble:
1862 CHECK_EQ(width, 8);
1863 // Long and Double must be treated as 64-bit values in JDWP.
1864 f->SetLong<kNoTransactionMode>(o, value);
1865 return JDWP::ERR_NONE;
1866
1867 case Primitive::kPrimNot: {
1868 JDWP::JdwpError error;
1869 mirror::Object* v = Dbg::GetObjectRegistry()->Get<mirror::Object*>(value, &error);
1870 if (error != JDWP::ERR_NONE) {
1871 return JDWP::ERR_INVALID_OBJECT;
1872 }
1873 if (v != nullptr) {
Mathieu Chartier3398c782016-09-30 10:27:43 -07001874 ObjPtr<mirror::Class> field_type;
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001875 {
1876 StackHandleScope<2> hs(Thread::Current());
1877 HandleWrapper<mirror::Object> h_v(hs.NewHandleWrapper(&v));
1878 HandleWrapper<mirror::Object> h_o(hs.NewHandleWrapper(&o));
1879 field_type = f->GetType<true>();
1880 }
1881 if (!field_type->IsAssignableFrom(v->GetClass())) {
1882 return JDWP::ERR_INVALID_OBJECT;
1883 }
1884 }
1885 f->SetObject<kNoTransactionMode>(o, v);
1886 return JDWP::ERR_NONE;
1887 }
1888
1889 case Primitive::kPrimVoid:
1890 LOG(FATAL) << "Attempt to write to field of type 'void'";
1891 UNREACHABLE();
1892 }
1893 LOG(FATAL) << "Attempt to write to field of unknown type";
1894 UNREACHABLE();
1895}
1896
Elliott Hughes88d63092013-01-09 09:55:54 -08001897static JDWP::JdwpError SetFieldValueImpl(JDWP::ObjectId object_id, JDWP::FieldId field_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001898 uint64_t value, int width, bool is_static)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001899 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001900 JDWP::JdwpError error;
Jeff Haode19a252016-09-14 15:56:35 -07001901 Thread* self = Thread::Current();
1902 StackHandleScope<2> hs(self);
1903 MutableHandle<mirror::Object>
1904 o(hs.NewHandle(Dbg::GetObjectRegistry()->Get<mirror::Object*>(object_id, &error)));
1905 if ((!is_static && o.Get() == nullptr) || error != JDWP::ERR_NONE) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001906 return JDWP::ERR_INVALID_OBJECT;
1907 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001908 ArtField* f = FromFieldId(field_id);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001909
Jeff Haode19a252016-09-14 15:56:35 -07001910 // Ensure the field's class is initialized.
1911 Handle<mirror::Class> klass(hs.NewHandle(f->GetDeclaringClass()));
1912 if (!Runtime::Current()->GetClassLinker()->EnsureInitialized(self, klass, true, false)) {
1913 LOG(WARNING) << "Not able to initialize class for SetValues: " << PrettyClass(klass.Get());
1914 }
1915
Elliott Hughes0cf74332012-02-23 23:14:00 -08001916 // The RI only enforces the static/non-static mismatch in one direction.
1917 // TODO: should we change the tests and check both?
1918 if (is_static) {
1919 if (!f->IsStatic()) {
1920 return JDWP::ERR_INVALID_FIELDID;
1921 }
1922 } else {
1923 if (f->IsStatic()) {
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001924 LOG(WARNING) << "Ignoring non-nullptr receiver for ObjectReference.SetValues"
1925 << " on static field " << PrettyField(f);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001926 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001927 }
jeffhao0dfbb7e2012-11-28 15:26:03 -08001928 if (f->IsStatic()) {
Jeff Haode19a252016-09-14 15:56:35 -07001929 o.Assign(f->GetDeclaringClass());
jeffhao0dfbb7e2012-11-28 15:26:03 -08001930 }
Jeff Haode19a252016-09-14 15:56:35 -07001931 return SetArtFieldValue(f, o.Get(), value, width);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001932}
1933
Elliott Hughes88d63092013-01-09 09:55:54 -08001934JDWP::JdwpError Dbg::SetFieldValue(JDWP::ObjectId object_id, JDWP::FieldId field_id, uint64_t value,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001935 int width) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001936 return SetFieldValueImpl(object_id, field_id, value, width, false);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001937}
1938
Elliott Hughes88d63092013-01-09 09:55:54 -08001939JDWP::JdwpError Dbg::SetStaticFieldValue(JDWP::FieldId field_id, uint64_t value, int width) {
1940 return SetFieldValueImpl(0, field_id, value, width, true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001941}
1942
Sebastien Hertzb0b0b492014-09-15 11:27:27 +02001943JDWP::JdwpError Dbg::StringToUtf8(JDWP::ObjectId string_id, std::string* str) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001944 JDWP::JdwpError error;
Sebastien Hertzb0b0b492014-09-15 11:27:27 +02001945 mirror::Object* obj = gRegistry->Get<mirror::Object*>(string_id, &error);
1946 if (error != JDWP::ERR_NONE) {
1947 return error;
1948 }
1949 if (obj == nullptr) {
1950 return JDWP::ERR_INVALID_OBJECT;
1951 }
1952 {
1953 ScopedObjectAccessUnchecked soa(Thread::Current());
Mathieu Chartier0795f232016-09-27 18:43:30 -07001954 ObjPtr<mirror::Class> java_lang_String =
1955 soa.Decode<mirror::Class>(WellKnownClasses::java_lang_String);
Sebastien Hertzb0b0b492014-09-15 11:27:27 +02001956 if (!java_lang_String->IsAssignableFrom(obj->GetClass())) {
1957 // This isn't a string.
1958 return JDWP::ERR_INVALID_STRING;
1959 }
1960 }
1961 *str = obj->AsString()->ToModifiedUtf8();
1962 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001963}
1964
Jeff Hao579b0242013-11-18 13:16:49 -08001965void Dbg::OutputJValue(JDWP::JdwpTag tag, const JValue* return_value, JDWP::ExpandBuf* pReply) {
1966 if (IsPrimitiveTag(tag)) {
1967 expandBufAdd1(pReply, tag);
1968 if (tag == JDWP::JT_BOOLEAN || tag == JDWP::JT_BYTE) {
1969 expandBufAdd1(pReply, return_value->GetI());
1970 } else if (tag == JDWP::JT_CHAR || tag == JDWP::JT_SHORT) {
1971 expandBufAdd2BE(pReply, return_value->GetI());
1972 } else if (tag == JDWP::JT_FLOAT || tag == JDWP::JT_INT) {
1973 expandBufAdd4BE(pReply, return_value->GetI());
1974 } else if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
1975 expandBufAdd8BE(pReply, return_value->GetJ());
1976 } else {
1977 CHECK_EQ(tag, JDWP::JT_VOID);
1978 }
1979 } else {
Ian Rogers98379392014-02-24 16:53:16 -08001980 ScopedObjectAccessUnchecked soa(Thread::Current());
Jeff Hao579b0242013-11-18 13:16:49 -08001981 mirror::Object* value = return_value->GetL();
Ian Rogers98379392014-02-24 16:53:16 -08001982 expandBufAdd1(pReply, TagFromObject(soa, value));
Jeff Hao579b0242013-11-18 13:16:49 -08001983 expandBufAddObjectId(pReply, gRegistry->Add(value));
1984 }
1985}
1986
Ian Rogersc0542af2014-09-03 16:16:56 -07001987JDWP::JdwpError Dbg::GetThreadName(JDWP::ObjectId thread_id, std::string* name) {
jeffhaoa77f0f62012-12-05 17:19:31 -08001988 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07001989 JDWP::JdwpError error;
Roland Levillain4b8f1ec2015-08-26 18:34:03 +01001990 DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08001991 if (error != JDWP::ERR_NONE && error != JDWP::ERR_THREAD_NOT_ALIVE) {
1992 return error;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001993 }
Elliott Hughes221229c2013-01-08 18:17:50 -08001994
1995 // We still need to report the zombie threads' names, so we can't just call Thread::GetThreadName.
Ian Rogersc0542af2014-09-03 16:16:56 -07001996 mirror::Object* thread_object = gRegistry->Get<mirror::Object*>(thread_id, &error);
1997 CHECK(thread_object != nullptr) << error;
Mathieu Chartierc7853442015-03-27 14:35:38 -07001998 ArtField* java_lang_Thread_name_field =
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001999 soa.DecodeField(WellKnownClasses::java_lang_Thread_name);
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07002000 ObjPtr<mirror::String> s(java_lang_Thread_name_field->GetObject(thread_object)->AsString());
Ian Rogersc0542af2014-09-03 16:16:56 -07002001 if (s != nullptr) {
2002 *name = s->ToModifiedUtf8();
Elliott Hughes221229c2013-01-08 18:17:50 -08002003 }
2004 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002005}
2006
Elliott Hughes221229c2013-01-08 18:17:50 -08002007JDWP::JdwpError Dbg::GetThreadGroup(JDWP::ObjectId thread_id, JDWP::ExpandBuf* pReply) {
Sebastien Hertza06430c2014-09-15 19:21:30 +02002008 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002009 JDWP::JdwpError error;
2010 mirror::Object* thread_object = gRegistry->Get<mirror::Object*>(thread_id, &error);
2011 if (error != JDWP::ERR_NONE) {
Elliott Hughes2435a572012-02-17 16:07:41 -08002012 return JDWP::ERR_INVALID_OBJECT;
2013 }
Mathieu Chartier268764d2016-09-13 12:09:38 -07002014 ScopedAssertNoThreadSuspension ants("Debugger: GetThreadGroup");
Elliott Hughes2435a572012-02-17 16:07:41 -08002015 // Okay, so it's an object, but is it actually a thread?
Roland Levillain4b8f1ec2015-08-26 18:34:03 +01002016 DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002017 if (error == JDWP::ERR_THREAD_NOT_ALIVE) {
2018 // Zombie threads are in the null group.
2019 expandBufAddObjectId(pReply, JDWP::ObjectId(0));
Sebastien Hertz52d131d2014-03-13 16:17:40 +01002020 error = JDWP::ERR_NONE;
2021 } else if (error == JDWP::ERR_NONE) {
Mathieu Chartier0795f232016-09-27 18:43:30 -07002022 ObjPtr<mirror::Class> c = soa.Decode<mirror::Class>(WellKnownClasses::java_lang_Thread);
Sebastien Hertz52d131d2014-03-13 16:17:40 +01002023 CHECK(c != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07002024 ArtField* f = soa.DecodeField(WellKnownClasses::java_lang_Thread_group);
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07002025 CHECK(f != nullptr);
Mathieu Chartier3398c782016-09-30 10:27:43 -07002026 ObjPtr<mirror::Object> group = f->GetObject(thread_object);
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07002027 CHECK(group != nullptr);
Sebastien Hertz52d131d2014-03-13 16:17:40 +01002028 JDWP::ObjectId thread_group_id = gRegistry->Add(group);
2029 expandBufAddObjectId(pReply, thread_group_id);
Elliott Hughes221229c2013-01-08 18:17:50 -08002030 }
Sebastien Hertz52d131d2014-03-13 16:17:40 +01002031 return error;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002032}
2033
Sebastien Hertza06430c2014-09-15 19:21:30 +02002034static mirror::Object* DecodeThreadGroup(ScopedObjectAccessUnchecked& soa,
2035 JDWP::ObjectId thread_group_id, JDWP::JdwpError* error)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002036 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz6995c602014-09-09 12:10:13 +02002037 mirror::Object* thread_group = Dbg::GetObjectRegistry()->Get<mirror::Object*>(thread_group_id,
2038 error);
Sebastien Hertza06430c2014-09-15 19:21:30 +02002039 if (*error != JDWP::ERR_NONE) {
2040 return nullptr;
2041 }
2042 if (thread_group == nullptr) {
2043 *error = JDWP::ERR_INVALID_OBJECT;
2044 return nullptr;
2045 }
Mathieu Chartier0795f232016-09-27 18:43:30 -07002046 ObjPtr<mirror::Class> c =
2047 soa.Decode<mirror::Class>(WellKnownClasses::java_lang_ThreadGroup);
Ian Rogers98379392014-02-24 16:53:16 -08002048 CHECK(c != nullptr);
Sebastien Hertza06430c2014-09-15 19:21:30 +02002049 if (!c->IsAssignableFrom(thread_group->GetClass())) {
2050 // This is not a java.lang.ThreadGroup.
2051 *error = JDWP::ERR_INVALID_THREAD_GROUP;
2052 return nullptr;
2053 }
2054 *error = JDWP::ERR_NONE;
2055 return thread_group;
2056}
2057
2058JDWP::JdwpError Dbg::GetThreadGroupName(JDWP::ObjectId thread_group_id, JDWP::ExpandBuf* pReply) {
2059 ScopedObjectAccessUnchecked soa(Thread::Current());
2060 JDWP::JdwpError error;
2061 mirror::Object* thread_group = DecodeThreadGroup(soa, thread_group_id, &error);
2062 if (error != JDWP::ERR_NONE) {
2063 return error;
2064 }
Mathieu Chartier268764d2016-09-13 12:09:38 -07002065 ScopedAssertNoThreadSuspension ants("Debugger: GetThreadGroupName");
Mathieu Chartierc7853442015-03-27 14:35:38 -07002066 ArtField* f = soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_name);
Ian Rogersc0542af2014-09-03 16:16:56 -07002067 CHECK(f != nullptr);
Mathieu Chartier3398c782016-09-30 10:27:43 -07002068 ObjPtr<mirror::String> s = f->GetObject(thread_group)->AsString();
Sebastien Hertza06430c2014-09-15 19:21:30 +02002069
2070 std::string thread_group_name(s->ToModifiedUtf8());
2071 expandBufAddUtf8String(pReply, thread_group_name);
2072 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002073}
2074
Sebastien Hertza06430c2014-09-15 19:21:30 +02002075JDWP::JdwpError Dbg::GetThreadGroupParent(JDWP::ObjectId thread_group_id, JDWP::ExpandBuf* pReply) {
Ian Rogers98379392014-02-24 16:53:16 -08002076 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002077 JDWP::JdwpError error;
Sebastien Hertza06430c2014-09-15 19:21:30 +02002078 mirror::Object* thread_group = DecodeThreadGroup(soa, thread_group_id, &error);
2079 if (error != JDWP::ERR_NONE) {
2080 return error;
2081 }
Mathieu Chartier3398c782016-09-30 10:27:43 -07002082 ObjPtr<mirror::Object> parent;
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07002083 {
Mathieu Chartier268764d2016-09-13 12:09:38 -07002084 ScopedAssertNoThreadSuspension ants("Debugger: GetThreadGroupParent");
Mathieu Chartierc7853442015-03-27 14:35:38 -07002085 ArtField* f = soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_parent);
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07002086 CHECK(f != nullptr);
2087 parent = f->GetObject(thread_group);
2088 }
Sebastien Hertza06430c2014-09-15 19:21:30 +02002089 JDWP::ObjectId parent_group_id = gRegistry->Add(parent);
2090 expandBufAddObjectId(pReply, parent_group_id);
2091 return JDWP::ERR_NONE;
2092}
2093
2094static void GetChildThreadGroups(ScopedObjectAccessUnchecked& soa, mirror::Object* thread_group,
2095 std::vector<JDWP::ObjectId>* child_thread_group_ids)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002096 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertza06430c2014-09-15 19:21:30 +02002097 CHECK(thread_group != nullptr);
2098
Przemyslaw Szczepaniak464595f2015-11-24 11:59:59 +00002099 // Get the int "ngroups" count of this thread group...
2100 ArtField* ngroups_field = soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_ngroups);
2101 CHECK(ngroups_field != nullptr);
2102 const int32_t size = ngroups_field->GetInt(thread_group);
2103 if (size == 0) {
2104 return;
Sebastien Hertze49e1952014-10-13 11:27:13 +02002105 }
Sebastien Hertza06430c2014-09-15 19:21:30 +02002106
Przemyslaw Szczepaniak464595f2015-11-24 11:59:59 +00002107 // Get the ThreadGroup[] "groups" out of this thread group...
2108 ArtField* groups_field = soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_groups);
Mathieu Chartier3398c782016-09-30 10:27:43 -07002109 ObjPtr<mirror::Object> groups_array = groups_field->GetObject(thread_group);
Przemyslaw Szczepaniak464595f2015-11-24 11:59:59 +00002110
2111 CHECK(groups_array != nullptr);
2112 CHECK(groups_array->IsObjectArray());
2113
Mathieu Chartier3398c782016-09-30 10:27:43 -07002114 ObjPtr<mirror::ObjectArray<mirror::Object>> groups_array_as_array =
Przemyslaw Szczepaniak464595f2015-11-24 11:59:59 +00002115 groups_array->AsObjectArray<mirror::Object>();
Sebastien Hertza06430c2014-09-15 19:21:30 +02002116
2117 // Copy the first 'size' elements out of the array into the result.
Sebastien Hertz6995c602014-09-09 12:10:13 +02002118 ObjectRegistry* registry = Dbg::GetObjectRegistry();
Sebastien Hertza06430c2014-09-15 19:21:30 +02002119 for (int32_t i = 0; i < size; ++i) {
Przemyslaw Szczepaniak464595f2015-11-24 11:59:59 +00002120 child_thread_group_ids->push_back(registry->Add(groups_array_as_array->Get(i)));
Sebastien Hertza06430c2014-09-15 19:21:30 +02002121 }
2122}
2123
2124JDWP::JdwpError Dbg::GetThreadGroupChildren(JDWP::ObjectId thread_group_id,
2125 JDWP::ExpandBuf* pReply) {
2126 ScopedObjectAccessUnchecked soa(Thread::Current());
2127 JDWP::JdwpError error;
2128 mirror::Object* thread_group = DecodeThreadGroup(soa, thread_group_id, &error);
2129 if (error != JDWP::ERR_NONE) {
2130 return error;
2131 }
2132
2133 // Add child threads.
2134 {
2135 std::vector<JDWP::ObjectId> child_thread_ids;
2136 GetThreads(thread_group, &child_thread_ids);
2137 expandBufAdd4BE(pReply, child_thread_ids.size());
2138 for (JDWP::ObjectId child_thread_id : child_thread_ids) {
2139 expandBufAddObjectId(pReply, child_thread_id);
2140 }
2141 }
2142
2143 // Add child thread groups.
2144 {
2145 std::vector<JDWP::ObjectId> child_thread_groups_ids;
2146 GetChildThreadGroups(soa, thread_group, &child_thread_groups_ids);
2147 expandBufAdd4BE(pReply, child_thread_groups_ids.size());
2148 for (JDWP::ObjectId child_thread_group_id : child_thread_groups_ids) {
2149 expandBufAddObjectId(pReply, child_thread_group_id);
2150 }
2151 }
2152
2153 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002154}
2155
2156JDWP::ObjectId Dbg::GetSystemThreadGroupId() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002157 ScopedObjectAccessUnchecked soa(Thread::Current());
Mathieu Chartierc7853442015-03-27 14:35:38 -07002158 ArtField* f = soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_systemThreadGroup);
Mathieu Chartier3398c782016-09-30 10:27:43 -07002159 ObjPtr<mirror::Object> group = f->GetObject(f->GetDeclaringClass());
Ian Rogers365c1022012-06-22 15:05:28 -07002160 return gRegistry->Add(group);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002161}
2162
Jeff Hao920af3e2013-08-28 15:46:38 -07002163JDWP::JdwpThreadStatus Dbg::ToJdwpThreadStatus(ThreadState state) {
2164 switch (state) {
2165 case kBlocked:
2166 return JDWP::TS_MONITOR;
2167 case kNative:
2168 case kRunnable:
2169 case kSuspended:
2170 return JDWP::TS_RUNNING;
2171 case kSleeping:
2172 return JDWP::TS_SLEEPING;
2173 case kStarting:
2174 case kTerminated:
2175 return JDWP::TS_ZOMBIE;
2176 case kTimedWaiting:
Sebastien Hertzbae182c2013-12-17 10:42:03 +01002177 case kWaitingForCheckPointsToRun:
Jeff Hao920af3e2013-08-28 15:46:38 -07002178 case kWaitingForDebuggerSend:
2179 case kWaitingForDebuggerSuspension:
2180 case kWaitingForDebuggerToAttach:
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002181 case kWaitingForDeoptimization:
Jeff Hao920af3e2013-08-28 15:46:38 -07002182 case kWaitingForGcToComplete:
Mathieu Chartierb43390c2015-05-12 10:47:11 -07002183 case kWaitingForGetObjectsAllocated:
Jeff Hao920af3e2013-08-28 15:46:38 -07002184 case kWaitingForJniOnLoad:
Sebastien Hertzbae182c2013-12-17 10:42:03 +01002185 case kWaitingForMethodTracingStart:
Jeff Hao920af3e2013-08-28 15:46:38 -07002186 case kWaitingForSignalCatcherOutput:
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -08002187 case kWaitingForVisitObjects:
Jeff Hao920af3e2013-08-28 15:46:38 -07002188 case kWaitingInMainDebuggerLoop:
2189 case kWaitingInMainSignalCatcherLoop:
2190 case kWaitingPerformingGc:
Mathieu Chartier90ef3db2015-08-04 15:19:41 -07002191 case kWaitingWeakGcRootRead:
Hiroshi Yamauchi76f55b02015-08-21 16:10:39 -07002192 case kWaitingForGcThreadFlip:
Jeff Hao920af3e2013-08-28 15:46:38 -07002193 case kWaiting:
2194 return JDWP::TS_WAIT;
2195 // Don't add a 'default' here so the compiler can spot incompatible enum changes.
2196 }
2197 LOG(FATAL) << "Unknown thread state: " << state;
2198 return JDWP::TS_ZOMBIE;
2199}
2200
Sebastien Hertz52d131d2014-03-13 16:17:40 +01002201JDWP::JdwpError Dbg::GetThreadStatus(JDWP::ObjectId thread_id, JDWP::JdwpThreadStatus* pThreadStatus,
2202 JDWP::JdwpSuspendStatus* pSuspendStatus) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002203 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes499c5132011-11-17 14:55:11 -08002204
Elliott Hughes9e0c1752013-01-09 14:02:58 -08002205 *pSuspendStatus = JDWP::SUSPEND_STATUS_NOT_SUSPENDED;
2206
Ian Rogersc0542af2014-09-03 16:16:56 -07002207 JDWP::JdwpError error;
2208 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002209 if (error != JDWP::ERR_NONE) {
2210 if (error == JDWP::ERR_THREAD_NOT_ALIVE) {
2211 *pThreadStatus = JDWP::TS_ZOMBIE;
Elliott Hughes221229c2013-01-08 18:17:50 -08002212 return JDWP::ERR_NONE;
2213 }
2214 return error;
Elliott Hughes499c5132011-11-17 14:55:11 -08002215 }
2216
Elliott Hughes9e0c1752013-01-09 14:02:58 -08002217 if (IsSuspendedForDebugger(soa, thread)) {
2218 *pSuspendStatus = JDWP::SUSPEND_STATUS_SUSPENDED;
Elliott Hughes499c5132011-11-17 14:55:11 -08002219 }
2220
Jeff Hao920af3e2013-08-28 15:46:38 -07002221 *pThreadStatus = ToJdwpThreadStatus(thread->GetState());
Elliott Hughes221229c2013-01-08 18:17:50 -08002222 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002223}
2224
Elliott Hughes221229c2013-01-08 18:17:50 -08002225JDWP::JdwpError Dbg::GetThreadDebugSuspendCount(JDWP::ObjectId thread_id, JDWP::ExpandBuf* pReply) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002226 ScopedObjectAccess soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002227 JDWP::JdwpError error;
2228 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002229 if (error != JDWP::ERR_NONE) {
2230 return error;
Elliott Hughes2435a572012-02-17 16:07:41 -08002231 }
Ian Rogers50b35e22012-10-04 10:09:15 -07002232 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002233 expandBufAdd4BE(pReply, thread->GetDebugSuspendCount());
Elliott Hughes2435a572012-02-17 16:07:41 -08002234 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002235}
2236
Elliott Hughesf9501702013-01-11 11:22:27 -08002237JDWP::JdwpError Dbg::Interrupt(JDWP::ObjectId thread_id) {
2238 ScopedObjectAccess soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002239 JDWP::JdwpError error;
2240 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughesf9501702013-01-11 11:22:27 -08002241 if (error != JDWP::ERR_NONE) {
2242 return error;
2243 }
Ian Rogersdd7624d2014-03-14 17:43:00 -07002244 thread->Interrupt(soa.Self());
Elliott Hughesf9501702013-01-11 11:22:27 -08002245 return JDWP::ERR_NONE;
2246}
2247
Sebastien Hertz070f7322014-09-09 12:08:49 +02002248static bool IsInDesiredThreadGroup(ScopedObjectAccessUnchecked& soa,
2249 mirror::Object* desired_thread_group, mirror::Object* peer)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002250 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz070f7322014-09-09 12:08:49 +02002251 // Do we want threads from all thread groups?
2252 if (desired_thread_group == nullptr) {
2253 return true;
2254 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07002255 ArtField* thread_group_field = soa.DecodeField(WellKnownClasses::java_lang_Thread_group);
Sebastien Hertz070f7322014-09-09 12:08:49 +02002256 DCHECK(thread_group_field != nullptr);
Mathieu Chartier3398c782016-09-30 10:27:43 -07002257 ObjPtr<mirror::Object> group = thread_group_field->GetObject(peer);
Sebastien Hertz070f7322014-09-09 12:08:49 +02002258 return (group == desired_thread_group);
2259}
2260
Sebastien Hertza06430c2014-09-15 19:21:30 +02002261void Dbg::GetThreads(mirror::Object* thread_group, std::vector<JDWP::ObjectId>* thread_ids) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002262 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz070f7322014-09-09 12:08:49 +02002263 std::list<Thread*> all_threads_list;
2264 {
2265 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
2266 all_threads_list = Runtime::Current()->GetThreadList()->GetList();
2267 }
2268 for (Thread* t : all_threads_list) {
2269 if (t == Dbg::GetDebugThread()) {
2270 // Skip the JDWP thread. Some debuggers get bent out of shape when they can't suspend and
2271 // query all threads, so it's easier if we just don't tell them about this thread.
2272 continue;
2273 }
2274 if (t->IsStillStarting()) {
2275 // This thread is being started (and has been registered in the thread list). However, it is
2276 // not completely started yet so we must ignore it.
2277 continue;
2278 }
2279 mirror::Object* peer = t->GetPeer();
2280 if (peer == nullptr) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002281 // 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 +02002282 // this thread yet.
2283 // TODO: if we identified threads to the debugger by their Thread*
2284 // rather than their peer's mirror::Object*, we could fix this.
2285 // Doing so might help us report ZOMBIE threads too.
2286 continue;
2287 }
2288 if (IsInDesiredThreadGroup(soa, thread_group, peer)) {
2289 thread_ids->push_back(gRegistry->Add(peer));
2290 }
2291 }
Elliott Hughescaf76542012-06-28 16:08:22 -07002292}
Elliott Hughesa2155262011-11-16 16:26:58 -08002293
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002294static int GetStackDepth(Thread* thread) REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002295 struct CountStackDepthVisitor : public StackVisitor {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002296 explicit CountStackDepthVisitor(Thread* thread_in)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01002297 : StackVisitor(thread_in, nullptr, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
2298 depth(0) {}
Ian Rogers0399dde2012-06-06 17:09:28 -07002299
Elliott Hughes64f574f2013-02-20 14:57:12 -08002300 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2301 // annotalysis.
2302 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07002303 if (!GetMethod()->IsRuntimeMethod()) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -08002304 ++depth;
2305 }
Elliott Hughes530fa002012-03-12 11:44:49 -07002306 return true;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08002307 }
2308 size_t depth;
2309 };
Elliott Hughes08fc03a2012-06-26 17:34:00 -07002310
Ian Rogers7a22fa62013-01-23 12:16:16 -08002311 CountStackDepthVisitor visitor(thread);
Ian Rogers0399dde2012-06-06 17:09:28 -07002312 visitor.WalkStack();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08002313 return visitor.depth;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002314}
2315
Ian Rogersc0542af2014-09-03 16:16:56 -07002316JDWP::JdwpError Dbg::GetThreadFrameCount(JDWP::ObjectId thread_id, size_t* result) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002317 ScopedObjectAccess soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002318 JDWP::JdwpError error;
2319 *result = 0;
2320 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002321 if (error != JDWP::ERR_NONE) {
2322 return error;
2323 }
Elliott Hughesf15f4a02013-01-09 10:09:38 -08002324 if (!IsSuspendedForDebugger(soa, thread)) {
2325 return JDWP::ERR_THREAD_NOT_SUSPENDED;
2326 }
Ian Rogersc0542af2014-09-03 16:16:56 -07002327 *result = GetStackDepth(thread);
Elliott Hughes221229c2013-01-08 18:17:50 -08002328 return JDWP::ERR_NONE;
Elliott Hughes86964332012-02-15 19:37:42 -08002329}
2330
Ian Rogers306057f2012-11-26 12:45:53 -08002331JDWP::JdwpError Dbg::GetThreadFrames(JDWP::ObjectId thread_id, size_t start_frame,
2332 size_t frame_count, JDWP::ExpandBuf* buf) {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002333 class GetFrameVisitor : public StackVisitor {
2334 public:
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002335 GetFrameVisitor(Thread* thread, size_t start_frame_in, size_t frame_count_in,
2336 JDWP::ExpandBuf* buf_in)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002337 REQUIRES_SHARED(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01002338 : StackVisitor(thread, nullptr, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
2339 depth_(0),
2340 start_frame_(start_frame_in),
2341 frame_count_(frame_count_in),
2342 buf_(buf_in) {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002343 expandBufAdd4BE(buf_, frame_count_);
Elliott Hughes03181a82011-11-17 17:22:21 -08002344 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002345
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002346 bool VisitFrame() OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002347 if (GetMethod()->IsRuntimeMethod()) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07002348 return true; // The debugger can't do anything useful with a frame that has no Method*.
Elliott Hughes03181a82011-11-17 17:22:21 -08002349 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002350 if (depth_ >= start_frame_ + frame_count_) {
Elliott Hughes530fa002012-03-12 11:44:49 -07002351 return false;
Elliott Hughes03181a82011-11-17 17:22:21 -08002352 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002353 if (depth_ >= start_frame_) {
2354 JDWP::FrameId frame_id(GetFrameId());
2355 JDWP::JdwpLocation location;
Sebastien Hertz6995c602014-09-09 12:10:13 +02002356 SetJdwpLocation(&location, GetMethod(), GetDexPc());
Ian Rogersef7d42f2014-01-06 12:55:46 -08002357 VLOG(jdwp) << StringPrintf(" Frame %3zd: id=%3" PRIu64 " ", depth_, frame_id) << location;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002358 expandBufAdd8BE(buf_, frame_id);
2359 expandBufAddLocation(buf_, location);
2360 }
2361 ++depth_;
Elliott Hughes530fa002012-03-12 11:44:49 -07002362 return true;
Elliott Hughes03181a82011-11-17 17:22:21 -08002363 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002364
2365 private:
2366 size_t depth_;
2367 const size_t start_frame_;
2368 const size_t frame_count_;
2369 JDWP::ExpandBuf* buf_;
Elliott Hughes03181a82011-11-17 17:22:21 -08002370 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002371
2372 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002373 JDWP::JdwpError error;
2374 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002375 if (error != JDWP::ERR_NONE) {
2376 return error;
2377 }
Elliott Hughesf15f4a02013-01-09 10:09:38 -08002378 if (!IsSuspendedForDebugger(soa, thread)) {
2379 return JDWP::ERR_THREAD_NOT_SUSPENDED;
2380 }
Ian Rogers7a22fa62013-01-23 12:16:16 -08002381 GetFrameVisitor visitor(thread, start_frame, frame_count, buf);
Ian Rogers0399dde2012-06-06 17:09:28 -07002382 visitor.WalkStack();
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002383 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002384}
2385
2386JDWP::ObjectId Dbg::GetThreadSelfId() {
Sebastien Hertz6995c602014-09-09 12:10:13 +02002387 return GetThreadId(Thread::Current());
2388}
2389
2390JDWP::ObjectId Dbg::GetThreadId(Thread* thread) {
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07002391 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz6995c602014-09-09 12:10:13 +02002392 return gRegistry->Add(thread->GetPeer());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002393}
2394
Elliott Hughes475fc232011-10-25 15:00:35 -07002395void Dbg::SuspendVM() {
Hiroshi Yamauchi8f95cf32016-04-19 11:14:06 -07002396 // Avoid a deadlock between GC and debugger where GC gets suspended during GC. b/25800335.
2397 gc::ScopedGCCriticalSection gcs(Thread::Current(),
2398 gc::kGcCauseDebugger,
2399 gc::kCollectorTypeDebugger);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002400 Runtime::Current()->GetThreadList()->SuspendAllForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002401}
2402
2403void Dbg::ResumeVM() {
Sebastien Hertz253fa552014-10-14 17:27:15 +02002404 Runtime::Current()->GetThreadList()->ResumeAllForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002405}
2406
Elliott Hughes221229c2013-01-08 18:17:50 -08002407JDWP::JdwpError Dbg::SuspendThread(JDWP::ObjectId thread_id, bool request_suspension) {
Ian Rogersf3d874c2014-07-17 18:52:42 -07002408 Thread* self = Thread::Current();
Ian Rogersc0542af2014-09-03 16:16:56 -07002409 ScopedLocalRef<jobject> peer(self->GetJniEnv(), nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002410 {
Ian Rogersf3d874c2014-07-17 18:52:42 -07002411 ScopedObjectAccess soa(self);
Ian Rogersc0542af2014-09-03 16:16:56 -07002412 JDWP::JdwpError error;
2413 peer.reset(soa.AddLocalReference<jobject>(gRegistry->Get<mirror::Object*>(thread_id, &error)));
Elliott Hughes4e235312011-12-02 11:34:15 -08002414 }
Ian Rogersc0542af2014-09-03 16:16:56 -07002415 if (peer.get() == nullptr) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002416 return JDWP::ERR_THREAD_NOT_ALIVE;
2417 }
Ian Rogers4ad5cd32014-11-11 23:08:07 -08002418 // Suspend thread to build stack trace.
Elliott Hughesf327e072013-01-09 16:01:26 -08002419 bool timed_out;
Brian Carlstromba32de42014-08-27 23:43:46 -07002420 ThreadList* thread_list = Runtime::Current()->GetThreadList();
2421 Thread* thread = thread_list->SuspendThreadByPeer(peer.get(), request_suspension, true,
2422 &timed_out);
Ian Rogersc0542af2014-09-03 16:16:56 -07002423 if (thread != nullptr) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002424 return JDWP::ERR_NONE;
Elliott Hughesf327e072013-01-09 16:01:26 -08002425 } else if (timed_out) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002426 return JDWP::ERR_INTERNAL;
2427 } else {
2428 return JDWP::ERR_THREAD_NOT_ALIVE;
2429 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002430}
2431
Elliott Hughes221229c2013-01-08 18:17:50 -08002432void Dbg::ResumeThread(JDWP::ObjectId thread_id) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002433 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002434 JDWP::JdwpError error;
2435 mirror::Object* peer = gRegistry->Get<mirror::Object*>(thread_id, &error);
2436 CHECK(peer != nullptr) << error;
jeffhaoa77f0f62012-12-05 17:19:31 -08002437 Thread* thread;
2438 {
2439 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
2440 thread = Thread::FromManagedThread(soa, peer);
2441 }
Ian Rogersc0542af2014-09-03 16:16:56 -07002442 if (thread == nullptr) {
Elliott Hughes4e235312011-12-02 11:34:15 -08002443 LOG(WARNING) << "No such thread for resume: " << peer;
2444 return;
2445 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002446 bool needs_resume;
2447 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002448 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002449 needs_resume = thread->GetSuspendCount() > 0;
2450 }
2451 if (needs_resume) {
Elliott Hughes546b9862012-06-20 16:06:13 -07002452 Runtime::Current()->GetThreadList()->Resume(thread, true);
2453 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002454}
2455
2456void Dbg::SuspendSelf() {
Elliott Hughes475fc232011-10-25 15:00:35 -07002457 Runtime::Current()->GetThreadList()->SuspendSelfForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002458}
2459
Ian Rogers0399dde2012-06-06 17:09:28 -07002460struct GetThisVisitor : public StackVisitor {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002461 GetThisVisitor(Thread* thread, Context* context, JDWP::FrameId frame_id_in)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002462 REQUIRES_SHARED(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01002463 : StackVisitor(thread, context, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
2464 this_object(nullptr),
2465 frame_id(frame_id_in) {}
Ian Rogers0399dde2012-06-06 17:09:28 -07002466
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002467 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2468 // annotalysis.
2469 virtual bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002470 if (frame_id != GetFrameId()) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002471 return true; // continue
Ian Rogers0399dde2012-06-06 17:09:28 -07002472 } else {
Ian Rogers62d6c772013-02-27 08:32:07 -08002473 this_object = GetThisObject();
2474 return false;
Ian Rogers0399dde2012-06-06 17:09:28 -07002475 }
Elliott Hughes86b00102011-12-05 17:54:26 -08002476 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002477
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002478 mirror::Object* this_object;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002479 JDWP::FrameId frame_id;
Ian Rogers0399dde2012-06-06 17:09:28 -07002480};
2481
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002482JDWP::JdwpError Dbg::GetThisObject(JDWP::ObjectId thread_id, JDWP::FrameId frame_id,
2483 JDWP::ObjectId* result) {
2484 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz69206392015-04-07 15:54:25 +02002485 JDWP::JdwpError error;
2486 Thread* thread = DecodeThread(soa, thread_id, &error);
2487 if (error != JDWP::ERR_NONE) {
2488 return error;
2489 }
2490 if (!IsSuspendedForDebugger(soa, thread)) {
2491 return JDWP::ERR_THREAD_NOT_SUSPENDED;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002492 }
Ian Rogers700a4022014-05-19 16:49:03 -07002493 std::unique_ptr<Context> context(Context::Create());
Ian Rogers7a22fa62013-01-23 12:16:16 -08002494 GetThisVisitor visitor(thread, context.get(), frame_id);
Ian Rogers0399dde2012-06-06 17:09:28 -07002495 visitor.WalkStack();
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002496 *result = gRegistry->Add(visitor.this_object);
2497 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002498}
2499
Sebastien Hertz8009f392014-09-01 17:07:11 +02002500// Walks the stack until we find the frame with the given FrameId.
2501class FindFrameVisitor FINAL : public StackVisitor {
2502 public:
2503 FindFrameVisitor(Thread* thread, Context* context, JDWP::FrameId frame_id)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002504 REQUIRES_SHARED(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01002505 : StackVisitor(thread, context, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
2506 frame_id_(frame_id),
2507 error_(JDWP::ERR_INVALID_FRAMEID) {}
Ian Rogersca190662012-06-26 15:45:57 -07002508
Sebastien Hertz8009f392014-09-01 17:07:11 +02002509 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2510 // annotalysis.
2511 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
2512 if (GetFrameId() != frame_id_) {
2513 return true; // Not our frame, carry on.
Ian Rogers0399dde2012-06-06 17:09:28 -07002514 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07002515 ArtMethod* m = GetMethod();
Sebastien Hertz8009f392014-09-01 17:07:11 +02002516 if (m->IsNative()) {
2517 // We can't read/write local value from/into native method.
2518 error_ = JDWP::ERR_OPAQUE_FRAME;
2519 } else {
2520 // We found our frame.
2521 error_ = JDWP::ERR_NONE;
2522 }
2523 return false;
2524 }
2525
2526 JDWP::JdwpError GetError() const {
2527 return error_;
2528 }
2529
2530 private:
2531 const JDWP::FrameId frame_id_;
2532 JDWP::JdwpError error_;
Sebastien Hertz26f72862015-09-15 09:52:07 +02002533
2534 DISALLOW_COPY_AND_ASSIGN(FindFrameVisitor);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002535};
2536
2537JDWP::JdwpError Dbg::GetLocalValues(JDWP::Request* request, JDWP::ExpandBuf* pReply) {
2538 JDWP::ObjectId thread_id = request->ReadThreadId();
2539 JDWP::FrameId frame_id = request->ReadFrameId();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002540
2541 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz69206392015-04-07 15:54:25 +02002542 JDWP::JdwpError error;
2543 Thread* thread = DecodeThread(soa, thread_id, &error);
2544 if (error != JDWP::ERR_NONE) {
2545 return error;
2546 }
2547 if (!IsSuspendedForDebugger(soa, thread)) {
2548 return JDWP::ERR_THREAD_NOT_SUSPENDED;
Elliott Hughes221229c2013-01-08 18:17:50 -08002549 }
Sebastien Hertz8009f392014-09-01 17:07:11 +02002550 // Find the frame with the given frame_id.
Ian Rogers700a4022014-05-19 16:49:03 -07002551 std::unique_ptr<Context> context(Context::Create());
Sebastien Hertz8009f392014-09-01 17:07:11 +02002552 FindFrameVisitor visitor(thread, context.get(), frame_id);
Ian Rogers0399dde2012-06-06 17:09:28 -07002553 visitor.WalkStack();
Sebastien Hertz8009f392014-09-01 17:07:11 +02002554 if (visitor.GetError() != JDWP::ERR_NONE) {
2555 return visitor.GetError();
2556 }
2557
2558 // Read the values from visitor's context.
2559 int32_t slot_count = request->ReadSigned32("slot count");
2560 expandBufAdd4BE(pReply, slot_count); /* "int values" */
2561 for (int32_t i = 0; i < slot_count; ++i) {
2562 uint32_t slot = request->ReadUnsigned32("slot");
2563 JDWP::JdwpTag reqSigByte = request->ReadTag();
2564
2565 VLOG(jdwp) << " --> slot " << slot << " " << reqSigByte;
2566
2567 size_t width = Dbg::GetTagWidth(reqSigByte);
Sebastien Hertz7d955652014-10-22 10:57:10 +02002568 uint8_t* ptr = expandBufAddSpace(pReply, width + 1);
Sebastien Hertz69206392015-04-07 15:54:25 +02002569 error = Dbg::GetLocalValue(visitor, soa, slot, reqSigByte, ptr, width);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002570 if (error != JDWP::ERR_NONE) {
2571 return error;
2572 }
2573 }
2574 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002575}
2576
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002577constexpr JDWP::JdwpError kStackFrameLocalAccessError = JDWP::ERR_ABSENT_INFORMATION;
2578
2579static std::string GetStackContextAsString(const StackVisitor& visitor)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002580 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002581 return StringPrintf(" at DEX pc 0x%08x in method %s", visitor.GetDexPc(false),
2582 PrettyMethod(visitor.GetMethod()).c_str());
2583}
2584
2585static JDWP::JdwpError FailGetLocalValue(const StackVisitor& visitor, uint16_t vreg,
2586 JDWP::JdwpTag tag)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002587 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002588 LOG(ERROR) << "Failed to read " << tag << " local from register v" << vreg
2589 << GetStackContextAsString(visitor);
2590 return kStackFrameLocalAccessError;
2591}
2592
Sebastien Hertz8009f392014-09-01 17:07:11 +02002593JDWP::JdwpError Dbg::GetLocalValue(const StackVisitor& visitor, ScopedObjectAccessUnchecked& soa,
2594 int slot, JDWP::JdwpTag tag, uint8_t* buf, size_t width) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002595 ArtMethod* m = visitor.GetMethod();
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002596 JDWP::JdwpError error = JDWP::ERR_NONE;
2597 uint16_t vreg = DemangleSlot(slot, m, &error);
2598 if (error != JDWP::ERR_NONE) {
2599 return error;
2600 }
Sebastien Hertz8009f392014-09-01 17:07:11 +02002601 // TODO: check that the tag is compatible with the actual type of the slot!
Sebastien Hertz8009f392014-09-01 17:07:11 +02002602 switch (tag) {
2603 case JDWP::JT_BOOLEAN: {
2604 CHECK_EQ(width, 1U);
2605 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002606 if (!visitor.GetVReg(m, vreg, kIntVReg, &intVal)) {
2607 return FailGetLocalValue(visitor, vreg, tag);
Ian Rogers0399dde2012-06-06 17:09:28 -07002608 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002609 VLOG(jdwp) << "get boolean local " << vreg << " = " << intVal;
2610 JDWP::Set1(buf + 1, intVal != 0);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002611 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002612 }
Sebastien Hertz8009f392014-09-01 17:07:11 +02002613 case JDWP::JT_BYTE: {
2614 CHECK_EQ(width, 1U);
2615 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002616 if (!visitor.GetVReg(m, vreg, kIntVReg, &intVal)) {
2617 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002618 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002619 VLOG(jdwp) << "get byte local " << vreg << " = " << intVal;
2620 JDWP::Set1(buf + 1, intVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002621 break;
2622 }
2623 case JDWP::JT_SHORT:
2624 case JDWP::JT_CHAR: {
2625 CHECK_EQ(width, 2U);
2626 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002627 if (!visitor.GetVReg(m, vreg, kIntVReg, &intVal)) {
2628 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002629 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002630 VLOG(jdwp) << "get short/char local " << vreg << " = " << intVal;
2631 JDWP::Set2BE(buf + 1, intVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002632 break;
2633 }
2634 case JDWP::JT_INT: {
2635 CHECK_EQ(width, 4U);
2636 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002637 if (!visitor.GetVReg(m, vreg, kIntVReg, &intVal)) {
2638 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002639 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002640 VLOG(jdwp) << "get int local " << vreg << " = " << intVal;
2641 JDWP::Set4BE(buf + 1, intVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002642 break;
2643 }
2644 case JDWP::JT_FLOAT: {
2645 CHECK_EQ(width, 4U);
2646 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002647 if (!visitor.GetVReg(m, vreg, kFloatVReg, &intVal)) {
2648 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002649 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002650 VLOG(jdwp) << "get float local " << vreg << " = " << intVal;
2651 JDWP::Set4BE(buf + 1, intVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002652 break;
2653 }
2654 case JDWP::JT_ARRAY:
2655 case JDWP::JT_CLASS_LOADER:
2656 case JDWP::JT_CLASS_OBJECT:
2657 case JDWP::JT_OBJECT:
2658 case JDWP::JT_STRING:
2659 case JDWP::JT_THREAD:
2660 case JDWP::JT_THREAD_GROUP: {
2661 CHECK_EQ(width, sizeof(JDWP::ObjectId));
2662 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002663 if (!visitor.GetVReg(m, vreg, kReferenceVReg, &intVal)) {
2664 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002665 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002666 mirror::Object* o = reinterpret_cast<mirror::Object*>(intVal);
2667 VLOG(jdwp) << "get " << tag << " object local " << vreg << " = " << o;
2668 if (!Runtime::Current()->GetHeap()->IsValidObjectAddress(o)) {
2669 LOG(FATAL) << StringPrintf("Found invalid object %#" PRIxPTR " in register v%u",
2670 reinterpret_cast<uintptr_t>(o), vreg)
2671 << GetStackContextAsString(visitor);
2672 UNREACHABLE();
2673 }
2674 tag = TagFromObject(soa, o);
2675 JDWP::SetObjectId(buf + 1, gRegistry->Add(o));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002676 break;
2677 }
2678 case JDWP::JT_DOUBLE: {
2679 CHECK_EQ(width, 8U);
2680 uint64_t longVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002681 if (!visitor.GetVRegPair(m, vreg, kDoubleLoVReg, kDoubleHiVReg, &longVal)) {
2682 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002683 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002684 VLOG(jdwp) << "get double local " << vreg << " = " << longVal;
2685 JDWP::Set8BE(buf + 1, longVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002686 break;
2687 }
2688 case JDWP::JT_LONG: {
2689 CHECK_EQ(width, 8U);
2690 uint64_t longVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002691 if (!visitor.GetVRegPair(m, vreg, kLongLoVReg, kLongHiVReg, &longVal)) {
2692 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002693 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002694 VLOG(jdwp) << "get long local " << vreg << " = " << longVal;
2695 JDWP::Set8BE(buf + 1, longVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002696 break;
2697 }
2698 default:
2699 LOG(FATAL) << "Unknown tag " << tag;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002700 UNREACHABLE();
Sebastien Hertz8009f392014-09-01 17:07:11 +02002701 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002702
Sebastien Hertz8009f392014-09-01 17:07:11 +02002703 // Prepend tag, which may have been updated.
2704 JDWP::Set1(buf, tag);
2705 return JDWP::ERR_NONE;
2706}
2707
2708JDWP::JdwpError Dbg::SetLocalValues(JDWP::Request* request) {
2709 JDWP::ObjectId thread_id = request->ReadThreadId();
2710 JDWP::FrameId frame_id = request->ReadFrameId();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002711
2712 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz69206392015-04-07 15:54:25 +02002713 JDWP::JdwpError error;
2714 Thread* thread = DecodeThread(soa, thread_id, &error);
2715 if (error != JDWP::ERR_NONE) {
2716 return error;
2717 }
2718 if (!IsSuspendedForDebugger(soa, thread)) {
2719 return JDWP::ERR_THREAD_NOT_SUSPENDED;
Elliott Hughes221229c2013-01-08 18:17:50 -08002720 }
Sebastien Hertz8009f392014-09-01 17:07:11 +02002721 // Find the frame with the given frame_id.
Ian Rogers700a4022014-05-19 16:49:03 -07002722 std::unique_ptr<Context> context(Context::Create());
Sebastien Hertz8009f392014-09-01 17:07:11 +02002723 FindFrameVisitor visitor(thread, context.get(), frame_id);
Ian Rogers0399dde2012-06-06 17:09:28 -07002724 visitor.WalkStack();
Sebastien Hertz8009f392014-09-01 17:07:11 +02002725 if (visitor.GetError() != JDWP::ERR_NONE) {
2726 return visitor.GetError();
2727 }
2728
2729 // Writes the values into visitor's context.
2730 int32_t slot_count = request->ReadSigned32("slot count");
2731 for (int32_t i = 0; i < slot_count; ++i) {
2732 uint32_t slot = request->ReadUnsigned32("slot");
2733 JDWP::JdwpTag sigByte = request->ReadTag();
2734 size_t width = Dbg::GetTagWidth(sigByte);
2735 uint64_t value = request->ReadValue(width);
2736
2737 VLOG(jdwp) << " --> slot " << slot << " " << sigByte << " " << value;
Mingyao Yang99170c62015-07-06 11:10:37 -07002738 error = Dbg::SetLocalValue(thread, visitor, slot, sigByte, value, width);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002739 if (error != JDWP::ERR_NONE) {
2740 return error;
2741 }
2742 }
2743 return JDWP::ERR_NONE;
2744}
2745
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002746template<typename T>
2747static JDWP::JdwpError FailSetLocalValue(const StackVisitor& visitor, uint16_t vreg,
2748 JDWP::JdwpTag tag, T value)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002749 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002750 LOG(ERROR) << "Failed to write " << tag << " local " << value
2751 << " (0x" << std::hex << value << ") into register v" << vreg
2752 << GetStackContextAsString(visitor);
2753 return kStackFrameLocalAccessError;
2754}
2755
Mingyao Yang99170c62015-07-06 11:10:37 -07002756JDWP::JdwpError Dbg::SetLocalValue(Thread* thread, StackVisitor& visitor, int slot,
2757 JDWP::JdwpTag tag, uint64_t value, size_t width) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002758 ArtMethod* m = visitor.GetMethod();
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002759 JDWP::JdwpError error = JDWP::ERR_NONE;
2760 uint16_t vreg = DemangleSlot(slot, m, &error);
2761 if (error != JDWP::ERR_NONE) {
2762 return error;
2763 }
Sebastien Hertz8009f392014-09-01 17:07:11 +02002764 // TODO: check that the tag is compatible with the actual type of the slot!
Sebastien Hertz8009f392014-09-01 17:07:11 +02002765 switch (tag) {
2766 case JDWP::JT_BOOLEAN:
2767 case JDWP::JT_BYTE:
2768 CHECK_EQ(width, 1U);
Mingyao Yang636b9252015-07-31 16:40:24 -07002769 if (!visitor.SetVReg(m, vreg, static_cast<uint32_t>(value), kIntVReg)) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002770 return FailSetLocalValue(visitor, vreg, tag, static_cast<uint32_t>(value));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002771 }
2772 break;
2773 case JDWP::JT_SHORT:
2774 case JDWP::JT_CHAR:
2775 CHECK_EQ(width, 2U);
Mingyao Yang636b9252015-07-31 16:40:24 -07002776 if (!visitor.SetVReg(m, vreg, static_cast<uint32_t>(value), kIntVReg)) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002777 return FailSetLocalValue(visitor, vreg, tag, static_cast<uint32_t>(value));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002778 }
2779 break;
2780 case JDWP::JT_INT:
2781 CHECK_EQ(width, 4U);
Mingyao Yang636b9252015-07-31 16:40:24 -07002782 if (!visitor.SetVReg(m, vreg, static_cast<uint32_t>(value), kIntVReg)) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002783 return FailSetLocalValue(visitor, vreg, tag, static_cast<uint32_t>(value));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002784 }
2785 break;
2786 case JDWP::JT_FLOAT:
2787 CHECK_EQ(width, 4U);
Mingyao Yang636b9252015-07-31 16:40:24 -07002788 if (!visitor.SetVReg(m, vreg, static_cast<uint32_t>(value), kFloatVReg)) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002789 return FailSetLocalValue(visitor, vreg, tag, static_cast<uint32_t>(value));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002790 }
2791 break;
2792 case JDWP::JT_ARRAY:
2793 case JDWP::JT_CLASS_LOADER:
2794 case JDWP::JT_CLASS_OBJECT:
2795 case JDWP::JT_OBJECT:
2796 case JDWP::JT_STRING:
2797 case JDWP::JT_THREAD:
2798 case JDWP::JT_THREAD_GROUP: {
2799 CHECK_EQ(width, sizeof(JDWP::ObjectId));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002800 mirror::Object* o = gRegistry->Get<mirror::Object*>(static_cast<JDWP::ObjectId>(value),
2801 &error);
2802 if (error != JDWP::ERR_NONE) {
2803 VLOG(jdwp) << tag << " object " << o << " is an invalid object";
2804 return JDWP::ERR_INVALID_OBJECT;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002805 }
Mingyao Yang636b9252015-07-31 16:40:24 -07002806 if (!visitor.SetVReg(m, vreg, static_cast<uint32_t>(reinterpret_cast<uintptr_t>(o)),
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002807 kReferenceVReg)) {
2808 return FailSetLocalValue(visitor, vreg, tag, reinterpret_cast<uintptr_t>(o));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002809 }
2810 break;
2811 }
2812 case JDWP::JT_DOUBLE: {
2813 CHECK_EQ(width, 8U);
Mingyao Yang636b9252015-07-31 16:40:24 -07002814 if (!visitor.SetVRegPair(m, vreg, value, kDoubleLoVReg, kDoubleHiVReg)) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002815 return FailSetLocalValue(visitor, vreg, tag, value);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002816 }
2817 break;
2818 }
2819 case JDWP::JT_LONG: {
2820 CHECK_EQ(width, 8U);
Mingyao Yang636b9252015-07-31 16:40:24 -07002821 if (!visitor.SetVRegPair(m, vreg, value, kLongLoVReg, kLongHiVReg)) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002822 return FailSetLocalValue(visitor, vreg, tag, value);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002823 }
2824 break;
2825 }
2826 default:
2827 LOG(FATAL) << "Unknown tag " << tag;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002828 UNREACHABLE();
Sebastien Hertz8009f392014-09-01 17:07:11 +02002829 }
Mingyao Yang99170c62015-07-06 11:10:37 -07002830
2831 // If we set the local variable in a compiled frame, we need to trigger a deoptimization of
2832 // the stack so we continue execution with the interpreter using the new value(s) of the updated
2833 // local variable(s). To achieve this, we install instrumentation exit stub on each method of the
2834 // thread's stack. The stub will cause the deoptimization to happen.
2835 if (!visitor.IsShadowFrame() && thread->HasDebuggerShadowFrames()) {
2836 Runtime::Current()->GetInstrumentation()->InstrumentThreadStack(thread);
2837 }
2838
Sebastien Hertz8009f392014-09-01 17:07:11 +02002839 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002840}
2841
Mathieu Chartiere401d142015-04-22 13:56:20 -07002842static void SetEventLocation(JDWP::EventLocation* location, ArtMethod* m, uint32_t dex_pc)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002843 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz6995c602014-09-09 12:10:13 +02002844 DCHECK(location != nullptr);
2845 if (m == nullptr) {
2846 memset(location, 0, sizeof(*location));
2847 } else {
Alex Light6c8467f2015-11-20 15:03:26 -08002848 location->method = GetCanonicalMethod(m);
Sebastien Hertz6995c602014-09-09 12:10:13 +02002849 location->dex_pc = (m->IsNative() || m->IsProxyMethod()) ? static_cast<uint32_t>(-1) : dex_pc;
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002850 }
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002851}
2852
Mathieu Chartiere401d142015-04-22 13:56:20 -07002853void Dbg::PostLocationEvent(ArtMethod* m, int dex_pc, mirror::Object* this_object,
Jeff Hao579b0242013-11-18 13:16:49 -08002854 int event_flags, const JValue* return_value) {
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002855 if (!IsDebuggerActive()) {
2856 return;
2857 }
2858 DCHECK(m != nullptr);
2859 DCHECK_EQ(m->IsStatic(), this_object == nullptr);
Sebastien Hertz6995c602014-09-09 12:10:13 +02002860 JDWP::EventLocation location;
2861 SetEventLocation(&location, m, dex_pc);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002862
Sebastien Hertzde48aa62015-05-26 11:53:39 +02002863 // We need to be sure no exception is pending when calling JdwpState::PostLocationEvent.
2864 // This is required to be able to call JNI functions to create JDWP ids. To achieve this,
2865 // we temporarily clear the current thread's exception (if any) and will restore it after
2866 // the call.
2867 // Note: the only way to get a pending exception here is to suspend on a move-exception
2868 // instruction.
2869 Thread* const self = Thread::Current();
2870 StackHandleScope<1> hs(self);
2871 Handle<mirror::Throwable> pending_exception(hs.NewHandle(self->GetException()));
2872 self->ClearException();
2873 if (kIsDebugBuild && pending_exception.Get() != nullptr) {
2874 const DexFile::CodeItem* code_item = location.method->GetCodeItem();
2875 const Instruction* instr = Instruction::At(&code_item->insns_[location.dex_pc]);
2876 CHECK_EQ(Instruction::MOVE_EXCEPTION, instr->Opcode());
2877 }
2878
Sebastien Hertz6995c602014-09-09 12:10:13 +02002879 gJdwpState->PostLocationEvent(&location, this_object, event_flags, return_value);
Sebastien Hertzde48aa62015-05-26 11:53:39 +02002880
2881 if (pending_exception.Get() != nullptr) {
2882 self->SetException(pending_exception.Get());
2883 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002884}
2885
Mathieu Chartiere401d142015-04-22 13:56:20 -07002886void Dbg::PostFieldAccessEvent(ArtMethod* m, int dex_pc,
Mathieu Chartierc7853442015-03-27 14:35:38 -07002887 mirror::Object* this_object, ArtField* f) {
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002888 if (!IsDebuggerActive()) {
2889 return;
2890 }
2891 DCHECK(m != nullptr);
2892 DCHECK(f != nullptr);
Sebastien Hertz6995c602014-09-09 12:10:13 +02002893 JDWP::EventLocation location;
2894 SetEventLocation(&location, m, dex_pc);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002895
Sebastien Hertz6995c602014-09-09 12:10:13 +02002896 gJdwpState->PostFieldEvent(&location, f, this_object, nullptr, false);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002897}
2898
Mathieu Chartiere401d142015-04-22 13:56:20 -07002899void Dbg::PostFieldModificationEvent(ArtMethod* m, int dex_pc,
Mathieu Chartierc7853442015-03-27 14:35:38 -07002900 mirror::Object* this_object, ArtField* f,
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002901 const JValue* field_value) {
2902 if (!IsDebuggerActive()) {
2903 return;
2904 }
2905 DCHECK(m != nullptr);
2906 DCHECK(f != nullptr);
2907 DCHECK(field_value != nullptr);
Sebastien Hertz6995c602014-09-09 12:10:13 +02002908 JDWP::EventLocation location;
2909 SetEventLocation(&location, m, dex_pc);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002910
Sebastien Hertz6995c602014-09-09 12:10:13 +02002911 gJdwpState->PostFieldEvent(&location, f, this_object, field_value, true);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002912}
2913
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002914/**
2915 * Finds the location where this exception will be caught. We search until we reach the top
2916 * frame, in which case this exception is considered uncaught.
2917 */
2918class CatchLocationFinder : public StackVisitor {
2919 public:
2920 CatchLocationFinder(Thread* self, const Handle<mirror::Throwable>& exception, Context* context)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002921 REQUIRES_SHARED(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01002922 : StackVisitor(self, context, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002923 exception_(exception),
2924 handle_scope_(self),
2925 this_at_throw_(handle_scope_.NewHandle<mirror::Object>(nullptr)),
Mathieu Chartiere401d142015-04-22 13:56:20 -07002926 catch_method_(nullptr),
2927 throw_method_(nullptr),
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002928 catch_dex_pc_(DexFile::kDexNoIndex),
2929 throw_dex_pc_(DexFile::kDexNoIndex) {
2930 }
2931
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002932 bool VisitFrame() OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002933 ArtMethod* method = GetMethod();
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002934 DCHECK(method != nullptr);
2935 if (method->IsRuntimeMethod()) {
2936 // Ignore callee save method.
2937 DCHECK(method->IsCalleeSaveMethod());
2938 return true;
2939 }
2940
2941 uint32_t dex_pc = GetDexPc();
Mathieu Chartiere401d142015-04-22 13:56:20 -07002942 if (throw_method_ == nullptr) {
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002943 // First Java method found. It is either the method that threw the exception,
2944 // or the Java native method that is reporting an exception thrown by
2945 // native code.
2946 this_at_throw_.Assign(GetThisObject());
Mathieu Chartiere401d142015-04-22 13:56:20 -07002947 throw_method_ = method;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002948 throw_dex_pc_ = dex_pc;
2949 }
2950
2951 if (dex_pc != DexFile::kDexNoIndex) {
Sebastien Hertz26f72862015-09-15 09:52:07 +02002952 StackHandleScope<1> hs(GetThread());
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002953 uint32_t found_dex_pc;
2954 Handle<mirror::Class> exception_class(hs.NewHandle(exception_->GetClass()));
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002955 bool unused_clear_exception;
Mathieu Chartiere401d142015-04-22 13:56:20 -07002956 found_dex_pc = method->FindCatchBlock(exception_class, dex_pc, &unused_clear_exception);
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002957 if (found_dex_pc != DexFile::kDexNoIndex) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002958 catch_method_ = method;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002959 catch_dex_pc_ = found_dex_pc;
2960 return false; // End stack walk.
2961 }
2962 }
2963 return true; // Continue stack walk.
2964 }
2965
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002966 ArtMethod* GetCatchMethod() REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002967 return catch_method_;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002968 }
2969
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002970 ArtMethod* GetThrowMethod() REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002971 return throw_method_;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002972 }
2973
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002974 mirror::Object* GetThisAtThrow() REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002975 return this_at_throw_.Get();
2976 }
2977
2978 uint32_t GetCatchDexPc() const {
2979 return catch_dex_pc_;
2980 }
2981
2982 uint32_t GetThrowDexPc() const {
2983 return throw_dex_pc_;
2984 }
2985
2986 private:
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002987 const Handle<mirror::Throwable>& exception_;
Mathieu Chartiere401d142015-04-22 13:56:20 -07002988 StackHandleScope<1> handle_scope_;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002989 MutableHandle<mirror::Object> this_at_throw_;
Mathieu Chartiere401d142015-04-22 13:56:20 -07002990 ArtMethod* catch_method_;
2991 ArtMethod* throw_method_;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002992 uint32_t catch_dex_pc_;
2993 uint32_t throw_dex_pc_;
2994
2995 DISALLOW_COPY_AND_ASSIGN(CatchLocationFinder);
2996};
2997
2998void Dbg::PostException(mirror::Throwable* exception_object) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002999 if (!IsDebuggerActive()) {
Ian Rogers0ad5bb82011-12-07 10:16:32 -08003000 return;
3001 }
Sebastien Hertz261bc042015-04-08 09:36:07 +02003002 Thread* const self = Thread::Current();
3003 StackHandleScope<1> handle_scope(self);
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003004 Handle<mirror::Throwable> h_exception(handle_scope.NewHandle(exception_object));
3005 std::unique_ptr<Context> context(Context::Create());
Sebastien Hertz261bc042015-04-08 09:36:07 +02003006 CatchLocationFinder clf(self, h_exception, context.get());
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003007 clf.WalkStack(/* include_transitions */ false);
Sebastien Hertz6995c602014-09-09 12:10:13 +02003008 JDWP::EventLocation exception_throw_location;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003009 SetEventLocation(&exception_throw_location, clf.GetThrowMethod(), clf.GetThrowDexPc());
Sebastien Hertz6995c602014-09-09 12:10:13 +02003010 JDWP::EventLocation exception_catch_location;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003011 SetEventLocation(&exception_catch_location, clf.GetCatchMethod(), clf.GetCatchDexPc());
Elliott Hughes4740cdf2011-12-07 14:07:12 -08003012
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003013 gJdwpState->PostException(&exception_throw_location, h_exception.Get(), &exception_catch_location,
3014 clf.GetThisAtThrow());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003015}
3016
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003017void Dbg::PostClassPrepare(mirror::Class* c) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07003018 if (!IsDebuggerActive()) {
Elliott Hughes4740cdf2011-12-07 14:07:12 -08003019 return;
3020 }
Sebastien Hertz6995c602014-09-09 12:10:13 +02003021 gJdwpState->PostClassPrepare(c);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003022}
3023
Ian Rogers62d6c772013-02-27 08:32:07 -08003024void Dbg::UpdateDebugger(Thread* thread, mirror::Object* this_object,
Mathieu Chartiere401d142015-04-22 13:56:20 -07003025 ArtMethod* m, uint32_t dex_pc,
Sebastien Hertz8379b222014-02-24 17:38:15 +01003026 int event_flags, const JValue* return_value) {
Ian Rogers62d6c772013-02-27 08:32:07 -08003027 if (!IsDebuggerActive() || dex_pc == static_cast<uint32_t>(-2) /* fake method exit */) {
Elliott Hughes2aa2e392012-02-17 17:15:43 -08003028 return;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003029 }
3030
Elliott Hughes86964332012-02-15 19:37:42 -08003031 if (IsBreakpoint(m, dex_pc)) {
3032 event_flags |= kBreakpoint;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003033 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003034
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003035 // If the debugger is single-stepping one of our threads, check to
3036 // see if we're that thread and we've reached a step point.
3037 const SingleStepControl* single_step_control = thread->GetSingleStepControl();
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003038 if (single_step_control != nullptr) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003039 CHECK(!m->IsNative());
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003040 if (single_step_control->GetStepDepth() == JDWP::SD_INTO) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003041 // Step into method calls. We break when the line number
3042 // or method pointer changes. If we're in SS_MIN mode, we
3043 // always stop.
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003044 if (single_step_control->GetMethod() != m) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003045 event_flags |= kSingleStep;
3046 VLOG(jdwp) << "SS new method";
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003047 } else if (single_step_control->GetStepSize() == JDWP::SS_MIN) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003048 event_flags |= kSingleStep;
3049 VLOG(jdwp) << "SS new instruction";
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003050 } else if (single_step_control->ContainsDexPc(dex_pc)) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003051 event_flags |= kSingleStep;
3052 VLOG(jdwp) << "SS new line";
3053 }
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003054 } else if (single_step_control->GetStepDepth() == JDWP::SD_OVER) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003055 // Step over method calls. We break when the line number is
3056 // different and the frame depth is <= the original frame
3057 // depth. (We can't just compare on the method, because we
3058 // might get unrolled past it by an exception, and it's tricky
3059 // to identify recursion.)
3060
3061 int stack_depth = GetStackDepth(thread);
3062
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003063 if (stack_depth < single_step_control->GetStackDepth()) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003064 // Popped up one or more frames, always trigger.
3065 event_flags |= kSingleStep;
3066 VLOG(jdwp) << "SS method pop";
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003067 } else if (stack_depth == single_step_control->GetStackDepth()) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003068 // Same depth, see if we moved.
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003069 if (single_step_control->GetStepSize() == JDWP::SS_MIN) {
Elliott Hughes86964332012-02-15 19:37:42 -08003070 event_flags |= kSingleStep;
3071 VLOG(jdwp) << "SS new instruction";
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003072 } else if (single_step_control->ContainsDexPc(dex_pc)) {
Elliott Hughes2435a572012-02-17 16:07:41 -08003073 event_flags |= kSingleStep;
3074 VLOG(jdwp) << "SS new line";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003075 }
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003076 }
3077 } else {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003078 CHECK_EQ(single_step_control->GetStepDepth(), JDWP::SD_OUT);
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003079 // Return from the current method. We break when the frame
3080 // depth pops up.
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003081
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003082 // This differs from the "method exit" break in that it stops
3083 // with the PC at the next instruction in the returned-to
3084 // function, rather than the end of the returning function.
Elliott Hughes86964332012-02-15 19:37:42 -08003085
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003086 int stack_depth = GetStackDepth(thread);
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003087 if (stack_depth < single_step_control->GetStackDepth()) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003088 event_flags |= kSingleStep;
3089 VLOG(jdwp) << "SS method pop";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003090 }
3091 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003092 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003093
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003094 // If there's something interesting going on, see if it matches one
3095 // of the debugger filters.
3096 if (event_flags != 0) {
Sebastien Hertz8379b222014-02-24 17:38:15 +01003097 Dbg::PostLocationEvent(m, dex_pc, this_object, event_flags, return_value);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003098 }
3099}
3100
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003101size_t* Dbg::GetReferenceCounterForEvent(uint32_t instrumentation_event) {
3102 switch (instrumentation_event) {
3103 case instrumentation::Instrumentation::kMethodEntered:
3104 return &method_enter_event_ref_count_;
3105 case instrumentation::Instrumentation::kMethodExited:
3106 return &method_exit_event_ref_count_;
3107 case instrumentation::Instrumentation::kDexPcMoved:
3108 return &dex_pc_change_event_ref_count_;
3109 case instrumentation::Instrumentation::kFieldRead:
3110 return &field_read_event_ref_count_;
3111 case instrumentation::Instrumentation::kFieldWritten:
3112 return &field_write_event_ref_count_;
3113 case instrumentation::Instrumentation::kExceptionCaught:
3114 return &exception_catch_event_ref_count_;
3115 default:
3116 return nullptr;
3117 }
3118}
3119
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003120// Process request while all mutator threads are suspended.
3121void Dbg::ProcessDeoptimizationRequest(const DeoptimizationRequest& request) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003122 instrumentation::Instrumentation* instrumentation = Runtime::Current()->GetInstrumentation();
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003123 switch (request.GetKind()) {
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003124 case DeoptimizationRequest::kNothing:
3125 LOG(WARNING) << "Ignoring empty deoptimization request.";
3126 break;
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003127 case DeoptimizationRequest::kRegisterForEvent:
3128 VLOG(jdwp) << StringPrintf("Add debugger as listener for instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003129 request.InstrumentationEvent());
3130 instrumentation->AddListener(&gDebugInstrumentationListener, request.InstrumentationEvent());
3131 instrumentation_events_ |= request.InstrumentationEvent();
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003132 break;
3133 case DeoptimizationRequest::kUnregisterForEvent:
3134 VLOG(jdwp) << StringPrintf("Remove debugger as listener for instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003135 request.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003136 instrumentation->RemoveListener(&gDebugInstrumentationListener,
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003137 request.InstrumentationEvent());
3138 instrumentation_events_ &= ~request.InstrumentationEvent();
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003139 break;
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003140 case DeoptimizationRequest::kFullDeoptimization:
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003141 VLOG(jdwp) << "Deoptimize the world ...";
Sebastien Hertz0462c4c2015-04-01 16:34:17 +02003142 instrumentation->DeoptimizeEverything(kDbgInstrumentationKey);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003143 VLOG(jdwp) << "Deoptimize the world DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003144 break;
3145 case DeoptimizationRequest::kFullUndeoptimization:
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003146 VLOG(jdwp) << "Undeoptimize the world ...";
Sebastien Hertz0462c4c2015-04-01 16:34:17 +02003147 instrumentation->UndeoptimizeEverything(kDbgInstrumentationKey);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003148 VLOG(jdwp) << "Undeoptimize the world DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003149 break;
3150 case DeoptimizationRequest::kSelectiveDeoptimization:
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003151 VLOG(jdwp) << "Deoptimize method " << PrettyMethod(request.Method()) << " ...";
3152 instrumentation->Deoptimize(request.Method());
3153 VLOG(jdwp) << "Deoptimize method " << PrettyMethod(request.Method()) << " DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003154 break;
3155 case DeoptimizationRequest::kSelectiveUndeoptimization:
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003156 VLOG(jdwp) << "Undeoptimize method " << PrettyMethod(request.Method()) << " ...";
3157 instrumentation->Undeoptimize(request.Method());
3158 VLOG(jdwp) << "Undeoptimize method " << PrettyMethod(request.Method()) << " DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003159 break;
3160 default:
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003161 LOG(FATAL) << "Unsupported deoptimization request kind " << request.GetKind();
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003162 break;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003163 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003164}
3165
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003166void Dbg::RequestDeoptimization(const DeoptimizationRequest& req) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003167 if (req.GetKind() == DeoptimizationRequest::kNothing) {
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003168 // Nothing to do.
3169 return;
3170 }
Brian Carlstrom306db812014-09-05 13:01:41 -07003171 MutexLock mu(Thread::Current(), *Locks::deoptimization_lock_);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003172 RequestDeoptimizationLocked(req);
3173}
3174
3175void Dbg::RequestDeoptimizationLocked(const DeoptimizationRequest& req) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003176 switch (req.GetKind()) {
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003177 case DeoptimizationRequest::kRegisterForEvent: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003178 DCHECK_NE(req.InstrumentationEvent(), 0u);
3179 size_t* counter = GetReferenceCounterForEvent(req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003180 CHECK(counter != nullptr) << StringPrintf("No counter for instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003181 req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003182 if (*counter == 0) {
Sebastien Hertz7d2ae432014-05-15 11:26:34 +02003183 VLOG(jdwp) << StringPrintf("Queue request #%zd to start listening to instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003184 deoptimization_requests_.size(), req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003185 deoptimization_requests_.push_back(req);
3186 }
3187 *counter = *counter + 1;
3188 break;
3189 }
3190 case DeoptimizationRequest::kUnregisterForEvent: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003191 DCHECK_NE(req.InstrumentationEvent(), 0u);
3192 size_t* counter = GetReferenceCounterForEvent(req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003193 CHECK(counter != nullptr) << StringPrintf("No counter for instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003194 req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003195 *counter = *counter - 1;
3196 if (*counter == 0) {
Sebastien Hertz7d2ae432014-05-15 11:26:34 +02003197 VLOG(jdwp) << StringPrintf("Queue request #%zd to stop listening to instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003198 deoptimization_requests_.size(), req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003199 deoptimization_requests_.push_back(req);
3200 }
3201 break;
3202 }
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003203 case DeoptimizationRequest::kFullDeoptimization: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003204 DCHECK(req.Method() == nullptr);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003205 if (full_deoptimization_event_count_ == 0) {
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003206 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
3207 << " for full deoptimization";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003208 deoptimization_requests_.push_back(req);
3209 }
3210 ++full_deoptimization_event_count_;
3211 break;
3212 }
3213 case DeoptimizationRequest::kFullUndeoptimization: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003214 DCHECK(req.Method() == nullptr);
Sebastien Hertze713d932014-05-15 10:48:53 +02003215 DCHECK_GT(full_deoptimization_event_count_, 0U);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003216 --full_deoptimization_event_count_;
3217 if (full_deoptimization_event_count_ == 0) {
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003218 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
3219 << " for full undeoptimization";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003220 deoptimization_requests_.push_back(req);
3221 }
3222 break;
3223 }
3224 case DeoptimizationRequest::kSelectiveDeoptimization: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003225 DCHECK(req.Method() != nullptr);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003226 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003227 << " for deoptimization of " << PrettyMethod(req.Method());
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003228 deoptimization_requests_.push_back(req);
3229 break;
3230 }
3231 case DeoptimizationRequest::kSelectiveUndeoptimization: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003232 DCHECK(req.Method() != nullptr);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003233 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003234 << " for undeoptimization of " << PrettyMethod(req.Method());
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003235 deoptimization_requests_.push_back(req);
3236 break;
3237 }
3238 default: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003239 LOG(FATAL) << "Unknown deoptimization request kind " << req.GetKind();
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003240 break;
3241 }
3242 }
3243}
3244
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003245void Dbg::ManageDeoptimization() {
3246 Thread* const self = Thread::Current();
3247 {
3248 // Avoid suspend/resume if there is no pending request.
Brian Carlstrom306db812014-09-05 13:01:41 -07003249 MutexLock mu(self, *Locks::deoptimization_lock_);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003250 if (deoptimization_requests_.empty()) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003251 return;
3252 }
3253 }
3254 CHECK_EQ(self->GetState(), kRunnable);
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07003255 ScopedThreadSuspension sts(self, kWaitingForDeoptimization);
Mathieu Chartieraa516822015-10-02 15:53:37 -07003256 // Required for ProcessDeoptimizationRequest.
3257 gc::ScopedGCCriticalSection gcs(self,
3258 gc::kGcCauseInstrumentation,
3259 gc::kCollectorTypeInstrumentation);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003260 // We need to suspend mutator threads first.
Mathieu Chartier4f55e222015-09-04 13:26:21 -07003261 ScopedSuspendAll ssa(__FUNCTION__);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003262 const ThreadState old_state = self->SetStateUnsafe(kRunnable);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003263 {
Brian Carlstrom306db812014-09-05 13:01:41 -07003264 MutexLock mu(self, *Locks::deoptimization_lock_);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003265 size_t req_index = 0;
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003266 for (DeoptimizationRequest& request : deoptimization_requests_) {
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003267 VLOG(jdwp) << "Process deoptimization request #" << req_index++;
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003268 ProcessDeoptimizationRequest(request);
3269 }
3270 deoptimization_requests_.clear();
3271 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003272 CHECK_EQ(self->SetStateUnsafe(old_state), kRunnable);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003273}
3274
Mathieu Chartiere401d142015-04-22 13:56:20 -07003275static const Breakpoint* FindFirstBreakpointForMethod(ArtMethod* m)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003276 REQUIRES_SHARED(Locks::mutator_lock_, Locks::breakpoint_lock_) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003277 for (Breakpoint& breakpoint : gBreakpoints) {
Alex Light6c8467f2015-11-20 15:03:26 -08003278 if (breakpoint.IsInMethod(m)) {
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003279 return &breakpoint;
3280 }
3281 }
3282 return nullptr;
3283}
3284
Mathieu Chartiere401d142015-04-22 13:56:20 -07003285bool Dbg::MethodHasAnyBreakpoints(ArtMethod* method) {
Mathieu Chartierd8565452015-03-26 09:41:50 -07003286 ReaderMutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
3287 return FindFirstBreakpointForMethod(method) != nullptr;
3288}
3289
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003290// Sanity checks all existing breakpoints on the same method.
Mathieu Chartiere401d142015-04-22 13:56:20 -07003291static void SanityCheckExistingBreakpoints(ArtMethod* m,
Sebastien Hertzf3928792014-11-17 19:00:37 +01003292 DeoptimizationRequest::Kind deoptimization_kind)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003293 REQUIRES_SHARED(Locks::mutator_lock_, Locks::breakpoint_lock_) {
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003294 for (const Breakpoint& breakpoint : gBreakpoints) {
Alex Light6c8467f2015-11-20 15:03:26 -08003295 if (breakpoint.IsInMethod(m)) {
Sebastien Hertzf3928792014-11-17 19:00:37 +01003296 CHECK_EQ(deoptimization_kind, breakpoint.GetDeoptimizationKind());
3297 }
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003298 }
Sebastien Hertzf3928792014-11-17 19:00:37 +01003299 instrumentation::Instrumentation* instrumentation = Runtime::Current()->GetInstrumentation();
3300 if (deoptimization_kind == DeoptimizationRequest::kFullDeoptimization) {
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003301 // We should have deoptimized everything but not "selectively" deoptimized this method.
Sebastien Hertzf3928792014-11-17 19:00:37 +01003302 CHECK(instrumentation->AreAllMethodsDeoptimized());
3303 CHECK(!instrumentation->IsDeoptimized(m));
3304 } else if (deoptimization_kind == DeoptimizationRequest::kSelectiveDeoptimization) {
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003305 // We should have "selectively" deoptimized this method.
3306 // Note: while we have not deoptimized everything for this method, we may have done it for
3307 // another event.
Sebastien Hertzf3928792014-11-17 19:00:37 +01003308 CHECK(instrumentation->IsDeoptimized(m));
3309 } else {
3310 // This method does not require deoptimization.
3311 CHECK_EQ(deoptimization_kind, DeoptimizationRequest::kNothing);
3312 CHECK(!instrumentation->IsDeoptimized(m));
3313 }
3314}
3315
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003316// Returns the deoptimization kind required to set a breakpoint in a method.
3317// If a breakpoint has already been set, we also return the first breakpoint
3318// through the given 'existing_brkpt' pointer.
Sebastien Hertzf3928792014-11-17 19:00:37 +01003319static DeoptimizationRequest::Kind GetRequiredDeoptimizationKind(Thread* self,
Mathieu Chartiere401d142015-04-22 13:56:20 -07003320 ArtMethod* m,
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003321 const Breakpoint** existing_brkpt)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003322 REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertzf3928792014-11-17 19:00:37 +01003323 if (!Dbg::RequiresDeoptimization()) {
3324 // We already run in interpreter-only mode so we don't need to deoptimize anything.
3325 VLOG(jdwp) << "No need for deoptimization when fully running with interpreter for method "
3326 << PrettyMethod(m);
3327 return DeoptimizationRequest::kNothing;
3328 }
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003329 const Breakpoint* first_breakpoint;
Sebastien Hertzf3928792014-11-17 19:00:37 +01003330 {
3331 ReaderMutexLock mu(self, *Locks::breakpoint_lock_);
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003332 first_breakpoint = FindFirstBreakpointForMethod(m);
3333 *existing_brkpt = first_breakpoint;
Sebastien Hertzf3928792014-11-17 19:00:37 +01003334 }
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003335
3336 if (first_breakpoint == nullptr) {
Nicolas Geoffray6300fd72016-03-18 09:40:17 +00003337 // There is no breakpoint on this method yet: we need to deoptimize. If this method is default,
3338 // we deoptimize everything; otherwise we deoptimize only this method. We
Alex Light6c8467f2015-11-20 15:03:26 -08003339 // deoptimize with defaults because we do not know everywhere they are used. It is possible some
Nicolas Geoffray6300fd72016-03-18 09:40:17 +00003340 // of the copies could be missed.
Alex Light6c8467f2015-11-20 15:03:26 -08003341 // TODO Deoptimizing on default methods might not be necessary in all cases.
Nicolas Geoffray6300fd72016-03-18 09:40:17 +00003342 bool need_full_deoptimization = m->IsDefault();
Sebastien Hertzf3928792014-11-17 19:00:37 +01003343 if (need_full_deoptimization) {
Nicolas Geoffray6300fd72016-03-18 09:40:17 +00003344 VLOG(jdwp) << "Need full deoptimization because of copying of method "
Sebastien Hertzf3928792014-11-17 19:00:37 +01003345 << PrettyMethod(m);
3346 return DeoptimizationRequest::kFullDeoptimization;
3347 } else {
3348 // We don't need to deoptimize if the method has not been compiled.
Nicolas Geoffraya5891e82015-11-06 14:18:27 +00003349 const bool is_compiled = m->HasAnyCompiledCode();
Sebastien Hertzf3928792014-11-17 19:00:37 +01003350 if (is_compiled) {
Nicolas Geoffray6300fd72016-03-18 09:40:17 +00003351 VLOG(jdwp) << "Need selective deoptimization for compiled method " << PrettyMethod(m);
3352 return DeoptimizationRequest::kSelectiveDeoptimization;
Sebastien Hertzf3928792014-11-17 19:00:37 +01003353 } else {
3354 // Method is not compiled: we don't need to deoptimize.
3355 VLOG(jdwp) << "No need for deoptimization for non-compiled method " << PrettyMethod(m);
3356 return DeoptimizationRequest::kNothing;
3357 }
3358 }
3359 } else {
3360 // There is at least one breakpoint for this method: we don't need to deoptimize.
3361 // Let's check that all breakpoints are configured the same way for deoptimization.
3362 VLOG(jdwp) << "Breakpoint already set: no deoptimization is required";
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003363 DeoptimizationRequest::Kind deoptimization_kind = first_breakpoint->GetDeoptimizationKind();
Sebastien Hertzf3928792014-11-17 19:00:37 +01003364 if (kIsDebugBuild) {
3365 ReaderMutexLock mu(self, *Locks::breakpoint_lock_);
3366 SanityCheckExistingBreakpoints(m, deoptimization_kind);
3367 }
3368 return DeoptimizationRequest::kNothing;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003369 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003370}
3371
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003372// Installs a breakpoint at the specified location. Also indicates through the deoptimization
3373// request if we need to deoptimize.
3374void Dbg::WatchLocation(const JDWP::JdwpLocation* location, DeoptimizationRequest* req) {
3375 Thread* const self = Thread::Current();
Mathieu Chartiere401d142015-04-22 13:56:20 -07003376 ArtMethod* m = FromMethodId(location->method_id);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003377 DCHECK(m != nullptr) << "No method for method id " << location->method_id;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003378
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003379 const Breakpoint* existing_breakpoint = nullptr;
3380 const DeoptimizationRequest::Kind deoptimization_kind =
3381 GetRequiredDeoptimizationKind(self, m, &existing_breakpoint);
Sebastien Hertzf3928792014-11-17 19:00:37 +01003382 req->SetKind(deoptimization_kind);
3383 if (deoptimization_kind == DeoptimizationRequest::kSelectiveDeoptimization) {
3384 req->SetMethod(m);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003385 } else {
Sebastien Hertzf3928792014-11-17 19:00:37 +01003386 CHECK(deoptimization_kind == DeoptimizationRequest::kNothing ||
3387 deoptimization_kind == DeoptimizationRequest::kFullDeoptimization);
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003388 req->SetMethod(nullptr);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003389 }
3390
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003391 {
3392 WriterMutexLock mu(self, *Locks::breakpoint_lock_);
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003393 // If there is at least one existing breakpoint on the same method, the new breakpoint
3394 // must have the same deoptimization kind than the existing breakpoint(s).
3395 DeoptimizationRequest::Kind breakpoint_deoptimization_kind;
3396 if (existing_breakpoint != nullptr) {
3397 breakpoint_deoptimization_kind = existing_breakpoint->GetDeoptimizationKind();
3398 } else {
3399 breakpoint_deoptimization_kind = deoptimization_kind;
3400 }
3401 gBreakpoints.push_back(Breakpoint(m, location->dex_pc, breakpoint_deoptimization_kind));
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003402 VLOG(jdwp) << "Set breakpoint #" << (gBreakpoints.size() - 1) << ": "
3403 << gBreakpoints[gBreakpoints.size() - 1];
3404 }
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003405}
3406
3407// Uninstalls a breakpoint at the specified location. Also indicates through the deoptimization
3408// request if we need to undeoptimize.
3409void Dbg::UnwatchLocation(const JDWP::JdwpLocation* location, DeoptimizationRequest* req) {
Sebastien Hertzed2be172014-08-19 15:33:43 +02003410 WriterMutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003411 ArtMethod* m = FromMethodId(location->method_id);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003412 DCHECK(m != nullptr) << "No method for method id " << location->method_id;
Sebastien Hertzf3928792014-11-17 19:00:37 +01003413 DeoptimizationRequest::Kind deoptimization_kind = DeoptimizationRequest::kNothing;
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003414 for (size_t i = 0, e = gBreakpoints.size(); i < e; ++i) {
Alex Light6c8467f2015-11-20 15:03:26 -08003415 if (gBreakpoints[i].DexPc() == location->dex_pc && gBreakpoints[i].IsInMethod(m)) {
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003416 VLOG(jdwp) << "Removed breakpoint #" << i << ": " << gBreakpoints[i];
Sebastien Hertzf3928792014-11-17 19:00:37 +01003417 deoptimization_kind = gBreakpoints[i].GetDeoptimizationKind();
3418 DCHECK_EQ(deoptimization_kind == DeoptimizationRequest::kSelectiveDeoptimization,
3419 Runtime::Current()->GetInstrumentation()->IsDeoptimized(m));
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003420 gBreakpoints.erase(gBreakpoints.begin() + i);
3421 break;
3422 }
3423 }
3424 const Breakpoint* const existing_breakpoint = FindFirstBreakpointForMethod(m);
3425 if (existing_breakpoint == nullptr) {
3426 // There is no more breakpoint on this method: we need to undeoptimize.
Sebastien Hertzf3928792014-11-17 19:00:37 +01003427 if (deoptimization_kind == DeoptimizationRequest::kFullDeoptimization) {
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003428 // This method required full deoptimization: we need to undeoptimize everything.
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003429 req->SetKind(DeoptimizationRequest::kFullUndeoptimization);
3430 req->SetMethod(nullptr);
Sebastien Hertzf3928792014-11-17 19:00:37 +01003431 } else if (deoptimization_kind == DeoptimizationRequest::kSelectiveDeoptimization) {
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003432 // This method required selective deoptimization: we need to undeoptimize only that method.
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003433 req->SetKind(DeoptimizationRequest::kSelectiveUndeoptimization);
3434 req->SetMethod(m);
Sebastien Hertzf3928792014-11-17 19:00:37 +01003435 } else {
3436 // This method had no need for deoptimization: do nothing.
3437 CHECK_EQ(deoptimization_kind, DeoptimizationRequest::kNothing);
3438 req->SetKind(DeoptimizationRequest::kNothing);
3439 req->SetMethod(nullptr);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003440 }
3441 } else {
3442 // There is at least one breakpoint for this method: we don't need to undeoptimize.
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003443 req->SetKind(DeoptimizationRequest::kNothing);
3444 req->SetMethod(nullptr);
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003445 if (kIsDebugBuild) {
Sebastien Hertzf3928792014-11-17 19:00:37 +01003446 SanityCheckExistingBreakpoints(m, deoptimization_kind);
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003447 }
Elliott Hughes86964332012-02-15 19:37:42 -08003448 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003449}
3450
Mathieu Chartiere401d142015-04-22 13:56:20 -07003451bool Dbg::IsForcedInterpreterNeededForCallingImpl(Thread* thread, ArtMethod* m) {
Daniel Mihalyieb076692014-08-22 17:33:31 +02003452 const SingleStepControl* const ssc = thread->GetSingleStepControl();
3453 if (ssc == nullptr) {
3454 // If we are not single-stepping, then we don't have to force interpreter.
3455 return false;
3456 }
3457 if (Runtime::Current()->GetInstrumentation()->InterpretOnly()) {
3458 // If we are in interpreter only mode, then we don't have to force interpreter.
3459 return false;
3460 }
3461
3462 if (!m->IsNative() && !m->IsProxyMethod()) {
3463 // If we want to step into a method, then we have to force interpreter on that call.
3464 if (ssc->GetStepDepth() == JDWP::SD_INTO) {
3465 return true;
3466 }
3467 }
3468 return false;
3469}
3470
Mathieu Chartiere401d142015-04-22 13:56:20 -07003471bool Dbg::IsForcedInterpreterNeededForResolutionImpl(Thread* thread, ArtMethod* m) {
Daniel Mihalyieb076692014-08-22 17:33:31 +02003472 instrumentation::Instrumentation* const instrumentation =
3473 Runtime::Current()->GetInstrumentation();
3474 // If we are in interpreter only mode, then we don't have to force interpreter.
3475 if (instrumentation->InterpretOnly()) {
3476 return false;
3477 }
3478 // We can only interpret pure Java method.
3479 if (m->IsNative() || m->IsProxyMethod()) {
3480 return false;
3481 }
3482 const SingleStepControl* const ssc = thread->GetSingleStepControl();
3483 if (ssc != nullptr) {
3484 // If we want to step into a method, then we have to force interpreter on that call.
3485 if (ssc->GetStepDepth() == JDWP::SD_INTO) {
3486 return true;
3487 }
3488 // If we are stepping out from a static initializer, by issuing a step
3489 // in or step over, that was implicitly invoked by calling a static method,
3490 // then we need to step into that method. Having a lower stack depth than
3491 // the one the single step control has indicates that the step originates
3492 // from the static initializer.
3493 if (ssc->GetStepDepth() != JDWP::SD_OUT &&
3494 ssc->GetStackDepth() > GetStackDepth(thread)) {
3495 return true;
3496 }
3497 }
3498 // There are cases where we have to force interpreter on deoptimized methods,
3499 // because in some cases the call will not be performed by invoking an entry
3500 // point that has been replaced by the deoptimization, but instead by directly
3501 // invoking the compiled code of the method, for example.
3502 return instrumentation->IsDeoptimized(m);
3503}
3504
Mathieu Chartiere401d142015-04-22 13:56:20 -07003505bool Dbg::IsForcedInstrumentationNeededForResolutionImpl(Thread* thread, ArtMethod* m) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07003506 // The upcall can be null and in that case we don't need to do anything.
Daniel Mihalyieb076692014-08-22 17:33:31 +02003507 if (m == nullptr) {
3508 return false;
3509 }
3510 instrumentation::Instrumentation* const instrumentation =
3511 Runtime::Current()->GetInstrumentation();
3512 // If we are in interpreter only mode, then we don't have to force interpreter.
3513 if (instrumentation->InterpretOnly()) {
3514 return false;
3515 }
3516 // We can only interpret pure Java method.
3517 if (m->IsNative() || m->IsProxyMethod()) {
3518 return false;
3519 }
3520 const SingleStepControl* const ssc = thread->GetSingleStepControl();
3521 if (ssc != nullptr) {
3522 // If we are stepping out from a static initializer, by issuing a step
3523 // out, that was implicitly invoked by calling a static method, then we
3524 // need to step into the caller of that method. Having a lower stack
3525 // depth than the one the single step control has indicates that the
3526 // step originates from the static initializer.
3527 if (ssc->GetStepDepth() == JDWP::SD_OUT &&
3528 ssc->GetStackDepth() > GetStackDepth(thread)) {
3529 return true;
3530 }
3531 }
3532 // If we are returning from a static intializer, that was implicitly
3533 // invoked by calling a static method and the caller is deoptimized,
3534 // then we have to deoptimize the stack without forcing interpreter
3535 // on the static method that was called originally. This problem can
3536 // be solved easily by forcing instrumentation on the called method,
3537 // because the instrumentation exit hook will recognise the need of
3538 // stack deoptimization by calling IsForcedInterpreterNeededForUpcall.
3539 return instrumentation->IsDeoptimized(m);
3540}
3541
Mathieu Chartiere401d142015-04-22 13:56:20 -07003542bool Dbg::IsForcedInterpreterNeededForUpcallImpl(Thread* thread, ArtMethod* m) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07003543 // The upcall can be null and in that case we don't need to do anything.
Daniel Mihalyieb076692014-08-22 17:33:31 +02003544 if (m == nullptr) {
3545 return false;
3546 }
3547 instrumentation::Instrumentation* const instrumentation =
3548 Runtime::Current()->GetInstrumentation();
3549 // If we are in interpreter only mode, then we don't have to force interpreter.
3550 if (instrumentation->InterpretOnly()) {
3551 return false;
3552 }
3553 // We can only interpret pure Java method.
3554 if (m->IsNative() || m->IsProxyMethod()) {
3555 return false;
3556 }
3557 const SingleStepControl* const ssc = thread->GetSingleStepControl();
3558 if (ssc != nullptr) {
3559 // The debugger is not interested in what is happening under the level
3560 // of the step, thus we only force interpreter when we are not below of
3561 // the step.
3562 if (ssc->GetStackDepth() >= GetStackDepth(thread)) {
3563 return true;
3564 }
3565 }
Mingyao Yang99170c62015-07-06 11:10:37 -07003566 if (thread->HasDebuggerShadowFrames()) {
3567 // We need to deoptimize the stack for the exception handling flow so that
3568 // we don't miss any deoptimization that should be done when there are
3569 // debugger shadow frames.
3570 return true;
3571 }
Daniel Mihalyieb076692014-08-22 17:33:31 +02003572 // We have to require stack deoptimization if the upcall is deoptimized.
3573 return instrumentation->IsDeoptimized(m);
3574}
3575
Mingyao Yang99170c62015-07-06 11:10:37 -07003576class NeedsDeoptimizationVisitor : public StackVisitor {
Sebastien Hertz520633b2015-09-08 17:03:36 +02003577 public:
3578 explicit NeedsDeoptimizationVisitor(Thread* self)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003579 REQUIRES_SHARED(Locks::mutator_lock_)
Sebastien Hertz520633b2015-09-08 17:03:36 +02003580 : StackVisitor(self, nullptr, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
3581 needs_deoptimization_(false) {}
3582
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003583 bool VisitFrame() OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz520633b2015-09-08 17:03:36 +02003584 // The visitor is meant to be used when handling exception from compiled code only.
3585 CHECK(!IsShadowFrame()) << "We only expect to visit compiled frame: " << PrettyMethod(GetMethod());
3586 ArtMethod* method = GetMethod();
3587 if (method == nullptr) {
3588 // We reach an upcall and don't need to deoptimize this part of the stack (ManagedFragment)
3589 // so we can stop the visit.
3590 DCHECK(!needs_deoptimization_);
3591 return false;
3592 }
3593 if (Runtime::Current()->GetInstrumentation()->InterpretOnly()) {
3594 // We found a compiled frame in the stack but instrumentation is set to interpret
3595 // everything: we need to deoptimize.
3596 needs_deoptimization_ = true;
3597 return false;
3598 }
3599 if (Runtime::Current()->GetInstrumentation()->IsDeoptimized(method)) {
3600 // We found a deoptimized method in the stack.
3601 needs_deoptimization_ = true;
3602 return false;
3603 }
Mingyao Yang99170c62015-07-06 11:10:37 -07003604 ShadowFrame* frame = GetThread()->FindDebuggerShadowFrame(GetFrameId());
3605 if (frame != nullptr) {
3606 // The debugger allocated a ShadowFrame to update a variable in the stack: we need to
3607 // deoptimize the stack to execute (and deallocate) this frame.
3608 needs_deoptimization_ = true;
3609 return false;
3610 }
Sebastien Hertz520633b2015-09-08 17:03:36 +02003611 return true;
3612 }
3613
3614 bool NeedsDeoptimization() const {
3615 return needs_deoptimization_;
3616 }
3617
3618 private:
3619 // Do we need to deoptimize the stack?
3620 bool needs_deoptimization_;
3621
3622 DISALLOW_COPY_AND_ASSIGN(NeedsDeoptimizationVisitor);
3623};
3624
3625// Do we need to deoptimize the stack to handle an exception?
3626bool Dbg::IsForcedInterpreterNeededForExceptionImpl(Thread* thread) {
3627 const SingleStepControl* const ssc = thread->GetSingleStepControl();
3628 if (ssc != nullptr) {
3629 // We deopt to step into the catch handler.
3630 return true;
3631 }
3632 // Deoptimization is required if at least one method in the stack needs it. However we
3633 // skip frames that will be unwound (thus not executed).
3634 NeedsDeoptimizationVisitor visitor(thread);
3635 visitor.WalkStack(true); // includes upcall.
3636 return visitor.NeedsDeoptimization();
3637}
3638
Jeff Hao449db332013-04-12 18:30:52 -07003639// Scoped utility class to suspend a thread so that we may do tasks such as walk its stack. Doesn't
3640// cause suspension if the thread is the current thread.
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07003641class ScopedDebuggerThreadSuspension {
Jeff Hao449db332013-04-12 18:30:52 -07003642 public:
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07003643 ScopedDebuggerThreadSuspension(Thread* self, JDWP::ObjectId thread_id)
Mathieu Chartier90443472015-07-16 20:32:27 -07003644 REQUIRES(!Locks::thread_list_lock_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003645 REQUIRES_SHARED(Locks::mutator_lock_) :
Ian Rogersf3d874c2014-07-17 18:52:42 -07003646 thread_(nullptr),
Jeff Hao449db332013-04-12 18:30:52 -07003647 error_(JDWP::ERR_NONE),
3648 self_suspend_(false),
Ian Rogers33e95662013-05-20 20:29:14 -07003649 other_suspend_(false) {
Jeff Hao449db332013-04-12 18:30:52 -07003650 ScopedObjectAccessUnchecked soa(self);
Sebastien Hertz69206392015-04-07 15:54:25 +02003651 thread_ = DecodeThread(soa, thread_id, &error_);
Jeff Hao449db332013-04-12 18:30:52 -07003652 if (error_ == JDWP::ERR_NONE) {
3653 if (thread_ == soa.Self()) {
3654 self_suspend_ = true;
3655 } else {
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07003656 Thread* suspended_thread;
3657 {
3658 ScopedThreadSuspension sts(self, kWaitingForDebuggerSuspension);
3659 jobject thread_peer = Dbg::GetObjectRegistry()->GetJObject(thread_id);
3660 bool timed_out;
3661 ThreadList* const thread_list = Runtime::Current()->GetThreadList();
3662 suspended_thread = thread_list->SuspendThreadByPeer(thread_peer, true, true, &timed_out);
3663 }
Ian Rogersf3d874c2014-07-17 18:52:42 -07003664 if (suspended_thread == nullptr) {
Jeff Hao449db332013-04-12 18:30:52 -07003665 // Thread terminated from under us while suspending.
3666 error_ = JDWP::ERR_INVALID_THREAD;
3667 } else {
3668 CHECK_EQ(suspended_thread, thread_);
3669 other_suspend_ = true;
3670 }
3671 }
3672 }
Elliott Hughes2435a572012-02-17 16:07:41 -08003673 }
Elliott Hughes86964332012-02-15 19:37:42 -08003674
Jeff Hao449db332013-04-12 18:30:52 -07003675 Thread* GetThread() const {
3676 return thread_;
3677 }
3678
3679 JDWP::JdwpError GetError() const {
3680 return error_;
3681 }
3682
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07003683 ~ScopedDebuggerThreadSuspension() {
Jeff Hao449db332013-04-12 18:30:52 -07003684 if (other_suspend_) {
3685 Runtime::Current()->GetThreadList()->Resume(thread_, true);
3686 }
3687 }
3688
3689 private:
3690 Thread* thread_;
3691 JDWP::JdwpError error_;
3692 bool self_suspend_;
3693 bool other_suspend_;
3694};
3695
3696JDWP::JdwpError Dbg::ConfigureStep(JDWP::ObjectId thread_id, JDWP::JdwpStepSize step_size,
3697 JDWP::JdwpStepDepth step_depth) {
3698 Thread* self = Thread::Current();
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07003699 ScopedDebuggerThreadSuspension sts(self, thread_id);
Jeff Hao449db332013-04-12 18:30:52 -07003700 if (sts.GetError() != JDWP::ERR_NONE) {
3701 return sts.GetError();
3702 }
3703
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003704 // Work out what ArtMethod* we're in, the current line number, and how deep the stack currently
Elliott Hughes2435a572012-02-17 16:07:41 -08003705 // is for step-out.
Ian Rogers0399dde2012-06-06 17:09:28 -07003706 struct SingleStepStackVisitor : public StackVisitor {
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003707 explicit SingleStepStackVisitor(Thread* thread) REQUIRES_SHARED(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01003708 : StackVisitor(thread, nullptr, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
3709 stack_depth(0),
3710 method(nullptr),
3711 line_number(-1) {}
Ian Rogersca190662012-06-26 15:45:57 -07003712
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003713 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
3714 // annotalysis.
3715 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003716 ArtMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07003717 if (!m->IsRuntimeMethod()) {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003718 ++stack_depth;
3719 if (method == nullptr) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08003720 mirror::DexCache* dex_cache = m->GetDeclaringClass()->GetDexCache();
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003721 method = m;
Ian Rogersc0542af2014-09-03 16:16:56 -07003722 if (dex_cache != nullptr) {
David Sehr9323e6e2016-09-13 08:58:35 -07003723 const DexFile* dex_file = dex_cache->GetDexFile();
3724 line_number = annotations::GetLineNumFromPC(dex_file, m, GetDexPc());
Elliott Hughes2435a572012-02-17 16:07:41 -08003725 }
Elliott Hughes86964332012-02-15 19:37:42 -08003726 }
3727 }
Elliott Hughes530fa002012-03-12 11:44:49 -07003728 return true;
Elliott Hughes86964332012-02-15 19:37:42 -08003729 }
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003730
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003731 int stack_depth;
Mathieu Chartiere401d142015-04-22 13:56:20 -07003732 ArtMethod* method;
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003733 int32_t line_number;
Elliott Hughes86964332012-02-15 19:37:42 -08003734 };
Jeff Hao449db332013-04-12 18:30:52 -07003735
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003736 Thread* const thread = sts.GetThread();
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003737 SingleStepStackVisitor visitor(thread);
Ian Rogers0399dde2012-06-06 17:09:28 -07003738 visitor.WalkStack();
Elliott Hughes86964332012-02-15 19:37:42 -08003739
Elliott Hughes2435a572012-02-17 16:07:41 -08003740 // Find the dex_pc values that correspond to the current line, for line-based single-stepping.
Elliott Hughes2435a572012-02-17 16:07:41 -08003741 struct DebugCallbackContext {
Roland Levillain3887c462015-08-12 18:15:42 +01003742 DebugCallbackContext(SingleStepControl* single_step_control_cb,
3743 int32_t line_number_cb, const DexFile::CodeItem* code_item)
3744 : single_step_control_(single_step_control_cb), line_number_(line_number_cb),
3745 code_item_(code_item), last_pc_valid(false), last_pc(0) {
Elliott Hughes2435a572012-02-17 16:07:41 -08003746 }
3747
David Srbeckyb06e28e2015-12-10 13:15:00 +00003748 static bool Callback(void* raw_context, const DexFile::PositionInfo& entry) {
Elliott Hughes2435a572012-02-17 16:07:41 -08003749 DebugCallbackContext* context = reinterpret_cast<DebugCallbackContext*>(raw_context);
David Srbeckyb06e28e2015-12-10 13:15:00 +00003750 if (static_cast<int32_t>(entry.line_) == context->line_number_) {
Elliott Hughes2435a572012-02-17 16:07:41 -08003751 if (!context->last_pc_valid) {
3752 // Everything from this address until the next line change is ours.
David Srbeckyb06e28e2015-12-10 13:15:00 +00003753 context->last_pc = entry.address_;
Elliott Hughes2435a572012-02-17 16:07:41 -08003754 context->last_pc_valid = true;
3755 }
3756 // Otherwise, if we're already in a valid range for this line,
3757 // just keep going (shouldn't really happen)...
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003758 } else if (context->last_pc_valid) { // and the line number is new
Elliott Hughes2435a572012-02-17 16:07:41 -08003759 // Add everything from the last entry up until here to the set
David Srbeckyb06e28e2015-12-10 13:15:00 +00003760 for (uint32_t dex_pc = context->last_pc; dex_pc < entry.address_; ++dex_pc) {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003761 context->single_step_control_->AddDexPc(dex_pc);
Elliott Hughes2435a572012-02-17 16:07:41 -08003762 }
3763 context->last_pc_valid = false;
3764 }
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003765 return false; // There may be multiple entries for any given line.
Elliott Hughes2435a572012-02-17 16:07:41 -08003766 }
3767
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003768 ~DebugCallbackContext() {
Elliott Hughes2435a572012-02-17 16:07:41 -08003769 // If the line number was the last in the position table...
3770 if (last_pc_valid) {
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003771 size_t end = code_item_->insns_size_in_code_units_;
Elliott Hughes2435a572012-02-17 16:07:41 -08003772 for (uint32_t dex_pc = last_pc; dex_pc < end; ++dex_pc) {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003773 single_step_control_->AddDexPc(dex_pc);
Elliott Hughes2435a572012-02-17 16:07:41 -08003774 }
3775 }
3776 }
3777
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003778 SingleStepControl* const single_step_control_;
3779 const int32_t line_number_;
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003780 const DexFile::CodeItem* const code_item_;
Elliott Hughes2435a572012-02-17 16:07:41 -08003781 bool last_pc_valid;
3782 uint32_t last_pc;
3783 };
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003784
3785 // Allocate single step.
Sebastien Hertz1558b572015-02-25 15:05:59 +01003786 SingleStepControl* single_step_control =
3787 new (std::nothrow) SingleStepControl(step_size, step_depth,
3788 visitor.stack_depth, visitor.method);
3789 if (single_step_control == nullptr) {
3790 LOG(ERROR) << "Failed to allocate SingleStepControl";
3791 return JDWP::ERR_OUT_OF_MEMORY;
3792 }
3793
Mathieu Chartiere401d142015-04-22 13:56:20 -07003794 ArtMethod* m = single_step_control->GetMethod();
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003795 const int32_t line_number = visitor.line_number;
Sebastien Hertz52f5f932015-05-28 11:00:57 +02003796 // Note: if the thread is not running Java code (pure native thread), there is no "current"
3797 // method on the stack (and no line number either).
3798 if (m != nullptr && !m->IsNative()) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003799 const DexFile::CodeItem* const code_item = m->GetCodeItem();
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003800 DebugCallbackContext context(single_step_control, line_number, code_item);
David Srbeckyb06e28e2015-12-10 13:15:00 +00003801 m->GetDexFile()->DecodeDebugPositionInfo(code_item, DebugCallbackContext::Callback, &context);
Elliott Hughes3e2e1a22012-02-21 11:33:41 -08003802 }
Elliott Hughes2435a572012-02-17 16:07:41 -08003803
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003804 // Activate single-step in the thread.
3805 thread->ActivateSingleStepControl(single_step_control);
Elliott Hughes86964332012-02-15 19:37:42 -08003806
Elliott Hughes2435a572012-02-17 16:07:41 -08003807 if (VLOG_IS_ON(jdwp)) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003808 VLOG(jdwp) << "Single-step thread: " << *thread;
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003809 VLOG(jdwp) << "Single-step step size: " << single_step_control->GetStepSize();
3810 VLOG(jdwp) << "Single-step step depth: " << single_step_control->GetStepDepth();
3811 VLOG(jdwp) << "Single-step current method: " << PrettyMethod(single_step_control->GetMethod());
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003812 VLOG(jdwp) << "Single-step current line: " << line_number;
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003813 VLOG(jdwp) << "Single-step current stack depth: " << single_step_control->GetStackDepth();
Elliott Hughes2435a572012-02-17 16:07:41 -08003814 VLOG(jdwp) << "Single-step dex_pc values:";
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003815 for (uint32_t dex_pc : single_step_control->GetDexPcs()) {
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003816 VLOG(jdwp) << StringPrintf(" %#x", dex_pc);
Elliott Hughes2435a572012-02-17 16:07:41 -08003817 }
3818 }
3819
3820 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003821}
3822
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003823void Dbg::UnconfigureStep(JDWP::ObjectId thread_id) {
3824 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07003825 JDWP::JdwpError error;
3826 Thread* thread = DecodeThread(soa, thread_id, &error);
Sebastien Hertz87118ed2013-11-26 17:57:18 +01003827 if (error == JDWP::ERR_NONE) {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003828 thread->DeactivateSingleStepControl();
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003829 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003830}
3831
Elliott Hughes45651fd2012-02-21 15:48:20 -08003832static char JdwpTagToShortyChar(JDWP::JdwpTag tag) {
3833 switch (tag) {
3834 default:
3835 LOG(FATAL) << "unknown JDWP tag: " << PrintableChar(tag);
Ian Rogersfc787ec2014-10-09 21:56:44 -07003836 UNREACHABLE();
Elliott Hughes45651fd2012-02-21 15:48:20 -08003837
3838 // Primitives.
3839 case JDWP::JT_BYTE: return 'B';
3840 case JDWP::JT_CHAR: return 'C';
3841 case JDWP::JT_FLOAT: return 'F';
3842 case JDWP::JT_DOUBLE: return 'D';
3843 case JDWP::JT_INT: return 'I';
3844 case JDWP::JT_LONG: return 'J';
3845 case JDWP::JT_SHORT: return 'S';
3846 case JDWP::JT_VOID: return 'V';
3847 case JDWP::JT_BOOLEAN: return 'Z';
3848
3849 // Reference types.
3850 case JDWP::JT_ARRAY:
3851 case JDWP::JT_OBJECT:
3852 case JDWP::JT_STRING:
3853 case JDWP::JT_THREAD:
3854 case JDWP::JT_THREAD_GROUP:
3855 case JDWP::JT_CLASS_LOADER:
3856 case JDWP::JT_CLASS_OBJECT:
3857 return 'L';
3858 }
3859}
3860
Sebastien Hertzcbc50642015-06-01 17:33:12 +02003861JDWP::JdwpError Dbg::PrepareInvokeMethod(uint32_t request_id, JDWP::ObjectId thread_id,
3862 JDWP::ObjectId object_id, JDWP::RefTypeId class_id,
3863 JDWP::MethodId method_id, uint32_t arg_count,
3864 uint64_t arg_values[], JDWP::JdwpTag* arg_types,
3865 uint32_t options) {
3866 Thread* const self = Thread::Current();
3867 CHECK_EQ(self, GetDebugThread()) << "This must be called by the JDWP thread";
Sebastien Hertzd4032e42015-06-12 15:47:34 +02003868 const bool resume_all_threads = ((options & JDWP::INVOKE_SINGLE_THREADED) == 0);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003869
Sebastien Hertzcbc50642015-06-01 17:33:12 +02003870 ThreadList* thread_list = Runtime::Current()->GetThreadList();
Ian Rogersc0542af2014-09-03 16:16:56 -07003871 Thread* targetThread = nullptr;
Elliott Hughesd07986f2011-12-06 18:27:45 -08003872 {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003873 ScopedObjectAccessUnchecked soa(self);
Ian Rogersc0542af2014-09-03 16:16:56 -07003874 JDWP::JdwpError error;
3875 targetThread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08003876 if (error != JDWP::ERR_NONE) {
3877 LOG(ERROR) << "InvokeMethod request for invalid thread id " << thread_id;
3878 return error;
Elliott Hughesd07986f2011-12-06 18:27:45 -08003879 }
Sebastien Hertz1558b572015-02-25 15:05:59 +01003880 if (targetThread->GetInvokeReq() != nullptr) {
3881 // Thread is already invoking a method on behalf of the debugger.
3882 LOG(ERROR) << "InvokeMethod request for thread already invoking a method: " << *targetThread;
3883 return JDWP::ERR_ALREADY_INVOKING;
3884 }
3885 if (!targetThread->IsReadyForDebugInvoke()) {
3886 // Thread is not suspended by an event so it cannot invoke a method.
Elliott Hughesd07986f2011-12-06 18:27:45 -08003887 LOG(ERROR) << "InvokeMethod request for thread not stopped by event: " << *targetThread;
3888 return JDWP::ERR_INVALID_THREAD;
3889 }
3890
3891 /*
Sebastien Hertzd4032e42015-06-12 15:47:34 +02003892 * According to the JDWP specs, we are expected to resume all threads (or only the
3893 * target thread) once. So if a thread has been suspended more than once (either by
3894 * the debugger for an event or by the runtime for GC), it will remain suspended before
3895 * the invoke is executed. This means the debugger is responsible to properly resume all
3896 * the threads it has suspended so the target thread can execute the method.
Elliott Hughesd07986f2011-12-06 18:27:45 -08003897 *
Sebastien Hertzd4032e42015-06-12 15:47:34 +02003898 * However, for compatibility reason with older versions of debuggers (like Eclipse), we
3899 * fully resume all threads (by canceling *all* debugger suspensions) when the debugger
3900 * wants us to resume all threads. This is to avoid ending up in deadlock situation.
3901 *
3902 * On the other hand, if we are asked to only resume the target thread, then we follow the
3903 * JDWP specs by resuming that thread only once. This means the thread will remain suspended
3904 * if it has been suspended more than once before the invoke (and again, this is the
3905 * responsibility of the debugger to properly resume that thread before invoking a method).
Elliott Hughesd07986f2011-12-06 18:27:45 -08003906 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003907 int suspend_count;
3908 {
Ian Rogers50b35e22012-10-04 10:09:15 -07003909 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003910 suspend_count = targetThread->GetSuspendCount();
3911 }
Sebastien Hertzd4032e42015-06-12 15:47:34 +02003912 if (suspend_count > 1 && resume_all_threads) {
3913 // The target thread will remain suspended even after we resume it. Let's emit a warning
3914 // to indicate the invoke won't be executed until the thread is resumed.
3915 LOG(WARNING) << *targetThread << " suspended more than once (suspend count == "
3916 << suspend_count << "). This thread will invoke the method only once "
3917 << "it is fully resumed.";
Elliott Hughesd07986f2011-12-06 18:27:45 -08003918 }
3919
Ian Rogersc0542af2014-09-03 16:16:56 -07003920 mirror::Object* receiver = gRegistry->Get<mirror::Object*>(object_id, &error);
3921 if (error != JDWP::ERR_NONE) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08003922 return JDWP::ERR_INVALID_OBJECT;
3923 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003924
Sebastien Hertz1558b572015-02-25 15:05:59 +01003925 gRegistry->Get<mirror::Object*>(thread_id, &error);
Ian Rogersc0542af2014-09-03 16:16:56 -07003926 if (error != JDWP::ERR_NONE) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08003927 return JDWP::ERR_INVALID_OBJECT;
3928 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003929
Ian Rogersc0542af2014-09-03 16:16:56 -07003930 mirror::Class* c = DecodeClass(class_id, &error);
3931 if (c == nullptr) {
3932 return error;
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08003933 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003934
Mathieu Chartiere401d142015-04-22 13:56:20 -07003935 ArtMethod* m = FromMethodId(method_id);
Ian Rogersc0542af2014-09-03 16:16:56 -07003936 if (m->IsStatic() != (receiver == nullptr)) {
Elliott Hughes45651fd2012-02-21 15:48:20 -08003937 return JDWP::ERR_INVALID_METHODID;
3938 }
3939 if (m->IsStatic()) {
3940 if (m->GetDeclaringClass() != c) {
3941 return JDWP::ERR_INVALID_METHODID;
3942 }
3943 } else {
3944 if (!m->GetDeclaringClass()->IsAssignableFrom(c)) {
3945 return JDWP::ERR_INVALID_METHODID;
3946 }
3947 }
3948
3949 // Check the argument list matches the method.
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003950 uint32_t shorty_len = 0;
3951 const char* shorty = m->GetShorty(&shorty_len);
3952 if (shorty_len - 1 != arg_count) {
Elliott Hughes45651fd2012-02-21 15:48:20 -08003953 return JDWP::ERR_ILLEGAL_ARGUMENT;
3954 }
Elliott Hughes09201632013-04-15 15:50:07 -07003955
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003956 {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003957 StackHandleScope<2> hs(soa.Self());
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003958 HandleWrapper<mirror::Object> h_obj(hs.NewHandleWrapper(&receiver));
3959 HandleWrapper<mirror::Class> h_klass(hs.NewHandleWrapper(&c));
3960 const DexFile::TypeList* types = m->GetParameterTypeList();
3961 for (size_t i = 0; i < arg_count; ++i) {
3962 if (shorty[i + 1] != JdwpTagToShortyChar(arg_types[i])) {
Elliott Hughes09201632013-04-15 15:50:07 -07003963 return JDWP::ERR_ILLEGAL_ARGUMENT;
3964 }
3965
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003966 if (shorty[i + 1] == 'L') {
3967 // Did we really get an argument of an appropriate reference type?
Ian Rogersa0485602014-12-02 15:48:04 -08003968 mirror::Class* parameter_type =
Vladimir Marko05792b92015-08-03 11:56:49 +01003969 m->GetClassFromTypeIndex(types->GetTypeItem(i).type_idx_,
3970 true /* resolve */,
Andreas Gampe542451c2016-07-26 09:02:02 -07003971 kRuntimePointerSize);
Ian Rogersc0542af2014-09-03 16:16:56 -07003972 mirror::Object* argument = gRegistry->Get<mirror::Object*>(arg_values[i], &error);
3973 if (error != JDWP::ERR_NONE) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003974 return JDWP::ERR_INVALID_OBJECT;
3975 }
Ian Rogersc0542af2014-09-03 16:16:56 -07003976 if (argument != nullptr && !argument->InstanceOf(parameter_type)) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003977 return JDWP::ERR_ILLEGAL_ARGUMENT;
3978 }
3979
3980 // Turn the on-the-wire ObjectId into a jobject.
3981 jvalue& v = reinterpret_cast<jvalue&>(arg_values[i]);
3982 v.l = gRegistry->GetJObject(arg_values[i]);
3983 }
Elliott Hughes09201632013-04-15 15:50:07 -07003984 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003985 }
3986
Sebastien Hertz1558b572015-02-25 15:05:59 +01003987 // Allocates a DebugInvokeReq.
Sebastien Hertzcbc50642015-06-01 17:33:12 +02003988 DebugInvokeReq* req = new (std::nothrow) DebugInvokeReq(request_id, thread_id, receiver, c, m,
3989 options, arg_values, arg_count);
3990 if (req == nullptr) {
Sebastien Hertz1558b572015-02-25 15:05:59 +01003991 LOG(ERROR) << "Failed to allocate DebugInvokeReq";
3992 return JDWP::ERR_OUT_OF_MEMORY;
3993 }
3994
Sebastien Hertzcbc50642015-06-01 17:33:12 +02003995 // Attaches the DebugInvokeReq to the target thread so it executes the method when
3996 // it is resumed. Once the invocation completes, the target thread will delete it before
3997 // suspending itself (see ThreadList::SuspendSelfForDebugger).
3998 targetThread->SetDebugInvokeReq(req);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003999 }
4000
4001 // 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 +02004002 // away we're sitting high and dry -- but we must release this before the UndoDebuggerSuspensions
4003 // call.
Sebastien Hertzd4032e42015-06-12 15:47:34 +02004004 if (resume_all_threads) {
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004005 VLOG(jdwp) << " Resuming all threads";
4006 thread_list->UndoDebuggerSuspensions();
4007 } else {
4008 VLOG(jdwp) << " Resuming event thread only";
Elliott Hughesd07986f2011-12-06 18:27:45 -08004009 thread_list->Resume(targetThread, true);
4010 }
4011
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004012 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004013}
4014
4015void Dbg::ExecuteMethod(DebugInvokeReq* pReq) {
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004016 Thread* const self = Thread::Current();
4017 CHECK_NE(self, GetDebugThread()) << "This must be called by the event thread";
4018
4019 ScopedObjectAccess soa(self);
Elliott Hughesd07986f2011-12-06 18:27:45 -08004020
Elliott Hughes81ff3182012-03-23 20:35:56 -07004021 // We can be called while an exception is pending. We need
Elliott Hughesd07986f2011-12-06 18:27:45 -08004022 // to preserve that across the method invocation.
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004023 StackHandleScope<1> hs(soa.Self());
4024 Handle<mirror::Throwable> old_exception = hs.NewHandle(soa.Self()->GetException());
Sebastien Hertz1558b572015-02-25 15:05:59 +01004025 soa.Self()->ClearException();
Elliott Hughesd07986f2011-12-06 18:27:45 -08004026
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004027 // Execute the method then sends reply to the debugger.
4028 ExecuteMethodWithoutPendingException(soa, pReq);
4029
4030 // If an exception was pending before the invoke, restore it now.
4031 if (old_exception.Get() != nullptr) {
4032 soa.Self()->SetException(old_exception.Get());
4033 }
4034}
4035
4036// Helper function: write a variable-width value into the output input buffer.
4037static void WriteValue(JDWP::ExpandBuf* pReply, int width, uint64_t value) {
4038 switch (width) {
4039 case 1:
4040 expandBufAdd1(pReply, value);
4041 break;
4042 case 2:
4043 expandBufAdd2BE(pReply, value);
4044 break;
4045 case 4:
4046 expandBufAdd4BE(pReply, value);
4047 break;
4048 case 8:
4049 expandBufAdd8BE(pReply, value);
4050 break;
4051 default:
4052 LOG(FATAL) << width;
4053 UNREACHABLE();
4054 }
4055}
4056
4057void Dbg::ExecuteMethodWithoutPendingException(ScopedObjectAccess& soa, DebugInvokeReq* pReq) {
4058 soa.Self()->AssertNoPendingException();
4059
Elliott Hughesd07986f2011-12-06 18:27:45 -08004060 // Translate the method through the vtable, unless the debugger wants to suppress it.
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004061 ArtMethod* m = pReq->method;
Andreas Gampe542451c2016-07-26 09:02:02 -07004062 PointerSize image_pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
Sebastien Hertz1558b572015-02-25 15:05:59 +01004063 if ((pReq->options & JDWP::INVOKE_NONVIRTUAL) == 0 && pReq->receiver.Read() != nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004064 ArtMethod* actual_method =
4065 pReq->klass.Read()->FindVirtualMethodForVirtualOrInterface(m, image_pointer_size);
4066 if (actual_method != m) {
4067 VLOG(jdwp) << "ExecuteMethod translated " << PrettyMethod(m)
Sebastien Hertz1558b572015-02-25 15:05:59 +01004068 << " to " << PrettyMethod(actual_method);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004069 m = actual_method;
Elliott Hughes45651fd2012-02-21 15:48:20 -08004070 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08004071 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07004072 VLOG(jdwp) << "ExecuteMethod " << PrettyMethod(m)
Sebastien Hertz1558b572015-02-25 15:05:59 +01004073 << " receiver=" << pReq->receiver.Read()
Sebastien Hertzd38667a2013-11-25 15:43:54 +01004074 << " arg_count=" << pReq->arg_count;
Mathieu Chartiere401d142015-04-22 13:56:20 -07004075 CHECK(m != nullptr);
Elliott Hughesd07986f2011-12-06 18:27:45 -08004076
Roland Levillain33d69032015-06-18 18:20:59 +01004077 static_assert(sizeof(jvalue) == sizeof(uint64_t), "jvalue and uint64_t have different sizes.");
Elliott Hughesd07986f2011-12-06 18:27:45 -08004078
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004079 // Invoke the method.
Jeff Hao39b6c242015-05-19 20:30:23 -07004080 ScopedLocalRef<jobject> ref(soa.Env(), soa.AddLocalReference<jobject>(pReq->receiver.Read()));
Mathieu Chartiere401d142015-04-22 13:56:20 -07004081 JValue result = InvokeWithJValues(soa, ref.get(), soa.EncodeMethod(m),
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004082 reinterpret_cast<jvalue*>(pReq->arg_values.get()));
Elliott Hughesd07986f2011-12-06 18:27:45 -08004083
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004084 // Prepare JDWP ids for the reply.
4085 JDWP::JdwpTag result_tag = BasicTagFromDescriptor(m->GetShorty());
4086 const bool is_object_result = (result_tag == JDWP::JT_OBJECT);
Jeff Hao064d24e2016-08-25 03:52:40 +00004087 StackHandleScope<3> hs(soa.Self());
Sebastien Hertz1558b572015-02-25 15:05:59 +01004088 Handle<mirror::Object> object_result = hs.NewHandle(is_object_result ? result.GetL() : nullptr);
4089 Handle<mirror::Throwable> exception = hs.NewHandle(soa.Self()->GetException());
4090 soa.Self()->ClearException();
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004091
4092 if (!IsDebuggerActive()) {
4093 // The debugger detached: we must not re-suspend threads. We also don't need to fill the reply
4094 // because it won't be sent either.
4095 return;
4096 }
4097
4098 JDWP::ObjectId exceptionObjectId = gRegistry->Add(exception);
4099 uint64_t result_value = 0;
4100 if (exceptionObjectId != 0) {
Sebastien Hertz1558b572015-02-25 15:05:59 +01004101 VLOG(jdwp) << " JDWP invocation returning with exception=" << exception.Get()
4102 << " " << exception->Dump();
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004103 result_value = 0;
Sebastien Hertz1558b572015-02-25 15:05:59 +01004104 } else if (is_object_result) {
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004105 /* if no exception was thrown, examine object result more closely */
Sebastien Hertz1558b572015-02-25 15:05:59 +01004106 JDWP::JdwpTag new_tag = TagFromObject(soa, object_result.Get());
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004107 if (new_tag != result_tag) {
4108 VLOG(jdwp) << " JDWP promoted result from " << result_tag << " to " << new_tag;
4109 result_tag = new_tag;
Elliott Hughesd07986f2011-12-06 18:27:45 -08004110 }
4111
Sebastien Hertz1558b572015-02-25 15:05:59 +01004112 // Register the object in the registry and reference its ObjectId. This ensures
4113 // GC safety and prevents from accessing stale reference if the object is moved.
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004114 result_value = gRegistry->Add(object_result.Get());
Sebastien Hertz1558b572015-02-25 15:05:59 +01004115 } else {
4116 // Primitive result.
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004117 DCHECK(IsPrimitiveTag(result_tag));
4118 result_value = result.GetJ();
4119 }
4120 const bool is_constructor = m->IsConstructor() && !m->IsStatic();
4121 if (is_constructor) {
4122 // If we invoked a constructor (which actually returns void), return the receiver,
4123 // unless we threw, in which case we return null.
Sebastien Hertza3e13772015-11-05 12:09:44 +01004124 DCHECK_EQ(JDWP::JT_VOID, result_tag);
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004125 if (exceptionObjectId == 0) {
Jeff Hao064d24e2016-08-25 03:52:40 +00004126 if (m->GetDeclaringClass()->IsStringClass()) {
4127 // For string constructors, the new string is remapped to the receiver (stored in ref).
4128 Handle<mirror::Object> decoded_ref = hs.NewHandle(soa.Self()->DecodeJObject(ref.get()));
4129 result_value = gRegistry->Add(decoded_ref);
4130 result_tag = TagFromObject(soa, decoded_ref.Get());
4131 } else {
4132 // TODO we could keep the receiver ObjectId in the DebugInvokeReq to avoid looking into the
4133 // object registry.
4134 result_value = GetObjectRegistry()->Add(pReq->receiver.Read());
4135 result_tag = TagFromObject(soa, pReq->receiver.Read());
4136 }
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004137 } else {
4138 result_value = 0;
Sebastien Hertza3e13772015-11-05 12:09:44 +01004139 result_tag = JDWP::JT_OBJECT;
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004140 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08004141 }
4142
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004143 // Suspend other threads if the invoke is not single-threaded.
4144 if ((pReq->options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07004145 ScopedThreadSuspension sts(soa.Self(), kWaitingForDebuggerSuspension);
Hiroshi Yamauchi8f95cf32016-04-19 11:14:06 -07004146 // Avoid a deadlock between GC and debugger where GC gets suspended during GC. b/25800335.
4147 gc::ScopedGCCriticalSection gcs(soa.Self(), gc::kGcCauseDebugger, gc::kCollectorTypeDebugger);
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004148 VLOG(jdwp) << " Suspending all threads";
4149 Runtime::Current()->GetThreadList()->SuspendAllForDebugger();
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004150 }
4151
4152 VLOG(jdwp) << " --> returned " << result_tag
4153 << StringPrintf(" %#" PRIx64 " (except=%#" PRIx64 ")", result_value,
4154 exceptionObjectId);
4155
4156 // Show detailed debug output.
4157 if (result_tag == JDWP::JT_STRING && exceptionObjectId == 0) {
4158 if (result_value != 0) {
4159 if (VLOG_IS_ON(jdwp)) {
4160 std::string result_string;
4161 JDWP::JdwpError error = Dbg::StringToUtf8(result_value, &result_string);
4162 CHECK_EQ(error, JDWP::ERR_NONE);
4163 VLOG(jdwp) << " string '" << result_string << "'";
4164 }
4165 } else {
4166 VLOG(jdwp) << " string (null)";
4167 }
4168 }
4169
4170 // Attach the reply to DebugInvokeReq so it can be sent to the debugger when the event thread
4171 // is ready to suspend.
4172 BuildInvokeReply(pReq->reply, pReq->request_id, result_tag, result_value, exceptionObjectId);
4173}
4174
4175void Dbg::BuildInvokeReply(JDWP::ExpandBuf* pReply, uint32_t request_id, JDWP::JdwpTag result_tag,
4176 uint64_t result_value, JDWP::ObjectId exception) {
4177 // Make room for the JDWP header since we do not know the size of the reply yet.
4178 JDWP::expandBufAddSpace(pReply, kJDWPHeaderLen);
4179
4180 size_t width = GetTagWidth(result_tag);
4181 JDWP::expandBufAdd1(pReply, result_tag);
4182 if (width != 0) {
4183 WriteValue(pReply, width, result_value);
4184 }
4185 JDWP::expandBufAdd1(pReply, JDWP::JT_OBJECT);
4186 JDWP::expandBufAddObjectId(pReply, exception);
4187
4188 // Now we know the size, we can complete the JDWP header.
4189 uint8_t* buf = expandBufGetBuffer(pReply);
4190 JDWP::Set4BE(buf + kJDWPHeaderSizeOffset, expandBufGetLength(pReply));
4191 JDWP::Set4BE(buf + kJDWPHeaderIdOffset, request_id);
4192 JDWP::Set1(buf + kJDWPHeaderFlagsOffset, kJDWPFlagReply); // flags
4193 JDWP::Set2BE(buf + kJDWPHeaderErrorCodeOffset, JDWP::ERR_NONE);
4194}
4195
4196void Dbg::FinishInvokeMethod(DebugInvokeReq* pReq) {
4197 CHECK_NE(Thread::Current(), GetDebugThread()) << "This must be called by the event thread";
4198
4199 JDWP::ExpandBuf* const pReply = pReq->reply;
4200 CHECK(pReply != nullptr) << "No reply attached to DebugInvokeReq";
4201
4202 // We need to prevent other threads (including JDWP thread) from interacting with the debugger
4203 // while we send the reply but are not yet suspended. The JDWP token will be released just before
4204 // we suspend ourself again (see ThreadList::SuspendSelfForDebugger).
4205 gJdwpState->AcquireJdwpTokenForEvent(pReq->thread_id);
4206
4207 // Send the reply unless the debugger detached before the completion of the method.
4208 if (IsDebuggerActive()) {
4209 const size_t replyDataLength = expandBufGetLength(pReply) - kJDWPHeaderLen;
4210 VLOG(jdwp) << StringPrintf("REPLY INVOKE id=0x%06x (length=%zu)",
4211 pReq->request_id, replyDataLength);
4212
4213 gJdwpState->SendRequest(pReply);
4214 } else {
4215 VLOG(jdwp) << "Not sending invoke reply because debugger detached";
Elliott Hughesd07986f2011-12-06 18:27:45 -08004216 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004217}
4218
Elliott Hughesd07986f2011-12-06 18:27:45 -08004219/*
Elliott Hughes4b9702c2013-02-20 18:13:24 -08004220 * "request" contains a full JDWP packet, possibly with multiple chunks. We
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004221 * need to process each, accumulate the replies, and ship the whole thing
4222 * back.
4223 *
4224 * Returns "true" if we have a reply. The reply buffer is newly allocated,
4225 * and includes the chunk type/length, followed by the data.
4226 *
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08004227 * OLD-TODO: we currently assume that the request and reply include a single
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004228 * chunk. If this becomes inconvenient we will need to adapt.
4229 */
Ian Rogersc0542af2014-09-03 16:16:56 -07004230bool Dbg::DdmHandlePacket(JDWP::Request* request, uint8_t** pReplyBuf, int* pReplyLen) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004231 Thread* self = Thread::Current();
4232 JNIEnv* env = self->GetJniEnv();
4233
Ian Rogersc0542af2014-09-03 16:16:56 -07004234 uint32_t type = request->ReadUnsigned32("type");
4235 uint32_t length = request->ReadUnsigned32("length");
Elliott Hughes4b9702c2013-02-20 18:13:24 -08004236
4237 // Create a byte[] corresponding to 'request'.
Ian Rogersc0542af2014-09-03 16:16:56 -07004238 size_t request_length = request->size();
Elliott Hughes4b9702c2013-02-20 18:13:24 -08004239 ScopedLocalRef<jbyteArray> dataArray(env, env->NewByteArray(request_length));
Ian Rogersc0542af2014-09-03 16:16:56 -07004240 if (dataArray.get() == nullptr) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08004241 LOG(WARNING) << "byte[] allocation failed: " << request_length;
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004242 env->ExceptionClear();
4243 return false;
4244 }
Ian Rogersc0542af2014-09-03 16:16:56 -07004245 env->SetByteArrayRegion(dataArray.get(), 0, request_length,
4246 reinterpret_cast<const jbyte*>(request->data()));
4247 request->Skip(request_length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004248
4249 // Run through and find all chunks. [Currently just find the first.]
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004250 ScopedByteArrayRO contents(env, dataArray.get());
Elliott Hughes4b9702c2013-02-20 18:13:24 -08004251 if (length != request_length) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08004252 LOG(WARNING) << StringPrintf("bad chunk found (len=%u pktLen=%zd)", length, request_length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004253 return false;
4254 }
4255
4256 // Call "private static Chunk dispatch(int type, byte[] data, int offset, int length)".
Elliott Hugheseac76672012-05-24 21:56:51 -07004257 ScopedLocalRef<jobject> chunk(env, env->CallStaticObjectMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
4258 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_dispatch,
Elliott Hughes4b9702c2013-02-20 18:13:24 -08004259 type, dataArray.get(), 0, length));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004260 if (env->ExceptionCheck()) {
4261 LOG(INFO) << StringPrintf("Exception thrown by dispatcher for 0x%08x", type);
4262 env->ExceptionDescribe();
4263 env->ExceptionClear();
4264 return false;
4265 }
4266
Ian Rogersc0542af2014-09-03 16:16:56 -07004267 if (chunk.get() == nullptr) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004268 return false;
4269 }
4270
4271 /*
4272 * Pull the pieces out of the chunk. We copy the results into a
4273 * newly-allocated buffer that the caller can free. We don't want to
4274 * continue using the Chunk object because nothing has a reference to it.
4275 *
4276 * We could avoid this by returning type/data/offset/length and having
4277 * the caller be aware of the object lifetime issues, but that
Elliott Hughes81ff3182012-03-23 20:35:56 -07004278 * integrates the JDWP code more tightly into the rest of the runtime, and doesn't work
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004279 * if we have responses for multiple chunks.
4280 *
4281 * So we're pretty much stuck with copying data around multiple times.
4282 */
Elliott Hugheseac76672012-05-24 21:56:51 -07004283 ScopedLocalRef<jbyteArray> replyData(env, reinterpret_cast<jbyteArray>(env->GetObjectField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_data)));
Elliott Hughes4b9702c2013-02-20 18:13:24 -08004284 jint offset = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_offset);
Elliott Hugheseac76672012-05-24 21:56:51 -07004285 length = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_length);
Elliott Hugheseac76672012-05-24 21:56:51 -07004286 type = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_type);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004287
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08004288 VLOG(jdwp) << StringPrintf("DDM reply: type=0x%08x data=%p offset=%d length=%d", type, replyData.get(), offset, length);
Ian Rogersc0542af2014-09-03 16:16:56 -07004289 if (length == 0 || replyData.get() == nullptr) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004290 return false;
4291 }
4292
Elliott Hughes4b9702c2013-02-20 18:13:24 -08004293 const int kChunkHdrLen = 8;
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004294 uint8_t* reply = new uint8_t[length + kChunkHdrLen];
Ian Rogersc0542af2014-09-03 16:16:56 -07004295 if (reply == nullptr) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004296 LOG(WARNING) << "malloc failed: " << (length + kChunkHdrLen);
4297 return false;
4298 }
Elliott Hughesf7c3b662011-10-27 12:04:56 -07004299 JDWP::Set4BE(reply + 0, type);
4300 JDWP::Set4BE(reply + 4, length);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004301 env->GetByteArrayRegion(replyData.get(), offset, length, reinterpret_cast<jbyte*>(reply + kChunkHdrLen));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004302
4303 *pReplyBuf = reply;
4304 *pReplyLen = length + kChunkHdrLen;
4305
Elliott Hughes4b9702c2013-02-20 18:13:24 -08004306 VLOG(jdwp) << StringPrintf("dvmHandleDdm returning type=%.4s %p len=%d", reinterpret_cast<char*>(reply), reply, length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004307 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004308}
4309
Elliott Hughesa2155262011-11-16 16:26:58 -08004310void Dbg::DdmBroadcast(bool connect) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08004311 VLOG(jdwp) << "Broadcasting DDM " << (connect ? "connect" : "disconnect") << "...";
Elliott Hughes47fce012011-10-25 18:37:19 -07004312
4313 Thread* self = Thread::Current();
Ian Rogers50b35e22012-10-04 10:09:15 -07004314 if (self->GetState() != kRunnable) {
4315 LOG(ERROR) << "DDM broadcast in thread state " << self->GetState();
4316 /* try anyway? */
Elliott Hughes47fce012011-10-25 18:37:19 -07004317 }
4318
4319 JNIEnv* env = self->GetJniEnv();
Elliott Hughes47fce012011-10-25 18:37:19 -07004320 jint event = connect ? 1 /*DdmServer.CONNECTED*/ : 2 /*DdmServer.DISCONNECTED*/;
Elliott Hugheseac76672012-05-24 21:56:51 -07004321 env->CallStaticVoidMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
4322 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_broadcast,
4323 event);
Elliott Hughes47fce012011-10-25 18:37:19 -07004324 if (env->ExceptionCheck()) {
4325 LOG(ERROR) << "DdmServer.broadcast " << event << " failed";
4326 env->ExceptionDescribe();
4327 env->ExceptionClear();
4328 }
4329}
4330
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004331void Dbg::DdmConnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08004332 Dbg::DdmBroadcast(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004333}
4334
4335void Dbg::DdmDisconnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08004336 Dbg::DdmBroadcast(false);
Elliott Hughes47fce012011-10-25 18:37:19 -07004337 gDdmThreadNotification = false;
4338}
4339
4340/*
Elliott Hughes82188472011-11-07 18:11:48 -08004341 * Send a notification when a thread starts, stops, or changes its name.
Elliott Hughes47fce012011-10-25 18:37:19 -07004342 *
4343 * Because we broadcast the full set of threads when the notifications are
4344 * first enabled, it's possible for "thread" to be actively executing.
4345 */
Elliott Hughes82188472011-11-07 18:11:48 -08004346void Dbg::DdmSendThreadNotification(Thread* t, uint32_t type) {
Elliott Hughes47fce012011-10-25 18:37:19 -07004347 if (!gDdmThreadNotification) {
4348 return;
4349 }
4350
Elliott Hughes82188472011-11-07 18:11:48 -08004351 if (type == CHUNK_TYPE("THDE")) {
Elliott Hughes47fce012011-10-25 18:37:19 -07004352 uint8_t buf[4];
Ian Rogersd9c4fc92013-10-01 19:45:43 -07004353 JDWP::Set4BE(&buf[0], t->GetThreadId());
Elliott Hughes47fce012011-10-25 18:37:19 -07004354 Dbg::DdmSendChunk(CHUNK_TYPE("THDE"), 4, buf);
Elliott Hughes82188472011-11-07 18:11:48 -08004355 } else {
4356 CHECK(type == CHUNK_TYPE("THCR") || type == CHUNK_TYPE("THNM")) << type;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004357 ScopedObjectAccessUnchecked soa(Thread::Current());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004358 StackHandleScope<1> hs(soa.Self());
4359 Handle<mirror::String> name(hs.NewHandle(t->GetThreadName(soa)));
Ian Rogersc0542af2014-09-03 16:16:56 -07004360 size_t char_count = (name.Get() != nullptr) ? name->GetLength() : 0;
Jeff Hao848f70a2014-01-15 13:49:50 -08004361 const jchar* chars = (name.Get() != nullptr) ? name->GetValue() : nullptr;
jessicahandojo3aaa37b2016-07-29 14:46:37 -07004362 bool is_compressed = (name.Get() != nullptr) ? name->IsCompressed() : false;
Elliott Hughes82188472011-11-07 18:11:48 -08004363
Elliott Hughes21f32d72011-11-09 17:44:13 -08004364 std::vector<uint8_t> bytes;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07004365 JDWP::Append4BE(bytes, t->GetThreadId());
jessicahandojo3aaa37b2016-07-29 14:46:37 -07004366 if (is_compressed) {
4367 const uint8_t* chars_compressed = name->GetValueCompressed();
4368 JDWP::AppendUtf16CompressedBE(bytes, chars_compressed, char_count);
4369 } else {
4370 JDWP::AppendUtf16BE(bytes, chars, char_count);
4371 }
Elliott Hughes21f32d72011-11-09 17:44:13 -08004372 CHECK_EQ(bytes.size(), char_count*2 + sizeof(uint32_t)*2);
4373 Dbg::DdmSendChunk(type, bytes);
Elliott Hughes47fce012011-10-25 18:37:19 -07004374 }
4375}
4376
Elliott Hughes47fce012011-10-25 18:37:19 -07004377void Dbg::DdmSetThreadNotification(bool enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004378 // Enable/disable thread notifications.
Elliott Hughes47fce012011-10-25 18:37:19 -07004379 gDdmThreadNotification = enable;
4380 if (enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004381 // Suspend the VM then post thread start notifications for all threads. Threads attaching will
4382 // see a suspension in progress and block until that ends. They then post their own start
4383 // notification.
4384 SuspendVM();
4385 std::list<Thread*> threads;
Ian Rogers50b35e22012-10-04 10:09:15 -07004386 Thread* self = Thread::Current();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004387 {
Ian Rogers50b35e22012-10-04 10:09:15 -07004388 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004389 threads = Runtime::Current()->GetThreadList()->GetList();
4390 }
4391 {
Ian Rogers50b35e22012-10-04 10:09:15 -07004392 ScopedObjectAccess soa(self);
Mathieu Chartier02e25112013-08-14 16:14:24 -07004393 for (Thread* thread : threads) {
4394 Dbg::DdmSendThreadNotification(thread, CHUNK_TYPE("THCR"));
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004395 }
4396 }
4397 ResumeVM();
Elliott Hughes47fce012011-10-25 18:37:19 -07004398 }
4399}
4400
Elliott Hughesa2155262011-11-16 16:26:58 -08004401void Dbg::PostThreadStartOrStop(Thread* t, uint32_t type) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07004402 if (IsDebuggerActive()) {
Sebastien Hertz6995c602014-09-09 12:10:13 +02004403 gJdwpState->PostThreadChange(t, type == CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07004404 }
Elliott Hughes82188472011-11-07 18:11:48 -08004405 Dbg::DdmSendThreadNotification(t, type);
Elliott Hughes47fce012011-10-25 18:37:19 -07004406}
4407
4408void Dbg::PostThreadStart(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004409 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07004410}
4411
4412void Dbg::PostThreadDeath(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004413 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THDE"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004414}
4415
Elliott Hughes82188472011-11-07 18:11:48 -08004416void Dbg::DdmSendChunk(uint32_t type, size_t byte_count, const uint8_t* buf) {
Ian Rogersc0542af2014-09-03 16:16:56 -07004417 CHECK(buf != nullptr);
Elliott Hughes3bb81562011-10-21 18:52:59 -07004418 iovec vec[1];
4419 vec[0].iov_base = reinterpret_cast<void*>(const_cast<uint8_t*>(buf));
4420 vec[0].iov_len = byte_count;
4421 Dbg::DdmSendChunkV(type, vec, 1);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004422}
4423
Elliott Hughes21f32d72011-11-09 17:44:13 -08004424void Dbg::DdmSendChunk(uint32_t type, const std::vector<uint8_t>& bytes) {
4425 DdmSendChunk(type, bytes.size(), &bytes[0]);
4426}
4427
Brian Carlstromf5293522013-07-19 00:24:00 -07004428void Dbg::DdmSendChunkV(uint32_t type, const iovec* iov, int iov_count) {
Ian Rogersc0542af2014-09-03 16:16:56 -07004429 if (gJdwpState == nullptr) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08004430 VLOG(jdwp) << "Debugger thread not active, ignoring DDM send: " << type;
Elliott Hughes3bb81562011-10-21 18:52:59 -07004431 } else {
Elliott Hughescccd84f2011-12-05 16:51:54 -08004432 gJdwpState->DdmSendChunkV(type, iov, iov_count);
Elliott Hughes3bb81562011-10-21 18:52:59 -07004433 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004434}
4435
Mathieu Chartierad466ad2015-01-08 16:28:08 -08004436JDWP::JdwpState* Dbg::GetJdwpState() {
4437 return gJdwpState;
4438}
4439
Elliott Hughes767a1472011-10-26 18:49:02 -07004440int Dbg::DdmHandleHpifChunk(HpifWhen when) {
4441 if (when == HPIF_WHEN_NOW) {
Elliott Hughes7162ad92011-10-27 14:08:42 -07004442 DdmSendHeapInfo(when);
Elliott Hughes767a1472011-10-26 18:49:02 -07004443 return true;
4444 }
4445
4446 if (when != HPIF_WHEN_NEVER && when != HPIF_WHEN_NEXT_GC && when != HPIF_WHEN_EVERY_GC) {
4447 LOG(ERROR) << "invalid HpifWhen value: " << static_cast<int>(when);
4448 return false;
4449 }
4450
4451 gDdmHpifWhen = when;
4452 return true;
4453}
4454
4455bool Dbg::DdmHandleHpsgNhsgChunk(Dbg::HpsgWhen when, Dbg::HpsgWhat what, bool native) {
4456 if (when != HPSG_WHEN_NEVER && when != HPSG_WHEN_EVERY_GC) {
4457 LOG(ERROR) << "invalid HpsgWhen value: " << static_cast<int>(when);
4458 return false;
4459 }
4460
4461 if (what != HPSG_WHAT_MERGED_OBJECTS && what != HPSG_WHAT_DISTINCT_OBJECTS) {
4462 LOG(ERROR) << "invalid HpsgWhat value: " << static_cast<int>(what);
4463 return false;
4464 }
4465
4466 if (native) {
4467 gDdmNhsgWhen = when;
4468 gDdmNhsgWhat = what;
4469 } else {
4470 gDdmHpsgWhen = when;
4471 gDdmHpsgWhat = what;
4472 }
4473 return true;
4474}
4475
Elliott Hughes7162ad92011-10-27 14:08:42 -07004476void Dbg::DdmSendHeapInfo(HpifWhen reason) {
4477 // If there's a one-shot 'when', reset it.
4478 if (reason == gDdmHpifWhen) {
4479 if (gDdmHpifWhen == HPIF_WHEN_NEXT_GC) {
4480 gDdmHpifWhen = HPIF_WHEN_NEVER;
4481 }
4482 }
4483
4484 /*
4485 * Chunk HPIF (client --> server)
4486 *
4487 * Heap Info. General information about the heap,
4488 * suitable for a summary display.
4489 *
4490 * [u4]: number of heaps
4491 *
4492 * For each heap:
4493 * [u4]: heap ID
4494 * [u8]: timestamp in ms since Unix epoch
4495 * [u1]: capture reason (same as 'when' value from server)
4496 * [u4]: max heap size in bytes (-Xmx)
4497 * [u4]: current heap size in bytes
4498 * [u4]: current number of bytes allocated
4499 * [u4]: current number of objects allocated
4500 */
4501 uint8_t heap_count = 1;
Ian Rogers1d54e732013-05-02 21:10:01 -07004502 gc::Heap* heap = Runtime::Current()->GetHeap();
Elliott Hughes21f32d72011-11-09 17:44:13 -08004503 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08004504 JDWP::Append4BE(bytes, heap_count);
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004505 JDWP::Append4BE(bytes, 1); // Heap id (bogus; we only have one heap).
Elliott Hughes545a0642011-11-08 19:10:03 -08004506 JDWP::Append8BE(bytes, MilliTime());
4507 JDWP::Append1BE(bytes, reason);
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004508 JDWP::Append4BE(bytes, heap->GetMaxMemory()); // Max allowed heap size in bytes.
4509 JDWP::Append4BE(bytes, heap->GetTotalMemory()); // Current heap size in bytes.
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08004510 JDWP::Append4BE(bytes, heap->GetBytesAllocated());
4511 JDWP::Append4BE(bytes, heap->GetObjectsAllocated());
Elliott Hughes21f32d72011-11-09 17:44:13 -08004512 CHECK_EQ(bytes.size(), 4U + (heap_count * (4 + 8 + 1 + 4 + 4 + 4 + 4)));
4513 Dbg::DdmSendChunk(CHUNK_TYPE("HPIF"), bytes);
Elliott Hughes767a1472011-10-26 18:49:02 -07004514}
4515
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004516enum HpsgSolidity {
4517 SOLIDITY_FREE = 0,
4518 SOLIDITY_HARD = 1,
4519 SOLIDITY_SOFT = 2,
4520 SOLIDITY_WEAK = 3,
4521 SOLIDITY_PHANTOM = 4,
4522 SOLIDITY_FINALIZABLE = 5,
4523 SOLIDITY_SWEEP = 6,
4524};
4525
4526enum HpsgKind {
4527 KIND_OBJECT = 0,
4528 KIND_CLASS_OBJECT = 1,
4529 KIND_ARRAY_1 = 2,
4530 KIND_ARRAY_2 = 3,
4531 KIND_ARRAY_4 = 4,
4532 KIND_ARRAY_8 = 5,
4533 KIND_UNKNOWN = 6,
4534 KIND_NATIVE = 7,
4535};
4536
4537#define HPSG_PARTIAL (1<<7)
4538#define HPSG_STATE(solidity, kind) ((uint8_t)((((kind) & 0x7) << 3) | ((solidity) & 0x7)))
4539
Ian Rogers30fab402012-01-23 15:43:46 -08004540class HeapChunkContext {
4541 public:
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004542 // Maximum chunk size. Obtain this from the formula:
4543 // (((maximum_heap_size / ALLOCATION_UNIT_SIZE) + 255) / 256) * 2
4544 HeapChunkContext(bool merge, bool native)
Ian Rogers30fab402012-01-23 15:43:46 -08004545 : buf_(16384 - 16),
4546 type_(0),
Mathieu Chartier36dab362014-07-30 14:59:56 -07004547 chunk_overhead_(0) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004548 Reset();
4549 if (native) {
Ian Rogers30fab402012-01-23 15:43:46 -08004550 type_ = CHUNK_TYPE("NHSG");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004551 } else {
Ian Rogers30fab402012-01-23 15:43:46 -08004552 type_ = merge ? CHUNK_TYPE("HPSG") : CHUNK_TYPE("HPSO");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004553 }
4554 }
4555
4556 ~HeapChunkContext() {
Ian Rogers30fab402012-01-23 15:43:46 -08004557 if (p_ > &buf_[0]) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004558 Flush();
4559 }
4560 }
4561
Mathieu Chartier36dab362014-07-30 14:59:56 -07004562 void SetChunkOverhead(size_t chunk_overhead) {
4563 chunk_overhead_ = chunk_overhead;
4564 }
4565
4566 void ResetStartOfNextChunk() {
4567 startOfNextMemoryChunk_ = nullptr;
4568 }
4569
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004570 void EnsureHeader(const void* chunk_ptr) {
Ian Rogers30fab402012-01-23 15:43:46 -08004571 if (!needHeader_) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004572 return;
4573 }
4574
4575 // Start a new HPSx chunk.
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004576 JDWP::Write4BE(&p_, 1); // Heap id (bogus; we only have one heap).
4577 JDWP::Write1BE(&p_, 8); // Size of allocation unit, in bytes.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004578
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004579 JDWP::Write4BE(&p_, reinterpret_cast<uintptr_t>(chunk_ptr)); // virtual address of segment start.
4580 JDWP::Write4BE(&p_, 0); // offset of this piece (relative to the virtual address).
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004581 // [u4]: length of piece, in allocation units
4582 // 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 -08004583 pieceLenField_ = p_;
4584 JDWP::Write4BE(&p_, 0x55555555);
4585 needHeader_ = false;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004586 }
4587
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004588 void Flush() REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -07004589 if (pieceLenField_ == nullptr) {
Ian Rogersd636b062013-01-18 17:51:18 -08004590 // Flush immediately post Reset (maybe back-to-back Flush). Ignore.
4591 CHECK(needHeader_);
4592 return;
4593 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004594 // Patch the "length of piece" field.
Ian Rogers30fab402012-01-23 15:43:46 -08004595 CHECK_LE(&buf_[0], pieceLenField_);
4596 CHECK_LE(pieceLenField_, p_);
4597 JDWP::Set4BE(pieceLenField_, totalAllocationUnits_);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004598
Ian Rogers30fab402012-01-23 15:43:46 -08004599 Dbg::DdmSendChunk(type_, p_ - &buf_[0], &buf_[0]);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004600 Reset();
4601 }
4602
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004603 static void HeapChunkJavaCallback(void* start, void* end, size_t used_bytes, void* arg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004604 REQUIRES_SHARED(Locks::heap_bitmap_lock_,
Ian Rogersb726dcb2012-09-05 08:57:23 -07004605 Locks::mutator_lock_) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004606 reinterpret_cast<HeapChunkContext*>(arg)->HeapChunkJavaCallback(start, end, used_bytes);
4607 }
4608
4609 static void HeapChunkNativeCallback(void* start, void* end, size_t used_bytes, void* arg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004610 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004611 reinterpret_cast<HeapChunkContext*>(arg)->HeapChunkNativeCallback(start, end, used_bytes);
Elliott Hughesa2155262011-11-16 16:26:58 -08004612 }
4613
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004614 private:
Elliott Hughesa2155262011-11-16 16:26:58 -08004615 enum { ALLOCATION_UNIT_SIZE = 8 };
4616
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004617 void Reset() {
Ian Rogers30fab402012-01-23 15:43:46 -08004618 p_ = &buf_[0];
Mathieu Chartier36dab362014-07-30 14:59:56 -07004619 ResetStartOfNextChunk();
Ian Rogers30fab402012-01-23 15:43:46 -08004620 totalAllocationUnits_ = 0;
4621 needHeader_ = true;
Ian Rogersc0542af2014-09-03 16:16:56 -07004622 pieceLenField_ = nullptr;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004623 }
4624
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004625 bool IsNative() const {
4626 return type_ == CHUNK_TYPE("NHSG");
4627 }
4628
4629 // Returns true if the object is not an empty chunk.
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004630 bool ProcessRecord(void* start, size_t used_bytes) REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers30fab402012-01-23 15:43:46 -08004631 // Note: heap call backs cannot manipulate the heap upon which they are crawling, care is taken
4632 // in the following code not to allocate memory, by ensuring buf_ is of the correct size
Ian Rogers15bf2d32012-08-28 17:33:04 -07004633 if (used_bytes == 0) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004634 if (start == nullptr) {
4635 // Reset for start of new heap.
4636 startOfNextMemoryChunk_ = nullptr;
4637 Flush();
4638 }
4639 // Only process in use memory so that free region information
4640 // also includes dlmalloc book keeping.
4641 return false;
Elliott Hughesa2155262011-11-16 16:26:58 -08004642 }
Ian Rogersc0542af2014-09-03 16:16:56 -07004643 if (startOfNextMemoryChunk_ != nullptr) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004644 // Transmit any pending free memory. Native free memory of over kMaxFreeLen could be because
4645 // of the use of mmaps, so don't report. If not free memory then start a new segment.
4646 bool flush = true;
4647 if (start > startOfNextMemoryChunk_) {
4648 const size_t kMaxFreeLen = 2 * kPageSize;
4649 void* free_start = startOfNextMemoryChunk_;
4650 void* free_end = start;
4651 const size_t free_len =
4652 reinterpret_cast<uintptr_t>(free_end) - reinterpret_cast<uintptr_t>(free_start);
4653 if (!IsNative() || free_len < kMaxFreeLen) {
4654 AppendChunk(HPSG_STATE(SOLIDITY_FREE, 0), free_start, free_len, IsNative());
4655 flush = false;
Ian Rogers15bf2d32012-08-28 17:33:04 -07004656 }
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004657 }
4658 if (flush) {
4659 startOfNextMemoryChunk_ = nullptr;
4660 Flush();
4661 }
Ian Rogers15bf2d32012-08-28 17:33:04 -07004662 }
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004663 return true;
Ian Rogers15bf2d32012-08-28 17:33:04 -07004664 }
Elliott Hughesa2155262011-11-16 16:26:58 -08004665
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004666 void HeapChunkNativeCallback(void* start, void* /*end*/, size_t used_bytes)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004667 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004668 if (ProcessRecord(start, used_bytes)) {
4669 uint8_t state = ExamineNativeObject(start);
4670 AppendChunk(state, start, used_bytes + chunk_overhead_, true /*is_native*/);
4671 startOfNextMemoryChunk_ = reinterpret_cast<char*>(start) + used_bytes + chunk_overhead_;
4672 }
4673 }
4674
4675 void HeapChunkJavaCallback(void* start, void* /*end*/, size_t used_bytes)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004676 REQUIRES_SHARED(Locks::heap_bitmap_lock_, Locks::mutator_lock_) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004677 if (ProcessRecord(start, used_bytes)) {
4678 // Determine the type of this chunk.
4679 // OLD-TODO: if context.merge, see if this chunk is different from the last chunk.
4680 // If it's the same, we should combine them.
4681 uint8_t state = ExamineJavaObject(reinterpret_cast<mirror::Object*>(start));
4682 AppendChunk(state, start, used_bytes + chunk_overhead_, false /*is_native*/);
4683 startOfNextMemoryChunk_ = reinterpret_cast<char*>(start) + used_bytes + chunk_overhead_;
4684 }
4685 }
4686
4687 void AppendChunk(uint8_t state, void* ptr, size_t length, bool is_native)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004688 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07004689 // Make sure there's enough room left in the buffer.
4690 // We need to use two bytes for every fractional 256 allocation units used by the chunk plus
4691 // 17 bytes for any header.
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004692 const size_t needed = ((RoundUp(length / ALLOCATION_UNIT_SIZE, 256) / 256) * 2) + 17;
4693 size_t byte_left = &buf_.back() - p_;
4694 if (byte_left < needed) {
4695 if (is_native) {
Pavel Vyssotski7522c742014-12-08 13:38:26 +06004696 // Cannot trigger memory allocation while walking native heap.
Pavel Vyssotski7522c742014-12-08 13:38:26 +06004697 return;
4698 }
Ian Rogers15bf2d32012-08-28 17:33:04 -07004699 Flush();
4700 }
4701
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004702 byte_left = &buf_.back() - p_;
4703 if (byte_left < needed) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07004704 LOG(WARNING) << "Chunk is too big to transmit (chunk_len=" << length << ", "
4705 << needed << " bytes)";
4706 return;
4707 }
4708 EnsureHeader(ptr);
Elliott Hughesa2155262011-11-16 16:26:58 -08004709 // Write out the chunk description.
Ian Rogers15bf2d32012-08-28 17:33:04 -07004710 length /= ALLOCATION_UNIT_SIZE; // Convert to allocation units.
4711 totalAllocationUnits_ += length;
4712 while (length > 256) {
Ian Rogers30fab402012-01-23 15:43:46 -08004713 *p_++ = state | HPSG_PARTIAL;
4714 *p_++ = 255; // length - 1
Ian Rogers15bf2d32012-08-28 17:33:04 -07004715 length -= 256;
Elliott Hughesa2155262011-11-16 16:26:58 -08004716 }
Ian Rogers30fab402012-01-23 15:43:46 -08004717 *p_++ = state;
Ian Rogers15bf2d32012-08-28 17:33:04 -07004718 *p_++ = length - 1;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004719 }
4720
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004721 uint8_t ExamineNativeObject(const void* p) REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004722 return p == nullptr ? HPSG_STATE(SOLIDITY_FREE, 0) : HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
4723 }
4724
4725 uint8_t ExamineJavaObject(mirror::Object* o)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004726 REQUIRES_SHARED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -07004727 if (o == nullptr) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004728 return HPSG_STATE(SOLIDITY_FREE, 0);
4729 }
Elliott Hughesa2155262011-11-16 16:26:58 -08004730 // It's an allocated chunk. Figure out what it is.
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004731 gc::Heap* heap = Runtime::Current()->GetHeap();
4732 if (!heap->IsLiveObjectLocked(o)) {
4733 LOG(ERROR) << "Invalid object in managed heap: " << o;
Elliott Hughesa2155262011-11-16 16:26:58 -08004734 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
4735 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004736 mirror::Class* c = o->GetClass();
Ian Rogersc0542af2014-09-03 16:16:56 -07004737 if (c == nullptr) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004738 // The object was probably just created but hasn't been initialized yet.
4739 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
4740 }
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004741 if (!heap->IsValidObjectAddress(c)) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07004742 LOG(ERROR) << "Invalid class for managed heap object: " << o << " " << c;
Elliott Hughesa2155262011-11-16 16:26:58 -08004743 return HPSG_STATE(SOLIDITY_HARD, KIND_UNKNOWN);
4744 }
Mathieu Chartierf26e1b32015-01-29 10:47:10 -08004745 if (c->GetClass() == nullptr) {
4746 LOG(ERROR) << "Null class of class " << c << " for object " << o;
4747 return HPSG_STATE(SOLIDITY_HARD, KIND_UNKNOWN);
4748 }
Elliott Hughesa2155262011-11-16 16:26:58 -08004749 if (c->IsClassClass()) {
4750 return HPSG_STATE(SOLIDITY_HARD, KIND_CLASS_OBJECT);
4751 }
Elliott Hughesa2155262011-11-16 16:26:58 -08004752 if (c->IsArrayClass()) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004753 switch (c->GetComponentSize()) {
4754 case 1: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_1);
4755 case 2: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_2);
4756 case 4: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
4757 case 8: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_8);
4758 }
4759 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004760 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
4761 }
4762
Ian Rogers30fab402012-01-23 15:43:46 -08004763 std::vector<uint8_t> buf_;
4764 uint8_t* p_;
4765 uint8_t* pieceLenField_;
Ian Rogers15bf2d32012-08-28 17:33:04 -07004766 void* startOfNextMemoryChunk_;
Ian Rogers30fab402012-01-23 15:43:46 -08004767 size_t totalAllocationUnits_;
4768 uint32_t type_;
Ian Rogers30fab402012-01-23 15:43:46 -08004769 bool needHeader_;
Mathieu Chartier36dab362014-07-30 14:59:56 -07004770 size_t chunk_overhead_;
Ian Rogers30fab402012-01-23 15:43:46 -08004771
Elliott Hughesa2155262011-11-16 16:26:58 -08004772 DISALLOW_COPY_AND_ASSIGN(HeapChunkContext);
4773};
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004774
Mathieu Chartier36dab362014-07-30 14:59:56 -07004775static void BumpPointerSpaceCallback(mirror::Object* obj, void* arg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004776 REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
Mathieu Chartier36dab362014-07-30 14:59:56 -07004777 const size_t size = RoundUp(obj->SizeOf(), kObjectAlignment);
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004778 HeapChunkContext::HeapChunkJavaCallback(
Mathieu Chartier36dab362014-07-30 14:59:56 -07004779 obj, reinterpret_cast<void*>(reinterpret_cast<uintptr_t>(obj) + size), size, arg);
4780}
4781
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004782void Dbg::DdmSendHeapSegments(bool native) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004783 Dbg::HpsgWhen when = native ? gDdmNhsgWhen : gDdmHpsgWhen;
4784 Dbg::HpsgWhat what = native ? gDdmNhsgWhat : gDdmHpsgWhat;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004785 if (when == HPSG_WHEN_NEVER) {
4786 return;
4787 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004788 // Figure out what kind of chunks we'll be sending.
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004789 CHECK(what == HPSG_WHAT_MERGED_OBJECTS || what == HPSG_WHAT_DISTINCT_OBJECTS)
4790 << static_cast<int>(what);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004791
4792 // First, send a heap start chunk.
4793 uint8_t heap_id[4];
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004794 JDWP::Set4BE(&heap_id[0], 1); // Heap id (bogus; we only have one heap).
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004795 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHST") : CHUNK_TYPE("HPST"), sizeof(heap_id), heap_id);
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07004796 Thread* self = Thread::Current();
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07004797 Locks::mutator_lock_->AssertSharedHeld(self);
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07004798
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004799 // Send a series of heap segment chunks.
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004800 HeapChunkContext context(what == HPSG_WHAT_MERGED_OBJECTS, native);
Elliott Hughesa2155262011-11-16 16:26:58 -08004801 if (native) {
Dimitry Ivanove6465bc2015-12-14 18:55:02 -08004802 UNIMPLEMENTED(WARNING) << "Native heap inspection is not supported";
Elliott Hughesa2155262011-11-16 16:26:58 -08004803 } else {
Ian Rogers1d54e732013-05-02 21:10:01 -07004804 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartier36dab362014-07-30 14:59:56 -07004805 for (const auto& space : heap->GetContinuousSpaces()) {
4806 if (space->IsDlMallocSpace()) {
Mathieu Chartier4c69d7f2014-10-10 12:45:50 -07004807 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004808 // dlmalloc's chunk header is 2 * sizeof(size_t), but if the previous chunk is in use for an
4809 // allocation then the first sizeof(size_t) may belong to it.
4810 context.SetChunkOverhead(sizeof(size_t));
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004811 space->AsDlMallocSpace()->Walk(HeapChunkContext::HeapChunkJavaCallback, &context);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004812 } else if (space->IsRosAllocSpace()) {
4813 context.SetChunkOverhead(0);
Mathieu Chartier4c69d7f2014-10-10 12:45:50 -07004814 // Need to acquire the mutator lock before the heap bitmap lock with exclusive access since
4815 // RosAlloc's internal logic doesn't know to release and reacquire the heap bitmap lock.
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07004816 ScopedThreadSuspension sts(self, kSuspended);
Mathieu Chartier4f55e222015-09-04 13:26:21 -07004817 ScopedSuspendAll ssa(__FUNCTION__);
4818 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
4819 space->AsRosAllocSpace()->Walk(HeapChunkContext::HeapChunkJavaCallback, &context);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004820 } else if (space->IsBumpPointerSpace()) {
Mathieu Chartier4c69d7f2014-10-10 12:45:50 -07004821 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004822 context.SetChunkOverhead(0);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004823 space->AsBumpPointerSpace()->Walk(BumpPointerSpaceCallback, &context);
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004824 HeapChunkContext::HeapChunkJavaCallback(nullptr, nullptr, 0, &context);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08004825 } else if (space->IsRegionSpace()) {
4826 heap->IncrementDisableMovingGC(self);
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07004827 {
4828 ScopedThreadSuspension sts(self, kSuspended);
Mathieu Chartier4f55e222015-09-04 13:26:21 -07004829 ScopedSuspendAll ssa(__FUNCTION__);
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07004830 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
4831 context.SetChunkOverhead(0);
4832 space->AsRegionSpace()->Walk(BumpPointerSpaceCallback, &context);
4833 HeapChunkContext::HeapChunkJavaCallback(nullptr, nullptr, 0, &context);
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07004834 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08004835 heap->DecrementDisableMovingGC(self);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004836 } else {
4837 UNIMPLEMENTED(WARNING) << "Not counting objects in space " << *space;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07004838 }
Mathieu Chartier36dab362014-07-30 14:59:56 -07004839 context.ResetStartOfNextChunk();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07004840 }
Mathieu Chartier4c69d7f2014-10-10 12:45:50 -07004841 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07004842 // Walk the large objects, these are not in the AllocSpace.
Mathieu Chartier36dab362014-07-30 14:59:56 -07004843 context.SetChunkOverhead(0);
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004844 heap->GetLargeObjectsSpace()->Walk(HeapChunkContext::HeapChunkJavaCallback, &context);
Elliott Hughesa2155262011-11-16 16:26:58 -08004845 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004846
4847 // Finally, send a heap end chunk.
4848 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHEN") : CHUNK_TYPE("HPEN"), sizeof(heap_id), heap_id);
Elliott Hughes767a1472011-10-26 18:49:02 -07004849}
4850
Brian Carlstrom306db812014-09-05 13:01:41 -07004851void Dbg::SetAllocTrackingEnabled(bool enable) {
Man Cao8c2ff642015-05-27 17:25:30 -07004852 gc::AllocRecordObjectMap::SetAllocTrackingEnabled(enable);
Elliott Hughes545a0642011-11-08 19:10:03 -08004853}
4854
4855void Dbg::DumpRecentAllocations() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004856 ScopedObjectAccess soa(Thread::Current());
Brian Carlstrom306db812014-09-05 13:01:41 -07004857 MutexLock mu(soa.Self(), *Locks::alloc_tracker_lock_);
Man Cao8c2ff642015-05-27 17:25:30 -07004858 if (!Runtime::Current()->GetHeap()->IsAllocTrackingEnabled()) {
Elliott Hughes545a0642011-11-08 19:10:03 -08004859 LOG(INFO) << "Not recording tracked allocations";
4860 return;
4861 }
Man Cao8c2ff642015-05-27 17:25:30 -07004862 gc::AllocRecordObjectMap* records = Runtime::Current()->GetHeap()->GetAllocationRecords();
4863 CHECK(records != nullptr);
Elliott Hughes545a0642011-11-08 19:10:03 -08004864
Man Cao1ed11b92015-06-11 22:47:35 -07004865 const uint16_t capped_count = CappedAllocRecordCount(records->GetRecentAllocationSize());
Brian Carlstrom306db812014-09-05 13:01:41 -07004866 uint16_t count = capped_count;
Elliott Hughes545a0642011-11-08 19:10:03 -08004867
Man Cao8c2ff642015-05-27 17:25:30 -07004868 LOG(INFO) << "Tracked allocations, (count=" << count << ")";
4869 for (auto it = records->RBegin(), end = records->REnd();
4870 count > 0 && it != end; count--, it++) {
Mathieu Chartier458b1052016-03-29 14:02:55 -07004871 const gc::AllocRecord* record = &it->second;
Elliott Hughes545a0642011-11-08 19:10:03 -08004872
Man Cao8c2ff642015-05-27 17:25:30 -07004873 LOG(INFO) << StringPrintf(" Thread %-2d %6zd bytes ", record->GetTid(), record->ByteCount())
Man Cao42c3c332015-06-23 16:38:25 -07004874 << PrettyClass(record->GetClass());
Elliott Hughes545a0642011-11-08 19:10:03 -08004875
Man Cao8c2ff642015-05-27 17:25:30 -07004876 for (size_t stack_frame = 0, depth = record->GetDepth(); stack_frame < depth; ++stack_frame) {
4877 const gc::AllocRecordStackTraceElement& stack_element = record->StackElement(stack_frame);
4878 ArtMethod* m = stack_element.GetMethod();
4879 LOG(INFO) << " " << PrettyMethod(m) << " line " << stack_element.ComputeLineNumber();
Elliott Hughes545a0642011-11-08 19:10:03 -08004880 }
4881
4882 // pause periodically to help logcat catch up
4883 if ((count % 5) == 0) {
4884 usleep(40000);
4885 }
Elliott Hughes545a0642011-11-08 19:10:03 -08004886 }
4887}
4888
4889class StringTable {
4890 public:
4891 StringTable() {
4892 }
4893
Mathieu Chartier4345c462014-06-27 10:20:14 -07004894 void Add(const std::string& str) {
4895 table_.insert(str);
4896 }
4897
4898 void Add(const char* str) {
4899 table_.insert(str);
Elliott Hughes545a0642011-11-08 19:10:03 -08004900 }
4901
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004902 size_t IndexOf(const char* s) const {
Mathieu Chartier02e25112013-08-14 16:14:24 -07004903 auto it = table_.find(s);
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004904 if (it == table_.end()) {
4905 LOG(FATAL) << "IndexOf(\"" << s << "\") failed";
4906 }
4907 return std::distance(table_.begin(), it);
Elliott Hughes545a0642011-11-08 19:10:03 -08004908 }
4909
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004910 size_t Size() const {
Elliott Hughes545a0642011-11-08 19:10:03 -08004911 return table_.size();
4912 }
4913
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004914 void WriteTo(std::vector<uint8_t>& bytes) const {
Mathieu Chartier02e25112013-08-14 16:14:24 -07004915 for (const std::string& str : table_) {
4916 const char* s = str.c_str();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004917 size_t s_len = CountModifiedUtf8Chars(s);
Christopher Ferris8a354052015-04-24 17:23:53 -07004918 std::unique_ptr<uint16_t[]> s_utf16(new uint16_t[s_len]);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004919 ConvertModifiedUtf8ToUtf16(s_utf16.get(), s);
4920 JDWP::AppendUtf16BE(bytes, s_utf16.get(), s_len);
Elliott Hughes545a0642011-11-08 19:10:03 -08004921 }
4922 }
4923
4924 private:
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004925 std::set<std::string> table_;
Elliott Hughes545a0642011-11-08 19:10:03 -08004926 DISALLOW_COPY_AND_ASSIGN(StringTable);
4927};
4928
Mathieu Chartiere401d142015-04-22 13:56:20 -07004929static const char* GetMethodSourceFile(ArtMethod* method)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004930 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004931 DCHECK(method != nullptr);
4932 const char* source_file = method->GetDeclaringClassSourceFile();
Sebastien Hertz280286a2014-04-28 09:26:50 +02004933 return (source_file != nullptr) ? source_file : "";
4934}
4935
Elliott Hughes545a0642011-11-08 19:10:03 -08004936/*
4937 * The data we send to DDMS contains everything we have recorded.
4938 *
4939 * Message header (all values big-endian):
4940 * (1b) message header len (to allow future expansion); includes itself
4941 * (1b) entry header len
4942 * (1b) stack frame len
4943 * (2b) number of entries
4944 * (4b) offset to string table from start of message
4945 * (2b) number of class name strings
4946 * (2b) number of method name strings
4947 * (2b) number of source file name strings
4948 * For each entry:
4949 * (4b) total allocation size
Elliott Hughes221229c2013-01-08 18:17:50 -08004950 * (2b) thread id
Elliott Hughes545a0642011-11-08 19:10:03 -08004951 * (2b) allocated object's class name index
4952 * (1b) stack depth
4953 * For each stack frame:
4954 * (2b) method's class name
4955 * (2b) method name
4956 * (2b) method source file
4957 * (2b) line number, clipped to 32767; -2 if native; -1 if no source
4958 * (xb) class name strings
4959 * (xb) method name strings
4960 * (xb) source file strings
4961 *
4962 * As with other DDM traffic, strings are sent as a 4-byte length
4963 * followed by UTF-16 data.
4964 *
4965 * We send up 16-bit unsigned indexes into string tables. In theory there
Brian Carlstrom306db812014-09-05 13:01:41 -07004966 * can be (kMaxAllocRecordStackDepth * alloc_record_max_) unique strings in
Elliott Hughes545a0642011-11-08 19:10:03 -08004967 * each table, but in practice there should be far fewer.
4968 *
4969 * The chief reason for using a string table here is to keep the size of
4970 * the DDMS message to a minimum. This is partly to make the protocol
4971 * efficient, but also because we have to form the whole thing up all at
4972 * once in a memory buffer.
4973 *
4974 * We use separate string tables for class names, method names, and source
4975 * files to keep the indexes small. There will generally be no overlap
4976 * between the contents of these tables.
4977 */
4978jbyteArray Dbg::GetRecentAllocations() {
Ian Rogerscf7f1912014-10-22 22:06:39 -07004979 if ((false)) {
Elliott Hughes545a0642011-11-08 19:10:03 -08004980 DumpRecentAllocations();
4981 }
4982
Ian Rogers50b35e22012-10-04 10:09:15 -07004983 Thread* self = Thread::Current();
Elliott Hughes545a0642011-11-08 19:10:03 -08004984 std::vector<uint8_t> bytes;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004985 {
Brian Carlstrom306db812014-09-05 13:01:41 -07004986 MutexLock mu(self, *Locks::alloc_tracker_lock_);
Man Cao8c2ff642015-05-27 17:25:30 -07004987 gc::AllocRecordObjectMap* records = Runtime::Current()->GetHeap()->GetAllocationRecords();
4988 // In case this method is called when allocation tracker is disabled,
4989 // we should still send some data back.
4990 gc::AllocRecordObjectMap dummy;
4991 if (records == nullptr) {
4992 CHECK(!Runtime::Current()->GetHeap()->IsAllocTrackingEnabled());
4993 records = &dummy;
4994 }
Man Cao41656de2015-07-06 18:53:15 -07004995 // We don't need to wait on the condition variable records->new_record_condition_, because this
4996 // function only reads the class objects, which are already marked so it doesn't change their
4997 // reachability.
Man Cao8c2ff642015-05-27 17:25:30 -07004998
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004999 //
5000 // Part 1: generate string tables.
5001 //
5002 StringTable class_names;
5003 StringTable method_names;
5004 StringTable filenames;
Elliott Hughes545a0642011-11-08 19:10:03 -08005005
Man Cao1ed11b92015-06-11 22:47:35 -07005006 const uint16_t capped_count = CappedAllocRecordCount(records->GetRecentAllocationSize());
Brian Carlstrom306db812014-09-05 13:01:41 -07005007 uint16_t count = capped_count;
Man Cao8c2ff642015-05-27 17:25:30 -07005008 for (auto it = records->RBegin(), end = records->REnd();
5009 count > 0 && it != end; count--, it++) {
Mathieu Chartier458b1052016-03-29 14:02:55 -07005010 const gc::AllocRecord* record = &it->second;
Ian Rogers1ff3c982014-08-12 02:30:58 -07005011 std::string temp;
Man Cao41656de2015-07-06 18:53:15 -07005012 class_names.Add(record->GetClassDescriptor(&temp));
Man Cao8c2ff642015-05-27 17:25:30 -07005013 for (size_t i = 0, depth = record->GetDepth(); i < depth; i++) {
5014 ArtMethod* m = record->StackElement(i).GetMethod();
5015 class_names.Add(m->GetDeclaringClassDescriptor());
5016 method_names.Add(m->GetName());
5017 filenames.Add(GetMethodSourceFile(m));
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005018 }
Elliott Hughes545a0642011-11-08 19:10:03 -08005019 }
5020
Man Cao8c2ff642015-05-27 17:25:30 -07005021 LOG(INFO) << "recent allocation records: " << capped_count;
5022 LOG(INFO) << "allocation records all objects: " << records->Size();
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005023
5024 //
5025 // Part 2: Generate the output and store it in the buffer.
5026 //
5027
5028 // (1b) message header len (to allow future expansion); includes itself
5029 // (1b) entry header len
5030 // (1b) stack frame len
5031 const int kMessageHeaderLen = 15;
5032 const int kEntryHeaderLen = 9;
5033 const int kStackFrameLen = 8;
5034 JDWP::Append1BE(bytes, kMessageHeaderLen);
5035 JDWP::Append1BE(bytes, kEntryHeaderLen);
5036 JDWP::Append1BE(bytes, kStackFrameLen);
5037
5038 // (2b) number of entries
5039 // (4b) offset to string table from start of message
5040 // (2b) number of class name strings
5041 // (2b) number of method name strings
5042 // (2b) number of source file name strings
Brian Carlstrom306db812014-09-05 13:01:41 -07005043 JDWP::Append2BE(bytes, capped_count);
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005044 size_t string_table_offset = bytes.size();
Brian Carlstrom7934ac22013-07-26 10:54:15 -07005045 JDWP::Append4BE(bytes, 0); // We'll patch this later...
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005046 JDWP::Append2BE(bytes, class_names.Size());
5047 JDWP::Append2BE(bytes, method_names.Size());
5048 JDWP::Append2BE(bytes, filenames.Size());
5049
Ian Rogers1ff3c982014-08-12 02:30:58 -07005050 std::string temp;
Man Cao8c2ff642015-05-27 17:25:30 -07005051 count = capped_count;
5052 // The last "count" number of allocation records in "records" are the most recent "count" number
5053 // of allocations. Reverse iterate to get them. The most recent allocation is sent first.
5054 for (auto it = records->RBegin(), end = records->REnd();
5055 count > 0 && it != end; count--, it++) {
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005056 // For each entry:
5057 // (4b) total allocation size
5058 // (2b) thread id
5059 // (2b) allocated object's class name index
5060 // (1b) stack depth
Mathieu Chartier458b1052016-03-29 14:02:55 -07005061 const gc::AllocRecord* record = &it->second;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005062 size_t stack_depth = record->GetDepth();
Mathieu Chartierf8322842014-05-16 10:59:25 -07005063 size_t allocated_object_class_name_index =
Man Cao41656de2015-07-06 18:53:15 -07005064 class_names.IndexOf(record->GetClassDescriptor(&temp));
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07005065 JDWP::Append4BE(bytes, record->ByteCount());
Man Cao8c2ff642015-05-27 17:25:30 -07005066 JDWP::Append2BE(bytes, static_cast<uint16_t>(record->GetTid()));
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005067 JDWP::Append2BE(bytes, allocated_object_class_name_index);
5068 JDWP::Append1BE(bytes, stack_depth);
5069
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005070 for (size_t stack_frame = 0; stack_frame < stack_depth; ++stack_frame) {
5071 // For each stack frame:
5072 // (2b) method's class name
5073 // (2b) method name
5074 // (2b) method source file
5075 // (2b) line number, clipped to 32767; -2 if native; -1 if no source
Man Cao8c2ff642015-05-27 17:25:30 -07005076 ArtMethod* m = record->StackElement(stack_frame).GetMethod();
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07005077 size_t class_name_index = class_names.IndexOf(m->GetDeclaringClassDescriptor());
5078 size_t method_name_index = method_names.IndexOf(m->GetName());
5079 size_t file_name_index = filenames.IndexOf(GetMethodSourceFile(m));
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005080 JDWP::Append2BE(bytes, class_name_index);
5081 JDWP::Append2BE(bytes, method_name_index);
5082 JDWP::Append2BE(bytes, file_name_index);
Man Cao8c2ff642015-05-27 17:25:30 -07005083 JDWP::Append2BE(bytes, record->StackElement(stack_frame).ComputeLineNumber());
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005084 }
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005085 }
5086
5087 // (xb) class name strings
5088 // (xb) method name strings
5089 // (xb) source file strings
5090 JDWP::Set4BE(&bytes[string_table_offset], bytes.size());
5091 class_names.WriteTo(bytes);
5092 method_names.WriteTo(bytes);
5093 filenames.WriteTo(bytes);
Elliott Hughes545a0642011-11-08 19:10:03 -08005094 }
Ian Rogers50b35e22012-10-04 10:09:15 -07005095 JNIEnv* env = self->GetJniEnv();
Elliott Hughes545a0642011-11-08 19:10:03 -08005096 jbyteArray result = env->NewByteArray(bytes.size());
Ian Rogersc0542af2014-09-03 16:16:56 -07005097 if (result != nullptr) {
Elliott Hughes545a0642011-11-08 19:10:03 -08005098 env->SetByteArrayRegion(result, 0, bytes.size(), reinterpret_cast<const jbyte*>(&bytes[0]));
5099 }
5100 return result;
5101}
5102
Mathieu Chartiere401d142015-04-22 13:56:20 -07005103ArtMethod* DeoptimizationRequest::Method() const {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07005104 ScopedObjectAccessUnchecked soa(Thread::Current());
5105 return soa.DecodeMethod(method_);
5106}
5107
Mathieu Chartiere401d142015-04-22 13:56:20 -07005108void DeoptimizationRequest::SetMethod(ArtMethod* m) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07005109 ScopedObjectAccessUnchecked soa(Thread::Current());
5110 method_ = soa.EncodeMethod(m);
5111}
5112
Mathieu Chartiera6b1ead2015-10-06 10:32:38 -07005113void Dbg::VisitRoots(RootVisitor* visitor) {
5114 // Visit breakpoint roots, used to prevent unloading of methods with breakpoints.
5115 ReaderMutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
5116 BufferedRootVisitor<128> root_visitor(visitor, RootInfo(kRootVMInternal));
5117 for (Breakpoint& breakpoint : gBreakpoints) {
Andreas Gampe542451c2016-07-26 09:02:02 -07005118 breakpoint.Method()->VisitRoots(root_visitor, kRuntimePointerSize);
Mathieu Chartiera6b1ead2015-10-06 10:32:38 -07005119 }
5120}
5121
Elliott Hughes872d4ec2011-10-21 17:07:15 -07005122} // namespace art