blob: 22a0e22fe92d22d3fd578b4a9b023b8739c18094 [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"
Elliott Hughes545a0642011-11-08 19:10:03 -080024#include "class_linker.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080025#include "class_linker-inl.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070026#include "dex_file-inl.h"
Ian Rogers776ac1f2012-04-13 23:36:36 -070027#include "dex_instruction.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070028#include "gc/accounting/card_table-inl.h"
29#include "gc/space/large_object_space.h"
30#include "gc/space/space-inl.h"
Elliott Hughes64f574f2013-02-20 14:57:12 -080031#include "jdwp/object_registry.h"
Brian Carlstromea46f952013-07-30 01:26:50 -070032#include "mirror/art_field-inl.h"
33#include "mirror/art_method-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080034#include "mirror/class.h"
35#include "mirror/class-inl.h"
36#include "mirror/class_loader.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080037#include "mirror/object-inl.h"
38#include "mirror/object_array-inl.h"
Ian Rogersb0fa5dc2014-04-28 16:47:08 -070039#include "mirror/string-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080040#include "mirror/throwable.h"
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080041#include "object_utils.h"
Sebastien Hertza76a6d42014-03-20 16:40:17 +010042#include "quick/inline_method_analyser.h"
Ian Rogers53b8b092014-03-13 23:45:53 -070043#include "reflection.h"
Elliott Hughesa0e18062012-04-13 15:59:59 -070044#include "safe_map.h"
Elliott Hughes64f574f2013-02-20 14:57:12 -080045#include "scoped_thread_state_change.h"
Elliott Hughes6a5bd492011-10-28 14:33:57 -070046#include "ScopedLocalRef.h"
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -070047#include "ScopedPrimitiveArray.h"
Ian Rogers1f539342012-10-03 21:09:42 -070048#include "sirt_ref.h"
Elliott Hughes47fce012011-10-25 18:37:19 -070049#include "stack_indirect_reference_table.h"
Elliott Hughes475fc232011-10-25 15:00:35 -070050#include "thread_list.h"
Ian Rogers62d6c772013-02-27 08:32:07 -080051#include "throw_location.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
Brian Carlstrom7934ac22013-07-26 10:54:15 -070062static const size_t kMaxAllocRecordStackDepth = 16; // Max 255.
63static const size_t kDefaultNumAllocRecords = 64*1024; // Must be a power of 2.
Elliott Hughes475fc232011-10-25 15:00:35 -070064
Elliott Hughes545a0642011-11-08 19:10:03 -080065struct AllocRecordStackTraceElement {
Brian Carlstromea46f952013-07-30 01:26:50 -070066 mirror::ArtMethod* method;
Ian Rogers0399dde2012-06-06 17:09:28 -070067 uint32_t dex_pc;
Elliott Hughes545a0642011-11-08 19:10:03 -080068
Mathieu Chartier412c7fc2014-02-07 12:18:39 -080069 AllocRecordStackTraceElement() : method(nullptr), dex_pc(0) {
70 }
71
Ian Rogersb726dcb2012-09-05 08:57:23 -070072 int32_t LineNumber() const SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers0399dde2012-06-06 17:09:28 -070073 return MethodHelper(method).GetLineNumFromDexPC(dex_pc);
Elliott Hughes545a0642011-11-08 19:10:03 -080074 }
75};
76
77struct AllocRecord {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080078 mirror::Class* type;
Elliott Hughes545a0642011-11-08 19:10:03 -080079 size_t byte_count;
80 uint16_t thin_lock_id;
Brian Carlstrom7934ac22013-07-26 10:54:15 -070081 AllocRecordStackTraceElement stack[kMaxAllocRecordStackDepth]; // Unused entries have NULL method.
Elliott Hughes545a0642011-11-08 19:10:03 -080082
83 size_t GetDepth() {
84 size_t depth = 0;
85 while (depth < kMaxAllocRecordStackDepth && stack[depth].method != NULL) {
86 ++depth;
87 }
88 return depth;
89 }
Mathieu Chartier412c7fc2014-02-07 12:18:39 -080090
Mathieu Chartier83c8ee02014-01-28 14:50:23 -080091 void UpdateObjectPointers(IsMarkedCallback* callback, void* arg)
Mathieu Chartier412c7fc2014-02-07 12:18:39 -080092 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
93 if (type != nullptr) {
Mathieu Chartier83c8ee02014-01-28 14:50:23 -080094 type = down_cast<mirror::Class*>(callback(type, arg));
Mathieu Chartier412c7fc2014-02-07 12:18:39 -080095 }
96 for (size_t stack_frame = 0; stack_frame < kMaxAllocRecordStackDepth; ++stack_frame) {
97 mirror::ArtMethod*& m = stack[stack_frame].method;
98 if (m == nullptr) {
99 break;
100 }
Mathieu Chartier83c8ee02014-01-28 14:50:23 -0800101 m = down_cast<mirror::ArtMethod*>(callback(m, arg));
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800102 }
103 }
Elliott Hughes545a0642011-11-08 19:10:03 -0800104};
105
Elliott Hughes86964332012-02-15 19:37:42 -0800106struct Breakpoint {
Sebastien Hertza76a6d42014-03-20 16:40:17 +0100107 // The location of this breakpoint.
Brian Carlstromea46f952013-07-30 01:26:50 -0700108 mirror::ArtMethod* method;
Elliott Hughesa656a0f2012-02-21 18:03:44 -0800109 uint32_t dex_pc;
Sebastien Hertza76a6d42014-03-20 16:40:17 +0100110
111 // Indicates whether breakpoint needs full deoptimization or selective deoptimization.
112 bool need_full_deoptimization;
113
114 Breakpoint(mirror::ArtMethod* method, uint32_t dex_pc, bool need_full_deoptimization)
115 : method(method), dex_pc(dex_pc), need_full_deoptimization(need_full_deoptimization) {}
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700116
117 void VisitRoots(RootCallback* callback, void* arg) {
118 if (method != nullptr) {
119 callback(reinterpret_cast<mirror::Object**>(&method), arg, 0, kRootDebugger);
120 }
121 }
Elliott Hughes86964332012-02-15 19:37:42 -0800122};
123
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700124static std::ostream& operator<<(std::ostream& os, const Breakpoint& rhs)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700125 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes229feb72012-02-23 13:33:29 -0800126 os << StringPrintf("Breakpoint[%s @%#x]", PrettyMethod(rhs.method).c_str(), rhs.dex_pc);
Elliott Hughes86964332012-02-15 19:37:42 -0800127 return os;
128}
129
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200130class DebugInstrumentationListener FINAL : public instrumentation::InstrumentationListener {
Ian Rogers62d6c772013-02-27 08:32:07 -0800131 public:
132 DebugInstrumentationListener() {}
133 virtual ~DebugInstrumentationListener() {}
134
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200135 void MethodEntered(Thread* thread, mirror::Object* this_object, mirror::ArtMethod* method,
136 uint32_t dex_pc)
137 OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800138 if (method->IsNative()) {
139 // TODO: post location events is a suspension point and native method entry stubs aren't.
140 return;
141 }
Jeff Hao579b0242013-11-18 13:16:49 -0800142 Dbg::PostLocationEvent(method, 0, this_object, Dbg::kMethodEntry, nullptr);
Ian Rogers62d6c772013-02-27 08:32:07 -0800143 }
144
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200145 void MethodExited(Thread* thread, mirror::Object* this_object, mirror::ArtMethod* method,
146 uint32_t dex_pc, const JValue& return_value)
147 OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800148 if (method->IsNative()) {
149 // TODO: post location events is a suspension point and native method entry stubs aren't.
150 return;
151 }
Jeff Hao579b0242013-11-18 13:16:49 -0800152 Dbg::PostLocationEvent(method, dex_pc, this_object, Dbg::kMethodExit, &return_value);
Ian Rogers62d6c772013-02-27 08:32:07 -0800153 }
154
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200155 void MethodUnwind(Thread* thread, mirror::Object* this_object, mirror::ArtMethod* method,
156 uint32_t dex_pc)
157 OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800158 // We're not recorded to listen to this kind of event, so complain.
159 LOG(ERROR) << "Unexpected method unwind event in debugger " << PrettyMethod(method)
Sebastien Hertz51db44a2013-11-19 10:00:29 +0100160 << " " << dex_pc;
Ian Rogers62d6c772013-02-27 08:32:07 -0800161 }
162
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200163 void DexPcMoved(Thread* thread, mirror::Object* this_object, mirror::ArtMethod* method,
164 uint32_t new_dex_pc)
165 OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800166 Dbg::UpdateDebugger(thread, this_object, method, new_dex_pc);
167 }
168
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200169 void FieldRead(Thread* thread, mirror::Object* this_object, mirror::ArtMethod* method,
170 uint32_t dex_pc, mirror::ArtField* field)
171 OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
172 Dbg::PostFieldAccessEvent(method, dex_pc, this_object, field);
Ian Rogers62d6c772013-02-27 08:32:07 -0800173 }
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200174
175 void FieldWritten(Thread* thread, mirror::Object* this_object, mirror::ArtMethod* method,
176 uint32_t dex_pc, mirror::ArtField* field, const JValue& field_value)
177 OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
178 Dbg::PostFieldModificationEvent(method, dex_pc, this_object, field, &field_value);
179 }
180
181 void ExceptionCaught(Thread* thread, const ThrowLocation& throw_location,
182 mirror::ArtMethod* catch_method, uint32_t catch_dex_pc,
183 mirror::Throwable* exception_object)
184 OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
185 Dbg::PostException(throw_location, catch_method, catch_dex_pc, exception_object);
186 }
187
188 private:
189 DISALLOW_COPY_AND_ASSIGN(DebugInstrumentationListener);
Ian Rogers62d6c772013-02-27 08:32:07 -0800190} gDebugInstrumentationListener;
191
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700192// JDWP is allowed unless the Zygote forbids it.
193static bool gJdwpAllowed = true;
194
Elliott Hughesc0f09332012-03-26 13:27:06 -0700195// Was there a -Xrunjdwp or -agentlib:jdwp= argument on the command line?
Elliott Hughes3bb81562011-10-21 18:52:59 -0700196static bool gJdwpConfigured = false;
197
Elliott Hughesc0f09332012-03-26 13:27:06 -0700198// Broken-down JDWP options. (Only valid if IsJdwpConfigured() is true.)
Elliott Hughes376a7a02011-10-24 18:35:55 -0700199static JDWP::JdwpOptions gJdwpOptions;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700200
201// Runtime JDWP state.
202static JDWP::JdwpState* gJdwpState = NULL;
203static bool gDebuggerConnected; // debugger or DDMS is connected.
204static bool gDebuggerActive; // debugger is making requests.
Elliott Hughes86964332012-02-15 19:37:42 -0800205static bool gDisposed; // debugger called VirtualMachine.Dispose, so we should drop the connection.
Elliott Hughes3bb81562011-10-21 18:52:59 -0700206
Elliott Hughes47fce012011-10-25 18:37:19 -0700207static bool gDdmThreadNotification = false;
208
Elliott Hughes767a1472011-10-26 18:49:02 -0700209// DDMS GC-related settings.
210static Dbg::HpifWhen gDdmHpifWhen = Dbg::HPIF_WHEN_NEVER;
211static Dbg::HpsgWhen gDdmHpsgWhen = Dbg::HPSG_WHEN_NEVER;
212static Dbg::HpsgWhat gDdmHpsgWhat;
213static Dbg::HpsgWhen gDdmNhsgWhen = Dbg::HPSG_WHEN_NEVER;
214static Dbg::HpsgWhat gDdmNhsgWhat;
215
Ian Rogers719d1a32014-03-06 12:13:39 -0800216static ObjectRegistry* gRegistry = nullptr;
Elliott Hughes475fc232011-10-25 15:00:35 -0700217
Elliott Hughes545a0642011-11-08 19:10:03 -0800218// Recent allocation tracking.
Ian Rogers719d1a32014-03-06 12:13:39 -0800219Mutex* Dbg::alloc_tracker_lock_ = nullptr;
220AllocRecord* Dbg::recent_allocation_records_ = nullptr; // TODO: CircularBuffer<AllocRecord>
221size_t Dbg::alloc_record_max_ = 0;
222size_t Dbg::alloc_record_head_ = 0;
223size_t Dbg::alloc_record_count_ = 0;
Elliott Hughes545a0642011-11-08 19:10:03 -0800224
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100225// Deoptimization support.
Sebastien Hertz4d25df32014-03-21 17:44:46 +0100226Mutex* Dbg::deoptimization_lock_ = nullptr;
227std::vector<DeoptimizationRequest> Dbg::deoptimization_requests_;
228size_t Dbg::full_deoptimization_event_count_ = 0;
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +0100229size_t Dbg::delayed_full_undeoptimization_count_ = 0;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100230
231// Breakpoints.
jeffhao09bfc6a2012-12-11 18:11:43 -0800232static std::vector<Breakpoint> gBreakpoints GUARDED_BY(Locks::breakpoint_lock_);
Elliott Hughes86964332012-02-15 19:37:42 -0800233
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700234void DebugInvokeReq::VisitRoots(RootCallback* callback, void* arg, uint32_t tid,
235 RootType root_type) {
236 if (receiver != nullptr) {
237 callback(&receiver, arg, tid, root_type);
238 }
239 if (thread != nullptr) {
240 callback(&thread, arg, tid, root_type);
241 }
242 if (klass != nullptr) {
243 callback(reinterpret_cast<mirror::Object**>(&klass), arg, tid, root_type);
244 }
245 if (method != nullptr) {
246 callback(reinterpret_cast<mirror::Object**>(&method), arg, tid, root_type);
247 }
248}
249
Sebastien Hertzbb43b432014-04-14 11:59:08 +0200250void DebugInvokeReq::Clear() {
251 invoke_needed = false;
252 receiver = nullptr;
253 thread = nullptr;
254 klass = nullptr;
255 method = nullptr;
256}
257
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700258void SingleStepControl::VisitRoots(RootCallback* callback, void* arg, uint32_t tid,
259 RootType root_type) {
260 if (method != nullptr) {
261 callback(reinterpret_cast<mirror::Object**>(&method), arg, tid, root_type);
262 }
263}
264
Sebastien Hertzbb43b432014-04-14 11:59:08 +0200265bool SingleStepControl::ContainsDexPc(uint32_t dex_pc) const {
266 return dex_pcs.find(dex_pc) == dex_pcs.end();
267}
268
269void SingleStepControl::Clear() {
270 is_active = false;
271 method = nullptr;
272 dex_pcs.clear();
273}
274
Sebastien Hertz4d25df32014-03-21 17:44:46 +0100275void DeoptimizationRequest::VisitRoots(RootCallback* callback, void* arg) {
276 if (method != nullptr) {
277 callback(reinterpret_cast<mirror::Object**>(&method), arg, 0, kRootDebugger);
278 }
279}
280
Brian Carlstromea46f952013-07-30 01:26:50 -0700281static bool IsBreakpoint(const mirror::ArtMethod* m, uint32_t dex_pc)
jeffhao09bfc6a2012-12-11 18:11:43 -0800282 LOCKS_EXCLUDED(Locks::breakpoint_lock_)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700283 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
jeffhao09bfc6a2012-12-11 18:11:43 -0800284 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100285 for (size_t i = 0, e = gBreakpoints.size(); i < e; ++i) {
Elliott Hughesa656a0f2012-02-21 18:03:44 -0800286 if (gBreakpoints[i].method == m && gBreakpoints[i].dex_pc == dex_pc) {
Elliott Hughes86964332012-02-15 19:37:42 -0800287 VLOG(jdwp) << "Hit breakpoint #" << i << ": " << gBreakpoints[i];
288 return true;
289 }
290 }
291 return false;
292}
293
Sebastien Hertz52d131d2014-03-13 16:17:40 +0100294static bool IsSuspendedForDebugger(ScopedObjectAccessUnchecked& soa, Thread* thread)
295 LOCKS_EXCLUDED(Locks::thread_suspend_count_lock_) {
Elliott Hughes9e0c1752013-01-09 14:02:58 -0800296 MutexLock mu(soa.Self(), *Locks::thread_suspend_count_lock_);
297 // A thread may be suspended for GC; in this code, we really want to know whether
298 // there's a debugger suspension active.
299 return thread->IsSuspended() && thread->GetDebugSuspendCount() > 0;
300}
301
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800302static mirror::Array* DecodeArray(JDWP::RefTypeId id, JDWP::JdwpError& status)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700303 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800304 mirror::Object* o = gRegistry->Get<mirror::Object*>(id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800305 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800306 status = JDWP::ERR_INVALID_OBJECT;
307 return NULL;
308 }
309 if (!o->IsArrayInstance()) {
310 status = JDWP::ERR_INVALID_ARRAY;
311 return NULL;
312 }
313 status = JDWP::ERR_NONE;
314 return o->AsArray();
315}
316
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800317static mirror::Class* DecodeClass(JDWP::RefTypeId id, JDWP::JdwpError& status)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700318 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800319 mirror::Object* o = gRegistry->Get<mirror::Object*>(id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800320 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800321 status = JDWP::ERR_INVALID_OBJECT;
322 return NULL;
323 }
324 if (!o->IsClass()) {
325 status = JDWP::ERR_INVALID_CLASS;
326 return NULL;
327 }
328 status = JDWP::ERR_NONE;
329 return o->AsClass();
330}
331
Elliott Hughes221229c2013-01-08 18:17:50 -0800332static JDWP::JdwpError DecodeThread(ScopedObjectAccessUnchecked& soa, JDWP::ObjectId thread_id, Thread*& thread)
jeffhaoa77f0f62012-12-05 17:19:31 -0800333 EXCLUSIVE_LOCKS_REQUIRED(Locks::thread_list_lock_)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700334 LOCKS_EXCLUDED(Locks::thread_suspend_count_lock_)
335 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800336 mirror::Object* thread_peer = gRegistry->Get<mirror::Object*>(thread_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800337 if (thread_peer == NULL || thread_peer == ObjectRegistry::kInvalidObject) {
Elliott Hughes221229c2013-01-08 18:17:50 -0800338 // This isn't even an object.
339 return JDWP::ERR_INVALID_OBJECT;
Elliott Hughes436e3722012-02-17 20:01:47 -0800340 }
Elliott Hughes221229c2013-01-08 18:17:50 -0800341
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800342 mirror::Class* java_lang_Thread = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_Thread);
Elliott Hughes221229c2013-01-08 18:17:50 -0800343 if (!java_lang_Thread->IsAssignableFrom(thread_peer->GetClass())) {
344 // This isn't a thread.
345 return JDWP::ERR_INVALID_THREAD;
346 }
347
348 thread = Thread::FromManagedThread(soa, thread_peer);
349 if (thread == NULL) {
350 // This is a java.lang.Thread without a Thread*. Must be a zombie.
351 return JDWP::ERR_THREAD_NOT_ALIVE;
352 }
353 return JDWP::ERR_NONE;
Elliott Hughes436e3722012-02-17 20:01:47 -0800354}
355
Elliott Hughes24437992011-11-30 14:49:33 -0800356static JDWP::JdwpTag BasicTagFromDescriptor(const char* descriptor) {
357 // JDWP deliberately uses the descriptor characters' ASCII values for its enum.
358 // Note that by "basic" we mean that we don't get more specific than JT_OBJECT.
359 return static_cast<JDWP::JdwpTag>(descriptor[0]);
360}
361
Ian Rogers98379392014-02-24 16:53:16 -0800362static JDWP::JdwpTag TagFromClass(const ScopedObjectAccessUnchecked& soa, mirror::Class* c)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700363 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes86b00102011-12-05 17:54:26 -0800364 CHECK(c != NULL);
Elliott Hughes24437992011-11-30 14:49:33 -0800365 if (c->IsArrayClass()) {
366 return JDWP::JT_ARRAY;
367 }
Elliott Hughes24437992011-11-30 14:49:33 -0800368 if (c->IsStringClass()) {
369 return JDWP::JT_STRING;
Elliott Hughes24437992011-11-30 14:49:33 -0800370 }
Ian Rogers98379392014-02-24 16:53:16 -0800371 if (c->IsClassClass()) {
372 return JDWP::JT_CLASS_OBJECT;
373 }
374 {
375 mirror::Class* thread_class = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_Thread);
376 if (thread_class->IsAssignableFrom(c)) {
377 return JDWP::JT_THREAD;
378 }
379 }
380 {
381 mirror::Class* thread_group_class =
382 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_ThreadGroup);
383 if (thread_group_class->IsAssignableFrom(c)) {
384 return JDWP::JT_THREAD_GROUP;
385 }
386 }
387 {
388 mirror::Class* class_loader_class =
389 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_ClassLoader);
390 if (class_loader_class->IsAssignableFrom(c)) {
391 return JDWP::JT_CLASS_LOADER;
392 }
393 }
394 return JDWP::JT_OBJECT;
Elliott Hughes24437992011-11-30 14:49:33 -0800395}
396
397/*
398 * Objects declared to hold Object might actually hold a more specific
399 * type. The debugger may take a special interest in these (e.g. it
400 * wants to display the contents of Strings), so we want to return an
401 * appropriate tag.
402 *
403 * Null objects are tagged JT_OBJECT.
404 */
Ian Rogers98379392014-02-24 16:53:16 -0800405static JDWP::JdwpTag TagFromObject(const ScopedObjectAccessUnchecked& soa, mirror::Object* o)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700406 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers98379392014-02-24 16:53:16 -0800407 return (o == NULL) ? JDWP::JT_OBJECT : TagFromClass(soa, o->GetClass());
Elliott Hughes24437992011-11-30 14:49:33 -0800408}
409
410static bool IsPrimitiveTag(JDWP::JdwpTag tag) {
411 switch (tag) {
412 case JDWP::JT_BOOLEAN:
413 case JDWP::JT_BYTE:
414 case JDWP::JT_CHAR:
415 case JDWP::JT_FLOAT:
416 case JDWP::JT_DOUBLE:
417 case JDWP::JT_INT:
418 case JDWP::JT_LONG:
419 case JDWP::JT_SHORT:
420 case JDWP::JT_VOID:
421 return true;
422 default:
423 return false;
424 }
425}
426
Elliott Hughes3bb81562011-10-21 18:52:59 -0700427/*
428 * Handle one of the JDWP name/value pairs.
429 *
430 * JDWP options are:
431 * help: if specified, show help message and bail
432 * transport: may be dt_socket or dt_shmem
433 * address: for dt_socket, "host:port", or just "port" when listening
434 * server: if "y", wait for debugger to attach; if "n", attach to debugger
435 * timeout: how long to wait for debugger to connect / listen
436 *
437 * Useful with server=n (these aren't supported yet):
438 * onthrow=<exception-name>: connect to debugger when exception thrown
439 * onuncaught=y|n: connect to debugger when uncaught exception thrown
440 * launch=<command-line>: launch the debugger itself
441 *
442 * The "transport" option is required, as is "address" if server=n.
443 */
444static bool ParseJdwpOption(const std::string& name, const std::string& value) {
445 if (name == "transport") {
446 if (value == "dt_socket") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700447 gJdwpOptions.transport = JDWP::kJdwpTransportSocket;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700448 } else if (value == "dt_android_adb") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700449 gJdwpOptions.transport = JDWP::kJdwpTransportAndroidAdb;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700450 } else {
451 LOG(ERROR) << "JDWP transport not supported: " << value;
452 return false;
453 }
454 } else if (name == "server") {
455 if (value == "n") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700456 gJdwpOptions.server = false;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700457 } else if (value == "y") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700458 gJdwpOptions.server = true;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700459 } else {
460 LOG(ERROR) << "JDWP option 'server' must be 'y' or 'n'";
461 return false;
462 }
463 } else if (name == "suspend") {
464 if (value == "n") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700465 gJdwpOptions.suspend = false;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700466 } else if (value == "y") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700467 gJdwpOptions.suspend = true;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700468 } else {
469 LOG(ERROR) << "JDWP option 'suspend' must be 'y' or 'n'";
470 return false;
471 }
472 } else if (name == "address") {
473 /* this is either <port> or <host>:<port> */
474 std::string port_string;
Elliott Hughes376a7a02011-10-24 18:35:55 -0700475 gJdwpOptions.host.clear();
Elliott Hughes3bb81562011-10-21 18:52:59 -0700476 std::string::size_type colon = value.find(':');
477 if (colon != std::string::npos) {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700478 gJdwpOptions.host = value.substr(0, colon);
Elliott Hughes3bb81562011-10-21 18:52:59 -0700479 port_string = value.substr(colon + 1);
480 } else {
481 port_string = value;
482 }
483 if (port_string.empty()) {
484 LOG(ERROR) << "JDWP address missing port: " << value;
485 return false;
486 }
487 char* end;
Elliott Hughesba8eee12012-01-24 20:25:24 -0800488 uint64_t port = strtoul(port_string.c_str(), &end, 10);
489 if (*end != '\0' || port > 0xffff) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700490 LOG(ERROR) << "JDWP address has junk in port field: " << value;
491 return false;
492 }
Elliott Hughes376a7a02011-10-24 18:35:55 -0700493 gJdwpOptions.port = port;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700494 } else if (name == "launch" || name == "onthrow" || name == "oncaught" || name == "timeout") {
495 /* valid but unsupported */
496 LOG(INFO) << "Ignoring JDWP option '" << name << "'='" << value << "'";
497 } else {
498 LOG(INFO) << "Ignoring unrecognized JDWP option '" << name << "'='" << value << "'";
499 }
500
501 return true;
502}
503
504/*
505 * Parse the latter half of a -Xrunjdwp/-agentlib:jdwp= string, e.g.:
506 * "transport=dt_socket,address=8000,server=y,suspend=n"
507 */
508bool Dbg::ParseJdwpOptions(const std::string& options) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800509 VLOG(jdwp) << "ParseJdwpOptions: " << options;
Elliott Hughes47fce012011-10-25 18:37:19 -0700510
Elliott Hughes3bb81562011-10-21 18:52:59 -0700511 std::vector<std::string> pairs;
512 Split(options, ',', pairs);
513
514 for (size_t i = 0; i < pairs.size(); ++i) {
515 std::string::size_type equals = pairs[i].find('=');
516 if (equals == std::string::npos) {
517 LOG(ERROR) << "Can't parse JDWP option '" << pairs[i] << "' in '" << options << "'";
518 return false;
519 }
520 ParseJdwpOption(pairs[i].substr(0, equals), pairs[i].substr(equals + 1));
521 }
522
Elliott Hughes376a7a02011-10-24 18:35:55 -0700523 if (gJdwpOptions.transport == JDWP::kJdwpTransportUnknown) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700524 LOG(ERROR) << "Must specify JDWP transport: " << options;
525 }
Elliott Hughes376a7a02011-10-24 18:35:55 -0700526 if (!gJdwpOptions.server && (gJdwpOptions.host.empty() || gJdwpOptions.port == 0)) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700527 LOG(ERROR) << "Must specify JDWP host and port when server=n: " << options;
528 return false;
529 }
530
531 gJdwpConfigured = true;
532 return true;
533}
534
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700535void Dbg::StartJdwp() {
Elliott Hughesc0f09332012-03-26 13:27:06 -0700536 if (!gJdwpAllowed || !IsJdwpConfigured()) {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700537 // No JDWP for you!
538 return;
539 }
540
Ian Rogers719d1a32014-03-06 12:13:39 -0800541 CHECK(gRegistry == nullptr);
Elliott Hughes475fc232011-10-25 15:00:35 -0700542 gRegistry = new ObjectRegistry;
543
Ian Rogers719d1a32014-03-06 12:13:39 -0800544 alloc_tracker_lock_ = new Mutex("AllocTracker lock");
Sebastien Hertz4d25df32014-03-21 17:44:46 +0100545 deoptimization_lock_ = new Mutex("deoptimization lock", kDeoptimizationLock);
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700546 // Init JDWP if the debugger is enabled. This may connect out to a
547 // debugger, passively listen for a debugger, or block waiting for a
548 // debugger.
Elliott Hughes376a7a02011-10-24 18:35:55 -0700549 gJdwpState = JDWP::JdwpState::Create(&gJdwpOptions);
550 if (gJdwpState == NULL) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -0800551 // We probably failed because some other process has the port already, which means that
552 // if we don't abort the user is likely to think they're talking to us when they're actually
553 // talking to that other process.
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800554 LOG(FATAL) << "Debugger thread failed to initialize";
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700555 }
556
557 // If a debugger has already attached, send the "welcome" message.
558 // This may cause us to suspend all threads.
Elliott Hughes376a7a02011-10-24 18:35:55 -0700559 if (gJdwpState->IsActive()) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700560 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes376a7a02011-10-24 18:35:55 -0700561 if (!gJdwpState->PostVMStart()) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800562 LOG(WARNING) << "Failed to post 'start' message to debugger";
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700563 }
564 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700565}
566
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700567void Dbg::VisitRoots(RootCallback* callback, void* arg) {
Sebastien Hertz4d25df32014-03-21 17:44:46 +0100568 {
569 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
570 for (Breakpoint& bp : gBreakpoints) {
571 bp.VisitRoots(callback, arg);
572 }
573 }
574 if (deoptimization_lock_ != nullptr) { // only true if the debugger is started.
575 MutexLock mu(Thread::Current(), *deoptimization_lock_);
576 for (DeoptimizationRequest& req : deoptimization_requests_) {
577 req.VisitRoots(callback, arg);
578 }
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700579 }
580}
581
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700582void Dbg::StopJdwp() {
Sebastien Hertz0376e6b2014-02-06 18:12:59 +0100583 // Prevent the JDWP thread from processing JDWP incoming packets after we close the connection.
584 Disposed();
Elliott Hughes376a7a02011-10-24 18:35:55 -0700585 delete gJdwpState;
Ian Rogers719d1a32014-03-06 12:13:39 -0800586 gJdwpState = nullptr;
Elliott Hughes475fc232011-10-25 15:00:35 -0700587 delete gRegistry;
Ian Rogers719d1a32014-03-06 12:13:39 -0800588 gRegistry = nullptr;
589 delete alloc_tracker_lock_;
590 alloc_tracker_lock_ = nullptr;
Sebastien Hertz4d25df32014-03-21 17:44:46 +0100591 delete deoptimization_lock_;
592 deoptimization_lock_ = nullptr;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700593}
594
Elliott Hughes767a1472011-10-26 18:49:02 -0700595void Dbg::GcDidFinish() {
596 if (gDdmHpifWhen != HPIF_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700597 ScopedObjectAccess soa(Thread::Current());
Brian Carlstrom4d466a82014-05-08 19:05:29 -0700598 VLOG(jdwp) << "Sending heap info to DDM";
Elliott Hughes7162ad92011-10-27 14:08:42 -0700599 DdmSendHeapInfo(gDdmHpifWhen);
Elliott Hughes767a1472011-10-26 18:49:02 -0700600 }
601 if (gDdmHpsgWhen != HPSG_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700602 ScopedObjectAccess soa(Thread::Current());
Brian Carlstrom4d466a82014-05-08 19:05:29 -0700603 VLOG(jdwp) << "Dumping heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700604 DdmSendHeapSegments(false);
Elliott Hughes767a1472011-10-26 18:49:02 -0700605 }
606 if (gDdmNhsgWhen != HPSG_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700607 ScopedObjectAccess soa(Thread::Current());
Brian Carlstrom4d466a82014-05-08 19:05:29 -0700608 VLOG(jdwp) << "Dumping native heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700609 DdmSendHeapSegments(true);
Elliott Hughes767a1472011-10-26 18:49:02 -0700610 }
611}
612
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700613void Dbg::SetJdwpAllowed(bool allowed) {
614 gJdwpAllowed = allowed;
615}
616
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700617DebugInvokeReq* Dbg::GetInvokeReq() {
Elliott Hughes475fc232011-10-25 15:00:35 -0700618 return Thread::Current()->GetInvokeReq();
619}
620
621Thread* Dbg::GetDebugThread() {
622 return (gJdwpState != NULL) ? gJdwpState->GetDebugThread() : NULL;
623}
624
625void Dbg::ClearWaitForEventThread() {
626 gJdwpState->ClearWaitForEventThread();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700627}
628
629void Dbg::Connected() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700630 CHECK(!gDebuggerConnected);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800631 VLOG(jdwp) << "JDWP has attached";
Elliott Hughes3bb81562011-10-21 18:52:59 -0700632 gDebuggerConnected = true;
Elliott Hughes86964332012-02-15 19:37:42 -0800633 gDisposed = false;
634}
635
636void Dbg::Disposed() {
637 gDisposed = true;
638}
639
640bool Dbg::IsDisposed() {
641 return gDisposed;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700642}
643
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200644// All the instrumentation events the debugger is registered for.
645static constexpr uint32_t kListenerEvents = instrumentation::Instrumentation::kMethodEntered |
646 instrumentation::Instrumentation::kMethodExited |
647 instrumentation::Instrumentation::kDexPcMoved |
648 instrumentation::Instrumentation::kFieldRead |
649 instrumentation::Instrumentation::kFieldWritten |
650 instrumentation::Instrumentation::kExceptionCaught;
651
Elliott Hughesa2155262011-11-16 16:26:58 -0800652void Dbg::GoActive() {
653 // Enable all debugging features, including scans for breakpoints.
654 // This is a no-op if we're already active.
655 // Only called from the JDWP handler thread.
656 if (gDebuggerActive) {
657 return;
658 }
659
Elliott Hughesc0f09332012-03-26 13:27:06 -0700660 {
661 // TODO: dalvik only warned if there were breakpoints left over. clear in Dbg::Disconnected?
jeffhao09bfc6a2012-12-11 18:11:43 -0800662 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Elliott Hughesc0f09332012-03-26 13:27:06 -0700663 CHECK_EQ(gBreakpoints.size(), 0U);
664 }
Elliott Hughesa2155262011-11-16 16:26:58 -0800665
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100666 {
Sebastien Hertz4d25df32014-03-21 17:44:46 +0100667 MutexLock mu(Thread::Current(), *deoptimization_lock_);
668 CHECK_EQ(deoptimization_requests_.size(), 0U);
669 CHECK_EQ(full_deoptimization_event_count_, 0U);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +0100670 CHECK_EQ(delayed_full_undeoptimization_count_, 0U);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100671 }
672
Ian Rogers62d6c772013-02-27 08:32:07 -0800673 Runtime* runtime = Runtime::Current();
674 runtime->GetThreadList()->SuspendAll();
675 Thread* self = Thread::Current();
676 ThreadState old_state = self->SetStateUnsafe(kRunnable);
677 CHECK_NE(old_state, kRunnable);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100678 runtime->GetInstrumentation()->EnableDeoptimization();
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200679 runtime->GetInstrumentation()->AddListener(&gDebugInstrumentationListener, kListenerEvents);
Elliott Hughesa2155262011-11-16 16:26:58 -0800680 gDebuggerActive = true;
Ian Rogers62d6c772013-02-27 08:32:07 -0800681 CHECK_EQ(self->SetStateUnsafe(old_state), kRunnable);
682 runtime->GetThreadList()->ResumeAll();
683
684 LOG(INFO) << "Debugger is active";
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700685}
686
687void Dbg::Disconnected() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700688 CHECK(gDebuggerConnected);
689
Elliott Hughesc0f09332012-03-26 13:27:06 -0700690 LOG(INFO) << "Debugger is no longer active";
Elliott Hughes234ab152011-10-26 14:02:26 -0700691
Ian Rogers62d6c772013-02-27 08:32:07 -0800692 // Suspend all threads and exclusively acquire the mutator lock. Set the state of the thread
693 // to kRunnable to avoid scoped object access transitions. Remove the debugger as a listener
694 // and clear the object registry.
695 Runtime* runtime = Runtime::Current();
696 runtime->GetThreadList()->SuspendAll();
697 Thread* self = Thread::Current();
698 ThreadState old_state = self->SetStateUnsafe(kRunnable);
Sebastien Hertzaaea7342014-02-25 15:10:04 +0100699
700 // Debugger may not be active at this point.
701 if (gDebuggerActive) {
702 {
703 // Since we're going to disable deoptimization, we clear the deoptimization requests queue.
704 // This prevents us from having any pending deoptimization request when the debugger attaches
705 // to us again while no event has been requested yet.
Sebastien Hertz4d25df32014-03-21 17:44:46 +0100706 MutexLock mu(Thread::Current(), *deoptimization_lock_);
707 deoptimization_requests_.clear();
708 full_deoptimization_event_count_ = 0U;
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +0100709 delayed_full_undeoptimization_count_ = 0U;
Sebastien Hertzaaea7342014-02-25 15:10:04 +0100710 }
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200711 runtime->GetInstrumentation()->RemoveListener(&gDebugInstrumentationListener, kListenerEvents);
Sebastien Hertzaaea7342014-02-25 15:10:04 +0100712 runtime->GetInstrumentation()->DisableDeoptimization();
713 gDebuggerActive = false;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100714 }
Elliott Hughes234ab152011-10-26 14:02:26 -0700715 gRegistry->Clear();
716 gDebuggerConnected = false;
Ian Rogers62d6c772013-02-27 08:32:07 -0800717 CHECK_EQ(self->SetStateUnsafe(old_state), kRunnable);
718 runtime->GetThreadList()->ResumeAll();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700719}
720
Elliott Hughesc0f09332012-03-26 13:27:06 -0700721bool Dbg::IsDebuggerActive() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700722 return gDebuggerActive;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700723}
724
Elliott Hughesc0f09332012-03-26 13:27:06 -0700725bool Dbg::IsJdwpConfigured() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700726 return gJdwpConfigured;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700727}
728
729int64_t Dbg::LastDebuggerActivity() {
Elliott Hughesca951522011-12-05 12:01:32 -0800730 return gJdwpState->LastDebuggerActivity();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700731}
732
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700733void Dbg::UndoDebuggerSuspensions() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700734 Runtime::Current()->GetThreadList()->UndoDebuggerSuspensions();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700735}
736
Elliott Hughes88d63092013-01-09 09:55:54 -0800737std::string Dbg::GetClassName(JDWP::RefTypeId class_id) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800738 mirror::Object* o = gRegistry->Get<mirror::Object*>(class_id);
Elliott Hughes436e3722012-02-17 20:01:47 -0800739 if (o == NULL) {
740 return "NULL";
741 }
Elliott Hughes64f574f2013-02-20 14:57:12 -0800742 if (o == ObjectRegistry::kInvalidObject) {
Elliott Hughes88d63092013-01-09 09:55:54 -0800743 return StringPrintf("invalid object %p", reinterpret_cast<void*>(class_id));
Elliott Hughes436e3722012-02-17 20:01:47 -0800744 }
745 if (!o->IsClass()) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700746 return StringPrintf("non-class %p", o); // This is only used for debugging output anyway.
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800747 }
Elliott Hughesc308a5d2012-02-16 17:12:06 -0800748 return DescriptorToName(ClassHelper(o->AsClass()).GetDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700749}
750
Elliott Hughes88d63092013-01-09 09:55:54 -0800751JDWP::JdwpError Dbg::GetClassObject(JDWP::RefTypeId id, JDWP::ObjectId& class_object_id) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800752 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800753 mirror::Class* c = DecodeClass(id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -0800754 if (c == NULL) {
755 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800756 }
Elliott Hughes88d63092013-01-09 09:55:54 -0800757 class_object_id = gRegistry->Add(c);
Elliott Hughes436e3722012-02-17 20:01:47 -0800758 return JDWP::ERR_NONE;
Elliott Hughes86964332012-02-15 19:37:42 -0800759}
760
Elliott Hughes88d63092013-01-09 09:55:54 -0800761JDWP::JdwpError Dbg::GetSuperclass(JDWP::RefTypeId id, JDWP::RefTypeId& superclass_id) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800762 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800763 mirror::Class* c = DecodeClass(id, status);
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800764 if (c == NULL) {
765 return status;
766 }
767 if (c->IsInterface()) {
768 // http://code.google.com/p/android/issues/detail?id=20856
Elliott Hughes88d63092013-01-09 09:55:54 -0800769 superclass_id = 0;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800770 } else {
Elliott Hughes88d63092013-01-09 09:55:54 -0800771 superclass_id = gRegistry->Add(c->GetSuperClass());
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800772 }
773 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700774}
775
Elliott Hughes436e3722012-02-17 20:01:47 -0800776JDWP::JdwpError Dbg::GetClassLoader(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800777 mirror::Object* o = gRegistry->Get<mirror::Object*>(id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800778 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800779 return JDWP::ERR_INVALID_OBJECT;
780 }
781 expandBufAddObjectId(pReply, gRegistry->Add(o->GetClass()->GetClassLoader()));
782 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700783}
784
Elliott Hughes436e3722012-02-17 20:01:47 -0800785JDWP::JdwpError Dbg::GetModifiers(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) {
786 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800787 mirror::Class* c = DecodeClass(id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -0800788 if (c == NULL) {
789 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800790 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800791
792 uint32_t access_flags = c->GetAccessFlags() & kAccJavaFlagsMask;
793
Yevgeny Roubande34eea2014-02-15 01:06:03 +0700794 // Set ACC_SUPER. Dex files don't contain this flag but only classes are supposed to have it set,
795 // not interfaces.
Elliott Hughes436e3722012-02-17 20:01:47 -0800796 // Class.getModifiers doesn't return it, but JDWP does, so we set it here.
Yevgeny Roubande34eea2014-02-15 01:06:03 +0700797 if ((access_flags & kAccInterface) == 0) {
798 access_flags |= kAccSuper;
799 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800800
801 expandBufAdd4BE(pReply, access_flags);
802
803 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700804}
805
Elliott Hughesf327e072013-01-09 16:01:26 -0800806JDWP::JdwpError Dbg::GetMonitorInfo(JDWP::ObjectId object_id, JDWP::ExpandBuf* reply)
807 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800808 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800809 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughesf327e072013-01-09 16:01:26 -0800810 return JDWP::ERR_INVALID_OBJECT;
811 }
812
813 // Ensure all threads are suspended while we read objects' lock words.
814 Thread* self = Thread::Current();
Sebastien Hertz54263242014-03-19 18:16:50 +0100815 CHECK_EQ(self->GetState(), kRunnable);
816 self->TransitionFromRunnableToSuspended(kSuspended);
817 Runtime::Current()->GetThreadList()->SuspendAll();
Elliott Hughesf327e072013-01-09 16:01:26 -0800818
819 MonitorInfo monitor_info(o);
820
Sebastien Hertz54263242014-03-19 18:16:50 +0100821 Runtime::Current()->GetThreadList()->ResumeAll();
822 self->TransitionFromSuspendedToRunnable();
Elliott Hughesf327e072013-01-09 16:01:26 -0800823
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700824 if (monitor_info.owner_ != NULL) {
825 expandBufAddObjectId(reply, gRegistry->Add(monitor_info.owner_->GetPeer()));
Elliott Hughesf327e072013-01-09 16:01:26 -0800826 } else {
827 expandBufAddObjectId(reply, gRegistry->Add(NULL));
828 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700829 expandBufAdd4BE(reply, monitor_info.entry_count_);
830 expandBufAdd4BE(reply, monitor_info.waiters_.size());
831 for (size_t i = 0; i < monitor_info.waiters_.size(); ++i) {
832 expandBufAddObjectId(reply, gRegistry->Add(monitor_info.waiters_[i]->GetPeer()));
Elliott Hughesf327e072013-01-09 16:01:26 -0800833 }
834 return JDWP::ERR_NONE;
835}
836
Elliott Hughes734b8c62013-01-11 15:32:45 -0800837JDWP::JdwpError Dbg::GetOwnedMonitors(JDWP::ObjectId thread_id,
838 std::vector<JDWP::ObjectId>& monitors,
Sebastien Hertz52d131d2014-03-13 16:17:40 +0100839 std::vector<uint32_t>& stack_depths) {
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800840 ScopedObjectAccessUnchecked soa(Thread::Current());
841 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
842 Thread* thread;
843 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
844 if (error != JDWP::ERR_NONE) {
845 return error;
846 }
847 if (!IsSuspendedForDebugger(soa, thread)) {
848 return JDWP::ERR_THREAD_NOT_SUSPENDED;
849 }
850
851 struct OwnedMonitorVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -0800852 OwnedMonitorVisitor(Thread* thread, Context* context)
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800853 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -0800854 : StackVisitor(thread, context), current_stack_depth(0) {}
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800855
856 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
857 // annotalysis.
858 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
859 if (!GetMethod()->IsRuntimeMethod()) {
860 Monitor::VisitLocks(this, AppendOwnedMonitors, this);
Elliott Hughes734b8c62013-01-11 15:32:45 -0800861 ++current_stack_depth;
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800862 }
863 return true;
864 }
865
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800866 static void AppendOwnedMonitors(mirror::Object* owned_monitor, void* arg) {
Ian Rogers7a22fa62013-01-23 12:16:16 -0800867 OwnedMonitorVisitor* visitor = reinterpret_cast<OwnedMonitorVisitor*>(arg);
Elliott Hughes734b8c62013-01-11 15:32:45 -0800868 visitor->monitors.push_back(owned_monitor);
869 visitor->stack_depths.push_back(visitor->current_stack_depth);
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800870 }
871
Elliott Hughes734b8c62013-01-11 15:32:45 -0800872 size_t current_stack_depth;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800873 std::vector<mirror::Object*> monitors;
Elliott Hughes734b8c62013-01-11 15:32:45 -0800874 std::vector<uint32_t> stack_depths;
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800875 };
Ian Rogers7a22fa62013-01-23 12:16:16 -0800876 UniquePtr<Context> context(Context::Create());
877 OwnedMonitorVisitor visitor(thread, context.get());
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800878 visitor.WalkStack();
879
880 for (size_t i = 0; i < visitor.monitors.size(); ++i) {
881 monitors.push_back(gRegistry->Add(visitor.monitors[i]));
Elliott Hughes734b8c62013-01-11 15:32:45 -0800882 stack_depths.push_back(visitor.stack_depths[i]);
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800883 }
884
885 return JDWP::ERR_NONE;
886}
887
Sebastien Hertz52d131d2014-03-13 16:17:40 +0100888JDWP::JdwpError Dbg::GetContendedMonitor(JDWP::ObjectId thread_id,
889 JDWP::ObjectId& contended_monitor) {
Elliott Hughesf9501702013-01-11 11:22:27 -0800890 ScopedObjectAccessUnchecked soa(Thread::Current());
891 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
892 Thread* thread;
893 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
894 if (error != JDWP::ERR_NONE) {
895 return error;
896 }
897 if (!IsSuspendedForDebugger(soa, thread)) {
898 return JDWP::ERR_THREAD_NOT_SUSPENDED;
899 }
900
901 contended_monitor = gRegistry->Add(Monitor::GetContendedMonitor(thread));
902
903 return JDWP::ERR_NONE;
904}
905
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800906JDWP::JdwpError Dbg::GetInstanceCounts(const std::vector<JDWP::RefTypeId>& class_ids,
907 std::vector<uint64_t>& counts)
908 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800909 gc::Heap* heap = Runtime::Current()->GetHeap();
910 heap->CollectGarbage(false);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800911 std::vector<mirror::Class*> classes;
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800912 counts.clear();
913 for (size_t i = 0; i < class_ids.size(); ++i) {
914 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800915 mirror::Class* c = DecodeClass(class_ids[i], status);
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800916 if (c == NULL) {
917 return status;
918 }
919 classes.push_back(c);
920 counts.push_back(0);
921 }
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800922 heap->CountInstances(classes, false, &counts[0]);
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800923 return JDWP::ERR_NONE;
924}
925
Elliott Hughes3b78c942013-01-15 17:35:41 -0800926JDWP::JdwpError Dbg::GetInstances(JDWP::RefTypeId class_id, int32_t max_count, std::vector<JDWP::ObjectId>& instances)
927 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800928 gc::Heap* heap = Runtime::Current()->GetHeap();
929 // We only want reachable instances, so do a GC.
930 heap->CollectGarbage(false);
Elliott Hughes3b78c942013-01-15 17:35:41 -0800931 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800932 mirror::Class* c = DecodeClass(class_id, status);
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800933 if (c == nullptr) {
Elliott Hughes3b78c942013-01-15 17:35:41 -0800934 return status;
935 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800936 std::vector<mirror::Object*> raw_instances;
Elliott Hughes3b78c942013-01-15 17:35:41 -0800937 Runtime::Current()->GetHeap()->GetInstances(c, max_count, raw_instances);
938 for (size_t i = 0; i < raw_instances.size(); ++i) {
939 instances.push_back(gRegistry->Add(raw_instances[i]));
940 }
941 return JDWP::ERR_NONE;
942}
943
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800944JDWP::JdwpError Dbg::GetReferringObjects(JDWP::ObjectId object_id, int32_t max_count,
945 std::vector<JDWP::ObjectId>& referring_objects)
946 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800947 gc::Heap* heap = Runtime::Current()->GetHeap();
948 heap->CollectGarbage(false);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800949 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800950 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800951 return JDWP::ERR_INVALID_OBJECT;
952 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800953 std::vector<mirror::Object*> raw_instances;
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800954 heap->GetReferringObjects(o, max_count, raw_instances);
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800955 for (size_t i = 0; i < raw_instances.size(); ++i) {
956 referring_objects.push_back(gRegistry->Add(raw_instances[i]));
957 }
958 return JDWP::ERR_NONE;
959}
960
Elliott Hughes64f574f2013-02-20 14:57:12 -0800961JDWP::JdwpError Dbg::DisableCollection(JDWP::ObjectId object_id)
962 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Sebastien Hertze96060a2013-12-11 12:06:28 +0100963 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
964 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
965 return JDWP::ERR_INVALID_OBJECT;
966 }
Elliott Hughes64f574f2013-02-20 14:57:12 -0800967 gRegistry->DisableCollection(object_id);
968 return JDWP::ERR_NONE;
969}
970
971JDWP::JdwpError Dbg::EnableCollection(JDWP::ObjectId object_id)
972 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Sebastien Hertze96060a2013-12-11 12:06:28 +0100973 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
974 // Unlike DisableCollection, JDWP specs do not state an invalid object causes an error. The RI
975 // also ignores these cases and never return an error. However it's not obvious why this command
976 // should behave differently from DisableCollection and IsCollected commands. So let's be more
977 // strict and return an error if this happens.
978 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
979 return JDWP::ERR_INVALID_OBJECT;
980 }
Elliott Hughes64f574f2013-02-20 14:57:12 -0800981 gRegistry->EnableCollection(object_id);
982 return JDWP::ERR_NONE;
983}
984
985JDWP::JdwpError Dbg::IsCollected(JDWP::ObjectId object_id, bool& is_collected)
986 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Sebastien Hertz65637eb2014-01-10 17:40:02 +0100987 if (object_id == 0) {
988 // Null object id is invalid.
Sebastien Hertze96060a2013-12-11 12:06:28 +0100989 return JDWP::ERR_INVALID_OBJECT;
990 }
Sebastien Hertz65637eb2014-01-10 17:40:02 +0100991 // JDWP specs state an INVALID_OBJECT error is returned if the object ID is not valid. However
992 // the RI seems to ignore this and assume object has been collected.
993 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
994 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
995 is_collected = true;
996 } else {
997 is_collected = gRegistry->IsCollected(object_id);
998 }
Elliott Hughes64f574f2013-02-20 14:57:12 -0800999 return JDWP::ERR_NONE;
1000}
1001
1002void Dbg::DisposeObject(JDWP::ObjectId object_id, uint32_t reference_count)
1003 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1004 gRegistry->DisposeObject(object_id, reference_count);
1005}
1006
Sebastien Hertz4d8fd492014-03-28 16:29:41 +01001007static JDWP::JdwpTypeTag GetTypeTag(mirror::Class* klass)
1008 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1009 DCHECK(klass != nullptr);
1010 if (klass->IsArrayClass()) {
1011 return JDWP::TT_ARRAY;
1012 } else if (klass->IsInterface()) {
1013 return JDWP::TT_INTERFACE;
1014 } else {
1015 return JDWP::TT_CLASS;
1016 }
1017}
1018
Elliott Hughes88d63092013-01-09 09:55:54 -08001019JDWP::JdwpError Dbg::GetReflectedType(JDWP::RefTypeId class_id, JDWP::ExpandBuf* pReply) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001020 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001021 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001022 if (c == NULL) {
1023 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001024 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001025
Sebastien Hertz4d8fd492014-03-28 16:29:41 +01001026 JDWP::JdwpTypeTag type_tag = GetTypeTag(c);
1027 expandBufAdd1(pReply, type_tag);
Elliott Hughes88d63092013-01-09 09:55:54 -08001028 expandBufAddRefTypeId(pReply, class_id);
Elliott Hughes436e3722012-02-17 20:01:47 -08001029 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001030}
1031
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001032void Dbg::GetClassList(std::vector<JDWP::RefTypeId>& classes) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001033 // Get the complete list of reference classes (i.e. all classes except
1034 // the primitive types).
1035 // Returns a newly-allocated buffer full of RefTypeId values.
1036 struct ClassListCreator {
Elliott Hughesba8eee12012-01-24 20:25:24 -08001037 explicit ClassListCreator(std::vector<JDWP::RefTypeId>& classes) : classes(classes) {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001038 }
1039
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001040 static bool Visit(mirror::Class* c, void* arg) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001041 return reinterpret_cast<ClassListCreator*>(arg)->Visit(c);
1042 }
1043
Elliott Hughes64f574f2013-02-20 14:57:12 -08001044 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1045 // annotalysis.
1046 bool Visit(mirror::Class* c) NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughesa2155262011-11-16 16:26:58 -08001047 if (!c->IsPrimitive()) {
Elliott Hughes64f574f2013-02-20 14:57:12 -08001048 classes.push_back(gRegistry->AddRefType(c));
Elliott Hughesa2155262011-11-16 16:26:58 -08001049 }
1050 return true;
1051 }
1052
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001053 std::vector<JDWP::RefTypeId>& classes;
Elliott Hughesa2155262011-11-16 16:26:58 -08001054 };
1055
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001056 ClassListCreator clc(classes);
Elliott Hughesa2155262011-11-16 16:26:58 -08001057 Runtime::Current()->GetClassLinker()->VisitClasses(ClassListCreator::Visit, &clc);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001058}
1059
Elliott Hughes88d63092013-01-09 09:55:54 -08001060JDWP::JdwpError Dbg::GetClassInfo(JDWP::RefTypeId class_id, JDWP::JdwpTypeTag* pTypeTag, uint32_t* pStatus, std::string* pDescriptor) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001061 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001062 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001063 if (c == NULL) {
1064 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001065 }
1066
Elliott Hughesa2155262011-11-16 16:26:58 -08001067 if (c->IsArrayClass()) {
1068 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
1069 *pTypeTag = JDWP::TT_ARRAY;
1070 } else {
1071 if (c->IsErroneous()) {
1072 *pStatus = JDWP::CS_ERROR;
1073 } else {
1074 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED | JDWP::CS_INITIALIZED;
1075 }
1076 *pTypeTag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
1077 }
1078
1079 if (pDescriptor != NULL) {
Ian Rogersdfb325e2013-10-30 01:00:44 -07001080 *pDescriptor = ClassHelper(c).GetDescriptor();
Elliott Hughesa2155262011-11-16 16:26:58 -08001081 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001082 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001083}
1084
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001085void Dbg::FindLoadedClassBySignature(const char* descriptor, std::vector<JDWP::RefTypeId>& ids) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001086 std::vector<mirror::Class*> classes;
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001087 Runtime::Current()->GetClassLinker()->LookupClasses(descriptor, classes);
1088 ids.clear();
1089 for (size_t i = 0; i < classes.size(); ++i) {
1090 ids.push_back(gRegistry->Add(classes[i]));
1091 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001092}
1093
Elliott Hughes64f574f2013-02-20 14:57:12 -08001094JDWP::JdwpError Dbg::GetReferenceType(JDWP::ObjectId object_id, JDWP::ExpandBuf* pReply)
1095 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001096 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001097 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001098 return JDWP::ERR_INVALID_OBJECT;
Elliott Hughes499c5132011-11-17 14:55:11 -08001099 }
Elliott Hughes2435a572012-02-17 16:07:41 -08001100
Sebastien Hertz4d8fd492014-03-28 16:29:41 +01001101 JDWP::JdwpTypeTag type_tag = GetTypeTag(o->GetClass());
Elliott Hughes64f574f2013-02-20 14:57:12 -08001102 JDWP::RefTypeId type_id = gRegistry->AddRefType(o->GetClass());
Elliott Hughes2435a572012-02-17 16:07:41 -08001103
1104 expandBufAdd1(pReply, type_tag);
1105 expandBufAddRefTypeId(pReply, type_id);
1106
1107 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001108}
1109
Ian Rogersfc0e94b2013-09-23 23:51:32 -07001110JDWP::JdwpError Dbg::GetSignature(JDWP::RefTypeId class_id, std::string* signature) {
Elliott Hughes1fe7afb2012-02-13 17:23:03 -08001111 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001112 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes1fe7afb2012-02-13 17:23:03 -08001113 if (c == NULL) {
1114 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001115 }
Ian Rogersdfb325e2013-10-30 01:00:44 -07001116 *signature = ClassHelper(c).GetDescriptor();
Elliott Hughes1fe7afb2012-02-13 17:23:03 -08001117 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001118}
1119
Elliott Hughes88d63092013-01-09 09:55:54 -08001120JDWP::JdwpError Dbg::GetSourceFile(JDWP::RefTypeId class_id, std::string& result) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001121 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001122 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001123 if (c == NULL) {
1124 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001125 }
Sebastien Hertzb7054ba2014-03-13 11:52:31 +01001126 if (c->IsProxyClass()) {
1127 return JDWP::ERR_ABSENT_INFORMATION;
1128 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001129 result = ClassHelper(c).GetSourceFile();
1130 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001131}
1132
Elliott Hughes88d63092013-01-09 09:55:54 -08001133JDWP::JdwpError Dbg::GetObjectTag(JDWP::ObjectId object_id, uint8_t& tag) {
Ian Rogers98379392014-02-24 16:53:16 -08001134 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001135 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001136 if (o == ObjectRegistry::kInvalidObject) {
Elliott Hughes546b9862012-06-20 16:06:13 -07001137 return JDWP::ERR_INVALID_OBJECT;
1138 }
Ian Rogers98379392014-02-24 16:53:16 -08001139 tag = TagFromObject(soa, o);
Elliott Hughes546b9862012-06-20 16:06:13 -07001140 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001141}
1142
Elliott Hughesaed4be92011-12-02 16:16:23 -08001143size_t Dbg::GetTagWidth(JDWP::JdwpTag tag) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001144 switch (tag) {
1145 case JDWP::JT_VOID:
1146 return 0;
1147 case JDWP::JT_BYTE:
1148 case JDWP::JT_BOOLEAN:
1149 return 1;
1150 case JDWP::JT_CHAR:
1151 case JDWP::JT_SHORT:
1152 return 2;
1153 case JDWP::JT_FLOAT:
1154 case JDWP::JT_INT:
1155 return 4;
1156 case JDWP::JT_ARRAY:
1157 case JDWP::JT_OBJECT:
1158 case JDWP::JT_STRING:
1159 case JDWP::JT_THREAD:
1160 case JDWP::JT_THREAD_GROUP:
1161 case JDWP::JT_CLASS_LOADER:
1162 case JDWP::JT_CLASS_OBJECT:
1163 return sizeof(JDWP::ObjectId);
1164 case JDWP::JT_DOUBLE:
1165 case JDWP::JT_LONG:
1166 return 8;
1167 default:
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001168 LOG(FATAL) << "Unknown tag " << tag;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001169 return -1;
1170 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001171}
1172
Elliott Hughes88d63092013-01-09 09:55:54 -08001173JDWP::JdwpError Dbg::GetArrayLength(JDWP::ObjectId array_id, int& length) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001174 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001175 mirror::Array* a = DecodeArray(array_id, status);
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001176 if (a == NULL) {
1177 return status;
Elliott Hughes24437992011-11-30 14:49:33 -08001178 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001179 length = a->GetLength();
1180 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001181}
1182
Elliott Hughes88d63092013-01-09 09:55:54 -08001183JDWP::JdwpError Dbg::OutputArray(JDWP::ObjectId array_id, int offset, int count, JDWP::ExpandBuf* pReply) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001184 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001185 mirror::Array* a = DecodeArray(array_id, status);
Ian Rogers98379392014-02-24 16:53:16 -08001186 if (a == nullptr) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001187 return status;
1188 }
Elliott Hughes24437992011-11-30 14:49:33 -08001189
1190 if (offset < 0 || count < 0 || offset > a->GetLength() || a->GetLength() - offset < count) {
1191 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001192 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughes24437992011-11-30 14:49:33 -08001193 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001194 std::string descriptor(ClassHelper(a->GetClass()).GetDescriptor());
Elliott Hughes24437992011-11-30 14:49:33 -08001195 JDWP::JdwpTag tag = BasicTagFromDescriptor(descriptor.c_str() + 1);
1196
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001197 expandBufAdd1(pReply, tag);
1198 expandBufAdd4BE(pReply, count);
1199
Elliott Hughes24437992011-11-30 14:49:33 -08001200 if (IsPrimitiveTag(tag)) {
1201 size_t width = GetTagWidth(tag);
Elliott Hughes24437992011-11-30 14:49:33 -08001202 uint8_t* dst = expandBufAddSpace(pReply, count * width);
1203 if (width == 8) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001204 const uint64_t* src8 = reinterpret_cast<uint64_t*>(a->GetRawData(sizeof(uint64_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001205 for (int i = 0; i < count; ++i) JDWP::Write8BE(&dst, src8[offset + i]);
1206 } else if (width == 4) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001207 const uint32_t* src4 = reinterpret_cast<uint32_t*>(a->GetRawData(sizeof(uint32_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001208 for (int i = 0; i < count; ++i) JDWP::Write4BE(&dst, src4[offset + i]);
1209 } else if (width == 2) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001210 const uint16_t* src2 = reinterpret_cast<uint16_t*>(a->GetRawData(sizeof(uint16_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001211 for (int i = 0; i < count; ++i) JDWP::Write2BE(&dst, src2[offset + i]);
1212 } else {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001213 const uint8_t* src = reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint8_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001214 memcpy(dst, &src[offset * width], count * width);
1215 }
1216 } else {
Ian Rogers98379392014-02-24 16:53:16 -08001217 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001218 mirror::ObjectArray<mirror::Object>* oa = a->AsObjectArray<mirror::Object>();
Elliott Hughes24437992011-11-30 14:49:33 -08001219 for (int i = 0; i < count; ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001220 mirror::Object* element = oa->Get(offset + i);
Ian Rogers98379392014-02-24 16:53:16 -08001221 JDWP::JdwpTag specific_tag = (element != nullptr) ? TagFromObject(soa, element)
1222 : tag;
Elliott Hughes24437992011-11-30 14:49:33 -08001223 expandBufAdd1(pReply, specific_tag);
1224 expandBufAddObjectId(pReply, gRegistry->Add(element));
1225 }
1226 }
1227
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001228 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001229}
1230
Ian Rogersef7d42f2014-01-06 12:55:46 -08001231template <typename T>
1232static void CopyArrayData(mirror::Array* a, JDWP::Request& src, int offset, int count)
1233 NO_THREAD_SAFETY_ANALYSIS {
1234 // TODO: fix when annotalysis correctly handles non-member functions.
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001235 DCHECK(a->GetClass()->IsPrimitiveArray());
1236
Ian Rogersef7d42f2014-01-06 12:55:46 -08001237 T* dst = reinterpret_cast<T*>(a->GetRawData(sizeof(T), offset));
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001238 for (int i = 0; i < count; ++i) {
1239 *dst++ = src.ReadValue(sizeof(T));
1240 }
1241}
1242
Elliott Hughes88d63092013-01-09 09:55:54 -08001243JDWP::JdwpError Dbg::SetArrayElements(JDWP::ObjectId array_id, int offset, int count,
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001244 JDWP::Request& request)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001245 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001246 JDWP::JdwpError status;
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001247 mirror::Array* dst = DecodeArray(array_id, status);
1248 if (dst == NULL) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001249 return status;
1250 }
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001251
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001252 if (offset < 0 || count < 0 || offset > dst->GetLength() || dst->GetLength() - offset < count) {
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001253 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001254 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001255 }
nikolay serdjuk1d66e882014-04-07 13:54:24 +07001256 ClassHelper ch(dst->GetClass());
1257 const char* descriptor = ch.GetDescriptor();
Ian Rogersfc0e94b2013-09-23 23:51:32 -07001258 JDWP::JdwpTag tag = BasicTagFromDescriptor(descriptor + 1);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001259
1260 if (IsPrimitiveTag(tag)) {
1261 size_t width = GetTagWidth(tag);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001262 if (width == 8) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001263 CopyArrayData<uint64_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001264 } else if (width == 4) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001265 CopyArrayData<uint32_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001266 } else if (width == 2) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001267 CopyArrayData<uint16_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001268 } else {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001269 CopyArrayData<uint8_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001270 }
1271 } else {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001272 mirror::ObjectArray<mirror::Object>* oa = dst->AsObjectArray<mirror::Object>();
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001273 for (int i = 0; i < count; ++i) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001274 JDWP::ObjectId id = request.ReadObjectId();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001275 mirror::Object* o = gRegistry->Get<mirror::Object*>(id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001276 if (o == ObjectRegistry::kInvalidObject) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001277 return JDWP::ERR_INVALID_OBJECT;
1278 }
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001279 oa->Set<false>(offset + i, o);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001280 }
1281 }
1282
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001283 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001284}
1285
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001286JDWP::ObjectId Dbg::CreateString(const std::string& str) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001287 return gRegistry->Add(mirror::String::AllocFromModifiedUtf8(Thread::Current(), str.c_str()));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001288}
1289
Elliott Hughes88d63092013-01-09 09:55:54 -08001290JDWP::JdwpError Dbg::CreateObject(JDWP::RefTypeId class_id, JDWP::ObjectId& new_object) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001291 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001292 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001293 if (c == NULL) {
1294 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001295 }
Ian Rogers50b35e22012-10-04 10:09:15 -07001296 new_object = gRegistry->Add(c->AllocObject(Thread::Current()));
Elliott Hughes436e3722012-02-17 20:01:47 -08001297 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001298}
1299
Elliott Hughesbf13d362011-12-08 15:51:37 -08001300/*
1301 * Used by Eclipse's "Display" view to evaluate "new byte[5]" to get "(byte[]) [0, 0, 0, 0, 0]".
1302 */
Elliott Hughes88d63092013-01-09 09:55:54 -08001303JDWP::JdwpError Dbg::CreateArrayObject(JDWP::RefTypeId array_class_id, uint32_t length,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001304 JDWP::ObjectId& new_array) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001305 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001306 mirror::Class* c = DecodeClass(array_class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001307 if (c == NULL) {
1308 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001309 }
Ian Rogers6fac4472014-02-25 17:01:10 -08001310 new_array = gRegistry->Add(mirror::Array::Alloc<true>(Thread::Current(), c, length,
1311 c->GetComponentSize(),
1312 Runtime::Current()->GetHeap()->GetCurrentAllocator()));
Elliott Hughes436e3722012-02-17 20:01:47 -08001313 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001314}
1315
Elliott Hughes88d63092013-01-09 09:55:54 -08001316bool Dbg::MatchType(JDWP::RefTypeId instance_class_id, JDWP::RefTypeId class_id) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001317 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001318 mirror::Class* c1 = DecodeClass(instance_class_id, status);
Elliott Hughesa656a0f2012-02-21 18:03:44 -08001319 CHECK(c1 != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001320 mirror::Class* c2 = DecodeClass(class_id, status);
Elliott Hughesa656a0f2012-02-21 18:03:44 -08001321 CHECK(c2 != NULL);
Sebastien Hertz123756a2013-11-27 15:49:42 +01001322 return c2->IsAssignableFrom(c1);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001323}
1324
Brian Carlstromea46f952013-07-30 01:26:50 -07001325static JDWP::FieldId ToFieldId(const mirror::ArtField* f)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001326 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001327 CHECK(!kMovingFields);
Elliott Hughes03181a82011-11-17 17:22:21 -08001328 return static_cast<JDWP::FieldId>(reinterpret_cast<uintptr_t>(f));
Elliott Hughes03181a82011-11-17 17:22:21 -08001329}
1330
Brian Carlstromea46f952013-07-30 01:26:50 -07001331static JDWP::MethodId ToMethodId(const mirror::ArtMethod* m)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001332 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001333 CHECK(!kMovingMethods);
Elliott Hughes03181a82011-11-17 17:22:21 -08001334 return static_cast<JDWP::MethodId>(reinterpret_cast<uintptr_t>(m));
Elliott Hughes03181a82011-11-17 17:22:21 -08001335}
1336
Brian Carlstromea46f952013-07-30 01:26:50 -07001337static mirror::ArtField* FromFieldId(JDWP::FieldId fid)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001338 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001339 CHECK(!kMovingFields);
Brian Carlstromea46f952013-07-30 01:26:50 -07001340 return reinterpret_cast<mirror::ArtField*>(static_cast<uintptr_t>(fid));
Elliott Hughesaed4be92011-12-02 16:16:23 -08001341}
1342
Brian Carlstromea46f952013-07-30 01:26:50 -07001343static mirror::ArtMethod* FromMethodId(JDWP::MethodId mid)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001344 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001345 CHECK(!kMovingMethods);
Brian Carlstromea46f952013-07-30 01:26:50 -07001346 return reinterpret_cast<mirror::ArtMethod*>(static_cast<uintptr_t>(mid));
Elliott Hughes03181a82011-11-17 17:22:21 -08001347}
1348
Brian Carlstromea46f952013-07-30 01:26:50 -07001349static void SetLocation(JDWP::JdwpLocation& location, mirror::ArtMethod* m, uint32_t dex_pc)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001350 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001351 if (m == NULL) {
1352 memset(&location, 0, sizeof(location));
1353 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001354 mirror::Class* c = m->GetDeclaringClass();
Sebastien Hertz4d8fd492014-03-28 16:29:41 +01001355 location.type_tag = GetTypeTag(c);
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001356 location.class_id = gRegistry->AddRefType(c);
Elliott Hughes74847412012-06-20 18:10:21 -07001357 location.method_id = ToMethodId(m);
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001358 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
Elliott Hughesa96836a2013-01-17 12:27:49 -08001362std::string Dbg::GetMethodName(JDWP::MethodId method_id)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001363 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001364 mirror::ArtMethod* m = FromMethodId(method_id);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001365 return MethodHelper(m).GetName();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001366}
1367
Elliott Hughesa96836a2013-01-17 12:27:49 -08001368std::string Dbg::GetFieldName(JDWP::FieldId field_id)
1369 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001370 mirror::ArtField* f = FromFieldId(field_id);
Elliott Hughesa96836a2013-01-17 12:27:49 -08001371 return FieldHelper(f).GetName();
1372}
1373
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001374/*
1375 * Augment the access flags for synthetic methods and fields by setting
1376 * the (as described by the spec) "0xf0000000 bit". Also, strip out any
1377 * flags not specified by the Java programming language.
1378 */
1379static uint32_t MangleAccessFlags(uint32_t accessFlags) {
1380 accessFlags &= kAccJavaFlagsMask;
1381 if ((accessFlags & kAccSynthetic) != 0) {
1382 accessFlags |= 0xf0000000;
1383 }
1384 return accessFlags;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001385}
1386
Elliott Hughesdbb40792011-11-18 17:05:22 -08001387/*
Jeff Haob7cefc72013-11-14 14:51:09 -08001388 * Circularly shifts registers so that arguments come first. Debuggers
1389 * expect slots to begin with arguments, but dex code places them at
1390 * the end.
Elliott Hughesdbb40792011-11-18 17:05:22 -08001391 */
Jeff Haob7cefc72013-11-14 14:51:09 -08001392static uint16_t MangleSlot(uint16_t slot, mirror::ArtMethod* m)
1393 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1394 const DexFile::CodeItem* code_item = MethodHelper(m).GetCodeItem();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001395 if (code_item == nullptr) {
1396 // We should not get here for a method without code (native, proxy or abstract). Log it and
1397 // return the slot as is since all registers are arguments.
1398 LOG(WARNING) << "Trying to mangle slot for method without code " << PrettyMethod(m);
1399 return slot;
1400 }
Jeff Haob7cefc72013-11-14 14:51:09 -08001401 uint16_t ins_size = code_item->ins_size_;
1402 uint16_t locals_size = code_item->registers_size_ - ins_size;
1403 if (slot >= locals_size) {
1404 return slot - locals_size;
1405 } else {
1406 return slot + ins_size;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001407 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001408}
1409
Jeff Haob7cefc72013-11-14 14:51:09 -08001410/*
1411 * Circularly shifts registers so that arguments come last. Reverts
1412 * slots to dex style argument placement.
1413 */
Brian Carlstromea46f952013-07-30 01:26:50 -07001414static uint16_t DemangleSlot(uint16_t slot, mirror::ArtMethod* m)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001415 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Jeff Haob7cefc72013-11-14 14:51:09 -08001416 const DexFile::CodeItem* code_item = MethodHelper(m).GetCodeItem();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001417 if (code_item == nullptr) {
1418 // We should not get here for a method without code (native, proxy or abstract). Log it and
1419 // return the slot as is since all registers are arguments.
1420 LOG(WARNING) << "Trying to demangle slot for method without code " << PrettyMethod(m);
1421 return slot;
1422 }
Jeff Haob7cefc72013-11-14 14:51:09 -08001423 uint16_t ins_size = code_item->ins_size_;
1424 uint16_t locals_size = code_item->registers_size_ - ins_size;
1425 if (slot < ins_size) {
1426 return slot + locals_size;
1427 } else {
1428 return slot - ins_size;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001429 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001430}
1431
Elliott Hughes88d63092013-01-09 09:55:54 -08001432JDWP::JdwpError Dbg::OutputDeclaredFields(JDWP::RefTypeId class_id, bool with_generic, JDWP::ExpandBuf* pReply) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001433 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001434 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001435 if (c == NULL) {
1436 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001437 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001438
1439 size_t instance_field_count = c->NumInstanceFields();
1440 size_t static_field_count = c->NumStaticFields();
1441
1442 expandBufAdd4BE(pReply, instance_field_count + static_field_count);
1443
1444 for (size_t i = 0; i < instance_field_count + static_field_count; ++i) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001445 mirror::ArtField* f = (i < instance_field_count) ? c->GetInstanceField(i) : c->GetStaticField(i - instance_field_count);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001446 FieldHelper fh(f);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001447 expandBufAddFieldId(pReply, ToFieldId(f));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001448 expandBufAddUtf8String(pReply, fh.GetName());
1449 expandBufAddUtf8String(pReply, fh.GetTypeDescriptor());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001450 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001451 static const char genericSignature[1] = "";
1452 expandBufAddUtf8String(pReply, genericSignature);
1453 }
1454 expandBufAdd4BE(pReply, MangleAccessFlags(f->GetAccessFlags()));
1455 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001456 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001457}
1458
Elliott Hughes88d63092013-01-09 09:55:54 -08001459JDWP::JdwpError Dbg::OutputDeclaredMethods(JDWP::RefTypeId class_id, bool with_generic,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001460 JDWP::ExpandBuf* pReply) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001461 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001462 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001463 if (c == NULL) {
1464 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001465 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001466
1467 size_t direct_method_count = c->NumDirectMethods();
1468 size_t virtual_method_count = c->NumVirtualMethods();
1469
1470 expandBufAdd4BE(pReply, direct_method_count + virtual_method_count);
1471
1472 for (size_t i = 0; i < direct_method_count + virtual_method_count; ++i) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001473 mirror::ArtMethod* m = (i < direct_method_count) ? c->GetDirectMethod(i) : c->GetVirtualMethod(i - direct_method_count);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001474 MethodHelper mh(m);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001475 expandBufAddMethodId(pReply, ToMethodId(m));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001476 expandBufAddUtf8String(pReply, mh.GetName());
Ian Rogersd91d6d62013-09-25 20:26:14 -07001477 expandBufAddUtf8String(pReply, mh.GetSignature().ToString());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001478 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001479 static const char genericSignature[1] = "";
1480 expandBufAddUtf8String(pReply, genericSignature);
1481 }
1482 expandBufAdd4BE(pReply, MangleAccessFlags(m->GetAccessFlags()));
1483 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001484 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001485}
1486
Elliott Hughes88d63092013-01-09 09:55:54 -08001487JDWP::JdwpError Dbg::OutputDeclaredInterfaces(JDWP::RefTypeId class_id, JDWP::ExpandBuf* pReply) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001488 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001489 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001490 if (c == NULL) {
1491 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001492 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001493
1494 ClassHelper kh(c);
Ian Rogersd24e2642012-06-06 21:21:43 -07001495 size_t interface_count = kh.NumDirectInterfaces();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001496 expandBufAdd4BE(pReply, interface_count);
1497 for (size_t i = 0; i < interface_count; ++i) {
Elliott Hughes64f574f2013-02-20 14:57:12 -08001498 expandBufAddRefTypeId(pReply, gRegistry->AddRefType(kh.GetDirectInterface(i)));
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001499 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001500 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001501}
1502
Elliott Hughes88d63092013-01-09 09:55:54 -08001503void Dbg::OutputLineTable(JDWP::RefTypeId, JDWP::MethodId method_id, JDWP::ExpandBuf* pReply)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001504 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001505 struct DebugCallbackContext {
1506 int numItems;
1507 JDWP::ExpandBuf* pReply;
1508
Elliott Hughes2435a572012-02-17 16:07:41 -08001509 static bool Callback(void* context, uint32_t address, uint32_t line_number) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001510 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
1511 expandBufAdd8BE(pContext->pReply, address);
Elliott Hughes2435a572012-02-17 16:07:41 -08001512 expandBufAdd4BE(pContext->pReply, line_number);
Elliott Hughes03181a82011-11-17 17:22:21 -08001513 pContext->numItems++;
Sebastien Hertzf2910ee2013-10-19 16:39:24 +02001514 return false;
Elliott Hughes03181a82011-11-17 17:22:21 -08001515 }
1516 };
Brian Carlstromea46f952013-07-30 01:26:50 -07001517 mirror::ArtMethod* m = FromMethodId(method_id);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001518 MethodHelper mh(m);
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001519 const DexFile::CodeItem* code_item = mh.GetCodeItem();
Elliott Hughes03181a82011-11-17 17:22:21 -08001520 uint64_t start, end;
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001521 if (code_item == nullptr) {
1522 DCHECK(m->IsNative() || m->IsProxyMethod());
Elliott Hughes03181a82011-11-17 17:22:21 -08001523 start = -1;
1524 end = -1;
1525 } else {
1526 start = 0;
jeffhao14f0db92012-12-14 17:50:42 -08001527 // Return the index of the last instruction
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001528 end = code_item->insns_size_in_code_units_ - 1;
Elliott Hughes03181a82011-11-17 17:22:21 -08001529 }
1530
1531 expandBufAdd8BE(pReply, start);
1532 expandBufAdd8BE(pReply, end);
1533
1534 // Add numLines later
1535 size_t numLinesOffset = expandBufGetLength(pReply);
1536 expandBufAdd4BE(pReply, 0);
1537
1538 DebugCallbackContext context;
1539 context.numItems = 0;
1540 context.pReply = pReply;
1541
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001542 if (code_item != nullptr) {
1543 mh.GetDexFile().DecodeDebugInfo(code_item, m->IsStatic(), m->GetDexMethodIndex(),
1544 DebugCallbackContext::Callback, NULL, &context);
1545 }
Elliott Hughes03181a82011-11-17 17:22:21 -08001546
1547 JDWP::Set4BE(expandBufGetBuffer(pReply) + numLinesOffset, context.numItems);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001548}
1549
Elliott Hughes88d63092013-01-09 09:55:54 -08001550void Dbg::OutputVariableTable(JDWP::RefTypeId, JDWP::MethodId method_id, bool with_generic, JDWP::ExpandBuf* pReply) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001551 struct DebugCallbackContext {
Jeff Haob7cefc72013-11-14 14:51:09 -08001552 mirror::ArtMethod* method;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001553 JDWP::ExpandBuf* pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001554 size_t variable_count;
1555 bool with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001556
Jeff Haob7cefc72013-11-14 14:51:09 -08001557 static void Callback(void* context, uint16_t slot, uint32_t startAddress, uint32_t endAddress, const char* name, const char* descriptor, const char* signature)
1558 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001559 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
1560
Jeff Haob7cefc72013-11-14 14:51:09 -08001561 VLOG(jdwp) << StringPrintf(" %2zd: %d(%d) '%s' '%s' '%s' actual slot=%d mangled slot=%d", pContext->variable_count, startAddress, endAddress - startAddress, name, descriptor, signature, slot, MangleSlot(slot, pContext->method));
Elliott Hughesdbb40792011-11-18 17:05:22 -08001562
Jeff Haob7cefc72013-11-14 14:51:09 -08001563 slot = MangleSlot(slot, pContext->method);
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001564
Elliott Hughesdbb40792011-11-18 17:05:22 -08001565 expandBufAdd8BE(pContext->pReply, startAddress);
1566 expandBufAddUtf8String(pContext->pReply, name);
1567 expandBufAddUtf8String(pContext->pReply, descriptor);
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001568 if (pContext->with_generic) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001569 expandBufAddUtf8String(pContext->pReply, signature);
1570 }
1571 expandBufAdd4BE(pContext->pReply, endAddress - startAddress);
1572 expandBufAdd4BE(pContext->pReply, slot);
1573
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001574 ++pContext->variable_count;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001575 }
1576 };
Brian Carlstromea46f952013-07-30 01:26:50 -07001577 mirror::ArtMethod* m = FromMethodId(method_id);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001578 MethodHelper mh(m);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001579
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001580 // arg_count considers doubles and longs to take 2 units.
1581 // variable_count considers everything to take 1 unit.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001582 std::string shorty(mh.GetShorty());
Brian Carlstromea46f952013-07-30 01:26:50 -07001583 expandBufAdd4BE(pReply, mirror::ArtMethod::NumArgRegisters(shorty));
Elliott Hughesdbb40792011-11-18 17:05:22 -08001584
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001585 // We don't know the total number of variables yet, so leave a blank and update it later.
1586 size_t variable_count_offset = expandBufGetLength(pReply);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001587 expandBufAdd4BE(pReply, 0);
1588
1589 DebugCallbackContext context;
Jeff Haob7cefc72013-11-14 14:51:09 -08001590 context.method = m;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001591 context.pReply = pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001592 context.variable_count = 0;
1593 context.with_generic = with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001594
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001595 const DexFile::CodeItem* code_item = mh.GetCodeItem();
1596 if (code_item != nullptr) {
1597 mh.GetDexFile().DecodeDebugInfo(code_item, m->IsStatic(), m->GetDexMethodIndex(), NULL,
1598 DebugCallbackContext::Callback, &context);
1599 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001600
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001601 JDWP::Set4BE(expandBufGetBuffer(pReply) + variable_count_offset, context.variable_count);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001602}
1603
Jeff Hao579b0242013-11-18 13:16:49 -08001604void Dbg::OutputMethodReturnValue(JDWP::MethodId method_id, const JValue* return_value,
1605 JDWP::ExpandBuf* pReply) {
1606 mirror::ArtMethod* m = FromMethodId(method_id);
1607 JDWP::JdwpTag tag = BasicTagFromDescriptor(MethodHelper(m).GetShorty());
1608 OutputJValue(tag, return_value, pReply);
1609}
1610
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02001611void Dbg::OutputFieldValue(JDWP::FieldId field_id, const JValue* field_value,
1612 JDWP::ExpandBuf* pReply) {
1613 mirror::ArtField* f = FromFieldId(field_id);
1614 JDWP::JdwpTag tag = BasicTagFromDescriptor(FieldHelper(f).GetTypeDescriptor());
1615 OutputJValue(tag, field_value, pReply);
1616}
1617
Elliott Hughes9777ba22013-01-17 09:04:19 -08001618JDWP::JdwpError Dbg::GetBytecodes(JDWP::RefTypeId, JDWP::MethodId method_id,
1619 std::vector<uint8_t>& bytecodes)
1620 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001621 mirror::ArtMethod* m = FromMethodId(method_id);
Elliott Hughes9777ba22013-01-17 09:04:19 -08001622 if (m == NULL) {
1623 return JDWP::ERR_INVALID_METHODID;
1624 }
1625 MethodHelper mh(m);
1626 const DexFile::CodeItem* code_item = mh.GetCodeItem();
1627 size_t byte_count = code_item->insns_size_in_code_units_ * 2;
1628 const uint8_t* begin = reinterpret_cast<const uint8_t*>(code_item->insns_);
1629 const uint8_t* end = begin + byte_count;
1630 for (const uint8_t* p = begin; p != end; ++p) {
1631 bytecodes.push_back(*p);
1632 }
1633 return JDWP::ERR_NONE;
1634}
1635
Elliott Hughes88d63092013-01-09 09:55:54 -08001636JDWP::JdwpTag Dbg::GetFieldBasicTag(JDWP::FieldId field_id) {
1637 return BasicTagFromDescriptor(FieldHelper(FromFieldId(field_id)).GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001638}
1639
Elliott Hughes88d63092013-01-09 09:55:54 -08001640JDWP::JdwpTag Dbg::GetStaticFieldBasicTag(JDWP::FieldId field_id) {
1641 return BasicTagFromDescriptor(FieldHelper(FromFieldId(field_id)).GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001642}
1643
Elliott Hughes88d63092013-01-09 09:55:54 -08001644static JDWP::JdwpError GetFieldValueImpl(JDWP::RefTypeId ref_type_id, JDWP::ObjectId object_id,
1645 JDWP::FieldId field_id, JDWP::ExpandBuf* pReply,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001646 bool is_static)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001647 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes0cf74332012-02-23 23:14:00 -08001648 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001649 mirror::Class* c = DecodeClass(ref_type_id, status);
Elliott Hughes88d63092013-01-09 09:55:54 -08001650 if (ref_type_id != 0 && c == NULL) {
Elliott Hughes0cf74332012-02-23 23:14:00 -08001651 return status;
1652 }
1653
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001654 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001655 if ((!is_static && o == NULL) || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001656 return JDWP::ERR_INVALID_OBJECT;
1657 }
Brian Carlstromea46f952013-07-30 01:26:50 -07001658 mirror::ArtField* f = FromFieldId(field_id);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001659
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001660 mirror::Class* receiver_class = c;
Elliott Hughes0cf74332012-02-23 23:14:00 -08001661 if (receiver_class == NULL && o != NULL) {
1662 receiver_class = o->GetClass();
1663 }
1664 // TODO: should we give up now if receiver_class is NULL?
1665 if (receiver_class != NULL && !f->GetDeclaringClass()->IsAssignableFrom(receiver_class)) {
1666 LOG(INFO) << "ERR_INVALID_FIELDID: " << PrettyField(f) << " " << PrettyClass(receiver_class);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001667 return JDWP::ERR_INVALID_FIELDID;
1668 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001669
Elliott Hughes0cf74332012-02-23 23:14:00 -08001670 // The RI only enforces the static/non-static mismatch in one direction.
1671 // TODO: should we change the tests and check both?
1672 if (is_static) {
1673 if (!f->IsStatic()) {
1674 return JDWP::ERR_INVALID_FIELDID;
1675 }
1676 } else {
1677 if (f->IsStatic()) {
1678 LOG(WARNING) << "Ignoring non-NULL receiver for ObjectReference.SetValues on static field " << PrettyField(f);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001679 }
1680 }
jeffhao0dfbb7e2012-11-28 15:26:03 -08001681 if (f->IsStatic()) {
1682 o = f->GetDeclaringClass();
1683 }
Elliott Hughes0cf74332012-02-23 23:14:00 -08001684
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001685 JDWP::JdwpTag tag = BasicTagFromDescriptor(FieldHelper(f).GetTypeDescriptor());
Jeff Hao579b0242013-11-18 13:16:49 -08001686 JValue field_value;
1687 if (tag == JDWP::JT_VOID) {
1688 LOG(FATAL) << "Unknown tag: " << tag;
1689 } else if (!IsPrimitiveTag(tag)) {
1690 field_value.SetL(f->GetObject(o));
1691 } else if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
1692 field_value.SetJ(f->Get64(o));
Elliott Hughesaed4be92011-12-02 16:16:23 -08001693 } else {
Jeff Hao579b0242013-11-18 13:16:49 -08001694 field_value.SetI(f->Get32(o));
Elliott Hughesaed4be92011-12-02 16:16:23 -08001695 }
Jeff Hao579b0242013-11-18 13:16:49 -08001696 Dbg::OutputJValue(tag, &field_value, pReply);
1697
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001698 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001699}
1700
Elliott Hughes88d63092013-01-09 09:55:54 -08001701JDWP::JdwpError Dbg::GetFieldValue(JDWP::ObjectId object_id, JDWP::FieldId field_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001702 JDWP::ExpandBuf* pReply) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001703 return GetFieldValueImpl(0, object_id, field_id, pReply, false);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001704}
1705
Elliott Hughes88d63092013-01-09 09:55:54 -08001706JDWP::JdwpError Dbg::GetStaticFieldValue(JDWP::RefTypeId ref_type_id, JDWP::FieldId field_id, JDWP::ExpandBuf* pReply) {
1707 return GetFieldValueImpl(ref_type_id, 0, field_id, pReply, true);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001708}
1709
Elliott Hughes88d63092013-01-09 09:55:54 -08001710static JDWP::JdwpError SetFieldValueImpl(JDWP::ObjectId object_id, JDWP::FieldId field_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001711 uint64_t value, int width, bool is_static)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001712 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001713 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001714 if ((!is_static && o == NULL) || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001715 return JDWP::ERR_INVALID_OBJECT;
1716 }
Brian Carlstromea46f952013-07-30 01:26:50 -07001717 mirror::ArtField* f = FromFieldId(field_id);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001718
1719 // The RI only enforces the static/non-static mismatch in one direction.
1720 // TODO: should we change the tests and check both?
1721 if (is_static) {
1722 if (!f->IsStatic()) {
1723 return JDWP::ERR_INVALID_FIELDID;
1724 }
1725 } else {
1726 if (f->IsStatic()) {
1727 LOG(WARNING) << "Ignoring non-NULL receiver for ObjectReference.SetValues on static field " << PrettyField(f);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001728 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001729 }
jeffhao0dfbb7e2012-11-28 15:26:03 -08001730 if (f->IsStatic()) {
1731 o = f->GetDeclaringClass();
1732 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001733
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001734 JDWP::JdwpTag tag = BasicTagFromDescriptor(FieldHelper(f).GetTypeDescriptor());
Elliott Hughesaed4be92011-12-02 16:16:23 -08001735
1736 if (IsPrimitiveTag(tag)) {
1737 if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001738 CHECK_EQ(width, 8);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001739 // Debugging can't use transactional mode (runtime only).
1740 f->Set64<false>(o, value);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001741 } else {
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001742 CHECK_LE(width, 4);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001743 // Debugging can't use transactional mode (runtime only).
1744 f->Set32<false>(o, value);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001745 }
1746 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001747 mirror::Object* v = gRegistry->Get<mirror::Object*>(value);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001748 if (v == ObjectRegistry::kInvalidObject) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001749 return JDWP::ERR_INVALID_OBJECT;
1750 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001751 if (v != NULL) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001752 mirror::Class* field_type = FieldHelper(f).GetType();
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001753 if (!field_type->IsAssignableFrom(v->GetClass())) {
1754 return JDWP::ERR_INVALID_OBJECT;
1755 }
1756 }
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001757 // Debugging can't use transactional mode (runtime only).
1758 f->SetObject<false>(o, v);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001759 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001760
1761 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001762}
1763
Elliott Hughes88d63092013-01-09 09:55:54 -08001764JDWP::JdwpError Dbg::SetFieldValue(JDWP::ObjectId object_id, JDWP::FieldId field_id, uint64_t value,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001765 int width) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001766 return SetFieldValueImpl(object_id, field_id, value, width, false);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001767}
1768
Elliott Hughes88d63092013-01-09 09:55:54 -08001769JDWP::JdwpError Dbg::SetStaticFieldValue(JDWP::FieldId field_id, uint64_t value, int width) {
1770 return SetFieldValueImpl(0, field_id, value, width, true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001771}
1772
Elliott Hughes88d63092013-01-09 09:55:54 -08001773std::string Dbg::StringToUtf8(JDWP::ObjectId string_id) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001774 mirror::String* s = gRegistry->Get<mirror::String*>(string_id);
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001775 return s->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001776}
1777
Jeff Hao579b0242013-11-18 13:16:49 -08001778void Dbg::OutputJValue(JDWP::JdwpTag tag, const JValue* return_value, JDWP::ExpandBuf* pReply) {
1779 if (IsPrimitiveTag(tag)) {
1780 expandBufAdd1(pReply, tag);
1781 if (tag == JDWP::JT_BOOLEAN || tag == JDWP::JT_BYTE) {
1782 expandBufAdd1(pReply, return_value->GetI());
1783 } else if (tag == JDWP::JT_CHAR || tag == JDWP::JT_SHORT) {
1784 expandBufAdd2BE(pReply, return_value->GetI());
1785 } else if (tag == JDWP::JT_FLOAT || tag == JDWP::JT_INT) {
1786 expandBufAdd4BE(pReply, return_value->GetI());
1787 } else if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
1788 expandBufAdd8BE(pReply, return_value->GetJ());
1789 } else {
1790 CHECK_EQ(tag, JDWP::JT_VOID);
1791 }
1792 } else {
Ian Rogers98379392014-02-24 16:53:16 -08001793 ScopedObjectAccessUnchecked soa(Thread::Current());
Jeff Hao579b0242013-11-18 13:16:49 -08001794 mirror::Object* value = return_value->GetL();
Ian Rogers98379392014-02-24 16:53:16 -08001795 expandBufAdd1(pReply, TagFromObject(soa, value));
Jeff Hao579b0242013-11-18 13:16:49 -08001796 expandBufAddObjectId(pReply, gRegistry->Add(value));
1797 }
1798}
1799
Elliott Hughes221229c2013-01-08 18:17:50 -08001800JDWP::JdwpError Dbg::GetThreadName(JDWP::ObjectId thread_id, std::string& name) {
jeffhaoa77f0f62012-12-05 17:19:31 -08001801 ScopedObjectAccessUnchecked soa(Thread::Current());
1802 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001803 Thread* thread;
1804 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1805 if (error != JDWP::ERR_NONE && error != JDWP::ERR_THREAD_NOT_ALIVE) {
1806 return error;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001807 }
Elliott Hughes221229c2013-01-08 18:17:50 -08001808
1809 // We still need to report the zombie threads' names, so we can't just call Thread::GetThreadName.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001810 mirror::Object* thread_object = gRegistry->Get<mirror::Object*>(thread_id);
Brian Carlstromea46f952013-07-30 01:26:50 -07001811 mirror::ArtField* java_lang_Thread_name_field =
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001812 soa.DecodeField(WellKnownClasses::java_lang_Thread_name);
1813 mirror::String* s =
1814 reinterpret_cast<mirror::String*>(java_lang_Thread_name_field->GetObject(thread_object));
Elliott Hughes221229c2013-01-08 18:17:50 -08001815 if (s != NULL) {
1816 name = s->ToModifiedUtf8();
1817 }
1818 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001819}
1820
Elliott Hughes221229c2013-01-08 18:17:50 -08001821JDWP::JdwpError Dbg::GetThreadGroup(JDWP::ObjectId thread_id, JDWP::ExpandBuf* pReply) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001822 ScopedObjectAccess soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001823 mirror::Object* thread_object = gRegistry->Get<mirror::Object*>(thread_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001824 if (thread_object == ObjectRegistry::kInvalidObject) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001825 return JDWP::ERR_INVALID_OBJECT;
1826 }
Ian Rogers98379392014-02-24 16:53:16 -08001827 const char* old_cause = soa.Self()->StartAssertNoThreadSuspension("Debugger: GetThreadGroup");
Elliott Hughes2435a572012-02-17 16:07:41 -08001828 // Okay, so it's an object, but is it actually a thread?
Ian Rogers50b35e22012-10-04 10:09:15 -07001829 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001830 Thread* thread;
1831 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1832 if (error == JDWP::ERR_THREAD_NOT_ALIVE) {
1833 // Zombie threads are in the null group.
1834 expandBufAddObjectId(pReply, JDWP::ObjectId(0));
Sebastien Hertz52d131d2014-03-13 16:17:40 +01001835 error = JDWP::ERR_NONE;
1836 } else if (error == JDWP::ERR_NONE) {
1837 mirror::Class* c = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_Thread);
1838 CHECK(c != nullptr);
1839 mirror::ArtField* f = c->FindInstanceField("group", "Ljava/lang/ThreadGroup;");
1840 CHECK(f != NULL);
1841 mirror::Object* group = f->GetObject(thread_object);
1842 CHECK(group != NULL);
1843 JDWP::ObjectId thread_group_id = gRegistry->Add(group);
1844 expandBufAddObjectId(pReply, thread_group_id);
Elliott Hughes221229c2013-01-08 18:17:50 -08001845 }
Ian Rogers98379392014-02-24 16:53:16 -08001846 soa.Self()->EndAssertNoThreadSuspension(old_cause);
Sebastien Hertz52d131d2014-03-13 16:17:40 +01001847 return error;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001848}
1849
Elliott Hughes88d63092013-01-09 09:55:54 -08001850std::string Dbg::GetThreadGroupName(JDWP::ObjectId thread_group_id) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001851 ScopedObjectAccess soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001852 mirror::Object* thread_group = gRegistry->Get<mirror::Object*>(thread_group_id);
Ian Rogers98379392014-02-24 16:53:16 -08001853 CHECK(thread_group != nullptr);
1854 const char* old_cause = soa.Self()->StartAssertNoThreadSuspension("Debugger: GetThreadGroupName");
1855 mirror::Class* c = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_ThreadGroup);
1856 CHECK(c != nullptr);
Brian Carlstromea46f952013-07-30 01:26:50 -07001857 mirror::ArtField* f = c->FindInstanceField("name", "Ljava/lang/String;");
Elliott Hughes499c5132011-11-17 14:55:11 -08001858 CHECK(f != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001859 mirror::String* s = reinterpret_cast<mirror::String*>(f->GetObject(thread_group));
Ian Rogers98379392014-02-24 16:53:16 -08001860 soa.Self()->EndAssertNoThreadSuspension(old_cause);
Elliott Hughes499c5132011-11-17 14:55:11 -08001861 return s->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001862}
1863
Elliott Hughes88d63092013-01-09 09:55:54 -08001864JDWP::ObjectId Dbg::GetThreadGroupParent(JDWP::ObjectId thread_group_id) {
Ian Rogers98379392014-02-24 16:53:16 -08001865 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001866 mirror::Object* thread_group = gRegistry->Get<mirror::Object*>(thread_group_id);
Ian Rogers98379392014-02-24 16:53:16 -08001867 CHECK(thread_group != nullptr);
1868 const char* old_cause = soa.Self()->StartAssertNoThreadSuspension("Debugger: GetThreadGroupParent");
1869 mirror::Class* c = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_ThreadGroup);
1870 CHECK(c != nullptr);
Brian Carlstromea46f952013-07-30 01:26:50 -07001871 mirror::ArtField* f = c->FindInstanceField("parent", "Ljava/lang/ThreadGroup;");
Elliott Hughes4e235312011-12-02 11:34:15 -08001872 CHECK(f != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001873 mirror::Object* parent = f->GetObject(thread_group);
Ian Rogers98379392014-02-24 16:53:16 -08001874 soa.Self()->EndAssertNoThreadSuspension(old_cause);
Elliott Hughes4e235312011-12-02 11:34:15 -08001875 return gRegistry->Add(parent);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001876}
1877
1878JDWP::ObjectId Dbg::GetSystemThreadGroupId() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001879 ScopedObjectAccessUnchecked soa(Thread::Current());
Brian Carlstromea46f952013-07-30 01:26:50 -07001880 mirror::ArtField* f = soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_systemThreadGroup);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001881 mirror::Object* group = f->GetObject(f->GetDeclaringClass());
Ian Rogers365c1022012-06-22 15:05:28 -07001882 return gRegistry->Add(group);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001883}
1884
1885JDWP::ObjectId Dbg::GetMainThreadGroupId() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001886 ScopedObjectAccess soa(Thread::Current());
Brian Carlstromea46f952013-07-30 01:26:50 -07001887 mirror::ArtField* f = soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_mainThreadGroup);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001888 mirror::Object* group = f->GetObject(f->GetDeclaringClass());
Ian Rogers365c1022012-06-22 15:05:28 -07001889 return gRegistry->Add(group);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001890}
1891
Jeff Hao920af3e2013-08-28 15:46:38 -07001892JDWP::JdwpThreadStatus Dbg::ToJdwpThreadStatus(ThreadState state) {
1893 switch (state) {
1894 case kBlocked:
1895 return JDWP::TS_MONITOR;
1896 case kNative:
1897 case kRunnable:
1898 case kSuspended:
1899 return JDWP::TS_RUNNING;
1900 case kSleeping:
1901 return JDWP::TS_SLEEPING;
1902 case kStarting:
1903 case kTerminated:
1904 return JDWP::TS_ZOMBIE;
1905 case kTimedWaiting:
1906 case kWaitingForDebuggerSend:
1907 case kWaitingForDebuggerSuspension:
1908 case kWaitingForDebuggerToAttach:
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01001909 case kWaitingForDeoptimization:
Jeff Hao920af3e2013-08-28 15:46:38 -07001910 case kWaitingForGcToComplete:
1911 case kWaitingForCheckPointsToRun:
1912 case kWaitingForJniOnLoad:
1913 case kWaitingForSignalCatcherOutput:
1914 case kWaitingInMainDebuggerLoop:
1915 case kWaitingInMainSignalCatcherLoop:
1916 case kWaitingPerformingGc:
1917 case kWaiting:
1918 return JDWP::TS_WAIT;
1919 // Don't add a 'default' here so the compiler can spot incompatible enum changes.
1920 }
1921 LOG(FATAL) << "Unknown thread state: " << state;
1922 return JDWP::TS_ZOMBIE;
1923}
1924
Sebastien Hertz52d131d2014-03-13 16:17:40 +01001925JDWP::JdwpError Dbg::GetThreadStatus(JDWP::ObjectId thread_id, JDWP::JdwpThreadStatus* pThreadStatus,
1926 JDWP::JdwpSuspendStatus* pSuspendStatus) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001927 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes499c5132011-11-17 14:55:11 -08001928
Elliott Hughes9e0c1752013-01-09 14:02:58 -08001929 *pSuspendStatus = JDWP::SUSPEND_STATUS_NOT_SUSPENDED;
1930
Ian Rogers50b35e22012-10-04 10:09:15 -07001931 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001932 Thread* thread;
1933 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1934 if (error != JDWP::ERR_NONE) {
1935 if (error == JDWP::ERR_THREAD_NOT_ALIVE) {
1936 *pThreadStatus = JDWP::TS_ZOMBIE;
Elliott Hughes221229c2013-01-08 18:17:50 -08001937 return JDWP::ERR_NONE;
1938 }
1939 return error;
Elliott Hughes499c5132011-11-17 14:55:11 -08001940 }
1941
Elliott Hughes9e0c1752013-01-09 14:02:58 -08001942 if (IsSuspendedForDebugger(soa, thread)) {
1943 *pSuspendStatus = JDWP::SUSPEND_STATUS_SUSPENDED;
Elliott Hughes499c5132011-11-17 14:55:11 -08001944 }
1945
Jeff Hao920af3e2013-08-28 15:46:38 -07001946 *pThreadStatus = ToJdwpThreadStatus(thread->GetState());
Elliott Hughes221229c2013-01-08 18:17:50 -08001947 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001948}
1949
Elliott Hughes221229c2013-01-08 18:17:50 -08001950JDWP::JdwpError Dbg::GetThreadDebugSuspendCount(JDWP::ObjectId thread_id, JDWP::ExpandBuf* pReply) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001951 ScopedObjectAccess soa(Thread::Current());
Ian Rogers50b35e22012-10-04 10:09:15 -07001952 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001953 Thread* thread;
1954 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1955 if (error != JDWP::ERR_NONE) {
1956 return error;
Elliott Hughes2435a572012-02-17 16:07:41 -08001957 }
Ian Rogers50b35e22012-10-04 10:09:15 -07001958 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001959 expandBufAdd4BE(pReply, thread->GetDebugSuspendCount());
Elliott Hughes2435a572012-02-17 16:07:41 -08001960 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001961}
1962
Elliott Hughesf9501702013-01-11 11:22:27 -08001963JDWP::JdwpError Dbg::Interrupt(JDWP::ObjectId thread_id) {
1964 ScopedObjectAccess soa(Thread::Current());
1965 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
1966 Thread* thread;
1967 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1968 if (error != JDWP::ERR_NONE) {
1969 return error;
1970 }
Ian Rogersdd7624d2014-03-14 17:43:00 -07001971 thread->Interrupt(soa.Self());
Elliott Hughesf9501702013-01-11 11:22:27 -08001972 return JDWP::ERR_NONE;
1973}
1974
Elliott Hughescaf76542012-06-28 16:08:22 -07001975void Dbg::GetThreads(JDWP::ObjectId thread_group_id, std::vector<JDWP::ObjectId>& thread_ids) {
Ian Rogers365c1022012-06-22 15:05:28 -07001976 class ThreadListVisitor {
1977 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001978 ThreadListVisitor(const ScopedObjectAccessUnchecked& soa, mirror::Object* desired_thread_group,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001979 std::vector<JDWP::ObjectId>& thread_ids)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001980 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
jeffhao0dfbb7e2012-11-28 15:26:03 -08001981 : soa_(soa), desired_thread_group_(desired_thread_group), thread_ids_(thread_ids) {}
Ian Rogers365c1022012-06-22 15:05:28 -07001982
Elliott Hughesa2155262011-11-16 16:26:58 -08001983 static void Visit(Thread* t, void* arg) {
1984 reinterpret_cast<ThreadListVisitor*>(arg)->Visit(t);
1985 }
1986
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001987 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1988 // annotalysis.
1989 void Visit(Thread* t) NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughesa2155262011-11-16 16:26:58 -08001990 if (t == Dbg::GetDebugThread()) {
1991 // Skip the JDWP thread. Some debuggers get bent out of shape when they can't suspend and
1992 // query all threads, so it's easier if we just don't tell them about this thread.
1993 return;
1994 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001995 mirror::Object* peer = t->GetPeer();
jeffhao0dfbb7e2012-11-28 15:26:03 -08001996 if (IsInDesiredThreadGroup(peer)) {
Ian Rogers120f1c72012-09-28 17:17:10 -07001997 thread_ids_.push_back(gRegistry->Add(peer));
Elliott Hughesa2155262011-11-16 16:26:58 -08001998 }
1999 }
2000
Ian Rogers365c1022012-06-22 15:05:28 -07002001 private:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002002 bool IsInDesiredThreadGroup(mirror::Object* peer)
jeffhao0dfbb7e2012-11-28 15:26:03 -08002003 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
jeffhao0dfbb7e2012-11-28 15:26:03 -08002004 // peer might be NULL if the thread is still starting up.
2005 if (peer == NULL) {
2006 // We can't tell the debugger about this thread yet.
2007 // TODO: if we identified threads to the debugger by their Thread*
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002008 // rather than their peer's mirror::Object*, we could fix this.
jeffhao0dfbb7e2012-11-28 15:26:03 -08002009 // Doing so might help us report ZOMBIE threads too.
2010 return false;
2011 }
jeffhaoc1e04902012-12-13 12:41:10 -08002012 // Do we want threads from all thread groups?
2013 if (desired_thread_group_ == NULL) {
2014 return true;
2015 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002016 mirror::Object* group = soa_.DecodeField(WellKnownClasses::java_lang_Thread_group)->GetObject(peer);
jeffhao0dfbb7e2012-11-28 15:26:03 -08002017 return (group == desired_thread_group_);
2018 }
2019
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07002020 const ScopedObjectAccessUnchecked& soa_;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002021 mirror::Object* const desired_thread_group_;
Elliott Hughescaf76542012-06-28 16:08:22 -07002022 std::vector<JDWP::ObjectId>& thread_ids_;
Elliott Hughesa2155262011-11-16 16:26:58 -08002023 };
2024
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002025 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002026 mirror::Object* thread_group = gRegistry->Get<mirror::Object*>(thread_group_id);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002027 ThreadListVisitor tlv(soa, thread_group, thread_ids);
Ian Rogers50b35e22012-10-04 10:09:15 -07002028 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughesf8349362012-06-18 15:00:06 -07002029 Runtime::Current()->GetThreadList()->ForEach(ThreadListVisitor::Visit, &tlv);
Elliott Hughescaf76542012-06-28 16:08:22 -07002030}
Elliott Hughesa2155262011-11-16 16:26:58 -08002031
Elliott Hughescaf76542012-06-28 16:08:22 -07002032void Dbg::GetChildThreadGroups(JDWP::ObjectId thread_group_id, std::vector<JDWP::ObjectId>& child_thread_group_ids) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002033 ScopedObjectAccess soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002034 mirror::Object* thread_group = gRegistry->Get<mirror::Object*>(thread_group_id);
Elliott Hughescaf76542012-06-28 16:08:22 -07002035
2036 // Get the ArrayList<ThreadGroup> "groups" out of this thread group...
Brian Carlstromea46f952013-07-30 01:26:50 -07002037 mirror::ArtField* groups_field = thread_group->GetClass()->FindInstanceField("groups", "Ljava/util/List;");
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002038 mirror::Object* groups_array_list = groups_field->GetObject(thread_group);
Elliott Hughescaf76542012-06-28 16:08:22 -07002039
2040 // Get the array and size out of the ArrayList<ThreadGroup>...
Brian Carlstromea46f952013-07-30 01:26:50 -07002041 mirror::ArtField* array_field = groups_array_list->GetClass()->FindInstanceField("array", "[Ljava/lang/Object;");
2042 mirror::ArtField* size_field = groups_array_list->GetClass()->FindInstanceField("size", "I");
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002043 mirror::ObjectArray<mirror::Object>* groups_array =
2044 array_field->GetObject(groups_array_list)->AsObjectArray<mirror::Object>();
Elliott Hughescaf76542012-06-28 16:08:22 -07002045 const int32_t size = size_field->GetInt(groups_array_list);
2046
2047 // Copy the first 'size' elements out of the array into the result.
2048 for (int32_t i = 0; i < size; ++i) {
2049 child_thread_group_ids.push_back(gRegistry->Add(groups_array->Get(i)));
Elliott Hughesa2155262011-11-16 16:26:58 -08002050 }
2051}
2052
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002053static int GetStackDepth(Thread* thread)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002054 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002055 struct CountStackDepthVisitor : public StackVisitor {
Brian Carlstrom93ba8932013-07-17 21:31:49 -07002056 explicit CountStackDepthVisitor(Thread* thread)
Ian Rogers7a22fa62013-01-23 12:16:16 -08002057 : StackVisitor(thread, NULL), depth(0) {}
Ian Rogers0399dde2012-06-06 17:09:28 -07002058
Elliott Hughes64f574f2013-02-20 14:57:12 -08002059 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2060 // annotalysis.
2061 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07002062 if (!GetMethod()->IsRuntimeMethod()) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -08002063 ++depth;
2064 }
Elliott Hughes530fa002012-03-12 11:44:49 -07002065 return true;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08002066 }
2067 size_t depth;
2068 };
Elliott Hughes08fc03a2012-06-26 17:34:00 -07002069
Ian Rogers7a22fa62013-01-23 12:16:16 -08002070 CountStackDepthVisitor visitor(thread);
Ian Rogers0399dde2012-06-06 17:09:28 -07002071 visitor.WalkStack();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08002072 return visitor.depth;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002073}
2074
Elliott Hughes221229c2013-01-08 18:17:50 -08002075JDWP::JdwpError Dbg::GetThreadFrameCount(JDWP::ObjectId thread_id, size_t& result) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002076 ScopedObjectAccess soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08002077 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002078 Thread* thread;
2079 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
2080 if (error != JDWP::ERR_NONE) {
2081 return error;
2082 }
Elliott Hughesf15f4a02013-01-09 10:09:38 -08002083 if (!IsSuspendedForDebugger(soa, thread)) {
2084 return JDWP::ERR_THREAD_NOT_SUSPENDED;
2085 }
Elliott Hughes221229c2013-01-08 18:17:50 -08002086 result = GetStackDepth(thread);
2087 return JDWP::ERR_NONE;
Elliott Hughes86964332012-02-15 19:37:42 -08002088}
2089
Ian Rogers306057f2012-11-26 12:45:53 -08002090JDWP::JdwpError Dbg::GetThreadFrames(JDWP::ObjectId thread_id, size_t start_frame,
2091 size_t frame_count, JDWP::ExpandBuf* buf) {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002092 class GetFrameVisitor : public StackVisitor {
2093 public:
Ian Rogers7a22fa62013-01-23 12:16:16 -08002094 GetFrameVisitor(Thread* thread, size_t start_frame, size_t frame_count, JDWP::ExpandBuf* buf)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002095 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08002096 : StackVisitor(thread, NULL), depth_(0),
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002097 start_frame_(start_frame), frame_count_(frame_count), buf_(buf) {
2098 expandBufAdd4BE(buf_, frame_count_);
Elliott Hughes03181a82011-11-17 17:22:21 -08002099 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002100
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002101 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2102 // annotalysis.
2103 virtual bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07002104 if (GetMethod()->IsRuntimeMethod()) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07002105 return true; // The debugger can't do anything useful with a frame that has no Method*.
Elliott Hughes03181a82011-11-17 17:22:21 -08002106 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002107 if (depth_ >= start_frame_ + frame_count_) {
Elliott Hughes530fa002012-03-12 11:44:49 -07002108 return false;
Elliott Hughes03181a82011-11-17 17:22:21 -08002109 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002110 if (depth_ >= start_frame_) {
2111 JDWP::FrameId frame_id(GetFrameId());
2112 JDWP::JdwpLocation location;
2113 SetLocation(location, GetMethod(), GetDexPc());
Ian Rogersef7d42f2014-01-06 12:55:46 -08002114 VLOG(jdwp) << StringPrintf(" Frame %3zd: id=%3" PRIu64 " ", depth_, frame_id) << location;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002115 expandBufAdd8BE(buf_, frame_id);
2116 expandBufAddLocation(buf_, location);
2117 }
2118 ++depth_;
Elliott Hughes530fa002012-03-12 11:44:49 -07002119 return true;
Elliott Hughes03181a82011-11-17 17:22:21 -08002120 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002121
2122 private:
2123 size_t depth_;
2124 const size_t start_frame_;
2125 const size_t frame_count_;
2126 JDWP::ExpandBuf* buf_;
Elliott Hughes03181a82011-11-17 17:22:21 -08002127 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002128
2129 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08002130 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002131 Thread* thread;
2132 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
2133 if (error != JDWP::ERR_NONE) {
2134 return error;
2135 }
Elliott Hughesf15f4a02013-01-09 10:09:38 -08002136 if (!IsSuspendedForDebugger(soa, thread)) {
2137 return JDWP::ERR_THREAD_NOT_SUSPENDED;
2138 }
Ian Rogers7a22fa62013-01-23 12:16:16 -08002139 GetFrameVisitor visitor(thread, start_frame, frame_count, buf);
Ian Rogers0399dde2012-06-06 17:09:28 -07002140 visitor.WalkStack();
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002141 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002142}
2143
2144JDWP::ObjectId Dbg::GetThreadSelfId() {
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07002145 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogerscfaa4552012-11-26 21:00:08 -08002146 return gRegistry->Add(soa.Self()->GetPeer());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002147}
2148
Elliott Hughes475fc232011-10-25 15:00:35 -07002149void Dbg::SuspendVM() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002150 Runtime::Current()->GetThreadList()->SuspendAllForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002151}
2152
2153void Dbg::ResumeVM() {
Elliott Hughesc61a2672012-06-21 14:52:29 -07002154 Runtime::Current()->GetThreadList()->UndoDebuggerSuspensions();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002155}
2156
Elliott Hughes221229c2013-01-08 18:17:50 -08002157JDWP::JdwpError Dbg::SuspendThread(JDWP::ObjectId thread_id, bool request_suspension) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002158 ScopedLocalRef<jobject> peer(Thread::Current()->GetJniEnv(), NULL);
2159 {
2160 ScopedObjectAccess soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002161 peer.reset(soa.AddLocalReference<jobject>(gRegistry->Get<mirror::Object*>(thread_id)));
Elliott Hughes4e235312011-12-02 11:34:15 -08002162 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002163 if (peer.get() == NULL) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002164 return JDWP::ERR_THREAD_NOT_ALIVE;
2165 }
2166 // Suspend thread to build stack trace.
Elliott Hughesf327e072013-01-09 16:01:26 -08002167 bool timed_out;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07002168 Thread* thread = ThreadList::SuspendThreadByPeer(peer.get(), request_suspension, true,
2169 &timed_out);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002170 if (thread != NULL) {
2171 return JDWP::ERR_NONE;
Elliott Hughesf327e072013-01-09 16:01:26 -08002172 } else if (timed_out) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002173 return JDWP::ERR_INTERNAL;
2174 } else {
2175 return JDWP::ERR_THREAD_NOT_ALIVE;
2176 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002177}
2178
Elliott Hughes221229c2013-01-08 18:17:50 -08002179void Dbg::ResumeThread(JDWP::ObjectId thread_id) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002180 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002181 mirror::Object* peer = gRegistry->Get<mirror::Object*>(thread_id);
jeffhaoa77f0f62012-12-05 17:19:31 -08002182 Thread* thread;
2183 {
2184 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
2185 thread = Thread::FromManagedThread(soa, peer);
2186 }
Elliott Hughes4e235312011-12-02 11:34:15 -08002187 if (thread == NULL) {
2188 LOG(WARNING) << "No such thread for resume: " << peer;
2189 return;
2190 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002191 bool needs_resume;
2192 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002193 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002194 needs_resume = thread->GetSuspendCount() > 0;
2195 }
2196 if (needs_resume) {
Elliott Hughes546b9862012-06-20 16:06:13 -07002197 Runtime::Current()->GetThreadList()->Resume(thread, true);
2198 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002199}
2200
2201void Dbg::SuspendSelf() {
Elliott Hughes475fc232011-10-25 15:00:35 -07002202 Runtime::Current()->GetThreadList()->SuspendSelfForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002203}
2204
Ian Rogers0399dde2012-06-06 17:09:28 -07002205struct GetThisVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -08002206 GetThisVisitor(Thread* thread, Context* context, JDWP::FrameId frame_id)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002207 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08002208 : StackVisitor(thread, context), this_object(NULL), frame_id(frame_id) {}
Ian Rogers0399dde2012-06-06 17:09:28 -07002209
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002210 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2211 // annotalysis.
2212 virtual bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002213 if (frame_id != GetFrameId()) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002214 return true; // continue
Ian Rogers0399dde2012-06-06 17:09:28 -07002215 } else {
Ian Rogers62d6c772013-02-27 08:32:07 -08002216 this_object = GetThisObject();
2217 return false;
Ian Rogers0399dde2012-06-06 17:09:28 -07002218 }
Elliott Hughes86b00102011-12-05 17:54:26 -08002219 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002220
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002221 mirror::Object* this_object;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002222 JDWP::FrameId frame_id;
Ian Rogers0399dde2012-06-06 17:09:28 -07002223};
2224
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002225JDWP::JdwpError Dbg::GetThisObject(JDWP::ObjectId thread_id, JDWP::FrameId frame_id,
2226 JDWP::ObjectId* result) {
2227 ScopedObjectAccessUnchecked soa(Thread::Current());
2228 Thread* thread;
2229 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002230 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002231 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
2232 if (error != JDWP::ERR_NONE) {
2233 return error;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002234 }
Elliott Hughes9e0c1752013-01-09 14:02:58 -08002235 if (!IsSuspendedForDebugger(soa, thread)) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002236 return JDWP::ERR_THREAD_NOT_SUSPENDED;
2237 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002238 }
Elliott Hughescaf76542012-06-28 16:08:22 -07002239 UniquePtr<Context> context(Context::Create());
Ian Rogers7a22fa62013-01-23 12:16:16 -08002240 GetThisVisitor visitor(thread, context.get(), frame_id);
Ian Rogers0399dde2012-06-06 17:09:28 -07002241 visitor.WalkStack();
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002242 *result = gRegistry->Add(visitor.this_object);
2243 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002244}
2245
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002246JDWP::JdwpError Dbg::GetLocalValue(JDWP::ObjectId thread_id, JDWP::FrameId frame_id, int slot,
2247 JDWP::JdwpTag tag, uint8_t* buf, size_t width) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002248 struct GetLocalVisitor : public StackVisitor {
Ian Rogers98379392014-02-24 16:53:16 -08002249 GetLocalVisitor(const ScopedObjectAccessUnchecked& soa, Thread* thread, Context* context,
2250 JDWP::FrameId frame_id, int slot, JDWP::JdwpTag tag, uint8_t* buf, size_t width)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002251 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers98379392014-02-24 16:53:16 -08002252 : StackVisitor(thread, context), soa_(soa), frame_id_(frame_id), slot_(slot), tag_(tag),
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002253 buf_(buf), width_(width), error_(JDWP::ERR_NONE) {}
Ian Rogersca190662012-06-26 15:45:57 -07002254
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002255 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2256 // annotalysis.
2257 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07002258 if (GetFrameId() != frame_id_) {
2259 return true; // Not our frame, carry on.
Elliott Hughesdbb40792011-11-18 17:05:22 -08002260 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002261 // TODO: check that the tag is compatible with the actual type of the slot!
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002262 // TODO: check slot is valid for this method or return INVALID_SLOT error.
Brian Carlstromea46f952013-07-30 01:26:50 -07002263 mirror::ArtMethod* m = GetMethod();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002264 if (m->IsNative()) {
2265 // We can't read local value from native method.
2266 error_ = JDWP::ERR_OPAQUE_FRAME;
2267 return false;
2268 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002269 uint16_t reg = DemangleSlot(slot_, m);
Elliott Hughesdbb40792011-11-18 17:05:22 -08002270
Ian Rogers0399dde2012-06-06 17:09:28 -07002271 switch (tag_) {
2272 case JDWP::JT_BOOLEAN:
2273 {
2274 CHECK_EQ(width_, 1U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002275 uint32_t intVal = GetVReg(m, reg, kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002276 VLOG(jdwp) << "get boolean local " << reg << " = " << intVal;
2277 JDWP::Set1(buf_+1, intVal != 0);
2278 }
2279 break;
2280 case JDWP::JT_BYTE:
2281 {
2282 CHECK_EQ(width_, 1U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002283 uint32_t intVal = GetVReg(m, reg, kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002284 VLOG(jdwp) << "get byte local " << reg << " = " << intVal;
2285 JDWP::Set1(buf_+1, intVal);
2286 }
2287 break;
2288 case JDWP::JT_SHORT:
2289 case JDWP::JT_CHAR:
2290 {
2291 CHECK_EQ(width_, 2U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002292 uint32_t intVal = GetVReg(m, reg, kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002293 VLOG(jdwp) << "get short/char local " << reg << " = " << intVal;
2294 JDWP::Set2BE(buf_+1, intVal);
2295 }
2296 break;
2297 case JDWP::JT_INT:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002298 {
2299 CHECK_EQ(width_, 4U);
2300 uint32_t intVal = GetVReg(m, reg, kIntVReg);
2301 VLOG(jdwp) << "get int local " << reg << " = " << intVal;
2302 JDWP::Set4BE(buf_+1, intVal);
2303 }
2304 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002305 case JDWP::JT_FLOAT:
2306 {
2307 CHECK_EQ(width_, 4U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002308 uint32_t intVal = GetVReg(m, reg, kFloatVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002309 VLOG(jdwp) << "get int/float local " << reg << " = " << intVal;
2310 JDWP::Set4BE(buf_+1, intVal);
2311 }
2312 break;
2313 case JDWP::JT_ARRAY:
2314 {
2315 CHECK_EQ(width_, sizeof(JDWP::ObjectId));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002316 mirror::Object* o = reinterpret_cast<mirror::Object*>(GetVReg(m, reg, kReferenceVReg));
Ian Rogers0399dde2012-06-06 17:09:28 -07002317 VLOG(jdwp) << "get array local " << reg << " = " << o;
Mathieu Chartier590fee92013-09-13 13:46:47 -07002318 if (!Runtime::Current()->GetHeap()->IsValidObjectAddress(o)) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002319 LOG(FATAL) << "Register " << reg << " expected to hold array: " << o;
2320 }
2321 JDWP::SetObjectId(buf_+1, gRegistry->Add(o));
2322 }
2323 break;
2324 case JDWP::JT_CLASS_LOADER:
2325 case JDWP::JT_CLASS_OBJECT:
2326 case JDWP::JT_OBJECT:
2327 case JDWP::JT_STRING:
2328 case JDWP::JT_THREAD:
2329 case JDWP::JT_THREAD_GROUP:
2330 {
2331 CHECK_EQ(width_, sizeof(JDWP::ObjectId));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002332 mirror::Object* o = reinterpret_cast<mirror::Object*>(GetVReg(m, reg, kReferenceVReg));
Ian Rogers0399dde2012-06-06 17:09:28 -07002333 VLOG(jdwp) << "get object local " << reg << " = " << o;
Mathieu Chartier590fee92013-09-13 13:46:47 -07002334 if (!Runtime::Current()->GetHeap()->IsValidObjectAddress(o)) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002335 LOG(FATAL) << "Register " << reg << " expected to hold object: " << o;
2336 }
Ian Rogers98379392014-02-24 16:53:16 -08002337 tag_ = TagFromObject(soa_, o);
Ian Rogers0399dde2012-06-06 17:09:28 -07002338 JDWP::SetObjectId(buf_+1, gRegistry->Add(o));
2339 }
2340 break;
2341 case JDWP::JT_DOUBLE:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002342 {
2343 CHECK_EQ(width_, 8U);
2344 uint32_t lo = GetVReg(m, reg, kDoubleLoVReg);
2345 uint64_t hi = GetVReg(m, reg + 1, kDoubleHiVReg);
2346 uint64_t longVal = (hi << 32) | lo;
2347 VLOG(jdwp) << "get double/long local " << hi << ":" << lo << " = " << longVal;
2348 JDWP::Set8BE(buf_+1, longVal);
2349 }
2350 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002351 case JDWP::JT_LONG:
2352 {
2353 CHECK_EQ(width_, 8U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002354 uint32_t lo = GetVReg(m, reg, kLongLoVReg);
2355 uint64_t hi = GetVReg(m, reg + 1, kLongHiVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002356 uint64_t longVal = (hi << 32) | lo;
2357 VLOG(jdwp) << "get double/long local " << hi << ":" << lo << " = " << longVal;
2358 JDWP::Set8BE(buf_+1, longVal);
2359 }
2360 break;
2361 default:
2362 LOG(FATAL) << "Unknown tag " << tag_;
2363 break;
2364 }
2365
2366 // Prepend tag, which may have been updated.
2367 JDWP::Set1(buf_, tag_);
2368 return false;
2369 }
Ian Rogers98379392014-02-24 16:53:16 -08002370 const ScopedObjectAccessUnchecked& soa_;
Ian Rogers0399dde2012-06-06 17:09:28 -07002371 const JDWP::FrameId frame_id_;
2372 const int slot_;
2373 JDWP::JdwpTag tag_;
2374 uint8_t* const buf_;
2375 const size_t width_;
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002376 JDWP::JdwpError error_;
Ian Rogers0399dde2012-06-06 17:09:28 -07002377 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002378
2379 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08002380 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002381 Thread* thread;
2382 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
2383 if (error != JDWP::ERR_NONE) {
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002384 return error;
Elliott Hughes221229c2013-01-08 18:17:50 -08002385 }
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002386 // TODO check thread is suspended by the debugger ?
Ian Rogers0399dde2012-06-06 17:09:28 -07002387 UniquePtr<Context> context(Context::Create());
Ian Rogers98379392014-02-24 16:53:16 -08002388 GetLocalVisitor visitor(soa, thread, context.get(), frame_id, slot, tag, buf, width);
Ian Rogers0399dde2012-06-06 17:09:28 -07002389 visitor.WalkStack();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002390 return visitor.error_;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002391}
2392
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002393JDWP::JdwpError Dbg::SetLocalValue(JDWP::ObjectId thread_id, JDWP::FrameId frame_id, int slot,
2394 JDWP::JdwpTag tag, uint64_t value, size_t width) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002395 struct SetLocalVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -08002396 SetLocalVisitor(Thread* thread, Context* context,
Ian Rogers0399dde2012-06-06 17:09:28 -07002397 JDWP::FrameId frame_id, int slot, JDWP::JdwpTag tag, uint64_t value,
Ian Rogersca190662012-06-26 15:45:57 -07002398 size_t width)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002399 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08002400 : StackVisitor(thread, context),
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002401 frame_id_(frame_id), slot_(slot), tag_(tag), value_(value), width_(width),
2402 error_(JDWP::ERR_NONE) {}
Ian Rogersca190662012-06-26 15:45:57 -07002403
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002404 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2405 // annotalysis.
2406 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07002407 if (GetFrameId() != frame_id_) {
2408 return true; // Not our frame, carry on.
2409 }
2410 // TODO: check that the tag is compatible with the actual type of the slot!
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002411 // TODO: check slot is valid for this method or return INVALID_SLOT error.
Brian Carlstromea46f952013-07-30 01:26:50 -07002412 mirror::ArtMethod* m = GetMethod();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002413 if (m->IsNative()) {
2414 // We can't read local value from native method.
2415 error_ = JDWP::ERR_OPAQUE_FRAME;
2416 return false;
2417 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002418 uint16_t reg = DemangleSlot(slot_, m);
2419
2420 switch (tag_) {
2421 case JDWP::JT_BOOLEAN:
2422 case JDWP::JT_BYTE:
2423 CHECK_EQ(width_, 1U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002424 SetVReg(m, reg, static_cast<uint32_t>(value_), kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002425 break;
2426 case JDWP::JT_SHORT:
2427 case JDWP::JT_CHAR:
2428 CHECK_EQ(width_, 2U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002429 SetVReg(m, reg, static_cast<uint32_t>(value_), kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002430 break;
2431 case JDWP::JT_INT:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002432 CHECK_EQ(width_, 4U);
2433 SetVReg(m, reg, static_cast<uint32_t>(value_), kIntVReg);
2434 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002435 case JDWP::JT_FLOAT:
2436 CHECK_EQ(width_, 4U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002437 SetVReg(m, reg, static_cast<uint32_t>(value_), kFloatVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002438 break;
2439 case JDWP::JT_ARRAY:
2440 case JDWP::JT_OBJECT:
2441 case JDWP::JT_STRING:
2442 {
2443 CHECK_EQ(width_, sizeof(JDWP::ObjectId));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002444 mirror::Object* o = gRegistry->Get<mirror::Object*>(static_cast<JDWP::ObjectId>(value_));
Elliott Hughes64f574f2013-02-20 14:57:12 -08002445 if (o == ObjectRegistry::kInvalidObject) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002446 UNIMPLEMENTED(FATAL) << "return an error code when given an invalid object to store";
2447 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002448 SetVReg(m, reg, static_cast<uint32_t>(reinterpret_cast<uintptr_t>(o)), kReferenceVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002449 }
2450 break;
2451 case JDWP::JT_DOUBLE:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002452 CHECK_EQ(width_, 8U);
2453 SetVReg(m, reg, static_cast<uint32_t>(value_), kDoubleLoVReg);
2454 SetVReg(m, reg + 1, static_cast<uint32_t>(value_ >> 32), kDoubleHiVReg);
2455 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002456 case JDWP::JT_LONG:
2457 CHECK_EQ(width_, 8U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002458 SetVReg(m, reg, static_cast<uint32_t>(value_), kLongLoVReg);
2459 SetVReg(m, reg + 1, static_cast<uint32_t>(value_ >> 32), kLongHiVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002460 break;
2461 default:
2462 LOG(FATAL) << "Unknown tag " << tag_;
2463 break;
2464 }
2465 return false;
2466 }
2467
2468 const JDWP::FrameId frame_id_;
2469 const int slot_;
2470 const JDWP::JdwpTag tag_;
2471 const uint64_t value_;
2472 const size_t width_;
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002473 JDWP::JdwpError error_;
Ian Rogers0399dde2012-06-06 17:09:28 -07002474 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002475
2476 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08002477 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002478 Thread* thread;
2479 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
2480 if (error != JDWP::ERR_NONE) {
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002481 return error;
Elliott Hughes221229c2013-01-08 18:17:50 -08002482 }
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002483 // TODO check thread is suspended by the debugger ?
Elliott Hughes08fc03a2012-06-26 17:34:00 -07002484 UniquePtr<Context> context(Context::Create());
Ian Rogers7a22fa62013-01-23 12:16:16 -08002485 SetLocalVisitor visitor(thread, context.get(), frame_id, slot, tag, value, width);
Ian Rogers0399dde2012-06-06 17:09:28 -07002486 visitor.WalkStack();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002487 return visitor.error_;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002488}
2489
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002490JDWP::ObjectId Dbg::GetThisObjectIdForEvent(mirror::Object* this_object) {
2491 // If 'this_object' isn't already in the registry, we know that we're not looking for it, so
2492 // there's no point adding it to the registry and burning through ids.
2493 // When registering an event request with an instance filter, we've been given an existing object
2494 // id so it must already be present in the registry when the event fires.
2495 JDWP::ObjectId this_id = 0;
2496 if (this_object != nullptr && gRegistry->Contains(this_object)) {
2497 this_id = gRegistry->Add(this_object);
2498 }
2499 return this_id;
2500}
2501
Ian Rogersef7d42f2014-01-06 12:55:46 -08002502void Dbg::PostLocationEvent(mirror::ArtMethod* m, int dex_pc, mirror::Object* this_object,
Jeff Hao579b0242013-11-18 13:16:49 -08002503 int event_flags, const JValue* return_value) {
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002504 if (!IsDebuggerActive()) {
2505 return;
2506 }
2507 DCHECK(m != nullptr);
2508 DCHECK_EQ(m->IsStatic(), this_object == nullptr);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002509 JDWP::JdwpLocation location;
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002510 SetLocation(location, m, dex_pc);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002511
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002512 // We need 'this' for InstanceOnly filters only.
2513 JDWP::ObjectId this_id = GetThisObjectIdForEvent(this_object);
Jeff Hao579b0242013-11-18 13:16:49 -08002514 gJdwpState->PostLocationEvent(&location, this_id, event_flags, return_value);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002515}
2516
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002517void Dbg::PostFieldAccessEvent(mirror::ArtMethod* m, int dex_pc,
2518 mirror::Object* this_object, mirror::ArtField* f) {
2519 if (!IsDebuggerActive()) {
2520 return;
2521 }
2522 DCHECK(m != nullptr);
2523 DCHECK(f != nullptr);
2524 JDWP::JdwpLocation location;
2525 SetLocation(location, m, dex_pc);
2526
2527 JDWP::RefTypeId type_id = gRegistry->AddRefType(f->GetDeclaringClass());
2528 JDWP::FieldId field_id = ToFieldId(f);
2529 JDWP::ObjectId this_id = gRegistry->Add(this_object);
2530
2531 gJdwpState->PostFieldEvent(&location, type_id, field_id, this_id, nullptr, false);
2532}
2533
2534void Dbg::PostFieldModificationEvent(mirror::ArtMethod* m, int dex_pc,
2535 mirror::Object* this_object, mirror::ArtField* f,
2536 const JValue* field_value) {
2537 if (!IsDebuggerActive()) {
2538 return;
2539 }
2540 DCHECK(m != nullptr);
2541 DCHECK(f != nullptr);
2542 DCHECK(field_value != nullptr);
2543 JDWP::JdwpLocation location;
2544 SetLocation(location, m, dex_pc);
2545
2546 JDWP::RefTypeId type_id = gRegistry->AddRefType(f->GetDeclaringClass());
2547 JDWP::FieldId field_id = ToFieldId(f);
2548 JDWP::ObjectId this_id = gRegistry->Add(this_object);
2549
2550 gJdwpState->PostFieldEvent(&location, type_id, field_id, this_id, field_value, true);
2551}
2552
2553void Dbg::PostException(const ThrowLocation& throw_location,
Brian Carlstromea46f952013-07-30 01:26:50 -07002554 mirror::ArtMethod* catch_method,
Elliott Hughes64f574f2013-02-20 14:57:12 -08002555 uint32_t catch_dex_pc, mirror::Throwable* exception_object) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002556 if (!IsDebuggerActive()) {
Ian Rogers0ad5bb82011-12-07 10:16:32 -08002557 return;
2558 }
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002559
Ian Rogers62d6c772013-02-27 08:32:07 -08002560 JDWP::JdwpLocation jdwp_throw_location;
2561 SetLocation(jdwp_throw_location, throw_location.GetMethod(), throw_location.GetDexPc());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002562 JDWP::JdwpLocation catch_location;
Elliott Hughescaf76542012-06-28 16:08:22 -07002563 SetLocation(catch_location, catch_method, catch_dex_pc);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002564
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002565 // We need 'this' for InstanceOnly filters only.
2566 JDWP::ObjectId this_id = GetThisObjectIdForEvent(throw_location.GetThis());
Elliott Hughes64f574f2013-02-20 14:57:12 -08002567 JDWP::ObjectId exception_id = gRegistry->Add(exception_object);
2568 JDWP::RefTypeId exception_class_id = gRegistry->AddRefType(exception_object->GetClass());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002569
Ian Rogers62d6c772013-02-27 08:32:07 -08002570 gJdwpState->PostException(&jdwp_throw_location, exception_id, exception_class_id, &catch_location,
2571 this_id);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002572}
2573
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002574void Dbg::PostClassPrepare(mirror::Class* c) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002575 if (!IsDebuggerActive()) {
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002576 return;
2577 }
2578
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08002579 // OLD-TODO - we currently always send both "verified" and "prepared" since
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002580 // debuggers seem to like that. There might be some advantage to honesty,
2581 // since the class may not yet be verified.
2582 int state = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
Sebastien Hertz4d8fd492014-03-28 16:29:41 +01002583 JDWP::JdwpTypeTag tag = GetTypeTag(c);
Ian Rogersfc0e94b2013-09-23 23:51:32 -07002584 gJdwpState->PostClassPrepare(tag, gRegistry->Add(c),
Ian Rogersdfb325e2013-10-30 01:00:44 -07002585 ClassHelper(c).GetDescriptor(), state);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002586}
2587
Ian Rogers62d6c772013-02-27 08:32:07 -08002588void Dbg::UpdateDebugger(Thread* thread, mirror::Object* this_object,
Ian Rogersef7d42f2014-01-06 12:55:46 -08002589 mirror::ArtMethod* m, uint32_t dex_pc) {
Ian Rogers62d6c772013-02-27 08:32:07 -08002590 if (!IsDebuggerActive() || dex_pc == static_cast<uint32_t>(-2) /* fake method exit */) {
Elliott Hughes2aa2e392012-02-17 17:15:43 -08002591 return;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002592 }
2593
Elliott Hughes2aa2e392012-02-17 17:15:43 -08002594 int event_flags = 0;
2595
Elliott Hughes86964332012-02-15 19:37:42 -08002596 if (IsBreakpoint(m, dex_pc)) {
2597 event_flags |= kBreakpoint;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002598 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002599
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002600 // If the debugger is single-stepping one of our threads, check to
2601 // see if we're that thread and we've reached a step point.
2602 const SingleStepControl* single_step_control = thread->GetSingleStepControl();
2603 DCHECK(single_step_control != nullptr);
2604 if (single_step_control->is_active) {
2605 CHECK(!m->IsNative());
2606 if (single_step_control->step_depth == JDWP::SD_INTO) {
2607 // Step into method calls. We break when the line number
2608 // or method pointer changes. If we're in SS_MIN mode, we
2609 // always stop.
2610 if (single_step_control->method != m) {
2611 event_flags |= kSingleStep;
2612 VLOG(jdwp) << "SS new method";
2613 } else if (single_step_control->step_size == JDWP::SS_MIN) {
2614 event_flags |= kSingleStep;
2615 VLOG(jdwp) << "SS new instruction";
Sebastien Hertzbb43b432014-04-14 11:59:08 +02002616 } else if (single_step_control->ContainsDexPc(dex_pc)) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002617 event_flags |= kSingleStep;
2618 VLOG(jdwp) << "SS new line";
2619 }
2620 } else if (single_step_control->step_depth == JDWP::SD_OVER) {
2621 // Step over method calls. We break when the line number is
2622 // different and the frame depth is <= the original frame
2623 // depth. (We can't just compare on the method, because we
2624 // might get unrolled past it by an exception, and it's tricky
2625 // to identify recursion.)
2626
2627 int stack_depth = GetStackDepth(thread);
2628
2629 if (stack_depth < single_step_control->stack_depth) {
2630 // Popped up one or more frames, always trigger.
2631 event_flags |= kSingleStep;
2632 VLOG(jdwp) << "SS method pop";
2633 } else if (stack_depth == single_step_control->stack_depth) {
2634 // Same depth, see if we moved.
2635 if (single_step_control->step_size == JDWP::SS_MIN) {
Elliott Hughes86964332012-02-15 19:37:42 -08002636 event_flags |= kSingleStep;
2637 VLOG(jdwp) << "SS new instruction";
Sebastien Hertzbb43b432014-04-14 11:59:08 +02002638 } else if (single_step_control->ContainsDexPc(dex_pc)) {
Elliott Hughes2435a572012-02-17 16:07:41 -08002639 event_flags |= kSingleStep;
2640 VLOG(jdwp) << "SS new line";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002641 }
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002642 }
2643 } else {
2644 CHECK_EQ(single_step_control->step_depth, JDWP::SD_OUT);
2645 // Return from the current method. We break when the frame
2646 // depth pops up.
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002647
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002648 // This differs from the "method exit" break in that it stops
2649 // with the PC at the next instruction in the returned-to
2650 // function, rather than the end of the returning function.
Elliott Hughes86964332012-02-15 19:37:42 -08002651
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002652 int stack_depth = GetStackDepth(thread);
2653 if (stack_depth < single_step_control->stack_depth) {
2654 event_flags |= kSingleStep;
2655 VLOG(jdwp) << "SS method pop";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002656 }
2657 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002658 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002659
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002660 // If there's something interesting going on, see if it matches one
2661 // of the debugger filters.
2662 if (event_flags != 0) {
Jeff Hao579b0242013-11-18 13:16:49 -08002663 Dbg::PostLocationEvent(m, dex_pc, this_object, event_flags, nullptr);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002664 }
2665}
2666
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002667// Process request while all mutator threads are suspended.
2668void Dbg::ProcessDeoptimizationRequest(const DeoptimizationRequest& request) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002669 instrumentation::Instrumentation* instrumentation = Runtime::Current()->GetInstrumentation();
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002670 switch (request.kind) {
2671 case DeoptimizationRequest::kNothing:
2672 LOG(WARNING) << "Ignoring empty deoptimization request.";
2673 break;
2674 case DeoptimizationRequest::kFullDeoptimization:
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01002675 VLOG(jdwp) << "Deoptimize the world ...";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002676 instrumentation->DeoptimizeEverything();
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01002677 VLOG(jdwp) << "Deoptimize the world DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002678 break;
2679 case DeoptimizationRequest::kFullUndeoptimization:
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01002680 VLOG(jdwp) << "Undeoptimize the world ...";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002681 instrumentation->UndeoptimizeEverything();
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01002682 VLOG(jdwp) << "Undeoptimize the world DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002683 break;
2684 case DeoptimizationRequest::kSelectiveDeoptimization:
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01002685 VLOG(jdwp) << "Deoptimize method " << PrettyMethod(request.method) << " ...";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002686 instrumentation->Deoptimize(request.method);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01002687 VLOG(jdwp) << "Deoptimize method " << PrettyMethod(request.method) << " DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002688 break;
2689 case DeoptimizationRequest::kSelectiveUndeoptimization:
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01002690 VLOG(jdwp) << "Undeoptimize method " << PrettyMethod(request.method) << " ...";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002691 instrumentation->Undeoptimize(request.method);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01002692 VLOG(jdwp) << "Undeoptimize method " << PrettyMethod(request.method) << " DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002693 break;
2694 default:
2695 LOG(FATAL) << "Unsupported deoptimization request kind " << request.kind;
2696 break;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002697 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002698}
2699
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01002700void Dbg::DelayFullUndeoptimization() {
2701 MutexLock mu(Thread::Current(), *deoptimization_lock_);
2702 ++delayed_full_undeoptimization_count_;
2703 DCHECK_LE(delayed_full_undeoptimization_count_, full_deoptimization_event_count_);
2704}
2705
2706void Dbg::ProcessDelayedFullUndeoptimizations() {
2707 // TODO: avoid taking the lock twice (once here and once in ManageDeoptimization).
2708 {
2709 MutexLock mu(Thread::Current(), *deoptimization_lock_);
2710 while (delayed_full_undeoptimization_count_ > 0) {
2711 DeoptimizationRequest req;
2712 req.kind = DeoptimizationRequest::kFullUndeoptimization;
2713 req.method = nullptr;
2714 RequestDeoptimizationLocked(req);
2715 --delayed_full_undeoptimization_count_;
2716 }
2717 }
2718 ManageDeoptimization();
2719}
2720
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002721void Dbg::RequestDeoptimization(const DeoptimizationRequest& req) {
2722 if (req.kind == DeoptimizationRequest::kNothing) {
2723 // Nothing to do.
2724 return;
2725 }
2726 MutexLock mu(Thread::Current(), *deoptimization_lock_);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01002727 RequestDeoptimizationLocked(req);
2728}
2729
2730void Dbg::RequestDeoptimizationLocked(const DeoptimizationRequest& req) {
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002731 switch (req.kind) {
2732 case DeoptimizationRequest::kFullDeoptimization: {
2733 DCHECK(req.method == nullptr);
2734 if (full_deoptimization_event_count_ == 0) {
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01002735 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
2736 << " for full deoptimization";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002737 deoptimization_requests_.push_back(req);
2738 }
2739 ++full_deoptimization_event_count_;
2740 break;
2741 }
2742 case DeoptimizationRequest::kFullUndeoptimization: {
2743 DCHECK(req.method == nullptr);
2744 DCHECK_GT(full_deoptimization_event_count_, 0U);
2745 --full_deoptimization_event_count_;
2746 if (full_deoptimization_event_count_ == 0) {
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01002747 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
2748 << " for full undeoptimization";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002749 deoptimization_requests_.push_back(req);
2750 }
2751 break;
2752 }
2753 case DeoptimizationRequest::kSelectiveDeoptimization: {
2754 DCHECK(req.method != nullptr);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01002755 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
2756 << " for deoptimization of " << PrettyMethod(req.method);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002757 deoptimization_requests_.push_back(req);
2758 break;
2759 }
2760 case DeoptimizationRequest::kSelectiveUndeoptimization: {
2761 DCHECK(req.method != nullptr);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01002762 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
2763 << " for undeoptimization of " << PrettyMethod(req.method);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002764 deoptimization_requests_.push_back(req);
2765 break;
2766 }
2767 default: {
2768 LOG(FATAL) << "Unknown deoptimization request kind " << req.kind;
2769 break;
2770 }
2771 }
2772}
2773
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002774void Dbg::ManageDeoptimization() {
2775 Thread* const self = Thread::Current();
2776 {
2777 // Avoid suspend/resume if there is no pending request.
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002778 MutexLock mu(self, *deoptimization_lock_);
2779 if (deoptimization_requests_.empty()) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002780 return;
2781 }
2782 }
2783 CHECK_EQ(self->GetState(), kRunnable);
2784 self->TransitionFromRunnableToSuspended(kWaitingForDeoptimization);
2785 // We need to suspend mutator threads first.
2786 Runtime* const runtime = Runtime::Current();
2787 runtime->GetThreadList()->SuspendAll();
2788 const ThreadState old_state = self->SetStateUnsafe(kRunnable);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002789 {
2790 MutexLock mu(self, *deoptimization_lock_);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01002791 size_t req_index = 0;
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002792 for (const DeoptimizationRequest& request : deoptimization_requests_) {
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01002793 VLOG(jdwp) << "Process deoptimization request #" << req_index++;
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002794 ProcessDeoptimizationRequest(request);
2795 }
2796 deoptimization_requests_.clear();
2797 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002798 CHECK_EQ(self->SetStateUnsafe(old_state), kRunnable);
2799 runtime->GetThreadList()->ResumeAll();
2800 self->TransitionFromSuspendedToRunnable();
2801}
2802
Sebastien Hertza76a6d42014-03-20 16:40:17 +01002803static bool IsMethodPossiblyInlined(Thread* self, mirror::ArtMethod* m)
2804 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2805 MethodHelper mh(m);
2806 const DexFile::CodeItem* code_item = mh.GetCodeItem();
2807 if (code_item == nullptr) {
2808 // TODO We should not be asked to watch location in a native or abstract method so the code item
2809 // should never be null. We could just check we never encounter this case.
2810 return false;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002811 }
Sebastien Hertza76a6d42014-03-20 16:40:17 +01002812 SirtRef<mirror::DexCache> dex_cache(self, mh.GetDexCache());
2813 SirtRef<mirror::ClassLoader> class_loader(self, mh.GetClassLoader());
2814 verifier::MethodVerifier verifier(&mh.GetDexFile(), &dex_cache, &class_loader,
2815 &mh.GetClassDef(), code_item, m->GetDexMethodIndex(), m,
2816 m->GetAccessFlags(), false, true);
2817 // Note: we don't need to verify the method.
2818 return InlineMethodAnalyser::AnalyseMethodCode(&verifier, nullptr);
2819}
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002820
Sebastien Hertza76a6d42014-03-20 16:40:17 +01002821static const Breakpoint* FindFirstBreakpointForMethod(mirror::ArtMethod* m)
2822 EXCLUSIVE_LOCKS_REQUIRED(Locks::breakpoint_lock_) {
2823 for (const Breakpoint& breakpoint : gBreakpoints) {
2824 if (breakpoint.method == m) {
2825 return &breakpoint;
2826 }
2827 }
2828 return nullptr;
2829}
2830
2831// Sanity checks all existing breakpoints on the same method.
2832static void SanityCheckExistingBreakpoints(mirror::ArtMethod* m, bool need_full_deoptimization)
2833 EXCLUSIVE_LOCKS_REQUIRED(Locks::breakpoint_lock_) {
2834 if (kIsDebugBuild) {
2835 for (const Breakpoint& breakpoint : gBreakpoints) {
2836 CHECK_EQ(need_full_deoptimization, breakpoint.need_full_deoptimization);
2837 }
2838 if (need_full_deoptimization) {
2839 // We should have deoptimized everything but not "selectively" deoptimized this method.
2840 CHECK(Runtime::Current()->GetInstrumentation()->AreAllMethodsDeoptimized());
2841 CHECK(!Runtime::Current()->GetInstrumentation()->IsDeoptimized(m));
2842 } else {
2843 // We should have "selectively" deoptimized this method.
2844 // Note: while we have not deoptimized everything for this method, we may have done it for
2845 // another event.
2846 CHECK(Runtime::Current()->GetInstrumentation()->IsDeoptimized(m));
2847 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002848 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002849}
2850
Sebastien Hertza76a6d42014-03-20 16:40:17 +01002851// Installs a breakpoint at the specified location. Also indicates through the deoptimization
2852// request if we need to deoptimize.
2853void Dbg::WatchLocation(const JDWP::JdwpLocation* location, DeoptimizationRequest* req) {
2854 Thread* const self = Thread::Current();
Brian Carlstromea46f952013-07-30 01:26:50 -07002855 mirror::ArtMethod* m = FromMethodId(location->method_id);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01002856 DCHECK(m != nullptr) << "No method for method id " << location->method_id;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002857
Sebastien Hertza76a6d42014-03-20 16:40:17 +01002858 MutexLock mu(self, *Locks::breakpoint_lock_);
2859 const Breakpoint* const existing_breakpoint = FindFirstBreakpointForMethod(m);
2860 bool need_full_deoptimization;
2861 if (existing_breakpoint == nullptr) {
2862 // There is no breakpoint on this method yet: we need to deoptimize. If this method may be
2863 // inlined, we deoptimize everything; otherwise we deoptimize only this method.
2864 need_full_deoptimization = IsMethodPossiblyInlined(self, m);
2865 if (need_full_deoptimization) {
2866 req->kind = DeoptimizationRequest::kFullDeoptimization;
2867 req->method = nullptr;
2868 } else {
2869 req->kind = DeoptimizationRequest::kSelectiveDeoptimization;
2870 req->method = m;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002871 }
Sebastien Hertza76a6d42014-03-20 16:40:17 +01002872 } else {
2873 // There is at least one breakpoint for this method: we don't need to deoptimize.
2874 req->kind = DeoptimizationRequest::kNothing;
2875 req->method = nullptr;
2876
2877 need_full_deoptimization = existing_breakpoint->need_full_deoptimization;
2878 SanityCheckExistingBreakpoints(m, need_full_deoptimization);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002879 }
2880
Sebastien Hertza76a6d42014-03-20 16:40:17 +01002881 gBreakpoints.push_back(Breakpoint(m, location->dex_pc, need_full_deoptimization));
2882 VLOG(jdwp) << "Set breakpoint #" << (gBreakpoints.size() - 1) << ": "
2883 << gBreakpoints[gBreakpoints.size() - 1];
2884}
2885
2886// Uninstalls a breakpoint at the specified location. Also indicates through the deoptimization
2887// request if we need to undeoptimize.
2888void Dbg::UnwatchLocation(const JDWP::JdwpLocation* location, DeoptimizationRequest* req) {
2889 mirror::ArtMethod* m = FromMethodId(location->method_id);
2890 DCHECK(m != nullptr) << "No method for method id " << location->method_id;
2891
2892 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
2893 bool need_full_deoptimization = false;
2894 for (size_t i = 0, e = gBreakpoints.size(); i < e; ++i) {
2895 if (gBreakpoints[i].method == m && gBreakpoints[i].dex_pc == location->dex_pc) {
2896 VLOG(jdwp) << "Removed breakpoint #" << i << ": " << gBreakpoints[i];
2897 need_full_deoptimization = gBreakpoints[i].need_full_deoptimization;
2898 DCHECK_NE(need_full_deoptimization, Runtime::Current()->GetInstrumentation()->IsDeoptimized(m));
2899 gBreakpoints.erase(gBreakpoints.begin() + i);
2900 break;
2901 }
2902 }
2903 const Breakpoint* const existing_breakpoint = FindFirstBreakpointForMethod(m);
2904 if (existing_breakpoint == nullptr) {
2905 // There is no more breakpoint on this method: we need to undeoptimize.
2906 if (need_full_deoptimization) {
2907 // This method required full deoptimization: we need to undeoptimize everything.
2908 req->kind = DeoptimizationRequest::kFullUndeoptimization;
2909 req->method = nullptr;
2910 } else {
2911 // This method required selective deoptimization: we need to undeoptimize only that method.
2912 req->kind = DeoptimizationRequest::kSelectiveUndeoptimization;
2913 req->method = m;
2914 }
2915 } else {
2916 // There is at least one breakpoint for this method: we don't need to undeoptimize.
2917 req->kind = DeoptimizationRequest::kNothing;
2918 req->method = nullptr;
2919 SanityCheckExistingBreakpoints(m, need_full_deoptimization);
Elliott Hughes86964332012-02-15 19:37:42 -08002920 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002921}
2922
Jeff Hao449db332013-04-12 18:30:52 -07002923// Scoped utility class to suspend a thread so that we may do tasks such as walk its stack. Doesn't
2924// cause suspension if the thread is the current thread.
2925class ScopedThreadSuspension {
2926 public:
Ian Rogers33e95662013-05-20 20:29:14 -07002927 ScopedThreadSuspension(Thread* self, JDWP::ObjectId thread_id)
Sebastien Hertz52d131d2014-03-13 16:17:40 +01002928 LOCKS_EXCLUDED(Locks::thread_list_lock_)
Ian Rogers33e95662013-05-20 20:29:14 -07002929 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) :
Jeff Hao449db332013-04-12 18:30:52 -07002930 thread_(NULL),
2931 error_(JDWP::ERR_NONE),
2932 self_suspend_(false),
Ian Rogers33e95662013-05-20 20:29:14 -07002933 other_suspend_(false) {
Jeff Hao449db332013-04-12 18:30:52 -07002934 ScopedObjectAccessUnchecked soa(self);
2935 {
2936 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
2937 error_ = DecodeThread(soa, thread_id, thread_);
2938 }
2939 if (error_ == JDWP::ERR_NONE) {
2940 if (thread_ == soa.Self()) {
2941 self_suspend_ = true;
2942 } else {
2943 soa.Self()->TransitionFromRunnableToSuspended(kWaitingForDebuggerSuspension);
2944 jobject thread_peer = gRegistry->GetJObject(thread_id);
2945 bool timed_out;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07002946 Thread* suspended_thread = ThreadList::SuspendThreadByPeer(thread_peer, true, true,
2947 &timed_out);
Jeff Hao449db332013-04-12 18:30:52 -07002948 CHECK_EQ(soa.Self()->TransitionFromSuspendedToRunnable(), kWaitingForDebuggerSuspension);
2949 if (suspended_thread == NULL) {
2950 // Thread terminated from under us while suspending.
2951 error_ = JDWP::ERR_INVALID_THREAD;
2952 } else {
2953 CHECK_EQ(suspended_thread, thread_);
2954 other_suspend_ = true;
2955 }
2956 }
2957 }
Elliott Hughes2435a572012-02-17 16:07:41 -08002958 }
Elliott Hughes86964332012-02-15 19:37:42 -08002959
Jeff Hao449db332013-04-12 18:30:52 -07002960 Thread* GetThread() const {
2961 return thread_;
2962 }
2963
2964 JDWP::JdwpError GetError() const {
2965 return error_;
2966 }
2967
2968 ~ScopedThreadSuspension() {
2969 if (other_suspend_) {
2970 Runtime::Current()->GetThreadList()->Resume(thread_, true);
2971 }
2972 }
2973
2974 private:
2975 Thread* thread_;
2976 JDWP::JdwpError error_;
2977 bool self_suspend_;
2978 bool other_suspend_;
2979};
2980
2981JDWP::JdwpError Dbg::ConfigureStep(JDWP::ObjectId thread_id, JDWP::JdwpStepSize step_size,
2982 JDWP::JdwpStepDepth step_depth) {
2983 Thread* self = Thread::Current();
2984 ScopedThreadSuspension sts(self, thread_id);
2985 if (sts.GetError() != JDWP::ERR_NONE) {
2986 return sts.GetError();
2987 }
2988
Elliott Hughes2435a572012-02-17 16:07:41 -08002989 //
2990 // Work out what Method* we're in, the current line number, and how deep the stack currently
2991 // is for step-out.
2992 //
2993
Ian Rogers0399dde2012-06-06 17:09:28 -07002994 struct SingleStepStackVisitor : public StackVisitor {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002995 explicit SingleStepStackVisitor(Thread* thread, SingleStepControl* single_step_control,
2996 int32_t* line_number)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002997 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002998 : StackVisitor(thread, NULL), single_step_control_(single_step_control),
2999 line_number_(line_number) {
3000 DCHECK_EQ(single_step_control_, thread->GetSingleStepControl());
3001 single_step_control_->method = NULL;
3002 single_step_control_->stack_depth = 0;
Elliott Hughes86964332012-02-15 19:37:42 -08003003 }
Ian Rogersca190662012-06-26 15:45:57 -07003004
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003005 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
3006 // annotalysis.
3007 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003008 mirror::ArtMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07003009 if (!m->IsRuntimeMethod()) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003010 ++single_step_control_->stack_depth;
3011 if (single_step_control_->method == NULL) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08003012 mirror::DexCache* dex_cache = m->GetDeclaringClass()->GetDexCache();
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003013 single_step_control_->method = m;
3014 *line_number_ = -1;
Elliott Hughes2435a572012-02-17 16:07:41 -08003015 if (dex_cache != NULL) {
Ian Rogers4445a7e2012-10-05 17:19:13 -07003016 const DexFile& dex_file = *dex_cache->GetDexFile();
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003017 *line_number_ = dex_file.GetLineNumFromPC(m, GetDexPc());
Elliott Hughes2435a572012-02-17 16:07:41 -08003018 }
Elliott Hughes86964332012-02-15 19:37:42 -08003019 }
3020 }
Elliott Hughes530fa002012-03-12 11:44:49 -07003021 return true;
Elliott Hughes86964332012-02-15 19:37:42 -08003022 }
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003023
3024 SingleStepControl* const single_step_control_;
3025 int32_t* const line_number_;
Elliott Hughes86964332012-02-15 19:37:42 -08003026 };
Jeff Hao449db332013-04-12 18:30:52 -07003027
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003028 Thread* const thread = sts.GetThread();
3029 SingleStepControl* const single_step_control = thread->GetSingleStepControl();
3030 DCHECK(single_step_control != nullptr);
3031 int32_t line_number = -1;
3032 SingleStepStackVisitor visitor(thread, single_step_control, &line_number);
Ian Rogers0399dde2012-06-06 17:09:28 -07003033 visitor.WalkStack();
Elliott Hughes86964332012-02-15 19:37:42 -08003034
Elliott Hughes2435a572012-02-17 16:07:41 -08003035 //
3036 // Find the dex_pc values that correspond to the current line, for line-based single-stepping.
3037 //
3038
3039 struct DebugCallbackContext {
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003040 explicit DebugCallbackContext(SingleStepControl* single_step_control, int32_t line_number,
3041 const DexFile::CodeItem* code_item)
3042 : single_step_control_(single_step_control), line_number_(line_number), code_item_(code_item),
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003043 last_pc_valid(false), last_pc(0) {
Elliott Hughes2435a572012-02-17 16:07:41 -08003044 }
3045
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003046 static bool Callback(void* raw_context, uint32_t address, uint32_t line_number) {
Elliott Hughes2435a572012-02-17 16:07:41 -08003047 DebugCallbackContext* context = reinterpret_cast<DebugCallbackContext*>(raw_context);
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003048 if (static_cast<int32_t>(line_number) == context->line_number_) {
Elliott Hughes2435a572012-02-17 16:07:41 -08003049 if (!context->last_pc_valid) {
3050 // Everything from this address until the next line change is ours.
3051 context->last_pc = address;
3052 context->last_pc_valid = true;
3053 }
3054 // Otherwise, if we're already in a valid range for this line,
3055 // just keep going (shouldn't really happen)...
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003056 } else if (context->last_pc_valid) { // and the line number is new
Elliott Hughes2435a572012-02-17 16:07:41 -08003057 // Add everything from the last entry up until here to the set
3058 for (uint32_t dex_pc = context->last_pc; dex_pc < address; ++dex_pc) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003059 context->single_step_control_->dex_pcs.insert(dex_pc);
Elliott Hughes2435a572012-02-17 16:07:41 -08003060 }
3061 context->last_pc_valid = false;
3062 }
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003063 return false; // There may be multiple entries for any given line.
Elliott Hughes2435a572012-02-17 16:07:41 -08003064 }
3065
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003066 ~DebugCallbackContext() {
Elliott Hughes2435a572012-02-17 16:07:41 -08003067 // If the line number was the last in the position table...
3068 if (last_pc_valid) {
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003069 size_t end = code_item_->insns_size_in_code_units_;
Elliott Hughes2435a572012-02-17 16:07:41 -08003070 for (uint32_t dex_pc = last_pc; dex_pc < end; ++dex_pc) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003071 single_step_control_->dex_pcs.insert(dex_pc);
Elliott Hughes2435a572012-02-17 16:07:41 -08003072 }
3073 }
3074 }
3075
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003076 SingleStepControl* const single_step_control_;
3077 const int32_t line_number_;
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003078 const DexFile::CodeItem* const code_item_;
Elliott Hughes2435a572012-02-17 16:07:41 -08003079 bool last_pc_valid;
3080 uint32_t last_pc;
3081 };
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003082 single_step_control->dex_pcs.clear();
Ian Rogersef7d42f2014-01-06 12:55:46 -08003083 mirror::ArtMethod* m = single_step_control->method;
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003084 if (!m->IsNative()) {
Elliott Hughes3e2e1a22012-02-21 11:33:41 -08003085 MethodHelper mh(m);
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003086 const DexFile::CodeItem* const code_item = mh.GetCodeItem();
3087 DebugCallbackContext context(single_step_control, line_number, code_item);
3088 mh.GetDexFile().DecodeDebugInfo(code_item, m->IsStatic(), m->GetDexMethodIndex(),
Elliott Hughes3e2e1a22012-02-21 11:33:41 -08003089 DebugCallbackContext::Callback, NULL, &context);
3090 }
Elliott Hughes2435a572012-02-17 16:07:41 -08003091
3092 //
3093 // Everything else...
3094 //
3095
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003096 single_step_control->step_size = step_size;
3097 single_step_control->step_depth = step_depth;
3098 single_step_control->is_active = true;
Elliott Hughes86964332012-02-15 19:37:42 -08003099
Elliott Hughes2435a572012-02-17 16:07:41 -08003100 if (VLOG_IS_ON(jdwp)) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003101 VLOG(jdwp) << "Single-step thread: " << *thread;
3102 VLOG(jdwp) << "Single-step step size: " << single_step_control->step_size;
3103 VLOG(jdwp) << "Single-step step depth: " << single_step_control->step_depth;
3104 VLOG(jdwp) << "Single-step current method: " << PrettyMethod(single_step_control->method);
3105 VLOG(jdwp) << "Single-step current line: " << line_number;
3106 VLOG(jdwp) << "Single-step current stack depth: " << single_step_control->stack_depth;
Elliott Hughes2435a572012-02-17 16:07:41 -08003107 VLOG(jdwp) << "Single-step dex_pc values:";
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003108 for (uint32_t dex_pc : single_step_control->dex_pcs) {
3109 VLOG(jdwp) << StringPrintf(" %#x", dex_pc);
Elliott Hughes2435a572012-02-17 16:07:41 -08003110 }
3111 }
3112
3113 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003114}
3115
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003116void Dbg::UnconfigureStep(JDWP::ObjectId thread_id) {
3117 ScopedObjectAccessUnchecked soa(Thread::Current());
3118 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
3119 Thread* thread;
3120 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
Sebastien Hertz87118ed2013-11-26 17:57:18 +01003121 if (error == JDWP::ERR_NONE) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003122 SingleStepControl* single_step_control = thread->GetSingleStepControl();
3123 DCHECK(single_step_control != nullptr);
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003124 single_step_control->Clear();
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003125 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003126}
3127
Elliott Hughes45651fd2012-02-21 15:48:20 -08003128static char JdwpTagToShortyChar(JDWP::JdwpTag tag) {
3129 switch (tag) {
3130 default:
3131 LOG(FATAL) << "unknown JDWP tag: " << PrintableChar(tag);
3132
3133 // Primitives.
3134 case JDWP::JT_BYTE: return 'B';
3135 case JDWP::JT_CHAR: return 'C';
3136 case JDWP::JT_FLOAT: return 'F';
3137 case JDWP::JT_DOUBLE: return 'D';
3138 case JDWP::JT_INT: return 'I';
3139 case JDWP::JT_LONG: return 'J';
3140 case JDWP::JT_SHORT: return 'S';
3141 case JDWP::JT_VOID: return 'V';
3142 case JDWP::JT_BOOLEAN: return 'Z';
3143
3144 // Reference types.
3145 case JDWP::JT_ARRAY:
3146 case JDWP::JT_OBJECT:
3147 case JDWP::JT_STRING:
3148 case JDWP::JT_THREAD:
3149 case JDWP::JT_THREAD_GROUP:
3150 case JDWP::JT_CLASS_LOADER:
3151 case JDWP::JT_CLASS_OBJECT:
3152 return 'L';
3153 }
3154}
3155
Elliott Hughes88d63092013-01-09 09:55:54 -08003156JDWP::JdwpError Dbg::InvokeMethod(JDWP::ObjectId thread_id, JDWP::ObjectId object_id,
3157 JDWP::RefTypeId class_id, JDWP::MethodId method_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003158 uint32_t arg_count, uint64_t* arg_values,
3159 JDWP::JdwpTag* arg_types, uint32_t options,
3160 JDWP::JdwpTag* pResultTag, uint64_t* pResultValue,
3161 JDWP::ObjectId* pExceptionId) {
Elliott Hughesd07986f2011-12-06 18:27:45 -08003162 ThreadList* thread_list = Runtime::Current()->GetThreadList();
3163
3164 Thread* targetThread = NULL;
3165 DebugInvokeReq* req = NULL;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003166 Thread* self = Thread::Current();
Elliott Hughesd07986f2011-12-06 18:27:45 -08003167 {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003168 ScopedObjectAccessUnchecked soa(self);
Ian Rogers50b35e22012-10-04 10:09:15 -07003169 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08003170 JDWP::JdwpError error = DecodeThread(soa, thread_id, targetThread);
3171 if (error != JDWP::ERR_NONE) {
3172 LOG(ERROR) << "InvokeMethod request for invalid thread id " << thread_id;
3173 return error;
Elliott Hughesd07986f2011-12-06 18:27:45 -08003174 }
3175 req = targetThread->GetInvokeReq();
3176 if (!req->ready) {
3177 LOG(ERROR) << "InvokeMethod request for thread not stopped by event: " << *targetThread;
3178 return JDWP::ERR_INVALID_THREAD;
3179 }
3180
3181 /*
3182 * We currently have a bug where we don't successfully resume the
3183 * target thread if the suspend count is too deep. We're expected to
3184 * require one "resume" for each "suspend", but when asked to execute
3185 * a method we have to resume fully and then re-suspend it back to the
3186 * same level. (The easiest way to cause this is to type "suspend"
3187 * multiple times in jdb.)
3188 *
3189 * It's unclear what this means when the event specifies "resume all"
3190 * and some threads are suspended more deeply than others. This is
3191 * a rare problem, so for now we just prevent it from hanging forever
3192 * by rejecting the method invocation request. Without this, we will
3193 * be stuck waiting on a suspended thread.
3194 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003195 int suspend_count;
3196 {
Ian Rogers50b35e22012-10-04 10:09:15 -07003197 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003198 suspend_count = targetThread->GetSuspendCount();
3199 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08003200 if (suspend_count > 1) {
3201 LOG(ERROR) << *targetThread << " suspend count too deep for method invocation: " << suspend_count;
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003202 return JDWP::ERR_THREAD_SUSPENDED; // Probably not expected here.
Elliott Hughesd07986f2011-12-06 18:27:45 -08003203 }
3204
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08003205 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003206 mirror::Object* receiver = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08003207 if (receiver == ObjectRegistry::kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08003208 return JDWP::ERR_INVALID_OBJECT;
3209 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003210
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003211 mirror::Object* thread = gRegistry->Get<mirror::Object*>(thread_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08003212 if (thread == ObjectRegistry::kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08003213 return JDWP::ERR_INVALID_OBJECT;
3214 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003215 // TODO: check that 'thread' is actually a java.lang.Thread!
3216
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003217 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes45651fd2012-02-21 15:48:20 -08003218 if (c == NULL) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08003219 return status;
3220 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003221
Brian Carlstromea46f952013-07-30 01:26:50 -07003222 mirror::ArtMethod* m = FromMethodId(method_id);
Elliott Hughes45651fd2012-02-21 15:48:20 -08003223 if (m->IsStatic() != (receiver == NULL)) {
3224 return JDWP::ERR_INVALID_METHODID;
3225 }
3226 if (m->IsStatic()) {
3227 if (m->GetDeclaringClass() != c) {
3228 return JDWP::ERR_INVALID_METHODID;
3229 }
3230 } else {
3231 if (!m->GetDeclaringClass()->IsAssignableFrom(c)) {
3232 return JDWP::ERR_INVALID_METHODID;
3233 }
3234 }
3235
3236 // Check the argument list matches the method.
3237 MethodHelper mh(m);
3238 if (mh.GetShortyLength() - 1 != arg_count) {
3239 return JDWP::ERR_ILLEGAL_ARGUMENT;
3240 }
3241 const char* shorty = mh.GetShorty();
Elliott Hughes09201632013-04-15 15:50:07 -07003242 const DexFile::TypeList* types = mh.GetParameterTypeList();
Elliott Hughes45651fd2012-02-21 15:48:20 -08003243 for (size_t i = 0; i < arg_count; ++i) {
3244 if (shorty[i + 1] != JdwpTagToShortyChar(arg_types[i])) {
3245 return JDWP::ERR_ILLEGAL_ARGUMENT;
3246 }
Elliott Hughes09201632013-04-15 15:50:07 -07003247
3248 if (shorty[i + 1] == 'L') {
3249 // Did we really get an argument of an appropriate reference type?
3250 mirror::Class* parameter_type = mh.GetClassFromTypeIdx(types->GetTypeItem(i).type_idx_);
3251 mirror::Object* argument = gRegistry->Get<mirror::Object*>(arg_values[i]);
3252 if (argument == ObjectRegistry::kInvalidObject) {
3253 return JDWP::ERR_INVALID_OBJECT;
3254 }
Sebastien Hertz0630ab52013-11-28 18:53:35 +01003255 if (argument != NULL && !argument->InstanceOf(parameter_type)) {
Elliott Hughes09201632013-04-15 15:50:07 -07003256 return JDWP::ERR_ILLEGAL_ARGUMENT;
3257 }
3258
3259 // Turn the on-the-wire ObjectId into a jobject.
3260 jvalue& v = reinterpret_cast<jvalue&>(arg_values[i]);
3261 v.l = gRegistry->GetJObject(arg_values[i]);
3262 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003263 }
3264
Sebastien Hertzd38667a2013-11-25 15:43:54 +01003265 req->receiver = receiver;
3266 req->thread = thread;
3267 req->klass = c;
3268 req->method = m;
3269 req->arg_count = arg_count;
3270 req->arg_values = arg_values;
3271 req->options = options;
3272 req->invoke_needed = true;
Elliott Hughesd07986f2011-12-06 18:27:45 -08003273 }
3274
3275 // The fact that we've released the thread list lock is a bit risky --- if the thread goes
3276 // away we're sitting high and dry -- but we must release this before the ResumeAllThreads
3277 // call, and it's unwise to hold it during WaitForSuspend.
3278
3279 {
3280 /*
3281 * We change our (JDWP thread) status, which should be THREAD_RUNNING,
Elliott Hughes81ff3182012-03-23 20:35:56 -07003282 * so we can suspend for a GC if the invoke request causes us to
Elliott Hughesd07986f2011-12-06 18:27:45 -08003283 * run out of memory. It's also a good idea to change it before locking
3284 * the invokeReq mutex, although that should never be held for long.
3285 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003286 self->TransitionFromRunnableToSuspended(kWaitingForDebuggerSend);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003287
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003288 VLOG(jdwp) << " Transferring control to event thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08003289 {
Sebastien Hertzd38667a2013-11-25 15:43:54 +01003290 MutexLock mu(self, req->lock);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003291
3292 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003293 VLOG(jdwp) << " Resuming all threads";
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003294 thread_list->UndoDebuggerSuspensions();
Elliott Hughesd07986f2011-12-06 18:27:45 -08003295 } else {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003296 VLOG(jdwp) << " Resuming event thread only";
Elliott Hughesd07986f2011-12-06 18:27:45 -08003297 thread_list->Resume(targetThread, true);
3298 }
3299
3300 // Wait for the request to finish executing.
Sebastien Hertzd38667a2013-11-25 15:43:54 +01003301 while (req->invoke_needed) {
3302 req->cond.Wait(self);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003303 }
3304 }
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003305 VLOG(jdwp) << " Control has returned from event thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08003306
3307 /* wait for thread to re-suspend itself */
Brian Carlstromdf629502013-07-17 22:39:56 -07003308 SuspendThread(thread_id, false /* request_suspension */);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003309 self->TransitionFromSuspendedToRunnable();
Elliott Hughesd07986f2011-12-06 18:27:45 -08003310 }
3311
3312 /*
3313 * Suspend the threads. We waited for the target thread to suspend
3314 * itself, so all we need to do is suspend the others.
3315 *
3316 * The suspendAllThreads() call will double-suspend the event thread,
3317 * so we want to resume the target thread once to keep the books straight.
3318 */
3319 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003320 self->TransitionFromRunnableToSuspended(kWaitingForDebuggerSuspension);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003321 VLOG(jdwp) << " Suspending all threads";
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003322 thread_list->SuspendAllForDebugger();
3323 self->TransitionFromSuspendedToRunnable();
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003324 VLOG(jdwp) << " Resuming event thread to balance the count";
Elliott Hughesd07986f2011-12-06 18:27:45 -08003325 thread_list->Resume(targetThread, true);
3326 }
3327
3328 // Copy the result.
3329 *pResultTag = req->result_tag;
3330 if (IsPrimitiveTag(req->result_tag)) {
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07003331 *pResultValue = req->result_value.GetJ();
Elliott Hughesd07986f2011-12-06 18:27:45 -08003332 } else {
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07003333 *pResultValue = gRegistry->Add(req->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003334 }
3335 *pExceptionId = req->exception;
3336 return req->error;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003337}
3338
3339void Dbg::ExecuteMethod(DebugInvokeReq* pReq) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003340 ScopedObjectAccess soa(Thread::Current());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003341
Elliott Hughes81ff3182012-03-23 20:35:56 -07003342 // We can be called while an exception is pending. We need
Elliott Hughesd07986f2011-12-06 18:27:45 -08003343 // to preserve that across the method invocation.
Ian Rogers62d6c772013-02-27 08:32:07 -08003344 SirtRef<mirror::Object> old_throw_this_object(soa.Self(), NULL);
Brian Carlstromea46f952013-07-30 01:26:50 -07003345 SirtRef<mirror::ArtMethod> old_throw_method(soa.Self(), NULL);
Ian Rogers62d6c772013-02-27 08:32:07 -08003346 SirtRef<mirror::Throwable> old_exception(soa.Self(), NULL);
3347 uint32_t old_throw_dex_pc;
3348 {
3349 ThrowLocation old_throw_location;
3350 mirror::Throwable* old_exception_obj = soa.Self()->GetException(&old_throw_location);
3351 old_throw_this_object.reset(old_throw_location.GetThis());
3352 old_throw_method.reset(old_throw_location.GetMethod());
3353 old_exception.reset(old_exception_obj);
3354 old_throw_dex_pc = old_throw_location.GetDexPc();
3355 soa.Self()->ClearException();
3356 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08003357
3358 // Translate the method through the vtable, unless the debugger wants to suppress it.
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003359 SirtRef<mirror::ArtMethod> m(soa.Self(), pReq->method);
Sebastien Hertzd38667a2013-11-25 15:43:54 +01003360 if ((pReq->options & JDWP::INVOKE_NONVIRTUAL) == 0 && pReq->receiver != NULL) {
Sebastien Hertz83a47d82014-03-20 09:57:40 +01003361 mirror::ArtMethod* actual_method = pReq->klass->FindVirtualMethodForVirtualOrInterface(m.get());
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003362 if (actual_method != m.get()) {
3363 VLOG(jdwp) << "ExecuteMethod translated " << PrettyMethod(m.get()) << " to " << PrettyMethod(actual_method);
3364 m.reset(actual_method);
Elliott Hughes45651fd2012-02-21 15:48:20 -08003365 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08003366 }
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003367 VLOG(jdwp) << "ExecuteMethod " << PrettyMethod(m.get())
Sebastien Hertzd38667a2013-11-25 15:43:54 +01003368 << " receiver=" << pReq->receiver
3369 << " arg_count=" << pReq->arg_count;
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003370 CHECK(m.get() != nullptr);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003371
3372 CHECK_EQ(sizeof(jvalue), sizeof(uint64_t));
3373
Sebastien Hertz83a47d82014-03-20 09:57:40 +01003374 pReq->result_value = InvokeWithJValues(soa, pReq->receiver, soa.EncodeMethod(m.get()),
Ian Rogers53b8b092014-03-13 23:45:53 -07003375 reinterpret_cast<jvalue*>(pReq->arg_values));
Elliott Hughesd07986f2011-12-06 18:27:45 -08003376
Ian Rogers62d6c772013-02-27 08:32:07 -08003377 mirror::Throwable* exception = soa.Self()->GetException(NULL);
3378 soa.Self()->ClearException();
3379 pReq->exception = gRegistry->Add(exception);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003380 pReq->result_tag = BasicTagFromDescriptor(MethodHelper(m.get()).GetShorty());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003381 if (pReq->exception != 0) {
Ian Rogers62d6c772013-02-27 08:32:07 -08003382 VLOG(jdwp) << " JDWP invocation returning with exception=" << exception
3383 << " " << exception->Dump();
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07003384 pReq->result_value.SetJ(0);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003385 } else if (pReq->result_tag == JDWP::JT_OBJECT) {
3386 /* if no exception thrown, examine object result more closely */
Ian Rogers98379392014-02-24 16:53:16 -08003387 JDWP::JdwpTag new_tag = TagFromObject(soa, pReq->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003388 if (new_tag != pReq->result_tag) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003389 VLOG(jdwp) << " JDWP promoted result from " << pReq->result_tag << " to " << new_tag;
Elliott Hughesd07986f2011-12-06 18:27:45 -08003390 pReq->result_tag = new_tag;
3391 }
3392
3393 /*
3394 * Register the object. We don't actually need an ObjectId yet,
3395 * but we do need to be sure that the GC won't move or discard the
3396 * object when we switch out of RUNNING. The ObjectId conversion
3397 * will add the object to the "do not touch" list.
3398 *
3399 * We can't use the "tracked allocation" mechanism here because
3400 * the object is going to be handed off to a different thread.
3401 */
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07003402 gRegistry->Add(pReq->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003403 }
3404
3405 if (old_exception.get() != NULL) {
Ian Rogers62d6c772013-02-27 08:32:07 -08003406 ThrowLocation gc_safe_throw_location(old_throw_this_object.get(), old_throw_method.get(),
3407 old_throw_dex_pc);
3408 soa.Self()->SetException(gc_safe_throw_location, old_exception.get());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003409 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003410}
3411
Elliott Hughesd07986f2011-12-06 18:27:45 -08003412/*
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003413 * "request" contains a full JDWP packet, possibly with multiple chunks. We
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003414 * need to process each, accumulate the replies, and ship the whole thing
3415 * back.
3416 *
3417 * Returns "true" if we have a reply. The reply buffer is newly allocated,
3418 * and includes the chunk type/length, followed by the data.
3419 *
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08003420 * OLD-TODO: we currently assume that the request and reply include a single
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003421 * chunk. If this becomes inconvenient we will need to adapt.
3422 */
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003423bool Dbg::DdmHandlePacket(JDWP::Request& request, uint8_t** pReplyBuf, int* pReplyLen) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003424 Thread* self = Thread::Current();
3425 JNIEnv* env = self->GetJniEnv();
3426
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003427 uint32_t type = request.ReadUnsigned32("type");
3428 uint32_t length = request.ReadUnsigned32("length");
3429
3430 // Create a byte[] corresponding to 'request'.
3431 size_t request_length = request.size();
3432 ScopedLocalRef<jbyteArray> dataArray(env, env->NewByteArray(request_length));
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003433 if (dataArray.get() == NULL) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003434 LOG(WARNING) << "byte[] allocation failed: " << request_length;
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003435 env->ExceptionClear();
3436 return false;
3437 }
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003438 env->SetByteArrayRegion(dataArray.get(), 0, request_length, reinterpret_cast<const jbyte*>(request.data()));
3439 request.Skip(request_length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003440
3441 // Run through and find all chunks. [Currently just find the first.]
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003442 ScopedByteArrayRO contents(env, dataArray.get());
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003443 if (length != request_length) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08003444 LOG(WARNING) << StringPrintf("bad chunk found (len=%u pktLen=%zd)", length, request_length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003445 return false;
3446 }
3447
3448 // Call "private static Chunk dispatch(int type, byte[] data, int offset, int length)".
Elliott Hugheseac76672012-05-24 21:56:51 -07003449 ScopedLocalRef<jobject> chunk(env, env->CallStaticObjectMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
3450 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_dispatch,
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003451 type, dataArray.get(), 0, length));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003452 if (env->ExceptionCheck()) {
3453 LOG(INFO) << StringPrintf("Exception thrown by dispatcher for 0x%08x", type);
3454 env->ExceptionDescribe();
3455 env->ExceptionClear();
3456 return false;
3457 }
3458
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003459 if (chunk.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003460 return false;
3461 }
3462
3463 /*
3464 * Pull the pieces out of the chunk. We copy the results into a
3465 * newly-allocated buffer that the caller can free. We don't want to
3466 * continue using the Chunk object because nothing has a reference to it.
3467 *
3468 * We could avoid this by returning type/data/offset/length and having
3469 * the caller be aware of the object lifetime issues, but that
Elliott Hughes81ff3182012-03-23 20:35:56 -07003470 * integrates the JDWP code more tightly into the rest of the runtime, and doesn't work
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003471 * if we have responses for multiple chunks.
3472 *
3473 * So we're pretty much stuck with copying data around multiple times.
3474 */
Elliott Hugheseac76672012-05-24 21:56:51 -07003475 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 -08003476 jint offset = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_offset);
Elliott Hugheseac76672012-05-24 21:56:51 -07003477 length = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_length);
Elliott Hugheseac76672012-05-24 21:56:51 -07003478 type = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_type);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003479
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003480 VLOG(jdwp) << StringPrintf("DDM reply: type=0x%08x data=%p offset=%d length=%d", type, replyData.get(), offset, length);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003481 if (length == 0 || replyData.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003482 return false;
3483 }
3484
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003485 const int kChunkHdrLen = 8;
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003486 uint8_t* reply = new uint8_t[length + kChunkHdrLen];
3487 if (reply == NULL) {
3488 LOG(WARNING) << "malloc failed: " << (length + kChunkHdrLen);
3489 return false;
3490 }
Elliott Hughesf7c3b662011-10-27 12:04:56 -07003491 JDWP::Set4BE(reply + 0, type);
3492 JDWP::Set4BE(reply + 4, length);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003493 env->GetByteArrayRegion(replyData.get(), offset, length, reinterpret_cast<jbyte*>(reply + kChunkHdrLen));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003494
3495 *pReplyBuf = reply;
3496 *pReplyLen = length + kChunkHdrLen;
3497
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003498 VLOG(jdwp) << StringPrintf("dvmHandleDdm returning type=%.4s %p len=%d", reinterpret_cast<char*>(reply), reply, length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003499 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003500}
3501
Elliott Hughesa2155262011-11-16 16:26:58 -08003502void Dbg::DdmBroadcast(bool connect) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003503 VLOG(jdwp) << "Broadcasting DDM " << (connect ? "connect" : "disconnect") << "...";
Elliott Hughes47fce012011-10-25 18:37:19 -07003504
3505 Thread* self = Thread::Current();
Ian Rogers50b35e22012-10-04 10:09:15 -07003506 if (self->GetState() != kRunnable) {
3507 LOG(ERROR) << "DDM broadcast in thread state " << self->GetState();
3508 /* try anyway? */
Elliott Hughes47fce012011-10-25 18:37:19 -07003509 }
3510
3511 JNIEnv* env = self->GetJniEnv();
Elliott Hughes47fce012011-10-25 18:37:19 -07003512 jint event = connect ? 1 /*DdmServer.CONNECTED*/ : 2 /*DdmServer.DISCONNECTED*/;
Elliott Hugheseac76672012-05-24 21:56:51 -07003513 env->CallStaticVoidMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
3514 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_broadcast,
3515 event);
Elliott Hughes47fce012011-10-25 18:37:19 -07003516 if (env->ExceptionCheck()) {
3517 LOG(ERROR) << "DdmServer.broadcast " << event << " failed";
3518 env->ExceptionDescribe();
3519 env->ExceptionClear();
3520 }
3521}
3522
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003523void Dbg::DdmConnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08003524 Dbg::DdmBroadcast(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003525}
3526
3527void Dbg::DdmDisconnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08003528 Dbg::DdmBroadcast(false);
Elliott Hughes47fce012011-10-25 18:37:19 -07003529 gDdmThreadNotification = false;
3530}
3531
3532/*
Elliott Hughes82188472011-11-07 18:11:48 -08003533 * Send a notification when a thread starts, stops, or changes its name.
Elliott Hughes47fce012011-10-25 18:37:19 -07003534 *
3535 * Because we broadcast the full set of threads when the notifications are
3536 * first enabled, it's possible for "thread" to be actively executing.
3537 */
Elliott Hughes82188472011-11-07 18:11:48 -08003538void Dbg::DdmSendThreadNotification(Thread* t, uint32_t type) {
Elliott Hughes47fce012011-10-25 18:37:19 -07003539 if (!gDdmThreadNotification) {
3540 return;
3541 }
3542
Elliott Hughes82188472011-11-07 18:11:48 -08003543 if (type == CHUNK_TYPE("THDE")) {
Elliott Hughes47fce012011-10-25 18:37:19 -07003544 uint8_t buf[4];
Ian Rogersd9c4fc92013-10-01 19:45:43 -07003545 JDWP::Set4BE(&buf[0], t->GetThreadId());
Elliott Hughes47fce012011-10-25 18:37:19 -07003546 Dbg::DdmSendChunk(CHUNK_TYPE("THDE"), 4, buf);
Elliott Hughes82188472011-11-07 18:11:48 -08003547 } else {
3548 CHECK(type == CHUNK_TYPE("THCR") || type == CHUNK_TYPE("THNM")) << type;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003549 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003550 SirtRef<mirror::String> name(soa.Self(), t->GetThreadName(soa));
Elliott Hughes82188472011-11-07 18:11:48 -08003551 size_t char_count = (name.get() != NULL) ? name->GetLength() : 0;
jeffhao725a9572012-11-13 18:20:12 -08003552 const jchar* chars = (name.get() != NULL) ? name->GetCharArray()->GetData() : NULL;
Elliott Hughes82188472011-11-07 18:11:48 -08003553
Elliott Hughes21f32d72011-11-09 17:44:13 -08003554 std::vector<uint8_t> bytes;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07003555 JDWP::Append4BE(bytes, t->GetThreadId());
Elliott Hughes545a0642011-11-08 19:10:03 -08003556 JDWP::AppendUtf16BE(bytes, chars, char_count);
Elliott Hughes21f32d72011-11-09 17:44:13 -08003557 CHECK_EQ(bytes.size(), char_count*2 + sizeof(uint32_t)*2);
3558 Dbg::DdmSendChunk(type, bytes);
Elliott Hughes47fce012011-10-25 18:37:19 -07003559 }
3560}
3561
Elliott Hughes47fce012011-10-25 18:37:19 -07003562void Dbg::DdmSetThreadNotification(bool enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003563 // Enable/disable thread notifications.
Elliott Hughes47fce012011-10-25 18:37:19 -07003564 gDdmThreadNotification = enable;
3565 if (enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003566 // Suspend the VM then post thread start notifications for all threads. Threads attaching will
3567 // see a suspension in progress and block until that ends. They then post their own start
3568 // notification.
3569 SuspendVM();
3570 std::list<Thread*> threads;
Ian Rogers50b35e22012-10-04 10:09:15 -07003571 Thread* self = Thread::Current();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003572 {
Ian Rogers50b35e22012-10-04 10:09:15 -07003573 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003574 threads = Runtime::Current()->GetThreadList()->GetList();
3575 }
3576 {
Ian Rogers50b35e22012-10-04 10:09:15 -07003577 ScopedObjectAccess soa(self);
Mathieu Chartier02e25112013-08-14 16:14:24 -07003578 for (Thread* thread : threads) {
3579 Dbg::DdmSendThreadNotification(thread, CHUNK_TYPE("THCR"));
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003580 }
3581 }
3582 ResumeVM();
Elliott Hughes47fce012011-10-25 18:37:19 -07003583 }
3584}
3585
Elliott Hughesa2155262011-11-16 16:26:58 -08003586void Dbg::PostThreadStartOrStop(Thread* t, uint32_t type) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07003587 if (IsDebuggerActive()) {
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07003588 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogerscfaa4552012-11-26 21:00:08 -08003589 JDWP::ObjectId id = gRegistry->Add(t->GetPeer());
Elliott Hughes82188472011-11-07 18:11:48 -08003590 gJdwpState->PostThreadChange(id, type == CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07003591 }
Elliott Hughes82188472011-11-07 18:11:48 -08003592 Dbg::DdmSendThreadNotification(t, type);
Elliott Hughes47fce012011-10-25 18:37:19 -07003593}
3594
3595void Dbg::PostThreadStart(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08003596 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07003597}
3598
3599void Dbg::PostThreadDeath(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08003600 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THDE"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003601}
3602
Elliott Hughes82188472011-11-07 18:11:48 -08003603void Dbg::DdmSendChunk(uint32_t type, size_t byte_count, const uint8_t* buf) {
Elliott Hughes3bb81562011-10-21 18:52:59 -07003604 CHECK(buf != NULL);
3605 iovec vec[1];
3606 vec[0].iov_base = reinterpret_cast<void*>(const_cast<uint8_t*>(buf));
3607 vec[0].iov_len = byte_count;
3608 Dbg::DdmSendChunkV(type, vec, 1);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003609}
3610
Elliott Hughes21f32d72011-11-09 17:44:13 -08003611void Dbg::DdmSendChunk(uint32_t type, const std::vector<uint8_t>& bytes) {
3612 DdmSendChunk(type, bytes.size(), &bytes[0]);
3613}
3614
Brian Carlstromf5293522013-07-19 00:24:00 -07003615void Dbg::DdmSendChunkV(uint32_t type, const iovec* iov, int iov_count) {
Elliott Hughes3bb81562011-10-21 18:52:59 -07003616 if (gJdwpState == NULL) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003617 VLOG(jdwp) << "Debugger thread not active, ignoring DDM send: " << type;
Elliott Hughes3bb81562011-10-21 18:52:59 -07003618 } else {
Elliott Hughescccd84f2011-12-05 16:51:54 -08003619 gJdwpState->DdmSendChunkV(type, iov, iov_count);
Elliott Hughes3bb81562011-10-21 18:52:59 -07003620 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003621}
3622
Elliott Hughes767a1472011-10-26 18:49:02 -07003623int Dbg::DdmHandleHpifChunk(HpifWhen when) {
3624 if (when == HPIF_WHEN_NOW) {
Elliott Hughes7162ad92011-10-27 14:08:42 -07003625 DdmSendHeapInfo(when);
Elliott Hughes767a1472011-10-26 18:49:02 -07003626 return true;
3627 }
3628
3629 if (when != HPIF_WHEN_NEVER && when != HPIF_WHEN_NEXT_GC && when != HPIF_WHEN_EVERY_GC) {
3630 LOG(ERROR) << "invalid HpifWhen value: " << static_cast<int>(when);
3631 return false;
3632 }
3633
3634 gDdmHpifWhen = when;
3635 return true;
3636}
3637
3638bool Dbg::DdmHandleHpsgNhsgChunk(Dbg::HpsgWhen when, Dbg::HpsgWhat what, bool native) {
3639 if (when != HPSG_WHEN_NEVER && when != HPSG_WHEN_EVERY_GC) {
3640 LOG(ERROR) << "invalid HpsgWhen value: " << static_cast<int>(when);
3641 return false;
3642 }
3643
3644 if (what != HPSG_WHAT_MERGED_OBJECTS && what != HPSG_WHAT_DISTINCT_OBJECTS) {
3645 LOG(ERROR) << "invalid HpsgWhat value: " << static_cast<int>(what);
3646 return false;
3647 }
3648
3649 if (native) {
3650 gDdmNhsgWhen = when;
3651 gDdmNhsgWhat = what;
3652 } else {
3653 gDdmHpsgWhen = when;
3654 gDdmHpsgWhat = what;
3655 }
3656 return true;
3657}
3658
Elliott Hughes7162ad92011-10-27 14:08:42 -07003659void Dbg::DdmSendHeapInfo(HpifWhen reason) {
3660 // If there's a one-shot 'when', reset it.
3661 if (reason == gDdmHpifWhen) {
3662 if (gDdmHpifWhen == HPIF_WHEN_NEXT_GC) {
3663 gDdmHpifWhen = HPIF_WHEN_NEVER;
3664 }
3665 }
3666
3667 /*
3668 * Chunk HPIF (client --> server)
3669 *
3670 * Heap Info. General information about the heap,
3671 * suitable for a summary display.
3672 *
3673 * [u4]: number of heaps
3674 *
3675 * For each heap:
3676 * [u4]: heap ID
3677 * [u8]: timestamp in ms since Unix epoch
3678 * [u1]: capture reason (same as 'when' value from server)
3679 * [u4]: max heap size in bytes (-Xmx)
3680 * [u4]: current heap size in bytes
3681 * [u4]: current number of bytes allocated
3682 * [u4]: current number of objects allocated
3683 */
3684 uint8_t heap_count = 1;
Ian Rogers1d54e732013-05-02 21:10:01 -07003685 gc::Heap* heap = Runtime::Current()->GetHeap();
Elliott Hughes21f32d72011-11-09 17:44:13 -08003686 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08003687 JDWP::Append4BE(bytes, heap_count);
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003688 JDWP::Append4BE(bytes, 1); // Heap id (bogus; we only have one heap).
Elliott Hughes545a0642011-11-08 19:10:03 -08003689 JDWP::Append8BE(bytes, MilliTime());
3690 JDWP::Append1BE(bytes, reason);
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003691 JDWP::Append4BE(bytes, heap->GetMaxMemory()); // Max allowed heap size in bytes.
3692 JDWP::Append4BE(bytes, heap->GetTotalMemory()); // Current heap size in bytes.
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08003693 JDWP::Append4BE(bytes, heap->GetBytesAllocated());
3694 JDWP::Append4BE(bytes, heap->GetObjectsAllocated());
Elliott Hughes21f32d72011-11-09 17:44:13 -08003695 CHECK_EQ(bytes.size(), 4U + (heap_count * (4 + 8 + 1 + 4 + 4 + 4 + 4)));
3696 Dbg::DdmSendChunk(CHUNK_TYPE("HPIF"), bytes);
Elliott Hughes767a1472011-10-26 18:49:02 -07003697}
3698
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003699enum HpsgSolidity {
3700 SOLIDITY_FREE = 0,
3701 SOLIDITY_HARD = 1,
3702 SOLIDITY_SOFT = 2,
3703 SOLIDITY_WEAK = 3,
3704 SOLIDITY_PHANTOM = 4,
3705 SOLIDITY_FINALIZABLE = 5,
3706 SOLIDITY_SWEEP = 6,
3707};
3708
3709enum HpsgKind {
3710 KIND_OBJECT = 0,
3711 KIND_CLASS_OBJECT = 1,
3712 KIND_ARRAY_1 = 2,
3713 KIND_ARRAY_2 = 3,
3714 KIND_ARRAY_4 = 4,
3715 KIND_ARRAY_8 = 5,
3716 KIND_UNKNOWN = 6,
3717 KIND_NATIVE = 7,
3718};
3719
3720#define HPSG_PARTIAL (1<<7)
3721#define HPSG_STATE(solidity, kind) ((uint8_t)((((kind) & 0x7) << 3) | ((solidity) & 0x7)))
3722
Ian Rogers30fab402012-01-23 15:43:46 -08003723class HeapChunkContext {
3724 public:
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003725 // Maximum chunk size. Obtain this from the formula:
3726 // (((maximum_heap_size / ALLOCATION_UNIT_SIZE) + 255) / 256) * 2
3727 HeapChunkContext(bool merge, bool native)
Ian Rogers30fab402012-01-23 15:43:46 -08003728 : buf_(16384 - 16),
3729 type_(0),
3730 merge_(merge) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003731 Reset();
3732 if (native) {
Ian Rogers30fab402012-01-23 15:43:46 -08003733 type_ = CHUNK_TYPE("NHSG");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003734 } else {
Ian Rogers30fab402012-01-23 15:43:46 -08003735 type_ = merge ? CHUNK_TYPE("HPSG") : CHUNK_TYPE("HPSO");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003736 }
3737 }
3738
3739 ~HeapChunkContext() {
Ian Rogers30fab402012-01-23 15:43:46 -08003740 if (p_ > &buf_[0]) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003741 Flush();
3742 }
3743 }
3744
3745 void EnsureHeader(const void* chunk_ptr) {
Ian Rogers30fab402012-01-23 15:43:46 -08003746 if (!needHeader_) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003747 return;
3748 }
3749
3750 // Start a new HPSx chunk.
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003751 JDWP::Write4BE(&p_, 1); // Heap id (bogus; we only have one heap).
3752 JDWP::Write1BE(&p_, 8); // Size of allocation unit, in bytes.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003753
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003754 JDWP::Write4BE(&p_, reinterpret_cast<uintptr_t>(chunk_ptr)); // virtual address of segment start.
3755 JDWP::Write4BE(&p_, 0); // offset of this piece (relative to the virtual address).
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003756 // [u4]: length of piece, in allocation units
3757 // 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 -08003758 pieceLenField_ = p_;
3759 JDWP::Write4BE(&p_, 0x55555555);
3760 needHeader_ = false;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003761 }
3762
Ian Rogersb726dcb2012-09-05 08:57:23 -07003763 void Flush() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogersd636b062013-01-18 17:51:18 -08003764 if (pieceLenField_ == NULL) {
3765 // Flush immediately post Reset (maybe back-to-back Flush). Ignore.
3766 CHECK(needHeader_);
3767 return;
3768 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003769 // Patch the "length of piece" field.
Ian Rogers30fab402012-01-23 15:43:46 -08003770 CHECK_LE(&buf_[0], pieceLenField_);
3771 CHECK_LE(pieceLenField_, p_);
3772 JDWP::Set4BE(pieceLenField_, totalAllocationUnits_);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003773
Ian Rogers30fab402012-01-23 15:43:46 -08003774 Dbg::DdmSendChunk(type_, p_ - &buf_[0], &buf_[0]);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003775 Reset();
3776 }
3777
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003778 static void HeapChunkCallback(void* start, void* end, size_t used_bytes, void* arg)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003779 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_,
3780 Locks::mutator_lock_) {
Ian Rogers30fab402012-01-23 15:43:46 -08003781 reinterpret_cast<HeapChunkContext*>(arg)->HeapChunkCallback(start, end, used_bytes);
Elliott Hughesa2155262011-11-16 16:26:58 -08003782 }
3783
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003784 private:
Elliott Hughesa2155262011-11-16 16:26:58 -08003785 enum { ALLOCATION_UNIT_SIZE = 8 };
3786
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003787 void Reset() {
Ian Rogers30fab402012-01-23 15:43:46 -08003788 p_ = &buf_[0];
Ian Rogers15bf2d32012-08-28 17:33:04 -07003789 startOfNextMemoryChunk_ = NULL;
Ian Rogers30fab402012-01-23 15:43:46 -08003790 totalAllocationUnits_ = 0;
3791 needHeader_ = true;
3792 pieceLenField_ = NULL;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003793 }
3794
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003795 void HeapChunkCallback(void* start, void* /*end*/, size_t used_bytes)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003796 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_,
3797 Locks::mutator_lock_) {
Ian Rogers30fab402012-01-23 15:43:46 -08003798 // Note: heap call backs cannot manipulate the heap upon which they are crawling, care is taken
3799 // in the following code not to allocate memory, by ensuring buf_ is of the correct size
Ian Rogers15bf2d32012-08-28 17:33:04 -07003800 if (used_bytes == 0) {
3801 if (start == NULL) {
3802 // Reset for start of new heap.
3803 startOfNextMemoryChunk_ = NULL;
3804 Flush();
3805 }
3806 // Only process in use memory so that free region information
3807 // also includes dlmalloc book keeping.
Elliott Hughesa2155262011-11-16 16:26:58 -08003808 return;
Elliott Hughesa2155262011-11-16 16:26:58 -08003809 }
3810
Ian Rogers15bf2d32012-08-28 17:33:04 -07003811 /* If we're looking at the native heap, we'll just return
3812 * (SOLIDITY_HARD, KIND_NATIVE) for all allocated chunks
3813 */
3814 bool native = type_ == CHUNK_TYPE("NHSG");
3815
3816 if (startOfNextMemoryChunk_ != NULL) {
3817 // Transmit any pending free memory. Native free memory of
3818 // over kMaxFreeLen could be because of the use of mmaps, so
3819 // don't report. If not free memory then start a new segment.
3820 bool flush = true;
3821 if (start > startOfNextMemoryChunk_) {
3822 const size_t kMaxFreeLen = 2 * kPageSize;
3823 void* freeStart = startOfNextMemoryChunk_;
3824 void* freeEnd = start;
Brian Carlstrom2d888622013-07-18 17:02:00 -07003825 size_t freeLen = reinterpret_cast<char*>(freeEnd) - reinterpret_cast<char*>(freeStart);
Ian Rogers15bf2d32012-08-28 17:33:04 -07003826 if (!native || freeLen < kMaxFreeLen) {
3827 AppendChunk(HPSG_STATE(SOLIDITY_FREE, 0), freeStart, freeLen);
3828 flush = false;
3829 }
3830 }
3831 if (flush) {
3832 startOfNextMemoryChunk_ = NULL;
3833 Flush();
3834 }
3835 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08003836 mirror::Object* obj = reinterpret_cast<mirror::Object*>(start);
Elliott Hughesa2155262011-11-16 16:26:58 -08003837
3838 // Determine the type of this chunk.
3839 // OLD-TODO: if context.merge, see if this chunk is different from the last chunk.
3840 // If it's the same, we should combine them.
Ian Rogers15bf2d32012-08-28 17:33:04 -07003841 uint8_t state = ExamineObject(obj, native);
3842 // dlmalloc's chunk header is 2 * sizeof(size_t), but if the previous chunk is in use for an
3843 // allocation then the first sizeof(size_t) may belong to it.
3844 const size_t dlMallocOverhead = sizeof(size_t);
3845 AppendChunk(state, start, used_bytes + dlMallocOverhead);
Brian Carlstrom2d888622013-07-18 17:02:00 -07003846 startOfNextMemoryChunk_ = reinterpret_cast<char*>(start) + used_bytes + dlMallocOverhead;
Ian Rogers15bf2d32012-08-28 17:33:04 -07003847 }
Elliott Hughesa2155262011-11-16 16:26:58 -08003848
Ian Rogers15bf2d32012-08-28 17:33:04 -07003849 void AppendChunk(uint8_t state, void* ptr, size_t length)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003850 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07003851 // Make sure there's enough room left in the buffer.
3852 // We need to use two bytes for every fractional 256 allocation units used by the chunk plus
3853 // 17 bytes for any header.
3854 size_t needed = (((length/ALLOCATION_UNIT_SIZE + 255) / 256) * 2) + 17;
3855 size_t bytesLeft = buf_.size() - (size_t)(p_ - &buf_[0]);
3856 if (bytesLeft < needed) {
3857 Flush();
3858 }
3859
3860 bytesLeft = buf_.size() - (size_t)(p_ - &buf_[0]);
3861 if (bytesLeft < needed) {
3862 LOG(WARNING) << "Chunk is too big to transmit (chunk_len=" << length << ", "
3863 << needed << " bytes)";
3864 return;
3865 }
3866 EnsureHeader(ptr);
Elliott Hughesa2155262011-11-16 16:26:58 -08003867 // Write out the chunk description.
Ian Rogers15bf2d32012-08-28 17:33:04 -07003868 length /= ALLOCATION_UNIT_SIZE; // Convert to allocation units.
3869 totalAllocationUnits_ += length;
3870 while (length > 256) {
Ian Rogers30fab402012-01-23 15:43:46 -08003871 *p_++ = state | HPSG_PARTIAL;
3872 *p_++ = 255; // length - 1
Ian Rogers15bf2d32012-08-28 17:33:04 -07003873 length -= 256;
Elliott Hughesa2155262011-11-16 16:26:58 -08003874 }
Ian Rogers30fab402012-01-23 15:43:46 -08003875 *p_++ = state;
Ian Rogers15bf2d32012-08-28 17:33:04 -07003876 *p_++ = length - 1;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003877 }
3878
Ian Rogersef7d42f2014-01-06 12:55:46 -08003879 uint8_t ExamineObject(mirror::Object* o, bool is_native_heap)
3880 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Elliott Hughesa2155262011-11-16 16:26:58 -08003881 if (o == NULL) {
3882 return HPSG_STATE(SOLIDITY_FREE, 0);
3883 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003884
Elliott Hughesa2155262011-11-16 16:26:58 -08003885 // It's an allocated chunk. Figure out what it is.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003886
Elliott Hughesa2155262011-11-16 16:26:58 -08003887 // If we're looking at the native heap, we'll just return
3888 // (SOLIDITY_HARD, KIND_NATIVE) for all allocated chunks.
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003889 if (is_native_heap) {
Elliott Hughesa2155262011-11-16 16:26:58 -08003890 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
3891 }
3892
Ian Rogers5bfa60f2012-09-02 21:17:56 -07003893 if (!Runtime::Current()->GetHeap()->IsLiveObjectLocked(o)) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07003894 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003895 }
3896
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003897 mirror::Class* c = o->GetClass();
Elliott Hughesa2155262011-11-16 16:26:58 -08003898 if (c == NULL) {
3899 // The object was probably just created but hasn't been initialized yet.
3900 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
3901 }
3902
Mathieu Chartier590fee92013-09-13 13:46:47 -07003903 if (!Runtime::Current()->GetHeap()->IsValidObjectAddress(c)) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07003904 LOG(ERROR) << "Invalid class for managed heap object: " << o << " " << c;
Elliott Hughesa2155262011-11-16 16:26:58 -08003905 return HPSG_STATE(SOLIDITY_HARD, KIND_UNKNOWN);
3906 }
3907
3908 if (c->IsClassClass()) {
3909 return HPSG_STATE(SOLIDITY_HARD, KIND_CLASS_OBJECT);
3910 }
3911
3912 if (c->IsArrayClass()) {
3913 if (o->IsObjectArray()) {
3914 return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
3915 }
3916 switch (c->GetComponentSize()) {
3917 case 1: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_1);
3918 case 2: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_2);
3919 case 4: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
3920 case 8: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_8);
3921 }
3922 }
3923
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003924 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
3925 }
3926
Ian Rogers30fab402012-01-23 15:43:46 -08003927 std::vector<uint8_t> buf_;
3928 uint8_t* p_;
3929 uint8_t* pieceLenField_;
Ian Rogers15bf2d32012-08-28 17:33:04 -07003930 void* startOfNextMemoryChunk_;
Ian Rogers30fab402012-01-23 15:43:46 -08003931 size_t totalAllocationUnits_;
3932 uint32_t type_;
3933 bool merge_;
3934 bool needHeader_;
3935
Elliott Hughesa2155262011-11-16 16:26:58 -08003936 DISALLOW_COPY_AND_ASSIGN(HeapChunkContext);
3937};
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003938
3939void Dbg::DdmSendHeapSegments(bool native) {
3940 Dbg::HpsgWhen when;
3941 Dbg::HpsgWhat what;
3942 if (!native) {
3943 when = gDdmHpsgWhen;
3944 what = gDdmHpsgWhat;
3945 } else {
3946 when = gDdmNhsgWhen;
3947 what = gDdmNhsgWhat;
3948 }
3949 if (when == HPSG_WHEN_NEVER) {
3950 return;
3951 }
3952
3953 // Figure out what kind of chunks we'll be sending.
3954 CHECK(what == HPSG_WHAT_MERGED_OBJECTS || what == HPSG_WHAT_DISTINCT_OBJECTS) << static_cast<int>(what);
3955
3956 // First, send a heap start chunk.
3957 uint8_t heap_id[4];
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003958 JDWP::Set4BE(&heap_id[0], 1); // Heap id (bogus; we only have one heap).
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003959 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHST") : CHUNK_TYPE("HPST"), sizeof(heap_id), heap_id);
3960
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07003961 Thread* self = Thread::Current();
3962
3963 // To allow the Walk/InspectAll() below to exclusively-lock the
3964 // mutator lock, temporarily release the shared access to the
3965 // mutator lock here by transitioning to the suspended state.
3966 Locks::mutator_lock_->AssertSharedHeld(self);
3967 self->TransitionFromRunnableToSuspended(kSuspended);
3968
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003969 // Send a series of heap segment chunks.
Elliott Hughesa2155262011-11-16 16:26:58 -08003970 HeapChunkContext context((what == HPSG_WHAT_MERGED_OBJECTS), native);
3971 if (native) {
Ian Rogers1d54e732013-05-02 21:10:01 -07003972 dlmalloc_inspect_all(HeapChunkContext::HeapChunkCallback, &context);
Elliott Hughesa2155262011-11-16 16:26:58 -08003973 } else {
Ian Rogers1d54e732013-05-02 21:10:01 -07003974 gc::Heap* heap = Runtime::Current()->GetHeap();
3975 const std::vector<gc::space::ContinuousSpace*>& spaces = heap->GetContinuousSpaces();
Ian Rogers1d54e732013-05-02 21:10:01 -07003976 typedef std::vector<gc::space::ContinuousSpace*>::const_iterator It;
3977 for (It cur = spaces.begin(), end = spaces.end(); cur != end; ++cur) {
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07003978 if ((*cur)->IsMallocSpace()) {
3979 (*cur)->AsMallocSpace()->Walk(HeapChunkContext::HeapChunkCallback, &context);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07003980 }
3981 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07003982 // Walk the large objects, these are not in the AllocSpace.
3983 heap->GetLargeObjectsSpace()->Walk(HeapChunkContext::HeapChunkCallback, &context);
Elliott Hughesa2155262011-11-16 16:26:58 -08003984 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003985
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07003986 // Shared-lock the mutator lock back.
3987 self->TransitionFromSuspendedToRunnable();
3988 Locks::mutator_lock_->AssertSharedHeld(self);
3989
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003990 // Finally, send a heap end chunk.
3991 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHEN") : CHUNK_TYPE("HPEN"), sizeof(heap_id), heap_id);
Elliott Hughes767a1472011-10-26 18:49:02 -07003992}
3993
Elliott Hughesb1a58792013-07-11 18:10:58 -07003994static size_t GetAllocTrackerMax() {
3995#ifdef HAVE_ANDROID_OS
3996 // Check whether there's a system property overriding the number of records.
3997 const char* propertyName = "dalvik.vm.allocTrackerMax";
3998 char allocRecordMaxString[PROPERTY_VALUE_MAX];
3999 if (property_get(propertyName, allocRecordMaxString, "") > 0) {
4000 char* end;
4001 size_t value = strtoul(allocRecordMaxString, &end, 10);
4002 if (*end != '\0') {
Ruben Brunk3e47a742013-09-09 17:56:07 -07004003 LOG(ERROR) << "Ignoring " << propertyName << " '" << allocRecordMaxString
4004 << "' --- invalid";
Elliott Hughesb1a58792013-07-11 18:10:58 -07004005 return kDefaultNumAllocRecords;
4006 }
4007 if (!IsPowerOfTwo(value)) {
Ruben Brunk3e47a742013-09-09 17:56:07 -07004008 LOG(ERROR) << "Ignoring " << propertyName << " '" << allocRecordMaxString
4009 << "' --- not power of two";
Elliott Hughesb1a58792013-07-11 18:10:58 -07004010 return kDefaultNumAllocRecords;
4011 }
4012 return value;
4013 }
4014#endif
4015 return kDefaultNumAllocRecords;
4016}
4017
Elliott Hughes545a0642011-11-08 19:10:03 -08004018void Dbg::SetAllocTrackingEnabled(bool enabled) {
Elliott Hughes545a0642011-11-08 19:10:03 -08004019 if (enabled) {
Sebastien Hertzb98063a2014-03-26 10:57:20 +01004020 {
4021 MutexLock mu(Thread::Current(), *alloc_tracker_lock_);
4022 if (recent_allocation_records_ == NULL) {
4023 alloc_record_max_ = GetAllocTrackerMax();
4024 LOG(INFO) << "Enabling alloc tracker (" << alloc_record_max_ << " entries of "
4025 << kMaxAllocRecordStackDepth << " frames, taking "
4026 << PrettySize(sizeof(AllocRecord) * alloc_record_max_) << ")";
4027 alloc_record_head_ = alloc_record_count_ = 0;
4028 recent_allocation_records_ = new AllocRecord[alloc_record_max_];
4029 CHECK(recent_allocation_records_ != NULL);
4030 }
Elliott Hughes545a0642011-11-08 19:10:03 -08004031 }
Ian Rogersfa824272013-11-05 16:12:57 -08004032 Runtime::Current()->GetInstrumentation()->InstrumentQuickAllocEntryPoints();
Elliott Hughes545a0642011-11-08 19:10:03 -08004033 } else {
Ian Rogersfa824272013-11-05 16:12:57 -08004034 Runtime::Current()->GetInstrumentation()->UninstrumentQuickAllocEntryPoints();
Sebastien Hertzb98063a2014-03-26 10:57:20 +01004035 {
4036 MutexLock mu(Thread::Current(), *alloc_tracker_lock_);
4037 delete[] recent_allocation_records_;
4038 recent_allocation_records_ = NULL;
4039 }
Elliott Hughes545a0642011-11-08 19:10:03 -08004040 }
4041}
4042
Ian Rogers0399dde2012-06-06 17:09:28 -07004043struct AllocRecordStackVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -08004044 AllocRecordStackVisitor(Thread* thread, AllocRecord* record)
Ian Rogersb726dcb2012-09-05 08:57:23 -07004045 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08004046 : StackVisitor(thread, NULL), record(record), depth(0) {}
Elliott Hughes545a0642011-11-08 19:10:03 -08004047
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004048 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
4049 // annotalysis.
4050 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughes545a0642011-11-08 19:10:03 -08004051 if (depth >= kMaxAllocRecordStackDepth) {
Elliott Hughes530fa002012-03-12 11:44:49 -07004052 return false;
Elliott Hughes545a0642011-11-08 19:10:03 -08004053 }
Brian Carlstromea46f952013-07-30 01:26:50 -07004054 mirror::ArtMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07004055 if (!m->IsRuntimeMethod()) {
4056 record->stack[depth].method = m;
4057 record->stack[depth].dex_pc = GetDexPc();
Elliott Hughes530fa002012-03-12 11:44:49 -07004058 ++depth;
Elliott Hughes545a0642011-11-08 19:10:03 -08004059 }
Elliott Hughes530fa002012-03-12 11:44:49 -07004060 return true;
Elliott Hughes545a0642011-11-08 19:10:03 -08004061 }
4062
4063 ~AllocRecordStackVisitor() {
4064 // Clear out any unused stack trace elements.
4065 for (; depth < kMaxAllocRecordStackDepth; ++depth) {
4066 record->stack[depth].method = NULL;
Ian Rogers0399dde2012-06-06 17:09:28 -07004067 record->stack[depth].dex_pc = 0;
Elliott Hughes545a0642011-11-08 19:10:03 -08004068 }
4069 }
4070
4071 AllocRecord* record;
4072 size_t depth;
4073};
4074
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004075void Dbg::RecordAllocation(mirror::Class* type, size_t byte_count) {
Elliott Hughes545a0642011-11-08 19:10:03 -08004076 Thread* self = Thread::Current();
4077 CHECK(self != NULL);
4078
Ian Rogers719d1a32014-03-06 12:13:39 -08004079 MutexLock mu(self, *alloc_tracker_lock_);
Elliott Hughes545a0642011-11-08 19:10:03 -08004080 if (recent_allocation_records_ == NULL) {
4081 return;
4082 }
4083
4084 // Advance and clip.
Ian Rogers719d1a32014-03-06 12:13:39 -08004085 if (++alloc_record_head_ == alloc_record_max_) {
4086 alloc_record_head_ = 0;
Elliott Hughes545a0642011-11-08 19:10:03 -08004087 }
4088
4089 // Fill in the basics.
Ian Rogers719d1a32014-03-06 12:13:39 -08004090 AllocRecord* record = &recent_allocation_records_[alloc_record_head_];
Elliott Hughes545a0642011-11-08 19:10:03 -08004091 record->type = type;
4092 record->byte_count = byte_count;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07004093 record->thin_lock_id = self->GetThreadId();
Elliott Hughes545a0642011-11-08 19:10:03 -08004094
4095 // Fill in the stack trace.
Ian Rogers7a22fa62013-01-23 12:16:16 -08004096 AllocRecordStackVisitor visitor(self, record);
Ian Rogers0399dde2012-06-06 17:09:28 -07004097 visitor.WalkStack();
Elliott Hughes545a0642011-11-08 19:10:03 -08004098
Ian Rogers719d1a32014-03-06 12:13:39 -08004099 if (alloc_record_count_ < alloc_record_max_) {
4100 ++alloc_record_count_;
Elliott Hughes545a0642011-11-08 19:10:03 -08004101 }
4102}
4103
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004104// Returns the index of the head element.
4105//
4106// We point at the most-recently-written record, so if gAllocRecordCount is 1
4107// we want to use the current element. Take "head+1" and subtract count
4108// from it.
4109//
4110// We need to handle underflow in our circular buffer, so we add
Elliott Hughesb1a58792013-07-11 18:10:58 -07004111// gAllocRecordMax and then mask it back down.
Ian Rogers719d1a32014-03-06 12:13:39 -08004112size_t Dbg::HeadIndex() {
4113 return (Dbg::alloc_record_head_ + 1 + Dbg::alloc_record_max_ - Dbg::alloc_record_count_) &
4114 (Dbg::alloc_record_max_ - 1);
Elliott Hughes545a0642011-11-08 19:10:03 -08004115}
4116
4117void Dbg::DumpRecentAllocations() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004118 ScopedObjectAccess soa(Thread::Current());
Ian Rogers719d1a32014-03-06 12:13:39 -08004119 MutexLock mu(soa.Self(), *alloc_tracker_lock_);
Elliott Hughes545a0642011-11-08 19:10:03 -08004120 if (recent_allocation_records_ == NULL) {
4121 LOG(INFO) << "Not recording tracked allocations";
4122 return;
4123 }
4124
4125 // "i" is the head of the list. We want to start at the end of the
4126 // list and move forward to the tail.
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004127 size_t i = HeadIndex();
Ian Rogers719d1a32014-03-06 12:13:39 -08004128 size_t count = alloc_record_count_;
Elliott Hughes545a0642011-11-08 19:10:03 -08004129
Ian Rogers719d1a32014-03-06 12:13:39 -08004130 LOG(INFO) << "Tracked allocations, (head=" << alloc_record_head_ << " count=" << count << ")";
Elliott Hughes545a0642011-11-08 19:10:03 -08004131 while (count--) {
4132 AllocRecord* record = &recent_allocation_records_[i];
4133
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004134 LOG(INFO) << StringPrintf(" Thread %-2d %6zd bytes ", record->thin_lock_id, record->byte_count)
Elliott Hughes545a0642011-11-08 19:10:03 -08004135 << PrettyClass(record->type);
4136
4137 for (size_t stack_frame = 0; stack_frame < kMaxAllocRecordStackDepth; ++stack_frame) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08004138 mirror::ArtMethod* m = record->stack[stack_frame].method;
Elliott Hughes545a0642011-11-08 19:10:03 -08004139 if (m == NULL) {
4140 break;
4141 }
4142 LOG(INFO) << " " << PrettyMethod(m) << " line " << record->stack[stack_frame].LineNumber();
4143 }
4144
4145 // pause periodically to help logcat catch up
4146 if ((count % 5) == 0) {
4147 usleep(40000);
4148 }
4149
Ian Rogers719d1a32014-03-06 12:13:39 -08004150 i = (i + 1) & (alloc_record_max_ - 1);
Elliott Hughes545a0642011-11-08 19:10:03 -08004151 }
4152}
4153
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -07004154void Dbg::UpdateObjectPointers(IsMarkedCallback* callback, void* arg) {
Ian Rogers719d1a32014-03-06 12:13:39 -08004155 if (recent_allocation_records_ != nullptr) {
4156 MutexLock mu(Thread::Current(), *alloc_tracker_lock_);
4157 size_t i = HeadIndex();
4158 size_t count = alloc_record_count_;
4159 while (count--) {
4160 AllocRecord* record = &recent_allocation_records_[i];
4161 DCHECK(record != nullptr);
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -07004162 record->UpdateObjectPointers(callback, arg);
Ian Rogers719d1a32014-03-06 12:13:39 -08004163 i = (i + 1) & (alloc_record_max_ - 1);
Mathieu Chartier412c7fc2014-02-07 12:18:39 -08004164 }
4165 }
4166 if (gRegistry != nullptr) {
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -07004167 gRegistry->UpdateObjectPointers(callback, arg);
Mathieu Chartier412c7fc2014-02-07 12:18:39 -08004168 }
4169}
4170
4171void Dbg::AllowNewObjectRegistryObjects() {
4172 if (gRegistry != nullptr) {
4173 gRegistry->AllowNewObjects();
4174 }
4175}
4176
4177void Dbg::DisallowNewObjectRegistryObjects() {
4178 if (gRegistry != nullptr) {
4179 gRegistry->DisallowNewObjects();
4180 }
4181}
4182
Elliott Hughes545a0642011-11-08 19:10:03 -08004183class StringTable {
4184 public:
4185 StringTable() {
4186 }
4187
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004188 void Add(const char* s) {
Elliott Hughes545a0642011-11-08 19:10:03 -08004189 table_.insert(s);
4190 }
4191
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004192 size_t IndexOf(const char* s) const {
Mathieu Chartier02e25112013-08-14 16:14:24 -07004193 auto it = table_.find(s);
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004194 if (it == table_.end()) {
4195 LOG(FATAL) << "IndexOf(\"" << s << "\") failed";
4196 }
4197 return std::distance(table_.begin(), it);
Elliott Hughes545a0642011-11-08 19:10:03 -08004198 }
4199
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004200 size_t Size() const {
Elliott Hughes545a0642011-11-08 19:10:03 -08004201 return table_.size();
4202 }
4203
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004204 void WriteTo(std::vector<uint8_t>& bytes) const {
Mathieu Chartier02e25112013-08-14 16:14:24 -07004205 for (const std::string& str : table_) {
4206 const char* s = str.c_str();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004207 size_t s_len = CountModifiedUtf8Chars(s);
4208 UniquePtr<uint16_t> s_utf16(new uint16_t[s_len]);
4209 ConvertModifiedUtf8ToUtf16(s_utf16.get(), s);
4210 JDWP::AppendUtf16BE(bytes, s_utf16.get(), s_len);
Elliott Hughes545a0642011-11-08 19:10:03 -08004211 }
4212 }
4213
4214 private:
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004215 std::set<std::string> table_;
Elliott Hughes545a0642011-11-08 19:10:03 -08004216 DISALLOW_COPY_AND_ASSIGN(StringTable);
4217};
4218
Sebastien Hertz280286a2014-04-28 09:26:50 +02004219static const char* GetMethodSourceFile(MethodHelper* mh)
4220 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4221 DCHECK(mh != nullptr);
4222 const char* source_file = mh->GetDeclaringClassSourceFile();
4223 return (source_file != nullptr) ? source_file : "";
4224}
4225
Elliott Hughes545a0642011-11-08 19:10:03 -08004226/*
4227 * The data we send to DDMS contains everything we have recorded.
4228 *
4229 * Message header (all values big-endian):
4230 * (1b) message header len (to allow future expansion); includes itself
4231 * (1b) entry header len
4232 * (1b) stack frame len
4233 * (2b) number of entries
4234 * (4b) offset to string table from start of message
4235 * (2b) number of class name strings
4236 * (2b) number of method name strings
4237 * (2b) number of source file name strings
4238 * For each entry:
4239 * (4b) total allocation size
Elliott Hughes221229c2013-01-08 18:17:50 -08004240 * (2b) thread id
Elliott Hughes545a0642011-11-08 19:10:03 -08004241 * (2b) allocated object's class name index
4242 * (1b) stack depth
4243 * For each stack frame:
4244 * (2b) method's class name
4245 * (2b) method name
4246 * (2b) method source file
4247 * (2b) line number, clipped to 32767; -2 if native; -1 if no source
4248 * (xb) class name strings
4249 * (xb) method name strings
4250 * (xb) source file strings
4251 *
4252 * As with other DDM traffic, strings are sent as a 4-byte length
4253 * followed by UTF-16 data.
4254 *
4255 * We send up 16-bit unsigned indexes into string tables. In theory there
Elliott Hughesb1a58792013-07-11 18:10:58 -07004256 * can be (kMaxAllocRecordStackDepth * gAllocRecordMax) unique strings in
Elliott Hughes545a0642011-11-08 19:10:03 -08004257 * each table, but in practice there should be far fewer.
4258 *
4259 * The chief reason for using a string table here is to keep the size of
4260 * the DDMS message to a minimum. This is partly to make the protocol
4261 * efficient, but also because we have to form the whole thing up all at
4262 * once in a memory buffer.
4263 *
4264 * We use separate string tables for class names, method names, and source
4265 * files to keep the indexes small. There will generally be no overlap
4266 * between the contents of these tables.
4267 */
4268jbyteArray Dbg::GetRecentAllocations() {
4269 if (false) {
4270 DumpRecentAllocations();
4271 }
4272
Ian Rogers50b35e22012-10-04 10:09:15 -07004273 Thread* self = Thread::Current();
Elliott Hughes545a0642011-11-08 19:10:03 -08004274 std::vector<uint8_t> bytes;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004275 {
Ian Rogers719d1a32014-03-06 12:13:39 -08004276 MutexLock mu(self, *alloc_tracker_lock_);
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004277 //
4278 // Part 1: generate string tables.
4279 //
4280 StringTable class_names;
4281 StringTable method_names;
4282 StringTable filenames;
Elliott Hughes545a0642011-11-08 19:10:03 -08004283
Ian Rogers719d1a32014-03-06 12:13:39 -08004284 int count = alloc_record_count_;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004285 int idx = HeadIndex();
4286 while (count--) {
4287 AllocRecord* record = &recent_allocation_records_[idx];
Elliott Hughes545a0642011-11-08 19:10:03 -08004288
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004289 class_names.Add(ClassHelper(record->type).GetDescriptor());
Elliott Hughes545a0642011-11-08 19:10:03 -08004290
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004291 MethodHelper mh;
4292 for (size_t i = 0; i < kMaxAllocRecordStackDepth; i++) {
Brian Carlstromea46f952013-07-30 01:26:50 -07004293 mirror::ArtMethod* m = record->stack[i].method;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004294 if (m != NULL) {
4295 mh.ChangeMethod(m);
4296 class_names.Add(mh.GetDeclaringClassDescriptor());
4297 method_names.Add(mh.GetName());
Sebastien Hertz280286a2014-04-28 09:26:50 +02004298 filenames.Add(GetMethodSourceFile(&mh));
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004299 }
4300 }
Elliott Hughes545a0642011-11-08 19:10:03 -08004301
Ian Rogers719d1a32014-03-06 12:13:39 -08004302 idx = (idx + 1) & (alloc_record_max_ - 1);
Elliott Hughes545a0642011-11-08 19:10:03 -08004303 }
4304
Ian Rogers719d1a32014-03-06 12:13:39 -08004305 LOG(INFO) << "allocation records: " << alloc_record_count_;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004306
4307 //
4308 // Part 2: Generate the output and store it in the buffer.
4309 //
4310
4311 // (1b) message header len (to allow future expansion); includes itself
4312 // (1b) entry header len
4313 // (1b) stack frame len
4314 const int kMessageHeaderLen = 15;
4315 const int kEntryHeaderLen = 9;
4316 const int kStackFrameLen = 8;
4317 JDWP::Append1BE(bytes, kMessageHeaderLen);
4318 JDWP::Append1BE(bytes, kEntryHeaderLen);
4319 JDWP::Append1BE(bytes, kStackFrameLen);
4320
4321 // (2b) number of entries
4322 // (4b) offset to string table from start of message
4323 // (2b) number of class name strings
4324 // (2b) number of method name strings
4325 // (2b) number of source file name strings
Ian Rogers719d1a32014-03-06 12:13:39 -08004326 JDWP::Append2BE(bytes, alloc_record_count_);
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004327 size_t string_table_offset = bytes.size();
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004328 JDWP::Append4BE(bytes, 0); // We'll patch this later...
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004329 JDWP::Append2BE(bytes, class_names.Size());
4330 JDWP::Append2BE(bytes, method_names.Size());
4331 JDWP::Append2BE(bytes, filenames.Size());
4332
Ian Rogers719d1a32014-03-06 12:13:39 -08004333 count = alloc_record_count_;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004334 idx = HeadIndex();
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004335 while (count--) {
4336 // For each entry:
4337 // (4b) total allocation size
4338 // (2b) thread id
4339 // (2b) allocated object's class name index
4340 // (1b) stack depth
4341 AllocRecord* record = &recent_allocation_records_[idx];
4342 size_t stack_depth = record->GetDepth();
Mathieu Chartier590fee92013-09-13 13:46:47 -07004343 ClassHelper kh(record->type);
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004344 size_t allocated_object_class_name_index = class_names.IndexOf(kh.GetDescriptor());
4345 JDWP::Append4BE(bytes, record->byte_count);
4346 JDWP::Append2BE(bytes, record->thin_lock_id);
4347 JDWP::Append2BE(bytes, allocated_object_class_name_index);
4348 JDWP::Append1BE(bytes, stack_depth);
4349
4350 MethodHelper mh;
4351 for (size_t stack_frame = 0; stack_frame < stack_depth; ++stack_frame) {
4352 // For each stack frame:
4353 // (2b) method's class name
4354 // (2b) method name
4355 // (2b) method source file
4356 // (2b) line number, clipped to 32767; -2 if native; -1 if no source
4357 mh.ChangeMethod(record->stack[stack_frame].method);
4358 size_t class_name_index = class_names.IndexOf(mh.GetDeclaringClassDescriptor());
4359 size_t method_name_index = method_names.IndexOf(mh.GetName());
Sebastien Hertz280286a2014-04-28 09:26:50 +02004360 size_t file_name_index = filenames.IndexOf(GetMethodSourceFile(&mh));
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004361 JDWP::Append2BE(bytes, class_name_index);
4362 JDWP::Append2BE(bytes, method_name_index);
4363 JDWP::Append2BE(bytes, file_name_index);
4364 JDWP::Append2BE(bytes, record->stack[stack_frame].LineNumber());
4365 }
4366
Ian Rogers719d1a32014-03-06 12:13:39 -08004367 idx = (idx + 1) & (alloc_record_max_ - 1);
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004368 }
4369
4370 // (xb) class name strings
4371 // (xb) method name strings
4372 // (xb) source file strings
4373 JDWP::Set4BE(&bytes[string_table_offset], bytes.size());
4374 class_names.WriteTo(bytes);
4375 method_names.WriteTo(bytes);
4376 filenames.WriteTo(bytes);
Elliott Hughes545a0642011-11-08 19:10:03 -08004377 }
Ian Rogers50b35e22012-10-04 10:09:15 -07004378 JNIEnv* env = self->GetJniEnv();
Elliott Hughes545a0642011-11-08 19:10:03 -08004379 jbyteArray result = env->NewByteArray(bytes.size());
4380 if (result != NULL) {
4381 env->SetByteArrayRegion(result, 0, bytes.size(), reinterpret_cast<const jbyte*>(&bytes[0]));
4382 }
4383 return result;
4384}
4385
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004386} // namespace art