blob: c0811f16132ecf38254330dd4a95e6157665e05c [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"
Vladimir Marko80afd022015-05-19 18:08:00 +010026#include "base/time_utils.h"
Elliott Hughes545a0642011-11-08 19:10:03 -080027#include "class_linker.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080028#include "class_linker-inl.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070029#include "dex_file-inl.h"
Ian Rogers776ac1f2012-04-13 23:36:36 -070030#include "dex_instruction.h"
Mingyao Yang6ea1a0e2016-01-29 12:12:49 -080031#include "entrypoints/runtime_asm_entrypoints.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070032#include "gc/accounting/card_table-inl.h"
Man Cao8c2ff642015-05-27 17:25:30 -070033#include "gc/allocation_record.h"
Mathieu Chartieraa516822015-10-02 15:53:37 -070034#include "gc/scoped_gc_critical_section.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070035#include "gc/space/large_object_space.h"
36#include "gc/space/space-inl.h"
Mathieu Chartiereb8167a2014-05-07 15:43:14 -070037#include "handle_scope.h"
Sebastien Hertzcbc50642015-06-01 17:33:12 +020038#include "jdwp/jdwp_priv.h"
Elliott Hughes64f574f2013-02-20 14:57:12 -080039#include "jdwp/object_registry.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080040#include "mirror/class.h"
41#include "mirror/class-inl.h"
42#include "mirror/class_loader.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080043#include "mirror/object-inl.h"
44#include "mirror/object_array-inl.h"
Ian Rogersb0fa5dc2014-04-28 16:47:08 -070045#include "mirror/string-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080046#include "mirror/throwable.h"
Ian Rogers53b8b092014-03-13 23:45:53 -070047#include "reflection.h"
Elliott Hughesa0e18062012-04-13 15:59:59 -070048#include "safe_map.h"
Elliott Hughes64f574f2013-02-20 14:57:12 -080049#include "scoped_thread_state_change.h"
Elliott Hughes6a5bd492011-10-28 14:33:57 -070050#include "ScopedLocalRef.h"
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -070051#include "ScopedPrimitiveArray.h"
Mathieu Chartiereb8167a2014-05-07 15:43:14 -070052#include "handle_scope-inl.h"
Elliott Hughes475fc232011-10-25 15:00:35 -070053#include "thread_list.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080054#include "utf.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070055#include "well_known_classes.h"
Elliott Hughes475fc232011-10-25 15:00:35 -070056
Elliott Hughes872d4ec2011-10-21 17:07:15 -070057namespace art {
58
Sebastien Hertz0462c4c2015-04-01 16:34:17 +020059// The key identifying the debugger to update instrumentation.
60static constexpr const char* kDbgInstrumentationKey = "Debugger";
61
Man Cao8c2ff642015-05-27 17:25:30 -070062// 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 -070063static uint16_t CappedAllocRecordCount(size_t alloc_record_count) {
Man Cao1ed11b92015-06-11 22:47:35 -070064 const size_t cap = 0xffff;
Man Cao8c2ff642015-05-27 17:25:30 -070065 if (alloc_record_count > cap) {
66 return cap;
Brian Carlstrom306db812014-09-05 13:01:41 -070067 }
68 return alloc_record_count;
69}
Elliott Hughes475fc232011-10-25 15:00:35 -070070
Alex Light6c8467f2015-11-20 15:03:26 -080071// Takes a method and returns a 'canonical' one if the method is default (and therefore potentially
72// copied from some other class). This ensures that the debugger does not get confused as to which
73// method we are in.
74static ArtMethod* GetCanonicalMethod(ArtMethod* m)
75 SHARED_REQUIRES(Locks::mutator_lock_) {
76 if (LIKELY(!m->IsDefault())) {
77 return m;
78 } else {
79 mirror::Class* declaring_class = m->GetDeclaringClass();
80 return declaring_class->FindDeclaredVirtualMethod(declaring_class->GetDexCache(),
81 m->GetDexMethodIndex(),
82 sizeof(void*));
83 }
84}
85
Mathieu Chartier41af5e52015-10-28 11:10:46 -070086class Breakpoint : public ValueObject {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -070087 public:
Mathieu Chartier41af5e52015-10-28 11:10:46 -070088 Breakpoint(ArtMethod* method, uint32_t dex_pc, DeoptimizationRequest::Kind deoptimization_kind)
Alex Light6c8467f2015-11-20 15:03:26 -080089 : method_(GetCanonicalMethod(method)),
Mathieu Chartier41af5e52015-10-28 11:10:46 -070090 dex_pc_(dex_pc),
91 deoptimization_kind_(deoptimization_kind) {
Sebastien Hertzf3928792014-11-17 19:00:37 +010092 CHECK(deoptimization_kind_ == DeoptimizationRequest::kNothing ||
93 deoptimization_kind_ == DeoptimizationRequest::kSelectiveDeoptimization ||
94 deoptimization_kind_ == DeoptimizationRequest::kFullDeoptimization);
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -070095 }
96
Mathieu Chartier90443472015-07-16 20:32:27 -070097 Breakpoint(const Breakpoint& other) SHARED_REQUIRES(Locks::mutator_lock_)
Mathieu Chartier41af5e52015-10-28 11:10:46 -070098 : method_(other.method_),
99 dex_pc_(other.dex_pc_),
100 deoptimization_kind_(other.deoptimization_kind_) {}
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700101
Mathieu Chartier41af5e52015-10-28 11:10:46 -0700102 // Method() is called from root visiting, do not use ScopedObjectAccess here or it can cause
103 // GC to deadlock if another thread tries to call SuspendAll while the GC is in a runnable state.
104 ArtMethod* Method() const {
105 return method_;
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700106 }
107
108 uint32_t DexPc() const {
109 return dex_pc_;
110 }
111
Sebastien Hertzf3928792014-11-17 19:00:37 +0100112 DeoptimizationRequest::Kind GetDeoptimizationKind() const {
113 return deoptimization_kind_;
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700114 }
115
Alex Light6c8467f2015-11-20 15:03:26 -0800116 // Returns true if the method of this breakpoint and the passed in method should be considered the
117 // same. That is, they are either the same method or they are copied from the same method.
118 bool IsInMethod(ArtMethod* m) const SHARED_REQUIRES(Locks::mutator_lock_) {
119 return method_ == GetCanonicalMethod(m);
120 }
121
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700122 private:
Sebastien Hertza76a6d42014-03-20 16:40:17 +0100123 // The location of this breakpoint.
Mathieu Chartier41af5e52015-10-28 11:10:46 -0700124 ArtMethod* method_;
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700125 uint32_t dex_pc_;
Sebastien Hertza76a6d42014-03-20 16:40:17 +0100126
127 // Indicates whether breakpoint needs full deoptimization or selective deoptimization.
Sebastien Hertzf3928792014-11-17 19:00:37 +0100128 DeoptimizationRequest::Kind deoptimization_kind_;
Elliott Hughes86964332012-02-15 19:37:42 -0800129};
130
Sebastien Hertzed2be172014-08-19 15:33:43 +0200131static std::ostream& operator<<(std::ostream& os, const Breakpoint& rhs)
Mathieu Chartier90443472015-07-16 20:32:27 -0700132 SHARED_REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700133 os << StringPrintf("Breakpoint[%s @%#x]", PrettyMethod(rhs.Method()).c_str(), rhs.DexPc());
Elliott Hughes86964332012-02-15 19:37:42 -0800134 return os;
135}
136
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200137class DebugInstrumentationListener FINAL : public instrumentation::InstrumentationListener {
Ian Rogers62d6c772013-02-27 08:32:07 -0800138 public:
139 DebugInstrumentationListener() {}
140 virtual ~DebugInstrumentationListener() {}
141
Mathieu Chartiere401d142015-04-22 13:56:20 -0700142 void MethodEntered(Thread* thread, mirror::Object* this_object, ArtMethod* method,
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200143 uint32_t dex_pc)
Mathieu Chartier90443472015-07-16 20:32:27 -0700144 OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800145 if (method->IsNative()) {
146 // TODO: post location events is a suspension point and native method entry stubs aren't.
147 return;
148 }
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200149 if (IsListeningToDexPcMoved()) {
150 // We also listen to kDexPcMoved instrumentation event so we know the DexPcMoved method is
151 // going to be called right after us. To avoid sending JDWP events twice for this location,
152 // we report the event in DexPcMoved. However, we must remind this is method entry so we
153 // send the METHOD_ENTRY event. And we can also group it with other events for this location
154 // like BREAKPOINT or SINGLE_STEP (or even METHOD_EXIT if this is a RETURN instruction).
155 thread->SetDebugMethodEntry();
156 } else if (IsListeningToMethodExit() && IsReturn(method, dex_pc)) {
157 // We also listen to kMethodExited instrumentation event and the current instruction is a
158 // RETURN so we know the MethodExited method is going to be called right after us. To avoid
159 // sending JDWP events twice for this location, we report the event(s) in MethodExited.
160 // However, we must remind this is method entry so we send the METHOD_ENTRY event. And we can
161 // also group it with other events for this location like BREAKPOINT or SINGLE_STEP.
162 thread->SetDebugMethodEntry();
163 } else {
164 Dbg::UpdateDebugger(thread, this_object, method, 0, Dbg::kMethodEntry, nullptr);
165 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800166 }
167
Mathieu Chartiere401d142015-04-22 13:56:20 -0700168 void MethodExited(Thread* thread, mirror::Object* this_object, ArtMethod* method,
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200169 uint32_t dex_pc, const JValue& return_value)
Mathieu Chartier90443472015-07-16 20:32:27 -0700170 OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800171 if (method->IsNative()) {
172 // TODO: post location events is a suspension point and native method entry stubs aren't.
173 return;
174 }
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200175 uint32_t events = Dbg::kMethodExit;
176 if (thread->IsDebugMethodEntry()) {
177 // It is also the method entry.
178 DCHECK(IsReturn(method, dex_pc));
179 events |= Dbg::kMethodEntry;
180 thread->ClearDebugMethodEntry();
181 }
182 Dbg::UpdateDebugger(thread, this_object, method, dex_pc, events, &return_value);
Ian Rogers62d6c772013-02-27 08:32:07 -0800183 }
184
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200185 void MethodUnwind(Thread* thread ATTRIBUTE_UNUSED, mirror::Object* this_object ATTRIBUTE_UNUSED,
Mathieu Chartiere401d142015-04-22 13:56:20 -0700186 ArtMethod* method, uint32_t dex_pc)
Mathieu Chartier90443472015-07-16 20:32:27 -0700187 OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800188 // We're not recorded to listen to this kind of event, so complain.
189 LOG(ERROR) << "Unexpected method unwind event in debugger " << PrettyMethod(method)
Sebastien Hertz51db44a2013-11-19 10:00:29 +0100190 << " " << dex_pc;
Ian Rogers62d6c772013-02-27 08:32:07 -0800191 }
192
Mathieu Chartiere401d142015-04-22 13:56:20 -0700193 void DexPcMoved(Thread* thread, mirror::Object* this_object, ArtMethod* method,
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200194 uint32_t new_dex_pc)
Mathieu Chartier90443472015-07-16 20:32:27 -0700195 OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200196 if (IsListeningToMethodExit() && IsReturn(method, new_dex_pc)) {
197 // We also listen to kMethodExited instrumentation event and the current instruction is a
198 // RETURN so we know the MethodExited method is going to be called right after us. Like in
199 // MethodEntered, we delegate event reporting to MethodExited.
200 // Besides, if this RETURN instruction is the only one in the method, we can send multiple
201 // JDWP events in the same packet: METHOD_ENTRY, METHOD_EXIT, BREAKPOINT and/or SINGLE_STEP.
202 // Therefore, we must not clear the debug method entry flag here.
203 } else {
204 uint32_t events = 0;
205 if (thread->IsDebugMethodEntry()) {
206 // It is also the method entry.
207 events = Dbg::kMethodEntry;
208 thread->ClearDebugMethodEntry();
209 }
210 Dbg::UpdateDebugger(thread, this_object, method, new_dex_pc, events, nullptr);
211 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800212 }
213
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200214 void FieldRead(Thread* thread ATTRIBUTE_UNUSED, mirror::Object* this_object,
Mathieu Chartiere401d142015-04-22 13:56:20 -0700215 ArtMethod* method, uint32_t dex_pc, ArtField* field)
Mathieu Chartier90443472015-07-16 20:32:27 -0700216 OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200217 Dbg::PostFieldAccessEvent(method, dex_pc, this_object, field);
Ian Rogers62d6c772013-02-27 08:32:07 -0800218 }
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200219
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700220 void FieldWritten(Thread* thread ATTRIBUTE_UNUSED, mirror::Object* this_object,
Mathieu Chartiere401d142015-04-22 13:56:20 -0700221 ArtMethod* method, uint32_t dex_pc, ArtField* field,
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700222 const JValue& field_value)
Mathieu Chartier90443472015-07-16 20:32:27 -0700223 OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200224 Dbg::PostFieldModificationEvent(method, dex_pc, this_object, field, &field_value);
225 }
226
Nicolas Geoffray14691c52015-03-05 10:40:17 +0000227 void ExceptionCaught(Thread* thread ATTRIBUTE_UNUSED, mirror::Throwable* exception_object)
Mathieu Chartier90443472015-07-16 20:32:27 -0700228 OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Nicolas Geoffray14691c52015-03-05 10:40:17 +0000229 Dbg::PostException(exception_object);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200230 }
231
Nicolas Geoffray81f0f952016-01-20 16:25:19 +0000232 // We only care about branches in the Jit.
233 void Branch(Thread* /*thread*/, ArtMethod* method, uint32_t dex_pc, int32_t dex_pc_offset)
Mathieu Chartier90443472015-07-16 20:32:27 -0700234 OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Nicolas Geoffray81f0f952016-01-20 16:25:19 +0000235 LOG(ERROR) << "Unexpected branch event in debugger " << PrettyMethod(method)
236 << " " << dex_pc << ", " << dex_pc_offset;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800237 }
238
Nicolas Geoffray5550ca82015-08-21 18:38:30 +0100239 // We only care about invokes in the Jit.
240 void InvokeVirtualOrInterface(Thread* thread ATTRIBUTE_UNUSED,
241 mirror::Object*,
242 ArtMethod* method,
243 uint32_t dex_pc,
244 ArtMethod*)
245 OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
246 LOG(ERROR) << "Unexpected invoke event in debugger " << PrettyMethod(method)
247 << " " << dex_pc;
248 }
249
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200250 private:
Mathieu Chartiere401d142015-04-22 13:56:20 -0700251 static bool IsReturn(ArtMethod* method, uint32_t dex_pc)
Mathieu Chartier90443472015-07-16 20:32:27 -0700252 SHARED_REQUIRES(Locks::mutator_lock_) {
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200253 const DexFile::CodeItem* code_item = method->GetCodeItem();
254 const Instruction* instruction = Instruction::At(&code_item->insns_[dex_pc]);
255 return instruction->IsReturn();
256 }
257
Mathieu Chartier90443472015-07-16 20:32:27 -0700258 static bool IsListeningToDexPcMoved() SHARED_REQUIRES(Locks::mutator_lock_) {
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200259 return IsListeningTo(instrumentation::Instrumentation::kDexPcMoved);
260 }
261
Mathieu Chartier90443472015-07-16 20:32:27 -0700262 static bool IsListeningToMethodExit() SHARED_REQUIRES(Locks::mutator_lock_) {
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200263 return IsListeningTo(instrumentation::Instrumentation::kMethodExited);
264 }
265
266 static bool IsListeningTo(instrumentation::Instrumentation::InstrumentationEvent event)
Mathieu Chartier90443472015-07-16 20:32:27 -0700267 SHARED_REQUIRES(Locks::mutator_lock_) {
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200268 return (Dbg::GetInstrumentationEvents() & event) != 0;
269 }
270
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200271 DISALLOW_COPY_AND_ASSIGN(DebugInstrumentationListener);
Ian Rogers62d6c772013-02-27 08:32:07 -0800272} gDebugInstrumentationListener;
273
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700274// JDWP is allowed unless the Zygote forbids it.
275static bool gJdwpAllowed = true;
276
Elliott Hughesc0f09332012-03-26 13:27:06 -0700277// Was there a -Xrunjdwp or -agentlib:jdwp= argument on the command line?
Elliott Hughes3bb81562011-10-21 18:52:59 -0700278static bool gJdwpConfigured = false;
279
Sebastien Hertzb3b173b2015-02-06 09:16:32 +0100280// JDWP options for debugging. Only valid if IsJdwpConfigured() is true.
281static JDWP::JdwpOptions gJdwpOptions;
282
Elliott Hughes3bb81562011-10-21 18:52:59 -0700283// Runtime JDWP state.
Ian Rogersc0542af2014-09-03 16:16:56 -0700284static JDWP::JdwpState* gJdwpState = nullptr;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700285static bool gDebuggerConnected; // debugger or DDMS is connected.
Elliott Hughes3bb81562011-10-21 18:52:59 -0700286
Elliott Hughes47fce012011-10-25 18:37:19 -0700287static bool gDdmThreadNotification = false;
288
Elliott Hughes767a1472011-10-26 18:49:02 -0700289// DDMS GC-related settings.
290static Dbg::HpifWhen gDdmHpifWhen = Dbg::HPIF_WHEN_NEVER;
291static Dbg::HpsgWhen gDdmHpsgWhen = Dbg::HPSG_WHEN_NEVER;
292static Dbg::HpsgWhat gDdmHpsgWhat;
293static Dbg::HpsgWhen gDdmNhsgWhen = Dbg::HPSG_WHEN_NEVER;
294static Dbg::HpsgWhat gDdmNhsgWhat;
295
Daniel Mihalyieb076692014-08-22 17:33:31 +0200296bool Dbg::gDebuggerActive = false;
Sebastien Hertz4e5b2082015-03-24 19:03:40 +0100297bool Dbg::gDisposed = false;
Sebastien Hertz6995c602014-09-09 12:10:13 +0200298ObjectRegistry* Dbg::gRegistry = nullptr;
Elliott Hughes475fc232011-10-25 15:00:35 -0700299
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100300// Deoptimization support.
Sebastien Hertz4d25df32014-03-21 17:44:46 +0100301std::vector<DeoptimizationRequest> Dbg::deoptimization_requests_;
302size_t Dbg::full_deoptimization_event_count_ = 0;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100303
Sebastien Hertz42cd43f2014-05-13 14:15:41 +0200304// Instrumentation event reference counters.
305size_t Dbg::dex_pc_change_event_ref_count_ = 0;
306size_t Dbg::method_enter_event_ref_count_ = 0;
307size_t Dbg::method_exit_event_ref_count_ = 0;
308size_t Dbg::field_read_event_ref_count_ = 0;
309size_t Dbg::field_write_event_ref_count_ = 0;
310size_t Dbg::exception_catch_event_ref_count_ = 0;
311uint32_t Dbg::instrumentation_events_ = 0;
312
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100313// Breakpoints.
jeffhao09bfc6a2012-12-11 18:11:43 -0800314static std::vector<Breakpoint> gBreakpoints GUARDED_BY(Locks::breakpoint_lock_);
Elliott Hughes86964332012-02-15 19:37:42 -0800315
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700316void DebugInvokeReq::VisitRoots(RootVisitor* visitor, const RootInfo& root_info) {
317 receiver.VisitRootIfNonNull(visitor, root_info); // null for static method call.
318 klass.VisitRoot(visitor, root_info);
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700319}
320
Sebastien Hertz597c4f02015-01-26 17:37:14 +0100321void SingleStepControl::AddDexPc(uint32_t dex_pc) {
322 dex_pcs_.insert(dex_pc);
Sebastien Hertzbb43b432014-04-14 11:59:08 +0200323}
324
Sebastien Hertz597c4f02015-01-26 17:37:14 +0100325bool SingleStepControl::ContainsDexPc(uint32_t dex_pc) const {
326 return dex_pcs_.find(dex_pc) == dex_pcs_.end();
Sebastien Hertzbb43b432014-04-14 11:59:08 +0200327}
328
Alex Light6c8467f2015-11-20 15:03:26 -0800329static bool IsBreakpoint(ArtMethod* m, uint32_t dex_pc)
Mathieu Chartier90443472015-07-16 20:32:27 -0700330 REQUIRES(!Locks::breakpoint_lock_)
331 SHARED_REQUIRES(Locks::mutator_lock_) {
Sebastien Hertzed2be172014-08-19 15:33:43 +0200332 ReaderMutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100333 for (size_t i = 0, e = gBreakpoints.size(); i < e; ++i) {
Alex Light6c8467f2015-11-20 15:03:26 -0800334 if (gBreakpoints[i].DexPc() == dex_pc && gBreakpoints[i].IsInMethod(m)) {
Elliott Hughes86964332012-02-15 19:37:42 -0800335 VLOG(jdwp) << "Hit breakpoint #" << i << ": " << gBreakpoints[i];
336 return true;
337 }
338 }
339 return false;
340}
341
Sebastien Hertz52d131d2014-03-13 16:17:40 +0100342static bool IsSuspendedForDebugger(ScopedObjectAccessUnchecked& soa, Thread* thread)
Mathieu Chartier90443472015-07-16 20:32:27 -0700343 REQUIRES(!Locks::thread_suspend_count_lock_) {
Elliott Hughes9e0c1752013-01-09 14:02:58 -0800344 MutexLock mu(soa.Self(), *Locks::thread_suspend_count_lock_);
345 // A thread may be suspended for GC; in this code, we really want to know whether
346 // there's a debugger suspension active.
347 return thread->IsSuspended() && thread->GetDebugSuspendCount() > 0;
348}
349
Ian Rogersc0542af2014-09-03 16:16:56 -0700350static mirror::Array* DecodeNonNullArray(JDWP::RefTypeId id, JDWP::JdwpError* error)
Mathieu Chartier90443472015-07-16 20:32:27 -0700351 SHARED_REQUIRES(Locks::mutator_lock_) {
Sebastien Hertz6995c602014-09-09 12:10:13 +0200352 mirror::Object* o = Dbg::GetObjectRegistry()->Get<mirror::Object*>(id, error);
Ian Rogersc0542af2014-09-03 16:16:56 -0700353 if (o == nullptr) {
354 *error = JDWP::ERR_INVALID_OBJECT;
355 return nullptr;
Elliott Hughes436e3722012-02-17 20:01:47 -0800356 }
357 if (!o->IsArrayInstance()) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700358 *error = JDWP::ERR_INVALID_ARRAY;
359 return nullptr;
Elliott Hughes436e3722012-02-17 20:01:47 -0800360 }
Ian Rogersc0542af2014-09-03 16:16:56 -0700361 *error = JDWP::ERR_NONE;
Elliott Hughes436e3722012-02-17 20:01:47 -0800362 return o->AsArray();
363}
364
Ian Rogersc0542af2014-09-03 16:16:56 -0700365static mirror::Class* DecodeClass(JDWP::RefTypeId id, JDWP::JdwpError* error)
Mathieu Chartier90443472015-07-16 20:32:27 -0700366 SHARED_REQUIRES(Locks::mutator_lock_) {
Sebastien Hertz6995c602014-09-09 12:10:13 +0200367 mirror::Object* o = Dbg::GetObjectRegistry()->Get<mirror::Object*>(id, error);
Ian Rogersc0542af2014-09-03 16:16:56 -0700368 if (o == nullptr) {
369 *error = JDWP::ERR_INVALID_OBJECT;
370 return nullptr;
Elliott Hughes436e3722012-02-17 20:01:47 -0800371 }
372 if (!o->IsClass()) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700373 *error = JDWP::ERR_INVALID_CLASS;
374 return nullptr;
Elliott Hughes436e3722012-02-17 20:01:47 -0800375 }
Ian Rogersc0542af2014-09-03 16:16:56 -0700376 *error = JDWP::ERR_NONE;
Elliott Hughes436e3722012-02-17 20:01:47 -0800377 return o->AsClass();
378}
379
Ian Rogersc0542af2014-09-03 16:16:56 -0700380static Thread* DecodeThread(ScopedObjectAccessUnchecked& soa, JDWP::ObjectId thread_id,
381 JDWP::JdwpError* error)
Mathieu Chartier90443472015-07-16 20:32:27 -0700382 SHARED_REQUIRES(Locks::mutator_lock_)
383 REQUIRES(!Locks::thread_list_lock_, !Locks::thread_suspend_count_lock_) {
Sebastien Hertz6995c602014-09-09 12:10:13 +0200384 mirror::Object* thread_peer = Dbg::GetObjectRegistry()->Get<mirror::Object*>(thread_id, error);
Ian Rogersc0542af2014-09-03 16:16:56 -0700385 if (thread_peer == nullptr) {
Elliott Hughes221229c2013-01-08 18:17:50 -0800386 // This isn't even an object.
Ian Rogersc0542af2014-09-03 16:16:56 -0700387 *error = JDWP::ERR_INVALID_OBJECT;
388 return nullptr;
Elliott Hughes436e3722012-02-17 20:01:47 -0800389 }
Elliott Hughes221229c2013-01-08 18:17:50 -0800390
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800391 mirror::Class* java_lang_Thread = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_Thread);
Elliott Hughes221229c2013-01-08 18:17:50 -0800392 if (!java_lang_Thread->IsAssignableFrom(thread_peer->GetClass())) {
393 // This isn't a thread.
Ian Rogersc0542af2014-09-03 16:16:56 -0700394 *error = JDWP::ERR_INVALID_THREAD;
395 return nullptr;
Elliott Hughes221229c2013-01-08 18:17:50 -0800396 }
397
Sebastien Hertz69206392015-04-07 15:54:25 +0200398 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogersc0542af2014-09-03 16:16:56 -0700399 Thread* thread = Thread::FromManagedThread(soa, thread_peer);
400 // If thread is null then this a java.lang.Thread without a Thread*. Must be a un-started or a
401 // zombie.
402 *error = (thread == nullptr) ? JDWP::ERR_THREAD_NOT_ALIVE : JDWP::ERR_NONE;
403 return thread;
Elliott Hughes436e3722012-02-17 20:01:47 -0800404}
405
Elliott Hughes24437992011-11-30 14:49:33 -0800406static JDWP::JdwpTag BasicTagFromDescriptor(const char* descriptor) {
407 // JDWP deliberately uses the descriptor characters' ASCII values for its enum.
408 // Note that by "basic" we mean that we don't get more specific than JT_OBJECT.
409 return static_cast<JDWP::JdwpTag>(descriptor[0]);
410}
411
Ian Rogers1ff3c982014-08-12 02:30:58 -0700412static JDWP::JdwpTag BasicTagFromClass(mirror::Class* klass)
Mathieu Chartier90443472015-07-16 20:32:27 -0700413 SHARED_REQUIRES(Locks::mutator_lock_) {
Ian Rogers1ff3c982014-08-12 02:30:58 -0700414 std::string temp;
415 const char* descriptor = klass->GetDescriptor(&temp);
416 return BasicTagFromDescriptor(descriptor);
417}
418
Ian Rogers98379392014-02-24 16:53:16 -0800419static JDWP::JdwpTag TagFromClass(const ScopedObjectAccessUnchecked& soa, mirror::Class* c)
Mathieu Chartier90443472015-07-16 20:32:27 -0700420 SHARED_REQUIRES(Locks::mutator_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700421 CHECK(c != nullptr);
Elliott Hughes24437992011-11-30 14:49:33 -0800422 if (c->IsArrayClass()) {
423 return JDWP::JT_ARRAY;
424 }
Elliott Hughes24437992011-11-30 14:49:33 -0800425 if (c->IsStringClass()) {
426 return JDWP::JT_STRING;
Elliott Hughes24437992011-11-30 14:49:33 -0800427 }
Ian Rogers98379392014-02-24 16:53:16 -0800428 if (c->IsClassClass()) {
429 return JDWP::JT_CLASS_OBJECT;
430 }
431 {
432 mirror::Class* thread_class = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_Thread);
433 if (thread_class->IsAssignableFrom(c)) {
434 return JDWP::JT_THREAD;
435 }
436 }
437 {
438 mirror::Class* thread_group_class =
439 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_ThreadGroup);
440 if (thread_group_class->IsAssignableFrom(c)) {
441 return JDWP::JT_THREAD_GROUP;
442 }
443 }
444 {
445 mirror::Class* class_loader_class =
446 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_ClassLoader);
447 if (class_loader_class->IsAssignableFrom(c)) {
448 return JDWP::JT_CLASS_LOADER;
449 }
450 }
451 return JDWP::JT_OBJECT;
Elliott Hughes24437992011-11-30 14:49:33 -0800452}
453
454/*
455 * Objects declared to hold Object might actually hold a more specific
456 * type. The debugger may take a special interest in these (e.g. it
457 * wants to display the contents of Strings), so we want to return an
458 * appropriate tag.
459 *
460 * Null objects are tagged JT_OBJECT.
461 */
Sebastien Hertz6995c602014-09-09 12:10:13 +0200462JDWP::JdwpTag Dbg::TagFromObject(const ScopedObjectAccessUnchecked& soa, mirror::Object* o) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700463 return (o == nullptr) ? JDWP::JT_OBJECT : TagFromClass(soa, o->GetClass());
Elliott Hughes24437992011-11-30 14:49:33 -0800464}
465
466static bool IsPrimitiveTag(JDWP::JdwpTag tag) {
467 switch (tag) {
468 case JDWP::JT_BOOLEAN:
469 case JDWP::JT_BYTE:
470 case JDWP::JT_CHAR:
471 case JDWP::JT_FLOAT:
472 case JDWP::JT_DOUBLE:
473 case JDWP::JT_INT:
474 case JDWP::JT_LONG:
475 case JDWP::JT_SHORT:
476 case JDWP::JT_VOID:
477 return true;
478 default:
479 return false;
480 }
481}
482
Sebastien Hertzb3b173b2015-02-06 09:16:32 +0100483void Dbg::StartJdwp() {
Elliott Hughesc0f09332012-03-26 13:27:06 -0700484 if (!gJdwpAllowed || !IsJdwpConfigured()) {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700485 // No JDWP for you!
486 return;
487 }
488
Ian Rogers719d1a32014-03-06 12:13:39 -0800489 CHECK(gRegistry == nullptr);
Elliott Hughes475fc232011-10-25 15:00:35 -0700490 gRegistry = new ObjectRegistry;
491
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700492 // Init JDWP if the debugger is enabled. This may connect out to a
493 // debugger, passively listen for a debugger, or block waiting for a
494 // debugger.
Sebastien Hertzb3b173b2015-02-06 09:16:32 +0100495 gJdwpState = JDWP::JdwpState::Create(&gJdwpOptions);
Ian Rogersc0542af2014-09-03 16:16:56 -0700496 if (gJdwpState == nullptr) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -0800497 // We probably failed because some other process has the port already, which means that
498 // if we don't abort the user is likely to think they're talking to us when they're actually
499 // talking to that other process.
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800500 LOG(FATAL) << "Debugger thread failed to initialize";
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700501 }
502
503 // If a debugger has already attached, send the "welcome" message.
504 // This may cause us to suspend all threads.
Elliott Hughes376a7a02011-10-24 18:35:55 -0700505 if (gJdwpState->IsActive()) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700506 ScopedObjectAccess soa(Thread::Current());
Sebastien Hertz7d955652014-10-22 10:57:10 +0200507 gJdwpState->PostVMStart();
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700508 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700509}
510
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700511void Dbg::StopJdwp() {
Sebastien Hertzc6345ef2014-08-18 19:26:39 +0200512 // Post VM_DEATH event before the JDWP connection is closed (either by the JDWP thread or the
513 // destruction of gJdwpState).
514 if (gJdwpState != nullptr && gJdwpState->IsActive()) {
515 gJdwpState->PostVMDeath();
516 }
Sebastien Hertz0376e6b2014-02-06 18:12:59 +0100517 // Prevent the JDWP thread from processing JDWP incoming packets after we close the connection.
Sebastien Hertz4e5b2082015-03-24 19:03:40 +0100518 Dispose();
Elliott Hughes376a7a02011-10-24 18:35:55 -0700519 delete gJdwpState;
Ian Rogers719d1a32014-03-06 12:13:39 -0800520 gJdwpState = nullptr;
Elliott Hughes475fc232011-10-25 15:00:35 -0700521 delete gRegistry;
Ian Rogers719d1a32014-03-06 12:13:39 -0800522 gRegistry = nullptr;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700523}
524
Elliott Hughes767a1472011-10-26 18:49:02 -0700525void Dbg::GcDidFinish() {
526 if (gDdmHpifWhen != HPIF_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700527 ScopedObjectAccess soa(Thread::Current());
Brian Carlstrom4d466a82014-05-08 19:05:29 -0700528 VLOG(jdwp) << "Sending heap info to DDM";
Elliott Hughes7162ad92011-10-27 14:08:42 -0700529 DdmSendHeapInfo(gDdmHpifWhen);
Elliott Hughes767a1472011-10-26 18:49:02 -0700530 }
531 if (gDdmHpsgWhen != HPSG_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700532 ScopedObjectAccess soa(Thread::Current());
Brian Carlstrom4d466a82014-05-08 19:05:29 -0700533 VLOG(jdwp) << "Dumping heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700534 DdmSendHeapSegments(false);
Elliott Hughes767a1472011-10-26 18:49:02 -0700535 }
536 if (gDdmNhsgWhen != 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 native heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700539 DdmSendHeapSegments(true);
Elliott Hughes767a1472011-10-26 18:49:02 -0700540 }
541}
542
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700543void Dbg::SetJdwpAllowed(bool allowed) {
544 gJdwpAllowed = allowed;
545}
546
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700547DebugInvokeReq* Dbg::GetInvokeReq() {
Elliott Hughes475fc232011-10-25 15:00:35 -0700548 return Thread::Current()->GetInvokeReq();
549}
550
551Thread* Dbg::GetDebugThread() {
Ian Rogersc0542af2014-09-03 16:16:56 -0700552 return (gJdwpState != nullptr) ? gJdwpState->GetDebugThread() : nullptr;
Elliott Hughes475fc232011-10-25 15:00:35 -0700553}
554
555void Dbg::ClearWaitForEventThread() {
Sebastien Hertz2bf93f42015-01-09 18:44:05 +0100556 gJdwpState->ReleaseJdwpTokenForEvent();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700557}
558
559void Dbg::Connected() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700560 CHECK(!gDebuggerConnected);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800561 VLOG(jdwp) << "JDWP has attached";
Elliott Hughes3bb81562011-10-21 18:52:59 -0700562 gDebuggerConnected = true;
Elliott Hughes86964332012-02-15 19:37:42 -0800563 gDisposed = false;
564}
565
Sebastien Hertzf3928792014-11-17 19:00:37 +0100566bool Dbg::RequiresDeoptimization() {
567 // We don't need deoptimization if everything runs with interpreter after
568 // enabling -Xint mode.
569 return !Runtime::Current()->GetInstrumentation()->IsForcedInterpretOnly();
570}
571
Mingyao Yang6ea1a0e2016-01-29 12:12:49 -0800572// Used to patch boot image method entry point to interpreter bridge.
573class UpdateEntryPointsClassVisitor : public ClassVisitor {
574 public:
575 explicit UpdateEntryPointsClassVisitor(instrumentation::Instrumentation* instrumentation)
576 : instrumentation_(instrumentation) {}
577
578 bool operator()(mirror::Class* klass) OVERRIDE REQUIRES(Locks::mutator_lock_) {
579 auto pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
580 for (auto& m : klass->GetMethods(pointer_size)) {
581 const void* code = m.GetEntryPointFromQuickCompiledCode();
582 if (Runtime::Current()->GetHeap()->IsInBootImageOatFile(code) &&
583 !m.IsNative() &&
584 !m.IsProxyMethod()) {
585 instrumentation_->UpdateMethodsCode(&m, GetQuickToInterpreterBridge());
586 }
587 }
588 return true;
589 }
590
591 private:
592 instrumentation::Instrumentation* const instrumentation_;
593};
594
Elliott Hughesa2155262011-11-16 16:26:58 -0800595void Dbg::GoActive() {
596 // Enable all debugging features, including scans for breakpoints.
597 // This is a no-op if we're already active.
598 // Only called from the JDWP handler thread.
Daniel Mihalyieb076692014-08-22 17:33:31 +0200599 if (IsDebuggerActive()) {
Elliott Hughesa2155262011-11-16 16:26:58 -0800600 return;
601 }
602
Mathieu Chartieraa516822015-10-02 15:53:37 -0700603 Thread* const self = Thread::Current();
Elliott Hughesc0f09332012-03-26 13:27:06 -0700604 {
605 // TODO: dalvik only warned if there were breakpoints left over. clear in Dbg::Disconnected?
Mathieu Chartieraa516822015-10-02 15:53:37 -0700606 ReaderMutexLock mu(self, *Locks::breakpoint_lock_);
Elliott Hughesc0f09332012-03-26 13:27:06 -0700607 CHECK_EQ(gBreakpoints.size(), 0U);
608 }
Elliott Hughesa2155262011-11-16 16:26:58 -0800609
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100610 {
Mathieu Chartieraa516822015-10-02 15:53:37 -0700611 MutexLock mu(self, *Locks::deoptimization_lock_);
Sebastien Hertz4d25df32014-03-21 17:44:46 +0100612 CHECK_EQ(deoptimization_requests_.size(), 0U);
613 CHECK_EQ(full_deoptimization_event_count_, 0U);
Sebastien Hertz42cd43f2014-05-13 14:15:41 +0200614 CHECK_EQ(dex_pc_change_event_ref_count_, 0U);
615 CHECK_EQ(method_enter_event_ref_count_, 0U);
616 CHECK_EQ(method_exit_event_ref_count_, 0U);
617 CHECK_EQ(field_read_event_ref_count_, 0U);
618 CHECK_EQ(field_write_event_ref_count_, 0U);
619 CHECK_EQ(exception_catch_event_ref_count_, 0U);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100620 }
621
Ian Rogers62d6c772013-02-27 08:32:07 -0800622 Runtime* runtime = Runtime::Current();
David Srbeckyf4480162016-03-16 00:06:24 +0000623 // Since boot image code may be AOT compiled as not debuggable, we need to patch
Mingyao Yang6ea1a0e2016-01-29 12:12:49 -0800624 // entry points of methods in boot image to interpreter bridge.
David Srbeckyf4480162016-03-16 00:06:24 +0000625 // However, the performance cost of this is non-negligible during native-debugging due to the
626 // forced JIT, so we keep the AOT code in that case in exchange for limited native debugging.
627 if (!runtime->GetInstrumentation()->IsForcedInterpretOnly() && !runtime->IsNativeDebuggable()) {
Mingyao Yang6ea1a0e2016-01-29 12:12:49 -0800628 ScopedObjectAccess soa(self);
629 UpdateEntryPointsClassVisitor visitor(runtime->GetInstrumentation());
630 runtime->GetClassLinker()->VisitClasses(&visitor);
631 }
632
Mathieu Chartier4f55e222015-09-04 13:26:21 -0700633 ScopedSuspendAll ssa(__FUNCTION__);
Sebastien Hertzf3928792014-11-17 19:00:37 +0100634 if (RequiresDeoptimization()) {
635 runtime->GetInstrumentation()->EnableDeoptimization();
636 }
Sebastien Hertz42cd43f2014-05-13 14:15:41 +0200637 instrumentation_events_ = 0;
Elliott Hughesa2155262011-11-16 16:26:58 -0800638 gDebuggerActive = true;
Ian Rogers62d6c772013-02-27 08:32:07 -0800639 LOG(INFO) << "Debugger is active";
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700640}
641
642void Dbg::Disconnected() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700643 CHECK(gDebuggerConnected);
644
Elliott Hughesc0f09332012-03-26 13:27:06 -0700645 LOG(INFO) << "Debugger is no longer active";
Elliott Hughes234ab152011-10-26 14:02:26 -0700646
Hiroshi Yamauchi98810e32016-05-24 14:55:40 -0700647 // Suspend all threads and exclusively acquire the mutator lock. Remove the debugger as a listener
Ian Rogers62d6c772013-02-27 08:32:07 -0800648 // and clear the object registry.
649 Runtime* runtime = Runtime::Current();
Ian Rogers62d6c772013-02-27 08:32:07 -0800650 Thread* self = Thread::Current();
Mathieu Chartier4f55e222015-09-04 13:26:21 -0700651 {
Mathieu Chartieraa516822015-10-02 15:53:37 -0700652 // Required for DisableDeoptimization.
653 gc::ScopedGCCriticalSection gcs(self,
654 gc::kGcCauseInstrumentation,
655 gc::kCollectorTypeInstrumentation);
Mathieu Chartier4f55e222015-09-04 13:26:21 -0700656 ScopedSuspendAll ssa(__FUNCTION__);
Mathieu Chartier4f55e222015-09-04 13:26:21 -0700657 // Debugger may not be active at this point.
658 if (IsDebuggerActive()) {
659 {
660 // Since we're going to disable deoptimization, we clear the deoptimization requests queue.
661 // This prevents us from having any pending deoptimization request when the debugger attaches
662 // to us again while no event has been requested yet.
Mathieu Chartiera6b1ead2015-10-06 10:32:38 -0700663 MutexLock mu(self, *Locks::deoptimization_lock_);
Mathieu Chartier4f55e222015-09-04 13:26:21 -0700664 deoptimization_requests_.clear();
665 full_deoptimization_event_count_ = 0U;
666 }
667 if (instrumentation_events_ != 0) {
668 runtime->GetInstrumentation()->RemoveListener(&gDebugInstrumentationListener,
669 instrumentation_events_);
670 instrumentation_events_ = 0;
671 }
672 if (RequiresDeoptimization()) {
673 runtime->GetInstrumentation()->DisableDeoptimization(kDbgInstrumentationKey);
674 }
675 gDebuggerActive = false;
Sebastien Hertzaaea7342014-02-25 15:10:04 +0100676 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100677 }
Sebastien Hertz55f65342015-01-13 22:48:34 +0100678
679 {
680 ScopedObjectAccess soa(self);
681 gRegistry->Clear();
682 }
683
684 gDebuggerConnected = false;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700685}
686
Sebastien Hertzb3b173b2015-02-06 09:16:32 +0100687void Dbg::ConfigureJdwp(const JDWP::JdwpOptions& jdwp_options) {
688 CHECK_NE(jdwp_options.transport, JDWP::kJdwpTransportUnknown);
689 gJdwpOptions = jdwp_options;
690 gJdwpConfigured = true;
691}
692
Elliott Hughesc0f09332012-03-26 13:27:06 -0700693bool Dbg::IsJdwpConfigured() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700694 return gJdwpConfigured;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700695}
696
697int64_t Dbg::LastDebuggerActivity() {
Elliott Hughesca951522011-12-05 12:01:32 -0800698 return gJdwpState->LastDebuggerActivity();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700699}
700
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700701void Dbg::UndoDebuggerSuspensions() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700702 Runtime::Current()->GetThreadList()->UndoDebuggerSuspensions();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700703}
704
Elliott Hughes88d63092013-01-09 09:55:54 -0800705std::string Dbg::GetClassName(JDWP::RefTypeId class_id) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700706 JDWP::JdwpError error;
707 mirror::Object* o = gRegistry->Get<mirror::Object*>(class_id, &error);
708 if (o == nullptr) {
709 if (error == JDWP::ERR_NONE) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700710 return "null";
Ian Rogersc0542af2014-09-03 16:16:56 -0700711 } else {
712 return StringPrintf("invalid object %p", reinterpret_cast<void*>(class_id));
713 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800714 }
715 if (!o->IsClass()) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700716 return StringPrintf("non-class %p", o); // This is only used for debugging output anyway.
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800717 }
Sebastien Hertz6995c602014-09-09 12:10:13 +0200718 return GetClassName(o->AsClass());
719}
720
721std::string Dbg::GetClassName(mirror::Class* klass) {
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +0200722 if (klass == nullptr) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700723 return "null";
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +0200724 }
Ian Rogers1ff3c982014-08-12 02:30:58 -0700725 std::string temp;
Sebastien Hertz6995c602014-09-09 12:10:13 +0200726 return DescriptorToName(klass->GetDescriptor(&temp));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700727}
728
Ian Rogersc0542af2014-09-03 16:16:56 -0700729JDWP::JdwpError Dbg::GetClassObject(JDWP::RefTypeId id, JDWP::ObjectId* class_object_id) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800730 JDWP::JdwpError status;
Ian Rogersc0542af2014-09-03 16:16:56 -0700731 mirror::Class* c = DecodeClass(id, &status);
732 if (c == nullptr) {
733 *class_object_id = 0;
Elliott Hughes436e3722012-02-17 20:01:47 -0800734 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800735 }
Ian Rogersc0542af2014-09-03 16:16:56 -0700736 *class_object_id = gRegistry->Add(c);
Elliott Hughes436e3722012-02-17 20:01:47 -0800737 return JDWP::ERR_NONE;
Elliott Hughes86964332012-02-15 19:37:42 -0800738}
739
Ian Rogersc0542af2014-09-03 16:16:56 -0700740JDWP::JdwpError Dbg::GetSuperclass(JDWP::RefTypeId id, JDWP::RefTypeId* superclass_id) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800741 JDWP::JdwpError status;
Ian Rogersc0542af2014-09-03 16:16:56 -0700742 mirror::Class* c = DecodeClass(id, &status);
743 if (c == nullptr) {
744 *superclass_id = 0;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800745 return status;
746 }
747 if (c->IsInterface()) {
748 // http://code.google.com/p/android/issues/detail?id=20856
Ian Rogersc0542af2014-09-03 16:16:56 -0700749 *superclass_id = 0;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800750 } else {
Ian Rogersc0542af2014-09-03 16:16:56 -0700751 *superclass_id = gRegistry->Add(c->GetSuperClass());
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800752 }
753 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700754}
755
Elliott Hughes436e3722012-02-17 20:01:47 -0800756JDWP::JdwpError Dbg::GetClassLoader(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700757 JDWP::JdwpError error;
Andreas Gampe7929a482015-12-30 19:33:49 -0800758 mirror::Class* c = DecodeClass(id, &error);
759 if (c == nullptr) {
760 return error;
Elliott Hughes436e3722012-02-17 20:01:47 -0800761 }
Andreas Gampe7929a482015-12-30 19:33:49 -0800762 expandBufAddObjectId(pReply, gRegistry->Add(c->GetClassLoader()));
Elliott Hughes436e3722012-02-17 20:01:47 -0800763 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700764}
765
Elliott Hughes436e3722012-02-17 20:01:47 -0800766JDWP::JdwpError Dbg::GetModifiers(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700767 JDWP::JdwpError error;
768 mirror::Class* c = DecodeClass(id, &error);
769 if (c == nullptr) {
770 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800771 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800772
773 uint32_t access_flags = c->GetAccessFlags() & kAccJavaFlagsMask;
774
Yevgeny Roubande34eea2014-02-15 01:06:03 +0700775 // Set ACC_SUPER. Dex files don't contain this flag but only classes are supposed to have it set,
776 // not interfaces.
Elliott Hughes436e3722012-02-17 20:01:47 -0800777 // Class.getModifiers doesn't return it, but JDWP does, so we set it here.
Yevgeny Roubande34eea2014-02-15 01:06:03 +0700778 if ((access_flags & kAccInterface) == 0) {
779 access_flags |= kAccSuper;
780 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800781
782 expandBufAdd4BE(pReply, access_flags);
783
784 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700785}
786
Ian Rogersc0542af2014-09-03 16:16:56 -0700787JDWP::JdwpError Dbg::GetMonitorInfo(JDWP::ObjectId object_id, JDWP::ExpandBuf* reply) {
788 JDWP::JdwpError error;
789 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
790 if (o == nullptr) {
Elliott Hughesf327e072013-01-09 16:01:26 -0800791 return JDWP::ERR_INVALID_OBJECT;
792 }
793
794 // Ensure all threads are suspended while we read objects' lock words.
795 Thread* self = Thread::Current();
Sebastien Hertz54263242014-03-19 18:16:50 +0100796 CHECK_EQ(self->GetState(), kRunnable);
Elliott Hughesf327e072013-01-09 16:01:26 -0800797
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700798 MonitorInfo monitor_info;
799 {
800 ScopedThreadSuspension sts(self, kSuspended);
Mathieu Chartier4f55e222015-09-04 13:26:21 -0700801 ScopedSuspendAll ssa(__FUNCTION__);
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700802 monitor_info = MonitorInfo(o);
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700803 }
Ian Rogersc0542af2014-09-03 16:16:56 -0700804 if (monitor_info.owner_ != nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700805 expandBufAddObjectId(reply, gRegistry->Add(monitor_info.owner_->GetPeer()));
Elliott Hughesf327e072013-01-09 16:01:26 -0800806 } else {
Ian Rogersc0542af2014-09-03 16:16:56 -0700807 expandBufAddObjectId(reply, gRegistry->Add(nullptr));
Elliott Hughesf327e072013-01-09 16:01:26 -0800808 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700809 expandBufAdd4BE(reply, monitor_info.entry_count_);
810 expandBufAdd4BE(reply, monitor_info.waiters_.size());
811 for (size_t i = 0; i < monitor_info.waiters_.size(); ++i) {
812 expandBufAddObjectId(reply, gRegistry->Add(monitor_info.waiters_[i]->GetPeer()));
Elliott Hughesf327e072013-01-09 16:01:26 -0800813 }
814 return JDWP::ERR_NONE;
815}
816
Elliott Hughes734b8c62013-01-11 15:32:45 -0800817JDWP::JdwpError Dbg::GetOwnedMonitors(JDWP::ObjectId thread_id,
Ian Rogersc0542af2014-09-03 16:16:56 -0700818 std::vector<JDWP::ObjectId>* monitors,
819 std::vector<uint32_t>* stack_depths) {
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800820 struct OwnedMonitorVisitor : public StackVisitor {
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700821 OwnedMonitorVisitor(Thread* thread, Context* context,
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -0700822 std::vector<JDWP::ObjectId>* monitor_vector,
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700823 std::vector<uint32_t>* stack_depth_vector)
Mathieu Chartier90443472015-07-16 20:32:27 -0700824 SHARED_REQUIRES(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +0100825 : StackVisitor(thread, context, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
826 current_stack_depth(0),
827 monitors(monitor_vector),
828 stack_depths(stack_depth_vector) {}
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800829
830 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
831 // annotalysis.
832 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
833 if (!GetMethod()->IsRuntimeMethod()) {
834 Monitor::VisitLocks(this, AppendOwnedMonitors, this);
Elliott Hughes734b8c62013-01-11 15:32:45 -0800835 ++current_stack_depth;
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800836 }
837 return true;
838 }
839
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -0700840 static void AppendOwnedMonitors(mirror::Object* owned_monitor, void* arg)
Mathieu Chartier90443472015-07-16 20:32:27 -0700841 SHARED_REQUIRES(Locks::mutator_lock_) {
Ian Rogers7a22fa62013-01-23 12:16:16 -0800842 OwnedMonitorVisitor* visitor = reinterpret_cast<OwnedMonitorVisitor*>(arg);
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -0700843 visitor->monitors->push_back(gRegistry->Add(owned_monitor));
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700844 visitor->stack_depths->push_back(visitor->current_stack_depth);
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800845 }
846
Elliott Hughes734b8c62013-01-11 15:32:45 -0800847 size_t current_stack_depth;
Ian Rogersc0542af2014-09-03 16:16:56 -0700848 std::vector<JDWP::ObjectId>* const monitors;
849 std::vector<uint32_t>* const stack_depths;
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800850 };
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800851
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700852 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz69206392015-04-07 15:54:25 +0200853 JDWP::JdwpError error;
854 Thread* thread = DecodeThread(soa, thread_id, &error);
855 if (thread == nullptr) {
856 return error;
857 }
858 if (!IsSuspendedForDebugger(soa, thread)) {
859 return JDWP::ERR_THREAD_NOT_SUSPENDED;
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700860 }
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -0700861 std::unique_ptr<Context> context(Context::Create());
Ian Rogersc0542af2014-09-03 16:16:56 -0700862 OwnedMonitorVisitor visitor(thread, context.get(), monitors, stack_depths);
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -0700863 visitor.WalkStack();
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800864 return JDWP::ERR_NONE;
865}
866
Sebastien Hertz52d131d2014-03-13 16:17:40 +0100867JDWP::JdwpError Dbg::GetContendedMonitor(JDWP::ObjectId thread_id,
Ian Rogersc0542af2014-09-03 16:16:56 -0700868 JDWP::ObjectId* contended_monitor) {
Elliott Hughesf9501702013-01-11 11:22:27 -0800869 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -0700870 *contended_monitor = 0;
Sebastien Hertz69206392015-04-07 15:54:25 +0200871 JDWP::JdwpError error;
872 Thread* thread = DecodeThread(soa, thread_id, &error);
873 if (thread == nullptr) {
874 return error;
Elliott Hughesf9501702013-01-11 11:22:27 -0800875 }
Sebastien Hertz69206392015-04-07 15:54:25 +0200876 if (!IsSuspendedForDebugger(soa, thread)) {
877 return JDWP::ERR_THREAD_NOT_SUSPENDED;
878 }
879 mirror::Object* contended_monitor_obj = Monitor::GetContendedMonitor(thread);
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700880 // Add() requires the thread_list_lock_ not held to avoid the lock
881 // level violation.
Ian Rogersc0542af2014-09-03 16:16:56 -0700882 *contended_monitor = gRegistry->Add(contended_monitor_obj);
Elliott Hughesf9501702013-01-11 11:22:27 -0800883 return JDWP::ERR_NONE;
884}
885
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800886JDWP::JdwpError Dbg::GetInstanceCounts(const std::vector<JDWP::RefTypeId>& class_ids,
Ian Rogersc0542af2014-09-03 16:16:56 -0700887 std::vector<uint64_t>* counts) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800888 gc::Heap* heap = Runtime::Current()->GetHeap();
889 heap->CollectGarbage(false);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800890 std::vector<mirror::Class*> classes;
Ian Rogersc0542af2014-09-03 16:16:56 -0700891 counts->clear();
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800892 for (size_t i = 0; i < class_ids.size(); ++i) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700893 JDWP::JdwpError error;
894 mirror::Class* c = DecodeClass(class_ids[i], &error);
895 if (c == nullptr) {
896 return error;
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800897 }
898 classes.push_back(c);
Ian Rogersc0542af2014-09-03 16:16:56 -0700899 counts->push_back(0);
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800900 }
Ian Rogersc0542af2014-09-03 16:16:56 -0700901 heap->CountInstances(classes, false, &(*counts)[0]);
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800902 return JDWP::ERR_NONE;
903}
904
Ian Rogersc0542af2014-09-03 16:16:56 -0700905JDWP::JdwpError Dbg::GetInstances(JDWP::RefTypeId class_id, int32_t max_count,
906 std::vector<JDWP::ObjectId>* instances) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800907 gc::Heap* heap = Runtime::Current()->GetHeap();
908 // We only want reachable instances, so do a GC.
909 heap->CollectGarbage(false);
Ian Rogersc0542af2014-09-03 16:16:56 -0700910 JDWP::JdwpError error;
911 mirror::Class* c = DecodeClass(class_id, &error);
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800912 if (c == nullptr) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700913 return error;
Elliott Hughes3b78c942013-01-15 17:35:41 -0800914 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800915 std::vector<mirror::Object*> raw_instances;
Elliott Hughes3b78c942013-01-15 17:35:41 -0800916 Runtime::Current()->GetHeap()->GetInstances(c, max_count, raw_instances);
917 for (size_t i = 0; i < raw_instances.size(); ++i) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700918 instances->push_back(gRegistry->Add(raw_instances[i]));
Elliott Hughes3b78c942013-01-15 17:35:41 -0800919 }
920 return JDWP::ERR_NONE;
921}
922
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800923JDWP::JdwpError Dbg::GetReferringObjects(JDWP::ObjectId object_id, int32_t max_count,
Ian Rogersc0542af2014-09-03 16:16:56 -0700924 std::vector<JDWP::ObjectId>* referring_objects) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800925 gc::Heap* heap = Runtime::Current()->GetHeap();
926 heap->CollectGarbage(false);
Ian Rogersc0542af2014-09-03 16:16:56 -0700927 JDWP::JdwpError error;
928 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
929 if (o == nullptr) {
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800930 return JDWP::ERR_INVALID_OBJECT;
931 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800932 std::vector<mirror::Object*> raw_instances;
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800933 heap->GetReferringObjects(o, max_count, raw_instances);
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800934 for (size_t i = 0; i < raw_instances.size(); ++i) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700935 referring_objects->push_back(gRegistry->Add(raw_instances[i]));
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800936 }
937 return JDWP::ERR_NONE;
938}
939
Ian Rogersc0542af2014-09-03 16:16:56 -0700940JDWP::JdwpError Dbg::DisableCollection(JDWP::ObjectId object_id) {
941 JDWP::JdwpError error;
942 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
943 if (o == nullptr) {
Sebastien Hertze96060a2013-12-11 12:06:28 +0100944 return JDWP::ERR_INVALID_OBJECT;
945 }
Elliott Hughes64f574f2013-02-20 14:57:12 -0800946 gRegistry->DisableCollection(object_id);
947 return JDWP::ERR_NONE;
948}
949
Ian Rogersc0542af2014-09-03 16:16:56 -0700950JDWP::JdwpError Dbg::EnableCollection(JDWP::ObjectId object_id) {
951 JDWP::JdwpError error;
952 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
Sebastien Hertze96060a2013-12-11 12:06:28 +0100953 // Unlike DisableCollection, JDWP specs do not state an invalid object causes an error. The RI
954 // also ignores these cases and never return an error. However it's not obvious why this command
955 // should behave differently from DisableCollection and IsCollected commands. So let's be more
956 // strict and return an error if this happens.
Ian Rogersc0542af2014-09-03 16:16:56 -0700957 if (o == nullptr) {
Sebastien Hertze96060a2013-12-11 12:06:28 +0100958 return JDWP::ERR_INVALID_OBJECT;
959 }
Elliott Hughes64f574f2013-02-20 14:57:12 -0800960 gRegistry->EnableCollection(object_id);
961 return JDWP::ERR_NONE;
962}
963
Ian Rogersc0542af2014-09-03 16:16:56 -0700964JDWP::JdwpError Dbg::IsCollected(JDWP::ObjectId object_id, bool* is_collected) {
965 *is_collected = true;
Sebastien Hertz65637eb2014-01-10 17:40:02 +0100966 if (object_id == 0) {
967 // Null object id is invalid.
Sebastien Hertze96060a2013-12-11 12:06:28 +0100968 return JDWP::ERR_INVALID_OBJECT;
969 }
Sebastien Hertz65637eb2014-01-10 17:40:02 +0100970 // JDWP specs state an INVALID_OBJECT error is returned if the object ID is not valid. However
971 // the RI seems to ignore this and assume object has been collected.
Ian Rogersc0542af2014-09-03 16:16:56 -0700972 JDWP::JdwpError error;
973 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
974 if (o != nullptr) {
975 *is_collected = gRegistry->IsCollected(object_id);
Sebastien Hertz65637eb2014-01-10 17:40:02 +0100976 }
Elliott Hughes64f574f2013-02-20 14:57:12 -0800977 return JDWP::ERR_NONE;
978}
979
Ian Rogersc0542af2014-09-03 16:16:56 -0700980void Dbg::DisposeObject(JDWP::ObjectId object_id, uint32_t reference_count) {
Elliott Hughes64f574f2013-02-20 14:57:12 -0800981 gRegistry->DisposeObject(object_id, reference_count);
982}
983
Sebastien Hertz6995c602014-09-09 12:10:13 +0200984JDWP::JdwpTypeTag Dbg::GetTypeTag(mirror::Class* klass) {
Sebastien Hertz4d8fd492014-03-28 16:29:41 +0100985 DCHECK(klass != nullptr);
986 if (klass->IsArrayClass()) {
987 return JDWP::TT_ARRAY;
988 } else if (klass->IsInterface()) {
989 return JDWP::TT_INTERFACE;
990 } else {
991 return JDWP::TT_CLASS;
992 }
993}
994
Elliott Hughes88d63092013-01-09 09:55:54 -0800995JDWP::JdwpError Dbg::GetReflectedType(JDWP::RefTypeId class_id, JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700996 JDWP::JdwpError error;
997 mirror::Class* c = DecodeClass(class_id, &error);
998 if (c == nullptr) {
999 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001000 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001001
Sebastien Hertz4d8fd492014-03-28 16:29:41 +01001002 JDWP::JdwpTypeTag type_tag = GetTypeTag(c);
1003 expandBufAdd1(pReply, type_tag);
Elliott Hughes88d63092013-01-09 09:55:54 -08001004 expandBufAddRefTypeId(pReply, class_id);
Elliott Hughes436e3722012-02-17 20:01:47 -08001005 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001006}
1007
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001008// Get the complete list of reference classes (i.e. all classes except
1009// the primitive types).
1010// Returns a newly-allocated buffer full of RefTypeId values.
1011class ClassListCreator : public ClassVisitor {
1012 public:
1013 explicit ClassListCreator(std::vector<JDWP::RefTypeId>* classes) : classes_(classes) {}
1014
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08001015 bool operator()(mirror::Class* c) OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001016 if (!c->IsPrimitive()) {
1017 classes_->push_back(Dbg::GetObjectRegistry()->AddRefType(c));
1018 }
1019 return true;
1020 }
1021
1022 private:
1023 std::vector<JDWP::RefTypeId>* const classes_;
1024};
1025
Ian Rogersc0542af2014-09-03 16:16:56 -07001026void Dbg::GetClassList(std::vector<JDWP::RefTypeId>* classes) {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001027 ClassListCreator clc(classes);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001028 Runtime::Current()->GetClassLinker()->VisitClassesWithoutClassesLock(&clc);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001029}
1030
Ian Rogers1ff3c982014-08-12 02:30:58 -07001031JDWP::JdwpError Dbg::GetClassInfo(JDWP::RefTypeId class_id, JDWP::JdwpTypeTag* pTypeTag,
1032 uint32_t* pStatus, std::string* pDescriptor) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001033 JDWP::JdwpError error;
1034 mirror::Class* c = DecodeClass(class_id, &error);
1035 if (c == nullptr) {
1036 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001037 }
1038
Elliott Hughesa2155262011-11-16 16:26:58 -08001039 if (c->IsArrayClass()) {
1040 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
1041 *pTypeTag = JDWP::TT_ARRAY;
1042 } else {
1043 if (c->IsErroneous()) {
1044 *pStatus = JDWP::CS_ERROR;
1045 } else {
1046 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED | JDWP::CS_INITIALIZED;
1047 }
1048 *pTypeTag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
1049 }
1050
Ian Rogersc0542af2014-09-03 16:16:56 -07001051 if (pDescriptor != nullptr) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07001052 std::string temp;
1053 *pDescriptor = c->GetDescriptor(&temp);
Elliott Hughesa2155262011-11-16 16:26:58 -08001054 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001055 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001056}
1057
Ian Rogersc0542af2014-09-03 16:16:56 -07001058void Dbg::FindLoadedClassBySignature(const char* descriptor, std::vector<JDWP::RefTypeId>* ids) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001059 std::vector<mirror::Class*> classes;
Igor Murashkinb1d8c312015-08-04 11:18:43 -07001060 Runtime::Current()->GetClassLinker()->LookupClasses(descriptor, classes);
Ian Rogersc0542af2014-09-03 16:16:56 -07001061 ids->clear();
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001062 for (size_t i = 0; i < classes.size(); ++i) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001063 ids->push_back(gRegistry->Add(classes[i]));
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001064 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001065}
1066
Ian Rogersc0542af2014-09-03 16:16:56 -07001067JDWP::JdwpError Dbg::GetReferenceType(JDWP::ObjectId object_id, JDWP::ExpandBuf* pReply) {
1068 JDWP::JdwpError error;
1069 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
1070 if (o == nullptr) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001071 return JDWP::ERR_INVALID_OBJECT;
Elliott Hughes499c5132011-11-17 14:55:11 -08001072 }
Elliott Hughes2435a572012-02-17 16:07:41 -08001073
Sebastien Hertz4d8fd492014-03-28 16:29:41 +01001074 JDWP::JdwpTypeTag type_tag = GetTypeTag(o->GetClass());
Elliott Hughes64f574f2013-02-20 14:57:12 -08001075 JDWP::RefTypeId type_id = gRegistry->AddRefType(o->GetClass());
Elliott Hughes2435a572012-02-17 16:07:41 -08001076
1077 expandBufAdd1(pReply, type_tag);
1078 expandBufAddRefTypeId(pReply, type_id);
1079
1080 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001081}
1082
Ian Rogersfc0e94b2013-09-23 23:51:32 -07001083JDWP::JdwpError Dbg::GetSignature(JDWP::RefTypeId class_id, std::string* signature) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001084 JDWP::JdwpError error;
1085 mirror::Class* c = DecodeClass(class_id, &error);
1086 if (c == nullptr) {
1087 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001088 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07001089 std::string temp;
1090 *signature = c->GetDescriptor(&temp);
Elliott Hughes1fe7afb2012-02-13 17:23:03 -08001091 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001092}
1093
Ian Rogersc0542af2014-09-03 16:16:56 -07001094JDWP::JdwpError Dbg::GetSourceFile(JDWP::RefTypeId class_id, std::string* result) {
1095 JDWP::JdwpError error;
1096 mirror::Class* c = DecodeClass(class_id, &error);
Sebastien Hertz4206eb52014-06-05 10:15:45 +02001097 if (c == nullptr) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001098 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001099 }
Sebastien Hertz4206eb52014-06-05 10:15:45 +02001100 const char* source_file = c->GetSourceFile();
1101 if (source_file == nullptr) {
Sebastien Hertzb7054ba2014-03-13 11:52:31 +01001102 return JDWP::ERR_ABSENT_INFORMATION;
1103 }
Ian Rogersc0542af2014-09-03 16:16:56 -07001104 *result = source_file;
Elliott Hughes436e3722012-02-17 20:01:47 -08001105 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001106}
1107
Ian Rogersc0542af2014-09-03 16:16:56 -07001108JDWP::JdwpError Dbg::GetObjectTag(JDWP::ObjectId object_id, uint8_t* tag) {
Ian Rogers98379392014-02-24 16:53:16 -08001109 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07001110 JDWP::JdwpError error;
1111 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
1112 if (error != JDWP::ERR_NONE) {
1113 *tag = JDWP::JT_VOID;
1114 return error;
Elliott Hughes546b9862012-06-20 16:06:13 -07001115 }
Ian Rogersc0542af2014-09-03 16:16:56 -07001116 *tag = TagFromObject(soa, o);
Elliott Hughes546b9862012-06-20 16:06:13 -07001117 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001118}
1119
Elliott Hughesaed4be92011-12-02 16:16:23 -08001120size_t Dbg::GetTagWidth(JDWP::JdwpTag tag) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001121 switch (tag) {
1122 case JDWP::JT_VOID:
1123 return 0;
1124 case JDWP::JT_BYTE:
1125 case JDWP::JT_BOOLEAN:
1126 return 1;
1127 case JDWP::JT_CHAR:
1128 case JDWP::JT_SHORT:
1129 return 2;
1130 case JDWP::JT_FLOAT:
1131 case JDWP::JT_INT:
1132 return 4;
1133 case JDWP::JT_ARRAY:
1134 case JDWP::JT_OBJECT:
1135 case JDWP::JT_STRING:
1136 case JDWP::JT_THREAD:
1137 case JDWP::JT_THREAD_GROUP:
1138 case JDWP::JT_CLASS_LOADER:
1139 case JDWP::JT_CLASS_OBJECT:
1140 return sizeof(JDWP::ObjectId);
1141 case JDWP::JT_DOUBLE:
1142 case JDWP::JT_LONG:
1143 return 8;
1144 default:
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001145 LOG(FATAL) << "Unknown tag " << tag;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001146 return -1;
1147 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001148}
1149
Ian Rogersc0542af2014-09-03 16:16:56 -07001150JDWP::JdwpError Dbg::GetArrayLength(JDWP::ObjectId array_id, int32_t* length) {
1151 JDWP::JdwpError error;
1152 mirror::Array* a = DecodeNonNullArray(array_id, &error);
1153 if (a == nullptr) {
1154 return error;
Elliott Hughes24437992011-11-30 14:49:33 -08001155 }
Ian Rogersc0542af2014-09-03 16:16:56 -07001156 *length = a->GetLength();
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001157 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001158}
1159
Elliott Hughes88d63092013-01-09 09:55:54 -08001160JDWP::JdwpError Dbg::OutputArray(JDWP::ObjectId array_id, int offset, int count, JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001161 JDWP::JdwpError error;
1162 mirror::Array* a = DecodeNonNullArray(array_id, &error);
Ian Rogers98379392014-02-24 16:53:16 -08001163 if (a == nullptr) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001164 return error;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001165 }
Elliott Hughes24437992011-11-30 14:49:33 -08001166
1167 if (offset < 0 || count < 0 || offset > a->GetLength() || a->GetLength() - offset < count) {
1168 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001169 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughes24437992011-11-30 14:49:33 -08001170 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07001171 JDWP::JdwpTag element_tag = BasicTagFromClass(a->GetClass()->GetComponentType());
1172 expandBufAdd1(pReply, element_tag);
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001173 expandBufAdd4BE(pReply, count);
1174
Ian Rogers1ff3c982014-08-12 02:30:58 -07001175 if (IsPrimitiveTag(element_tag)) {
1176 size_t width = GetTagWidth(element_tag);
Elliott Hughes24437992011-11-30 14:49:33 -08001177 uint8_t* dst = expandBufAddSpace(pReply, count * width);
1178 if (width == 8) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001179 const uint64_t* src8 = reinterpret_cast<uint64_t*>(a->GetRawData(sizeof(uint64_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001180 for (int i = 0; i < count; ++i) JDWP::Write8BE(&dst, src8[offset + i]);
1181 } else if (width == 4) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001182 const uint32_t* src4 = reinterpret_cast<uint32_t*>(a->GetRawData(sizeof(uint32_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001183 for (int i = 0; i < count; ++i) JDWP::Write4BE(&dst, src4[offset + i]);
1184 } else if (width == 2) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001185 const uint16_t* src2 = reinterpret_cast<uint16_t*>(a->GetRawData(sizeof(uint16_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001186 for (int i = 0; i < count; ++i) JDWP::Write2BE(&dst, src2[offset + i]);
1187 } else {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001188 const uint8_t* src = reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint8_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001189 memcpy(dst, &src[offset * width], count * width);
1190 }
1191 } else {
Ian Rogers98379392014-02-24 16:53:16 -08001192 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001193 mirror::ObjectArray<mirror::Object>* oa = a->AsObjectArray<mirror::Object>();
Elliott Hughes24437992011-11-30 14:49:33 -08001194 for (int i = 0; i < count; ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001195 mirror::Object* element = oa->Get(offset + i);
Ian Rogers98379392014-02-24 16:53:16 -08001196 JDWP::JdwpTag specific_tag = (element != nullptr) ? TagFromObject(soa, element)
Ian Rogers1ff3c982014-08-12 02:30:58 -07001197 : element_tag;
Elliott Hughes24437992011-11-30 14:49:33 -08001198 expandBufAdd1(pReply, specific_tag);
1199 expandBufAddObjectId(pReply, gRegistry->Add(element));
1200 }
1201 }
1202
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001203 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001204}
1205
Ian Rogersef7d42f2014-01-06 12:55:46 -08001206template <typename T>
Ian Rogersc0542af2014-09-03 16:16:56 -07001207static void CopyArrayData(mirror::Array* a, JDWP::Request* src, int offset, int count)
Ian Rogersef7d42f2014-01-06 12:55:46 -08001208 NO_THREAD_SAFETY_ANALYSIS {
1209 // TODO: fix when annotalysis correctly handles non-member functions.
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001210 DCHECK(a->GetClass()->IsPrimitiveArray());
1211
Ian Rogersef7d42f2014-01-06 12:55:46 -08001212 T* dst = reinterpret_cast<T*>(a->GetRawData(sizeof(T), offset));
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001213 for (int i = 0; i < count; ++i) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001214 *dst++ = src->ReadValue(sizeof(T));
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001215 }
1216}
1217
Elliott Hughes88d63092013-01-09 09:55:54 -08001218JDWP::JdwpError Dbg::SetArrayElements(JDWP::ObjectId array_id, int offset, int count,
Ian Rogersc0542af2014-09-03 16:16:56 -07001219 JDWP::Request* request) {
1220 JDWP::JdwpError error;
1221 mirror::Array* dst = DecodeNonNullArray(array_id, &error);
1222 if (dst == nullptr) {
1223 return error;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001224 }
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001225
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001226 if (offset < 0 || count < 0 || offset > dst->GetLength() || dst->GetLength() - offset < count) {
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001227 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001228 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001229 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07001230 JDWP::JdwpTag element_tag = BasicTagFromClass(dst->GetClass()->GetComponentType());
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001231
Ian Rogers1ff3c982014-08-12 02:30:58 -07001232 if (IsPrimitiveTag(element_tag)) {
1233 size_t width = GetTagWidth(element_tag);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001234 if (width == 8) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001235 CopyArrayData<uint64_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001236 } else if (width == 4) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001237 CopyArrayData<uint32_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001238 } else if (width == 2) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001239 CopyArrayData<uint16_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001240 } else {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001241 CopyArrayData<uint8_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001242 }
1243 } else {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001244 mirror::ObjectArray<mirror::Object>* oa = dst->AsObjectArray<mirror::Object>();
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001245 for (int i = 0; i < count; ++i) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001246 JDWP::ObjectId id = request->ReadObjectId();
Ian Rogersc0542af2014-09-03 16:16:56 -07001247 mirror::Object* o = gRegistry->Get<mirror::Object*>(id, &error);
1248 if (error != JDWP::ERR_NONE) {
1249 return error;
Elliott Hughes436e3722012-02-17 20:01:47 -08001250 }
Sebastien Hertz2e1c16d2015-08-28 11:57:49 +02001251 // Check if the object's type is compatible with the array's type.
1252 if (o != nullptr && !o->InstanceOf(oa->GetClass()->GetComponentType())) {
1253 return JDWP::ERR_TYPE_MISMATCH;
1254 }
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001255 oa->Set<false>(offset + i, o);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001256 }
1257 }
1258
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001259 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001260}
1261
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001262JDWP::JdwpError Dbg::CreateString(const std::string& str, JDWP::ObjectId* new_string_id) {
1263 Thread* self = Thread::Current();
1264 mirror::String* new_string = mirror::String::AllocFromModifiedUtf8(self, str.c_str());
1265 if (new_string == nullptr) {
1266 DCHECK(self->IsExceptionPending());
1267 self->ClearException();
1268 LOG(ERROR) << "Could not allocate string";
1269 *new_string_id = 0;
1270 return JDWP::ERR_OUT_OF_MEMORY;
1271 }
1272 *new_string_id = gRegistry->Add(new_string);
1273 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001274}
1275
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001276JDWP::JdwpError Dbg::CreateObject(JDWP::RefTypeId class_id, JDWP::ObjectId* new_object_id) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001277 JDWP::JdwpError error;
1278 mirror::Class* c = DecodeClass(class_id, &error);
1279 if (c == nullptr) {
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001280 *new_object_id = 0;
Ian Rogersc0542af2014-09-03 16:16:56 -07001281 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001282 }
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001283 Thread* self = Thread::Current();
Sebastien Hertz56d5e502015-11-03 17:38:35 +01001284 mirror::Object* new_object;
1285 if (c->IsStringClass()) {
1286 // Special case for java.lang.String.
1287 gc::AllocatorType allocator_type = Runtime::Current()->GetHeap()->GetCurrentAllocator();
1288 mirror::SetStringCountVisitor visitor(0);
1289 new_object = mirror::String::Alloc<true>(self, 0, allocator_type, visitor);
1290 } else {
1291 new_object = c->AllocObject(self);
1292 }
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001293 if (new_object == nullptr) {
1294 DCHECK(self->IsExceptionPending());
1295 self->ClearException();
1296 LOG(ERROR) << "Could not allocate object of type " << PrettyDescriptor(c);
1297 *new_object_id = 0;
1298 return JDWP::ERR_OUT_OF_MEMORY;
1299 }
1300 *new_object_id = gRegistry->Add(new_object);
Elliott Hughes436e3722012-02-17 20:01:47 -08001301 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001302}
1303
Elliott Hughesbf13d362011-12-08 15:51:37 -08001304/*
1305 * Used by Eclipse's "Display" view to evaluate "new byte[5]" to get "(byte[]) [0, 0, 0, 0, 0]".
1306 */
Elliott Hughes88d63092013-01-09 09:55:54 -08001307JDWP::JdwpError Dbg::CreateArrayObject(JDWP::RefTypeId array_class_id, uint32_t length,
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001308 JDWP::ObjectId* new_array_id) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001309 JDWP::JdwpError error;
1310 mirror::Class* c = DecodeClass(array_class_id, &error);
1311 if (c == nullptr) {
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001312 *new_array_id = 0;
Ian Rogersc0542af2014-09-03 16:16:56 -07001313 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001314 }
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001315 Thread* self = Thread::Current();
1316 gc::Heap* heap = Runtime::Current()->GetHeap();
1317 mirror::Array* new_array = mirror::Array::Alloc<true>(self, c, length,
1318 c->GetComponentSizeShift(),
1319 heap->GetCurrentAllocator());
1320 if (new_array == nullptr) {
1321 DCHECK(self->IsExceptionPending());
1322 self->ClearException();
1323 LOG(ERROR) << "Could not allocate array of type " << PrettyDescriptor(c);
1324 *new_array_id = 0;
1325 return JDWP::ERR_OUT_OF_MEMORY;
1326 }
1327 *new_array_id = gRegistry->Add(new_array);
Elliott Hughes436e3722012-02-17 20:01:47 -08001328 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001329}
1330
Mathieu Chartierc7853442015-03-27 14:35:38 -07001331JDWP::FieldId Dbg::ToFieldId(const ArtField* f) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001332 return static_cast<JDWP::FieldId>(reinterpret_cast<uintptr_t>(f));
Elliott Hughes03181a82011-11-17 17:22:21 -08001333}
1334
Alex Light6c8467f2015-11-20 15:03:26 -08001335static JDWP::MethodId ToMethodId(ArtMethod* m)
Mathieu Chartier90443472015-07-16 20:32:27 -07001336 SHARED_REQUIRES(Locks::mutator_lock_) {
Alex Light6c8467f2015-11-20 15:03:26 -08001337 return static_cast<JDWP::MethodId>(reinterpret_cast<uintptr_t>(GetCanonicalMethod(m)));
Elliott Hughes03181a82011-11-17 17:22:21 -08001338}
1339
Mathieu Chartierc7853442015-03-27 14:35:38 -07001340static ArtField* FromFieldId(JDWP::FieldId fid)
Mathieu Chartier90443472015-07-16 20:32:27 -07001341 SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001342 return reinterpret_cast<ArtField*>(static_cast<uintptr_t>(fid));
Elliott Hughesaed4be92011-12-02 16:16:23 -08001343}
1344
Mathieu Chartiere401d142015-04-22 13:56:20 -07001345static ArtMethod* FromMethodId(JDWP::MethodId mid)
Mathieu Chartier90443472015-07-16 20:32:27 -07001346 SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001347 return reinterpret_cast<ArtMethod*>(static_cast<uintptr_t>(mid));
Elliott Hughes03181a82011-11-17 17:22:21 -08001348}
1349
Sebastien Hertz6995c602014-09-09 12:10:13 +02001350bool Dbg::MatchThread(JDWP::ObjectId expected_thread_id, Thread* event_thread) {
1351 CHECK(event_thread != nullptr);
1352 JDWP::JdwpError error;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001353 mirror::Object* expected_thread_peer = gRegistry->Get<mirror::Object*>(
1354 expected_thread_id, &error);
Sebastien Hertz6995c602014-09-09 12:10:13 +02001355 return expected_thread_peer == event_thread->GetPeer();
1356}
1357
1358bool Dbg::MatchLocation(const JDWP::JdwpLocation& expected_location,
1359 const JDWP::EventLocation& event_location) {
1360 if (expected_location.dex_pc != event_location.dex_pc) {
1361 return false;
1362 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001363 ArtMethod* m = FromMethodId(expected_location.method_id);
Sebastien Hertz6995c602014-09-09 12:10:13 +02001364 return m == event_location.method;
1365}
1366
1367bool Dbg::MatchType(mirror::Class* event_class, JDWP::RefTypeId class_id) {
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001368 if (event_class == nullptr) {
1369 return false;
1370 }
Sebastien Hertz6995c602014-09-09 12:10:13 +02001371 JDWP::JdwpError error;
1372 mirror::Class* expected_class = DecodeClass(class_id, &error);
1373 CHECK(expected_class != nullptr);
1374 return expected_class->IsAssignableFrom(event_class);
1375}
1376
1377bool Dbg::MatchField(JDWP::RefTypeId expected_type_id, JDWP::FieldId expected_field_id,
Mathieu Chartierc7853442015-03-27 14:35:38 -07001378 ArtField* event_field) {
1379 ArtField* expected_field = FromFieldId(expected_field_id);
Sebastien Hertz6995c602014-09-09 12:10:13 +02001380 if (expected_field != event_field) {
1381 return false;
1382 }
1383 return Dbg::MatchType(event_field->GetDeclaringClass(), expected_type_id);
1384}
1385
1386bool Dbg::MatchInstance(JDWP::ObjectId expected_instance_id, mirror::Object* event_instance) {
1387 JDWP::JdwpError error;
1388 mirror::Object* modifier_instance = gRegistry->Get<mirror::Object*>(expected_instance_id, &error);
1389 return modifier_instance == event_instance;
1390}
1391
Mathieu Chartier90443472015-07-16 20:32:27 -07001392void Dbg::SetJdwpLocation(JDWP::JdwpLocation* location, ArtMethod* m, uint32_t dex_pc) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001393 if (m == nullptr) {
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001394 memset(location, 0, sizeof(*location));
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001395 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001396 mirror::Class* c = m->GetDeclaringClass();
Ian Rogersc0542af2014-09-03 16:16:56 -07001397 location->type_tag = GetTypeTag(c);
1398 location->class_id = gRegistry->AddRefType(c);
1399 location->method_id = ToMethodId(m);
1400 location->dex_pc = (m->IsNative() || m->IsProxyMethod()) ? static_cast<uint64_t>(-1) : dex_pc;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001401 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08001402}
1403
Ian Rogersc0542af2014-09-03 16:16:56 -07001404std::string Dbg::GetMethodName(JDWP::MethodId method_id) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001405 ArtMethod* m = FromMethodId(method_id);
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001406 if (m == nullptr) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001407 return "null";
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001408 }
Sebastien Hertz415fd082015-06-01 11:42:27 +02001409 return m->GetInterfaceMethodIfProxy(sizeof(void*))->GetName();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001410}
1411
Ian Rogersc0542af2014-09-03 16:16:56 -07001412std::string Dbg::GetFieldName(JDWP::FieldId field_id) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001413 ArtField* f = FromFieldId(field_id);
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001414 if (f == nullptr) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001415 return "null";
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001416 }
1417 return f->GetName();
Elliott Hughesa96836a2013-01-17 12:27:49 -08001418}
1419
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001420/*
1421 * Augment the access flags for synthetic methods and fields by setting
1422 * the (as described by the spec) "0xf0000000 bit". Also, strip out any
1423 * flags not specified by the Java programming language.
1424 */
1425static uint32_t MangleAccessFlags(uint32_t accessFlags) {
1426 accessFlags &= kAccJavaFlagsMask;
1427 if ((accessFlags & kAccSynthetic) != 0) {
1428 accessFlags |= 0xf0000000;
1429 }
1430 return accessFlags;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001431}
1432
Elliott Hughesdbb40792011-11-18 17:05:22 -08001433/*
Jeff Haob7cefc72013-11-14 14:51:09 -08001434 * Circularly shifts registers so that arguments come first. Debuggers
1435 * expect slots to begin with arguments, but dex code places them at
1436 * the end.
Elliott Hughesdbb40792011-11-18 17:05:22 -08001437 */
Mathieu Chartiere401d142015-04-22 13:56:20 -07001438static uint16_t MangleSlot(uint16_t slot, ArtMethod* m)
Mathieu Chartier90443472015-07-16 20:32:27 -07001439 SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001440 const DexFile::CodeItem* code_item = m->GetCodeItem();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001441 if (code_item == nullptr) {
1442 // We should not get here for a method without code (native, proxy or abstract). Log it and
1443 // return the slot as is since all registers are arguments.
1444 LOG(WARNING) << "Trying to mangle slot for method without code " << PrettyMethod(m);
1445 return slot;
1446 }
Jeff Haob7cefc72013-11-14 14:51:09 -08001447 uint16_t ins_size = code_item->ins_size_;
1448 uint16_t locals_size = code_item->registers_size_ - ins_size;
1449 if (slot >= locals_size) {
1450 return slot - locals_size;
1451 } else {
1452 return slot + ins_size;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001453 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001454}
1455
Jeff Haob7cefc72013-11-14 14:51:09 -08001456/*
1457 * Circularly shifts registers so that arguments come last. Reverts
1458 * slots to dex style argument placement.
1459 */
Mathieu Chartiere401d142015-04-22 13:56:20 -07001460static uint16_t DemangleSlot(uint16_t slot, ArtMethod* m, JDWP::JdwpError* error)
Mathieu Chartier90443472015-07-16 20:32:27 -07001461 SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001462 const DexFile::CodeItem* code_item = m->GetCodeItem();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001463 if (code_item == nullptr) {
1464 // We should not get here for a method without code (native, proxy or abstract). Log it and
1465 // return the slot as is since all registers are arguments.
1466 LOG(WARNING) << "Trying to demangle slot for method without code " << PrettyMethod(m);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001467 uint16_t vreg_count = ArtMethod::NumArgRegisters(m->GetShorty());
Sebastien Hertzabbabc82015-03-26 08:47:47 +01001468 if (slot < vreg_count) {
1469 *error = JDWP::ERR_NONE;
1470 return slot;
1471 }
Jeff Haob7cefc72013-11-14 14:51:09 -08001472 } else {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01001473 if (slot < code_item->registers_size_) {
1474 uint16_t ins_size = code_item->ins_size_;
1475 uint16_t locals_size = code_item->registers_size_ - ins_size;
1476 *error = JDWP::ERR_NONE;
1477 return (slot < ins_size) ? slot + locals_size : slot - ins_size;
1478 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001479 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01001480
1481 // Slot is invalid in the method.
1482 LOG(ERROR) << "Invalid local slot " << slot << " for method " << PrettyMethod(m);
1483 *error = JDWP::ERR_INVALID_SLOT;
1484 return DexFile::kDexNoIndex16;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001485}
1486
Mathieu Chartier90443472015-07-16 20:32:27 -07001487JDWP::JdwpError Dbg::OutputDeclaredFields(JDWP::RefTypeId class_id, bool with_generic,
1488 JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001489 JDWP::JdwpError error;
1490 mirror::Class* c = DecodeClass(class_id, &error);
1491 if (c == nullptr) {
1492 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001493 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001494
1495 size_t instance_field_count = c->NumInstanceFields();
1496 size_t static_field_count = c->NumStaticFields();
1497
1498 expandBufAdd4BE(pReply, instance_field_count + static_field_count);
1499
1500 for (size_t i = 0; i < instance_field_count + static_field_count; ++i) {
Mathieu Chartier90443472015-07-16 20:32:27 -07001501 ArtField* f = (i < instance_field_count) ? c->GetInstanceField(i) :
1502 c->GetStaticField(i - instance_field_count);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001503 expandBufAddFieldId(pReply, ToFieldId(f));
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001504 expandBufAddUtf8String(pReply, f->GetName());
1505 expandBufAddUtf8String(pReply, f->GetTypeDescriptor());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001506 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001507 static const char genericSignature[1] = "";
1508 expandBufAddUtf8String(pReply, genericSignature);
1509 }
1510 expandBufAdd4BE(pReply, MangleAccessFlags(f->GetAccessFlags()));
1511 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001512 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001513}
1514
Elliott Hughes88d63092013-01-09 09:55:54 -08001515JDWP::JdwpError Dbg::OutputDeclaredMethods(JDWP::RefTypeId class_id, bool with_generic,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001516 JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001517 JDWP::JdwpError error;
1518 mirror::Class* c = DecodeClass(class_id, &error);
1519 if (c == nullptr) {
1520 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001521 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001522
Alex Light51a64d52015-12-17 13:55:59 -08001523 expandBufAdd4BE(pReply, c->NumMethods());
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001524
Mathieu Chartiere401d142015-04-22 13:56:20 -07001525 auto* cl = Runtime::Current()->GetClassLinker();
1526 auto ptr_size = cl->GetImagePointerSize();
Alex Light51a64d52015-12-17 13:55:59 -08001527 for (ArtMethod& m : c->GetMethods(ptr_size)) {
1528 expandBufAddMethodId(pReply, ToMethodId(&m));
1529 expandBufAddUtf8String(pReply, m.GetInterfaceMethodIfProxy(sizeof(void*))->GetName());
Sebastien Hertz415fd082015-06-01 11:42:27 +02001530 expandBufAddUtf8String(pReply,
Alex Light51a64d52015-12-17 13:55:59 -08001531 m.GetInterfaceMethodIfProxy(sizeof(void*))->GetSignature().ToString());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001532 if (with_generic) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001533 const char* generic_signature = "";
1534 expandBufAddUtf8String(pReply, generic_signature);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001535 }
Alex Light51a64d52015-12-17 13:55:59 -08001536 expandBufAdd4BE(pReply, MangleAccessFlags(m.GetAccessFlags()));
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001537 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001538 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001539}
1540
Elliott Hughes88d63092013-01-09 09:55:54 -08001541JDWP::JdwpError Dbg::OutputDeclaredInterfaces(JDWP::RefTypeId class_id, JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001542 JDWP::JdwpError error;
Mathieu Chartierf8322842014-05-16 10:59:25 -07001543 Thread* self = Thread::Current();
1544 StackHandleScope<1> hs(self);
Ian Rogersc0542af2014-09-03 16:16:56 -07001545 Handle<mirror::Class> c(hs.NewHandle(DecodeClass(class_id, &error)));
Mathieu Chartierf8322842014-05-16 10:59:25 -07001546 if (c.Get() == nullptr) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001547 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001548 }
Mathieu Chartierf8322842014-05-16 10:59:25 -07001549 size_t interface_count = c->NumDirectInterfaces();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001550 expandBufAdd4BE(pReply, interface_count);
1551 for (size_t i = 0; i < interface_count; ++i) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07001552 expandBufAddRefTypeId(pReply,
1553 gRegistry->AddRefType(mirror::Class::GetDirectInterface(self, c, i)));
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001554 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001555 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001556}
1557
Ian Rogersc0542af2014-09-03 16:16:56 -07001558void Dbg::OutputLineTable(JDWP::RefTypeId, JDWP::MethodId method_id, JDWP::ExpandBuf* pReply) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001559 struct DebugCallbackContext {
1560 int numItems;
1561 JDWP::ExpandBuf* pReply;
1562
David Srbeckyb06e28e2015-12-10 13:15:00 +00001563 static bool Callback(void* context, const DexFile::PositionInfo& entry) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001564 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
David Srbeckyb06e28e2015-12-10 13:15:00 +00001565 expandBufAdd8BE(pContext->pReply, entry.address_);
1566 expandBufAdd4BE(pContext->pReply, entry.line_);
Elliott Hughes03181a82011-11-17 17:22:21 -08001567 pContext->numItems++;
Sebastien Hertzf2910ee2013-10-19 16:39:24 +02001568 return false;
Elliott Hughes03181a82011-11-17 17:22:21 -08001569 }
1570 };
Mathieu Chartiere401d142015-04-22 13:56:20 -07001571 ArtMethod* m = FromMethodId(method_id);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001572 const DexFile::CodeItem* code_item = m->GetCodeItem();
Elliott Hughes03181a82011-11-17 17:22:21 -08001573 uint64_t start, end;
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001574 if (code_item == nullptr) {
1575 DCHECK(m->IsNative() || m->IsProxyMethod());
Elliott Hughes03181a82011-11-17 17:22:21 -08001576 start = -1;
1577 end = -1;
1578 } else {
1579 start = 0;
jeffhao14f0db92012-12-14 17:50:42 -08001580 // Return the index of the last instruction
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001581 end = code_item->insns_size_in_code_units_ - 1;
Elliott Hughes03181a82011-11-17 17:22:21 -08001582 }
1583
1584 expandBufAdd8BE(pReply, start);
1585 expandBufAdd8BE(pReply, end);
1586
1587 // Add numLines later
1588 size_t numLinesOffset = expandBufGetLength(pReply);
1589 expandBufAdd4BE(pReply, 0);
1590
1591 DebugCallbackContext context;
1592 context.numItems = 0;
1593 context.pReply = pReply;
1594
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001595 if (code_item != nullptr) {
David Srbeckyb06e28e2015-12-10 13:15:00 +00001596 m->GetDexFile()->DecodeDebugPositionInfo(code_item, DebugCallbackContext::Callback, &context);
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001597 }
Elliott Hughes03181a82011-11-17 17:22:21 -08001598
1599 JDWP::Set4BE(expandBufGetBuffer(pReply) + numLinesOffset, context.numItems);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001600}
1601
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001602void Dbg::OutputVariableTable(JDWP::RefTypeId, JDWP::MethodId method_id, bool with_generic,
1603 JDWP::ExpandBuf* pReply) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001604 struct DebugCallbackContext {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001605 ArtMethod* method;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001606 JDWP::ExpandBuf* pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001607 size_t variable_count;
1608 bool with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001609
David Srbeckyb06e28e2015-12-10 13:15:00 +00001610 static void Callback(void* context, const DexFile::LocalInfo& entry)
Mathieu Chartier90443472015-07-16 20:32:27 -07001611 SHARED_REQUIRES(Locks::mutator_lock_) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001612 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
1613
David Srbeckyb06e28e2015-12-10 13:15:00 +00001614 uint16_t slot = entry.reg_;
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001615 VLOG(jdwp) << StringPrintf(" %2zd: %d(%d) '%s' '%s' '%s' actual slot=%d mangled slot=%d",
David Srbeckyb06e28e2015-12-10 13:15:00 +00001616 pContext->variable_count, entry.start_address_,
1617 entry.end_address_ - entry.start_address_,
1618 entry.name_, entry.descriptor_, entry.signature_, slot,
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001619 MangleSlot(slot, pContext->method));
Elliott Hughesdbb40792011-11-18 17:05:22 -08001620
Jeff Haob7cefc72013-11-14 14:51:09 -08001621 slot = MangleSlot(slot, pContext->method);
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001622
David Srbeckyb06e28e2015-12-10 13:15:00 +00001623 expandBufAdd8BE(pContext->pReply, entry.start_address_);
1624 expandBufAddUtf8String(pContext->pReply, entry.name_);
1625 expandBufAddUtf8String(pContext->pReply, entry.descriptor_);
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001626 if (pContext->with_generic) {
David Srbeckyb06e28e2015-12-10 13:15:00 +00001627 expandBufAddUtf8String(pContext->pReply, entry.signature_);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001628 }
David Srbeckyb06e28e2015-12-10 13:15:00 +00001629 expandBufAdd4BE(pContext->pReply, entry.end_address_- entry.start_address_);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001630 expandBufAdd4BE(pContext->pReply, slot);
1631
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001632 ++pContext->variable_count;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001633 }
1634 };
Mathieu Chartiere401d142015-04-22 13:56:20 -07001635 ArtMethod* m = FromMethodId(method_id);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001636
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001637 // arg_count considers doubles and longs to take 2 units.
1638 // variable_count considers everything to take 1 unit.
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001639 std::string shorty(m->GetShorty());
Mathieu Chartiere401d142015-04-22 13:56:20 -07001640 expandBufAdd4BE(pReply, ArtMethod::NumArgRegisters(shorty));
Elliott Hughesdbb40792011-11-18 17:05:22 -08001641
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001642 // We don't know the total number of variables yet, so leave a blank and update it later.
1643 size_t variable_count_offset = expandBufGetLength(pReply);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001644 expandBufAdd4BE(pReply, 0);
1645
1646 DebugCallbackContext context;
Jeff Haob7cefc72013-11-14 14:51:09 -08001647 context.method = m;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001648 context.pReply = pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001649 context.variable_count = 0;
1650 context.with_generic = with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001651
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001652 const DexFile::CodeItem* code_item = m->GetCodeItem();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001653 if (code_item != nullptr) {
David Srbeckyb06e28e2015-12-10 13:15:00 +00001654 m->GetDexFile()->DecodeDebugLocalInfo(
1655 code_item, m->IsStatic(), m->GetDexMethodIndex(), DebugCallbackContext::Callback,
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001656 &context);
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001657 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001658
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001659 JDWP::Set4BE(expandBufGetBuffer(pReply) + variable_count_offset, context.variable_count);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001660}
1661
Jeff Hao579b0242013-11-18 13:16:49 -08001662void Dbg::OutputMethodReturnValue(JDWP::MethodId method_id, const JValue* return_value,
1663 JDWP::ExpandBuf* pReply) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001664 ArtMethod* m = FromMethodId(method_id);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001665 JDWP::JdwpTag tag = BasicTagFromDescriptor(m->GetShorty());
Jeff Hao579b0242013-11-18 13:16:49 -08001666 OutputJValue(tag, return_value, pReply);
1667}
1668
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02001669void Dbg::OutputFieldValue(JDWP::FieldId field_id, const JValue* field_value,
1670 JDWP::ExpandBuf* pReply) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001671 ArtField* f = FromFieldId(field_id);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001672 JDWP::JdwpTag tag = BasicTagFromDescriptor(f->GetTypeDescriptor());
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02001673 OutputJValue(tag, field_value, pReply);
1674}
1675
Elliott Hughes9777ba22013-01-17 09:04:19 -08001676JDWP::JdwpError Dbg::GetBytecodes(JDWP::RefTypeId, JDWP::MethodId method_id,
Ian Rogersc0542af2014-09-03 16:16:56 -07001677 std::vector<uint8_t>* bytecodes) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001678 ArtMethod* m = FromMethodId(method_id);
Ian Rogersc0542af2014-09-03 16:16:56 -07001679 if (m == nullptr) {
Elliott Hughes9777ba22013-01-17 09:04:19 -08001680 return JDWP::ERR_INVALID_METHODID;
1681 }
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001682 const DexFile::CodeItem* code_item = m->GetCodeItem();
Elliott Hughes9777ba22013-01-17 09:04:19 -08001683 size_t byte_count = code_item->insns_size_in_code_units_ * 2;
1684 const uint8_t* begin = reinterpret_cast<const uint8_t*>(code_item->insns_);
1685 const uint8_t* end = begin + byte_count;
1686 for (const uint8_t* p = begin; p != end; ++p) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001687 bytecodes->push_back(*p);
Elliott Hughes9777ba22013-01-17 09:04:19 -08001688 }
1689 return JDWP::ERR_NONE;
1690}
1691
Elliott Hughes88d63092013-01-09 09:55:54 -08001692JDWP::JdwpTag Dbg::GetFieldBasicTag(JDWP::FieldId field_id) {
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001693 return BasicTagFromDescriptor(FromFieldId(field_id)->GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001694}
1695
Elliott Hughes88d63092013-01-09 09:55:54 -08001696JDWP::JdwpTag Dbg::GetStaticFieldBasicTag(JDWP::FieldId field_id) {
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001697 return BasicTagFromDescriptor(FromFieldId(field_id)->GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001698}
1699
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001700static JValue GetArtFieldValue(ArtField* f, mirror::Object* o)
Mathieu Chartier90443472015-07-16 20:32:27 -07001701 SHARED_REQUIRES(Locks::mutator_lock_) {
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001702 Primitive::Type fieldType = f->GetTypeAsPrimitiveType();
1703 JValue field_value;
1704 switch (fieldType) {
1705 case Primitive::kPrimBoolean:
1706 field_value.SetZ(f->GetBoolean(o));
1707 return field_value;
1708
1709 case Primitive::kPrimByte:
1710 field_value.SetB(f->GetByte(o));
1711 return field_value;
1712
1713 case Primitive::kPrimChar:
1714 field_value.SetC(f->GetChar(o));
1715 return field_value;
1716
1717 case Primitive::kPrimShort:
1718 field_value.SetS(f->GetShort(o));
1719 return field_value;
1720
1721 case Primitive::kPrimInt:
1722 case Primitive::kPrimFloat:
1723 // Int and Float must be treated as 32-bit values in JDWP.
1724 field_value.SetI(f->GetInt(o));
1725 return field_value;
1726
1727 case Primitive::kPrimLong:
1728 case Primitive::kPrimDouble:
1729 // Long and Double must be treated as 64-bit values in JDWP.
1730 field_value.SetJ(f->GetLong(o));
1731 return field_value;
1732
1733 case Primitive::kPrimNot:
1734 field_value.SetL(f->GetObject(o));
1735 return field_value;
1736
1737 case Primitive::kPrimVoid:
1738 LOG(FATAL) << "Attempt to read from field of type 'void'";
1739 UNREACHABLE();
1740 }
1741 LOG(FATAL) << "Attempt to read from field of unknown type";
1742 UNREACHABLE();
1743}
1744
Elliott Hughes88d63092013-01-09 09:55:54 -08001745static JDWP::JdwpError GetFieldValueImpl(JDWP::RefTypeId ref_type_id, JDWP::ObjectId object_id,
1746 JDWP::FieldId field_id, JDWP::ExpandBuf* pReply,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001747 bool is_static)
Mathieu Chartier90443472015-07-16 20:32:27 -07001748 SHARED_REQUIRES(Locks::mutator_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001749 JDWP::JdwpError error;
1750 mirror::Class* c = DecodeClass(ref_type_id, &error);
1751 if (ref_type_id != 0 && c == nullptr) {
1752 return error;
Elliott Hughes0cf74332012-02-23 23:14:00 -08001753 }
1754
Sebastien Hertz6995c602014-09-09 12:10:13 +02001755 mirror::Object* o = Dbg::GetObjectRegistry()->Get<mirror::Object*>(object_id, &error);
Ian Rogersc0542af2014-09-03 16:16:56 -07001756 if ((!is_static && o == nullptr) || error != JDWP::ERR_NONE) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001757 return JDWP::ERR_INVALID_OBJECT;
1758 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001759 ArtField* f = FromFieldId(field_id);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001760
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001761 mirror::Class* receiver_class = c;
Ian Rogersc0542af2014-09-03 16:16:56 -07001762 if (receiver_class == nullptr && o != nullptr) {
Elliott Hughes0cf74332012-02-23 23:14:00 -08001763 receiver_class = o->GetClass();
1764 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001765 // TODO: should we give up now if receiver_class is null?
Ian Rogersc0542af2014-09-03 16:16:56 -07001766 if (receiver_class != nullptr && !f->GetDeclaringClass()->IsAssignableFrom(receiver_class)) {
Elliott Hughes0cf74332012-02-23 23:14:00 -08001767 LOG(INFO) << "ERR_INVALID_FIELDID: " << PrettyField(f) << " " << PrettyClass(receiver_class);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001768 return JDWP::ERR_INVALID_FIELDID;
1769 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001770
Elliott Hughes0cf74332012-02-23 23:14:00 -08001771 // The RI only enforces the static/non-static mismatch in one direction.
1772 // TODO: should we change the tests and check both?
1773 if (is_static) {
1774 if (!f->IsStatic()) {
1775 return JDWP::ERR_INVALID_FIELDID;
1776 }
1777 } else {
1778 if (f->IsStatic()) {
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001779 LOG(WARNING) << "Ignoring non-nullptr receiver for ObjectReference.GetValues"
1780 << " on static field " << PrettyField(f);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001781 }
1782 }
jeffhao0dfbb7e2012-11-28 15:26:03 -08001783 if (f->IsStatic()) {
1784 o = f->GetDeclaringClass();
1785 }
Elliott Hughes0cf74332012-02-23 23:14:00 -08001786
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001787 JValue field_value(GetArtFieldValue(f, o));
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001788 JDWP::JdwpTag tag = BasicTagFromDescriptor(f->GetTypeDescriptor());
Jeff Hao579b0242013-11-18 13:16:49 -08001789 Dbg::OutputJValue(tag, &field_value, pReply);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001790 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001791}
1792
Elliott Hughes88d63092013-01-09 09:55:54 -08001793JDWP::JdwpError Dbg::GetFieldValue(JDWP::ObjectId object_id, JDWP::FieldId field_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001794 JDWP::ExpandBuf* pReply) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001795 return GetFieldValueImpl(0, object_id, field_id, pReply, false);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001796}
1797
Ian Rogersc0542af2014-09-03 16:16:56 -07001798JDWP::JdwpError Dbg::GetStaticFieldValue(JDWP::RefTypeId ref_type_id, JDWP::FieldId field_id,
1799 JDWP::ExpandBuf* pReply) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001800 return GetFieldValueImpl(ref_type_id, 0, field_id, pReply, true);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001801}
1802
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001803static JDWP::JdwpError SetArtFieldValue(ArtField* f, mirror::Object* o, uint64_t value, int width)
Mathieu Chartier90443472015-07-16 20:32:27 -07001804 SHARED_REQUIRES(Locks::mutator_lock_) {
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001805 Primitive::Type fieldType = f->GetTypeAsPrimitiveType();
1806 // Debugging only happens at runtime so we know we are not running in a transaction.
1807 static constexpr bool kNoTransactionMode = false;
1808 switch (fieldType) {
1809 case Primitive::kPrimBoolean:
1810 CHECK_EQ(width, 1);
1811 f->SetBoolean<kNoTransactionMode>(o, static_cast<uint8_t>(value));
1812 return JDWP::ERR_NONE;
1813
1814 case Primitive::kPrimByte:
1815 CHECK_EQ(width, 1);
1816 f->SetByte<kNoTransactionMode>(o, static_cast<uint8_t>(value));
1817 return JDWP::ERR_NONE;
1818
1819 case Primitive::kPrimChar:
1820 CHECK_EQ(width, 2);
1821 f->SetChar<kNoTransactionMode>(o, static_cast<uint16_t>(value));
1822 return JDWP::ERR_NONE;
1823
1824 case Primitive::kPrimShort:
1825 CHECK_EQ(width, 2);
1826 f->SetShort<kNoTransactionMode>(o, static_cast<int16_t>(value));
1827 return JDWP::ERR_NONE;
1828
1829 case Primitive::kPrimInt:
1830 case Primitive::kPrimFloat:
1831 CHECK_EQ(width, 4);
1832 // Int and Float must be treated as 32-bit values in JDWP.
1833 f->SetInt<kNoTransactionMode>(o, static_cast<int32_t>(value));
1834 return JDWP::ERR_NONE;
1835
1836 case Primitive::kPrimLong:
1837 case Primitive::kPrimDouble:
1838 CHECK_EQ(width, 8);
1839 // Long and Double must be treated as 64-bit values in JDWP.
1840 f->SetLong<kNoTransactionMode>(o, value);
1841 return JDWP::ERR_NONE;
1842
1843 case Primitive::kPrimNot: {
1844 JDWP::JdwpError error;
1845 mirror::Object* v = Dbg::GetObjectRegistry()->Get<mirror::Object*>(value, &error);
1846 if (error != JDWP::ERR_NONE) {
1847 return JDWP::ERR_INVALID_OBJECT;
1848 }
1849 if (v != nullptr) {
1850 mirror::Class* field_type;
1851 {
1852 StackHandleScope<2> hs(Thread::Current());
1853 HandleWrapper<mirror::Object> h_v(hs.NewHandleWrapper(&v));
1854 HandleWrapper<mirror::Object> h_o(hs.NewHandleWrapper(&o));
1855 field_type = f->GetType<true>();
1856 }
1857 if (!field_type->IsAssignableFrom(v->GetClass())) {
1858 return JDWP::ERR_INVALID_OBJECT;
1859 }
1860 }
1861 f->SetObject<kNoTransactionMode>(o, v);
1862 return JDWP::ERR_NONE;
1863 }
1864
1865 case Primitive::kPrimVoid:
1866 LOG(FATAL) << "Attempt to write to field of type 'void'";
1867 UNREACHABLE();
1868 }
1869 LOG(FATAL) << "Attempt to write to field of unknown type";
1870 UNREACHABLE();
1871}
1872
Elliott Hughes88d63092013-01-09 09:55:54 -08001873static JDWP::JdwpError SetFieldValueImpl(JDWP::ObjectId object_id, JDWP::FieldId field_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001874 uint64_t value, int width, bool is_static)
Mathieu Chartier90443472015-07-16 20:32:27 -07001875 SHARED_REQUIRES(Locks::mutator_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001876 JDWP::JdwpError error;
Sebastien Hertz6995c602014-09-09 12:10:13 +02001877 mirror::Object* o = Dbg::GetObjectRegistry()->Get<mirror::Object*>(object_id, &error);
Ian Rogersc0542af2014-09-03 16:16:56 -07001878 if ((!is_static && o == nullptr) || error != JDWP::ERR_NONE) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001879 return JDWP::ERR_INVALID_OBJECT;
1880 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001881 ArtField* f = FromFieldId(field_id);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001882
1883 // The RI only enforces the static/non-static mismatch in one direction.
1884 // TODO: should we change the tests and check both?
1885 if (is_static) {
1886 if (!f->IsStatic()) {
1887 return JDWP::ERR_INVALID_FIELDID;
1888 }
1889 } else {
1890 if (f->IsStatic()) {
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001891 LOG(WARNING) << "Ignoring non-nullptr receiver for ObjectReference.SetValues"
1892 << " on static field " << PrettyField(f);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001893 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001894 }
jeffhao0dfbb7e2012-11-28 15:26:03 -08001895 if (f->IsStatic()) {
1896 o = f->GetDeclaringClass();
1897 }
Sebastien Hertz05c26b32015-06-11 18:42:58 +02001898 return SetArtFieldValue(f, o, value, width);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001899}
1900
Elliott Hughes88d63092013-01-09 09:55:54 -08001901JDWP::JdwpError Dbg::SetFieldValue(JDWP::ObjectId object_id, JDWP::FieldId field_id, uint64_t value,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001902 int width) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001903 return SetFieldValueImpl(object_id, field_id, value, width, false);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001904}
1905
Elliott Hughes88d63092013-01-09 09:55:54 -08001906JDWP::JdwpError Dbg::SetStaticFieldValue(JDWP::FieldId field_id, uint64_t value, int width) {
1907 return SetFieldValueImpl(0, field_id, value, width, true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001908}
1909
Sebastien Hertzb0b0b492014-09-15 11:27:27 +02001910JDWP::JdwpError Dbg::StringToUtf8(JDWP::ObjectId string_id, std::string* str) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001911 JDWP::JdwpError error;
Sebastien Hertzb0b0b492014-09-15 11:27:27 +02001912 mirror::Object* obj = gRegistry->Get<mirror::Object*>(string_id, &error);
1913 if (error != JDWP::ERR_NONE) {
1914 return error;
1915 }
1916 if (obj == nullptr) {
1917 return JDWP::ERR_INVALID_OBJECT;
1918 }
1919 {
1920 ScopedObjectAccessUnchecked soa(Thread::Current());
1921 mirror::Class* java_lang_String = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_String);
1922 if (!java_lang_String->IsAssignableFrom(obj->GetClass())) {
1923 // This isn't a string.
1924 return JDWP::ERR_INVALID_STRING;
1925 }
1926 }
1927 *str = obj->AsString()->ToModifiedUtf8();
1928 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001929}
1930
Jeff Hao579b0242013-11-18 13:16:49 -08001931void Dbg::OutputJValue(JDWP::JdwpTag tag, const JValue* return_value, JDWP::ExpandBuf* pReply) {
1932 if (IsPrimitiveTag(tag)) {
1933 expandBufAdd1(pReply, tag);
1934 if (tag == JDWP::JT_BOOLEAN || tag == JDWP::JT_BYTE) {
1935 expandBufAdd1(pReply, return_value->GetI());
1936 } else if (tag == JDWP::JT_CHAR || tag == JDWP::JT_SHORT) {
1937 expandBufAdd2BE(pReply, return_value->GetI());
1938 } else if (tag == JDWP::JT_FLOAT || tag == JDWP::JT_INT) {
1939 expandBufAdd4BE(pReply, return_value->GetI());
1940 } else if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
1941 expandBufAdd8BE(pReply, return_value->GetJ());
1942 } else {
1943 CHECK_EQ(tag, JDWP::JT_VOID);
1944 }
1945 } else {
Ian Rogers98379392014-02-24 16:53:16 -08001946 ScopedObjectAccessUnchecked soa(Thread::Current());
Jeff Hao579b0242013-11-18 13:16:49 -08001947 mirror::Object* value = return_value->GetL();
Ian Rogers98379392014-02-24 16:53:16 -08001948 expandBufAdd1(pReply, TagFromObject(soa, value));
Jeff Hao579b0242013-11-18 13:16:49 -08001949 expandBufAddObjectId(pReply, gRegistry->Add(value));
1950 }
1951}
1952
Ian Rogersc0542af2014-09-03 16:16:56 -07001953JDWP::JdwpError Dbg::GetThreadName(JDWP::ObjectId thread_id, std::string* name) {
jeffhaoa77f0f62012-12-05 17:19:31 -08001954 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07001955 JDWP::JdwpError error;
Roland Levillain4b8f1ec2015-08-26 18:34:03 +01001956 DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08001957 if (error != JDWP::ERR_NONE && error != JDWP::ERR_THREAD_NOT_ALIVE) {
1958 return error;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001959 }
Elliott Hughes221229c2013-01-08 18:17:50 -08001960
1961 // We still need to report the zombie threads' names, so we can't just call Thread::GetThreadName.
Ian Rogersc0542af2014-09-03 16:16:56 -07001962 mirror::Object* thread_object = gRegistry->Get<mirror::Object*>(thread_id, &error);
1963 CHECK(thread_object != nullptr) << error;
Mathieu Chartierc7853442015-03-27 14:35:38 -07001964 ArtField* java_lang_Thread_name_field =
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001965 soa.DecodeField(WellKnownClasses::java_lang_Thread_name);
1966 mirror::String* s =
1967 reinterpret_cast<mirror::String*>(java_lang_Thread_name_field->GetObject(thread_object));
Ian Rogersc0542af2014-09-03 16:16:56 -07001968 if (s != nullptr) {
1969 *name = s->ToModifiedUtf8();
Elliott Hughes221229c2013-01-08 18:17:50 -08001970 }
1971 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001972}
1973
Elliott Hughes221229c2013-01-08 18:17:50 -08001974JDWP::JdwpError Dbg::GetThreadGroup(JDWP::ObjectId thread_id, JDWP::ExpandBuf* pReply) {
Sebastien Hertza06430c2014-09-15 19:21:30 +02001975 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07001976 JDWP::JdwpError error;
1977 mirror::Object* thread_object = gRegistry->Get<mirror::Object*>(thread_id, &error);
1978 if (error != JDWP::ERR_NONE) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001979 return JDWP::ERR_INVALID_OBJECT;
1980 }
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07001981 ScopedAssertNoThreadSuspension ants(soa.Self(), "Debugger: GetThreadGroup");
Elliott Hughes2435a572012-02-17 16:07:41 -08001982 // Okay, so it's an object, but is it actually a thread?
Roland Levillain4b8f1ec2015-08-26 18:34:03 +01001983 DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08001984 if (error == JDWP::ERR_THREAD_NOT_ALIVE) {
1985 // Zombie threads are in the null group.
1986 expandBufAddObjectId(pReply, JDWP::ObjectId(0));
Sebastien Hertz52d131d2014-03-13 16:17:40 +01001987 error = JDWP::ERR_NONE;
1988 } else if (error == JDWP::ERR_NONE) {
1989 mirror::Class* c = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_Thread);
1990 CHECK(c != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001991 ArtField* f = soa.DecodeField(WellKnownClasses::java_lang_Thread_group);
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07001992 CHECK(f != nullptr);
Sebastien Hertz52d131d2014-03-13 16:17:40 +01001993 mirror::Object* group = f->GetObject(thread_object);
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07001994 CHECK(group != nullptr);
Sebastien Hertz52d131d2014-03-13 16:17:40 +01001995 JDWP::ObjectId thread_group_id = gRegistry->Add(group);
1996 expandBufAddObjectId(pReply, thread_group_id);
Elliott Hughes221229c2013-01-08 18:17:50 -08001997 }
Sebastien Hertz52d131d2014-03-13 16:17:40 +01001998 return error;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001999}
2000
Sebastien Hertza06430c2014-09-15 19:21:30 +02002001static mirror::Object* DecodeThreadGroup(ScopedObjectAccessUnchecked& soa,
2002 JDWP::ObjectId thread_group_id, JDWP::JdwpError* error)
Mathieu Chartier90443472015-07-16 20:32:27 -07002003 SHARED_REQUIRES(Locks::mutator_lock_) {
Sebastien Hertz6995c602014-09-09 12:10:13 +02002004 mirror::Object* thread_group = Dbg::GetObjectRegistry()->Get<mirror::Object*>(thread_group_id,
2005 error);
Sebastien Hertza06430c2014-09-15 19:21:30 +02002006 if (*error != JDWP::ERR_NONE) {
2007 return nullptr;
2008 }
2009 if (thread_group == nullptr) {
2010 *error = JDWP::ERR_INVALID_OBJECT;
2011 return nullptr;
2012 }
Ian Rogers98379392014-02-24 16:53:16 -08002013 mirror::Class* c = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_ThreadGroup);
2014 CHECK(c != nullptr);
Sebastien Hertza06430c2014-09-15 19:21:30 +02002015 if (!c->IsAssignableFrom(thread_group->GetClass())) {
2016 // This is not a java.lang.ThreadGroup.
2017 *error = JDWP::ERR_INVALID_THREAD_GROUP;
2018 return nullptr;
2019 }
2020 *error = JDWP::ERR_NONE;
2021 return thread_group;
2022}
2023
2024JDWP::JdwpError Dbg::GetThreadGroupName(JDWP::ObjectId thread_group_id, JDWP::ExpandBuf* pReply) {
2025 ScopedObjectAccessUnchecked soa(Thread::Current());
2026 JDWP::JdwpError error;
2027 mirror::Object* thread_group = DecodeThreadGroup(soa, thread_group_id, &error);
2028 if (error != JDWP::ERR_NONE) {
2029 return error;
2030 }
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07002031 ScopedAssertNoThreadSuspension ants(soa.Self(), "Debugger: GetThreadGroupName");
Mathieu Chartierc7853442015-03-27 14:35:38 -07002032 ArtField* f = soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_name);
Ian Rogersc0542af2014-09-03 16:16:56 -07002033 CHECK(f != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002034 mirror::String* s = reinterpret_cast<mirror::String*>(f->GetObject(thread_group));
Sebastien Hertza06430c2014-09-15 19:21:30 +02002035
2036 std::string thread_group_name(s->ToModifiedUtf8());
2037 expandBufAddUtf8String(pReply, thread_group_name);
2038 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002039}
2040
Sebastien Hertza06430c2014-09-15 19:21:30 +02002041JDWP::JdwpError Dbg::GetThreadGroupParent(JDWP::ObjectId thread_group_id, JDWP::ExpandBuf* pReply) {
Ian Rogers98379392014-02-24 16:53:16 -08002042 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002043 JDWP::JdwpError error;
Sebastien Hertza06430c2014-09-15 19:21:30 +02002044 mirror::Object* thread_group = DecodeThreadGroup(soa, thread_group_id, &error);
2045 if (error != JDWP::ERR_NONE) {
2046 return error;
2047 }
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07002048 mirror::Object* parent;
2049 {
2050 ScopedAssertNoThreadSuspension ants(soa.Self(), "Debugger: GetThreadGroupParent");
Mathieu Chartierc7853442015-03-27 14:35:38 -07002051 ArtField* f = soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_parent);
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07002052 CHECK(f != nullptr);
2053 parent = f->GetObject(thread_group);
2054 }
Sebastien Hertza06430c2014-09-15 19:21:30 +02002055 JDWP::ObjectId parent_group_id = gRegistry->Add(parent);
2056 expandBufAddObjectId(pReply, parent_group_id);
2057 return JDWP::ERR_NONE;
2058}
2059
2060static void GetChildThreadGroups(ScopedObjectAccessUnchecked& soa, mirror::Object* thread_group,
2061 std::vector<JDWP::ObjectId>* child_thread_group_ids)
Mathieu Chartier90443472015-07-16 20:32:27 -07002062 SHARED_REQUIRES(Locks::mutator_lock_) {
Sebastien Hertza06430c2014-09-15 19:21:30 +02002063 CHECK(thread_group != nullptr);
2064
Przemyslaw Szczepaniak464595f2015-11-24 11:59:59 +00002065 // Get the int "ngroups" count of this thread group...
2066 ArtField* ngroups_field = soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_ngroups);
2067 CHECK(ngroups_field != nullptr);
2068 const int32_t size = ngroups_field->GetInt(thread_group);
2069 if (size == 0) {
2070 return;
Sebastien Hertze49e1952014-10-13 11:27:13 +02002071 }
Sebastien Hertza06430c2014-09-15 19:21:30 +02002072
Przemyslaw Szczepaniak464595f2015-11-24 11:59:59 +00002073 // Get the ThreadGroup[] "groups" out of this thread group...
2074 ArtField* groups_field = soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_groups);
2075 mirror::Object* groups_array = groups_field->GetObject(thread_group);
2076
2077 CHECK(groups_array != nullptr);
2078 CHECK(groups_array->IsObjectArray());
2079
2080 mirror::ObjectArray<mirror::Object>* groups_array_as_array =
2081 groups_array->AsObjectArray<mirror::Object>();
Sebastien Hertza06430c2014-09-15 19:21:30 +02002082
2083 // Copy the first 'size' elements out of the array into the result.
Sebastien Hertz6995c602014-09-09 12:10:13 +02002084 ObjectRegistry* registry = Dbg::GetObjectRegistry();
Sebastien Hertza06430c2014-09-15 19:21:30 +02002085 for (int32_t i = 0; i < size; ++i) {
Przemyslaw Szczepaniak464595f2015-11-24 11:59:59 +00002086 child_thread_group_ids->push_back(registry->Add(groups_array_as_array->Get(i)));
Sebastien Hertza06430c2014-09-15 19:21:30 +02002087 }
2088}
2089
2090JDWP::JdwpError Dbg::GetThreadGroupChildren(JDWP::ObjectId thread_group_id,
2091 JDWP::ExpandBuf* pReply) {
2092 ScopedObjectAccessUnchecked soa(Thread::Current());
2093 JDWP::JdwpError error;
2094 mirror::Object* thread_group = DecodeThreadGroup(soa, thread_group_id, &error);
2095 if (error != JDWP::ERR_NONE) {
2096 return error;
2097 }
2098
2099 // Add child threads.
2100 {
2101 std::vector<JDWP::ObjectId> child_thread_ids;
2102 GetThreads(thread_group, &child_thread_ids);
2103 expandBufAdd4BE(pReply, child_thread_ids.size());
2104 for (JDWP::ObjectId child_thread_id : child_thread_ids) {
2105 expandBufAddObjectId(pReply, child_thread_id);
2106 }
2107 }
2108
2109 // Add child thread groups.
2110 {
2111 std::vector<JDWP::ObjectId> child_thread_groups_ids;
2112 GetChildThreadGroups(soa, thread_group, &child_thread_groups_ids);
2113 expandBufAdd4BE(pReply, child_thread_groups_ids.size());
2114 for (JDWP::ObjectId child_thread_group_id : child_thread_groups_ids) {
2115 expandBufAddObjectId(pReply, child_thread_group_id);
2116 }
2117 }
2118
2119 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002120}
2121
2122JDWP::ObjectId Dbg::GetSystemThreadGroupId() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002123 ScopedObjectAccessUnchecked soa(Thread::Current());
Mathieu Chartierc7853442015-03-27 14:35:38 -07002124 ArtField* f = soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_systemThreadGroup);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002125 mirror::Object* group = f->GetObject(f->GetDeclaringClass());
Ian Rogers365c1022012-06-22 15:05:28 -07002126 return gRegistry->Add(group);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002127}
2128
Jeff Hao920af3e2013-08-28 15:46:38 -07002129JDWP::JdwpThreadStatus Dbg::ToJdwpThreadStatus(ThreadState state) {
2130 switch (state) {
2131 case kBlocked:
2132 return JDWP::TS_MONITOR;
2133 case kNative:
2134 case kRunnable:
2135 case kSuspended:
2136 return JDWP::TS_RUNNING;
2137 case kSleeping:
2138 return JDWP::TS_SLEEPING;
2139 case kStarting:
2140 case kTerminated:
2141 return JDWP::TS_ZOMBIE;
2142 case kTimedWaiting:
Sebastien Hertzbae182c2013-12-17 10:42:03 +01002143 case kWaitingForCheckPointsToRun:
Jeff Hao920af3e2013-08-28 15:46:38 -07002144 case kWaitingForDebuggerSend:
2145 case kWaitingForDebuggerSuspension:
2146 case kWaitingForDebuggerToAttach:
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002147 case kWaitingForDeoptimization:
Jeff Hao920af3e2013-08-28 15:46:38 -07002148 case kWaitingForGcToComplete:
Mathieu Chartierb43390c2015-05-12 10:47:11 -07002149 case kWaitingForGetObjectsAllocated:
Jeff Hao920af3e2013-08-28 15:46:38 -07002150 case kWaitingForJniOnLoad:
Sebastien Hertzbae182c2013-12-17 10:42:03 +01002151 case kWaitingForMethodTracingStart:
Jeff Hao920af3e2013-08-28 15:46:38 -07002152 case kWaitingForSignalCatcherOutput:
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -08002153 case kWaitingForVisitObjects:
Jeff Hao920af3e2013-08-28 15:46:38 -07002154 case kWaitingInMainDebuggerLoop:
2155 case kWaitingInMainSignalCatcherLoop:
2156 case kWaitingPerformingGc:
Mathieu Chartier90ef3db2015-08-04 15:19:41 -07002157 case kWaitingWeakGcRootRead:
Hiroshi Yamauchi76f55b02015-08-21 16:10:39 -07002158 case kWaitingForGcThreadFlip:
Jeff Hao920af3e2013-08-28 15:46:38 -07002159 case kWaiting:
2160 return JDWP::TS_WAIT;
2161 // Don't add a 'default' here so the compiler can spot incompatible enum changes.
2162 }
2163 LOG(FATAL) << "Unknown thread state: " << state;
2164 return JDWP::TS_ZOMBIE;
2165}
2166
Sebastien Hertz52d131d2014-03-13 16:17:40 +01002167JDWP::JdwpError Dbg::GetThreadStatus(JDWP::ObjectId thread_id, JDWP::JdwpThreadStatus* pThreadStatus,
2168 JDWP::JdwpSuspendStatus* pSuspendStatus) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002169 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes499c5132011-11-17 14:55:11 -08002170
Elliott Hughes9e0c1752013-01-09 14:02:58 -08002171 *pSuspendStatus = JDWP::SUSPEND_STATUS_NOT_SUSPENDED;
2172
Ian Rogersc0542af2014-09-03 16:16:56 -07002173 JDWP::JdwpError error;
2174 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002175 if (error != JDWP::ERR_NONE) {
2176 if (error == JDWP::ERR_THREAD_NOT_ALIVE) {
2177 *pThreadStatus = JDWP::TS_ZOMBIE;
Elliott Hughes221229c2013-01-08 18:17:50 -08002178 return JDWP::ERR_NONE;
2179 }
2180 return error;
Elliott Hughes499c5132011-11-17 14:55:11 -08002181 }
2182
Elliott Hughes9e0c1752013-01-09 14:02:58 -08002183 if (IsSuspendedForDebugger(soa, thread)) {
2184 *pSuspendStatus = JDWP::SUSPEND_STATUS_SUSPENDED;
Elliott Hughes499c5132011-11-17 14:55:11 -08002185 }
2186
Jeff Hao920af3e2013-08-28 15:46:38 -07002187 *pThreadStatus = ToJdwpThreadStatus(thread->GetState());
Elliott Hughes221229c2013-01-08 18:17:50 -08002188 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002189}
2190
Elliott Hughes221229c2013-01-08 18:17:50 -08002191JDWP::JdwpError Dbg::GetThreadDebugSuspendCount(JDWP::ObjectId thread_id, JDWP::ExpandBuf* pReply) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002192 ScopedObjectAccess soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002193 JDWP::JdwpError error;
2194 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002195 if (error != JDWP::ERR_NONE) {
2196 return error;
Elliott Hughes2435a572012-02-17 16:07:41 -08002197 }
Ian Rogers50b35e22012-10-04 10:09:15 -07002198 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002199 expandBufAdd4BE(pReply, thread->GetDebugSuspendCount());
Elliott Hughes2435a572012-02-17 16:07:41 -08002200 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002201}
2202
Elliott Hughesf9501702013-01-11 11:22:27 -08002203JDWP::JdwpError Dbg::Interrupt(JDWP::ObjectId thread_id) {
2204 ScopedObjectAccess soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002205 JDWP::JdwpError error;
2206 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughesf9501702013-01-11 11:22:27 -08002207 if (error != JDWP::ERR_NONE) {
2208 return error;
2209 }
Ian Rogersdd7624d2014-03-14 17:43:00 -07002210 thread->Interrupt(soa.Self());
Elliott Hughesf9501702013-01-11 11:22:27 -08002211 return JDWP::ERR_NONE;
2212}
2213
Sebastien Hertz070f7322014-09-09 12:08:49 +02002214static bool IsInDesiredThreadGroup(ScopedObjectAccessUnchecked& soa,
2215 mirror::Object* desired_thread_group, mirror::Object* peer)
Mathieu Chartier90443472015-07-16 20:32:27 -07002216 SHARED_REQUIRES(Locks::mutator_lock_) {
Sebastien Hertz070f7322014-09-09 12:08:49 +02002217 // Do we want threads from all thread groups?
2218 if (desired_thread_group == nullptr) {
2219 return true;
2220 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07002221 ArtField* thread_group_field = soa.DecodeField(WellKnownClasses::java_lang_Thread_group);
Sebastien Hertz070f7322014-09-09 12:08:49 +02002222 DCHECK(thread_group_field != nullptr);
2223 mirror::Object* group = thread_group_field->GetObject(peer);
2224 return (group == desired_thread_group);
2225}
2226
Sebastien Hertza06430c2014-09-15 19:21:30 +02002227void Dbg::GetThreads(mirror::Object* thread_group, std::vector<JDWP::ObjectId>* thread_ids) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002228 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz070f7322014-09-09 12:08:49 +02002229 std::list<Thread*> all_threads_list;
2230 {
2231 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
2232 all_threads_list = Runtime::Current()->GetThreadList()->GetList();
2233 }
2234 for (Thread* t : all_threads_list) {
2235 if (t == Dbg::GetDebugThread()) {
2236 // Skip the JDWP thread. Some debuggers get bent out of shape when they can't suspend and
2237 // query all threads, so it's easier if we just don't tell them about this thread.
2238 continue;
2239 }
2240 if (t->IsStillStarting()) {
2241 // This thread is being started (and has been registered in the thread list). However, it is
2242 // not completely started yet so we must ignore it.
2243 continue;
2244 }
2245 mirror::Object* peer = t->GetPeer();
2246 if (peer == nullptr) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002247 // 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 +02002248 // this thread yet.
2249 // TODO: if we identified threads to the debugger by their Thread*
2250 // rather than their peer's mirror::Object*, we could fix this.
2251 // Doing so might help us report ZOMBIE threads too.
2252 continue;
2253 }
2254 if (IsInDesiredThreadGroup(soa, thread_group, peer)) {
2255 thread_ids->push_back(gRegistry->Add(peer));
2256 }
2257 }
Elliott Hughescaf76542012-06-28 16:08:22 -07002258}
Elliott Hughesa2155262011-11-16 16:26:58 -08002259
Mathieu Chartier90443472015-07-16 20:32:27 -07002260static int GetStackDepth(Thread* thread) SHARED_REQUIRES(Locks::mutator_lock_) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002261 struct CountStackDepthVisitor : public StackVisitor {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002262 explicit CountStackDepthVisitor(Thread* thread_in)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01002263 : StackVisitor(thread_in, nullptr, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
2264 depth(0) {}
Ian Rogers0399dde2012-06-06 17:09:28 -07002265
Elliott Hughes64f574f2013-02-20 14:57:12 -08002266 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2267 // annotalysis.
2268 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07002269 if (!GetMethod()->IsRuntimeMethod()) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -08002270 ++depth;
2271 }
Elliott Hughes530fa002012-03-12 11:44:49 -07002272 return true;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08002273 }
2274 size_t depth;
2275 };
Elliott Hughes08fc03a2012-06-26 17:34:00 -07002276
Ian Rogers7a22fa62013-01-23 12:16:16 -08002277 CountStackDepthVisitor visitor(thread);
Ian Rogers0399dde2012-06-06 17:09:28 -07002278 visitor.WalkStack();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08002279 return visitor.depth;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002280}
2281
Ian Rogersc0542af2014-09-03 16:16:56 -07002282JDWP::JdwpError Dbg::GetThreadFrameCount(JDWP::ObjectId thread_id, size_t* result) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002283 ScopedObjectAccess soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002284 JDWP::JdwpError error;
2285 *result = 0;
2286 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002287 if (error != JDWP::ERR_NONE) {
2288 return error;
2289 }
Elliott Hughesf15f4a02013-01-09 10:09:38 -08002290 if (!IsSuspendedForDebugger(soa, thread)) {
2291 return JDWP::ERR_THREAD_NOT_SUSPENDED;
2292 }
Ian Rogersc0542af2014-09-03 16:16:56 -07002293 *result = GetStackDepth(thread);
Elliott Hughes221229c2013-01-08 18:17:50 -08002294 return JDWP::ERR_NONE;
Elliott Hughes86964332012-02-15 19:37:42 -08002295}
2296
Ian Rogers306057f2012-11-26 12:45:53 -08002297JDWP::JdwpError Dbg::GetThreadFrames(JDWP::ObjectId thread_id, size_t start_frame,
2298 size_t frame_count, JDWP::ExpandBuf* buf) {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002299 class GetFrameVisitor : public StackVisitor {
2300 public:
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002301 GetFrameVisitor(Thread* thread, size_t start_frame_in, size_t frame_count_in,
2302 JDWP::ExpandBuf* buf_in)
Mathieu Chartier90443472015-07-16 20:32:27 -07002303 SHARED_REQUIRES(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01002304 : StackVisitor(thread, nullptr, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
2305 depth_(0),
2306 start_frame_(start_frame_in),
2307 frame_count_(frame_count_in),
2308 buf_(buf_in) {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002309 expandBufAdd4BE(buf_, frame_count_);
Elliott Hughes03181a82011-11-17 17:22:21 -08002310 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002311
Mathieu Chartier90443472015-07-16 20:32:27 -07002312 bool VisitFrame() OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002313 if (GetMethod()->IsRuntimeMethod()) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07002314 return true; // The debugger can't do anything useful with a frame that has no Method*.
Elliott Hughes03181a82011-11-17 17:22:21 -08002315 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002316 if (depth_ >= start_frame_ + frame_count_) {
Elliott Hughes530fa002012-03-12 11:44:49 -07002317 return false;
Elliott Hughes03181a82011-11-17 17:22:21 -08002318 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002319 if (depth_ >= start_frame_) {
2320 JDWP::FrameId frame_id(GetFrameId());
2321 JDWP::JdwpLocation location;
Sebastien Hertz6995c602014-09-09 12:10:13 +02002322 SetJdwpLocation(&location, GetMethod(), GetDexPc());
Ian Rogersef7d42f2014-01-06 12:55:46 -08002323 VLOG(jdwp) << StringPrintf(" Frame %3zd: id=%3" PRIu64 " ", depth_, frame_id) << location;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002324 expandBufAdd8BE(buf_, frame_id);
2325 expandBufAddLocation(buf_, location);
2326 }
2327 ++depth_;
Elliott Hughes530fa002012-03-12 11:44:49 -07002328 return true;
Elliott Hughes03181a82011-11-17 17:22:21 -08002329 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002330
2331 private:
2332 size_t depth_;
2333 const size_t start_frame_;
2334 const size_t frame_count_;
2335 JDWP::ExpandBuf* buf_;
Elliott Hughes03181a82011-11-17 17:22:21 -08002336 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002337
2338 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002339 JDWP::JdwpError error;
2340 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002341 if (error != JDWP::ERR_NONE) {
2342 return error;
2343 }
Elliott Hughesf15f4a02013-01-09 10:09:38 -08002344 if (!IsSuspendedForDebugger(soa, thread)) {
2345 return JDWP::ERR_THREAD_NOT_SUSPENDED;
2346 }
Ian Rogers7a22fa62013-01-23 12:16:16 -08002347 GetFrameVisitor visitor(thread, start_frame, frame_count, buf);
Ian Rogers0399dde2012-06-06 17:09:28 -07002348 visitor.WalkStack();
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002349 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002350}
2351
2352JDWP::ObjectId Dbg::GetThreadSelfId() {
Sebastien Hertz6995c602014-09-09 12:10:13 +02002353 return GetThreadId(Thread::Current());
2354}
2355
2356JDWP::ObjectId Dbg::GetThreadId(Thread* thread) {
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07002357 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz6995c602014-09-09 12:10:13 +02002358 return gRegistry->Add(thread->GetPeer());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002359}
2360
Elliott Hughes475fc232011-10-25 15:00:35 -07002361void Dbg::SuspendVM() {
Hiroshi Yamauchi8f95cf32016-04-19 11:14:06 -07002362 // Avoid a deadlock between GC and debugger where GC gets suspended during GC. b/25800335.
2363 gc::ScopedGCCriticalSection gcs(Thread::Current(),
2364 gc::kGcCauseDebugger,
2365 gc::kCollectorTypeDebugger);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002366 Runtime::Current()->GetThreadList()->SuspendAllForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002367}
2368
2369void Dbg::ResumeVM() {
Sebastien Hertz253fa552014-10-14 17:27:15 +02002370 Runtime::Current()->GetThreadList()->ResumeAllForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002371}
2372
Elliott Hughes221229c2013-01-08 18:17:50 -08002373JDWP::JdwpError Dbg::SuspendThread(JDWP::ObjectId thread_id, bool request_suspension) {
Ian Rogersf3d874c2014-07-17 18:52:42 -07002374 Thread* self = Thread::Current();
Ian Rogersc0542af2014-09-03 16:16:56 -07002375 ScopedLocalRef<jobject> peer(self->GetJniEnv(), nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002376 {
Ian Rogersf3d874c2014-07-17 18:52:42 -07002377 ScopedObjectAccess soa(self);
Ian Rogersc0542af2014-09-03 16:16:56 -07002378 JDWP::JdwpError error;
2379 peer.reset(soa.AddLocalReference<jobject>(gRegistry->Get<mirror::Object*>(thread_id, &error)));
Elliott Hughes4e235312011-12-02 11:34:15 -08002380 }
Ian Rogersc0542af2014-09-03 16:16:56 -07002381 if (peer.get() == nullptr) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002382 return JDWP::ERR_THREAD_NOT_ALIVE;
2383 }
Ian Rogers4ad5cd32014-11-11 23:08:07 -08002384 // Suspend thread to build stack trace.
Elliott Hughesf327e072013-01-09 16:01:26 -08002385 bool timed_out;
Brian Carlstromba32de42014-08-27 23:43:46 -07002386 ThreadList* thread_list = Runtime::Current()->GetThreadList();
2387 Thread* thread = thread_list->SuspendThreadByPeer(peer.get(), request_suspension, true,
2388 &timed_out);
Ian Rogersc0542af2014-09-03 16:16:56 -07002389 if (thread != nullptr) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002390 return JDWP::ERR_NONE;
Elliott Hughesf327e072013-01-09 16:01:26 -08002391 } else if (timed_out) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002392 return JDWP::ERR_INTERNAL;
2393 } else {
2394 return JDWP::ERR_THREAD_NOT_ALIVE;
2395 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002396}
2397
Elliott Hughes221229c2013-01-08 18:17:50 -08002398void Dbg::ResumeThread(JDWP::ObjectId thread_id) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002399 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002400 JDWP::JdwpError error;
2401 mirror::Object* peer = gRegistry->Get<mirror::Object*>(thread_id, &error);
2402 CHECK(peer != nullptr) << error;
jeffhaoa77f0f62012-12-05 17:19:31 -08002403 Thread* thread;
2404 {
2405 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
2406 thread = Thread::FromManagedThread(soa, peer);
2407 }
Ian Rogersc0542af2014-09-03 16:16:56 -07002408 if (thread == nullptr) {
Elliott Hughes4e235312011-12-02 11:34:15 -08002409 LOG(WARNING) << "No such thread for resume: " << peer;
2410 return;
2411 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002412 bool needs_resume;
2413 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002414 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002415 needs_resume = thread->GetSuspendCount() > 0;
2416 }
2417 if (needs_resume) {
Elliott Hughes546b9862012-06-20 16:06:13 -07002418 Runtime::Current()->GetThreadList()->Resume(thread, true);
2419 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002420}
2421
2422void Dbg::SuspendSelf() {
Elliott Hughes475fc232011-10-25 15:00:35 -07002423 Runtime::Current()->GetThreadList()->SuspendSelfForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002424}
2425
Ian Rogers0399dde2012-06-06 17:09:28 -07002426struct GetThisVisitor : public StackVisitor {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002427 GetThisVisitor(Thread* thread, Context* context, JDWP::FrameId frame_id_in)
Mathieu Chartier90443472015-07-16 20:32:27 -07002428 SHARED_REQUIRES(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01002429 : StackVisitor(thread, context, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
2430 this_object(nullptr),
2431 frame_id(frame_id_in) {}
Ian Rogers0399dde2012-06-06 17:09:28 -07002432
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002433 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2434 // annotalysis.
2435 virtual bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002436 if (frame_id != GetFrameId()) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002437 return true; // continue
Ian Rogers0399dde2012-06-06 17:09:28 -07002438 } else {
Ian Rogers62d6c772013-02-27 08:32:07 -08002439 this_object = GetThisObject();
2440 return false;
Ian Rogers0399dde2012-06-06 17:09:28 -07002441 }
Elliott Hughes86b00102011-12-05 17:54:26 -08002442 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002443
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002444 mirror::Object* this_object;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002445 JDWP::FrameId frame_id;
Ian Rogers0399dde2012-06-06 17:09:28 -07002446};
2447
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002448JDWP::JdwpError Dbg::GetThisObject(JDWP::ObjectId thread_id, JDWP::FrameId frame_id,
2449 JDWP::ObjectId* result) {
2450 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz69206392015-04-07 15:54:25 +02002451 JDWP::JdwpError error;
2452 Thread* thread = DecodeThread(soa, thread_id, &error);
2453 if (error != JDWP::ERR_NONE) {
2454 return error;
2455 }
2456 if (!IsSuspendedForDebugger(soa, thread)) {
2457 return JDWP::ERR_THREAD_NOT_SUSPENDED;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002458 }
Ian Rogers700a4022014-05-19 16:49:03 -07002459 std::unique_ptr<Context> context(Context::Create());
Ian Rogers7a22fa62013-01-23 12:16:16 -08002460 GetThisVisitor visitor(thread, context.get(), frame_id);
Ian Rogers0399dde2012-06-06 17:09:28 -07002461 visitor.WalkStack();
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002462 *result = gRegistry->Add(visitor.this_object);
2463 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002464}
2465
Sebastien Hertz8009f392014-09-01 17:07:11 +02002466// Walks the stack until we find the frame with the given FrameId.
2467class FindFrameVisitor FINAL : public StackVisitor {
2468 public:
2469 FindFrameVisitor(Thread* thread, Context* context, JDWP::FrameId frame_id)
Mathieu Chartier90443472015-07-16 20:32:27 -07002470 SHARED_REQUIRES(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01002471 : StackVisitor(thread, context, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
2472 frame_id_(frame_id),
2473 error_(JDWP::ERR_INVALID_FRAMEID) {}
Ian Rogersca190662012-06-26 15:45:57 -07002474
Sebastien Hertz8009f392014-09-01 17:07:11 +02002475 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2476 // annotalysis.
2477 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
2478 if (GetFrameId() != frame_id_) {
2479 return true; // Not our frame, carry on.
Ian Rogers0399dde2012-06-06 17:09:28 -07002480 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07002481 ArtMethod* m = GetMethod();
Sebastien Hertz8009f392014-09-01 17:07:11 +02002482 if (m->IsNative()) {
2483 // We can't read/write local value from/into native method.
2484 error_ = JDWP::ERR_OPAQUE_FRAME;
2485 } else {
2486 // We found our frame.
2487 error_ = JDWP::ERR_NONE;
2488 }
2489 return false;
2490 }
2491
2492 JDWP::JdwpError GetError() const {
2493 return error_;
2494 }
2495
2496 private:
2497 const JDWP::FrameId frame_id_;
2498 JDWP::JdwpError error_;
Sebastien Hertz26f72862015-09-15 09:52:07 +02002499
2500 DISALLOW_COPY_AND_ASSIGN(FindFrameVisitor);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002501};
2502
2503JDWP::JdwpError Dbg::GetLocalValues(JDWP::Request* request, JDWP::ExpandBuf* pReply) {
2504 JDWP::ObjectId thread_id = request->ReadThreadId();
2505 JDWP::FrameId frame_id = request->ReadFrameId();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002506
2507 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz69206392015-04-07 15:54:25 +02002508 JDWP::JdwpError error;
2509 Thread* thread = DecodeThread(soa, thread_id, &error);
2510 if (error != JDWP::ERR_NONE) {
2511 return error;
2512 }
2513 if (!IsSuspendedForDebugger(soa, thread)) {
2514 return JDWP::ERR_THREAD_NOT_SUSPENDED;
Elliott Hughes221229c2013-01-08 18:17:50 -08002515 }
Sebastien Hertz8009f392014-09-01 17:07:11 +02002516 // Find the frame with the given frame_id.
Ian Rogers700a4022014-05-19 16:49:03 -07002517 std::unique_ptr<Context> context(Context::Create());
Sebastien Hertz8009f392014-09-01 17:07:11 +02002518 FindFrameVisitor visitor(thread, context.get(), frame_id);
Ian Rogers0399dde2012-06-06 17:09:28 -07002519 visitor.WalkStack();
Sebastien Hertz8009f392014-09-01 17:07:11 +02002520 if (visitor.GetError() != JDWP::ERR_NONE) {
2521 return visitor.GetError();
2522 }
2523
2524 // Read the values from visitor's context.
2525 int32_t slot_count = request->ReadSigned32("slot count");
2526 expandBufAdd4BE(pReply, slot_count); /* "int values" */
2527 for (int32_t i = 0; i < slot_count; ++i) {
2528 uint32_t slot = request->ReadUnsigned32("slot");
2529 JDWP::JdwpTag reqSigByte = request->ReadTag();
2530
2531 VLOG(jdwp) << " --> slot " << slot << " " << reqSigByte;
2532
2533 size_t width = Dbg::GetTagWidth(reqSigByte);
Sebastien Hertz7d955652014-10-22 10:57:10 +02002534 uint8_t* ptr = expandBufAddSpace(pReply, width + 1);
Sebastien Hertz69206392015-04-07 15:54:25 +02002535 error = Dbg::GetLocalValue(visitor, soa, slot, reqSigByte, ptr, width);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002536 if (error != JDWP::ERR_NONE) {
2537 return error;
2538 }
2539 }
2540 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002541}
2542
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002543constexpr JDWP::JdwpError kStackFrameLocalAccessError = JDWP::ERR_ABSENT_INFORMATION;
2544
2545static std::string GetStackContextAsString(const StackVisitor& visitor)
Mathieu Chartier90443472015-07-16 20:32:27 -07002546 SHARED_REQUIRES(Locks::mutator_lock_) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002547 return StringPrintf(" at DEX pc 0x%08x in method %s", visitor.GetDexPc(false),
2548 PrettyMethod(visitor.GetMethod()).c_str());
2549}
2550
2551static JDWP::JdwpError FailGetLocalValue(const StackVisitor& visitor, uint16_t vreg,
2552 JDWP::JdwpTag tag)
Mathieu Chartier90443472015-07-16 20:32:27 -07002553 SHARED_REQUIRES(Locks::mutator_lock_) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002554 LOG(ERROR) << "Failed to read " << tag << " local from register v" << vreg
2555 << GetStackContextAsString(visitor);
2556 return kStackFrameLocalAccessError;
2557}
2558
Sebastien Hertz8009f392014-09-01 17:07:11 +02002559JDWP::JdwpError Dbg::GetLocalValue(const StackVisitor& visitor, ScopedObjectAccessUnchecked& soa,
2560 int slot, JDWP::JdwpTag tag, uint8_t* buf, size_t width) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002561 ArtMethod* m = visitor.GetMethod();
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002562 JDWP::JdwpError error = JDWP::ERR_NONE;
2563 uint16_t vreg = DemangleSlot(slot, m, &error);
2564 if (error != JDWP::ERR_NONE) {
2565 return error;
2566 }
Sebastien Hertz8009f392014-09-01 17:07:11 +02002567 // TODO: check that the tag is compatible with the actual type of the slot!
Sebastien Hertz8009f392014-09-01 17:07:11 +02002568 switch (tag) {
2569 case JDWP::JT_BOOLEAN: {
2570 CHECK_EQ(width, 1U);
2571 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002572 if (!visitor.GetVReg(m, vreg, kIntVReg, &intVal)) {
2573 return FailGetLocalValue(visitor, vreg, tag);
Ian Rogers0399dde2012-06-06 17:09:28 -07002574 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002575 VLOG(jdwp) << "get boolean local " << vreg << " = " << intVal;
2576 JDWP::Set1(buf + 1, intVal != 0);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002577 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002578 }
Sebastien Hertz8009f392014-09-01 17:07:11 +02002579 case JDWP::JT_BYTE: {
2580 CHECK_EQ(width, 1U);
2581 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002582 if (!visitor.GetVReg(m, vreg, kIntVReg, &intVal)) {
2583 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002584 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002585 VLOG(jdwp) << "get byte local " << vreg << " = " << intVal;
2586 JDWP::Set1(buf + 1, intVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002587 break;
2588 }
2589 case JDWP::JT_SHORT:
2590 case JDWP::JT_CHAR: {
2591 CHECK_EQ(width, 2U);
2592 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002593 if (!visitor.GetVReg(m, vreg, kIntVReg, &intVal)) {
2594 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002595 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002596 VLOG(jdwp) << "get short/char local " << vreg << " = " << intVal;
2597 JDWP::Set2BE(buf + 1, intVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002598 break;
2599 }
2600 case JDWP::JT_INT: {
2601 CHECK_EQ(width, 4U);
2602 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002603 if (!visitor.GetVReg(m, vreg, kIntVReg, &intVal)) {
2604 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002605 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002606 VLOG(jdwp) << "get int local " << vreg << " = " << intVal;
2607 JDWP::Set4BE(buf + 1, intVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002608 break;
2609 }
2610 case JDWP::JT_FLOAT: {
2611 CHECK_EQ(width, 4U);
2612 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002613 if (!visitor.GetVReg(m, vreg, kFloatVReg, &intVal)) {
2614 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002615 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002616 VLOG(jdwp) << "get float local " << vreg << " = " << intVal;
2617 JDWP::Set4BE(buf + 1, intVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002618 break;
2619 }
2620 case JDWP::JT_ARRAY:
2621 case JDWP::JT_CLASS_LOADER:
2622 case JDWP::JT_CLASS_OBJECT:
2623 case JDWP::JT_OBJECT:
2624 case JDWP::JT_STRING:
2625 case JDWP::JT_THREAD:
2626 case JDWP::JT_THREAD_GROUP: {
2627 CHECK_EQ(width, sizeof(JDWP::ObjectId));
2628 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002629 if (!visitor.GetVReg(m, vreg, kReferenceVReg, &intVal)) {
2630 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002631 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002632 mirror::Object* o = reinterpret_cast<mirror::Object*>(intVal);
2633 VLOG(jdwp) << "get " << tag << " object local " << vreg << " = " << o;
2634 if (!Runtime::Current()->GetHeap()->IsValidObjectAddress(o)) {
2635 LOG(FATAL) << StringPrintf("Found invalid object %#" PRIxPTR " in register v%u",
2636 reinterpret_cast<uintptr_t>(o), vreg)
2637 << GetStackContextAsString(visitor);
2638 UNREACHABLE();
2639 }
2640 tag = TagFromObject(soa, o);
2641 JDWP::SetObjectId(buf + 1, gRegistry->Add(o));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002642 break;
2643 }
2644 case JDWP::JT_DOUBLE: {
2645 CHECK_EQ(width, 8U);
2646 uint64_t longVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002647 if (!visitor.GetVRegPair(m, vreg, kDoubleLoVReg, kDoubleHiVReg, &longVal)) {
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 double local " << vreg << " = " << longVal;
2651 JDWP::Set8BE(buf + 1, longVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002652 break;
2653 }
2654 case JDWP::JT_LONG: {
2655 CHECK_EQ(width, 8U);
2656 uint64_t longVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002657 if (!visitor.GetVRegPair(m, vreg, kLongLoVReg, kLongHiVReg, &longVal)) {
2658 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002659 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002660 VLOG(jdwp) << "get long local " << vreg << " = " << longVal;
2661 JDWP::Set8BE(buf + 1, longVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002662 break;
2663 }
2664 default:
2665 LOG(FATAL) << "Unknown tag " << tag;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002666 UNREACHABLE();
Sebastien Hertz8009f392014-09-01 17:07:11 +02002667 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002668
Sebastien Hertz8009f392014-09-01 17:07:11 +02002669 // Prepend tag, which may have been updated.
2670 JDWP::Set1(buf, tag);
2671 return JDWP::ERR_NONE;
2672}
2673
2674JDWP::JdwpError Dbg::SetLocalValues(JDWP::Request* request) {
2675 JDWP::ObjectId thread_id = request->ReadThreadId();
2676 JDWP::FrameId frame_id = request->ReadFrameId();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002677
2678 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz69206392015-04-07 15:54:25 +02002679 JDWP::JdwpError error;
2680 Thread* thread = DecodeThread(soa, thread_id, &error);
2681 if (error != JDWP::ERR_NONE) {
2682 return error;
2683 }
2684 if (!IsSuspendedForDebugger(soa, thread)) {
2685 return JDWP::ERR_THREAD_NOT_SUSPENDED;
Elliott Hughes221229c2013-01-08 18:17:50 -08002686 }
Sebastien Hertz8009f392014-09-01 17:07:11 +02002687 // Find the frame with the given frame_id.
Ian Rogers700a4022014-05-19 16:49:03 -07002688 std::unique_ptr<Context> context(Context::Create());
Sebastien Hertz8009f392014-09-01 17:07:11 +02002689 FindFrameVisitor visitor(thread, context.get(), frame_id);
Ian Rogers0399dde2012-06-06 17:09:28 -07002690 visitor.WalkStack();
Sebastien Hertz8009f392014-09-01 17:07:11 +02002691 if (visitor.GetError() != JDWP::ERR_NONE) {
2692 return visitor.GetError();
2693 }
2694
2695 // Writes the values into visitor's context.
2696 int32_t slot_count = request->ReadSigned32("slot count");
2697 for (int32_t i = 0; i < slot_count; ++i) {
2698 uint32_t slot = request->ReadUnsigned32("slot");
2699 JDWP::JdwpTag sigByte = request->ReadTag();
2700 size_t width = Dbg::GetTagWidth(sigByte);
2701 uint64_t value = request->ReadValue(width);
2702
2703 VLOG(jdwp) << " --> slot " << slot << " " << sigByte << " " << value;
Mingyao Yang99170c62015-07-06 11:10:37 -07002704 error = Dbg::SetLocalValue(thread, visitor, slot, sigByte, value, width);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002705 if (error != JDWP::ERR_NONE) {
2706 return error;
2707 }
2708 }
2709 return JDWP::ERR_NONE;
2710}
2711
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002712template<typename T>
2713static JDWP::JdwpError FailSetLocalValue(const StackVisitor& visitor, uint16_t vreg,
2714 JDWP::JdwpTag tag, T value)
Mathieu Chartier90443472015-07-16 20:32:27 -07002715 SHARED_REQUIRES(Locks::mutator_lock_) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002716 LOG(ERROR) << "Failed to write " << tag << " local " << value
2717 << " (0x" << std::hex << value << ") into register v" << vreg
2718 << GetStackContextAsString(visitor);
2719 return kStackFrameLocalAccessError;
2720}
2721
Mingyao Yang99170c62015-07-06 11:10:37 -07002722JDWP::JdwpError Dbg::SetLocalValue(Thread* thread, StackVisitor& visitor, int slot,
2723 JDWP::JdwpTag tag, uint64_t value, size_t width) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002724 ArtMethod* m = visitor.GetMethod();
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002725 JDWP::JdwpError error = JDWP::ERR_NONE;
2726 uint16_t vreg = DemangleSlot(slot, m, &error);
2727 if (error != JDWP::ERR_NONE) {
2728 return error;
2729 }
Sebastien Hertz8009f392014-09-01 17:07:11 +02002730 // TODO: check that the tag is compatible with the actual type of the slot!
Sebastien Hertz8009f392014-09-01 17:07:11 +02002731 switch (tag) {
2732 case JDWP::JT_BOOLEAN:
2733 case JDWP::JT_BYTE:
2734 CHECK_EQ(width, 1U);
Mingyao Yang636b9252015-07-31 16:40:24 -07002735 if (!visitor.SetVReg(m, vreg, static_cast<uint32_t>(value), kIntVReg)) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002736 return FailSetLocalValue(visitor, vreg, tag, static_cast<uint32_t>(value));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002737 }
2738 break;
2739 case JDWP::JT_SHORT:
2740 case JDWP::JT_CHAR:
2741 CHECK_EQ(width, 2U);
Mingyao Yang636b9252015-07-31 16:40:24 -07002742 if (!visitor.SetVReg(m, vreg, static_cast<uint32_t>(value), kIntVReg)) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002743 return FailSetLocalValue(visitor, vreg, tag, static_cast<uint32_t>(value));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002744 }
2745 break;
2746 case JDWP::JT_INT:
2747 CHECK_EQ(width, 4U);
Mingyao Yang636b9252015-07-31 16:40:24 -07002748 if (!visitor.SetVReg(m, vreg, static_cast<uint32_t>(value), kIntVReg)) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002749 return FailSetLocalValue(visitor, vreg, tag, static_cast<uint32_t>(value));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002750 }
2751 break;
2752 case JDWP::JT_FLOAT:
2753 CHECK_EQ(width, 4U);
Mingyao Yang636b9252015-07-31 16:40:24 -07002754 if (!visitor.SetVReg(m, vreg, static_cast<uint32_t>(value), kFloatVReg)) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002755 return FailSetLocalValue(visitor, vreg, tag, static_cast<uint32_t>(value));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002756 }
2757 break;
2758 case JDWP::JT_ARRAY:
2759 case JDWP::JT_CLASS_LOADER:
2760 case JDWP::JT_CLASS_OBJECT:
2761 case JDWP::JT_OBJECT:
2762 case JDWP::JT_STRING:
2763 case JDWP::JT_THREAD:
2764 case JDWP::JT_THREAD_GROUP: {
2765 CHECK_EQ(width, sizeof(JDWP::ObjectId));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002766 mirror::Object* o = gRegistry->Get<mirror::Object*>(static_cast<JDWP::ObjectId>(value),
2767 &error);
2768 if (error != JDWP::ERR_NONE) {
2769 VLOG(jdwp) << tag << " object " << o << " is an invalid object";
2770 return JDWP::ERR_INVALID_OBJECT;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002771 }
Mingyao Yang636b9252015-07-31 16:40:24 -07002772 if (!visitor.SetVReg(m, vreg, static_cast<uint32_t>(reinterpret_cast<uintptr_t>(o)),
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002773 kReferenceVReg)) {
2774 return FailSetLocalValue(visitor, vreg, tag, reinterpret_cast<uintptr_t>(o));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002775 }
2776 break;
2777 }
2778 case JDWP::JT_DOUBLE: {
2779 CHECK_EQ(width, 8U);
Mingyao Yang636b9252015-07-31 16:40:24 -07002780 if (!visitor.SetVRegPair(m, vreg, value, kDoubleLoVReg, kDoubleHiVReg)) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002781 return FailSetLocalValue(visitor, vreg, tag, value);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002782 }
2783 break;
2784 }
2785 case JDWP::JT_LONG: {
2786 CHECK_EQ(width, 8U);
Mingyao Yang636b9252015-07-31 16:40:24 -07002787 if (!visitor.SetVRegPair(m, vreg, value, kLongLoVReg, kLongHiVReg)) {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002788 return FailSetLocalValue(visitor, vreg, tag, value);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002789 }
2790 break;
2791 }
2792 default:
2793 LOG(FATAL) << "Unknown tag " << tag;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002794 UNREACHABLE();
Sebastien Hertz8009f392014-09-01 17:07:11 +02002795 }
Mingyao Yang99170c62015-07-06 11:10:37 -07002796
2797 // If we set the local variable in a compiled frame, we need to trigger a deoptimization of
2798 // the stack so we continue execution with the interpreter using the new value(s) of the updated
2799 // local variable(s). To achieve this, we install instrumentation exit stub on each method of the
2800 // thread's stack. The stub will cause the deoptimization to happen.
2801 if (!visitor.IsShadowFrame() && thread->HasDebuggerShadowFrames()) {
2802 Runtime::Current()->GetInstrumentation()->InstrumentThreadStack(thread);
2803 }
2804
Sebastien Hertz8009f392014-09-01 17:07:11 +02002805 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002806}
2807
Mathieu Chartiere401d142015-04-22 13:56:20 -07002808static void SetEventLocation(JDWP::EventLocation* location, ArtMethod* m, uint32_t dex_pc)
Mathieu Chartier90443472015-07-16 20:32:27 -07002809 SHARED_REQUIRES(Locks::mutator_lock_) {
Sebastien Hertz6995c602014-09-09 12:10:13 +02002810 DCHECK(location != nullptr);
2811 if (m == nullptr) {
2812 memset(location, 0, sizeof(*location));
2813 } else {
Alex Light6c8467f2015-11-20 15:03:26 -08002814 location->method = GetCanonicalMethod(m);
Sebastien Hertz6995c602014-09-09 12:10:13 +02002815 location->dex_pc = (m->IsNative() || m->IsProxyMethod()) ? static_cast<uint32_t>(-1) : dex_pc;
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002816 }
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002817}
2818
Mathieu Chartiere401d142015-04-22 13:56:20 -07002819void Dbg::PostLocationEvent(ArtMethod* m, int dex_pc, mirror::Object* this_object,
Jeff Hao579b0242013-11-18 13:16:49 -08002820 int event_flags, const JValue* return_value) {
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002821 if (!IsDebuggerActive()) {
2822 return;
2823 }
2824 DCHECK(m != nullptr);
2825 DCHECK_EQ(m->IsStatic(), this_object == nullptr);
Sebastien Hertz6995c602014-09-09 12:10:13 +02002826 JDWP::EventLocation location;
2827 SetEventLocation(&location, m, dex_pc);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002828
Sebastien Hertzde48aa62015-05-26 11:53:39 +02002829 // We need to be sure no exception is pending when calling JdwpState::PostLocationEvent.
2830 // This is required to be able to call JNI functions to create JDWP ids. To achieve this,
2831 // we temporarily clear the current thread's exception (if any) and will restore it after
2832 // the call.
2833 // Note: the only way to get a pending exception here is to suspend on a move-exception
2834 // instruction.
2835 Thread* const self = Thread::Current();
2836 StackHandleScope<1> hs(self);
2837 Handle<mirror::Throwable> pending_exception(hs.NewHandle(self->GetException()));
2838 self->ClearException();
2839 if (kIsDebugBuild && pending_exception.Get() != nullptr) {
2840 const DexFile::CodeItem* code_item = location.method->GetCodeItem();
2841 const Instruction* instr = Instruction::At(&code_item->insns_[location.dex_pc]);
2842 CHECK_EQ(Instruction::MOVE_EXCEPTION, instr->Opcode());
2843 }
2844
Sebastien Hertz6995c602014-09-09 12:10:13 +02002845 gJdwpState->PostLocationEvent(&location, this_object, event_flags, return_value);
Sebastien Hertzde48aa62015-05-26 11:53:39 +02002846
2847 if (pending_exception.Get() != nullptr) {
2848 self->SetException(pending_exception.Get());
2849 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002850}
2851
Mathieu Chartiere401d142015-04-22 13:56:20 -07002852void Dbg::PostFieldAccessEvent(ArtMethod* m, int dex_pc,
Mathieu Chartierc7853442015-03-27 14:35:38 -07002853 mirror::Object* this_object, ArtField* f) {
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002854 if (!IsDebuggerActive()) {
2855 return;
2856 }
2857 DCHECK(m != nullptr);
2858 DCHECK(f != nullptr);
Sebastien Hertz6995c602014-09-09 12:10:13 +02002859 JDWP::EventLocation location;
2860 SetEventLocation(&location, m, dex_pc);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002861
Sebastien Hertz6995c602014-09-09 12:10:13 +02002862 gJdwpState->PostFieldEvent(&location, f, this_object, nullptr, false);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002863}
2864
Mathieu Chartiere401d142015-04-22 13:56:20 -07002865void Dbg::PostFieldModificationEvent(ArtMethod* m, int dex_pc,
Mathieu Chartierc7853442015-03-27 14:35:38 -07002866 mirror::Object* this_object, ArtField* f,
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002867 const JValue* field_value) {
2868 if (!IsDebuggerActive()) {
2869 return;
2870 }
2871 DCHECK(m != nullptr);
2872 DCHECK(f != nullptr);
2873 DCHECK(field_value != nullptr);
Sebastien Hertz6995c602014-09-09 12:10:13 +02002874 JDWP::EventLocation location;
2875 SetEventLocation(&location, m, dex_pc);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002876
Sebastien Hertz6995c602014-09-09 12:10:13 +02002877 gJdwpState->PostFieldEvent(&location, f, this_object, field_value, true);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002878}
2879
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002880/**
2881 * Finds the location where this exception will be caught. We search until we reach the top
2882 * frame, in which case this exception is considered uncaught.
2883 */
2884class CatchLocationFinder : public StackVisitor {
2885 public:
2886 CatchLocationFinder(Thread* self, const Handle<mirror::Throwable>& exception, Context* context)
Mathieu Chartier90443472015-07-16 20:32:27 -07002887 SHARED_REQUIRES(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01002888 : StackVisitor(self, context, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002889 exception_(exception),
2890 handle_scope_(self),
2891 this_at_throw_(handle_scope_.NewHandle<mirror::Object>(nullptr)),
Mathieu Chartiere401d142015-04-22 13:56:20 -07002892 catch_method_(nullptr),
2893 throw_method_(nullptr),
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002894 catch_dex_pc_(DexFile::kDexNoIndex),
2895 throw_dex_pc_(DexFile::kDexNoIndex) {
2896 }
2897
Mathieu Chartier90443472015-07-16 20:32:27 -07002898 bool VisitFrame() OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002899 ArtMethod* method = GetMethod();
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002900 DCHECK(method != nullptr);
2901 if (method->IsRuntimeMethod()) {
2902 // Ignore callee save method.
2903 DCHECK(method->IsCalleeSaveMethod());
2904 return true;
2905 }
2906
2907 uint32_t dex_pc = GetDexPc();
Mathieu Chartiere401d142015-04-22 13:56:20 -07002908 if (throw_method_ == nullptr) {
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002909 // First Java method found. It is either the method that threw the exception,
2910 // or the Java native method that is reporting an exception thrown by
2911 // native code.
2912 this_at_throw_.Assign(GetThisObject());
Mathieu Chartiere401d142015-04-22 13:56:20 -07002913 throw_method_ = method;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002914 throw_dex_pc_ = dex_pc;
2915 }
2916
2917 if (dex_pc != DexFile::kDexNoIndex) {
Sebastien Hertz26f72862015-09-15 09:52:07 +02002918 StackHandleScope<1> hs(GetThread());
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002919 uint32_t found_dex_pc;
2920 Handle<mirror::Class> exception_class(hs.NewHandle(exception_->GetClass()));
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002921 bool unused_clear_exception;
Mathieu Chartiere401d142015-04-22 13:56:20 -07002922 found_dex_pc = method->FindCatchBlock(exception_class, dex_pc, &unused_clear_exception);
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002923 if (found_dex_pc != DexFile::kDexNoIndex) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002924 catch_method_ = method;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002925 catch_dex_pc_ = found_dex_pc;
2926 return false; // End stack walk.
2927 }
2928 }
2929 return true; // Continue stack walk.
2930 }
2931
Mathieu Chartier90443472015-07-16 20:32:27 -07002932 ArtMethod* GetCatchMethod() SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002933 return catch_method_;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002934 }
2935
Mathieu Chartier90443472015-07-16 20:32:27 -07002936 ArtMethod* GetThrowMethod() SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002937 return throw_method_;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002938 }
2939
Mathieu Chartier90443472015-07-16 20:32:27 -07002940 mirror::Object* GetThisAtThrow() SHARED_REQUIRES(Locks::mutator_lock_) {
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002941 return this_at_throw_.Get();
2942 }
2943
2944 uint32_t GetCatchDexPc() const {
2945 return catch_dex_pc_;
2946 }
2947
2948 uint32_t GetThrowDexPc() const {
2949 return throw_dex_pc_;
2950 }
2951
2952 private:
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002953 const Handle<mirror::Throwable>& exception_;
Mathieu Chartiere401d142015-04-22 13:56:20 -07002954 StackHandleScope<1> handle_scope_;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002955 MutableHandle<mirror::Object> this_at_throw_;
Mathieu Chartiere401d142015-04-22 13:56:20 -07002956 ArtMethod* catch_method_;
2957 ArtMethod* throw_method_;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002958 uint32_t catch_dex_pc_;
2959 uint32_t throw_dex_pc_;
2960
2961 DISALLOW_COPY_AND_ASSIGN(CatchLocationFinder);
2962};
2963
2964void Dbg::PostException(mirror::Throwable* exception_object) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002965 if (!IsDebuggerActive()) {
Ian Rogers0ad5bb82011-12-07 10:16:32 -08002966 return;
2967 }
Sebastien Hertz261bc042015-04-08 09:36:07 +02002968 Thread* const self = Thread::Current();
2969 StackHandleScope<1> handle_scope(self);
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002970 Handle<mirror::Throwable> h_exception(handle_scope.NewHandle(exception_object));
2971 std::unique_ptr<Context> context(Context::Create());
Sebastien Hertz261bc042015-04-08 09:36:07 +02002972 CatchLocationFinder clf(self, h_exception, context.get());
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002973 clf.WalkStack(/* include_transitions */ false);
Sebastien Hertz6995c602014-09-09 12:10:13 +02002974 JDWP::EventLocation exception_throw_location;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002975 SetEventLocation(&exception_throw_location, clf.GetThrowMethod(), clf.GetThrowDexPc());
Sebastien Hertz6995c602014-09-09 12:10:13 +02002976 JDWP::EventLocation exception_catch_location;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002977 SetEventLocation(&exception_catch_location, clf.GetCatchMethod(), clf.GetCatchDexPc());
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002978
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002979 gJdwpState->PostException(&exception_throw_location, h_exception.Get(), &exception_catch_location,
2980 clf.GetThisAtThrow());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002981}
2982
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002983void Dbg::PostClassPrepare(mirror::Class* c) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002984 if (!IsDebuggerActive()) {
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002985 return;
2986 }
Sebastien Hertz6995c602014-09-09 12:10:13 +02002987 gJdwpState->PostClassPrepare(c);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002988}
2989
Ian Rogers62d6c772013-02-27 08:32:07 -08002990void Dbg::UpdateDebugger(Thread* thread, mirror::Object* this_object,
Mathieu Chartiere401d142015-04-22 13:56:20 -07002991 ArtMethod* m, uint32_t dex_pc,
Sebastien Hertz8379b222014-02-24 17:38:15 +01002992 int event_flags, const JValue* return_value) {
Ian Rogers62d6c772013-02-27 08:32:07 -08002993 if (!IsDebuggerActive() || dex_pc == static_cast<uint32_t>(-2) /* fake method exit */) {
Elliott Hughes2aa2e392012-02-17 17:15:43 -08002994 return;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002995 }
2996
Elliott Hughes86964332012-02-15 19:37:42 -08002997 if (IsBreakpoint(m, dex_pc)) {
2998 event_flags |= kBreakpoint;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002999 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003000
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003001 // If the debugger is single-stepping one of our threads, check to
3002 // see if we're that thread and we've reached a step point.
3003 const SingleStepControl* single_step_control = thread->GetSingleStepControl();
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003004 if (single_step_control != nullptr) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003005 CHECK(!m->IsNative());
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003006 if (single_step_control->GetStepDepth() == JDWP::SD_INTO) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003007 // Step into method calls. We break when the line number
3008 // or method pointer changes. If we're in SS_MIN mode, we
3009 // always stop.
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003010 if (single_step_control->GetMethod() != m) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003011 event_flags |= kSingleStep;
3012 VLOG(jdwp) << "SS new method";
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003013 } else if (single_step_control->GetStepSize() == JDWP::SS_MIN) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003014 event_flags |= kSingleStep;
3015 VLOG(jdwp) << "SS new instruction";
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003016 } else if (single_step_control->ContainsDexPc(dex_pc)) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003017 event_flags |= kSingleStep;
3018 VLOG(jdwp) << "SS new line";
3019 }
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003020 } else if (single_step_control->GetStepDepth() == JDWP::SD_OVER) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003021 // Step over method calls. We break when the line number is
3022 // different and the frame depth is <= the original frame
3023 // depth. (We can't just compare on the method, because we
3024 // might get unrolled past it by an exception, and it's tricky
3025 // to identify recursion.)
3026
3027 int stack_depth = GetStackDepth(thread);
3028
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003029 if (stack_depth < single_step_control->GetStackDepth()) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003030 // Popped up one or more frames, always trigger.
3031 event_flags |= kSingleStep;
3032 VLOG(jdwp) << "SS method pop";
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003033 } else if (stack_depth == single_step_control->GetStackDepth()) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003034 // Same depth, see if we moved.
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003035 if (single_step_control->GetStepSize() == JDWP::SS_MIN) {
Elliott Hughes86964332012-02-15 19:37:42 -08003036 event_flags |= kSingleStep;
3037 VLOG(jdwp) << "SS new instruction";
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003038 } else if (single_step_control->ContainsDexPc(dex_pc)) {
Elliott Hughes2435a572012-02-17 16:07:41 -08003039 event_flags |= kSingleStep;
3040 VLOG(jdwp) << "SS new line";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003041 }
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003042 }
3043 } else {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003044 CHECK_EQ(single_step_control->GetStepDepth(), JDWP::SD_OUT);
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003045 // Return from the current method. We break when the frame
3046 // depth pops up.
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003047
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003048 // This differs from the "method exit" break in that it stops
3049 // with the PC at the next instruction in the returned-to
3050 // function, rather than the end of the returning function.
Elliott Hughes86964332012-02-15 19:37:42 -08003051
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003052 int stack_depth = GetStackDepth(thread);
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003053 if (stack_depth < single_step_control->GetStackDepth()) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003054 event_flags |= kSingleStep;
3055 VLOG(jdwp) << "SS method pop";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003056 }
3057 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003058 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003059
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003060 // If there's something interesting going on, see if it matches one
3061 // of the debugger filters.
3062 if (event_flags != 0) {
Sebastien Hertz8379b222014-02-24 17:38:15 +01003063 Dbg::PostLocationEvent(m, dex_pc, this_object, event_flags, return_value);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08003064 }
3065}
3066
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003067size_t* Dbg::GetReferenceCounterForEvent(uint32_t instrumentation_event) {
3068 switch (instrumentation_event) {
3069 case instrumentation::Instrumentation::kMethodEntered:
3070 return &method_enter_event_ref_count_;
3071 case instrumentation::Instrumentation::kMethodExited:
3072 return &method_exit_event_ref_count_;
3073 case instrumentation::Instrumentation::kDexPcMoved:
3074 return &dex_pc_change_event_ref_count_;
3075 case instrumentation::Instrumentation::kFieldRead:
3076 return &field_read_event_ref_count_;
3077 case instrumentation::Instrumentation::kFieldWritten:
3078 return &field_write_event_ref_count_;
3079 case instrumentation::Instrumentation::kExceptionCaught:
3080 return &exception_catch_event_ref_count_;
3081 default:
3082 return nullptr;
3083 }
3084}
3085
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003086// Process request while all mutator threads are suspended.
3087void Dbg::ProcessDeoptimizationRequest(const DeoptimizationRequest& request) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003088 instrumentation::Instrumentation* instrumentation = Runtime::Current()->GetInstrumentation();
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003089 switch (request.GetKind()) {
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003090 case DeoptimizationRequest::kNothing:
3091 LOG(WARNING) << "Ignoring empty deoptimization request.";
3092 break;
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003093 case DeoptimizationRequest::kRegisterForEvent:
3094 VLOG(jdwp) << StringPrintf("Add debugger as listener for instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003095 request.InstrumentationEvent());
3096 instrumentation->AddListener(&gDebugInstrumentationListener, request.InstrumentationEvent());
3097 instrumentation_events_ |= request.InstrumentationEvent();
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003098 break;
3099 case DeoptimizationRequest::kUnregisterForEvent:
3100 VLOG(jdwp) << StringPrintf("Remove debugger as listener for instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003101 request.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003102 instrumentation->RemoveListener(&gDebugInstrumentationListener,
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003103 request.InstrumentationEvent());
3104 instrumentation_events_ &= ~request.InstrumentationEvent();
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003105 break;
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003106 case DeoptimizationRequest::kFullDeoptimization:
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003107 VLOG(jdwp) << "Deoptimize the world ...";
Sebastien Hertz0462c4c2015-04-01 16:34:17 +02003108 instrumentation->DeoptimizeEverything(kDbgInstrumentationKey);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003109 VLOG(jdwp) << "Deoptimize the world DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003110 break;
3111 case DeoptimizationRequest::kFullUndeoptimization:
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003112 VLOG(jdwp) << "Undeoptimize the world ...";
Sebastien Hertz0462c4c2015-04-01 16:34:17 +02003113 instrumentation->UndeoptimizeEverything(kDbgInstrumentationKey);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003114 VLOG(jdwp) << "Undeoptimize the world DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003115 break;
3116 case DeoptimizationRequest::kSelectiveDeoptimization:
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003117 VLOG(jdwp) << "Deoptimize method " << PrettyMethod(request.Method()) << " ...";
3118 instrumentation->Deoptimize(request.Method());
3119 VLOG(jdwp) << "Deoptimize method " << PrettyMethod(request.Method()) << " DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003120 break;
3121 case DeoptimizationRequest::kSelectiveUndeoptimization:
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003122 VLOG(jdwp) << "Undeoptimize method " << PrettyMethod(request.Method()) << " ...";
3123 instrumentation->Undeoptimize(request.Method());
3124 VLOG(jdwp) << "Undeoptimize method " << PrettyMethod(request.Method()) << " DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003125 break;
3126 default:
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003127 LOG(FATAL) << "Unsupported deoptimization request kind " << request.GetKind();
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003128 break;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003129 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003130}
3131
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003132void Dbg::RequestDeoptimization(const DeoptimizationRequest& req) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003133 if (req.GetKind() == DeoptimizationRequest::kNothing) {
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003134 // Nothing to do.
3135 return;
3136 }
Brian Carlstrom306db812014-09-05 13:01:41 -07003137 MutexLock mu(Thread::Current(), *Locks::deoptimization_lock_);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003138 RequestDeoptimizationLocked(req);
3139}
3140
3141void Dbg::RequestDeoptimizationLocked(const DeoptimizationRequest& req) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003142 switch (req.GetKind()) {
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003143 case DeoptimizationRequest::kRegisterForEvent: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003144 DCHECK_NE(req.InstrumentationEvent(), 0u);
3145 size_t* counter = GetReferenceCounterForEvent(req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003146 CHECK(counter != nullptr) << StringPrintf("No counter for instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003147 req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003148 if (*counter == 0) {
Sebastien Hertz7d2ae432014-05-15 11:26:34 +02003149 VLOG(jdwp) << StringPrintf("Queue request #%zd to start listening to instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003150 deoptimization_requests_.size(), req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003151 deoptimization_requests_.push_back(req);
3152 }
3153 *counter = *counter + 1;
3154 break;
3155 }
3156 case DeoptimizationRequest::kUnregisterForEvent: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003157 DCHECK_NE(req.InstrumentationEvent(), 0u);
3158 size_t* counter = GetReferenceCounterForEvent(req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003159 CHECK(counter != nullptr) << StringPrintf("No counter for instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003160 req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003161 *counter = *counter - 1;
3162 if (*counter == 0) {
Sebastien Hertz7d2ae432014-05-15 11:26:34 +02003163 VLOG(jdwp) << StringPrintf("Queue request #%zd to stop listening to instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003164 deoptimization_requests_.size(), req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003165 deoptimization_requests_.push_back(req);
3166 }
3167 break;
3168 }
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003169 case DeoptimizationRequest::kFullDeoptimization: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003170 DCHECK(req.Method() == nullptr);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003171 if (full_deoptimization_event_count_ == 0) {
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003172 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
3173 << " for full deoptimization";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003174 deoptimization_requests_.push_back(req);
3175 }
3176 ++full_deoptimization_event_count_;
3177 break;
3178 }
3179 case DeoptimizationRequest::kFullUndeoptimization: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003180 DCHECK(req.Method() == nullptr);
Sebastien Hertze713d932014-05-15 10:48:53 +02003181 DCHECK_GT(full_deoptimization_event_count_, 0U);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003182 --full_deoptimization_event_count_;
3183 if (full_deoptimization_event_count_ == 0) {
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003184 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
3185 << " for full undeoptimization";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003186 deoptimization_requests_.push_back(req);
3187 }
3188 break;
3189 }
3190 case DeoptimizationRequest::kSelectiveDeoptimization: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003191 DCHECK(req.Method() != nullptr);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003192 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003193 << " for deoptimization of " << PrettyMethod(req.Method());
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003194 deoptimization_requests_.push_back(req);
3195 break;
3196 }
3197 case DeoptimizationRequest::kSelectiveUndeoptimization: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003198 DCHECK(req.Method() != nullptr);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003199 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003200 << " for undeoptimization of " << PrettyMethod(req.Method());
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003201 deoptimization_requests_.push_back(req);
3202 break;
3203 }
3204 default: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003205 LOG(FATAL) << "Unknown deoptimization request kind " << req.GetKind();
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003206 break;
3207 }
3208 }
3209}
3210
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003211void Dbg::ManageDeoptimization() {
3212 Thread* const self = Thread::Current();
3213 {
3214 // Avoid suspend/resume if there is no pending request.
Brian Carlstrom306db812014-09-05 13:01:41 -07003215 MutexLock mu(self, *Locks::deoptimization_lock_);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003216 if (deoptimization_requests_.empty()) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003217 return;
3218 }
3219 }
3220 CHECK_EQ(self->GetState(), kRunnable);
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07003221 ScopedThreadSuspension sts(self, kWaitingForDeoptimization);
Mathieu Chartieraa516822015-10-02 15:53:37 -07003222 // Required for ProcessDeoptimizationRequest.
3223 gc::ScopedGCCriticalSection gcs(self,
3224 gc::kGcCauseInstrumentation,
3225 gc::kCollectorTypeInstrumentation);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003226 // We need to suspend mutator threads first.
Mathieu Chartier4f55e222015-09-04 13:26:21 -07003227 ScopedSuspendAll ssa(__FUNCTION__);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003228 const ThreadState old_state = self->SetStateUnsafe(kRunnable);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003229 {
Brian Carlstrom306db812014-09-05 13:01:41 -07003230 MutexLock mu(self, *Locks::deoptimization_lock_);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003231 size_t req_index = 0;
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003232 for (DeoptimizationRequest& request : deoptimization_requests_) {
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003233 VLOG(jdwp) << "Process deoptimization request #" << req_index++;
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003234 ProcessDeoptimizationRequest(request);
3235 }
3236 deoptimization_requests_.clear();
3237 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003238 CHECK_EQ(self->SetStateUnsafe(old_state), kRunnable);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003239}
3240
Mathieu Chartiere401d142015-04-22 13:56:20 -07003241static const Breakpoint* FindFirstBreakpointForMethod(ArtMethod* m)
Mathieu Chartier90443472015-07-16 20:32:27 -07003242 SHARED_REQUIRES(Locks::mutator_lock_, Locks::breakpoint_lock_) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003243 for (Breakpoint& breakpoint : gBreakpoints) {
Alex Light6c8467f2015-11-20 15:03:26 -08003244 if (breakpoint.IsInMethod(m)) {
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003245 return &breakpoint;
3246 }
3247 }
3248 return nullptr;
3249}
3250
Mathieu Chartiere401d142015-04-22 13:56:20 -07003251bool Dbg::MethodHasAnyBreakpoints(ArtMethod* method) {
Mathieu Chartierd8565452015-03-26 09:41:50 -07003252 ReaderMutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
3253 return FindFirstBreakpointForMethod(method) != nullptr;
3254}
3255
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003256// Sanity checks all existing breakpoints on the same method.
Mathieu Chartiere401d142015-04-22 13:56:20 -07003257static void SanityCheckExistingBreakpoints(ArtMethod* m,
Sebastien Hertzf3928792014-11-17 19:00:37 +01003258 DeoptimizationRequest::Kind deoptimization_kind)
Mathieu Chartier90443472015-07-16 20:32:27 -07003259 SHARED_REQUIRES(Locks::mutator_lock_, Locks::breakpoint_lock_) {
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003260 for (const Breakpoint& breakpoint : gBreakpoints) {
Alex Light6c8467f2015-11-20 15:03:26 -08003261 if (breakpoint.IsInMethod(m)) {
Sebastien Hertzf3928792014-11-17 19:00:37 +01003262 CHECK_EQ(deoptimization_kind, breakpoint.GetDeoptimizationKind());
3263 }
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003264 }
Sebastien Hertzf3928792014-11-17 19:00:37 +01003265 instrumentation::Instrumentation* instrumentation = Runtime::Current()->GetInstrumentation();
3266 if (deoptimization_kind == DeoptimizationRequest::kFullDeoptimization) {
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003267 // We should have deoptimized everything but not "selectively" deoptimized this method.
Sebastien Hertzf3928792014-11-17 19:00:37 +01003268 CHECK(instrumentation->AreAllMethodsDeoptimized());
3269 CHECK(!instrumentation->IsDeoptimized(m));
3270 } else if (deoptimization_kind == DeoptimizationRequest::kSelectiveDeoptimization) {
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003271 // We should have "selectively" deoptimized this method.
3272 // Note: while we have not deoptimized everything for this method, we may have done it for
3273 // another event.
Sebastien Hertzf3928792014-11-17 19:00:37 +01003274 CHECK(instrumentation->IsDeoptimized(m));
3275 } else {
3276 // This method does not require deoptimization.
3277 CHECK_EQ(deoptimization_kind, DeoptimizationRequest::kNothing);
3278 CHECK(!instrumentation->IsDeoptimized(m));
3279 }
3280}
3281
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003282// Returns the deoptimization kind required to set a breakpoint in a method.
3283// If a breakpoint has already been set, we also return the first breakpoint
3284// through the given 'existing_brkpt' pointer.
Sebastien Hertzf3928792014-11-17 19:00:37 +01003285static DeoptimizationRequest::Kind GetRequiredDeoptimizationKind(Thread* self,
Mathieu Chartiere401d142015-04-22 13:56:20 -07003286 ArtMethod* m,
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003287 const Breakpoint** existing_brkpt)
Mathieu Chartier90443472015-07-16 20:32:27 -07003288 SHARED_REQUIRES(Locks::mutator_lock_) {
Sebastien Hertzf3928792014-11-17 19:00:37 +01003289 if (!Dbg::RequiresDeoptimization()) {
3290 // We already run in interpreter-only mode so we don't need to deoptimize anything.
3291 VLOG(jdwp) << "No need for deoptimization when fully running with interpreter for method "
3292 << PrettyMethod(m);
3293 return DeoptimizationRequest::kNothing;
3294 }
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003295 const Breakpoint* first_breakpoint;
Sebastien Hertzf3928792014-11-17 19:00:37 +01003296 {
3297 ReaderMutexLock mu(self, *Locks::breakpoint_lock_);
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003298 first_breakpoint = FindFirstBreakpointForMethod(m);
3299 *existing_brkpt = first_breakpoint;
Sebastien Hertzf3928792014-11-17 19:00:37 +01003300 }
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003301
3302 if (first_breakpoint == nullptr) {
Nicolas Geoffray6300fd72016-03-18 09:40:17 +00003303 // There is no breakpoint on this method yet: we need to deoptimize. If this method is default,
3304 // we deoptimize everything; otherwise we deoptimize only this method. We
Alex Light6c8467f2015-11-20 15:03:26 -08003305 // deoptimize with defaults because we do not know everywhere they are used. It is possible some
Nicolas Geoffray6300fd72016-03-18 09:40:17 +00003306 // of the copies could be missed.
Alex Light6c8467f2015-11-20 15:03:26 -08003307 // TODO Deoptimizing on default methods might not be necessary in all cases.
Nicolas Geoffray6300fd72016-03-18 09:40:17 +00003308 bool need_full_deoptimization = m->IsDefault();
Sebastien Hertzf3928792014-11-17 19:00:37 +01003309 if (need_full_deoptimization) {
Nicolas Geoffray6300fd72016-03-18 09:40:17 +00003310 VLOG(jdwp) << "Need full deoptimization because of copying of method "
Sebastien Hertzf3928792014-11-17 19:00:37 +01003311 << PrettyMethod(m);
3312 return DeoptimizationRequest::kFullDeoptimization;
3313 } else {
3314 // We don't need to deoptimize if the method has not been compiled.
Nicolas Geoffraya5891e82015-11-06 14:18:27 +00003315 const bool is_compiled = m->HasAnyCompiledCode();
Sebastien Hertzf3928792014-11-17 19:00:37 +01003316 if (is_compiled) {
Nicolas Geoffray6300fd72016-03-18 09:40:17 +00003317 VLOG(jdwp) << "Need selective deoptimization for compiled method " << PrettyMethod(m);
3318 return DeoptimizationRequest::kSelectiveDeoptimization;
Sebastien Hertzf3928792014-11-17 19:00:37 +01003319 } else {
3320 // Method is not compiled: we don't need to deoptimize.
3321 VLOG(jdwp) << "No need for deoptimization for non-compiled method " << PrettyMethod(m);
3322 return DeoptimizationRequest::kNothing;
3323 }
3324 }
3325 } else {
3326 // There is at least one breakpoint for this method: we don't need to deoptimize.
3327 // Let's check that all breakpoints are configured the same way for deoptimization.
3328 VLOG(jdwp) << "Breakpoint already set: no deoptimization is required";
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003329 DeoptimizationRequest::Kind deoptimization_kind = first_breakpoint->GetDeoptimizationKind();
Sebastien Hertzf3928792014-11-17 19:00:37 +01003330 if (kIsDebugBuild) {
3331 ReaderMutexLock mu(self, *Locks::breakpoint_lock_);
3332 SanityCheckExistingBreakpoints(m, deoptimization_kind);
3333 }
3334 return DeoptimizationRequest::kNothing;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003335 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003336}
3337
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003338// Installs a breakpoint at the specified location. Also indicates through the deoptimization
3339// request if we need to deoptimize.
3340void Dbg::WatchLocation(const JDWP::JdwpLocation* location, DeoptimizationRequest* req) {
3341 Thread* const self = Thread::Current();
Mathieu Chartiere401d142015-04-22 13:56:20 -07003342 ArtMethod* m = FromMethodId(location->method_id);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003343 DCHECK(m != nullptr) << "No method for method id " << location->method_id;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003344
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003345 const Breakpoint* existing_breakpoint = nullptr;
3346 const DeoptimizationRequest::Kind deoptimization_kind =
3347 GetRequiredDeoptimizationKind(self, m, &existing_breakpoint);
Sebastien Hertzf3928792014-11-17 19:00:37 +01003348 req->SetKind(deoptimization_kind);
3349 if (deoptimization_kind == DeoptimizationRequest::kSelectiveDeoptimization) {
3350 req->SetMethod(m);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003351 } else {
Sebastien Hertzf3928792014-11-17 19:00:37 +01003352 CHECK(deoptimization_kind == DeoptimizationRequest::kNothing ||
3353 deoptimization_kind == DeoptimizationRequest::kFullDeoptimization);
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003354 req->SetMethod(nullptr);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003355 }
3356
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003357 {
3358 WriterMutexLock mu(self, *Locks::breakpoint_lock_);
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003359 // If there is at least one existing breakpoint on the same method, the new breakpoint
3360 // must have the same deoptimization kind than the existing breakpoint(s).
3361 DeoptimizationRequest::Kind breakpoint_deoptimization_kind;
3362 if (existing_breakpoint != nullptr) {
3363 breakpoint_deoptimization_kind = existing_breakpoint->GetDeoptimizationKind();
3364 } else {
3365 breakpoint_deoptimization_kind = deoptimization_kind;
3366 }
3367 gBreakpoints.push_back(Breakpoint(m, location->dex_pc, breakpoint_deoptimization_kind));
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003368 VLOG(jdwp) << "Set breakpoint #" << (gBreakpoints.size() - 1) << ": "
3369 << gBreakpoints[gBreakpoints.size() - 1];
3370 }
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003371}
3372
3373// Uninstalls a breakpoint at the specified location. Also indicates through the deoptimization
3374// request if we need to undeoptimize.
3375void Dbg::UnwatchLocation(const JDWP::JdwpLocation* location, DeoptimizationRequest* req) {
Sebastien Hertzed2be172014-08-19 15:33:43 +02003376 WriterMutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003377 ArtMethod* m = FromMethodId(location->method_id);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003378 DCHECK(m != nullptr) << "No method for method id " << location->method_id;
Sebastien Hertzf3928792014-11-17 19:00:37 +01003379 DeoptimizationRequest::Kind deoptimization_kind = DeoptimizationRequest::kNothing;
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003380 for (size_t i = 0, e = gBreakpoints.size(); i < e; ++i) {
Alex Light6c8467f2015-11-20 15:03:26 -08003381 if (gBreakpoints[i].DexPc() == location->dex_pc && gBreakpoints[i].IsInMethod(m)) {
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003382 VLOG(jdwp) << "Removed breakpoint #" << i << ": " << gBreakpoints[i];
Sebastien Hertzf3928792014-11-17 19:00:37 +01003383 deoptimization_kind = gBreakpoints[i].GetDeoptimizationKind();
3384 DCHECK_EQ(deoptimization_kind == DeoptimizationRequest::kSelectiveDeoptimization,
3385 Runtime::Current()->GetInstrumentation()->IsDeoptimized(m));
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003386 gBreakpoints.erase(gBreakpoints.begin() + i);
3387 break;
3388 }
3389 }
3390 const Breakpoint* const existing_breakpoint = FindFirstBreakpointForMethod(m);
3391 if (existing_breakpoint == nullptr) {
3392 // There is no more breakpoint on this method: we need to undeoptimize.
Sebastien Hertzf3928792014-11-17 19:00:37 +01003393 if (deoptimization_kind == DeoptimizationRequest::kFullDeoptimization) {
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003394 // This method required full deoptimization: we need to undeoptimize everything.
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003395 req->SetKind(DeoptimizationRequest::kFullUndeoptimization);
3396 req->SetMethod(nullptr);
Sebastien Hertzf3928792014-11-17 19:00:37 +01003397 } else if (deoptimization_kind == DeoptimizationRequest::kSelectiveDeoptimization) {
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003398 // This method required selective deoptimization: we need to undeoptimize only that method.
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003399 req->SetKind(DeoptimizationRequest::kSelectiveUndeoptimization);
3400 req->SetMethod(m);
Sebastien Hertzf3928792014-11-17 19:00:37 +01003401 } else {
3402 // This method had no need for deoptimization: do nothing.
3403 CHECK_EQ(deoptimization_kind, DeoptimizationRequest::kNothing);
3404 req->SetKind(DeoptimizationRequest::kNothing);
3405 req->SetMethod(nullptr);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003406 }
3407 } else {
3408 // There is at least one breakpoint for this method: we don't need to undeoptimize.
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003409 req->SetKind(DeoptimizationRequest::kNothing);
3410 req->SetMethod(nullptr);
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003411 if (kIsDebugBuild) {
Sebastien Hertzf3928792014-11-17 19:00:37 +01003412 SanityCheckExistingBreakpoints(m, deoptimization_kind);
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003413 }
Elliott Hughes86964332012-02-15 19:37:42 -08003414 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003415}
3416
Mathieu Chartiere401d142015-04-22 13:56:20 -07003417bool Dbg::IsForcedInterpreterNeededForCallingImpl(Thread* thread, ArtMethod* m) {
Daniel Mihalyieb076692014-08-22 17:33:31 +02003418 const SingleStepControl* const ssc = thread->GetSingleStepControl();
3419 if (ssc == nullptr) {
3420 // If we are not single-stepping, then we don't have to force interpreter.
3421 return false;
3422 }
3423 if (Runtime::Current()->GetInstrumentation()->InterpretOnly()) {
3424 // If we are in interpreter only mode, then we don't have to force interpreter.
3425 return false;
3426 }
3427
3428 if (!m->IsNative() && !m->IsProxyMethod()) {
3429 // If we want to step into a method, then we have to force interpreter on that call.
3430 if (ssc->GetStepDepth() == JDWP::SD_INTO) {
3431 return true;
3432 }
3433 }
3434 return false;
3435}
3436
Mathieu Chartiere401d142015-04-22 13:56:20 -07003437bool Dbg::IsForcedInterpreterNeededForResolutionImpl(Thread* thread, ArtMethod* m) {
Daniel Mihalyieb076692014-08-22 17:33:31 +02003438 instrumentation::Instrumentation* const instrumentation =
3439 Runtime::Current()->GetInstrumentation();
3440 // If we are in interpreter only mode, then we don't have to force interpreter.
3441 if (instrumentation->InterpretOnly()) {
3442 return false;
3443 }
3444 // We can only interpret pure Java method.
3445 if (m->IsNative() || m->IsProxyMethod()) {
3446 return false;
3447 }
3448 const SingleStepControl* const ssc = thread->GetSingleStepControl();
3449 if (ssc != nullptr) {
3450 // If we want to step into a method, then we have to force interpreter on that call.
3451 if (ssc->GetStepDepth() == JDWP::SD_INTO) {
3452 return true;
3453 }
3454 // If we are stepping out from a static initializer, by issuing a step
3455 // in or step over, that was implicitly invoked by calling a static method,
3456 // then we need to step into that method. Having a lower stack depth than
3457 // the one the single step control has indicates that the step originates
3458 // from the static initializer.
3459 if (ssc->GetStepDepth() != JDWP::SD_OUT &&
3460 ssc->GetStackDepth() > GetStackDepth(thread)) {
3461 return true;
3462 }
3463 }
3464 // There are cases where we have to force interpreter on deoptimized methods,
3465 // because in some cases the call will not be performed by invoking an entry
3466 // point that has been replaced by the deoptimization, but instead by directly
3467 // invoking the compiled code of the method, for example.
3468 return instrumentation->IsDeoptimized(m);
3469}
3470
Mathieu Chartiere401d142015-04-22 13:56:20 -07003471bool Dbg::IsForcedInstrumentationNeededForResolutionImpl(Thread* thread, ArtMethod* m) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07003472 // The upcall can be null and in that case we don't need to do anything.
Daniel Mihalyieb076692014-08-22 17:33:31 +02003473 if (m == nullptr) {
3474 return false;
3475 }
3476 instrumentation::Instrumentation* const instrumentation =
3477 Runtime::Current()->GetInstrumentation();
3478 // If we are in interpreter only mode, then we don't have to force interpreter.
3479 if (instrumentation->InterpretOnly()) {
3480 return false;
3481 }
3482 // We can only interpret pure Java method.
3483 if (m->IsNative() || m->IsProxyMethod()) {
3484 return false;
3485 }
3486 const SingleStepControl* const ssc = thread->GetSingleStepControl();
3487 if (ssc != nullptr) {
3488 // If we are stepping out from a static initializer, by issuing a step
3489 // out, that was implicitly invoked by calling a static method, then we
3490 // need to step into the caller of that method. Having a lower stack
3491 // depth than the one the single step control has indicates that the
3492 // step originates from the static initializer.
3493 if (ssc->GetStepDepth() == JDWP::SD_OUT &&
3494 ssc->GetStackDepth() > GetStackDepth(thread)) {
3495 return true;
3496 }
3497 }
3498 // If we are returning from a static intializer, that was implicitly
3499 // invoked by calling a static method and the caller is deoptimized,
3500 // then we have to deoptimize the stack without forcing interpreter
3501 // on the static method that was called originally. This problem can
3502 // be solved easily by forcing instrumentation on the called method,
3503 // because the instrumentation exit hook will recognise the need of
3504 // stack deoptimization by calling IsForcedInterpreterNeededForUpcall.
3505 return instrumentation->IsDeoptimized(m);
3506}
3507
Mathieu Chartiere401d142015-04-22 13:56:20 -07003508bool Dbg::IsForcedInterpreterNeededForUpcallImpl(Thread* thread, ArtMethod* m) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07003509 // The upcall can be null and in that case we don't need to do anything.
Daniel Mihalyieb076692014-08-22 17:33:31 +02003510 if (m == nullptr) {
3511 return false;
3512 }
3513 instrumentation::Instrumentation* const instrumentation =
3514 Runtime::Current()->GetInstrumentation();
3515 // If we are in interpreter only mode, then we don't have to force interpreter.
3516 if (instrumentation->InterpretOnly()) {
3517 return false;
3518 }
3519 // We can only interpret pure Java method.
3520 if (m->IsNative() || m->IsProxyMethod()) {
3521 return false;
3522 }
3523 const SingleStepControl* const ssc = thread->GetSingleStepControl();
3524 if (ssc != nullptr) {
3525 // The debugger is not interested in what is happening under the level
3526 // of the step, thus we only force interpreter when we are not below of
3527 // the step.
3528 if (ssc->GetStackDepth() >= GetStackDepth(thread)) {
3529 return true;
3530 }
3531 }
Mingyao Yang99170c62015-07-06 11:10:37 -07003532 if (thread->HasDebuggerShadowFrames()) {
3533 // We need to deoptimize the stack for the exception handling flow so that
3534 // we don't miss any deoptimization that should be done when there are
3535 // debugger shadow frames.
3536 return true;
3537 }
Daniel Mihalyieb076692014-08-22 17:33:31 +02003538 // We have to require stack deoptimization if the upcall is deoptimized.
3539 return instrumentation->IsDeoptimized(m);
3540}
3541
Mingyao Yang99170c62015-07-06 11:10:37 -07003542class NeedsDeoptimizationVisitor : public StackVisitor {
Sebastien Hertz520633b2015-09-08 17:03:36 +02003543 public:
3544 explicit NeedsDeoptimizationVisitor(Thread* self)
3545 SHARED_REQUIRES(Locks::mutator_lock_)
3546 : StackVisitor(self, nullptr, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
3547 needs_deoptimization_(false) {}
3548
3549 bool VisitFrame() OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
3550 // The visitor is meant to be used when handling exception from compiled code only.
3551 CHECK(!IsShadowFrame()) << "We only expect to visit compiled frame: " << PrettyMethod(GetMethod());
3552 ArtMethod* method = GetMethod();
3553 if (method == nullptr) {
3554 // We reach an upcall and don't need to deoptimize this part of the stack (ManagedFragment)
3555 // so we can stop the visit.
3556 DCHECK(!needs_deoptimization_);
3557 return false;
3558 }
3559 if (Runtime::Current()->GetInstrumentation()->InterpretOnly()) {
3560 // We found a compiled frame in the stack but instrumentation is set to interpret
3561 // everything: we need to deoptimize.
3562 needs_deoptimization_ = true;
3563 return false;
3564 }
3565 if (Runtime::Current()->GetInstrumentation()->IsDeoptimized(method)) {
3566 // We found a deoptimized method in the stack.
3567 needs_deoptimization_ = true;
3568 return false;
3569 }
Mingyao Yang99170c62015-07-06 11:10:37 -07003570 ShadowFrame* frame = GetThread()->FindDebuggerShadowFrame(GetFrameId());
3571 if (frame != nullptr) {
3572 // The debugger allocated a ShadowFrame to update a variable in the stack: we need to
3573 // deoptimize the stack to execute (and deallocate) this frame.
3574 needs_deoptimization_ = true;
3575 return false;
3576 }
Sebastien Hertz520633b2015-09-08 17:03:36 +02003577 return true;
3578 }
3579
3580 bool NeedsDeoptimization() const {
3581 return needs_deoptimization_;
3582 }
3583
3584 private:
3585 // Do we need to deoptimize the stack?
3586 bool needs_deoptimization_;
3587
3588 DISALLOW_COPY_AND_ASSIGN(NeedsDeoptimizationVisitor);
3589};
3590
3591// Do we need to deoptimize the stack to handle an exception?
3592bool Dbg::IsForcedInterpreterNeededForExceptionImpl(Thread* thread) {
3593 const SingleStepControl* const ssc = thread->GetSingleStepControl();
3594 if (ssc != nullptr) {
3595 // We deopt to step into the catch handler.
3596 return true;
3597 }
3598 // Deoptimization is required if at least one method in the stack needs it. However we
3599 // skip frames that will be unwound (thus not executed).
3600 NeedsDeoptimizationVisitor visitor(thread);
3601 visitor.WalkStack(true); // includes upcall.
3602 return visitor.NeedsDeoptimization();
3603}
3604
Jeff Hao449db332013-04-12 18:30:52 -07003605// Scoped utility class to suspend a thread so that we may do tasks such as walk its stack. Doesn't
3606// cause suspension if the thread is the current thread.
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07003607class ScopedDebuggerThreadSuspension {
Jeff Hao449db332013-04-12 18:30:52 -07003608 public:
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07003609 ScopedDebuggerThreadSuspension(Thread* self, JDWP::ObjectId thread_id)
Mathieu Chartier90443472015-07-16 20:32:27 -07003610 REQUIRES(!Locks::thread_list_lock_)
3611 SHARED_REQUIRES(Locks::mutator_lock_) :
Ian Rogersf3d874c2014-07-17 18:52:42 -07003612 thread_(nullptr),
Jeff Hao449db332013-04-12 18:30:52 -07003613 error_(JDWP::ERR_NONE),
3614 self_suspend_(false),
Ian Rogers33e95662013-05-20 20:29:14 -07003615 other_suspend_(false) {
Jeff Hao449db332013-04-12 18:30:52 -07003616 ScopedObjectAccessUnchecked soa(self);
Sebastien Hertz69206392015-04-07 15:54:25 +02003617 thread_ = DecodeThread(soa, thread_id, &error_);
Jeff Hao449db332013-04-12 18:30:52 -07003618 if (error_ == JDWP::ERR_NONE) {
3619 if (thread_ == soa.Self()) {
3620 self_suspend_ = true;
3621 } else {
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07003622 Thread* suspended_thread;
3623 {
3624 ScopedThreadSuspension sts(self, kWaitingForDebuggerSuspension);
3625 jobject thread_peer = Dbg::GetObjectRegistry()->GetJObject(thread_id);
3626 bool timed_out;
3627 ThreadList* const thread_list = Runtime::Current()->GetThreadList();
3628 suspended_thread = thread_list->SuspendThreadByPeer(thread_peer, true, true, &timed_out);
3629 }
Ian Rogersf3d874c2014-07-17 18:52:42 -07003630 if (suspended_thread == nullptr) {
Jeff Hao449db332013-04-12 18:30:52 -07003631 // Thread terminated from under us while suspending.
3632 error_ = JDWP::ERR_INVALID_THREAD;
3633 } else {
3634 CHECK_EQ(suspended_thread, thread_);
3635 other_suspend_ = true;
3636 }
3637 }
3638 }
Elliott Hughes2435a572012-02-17 16:07:41 -08003639 }
Elliott Hughes86964332012-02-15 19:37:42 -08003640
Jeff Hao449db332013-04-12 18:30:52 -07003641 Thread* GetThread() const {
3642 return thread_;
3643 }
3644
3645 JDWP::JdwpError GetError() const {
3646 return error_;
3647 }
3648
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07003649 ~ScopedDebuggerThreadSuspension() {
Jeff Hao449db332013-04-12 18:30:52 -07003650 if (other_suspend_) {
3651 Runtime::Current()->GetThreadList()->Resume(thread_, true);
3652 }
3653 }
3654
3655 private:
3656 Thread* thread_;
3657 JDWP::JdwpError error_;
3658 bool self_suspend_;
3659 bool other_suspend_;
3660};
3661
3662JDWP::JdwpError Dbg::ConfigureStep(JDWP::ObjectId thread_id, JDWP::JdwpStepSize step_size,
3663 JDWP::JdwpStepDepth step_depth) {
3664 Thread* self = Thread::Current();
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07003665 ScopedDebuggerThreadSuspension sts(self, thread_id);
Jeff Hao449db332013-04-12 18:30:52 -07003666 if (sts.GetError() != JDWP::ERR_NONE) {
3667 return sts.GetError();
3668 }
3669
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003670 // Work out what ArtMethod* we're in, the current line number, and how deep the stack currently
Elliott Hughes2435a572012-02-17 16:07:41 -08003671 // is for step-out.
Ian Rogers0399dde2012-06-06 17:09:28 -07003672 struct SingleStepStackVisitor : public StackVisitor {
Mathieu Chartier90443472015-07-16 20:32:27 -07003673 explicit SingleStepStackVisitor(Thread* thread) SHARED_REQUIRES(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01003674 : StackVisitor(thread, nullptr, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
3675 stack_depth(0),
3676 method(nullptr),
3677 line_number(-1) {}
Ian Rogersca190662012-06-26 15:45:57 -07003678
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003679 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
3680 // annotalysis.
3681 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003682 ArtMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07003683 if (!m->IsRuntimeMethod()) {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003684 ++stack_depth;
3685 if (method == nullptr) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08003686 mirror::DexCache* dex_cache = m->GetDeclaringClass()->GetDexCache();
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003687 method = m;
Ian Rogersc0542af2014-09-03 16:16:56 -07003688 if (dex_cache != nullptr) {
Ian Rogers4445a7e2012-10-05 17:19:13 -07003689 const DexFile& dex_file = *dex_cache->GetDexFile();
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003690 line_number = dex_file.GetLineNumFromPC(m, GetDexPc());
Elliott Hughes2435a572012-02-17 16:07:41 -08003691 }
Elliott Hughes86964332012-02-15 19:37:42 -08003692 }
3693 }
Elliott Hughes530fa002012-03-12 11:44:49 -07003694 return true;
Elliott Hughes86964332012-02-15 19:37:42 -08003695 }
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003696
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003697 int stack_depth;
Mathieu Chartiere401d142015-04-22 13:56:20 -07003698 ArtMethod* method;
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003699 int32_t line_number;
Elliott Hughes86964332012-02-15 19:37:42 -08003700 };
Jeff Hao449db332013-04-12 18:30:52 -07003701
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003702 Thread* const thread = sts.GetThread();
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003703 SingleStepStackVisitor visitor(thread);
Ian Rogers0399dde2012-06-06 17:09:28 -07003704 visitor.WalkStack();
Elliott Hughes86964332012-02-15 19:37:42 -08003705
Elliott Hughes2435a572012-02-17 16:07:41 -08003706 // Find the dex_pc values that correspond to the current line, for line-based single-stepping.
Elliott Hughes2435a572012-02-17 16:07:41 -08003707 struct DebugCallbackContext {
Roland Levillain3887c462015-08-12 18:15:42 +01003708 DebugCallbackContext(SingleStepControl* single_step_control_cb,
3709 int32_t line_number_cb, const DexFile::CodeItem* code_item)
3710 : single_step_control_(single_step_control_cb), line_number_(line_number_cb),
3711 code_item_(code_item), last_pc_valid(false), last_pc(0) {
Elliott Hughes2435a572012-02-17 16:07:41 -08003712 }
3713
David Srbeckyb06e28e2015-12-10 13:15:00 +00003714 static bool Callback(void* raw_context, const DexFile::PositionInfo& entry) {
Elliott Hughes2435a572012-02-17 16:07:41 -08003715 DebugCallbackContext* context = reinterpret_cast<DebugCallbackContext*>(raw_context);
David Srbeckyb06e28e2015-12-10 13:15:00 +00003716 if (static_cast<int32_t>(entry.line_) == context->line_number_) {
Elliott Hughes2435a572012-02-17 16:07:41 -08003717 if (!context->last_pc_valid) {
3718 // Everything from this address until the next line change is ours.
David Srbeckyb06e28e2015-12-10 13:15:00 +00003719 context->last_pc = entry.address_;
Elliott Hughes2435a572012-02-17 16:07:41 -08003720 context->last_pc_valid = true;
3721 }
3722 // Otherwise, if we're already in a valid range for this line,
3723 // just keep going (shouldn't really happen)...
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003724 } else if (context->last_pc_valid) { // and the line number is new
Elliott Hughes2435a572012-02-17 16:07:41 -08003725 // Add everything from the last entry up until here to the set
David Srbeckyb06e28e2015-12-10 13:15:00 +00003726 for (uint32_t dex_pc = context->last_pc; dex_pc < entry.address_; ++dex_pc) {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003727 context->single_step_control_->AddDexPc(dex_pc);
Elliott Hughes2435a572012-02-17 16:07:41 -08003728 }
3729 context->last_pc_valid = false;
3730 }
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003731 return false; // There may be multiple entries for any given line.
Elliott Hughes2435a572012-02-17 16:07:41 -08003732 }
3733
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003734 ~DebugCallbackContext() {
Elliott Hughes2435a572012-02-17 16:07:41 -08003735 // If the line number was the last in the position table...
3736 if (last_pc_valid) {
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003737 size_t end = code_item_->insns_size_in_code_units_;
Elliott Hughes2435a572012-02-17 16:07:41 -08003738 for (uint32_t dex_pc = last_pc; dex_pc < end; ++dex_pc) {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003739 single_step_control_->AddDexPc(dex_pc);
Elliott Hughes2435a572012-02-17 16:07:41 -08003740 }
3741 }
3742 }
3743
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003744 SingleStepControl* const single_step_control_;
3745 const int32_t line_number_;
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003746 const DexFile::CodeItem* const code_item_;
Elliott Hughes2435a572012-02-17 16:07:41 -08003747 bool last_pc_valid;
3748 uint32_t last_pc;
3749 };
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003750
3751 // Allocate single step.
Sebastien Hertz1558b572015-02-25 15:05:59 +01003752 SingleStepControl* single_step_control =
3753 new (std::nothrow) SingleStepControl(step_size, step_depth,
3754 visitor.stack_depth, visitor.method);
3755 if (single_step_control == nullptr) {
3756 LOG(ERROR) << "Failed to allocate SingleStepControl";
3757 return JDWP::ERR_OUT_OF_MEMORY;
3758 }
3759
Mathieu Chartiere401d142015-04-22 13:56:20 -07003760 ArtMethod* m = single_step_control->GetMethod();
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003761 const int32_t line_number = visitor.line_number;
Sebastien Hertz52f5f932015-05-28 11:00:57 +02003762 // Note: if the thread is not running Java code (pure native thread), there is no "current"
3763 // method on the stack (and no line number either).
3764 if (m != nullptr && !m->IsNative()) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003765 const DexFile::CodeItem* const code_item = m->GetCodeItem();
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003766 DebugCallbackContext context(single_step_control, line_number, code_item);
David Srbeckyb06e28e2015-12-10 13:15:00 +00003767 m->GetDexFile()->DecodeDebugPositionInfo(code_item, DebugCallbackContext::Callback, &context);
Elliott Hughes3e2e1a22012-02-21 11:33:41 -08003768 }
Elliott Hughes2435a572012-02-17 16:07:41 -08003769
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003770 // Activate single-step in the thread.
3771 thread->ActivateSingleStepControl(single_step_control);
Elliott Hughes86964332012-02-15 19:37:42 -08003772
Elliott Hughes2435a572012-02-17 16:07:41 -08003773 if (VLOG_IS_ON(jdwp)) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003774 VLOG(jdwp) << "Single-step thread: " << *thread;
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003775 VLOG(jdwp) << "Single-step step size: " << single_step_control->GetStepSize();
3776 VLOG(jdwp) << "Single-step step depth: " << single_step_control->GetStepDepth();
3777 VLOG(jdwp) << "Single-step current method: " << PrettyMethod(single_step_control->GetMethod());
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003778 VLOG(jdwp) << "Single-step current line: " << line_number;
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003779 VLOG(jdwp) << "Single-step current stack depth: " << single_step_control->GetStackDepth();
Elliott Hughes2435a572012-02-17 16:07:41 -08003780 VLOG(jdwp) << "Single-step dex_pc values:";
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003781 for (uint32_t dex_pc : single_step_control->GetDexPcs()) {
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003782 VLOG(jdwp) << StringPrintf(" %#x", dex_pc);
Elliott Hughes2435a572012-02-17 16:07:41 -08003783 }
3784 }
3785
3786 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003787}
3788
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003789void Dbg::UnconfigureStep(JDWP::ObjectId thread_id) {
3790 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07003791 JDWP::JdwpError error;
3792 Thread* thread = DecodeThread(soa, thread_id, &error);
Sebastien Hertz87118ed2013-11-26 17:57:18 +01003793 if (error == JDWP::ERR_NONE) {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003794 thread->DeactivateSingleStepControl();
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003795 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003796}
3797
Elliott Hughes45651fd2012-02-21 15:48:20 -08003798static char JdwpTagToShortyChar(JDWP::JdwpTag tag) {
3799 switch (tag) {
3800 default:
3801 LOG(FATAL) << "unknown JDWP tag: " << PrintableChar(tag);
Ian Rogersfc787ec2014-10-09 21:56:44 -07003802 UNREACHABLE();
Elliott Hughes45651fd2012-02-21 15:48:20 -08003803
3804 // Primitives.
3805 case JDWP::JT_BYTE: return 'B';
3806 case JDWP::JT_CHAR: return 'C';
3807 case JDWP::JT_FLOAT: return 'F';
3808 case JDWP::JT_DOUBLE: return 'D';
3809 case JDWP::JT_INT: return 'I';
3810 case JDWP::JT_LONG: return 'J';
3811 case JDWP::JT_SHORT: return 'S';
3812 case JDWP::JT_VOID: return 'V';
3813 case JDWP::JT_BOOLEAN: return 'Z';
3814
3815 // Reference types.
3816 case JDWP::JT_ARRAY:
3817 case JDWP::JT_OBJECT:
3818 case JDWP::JT_STRING:
3819 case JDWP::JT_THREAD:
3820 case JDWP::JT_THREAD_GROUP:
3821 case JDWP::JT_CLASS_LOADER:
3822 case JDWP::JT_CLASS_OBJECT:
3823 return 'L';
3824 }
3825}
3826
Sebastien Hertzcbc50642015-06-01 17:33:12 +02003827JDWP::JdwpError Dbg::PrepareInvokeMethod(uint32_t request_id, JDWP::ObjectId thread_id,
3828 JDWP::ObjectId object_id, JDWP::RefTypeId class_id,
3829 JDWP::MethodId method_id, uint32_t arg_count,
3830 uint64_t arg_values[], JDWP::JdwpTag* arg_types,
3831 uint32_t options) {
3832 Thread* const self = Thread::Current();
3833 CHECK_EQ(self, GetDebugThread()) << "This must be called by the JDWP thread";
Sebastien Hertzd4032e42015-06-12 15:47:34 +02003834 const bool resume_all_threads = ((options & JDWP::INVOKE_SINGLE_THREADED) == 0);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003835
Sebastien Hertzcbc50642015-06-01 17:33:12 +02003836 ThreadList* thread_list = Runtime::Current()->GetThreadList();
Ian Rogersc0542af2014-09-03 16:16:56 -07003837 Thread* targetThread = nullptr;
Elliott Hughesd07986f2011-12-06 18:27:45 -08003838 {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003839 ScopedObjectAccessUnchecked soa(self);
Ian Rogersc0542af2014-09-03 16:16:56 -07003840 JDWP::JdwpError error;
3841 targetThread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08003842 if (error != JDWP::ERR_NONE) {
3843 LOG(ERROR) << "InvokeMethod request for invalid thread id " << thread_id;
3844 return error;
Elliott Hughesd07986f2011-12-06 18:27:45 -08003845 }
Sebastien Hertz1558b572015-02-25 15:05:59 +01003846 if (targetThread->GetInvokeReq() != nullptr) {
3847 // Thread is already invoking a method on behalf of the debugger.
3848 LOG(ERROR) << "InvokeMethod request for thread already invoking a method: " << *targetThread;
3849 return JDWP::ERR_ALREADY_INVOKING;
3850 }
3851 if (!targetThread->IsReadyForDebugInvoke()) {
3852 // Thread is not suspended by an event so it cannot invoke a method.
Elliott Hughesd07986f2011-12-06 18:27:45 -08003853 LOG(ERROR) << "InvokeMethod request for thread not stopped by event: " << *targetThread;
3854 return JDWP::ERR_INVALID_THREAD;
3855 }
3856
3857 /*
Sebastien Hertzd4032e42015-06-12 15:47:34 +02003858 * According to the JDWP specs, we are expected to resume all threads (or only the
3859 * target thread) once. So if a thread has been suspended more than once (either by
3860 * the debugger for an event or by the runtime for GC), it will remain suspended before
3861 * the invoke is executed. This means the debugger is responsible to properly resume all
3862 * the threads it has suspended so the target thread can execute the method.
Elliott Hughesd07986f2011-12-06 18:27:45 -08003863 *
Sebastien Hertzd4032e42015-06-12 15:47:34 +02003864 * However, for compatibility reason with older versions of debuggers (like Eclipse), we
3865 * fully resume all threads (by canceling *all* debugger suspensions) when the debugger
3866 * wants us to resume all threads. This is to avoid ending up in deadlock situation.
3867 *
3868 * On the other hand, if we are asked to only resume the target thread, then we follow the
3869 * JDWP specs by resuming that thread only once. This means the thread will remain suspended
3870 * if it has been suspended more than once before the invoke (and again, this is the
3871 * responsibility of the debugger to properly resume that thread before invoking a method).
Elliott Hughesd07986f2011-12-06 18:27:45 -08003872 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003873 int suspend_count;
3874 {
Ian Rogers50b35e22012-10-04 10:09:15 -07003875 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003876 suspend_count = targetThread->GetSuspendCount();
3877 }
Sebastien Hertzd4032e42015-06-12 15:47:34 +02003878 if (suspend_count > 1 && resume_all_threads) {
3879 // The target thread will remain suspended even after we resume it. Let's emit a warning
3880 // to indicate the invoke won't be executed until the thread is resumed.
3881 LOG(WARNING) << *targetThread << " suspended more than once (suspend count == "
3882 << suspend_count << "). This thread will invoke the method only once "
3883 << "it is fully resumed.";
Elliott Hughesd07986f2011-12-06 18:27:45 -08003884 }
3885
Ian Rogersc0542af2014-09-03 16:16:56 -07003886 mirror::Object* receiver = gRegistry->Get<mirror::Object*>(object_id, &error);
3887 if (error != JDWP::ERR_NONE) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08003888 return JDWP::ERR_INVALID_OBJECT;
3889 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003890
Sebastien Hertz1558b572015-02-25 15:05:59 +01003891 gRegistry->Get<mirror::Object*>(thread_id, &error);
Ian Rogersc0542af2014-09-03 16:16:56 -07003892 if (error != JDWP::ERR_NONE) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08003893 return JDWP::ERR_INVALID_OBJECT;
3894 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003895
Ian Rogersc0542af2014-09-03 16:16:56 -07003896 mirror::Class* c = DecodeClass(class_id, &error);
3897 if (c == nullptr) {
3898 return error;
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08003899 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003900
Mathieu Chartiere401d142015-04-22 13:56:20 -07003901 ArtMethod* m = FromMethodId(method_id);
Ian Rogersc0542af2014-09-03 16:16:56 -07003902 if (m->IsStatic() != (receiver == nullptr)) {
Elliott Hughes45651fd2012-02-21 15:48:20 -08003903 return JDWP::ERR_INVALID_METHODID;
3904 }
3905 if (m->IsStatic()) {
3906 if (m->GetDeclaringClass() != c) {
3907 return JDWP::ERR_INVALID_METHODID;
3908 }
3909 } else {
3910 if (!m->GetDeclaringClass()->IsAssignableFrom(c)) {
3911 return JDWP::ERR_INVALID_METHODID;
3912 }
3913 }
3914
3915 // Check the argument list matches the method.
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003916 uint32_t shorty_len = 0;
3917 const char* shorty = m->GetShorty(&shorty_len);
3918 if (shorty_len - 1 != arg_count) {
Elliott Hughes45651fd2012-02-21 15:48:20 -08003919 return JDWP::ERR_ILLEGAL_ARGUMENT;
3920 }
Elliott Hughes09201632013-04-15 15:50:07 -07003921
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003922 {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003923 StackHandleScope<2> hs(soa.Self());
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003924 HandleWrapper<mirror::Object> h_obj(hs.NewHandleWrapper(&receiver));
3925 HandleWrapper<mirror::Class> h_klass(hs.NewHandleWrapper(&c));
3926 const DexFile::TypeList* types = m->GetParameterTypeList();
3927 for (size_t i = 0; i < arg_count; ++i) {
3928 if (shorty[i + 1] != JdwpTagToShortyChar(arg_types[i])) {
Elliott Hughes09201632013-04-15 15:50:07 -07003929 return JDWP::ERR_ILLEGAL_ARGUMENT;
3930 }
3931
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003932 if (shorty[i + 1] == 'L') {
3933 // Did we really get an argument of an appropriate reference type?
Ian Rogersa0485602014-12-02 15:48:04 -08003934 mirror::Class* parameter_type =
Vladimir Marko05792b92015-08-03 11:56:49 +01003935 m->GetClassFromTypeIndex(types->GetTypeItem(i).type_idx_,
3936 true /* resolve */,
3937 sizeof(void*));
Ian Rogersc0542af2014-09-03 16:16:56 -07003938 mirror::Object* argument = gRegistry->Get<mirror::Object*>(arg_values[i], &error);
3939 if (error != JDWP::ERR_NONE) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003940 return JDWP::ERR_INVALID_OBJECT;
3941 }
Ian Rogersc0542af2014-09-03 16:16:56 -07003942 if (argument != nullptr && !argument->InstanceOf(parameter_type)) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003943 return JDWP::ERR_ILLEGAL_ARGUMENT;
3944 }
3945
3946 // Turn the on-the-wire ObjectId into a jobject.
3947 jvalue& v = reinterpret_cast<jvalue&>(arg_values[i]);
3948 v.l = gRegistry->GetJObject(arg_values[i]);
3949 }
Elliott Hughes09201632013-04-15 15:50:07 -07003950 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003951 }
3952
Sebastien Hertz1558b572015-02-25 15:05:59 +01003953 // Allocates a DebugInvokeReq.
Sebastien Hertzcbc50642015-06-01 17:33:12 +02003954 DebugInvokeReq* req = new (std::nothrow) DebugInvokeReq(request_id, thread_id, receiver, c, m,
3955 options, arg_values, arg_count);
3956 if (req == nullptr) {
Sebastien Hertz1558b572015-02-25 15:05:59 +01003957 LOG(ERROR) << "Failed to allocate DebugInvokeReq";
3958 return JDWP::ERR_OUT_OF_MEMORY;
3959 }
3960
Sebastien Hertzcbc50642015-06-01 17:33:12 +02003961 // Attaches the DebugInvokeReq to the target thread so it executes the method when
3962 // it is resumed. Once the invocation completes, the target thread will delete it before
3963 // suspending itself (see ThreadList::SuspendSelfForDebugger).
3964 targetThread->SetDebugInvokeReq(req);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003965 }
3966
3967 // 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 +02003968 // away we're sitting high and dry -- but we must release this before the UndoDebuggerSuspensions
3969 // call.
Sebastien Hertzd4032e42015-06-12 15:47:34 +02003970 if (resume_all_threads) {
Sebastien Hertzcbc50642015-06-01 17:33:12 +02003971 VLOG(jdwp) << " Resuming all threads";
3972 thread_list->UndoDebuggerSuspensions();
3973 } else {
3974 VLOG(jdwp) << " Resuming event thread only";
Elliott Hughesd07986f2011-12-06 18:27:45 -08003975 thread_list->Resume(targetThread, true);
3976 }
3977
Sebastien Hertzcbc50642015-06-01 17:33:12 +02003978 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003979}
3980
3981void Dbg::ExecuteMethod(DebugInvokeReq* pReq) {
Sebastien Hertzcbc50642015-06-01 17:33:12 +02003982 Thread* const self = Thread::Current();
3983 CHECK_NE(self, GetDebugThread()) << "This must be called by the event thread";
3984
3985 ScopedObjectAccess soa(self);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003986
Elliott Hughes81ff3182012-03-23 20:35:56 -07003987 // We can be called while an exception is pending. We need
Elliott Hughesd07986f2011-12-06 18:27:45 -08003988 // to preserve that across the method invocation.
Sebastien Hertzcbc50642015-06-01 17:33:12 +02003989 StackHandleScope<1> hs(soa.Self());
3990 Handle<mirror::Throwable> old_exception = hs.NewHandle(soa.Self()->GetException());
Sebastien Hertz1558b572015-02-25 15:05:59 +01003991 soa.Self()->ClearException();
Elliott Hughesd07986f2011-12-06 18:27:45 -08003992
Sebastien Hertzcbc50642015-06-01 17:33:12 +02003993 // Execute the method then sends reply to the debugger.
3994 ExecuteMethodWithoutPendingException(soa, pReq);
3995
3996 // If an exception was pending before the invoke, restore it now.
3997 if (old_exception.Get() != nullptr) {
3998 soa.Self()->SetException(old_exception.Get());
3999 }
4000}
4001
4002// Helper function: write a variable-width value into the output input buffer.
4003static void WriteValue(JDWP::ExpandBuf* pReply, int width, uint64_t value) {
4004 switch (width) {
4005 case 1:
4006 expandBufAdd1(pReply, value);
4007 break;
4008 case 2:
4009 expandBufAdd2BE(pReply, value);
4010 break;
4011 case 4:
4012 expandBufAdd4BE(pReply, value);
4013 break;
4014 case 8:
4015 expandBufAdd8BE(pReply, value);
4016 break;
4017 default:
4018 LOG(FATAL) << width;
4019 UNREACHABLE();
4020 }
4021}
4022
4023void Dbg::ExecuteMethodWithoutPendingException(ScopedObjectAccess& soa, DebugInvokeReq* pReq) {
4024 soa.Self()->AssertNoPendingException();
4025
Elliott Hughesd07986f2011-12-06 18:27:45 -08004026 // Translate the method through the vtable, unless the debugger wants to suppress it.
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004027 ArtMethod* m = pReq->method;
4028 size_t image_pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
Sebastien Hertz1558b572015-02-25 15:05:59 +01004029 if ((pReq->options & JDWP::INVOKE_NONVIRTUAL) == 0 && pReq->receiver.Read() != nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004030 ArtMethod* actual_method =
4031 pReq->klass.Read()->FindVirtualMethodForVirtualOrInterface(m, image_pointer_size);
4032 if (actual_method != m) {
4033 VLOG(jdwp) << "ExecuteMethod translated " << PrettyMethod(m)
Sebastien Hertz1558b572015-02-25 15:05:59 +01004034 << " to " << PrettyMethod(actual_method);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004035 m = actual_method;
Elliott Hughes45651fd2012-02-21 15:48:20 -08004036 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08004037 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07004038 VLOG(jdwp) << "ExecuteMethod " << PrettyMethod(m)
Sebastien Hertz1558b572015-02-25 15:05:59 +01004039 << " receiver=" << pReq->receiver.Read()
Sebastien Hertzd38667a2013-11-25 15:43:54 +01004040 << " arg_count=" << pReq->arg_count;
Mathieu Chartiere401d142015-04-22 13:56:20 -07004041 CHECK(m != nullptr);
Elliott Hughesd07986f2011-12-06 18:27:45 -08004042
Roland Levillain33d69032015-06-18 18:20:59 +01004043 static_assert(sizeof(jvalue) == sizeof(uint64_t), "jvalue and uint64_t have different sizes.");
Elliott Hughesd07986f2011-12-06 18:27:45 -08004044
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004045 // Invoke the method.
Jeff Hao39b6c242015-05-19 20:30:23 -07004046 ScopedLocalRef<jobject> ref(soa.Env(), soa.AddLocalReference<jobject>(pReq->receiver.Read()));
Mathieu Chartiere401d142015-04-22 13:56:20 -07004047 JValue result = InvokeWithJValues(soa, ref.get(), soa.EncodeMethod(m),
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004048 reinterpret_cast<jvalue*>(pReq->arg_values.get()));
Elliott Hughesd07986f2011-12-06 18:27:45 -08004049
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004050 // Prepare JDWP ids for the reply.
4051 JDWP::JdwpTag result_tag = BasicTagFromDescriptor(m->GetShorty());
4052 const bool is_object_result = (result_tag == JDWP::JT_OBJECT);
4053 StackHandleScope<2> hs(soa.Self());
Sebastien Hertz1558b572015-02-25 15:05:59 +01004054 Handle<mirror::Object> object_result = hs.NewHandle(is_object_result ? result.GetL() : nullptr);
4055 Handle<mirror::Throwable> exception = hs.NewHandle(soa.Self()->GetException());
4056 soa.Self()->ClearException();
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004057
4058 if (!IsDebuggerActive()) {
4059 // The debugger detached: we must not re-suspend threads. We also don't need to fill the reply
4060 // because it won't be sent either.
4061 return;
4062 }
4063
4064 JDWP::ObjectId exceptionObjectId = gRegistry->Add(exception);
4065 uint64_t result_value = 0;
4066 if (exceptionObjectId != 0) {
Sebastien Hertz1558b572015-02-25 15:05:59 +01004067 VLOG(jdwp) << " JDWP invocation returning with exception=" << exception.Get()
4068 << " " << exception->Dump();
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004069 result_value = 0;
Sebastien Hertz1558b572015-02-25 15:05:59 +01004070 } else if (is_object_result) {
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004071 /* if no exception was thrown, examine object result more closely */
Sebastien Hertz1558b572015-02-25 15:05:59 +01004072 JDWP::JdwpTag new_tag = TagFromObject(soa, object_result.Get());
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004073 if (new_tag != result_tag) {
4074 VLOG(jdwp) << " JDWP promoted result from " << result_tag << " to " << new_tag;
4075 result_tag = new_tag;
Elliott Hughesd07986f2011-12-06 18:27:45 -08004076 }
4077
Sebastien Hertz1558b572015-02-25 15:05:59 +01004078 // Register the object in the registry and reference its ObjectId. This ensures
4079 // GC safety and prevents from accessing stale reference if the object is moved.
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004080 result_value = gRegistry->Add(object_result.Get());
Sebastien Hertz1558b572015-02-25 15:05:59 +01004081 } else {
4082 // Primitive result.
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004083 DCHECK(IsPrimitiveTag(result_tag));
4084 result_value = result.GetJ();
4085 }
4086 const bool is_constructor = m->IsConstructor() && !m->IsStatic();
4087 if (is_constructor) {
4088 // If we invoked a constructor (which actually returns void), return the receiver,
4089 // unless we threw, in which case we return null.
Sebastien Hertza3e13772015-11-05 12:09:44 +01004090 DCHECK_EQ(JDWP::JT_VOID, result_tag);
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004091 if (exceptionObjectId == 0) {
4092 // TODO we could keep the receiver ObjectId in the DebugInvokeReq to avoid looking into the
4093 // object registry.
4094 result_value = GetObjectRegistry()->Add(pReq->receiver.Read());
Sebastien Hertza3e13772015-11-05 12:09:44 +01004095 result_tag = TagFromObject(soa, pReq->receiver.Read());
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004096 } else {
4097 result_value = 0;
Sebastien Hertza3e13772015-11-05 12:09:44 +01004098 result_tag = JDWP::JT_OBJECT;
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004099 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08004100 }
4101
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004102 // Suspend other threads if the invoke is not single-threaded.
4103 if ((pReq->options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07004104 ScopedThreadSuspension sts(soa.Self(), kWaitingForDebuggerSuspension);
Hiroshi Yamauchi8f95cf32016-04-19 11:14:06 -07004105 // Avoid a deadlock between GC and debugger where GC gets suspended during GC. b/25800335.
4106 gc::ScopedGCCriticalSection gcs(soa.Self(), gc::kGcCauseDebugger, gc::kCollectorTypeDebugger);
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004107 VLOG(jdwp) << " Suspending all threads";
4108 Runtime::Current()->GetThreadList()->SuspendAllForDebugger();
Sebastien Hertzcbc50642015-06-01 17:33:12 +02004109 }
4110
4111 VLOG(jdwp) << " --> returned " << result_tag
4112 << StringPrintf(" %#" PRIx64 " (except=%#" PRIx64 ")", result_value,
4113 exceptionObjectId);
4114
4115 // Show detailed debug output.
4116 if (result_tag == JDWP::JT_STRING && exceptionObjectId == 0) {
4117 if (result_value != 0) {
4118 if (VLOG_IS_ON(jdwp)) {
4119 std::string result_string;
4120 JDWP::JdwpError error = Dbg::StringToUtf8(result_value, &result_string);
4121 CHECK_EQ(error, JDWP::ERR_NONE);
4122 VLOG(jdwp) << " string '" << result_string << "'";
4123 }
4124 } else {
4125 VLOG(jdwp) << " string (null)";
4126 }
4127 }
4128
4129 // Attach the reply to DebugInvokeReq so it can be sent to the debugger when the event thread
4130 // is ready to suspend.
4131 BuildInvokeReply(pReq->reply, pReq->request_id, result_tag, result_value, exceptionObjectId);
4132}
4133
4134void Dbg::BuildInvokeReply(JDWP::ExpandBuf* pReply, uint32_t request_id, JDWP::JdwpTag result_tag,
4135 uint64_t result_value, JDWP::ObjectId exception) {
4136 // Make room for the JDWP header since we do not know the size of the reply yet.
4137 JDWP::expandBufAddSpace(pReply, kJDWPHeaderLen);
4138
4139 size_t width = GetTagWidth(result_tag);
4140 JDWP::expandBufAdd1(pReply, result_tag);
4141 if (width != 0) {
4142 WriteValue(pReply, width, result_value);
4143 }
4144 JDWP::expandBufAdd1(pReply, JDWP::JT_OBJECT);
4145 JDWP::expandBufAddObjectId(pReply, exception);
4146
4147 // Now we know the size, we can complete the JDWP header.
4148 uint8_t* buf = expandBufGetBuffer(pReply);
4149 JDWP::Set4BE(buf + kJDWPHeaderSizeOffset, expandBufGetLength(pReply));
4150 JDWP::Set4BE(buf + kJDWPHeaderIdOffset, request_id);
4151 JDWP::Set1(buf + kJDWPHeaderFlagsOffset, kJDWPFlagReply); // flags
4152 JDWP::Set2BE(buf + kJDWPHeaderErrorCodeOffset, JDWP::ERR_NONE);
4153}
4154
4155void Dbg::FinishInvokeMethod(DebugInvokeReq* pReq) {
4156 CHECK_NE(Thread::Current(), GetDebugThread()) << "This must be called by the event thread";
4157
4158 JDWP::ExpandBuf* const pReply = pReq->reply;
4159 CHECK(pReply != nullptr) << "No reply attached to DebugInvokeReq";
4160
4161 // We need to prevent other threads (including JDWP thread) from interacting with the debugger
4162 // while we send the reply but are not yet suspended. The JDWP token will be released just before
4163 // we suspend ourself again (see ThreadList::SuspendSelfForDebugger).
4164 gJdwpState->AcquireJdwpTokenForEvent(pReq->thread_id);
4165
4166 // Send the reply unless the debugger detached before the completion of the method.
4167 if (IsDebuggerActive()) {
4168 const size_t replyDataLength = expandBufGetLength(pReply) - kJDWPHeaderLen;
4169 VLOG(jdwp) << StringPrintf("REPLY INVOKE id=0x%06x (length=%zu)",
4170 pReq->request_id, replyDataLength);
4171
4172 gJdwpState->SendRequest(pReply);
4173 } else {
4174 VLOG(jdwp) << "Not sending invoke reply because debugger detached";
Elliott Hughesd07986f2011-12-06 18:27:45 -08004175 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004176}
4177
Elliott Hughesd07986f2011-12-06 18:27:45 -08004178/*
Elliott Hughes4b9702c2013-02-20 18:13:24 -08004179 * "request" contains a full JDWP packet, possibly with multiple chunks. We
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004180 * need to process each, accumulate the replies, and ship the whole thing
4181 * back.
4182 *
4183 * Returns "true" if we have a reply. The reply buffer is newly allocated,
4184 * and includes the chunk type/length, followed by the data.
4185 *
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08004186 * OLD-TODO: we currently assume that the request and reply include a single
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004187 * chunk. If this becomes inconvenient we will need to adapt.
4188 */
Ian Rogersc0542af2014-09-03 16:16:56 -07004189bool Dbg::DdmHandlePacket(JDWP::Request* request, uint8_t** pReplyBuf, int* pReplyLen) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004190 Thread* self = Thread::Current();
4191 JNIEnv* env = self->GetJniEnv();
4192
Ian Rogersc0542af2014-09-03 16:16:56 -07004193 uint32_t type = request->ReadUnsigned32("type");
4194 uint32_t length = request->ReadUnsigned32("length");
Elliott Hughes4b9702c2013-02-20 18:13:24 -08004195
4196 // Create a byte[] corresponding to 'request'.
Ian Rogersc0542af2014-09-03 16:16:56 -07004197 size_t request_length = request->size();
Elliott Hughes4b9702c2013-02-20 18:13:24 -08004198 ScopedLocalRef<jbyteArray> dataArray(env, env->NewByteArray(request_length));
Ian Rogersc0542af2014-09-03 16:16:56 -07004199 if (dataArray.get() == nullptr) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08004200 LOG(WARNING) << "byte[] allocation failed: " << request_length;
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004201 env->ExceptionClear();
4202 return false;
4203 }
Ian Rogersc0542af2014-09-03 16:16:56 -07004204 env->SetByteArrayRegion(dataArray.get(), 0, request_length,
4205 reinterpret_cast<const jbyte*>(request->data()));
4206 request->Skip(request_length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004207
4208 // Run through and find all chunks. [Currently just find the first.]
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004209 ScopedByteArrayRO contents(env, dataArray.get());
Elliott Hughes4b9702c2013-02-20 18:13:24 -08004210 if (length != request_length) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08004211 LOG(WARNING) << StringPrintf("bad chunk found (len=%u pktLen=%zd)", length, request_length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004212 return false;
4213 }
4214
4215 // Call "private static Chunk dispatch(int type, byte[] data, int offset, int length)".
Elliott Hugheseac76672012-05-24 21:56:51 -07004216 ScopedLocalRef<jobject> chunk(env, env->CallStaticObjectMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
4217 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_dispatch,
Elliott Hughes4b9702c2013-02-20 18:13:24 -08004218 type, dataArray.get(), 0, length));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004219 if (env->ExceptionCheck()) {
4220 LOG(INFO) << StringPrintf("Exception thrown by dispatcher for 0x%08x", type);
4221 env->ExceptionDescribe();
4222 env->ExceptionClear();
4223 return false;
4224 }
4225
Ian Rogersc0542af2014-09-03 16:16:56 -07004226 if (chunk.get() == nullptr) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004227 return false;
4228 }
4229
4230 /*
4231 * Pull the pieces out of the chunk. We copy the results into a
4232 * newly-allocated buffer that the caller can free. We don't want to
4233 * continue using the Chunk object because nothing has a reference to it.
4234 *
4235 * We could avoid this by returning type/data/offset/length and having
4236 * the caller be aware of the object lifetime issues, but that
Elliott Hughes81ff3182012-03-23 20:35:56 -07004237 * integrates the JDWP code more tightly into the rest of the runtime, and doesn't work
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004238 * if we have responses for multiple chunks.
4239 *
4240 * So we're pretty much stuck with copying data around multiple times.
4241 */
Elliott Hugheseac76672012-05-24 21:56:51 -07004242 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 -08004243 jint offset = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_offset);
Elliott Hugheseac76672012-05-24 21:56:51 -07004244 length = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_length);
Elliott Hugheseac76672012-05-24 21:56:51 -07004245 type = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_type);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004246
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08004247 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 -07004248 if (length == 0 || replyData.get() == nullptr) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004249 return false;
4250 }
4251
Elliott Hughes4b9702c2013-02-20 18:13:24 -08004252 const int kChunkHdrLen = 8;
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004253 uint8_t* reply = new uint8_t[length + kChunkHdrLen];
Ian Rogersc0542af2014-09-03 16:16:56 -07004254 if (reply == nullptr) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004255 LOG(WARNING) << "malloc failed: " << (length + kChunkHdrLen);
4256 return false;
4257 }
Elliott Hughesf7c3b662011-10-27 12:04:56 -07004258 JDWP::Set4BE(reply + 0, type);
4259 JDWP::Set4BE(reply + 4, length);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004260 env->GetByteArrayRegion(replyData.get(), offset, length, reinterpret_cast<jbyte*>(reply + kChunkHdrLen));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004261
4262 *pReplyBuf = reply;
4263 *pReplyLen = length + kChunkHdrLen;
4264
Elliott Hughes4b9702c2013-02-20 18:13:24 -08004265 VLOG(jdwp) << StringPrintf("dvmHandleDdm returning type=%.4s %p len=%d", reinterpret_cast<char*>(reply), reply, length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004266 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004267}
4268
Elliott Hughesa2155262011-11-16 16:26:58 -08004269void Dbg::DdmBroadcast(bool connect) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08004270 VLOG(jdwp) << "Broadcasting DDM " << (connect ? "connect" : "disconnect") << "...";
Elliott Hughes47fce012011-10-25 18:37:19 -07004271
4272 Thread* self = Thread::Current();
Ian Rogers50b35e22012-10-04 10:09:15 -07004273 if (self->GetState() != kRunnable) {
4274 LOG(ERROR) << "DDM broadcast in thread state " << self->GetState();
4275 /* try anyway? */
Elliott Hughes47fce012011-10-25 18:37:19 -07004276 }
4277
4278 JNIEnv* env = self->GetJniEnv();
Elliott Hughes47fce012011-10-25 18:37:19 -07004279 jint event = connect ? 1 /*DdmServer.CONNECTED*/ : 2 /*DdmServer.DISCONNECTED*/;
Elliott Hugheseac76672012-05-24 21:56:51 -07004280 env->CallStaticVoidMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
4281 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_broadcast,
4282 event);
Elliott Hughes47fce012011-10-25 18:37:19 -07004283 if (env->ExceptionCheck()) {
4284 LOG(ERROR) << "DdmServer.broadcast " << event << " failed";
4285 env->ExceptionDescribe();
4286 env->ExceptionClear();
4287 }
4288}
4289
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004290void Dbg::DdmConnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08004291 Dbg::DdmBroadcast(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004292}
4293
4294void Dbg::DdmDisconnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08004295 Dbg::DdmBroadcast(false);
Elliott Hughes47fce012011-10-25 18:37:19 -07004296 gDdmThreadNotification = false;
4297}
4298
4299/*
Elliott Hughes82188472011-11-07 18:11:48 -08004300 * Send a notification when a thread starts, stops, or changes its name.
Elliott Hughes47fce012011-10-25 18:37:19 -07004301 *
4302 * Because we broadcast the full set of threads when the notifications are
4303 * first enabled, it's possible for "thread" to be actively executing.
4304 */
Elliott Hughes82188472011-11-07 18:11:48 -08004305void Dbg::DdmSendThreadNotification(Thread* t, uint32_t type) {
Elliott Hughes47fce012011-10-25 18:37:19 -07004306 if (!gDdmThreadNotification) {
4307 return;
4308 }
4309
Elliott Hughes82188472011-11-07 18:11:48 -08004310 if (type == CHUNK_TYPE("THDE")) {
Elliott Hughes47fce012011-10-25 18:37:19 -07004311 uint8_t buf[4];
Ian Rogersd9c4fc92013-10-01 19:45:43 -07004312 JDWP::Set4BE(&buf[0], t->GetThreadId());
Elliott Hughes47fce012011-10-25 18:37:19 -07004313 Dbg::DdmSendChunk(CHUNK_TYPE("THDE"), 4, buf);
Elliott Hughes82188472011-11-07 18:11:48 -08004314 } else {
4315 CHECK(type == CHUNK_TYPE("THCR") || type == CHUNK_TYPE("THNM")) << type;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004316 ScopedObjectAccessUnchecked soa(Thread::Current());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004317 StackHandleScope<1> hs(soa.Self());
4318 Handle<mirror::String> name(hs.NewHandle(t->GetThreadName(soa)));
Ian Rogersc0542af2014-09-03 16:16:56 -07004319 size_t char_count = (name.Get() != nullptr) ? name->GetLength() : 0;
Jeff Hao848f70a2014-01-15 13:49:50 -08004320 const jchar* chars = (name.Get() != nullptr) ? name->GetValue() : nullptr;
Elliott Hughes82188472011-11-07 18:11:48 -08004321
Elliott Hughes21f32d72011-11-09 17:44:13 -08004322 std::vector<uint8_t> bytes;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07004323 JDWP::Append4BE(bytes, t->GetThreadId());
Elliott Hughes545a0642011-11-08 19:10:03 -08004324 JDWP::AppendUtf16BE(bytes, chars, char_count);
Elliott Hughes21f32d72011-11-09 17:44:13 -08004325 CHECK_EQ(bytes.size(), char_count*2 + sizeof(uint32_t)*2);
4326 Dbg::DdmSendChunk(type, bytes);
Elliott Hughes47fce012011-10-25 18:37:19 -07004327 }
4328}
4329
Elliott Hughes47fce012011-10-25 18:37:19 -07004330void Dbg::DdmSetThreadNotification(bool enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004331 // Enable/disable thread notifications.
Elliott Hughes47fce012011-10-25 18:37:19 -07004332 gDdmThreadNotification = enable;
4333 if (enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004334 // Suspend the VM then post thread start notifications for all threads. Threads attaching will
4335 // see a suspension in progress and block until that ends. They then post their own start
4336 // notification.
4337 SuspendVM();
4338 std::list<Thread*> threads;
Ian Rogers50b35e22012-10-04 10:09:15 -07004339 Thread* self = Thread::Current();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004340 {
Ian Rogers50b35e22012-10-04 10:09:15 -07004341 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004342 threads = Runtime::Current()->GetThreadList()->GetList();
4343 }
4344 {
Ian Rogers50b35e22012-10-04 10:09:15 -07004345 ScopedObjectAccess soa(self);
Mathieu Chartier02e25112013-08-14 16:14:24 -07004346 for (Thread* thread : threads) {
4347 Dbg::DdmSendThreadNotification(thread, CHUNK_TYPE("THCR"));
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004348 }
4349 }
4350 ResumeVM();
Elliott Hughes47fce012011-10-25 18:37:19 -07004351 }
4352}
4353
Elliott Hughesa2155262011-11-16 16:26:58 -08004354void Dbg::PostThreadStartOrStop(Thread* t, uint32_t type) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07004355 if (IsDebuggerActive()) {
Sebastien Hertz6995c602014-09-09 12:10:13 +02004356 gJdwpState->PostThreadChange(t, type == CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07004357 }
Elliott Hughes82188472011-11-07 18:11:48 -08004358 Dbg::DdmSendThreadNotification(t, type);
Elliott Hughes47fce012011-10-25 18:37:19 -07004359}
4360
4361void Dbg::PostThreadStart(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004362 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07004363}
4364
4365void Dbg::PostThreadDeath(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004366 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THDE"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004367}
4368
Elliott Hughes82188472011-11-07 18:11:48 -08004369void Dbg::DdmSendChunk(uint32_t type, size_t byte_count, const uint8_t* buf) {
Ian Rogersc0542af2014-09-03 16:16:56 -07004370 CHECK(buf != nullptr);
Elliott Hughes3bb81562011-10-21 18:52:59 -07004371 iovec vec[1];
4372 vec[0].iov_base = reinterpret_cast<void*>(const_cast<uint8_t*>(buf));
4373 vec[0].iov_len = byte_count;
4374 Dbg::DdmSendChunkV(type, vec, 1);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004375}
4376
Elliott Hughes21f32d72011-11-09 17:44:13 -08004377void Dbg::DdmSendChunk(uint32_t type, const std::vector<uint8_t>& bytes) {
4378 DdmSendChunk(type, bytes.size(), &bytes[0]);
4379}
4380
Brian Carlstromf5293522013-07-19 00:24:00 -07004381void Dbg::DdmSendChunkV(uint32_t type, const iovec* iov, int iov_count) {
Ian Rogersc0542af2014-09-03 16:16:56 -07004382 if (gJdwpState == nullptr) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08004383 VLOG(jdwp) << "Debugger thread not active, ignoring DDM send: " << type;
Elliott Hughes3bb81562011-10-21 18:52:59 -07004384 } else {
Elliott Hughescccd84f2011-12-05 16:51:54 -08004385 gJdwpState->DdmSendChunkV(type, iov, iov_count);
Elliott Hughes3bb81562011-10-21 18:52:59 -07004386 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004387}
4388
Mathieu Chartierad466ad2015-01-08 16:28:08 -08004389JDWP::JdwpState* Dbg::GetJdwpState() {
4390 return gJdwpState;
4391}
4392
Elliott Hughes767a1472011-10-26 18:49:02 -07004393int Dbg::DdmHandleHpifChunk(HpifWhen when) {
4394 if (when == HPIF_WHEN_NOW) {
Elliott Hughes7162ad92011-10-27 14:08:42 -07004395 DdmSendHeapInfo(when);
Elliott Hughes767a1472011-10-26 18:49:02 -07004396 return true;
4397 }
4398
4399 if (when != HPIF_WHEN_NEVER && when != HPIF_WHEN_NEXT_GC && when != HPIF_WHEN_EVERY_GC) {
4400 LOG(ERROR) << "invalid HpifWhen value: " << static_cast<int>(when);
4401 return false;
4402 }
4403
4404 gDdmHpifWhen = when;
4405 return true;
4406}
4407
4408bool Dbg::DdmHandleHpsgNhsgChunk(Dbg::HpsgWhen when, Dbg::HpsgWhat what, bool native) {
4409 if (when != HPSG_WHEN_NEVER && when != HPSG_WHEN_EVERY_GC) {
4410 LOG(ERROR) << "invalid HpsgWhen value: " << static_cast<int>(when);
4411 return false;
4412 }
4413
4414 if (what != HPSG_WHAT_MERGED_OBJECTS && what != HPSG_WHAT_DISTINCT_OBJECTS) {
4415 LOG(ERROR) << "invalid HpsgWhat value: " << static_cast<int>(what);
4416 return false;
4417 }
4418
4419 if (native) {
4420 gDdmNhsgWhen = when;
4421 gDdmNhsgWhat = what;
4422 } else {
4423 gDdmHpsgWhen = when;
4424 gDdmHpsgWhat = what;
4425 }
4426 return true;
4427}
4428
Elliott Hughes7162ad92011-10-27 14:08:42 -07004429void Dbg::DdmSendHeapInfo(HpifWhen reason) {
4430 // If there's a one-shot 'when', reset it.
4431 if (reason == gDdmHpifWhen) {
4432 if (gDdmHpifWhen == HPIF_WHEN_NEXT_GC) {
4433 gDdmHpifWhen = HPIF_WHEN_NEVER;
4434 }
4435 }
4436
4437 /*
4438 * Chunk HPIF (client --> server)
4439 *
4440 * Heap Info. General information about the heap,
4441 * suitable for a summary display.
4442 *
4443 * [u4]: number of heaps
4444 *
4445 * For each heap:
4446 * [u4]: heap ID
4447 * [u8]: timestamp in ms since Unix epoch
4448 * [u1]: capture reason (same as 'when' value from server)
4449 * [u4]: max heap size in bytes (-Xmx)
4450 * [u4]: current heap size in bytes
4451 * [u4]: current number of bytes allocated
4452 * [u4]: current number of objects allocated
4453 */
4454 uint8_t heap_count = 1;
Ian Rogers1d54e732013-05-02 21:10:01 -07004455 gc::Heap* heap = Runtime::Current()->GetHeap();
Elliott Hughes21f32d72011-11-09 17:44:13 -08004456 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08004457 JDWP::Append4BE(bytes, heap_count);
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004458 JDWP::Append4BE(bytes, 1); // Heap id (bogus; we only have one heap).
Elliott Hughes545a0642011-11-08 19:10:03 -08004459 JDWP::Append8BE(bytes, MilliTime());
4460 JDWP::Append1BE(bytes, reason);
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004461 JDWP::Append4BE(bytes, heap->GetMaxMemory()); // Max allowed heap size in bytes.
4462 JDWP::Append4BE(bytes, heap->GetTotalMemory()); // Current heap size in bytes.
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08004463 JDWP::Append4BE(bytes, heap->GetBytesAllocated());
4464 JDWP::Append4BE(bytes, heap->GetObjectsAllocated());
Elliott Hughes21f32d72011-11-09 17:44:13 -08004465 CHECK_EQ(bytes.size(), 4U + (heap_count * (4 + 8 + 1 + 4 + 4 + 4 + 4)));
4466 Dbg::DdmSendChunk(CHUNK_TYPE("HPIF"), bytes);
Elliott Hughes767a1472011-10-26 18:49:02 -07004467}
4468
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004469enum HpsgSolidity {
4470 SOLIDITY_FREE = 0,
4471 SOLIDITY_HARD = 1,
4472 SOLIDITY_SOFT = 2,
4473 SOLIDITY_WEAK = 3,
4474 SOLIDITY_PHANTOM = 4,
4475 SOLIDITY_FINALIZABLE = 5,
4476 SOLIDITY_SWEEP = 6,
4477};
4478
4479enum HpsgKind {
4480 KIND_OBJECT = 0,
4481 KIND_CLASS_OBJECT = 1,
4482 KIND_ARRAY_1 = 2,
4483 KIND_ARRAY_2 = 3,
4484 KIND_ARRAY_4 = 4,
4485 KIND_ARRAY_8 = 5,
4486 KIND_UNKNOWN = 6,
4487 KIND_NATIVE = 7,
4488};
4489
4490#define HPSG_PARTIAL (1<<7)
4491#define HPSG_STATE(solidity, kind) ((uint8_t)((((kind) & 0x7) << 3) | ((solidity) & 0x7)))
4492
Ian Rogers30fab402012-01-23 15:43:46 -08004493class HeapChunkContext {
4494 public:
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004495 // Maximum chunk size. Obtain this from the formula:
4496 // (((maximum_heap_size / ALLOCATION_UNIT_SIZE) + 255) / 256) * 2
4497 HeapChunkContext(bool merge, bool native)
Ian Rogers30fab402012-01-23 15:43:46 -08004498 : buf_(16384 - 16),
4499 type_(0),
Mathieu Chartier36dab362014-07-30 14:59:56 -07004500 chunk_overhead_(0) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004501 Reset();
4502 if (native) {
Ian Rogers30fab402012-01-23 15:43:46 -08004503 type_ = CHUNK_TYPE("NHSG");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004504 } else {
Ian Rogers30fab402012-01-23 15:43:46 -08004505 type_ = merge ? CHUNK_TYPE("HPSG") : CHUNK_TYPE("HPSO");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004506 }
4507 }
4508
4509 ~HeapChunkContext() {
Ian Rogers30fab402012-01-23 15:43:46 -08004510 if (p_ > &buf_[0]) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004511 Flush();
4512 }
4513 }
4514
Mathieu Chartier36dab362014-07-30 14:59:56 -07004515 void SetChunkOverhead(size_t chunk_overhead) {
4516 chunk_overhead_ = chunk_overhead;
4517 }
4518
4519 void ResetStartOfNextChunk() {
4520 startOfNextMemoryChunk_ = nullptr;
4521 }
4522
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004523 void EnsureHeader(const void* chunk_ptr) {
Ian Rogers30fab402012-01-23 15:43:46 -08004524 if (!needHeader_) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004525 return;
4526 }
4527
4528 // Start a new HPSx chunk.
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004529 JDWP::Write4BE(&p_, 1); // Heap id (bogus; we only have one heap).
4530 JDWP::Write1BE(&p_, 8); // Size of allocation unit, in bytes.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004531
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004532 JDWP::Write4BE(&p_, reinterpret_cast<uintptr_t>(chunk_ptr)); // virtual address of segment start.
4533 JDWP::Write4BE(&p_, 0); // offset of this piece (relative to the virtual address).
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004534 // [u4]: length of piece, in allocation units
4535 // 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 -08004536 pieceLenField_ = p_;
4537 JDWP::Write4BE(&p_, 0x55555555);
4538 needHeader_ = false;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004539 }
4540
Mathieu Chartier90443472015-07-16 20:32:27 -07004541 void Flush() SHARED_REQUIRES(Locks::mutator_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -07004542 if (pieceLenField_ == nullptr) {
Ian Rogersd636b062013-01-18 17:51:18 -08004543 // Flush immediately post Reset (maybe back-to-back Flush). Ignore.
4544 CHECK(needHeader_);
4545 return;
4546 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004547 // Patch the "length of piece" field.
Ian Rogers30fab402012-01-23 15:43:46 -08004548 CHECK_LE(&buf_[0], pieceLenField_);
4549 CHECK_LE(pieceLenField_, p_);
4550 JDWP::Set4BE(pieceLenField_, totalAllocationUnits_);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004551
Ian Rogers30fab402012-01-23 15:43:46 -08004552 Dbg::DdmSendChunk(type_, p_ - &buf_[0], &buf_[0]);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004553 Reset();
4554 }
4555
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004556 static void HeapChunkJavaCallback(void* start, void* end, size_t used_bytes, void* arg)
Mathieu Chartier90443472015-07-16 20:32:27 -07004557 SHARED_REQUIRES(Locks::heap_bitmap_lock_,
Ian Rogersb726dcb2012-09-05 08:57:23 -07004558 Locks::mutator_lock_) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004559 reinterpret_cast<HeapChunkContext*>(arg)->HeapChunkJavaCallback(start, end, used_bytes);
4560 }
4561
4562 static void HeapChunkNativeCallback(void* start, void* end, size_t used_bytes, void* arg)
Mathieu Chartier90443472015-07-16 20:32:27 -07004563 SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004564 reinterpret_cast<HeapChunkContext*>(arg)->HeapChunkNativeCallback(start, end, used_bytes);
Elliott Hughesa2155262011-11-16 16:26:58 -08004565 }
4566
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004567 private:
Elliott Hughesa2155262011-11-16 16:26:58 -08004568 enum { ALLOCATION_UNIT_SIZE = 8 };
4569
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004570 void Reset() {
Ian Rogers30fab402012-01-23 15:43:46 -08004571 p_ = &buf_[0];
Mathieu Chartier36dab362014-07-30 14:59:56 -07004572 ResetStartOfNextChunk();
Ian Rogers30fab402012-01-23 15:43:46 -08004573 totalAllocationUnits_ = 0;
4574 needHeader_ = true;
Ian Rogersc0542af2014-09-03 16:16:56 -07004575 pieceLenField_ = nullptr;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004576 }
4577
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004578 bool IsNative() const {
4579 return type_ == CHUNK_TYPE("NHSG");
4580 }
4581
4582 // Returns true if the object is not an empty chunk.
Mathieu Chartier90443472015-07-16 20:32:27 -07004583 bool ProcessRecord(void* start, size_t used_bytes) SHARED_REQUIRES(Locks::mutator_lock_) {
Ian Rogers30fab402012-01-23 15:43:46 -08004584 // Note: heap call backs cannot manipulate the heap upon which they are crawling, care is taken
4585 // in the following code not to allocate memory, by ensuring buf_ is of the correct size
Ian Rogers15bf2d32012-08-28 17:33:04 -07004586 if (used_bytes == 0) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004587 if (start == nullptr) {
4588 // Reset for start of new heap.
4589 startOfNextMemoryChunk_ = nullptr;
4590 Flush();
4591 }
4592 // Only process in use memory so that free region information
4593 // also includes dlmalloc book keeping.
4594 return false;
Elliott Hughesa2155262011-11-16 16:26:58 -08004595 }
Ian Rogersc0542af2014-09-03 16:16:56 -07004596 if (startOfNextMemoryChunk_ != nullptr) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004597 // Transmit any pending free memory. Native free memory of over kMaxFreeLen could be because
4598 // of the use of mmaps, so don't report. If not free memory then start a new segment.
4599 bool flush = true;
4600 if (start > startOfNextMemoryChunk_) {
4601 const size_t kMaxFreeLen = 2 * kPageSize;
4602 void* free_start = startOfNextMemoryChunk_;
4603 void* free_end = start;
4604 const size_t free_len =
4605 reinterpret_cast<uintptr_t>(free_end) - reinterpret_cast<uintptr_t>(free_start);
4606 if (!IsNative() || free_len < kMaxFreeLen) {
4607 AppendChunk(HPSG_STATE(SOLIDITY_FREE, 0), free_start, free_len, IsNative());
4608 flush = false;
Ian Rogers15bf2d32012-08-28 17:33:04 -07004609 }
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004610 }
4611 if (flush) {
4612 startOfNextMemoryChunk_ = nullptr;
4613 Flush();
4614 }
Ian Rogers15bf2d32012-08-28 17:33:04 -07004615 }
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004616 return true;
Ian Rogers15bf2d32012-08-28 17:33:04 -07004617 }
Elliott Hughesa2155262011-11-16 16:26:58 -08004618
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004619 void HeapChunkNativeCallback(void* start, void* /*end*/, size_t used_bytes)
Mathieu Chartier90443472015-07-16 20:32:27 -07004620 SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004621 if (ProcessRecord(start, used_bytes)) {
4622 uint8_t state = ExamineNativeObject(start);
4623 AppendChunk(state, start, used_bytes + chunk_overhead_, true /*is_native*/);
4624 startOfNextMemoryChunk_ = reinterpret_cast<char*>(start) + used_bytes + chunk_overhead_;
4625 }
4626 }
4627
4628 void HeapChunkJavaCallback(void* start, void* /*end*/, size_t used_bytes)
Mathieu Chartier90443472015-07-16 20:32:27 -07004629 SHARED_REQUIRES(Locks::heap_bitmap_lock_, Locks::mutator_lock_) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004630 if (ProcessRecord(start, used_bytes)) {
4631 // Determine the type of this chunk.
4632 // OLD-TODO: if context.merge, see if this chunk is different from the last chunk.
4633 // If it's the same, we should combine them.
4634 uint8_t state = ExamineJavaObject(reinterpret_cast<mirror::Object*>(start));
4635 AppendChunk(state, start, used_bytes + chunk_overhead_, false /*is_native*/);
4636 startOfNextMemoryChunk_ = reinterpret_cast<char*>(start) + used_bytes + chunk_overhead_;
4637 }
4638 }
4639
4640 void AppendChunk(uint8_t state, void* ptr, size_t length, bool is_native)
Mathieu Chartier90443472015-07-16 20:32:27 -07004641 SHARED_REQUIRES(Locks::mutator_lock_) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07004642 // Make sure there's enough room left in the buffer.
4643 // We need to use two bytes for every fractional 256 allocation units used by the chunk plus
4644 // 17 bytes for any header.
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004645 const size_t needed = ((RoundUp(length / ALLOCATION_UNIT_SIZE, 256) / 256) * 2) + 17;
4646 size_t byte_left = &buf_.back() - p_;
4647 if (byte_left < needed) {
4648 if (is_native) {
Pavel Vyssotski7522c742014-12-08 13:38:26 +06004649 // Cannot trigger memory allocation while walking native heap.
Pavel Vyssotski7522c742014-12-08 13:38:26 +06004650 return;
4651 }
Ian Rogers15bf2d32012-08-28 17:33:04 -07004652 Flush();
4653 }
4654
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004655 byte_left = &buf_.back() - p_;
4656 if (byte_left < needed) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07004657 LOG(WARNING) << "Chunk is too big to transmit (chunk_len=" << length << ", "
4658 << needed << " bytes)";
4659 return;
4660 }
4661 EnsureHeader(ptr);
Elliott Hughesa2155262011-11-16 16:26:58 -08004662 // Write out the chunk description.
Ian Rogers15bf2d32012-08-28 17:33:04 -07004663 length /= ALLOCATION_UNIT_SIZE; // Convert to allocation units.
4664 totalAllocationUnits_ += length;
4665 while (length > 256) {
Ian Rogers30fab402012-01-23 15:43:46 -08004666 *p_++ = state | HPSG_PARTIAL;
4667 *p_++ = 255; // length - 1
Ian Rogers15bf2d32012-08-28 17:33:04 -07004668 length -= 256;
Elliott Hughesa2155262011-11-16 16:26:58 -08004669 }
Ian Rogers30fab402012-01-23 15:43:46 -08004670 *p_++ = state;
Ian Rogers15bf2d32012-08-28 17:33:04 -07004671 *p_++ = length - 1;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004672 }
4673
Mathieu Chartier90443472015-07-16 20:32:27 -07004674 uint8_t ExamineNativeObject(const void* p) SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004675 return p == nullptr ? HPSG_STATE(SOLIDITY_FREE, 0) : HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
4676 }
4677
4678 uint8_t ExamineJavaObject(mirror::Object* o)
Mathieu Chartier90443472015-07-16 20:32:27 -07004679 SHARED_REQUIRES(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -07004680 if (o == nullptr) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004681 return HPSG_STATE(SOLIDITY_FREE, 0);
4682 }
Elliott Hughesa2155262011-11-16 16:26:58 -08004683 // It's an allocated chunk. Figure out what it is.
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004684 gc::Heap* heap = Runtime::Current()->GetHeap();
4685 if (!heap->IsLiveObjectLocked(o)) {
4686 LOG(ERROR) << "Invalid object in managed heap: " << o;
Elliott Hughesa2155262011-11-16 16:26:58 -08004687 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
4688 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004689 mirror::Class* c = o->GetClass();
Ian Rogersc0542af2014-09-03 16:16:56 -07004690 if (c == nullptr) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004691 // The object was probably just created but hasn't been initialized yet.
4692 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
4693 }
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004694 if (!heap->IsValidObjectAddress(c)) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07004695 LOG(ERROR) << "Invalid class for managed heap object: " << o << " " << c;
Elliott Hughesa2155262011-11-16 16:26:58 -08004696 return HPSG_STATE(SOLIDITY_HARD, KIND_UNKNOWN);
4697 }
Mathieu Chartierf26e1b32015-01-29 10:47:10 -08004698 if (c->GetClass() == nullptr) {
4699 LOG(ERROR) << "Null class of class " << c << " for object " << o;
4700 return HPSG_STATE(SOLIDITY_HARD, KIND_UNKNOWN);
4701 }
Elliott Hughesa2155262011-11-16 16:26:58 -08004702 if (c->IsClassClass()) {
4703 return HPSG_STATE(SOLIDITY_HARD, KIND_CLASS_OBJECT);
4704 }
Elliott Hughesa2155262011-11-16 16:26:58 -08004705 if (c->IsArrayClass()) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004706 switch (c->GetComponentSize()) {
4707 case 1: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_1);
4708 case 2: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_2);
4709 case 4: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
4710 case 8: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_8);
4711 }
4712 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004713 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
4714 }
4715
Ian Rogers30fab402012-01-23 15:43:46 -08004716 std::vector<uint8_t> buf_;
4717 uint8_t* p_;
4718 uint8_t* pieceLenField_;
Ian Rogers15bf2d32012-08-28 17:33:04 -07004719 void* startOfNextMemoryChunk_;
Ian Rogers30fab402012-01-23 15:43:46 -08004720 size_t totalAllocationUnits_;
4721 uint32_t type_;
Ian Rogers30fab402012-01-23 15:43:46 -08004722 bool needHeader_;
Mathieu Chartier36dab362014-07-30 14:59:56 -07004723 size_t chunk_overhead_;
Ian Rogers30fab402012-01-23 15:43:46 -08004724
Elliott Hughesa2155262011-11-16 16:26:58 -08004725 DISALLOW_COPY_AND_ASSIGN(HeapChunkContext);
4726};
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004727
Mathieu Chartier36dab362014-07-30 14:59:56 -07004728static void BumpPointerSpaceCallback(mirror::Object* obj, void* arg)
Mathieu Chartier90443472015-07-16 20:32:27 -07004729 SHARED_REQUIRES(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
Mathieu Chartier36dab362014-07-30 14:59:56 -07004730 const size_t size = RoundUp(obj->SizeOf(), kObjectAlignment);
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004731 HeapChunkContext::HeapChunkJavaCallback(
Mathieu Chartier36dab362014-07-30 14:59:56 -07004732 obj, reinterpret_cast<void*>(reinterpret_cast<uintptr_t>(obj) + size), size, arg);
4733}
4734
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004735void Dbg::DdmSendHeapSegments(bool native) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004736 Dbg::HpsgWhen when = native ? gDdmNhsgWhen : gDdmHpsgWhen;
4737 Dbg::HpsgWhat what = native ? gDdmNhsgWhat : gDdmHpsgWhat;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004738 if (when == HPSG_WHEN_NEVER) {
4739 return;
4740 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004741 // Figure out what kind of chunks we'll be sending.
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004742 CHECK(what == HPSG_WHAT_MERGED_OBJECTS || what == HPSG_WHAT_DISTINCT_OBJECTS)
4743 << static_cast<int>(what);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004744
4745 // First, send a heap start chunk.
4746 uint8_t heap_id[4];
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004747 JDWP::Set4BE(&heap_id[0], 1); // Heap id (bogus; we only have one heap).
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004748 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHST") : CHUNK_TYPE("HPST"), sizeof(heap_id), heap_id);
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07004749 Thread* self = Thread::Current();
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07004750 Locks::mutator_lock_->AssertSharedHeld(self);
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07004751
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004752 // Send a series of heap segment chunks.
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004753 HeapChunkContext context(what == HPSG_WHAT_MERGED_OBJECTS, native);
Elliott Hughesa2155262011-11-16 16:26:58 -08004754 if (native) {
Dimitry Ivanove6465bc2015-12-14 18:55:02 -08004755 UNIMPLEMENTED(WARNING) << "Native heap inspection is not supported";
Elliott Hughesa2155262011-11-16 16:26:58 -08004756 } else {
Ian Rogers1d54e732013-05-02 21:10:01 -07004757 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartier36dab362014-07-30 14:59:56 -07004758 for (const auto& space : heap->GetContinuousSpaces()) {
4759 if (space->IsDlMallocSpace()) {
Mathieu Chartier4c69d7f2014-10-10 12:45:50 -07004760 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004761 // dlmalloc's chunk header is 2 * sizeof(size_t), but if the previous chunk is in use for an
4762 // allocation then the first sizeof(size_t) may belong to it.
4763 context.SetChunkOverhead(sizeof(size_t));
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004764 space->AsDlMallocSpace()->Walk(HeapChunkContext::HeapChunkJavaCallback, &context);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004765 } else if (space->IsRosAllocSpace()) {
4766 context.SetChunkOverhead(0);
Mathieu Chartier4c69d7f2014-10-10 12:45:50 -07004767 // Need to acquire the mutator lock before the heap bitmap lock with exclusive access since
4768 // RosAlloc's internal logic doesn't know to release and reacquire the heap bitmap lock.
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07004769 ScopedThreadSuspension sts(self, kSuspended);
Mathieu Chartier4f55e222015-09-04 13:26:21 -07004770 ScopedSuspendAll ssa(__FUNCTION__);
4771 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
4772 space->AsRosAllocSpace()->Walk(HeapChunkContext::HeapChunkJavaCallback, &context);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004773 } else if (space->IsBumpPointerSpace()) {
Mathieu Chartier4c69d7f2014-10-10 12:45:50 -07004774 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004775 context.SetChunkOverhead(0);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004776 space->AsBumpPointerSpace()->Walk(BumpPointerSpaceCallback, &context);
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004777 HeapChunkContext::HeapChunkJavaCallback(nullptr, nullptr, 0, &context);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08004778 } else if (space->IsRegionSpace()) {
4779 heap->IncrementDisableMovingGC(self);
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07004780 {
4781 ScopedThreadSuspension sts(self, kSuspended);
Mathieu Chartier4f55e222015-09-04 13:26:21 -07004782 ScopedSuspendAll ssa(__FUNCTION__);
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07004783 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
4784 context.SetChunkOverhead(0);
4785 space->AsRegionSpace()->Walk(BumpPointerSpaceCallback, &context);
4786 HeapChunkContext::HeapChunkJavaCallback(nullptr, nullptr, 0, &context);
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07004787 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08004788 heap->DecrementDisableMovingGC(self);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004789 } else {
4790 UNIMPLEMENTED(WARNING) << "Not counting objects in space " << *space;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07004791 }
Mathieu Chartier36dab362014-07-30 14:59:56 -07004792 context.ResetStartOfNextChunk();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07004793 }
Mathieu Chartier4c69d7f2014-10-10 12:45:50 -07004794 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07004795 // Walk the large objects, these are not in the AllocSpace.
Mathieu Chartier36dab362014-07-30 14:59:56 -07004796 context.SetChunkOverhead(0);
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004797 heap->GetLargeObjectsSpace()->Walk(HeapChunkContext::HeapChunkJavaCallback, &context);
Elliott Hughesa2155262011-11-16 16:26:58 -08004798 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004799
4800 // Finally, send a heap end chunk.
4801 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHEN") : CHUNK_TYPE("HPEN"), sizeof(heap_id), heap_id);
Elliott Hughes767a1472011-10-26 18:49:02 -07004802}
4803
Brian Carlstrom306db812014-09-05 13:01:41 -07004804void Dbg::SetAllocTrackingEnabled(bool enable) {
Man Cao8c2ff642015-05-27 17:25:30 -07004805 gc::AllocRecordObjectMap::SetAllocTrackingEnabled(enable);
Elliott Hughes545a0642011-11-08 19:10:03 -08004806}
4807
4808void Dbg::DumpRecentAllocations() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004809 ScopedObjectAccess soa(Thread::Current());
Brian Carlstrom306db812014-09-05 13:01:41 -07004810 MutexLock mu(soa.Self(), *Locks::alloc_tracker_lock_);
Man Cao8c2ff642015-05-27 17:25:30 -07004811 if (!Runtime::Current()->GetHeap()->IsAllocTrackingEnabled()) {
Elliott Hughes545a0642011-11-08 19:10:03 -08004812 LOG(INFO) << "Not recording tracked allocations";
4813 return;
4814 }
Man Cao8c2ff642015-05-27 17:25:30 -07004815 gc::AllocRecordObjectMap* records = Runtime::Current()->GetHeap()->GetAllocationRecords();
4816 CHECK(records != nullptr);
Elliott Hughes545a0642011-11-08 19:10:03 -08004817
Man Cao1ed11b92015-06-11 22:47:35 -07004818 const uint16_t capped_count = CappedAllocRecordCount(records->GetRecentAllocationSize());
Brian Carlstrom306db812014-09-05 13:01:41 -07004819 uint16_t count = capped_count;
Elliott Hughes545a0642011-11-08 19:10:03 -08004820
Man Cao8c2ff642015-05-27 17:25:30 -07004821 LOG(INFO) << "Tracked allocations, (count=" << count << ")";
4822 for (auto it = records->RBegin(), end = records->REnd();
4823 count > 0 && it != end; count--, it++) {
Mathieu Chartier458b1052016-03-29 14:02:55 -07004824 const gc::AllocRecord* record = &it->second;
Elliott Hughes545a0642011-11-08 19:10:03 -08004825
Man Cao8c2ff642015-05-27 17:25:30 -07004826 LOG(INFO) << StringPrintf(" Thread %-2d %6zd bytes ", record->GetTid(), record->ByteCount())
Man Cao42c3c332015-06-23 16:38:25 -07004827 << PrettyClass(record->GetClass());
Elliott Hughes545a0642011-11-08 19:10:03 -08004828
Man Cao8c2ff642015-05-27 17:25:30 -07004829 for (size_t stack_frame = 0, depth = record->GetDepth(); stack_frame < depth; ++stack_frame) {
4830 const gc::AllocRecordStackTraceElement& stack_element = record->StackElement(stack_frame);
4831 ArtMethod* m = stack_element.GetMethod();
4832 LOG(INFO) << " " << PrettyMethod(m) << " line " << stack_element.ComputeLineNumber();
Elliott Hughes545a0642011-11-08 19:10:03 -08004833 }
4834
4835 // pause periodically to help logcat catch up
4836 if ((count % 5) == 0) {
4837 usleep(40000);
4838 }
Elliott Hughes545a0642011-11-08 19:10:03 -08004839 }
4840}
4841
4842class StringTable {
4843 public:
4844 StringTable() {
4845 }
4846
Mathieu Chartier4345c462014-06-27 10:20:14 -07004847 void Add(const std::string& str) {
4848 table_.insert(str);
4849 }
4850
4851 void Add(const char* str) {
4852 table_.insert(str);
Elliott Hughes545a0642011-11-08 19:10:03 -08004853 }
4854
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004855 size_t IndexOf(const char* s) const {
Mathieu Chartier02e25112013-08-14 16:14:24 -07004856 auto it = table_.find(s);
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004857 if (it == table_.end()) {
4858 LOG(FATAL) << "IndexOf(\"" << s << "\") failed";
4859 }
4860 return std::distance(table_.begin(), it);
Elliott Hughes545a0642011-11-08 19:10:03 -08004861 }
4862
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004863 size_t Size() const {
Elliott Hughes545a0642011-11-08 19:10:03 -08004864 return table_.size();
4865 }
4866
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004867 void WriteTo(std::vector<uint8_t>& bytes) const {
Mathieu Chartier02e25112013-08-14 16:14:24 -07004868 for (const std::string& str : table_) {
4869 const char* s = str.c_str();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004870 size_t s_len = CountModifiedUtf8Chars(s);
Christopher Ferris8a354052015-04-24 17:23:53 -07004871 std::unique_ptr<uint16_t[]> s_utf16(new uint16_t[s_len]);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004872 ConvertModifiedUtf8ToUtf16(s_utf16.get(), s);
4873 JDWP::AppendUtf16BE(bytes, s_utf16.get(), s_len);
Elliott Hughes545a0642011-11-08 19:10:03 -08004874 }
4875 }
4876
4877 private:
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004878 std::set<std::string> table_;
Elliott Hughes545a0642011-11-08 19:10:03 -08004879 DISALLOW_COPY_AND_ASSIGN(StringTable);
4880};
4881
Mathieu Chartiere401d142015-04-22 13:56:20 -07004882static const char* GetMethodSourceFile(ArtMethod* method)
Mathieu Chartier90443472015-07-16 20:32:27 -07004883 SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004884 DCHECK(method != nullptr);
4885 const char* source_file = method->GetDeclaringClassSourceFile();
Sebastien Hertz280286a2014-04-28 09:26:50 +02004886 return (source_file != nullptr) ? source_file : "";
4887}
4888
Elliott Hughes545a0642011-11-08 19:10:03 -08004889/*
4890 * The data we send to DDMS contains everything we have recorded.
4891 *
4892 * Message header (all values big-endian):
4893 * (1b) message header len (to allow future expansion); includes itself
4894 * (1b) entry header len
4895 * (1b) stack frame len
4896 * (2b) number of entries
4897 * (4b) offset to string table from start of message
4898 * (2b) number of class name strings
4899 * (2b) number of method name strings
4900 * (2b) number of source file name strings
4901 * For each entry:
4902 * (4b) total allocation size
Elliott Hughes221229c2013-01-08 18:17:50 -08004903 * (2b) thread id
Elliott Hughes545a0642011-11-08 19:10:03 -08004904 * (2b) allocated object's class name index
4905 * (1b) stack depth
4906 * For each stack frame:
4907 * (2b) method's class name
4908 * (2b) method name
4909 * (2b) method source file
4910 * (2b) line number, clipped to 32767; -2 if native; -1 if no source
4911 * (xb) class name strings
4912 * (xb) method name strings
4913 * (xb) source file strings
4914 *
4915 * As with other DDM traffic, strings are sent as a 4-byte length
4916 * followed by UTF-16 data.
4917 *
4918 * We send up 16-bit unsigned indexes into string tables. In theory there
Brian Carlstrom306db812014-09-05 13:01:41 -07004919 * can be (kMaxAllocRecordStackDepth * alloc_record_max_) unique strings in
Elliott Hughes545a0642011-11-08 19:10:03 -08004920 * each table, but in practice there should be far fewer.
4921 *
4922 * The chief reason for using a string table here is to keep the size of
4923 * the DDMS message to a minimum. This is partly to make the protocol
4924 * efficient, but also because we have to form the whole thing up all at
4925 * once in a memory buffer.
4926 *
4927 * We use separate string tables for class names, method names, and source
4928 * files to keep the indexes small. There will generally be no overlap
4929 * between the contents of these tables.
4930 */
4931jbyteArray Dbg::GetRecentAllocations() {
Ian Rogerscf7f1912014-10-22 22:06:39 -07004932 if ((false)) {
Elliott Hughes545a0642011-11-08 19:10:03 -08004933 DumpRecentAllocations();
4934 }
4935
Ian Rogers50b35e22012-10-04 10:09:15 -07004936 Thread* self = Thread::Current();
Elliott Hughes545a0642011-11-08 19:10:03 -08004937 std::vector<uint8_t> bytes;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004938 {
Brian Carlstrom306db812014-09-05 13:01:41 -07004939 MutexLock mu(self, *Locks::alloc_tracker_lock_);
Man Cao8c2ff642015-05-27 17:25:30 -07004940 gc::AllocRecordObjectMap* records = Runtime::Current()->GetHeap()->GetAllocationRecords();
4941 // In case this method is called when allocation tracker is disabled,
4942 // we should still send some data back.
4943 gc::AllocRecordObjectMap dummy;
4944 if (records == nullptr) {
4945 CHECK(!Runtime::Current()->GetHeap()->IsAllocTrackingEnabled());
4946 records = &dummy;
4947 }
Man Cao41656de2015-07-06 18:53:15 -07004948 // We don't need to wait on the condition variable records->new_record_condition_, because this
4949 // function only reads the class objects, which are already marked so it doesn't change their
4950 // reachability.
Man Cao8c2ff642015-05-27 17:25:30 -07004951
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004952 //
4953 // Part 1: generate string tables.
4954 //
4955 StringTable class_names;
4956 StringTable method_names;
4957 StringTable filenames;
Elliott Hughes545a0642011-11-08 19:10:03 -08004958
Man Cao1ed11b92015-06-11 22:47:35 -07004959 const uint16_t capped_count = CappedAllocRecordCount(records->GetRecentAllocationSize());
Brian Carlstrom306db812014-09-05 13:01:41 -07004960 uint16_t count = capped_count;
Man Cao8c2ff642015-05-27 17:25:30 -07004961 for (auto it = records->RBegin(), end = records->REnd();
4962 count > 0 && it != end; count--, it++) {
Mathieu Chartier458b1052016-03-29 14:02:55 -07004963 const gc::AllocRecord* record = &it->second;
Ian Rogers1ff3c982014-08-12 02:30:58 -07004964 std::string temp;
Man Cao41656de2015-07-06 18:53:15 -07004965 class_names.Add(record->GetClassDescriptor(&temp));
Man Cao8c2ff642015-05-27 17:25:30 -07004966 for (size_t i = 0, depth = record->GetDepth(); i < depth; i++) {
4967 ArtMethod* m = record->StackElement(i).GetMethod();
4968 class_names.Add(m->GetDeclaringClassDescriptor());
4969 method_names.Add(m->GetName());
4970 filenames.Add(GetMethodSourceFile(m));
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004971 }
Elliott Hughes545a0642011-11-08 19:10:03 -08004972 }
4973
Man Cao8c2ff642015-05-27 17:25:30 -07004974 LOG(INFO) << "recent allocation records: " << capped_count;
4975 LOG(INFO) << "allocation records all objects: " << records->Size();
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004976
4977 //
4978 // Part 2: Generate the output and store it in the buffer.
4979 //
4980
4981 // (1b) message header len (to allow future expansion); includes itself
4982 // (1b) entry header len
4983 // (1b) stack frame len
4984 const int kMessageHeaderLen = 15;
4985 const int kEntryHeaderLen = 9;
4986 const int kStackFrameLen = 8;
4987 JDWP::Append1BE(bytes, kMessageHeaderLen);
4988 JDWP::Append1BE(bytes, kEntryHeaderLen);
4989 JDWP::Append1BE(bytes, kStackFrameLen);
4990
4991 // (2b) number of entries
4992 // (4b) offset to string table from start of message
4993 // (2b) number of class name strings
4994 // (2b) number of method name strings
4995 // (2b) number of source file name strings
Brian Carlstrom306db812014-09-05 13:01:41 -07004996 JDWP::Append2BE(bytes, capped_count);
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004997 size_t string_table_offset = bytes.size();
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004998 JDWP::Append4BE(bytes, 0); // We'll patch this later...
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004999 JDWP::Append2BE(bytes, class_names.Size());
5000 JDWP::Append2BE(bytes, method_names.Size());
5001 JDWP::Append2BE(bytes, filenames.Size());
5002
Ian Rogers1ff3c982014-08-12 02:30:58 -07005003 std::string temp;
Man Cao8c2ff642015-05-27 17:25:30 -07005004 count = capped_count;
5005 // The last "count" number of allocation records in "records" are the most recent "count" number
5006 // of allocations. Reverse iterate to get them. The most recent allocation is sent first.
5007 for (auto it = records->RBegin(), end = records->REnd();
5008 count > 0 && it != end; count--, it++) {
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005009 // For each entry:
5010 // (4b) total allocation size
5011 // (2b) thread id
5012 // (2b) allocated object's class name index
5013 // (1b) stack depth
Mathieu Chartier458b1052016-03-29 14:02:55 -07005014 const gc::AllocRecord* record = &it->second;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005015 size_t stack_depth = record->GetDepth();
Mathieu Chartierf8322842014-05-16 10:59:25 -07005016 size_t allocated_object_class_name_index =
Man Cao41656de2015-07-06 18:53:15 -07005017 class_names.IndexOf(record->GetClassDescriptor(&temp));
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07005018 JDWP::Append4BE(bytes, record->ByteCount());
Man Cao8c2ff642015-05-27 17:25:30 -07005019 JDWP::Append2BE(bytes, static_cast<uint16_t>(record->GetTid()));
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005020 JDWP::Append2BE(bytes, allocated_object_class_name_index);
5021 JDWP::Append1BE(bytes, stack_depth);
5022
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005023 for (size_t stack_frame = 0; stack_frame < stack_depth; ++stack_frame) {
5024 // For each stack frame:
5025 // (2b) method's class name
5026 // (2b) method name
5027 // (2b) method source file
5028 // (2b) line number, clipped to 32767; -2 if native; -1 if no source
Man Cao8c2ff642015-05-27 17:25:30 -07005029 ArtMethod* m = record->StackElement(stack_frame).GetMethod();
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07005030 size_t class_name_index = class_names.IndexOf(m->GetDeclaringClassDescriptor());
5031 size_t method_name_index = method_names.IndexOf(m->GetName());
5032 size_t file_name_index = filenames.IndexOf(GetMethodSourceFile(m));
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005033 JDWP::Append2BE(bytes, class_name_index);
5034 JDWP::Append2BE(bytes, method_name_index);
5035 JDWP::Append2BE(bytes, file_name_index);
Man Cao8c2ff642015-05-27 17:25:30 -07005036 JDWP::Append2BE(bytes, record->StackElement(stack_frame).ComputeLineNumber());
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005037 }
Mathieu Chartier46e811b2013-07-10 17:09:14 -07005038 }
5039
5040 // (xb) class name strings
5041 // (xb) method name strings
5042 // (xb) source file strings
5043 JDWP::Set4BE(&bytes[string_table_offset], bytes.size());
5044 class_names.WriteTo(bytes);
5045 method_names.WriteTo(bytes);
5046 filenames.WriteTo(bytes);
Elliott Hughes545a0642011-11-08 19:10:03 -08005047 }
Ian Rogers50b35e22012-10-04 10:09:15 -07005048 JNIEnv* env = self->GetJniEnv();
Elliott Hughes545a0642011-11-08 19:10:03 -08005049 jbyteArray result = env->NewByteArray(bytes.size());
Ian Rogersc0542af2014-09-03 16:16:56 -07005050 if (result != nullptr) {
Elliott Hughes545a0642011-11-08 19:10:03 -08005051 env->SetByteArrayRegion(result, 0, bytes.size(), reinterpret_cast<const jbyte*>(&bytes[0]));
5052 }
5053 return result;
5054}
5055
Mathieu Chartiere401d142015-04-22 13:56:20 -07005056ArtMethod* DeoptimizationRequest::Method() const {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07005057 ScopedObjectAccessUnchecked soa(Thread::Current());
5058 return soa.DecodeMethod(method_);
5059}
5060
Mathieu Chartiere401d142015-04-22 13:56:20 -07005061void DeoptimizationRequest::SetMethod(ArtMethod* m) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07005062 ScopedObjectAccessUnchecked soa(Thread::Current());
5063 method_ = soa.EncodeMethod(m);
5064}
5065
Mathieu Chartiera6b1ead2015-10-06 10:32:38 -07005066void Dbg::VisitRoots(RootVisitor* visitor) {
5067 // Visit breakpoint roots, used to prevent unloading of methods with breakpoints.
5068 ReaderMutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
5069 BufferedRootVisitor<128> root_visitor(visitor, RootInfo(kRootVMInternal));
5070 for (Breakpoint& breakpoint : gBreakpoints) {
5071 breakpoint.Method()->VisitRoots(root_visitor, sizeof(void*));
5072 }
5073}
5074
Elliott Hughes872d4ec2011-10-21 17:07:15 -07005075} // namespace art