blob: c52a5887aa5d6bdf2c968f24ebe17904e96b2ab5 [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 Hertz138dbfc2013-12-04 18:15:25 +0100228
229// Breakpoints.
jeffhao09bfc6a2012-12-11 18:11:43 -0800230static std::vector<Breakpoint> gBreakpoints GUARDED_BY(Locks::breakpoint_lock_);
Elliott Hughes86964332012-02-15 19:37:42 -0800231
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700232void DebugInvokeReq::VisitRoots(RootCallback* callback, void* arg, uint32_t tid,
233 RootType root_type) {
234 if (receiver != nullptr) {
235 callback(&receiver, arg, tid, root_type);
236 }
237 if (thread != nullptr) {
238 callback(&thread, arg, tid, root_type);
239 }
240 if (klass != nullptr) {
241 callback(reinterpret_cast<mirror::Object**>(&klass), arg, tid, root_type);
242 }
243 if (method != nullptr) {
244 callback(reinterpret_cast<mirror::Object**>(&method), arg, tid, root_type);
245 }
246}
247
Sebastien Hertzbb43b432014-04-14 11:59:08 +0200248void DebugInvokeReq::Clear() {
249 invoke_needed = false;
250 receiver = nullptr;
251 thread = nullptr;
252 klass = nullptr;
253 method = nullptr;
254}
255
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700256void SingleStepControl::VisitRoots(RootCallback* callback, void* arg, uint32_t tid,
257 RootType root_type) {
258 if (method != nullptr) {
259 callback(reinterpret_cast<mirror::Object**>(&method), arg, tid, root_type);
260 }
261}
262
Sebastien Hertzbb43b432014-04-14 11:59:08 +0200263bool SingleStepControl::ContainsDexPc(uint32_t dex_pc) const {
264 return dex_pcs.find(dex_pc) == dex_pcs.end();
265}
266
267void SingleStepControl::Clear() {
268 is_active = false;
269 method = nullptr;
270 dex_pcs.clear();
271}
272
Sebastien Hertz4d25df32014-03-21 17:44:46 +0100273void DeoptimizationRequest::VisitRoots(RootCallback* callback, void* arg) {
274 if (method != nullptr) {
275 callback(reinterpret_cast<mirror::Object**>(&method), arg, 0, kRootDebugger);
276 }
277}
278
Brian Carlstromea46f952013-07-30 01:26:50 -0700279static bool IsBreakpoint(const mirror::ArtMethod* m, uint32_t dex_pc)
jeffhao09bfc6a2012-12-11 18:11:43 -0800280 LOCKS_EXCLUDED(Locks::breakpoint_lock_)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700281 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
jeffhao09bfc6a2012-12-11 18:11:43 -0800282 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100283 for (size_t i = 0, e = gBreakpoints.size(); i < e; ++i) {
Elliott Hughesa656a0f2012-02-21 18:03:44 -0800284 if (gBreakpoints[i].method == m && gBreakpoints[i].dex_pc == dex_pc) {
Elliott Hughes86964332012-02-15 19:37:42 -0800285 VLOG(jdwp) << "Hit breakpoint #" << i << ": " << gBreakpoints[i];
286 return true;
287 }
288 }
289 return false;
290}
291
Sebastien Hertz52d131d2014-03-13 16:17:40 +0100292static bool IsSuspendedForDebugger(ScopedObjectAccessUnchecked& soa, Thread* thread)
293 LOCKS_EXCLUDED(Locks::thread_suspend_count_lock_) {
Elliott Hughes9e0c1752013-01-09 14:02:58 -0800294 MutexLock mu(soa.Self(), *Locks::thread_suspend_count_lock_);
295 // A thread may be suspended for GC; in this code, we really want to know whether
296 // there's a debugger suspension active.
297 return thread->IsSuspended() && thread->GetDebugSuspendCount() > 0;
298}
299
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800300static mirror::Array* DecodeArray(JDWP::RefTypeId id, JDWP::JdwpError& status)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700301 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800302 mirror::Object* o = gRegistry->Get<mirror::Object*>(id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800303 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800304 status = JDWP::ERR_INVALID_OBJECT;
305 return NULL;
306 }
307 if (!o->IsArrayInstance()) {
308 status = JDWP::ERR_INVALID_ARRAY;
309 return NULL;
310 }
311 status = JDWP::ERR_NONE;
312 return o->AsArray();
313}
314
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800315static mirror::Class* DecodeClass(JDWP::RefTypeId id, JDWP::JdwpError& status)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700316 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800317 mirror::Object* o = gRegistry->Get<mirror::Object*>(id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800318 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800319 status = JDWP::ERR_INVALID_OBJECT;
320 return NULL;
321 }
322 if (!o->IsClass()) {
323 status = JDWP::ERR_INVALID_CLASS;
324 return NULL;
325 }
326 status = JDWP::ERR_NONE;
327 return o->AsClass();
328}
329
Elliott Hughes221229c2013-01-08 18:17:50 -0800330static JDWP::JdwpError DecodeThread(ScopedObjectAccessUnchecked& soa, JDWP::ObjectId thread_id, Thread*& thread)
jeffhaoa77f0f62012-12-05 17:19:31 -0800331 EXCLUSIVE_LOCKS_REQUIRED(Locks::thread_list_lock_)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700332 LOCKS_EXCLUDED(Locks::thread_suspend_count_lock_)
333 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800334 mirror::Object* thread_peer = gRegistry->Get<mirror::Object*>(thread_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800335 if (thread_peer == NULL || thread_peer == ObjectRegistry::kInvalidObject) {
Elliott Hughes221229c2013-01-08 18:17:50 -0800336 // This isn't even an object.
337 return JDWP::ERR_INVALID_OBJECT;
Elliott Hughes436e3722012-02-17 20:01:47 -0800338 }
Elliott Hughes221229c2013-01-08 18:17:50 -0800339
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800340 mirror::Class* java_lang_Thread = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_Thread);
Elliott Hughes221229c2013-01-08 18:17:50 -0800341 if (!java_lang_Thread->IsAssignableFrom(thread_peer->GetClass())) {
342 // This isn't a thread.
343 return JDWP::ERR_INVALID_THREAD;
344 }
345
346 thread = Thread::FromManagedThread(soa, thread_peer);
347 if (thread == NULL) {
348 // This is a java.lang.Thread without a Thread*. Must be a zombie.
349 return JDWP::ERR_THREAD_NOT_ALIVE;
350 }
351 return JDWP::ERR_NONE;
Elliott Hughes436e3722012-02-17 20:01:47 -0800352}
353
Elliott Hughes24437992011-11-30 14:49:33 -0800354static JDWP::JdwpTag BasicTagFromDescriptor(const char* descriptor) {
355 // JDWP deliberately uses the descriptor characters' ASCII values for its enum.
356 // Note that by "basic" we mean that we don't get more specific than JT_OBJECT.
357 return static_cast<JDWP::JdwpTag>(descriptor[0]);
358}
359
Ian Rogers98379392014-02-24 16:53:16 -0800360static JDWP::JdwpTag TagFromClass(const ScopedObjectAccessUnchecked& soa, mirror::Class* c)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700361 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes86b00102011-12-05 17:54:26 -0800362 CHECK(c != NULL);
Elliott Hughes24437992011-11-30 14:49:33 -0800363 if (c->IsArrayClass()) {
364 return JDWP::JT_ARRAY;
365 }
Elliott Hughes24437992011-11-30 14:49:33 -0800366 if (c->IsStringClass()) {
367 return JDWP::JT_STRING;
Elliott Hughes24437992011-11-30 14:49:33 -0800368 }
Ian Rogers98379392014-02-24 16:53:16 -0800369 if (c->IsClassClass()) {
370 return JDWP::JT_CLASS_OBJECT;
371 }
372 {
373 mirror::Class* thread_class = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_Thread);
374 if (thread_class->IsAssignableFrom(c)) {
375 return JDWP::JT_THREAD;
376 }
377 }
378 {
379 mirror::Class* thread_group_class =
380 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_ThreadGroup);
381 if (thread_group_class->IsAssignableFrom(c)) {
382 return JDWP::JT_THREAD_GROUP;
383 }
384 }
385 {
386 mirror::Class* class_loader_class =
387 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_ClassLoader);
388 if (class_loader_class->IsAssignableFrom(c)) {
389 return JDWP::JT_CLASS_LOADER;
390 }
391 }
392 return JDWP::JT_OBJECT;
Elliott Hughes24437992011-11-30 14:49:33 -0800393}
394
395/*
396 * Objects declared to hold Object might actually hold a more specific
397 * type. The debugger may take a special interest in these (e.g. it
398 * wants to display the contents of Strings), so we want to return an
399 * appropriate tag.
400 *
401 * Null objects are tagged JT_OBJECT.
402 */
Ian Rogers98379392014-02-24 16:53:16 -0800403static JDWP::JdwpTag TagFromObject(const ScopedObjectAccessUnchecked& soa, mirror::Object* o)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700404 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers98379392014-02-24 16:53:16 -0800405 return (o == NULL) ? JDWP::JT_OBJECT : TagFromClass(soa, o->GetClass());
Elliott Hughes24437992011-11-30 14:49:33 -0800406}
407
408static bool IsPrimitiveTag(JDWP::JdwpTag tag) {
409 switch (tag) {
410 case JDWP::JT_BOOLEAN:
411 case JDWP::JT_BYTE:
412 case JDWP::JT_CHAR:
413 case JDWP::JT_FLOAT:
414 case JDWP::JT_DOUBLE:
415 case JDWP::JT_INT:
416 case JDWP::JT_LONG:
417 case JDWP::JT_SHORT:
418 case JDWP::JT_VOID:
419 return true;
420 default:
421 return false;
422 }
423}
424
Elliott Hughes3bb81562011-10-21 18:52:59 -0700425/*
426 * Handle one of the JDWP name/value pairs.
427 *
428 * JDWP options are:
429 * help: if specified, show help message and bail
430 * transport: may be dt_socket or dt_shmem
431 * address: for dt_socket, "host:port", or just "port" when listening
432 * server: if "y", wait for debugger to attach; if "n", attach to debugger
433 * timeout: how long to wait for debugger to connect / listen
434 *
435 * Useful with server=n (these aren't supported yet):
436 * onthrow=<exception-name>: connect to debugger when exception thrown
437 * onuncaught=y|n: connect to debugger when uncaught exception thrown
438 * launch=<command-line>: launch the debugger itself
439 *
440 * The "transport" option is required, as is "address" if server=n.
441 */
442static bool ParseJdwpOption(const std::string& name, const std::string& value) {
443 if (name == "transport") {
444 if (value == "dt_socket") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700445 gJdwpOptions.transport = JDWP::kJdwpTransportSocket;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700446 } else if (value == "dt_android_adb") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700447 gJdwpOptions.transport = JDWP::kJdwpTransportAndroidAdb;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700448 } else {
449 LOG(ERROR) << "JDWP transport not supported: " << value;
450 return false;
451 }
452 } else if (name == "server") {
453 if (value == "n") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700454 gJdwpOptions.server = false;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700455 } else if (value == "y") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700456 gJdwpOptions.server = true;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700457 } else {
458 LOG(ERROR) << "JDWP option 'server' must be 'y' or 'n'";
459 return false;
460 }
461 } else if (name == "suspend") {
462 if (value == "n") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700463 gJdwpOptions.suspend = false;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700464 } else if (value == "y") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700465 gJdwpOptions.suspend = true;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700466 } else {
467 LOG(ERROR) << "JDWP option 'suspend' must be 'y' or 'n'";
468 return false;
469 }
470 } else if (name == "address") {
471 /* this is either <port> or <host>:<port> */
472 std::string port_string;
Elliott Hughes376a7a02011-10-24 18:35:55 -0700473 gJdwpOptions.host.clear();
Elliott Hughes3bb81562011-10-21 18:52:59 -0700474 std::string::size_type colon = value.find(':');
475 if (colon != std::string::npos) {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700476 gJdwpOptions.host = value.substr(0, colon);
Elliott Hughes3bb81562011-10-21 18:52:59 -0700477 port_string = value.substr(colon + 1);
478 } else {
479 port_string = value;
480 }
481 if (port_string.empty()) {
482 LOG(ERROR) << "JDWP address missing port: " << value;
483 return false;
484 }
485 char* end;
Elliott Hughesba8eee12012-01-24 20:25:24 -0800486 uint64_t port = strtoul(port_string.c_str(), &end, 10);
487 if (*end != '\0' || port > 0xffff) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700488 LOG(ERROR) << "JDWP address has junk in port field: " << value;
489 return false;
490 }
Elliott Hughes376a7a02011-10-24 18:35:55 -0700491 gJdwpOptions.port = port;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700492 } else if (name == "launch" || name == "onthrow" || name == "oncaught" || name == "timeout") {
493 /* valid but unsupported */
494 LOG(INFO) << "Ignoring JDWP option '" << name << "'='" << value << "'";
495 } else {
496 LOG(INFO) << "Ignoring unrecognized JDWP option '" << name << "'='" << value << "'";
497 }
498
499 return true;
500}
501
502/*
503 * Parse the latter half of a -Xrunjdwp/-agentlib:jdwp= string, e.g.:
504 * "transport=dt_socket,address=8000,server=y,suspend=n"
505 */
506bool Dbg::ParseJdwpOptions(const std::string& options) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800507 VLOG(jdwp) << "ParseJdwpOptions: " << options;
Elliott Hughes47fce012011-10-25 18:37:19 -0700508
Elliott Hughes3bb81562011-10-21 18:52:59 -0700509 std::vector<std::string> pairs;
510 Split(options, ',', pairs);
511
512 for (size_t i = 0; i < pairs.size(); ++i) {
513 std::string::size_type equals = pairs[i].find('=');
514 if (equals == std::string::npos) {
515 LOG(ERROR) << "Can't parse JDWP option '" << pairs[i] << "' in '" << options << "'";
516 return false;
517 }
518 ParseJdwpOption(pairs[i].substr(0, equals), pairs[i].substr(equals + 1));
519 }
520
Elliott Hughes376a7a02011-10-24 18:35:55 -0700521 if (gJdwpOptions.transport == JDWP::kJdwpTransportUnknown) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700522 LOG(ERROR) << "Must specify JDWP transport: " << options;
523 }
Elliott Hughes376a7a02011-10-24 18:35:55 -0700524 if (!gJdwpOptions.server && (gJdwpOptions.host.empty() || gJdwpOptions.port == 0)) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700525 LOG(ERROR) << "Must specify JDWP host and port when server=n: " << options;
526 return false;
527 }
528
529 gJdwpConfigured = true;
530 return true;
531}
532
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700533void Dbg::StartJdwp() {
Elliott Hughesc0f09332012-03-26 13:27:06 -0700534 if (!gJdwpAllowed || !IsJdwpConfigured()) {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700535 // No JDWP for you!
536 return;
537 }
538
Ian Rogers719d1a32014-03-06 12:13:39 -0800539 CHECK(gRegistry == nullptr);
Elliott Hughes475fc232011-10-25 15:00:35 -0700540 gRegistry = new ObjectRegistry;
541
Ian Rogers719d1a32014-03-06 12:13:39 -0800542 alloc_tracker_lock_ = new Mutex("AllocTracker lock");
Sebastien Hertz4d25df32014-03-21 17:44:46 +0100543 deoptimization_lock_ = new Mutex("deoptimization lock", kDeoptimizationLock);
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700544 // Init JDWP if the debugger is enabled. This may connect out to a
545 // debugger, passively listen for a debugger, or block waiting for a
546 // debugger.
Elliott Hughes376a7a02011-10-24 18:35:55 -0700547 gJdwpState = JDWP::JdwpState::Create(&gJdwpOptions);
548 if (gJdwpState == NULL) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -0800549 // We probably failed because some other process has the port already, which means that
550 // if we don't abort the user is likely to think they're talking to us when they're actually
551 // talking to that other process.
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800552 LOG(FATAL) << "Debugger thread failed to initialize";
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700553 }
554
555 // If a debugger has already attached, send the "welcome" message.
556 // This may cause us to suspend all threads.
Elliott Hughes376a7a02011-10-24 18:35:55 -0700557 if (gJdwpState->IsActive()) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700558 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes376a7a02011-10-24 18:35:55 -0700559 if (!gJdwpState->PostVMStart()) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800560 LOG(WARNING) << "Failed to post 'start' message to debugger";
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700561 }
562 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700563}
564
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700565void Dbg::VisitRoots(RootCallback* callback, void* arg) {
Sebastien Hertz4d25df32014-03-21 17:44:46 +0100566 {
567 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
568 for (Breakpoint& bp : gBreakpoints) {
569 bp.VisitRoots(callback, arg);
570 }
571 }
572 if (deoptimization_lock_ != nullptr) { // only true if the debugger is started.
573 MutexLock mu(Thread::Current(), *deoptimization_lock_);
574 for (DeoptimizationRequest& req : deoptimization_requests_) {
575 req.VisitRoots(callback, arg);
576 }
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700577 }
578}
579
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700580void Dbg::StopJdwp() {
Sebastien Hertz0376e6b2014-02-06 18:12:59 +0100581 // Prevent the JDWP thread from processing JDWP incoming packets after we close the connection.
582 Disposed();
Elliott Hughes376a7a02011-10-24 18:35:55 -0700583 delete gJdwpState;
Ian Rogers719d1a32014-03-06 12:13:39 -0800584 gJdwpState = nullptr;
Elliott Hughes475fc232011-10-25 15:00:35 -0700585 delete gRegistry;
Ian Rogers719d1a32014-03-06 12:13:39 -0800586 gRegistry = nullptr;
587 delete alloc_tracker_lock_;
588 alloc_tracker_lock_ = nullptr;
Sebastien Hertz4d25df32014-03-21 17:44:46 +0100589 delete deoptimization_lock_;
590 deoptimization_lock_ = nullptr;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700591}
592
Elliott Hughes767a1472011-10-26 18:49:02 -0700593void Dbg::GcDidFinish() {
594 if (gDdmHpifWhen != HPIF_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700595 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes81ff3182012-03-23 20:35:56 -0700596 LOG(DEBUG) << "Sending heap info to DDM";
Elliott Hughes7162ad92011-10-27 14:08:42 -0700597 DdmSendHeapInfo(gDdmHpifWhen);
Elliott Hughes767a1472011-10-26 18:49:02 -0700598 }
599 if (gDdmHpsgWhen != HPSG_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700600 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes81ff3182012-03-23 20:35:56 -0700601 LOG(DEBUG) << "Dumping heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700602 DdmSendHeapSegments(false);
Elliott Hughes767a1472011-10-26 18:49:02 -0700603 }
604 if (gDdmNhsgWhen != HPSG_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700605 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes767a1472011-10-26 18:49:02 -0700606 LOG(DEBUG) << "Dumping native heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700607 DdmSendHeapSegments(true);
Elliott Hughes767a1472011-10-26 18:49:02 -0700608 }
609}
610
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700611void Dbg::SetJdwpAllowed(bool allowed) {
612 gJdwpAllowed = allowed;
613}
614
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700615DebugInvokeReq* Dbg::GetInvokeReq() {
Elliott Hughes475fc232011-10-25 15:00:35 -0700616 return Thread::Current()->GetInvokeReq();
617}
618
619Thread* Dbg::GetDebugThread() {
620 return (gJdwpState != NULL) ? gJdwpState->GetDebugThread() : NULL;
621}
622
623void Dbg::ClearWaitForEventThread() {
624 gJdwpState->ClearWaitForEventThread();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700625}
626
627void Dbg::Connected() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700628 CHECK(!gDebuggerConnected);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800629 VLOG(jdwp) << "JDWP has attached";
Elliott Hughes3bb81562011-10-21 18:52:59 -0700630 gDebuggerConnected = true;
Elliott Hughes86964332012-02-15 19:37:42 -0800631 gDisposed = false;
632}
633
634void Dbg::Disposed() {
635 gDisposed = true;
636}
637
638bool Dbg::IsDisposed() {
639 return gDisposed;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700640}
641
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200642// All the instrumentation events the debugger is registered for.
643static constexpr uint32_t kListenerEvents = instrumentation::Instrumentation::kMethodEntered |
644 instrumentation::Instrumentation::kMethodExited |
645 instrumentation::Instrumentation::kDexPcMoved |
646 instrumentation::Instrumentation::kFieldRead |
647 instrumentation::Instrumentation::kFieldWritten |
648 instrumentation::Instrumentation::kExceptionCaught;
649
Elliott Hughesa2155262011-11-16 16:26:58 -0800650void Dbg::GoActive() {
651 // Enable all debugging features, including scans for breakpoints.
652 // This is a no-op if we're already active.
653 // Only called from the JDWP handler thread.
654 if (gDebuggerActive) {
655 return;
656 }
657
Elliott Hughesc0f09332012-03-26 13:27:06 -0700658 {
659 // TODO: dalvik only warned if there were breakpoints left over. clear in Dbg::Disconnected?
jeffhao09bfc6a2012-12-11 18:11:43 -0800660 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Elliott Hughesc0f09332012-03-26 13:27:06 -0700661 CHECK_EQ(gBreakpoints.size(), 0U);
662 }
Elliott Hughesa2155262011-11-16 16:26:58 -0800663
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100664 {
Sebastien Hertz4d25df32014-03-21 17:44:46 +0100665 MutexLock mu(Thread::Current(), *deoptimization_lock_);
666 CHECK_EQ(deoptimization_requests_.size(), 0U);
667 CHECK_EQ(full_deoptimization_event_count_, 0U);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100668 }
669
Ian Rogers62d6c772013-02-27 08:32:07 -0800670 Runtime* runtime = Runtime::Current();
671 runtime->GetThreadList()->SuspendAll();
672 Thread* self = Thread::Current();
673 ThreadState old_state = self->SetStateUnsafe(kRunnable);
674 CHECK_NE(old_state, kRunnable);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100675 runtime->GetInstrumentation()->EnableDeoptimization();
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200676 runtime->GetInstrumentation()->AddListener(&gDebugInstrumentationListener, kListenerEvents);
Elliott Hughesa2155262011-11-16 16:26:58 -0800677 gDebuggerActive = true;
Ian Rogers62d6c772013-02-27 08:32:07 -0800678 CHECK_EQ(self->SetStateUnsafe(old_state), kRunnable);
679 runtime->GetThreadList()->ResumeAll();
680
681 LOG(INFO) << "Debugger is active";
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700682}
683
684void Dbg::Disconnected() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700685 CHECK(gDebuggerConnected);
686
Elliott Hughesc0f09332012-03-26 13:27:06 -0700687 LOG(INFO) << "Debugger is no longer active";
Elliott Hughes234ab152011-10-26 14:02:26 -0700688
Ian Rogers62d6c772013-02-27 08:32:07 -0800689 // Suspend all threads and exclusively acquire the mutator lock. Set the state of the thread
690 // to kRunnable to avoid scoped object access transitions. Remove the debugger as a listener
691 // and clear the object registry.
692 Runtime* runtime = Runtime::Current();
693 runtime->GetThreadList()->SuspendAll();
694 Thread* self = Thread::Current();
695 ThreadState old_state = self->SetStateUnsafe(kRunnable);
Sebastien Hertzaaea7342014-02-25 15:10:04 +0100696
697 // Debugger may not be active at this point.
698 if (gDebuggerActive) {
699 {
700 // Since we're going to disable deoptimization, we clear the deoptimization requests queue.
701 // This prevents us from having any pending deoptimization request when the debugger attaches
702 // to us again while no event has been requested yet.
Sebastien Hertz4d25df32014-03-21 17:44:46 +0100703 MutexLock mu(Thread::Current(), *deoptimization_lock_);
704 deoptimization_requests_.clear();
705 full_deoptimization_event_count_ = 0U;
Sebastien Hertzaaea7342014-02-25 15:10:04 +0100706 }
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200707 runtime->GetInstrumentation()->RemoveListener(&gDebugInstrumentationListener, kListenerEvents);
Sebastien Hertzaaea7342014-02-25 15:10:04 +0100708 runtime->GetInstrumentation()->DisableDeoptimization();
709 gDebuggerActive = false;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100710 }
Elliott Hughes234ab152011-10-26 14:02:26 -0700711 gRegistry->Clear();
712 gDebuggerConnected = false;
Ian Rogers62d6c772013-02-27 08:32:07 -0800713 CHECK_EQ(self->SetStateUnsafe(old_state), kRunnable);
714 runtime->GetThreadList()->ResumeAll();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700715}
716
Elliott Hughesc0f09332012-03-26 13:27:06 -0700717bool Dbg::IsDebuggerActive() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700718 return gDebuggerActive;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700719}
720
Elliott Hughesc0f09332012-03-26 13:27:06 -0700721bool Dbg::IsJdwpConfigured() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700722 return gJdwpConfigured;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700723}
724
725int64_t Dbg::LastDebuggerActivity() {
Elliott Hughesca951522011-12-05 12:01:32 -0800726 return gJdwpState->LastDebuggerActivity();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700727}
728
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700729void Dbg::UndoDebuggerSuspensions() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700730 Runtime::Current()->GetThreadList()->UndoDebuggerSuspensions();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700731}
732
Elliott Hughes88d63092013-01-09 09:55:54 -0800733std::string Dbg::GetClassName(JDWP::RefTypeId class_id) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800734 mirror::Object* o = gRegistry->Get<mirror::Object*>(class_id);
Elliott Hughes436e3722012-02-17 20:01:47 -0800735 if (o == NULL) {
736 return "NULL";
737 }
Elliott Hughes64f574f2013-02-20 14:57:12 -0800738 if (o == ObjectRegistry::kInvalidObject) {
Elliott Hughes88d63092013-01-09 09:55:54 -0800739 return StringPrintf("invalid object %p", reinterpret_cast<void*>(class_id));
Elliott Hughes436e3722012-02-17 20:01:47 -0800740 }
741 if (!o->IsClass()) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700742 return StringPrintf("non-class %p", o); // This is only used for debugging output anyway.
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800743 }
Elliott Hughesc308a5d2012-02-16 17:12:06 -0800744 return DescriptorToName(ClassHelper(o->AsClass()).GetDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700745}
746
Elliott Hughes88d63092013-01-09 09:55:54 -0800747JDWP::JdwpError Dbg::GetClassObject(JDWP::RefTypeId id, JDWP::ObjectId& class_object_id) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800748 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800749 mirror::Class* c = DecodeClass(id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -0800750 if (c == NULL) {
751 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800752 }
Elliott Hughes88d63092013-01-09 09:55:54 -0800753 class_object_id = gRegistry->Add(c);
Elliott Hughes436e3722012-02-17 20:01:47 -0800754 return JDWP::ERR_NONE;
Elliott Hughes86964332012-02-15 19:37:42 -0800755}
756
Elliott Hughes88d63092013-01-09 09:55:54 -0800757JDWP::JdwpError Dbg::GetSuperclass(JDWP::RefTypeId id, JDWP::RefTypeId& superclass_id) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800758 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800759 mirror::Class* c = DecodeClass(id, status);
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800760 if (c == NULL) {
761 return status;
762 }
763 if (c->IsInterface()) {
764 // http://code.google.com/p/android/issues/detail?id=20856
Elliott Hughes88d63092013-01-09 09:55:54 -0800765 superclass_id = 0;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800766 } else {
Elliott Hughes88d63092013-01-09 09:55:54 -0800767 superclass_id = gRegistry->Add(c->GetSuperClass());
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800768 }
769 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700770}
771
Elliott Hughes436e3722012-02-17 20:01:47 -0800772JDWP::JdwpError Dbg::GetClassLoader(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800773 mirror::Object* o = gRegistry->Get<mirror::Object*>(id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800774 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800775 return JDWP::ERR_INVALID_OBJECT;
776 }
777 expandBufAddObjectId(pReply, gRegistry->Add(o->GetClass()->GetClassLoader()));
778 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700779}
780
Elliott Hughes436e3722012-02-17 20:01:47 -0800781JDWP::JdwpError Dbg::GetModifiers(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) {
782 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800783 mirror::Class* c = DecodeClass(id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -0800784 if (c == NULL) {
785 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800786 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800787
788 uint32_t access_flags = c->GetAccessFlags() & kAccJavaFlagsMask;
789
Yevgeny Roubande34eea2014-02-15 01:06:03 +0700790 // Set ACC_SUPER. Dex files don't contain this flag but only classes are supposed to have it set,
791 // not interfaces.
Elliott Hughes436e3722012-02-17 20:01:47 -0800792 // Class.getModifiers doesn't return it, but JDWP does, so we set it here.
Yevgeny Roubande34eea2014-02-15 01:06:03 +0700793 if ((access_flags & kAccInterface) == 0) {
794 access_flags |= kAccSuper;
795 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800796
797 expandBufAdd4BE(pReply, access_flags);
798
799 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700800}
801
Elliott Hughesf327e072013-01-09 16:01:26 -0800802JDWP::JdwpError Dbg::GetMonitorInfo(JDWP::ObjectId object_id, JDWP::ExpandBuf* reply)
803 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800804 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800805 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughesf327e072013-01-09 16:01:26 -0800806 return JDWP::ERR_INVALID_OBJECT;
807 }
808
809 // Ensure all threads are suspended while we read objects' lock words.
810 Thread* self = Thread::Current();
Sebastien Hertz54263242014-03-19 18:16:50 +0100811 CHECK_EQ(self->GetState(), kRunnable);
812 self->TransitionFromRunnableToSuspended(kSuspended);
813 Runtime::Current()->GetThreadList()->SuspendAll();
Elliott Hughesf327e072013-01-09 16:01:26 -0800814
815 MonitorInfo monitor_info(o);
816
Sebastien Hertz54263242014-03-19 18:16:50 +0100817 Runtime::Current()->GetThreadList()->ResumeAll();
818 self->TransitionFromSuspendedToRunnable();
Elliott Hughesf327e072013-01-09 16:01:26 -0800819
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700820 if (monitor_info.owner_ != NULL) {
821 expandBufAddObjectId(reply, gRegistry->Add(monitor_info.owner_->GetPeer()));
Elliott Hughesf327e072013-01-09 16:01:26 -0800822 } else {
823 expandBufAddObjectId(reply, gRegistry->Add(NULL));
824 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700825 expandBufAdd4BE(reply, monitor_info.entry_count_);
826 expandBufAdd4BE(reply, monitor_info.waiters_.size());
827 for (size_t i = 0; i < monitor_info.waiters_.size(); ++i) {
828 expandBufAddObjectId(reply, gRegistry->Add(monitor_info.waiters_[i]->GetPeer()));
Elliott Hughesf327e072013-01-09 16:01:26 -0800829 }
830 return JDWP::ERR_NONE;
831}
832
Elliott Hughes734b8c62013-01-11 15:32:45 -0800833JDWP::JdwpError Dbg::GetOwnedMonitors(JDWP::ObjectId thread_id,
834 std::vector<JDWP::ObjectId>& monitors,
Sebastien Hertz52d131d2014-03-13 16:17:40 +0100835 std::vector<uint32_t>& stack_depths) {
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800836 ScopedObjectAccessUnchecked soa(Thread::Current());
837 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
838 Thread* thread;
839 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
840 if (error != JDWP::ERR_NONE) {
841 return error;
842 }
843 if (!IsSuspendedForDebugger(soa, thread)) {
844 return JDWP::ERR_THREAD_NOT_SUSPENDED;
845 }
846
847 struct OwnedMonitorVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -0800848 OwnedMonitorVisitor(Thread* thread, Context* context)
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800849 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -0800850 : StackVisitor(thread, context), current_stack_depth(0) {}
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800851
852 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
853 // annotalysis.
854 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
855 if (!GetMethod()->IsRuntimeMethod()) {
856 Monitor::VisitLocks(this, AppendOwnedMonitors, this);
Elliott Hughes734b8c62013-01-11 15:32:45 -0800857 ++current_stack_depth;
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800858 }
859 return true;
860 }
861
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800862 static void AppendOwnedMonitors(mirror::Object* owned_monitor, void* arg) {
Ian Rogers7a22fa62013-01-23 12:16:16 -0800863 OwnedMonitorVisitor* visitor = reinterpret_cast<OwnedMonitorVisitor*>(arg);
Elliott Hughes734b8c62013-01-11 15:32:45 -0800864 visitor->monitors.push_back(owned_monitor);
865 visitor->stack_depths.push_back(visitor->current_stack_depth);
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800866 }
867
Elliott Hughes734b8c62013-01-11 15:32:45 -0800868 size_t current_stack_depth;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800869 std::vector<mirror::Object*> monitors;
Elliott Hughes734b8c62013-01-11 15:32:45 -0800870 std::vector<uint32_t> stack_depths;
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800871 };
Ian Rogers7a22fa62013-01-23 12:16:16 -0800872 UniquePtr<Context> context(Context::Create());
873 OwnedMonitorVisitor visitor(thread, context.get());
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800874 visitor.WalkStack();
875
876 for (size_t i = 0; i < visitor.monitors.size(); ++i) {
877 monitors.push_back(gRegistry->Add(visitor.monitors[i]));
Elliott Hughes734b8c62013-01-11 15:32:45 -0800878 stack_depths.push_back(visitor.stack_depths[i]);
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800879 }
880
881 return JDWP::ERR_NONE;
882}
883
Sebastien Hertz52d131d2014-03-13 16:17:40 +0100884JDWP::JdwpError Dbg::GetContendedMonitor(JDWP::ObjectId thread_id,
885 JDWP::ObjectId& contended_monitor) {
Elliott Hughesf9501702013-01-11 11:22:27 -0800886 ScopedObjectAccessUnchecked soa(Thread::Current());
887 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
888 Thread* thread;
889 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
890 if (error != JDWP::ERR_NONE) {
891 return error;
892 }
893 if (!IsSuspendedForDebugger(soa, thread)) {
894 return JDWP::ERR_THREAD_NOT_SUSPENDED;
895 }
896
897 contended_monitor = gRegistry->Add(Monitor::GetContendedMonitor(thread));
898
899 return JDWP::ERR_NONE;
900}
901
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800902JDWP::JdwpError Dbg::GetInstanceCounts(const std::vector<JDWP::RefTypeId>& class_ids,
903 std::vector<uint64_t>& counts)
904 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800905 gc::Heap* heap = Runtime::Current()->GetHeap();
906 heap->CollectGarbage(false);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800907 std::vector<mirror::Class*> classes;
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800908 counts.clear();
909 for (size_t i = 0; i < class_ids.size(); ++i) {
910 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800911 mirror::Class* c = DecodeClass(class_ids[i], status);
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800912 if (c == NULL) {
913 return status;
914 }
915 classes.push_back(c);
916 counts.push_back(0);
917 }
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800918 heap->CountInstances(classes, false, &counts[0]);
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800919 return JDWP::ERR_NONE;
920}
921
Elliott Hughes3b78c942013-01-15 17:35:41 -0800922JDWP::JdwpError Dbg::GetInstances(JDWP::RefTypeId class_id, int32_t max_count, std::vector<JDWP::ObjectId>& instances)
923 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800924 gc::Heap* heap = Runtime::Current()->GetHeap();
925 // We only want reachable instances, so do a GC.
926 heap->CollectGarbage(false);
Elliott Hughes3b78c942013-01-15 17:35:41 -0800927 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800928 mirror::Class* c = DecodeClass(class_id, status);
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800929 if (c == nullptr) {
Elliott Hughes3b78c942013-01-15 17:35:41 -0800930 return status;
931 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800932 std::vector<mirror::Object*> raw_instances;
Elliott Hughes3b78c942013-01-15 17:35:41 -0800933 Runtime::Current()->GetHeap()->GetInstances(c, max_count, raw_instances);
934 for (size_t i = 0; i < raw_instances.size(); ++i) {
935 instances.push_back(gRegistry->Add(raw_instances[i]));
936 }
937 return JDWP::ERR_NONE;
938}
939
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800940JDWP::JdwpError Dbg::GetReferringObjects(JDWP::ObjectId object_id, int32_t max_count,
941 std::vector<JDWP::ObjectId>& referring_objects)
942 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800943 gc::Heap* heap = Runtime::Current()->GetHeap();
944 heap->CollectGarbage(false);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800945 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800946 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800947 return JDWP::ERR_INVALID_OBJECT;
948 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800949 std::vector<mirror::Object*> raw_instances;
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800950 heap->GetReferringObjects(o, max_count, raw_instances);
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800951 for (size_t i = 0; i < raw_instances.size(); ++i) {
952 referring_objects.push_back(gRegistry->Add(raw_instances[i]));
953 }
954 return JDWP::ERR_NONE;
955}
956
Elliott Hughes64f574f2013-02-20 14:57:12 -0800957JDWP::JdwpError Dbg::DisableCollection(JDWP::ObjectId object_id)
958 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Sebastien Hertze96060a2013-12-11 12:06:28 +0100959 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
960 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
961 return JDWP::ERR_INVALID_OBJECT;
962 }
Elliott Hughes64f574f2013-02-20 14:57:12 -0800963 gRegistry->DisableCollection(object_id);
964 return JDWP::ERR_NONE;
965}
966
967JDWP::JdwpError Dbg::EnableCollection(JDWP::ObjectId object_id)
968 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Sebastien Hertze96060a2013-12-11 12:06:28 +0100969 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
970 // Unlike DisableCollection, JDWP specs do not state an invalid object causes an error. The RI
971 // also ignores these cases and never return an error. However it's not obvious why this command
972 // should behave differently from DisableCollection and IsCollected commands. So let's be more
973 // strict and return an error if this happens.
974 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
975 return JDWP::ERR_INVALID_OBJECT;
976 }
Elliott Hughes64f574f2013-02-20 14:57:12 -0800977 gRegistry->EnableCollection(object_id);
978 return JDWP::ERR_NONE;
979}
980
981JDWP::JdwpError Dbg::IsCollected(JDWP::ObjectId object_id, bool& is_collected)
982 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Sebastien Hertz65637eb2014-01-10 17:40:02 +0100983 if (object_id == 0) {
984 // Null object id is invalid.
Sebastien Hertze96060a2013-12-11 12:06:28 +0100985 return JDWP::ERR_INVALID_OBJECT;
986 }
Sebastien Hertz65637eb2014-01-10 17:40:02 +0100987 // JDWP specs state an INVALID_OBJECT error is returned if the object ID is not valid. However
988 // the RI seems to ignore this and assume object has been collected.
989 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
990 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
991 is_collected = true;
992 } else {
993 is_collected = gRegistry->IsCollected(object_id);
994 }
Elliott Hughes64f574f2013-02-20 14:57:12 -0800995 return JDWP::ERR_NONE;
996}
997
998void Dbg::DisposeObject(JDWP::ObjectId object_id, uint32_t reference_count)
999 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1000 gRegistry->DisposeObject(object_id, reference_count);
1001}
1002
Sebastien Hertz4d8fd492014-03-28 16:29:41 +01001003static JDWP::JdwpTypeTag GetTypeTag(mirror::Class* klass)
1004 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1005 DCHECK(klass != nullptr);
1006 if (klass->IsArrayClass()) {
1007 return JDWP::TT_ARRAY;
1008 } else if (klass->IsInterface()) {
1009 return JDWP::TT_INTERFACE;
1010 } else {
1011 return JDWP::TT_CLASS;
1012 }
1013}
1014
Elliott Hughes88d63092013-01-09 09:55:54 -08001015JDWP::JdwpError Dbg::GetReflectedType(JDWP::RefTypeId class_id, JDWP::ExpandBuf* pReply) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001016 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001017 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001018 if (c == NULL) {
1019 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001020 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001021
Sebastien Hertz4d8fd492014-03-28 16:29:41 +01001022 JDWP::JdwpTypeTag type_tag = GetTypeTag(c);
1023 expandBufAdd1(pReply, type_tag);
Elliott Hughes88d63092013-01-09 09:55:54 -08001024 expandBufAddRefTypeId(pReply, class_id);
Elliott Hughes436e3722012-02-17 20:01:47 -08001025 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001026}
1027
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001028void Dbg::GetClassList(std::vector<JDWP::RefTypeId>& classes) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001029 // Get the complete list of reference classes (i.e. all classes except
1030 // the primitive types).
1031 // Returns a newly-allocated buffer full of RefTypeId values.
1032 struct ClassListCreator {
Elliott Hughesba8eee12012-01-24 20:25:24 -08001033 explicit ClassListCreator(std::vector<JDWP::RefTypeId>& classes) : classes(classes) {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001034 }
1035
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001036 static bool Visit(mirror::Class* c, void* arg) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001037 return reinterpret_cast<ClassListCreator*>(arg)->Visit(c);
1038 }
1039
Elliott Hughes64f574f2013-02-20 14:57:12 -08001040 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1041 // annotalysis.
1042 bool Visit(mirror::Class* c) NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughesa2155262011-11-16 16:26:58 -08001043 if (!c->IsPrimitive()) {
Elliott Hughes64f574f2013-02-20 14:57:12 -08001044 classes.push_back(gRegistry->AddRefType(c));
Elliott Hughesa2155262011-11-16 16:26:58 -08001045 }
1046 return true;
1047 }
1048
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001049 std::vector<JDWP::RefTypeId>& classes;
Elliott Hughesa2155262011-11-16 16:26:58 -08001050 };
1051
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001052 ClassListCreator clc(classes);
Elliott Hughesa2155262011-11-16 16:26:58 -08001053 Runtime::Current()->GetClassLinker()->VisitClasses(ClassListCreator::Visit, &clc);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001054}
1055
Elliott Hughes88d63092013-01-09 09:55:54 -08001056JDWP::JdwpError Dbg::GetClassInfo(JDWP::RefTypeId class_id, JDWP::JdwpTypeTag* pTypeTag, uint32_t* pStatus, std::string* pDescriptor) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001057 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001058 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001059 if (c == NULL) {
1060 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001061 }
1062
Elliott Hughesa2155262011-11-16 16:26:58 -08001063 if (c->IsArrayClass()) {
1064 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
1065 *pTypeTag = JDWP::TT_ARRAY;
1066 } else {
1067 if (c->IsErroneous()) {
1068 *pStatus = JDWP::CS_ERROR;
1069 } else {
1070 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED | JDWP::CS_INITIALIZED;
1071 }
1072 *pTypeTag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
1073 }
1074
1075 if (pDescriptor != NULL) {
Ian Rogersdfb325e2013-10-30 01:00:44 -07001076 *pDescriptor = ClassHelper(c).GetDescriptor();
Elliott Hughesa2155262011-11-16 16:26:58 -08001077 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001078 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001079}
1080
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001081void Dbg::FindLoadedClassBySignature(const char* descriptor, std::vector<JDWP::RefTypeId>& ids) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001082 std::vector<mirror::Class*> classes;
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001083 Runtime::Current()->GetClassLinker()->LookupClasses(descriptor, classes);
1084 ids.clear();
1085 for (size_t i = 0; i < classes.size(); ++i) {
1086 ids.push_back(gRegistry->Add(classes[i]));
1087 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001088}
1089
Elliott Hughes64f574f2013-02-20 14:57:12 -08001090JDWP::JdwpError Dbg::GetReferenceType(JDWP::ObjectId object_id, JDWP::ExpandBuf* pReply)
1091 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001092 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001093 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001094 return JDWP::ERR_INVALID_OBJECT;
Elliott Hughes499c5132011-11-17 14:55:11 -08001095 }
Elliott Hughes2435a572012-02-17 16:07:41 -08001096
Sebastien Hertz4d8fd492014-03-28 16:29:41 +01001097 JDWP::JdwpTypeTag type_tag = GetTypeTag(o->GetClass());
Elliott Hughes64f574f2013-02-20 14:57:12 -08001098 JDWP::RefTypeId type_id = gRegistry->AddRefType(o->GetClass());
Elliott Hughes2435a572012-02-17 16:07:41 -08001099
1100 expandBufAdd1(pReply, type_tag);
1101 expandBufAddRefTypeId(pReply, type_id);
1102
1103 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001104}
1105
Ian Rogersfc0e94b2013-09-23 23:51:32 -07001106JDWP::JdwpError Dbg::GetSignature(JDWP::RefTypeId class_id, std::string* signature) {
Elliott Hughes1fe7afb2012-02-13 17:23:03 -08001107 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001108 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes1fe7afb2012-02-13 17:23:03 -08001109 if (c == NULL) {
1110 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001111 }
Ian Rogersdfb325e2013-10-30 01:00:44 -07001112 *signature = ClassHelper(c).GetDescriptor();
Elliott Hughes1fe7afb2012-02-13 17:23:03 -08001113 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001114}
1115
Elliott Hughes88d63092013-01-09 09:55:54 -08001116JDWP::JdwpError Dbg::GetSourceFile(JDWP::RefTypeId class_id, std::string& result) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001117 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001118 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001119 if (c == NULL) {
1120 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001121 }
Sebastien Hertzb7054ba2014-03-13 11:52:31 +01001122 if (c->IsProxyClass()) {
1123 return JDWP::ERR_ABSENT_INFORMATION;
1124 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001125 result = ClassHelper(c).GetSourceFile();
1126 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001127}
1128
Elliott Hughes88d63092013-01-09 09:55:54 -08001129JDWP::JdwpError Dbg::GetObjectTag(JDWP::ObjectId object_id, uint8_t& tag) {
Ian Rogers98379392014-02-24 16:53:16 -08001130 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001131 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001132 if (o == ObjectRegistry::kInvalidObject) {
Elliott Hughes546b9862012-06-20 16:06:13 -07001133 return JDWP::ERR_INVALID_OBJECT;
1134 }
Ian Rogers98379392014-02-24 16:53:16 -08001135 tag = TagFromObject(soa, o);
Elliott Hughes546b9862012-06-20 16:06:13 -07001136 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001137}
1138
Elliott Hughesaed4be92011-12-02 16:16:23 -08001139size_t Dbg::GetTagWidth(JDWP::JdwpTag tag) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001140 switch (tag) {
1141 case JDWP::JT_VOID:
1142 return 0;
1143 case JDWP::JT_BYTE:
1144 case JDWP::JT_BOOLEAN:
1145 return 1;
1146 case JDWP::JT_CHAR:
1147 case JDWP::JT_SHORT:
1148 return 2;
1149 case JDWP::JT_FLOAT:
1150 case JDWP::JT_INT:
1151 return 4;
1152 case JDWP::JT_ARRAY:
1153 case JDWP::JT_OBJECT:
1154 case JDWP::JT_STRING:
1155 case JDWP::JT_THREAD:
1156 case JDWP::JT_THREAD_GROUP:
1157 case JDWP::JT_CLASS_LOADER:
1158 case JDWP::JT_CLASS_OBJECT:
1159 return sizeof(JDWP::ObjectId);
1160 case JDWP::JT_DOUBLE:
1161 case JDWP::JT_LONG:
1162 return 8;
1163 default:
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001164 LOG(FATAL) << "Unknown tag " << tag;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001165 return -1;
1166 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001167}
1168
Elliott Hughes88d63092013-01-09 09:55:54 -08001169JDWP::JdwpError Dbg::GetArrayLength(JDWP::ObjectId array_id, int& length) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001170 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001171 mirror::Array* a = DecodeArray(array_id, status);
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001172 if (a == NULL) {
1173 return status;
Elliott Hughes24437992011-11-30 14:49:33 -08001174 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001175 length = a->GetLength();
1176 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001177}
1178
Elliott Hughes88d63092013-01-09 09:55:54 -08001179JDWP::JdwpError Dbg::OutputArray(JDWP::ObjectId array_id, int offset, int count, JDWP::ExpandBuf* pReply) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001180 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001181 mirror::Array* a = DecodeArray(array_id, status);
Ian Rogers98379392014-02-24 16:53:16 -08001182 if (a == nullptr) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001183 return status;
1184 }
Elliott Hughes24437992011-11-30 14:49:33 -08001185
1186 if (offset < 0 || count < 0 || offset > a->GetLength() || a->GetLength() - offset < count) {
1187 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001188 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughes24437992011-11-30 14:49:33 -08001189 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001190 std::string descriptor(ClassHelper(a->GetClass()).GetDescriptor());
Elliott Hughes24437992011-11-30 14:49:33 -08001191 JDWP::JdwpTag tag = BasicTagFromDescriptor(descriptor.c_str() + 1);
1192
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001193 expandBufAdd1(pReply, tag);
1194 expandBufAdd4BE(pReply, count);
1195
Elliott Hughes24437992011-11-30 14:49:33 -08001196 if (IsPrimitiveTag(tag)) {
1197 size_t width = GetTagWidth(tag);
Elliott Hughes24437992011-11-30 14:49:33 -08001198 uint8_t* dst = expandBufAddSpace(pReply, count * width);
1199 if (width == 8) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001200 const uint64_t* src8 = reinterpret_cast<uint64_t*>(a->GetRawData(sizeof(uint64_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001201 for (int i = 0; i < count; ++i) JDWP::Write8BE(&dst, src8[offset + i]);
1202 } else if (width == 4) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001203 const uint32_t* src4 = reinterpret_cast<uint32_t*>(a->GetRawData(sizeof(uint32_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001204 for (int i = 0; i < count; ++i) JDWP::Write4BE(&dst, src4[offset + i]);
1205 } else if (width == 2) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001206 const uint16_t* src2 = reinterpret_cast<uint16_t*>(a->GetRawData(sizeof(uint16_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001207 for (int i = 0; i < count; ++i) JDWP::Write2BE(&dst, src2[offset + i]);
1208 } else {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001209 const uint8_t* src = reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint8_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001210 memcpy(dst, &src[offset * width], count * width);
1211 }
1212 } else {
Ian Rogers98379392014-02-24 16:53:16 -08001213 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001214 mirror::ObjectArray<mirror::Object>* oa = a->AsObjectArray<mirror::Object>();
Elliott Hughes24437992011-11-30 14:49:33 -08001215 for (int i = 0; i < count; ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001216 mirror::Object* element = oa->Get(offset + i);
Ian Rogers98379392014-02-24 16:53:16 -08001217 JDWP::JdwpTag specific_tag = (element != nullptr) ? TagFromObject(soa, element)
1218 : tag;
Elliott Hughes24437992011-11-30 14:49:33 -08001219 expandBufAdd1(pReply, specific_tag);
1220 expandBufAddObjectId(pReply, gRegistry->Add(element));
1221 }
1222 }
1223
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001224 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001225}
1226
Ian Rogersef7d42f2014-01-06 12:55:46 -08001227template <typename T>
1228static void CopyArrayData(mirror::Array* a, JDWP::Request& src, int offset, int count)
1229 NO_THREAD_SAFETY_ANALYSIS {
1230 // TODO: fix when annotalysis correctly handles non-member functions.
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001231 DCHECK(a->GetClass()->IsPrimitiveArray());
1232
Ian Rogersef7d42f2014-01-06 12:55:46 -08001233 T* dst = reinterpret_cast<T*>(a->GetRawData(sizeof(T), offset));
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001234 for (int i = 0; i < count; ++i) {
1235 *dst++ = src.ReadValue(sizeof(T));
1236 }
1237}
1238
Elliott Hughes88d63092013-01-09 09:55:54 -08001239JDWP::JdwpError Dbg::SetArrayElements(JDWP::ObjectId array_id, int offset, int count,
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001240 JDWP::Request& request)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001241 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001242 JDWP::JdwpError status;
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001243 mirror::Array* dst = DecodeArray(array_id, status);
1244 if (dst == NULL) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001245 return status;
1246 }
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001247
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001248 if (offset < 0 || count < 0 || offset > dst->GetLength() || dst->GetLength() - offset < count) {
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001249 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001250 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001251 }
nikolay serdjuk1d66e882014-04-07 13:54:24 +07001252 ClassHelper ch(dst->GetClass());
1253 const char* descriptor = ch.GetDescriptor();
Ian Rogersfc0e94b2013-09-23 23:51:32 -07001254 JDWP::JdwpTag tag = BasicTagFromDescriptor(descriptor + 1);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001255
1256 if (IsPrimitiveTag(tag)) {
1257 size_t width = GetTagWidth(tag);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001258 if (width == 8) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001259 CopyArrayData<uint64_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001260 } else if (width == 4) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001261 CopyArrayData<uint32_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001262 } else if (width == 2) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001263 CopyArrayData<uint16_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001264 } else {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001265 CopyArrayData<uint8_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001266 }
1267 } else {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001268 mirror::ObjectArray<mirror::Object>* oa = dst->AsObjectArray<mirror::Object>();
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001269 for (int i = 0; i < count; ++i) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001270 JDWP::ObjectId id = request.ReadObjectId();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001271 mirror::Object* o = gRegistry->Get<mirror::Object*>(id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001272 if (o == ObjectRegistry::kInvalidObject) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001273 return JDWP::ERR_INVALID_OBJECT;
1274 }
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001275 oa->Set<false>(offset + i, o);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001276 }
1277 }
1278
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001279 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001280}
1281
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001282JDWP::ObjectId Dbg::CreateString(const std::string& str) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001283 return gRegistry->Add(mirror::String::AllocFromModifiedUtf8(Thread::Current(), str.c_str()));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001284}
1285
Elliott Hughes88d63092013-01-09 09:55:54 -08001286JDWP::JdwpError Dbg::CreateObject(JDWP::RefTypeId class_id, JDWP::ObjectId& new_object) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001287 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001288 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001289 if (c == NULL) {
1290 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001291 }
Ian Rogers50b35e22012-10-04 10:09:15 -07001292 new_object = gRegistry->Add(c->AllocObject(Thread::Current()));
Elliott Hughes436e3722012-02-17 20:01:47 -08001293 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001294}
1295
Elliott Hughesbf13d362011-12-08 15:51:37 -08001296/*
1297 * Used by Eclipse's "Display" view to evaluate "new byte[5]" to get "(byte[]) [0, 0, 0, 0, 0]".
1298 */
Elliott Hughes88d63092013-01-09 09:55:54 -08001299JDWP::JdwpError Dbg::CreateArrayObject(JDWP::RefTypeId array_class_id, uint32_t length,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001300 JDWP::ObjectId& new_array) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001301 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001302 mirror::Class* c = DecodeClass(array_class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001303 if (c == NULL) {
1304 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001305 }
Ian Rogers6fac4472014-02-25 17:01:10 -08001306 new_array = gRegistry->Add(mirror::Array::Alloc<true>(Thread::Current(), c, length,
1307 c->GetComponentSize(),
1308 Runtime::Current()->GetHeap()->GetCurrentAllocator()));
Elliott Hughes436e3722012-02-17 20:01:47 -08001309 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001310}
1311
Elliott Hughes88d63092013-01-09 09:55:54 -08001312bool Dbg::MatchType(JDWP::RefTypeId instance_class_id, JDWP::RefTypeId class_id) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001313 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001314 mirror::Class* c1 = DecodeClass(instance_class_id, status);
Elliott Hughesa656a0f2012-02-21 18:03:44 -08001315 CHECK(c1 != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001316 mirror::Class* c2 = DecodeClass(class_id, status);
Elliott Hughesa656a0f2012-02-21 18:03:44 -08001317 CHECK(c2 != NULL);
Sebastien Hertz123756a2013-11-27 15:49:42 +01001318 return c2->IsAssignableFrom(c1);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001319}
1320
Brian Carlstromea46f952013-07-30 01:26:50 -07001321static JDWP::FieldId ToFieldId(const mirror::ArtField* f)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001322 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001323 CHECK(!kMovingFields);
Elliott Hughes03181a82011-11-17 17:22:21 -08001324 return static_cast<JDWP::FieldId>(reinterpret_cast<uintptr_t>(f));
Elliott Hughes03181a82011-11-17 17:22:21 -08001325}
1326
Brian Carlstromea46f952013-07-30 01:26:50 -07001327static JDWP::MethodId ToMethodId(const mirror::ArtMethod* m)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001328 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001329 CHECK(!kMovingMethods);
Elliott Hughes03181a82011-11-17 17:22:21 -08001330 return static_cast<JDWP::MethodId>(reinterpret_cast<uintptr_t>(m));
Elliott Hughes03181a82011-11-17 17:22:21 -08001331}
1332
Brian Carlstromea46f952013-07-30 01:26:50 -07001333static mirror::ArtField* FromFieldId(JDWP::FieldId fid)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001334 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001335 CHECK(!kMovingFields);
Brian Carlstromea46f952013-07-30 01:26:50 -07001336 return reinterpret_cast<mirror::ArtField*>(static_cast<uintptr_t>(fid));
Elliott Hughesaed4be92011-12-02 16:16:23 -08001337}
1338
Brian Carlstromea46f952013-07-30 01:26:50 -07001339static mirror::ArtMethod* FromMethodId(JDWP::MethodId mid)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001340 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001341 CHECK(!kMovingMethods);
Brian Carlstromea46f952013-07-30 01:26:50 -07001342 return reinterpret_cast<mirror::ArtMethod*>(static_cast<uintptr_t>(mid));
Elliott Hughes03181a82011-11-17 17:22:21 -08001343}
1344
Brian Carlstromea46f952013-07-30 01:26:50 -07001345static void SetLocation(JDWP::JdwpLocation& location, mirror::ArtMethod* m, uint32_t dex_pc)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001346 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001347 if (m == NULL) {
1348 memset(&location, 0, sizeof(location));
1349 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001350 mirror::Class* c = m->GetDeclaringClass();
Sebastien Hertz4d8fd492014-03-28 16:29:41 +01001351 location.type_tag = GetTypeTag(c);
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001352 location.class_id = gRegistry->AddRefType(c);
Elliott Hughes74847412012-06-20 18:10:21 -07001353 location.method_id = ToMethodId(m);
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001354 location.dex_pc = (m->IsNative() || m->IsProxyMethod()) ? static_cast<uint64_t>(-1) : dex_pc;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001355 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08001356}
1357
Elliott Hughesa96836a2013-01-17 12:27:49 -08001358std::string Dbg::GetMethodName(JDWP::MethodId method_id)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001359 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001360 mirror::ArtMethod* m = FromMethodId(method_id);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001361 return MethodHelper(m).GetName();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001362}
1363
Elliott Hughesa96836a2013-01-17 12:27:49 -08001364std::string Dbg::GetFieldName(JDWP::FieldId field_id)
1365 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001366 mirror::ArtField* f = FromFieldId(field_id);
Elliott Hughesa96836a2013-01-17 12:27:49 -08001367 return FieldHelper(f).GetName();
1368}
1369
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001370/*
1371 * Augment the access flags for synthetic methods and fields by setting
1372 * the (as described by the spec) "0xf0000000 bit". Also, strip out any
1373 * flags not specified by the Java programming language.
1374 */
1375static uint32_t MangleAccessFlags(uint32_t accessFlags) {
1376 accessFlags &= kAccJavaFlagsMask;
1377 if ((accessFlags & kAccSynthetic) != 0) {
1378 accessFlags |= 0xf0000000;
1379 }
1380 return accessFlags;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001381}
1382
Elliott Hughesdbb40792011-11-18 17:05:22 -08001383/*
Jeff Haob7cefc72013-11-14 14:51:09 -08001384 * Circularly shifts registers so that arguments come first. Debuggers
1385 * expect slots to begin with arguments, but dex code places them at
1386 * the end.
Elliott Hughesdbb40792011-11-18 17:05:22 -08001387 */
Jeff Haob7cefc72013-11-14 14:51:09 -08001388static uint16_t MangleSlot(uint16_t slot, mirror::ArtMethod* m)
1389 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1390 const DexFile::CodeItem* code_item = MethodHelper(m).GetCodeItem();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001391 if (code_item == nullptr) {
1392 // We should not get here for a method without code (native, proxy or abstract). Log it and
1393 // return the slot as is since all registers are arguments.
1394 LOG(WARNING) << "Trying to mangle slot for method without code " << PrettyMethod(m);
1395 return slot;
1396 }
Jeff Haob7cefc72013-11-14 14:51:09 -08001397 uint16_t ins_size = code_item->ins_size_;
1398 uint16_t locals_size = code_item->registers_size_ - ins_size;
1399 if (slot >= locals_size) {
1400 return slot - locals_size;
1401 } else {
1402 return slot + ins_size;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001403 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001404}
1405
Jeff Haob7cefc72013-11-14 14:51:09 -08001406/*
1407 * Circularly shifts registers so that arguments come last. Reverts
1408 * slots to dex style argument placement.
1409 */
Brian Carlstromea46f952013-07-30 01:26:50 -07001410static uint16_t DemangleSlot(uint16_t slot, mirror::ArtMethod* m)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001411 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Jeff Haob7cefc72013-11-14 14:51:09 -08001412 const DexFile::CodeItem* code_item = MethodHelper(m).GetCodeItem();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001413 if (code_item == nullptr) {
1414 // We should not get here for a method without code (native, proxy or abstract). Log it and
1415 // return the slot as is since all registers are arguments.
1416 LOG(WARNING) << "Trying to demangle slot for method without code " << PrettyMethod(m);
1417 return slot;
1418 }
Jeff Haob7cefc72013-11-14 14:51:09 -08001419 uint16_t ins_size = code_item->ins_size_;
1420 uint16_t locals_size = code_item->registers_size_ - ins_size;
1421 if (slot < ins_size) {
1422 return slot + locals_size;
1423 } else {
1424 return slot - ins_size;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001425 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001426}
1427
Elliott Hughes88d63092013-01-09 09:55:54 -08001428JDWP::JdwpError Dbg::OutputDeclaredFields(JDWP::RefTypeId class_id, bool with_generic, JDWP::ExpandBuf* pReply) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001429 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001430 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001431 if (c == NULL) {
1432 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001433 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001434
1435 size_t instance_field_count = c->NumInstanceFields();
1436 size_t static_field_count = c->NumStaticFields();
1437
1438 expandBufAdd4BE(pReply, instance_field_count + static_field_count);
1439
1440 for (size_t i = 0; i < instance_field_count + static_field_count; ++i) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001441 mirror::ArtField* f = (i < instance_field_count) ? c->GetInstanceField(i) : c->GetStaticField(i - instance_field_count);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001442 FieldHelper fh(f);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001443 expandBufAddFieldId(pReply, ToFieldId(f));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001444 expandBufAddUtf8String(pReply, fh.GetName());
1445 expandBufAddUtf8String(pReply, fh.GetTypeDescriptor());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001446 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001447 static const char genericSignature[1] = "";
1448 expandBufAddUtf8String(pReply, genericSignature);
1449 }
1450 expandBufAdd4BE(pReply, MangleAccessFlags(f->GetAccessFlags()));
1451 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001452 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001453}
1454
Elliott Hughes88d63092013-01-09 09:55:54 -08001455JDWP::JdwpError Dbg::OutputDeclaredMethods(JDWP::RefTypeId class_id, bool with_generic,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001456 JDWP::ExpandBuf* pReply) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001457 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001458 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001459 if (c == NULL) {
1460 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001461 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001462
1463 size_t direct_method_count = c->NumDirectMethods();
1464 size_t virtual_method_count = c->NumVirtualMethods();
1465
1466 expandBufAdd4BE(pReply, direct_method_count + virtual_method_count);
1467
1468 for (size_t i = 0; i < direct_method_count + virtual_method_count; ++i) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001469 mirror::ArtMethod* m = (i < direct_method_count) ? c->GetDirectMethod(i) : c->GetVirtualMethod(i - direct_method_count);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001470 MethodHelper mh(m);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001471 expandBufAddMethodId(pReply, ToMethodId(m));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001472 expandBufAddUtf8String(pReply, mh.GetName());
Ian Rogersd91d6d62013-09-25 20:26:14 -07001473 expandBufAddUtf8String(pReply, mh.GetSignature().ToString());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001474 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001475 static const char genericSignature[1] = "";
1476 expandBufAddUtf8String(pReply, genericSignature);
1477 }
1478 expandBufAdd4BE(pReply, MangleAccessFlags(m->GetAccessFlags()));
1479 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001480 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001481}
1482
Elliott Hughes88d63092013-01-09 09:55:54 -08001483JDWP::JdwpError Dbg::OutputDeclaredInterfaces(JDWP::RefTypeId class_id, JDWP::ExpandBuf* pReply) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001484 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001485 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001486 if (c == NULL) {
1487 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001488 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001489
1490 ClassHelper kh(c);
Ian Rogersd24e2642012-06-06 21:21:43 -07001491 size_t interface_count = kh.NumDirectInterfaces();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001492 expandBufAdd4BE(pReply, interface_count);
1493 for (size_t i = 0; i < interface_count; ++i) {
Elliott Hughes64f574f2013-02-20 14:57:12 -08001494 expandBufAddRefTypeId(pReply, gRegistry->AddRefType(kh.GetDirectInterface(i)));
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001495 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001496 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001497}
1498
Elliott Hughes88d63092013-01-09 09:55:54 -08001499void Dbg::OutputLineTable(JDWP::RefTypeId, JDWP::MethodId method_id, JDWP::ExpandBuf* pReply)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001500 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001501 struct DebugCallbackContext {
1502 int numItems;
1503 JDWP::ExpandBuf* pReply;
1504
Elliott Hughes2435a572012-02-17 16:07:41 -08001505 static bool Callback(void* context, uint32_t address, uint32_t line_number) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001506 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
1507 expandBufAdd8BE(pContext->pReply, address);
Elliott Hughes2435a572012-02-17 16:07:41 -08001508 expandBufAdd4BE(pContext->pReply, line_number);
Elliott Hughes03181a82011-11-17 17:22:21 -08001509 pContext->numItems++;
Sebastien Hertzf2910ee2013-10-19 16:39:24 +02001510 return false;
Elliott Hughes03181a82011-11-17 17:22:21 -08001511 }
1512 };
Brian Carlstromea46f952013-07-30 01:26:50 -07001513 mirror::ArtMethod* m = FromMethodId(method_id);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001514 MethodHelper mh(m);
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001515 const DexFile::CodeItem* code_item = mh.GetCodeItem();
Elliott Hughes03181a82011-11-17 17:22:21 -08001516 uint64_t start, end;
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001517 if (code_item == nullptr) {
1518 DCHECK(m->IsNative() || m->IsProxyMethod());
Elliott Hughes03181a82011-11-17 17:22:21 -08001519 start = -1;
1520 end = -1;
1521 } else {
1522 start = 0;
jeffhao14f0db92012-12-14 17:50:42 -08001523 // Return the index of the last instruction
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001524 end = code_item->insns_size_in_code_units_ - 1;
Elliott Hughes03181a82011-11-17 17:22:21 -08001525 }
1526
1527 expandBufAdd8BE(pReply, start);
1528 expandBufAdd8BE(pReply, end);
1529
1530 // Add numLines later
1531 size_t numLinesOffset = expandBufGetLength(pReply);
1532 expandBufAdd4BE(pReply, 0);
1533
1534 DebugCallbackContext context;
1535 context.numItems = 0;
1536 context.pReply = pReply;
1537
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001538 if (code_item != nullptr) {
1539 mh.GetDexFile().DecodeDebugInfo(code_item, m->IsStatic(), m->GetDexMethodIndex(),
1540 DebugCallbackContext::Callback, NULL, &context);
1541 }
Elliott Hughes03181a82011-11-17 17:22:21 -08001542
1543 JDWP::Set4BE(expandBufGetBuffer(pReply) + numLinesOffset, context.numItems);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001544}
1545
Elliott Hughes88d63092013-01-09 09:55:54 -08001546void Dbg::OutputVariableTable(JDWP::RefTypeId, JDWP::MethodId method_id, bool with_generic, JDWP::ExpandBuf* pReply) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001547 struct DebugCallbackContext {
Jeff Haob7cefc72013-11-14 14:51:09 -08001548 mirror::ArtMethod* method;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001549 JDWP::ExpandBuf* pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001550 size_t variable_count;
1551 bool with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001552
Jeff Haob7cefc72013-11-14 14:51:09 -08001553 static void Callback(void* context, uint16_t slot, uint32_t startAddress, uint32_t endAddress, const char* name, const char* descriptor, const char* signature)
1554 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001555 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
1556
Jeff Haob7cefc72013-11-14 14:51:09 -08001557 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 -08001558
Jeff Haob7cefc72013-11-14 14:51:09 -08001559 slot = MangleSlot(slot, pContext->method);
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001560
Elliott Hughesdbb40792011-11-18 17:05:22 -08001561 expandBufAdd8BE(pContext->pReply, startAddress);
1562 expandBufAddUtf8String(pContext->pReply, name);
1563 expandBufAddUtf8String(pContext->pReply, descriptor);
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001564 if (pContext->with_generic) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001565 expandBufAddUtf8String(pContext->pReply, signature);
1566 }
1567 expandBufAdd4BE(pContext->pReply, endAddress - startAddress);
1568 expandBufAdd4BE(pContext->pReply, slot);
1569
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001570 ++pContext->variable_count;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001571 }
1572 };
Brian Carlstromea46f952013-07-30 01:26:50 -07001573 mirror::ArtMethod* m = FromMethodId(method_id);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001574 MethodHelper mh(m);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001575
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001576 // arg_count considers doubles and longs to take 2 units.
1577 // variable_count considers everything to take 1 unit.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001578 std::string shorty(mh.GetShorty());
Brian Carlstromea46f952013-07-30 01:26:50 -07001579 expandBufAdd4BE(pReply, mirror::ArtMethod::NumArgRegisters(shorty));
Elliott Hughesdbb40792011-11-18 17:05:22 -08001580
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001581 // We don't know the total number of variables yet, so leave a blank and update it later.
1582 size_t variable_count_offset = expandBufGetLength(pReply);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001583 expandBufAdd4BE(pReply, 0);
1584
1585 DebugCallbackContext context;
Jeff Haob7cefc72013-11-14 14:51:09 -08001586 context.method = m;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001587 context.pReply = pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001588 context.variable_count = 0;
1589 context.with_generic = with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001590
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001591 const DexFile::CodeItem* code_item = mh.GetCodeItem();
1592 if (code_item != nullptr) {
1593 mh.GetDexFile().DecodeDebugInfo(code_item, m->IsStatic(), m->GetDexMethodIndex(), NULL,
1594 DebugCallbackContext::Callback, &context);
1595 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001596
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001597 JDWP::Set4BE(expandBufGetBuffer(pReply) + variable_count_offset, context.variable_count);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001598}
1599
Jeff Hao579b0242013-11-18 13:16:49 -08001600void Dbg::OutputMethodReturnValue(JDWP::MethodId method_id, const JValue* return_value,
1601 JDWP::ExpandBuf* pReply) {
1602 mirror::ArtMethod* m = FromMethodId(method_id);
1603 JDWP::JdwpTag tag = BasicTagFromDescriptor(MethodHelper(m).GetShorty());
1604 OutputJValue(tag, return_value, pReply);
1605}
1606
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02001607void Dbg::OutputFieldValue(JDWP::FieldId field_id, const JValue* field_value,
1608 JDWP::ExpandBuf* pReply) {
1609 mirror::ArtField* f = FromFieldId(field_id);
1610 JDWP::JdwpTag tag = BasicTagFromDescriptor(FieldHelper(f).GetTypeDescriptor());
1611 OutputJValue(tag, field_value, pReply);
1612}
1613
Elliott Hughes9777ba22013-01-17 09:04:19 -08001614JDWP::JdwpError Dbg::GetBytecodes(JDWP::RefTypeId, JDWP::MethodId method_id,
1615 std::vector<uint8_t>& bytecodes)
1616 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001617 mirror::ArtMethod* m = FromMethodId(method_id);
Elliott Hughes9777ba22013-01-17 09:04:19 -08001618 if (m == NULL) {
1619 return JDWP::ERR_INVALID_METHODID;
1620 }
1621 MethodHelper mh(m);
1622 const DexFile::CodeItem* code_item = mh.GetCodeItem();
1623 size_t byte_count = code_item->insns_size_in_code_units_ * 2;
1624 const uint8_t* begin = reinterpret_cast<const uint8_t*>(code_item->insns_);
1625 const uint8_t* end = begin + byte_count;
1626 for (const uint8_t* p = begin; p != end; ++p) {
1627 bytecodes.push_back(*p);
1628 }
1629 return JDWP::ERR_NONE;
1630}
1631
Elliott Hughes88d63092013-01-09 09:55:54 -08001632JDWP::JdwpTag Dbg::GetFieldBasicTag(JDWP::FieldId field_id) {
1633 return BasicTagFromDescriptor(FieldHelper(FromFieldId(field_id)).GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001634}
1635
Elliott Hughes88d63092013-01-09 09:55:54 -08001636JDWP::JdwpTag Dbg::GetStaticFieldBasicTag(JDWP::FieldId field_id) {
1637 return BasicTagFromDescriptor(FieldHelper(FromFieldId(field_id)).GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001638}
1639
Elliott Hughes88d63092013-01-09 09:55:54 -08001640static JDWP::JdwpError GetFieldValueImpl(JDWP::RefTypeId ref_type_id, JDWP::ObjectId object_id,
1641 JDWP::FieldId field_id, JDWP::ExpandBuf* pReply,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001642 bool is_static)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001643 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes0cf74332012-02-23 23:14:00 -08001644 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001645 mirror::Class* c = DecodeClass(ref_type_id, status);
Elliott Hughes88d63092013-01-09 09:55:54 -08001646 if (ref_type_id != 0 && c == NULL) {
Elliott Hughes0cf74332012-02-23 23:14:00 -08001647 return status;
1648 }
1649
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001650 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001651 if ((!is_static && o == NULL) || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001652 return JDWP::ERR_INVALID_OBJECT;
1653 }
Brian Carlstromea46f952013-07-30 01:26:50 -07001654 mirror::ArtField* f = FromFieldId(field_id);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001655
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001656 mirror::Class* receiver_class = c;
Elliott Hughes0cf74332012-02-23 23:14:00 -08001657 if (receiver_class == NULL && o != NULL) {
1658 receiver_class = o->GetClass();
1659 }
1660 // TODO: should we give up now if receiver_class is NULL?
1661 if (receiver_class != NULL && !f->GetDeclaringClass()->IsAssignableFrom(receiver_class)) {
1662 LOG(INFO) << "ERR_INVALID_FIELDID: " << PrettyField(f) << " " << PrettyClass(receiver_class);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001663 return JDWP::ERR_INVALID_FIELDID;
1664 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001665
Elliott Hughes0cf74332012-02-23 23:14:00 -08001666 // The RI only enforces the static/non-static mismatch in one direction.
1667 // TODO: should we change the tests and check both?
1668 if (is_static) {
1669 if (!f->IsStatic()) {
1670 return JDWP::ERR_INVALID_FIELDID;
1671 }
1672 } else {
1673 if (f->IsStatic()) {
1674 LOG(WARNING) << "Ignoring non-NULL receiver for ObjectReference.SetValues on static field " << PrettyField(f);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001675 }
1676 }
jeffhao0dfbb7e2012-11-28 15:26:03 -08001677 if (f->IsStatic()) {
1678 o = f->GetDeclaringClass();
1679 }
Elliott Hughes0cf74332012-02-23 23:14:00 -08001680
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001681 JDWP::JdwpTag tag = BasicTagFromDescriptor(FieldHelper(f).GetTypeDescriptor());
Jeff Hao579b0242013-11-18 13:16:49 -08001682 JValue field_value;
1683 if (tag == JDWP::JT_VOID) {
1684 LOG(FATAL) << "Unknown tag: " << tag;
1685 } else if (!IsPrimitiveTag(tag)) {
1686 field_value.SetL(f->GetObject(o));
1687 } else if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
1688 field_value.SetJ(f->Get64(o));
Elliott Hughesaed4be92011-12-02 16:16:23 -08001689 } else {
Jeff Hao579b0242013-11-18 13:16:49 -08001690 field_value.SetI(f->Get32(o));
Elliott Hughesaed4be92011-12-02 16:16:23 -08001691 }
Jeff Hao579b0242013-11-18 13:16:49 -08001692 Dbg::OutputJValue(tag, &field_value, pReply);
1693
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001694 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001695}
1696
Elliott Hughes88d63092013-01-09 09:55:54 -08001697JDWP::JdwpError Dbg::GetFieldValue(JDWP::ObjectId object_id, JDWP::FieldId field_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001698 JDWP::ExpandBuf* pReply) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001699 return GetFieldValueImpl(0, object_id, field_id, pReply, false);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001700}
1701
Elliott Hughes88d63092013-01-09 09:55:54 -08001702JDWP::JdwpError Dbg::GetStaticFieldValue(JDWP::RefTypeId ref_type_id, JDWP::FieldId field_id, JDWP::ExpandBuf* pReply) {
1703 return GetFieldValueImpl(ref_type_id, 0, field_id, pReply, true);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001704}
1705
Elliott Hughes88d63092013-01-09 09:55:54 -08001706static JDWP::JdwpError SetFieldValueImpl(JDWP::ObjectId object_id, JDWP::FieldId field_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001707 uint64_t value, int width, bool is_static)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001708 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001709 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001710 if ((!is_static && o == NULL) || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001711 return JDWP::ERR_INVALID_OBJECT;
1712 }
Brian Carlstromea46f952013-07-30 01:26:50 -07001713 mirror::ArtField* f = FromFieldId(field_id);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001714
1715 // The RI only enforces the static/non-static mismatch in one direction.
1716 // TODO: should we change the tests and check both?
1717 if (is_static) {
1718 if (!f->IsStatic()) {
1719 return JDWP::ERR_INVALID_FIELDID;
1720 }
1721 } else {
1722 if (f->IsStatic()) {
1723 LOG(WARNING) << "Ignoring non-NULL receiver for ObjectReference.SetValues on static field " << PrettyField(f);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001724 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001725 }
jeffhao0dfbb7e2012-11-28 15:26:03 -08001726 if (f->IsStatic()) {
1727 o = f->GetDeclaringClass();
1728 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001729
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001730 JDWP::JdwpTag tag = BasicTagFromDescriptor(FieldHelper(f).GetTypeDescriptor());
Elliott Hughesaed4be92011-12-02 16:16:23 -08001731
1732 if (IsPrimitiveTag(tag)) {
1733 if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001734 CHECK_EQ(width, 8);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001735 // Debugging can't use transactional mode (runtime only).
1736 f->Set64<false>(o, value);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001737 } else {
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001738 CHECK_LE(width, 4);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001739 // Debugging can't use transactional mode (runtime only).
1740 f->Set32<false>(o, value);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001741 }
1742 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001743 mirror::Object* v = gRegistry->Get<mirror::Object*>(value);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001744 if (v == ObjectRegistry::kInvalidObject) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001745 return JDWP::ERR_INVALID_OBJECT;
1746 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001747 if (v != NULL) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001748 mirror::Class* field_type = FieldHelper(f).GetType();
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001749 if (!field_type->IsAssignableFrom(v->GetClass())) {
1750 return JDWP::ERR_INVALID_OBJECT;
1751 }
1752 }
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001753 // Debugging can't use transactional mode (runtime only).
1754 f->SetObject<false>(o, v);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001755 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001756
1757 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001758}
1759
Elliott Hughes88d63092013-01-09 09:55:54 -08001760JDWP::JdwpError Dbg::SetFieldValue(JDWP::ObjectId object_id, JDWP::FieldId field_id, uint64_t value,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001761 int width) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001762 return SetFieldValueImpl(object_id, field_id, value, width, false);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001763}
1764
Elliott Hughes88d63092013-01-09 09:55:54 -08001765JDWP::JdwpError Dbg::SetStaticFieldValue(JDWP::FieldId field_id, uint64_t value, int width) {
1766 return SetFieldValueImpl(0, field_id, value, width, true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001767}
1768
Elliott Hughes88d63092013-01-09 09:55:54 -08001769std::string Dbg::StringToUtf8(JDWP::ObjectId string_id) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001770 mirror::String* s = gRegistry->Get<mirror::String*>(string_id);
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001771 return s->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001772}
1773
Jeff Hao579b0242013-11-18 13:16:49 -08001774void Dbg::OutputJValue(JDWP::JdwpTag tag, const JValue* return_value, JDWP::ExpandBuf* pReply) {
1775 if (IsPrimitiveTag(tag)) {
1776 expandBufAdd1(pReply, tag);
1777 if (tag == JDWP::JT_BOOLEAN || tag == JDWP::JT_BYTE) {
1778 expandBufAdd1(pReply, return_value->GetI());
1779 } else if (tag == JDWP::JT_CHAR || tag == JDWP::JT_SHORT) {
1780 expandBufAdd2BE(pReply, return_value->GetI());
1781 } else if (tag == JDWP::JT_FLOAT || tag == JDWP::JT_INT) {
1782 expandBufAdd4BE(pReply, return_value->GetI());
1783 } else if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
1784 expandBufAdd8BE(pReply, return_value->GetJ());
1785 } else {
1786 CHECK_EQ(tag, JDWP::JT_VOID);
1787 }
1788 } else {
Ian Rogers98379392014-02-24 16:53:16 -08001789 ScopedObjectAccessUnchecked soa(Thread::Current());
Jeff Hao579b0242013-11-18 13:16:49 -08001790 mirror::Object* value = return_value->GetL();
Ian Rogers98379392014-02-24 16:53:16 -08001791 expandBufAdd1(pReply, TagFromObject(soa, value));
Jeff Hao579b0242013-11-18 13:16:49 -08001792 expandBufAddObjectId(pReply, gRegistry->Add(value));
1793 }
1794}
1795
Elliott Hughes221229c2013-01-08 18:17:50 -08001796JDWP::JdwpError Dbg::GetThreadName(JDWP::ObjectId thread_id, std::string& name) {
jeffhaoa77f0f62012-12-05 17:19:31 -08001797 ScopedObjectAccessUnchecked soa(Thread::Current());
1798 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001799 Thread* thread;
1800 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1801 if (error != JDWP::ERR_NONE && error != JDWP::ERR_THREAD_NOT_ALIVE) {
1802 return error;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001803 }
Elliott Hughes221229c2013-01-08 18:17:50 -08001804
1805 // We still need to report the zombie threads' names, so we can't just call Thread::GetThreadName.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001806 mirror::Object* thread_object = gRegistry->Get<mirror::Object*>(thread_id);
Brian Carlstromea46f952013-07-30 01:26:50 -07001807 mirror::ArtField* java_lang_Thread_name_field =
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001808 soa.DecodeField(WellKnownClasses::java_lang_Thread_name);
1809 mirror::String* s =
1810 reinterpret_cast<mirror::String*>(java_lang_Thread_name_field->GetObject(thread_object));
Elliott Hughes221229c2013-01-08 18:17:50 -08001811 if (s != NULL) {
1812 name = s->ToModifiedUtf8();
1813 }
1814 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001815}
1816
Elliott Hughes221229c2013-01-08 18:17:50 -08001817JDWP::JdwpError Dbg::GetThreadGroup(JDWP::ObjectId thread_id, JDWP::ExpandBuf* pReply) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001818 ScopedObjectAccess soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001819 mirror::Object* thread_object = gRegistry->Get<mirror::Object*>(thread_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001820 if (thread_object == ObjectRegistry::kInvalidObject) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001821 return JDWP::ERR_INVALID_OBJECT;
1822 }
Ian Rogers98379392014-02-24 16:53:16 -08001823 const char* old_cause = soa.Self()->StartAssertNoThreadSuspension("Debugger: GetThreadGroup");
Elliott Hughes2435a572012-02-17 16:07:41 -08001824 // Okay, so it's an object, but is it actually a thread?
Ian Rogers50b35e22012-10-04 10:09:15 -07001825 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001826 Thread* thread;
1827 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1828 if (error == JDWP::ERR_THREAD_NOT_ALIVE) {
1829 // Zombie threads are in the null group.
1830 expandBufAddObjectId(pReply, JDWP::ObjectId(0));
Sebastien Hertz52d131d2014-03-13 16:17:40 +01001831 error = JDWP::ERR_NONE;
1832 } else if (error == JDWP::ERR_NONE) {
1833 mirror::Class* c = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_Thread);
1834 CHECK(c != nullptr);
1835 mirror::ArtField* f = c->FindInstanceField("group", "Ljava/lang/ThreadGroup;");
1836 CHECK(f != NULL);
1837 mirror::Object* group = f->GetObject(thread_object);
1838 CHECK(group != NULL);
1839 JDWP::ObjectId thread_group_id = gRegistry->Add(group);
1840 expandBufAddObjectId(pReply, thread_group_id);
Elliott Hughes221229c2013-01-08 18:17:50 -08001841 }
Ian Rogers98379392014-02-24 16:53:16 -08001842 soa.Self()->EndAssertNoThreadSuspension(old_cause);
Sebastien Hertz52d131d2014-03-13 16:17:40 +01001843 return error;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001844}
1845
Elliott Hughes88d63092013-01-09 09:55:54 -08001846std::string Dbg::GetThreadGroupName(JDWP::ObjectId thread_group_id) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001847 ScopedObjectAccess soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001848 mirror::Object* thread_group = gRegistry->Get<mirror::Object*>(thread_group_id);
Ian Rogers98379392014-02-24 16:53:16 -08001849 CHECK(thread_group != nullptr);
1850 const char* old_cause = soa.Self()->StartAssertNoThreadSuspension("Debugger: GetThreadGroupName");
1851 mirror::Class* c = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_ThreadGroup);
1852 CHECK(c != nullptr);
Brian Carlstromea46f952013-07-30 01:26:50 -07001853 mirror::ArtField* f = c->FindInstanceField("name", "Ljava/lang/String;");
Elliott Hughes499c5132011-11-17 14:55:11 -08001854 CHECK(f != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001855 mirror::String* s = reinterpret_cast<mirror::String*>(f->GetObject(thread_group));
Ian Rogers98379392014-02-24 16:53:16 -08001856 soa.Self()->EndAssertNoThreadSuspension(old_cause);
Elliott Hughes499c5132011-11-17 14:55:11 -08001857 return s->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001858}
1859
Elliott Hughes88d63092013-01-09 09:55:54 -08001860JDWP::ObjectId Dbg::GetThreadGroupParent(JDWP::ObjectId thread_group_id) {
Ian Rogers98379392014-02-24 16:53:16 -08001861 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001862 mirror::Object* thread_group = gRegistry->Get<mirror::Object*>(thread_group_id);
Ian Rogers98379392014-02-24 16:53:16 -08001863 CHECK(thread_group != nullptr);
1864 const char* old_cause = soa.Self()->StartAssertNoThreadSuspension("Debugger: GetThreadGroupParent");
1865 mirror::Class* c = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_ThreadGroup);
1866 CHECK(c != nullptr);
Brian Carlstromea46f952013-07-30 01:26:50 -07001867 mirror::ArtField* f = c->FindInstanceField("parent", "Ljava/lang/ThreadGroup;");
Elliott Hughes4e235312011-12-02 11:34:15 -08001868 CHECK(f != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001869 mirror::Object* parent = f->GetObject(thread_group);
Ian Rogers98379392014-02-24 16:53:16 -08001870 soa.Self()->EndAssertNoThreadSuspension(old_cause);
Elliott Hughes4e235312011-12-02 11:34:15 -08001871 return gRegistry->Add(parent);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001872}
1873
1874JDWP::ObjectId Dbg::GetSystemThreadGroupId() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001875 ScopedObjectAccessUnchecked soa(Thread::Current());
Brian Carlstromea46f952013-07-30 01:26:50 -07001876 mirror::ArtField* f = soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_systemThreadGroup);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001877 mirror::Object* group = f->GetObject(f->GetDeclaringClass());
Ian Rogers365c1022012-06-22 15:05:28 -07001878 return gRegistry->Add(group);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001879}
1880
1881JDWP::ObjectId Dbg::GetMainThreadGroupId() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001882 ScopedObjectAccess soa(Thread::Current());
Brian Carlstromea46f952013-07-30 01:26:50 -07001883 mirror::ArtField* f = soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_mainThreadGroup);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001884 mirror::Object* group = f->GetObject(f->GetDeclaringClass());
Ian Rogers365c1022012-06-22 15:05:28 -07001885 return gRegistry->Add(group);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001886}
1887
Jeff Hao920af3e2013-08-28 15:46:38 -07001888JDWP::JdwpThreadStatus Dbg::ToJdwpThreadStatus(ThreadState state) {
1889 switch (state) {
1890 case kBlocked:
1891 return JDWP::TS_MONITOR;
1892 case kNative:
1893 case kRunnable:
1894 case kSuspended:
1895 return JDWP::TS_RUNNING;
1896 case kSleeping:
1897 return JDWP::TS_SLEEPING;
1898 case kStarting:
1899 case kTerminated:
1900 return JDWP::TS_ZOMBIE;
1901 case kTimedWaiting:
1902 case kWaitingForDebuggerSend:
1903 case kWaitingForDebuggerSuspension:
1904 case kWaitingForDebuggerToAttach:
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01001905 case kWaitingForDeoptimization:
Jeff Hao920af3e2013-08-28 15:46:38 -07001906 case kWaitingForGcToComplete:
1907 case kWaitingForCheckPointsToRun:
1908 case kWaitingForJniOnLoad:
1909 case kWaitingForSignalCatcherOutput:
1910 case kWaitingInMainDebuggerLoop:
1911 case kWaitingInMainSignalCatcherLoop:
1912 case kWaitingPerformingGc:
1913 case kWaiting:
1914 return JDWP::TS_WAIT;
1915 // Don't add a 'default' here so the compiler can spot incompatible enum changes.
1916 }
1917 LOG(FATAL) << "Unknown thread state: " << state;
1918 return JDWP::TS_ZOMBIE;
1919}
1920
Sebastien Hertz52d131d2014-03-13 16:17:40 +01001921JDWP::JdwpError Dbg::GetThreadStatus(JDWP::ObjectId thread_id, JDWP::JdwpThreadStatus* pThreadStatus,
1922 JDWP::JdwpSuspendStatus* pSuspendStatus) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001923 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes499c5132011-11-17 14:55:11 -08001924
Elliott Hughes9e0c1752013-01-09 14:02:58 -08001925 *pSuspendStatus = JDWP::SUSPEND_STATUS_NOT_SUSPENDED;
1926
Ian Rogers50b35e22012-10-04 10:09:15 -07001927 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001928 Thread* thread;
1929 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1930 if (error != JDWP::ERR_NONE) {
1931 if (error == JDWP::ERR_THREAD_NOT_ALIVE) {
1932 *pThreadStatus = JDWP::TS_ZOMBIE;
Elliott Hughes221229c2013-01-08 18:17:50 -08001933 return JDWP::ERR_NONE;
1934 }
1935 return error;
Elliott Hughes499c5132011-11-17 14:55:11 -08001936 }
1937
Elliott Hughes9e0c1752013-01-09 14:02:58 -08001938 if (IsSuspendedForDebugger(soa, thread)) {
1939 *pSuspendStatus = JDWP::SUSPEND_STATUS_SUSPENDED;
Elliott Hughes499c5132011-11-17 14:55:11 -08001940 }
1941
Jeff Hao920af3e2013-08-28 15:46:38 -07001942 *pThreadStatus = ToJdwpThreadStatus(thread->GetState());
Elliott Hughes221229c2013-01-08 18:17:50 -08001943 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001944}
1945
Elliott Hughes221229c2013-01-08 18:17:50 -08001946JDWP::JdwpError Dbg::GetThreadDebugSuspendCount(JDWP::ObjectId thread_id, JDWP::ExpandBuf* pReply) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001947 ScopedObjectAccess soa(Thread::Current());
Ian Rogers50b35e22012-10-04 10:09:15 -07001948 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001949 Thread* thread;
1950 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1951 if (error != JDWP::ERR_NONE) {
1952 return error;
Elliott Hughes2435a572012-02-17 16:07:41 -08001953 }
Ian Rogers50b35e22012-10-04 10:09:15 -07001954 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001955 expandBufAdd4BE(pReply, thread->GetDebugSuspendCount());
Elliott Hughes2435a572012-02-17 16:07:41 -08001956 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001957}
1958
Elliott Hughesf9501702013-01-11 11:22:27 -08001959JDWP::JdwpError Dbg::Interrupt(JDWP::ObjectId thread_id) {
1960 ScopedObjectAccess soa(Thread::Current());
1961 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
1962 Thread* thread;
1963 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1964 if (error != JDWP::ERR_NONE) {
1965 return error;
1966 }
Ian Rogersdd7624d2014-03-14 17:43:00 -07001967 thread->Interrupt(soa.Self());
Elliott Hughesf9501702013-01-11 11:22:27 -08001968 return JDWP::ERR_NONE;
1969}
1970
Elliott Hughescaf76542012-06-28 16:08:22 -07001971void Dbg::GetThreads(JDWP::ObjectId thread_group_id, std::vector<JDWP::ObjectId>& thread_ids) {
Ian Rogers365c1022012-06-22 15:05:28 -07001972 class ThreadListVisitor {
1973 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001974 ThreadListVisitor(const ScopedObjectAccessUnchecked& soa, mirror::Object* desired_thread_group,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001975 std::vector<JDWP::ObjectId>& thread_ids)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001976 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
jeffhao0dfbb7e2012-11-28 15:26:03 -08001977 : soa_(soa), desired_thread_group_(desired_thread_group), thread_ids_(thread_ids) {}
Ian Rogers365c1022012-06-22 15:05:28 -07001978
Elliott Hughesa2155262011-11-16 16:26:58 -08001979 static void Visit(Thread* t, void* arg) {
1980 reinterpret_cast<ThreadListVisitor*>(arg)->Visit(t);
1981 }
1982
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001983 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1984 // annotalysis.
1985 void Visit(Thread* t) NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughesa2155262011-11-16 16:26:58 -08001986 if (t == Dbg::GetDebugThread()) {
1987 // Skip the JDWP thread. Some debuggers get bent out of shape when they can't suspend and
1988 // query all threads, so it's easier if we just don't tell them about this thread.
1989 return;
1990 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001991 mirror::Object* peer = t->GetPeer();
jeffhao0dfbb7e2012-11-28 15:26:03 -08001992 if (IsInDesiredThreadGroup(peer)) {
Ian Rogers120f1c72012-09-28 17:17:10 -07001993 thread_ids_.push_back(gRegistry->Add(peer));
Elliott Hughesa2155262011-11-16 16:26:58 -08001994 }
1995 }
1996
Ian Rogers365c1022012-06-22 15:05:28 -07001997 private:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001998 bool IsInDesiredThreadGroup(mirror::Object* peer)
jeffhao0dfbb7e2012-11-28 15:26:03 -08001999 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
jeffhao0dfbb7e2012-11-28 15:26:03 -08002000 // peer might be NULL if the thread is still starting up.
2001 if (peer == NULL) {
2002 // We can't tell the debugger about this thread yet.
2003 // TODO: if we identified threads to the debugger by their Thread*
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002004 // rather than their peer's mirror::Object*, we could fix this.
jeffhao0dfbb7e2012-11-28 15:26:03 -08002005 // Doing so might help us report ZOMBIE threads too.
2006 return false;
2007 }
jeffhaoc1e04902012-12-13 12:41:10 -08002008 // Do we want threads from all thread groups?
2009 if (desired_thread_group_ == NULL) {
2010 return true;
2011 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002012 mirror::Object* group = soa_.DecodeField(WellKnownClasses::java_lang_Thread_group)->GetObject(peer);
jeffhao0dfbb7e2012-11-28 15:26:03 -08002013 return (group == desired_thread_group_);
2014 }
2015
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07002016 const ScopedObjectAccessUnchecked& soa_;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002017 mirror::Object* const desired_thread_group_;
Elliott Hughescaf76542012-06-28 16:08:22 -07002018 std::vector<JDWP::ObjectId>& thread_ids_;
Elliott Hughesa2155262011-11-16 16:26:58 -08002019 };
2020
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002021 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002022 mirror::Object* thread_group = gRegistry->Get<mirror::Object*>(thread_group_id);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002023 ThreadListVisitor tlv(soa, thread_group, thread_ids);
Ian Rogers50b35e22012-10-04 10:09:15 -07002024 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughesf8349362012-06-18 15:00:06 -07002025 Runtime::Current()->GetThreadList()->ForEach(ThreadListVisitor::Visit, &tlv);
Elliott Hughescaf76542012-06-28 16:08:22 -07002026}
Elliott Hughesa2155262011-11-16 16:26:58 -08002027
Elliott Hughescaf76542012-06-28 16:08:22 -07002028void Dbg::GetChildThreadGroups(JDWP::ObjectId thread_group_id, std::vector<JDWP::ObjectId>& child_thread_group_ids) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002029 ScopedObjectAccess soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002030 mirror::Object* thread_group = gRegistry->Get<mirror::Object*>(thread_group_id);
Elliott Hughescaf76542012-06-28 16:08:22 -07002031
2032 // Get the ArrayList<ThreadGroup> "groups" out of this thread group...
Brian Carlstromea46f952013-07-30 01:26:50 -07002033 mirror::ArtField* groups_field = thread_group->GetClass()->FindInstanceField("groups", "Ljava/util/List;");
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002034 mirror::Object* groups_array_list = groups_field->GetObject(thread_group);
Elliott Hughescaf76542012-06-28 16:08:22 -07002035
2036 // Get the array and size out of the ArrayList<ThreadGroup>...
Brian Carlstromea46f952013-07-30 01:26:50 -07002037 mirror::ArtField* array_field = groups_array_list->GetClass()->FindInstanceField("array", "[Ljava/lang/Object;");
2038 mirror::ArtField* size_field = groups_array_list->GetClass()->FindInstanceField("size", "I");
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002039 mirror::ObjectArray<mirror::Object>* groups_array =
2040 array_field->GetObject(groups_array_list)->AsObjectArray<mirror::Object>();
Elliott Hughescaf76542012-06-28 16:08:22 -07002041 const int32_t size = size_field->GetInt(groups_array_list);
2042
2043 // Copy the first 'size' elements out of the array into the result.
2044 for (int32_t i = 0; i < size; ++i) {
2045 child_thread_group_ids.push_back(gRegistry->Add(groups_array->Get(i)));
Elliott Hughesa2155262011-11-16 16:26:58 -08002046 }
2047}
2048
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002049static int GetStackDepth(Thread* thread)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002050 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002051 struct CountStackDepthVisitor : public StackVisitor {
Brian Carlstrom93ba8932013-07-17 21:31:49 -07002052 explicit CountStackDepthVisitor(Thread* thread)
Ian Rogers7a22fa62013-01-23 12:16:16 -08002053 : StackVisitor(thread, NULL), depth(0) {}
Ian Rogers0399dde2012-06-06 17:09:28 -07002054
Elliott Hughes64f574f2013-02-20 14:57:12 -08002055 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2056 // annotalysis.
2057 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07002058 if (!GetMethod()->IsRuntimeMethod()) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -08002059 ++depth;
2060 }
Elliott Hughes530fa002012-03-12 11:44:49 -07002061 return true;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08002062 }
2063 size_t depth;
2064 };
Elliott Hughes08fc03a2012-06-26 17:34:00 -07002065
Ian Rogers7a22fa62013-01-23 12:16:16 -08002066 CountStackDepthVisitor visitor(thread);
Ian Rogers0399dde2012-06-06 17:09:28 -07002067 visitor.WalkStack();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08002068 return visitor.depth;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002069}
2070
Elliott Hughes221229c2013-01-08 18:17:50 -08002071JDWP::JdwpError Dbg::GetThreadFrameCount(JDWP::ObjectId thread_id, size_t& result) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002072 ScopedObjectAccess soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08002073 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002074 Thread* thread;
2075 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
2076 if (error != JDWP::ERR_NONE) {
2077 return error;
2078 }
Elliott Hughesf15f4a02013-01-09 10:09:38 -08002079 if (!IsSuspendedForDebugger(soa, thread)) {
2080 return JDWP::ERR_THREAD_NOT_SUSPENDED;
2081 }
Elliott Hughes221229c2013-01-08 18:17:50 -08002082 result = GetStackDepth(thread);
2083 return JDWP::ERR_NONE;
Elliott Hughes86964332012-02-15 19:37:42 -08002084}
2085
Ian Rogers306057f2012-11-26 12:45:53 -08002086JDWP::JdwpError Dbg::GetThreadFrames(JDWP::ObjectId thread_id, size_t start_frame,
2087 size_t frame_count, JDWP::ExpandBuf* buf) {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002088 class GetFrameVisitor : public StackVisitor {
2089 public:
Ian Rogers7a22fa62013-01-23 12:16:16 -08002090 GetFrameVisitor(Thread* thread, size_t start_frame, size_t frame_count, JDWP::ExpandBuf* buf)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002091 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08002092 : StackVisitor(thread, NULL), depth_(0),
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002093 start_frame_(start_frame), frame_count_(frame_count), buf_(buf) {
2094 expandBufAdd4BE(buf_, frame_count_);
Elliott Hughes03181a82011-11-17 17:22:21 -08002095 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002096
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002097 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2098 // annotalysis.
2099 virtual bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07002100 if (GetMethod()->IsRuntimeMethod()) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07002101 return true; // The debugger can't do anything useful with a frame that has no Method*.
Elliott Hughes03181a82011-11-17 17:22:21 -08002102 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002103 if (depth_ >= start_frame_ + frame_count_) {
Elliott Hughes530fa002012-03-12 11:44:49 -07002104 return false;
Elliott Hughes03181a82011-11-17 17:22:21 -08002105 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002106 if (depth_ >= start_frame_) {
2107 JDWP::FrameId frame_id(GetFrameId());
2108 JDWP::JdwpLocation location;
2109 SetLocation(location, GetMethod(), GetDexPc());
Ian Rogersef7d42f2014-01-06 12:55:46 -08002110 VLOG(jdwp) << StringPrintf(" Frame %3zd: id=%3" PRIu64 " ", depth_, frame_id) << location;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002111 expandBufAdd8BE(buf_, frame_id);
2112 expandBufAddLocation(buf_, location);
2113 }
2114 ++depth_;
Elliott Hughes530fa002012-03-12 11:44:49 -07002115 return true;
Elliott Hughes03181a82011-11-17 17:22:21 -08002116 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002117
2118 private:
2119 size_t depth_;
2120 const size_t start_frame_;
2121 const size_t frame_count_;
2122 JDWP::ExpandBuf* buf_;
Elliott Hughes03181a82011-11-17 17:22:21 -08002123 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002124
2125 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08002126 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002127 Thread* thread;
2128 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
2129 if (error != JDWP::ERR_NONE) {
2130 return error;
2131 }
Elliott Hughesf15f4a02013-01-09 10:09:38 -08002132 if (!IsSuspendedForDebugger(soa, thread)) {
2133 return JDWP::ERR_THREAD_NOT_SUSPENDED;
2134 }
Ian Rogers7a22fa62013-01-23 12:16:16 -08002135 GetFrameVisitor visitor(thread, start_frame, frame_count, buf);
Ian Rogers0399dde2012-06-06 17:09:28 -07002136 visitor.WalkStack();
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002137 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002138}
2139
2140JDWP::ObjectId Dbg::GetThreadSelfId() {
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07002141 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogerscfaa4552012-11-26 21:00:08 -08002142 return gRegistry->Add(soa.Self()->GetPeer());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002143}
2144
Elliott Hughes475fc232011-10-25 15:00:35 -07002145void Dbg::SuspendVM() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002146 Runtime::Current()->GetThreadList()->SuspendAllForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002147}
2148
2149void Dbg::ResumeVM() {
Elliott Hughesc61a2672012-06-21 14:52:29 -07002150 Runtime::Current()->GetThreadList()->UndoDebuggerSuspensions();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002151}
2152
Elliott Hughes221229c2013-01-08 18:17:50 -08002153JDWP::JdwpError Dbg::SuspendThread(JDWP::ObjectId thread_id, bool request_suspension) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002154 ScopedLocalRef<jobject> peer(Thread::Current()->GetJniEnv(), NULL);
2155 {
2156 ScopedObjectAccess soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002157 peer.reset(soa.AddLocalReference<jobject>(gRegistry->Get<mirror::Object*>(thread_id)));
Elliott Hughes4e235312011-12-02 11:34:15 -08002158 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002159 if (peer.get() == NULL) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002160 return JDWP::ERR_THREAD_NOT_ALIVE;
2161 }
2162 // Suspend thread to build stack trace.
Elliott Hughesf327e072013-01-09 16:01:26 -08002163 bool timed_out;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07002164 Thread* thread = ThreadList::SuspendThreadByPeer(peer.get(), request_suspension, true,
2165 &timed_out);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002166 if (thread != NULL) {
2167 return JDWP::ERR_NONE;
Elliott Hughesf327e072013-01-09 16:01:26 -08002168 } else if (timed_out) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002169 return JDWP::ERR_INTERNAL;
2170 } else {
2171 return JDWP::ERR_THREAD_NOT_ALIVE;
2172 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002173}
2174
Elliott Hughes221229c2013-01-08 18:17:50 -08002175void Dbg::ResumeThread(JDWP::ObjectId thread_id) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002176 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002177 mirror::Object* peer = gRegistry->Get<mirror::Object*>(thread_id);
jeffhaoa77f0f62012-12-05 17:19:31 -08002178 Thread* thread;
2179 {
2180 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
2181 thread = Thread::FromManagedThread(soa, peer);
2182 }
Elliott Hughes4e235312011-12-02 11:34:15 -08002183 if (thread == NULL) {
2184 LOG(WARNING) << "No such thread for resume: " << peer;
2185 return;
2186 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002187 bool needs_resume;
2188 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002189 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002190 needs_resume = thread->GetSuspendCount() > 0;
2191 }
2192 if (needs_resume) {
Elliott Hughes546b9862012-06-20 16:06:13 -07002193 Runtime::Current()->GetThreadList()->Resume(thread, true);
2194 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002195}
2196
2197void Dbg::SuspendSelf() {
Elliott Hughes475fc232011-10-25 15:00:35 -07002198 Runtime::Current()->GetThreadList()->SuspendSelfForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002199}
2200
Ian Rogers0399dde2012-06-06 17:09:28 -07002201struct GetThisVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -08002202 GetThisVisitor(Thread* thread, Context* context, JDWP::FrameId frame_id)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002203 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08002204 : StackVisitor(thread, context), this_object(NULL), frame_id(frame_id) {}
Ian Rogers0399dde2012-06-06 17:09:28 -07002205
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002206 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2207 // annotalysis.
2208 virtual bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002209 if (frame_id != GetFrameId()) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002210 return true; // continue
Ian Rogers0399dde2012-06-06 17:09:28 -07002211 } else {
Ian Rogers62d6c772013-02-27 08:32:07 -08002212 this_object = GetThisObject();
2213 return false;
Ian Rogers0399dde2012-06-06 17:09:28 -07002214 }
Elliott Hughes86b00102011-12-05 17:54:26 -08002215 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002216
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002217 mirror::Object* this_object;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002218 JDWP::FrameId frame_id;
Ian Rogers0399dde2012-06-06 17:09:28 -07002219};
2220
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002221JDWP::JdwpError Dbg::GetThisObject(JDWP::ObjectId thread_id, JDWP::FrameId frame_id,
2222 JDWP::ObjectId* result) {
2223 ScopedObjectAccessUnchecked soa(Thread::Current());
2224 Thread* thread;
2225 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002226 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002227 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
2228 if (error != JDWP::ERR_NONE) {
2229 return error;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002230 }
Elliott Hughes9e0c1752013-01-09 14:02:58 -08002231 if (!IsSuspendedForDebugger(soa, thread)) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002232 return JDWP::ERR_THREAD_NOT_SUSPENDED;
2233 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002234 }
Elliott Hughescaf76542012-06-28 16:08:22 -07002235 UniquePtr<Context> context(Context::Create());
Ian Rogers7a22fa62013-01-23 12:16:16 -08002236 GetThisVisitor visitor(thread, context.get(), frame_id);
Ian Rogers0399dde2012-06-06 17:09:28 -07002237 visitor.WalkStack();
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002238 *result = gRegistry->Add(visitor.this_object);
2239 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002240}
2241
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002242JDWP::JdwpError Dbg::GetLocalValue(JDWP::ObjectId thread_id, JDWP::FrameId frame_id, int slot,
2243 JDWP::JdwpTag tag, uint8_t* buf, size_t width) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002244 struct GetLocalVisitor : public StackVisitor {
Ian Rogers98379392014-02-24 16:53:16 -08002245 GetLocalVisitor(const ScopedObjectAccessUnchecked& soa, Thread* thread, Context* context,
2246 JDWP::FrameId frame_id, int slot, JDWP::JdwpTag tag, uint8_t* buf, size_t width)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002247 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers98379392014-02-24 16:53:16 -08002248 : StackVisitor(thread, context), soa_(soa), frame_id_(frame_id), slot_(slot), tag_(tag),
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002249 buf_(buf), width_(width), error_(JDWP::ERR_NONE) {}
Ian Rogersca190662012-06-26 15:45:57 -07002250
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002251 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2252 // annotalysis.
2253 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07002254 if (GetFrameId() != frame_id_) {
2255 return true; // Not our frame, carry on.
Elliott Hughesdbb40792011-11-18 17:05:22 -08002256 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002257 // TODO: check that the tag is compatible with the actual type of the slot!
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002258 // TODO: check slot is valid for this method or return INVALID_SLOT error.
Brian Carlstromea46f952013-07-30 01:26:50 -07002259 mirror::ArtMethod* m = GetMethod();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002260 if (m->IsNative()) {
2261 // We can't read local value from native method.
2262 error_ = JDWP::ERR_OPAQUE_FRAME;
2263 return false;
2264 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002265 uint16_t reg = DemangleSlot(slot_, m);
Elliott Hughesdbb40792011-11-18 17:05:22 -08002266
Ian Rogers0399dde2012-06-06 17:09:28 -07002267 switch (tag_) {
2268 case JDWP::JT_BOOLEAN:
2269 {
2270 CHECK_EQ(width_, 1U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002271 uint32_t intVal = GetVReg(m, reg, kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002272 VLOG(jdwp) << "get boolean local " << reg << " = " << intVal;
2273 JDWP::Set1(buf_+1, intVal != 0);
2274 }
2275 break;
2276 case JDWP::JT_BYTE:
2277 {
2278 CHECK_EQ(width_, 1U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002279 uint32_t intVal = GetVReg(m, reg, kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002280 VLOG(jdwp) << "get byte local " << reg << " = " << intVal;
2281 JDWP::Set1(buf_+1, intVal);
2282 }
2283 break;
2284 case JDWP::JT_SHORT:
2285 case JDWP::JT_CHAR:
2286 {
2287 CHECK_EQ(width_, 2U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002288 uint32_t intVal = GetVReg(m, reg, kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002289 VLOG(jdwp) << "get short/char local " << reg << " = " << intVal;
2290 JDWP::Set2BE(buf_+1, intVal);
2291 }
2292 break;
2293 case JDWP::JT_INT:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002294 {
2295 CHECK_EQ(width_, 4U);
2296 uint32_t intVal = GetVReg(m, reg, kIntVReg);
2297 VLOG(jdwp) << "get int local " << reg << " = " << intVal;
2298 JDWP::Set4BE(buf_+1, intVal);
2299 }
2300 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002301 case JDWP::JT_FLOAT:
2302 {
2303 CHECK_EQ(width_, 4U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002304 uint32_t intVal = GetVReg(m, reg, kFloatVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002305 VLOG(jdwp) << "get int/float local " << reg << " = " << intVal;
2306 JDWP::Set4BE(buf_+1, intVal);
2307 }
2308 break;
2309 case JDWP::JT_ARRAY:
2310 {
2311 CHECK_EQ(width_, sizeof(JDWP::ObjectId));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002312 mirror::Object* o = reinterpret_cast<mirror::Object*>(GetVReg(m, reg, kReferenceVReg));
Ian Rogers0399dde2012-06-06 17:09:28 -07002313 VLOG(jdwp) << "get array local " << reg << " = " << o;
Mathieu Chartier590fee92013-09-13 13:46:47 -07002314 if (!Runtime::Current()->GetHeap()->IsValidObjectAddress(o)) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002315 LOG(FATAL) << "Register " << reg << " expected to hold array: " << o;
2316 }
2317 JDWP::SetObjectId(buf_+1, gRegistry->Add(o));
2318 }
2319 break;
2320 case JDWP::JT_CLASS_LOADER:
2321 case JDWP::JT_CLASS_OBJECT:
2322 case JDWP::JT_OBJECT:
2323 case JDWP::JT_STRING:
2324 case JDWP::JT_THREAD:
2325 case JDWP::JT_THREAD_GROUP:
2326 {
2327 CHECK_EQ(width_, sizeof(JDWP::ObjectId));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002328 mirror::Object* o = reinterpret_cast<mirror::Object*>(GetVReg(m, reg, kReferenceVReg));
Ian Rogers0399dde2012-06-06 17:09:28 -07002329 VLOG(jdwp) << "get object local " << reg << " = " << o;
Mathieu Chartier590fee92013-09-13 13:46:47 -07002330 if (!Runtime::Current()->GetHeap()->IsValidObjectAddress(o)) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002331 LOG(FATAL) << "Register " << reg << " expected to hold object: " << o;
2332 }
Ian Rogers98379392014-02-24 16:53:16 -08002333 tag_ = TagFromObject(soa_, o);
Ian Rogers0399dde2012-06-06 17:09:28 -07002334 JDWP::SetObjectId(buf_+1, gRegistry->Add(o));
2335 }
2336 break;
2337 case JDWP::JT_DOUBLE:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002338 {
2339 CHECK_EQ(width_, 8U);
2340 uint32_t lo = GetVReg(m, reg, kDoubleLoVReg);
2341 uint64_t hi = GetVReg(m, reg + 1, kDoubleHiVReg);
2342 uint64_t longVal = (hi << 32) | lo;
2343 VLOG(jdwp) << "get double/long local " << hi << ":" << lo << " = " << longVal;
2344 JDWP::Set8BE(buf_+1, longVal);
2345 }
2346 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002347 case JDWP::JT_LONG:
2348 {
2349 CHECK_EQ(width_, 8U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002350 uint32_t lo = GetVReg(m, reg, kLongLoVReg);
2351 uint64_t hi = GetVReg(m, reg + 1, kLongHiVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002352 uint64_t longVal = (hi << 32) | lo;
2353 VLOG(jdwp) << "get double/long local " << hi << ":" << lo << " = " << longVal;
2354 JDWP::Set8BE(buf_+1, longVal);
2355 }
2356 break;
2357 default:
2358 LOG(FATAL) << "Unknown tag " << tag_;
2359 break;
2360 }
2361
2362 // Prepend tag, which may have been updated.
2363 JDWP::Set1(buf_, tag_);
2364 return false;
2365 }
Ian Rogers98379392014-02-24 16:53:16 -08002366 const ScopedObjectAccessUnchecked& soa_;
Ian Rogers0399dde2012-06-06 17:09:28 -07002367 const JDWP::FrameId frame_id_;
2368 const int slot_;
2369 JDWP::JdwpTag tag_;
2370 uint8_t* const buf_;
2371 const size_t width_;
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002372 JDWP::JdwpError error_;
Ian Rogers0399dde2012-06-06 17:09:28 -07002373 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002374
2375 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08002376 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002377 Thread* thread;
2378 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
2379 if (error != JDWP::ERR_NONE) {
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002380 return error;
Elliott Hughes221229c2013-01-08 18:17:50 -08002381 }
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002382 // TODO check thread is suspended by the debugger ?
Ian Rogers0399dde2012-06-06 17:09:28 -07002383 UniquePtr<Context> context(Context::Create());
Ian Rogers98379392014-02-24 16:53:16 -08002384 GetLocalVisitor visitor(soa, thread, context.get(), frame_id, slot, tag, buf, width);
Ian Rogers0399dde2012-06-06 17:09:28 -07002385 visitor.WalkStack();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002386 return visitor.error_;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002387}
2388
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002389JDWP::JdwpError Dbg::SetLocalValue(JDWP::ObjectId thread_id, JDWP::FrameId frame_id, int slot,
2390 JDWP::JdwpTag tag, uint64_t value, size_t width) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002391 struct SetLocalVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -08002392 SetLocalVisitor(Thread* thread, Context* context,
Ian Rogers0399dde2012-06-06 17:09:28 -07002393 JDWP::FrameId frame_id, int slot, JDWP::JdwpTag tag, uint64_t value,
Ian Rogersca190662012-06-26 15:45:57 -07002394 size_t width)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002395 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08002396 : StackVisitor(thread, context),
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002397 frame_id_(frame_id), slot_(slot), tag_(tag), value_(value), width_(width),
2398 error_(JDWP::ERR_NONE) {}
Ian Rogersca190662012-06-26 15:45:57 -07002399
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002400 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2401 // annotalysis.
2402 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07002403 if (GetFrameId() != frame_id_) {
2404 return true; // Not our frame, carry on.
2405 }
2406 // TODO: check that the tag is compatible with the actual type of the slot!
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002407 // TODO: check slot is valid for this method or return INVALID_SLOT error.
Brian Carlstromea46f952013-07-30 01:26:50 -07002408 mirror::ArtMethod* m = GetMethod();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002409 if (m->IsNative()) {
2410 // We can't read local value from native method.
2411 error_ = JDWP::ERR_OPAQUE_FRAME;
2412 return false;
2413 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002414 uint16_t reg = DemangleSlot(slot_, m);
2415
2416 switch (tag_) {
2417 case JDWP::JT_BOOLEAN:
2418 case JDWP::JT_BYTE:
2419 CHECK_EQ(width_, 1U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002420 SetVReg(m, reg, static_cast<uint32_t>(value_), kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002421 break;
2422 case JDWP::JT_SHORT:
2423 case JDWP::JT_CHAR:
2424 CHECK_EQ(width_, 2U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002425 SetVReg(m, reg, static_cast<uint32_t>(value_), kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002426 break;
2427 case JDWP::JT_INT:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002428 CHECK_EQ(width_, 4U);
2429 SetVReg(m, reg, static_cast<uint32_t>(value_), kIntVReg);
2430 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002431 case JDWP::JT_FLOAT:
2432 CHECK_EQ(width_, 4U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002433 SetVReg(m, reg, static_cast<uint32_t>(value_), kFloatVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002434 break;
2435 case JDWP::JT_ARRAY:
2436 case JDWP::JT_OBJECT:
2437 case JDWP::JT_STRING:
2438 {
2439 CHECK_EQ(width_, sizeof(JDWP::ObjectId));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002440 mirror::Object* o = gRegistry->Get<mirror::Object*>(static_cast<JDWP::ObjectId>(value_));
Elliott Hughes64f574f2013-02-20 14:57:12 -08002441 if (o == ObjectRegistry::kInvalidObject) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002442 UNIMPLEMENTED(FATAL) << "return an error code when given an invalid object to store";
2443 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002444 SetVReg(m, reg, static_cast<uint32_t>(reinterpret_cast<uintptr_t>(o)), kReferenceVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002445 }
2446 break;
2447 case JDWP::JT_DOUBLE:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002448 CHECK_EQ(width_, 8U);
2449 SetVReg(m, reg, static_cast<uint32_t>(value_), kDoubleLoVReg);
2450 SetVReg(m, reg + 1, static_cast<uint32_t>(value_ >> 32), kDoubleHiVReg);
2451 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002452 case JDWP::JT_LONG:
2453 CHECK_EQ(width_, 8U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002454 SetVReg(m, reg, static_cast<uint32_t>(value_), kLongLoVReg);
2455 SetVReg(m, reg + 1, static_cast<uint32_t>(value_ >> 32), kLongHiVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002456 break;
2457 default:
2458 LOG(FATAL) << "Unknown tag " << tag_;
2459 break;
2460 }
2461 return false;
2462 }
2463
2464 const JDWP::FrameId frame_id_;
2465 const int slot_;
2466 const JDWP::JdwpTag tag_;
2467 const uint64_t value_;
2468 const size_t width_;
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002469 JDWP::JdwpError error_;
Ian Rogers0399dde2012-06-06 17:09:28 -07002470 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002471
2472 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08002473 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002474 Thread* thread;
2475 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
2476 if (error != JDWP::ERR_NONE) {
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002477 return error;
Elliott Hughes221229c2013-01-08 18:17:50 -08002478 }
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002479 // TODO check thread is suspended by the debugger ?
Elliott Hughes08fc03a2012-06-26 17:34:00 -07002480 UniquePtr<Context> context(Context::Create());
Ian Rogers7a22fa62013-01-23 12:16:16 -08002481 SetLocalVisitor visitor(thread, context.get(), frame_id, slot, tag, value, width);
Ian Rogers0399dde2012-06-06 17:09:28 -07002482 visitor.WalkStack();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002483 return visitor.error_;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002484}
2485
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002486JDWP::ObjectId Dbg::GetThisObjectIdForEvent(mirror::Object* this_object) {
2487 // If 'this_object' isn't already in the registry, we know that we're not looking for it, so
2488 // there's no point adding it to the registry and burning through ids.
2489 // When registering an event request with an instance filter, we've been given an existing object
2490 // id so it must already be present in the registry when the event fires.
2491 JDWP::ObjectId this_id = 0;
2492 if (this_object != nullptr && gRegistry->Contains(this_object)) {
2493 this_id = gRegistry->Add(this_object);
2494 }
2495 return this_id;
2496}
2497
Ian Rogersef7d42f2014-01-06 12:55:46 -08002498void Dbg::PostLocationEvent(mirror::ArtMethod* m, int dex_pc, mirror::Object* this_object,
Jeff Hao579b0242013-11-18 13:16:49 -08002499 int event_flags, const JValue* return_value) {
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002500 if (!IsDebuggerActive()) {
2501 return;
2502 }
2503 DCHECK(m != nullptr);
2504 DCHECK_EQ(m->IsStatic(), this_object == nullptr);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002505 JDWP::JdwpLocation location;
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002506 SetLocation(location, m, dex_pc);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002507
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002508 // We need 'this' for InstanceOnly filters only.
2509 JDWP::ObjectId this_id = GetThisObjectIdForEvent(this_object);
Jeff Hao579b0242013-11-18 13:16:49 -08002510 gJdwpState->PostLocationEvent(&location, this_id, event_flags, return_value);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002511}
2512
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002513void Dbg::PostFieldAccessEvent(mirror::ArtMethod* m, int dex_pc,
2514 mirror::Object* this_object, mirror::ArtField* f) {
2515 if (!IsDebuggerActive()) {
2516 return;
2517 }
2518 DCHECK(m != nullptr);
2519 DCHECK(f != nullptr);
2520 JDWP::JdwpLocation location;
2521 SetLocation(location, m, dex_pc);
2522
2523 JDWP::RefTypeId type_id = gRegistry->AddRefType(f->GetDeclaringClass());
2524 JDWP::FieldId field_id = ToFieldId(f);
2525 JDWP::ObjectId this_id = gRegistry->Add(this_object);
2526
2527 gJdwpState->PostFieldEvent(&location, type_id, field_id, this_id, nullptr, false);
2528}
2529
2530void Dbg::PostFieldModificationEvent(mirror::ArtMethod* m, int dex_pc,
2531 mirror::Object* this_object, mirror::ArtField* f,
2532 const JValue* field_value) {
2533 if (!IsDebuggerActive()) {
2534 return;
2535 }
2536 DCHECK(m != nullptr);
2537 DCHECK(f != nullptr);
2538 DCHECK(field_value != nullptr);
2539 JDWP::JdwpLocation location;
2540 SetLocation(location, m, dex_pc);
2541
2542 JDWP::RefTypeId type_id = gRegistry->AddRefType(f->GetDeclaringClass());
2543 JDWP::FieldId field_id = ToFieldId(f);
2544 JDWP::ObjectId this_id = gRegistry->Add(this_object);
2545
2546 gJdwpState->PostFieldEvent(&location, type_id, field_id, this_id, field_value, true);
2547}
2548
2549void Dbg::PostException(const ThrowLocation& throw_location,
Brian Carlstromea46f952013-07-30 01:26:50 -07002550 mirror::ArtMethod* catch_method,
Elliott Hughes64f574f2013-02-20 14:57:12 -08002551 uint32_t catch_dex_pc, mirror::Throwable* exception_object) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002552 if (!IsDebuggerActive()) {
Ian Rogers0ad5bb82011-12-07 10:16:32 -08002553 return;
2554 }
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002555
Ian Rogers62d6c772013-02-27 08:32:07 -08002556 JDWP::JdwpLocation jdwp_throw_location;
2557 SetLocation(jdwp_throw_location, throw_location.GetMethod(), throw_location.GetDexPc());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002558 JDWP::JdwpLocation catch_location;
Elliott Hughescaf76542012-06-28 16:08:22 -07002559 SetLocation(catch_location, catch_method, catch_dex_pc);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002560
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002561 // We need 'this' for InstanceOnly filters only.
2562 JDWP::ObjectId this_id = GetThisObjectIdForEvent(throw_location.GetThis());
Elliott Hughes64f574f2013-02-20 14:57:12 -08002563 JDWP::ObjectId exception_id = gRegistry->Add(exception_object);
2564 JDWP::RefTypeId exception_class_id = gRegistry->AddRefType(exception_object->GetClass());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002565
Ian Rogers62d6c772013-02-27 08:32:07 -08002566 gJdwpState->PostException(&jdwp_throw_location, exception_id, exception_class_id, &catch_location,
2567 this_id);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002568}
2569
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002570void Dbg::PostClassPrepare(mirror::Class* c) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002571 if (!IsDebuggerActive()) {
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002572 return;
2573 }
2574
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08002575 // OLD-TODO - we currently always send both "verified" and "prepared" since
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002576 // debuggers seem to like that. There might be some advantage to honesty,
2577 // since the class may not yet be verified.
2578 int state = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
Sebastien Hertz4d8fd492014-03-28 16:29:41 +01002579 JDWP::JdwpTypeTag tag = GetTypeTag(c);
Ian Rogersfc0e94b2013-09-23 23:51:32 -07002580 gJdwpState->PostClassPrepare(tag, gRegistry->Add(c),
Ian Rogersdfb325e2013-10-30 01:00:44 -07002581 ClassHelper(c).GetDescriptor(), state);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002582}
2583
Ian Rogers62d6c772013-02-27 08:32:07 -08002584void Dbg::UpdateDebugger(Thread* thread, mirror::Object* this_object,
Ian Rogersef7d42f2014-01-06 12:55:46 -08002585 mirror::ArtMethod* m, uint32_t dex_pc) {
Ian Rogers62d6c772013-02-27 08:32:07 -08002586 if (!IsDebuggerActive() || dex_pc == static_cast<uint32_t>(-2) /* fake method exit */) {
Elliott Hughes2aa2e392012-02-17 17:15:43 -08002587 return;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002588 }
2589
Elliott Hughes2aa2e392012-02-17 17:15:43 -08002590 int event_flags = 0;
2591
Elliott Hughes86964332012-02-15 19:37:42 -08002592 if (IsBreakpoint(m, dex_pc)) {
2593 event_flags |= kBreakpoint;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002594 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002595
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002596 // If the debugger is single-stepping one of our threads, check to
2597 // see if we're that thread and we've reached a step point.
2598 const SingleStepControl* single_step_control = thread->GetSingleStepControl();
2599 DCHECK(single_step_control != nullptr);
2600 if (single_step_control->is_active) {
2601 CHECK(!m->IsNative());
2602 if (single_step_control->step_depth == JDWP::SD_INTO) {
2603 // Step into method calls. We break when the line number
2604 // or method pointer changes. If we're in SS_MIN mode, we
2605 // always stop.
2606 if (single_step_control->method != m) {
2607 event_flags |= kSingleStep;
2608 VLOG(jdwp) << "SS new method";
2609 } else if (single_step_control->step_size == JDWP::SS_MIN) {
2610 event_flags |= kSingleStep;
2611 VLOG(jdwp) << "SS new instruction";
Sebastien Hertzbb43b432014-04-14 11:59:08 +02002612 } else if (single_step_control->ContainsDexPc(dex_pc)) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002613 event_flags |= kSingleStep;
2614 VLOG(jdwp) << "SS new line";
2615 }
2616 } else if (single_step_control->step_depth == JDWP::SD_OVER) {
2617 // Step over method calls. We break when the line number is
2618 // different and the frame depth is <= the original frame
2619 // depth. (We can't just compare on the method, because we
2620 // might get unrolled past it by an exception, and it's tricky
2621 // to identify recursion.)
2622
2623 int stack_depth = GetStackDepth(thread);
2624
2625 if (stack_depth < single_step_control->stack_depth) {
2626 // Popped up one or more frames, always trigger.
2627 event_flags |= kSingleStep;
2628 VLOG(jdwp) << "SS method pop";
2629 } else if (stack_depth == single_step_control->stack_depth) {
2630 // Same depth, see if we moved.
2631 if (single_step_control->step_size == JDWP::SS_MIN) {
Elliott Hughes86964332012-02-15 19:37:42 -08002632 event_flags |= kSingleStep;
2633 VLOG(jdwp) << "SS new instruction";
Sebastien Hertzbb43b432014-04-14 11:59:08 +02002634 } else if (single_step_control->ContainsDexPc(dex_pc)) {
Elliott Hughes2435a572012-02-17 16:07:41 -08002635 event_flags |= kSingleStep;
2636 VLOG(jdwp) << "SS new line";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002637 }
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002638 }
2639 } else {
2640 CHECK_EQ(single_step_control->step_depth, JDWP::SD_OUT);
2641 // Return from the current method. We break when the frame
2642 // depth pops up.
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002643
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002644 // This differs from the "method exit" break in that it stops
2645 // with the PC at the next instruction in the returned-to
2646 // function, rather than the end of the returning function.
Elliott Hughes86964332012-02-15 19:37:42 -08002647
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002648 int stack_depth = GetStackDepth(thread);
2649 if (stack_depth < single_step_control->stack_depth) {
2650 event_flags |= kSingleStep;
2651 VLOG(jdwp) << "SS method pop";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002652 }
2653 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002654 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002655
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002656 // If there's something interesting going on, see if it matches one
2657 // of the debugger filters.
2658 if (event_flags != 0) {
Jeff Hao579b0242013-11-18 13:16:49 -08002659 Dbg::PostLocationEvent(m, dex_pc, this_object, event_flags, nullptr);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002660 }
2661}
2662
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002663// Process request while all mutator threads are suspended.
2664void Dbg::ProcessDeoptimizationRequest(const DeoptimizationRequest& request) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002665 instrumentation::Instrumentation* instrumentation = Runtime::Current()->GetInstrumentation();
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002666 switch (request.kind) {
2667 case DeoptimizationRequest::kNothing:
2668 LOG(WARNING) << "Ignoring empty deoptimization request.";
2669 break;
2670 case DeoptimizationRequest::kFullDeoptimization:
2671 VLOG(jdwp) << "Deoptimize the world";
2672 instrumentation->DeoptimizeEverything();
2673 break;
2674 case DeoptimizationRequest::kFullUndeoptimization:
2675 VLOG(jdwp) << "Undeoptimize the world";
2676 instrumentation->UndeoptimizeEverything();
2677 break;
2678 case DeoptimizationRequest::kSelectiveDeoptimization:
2679 VLOG(jdwp) << "Deoptimize method " << PrettyMethod(request.method);
2680 instrumentation->Deoptimize(request.method);
2681 break;
2682 case DeoptimizationRequest::kSelectiveUndeoptimization:
2683 VLOG(jdwp) << "Undeoptimize method " << PrettyMethod(request.method);
2684 instrumentation->Undeoptimize(request.method);
2685 break;
2686 default:
2687 LOG(FATAL) << "Unsupported deoptimization request kind " << request.kind;
2688 break;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002689 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002690}
2691
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002692void Dbg::RequestDeoptimization(const DeoptimizationRequest& req) {
2693 if (req.kind == DeoptimizationRequest::kNothing) {
2694 // Nothing to do.
2695 return;
2696 }
2697 MutexLock mu(Thread::Current(), *deoptimization_lock_);
2698 switch (req.kind) {
2699 case DeoptimizationRequest::kFullDeoptimization: {
2700 DCHECK(req.method == nullptr);
2701 if (full_deoptimization_event_count_ == 0) {
2702 VLOG(jdwp) << "Request full deoptimization";
2703 deoptimization_requests_.push_back(req);
2704 }
2705 ++full_deoptimization_event_count_;
2706 break;
2707 }
2708 case DeoptimizationRequest::kFullUndeoptimization: {
2709 DCHECK(req.method == nullptr);
2710 DCHECK_GT(full_deoptimization_event_count_, 0U);
2711 --full_deoptimization_event_count_;
2712 if (full_deoptimization_event_count_ == 0) {
2713 VLOG(jdwp) << "Request full undeoptimization";
2714 deoptimization_requests_.push_back(req);
2715 }
2716 break;
2717 }
2718 case DeoptimizationRequest::kSelectiveDeoptimization: {
2719 DCHECK(req.method != nullptr);
2720 VLOG(jdwp) << "Request deoptimization of " << PrettyMethod(req.method);
2721 deoptimization_requests_.push_back(req);
2722 break;
2723 }
2724 case DeoptimizationRequest::kSelectiveUndeoptimization: {
2725 DCHECK(req.method != nullptr);
2726 VLOG(jdwp) << "Request undeoptimization of " << PrettyMethod(req.method);
2727 deoptimization_requests_.push_back(req);
2728 break;
2729 }
2730 default: {
2731 LOG(FATAL) << "Unknown deoptimization request kind " << req.kind;
2732 break;
2733 }
2734 }
2735}
2736
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002737void Dbg::ManageDeoptimization() {
2738 Thread* const self = Thread::Current();
2739 {
2740 // Avoid suspend/resume if there is no pending request.
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002741 MutexLock mu(self, *deoptimization_lock_);
2742 if (deoptimization_requests_.empty()) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002743 return;
2744 }
2745 }
2746 CHECK_EQ(self->GetState(), kRunnable);
2747 self->TransitionFromRunnableToSuspended(kWaitingForDeoptimization);
2748 // We need to suspend mutator threads first.
2749 Runtime* const runtime = Runtime::Current();
2750 runtime->GetThreadList()->SuspendAll();
2751 const ThreadState old_state = self->SetStateUnsafe(kRunnable);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002752 {
2753 MutexLock mu(self, *deoptimization_lock_);
2754 for (const DeoptimizationRequest& request : deoptimization_requests_) {
2755 ProcessDeoptimizationRequest(request);
2756 }
2757 deoptimization_requests_.clear();
2758 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002759 CHECK_EQ(self->SetStateUnsafe(old_state), kRunnable);
2760 runtime->GetThreadList()->ResumeAll();
2761 self->TransitionFromSuspendedToRunnable();
2762}
2763
Sebastien Hertza76a6d42014-03-20 16:40:17 +01002764static bool IsMethodPossiblyInlined(Thread* self, mirror::ArtMethod* m)
2765 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2766 MethodHelper mh(m);
2767 const DexFile::CodeItem* code_item = mh.GetCodeItem();
2768 if (code_item == nullptr) {
2769 // TODO We should not be asked to watch location in a native or abstract method so the code item
2770 // should never be null. We could just check we never encounter this case.
2771 return false;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002772 }
Sebastien Hertza76a6d42014-03-20 16:40:17 +01002773 SirtRef<mirror::DexCache> dex_cache(self, mh.GetDexCache());
2774 SirtRef<mirror::ClassLoader> class_loader(self, mh.GetClassLoader());
2775 verifier::MethodVerifier verifier(&mh.GetDexFile(), &dex_cache, &class_loader,
2776 &mh.GetClassDef(), code_item, m->GetDexMethodIndex(), m,
2777 m->GetAccessFlags(), false, true);
2778 // Note: we don't need to verify the method.
2779 return InlineMethodAnalyser::AnalyseMethodCode(&verifier, nullptr);
2780}
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002781
Sebastien Hertza76a6d42014-03-20 16:40:17 +01002782static const Breakpoint* FindFirstBreakpointForMethod(mirror::ArtMethod* m)
2783 EXCLUSIVE_LOCKS_REQUIRED(Locks::breakpoint_lock_) {
2784 for (const Breakpoint& breakpoint : gBreakpoints) {
2785 if (breakpoint.method == m) {
2786 return &breakpoint;
2787 }
2788 }
2789 return nullptr;
2790}
2791
2792// Sanity checks all existing breakpoints on the same method.
2793static void SanityCheckExistingBreakpoints(mirror::ArtMethod* m, bool need_full_deoptimization)
2794 EXCLUSIVE_LOCKS_REQUIRED(Locks::breakpoint_lock_) {
2795 if (kIsDebugBuild) {
2796 for (const Breakpoint& breakpoint : gBreakpoints) {
2797 CHECK_EQ(need_full_deoptimization, breakpoint.need_full_deoptimization);
2798 }
2799 if (need_full_deoptimization) {
2800 // We should have deoptimized everything but not "selectively" deoptimized this method.
2801 CHECK(Runtime::Current()->GetInstrumentation()->AreAllMethodsDeoptimized());
2802 CHECK(!Runtime::Current()->GetInstrumentation()->IsDeoptimized(m));
2803 } else {
2804 // We should have "selectively" deoptimized this method.
2805 // Note: while we have not deoptimized everything for this method, we may have done it for
2806 // another event.
2807 CHECK(Runtime::Current()->GetInstrumentation()->IsDeoptimized(m));
2808 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002809 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002810}
2811
Sebastien Hertza76a6d42014-03-20 16:40:17 +01002812// Installs a breakpoint at the specified location. Also indicates through the deoptimization
2813// request if we need to deoptimize.
2814void Dbg::WatchLocation(const JDWP::JdwpLocation* location, DeoptimizationRequest* req) {
2815 Thread* const self = Thread::Current();
Brian Carlstromea46f952013-07-30 01:26:50 -07002816 mirror::ArtMethod* m = FromMethodId(location->method_id);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01002817 DCHECK(m != nullptr) << "No method for method id " << location->method_id;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002818
Sebastien Hertza76a6d42014-03-20 16:40:17 +01002819 MutexLock mu(self, *Locks::breakpoint_lock_);
2820 const Breakpoint* const existing_breakpoint = FindFirstBreakpointForMethod(m);
2821 bool need_full_deoptimization;
2822 if (existing_breakpoint == nullptr) {
2823 // There is no breakpoint on this method yet: we need to deoptimize. If this method may be
2824 // inlined, we deoptimize everything; otherwise we deoptimize only this method.
2825 need_full_deoptimization = IsMethodPossiblyInlined(self, m);
2826 if (need_full_deoptimization) {
2827 req->kind = DeoptimizationRequest::kFullDeoptimization;
2828 req->method = nullptr;
2829 } else {
2830 req->kind = DeoptimizationRequest::kSelectiveDeoptimization;
2831 req->method = m;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002832 }
Sebastien Hertza76a6d42014-03-20 16:40:17 +01002833 } else {
2834 // There is at least one breakpoint for this method: we don't need to deoptimize.
2835 req->kind = DeoptimizationRequest::kNothing;
2836 req->method = nullptr;
2837
2838 need_full_deoptimization = existing_breakpoint->need_full_deoptimization;
2839 SanityCheckExistingBreakpoints(m, need_full_deoptimization);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002840 }
2841
Sebastien Hertza76a6d42014-03-20 16:40:17 +01002842 gBreakpoints.push_back(Breakpoint(m, location->dex_pc, need_full_deoptimization));
2843 VLOG(jdwp) << "Set breakpoint #" << (gBreakpoints.size() - 1) << ": "
2844 << gBreakpoints[gBreakpoints.size() - 1];
2845}
2846
2847// Uninstalls a breakpoint at the specified location. Also indicates through the deoptimization
2848// request if we need to undeoptimize.
2849void Dbg::UnwatchLocation(const JDWP::JdwpLocation* location, DeoptimizationRequest* req) {
2850 mirror::ArtMethod* m = FromMethodId(location->method_id);
2851 DCHECK(m != nullptr) << "No method for method id " << location->method_id;
2852
2853 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
2854 bool need_full_deoptimization = false;
2855 for (size_t i = 0, e = gBreakpoints.size(); i < e; ++i) {
2856 if (gBreakpoints[i].method == m && gBreakpoints[i].dex_pc == location->dex_pc) {
2857 VLOG(jdwp) << "Removed breakpoint #" << i << ": " << gBreakpoints[i];
2858 need_full_deoptimization = gBreakpoints[i].need_full_deoptimization;
2859 DCHECK_NE(need_full_deoptimization, Runtime::Current()->GetInstrumentation()->IsDeoptimized(m));
2860 gBreakpoints.erase(gBreakpoints.begin() + i);
2861 break;
2862 }
2863 }
2864 const Breakpoint* const existing_breakpoint = FindFirstBreakpointForMethod(m);
2865 if (existing_breakpoint == nullptr) {
2866 // There is no more breakpoint on this method: we need to undeoptimize.
2867 if (need_full_deoptimization) {
2868 // This method required full deoptimization: we need to undeoptimize everything.
2869 req->kind = DeoptimizationRequest::kFullUndeoptimization;
2870 req->method = nullptr;
2871 } else {
2872 // This method required selective deoptimization: we need to undeoptimize only that method.
2873 req->kind = DeoptimizationRequest::kSelectiveUndeoptimization;
2874 req->method = m;
2875 }
2876 } else {
2877 // There is at least one breakpoint for this method: we don't need to undeoptimize.
2878 req->kind = DeoptimizationRequest::kNothing;
2879 req->method = nullptr;
2880 SanityCheckExistingBreakpoints(m, need_full_deoptimization);
Elliott Hughes86964332012-02-15 19:37:42 -08002881 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002882}
2883
Jeff Hao449db332013-04-12 18:30:52 -07002884// Scoped utility class to suspend a thread so that we may do tasks such as walk its stack. Doesn't
2885// cause suspension if the thread is the current thread.
2886class ScopedThreadSuspension {
2887 public:
Ian Rogers33e95662013-05-20 20:29:14 -07002888 ScopedThreadSuspension(Thread* self, JDWP::ObjectId thread_id)
Sebastien Hertz52d131d2014-03-13 16:17:40 +01002889 LOCKS_EXCLUDED(Locks::thread_list_lock_)
Ian Rogers33e95662013-05-20 20:29:14 -07002890 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) :
Jeff Hao449db332013-04-12 18:30:52 -07002891 thread_(NULL),
2892 error_(JDWP::ERR_NONE),
2893 self_suspend_(false),
Ian Rogers33e95662013-05-20 20:29:14 -07002894 other_suspend_(false) {
Jeff Hao449db332013-04-12 18:30:52 -07002895 ScopedObjectAccessUnchecked soa(self);
2896 {
2897 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
2898 error_ = DecodeThread(soa, thread_id, thread_);
2899 }
2900 if (error_ == JDWP::ERR_NONE) {
2901 if (thread_ == soa.Self()) {
2902 self_suspend_ = true;
2903 } else {
2904 soa.Self()->TransitionFromRunnableToSuspended(kWaitingForDebuggerSuspension);
2905 jobject thread_peer = gRegistry->GetJObject(thread_id);
2906 bool timed_out;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07002907 Thread* suspended_thread = ThreadList::SuspendThreadByPeer(thread_peer, true, true,
2908 &timed_out);
Jeff Hao449db332013-04-12 18:30:52 -07002909 CHECK_EQ(soa.Self()->TransitionFromSuspendedToRunnable(), kWaitingForDebuggerSuspension);
2910 if (suspended_thread == NULL) {
2911 // Thread terminated from under us while suspending.
2912 error_ = JDWP::ERR_INVALID_THREAD;
2913 } else {
2914 CHECK_EQ(suspended_thread, thread_);
2915 other_suspend_ = true;
2916 }
2917 }
2918 }
Elliott Hughes2435a572012-02-17 16:07:41 -08002919 }
Elliott Hughes86964332012-02-15 19:37:42 -08002920
Jeff Hao449db332013-04-12 18:30:52 -07002921 Thread* GetThread() const {
2922 return thread_;
2923 }
2924
2925 JDWP::JdwpError GetError() const {
2926 return error_;
2927 }
2928
2929 ~ScopedThreadSuspension() {
2930 if (other_suspend_) {
2931 Runtime::Current()->GetThreadList()->Resume(thread_, true);
2932 }
2933 }
2934
2935 private:
2936 Thread* thread_;
2937 JDWP::JdwpError error_;
2938 bool self_suspend_;
2939 bool other_suspend_;
2940};
2941
2942JDWP::JdwpError Dbg::ConfigureStep(JDWP::ObjectId thread_id, JDWP::JdwpStepSize step_size,
2943 JDWP::JdwpStepDepth step_depth) {
2944 Thread* self = Thread::Current();
2945 ScopedThreadSuspension sts(self, thread_id);
2946 if (sts.GetError() != JDWP::ERR_NONE) {
2947 return sts.GetError();
2948 }
2949
Elliott Hughes2435a572012-02-17 16:07:41 -08002950 //
2951 // Work out what Method* we're in, the current line number, and how deep the stack currently
2952 // is for step-out.
2953 //
2954
Ian Rogers0399dde2012-06-06 17:09:28 -07002955 struct SingleStepStackVisitor : public StackVisitor {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002956 explicit SingleStepStackVisitor(Thread* thread, SingleStepControl* single_step_control,
2957 int32_t* line_number)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002958 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002959 : StackVisitor(thread, NULL), single_step_control_(single_step_control),
2960 line_number_(line_number) {
2961 DCHECK_EQ(single_step_control_, thread->GetSingleStepControl());
2962 single_step_control_->method = NULL;
2963 single_step_control_->stack_depth = 0;
Elliott Hughes86964332012-02-15 19:37:42 -08002964 }
Ian Rogersca190662012-06-26 15:45:57 -07002965
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002966 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2967 // annotalysis.
2968 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002969 mirror::ArtMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07002970 if (!m->IsRuntimeMethod()) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002971 ++single_step_control_->stack_depth;
2972 if (single_step_control_->method == NULL) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002973 mirror::DexCache* dex_cache = m->GetDeclaringClass()->GetDexCache();
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002974 single_step_control_->method = m;
2975 *line_number_ = -1;
Elliott Hughes2435a572012-02-17 16:07:41 -08002976 if (dex_cache != NULL) {
Ian Rogers4445a7e2012-10-05 17:19:13 -07002977 const DexFile& dex_file = *dex_cache->GetDexFile();
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002978 *line_number_ = dex_file.GetLineNumFromPC(m, GetDexPc());
Elliott Hughes2435a572012-02-17 16:07:41 -08002979 }
Elliott Hughes86964332012-02-15 19:37:42 -08002980 }
2981 }
Elliott Hughes530fa002012-03-12 11:44:49 -07002982 return true;
Elliott Hughes86964332012-02-15 19:37:42 -08002983 }
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002984
2985 SingleStepControl* const single_step_control_;
2986 int32_t* const line_number_;
Elliott Hughes86964332012-02-15 19:37:42 -08002987 };
Jeff Hao449db332013-04-12 18:30:52 -07002988
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002989 Thread* const thread = sts.GetThread();
2990 SingleStepControl* const single_step_control = thread->GetSingleStepControl();
2991 DCHECK(single_step_control != nullptr);
2992 int32_t line_number = -1;
2993 SingleStepStackVisitor visitor(thread, single_step_control, &line_number);
Ian Rogers0399dde2012-06-06 17:09:28 -07002994 visitor.WalkStack();
Elliott Hughes86964332012-02-15 19:37:42 -08002995
Elliott Hughes2435a572012-02-17 16:07:41 -08002996 //
2997 // Find the dex_pc values that correspond to the current line, for line-based single-stepping.
2998 //
2999
3000 struct DebugCallbackContext {
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003001 explicit DebugCallbackContext(SingleStepControl* single_step_control, int32_t line_number,
3002 const DexFile::CodeItem* code_item)
3003 : single_step_control_(single_step_control), line_number_(line_number), code_item_(code_item),
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003004 last_pc_valid(false), last_pc(0) {
Elliott Hughes2435a572012-02-17 16:07:41 -08003005 }
3006
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003007 static bool Callback(void* raw_context, uint32_t address, uint32_t line_number) {
Elliott Hughes2435a572012-02-17 16:07:41 -08003008 DebugCallbackContext* context = reinterpret_cast<DebugCallbackContext*>(raw_context);
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003009 if (static_cast<int32_t>(line_number) == context->line_number_) {
Elliott Hughes2435a572012-02-17 16:07:41 -08003010 if (!context->last_pc_valid) {
3011 // Everything from this address until the next line change is ours.
3012 context->last_pc = address;
3013 context->last_pc_valid = true;
3014 }
3015 // Otherwise, if we're already in a valid range for this line,
3016 // just keep going (shouldn't really happen)...
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003017 } else if (context->last_pc_valid) { // and the line number is new
Elliott Hughes2435a572012-02-17 16:07:41 -08003018 // Add everything from the last entry up until here to the set
3019 for (uint32_t dex_pc = context->last_pc; dex_pc < address; ++dex_pc) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003020 context->single_step_control_->dex_pcs.insert(dex_pc);
Elliott Hughes2435a572012-02-17 16:07:41 -08003021 }
3022 context->last_pc_valid = false;
3023 }
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003024 return false; // There may be multiple entries for any given line.
Elliott Hughes2435a572012-02-17 16:07:41 -08003025 }
3026
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003027 ~DebugCallbackContext() {
Elliott Hughes2435a572012-02-17 16:07:41 -08003028 // If the line number was the last in the position table...
3029 if (last_pc_valid) {
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003030 size_t end = code_item_->insns_size_in_code_units_;
Elliott Hughes2435a572012-02-17 16:07:41 -08003031 for (uint32_t dex_pc = last_pc; dex_pc < end; ++dex_pc) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003032 single_step_control_->dex_pcs.insert(dex_pc);
Elliott Hughes2435a572012-02-17 16:07:41 -08003033 }
3034 }
3035 }
3036
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003037 SingleStepControl* const single_step_control_;
3038 const int32_t line_number_;
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003039 const DexFile::CodeItem* const code_item_;
Elliott Hughes2435a572012-02-17 16:07:41 -08003040 bool last_pc_valid;
3041 uint32_t last_pc;
3042 };
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003043 single_step_control->dex_pcs.clear();
Ian Rogersef7d42f2014-01-06 12:55:46 -08003044 mirror::ArtMethod* m = single_step_control->method;
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003045 if (!m->IsNative()) {
Elliott Hughes3e2e1a22012-02-21 11:33:41 -08003046 MethodHelper mh(m);
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003047 const DexFile::CodeItem* const code_item = mh.GetCodeItem();
3048 DebugCallbackContext context(single_step_control, line_number, code_item);
3049 mh.GetDexFile().DecodeDebugInfo(code_item, m->IsStatic(), m->GetDexMethodIndex(),
Elliott Hughes3e2e1a22012-02-21 11:33:41 -08003050 DebugCallbackContext::Callback, NULL, &context);
3051 }
Elliott Hughes2435a572012-02-17 16:07:41 -08003052
3053 //
3054 // Everything else...
3055 //
3056
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003057 single_step_control->step_size = step_size;
3058 single_step_control->step_depth = step_depth;
3059 single_step_control->is_active = true;
Elliott Hughes86964332012-02-15 19:37:42 -08003060
Elliott Hughes2435a572012-02-17 16:07:41 -08003061 if (VLOG_IS_ON(jdwp)) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003062 VLOG(jdwp) << "Single-step thread: " << *thread;
3063 VLOG(jdwp) << "Single-step step size: " << single_step_control->step_size;
3064 VLOG(jdwp) << "Single-step step depth: " << single_step_control->step_depth;
3065 VLOG(jdwp) << "Single-step current method: " << PrettyMethod(single_step_control->method);
3066 VLOG(jdwp) << "Single-step current line: " << line_number;
3067 VLOG(jdwp) << "Single-step current stack depth: " << single_step_control->stack_depth;
Elliott Hughes2435a572012-02-17 16:07:41 -08003068 VLOG(jdwp) << "Single-step dex_pc values:";
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003069 for (uint32_t dex_pc : single_step_control->dex_pcs) {
3070 VLOG(jdwp) << StringPrintf(" %#x", dex_pc);
Elliott Hughes2435a572012-02-17 16:07:41 -08003071 }
3072 }
3073
3074 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003075}
3076
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003077void Dbg::UnconfigureStep(JDWP::ObjectId thread_id) {
3078 ScopedObjectAccessUnchecked soa(Thread::Current());
3079 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
3080 Thread* thread;
3081 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
Sebastien Hertz87118ed2013-11-26 17:57:18 +01003082 if (error == JDWP::ERR_NONE) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003083 SingleStepControl* single_step_control = thread->GetSingleStepControl();
3084 DCHECK(single_step_control != nullptr);
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003085 single_step_control->Clear();
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003086 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003087}
3088
Elliott Hughes45651fd2012-02-21 15:48:20 -08003089static char JdwpTagToShortyChar(JDWP::JdwpTag tag) {
3090 switch (tag) {
3091 default:
3092 LOG(FATAL) << "unknown JDWP tag: " << PrintableChar(tag);
3093
3094 // Primitives.
3095 case JDWP::JT_BYTE: return 'B';
3096 case JDWP::JT_CHAR: return 'C';
3097 case JDWP::JT_FLOAT: return 'F';
3098 case JDWP::JT_DOUBLE: return 'D';
3099 case JDWP::JT_INT: return 'I';
3100 case JDWP::JT_LONG: return 'J';
3101 case JDWP::JT_SHORT: return 'S';
3102 case JDWP::JT_VOID: return 'V';
3103 case JDWP::JT_BOOLEAN: return 'Z';
3104
3105 // Reference types.
3106 case JDWP::JT_ARRAY:
3107 case JDWP::JT_OBJECT:
3108 case JDWP::JT_STRING:
3109 case JDWP::JT_THREAD:
3110 case JDWP::JT_THREAD_GROUP:
3111 case JDWP::JT_CLASS_LOADER:
3112 case JDWP::JT_CLASS_OBJECT:
3113 return 'L';
3114 }
3115}
3116
Elliott Hughes88d63092013-01-09 09:55:54 -08003117JDWP::JdwpError Dbg::InvokeMethod(JDWP::ObjectId thread_id, JDWP::ObjectId object_id,
3118 JDWP::RefTypeId class_id, JDWP::MethodId method_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003119 uint32_t arg_count, uint64_t* arg_values,
3120 JDWP::JdwpTag* arg_types, uint32_t options,
3121 JDWP::JdwpTag* pResultTag, uint64_t* pResultValue,
3122 JDWP::ObjectId* pExceptionId) {
Elliott Hughesd07986f2011-12-06 18:27:45 -08003123 ThreadList* thread_list = Runtime::Current()->GetThreadList();
3124
3125 Thread* targetThread = NULL;
3126 DebugInvokeReq* req = NULL;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003127 Thread* self = Thread::Current();
Elliott Hughesd07986f2011-12-06 18:27:45 -08003128 {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003129 ScopedObjectAccessUnchecked soa(self);
Ian Rogers50b35e22012-10-04 10:09:15 -07003130 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08003131 JDWP::JdwpError error = DecodeThread(soa, thread_id, targetThread);
3132 if (error != JDWP::ERR_NONE) {
3133 LOG(ERROR) << "InvokeMethod request for invalid thread id " << thread_id;
3134 return error;
Elliott Hughesd07986f2011-12-06 18:27:45 -08003135 }
3136 req = targetThread->GetInvokeReq();
3137 if (!req->ready) {
3138 LOG(ERROR) << "InvokeMethod request for thread not stopped by event: " << *targetThread;
3139 return JDWP::ERR_INVALID_THREAD;
3140 }
3141
3142 /*
3143 * We currently have a bug where we don't successfully resume the
3144 * target thread if the suspend count is too deep. We're expected to
3145 * require one "resume" for each "suspend", but when asked to execute
3146 * a method we have to resume fully and then re-suspend it back to the
3147 * same level. (The easiest way to cause this is to type "suspend"
3148 * multiple times in jdb.)
3149 *
3150 * It's unclear what this means when the event specifies "resume all"
3151 * and some threads are suspended more deeply than others. This is
3152 * a rare problem, so for now we just prevent it from hanging forever
3153 * by rejecting the method invocation request. Without this, we will
3154 * be stuck waiting on a suspended thread.
3155 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003156 int suspend_count;
3157 {
Ian Rogers50b35e22012-10-04 10:09:15 -07003158 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003159 suspend_count = targetThread->GetSuspendCount();
3160 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08003161 if (suspend_count > 1) {
3162 LOG(ERROR) << *targetThread << " suspend count too deep for method invocation: " << suspend_count;
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003163 return JDWP::ERR_THREAD_SUSPENDED; // Probably not expected here.
Elliott Hughesd07986f2011-12-06 18:27:45 -08003164 }
3165
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08003166 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003167 mirror::Object* receiver = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08003168 if (receiver == ObjectRegistry::kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08003169 return JDWP::ERR_INVALID_OBJECT;
3170 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003171
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003172 mirror::Object* thread = gRegistry->Get<mirror::Object*>(thread_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08003173 if (thread == ObjectRegistry::kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08003174 return JDWP::ERR_INVALID_OBJECT;
3175 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003176 // TODO: check that 'thread' is actually a java.lang.Thread!
3177
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003178 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes45651fd2012-02-21 15:48:20 -08003179 if (c == NULL) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08003180 return status;
3181 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003182
Brian Carlstromea46f952013-07-30 01:26:50 -07003183 mirror::ArtMethod* m = FromMethodId(method_id);
Elliott Hughes45651fd2012-02-21 15:48:20 -08003184 if (m->IsStatic() != (receiver == NULL)) {
3185 return JDWP::ERR_INVALID_METHODID;
3186 }
3187 if (m->IsStatic()) {
3188 if (m->GetDeclaringClass() != c) {
3189 return JDWP::ERR_INVALID_METHODID;
3190 }
3191 } else {
3192 if (!m->GetDeclaringClass()->IsAssignableFrom(c)) {
3193 return JDWP::ERR_INVALID_METHODID;
3194 }
3195 }
3196
3197 // Check the argument list matches the method.
3198 MethodHelper mh(m);
3199 if (mh.GetShortyLength() - 1 != arg_count) {
3200 return JDWP::ERR_ILLEGAL_ARGUMENT;
3201 }
3202 const char* shorty = mh.GetShorty();
Elliott Hughes09201632013-04-15 15:50:07 -07003203 const DexFile::TypeList* types = mh.GetParameterTypeList();
Elliott Hughes45651fd2012-02-21 15:48:20 -08003204 for (size_t i = 0; i < arg_count; ++i) {
3205 if (shorty[i + 1] != JdwpTagToShortyChar(arg_types[i])) {
3206 return JDWP::ERR_ILLEGAL_ARGUMENT;
3207 }
Elliott Hughes09201632013-04-15 15:50:07 -07003208
3209 if (shorty[i + 1] == 'L') {
3210 // Did we really get an argument of an appropriate reference type?
3211 mirror::Class* parameter_type = mh.GetClassFromTypeIdx(types->GetTypeItem(i).type_idx_);
3212 mirror::Object* argument = gRegistry->Get<mirror::Object*>(arg_values[i]);
3213 if (argument == ObjectRegistry::kInvalidObject) {
3214 return JDWP::ERR_INVALID_OBJECT;
3215 }
Sebastien Hertz0630ab52013-11-28 18:53:35 +01003216 if (argument != NULL && !argument->InstanceOf(parameter_type)) {
Elliott Hughes09201632013-04-15 15:50:07 -07003217 return JDWP::ERR_ILLEGAL_ARGUMENT;
3218 }
3219
3220 // Turn the on-the-wire ObjectId into a jobject.
3221 jvalue& v = reinterpret_cast<jvalue&>(arg_values[i]);
3222 v.l = gRegistry->GetJObject(arg_values[i]);
3223 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003224 }
3225
Sebastien Hertzd38667a2013-11-25 15:43:54 +01003226 req->receiver = receiver;
3227 req->thread = thread;
3228 req->klass = c;
3229 req->method = m;
3230 req->arg_count = arg_count;
3231 req->arg_values = arg_values;
3232 req->options = options;
3233 req->invoke_needed = true;
Elliott Hughesd07986f2011-12-06 18:27:45 -08003234 }
3235
3236 // The fact that we've released the thread list lock is a bit risky --- if the thread goes
3237 // away we're sitting high and dry -- but we must release this before the ResumeAllThreads
3238 // call, and it's unwise to hold it during WaitForSuspend.
3239
3240 {
3241 /*
3242 * We change our (JDWP thread) status, which should be THREAD_RUNNING,
Elliott Hughes81ff3182012-03-23 20:35:56 -07003243 * so we can suspend for a GC if the invoke request causes us to
Elliott Hughesd07986f2011-12-06 18:27:45 -08003244 * run out of memory. It's also a good idea to change it before locking
3245 * the invokeReq mutex, although that should never be held for long.
3246 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003247 self->TransitionFromRunnableToSuspended(kWaitingForDebuggerSend);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003248
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003249 VLOG(jdwp) << " Transferring control to event thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08003250 {
Sebastien Hertzd38667a2013-11-25 15:43:54 +01003251 MutexLock mu(self, req->lock);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003252
3253 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003254 VLOG(jdwp) << " Resuming all threads";
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003255 thread_list->UndoDebuggerSuspensions();
Elliott Hughesd07986f2011-12-06 18:27:45 -08003256 } else {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003257 VLOG(jdwp) << " Resuming event thread only";
Elliott Hughesd07986f2011-12-06 18:27:45 -08003258 thread_list->Resume(targetThread, true);
3259 }
3260
3261 // Wait for the request to finish executing.
Sebastien Hertzd38667a2013-11-25 15:43:54 +01003262 while (req->invoke_needed) {
3263 req->cond.Wait(self);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003264 }
3265 }
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003266 VLOG(jdwp) << " Control has returned from event thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08003267
3268 /* wait for thread to re-suspend itself */
Brian Carlstromdf629502013-07-17 22:39:56 -07003269 SuspendThread(thread_id, false /* request_suspension */);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003270 self->TransitionFromSuspendedToRunnable();
Elliott Hughesd07986f2011-12-06 18:27:45 -08003271 }
3272
3273 /*
3274 * Suspend the threads. We waited for the target thread to suspend
3275 * itself, so all we need to do is suspend the others.
3276 *
3277 * The suspendAllThreads() call will double-suspend the event thread,
3278 * so we want to resume the target thread once to keep the books straight.
3279 */
3280 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003281 self->TransitionFromRunnableToSuspended(kWaitingForDebuggerSuspension);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003282 VLOG(jdwp) << " Suspending all threads";
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003283 thread_list->SuspendAllForDebugger();
3284 self->TransitionFromSuspendedToRunnable();
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003285 VLOG(jdwp) << " Resuming event thread to balance the count";
Elliott Hughesd07986f2011-12-06 18:27:45 -08003286 thread_list->Resume(targetThread, true);
3287 }
3288
3289 // Copy the result.
3290 *pResultTag = req->result_tag;
3291 if (IsPrimitiveTag(req->result_tag)) {
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07003292 *pResultValue = req->result_value.GetJ();
Elliott Hughesd07986f2011-12-06 18:27:45 -08003293 } else {
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07003294 *pResultValue = gRegistry->Add(req->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003295 }
3296 *pExceptionId = req->exception;
3297 return req->error;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003298}
3299
3300void Dbg::ExecuteMethod(DebugInvokeReq* pReq) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003301 ScopedObjectAccess soa(Thread::Current());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003302
Elliott Hughes81ff3182012-03-23 20:35:56 -07003303 // We can be called while an exception is pending. We need
Elliott Hughesd07986f2011-12-06 18:27:45 -08003304 // to preserve that across the method invocation.
Ian Rogers62d6c772013-02-27 08:32:07 -08003305 SirtRef<mirror::Object> old_throw_this_object(soa.Self(), NULL);
Brian Carlstromea46f952013-07-30 01:26:50 -07003306 SirtRef<mirror::ArtMethod> old_throw_method(soa.Self(), NULL);
Ian Rogers62d6c772013-02-27 08:32:07 -08003307 SirtRef<mirror::Throwable> old_exception(soa.Self(), NULL);
3308 uint32_t old_throw_dex_pc;
3309 {
3310 ThrowLocation old_throw_location;
3311 mirror::Throwable* old_exception_obj = soa.Self()->GetException(&old_throw_location);
3312 old_throw_this_object.reset(old_throw_location.GetThis());
3313 old_throw_method.reset(old_throw_location.GetMethod());
3314 old_exception.reset(old_exception_obj);
3315 old_throw_dex_pc = old_throw_location.GetDexPc();
3316 soa.Self()->ClearException();
3317 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08003318
3319 // Translate the method through the vtable, unless the debugger wants to suppress it.
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003320 SirtRef<mirror::ArtMethod> m(soa.Self(), pReq->method);
Sebastien Hertzd38667a2013-11-25 15:43:54 +01003321 if ((pReq->options & JDWP::INVOKE_NONVIRTUAL) == 0 && pReq->receiver != NULL) {
Sebastien Hertz83a47d82014-03-20 09:57:40 +01003322 mirror::ArtMethod* actual_method = pReq->klass->FindVirtualMethodForVirtualOrInterface(m.get());
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003323 if (actual_method != m.get()) {
3324 VLOG(jdwp) << "ExecuteMethod translated " << PrettyMethod(m.get()) << " to " << PrettyMethod(actual_method);
3325 m.reset(actual_method);
Elliott Hughes45651fd2012-02-21 15:48:20 -08003326 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08003327 }
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003328 VLOG(jdwp) << "ExecuteMethod " << PrettyMethod(m.get())
Sebastien Hertzd38667a2013-11-25 15:43:54 +01003329 << " receiver=" << pReq->receiver
3330 << " arg_count=" << pReq->arg_count;
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003331 CHECK(m.get() != nullptr);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003332
3333 CHECK_EQ(sizeof(jvalue), sizeof(uint64_t));
3334
Sebastien Hertz83a47d82014-03-20 09:57:40 +01003335 pReq->result_value = InvokeWithJValues(soa, pReq->receiver, soa.EncodeMethod(m.get()),
Ian Rogers53b8b092014-03-13 23:45:53 -07003336 reinterpret_cast<jvalue*>(pReq->arg_values));
Elliott Hughesd07986f2011-12-06 18:27:45 -08003337
Ian Rogers62d6c772013-02-27 08:32:07 -08003338 mirror::Throwable* exception = soa.Self()->GetException(NULL);
3339 soa.Self()->ClearException();
3340 pReq->exception = gRegistry->Add(exception);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003341 pReq->result_tag = BasicTagFromDescriptor(MethodHelper(m.get()).GetShorty());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003342 if (pReq->exception != 0) {
Ian Rogers62d6c772013-02-27 08:32:07 -08003343 VLOG(jdwp) << " JDWP invocation returning with exception=" << exception
3344 << " " << exception->Dump();
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07003345 pReq->result_value.SetJ(0);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003346 } else if (pReq->result_tag == JDWP::JT_OBJECT) {
3347 /* if no exception thrown, examine object result more closely */
Ian Rogers98379392014-02-24 16:53:16 -08003348 JDWP::JdwpTag new_tag = TagFromObject(soa, pReq->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003349 if (new_tag != pReq->result_tag) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003350 VLOG(jdwp) << " JDWP promoted result from " << pReq->result_tag << " to " << new_tag;
Elliott Hughesd07986f2011-12-06 18:27:45 -08003351 pReq->result_tag = new_tag;
3352 }
3353
3354 /*
3355 * Register the object. We don't actually need an ObjectId yet,
3356 * but we do need to be sure that the GC won't move or discard the
3357 * object when we switch out of RUNNING. The ObjectId conversion
3358 * will add the object to the "do not touch" list.
3359 *
3360 * We can't use the "tracked allocation" mechanism here because
3361 * the object is going to be handed off to a different thread.
3362 */
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07003363 gRegistry->Add(pReq->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003364 }
3365
3366 if (old_exception.get() != NULL) {
Ian Rogers62d6c772013-02-27 08:32:07 -08003367 ThrowLocation gc_safe_throw_location(old_throw_this_object.get(), old_throw_method.get(),
3368 old_throw_dex_pc);
3369 soa.Self()->SetException(gc_safe_throw_location, old_exception.get());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003370 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003371}
3372
Elliott Hughesd07986f2011-12-06 18:27:45 -08003373/*
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003374 * "request" contains a full JDWP packet, possibly with multiple chunks. We
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003375 * need to process each, accumulate the replies, and ship the whole thing
3376 * back.
3377 *
3378 * Returns "true" if we have a reply. The reply buffer is newly allocated,
3379 * and includes the chunk type/length, followed by the data.
3380 *
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08003381 * OLD-TODO: we currently assume that the request and reply include a single
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003382 * chunk. If this becomes inconvenient we will need to adapt.
3383 */
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003384bool Dbg::DdmHandlePacket(JDWP::Request& request, uint8_t** pReplyBuf, int* pReplyLen) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003385 Thread* self = Thread::Current();
3386 JNIEnv* env = self->GetJniEnv();
3387
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003388 uint32_t type = request.ReadUnsigned32("type");
3389 uint32_t length = request.ReadUnsigned32("length");
3390
3391 // Create a byte[] corresponding to 'request'.
3392 size_t request_length = request.size();
3393 ScopedLocalRef<jbyteArray> dataArray(env, env->NewByteArray(request_length));
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003394 if (dataArray.get() == NULL) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003395 LOG(WARNING) << "byte[] allocation failed: " << request_length;
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003396 env->ExceptionClear();
3397 return false;
3398 }
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003399 env->SetByteArrayRegion(dataArray.get(), 0, request_length, reinterpret_cast<const jbyte*>(request.data()));
3400 request.Skip(request_length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003401
3402 // Run through and find all chunks. [Currently just find the first.]
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003403 ScopedByteArrayRO contents(env, dataArray.get());
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003404 if (length != request_length) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08003405 LOG(WARNING) << StringPrintf("bad chunk found (len=%u pktLen=%zd)", length, request_length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003406 return false;
3407 }
3408
3409 // Call "private static Chunk dispatch(int type, byte[] data, int offset, int length)".
Elliott Hugheseac76672012-05-24 21:56:51 -07003410 ScopedLocalRef<jobject> chunk(env, env->CallStaticObjectMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
3411 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_dispatch,
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003412 type, dataArray.get(), 0, length));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003413 if (env->ExceptionCheck()) {
3414 LOG(INFO) << StringPrintf("Exception thrown by dispatcher for 0x%08x", type);
3415 env->ExceptionDescribe();
3416 env->ExceptionClear();
3417 return false;
3418 }
3419
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003420 if (chunk.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003421 return false;
3422 }
3423
3424 /*
3425 * Pull the pieces out of the chunk. We copy the results into a
3426 * newly-allocated buffer that the caller can free. We don't want to
3427 * continue using the Chunk object because nothing has a reference to it.
3428 *
3429 * We could avoid this by returning type/data/offset/length and having
3430 * the caller be aware of the object lifetime issues, but that
Elliott Hughes81ff3182012-03-23 20:35:56 -07003431 * integrates the JDWP code more tightly into the rest of the runtime, and doesn't work
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003432 * if we have responses for multiple chunks.
3433 *
3434 * So we're pretty much stuck with copying data around multiple times.
3435 */
Elliott Hugheseac76672012-05-24 21:56:51 -07003436 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 -08003437 jint offset = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_offset);
Elliott Hugheseac76672012-05-24 21:56:51 -07003438 length = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_length);
Elliott Hugheseac76672012-05-24 21:56:51 -07003439 type = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_type);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003440
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003441 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 -07003442 if (length == 0 || replyData.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003443 return false;
3444 }
3445
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003446 const int kChunkHdrLen = 8;
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003447 uint8_t* reply = new uint8_t[length + kChunkHdrLen];
3448 if (reply == NULL) {
3449 LOG(WARNING) << "malloc failed: " << (length + kChunkHdrLen);
3450 return false;
3451 }
Elliott Hughesf7c3b662011-10-27 12:04:56 -07003452 JDWP::Set4BE(reply + 0, type);
3453 JDWP::Set4BE(reply + 4, length);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003454 env->GetByteArrayRegion(replyData.get(), offset, length, reinterpret_cast<jbyte*>(reply + kChunkHdrLen));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003455
3456 *pReplyBuf = reply;
3457 *pReplyLen = length + kChunkHdrLen;
3458
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003459 VLOG(jdwp) << StringPrintf("dvmHandleDdm returning type=%.4s %p len=%d", reinterpret_cast<char*>(reply), reply, length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003460 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003461}
3462
Elliott Hughesa2155262011-11-16 16:26:58 -08003463void Dbg::DdmBroadcast(bool connect) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003464 VLOG(jdwp) << "Broadcasting DDM " << (connect ? "connect" : "disconnect") << "...";
Elliott Hughes47fce012011-10-25 18:37:19 -07003465
3466 Thread* self = Thread::Current();
Ian Rogers50b35e22012-10-04 10:09:15 -07003467 if (self->GetState() != kRunnable) {
3468 LOG(ERROR) << "DDM broadcast in thread state " << self->GetState();
3469 /* try anyway? */
Elliott Hughes47fce012011-10-25 18:37:19 -07003470 }
3471
3472 JNIEnv* env = self->GetJniEnv();
Elliott Hughes47fce012011-10-25 18:37:19 -07003473 jint event = connect ? 1 /*DdmServer.CONNECTED*/ : 2 /*DdmServer.DISCONNECTED*/;
Elliott Hugheseac76672012-05-24 21:56:51 -07003474 env->CallStaticVoidMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
3475 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_broadcast,
3476 event);
Elliott Hughes47fce012011-10-25 18:37:19 -07003477 if (env->ExceptionCheck()) {
3478 LOG(ERROR) << "DdmServer.broadcast " << event << " failed";
3479 env->ExceptionDescribe();
3480 env->ExceptionClear();
3481 }
3482}
3483
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003484void Dbg::DdmConnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08003485 Dbg::DdmBroadcast(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003486}
3487
3488void Dbg::DdmDisconnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08003489 Dbg::DdmBroadcast(false);
Elliott Hughes47fce012011-10-25 18:37:19 -07003490 gDdmThreadNotification = false;
3491}
3492
3493/*
Elliott Hughes82188472011-11-07 18:11:48 -08003494 * Send a notification when a thread starts, stops, or changes its name.
Elliott Hughes47fce012011-10-25 18:37:19 -07003495 *
3496 * Because we broadcast the full set of threads when the notifications are
3497 * first enabled, it's possible for "thread" to be actively executing.
3498 */
Elliott Hughes82188472011-11-07 18:11:48 -08003499void Dbg::DdmSendThreadNotification(Thread* t, uint32_t type) {
Elliott Hughes47fce012011-10-25 18:37:19 -07003500 if (!gDdmThreadNotification) {
3501 return;
3502 }
3503
Elliott Hughes82188472011-11-07 18:11:48 -08003504 if (type == CHUNK_TYPE("THDE")) {
Elliott Hughes47fce012011-10-25 18:37:19 -07003505 uint8_t buf[4];
Ian Rogersd9c4fc92013-10-01 19:45:43 -07003506 JDWP::Set4BE(&buf[0], t->GetThreadId());
Elliott Hughes47fce012011-10-25 18:37:19 -07003507 Dbg::DdmSendChunk(CHUNK_TYPE("THDE"), 4, buf);
Elliott Hughes82188472011-11-07 18:11:48 -08003508 } else {
3509 CHECK(type == CHUNK_TYPE("THCR") || type == CHUNK_TYPE("THNM")) << type;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003510 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003511 SirtRef<mirror::String> name(soa.Self(), t->GetThreadName(soa));
Elliott Hughes82188472011-11-07 18:11:48 -08003512 size_t char_count = (name.get() != NULL) ? name->GetLength() : 0;
jeffhao725a9572012-11-13 18:20:12 -08003513 const jchar* chars = (name.get() != NULL) ? name->GetCharArray()->GetData() : NULL;
Elliott Hughes82188472011-11-07 18:11:48 -08003514
Elliott Hughes21f32d72011-11-09 17:44:13 -08003515 std::vector<uint8_t> bytes;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07003516 JDWP::Append4BE(bytes, t->GetThreadId());
Elliott Hughes545a0642011-11-08 19:10:03 -08003517 JDWP::AppendUtf16BE(bytes, chars, char_count);
Elliott Hughes21f32d72011-11-09 17:44:13 -08003518 CHECK_EQ(bytes.size(), char_count*2 + sizeof(uint32_t)*2);
3519 Dbg::DdmSendChunk(type, bytes);
Elliott Hughes47fce012011-10-25 18:37:19 -07003520 }
3521}
3522
Elliott Hughes47fce012011-10-25 18:37:19 -07003523void Dbg::DdmSetThreadNotification(bool enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003524 // Enable/disable thread notifications.
Elliott Hughes47fce012011-10-25 18:37:19 -07003525 gDdmThreadNotification = enable;
3526 if (enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003527 // Suspend the VM then post thread start notifications for all threads. Threads attaching will
3528 // see a suspension in progress and block until that ends. They then post their own start
3529 // notification.
3530 SuspendVM();
3531 std::list<Thread*> threads;
Ian Rogers50b35e22012-10-04 10:09:15 -07003532 Thread* self = Thread::Current();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003533 {
Ian Rogers50b35e22012-10-04 10:09:15 -07003534 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003535 threads = Runtime::Current()->GetThreadList()->GetList();
3536 }
3537 {
Ian Rogers50b35e22012-10-04 10:09:15 -07003538 ScopedObjectAccess soa(self);
Mathieu Chartier02e25112013-08-14 16:14:24 -07003539 for (Thread* thread : threads) {
3540 Dbg::DdmSendThreadNotification(thread, CHUNK_TYPE("THCR"));
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003541 }
3542 }
3543 ResumeVM();
Elliott Hughes47fce012011-10-25 18:37:19 -07003544 }
3545}
3546
Elliott Hughesa2155262011-11-16 16:26:58 -08003547void Dbg::PostThreadStartOrStop(Thread* t, uint32_t type) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07003548 if (IsDebuggerActive()) {
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07003549 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogerscfaa4552012-11-26 21:00:08 -08003550 JDWP::ObjectId id = gRegistry->Add(t->GetPeer());
Elliott Hughes82188472011-11-07 18:11:48 -08003551 gJdwpState->PostThreadChange(id, type == CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07003552 }
Elliott Hughes82188472011-11-07 18:11:48 -08003553 Dbg::DdmSendThreadNotification(t, type);
Elliott Hughes47fce012011-10-25 18:37:19 -07003554}
3555
3556void Dbg::PostThreadStart(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08003557 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07003558}
3559
3560void Dbg::PostThreadDeath(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08003561 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THDE"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003562}
3563
Elliott Hughes82188472011-11-07 18:11:48 -08003564void Dbg::DdmSendChunk(uint32_t type, size_t byte_count, const uint8_t* buf) {
Elliott Hughes3bb81562011-10-21 18:52:59 -07003565 CHECK(buf != NULL);
3566 iovec vec[1];
3567 vec[0].iov_base = reinterpret_cast<void*>(const_cast<uint8_t*>(buf));
3568 vec[0].iov_len = byte_count;
3569 Dbg::DdmSendChunkV(type, vec, 1);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003570}
3571
Elliott Hughes21f32d72011-11-09 17:44:13 -08003572void Dbg::DdmSendChunk(uint32_t type, const std::vector<uint8_t>& bytes) {
3573 DdmSendChunk(type, bytes.size(), &bytes[0]);
3574}
3575
Brian Carlstromf5293522013-07-19 00:24:00 -07003576void Dbg::DdmSendChunkV(uint32_t type, const iovec* iov, int iov_count) {
Elliott Hughes3bb81562011-10-21 18:52:59 -07003577 if (gJdwpState == NULL) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003578 VLOG(jdwp) << "Debugger thread not active, ignoring DDM send: " << type;
Elliott Hughes3bb81562011-10-21 18:52:59 -07003579 } else {
Elliott Hughescccd84f2011-12-05 16:51:54 -08003580 gJdwpState->DdmSendChunkV(type, iov, iov_count);
Elliott Hughes3bb81562011-10-21 18:52:59 -07003581 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003582}
3583
Elliott Hughes767a1472011-10-26 18:49:02 -07003584int Dbg::DdmHandleHpifChunk(HpifWhen when) {
3585 if (when == HPIF_WHEN_NOW) {
Elliott Hughes7162ad92011-10-27 14:08:42 -07003586 DdmSendHeapInfo(when);
Elliott Hughes767a1472011-10-26 18:49:02 -07003587 return true;
3588 }
3589
3590 if (when != HPIF_WHEN_NEVER && when != HPIF_WHEN_NEXT_GC && when != HPIF_WHEN_EVERY_GC) {
3591 LOG(ERROR) << "invalid HpifWhen value: " << static_cast<int>(when);
3592 return false;
3593 }
3594
3595 gDdmHpifWhen = when;
3596 return true;
3597}
3598
3599bool Dbg::DdmHandleHpsgNhsgChunk(Dbg::HpsgWhen when, Dbg::HpsgWhat what, bool native) {
3600 if (when != HPSG_WHEN_NEVER && when != HPSG_WHEN_EVERY_GC) {
3601 LOG(ERROR) << "invalid HpsgWhen value: " << static_cast<int>(when);
3602 return false;
3603 }
3604
3605 if (what != HPSG_WHAT_MERGED_OBJECTS && what != HPSG_WHAT_DISTINCT_OBJECTS) {
3606 LOG(ERROR) << "invalid HpsgWhat value: " << static_cast<int>(what);
3607 return false;
3608 }
3609
3610 if (native) {
3611 gDdmNhsgWhen = when;
3612 gDdmNhsgWhat = what;
3613 } else {
3614 gDdmHpsgWhen = when;
3615 gDdmHpsgWhat = what;
3616 }
3617 return true;
3618}
3619
Elliott Hughes7162ad92011-10-27 14:08:42 -07003620void Dbg::DdmSendHeapInfo(HpifWhen reason) {
3621 // If there's a one-shot 'when', reset it.
3622 if (reason == gDdmHpifWhen) {
3623 if (gDdmHpifWhen == HPIF_WHEN_NEXT_GC) {
3624 gDdmHpifWhen = HPIF_WHEN_NEVER;
3625 }
3626 }
3627
3628 /*
3629 * Chunk HPIF (client --> server)
3630 *
3631 * Heap Info. General information about the heap,
3632 * suitable for a summary display.
3633 *
3634 * [u4]: number of heaps
3635 *
3636 * For each heap:
3637 * [u4]: heap ID
3638 * [u8]: timestamp in ms since Unix epoch
3639 * [u1]: capture reason (same as 'when' value from server)
3640 * [u4]: max heap size in bytes (-Xmx)
3641 * [u4]: current heap size in bytes
3642 * [u4]: current number of bytes allocated
3643 * [u4]: current number of objects allocated
3644 */
3645 uint8_t heap_count = 1;
Ian Rogers1d54e732013-05-02 21:10:01 -07003646 gc::Heap* heap = Runtime::Current()->GetHeap();
Elliott Hughes21f32d72011-11-09 17:44:13 -08003647 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08003648 JDWP::Append4BE(bytes, heap_count);
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003649 JDWP::Append4BE(bytes, 1); // Heap id (bogus; we only have one heap).
Elliott Hughes545a0642011-11-08 19:10:03 -08003650 JDWP::Append8BE(bytes, MilliTime());
3651 JDWP::Append1BE(bytes, reason);
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003652 JDWP::Append4BE(bytes, heap->GetMaxMemory()); // Max allowed heap size in bytes.
3653 JDWP::Append4BE(bytes, heap->GetTotalMemory()); // Current heap size in bytes.
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08003654 JDWP::Append4BE(bytes, heap->GetBytesAllocated());
3655 JDWP::Append4BE(bytes, heap->GetObjectsAllocated());
Elliott Hughes21f32d72011-11-09 17:44:13 -08003656 CHECK_EQ(bytes.size(), 4U + (heap_count * (4 + 8 + 1 + 4 + 4 + 4 + 4)));
3657 Dbg::DdmSendChunk(CHUNK_TYPE("HPIF"), bytes);
Elliott Hughes767a1472011-10-26 18:49:02 -07003658}
3659
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003660enum HpsgSolidity {
3661 SOLIDITY_FREE = 0,
3662 SOLIDITY_HARD = 1,
3663 SOLIDITY_SOFT = 2,
3664 SOLIDITY_WEAK = 3,
3665 SOLIDITY_PHANTOM = 4,
3666 SOLIDITY_FINALIZABLE = 5,
3667 SOLIDITY_SWEEP = 6,
3668};
3669
3670enum HpsgKind {
3671 KIND_OBJECT = 0,
3672 KIND_CLASS_OBJECT = 1,
3673 KIND_ARRAY_1 = 2,
3674 KIND_ARRAY_2 = 3,
3675 KIND_ARRAY_4 = 4,
3676 KIND_ARRAY_8 = 5,
3677 KIND_UNKNOWN = 6,
3678 KIND_NATIVE = 7,
3679};
3680
3681#define HPSG_PARTIAL (1<<7)
3682#define HPSG_STATE(solidity, kind) ((uint8_t)((((kind) & 0x7) << 3) | ((solidity) & 0x7)))
3683
Ian Rogers30fab402012-01-23 15:43:46 -08003684class HeapChunkContext {
3685 public:
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003686 // Maximum chunk size. Obtain this from the formula:
3687 // (((maximum_heap_size / ALLOCATION_UNIT_SIZE) + 255) / 256) * 2
3688 HeapChunkContext(bool merge, bool native)
Ian Rogers30fab402012-01-23 15:43:46 -08003689 : buf_(16384 - 16),
3690 type_(0),
3691 merge_(merge) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003692 Reset();
3693 if (native) {
Ian Rogers30fab402012-01-23 15:43:46 -08003694 type_ = CHUNK_TYPE("NHSG");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003695 } else {
Ian Rogers30fab402012-01-23 15:43:46 -08003696 type_ = merge ? CHUNK_TYPE("HPSG") : CHUNK_TYPE("HPSO");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003697 }
3698 }
3699
3700 ~HeapChunkContext() {
Ian Rogers30fab402012-01-23 15:43:46 -08003701 if (p_ > &buf_[0]) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003702 Flush();
3703 }
3704 }
3705
3706 void EnsureHeader(const void* chunk_ptr) {
Ian Rogers30fab402012-01-23 15:43:46 -08003707 if (!needHeader_) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003708 return;
3709 }
3710
3711 // Start a new HPSx chunk.
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003712 JDWP::Write4BE(&p_, 1); // Heap id (bogus; we only have one heap).
3713 JDWP::Write1BE(&p_, 8); // Size of allocation unit, in bytes.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003714
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003715 JDWP::Write4BE(&p_, reinterpret_cast<uintptr_t>(chunk_ptr)); // virtual address of segment start.
3716 JDWP::Write4BE(&p_, 0); // offset of this piece (relative to the virtual address).
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003717 // [u4]: length of piece, in allocation units
3718 // 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 -08003719 pieceLenField_ = p_;
3720 JDWP::Write4BE(&p_, 0x55555555);
3721 needHeader_ = false;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003722 }
3723
Ian Rogersb726dcb2012-09-05 08:57:23 -07003724 void Flush() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogersd636b062013-01-18 17:51:18 -08003725 if (pieceLenField_ == NULL) {
3726 // Flush immediately post Reset (maybe back-to-back Flush). Ignore.
3727 CHECK(needHeader_);
3728 return;
3729 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003730 // Patch the "length of piece" field.
Ian Rogers30fab402012-01-23 15:43:46 -08003731 CHECK_LE(&buf_[0], pieceLenField_);
3732 CHECK_LE(pieceLenField_, p_);
3733 JDWP::Set4BE(pieceLenField_, totalAllocationUnits_);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003734
Ian Rogers30fab402012-01-23 15:43:46 -08003735 Dbg::DdmSendChunk(type_, p_ - &buf_[0], &buf_[0]);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003736 Reset();
3737 }
3738
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003739 static void HeapChunkCallback(void* start, void* end, size_t used_bytes, void* arg)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003740 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_,
3741 Locks::mutator_lock_) {
Ian Rogers30fab402012-01-23 15:43:46 -08003742 reinterpret_cast<HeapChunkContext*>(arg)->HeapChunkCallback(start, end, used_bytes);
Elliott Hughesa2155262011-11-16 16:26:58 -08003743 }
3744
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003745 private:
Elliott Hughesa2155262011-11-16 16:26:58 -08003746 enum { ALLOCATION_UNIT_SIZE = 8 };
3747
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003748 void Reset() {
Ian Rogers30fab402012-01-23 15:43:46 -08003749 p_ = &buf_[0];
Ian Rogers15bf2d32012-08-28 17:33:04 -07003750 startOfNextMemoryChunk_ = NULL;
Ian Rogers30fab402012-01-23 15:43:46 -08003751 totalAllocationUnits_ = 0;
3752 needHeader_ = true;
3753 pieceLenField_ = NULL;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003754 }
3755
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003756 void HeapChunkCallback(void* start, void* /*end*/, size_t used_bytes)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003757 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_,
3758 Locks::mutator_lock_) {
Ian Rogers30fab402012-01-23 15:43:46 -08003759 // Note: heap call backs cannot manipulate the heap upon which they are crawling, care is taken
3760 // in the following code not to allocate memory, by ensuring buf_ is of the correct size
Ian Rogers15bf2d32012-08-28 17:33:04 -07003761 if (used_bytes == 0) {
3762 if (start == NULL) {
3763 // Reset for start of new heap.
3764 startOfNextMemoryChunk_ = NULL;
3765 Flush();
3766 }
3767 // Only process in use memory so that free region information
3768 // also includes dlmalloc book keeping.
Elliott Hughesa2155262011-11-16 16:26:58 -08003769 return;
Elliott Hughesa2155262011-11-16 16:26:58 -08003770 }
3771
Ian Rogers15bf2d32012-08-28 17:33:04 -07003772 /* If we're looking at the native heap, we'll just return
3773 * (SOLIDITY_HARD, KIND_NATIVE) for all allocated chunks
3774 */
3775 bool native = type_ == CHUNK_TYPE("NHSG");
3776
3777 if (startOfNextMemoryChunk_ != NULL) {
3778 // Transmit any pending free memory. Native free memory of
3779 // over kMaxFreeLen could be because of the use of mmaps, so
3780 // don't report. If not free memory then start a new segment.
3781 bool flush = true;
3782 if (start > startOfNextMemoryChunk_) {
3783 const size_t kMaxFreeLen = 2 * kPageSize;
3784 void* freeStart = startOfNextMemoryChunk_;
3785 void* freeEnd = start;
Brian Carlstrom2d888622013-07-18 17:02:00 -07003786 size_t freeLen = reinterpret_cast<char*>(freeEnd) - reinterpret_cast<char*>(freeStart);
Ian Rogers15bf2d32012-08-28 17:33:04 -07003787 if (!native || freeLen < kMaxFreeLen) {
3788 AppendChunk(HPSG_STATE(SOLIDITY_FREE, 0), freeStart, freeLen);
3789 flush = false;
3790 }
3791 }
3792 if (flush) {
3793 startOfNextMemoryChunk_ = NULL;
3794 Flush();
3795 }
3796 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08003797 mirror::Object* obj = reinterpret_cast<mirror::Object*>(start);
Elliott Hughesa2155262011-11-16 16:26:58 -08003798
3799 // Determine the type of this chunk.
3800 // OLD-TODO: if context.merge, see if this chunk is different from the last chunk.
3801 // If it's the same, we should combine them.
Ian Rogers15bf2d32012-08-28 17:33:04 -07003802 uint8_t state = ExamineObject(obj, native);
3803 // dlmalloc's chunk header is 2 * sizeof(size_t), but if the previous chunk is in use for an
3804 // allocation then the first sizeof(size_t) may belong to it.
3805 const size_t dlMallocOverhead = sizeof(size_t);
3806 AppendChunk(state, start, used_bytes + dlMallocOverhead);
Brian Carlstrom2d888622013-07-18 17:02:00 -07003807 startOfNextMemoryChunk_ = reinterpret_cast<char*>(start) + used_bytes + dlMallocOverhead;
Ian Rogers15bf2d32012-08-28 17:33:04 -07003808 }
Elliott Hughesa2155262011-11-16 16:26:58 -08003809
Ian Rogers15bf2d32012-08-28 17:33:04 -07003810 void AppendChunk(uint8_t state, void* ptr, size_t length)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003811 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07003812 // Make sure there's enough room left in the buffer.
3813 // We need to use two bytes for every fractional 256 allocation units used by the chunk plus
3814 // 17 bytes for any header.
3815 size_t needed = (((length/ALLOCATION_UNIT_SIZE + 255) / 256) * 2) + 17;
3816 size_t bytesLeft = buf_.size() - (size_t)(p_ - &buf_[0]);
3817 if (bytesLeft < needed) {
3818 Flush();
3819 }
3820
3821 bytesLeft = buf_.size() - (size_t)(p_ - &buf_[0]);
3822 if (bytesLeft < needed) {
3823 LOG(WARNING) << "Chunk is too big to transmit (chunk_len=" << length << ", "
3824 << needed << " bytes)";
3825 return;
3826 }
3827 EnsureHeader(ptr);
Elliott Hughesa2155262011-11-16 16:26:58 -08003828 // Write out the chunk description.
Ian Rogers15bf2d32012-08-28 17:33:04 -07003829 length /= ALLOCATION_UNIT_SIZE; // Convert to allocation units.
3830 totalAllocationUnits_ += length;
3831 while (length > 256) {
Ian Rogers30fab402012-01-23 15:43:46 -08003832 *p_++ = state | HPSG_PARTIAL;
3833 *p_++ = 255; // length - 1
Ian Rogers15bf2d32012-08-28 17:33:04 -07003834 length -= 256;
Elliott Hughesa2155262011-11-16 16:26:58 -08003835 }
Ian Rogers30fab402012-01-23 15:43:46 -08003836 *p_++ = state;
Ian Rogers15bf2d32012-08-28 17:33:04 -07003837 *p_++ = length - 1;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003838 }
3839
Ian Rogersef7d42f2014-01-06 12:55:46 -08003840 uint8_t ExamineObject(mirror::Object* o, bool is_native_heap)
3841 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Elliott Hughesa2155262011-11-16 16:26:58 -08003842 if (o == NULL) {
3843 return HPSG_STATE(SOLIDITY_FREE, 0);
3844 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003845
Elliott Hughesa2155262011-11-16 16:26:58 -08003846 // It's an allocated chunk. Figure out what it is.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003847
Elliott Hughesa2155262011-11-16 16:26:58 -08003848 // If we're looking at the native heap, we'll just return
3849 // (SOLIDITY_HARD, KIND_NATIVE) for all allocated chunks.
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003850 if (is_native_heap) {
Elliott Hughesa2155262011-11-16 16:26:58 -08003851 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
3852 }
3853
Ian Rogers5bfa60f2012-09-02 21:17:56 -07003854 if (!Runtime::Current()->GetHeap()->IsLiveObjectLocked(o)) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07003855 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003856 }
3857
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003858 mirror::Class* c = o->GetClass();
Elliott Hughesa2155262011-11-16 16:26:58 -08003859 if (c == NULL) {
3860 // The object was probably just created but hasn't been initialized yet.
3861 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
3862 }
3863
Mathieu Chartier590fee92013-09-13 13:46:47 -07003864 if (!Runtime::Current()->GetHeap()->IsValidObjectAddress(c)) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07003865 LOG(ERROR) << "Invalid class for managed heap object: " << o << " " << c;
Elliott Hughesa2155262011-11-16 16:26:58 -08003866 return HPSG_STATE(SOLIDITY_HARD, KIND_UNKNOWN);
3867 }
3868
3869 if (c->IsClassClass()) {
3870 return HPSG_STATE(SOLIDITY_HARD, KIND_CLASS_OBJECT);
3871 }
3872
3873 if (c->IsArrayClass()) {
3874 if (o->IsObjectArray()) {
3875 return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
3876 }
3877 switch (c->GetComponentSize()) {
3878 case 1: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_1);
3879 case 2: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_2);
3880 case 4: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
3881 case 8: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_8);
3882 }
3883 }
3884
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003885 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
3886 }
3887
Ian Rogers30fab402012-01-23 15:43:46 -08003888 std::vector<uint8_t> buf_;
3889 uint8_t* p_;
3890 uint8_t* pieceLenField_;
Ian Rogers15bf2d32012-08-28 17:33:04 -07003891 void* startOfNextMemoryChunk_;
Ian Rogers30fab402012-01-23 15:43:46 -08003892 size_t totalAllocationUnits_;
3893 uint32_t type_;
3894 bool merge_;
3895 bool needHeader_;
3896
Elliott Hughesa2155262011-11-16 16:26:58 -08003897 DISALLOW_COPY_AND_ASSIGN(HeapChunkContext);
3898};
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003899
3900void Dbg::DdmSendHeapSegments(bool native) {
3901 Dbg::HpsgWhen when;
3902 Dbg::HpsgWhat what;
3903 if (!native) {
3904 when = gDdmHpsgWhen;
3905 what = gDdmHpsgWhat;
3906 } else {
3907 when = gDdmNhsgWhen;
3908 what = gDdmNhsgWhat;
3909 }
3910 if (when == HPSG_WHEN_NEVER) {
3911 return;
3912 }
3913
3914 // Figure out what kind of chunks we'll be sending.
3915 CHECK(what == HPSG_WHAT_MERGED_OBJECTS || what == HPSG_WHAT_DISTINCT_OBJECTS) << static_cast<int>(what);
3916
3917 // First, send a heap start chunk.
3918 uint8_t heap_id[4];
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003919 JDWP::Set4BE(&heap_id[0], 1); // Heap id (bogus; we only have one heap).
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003920 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHST") : CHUNK_TYPE("HPST"), sizeof(heap_id), heap_id);
3921
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07003922 Thread* self = Thread::Current();
3923
3924 // To allow the Walk/InspectAll() below to exclusively-lock the
3925 // mutator lock, temporarily release the shared access to the
3926 // mutator lock here by transitioning to the suspended state.
3927 Locks::mutator_lock_->AssertSharedHeld(self);
3928 self->TransitionFromRunnableToSuspended(kSuspended);
3929
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003930 // Send a series of heap segment chunks.
Elliott Hughesa2155262011-11-16 16:26:58 -08003931 HeapChunkContext context((what == HPSG_WHAT_MERGED_OBJECTS), native);
3932 if (native) {
Ian Rogers1d54e732013-05-02 21:10:01 -07003933 dlmalloc_inspect_all(HeapChunkContext::HeapChunkCallback, &context);
Elliott Hughesa2155262011-11-16 16:26:58 -08003934 } else {
Ian Rogers1d54e732013-05-02 21:10:01 -07003935 gc::Heap* heap = Runtime::Current()->GetHeap();
3936 const std::vector<gc::space::ContinuousSpace*>& spaces = heap->GetContinuousSpaces();
Ian Rogers1d54e732013-05-02 21:10:01 -07003937 typedef std::vector<gc::space::ContinuousSpace*>::const_iterator It;
3938 for (It cur = spaces.begin(), end = spaces.end(); cur != end; ++cur) {
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07003939 if ((*cur)->IsMallocSpace()) {
3940 (*cur)->AsMallocSpace()->Walk(HeapChunkContext::HeapChunkCallback, &context);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07003941 }
3942 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07003943 // Walk the large objects, these are not in the AllocSpace.
3944 heap->GetLargeObjectsSpace()->Walk(HeapChunkContext::HeapChunkCallback, &context);
Elliott Hughesa2155262011-11-16 16:26:58 -08003945 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003946
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07003947 // Shared-lock the mutator lock back.
3948 self->TransitionFromSuspendedToRunnable();
3949 Locks::mutator_lock_->AssertSharedHeld(self);
3950
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003951 // Finally, send a heap end chunk.
3952 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHEN") : CHUNK_TYPE("HPEN"), sizeof(heap_id), heap_id);
Elliott Hughes767a1472011-10-26 18:49:02 -07003953}
3954
Elliott Hughesb1a58792013-07-11 18:10:58 -07003955static size_t GetAllocTrackerMax() {
3956#ifdef HAVE_ANDROID_OS
3957 // Check whether there's a system property overriding the number of records.
3958 const char* propertyName = "dalvik.vm.allocTrackerMax";
3959 char allocRecordMaxString[PROPERTY_VALUE_MAX];
3960 if (property_get(propertyName, allocRecordMaxString, "") > 0) {
3961 char* end;
3962 size_t value = strtoul(allocRecordMaxString, &end, 10);
3963 if (*end != '\0') {
Ruben Brunk3e47a742013-09-09 17:56:07 -07003964 LOG(ERROR) << "Ignoring " << propertyName << " '" << allocRecordMaxString
3965 << "' --- invalid";
Elliott Hughesb1a58792013-07-11 18:10:58 -07003966 return kDefaultNumAllocRecords;
3967 }
3968 if (!IsPowerOfTwo(value)) {
Ruben Brunk3e47a742013-09-09 17:56:07 -07003969 LOG(ERROR) << "Ignoring " << propertyName << " '" << allocRecordMaxString
3970 << "' --- not power of two";
Elliott Hughesb1a58792013-07-11 18:10:58 -07003971 return kDefaultNumAllocRecords;
3972 }
3973 return value;
3974 }
3975#endif
3976 return kDefaultNumAllocRecords;
3977}
3978
Elliott Hughes545a0642011-11-08 19:10:03 -08003979void Dbg::SetAllocTrackingEnabled(bool enabled) {
Elliott Hughes545a0642011-11-08 19:10:03 -08003980 if (enabled) {
Sebastien Hertzb98063a2014-03-26 10:57:20 +01003981 {
3982 MutexLock mu(Thread::Current(), *alloc_tracker_lock_);
3983 if (recent_allocation_records_ == NULL) {
3984 alloc_record_max_ = GetAllocTrackerMax();
3985 LOG(INFO) << "Enabling alloc tracker (" << alloc_record_max_ << " entries of "
3986 << kMaxAllocRecordStackDepth << " frames, taking "
3987 << PrettySize(sizeof(AllocRecord) * alloc_record_max_) << ")";
3988 alloc_record_head_ = alloc_record_count_ = 0;
3989 recent_allocation_records_ = new AllocRecord[alloc_record_max_];
3990 CHECK(recent_allocation_records_ != NULL);
3991 }
Elliott Hughes545a0642011-11-08 19:10:03 -08003992 }
Ian Rogersfa824272013-11-05 16:12:57 -08003993 Runtime::Current()->GetInstrumentation()->InstrumentQuickAllocEntryPoints();
Elliott Hughes545a0642011-11-08 19:10:03 -08003994 } else {
Ian Rogersfa824272013-11-05 16:12:57 -08003995 Runtime::Current()->GetInstrumentation()->UninstrumentQuickAllocEntryPoints();
Sebastien Hertzb98063a2014-03-26 10:57:20 +01003996 {
3997 MutexLock mu(Thread::Current(), *alloc_tracker_lock_);
3998 delete[] recent_allocation_records_;
3999 recent_allocation_records_ = NULL;
4000 }
Elliott Hughes545a0642011-11-08 19:10:03 -08004001 }
4002}
4003
Ian Rogers0399dde2012-06-06 17:09:28 -07004004struct AllocRecordStackVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -08004005 AllocRecordStackVisitor(Thread* thread, AllocRecord* record)
Ian Rogersb726dcb2012-09-05 08:57:23 -07004006 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08004007 : StackVisitor(thread, NULL), record(record), depth(0) {}
Elliott Hughes545a0642011-11-08 19:10:03 -08004008
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004009 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
4010 // annotalysis.
4011 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughes545a0642011-11-08 19:10:03 -08004012 if (depth >= kMaxAllocRecordStackDepth) {
Elliott Hughes530fa002012-03-12 11:44:49 -07004013 return false;
Elliott Hughes545a0642011-11-08 19:10:03 -08004014 }
Brian Carlstromea46f952013-07-30 01:26:50 -07004015 mirror::ArtMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07004016 if (!m->IsRuntimeMethod()) {
4017 record->stack[depth].method = m;
4018 record->stack[depth].dex_pc = GetDexPc();
Elliott Hughes530fa002012-03-12 11:44:49 -07004019 ++depth;
Elliott Hughes545a0642011-11-08 19:10:03 -08004020 }
Elliott Hughes530fa002012-03-12 11:44:49 -07004021 return true;
Elliott Hughes545a0642011-11-08 19:10:03 -08004022 }
4023
4024 ~AllocRecordStackVisitor() {
4025 // Clear out any unused stack trace elements.
4026 for (; depth < kMaxAllocRecordStackDepth; ++depth) {
4027 record->stack[depth].method = NULL;
Ian Rogers0399dde2012-06-06 17:09:28 -07004028 record->stack[depth].dex_pc = 0;
Elliott Hughes545a0642011-11-08 19:10:03 -08004029 }
4030 }
4031
4032 AllocRecord* record;
4033 size_t depth;
4034};
4035
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004036void Dbg::RecordAllocation(mirror::Class* type, size_t byte_count) {
Elliott Hughes545a0642011-11-08 19:10:03 -08004037 Thread* self = Thread::Current();
4038 CHECK(self != NULL);
4039
Ian Rogers719d1a32014-03-06 12:13:39 -08004040 MutexLock mu(self, *alloc_tracker_lock_);
Elliott Hughes545a0642011-11-08 19:10:03 -08004041 if (recent_allocation_records_ == NULL) {
4042 return;
4043 }
4044
4045 // Advance and clip.
Ian Rogers719d1a32014-03-06 12:13:39 -08004046 if (++alloc_record_head_ == alloc_record_max_) {
4047 alloc_record_head_ = 0;
Elliott Hughes545a0642011-11-08 19:10:03 -08004048 }
4049
4050 // Fill in the basics.
Ian Rogers719d1a32014-03-06 12:13:39 -08004051 AllocRecord* record = &recent_allocation_records_[alloc_record_head_];
Elliott Hughes545a0642011-11-08 19:10:03 -08004052 record->type = type;
4053 record->byte_count = byte_count;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07004054 record->thin_lock_id = self->GetThreadId();
Elliott Hughes545a0642011-11-08 19:10:03 -08004055
4056 // Fill in the stack trace.
Ian Rogers7a22fa62013-01-23 12:16:16 -08004057 AllocRecordStackVisitor visitor(self, record);
Ian Rogers0399dde2012-06-06 17:09:28 -07004058 visitor.WalkStack();
Elliott Hughes545a0642011-11-08 19:10:03 -08004059
Ian Rogers719d1a32014-03-06 12:13:39 -08004060 if (alloc_record_count_ < alloc_record_max_) {
4061 ++alloc_record_count_;
Elliott Hughes545a0642011-11-08 19:10:03 -08004062 }
4063}
4064
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004065// Returns the index of the head element.
4066//
4067// We point at the most-recently-written record, so if gAllocRecordCount is 1
4068// we want to use the current element. Take "head+1" and subtract count
4069// from it.
4070//
4071// We need to handle underflow in our circular buffer, so we add
Elliott Hughesb1a58792013-07-11 18:10:58 -07004072// gAllocRecordMax and then mask it back down.
Ian Rogers719d1a32014-03-06 12:13:39 -08004073size_t Dbg::HeadIndex() {
4074 return (Dbg::alloc_record_head_ + 1 + Dbg::alloc_record_max_ - Dbg::alloc_record_count_) &
4075 (Dbg::alloc_record_max_ - 1);
Elliott Hughes545a0642011-11-08 19:10:03 -08004076}
4077
4078void Dbg::DumpRecentAllocations() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004079 ScopedObjectAccess soa(Thread::Current());
Ian Rogers719d1a32014-03-06 12:13:39 -08004080 MutexLock mu(soa.Self(), *alloc_tracker_lock_);
Elliott Hughes545a0642011-11-08 19:10:03 -08004081 if (recent_allocation_records_ == NULL) {
4082 LOG(INFO) << "Not recording tracked allocations";
4083 return;
4084 }
4085
4086 // "i" is the head of the list. We want to start at the end of the
4087 // list and move forward to the tail.
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004088 size_t i = HeadIndex();
Ian Rogers719d1a32014-03-06 12:13:39 -08004089 size_t count = alloc_record_count_;
Elliott Hughes545a0642011-11-08 19:10:03 -08004090
Ian Rogers719d1a32014-03-06 12:13:39 -08004091 LOG(INFO) << "Tracked allocations, (head=" << alloc_record_head_ << " count=" << count << ")";
Elliott Hughes545a0642011-11-08 19:10:03 -08004092 while (count--) {
4093 AllocRecord* record = &recent_allocation_records_[i];
4094
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004095 LOG(INFO) << StringPrintf(" Thread %-2d %6zd bytes ", record->thin_lock_id, record->byte_count)
Elliott Hughes545a0642011-11-08 19:10:03 -08004096 << PrettyClass(record->type);
4097
4098 for (size_t stack_frame = 0; stack_frame < kMaxAllocRecordStackDepth; ++stack_frame) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08004099 mirror::ArtMethod* m = record->stack[stack_frame].method;
Elliott Hughes545a0642011-11-08 19:10:03 -08004100 if (m == NULL) {
4101 break;
4102 }
4103 LOG(INFO) << " " << PrettyMethod(m) << " line " << record->stack[stack_frame].LineNumber();
4104 }
4105
4106 // pause periodically to help logcat catch up
4107 if ((count % 5) == 0) {
4108 usleep(40000);
4109 }
4110
Ian Rogers719d1a32014-03-06 12:13:39 -08004111 i = (i + 1) & (alloc_record_max_ - 1);
Elliott Hughes545a0642011-11-08 19:10:03 -08004112 }
4113}
4114
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -07004115void Dbg::UpdateObjectPointers(IsMarkedCallback* callback, void* arg) {
Ian Rogers719d1a32014-03-06 12:13:39 -08004116 if (recent_allocation_records_ != nullptr) {
4117 MutexLock mu(Thread::Current(), *alloc_tracker_lock_);
4118 size_t i = HeadIndex();
4119 size_t count = alloc_record_count_;
4120 while (count--) {
4121 AllocRecord* record = &recent_allocation_records_[i];
4122 DCHECK(record != nullptr);
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -07004123 record->UpdateObjectPointers(callback, arg);
Ian Rogers719d1a32014-03-06 12:13:39 -08004124 i = (i + 1) & (alloc_record_max_ - 1);
Mathieu Chartier412c7fc2014-02-07 12:18:39 -08004125 }
4126 }
4127 if (gRegistry != nullptr) {
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -07004128 gRegistry->UpdateObjectPointers(callback, arg);
Mathieu Chartier412c7fc2014-02-07 12:18:39 -08004129 }
4130}
4131
4132void Dbg::AllowNewObjectRegistryObjects() {
4133 if (gRegistry != nullptr) {
4134 gRegistry->AllowNewObjects();
4135 }
4136}
4137
4138void Dbg::DisallowNewObjectRegistryObjects() {
4139 if (gRegistry != nullptr) {
4140 gRegistry->DisallowNewObjects();
4141 }
4142}
4143
Elliott Hughes545a0642011-11-08 19:10:03 -08004144class StringTable {
4145 public:
4146 StringTable() {
4147 }
4148
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004149 void Add(const char* s) {
Elliott Hughes545a0642011-11-08 19:10:03 -08004150 table_.insert(s);
4151 }
4152
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004153 size_t IndexOf(const char* s) const {
Mathieu Chartier02e25112013-08-14 16:14:24 -07004154 auto it = table_.find(s);
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004155 if (it == table_.end()) {
4156 LOG(FATAL) << "IndexOf(\"" << s << "\") failed";
4157 }
4158 return std::distance(table_.begin(), it);
Elliott Hughes545a0642011-11-08 19:10:03 -08004159 }
4160
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004161 size_t Size() const {
Elliott Hughes545a0642011-11-08 19:10:03 -08004162 return table_.size();
4163 }
4164
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004165 void WriteTo(std::vector<uint8_t>& bytes) const {
Mathieu Chartier02e25112013-08-14 16:14:24 -07004166 for (const std::string& str : table_) {
4167 const char* s = str.c_str();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004168 size_t s_len = CountModifiedUtf8Chars(s);
4169 UniquePtr<uint16_t> s_utf16(new uint16_t[s_len]);
4170 ConvertModifiedUtf8ToUtf16(s_utf16.get(), s);
4171 JDWP::AppendUtf16BE(bytes, s_utf16.get(), s_len);
Elliott Hughes545a0642011-11-08 19:10:03 -08004172 }
4173 }
4174
4175 private:
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004176 std::set<std::string> table_;
Elliott Hughes545a0642011-11-08 19:10:03 -08004177 DISALLOW_COPY_AND_ASSIGN(StringTable);
4178};
4179
4180/*
4181 * The data we send to DDMS contains everything we have recorded.
4182 *
4183 * Message header (all values big-endian):
4184 * (1b) message header len (to allow future expansion); includes itself
4185 * (1b) entry header len
4186 * (1b) stack frame len
4187 * (2b) number of entries
4188 * (4b) offset to string table from start of message
4189 * (2b) number of class name strings
4190 * (2b) number of method name strings
4191 * (2b) number of source file name strings
4192 * For each entry:
4193 * (4b) total allocation size
Elliott Hughes221229c2013-01-08 18:17:50 -08004194 * (2b) thread id
Elliott Hughes545a0642011-11-08 19:10:03 -08004195 * (2b) allocated object's class name index
4196 * (1b) stack depth
4197 * For each stack frame:
4198 * (2b) method's class name
4199 * (2b) method name
4200 * (2b) method source file
4201 * (2b) line number, clipped to 32767; -2 if native; -1 if no source
4202 * (xb) class name strings
4203 * (xb) method name strings
4204 * (xb) source file strings
4205 *
4206 * As with other DDM traffic, strings are sent as a 4-byte length
4207 * followed by UTF-16 data.
4208 *
4209 * We send up 16-bit unsigned indexes into string tables. In theory there
Elliott Hughesb1a58792013-07-11 18:10:58 -07004210 * can be (kMaxAllocRecordStackDepth * gAllocRecordMax) unique strings in
Elliott Hughes545a0642011-11-08 19:10:03 -08004211 * each table, but in practice there should be far fewer.
4212 *
4213 * The chief reason for using a string table here is to keep the size of
4214 * the DDMS message to a minimum. This is partly to make the protocol
4215 * efficient, but also because we have to form the whole thing up all at
4216 * once in a memory buffer.
4217 *
4218 * We use separate string tables for class names, method names, and source
4219 * files to keep the indexes small. There will generally be no overlap
4220 * between the contents of these tables.
4221 */
4222jbyteArray Dbg::GetRecentAllocations() {
4223 if (false) {
4224 DumpRecentAllocations();
4225 }
4226
Ian Rogers50b35e22012-10-04 10:09:15 -07004227 Thread* self = Thread::Current();
Elliott Hughes545a0642011-11-08 19:10:03 -08004228 std::vector<uint8_t> bytes;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004229 {
Ian Rogers719d1a32014-03-06 12:13:39 -08004230 MutexLock mu(self, *alloc_tracker_lock_);
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004231 //
4232 // Part 1: generate string tables.
4233 //
4234 StringTable class_names;
4235 StringTable method_names;
4236 StringTable filenames;
Elliott Hughes545a0642011-11-08 19:10:03 -08004237
Ian Rogers719d1a32014-03-06 12:13:39 -08004238 int count = alloc_record_count_;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004239 int idx = HeadIndex();
4240 while (count--) {
4241 AllocRecord* record = &recent_allocation_records_[idx];
Elliott Hughes545a0642011-11-08 19:10:03 -08004242
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004243 class_names.Add(ClassHelper(record->type).GetDescriptor());
Elliott Hughes545a0642011-11-08 19:10:03 -08004244
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004245 MethodHelper mh;
4246 for (size_t i = 0; i < kMaxAllocRecordStackDepth; i++) {
Brian Carlstromea46f952013-07-30 01:26:50 -07004247 mirror::ArtMethod* m = record->stack[i].method;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004248 if (m != NULL) {
4249 mh.ChangeMethod(m);
4250 class_names.Add(mh.GetDeclaringClassDescriptor());
4251 method_names.Add(mh.GetName());
4252 filenames.Add(mh.GetDeclaringClassSourceFile());
4253 }
4254 }
Elliott Hughes545a0642011-11-08 19:10:03 -08004255
Ian Rogers719d1a32014-03-06 12:13:39 -08004256 idx = (idx + 1) & (alloc_record_max_ - 1);
Elliott Hughes545a0642011-11-08 19:10:03 -08004257 }
4258
Ian Rogers719d1a32014-03-06 12:13:39 -08004259 LOG(INFO) << "allocation records: " << alloc_record_count_;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004260
4261 //
4262 // Part 2: Generate the output and store it in the buffer.
4263 //
4264
4265 // (1b) message header len (to allow future expansion); includes itself
4266 // (1b) entry header len
4267 // (1b) stack frame len
4268 const int kMessageHeaderLen = 15;
4269 const int kEntryHeaderLen = 9;
4270 const int kStackFrameLen = 8;
4271 JDWP::Append1BE(bytes, kMessageHeaderLen);
4272 JDWP::Append1BE(bytes, kEntryHeaderLen);
4273 JDWP::Append1BE(bytes, kStackFrameLen);
4274
4275 // (2b) number of entries
4276 // (4b) offset to string table from start of message
4277 // (2b) number of class name strings
4278 // (2b) number of method name strings
4279 // (2b) number of source file name strings
Ian Rogers719d1a32014-03-06 12:13:39 -08004280 JDWP::Append2BE(bytes, alloc_record_count_);
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004281 size_t string_table_offset = bytes.size();
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004282 JDWP::Append4BE(bytes, 0); // We'll patch this later...
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004283 JDWP::Append2BE(bytes, class_names.Size());
4284 JDWP::Append2BE(bytes, method_names.Size());
4285 JDWP::Append2BE(bytes, filenames.Size());
4286
Ian Rogers719d1a32014-03-06 12:13:39 -08004287 count = alloc_record_count_;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004288 idx = HeadIndex();
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004289 while (count--) {
4290 // For each entry:
4291 // (4b) total allocation size
4292 // (2b) thread id
4293 // (2b) allocated object's class name index
4294 // (1b) stack depth
4295 AllocRecord* record = &recent_allocation_records_[idx];
4296 size_t stack_depth = record->GetDepth();
Mathieu Chartier590fee92013-09-13 13:46:47 -07004297 ClassHelper kh(record->type);
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004298 size_t allocated_object_class_name_index = class_names.IndexOf(kh.GetDescriptor());
4299 JDWP::Append4BE(bytes, record->byte_count);
4300 JDWP::Append2BE(bytes, record->thin_lock_id);
4301 JDWP::Append2BE(bytes, allocated_object_class_name_index);
4302 JDWP::Append1BE(bytes, stack_depth);
4303
4304 MethodHelper mh;
4305 for (size_t stack_frame = 0; stack_frame < stack_depth; ++stack_frame) {
4306 // For each stack frame:
4307 // (2b) method's class name
4308 // (2b) method name
4309 // (2b) method source file
4310 // (2b) line number, clipped to 32767; -2 if native; -1 if no source
4311 mh.ChangeMethod(record->stack[stack_frame].method);
4312 size_t class_name_index = class_names.IndexOf(mh.GetDeclaringClassDescriptor());
4313 size_t method_name_index = method_names.IndexOf(mh.GetName());
4314 size_t file_name_index = filenames.IndexOf(mh.GetDeclaringClassSourceFile());
4315 JDWP::Append2BE(bytes, class_name_index);
4316 JDWP::Append2BE(bytes, method_name_index);
4317 JDWP::Append2BE(bytes, file_name_index);
4318 JDWP::Append2BE(bytes, record->stack[stack_frame].LineNumber());
4319 }
4320
Ian Rogers719d1a32014-03-06 12:13:39 -08004321 idx = (idx + 1) & (alloc_record_max_ - 1);
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004322 }
4323
4324 // (xb) class name strings
4325 // (xb) method name strings
4326 // (xb) source file strings
4327 JDWP::Set4BE(&bytes[string_table_offset], bytes.size());
4328 class_names.WriteTo(bytes);
4329 method_names.WriteTo(bytes);
4330 filenames.WriteTo(bytes);
Elliott Hughes545a0642011-11-08 19:10:03 -08004331 }
Ian Rogers50b35e22012-10-04 10:09:15 -07004332 JNIEnv* env = self->GetJniEnv();
Elliott Hughes545a0642011-11-08 19:10:03 -08004333 jbyteArray result = env->NewByteArray(bytes.size());
4334 if (result != NULL) {
4335 env->SetByteArrayRegion(result, 0, bytes.size(), reinterpret_cast<const jbyte*>(&bytes[0]));
4336 }
4337 return result;
4338}
4339
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004340} // namespace art