blob: 3c75daf7b01936feac5cc4f8419f2df58965f205 [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"
Ian Rogers1d54e732013-05-02 21:10:01 -070031#include "gc/accounting/card_table-inl.h"
Man Cao8c2ff642015-05-27 17:25:30 -070032#include "gc/allocation_record.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070033#include "gc/space/large_object_space.h"
34#include "gc/space/space-inl.h"
Mathieu Chartiereb8167a2014-05-07 15:43:14 -070035#include "handle_scope.h"
Elliott Hughes64f574f2013-02-20 14:57:12 -080036#include "jdwp/object_registry.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080037#include "mirror/class.h"
38#include "mirror/class-inl.h"
39#include "mirror/class_loader.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080040#include "mirror/object-inl.h"
41#include "mirror/object_array-inl.h"
Ian Rogersb0fa5dc2014-04-28 16:47:08 -070042#include "mirror/string-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080043#include "mirror/throwable.h"
Sebastien Hertza76a6d42014-03-20 16:40:17 +010044#include "quick/inline_method_analyser.h"
Ian Rogers53b8b092014-03-13 23:45:53 -070045#include "reflection.h"
Elliott Hughesa0e18062012-04-13 15:59:59 -070046#include "safe_map.h"
Elliott Hughes64f574f2013-02-20 14:57:12 -080047#include "scoped_thread_state_change.h"
Elliott Hughes6a5bd492011-10-28 14:33:57 -070048#include "ScopedLocalRef.h"
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -070049#include "ScopedPrimitiveArray.h"
Mathieu Chartiereb8167a2014-05-07 15:43:14 -070050#include "handle_scope-inl.h"
Elliott Hughes475fc232011-10-25 15:00:35 -070051#include "thread_list.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080052#include "utf.h"
Sebastien Hertza76a6d42014-03-20 16:40:17 +010053#include "verifier/method_verifier-inl.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070054#include "well_known_classes.h"
Elliott Hughes475fc232011-10-25 15:00:35 -070055
Brian Carlstrom3d92d522013-07-12 09:03:08 -070056#ifdef HAVE_ANDROID_OS
57#include "cutils/properties.h"
58#endif
59
Elliott Hughes872d4ec2011-10-21 17:07:15 -070060namespace art {
61
Sebastien Hertz0462c4c2015-04-01 16:34:17 +020062// The key identifying the debugger to update instrumentation.
63static constexpr const char* kDbgInstrumentationKey = "Debugger";
64
Man Cao8c2ff642015-05-27 17:25:30 -070065// Limit alloc_record_count to the 2BE value (64k-1) that is the limit of the current protocol.
Brian Carlstrom306db812014-09-05 13:01:41 -070066static uint16_t CappedAllocRecordCount(size_t alloc_record_count) {
Man Cao8c2ff642015-05-27 17:25:30 -070067 size_t cap = 0xffff;
68#ifdef HAVE_ANDROID_OS
69 // Check whether there's a system property overriding the number of recent records.
70 const char* propertyName = "dalvik.vm.recentAllocMax";
71 char recentAllocMaxString[PROPERTY_VALUE_MAX];
72 if (property_get(propertyName, recentAllocMaxString, "") > 0) {
73 char* end;
74 size_t value = strtoul(recentAllocMaxString, &end, 10);
75 if (*end != '\0') {
76 LOG(ERROR) << "Ignoring " << propertyName << " '" << recentAllocMaxString
77 << "' --- invalid";
78 } else {
79 cap = value;
80 }
81 }
82#endif
83 if (alloc_record_count > cap) {
84 return cap;
Brian Carlstrom306db812014-09-05 13:01:41 -070085 }
86 return alloc_record_count;
87}
Elliott Hughes475fc232011-10-25 15:00:35 -070088
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -070089class Breakpoint {
90 public:
Mathieu Chartiere401d142015-04-22 13:56:20 -070091 Breakpoint(ArtMethod* method, uint32_t dex_pc,
Sebastien Hertzf3928792014-11-17 19:00:37 +010092 DeoptimizationRequest::Kind deoptimization_kind)
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -070093 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Sebastien Hertzf3928792014-11-17 19:00:37 +010094 : method_(nullptr), dex_pc_(dex_pc), deoptimization_kind_(deoptimization_kind) {
95 CHECK(deoptimization_kind_ == DeoptimizationRequest::kNothing ||
96 deoptimization_kind_ == DeoptimizationRequest::kSelectiveDeoptimization ||
97 deoptimization_kind_ == DeoptimizationRequest::kFullDeoptimization);
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -070098 ScopedObjectAccessUnchecked soa(Thread::Current());
99 method_ = soa.EncodeMethod(method);
100 }
101
102 Breakpoint(const Breakpoint& other) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
103 : method_(nullptr), dex_pc_(other.dex_pc_),
Sebastien Hertzf3928792014-11-17 19:00:37 +0100104 deoptimization_kind_(other.deoptimization_kind_) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700105 ScopedObjectAccessUnchecked soa(Thread::Current());
106 method_ = soa.EncodeMethod(other.Method());
107 }
108
Mathieu Chartiere401d142015-04-22 13:56:20 -0700109 ArtMethod* Method() const SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700110 ScopedObjectAccessUnchecked soa(Thread::Current());
111 return soa.DecodeMethod(method_);
112 }
113
114 uint32_t DexPc() const {
115 return dex_pc_;
116 }
117
Sebastien Hertzf3928792014-11-17 19:00:37 +0100118 DeoptimizationRequest::Kind GetDeoptimizationKind() const {
119 return deoptimization_kind_;
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700120 }
121
122 private:
Sebastien Hertza76a6d42014-03-20 16:40:17 +0100123 // The location of this breakpoint.
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700124 jmethodID method_;
125 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)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700132 SHARED_LOCKS_REQUIRED(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)
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200144 OVERRIDE SHARED_LOCKS_REQUIRED(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)
170 OVERRIDE SHARED_LOCKS_REQUIRED(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)
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200187 OVERRIDE SHARED_LOCKS_REQUIRED(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)
195 OVERRIDE SHARED_LOCKS_REQUIRED(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)
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200216 OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
217 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)
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200223 OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
224 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)
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200228 OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Nicolas Geoffray14691c52015-03-05 10:40:17 +0000229 Dbg::PostException(exception_object);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200230 }
231
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800232 // We only care about how many backward branches were executed in the Jit.
Mathieu Chartiere401d142015-04-22 13:56:20 -0700233 void BackwardBranch(Thread* /*thread*/, ArtMethod* method, int32_t dex_pc_offset)
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800234 OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
235 LOG(ERROR) << "Unexpected backward branch event in debugger " << PrettyMethod(method)
236 << " " << dex_pc_offset;
237 }
238
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200239 private:
Mathieu Chartiere401d142015-04-22 13:56:20 -0700240 static bool IsReturn(ArtMethod* method, uint32_t dex_pc)
Sebastien Hertz9d6bf692015-04-10 12:12:33 +0200241 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
242 const DexFile::CodeItem* code_item = method->GetCodeItem();
243 const Instruction* instruction = Instruction::At(&code_item->insns_[dex_pc]);
244 return instruction->IsReturn();
245 }
246
247 static bool IsListeningToDexPcMoved() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
248 return IsListeningTo(instrumentation::Instrumentation::kDexPcMoved);
249 }
250
251 static bool IsListeningToMethodExit() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
252 return IsListeningTo(instrumentation::Instrumentation::kMethodExited);
253 }
254
255 static bool IsListeningTo(instrumentation::Instrumentation::InstrumentationEvent event)
256 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
257 return (Dbg::GetInstrumentationEvents() & event) != 0;
258 }
259
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200260 DISALLOW_COPY_AND_ASSIGN(DebugInstrumentationListener);
Ian Rogers62d6c772013-02-27 08:32:07 -0800261} gDebugInstrumentationListener;
262
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700263// JDWP is allowed unless the Zygote forbids it.
264static bool gJdwpAllowed = true;
265
Elliott Hughesc0f09332012-03-26 13:27:06 -0700266// Was there a -Xrunjdwp or -agentlib:jdwp= argument on the command line?
Elliott Hughes3bb81562011-10-21 18:52:59 -0700267static bool gJdwpConfigured = false;
268
Sebastien Hertzb3b173b2015-02-06 09:16:32 +0100269// JDWP options for debugging. Only valid if IsJdwpConfigured() is true.
270static JDWP::JdwpOptions gJdwpOptions;
271
Elliott Hughes3bb81562011-10-21 18:52:59 -0700272// Runtime JDWP state.
Ian Rogersc0542af2014-09-03 16:16:56 -0700273static JDWP::JdwpState* gJdwpState = nullptr;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700274static bool gDebuggerConnected; // debugger or DDMS is connected.
Elliott Hughes3bb81562011-10-21 18:52:59 -0700275
Elliott Hughes47fce012011-10-25 18:37:19 -0700276static bool gDdmThreadNotification = false;
277
Elliott Hughes767a1472011-10-26 18:49:02 -0700278// DDMS GC-related settings.
279static Dbg::HpifWhen gDdmHpifWhen = Dbg::HPIF_WHEN_NEVER;
280static Dbg::HpsgWhen gDdmHpsgWhen = Dbg::HPSG_WHEN_NEVER;
281static Dbg::HpsgWhat gDdmHpsgWhat;
282static Dbg::HpsgWhen gDdmNhsgWhen = Dbg::HPSG_WHEN_NEVER;
283static Dbg::HpsgWhat gDdmNhsgWhat;
284
Daniel Mihalyieb076692014-08-22 17:33:31 +0200285bool Dbg::gDebuggerActive = false;
Sebastien Hertz4e5b2082015-03-24 19:03:40 +0100286bool Dbg::gDisposed = false;
Sebastien Hertz6995c602014-09-09 12:10:13 +0200287ObjectRegistry* Dbg::gRegistry = nullptr;
Elliott Hughes475fc232011-10-25 15:00:35 -0700288
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100289// Deoptimization support.
Sebastien Hertz4d25df32014-03-21 17:44:46 +0100290std::vector<DeoptimizationRequest> Dbg::deoptimization_requests_;
291size_t Dbg::full_deoptimization_event_count_ = 0;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100292
Sebastien Hertz42cd43f2014-05-13 14:15:41 +0200293// Instrumentation event reference counters.
294size_t Dbg::dex_pc_change_event_ref_count_ = 0;
295size_t Dbg::method_enter_event_ref_count_ = 0;
296size_t Dbg::method_exit_event_ref_count_ = 0;
297size_t Dbg::field_read_event_ref_count_ = 0;
298size_t Dbg::field_write_event_ref_count_ = 0;
299size_t Dbg::exception_catch_event_ref_count_ = 0;
300uint32_t Dbg::instrumentation_events_ = 0;
301
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100302// Breakpoints.
jeffhao09bfc6a2012-12-11 18:11:43 -0800303static std::vector<Breakpoint> gBreakpoints GUARDED_BY(Locks::breakpoint_lock_);
Elliott Hughes86964332012-02-15 19:37:42 -0800304
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700305void DebugInvokeReq::VisitRoots(RootVisitor* visitor, const RootInfo& root_info) {
306 receiver.VisitRootIfNonNull(visitor, root_info); // null for static method call.
307 klass.VisitRoot(visitor, root_info);
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700308}
309
Sebastien Hertz597c4f02015-01-26 17:37:14 +0100310void SingleStepControl::AddDexPc(uint32_t dex_pc) {
311 dex_pcs_.insert(dex_pc);
Sebastien Hertzbb43b432014-04-14 11:59:08 +0200312}
313
Sebastien Hertz597c4f02015-01-26 17:37:14 +0100314bool SingleStepControl::ContainsDexPc(uint32_t dex_pc) const {
315 return dex_pcs_.find(dex_pc) == dex_pcs_.end();
Sebastien Hertzbb43b432014-04-14 11:59:08 +0200316}
317
Mathieu Chartiere401d142015-04-22 13:56:20 -0700318static bool IsBreakpoint(const ArtMethod* m, uint32_t dex_pc)
jeffhao09bfc6a2012-12-11 18:11:43 -0800319 LOCKS_EXCLUDED(Locks::breakpoint_lock_)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700320 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Sebastien Hertzed2be172014-08-19 15:33:43 +0200321 ReaderMutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100322 for (size_t i = 0, e = gBreakpoints.size(); i < e; ++i) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -0700323 if (gBreakpoints[i].DexPc() == dex_pc && gBreakpoints[i].Method() == m) {
Elliott Hughes86964332012-02-15 19:37:42 -0800324 VLOG(jdwp) << "Hit breakpoint #" << i << ": " << gBreakpoints[i];
325 return true;
326 }
327 }
328 return false;
329}
330
Sebastien Hertz52d131d2014-03-13 16:17:40 +0100331static bool IsSuspendedForDebugger(ScopedObjectAccessUnchecked& soa, Thread* thread)
332 LOCKS_EXCLUDED(Locks::thread_suspend_count_lock_) {
Elliott Hughes9e0c1752013-01-09 14:02:58 -0800333 MutexLock mu(soa.Self(), *Locks::thread_suspend_count_lock_);
334 // A thread may be suspended for GC; in this code, we really want to know whether
335 // there's a debugger suspension active.
336 return thread->IsSuspended() && thread->GetDebugSuspendCount() > 0;
337}
338
Ian Rogersc0542af2014-09-03 16:16:56 -0700339static mirror::Array* DecodeNonNullArray(JDWP::RefTypeId id, JDWP::JdwpError* error)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700340 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Sebastien Hertz6995c602014-09-09 12:10:13 +0200341 mirror::Object* o = Dbg::GetObjectRegistry()->Get<mirror::Object*>(id, error);
Ian Rogersc0542af2014-09-03 16:16:56 -0700342 if (o == nullptr) {
343 *error = JDWP::ERR_INVALID_OBJECT;
344 return nullptr;
Elliott Hughes436e3722012-02-17 20:01:47 -0800345 }
346 if (!o->IsArrayInstance()) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700347 *error = JDWP::ERR_INVALID_ARRAY;
348 return nullptr;
Elliott Hughes436e3722012-02-17 20:01:47 -0800349 }
Ian Rogersc0542af2014-09-03 16:16:56 -0700350 *error = JDWP::ERR_NONE;
Elliott Hughes436e3722012-02-17 20:01:47 -0800351 return o->AsArray();
352}
353
Ian Rogersc0542af2014-09-03 16:16:56 -0700354static mirror::Class* DecodeClass(JDWP::RefTypeId id, JDWP::JdwpError* error)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700355 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Sebastien Hertz6995c602014-09-09 12:10:13 +0200356 mirror::Object* o = Dbg::GetObjectRegistry()->Get<mirror::Object*>(id, error);
Ian Rogersc0542af2014-09-03 16:16:56 -0700357 if (o == nullptr) {
358 *error = JDWP::ERR_INVALID_OBJECT;
359 return nullptr;
Elliott Hughes436e3722012-02-17 20:01:47 -0800360 }
361 if (!o->IsClass()) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700362 *error = JDWP::ERR_INVALID_CLASS;
363 return nullptr;
Elliott Hughes436e3722012-02-17 20:01:47 -0800364 }
Ian Rogersc0542af2014-09-03 16:16:56 -0700365 *error = JDWP::ERR_NONE;
Elliott Hughes436e3722012-02-17 20:01:47 -0800366 return o->AsClass();
367}
368
Ian Rogersc0542af2014-09-03 16:16:56 -0700369static Thread* DecodeThread(ScopedObjectAccessUnchecked& soa, JDWP::ObjectId thread_id,
370 JDWP::JdwpError* error)
Sebastien Hertz69206392015-04-07 15:54:25 +0200371 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
372 LOCKS_EXCLUDED(Locks::thread_list_lock_, Locks::thread_suspend_count_lock_) {
Sebastien Hertz6995c602014-09-09 12:10:13 +0200373 mirror::Object* thread_peer = Dbg::GetObjectRegistry()->Get<mirror::Object*>(thread_id, error);
Ian Rogersc0542af2014-09-03 16:16:56 -0700374 if (thread_peer == nullptr) {
Elliott Hughes221229c2013-01-08 18:17:50 -0800375 // This isn't even an object.
Ian Rogersc0542af2014-09-03 16:16:56 -0700376 *error = JDWP::ERR_INVALID_OBJECT;
377 return nullptr;
Elliott Hughes436e3722012-02-17 20:01:47 -0800378 }
Elliott Hughes221229c2013-01-08 18:17:50 -0800379
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800380 mirror::Class* java_lang_Thread = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_Thread);
Elliott Hughes221229c2013-01-08 18:17:50 -0800381 if (!java_lang_Thread->IsAssignableFrom(thread_peer->GetClass())) {
382 // This isn't a thread.
Ian Rogersc0542af2014-09-03 16:16:56 -0700383 *error = JDWP::ERR_INVALID_THREAD;
384 return nullptr;
Elliott Hughes221229c2013-01-08 18:17:50 -0800385 }
386
Sebastien Hertz69206392015-04-07 15:54:25 +0200387 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogersc0542af2014-09-03 16:16:56 -0700388 Thread* thread = Thread::FromManagedThread(soa, thread_peer);
389 // If thread is null then this a java.lang.Thread without a Thread*. Must be a un-started or a
390 // zombie.
391 *error = (thread == nullptr) ? JDWP::ERR_THREAD_NOT_ALIVE : JDWP::ERR_NONE;
392 return thread;
Elliott Hughes436e3722012-02-17 20:01:47 -0800393}
394
Elliott Hughes24437992011-11-30 14:49:33 -0800395static JDWP::JdwpTag BasicTagFromDescriptor(const char* descriptor) {
396 // JDWP deliberately uses the descriptor characters' ASCII values for its enum.
397 // Note that by "basic" we mean that we don't get more specific than JT_OBJECT.
398 return static_cast<JDWP::JdwpTag>(descriptor[0]);
399}
400
Ian Rogers1ff3c982014-08-12 02:30:58 -0700401static JDWP::JdwpTag BasicTagFromClass(mirror::Class* klass)
402 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
403 std::string temp;
404 const char* descriptor = klass->GetDescriptor(&temp);
405 return BasicTagFromDescriptor(descriptor);
406}
407
Ian Rogers98379392014-02-24 16:53:16 -0800408static JDWP::JdwpTag TagFromClass(const ScopedObjectAccessUnchecked& soa, mirror::Class* c)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700409 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700410 CHECK(c != nullptr);
Elliott Hughes24437992011-11-30 14:49:33 -0800411 if (c->IsArrayClass()) {
412 return JDWP::JT_ARRAY;
413 }
Elliott Hughes24437992011-11-30 14:49:33 -0800414 if (c->IsStringClass()) {
415 return JDWP::JT_STRING;
Elliott Hughes24437992011-11-30 14:49:33 -0800416 }
Ian Rogers98379392014-02-24 16:53:16 -0800417 if (c->IsClassClass()) {
418 return JDWP::JT_CLASS_OBJECT;
419 }
420 {
421 mirror::Class* thread_class = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_Thread);
422 if (thread_class->IsAssignableFrom(c)) {
423 return JDWP::JT_THREAD;
424 }
425 }
426 {
427 mirror::Class* thread_group_class =
428 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_ThreadGroup);
429 if (thread_group_class->IsAssignableFrom(c)) {
430 return JDWP::JT_THREAD_GROUP;
431 }
432 }
433 {
434 mirror::Class* class_loader_class =
435 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_ClassLoader);
436 if (class_loader_class->IsAssignableFrom(c)) {
437 return JDWP::JT_CLASS_LOADER;
438 }
439 }
440 return JDWP::JT_OBJECT;
Elliott Hughes24437992011-11-30 14:49:33 -0800441}
442
443/*
444 * Objects declared to hold Object might actually hold a more specific
445 * type. The debugger may take a special interest in these (e.g. it
446 * wants to display the contents of Strings), so we want to return an
447 * appropriate tag.
448 *
449 * Null objects are tagged JT_OBJECT.
450 */
Sebastien Hertz6995c602014-09-09 12:10:13 +0200451JDWP::JdwpTag Dbg::TagFromObject(const ScopedObjectAccessUnchecked& soa, mirror::Object* o) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700452 return (o == nullptr) ? JDWP::JT_OBJECT : TagFromClass(soa, o->GetClass());
Elliott Hughes24437992011-11-30 14:49:33 -0800453}
454
455static bool IsPrimitiveTag(JDWP::JdwpTag tag) {
456 switch (tag) {
457 case JDWP::JT_BOOLEAN:
458 case JDWP::JT_BYTE:
459 case JDWP::JT_CHAR:
460 case JDWP::JT_FLOAT:
461 case JDWP::JT_DOUBLE:
462 case JDWP::JT_INT:
463 case JDWP::JT_LONG:
464 case JDWP::JT_SHORT:
465 case JDWP::JT_VOID:
466 return true;
467 default:
468 return false;
469 }
470}
471
Sebastien Hertzb3b173b2015-02-06 09:16:32 +0100472void Dbg::StartJdwp() {
Elliott Hughesc0f09332012-03-26 13:27:06 -0700473 if (!gJdwpAllowed || !IsJdwpConfigured()) {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700474 // No JDWP for you!
475 return;
476 }
477
Ian Rogers719d1a32014-03-06 12:13:39 -0800478 CHECK(gRegistry == nullptr);
Elliott Hughes475fc232011-10-25 15:00:35 -0700479 gRegistry = new ObjectRegistry;
480
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700481 // Init JDWP if the debugger is enabled. This may connect out to a
482 // debugger, passively listen for a debugger, or block waiting for a
483 // debugger.
Sebastien Hertzb3b173b2015-02-06 09:16:32 +0100484 gJdwpState = JDWP::JdwpState::Create(&gJdwpOptions);
Ian Rogersc0542af2014-09-03 16:16:56 -0700485 if (gJdwpState == nullptr) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -0800486 // We probably failed because some other process has the port already, which means that
487 // if we don't abort the user is likely to think they're talking to us when they're actually
488 // talking to that other process.
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800489 LOG(FATAL) << "Debugger thread failed to initialize";
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700490 }
491
492 // If a debugger has already attached, send the "welcome" message.
493 // This may cause us to suspend all threads.
Elliott Hughes376a7a02011-10-24 18:35:55 -0700494 if (gJdwpState->IsActive()) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700495 ScopedObjectAccess soa(Thread::Current());
Sebastien Hertz7d955652014-10-22 10:57:10 +0200496 gJdwpState->PostVMStart();
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700497 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700498}
499
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700500void Dbg::StopJdwp() {
Sebastien Hertzc6345ef2014-08-18 19:26:39 +0200501 // Post VM_DEATH event before the JDWP connection is closed (either by the JDWP thread or the
502 // destruction of gJdwpState).
503 if (gJdwpState != nullptr && gJdwpState->IsActive()) {
504 gJdwpState->PostVMDeath();
505 }
Sebastien Hertz0376e6b2014-02-06 18:12:59 +0100506 // Prevent the JDWP thread from processing JDWP incoming packets after we close the connection.
Sebastien Hertz4e5b2082015-03-24 19:03:40 +0100507 Dispose();
Elliott Hughes376a7a02011-10-24 18:35:55 -0700508 delete gJdwpState;
Ian Rogers719d1a32014-03-06 12:13:39 -0800509 gJdwpState = nullptr;
Elliott Hughes475fc232011-10-25 15:00:35 -0700510 delete gRegistry;
Ian Rogers719d1a32014-03-06 12:13:39 -0800511 gRegistry = nullptr;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700512}
513
Elliott Hughes767a1472011-10-26 18:49:02 -0700514void Dbg::GcDidFinish() {
515 if (gDdmHpifWhen != HPIF_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700516 ScopedObjectAccess soa(Thread::Current());
Brian Carlstrom4d466a82014-05-08 19:05:29 -0700517 VLOG(jdwp) << "Sending heap info to DDM";
Elliott Hughes7162ad92011-10-27 14:08:42 -0700518 DdmSendHeapInfo(gDdmHpifWhen);
Elliott Hughes767a1472011-10-26 18:49:02 -0700519 }
520 if (gDdmHpsgWhen != HPSG_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700521 ScopedObjectAccess soa(Thread::Current());
Brian Carlstrom4d466a82014-05-08 19:05:29 -0700522 VLOG(jdwp) << "Dumping heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700523 DdmSendHeapSegments(false);
Elliott Hughes767a1472011-10-26 18:49:02 -0700524 }
525 if (gDdmNhsgWhen != HPSG_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700526 ScopedObjectAccess soa(Thread::Current());
Brian Carlstrom4d466a82014-05-08 19:05:29 -0700527 VLOG(jdwp) << "Dumping native heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700528 DdmSendHeapSegments(true);
Elliott Hughes767a1472011-10-26 18:49:02 -0700529 }
530}
531
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700532void Dbg::SetJdwpAllowed(bool allowed) {
533 gJdwpAllowed = allowed;
534}
535
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700536DebugInvokeReq* Dbg::GetInvokeReq() {
Elliott Hughes475fc232011-10-25 15:00:35 -0700537 return Thread::Current()->GetInvokeReq();
538}
539
540Thread* Dbg::GetDebugThread() {
Ian Rogersc0542af2014-09-03 16:16:56 -0700541 return (gJdwpState != nullptr) ? gJdwpState->GetDebugThread() : nullptr;
Elliott Hughes475fc232011-10-25 15:00:35 -0700542}
543
544void Dbg::ClearWaitForEventThread() {
Sebastien Hertz2bf93f42015-01-09 18:44:05 +0100545 gJdwpState->ReleaseJdwpTokenForEvent();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700546}
547
548void Dbg::Connected() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700549 CHECK(!gDebuggerConnected);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800550 VLOG(jdwp) << "JDWP has attached";
Elliott Hughes3bb81562011-10-21 18:52:59 -0700551 gDebuggerConnected = true;
Elliott Hughes86964332012-02-15 19:37:42 -0800552 gDisposed = false;
553}
554
Sebastien Hertzf3928792014-11-17 19:00:37 +0100555bool Dbg::RequiresDeoptimization() {
556 // We don't need deoptimization if everything runs with interpreter after
557 // enabling -Xint mode.
558 return !Runtime::Current()->GetInstrumentation()->IsForcedInterpretOnly();
559}
560
Elliott Hughesa2155262011-11-16 16:26:58 -0800561void Dbg::GoActive() {
562 // Enable all debugging features, including scans for breakpoints.
563 // This is a no-op if we're already active.
564 // Only called from the JDWP handler thread.
Daniel Mihalyieb076692014-08-22 17:33:31 +0200565 if (IsDebuggerActive()) {
Elliott Hughesa2155262011-11-16 16:26:58 -0800566 return;
567 }
568
Elliott Hughesc0f09332012-03-26 13:27:06 -0700569 {
570 // TODO: dalvik only warned if there were breakpoints left over. clear in Dbg::Disconnected?
Sebastien Hertzed2be172014-08-19 15:33:43 +0200571 ReaderMutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Elliott Hughesc0f09332012-03-26 13:27:06 -0700572 CHECK_EQ(gBreakpoints.size(), 0U);
573 }
Elliott Hughesa2155262011-11-16 16:26:58 -0800574
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100575 {
Brian Carlstrom306db812014-09-05 13:01:41 -0700576 MutexLock mu(Thread::Current(), *Locks::deoptimization_lock_);
Sebastien Hertz4d25df32014-03-21 17:44:46 +0100577 CHECK_EQ(deoptimization_requests_.size(), 0U);
578 CHECK_EQ(full_deoptimization_event_count_, 0U);
Sebastien Hertz42cd43f2014-05-13 14:15:41 +0200579 CHECK_EQ(dex_pc_change_event_ref_count_, 0U);
580 CHECK_EQ(method_enter_event_ref_count_, 0U);
581 CHECK_EQ(method_exit_event_ref_count_, 0U);
582 CHECK_EQ(field_read_event_ref_count_, 0U);
583 CHECK_EQ(field_write_event_ref_count_, 0U);
584 CHECK_EQ(exception_catch_event_ref_count_, 0U);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100585 }
586
Ian Rogers62d6c772013-02-27 08:32:07 -0800587 Runtime* runtime = Runtime::Current();
Mathieu Chartierbf9fc582015-03-13 17:21:25 -0700588 runtime->GetThreadList()->SuspendAll(__FUNCTION__);
Ian Rogers62d6c772013-02-27 08:32:07 -0800589 Thread* self = Thread::Current();
590 ThreadState old_state = self->SetStateUnsafe(kRunnable);
591 CHECK_NE(old_state, kRunnable);
Sebastien Hertzf3928792014-11-17 19:00:37 +0100592 if (RequiresDeoptimization()) {
593 runtime->GetInstrumentation()->EnableDeoptimization();
594 }
Sebastien Hertz42cd43f2014-05-13 14:15:41 +0200595 instrumentation_events_ = 0;
Elliott Hughesa2155262011-11-16 16:26:58 -0800596 gDebuggerActive = true;
Ian Rogers62d6c772013-02-27 08:32:07 -0800597 CHECK_EQ(self->SetStateUnsafe(old_state), kRunnable);
598 runtime->GetThreadList()->ResumeAll();
599
600 LOG(INFO) << "Debugger is active";
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700601}
602
603void Dbg::Disconnected() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700604 CHECK(gDebuggerConnected);
605
Elliott Hughesc0f09332012-03-26 13:27:06 -0700606 LOG(INFO) << "Debugger is no longer active";
Elliott Hughes234ab152011-10-26 14:02:26 -0700607
Ian Rogers62d6c772013-02-27 08:32:07 -0800608 // Suspend all threads and exclusively acquire the mutator lock. Set the state of the thread
609 // to kRunnable to avoid scoped object access transitions. Remove the debugger as a listener
610 // and clear the object registry.
611 Runtime* runtime = Runtime::Current();
Mathieu Chartierbf9fc582015-03-13 17:21:25 -0700612 runtime->GetThreadList()->SuspendAll(__FUNCTION__);
Ian Rogers62d6c772013-02-27 08:32:07 -0800613 Thread* self = Thread::Current();
614 ThreadState old_state = self->SetStateUnsafe(kRunnable);
Sebastien Hertzaaea7342014-02-25 15:10:04 +0100615
616 // Debugger may not be active at this point.
Daniel Mihalyieb076692014-08-22 17:33:31 +0200617 if (IsDebuggerActive()) {
Sebastien Hertzaaea7342014-02-25 15:10:04 +0100618 {
619 // Since we're going to disable deoptimization, we clear the deoptimization requests queue.
620 // This prevents us from having any pending deoptimization request when the debugger attaches
621 // to us again while no event has been requested yet.
Brian Carlstrom306db812014-09-05 13:01:41 -0700622 MutexLock mu(Thread::Current(), *Locks::deoptimization_lock_);
Sebastien Hertz4d25df32014-03-21 17:44:46 +0100623 deoptimization_requests_.clear();
624 full_deoptimization_event_count_ = 0U;
Sebastien Hertzaaea7342014-02-25 15:10:04 +0100625 }
Sebastien Hertz42cd43f2014-05-13 14:15:41 +0200626 if (instrumentation_events_ != 0) {
627 runtime->GetInstrumentation()->RemoveListener(&gDebugInstrumentationListener,
628 instrumentation_events_);
629 instrumentation_events_ = 0;
630 }
Sebastien Hertzf3928792014-11-17 19:00:37 +0100631 if (RequiresDeoptimization()) {
Sebastien Hertz0462c4c2015-04-01 16:34:17 +0200632 runtime->GetInstrumentation()->DisableDeoptimization(kDbgInstrumentationKey);
Sebastien Hertzf3928792014-11-17 19:00:37 +0100633 }
Sebastien Hertzaaea7342014-02-25 15:10:04 +0100634 gDebuggerActive = false;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100635 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800636 CHECK_EQ(self->SetStateUnsafe(old_state), kRunnable);
637 runtime->GetThreadList()->ResumeAll();
Sebastien Hertz55f65342015-01-13 22:48:34 +0100638
639 {
640 ScopedObjectAccess soa(self);
641 gRegistry->Clear();
642 }
643
644 gDebuggerConnected = false;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700645}
646
Sebastien Hertzb3b173b2015-02-06 09:16:32 +0100647void Dbg::ConfigureJdwp(const JDWP::JdwpOptions& jdwp_options) {
648 CHECK_NE(jdwp_options.transport, JDWP::kJdwpTransportUnknown);
649 gJdwpOptions = jdwp_options;
650 gJdwpConfigured = true;
651}
652
Elliott Hughesc0f09332012-03-26 13:27:06 -0700653bool Dbg::IsJdwpConfigured() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700654 return gJdwpConfigured;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700655}
656
657int64_t Dbg::LastDebuggerActivity() {
Elliott Hughesca951522011-12-05 12:01:32 -0800658 return gJdwpState->LastDebuggerActivity();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700659}
660
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700661void Dbg::UndoDebuggerSuspensions() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700662 Runtime::Current()->GetThreadList()->UndoDebuggerSuspensions();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700663}
664
Elliott Hughes88d63092013-01-09 09:55:54 -0800665std::string Dbg::GetClassName(JDWP::RefTypeId class_id) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700666 JDWP::JdwpError error;
667 mirror::Object* o = gRegistry->Get<mirror::Object*>(class_id, &error);
668 if (o == nullptr) {
669 if (error == JDWP::ERR_NONE) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700670 return "null";
Ian Rogersc0542af2014-09-03 16:16:56 -0700671 } else {
672 return StringPrintf("invalid object %p", reinterpret_cast<void*>(class_id));
673 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800674 }
675 if (!o->IsClass()) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700676 return StringPrintf("non-class %p", o); // This is only used for debugging output anyway.
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800677 }
Sebastien Hertz6995c602014-09-09 12:10:13 +0200678 return GetClassName(o->AsClass());
679}
680
681std::string Dbg::GetClassName(mirror::Class* klass) {
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +0200682 if (klass == nullptr) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700683 return "null";
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +0200684 }
Ian Rogers1ff3c982014-08-12 02:30:58 -0700685 std::string temp;
Sebastien Hertz6995c602014-09-09 12:10:13 +0200686 return DescriptorToName(klass->GetDescriptor(&temp));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700687}
688
Ian Rogersc0542af2014-09-03 16:16:56 -0700689JDWP::JdwpError Dbg::GetClassObject(JDWP::RefTypeId id, JDWP::ObjectId* class_object_id) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800690 JDWP::JdwpError status;
Ian Rogersc0542af2014-09-03 16:16:56 -0700691 mirror::Class* c = DecodeClass(id, &status);
692 if (c == nullptr) {
693 *class_object_id = 0;
Elliott Hughes436e3722012-02-17 20:01:47 -0800694 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800695 }
Ian Rogersc0542af2014-09-03 16:16:56 -0700696 *class_object_id = gRegistry->Add(c);
Elliott Hughes436e3722012-02-17 20:01:47 -0800697 return JDWP::ERR_NONE;
Elliott Hughes86964332012-02-15 19:37:42 -0800698}
699
Ian Rogersc0542af2014-09-03 16:16:56 -0700700JDWP::JdwpError Dbg::GetSuperclass(JDWP::RefTypeId id, JDWP::RefTypeId* superclass_id) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800701 JDWP::JdwpError status;
Ian Rogersc0542af2014-09-03 16:16:56 -0700702 mirror::Class* c = DecodeClass(id, &status);
703 if (c == nullptr) {
704 *superclass_id = 0;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800705 return status;
706 }
707 if (c->IsInterface()) {
708 // http://code.google.com/p/android/issues/detail?id=20856
Ian Rogersc0542af2014-09-03 16:16:56 -0700709 *superclass_id = 0;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800710 } else {
Ian Rogersc0542af2014-09-03 16:16:56 -0700711 *superclass_id = gRegistry->Add(c->GetSuperClass());
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800712 }
713 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700714}
715
Elliott Hughes436e3722012-02-17 20:01:47 -0800716JDWP::JdwpError Dbg::GetClassLoader(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700717 JDWP::JdwpError error;
718 mirror::Object* o = gRegistry->Get<mirror::Object*>(id, &error);
719 if (o == nullptr) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800720 return JDWP::ERR_INVALID_OBJECT;
721 }
722 expandBufAddObjectId(pReply, gRegistry->Add(o->GetClass()->GetClassLoader()));
723 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700724}
725
Elliott Hughes436e3722012-02-17 20:01:47 -0800726JDWP::JdwpError Dbg::GetModifiers(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700727 JDWP::JdwpError error;
728 mirror::Class* c = DecodeClass(id, &error);
729 if (c == nullptr) {
730 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800731 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800732
733 uint32_t access_flags = c->GetAccessFlags() & kAccJavaFlagsMask;
734
Yevgeny Roubande34eea2014-02-15 01:06:03 +0700735 // Set ACC_SUPER. Dex files don't contain this flag but only classes are supposed to have it set,
736 // not interfaces.
Elliott Hughes436e3722012-02-17 20:01:47 -0800737 // Class.getModifiers doesn't return it, but JDWP does, so we set it here.
Yevgeny Roubande34eea2014-02-15 01:06:03 +0700738 if ((access_flags & kAccInterface) == 0) {
739 access_flags |= kAccSuper;
740 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800741
742 expandBufAdd4BE(pReply, access_flags);
743
744 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700745}
746
Ian Rogersc0542af2014-09-03 16:16:56 -0700747JDWP::JdwpError Dbg::GetMonitorInfo(JDWP::ObjectId object_id, JDWP::ExpandBuf* reply) {
748 JDWP::JdwpError error;
749 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
750 if (o == nullptr) {
Elliott Hughesf327e072013-01-09 16:01:26 -0800751 return JDWP::ERR_INVALID_OBJECT;
752 }
753
754 // Ensure all threads are suspended while we read objects' lock words.
755 Thread* self = Thread::Current();
Sebastien Hertz54263242014-03-19 18:16:50 +0100756 CHECK_EQ(self->GetState(), kRunnable);
757 self->TransitionFromRunnableToSuspended(kSuspended);
Mathieu Chartierbf9fc582015-03-13 17:21:25 -0700758 Runtime::Current()->GetThreadList()->SuspendAll(__FUNCTION__);
Elliott Hughesf327e072013-01-09 16:01:26 -0800759
760 MonitorInfo monitor_info(o);
761
Sebastien Hertz54263242014-03-19 18:16:50 +0100762 Runtime::Current()->GetThreadList()->ResumeAll();
763 self->TransitionFromSuspendedToRunnable();
Elliott Hughesf327e072013-01-09 16:01:26 -0800764
Ian Rogersc0542af2014-09-03 16:16:56 -0700765 if (monitor_info.owner_ != nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700766 expandBufAddObjectId(reply, gRegistry->Add(monitor_info.owner_->GetPeer()));
Elliott Hughesf327e072013-01-09 16:01:26 -0800767 } else {
Ian Rogersc0542af2014-09-03 16:16:56 -0700768 expandBufAddObjectId(reply, gRegistry->Add(nullptr));
Elliott Hughesf327e072013-01-09 16:01:26 -0800769 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700770 expandBufAdd4BE(reply, monitor_info.entry_count_);
771 expandBufAdd4BE(reply, monitor_info.waiters_.size());
772 for (size_t i = 0; i < monitor_info.waiters_.size(); ++i) {
773 expandBufAddObjectId(reply, gRegistry->Add(monitor_info.waiters_[i]->GetPeer()));
Elliott Hughesf327e072013-01-09 16:01:26 -0800774 }
775 return JDWP::ERR_NONE;
776}
777
Elliott Hughes734b8c62013-01-11 15:32:45 -0800778JDWP::JdwpError Dbg::GetOwnedMonitors(JDWP::ObjectId thread_id,
Ian Rogersc0542af2014-09-03 16:16:56 -0700779 std::vector<JDWP::ObjectId>* monitors,
780 std::vector<uint32_t>* stack_depths) {
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800781 struct OwnedMonitorVisitor : public StackVisitor {
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700782 OwnedMonitorVisitor(Thread* thread, Context* context,
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -0700783 std::vector<JDWP::ObjectId>* monitor_vector,
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700784 std::vector<uint32_t>* stack_depth_vector)
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800785 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +0100786 : StackVisitor(thread, context, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
787 current_stack_depth(0),
788 monitors(monitor_vector),
789 stack_depths(stack_depth_vector) {}
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800790
791 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
792 // annotalysis.
793 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
794 if (!GetMethod()->IsRuntimeMethod()) {
795 Monitor::VisitLocks(this, AppendOwnedMonitors, this);
Elliott Hughes734b8c62013-01-11 15:32:45 -0800796 ++current_stack_depth;
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800797 }
798 return true;
799 }
800
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -0700801 static void AppendOwnedMonitors(mirror::Object* owned_monitor, void* arg)
802 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers7a22fa62013-01-23 12:16:16 -0800803 OwnedMonitorVisitor* visitor = reinterpret_cast<OwnedMonitorVisitor*>(arg);
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -0700804 visitor->monitors->push_back(gRegistry->Add(owned_monitor));
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700805 visitor->stack_depths->push_back(visitor->current_stack_depth);
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800806 }
807
Elliott Hughes734b8c62013-01-11 15:32:45 -0800808 size_t current_stack_depth;
Ian Rogersc0542af2014-09-03 16:16:56 -0700809 std::vector<JDWP::ObjectId>* const monitors;
810 std::vector<uint32_t>* const stack_depths;
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800811 };
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800812
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700813 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz69206392015-04-07 15:54:25 +0200814 JDWP::JdwpError error;
815 Thread* thread = DecodeThread(soa, thread_id, &error);
816 if (thread == nullptr) {
817 return error;
818 }
819 if (!IsSuspendedForDebugger(soa, thread)) {
820 return JDWP::ERR_THREAD_NOT_SUSPENDED;
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700821 }
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -0700822 std::unique_ptr<Context> context(Context::Create());
Ian Rogersc0542af2014-09-03 16:16:56 -0700823 OwnedMonitorVisitor visitor(thread, context.get(), monitors, stack_depths);
Hiroshi Yamauchicc8c5c52014-06-13 15:08:05 -0700824 visitor.WalkStack();
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800825 return JDWP::ERR_NONE;
826}
827
Sebastien Hertz52d131d2014-03-13 16:17:40 +0100828JDWP::JdwpError Dbg::GetContendedMonitor(JDWP::ObjectId thread_id,
Ian Rogersc0542af2014-09-03 16:16:56 -0700829 JDWP::ObjectId* contended_monitor) {
Elliott Hughesf9501702013-01-11 11:22:27 -0800830 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -0700831 *contended_monitor = 0;
Sebastien Hertz69206392015-04-07 15:54:25 +0200832 JDWP::JdwpError error;
833 Thread* thread = DecodeThread(soa, thread_id, &error);
834 if (thread == nullptr) {
835 return error;
Elliott Hughesf9501702013-01-11 11:22:27 -0800836 }
Sebastien Hertz69206392015-04-07 15:54:25 +0200837 if (!IsSuspendedForDebugger(soa, thread)) {
838 return JDWP::ERR_THREAD_NOT_SUSPENDED;
839 }
840 mirror::Object* contended_monitor_obj = Monitor::GetContendedMonitor(thread);
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -0700841 // Add() requires the thread_list_lock_ not held to avoid the lock
842 // level violation.
Ian Rogersc0542af2014-09-03 16:16:56 -0700843 *contended_monitor = gRegistry->Add(contended_monitor_obj);
Elliott Hughesf9501702013-01-11 11:22:27 -0800844 return JDWP::ERR_NONE;
845}
846
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800847JDWP::JdwpError Dbg::GetInstanceCounts(const std::vector<JDWP::RefTypeId>& class_ids,
Ian Rogersc0542af2014-09-03 16:16:56 -0700848 std::vector<uint64_t>* counts) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800849 gc::Heap* heap = Runtime::Current()->GetHeap();
850 heap->CollectGarbage(false);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800851 std::vector<mirror::Class*> classes;
Ian Rogersc0542af2014-09-03 16:16:56 -0700852 counts->clear();
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800853 for (size_t i = 0; i < class_ids.size(); ++i) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700854 JDWP::JdwpError error;
855 mirror::Class* c = DecodeClass(class_ids[i], &error);
856 if (c == nullptr) {
857 return error;
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800858 }
859 classes.push_back(c);
Ian Rogersc0542af2014-09-03 16:16:56 -0700860 counts->push_back(0);
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800861 }
Ian Rogersc0542af2014-09-03 16:16:56 -0700862 heap->CountInstances(classes, false, &(*counts)[0]);
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800863 return JDWP::ERR_NONE;
864}
865
Ian Rogersc0542af2014-09-03 16:16:56 -0700866JDWP::JdwpError Dbg::GetInstances(JDWP::RefTypeId class_id, int32_t max_count,
867 std::vector<JDWP::ObjectId>* instances) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800868 gc::Heap* heap = Runtime::Current()->GetHeap();
869 // We only want reachable instances, so do a GC.
870 heap->CollectGarbage(false);
Ian Rogersc0542af2014-09-03 16:16:56 -0700871 JDWP::JdwpError error;
872 mirror::Class* c = DecodeClass(class_id, &error);
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800873 if (c == nullptr) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700874 return error;
Elliott Hughes3b78c942013-01-15 17:35:41 -0800875 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800876 std::vector<mirror::Object*> raw_instances;
Elliott Hughes3b78c942013-01-15 17:35:41 -0800877 Runtime::Current()->GetHeap()->GetInstances(c, max_count, raw_instances);
878 for (size_t i = 0; i < raw_instances.size(); ++i) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700879 instances->push_back(gRegistry->Add(raw_instances[i]));
Elliott Hughes3b78c942013-01-15 17:35:41 -0800880 }
881 return JDWP::ERR_NONE;
882}
883
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800884JDWP::JdwpError Dbg::GetReferringObjects(JDWP::ObjectId object_id, int32_t max_count,
Ian Rogersc0542af2014-09-03 16:16:56 -0700885 std::vector<JDWP::ObjectId>* referring_objects) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800886 gc::Heap* heap = Runtime::Current()->GetHeap();
887 heap->CollectGarbage(false);
Ian Rogersc0542af2014-09-03 16:16:56 -0700888 JDWP::JdwpError error;
889 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
890 if (o == nullptr) {
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800891 return JDWP::ERR_INVALID_OBJECT;
892 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800893 std::vector<mirror::Object*> raw_instances;
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800894 heap->GetReferringObjects(o, max_count, raw_instances);
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800895 for (size_t i = 0; i < raw_instances.size(); ++i) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700896 referring_objects->push_back(gRegistry->Add(raw_instances[i]));
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800897 }
898 return JDWP::ERR_NONE;
899}
900
Ian Rogersc0542af2014-09-03 16:16:56 -0700901JDWP::JdwpError Dbg::DisableCollection(JDWP::ObjectId object_id) {
902 JDWP::JdwpError error;
903 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
904 if (o == nullptr) {
Sebastien Hertze96060a2013-12-11 12:06:28 +0100905 return JDWP::ERR_INVALID_OBJECT;
906 }
Elliott Hughes64f574f2013-02-20 14:57:12 -0800907 gRegistry->DisableCollection(object_id);
908 return JDWP::ERR_NONE;
909}
910
Ian Rogersc0542af2014-09-03 16:16:56 -0700911JDWP::JdwpError Dbg::EnableCollection(JDWP::ObjectId object_id) {
912 JDWP::JdwpError error;
913 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
Sebastien Hertze96060a2013-12-11 12:06:28 +0100914 // Unlike DisableCollection, JDWP specs do not state an invalid object causes an error. The RI
915 // also ignores these cases and never return an error. However it's not obvious why this command
916 // should behave differently from DisableCollection and IsCollected commands. So let's be more
917 // strict and return an error if this happens.
Ian Rogersc0542af2014-09-03 16:16:56 -0700918 if (o == nullptr) {
Sebastien Hertze96060a2013-12-11 12:06:28 +0100919 return JDWP::ERR_INVALID_OBJECT;
920 }
Elliott Hughes64f574f2013-02-20 14:57:12 -0800921 gRegistry->EnableCollection(object_id);
922 return JDWP::ERR_NONE;
923}
924
Ian Rogersc0542af2014-09-03 16:16:56 -0700925JDWP::JdwpError Dbg::IsCollected(JDWP::ObjectId object_id, bool* is_collected) {
926 *is_collected = true;
Sebastien Hertz65637eb2014-01-10 17:40:02 +0100927 if (object_id == 0) {
928 // Null object id is invalid.
Sebastien Hertze96060a2013-12-11 12:06:28 +0100929 return JDWP::ERR_INVALID_OBJECT;
930 }
Sebastien Hertz65637eb2014-01-10 17:40:02 +0100931 // JDWP specs state an INVALID_OBJECT error is returned if the object ID is not valid. However
932 // the RI seems to ignore this and assume object has been collected.
Ian Rogersc0542af2014-09-03 16:16:56 -0700933 JDWP::JdwpError error;
934 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
935 if (o != nullptr) {
936 *is_collected = gRegistry->IsCollected(object_id);
Sebastien Hertz65637eb2014-01-10 17:40:02 +0100937 }
Elliott Hughes64f574f2013-02-20 14:57:12 -0800938 return JDWP::ERR_NONE;
939}
940
Ian Rogersc0542af2014-09-03 16:16:56 -0700941void Dbg::DisposeObject(JDWP::ObjectId object_id, uint32_t reference_count) {
Elliott Hughes64f574f2013-02-20 14:57:12 -0800942 gRegistry->DisposeObject(object_id, reference_count);
943}
944
Sebastien Hertz6995c602014-09-09 12:10:13 +0200945JDWP::JdwpTypeTag Dbg::GetTypeTag(mirror::Class* klass) {
Sebastien Hertz4d8fd492014-03-28 16:29:41 +0100946 DCHECK(klass != nullptr);
947 if (klass->IsArrayClass()) {
948 return JDWP::TT_ARRAY;
949 } else if (klass->IsInterface()) {
950 return JDWP::TT_INTERFACE;
951 } else {
952 return JDWP::TT_CLASS;
953 }
954}
955
Elliott Hughes88d63092013-01-09 09:55:54 -0800956JDWP::JdwpError Dbg::GetReflectedType(JDWP::RefTypeId class_id, JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700957 JDWP::JdwpError error;
958 mirror::Class* c = DecodeClass(class_id, &error);
959 if (c == nullptr) {
960 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800961 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800962
Sebastien Hertz4d8fd492014-03-28 16:29:41 +0100963 JDWP::JdwpTypeTag type_tag = GetTypeTag(c);
964 expandBufAdd1(pReply, type_tag);
Elliott Hughes88d63092013-01-09 09:55:54 -0800965 expandBufAddRefTypeId(pReply, class_id);
Elliott Hughes436e3722012-02-17 20:01:47 -0800966 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700967}
968
Ian Rogersc0542af2014-09-03 16:16:56 -0700969void Dbg::GetClassList(std::vector<JDWP::RefTypeId>* classes) {
Elliott Hughesa2155262011-11-16 16:26:58 -0800970 // Get the complete list of reference classes (i.e. all classes except
971 // the primitive types).
972 // Returns a newly-allocated buffer full of RefTypeId values.
973 struct ClassListCreator {
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800974 explicit ClassListCreator(std::vector<JDWP::RefTypeId>* classes_in) : classes(classes_in) {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800975 }
976
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800977 static bool Visit(mirror::Class* c, void* arg) {
Elliott Hughesa2155262011-11-16 16:26:58 -0800978 return reinterpret_cast<ClassListCreator*>(arg)->Visit(c);
979 }
980
Elliott Hughes64f574f2013-02-20 14:57:12 -0800981 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
982 // annotalysis.
983 bool Visit(mirror::Class* c) NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughesa2155262011-11-16 16:26:58 -0800984 if (!c->IsPrimitive()) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700985 classes->push_back(gRegistry->AddRefType(c));
Elliott Hughesa2155262011-11-16 16:26:58 -0800986 }
987 return true;
988 }
989
Ian Rogersc0542af2014-09-03 16:16:56 -0700990 std::vector<JDWP::RefTypeId>* const classes;
Elliott Hughesa2155262011-11-16 16:26:58 -0800991 };
992
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800993 ClassListCreator clc(classes);
Sebastien Hertz4537c412014-08-28 14:41:50 +0200994 Runtime::Current()->GetClassLinker()->VisitClassesWithoutClassesLock(ClassListCreator::Visit,
995 &clc);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700996}
997
Ian Rogers1ff3c982014-08-12 02:30:58 -0700998JDWP::JdwpError Dbg::GetClassInfo(JDWP::RefTypeId class_id, JDWP::JdwpTypeTag* pTypeTag,
999 uint32_t* pStatus, std::string* pDescriptor) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001000 JDWP::JdwpError error;
1001 mirror::Class* c = DecodeClass(class_id, &error);
1002 if (c == nullptr) {
1003 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001004 }
1005
Elliott Hughesa2155262011-11-16 16:26:58 -08001006 if (c->IsArrayClass()) {
1007 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
1008 *pTypeTag = JDWP::TT_ARRAY;
1009 } else {
1010 if (c->IsErroneous()) {
1011 *pStatus = JDWP::CS_ERROR;
1012 } else {
1013 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED | JDWP::CS_INITIALIZED;
1014 }
1015 *pTypeTag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
1016 }
1017
Ian Rogersc0542af2014-09-03 16:16:56 -07001018 if (pDescriptor != nullptr) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07001019 std::string temp;
1020 *pDescriptor = c->GetDescriptor(&temp);
Elliott Hughesa2155262011-11-16 16:26:58 -08001021 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001022 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001023}
1024
Ian Rogersc0542af2014-09-03 16:16:56 -07001025void Dbg::FindLoadedClassBySignature(const char* descriptor, std::vector<JDWP::RefTypeId>* ids) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001026 std::vector<mirror::Class*> classes;
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001027 Runtime::Current()->GetClassLinker()->LookupClasses(descriptor, classes);
Ian Rogersc0542af2014-09-03 16:16:56 -07001028 ids->clear();
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001029 for (size_t i = 0; i < classes.size(); ++i) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001030 ids->push_back(gRegistry->Add(classes[i]));
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001031 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001032}
1033
Ian Rogersc0542af2014-09-03 16:16:56 -07001034JDWP::JdwpError Dbg::GetReferenceType(JDWP::ObjectId object_id, JDWP::ExpandBuf* pReply) {
1035 JDWP::JdwpError error;
1036 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
1037 if (o == nullptr) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001038 return JDWP::ERR_INVALID_OBJECT;
Elliott Hughes499c5132011-11-17 14:55:11 -08001039 }
Elliott Hughes2435a572012-02-17 16:07:41 -08001040
Sebastien Hertz4d8fd492014-03-28 16:29:41 +01001041 JDWP::JdwpTypeTag type_tag = GetTypeTag(o->GetClass());
Elliott Hughes64f574f2013-02-20 14:57:12 -08001042 JDWP::RefTypeId type_id = gRegistry->AddRefType(o->GetClass());
Elliott Hughes2435a572012-02-17 16:07:41 -08001043
1044 expandBufAdd1(pReply, type_tag);
1045 expandBufAddRefTypeId(pReply, type_id);
1046
1047 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001048}
1049
Ian Rogersfc0e94b2013-09-23 23:51:32 -07001050JDWP::JdwpError Dbg::GetSignature(JDWP::RefTypeId class_id, std::string* signature) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001051 JDWP::JdwpError error;
1052 mirror::Class* c = DecodeClass(class_id, &error);
1053 if (c == nullptr) {
1054 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001055 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07001056 std::string temp;
1057 *signature = c->GetDescriptor(&temp);
Elliott Hughes1fe7afb2012-02-13 17:23:03 -08001058 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001059}
1060
Ian Rogersc0542af2014-09-03 16:16:56 -07001061JDWP::JdwpError Dbg::GetSourceFile(JDWP::RefTypeId class_id, std::string* result) {
1062 JDWP::JdwpError error;
1063 mirror::Class* c = DecodeClass(class_id, &error);
Sebastien Hertz4206eb52014-06-05 10:15:45 +02001064 if (c == nullptr) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001065 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001066 }
Sebastien Hertz4206eb52014-06-05 10:15:45 +02001067 const char* source_file = c->GetSourceFile();
1068 if (source_file == nullptr) {
Sebastien Hertzb7054ba2014-03-13 11:52:31 +01001069 return JDWP::ERR_ABSENT_INFORMATION;
1070 }
Ian Rogersc0542af2014-09-03 16:16:56 -07001071 *result = source_file;
Elliott Hughes436e3722012-02-17 20:01:47 -08001072 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001073}
1074
Ian Rogersc0542af2014-09-03 16:16:56 -07001075JDWP::JdwpError Dbg::GetObjectTag(JDWP::ObjectId object_id, uint8_t* tag) {
Ian Rogers98379392014-02-24 16:53:16 -08001076 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07001077 JDWP::JdwpError error;
1078 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id, &error);
1079 if (error != JDWP::ERR_NONE) {
1080 *tag = JDWP::JT_VOID;
1081 return error;
Elliott Hughes546b9862012-06-20 16:06:13 -07001082 }
Ian Rogersc0542af2014-09-03 16:16:56 -07001083 *tag = TagFromObject(soa, o);
Elliott Hughes546b9862012-06-20 16:06:13 -07001084 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001085}
1086
Elliott Hughesaed4be92011-12-02 16:16:23 -08001087size_t Dbg::GetTagWidth(JDWP::JdwpTag tag) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001088 switch (tag) {
1089 case JDWP::JT_VOID:
1090 return 0;
1091 case JDWP::JT_BYTE:
1092 case JDWP::JT_BOOLEAN:
1093 return 1;
1094 case JDWP::JT_CHAR:
1095 case JDWP::JT_SHORT:
1096 return 2;
1097 case JDWP::JT_FLOAT:
1098 case JDWP::JT_INT:
1099 return 4;
1100 case JDWP::JT_ARRAY:
1101 case JDWP::JT_OBJECT:
1102 case JDWP::JT_STRING:
1103 case JDWP::JT_THREAD:
1104 case JDWP::JT_THREAD_GROUP:
1105 case JDWP::JT_CLASS_LOADER:
1106 case JDWP::JT_CLASS_OBJECT:
1107 return sizeof(JDWP::ObjectId);
1108 case JDWP::JT_DOUBLE:
1109 case JDWP::JT_LONG:
1110 return 8;
1111 default:
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001112 LOG(FATAL) << "Unknown tag " << tag;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001113 return -1;
1114 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001115}
1116
Ian Rogersc0542af2014-09-03 16:16:56 -07001117JDWP::JdwpError Dbg::GetArrayLength(JDWP::ObjectId array_id, int32_t* length) {
1118 JDWP::JdwpError error;
1119 mirror::Array* a = DecodeNonNullArray(array_id, &error);
1120 if (a == nullptr) {
1121 return error;
Elliott Hughes24437992011-11-30 14:49:33 -08001122 }
Ian Rogersc0542af2014-09-03 16:16:56 -07001123 *length = a->GetLength();
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001124 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001125}
1126
Elliott Hughes88d63092013-01-09 09:55:54 -08001127JDWP::JdwpError Dbg::OutputArray(JDWP::ObjectId array_id, int offset, int count, JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001128 JDWP::JdwpError error;
1129 mirror::Array* a = DecodeNonNullArray(array_id, &error);
Ian Rogers98379392014-02-24 16:53:16 -08001130 if (a == nullptr) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001131 return error;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001132 }
Elliott Hughes24437992011-11-30 14:49:33 -08001133
1134 if (offset < 0 || count < 0 || offset > a->GetLength() || a->GetLength() - offset < count) {
1135 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001136 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughes24437992011-11-30 14:49:33 -08001137 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07001138 JDWP::JdwpTag element_tag = BasicTagFromClass(a->GetClass()->GetComponentType());
1139 expandBufAdd1(pReply, element_tag);
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001140 expandBufAdd4BE(pReply, count);
1141
Ian Rogers1ff3c982014-08-12 02:30:58 -07001142 if (IsPrimitiveTag(element_tag)) {
1143 size_t width = GetTagWidth(element_tag);
Elliott Hughes24437992011-11-30 14:49:33 -08001144 uint8_t* dst = expandBufAddSpace(pReply, count * width);
1145 if (width == 8) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001146 const uint64_t* src8 = reinterpret_cast<uint64_t*>(a->GetRawData(sizeof(uint64_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001147 for (int i = 0; i < count; ++i) JDWP::Write8BE(&dst, src8[offset + i]);
1148 } else if (width == 4) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001149 const uint32_t* src4 = reinterpret_cast<uint32_t*>(a->GetRawData(sizeof(uint32_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001150 for (int i = 0; i < count; ++i) JDWP::Write4BE(&dst, src4[offset + i]);
1151 } else if (width == 2) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001152 const uint16_t* src2 = reinterpret_cast<uint16_t*>(a->GetRawData(sizeof(uint16_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001153 for (int i = 0; i < count; ++i) JDWP::Write2BE(&dst, src2[offset + i]);
1154 } else {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001155 const uint8_t* src = reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint8_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001156 memcpy(dst, &src[offset * width], count * width);
1157 }
1158 } else {
Ian Rogers98379392014-02-24 16:53:16 -08001159 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001160 mirror::ObjectArray<mirror::Object>* oa = a->AsObjectArray<mirror::Object>();
Elliott Hughes24437992011-11-30 14:49:33 -08001161 for (int i = 0; i < count; ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001162 mirror::Object* element = oa->Get(offset + i);
Ian Rogers98379392014-02-24 16:53:16 -08001163 JDWP::JdwpTag specific_tag = (element != nullptr) ? TagFromObject(soa, element)
Ian Rogers1ff3c982014-08-12 02:30:58 -07001164 : element_tag;
Elliott Hughes24437992011-11-30 14:49:33 -08001165 expandBufAdd1(pReply, specific_tag);
1166 expandBufAddObjectId(pReply, gRegistry->Add(element));
1167 }
1168 }
1169
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001170 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001171}
1172
Ian Rogersef7d42f2014-01-06 12:55:46 -08001173template <typename T>
Ian Rogersc0542af2014-09-03 16:16:56 -07001174static void CopyArrayData(mirror::Array* a, JDWP::Request* src, int offset, int count)
Ian Rogersef7d42f2014-01-06 12:55:46 -08001175 NO_THREAD_SAFETY_ANALYSIS {
1176 // TODO: fix when annotalysis correctly handles non-member functions.
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001177 DCHECK(a->GetClass()->IsPrimitiveArray());
1178
Ian Rogersef7d42f2014-01-06 12:55:46 -08001179 T* dst = reinterpret_cast<T*>(a->GetRawData(sizeof(T), offset));
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001180 for (int i = 0; i < count; ++i) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001181 *dst++ = src->ReadValue(sizeof(T));
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001182 }
1183}
1184
Elliott Hughes88d63092013-01-09 09:55:54 -08001185JDWP::JdwpError Dbg::SetArrayElements(JDWP::ObjectId array_id, int offset, int count,
Ian Rogersc0542af2014-09-03 16:16:56 -07001186 JDWP::Request* request) {
1187 JDWP::JdwpError error;
1188 mirror::Array* dst = DecodeNonNullArray(array_id, &error);
1189 if (dst == nullptr) {
1190 return error;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001191 }
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001192
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001193 if (offset < 0 || count < 0 || offset > dst->GetLength() || dst->GetLength() - offset < count) {
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001194 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001195 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001196 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07001197 JDWP::JdwpTag element_tag = BasicTagFromClass(dst->GetClass()->GetComponentType());
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001198
Ian Rogers1ff3c982014-08-12 02:30:58 -07001199 if (IsPrimitiveTag(element_tag)) {
1200 size_t width = GetTagWidth(element_tag);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001201 if (width == 8) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001202 CopyArrayData<uint64_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001203 } else if (width == 4) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001204 CopyArrayData<uint32_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001205 } else if (width == 2) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001206 CopyArrayData<uint16_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001207 } else {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001208 CopyArrayData<uint8_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001209 }
1210 } else {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001211 mirror::ObjectArray<mirror::Object>* oa = dst->AsObjectArray<mirror::Object>();
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001212 for (int i = 0; i < count; ++i) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001213 JDWP::ObjectId id = request->ReadObjectId();
Ian Rogersc0542af2014-09-03 16:16:56 -07001214 mirror::Object* o = gRegistry->Get<mirror::Object*>(id, &error);
1215 if (error != JDWP::ERR_NONE) {
1216 return error;
Elliott Hughes436e3722012-02-17 20:01:47 -08001217 }
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001218 oa->Set<false>(offset + i, o);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001219 }
1220 }
1221
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001222 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001223}
1224
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001225JDWP::JdwpError Dbg::CreateString(const std::string& str, JDWP::ObjectId* new_string_id) {
1226 Thread* self = Thread::Current();
1227 mirror::String* new_string = mirror::String::AllocFromModifiedUtf8(self, str.c_str());
1228 if (new_string == nullptr) {
1229 DCHECK(self->IsExceptionPending());
1230 self->ClearException();
1231 LOG(ERROR) << "Could not allocate string";
1232 *new_string_id = 0;
1233 return JDWP::ERR_OUT_OF_MEMORY;
1234 }
1235 *new_string_id = gRegistry->Add(new_string);
1236 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001237}
1238
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001239JDWP::JdwpError Dbg::CreateObject(JDWP::RefTypeId class_id, JDWP::ObjectId* new_object_id) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001240 JDWP::JdwpError error;
1241 mirror::Class* c = DecodeClass(class_id, &error);
1242 if (c == nullptr) {
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001243 *new_object_id = 0;
Ian Rogersc0542af2014-09-03 16:16:56 -07001244 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001245 }
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001246 Thread* self = Thread::Current();
1247 mirror::Object* new_object = c->AllocObject(self);
1248 if (new_object == nullptr) {
1249 DCHECK(self->IsExceptionPending());
1250 self->ClearException();
1251 LOG(ERROR) << "Could not allocate object of type " << PrettyDescriptor(c);
1252 *new_object_id = 0;
1253 return JDWP::ERR_OUT_OF_MEMORY;
1254 }
1255 *new_object_id = gRegistry->Add(new_object);
Elliott Hughes436e3722012-02-17 20:01:47 -08001256 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001257}
1258
Elliott Hughesbf13d362011-12-08 15:51:37 -08001259/*
1260 * Used by Eclipse's "Display" view to evaluate "new byte[5]" to get "(byte[]) [0, 0, 0, 0, 0]".
1261 */
Elliott Hughes88d63092013-01-09 09:55:54 -08001262JDWP::JdwpError Dbg::CreateArrayObject(JDWP::RefTypeId array_class_id, uint32_t length,
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001263 JDWP::ObjectId* new_array_id) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001264 JDWP::JdwpError error;
1265 mirror::Class* c = DecodeClass(array_class_id, &error);
1266 if (c == nullptr) {
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001267 *new_array_id = 0;
Ian Rogersc0542af2014-09-03 16:16:56 -07001268 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001269 }
Sebastien Hertz2c3e77a2015-04-02 16:26:48 +02001270 Thread* self = Thread::Current();
1271 gc::Heap* heap = Runtime::Current()->GetHeap();
1272 mirror::Array* new_array = mirror::Array::Alloc<true>(self, c, length,
1273 c->GetComponentSizeShift(),
1274 heap->GetCurrentAllocator());
1275 if (new_array == nullptr) {
1276 DCHECK(self->IsExceptionPending());
1277 self->ClearException();
1278 LOG(ERROR) << "Could not allocate array of type " << PrettyDescriptor(c);
1279 *new_array_id = 0;
1280 return JDWP::ERR_OUT_OF_MEMORY;
1281 }
1282 *new_array_id = gRegistry->Add(new_array);
Elliott Hughes436e3722012-02-17 20:01:47 -08001283 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001284}
1285
Mathieu Chartierc7853442015-03-27 14:35:38 -07001286JDWP::FieldId Dbg::ToFieldId(const ArtField* f) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001287 return static_cast<JDWP::FieldId>(reinterpret_cast<uintptr_t>(f));
Elliott Hughes03181a82011-11-17 17:22:21 -08001288}
1289
Mathieu Chartiere401d142015-04-22 13:56:20 -07001290static JDWP::MethodId ToMethodId(const ArtMethod* m)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001291 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001292 return static_cast<JDWP::MethodId>(reinterpret_cast<uintptr_t>(m));
Elliott Hughes03181a82011-11-17 17:22:21 -08001293}
1294
Mathieu Chartierc7853442015-03-27 14:35:38 -07001295static ArtField* FromFieldId(JDWP::FieldId fid)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001296 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001297 return reinterpret_cast<ArtField*>(static_cast<uintptr_t>(fid));
Elliott Hughesaed4be92011-12-02 16:16:23 -08001298}
1299
Mathieu Chartiere401d142015-04-22 13:56:20 -07001300static ArtMethod* FromMethodId(JDWP::MethodId mid)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001301 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001302 return reinterpret_cast<ArtMethod*>(static_cast<uintptr_t>(mid));
Elliott Hughes03181a82011-11-17 17:22:21 -08001303}
1304
Sebastien Hertz6995c602014-09-09 12:10:13 +02001305bool Dbg::MatchThread(JDWP::ObjectId expected_thread_id, Thread* event_thread) {
1306 CHECK(event_thread != nullptr);
1307 JDWP::JdwpError error;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001308 mirror::Object* expected_thread_peer = gRegistry->Get<mirror::Object*>(
1309 expected_thread_id, &error);
Sebastien Hertz6995c602014-09-09 12:10:13 +02001310 return expected_thread_peer == event_thread->GetPeer();
1311}
1312
1313bool Dbg::MatchLocation(const JDWP::JdwpLocation& expected_location,
1314 const JDWP::EventLocation& event_location) {
1315 if (expected_location.dex_pc != event_location.dex_pc) {
1316 return false;
1317 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001318 ArtMethod* m = FromMethodId(expected_location.method_id);
Sebastien Hertz6995c602014-09-09 12:10:13 +02001319 return m == event_location.method;
1320}
1321
1322bool Dbg::MatchType(mirror::Class* event_class, JDWP::RefTypeId class_id) {
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001323 if (event_class == nullptr) {
1324 return false;
1325 }
Sebastien Hertz6995c602014-09-09 12:10:13 +02001326 JDWP::JdwpError error;
1327 mirror::Class* expected_class = DecodeClass(class_id, &error);
1328 CHECK(expected_class != nullptr);
1329 return expected_class->IsAssignableFrom(event_class);
1330}
1331
1332bool Dbg::MatchField(JDWP::RefTypeId expected_type_id, JDWP::FieldId expected_field_id,
Mathieu Chartierc7853442015-03-27 14:35:38 -07001333 ArtField* event_field) {
1334 ArtField* expected_field = FromFieldId(expected_field_id);
Sebastien Hertz6995c602014-09-09 12:10:13 +02001335 if (expected_field != event_field) {
1336 return false;
1337 }
1338 return Dbg::MatchType(event_field->GetDeclaringClass(), expected_type_id);
1339}
1340
1341bool Dbg::MatchInstance(JDWP::ObjectId expected_instance_id, mirror::Object* event_instance) {
1342 JDWP::JdwpError error;
1343 mirror::Object* modifier_instance = gRegistry->Get<mirror::Object*>(expected_instance_id, &error);
1344 return modifier_instance == event_instance;
1345}
1346
Mathieu Chartiere401d142015-04-22 13:56:20 -07001347void Dbg::SetJdwpLocation(JDWP::JdwpLocation* location, ArtMethod* m, uint32_t dex_pc)
Sebastien Hertz69206392015-04-07 15:54:25 +02001348 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
1349 LOCKS_EXCLUDED(Locks::thread_list_lock_,
1350 Locks::thread_suspend_count_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001351 if (m == nullptr) {
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001352 memset(location, 0, sizeof(*location));
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001353 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001354 mirror::Class* c = m->GetDeclaringClass();
Ian Rogersc0542af2014-09-03 16:16:56 -07001355 location->type_tag = GetTypeTag(c);
1356 location->class_id = gRegistry->AddRefType(c);
1357 location->method_id = ToMethodId(m);
1358 location->dex_pc = (m->IsNative() || m->IsProxyMethod()) ? static_cast<uint64_t>(-1) : dex_pc;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001359 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08001360}
1361
Ian Rogersc0542af2014-09-03 16:16:56 -07001362std::string Dbg::GetMethodName(JDWP::MethodId method_id) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001363 ArtMethod* m = FromMethodId(method_id);
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001364 if (m == nullptr) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001365 return "null";
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001366 }
Sebastien Hertz415fd082015-06-01 11:42:27 +02001367 return m->GetInterfaceMethodIfProxy(sizeof(void*))->GetName();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001368}
1369
Ian Rogersc0542af2014-09-03 16:16:56 -07001370std::string Dbg::GetFieldName(JDWP::FieldId field_id) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001371 ArtField* f = FromFieldId(field_id);
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001372 if (f == nullptr) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001373 return "null";
Sebastien Hertza9aa0ff2014-09-19 12:07:51 +02001374 }
1375 return f->GetName();
Elliott Hughesa96836a2013-01-17 12:27:49 -08001376}
1377
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001378/*
1379 * Augment the access flags for synthetic methods and fields by setting
1380 * the (as described by the spec) "0xf0000000 bit". Also, strip out any
1381 * flags not specified by the Java programming language.
1382 */
1383static uint32_t MangleAccessFlags(uint32_t accessFlags) {
1384 accessFlags &= kAccJavaFlagsMask;
1385 if ((accessFlags & kAccSynthetic) != 0) {
1386 accessFlags |= 0xf0000000;
1387 }
1388 return accessFlags;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001389}
1390
Elliott Hughesdbb40792011-11-18 17:05:22 -08001391/*
Jeff Haob7cefc72013-11-14 14:51:09 -08001392 * Circularly shifts registers so that arguments come first. Debuggers
1393 * expect slots to begin with arguments, but dex code places them at
1394 * the end.
Elliott Hughesdbb40792011-11-18 17:05:22 -08001395 */
Mathieu Chartiere401d142015-04-22 13:56:20 -07001396static uint16_t MangleSlot(uint16_t slot, ArtMethod* m)
Jeff Haob7cefc72013-11-14 14:51:09 -08001397 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001398 const DexFile::CodeItem* code_item = m->GetCodeItem();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001399 if (code_item == nullptr) {
1400 // We should not get here for a method without code (native, proxy or abstract). Log it and
1401 // return the slot as is since all registers are arguments.
1402 LOG(WARNING) << "Trying to mangle slot for method without code " << PrettyMethod(m);
1403 return slot;
1404 }
Jeff Haob7cefc72013-11-14 14:51:09 -08001405 uint16_t ins_size = code_item->ins_size_;
1406 uint16_t locals_size = code_item->registers_size_ - ins_size;
1407 if (slot >= locals_size) {
1408 return slot - locals_size;
1409 } else {
1410 return slot + ins_size;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001411 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001412}
1413
Jeff Haob7cefc72013-11-14 14:51:09 -08001414/*
1415 * Circularly shifts registers so that arguments come last. Reverts
1416 * slots to dex style argument placement.
1417 */
Mathieu Chartiere401d142015-04-22 13:56:20 -07001418static uint16_t DemangleSlot(uint16_t slot, ArtMethod* m, JDWP::JdwpError* error)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001419 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001420 const DexFile::CodeItem* code_item = m->GetCodeItem();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001421 if (code_item == nullptr) {
1422 // We should not get here for a method without code (native, proxy or abstract). Log it and
1423 // return the slot as is since all registers are arguments.
1424 LOG(WARNING) << "Trying to demangle slot for method without code " << PrettyMethod(m);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001425 uint16_t vreg_count = ArtMethod::NumArgRegisters(m->GetShorty());
Sebastien Hertzabbabc82015-03-26 08:47:47 +01001426 if (slot < vreg_count) {
1427 *error = JDWP::ERR_NONE;
1428 return slot;
1429 }
Jeff Haob7cefc72013-11-14 14:51:09 -08001430 } else {
Sebastien Hertzabbabc82015-03-26 08:47:47 +01001431 if (slot < code_item->registers_size_) {
1432 uint16_t ins_size = code_item->ins_size_;
1433 uint16_t locals_size = code_item->registers_size_ - ins_size;
1434 *error = JDWP::ERR_NONE;
1435 return (slot < ins_size) ? slot + locals_size : slot - ins_size;
1436 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001437 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01001438
1439 // Slot is invalid in the method.
1440 LOG(ERROR) << "Invalid local slot " << slot << " for method " << PrettyMethod(m);
1441 *error = JDWP::ERR_INVALID_SLOT;
1442 return DexFile::kDexNoIndex16;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001443}
1444
Elliott Hughes88d63092013-01-09 09:55:54 -08001445JDWP::JdwpError Dbg::OutputDeclaredFields(JDWP::RefTypeId class_id, bool with_generic, JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001446 JDWP::JdwpError error;
1447 mirror::Class* c = DecodeClass(class_id, &error);
1448 if (c == nullptr) {
1449 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001450 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001451
1452 size_t instance_field_count = c->NumInstanceFields();
1453 size_t static_field_count = c->NumStaticFields();
1454
1455 expandBufAdd4BE(pReply, instance_field_count + static_field_count);
1456
1457 for (size_t i = 0; i < instance_field_count + static_field_count; ++i) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001458 ArtField* f = (i < instance_field_count) ? c->GetInstanceField(i) : c->GetStaticField(i - instance_field_count);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001459 expandBufAddFieldId(pReply, ToFieldId(f));
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001460 expandBufAddUtf8String(pReply, f->GetName());
1461 expandBufAddUtf8String(pReply, f->GetTypeDescriptor());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001462 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001463 static const char genericSignature[1] = "";
1464 expandBufAddUtf8String(pReply, genericSignature);
1465 }
1466 expandBufAdd4BE(pReply, MangleAccessFlags(f->GetAccessFlags()));
1467 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001468 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001469}
1470
Elliott Hughes88d63092013-01-09 09:55:54 -08001471JDWP::JdwpError Dbg::OutputDeclaredMethods(JDWP::RefTypeId class_id, bool with_generic,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001472 JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001473 JDWP::JdwpError error;
1474 mirror::Class* c = DecodeClass(class_id, &error);
1475 if (c == nullptr) {
1476 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001477 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001478
1479 size_t direct_method_count = c->NumDirectMethods();
1480 size_t virtual_method_count = c->NumVirtualMethods();
1481
1482 expandBufAdd4BE(pReply, direct_method_count + virtual_method_count);
1483
Mathieu Chartiere401d142015-04-22 13:56:20 -07001484 auto* cl = Runtime::Current()->GetClassLinker();
1485 auto ptr_size = cl->GetImagePointerSize();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001486 for (size_t i = 0; i < direct_method_count + virtual_method_count; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001487 ArtMethod* m = i < direct_method_count ?
1488 c->GetDirectMethod(i, ptr_size) : c->GetVirtualMethod(i - direct_method_count, ptr_size);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001489 expandBufAddMethodId(pReply, ToMethodId(m));
Sebastien Hertz415fd082015-06-01 11:42:27 +02001490 expandBufAddUtf8String(pReply, m->GetInterfaceMethodIfProxy(sizeof(void*))->GetName());
1491 expandBufAddUtf8String(pReply,
1492 m->GetInterfaceMethodIfProxy(sizeof(void*))->GetSignature().ToString());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001493 if (with_generic) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001494 const char* generic_signature = "";
1495 expandBufAddUtf8String(pReply, generic_signature);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001496 }
1497 expandBufAdd4BE(pReply, MangleAccessFlags(m->GetAccessFlags()));
1498 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001499 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001500}
1501
Elliott Hughes88d63092013-01-09 09:55:54 -08001502JDWP::JdwpError Dbg::OutputDeclaredInterfaces(JDWP::RefTypeId class_id, JDWP::ExpandBuf* pReply) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001503 JDWP::JdwpError error;
Mathieu Chartierf8322842014-05-16 10:59:25 -07001504 Thread* self = Thread::Current();
1505 StackHandleScope<1> hs(self);
Ian Rogersc0542af2014-09-03 16:16:56 -07001506 Handle<mirror::Class> c(hs.NewHandle(DecodeClass(class_id, &error)));
Mathieu Chartierf8322842014-05-16 10:59:25 -07001507 if (c.Get() == nullptr) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001508 return error;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001509 }
Mathieu Chartierf8322842014-05-16 10:59:25 -07001510 size_t interface_count = c->NumDirectInterfaces();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001511 expandBufAdd4BE(pReply, interface_count);
1512 for (size_t i = 0; i < interface_count; ++i) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07001513 expandBufAddRefTypeId(pReply,
1514 gRegistry->AddRefType(mirror::Class::GetDirectInterface(self, c, i)));
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001515 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001516 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001517}
1518
Ian Rogersc0542af2014-09-03 16:16:56 -07001519void Dbg::OutputLineTable(JDWP::RefTypeId, JDWP::MethodId method_id, JDWP::ExpandBuf* pReply) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001520 struct DebugCallbackContext {
1521 int numItems;
1522 JDWP::ExpandBuf* pReply;
1523
Elliott Hughes2435a572012-02-17 16:07:41 -08001524 static bool Callback(void* context, uint32_t address, uint32_t line_number) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001525 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
1526 expandBufAdd8BE(pContext->pReply, address);
Elliott Hughes2435a572012-02-17 16:07:41 -08001527 expandBufAdd4BE(pContext->pReply, line_number);
Elliott Hughes03181a82011-11-17 17:22:21 -08001528 pContext->numItems++;
Sebastien Hertzf2910ee2013-10-19 16:39:24 +02001529 return false;
Elliott Hughes03181a82011-11-17 17:22:21 -08001530 }
1531 };
Mathieu Chartiere401d142015-04-22 13:56:20 -07001532 ArtMethod* m = FromMethodId(method_id);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001533 const DexFile::CodeItem* code_item = m->GetCodeItem();
Elliott Hughes03181a82011-11-17 17:22:21 -08001534 uint64_t start, end;
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001535 if (code_item == nullptr) {
1536 DCHECK(m->IsNative() || m->IsProxyMethod());
Elliott Hughes03181a82011-11-17 17:22:21 -08001537 start = -1;
1538 end = -1;
1539 } else {
1540 start = 0;
jeffhao14f0db92012-12-14 17:50:42 -08001541 // Return the index of the last instruction
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001542 end = code_item->insns_size_in_code_units_ - 1;
Elliott Hughes03181a82011-11-17 17:22:21 -08001543 }
1544
1545 expandBufAdd8BE(pReply, start);
1546 expandBufAdd8BE(pReply, end);
1547
1548 // Add numLines later
1549 size_t numLinesOffset = expandBufGetLength(pReply);
1550 expandBufAdd4BE(pReply, 0);
1551
1552 DebugCallbackContext context;
1553 context.numItems = 0;
1554 context.pReply = pReply;
1555
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001556 if (code_item != nullptr) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001557 m->GetDexFile()->DecodeDebugInfo(code_item, m->IsStatic(), m->GetDexMethodIndex(),
Ian Rogersc0542af2014-09-03 16:16:56 -07001558 DebugCallbackContext::Callback, nullptr, &context);
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001559 }
Elliott Hughes03181a82011-11-17 17:22:21 -08001560
1561 JDWP::Set4BE(expandBufGetBuffer(pReply) + numLinesOffset, context.numItems);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001562}
1563
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001564void Dbg::OutputVariableTable(JDWP::RefTypeId, JDWP::MethodId method_id, bool with_generic,
1565 JDWP::ExpandBuf* pReply) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001566 struct DebugCallbackContext {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001567 ArtMethod* method;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001568 JDWP::ExpandBuf* pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001569 size_t variable_count;
1570 bool with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001571
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001572 static void Callback(void* context, uint16_t slot, uint32_t startAddress, uint32_t endAddress,
1573 const char* name, const char* descriptor, const char* signature)
Jeff Haob7cefc72013-11-14 14:51:09 -08001574 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001575 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
1576
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001577 VLOG(jdwp) << StringPrintf(" %2zd: %d(%d) '%s' '%s' '%s' actual slot=%d mangled slot=%d",
1578 pContext->variable_count, startAddress, endAddress - startAddress,
1579 name, descriptor, signature, slot,
1580 MangleSlot(slot, pContext->method));
Elliott Hughesdbb40792011-11-18 17:05:22 -08001581
Jeff Haob7cefc72013-11-14 14:51:09 -08001582 slot = MangleSlot(slot, pContext->method);
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001583
Elliott Hughesdbb40792011-11-18 17:05:22 -08001584 expandBufAdd8BE(pContext->pReply, startAddress);
1585 expandBufAddUtf8String(pContext->pReply, name);
1586 expandBufAddUtf8String(pContext->pReply, descriptor);
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001587 if (pContext->with_generic) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001588 expandBufAddUtf8String(pContext->pReply, signature);
1589 }
1590 expandBufAdd4BE(pContext->pReply, endAddress - startAddress);
1591 expandBufAdd4BE(pContext->pReply, slot);
1592
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001593 ++pContext->variable_count;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001594 }
1595 };
Mathieu Chartiere401d142015-04-22 13:56:20 -07001596 ArtMethod* m = FromMethodId(method_id);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001597
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001598 // arg_count considers doubles and longs to take 2 units.
1599 // variable_count considers everything to take 1 unit.
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001600 std::string shorty(m->GetShorty());
Mathieu Chartiere401d142015-04-22 13:56:20 -07001601 expandBufAdd4BE(pReply, ArtMethod::NumArgRegisters(shorty));
Elliott Hughesdbb40792011-11-18 17:05:22 -08001602
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001603 // We don't know the total number of variables yet, so leave a blank and update it later.
1604 size_t variable_count_offset = expandBufGetLength(pReply);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001605 expandBufAdd4BE(pReply, 0);
1606
1607 DebugCallbackContext context;
Jeff Haob7cefc72013-11-14 14:51:09 -08001608 context.method = m;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001609 context.pReply = pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001610 context.variable_count = 0;
1611 context.with_generic = with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001612
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001613 const DexFile::CodeItem* code_item = m->GetCodeItem();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001614 if (code_item != nullptr) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001615 m->GetDexFile()->DecodeDebugInfo(
Ian Rogersc0542af2014-09-03 16:16:56 -07001616 code_item, m->IsStatic(), m->GetDexMethodIndex(), nullptr, DebugCallbackContext::Callback,
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001617 &context);
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001618 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001619
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001620 JDWP::Set4BE(expandBufGetBuffer(pReply) + variable_count_offset, context.variable_count);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001621}
1622
Jeff Hao579b0242013-11-18 13:16:49 -08001623void Dbg::OutputMethodReturnValue(JDWP::MethodId method_id, const JValue* return_value,
1624 JDWP::ExpandBuf* pReply) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001625 ArtMethod* m = FromMethodId(method_id);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001626 JDWP::JdwpTag tag = BasicTagFromDescriptor(m->GetShorty());
Jeff Hao579b0242013-11-18 13:16:49 -08001627 OutputJValue(tag, return_value, pReply);
1628}
1629
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02001630void Dbg::OutputFieldValue(JDWP::FieldId field_id, const JValue* field_value,
1631 JDWP::ExpandBuf* pReply) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001632 ArtField* f = FromFieldId(field_id);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001633 JDWP::JdwpTag tag = BasicTagFromDescriptor(f->GetTypeDescriptor());
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02001634 OutputJValue(tag, field_value, pReply);
1635}
1636
Elliott Hughes9777ba22013-01-17 09:04:19 -08001637JDWP::JdwpError Dbg::GetBytecodes(JDWP::RefTypeId, JDWP::MethodId method_id,
Ian Rogersc0542af2014-09-03 16:16:56 -07001638 std::vector<uint8_t>* bytecodes) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001639 ArtMethod* m = FromMethodId(method_id);
Ian Rogersc0542af2014-09-03 16:16:56 -07001640 if (m == nullptr) {
Elliott Hughes9777ba22013-01-17 09:04:19 -08001641 return JDWP::ERR_INVALID_METHODID;
1642 }
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001643 const DexFile::CodeItem* code_item = m->GetCodeItem();
Elliott Hughes9777ba22013-01-17 09:04:19 -08001644 size_t byte_count = code_item->insns_size_in_code_units_ * 2;
1645 const uint8_t* begin = reinterpret_cast<const uint8_t*>(code_item->insns_);
1646 const uint8_t* end = begin + byte_count;
1647 for (const uint8_t* p = begin; p != end; ++p) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001648 bytecodes->push_back(*p);
Elliott Hughes9777ba22013-01-17 09:04:19 -08001649 }
1650 return JDWP::ERR_NONE;
1651}
1652
Elliott Hughes88d63092013-01-09 09:55:54 -08001653JDWP::JdwpTag Dbg::GetFieldBasicTag(JDWP::FieldId field_id) {
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001654 return BasicTagFromDescriptor(FromFieldId(field_id)->GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001655}
1656
Elliott Hughes88d63092013-01-09 09:55:54 -08001657JDWP::JdwpTag Dbg::GetStaticFieldBasicTag(JDWP::FieldId field_id) {
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001658 return BasicTagFromDescriptor(FromFieldId(field_id)->GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001659}
1660
Elliott Hughes88d63092013-01-09 09:55:54 -08001661static JDWP::JdwpError GetFieldValueImpl(JDWP::RefTypeId ref_type_id, JDWP::ObjectId object_id,
1662 JDWP::FieldId field_id, JDWP::ExpandBuf* pReply,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001663 bool is_static)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001664 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001665 JDWP::JdwpError error;
1666 mirror::Class* c = DecodeClass(ref_type_id, &error);
1667 if (ref_type_id != 0 && c == nullptr) {
1668 return error;
Elliott Hughes0cf74332012-02-23 23:14:00 -08001669 }
1670
Sebastien Hertz6995c602014-09-09 12:10:13 +02001671 mirror::Object* o = Dbg::GetObjectRegistry()->Get<mirror::Object*>(object_id, &error);
Ian Rogersc0542af2014-09-03 16:16:56 -07001672 if ((!is_static && o == nullptr) || error != JDWP::ERR_NONE) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001673 return JDWP::ERR_INVALID_OBJECT;
1674 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001675 ArtField* f = FromFieldId(field_id);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001676
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001677 mirror::Class* receiver_class = c;
Ian Rogersc0542af2014-09-03 16:16:56 -07001678 if (receiver_class == nullptr && o != nullptr) {
Elliott Hughes0cf74332012-02-23 23:14:00 -08001679 receiver_class = o->GetClass();
1680 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001681 // TODO: should we give up now if receiver_class is null?
Ian Rogersc0542af2014-09-03 16:16:56 -07001682 if (receiver_class != nullptr && !f->GetDeclaringClass()->IsAssignableFrom(receiver_class)) {
Elliott Hughes0cf74332012-02-23 23:14:00 -08001683 LOG(INFO) << "ERR_INVALID_FIELDID: " << PrettyField(f) << " " << PrettyClass(receiver_class);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001684 return JDWP::ERR_INVALID_FIELDID;
1685 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001686
Elliott Hughes0cf74332012-02-23 23:14:00 -08001687 // The RI only enforces the static/non-static mismatch in one direction.
1688 // TODO: should we change the tests and check both?
1689 if (is_static) {
1690 if (!f->IsStatic()) {
1691 return JDWP::ERR_INVALID_FIELDID;
1692 }
1693 } else {
1694 if (f->IsStatic()) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001695 LOG(WARNING) << "Ignoring non-nullptr receiver for ObjectReference.SetValues on static field "
1696 << PrettyField(f);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001697 }
1698 }
jeffhao0dfbb7e2012-11-28 15:26:03 -08001699 if (f->IsStatic()) {
1700 o = f->GetDeclaringClass();
1701 }
Elliott Hughes0cf74332012-02-23 23:14:00 -08001702
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001703 JDWP::JdwpTag tag = BasicTagFromDescriptor(f->GetTypeDescriptor());
Jeff Hao579b0242013-11-18 13:16:49 -08001704 JValue field_value;
1705 if (tag == JDWP::JT_VOID) {
1706 LOG(FATAL) << "Unknown tag: " << tag;
1707 } else if (!IsPrimitiveTag(tag)) {
1708 field_value.SetL(f->GetObject(o));
1709 } else if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
1710 field_value.SetJ(f->Get64(o));
Elliott Hughesaed4be92011-12-02 16:16:23 -08001711 } else {
Jeff Hao579b0242013-11-18 13:16:49 -08001712 field_value.SetI(f->Get32(o));
Elliott Hughesaed4be92011-12-02 16:16:23 -08001713 }
Jeff Hao579b0242013-11-18 13:16:49 -08001714 Dbg::OutputJValue(tag, &field_value, pReply);
1715
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001716 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001717}
1718
Elliott Hughes88d63092013-01-09 09:55:54 -08001719JDWP::JdwpError Dbg::GetFieldValue(JDWP::ObjectId object_id, JDWP::FieldId field_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001720 JDWP::ExpandBuf* pReply) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001721 return GetFieldValueImpl(0, object_id, field_id, pReply, false);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001722}
1723
Ian Rogersc0542af2014-09-03 16:16:56 -07001724JDWP::JdwpError Dbg::GetStaticFieldValue(JDWP::RefTypeId ref_type_id, JDWP::FieldId field_id,
1725 JDWP::ExpandBuf* pReply) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001726 return GetFieldValueImpl(ref_type_id, 0, field_id, pReply, true);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001727}
1728
Elliott Hughes88d63092013-01-09 09:55:54 -08001729static JDWP::JdwpError SetFieldValueImpl(JDWP::ObjectId object_id, JDWP::FieldId field_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001730 uint64_t value, int width, bool is_static)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001731 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001732 JDWP::JdwpError error;
Sebastien Hertz6995c602014-09-09 12:10:13 +02001733 mirror::Object* o = Dbg::GetObjectRegistry()->Get<mirror::Object*>(object_id, &error);
Ian Rogersc0542af2014-09-03 16:16:56 -07001734 if ((!is_static && o == nullptr) || error != JDWP::ERR_NONE) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001735 return JDWP::ERR_INVALID_OBJECT;
1736 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001737 ArtField* f = FromFieldId(field_id);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001738
1739 // The RI only enforces the static/non-static mismatch in one direction.
1740 // TODO: should we change the tests and check both?
1741 if (is_static) {
1742 if (!f->IsStatic()) {
1743 return JDWP::ERR_INVALID_FIELDID;
1744 }
1745 } else {
1746 if (f->IsStatic()) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001747 LOG(WARNING) << "Ignoring non-nullptr receiver for ObjectReference.SetValues on static field " << PrettyField(f);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001748 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001749 }
jeffhao0dfbb7e2012-11-28 15:26:03 -08001750 if (f->IsStatic()) {
1751 o = f->GetDeclaringClass();
1752 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001753
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001754 JDWP::JdwpTag tag = BasicTagFromDescriptor(f->GetTypeDescriptor());
Elliott Hughesaed4be92011-12-02 16:16:23 -08001755
1756 if (IsPrimitiveTag(tag)) {
1757 if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001758 CHECK_EQ(width, 8);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001759 // Debugging can't use transactional mode (runtime only).
1760 f->Set64<false>(o, value);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001761 } else {
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001762 CHECK_LE(width, 4);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001763 // Debugging can't use transactional mode (runtime only).
1764 f->Set32<false>(o, value);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001765 }
1766 } else {
Sebastien Hertz6995c602014-09-09 12:10:13 +02001767 mirror::Object* v = Dbg::GetObjectRegistry()->Get<mirror::Object*>(value, &error);
Ian Rogersc0542af2014-09-03 16:16:56 -07001768 if (error != JDWP::ERR_NONE) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001769 return JDWP::ERR_INVALID_OBJECT;
1770 }
Ian Rogersc0542af2014-09-03 16:16:56 -07001771 if (v != nullptr) {
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001772 mirror::Class* field_type;
1773 {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001774 StackHandleScope<2> hs(Thread::Current());
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001775 HandleWrapper<mirror::Object> h_v(hs.NewHandleWrapper(&v));
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001776 HandleWrapper<mirror::Object> h_o(hs.NewHandleWrapper(&o));
Mathieu Chartierc7853442015-03-27 14:35:38 -07001777 field_type = f->GetType<true>();
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001778 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001779 if (!field_type->IsAssignableFrom(v->GetClass())) {
1780 return JDWP::ERR_INVALID_OBJECT;
1781 }
1782 }
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001783 // Debugging can't use transactional mode (runtime only).
1784 f->SetObject<false>(o, v);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001785 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001786
1787 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001788}
1789
Elliott Hughes88d63092013-01-09 09:55:54 -08001790JDWP::JdwpError Dbg::SetFieldValue(JDWP::ObjectId object_id, JDWP::FieldId field_id, uint64_t value,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001791 int width) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001792 return SetFieldValueImpl(object_id, field_id, value, width, false);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001793}
1794
Elliott Hughes88d63092013-01-09 09:55:54 -08001795JDWP::JdwpError Dbg::SetStaticFieldValue(JDWP::FieldId field_id, uint64_t value, int width) {
1796 return SetFieldValueImpl(0, field_id, value, width, true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001797}
1798
Sebastien Hertzb0b0b492014-09-15 11:27:27 +02001799JDWP::JdwpError Dbg::StringToUtf8(JDWP::ObjectId string_id, std::string* str) {
Ian Rogersc0542af2014-09-03 16:16:56 -07001800 JDWP::JdwpError error;
Sebastien Hertzb0b0b492014-09-15 11:27:27 +02001801 mirror::Object* obj = gRegistry->Get<mirror::Object*>(string_id, &error);
1802 if (error != JDWP::ERR_NONE) {
1803 return error;
1804 }
1805 if (obj == nullptr) {
1806 return JDWP::ERR_INVALID_OBJECT;
1807 }
1808 {
1809 ScopedObjectAccessUnchecked soa(Thread::Current());
1810 mirror::Class* java_lang_String = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_String);
1811 if (!java_lang_String->IsAssignableFrom(obj->GetClass())) {
1812 // This isn't a string.
1813 return JDWP::ERR_INVALID_STRING;
1814 }
1815 }
1816 *str = obj->AsString()->ToModifiedUtf8();
1817 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001818}
1819
Jeff Hao579b0242013-11-18 13:16:49 -08001820void Dbg::OutputJValue(JDWP::JdwpTag tag, const JValue* return_value, JDWP::ExpandBuf* pReply) {
1821 if (IsPrimitiveTag(tag)) {
1822 expandBufAdd1(pReply, tag);
1823 if (tag == JDWP::JT_BOOLEAN || tag == JDWP::JT_BYTE) {
1824 expandBufAdd1(pReply, return_value->GetI());
1825 } else if (tag == JDWP::JT_CHAR || tag == JDWP::JT_SHORT) {
1826 expandBufAdd2BE(pReply, return_value->GetI());
1827 } else if (tag == JDWP::JT_FLOAT || tag == JDWP::JT_INT) {
1828 expandBufAdd4BE(pReply, return_value->GetI());
1829 } else if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
1830 expandBufAdd8BE(pReply, return_value->GetJ());
1831 } else {
1832 CHECK_EQ(tag, JDWP::JT_VOID);
1833 }
1834 } else {
Ian Rogers98379392014-02-24 16:53:16 -08001835 ScopedObjectAccessUnchecked soa(Thread::Current());
Jeff Hao579b0242013-11-18 13:16:49 -08001836 mirror::Object* value = return_value->GetL();
Ian Rogers98379392014-02-24 16:53:16 -08001837 expandBufAdd1(pReply, TagFromObject(soa, value));
Jeff Hao579b0242013-11-18 13:16:49 -08001838 expandBufAddObjectId(pReply, gRegistry->Add(value));
1839 }
1840}
1841
Ian Rogersc0542af2014-09-03 16:16:56 -07001842JDWP::JdwpError Dbg::GetThreadName(JDWP::ObjectId thread_id, std::string* name) {
jeffhaoa77f0f62012-12-05 17:19:31 -08001843 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07001844 JDWP::JdwpError error;
1845 Thread* thread = DecodeThread(soa, thread_id, &error);
1846 UNUSED(thread);
Elliott Hughes221229c2013-01-08 18:17:50 -08001847 if (error != JDWP::ERR_NONE && error != JDWP::ERR_THREAD_NOT_ALIVE) {
1848 return error;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001849 }
Elliott Hughes221229c2013-01-08 18:17:50 -08001850
1851 // We still need to report the zombie threads' names, so we can't just call Thread::GetThreadName.
Ian Rogersc0542af2014-09-03 16:16:56 -07001852 mirror::Object* thread_object = gRegistry->Get<mirror::Object*>(thread_id, &error);
1853 CHECK(thread_object != nullptr) << error;
Mathieu Chartierc7853442015-03-27 14:35:38 -07001854 ArtField* java_lang_Thread_name_field =
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001855 soa.DecodeField(WellKnownClasses::java_lang_Thread_name);
1856 mirror::String* s =
1857 reinterpret_cast<mirror::String*>(java_lang_Thread_name_field->GetObject(thread_object));
Ian Rogersc0542af2014-09-03 16:16:56 -07001858 if (s != nullptr) {
1859 *name = s->ToModifiedUtf8();
Elliott Hughes221229c2013-01-08 18:17:50 -08001860 }
1861 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001862}
1863
Elliott Hughes221229c2013-01-08 18:17:50 -08001864JDWP::JdwpError Dbg::GetThreadGroup(JDWP::ObjectId thread_id, JDWP::ExpandBuf* pReply) {
Sebastien Hertza06430c2014-09-15 19:21:30 +02001865 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07001866 JDWP::JdwpError error;
1867 mirror::Object* thread_object = gRegistry->Get<mirror::Object*>(thread_id, &error);
1868 if (error != JDWP::ERR_NONE) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001869 return JDWP::ERR_INVALID_OBJECT;
1870 }
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07001871 ScopedAssertNoThreadSuspension ants(soa.Self(), "Debugger: GetThreadGroup");
Elliott Hughes2435a572012-02-17 16:07:41 -08001872 // Okay, so it's an object, but is it actually a thread?
Sebastien Hertz69206392015-04-07 15:54:25 +02001873 Thread* thread = DecodeThread(soa, thread_id, &error);
1874 UNUSED(thread);
Elliott Hughes221229c2013-01-08 18:17:50 -08001875 if (error == JDWP::ERR_THREAD_NOT_ALIVE) {
1876 // Zombie threads are in the null group.
1877 expandBufAddObjectId(pReply, JDWP::ObjectId(0));
Sebastien Hertz52d131d2014-03-13 16:17:40 +01001878 error = JDWP::ERR_NONE;
1879 } else if (error == JDWP::ERR_NONE) {
1880 mirror::Class* c = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_Thread);
1881 CHECK(c != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001882 ArtField* f = soa.DecodeField(WellKnownClasses::java_lang_Thread_group);
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07001883 CHECK(f != nullptr);
Sebastien Hertz52d131d2014-03-13 16:17:40 +01001884 mirror::Object* group = f->GetObject(thread_object);
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07001885 CHECK(group != nullptr);
Sebastien Hertz52d131d2014-03-13 16:17:40 +01001886 JDWP::ObjectId thread_group_id = gRegistry->Add(group);
1887 expandBufAddObjectId(pReply, thread_group_id);
Elliott Hughes221229c2013-01-08 18:17:50 -08001888 }
Sebastien Hertz52d131d2014-03-13 16:17:40 +01001889 return error;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001890}
1891
Sebastien Hertza06430c2014-09-15 19:21:30 +02001892static mirror::Object* DecodeThreadGroup(ScopedObjectAccessUnchecked& soa,
1893 JDWP::ObjectId thread_group_id, JDWP::JdwpError* error)
1894 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Sebastien Hertz6995c602014-09-09 12:10:13 +02001895 mirror::Object* thread_group = Dbg::GetObjectRegistry()->Get<mirror::Object*>(thread_group_id,
1896 error);
Sebastien Hertza06430c2014-09-15 19:21:30 +02001897 if (*error != JDWP::ERR_NONE) {
1898 return nullptr;
1899 }
1900 if (thread_group == nullptr) {
1901 *error = JDWP::ERR_INVALID_OBJECT;
1902 return nullptr;
1903 }
Ian Rogers98379392014-02-24 16:53:16 -08001904 mirror::Class* c = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_ThreadGroup);
1905 CHECK(c != nullptr);
Sebastien Hertza06430c2014-09-15 19:21:30 +02001906 if (!c->IsAssignableFrom(thread_group->GetClass())) {
1907 // This is not a java.lang.ThreadGroup.
1908 *error = JDWP::ERR_INVALID_THREAD_GROUP;
1909 return nullptr;
1910 }
1911 *error = JDWP::ERR_NONE;
1912 return thread_group;
1913}
1914
1915JDWP::JdwpError Dbg::GetThreadGroupName(JDWP::ObjectId thread_group_id, JDWP::ExpandBuf* pReply) {
1916 ScopedObjectAccessUnchecked soa(Thread::Current());
1917 JDWP::JdwpError error;
1918 mirror::Object* thread_group = DecodeThreadGroup(soa, thread_group_id, &error);
1919 if (error != JDWP::ERR_NONE) {
1920 return error;
1921 }
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07001922 ScopedAssertNoThreadSuspension ants(soa.Self(), "Debugger: GetThreadGroupName");
Mathieu Chartierc7853442015-03-27 14:35:38 -07001923 ArtField* f = soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_name);
Ian Rogersc0542af2014-09-03 16:16:56 -07001924 CHECK(f != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001925 mirror::String* s = reinterpret_cast<mirror::String*>(f->GetObject(thread_group));
Sebastien Hertza06430c2014-09-15 19:21:30 +02001926
1927 std::string thread_group_name(s->ToModifiedUtf8());
1928 expandBufAddUtf8String(pReply, thread_group_name);
1929 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001930}
1931
Sebastien Hertza06430c2014-09-15 19:21:30 +02001932JDWP::JdwpError Dbg::GetThreadGroupParent(JDWP::ObjectId thread_group_id, JDWP::ExpandBuf* pReply) {
Ian Rogers98379392014-02-24 16:53:16 -08001933 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07001934 JDWP::JdwpError error;
Sebastien Hertza06430c2014-09-15 19:21:30 +02001935 mirror::Object* thread_group = DecodeThreadGroup(soa, thread_group_id, &error);
1936 if (error != JDWP::ERR_NONE) {
1937 return error;
1938 }
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07001939 mirror::Object* parent;
1940 {
1941 ScopedAssertNoThreadSuspension ants(soa.Self(), "Debugger: GetThreadGroupParent");
Mathieu Chartierc7853442015-03-27 14:35:38 -07001942 ArtField* f = soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_parent);
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07001943 CHECK(f != nullptr);
1944 parent = f->GetObject(thread_group);
1945 }
Sebastien Hertza06430c2014-09-15 19:21:30 +02001946 JDWP::ObjectId parent_group_id = gRegistry->Add(parent);
1947 expandBufAddObjectId(pReply, parent_group_id);
1948 return JDWP::ERR_NONE;
1949}
1950
1951static void GetChildThreadGroups(ScopedObjectAccessUnchecked& soa, mirror::Object* thread_group,
1952 std::vector<JDWP::ObjectId>* child_thread_group_ids)
1953 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1954 CHECK(thread_group != nullptr);
1955
1956 // Get the ArrayList<ThreadGroup> "groups" out of this thread group...
Mathieu Chartierc7853442015-03-27 14:35:38 -07001957 ArtField* groups_field = soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_groups);
Sebastien Hertza06430c2014-09-15 19:21:30 +02001958 mirror::Object* groups_array_list = groups_field->GetObject(thread_group);
Sebastien Hertze49e1952014-10-13 11:27:13 +02001959 {
1960 // The "groups" field is declared as a java.util.List: check it really is
1961 // an instance of java.util.ArrayList.
1962 CHECK(groups_array_list != nullptr);
1963 mirror::Class* java_util_ArrayList_class =
1964 soa.Decode<mirror::Class*>(WellKnownClasses::java_util_ArrayList);
1965 CHECK(groups_array_list->InstanceOf(java_util_ArrayList_class));
1966 }
Sebastien Hertza06430c2014-09-15 19:21:30 +02001967
1968 // Get the array and size out of the ArrayList<ThreadGroup>...
Mathieu Chartierc7853442015-03-27 14:35:38 -07001969 ArtField* array_field = soa.DecodeField(WellKnownClasses::java_util_ArrayList_array);
1970 ArtField* size_field = soa.DecodeField(WellKnownClasses::java_util_ArrayList_size);
Sebastien Hertza06430c2014-09-15 19:21:30 +02001971 mirror::ObjectArray<mirror::Object>* groups_array =
1972 array_field->GetObject(groups_array_list)->AsObjectArray<mirror::Object>();
1973 const int32_t size = size_field->GetInt(groups_array_list);
1974
1975 // Copy the first 'size' elements out of the array into the result.
Sebastien Hertz6995c602014-09-09 12:10:13 +02001976 ObjectRegistry* registry = Dbg::GetObjectRegistry();
Sebastien Hertza06430c2014-09-15 19:21:30 +02001977 for (int32_t i = 0; i < size; ++i) {
Sebastien Hertz6995c602014-09-09 12:10:13 +02001978 child_thread_group_ids->push_back(registry->Add(groups_array->Get(i)));
Sebastien Hertza06430c2014-09-15 19:21:30 +02001979 }
1980}
1981
1982JDWP::JdwpError Dbg::GetThreadGroupChildren(JDWP::ObjectId thread_group_id,
1983 JDWP::ExpandBuf* pReply) {
1984 ScopedObjectAccessUnchecked soa(Thread::Current());
1985 JDWP::JdwpError error;
1986 mirror::Object* thread_group = DecodeThreadGroup(soa, thread_group_id, &error);
1987 if (error != JDWP::ERR_NONE) {
1988 return error;
1989 }
1990
1991 // Add child threads.
1992 {
1993 std::vector<JDWP::ObjectId> child_thread_ids;
1994 GetThreads(thread_group, &child_thread_ids);
1995 expandBufAdd4BE(pReply, child_thread_ids.size());
1996 for (JDWP::ObjectId child_thread_id : child_thread_ids) {
1997 expandBufAddObjectId(pReply, child_thread_id);
1998 }
1999 }
2000
2001 // Add child thread groups.
2002 {
2003 std::vector<JDWP::ObjectId> child_thread_groups_ids;
2004 GetChildThreadGroups(soa, thread_group, &child_thread_groups_ids);
2005 expandBufAdd4BE(pReply, child_thread_groups_ids.size());
2006 for (JDWP::ObjectId child_thread_group_id : child_thread_groups_ids) {
2007 expandBufAddObjectId(pReply, child_thread_group_id);
2008 }
2009 }
2010
2011 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002012}
2013
2014JDWP::ObjectId Dbg::GetSystemThreadGroupId() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002015 ScopedObjectAccessUnchecked soa(Thread::Current());
Mathieu Chartierc7853442015-03-27 14:35:38 -07002016 ArtField* f = soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_systemThreadGroup);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002017 mirror::Object* group = f->GetObject(f->GetDeclaringClass());
Ian Rogers365c1022012-06-22 15:05:28 -07002018 return gRegistry->Add(group);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002019}
2020
Jeff Hao920af3e2013-08-28 15:46:38 -07002021JDWP::JdwpThreadStatus Dbg::ToJdwpThreadStatus(ThreadState state) {
2022 switch (state) {
2023 case kBlocked:
2024 return JDWP::TS_MONITOR;
2025 case kNative:
2026 case kRunnable:
2027 case kSuspended:
2028 return JDWP::TS_RUNNING;
2029 case kSleeping:
2030 return JDWP::TS_SLEEPING;
2031 case kStarting:
2032 case kTerminated:
2033 return JDWP::TS_ZOMBIE;
2034 case kTimedWaiting:
Sebastien Hertzbae182c2013-12-17 10:42:03 +01002035 case kWaitingForCheckPointsToRun:
Jeff Hao920af3e2013-08-28 15:46:38 -07002036 case kWaitingForDebuggerSend:
2037 case kWaitingForDebuggerSuspension:
2038 case kWaitingForDebuggerToAttach:
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002039 case kWaitingForDeoptimization:
Jeff Hao920af3e2013-08-28 15:46:38 -07002040 case kWaitingForGcToComplete:
Mathieu Chartierb43390c2015-05-12 10:47:11 -07002041 case kWaitingForGetObjectsAllocated:
Jeff Hao920af3e2013-08-28 15:46:38 -07002042 case kWaitingForJniOnLoad:
Sebastien Hertzbae182c2013-12-17 10:42:03 +01002043 case kWaitingForMethodTracingStart:
Jeff Hao920af3e2013-08-28 15:46:38 -07002044 case kWaitingForSignalCatcherOutput:
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -08002045 case kWaitingForVisitObjects:
Jeff Hao920af3e2013-08-28 15:46:38 -07002046 case kWaitingInMainDebuggerLoop:
2047 case kWaitingInMainSignalCatcherLoop:
2048 case kWaitingPerformingGc:
2049 case kWaiting:
2050 return JDWP::TS_WAIT;
2051 // Don't add a 'default' here so the compiler can spot incompatible enum changes.
2052 }
2053 LOG(FATAL) << "Unknown thread state: " << state;
2054 return JDWP::TS_ZOMBIE;
2055}
2056
Sebastien Hertz52d131d2014-03-13 16:17:40 +01002057JDWP::JdwpError Dbg::GetThreadStatus(JDWP::ObjectId thread_id, JDWP::JdwpThreadStatus* pThreadStatus,
2058 JDWP::JdwpSuspendStatus* pSuspendStatus) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002059 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes499c5132011-11-17 14:55:11 -08002060
Elliott Hughes9e0c1752013-01-09 14:02:58 -08002061 *pSuspendStatus = JDWP::SUSPEND_STATUS_NOT_SUSPENDED;
2062
Ian Rogersc0542af2014-09-03 16:16:56 -07002063 JDWP::JdwpError error;
2064 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002065 if (error != JDWP::ERR_NONE) {
2066 if (error == JDWP::ERR_THREAD_NOT_ALIVE) {
2067 *pThreadStatus = JDWP::TS_ZOMBIE;
Elliott Hughes221229c2013-01-08 18:17:50 -08002068 return JDWP::ERR_NONE;
2069 }
2070 return error;
Elliott Hughes499c5132011-11-17 14:55:11 -08002071 }
2072
Elliott Hughes9e0c1752013-01-09 14:02:58 -08002073 if (IsSuspendedForDebugger(soa, thread)) {
2074 *pSuspendStatus = JDWP::SUSPEND_STATUS_SUSPENDED;
Elliott Hughes499c5132011-11-17 14:55:11 -08002075 }
2076
Jeff Hao920af3e2013-08-28 15:46:38 -07002077 *pThreadStatus = ToJdwpThreadStatus(thread->GetState());
Elliott Hughes221229c2013-01-08 18:17:50 -08002078 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002079}
2080
Elliott Hughes221229c2013-01-08 18:17:50 -08002081JDWP::JdwpError Dbg::GetThreadDebugSuspendCount(JDWP::ObjectId thread_id, JDWP::ExpandBuf* pReply) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002082 ScopedObjectAccess soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002083 JDWP::JdwpError error;
2084 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002085 if (error != JDWP::ERR_NONE) {
2086 return error;
Elliott Hughes2435a572012-02-17 16:07:41 -08002087 }
Ian Rogers50b35e22012-10-04 10:09:15 -07002088 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002089 expandBufAdd4BE(pReply, thread->GetDebugSuspendCount());
Elliott Hughes2435a572012-02-17 16:07:41 -08002090 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002091}
2092
Elliott Hughesf9501702013-01-11 11:22:27 -08002093JDWP::JdwpError Dbg::Interrupt(JDWP::ObjectId thread_id) {
2094 ScopedObjectAccess soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002095 JDWP::JdwpError error;
2096 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughesf9501702013-01-11 11:22:27 -08002097 if (error != JDWP::ERR_NONE) {
2098 return error;
2099 }
Ian Rogersdd7624d2014-03-14 17:43:00 -07002100 thread->Interrupt(soa.Self());
Elliott Hughesf9501702013-01-11 11:22:27 -08002101 return JDWP::ERR_NONE;
2102}
2103
Sebastien Hertz070f7322014-09-09 12:08:49 +02002104static bool IsInDesiredThreadGroup(ScopedObjectAccessUnchecked& soa,
2105 mirror::Object* desired_thread_group, mirror::Object* peer)
2106 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2107 // Do we want threads from all thread groups?
2108 if (desired_thread_group == nullptr) {
2109 return true;
2110 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07002111 ArtField* thread_group_field = soa.DecodeField(WellKnownClasses::java_lang_Thread_group);
Sebastien Hertz070f7322014-09-09 12:08:49 +02002112 DCHECK(thread_group_field != nullptr);
2113 mirror::Object* group = thread_group_field->GetObject(peer);
2114 return (group == desired_thread_group);
2115}
2116
Sebastien Hertza06430c2014-09-15 19:21:30 +02002117void Dbg::GetThreads(mirror::Object* thread_group, std::vector<JDWP::ObjectId>* thread_ids) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002118 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz070f7322014-09-09 12:08:49 +02002119 std::list<Thread*> all_threads_list;
2120 {
2121 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
2122 all_threads_list = Runtime::Current()->GetThreadList()->GetList();
2123 }
2124 for (Thread* t : all_threads_list) {
2125 if (t == Dbg::GetDebugThread()) {
2126 // Skip the JDWP thread. Some debuggers get bent out of shape when they can't suspend and
2127 // query all threads, so it's easier if we just don't tell them about this thread.
2128 continue;
2129 }
2130 if (t->IsStillStarting()) {
2131 // This thread is being started (and has been registered in the thread list). However, it is
2132 // not completely started yet so we must ignore it.
2133 continue;
2134 }
2135 mirror::Object* peer = t->GetPeer();
2136 if (peer == nullptr) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002137 // 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 +02002138 // this thread yet.
2139 // TODO: if we identified threads to the debugger by their Thread*
2140 // rather than their peer's mirror::Object*, we could fix this.
2141 // Doing so might help us report ZOMBIE threads too.
2142 continue;
2143 }
2144 if (IsInDesiredThreadGroup(soa, thread_group, peer)) {
2145 thread_ids->push_back(gRegistry->Add(peer));
2146 }
2147 }
Elliott Hughescaf76542012-06-28 16:08:22 -07002148}
Elliott Hughesa2155262011-11-16 16:26:58 -08002149
Ian Rogersc0542af2014-09-03 16:16:56 -07002150static int GetStackDepth(Thread* thread) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002151 struct CountStackDepthVisitor : public StackVisitor {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002152 explicit CountStackDepthVisitor(Thread* thread_in)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01002153 : StackVisitor(thread_in, nullptr, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
2154 depth(0) {}
Ian Rogers0399dde2012-06-06 17:09:28 -07002155
Elliott Hughes64f574f2013-02-20 14:57:12 -08002156 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2157 // annotalysis.
2158 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07002159 if (!GetMethod()->IsRuntimeMethod()) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -08002160 ++depth;
2161 }
Elliott Hughes530fa002012-03-12 11:44:49 -07002162 return true;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08002163 }
2164 size_t depth;
2165 };
Elliott Hughes08fc03a2012-06-26 17:34:00 -07002166
Ian Rogers7a22fa62013-01-23 12:16:16 -08002167 CountStackDepthVisitor visitor(thread);
Ian Rogers0399dde2012-06-06 17:09:28 -07002168 visitor.WalkStack();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08002169 return visitor.depth;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002170}
2171
Ian Rogersc0542af2014-09-03 16:16:56 -07002172JDWP::JdwpError Dbg::GetThreadFrameCount(JDWP::ObjectId thread_id, size_t* result) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002173 ScopedObjectAccess soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002174 JDWP::JdwpError error;
2175 *result = 0;
2176 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002177 if (error != JDWP::ERR_NONE) {
2178 return error;
2179 }
Elliott Hughesf15f4a02013-01-09 10:09:38 -08002180 if (!IsSuspendedForDebugger(soa, thread)) {
2181 return JDWP::ERR_THREAD_NOT_SUSPENDED;
2182 }
Ian Rogersc0542af2014-09-03 16:16:56 -07002183 *result = GetStackDepth(thread);
Elliott Hughes221229c2013-01-08 18:17:50 -08002184 return JDWP::ERR_NONE;
Elliott Hughes86964332012-02-15 19:37:42 -08002185}
2186
Ian Rogers306057f2012-11-26 12:45:53 -08002187JDWP::JdwpError Dbg::GetThreadFrames(JDWP::ObjectId thread_id, size_t start_frame,
2188 size_t frame_count, JDWP::ExpandBuf* buf) {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002189 class GetFrameVisitor : public StackVisitor {
2190 public:
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002191 GetFrameVisitor(Thread* thread, size_t start_frame_in, size_t frame_count_in,
2192 JDWP::ExpandBuf* buf_in)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002193 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01002194 : StackVisitor(thread, nullptr, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
2195 depth_(0),
2196 start_frame_(start_frame_in),
2197 frame_count_(frame_count_in),
2198 buf_(buf_in) {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002199 expandBufAdd4BE(buf_, frame_count_);
Elliott Hughes03181a82011-11-17 17:22:21 -08002200 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002201
Sebastien Hertz69206392015-04-07 15:54:25 +02002202 bool VisitFrame() OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002203 if (GetMethod()->IsRuntimeMethod()) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07002204 return true; // The debugger can't do anything useful with a frame that has no Method*.
Elliott Hughes03181a82011-11-17 17:22:21 -08002205 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002206 if (depth_ >= start_frame_ + frame_count_) {
Elliott Hughes530fa002012-03-12 11:44:49 -07002207 return false;
Elliott Hughes03181a82011-11-17 17:22:21 -08002208 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002209 if (depth_ >= start_frame_) {
2210 JDWP::FrameId frame_id(GetFrameId());
2211 JDWP::JdwpLocation location;
Sebastien Hertz6995c602014-09-09 12:10:13 +02002212 SetJdwpLocation(&location, GetMethod(), GetDexPc());
Ian Rogersef7d42f2014-01-06 12:55:46 -08002213 VLOG(jdwp) << StringPrintf(" Frame %3zd: id=%3" PRIu64 " ", depth_, frame_id) << location;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002214 expandBufAdd8BE(buf_, frame_id);
2215 expandBufAddLocation(buf_, location);
2216 }
2217 ++depth_;
Elliott Hughes530fa002012-03-12 11:44:49 -07002218 return true;
Elliott Hughes03181a82011-11-17 17:22:21 -08002219 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002220
2221 private:
2222 size_t depth_;
2223 const size_t start_frame_;
2224 const size_t frame_count_;
2225 JDWP::ExpandBuf* buf_;
Elliott Hughes03181a82011-11-17 17:22:21 -08002226 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002227
2228 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002229 JDWP::JdwpError error;
2230 Thread* thread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08002231 if (error != JDWP::ERR_NONE) {
2232 return error;
2233 }
Elliott Hughesf15f4a02013-01-09 10:09:38 -08002234 if (!IsSuspendedForDebugger(soa, thread)) {
2235 return JDWP::ERR_THREAD_NOT_SUSPENDED;
2236 }
Ian Rogers7a22fa62013-01-23 12:16:16 -08002237 GetFrameVisitor visitor(thread, start_frame, frame_count, buf);
Ian Rogers0399dde2012-06-06 17:09:28 -07002238 visitor.WalkStack();
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002239 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002240}
2241
2242JDWP::ObjectId Dbg::GetThreadSelfId() {
Sebastien Hertz6995c602014-09-09 12:10:13 +02002243 return GetThreadId(Thread::Current());
2244}
2245
2246JDWP::ObjectId Dbg::GetThreadId(Thread* thread) {
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07002247 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz6995c602014-09-09 12:10:13 +02002248 return gRegistry->Add(thread->GetPeer());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002249}
2250
Elliott Hughes475fc232011-10-25 15:00:35 -07002251void Dbg::SuspendVM() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002252 Runtime::Current()->GetThreadList()->SuspendAllForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002253}
2254
2255void Dbg::ResumeVM() {
Sebastien Hertz253fa552014-10-14 17:27:15 +02002256 Runtime::Current()->GetThreadList()->ResumeAllForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002257}
2258
Elliott Hughes221229c2013-01-08 18:17:50 -08002259JDWP::JdwpError Dbg::SuspendThread(JDWP::ObjectId thread_id, bool request_suspension) {
Ian Rogersf3d874c2014-07-17 18:52:42 -07002260 Thread* self = Thread::Current();
Ian Rogersc0542af2014-09-03 16:16:56 -07002261 ScopedLocalRef<jobject> peer(self->GetJniEnv(), nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002262 {
Ian Rogersf3d874c2014-07-17 18:52:42 -07002263 ScopedObjectAccess soa(self);
Ian Rogersc0542af2014-09-03 16:16:56 -07002264 JDWP::JdwpError error;
2265 peer.reset(soa.AddLocalReference<jobject>(gRegistry->Get<mirror::Object*>(thread_id, &error)));
Elliott Hughes4e235312011-12-02 11:34:15 -08002266 }
Ian Rogersc0542af2014-09-03 16:16:56 -07002267 if (peer.get() == nullptr) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002268 return JDWP::ERR_THREAD_NOT_ALIVE;
2269 }
Ian Rogers4ad5cd32014-11-11 23:08:07 -08002270 // Suspend thread to build stack trace.
Elliott Hughesf327e072013-01-09 16:01:26 -08002271 bool timed_out;
Brian Carlstromba32de42014-08-27 23:43:46 -07002272 ThreadList* thread_list = Runtime::Current()->GetThreadList();
2273 Thread* thread = thread_list->SuspendThreadByPeer(peer.get(), request_suspension, true,
2274 &timed_out);
Ian Rogersc0542af2014-09-03 16:16:56 -07002275 if (thread != nullptr) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002276 return JDWP::ERR_NONE;
Elliott Hughesf327e072013-01-09 16:01:26 -08002277 } else if (timed_out) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002278 return JDWP::ERR_INTERNAL;
2279 } else {
2280 return JDWP::ERR_THREAD_NOT_ALIVE;
2281 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002282}
2283
Elliott Hughes221229c2013-01-08 18:17:50 -08002284void Dbg::ResumeThread(JDWP::ObjectId thread_id) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002285 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07002286 JDWP::JdwpError error;
2287 mirror::Object* peer = gRegistry->Get<mirror::Object*>(thread_id, &error);
2288 CHECK(peer != nullptr) << error;
jeffhaoa77f0f62012-12-05 17:19:31 -08002289 Thread* thread;
2290 {
2291 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
2292 thread = Thread::FromManagedThread(soa, peer);
2293 }
Ian Rogersc0542af2014-09-03 16:16:56 -07002294 if (thread == nullptr) {
Elliott Hughes4e235312011-12-02 11:34:15 -08002295 LOG(WARNING) << "No such thread for resume: " << peer;
2296 return;
2297 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002298 bool needs_resume;
2299 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002300 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002301 needs_resume = thread->GetSuspendCount() > 0;
2302 }
2303 if (needs_resume) {
Elliott Hughes546b9862012-06-20 16:06:13 -07002304 Runtime::Current()->GetThreadList()->Resume(thread, true);
2305 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002306}
2307
2308void Dbg::SuspendSelf() {
Elliott Hughes475fc232011-10-25 15:00:35 -07002309 Runtime::Current()->GetThreadList()->SuspendSelfForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002310}
2311
Ian Rogers0399dde2012-06-06 17:09:28 -07002312struct GetThisVisitor : public StackVisitor {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002313 GetThisVisitor(Thread* thread, Context* context, JDWP::FrameId frame_id_in)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002314 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01002315 : StackVisitor(thread, context, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
2316 this_object(nullptr),
2317 frame_id(frame_id_in) {}
Ian Rogers0399dde2012-06-06 17:09:28 -07002318
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002319 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2320 // annotalysis.
2321 virtual bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002322 if (frame_id != GetFrameId()) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002323 return true; // continue
Ian Rogers0399dde2012-06-06 17:09:28 -07002324 } else {
Ian Rogers62d6c772013-02-27 08:32:07 -08002325 this_object = GetThisObject();
2326 return false;
Ian Rogers0399dde2012-06-06 17:09:28 -07002327 }
Elliott Hughes86b00102011-12-05 17:54:26 -08002328 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002329
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002330 mirror::Object* this_object;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002331 JDWP::FrameId frame_id;
Ian Rogers0399dde2012-06-06 17:09:28 -07002332};
2333
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002334JDWP::JdwpError Dbg::GetThisObject(JDWP::ObjectId thread_id, JDWP::FrameId frame_id,
2335 JDWP::ObjectId* result) {
2336 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz69206392015-04-07 15:54:25 +02002337 JDWP::JdwpError error;
2338 Thread* thread = DecodeThread(soa, thread_id, &error);
2339 if (error != JDWP::ERR_NONE) {
2340 return error;
2341 }
2342 if (!IsSuspendedForDebugger(soa, thread)) {
2343 return JDWP::ERR_THREAD_NOT_SUSPENDED;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002344 }
Ian Rogers700a4022014-05-19 16:49:03 -07002345 std::unique_ptr<Context> context(Context::Create());
Ian Rogers7a22fa62013-01-23 12:16:16 -08002346 GetThisVisitor visitor(thread, context.get(), frame_id);
Ian Rogers0399dde2012-06-06 17:09:28 -07002347 visitor.WalkStack();
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002348 *result = gRegistry->Add(visitor.this_object);
2349 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002350}
2351
Sebastien Hertz8009f392014-09-01 17:07:11 +02002352// Walks the stack until we find the frame with the given FrameId.
2353class FindFrameVisitor FINAL : public StackVisitor {
2354 public:
2355 FindFrameVisitor(Thread* thread, Context* context, JDWP::FrameId frame_id)
2356 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01002357 : StackVisitor(thread, context, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
2358 frame_id_(frame_id),
2359 error_(JDWP::ERR_INVALID_FRAMEID) {}
Ian Rogersca190662012-06-26 15:45:57 -07002360
Sebastien Hertz8009f392014-09-01 17:07:11 +02002361 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2362 // annotalysis.
2363 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
2364 if (GetFrameId() != frame_id_) {
2365 return true; // Not our frame, carry on.
Ian Rogers0399dde2012-06-06 17:09:28 -07002366 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07002367 ArtMethod* m = GetMethod();
Sebastien Hertz8009f392014-09-01 17:07:11 +02002368 if (m->IsNative()) {
2369 // We can't read/write local value from/into native method.
2370 error_ = JDWP::ERR_OPAQUE_FRAME;
2371 } else {
2372 // We found our frame.
2373 error_ = JDWP::ERR_NONE;
2374 }
2375 return false;
2376 }
2377
2378 JDWP::JdwpError GetError() const {
2379 return error_;
2380 }
2381
2382 private:
2383 const JDWP::FrameId frame_id_;
2384 JDWP::JdwpError error_;
2385};
2386
2387JDWP::JdwpError Dbg::GetLocalValues(JDWP::Request* request, JDWP::ExpandBuf* pReply) {
2388 JDWP::ObjectId thread_id = request->ReadThreadId();
2389 JDWP::FrameId frame_id = request->ReadFrameId();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002390
2391 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz69206392015-04-07 15:54:25 +02002392 JDWP::JdwpError error;
2393 Thread* thread = DecodeThread(soa, thread_id, &error);
2394 if (error != JDWP::ERR_NONE) {
2395 return error;
2396 }
2397 if (!IsSuspendedForDebugger(soa, thread)) {
2398 return JDWP::ERR_THREAD_NOT_SUSPENDED;
Elliott Hughes221229c2013-01-08 18:17:50 -08002399 }
Sebastien Hertz8009f392014-09-01 17:07:11 +02002400 // Find the frame with the given frame_id.
Ian Rogers700a4022014-05-19 16:49:03 -07002401 std::unique_ptr<Context> context(Context::Create());
Sebastien Hertz8009f392014-09-01 17:07:11 +02002402 FindFrameVisitor visitor(thread, context.get(), frame_id);
Ian Rogers0399dde2012-06-06 17:09:28 -07002403 visitor.WalkStack();
Sebastien Hertz8009f392014-09-01 17:07:11 +02002404 if (visitor.GetError() != JDWP::ERR_NONE) {
2405 return visitor.GetError();
2406 }
2407
2408 // Read the values from visitor's context.
2409 int32_t slot_count = request->ReadSigned32("slot count");
2410 expandBufAdd4BE(pReply, slot_count); /* "int values" */
2411 for (int32_t i = 0; i < slot_count; ++i) {
2412 uint32_t slot = request->ReadUnsigned32("slot");
2413 JDWP::JdwpTag reqSigByte = request->ReadTag();
2414
2415 VLOG(jdwp) << " --> slot " << slot << " " << reqSigByte;
2416
2417 size_t width = Dbg::GetTagWidth(reqSigByte);
Sebastien Hertz7d955652014-10-22 10:57:10 +02002418 uint8_t* ptr = expandBufAddSpace(pReply, width + 1);
Sebastien Hertz69206392015-04-07 15:54:25 +02002419 error = Dbg::GetLocalValue(visitor, soa, slot, reqSigByte, ptr, width);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002420 if (error != JDWP::ERR_NONE) {
2421 return error;
2422 }
2423 }
2424 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002425}
2426
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002427constexpr JDWP::JdwpError kStackFrameLocalAccessError = JDWP::ERR_ABSENT_INFORMATION;
2428
2429static std::string GetStackContextAsString(const StackVisitor& visitor)
2430 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2431 return StringPrintf(" at DEX pc 0x%08x in method %s", visitor.GetDexPc(false),
2432 PrettyMethod(visitor.GetMethod()).c_str());
2433}
2434
2435static JDWP::JdwpError FailGetLocalValue(const StackVisitor& visitor, uint16_t vreg,
2436 JDWP::JdwpTag tag)
2437 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2438 LOG(ERROR) << "Failed to read " << tag << " local from register v" << vreg
2439 << GetStackContextAsString(visitor);
2440 return kStackFrameLocalAccessError;
2441}
2442
Sebastien Hertz8009f392014-09-01 17:07:11 +02002443JDWP::JdwpError Dbg::GetLocalValue(const StackVisitor& visitor, ScopedObjectAccessUnchecked& soa,
2444 int slot, JDWP::JdwpTag tag, uint8_t* buf, size_t width) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002445 ArtMethod* m = visitor.GetMethod();
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002446 JDWP::JdwpError error = JDWP::ERR_NONE;
2447 uint16_t vreg = DemangleSlot(slot, m, &error);
2448 if (error != JDWP::ERR_NONE) {
2449 return error;
2450 }
Sebastien Hertz8009f392014-09-01 17:07:11 +02002451 // TODO: check that the tag is compatible with the actual type of the slot!
Sebastien Hertz8009f392014-09-01 17:07:11 +02002452 switch (tag) {
2453 case JDWP::JT_BOOLEAN: {
2454 CHECK_EQ(width, 1U);
2455 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002456 if (!visitor.GetVReg(m, vreg, kIntVReg, &intVal)) {
2457 return FailGetLocalValue(visitor, vreg, tag);
Ian Rogers0399dde2012-06-06 17:09:28 -07002458 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002459 VLOG(jdwp) << "get boolean local " << vreg << " = " << intVal;
2460 JDWP::Set1(buf + 1, intVal != 0);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002461 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002462 }
Sebastien Hertz8009f392014-09-01 17:07:11 +02002463 case JDWP::JT_BYTE: {
2464 CHECK_EQ(width, 1U);
2465 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002466 if (!visitor.GetVReg(m, vreg, kIntVReg, &intVal)) {
2467 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002468 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002469 VLOG(jdwp) << "get byte local " << vreg << " = " << intVal;
2470 JDWP::Set1(buf + 1, intVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002471 break;
2472 }
2473 case JDWP::JT_SHORT:
2474 case JDWP::JT_CHAR: {
2475 CHECK_EQ(width, 2U);
2476 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002477 if (!visitor.GetVReg(m, vreg, kIntVReg, &intVal)) {
2478 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002479 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002480 VLOG(jdwp) << "get short/char local " << vreg << " = " << intVal;
2481 JDWP::Set2BE(buf + 1, intVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002482 break;
2483 }
2484 case JDWP::JT_INT: {
2485 CHECK_EQ(width, 4U);
2486 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002487 if (!visitor.GetVReg(m, vreg, kIntVReg, &intVal)) {
2488 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002489 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002490 VLOG(jdwp) << "get int local " << vreg << " = " << intVal;
2491 JDWP::Set4BE(buf + 1, intVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002492 break;
2493 }
2494 case JDWP::JT_FLOAT: {
2495 CHECK_EQ(width, 4U);
2496 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002497 if (!visitor.GetVReg(m, vreg, kFloatVReg, &intVal)) {
2498 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002499 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002500 VLOG(jdwp) << "get float local " << vreg << " = " << intVal;
2501 JDWP::Set4BE(buf + 1, intVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002502 break;
2503 }
2504 case JDWP::JT_ARRAY:
2505 case JDWP::JT_CLASS_LOADER:
2506 case JDWP::JT_CLASS_OBJECT:
2507 case JDWP::JT_OBJECT:
2508 case JDWP::JT_STRING:
2509 case JDWP::JT_THREAD:
2510 case JDWP::JT_THREAD_GROUP: {
2511 CHECK_EQ(width, sizeof(JDWP::ObjectId));
2512 uint32_t intVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002513 if (!visitor.GetVReg(m, vreg, kReferenceVReg, &intVal)) {
2514 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002515 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002516 mirror::Object* o = reinterpret_cast<mirror::Object*>(intVal);
2517 VLOG(jdwp) << "get " << tag << " object local " << vreg << " = " << o;
2518 if (!Runtime::Current()->GetHeap()->IsValidObjectAddress(o)) {
2519 LOG(FATAL) << StringPrintf("Found invalid object %#" PRIxPTR " in register v%u",
2520 reinterpret_cast<uintptr_t>(o), vreg)
2521 << GetStackContextAsString(visitor);
2522 UNREACHABLE();
2523 }
2524 tag = TagFromObject(soa, o);
2525 JDWP::SetObjectId(buf + 1, gRegistry->Add(o));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002526 break;
2527 }
2528 case JDWP::JT_DOUBLE: {
2529 CHECK_EQ(width, 8U);
2530 uint64_t longVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002531 if (!visitor.GetVRegPair(m, vreg, kDoubleLoVReg, kDoubleHiVReg, &longVal)) {
2532 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002533 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002534 VLOG(jdwp) << "get double local " << vreg << " = " << longVal;
2535 JDWP::Set8BE(buf + 1, longVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002536 break;
2537 }
2538 case JDWP::JT_LONG: {
2539 CHECK_EQ(width, 8U);
2540 uint64_t longVal;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002541 if (!visitor.GetVRegPair(m, vreg, kLongLoVReg, kLongHiVReg, &longVal)) {
2542 return FailGetLocalValue(visitor, vreg, tag);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002543 }
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002544 VLOG(jdwp) << "get long local " << vreg << " = " << longVal;
2545 JDWP::Set8BE(buf + 1, longVal);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002546 break;
2547 }
2548 default:
2549 LOG(FATAL) << "Unknown tag " << tag;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002550 UNREACHABLE();
Sebastien Hertz8009f392014-09-01 17:07:11 +02002551 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002552
Sebastien Hertz8009f392014-09-01 17:07:11 +02002553 // Prepend tag, which may have been updated.
2554 JDWP::Set1(buf, tag);
2555 return JDWP::ERR_NONE;
2556}
2557
2558JDWP::JdwpError Dbg::SetLocalValues(JDWP::Request* request) {
2559 JDWP::ObjectId thread_id = request->ReadThreadId();
2560 JDWP::FrameId frame_id = request->ReadFrameId();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002561
2562 ScopedObjectAccessUnchecked soa(Thread::Current());
Sebastien Hertz69206392015-04-07 15:54:25 +02002563 JDWP::JdwpError error;
2564 Thread* thread = DecodeThread(soa, thread_id, &error);
2565 if (error != JDWP::ERR_NONE) {
2566 return error;
2567 }
2568 if (!IsSuspendedForDebugger(soa, thread)) {
2569 return JDWP::ERR_THREAD_NOT_SUSPENDED;
Elliott Hughes221229c2013-01-08 18:17:50 -08002570 }
Sebastien Hertz8009f392014-09-01 17:07:11 +02002571 // Find the frame with the given frame_id.
Ian Rogers700a4022014-05-19 16:49:03 -07002572 std::unique_ptr<Context> context(Context::Create());
Sebastien Hertz8009f392014-09-01 17:07:11 +02002573 FindFrameVisitor visitor(thread, context.get(), frame_id);
Ian Rogers0399dde2012-06-06 17:09:28 -07002574 visitor.WalkStack();
Sebastien Hertz8009f392014-09-01 17:07:11 +02002575 if (visitor.GetError() != JDWP::ERR_NONE) {
2576 return visitor.GetError();
2577 }
2578
2579 // Writes the values into visitor's context.
2580 int32_t slot_count = request->ReadSigned32("slot count");
2581 for (int32_t i = 0; i < slot_count; ++i) {
2582 uint32_t slot = request->ReadUnsigned32("slot");
2583 JDWP::JdwpTag sigByte = request->ReadTag();
2584 size_t width = Dbg::GetTagWidth(sigByte);
2585 uint64_t value = request->ReadValue(width);
2586
2587 VLOG(jdwp) << " --> slot " << slot << " " << sigByte << " " << value;
Sebastien Hertz69206392015-04-07 15:54:25 +02002588 error = Dbg::SetLocalValue(visitor, slot, sigByte, value, width);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002589 if (error != JDWP::ERR_NONE) {
2590 return error;
2591 }
2592 }
2593 return JDWP::ERR_NONE;
2594}
2595
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002596template<typename T>
2597static JDWP::JdwpError FailSetLocalValue(const StackVisitor& visitor, uint16_t vreg,
2598 JDWP::JdwpTag tag, T value)
2599 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2600 LOG(ERROR) << "Failed to write " << tag << " local " << value
2601 << " (0x" << std::hex << value << ") into register v" << vreg
2602 << GetStackContextAsString(visitor);
2603 return kStackFrameLocalAccessError;
2604}
2605
Sebastien Hertz8009f392014-09-01 17:07:11 +02002606JDWP::JdwpError Dbg::SetLocalValue(StackVisitor& visitor, int slot, JDWP::JdwpTag tag,
2607 uint64_t value, size_t width) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002608 ArtMethod* m = visitor.GetMethod();
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002609 JDWP::JdwpError error = JDWP::ERR_NONE;
2610 uint16_t vreg = DemangleSlot(slot, m, &error);
2611 if (error != JDWP::ERR_NONE) {
2612 return error;
2613 }
Sebastien Hertz8009f392014-09-01 17:07:11 +02002614 // TODO: check that the tag is compatible with the actual type of the slot!
Sebastien Hertz8009f392014-09-01 17:07:11 +02002615 switch (tag) {
2616 case JDWP::JT_BOOLEAN:
2617 case JDWP::JT_BYTE:
2618 CHECK_EQ(width, 1U);
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002619 if (!visitor.SetVReg(m, vreg, static_cast<uint32_t>(value), kIntVReg)) {
2620 return FailSetLocalValue(visitor, vreg, tag, static_cast<uint32_t>(value));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002621 }
2622 break;
2623 case JDWP::JT_SHORT:
2624 case JDWP::JT_CHAR:
2625 CHECK_EQ(width, 2U);
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002626 if (!visitor.SetVReg(m, vreg, static_cast<uint32_t>(value), kIntVReg)) {
2627 return FailSetLocalValue(visitor, vreg, tag, static_cast<uint32_t>(value));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002628 }
2629 break;
2630 case JDWP::JT_INT:
2631 CHECK_EQ(width, 4U);
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002632 if (!visitor.SetVReg(m, vreg, static_cast<uint32_t>(value), kIntVReg)) {
2633 return FailSetLocalValue(visitor, vreg, tag, static_cast<uint32_t>(value));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002634 }
2635 break;
2636 case JDWP::JT_FLOAT:
2637 CHECK_EQ(width, 4U);
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002638 if (!visitor.SetVReg(m, vreg, static_cast<uint32_t>(value), kFloatVReg)) {
2639 return FailSetLocalValue(visitor, vreg, tag, static_cast<uint32_t>(value));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002640 }
2641 break;
2642 case JDWP::JT_ARRAY:
2643 case JDWP::JT_CLASS_LOADER:
2644 case JDWP::JT_CLASS_OBJECT:
2645 case JDWP::JT_OBJECT:
2646 case JDWP::JT_STRING:
2647 case JDWP::JT_THREAD:
2648 case JDWP::JT_THREAD_GROUP: {
2649 CHECK_EQ(width, sizeof(JDWP::ObjectId));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002650 mirror::Object* o = gRegistry->Get<mirror::Object*>(static_cast<JDWP::ObjectId>(value),
2651 &error);
2652 if (error != JDWP::ERR_NONE) {
2653 VLOG(jdwp) << tag << " object " << o << " is an invalid object";
2654 return JDWP::ERR_INVALID_OBJECT;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002655 }
2656 if (!visitor.SetVReg(m, vreg, static_cast<uint32_t>(reinterpret_cast<uintptr_t>(o)),
2657 kReferenceVReg)) {
2658 return FailSetLocalValue(visitor, vreg, tag, reinterpret_cast<uintptr_t>(o));
Sebastien Hertz8009f392014-09-01 17:07:11 +02002659 }
2660 break;
2661 }
2662 case JDWP::JT_DOUBLE: {
2663 CHECK_EQ(width, 8U);
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002664 if (!visitor.SetVRegPair(m, vreg, value, kDoubleLoVReg, kDoubleHiVReg)) {
2665 return FailSetLocalValue(visitor, vreg, tag, value);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002666 }
2667 break;
2668 }
2669 case JDWP::JT_LONG: {
2670 CHECK_EQ(width, 8U);
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002671 if (!visitor.SetVRegPair(m, vreg, value, kLongLoVReg, kLongHiVReg)) {
2672 return FailSetLocalValue(visitor, vreg, tag, value);
Sebastien Hertz8009f392014-09-01 17:07:11 +02002673 }
2674 break;
2675 }
2676 default:
2677 LOG(FATAL) << "Unknown tag " << tag;
Sebastien Hertzabbabc82015-03-26 08:47:47 +01002678 UNREACHABLE();
Sebastien Hertz8009f392014-09-01 17:07:11 +02002679 }
2680 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002681}
2682
Mathieu Chartiere401d142015-04-22 13:56:20 -07002683static void SetEventLocation(JDWP::EventLocation* location, ArtMethod* m, uint32_t dex_pc)
Sebastien Hertz6995c602014-09-09 12:10:13 +02002684 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2685 DCHECK(location != nullptr);
2686 if (m == nullptr) {
2687 memset(location, 0, sizeof(*location));
2688 } else {
2689 location->method = m;
2690 location->dex_pc = (m->IsNative() || m->IsProxyMethod()) ? static_cast<uint32_t>(-1) : dex_pc;
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002691 }
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002692}
2693
Mathieu Chartiere401d142015-04-22 13:56:20 -07002694void Dbg::PostLocationEvent(ArtMethod* m, int dex_pc, mirror::Object* this_object,
Jeff Hao579b0242013-11-18 13:16:49 -08002695 int event_flags, const JValue* return_value) {
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002696 if (!IsDebuggerActive()) {
2697 return;
2698 }
2699 DCHECK(m != nullptr);
2700 DCHECK_EQ(m->IsStatic(), this_object == nullptr);
Sebastien Hertz6995c602014-09-09 12:10:13 +02002701 JDWP::EventLocation location;
2702 SetEventLocation(&location, m, dex_pc);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002703
Sebastien Hertzde48aa62015-05-26 11:53:39 +02002704 // We need to be sure no exception is pending when calling JdwpState::PostLocationEvent.
2705 // This is required to be able to call JNI functions to create JDWP ids. To achieve this,
2706 // we temporarily clear the current thread's exception (if any) and will restore it after
2707 // the call.
2708 // Note: the only way to get a pending exception here is to suspend on a move-exception
2709 // instruction.
2710 Thread* const self = Thread::Current();
2711 StackHandleScope<1> hs(self);
2712 Handle<mirror::Throwable> pending_exception(hs.NewHandle(self->GetException()));
2713 self->ClearException();
2714 if (kIsDebugBuild && pending_exception.Get() != nullptr) {
2715 const DexFile::CodeItem* code_item = location.method->GetCodeItem();
2716 const Instruction* instr = Instruction::At(&code_item->insns_[location.dex_pc]);
2717 CHECK_EQ(Instruction::MOVE_EXCEPTION, instr->Opcode());
2718 }
2719
Sebastien Hertz6995c602014-09-09 12:10:13 +02002720 gJdwpState->PostLocationEvent(&location, this_object, event_flags, return_value);
Sebastien Hertzde48aa62015-05-26 11:53:39 +02002721
2722 if (pending_exception.Get() != nullptr) {
2723 self->SetException(pending_exception.Get());
2724 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002725}
2726
Mathieu Chartiere401d142015-04-22 13:56:20 -07002727void Dbg::PostFieldAccessEvent(ArtMethod* m, int dex_pc,
Mathieu Chartierc7853442015-03-27 14:35:38 -07002728 mirror::Object* this_object, ArtField* f) {
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002729 if (!IsDebuggerActive()) {
2730 return;
2731 }
2732 DCHECK(m != nullptr);
2733 DCHECK(f != nullptr);
Sebastien Hertz6995c602014-09-09 12:10:13 +02002734 JDWP::EventLocation location;
2735 SetEventLocation(&location, m, dex_pc);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002736
Sebastien Hertz6995c602014-09-09 12:10:13 +02002737 gJdwpState->PostFieldEvent(&location, f, this_object, nullptr, false);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002738}
2739
Mathieu Chartiere401d142015-04-22 13:56:20 -07002740void Dbg::PostFieldModificationEvent(ArtMethod* m, int dex_pc,
Mathieu Chartierc7853442015-03-27 14:35:38 -07002741 mirror::Object* this_object, ArtField* f,
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002742 const JValue* field_value) {
2743 if (!IsDebuggerActive()) {
2744 return;
2745 }
2746 DCHECK(m != nullptr);
2747 DCHECK(f != nullptr);
2748 DCHECK(field_value != nullptr);
Sebastien Hertz6995c602014-09-09 12:10:13 +02002749 JDWP::EventLocation location;
2750 SetEventLocation(&location, m, dex_pc);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002751
Sebastien Hertz6995c602014-09-09 12:10:13 +02002752 gJdwpState->PostFieldEvent(&location, f, this_object, field_value, true);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002753}
2754
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002755/**
2756 * Finds the location where this exception will be caught. We search until we reach the top
2757 * frame, in which case this exception is considered uncaught.
2758 */
2759class CatchLocationFinder : public StackVisitor {
2760 public:
2761 CatchLocationFinder(Thread* self, const Handle<mirror::Throwable>& exception, Context* context)
2762 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01002763 : StackVisitor(self, context, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002764 self_(self),
2765 exception_(exception),
2766 handle_scope_(self),
2767 this_at_throw_(handle_scope_.NewHandle<mirror::Object>(nullptr)),
Mathieu Chartiere401d142015-04-22 13:56:20 -07002768 catch_method_(nullptr),
2769 throw_method_(nullptr),
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002770 catch_dex_pc_(DexFile::kDexNoIndex),
2771 throw_dex_pc_(DexFile::kDexNoIndex) {
2772 }
2773
2774 bool VisitFrame() OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002775 ArtMethod* method = GetMethod();
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002776 DCHECK(method != nullptr);
2777 if (method->IsRuntimeMethod()) {
2778 // Ignore callee save method.
2779 DCHECK(method->IsCalleeSaveMethod());
2780 return true;
2781 }
2782
2783 uint32_t dex_pc = GetDexPc();
Mathieu Chartiere401d142015-04-22 13:56:20 -07002784 if (throw_method_ == nullptr) {
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002785 // First Java method found. It is either the method that threw the exception,
2786 // or the Java native method that is reporting an exception thrown by
2787 // native code.
2788 this_at_throw_.Assign(GetThisObject());
Mathieu Chartiere401d142015-04-22 13:56:20 -07002789 throw_method_ = method;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002790 throw_dex_pc_ = dex_pc;
2791 }
2792
2793 if (dex_pc != DexFile::kDexNoIndex) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002794 StackHandleScope<1> hs(self_);
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002795 uint32_t found_dex_pc;
2796 Handle<mirror::Class> exception_class(hs.NewHandle(exception_->GetClass()));
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002797 bool unused_clear_exception;
Mathieu Chartiere401d142015-04-22 13:56:20 -07002798 found_dex_pc = method->FindCatchBlock(exception_class, dex_pc, &unused_clear_exception);
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002799 if (found_dex_pc != DexFile::kDexNoIndex) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002800 catch_method_ = method;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002801 catch_dex_pc_ = found_dex_pc;
2802 return false; // End stack walk.
2803 }
2804 }
2805 return true; // Continue stack walk.
2806 }
2807
Mathieu Chartiere401d142015-04-22 13:56:20 -07002808 ArtMethod* GetCatchMethod() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2809 return catch_method_;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002810 }
2811
Mathieu Chartiere401d142015-04-22 13:56:20 -07002812 ArtMethod* GetThrowMethod() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2813 return throw_method_;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002814 }
2815
2816 mirror::Object* GetThisAtThrow() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2817 return this_at_throw_.Get();
2818 }
2819
2820 uint32_t GetCatchDexPc() const {
2821 return catch_dex_pc_;
2822 }
2823
2824 uint32_t GetThrowDexPc() const {
2825 return throw_dex_pc_;
2826 }
2827
2828 private:
2829 Thread* const self_;
2830 const Handle<mirror::Throwable>& exception_;
Mathieu Chartiere401d142015-04-22 13:56:20 -07002831 StackHandleScope<1> handle_scope_;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002832 MutableHandle<mirror::Object> this_at_throw_;
Mathieu Chartiere401d142015-04-22 13:56:20 -07002833 ArtMethod* catch_method_;
2834 ArtMethod* throw_method_;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002835 uint32_t catch_dex_pc_;
2836 uint32_t throw_dex_pc_;
2837
2838 DISALLOW_COPY_AND_ASSIGN(CatchLocationFinder);
2839};
2840
2841void Dbg::PostException(mirror::Throwable* exception_object) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002842 if (!IsDebuggerActive()) {
Ian Rogers0ad5bb82011-12-07 10:16:32 -08002843 return;
2844 }
Sebastien Hertz261bc042015-04-08 09:36:07 +02002845 Thread* const self = Thread::Current();
2846 StackHandleScope<1> handle_scope(self);
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002847 Handle<mirror::Throwable> h_exception(handle_scope.NewHandle(exception_object));
2848 std::unique_ptr<Context> context(Context::Create());
Sebastien Hertz261bc042015-04-08 09:36:07 +02002849 CatchLocationFinder clf(self, h_exception, context.get());
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002850 clf.WalkStack(/* include_transitions */ false);
Sebastien Hertz6995c602014-09-09 12:10:13 +02002851 JDWP::EventLocation exception_throw_location;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002852 SetEventLocation(&exception_throw_location, clf.GetThrowMethod(), clf.GetThrowDexPc());
Sebastien Hertz6995c602014-09-09 12:10:13 +02002853 JDWP::EventLocation exception_catch_location;
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002854 SetEventLocation(&exception_catch_location, clf.GetCatchMethod(), clf.GetCatchDexPc());
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002855
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002856 gJdwpState->PostException(&exception_throw_location, h_exception.Get(), &exception_catch_location,
2857 clf.GetThisAtThrow());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002858}
2859
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002860void Dbg::PostClassPrepare(mirror::Class* c) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002861 if (!IsDebuggerActive()) {
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002862 return;
2863 }
Sebastien Hertz6995c602014-09-09 12:10:13 +02002864 gJdwpState->PostClassPrepare(c);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002865}
2866
Ian Rogers62d6c772013-02-27 08:32:07 -08002867void Dbg::UpdateDebugger(Thread* thread, mirror::Object* this_object,
Mathieu Chartiere401d142015-04-22 13:56:20 -07002868 ArtMethod* m, uint32_t dex_pc,
Sebastien Hertz8379b222014-02-24 17:38:15 +01002869 int event_flags, const JValue* return_value) {
Ian Rogers62d6c772013-02-27 08:32:07 -08002870 if (!IsDebuggerActive() || dex_pc == static_cast<uint32_t>(-2) /* fake method exit */) {
Elliott Hughes2aa2e392012-02-17 17:15:43 -08002871 return;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002872 }
2873
Elliott Hughes86964332012-02-15 19:37:42 -08002874 if (IsBreakpoint(m, dex_pc)) {
2875 event_flags |= kBreakpoint;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002876 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002877
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002878 // If the debugger is single-stepping one of our threads, check to
2879 // see if we're that thread and we've reached a step point.
2880 const SingleStepControl* single_step_control = thread->GetSingleStepControl();
Sebastien Hertz597c4f02015-01-26 17:37:14 +01002881 if (single_step_control != nullptr) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002882 CHECK(!m->IsNative());
Sebastien Hertz597c4f02015-01-26 17:37:14 +01002883 if (single_step_control->GetStepDepth() == JDWP::SD_INTO) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002884 // Step into method calls. We break when the line number
2885 // or method pointer changes. If we're in SS_MIN mode, we
2886 // always stop.
Sebastien Hertz597c4f02015-01-26 17:37:14 +01002887 if (single_step_control->GetMethod() != m) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002888 event_flags |= kSingleStep;
2889 VLOG(jdwp) << "SS new method";
Sebastien Hertz597c4f02015-01-26 17:37:14 +01002890 } else if (single_step_control->GetStepSize() == JDWP::SS_MIN) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002891 event_flags |= kSingleStep;
2892 VLOG(jdwp) << "SS new instruction";
Sebastien Hertzbb43b432014-04-14 11:59:08 +02002893 } else if (single_step_control->ContainsDexPc(dex_pc)) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002894 event_flags |= kSingleStep;
2895 VLOG(jdwp) << "SS new line";
2896 }
Sebastien Hertz597c4f02015-01-26 17:37:14 +01002897 } else if (single_step_control->GetStepDepth() == JDWP::SD_OVER) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002898 // Step over method calls. We break when the line number is
2899 // different and the frame depth is <= the original frame
2900 // depth. (We can't just compare on the method, because we
2901 // might get unrolled past it by an exception, and it's tricky
2902 // to identify recursion.)
2903
2904 int stack_depth = GetStackDepth(thread);
2905
Sebastien Hertz597c4f02015-01-26 17:37:14 +01002906 if (stack_depth < single_step_control->GetStackDepth()) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002907 // Popped up one or more frames, always trigger.
2908 event_flags |= kSingleStep;
2909 VLOG(jdwp) << "SS method pop";
Sebastien Hertz597c4f02015-01-26 17:37:14 +01002910 } else if (stack_depth == single_step_control->GetStackDepth()) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002911 // Same depth, see if we moved.
Sebastien Hertz597c4f02015-01-26 17:37:14 +01002912 if (single_step_control->GetStepSize() == JDWP::SS_MIN) {
Elliott Hughes86964332012-02-15 19:37:42 -08002913 event_flags |= kSingleStep;
2914 VLOG(jdwp) << "SS new instruction";
Sebastien Hertzbb43b432014-04-14 11:59:08 +02002915 } else if (single_step_control->ContainsDexPc(dex_pc)) {
Elliott Hughes2435a572012-02-17 16:07:41 -08002916 event_flags |= kSingleStep;
2917 VLOG(jdwp) << "SS new line";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002918 }
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002919 }
2920 } else {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01002921 CHECK_EQ(single_step_control->GetStepDepth(), JDWP::SD_OUT);
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002922 // Return from the current method. We break when the frame
2923 // depth pops up.
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002924
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002925 // This differs from the "method exit" break in that it stops
2926 // with the PC at the next instruction in the returned-to
2927 // function, rather than the end of the returning function.
Elliott Hughes86964332012-02-15 19:37:42 -08002928
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002929 int stack_depth = GetStackDepth(thread);
Sebastien Hertz597c4f02015-01-26 17:37:14 +01002930 if (stack_depth < single_step_control->GetStackDepth()) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002931 event_flags |= kSingleStep;
2932 VLOG(jdwp) << "SS method pop";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002933 }
2934 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002935 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002936
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002937 // If there's something interesting going on, see if it matches one
2938 // of the debugger filters.
2939 if (event_flags != 0) {
Sebastien Hertz8379b222014-02-24 17:38:15 +01002940 Dbg::PostLocationEvent(m, dex_pc, this_object, event_flags, return_value);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002941 }
2942}
2943
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02002944size_t* Dbg::GetReferenceCounterForEvent(uint32_t instrumentation_event) {
2945 switch (instrumentation_event) {
2946 case instrumentation::Instrumentation::kMethodEntered:
2947 return &method_enter_event_ref_count_;
2948 case instrumentation::Instrumentation::kMethodExited:
2949 return &method_exit_event_ref_count_;
2950 case instrumentation::Instrumentation::kDexPcMoved:
2951 return &dex_pc_change_event_ref_count_;
2952 case instrumentation::Instrumentation::kFieldRead:
2953 return &field_read_event_ref_count_;
2954 case instrumentation::Instrumentation::kFieldWritten:
2955 return &field_write_event_ref_count_;
2956 case instrumentation::Instrumentation::kExceptionCaught:
2957 return &exception_catch_event_ref_count_;
2958 default:
2959 return nullptr;
2960 }
2961}
2962
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002963// Process request while all mutator threads are suspended.
2964void Dbg::ProcessDeoptimizationRequest(const DeoptimizationRequest& request) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002965 instrumentation::Instrumentation* instrumentation = Runtime::Current()->GetInstrumentation();
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07002966 switch (request.GetKind()) {
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002967 case DeoptimizationRequest::kNothing:
2968 LOG(WARNING) << "Ignoring empty deoptimization request.";
2969 break;
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02002970 case DeoptimizationRequest::kRegisterForEvent:
2971 VLOG(jdwp) << StringPrintf("Add debugger as listener for instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07002972 request.InstrumentationEvent());
2973 instrumentation->AddListener(&gDebugInstrumentationListener, request.InstrumentationEvent());
2974 instrumentation_events_ |= request.InstrumentationEvent();
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02002975 break;
2976 case DeoptimizationRequest::kUnregisterForEvent:
2977 VLOG(jdwp) << StringPrintf("Remove debugger as listener for instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07002978 request.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02002979 instrumentation->RemoveListener(&gDebugInstrumentationListener,
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07002980 request.InstrumentationEvent());
2981 instrumentation_events_ &= ~request.InstrumentationEvent();
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02002982 break;
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002983 case DeoptimizationRequest::kFullDeoptimization:
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01002984 VLOG(jdwp) << "Deoptimize the world ...";
Sebastien Hertz0462c4c2015-04-01 16:34:17 +02002985 instrumentation->DeoptimizeEverything(kDbgInstrumentationKey);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01002986 VLOG(jdwp) << "Deoptimize the world DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002987 break;
2988 case DeoptimizationRequest::kFullUndeoptimization:
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01002989 VLOG(jdwp) << "Undeoptimize the world ...";
Sebastien Hertz0462c4c2015-04-01 16:34:17 +02002990 instrumentation->UndeoptimizeEverything(kDbgInstrumentationKey);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01002991 VLOG(jdwp) << "Undeoptimize the world DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002992 break;
2993 case DeoptimizationRequest::kSelectiveDeoptimization:
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07002994 VLOG(jdwp) << "Deoptimize method " << PrettyMethod(request.Method()) << " ...";
2995 instrumentation->Deoptimize(request.Method());
2996 VLOG(jdwp) << "Deoptimize method " << PrettyMethod(request.Method()) << " DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002997 break;
2998 case DeoptimizationRequest::kSelectiveUndeoptimization:
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07002999 VLOG(jdwp) << "Undeoptimize method " << PrettyMethod(request.Method()) << " ...";
3000 instrumentation->Undeoptimize(request.Method());
3001 VLOG(jdwp) << "Undeoptimize method " << PrettyMethod(request.Method()) << " DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003002 break;
3003 default:
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003004 LOG(FATAL) << "Unsupported deoptimization request kind " << request.GetKind();
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003005 break;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003006 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003007}
3008
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003009void Dbg::RequestDeoptimization(const DeoptimizationRequest& req) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003010 if (req.GetKind() == DeoptimizationRequest::kNothing) {
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003011 // Nothing to do.
3012 return;
3013 }
Brian Carlstrom306db812014-09-05 13:01:41 -07003014 MutexLock mu(Thread::Current(), *Locks::deoptimization_lock_);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003015 RequestDeoptimizationLocked(req);
3016}
3017
3018void Dbg::RequestDeoptimizationLocked(const DeoptimizationRequest& req) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003019 switch (req.GetKind()) {
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003020 case DeoptimizationRequest::kRegisterForEvent: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003021 DCHECK_NE(req.InstrumentationEvent(), 0u);
3022 size_t* counter = GetReferenceCounterForEvent(req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003023 CHECK(counter != nullptr) << StringPrintf("No counter for instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003024 req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003025 if (*counter == 0) {
Sebastien Hertz7d2ae432014-05-15 11:26:34 +02003026 VLOG(jdwp) << StringPrintf("Queue request #%zd to start listening to instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003027 deoptimization_requests_.size(), req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003028 deoptimization_requests_.push_back(req);
3029 }
3030 *counter = *counter + 1;
3031 break;
3032 }
3033 case DeoptimizationRequest::kUnregisterForEvent: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003034 DCHECK_NE(req.InstrumentationEvent(), 0u);
3035 size_t* counter = GetReferenceCounterForEvent(req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003036 CHECK(counter != nullptr) << StringPrintf("No counter for instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003037 req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003038 *counter = *counter - 1;
3039 if (*counter == 0) {
Sebastien Hertz7d2ae432014-05-15 11:26:34 +02003040 VLOG(jdwp) << StringPrintf("Queue request #%zd to stop listening to instrumentation event 0x%x",
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003041 deoptimization_requests_.size(), req.InstrumentationEvent());
Sebastien Hertz42cd43f2014-05-13 14:15:41 +02003042 deoptimization_requests_.push_back(req);
3043 }
3044 break;
3045 }
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003046 case DeoptimizationRequest::kFullDeoptimization: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003047 DCHECK(req.Method() == nullptr);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003048 if (full_deoptimization_event_count_ == 0) {
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003049 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
3050 << " for full deoptimization";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003051 deoptimization_requests_.push_back(req);
3052 }
3053 ++full_deoptimization_event_count_;
3054 break;
3055 }
3056 case DeoptimizationRequest::kFullUndeoptimization: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003057 DCHECK(req.Method() == nullptr);
Sebastien Hertze713d932014-05-15 10:48:53 +02003058 DCHECK_GT(full_deoptimization_event_count_, 0U);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003059 --full_deoptimization_event_count_;
3060 if (full_deoptimization_event_count_ == 0) {
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003061 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
3062 << " for full undeoptimization";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003063 deoptimization_requests_.push_back(req);
3064 }
3065 break;
3066 }
3067 case DeoptimizationRequest::kSelectiveDeoptimization: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003068 DCHECK(req.Method() != nullptr);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003069 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003070 << " for deoptimization of " << PrettyMethod(req.Method());
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003071 deoptimization_requests_.push_back(req);
3072 break;
3073 }
3074 case DeoptimizationRequest::kSelectiveUndeoptimization: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003075 DCHECK(req.Method() != nullptr);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003076 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003077 << " for undeoptimization of " << PrettyMethod(req.Method());
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003078 deoptimization_requests_.push_back(req);
3079 break;
3080 }
3081 default: {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003082 LOG(FATAL) << "Unknown deoptimization request kind " << req.GetKind();
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003083 break;
3084 }
3085 }
3086}
3087
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003088void Dbg::ManageDeoptimization() {
3089 Thread* const self = Thread::Current();
3090 {
3091 // Avoid suspend/resume if there is no pending request.
Brian Carlstrom306db812014-09-05 13:01:41 -07003092 MutexLock mu(self, *Locks::deoptimization_lock_);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003093 if (deoptimization_requests_.empty()) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003094 return;
3095 }
3096 }
3097 CHECK_EQ(self->GetState(), kRunnable);
3098 self->TransitionFromRunnableToSuspended(kWaitingForDeoptimization);
3099 // We need to suspend mutator threads first.
3100 Runtime* const runtime = Runtime::Current();
Mathieu Chartierbf9fc582015-03-13 17:21:25 -07003101 runtime->GetThreadList()->SuspendAll(__FUNCTION__);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003102 const ThreadState old_state = self->SetStateUnsafe(kRunnable);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003103 {
Brian Carlstrom306db812014-09-05 13:01:41 -07003104 MutexLock mu(self, *Locks::deoptimization_lock_);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003105 size_t req_index = 0;
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003106 for (DeoptimizationRequest& request : deoptimization_requests_) {
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01003107 VLOG(jdwp) << "Process deoptimization request #" << req_index++;
Sebastien Hertz4d25df32014-03-21 17:44:46 +01003108 ProcessDeoptimizationRequest(request);
3109 }
3110 deoptimization_requests_.clear();
3111 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003112 CHECK_EQ(self->SetStateUnsafe(old_state), kRunnable);
3113 runtime->GetThreadList()->ResumeAll();
3114 self->TransitionFromSuspendedToRunnable();
3115}
3116
Mathieu Chartiere401d142015-04-22 13:56:20 -07003117static bool IsMethodPossiblyInlined(Thread* self, ArtMethod* m)
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003118 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003119 const DexFile::CodeItem* code_item = m->GetCodeItem();
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003120 if (code_item == nullptr) {
3121 // TODO We should not be asked to watch location in a native or abstract method so the code item
3122 // should never be null. We could just check we never encounter this case.
3123 return false;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003124 }
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003125 // Note: method verifier may cause thread suspension.
3126 self->AssertThreadSuspensionIsAllowable();
Mathieu Chartiere401d142015-04-22 13:56:20 -07003127 StackHandleScope<2> hs(self);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003128 mirror::Class* declaring_class = m->GetDeclaringClass();
3129 Handle<mirror::DexCache> dex_cache(hs.NewHandle(declaring_class->GetDexCache()));
3130 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(declaring_class->GetClassLoader()));
Ian Rogers7b078e82014-09-10 14:44:24 -07003131 verifier::MethodVerifier verifier(self, dex_cache->GetDexFile(), dex_cache, class_loader,
Mathieu Chartiere401d142015-04-22 13:56:20 -07003132 &m->GetClassDef(), code_item, m->GetDexMethodIndex(), m,
Mathieu Chartier4306ef82014-12-19 18:41:47 -08003133 m->GetAccessFlags(), false, true, false, true);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003134 // Note: we don't need to verify the method.
3135 return InlineMethodAnalyser::AnalyseMethodCode(&verifier, nullptr);
3136}
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003137
Mathieu Chartiere401d142015-04-22 13:56:20 -07003138static const Breakpoint* FindFirstBreakpointForMethod(ArtMethod* m)
Sebastien Hertzed2be172014-08-19 15:33:43 +02003139 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::breakpoint_lock_) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003140 for (Breakpoint& breakpoint : gBreakpoints) {
3141 if (breakpoint.Method() == m) {
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003142 return &breakpoint;
3143 }
3144 }
3145 return nullptr;
3146}
3147
Mathieu Chartiere401d142015-04-22 13:56:20 -07003148bool Dbg::MethodHasAnyBreakpoints(ArtMethod* method) {
Mathieu Chartierd8565452015-03-26 09:41:50 -07003149 ReaderMutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
3150 return FindFirstBreakpointForMethod(method) != nullptr;
3151}
3152
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003153// Sanity checks all existing breakpoints on the same method.
Mathieu Chartiere401d142015-04-22 13:56:20 -07003154static void SanityCheckExistingBreakpoints(ArtMethod* m,
Sebastien Hertzf3928792014-11-17 19:00:37 +01003155 DeoptimizationRequest::Kind deoptimization_kind)
Sebastien Hertzed2be172014-08-19 15:33:43 +02003156 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::breakpoint_lock_) {
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003157 for (const Breakpoint& breakpoint : gBreakpoints) {
Sebastien Hertzf3928792014-11-17 19:00:37 +01003158 if (breakpoint.Method() == m) {
3159 CHECK_EQ(deoptimization_kind, breakpoint.GetDeoptimizationKind());
3160 }
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003161 }
Sebastien Hertzf3928792014-11-17 19:00:37 +01003162 instrumentation::Instrumentation* instrumentation = Runtime::Current()->GetInstrumentation();
3163 if (deoptimization_kind == DeoptimizationRequest::kFullDeoptimization) {
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003164 // We should have deoptimized everything but not "selectively" deoptimized this method.
Sebastien Hertzf3928792014-11-17 19:00:37 +01003165 CHECK(instrumentation->AreAllMethodsDeoptimized());
3166 CHECK(!instrumentation->IsDeoptimized(m));
3167 } else if (deoptimization_kind == DeoptimizationRequest::kSelectiveDeoptimization) {
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003168 // We should have "selectively" deoptimized this method.
3169 // Note: while we have not deoptimized everything for this method, we may have done it for
3170 // another event.
Sebastien Hertzf3928792014-11-17 19:00:37 +01003171 CHECK(instrumentation->IsDeoptimized(m));
3172 } else {
3173 // This method does not require deoptimization.
3174 CHECK_EQ(deoptimization_kind, DeoptimizationRequest::kNothing);
3175 CHECK(!instrumentation->IsDeoptimized(m));
3176 }
3177}
3178
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003179// Returns the deoptimization kind required to set a breakpoint in a method.
3180// If a breakpoint has already been set, we also return the first breakpoint
3181// through the given 'existing_brkpt' pointer.
Sebastien Hertzf3928792014-11-17 19:00:37 +01003182static DeoptimizationRequest::Kind GetRequiredDeoptimizationKind(Thread* self,
Mathieu Chartiere401d142015-04-22 13:56:20 -07003183 ArtMethod* m,
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003184 const Breakpoint** existing_brkpt)
Sebastien Hertzf3928792014-11-17 19:00:37 +01003185 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
3186 if (!Dbg::RequiresDeoptimization()) {
3187 // We already run in interpreter-only mode so we don't need to deoptimize anything.
3188 VLOG(jdwp) << "No need for deoptimization when fully running with interpreter for method "
3189 << PrettyMethod(m);
3190 return DeoptimizationRequest::kNothing;
3191 }
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003192 const Breakpoint* first_breakpoint;
Sebastien Hertzf3928792014-11-17 19:00:37 +01003193 {
3194 ReaderMutexLock mu(self, *Locks::breakpoint_lock_);
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003195 first_breakpoint = FindFirstBreakpointForMethod(m);
3196 *existing_brkpt = first_breakpoint;
Sebastien Hertzf3928792014-11-17 19:00:37 +01003197 }
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003198
3199 if (first_breakpoint == nullptr) {
Sebastien Hertzf3928792014-11-17 19:00:37 +01003200 // There is no breakpoint on this method yet: we need to deoptimize. If this method may be
3201 // inlined, we deoptimize everything; otherwise we deoptimize only this method.
3202 // Note: IsMethodPossiblyInlined goes into the method verifier and may cause thread suspension.
3203 // Therefore we must not hold any lock when we call it.
3204 bool need_full_deoptimization = IsMethodPossiblyInlined(self, m);
3205 if (need_full_deoptimization) {
3206 VLOG(jdwp) << "Need full deoptimization because of possible inlining of method "
3207 << PrettyMethod(m);
3208 return DeoptimizationRequest::kFullDeoptimization;
3209 } else {
3210 // We don't need to deoptimize if the method has not been compiled.
3211 ClassLinker* const class_linker = Runtime::Current()->GetClassLinker();
3212 const bool is_compiled = class_linker->GetOatMethodQuickCodeFor(m) != nullptr;
3213 if (is_compiled) {
Sebastien Hertz6963e442014-11-26 22:11:27 +01003214 // If the method may be called through its direct code pointer (without loading
3215 // its updated entrypoint), we need full deoptimization to not miss the breakpoint.
3216 if (class_linker->MayBeCalledWithDirectCodePointer(m)) {
3217 VLOG(jdwp) << "Need full deoptimization because of possible direct code call "
3218 << "into image for compiled method " << PrettyMethod(m);
3219 return DeoptimizationRequest::kFullDeoptimization;
3220 } else {
3221 VLOG(jdwp) << "Need selective deoptimization for compiled method " << PrettyMethod(m);
3222 return DeoptimizationRequest::kSelectiveDeoptimization;
3223 }
Sebastien Hertzf3928792014-11-17 19:00:37 +01003224 } else {
3225 // Method is not compiled: we don't need to deoptimize.
3226 VLOG(jdwp) << "No need for deoptimization for non-compiled method " << PrettyMethod(m);
3227 return DeoptimizationRequest::kNothing;
3228 }
3229 }
3230 } else {
3231 // There is at least one breakpoint for this method: we don't need to deoptimize.
3232 // Let's check that all breakpoints are configured the same way for deoptimization.
3233 VLOG(jdwp) << "Breakpoint already set: no deoptimization is required";
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003234 DeoptimizationRequest::Kind deoptimization_kind = first_breakpoint->GetDeoptimizationKind();
Sebastien Hertzf3928792014-11-17 19:00:37 +01003235 if (kIsDebugBuild) {
3236 ReaderMutexLock mu(self, *Locks::breakpoint_lock_);
3237 SanityCheckExistingBreakpoints(m, deoptimization_kind);
3238 }
3239 return DeoptimizationRequest::kNothing;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003240 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003241}
3242
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003243// Installs a breakpoint at the specified location. Also indicates through the deoptimization
3244// request if we need to deoptimize.
3245void Dbg::WatchLocation(const JDWP::JdwpLocation* location, DeoptimizationRequest* req) {
3246 Thread* const self = Thread::Current();
Mathieu Chartiere401d142015-04-22 13:56:20 -07003247 ArtMethod* m = FromMethodId(location->method_id);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003248 DCHECK(m != nullptr) << "No method for method id " << location->method_id;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003249
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003250 const Breakpoint* existing_breakpoint = nullptr;
3251 const DeoptimizationRequest::Kind deoptimization_kind =
3252 GetRequiredDeoptimizationKind(self, m, &existing_breakpoint);
Sebastien Hertzf3928792014-11-17 19:00:37 +01003253 req->SetKind(deoptimization_kind);
3254 if (deoptimization_kind == DeoptimizationRequest::kSelectiveDeoptimization) {
3255 req->SetMethod(m);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003256 } else {
Sebastien Hertzf3928792014-11-17 19:00:37 +01003257 CHECK(deoptimization_kind == DeoptimizationRequest::kNothing ||
3258 deoptimization_kind == DeoptimizationRequest::kFullDeoptimization);
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003259 req->SetMethod(nullptr);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01003260 }
3261
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003262 {
3263 WriterMutexLock mu(self, *Locks::breakpoint_lock_);
Sebastien Hertzabe93e02014-12-17 16:35:50 +01003264 // If there is at least one existing breakpoint on the same method, the new breakpoint
3265 // must have the same deoptimization kind than the existing breakpoint(s).
3266 DeoptimizationRequest::Kind breakpoint_deoptimization_kind;
3267 if (existing_breakpoint != nullptr) {
3268 breakpoint_deoptimization_kind = existing_breakpoint->GetDeoptimizationKind();
3269 } else {
3270 breakpoint_deoptimization_kind = deoptimization_kind;
3271 }
3272 gBreakpoints.push_back(Breakpoint(m, location->dex_pc, breakpoint_deoptimization_kind));
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003273 VLOG(jdwp) << "Set breakpoint #" << (gBreakpoints.size() - 1) << ": "
3274 << gBreakpoints[gBreakpoints.size() - 1];
3275 }
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003276}
3277
3278// Uninstalls a breakpoint at the specified location. Also indicates through the deoptimization
3279// request if we need to undeoptimize.
3280void Dbg::UnwatchLocation(const JDWP::JdwpLocation* location, DeoptimizationRequest* req) {
Sebastien Hertzed2be172014-08-19 15:33:43 +02003281 WriterMutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003282 ArtMethod* m = FromMethodId(location->method_id);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003283 DCHECK(m != nullptr) << "No method for method id " << location->method_id;
Sebastien Hertzf3928792014-11-17 19:00:37 +01003284 DeoptimizationRequest::Kind deoptimization_kind = DeoptimizationRequest::kNothing;
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003285 for (size_t i = 0, e = gBreakpoints.size(); i < e; ++i) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003286 if (gBreakpoints[i].DexPc() == location->dex_pc && gBreakpoints[i].Method() == m) {
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003287 VLOG(jdwp) << "Removed breakpoint #" << i << ": " << gBreakpoints[i];
Sebastien Hertzf3928792014-11-17 19:00:37 +01003288 deoptimization_kind = gBreakpoints[i].GetDeoptimizationKind();
3289 DCHECK_EQ(deoptimization_kind == DeoptimizationRequest::kSelectiveDeoptimization,
3290 Runtime::Current()->GetInstrumentation()->IsDeoptimized(m));
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003291 gBreakpoints.erase(gBreakpoints.begin() + i);
3292 break;
3293 }
3294 }
3295 const Breakpoint* const existing_breakpoint = FindFirstBreakpointForMethod(m);
3296 if (existing_breakpoint == nullptr) {
3297 // There is no more breakpoint on this method: we need to undeoptimize.
Sebastien Hertzf3928792014-11-17 19:00:37 +01003298 if (deoptimization_kind == DeoptimizationRequest::kFullDeoptimization) {
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003299 // This method required full deoptimization: we need to undeoptimize everything.
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003300 req->SetKind(DeoptimizationRequest::kFullUndeoptimization);
3301 req->SetMethod(nullptr);
Sebastien Hertzf3928792014-11-17 19:00:37 +01003302 } else if (deoptimization_kind == DeoptimizationRequest::kSelectiveDeoptimization) {
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003303 // This method required selective deoptimization: we need to undeoptimize only that method.
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003304 req->SetKind(DeoptimizationRequest::kSelectiveUndeoptimization);
3305 req->SetMethod(m);
Sebastien Hertzf3928792014-11-17 19:00:37 +01003306 } else {
3307 // This method had no need for deoptimization: do nothing.
3308 CHECK_EQ(deoptimization_kind, DeoptimizationRequest::kNothing);
3309 req->SetKind(DeoptimizationRequest::kNothing);
3310 req->SetMethod(nullptr);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01003311 }
3312 } else {
3313 // There is at least one breakpoint for this method: we don't need to undeoptimize.
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07003314 req->SetKind(DeoptimizationRequest::kNothing);
3315 req->SetMethod(nullptr);
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003316 if (kIsDebugBuild) {
Sebastien Hertzf3928792014-11-17 19:00:37 +01003317 SanityCheckExistingBreakpoints(m, deoptimization_kind);
Sebastien Hertz4d1e9ab2014-09-18 16:03:34 +02003318 }
Elliott Hughes86964332012-02-15 19:37:42 -08003319 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003320}
3321
Mathieu Chartiere401d142015-04-22 13:56:20 -07003322bool Dbg::IsForcedInterpreterNeededForCallingImpl(Thread* thread, ArtMethod* m) {
Daniel Mihalyieb076692014-08-22 17:33:31 +02003323 const SingleStepControl* const ssc = thread->GetSingleStepControl();
3324 if (ssc == nullptr) {
3325 // If we are not single-stepping, then we don't have to force interpreter.
3326 return false;
3327 }
3328 if (Runtime::Current()->GetInstrumentation()->InterpretOnly()) {
3329 // If we are in interpreter only mode, then we don't have to force interpreter.
3330 return false;
3331 }
3332
3333 if (!m->IsNative() && !m->IsProxyMethod()) {
3334 // If we want to step into a method, then we have to force interpreter on that call.
3335 if (ssc->GetStepDepth() == JDWP::SD_INTO) {
3336 return true;
3337 }
3338 }
3339 return false;
3340}
3341
Mathieu Chartiere401d142015-04-22 13:56:20 -07003342bool Dbg::IsForcedInterpreterNeededForResolutionImpl(Thread* thread, ArtMethod* m) {
Daniel Mihalyieb076692014-08-22 17:33:31 +02003343 instrumentation::Instrumentation* const instrumentation =
3344 Runtime::Current()->GetInstrumentation();
3345 // If we are in interpreter only mode, then we don't have to force interpreter.
3346 if (instrumentation->InterpretOnly()) {
3347 return false;
3348 }
3349 // We can only interpret pure Java method.
3350 if (m->IsNative() || m->IsProxyMethod()) {
3351 return false;
3352 }
3353 const SingleStepControl* const ssc = thread->GetSingleStepControl();
3354 if (ssc != nullptr) {
3355 // If we want to step into a method, then we have to force interpreter on that call.
3356 if (ssc->GetStepDepth() == JDWP::SD_INTO) {
3357 return true;
3358 }
3359 // If we are stepping out from a static initializer, by issuing a step
3360 // in or step over, that was implicitly invoked by calling a static method,
3361 // then we need to step into that method. Having a lower stack depth than
3362 // the one the single step control has indicates that the step originates
3363 // from the static initializer.
3364 if (ssc->GetStepDepth() != JDWP::SD_OUT &&
3365 ssc->GetStackDepth() > GetStackDepth(thread)) {
3366 return true;
3367 }
3368 }
3369 // There are cases where we have to force interpreter on deoptimized methods,
3370 // because in some cases the call will not be performed by invoking an entry
3371 // point that has been replaced by the deoptimization, but instead by directly
3372 // invoking the compiled code of the method, for example.
3373 return instrumentation->IsDeoptimized(m);
3374}
3375
Mathieu Chartiere401d142015-04-22 13:56:20 -07003376bool Dbg::IsForcedInstrumentationNeededForResolutionImpl(Thread* thread, ArtMethod* m) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07003377 // The upcall can be null and in that case we don't need to do anything.
Daniel Mihalyieb076692014-08-22 17:33:31 +02003378 if (m == nullptr) {
3379 return false;
3380 }
3381 instrumentation::Instrumentation* const instrumentation =
3382 Runtime::Current()->GetInstrumentation();
3383 // If we are in interpreter only mode, then we don't have to force interpreter.
3384 if (instrumentation->InterpretOnly()) {
3385 return false;
3386 }
3387 // We can only interpret pure Java method.
3388 if (m->IsNative() || m->IsProxyMethod()) {
3389 return false;
3390 }
3391 const SingleStepControl* const ssc = thread->GetSingleStepControl();
3392 if (ssc != nullptr) {
3393 // If we are stepping out from a static initializer, by issuing a step
3394 // out, that was implicitly invoked by calling a static method, then we
3395 // need to step into the caller of that method. Having a lower stack
3396 // depth than the one the single step control has indicates that the
3397 // step originates from the static initializer.
3398 if (ssc->GetStepDepth() == JDWP::SD_OUT &&
3399 ssc->GetStackDepth() > GetStackDepth(thread)) {
3400 return true;
3401 }
3402 }
3403 // If we are returning from a static intializer, that was implicitly
3404 // invoked by calling a static method and the caller is deoptimized,
3405 // then we have to deoptimize the stack without forcing interpreter
3406 // on the static method that was called originally. This problem can
3407 // be solved easily by forcing instrumentation on the called method,
3408 // because the instrumentation exit hook will recognise the need of
3409 // stack deoptimization by calling IsForcedInterpreterNeededForUpcall.
3410 return instrumentation->IsDeoptimized(m);
3411}
3412
Mathieu Chartiere401d142015-04-22 13:56:20 -07003413bool Dbg::IsForcedInterpreterNeededForUpcallImpl(Thread* thread, ArtMethod* m) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07003414 // The upcall can be null and in that case we don't need to do anything.
Daniel Mihalyieb076692014-08-22 17:33:31 +02003415 if (m == nullptr) {
3416 return false;
3417 }
3418 instrumentation::Instrumentation* const instrumentation =
3419 Runtime::Current()->GetInstrumentation();
3420 // If we are in interpreter only mode, then we don't have to force interpreter.
3421 if (instrumentation->InterpretOnly()) {
3422 return false;
3423 }
3424 // We can only interpret pure Java method.
3425 if (m->IsNative() || m->IsProxyMethod()) {
3426 return false;
3427 }
3428 const SingleStepControl* const ssc = thread->GetSingleStepControl();
3429 if (ssc != nullptr) {
3430 // The debugger is not interested in what is happening under the level
3431 // of the step, thus we only force interpreter when we are not below of
3432 // the step.
3433 if (ssc->GetStackDepth() >= GetStackDepth(thread)) {
3434 return true;
3435 }
3436 }
3437 // We have to require stack deoptimization if the upcall is deoptimized.
3438 return instrumentation->IsDeoptimized(m);
3439}
3440
Jeff Hao449db332013-04-12 18:30:52 -07003441// Scoped utility class to suspend a thread so that we may do tasks such as walk its stack. Doesn't
3442// cause suspension if the thread is the current thread.
3443class ScopedThreadSuspension {
3444 public:
Ian Rogers33e95662013-05-20 20:29:14 -07003445 ScopedThreadSuspension(Thread* self, JDWP::ObjectId thread_id)
Sebastien Hertz52d131d2014-03-13 16:17:40 +01003446 LOCKS_EXCLUDED(Locks::thread_list_lock_)
Ian Rogers33e95662013-05-20 20:29:14 -07003447 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) :
Ian Rogersf3d874c2014-07-17 18:52:42 -07003448 thread_(nullptr),
Jeff Hao449db332013-04-12 18:30:52 -07003449 error_(JDWP::ERR_NONE),
3450 self_suspend_(false),
Ian Rogers33e95662013-05-20 20:29:14 -07003451 other_suspend_(false) {
Jeff Hao449db332013-04-12 18:30:52 -07003452 ScopedObjectAccessUnchecked soa(self);
Sebastien Hertz69206392015-04-07 15:54:25 +02003453 thread_ = DecodeThread(soa, thread_id, &error_);
Jeff Hao449db332013-04-12 18:30:52 -07003454 if (error_ == JDWP::ERR_NONE) {
3455 if (thread_ == soa.Self()) {
3456 self_suspend_ = true;
3457 } else {
3458 soa.Self()->TransitionFromRunnableToSuspended(kWaitingForDebuggerSuspension);
Sebastien Hertz6995c602014-09-09 12:10:13 +02003459 jobject thread_peer = Dbg::GetObjectRegistry()->GetJObject(thread_id);
Jeff Hao449db332013-04-12 18:30:52 -07003460 bool timed_out;
Ian Rogers4ad5cd32014-11-11 23:08:07 -08003461 ThreadList* thread_list = Runtime::Current()->GetThreadList();
3462 Thread* suspended_thread = thread_list->SuspendThreadByPeer(thread_peer, true, true,
3463 &timed_out);
Jeff Hao449db332013-04-12 18:30:52 -07003464 CHECK_EQ(soa.Self()->TransitionFromSuspendedToRunnable(), kWaitingForDebuggerSuspension);
Ian Rogersf3d874c2014-07-17 18:52:42 -07003465 if (suspended_thread == nullptr) {
Jeff Hao449db332013-04-12 18:30:52 -07003466 // Thread terminated from under us while suspending.
3467 error_ = JDWP::ERR_INVALID_THREAD;
3468 } else {
3469 CHECK_EQ(suspended_thread, thread_);
3470 other_suspend_ = true;
3471 }
3472 }
3473 }
Elliott Hughes2435a572012-02-17 16:07:41 -08003474 }
Elliott Hughes86964332012-02-15 19:37:42 -08003475
Jeff Hao449db332013-04-12 18:30:52 -07003476 Thread* GetThread() const {
3477 return thread_;
3478 }
3479
3480 JDWP::JdwpError GetError() const {
3481 return error_;
3482 }
3483
3484 ~ScopedThreadSuspension() {
3485 if (other_suspend_) {
3486 Runtime::Current()->GetThreadList()->Resume(thread_, true);
3487 }
3488 }
3489
3490 private:
3491 Thread* thread_;
3492 JDWP::JdwpError error_;
3493 bool self_suspend_;
3494 bool other_suspend_;
3495};
3496
3497JDWP::JdwpError Dbg::ConfigureStep(JDWP::ObjectId thread_id, JDWP::JdwpStepSize step_size,
3498 JDWP::JdwpStepDepth step_depth) {
3499 Thread* self = Thread::Current();
3500 ScopedThreadSuspension sts(self, thread_id);
3501 if (sts.GetError() != JDWP::ERR_NONE) {
3502 return sts.GetError();
3503 }
3504
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003505 // Work out what ArtMethod* we're in, the current line number, and how deep the stack currently
Elliott Hughes2435a572012-02-17 16:07:41 -08003506 // is for step-out.
Ian Rogers0399dde2012-06-06 17:09:28 -07003507 struct SingleStepStackVisitor : public StackVisitor {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003508 explicit SingleStepStackVisitor(Thread* thread) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01003509 : StackVisitor(thread, nullptr, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
3510 stack_depth(0),
3511 method(nullptr),
3512 line_number(-1) {}
Ian Rogersca190662012-06-26 15:45:57 -07003513
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003514 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
3515 // annotalysis.
3516 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003517 ArtMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07003518 if (!m->IsRuntimeMethod()) {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003519 ++stack_depth;
3520 if (method == nullptr) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08003521 mirror::DexCache* dex_cache = m->GetDeclaringClass()->GetDexCache();
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003522 method = m;
Ian Rogersc0542af2014-09-03 16:16:56 -07003523 if (dex_cache != nullptr) {
Ian Rogers4445a7e2012-10-05 17:19:13 -07003524 const DexFile& dex_file = *dex_cache->GetDexFile();
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003525 line_number = dex_file.GetLineNumFromPC(m, GetDexPc());
Elliott Hughes2435a572012-02-17 16:07:41 -08003526 }
Elliott Hughes86964332012-02-15 19:37:42 -08003527 }
3528 }
Elliott Hughes530fa002012-03-12 11:44:49 -07003529 return true;
Elliott Hughes86964332012-02-15 19:37:42 -08003530 }
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003531
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003532 int stack_depth;
Mathieu Chartiere401d142015-04-22 13:56:20 -07003533 ArtMethod* method;
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003534 int32_t line_number;
Elliott Hughes86964332012-02-15 19:37:42 -08003535 };
Jeff Hao449db332013-04-12 18:30:52 -07003536
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003537 Thread* const thread = sts.GetThread();
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003538 SingleStepStackVisitor visitor(thread);
Ian Rogers0399dde2012-06-06 17:09:28 -07003539 visitor.WalkStack();
Elliott Hughes86964332012-02-15 19:37:42 -08003540
Elliott Hughes2435a572012-02-17 16:07:41 -08003541 // Find the dex_pc values that correspond to the current line, for line-based single-stepping.
Elliott Hughes2435a572012-02-17 16:07:41 -08003542 struct DebugCallbackContext {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003543 explicit DebugCallbackContext(SingleStepControl* single_step_control_cb,
3544 int32_t line_number_cb, const DexFile::CodeItem* code_item)
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003545 : single_step_control_(single_step_control_cb), line_number_(line_number_cb),
3546 code_item_(code_item), last_pc_valid(false), last_pc(0) {
Elliott Hughes2435a572012-02-17 16:07:41 -08003547 }
3548
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003549 static bool Callback(void* raw_context, uint32_t address, uint32_t line_number_cb) {
Elliott Hughes2435a572012-02-17 16:07:41 -08003550 DebugCallbackContext* context = reinterpret_cast<DebugCallbackContext*>(raw_context);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003551 if (static_cast<int32_t>(line_number_cb) == context->line_number_) {
Elliott Hughes2435a572012-02-17 16:07:41 -08003552 if (!context->last_pc_valid) {
3553 // Everything from this address until the next line change is ours.
3554 context->last_pc = address;
3555 context->last_pc_valid = true;
3556 }
3557 // Otherwise, if we're already in a valid range for this line,
3558 // just keep going (shouldn't really happen)...
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003559 } else if (context->last_pc_valid) { // and the line number is new
Elliott Hughes2435a572012-02-17 16:07:41 -08003560 // Add everything from the last entry up until here to the set
3561 for (uint32_t dex_pc = context->last_pc; dex_pc < address; ++dex_pc) {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003562 context->single_step_control_->AddDexPc(dex_pc);
Elliott Hughes2435a572012-02-17 16:07:41 -08003563 }
3564 context->last_pc_valid = false;
3565 }
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003566 return false; // There may be multiple entries for any given line.
Elliott Hughes2435a572012-02-17 16:07:41 -08003567 }
3568
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003569 ~DebugCallbackContext() {
Elliott Hughes2435a572012-02-17 16:07:41 -08003570 // If the line number was the last in the position table...
3571 if (last_pc_valid) {
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003572 size_t end = code_item_->insns_size_in_code_units_;
Elliott Hughes2435a572012-02-17 16:07:41 -08003573 for (uint32_t dex_pc = last_pc; dex_pc < end; ++dex_pc) {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003574 single_step_control_->AddDexPc(dex_pc);
Elliott Hughes2435a572012-02-17 16:07:41 -08003575 }
3576 }
3577 }
3578
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003579 SingleStepControl* const single_step_control_;
3580 const int32_t line_number_;
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003581 const DexFile::CodeItem* const code_item_;
Elliott Hughes2435a572012-02-17 16:07:41 -08003582 bool last_pc_valid;
3583 uint32_t last_pc;
3584 };
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003585
3586 // Allocate single step.
Sebastien Hertz1558b572015-02-25 15:05:59 +01003587 SingleStepControl* single_step_control =
3588 new (std::nothrow) SingleStepControl(step_size, step_depth,
3589 visitor.stack_depth, visitor.method);
3590 if (single_step_control == nullptr) {
3591 LOG(ERROR) << "Failed to allocate SingleStepControl";
3592 return JDWP::ERR_OUT_OF_MEMORY;
3593 }
3594
Mathieu Chartiere401d142015-04-22 13:56:20 -07003595 ArtMethod* m = single_step_control->GetMethod();
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003596 const int32_t line_number = visitor.line_number;
Sebastien Hertz52f5f932015-05-28 11:00:57 +02003597 // Note: if the thread is not running Java code (pure native thread), there is no "current"
3598 // method on the stack (and no line number either).
3599 if (m != nullptr && !m->IsNative()) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003600 const DexFile::CodeItem* const code_item = m->GetCodeItem();
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003601 DebugCallbackContext context(single_step_control, line_number, code_item);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003602 m->GetDexFile()->DecodeDebugInfo(code_item, m->IsStatic(), m->GetDexMethodIndex(),
Ian Rogersc0542af2014-09-03 16:16:56 -07003603 DebugCallbackContext::Callback, nullptr, &context);
Elliott Hughes3e2e1a22012-02-21 11:33:41 -08003604 }
Elliott Hughes2435a572012-02-17 16:07:41 -08003605
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003606 // Activate single-step in the thread.
3607 thread->ActivateSingleStepControl(single_step_control);
Elliott Hughes86964332012-02-15 19:37:42 -08003608
Elliott Hughes2435a572012-02-17 16:07:41 -08003609 if (VLOG_IS_ON(jdwp)) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003610 VLOG(jdwp) << "Single-step thread: " << *thread;
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003611 VLOG(jdwp) << "Single-step step size: " << single_step_control->GetStepSize();
3612 VLOG(jdwp) << "Single-step step depth: " << single_step_control->GetStepDepth();
3613 VLOG(jdwp) << "Single-step current method: " << PrettyMethod(single_step_control->GetMethod());
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003614 VLOG(jdwp) << "Single-step current line: " << line_number;
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003615 VLOG(jdwp) << "Single-step current stack depth: " << single_step_control->GetStackDepth();
Elliott Hughes2435a572012-02-17 16:07:41 -08003616 VLOG(jdwp) << "Single-step dex_pc values:";
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003617 for (uint32_t dex_pc : single_step_control->GetDexPcs()) {
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003618 VLOG(jdwp) << StringPrintf(" %#x", dex_pc);
Elliott Hughes2435a572012-02-17 16:07:41 -08003619 }
3620 }
3621
3622 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003623}
3624
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003625void Dbg::UnconfigureStep(JDWP::ObjectId thread_id) {
3626 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogersc0542af2014-09-03 16:16:56 -07003627 JDWP::JdwpError error;
3628 Thread* thread = DecodeThread(soa, thread_id, &error);
Sebastien Hertz87118ed2013-11-26 17:57:18 +01003629 if (error == JDWP::ERR_NONE) {
Sebastien Hertz597c4f02015-01-26 17:37:14 +01003630 thread->DeactivateSingleStepControl();
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003631 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003632}
3633
Elliott Hughes45651fd2012-02-21 15:48:20 -08003634static char JdwpTagToShortyChar(JDWP::JdwpTag tag) {
3635 switch (tag) {
3636 default:
3637 LOG(FATAL) << "unknown JDWP tag: " << PrintableChar(tag);
Ian Rogersfc787ec2014-10-09 21:56:44 -07003638 UNREACHABLE();
Elliott Hughes45651fd2012-02-21 15:48:20 -08003639
3640 // Primitives.
3641 case JDWP::JT_BYTE: return 'B';
3642 case JDWP::JT_CHAR: return 'C';
3643 case JDWP::JT_FLOAT: return 'F';
3644 case JDWP::JT_DOUBLE: return 'D';
3645 case JDWP::JT_INT: return 'I';
3646 case JDWP::JT_LONG: return 'J';
3647 case JDWP::JT_SHORT: return 'S';
3648 case JDWP::JT_VOID: return 'V';
3649 case JDWP::JT_BOOLEAN: return 'Z';
3650
3651 // Reference types.
3652 case JDWP::JT_ARRAY:
3653 case JDWP::JT_OBJECT:
3654 case JDWP::JT_STRING:
3655 case JDWP::JT_THREAD:
3656 case JDWP::JT_THREAD_GROUP:
3657 case JDWP::JT_CLASS_LOADER:
3658 case JDWP::JT_CLASS_OBJECT:
3659 return 'L';
3660 }
3661}
3662
Elliott Hughes88d63092013-01-09 09:55:54 -08003663JDWP::JdwpError Dbg::InvokeMethod(JDWP::ObjectId thread_id, JDWP::ObjectId object_id,
3664 JDWP::RefTypeId class_id, JDWP::MethodId method_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003665 uint32_t arg_count, uint64_t* arg_values,
3666 JDWP::JdwpTag* arg_types, uint32_t options,
3667 JDWP::JdwpTag* pResultTag, uint64_t* pResultValue,
3668 JDWP::ObjectId* pExceptionId) {
Elliott Hughesd07986f2011-12-06 18:27:45 -08003669 ThreadList* thread_list = Runtime::Current()->GetThreadList();
3670
Ian Rogersc0542af2014-09-03 16:16:56 -07003671 Thread* targetThread = nullptr;
Sebastien Hertz1558b572015-02-25 15:05:59 +01003672 std::unique_ptr<DebugInvokeReq> req;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003673 Thread* self = Thread::Current();
Elliott Hughesd07986f2011-12-06 18:27:45 -08003674 {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003675 ScopedObjectAccessUnchecked soa(self);
Ian Rogersc0542af2014-09-03 16:16:56 -07003676 JDWP::JdwpError error;
3677 targetThread = DecodeThread(soa, thread_id, &error);
Elliott Hughes221229c2013-01-08 18:17:50 -08003678 if (error != JDWP::ERR_NONE) {
3679 LOG(ERROR) << "InvokeMethod request for invalid thread id " << thread_id;
3680 return error;
Elliott Hughesd07986f2011-12-06 18:27:45 -08003681 }
Sebastien Hertz1558b572015-02-25 15:05:59 +01003682 if (targetThread->GetInvokeReq() != nullptr) {
3683 // Thread is already invoking a method on behalf of the debugger.
3684 LOG(ERROR) << "InvokeMethod request for thread already invoking a method: " << *targetThread;
3685 return JDWP::ERR_ALREADY_INVOKING;
3686 }
3687 if (!targetThread->IsReadyForDebugInvoke()) {
3688 // Thread is not suspended by an event so it cannot invoke a method.
Elliott Hughesd07986f2011-12-06 18:27:45 -08003689 LOG(ERROR) << "InvokeMethod request for thread not stopped by event: " << *targetThread;
3690 return JDWP::ERR_INVALID_THREAD;
3691 }
3692
3693 /*
3694 * We currently have a bug where we don't successfully resume the
3695 * target thread if the suspend count is too deep. We're expected to
3696 * require one "resume" for each "suspend", but when asked to execute
3697 * a method we have to resume fully and then re-suspend it back to the
3698 * same level. (The easiest way to cause this is to type "suspend"
3699 * multiple times in jdb.)
3700 *
3701 * It's unclear what this means when the event specifies "resume all"
3702 * and some threads are suspended more deeply than others. This is
3703 * a rare problem, so for now we just prevent it from hanging forever
3704 * by rejecting the method invocation request. Without this, we will
3705 * be stuck waiting on a suspended thread.
3706 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003707 int suspend_count;
3708 {
Ian Rogers50b35e22012-10-04 10:09:15 -07003709 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003710 suspend_count = targetThread->GetSuspendCount();
3711 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08003712 if (suspend_count > 1) {
3713 LOG(ERROR) << *targetThread << " suspend count too deep for method invocation: " << suspend_count;
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003714 return JDWP::ERR_THREAD_SUSPENDED; // Probably not expected here.
Elliott Hughesd07986f2011-12-06 18:27:45 -08003715 }
3716
Ian Rogersc0542af2014-09-03 16:16:56 -07003717 mirror::Object* receiver = gRegistry->Get<mirror::Object*>(object_id, &error);
3718 if (error != JDWP::ERR_NONE) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08003719 return JDWP::ERR_INVALID_OBJECT;
3720 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003721
Sebastien Hertz1558b572015-02-25 15:05:59 +01003722 gRegistry->Get<mirror::Object*>(thread_id, &error);
Ian Rogersc0542af2014-09-03 16:16:56 -07003723 if (error != JDWP::ERR_NONE) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08003724 return JDWP::ERR_INVALID_OBJECT;
3725 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003726
Ian Rogersc0542af2014-09-03 16:16:56 -07003727 mirror::Class* c = DecodeClass(class_id, &error);
3728 if (c == nullptr) {
3729 return error;
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08003730 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003731
Mathieu Chartiere401d142015-04-22 13:56:20 -07003732 ArtMethod* m = FromMethodId(method_id);
Ian Rogersc0542af2014-09-03 16:16:56 -07003733 if (m->IsStatic() != (receiver == nullptr)) {
Elliott Hughes45651fd2012-02-21 15:48:20 -08003734 return JDWP::ERR_INVALID_METHODID;
3735 }
3736 if (m->IsStatic()) {
3737 if (m->GetDeclaringClass() != c) {
3738 return JDWP::ERR_INVALID_METHODID;
3739 }
3740 } else {
3741 if (!m->GetDeclaringClass()->IsAssignableFrom(c)) {
3742 return JDWP::ERR_INVALID_METHODID;
3743 }
3744 }
3745
3746 // Check the argument list matches the method.
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003747 uint32_t shorty_len = 0;
3748 const char* shorty = m->GetShorty(&shorty_len);
3749 if (shorty_len - 1 != arg_count) {
Elliott Hughes45651fd2012-02-21 15:48:20 -08003750 return JDWP::ERR_ILLEGAL_ARGUMENT;
3751 }
Elliott Hughes09201632013-04-15 15:50:07 -07003752
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003753 {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003754 StackHandleScope<2> hs(soa.Self());
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003755 HandleWrapper<mirror::Object> h_obj(hs.NewHandleWrapper(&receiver));
3756 HandleWrapper<mirror::Class> h_klass(hs.NewHandleWrapper(&c));
3757 const DexFile::TypeList* types = m->GetParameterTypeList();
3758 for (size_t i = 0; i < arg_count; ++i) {
3759 if (shorty[i + 1] != JdwpTagToShortyChar(arg_types[i])) {
Elliott Hughes09201632013-04-15 15:50:07 -07003760 return JDWP::ERR_ILLEGAL_ARGUMENT;
3761 }
3762
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003763 if (shorty[i + 1] == 'L') {
3764 // Did we really get an argument of an appropriate reference type?
Ian Rogersa0485602014-12-02 15:48:04 -08003765 mirror::Class* parameter_type =
Mathieu Chartiere401d142015-04-22 13:56:20 -07003766 m->GetClassFromTypeIndex(types->GetTypeItem(i).type_idx_, true);
Ian Rogersc0542af2014-09-03 16:16:56 -07003767 mirror::Object* argument = gRegistry->Get<mirror::Object*>(arg_values[i], &error);
3768 if (error != JDWP::ERR_NONE) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003769 return JDWP::ERR_INVALID_OBJECT;
3770 }
Ian Rogersc0542af2014-09-03 16:16:56 -07003771 if (argument != nullptr && !argument->InstanceOf(parameter_type)) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003772 return JDWP::ERR_ILLEGAL_ARGUMENT;
3773 }
3774
3775 // Turn the on-the-wire ObjectId into a jobject.
3776 jvalue& v = reinterpret_cast<jvalue&>(arg_values[i]);
3777 v.l = gRegistry->GetJObject(arg_values[i]);
3778 }
Elliott Hughes09201632013-04-15 15:50:07 -07003779 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003780 }
3781
Sebastien Hertz1558b572015-02-25 15:05:59 +01003782 // Allocates a DebugInvokeReq.
3783 req.reset(new (std::nothrow) DebugInvokeReq(receiver, c, m, options, arg_values, arg_count));
3784 if (req.get() == nullptr) {
3785 LOG(ERROR) << "Failed to allocate DebugInvokeReq";
3786 return JDWP::ERR_OUT_OF_MEMORY;
3787 }
3788
3789 // Attach the DebugInvokeReq to the target thread so it executes the method when
3790 // it is resumed. Once the invocation completes, it will detach it and signal us
3791 // before suspending itself.
3792 targetThread->SetDebugInvokeReq(req.get());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003793 }
3794
3795 // The fact that we've released the thread list lock is a bit risky --- if the thread goes
3796 // away we're sitting high and dry -- but we must release this before the ResumeAllThreads
3797 // call, and it's unwise to hold it during WaitForSuspend.
3798
3799 {
3800 /*
3801 * We change our (JDWP thread) status, which should be THREAD_RUNNING,
Elliott Hughes81ff3182012-03-23 20:35:56 -07003802 * so we can suspend for a GC if the invoke request causes us to
Elliott Hughesd07986f2011-12-06 18:27:45 -08003803 * run out of memory. It's also a good idea to change it before locking
3804 * the invokeReq mutex, although that should never be held for long.
3805 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003806 self->TransitionFromRunnableToSuspended(kWaitingForDebuggerSend);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003807
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003808 VLOG(jdwp) << " Transferring control to event thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08003809 {
Sebastien Hertzd38667a2013-11-25 15:43:54 +01003810 MutexLock mu(self, req->lock);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003811
3812 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003813 VLOG(jdwp) << " Resuming all threads";
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003814 thread_list->UndoDebuggerSuspensions();
Elliott Hughesd07986f2011-12-06 18:27:45 -08003815 } else {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003816 VLOG(jdwp) << " Resuming event thread only";
Elliott Hughesd07986f2011-12-06 18:27:45 -08003817 thread_list->Resume(targetThread, true);
3818 }
3819
Sebastien Hertz2bf93f42015-01-09 18:44:05 +01003820 // The target thread is resumed but needs the JDWP token we're holding.
3821 // We release it now and will acquire it again when the invocation is
3822 // complete and the target thread suspends itself.
3823 gJdwpState->ReleaseJdwpTokenForCommand();
3824
Elliott Hughesd07986f2011-12-06 18:27:45 -08003825 // Wait for the request to finish executing.
Sebastien Hertz1558b572015-02-25 15:05:59 +01003826 while (targetThread->GetInvokeReq() != nullptr) {
Sebastien Hertzd38667a2013-11-25 15:43:54 +01003827 req->cond.Wait(self);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003828 }
3829 }
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003830 VLOG(jdwp) << " Control has returned from event thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08003831
3832 /* wait for thread to re-suspend itself */
Brian Carlstromdf629502013-07-17 22:39:56 -07003833 SuspendThread(thread_id, false /* request_suspension */);
Sebastien Hertz2bf93f42015-01-09 18:44:05 +01003834
3835 // Now the thread is suspended again, we can re-acquire the JDWP token.
3836 gJdwpState->AcquireJdwpTokenForCommand();
3837
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003838 self->TransitionFromSuspendedToRunnable();
Elliott Hughesd07986f2011-12-06 18:27:45 -08003839 }
3840
3841 /*
3842 * Suspend the threads. We waited for the target thread to suspend
3843 * itself, so all we need to do is suspend the others.
3844 *
Sebastien Hertz2bf93f42015-01-09 18:44:05 +01003845 * The SuspendAllForDebugger() call will double-suspend the event thread,
Elliott Hughesd07986f2011-12-06 18:27:45 -08003846 * so we want to resume the target thread once to keep the books straight.
3847 */
3848 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003849 self->TransitionFromRunnableToSuspended(kWaitingForDebuggerSuspension);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003850 VLOG(jdwp) << " Suspending all threads";
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003851 thread_list->SuspendAllForDebugger();
3852 self->TransitionFromSuspendedToRunnable();
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003853 VLOG(jdwp) << " Resuming event thread to balance the count";
Elliott Hughesd07986f2011-12-06 18:27:45 -08003854 thread_list->Resume(targetThread, true);
3855 }
3856
3857 // Copy the result.
3858 *pResultTag = req->result_tag;
Sebastien Hertz1558b572015-02-25 15:05:59 +01003859 *pResultValue = req->result_value;
Elliott Hughesd07986f2011-12-06 18:27:45 -08003860 *pExceptionId = req->exception;
3861 return req->error;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003862}
3863
3864void Dbg::ExecuteMethod(DebugInvokeReq* pReq) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003865 ScopedObjectAccess soa(Thread::Current());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003866
Elliott Hughes81ff3182012-03-23 20:35:56 -07003867 // We can be called while an exception is pending. We need
Elliott Hughesd07986f2011-12-06 18:27:45 -08003868 // to preserve that across the method invocation.
Mathieu Chartiere401d142015-04-22 13:56:20 -07003869 StackHandleScope<3> hs(soa.Self());
Sebastien Hertz1558b572015-02-25 15:05:59 +01003870 auto old_exception = hs.NewHandle<mirror::Throwable>(soa.Self()->GetException());
3871 soa.Self()->ClearException();
Elliott Hughesd07986f2011-12-06 18:27:45 -08003872
3873 // Translate the method through the vtable, unless the debugger wants to suppress it.
Mathieu Chartiere401d142015-04-22 13:56:20 -07003874 auto* m = pReq->method;
3875 auto image_pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
Sebastien Hertz1558b572015-02-25 15:05:59 +01003876 if ((pReq->options & JDWP::INVOKE_NONVIRTUAL) == 0 && pReq->receiver.Read() != nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003877 ArtMethod* actual_method =
3878 pReq->klass.Read()->FindVirtualMethodForVirtualOrInterface(m, image_pointer_size);
3879 if (actual_method != m) {
3880 VLOG(jdwp) << "ExecuteMethod translated " << PrettyMethod(m)
Sebastien Hertz1558b572015-02-25 15:05:59 +01003881 << " to " << PrettyMethod(actual_method);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003882 m = actual_method;
Elliott Hughes45651fd2012-02-21 15:48:20 -08003883 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08003884 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07003885 VLOG(jdwp) << "ExecuteMethod " << PrettyMethod(m)
Sebastien Hertz1558b572015-02-25 15:05:59 +01003886 << " receiver=" << pReq->receiver.Read()
Sebastien Hertzd38667a2013-11-25 15:43:54 +01003887 << " arg_count=" << pReq->arg_count;
Mathieu Chartiere401d142015-04-22 13:56:20 -07003888 CHECK(m != nullptr);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003889
3890 CHECK_EQ(sizeof(jvalue), sizeof(uint64_t));
3891
Jeff Hao39b6c242015-05-19 20:30:23 -07003892 ScopedLocalRef<jobject> ref(soa.Env(), soa.AddLocalReference<jobject>(pReq->receiver.Read()));
Mathieu Chartiere401d142015-04-22 13:56:20 -07003893 JValue result = InvokeWithJValues(soa, ref.get(), soa.EncodeMethod(m),
Sebastien Hertz1558b572015-02-25 15:05:59 +01003894 reinterpret_cast<jvalue*>(pReq->arg_values));
Elliott Hughesd07986f2011-12-06 18:27:45 -08003895
Mathieu Chartiere401d142015-04-22 13:56:20 -07003896 pReq->result_tag = BasicTagFromDescriptor(m->GetShorty());
Sebastien Hertz1558b572015-02-25 15:05:59 +01003897 const bool is_object_result = (pReq->result_tag == JDWP::JT_OBJECT);
3898 Handle<mirror::Object> object_result = hs.NewHandle(is_object_result ? result.GetL() : nullptr);
3899 Handle<mirror::Throwable> exception = hs.NewHandle(soa.Self()->GetException());
3900 soa.Self()->ClearException();
Sebastien Hertz261bc042015-04-08 09:36:07 +02003901 pReq->exception = gRegistry->Add(exception);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003902 if (pReq->exception != 0) {
Sebastien Hertz1558b572015-02-25 15:05:59 +01003903 VLOG(jdwp) << " JDWP invocation returning with exception=" << exception.Get()
3904 << " " << exception->Dump();
3905 pReq->result_value = 0;
3906 } else if (is_object_result) {
Elliott Hughesd07986f2011-12-06 18:27:45 -08003907 /* if no exception thrown, examine object result more closely */
Sebastien Hertz1558b572015-02-25 15:05:59 +01003908 JDWP::JdwpTag new_tag = TagFromObject(soa, object_result.Get());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003909 if (new_tag != pReq->result_tag) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003910 VLOG(jdwp) << " JDWP promoted result from " << pReq->result_tag << " to " << new_tag;
Elliott Hughesd07986f2011-12-06 18:27:45 -08003911 pReq->result_tag = new_tag;
3912 }
3913
Sebastien Hertz1558b572015-02-25 15:05:59 +01003914 // Register the object in the registry and reference its ObjectId. This ensures
3915 // GC safety and prevents from accessing stale reference if the object is moved.
3916 pReq->result_value = gRegistry->Add(object_result.Get());
3917 } else {
3918 // Primitive result.
3919 DCHECK(IsPrimitiveTag(pReq->result_tag));
3920 pReq->result_value = result.GetJ();
Elliott Hughesd07986f2011-12-06 18:27:45 -08003921 }
3922
Ian Rogersc0542af2014-09-03 16:16:56 -07003923 if (old_exception.Get() != nullptr) {
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003924 soa.Self()->SetException(old_exception.Get());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003925 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003926}
3927
Elliott Hughesd07986f2011-12-06 18:27:45 -08003928/*
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003929 * "request" contains a full JDWP packet, possibly with multiple chunks. We
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003930 * need to process each, accumulate the replies, and ship the whole thing
3931 * back.
3932 *
3933 * Returns "true" if we have a reply. The reply buffer is newly allocated,
3934 * and includes the chunk type/length, followed by the data.
3935 *
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08003936 * OLD-TODO: we currently assume that the request and reply include a single
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003937 * chunk. If this becomes inconvenient we will need to adapt.
3938 */
Ian Rogersc0542af2014-09-03 16:16:56 -07003939bool Dbg::DdmHandlePacket(JDWP::Request* request, uint8_t** pReplyBuf, int* pReplyLen) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003940 Thread* self = Thread::Current();
3941 JNIEnv* env = self->GetJniEnv();
3942
Ian Rogersc0542af2014-09-03 16:16:56 -07003943 uint32_t type = request->ReadUnsigned32("type");
3944 uint32_t length = request->ReadUnsigned32("length");
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003945
3946 // Create a byte[] corresponding to 'request'.
Ian Rogersc0542af2014-09-03 16:16:56 -07003947 size_t request_length = request->size();
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003948 ScopedLocalRef<jbyteArray> dataArray(env, env->NewByteArray(request_length));
Ian Rogersc0542af2014-09-03 16:16:56 -07003949 if (dataArray.get() == nullptr) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003950 LOG(WARNING) << "byte[] allocation failed: " << request_length;
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003951 env->ExceptionClear();
3952 return false;
3953 }
Ian Rogersc0542af2014-09-03 16:16:56 -07003954 env->SetByteArrayRegion(dataArray.get(), 0, request_length,
3955 reinterpret_cast<const jbyte*>(request->data()));
3956 request->Skip(request_length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003957
3958 // Run through and find all chunks. [Currently just find the first.]
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003959 ScopedByteArrayRO contents(env, dataArray.get());
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003960 if (length != request_length) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08003961 LOG(WARNING) << StringPrintf("bad chunk found (len=%u pktLen=%zd)", length, request_length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003962 return false;
3963 }
3964
3965 // Call "private static Chunk dispatch(int type, byte[] data, int offset, int length)".
Elliott Hugheseac76672012-05-24 21:56:51 -07003966 ScopedLocalRef<jobject> chunk(env, env->CallStaticObjectMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
3967 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_dispatch,
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003968 type, dataArray.get(), 0, length));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003969 if (env->ExceptionCheck()) {
3970 LOG(INFO) << StringPrintf("Exception thrown by dispatcher for 0x%08x", type);
3971 env->ExceptionDescribe();
3972 env->ExceptionClear();
3973 return false;
3974 }
3975
Ian Rogersc0542af2014-09-03 16:16:56 -07003976 if (chunk.get() == nullptr) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003977 return false;
3978 }
3979
3980 /*
3981 * Pull the pieces out of the chunk. We copy the results into a
3982 * newly-allocated buffer that the caller can free. We don't want to
3983 * continue using the Chunk object because nothing has a reference to it.
3984 *
3985 * We could avoid this by returning type/data/offset/length and having
3986 * the caller be aware of the object lifetime issues, but that
Elliott Hughes81ff3182012-03-23 20:35:56 -07003987 * integrates the JDWP code more tightly into the rest of the runtime, and doesn't work
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003988 * if we have responses for multiple chunks.
3989 *
3990 * So we're pretty much stuck with copying data around multiple times.
3991 */
Elliott Hugheseac76672012-05-24 21:56:51 -07003992 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 -08003993 jint offset = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_offset);
Elliott Hugheseac76672012-05-24 21:56:51 -07003994 length = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_length);
Elliott Hugheseac76672012-05-24 21:56:51 -07003995 type = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_type);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003996
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003997 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 -07003998 if (length == 0 || replyData.get() == nullptr) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003999 return false;
4000 }
4001
Elliott Hughes4b9702c2013-02-20 18:13:24 -08004002 const int kChunkHdrLen = 8;
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004003 uint8_t* reply = new uint8_t[length + kChunkHdrLen];
Ian Rogersc0542af2014-09-03 16:16:56 -07004004 if (reply == nullptr) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004005 LOG(WARNING) << "malloc failed: " << (length + kChunkHdrLen);
4006 return false;
4007 }
Elliott Hughesf7c3b662011-10-27 12:04:56 -07004008 JDWP::Set4BE(reply + 0, type);
4009 JDWP::Set4BE(reply + 4, length);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004010 env->GetByteArrayRegion(replyData.get(), offset, length, reinterpret_cast<jbyte*>(reply + kChunkHdrLen));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004011
4012 *pReplyBuf = reply;
4013 *pReplyLen = length + kChunkHdrLen;
4014
Elliott Hughes4b9702c2013-02-20 18:13:24 -08004015 VLOG(jdwp) << StringPrintf("dvmHandleDdm returning type=%.4s %p len=%d", reinterpret_cast<char*>(reply), reply, length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07004016 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004017}
4018
Elliott Hughesa2155262011-11-16 16:26:58 -08004019void Dbg::DdmBroadcast(bool connect) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08004020 VLOG(jdwp) << "Broadcasting DDM " << (connect ? "connect" : "disconnect") << "...";
Elliott Hughes47fce012011-10-25 18:37:19 -07004021
4022 Thread* self = Thread::Current();
Ian Rogers50b35e22012-10-04 10:09:15 -07004023 if (self->GetState() != kRunnable) {
4024 LOG(ERROR) << "DDM broadcast in thread state " << self->GetState();
4025 /* try anyway? */
Elliott Hughes47fce012011-10-25 18:37:19 -07004026 }
4027
4028 JNIEnv* env = self->GetJniEnv();
Elliott Hughes47fce012011-10-25 18:37:19 -07004029 jint event = connect ? 1 /*DdmServer.CONNECTED*/ : 2 /*DdmServer.DISCONNECTED*/;
Elliott Hugheseac76672012-05-24 21:56:51 -07004030 env->CallStaticVoidMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
4031 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_broadcast,
4032 event);
Elliott Hughes47fce012011-10-25 18:37:19 -07004033 if (env->ExceptionCheck()) {
4034 LOG(ERROR) << "DdmServer.broadcast " << event << " failed";
4035 env->ExceptionDescribe();
4036 env->ExceptionClear();
4037 }
4038}
4039
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004040void Dbg::DdmConnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08004041 Dbg::DdmBroadcast(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004042}
4043
4044void Dbg::DdmDisconnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08004045 Dbg::DdmBroadcast(false);
Elliott Hughes47fce012011-10-25 18:37:19 -07004046 gDdmThreadNotification = false;
4047}
4048
4049/*
Elliott Hughes82188472011-11-07 18:11:48 -08004050 * Send a notification when a thread starts, stops, or changes its name.
Elliott Hughes47fce012011-10-25 18:37:19 -07004051 *
4052 * Because we broadcast the full set of threads when the notifications are
4053 * first enabled, it's possible for "thread" to be actively executing.
4054 */
Elliott Hughes82188472011-11-07 18:11:48 -08004055void Dbg::DdmSendThreadNotification(Thread* t, uint32_t type) {
Elliott Hughes47fce012011-10-25 18:37:19 -07004056 if (!gDdmThreadNotification) {
4057 return;
4058 }
4059
Elliott Hughes82188472011-11-07 18:11:48 -08004060 if (type == CHUNK_TYPE("THDE")) {
Elliott Hughes47fce012011-10-25 18:37:19 -07004061 uint8_t buf[4];
Ian Rogersd9c4fc92013-10-01 19:45:43 -07004062 JDWP::Set4BE(&buf[0], t->GetThreadId());
Elliott Hughes47fce012011-10-25 18:37:19 -07004063 Dbg::DdmSendChunk(CHUNK_TYPE("THDE"), 4, buf);
Elliott Hughes82188472011-11-07 18:11:48 -08004064 } else {
4065 CHECK(type == CHUNK_TYPE("THCR") || type == CHUNK_TYPE("THNM")) << type;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004066 ScopedObjectAccessUnchecked soa(Thread::Current());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004067 StackHandleScope<1> hs(soa.Self());
4068 Handle<mirror::String> name(hs.NewHandle(t->GetThreadName(soa)));
Ian Rogersc0542af2014-09-03 16:16:56 -07004069 size_t char_count = (name.Get() != nullptr) ? name->GetLength() : 0;
Jeff Hao848f70a2014-01-15 13:49:50 -08004070 const jchar* chars = (name.Get() != nullptr) ? name->GetValue() : nullptr;
Elliott Hughes82188472011-11-07 18:11:48 -08004071
Elliott Hughes21f32d72011-11-09 17:44:13 -08004072 std::vector<uint8_t> bytes;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07004073 JDWP::Append4BE(bytes, t->GetThreadId());
Elliott Hughes545a0642011-11-08 19:10:03 -08004074 JDWP::AppendUtf16BE(bytes, chars, char_count);
Elliott Hughes21f32d72011-11-09 17:44:13 -08004075 CHECK_EQ(bytes.size(), char_count*2 + sizeof(uint32_t)*2);
4076 Dbg::DdmSendChunk(type, bytes);
Elliott Hughes47fce012011-10-25 18:37:19 -07004077 }
4078}
4079
Elliott Hughes47fce012011-10-25 18:37:19 -07004080void Dbg::DdmSetThreadNotification(bool enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004081 // Enable/disable thread notifications.
Elliott Hughes47fce012011-10-25 18:37:19 -07004082 gDdmThreadNotification = enable;
4083 if (enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004084 // Suspend the VM then post thread start notifications for all threads. Threads attaching will
4085 // see a suspension in progress and block until that ends. They then post their own start
4086 // notification.
4087 SuspendVM();
4088 std::list<Thread*> threads;
Ian Rogers50b35e22012-10-04 10:09:15 -07004089 Thread* self = Thread::Current();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004090 {
Ian Rogers50b35e22012-10-04 10:09:15 -07004091 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004092 threads = Runtime::Current()->GetThreadList()->GetList();
4093 }
4094 {
Ian Rogers50b35e22012-10-04 10:09:15 -07004095 ScopedObjectAccess soa(self);
Mathieu Chartier02e25112013-08-14 16:14:24 -07004096 for (Thread* thread : threads) {
4097 Dbg::DdmSendThreadNotification(thread, CHUNK_TYPE("THCR"));
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004098 }
4099 }
4100 ResumeVM();
Elliott Hughes47fce012011-10-25 18:37:19 -07004101 }
4102}
4103
Elliott Hughesa2155262011-11-16 16:26:58 -08004104void Dbg::PostThreadStartOrStop(Thread* t, uint32_t type) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07004105 if (IsDebuggerActive()) {
Sebastien Hertz6995c602014-09-09 12:10:13 +02004106 gJdwpState->PostThreadChange(t, type == CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07004107 }
Elliott Hughes82188472011-11-07 18:11:48 -08004108 Dbg::DdmSendThreadNotification(t, type);
Elliott Hughes47fce012011-10-25 18:37:19 -07004109}
4110
4111void Dbg::PostThreadStart(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004112 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07004113}
4114
4115void Dbg::PostThreadDeath(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004116 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THDE"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004117}
4118
Elliott Hughes82188472011-11-07 18:11:48 -08004119void Dbg::DdmSendChunk(uint32_t type, size_t byte_count, const uint8_t* buf) {
Ian Rogersc0542af2014-09-03 16:16:56 -07004120 CHECK(buf != nullptr);
Elliott Hughes3bb81562011-10-21 18:52:59 -07004121 iovec vec[1];
4122 vec[0].iov_base = reinterpret_cast<void*>(const_cast<uint8_t*>(buf));
4123 vec[0].iov_len = byte_count;
4124 Dbg::DdmSendChunkV(type, vec, 1);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004125}
4126
Elliott Hughes21f32d72011-11-09 17:44:13 -08004127void Dbg::DdmSendChunk(uint32_t type, const std::vector<uint8_t>& bytes) {
4128 DdmSendChunk(type, bytes.size(), &bytes[0]);
4129}
4130
Brian Carlstromf5293522013-07-19 00:24:00 -07004131void Dbg::DdmSendChunkV(uint32_t type, const iovec* iov, int iov_count) {
Ian Rogersc0542af2014-09-03 16:16:56 -07004132 if (gJdwpState == nullptr) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08004133 VLOG(jdwp) << "Debugger thread not active, ignoring DDM send: " << type;
Elliott Hughes3bb81562011-10-21 18:52:59 -07004134 } else {
Elliott Hughescccd84f2011-12-05 16:51:54 -08004135 gJdwpState->DdmSendChunkV(type, iov, iov_count);
Elliott Hughes3bb81562011-10-21 18:52:59 -07004136 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004137}
4138
Mathieu Chartierad466ad2015-01-08 16:28:08 -08004139JDWP::JdwpState* Dbg::GetJdwpState() {
4140 return gJdwpState;
4141}
4142
Elliott Hughes767a1472011-10-26 18:49:02 -07004143int Dbg::DdmHandleHpifChunk(HpifWhen when) {
4144 if (when == HPIF_WHEN_NOW) {
Elliott Hughes7162ad92011-10-27 14:08:42 -07004145 DdmSendHeapInfo(when);
Elliott Hughes767a1472011-10-26 18:49:02 -07004146 return true;
4147 }
4148
4149 if (when != HPIF_WHEN_NEVER && when != HPIF_WHEN_NEXT_GC && when != HPIF_WHEN_EVERY_GC) {
4150 LOG(ERROR) << "invalid HpifWhen value: " << static_cast<int>(when);
4151 return false;
4152 }
4153
4154 gDdmHpifWhen = when;
4155 return true;
4156}
4157
4158bool Dbg::DdmHandleHpsgNhsgChunk(Dbg::HpsgWhen when, Dbg::HpsgWhat what, bool native) {
4159 if (when != HPSG_WHEN_NEVER && when != HPSG_WHEN_EVERY_GC) {
4160 LOG(ERROR) << "invalid HpsgWhen value: " << static_cast<int>(when);
4161 return false;
4162 }
4163
4164 if (what != HPSG_WHAT_MERGED_OBJECTS && what != HPSG_WHAT_DISTINCT_OBJECTS) {
4165 LOG(ERROR) << "invalid HpsgWhat value: " << static_cast<int>(what);
4166 return false;
4167 }
4168
4169 if (native) {
4170 gDdmNhsgWhen = when;
4171 gDdmNhsgWhat = what;
4172 } else {
4173 gDdmHpsgWhen = when;
4174 gDdmHpsgWhat = what;
4175 }
4176 return true;
4177}
4178
Elliott Hughes7162ad92011-10-27 14:08:42 -07004179void Dbg::DdmSendHeapInfo(HpifWhen reason) {
4180 // If there's a one-shot 'when', reset it.
4181 if (reason == gDdmHpifWhen) {
4182 if (gDdmHpifWhen == HPIF_WHEN_NEXT_GC) {
4183 gDdmHpifWhen = HPIF_WHEN_NEVER;
4184 }
4185 }
4186
4187 /*
4188 * Chunk HPIF (client --> server)
4189 *
4190 * Heap Info. General information about the heap,
4191 * suitable for a summary display.
4192 *
4193 * [u4]: number of heaps
4194 *
4195 * For each heap:
4196 * [u4]: heap ID
4197 * [u8]: timestamp in ms since Unix epoch
4198 * [u1]: capture reason (same as 'when' value from server)
4199 * [u4]: max heap size in bytes (-Xmx)
4200 * [u4]: current heap size in bytes
4201 * [u4]: current number of bytes allocated
4202 * [u4]: current number of objects allocated
4203 */
4204 uint8_t heap_count = 1;
Ian Rogers1d54e732013-05-02 21:10:01 -07004205 gc::Heap* heap = Runtime::Current()->GetHeap();
Elliott Hughes21f32d72011-11-09 17:44:13 -08004206 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08004207 JDWP::Append4BE(bytes, heap_count);
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004208 JDWP::Append4BE(bytes, 1); // Heap id (bogus; we only have one heap).
Elliott Hughes545a0642011-11-08 19:10:03 -08004209 JDWP::Append8BE(bytes, MilliTime());
4210 JDWP::Append1BE(bytes, reason);
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004211 JDWP::Append4BE(bytes, heap->GetMaxMemory()); // Max allowed heap size in bytes.
4212 JDWP::Append4BE(bytes, heap->GetTotalMemory()); // Current heap size in bytes.
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08004213 JDWP::Append4BE(bytes, heap->GetBytesAllocated());
4214 JDWP::Append4BE(bytes, heap->GetObjectsAllocated());
Elliott Hughes21f32d72011-11-09 17:44:13 -08004215 CHECK_EQ(bytes.size(), 4U + (heap_count * (4 + 8 + 1 + 4 + 4 + 4 + 4)));
4216 Dbg::DdmSendChunk(CHUNK_TYPE("HPIF"), bytes);
Elliott Hughes767a1472011-10-26 18:49:02 -07004217}
4218
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004219enum HpsgSolidity {
4220 SOLIDITY_FREE = 0,
4221 SOLIDITY_HARD = 1,
4222 SOLIDITY_SOFT = 2,
4223 SOLIDITY_WEAK = 3,
4224 SOLIDITY_PHANTOM = 4,
4225 SOLIDITY_FINALIZABLE = 5,
4226 SOLIDITY_SWEEP = 6,
4227};
4228
4229enum HpsgKind {
4230 KIND_OBJECT = 0,
4231 KIND_CLASS_OBJECT = 1,
4232 KIND_ARRAY_1 = 2,
4233 KIND_ARRAY_2 = 3,
4234 KIND_ARRAY_4 = 4,
4235 KIND_ARRAY_8 = 5,
4236 KIND_UNKNOWN = 6,
4237 KIND_NATIVE = 7,
4238};
4239
4240#define HPSG_PARTIAL (1<<7)
4241#define HPSG_STATE(solidity, kind) ((uint8_t)((((kind) & 0x7) << 3) | ((solidity) & 0x7)))
4242
Ian Rogers30fab402012-01-23 15:43:46 -08004243class HeapChunkContext {
4244 public:
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004245 // Maximum chunk size. Obtain this from the formula:
4246 // (((maximum_heap_size / ALLOCATION_UNIT_SIZE) + 255) / 256) * 2
4247 HeapChunkContext(bool merge, bool native)
Ian Rogers30fab402012-01-23 15:43:46 -08004248 : buf_(16384 - 16),
4249 type_(0),
Mathieu Chartier36dab362014-07-30 14:59:56 -07004250 chunk_overhead_(0) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004251 Reset();
4252 if (native) {
Ian Rogers30fab402012-01-23 15:43:46 -08004253 type_ = CHUNK_TYPE("NHSG");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004254 } else {
Ian Rogers30fab402012-01-23 15:43:46 -08004255 type_ = merge ? CHUNK_TYPE("HPSG") : CHUNK_TYPE("HPSO");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004256 }
4257 }
4258
4259 ~HeapChunkContext() {
Ian Rogers30fab402012-01-23 15:43:46 -08004260 if (p_ > &buf_[0]) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004261 Flush();
4262 }
4263 }
4264
Mathieu Chartier36dab362014-07-30 14:59:56 -07004265 void SetChunkOverhead(size_t chunk_overhead) {
4266 chunk_overhead_ = chunk_overhead;
4267 }
4268
4269 void ResetStartOfNextChunk() {
4270 startOfNextMemoryChunk_ = nullptr;
4271 }
4272
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004273 void EnsureHeader(const void* chunk_ptr) {
Ian Rogers30fab402012-01-23 15:43:46 -08004274 if (!needHeader_) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004275 return;
4276 }
4277
4278 // Start a new HPSx chunk.
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004279 JDWP::Write4BE(&p_, 1); // Heap id (bogus; we only have one heap).
4280 JDWP::Write1BE(&p_, 8); // Size of allocation unit, in bytes.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004281
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004282 JDWP::Write4BE(&p_, reinterpret_cast<uintptr_t>(chunk_ptr)); // virtual address of segment start.
4283 JDWP::Write4BE(&p_, 0); // offset of this piece (relative to the virtual address).
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004284 // [u4]: length of piece, in allocation units
4285 // 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 -08004286 pieceLenField_ = p_;
4287 JDWP::Write4BE(&p_, 0x55555555);
4288 needHeader_ = false;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004289 }
4290
Ian Rogersb726dcb2012-09-05 08:57:23 -07004291 void Flush() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -07004292 if (pieceLenField_ == nullptr) {
Ian Rogersd636b062013-01-18 17:51:18 -08004293 // Flush immediately post Reset (maybe back-to-back Flush). Ignore.
4294 CHECK(needHeader_);
4295 return;
4296 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004297 // Patch the "length of piece" field.
Ian Rogers30fab402012-01-23 15:43:46 -08004298 CHECK_LE(&buf_[0], pieceLenField_);
4299 CHECK_LE(pieceLenField_, p_);
4300 JDWP::Set4BE(pieceLenField_, totalAllocationUnits_);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004301
Ian Rogers30fab402012-01-23 15:43:46 -08004302 Dbg::DdmSendChunk(type_, p_ - &buf_[0], &buf_[0]);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004303 Reset();
4304 }
4305
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004306 static void HeapChunkJavaCallback(void* start, void* end, size_t used_bytes, void* arg)
Ian Rogersb726dcb2012-09-05 08:57:23 -07004307 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_,
4308 Locks::mutator_lock_) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004309 reinterpret_cast<HeapChunkContext*>(arg)->HeapChunkJavaCallback(start, end, used_bytes);
4310 }
4311
4312 static void HeapChunkNativeCallback(void* start, void* end, size_t used_bytes, void* arg)
4313 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4314 reinterpret_cast<HeapChunkContext*>(arg)->HeapChunkNativeCallback(start, end, used_bytes);
Elliott Hughesa2155262011-11-16 16:26:58 -08004315 }
4316
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004317 private:
Elliott Hughesa2155262011-11-16 16:26:58 -08004318 enum { ALLOCATION_UNIT_SIZE = 8 };
4319
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004320 void Reset() {
Ian Rogers30fab402012-01-23 15:43:46 -08004321 p_ = &buf_[0];
Mathieu Chartier36dab362014-07-30 14:59:56 -07004322 ResetStartOfNextChunk();
Ian Rogers30fab402012-01-23 15:43:46 -08004323 totalAllocationUnits_ = 0;
4324 needHeader_ = true;
Ian Rogersc0542af2014-09-03 16:16:56 -07004325 pieceLenField_ = nullptr;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004326 }
4327
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004328 bool IsNative() const {
4329 return type_ == CHUNK_TYPE("NHSG");
4330 }
4331
4332 // Returns true if the object is not an empty chunk.
4333 bool ProcessRecord(void* start, size_t used_bytes) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers30fab402012-01-23 15:43:46 -08004334 // Note: heap call backs cannot manipulate the heap upon which they are crawling, care is taken
4335 // in the following code not to allocate memory, by ensuring buf_ is of the correct size
Ian Rogers15bf2d32012-08-28 17:33:04 -07004336 if (used_bytes == 0) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004337 if (start == nullptr) {
4338 // Reset for start of new heap.
4339 startOfNextMemoryChunk_ = nullptr;
4340 Flush();
4341 }
4342 // Only process in use memory so that free region information
4343 // also includes dlmalloc book keeping.
4344 return false;
Elliott Hughesa2155262011-11-16 16:26:58 -08004345 }
Ian Rogersc0542af2014-09-03 16:16:56 -07004346 if (startOfNextMemoryChunk_ != nullptr) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004347 // Transmit any pending free memory. Native free memory of over kMaxFreeLen could be because
4348 // of the use of mmaps, so don't report. If not free memory then start a new segment.
4349 bool flush = true;
4350 if (start > startOfNextMemoryChunk_) {
4351 const size_t kMaxFreeLen = 2 * kPageSize;
4352 void* free_start = startOfNextMemoryChunk_;
4353 void* free_end = start;
4354 const size_t free_len =
4355 reinterpret_cast<uintptr_t>(free_end) - reinterpret_cast<uintptr_t>(free_start);
4356 if (!IsNative() || free_len < kMaxFreeLen) {
4357 AppendChunk(HPSG_STATE(SOLIDITY_FREE, 0), free_start, free_len, IsNative());
4358 flush = false;
Ian Rogers15bf2d32012-08-28 17:33:04 -07004359 }
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004360 }
4361 if (flush) {
4362 startOfNextMemoryChunk_ = nullptr;
4363 Flush();
4364 }
Ian Rogers15bf2d32012-08-28 17:33:04 -07004365 }
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004366 return true;
Ian Rogers15bf2d32012-08-28 17:33:04 -07004367 }
Elliott Hughesa2155262011-11-16 16:26:58 -08004368
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004369 void HeapChunkNativeCallback(void* start, void* /*end*/, size_t used_bytes)
4370 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4371 if (ProcessRecord(start, used_bytes)) {
4372 uint8_t state = ExamineNativeObject(start);
4373 AppendChunk(state, start, used_bytes + chunk_overhead_, true /*is_native*/);
4374 startOfNextMemoryChunk_ = reinterpret_cast<char*>(start) + used_bytes + chunk_overhead_;
4375 }
4376 }
4377
4378 void HeapChunkJavaCallback(void* start, void* /*end*/, size_t used_bytes)
4379 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_, Locks::mutator_lock_) {
4380 if (ProcessRecord(start, used_bytes)) {
4381 // Determine the type of this chunk.
4382 // OLD-TODO: if context.merge, see if this chunk is different from the last chunk.
4383 // If it's the same, we should combine them.
4384 uint8_t state = ExamineJavaObject(reinterpret_cast<mirror::Object*>(start));
4385 AppendChunk(state, start, used_bytes + chunk_overhead_, false /*is_native*/);
4386 startOfNextMemoryChunk_ = reinterpret_cast<char*>(start) + used_bytes + chunk_overhead_;
4387 }
4388 }
4389
4390 void AppendChunk(uint8_t state, void* ptr, size_t length, bool is_native)
Ian Rogersb726dcb2012-09-05 08:57:23 -07004391 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07004392 // Make sure there's enough room left in the buffer.
4393 // We need to use two bytes for every fractional 256 allocation units used by the chunk plus
4394 // 17 bytes for any header.
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004395 const size_t needed = ((RoundUp(length / ALLOCATION_UNIT_SIZE, 256) / 256) * 2) + 17;
4396 size_t byte_left = &buf_.back() - p_;
4397 if (byte_left < needed) {
4398 if (is_native) {
Pavel Vyssotski7522c742014-12-08 13:38:26 +06004399 // Cannot trigger memory allocation while walking native heap.
Pavel Vyssotski7522c742014-12-08 13:38:26 +06004400 return;
4401 }
Ian Rogers15bf2d32012-08-28 17:33:04 -07004402 Flush();
4403 }
4404
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004405 byte_left = &buf_.back() - p_;
4406 if (byte_left < needed) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07004407 LOG(WARNING) << "Chunk is too big to transmit (chunk_len=" << length << ", "
4408 << needed << " bytes)";
4409 return;
4410 }
4411 EnsureHeader(ptr);
Elliott Hughesa2155262011-11-16 16:26:58 -08004412 // Write out the chunk description.
Ian Rogers15bf2d32012-08-28 17:33:04 -07004413 length /= ALLOCATION_UNIT_SIZE; // Convert to allocation units.
4414 totalAllocationUnits_ += length;
4415 while (length > 256) {
Ian Rogers30fab402012-01-23 15:43:46 -08004416 *p_++ = state | HPSG_PARTIAL;
4417 *p_++ = 255; // length - 1
Ian Rogers15bf2d32012-08-28 17:33:04 -07004418 length -= 256;
Elliott Hughesa2155262011-11-16 16:26:58 -08004419 }
Ian Rogers30fab402012-01-23 15:43:46 -08004420 *p_++ = state;
Ian Rogers15bf2d32012-08-28 17:33:04 -07004421 *p_++ = length - 1;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004422 }
4423
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004424 uint8_t ExamineNativeObject(const void* p) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4425 return p == nullptr ? HPSG_STATE(SOLIDITY_FREE, 0) : HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
4426 }
4427
4428 uint8_t ExamineJavaObject(mirror::Object* o)
Ian Rogersef7d42f2014-01-06 12:55:46 -08004429 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Ian Rogersc0542af2014-09-03 16:16:56 -07004430 if (o == nullptr) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004431 return HPSG_STATE(SOLIDITY_FREE, 0);
4432 }
Elliott Hughesa2155262011-11-16 16:26:58 -08004433 // It's an allocated chunk. Figure out what it is.
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004434 gc::Heap* heap = Runtime::Current()->GetHeap();
4435 if (!heap->IsLiveObjectLocked(o)) {
4436 LOG(ERROR) << "Invalid object in managed heap: " << o;
Elliott Hughesa2155262011-11-16 16:26:58 -08004437 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
4438 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004439 mirror::Class* c = o->GetClass();
Ian Rogersc0542af2014-09-03 16:16:56 -07004440 if (c == nullptr) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004441 // The object was probably just created but hasn't been initialized yet.
4442 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
4443 }
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004444 if (!heap->IsValidObjectAddress(c)) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07004445 LOG(ERROR) << "Invalid class for managed heap object: " << o << " " << c;
Elliott Hughesa2155262011-11-16 16:26:58 -08004446 return HPSG_STATE(SOLIDITY_HARD, KIND_UNKNOWN);
4447 }
Mathieu Chartierf26e1b32015-01-29 10:47:10 -08004448 if (c->GetClass() == nullptr) {
4449 LOG(ERROR) << "Null class of class " << c << " for object " << o;
4450 return HPSG_STATE(SOLIDITY_HARD, KIND_UNKNOWN);
4451 }
Elliott Hughesa2155262011-11-16 16:26:58 -08004452 if (c->IsClassClass()) {
4453 return HPSG_STATE(SOLIDITY_HARD, KIND_CLASS_OBJECT);
4454 }
Elliott Hughesa2155262011-11-16 16:26:58 -08004455 if (c->IsArrayClass()) {
Elliott Hughesa2155262011-11-16 16:26:58 -08004456 switch (c->GetComponentSize()) {
4457 case 1: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_1);
4458 case 2: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_2);
4459 case 4: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
4460 case 8: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_8);
4461 }
4462 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004463 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
4464 }
4465
Ian Rogers30fab402012-01-23 15:43:46 -08004466 std::vector<uint8_t> buf_;
4467 uint8_t* p_;
4468 uint8_t* pieceLenField_;
Ian Rogers15bf2d32012-08-28 17:33:04 -07004469 void* startOfNextMemoryChunk_;
Ian Rogers30fab402012-01-23 15:43:46 -08004470 size_t totalAllocationUnits_;
4471 uint32_t type_;
Ian Rogers30fab402012-01-23 15:43:46 -08004472 bool needHeader_;
Mathieu Chartier36dab362014-07-30 14:59:56 -07004473 size_t chunk_overhead_;
Ian Rogers30fab402012-01-23 15:43:46 -08004474
Elliott Hughesa2155262011-11-16 16:26:58 -08004475 DISALLOW_COPY_AND_ASSIGN(HeapChunkContext);
4476};
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004477
Mathieu Chartier36dab362014-07-30 14:59:56 -07004478static void BumpPointerSpaceCallback(mirror::Object* obj, void* arg)
4479 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) EXCLUSIVE_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
4480 const size_t size = RoundUp(obj->SizeOf(), kObjectAlignment);
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004481 HeapChunkContext::HeapChunkJavaCallback(
Mathieu Chartier36dab362014-07-30 14:59:56 -07004482 obj, reinterpret_cast<void*>(reinterpret_cast<uintptr_t>(obj) + size), size, arg);
4483}
4484
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004485void Dbg::DdmSendHeapSegments(bool native) {
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004486 Dbg::HpsgWhen when = native ? gDdmNhsgWhen : gDdmHpsgWhen;
4487 Dbg::HpsgWhat what = native ? gDdmNhsgWhat : gDdmHpsgWhat;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004488 if (when == HPSG_WHEN_NEVER) {
4489 return;
4490 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004491 // Figure out what kind of chunks we'll be sending.
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004492 CHECK(what == HPSG_WHAT_MERGED_OBJECTS || what == HPSG_WHAT_DISTINCT_OBJECTS)
4493 << static_cast<int>(what);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004494
4495 // First, send a heap start chunk.
4496 uint8_t heap_id[4];
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004497 JDWP::Set4BE(&heap_id[0], 1); // Heap id (bogus; we only have one heap).
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004498 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHST") : CHUNK_TYPE("HPST"), sizeof(heap_id), heap_id);
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07004499 Thread* self = Thread::Current();
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07004500 Locks::mutator_lock_->AssertSharedHeld(self);
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07004501
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004502 // Send a series of heap segment chunks.
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004503 HeapChunkContext context(what == HPSG_WHAT_MERGED_OBJECTS, native);
Elliott Hughesa2155262011-11-16 16:26:58 -08004504 if (native) {
Ian Rogers872dd822014-10-30 11:19:14 -07004505#if defined(HAVE_ANDROID_OS) && defined(USE_DLMALLOC)
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004506 dlmalloc_inspect_all(HeapChunkContext::HeapChunkNativeCallback, &context);
4507 HeapChunkContext::HeapChunkNativeCallback(nullptr, nullptr, 0, &context); // Indicate end of a space.
Christopher Ferrisc4ddc042014-05-13 14:47:50 -07004508#else
4509 UNIMPLEMENTED(WARNING) << "Native heap inspection is only supported with dlmalloc";
4510#endif
Elliott Hughesa2155262011-11-16 16:26:58 -08004511 } else {
Ian Rogers1d54e732013-05-02 21:10:01 -07004512 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartier36dab362014-07-30 14:59:56 -07004513 for (const auto& space : heap->GetContinuousSpaces()) {
4514 if (space->IsDlMallocSpace()) {
Mathieu Chartier4c69d7f2014-10-10 12:45:50 -07004515 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004516 // dlmalloc's chunk header is 2 * sizeof(size_t), but if the previous chunk is in use for an
4517 // allocation then the first sizeof(size_t) may belong to it.
4518 context.SetChunkOverhead(sizeof(size_t));
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004519 space->AsDlMallocSpace()->Walk(HeapChunkContext::HeapChunkJavaCallback, &context);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004520 } else if (space->IsRosAllocSpace()) {
4521 context.SetChunkOverhead(0);
Mathieu Chartier4c69d7f2014-10-10 12:45:50 -07004522 // Need to acquire the mutator lock before the heap bitmap lock with exclusive access since
4523 // RosAlloc's internal logic doesn't know to release and reacquire the heap bitmap lock.
4524 self->TransitionFromRunnableToSuspended(kSuspended);
4525 ThreadList* tl = Runtime::Current()->GetThreadList();
Mathieu Chartierbf9fc582015-03-13 17:21:25 -07004526 tl->SuspendAll(__FUNCTION__);
Mathieu Chartier4c69d7f2014-10-10 12:45:50 -07004527 {
4528 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004529 space->AsRosAllocSpace()->Walk(HeapChunkContext::HeapChunkJavaCallback, &context);
Mathieu Chartier4c69d7f2014-10-10 12:45:50 -07004530 }
4531 tl->ResumeAll();
4532 self->TransitionFromSuspendedToRunnable();
Mathieu Chartier36dab362014-07-30 14:59:56 -07004533 } else if (space->IsBumpPointerSpace()) {
Mathieu Chartier4c69d7f2014-10-10 12:45:50 -07004534 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004535 context.SetChunkOverhead(0);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004536 space->AsBumpPointerSpace()->Walk(BumpPointerSpaceCallback, &context);
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004537 HeapChunkContext::HeapChunkJavaCallback(nullptr, nullptr, 0, &context);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08004538 } else if (space->IsRegionSpace()) {
4539 heap->IncrementDisableMovingGC(self);
4540 self->TransitionFromRunnableToSuspended(kSuspended);
4541 ThreadList* tl = Runtime::Current()->GetThreadList();
Mathieu Chartierbf9fc582015-03-13 17:21:25 -07004542 tl->SuspendAll(__FUNCTION__);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08004543 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
4544 context.SetChunkOverhead(0);
4545 space->AsRegionSpace()->Walk(BumpPointerSpaceCallback, &context);
4546 HeapChunkContext::HeapChunkJavaCallback(nullptr, nullptr, 0, &context);
4547 tl->ResumeAll();
4548 self->TransitionFromSuspendedToRunnable();
4549 heap->DecrementDisableMovingGC(self);
Mathieu Chartier36dab362014-07-30 14:59:56 -07004550 } else {
4551 UNIMPLEMENTED(WARNING) << "Not counting objects in space " << *space;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07004552 }
Mathieu Chartier36dab362014-07-30 14:59:56 -07004553 context.ResetStartOfNextChunk();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07004554 }
Mathieu Chartier4c69d7f2014-10-10 12:45:50 -07004555 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07004556 // Walk the large objects, these are not in the AllocSpace.
Mathieu Chartier36dab362014-07-30 14:59:56 -07004557 context.SetChunkOverhead(0);
Mathieu Chartierbc689b72014-12-14 17:01:31 -08004558 heap->GetLargeObjectsSpace()->Walk(HeapChunkContext::HeapChunkJavaCallback, &context);
Elliott Hughesa2155262011-11-16 16:26:58 -08004559 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07004560
4561 // Finally, send a heap end chunk.
4562 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHEN") : CHUNK_TYPE("HPEN"), sizeof(heap_id), heap_id);
Elliott Hughes767a1472011-10-26 18:49:02 -07004563}
4564
Brian Carlstrom306db812014-09-05 13:01:41 -07004565void Dbg::SetAllocTrackingEnabled(bool enable) {
Man Cao8c2ff642015-05-27 17:25:30 -07004566 gc::AllocRecordObjectMap::SetAllocTrackingEnabled(enable);
Elliott Hughes545a0642011-11-08 19:10:03 -08004567}
4568
4569void Dbg::DumpRecentAllocations() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004570 ScopedObjectAccess soa(Thread::Current());
Brian Carlstrom306db812014-09-05 13:01:41 -07004571 MutexLock mu(soa.Self(), *Locks::alloc_tracker_lock_);
Man Cao8c2ff642015-05-27 17:25:30 -07004572 if (!Runtime::Current()->GetHeap()->IsAllocTrackingEnabled()) {
Elliott Hughes545a0642011-11-08 19:10:03 -08004573 LOG(INFO) << "Not recording tracked allocations";
4574 return;
4575 }
Man Cao8c2ff642015-05-27 17:25:30 -07004576 gc::AllocRecordObjectMap* records = Runtime::Current()->GetHeap()->GetAllocationRecords();
4577 CHECK(records != nullptr);
Elliott Hughes545a0642011-11-08 19:10:03 -08004578
Man Cao8c2ff642015-05-27 17:25:30 -07004579 const uint16_t capped_count = CappedAllocRecordCount(records->Size());
Brian Carlstrom306db812014-09-05 13:01:41 -07004580 uint16_t count = capped_count;
Elliott Hughes545a0642011-11-08 19:10:03 -08004581
Man Cao8c2ff642015-05-27 17:25:30 -07004582 LOG(INFO) << "Tracked allocations, (count=" << count << ")";
4583 for (auto it = records->RBegin(), end = records->REnd();
4584 count > 0 && it != end; count--, it++) {
4585 const gc::AllocRecord* record = it->second;
Elliott Hughes545a0642011-11-08 19:10:03 -08004586
Man Cao8c2ff642015-05-27 17:25:30 -07004587 LOG(INFO) << StringPrintf(" Thread %-2d %6zd bytes ", record->GetTid(), record->ByteCount())
4588 << PrettyClass(it->first.Read()->GetClass());
Elliott Hughes545a0642011-11-08 19:10:03 -08004589
Man Cao8c2ff642015-05-27 17:25:30 -07004590 for (size_t stack_frame = 0, depth = record->GetDepth(); stack_frame < depth; ++stack_frame) {
4591 const gc::AllocRecordStackTraceElement& stack_element = record->StackElement(stack_frame);
4592 ArtMethod* m = stack_element.GetMethod();
4593 LOG(INFO) << " " << PrettyMethod(m) << " line " << stack_element.ComputeLineNumber();
Elliott Hughes545a0642011-11-08 19:10:03 -08004594 }
4595
4596 // pause periodically to help logcat catch up
4597 if ((count % 5) == 0) {
4598 usleep(40000);
4599 }
Elliott Hughes545a0642011-11-08 19:10:03 -08004600 }
4601}
4602
4603class StringTable {
4604 public:
4605 StringTable() {
4606 }
4607
Mathieu Chartier4345c462014-06-27 10:20:14 -07004608 void Add(const std::string& str) {
4609 table_.insert(str);
4610 }
4611
4612 void Add(const char* str) {
4613 table_.insert(str);
Elliott Hughes545a0642011-11-08 19:10:03 -08004614 }
4615
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004616 size_t IndexOf(const char* s) const {
Mathieu Chartier02e25112013-08-14 16:14:24 -07004617 auto it = table_.find(s);
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004618 if (it == table_.end()) {
4619 LOG(FATAL) << "IndexOf(\"" << s << "\") failed";
4620 }
4621 return std::distance(table_.begin(), it);
Elliott Hughes545a0642011-11-08 19:10:03 -08004622 }
4623
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004624 size_t Size() const {
Elliott Hughes545a0642011-11-08 19:10:03 -08004625 return table_.size();
4626 }
4627
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004628 void WriteTo(std::vector<uint8_t>& bytes) const {
Mathieu Chartier02e25112013-08-14 16:14:24 -07004629 for (const std::string& str : table_) {
4630 const char* s = str.c_str();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004631 size_t s_len = CountModifiedUtf8Chars(s);
Christopher Ferris8a354052015-04-24 17:23:53 -07004632 std::unique_ptr<uint16_t[]> s_utf16(new uint16_t[s_len]);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004633 ConvertModifiedUtf8ToUtf16(s_utf16.get(), s);
4634 JDWP::AppendUtf16BE(bytes, s_utf16.get(), s_len);
Elliott Hughes545a0642011-11-08 19:10:03 -08004635 }
4636 }
4637
4638 private:
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004639 std::set<std::string> table_;
Elliott Hughes545a0642011-11-08 19:10:03 -08004640 DISALLOW_COPY_AND_ASSIGN(StringTable);
4641};
4642
Mathieu Chartiere401d142015-04-22 13:56:20 -07004643static const char* GetMethodSourceFile(ArtMethod* method)
Sebastien Hertz280286a2014-04-28 09:26:50 +02004644 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004645 DCHECK(method != nullptr);
4646 const char* source_file = method->GetDeclaringClassSourceFile();
Sebastien Hertz280286a2014-04-28 09:26:50 +02004647 return (source_file != nullptr) ? source_file : "";
4648}
4649
Elliott Hughes545a0642011-11-08 19:10:03 -08004650/*
4651 * The data we send to DDMS contains everything we have recorded.
4652 *
4653 * Message header (all values big-endian):
4654 * (1b) message header len (to allow future expansion); includes itself
4655 * (1b) entry header len
4656 * (1b) stack frame len
4657 * (2b) number of entries
4658 * (4b) offset to string table from start of message
4659 * (2b) number of class name strings
4660 * (2b) number of method name strings
4661 * (2b) number of source file name strings
4662 * For each entry:
4663 * (4b) total allocation size
Elliott Hughes221229c2013-01-08 18:17:50 -08004664 * (2b) thread id
Elliott Hughes545a0642011-11-08 19:10:03 -08004665 * (2b) allocated object's class name index
4666 * (1b) stack depth
4667 * For each stack frame:
4668 * (2b) method's class name
4669 * (2b) method name
4670 * (2b) method source file
4671 * (2b) line number, clipped to 32767; -2 if native; -1 if no source
4672 * (xb) class name strings
4673 * (xb) method name strings
4674 * (xb) source file strings
4675 *
4676 * As with other DDM traffic, strings are sent as a 4-byte length
4677 * followed by UTF-16 data.
4678 *
4679 * We send up 16-bit unsigned indexes into string tables. In theory there
Brian Carlstrom306db812014-09-05 13:01:41 -07004680 * can be (kMaxAllocRecordStackDepth * alloc_record_max_) unique strings in
Elliott Hughes545a0642011-11-08 19:10:03 -08004681 * each table, but in practice there should be far fewer.
4682 *
4683 * The chief reason for using a string table here is to keep the size of
4684 * the DDMS message to a minimum. This is partly to make the protocol
4685 * efficient, but also because we have to form the whole thing up all at
4686 * once in a memory buffer.
4687 *
4688 * We use separate string tables for class names, method names, and source
4689 * files to keep the indexes small. There will generally be no overlap
4690 * between the contents of these tables.
4691 */
4692jbyteArray Dbg::GetRecentAllocations() {
Ian Rogerscf7f1912014-10-22 22:06:39 -07004693 if ((false)) {
Elliott Hughes545a0642011-11-08 19:10:03 -08004694 DumpRecentAllocations();
4695 }
4696
Ian Rogers50b35e22012-10-04 10:09:15 -07004697 Thread* self = Thread::Current();
Elliott Hughes545a0642011-11-08 19:10:03 -08004698 std::vector<uint8_t> bytes;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004699 {
Brian Carlstrom306db812014-09-05 13:01:41 -07004700 MutexLock mu(self, *Locks::alloc_tracker_lock_);
Man Cao8c2ff642015-05-27 17:25:30 -07004701 gc::AllocRecordObjectMap* records = Runtime::Current()->GetHeap()->GetAllocationRecords();
4702 // In case this method is called when allocation tracker is disabled,
4703 // we should still send some data back.
4704 gc::AllocRecordObjectMap dummy;
4705 if (records == nullptr) {
4706 CHECK(!Runtime::Current()->GetHeap()->IsAllocTrackingEnabled());
4707 records = &dummy;
4708 }
4709
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004710 //
4711 // Part 1: generate string tables.
4712 //
4713 StringTable class_names;
4714 StringTable method_names;
4715 StringTable filenames;
Elliott Hughes545a0642011-11-08 19:10:03 -08004716
Man Cao8c2ff642015-05-27 17:25:30 -07004717 const uint16_t capped_count = CappedAllocRecordCount(records->Size());
Brian Carlstrom306db812014-09-05 13:01:41 -07004718 uint16_t count = capped_count;
Man Cao8c2ff642015-05-27 17:25:30 -07004719 for (auto it = records->RBegin(), end = records->REnd();
4720 count > 0 && it != end; count--, it++) {
4721 const gc::AllocRecord* record = it->second;
Ian Rogers1ff3c982014-08-12 02:30:58 -07004722 std::string temp;
Man Cao8c2ff642015-05-27 17:25:30 -07004723 class_names.Add(it->first.Read()->GetClass()->GetDescriptor(&temp));
4724 for (size_t i = 0, depth = record->GetDepth(); i < depth; i++) {
4725 ArtMethod* m = record->StackElement(i).GetMethod();
4726 class_names.Add(m->GetDeclaringClassDescriptor());
4727 method_names.Add(m->GetName());
4728 filenames.Add(GetMethodSourceFile(m));
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004729 }
Elliott Hughes545a0642011-11-08 19:10:03 -08004730 }
4731
Man Cao8c2ff642015-05-27 17:25:30 -07004732 LOG(INFO) << "recent allocation records: " << capped_count;
4733 LOG(INFO) << "allocation records all objects: " << records->Size();
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004734
4735 //
4736 // Part 2: Generate the output and store it in the buffer.
4737 //
4738
4739 // (1b) message header len (to allow future expansion); includes itself
4740 // (1b) entry header len
4741 // (1b) stack frame len
4742 const int kMessageHeaderLen = 15;
4743 const int kEntryHeaderLen = 9;
4744 const int kStackFrameLen = 8;
4745 JDWP::Append1BE(bytes, kMessageHeaderLen);
4746 JDWP::Append1BE(bytes, kEntryHeaderLen);
4747 JDWP::Append1BE(bytes, kStackFrameLen);
4748
4749 // (2b) number of entries
4750 // (4b) offset to string table from start of message
4751 // (2b) number of class name strings
4752 // (2b) number of method name strings
4753 // (2b) number of source file name strings
Brian Carlstrom306db812014-09-05 13:01:41 -07004754 JDWP::Append2BE(bytes, capped_count);
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004755 size_t string_table_offset = bytes.size();
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004756 JDWP::Append4BE(bytes, 0); // We'll patch this later...
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004757 JDWP::Append2BE(bytes, class_names.Size());
4758 JDWP::Append2BE(bytes, method_names.Size());
4759 JDWP::Append2BE(bytes, filenames.Size());
4760
Ian Rogers1ff3c982014-08-12 02:30:58 -07004761 std::string temp;
Man Cao8c2ff642015-05-27 17:25:30 -07004762 count = capped_count;
4763 // The last "count" number of allocation records in "records" are the most recent "count" number
4764 // of allocations. Reverse iterate to get them. The most recent allocation is sent first.
4765 for (auto it = records->RBegin(), end = records->REnd();
4766 count > 0 && it != end; count--, it++) {
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004767 // For each entry:
4768 // (4b) total allocation size
4769 // (2b) thread id
4770 // (2b) allocated object's class name index
4771 // (1b) stack depth
Man Cao8c2ff642015-05-27 17:25:30 -07004772 const gc::AllocRecord* record = it->second;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004773 size_t stack_depth = record->GetDepth();
Mathieu Chartierf8322842014-05-16 10:59:25 -07004774 size_t allocated_object_class_name_index =
Man Cao8c2ff642015-05-27 17:25:30 -07004775 class_names.IndexOf(it->first.Read()->GetClass()->GetDescriptor(&temp));
Hiroshi Yamauchib5a9e3d2014-06-09 12:11:20 -07004776 JDWP::Append4BE(bytes, record->ByteCount());
Man Cao8c2ff642015-05-27 17:25:30 -07004777 JDWP::Append2BE(bytes, static_cast<uint16_t>(record->GetTid()));
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004778 JDWP::Append2BE(bytes, allocated_object_class_name_index);
4779 JDWP::Append1BE(bytes, stack_depth);
4780
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004781 for (size_t stack_frame = 0; stack_frame < stack_depth; ++stack_frame) {
4782 // For each stack frame:
4783 // (2b) method's class name
4784 // (2b) method name
4785 // (2b) method source file
4786 // (2b) line number, clipped to 32767; -2 if native; -1 if no source
Man Cao8c2ff642015-05-27 17:25:30 -07004787 ArtMethod* m = record->StackElement(stack_frame).GetMethod();
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004788 size_t class_name_index = class_names.IndexOf(m->GetDeclaringClassDescriptor());
4789 size_t method_name_index = method_names.IndexOf(m->GetName());
4790 size_t file_name_index = filenames.IndexOf(GetMethodSourceFile(m));
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004791 JDWP::Append2BE(bytes, class_name_index);
4792 JDWP::Append2BE(bytes, method_name_index);
4793 JDWP::Append2BE(bytes, file_name_index);
Man Cao8c2ff642015-05-27 17:25:30 -07004794 JDWP::Append2BE(bytes, record->StackElement(stack_frame).ComputeLineNumber());
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004795 }
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004796 }
4797
4798 // (xb) class name strings
4799 // (xb) method name strings
4800 // (xb) source file strings
4801 JDWP::Set4BE(&bytes[string_table_offset], bytes.size());
4802 class_names.WriteTo(bytes);
4803 method_names.WriteTo(bytes);
4804 filenames.WriteTo(bytes);
Elliott Hughes545a0642011-11-08 19:10:03 -08004805 }
Ian Rogers50b35e22012-10-04 10:09:15 -07004806 JNIEnv* env = self->GetJniEnv();
Elliott Hughes545a0642011-11-08 19:10:03 -08004807 jbyteArray result = env->NewByteArray(bytes.size());
Ian Rogersc0542af2014-09-03 16:16:56 -07004808 if (result != nullptr) {
Elliott Hughes545a0642011-11-08 19:10:03 -08004809 env->SetByteArrayRegion(result, 0, bytes.size(), reinterpret_cast<const jbyte*>(&bytes[0]));
4810 }
4811 return result;
4812}
4813
Mathieu Chartiere401d142015-04-22 13:56:20 -07004814ArtMethod* DeoptimizationRequest::Method() const {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07004815 ScopedObjectAccessUnchecked soa(Thread::Current());
4816 return soa.DecodeMethod(method_);
4817}
4818
Mathieu Chartiere401d142015-04-22 13:56:20 -07004819void DeoptimizationRequest::SetMethod(ArtMethod* m) {
Hiroshi Yamauchi0ec17d22014-07-07 13:07:08 -07004820 ScopedObjectAccessUnchecked soa(Thread::Current());
4821 method_ = soa.EncodeMethod(m);
4822}
4823
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004824} // namespace art