blob: 07d3a2a5b816d2536db1435950c4be54419743eb [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"
39#include "mirror/throwable.h"
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080040#include "object_utils.h"
Sebastien Hertza76a6d42014-03-20 16:40:17 +010041#include "quick/inline_method_analyser.h"
Ian Rogers53b8b092014-03-13 23:45:53 -070042#include "reflection.h"
Elliott Hughesa0e18062012-04-13 15:59:59 -070043#include "safe_map.h"
Elliott Hughes64f574f2013-02-20 14:57:12 -080044#include "scoped_thread_state_change.h"
Elliott Hughes6a5bd492011-10-28 14:33:57 -070045#include "ScopedLocalRef.h"
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -070046#include "ScopedPrimitiveArray.h"
Ian Rogers1f539342012-10-03 21:09:42 -070047#include "sirt_ref.h"
Elliott Hughes47fce012011-10-25 18:37:19 -070048#include "stack_indirect_reference_table.h"
Elliott Hughes475fc232011-10-25 15:00:35 -070049#include "thread_list.h"
Ian Rogers62d6c772013-02-27 08:32:07 -080050#include "throw_location.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080051#include "utf.h"
Sebastien Hertza76a6d42014-03-20 16:40:17 +010052#include "verifier/method_verifier-inl.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070053#include "well_known_classes.h"
Elliott Hughes475fc232011-10-25 15:00:35 -070054
Brian Carlstrom3d92d522013-07-12 09:03:08 -070055#ifdef HAVE_ANDROID_OS
56#include "cutils/properties.h"
57#endif
58
Elliott Hughes872d4ec2011-10-21 17:07:15 -070059namespace art {
60
Brian Carlstrom7934ac22013-07-26 10:54:15 -070061static const size_t kMaxAllocRecordStackDepth = 16; // Max 255.
62static const size_t kDefaultNumAllocRecords = 64*1024; // Must be a power of 2.
Elliott Hughes475fc232011-10-25 15:00:35 -070063
Elliott Hughes545a0642011-11-08 19:10:03 -080064struct AllocRecordStackTraceElement {
Brian Carlstromea46f952013-07-30 01:26:50 -070065 mirror::ArtMethod* method;
Ian Rogers0399dde2012-06-06 17:09:28 -070066 uint32_t dex_pc;
Elliott Hughes545a0642011-11-08 19:10:03 -080067
Mathieu Chartier412c7fc2014-02-07 12:18:39 -080068 AllocRecordStackTraceElement() : method(nullptr), dex_pc(0) {
69 }
70
Ian Rogersb726dcb2012-09-05 08:57:23 -070071 int32_t LineNumber() const SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers0399dde2012-06-06 17:09:28 -070072 return MethodHelper(method).GetLineNumFromDexPC(dex_pc);
Elliott Hughes545a0642011-11-08 19:10:03 -080073 }
74};
75
76struct AllocRecord {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080077 mirror::Class* type;
Elliott Hughes545a0642011-11-08 19:10:03 -080078 size_t byte_count;
79 uint16_t thin_lock_id;
Brian Carlstrom7934ac22013-07-26 10:54:15 -070080 AllocRecordStackTraceElement stack[kMaxAllocRecordStackDepth]; // Unused entries have NULL method.
Elliott Hughes545a0642011-11-08 19:10:03 -080081
82 size_t GetDepth() {
83 size_t depth = 0;
84 while (depth < kMaxAllocRecordStackDepth && stack[depth].method != NULL) {
85 ++depth;
86 }
87 return depth;
88 }
Mathieu Chartier412c7fc2014-02-07 12:18:39 -080089
Mathieu Chartier83c8ee02014-01-28 14:50:23 -080090 void UpdateObjectPointers(IsMarkedCallback* callback, void* arg)
Mathieu Chartier412c7fc2014-02-07 12:18:39 -080091 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
92 if (type != nullptr) {
Mathieu Chartier83c8ee02014-01-28 14:50:23 -080093 type = down_cast<mirror::Class*>(callback(type, arg));
Mathieu Chartier412c7fc2014-02-07 12:18:39 -080094 }
95 for (size_t stack_frame = 0; stack_frame < kMaxAllocRecordStackDepth; ++stack_frame) {
96 mirror::ArtMethod*& m = stack[stack_frame].method;
97 if (m == nullptr) {
98 break;
99 }
Mathieu Chartier83c8ee02014-01-28 14:50:23 -0800100 m = down_cast<mirror::ArtMethod*>(callback(m, arg));
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800101 }
102 }
Elliott Hughes545a0642011-11-08 19:10:03 -0800103};
104
Elliott Hughes86964332012-02-15 19:37:42 -0800105struct Breakpoint {
Sebastien Hertza76a6d42014-03-20 16:40:17 +0100106 // The location of this breakpoint.
Brian Carlstromea46f952013-07-30 01:26:50 -0700107 mirror::ArtMethod* method;
Elliott Hughesa656a0f2012-02-21 18:03:44 -0800108 uint32_t dex_pc;
Sebastien Hertza76a6d42014-03-20 16:40:17 +0100109
110 // Indicates whether breakpoint needs full deoptimization or selective deoptimization.
111 bool need_full_deoptimization;
112
113 Breakpoint(mirror::ArtMethod* method, uint32_t dex_pc, bool need_full_deoptimization)
114 : method(method), dex_pc(dex_pc), need_full_deoptimization(need_full_deoptimization) {}
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700115
116 void VisitRoots(RootCallback* callback, void* arg) {
117 if (method != nullptr) {
118 callback(reinterpret_cast<mirror::Object**>(&method), arg, 0, kRootDebugger);
119 }
120 }
Elliott Hughes86964332012-02-15 19:37:42 -0800121};
122
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700123static std::ostream& operator<<(std::ostream& os, const Breakpoint& rhs)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700124 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes229feb72012-02-23 13:33:29 -0800125 os << StringPrintf("Breakpoint[%s @%#x]", PrettyMethod(rhs.method).c_str(), rhs.dex_pc);
Elliott Hughes86964332012-02-15 19:37:42 -0800126 return os;
127}
128
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200129class DebugInstrumentationListener FINAL : public instrumentation::InstrumentationListener {
Ian Rogers62d6c772013-02-27 08:32:07 -0800130 public:
131 DebugInstrumentationListener() {}
132 virtual ~DebugInstrumentationListener() {}
133
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200134 void MethodEntered(Thread* thread, mirror::Object* this_object, mirror::ArtMethod* method,
135 uint32_t dex_pc)
136 OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800137 if (method->IsNative()) {
138 // TODO: post location events is a suspension point and native method entry stubs aren't.
139 return;
140 }
Jeff Hao579b0242013-11-18 13:16:49 -0800141 Dbg::PostLocationEvent(method, 0, this_object, Dbg::kMethodEntry, nullptr);
Ian Rogers62d6c772013-02-27 08:32:07 -0800142 }
143
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200144 void MethodExited(Thread* thread, mirror::Object* this_object, mirror::ArtMethod* method,
145 uint32_t dex_pc, const JValue& return_value)
146 OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800147 if (method->IsNative()) {
148 // TODO: post location events is a suspension point and native method entry stubs aren't.
149 return;
150 }
Jeff Hao579b0242013-11-18 13:16:49 -0800151 Dbg::PostLocationEvent(method, dex_pc, this_object, Dbg::kMethodExit, &return_value);
Ian Rogers62d6c772013-02-27 08:32:07 -0800152 }
153
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200154 void MethodUnwind(Thread* thread, mirror::Object* this_object, mirror::ArtMethod* method,
155 uint32_t dex_pc)
156 OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800157 // We're not recorded to listen to this kind of event, so complain.
158 LOG(ERROR) << "Unexpected method unwind event in debugger " << PrettyMethod(method)
Sebastien Hertz51db44a2013-11-19 10:00:29 +0100159 << " " << dex_pc;
Ian Rogers62d6c772013-02-27 08:32:07 -0800160 }
161
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200162 void DexPcMoved(Thread* thread, mirror::Object* this_object, mirror::ArtMethod* method,
163 uint32_t new_dex_pc)
164 OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800165 Dbg::UpdateDebugger(thread, this_object, method, new_dex_pc);
166 }
167
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200168 void FieldRead(Thread* thread, mirror::Object* this_object, mirror::ArtMethod* method,
169 uint32_t dex_pc, mirror::ArtField* field)
170 OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
171 Dbg::PostFieldAccessEvent(method, dex_pc, this_object, field);
Ian Rogers62d6c772013-02-27 08:32:07 -0800172 }
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200173
174 void FieldWritten(Thread* thread, mirror::Object* this_object, mirror::ArtMethod* method,
175 uint32_t dex_pc, mirror::ArtField* field, const JValue& field_value)
176 OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
177 Dbg::PostFieldModificationEvent(method, dex_pc, this_object, field, &field_value);
178 }
179
180 void ExceptionCaught(Thread* thread, const ThrowLocation& throw_location,
181 mirror::ArtMethod* catch_method, uint32_t catch_dex_pc,
182 mirror::Throwable* exception_object)
183 OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
184 Dbg::PostException(throw_location, catch_method, catch_dex_pc, exception_object);
185 }
186
187 private:
188 DISALLOW_COPY_AND_ASSIGN(DebugInstrumentationListener);
Ian Rogers62d6c772013-02-27 08:32:07 -0800189} gDebugInstrumentationListener;
190
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700191// JDWP is allowed unless the Zygote forbids it.
192static bool gJdwpAllowed = true;
193
Elliott Hughesc0f09332012-03-26 13:27:06 -0700194// Was there a -Xrunjdwp or -agentlib:jdwp= argument on the command line?
Elliott Hughes3bb81562011-10-21 18:52:59 -0700195static bool gJdwpConfigured = false;
196
Elliott Hughesc0f09332012-03-26 13:27:06 -0700197// Broken-down JDWP options. (Only valid if IsJdwpConfigured() is true.)
Elliott Hughes376a7a02011-10-24 18:35:55 -0700198static JDWP::JdwpOptions gJdwpOptions;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700199
200// Runtime JDWP state.
201static JDWP::JdwpState* gJdwpState = NULL;
202static bool gDebuggerConnected; // debugger or DDMS is connected.
203static bool gDebuggerActive; // debugger is making requests.
Elliott Hughes86964332012-02-15 19:37:42 -0800204static bool gDisposed; // debugger called VirtualMachine.Dispose, so we should drop the connection.
Elliott Hughes3bb81562011-10-21 18:52:59 -0700205
Elliott Hughes47fce012011-10-25 18:37:19 -0700206static bool gDdmThreadNotification = false;
207
Elliott Hughes767a1472011-10-26 18:49:02 -0700208// DDMS GC-related settings.
209static Dbg::HpifWhen gDdmHpifWhen = Dbg::HPIF_WHEN_NEVER;
210static Dbg::HpsgWhen gDdmHpsgWhen = Dbg::HPSG_WHEN_NEVER;
211static Dbg::HpsgWhat gDdmHpsgWhat;
212static Dbg::HpsgWhen gDdmNhsgWhen = Dbg::HPSG_WHEN_NEVER;
213static Dbg::HpsgWhat gDdmNhsgWhat;
214
Ian Rogers719d1a32014-03-06 12:13:39 -0800215static ObjectRegistry* gRegistry = nullptr;
Elliott Hughes475fc232011-10-25 15:00:35 -0700216
Elliott Hughes545a0642011-11-08 19:10:03 -0800217// Recent allocation tracking.
Ian Rogers719d1a32014-03-06 12:13:39 -0800218Mutex* Dbg::alloc_tracker_lock_ = nullptr;
219AllocRecord* Dbg::recent_allocation_records_ = nullptr; // TODO: CircularBuffer<AllocRecord>
220size_t Dbg::alloc_record_max_ = 0;
221size_t Dbg::alloc_record_head_ = 0;
222size_t Dbg::alloc_record_count_ = 0;
Elliott Hughes545a0642011-11-08 19:10:03 -0800223
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100224// Deoptimization support.
Sebastien Hertz4d25df32014-03-21 17:44:46 +0100225Mutex* Dbg::deoptimization_lock_ = nullptr;
226std::vector<DeoptimizationRequest> Dbg::deoptimization_requests_;
227size_t Dbg::full_deoptimization_event_count_ = 0;
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +0100228size_t Dbg::delayed_full_undeoptimization_count_ = 0;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100229
230// Breakpoints.
jeffhao09bfc6a2012-12-11 18:11:43 -0800231static std::vector<Breakpoint> gBreakpoints GUARDED_BY(Locks::breakpoint_lock_);
Elliott Hughes86964332012-02-15 19:37:42 -0800232
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700233void DebugInvokeReq::VisitRoots(RootCallback* callback, void* arg, uint32_t tid,
234 RootType root_type) {
235 if (receiver != nullptr) {
236 callback(&receiver, arg, tid, root_type);
237 }
238 if (thread != nullptr) {
239 callback(&thread, arg, tid, root_type);
240 }
241 if (klass != nullptr) {
242 callback(reinterpret_cast<mirror::Object**>(&klass), arg, tid, root_type);
243 }
244 if (method != nullptr) {
245 callback(reinterpret_cast<mirror::Object**>(&method), arg, tid, root_type);
246 }
247}
248
Sebastien Hertzbb43b432014-04-14 11:59:08 +0200249void DebugInvokeReq::Clear() {
250 invoke_needed = false;
251 receiver = nullptr;
252 thread = nullptr;
253 klass = nullptr;
254 method = nullptr;
255}
256
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700257void SingleStepControl::VisitRoots(RootCallback* callback, void* arg, uint32_t tid,
258 RootType root_type) {
259 if (method != nullptr) {
260 callback(reinterpret_cast<mirror::Object**>(&method), arg, tid, root_type);
261 }
262}
263
Sebastien Hertzbb43b432014-04-14 11:59:08 +0200264bool SingleStepControl::ContainsDexPc(uint32_t dex_pc) const {
265 return dex_pcs.find(dex_pc) == dex_pcs.end();
266}
267
268void SingleStepControl::Clear() {
269 is_active = false;
270 method = nullptr;
271 dex_pcs.clear();
272}
273
Sebastien Hertz4d25df32014-03-21 17:44:46 +0100274void DeoptimizationRequest::VisitRoots(RootCallback* callback, void* arg) {
275 if (method != nullptr) {
276 callback(reinterpret_cast<mirror::Object**>(&method), arg, 0, kRootDebugger);
277 }
278}
279
Brian Carlstromea46f952013-07-30 01:26:50 -0700280static bool IsBreakpoint(const mirror::ArtMethod* m, uint32_t dex_pc)
jeffhao09bfc6a2012-12-11 18:11:43 -0800281 LOCKS_EXCLUDED(Locks::breakpoint_lock_)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700282 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
jeffhao09bfc6a2012-12-11 18:11:43 -0800283 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100284 for (size_t i = 0, e = gBreakpoints.size(); i < e; ++i) {
Elliott Hughesa656a0f2012-02-21 18:03:44 -0800285 if (gBreakpoints[i].method == m && gBreakpoints[i].dex_pc == dex_pc) {
Elliott Hughes86964332012-02-15 19:37:42 -0800286 VLOG(jdwp) << "Hit breakpoint #" << i << ": " << gBreakpoints[i];
287 return true;
288 }
289 }
290 return false;
291}
292
Sebastien Hertz52d131d2014-03-13 16:17:40 +0100293static bool IsSuspendedForDebugger(ScopedObjectAccessUnchecked& soa, Thread* thread)
294 LOCKS_EXCLUDED(Locks::thread_suspend_count_lock_) {
Elliott Hughes9e0c1752013-01-09 14:02:58 -0800295 MutexLock mu(soa.Self(), *Locks::thread_suspend_count_lock_);
296 // A thread may be suspended for GC; in this code, we really want to know whether
297 // there's a debugger suspension active.
298 return thread->IsSuspended() && thread->GetDebugSuspendCount() > 0;
299}
300
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800301static mirror::Array* DecodeArray(JDWP::RefTypeId id, JDWP::JdwpError& status)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700302 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800303 mirror::Object* o = gRegistry->Get<mirror::Object*>(id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800304 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800305 status = JDWP::ERR_INVALID_OBJECT;
306 return NULL;
307 }
308 if (!o->IsArrayInstance()) {
309 status = JDWP::ERR_INVALID_ARRAY;
310 return NULL;
311 }
312 status = JDWP::ERR_NONE;
313 return o->AsArray();
314}
315
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800316static mirror::Class* DecodeClass(JDWP::RefTypeId id, JDWP::JdwpError& status)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700317 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800318 mirror::Object* o = gRegistry->Get<mirror::Object*>(id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800319 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800320 status = JDWP::ERR_INVALID_OBJECT;
321 return NULL;
322 }
323 if (!o->IsClass()) {
324 status = JDWP::ERR_INVALID_CLASS;
325 return NULL;
326 }
327 status = JDWP::ERR_NONE;
328 return o->AsClass();
329}
330
Elliott Hughes221229c2013-01-08 18:17:50 -0800331static JDWP::JdwpError DecodeThread(ScopedObjectAccessUnchecked& soa, JDWP::ObjectId thread_id, Thread*& thread)
jeffhaoa77f0f62012-12-05 17:19:31 -0800332 EXCLUSIVE_LOCKS_REQUIRED(Locks::thread_list_lock_)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700333 LOCKS_EXCLUDED(Locks::thread_suspend_count_lock_)
334 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800335 mirror::Object* thread_peer = gRegistry->Get<mirror::Object*>(thread_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800336 if (thread_peer == NULL || thread_peer == ObjectRegistry::kInvalidObject) {
Elliott Hughes221229c2013-01-08 18:17:50 -0800337 // This isn't even an object.
338 return JDWP::ERR_INVALID_OBJECT;
Elliott Hughes436e3722012-02-17 20:01:47 -0800339 }
Elliott Hughes221229c2013-01-08 18:17:50 -0800340
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800341 mirror::Class* java_lang_Thread = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_Thread);
Elliott Hughes221229c2013-01-08 18:17:50 -0800342 if (!java_lang_Thread->IsAssignableFrom(thread_peer->GetClass())) {
343 // This isn't a thread.
344 return JDWP::ERR_INVALID_THREAD;
345 }
346
347 thread = Thread::FromManagedThread(soa, thread_peer);
348 if (thread == NULL) {
349 // This is a java.lang.Thread without a Thread*. Must be a zombie.
350 return JDWP::ERR_THREAD_NOT_ALIVE;
351 }
352 return JDWP::ERR_NONE;
Elliott Hughes436e3722012-02-17 20:01:47 -0800353}
354
Elliott Hughes24437992011-11-30 14:49:33 -0800355static JDWP::JdwpTag BasicTagFromDescriptor(const char* descriptor) {
356 // JDWP deliberately uses the descriptor characters' ASCII values for its enum.
357 // Note that by "basic" we mean that we don't get more specific than JT_OBJECT.
358 return static_cast<JDWP::JdwpTag>(descriptor[0]);
359}
360
Ian Rogers98379392014-02-24 16:53:16 -0800361static JDWP::JdwpTag TagFromClass(const ScopedObjectAccessUnchecked& soa, mirror::Class* c)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700362 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes86b00102011-12-05 17:54:26 -0800363 CHECK(c != NULL);
Elliott Hughes24437992011-11-30 14:49:33 -0800364 if (c->IsArrayClass()) {
365 return JDWP::JT_ARRAY;
366 }
Elliott Hughes24437992011-11-30 14:49:33 -0800367 if (c->IsStringClass()) {
368 return JDWP::JT_STRING;
Elliott Hughes24437992011-11-30 14:49:33 -0800369 }
Ian Rogers98379392014-02-24 16:53:16 -0800370 if (c->IsClassClass()) {
371 return JDWP::JT_CLASS_OBJECT;
372 }
373 {
374 mirror::Class* thread_class = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_Thread);
375 if (thread_class->IsAssignableFrom(c)) {
376 return JDWP::JT_THREAD;
377 }
378 }
379 {
380 mirror::Class* thread_group_class =
381 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_ThreadGroup);
382 if (thread_group_class->IsAssignableFrom(c)) {
383 return JDWP::JT_THREAD_GROUP;
384 }
385 }
386 {
387 mirror::Class* class_loader_class =
388 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_ClassLoader);
389 if (class_loader_class->IsAssignableFrom(c)) {
390 return JDWP::JT_CLASS_LOADER;
391 }
392 }
393 return JDWP::JT_OBJECT;
Elliott Hughes24437992011-11-30 14:49:33 -0800394}
395
396/*
397 * Objects declared to hold Object might actually hold a more specific
398 * type. The debugger may take a special interest in these (e.g. it
399 * wants to display the contents of Strings), so we want to return an
400 * appropriate tag.
401 *
402 * Null objects are tagged JT_OBJECT.
403 */
Ian Rogers98379392014-02-24 16:53:16 -0800404static JDWP::JdwpTag TagFromObject(const ScopedObjectAccessUnchecked& soa, mirror::Object* o)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700405 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers98379392014-02-24 16:53:16 -0800406 return (o == NULL) ? JDWP::JT_OBJECT : TagFromClass(soa, o->GetClass());
Elliott Hughes24437992011-11-30 14:49:33 -0800407}
408
409static bool IsPrimitiveTag(JDWP::JdwpTag tag) {
410 switch (tag) {
411 case JDWP::JT_BOOLEAN:
412 case JDWP::JT_BYTE:
413 case JDWP::JT_CHAR:
414 case JDWP::JT_FLOAT:
415 case JDWP::JT_DOUBLE:
416 case JDWP::JT_INT:
417 case JDWP::JT_LONG:
418 case JDWP::JT_SHORT:
419 case JDWP::JT_VOID:
420 return true;
421 default:
422 return false;
423 }
424}
425
Elliott Hughes3bb81562011-10-21 18:52:59 -0700426/*
427 * Handle one of the JDWP name/value pairs.
428 *
429 * JDWP options are:
430 * help: if specified, show help message and bail
431 * transport: may be dt_socket or dt_shmem
432 * address: for dt_socket, "host:port", or just "port" when listening
433 * server: if "y", wait for debugger to attach; if "n", attach to debugger
434 * timeout: how long to wait for debugger to connect / listen
435 *
436 * Useful with server=n (these aren't supported yet):
437 * onthrow=<exception-name>: connect to debugger when exception thrown
438 * onuncaught=y|n: connect to debugger when uncaught exception thrown
439 * launch=<command-line>: launch the debugger itself
440 *
441 * The "transport" option is required, as is "address" if server=n.
442 */
443static bool ParseJdwpOption(const std::string& name, const std::string& value) {
444 if (name == "transport") {
445 if (value == "dt_socket") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700446 gJdwpOptions.transport = JDWP::kJdwpTransportSocket;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700447 } else if (value == "dt_android_adb") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700448 gJdwpOptions.transport = JDWP::kJdwpTransportAndroidAdb;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700449 } else {
450 LOG(ERROR) << "JDWP transport not supported: " << value;
451 return false;
452 }
453 } else if (name == "server") {
454 if (value == "n") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700455 gJdwpOptions.server = false;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700456 } else if (value == "y") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700457 gJdwpOptions.server = true;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700458 } else {
459 LOG(ERROR) << "JDWP option 'server' must be 'y' or 'n'";
460 return false;
461 }
462 } else if (name == "suspend") {
463 if (value == "n") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700464 gJdwpOptions.suspend = false;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700465 } else if (value == "y") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700466 gJdwpOptions.suspend = true;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700467 } else {
468 LOG(ERROR) << "JDWP option 'suspend' must be 'y' or 'n'";
469 return false;
470 }
471 } else if (name == "address") {
472 /* this is either <port> or <host>:<port> */
473 std::string port_string;
Elliott Hughes376a7a02011-10-24 18:35:55 -0700474 gJdwpOptions.host.clear();
Elliott Hughes3bb81562011-10-21 18:52:59 -0700475 std::string::size_type colon = value.find(':');
476 if (colon != std::string::npos) {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700477 gJdwpOptions.host = value.substr(0, colon);
Elliott Hughes3bb81562011-10-21 18:52:59 -0700478 port_string = value.substr(colon + 1);
479 } else {
480 port_string = value;
481 }
482 if (port_string.empty()) {
483 LOG(ERROR) << "JDWP address missing port: " << value;
484 return false;
485 }
486 char* end;
Elliott Hughesba8eee12012-01-24 20:25:24 -0800487 uint64_t port = strtoul(port_string.c_str(), &end, 10);
488 if (*end != '\0' || port > 0xffff) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700489 LOG(ERROR) << "JDWP address has junk in port field: " << value;
490 return false;
491 }
Elliott Hughes376a7a02011-10-24 18:35:55 -0700492 gJdwpOptions.port = port;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700493 } else if (name == "launch" || name == "onthrow" || name == "oncaught" || name == "timeout") {
494 /* valid but unsupported */
495 LOG(INFO) << "Ignoring JDWP option '" << name << "'='" << value << "'";
496 } else {
497 LOG(INFO) << "Ignoring unrecognized JDWP option '" << name << "'='" << value << "'";
498 }
499
500 return true;
501}
502
503/*
504 * Parse the latter half of a -Xrunjdwp/-agentlib:jdwp= string, e.g.:
505 * "transport=dt_socket,address=8000,server=y,suspend=n"
506 */
507bool Dbg::ParseJdwpOptions(const std::string& options) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800508 VLOG(jdwp) << "ParseJdwpOptions: " << options;
Elliott Hughes47fce012011-10-25 18:37:19 -0700509
Elliott Hughes3bb81562011-10-21 18:52:59 -0700510 std::vector<std::string> pairs;
511 Split(options, ',', pairs);
512
513 for (size_t i = 0; i < pairs.size(); ++i) {
514 std::string::size_type equals = pairs[i].find('=');
515 if (equals == std::string::npos) {
516 LOG(ERROR) << "Can't parse JDWP option '" << pairs[i] << "' in '" << options << "'";
517 return false;
518 }
519 ParseJdwpOption(pairs[i].substr(0, equals), pairs[i].substr(equals + 1));
520 }
521
Elliott Hughes376a7a02011-10-24 18:35:55 -0700522 if (gJdwpOptions.transport == JDWP::kJdwpTransportUnknown) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700523 LOG(ERROR) << "Must specify JDWP transport: " << options;
524 }
Elliott Hughes376a7a02011-10-24 18:35:55 -0700525 if (!gJdwpOptions.server && (gJdwpOptions.host.empty() || gJdwpOptions.port == 0)) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700526 LOG(ERROR) << "Must specify JDWP host and port when server=n: " << options;
527 return false;
528 }
529
530 gJdwpConfigured = true;
531 return true;
532}
533
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700534void Dbg::StartJdwp() {
Elliott Hughesc0f09332012-03-26 13:27:06 -0700535 if (!gJdwpAllowed || !IsJdwpConfigured()) {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700536 // No JDWP for you!
537 return;
538 }
539
Ian Rogers719d1a32014-03-06 12:13:39 -0800540 CHECK(gRegistry == nullptr);
Elliott Hughes475fc232011-10-25 15:00:35 -0700541 gRegistry = new ObjectRegistry;
542
Ian Rogers719d1a32014-03-06 12:13:39 -0800543 alloc_tracker_lock_ = new Mutex("AllocTracker lock");
Sebastien Hertz4d25df32014-03-21 17:44:46 +0100544 deoptimization_lock_ = new Mutex("deoptimization lock", kDeoptimizationLock);
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700545 // Init JDWP if the debugger is enabled. This may connect out to a
546 // debugger, passively listen for a debugger, or block waiting for a
547 // debugger.
Elliott Hughes376a7a02011-10-24 18:35:55 -0700548 gJdwpState = JDWP::JdwpState::Create(&gJdwpOptions);
549 if (gJdwpState == NULL) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -0800550 // We probably failed because some other process has the port already, which means that
551 // if we don't abort the user is likely to think they're talking to us when they're actually
552 // talking to that other process.
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800553 LOG(FATAL) << "Debugger thread failed to initialize";
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700554 }
555
556 // If a debugger has already attached, send the "welcome" message.
557 // This may cause us to suspend all threads.
Elliott Hughes376a7a02011-10-24 18:35:55 -0700558 if (gJdwpState->IsActive()) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700559 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes376a7a02011-10-24 18:35:55 -0700560 if (!gJdwpState->PostVMStart()) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800561 LOG(WARNING) << "Failed to post 'start' message to debugger";
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700562 }
563 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700564}
565
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700566void Dbg::VisitRoots(RootCallback* callback, void* arg) {
Sebastien Hertz4d25df32014-03-21 17:44:46 +0100567 {
568 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
569 for (Breakpoint& bp : gBreakpoints) {
570 bp.VisitRoots(callback, arg);
571 }
572 }
573 if (deoptimization_lock_ != nullptr) { // only true if the debugger is started.
574 MutexLock mu(Thread::Current(), *deoptimization_lock_);
575 for (DeoptimizationRequest& req : deoptimization_requests_) {
576 req.VisitRoots(callback, arg);
577 }
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700578 }
579}
580
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700581void Dbg::StopJdwp() {
Sebastien Hertz0376e6b2014-02-06 18:12:59 +0100582 // Prevent the JDWP thread from processing JDWP incoming packets after we close the connection.
583 Disposed();
Elliott Hughes376a7a02011-10-24 18:35:55 -0700584 delete gJdwpState;
Ian Rogers719d1a32014-03-06 12:13:39 -0800585 gJdwpState = nullptr;
Elliott Hughes475fc232011-10-25 15:00:35 -0700586 delete gRegistry;
Ian Rogers719d1a32014-03-06 12:13:39 -0800587 gRegistry = nullptr;
588 delete alloc_tracker_lock_;
589 alloc_tracker_lock_ = nullptr;
Sebastien Hertz4d25df32014-03-21 17:44:46 +0100590 delete deoptimization_lock_;
591 deoptimization_lock_ = nullptr;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700592}
593
Elliott Hughes767a1472011-10-26 18:49:02 -0700594void Dbg::GcDidFinish() {
595 if (gDdmHpifWhen != HPIF_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700596 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes81ff3182012-03-23 20:35:56 -0700597 LOG(DEBUG) << "Sending heap info to DDM";
Elliott Hughes7162ad92011-10-27 14:08:42 -0700598 DdmSendHeapInfo(gDdmHpifWhen);
Elliott Hughes767a1472011-10-26 18:49:02 -0700599 }
600 if (gDdmHpsgWhen != HPSG_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700601 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes81ff3182012-03-23 20:35:56 -0700602 LOG(DEBUG) << "Dumping heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700603 DdmSendHeapSegments(false);
Elliott Hughes767a1472011-10-26 18:49:02 -0700604 }
605 if (gDdmNhsgWhen != HPSG_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700606 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes767a1472011-10-26 18:49:02 -0700607 LOG(DEBUG) << "Dumping native heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700608 DdmSendHeapSegments(true);
Elliott Hughes767a1472011-10-26 18:49:02 -0700609 }
610}
611
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700612void Dbg::SetJdwpAllowed(bool allowed) {
613 gJdwpAllowed = allowed;
614}
615
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700616DebugInvokeReq* Dbg::GetInvokeReq() {
Elliott Hughes475fc232011-10-25 15:00:35 -0700617 return Thread::Current()->GetInvokeReq();
618}
619
620Thread* Dbg::GetDebugThread() {
621 return (gJdwpState != NULL) ? gJdwpState->GetDebugThread() : NULL;
622}
623
624void Dbg::ClearWaitForEventThread() {
625 gJdwpState->ClearWaitForEventThread();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700626}
627
628void Dbg::Connected() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700629 CHECK(!gDebuggerConnected);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800630 VLOG(jdwp) << "JDWP has attached";
Elliott Hughes3bb81562011-10-21 18:52:59 -0700631 gDebuggerConnected = true;
Elliott Hughes86964332012-02-15 19:37:42 -0800632 gDisposed = false;
633}
634
635void Dbg::Disposed() {
636 gDisposed = true;
637}
638
639bool Dbg::IsDisposed() {
640 return gDisposed;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700641}
642
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200643// All the instrumentation events the debugger is registered for.
644static constexpr uint32_t kListenerEvents = instrumentation::Instrumentation::kMethodEntered |
645 instrumentation::Instrumentation::kMethodExited |
646 instrumentation::Instrumentation::kDexPcMoved |
647 instrumentation::Instrumentation::kFieldRead |
648 instrumentation::Instrumentation::kFieldWritten |
649 instrumentation::Instrumentation::kExceptionCaught;
650
Elliott Hughesa2155262011-11-16 16:26:58 -0800651void Dbg::GoActive() {
652 // Enable all debugging features, including scans for breakpoints.
653 // This is a no-op if we're already active.
654 // Only called from the JDWP handler thread.
655 if (gDebuggerActive) {
656 return;
657 }
658
Elliott Hughesc0f09332012-03-26 13:27:06 -0700659 {
660 // TODO: dalvik only warned if there were breakpoints left over. clear in Dbg::Disconnected?
jeffhao09bfc6a2012-12-11 18:11:43 -0800661 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Elliott Hughesc0f09332012-03-26 13:27:06 -0700662 CHECK_EQ(gBreakpoints.size(), 0U);
663 }
Elliott Hughesa2155262011-11-16 16:26:58 -0800664
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100665 {
Sebastien Hertz4d25df32014-03-21 17:44:46 +0100666 MutexLock mu(Thread::Current(), *deoptimization_lock_);
667 CHECK_EQ(deoptimization_requests_.size(), 0U);
668 CHECK_EQ(full_deoptimization_event_count_, 0U);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +0100669 CHECK_EQ(delayed_full_undeoptimization_count_, 0U);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100670 }
671
Ian Rogers62d6c772013-02-27 08:32:07 -0800672 Runtime* runtime = Runtime::Current();
673 runtime->GetThreadList()->SuspendAll();
674 Thread* self = Thread::Current();
675 ThreadState old_state = self->SetStateUnsafe(kRunnable);
676 CHECK_NE(old_state, kRunnable);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100677 runtime->GetInstrumentation()->EnableDeoptimization();
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200678 runtime->GetInstrumentation()->AddListener(&gDebugInstrumentationListener, kListenerEvents);
Elliott Hughesa2155262011-11-16 16:26:58 -0800679 gDebuggerActive = true;
Ian Rogers62d6c772013-02-27 08:32:07 -0800680 CHECK_EQ(self->SetStateUnsafe(old_state), kRunnable);
681 runtime->GetThreadList()->ResumeAll();
682
683 LOG(INFO) << "Debugger is active";
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700684}
685
686void Dbg::Disconnected() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700687 CHECK(gDebuggerConnected);
688
Elliott Hughesc0f09332012-03-26 13:27:06 -0700689 LOG(INFO) << "Debugger is no longer active";
Elliott Hughes234ab152011-10-26 14:02:26 -0700690
Ian Rogers62d6c772013-02-27 08:32:07 -0800691 // Suspend all threads and exclusively acquire the mutator lock. Set the state of the thread
692 // to kRunnable to avoid scoped object access transitions. Remove the debugger as a listener
693 // and clear the object registry.
694 Runtime* runtime = Runtime::Current();
695 runtime->GetThreadList()->SuspendAll();
696 Thread* self = Thread::Current();
697 ThreadState old_state = self->SetStateUnsafe(kRunnable);
Sebastien Hertzaaea7342014-02-25 15:10:04 +0100698
699 // Debugger may not be active at this point.
700 if (gDebuggerActive) {
701 {
702 // Since we're going to disable deoptimization, we clear the deoptimization requests queue.
703 // This prevents us from having any pending deoptimization request when the debugger attaches
704 // to us again while no event has been requested yet.
Sebastien Hertz4d25df32014-03-21 17:44:46 +0100705 MutexLock mu(Thread::Current(), *deoptimization_lock_);
706 deoptimization_requests_.clear();
707 full_deoptimization_event_count_ = 0U;
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +0100708 delayed_full_undeoptimization_count_ = 0U;
Sebastien Hertzaaea7342014-02-25 15:10:04 +0100709 }
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200710 runtime->GetInstrumentation()->RemoveListener(&gDebugInstrumentationListener, kListenerEvents);
Sebastien Hertzaaea7342014-02-25 15:10:04 +0100711 runtime->GetInstrumentation()->DisableDeoptimization();
712 gDebuggerActive = false;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100713 }
Elliott Hughes234ab152011-10-26 14:02:26 -0700714 gRegistry->Clear();
715 gDebuggerConnected = false;
Ian Rogers62d6c772013-02-27 08:32:07 -0800716 CHECK_EQ(self->SetStateUnsafe(old_state), kRunnable);
717 runtime->GetThreadList()->ResumeAll();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700718}
719
Elliott Hughesc0f09332012-03-26 13:27:06 -0700720bool Dbg::IsDebuggerActive() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700721 return gDebuggerActive;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700722}
723
Elliott Hughesc0f09332012-03-26 13:27:06 -0700724bool Dbg::IsJdwpConfigured() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700725 return gJdwpConfigured;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700726}
727
728int64_t Dbg::LastDebuggerActivity() {
Elliott Hughesca951522011-12-05 12:01:32 -0800729 return gJdwpState->LastDebuggerActivity();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700730}
731
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700732void Dbg::UndoDebuggerSuspensions() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700733 Runtime::Current()->GetThreadList()->UndoDebuggerSuspensions();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700734}
735
Elliott Hughes88d63092013-01-09 09:55:54 -0800736std::string Dbg::GetClassName(JDWP::RefTypeId class_id) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800737 mirror::Object* o = gRegistry->Get<mirror::Object*>(class_id);
Elliott Hughes436e3722012-02-17 20:01:47 -0800738 if (o == NULL) {
739 return "NULL";
740 }
Elliott Hughes64f574f2013-02-20 14:57:12 -0800741 if (o == ObjectRegistry::kInvalidObject) {
Elliott Hughes88d63092013-01-09 09:55:54 -0800742 return StringPrintf("invalid object %p", reinterpret_cast<void*>(class_id));
Elliott Hughes436e3722012-02-17 20:01:47 -0800743 }
744 if (!o->IsClass()) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700745 return StringPrintf("non-class %p", o); // This is only used for debugging output anyway.
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800746 }
Elliott Hughesc308a5d2012-02-16 17:12:06 -0800747 return DescriptorToName(ClassHelper(o->AsClass()).GetDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700748}
749
Elliott Hughes88d63092013-01-09 09:55:54 -0800750JDWP::JdwpError Dbg::GetClassObject(JDWP::RefTypeId id, JDWP::ObjectId& class_object_id) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800751 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800752 mirror::Class* c = DecodeClass(id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -0800753 if (c == NULL) {
754 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800755 }
Elliott Hughes88d63092013-01-09 09:55:54 -0800756 class_object_id = gRegistry->Add(c);
Elliott Hughes436e3722012-02-17 20:01:47 -0800757 return JDWP::ERR_NONE;
Elliott Hughes86964332012-02-15 19:37:42 -0800758}
759
Elliott Hughes88d63092013-01-09 09:55:54 -0800760JDWP::JdwpError Dbg::GetSuperclass(JDWP::RefTypeId id, JDWP::RefTypeId& superclass_id) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800761 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800762 mirror::Class* c = DecodeClass(id, status);
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800763 if (c == NULL) {
764 return status;
765 }
766 if (c->IsInterface()) {
767 // http://code.google.com/p/android/issues/detail?id=20856
Elliott Hughes88d63092013-01-09 09:55:54 -0800768 superclass_id = 0;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800769 } else {
Elliott Hughes88d63092013-01-09 09:55:54 -0800770 superclass_id = gRegistry->Add(c->GetSuperClass());
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800771 }
772 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700773}
774
Elliott Hughes436e3722012-02-17 20:01:47 -0800775JDWP::JdwpError Dbg::GetClassLoader(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800776 mirror::Object* o = gRegistry->Get<mirror::Object*>(id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800777 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800778 return JDWP::ERR_INVALID_OBJECT;
779 }
780 expandBufAddObjectId(pReply, gRegistry->Add(o->GetClass()->GetClassLoader()));
781 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700782}
783
Elliott Hughes436e3722012-02-17 20:01:47 -0800784JDWP::JdwpError Dbg::GetModifiers(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) {
785 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800786 mirror::Class* c = DecodeClass(id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -0800787 if (c == NULL) {
788 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800789 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800790
791 uint32_t access_flags = c->GetAccessFlags() & kAccJavaFlagsMask;
792
Yevgeny Roubande34eea2014-02-15 01:06:03 +0700793 // Set ACC_SUPER. Dex files don't contain this flag but only classes are supposed to have it set,
794 // not interfaces.
Elliott Hughes436e3722012-02-17 20:01:47 -0800795 // Class.getModifiers doesn't return it, but JDWP does, so we set it here.
Yevgeny Roubande34eea2014-02-15 01:06:03 +0700796 if ((access_flags & kAccInterface) == 0) {
797 access_flags |= kAccSuper;
798 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800799
800 expandBufAdd4BE(pReply, access_flags);
801
802 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700803}
804
Elliott Hughesf327e072013-01-09 16:01:26 -0800805JDWP::JdwpError Dbg::GetMonitorInfo(JDWP::ObjectId object_id, JDWP::ExpandBuf* reply)
806 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800807 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800808 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughesf327e072013-01-09 16:01:26 -0800809 return JDWP::ERR_INVALID_OBJECT;
810 }
811
812 // Ensure all threads are suspended while we read objects' lock words.
813 Thread* self = Thread::Current();
Sebastien Hertz54263242014-03-19 18:16:50 +0100814 CHECK_EQ(self->GetState(), kRunnable);
815 self->TransitionFromRunnableToSuspended(kSuspended);
816 Runtime::Current()->GetThreadList()->SuspendAll();
Elliott Hughesf327e072013-01-09 16:01:26 -0800817
818 MonitorInfo monitor_info(o);
819
Sebastien Hertz54263242014-03-19 18:16:50 +0100820 Runtime::Current()->GetThreadList()->ResumeAll();
821 self->TransitionFromSuspendedToRunnable();
Elliott Hughesf327e072013-01-09 16:01:26 -0800822
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700823 if (monitor_info.owner_ != NULL) {
824 expandBufAddObjectId(reply, gRegistry->Add(monitor_info.owner_->GetPeer()));
Elliott Hughesf327e072013-01-09 16:01:26 -0800825 } else {
826 expandBufAddObjectId(reply, gRegistry->Add(NULL));
827 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700828 expandBufAdd4BE(reply, monitor_info.entry_count_);
829 expandBufAdd4BE(reply, monitor_info.waiters_.size());
830 for (size_t i = 0; i < monitor_info.waiters_.size(); ++i) {
831 expandBufAddObjectId(reply, gRegistry->Add(monitor_info.waiters_[i]->GetPeer()));
Elliott Hughesf327e072013-01-09 16:01:26 -0800832 }
833 return JDWP::ERR_NONE;
834}
835
Elliott Hughes734b8c62013-01-11 15:32:45 -0800836JDWP::JdwpError Dbg::GetOwnedMonitors(JDWP::ObjectId thread_id,
837 std::vector<JDWP::ObjectId>& monitors,
Sebastien Hertz52d131d2014-03-13 16:17:40 +0100838 std::vector<uint32_t>& stack_depths) {
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800839 ScopedObjectAccessUnchecked soa(Thread::Current());
840 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
841 Thread* thread;
842 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
843 if (error != JDWP::ERR_NONE) {
844 return error;
845 }
846 if (!IsSuspendedForDebugger(soa, thread)) {
847 return JDWP::ERR_THREAD_NOT_SUSPENDED;
848 }
849
850 struct OwnedMonitorVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -0800851 OwnedMonitorVisitor(Thread* thread, Context* context)
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800852 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -0800853 : StackVisitor(thread, context), current_stack_depth(0) {}
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800854
855 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
856 // annotalysis.
857 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
858 if (!GetMethod()->IsRuntimeMethod()) {
859 Monitor::VisitLocks(this, AppendOwnedMonitors, this);
Elliott Hughes734b8c62013-01-11 15:32:45 -0800860 ++current_stack_depth;
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800861 }
862 return true;
863 }
864
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800865 static void AppendOwnedMonitors(mirror::Object* owned_monitor, void* arg) {
Ian Rogers7a22fa62013-01-23 12:16:16 -0800866 OwnedMonitorVisitor* visitor = reinterpret_cast<OwnedMonitorVisitor*>(arg);
Elliott Hughes734b8c62013-01-11 15:32:45 -0800867 visitor->monitors.push_back(owned_monitor);
868 visitor->stack_depths.push_back(visitor->current_stack_depth);
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800869 }
870
Elliott Hughes734b8c62013-01-11 15:32:45 -0800871 size_t current_stack_depth;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800872 std::vector<mirror::Object*> monitors;
Elliott Hughes734b8c62013-01-11 15:32:45 -0800873 std::vector<uint32_t> stack_depths;
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800874 };
Ian Rogers7a22fa62013-01-23 12:16:16 -0800875 UniquePtr<Context> context(Context::Create());
876 OwnedMonitorVisitor visitor(thread, context.get());
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800877 visitor.WalkStack();
878
879 for (size_t i = 0; i < visitor.monitors.size(); ++i) {
880 monitors.push_back(gRegistry->Add(visitor.monitors[i]));
Elliott Hughes734b8c62013-01-11 15:32:45 -0800881 stack_depths.push_back(visitor.stack_depths[i]);
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800882 }
883
884 return JDWP::ERR_NONE;
885}
886
Sebastien Hertz52d131d2014-03-13 16:17:40 +0100887JDWP::JdwpError Dbg::GetContendedMonitor(JDWP::ObjectId thread_id,
888 JDWP::ObjectId& contended_monitor) {
Elliott Hughesf9501702013-01-11 11:22:27 -0800889 ScopedObjectAccessUnchecked soa(Thread::Current());
890 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
891 Thread* thread;
892 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
893 if (error != JDWP::ERR_NONE) {
894 return error;
895 }
896 if (!IsSuspendedForDebugger(soa, thread)) {
897 return JDWP::ERR_THREAD_NOT_SUSPENDED;
898 }
899
900 contended_monitor = gRegistry->Add(Monitor::GetContendedMonitor(thread));
901
902 return JDWP::ERR_NONE;
903}
904
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800905JDWP::JdwpError Dbg::GetInstanceCounts(const std::vector<JDWP::RefTypeId>& class_ids,
906 std::vector<uint64_t>& counts)
907 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800908 gc::Heap* heap = Runtime::Current()->GetHeap();
909 heap->CollectGarbage(false);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800910 std::vector<mirror::Class*> classes;
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800911 counts.clear();
912 for (size_t i = 0; i < class_ids.size(); ++i) {
913 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800914 mirror::Class* c = DecodeClass(class_ids[i], status);
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800915 if (c == NULL) {
916 return status;
917 }
918 classes.push_back(c);
919 counts.push_back(0);
920 }
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800921 heap->CountInstances(classes, false, &counts[0]);
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800922 return JDWP::ERR_NONE;
923}
924
Elliott Hughes3b78c942013-01-15 17:35:41 -0800925JDWP::JdwpError Dbg::GetInstances(JDWP::RefTypeId class_id, int32_t max_count, std::vector<JDWP::ObjectId>& instances)
926 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800927 gc::Heap* heap = Runtime::Current()->GetHeap();
928 // We only want reachable instances, so do a GC.
929 heap->CollectGarbage(false);
Elliott Hughes3b78c942013-01-15 17:35:41 -0800930 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800931 mirror::Class* c = DecodeClass(class_id, status);
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800932 if (c == nullptr) {
Elliott Hughes3b78c942013-01-15 17:35:41 -0800933 return status;
934 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800935 std::vector<mirror::Object*> raw_instances;
Elliott Hughes3b78c942013-01-15 17:35:41 -0800936 Runtime::Current()->GetHeap()->GetInstances(c, max_count, raw_instances);
937 for (size_t i = 0; i < raw_instances.size(); ++i) {
938 instances.push_back(gRegistry->Add(raw_instances[i]));
939 }
940 return JDWP::ERR_NONE;
941}
942
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800943JDWP::JdwpError Dbg::GetReferringObjects(JDWP::ObjectId object_id, int32_t max_count,
944 std::vector<JDWP::ObjectId>& referring_objects)
945 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800946 gc::Heap* heap = Runtime::Current()->GetHeap();
947 heap->CollectGarbage(false);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800948 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800949 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800950 return JDWP::ERR_INVALID_OBJECT;
951 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800952 std::vector<mirror::Object*> raw_instances;
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800953 heap->GetReferringObjects(o, max_count, raw_instances);
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800954 for (size_t i = 0; i < raw_instances.size(); ++i) {
955 referring_objects.push_back(gRegistry->Add(raw_instances[i]));
956 }
957 return JDWP::ERR_NONE;
958}
959
Elliott Hughes64f574f2013-02-20 14:57:12 -0800960JDWP::JdwpError Dbg::DisableCollection(JDWP::ObjectId object_id)
961 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Sebastien Hertze96060a2013-12-11 12:06:28 +0100962 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
963 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
964 return JDWP::ERR_INVALID_OBJECT;
965 }
Elliott Hughes64f574f2013-02-20 14:57:12 -0800966 gRegistry->DisableCollection(object_id);
967 return JDWP::ERR_NONE;
968}
969
970JDWP::JdwpError Dbg::EnableCollection(JDWP::ObjectId object_id)
971 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Sebastien Hertze96060a2013-12-11 12:06:28 +0100972 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
973 // Unlike DisableCollection, JDWP specs do not state an invalid object causes an error. The RI
974 // also ignores these cases and never return an error. However it's not obvious why this command
975 // should behave differently from DisableCollection and IsCollected commands. So let's be more
976 // strict and return an error if this happens.
977 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
978 return JDWP::ERR_INVALID_OBJECT;
979 }
Elliott Hughes64f574f2013-02-20 14:57:12 -0800980 gRegistry->EnableCollection(object_id);
981 return JDWP::ERR_NONE;
982}
983
984JDWP::JdwpError Dbg::IsCollected(JDWP::ObjectId object_id, bool& is_collected)
985 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Sebastien Hertz65637eb2014-01-10 17:40:02 +0100986 if (object_id == 0) {
987 // Null object id is invalid.
Sebastien Hertze96060a2013-12-11 12:06:28 +0100988 return JDWP::ERR_INVALID_OBJECT;
989 }
Sebastien Hertz65637eb2014-01-10 17:40:02 +0100990 // JDWP specs state an INVALID_OBJECT error is returned if the object ID is not valid. However
991 // the RI seems to ignore this and assume object has been collected.
992 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
993 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
994 is_collected = true;
995 } else {
996 is_collected = gRegistry->IsCollected(object_id);
997 }
Elliott Hughes64f574f2013-02-20 14:57:12 -0800998 return JDWP::ERR_NONE;
999}
1000
1001void Dbg::DisposeObject(JDWP::ObjectId object_id, uint32_t reference_count)
1002 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1003 gRegistry->DisposeObject(object_id, reference_count);
1004}
1005
Sebastien Hertz4d8fd492014-03-28 16:29:41 +01001006static JDWP::JdwpTypeTag GetTypeTag(mirror::Class* klass)
1007 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1008 DCHECK(klass != nullptr);
1009 if (klass->IsArrayClass()) {
1010 return JDWP::TT_ARRAY;
1011 } else if (klass->IsInterface()) {
1012 return JDWP::TT_INTERFACE;
1013 } else {
1014 return JDWP::TT_CLASS;
1015 }
1016}
1017
Elliott Hughes88d63092013-01-09 09:55:54 -08001018JDWP::JdwpError Dbg::GetReflectedType(JDWP::RefTypeId class_id, JDWP::ExpandBuf* pReply) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001019 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001020 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001021 if (c == NULL) {
1022 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001023 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001024
Sebastien Hertz4d8fd492014-03-28 16:29:41 +01001025 JDWP::JdwpTypeTag type_tag = GetTypeTag(c);
1026 expandBufAdd1(pReply, type_tag);
Elliott Hughes88d63092013-01-09 09:55:54 -08001027 expandBufAddRefTypeId(pReply, class_id);
Elliott Hughes436e3722012-02-17 20:01:47 -08001028 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001029}
1030
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001031void Dbg::GetClassList(std::vector<JDWP::RefTypeId>& classes) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001032 // Get the complete list of reference classes (i.e. all classes except
1033 // the primitive types).
1034 // Returns a newly-allocated buffer full of RefTypeId values.
1035 struct ClassListCreator {
Elliott Hughesba8eee12012-01-24 20:25:24 -08001036 explicit ClassListCreator(std::vector<JDWP::RefTypeId>& classes) : classes(classes) {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001037 }
1038
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001039 static bool Visit(mirror::Class* c, void* arg) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001040 return reinterpret_cast<ClassListCreator*>(arg)->Visit(c);
1041 }
1042
Elliott Hughes64f574f2013-02-20 14:57:12 -08001043 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1044 // annotalysis.
1045 bool Visit(mirror::Class* c) NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughesa2155262011-11-16 16:26:58 -08001046 if (!c->IsPrimitive()) {
Elliott Hughes64f574f2013-02-20 14:57:12 -08001047 classes.push_back(gRegistry->AddRefType(c));
Elliott Hughesa2155262011-11-16 16:26:58 -08001048 }
1049 return true;
1050 }
1051
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001052 std::vector<JDWP::RefTypeId>& classes;
Elliott Hughesa2155262011-11-16 16:26:58 -08001053 };
1054
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001055 ClassListCreator clc(classes);
Elliott Hughesa2155262011-11-16 16:26:58 -08001056 Runtime::Current()->GetClassLinker()->VisitClasses(ClassListCreator::Visit, &clc);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001057}
1058
Elliott Hughes88d63092013-01-09 09:55:54 -08001059JDWP::JdwpError Dbg::GetClassInfo(JDWP::RefTypeId class_id, JDWP::JdwpTypeTag* pTypeTag, uint32_t* pStatus, std::string* pDescriptor) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001060 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001061 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001062 if (c == NULL) {
1063 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001064 }
1065
Elliott Hughesa2155262011-11-16 16:26:58 -08001066 if (c->IsArrayClass()) {
1067 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
1068 *pTypeTag = JDWP::TT_ARRAY;
1069 } else {
1070 if (c->IsErroneous()) {
1071 *pStatus = JDWP::CS_ERROR;
1072 } else {
1073 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED | JDWP::CS_INITIALIZED;
1074 }
1075 *pTypeTag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
1076 }
1077
1078 if (pDescriptor != NULL) {
Ian Rogersdfb325e2013-10-30 01:00:44 -07001079 *pDescriptor = ClassHelper(c).GetDescriptor();
Elliott Hughesa2155262011-11-16 16:26:58 -08001080 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001081 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001082}
1083
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001084void Dbg::FindLoadedClassBySignature(const char* descriptor, std::vector<JDWP::RefTypeId>& ids) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001085 std::vector<mirror::Class*> classes;
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001086 Runtime::Current()->GetClassLinker()->LookupClasses(descriptor, classes);
1087 ids.clear();
1088 for (size_t i = 0; i < classes.size(); ++i) {
1089 ids.push_back(gRegistry->Add(classes[i]));
1090 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001091}
1092
Elliott Hughes64f574f2013-02-20 14:57:12 -08001093JDWP::JdwpError Dbg::GetReferenceType(JDWP::ObjectId object_id, JDWP::ExpandBuf* pReply)
1094 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001095 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001096 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001097 return JDWP::ERR_INVALID_OBJECT;
Elliott Hughes499c5132011-11-17 14:55:11 -08001098 }
Elliott Hughes2435a572012-02-17 16:07:41 -08001099
Sebastien Hertz4d8fd492014-03-28 16:29:41 +01001100 JDWP::JdwpTypeTag type_tag = GetTypeTag(o->GetClass());
Elliott Hughes64f574f2013-02-20 14:57:12 -08001101 JDWP::RefTypeId type_id = gRegistry->AddRefType(o->GetClass());
Elliott Hughes2435a572012-02-17 16:07:41 -08001102
1103 expandBufAdd1(pReply, type_tag);
1104 expandBufAddRefTypeId(pReply, type_id);
1105
1106 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001107}
1108
Ian Rogersfc0e94b2013-09-23 23:51:32 -07001109JDWP::JdwpError Dbg::GetSignature(JDWP::RefTypeId class_id, std::string* signature) {
Elliott Hughes1fe7afb2012-02-13 17:23:03 -08001110 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001111 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes1fe7afb2012-02-13 17:23:03 -08001112 if (c == NULL) {
1113 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001114 }
Ian Rogersdfb325e2013-10-30 01:00:44 -07001115 *signature = ClassHelper(c).GetDescriptor();
Elliott Hughes1fe7afb2012-02-13 17:23:03 -08001116 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001117}
1118
Elliott Hughes88d63092013-01-09 09:55:54 -08001119JDWP::JdwpError Dbg::GetSourceFile(JDWP::RefTypeId class_id, std::string& result) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001120 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001121 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001122 if (c == NULL) {
1123 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001124 }
Sebastien Hertzb7054ba2014-03-13 11:52:31 +01001125 if (c->IsProxyClass()) {
1126 return JDWP::ERR_ABSENT_INFORMATION;
1127 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001128 result = ClassHelper(c).GetSourceFile();
1129 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001130}
1131
Elliott Hughes88d63092013-01-09 09:55:54 -08001132JDWP::JdwpError Dbg::GetObjectTag(JDWP::ObjectId object_id, uint8_t& tag) {
Ian Rogers98379392014-02-24 16:53:16 -08001133 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001134 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001135 if (o == ObjectRegistry::kInvalidObject) {
Elliott Hughes546b9862012-06-20 16:06:13 -07001136 return JDWP::ERR_INVALID_OBJECT;
1137 }
Ian Rogers98379392014-02-24 16:53:16 -08001138 tag = TagFromObject(soa, o);
Elliott Hughes546b9862012-06-20 16:06:13 -07001139 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001140}
1141
Elliott Hughesaed4be92011-12-02 16:16:23 -08001142size_t Dbg::GetTagWidth(JDWP::JdwpTag tag) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001143 switch (tag) {
1144 case JDWP::JT_VOID:
1145 return 0;
1146 case JDWP::JT_BYTE:
1147 case JDWP::JT_BOOLEAN:
1148 return 1;
1149 case JDWP::JT_CHAR:
1150 case JDWP::JT_SHORT:
1151 return 2;
1152 case JDWP::JT_FLOAT:
1153 case JDWP::JT_INT:
1154 return 4;
1155 case JDWP::JT_ARRAY:
1156 case JDWP::JT_OBJECT:
1157 case JDWP::JT_STRING:
1158 case JDWP::JT_THREAD:
1159 case JDWP::JT_THREAD_GROUP:
1160 case JDWP::JT_CLASS_LOADER:
1161 case JDWP::JT_CLASS_OBJECT:
1162 return sizeof(JDWP::ObjectId);
1163 case JDWP::JT_DOUBLE:
1164 case JDWP::JT_LONG:
1165 return 8;
1166 default:
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001167 LOG(FATAL) << "Unknown tag " << tag;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001168 return -1;
1169 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001170}
1171
Elliott Hughes88d63092013-01-09 09:55:54 -08001172JDWP::JdwpError Dbg::GetArrayLength(JDWP::ObjectId array_id, int& length) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001173 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001174 mirror::Array* a = DecodeArray(array_id, status);
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001175 if (a == NULL) {
1176 return status;
Elliott Hughes24437992011-11-30 14:49:33 -08001177 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001178 length = a->GetLength();
1179 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001180}
1181
Elliott Hughes88d63092013-01-09 09:55:54 -08001182JDWP::JdwpError Dbg::OutputArray(JDWP::ObjectId array_id, int offset, int count, JDWP::ExpandBuf* pReply) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001183 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001184 mirror::Array* a = DecodeArray(array_id, status);
Ian Rogers98379392014-02-24 16:53:16 -08001185 if (a == nullptr) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001186 return status;
1187 }
Elliott Hughes24437992011-11-30 14:49:33 -08001188
1189 if (offset < 0 || count < 0 || offset > a->GetLength() || a->GetLength() - offset < count) {
1190 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001191 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughes24437992011-11-30 14:49:33 -08001192 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001193 std::string descriptor(ClassHelper(a->GetClass()).GetDescriptor());
Elliott Hughes24437992011-11-30 14:49:33 -08001194 JDWP::JdwpTag tag = BasicTagFromDescriptor(descriptor.c_str() + 1);
1195
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001196 expandBufAdd1(pReply, tag);
1197 expandBufAdd4BE(pReply, count);
1198
Elliott Hughes24437992011-11-30 14:49:33 -08001199 if (IsPrimitiveTag(tag)) {
1200 size_t width = GetTagWidth(tag);
Elliott Hughes24437992011-11-30 14:49:33 -08001201 uint8_t* dst = expandBufAddSpace(pReply, count * width);
1202 if (width == 8) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001203 const uint64_t* src8 = reinterpret_cast<uint64_t*>(a->GetRawData(sizeof(uint64_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001204 for (int i = 0; i < count; ++i) JDWP::Write8BE(&dst, src8[offset + i]);
1205 } else if (width == 4) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001206 const uint32_t* src4 = reinterpret_cast<uint32_t*>(a->GetRawData(sizeof(uint32_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001207 for (int i = 0; i < count; ++i) JDWP::Write4BE(&dst, src4[offset + i]);
1208 } else if (width == 2) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001209 const uint16_t* src2 = reinterpret_cast<uint16_t*>(a->GetRawData(sizeof(uint16_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001210 for (int i = 0; i < count; ++i) JDWP::Write2BE(&dst, src2[offset + i]);
1211 } else {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001212 const uint8_t* src = reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint8_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001213 memcpy(dst, &src[offset * width], count * width);
1214 }
1215 } else {
Ian Rogers98379392014-02-24 16:53:16 -08001216 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001217 mirror::ObjectArray<mirror::Object>* oa = a->AsObjectArray<mirror::Object>();
Elliott Hughes24437992011-11-30 14:49:33 -08001218 for (int i = 0; i < count; ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001219 mirror::Object* element = oa->Get(offset + i);
Ian Rogers98379392014-02-24 16:53:16 -08001220 JDWP::JdwpTag specific_tag = (element != nullptr) ? TagFromObject(soa, element)
1221 : tag;
Elliott Hughes24437992011-11-30 14:49:33 -08001222 expandBufAdd1(pReply, specific_tag);
1223 expandBufAddObjectId(pReply, gRegistry->Add(element));
1224 }
1225 }
1226
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001227 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001228}
1229
Ian Rogersef7d42f2014-01-06 12:55:46 -08001230template <typename T>
1231static void CopyArrayData(mirror::Array* a, JDWP::Request& src, int offset, int count)
1232 NO_THREAD_SAFETY_ANALYSIS {
1233 // TODO: fix when annotalysis correctly handles non-member functions.
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001234 DCHECK(a->GetClass()->IsPrimitiveArray());
1235
Ian Rogersef7d42f2014-01-06 12:55:46 -08001236 T* dst = reinterpret_cast<T*>(a->GetRawData(sizeof(T), offset));
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001237 for (int i = 0; i < count; ++i) {
1238 *dst++ = src.ReadValue(sizeof(T));
1239 }
1240}
1241
Elliott Hughes88d63092013-01-09 09:55:54 -08001242JDWP::JdwpError Dbg::SetArrayElements(JDWP::ObjectId array_id, int offset, int count,
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001243 JDWP::Request& request)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001244 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001245 JDWP::JdwpError status;
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001246 mirror::Array* dst = DecodeArray(array_id, status);
1247 if (dst == NULL) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001248 return status;
1249 }
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001250
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001251 if (offset < 0 || count < 0 || offset > dst->GetLength() || dst->GetLength() - offset < count) {
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001252 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001253 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001254 }
nikolay serdjuk1d66e882014-04-07 13:54:24 +07001255 ClassHelper ch(dst->GetClass());
1256 const char* descriptor = ch.GetDescriptor();
Ian Rogersfc0e94b2013-09-23 23:51:32 -07001257 JDWP::JdwpTag tag = BasicTagFromDescriptor(descriptor + 1);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001258
1259 if (IsPrimitiveTag(tag)) {
1260 size_t width = GetTagWidth(tag);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001261 if (width == 8) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001262 CopyArrayData<uint64_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001263 } else if (width == 4) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001264 CopyArrayData<uint32_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001265 } else if (width == 2) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001266 CopyArrayData<uint16_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001267 } else {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001268 CopyArrayData<uint8_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001269 }
1270 } else {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001271 mirror::ObjectArray<mirror::Object>* oa = dst->AsObjectArray<mirror::Object>();
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001272 for (int i = 0; i < count; ++i) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001273 JDWP::ObjectId id = request.ReadObjectId();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001274 mirror::Object* o = gRegistry->Get<mirror::Object*>(id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001275 if (o == ObjectRegistry::kInvalidObject) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001276 return JDWP::ERR_INVALID_OBJECT;
1277 }
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001278 oa->Set<false>(offset + i, o);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001279 }
1280 }
1281
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001282 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001283}
1284
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001285JDWP::ObjectId Dbg::CreateString(const std::string& str) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001286 return gRegistry->Add(mirror::String::AllocFromModifiedUtf8(Thread::Current(), str.c_str()));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001287}
1288
Elliott Hughes88d63092013-01-09 09:55:54 -08001289JDWP::JdwpError Dbg::CreateObject(JDWP::RefTypeId class_id, JDWP::ObjectId& new_object) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001290 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001291 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001292 if (c == NULL) {
1293 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001294 }
Ian Rogers50b35e22012-10-04 10:09:15 -07001295 new_object = gRegistry->Add(c->AllocObject(Thread::Current()));
Elliott Hughes436e3722012-02-17 20:01:47 -08001296 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001297}
1298
Elliott Hughesbf13d362011-12-08 15:51:37 -08001299/*
1300 * Used by Eclipse's "Display" view to evaluate "new byte[5]" to get "(byte[]) [0, 0, 0, 0, 0]".
1301 */
Elliott Hughes88d63092013-01-09 09:55:54 -08001302JDWP::JdwpError Dbg::CreateArrayObject(JDWP::RefTypeId array_class_id, uint32_t length,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001303 JDWP::ObjectId& new_array) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001304 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001305 mirror::Class* c = DecodeClass(array_class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001306 if (c == NULL) {
1307 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001308 }
Ian Rogers6fac4472014-02-25 17:01:10 -08001309 new_array = gRegistry->Add(mirror::Array::Alloc<true>(Thread::Current(), c, length,
1310 c->GetComponentSize(),
1311 Runtime::Current()->GetHeap()->GetCurrentAllocator()));
Elliott Hughes436e3722012-02-17 20:01:47 -08001312 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001313}
1314
Elliott Hughes88d63092013-01-09 09:55:54 -08001315bool Dbg::MatchType(JDWP::RefTypeId instance_class_id, JDWP::RefTypeId class_id) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001316 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001317 mirror::Class* c1 = DecodeClass(instance_class_id, status);
Elliott Hughesa656a0f2012-02-21 18:03:44 -08001318 CHECK(c1 != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001319 mirror::Class* c2 = DecodeClass(class_id, status);
Elliott Hughesa656a0f2012-02-21 18:03:44 -08001320 CHECK(c2 != NULL);
Sebastien Hertz123756a2013-11-27 15:49:42 +01001321 return c2->IsAssignableFrom(c1);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001322}
1323
Brian Carlstromea46f952013-07-30 01:26:50 -07001324static JDWP::FieldId ToFieldId(const mirror::ArtField* f)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001325 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001326 CHECK(!kMovingFields);
Elliott Hughes03181a82011-11-17 17:22:21 -08001327 return static_cast<JDWP::FieldId>(reinterpret_cast<uintptr_t>(f));
Elliott Hughes03181a82011-11-17 17:22:21 -08001328}
1329
Brian Carlstromea46f952013-07-30 01:26:50 -07001330static JDWP::MethodId ToMethodId(const mirror::ArtMethod* m)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001331 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001332 CHECK(!kMovingMethods);
Elliott Hughes03181a82011-11-17 17:22:21 -08001333 return static_cast<JDWP::MethodId>(reinterpret_cast<uintptr_t>(m));
Elliott Hughes03181a82011-11-17 17:22:21 -08001334}
1335
Brian Carlstromea46f952013-07-30 01:26:50 -07001336static mirror::ArtField* FromFieldId(JDWP::FieldId fid)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001337 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001338 CHECK(!kMovingFields);
Brian Carlstromea46f952013-07-30 01:26:50 -07001339 return reinterpret_cast<mirror::ArtField*>(static_cast<uintptr_t>(fid));
Elliott Hughesaed4be92011-12-02 16:16:23 -08001340}
1341
Brian Carlstromea46f952013-07-30 01:26:50 -07001342static mirror::ArtMethod* FromMethodId(JDWP::MethodId mid)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001343 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001344 CHECK(!kMovingMethods);
Brian Carlstromea46f952013-07-30 01:26:50 -07001345 return reinterpret_cast<mirror::ArtMethod*>(static_cast<uintptr_t>(mid));
Elliott Hughes03181a82011-11-17 17:22:21 -08001346}
1347
Brian Carlstromea46f952013-07-30 01:26:50 -07001348static void SetLocation(JDWP::JdwpLocation& location, mirror::ArtMethod* m, uint32_t dex_pc)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001349 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001350 if (m == NULL) {
1351 memset(&location, 0, sizeof(location));
1352 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001353 mirror::Class* c = m->GetDeclaringClass();
Sebastien Hertz4d8fd492014-03-28 16:29:41 +01001354 location.type_tag = GetTypeTag(c);
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001355 location.class_id = gRegistry->AddRefType(c);
Elliott Hughes74847412012-06-20 18:10:21 -07001356 location.method_id = ToMethodId(m);
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001357 location.dex_pc = (m->IsNative() || m->IsProxyMethod()) ? static_cast<uint64_t>(-1) : dex_pc;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001358 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08001359}
1360
Elliott Hughesa96836a2013-01-17 12:27:49 -08001361std::string Dbg::GetMethodName(JDWP::MethodId method_id)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001362 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001363 mirror::ArtMethod* m = FromMethodId(method_id);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001364 return MethodHelper(m).GetName();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001365}
1366
Elliott Hughesa96836a2013-01-17 12:27:49 -08001367std::string Dbg::GetFieldName(JDWP::FieldId field_id)
1368 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001369 mirror::ArtField* f = FromFieldId(field_id);
Elliott Hughesa96836a2013-01-17 12:27:49 -08001370 return FieldHelper(f).GetName();
1371}
1372
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001373/*
1374 * Augment the access flags for synthetic methods and fields by setting
1375 * the (as described by the spec) "0xf0000000 bit". Also, strip out any
1376 * flags not specified by the Java programming language.
1377 */
1378static uint32_t MangleAccessFlags(uint32_t accessFlags) {
1379 accessFlags &= kAccJavaFlagsMask;
1380 if ((accessFlags & kAccSynthetic) != 0) {
1381 accessFlags |= 0xf0000000;
1382 }
1383 return accessFlags;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001384}
1385
Elliott Hughesdbb40792011-11-18 17:05:22 -08001386/*
Jeff Haob7cefc72013-11-14 14:51:09 -08001387 * Circularly shifts registers so that arguments come first. Debuggers
1388 * expect slots to begin with arguments, but dex code places them at
1389 * the end.
Elliott Hughesdbb40792011-11-18 17:05:22 -08001390 */
Jeff Haob7cefc72013-11-14 14:51:09 -08001391static uint16_t MangleSlot(uint16_t slot, mirror::ArtMethod* m)
1392 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1393 const DexFile::CodeItem* code_item = MethodHelper(m).GetCodeItem();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001394 if (code_item == nullptr) {
1395 // We should not get here for a method without code (native, proxy or abstract). Log it and
1396 // return the slot as is since all registers are arguments.
1397 LOG(WARNING) << "Trying to mangle slot for method without code " << PrettyMethod(m);
1398 return slot;
1399 }
Jeff Haob7cefc72013-11-14 14:51:09 -08001400 uint16_t ins_size = code_item->ins_size_;
1401 uint16_t locals_size = code_item->registers_size_ - ins_size;
1402 if (slot >= locals_size) {
1403 return slot - locals_size;
1404 } else {
1405 return slot + ins_size;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001406 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001407}
1408
Jeff Haob7cefc72013-11-14 14:51:09 -08001409/*
1410 * Circularly shifts registers so that arguments come last. Reverts
1411 * slots to dex style argument placement.
1412 */
Brian Carlstromea46f952013-07-30 01:26:50 -07001413static uint16_t DemangleSlot(uint16_t slot, mirror::ArtMethod* m)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001414 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Jeff Haob7cefc72013-11-14 14:51:09 -08001415 const DexFile::CodeItem* code_item = MethodHelper(m).GetCodeItem();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001416 if (code_item == nullptr) {
1417 // We should not get here for a method without code (native, proxy or abstract). Log it and
1418 // return the slot as is since all registers are arguments.
1419 LOG(WARNING) << "Trying to demangle slot for method without code " << PrettyMethod(m);
1420 return slot;
1421 }
Jeff Haob7cefc72013-11-14 14:51:09 -08001422 uint16_t ins_size = code_item->ins_size_;
1423 uint16_t locals_size = code_item->registers_size_ - ins_size;
1424 if (slot < ins_size) {
1425 return slot + locals_size;
1426 } else {
1427 return slot - ins_size;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001428 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001429}
1430
Elliott Hughes88d63092013-01-09 09:55:54 -08001431JDWP::JdwpError Dbg::OutputDeclaredFields(JDWP::RefTypeId class_id, bool with_generic, JDWP::ExpandBuf* pReply) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001432 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001433 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001434 if (c == NULL) {
1435 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001436 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001437
1438 size_t instance_field_count = c->NumInstanceFields();
1439 size_t static_field_count = c->NumStaticFields();
1440
1441 expandBufAdd4BE(pReply, instance_field_count + static_field_count);
1442
1443 for (size_t i = 0; i < instance_field_count + static_field_count; ++i) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001444 mirror::ArtField* f = (i < instance_field_count) ? c->GetInstanceField(i) : c->GetStaticField(i - instance_field_count);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001445 FieldHelper fh(f);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001446 expandBufAddFieldId(pReply, ToFieldId(f));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001447 expandBufAddUtf8String(pReply, fh.GetName());
1448 expandBufAddUtf8String(pReply, fh.GetTypeDescriptor());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001449 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001450 static const char genericSignature[1] = "";
1451 expandBufAddUtf8String(pReply, genericSignature);
1452 }
1453 expandBufAdd4BE(pReply, MangleAccessFlags(f->GetAccessFlags()));
1454 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001455 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001456}
1457
Elliott Hughes88d63092013-01-09 09:55:54 -08001458JDWP::JdwpError Dbg::OutputDeclaredMethods(JDWP::RefTypeId class_id, bool with_generic,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001459 JDWP::ExpandBuf* pReply) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001460 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001461 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001462 if (c == NULL) {
1463 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001464 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001465
1466 size_t direct_method_count = c->NumDirectMethods();
1467 size_t virtual_method_count = c->NumVirtualMethods();
1468
1469 expandBufAdd4BE(pReply, direct_method_count + virtual_method_count);
1470
1471 for (size_t i = 0; i < direct_method_count + virtual_method_count; ++i) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001472 mirror::ArtMethod* m = (i < direct_method_count) ? c->GetDirectMethod(i) : c->GetVirtualMethod(i - direct_method_count);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001473 MethodHelper mh(m);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001474 expandBufAddMethodId(pReply, ToMethodId(m));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001475 expandBufAddUtf8String(pReply, mh.GetName());
Ian Rogersd91d6d62013-09-25 20:26:14 -07001476 expandBufAddUtf8String(pReply, mh.GetSignature().ToString());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001477 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001478 static const char genericSignature[1] = "";
1479 expandBufAddUtf8String(pReply, genericSignature);
1480 }
1481 expandBufAdd4BE(pReply, MangleAccessFlags(m->GetAccessFlags()));
1482 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001483 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001484}
1485
Elliott Hughes88d63092013-01-09 09:55:54 -08001486JDWP::JdwpError Dbg::OutputDeclaredInterfaces(JDWP::RefTypeId class_id, JDWP::ExpandBuf* pReply) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001487 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001488 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001489 if (c == NULL) {
1490 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001491 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001492
1493 ClassHelper kh(c);
Ian Rogersd24e2642012-06-06 21:21:43 -07001494 size_t interface_count = kh.NumDirectInterfaces();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001495 expandBufAdd4BE(pReply, interface_count);
1496 for (size_t i = 0; i < interface_count; ++i) {
Elliott Hughes64f574f2013-02-20 14:57:12 -08001497 expandBufAddRefTypeId(pReply, gRegistry->AddRefType(kh.GetDirectInterface(i)));
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001498 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001499 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001500}
1501
Elliott Hughes88d63092013-01-09 09:55:54 -08001502void Dbg::OutputLineTable(JDWP::RefTypeId, JDWP::MethodId method_id, JDWP::ExpandBuf* pReply)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001503 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001504 struct DebugCallbackContext {
1505 int numItems;
1506 JDWP::ExpandBuf* pReply;
1507
Elliott Hughes2435a572012-02-17 16:07:41 -08001508 static bool Callback(void* context, uint32_t address, uint32_t line_number) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001509 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
1510 expandBufAdd8BE(pContext->pReply, address);
Elliott Hughes2435a572012-02-17 16:07:41 -08001511 expandBufAdd4BE(pContext->pReply, line_number);
Elliott Hughes03181a82011-11-17 17:22:21 -08001512 pContext->numItems++;
Sebastien Hertzf2910ee2013-10-19 16:39:24 +02001513 return false;
Elliott Hughes03181a82011-11-17 17:22:21 -08001514 }
1515 };
Brian Carlstromea46f952013-07-30 01:26:50 -07001516 mirror::ArtMethod* m = FromMethodId(method_id);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001517 MethodHelper mh(m);
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001518 const DexFile::CodeItem* code_item = mh.GetCodeItem();
Elliott Hughes03181a82011-11-17 17:22:21 -08001519 uint64_t start, end;
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001520 if (code_item == nullptr) {
1521 DCHECK(m->IsNative() || m->IsProxyMethod());
Elliott Hughes03181a82011-11-17 17:22:21 -08001522 start = -1;
1523 end = -1;
1524 } else {
1525 start = 0;
jeffhao14f0db92012-12-14 17:50:42 -08001526 // Return the index of the last instruction
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001527 end = code_item->insns_size_in_code_units_ - 1;
Elliott Hughes03181a82011-11-17 17:22:21 -08001528 }
1529
1530 expandBufAdd8BE(pReply, start);
1531 expandBufAdd8BE(pReply, end);
1532
1533 // Add numLines later
1534 size_t numLinesOffset = expandBufGetLength(pReply);
1535 expandBufAdd4BE(pReply, 0);
1536
1537 DebugCallbackContext context;
1538 context.numItems = 0;
1539 context.pReply = pReply;
1540
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001541 if (code_item != nullptr) {
1542 mh.GetDexFile().DecodeDebugInfo(code_item, m->IsStatic(), m->GetDexMethodIndex(),
1543 DebugCallbackContext::Callback, NULL, &context);
1544 }
Elliott Hughes03181a82011-11-17 17:22:21 -08001545
1546 JDWP::Set4BE(expandBufGetBuffer(pReply) + numLinesOffset, context.numItems);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001547}
1548
Elliott Hughes88d63092013-01-09 09:55:54 -08001549void Dbg::OutputVariableTable(JDWP::RefTypeId, JDWP::MethodId method_id, bool with_generic, JDWP::ExpandBuf* pReply) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001550 struct DebugCallbackContext {
Jeff Haob7cefc72013-11-14 14:51:09 -08001551 mirror::ArtMethod* method;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001552 JDWP::ExpandBuf* pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001553 size_t variable_count;
1554 bool with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001555
Jeff Haob7cefc72013-11-14 14:51:09 -08001556 static void Callback(void* context, uint16_t slot, uint32_t startAddress, uint32_t endAddress, const char* name, const char* descriptor, const char* signature)
1557 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001558 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
1559
Jeff Haob7cefc72013-11-14 14:51:09 -08001560 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 -08001561
Jeff Haob7cefc72013-11-14 14:51:09 -08001562 slot = MangleSlot(slot, pContext->method);
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001563
Elliott Hughesdbb40792011-11-18 17:05:22 -08001564 expandBufAdd8BE(pContext->pReply, startAddress);
1565 expandBufAddUtf8String(pContext->pReply, name);
1566 expandBufAddUtf8String(pContext->pReply, descriptor);
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001567 if (pContext->with_generic) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001568 expandBufAddUtf8String(pContext->pReply, signature);
1569 }
1570 expandBufAdd4BE(pContext->pReply, endAddress - startAddress);
1571 expandBufAdd4BE(pContext->pReply, slot);
1572
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001573 ++pContext->variable_count;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001574 }
1575 };
Brian Carlstromea46f952013-07-30 01:26:50 -07001576 mirror::ArtMethod* m = FromMethodId(method_id);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001577 MethodHelper mh(m);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001578
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001579 // arg_count considers doubles and longs to take 2 units.
1580 // variable_count considers everything to take 1 unit.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001581 std::string shorty(mh.GetShorty());
Brian Carlstromea46f952013-07-30 01:26:50 -07001582 expandBufAdd4BE(pReply, mirror::ArtMethod::NumArgRegisters(shorty));
Elliott Hughesdbb40792011-11-18 17:05:22 -08001583
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001584 // We don't know the total number of variables yet, so leave a blank and update it later.
1585 size_t variable_count_offset = expandBufGetLength(pReply);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001586 expandBufAdd4BE(pReply, 0);
1587
1588 DebugCallbackContext context;
Jeff Haob7cefc72013-11-14 14:51:09 -08001589 context.method = m;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001590 context.pReply = pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001591 context.variable_count = 0;
1592 context.with_generic = with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001593
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001594 const DexFile::CodeItem* code_item = mh.GetCodeItem();
1595 if (code_item != nullptr) {
1596 mh.GetDexFile().DecodeDebugInfo(code_item, m->IsStatic(), m->GetDexMethodIndex(), NULL,
1597 DebugCallbackContext::Callback, &context);
1598 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001599
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001600 JDWP::Set4BE(expandBufGetBuffer(pReply) + variable_count_offset, context.variable_count);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001601}
1602
Jeff Hao579b0242013-11-18 13:16:49 -08001603void Dbg::OutputMethodReturnValue(JDWP::MethodId method_id, const JValue* return_value,
1604 JDWP::ExpandBuf* pReply) {
1605 mirror::ArtMethod* m = FromMethodId(method_id);
1606 JDWP::JdwpTag tag = BasicTagFromDescriptor(MethodHelper(m).GetShorty());
1607 OutputJValue(tag, return_value, pReply);
1608}
1609
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02001610void Dbg::OutputFieldValue(JDWP::FieldId field_id, const JValue* field_value,
1611 JDWP::ExpandBuf* pReply) {
1612 mirror::ArtField* f = FromFieldId(field_id);
1613 JDWP::JdwpTag tag = BasicTagFromDescriptor(FieldHelper(f).GetTypeDescriptor());
1614 OutputJValue(tag, field_value, pReply);
1615}
1616
Elliott Hughes9777ba22013-01-17 09:04:19 -08001617JDWP::JdwpError Dbg::GetBytecodes(JDWP::RefTypeId, JDWP::MethodId method_id,
1618 std::vector<uint8_t>& bytecodes)
1619 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001620 mirror::ArtMethod* m = FromMethodId(method_id);
Elliott Hughes9777ba22013-01-17 09:04:19 -08001621 if (m == NULL) {
1622 return JDWP::ERR_INVALID_METHODID;
1623 }
1624 MethodHelper mh(m);
1625 const DexFile::CodeItem* code_item = mh.GetCodeItem();
1626 size_t byte_count = code_item->insns_size_in_code_units_ * 2;
1627 const uint8_t* begin = reinterpret_cast<const uint8_t*>(code_item->insns_);
1628 const uint8_t* end = begin + byte_count;
1629 for (const uint8_t* p = begin; p != end; ++p) {
1630 bytecodes.push_back(*p);
1631 }
1632 return JDWP::ERR_NONE;
1633}
1634
Elliott Hughes88d63092013-01-09 09:55:54 -08001635JDWP::JdwpTag Dbg::GetFieldBasicTag(JDWP::FieldId field_id) {
1636 return BasicTagFromDescriptor(FieldHelper(FromFieldId(field_id)).GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001637}
1638
Elliott Hughes88d63092013-01-09 09:55:54 -08001639JDWP::JdwpTag Dbg::GetStaticFieldBasicTag(JDWP::FieldId field_id) {
1640 return BasicTagFromDescriptor(FieldHelper(FromFieldId(field_id)).GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001641}
1642
Elliott Hughes88d63092013-01-09 09:55:54 -08001643static JDWP::JdwpError GetFieldValueImpl(JDWP::RefTypeId ref_type_id, JDWP::ObjectId object_id,
1644 JDWP::FieldId field_id, JDWP::ExpandBuf* pReply,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001645 bool is_static)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001646 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes0cf74332012-02-23 23:14:00 -08001647 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001648 mirror::Class* c = DecodeClass(ref_type_id, status);
Elliott Hughes88d63092013-01-09 09:55:54 -08001649 if (ref_type_id != 0 && c == NULL) {
Elliott Hughes0cf74332012-02-23 23:14:00 -08001650 return status;
1651 }
1652
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001653 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001654 if ((!is_static && o == NULL) || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001655 return JDWP::ERR_INVALID_OBJECT;
1656 }
Brian Carlstromea46f952013-07-30 01:26:50 -07001657 mirror::ArtField* f = FromFieldId(field_id);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001658
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001659 mirror::Class* receiver_class = c;
Elliott Hughes0cf74332012-02-23 23:14:00 -08001660 if (receiver_class == NULL && o != NULL) {
1661 receiver_class = o->GetClass();
1662 }
1663 // TODO: should we give up now if receiver_class is NULL?
1664 if (receiver_class != NULL && !f->GetDeclaringClass()->IsAssignableFrom(receiver_class)) {
1665 LOG(INFO) << "ERR_INVALID_FIELDID: " << PrettyField(f) << " " << PrettyClass(receiver_class);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001666 return JDWP::ERR_INVALID_FIELDID;
1667 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001668
Elliott Hughes0cf74332012-02-23 23:14:00 -08001669 // The RI only enforces the static/non-static mismatch in one direction.
1670 // TODO: should we change the tests and check both?
1671 if (is_static) {
1672 if (!f->IsStatic()) {
1673 return JDWP::ERR_INVALID_FIELDID;
1674 }
1675 } else {
1676 if (f->IsStatic()) {
1677 LOG(WARNING) << "Ignoring non-NULL receiver for ObjectReference.SetValues on static field " << PrettyField(f);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001678 }
1679 }
jeffhao0dfbb7e2012-11-28 15:26:03 -08001680 if (f->IsStatic()) {
1681 o = f->GetDeclaringClass();
1682 }
Elliott Hughes0cf74332012-02-23 23:14:00 -08001683
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001684 JDWP::JdwpTag tag = BasicTagFromDescriptor(FieldHelper(f).GetTypeDescriptor());
Jeff Hao579b0242013-11-18 13:16:49 -08001685 JValue field_value;
1686 if (tag == JDWP::JT_VOID) {
1687 LOG(FATAL) << "Unknown tag: " << tag;
1688 } else if (!IsPrimitiveTag(tag)) {
1689 field_value.SetL(f->GetObject(o));
1690 } else if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
1691 field_value.SetJ(f->Get64(o));
Elliott Hughesaed4be92011-12-02 16:16:23 -08001692 } else {
Jeff Hao579b0242013-11-18 13:16:49 -08001693 field_value.SetI(f->Get32(o));
Elliott Hughesaed4be92011-12-02 16:16:23 -08001694 }
Jeff Hao579b0242013-11-18 13:16:49 -08001695 Dbg::OutputJValue(tag, &field_value, pReply);
1696
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001697 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001698}
1699
Elliott Hughes88d63092013-01-09 09:55:54 -08001700JDWP::JdwpError Dbg::GetFieldValue(JDWP::ObjectId object_id, JDWP::FieldId field_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001701 JDWP::ExpandBuf* pReply) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001702 return GetFieldValueImpl(0, object_id, field_id, pReply, false);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001703}
1704
Elliott Hughes88d63092013-01-09 09:55:54 -08001705JDWP::JdwpError Dbg::GetStaticFieldValue(JDWP::RefTypeId ref_type_id, JDWP::FieldId field_id, JDWP::ExpandBuf* pReply) {
1706 return GetFieldValueImpl(ref_type_id, 0, field_id, pReply, true);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001707}
1708
Elliott Hughes88d63092013-01-09 09:55:54 -08001709static JDWP::JdwpError SetFieldValueImpl(JDWP::ObjectId object_id, JDWP::FieldId field_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001710 uint64_t value, int width, bool is_static)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001711 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001712 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001713 if ((!is_static && o == NULL) || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001714 return JDWP::ERR_INVALID_OBJECT;
1715 }
Brian Carlstromea46f952013-07-30 01:26:50 -07001716 mirror::ArtField* f = FromFieldId(field_id);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001717
1718 // The RI only enforces the static/non-static mismatch in one direction.
1719 // TODO: should we change the tests and check both?
1720 if (is_static) {
1721 if (!f->IsStatic()) {
1722 return JDWP::ERR_INVALID_FIELDID;
1723 }
1724 } else {
1725 if (f->IsStatic()) {
1726 LOG(WARNING) << "Ignoring non-NULL receiver for ObjectReference.SetValues on static field " << PrettyField(f);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001727 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001728 }
jeffhao0dfbb7e2012-11-28 15:26:03 -08001729 if (f->IsStatic()) {
1730 o = f->GetDeclaringClass();
1731 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001732
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001733 JDWP::JdwpTag tag = BasicTagFromDescriptor(FieldHelper(f).GetTypeDescriptor());
Elliott Hughesaed4be92011-12-02 16:16:23 -08001734
1735 if (IsPrimitiveTag(tag)) {
1736 if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001737 CHECK_EQ(width, 8);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001738 // Debugging can't use transactional mode (runtime only).
1739 f->Set64<false>(o, value);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001740 } else {
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001741 CHECK_LE(width, 4);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001742 // Debugging can't use transactional mode (runtime only).
1743 f->Set32<false>(o, value);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001744 }
1745 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001746 mirror::Object* v = gRegistry->Get<mirror::Object*>(value);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001747 if (v == ObjectRegistry::kInvalidObject) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001748 return JDWP::ERR_INVALID_OBJECT;
1749 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001750 if (v != NULL) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001751 mirror::Class* field_type = FieldHelper(f).GetType();
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001752 if (!field_type->IsAssignableFrom(v->GetClass())) {
1753 return JDWP::ERR_INVALID_OBJECT;
1754 }
1755 }
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001756 // Debugging can't use transactional mode (runtime only).
1757 f->SetObject<false>(o, v);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001758 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001759
1760 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001761}
1762
Elliott Hughes88d63092013-01-09 09:55:54 -08001763JDWP::JdwpError Dbg::SetFieldValue(JDWP::ObjectId object_id, JDWP::FieldId field_id, uint64_t value,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001764 int width) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001765 return SetFieldValueImpl(object_id, field_id, value, width, false);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001766}
1767
Elliott Hughes88d63092013-01-09 09:55:54 -08001768JDWP::JdwpError Dbg::SetStaticFieldValue(JDWP::FieldId field_id, uint64_t value, int width) {
1769 return SetFieldValueImpl(0, field_id, value, width, true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001770}
1771
Elliott Hughes88d63092013-01-09 09:55:54 -08001772std::string Dbg::StringToUtf8(JDWP::ObjectId string_id) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001773 mirror::String* s = gRegistry->Get<mirror::String*>(string_id);
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001774 return s->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001775}
1776
Jeff Hao579b0242013-11-18 13:16:49 -08001777void Dbg::OutputJValue(JDWP::JdwpTag tag, const JValue* return_value, JDWP::ExpandBuf* pReply) {
1778 if (IsPrimitiveTag(tag)) {
1779 expandBufAdd1(pReply, tag);
1780 if (tag == JDWP::JT_BOOLEAN || tag == JDWP::JT_BYTE) {
1781 expandBufAdd1(pReply, return_value->GetI());
1782 } else if (tag == JDWP::JT_CHAR || tag == JDWP::JT_SHORT) {
1783 expandBufAdd2BE(pReply, return_value->GetI());
1784 } else if (tag == JDWP::JT_FLOAT || tag == JDWP::JT_INT) {
1785 expandBufAdd4BE(pReply, return_value->GetI());
1786 } else if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
1787 expandBufAdd8BE(pReply, return_value->GetJ());
1788 } else {
1789 CHECK_EQ(tag, JDWP::JT_VOID);
1790 }
1791 } else {
Ian Rogers98379392014-02-24 16:53:16 -08001792 ScopedObjectAccessUnchecked soa(Thread::Current());
Jeff Hao579b0242013-11-18 13:16:49 -08001793 mirror::Object* value = return_value->GetL();
Ian Rogers98379392014-02-24 16:53:16 -08001794 expandBufAdd1(pReply, TagFromObject(soa, value));
Jeff Hao579b0242013-11-18 13:16:49 -08001795 expandBufAddObjectId(pReply, gRegistry->Add(value));
1796 }
1797}
1798
Elliott Hughes221229c2013-01-08 18:17:50 -08001799JDWP::JdwpError Dbg::GetThreadName(JDWP::ObjectId thread_id, std::string& name) {
jeffhaoa77f0f62012-12-05 17:19:31 -08001800 ScopedObjectAccessUnchecked soa(Thread::Current());
1801 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001802 Thread* thread;
1803 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1804 if (error != JDWP::ERR_NONE && error != JDWP::ERR_THREAD_NOT_ALIVE) {
1805 return error;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001806 }
Elliott Hughes221229c2013-01-08 18:17:50 -08001807
1808 // We still need to report the zombie threads' names, so we can't just call Thread::GetThreadName.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001809 mirror::Object* thread_object = gRegistry->Get<mirror::Object*>(thread_id);
Brian Carlstromea46f952013-07-30 01:26:50 -07001810 mirror::ArtField* java_lang_Thread_name_field =
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001811 soa.DecodeField(WellKnownClasses::java_lang_Thread_name);
1812 mirror::String* s =
1813 reinterpret_cast<mirror::String*>(java_lang_Thread_name_field->GetObject(thread_object));
Elliott Hughes221229c2013-01-08 18:17:50 -08001814 if (s != NULL) {
1815 name = s->ToModifiedUtf8();
1816 }
1817 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001818}
1819
Elliott Hughes221229c2013-01-08 18:17:50 -08001820JDWP::JdwpError Dbg::GetThreadGroup(JDWP::ObjectId thread_id, JDWP::ExpandBuf* pReply) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001821 ScopedObjectAccess soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001822 mirror::Object* thread_object = gRegistry->Get<mirror::Object*>(thread_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001823 if (thread_object == ObjectRegistry::kInvalidObject) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001824 return JDWP::ERR_INVALID_OBJECT;
1825 }
Ian Rogers98379392014-02-24 16:53:16 -08001826 const char* old_cause = soa.Self()->StartAssertNoThreadSuspension("Debugger: GetThreadGroup");
Elliott Hughes2435a572012-02-17 16:07:41 -08001827 // Okay, so it's an object, but is it actually a thread?
Ian Rogers50b35e22012-10-04 10:09:15 -07001828 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001829 Thread* thread;
1830 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1831 if (error == JDWP::ERR_THREAD_NOT_ALIVE) {
1832 // Zombie threads are in the null group.
1833 expandBufAddObjectId(pReply, JDWP::ObjectId(0));
Sebastien Hertz52d131d2014-03-13 16:17:40 +01001834 error = JDWP::ERR_NONE;
1835 } else if (error == JDWP::ERR_NONE) {
1836 mirror::Class* c = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_Thread);
1837 CHECK(c != nullptr);
1838 mirror::ArtField* f = c->FindInstanceField("group", "Ljava/lang/ThreadGroup;");
1839 CHECK(f != NULL);
1840 mirror::Object* group = f->GetObject(thread_object);
1841 CHECK(group != NULL);
1842 JDWP::ObjectId thread_group_id = gRegistry->Add(group);
1843 expandBufAddObjectId(pReply, thread_group_id);
Elliott Hughes221229c2013-01-08 18:17:50 -08001844 }
Ian Rogers98379392014-02-24 16:53:16 -08001845 soa.Self()->EndAssertNoThreadSuspension(old_cause);
Sebastien Hertz52d131d2014-03-13 16:17:40 +01001846 return error;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001847}
1848
Elliott Hughes88d63092013-01-09 09:55:54 -08001849std::string Dbg::GetThreadGroupName(JDWP::ObjectId thread_group_id) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001850 ScopedObjectAccess soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001851 mirror::Object* thread_group = gRegistry->Get<mirror::Object*>(thread_group_id);
Ian Rogers98379392014-02-24 16:53:16 -08001852 CHECK(thread_group != nullptr);
1853 const char* old_cause = soa.Self()->StartAssertNoThreadSuspension("Debugger: GetThreadGroupName");
1854 mirror::Class* c = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_ThreadGroup);
1855 CHECK(c != nullptr);
Brian Carlstromea46f952013-07-30 01:26:50 -07001856 mirror::ArtField* f = c->FindInstanceField("name", "Ljava/lang/String;");
Elliott Hughes499c5132011-11-17 14:55:11 -08001857 CHECK(f != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001858 mirror::String* s = reinterpret_cast<mirror::String*>(f->GetObject(thread_group));
Ian Rogers98379392014-02-24 16:53:16 -08001859 soa.Self()->EndAssertNoThreadSuspension(old_cause);
Elliott Hughes499c5132011-11-17 14:55:11 -08001860 return s->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001861}
1862
Elliott Hughes88d63092013-01-09 09:55:54 -08001863JDWP::ObjectId Dbg::GetThreadGroupParent(JDWP::ObjectId thread_group_id) {
Ian Rogers98379392014-02-24 16:53:16 -08001864 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001865 mirror::Object* thread_group = gRegistry->Get<mirror::Object*>(thread_group_id);
Ian Rogers98379392014-02-24 16:53:16 -08001866 CHECK(thread_group != nullptr);
1867 const char* old_cause = soa.Self()->StartAssertNoThreadSuspension("Debugger: GetThreadGroupParent");
1868 mirror::Class* c = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_ThreadGroup);
1869 CHECK(c != nullptr);
Brian Carlstromea46f952013-07-30 01:26:50 -07001870 mirror::ArtField* f = c->FindInstanceField("parent", "Ljava/lang/ThreadGroup;");
Elliott Hughes4e235312011-12-02 11:34:15 -08001871 CHECK(f != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001872 mirror::Object* parent = f->GetObject(thread_group);
Ian Rogers98379392014-02-24 16:53:16 -08001873 soa.Self()->EndAssertNoThreadSuspension(old_cause);
Elliott Hughes4e235312011-12-02 11:34:15 -08001874 return gRegistry->Add(parent);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001875}
1876
1877JDWP::ObjectId Dbg::GetSystemThreadGroupId() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001878 ScopedObjectAccessUnchecked soa(Thread::Current());
Brian Carlstromea46f952013-07-30 01:26:50 -07001879 mirror::ArtField* f = soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_systemThreadGroup);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001880 mirror::Object* group = f->GetObject(f->GetDeclaringClass());
Ian Rogers365c1022012-06-22 15:05:28 -07001881 return gRegistry->Add(group);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001882}
1883
1884JDWP::ObjectId Dbg::GetMainThreadGroupId() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001885 ScopedObjectAccess soa(Thread::Current());
Brian Carlstromea46f952013-07-30 01:26:50 -07001886 mirror::ArtField* f = soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_mainThreadGroup);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001887 mirror::Object* group = f->GetObject(f->GetDeclaringClass());
Ian Rogers365c1022012-06-22 15:05:28 -07001888 return gRegistry->Add(group);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001889}
1890
Jeff Hao920af3e2013-08-28 15:46:38 -07001891JDWP::JdwpThreadStatus Dbg::ToJdwpThreadStatus(ThreadState state) {
1892 switch (state) {
1893 case kBlocked:
1894 return JDWP::TS_MONITOR;
1895 case kNative:
1896 case kRunnable:
1897 case kSuspended:
1898 return JDWP::TS_RUNNING;
1899 case kSleeping:
1900 return JDWP::TS_SLEEPING;
1901 case kStarting:
1902 case kTerminated:
1903 return JDWP::TS_ZOMBIE;
1904 case kTimedWaiting:
1905 case kWaitingForDebuggerSend:
1906 case kWaitingForDebuggerSuspension:
1907 case kWaitingForDebuggerToAttach:
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01001908 case kWaitingForDeoptimization:
Jeff Hao920af3e2013-08-28 15:46:38 -07001909 case kWaitingForGcToComplete:
1910 case kWaitingForCheckPointsToRun:
1911 case kWaitingForJniOnLoad:
1912 case kWaitingForSignalCatcherOutput:
1913 case kWaitingInMainDebuggerLoop:
1914 case kWaitingInMainSignalCatcherLoop:
1915 case kWaitingPerformingGc:
1916 case kWaiting:
1917 return JDWP::TS_WAIT;
1918 // Don't add a 'default' here so the compiler can spot incompatible enum changes.
1919 }
1920 LOG(FATAL) << "Unknown thread state: " << state;
1921 return JDWP::TS_ZOMBIE;
1922}
1923
Sebastien Hertz52d131d2014-03-13 16:17:40 +01001924JDWP::JdwpError Dbg::GetThreadStatus(JDWP::ObjectId thread_id, JDWP::JdwpThreadStatus* pThreadStatus,
1925 JDWP::JdwpSuspendStatus* pSuspendStatus) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001926 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes499c5132011-11-17 14:55:11 -08001927
Elliott Hughes9e0c1752013-01-09 14:02:58 -08001928 *pSuspendStatus = JDWP::SUSPEND_STATUS_NOT_SUSPENDED;
1929
Ian Rogers50b35e22012-10-04 10:09:15 -07001930 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001931 Thread* thread;
1932 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1933 if (error != JDWP::ERR_NONE) {
1934 if (error == JDWP::ERR_THREAD_NOT_ALIVE) {
1935 *pThreadStatus = JDWP::TS_ZOMBIE;
Elliott Hughes221229c2013-01-08 18:17:50 -08001936 return JDWP::ERR_NONE;
1937 }
1938 return error;
Elliott Hughes499c5132011-11-17 14:55:11 -08001939 }
1940
Elliott Hughes9e0c1752013-01-09 14:02:58 -08001941 if (IsSuspendedForDebugger(soa, thread)) {
1942 *pSuspendStatus = JDWP::SUSPEND_STATUS_SUSPENDED;
Elliott Hughes499c5132011-11-17 14:55:11 -08001943 }
1944
Jeff Hao920af3e2013-08-28 15:46:38 -07001945 *pThreadStatus = ToJdwpThreadStatus(thread->GetState());
Elliott Hughes221229c2013-01-08 18:17:50 -08001946 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001947}
1948
Elliott Hughes221229c2013-01-08 18:17:50 -08001949JDWP::JdwpError Dbg::GetThreadDebugSuspendCount(JDWP::ObjectId thread_id, JDWP::ExpandBuf* pReply) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001950 ScopedObjectAccess soa(Thread::Current());
Ian Rogers50b35e22012-10-04 10:09:15 -07001951 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001952 Thread* thread;
1953 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1954 if (error != JDWP::ERR_NONE) {
1955 return error;
Elliott Hughes2435a572012-02-17 16:07:41 -08001956 }
Ian Rogers50b35e22012-10-04 10:09:15 -07001957 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001958 expandBufAdd4BE(pReply, thread->GetDebugSuspendCount());
Elliott Hughes2435a572012-02-17 16:07:41 -08001959 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001960}
1961
Elliott Hughesf9501702013-01-11 11:22:27 -08001962JDWP::JdwpError Dbg::Interrupt(JDWP::ObjectId thread_id) {
1963 ScopedObjectAccess soa(Thread::Current());
1964 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
1965 Thread* thread;
1966 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1967 if (error != JDWP::ERR_NONE) {
1968 return error;
1969 }
Ian Rogersdd7624d2014-03-14 17:43:00 -07001970 thread->Interrupt(soa.Self());
Elliott Hughesf9501702013-01-11 11:22:27 -08001971 return JDWP::ERR_NONE;
1972}
1973
Elliott Hughescaf76542012-06-28 16:08:22 -07001974void Dbg::GetThreads(JDWP::ObjectId thread_group_id, std::vector<JDWP::ObjectId>& thread_ids) {
Ian Rogers365c1022012-06-22 15:05:28 -07001975 class ThreadListVisitor {
1976 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001977 ThreadListVisitor(const ScopedObjectAccessUnchecked& soa, mirror::Object* desired_thread_group,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001978 std::vector<JDWP::ObjectId>& thread_ids)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001979 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
jeffhao0dfbb7e2012-11-28 15:26:03 -08001980 : soa_(soa), desired_thread_group_(desired_thread_group), thread_ids_(thread_ids) {}
Ian Rogers365c1022012-06-22 15:05:28 -07001981
Elliott Hughesa2155262011-11-16 16:26:58 -08001982 static void Visit(Thread* t, void* arg) {
1983 reinterpret_cast<ThreadListVisitor*>(arg)->Visit(t);
1984 }
1985
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001986 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1987 // annotalysis.
1988 void Visit(Thread* t) NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughesa2155262011-11-16 16:26:58 -08001989 if (t == Dbg::GetDebugThread()) {
1990 // Skip the JDWP thread. Some debuggers get bent out of shape when they can't suspend and
1991 // query all threads, so it's easier if we just don't tell them about this thread.
1992 return;
1993 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001994 mirror::Object* peer = t->GetPeer();
jeffhao0dfbb7e2012-11-28 15:26:03 -08001995 if (IsInDesiredThreadGroup(peer)) {
Ian Rogers120f1c72012-09-28 17:17:10 -07001996 thread_ids_.push_back(gRegistry->Add(peer));
Elliott Hughesa2155262011-11-16 16:26:58 -08001997 }
1998 }
1999
Ian Rogers365c1022012-06-22 15:05:28 -07002000 private:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002001 bool IsInDesiredThreadGroup(mirror::Object* peer)
jeffhao0dfbb7e2012-11-28 15:26:03 -08002002 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
jeffhao0dfbb7e2012-11-28 15:26:03 -08002003 // peer might be NULL if the thread is still starting up.
2004 if (peer == NULL) {
2005 // We can't tell the debugger about this thread yet.
2006 // TODO: if we identified threads to the debugger by their Thread*
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002007 // rather than their peer's mirror::Object*, we could fix this.
jeffhao0dfbb7e2012-11-28 15:26:03 -08002008 // Doing so might help us report ZOMBIE threads too.
2009 return false;
2010 }
jeffhaoc1e04902012-12-13 12:41:10 -08002011 // Do we want threads from all thread groups?
2012 if (desired_thread_group_ == NULL) {
2013 return true;
2014 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002015 mirror::Object* group = soa_.DecodeField(WellKnownClasses::java_lang_Thread_group)->GetObject(peer);
jeffhao0dfbb7e2012-11-28 15:26:03 -08002016 return (group == desired_thread_group_);
2017 }
2018
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07002019 const ScopedObjectAccessUnchecked& soa_;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002020 mirror::Object* const desired_thread_group_;
Elliott Hughescaf76542012-06-28 16:08:22 -07002021 std::vector<JDWP::ObjectId>& thread_ids_;
Elliott Hughesa2155262011-11-16 16:26:58 -08002022 };
2023
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002024 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002025 mirror::Object* thread_group = gRegistry->Get<mirror::Object*>(thread_group_id);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002026 ThreadListVisitor tlv(soa, thread_group, thread_ids);
Ian Rogers50b35e22012-10-04 10:09:15 -07002027 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughesf8349362012-06-18 15:00:06 -07002028 Runtime::Current()->GetThreadList()->ForEach(ThreadListVisitor::Visit, &tlv);
Elliott Hughescaf76542012-06-28 16:08:22 -07002029}
Elliott Hughesa2155262011-11-16 16:26:58 -08002030
Elliott Hughescaf76542012-06-28 16:08:22 -07002031void Dbg::GetChildThreadGroups(JDWP::ObjectId thread_group_id, std::vector<JDWP::ObjectId>& child_thread_group_ids) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002032 ScopedObjectAccess soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002033 mirror::Object* thread_group = gRegistry->Get<mirror::Object*>(thread_group_id);
Elliott Hughescaf76542012-06-28 16:08:22 -07002034
2035 // Get the ArrayList<ThreadGroup> "groups" out of this thread group...
Brian Carlstromea46f952013-07-30 01:26:50 -07002036 mirror::ArtField* groups_field = thread_group->GetClass()->FindInstanceField("groups", "Ljava/util/List;");
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002037 mirror::Object* groups_array_list = groups_field->GetObject(thread_group);
Elliott Hughescaf76542012-06-28 16:08:22 -07002038
2039 // Get the array and size out of the ArrayList<ThreadGroup>...
Brian Carlstromea46f952013-07-30 01:26:50 -07002040 mirror::ArtField* array_field = groups_array_list->GetClass()->FindInstanceField("array", "[Ljava/lang/Object;");
2041 mirror::ArtField* size_field = groups_array_list->GetClass()->FindInstanceField("size", "I");
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002042 mirror::ObjectArray<mirror::Object>* groups_array =
2043 array_field->GetObject(groups_array_list)->AsObjectArray<mirror::Object>();
Elliott Hughescaf76542012-06-28 16:08:22 -07002044 const int32_t size = size_field->GetInt(groups_array_list);
2045
2046 // Copy the first 'size' elements out of the array into the result.
2047 for (int32_t i = 0; i < size; ++i) {
2048 child_thread_group_ids.push_back(gRegistry->Add(groups_array->Get(i)));
Elliott Hughesa2155262011-11-16 16:26:58 -08002049 }
2050}
2051
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002052static int GetStackDepth(Thread* thread)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002053 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002054 struct CountStackDepthVisitor : public StackVisitor {
Brian Carlstrom93ba8932013-07-17 21:31:49 -07002055 explicit CountStackDepthVisitor(Thread* thread)
Ian Rogers7a22fa62013-01-23 12:16:16 -08002056 : StackVisitor(thread, NULL), depth(0) {}
Ian Rogers0399dde2012-06-06 17:09:28 -07002057
Elliott Hughes64f574f2013-02-20 14:57:12 -08002058 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2059 // annotalysis.
2060 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07002061 if (!GetMethod()->IsRuntimeMethod()) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -08002062 ++depth;
2063 }
Elliott Hughes530fa002012-03-12 11:44:49 -07002064 return true;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08002065 }
2066 size_t depth;
2067 };
Elliott Hughes08fc03a2012-06-26 17:34:00 -07002068
Ian Rogers7a22fa62013-01-23 12:16:16 -08002069 CountStackDepthVisitor visitor(thread);
Ian Rogers0399dde2012-06-06 17:09:28 -07002070 visitor.WalkStack();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08002071 return visitor.depth;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002072}
2073
Elliott Hughes221229c2013-01-08 18:17:50 -08002074JDWP::JdwpError Dbg::GetThreadFrameCount(JDWP::ObjectId thread_id, size_t& result) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002075 ScopedObjectAccess soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08002076 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002077 Thread* thread;
2078 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
2079 if (error != JDWP::ERR_NONE) {
2080 return error;
2081 }
Elliott Hughesf15f4a02013-01-09 10:09:38 -08002082 if (!IsSuspendedForDebugger(soa, thread)) {
2083 return JDWP::ERR_THREAD_NOT_SUSPENDED;
2084 }
Elliott Hughes221229c2013-01-08 18:17:50 -08002085 result = GetStackDepth(thread);
2086 return JDWP::ERR_NONE;
Elliott Hughes86964332012-02-15 19:37:42 -08002087}
2088
Ian Rogers306057f2012-11-26 12:45:53 -08002089JDWP::JdwpError Dbg::GetThreadFrames(JDWP::ObjectId thread_id, size_t start_frame,
2090 size_t frame_count, JDWP::ExpandBuf* buf) {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002091 class GetFrameVisitor : public StackVisitor {
2092 public:
Ian Rogers7a22fa62013-01-23 12:16:16 -08002093 GetFrameVisitor(Thread* thread, size_t start_frame, size_t frame_count, JDWP::ExpandBuf* buf)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002094 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08002095 : StackVisitor(thread, NULL), depth_(0),
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002096 start_frame_(start_frame), frame_count_(frame_count), buf_(buf) {
2097 expandBufAdd4BE(buf_, frame_count_);
Elliott Hughes03181a82011-11-17 17:22:21 -08002098 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002099
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002100 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2101 // annotalysis.
2102 virtual bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07002103 if (GetMethod()->IsRuntimeMethod()) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07002104 return true; // The debugger can't do anything useful with a frame that has no Method*.
Elliott Hughes03181a82011-11-17 17:22:21 -08002105 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002106 if (depth_ >= start_frame_ + frame_count_) {
Elliott Hughes530fa002012-03-12 11:44:49 -07002107 return false;
Elliott Hughes03181a82011-11-17 17:22:21 -08002108 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002109 if (depth_ >= start_frame_) {
2110 JDWP::FrameId frame_id(GetFrameId());
2111 JDWP::JdwpLocation location;
2112 SetLocation(location, GetMethod(), GetDexPc());
Ian Rogersef7d42f2014-01-06 12:55:46 -08002113 VLOG(jdwp) << StringPrintf(" Frame %3zd: id=%3" PRIu64 " ", depth_, frame_id) << location;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002114 expandBufAdd8BE(buf_, frame_id);
2115 expandBufAddLocation(buf_, location);
2116 }
2117 ++depth_;
Elliott Hughes530fa002012-03-12 11:44:49 -07002118 return true;
Elliott Hughes03181a82011-11-17 17:22:21 -08002119 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002120
2121 private:
2122 size_t depth_;
2123 const size_t start_frame_;
2124 const size_t frame_count_;
2125 JDWP::ExpandBuf* buf_;
Elliott Hughes03181a82011-11-17 17:22:21 -08002126 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002127
2128 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08002129 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002130 Thread* thread;
2131 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
2132 if (error != JDWP::ERR_NONE) {
2133 return error;
2134 }
Elliott Hughesf15f4a02013-01-09 10:09:38 -08002135 if (!IsSuspendedForDebugger(soa, thread)) {
2136 return JDWP::ERR_THREAD_NOT_SUSPENDED;
2137 }
Ian Rogers7a22fa62013-01-23 12:16:16 -08002138 GetFrameVisitor visitor(thread, start_frame, frame_count, buf);
Ian Rogers0399dde2012-06-06 17:09:28 -07002139 visitor.WalkStack();
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002140 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002141}
2142
2143JDWP::ObjectId Dbg::GetThreadSelfId() {
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07002144 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogerscfaa4552012-11-26 21:00:08 -08002145 return gRegistry->Add(soa.Self()->GetPeer());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002146}
2147
Elliott Hughes475fc232011-10-25 15:00:35 -07002148void Dbg::SuspendVM() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002149 Runtime::Current()->GetThreadList()->SuspendAllForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002150}
2151
2152void Dbg::ResumeVM() {
Elliott Hughesc61a2672012-06-21 14:52:29 -07002153 Runtime::Current()->GetThreadList()->UndoDebuggerSuspensions();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002154}
2155
Elliott Hughes221229c2013-01-08 18:17:50 -08002156JDWP::JdwpError Dbg::SuspendThread(JDWP::ObjectId thread_id, bool request_suspension) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002157 ScopedLocalRef<jobject> peer(Thread::Current()->GetJniEnv(), NULL);
2158 {
2159 ScopedObjectAccess soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002160 peer.reset(soa.AddLocalReference<jobject>(gRegistry->Get<mirror::Object*>(thread_id)));
Elliott Hughes4e235312011-12-02 11:34:15 -08002161 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002162 if (peer.get() == NULL) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002163 return JDWP::ERR_THREAD_NOT_ALIVE;
2164 }
2165 // Suspend thread to build stack trace.
Elliott Hughesf327e072013-01-09 16:01:26 -08002166 bool timed_out;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07002167 Thread* thread = ThreadList::SuspendThreadByPeer(peer.get(), request_suspension, true,
2168 &timed_out);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002169 if (thread != NULL) {
2170 return JDWP::ERR_NONE;
Elliott Hughesf327e072013-01-09 16:01:26 -08002171 } else if (timed_out) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002172 return JDWP::ERR_INTERNAL;
2173 } else {
2174 return JDWP::ERR_THREAD_NOT_ALIVE;
2175 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002176}
2177
Elliott Hughes221229c2013-01-08 18:17:50 -08002178void Dbg::ResumeThread(JDWP::ObjectId thread_id) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002179 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002180 mirror::Object* peer = gRegistry->Get<mirror::Object*>(thread_id);
jeffhaoa77f0f62012-12-05 17:19:31 -08002181 Thread* thread;
2182 {
2183 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
2184 thread = Thread::FromManagedThread(soa, peer);
2185 }
Elliott Hughes4e235312011-12-02 11:34:15 -08002186 if (thread == NULL) {
2187 LOG(WARNING) << "No such thread for resume: " << peer;
2188 return;
2189 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002190 bool needs_resume;
2191 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002192 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002193 needs_resume = thread->GetSuspendCount() > 0;
2194 }
2195 if (needs_resume) {
Elliott Hughes546b9862012-06-20 16:06:13 -07002196 Runtime::Current()->GetThreadList()->Resume(thread, true);
2197 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002198}
2199
2200void Dbg::SuspendSelf() {
Elliott Hughes475fc232011-10-25 15:00:35 -07002201 Runtime::Current()->GetThreadList()->SuspendSelfForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002202}
2203
Ian Rogers0399dde2012-06-06 17:09:28 -07002204struct GetThisVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -08002205 GetThisVisitor(Thread* thread, Context* context, JDWP::FrameId frame_id)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002206 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08002207 : StackVisitor(thread, context), this_object(NULL), frame_id(frame_id) {}
Ian Rogers0399dde2012-06-06 17:09:28 -07002208
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002209 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2210 // annotalysis.
2211 virtual bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002212 if (frame_id != GetFrameId()) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002213 return true; // continue
Ian Rogers0399dde2012-06-06 17:09:28 -07002214 } else {
Ian Rogers62d6c772013-02-27 08:32:07 -08002215 this_object = GetThisObject();
2216 return false;
Ian Rogers0399dde2012-06-06 17:09:28 -07002217 }
Elliott Hughes86b00102011-12-05 17:54:26 -08002218 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002219
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002220 mirror::Object* this_object;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002221 JDWP::FrameId frame_id;
Ian Rogers0399dde2012-06-06 17:09:28 -07002222};
2223
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002224JDWP::JdwpError Dbg::GetThisObject(JDWP::ObjectId thread_id, JDWP::FrameId frame_id,
2225 JDWP::ObjectId* result) {
2226 ScopedObjectAccessUnchecked soa(Thread::Current());
2227 Thread* thread;
2228 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002229 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002230 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
2231 if (error != JDWP::ERR_NONE) {
2232 return error;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002233 }
Elliott Hughes9e0c1752013-01-09 14:02:58 -08002234 if (!IsSuspendedForDebugger(soa, thread)) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002235 return JDWP::ERR_THREAD_NOT_SUSPENDED;
2236 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002237 }
Elliott Hughescaf76542012-06-28 16:08:22 -07002238 UniquePtr<Context> context(Context::Create());
Ian Rogers7a22fa62013-01-23 12:16:16 -08002239 GetThisVisitor visitor(thread, context.get(), frame_id);
Ian Rogers0399dde2012-06-06 17:09:28 -07002240 visitor.WalkStack();
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002241 *result = gRegistry->Add(visitor.this_object);
2242 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002243}
2244
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002245JDWP::JdwpError Dbg::GetLocalValue(JDWP::ObjectId thread_id, JDWP::FrameId frame_id, int slot,
2246 JDWP::JdwpTag tag, uint8_t* buf, size_t width) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002247 struct GetLocalVisitor : public StackVisitor {
Ian Rogers98379392014-02-24 16:53:16 -08002248 GetLocalVisitor(const ScopedObjectAccessUnchecked& soa, Thread* thread, Context* context,
2249 JDWP::FrameId frame_id, int slot, JDWP::JdwpTag tag, uint8_t* buf, size_t width)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002250 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers98379392014-02-24 16:53:16 -08002251 : StackVisitor(thread, context), soa_(soa), frame_id_(frame_id), slot_(slot), tag_(tag),
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002252 buf_(buf), width_(width), error_(JDWP::ERR_NONE) {}
Ian Rogersca190662012-06-26 15:45:57 -07002253
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002254 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2255 // annotalysis.
2256 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07002257 if (GetFrameId() != frame_id_) {
2258 return true; // Not our frame, carry on.
Elliott Hughesdbb40792011-11-18 17:05:22 -08002259 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002260 // TODO: check that the tag is compatible with the actual type of the slot!
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002261 // TODO: check slot is valid for this method or return INVALID_SLOT error.
Brian Carlstromea46f952013-07-30 01:26:50 -07002262 mirror::ArtMethod* m = GetMethod();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002263 if (m->IsNative()) {
2264 // We can't read local value from native method.
2265 error_ = JDWP::ERR_OPAQUE_FRAME;
2266 return false;
2267 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002268 uint16_t reg = DemangleSlot(slot_, m);
Elliott Hughesdbb40792011-11-18 17:05:22 -08002269
Ian Rogers0399dde2012-06-06 17:09:28 -07002270 switch (tag_) {
2271 case JDWP::JT_BOOLEAN:
2272 {
2273 CHECK_EQ(width_, 1U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002274 uint32_t intVal = GetVReg(m, reg, kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002275 VLOG(jdwp) << "get boolean local " << reg << " = " << intVal;
2276 JDWP::Set1(buf_+1, intVal != 0);
2277 }
2278 break;
2279 case JDWP::JT_BYTE:
2280 {
2281 CHECK_EQ(width_, 1U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002282 uint32_t intVal = GetVReg(m, reg, kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002283 VLOG(jdwp) << "get byte local " << reg << " = " << intVal;
2284 JDWP::Set1(buf_+1, intVal);
2285 }
2286 break;
2287 case JDWP::JT_SHORT:
2288 case JDWP::JT_CHAR:
2289 {
2290 CHECK_EQ(width_, 2U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002291 uint32_t intVal = GetVReg(m, reg, kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002292 VLOG(jdwp) << "get short/char local " << reg << " = " << intVal;
2293 JDWP::Set2BE(buf_+1, intVal);
2294 }
2295 break;
2296 case JDWP::JT_INT:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002297 {
2298 CHECK_EQ(width_, 4U);
2299 uint32_t intVal = GetVReg(m, reg, kIntVReg);
2300 VLOG(jdwp) << "get int local " << reg << " = " << intVal;
2301 JDWP::Set4BE(buf_+1, intVal);
2302 }
2303 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002304 case JDWP::JT_FLOAT:
2305 {
2306 CHECK_EQ(width_, 4U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002307 uint32_t intVal = GetVReg(m, reg, kFloatVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002308 VLOG(jdwp) << "get int/float local " << reg << " = " << intVal;
2309 JDWP::Set4BE(buf_+1, intVal);
2310 }
2311 break;
2312 case JDWP::JT_ARRAY:
2313 {
2314 CHECK_EQ(width_, sizeof(JDWP::ObjectId));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002315 mirror::Object* o = reinterpret_cast<mirror::Object*>(GetVReg(m, reg, kReferenceVReg));
Ian Rogers0399dde2012-06-06 17:09:28 -07002316 VLOG(jdwp) << "get array local " << reg << " = " << o;
Mathieu Chartier590fee92013-09-13 13:46:47 -07002317 if (!Runtime::Current()->GetHeap()->IsValidObjectAddress(o)) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002318 LOG(FATAL) << "Register " << reg << " expected to hold array: " << o;
2319 }
2320 JDWP::SetObjectId(buf_+1, gRegistry->Add(o));
2321 }
2322 break;
2323 case JDWP::JT_CLASS_LOADER:
2324 case JDWP::JT_CLASS_OBJECT:
2325 case JDWP::JT_OBJECT:
2326 case JDWP::JT_STRING:
2327 case JDWP::JT_THREAD:
2328 case JDWP::JT_THREAD_GROUP:
2329 {
2330 CHECK_EQ(width_, sizeof(JDWP::ObjectId));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002331 mirror::Object* o = reinterpret_cast<mirror::Object*>(GetVReg(m, reg, kReferenceVReg));
Ian Rogers0399dde2012-06-06 17:09:28 -07002332 VLOG(jdwp) << "get object local " << reg << " = " << o;
Mathieu Chartier590fee92013-09-13 13:46:47 -07002333 if (!Runtime::Current()->GetHeap()->IsValidObjectAddress(o)) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002334 LOG(FATAL) << "Register " << reg << " expected to hold object: " << o;
2335 }
Ian Rogers98379392014-02-24 16:53:16 -08002336 tag_ = TagFromObject(soa_, o);
Ian Rogers0399dde2012-06-06 17:09:28 -07002337 JDWP::SetObjectId(buf_+1, gRegistry->Add(o));
2338 }
2339 break;
2340 case JDWP::JT_DOUBLE:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002341 {
2342 CHECK_EQ(width_, 8U);
2343 uint32_t lo = GetVReg(m, reg, kDoubleLoVReg);
2344 uint64_t hi = GetVReg(m, reg + 1, kDoubleHiVReg);
2345 uint64_t longVal = (hi << 32) | lo;
2346 VLOG(jdwp) << "get double/long local " << hi << ":" << lo << " = " << longVal;
2347 JDWP::Set8BE(buf_+1, longVal);
2348 }
2349 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002350 case JDWP::JT_LONG:
2351 {
2352 CHECK_EQ(width_, 8U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002353 uint32_t lo = GetVReg(m, reg, kLongLoVReg);
2354 uint64_t hi = GetVReg(m, reg + 1, kLongHiVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002355 uint64_t longVal = (hi << 32) | lo;
2356 VLOG(jdwp) << "get double/long local " << hi << ":" << lo << " = " << longVal;
2357 JDWP::Set8BE(buf_+1, longVal);
2358 }
2359 break;
2360 default:
2361 LOG(FATAL) << "Unknown tag " << tag_;
2362 break;
2363 }
2364
2365 // Prepend tag, which may have been updated.
2366 JDWP::Set1(buf_, tag_);
2367 return false;
2368 }
Ian Rogers98379392014-02-24 16:53:16 -08002369 const ScopedObjectAccessUnchecked& soa_;
Ian Rogers0399dde2012-06-06 17:09:28 -07002370 const JDWP::FrameId frame_id_;
2371 const int slot_;
2372 JDWP::JdwpTag tag_;
2373 uint8_t* const buf_;
2374 const size_t width_;
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002375 JDWP::JdwpError error_;
Ian Rogers0399dde2012-06-06 17:09:28 -07002376 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002377
2378 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08002379 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002380 Thread* thread;
2381 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
2382 if (error != JDWP::ERR_NONE) {
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002383 return error;
Elliott Hughes221229c2013-01-08 18:17:50 -08002384 }
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002385 // TODO check thread is suspended by the debugger ?
Ian Rogers0399dde2012-06-06 17:09:28 -07002386 UniquePtr<Context> context(Context::Create());
Ian Rogers98379392014-02-24 16:53:16 -08002387 GetLocalVisitor visitor(soa, thread, context.get(), frame_id, slot, tag, buf, width);
Ian Rogers0399dde2012-06-06 17:09:28 -07002388 visitor.WalkStack();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002389 return visitor.error_;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002390}
2391
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002392JDWP::JdwpError Dbg::SetLocalValue(JDWP::ObjectId thread_id, JDWP::FrameId frame_id, int slot,
2393 JDWP::JdwpTag tag, uint64_t value, size_t width) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002394 struct SetLocalVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -08002395 SetLocalVisitor(Thread* thread, Context* context,
Ian Rogers0399dde2012-06-06 17:09:28 -07002396 JDWP::FrameId frame_id, int slot, JDWP::JdwpTag tag, uint64_t value,
Ian Rogersca190662012-06-26 15:45:57 -07002397 size_t width)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002398 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08002399 : StackVisitor(thread, context),
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002400 frame_id_(frame_id), slot_(slot), tag_(tag), value_(value), width_(width),
2401 error_(JDWP::ERR_NONE) {}
Ian Rogersca190662012-06-26 15:45:57 -07002402
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002403 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2404 // annotalysis.
2405 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07002406 if (GetFrameId() != frame_id_) {
2407 return true; // Not our frame, carry on.
2408 }
2409 // TODO: check that the tag is compatible with the actual type of the slot!
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002410 // TODO: check slot is valid for this method or return INVALID_SLOT error.
Brian Carlstromea46f952013-07-30 01:26:50 -07002411 mirror::ArtMethod* m = GetMethod();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002412 if (m->IsNative()) {
2413 // We can't read local value from native method.
2414 error_ = JDWP::ERR_OPAQUE_FRAME;
2415 return false;
2416 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002417 uint16_t reg = DemangleSlot(slot_, m);
2418
2419 switch (tag_) {
2420 case JDWP::JT_BOOLEAN:
2421 case JDWP::JT_BYTE:
2422 CHECK_EQ(width_, 1U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002423 SetVReg(m, reg, static_cast<uint32_t>(value_), kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002424 break;
2425 case JDWP::JT_SHORT:
2426 case JDWP::JT_CHAR:
2427 CHECK_EQ(width_, 2U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002428 SetVReg(m, reg, static_cast<uint32_t>(value_), kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002429 break;
2430 case JDWP::JT_INT:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002431 CHECK_EQ(width_, 4U);
2432 SetVReg(m, reg, static_cast<uint32_t>(value_), kIntVReg);
2433 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002434 case JDWP::JT_FLOAT:
2435 CHECK_EQ(width_, 4U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002436 SetVReg(m, reg, static_cast<uint32_t>(value_), kFloatVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002437 break;
2438 case JDWP::JT_ARRAY:
2439 case JDWP::JT_OBJECT:
2440 case JDWP::JT_STRING:
2441 {
2442 CHECK_EQ(width_, sizeof(JDWP::ObjectId));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002443 mirror::Object* o = gRegistry->Get<mirror::Object*>(static_cast<JDWP::ObjectId>(value_));
Elliott Hughes64f574f2013-02-20 14:57:12 -08002444 if (o == ObjectRegistry::kInvalidObject) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002445 UNIMPLEMENTED(FATAL) << "return an error code when given an invalid object to store";
2446 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002447 SetVReg(m, reg, static_cast<uint32_t>(reinterpret_cast<uintptr_t>(o)), kReferenceVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002448 }
2449 break;
2450 case JDWP::JT_DOUBLE:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002451 CHECK_EQ(width_, 8U);
2452 SetVReg(m, reg, static_cast<uint32_t>(value_), kDoubleLoVReg);
2453 SetVReg(m, reg + 1, static_cast<uint32_t>(value_ >> 32), kDoubleHiVReg);
2454 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002455 case JDWP::JT_LONG:
2456 CHECK_EQ(width_, 8U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002457 SetVReg(m, reg, static_cast<uint32_t>(value_), kLongLoVReg);
2458 SetVReg(m, reg + 1, static_cast<uint32_t>(value_ >> 32), kLongHiVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002459 break;
2460 default:
2461 LOG(FATAL) << "Unknown tag " << tag_;
2462 break;
2463 }
2464 return false;
2465 }
2466
2467 const JDWP::FrameId frame_id_;
2468 const int slot_;
2469 const JDWP::JdwpTag tag_;
2470 const uint64_t value_;
2471 const size_t width_;
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002472 JDWP::JdwpError error_;
Ian Rogers0399dde2012-06-06 17:09:28 -07002473 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002474
2475 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08002476 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002477 Thread* thread;
2478 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
2479 if (error != JDWP::ERR_NONE) {
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002480 return error;
Elliott Hughes221229c2013-01-08 18:17:50 -08002481 }
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002482 // TODO check thread is suspended by the debugger ?
Elliott Hughes08fc03a2012-06-26 17:34:00 -07002483 UniquePtr<Context> context(Context::Create());
Ian Rogers7a22fa62013-01-23 12:16:16 -08002484 SetLocalVisitor visitor(thread, context.get(), frame_id, slot, tag, value, width);
Ian Rogers0399dde2012-06-06 17:09:28 -07002485 visitor.WalkStack();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002486 return visitor.error_;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002487}
2488
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002489JDWP::ObjectId Dbg::GetThisObjectIdForEvent(mirror::Object* this_object) {
2490 // If 'this_object' isn't already in the registry, we know that we're not looking for it, so
2491 // there's no point adding it to the registry and burning through ids.
2492 // When registering an event request with an instance filter, we've been given an existing object
2493 // id so it must already be present in the registry when the event fires.
2494 JDWP::ObjectId this_id = 0;
2495 if (this_object != nullptr && gRegistry->Contains(this_object)) {
2496 this_id = gRegistry->Add(this_object);
2497 }
2498 return this_id;
2499}
2500
Ian Rogersef7d42f2014-01-06 12:55:46 -08002501void Dbg::PostLocationEvent(mirror::ArtMethod* m, int dex_pc, mirror::Object* this_object,
Jeff Hao579b0242013-11-18 13:16:49 -08002502 int event_flags, const JValue* return_value) {
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002503 if (!IsDebuggerActive()) {
2504 return;
2505 }
2506 DCHECK(m != nullptr);
2507 DCHECK_EQ(m->IsStatic(), this_object == nullptr);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002508 JDWP::JdwpLocation location;
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002509 SetLocation(location, m, dex_pc);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002510
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002511 // We need 'this' for InstanceOnly filters only.
2512 JDWP::ObjectId this_id = GetThisObjectIdForEvent(this_object);
Jeff Hao579b0242013-11-18 13:16:49 -08002513 gJdwpState->PostLocationEvent(&location, this_id, event_flags, return_value);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002514}
2515
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002516void Dbg::PostFieldAccessEvent(mirror::ArtMethod* m, int dex_pc,
2517 mirror::Object* this_object, mirror::ArtField* f) {
2518 if (!IsDebuggerActive()) {
2519 return;
2520 }
2521 DCHECK(m != nullptr);
2522 DCHECK(f != nullptr);
2523 JDWP::JdwpLocation location;
2524 SetLocation(location, m, dex_pc);
2525
2526 JDWP::RefTypeId type_id = gRegistry->AddRefType(f->GetDeclaringClass());
2527 JDWP::FieldId field_id = ToFieldId(f);
2528 JDWP::ObjectId this_id = gRegistry->Add(this_object);
2529
2530 gJdwpState->PostFieldEvent(&location, type_id, field_id, this_id, nullptr, false);
2531}
2532
2533void Dbg::PostFieldModificationEvent(mirror::ArtMethod* m, int dex_pc,
2534 mirror::Object* this_object, mirror::ArtField* f,
2535 const JValue* field_value) {
2536 if (!IsDebuggerActive()) {
2537 return;
2538 }
2539 DCHECK(m != nullptr);
2540 DCHECK(f != nullptr);
2541 DCHECK(field_value != nullptr);
2542 JDWP::JdwpLocation location;
2543 SetLocation(location, m, dex_pc);
2544
2545 JDWP::RefTypeId type_id = gRegistry->AddRefType(f->GetDeclaringClass());
2546 JDWP::FieldId field_id = ToFieldId(f);
2547 JDWP::ObjectId this_id = gRegistry->Add(this_object);
2548
2549 gJdwpState->PostFieldEvent(&location, type_id, field_id, this_id, field_value, true);
2550}
2551
2552void Dbg::PostException(const ThrowLocation& throw_location,
Brian Carlstromea46f952013-07-30 01:26:50 -07002553 mirror::ArtMethod* catch_method,
Elliott Hughes64f574f2013-02-20 14:57:12 -08002554 uint32_t catch_dex_pc, mirror::Throwable* exception_object) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002555 if (!IsDebuggerActive()) {
Ian Rogers0ad5bb82011-12-07 10:16:32 -08002556 return;
2557 }
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002558
Ian Rogers62d6c772013-02-27 08:32:07 -08002559 JDWP::JdwpLocation jdwp_throw_location;
2560 SetLocation(jdwp_throw_location, throw_location.GetMethod(), throw_location.GetDexPc());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002561 JDWP::JdwpLocation catch_location;
Elliott Hughescaf76542012-06-28 16:08:22 -07002562 SetLocation(catch_location, catch_method, catch_dex_pc);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002563
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002564 // We need 'this' for InstanceOnly filters only.
2565 JDWP::ObjectId this_id = GetThisObjectIdForEvent(throw_location.GetThis());
Elliott Hughes64f574f2013-02-20 14:57:12 -08002566 JDWP::ObjectId exception_id = gRegistry->Add(exception_object);
2567 JDWP::RefTypeId exception_class_id = gRegistry->AddRefType(exception_object->GetClass());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002568
Ian Rogers62d6c772013-02-27 08:32:07 -08002569 gJdwpState->PostException(&jdwp_throw_location, exception_id, exception_class_id, &catch_location,
2570 this_id);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002571}
2572
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002573void Dbg::PostClassPrepare(mirror::Class* c) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002574 if (!IsDebuggerActive()) {
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002575 return;
2576 }
2577
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08002578 // OLD-TODO - we currently always send both "verified" and "prepared" since
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002579 // debuggers seem to like that. There might be some advantage to honesty,
2580 // since the class may not yet be verified.
2581 int state = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
Sebastien Hertz4d8fd492014-03-28 16:29:41 +01002582 JDWP::JdwpTypeTag tag = GetTypeTag(c);
Ian Rogersfc0e94b2013-09-23 23:51:32 -07002583 gJdwpState->PostClassPrepare(tag, gRegistry->Add(c),
Ian Rogersdfb325e2013-10-30 01:00:44 -07002584 ClassHelper(c).GetDescriptor(), state);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002585}
2586
Ian Rogers62d6c772013-02-27 08:32:07 -08002587void Dbg::UpdateDebugger(Thread* thread, mirror::Object* this_object,
Ian Rogersef7d42f2014-01-06 12:55:46 -08002588 mirror::ArtMethod* m, uint32_t dex_pc) {
Ian Rogers62d6c772013-02-27 08:32:07 -08002589 if (!IsDebuggerActive() || dex_pc == static_cast<uint32_t>(-2) /* fake method exit */) {
Elliott Hughes2aa2e392012-02-17 17:15:43 -08002590 return;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002591 }
2592
Elliott Hughes2aa2e392012-02-17 17:15:43 -08002593 int event_flags = 0;
2594
Elliott Hughes86964332012-02-15 19:37:42 -08002595 if (IsBreakpoint(m, dex_pc)) {
2596 event_flags |= kBreakpoint;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002597 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002598
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002599 // If the debugger is single-stepping one of our threads, check to
2600 // see if we're that thread and we've reached a step point.
2601 const SingleStepControl* single_step_control = thread->GetSingleStepControl();
2602 DCHECK(single_step_control != nullptr);
2603 if (single_step_control->is_active) {
2604 CHECK(!m->IsNative());
2605 if (single_step_control->step_depth == JDWP::SD_INTO) {
2606 // Step into method calls. We break when the line number
2607 // or method pointer changes. If we're in SS_MIN mode, we
2608 // always stop.
2609 if (single_step_control->method != m) {
2610 event_flags |= kSingleStep;
2611 VLOG(jdwp) << "SS new method";
2612 } else if (single_step_control->step_size == JDWP::SS_MIN) {
2613 event_flags |= kSingleStep;
2614 VLOG(jdwp) << "SS new instruction";
Sebastien Hertzbb43b432014-04-14 11:59:08 +02002615 } else if (single_step_control->ContainsDexPc(dex_pc)) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002616 event_flags |= kSingleStep;
2617 VLOG(jdwp) << "SS new line";
2618 }
2619 } else if (single_step_control->step_depth == JDWP::SD_OVER) {
2620 // Step over method calls. We break when the line number is
2621 // different and the frame depth is <= the original frame
2622 // depth. (We can't just compare on the method, because we
2623 // might get unrolled past it by an exception, and it's tricky
2624 // to identify recursion.)
2625
2626 int stack_depth = GetStackDepth(thread);
2627
2628 if (stack_depth < single_step_control->stack_depth) {
2629 // Popped up one or more frames, always trigger.
2630 event_flags |= kSingleStep;
2631 VLOG(jdwp) << "SS method pop";
2632 } else if (stack_depth == single_step_control->stack_depth) {
2633 // Same depth, see if we moved.
2634 if (single_step_control->step_size == JDWP::SS_MIN) {
Elliott Hughes86964332012-02-15 19:37:42 -08002635 event_flags |= kSingleStep;
2636 VLOG(jdwp) << "SS new instruction";
Sebastien Hertzbb43b432014-04-14 11:59:08 +02002637 } else if (single_step_control->ContainsDexPc(dex_pc)) {
Elliott Hughes2435a572012-02-17 16:07:41 -08002638 event_flags |= kSingleStep;
2639 VLOG(jdwp) << "SS new line";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002640 }
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002641 }
2642 } else {
2643 CHECK_EQ(single_step_control->step_depth, JDWP::SD_OUT);
2644 // Return from the current method. We break when the frame
2645 // depth pops up.
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002646
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002647 // This differs from the "method exit" break in that it stops
2648 // with the PC at the next instruction in the returned-to
2649 // function, rather than the end of the returning function.
Elliott Hughes86964332012-02-15 19:37:42 -08002650
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002651 int stack_depth = GetStackDepth(thread);
2652 if (stack_depth < single_step_control->stack_depth) {
2653 event_flags |= kSingleStep;
2654 VLOG(jdwp) << "SS method pop";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002655 }
2656 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002657 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002658
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002659 // If there's something interesting going on, see if it matches one
2660 // of the debugger filters.
2661 if (event_flags != 0) {
Jeff Hao579b0242013-11-18 13:16:49 -08002662 Dbg::PostLocationEvent(m, dex_pc, this_object, event_flags, nullptr);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002663 }
2664}
2665
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002666// Process request while all mutator threads are suspended.
2667void Dbg::ProcessDeoptimizationRequest(const DeoptimizationRequest& request) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002668 instrumentation::Instrumentation* instrumentation = Runtime::Current()->GetInstrumentation();
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002669 switch (request.kind) {
2670 case DeoptimizationRequest::kNothing:
2671 LOG(WARNING) << "Ignoring empty deoptimization request.";
2672 break;
2673 case DeoptimizationRequest::kFullDeoptimization:
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01002674 VLOG(jdwp) << "Deoptimize the world ...";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002675 instrumentation->DeoptimizeEverything();
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01002676 VLOG(jdwp) << "Deoptimize the world DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002677 break;
2678 case DeoptimizationRequest::kFullUndeoptimization:
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01002679 VLOG(jdwp) << "Undeoptimize the world ...";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002680 instrumentation->UndeoptimizeEverything();
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01002681 VLOG(jdwp) << "Undeoptimize the world DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002682 break;
2683 case DeoptimizationRequest::kSelectiveDeoptimization:
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01002684 VLOG(jdwp) << "Deoptimize method " << PrettyMethod(request.method) << " ...";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002685 instrumentation->Deoptimize(request.method);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01002686 VLOG(jdwp) << "Deoptimize method " << PrettyMethod(request.method) << " DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002687 break;
2688 case DeoptimizationRequest::kSelectiveUndeoptimization:
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01002689 VLOG(jdwp) << "Undeoptimize method " << PrettyMethod(request.method) << " ...";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002690 instrumentation->Undeoptimize(request.method);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01002691 VLOG(jdwp) << "Undeoptimize method " << PrettyMethod(request.method) << " DONE";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002692 break;
2693 default:
2694 LOG(FATAL) << "Unsupported deoptimization request kind " << request.kind;
2695 break;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002696 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002697}
2698
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01002699void Dbg::DelayFullUndeoptimization() {
2700 MutexLock mu(Thread::Current(), *deoptimization_lock_);
2701 ++delayed_full_undeoptimization_count_;
2702 DCHECK_LE(delayed_full_undeoptimization_count_, full_deoptimization_event_count_);
2703}
2704
2705void Dbg::ProcessDelayedFullUndeoptimizations() {
2706 // TODO: avoid taking the lock twice (once here and once in ManageDeoptimization).
2707 {
2708 MutexLock mu(Thread::Current(), *deoptimization_lock_);
2709 while (delayed_full_undeoptimization_count_ > 0) {
2710 DeoptimizationRequest req;
2711 req.kind = DeoptimizationRequest::kFullUndeoptimization;
2712 req.method = nullptr;
2713 RequestDeoptimizationLocked(req);
2714 --delayed_full_undeoptimization_count_;
2715 }
2716 }
2717 ManageDeoptimization();
2718}
2719
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002720void Dbg::RequestDeoptimization(const DeoptimizationRequest& req) {
2721 if (req.kind == DeoptimizationRequest::kNothing) {
2722 // Nothing to do.
2723 return;
2724 }
2725 MutexLock mu(Thread::Current(), *deoptimization_lock_);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01002726 RequestDeoptimizationLocked(req);
2727}
2728
2729void Dbg::RequestDeoptimizationLocked(const DeoptimizationRequest& req) {
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002730 switch (req.kind) {
2731 case DeoptimizationRequest::kFullDeoptimization: {
2732 DCHECK(req.method == nullptr);
2733 if (full_deoptimization_event_count_ == 0) {
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01002734 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
2735 << " for full deoptimization";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002736 deoptimization_requests_.push_back(req);
2737 }
2738 ++full_deoptimization_event_count_;
2739 break;
2740 }
2741 case DeoptimizationRequest::kFullUndeoptimization: {
2742 DCHECK(req.method == nullptr);
2743 DCHECK_GT(full_deoptimization_event_count_, 0U);
2744 --full_deoptimization_event_count_;
2745 if (full_deoptimization_event_count_ == 0) {
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01002746 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
2747 << " for full undeoptimization";
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002748 deoptimization_requests_.push_back(req);
2749 }
2750 break;
2751 }
2752 case DeoptimizationRequest::kSelectiveDeoptimization: {
2753 DCHECK(req.method != nullptr);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01002754 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
2755 << " for deoptimization of " << PrettyMethod(req.method);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002756 deoptimization_requests_.push_back(req);
2757 break;
2758 }
2759 case DeoptimizationRequest::kSelectiveUndeoptimization: {
2760 DCHECK(req.method != nullptr);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01002761 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size()
2762 << " for undeoptimization of " << PrettyMethod(req.method);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002763 deoptimization_requests_.push_back(req);
2764 break;
2765 }
2766 default: {
2767 LOG(FATAL) << "Unknown deoptimization request kind " << req.kind;
2768 break;
2769 }
2770 }
2771}
2772
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002773void Dbg::ManageDeoptimization() {
2774 Thread* const self = Thread::Current();
2775 {
2776 // Avoid suspend/resume if there is no pending request.
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002777 MutexLock mu(self, *deoptimization_lock_);
2778 if (deoptimization_requests_.empty()) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002779 return;
2780 }
2781 }
2782 CHECK_EQ(self->GetState(), kRunnable);
2783 self->TransitionFromRunnableToSuspended(kWaitingForDeoptimization);
2784 // We need to suspend mutator threads first.
2785 Runtime* const runtime = Runtime::Current();
2786 runtime->GetThreadList()->SuspendAll();
2787 const ThreadState old_state = self->SetStateUnsafe(kRunnable);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002788 {
2789 MutexLock mu(self, *deoptimization_lock_);
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01002790 size_t req_index = 0;
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002791 for (const DeoptimizationRequest& request : deoptimization_requests_) {
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01002792 VLOG(jdwp) << "Process deoptimization request #" << req_index++;
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002793 ProcessDeoptimizationRequest(request);
2794 }
2795 deoptimization_requests_.clear();
2796 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002797 CHECK_EQ(self->SetStateUnsafe(old_state), kRunnable);
2798 runtime->GetThreadList()->ResumeAll();
2799 self->TransitionFromSuspendedToRunnable();
2800}
2801
Sebastien Hertza76a6d42014-03-20 16:40:17 +01002802static bool IsMethodPossiblyInlined(Thread* self, mirror::ArtMethod* m)
2803 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2804 MethodHelper mh(m);
2805 const DexFile::CodeItem* code_item = mh.GetCodeItem();
2806 if (code_item == nullptr) {
2807 // TODO We should not be asked to watch location in a native or abstract method so the code item
2808 // should never be null. We could just check we never encounter this case.
2809 return false;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002810 }
Sebastien Hertza76a6d42014-03-20 16:40:17 +01002811 SirtRef<mirror::DexCache> dex_cache(self, mh.GetDexCache());
2812 SirtRef<mirror::ClassLoader> class_loader(self, mh.GetClassLoader());
2813 verifier::MethodVerifier verifier(&mh.GetDexFile(), &dex_cache, &class_loader,
2814 &mh.GetClassDef(), code_item, m->GetDexMethodIndex(), m,
2815 m->GetAccessFlags(), false, true);
2816 // Note: we don't need to verify the method.
2817 return InlineMethodAnalyser::AnalyseMethodCode(&verifier, nullptr);
2818}
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002819
Sebastien Hertza76a6d42014-03-20 16:40:17 +01002820static const Breakpoint* FindFirstBreakpointForMethod(mirror::ArtMethod* m)
2821 EXCLUSIVE_LOCKS_REQUIRED(Locks::breakpoint_lock_) {
2822 for (const Breakpoint& breakpoint : gBreakpoints) {
2823 if (breakpoint.method == m) {
2824 return &breakpoint;
2825 }
2826 }
2827 return nullptr;
2828}
2829
2830// Sanity checks all existing breakpoints on the same method.
2831static void SanityCheckExistingBreakpoints(mirror::ArtMethod* m, bool need_full_deoptimization)
2832 EXCLUSIVE_LOCKS_REQUIRED(Locks::breakpoint_lock_) {
2833 if (kIsDebugBuild) {
2834 for (const Breakpoint& breakpoint : gBreakpoints) {
2835 CHECK_EQ(need_full_deoptimization, breakpoint.need_full_deoptimization);
2836 }
2837 if (need_full_deoptimization) {
2838 // We should have deoptimized everything but not "selectively" deoptimized this method.
2839 CHECK(Runtime::Current()->GetInstrumentation()->AreAllMethodsDeoptimized());
2840 CHECK(!Runtime::Current()->GetInstrumentation()->IsDeoptimized(m));
2841 } else {
2842 // We should have "selectively" deoptimized this method.
2843 // Note: while we have not deoptimized everything for this method, we may have done it for
2844 // another event.
2845 CHECK(Runtime::Current()->GetInstrumentation()->IsDeoptimized(m));
2846 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002847 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002848}
2849
Sebastien Hertza76a6d42014-03-20 16:40:17 +01002850// Installs a breakpoint at the specified location. Also indicates through the deoptimization
2851// request if we need to deoptimize.
2852void Dbg::WatchLocation(const JDWP::JdwpLocation* location, DeoptimizationRequest* req) {
2853 Thread* const self = Thread::Current();
Brian Carlstromea46f952013-07-30 01:26:50 -07002854 mirror::ArtMethod* m = FromMethodId(location->method_id);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01002855 DCHECK(m != nullptr) << "No method for method id " << location->method_id;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002856
Sebastien Hertza76a6d42014-03-20 16:40:17 +01002857 MutexLock mu(self, *Locks::breakpoint_lock_);
2858 const Breakpoint* const existing_breakpoint = FindFirstBreakpointForMethod(m);
2859 bool need_full_deoptimization;
2860 if (existing_breakpoint == nullptr) {
2861 // There is no breakpoint on this method yet: we need to deoptimize. If this method may be
2862 // inlined, we deoptimize everything; otherwise we deoptimize only this method.
2863 need_full_deoptimization = IsMethodPossiblyInlined(self, m);
2864 if (need_full_deoptimization) {
2865 req->kind = DeoptimizationRequest::kFullDeoptimization;
2866 req->method = nullptr;
2867 } else {
2868 req->kind = DeoptimizationRequest::kSelectiveDeoptimization;
2869 req->method = m;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002870 }
Sebastien Hertza76a6d42014-03-20 16:40:17 +01002871 } else {
2872 // There is at least one breakpoint for this method: we don't need to deoptimize.
2873 req->kind = DeoptimizationRequest::kNothing;
2874 req->method = nullptr;
2875
2876 need_full_deoptimization = existing_breakpoint->need_full_deoptimization;
2877 SanityCheckExistingBreakpoints(m, need_full_deoptimization);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002878 }
2879
Sebastien Hertza76a6d42014-03-20 16:40:17 +01002880 gBreakpoints.push_back(Breakpoint(m, location->dex_pc, need_full_deoptimization));
2881 VLOG(jdwp) << "Set breakpoint #" << (gBreakpoints.size() - 1) << ": "
2882 << gBreakpoints[gBreakpoints.size() - 1];
2883}
2884
2885// Uninstalls a breakpoint at the specified location. Also indicates through the deoptimization
2886// request if we need to undeoptimize.
2887void Dbg::UnwatchLocation(const JDWP::JdwpLocation* location, DeoptimizationRequest* req) {
2888 mirror::ArtMethod* m = FromMethodId(location->method_id);
2889 DCHECK(m != nullptr) << "No method for method id " << location->method_id;
2890
2891 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
2892 bool need_full_deoptimization = false;
2893 for (size_t i = 0, e = gBreakpoints.size(); i < e; ++i) {
2894 if (gBreakpoints[i].method == m && gBreakpoints[i].dex_pc == location->dex_pc) {
2895 VLOG(jdwp) << "Removed breakpoint #" << i << ": " << gBreakpoints[i];
2896 need_full_deoptimization = gBreakpoints[i].need_full_deoptimization;
2897 DCHECK_NE(need_full_deoptimization, Runtime::Current()->GetInstrumentation()->IsDeoptimized(m));
2898 gBreakpoints.erase(gBreakpoints.begin() + i);
2899 break;
2900 }
2901 }
2902 const Breakpoint* const existing_breakpoint = FindFirstBreakpointForMethod(m);
2903 if (existing_breakpoint == nullptr) {
2904 // There is no more breakpoint on this method: we need to undeoptimize.
2905 if (need_full_deoptimization) {
2906 // This method required full deoptimization: we need to undeoptimize everything.
2907 req->kind = DeoptimizationRequest::kFullUndeoptimization;
2908 req->method = nullptr;
2909 } else {
2910 // This method required selective deoptimization: we need to undeoptimize only that method.
2911 req->kind = DeoptimizationRequest::kSelectiveUndeoptimization;
2912 req->method = m;
2913 }
2914 } else {
2915 // There is at least one breakpoint for this method: we don't need to undeoptimize.
2916 req->kind = DeoptimizationRequest::kNothing;
2917 req->method = nullptr;
2918 SanityCheckExistingBreakpoints(m, need_full_deoptimization);
Elliott Hughes86964332012-02-15 19:37:42 -08002919 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002920}
2921
Jeff Hao449db332013-04-12 18:30:52 -07002922// Scoped utility class to suspend a thread so that we may do tasks such as walk its stack. Doesn't
2923// cause suspension if the thread is the current thread.
2924class ScopedThreadSuspension {
2925 public:
Ian Rogers33e95662013-05-20 20:29:14 -07002926 ScopedThreadSuspension(Thread* self, JDWP::ObjectId thread_id)
Sebastien Hertz52d131d2014-03-13 16:17:40 +01002927 LOCKS_EXCLUDED(Locks::thread_list_lock_)
Ian Rogers33e95662013-05-20 20:29:14 -07002928 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) :
Jeff Hao449db332013-04-12 18:30:52 -07002929 thread_(NULL),
2930 error_(JDWP::ERR_NONE),
2931 self_suspend_(false),
Ian Rogers33e95662013-05-20 20:29:14 -07002932 other_suspend_(false) {
Jeff Hao449db332013-04-12 18:30:52 -07002933 ScopedObjectAccessUnchecked soa(self);
2934 {
2935 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
2936 error_ = DecodeThread(soa, thread_id, thread_);
2937 }
2938 if (error_ == JDWP::ERR_NONE) {
2939 if (thread_ == soa.Self()) {
2940 self_suspend_ = true;
2941 } else {
2942 soa.Self()->TransitionFromRunnableToSuspended(kWaitingForDebuggerSuspension);
2943 jobject thread_peer = gRegistry->GetJObject(thread_id);
2944 bool timed_out;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07002945 Thread* suspended_thread = ThreadList::SuspendThreadByPeer(thread_peer, true, true,
2946 &timed_out);
Jeff Hao449db332013-04-12 18:30:52 -07002947 CHECK_EQ(soa.Self()->TransitionFromSuspendedToRunnable(), kWaitingForDebuggerSuspension);
2948 if (suspended_thread == NULL) {
2949 // Thread terminated from under us while suspending.
2950 error_ = JDWP::ERR_INVALID_THREAD;
2951 } else {
2952 CHECK_EQ(suspended_thread, thread_);
2953 other_suspend_ = true;
2954 }
2955 }
2956 }
Elliott Hughes2435a572012-02-17 16:07:41 -08002957 }
Elliott Hughes86964332012-02-15 19:37:42 -08002958
Jeff Hao449db332013-04-12 18:30:52 -07002959 Thread* GetThread() const {
2960 return thread_;
2961 }
2962
2963 JDWP::JdwpError GetError() const {
2964 return error_;
2965 }
2966
2967 ~ScopedThreadSuspension() {
2968 if (other_suspend_) {
2969 Runtime::Current()->GetThreadList()->Resume(thread_, true);
2970 }
2971 }
2972
2973 private:
2974 Thread* thread_;
2975 JDWP::JdwpError error_;
2976 bool self_suspend_;
2977 bool other_suspend_;
2978};
2979
2980JDWP::JdwpError Dbg::ConfigureStep(JDWP::ObjectId thread_id, JDWP::JdwpStepSize step_size,
2981 JDWP::JdwpStepDepth step_depth) {
2982 Thread* self = Thread::Current();
2983 ScopedThreadSuspension sts(self, thread_id);
2984 if (sts.GetError() != JDWP::ERR_NONE) {
2985 return sts.GetError();
2986 }
2987
Elliott Hughes2435a572012-02-17 16:07:41 -08002988 //
2989 // Work out what Method* we're in, the current line number, and how deep the stack currently
2990 // is for step-out.
2991 //
2992
Ian Rogers0399dde2012-06-06 17:09:28 -07002993 struct SingleStepStackVisitor : public StackVisitor {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002994 explicit SingleStepStackVisitor(Thread* thread, SingleStepControl* single_step_control,
2995 int32_t* line_number)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002996 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002997 : StackVisitor(thread, NULL), single_step_control_(single_step_control),
2998 line_number_(line_number) {
2999 DCHECK_EQ(single_step_control_, thread->GetSingleStepControl());
3000 single_step_control_->method = NULL;
3001 single_step_control_->stack_depth = 0;
Elliott Hughes86964332012-02-15 19:37:42 -08003002 }
Ian Rogersca190662012-06-26 15:45:57 -07003003
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003004 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
3005 // annotalysis.
3006 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003007 mirror::ArtMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07003008 if (!m->IsRuntimeMethod()) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003009 ++single_step_control_->stack_depth;
3010 if (single_step_control_->method == NULL) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08003011 mirror::DexCache* dex_cache = m->GetDeclaringClass()->GetDexCache();
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003012 single_step_control_->method = m;
3013 *line_number_ = -1;
Elliott Hughes2435a572012-02-17 16:07:41 -08003014 if (dex_cache != NULL) {
Ian Rogers4445a7e2012-10-05 17:19:13 -07003015 const DexFile& dex_file = *dex_cache->GetDexFile();
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003016 *line_number_ = dex_file.GetLineNumFromPC(m, GetDexPc());
Elliott Hughes2435a572012-02-17 16:07:41 -08003017 }
Elliott Hughes86964332012-02-15 19:37:42 -08003018 }
3019 }
Elliott Hughes530fa002012-03-12 11:44:49 -07003020 return true;
Elliott Hughes86964332012-02-15 19:37:42 -08003021 }
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003022
3023 SingleStepControl* const single_step_control_;
3024 int32_t* const line_number_;
Elliott Hughes86964332012-02-15 19:37:42 -08003025 };
Jeff Hao449db332013-04-12 18:30:52 -07003026
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003027 Thread* const thread = sts.GetThread();
3028 SingleStepControl* const single_step_control = thread->GetSingleStepControl();
3029 DCHECK(single_step_control != nullptr);
3030 int32_t line_number = -1;
3031 SingleStepStackVisitor visitor(thread, single_step_control, &line_number);
Ian Rogers0399dde2012-06-06 17:09:28 -07003032 visitor.WalkStack();
Elliott Hughes86964332012-02-15 19:37:42 -08003033
Elliott Hughes2435a572012-02-17 16:07:41 -08003034 //
3035 // Find the dex_pc values that correspond to the current line, for line-based single-stepping.
3036 //
3037
3038 struct DebugCallbackContext {
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003039 explicit DebugCallbackContext(SingleStepControl* single_step_control, int32_t line_number,
3040 const DexFile::CodeItem* code_item)
3041 : single_step_control_(single_step_control), line_number_(line_number), code_item_(code_item),
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003042 last_pc_valid(false), last_pc(0) {
Elliott Hughes2435a572012-02-17 16:07:41 -08003043 }
3044
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003045 static bool Callback(void* raw_context, uint32_t address, uint32_t line_number) {
Elliott Hughes2435a572012-02-17 16:07:41 -08003046 DebugCallbackContext* context = reinterpret_cast<DebugCallbackContext*>(raw_context);
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003047 if (static_cast<int32_t>(line_number) == context->line_number_) {
Elliott Hughes2435a572012-02-17 16:07:41 -08003048 if (!context->last_pc_valid) {
3049 // Everything from this address until the next line change is ours.
3050 context->last_pc = address;
3051 context->last_pc_valid = true;
3052 }
3053 // Otherwise, if we're already in a valid range for this line,
3054 // just keep going (shouldn't really happen)...
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003055 } else if (context->last_pc_valid) { // and the line number is new
Elliott Hughes2435a572012-02-17 16:07:41 -08003056 // Add everything from the last entry up until here to the set
3057 for (uint32_t dex_pc = context->last_pc; dex_pc < address; ++dex_pc) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003058 context->single_step_control_->dex_pcs.insert(dex_pc);
Elliott Hughes2435a572012-02-17 16:07:41 -08003059 }
3060 context->last_pc_valid = false;
3061 }
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003062 return false; // There may be multiple entries for any given line.
Elliott Hughes2435a572012-02-17 16:07:41 -08003063 }
3064
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003065 ~DebugCallbackContext() {
Elliott Hughes2435a572012-02-17 16:07:41 -08003066 // If the line number was the last in the position table...
3067 if (last_pc_valid) {
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003068 size_t end = code_item_->insns_size_in_code_units_;
Elliott Hughes2435a572012-02-17 16:07:41 -08003069 for (uint32_t dex_pc = last_pc; dex_pc < end; ++dex_pc) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003070 single_step_control_->dex_pcs.insert(dex_pc);
Elliott Hughes2435a572012-02-17 16:07:41 -08003071 }
3072 }
3073 }
3074
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003075 SingleStepControl* const single_step_control_;
3076 const int32_t line_number_;
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003077 const DexFile::CodeItem* const code_item_;
Elliott Hughes2435a572012-02-17 16:07:41 -08003078 bool last_pc_valid;
3079 uint32_t last_pc;
3080 };
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003081 single_step_control->dex_pcs.clear();
Ian Rogersef7d42f2014-01-06 12:55:46 -08003082 mirror::ArtMethod* m = single_step_control->method;
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003083 if (!m->IsNative()) {
Elliott Hughes3e2e1a22012-02-21 11:33:41 -08003084 MethodHelper mh(m);
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003085 const DexFile::CodeItem* const code_item = mh.GetCodeItem();
3086 DebugCallbackContext context(single_step_control, line_number, code_item);
3087 mh.GetDexFile().DecodeDebugInfo(code_item, m->IsStatic(), m->GetDexMethodIndex(),
Elliott Hughes3e2e1a22012-02-21 11:33:41 -08003088 DebugCallbackContext::Callback, NULL, &context);
3089 }
Elliott Hughes2435a572012-02-17 16:07:41 -08003090
3091 //
3092 // Everything else...
3093 //
3094
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003095 single_step_control->step_size = step_size;
3096 single_step_control->step_depth = step_depth;
3097 single_step_control->is_active = true;
Elliott Hughes86964332012-02-15 19:37:42 -08003098
Elliott Hughes2435a572012-02-17 16:07:41 -08003099 if (VLOG_IS_ON(jdwp)) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003100 VLOG(jdwp) << "Single-step thread: " << *thread;
3101 VLOG(jdwp) << "Single-step step size: " << single_step_control->step_size;
3102 VLOG(jdwp) << "Single-step step depth: " << single_step_control->step_depth;
3103 VLOG(jdwp) << "Single-step current method: " << PrettyMethod(single_step_control->method);
3104 VLOG(jdwp) << "Single-step current line: " << line_number;
3105 VLOG(jdwp) << "Single-step current stack depth: " << single_step_control->stack_depth;
Elliott Hughes2435a572012-02-17 16:07:41 -08003106 VLOG(jdwp) << "Single-step dex_pc values:";
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003107 for (uint32_t dex_pc : single_step_control->dex_pcs) {
3108 VLOG(jdwp) << StringPrintf(" %#x", dex_pc);
Elliott Hughes2435a572012-02-17 16:07:41 -08003109 }
3110 }
3111
3112 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003113}
3114
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003115void Dbg::UnconfigureStep(JDWP::ObjectId thread_id) {
3116 ScopedObjectAccessUnchecked soa(Thread::Current());
3117 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
3118 Thread* thread;
3119 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
Sebastien Hertz87118ed2013-11-26 17:57:18 +01003120 if (error == JDWP::ERR_NONE) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003121 SingleStepControl* single_step_control = thread->GetSingleStepControl();
3122 DCHECK(single_step_control != nullptr);
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003123 single_step_control->Clear();
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003124 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003125}
3126
Elliott Hughes45651fd2012-02-21 15:48:20 -08003127static char JdwpTagToShortyChar(JDWP::JdwpTag tag) {
3128 switch (tag) {
3129 default:
3130 LOG(FATAL) << "unknown JDWP tag: " << PrintableChar(tag);
3131
3132 // Primitives.
3133 case JDWP::JT_BYTE: return 'B';
3134 case JDWP::JT_CHAR: return 'C';
3135 case JDWP::JT_FLOAT: return 'F';
3136 case JDWP::JT_DOUBLE: return 'D';
3137 case JDWP::JT_INT: return 'I';
3138 case JDWP::JT_LONG: return 'J';
3139 case JDWP::JT_SHORT: return 'S';
3140 case JDWP::JT_VOID: return 'V';
3141 case JDWP::JT_BOOLEAN: return 'Z';
3142
3143 // Reference types.
3144 case JDWP::JT_ARRAY:
3145 case JDWP::JT_OBJECT:
3146 case JDWP::JT_STRING:
3147 case JDWP::JT_THREAD:
3148 case JDWP::JT_THREAD_GROUP:
3149 case JDWP::JT_CLASS_LOADER:
3150 case JDWP::JT_CLASS_OBJECT:
3151 return 'L';
3152 }
3153}
3154
Elliott Hughes88d63092013-01-09 09:55:54 -08003155JDWP::JdwpError Dbg::InvokeMethod(JDWP::ObjectId thread_id, JDWP::ObjectId object_id,
3156 JDWP::RefTypeId class_id, JDWP::MethodId method_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003157 uint32_t arg_count, uint64_t* arg_values,
3158 JDWP::JdwpTag* arg_types, uint32_t options,
3159 JDWP::JdwpTag* pResultTag, uint64_t* pResultValue,
3160 JDWP::ObjectId* pExceptionId) {
Elliott Hughesd07986f2011-12-06 18:27:45 -08003161 ThreadList* thread_list = Runtime::Current()->GetThreadList();
3162
3163 Thread* targetThread = NULL;
3164 DebugInvokeReq* req = NULL;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003165 Thread* self = Thread::Current();
Elliott Hughesd07986f2011-12-06 18:27:45 -08003166 {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003167 ScopedObjectAccessUnchecked soa(self);
Ian Rogers50b35e22012-10-04 10:09:15 -07003168 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08003169 JDWP::JdwpError error = DecodeThread(soa, thread_id, targetThread);
3170 if (error != JDWP::ERR_NONE) {
3171 LOG(ERROR) << "InvokeMethod request for invalid thread id " << thread_id;
3172 return error;
Elliott Hughesd07986f2011-12-06 18:27:45 -08003173 }
3174 req = targetThread->GetInvokeReq();
3175 if (!req->ready) {
3176 LOG(ERROR) << "InvokeMethod request for thread not stopped by event: " << *targetThread;
3177 return JDWP::ERR_INVALID_THREAD;
3178 }
3179
3180 /*
3181 * We currently have a bug where we don't successfully resume the
3182 * target thread if the suspend count is too deep. We're expected to
3183 * require one "resume" for each "suspend", but when asked to execute
3184 * a method we have to resume fully and then re-suspend it back to the
3185 * same level. (The easiest way to cause this is to type "suspend"
3186 * multiple times in jdb.)
3187 *
3188 * It's unclear what this means when the event specifies "resume all"
3189 * and some threads are suspended more deeply than others. This is
3190 * a rare problem, so for now we just prevent it from hanging forever
3191 * by rejecting the method invocation request. Without this, we will
3192 * be stuck waiting on a suspended thread.
3193 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003194 int suspend_count;
3195 {
Ian Rogers50b35e22012-10-04 10:09:15 -07003196 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003197 suspend_count = targetThread->GetSuspendCount();
3198 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08003199 if (suspend_count > 1) {
3200 LOG(ERROR) << *targetThread << " suspend count too deep for method invocation: " << suspend_count;
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003201 return JDWP::ERR_THREAD_SUSPENDED; // Probably not expected here.
Elliott Hughesd07986f2011-12-06 18:27:45 -08003202 }
3203
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08003204 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003205 mirror::Object* receiver = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08003206 if (receiver == ObjectRegistry::kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08003207 return JDWP::ERR_INVALID_OBJECT;
3208 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003209
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003210 mirror::Object* thread = gRegistry->Get<mirror::Object*>(thread_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08003211 if (thread == ObjectRegistry::kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08003212 return JDWP::ERR_INVALID_OBJECT;
3213 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003214 // TODO: check that 'thread' is actually a java.lang.Thread!
3215
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003216 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes45651fd2012-02-21 15:48:20 -08003217 if (c == NULL) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08003218 return status;
3219 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003220
Brian Carlstromea46f952013-07-30 01:26:50 -07003221 mirror::ArtMethod* m = FromMethodId(method_id);
Elliott Hughes45651fd2012-02-21 15:48:20 -08003222 if (m->IsStatic() != (receiver == NULL)) {
3223 return JDWP::ERR_INVALID_METHODID;
3224 }
3225 if (m->IsStatic()) {
3226 if (m->GetDeclaringClass() != c) {
3227 return JDWP::ERR_INVALID_METHODID;
3228 }
3229 } else {
3230 if (!m->GetDeclaringClass()->IsAssignableFrom(c)) {
3231 return JDWP::ERR_INVALID_METHODID;
3232 }
3233 }
3234
3235 // Check the argument list matches the method.
3236 MethodHelper mh(m);
3237 if (mh.GetShortyLength() - 1 != arg_count) {
3238 return JDWP::ERR_ILLEGAL_ARGUMENT;
3239 }
3240 const char* shorty = mh.GetShorty();
Elliott Hughes09201632013-04-15 15:50:07 -07003241 const DexFile::TypeList* types = mh.GetParameterTypeList();
Elliott Hughes45651fd2012-02-21 15:48:20 -08003242 for (size_t i = 0; i < arg_count; ++i) {
3243 if (shorty[i + 1] != JdwpTagToShortyChar(arg_types[i])) {
3244 return JDWP::ERR_ILLEGAL_ARGUMENT;
3245 }
Elliott Hughes09201632013-04-15 15:50:07 -07003246
3247 if (shorty[i + 1] == 'L') {
3248 // Did we really get an argument of an appropriate reference type?
3249 mirror::Class* parameter_type = mh.GetClassFromTypeIdx(types->GetTypeItem(i).type_idx_);
3250 mirror::Object* argument = gRegistry->Get<mirror::Object*>(arg_values[i]);
3251 if (argument == ObjectRegistry::kInvalidObject) {
3252 return JDWP::ERR_INVALID_OBJECT;
3253 }
Sebastien Hertz0630ab52013-11-28 18:53:35 +01003254 if (argument != NULL && !argument->InstanceOf(parameter_type)) {
Elliott Hughes09201632013-04-15 15:50:07 -07003255 return JDWP::ERR_ILLEGAL_ARGUMENT;
3256 }
3257
3258 // Turn the on-the-wire ObjectId into a jobject.
3259 jvalue& v = reinterpret_cast<jvalue&>(arg_values[i]);
3260 v.l = gRegistry->GetJObject(arg_values[i]);
3261 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003262 }
3263
Sebastien Hertzd38667a2013-11-25 15:43:54 +01003264 req->receiver = receiver;
3265 req->thread = thread;
3266 req->klass = c;
3267 req->method = m;
3268 req->arg_count = arg_count;
3269 req->arg_values = arg_values;
3270 req->options = options;
3271 req->invoke_needed = true;
Elliott Hughesd07986f2011-12-06 18:27:45 -08003272 }
3273
3274 // The fact that we've released the thread list lock is a bit risky --- if the thread goes
3275 // away we're sitting high and dry -- but we must release this before the ResumeAllThreads
3276 // call, and it's unwise to hold it during WaitForSuspend.
3277
3278 {
3279 /*
3280 * We change our (JDWP thread) status, which should be THREAD_RUNNING,
Elliott Hughes81ff3182012-03-23 20:35:56 -07003281 * so we can suspend for a GC if the invoke request causes us to
Elliott Hughesd07986f2011-12-06 18:27:45 -08003282 * run out of memory. It's also a good idea to change it before locking
3283 * the invokeReq mutex, although that should never be held for long.
3284 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003285 self->TransitionFromRunnableToSuspended(kWaitingForDebuggerSend);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003286
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003287 VLOG(jdwp) << " Transferring control to event thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08003288 {
Sebastien Hertzd38667a2013-11-25 15:43:54 +01003289 MutexLock mu(self, req->lock);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003290
3291 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003292 VLOG(jdwp) << " Resuming all threads";
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003293 thread_list->UndoDebuggerSuspensions();
Elliott Hughesd07986f2011-12-06 18:27:45 -08003294 } else {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003295 VLOG(jdwp) << " Resuming event thread only";
Elliott Hughesd07986f2011-12-06 18:27:45 -08003296 thread_list->Resume(targetThread, true);
3297 }
3298
3299 // Wait for the request to finish executing.
Sebastien Hertzd38667a2013-11-25 15:43:54 +01003300 while (req->invoke_needed) {
3301 req->cond.Wait(self);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003302 }
3303 }
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003304 VLOG(jdwp) << " Control has returned from event thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08003305
3306 /* wait for thread to re-suspend itself */
Brian Carlstromdf629502013-07-17 22:39:56 -07003307 SuspendThread(thread_id, false /* request_suspension */);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003308 self->TransitionFromSuspendedToRunnable();
Elliott Hughesd07986f2011-12-06 18:27:45 -08003309 }
3310
3311 /*
3312 * Suspend the threads. We waited for the target thread to suspend
3313 * itself, so all we need to do is suspend the others.
3314 *
3315 * The suspendAllThreads() call will double-suspend the event thread,
3316 * so we want to resume the target thread once to keep the books straight.
3317 */
3318 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003319 self->TransitionFromRunnableToSuspended(kWaitingForDebuggerSuspension);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003320 VLOG(jdwp) << " Suspending all threads";
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003321 thread_list->SuspendAllForDebugger();
3322 self->TransitionFromSuspendedToRunnable();
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003323 VLOG(jdwp) << " Resuming event thread to balance the count";
Elliott Hughesd07986f2011-12-06 18:27:45 -08003324 thread_list->Resume(targetThread, true);
3325 }
3326
3327 // Copy the result.
3328 *pResultTag = req->result_tag;
3329 if (IsPrimitiveTag(req->result_tag)) {
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07003330 *pResultValue = req->result_value.GetJ();
Elliott Hughesd07986f2011-12-06 18:27:45 -08003331 } else {
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07003332 *pResultValue = gRegistry->Add(req->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003333 }
3334 *pExceptionId = req->exception;
3335 return req->error;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003336}
3337
3338void Dbg::ExecuteMethod(DebugInvokeReq* pReq) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003339 ScopedObjectAccess soa(Thread::Current());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003340
Elliott Hughes81ff3182012-03-23 20:35:56 -07003341 // We can be called while an exception is pending. We need
Elliott Hughesd07986f2011-12-06 18:27:45 -08003342 // to preserve that across the method invocation.
Ian Rogers62d6c772013-02-27 08:32:07 -08003343 SirtRef<mirror::Object> old_throw_this_object(soa.Self(), NULL);
Brian Carlstromea46f952013-07-30 01:26:50 -07003344 SirtRef<mirror::ArtMethod> old_throw_method(soa.Self(), NULL);
Ian Rogers62d6c772013-02-27 08:32:07 -08003345 SirtRef<mirror::Throwable> old_exception(soa.Self(), NULL);
3346 uint32_t old_throw_dex_pc;
3347 {
3348 ThrowLocation old_throw_location;
3349 mirror::Throwable* old_exception_obj = soa.Self()->GetException(&old_throw_location);
3350 old_throw_this_object.reset(old_throw_location.GetThis());
3351 old_throw_method.reset(old_throw_location.GetMethod());
3352 old_exception.reset(old_exception_obj);
3353 old_throw_dex_pc = old_throw_location.GetDexPc();
3354 soa.Self()->ClearException();
3355 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08003356
3357 // Translate the method through the vtable, unless the debugger wants to suppress it.
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003358 SirtRef<mirror::ArtMethod> m(soa.Self(), pReq->method);
Sebastien Hertzd38667a2013-11-25 15:43:54 +01003359 if ((pReq->options & JDWP::INVOKE_NONVIRTUAL) == 0 && pReq->receiver != NULL) {
Sebastien Hertz83a47d82014-03-20 09:57:40 +01003360 mirror::ArtMethod* actual_method = pReq->klass->FindVirtualMethodForVirtualOrInterface(m.get());
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003361 if (actual_method != m.get()) {
3362 VLOG(jdwp) << "ExecuteMethod translated " << PrettyMethod(m.get()) << " to " << PrettyMethod(actual_method);
3363 m.reset(actual_method);
Elliott Hughes45651fd2012-02-21 15:48:20 -08003364 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08003365 }
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003366 VLOG(jdwp) << "ExecuteMethod " << PrettyMethod(m.get())
Sebastien Hertzd38667a2013-11-25 15:43:54 +01003367 << " receiver=" << pReq->receiver
3368 << " arg_count=" << pReq->arg_count;
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003369 CHECK(m.get() != nullptr);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003370
3371 CHECK_EQ(sizeof(jvalue), sizeof(uint64_t));
3372
Sebastien Hertz83a47d82014-03-20 09:57:40 +01003373 pReq->result_value = InvokeWithJValues(soa, pReq->receiver, soa.EncodeMethod(m.get()),
Ian Rogers53b8b092014-03-13 23:45:53 -07003374 reinterpret_cast<jvalue*>(pReq->arg_values));
Elliott Hughesd07986f2011-12-06 18:27:45 -08003375
Ian Rogers62d6c772013-02-27 08:32:07 -08003376 mirror::Throwable* exception = soa.Self()->GetException(NULL);
3377 soa.Self()->ClearException();
3378 pReq->exception = gRegistry->Add(exception);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003379 pReq->result_tag = BasicTagFromDescriptor(MethodHelper(m.get()).GetShorty());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003380 if (pReq->exception != 0) {
Ian Rogers62d6c772013-02-27 08:32:07 -08003381 VLOG(jdwp) << " JDWP invocation returning with exception=" << exception
3382 << " " << exception->Dump();
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07003383 pReq->result_value.SetJ(0);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003384 } else if (pReq->result_tag == JDWP::JT_OBJECT) {
3385 /* if no exception thrown, examine object result more closely */
Ian Rogers98379392014-02-24 16:53:16 -08003386 JDWP::JdwpTag new_tag = TagFromObject(soa, pReq->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003387 if (new_tag != pReq->result_tag) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003388 VLOG(jdwp) << " JDWP promoted result from " << pReq->result_tag << " to " << new_tag;
Elliott Hughesd07986f2011-12-06 18:27:45 -08003389 pReq->result_tag = new_tag;
3390 }
3391
3392 /*
3393 * Register the object. We don't actually need an ObjectId yet,
3394 * but we do need to be sure that the GC won't move or discard the
3395 * object when we switch out of RUNNING. The ObjectId conversion
3396 * will add the object to the "do not touch" list.
3397 *
3398 * We can't use the "tracked allocation" mechanism here because
3399 * the object is going to be handed off to a different thread.
3400 */
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07003401 gRegistry->Add(pReq->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003402 }
3403
3404 if (old_exception.get() != NULL) {
Ian Rogers62d6c772013-02-27 08:32:07 -08003405 ThrowLocation gc_safe_throw_location(old_throw_this_object.get(), old_throw_method.get(),
3406 old_throw_dex_pc);
3407 soa.Self()->SetException(gc_safe_throw_location, old_exception.get());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003408 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003409}
3410
Elliott Hughesd07986f2011-12-06 18:27:45 -08003411/*
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003412 * "request" contains a full JDWP packet, possibly with multiple chunks. We
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003413 * need to process each, accumulate the replies, and ship the whole thing
3414 * back.
3415 *
3416 * Returns "true" if we have a reply. The reply buffer is newly allocated,
3417 * and includes the chunk type/length, followed by the data.
3418 *
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08003419 * OLD-TODO: we currently assume that the request and reply include a single
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003420 * chunk. If this becomes inconvenient we will need to adapt.
3421 */
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003422bool Dbg::DdmHandlePacket(JDWP::Request& request, uint8_t** pReplyBuf, int* pReplyLen) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003423 Thread* self = Thread::Current();
3424 JNIEnv* env = self->GetJniEnv();
3425
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003426 uint32_t type = request.ReadUnsigned32("type");
3427 uint32_t length = request.ReadUnsigned32("length");
3428
3429 // Create a byte[] corresponding to 'request'.
3430 size_t request_length = request.size();
3431 ScopedLocalRef<jbyteArray> dataArray(env, env->NewByteArray(request_length));
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003432 if (dataArray.get() == NULL) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003433 LOG(WARNING) << "byte[] allocation failed: " << request_length;
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003434 env->ExceptionClear();
3435 return false;
3436 }
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003437 env->SetByteArrayRegion(dataArray.get(), 0, request_length, reinterpret_cast<const jbyte*>(request.data()));
3438 request.Skip(request_length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003439
3440 // Run through and find all chunks. [Currently just find the first.]
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003441 ScopedByteArrayRO contents(env, dataArray.get());
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003442 if (length != request_length) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08003443 LOG(WARNING) << StringPrintf("bad chunk found (len=%u pktLen=%zd)", length, request_length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003444 return false;
3445 }
3446
3447 // Call "private static Chunk dispatch(int type, byte[] data, int offset, int length)".
Elliott Hugheseac76672012-05-24 21:56:51 -07003448 ScopedLocalRef<jobject> chunk(env, env->CallStaticObjectMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
3449 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_dispatch,
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003450 type, dataArray.get(), 0, length));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003451 if (env->ExceptionCheck()) {
3452 LOG(INFO) << StringPrintf("Exception thrown by dispatcher for 0x%08x", type);
3453 env->ExceptionDescribe();
3454 env->ExceptionClear();
3455 return false;
3456 }
3457
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003458 if (chunk.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003459 return false;
3460 }
3461
3462 /*
3463 * Pull the pieces out of the chunk. We copy the results into a
3464 * newly-allocated buffer that the caller can free. We don't want to
3465 * continue using the Chunk object because nothing has a reference to it.
3466 *
3467 * We could avoid this by returning type/data/offset/length and having
3468 * the caller be aware of the object lifetime issues, but that
Elliott Hughes81ff3182012-03-23 20:35:56 -07003469 * integrates the JDWP code more tightly into the rest of the runtime, and doesn't work
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003470 * if we have responses for multiple chunks.
3471 *
3472 * So we're pretty much stuck with copying data around multiple times.
3473 */
Elliott Hugheseac76672012-05-24 21:56:51 -07003474 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 -08003475 jint offset = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_offset);
Elliott Hugheseac76672012-05-24 21:56:51 -07003476 length = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_length);
Elliott Hugheseac76672012-05-24 21:56:51 -07003477 type = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_type);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003478
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003479 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 -07003480 if (length == 0 || replyData.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003481 return false;
3482 }
3483
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003484 const int kChunkHdrLen = 8;
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003485 uint8_t* reply = new uint8_t[length + kChunkHdrLen];
3486 if (reply == NULL) {
3487 LOG(WARNING) << "malloc failed: " << (length + kChunkHdrLen);
3488 return false;
3489 }
Elliott Hughesf7c3b662011-10-27 12:04:56 -07003490 JDWP::Set4BE(reply + 0, type);
3491 JDWP::Set4BE(reply + 4, length);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003492 env->GetByteArrayRegion(replyData.get(), offset, length, reinterpret_cast<jbyte*>(reply + kChunkHdrLen));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003493
3494 *pReplyBuf = reply;
3495 *pReplyLen = length + kChunkHdrLen;
3496
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003497 VLOG(jdwp) << StringPrintf("dvmHandleDdm returning type=%.4s %p len=%d", reinterpret_cast<char*>(reply), reply, length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003498 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003499}
3500
Elliott Hughesa2155262011-11-16 16:26:58 -08003501void Dbg::DdmBroadcast(bool connect) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003502 VLOG(jdwp) << "Broadcasting DDM " << (connect ? "connect" : "disconnect") << "...";
Elliott Hughes47fce012011-10-25 18:37:19 -07003503
3504 Thread* self = Thread::Current();
Ian Rogers50b35e22012-10-04 10:09:15 -07003505 if (self->GetState() != kRunnable) {
3506 LOG(ERROR) << "DDM broadcast in thread state " << self->GetState();
3507 /* try anyway? */
Elliott Hughes47fce012011-10-25 18:37:19 -07003508 }
3509
3510 JNIEnv* env = self->GetJniEnv();
Elliott Hughes47fce012011-10-25 18:37:19 -07003511 jint event = connect ? 1 /*DdmServer.CONNECTED*/ : 2 /*DdmServer.DISCONNECTED*/;
Elliott Hugheseac76672012-05-24 21:56:51 -07003512 env->CallStaticVoidMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
3513 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_broadcast,
3514 event);
Elliott Hughes47fce012011-10-25 18:37:19 -07003515 if (env->ExceptionCheck()) {
3516 LOG(ERROR) << "DdmServer.broadcast " << event << " failed";
3517 env->ExceptionDescribe();
3518 env->ExceptionClear();
3519 }
3520}
3521
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003522void Dbg::DdmConnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08003523 Dbg::DdmBroadcast(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003524}
3525
3526void Dbg::DdmDisconnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08003527 Dbg::DdmBroadcast(false);
Elliott Hughes47fce012011-10-25 18:37:19 -07003528 gDdmThreadNotification = false;
3529}
3530
3531/*
Elliott Hughes82188472011-11-07 18:11:48 -08003532 * Send a notification when a thread starts, stops, or changes its name.
Elliott Hughes47fce012011-10-25 18:37:19 -07003533 *
3534 * Because we broadcast the full set of threads when the notifications are
3535 * first enabled, it's possible for "thread" to be actively executing.
3536 */
Elliott Hughes82188472011-11-07 18:11:48 -08003537void Dbg::DdmSendThreadNotification(Thread* t, uint32_t type) {
Elliott Hughes47fce012011-10-25 18:37:19 -07003538 if (!gDdmThreadNotification) {
3539 return;
3540 }
3541
Elliott Hughes82188472011-11-07 18:11:48 -08003542 if (type == CHUNK_TYPE("THDE")) {
Elliott Hughes47fce012011-10-25 18:37:19 -07003543 uint8_t buf[4];
Ian Rogersd9c4fc92013-10-01 19:45:43 -07003544 JDWP::Set4BE(&buf[0], t->GetThreadId());
Elliott Hughes47fce012011-10-25 18:37:19 -07003545 Dbg::DdmSendChunk(CHUNK_TYPE("THDE"), 4, buf);
Elliott Hughes82188472011-11-07 18:11:48 -08003546 } else {
3547 CHECK(type == CHUNK_TYPE("THCR") || type == CHUNK_TYPE("THNM")) << type;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003548 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003549 SirtRef<mirror::String> name(soa.Self(), t->GetThreadName(soa));
Elliott Hughes82188472011-11-07 18:11:48 -08003550 size_t char_count = (name.get() != NULL) ? name->GetLength() : 0;
jeffhao725a9572012-11-13 18:20:12 -08003551 const jchar* chars = (name.get() != NULL) ? name->GetCharArray()->GetData() : NULL;
Elliott Hughes82188472011-11-07 18:11:48 -08003552
Elliott Hughes21f32d72011-11-09 17:44:13 -08003553 std::vector<uint8_t> bytes;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07003554 JDWP::Append4BE(bytes, t->GetThreadId());
Elliott Hughes545a0642011-11-08 19:10:03 -08003555 JDWP::AppendUtf16BE(bytes, chars, char_count);
Elliott Hughes21f32d72011-11-09 17:44:13 -08003556 CHECK_EQ(bytes.size(), char_count*2 + sizeof(uint32_t)*2);
3557 Dbg::DdmSendChunk(type, bytes);
Elliott Hughes47fce012011-10-25 18:37:19 -07003558 }
3559}
3560
Elliott Hughes47fce012011-10-25 18:37:19 -07003561void Dbg::DdmSetThreadNotification(bool enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003562 // Enable/disable thread notifications.
Elliott Hughes47fce012011-10-25 18:37:19 -07003563 gDdmThreadNotification = enable;
3564 if (enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003565 // Suspend the VM then post thread start notifications for all threads. Threads attaching will
3566 // see a suspension in progress and block until that ends. They then post their own start
3567 // notification.
3568 SuspendVM();
3569 std::list<Thread*> threads;
Ian Rogers50b35e22012-10-04 10:09:15 -07003570 Thread* self = Thread::Current();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003571 {
Ian Rogers50b35e22012-10-04 10:09:15 -07003572 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003573 threads = Runtime::Current()->GetThreadList()->GetList();
3574 }
3575 {
Ian Rogers50b35e22012-10-04 10:09:15 -07003576 ScopedObjectAccess soa(self);
Mathieu Chartier02e25112013-08-14 16:14:24 -07003577 for (Thread* thread : threads) {
3578 Dbg::DdmSendThreadNotification(thread, CHUNK_TYPE("THCR"));
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003579 }
3580 }
3581 ResumeVM();
Elliott Hughes47fce012011-10-25 18:37:19 -07003582 }
3583}
3584
Elliott Hughesa2155262011-11-16 16:26:58 -08003585void Dbg::PostThreadStartOrStop(Thread* t, uint32_t type) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07003586 if (IsDebuggerActive()) {
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07003587 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogerscfaa4552012-11-26 21:00:08 -08003588 JDWP::ObjectId id = gRegistry->Add(t->GetPeer());
Elliott Hughes82188472011-11-07 18:11:48 -08003589 gJdwpState->PostThreadChange(id, type == CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07003590 }
Elliott Hughes82188472011-11-07 18:11:48 -08003591 Dbg::DdmSendThreadNotification(t, type);
Elliott Hughes47fce012011-10-25 18:37:19 -07003592}
3593
3594void Dbg::PostThreadStart(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08003595 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07003596}
3597
3598void Dbg::PostThreadDeath(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08003599 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THDE"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003600}
3601
Elliott Hughes82188472011-11-07 18:11:48 -08003602void Dbg::DdmSendChunk(uint32_t type, size_t byte_count, const uint8_t* buf) {
Elliott Hughes3bb81562011-10-21 18:52:59 -07003603 CHECK(buf != NULL);
3604 iovec vec[1];
3605 vec[0].iov_base = reinterpret_cast<void*>(const_cast<uint8_t*>(buf));
3606 vec[0].iov_len = byte_count;
3607 Dbg::DdmSendChunkV(type, vec, 1);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003608}
3609
Elliott Hughes21f32d72011-11-09 17:44:13 -08003610void Dbg::DdmSendChunk(uint32_t type, const std::vector<uint8_t>& bytes) {
3611 DdmSendChunk(type, bytes.size(), &bytes[0]);
3612}
3613
Brian Carlstromf5293522013-07-19 00:24:00 -07003614void Dbg::DdmSendChunkV(uint32_t type, const iovec* iov, int iov_count) {
Elliott Hughes3bb81562011-10-21 18:52:59 -07003615 if (gJdwpState == NULL) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003616 VLOG(jdwp) << "Debugger thread not active, ignoring DDM send: " << type;
Elliott Hughes3bb81562011-10-21 18:52:59 -07003617 } else {
Elliott Hughescccd84f2011-12-05 16:51:54 -08003618 gJdwpState->DdmSendChunkV(type, iov, iov_count);
Elliott Hughes3bb81562011-10-21 18:52:59 -07003619 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003620}
3621
Elliott Hughes767a1472011-10-26 18:49:02 -07003622int Dbg::DdmHandleHpifChunk(HpifWhen when) {
3623 if (when == HPIF_WHEN_NOW) {
Elliott Hughes7162ad92011-10-27 14:08:42 -07003624 DdmSendHeapInfo(when);
Elliott Hughes767a1472011-10-26 18:49:02 -07003625 return true;
3626 }
3627
3628 if (when != HPIF_WHEN_NEVER && when != HPIF_WHEN_NEXT_GC && when != HPIF_WHEN_EVERY_GC) {
3629 LOG(ERROR) << "invalid HpifWhen value: " << static_cast<int>(when);
3630 return false;
3631 }
3632
3633 gDdmHpifWhen = when;
3634 return true;
3635}
3636
3637bool Dbg::DdmHandleHpsgNhsgChunk(Dbg::HpsgWhen when, Dbg::HpsgWhat what, bool native) {
3638 if (when != HPSG_WHEN_NEVER && when != HPSG_WHEN_EVERY_GC) {
3639 LOG(ERROR) << "invalid HpsgWhen value: " << static_cast<int>(when);
3640 return false;
3641 }
3642
3643 if (what != HPSG_WHAT_MERGED_OBJECTS && what != HPSG_WHAT_DISTINCT_OBJECTS) {
3644 LOG(ERROR) << "invalid HpsgWhat value: " << static_cast<int>(what);
3645 return false;
3646 }
3647
3648 if (native) {
3649 gDdmNhsgWhen = when;
3650 gDdmNhsgWhat = what;
3651 } else {
3652 gDdmHpsgWhen = when;
3653 gDdmHpsgWhat = what;
3654 }
3655 return true;
3656}
3657
Elliott Hughes7162ad92011-10-27 14:08:42 -07003658void Dbg::DdmSendHeapInfo(HpifWhen reason) {
3659 // If there's a one-shot 'when', reset it.
3660 if (reason == gDdmHpifWhen) {
3661 if (gDdmHpifWhen == HPIF_WHEN_NEXT_GC) {
3662 gDdmHpifWhen = HPIF_WHEN_NEVER;
3663 }
3664 }
3665
3666 /*
3667 * Chunk HPIF (client --> server)
3668 *
3669 * Heap Info. General information about the heap,
3670 * suitable for a summary display.
3671 *
3672 * [u4]: number of heaps
3673 *
3674 * For each heap:
3675 * [u4]: heap ID
3676 * [u8]: timestamp in ms since Unix epoch
3677 * [u1]: capture reason (same as 'when' value from server)
3678 * [u4]: max heap size in bytes (-Xmx)
3679 * [u4]: current heap size in bytes
3680 * [u4]: current number of bytes allocated
3681 * [u4]: current number of objects allocated
3682 */
3683 uint8_t heap_count = 1;
Ian Rogers1d54e732013-05-02 21:10:01 -07003684 gc::Heap* heap = Runtime::Current()->GetHeap();
Elliott Hughes21f32d72011-11-09 17:44:13 -08003685 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08003686 JDWP::Append4BE(bytes, heap_count);
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003687 JDWP::Append4BE(bytes, 1); // Heap id (bogus; we only have one heap).
Elliott Hughes545a0642011-11-08 19:10:03 -08003688 JDWP::Append8BE(bytes, MilliTime());
3689 JDWP::Append1BE(bytes, reason);
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003690 JDWP::Append4BE(bytes, heap->GetMaxMemory()); // Max allowed heap size in bytes.
3691 JDWP::Append4BE(bytes, heap->GetTotalMemory()); // Current heap size in bytes.
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08003692 JDWP::Append4BE(bytes, heap->GetBytesAllocated());
3693 JDWP::Append4BE(bytes, heap->GetObjectsAllocated());
Elliott Hughes21f32d72011-11-09 17:44:13 -08003694 CHECK_EQ(bytes.size(), 4U + (heap_count * (4 + 8 + 1 + 4 + 4 + 4 + 4)));
3695 Dbg::DdmSendChunk(CHUNK_TYPE("HPIF"), bytes);
Elliott Hughes767a1472011-10-26 18:49:02 -07003696}
3697
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003698enum HpsgSolidity {
3699 SOLIDITY_FREE = 0,
3700 SOLIDITY_HARD = 1,
3701 SOLIDITY_SOFT = 2,
3702 SOLIDITY_WEAK = 3,
3703 SOLIDITY_PHANTOM = 4,
3704 SOLIDITY_FINALIZABLE = 5,
3705 SOLIDITY_SWEEP = 6,
3706};
3707
3708enum HpsgKind {
3709 KIND_OBJECT = 0,
3710 KIND_CLASS_OBJECT = 1,
3711 KIND_ARRAY_1 = 2,
3712 KIND_ARRAY_2 = 3,
3713 KIND_ARRAY_4 = 4,
3714 KIND_ARRAY_8 = 5,
3715 KIND_UNKNOWN = 6,
3716 KIND_NATIVE = 7,
3717};
3718
3719#define HPSG_PARTIAL (1<<7)
3720#define HPSG_STATE(solidity, kind) ((uint8_t)((((kind) & 0x7) << 3) | ((solidity) & 0x7)))
3721
Ian Rogers30fab402012-01-23 15:43:46 -08003722class HeapChunkContext {
3723 public:
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003724 // Maximum chunk size. Obtain this from the formula:
3725 // (((maximum_heap_size / ALLOCATION_UNIT_SIZE) + 255) / 256) * 2
3726 HeapChunkContext(bool merge, bool native)
Ian Rogers30fab402012-01-23 15:43:46 -08003727 : buf_(16384 - 16),
3728 type_(0),
3729 merge_(merge) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003730 Reset();
3731 if (native) {
Ian Rogers30fab402012-01-23 15:43:46 -08003732 type_ = CHUNK_TYPE("NHSG");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003733 } else {
Ian Rogers30fab402012-01-23 15:43:46 -08003734 type_ = merge ? CHUNK_TYPE("HPSG") : CHUNK_TYPE("HPSO");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003735 }
3736 }
3737
3738 ~HeapChunkContext() {
Ian Rogers30fab402012-01-23 15:43:46 -08003739 if (p_ > &buf_[0]) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003740 Flush();
3741 }
3742 }
3743
3744 void EnsureHeader(const void* chunk_ptr) {
Ian Rogers30fab402012-01-23 15:43:46 -08003745 if (!needHeader_) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003746 return;
3747 }
3748
3749 // Start a new HPSx chunk.
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003750 JDWP::Write4BE(&p_, 1); // Heap id (bogus; we only have one heap).
3751 JDWP::Write1BE(&p_, 8); // Size of allocation unit, in bytes.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003752
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003753 JDWP::Write4BE(&p_, reinterpret_cast<uintptr_t>(chunk_ptr)); // virtual address of segment start.
3754 JDWP::Write4BE(&p_, 0); // offset of this piece (relative to the virtual address).
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003755 // [u4]: length of piece, in allocation units
3756 // 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 -08003757 pieceLenField_ = p_;
3758 JDWP::Write4BE(&p_, 0x55555555);
3759 needHeader_ = false;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003760 }
3761
Ian Rogersb726dcb2012-09-05 08:57:23 -07003762 void Flush() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogersd636b062013-01-18 17:51:18 -08003763 if (pieceLenField_ == NULL) {
3764 // Flush immediately post Reset (maybe back-to-back Flush). Ignore.
3765 CHECK(needHeader_);
3766 return;
3767 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003768 // Patch the "length of piece" field.
Ian Rogers30fab402012-01-23 15:43:46 -08003769 CHECK_LE(&buf_[0], pieceLenField_);
3770 CHECK_LE(pieceLenField_, p_);
3771 JDWP::Set4BE(pieceLenField_, totalAllocationUnits_);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003772
Ian Rogers30fab402012-01-23 15:43:46 -08003773 Dbg::DdmSendChunk(type_, p_ - &buf_[0], &buf_[0]);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003774 Reset();
3775 }
3776
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003777 static void HeapChunkCallback(void* start, void* end, size_t used_bytes, void* arg)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003778 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_,
3779 Locks::mutator_lock_) {
Ian Rogers30fab402012-01-23 15:43:46 -08003780 reinterpret_cast<HeapChunkContext*>(arg)->HeapChunkCallback(start, end, used_bytes);
Elliott Hughesa2155262011-11-16 16:26:58 -08003781 }
3782
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003783 private:
Elliott Hughesa2155262011-11-16 16:26:58 -08003784 enum { ALLOCATION_UNIT_SIZE = 8 };
3785
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003786 void Reset() {
Ian Rogers30fab402012-01-23 15:43:46 -08003787 p_ = &buf_[0];
Ian Rogers15bf2d32012-08-28 17:33:04 -07003788 startOfNextMemoryChunk_ = NULL;
Ian Rogers30fab402012-01-23 15:43:46 -08003789 totalAllocationUnits_ = 0;
3790 needHeader_ = true;
3791 pieceLenField_ = NULL;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003792 }
3793
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003794 void HeapChunkCallback(void* start, void* /*end*/, size_t used_bytes)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003795 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_,
3796 Locks::mutator_lock_) {
Ian Rogers30fab402012-01-23 15:43:46 -08003797 // Note: heap call backs cannot manipulate the heap upon which they are crawling, care is taken
3798 // in the following code not to allocate memory, by ensuring buf_ is of the correct size
Ian Rogers15bf2d32012-08-28 17:33:04 -07003799 if (used_bytes == 0) {
3800 if (start == NULL) {
3801 // Reset for start of new heap.
3802 startOfNextMemoryChunk_ = NULL;
3803 Flush();
3804 }
3805 // Only process in use memory so that free region information
3806 // also includes dlmalloc book keeping.
Elliott Hughesa2155262011-11-16 16:26:58 -08003807 return;
Elliott Hughesa2155262011-11-16 16:26:58 -08003808 }
3809
Ian Rogers15bf2d32012-08-28 17:33:04 -07003810 /* If we're looking at the native heap, we'll just return
3811 * (SOLIDITY_HARD, KIND_NATIVE) for all allocated chunks
3812 */
3813 bool native = type_ == CHUNK_TYPE("NHSG");
3814
3815 if (startOfNextMemoryChunk_ != NULL) {
3816 // Transmit any pending free memory. Native free memory of
3817 // over kMaxFreeLen could be because of the use of mmaps, so
3818 // don't report. If not free memory then start a new segment.
3819 bool flush = true;
3820 if (start > startOfNextMemoryChunk_) {
3821 const size_t kMaxFreeLen = 2 * kPageSize;
3822 void* freeStart = startOfNextMemoryChunk_;
3823 void* freeEnd = start;
Brian Carlstrom2d888622013-07-18 17:02:00 -07003824 size_t freeLen = reinterpret_cast<char*>(freeEnd) - reinterpret_cast<char*>(freeStart);
Ian Rogers15bf2d32012-08-28 17:33:04 -07003825 if (!native || freeLen < kMaxFreeLen) {
3826 AppendChunk(HPSG_STATE(SOLIDITY_FREE, 0), freeStart, freeLen);
3827 flush = false;
3828 }
3829 }
3830 if (flush) {
3831 startOfNextMemoryChunk_ = NULL;
3832 Flush();
3833 }
3834 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08003835 mirror::Object* obj = reinterpret_cast<mirror::Object*>(start);
Elliott Hughesa2155262011-11-16 16:26:58 -08003836
3837 // Determine the type of this chunk.
3838 // OLD-TODO: if context.merge, see if this chunk is different from the last chunk.
3839 // If it's the same, we should combine them.
Ian Rogers15bf2d32012-08-28 17:33:04 -07003840 uint8_t state = ExamineObject(obj, native);
3841 // dlmalloc's chunk header is 2 * sizeof(size_t), but if the previous chunk is in use for an
3842 // allocation then the first sizeof(size_t) may belong to it.
3843 const size_t dlMallocOverhead = sizeof(size_t);
3844 AppendChunk(state, start, used_bytes + dlMallocOverhead);
Brian Carlstrom2d888622013-07-18 17:02:00 -07003845 startOfNextMemoryChunk_ = reinterpret_cast<char*>(start) + used_bytes + dlMallocOverhead;
Ian Rogers15bf2d32012-08-28 17:33:04 -07003846 }
Elliott Hughesa2155262011-11-16 16:26:58 -08003847
Ian Rogers15bf2d32012-08-28 17:33:04 -07003848 void AppendChunk(uint8_t state, void* ptr, size_t length)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003849 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07003850 // Make sure there's enough room left in the buffer.
3851 // We need to use two bytes for every fractional 256 allocation units used by the chunk plus
3852 // 17 bytes for any header.
3853 size_t needed = (((length/ALLOCATION_UNIT_SIZE + 255) / 256) * 2) + 17;
3854 size_t bytesLeft = buf_.size() - (size_t)(p_ - &buf_[0]);
3855 if (bytesLeft < needed) {
3856 Flush();
3857 }
3858
3859 bytesLeft = buf_.size() - (size_t)(p_ - &buf_[0]);
3860 if (bytesLeft < needed) {
3861 LOG(WARNING) << "Chunk is too big to transmit (chunk_len=" << length << ", "
3862 << needed << " bytes)";
3863 return;
3864 }
3865 EnsureHeader(ptr);
Elliott Hughesa2155262011-11-16 16:26:58 -08003866 // Write out the chunk description.
Ian Rogers15bf2d32012-08-28 17:33:04 -07003867 length /= ALLOCATION_UNIT_SIZE; // Convert to allocation units.
3868 totalAllocationUnits_ += length;
3869 while (length > 256) {
Ian Rogers30fab402012-01-23 15:43:46 -08003870 *p_++ = state | HPSG_PARTIAL;
3871 *p_++ = 255; // length - 1
Ian Rogers15bf2d32012-08-28 17:33:04 -07003872 length -= 256;
Elliott Hughesa2155262011-11-16 16:26:58 -08003873 }
Ian Rogers30fab402012-01-23 15:43:46 -08003874 *p_++ = state;
Ian Rogers15bf2d32012-08-28 17:33:04 -07003875 *p_++ = length - 1;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003876 }
3877
Ian Rogersef7d42f2014-01-06 12:55:46 -08003878 uint8_t ExamineObject(mirror::Object* o, bool is_native_heap)
3879 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Elliott Hughesa2155262011-11-16 16:26:58 -08003880 if (o == NULL) {
3881 return HPSG_STATE(SOLIDITY_FREE, 0);
3882 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003883
Elliott Hughesa2155262011-11-16 16:26:58 -08003884 // It's an allocated chunk. Figure out what it is.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003885
Elliott Hughesa2155262011-11-16 16:26:58 -08003886 // If we're looking at the native heap, we'll just return
3887 // (SOLIDITY_HARD, KIND_NATIVE) for all allocated chunks.
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003888 if (is_native_heap) {
Elliott Hughesa2155262011-11-16 16:26:58 -08003889 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
3890 }
3891
Ian Rogers5bfa60f2012-09-02 21:17:56 -07003892 if (!Runtime::Current()->GetHeap()->IsLiveObjectLocked(o)) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07003893 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003894 }
3895
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003896 mirror::Class* c = o->GetClass();
Elliott Hughesa2155262011-11-16 16:26:58 -08003897 if (c == NULL) {
3898 // The object was probably just created but hasn't been initialized yet.
3899 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
3900 }
3901
Mathieu Chartier590fee92013-09-13 13:46:47 -07003902 if (!Runtime::Current()->GetHeap()->IsValidObjectAddress(c)) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07003903 LOG(ERROR) << "Invalid class for managed heap object: " << o << " " << c;
Elliott Hughesa2155262011-11-16 16:26:58 -08003904 return HPSG_STATE(SOLIDITY_HARD, KIND_UNKNOWN);
3905 }
3906
3907 if (c->IsClassClass()) {
3908 return HPSG_STATE(SOLIDITY_HARD, KIND_CLASS_OBJECT);
3909 }
3910
3911 if (c->IsArrayClass()) {
3912 if (o->IsObjectArray()) {
3913 return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
3914 }
3915 switch (c->GetComponentSize()) {
3916 case 1: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_1);
3917 case 2: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_2);
3918 case 4: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
3919 case 8: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_8);
3920 }
3921 }
3922
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003923 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
3924 }
3925
Ian Rogers30fab402012-01-23 15:43:46 -08003926 std::vector<uint8_t> buf_;
3927 uint8_t* p_;
3928 uint8_t* pieceLenField_;
Ian Rogers15bf2d32012-08-28 17:33:04 -07003929 void* startOfNextMemoryChunk_;
Ian Rogers30fab402012-01-23 15:43:46 -08003930 size_t totalAllocationUnits_;
3931 uint32_t type_;
3932 bool merge_;
3933 bool needHeader_;
3934
Elliott Hughesa2155262011-11-16 16:26:58 -08003935 DISALLOW_COPY_AND_ASSIGN(HeapChunkContext);
3936};
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003937
3938void Dbg::DdmSendHeapSegments(bool native) {
3939 Dbg::HpsgWhen when;
3940 Dbg::HpsgWhat what;
3941 if (!native) {
3942 when = gDdmHpsgWhen;
3943 what = gDdmHpsgWhat;
3944 } else {
3945 when = gDdmNhsgWhen;
3946 what = gDdmNhsgWhat;
3947 }
3948 if (when == HPSG_WHEN_NEVER) {
3949 return;
3950 }
3951
3952 // Figure out what kind of chunks we'll be sending.
3953 CHECK(what == HPSG_WHAT_MERGED_OBJECTS || what == HPSG_WHAT_DISTINCT_OBJECTS) << static_cast<int>(what);
3954
3955 // First, send a heap start chunk.
3956 uint8_t heap_id[4];
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003957 JDWP::Set4BE(&heap_id[0], 1); // Heap id (bogus; we only have one heap).
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003958 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHST") : CHUNK_TYPE("HPST"), sizeof(heap_id), heap_id);
3959
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07003960 Thread* self = Thread::Current();
3961
3962 // To allow the Walk/InspectAll() below to exclusively-lock the
3963 // mutator lock, temporarily release the shared access to the
3964 // mutator lock here by transitioning to the suspended state.
3965 Locks::mutator_lock_->AssertSharedHeld(self);
3966 self->TransitionFromRunnableToSuspended(kSuspended);
3967
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003968 // Send a series of heap segment chunks.
Elliott Hughesa2155262011-11-16 16:26:58 -08003969 HeapChunkContext context((what == HPSG_WHAT_MERGED_OBJECTS), native);
3970 if (native) {
Ian Rogers1d54e732013-05-02 21:10:01 -07003971 dlmalloc_inspect_all(HeapChunkContext::HeapChunkCallback, &context);
Elliott Hughesa2155262011-11-16 16:26:58 -08003972 } else {
Ian Rogers1d54e732013-05-02 21:10:01 -07003973 gc::Heap* heap = Runtime::Current()->GetHeap();
3974 const std::vector<gc::space::ContinuousSpace*>& spaces = heap->GetContinuousSpaces();
Ian Rogers1d54e732013-05-02 21:10:01 -07003975 typedef std::vector<gc::space::ContinuousSpace*>::const_iterator It;
3976 for (It cur = spaces.begin(), end = spaces.end(); cur != end; ++cur) {
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07003977 if ((*cur)->IsMallocSpace()) {
3978 (*cur)->AsMallocSpace()->Walk(HeapChunkContext::HeapChunkCallback, &context);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07003979 }
3980 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07003981 // Walk the large objects, these are not in the AllocSpace.
3982 heap->GetLargeObjectsSpace()->Walk(HeapChunkContext::HeapChunkCallback, &context);
Elliott Hughesa2155262011-11-16 16:26:58 -08003983 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003984
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07003985 // Shared-lock the mutator lock back.
3986 self->TransitionFromSuspendedToRunnable();
3987 Locks::mutator_lock_->AssertSharedHeld(self);
3988
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003989 // Finally, send a heap end chunk.
3990 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHEN") : CHUNK_TYPE("HPEN"), sizeof(heap_id), heap_id);
Elliott Hughes767a1472011-10-26 18:49:02 -07003991}
3992
Elliott Hughesb1a58792013-07-11 18:10:58 -07003993static size_t GetAllocTrackerMax() {
3994#ifdef HAVE_ANDROID_OS
3995 // Check whether there's a system property overriding the number of records.
3996 const char* propertyName = "dalvik.vm.allocTrackerMax";
3997 char allocRecordMaxString[PROPERTY_VALUE_MAX];
3998 if (property_get(propertyName, allocRecordMaxString, "") > 0) {
3999 char* end;
4000 size_t value = strtoul(allocRecordMaxString, &end, 10);
4001 if (*end != '\0') {
Ruben Brunk3e47a742013-09-09 17:56:07 -07004002 LOG(ERROR) << "Ignoring " << propertyName << " '" << allocRecordMaxString
4003 << "' --- invalid";
Elliott Hughesb1a58792013-07-11 18:10:58 -07004004 return kDefaultNumAllocRecords;
4005 }
4006 if (!IsPowerOfTwo(value)) {
Ruben Brunk3e47a742013-09-09 17:56:07 -07004007 LOG(ERROR) << "Ignoring " << propertyName << " '" << allocRecordMaxString
4008 << "' --- not power of two";
Elliott Hughesb1a58792013-07-11 18:10:58 -07004009 return kDefaultNumAllocRecords;
4010 }
4011 return value;
4012 }
4013#endif
4014 return kDefaultNumAllocRecords;
4015}
4016
Elliott Hughes545a0642011-11-08 19:10:03 -08004017void Dbg::SetAllocTrackingEnabled(bool enabled) {
Elliott Hughes545a0642011-11-08 19:10:03 -08004018 if (enabled) {
Sebastien Hertzb98063a2014-03-26 10:57:20 +01004019 {
4020 MutexLock mu(Thread::Current(), *alloc_tracker_lock_);
4021 if (recent_allocation_records_ == NULL) {
4022 alloc_record_max_ = GetAllocTrackerMax();
4023 LOG(INFO) << "Enabling alloc tracker (" << alloc_record_max_ << " entries of "
4024 << kMaxAllocRecordStackDepth << " frames, taking "
4025 << PrettySize(sizeof(AllocRecord) * alloc_record_max_) << ")";
4026 alloc_record_head_ = alloc_record_count_ = 0;
4027 recent_allocation_records_ = new AllocRecord[alloc_record_max_];
4028 CHECK(recent_allocation_records_ != NULL);
4029 }
Elliott Hughes545a0642011-11-08 19:10:03 -08004030 }
Ian Rogersfa824272013-11-05 16:12:57 -08004031 Runtime::Current()->GetInstrumentation()->InstrumentQuickAllocEntryPoints();
Elliott Hughes545a0642011-11-08 19:10:03 -08004032 } else {
Ian Rogersfa824272013-11-05 16:12:57 -08004033 Runtime::Current()->GetInstrumentation()->UninstrumentQuickAllocEntryPoints();
Sebastien Hertzb98063a2014-03-26 10:57:20 +01004034 {
4035 MutexLock mu(Thread::Current(), *alloc_tracker_lock_);
4036 delete[] recent_allocation_records_;
4037 recent_allocation_records_ = NULL;
4038 }
Elliott Hughes545a0642011-11-08 19:10:03 -08004039 }
4040}
4041
Ian Rogers0399dde2012-06-06 17:09:28 -07004042struct AllocRecordStackVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -08004043 AllocRecordStackVisitor(Thread* thread, AllocRecord* record)
Ian Rogersb726dcb2012-09-05 08:57:23 -07004044 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08004045 : StackVisitor(thread, NULL), record(record), depth(0) {}
Elliott Hughes545a0642011-11-08 19:10:03 -08004046
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004047 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
4048 // annotalysis.
4049 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughes545a0642011-11-08 19:10:03 -08004050 if (depth >= kMaxAllocRecordStackDepth) {
Elliott Hughes530fa002012-03-12 11:44:49 -07004051 return false;
Elliott Hughes545a0642011-11-08 19:10:03 -08004052 }
Brian Carlstromea46f952013-07-30 01:26:50 -07004053 mirror::ArtMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07004054 if (!m->IsRuntimeMethod()) {
4055 record->stack[depth].method = m;
4056 record->stack[depth].dex_pc = GetDexPc();
Elliott Hughes530fa002012-03-12 11:44:49 -07004057 ++depth;
Elliott Hughes545a0642011-11-08 19:10:03 -08004058 }
Elliott Hughes530fa002012-03-12 11:44:49 -07004059 return true;
Elliott Hughes545a0642011-11-08 19:10:03 -08004060 }
4061
4062 ~AllocRecordStackVisitor() {
4063 // Clear out any unused stack trace elements.
4064 for (; depth < kMaxAllocRecordStackDepth; ++depth) {
4065 record->stack[depth].method = NULL;
Ian Rogers0399dde2012-06-06 17:09:28 -07004066 record->stack[depth].dex_pc = 0;
Elliott Hughes545a0642011-11-08 19:10:03 -08004067 }
4068 }
4069
4070 AllocRecord* record;
4071 size_t depth;
4072};
4073
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004074void Dbg::RecordAllocation(mirror::Class* type, size_t byte_count) {
Elliott Hughes545a0642011-11-08 19:10:03 -08004075 Thread* self = Thread::Current();
4076 CHECK(self != NULL);
4077
Ian Rogers719d1a32014-03-06 12:13:39 -08004078 MutexLock mu(self, *alloc_tracker_lock_);
Elliott Hughes545a0642011-11-08 19:10:03 -08004079 if (recent_allocation_records_ == NULL) {
4080 return;
4081 }
4082
4083 // Advance and clip.
Ian Rogers719d1a32014-03-06 12:13:39 -08004084 if (++alloc_record_head_ == alloc_record_max_) {
4085 alloc_record_head_ = 0;
Elliott Hughes545a0642011-11-08 19:10:03 -08004086 }
4087
4088 // Fill in the basics.
Ian Rogers719d1a32014-03-06 12:13:39 -08004089 AllocRecord* record = &recent_allocation_records_[alloc_record_head_];
Elliott Hughes545a0642011-11-08 19:10:03 -08004090 record->type = type;
4091 record->byte_count = byte_count;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07004092 record->thin_lock_id = self->GetThreadId();
Elliott Hughes545a0642011-11-08 19:10:03 -08004093
4094 // Fill in the stack trace.
Ian Rogers7a22fa62013-01-23 12:16:16 -08004095 AllocRecordStackVisitor visitor(self, record);
Ian Rogers0399dde2012-06-06 17:09:28 -07004096 visitor.WalkStack();
Elliott Hughes545a0642011-11-08 19:10:03 -08004097
Ian Rogers719d1a32014-03-06 12:13:39 -08004098 if (alloc_record_count_ < alloc_record_max_) {
4099 ++alloc_record_count_;
Elliott Hughes545a0642011-11-08 19:10:03 -08004100 }
4101}
4102
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004103// Returns the index of the head element.
4104//
4105// We point at the most-recently-written record, so if gAllocRecordCount is 1
4106// we want to use the current element. Take "head+1" and subtract count
4107// from it.
4108//
4109// We need to handle underflow in our circular buffer, so we add
Elliott Hughesb1a58792013-07-11 18:10:58 -07004110// gAllocRecordMax and then mask it back down.
Ian Rogers719d1a32014-03-06 12:13:39 -08004111size_t Dbg::HeadIndex() {
4112 return (Dbg::alloc_record_head_ + 1 + Dbg::alloc_record_max_ - Dbg::alloc_record_count_) &
4113 (Dbg::alloc_record_max_ - 1);
Elliott Hughes545a0642011-11-08 19:10:03 -08004114}
4115
4116void Dbg::DumpRecentAllocations() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004117 ScopedObjectAccess soa(Thread::Current());
Ian Rogers719d1a32014-03-06 12:13:39 -08004118 MutexLock mu(soa.Self(), *alloc_tracker_lock_);
Elliott Hughes545a0642011-11-08 19:10:03 -08004119 if (recent_allocation_records_ == NULL) {
4120 LOG(INFO) << "Not recording tracked allocations";
4121 return;
4122 }
4123
4124 // "i" is the head of the list. We want to start at the end of the
4125 // list and move forward to the tail.
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004126 size_t i = HeadIndex();
Ian Rogers719d1a32014-03-06 12:13:39 -08004127 size_t count = alloc_record_count_;
Elliott Hughes545a0642011-11-08 19:10:03 -08004128
Ian Rogers719d1a32014-03-06 12:13:39 -08004129 LOG(INFO) << "Tracked allocations, (head=" << alloc_record_head_ << " count=" << count << ")";
Elliott Hughes545a0642011-11-08 19:10:03 -08004130 while (count--) {
4131 AllocRecord* record = &recent_allocation_records_[i];
4132
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004133 LOG(INFO) << StringPrintf(" Thread %-2d %6zd bytes ", record->thin_lock_id, record->byte_count)
Elliott Hughes545a0642011-11-08 19:10:03 -08004134 << PrettyClass(record->type);
4135
4136 for (size_t stack_frame = 0; stack_frame < kMaxAllocRecordStackDepth; ++stack_frame) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08004137 mirror::ArtMethod* m = record->stack[stack_frame].method;
Elliott Hughes545a0642011-11-08 19:10:03 -08004138 if (m == NULL) {
4139 break;
4140 }
4141 LOG(INFO) << " " << PrettyMethod(m) << " line " << record->stack[stack_frame].LineNumber();
4142 }
4143
4144 // pause periodically to help logcat catch up
4145 if ((count % 5) == 0) {
4146 usleep(40000);
4147 }
4148
Ian Rogers719d1a32014-03-06 12:13:39 -08004149 i = (i + 1) & (alloc_record_max_ - 1);
Elliott Hughes545a0642011-11-08 19:10:03 -08004150 }
4151}
4152
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -07004153void Dbg::UpdateObjectPointers(IsMarkedCallback* callback, void* arg) {
Ian Rogers719d1a32014-03-06 12:13:39 -08004154 if (recent_allocation_records_ != nullptr) {
4155 MutexLock mu(Thread::Current(), *alloc_tracker_lock_);
4156 size_t i = HeadIndex();
4157 size_t count = alloc_record_count_;
4158 while (count--) {
4159 AllocRecord* record = &recent_allocation_records_[i];
4160 DCHECK(record != nullptr);
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -07004161 record->UpdateObjectPointers(callback, arg);
Ian Rogers719d1a32014-03-06 12:13:39 -08004162 i = (i + 1) & (alloc_record_max_ - 1);
Mathieu Chartier412c7fc2014-02-07 12:18:39 -08004163 }
4164 }
4165 if (gRegistry != nullptr) {
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -07004166 gRegistry->UpdateObjectPointers(callback, arg);
Mathieu Chartier412c7fc2014-02-07 12:18:39 -08004167 }
4168}
4169
4170void Dbg::AllowNewObjectRegistryObjects() {
4171 if (gRegistry != nullptr) {
4172 gRegistry->AllowNewObjects();
4173 }
4174}
4175
4176void Dbg::DisallowNewObjectRegistryObjects() {
4177 if (gRegistry != nullptr) {
4178 gRegistry->DisallowNewObjects();
4179 }
4180}
4181
Elliott Hughes545a0642011-11-08 19:10:03 -08004182class StringTable {
4183 public:
4184 StringTable() {
4185 }
4186
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004187 void Add(const char* s) {
Elliott Hughes545a0642011-11-08 19:10:03 -08004188 table_.insert(s);
4189 }
4190
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004191 size_t IndexOf(const char* s) const {
Mathieu Chartier02e25112013-08-14 16:14:24 -07004192 auto it = table_.find(s);
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004193 if (it == table_.end()) {
4194 LOG(FATAL) << "IndexOf(\"" << s << "\") failed";
4195 }
4196 return std::distance(table_.begin(), it);
Elliott Hughes545a0642011-11-08 19:10:03 -08004197 }
4198
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004199 size_t Size() const {
Elliott Hughes545a0642011-11-08 19:10:03 -08004200 return table_.size();
4201 }
4202
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004203 void WriteTo(std::vector<uint8_t>& bytes) const {
Mathieu Chartier02e25112013-08-14 16:14:24 -07004204 for (const std::string& str : table_) {
4205 const char* s = str.c_str();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004206 size_t s_len = CountModifiedUtf8Chars(s);
4207 UniquePtr<uint16_t> s_utf16(new uint16_t[s_len]);
4208 ConvertModifiedUtf8ToUtf16(s_utf16.get(), s);
4209 JDWP::AppendUtf16BE(bytes, s_utf16.get(), s_len);
Elliott Hughes545a0642011-11-08 19:10:03 -08004210 }
4211 }
4212
4213 private:
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004214 std::set<std::string> table_;
Elliott Hughes545a0642011-11-08 19:10:03 -08004215 DISALLOW_COPY_AND_ASSIGN(StringTable);
4216};
4217
Sebastien Hertz280286a2014-04-28 09:26:50 +02004218static const char* GetMethodSourceFile(MethodHelper* mh)
4219 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4220 DCHECK(mh != nullptr);
4221 const char* source_file = mh->GetDeclaringClassSourceFile();
4222 return (source_file != nullptr) ? source_file : "";
4223}
4224
Elliott Hughes545a0642011-11-08 19:10:03 -08004225/*
4226 * The data we send to DDMS contains everything we have recorded.
4227 *
4228 * Message header (all values big-endian):
4229 * (1b) message header len (to allow future expansion); includes itself
4230 * (1b) entry header len
4231 * (1b) stack frame len
4232 * (2b) number of entries
4233 * (4b) offset to string table from start of message
4234 * (2b) number of class name strings
4235 * (2b) number of method name strings
4236 * (2b) number of source file name strings
4237 * For each entry:
4238 * (4b) total allocation size
Elliott Hughes221229c2013-01-08 18:17:50 -08004239 * (2b) thread id
Elliott Hughes545a0642011-11-08 19:10:03 -08004240 * (2b) allocated object's class name index
4241 * (1b) stack depth
4242 * For each stack frame:
4243 * (2b) method's class name
4244 * (2b) method name
4245 * (2b) method source file
4246 * (2b) line number, clipped to 32767; -2 if native; -1 if no source
4247 * (xb) class name strings
4248 * (xb) method name strings
4249 * (xb) source file strings
4250 *
4251 * As with other DDM traffic, strings are sent as a 4-byte length
4252 * followed by UTF-16 data.
4253 *
4254 * We send up 16-bit unsigned indexes into string tables. In theory there
Elliott Hughesb1a58792013-07-11 18:10:58 -07004255 * can be (kMaxAllocRecordStackDepth * gAllocRecordMax) unique strings in
Elliott Hughes545a0642011-11-08 19:10:03 -08004256 * each table, but in practice there should be far fewer.
4257 *
4258 * The chief reason for using a string table here is to keep the size of
4259 * the DDMS message to a minimum. This is partly to make the protocol
4260 * efficient, but also because we have to form the whole thing up all at
4261 * once in a memory buffer.
4262 *
4263 * We use separate string tables for class names, method names, and source
4264 * files to keep the indexes small. There will generally be no overlap
4265 * between the contents of these tables.
4266 */
4267jbyteArray Dbg::GetRecentAllocations() {
4268 if (false) {
4269 DumpRecentAllocations();
4270 }
4271
Ian Rogers50b35e22012-10-04 10:09:15 -07004272 Thread* self = Thread::Current();
Elliott Hughes545a0642011-11-08 19:10:03 -08004273 std::vector<uint8_t> bytes;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004274 {
Ian Rogers719d1a32014-03-06 12:13:39 -08004275 MutexLock mu(self, *alloc_tracker_lock_);
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004276 //
4277 // Part 1: generate string tables.
4278 //
4279 StringTable class_names;
4280 StringTable method_names;
4281 StringTable filenames;
Elliott Hughes545a0642011-11-08 19:10:03 -08004282
Ian Rogers719d1a32014-03-06 12:13:39 -08004283 int count = alloc_record_count_;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004284 int idx = HeadIndex();
4285 while (count--) {
4286 AllocRecord* record = &recent_allocation_records_[idx];
Elliott Hughes545a0642011-11-08 19:10:03 -08004287
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004288 class_names.Add(ClassHelper(record->type).GetDescriptor());
Elliott Hughes545a0642011-11-08 19:10:03 -08004289
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004290 MethodHelper mh;
4291 for (size_t i = 0; i < kMaxAllocRecordStackDepth; i++) {
Brian Carlstromea46f952013-07-30 01:26:50 -07004292 mirror::ArtMethod* m = record->stack[i].method;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004293 if (m != NULL) {
4294 mh.ChangeMethod(m);
4295 class_names.Add(mh.GetDeclaringClassDescriptor());
4296 method_names.Add(mh.GetName());
Sebastien Hertz280286a2014-04-28 09:26:50 +02004297 filenames.Add(GetMethodSourceFile(&mh));
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004298 }
4299 }
Elliott Hughes545a0642011-11-08 19:10:03 -08004300
Ian Rogers719d1a32014-03-06 12:13:39 -08004301 idx = (idx + 1) & (alloc_record_max_ - 1);
Elliott Hughes545a0642011-11-08 19:10:03 -08004302 }
4303
Ian Rogers719d1a32014-03-06 12:13:39 -08004304 LOG(INFO) << "allocation records: " << alloc_record_count_;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004305
4306 //
4307 // Part 2: Generate the output and store it in the buffer.
4308 //
4309
4310 // (1b) message header len (to allow future expansion); includes itself
4311 // (1b) entry header len
4312 // (1b) stack frame len
4313 const int kMessageHeaderLen = 15;
4314 const int kEntryHeaderLen = 9;
4315 const int kStackFrameLen = 8;
4316 JDWP::Append1BE(bytes, kMessageHeaderLen);
4317 JDWP::Append1BE(bytes, kEntryHeaderLen);
4318 JDWP::Append1BE(bytes, kStackFrameLen);
4319
4320 // (2b) number of entries
4321 // (4b) offset to string table from start of message
4322 // (2b) number of class name strings
4323 // (2b) number of method name strings
4324 // (2b) number of source file name strings
Ian Rogers719d1a32014-03-06 12:13:39 -08004325 JDWP::Append2BE(bytes, alloc_record_count_);
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004326 size_t string_table_offset = bytes.size();
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004327 JDWP::Append4BE(bytes, 0); // We'll patch this later...
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004328 JDWP::Append2BE(bytes, class_names.Size());
4329 JDWP::Append2BE(bytes, method_names.Size());
4330 JDWP::Append2BE(bytes, filenames.Size());
4331
Ian Rogers719d1a32014-03-06 12:13:39 -08004332 count = alloc_record_count_;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004333 idx = HeadIndex();
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004334 while (count--) {
4335 // For each entry:
4336 // (4b) total allocation size
4337 // (2b) thread id
4338 // (2b) allocated object's class name index
4339 // (1b) stack depth
4340 AllocRecord* record = &recent_allocation_records_[idx];
4341 size_t stack_depth = record->GetDepth();
Mathieu Chartier590fee92013-09-13 13:46:47 -07004342 ClassHelper kh(record->type);
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004343 size_t allocated_object_class_name_index = class_names.IndexOf(kh.GetDescriptor());
4344 JDWP::Append4BE(bytes, record->byte_count);
4345 JDWP::Append2BE(bytes, record->thin_lock_id);
4346 JDWP::Append2BE(bytes, allocated_object_class_name_index);
4347 JDWP::Append1BE(bytes, stack_depth);
4348
4349 MethodHelper mh;
4350 for (size_t stack_frame = 0; stack_frame < stack_depth; ++stack_frame) {
4351 // For each stack frame:
4352 // (2b) method's class name
4353 // (2b) method name
4354 // (2b) method source file
4355 // (2b) line number, clipped to 32767; -2 if native; -1 if no source
4356 mh.ChangeMethod(record->stack[stack_frame].method);
4357 size_t class_name_index = class_names.IndexOf(mh.GetDeclaringClassDescriptor());
4358 size_t method_name_index = method_names.IndexOf(mh.GetName());
Sebastien Hertz280286a2014-04-28 09:26:50 +02004359 size_t file_name_index = filenames.IndexOf(GetMethodSourceFile(&mh));
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004360 JDWP::Append2BE(bytes, class_name_index);
4361 JDWP::Append2BE(bytes, method_name_index);
4362 JDWP::Append2BE(bytes, file_name_index);
4363 JDWP::Append2BE(bytes, record->stack[stack_frame].LineNumber());
4364 }
4365
Ian Rogers719d1a32014-03-06 12:13:39 -08004366 idx = (idx + 1) & (alloc_record_max_ - 1);
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004367 }
4368
4369 // (xb) class name strings
4370 // (xb) method name strings
4371 // (xb) source file strings
4372 JDWP::Set4BE(&bytes[string_table_offset], bytes.size());
4373 class_names.WriteTo(bytes);
4374 method_names.WriteTo(bytes);
4375 filenames.WriteTo(bytes);
Elliott Hughes545a0642011-11-08 19:10:03 -08004376 }
Ian Rogers50b35e22012-10-04 10:09:15 -07004377 JNIEnv* env = self->GetJniEnv();
Elliott Hughes545a0642011-11-08 19:10:03 -08004378 jbyteArray result = env->NewByteArray(bytes.size());
4379 if (result != NULL) {
4380 env->SetByteArrayRegion(result, 0, bytes.size(), reinterpret_cast<const jbyte*>(&bytes[0]));
4381 }
4382 return result;
4383}
4384
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004385} // namespace art