blob: bcecbc24230c21fe5b8d288d18e8c87218c1c06d [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
Ian Rogers62d6c772013-02-27 08:32:07 -0800129class DebugInstrumentationListener : public instrumentation::InstrumentationListener {
130 public:
131 DebugInstrumentationListener() {}
132 virtual ~DebugInstrumentationListener() {}
133
134 virtual void MethodEntered(Thread* thread, mirror::Object* this_object,
Ian Rogersef7d42f2014-01-06 12:55:46 -0800135 mirror::ArtMethod* method, uint32_t dex_pc)
Ian Rogers62d6c772013-02-27 08:32:07 -0800136 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
137 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
144 virtual void MethodExited(Thread* thread, mirror::Object* this_object,
Ian Rogersef7d42f2014-01-06 12:55:46 -0800145 mirror::ArtMethod* method,
Ian Rogers62d6c772013-02-27 08:32:07 -0800146 uint32_t dex_pc, const JValue& return_value)
147 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800148 if (method->IsNative()) {
149 // TODO: post location events is a suspension point and native method entry stubs aren't.
150 return;
151 }
Jeff Hao579b0242013-11-18 13:16:49 -0800152 Dbg::PostLocationEvent(method, dex_pc, this_object, Dbg::kMethodExit, &return_value);
Ian Rogers62d6c772013-02-27 08:32:07 -0800153 }
154
Sebastien Hertz51db44a2013-11-19 10:00:29 +0100155 virtual void MethodUnwind(Thread* thread, mirror::Object* this_object,
Ian Rogersef7d42f2014-01-06 12:55:46 -0800156 mirror::ArtMethod* method, uint32_t dex_pc)
Sebastien Hertz51db44a2013-11-19 10:00:29 +0100157 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800158 // We're not recorded to listen to this kind of event, so complain.
159 LOG(ERROR) << "Unexpected method unwind event in debugger " << PrettyMethod(method)
Sebastien Hertz51db44a2013-11-19 10:00:29 +0100160 << " " << dex_pc;
Ian Rogers62d6c772013-02-27 08:32:07 -0800161 }
162
163 virtual void DexPcMoved(Thread* thread, mirror::Object* this_object,
Ian Rogersef7d42f2014-01-06 12:55:46 -0800164 mirror::ArtMethod* method, uint32_t new_dex_pc)
Ian Rogers62d6c772013-02-27 08:32:07 -0800165 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
166 Dbg::UpdateDebugger(thread, this_object, method, new_dex_pc);
167 }
168
169 virtual void ExceptionCaught(Thread* thread, const ThrowLocation& throw_location,
Brian Carlstromea46f952013-07-30 01:26:50 -0700170 mirror::ArtMethod* catch_method, uint32_t catch_dex_pc,
Ian Rogers62d6c772013-02-27 08:32:07 -0800171 mirror::Throwable* exception_object)
172 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
173 Dbg::PostException(thread, throw_location, catch_method, catch_dex_pc, exception_object);
174 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800175} gDebugInstrumentationListener;
176
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700177// JDWP is allowed unless the Zygote forbids it.
178static bool gJdwpAllowed = true;
179
Elliott Hughesc0f09332012-03-26 13:27:06 -0700180// Was there a -Xrunjdwp or -agentlib:jdwp= argument on the command line?
Elliott Hughes3bb81562011-10-21 18:52:59 -0700181static bool gJdwpConfigured = false;
182
Elliott Hughesc0f09332012-03-26 13:27:06 -0700183// Broken-down JDWP options. (Only valid if IsJdwpConfigured() is true.)
Elliott Hughes376a7a02011-10-24 18:35:55 -0700184static JDWP::JdwpOptions gJdwpOptions;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700185
186// Runtime JDWP state.
187static JDWP::JdwpState* gJdwpState = NULL;
188static bool gDebuggerConnected; // debugger or DDMS is connected.
189static bool gDebuggerActive; // debugger is making requests.
Elliott Hughes86964332012-02-15 19:37:42 -0800190static bool gDisposed; // debugger called VirtualMachine.Dispose, so we should drop the connection.
Elliott Hughes3bb81562011-10-21 18:52:59 -0700191
Elliott Hughes47fce012011-10-25 18:37:19 -0700192static bool gDdmThreadNotification = false;
193
Elliott Hughes767a1472011-10-26 18:49:02 -0700194// DDMS GC-related settings.
195static Dbg::HpifWhen gDdmHpifWhen = Dbg::HPIF_WHEN_NEVER;
196static Dbg::HpsgWhen gDdmHpsgWhen = Dbg::HPSG_WHEN_NEVER;
197static Dbg::HpsgWhat gDdmHpsgWhat;
198static Dbg::HpsgWhen gDdmNhsgWhen = Dbg::HPSG_WHEN_NEVER;
199static Dbg::HpsgWhat gDdmNhsgWhat;
200
Ian Rogers719d1a32014-03-06 12:13:39 -0800201static ObjectRegistry* gRegistry = nullptr;
Elliott Hughes475fc232011-10-25 15:00:35 -0700202
Elliott Hughes545a0642011-11-08 19:10:03 -0800203// Recent allocation tracking.
Ian Rogers719d1a32014-03-06 12:13:39 -0800204Mutex* Dbg::alloc_tracker_lock_ = nullptr;
205AllocRecord* Dbg::recent_allocation_records_ = nullptr; // TODO: CircularBuffer<AllocRecord>
206size_t Dbg::alloc_record_max_ = 0;
207size_t Dbg::alloc_record_head_ = 0;
208size_t Dbg::alloc_record_count_ = 0;
Elliott Hughes545a0642011-11-08 19:10:03 -0800209
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100210// Deoptimization support.
Sebastien Hertz4d25df32014-03-21 17:44:46 +0100211Mutex* Dbg::deoptimization_lock_ = nullptr;
212std::vector<DeoptimizationRequest> Dbg::deoptimization_requests_;
213size_t Dbg::full_deoptimization_event_count_ = 0;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100214
215// Breakpoints.
jeffhao09bfc6a2012-12-11 18:11:43 -0800216static std::vector<Breakpoint> gBreakpoints GUARDED_BY(Locks::breakpoint_lock_);
Elliott Hughes86964332012-02-15 19:37:42 -0800217
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700218void DebugInvokeReq::VisitRoots(RootCallback* callback, void* arg, uint32_t tid,
219 RootType root_type) {
220 if (receiver != nullptr) {
221 callback(&receiver, arg, tid, root_type);
222 }
223 if (thread != nullptr) {
224 callback(&thread, arg, tid, root_type);
225 }
226 if (klass != nullptr) {
227 callback(reinterpret_cast<mirror::Object**>(&klass), arg, tid, root_type);
228 }
229 if (method != nullptr) {
230 callback(reinterpret_cast<mirror::Object**>(&method), arg, tid, root_type);
231 }
232}
233
Sebastien Hertzbb43b432014-04-14 11:59:08 +0200234void DebugInvokeReq::Clear() {
235 invoke_needed = false;
236 receiver = nullptr;
237 thread = nullptr;
238 klass = nullptr;
239 method = nullptr;
240}
241
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700242void SingleStepControl::VisitRoots(RootCallback* callback, void* arg, uint32_t tid,
243 RootType root_type) {
244 if (method != nullptr) {
245 callback(reinterpret_cast<mirror::Object**>(&method), arg, tid, root_type);
246 }
247}
248
Sebastien Hertzbb43b432014-04-14 11:59:08 +0200249bool SingleStepControl::ContainsDexPc(uint32_t dex_pc) const {
250 return dex_pcs.find(dex_pc) == dex_pcs.end();
251}
252
253void SingleStepControl::Clear() {
254 is_active = false;
255 method = nullptr;
256 dex_pcs.clear();
257}
258
Sebastien Hertz4d25df32014-03-21 17:44:46 +0100259void DeoptimizationRequest::VisitRoots(RootCallback* callback, void* arg) {
260 if (method != nullptr) {
261 callback(reinterpret_cast<mirror::Object**>(&method), arg, 0, kRootDebugger);
262 }
263}
264
Brian Carlstromea46f952013-07-30 01:26:50 -0700265static bool IsBreakpoint(const mirror::ArtMethod* m, uint32_t dex_pc)
jeffhao09bfc6a2012-12-11 18:11:43 -0800266 LOCKS_EXCLUDED(Locks::breakpoint_lock_)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700267 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
jeffhao09bfc6a2012-12-11 18:11:43 -0800268 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100269 for (size_t i = 0, e = gBreakpoints.size(); i < e; ++i) {
Elliott Hughesa656a0f2012-02-21 18:03:44 -0800270 if (gBreakpoints[i].method == m && gBreakpoints[i].dex_pc == dex_pc) {
Elliott Hughes86964332012-02-15 19:37:42 -0800271 VLOG(jdwp) << "Hit breakpoint #" << i << ": " << gBreakpoints[i];
272 return true;
273 }
274 }
275 return false;
276}
277
Sebastien Hertz52d131d2014-03-13 16:17:40 +0100278static bool IsSuspendedForDebugger(ScopedObjectAccessUnchecked& soa, Thread* thread)
279 LOCKS_EXCLUDED(Locks::thread_suspend_count_lock_) {
Elliott Hughes9e0c1752013-01-09 14:02:58 -0800280 MutexLock mu(soa.Self(), *Locks::thread_suspend_count_lock_);
281 // A thread may be suspended for GC; in this code, we really want to know whether
282 // there's a debugger suspension active.
283 return thread->IsSuspended() && thread->GetDebugSuspendCount() > 0;
284}
285
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800286static mirror::Array* DecodeArray(JDWP::RefTypeId id, JDWP::JdwpError& status)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700287 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800288 mirror::Object* o = gRegistry->Get<mirror::Object*>(id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800289 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800290 status = JDWP::ERR_INVALID_OBJECT;
291 return NULL;
292 }
293 if (!o->IsArrayInstance()) {
294 status = JDWP::ERR_INVALID_ARRAY;
295 return NULL;
296 }
297 status = JDWP::ERR_NONE;
298 return o->AsArray();
299}
300
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800301static mirror::Class* DecodeClass(JDWP::RefTypeId id, JDWP::JdwpError& status)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700302 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800303 mirror::Object* o = gRegistry->Get<mirror::Object*>(id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800304 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800305 status = JDWP::ERR_INVALID_OBJECT;
306 return NULL;
307 }
308 if (!o->IsClass()) {
309 status = JDWP::ERR_INVALID_CLASS;
310 return NULL;
311 }
312 status = JDWP::ERR_NONE;
313 return o->AsClass();
314}
315
Elliott Hughes221229c2013-01-08 18:17:50 -0800316static JDWP::JdwpError DecodeThread(ScopedObjectAccessUnchecked& soa, JDWP::ObjectId thread_id, Thread*& thread)
jeffhaoa77f0f62012-12-05 17:19:31 -0800317 EXCLUSIVE_LOCKS_REQUIRED(Locks::thread_list_lock_)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700318 LOCKS_EXCLUDED(Locks::thread_suspend_count_lock_)
319 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800320 mirror::Object* thread_peer = gRegistry->Get<mirror::Object*>(thread_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800321 if (thread_peer == NULL || thread_peer == ObjectRegistry::kInvalidObject) {
Elliott Hughes221229c2013-01-08 18:17:50 -0800322 // This isn't even an object.
323 return JDWP::ERR_INVALID_OBJECT;
Elliott Hughes436e3722012-02-17 20:01:47 -0800324 }
Elliott Hughes221229c2013-01-08 18:17:50 -0800325
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800326 mirror::Class* java_lang_Thread = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_Thread);
Elliott Hughes221229c2013-01-08 18:17:50 -0800327 if (!java_lang_Thread->IsAssignableFrom(thread_peer->GetClass())) {
328 // This isn't a thread.
329 return JDWP::ERR_INVALID_THREAD;
330 }
331
332 thread = Thread::FromManagedThread(soa, thread_peer);
333 if (thread == NULL) {
334 // This is a java.lang.Thread without a Thread*. Must be a zombie.
335 return JDWP::ERR_THREAD_NOT_ALIVE;
336 }
337 return JDWP::ERR_NONE;
Elliott Hughes436e3722012-02-17 20:01:47 -0800338}
339
Elliott Hughes24437992011-11-30 14:49:33 -0800340static JDWP::JdwpTag BasicTagFromDescriptor(const char* descriptor) {
341 // JDWP deliberately uses the descriptor characters' ASCII values for its enum.
342 // Note that by "basic" we mean that we don't get more specific than JT_OBJECT.
343 return static_cast<JDWP::JdwpTag>(descriptor[0]);
344}
345
Ian Rogers98379392014-02-24 16:53:16 -0800346static JDWP::JdwpTag TagFromClass(const ScopedObjectAccessUnchecked& soa, mirror::Class* c)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700347 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes86b00102011-12-05 17:54:26 -0800348 CHECK(c != NULL);
Elliott Hughes24437992011-11-30 14:49:33 -0800349 if (c->IsArrayClass()) {
350 return JDWP::JT_ARRAY;
351 }
Elliott Hughes24437992011-11-30 14:49:33 -0800352 if (c->IsStringClass()) {
353 return JDWP::JT_STRING;
Elliott Hughes24437992011-11-30 14:49:33 -0800354 }
Ian Rogers98379392014-02-24 16:53:16 -0800355 if (c->IsClassClass()) {
356 return JDWP::JT_CLASS_OBJECT;
357 }
358 {
359 mirror::Class* thread_class = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_Thread);
360 if (thread_class->IsAssignableFrom(c)) {
361 return JDWP::JT_THREAD;
362 }
363 }
364 {
365 mirror::Class* thread_group_class =
366 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_ThreadGroup);
367 if (thread_group_class->IsAssignableFrom(c)) {
368 return JDWP::JT_THREAD_GROUP;
369 }
370 }
371 {
372 mirror::Class* class_loader_class =
373 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_ClassLoader);
374 if (class_loader_class->IsAssignableFrom(c)) {
375 return JDWP::JT_CLASS_LOADER;
376 }
377 }
378 return JDWP::JT_OBJECT;
Elliott Hughes24437992011-11-30 14:49:33 -0800379}
380
381/*
382 * Objects declared to hold Object might actually hold a more specific
383 * type. The debugger may take a special interest in these (e.g. it
384 * wants to display the contents of Strings), so we want to return an
385 * appropriate tag.
386 *
387 * Null objects are tagged JT_OBJECT.
388 */
Ian Rogers98379392014-02-24 16:53:16 -0800389static JDWP::JdwpTag TagFromObject(const ScopedObjectAccessUnchecked& soa, mirror::Object* o)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700390 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers98379392014-02-24 16:53:16 -0800391 return (o == NULL) ? JDWP::JT_OBJECT : TagFromClass(soa, o->GetClass());
Elliott Hughes24437992011-11-30 14:49:33 -0800392}
393
394static bool IsPrimitiveTag(JDWP::JdwpTag tag) {
395 switch (tag) {
396 case JDWP::JT_BOOLEAN:
397 case JDWP::JT_BYTE:
398 case JDWP::JT_CHAR:
399 case JDWP::JT_FLOAT:
400 case JDWP::JT_DOUBLE:
401 case JDWP::JT_INT:
402 case JDWP::JT_LONG:
403 case JDWP::JT_SHORT:
404 case JDWP::JT_VOID:
405 return true;
406 default:
407 return false;
408 }
409}
410
Elliott Hughes3bb81562011-10-21 18:52:59 -0700411/*
412 * Handle one of the JDWP name/value pairs.
413 *
414 * JDWP options are:
415 * help: if specified, show help message and bail
416 * transport: may be dt_socket or dt_shmem
417 * address: for dt_socket, "host:port", or just "port" when listening
418 * server: if "y", wait for debugger to attach; if "n", attach to debugger
419 * timeout: how long to wait for debugger to connect / listen
420 *
421 * Useful with server=n (these aren't supported yet):
422 * onthrow=<exception-name>: connect to debugger when exception thrown
423 * onuncaught=y|n: connect to debugger when uncaught exception thrown
424 * launch=<command-line>: launch the debugger itself
425 *
426 * The "transport" option is required, as is "address" if server=n.
427 */
428static bool ParseJdwpOption(const std::string& name, const std::string& value) {
429 if (name == "transport") {
430 if (value == "dt_socket") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700431 gJdwpOptions.transport = JDWP::kJdwpTransportSocket;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700432 } else if (value == "dt_android_adb") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700433 gJdwpOptions.transport = JDWP::kJdwpTransportAndroidAdb;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700434 } else {
435 LOG(ERROR) << "JDWP transport not supported: " << value;
436 return false;
437 }
438 } else if (name == "server") {
439 if (value == "n") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700440 gJdwpOptions.server = false;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700441 } else if (value == "y") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700442 gJdwpOptions.server = true;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700443 } else {
444 LOG(ERROR) << "JDWP option 'server' must be 'y' or 'n'";
445 return false;
446 }
447 } else if (name == "suspend") {
448 if (value == "n") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700449 gJdwpOptions.suspend = false;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700450 } else if (value == "y") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700451 gJdwpOptions.suspend = true;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700452 } else {
453 LOG(ERROR) << "JDWP option 'suspend' must be 'y' or 'n'";
454 return false;
455 }
456 } else if (name == "address") {
457 /* this is either <port> or <host>:<port> */
458 std::string port_string;
Elliott Hughes376a7a02011-10-24 18:35:55 -0700459 gJdwpOptions.host.clear();
Elliott Hughes3bb81562011-10-21 18:52:59 -0700460 std::string::size_type colon = value.find(':');
461 if (colon != std::string::npos) {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700462 gJdwpOptions.host = value.substr(0, colon);
Elliott Hughes3bb81562011-10-21 18:52:59 -0700463 port_string = value.substr(colon + 1);
464 } else {
465 port_string = value;
466 }
467 if (port_string.empty()) {
468 LOG(ERROR) << "JDWP address missing port: " << value;
469 return false;
470 }
471 char* end;
Elliott Hughesba8eee12012-01-24 20:25:24 -0800472 uint64_t port = strtoul(port_string.c_str(), &end, 10);
473 if (*end != '\0' || port > 0xffff) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700474 LOG(ERROR) << "JDWP address has junk in port field: " << value;
475 return false;
476 }
Elliott Hughes376a7a02011-10-24 18:35:55 -0700477 gJdwpOptions.port = port;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700478 } else if (name == "launch" || name == "onthrow" || name == "oncaught" || name == "timeout") {
479 /* valid but unsupported */
480 LOG(INFO) << "Ignoring JDWP option '" << name << "'='" << value << "'";
481 } else {
482 LOG(INFO) << "Ignoring unrecognized JDWP option '" << name << "'='" << value << "'";
483 }
484
485 return true;
486}
487
488/*
489 * Parse the latter half of a -Xrunjdwp/-agentlib:jdwp= string, e.g.:
490 * "transport=dt_socket,address=8000,server=y,suspend=n"
491 */
492bool Dbg::ParseJdwpOptions(const std::string& options) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800493 VLOG(jdwp) << "ParseJdwpOptions: " << options;
Elliott Hughes47fce012011-10-25 18:37:19 -0700494
Elliott Hughes3bb81562011-10-21 18:52:59 -0700495 std::vector<std::string> pairs;
496 Split(options, ',', pairs);
497
498 for (size_t i = 0; i < pairs.size(); ++i) {
499 std::string::size_type equals = pairs[i].find('=');
500 if (equals == std::string::npos) {
501 LOG(ERROR) << "Can't parse JDWP option '" << pairs[i] << "' in '" << options << "'";
502 return false;
503 }
504 ParseJdwpOption(pairs[i].substr(0, equals), pairs[i].substr(equals + 1));
505 }
506
Elliott Hughes376a7a02011-10-24 18:35:55 -0700507 if (gJdwpOptions.transport == JDWP::kJdwpTransportUnknown) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700508 LOG(ERROR) << "Must specify JDWP transport: " << options;
509 }
Elliott Hughes376a7a02011-10-24 18:35:55 -0700510 if (!gJdwpOptions.server && (gJdwpOptions.host.empty() || gJdwpOptions.port == 0)) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700511 LOG(ERROR) << "Must specify JDWP host and port when server=n: " << options;
512 return false;
513 }
514
515 gJdwpConfigured = true;
516 return true;
517}
518
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700519void Dbg::StartJdwp() {
Elliott Hughesc0f09332012-03-26 13:27:06 -0700520 if (!gJdwpAllowed || !IsJdwpConfigured()) {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700521 // No JDWP for you!
522 return;
523 }
524
Ian Rogers719d1a32014-03-06 12:13:39 -0800525 CHECK(gRegistry == nullptr);
Elliott Hughes475fc232011-10-25 15:00:35 -0700526 gRegistry = new ObjectRegistry;
527
Ian Rogers719d1a32014-03-06 12:13:39 -0800528 alloc_tracker_lock_ = new Mutex("AllocTracker lock");
Sebastien Hertz4d25df32014-03-21 17:44:46 +0100529 deoptimization_lock_ = new Mutex("deoptimization lock", kDeoptimizationLock);
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700530 // Init JDWP if the debugger is enabled. This may connect out to a
531 // debugger, passively listen for a debugger, or block waiting for a
532 // debugger.
Elliott Hughes376a7a02011-10-24 18:35:55 -0700533 gJdwpState = JDWP::JdwpState::Create(&gJdwpOptions);
534 if (gJdwpState == NULL) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -0800535 // We probably failed because some other process has the port already, which means that
536 // if we don't abort the user is likely to think they're talking to us when they're actually
537 // talking to that other process.
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800538 LOG(FATAL) << "Debugger thread failed to initialize";
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700539 }
540
541 // If a debugger has already attached, send the "welcome" message.
542 // This may cause us to suspend all threads.
Elliott Hughes376a7a02011-10-24 18:35:55 -0700543 if (gJdwpState->IsActive()) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700544 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes376a7a02011-10-24 18:35:55 -0700545 if (!gJdwpState->PostVMStart()) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800546 LOG(WARNING) << "Failed to post 'start' message to debugger";
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700547 }
548 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700549}
550
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700551void Dbg::VisitRoots(RootCallback* callback, void* arg) {
Sebastien Hertz4d25df32014-03-21 17:44:46 +0100552 {
553 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
554 for (Breakpoint& bp : gBreakpoints) {
555 bp.VisitRoots(callback, arg);
556 }
557 }
558 if (deoptimization_lock_ != nullptr) { // only true if the debugger is started.
559 MutexLock mu(Thread::Current(), *deoptimization_lock_);
560 for (DeoptimizationRequest& req : deoptimization_requests_) {
561 req.VisitRoots(callback, arg);
562 }
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700563 }
564}
565
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700566void Dbg::StopJdwp() {
Sebastien Hertz0376e6b2014-02-06 18:12:59 +0100567 // Prevent the JDWP thread from processing JDWP incoming packets after we close the connection.
568 Disposed();
Elliott Hughes376a7a02011-10-24 18:35:55 -0700569 delete gJdwpState;
Ian Rogers719d1a32014-03-06 12:13:39 -0800570 gJdwpState = nullptr;
Elliott Hughes475fc232011-10-25 15:00:35 -0700571 delete gRegistry;
Ian Rogers719d1a32014-03-06 12:13:39 -0800572 gRegistry = nullptr;
573 delete alloc_tracker_lock_;
574 alloc_tracker_lock_ = nullptr;
Sebastien Hertz4d25df32014-03-21 17:44:46 +0100575 delete deoptimization_lock_;
576 deoptimization_lock_ = nullptr;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700577}
578
Elliott Hughes767a1472011-10-26 18:49:02 -0700579void Dbg::GcDidFinish() {
580 if (gDdmHpifWhen != HPIF_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700581 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes81ff3182012-03-23 20:35:56 -0700582 LOG(DEBUG) << "Sending heap info to DDM";
Elliott Hughes7162ad92011-10-27 14:08:42 -0700583 DdmSendHeapInfo(gDdmHpifWhen);
Elliott Hughes767a1472011-10-26 18:49:02 -0700584 }
585 if (gDdmHpsgWhen != HPSG_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700586 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes81ff3182012-03-23 20:35:56 -0700587 LOG(DEBUG) << "Dumping heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700588 DdmSendHeapSegments(false);
Elliott Hughes767a1472011-10-26 18:49:02 -0700589 }
590 if (gDdmNhsgWhen != HPSG_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700591 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes767a1472011-10-26 18:49:02 -0700592 LOG(DEBUG) << "Dumping native heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700593 DdmSendHeapSegments(true);
Elliott Hughes767a1472011-10-26 18:49:02 -0700594 }
595}
596
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700597void Dbg::SetJdwpAllowed(bool allowed) {
598 gJdwpAllowed = allowed;
599}
600
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700601DebugInvokeReq* Dbg::GetInvokeReq() {
Elliott Hughes475fc232011-10-25 15:00:35 -0700602 return Thread::Current()->GetInvokeReq();
603}
604
605Thread* Dbg::GetDebugThread() {
606 return (gJdwpState != NULL) ? gJdwpState->GetDebugThread() : NULL;
607}
608
609void Dbg::ClearWaitForEventThread() {
610 gJdwpState->ClearWaitForEventThread();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700611}
612
613void Dbg::Connected() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700614 CHECK(!gDebuggerConnected);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800615 VLOG(jdwp) << "JDWP has attached";
Elliott Hughes3bb81562011-10-21 18:52:59 -0700616 gDebuggerConnected = true;
Elliott Hughes86964332012-02-15 19:37:42 -0800617 gDisposed = false;
618}
619
620void Dbg::Disposed() {
621 gDisposed = true;
622}
623
624bool Dbg::IsDisposed() {
625 return gDisposed;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700626}
627
Elliott Hughesa2155262011-11-16 16:26:58 -0800628void Dbg::GoActive() {
629 // Enable all debugging features, including scans for breakpoints.
630 // This is a no-op if we're already active.
631 // Only called from the JDWP handler thread.
632 if (gDebuggerActive) {
633 return;
634 }
635
Elliott Hughesc0f09332012-03-26 13:27:06 -0700636 {
637 // TODO: dalvik only warned if there were breakpoints left over. clear in Dbg::Disconnected?
jeffhao09bfc6a2012-12-11 18:11:43 -0800638 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Elliott Hughesc0f09332012-03-26 13:27:06 -0700639 CHECK_EQ(gBreakpoints.size(), 0U);
640 }
Elliott Hughesa2155262011-11-16 16:26:58 -0800641
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100642 {
Sebastien Hertz4d25df32014-03-21 17:44:46 +0100643 MutexLock mu(Thread::Current(), *deoptimization_lock_);
644 CHECK_EQ(deoptimization_requests_.size(), 0U);
645 CHECK_EQ(full_deoptimization_event_count_, 0U);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100646 }
647
Ian Rogers62d6c772013-02-27 08:32:07 -0800648 Runtime* runtime = Runtime::Current();
649 runtime->GetThreadList()->SuspendAll();
650 Thread* self = Thread::Current();
651 ThreadState old_state = self->SetStateUnsafe(kRunnable);
652 CHECK_NE(old_state, kRunnable);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100653 runtime->GetInstrumentation()->EnableDeoptimization();
Ian Rogers62d6c772013-02-27 08:32:07 -0800654 runtime->GetInstrumentation()->AddListener(&gDebugInstrumentationListener,
655 instrumentation::Instrumentation::kMethodEntered |
656 instrumentation::Instrumentation::kMethodExited |
Jeff Hao14dd5a82013-04-11 10:23:36 -0700657 instrumentation::Instrumentation::kDexPcMoved |
658 instrumentation::Instrumentation::kExceptionCaught);
Elliott Hughesa2155262011-11-16 16:26:58 -0800659 gDebuggerActive = true;
Ian Rogers62d6c772013-02-27 08:32:07 -0800660 CHECK_EQ(self->SetStateUnsafe(old_state), kRunnable);
661 runtime->GetThreadList()->ResumeAll();
662
663 LOG(INFO) << "Debugger is active";
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700664}
665
666void Dbg::Disconnected() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700667 CHECK(gDebuggerConnected);
668
Elliott Hughesc0f09332012-03-26 13:27:06 -0700669 LOG(INFO) << "Debugger is no longer active";
Elliott Hughes234ab152011-10-26 14:02:26 -0700670
Ian Rogers62d6c772013-02-27 08:32:07 -0800671 // Suspend all threads and exclusively acquire the mutator lock. Set the state of the thread
672 // to kRunnable to avoid scoped object access transitions. Remove the debugger as a listener
673 // and clear the object registry.
674 Runtime* runtime = Runtime::Current();
675 runtime->GetThreadList()->SuspendAll();
676 Thread* self = Thread::Current();
677 ThreadState old_state = self->SetStateUnsafe(kRunnable);
Sebastien Hertzaaea7342014-02-25 15:10:04 +0100678
679 // Debugger may not be active at this point.
680 if (gDebuggerActive) {
681 {
682 // Since we're going to disable deoptimization, we clear the deoptimization requests queue.
683 // This prevents us from having any pending deoptimization request when the debugger attaches
684 // to us again while no event has been requested yet.
Sebastien Hertz4d25df32014-03-21 17:44:46 +0100685 MutexLock mu(Thread::Current(), *deoptimization_lock_);
686 deoptimization_requests_.clear();
687 full_deoptimization_event_count_ = 0U;
Sebastien Hertzaaea7342014-02-25 15:10:04 +0100688 }
689 runtime->GetInstrumentation()->RemoveListener(&gDebugInstrumentationListener,
690 instrumentation::Instrumentation::kMethodEntered |
691 instrumentation::Instrumentation::kMethodExited |
692 instrumentation::Instrumentation::kDexPcMoved |
693 instrumentation::Instrumentation::kExceptionCaught);
694 runtime->GetInstrumentation()->DisableDeoptimization();
695 gDebuggerActive = false;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100696 }
Elliott Hughes234ab152011-10-26 14:02:26 -0700697 gRegistry->Clear();
698 gDebuggerConnected = false;
Ian Rogers62d6c772013-02-27 08:32:07 -0800699 CHECK_EQ(self->SetStateUnsafe(old_state), kRunnable);
700 runtime->GetThreadList()->ResumeAll();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700701}
702
Elliott Hughesc0f09332012-03-26 13:27:06 -0700703bool Dbg::IsDebuggerActive() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700704 return gDebuggerActive;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700705}
706
Elliott Hughesc0f09332012-03-26 13:27:06 -0700707bool Dbg::IsJdwpConfigured() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700708 return gJdwpConfigured;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700709}
710
711int64_t Dbg::LastDebuggerActivity() {
Elliott Hughesca951522011-12-05 12:01:32 -0800712 return gJdwpState->LastDebuggerActivity();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700713}
714
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700715void Dbg::UndoDebuggerSuspensions() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700716 Runtime::Current()->GetThreadList()->UndoDebuggerSuspensions();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700717}
718
Elliott Hughes88d63092013-01-09 09:55:54 -0800719std::string Dbg::GetClassName(JDWP::RefTypeId class_id) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800720 mirror::Object* o = gRegistry->Get<mirror::Object*>(class_id);
Elliott Hughes436e3722012-02-17 20:01:47 -0800721 if (o == NULL) {
722 return "NULL";
723 }
Elliott Hughes64f574f2013-02-20 14:57:12 -0800724 if (o == ObjectRegistry::kInvalidObject) {
Elliott Hughes88d63092013-01-09 09:55:54 -0800725 return StringPrintf("invalid object %p", reinterpret_cast<void*>(class_id));
Elliott Hughes436e3722012-02-17 20:01:47 -0800726 }
727 if (!o->IsClass()) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700728 return StringPrintf("non-class %p", o); // This is only used for debugging output anyway.
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800729 }
Elliott Hughesc308a5d2012-02-16 17:12:06 -0800730 return DescriptorToName(ClassHelper(o->AsClass()).GetDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700731}
732
Elliott Hughes88d63092013-01-09 09:55:54 -0800733JDWP::JdwpError Dbg::GetClassObject(JDWP::RefTypeId id, JDWP::ObjectId& class_object_id) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800734 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800735 mirror::Class* c = DecodeClass(id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -0800736 if (c == NULL) {
737 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800738 }
Elliott Hughes88d63092013-01-09 09:55:54 -0800739 class_object_id = gRegistry->Add(c);
Elliott Hughes436e3722012-02-17 20:01:47 -0800740 return JDWP::ERR_NONE;
Elliott Hughes86964332012-02-15 19:37:42 -0800741}
742
Elliott Hughes88d63092013-01-09 09:55:54 -0800743JDWP::JdwpError Dbg::GetSuperclass(JDWP::RefTypeId id, JDWP::RefTypeId& superclass_id) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800744 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800745 mirror::Class* c = DecodeClass(id, status);
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800746 if (c == NULL) {
747 return status;
748 }
749 if (c->IsInterface()) {
750 // http://code.google.com/p/android/issues/detail?id=20856
Elliott Hughes88d63092013-01-09 09:55:54 -0800751 superclass_id = 0;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800752 } else {
Elliott Hughes88d63092013-01-09 09:55:54 -0800753 superclass_id = gRegistry->Add(c->GetSuperClass());
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800754 }
755 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700756}
757
Elliott Hughes436e3722012-02-17 20:01:47 -0800758JDWP::JdwpError Dbg::GetClassLoader(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800759 mirror::Object* o = gRegistry->Get<mirror::Object*>(id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800760 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800761 return JDWP::ERR_INVALID_OBJECT;
762 }
763 expandBufAddObjectId(pReply, gRegistry->Add(o->GetClass()->GetClassLoader()));
764 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700765}
766
Elliott Hughes436e3722012-02-17 20:01:47 -0800767JDWP::JdwpError Dbg::GetModifiers(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) {
768 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800769 mirror::Class* c = DecodeClass(id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -0800770 if (c == NULL) {
771 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800772 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800773
774 uint32_t access_flags = c->GetAccessFlags() & kAccJavaFlagsMask;
775
Yevgeny Roubande34eea2014-02-15 01:06:03 +0700776 // Set ACC_SUPER. Dex files don't contain this flag but only classes are supposed to have it set,
777 // not interfaces.
Elliott Hughes436e3722012-02-17 20:01:47 -0800778 // Class.getModifiers doesn't return it, but JDWP does, so we set it here.
Yevgeny Roubande34eea2014-02-15 01:06:03 +0700779 if ((access_flags & kAccInterface) == 0) {
780 access_flags |= kAccSuper;
781 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800782
783 expandBufAdd4BE(pReply, access_flags);
784
785 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700786}
787
Elliott Hughesf327e072013-01-09 16:01:26 -0800788JDWP::JdwpError Dbg::GetMonitorInfo(JDWP::ObjectId object_id, JDWP::ExpandBuf* reply)
789 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800790 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800791 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughesf327e072013-01-09 16:01:26 -0800792 return JDWP::ERR_INVALID_OBJECT;
793 }
794
795 // Ensure all threads are suspended while we read objects' lock words.
796 Thread* self = Thread::Current();
Sebastien Hertz54263242014-03-19 18:16:50 +0100797 CHECK_EQ(self->GetState(), kRunnable);
798 self->TransitionFromRunnableToSuspended(kSuspended);
799 Runtime::Current()->GetThreadList()->SuspendAll();
Elliott Hughesf327e072013-01-09 16:01:26 -0800800
801 MonitorInfo monitor_info(o);
802
Sebastien Hertz54263242014-03-19 18:16:50 +0100803 Runtime::Current()->GetThreadList()->ResumeAll();
804 self->TransitionFromSuspendedToRunnable();
Elliott Hughesf327e072013-01-09 16:01:26 -0800805
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700806 if (monitor_info.owner_ != NULL) {
807 expandBufAddObjectId(reply, gRegistry->Add(monitor_info.owner_->GetPeer()));
Elliott Hughesf327e072013-01-09 16:01:26 -0800808 } else {
809 expandBufAddObjectId(reply, gRegistry->Add(NULL));
810 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700811 expandBufAdd4BE(reply, monitor_info.entry_count_);
812 expandBufAdd4BE(reply, monitor_info.waiters_.size());
813 for (size_t i = 0; i < monitor_info.waiters_.size(); ++i) {
814 expandBufAddObjectId(reply, gRegistry->Add(monitor_info.waiters_[i]->GetPeer()));
Elliott Hughesf327e072013-01-09 16:01:26 -0800815 }
816 return JDWP::ERR_NONE;
817}
818
Elliott Hughes734b8c62013-01-11 15:32:45 -0800819JDWP::JdwpError Dbg::GetOwnedMonitors(JDWP::ObjectId thread_id,
820 std::vector<JDWP::ObjectId>& monitors,
Sebastien Hertz52d131d2014-03-13 16:17:40 +0100821 std::vector<uint32_t>& stack_depths) {
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800822 ScopedObjectAccessUnchecked soa(Thread::Current());
823 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
824 Thread* thread;
825 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
826 if (error != JDWP::ERR_NONE) {
827 return error;
828 }
829 if (!IsSuspendedForDebugger(soa, thread)) {
830 return JDWP::ERR_THREAD_NOT_SUSPENDED;
831 }
832
833 struct OwnedMonitorVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -0800834 OwnedMonitorVisitor(Thread* thread, Context* context)
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800835 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -0800836 : StackVisitor(thread, context), current_stack_depth(0) {}
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800837
838 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
839 // annotalysis.
840 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
841 if (!GetMethod()->IsRuntimeMethod()) {
842 Monitor::VisitLocks(this, AppendOwnedMonitors, this);
Elliott Hughes734b8c62013-01-11 15:32:45 -0800843 ++current_stack_depth;
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800844 }
845 return true;
846 }
847
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800848 static void AppendOwnedMonitors(mirror::Object* owned_monitor, void* arg) {
Ian Rogers7a22fa62013-01-23 12:16:16 -0800849 OwnedMonitorVisitor* visitor = reinterpret_cast<OwnedMonitorVisitor*>(arg);
Elliott Hughes734b8c62013-01-11 15:32:45 -0800850 visitor->monitors.push_back(owned_monitor);
851 visitor->stack_depths.push_back(visitor->current_stack_depth);
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800852 }
853
Elliott Hughes734b8c62013-01-11 15:32:45 -0800854 size_t current_stack_depth;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800855 std::vector<mirror::Object*> monitors;
Elliott Hughes734b8c62013-01-11 15:32:45 -0800856 std::vector<uint32_t> stack_depths;
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800857 };
Ian Rogers7a22fa62013-01-23 12:16:16 -0800858 UniquePtr<Context> context(Context::Create());
859 OwnedMonitorVisitor visitor(thread, context.get());
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800860 visitor.WalkStack();
861
862 for (size_t i = 0; i < visitor.monitors.size(); ++i) {
863 monitors.push_back(gRegistry->Add(visitor.monitors[i]));
Elliott Hughes734b8c62013-01-11 15:32:45 -0800864 stack_depths.push_back(visitor.stack_depths[i]);
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800865 }
866
867 return JDWP::ERR_NONE;
868}
869
Sebastien Hertz52d131d2014-03-13 16:17:40 +0100870JDWP::JdwpError Dbg::GetContendedMonitor(JDWP::ObjectId thread_id,
871 JDWP::ObjectId& contended_monitor) {
Elliott Hughesf9501702013-01-11 11:22:27 -0800872 ScopedObjectAccessUnchecked soa(Thread::Current());
873 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
874 Thread* thread;
875 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
876 if (error != JDWP::ERR_NONE) {
877 return error;
878 }
879 if (!IsSuspendedForDebugger(soa, thread)) {
880 return JDWP::ERR_THREAD_NOT_SUSPENDED;
881 }
882
883 contended_monitor = gRegistry->Add(Monitor::GetContendedMonitor(thread));
884
885 return JDWP::ERR_NONE;
886}
887
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800888JDWP::JdwpError Dbg::GetInstanceCounts(const std::vector<JDWP::RefTypeId>& class_ids,
889 std::vector<uint64_t>& counts)
890 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800891 gc::Heap* heap = Runtime::Current()->GetHeap();
892 heap->CollectGarbage(false);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800893 std::vector<mirror::Class*> classes;
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800894 counts.clear();
895 for (size_t i = 0; i < class_ids.size(); ++i) {
896 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800897 mirror::Class* c = DecodeClass(class_ids[i], status);
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800898 if (c == NULL) {
899 return status;
900 }
901 classes.push_back(c);
902 counts.push_back(0);
903 }
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800904 heap->CountInstances(classes, false, &counts[0]);
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800905 return JDWP::ERR_NONE;
906}
907
Elliott Hughes3b78c942013-01-15 17:35:41 -0800908JDWP::JdwpError Dbg::GetInstances(JDWP::RefTypeId class_id, int32_t max_count, std::vector<JDWP::ObjectId>& instances)
909 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800910 gc::Heap* heap = Runtime::Current()->GetHeap();
911 // We only want reachable instances, so do a GC.
912 heap->CollectGarbage(false);
Elliott Hughes3b78c942013-01-15 17:35:41 -0800913 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800914 mirror::Class* c = DecodeClass(class_id, status);
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800915 if (c == nullptr) {
Elliott Hughes3b78c942013-01-15 17:35:41 -0800916 return status;
917 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800918 std::vector<mirror::Object*> raw_instances;
Elliott Hughes3b78c942013-01-15 17:35:41 -0800919 Runtime::Current()->GetHeap()->GetInstances(c, max_count, raw_instances);
920 for (size_t i = 0; i < raw_instances.size(); ++i) {
921 instances.push_back(gRegistry->Add(raw_instances[i]));
922 }
923 return JDWP::ERR_NONE;
924}
925
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800926JDWP::JdwpError Dbg::GetReferringObjects(JDWP::ObjectId object_id, int32_t max_count,
927 std::vector<JDWP::ObjectId>& referring_objects)
928 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800929 gc::Heap* heap = Runtime::Current()->GetHeap();
930 heap->CollectGarbage(false);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800931 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800932 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800933 return JDWP::ERR_INVALID_OBJECT;
934 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800935 std::vector<mirror::Object*> raw_instances;
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800936 heap->GetReferringObjects(o, max_count, raw_instances);
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800937 for (size_t i = 0; i < raw_instances.size(); ++i) {
938 referring_objects.push_back(gRegistry->Add(raw_instances[i]));
939 }
940 return JDWP::ERR_NONE;
941}
942
Elliott Hughes64f574f2013-02-20 14:57:12 -0800943JDWP::JdwpError Dbg::DisableCollection(JDWP::ObjectId object_id)
944 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Sebastien Hertze96060a2013-12-11 12:06:28 +0100945 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
946 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
947 return JDWP::ERR_INVALID_OBJECT;
948 }
Elliott Hughes64f574f2013-02-20 14:57:12 -0800949 gRegistry->DisableCollection(object_id);
950 return JDWP::ERR_NONE;
951}
952
953JDWP::JdwpError Dbg::EnableCollection(JDWP::ObjectId object_id)
954 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Sebastien Hertze96060a2013-12-11 12:06:28 +0100955 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
956 // Unlike DisableCollection, JDWP specs do not state an invalid object causes an error. The RI
957 // also ignores these cases and never return an error. However it's not obvious why this command
958 // should behave differently from DisableCollection and IsCollected commands. So let's be more
959 // strict and return an error if this happens.
960 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
961 return JDWP::ERR_INVALID_OBJECT;
962 }
Elliott Hughes64f574f2013-02-20 14:57:12 -0800963 gRegistry->EnableCollection(object_id);
964 return JDWP::ERR_NONE;
965}
966
967JDWP::JdwpError Dbg::IsCollected(JDWP::ObjectId object_id, bool& is_collected)
968 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Sebastien Hertz65637eb2014-01-10 17:40:02 +0100969 if (object_id == 0) {
970 // Null object id is invalid.
Sebastien Hertze96060a2013-12-11 12:06:28 +0100971 return JDWP::ERR_INVALID_OBJECT;
972 }
Sebastien Hertz65637eb2014-01-10 17:40:02 +0100973 // JDWP specs state an INVALID_OBJECT error is returned if the object ID is not valid. However
974 // the RI seems to ignore this and assume object has been collected.
975 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
976 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
977 is_collected = true;
978 } else {
979 is_collected = gRegistry->IsCollected(object_id);
980 }
Elliott Hughes64f574f2013-02-20 14:57:12 -0800981 return JDWP::ERR_NONE;
982}
983
984void Dbg::DisposeObject(JDWP::ObjectId object_id, uint32_t reference_count)
985 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
986 gRegistry->DisposeObject(object_id, reference_count);
987}
988
Sebastien Hertz4d8fd492014-03-28 16:29:41 +0100989static JDWP::JdwpTypeTag GetTypeTag(mirror::Class* klass)
990 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
991 DCHECK(klass != nullptr);
992 if (klass->IsArrayClass()) {
993 return JDWP::TT_ARRAY;
994 } else if (klass->IsInterface()) {
995 return JDWP::TT_INTERFACE;
996 } else {
997 return JDWP::TT_CLASS;
998 }
999}
1000
Elliott Hughes88d63092013-01-09 09:55:54 -08001001JDWP::JdwpError Dbg::GetReflectedType(JDWP::RefTypeId class_id, JDWP::ExpandBuf* pReply) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001002 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001003 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001004 if (c == NULL) {
1005 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001006 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001007
Sebastien Hertz4d8fd492014-03-28 16:29:41 +01001008 JDWP::JdwpTypeTag type_tag = GetTypeTag(c);
1009 expandBufAdd1(pReply, type_tag);
Elliott Hughes88d63092013-01-09 09:55:54 -08001010 expandBufAddRefTypeId(pReply, class_id);
Elliott Hughes436e3722012-02-17 20:01:47 -08001011 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001012}
1013
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001014void Dbg::GetClassList(std::vector<JDWP::RefTypeId>& classes) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001015 // Get the complete list of reference classes (i.e. all classes except
1016 // the primitive types).
1017 // Returns a newly-allocated buffer full of RefTypeId values.
1018 struct ClassListCreator {
Elliott Hughesba8eee12012-01-24 20:25:24 -08001019 explicit ClassListCreator(std::vector<JDWP::RefTypeId>& classes) : classes(classes) {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001020 }
1021
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001022 static bool Visit(mirror::Class* c, void* arg) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001023 return reinterpret_cast<ClassListCreator*>(arg)->Visit(c);
1024 }
1025
Elliott Hughes64f574f2013-02-20 14:57:12 -08001026 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1027 // annotalysis.
1028 bool Visit(mirror::Class* c) NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughesa2155262011-11-16 16:26:58 -08001029 if (!c->IsPrimitive()) {
Elliott Hughes64f574f2013-02-20 14:57:12 -08001030 classes.push_back(gRegistry->AddRefType(c));
Elliott Hughesa2155262011-11-16 16:26:58 -08001031 }
1032 return true;
1033 }
1034
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001035 std::vector<JDWP::RefTypeId>& classes;
Elliott Hughesa2155262011-11-16 16:26:58 -08001036 };
1037
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001038 ClassListCreator clc(classes);
Elliott Hughesa2155262011-11-16 16:26:58 -08001039 Runtime::Current()->GetClassLinker()->VisitClasses(ClassListCreator::Visit, &clc);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001040}
1041
Elliott Hughes88d63092013-01-09 09:55:54 -08001042JDWP::JdwpError Dbg::GetClassInfo(JDWP::RefTypeId class_id, JDWP::JdwpTypeTag* pTypeTag, uint32_t* pStatus, std::string* pDescriptor) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001043 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001044 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001045 if (c == NULL) {
1046 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001047 }
1048
Elliott Hughesa2155262011-11-16 16:26:58 -08001049 if (c->IsArrayClass()) {
1050 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
1051 *pTypeTag = JDWP::TT_ARRAY;
1052 } else {
1053 if (c->IsErroneous()) {
1054 *pStatus = JDWP::CS_ERROR;
1055 } else {
1056 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED | JDWP::CS_INITIALIZED;
1057 }
1058 *pTypeTag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
1059 }
1060
1061 if (pDescriptor != NULL) {
Ian Rogersdfb325e2013-10-30 01:00:44 -07001062 *pDescriptor = ClassHelper(c).GetDescriptor();
Elliott Hughesa2155262011-11-16 16:26:58 -08001063 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001064 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001065}
1066
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001067void Dbg::FindLoadedClassBySignature(const char* descriptor, std::vector<JDWP::RefTypeId>& ids) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001068 std::vector<mirror::Class*> classes;
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001069 Runtime::Current()->GetClassLinker()->LookupClasses(descriptor, classes);
1070 ids.clear();
1071 for (size_t i = 0; i < classes.size(); ++i) {
1072 ids.push_back(gRegistry->Add(classes[i]));
1073 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001074}
1075
Elliott Hughes64f574f2013-02-20 14:57:12 -08001076JDWP::JdwpError Dbg::GetReferenceType(JDWP::ObjectId object_id, JDWP::ExpandBuf* pReply)
1077 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001078 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001079 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001080 return JDWP::ERR_INVALID_OBJECT;
Elliott Hughes499c5132011-11-17 14:55:11 -08001081 }
Elliott Hughes2435a572012-02-17 16:07:41 -08001082
Sebastien Hertz4d8fd492014-03-28 16:29:41 +01001083 JDWP::JdwpTypeTag type_tag = GetTypeTag(o->GetClass());
Elliott Hughes64f574f2013-02-20 14:57:12 -08001084 JDWP::RefTypeId type_id = gRegistry->AddRefType(o->GetClass());
Elliott Hughes2435a572012-02-17 16:07:41 -08001085
1086 expandBufAdd1(pReply, type_tag);
1087 expandBufAddRefTypeId(pReply, type_id);
1088
1089 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001090}
1091
Ian Rogersfc0e94b2013-09-23 23:51:32 -07001092JDWP::JdwpError Dbg::GetSignature(JDWP::RefTypeId class_id, std::string* signature) {
Elliott Hughes1fe7afb2012-02-13 17:23:03 -08001093 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001094 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes1fe7afb2012-02-13 17:23:03 -08001095 if (c == NULL) {
1096 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001097 }
Ian Rogersdfb325e2013-10-30 01:00:44 -07001098 *signature = ClassHelper(c).GetDescriptor();
Elliott Hughes1fe7afb2012-02-13 17:23:03 -08001099 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001100}
1101
Elliott Hughes88d63092013-01-09 09:55:54 -08001102JDWP::JdwpError Dbg::GetSourceFile(JDWP::RefTypeId class_id, std::string& result) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001103 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001104 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001105 if (c == NULL) {
1106 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001107 }
Sebastien Hertzb7054ba2014-03-13 11:52:31 +01001108 if (c->IsProxyClass()) {
1109 return JDWP::ERR_ABSENT_INFORMATION;
1110 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001111 result = ClassHelper(c).GetSourceFile();
1112 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001113}
1114
Elliott Hughes88d63092013-01-09 09:55:54 -08001115JDWP::JdwpError Dbg::GetObjectTag(JDWP::ObjectId object_id, uint8_t& tag) {
Ian Rogers98379392014-02-24 16:53:16 -08001116 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001117 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001118 if (o == ObjectRegistry::kInvalidObject) {
Elliott Hughes546b9862012-06-20 16:06:13 -07001119 return JDWP::ERR_INVALID_OBJECT;
1120 }
Ian Rogers98379392014-02-24 16:53:16 -08001121 tag = TagFromObject(soa, o);
Elliott Hughes546b9862012-06-20 16:06:13 -07001122 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001123}
1124
Elliott Hughesaed4be92011-12-02 16:16:23 -08001125size_t Dbg::GetTagWidth(JDWP::JdwpTag tag) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001126 switch (tag) {
1127 case JDWP::JT_VOID:
1128 return 0;
1129 case JDWP::JT_BYTE:
1130 case JDWP::JT_BOOLEAN:
1131 return 1;
1132 case JDWP::JT_CHAR:
1133 case JDWP::JT_SHORT:
1134 return 2;
1135 case JDWP::JT_FLOAT:
1136 case JDWP::JT_INT:
1137 return 4;
1138 case JDWP::JT_ARRAY:
1139 case JDWP::JT_OBJECT:
1140 case JDWP::JT_STRING:
1141 case JDWP::JT_THREAD:
1142 case JDWP::JT_THREAD_GROUP:
1143 case JDWP::JT_CLASS_LOADER:
1144 case JDWP::JT_CLASS_OBJECT:
1145 return sizeof(JDWP::ObjectId);
1146 case JDWP::JT_DOUBLE:
1147 case JDWP::JT_LONG:
1148 return 8;
1149 default:
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001150 LOG(FATAL) << "Unknown tag " << tag;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001151 return -1;
1152 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001153}
1154
Elliott Hughes88d63092013-01-09 09:55:54 -08001155JDWP::JdwpError Dbg::GetArrayLength(JDWP::ObjectId array_id, int& length) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001156 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001157 mirror::Array* a = DecodeArray(array_id, status);
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001158 if (a == NULL) {
1159 return status;
Elliott Hughes24437992011-11-30 14:49:33 -08001160 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001161 length = a->GetLength();
1162 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001163}
1164
Elliott Hughes88d63092013-01-09 09:55:54 -08001165JDWP::JdwpError Dbg::OutputArray(JDWP::ObjectId array_id, int offset, int count, JDWP::ExpandBuf* pReply) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001166 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001167 mirror::Array* a = DecodeArray(array_id, status);
Ian Rogers98379392014-02-24 16:53:16 -08001168 if (a == nullptr) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001169 return status;
1170 }
Elliott Hughes24437992011-11-30 14:49:33 -08001171
1172 if (offset < 0 || count < 0 || offset > a->GetLength() || a->GetLength() - offset < count) {
1173 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001174 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughes24437992011-11-30 14:49:33 -08001175 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001176 std::string descriptor(ClassHelper(a->GetClass()).GetDescriptor());
Elliott Hughes24437992011-11-30 14:49:33 -08001177 JDWP::JdwpTag tag = BasicTagFromDescriptor(descriptor.c_str() + 1);
1178
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001179 expandBufAdd1(pReply, tag);
1180 expandBufAdd4BE(pReply, count);
1181
Elliott Hughes24437992011-11-30 14:49:33 -08001182 if (IsPrimitiveTag(tag)) {
1183 size_t width = GetTagWidth(tag);
Elliott Hughes24437992011-11-30 14:49:33 -08001184 uint8_t* dst = expandBufAddSpace(pReply, count * width);
1185 if (width == 8) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001186 const uint64_t* src8 = reinterpret_cast<uint64_t*>(a->GetRawData(sizeof(uint64_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001187 for (int i = 0; i < count; ++i) JDWP::Write8BE(&dst, src8[offset + i]);
1188 } else if (width == 4) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001189 const uint32_t* src4 = reinterpret_cast<uint32_t*>(a->GetRawData(sizeof(uint32_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001190 for (int i = 0; i < count; ++i) JDWP::Write4BE(&dst, src4[offset + i]);
1191 } else if (width == 2) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001192 const uint16_t* src2 = reinterpret_cast<uint16_t*>(a->GetRawData(sizeof(uint16_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001193 for (int i = 0; i < count; ++i) JDWP::Write2BE(&dst, src2[offset + i]);
1194 } else {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001195 const uint8_t* src = reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint8_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001196 memcpy(dst, &src[offset * width], count * width);
1197 }
1198 } else {
Ian Rogers98379392014-02-24 16:53:16 -08001199 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001200 mirror::ObjectArray<mirror::Object>* oa = a->AsObjectArray<mirror::Object>();
Elliott Hughes24437992011-11-30 14:49:33 -08001201 for (int i = 0; i < count; ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001202 mirror::Object* element = oa->Get(offset + i);
Ian Rogers98379392014-02-24 16:53:16 -08001203 JDWP::JdwpTag specific_tag = (element != nullptr) ? TagFromObject(soa, element)
1204 : tag;
Elliott Hughes24437992011-11-30 14:49:33 -08001205 expandBufAdd1(pReply, specific_tag);
1206 expandBufAddObjectId(pReply, gRegistry->Add(element));
1207 }
1208 }
1209
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001210 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001211}
1212
Ian Rogersef7d42f2014-01-06 12:55:46 -08001213template <typename T>
1214static void CopyArrayData(mirror::Array* a, JDWP::Request& src, int offset, int count)
1215 NO_THREAD_SAFETY_ANALYSIS {
1216 // TODO: fix when annotalysis correctly handles non-member functions.
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001217 DCHECK(a->GetClass()->IsPrimitiveArray());
1218
Ian Rogersef7d42f2014-01-06 12:55:46 -08001219 T* dst = reinterpret_cast<T*>(a->GetRawData(sizeof(T), offset));
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001220 for (int i = 0; i < count; ++i) {
1221 *dst++ = src.ReadValue(sizeof(T));
1222 }
1223}
1224
Elliott Hughes88d63092013-01-09 09:55:54 -08001225JDWP::JdwpError Dbg::SetArrayElements(JDWP::ObjectId array_id, int offset, int count,
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001226 JDWP::Request& request)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001227 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001228 JDWP::JdwpError status;
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001229 mirror::Array* dst = DecodeArray(array_id, status);
1230 if (dst == NULL) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001231 return status;
1232 }
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001233
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001234 if (offset < 0 || count < 0 || offset > dst->GetLength() || dst->GetLength() - offset < count) {
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001235 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001236 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001237 }
nikolay serdjuk1d66e882014-04-07 13:54:24 +07001238 ClassHelper ch(dst->GetClass());
1239 const char* descriptor = ch.GetDescriptor();
Ian Rogersfc0e94b2013-09-23 23:51:32 -07001240 JDWP::JdwpTag tag = BasicTagFromDescriptor(descriptor + 1);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001241
1242 if (IsPrimitiveTag(tag)) {
1243 size_t width = GetTagWidth(tag);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001244 if (width == 8) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001245 CopyArrayData<uint64_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001246 } else if (width == 4) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001247 CopyArrayData<uint32_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001248 } else if (width == 2) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001249 CopyArrayData<uint16_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001250 } else {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001251 CopyArrayData<uint8_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001252 }
1253 } else {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001254 mirror::ObjectArray<mirror::Object>* oa = dst->AsObjectArray<mirror::Object>();
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001255 for (int i = 0; i < count; ++i) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001256 JDWP::ObjectId id = request.ReadObjectId();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001257 mirror::Object* o = gRegistry->Get<mirror::Object*>(id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001258 if (o == ObjectRegistry::kInvalidObject) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001259 return JDWP::ERR_INVALID_OBJECT;
1260 }
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001261 oa->Set<false>(offset + i, o);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001262 }
1263 }
1264
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001265 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001266}
1267
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001268JDWP::ObjectId Dbg::CreateString(const std::string& str) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001269 return gRegistry->Add(mirror::String::AllocFromModifiedUtf8(Thread::Current(), str.c_str()));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001270}
1271
Elliott Hughes88d63092013-01-09 09:55:54 -08001272JDWP::JdwpError Dbg::CreateObject(JDWP::RefTypeId class_id, JDWP::ObjectId& new_object) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001273 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001274 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001275 if (c == NULL) {
1276 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001277 }
Ian Rogers50b35e22012-10-04 10:09:15 -07001278 new_object = gRegistry->Add(c->AllocObject(Thread::Current()));
Elliott Hughes436e3722012-02-17 20:01:47 -08001279 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001280}
1281
Elliott Hughesbf13d362011-12-08 15:51:37 -08001282/*
1283 * Used by Eclipse's "Display" view to evaluate "new byte[5]" to get "(byte[]) [0, 0, 0, 0, 0]".
1284 */
Elliott Hughes88d63092013-01-09 09:55:54 -08001285JDWP::JdwpError Dbg::CreateArrayObject(JDWP::RefTypeId array_class_id, uint32_t length,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001286 JDWP::ObjectId& new_array) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001287 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001288 mirror::Class* c = DecodeClass(array_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 Rogers6fac4472014-02-25 17:01:10 -08001292 new_array = gRegistry->Add(mirror::Array::Alloc<true>(Thread::Current(), c, length,
1293 c->GetComponentSize(),
1294 Runtime::Current()->GetHeap()->GetCurrentAllocator()));
Elliott Hughes436e3722012-02-17 20:01:47 -08001295 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001296}
1297
Elliott Hughes88d63092013-01-09 09:55:54 -08001298bool Dbg::MatchType(JDWP::RefTypeId instance_class_id, JDWP::RefTypeId class_id) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001299 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001300 mirror::Class* c1 = DecodeClass(instance_class_id, status);
Elliott Hughesa656a0f2012-02-21 18:03:44 -08001301 CHECK(c1 != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001302 mirror::Class* c2 = DecodeClass(class_id, status);
Elliott Hughesa656a0f2012-02-21 18:03:44 -08001303 CHECK(c2 != NULL);
Sebastien Hertz123756a2013-11-27 15:49:42 +01001304 return c2->IsAssignableFrom(c1);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001305}
1306
Brian Carlstromea46f952013-07-30 01:26:50 -07001307static JDWP::FieldId ToFieldId(const mirror::ArtField* f)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001308 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001309 CHECK(!kMovingFields);
Elliott Hughes03181a82011-11-17 17:22:21 -08001310 return static_cast<JDWP::FieldId>(reinterpret_cast<uintptr_t>(f));
Elliott Hughes03181a82011-11-17 17:22:21 -08001311}
1312
Brian Carlstromea46f952013-07-30 01:26:50 -07001313static JDWP::MethodId ToMethodId(const mirror::ArtMethod* m)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001314 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001315 CHECK(!kMovingMethods);
Elliott Hughes03181a82011-11-17 17:22:21 -08001316 return static_cast<JDWP::MethodId>(reinterpret_cast<uintptr_t>(m));
Elliott Hughes03181a82011-11-17 17:22:21 -08001317}
1318
Brian Carlstromea46f952013-07-30 01:26:50 -07001319static mirror::ArtField* FromFieldId(JDWP::FieldId fid)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001320 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001321 CHECK(!kMovingFields);
Brian Carlstromea46f952013-07-30 01:26:50 -07001322 return reinterpret_cast<mirror::ArtField*>(static_cast<uintptr_t>(fid));
Elliott Hughesaed4be92011-12-02 16:16:23 -08001323}
1324
Brian Carlstromea46f952013-07-30 01:26:50 -07001325static mirror::ArtMethod* FromMethodId(JDWP::MethodId mid)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001326 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001327 CHECK(!kMovingMethods);
Brian Carlstromea46f952013-07-30 01:26:50 -07001328 return reinterpret_cast<mirror::ArtMethod*>(static_cast<uintptr_t>(mid));
Elliott Hughes03181a82011-11-17 17:22:21 -08001329}
1330
Brian Carlstromea46f952013-07-30 01:26:50 -07001331static void SetLocation(JDWP::JdwpLocation& location, mirror::ArtMethod* m, uint32_t dex_pc)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001332 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001333 if (m == NULL) {
1334 memset(&location, 0, sizeof(location));
1335 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001336 mirror::Class* c = m->GetDeclaringClass();
Sebastien Hertz4d8fd492014-03-28 16:29:41 +01001337 location.type_tag = GetTypeTag(c);
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001338 location.class_id = gRegistry->AddRefType(c);
Elliott Hughes74847412012-06-20 18:10:21 -07001339 location.method_id = ToMethodId(m);
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001340 location.dex_pc = (m->IsNative() || m->IsProxyMethod()) ? static_cast<uint64_t>(-1) : dex_pc;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001341 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08001342}
1343
Elliott Hughesa96836a2013-01-17 12:27:49 -08001344std::string Dbg::GetMethodName(JDWP::MethodId method_id)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001345 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001346 mirror::ArtMethod* m = FromMethodId(method_id);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001347 return MethodHelper(m).GetName();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001348}
1349
Elliott Hughesa96836a2013-01-17 12:27:49 -08001350std::string Dbg::GetFieldName(JDWP::FieldId field_id)
1351 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001352 mirror::ArtField* f = FromFieldId(field_id);
Elliott Hughesa96836a2013-01-17 12:27:49 -08001353 return FieldHelper(f).GetName();
1354}
1355
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001356/*
1357 * Augment the access flags for synthetic methods and fields by setting
1358 * the (as described by the spec) "0xf0000000 bit". Also, strip out any
1359 * flags not specified by the Java programming language.
1360 */
1361static uint32_t MangleAccessFlags(uint32_t accessFlags) {
1362 accessFlags &= kAccJavaFlagsMask;
1363 if ((accessFlags & kAccSynthetic) != 0) {
1364 accessFlags |= 0xf0000000;
1365 }
1366 return accessFlags;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001367}
1368
Elliott Hughesdbb40792011-11-18 17:05:22 -08001369/*
Jeff Haob7cefc72013-11-14 14:51:09 -08001370 * Circularly shifts registers so that arguments come first. Debuggers
1371 * expect slots to begin with arguments, but dex code places them at
1372 * the end.
Elliott Hughesdbb40792011-11-18 17:05:22 -08001373 */
Jeff Haob7cefc72013-11-14 14:51:09 -08001374static uint16_t MangleSlot(uint16_t slot, mirror::ArtMethod* m)
1375 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1376 const DexFile::CodeItem* code_item = MethodHelper(m).GetCodeItem();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001377 if (code_item == nullptr) {
1378 // We should not get here for a method without code (native, proxy or abstract). Log it and
1379 // return the slot as is since all registers are arguments.
1380 LOG(WARNING) << "Trying to mangle slot for method without code " << PrettyMethod(m);
1381 return slot;
1382 }
Jeff Haob7cefc72013-11-14 14:51:09 -08001383 uint16_t ins_size = code_item->ins_size_;
1384 uint16_t locals_size = code_item->registers_size_ - ins_size;
1385 if (slot >= locals_size) {
1386 return slot - locals_size;
1387 } else {
1388 return slot + ins_size;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001389 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001390}
1391
Jeff Haob7cefc72013-11-14 14:51:09 -08001392/*
1393 * Circularly shifts registers so that arguments come last. Reverts
1394 * slots to dex style argument placement.
1395 */
Brian Carlstromea46f952013-07-30 01:26:50 -07001396static uint16_t DemangleSlot(uint16_t slot, mirror::ArtMethod* m)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001397 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Jeff Haob7cefc72013-11-14 14:51:09 -08001398 const DexFile::CodeItem* code_item = MethodHelper(m).GetCodeItem();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001399 if (code_item == nullptr) {
1400 // We should not get here for a method without code (native, proxy or abstract). Log it and
1401 // return the slot as is since all registers are arguments.
1402 LOG(WARNING) << "Trying to demangle slot for method without code " << PrettyMethod(m);
1403 return slot;
1404 }
Jeff Haob7cefc72013-11-14 14:51:09 -08001405 uint16_t ins_size = code_item->ins_size_;
1406 uint16_t locals_size = code_item->registers_size_ - ins_size;
1407 if (slot < ins_size) {
1408 return slot + locals_size;
1409 } else {
1410 return slot - ins_size;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001411 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001412}
1413
Elliott Hughes88d63092013-01-09 09:55:54 -08001414JDWP::JdwpError Dbg::OutputDeclaredFields(JDWP::RefTypeId class_id, bool with_generic, JDWP::ExpandBuf* pReply) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001415 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001416 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001417 if (c == NULL) {
1418 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001419 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001420
1421 size_t instance_field_count = c->NumInstanceFields();
1422 size_t static_field_count = c->NumStaticFields();
1423
1424 expandBufAdd4BE(pReply, instance_field_count + static_field_count);
1425
1426 for (size_t i = 0; i < instance_field_count + static_field_count; ++i) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001427 mirror::ArtField* f = (i < instance_field_count) ? c->GetInstanceField(i) : c->GetStaticField(i - instance_field_count);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001428 FieldHelper fh(f);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001429 expandBufAddFieldId(pReply, ToFieldId(f));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001430 expandBufAddUtf8String(pReply, fh.GetName());
1431 expandBufAddUtf8String(pReply, fh.GetTypeDescriptor());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001432 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001433 static const char genericSignature[1] = "";
1434 expandBufAddUtf8String(pReply, genericSignature);
1435 }
1436 expandBufAdd4BE(pReply, MangleAccessFlags(f->GetAccessFlags()));
1437 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001438 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001439}
1440
Elliott Hughes88d63092013-01-09 09:55:54 -08001441JDWP::JdwpError Dbg::OutputDeclaredMethods(JDWP::RefTypeId class_id, bool with_generic,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001442 JDWP::ExpandBuf* pReply) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001443 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001444 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001445 if (c == NULL) {
1446 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001447 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001448
1449 size_t direct_method_count = c->NumDirectMethods();
1450 size_t virtual_method_count = c->NumVirtualMethods();
1451
1452 expandBufAdd4BE(pReply, direct_method_count + virtual_method_count);
1453
1454 for (size_t i = 0; i < direct_method_count + virtual_method_count; ++i) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001455 mirror::ArtMethod* m = (i < direct_method_count) ? c->GetDirectMethod(i) : c->GetVirtualMethod(i - direct_method_count);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001456 MethodHelper mh(m);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001457 expandBufAddMethodId(pReply, ToMethodId(m));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001458 expandBufAddUtf8String(pReply, mh.GetName());
Ian Rogersd91d6d62013-09-25 20:26:14 -07001459 expandBufAddUtf8String(pReply, mh.GetSignature().ToString());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001460 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001461 static const char genericSignature[1] = "";
1462 expandBufAddUtf8String(pReply, genericSignature);
1463 }
1464 expandBufAdd4BE(pReply, MangleAccessFlags(m->GetAccessFlags()));
1465 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001466 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001467}
1468
Elliott Hughes88d63092013-01-09 09:55:54 -08001469JDWP::JdwpError Dbg::OutputDeclaredInterfaces(JDWP::RefTypeId class_id, JDWP::ExpandBuf* pReply) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001470 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001471 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001472 if (c == NULL) {
1473 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001474 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001475
1476 ClassHelper kh(c);
Ian Rogersd24e2642012-06-06 21:21:43 -07001477 size_t interface_count = kh.NumDirectInterfaces();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001478 expandBufAdd4BE(pReply, interface_count);
1479 for (size_t i = 0; i < interface_count; ++i) {
Elliott Hughes64f574f2013-02-20 14:57:12 -08001480 expandBufAddRefTypeId(pReply, gRegistry->AddRefType(kh.GetDirectInterface(i)));
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001481 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001482 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001483}
1484
Elliott Hughes88d63092013-01-09 09:55:54 -08001485void Dbg::OutputLineTable(JDWP::RefTypeId, JDWP::MethodId method_id, JDWP::ExpandBuf* pReply)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001486 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001487 struct DebugCallbackContext {
1488 int numItems;
1489 JDWP::ExpandBuf* pReply;
1490
Elliott Hughes2435a572012-02-17 16:07:41 -08001491 static bool Callback(void* context, uint32_t address, uint32_t line_number) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001492 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
1493 expandBufAdd8BE(pContext->pReply, address);
Elliott Hughes2435a572012-02-17 16:07:41 -08001494 expandBufAdd4BE(pContext->pReply, line_number);
Elliott Hughes03181a82011-11-17 17:22:21 -08001495 pContext->numItems++;
Sebastien Hertzf2910ee2013-10-19 16:39:24 +02001496 return false;
Elliott Hughes03181a82011-11-17 17:22:21 -08001497 }
1498 };
Brian Carlstromea46f952013-07-30 01:26:50 -07001499 mirror::ArtMethod* m = FromMethodId(method_id);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001500 MethodHelper mh(m);
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001501 const DexFile::CodeItem* code_item = mh.GetCodeItem();
Elliott Hughes03181a82011-11-17 17:22:21 -08001502 uint64_t start, end;
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001503 if (code_item == nullptr) {
1504 DCHECK(m->IsNative() || m->IsProxyMethod());
Elliott Hughes03181a82011-11-17 17:22:21 -08001505 start = -1;
1506 end = -1;
1507 } else {
1508 start = 0;
jeffhao14f0db92012-12-14 17:50:42 -08001509 // Return the index of the last instruction
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001510 end = code_item->insns_size_in_code_units_ - 1;
Elliott Hughes03181a82011-11-17 17:22:21 -08001511 }
1512
1513 expandBufAdd8BE(pReply, start);
1514 expandBufAdd8BE(pReply, end);
1515
1516 // Add numLines later
1517 size_t numLinesOffset = expandBufGetLength(pReply);
1518 expandBufAdd4BE(pReply, 0);
1519
1520 DebugCallbackContext context;
1521 context.numItems = 0;
1522 context.pReply = pReply;
1523
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001524 if (code_item != nullptr) {
1525 mh.GetDexFile().DecodeDebugInfo(code_item, m->IsStatic(), m->GetDexMethodIndex(),
1526 DebugCallbackContext::Callback, NULL, &context);
1527 }
Elliott Hughes03181a82011-11-17 17:22:21 -08001528
1529 JDWP::Set4BE(expandBufGetBuffer(pReply) + numLinesOffset, context.numItems);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001530}
1531
Elliott Hughes88d63092013-01-09 09:55:54 -08001532void Dbg::OutputVariableTable(JDWP::RefTypeId, JDWP::MethodId method_id, bool with_generic, JDWP::ExpandBuf* pReply) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001533 struct DebugCallbackContext {
Jeff Haob7cefc72013-11-14 14:51:09 -08001534 mirror::ArtMethod* method;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001535 JDWP::ExpandBuf* pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001536 size_t variable_count;
1537 bool with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001538
Jeff Haob7cefc72013-11-14 14:51:09 -08001539 static void Callback(void* context, uint16_t slot, uint32_t startAddress, uint32_t endAddress, const char* name, const char* descriptor, const char* signature)
1540 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001541 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
1542
Jeff Haob7cefc72013-11-14 14:51:09 -08001543 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 -08001544
Jeff Haob7cefc72013-11-14 14:51:09 -08001545 slot = MangleSlot(slot, pContext->method);
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001546
Elliott Hughesdbb40792011-11-18 17:05:22 -08001547 expandBufAdd8BE(pContext->pReply, startAddress);
1548 expandBufAddUtf8String(pContext->pReply, name);
1549 expandBufAddUtf8String(pContext->pReply, descriptor);
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001550 if (pContext->with_generic) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001551 expandBufAddUtf8String(pContext->pReply, signature);
1552 }
1553 expandBufAdd4BE(pContext->pReply, endAddress - startAddress);
1554 expandBufAdd4BE(pContext->pReply, slot);
1555
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001556 ++pContext->variable_count;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001557 }
1558 };
Brian Carlstromea46f952013-07-30 01:26:50 -07001559 mirror::ArtMethod* m = FromMethodId(method_id);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001560 MethodHelper mh(m);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001561
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001562 // arg_count considers doubles and longs to take 2 units.
1563 // variable_count considers everything to take 1 unit.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001564 std::string shorty(mh.GetShorty());
Brian Carlstromea46f952013-07-30 01:26:50 -07001565 expandBufAdd4BE(pReply, mirror::ArtMethod::NumArgRegisters(shorty));
Elliott Hughesdbb40792011-11-18 17:05:22 -08001566
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001567 // We don't know the total number of variables yet, so leave a blank and update it later.
1568 size_t variable_count_offset = expandBufGetLength(pReply);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001569 expandBufAdd4BE(pReply, 0);
1570
1571 DebugCallbackContext context;
Jeff Haob7cefc72013-11-14 14:51:09 -08001572 context.method = m;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001573 context.pReply = pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001574 context.variable_count = 0;
1575 context.with_generic = with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001576
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001577 const DexFile::CodeItem* code_item = mh.GetCodeItem();
1578 if (code_item != nullptr) {
1579 mh.GetDexFile().DecodeDebugInfo(code_item, m->IsStatic(), m->GetDexMethodIndex(), NULL,
1580 DebugCallbackContext::Callback, &context);
1581 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001582
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001583 JDWP::Set4BE(expandBufGetBuffer(pReply) + variable_count_offset, context.variable_count);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001584}
1585
Jeff Hao579b0242013-11-18 13:16:49 -08001586void Dbg::OutputMethodReturnValue(JDWP::MethodId method_id, const JValue* return_value,
1587 JDWP::ExpandBuf* pReply) {
1588 mirror::ArtMethod* m = FromMethodId(method_id);
1589 JDWP::JdwpTag tag = BasicTagFromDescriptor(MethodHelper(m).GetShorty());
1590 OutputJValue(tag, return_value, pReply);
1591}
1592
Elliott Hughes9777ba22013-01-17 09:04:19 -08001593JDWP::JdwpError Dbg::GetBytecodes(JDWP::RefTypeId, JDWP::MethodId method_id,
1594 std::vector<uint8_t>& bytecodes)
1595 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001596 mirror::ArtMethod* m = FromMethodId(method_id);
Elliott Hughes9777ba22013-01-17 09:04:19 -08001597 if (m == NULL) {
1598 return JDWP::ERR_INVALID_METHODID;
1599 }
1600 MethodHelper mh(m);
1601 const DexFile::CodeItem* code_item = mh.GetCodeItem();
1602 size_t byte_count = code_item->insns_size_in_code_units_ * 2;
1603 const uint8_t* begin = reinterpret_cast<const uint8_t*>(code_item->insns_);
1604 const uint8_t* end = begin + byte_count;
1605 for (const uint8_t* p = begin; p != end; ++p) {
1606 bytecodes.push_back(*p);
1607 }
1608 return JDWP::ERR_NONE;
1609}
1610
Elliott Hughes88d63092013-01-09 09:55:54 -08001611JDWP::JdwpTag Dbg::GetFieldBasicTag(JDWP::FieldId field_id) {
1612 return BasicTagFromDescriptor(FieldHelper(FromFieldId(field_id)).GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001613}
1614
Elliott Hughes88d63092013-01-09 09:55:54 -08001615JDWP::JdwpTag Dbg::GetStaticFieldBasicTag(JDWP::FieldId field_id) {
1616 return BasicTagFromDescriptor(FieldHelper(FromFieldId(field_id)).GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001617}
1618
Elliott Hughes88d63092013-01-09 09:55:54 -08001619static JDWP::JdwpError GetFieldValueImpl(JDWP::RefTypeId ref_type_id, JDWP::ObjectId object_id,
1620 JDWP::FieldId field_id, JDWP::ExpandBuf* pReply,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001621 bool is_static)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001622 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes0cf74332012-02-23 23:14:00 -08001623 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001624 mirror::Class* c = DecodeClass(ref_type_id, status);
Elliott Hughes88d63092013-01-09 09:55:54 -08001625 if (ref_type_id != 0 && c == NULL) {
Elliott Hughes0cf74332012-02-23 23:14:00 -08001626 return status;
1627 }
1628
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001629 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001630 if ((!is_static && o == NULL) || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001631 return JDWP::ERR_INVALID_OBJECT;
1632 }
Brian Carlstromea46f952013-07-30 01:26:50 -07001633 mirror::ArtField* f = FromFieldId(field_id);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001634
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001635 mirror::Class* receiver_class = c;
Elliott Hughes0cf74332012-02-23 23:14:00 -08001636 if (receiver_class == NULL && o != NULL) {
1637 receiver_class = o->GetClass();
1638 }
1639 // TODO: should we give up now if receiver_class is NULL?
1640 if (receiver_class != NULL && !f->GetDeclaringClass()->IsAssignableFrom(receiver_class)) {
1641 LOG(INFO) << "ERR_INVALID_FIELDID: " << PrettyField(f) << " " << PrettyClass(receiver_class);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001642 return JDWP::ERR_INVALID_FIELDID;
1643 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001644
Elliott Hughes0cf74332012-02-23 23:14:00 -08001645 // The RI only enforces the static/non-static mismatch in one direction.
1646 // TODO: should we change the tests and check both?
1647 if (is_static) {
1648 if (!f->IsStatic()) {
1649 return JDWP::ERR_INVALID_FIELDID;
1650 }
1651 } else {
1652 if (f->IsStatic()) {
1653 LOG(WARNING) << "Ignoring non-NULL receiver for ObjectReference.SetValues on static field " << PrettyField(f);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001654 }
1655 }
jeffhao0dfbb7e2012-11-28 15:26:03 -08001656 if (f->IsStatic()) {
1657 o = f->GetDeclaringClass();
1658 }
Elliott Hughes0cf74332012-02-23 23:14:00 -08001659
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001660 JDWP::JdwpTag tag = BasicTagFromDescriptor(FieldHelper(f).GetTypeDescriptor());
Jeff Hao579b0242013-11-18 13:16:49 -08001661 JValue field_value;
1662 if (tag == JDWP::JT_VOID) {
1663 LOG(FATAL) << "Unknown tag: " << tag;
1664 } else if (!IsPrimitiveTag(tag)) {
1665 field_value.SetL(f->GetObject(o));
1666 } else if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
1667 field_value.SetJ(f->Get64(o));
Elliott Hughesaed4be92011-12-02 16:16:23 -08001668 } else {
Jeff Hao579b0242013-11-18 13:16:49 -08001669 field_value.SetI(f->Get32(o));
Elliott Hughesaed4be92011-12-02 16:16:23 -08001670 }
Jeff Hao579b0242013-11-18 13:16:49 -08001671 Dbg::OutputJValue(tag, &field_value, pReply);
1672
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001673 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001674}
1675
Elliott Hughes88d63092013-01-09 09:55:54 -08001676JDWP::JdwpError Dbg::GetFieldValue(JDWP::ObjectId object_id, JDWP::FieldId field_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001677 JDWP::ExpandBuf* pReply) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001678 return GetFieldValueImpl(0, object_id, field_id, pReply, false);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001679}
1680
Elliott Hughes88d63092013-01-09 09:55:54 -08001681JDWP::JdwpError Dbg::GetStaticFieldValue(JDWP::RefTypeId ref_type_id, JDWP::FieldId field_id, JDWP::ExpandBuf* pReply) {
1682 return GetFieldValueImpl(ref_type_id, 0, field_id, pReply, true);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001683}
1684
Elliott Hughes88d63092013-01-09 09:55:54 -08001685static JDWP::JdwpError SetFieldValueImpl(JDWP::ObjectId object_id, JDWP::FieldId field_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001686 uint64_t value, int width, bool is_static)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001687 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001688 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001689 if ((!is_static && o == NULL) || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001690 return JDWP::ERR_INVALID_OBJECT;
1691 }
Brian Carlstromea46f952013-07-30 01:26:50 -07001692 mirror::ArtField* f = FromFieldId(field_id);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001693
1694 // The RI only enforces the static/non-static mismatch in one direction.
1695 // TODO: should we change the tests and check both?
1696 if (is_static) {
1697 if (!f->IsStatic()) {
1698 return JDWP::ERR_INVALID_FIELDID;
1699 }
1700 } else {
1701 if (f->IsStatic()) {
1702 LOG(WARNING) << "Ignoring non-NULL receiver for ObjectReference.SetValues on static field " << PrettyField(f);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001703 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001704 }
jeffhao0dfbb7e2012-11-28 15:26:03 -08001705 if (f->IsStatic()) {
1706 o = f->GetDeclaringClass();
1707 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001708
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001709 JDWP::JdwpTag tag = BasicTagFromDescriptor(FieldHelper(f).GetTypeDescriptor());
Elliott Hughesaed4be92011-12-02 16:16:23 -08001710
1711 if (IsPrimitiveTag(tag)) {
1712 if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001713 CHECK_EQ(width, 8);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001714 // Debugging can't use transactional mode (runtime only).
1715 f->Set64<false>(o, value);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001716 } else {
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001717 CHECK_LE(width, 4);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001718 // Debugging can't use transactional mode (runtime only).
1719 f->Set32<false>(o, value);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001720 }
1721 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001722 mirror::Object* v = gRegistry->Get<mirror::Object*>(value);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001723 if (v == ObjectRegistry::kInvalidObject) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001724 return JDWP::ERR_INVALID_OBJECT;
1725 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001726 if (v != NULL) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001727 mirror::Class* field_type = FieldHelper(f).GetType();
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001728 if (!field_type->IsAssignableFrom(v->GetClass())) {
1729 return JDWP::ERR_INVALID_OBJECT;
1730 }
1731 }
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001732 // Debugging can't use transactional mode (runtime only).
1733 f->SetObject<false>(o, v);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001734 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001735
1736 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001737}
1738
Elliott Hughes88d63092013-01-09 09:55:54 -08001739JDWP::JdwpError Dbg::SetFieldValue(JDWP::ObjectId object_id, JDWP::FieldId field_id, uint64_t value,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001740 int width) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001741 return SetFieldValueImpl(object_id, field_id, value, width, false);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001742}
1743
Elliott Hughes88d63092013-01-09 09:55:54 -08001744JDWP::JdwpError Dbg::SetStaticFieldValue(JDWP::FieldId field_id, uint64_t value, int width) {
1745 return SetFieldValueImpl(0, field_id, value, width, true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001746}
1747
Elliott Hughes88d63092013-01-09 09:55:54 -08001748std::string Dbg::StringToUtf8(JDWP::ObjectId string_id) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001749 mirror::String* s = gRegistry->Get<mirror::String*>(string_id);
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001750 return s->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001751}
1752
Jeff Hao579b0242013-11-18 13:16:49 -08001753void Dbg::OutputJValue(JDWP::JdwpTag tag, const JValue* return_value, JDWP::ExpandBuf* pReply) {
1754 if (IsPrimitiveTag(tag)) {
1755 expandBufAdd1(pReply, tag);
1756 if (tag == JDWP::JT_BOOLEAN || tag == JDWP::JT_BYTE) {
1757 expandBufAdd1(pReply, return_value->GetI());
1758 } else if (tag == JDWP::JT_CHAR || tag == JDWP::JT_SHORT) {
1759 expandBufAdd2BE(pReply, return_value->GetI());
1760 } else if (tag == JDWP::JT_FLOAT || tag == JDWP::JT_INT) {
1761 expandBufAdd4BE(pReply, return_value->GetI());
1762 } else if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
1763 expandBufAdd8BE(pReply, return_value->GetJ());
1764 } else {
1765 CHECK_EQ(tag, JDWP::JT_VOID);
1766 }
1767 } else {
Ian Rogers98379392014-02-24 16:53:16 -08001768 ScopedObjectAccessUnchecked soa(Thread::Current());
Jeff Hao579b0242013-11-18 13:16:49 -08001769 mirror::Object* value = return_value->GetL();
Ian Rogers98379392014-02-24 16:53:16 -08001770 expandBufAdd1(pReply, TagFromObject(soa, value));
Jeff Hao579b0242013-11-18 13:16:49 -08001771 expandBufAddObjectId(pReply, gRegistry->Add(value));
1772 }
1773}
1774
Elliott Hughes221229c2013-01-08 18:17:50 -08001775JDWP::JdwpError Dbg::GetThreadName(JDWP::ObjectId thread_id, std::string& name) {
jeffhaoa77f0f62012-12-05 17:19:31 -08001776 ScopedObjectAccessUnchecked soa(Thread::Current());
1777 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001778 Thread* thread;
1779 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1780 if (error != JDWP::ERR_NONE && error != JDWP::ERR_THREAD_NOT_ALIVE) {
1781 return error;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001782 }
Elliott Hughes221229c2013-01-08 18:17:50 -08001783
1784 // We still need to report the zombie threads' names, so we can't just call Thread::GetThreadName.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001785 mirror::Object* thread_object = gRegistry->Get<mirror::Object*>(thread_id);
Brian Carlstromea46f952013-07-30 01:26:50 -07001786 mirror::ArtField* java_lang_Thread_name_field =
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001787 soa.DecodeField(WellKnownClasses::java_lang_Thread_name);
1788 mirror::String* s =
1789 reinterpret_cast<mirror::String*>(java_lang_Thread_name_field->GetObject(thread_object));
Elliott Hughes221229c2013-01-08 18:17:50 -08001790 if (s != NULL) {
1791 name = s->ToModifiedUtf8();
1792 }
1793 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001794}
1795
Elliott Hughes221229c2013-01-08 18:17:50 -08001796JDWP::JdwpError Dbg::GetThreadGroup(JDWP::ObjectId thread_id, JDWP::ExpandBuf* pReply) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001797 ScopedObjectAccess soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001798 mirror::Object* thread_object = gRegistry->Get<mirror::Object*>(thread_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001799 if (thread_object == ObjectRegistry::kInvalidObject) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001800 return JDWP::ERR_INVALID_OBJECT;
1801 }
Ian Rogers98379392014-02-24 16:53:16 -08001802 const char* old_cause = soa.Self()->StartAssertNoThreadSuspension("Debugger: GetThreadGroup");
Elliott Hughes2435a572012-02-17 16:07:41 -08001803 // Okay, so it's an object, but is it actually a thread?
Ian Rogers50b35e22012-10-04 10:09:15 -07001804 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001805 Thread* thread;
1806 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1807 if (error == JDWP::ERR_THREAD_NOT_ALIVE) {
1808 // Zombie threads are in the null group.
1809 expandBufAddObjectId(pReply, JDWP::ObjectId(0));
Sebastien Hertz52d131d2014-03-13 16:17:40 +01001810 error = JDWP::ERR_NONE;
1811 } else if (error == JDWP::ERR_NONE) {
1812 mirror::Class* c = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_Thread);
1813 CHECK(c != nullptr);
1814 mirror::ArtField* f = c->FindInstanceField("group", "Ljava/lang/ThreadGroup;");
1815 CHECK(f != NULL);
1816 mirror::Object* group = f->GetObject(thread_object);
1817 CHECK(group != NULL);
1818 JDWP::ObjectId thread_group_id = gRegistry->Add(group);
1819 expandBufAddObjectId(pReply, thread_group_id);
Elliott Hughes221229c2013-01-08 18:17:50 -08001820 }
Ian Rogers98379392014-02-24 16:53:16 -08001821 soa.Self()->EndAssertNoThreadSuspension(old_cause);
Sebastien Hertz52d131d2014-03-13 16:17:40 +01001822 return error;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001823}
1824
Elliott Hughes88d63092013-01-09 09:55:54 -08001825std::string Dbg::GetThreadGroupName(JDWP::ObjectId thread_group_id) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001826 ScopedObjectAccess soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001827 mirror::Object* thread_group = gRegistry->Get<mirror::Object*>(thread_group_id);
Ian Rogers98379392014-02-24 16:53:16 -08001828 CHECK(thread_group != nullptr);
1829 const char* old_cause = soa.Self()->StartAssertNoThreadSuspension("Debugger: GetThreadGroupName");
1830 mirror::Class* c = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_ThreadGroup);
1831 CHECK(c != nullptr);
Brian Carlstromea46f952013-07-30 01:26:50 -07001832 mirror::ArtField* f = c->FindInstanceField("name", "Ljava/lang/String;");
Elliott Hughes499c5132011-11-17 14:55:11 -08001833 CHECK(f != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001834 mirror::String* s = reinterpret_cast<mirror::String*>(f->GetObject(thread_group));
Ian Rogers98379392014-02-24 16:53:16 -08001835 soa.Self()->EndAssertNoThreadSuspension(old_cause);
Elliott Hughes499c5132011-11-17 14:55:11 -08001836 return s->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001837}
1838
Elliott Hughes88d63092013-01-09 09:55:54 -08001839JDWP::ObjectId Dbg::GetThreadGroupParent(JDWP::ObjectId thread_group_id) {
Ian Rogers98379392014-02-24 16:53:16 -08001840 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001841 mirror::Object* thread_group = gRegistry->Get<mirror::Object*>(thread_group_id);
Ian Rogers98379392014-02-24 16:53:16 -08001842 CHECK(thread_group != nullptr);
1843 const char* old_cause = soa.Self()->StartAssertNoThreadSuspension("Debugger: GetThreadGroupParent");
1844 mirror::Class* c = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_ThreadGroup);
1845 CHECK(c != nullptr);
Brian Carlstromea46f952013-07-30 01:26:50 -07001846 mirror::ArtField* f = c->FindInstanceField("parent", "Ljava/lang/ThreadGroup;");
Elliott Hughes4e235312011-12-02 11:34:15 -08001847 CHECK(f != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001848 mirror::Object* parent = f->GetObject(thread_group);
Ian Rogers98379392014-02-24 16:53:16 -08001849 soa.Self()->EndAssertNoThreadSuspension(old_cause);
Elliott Hughes4e235312011-12-02 11:34:15 -08001850 return gRegistry->Add(parent);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001851}
1852
1853JDWP::ObjectId Dbg::GetSystemThreadGroupId() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001854 ScopedObjectAccessUnchecked soa(Thread::Current());
Brian Carlstromea46f952013-07-30 01:26:50 -07001855 mirror::ArtField* f = soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_systemThreadGroup);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001856 mirror::Object* group = f->GetObject(f->GetDeclaringClass());
Ian Rogers365c1022012-06-22 15:05:28 -07001857 return gRegistry->Add(group);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001858}
1859
1860JDWP::ObjectId Dbg::GetMainThreadGroupId() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001861 ScopedObjectAccess soa(Thread::Current());
Brian Carlstromea46f952013-07-30 01:26:50 -07001862 mirror::ArtField* f = soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_mainThreadGroup);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001863 mirror::Object* group = f->GetObject(f->GetDeclaringClass());
Ian Rogers365c1022012-06-22 15:05:28 -07001864 return gRegistry->Add(group);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001865}
1866
Jeff Hao920af3e2013-08-28 15:46:38 -07001867JDWP::JdwpThreadStatus Dbg::ToJdwpThreadStatus(ThreadState state) {
1868 switch (state) {
1869 case kBlocked:
1870 return JDWP::TS_MONITOR;
1871 case kNative:
1872 case kRunnable:
1873 case kSuspended:
1874 return JDWP::TS_RUNNING;
1875 case kSleeping:
1876 return JDWP::TS_SLEEPING;
1877 case kStarting:
1878 case kTerminated:
1879 return JDWP::TS_ZOMBIE;
1880 case kTimedWaiting:
1881 case kWaitingForDebuggerSend:
1882 case kWaitingForDebuggerSuspension:
1883 case kWaitingForDebuggerToAttach:
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01001884 case kWaitingForDeoptimization:
Jeff Hao920af3e2013-08-28 15:46:38 -07001885 case kWaitingForGcToComplete:
1886 case kWaitingForCheckPointsToRun:
1887 case kWaitingForJniOnLoad:
1888 case kWaitingForSignalCatcherOutput:
1889 case kWaitingInMainDebuggerLoop:
1890 case kWaitingInMainSignalCatcherLoop:
1891 case kWaitingPerformingGc:
1892 case kWaiting:
1893 return JDWP::TS_WAIT;
1894 // Don't add a 'default' here so the compiler can spot incompatible enum changes.
1895 }
1896 LOG(FATAL) << "Unknown thread state: " << state;
1897 return JDWP::TS_ZOMBIE;
1898}
1899
Sebastien Hertz52d131d2014-03-13 16:17:40 +01001900JDWP::JdwpError Dbg::GetThreadStatus(JDWP::ObjectId thread_id, JDWP::JdwpThreadStatus* pThreadStatus,
1901 JDWP::JdwpSuspendStatus* pSuspendStatus) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001902 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes499c5132011-11-17 14:55:11 -08001903
Elliott Hughes9e0c1752013-01-09 14:02:58 -08001904 *pSuspendStatus = JDWP::SUSPEND_STATUS_NOT_SUSPENDED;
1905
Ian Rogers50b35e22012-10-04 10:09:15 -07001906 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001907 Thread* thread;
1908 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1909 if (error != JDWP::ERR_NONE) {
1910 if (error == JDWP::ERR_THREAD_NOT_ALIVE) {
1911 *pThreadStatus = JDWP::TS_ZOMBIE;
Elliott Hughes221229c2013-01-08 18:17:50 -08001912 return JDWP::ERR_NONE;
1913 }
1914 return error;
Elliott Hughes499c5132011-11-17 14:55:11 -08001915 }
1916
Elliott Hughes9e0c1752013-01-09 14:02:58 -08001917 if (IsSuspendedForDebugger(soa, thread)) {
1918 *pSuspendStatus = JDWP::SUSPEND_STATUS_SUSPENDED;
Elliott Hughes499c5132011-11-17 14:55:11 -08001919 }
1920
Jeff Hao920af3e2013-08-28 15:46:38 -07001921 *pThreadStatus = ToJdwpThreadStatus(thread->GetState());
Elliott Hughes221229c2013-01-08 18:17:50 -08001922 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001923}
1924
Elliott Hughes221229c2013-01-08 18:17:50 -08001925JDWP::JdwpError Dbg::GetThreadDebugSuspendCount(JDWP::ObjectId thread_id, JDWP::ExpandBuf* pReply) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001926 ScopedObjectAccess soa(Thread::Current());
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 return error;
Elliott Hughes2435a572012-02-17 16:07:41 -08001932 }
Ian Rogers50b35e22012-10-04 10:09:15 -07001933 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001934 expandBufAdd4BE(pReply, thread->GetDebugSuspendCount());
Elliott Hughes2435a572012-02-17 16:07:41 -08001935 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001936}
1937
Elliott Hughesf9501702013-01-11 11:22:27 -08001938JDWP::JdwpError Dbg::Interrupt(JDWP::ObjectId thread_id) {
1939 ScopedObjectAccess soa(Thread::Current());
1940 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
1941 Thread* thread;
1942 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1943 if (error != JDWP::ERR_NONE) {
1944 return error;
1945 }
Ian Rogersdd7624d2014-03-14 17:43:00 -07001946 thread->Interrupt(soa.Self());
Elliott Hughesf9501702013-01-11 11:22:27 -08001947 return JDWP::ERR_NONE;
1948}
1949
Elliott Hughescaf76542012-06-28 16:08:22 -07001950void Dbg::GetThreads(JDWP::ObjectId thread_group_id, std::vector<JDWP::ObjectId>& thread_ids) {
Ian Rogers365c1022012-06-22 15:05:28 -07001951 class ThreadListVisitor {
1952 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001953 ThreadListVisitor(const ScopedObjectAccessUnchecked& soa, mirror::Object* desired_thread_group,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001954 std::vector<JDWP::ObjectId>& thread_ids)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001955 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
jeffhao0dfbb7e2012-11-28 15:26:03 -08001956 : soa_(soa), desired_thread_group_(desired_thread_group), thread_ids_(thread_ids) {}
Ian Rogers365c1022012-06-22 15:05:28 -07001957
Elliott Hughesa2155262011-11-16 16:26:58 -08001958 static void Visit(Thread* t, void* arg) {
1959 reinterpret_cast<ThreadListVisitor*>(arg)->Visit(t);
1960 }
1961
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001962 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1963 // annotalysis.
1964 void Visit(Thread* t) NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughesa2155262011-11-16 16:26:58 -08001965 if (t == Dbg::GetDebugThread()) {
1966 // Skip the JDWP thread. Some debuggers get bent out of shape when they can't suspend and
1967 // query all threads, so it's easier if we just don't tell them about this thread.
1968 return;
1969 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001970 mirror::Object* peer = t->GetPeer();
jeffhao0dfbb7e2012-11-28 15:26:03 -08001971 if (IsInDesiredThreadGroup(peer)) {
Ian Rogers120f1c72012-09-28 17:17:10 -07001972 thread_ids_.push_back(gRegistry->Add(peer));
Elliott Hughesa2155262011-11-16 16:26:58 -08001973 }
1974 }
1975
Ian Rogers365c1022012-06-22 15:05:28 -07001976 private:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001977 bool IsInDesiredThreadGroup(mirror::Object* peer)
jeffhao0dfbb7e2012-11-28 15:26:03 -08001978 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
jeffhao0dfbb7e2012-11-28 15:26:03 -08001979 // peer might be NULL if the thread is still starting up.
1980 if (peer == NULL) {
1981 // We can't tell the debugger about this thread yet.
1982 // TODO: if we identified threads to the debugger by their Thread*
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001983 // rather than their peer's mirror::Object*, we could fix this.
jeffhao0dfbb7e2012-11-28 15:26:03 -08001984 // Doing so might help us report ZOMBIE threads too.
1985 return false;
1986 }
jeffhaoc1e04902012-12-13 12:41:10 -08001987 // Do we want threads from all thread groups?
1988 if (desired_thread_group_ == NULL) {
1989 return true;
1990 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001991 mirror::Object* group = soa_.DecodeField(WellKnownClasses::java_lang_Thread_group)->GetObject(peer);
jeffhao0dfbb7e2012-11-28 15:26:03 -08001992 return (group == desired_thread_group_);
1993 }
1994
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07001995 const ScopedObjectAccessUnchecked& soa_;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001996 mirror::Object* const desired_thread_group_;
Elliott Hughescaf76542012-06-28 16:08:22 -07001997 std::vector<JDWP::ObjectId>& thread_ids_;
Elliott Hughesa2155262011-11-16 16:26:58 -08001998 };
1999
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002000 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002001 mirror::Object* thread_group = gRegistry->Get<mirror::Object*>(thread_group_id);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002002 ThreadListVisitor tlv(soa, thread_group, thread_ids);
Ian Rogers50b35e22012-10-04 10:09:15 -07002003 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughesf8349362012-06-18 15:00:06 -07002004 Runtime::Current()->GetThreadList()->ForEach(ThreadListVisitor::Visit, &tlv);
Elliott Hughescaf76542012-06-28 16:08:22 -07002005}
Elliott Hughesa2155262011-11-16 16:26:58 -08002006
Elliott Hughescaf76542012-06-28 16:08:22 -07002007void Dbg::GetChildThreadGroups(JDWP::ObjectId thread_group_id, std::vector<JDWP::ObjectId>& child_thread_group_ids) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002008 ScopedObjectAccess soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002009 mirror::Object* thread_group = gRegistry->Get<mirror::Object*>(thread_group_id);
Elliott Hughescaf76542012-06-28 16:08:22 -07002010
2011 // Get the ArrayList<ThreadGroup> "groups" out of this thread group...
Brian Carlstromea46f952013-07-30 01:26:50 -07002012 mirror::ArtField* groups_field = thread_group->GetClass()->FindInstanceField("groups", "Ljava/util/List;");
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002013 mirror::Object* groups_array_list = groups_field->GetObject(thread_group);
Elliott Hughescaf76542012-06-28 16:08:22 -07002014
2015 // Get the array and size out of the ArrayList<ThreadGroup>...
Brian Carlstromea46f952013-07-30 01:26:50 -07002016 mirror::ArtField* array_field = groups_array_list->GetClass()->FindInstanceField("array", "[Ljava/lang/Object;");
2017 mirror::ArtField* size_field = groups_array_list->GetClass()->FindInstanceField("size", "I");
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002018 mirror::ObjectArray<mirror::Object>* groups_array =
2019 array_field->GetObject(groups_array_list)->AsObjectArray<mirror::Object>();
Elliott Hughescaf76542012-06-28 16:08:22 -07002020 const int32_t size = size_field->GetInt(groups_array_list);
2021
2022 // Copy the first 'size' elements out of the array into the result.
2023 for (int32_t i = 0; i < size; ++i) {
2024 child_thread_group_ids.push_back(gRegistry->Add(groups_array->Get(i)));
Elliott Hughesa2155262011-11-16 16:26:58 -08002025 }
2026}
2027
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002028static int GetStackDepth(Thread* thread)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002029 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002030 struct CountStackDepthVisitor : public StackVisitor {
Brian Carlstrom93ba8932013-07-17 21:31:49 -07002031 explicit CountStackDepthVisitor(Thread* thread)
Ian Rogers7a22fa62013-01-23 12:16:16 -08002032 : StackVisitor(thread, NULL), depth(0) {}
Ian Rogers0399dde2012-06-06 17:09:28 -07002033
Elliott Hughes64f574f2013-02-20 14:57:12 -08002034 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2035 // annotalysis.
2036 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07002037 if (!GetMethod()->IsRuntimeMethod()) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -08002038 ++depth;
2039 }
Elliott Hughes530fa002012-03-12 11:44:49 -07002040 return true;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08002041 }
2042 size_t depth;
2043 };
Elliott Hughes08fc03a2012-06-26 17:34:00 -07002044
Ian Rogers7a22fa62013-01-23 12:16:16 -08002045 CountStackDepthVisitor visitor(thread);
Ian Rogers0399dde2012-06-06 17:09:28 -07002046 visitor.WalkStack();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08002047 return visitor.depth;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002048}
2049
Elliott Hughes221229c2013-01-08 18:17:50 -08002050JDWP::JdwpError Dbg::GetThreadFrameCount(JDWP::ObjectId thread_id, size_t& result) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002051 ScopedObjectAccess soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08002052 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002053 Thread* thread;
2054 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
2055 if (error != JDWP::ERR_NONE) {
2056 return error;
2057 }
Elliott Hughesf15f4a02013-01-09 10:09:38 -08002058 if (!IsSuspendedForDebugger(soa, thread)) {
2059 return JDWP::ERR_THREAD_NOT_SUSPENDED;
2060 }
Elliott Hughes221229c2013-01-08 18:17:50 -08002061 result = GetStackDepth(thread);
2062 return JDWP::ERR_NONE;
Elliott Hughes86964332012-02-15 19:37:42 -08002063}
2064
Ian Rogers306057f2012-11-26 12:45:53 -08002065JDWP::JdwpError Dbg::GetThreadFrames(JDWP::ObjectId thread_id, size_t start_frame,
2066 size_t frame_count, JDWP::ExpandBuf* buf) {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002067 class GetFrameVisitor : public StackVisitor {
2068 public:
Ian Rogers7a22fa62013-01-23 12:16:16 -08002069 GetFrameVisitor(Thread* thread, size_t start_frame, size_t frame_count, JDWP::ExpandBuf* buf)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002070 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08002071 : StackVisitor(thread, NULL), depth_(0),
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002072 start_frame_(start_frame), frame_count_(frame_count), buf_(buf) {
2073 expandBufAdd4BE(buf_, frame_count_);
Elliott Hughes03181a82011-11-17 17:22:21 -08002074 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002075
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002076 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2077 // annotalysis.
2078 virtual bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07002079 if (GetMethod()->IsRuntimeMethod()) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07002080 return true; // The debugger can't do anything useful with a frame that has no Method*.
Elliott Hughes03181a82011-11-17 17:22:21 -08002081 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002082 if (depth_ >= start_frame_ + frame_count_) {
Elliott Hughes530fa002012-03-12 11:44:49 -07002083 return false;
Elliott Hughes03181a82011-11-17 17:22:21 -08002084 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002085 if (depth_ >= start_frame_) {
2086 JDWP::FrameId frame_id(GetFrameId());
2087 JDWP::JdwpLocation location;
2088 SetLocation(location, GetMethod(), GetDexPc());
Ian Rogersef7d42f2014-01-06 12:55:46 -08002089 VLOG(jdwp) << StringPrintf(" Frame %3zd: id=%3" PRIu64 " ", depth_, frame_id) << location;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002090 expandBufAdd8BE(buf_, frame_id);
2091 expandBufAddLocation(buf_, location);
2092 }
2093 ++depth_;
Elliott Hughes530fa002012-03-12 11:44:49 -07002094 return true;
Elliott Hughes03181a82011-11-17 17:22:21 -08002095 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002096
2097 private:
2098 size_t depth_;
2099 const size_t start_frame_;
2100 const size_t frame_count_;
2101 JDWP::ExpandBuf* buf_;
Elliott Hughes03181a82011-11-17 17:22:21 -08002102 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002103
2104 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08002105 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002106 Thread* thread;
2107 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
2108 if (error != JDWP::ERR_NONE) {
2109 return error;
2110 }
Elliott Hughesf15f4a02013-01-09 10:09:38 -08002111 if (!IsSuspendedForDebugger(soa, thread)) {
2112 return JDWP::ERR_THREAD_NOT_SUSPENDED;
2113 }
Ian Rogers7a22fa62013-01-23 12:16:16 -08002114 GetFrameVisitor visitor(thread, start_frame, frame_count, buf);
Ian Rogers0399dde2012-06-06 17:09:28 -07002115 visitor.WalkStack();
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002116 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002117}
2118
2119JDWP::ObjectId Dbg::GetThreadSelfId() {
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07002120 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogerscfaa4552012-11-26 21:00:08 -08002121 return gRegistry->Add(soa.Self()->GetPeer());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002122}
2123
Elliott Hughes475fc232011-10-25 15:00:35 -07002124void Dbg::SuspendVM() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002125 Runtime::Current()->GetThreadList()->SuspendAllForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002126}
2127
2128void Dbg::ResumeVM() {
Elliott Hughesc61a2672012-06-21 14:52:29 -07002129 Runtime::Current()->GetThreadList()->UndoDebuggerSuspensions();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002130}
2131
Elliott Hughes221229c2013-01-08 18:17:50 -08002132JDWP::JdwpError Dbg::SuspendThread(JDWP::ObjectId thread_id, bool request_suspension) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002133 ScopedLocalRef<jobject> peer(Thread::Current()->GetJniEnv(), NULL);
2134 {
2135 ScopedObjectAccess soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002136 peer.reset(soa.AddLocalReference<jobject>(gRegistry->Get<mirror::Object*>(thread_id)));
Elliott Hughes4e235312011-12-02 11:34:15 -08002137 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002138 if (peer.get() == NULL) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002139 return JDWP::ERR_THREAD_NOT_ALIVE;
2140 }
2141 // Suspend thread to build stack trace.
Elliott Hughesf327e072013-01-09 16:01:26 -08002142 bool timed_out;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07002143 Thread* thread = ThreadList::SuspendThreadByPeer(peer.get(), request_suspension, true,
2144 &timed_out);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002145 if (thread != NULL) {
2146 return JDWP::ERR_NONE;
Elliott Hughesf327e072013-01-09 16:01:26 -08002147 } else if (timed_out) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002148 return JDWP::ERR_INTERNAL;
2149 } else {
2150 return JDWP::ERR_THREAD_NOT_ALIVE;
2151 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002152}
2153
Elliott Hughes221229c2013-01-08 18:17:50 -08002154void Dbg::ResumeThread(JDWP::ObjectId thread_id) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002155 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002156 mirror::Object* peer = gRegistry->Get<mirror::Object*>(thread_id);
jeffhaoa77f0f62012-12-05 17:19:31 -08002157 Thread* thread;
2158 {
2159 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
2160 thread = Thread::FromManagedThread(soa, peer);
2161 }
Elliott Hughes4e235312011-12-02 11:34:15 -08002162 if (thread == NULL) {
2163 LOG(WARNING) << "No such thread for resume: " << peer;
2164 return;
2165 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002166 bool needs_resume;
2167 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002168 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002169 needs_resume = thread->GetSuspendCount() > 0;
2170 }
2171 if (needs_resume) {
Elliott Hughes546b9862012-06-20 16:06:13 -07002172 Runtime::Current()->GetThreadList()->Resume(thread, true);
2173 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002174}
2175
2176void Dbg::SuspendSelf() {
Elliott Hughes475fc232011-10-25 15:00:35 -07002177 Runtime::Current()->GetThreadList()->SuspendSelfForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002178}
2179
Ian Rogers0399dde2012-06-06 17:09:28 -07002180struct GetThisVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -08002181 GetThisVisitor(Thread* thread, Context* context, JDWP::FrameId frame_id)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002182 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08002183 : StackVisitor(thread, context), this_object(NULL), frame_id(frame_id) {}
Ian Rogers0399dde2012-06-06 17:09:28 -07002184
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002185 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2186 // annotalysis.
2187 virtual bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002188 if (frame_id != GetFrameId()) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002189 return true; // continue
Ian Rogers0399dde2012-06-06 17:09:28 -07002190 } else {
Ian Rogers62d6c772013-02-27 08:32:07 -08002191 this_object = GetThisObject();
2192 return false;
Ian Rogers0399dde2012-06-06 17:09:28 -07002193 }
Elliott Hughes86b00102011-12-05 17:54:26 -08002194 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002195
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002196 mirror::Object* this_object;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002197 JDWP::FrameId frame_id;
Ian Rogers0399dde2012-06-06 17:09:28 -07002198};
2199
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002200JDWP::JdwpError Dbg::GetThisObject(JDWP::ObjectId thread_id, JDWP::FrameId frame_id,
2201 JDWP::ObjectId* result) {
2202 ScopedObjectAccessUnchecked soa(Thread::Current());
2203 Thread* thread;
2204 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002205 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002206 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
2207 if (error != JDWP::ERR_NONE) {
2208 return error;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002209 }
Elliott Hughes9e0c1752013-01-09 14:02:58 -08002210 if (!IsSuspendedForDebugger(soa, thread)) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002211 return JDWP::ERR_THREAD_NOT_SUSPENDED;
2212 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002213 }
Elliott Hughescaf76542012-06-28 16:08:22 -07002214 UniquePtr<Context> context(Context::Create());
Ian Rogers7a22fa62013-01-23 12:16:16 -08002215 GetThisVisitor visitor(thread, context.get(), frame_id);
Ian Rogers0399dde2012-06-06 17:09:28 -07002216 visitor.WalkStack();
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002217 *result = gRegistry->Add(visitor.this_object);
2218 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002219}
2220
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002221JDWP::JdwpError Dbg::GetLocalValue(JDWP::ObjectId thread_id, JDWP::FrameId frame_id, int slot,
2222 JDWP::JdwpTag tag, uint8_t* buf, size_t width) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002223 struct GetLocalVisitor : public StackVisitor {
Ian Rogers98379392014-02-24 16:53:16 -08002224 GetLocalVisitor(const ScopedObjectAccessUnchecked& soa, Thread* thread, Context* context,
2225 JDWP::FrameId frame_id, int slot, JDWP::JdwpTag tag, uint8_t* buf, size_t width)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002226 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers98379392014-02-24 16:53:16 -08002227 : StackVisitor(thread, context), soa_(soa), frame_id_(frame_id), slot_(slot), tag_(tag),
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002228 buf_(buf), width_(width), error_(JDWP::ERR_NONE) {}
Ian Rogersca190662012-06-26 15:45:57 -07002229
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002230 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2231 // annotalysis.
2232 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07002233 if (GetFrameId() != frame_id_) {
2234 return true; // Not our frame, carry on.
Elliott Hughesdbb40792011-11-18 17:05:22 -08002235 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002236 // TODO: check that the tag is compatible with the actual type of the slot!
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002237 // TODO: check slot is valid for this method or return INVALID_SLOT error.
Brian Carlstromea46f952013-07-30 01:26:50 -07002238 mirror::ArtMethod* m = GetMethod();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002239 if (m->IsNative()) {
2240 // We can't read local value from native method.
2241 error_ = JDWP::ERR_OPAQUE_FRAME;
2242 return false;
2243 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002244 uint16_t reg = DemangleSlot(slot_, m);
Elliott Hughesdbb40792011-11-18 17:05:22 -08002245
Ian Rogers0399dde2012-06-06 17:09:28 -07002246 switch (tag_) {
2247 case JDWP::JT_BOOLEAN:
2248 {
2249 CHECK_EQ(width_, 1U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002250 uint32_t intVal = GetVReg(m, reg, kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002251 VLOG(jdwp) << "get boolean local " << reg << " = " << intVal;
2252 JDWP::Set1(buf_+1, intVal != 0);
2253 }
2254 break;
2255 case JDWP::JT_BYTE:
2256 {
2257 CHECK_EQ(width_, 1U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002258 uint32_t intVal = GetVReg(m, reg, kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002259 VLOG(jdwp) << "get byte local " << reg << " = " << intVal;
2260 JDWP::Set1(buf_+1, intVal);
2261 }
2262 break;
2263 case JDWP::JT_SHORT:
2264 case JDWP::JT_CHAR:
2265 {
2266 CHECK_EQ(width_, 2U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002267 uint32_t intVal = GetVReg(m, reg, kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002268 VLOG(jdwp) << "get short/char local " << reg << " = " << intVal;
2269 JDWP::Set2BE(buf_+1, intVal);
2270 }
2271 break;
2272 case JDWP::JT_INT:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002273 {
2274 CHECK_EQ(width_, 4U);
2275 uint32_t intVal = GetVReg(m, reg, kIntVReg);
2276 VLOG(jdwp) << "get int local " << reg << " = " << intVal;
2277 JDWP::Set4BE(buf_+1, intVal);
2278 }
2279 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002280 case JDWP::JT_FLOAT:
2281 {
2282 CHECK_EQ(width_, 4U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002283 uint32_t intVal = GetVReg(m, reg, kFloatVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002284 VLOG(jdwp) << "get int/float local " << reg << " = " << intVal;
2285 JDWP::Set4BE(buf_+1, intVal);
2286 }
2287 break;
2288 case JDWP::JT_ARRAY:
2289 {
2290 CHECK_EQ(width_, sizeof(JDWP::ObjectId));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002291 mirror::Object* o = reinterpret_cast<mirror::Object*>(GetVReg(m, reg, kReferenceVReg));
Ian Rogers0399dde2012-06-06 17:09:28 -07002292 VLOG(jdwp) << "get array local " << reg << " = " << o;
Mathieu Chartier590fee92013-09-13 13:46:47 -07002293 if (!Runtime::Current()->GetHeap()->IsValidObjectAddress(o)) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002294 LOG(FATAL) << "Register " << reg << " expected to hold array: " << o;
2295 }
2296 JDWP::SetObjectId(buf_+1, gRegistry->Add(o));
2297 }
2298 break;
2299 case JDWP::JT_CLASS_LOADER:
2300 case JDWP::JT_CLASS_OBJECT:
2301 case JDWP::JT_OBJECT:
2302 case JDWP::JT_STRING:
2303 case JDWP::JT_THREAD:
2304 case JDWP::JT_THREAD_GROUP:
2305 {
2306 CHECK_EQ(width_, sizeof(JDWP::ObjectId));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002307 mirror::Object* o = reinterpret_cast<mirror::Object*>(GetVReg(m, reg, kReferenceVReg));
Ian Rogers0399dde2012-06-06 17:09:28 -07002308 VLOG(jdwp) << "get object local " << reg << " = " << o;
Mathieu Chartier590fee92013-09-13 13:46:47 -07002309 if (!Runtime::Current()->GetHeap()->IsValidObjectAddress(o)) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002310 LOG(FATAL) << "Register " << reg << " expected to hold object: " << o;
2311 }
Ian Rogers98379392014-02-24 16:53:16 -08002312 tag_ = TagFromObject(soa_, o);
Ian Rogers0399dde2012-06-06 17:09:28 -07002313 JDWP::SetObjectId(buf_+1, gRegistry->Add(o));
2314 }
2315 break;
2316 case JDWP::JT_DOUBLE:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002317 {
2318 CHECK_EQ(width_, 8U);
2319 uint32_t lo = GetVReg(m, reg, kDoubleLoVReg);
2320 uint64_t hi = GetVReg(m, reg + 1, kDoubleHiVReg);
2321 uint64_t longVal = (hi << 32) | lo;
2322 VLOG(jdwp) << "get double/long local " << hi << ":" << lo << " = " << longVal;
2323 JDWP::Set8BE(buf_+1, longVal);
2324 }
2325 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002326 case JDWP::JT_LONG:
2327 {
2328 CHECK_EQ(width_, 8U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002329 uint32_t lo = GetVReg(m, reg, kLongLoVReg);
2330 uint64_t hi = GetVReg(m, reg + 1, kLongHiVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002331 uint64_t longVal = (hi << 32) | lo;
2332 VLOG(jdwp) << "get double/long local " << hi << ":" << lo << " = " << longVal;
2333 JDWP::Set8BE(buf_+1, longVal);
2334 }
2335 break;
2336 default:
2337 LOG(FATAL) << "Unknown tag " << tag_;
2338 break;
2339 }
2340
2341 // Prepend tag, which may have been updated.
2342 JDWP::Set1(buf_, tag_);
2343 return false;
2344 }
Ian Rogers98379392014-02-24 16:53:16 -08002345 const ScopedObjectAccessUnchecked& soa_;
Ian Rogers0399dde2012-06-06 17:09:28 -07002346 const JDWP::FrameId frame_id_;
2347 const int slot_;
2348 JDWP::JdwpTag tag_;
2349 uint8_t* const buf_;
2350 const size_t width_;
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002351 JDWP::JdwpError error_;
Ian Rogers0399dde2012-06-06 17:09:28 -07002352 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002353
2354 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08002355 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002356 Thread* thread;
2357 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
2358 if (error != JDWP::ERR_NONE) {
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002359 return error;
Elliott Hughes221229c2013-01-08 18:17:50 -08002360 }
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002361 // TODO check thread is suspended by the debugger ?
Ian Rogers0399dde2012-06-06 17:09:28 -07002362 UniquePtr<Context> context(Context::Create());
Ian Rogers98379392014-02-24 16:53:16 -08002363 GetLocalVisitor visitor(soa, thread, context.get(), frame_id, slot, tag, buf, width);
Ian Rogers0399dde2012-06-06 17:09:28 -07002364 visitor.WalkStack();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002365 return visitor.error_;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002366}
2367
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002368JDWP::JdwpError Dbg::SetLocalValue(JDWP::ObjectId thread_id, JDWP::FrameId frame_id, int slot,
2369 JDWP::JdwpTag tag, uint64_t value, size_t width) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002370 struct SetLocalVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -08002371 SetLocalVisitor(Thread* thread, Context* context,
Ian Rogers0399dde2012-06-06 17:09:28 -07002372 JDWP::FrameId frame_id, int slot, JDWP::JdwpTag tag, uint64_t value,
Ian Rogersca190662012-06-26 15:45:57 -07002373 size_t width)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002374 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08002375 : StackVisitor(thread, context),
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002376 frame_id_(frame_id), slot_(slot), tag_(tag), value_(value), width_(width),
2377 error_(JDWP::ERR_NONE) {}
Ian Rogersca190662012-06-26 15:45:57 -07002378
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002379 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2380 // annotalysis.
2381 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07002382 if (GetFrameId() != frame_id_) {
2383 return true; // Not our frame, carry on.
2384 }
2385 // TODO: check that the tag is compatible with the actual type of the slot!
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002386 // TODO: check slot is valid for this method or return INVALID_SLOT error.
Brian Carlstromea46f952013-07-30 01:26:50 -07002387 mirror::ArtMethod* m = GetMethod();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002388 if (m->IsNative()) {
2389 // We can't read local value from native method.
2390 error_ = JDWP::ERR_OPAQUE_FRAME;
2391 return false;
2392 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002393 uint16_t reg = DemangleSlot(slot_, m);
2394
2395 switch (tag_) {
2396 case JDWP::JT_BOOLEAN:
2397 case JDWP::JT_BYTE:
2398 CHECK_EQ(width_, 1U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002399 SetVReg(m, reg, static_cast<uint32_t>(value_), kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002400 break;
2401 case JDWP::JT_SHORT:
2402 case JDWP::JT_CHAR:
2403 CHECK_EQ(width_, 2U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002404 SetVReg(m, reg, static_cast<uint32_t>(value_), kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002405 break;
2406 case JDWP::JT_INT:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002407 CHECK_EQ(width_, 4U);
2408 SetVReg(m, reg, static_cast<uint32_t>(value_), kIntVReg);
2409 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002410 case JDWP::JT_FLOAT:
2411 CHECK_EQ(width_, 4U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002412 SetVReg(m, reg, static_cast<uint32_t>(value_), kFloatVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002413 break;
2414 case JDWP::JT_ARRAY:
2415 case JDWP::JT_OBJECT:
2416 case JDWP::JT_STRING:
2417 {
2418 CHECK_EQ(width_, sizeof(JDWP::ObjectId));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002419 mirror::Object* o = gRegistry->Get<mirror::Object*>(static_cast<JDWP::ObjectId>(value_));
Elliott Hughes64f574f2013-02-20 14:57:12 -08002420 if (o == ObjectRegistry::kInvalidObject) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002421 UNIMPLEMENTED(FATAL) << "return an error code when given an invalid object to store";
2422 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002423 SetVReg(m, reg, static_cast<uint32_t>(reinterpret_cast<uintptr_t>(o)), kReferenceVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002424 }
2425 break;
2426 case JDWP::JT_DOUBLE:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002427 CHECK_EQ(width_, 8U);
2428 SetVReg(m, reg, static_cast<uint32_t>(value_), kDoubleLoVReg);
2429 SetVReg(m, reg + 1, static_cast<uint32_t>(value_ >> 32), kDoubleHiVReg);
2430 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002431 case JDWP::JT_LONG:
2432 CHECK_EQ(width_, 8U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002433 SetVReg(m, reg, static_cast<uint32_t>(value_), kLongLoVReg);
2434 SetVReg(m, reg + 1, static_cast<uint32_t>(value_ >> 32), kLongHiVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002435 break;
2436 default:
2437 LOG(FATAL) << "Unknown tag " << tag_;
2438 break;
2439 }
2440 return false;
2441 }
2442
2443 const JDWP::FrameId frame_id_;
2444 const int slot_;
2445 const JDWP::JdwpTag tag_;
2446 const uint64_t value_;
2447 const size_t width_;
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002448 JDWP::JdwpError error_;
Ian Rogers0399dde2012-06-06 17:09:28 -07002449 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002450
2451 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08002452 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002453 Thread* thread;
2454 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
2455 if (error != JDWP::ERR_NONE) {
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002456 return error;
Elliott Hughes221229c2013-01-08 18:17:50 -08002457 }
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002458 // TODO check thread is suspended by the debugger ?
Elliott Hughes08fc03a2012-06-26 17:34:00 -07002459 UniquePtr<Context> context(Context::Create());
Ian Rogers7a22fa62013-01-23 12:16:16 -08002460 SetLocalVisitor visitor(thread, context.get(), frame_id, slot, tag, value, width);
Ian Rogers0399dde2012-06-06 17:09:28 -07002461 visitor.WalkStack();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002462 return visitor.error_;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002463}
2464
Ian Rogersef7d42f2014-01-06 12:55:46 -08002465void Dbg::PostLocationEvent(mirror::ArtMethod* m, int dex_pc, mirror::Object* this_object,
Jeff Hao579b0242013-11-18 13:16:49 -08002466 int event_flags, const JValue* return_value) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002467 JDWP::JdwpLocation location;
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002468 SetLocation(location, m, dex_pc);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002469
Elliott Hughes64f574f2013-02-20 14:57:12 -08002470 // If 'this_object' isn't already in the registry, we know that we're not looking for it,
2471 // so there's no point adding it to the registry and burning through ids.
2472 JDWP::ObjectId this_id = 0;
2473 if (gRegistry->Contains(this_object)) {
2474 this_id = gRegistry->Add(this_object);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002475 }
Jeff Hao579b0242013-11-18 13:16:49 -08002476 gJdwpState->PostLocationEvent(&location, this_id, event_flags, return_value);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002477}
2478
Ian Rogers62d6c772013-02-27 08:32:07 -08002479void Dbg::PostException(Thread* thread, const ThrowLocation& throw_location,
Brian Carlstromea46f952013-07-30 01:26:50 -07002480 mirror::ArtMethod* catch_method,
Elliott Hughes64f574f2013-02-20 14:57:12 -08002481 uint32_t catch_dex_pc, mirror::Throwable* exception_object) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002482 if (!IsDebuggerActive()) {
Ian Rogers0ad5bb82011-12-07 10:16:32 -08002483 return;
2484 }
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002485
Ian Rogers62d6c772013-02-27 08:32:07 -08002486 JDWP::JdwpLocation jdwp_throw_location;
2487 SetLocation(jdwp_throw_location, throw_location.GetMethod(), throw_location.GetDexPc());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002488 JDWP::JdwpLocation catch_location;
Elliott Hughescaf76542012-06-28 16:08:22 -07002489 SetLocation(catch_location, catch_method, catch_dex_pc);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002490
2491 // We need 'this' for InstanceOnly filters.
Ian Rogers62d6c772013-02-27 08:32:07 -08002492 JDWP::ObjectId this_id = gRegistry->Add(throw_location.GetThis());
Elliott Hughes64f574f2013-02-20 14:57:12 -08002493 JDWP::ObjectId exception_id = gRegistry->Add(exception_object);
2494 JDWP::RefTypeId exception_class_id = gRegistry->AddRefType(exception_object->GetClass());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002495
Ian Rogers62d6c772013-02-27 08:32:07 -08002496 gJdwpState->PostException(&jdwp_throw_location, exception_id, exception_class_id, &catch_location,
2497 this_id);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002498}
2499
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002500void Dbg::PostClassPrepare(mirror::Class* c) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002501 if (!IsDebuggerActive()) {
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002502 return;
2503 }
2504
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08002505 // OLD-TODO - we currently always send both "verified" and "prepared" since
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002506 // debuggers seem to like that. There might be some advantage to honesty,
2507 // since the class may not yet be verified.
2508 int state = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
Sebastien Hertz4d8fd492014-03-28 16:29:41 +01002509 JDWP::JdwpTypeTag tag = GetTypeTag(c);
Ian Rogersfc0e94b2013-09-23 23:51:32 -07002510 gJdwpState->PostClassPrepare(tag, gRegistry->Add(c),
Ian Rogersdfb325e2013-10-30 01:00:44 -07002511 ClassHelper(c).GetDescriptor(), state);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002512}
2513
Ian Rogers62d6c772013-02-27 08:32:07 -08002514void Dbg::UpdateDebugger(Thread* thread, mirror::Object* this_object,
Ian Rogersef7d42f2014-01-06 12:55:46 -08002515 mirror::ArtMethod* m, uint32_t dex_pc) {
Ian Rogers62d6c772013-02-27 08:32:07 -08002516 if (!IsDebuggerActive() || dex_pc == static_cast<uint32_t>(-2) /* fake method exit */) {
Elliott Hughes2aa2e392012-02-17 17:15:43 -08002517 return;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002518 }
2519
Elliott Hughes2aa2e392012-02-17 17:15:43 -08002520 int event_flags = 0;
2521
Elliott Hughes86964332012-02-15 19:37:42 -08002522 if (IsBreakpoint(m, dex_pc)) {
2523 event_flags |= kBreakpoint;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002524 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002525
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002526 // If the debugger is single-stepping one of our threads, check to
2527 // see if we're that thread and we've reached a step point.
2528 const SingleStepControl* single_step_control = thread->GetSingleStepControl();
2529 DCHECK(single_step_control != nullptr);
2530 if (single_step_control->is_active) {
2531 CHECK(!m->IsNative());
2532 if (single_step_control->step_depth == JDWP::SD_INTO) {
2533 // Step into method calls. We break when the line number
2534 // or method pointer changes. If we're in SS_MIN mode, we
2535 // always stop.
2536 if (single_step_control->method != m) {
2537 event_flags |= kSingleStep;
2538 VLOG(jdwp) << "SS new method";
2539 } else if (single_step_control->step_size == JDWP::SS_MIN) {
2540 event_flags |= kSingleStep;
2541 VLOG(jdwp) << "SS new instruction";
Sebastien Hertzbb43b432014-04-14 11:59:08 +02002542 } else if (single_step_control->ContainsDexPc(dex_pc)) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002543 event_flags |= kSingleStep;
2544 VLOG(jdwp) << "SS new line";
2545 }
2546 } else if (single_step_control->step_depth == JDWP::SD_OVER) {
2547 // Step over method calls. We break when the line number is
2548 // different and the frame depth is <= the original frame
2549 // depth. (We can't just compare on the method, because we
2550 // might get unrolled past it by an exception, and it's tricky
2551 // to identify recursion.)
2552
2553 int stack_depth = GetStackDepth(thread);
2554
2555 if (stack_depth < single_step_control->stack_depth) {
2556 // Popped up one or more frames, always trigger.
2557 event_flags |= kSingleStep;
2558 VLOG(jdwp) << "SS method pop";
2559 } else if (stack_depth == single_step_control->stack_depth) {
2560 // Same depth, see if we moved.
2561 if (single_step_control->step_size == JDWP::SS_MIN) {
Elliott Hughes86964332012-02-15 19:37:42 -08002562 event_flags |= kSingleStep;
2563 VLOG(jdwp) << "SS new instruction";
Sebastien Hertzbb43b432014-04-14 11:59:08 +02002564 } else if (single_step_control->ContainsDexPc(dex_pc)) {
Elliott Hughes2435a572012-02-17 16:07:41 -08002565 event_flags |= kSingleStep;
2566 VLOG(jdwp) << "SS new line";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002567 }
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002568 }
2569 } else {
2570 CHECK_EQ(single_step_control->step_depth, JDWP::SD_OUT);
2571 // Return from the current method. We break when the frame
2572 // depth pops up.
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002573
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002574 // This differs from the "method exit" break in that it stops
2575 // with the PC at the next instruction in the returned-to
2576 // function, rather than the end of the returning function.
Elliott Hughes86964332012-02-15 19:37:42 -08002577
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002578 int stack_depth = GetStackDepth(thread);
2579 if (stack_depth < single_step_control->stack_depth) {
2580 event_flags |= kSingleStep;
2581 VLOG(jdwp) << "SS method pop";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002582 }
2583 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002584 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002585
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002586 // If there's something interesting going on, see if it matches one
2587 // of the debugger filters.
2588 if (event_flags != 0) {
Jeff Hao579b0242013-11-18 13:16:49 -08002589 Dbg::PostLocationEvent(m, dex_pc, this_object, event_flags, nullptr);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002590 }
2591}
2592
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002593// Process request while all mutator threads are suspended.
2594void Dbg::ProcessDeoptimizationRequest(const DeoptimizationRequest& request) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002595 instrumentation::Instrumentation* instrumentation = Runtime::Current()->GetInstrumentation();
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002596 switch (request.kind) {
2597 case DeoptimizationRequest::kNothing:
2598 LOG(WARNING) << "Ignoring empty deoptimization request.";
2599 break;
2600 case DeoptimizationRequest::kFullDeoptimization:
2601 VLOG(jdwp) << "Deoptimize the world";
2602 instrumentation->DeoptimizeEverything();
2603 break;
2604 case DeoptimizationRequest::kFullUndeoptimization:
2605 VLOG(jdwp) << "Undeoptimize the world";
2606 instrumentation->UndeoptimizeEverything();
2607 break;
2608 case DeoptimizationRequest::kSelectiveDeoptimization:
2609 VLOG(jdwp) << "Deoptimize method " << PrettyMethod(request.method);
2610 instrumentation->Deoptimize(request.method);
2611 break;
2612 case DeoptimizationRequest::kSelectiveUndeoptimization:
2613 VLOG(jdwp) << "Undeoptimize method " << PrettyMethod(request.method);
2614 instrumentation->Undeoptimize(request.method);
2615 break;
2616 default:
2617 LOG(FATAL) << "Unsupported deoptimization request kind " << request.kind;
2618 break;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002619 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002620}
2621
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002622void Dbg::RequestDeoptimization(const DeoptimizationRequest& req) {
2623 if (req.kind == DeoptimizationRequest::kNothing) {
2624 // Nothing to do.
2625 return;
2626 }
2627 MutexLock mu(Thread::Current(), *deoptimization_lock_);
2628 switch (req.kind) {
2629 case DeoptimizationRequest::kFullDeoptimization: {
2630 DCHECK(req.method == nullptr);
2631 if (full_deoptimization_event_count_ == 0) {
2632 VLOG(jdwp) << "Request full deoptimization";
2633 deoptimization_requests_.push_back(req);
2634 }
2635 ++full_deoptimization_event_count_;
2636 break;
2637 }
2638 case DeoptimizationRequest::kFullUndeoptimization: {
2639 DCHECK(req.method == nullptr);
2640 DCHECK_GT(full_deoptimization_event_count_, 0U);
2641 --full_deoptimization_event_count_;
2642 if (full_deoptimization_event_count_ == 0) {
2643 VLOG(jdwp) << "Request full undeoptimization";
2644 deoptimization_requests_.push_back(req);
2645 }
2646 break;
2647 }
2648 case DeoptimizationRequest::kSelectiveDeoptimization: {
2649 DCHECK(req.method != nullptr);
2650 VLOG(jdwp) << "Request deoptimization of " << PrettyMethod(req.method);
2651 deoptimization_requests_.push_back(req);
2652 break;
2653 }
2654 case DeoptimizationRequest::kSelectiveUndeoptimization: {
2655 DCHECK(req.method != nullptr);
2656 VLOG(jdwp) << "Request undeoptimization of " << PrettyMethod(req.method);
2657 deoptimization_requests_.push_back(req);
2658 break;
2659 }
2660 default: {
2661 LOG(FATAL) << "Unknown deoptimization request kind " << req.kind;
2662 break;
2663 }
2664 }
2665}
2666
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002667void Dbg::ManageDeoptimization() {
2668 Thread* const self = Thread::Current();
2669 {
2670 // Avoid suspend/resume if there is no pending request.
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002671 MutexLock mu(self, *deoptimization_lock_);
2672 if (deoptimization_requests_.empty()) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002673 return;
2674 }
2675 }
2676 CHECK_EQ(self->GetState(), kRunnable);
2677 self->TransitionFromRunnableToSuspended(kWaitingForDeoptimization);
2678 // We need to suspend mutator threads first.
2679 Runtime* const runtime = Runtime::Current();
2680 runtime->GetThreadList()->SuspendAll();
2681 const ThreadState old_state = self->SetStateUnsafe(kRunnable);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002682 {
2683 MutexLock mu(self, *deoptimization_lock_);
2684 for (const DeoptimizationRequest& request : deoptimization_requests_) {
2685 ProcessDeoptimizationRequest(request);
2686 }
2687 deoptimization_requests_.clear();
2688 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002689 CHECK_EQ(self->SetStateUnsafe(old_state), kRunnable);
2690 runtime->GetThreadList()->ResumeAll();
2691 self->TransitionFromSuspendedToRunnable();
2692}
2693
Sebastien Hertza76a6d42014-03-20 16:40:17 +01002694static bool IsMethodPossiblyInlined(Thread* self, mirror::ArtMethod* m)
2695 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2696 MethodHelper mh(m);
2697 const DexFile::CodeItem* code_item = mh.GetCodeItem();
2698 if (code_item == nullptr) {
2699 // TODO We should not be asked to watch location in a native or abstract method so the code item
2700 // should never be null. We could just check we never encounter this case.
2701 return false;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002702 }
Sebastien Hertza76a6d42014-03-20 16:40:17 +01002703 SirtRef<mirror::DexCache> dex_cache(self, mh.GetDexCache());
2704 SirtRef<mirror::ClassLoader> class_loader(self, mh.GetClassLoader());
2705 verifier::MethodVerifier verifier(&mh.GetDexFile(), &dex_cache, &class_loader,
2706 &mh.GetClassDef(), code_item, m->GetDexMethodIndex(), m,
2707 m->GetAccessFlags(), false, true);
2708 // Note: we don't need to verify the method.
2709 return InlineMethodAnalyser::AnalyseMethodCode(&verifier, nullptr);
2710}
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002711
Sebastien Hertza76a6d42014-03-20 16:40:17 +01002712static const Breakpoint* FindFirstBreakpointForMethod(mirror::ArtMethod* m)
2713 EXCLUSIVE_LOCKS_REQUIRED(Locks::breakpoint_lock_) {
2714 for (const Breakpoint& breakpoint : gBreakpoints) {
2715 if (breakpoint.method == m) {
2716 return &breakpoint;
2717 }
2718 }
2719 return nullptr;
2720}
2721
2722// Sanity checks all existing breakpoints on the same method.
2723static void SanityCheckExistingBreakpoints(mirror::ArtMethod* m, bool need_full_deoptimization)
2724 EXCLUSIVE_LOCKS_REQUIRED(Locks::breakpoint_lock_) {
2725 if (kIsDebugBuild) {
2726 for (const Breakpoint& breakpoint : gBreakpoints) {
2727 CHECK_EQ(need_full_deoptimization, breakpoint.need_full_deoptimization);
2728 }
2729 if (need_full_deoptimization) {
2730 // We should have deoptimized everything but not "selectively" deoptimized this method.
2731 CHECK(Runtime::Current()->GetInstrumentation()->AreAllMethodsDeoptimized());
2732 CHECK(!Runtime::Current()->GetInstrumentation()->IsDeoptimized(m));
2733 } else {
2734 // We should have "selectively" deoptimized this method.
2735 // Note: while we have not deoptimized everything for this method, we may have done it for
2736 // another event.
2737 CHECK(Runtime::Current()->GetInstrumentation()->IsDeoptimized(m));
2738 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002739 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002740}
2741
Sebastien Hertza76a6d42014-03-20 16:40:17 +01002742// Installs a breakpoint at the specified location. Also indicates through the deoptimization
2743// request if we need to deoptimize.
2744void Dbg::WatchLocation(const JDWP::JdwpLocation* location, DeoptimizationRequest* req) {
2745 Thread* const self = Thread::Current();
Brian Carlstromea46f952013-07-30 01:26:50 -07002746 mirror::ArtMethod* m = FromMethodId(location->method_id);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01002747 DCHECK(m != nullptr) << "No method for method id " << location->method_id;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002748
Sebastien Hertza76a6d42014-03-20 16:40:17 +01002749 MutexLock mu(self, *Locks::breakpoint_lock_);
2750 const Breakpoint* const existing_breakpoint = FindFirstBreakpointForMethod(m);
2751 bool need_full_deoptimization;
2752 if (existing_breakpoint == nullptr) {
2753 // There is no breakpoint on this method yet: we need to deoptimize. If this method may be
2754 // inlined, we deoptimize everything; otherwise we deoptimize only this method.
2755 need_full_deoptimization = IsMethodPossiblyInlined(self, m);
2756 if (need_full_deoptimization) {
2757 req->kind = DeoptimizationRequest::kFullDeoptimization;
2758 req->method = nullptr;
2759 } else {
2760 req->kind = DeoptimizationRequest::kSelectiveDeoptimization;
2761 req->method = m;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002762 }
Sebastien Hertza76a6d42014-03-20 16:40:17 +01002763 } else {
2764 // There is at least one breakpoint for this method: we don't need to deoptimize.
2765 req->kind = DeoptimizationRequest::kNothing;
2766 req->method = nullptr;
2767
2768 need_full_deoptimization = existing_breakpoint->need_full_deoptimization;
2769 SanityCheckExistingBreakpoints(m, need_full_deoptimization);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002770 }
2771
Sebastien Hertza76a6d42014-03-20 16:40:17 +01002772 gBreakpoints.push_back(Breakpoint(m, location->dex_pc, need_full_deoptimization));
2773 VLOG(jdwp) << "Set breakpoint #" << (gBreakpoints.size() - 1) << ": "
2774 << gBreakpoints[gBreakpoints.size() - 1];
2775}
2776
2777// Uninstalls a breakpoint at the specified location. Also indicates through the deoptimization
2778// request if we need to undeoptimize.
2779void Dbg::UnwatchLocation(const JDWP::JdwpLocation* location, DeoptimizationRequest* req) {
2780 mirror::ArtMethod* m = FromMethodId(location->method_id);
2781 DCHECK(m != nullptr) << "No method for method id " << location->method_id;
2782
2783 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
2784 bool need_full_deoptimization = false;
2785 for (size_t i = 0, e = gBreakpoints.size(); i < e; ++i) {
2786 if (gBreakpoints[i].method == m && gBreakpoints[i].dex_pc == location->dex_pc) {
2787 VLOG(jdwp) << "Removed breakpoint #" << i << ": " << gBreakpoints[i];
2788 need_full_deoptimization = gBreakpoints[i].need_full_deoptimization;
2789 DCHECK_NE(need_full_deoptimization, Runtime::Current()->GetInstrumentation()->IsDeoptimized(m));
2790 gBreakpoints.erase(gBreakpoints.begin() + i);
2791 break;
2792 }
2793 }
2794 const Breakpoint* const existing_breakpoint = FindFirstBreakpointForMethod(m);
2795 if (existing_breakpoint == nullptr) {
2796 // There is no more breakpoint on this method: we need to undeoptimize.
2797 if (need_full_deoptimization) {
2798 // This method required full deoptimization: we need to undeoptimize everything.
2799 req->kind = DeoptimizationRequest::kFullUndeoptimization;
2800 req->method = nullptr;
2801 } else {
2802 // This method required selective deoptimization: we need to undeoptimize only that method.
2803 req->kind = DeoptimizationRequest::kSelectiveUndeoptimization;
2804 req->method = m;
2805 }
2806 } else {
2807 // There is at least one breakpoint for this method: we don't need to undeoptimize.
2808 req->kind = DeoptimizationRequest::kNothing;
2809 req->method = nullptr;
2810 SanityCheckExistingBreakpoints(m, need_full_deoptimization);
Elliott Hughes86964332012-02-15 19:37:42 -08002811 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002812}
2813
Jeff Hao449db332013-04-12 18:30:52 -07002814// Scoped utility class to suspend a thread so that we may do tasks such as walk its stack. Doesn't
2815// cause suspension if the thread is the current thread.
2816class ScopedThreadSuspension {
2817 public:
Ian Rogers33e95662013-05-20 20:29:14 -07002818 ScopedThreadSuspension(Thread* self, JDWP::ObjectId thread_id)
Sebastien Hertz52d131d2014-03-13 16:17:40 +01002819 LOCKS_EXCLUDED(Locks::thread_list_lock_)
Ian Rogers33e95662013-05-20 20:29:14 -07002820 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) :
Jeff Hao449db332013-04-12 18:30:52 -07002821 thread_(NULL),
2822 error_(JDWP::ERR_NONE),
2823 self_suspend_(false),
Ian Rogers33e95662013-05-20 20:29:14 -07002824 other_suspend_(false) {
Jeff Hao449db332013-04-12 18:30:52 -07002825 ScopedObjectAccessUnchecked soa(self);
2826 {
2827 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
2828 error_ = DecodeThread(soa, thread_id, thread_);
2829 }
2830 if (error_ == JDWP::ERR_NONE) {
2831 if (thread_ == soa.Self()) {
2832 self_suspend_ = true;
2833 } else {
2834 soa.Self()->TransitionFromRunnableToSuspended(kWaitingForDebuggerSuspension);
2835 jobject thread_peer = gRegistry->GetJObject(thread_id);
2836 bool timed_out;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07002837 Thread* suspended_thread = ThreadList::SuspendThreadByPeer(thread_peer, true, true,
2838 &timed_out);
Jeff Hao449db332013-04-12 18:30:52 -07002839 CHECK_EQ(soa.Self()->TransitionFromSuspendedToRunnable(), kWaitingForDebuggerSuspension);
2840 if (suspended_thread == NULL) {
2841 // Thread terminated from under us while suspending.
2842 error_ = JDWP::ERR_INVALID_THREAD;
2843 } else {
2844 CHECK_EQ(suspended_thread, thread_);
2845 other_suspend_ = true;
2846 }
2847 }
2848 }
Elliott Hughes2435a572012-02-17 16:07:41 -08002849 }
Elliott Hughes86964332012-02-15 19:37:42 -08002850
Jeff Hao449db332013-04-12 18:30:52 -07002851 Thread* GetThread() const {
2852 return thread_;
2853 }
2854
2855 JDWP::JdwpError GetError() const {
2856 return error_;
2857 }
2858
2859 ~ScopedThreadSuspension() {
2860 if (other_suspend_) {
2861 Runtime::Current()->GetThreadList()->Resume(thread_, true);
2862 }
2863 }
2864
2865 private:
2866 Thread* thread_;
2867 JDWP::JdwpError error_;
2868 bool self_suspend_;
2869 bool other_suspend_;
2870};
2871
2872JDWP::JdwpError Dbg::ConfigureStep(JDWP::ObjectId thread_id, JDWP::JdwpStepSize step_size,
2873 JDWP::JdwpStepDepth step_depth) {
2874 Thread* self = Thread::Current();
2875 ScopedThreadSuspension sts(self, thread_id);
2876 if (sts.GetError() != JDWP::ERR_NONE) {
2877 return sts.GetError();
2878 }
2879
Elliott Hughes2435a572012-02-17 16:07:41 -08002880 //
2881 // Work out what Method* we're in, the current line number, and how deep the stack currently
2882 // is for step-out.
2883 //
2884
Ian Rogers0399dde2012-06-06 17:09:28 -07002885 struct SingleStepStackVisitor : public StackVisitor {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002886 explicit SingleStepStackVisitor(Thread* thread, SingleStepControl* single_step_control,
2887 int32_t* line_number)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002888 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002889 : StackVisitor(thread, NULL), single_step_control_(single_step_control),
2890 line_number_(line_number) {
2891 DCHECK_EQ(single_step_control_, thread->GetSingleStepControl());
2892 single_step_control_->method = NULL;
2893 single_step_control_->stack_depth = 0;
Elliott Hughes86964332012-02-15 19:37:42 -08002894 }
Ian Rogersca190662012-06-26 15:45:57 -07002895
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002896 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2897 // annotalysis.
2898 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002899 mirror::ArtMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07002900 if (!m->IsRuntimeMethod()) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002901 ++single_step_control_->stack_depth;
2902 if (single_step_control_->method == NULL) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002903 mirror::DexCache* dex_cache = m->GetDeclaringClass()->GetDexCache();
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002904 single_step_control_->method = m;
2905 *line_number_ = -1;
Elliott Hughes2435a572012-02-17 16:07:41 -08002906 if (dex_cache != NULL) {
Ian Rogers4445a7e2012-10-05 17:19:13 -07002907 const DexFile& dex_file = *dex_cache->GetDexFile();
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002908 *line_number_ = dex_file.GetLineNumFromPC(m, GetDexPc());
Elliott Hughes2435a572012-02-17 16:07:41 -08002909 }
Elliott Hughes86964332012-02-15 19:37:42 -08002910 }
2911 }
Elliott Hughes530fa002012-03-12 11:44:49 -07002912 return true;
Elliott Hughes86964332012-02-15 19:37:42 -08002913 }
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002914
2915 SingleStepControl* const single_step_control_;
2916 int32_t* const line_number_;
Elliott Hughes86964332012-02-15 19:37:42 -08002917 };
Jeff Hao449db332013-04-12 18:30:52 -07002918
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002919 Thread* const thread = sts.GetThread();
2920 SingleStepControl* const single_step_control = thread->GetSingleStepControl();
2921 DCHECK(single_step_control != nullptr);
2922 int32_t line_number = -1;
2923 SingleStepStackVisitor visitor(thread, single_step_control, &line_number);
Ian Rogers0399dde2012-06-06 17:09:28 -07002924 visitor.WalkStack();
Elliott Hughes86964332012-02-15 19:37:42 -08002925
Elliott Hughes2435a572012-02-17 16:07:41 -08002926 //
2927 // Find the dex_pc values that correspond to the current line, for line-based single-stepping.
2928 //
2929
2930 struct DebugCallbackContext {
Sebastien Hertzbb43b432014-04-14 11:59:08 +02002931 explicit DebugCallbackContext(SingleStepControl* single_step_control, int32_t line_number,
2932 const DexFile::CodeItem* code_item)
2933 : single_step_control_(single_step_control), line_number_(line_number), code_item_(code_item),
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002934 last_pc_valid(false), last_pc(0) {
Elliott Hughes2435a572012-02-17 16:07:41 -08002935 }
2936
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002937 static bool Callback(void* raw_context, uint32_t address, uint32_t line_number) {
Elliott Hughes2435a572012-02-17 16:07:41 -08002938 DebugCallbackContext* context = reinterpret_cast<DebugCallbackContext*>(raw_context);
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002939 if (static_cast<int32_t>(line_number) == context->line_number_) {
Elliott Hughes2435a572012-02-17 16:07:41 -08002940 if (!context->last_pc_valid) {
2941 // Everything from this address until the next line change is ours.
2942 context->last_pc = address;
2943 context->last_pc_valid = true;
2944 }
2945 // Otherwise, if we're already in a valid range for this line,
2946 // just keep going (shouldn't really happen)...
Brian Carlstrom7934ac22013-07-26 10:54:15 -07002947 } else if (context->last_pc_valid) { // and the line number is new
Elliott Hughes2435a572012-02-17 16:07:41 -08002948 // Add everything from the last entry up until here to the set
2949 for (uint32_t dex_pc = context->last_pc; dex_pc < address; ++dex_pc) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002950 context->single_step_control_->dex_pcs.insert(dex_pc);
Elliott Hughes2435a572012-02-17 16:07:41 -08002951 }
2952 context->last_pc_valid = false;
2953 }
Brian Carlstrom7934ac22013-07-26 10:54:15 -07002954 return false; // There may be multiple entries for any given line.
Elliott Hughes2435a572012-02-17 16:07:41 -08002955 }
2956
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002957 ~DebugCallbackContext() {
Elliott Hughes2435a572012-02-17 16:07:41 -08002958 // If the line number was the last in the position table...
2959 if (last_pc_valid) {
Sebastien Hertzbb43b432014-04-14 11:59:08 +02002960 size_t end = code_item_->insns_size_in_code_units_;
Elliott Hughes2435a572012-02-17 16:07:41 -08002961 for (uint32_t dex_pc = last_pc; dex_pc < end; ++dex_pc) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002962 single_step_control_->dex_pcs.insert(dex_pc);
Elliott Hughes2435a572012-02-17 16:07:41 -08002963 }
2964 }
2965 }
2966
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002967 SingleStepControl* const single_step_control_;
2968 const int32_t line_number_;
Sebastien Hertzbb43b432014-04-14 11:59:08 +02002969 const DexFile::CodeItem* const code_item_;
Elliott Hughes2435a572012-02-17 16:07:41 -08002970 bool last_pc_valid;
2971 uint32_t last_pc;
2972 };
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002973 single_step_control->dex_pcs.clear();
Ian Rogersef7d42f2014-01-06 12:55:46 -08002974 mirror::ArtMethod* m = single_step_control->method;
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002975 if (!m->IsNative()) {
Elliott Hughes3e2e1a22012-02-21 11:33:41 -08002976 MethodHelper mh(m);
Sebastien Hertzbb43b432014-04-14 11:59:08 +02002977 const DexFile::CodeItem* const code_item = mh.GetCodeItem();
2978 DebugCallbackContext context(single_step_control, line_number, code_item);
2979 mh.GetDexFile().DecodeDebugInfo(code_item, m->IsStatic(), m->GetDexMethodIndex(),
Elliott Hughes3e2e1a22012-02-21 11:33:41 -08002980 DebugCallbackContext::Callback, NULL, &context);
2981 }
Elliott Hughes2435a572012-02-17 16:07:41 -08002982
2983 //
2984 // Everything else...
2985 //
2986
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002987 single_step_control->step_size = step_size;
2988 single_step_control->step_depth = step_depth;
2989 single_step_control->is_active = true;
Elliott Hughes86964332012-02-15 19:37:42 -08002990
Elliott Hughes2435a572012-02-17 16:07:41 -08002991 if (VLOG_IS_ON(jdwp)) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002992 VLOG(jdwp) << "Single-step thread: " << *thread;
2993 VLOG(jdwp) << "Single-step step size: " << single_step_control->step_size;
2994 VLOG(jdwp) << "Single-step step depth: " << single_step_control->step_depth;
2995 VLOG(jdwp) << "Single-step current method: " << PrettyMethod(single_step_control->method);
2996 VLOG(jdwp) << "Single-step current line: " << line_number;
2997 VLOG(jdwp) << "Single-step current stack depth: " << single_step_control->stack_depth;
Elliott Hughes2435a572012-02-17 16:07:41 -08002998 VLOG(jdwp) << "Single-step dex_pc values:";
Sebastien Hertzbb43b432014-04-14 11:59:08 +02002999 for (uint32_t dex_pc : single_step_control->dex_pcs) {
3000 VLOG(jdwp) << StringPrintf(" %#x", dex_pc);
Elliott Hughes2435a572012-02-17 16:07:41 -08003001 }
3002 }
3003
3004 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003005}
3006
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003007void Dbg::UnconfigureStep(JDWP::ObjectId thread_id) {
3008 ScopedObjectAccessUnchecked soa(Thread::Current());
3009 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
3010 Thread* thread;
3011 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
Sebastien Hertz87118ed2013-11-26 17:57:18 +01003012 if (error == JDWP::ERR_NONE) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003013 SingleStepControl* single_step_control = thread->GetSingleStepControl();
3014 DCHECK(single_step_control != nullptr);
Sebastien Hertzbb43b432014-04-14 11:59:08 +02003015 single_step_control->Clear();
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003016 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003017}
3018
Elliott Hughes45651fd2012-02-21 15:48:20 -08003019static char JdwpTagToShortyChar(JDWP::JdwpTag tag) {
3020 switch (tag) {
3021 default:
3022 LOG(FATAL) << "unknown JDWP tag: " << PrintableChar(tag);
3023
3024 // Primitives.
3025 case JDWP::JT_BYTE: return 'B';
3026 case JDWP::JT_CHAR: return 'C';
3027 case JDWP::JT_FLOAT: return 'F';
3028 case JDWP::JT_DOUBLE: return 'D';
3029 case JDWP::JT_INT: return 'I';
3030 case JDWP::JT_LONG: return 'J';
3031 case JDWP::JT_SHORT: return 'S';
3032 case JDWP::JT_VOID: return 'V';
3033 case JDWP::JT_BOOLEAN: return 'Z';
3034
3035 // Reference types.
3036 case JDWP::JT_ARRAY:
3037 case JDWP::JT_OBJECT:
3038 case JDWP::JT_STRING:
3039 case JDWP::JT_THREAD:
3040 case JDWP::JT_THREAD_GROUP:
3041 case JDWP::JT_CLASS_LOADER:
3042 case JDWP::JT_CLASS_OBJECT:
3043 return 'L';
3044 }
3045}
3046
Elliott Hughes88d63092013-01-09 09:55:54 -08003047JDWP::JdwpError Dbg::InvokeMethod(JDWP::ObjectId thread_id, JDWP::ObjectId object_id,
3048 JDWP::RefTypeId class_id, JDWP::MethodId method_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003049 uint32_t arg_count, uint64_t* arg_values,
3050 JDWP::JdwpTag* arg_types, uint32_t options,
3051 JDWP::JdwpTag* pResultTag, uint64_t* pResultValue,
3052 JDWP::ObjectId* pExceptionId) {
Elliott Hughesd07986f2011-12-06 18:27:45 -08003053 ThreadList* thread_list = Runtime::Current()->GetThreadList();
3054
3055 Thread* targetThread = NULL;
3056 DebugInvokeReq* req = NULL;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003057 Thread* self = Thread::Current();
Elliott Hughesd07986f2011-12-06 18:27:45 -08003058 {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003059 ScopedObjectAccessUnchecked soa(self);
Ian Rogers50b35e22012-10-04 10:09:15 -07003060 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08003061 JDWP::JdwpError error = DecodeThread(soa, thread_id, targetThread);
3062 if (error != JDWP::ERR_NONE) {
3063 LOG(ERROR) << "InvokeMethod request for invalid thread id " << thread_id;
3064 return error;
Elliott Hughesd07986f2011-12-06 18:27:45 -08003065 }
3066 req = targetThread->GetInvokeReq();
3067 if (!req->ready) {
3068 LOG(ERROR) << "InvokeMethod request for thread not stopped by event: " << *targetThread;
3069 return JDWP::ERR_INVALID_THREAD;
3070 }
3071
3072 /*
3073 * We currently have a bug where we don't successfully resume the
3074 * target thread if the suspend count is too deep. We're expected to
3075 * require one "resume" for each "suspend", but when asked to execute
3076 * a method we have to resume fully and then re-suspend it back to the
3077 * same level. (The easiest way to cause this is to type "suspend"
3078 * multiple times in jdb.)
3079 *
3080 * It's unclear what this means when the event specifies "resume all"
3081 * and some threads are suspended more deeply than others. This is
3082 * a rare problem, so for now we just prevent it from hanging forever
3083 * by rejecting the method invocation request. Without this, we will
3084 * be stuck waiting on a suspended thread.
3085 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003086 int suspend_count;
3087 {
Ian Rogers50b35e22012-10-04 10:09:15 -07003088 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003089 suspend_count = targetThread->GetSuspendCount();
3090 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08003091 if (suspend_count > 1) {
3092 LOG(ERROR) << *targetThread << " suspend count too deep for method invocation: " << suspend_count;
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003093 return JDWP::ERR_THREAD_SUSPENDED; // Probably not expected here.
Elliott Hughesd07986f2011-12-06 18:27:45 -08003094 }
3095
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08003096 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003097 mirror::Object* receiver = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08003098 if (receiver == ObjectRegistry::kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08003099 return JDWP::ERR_INVALID_OBJECT;
3100 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003101
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003102 mirror::Object* thread = gRegistry->Get<mirror::Object*>(thread_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08003103 if (thread == ObjectRegistry::kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08003104 return JDWP::ERR_INVALID_OBJECT;
3105 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003106 // TODO: check that 'thread' is actually a java.lang.Thread!
3107
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003108 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes45651fd2012-02-21 15:48:20 -08003109 if (c == NULL) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08003110 return status;
3111 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003112
Brian Carlstromea46f952013-07-30 01:26:50 -07003113 mirror::ArtMethod* m = FromMethodId(method_id);
Elliott Hughes45651fd2012-02-21 15:48:20 -08003114 if (m->IsStatic() != (receiver == NULL)) {
3115 return JDWP::ERR_INVALID_METHODID;
3116 }
3117 if (m->IsStatic()) {
3118 if (m->GetDeclaringClass() != c) {
3119 return JDWP::ERR_INVALID_METHODID;
3120 }
3121 } else {
3122 if (!m->GetDeclaringClass()->IsAssignableFrom(c)) {
3123 return JDWP::ERR_INVALID_METHODID;
3124 }
3125 }
3126
3127 // Check the argument list matches the method.
3128 MethodHelper mh(m);
3129 if (mh.GetShortyLength() - 1 != arg_count) {
3130 return JDWP::ERR_ILLEGAL_ARGUMENT;
3131 }
3132 const char* shorty = mh.GetShorty();
Elliott Hughes09201632013-04-15 15:50:07 -07003133 const DexFile::TypeList* types = mh.GetParameterTypeList();
Elliott Hughes45651fd2012-02-21 15:48:20 -08003134 for (size_t i = 0; i < arg_count; ++i) {
3135 if (shorty[i + 1] != JdwpTagToShortyChar(arg_types[i])) {
3136 return JDWP::ERR_ILLEGAL_ARGUMENT;
3137 }
Elliott Hughes09201632013-04-15 15:50:07 -07003138
3139 if (shorty[i + 1] == 'L') {
3140 // Did we really get an argument of an appropriate reference type?
3141 mirror::Class* parameter_type = mh.GetClassFromTypeIdx(types->GetTypeItem(i).type_idx_);
3142 mirror::Object* argument = gRegistry->Get<mirror::Object*>(arg_values[i]);
3143 if (argument == ObjectRegistry::kInvalidObject) {
3144 return JDWP::ERR_INVALID_OBJECT;
3145 }
Sebastien Hertz0630ab52013-11-28 18:53:35 +01003146 if (argument != NULL && !argument->InstanceOf(parameter_type)) {
Elliott Hughes09201632013-04-15 15:50:07 -07003147 return JDWP::ERR_ILLEGAL_ARGUMENT;
3148 }
3149
3150 // Turn the on-the-wire ObjectId into a jobject.
3151 jvalue& v = reinterpret_cast<jvalue&>(arg_values[i]);
3152 v.l = gRegistry->GetJObject(arg_values[i]);
3153 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003154 }
3155
Sebastien Hertzd38667a2013-11-25 15:43:54 +01003156 req->receiver = receiver;
3157 req->thread = thread;
3158 req->klass = c;
3159 req->method = m;
3160 req->arg_count = arg_count;
3161 req->arg_values = arg_values;
3162 req->options = options;
3163 req->invoke_needed = true;
Elliott Hughesd07986f2011-12-06 18:27:45 -08003164 }
3165
3166 // The fact that we've released the thread list lock is a bit risky --- if the thread goes
3167 // away we're sitting high and dry -- but we must release this before the ResumeAllThreads
3168 // call, and it's unwise to hold it during WaitForSuspend.
3169
3170 {
3171 /*
3172 * We change our (JDWP thread) status, which should be THREAD_RUNNING,
Elliott Hughes81ff3182012-03-23 20:35:56 -07003173 * so we can suspend for a GC if the invoke request causes us to
Elliott Hughesd07986f2011-12-06 18:27:45 -08003174 * run out of memory. It's also a good idea to change it before locking
3175 * the invokeReq mutex, although that should never be held for long.
3176 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003177 self->TransitionFromRunnableToSuspended(kWaitingForDebuggerSend);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003178
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003179 VLOG(jdwp) << " Transferring control to event thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08003180 {
Sebastien Hertzd38667a2013-11-25 15:43:54 +01003181 MutexLock mu(self, req->lock);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003182
3183 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003184 VLOG(jdwp) << " Resuming all threads";
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003185 thread_list->UndoDebuggerSuspensions();
Elliott Hughesd07986f2011-12-06 18:27:45 -08003186 } else {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003187 VLOG(jdwp) << " Resuming event thread only";
Elliott Hughesd07986f2011-12-06 18:27:45 -08003188 thread_list->Resume(targetThread, true);
3189 }
3190
3191 // Wait for the request to finish executing.
Sebastien Hertzd38667a2013-11-25 15:43:54 +01003192 while (req->invoke_needed) {
3193 req->cond.Wait(self);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003194 }
3195 }
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003196 VLOG(jdwp) << " Control has returned from event thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08003197
3198 /* wait for thread to re-suspend itself */
Brian Carlstromdf629502013-07-17 22:39:56 -07003199 SuspendThread(thread_id, false /* request_suspension */);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003200 self->TransitionFromSuspendedToRunnable();
Elliott Hughesd07986f2011-12-06 18:27:45 -08003201 }
3202
3203 /*
3204 * Suspend the threads. We waited for the target thread to suspend
3205 * itself, so all we need to do is suspend the others.
3206 *
3207 * The suspendAllThreads() call will double-suspend the event thread,
3208 * so we want to resume the target thread once to keep the books straight.
3209 */
3210 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003211 self->TransitionFromRunnableToSuspended(kWaitingForDebuggerSuspension);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003212 VLOG(jdwp) << " Suspending all threads";
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003213 thread_list->SuspendAllForDebugger();
3214 self->TransitionFromSuspendedToRunnable();
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003215 VLOG(jdwp) << " Resuming event thread to balance the count";
Elliott Hughesd07986f2011-12-06 18:27:45 -08003216 thread_list->Resume(targetThread, true);
3217 }
3218
3219 // Copy the result.
3220 *pResultTag = req->result_tag;
3221 if (IsPrimitiveTag(req->result_tag)) {
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07003222 *pResultValue = req->result_value.GetJ();
Elliott Hughesd07986f2011-12-06 18:27:45 -08003223 } else {
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07003224 *pResultValue = gRegistry->Add(req->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003225 }
3226 *pExceptionId = req->exception;
3227 return req->error;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003228}
3229
3230void Dbg::ExecuteMethod(DebugInvokeReq* pReq) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003231 ScopedObjectAccess soa(Thread::Current());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003232
Elliott Hughes81ff3182012-03-23 20:35:56 -07003233 // We can be called while an exception is pending. We need
Elliott Hughesd07986f2011-12-06 18:27:45 -08003234 // to preserve that across the method invocation.
Ian Rogers62d6c772013-02-27 08:32:07 -08003235 SirtRef<mirror::Object> old_throw_this_object(soa.Self(), NULL);
Brian Carlstromea46f952013-07-30 01:26:50 -07003236 SirtRef<mirror::ArtMethod> old_throw_method(soa.Self(), NULL);
Ian Rogers62d6c772013-02-27 08:32:07 -08003237 SirtRef<mirror::Throwable> old_exception(soa.Self(), NULL);
3238 uint32_t old_throw_dex_pc;
3239 {
3240 ThrowLocation old_throw_location;
3241 mirror::Throwable* old_exception_obj = soa.Self()->GetException(&old_throw_location);
3242 old_throw_this_object.reset(old_throw_location.GetThis());
3243 old_throw_method.reset(old_throw_location.GetMethod());
3244 old_exception.reset(old_exception_obj);
3245 old_throw_dex_pc = old_throw_location.GetDexPc();
3246 soa.Self()->ClearException();
3247 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08003248
3249 // Translate the method through the vtable, unless the debugger wants to suppress it.
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003250 SirtRef<mirror::ArtMethod> m(soa.Self(), pReq->method);
Sebastien Hertzd38667a2013-11-25 15:43:54 +01003251 if ((pReq->options & JDWP::INVOKE_NONVIRTUAL) == 0 && pReq->receiver != NULL) {
Sebastien Hertz83a47d82014-03-20 09:57:40 +01003252 mirror::ArtMethod* actual_method = pReq->klass->FindVirtualMethodForVirtualOrInterface(m.get());
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003253 if (actual_method != m.get()) {
3254 VLOG(jdwp) << "ExecuteMethod translated " << PrettyMethod(m.get()) << " to " << PrettyMethod(actual_method);
3255 m.reset(actual_method);
Elliott Hughes45651fd2012-02-21 15:48:20 -08003256 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08003257 }
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003258 VLOG(jdwp) << "ExecuteMethod " << PrettyMethod(m.get())
Sebastien Hertzd38667a2013-11-25 15:43:54 +01003259 << " receiver=" << pReq->receiver
3260 << " arg_count=" << pReq->arg_count;
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003261 CHECK(m.get() != nullptr);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003262
3263 CHECK_EQ(sizeof(jvalue), sizeof(uint64_t));
3264
Sebastien Hertz83a47d82014-03-20 09:57:40 +01003265 pReq->result_value = InvokeWithJValues(soa, pReq->receiver, soa.EncodeMethod(m.get()),
Ian Rogers53b8b092014-03-13 23:45:53 -07003266 reinterpret_cast<jvalue*>(pReq->arg_values));
Elliott Hughesd07986f2011-12-06 18:27:45 -08003267
Ian Rogers62d6c772013-02-27 08:32:07 -08003268 mirror::Throwable* exception = soa.Self()->GetException(NULL);
3269 soa.Self()->ClearException();
3270 pReq->exception = gRegistry->Add(exception);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003271 pReq->result_tag = BasicTagFromDescriptor(MethodHelper(m.get()).GetShorty());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003272 if (pReq->exception != 0) {
Ian Rogers62d6c772013-02-27 08:32:07 -08003273 VLOG(jdwp) << " JDWP invocation returning with exception=" << exception
3274 << " " << exception->Dump();
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07003275 pReq->result_value.SetJ(0);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003276 } else if (pReq->result_tag == JDWP::JT_OBJECT) {
3277 /* if no exception thrown, examine object result more closely */
Ian Rogers98379392014-02-24 16:53:16 -08003278 JDWP::JdwpTag new_tag = TagFromObject(soa, pReq->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003279 if (new_tag != pReq->result_tag) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003280 VLOG(jdwp) << " JDWP promoted result from " << pReq->result_tag << " to " << new_tag;
Elliott Hughesd07986f2011-12-06 18:27:45 -08003281 pReq->result_tag = new_tag;
3282 }
3283
3284 /*
3285 * Register the object. We don't actually need an ObjectId yet,
3286 * but we do need to be sure that the GC won't move or discard the
3287 * object when we switch out of RUNNING. The ObjectId conversion
3288 * will add the object to the "do not touch" list.
3289 *
3290 * We can't use the "tracked allocation" mechanism here because
3291 * the object is going to be handed off to a different thread.
3292 */
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07003293 gRegistry->Add(pReq->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003294 }
3295
3296 if (old_exception.get() != NULL) {
Ian Rogers62d6c772013-02-27 08:32:07 -08003297 ThrowLocation gc_safe_throw_location(old_throw_this_object.get(), old_throw_method.get(),
3298 old_throw_dex_pc);
3299 soa.Self()->SetException(gc_safe_throw_location, old_exception.get());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003300 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003301}
3302
Elliott Hughesd07986f2011-12-06 18:27:45 -08003303/*
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003304 * "request" contains a full JDWP packet, possibly with multiple chunks. We
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003305 * need to process each, accumulate the replies, and ship the whole thing
3306 * back.
3307 *
3308 * Returns "true" if we have a reply. The reply buffer is newly allocated,
3309 * and includes the chunk type/length, followed by the data.
3310 *
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08003311 * OLD-TODO: we currently assume that the request and reply include a single
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003312 * chunk. If this becomes inconvenient we will need to adapt.
3313 */
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003314bool Dbg::DdmHandlePacket(JDWP::Request& request, uint8_t** pReplyBuf, int* pReplyLen) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003315 Thread* self = Thread::Current();
3316 JNIEnv* env = self->GetJniEnv();
3317
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003318 uint32_t type = request.ReadUnsigned32("type");
3319 uint32_t length = request.ReadUnsigned32("length");
3320
3321 // Create a byte[] corresponding to 'request'.
3322 size_t request_length = request.size();
3323 ScopedLocalRef<jbyteArray> dataArray(env, env->NewByteArray(request_length));
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003324 if (dataArray.get() == NULL) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003325 LOG(WARNING) << "byte[] allocation failed: " << request_length;
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003326 env->ExceptionClear();
3327 return false;
3328 }
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003329 env->SetByteArrayRegion(dataArray.get(), 0, request_length, reinterpret_cast<const jbyte*>(request.data()));
3330 request.Skip(request_length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003331
3332 // Run through and find all chunks. [Currently just find the first.]
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003333 ScopedByteArrayRO contents(env, dataArray.get());
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003334 if (length != request_length) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08003335 LOG(WARNING) << StringPrintf("bad chunk found (len=%u pktLen=%zd)", length, request_length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003336 return false;
3337 }
3338
3339 // Call "private static Chunk dispatch(int type, byte[] data, int offset, int length)".
Elliott Hugheseac76672012-05-24 21:56:51 -07003340 ScopedLocalRef<jobject> chunk(env, env->CallStaticObjectMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
3341 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_dispatch,
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003342 type, dataArray.get(), 0, length));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003343 if (env->ExceptionCheck()) {
3344 LOG(INFO) << StringPrintf("Exception thrown by dispatcher for 0x%08x", type);
3345 env->ExceptionDescribe();
3346 env->ExceptionClear();
3347 return false;
3348 }
3349
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003350 if (chunk.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003351 return false;
3352 }
3353
3354 /*
3355 * Pull the pieces out of the chunk. We copy the results into a
3356 * newly-allocated buffer that the caller can free. We don't want to
3357 * continue using the Chunk object because nothing has a reference to it.
3358 *
3359 * We could avoid this by returning type/data/offset/length and having
3360 * the caller be aware of the object lifetime issues, but that
Elliott Hughes81ff3182012-03-23 20:35:56 -07003361 * integrates the JDWP code more tightly into the rest of the runtime, and doesn't work
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003362 * if we have responses for multiple chunks.
3363 *
3364 * So we're pretty much stuck with copying data around multiple times.
3365 */
Elliott Hugheseac76672012-05-24 21:56:51 -07003366 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 -08003367 jint offset = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_offset);
Elliott Hugheseac76672012-05-24 21:56:51 -07003368 length = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_length);
Elliott Hugheseac76672012-05-24 21:56:51 -07003369 type = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_type);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003370
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003371 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 -07003372 if (length == 0 || replyData.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003373 return false;
3374 }
3375
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003376 const int kChunkHdrLen = 8;
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003377 uint8_t* reply = new uint8_t[length + kChunkHdrLen];
3378 if (reply == NULL) {
3379 LOG(WARNING) << "malloc failed: " << (length + kChunkHdrLen);
3380 return false;
3381 }
Elliott Hughesf7c3b662011-10-27 12:04:56 -07003382 JDWP::Set4BE(reply + 0, type);
3383 JDWP::Set4BE(reply + 4, length);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003384 env->GetByteArrayRegion(replyData.get(), offset, length, reinterpret_cast<jbyte*>(reply + kChunkHdrLen));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003385
3386 *pReplyBuf = reply;
3387 *pReplyLen = length + kChunkHdrLen;
3388
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003389 VLOG(jdwp) << StringPrintf("dvmHandleDdm returning type=%.4s %p len=%d", reinterpret_cast<char*>(reply), reply, length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003390 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003391}
3392
Elliott Hughesa2155262011-11-16 16:26:58 -08003393void Dbg::DdmBroadcast(bool connect) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003394 VLOG(jdwp) << "Broadcasting DDM " << (connect ? "connect" : "disconnect") << "...";
Elliott Hughes47fce012011-10-25 18:37:19 -07003395
3396 Thread* self = Thread::Current();
Ian Rogers50b35e22012-10-04 10:09:15 -07003397 if (self->GetState() != kRunnable) {
3398 LOG(ERROR) << "DDM broadcast in thread state " << self->GetState();
3399 /* try anyway? */
Elliott Hughes47fce012011-10-25 18:37:19 -07003400 }
3401
3402 JNIEnv* env = self->GetJniEnv();
Elliott Hughes47fce012011-10-25 18:37:19 -07003403 jint event = connect ? 1 /*DdmServer.CONNECTED*/ : 2 /*DdmServer.DISCONNECTED*/;
Elliott Hugheseac76672012-05-24 21:56:51 -07003404 env->CallStaticVoidMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
3405 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_broadcast,
3406 event);
Elliott Hughes47fce012011-10-25 18:37:19 -07003407 if (env->ExceptionCheck()) {
3408 LOG(ERROR) << "DdmServer.broadcast " << event << " failed";
3409 env->ExceptionDescribe();
3410 env->ExceptionClear();
3411 }
3412}
3413
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003414void Dbg::DdmConnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08003415 Dbg::DdmBroadcast(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003416}
3417
3418void Dbg::DdmDisconnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08003419 Dbg::DdmBroadcast(false);
Elliott Hughes47fce012011-10-25 18:37:19 -07003420 gDdmThreadNotification = false;
3421}
3422
3423/*
Elliott Hughes82188472011-11-07 18:11:48 -08003424 * Send a notification when a thread starts, stops, or changes its name.
Elliott Hughes47fce012011-10-25 18:37:19 -07003425 *
3426 * Because we broadcast the full set of threads when the notifications are
3427 * first enabled, it's possible for "thread" to be actively executing.
3428 */
Elliott Hughes82188472011-11-07 18:11:48 -08003429void Dbg::DdmSendThreadNotification(Thread* t, uint32_t type) {
Elliott Hughes47fce012011-10-25 18:37:19 -07003430 if (!gDdmThreadNotification) {
3431 return;
3432 }
3433
Elliott Hughes82188472011-11-07 18:11:48 -08003434 if (type == CHUNK_TYPE("THDE")) {
Elliott Hughes47fce012011-10-25 18:37:19 -07003435 uint8_t buf[4];
Ian Rogersd9c4fc92013-10-01 19:45:43 -07003436 JDWP::Set4BE(&buf[0], t->GetThreadId());
Elliott Hughes47fce012011-10-25 18:37:19 -07003437 Dbg::DdmSendChunk(CHUNK_TYPE("THDE"), 4, buf);
Elliott Hughes82188472011-11-07 18:11:48 -08003438 } else {
3439 CHECK(type == CHUNK_TYPE("THCR") || type == CHUNK_TYPE("THNM")) << type;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003440 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003441 SirtRef<mirror::String> name(soa.Self(), t->GetThreadName(soa));
Elliott Hughes82188472011-11-07 18:11:48 -08003442 size_t char_count = (name.get() != NULL) ? name->GetLength() : 0;
jeffhao725a9572012-11-13 18:20:12 -08003443 const jchar* chars = (name.get() != NULL) ? name->GetCharArray()->GetData() : NULL;
Elliott Hughes82188472011-11-07 18:11:48 -08003444
Elliott Hughes21f32d72011-11-09 17:44:13 -08003445 std::vector<uint8_t> bytes;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07003446 JDWP::Append4BE(bytes, t->GetThreadId());
Elliott Hughes545a0642011-11-08 19:10:03 -08003447 JDWP::AppendUtf16BE(bytes, chars, char_count);
Elliott Hughes21f32d72011-11-09 17:44:13 -08003448 CHECK_EQ(bytes.size(), char_count*2 + sizeof(uint32_t)*2);
3449 Dbg::DdmSendChunk(type, bytes);
Elliott Hughes47fce012011-10-25 18:37:19 -07003450 }
3451}
3452
Elliott Hughes47fce012011-10-25 18:37:19 -07003453void Dbg::DdmSetThreadNotification(bool enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003454 // Enable/disable thread notifications.
Elliott Hughes47fce012011-10-25 18:37:19 -07003455 gDdmThreadNotification = enable;
3456 if (enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003457 // Suspend the VM then post thread start notifications for all threads. Threads attaching will
3458 // see a suspension in progress and block until that ends. They then post their own start
3459 // notification.
3460 SuspendVM();
3461 std::list<Thread*> threads;
Ian Rogers50b35e22012-10-04 10:09:15 -07003462 Thread* self = Thread::Current();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003463 {
Ian Rogers50b35e22012-10-04 10:09:15 -07003464 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003465 threads = Runtime::Current()->GetThreadList()->GetList();
3466 }
3467 {
Ian Rogers50b35e22012-10-04 10:09:15 -07003468 ScopedObjectAccess soa(self);
Mathieu Chartier02e25112013-08-14 16:14:24 -07003469 for (Thread* thread : threads) {
3470 Dbg::DdmSendThreadNotification(thread, CHUNK_TYPE("THCR"));
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003471 }
3472 }
3473 ResumeVM();
Elliott Hughes47fce012011-10-25 18:37:19 -07003474 }
3475}
3476
Elliott Hughesa2155262011-11-16 16:26:58 -08003477void Dbg::PostThreadStartOrStop(Thread* t, uint32_t type) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07003478 if (IsDebuggerActive()) {
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07003479 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogerscfaa4552012-11-26 21:00:08 -08003480 JDWP::ObjectId id = gRegistry->Add(t->GetPeer());
Elliott Hughes82188472011-11-07 18:11:48 -08003481 gJdwpState->PostThreadChange(id, type == CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07003482 }
Elliott Hughes82188472011-11-07 18:11:48 -08003483 Dbg::DdmSendThreadNotification(t, type);
Elliott Hughes47fce012011-10-25 18:37:19 -07003484}
3485
3486void Dbg::PostThreadStart(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08003487 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07003488}
3489
3490void Dbg::PostThreadDeath(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08003491 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THDE"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003492}
3493
Elliott Hughes82188472011-11-07 18:11:48 -08003494void Dbg::DdmSendChunk(uint32_t type, size_t byte_count, const uint8_t* buf) {
Elliott Hughes3bb81562011-10-21 18:52:59 -07003495 CHECK(buf != NULL);
3496 iovec vec[1];
3497 vec[0].iov_base = reinterpret_cast<void*>(const_cast<uint8_t*>(buf));
3498 vec[0].iov_len = byte_count;
3499 Dbg::DdmSendChunkV(type, vec, 1);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003500}
3501
Elliott Hughes21f32d72011-11-09 17:44:13 -08003502void Dbg::DdmSendChunk(uint32_t type, const std::vector<uint8_t>& bytes) {
3503 DdmSendChunk(type, bytes.size(), &bytes[0]);
3504}
3505
Brian Carlstromf5293522013-07-19 00:24:00 -07003506void Dbg::DdmSendChunkV(uint32_t type, const iovec* iov, int iov_count) {
Elliott Hughes3bb81562011-10-21 18:52:59 -07003507 if (gJdwpState == NULL) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003508 VLOG(jdwp) << "Debugger thread not active, ignoring DDM send: " << type;
Elliott Hughes3bb81562011-10-21 18:52:59 -07003509 } else {
Elliott Hughescccd84f2011-12-05 16:51:54 -08003510 gJdwpState->DdmSendChunkV(type, iov, iov_count);
Elliott Hughes3bb81562011-10-21 18:52:59 -07003511 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003512}
3513
Elliott Hughes767a1472011-10-26 18:49:02 -07003514int Dbg::DdmHandleHpifChunk(HpifWhen when) {
3515 if (when == HPIF_WHEN_NOW) {
Elliott Hughes7162ad92011-10-27 14:08:42 -07003516 DdmSendHeapInfo(when);
Elliott Hughes767a1472011-10-26 18:49:02 -07003517 return true;
3518 }
3519
3520 if (when != HPIF_WHEN_NEVER && when != HPIF_WHEN_NEXT_GC && when != HPIF_WHEN_EVERY_GC) {
3521 LOG(ERROR) << "invalid HpifWhen value: " << static_cast<int>(when);
3522 return false;
3523 }
3524
3525 gDdmHpifWhen = when;
3526 return true;
3527}
3528
3529bool Dbg::DdmHandleHpsgNhsgChunk(Dbg::HpsgWhen when, Dbg::HpsgWhat what, bool native) {
3530 if (when != HPSG_WHEN_NEVER && when != HPSG_WHEN_EVERY_GC) {
3531 LOG(ERROR) << "invalid HpsgWhen value: " << static_cast<int>(when);
3532 return false;
3533 }
3534
3535 if (what != HPSG_WHAT_MERGED_OBJECTS && what != HPSG_WHAT_DISTINCT_OBJECTS) {
3536 LOG(ERROR) << "invalid HpsgWhat value: " << static_cast<int>(what);
3537 return false;
3538 }
3539
3540 if (native) {
3541 gDdmNhsgWhen = when;
3542 gDdmNhsgWhat = what;
3543 } else {
3544 gDdmHpsgWhen = when;
3545 gDdmHpsgWhat = what;
3546 }
3547 return true;
3548}
3549
Elliott Hughes7162ad92011-10-27 14:08:42 -07003550void Dbg::DdmSendHeapInfo(HpifWhen reason) {
3551 // If there's a one-shot 'when', reset it.
3552 if (reason == gDdmHpifWhen) {
3553 if (gDdmHpifWhen == HPIF_WHEN_NEXT_GC) {
3554 gDdmHpifWhen = HPIF_WHEN_NEVER;
3555 }
3556 }
3557
3558 /*
3559 * Chunk HPIF (client --> server)
3560 *
3561 * Heap Info. General information about the heap,
3562 * suitable for a summary display.
3563 *
3564 * [u4]: number of heaps
3565 *
3566 * For each heap:
3567 * [u4]: heap ID
3568 * [u8]: timestamp in ms since Unix epoch
3569 * [u1]: capture reason (same as 'when' value from server)
3570 * [u4]: max heap size in bytes (-Xmx)
3571 * [u4]: current heap size in bytes
3572 * [u4]: current number of bytes allocated
3573 * [u4]: current number of objects allocated
3574 */
3575 uint8_t heap_count = 1;
Ian Rogers1d54e732013-05-02 21:10:01 -07003576 gc::Heap* heap = Runtime::Current()->GetHeap();
Elliott Hughes21f32d72011-11-09 17:44:13 -08003577 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08003578 JDWP::Append4BE(bytes, heap_count);
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003579 JDWP::Append4BE(bytes, 1); // Heap id (bogus; we only have one heap).
Elliott Hughes545a0642011-11-08 19:10:03 -08003580 JDWP::Append8BE(bytes, MilliTime());
3581 JDWP::Append1BE(bytes, reason);
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003582 JDWP::Append4BE(bytes, heap->GetMaxMemory()); // Max allowed heap size in bytes.
3583 JDWP::Append4BE(bytes, heap->GetTotalMemory()); // Current heap size in bytes.
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08003584 JDWP::Append4BE(bytes, heap->GetBytesAllocated());
3585 JDWP::Append4BE(bytes, heap->GetObjectsAllocated());
Elliott Hughes21f32d72011-11-09 17:44:13 -08003586 CHECK_EQ(bytes.size(), 4U + (heap_count * (4 + 8 + 1 + 4 + 4 + 4 + 4)));
3587 Dbg::DdmSendChunk(CHUNK_TYPE("HPIF"), bytes);
Elliott Hughes767a1472011-10-26 18:49:02 -07003588}
3589
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003590enum HpsgSolidity {
3591 SOLIDITY_FREE = 0,
3592 SOLIDITY_HARD = 1,
3593 SOLIDITY_SOFT = 2,
3594 SOLIDITY_WEAK = 3,
3595 SOLIDITY_PHANTOM = 4,
3596 SOLIDITY_FINALIZABLE = 5,
3597 SOLIDITY_SWEEP = 6,
3598};
3599
3600enum HpsgKind {
3601 KIND_OBJECT = 0,
3602 KIND_CLASS_OBJECT = 1,
3603 KIND_ARRAY_1 = 2,
3604 KIND_ARRAY_2 = 3,
3605 KIND_ARRAY_4 = 4,
3606 KIND_ARRAY_8 = 5,
3607 KIND_UNKNOWN = 6,
3608 KIND_NATIVE = 7,
3609};
3610
3611#define HPSG_PARTIAL (1<<7)
3612#define HPSG_STATE(solidity, kind) ((uint8_t)((((kind) & 0x7) << 3) | ((solidity) & 0x7)))
3613
Ian Rogers30fab402012-01-23 15:43:46 -08003614class HeapChunkContext {
3615 public:
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003616 // Maximum chunk size. Obtain this from the formula:
3617 // (((maximum_heap_size / ALLOCATION_UNIT_SIZE) + 255) / 256) * 2
3618 HeapChunkContext(bool merge, bool native)
Ian Rogers30fab402012-01-23 15:43:46 -08003619 : buf_(16384 - 16),
3620 type_(0),
3621 merge_(merge) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003622 Reset();
3623 if (native) {
Ian Rogers30fab402012-01-23 15:43:46 -08003624 type_ = CHUNK_TYPE("NHSG");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003625 } else {
Ian Rogers30fab402012-01-23 15:43:46 -08003626 type_ = merge ? CHUNK_TYPE("HPSG") : CHUNK_TYPE("HPSO");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003627 }
3628 }
3629
3630 ~HeapChunkContext() {
Ian Rogers30fab402012-01-23 15:43:46 -08003631 if (p_ > &buf_[0]) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003632 Flush();
3633 }
3634 }
3635
3636 void EnsureHeader(const void* chunk_ptr) {
Ian Rogers30fab402012-01-23 15:43:46 -08003637 if (!needHeader_) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003638 return;
3639 }
3640
3641 // Start a new HPSx chunk.
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003642 JDWP::Write4BE(&p_, 1); // Heap id (bogus; we only have one heap).
3643 JDWP::Write1BE(&p_, 8); // Size of allocation unit, in bytes.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003644
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003645 JDWP::Write4BE(&p_, reinterpret_cast<uintptr_t>(chunk_ptr)); // virtual address of segment start.
3646 JDWP::Write4BE(&p_, 0); // offset of this piece (relative to the virtual address).
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003647 // [u4]: length of piece, in allocation units
3648 // 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 -08003649 pieceLenField_ = p_;
3650 JDWP::Write4BE(&p_, 0x55555555);
3651 needHeader_ = false;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003652 }
3653
Ian Rogersb726dcb2012-09-05 08:57:23 -07003654 void Flush() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogersd636b062013-01-18 17:51:18 -08003655 if (pieceLenField_ == NULL) {
3656 // Flush immediately post Reset (maybe back-to-back Flush). Ignore.
3657 CHECK(needHeader_);
3658 return;
3659 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003660 // Patch the "length of piece" field.
Ian Rogers30fab402012-01-23 15:43:46 -08003661 CHECK_LE(&buf_[0], pieceLenField_);
3662 CHECK_LE(pieceLenField_, p_);
3663 JDWP::Set4BE(pieceLenField_, totalAllocationUnits_);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003664
Ian Rogers30fab402012-01-23 15:43:46 -08003665 Dbg::DdmSendChunk(type_, p_ - &buf_[0], &buf_[0]);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003666 Reset();
3667 }
3668
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003669 static void HeapChunkCallback(void* start, void* end, size_t used_bytes, void* arg)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003670 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_,
3671 Locks::mutator_lock_) {
Ian Rogers30fab402012-01-23 15:43:46 -08003672 reinterpret_cast<HeapChunkContext*>(arg)->HeapChunkCallback(start, end, used_bytes);
Elliott Hughesa2155262011-11-16 16:26:58 -08003673 }
3674
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003675 private:
Elliott Hughesa2155262011-11-16 16:26:58 -08003676 enum { ALLOCATION_UNIT_SIZE = 8 };
3677
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003678 void Reset() {
Ian Rogers30fab402012-01-23 15:43:46 -08003679 p_ = &buf_[0];
Ian Rogers15bf2d32012-08-28 17:33:04 -07003680 startOfNextMemoryChunk_ = NULL;
Ian Rogers30fab402012-01-23 15:43:46 -08003681 totalAllocationUnits_ = 0;
3682 needHeader_ = true;
3683 pieceLenField_ = NULL;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003684 }
3685
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003686 void HeapChunkCallback(void* start, void* /*end*/, size_t used_bytes)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003687 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_,
3688 Locks::mutator_lock_) {
Ian Rogers30fab402012-01-23 15:43:46 -08003689 // Note: heap call backs cannot manipulate the heap upon which they are crawling, care is taken
3690 // in the following code not to allocate memory, by ensuring buf_ is of the correct size
Ian Rogers15bf2d32012-08-28 17:33:04 -07003691 if (used_bytes == 0) {
3692 if (start == NULL) {
3693 // Reset for start of new heap.
3694 startOfNextMemoryChunk_ = NULL;
3695 Flush();
3696 }
3697 // Only process in use memory so that free region information
3698 // also includes dlmalloc book keeping.
Elliott Hughesa2155262011-11-16 16:26:58 -08003699 return;
Elliott Hughesa2155262011-11-16 16:26:58 -08003700 }
3701
Ian Rogers15bf2d32012-08-28 17:33:04 -07003702 /* If we're looking at the native heap, we'll just return
3703 * (SOLIDITY_HARD, KIND_NATIVE) for all allocated chunks
3704 */
3705 bool native = type_ == CHUNK_TYPE("NHSG");
3706
3707 if (startOfNextMemoryChunk_ != NULL) {
3708 // Transmit any pending free memory. Native free memory of
3709 // over kMaxFreeLen could be because of the use of mmaps, so
3710 // don't report. If not free memory then start a new segment.
3711 bool flush = true;
3712 if (start > startOfNextMemoryChunk_) {
3713 const size_t kMaxFreeLen = 2 * kPageSize;
3714 void* freeStart = startOfNextMemoryChunk_;
3715 void* freeEnd = start;
Brian Carlstrom2d888622013-07-18 17:02:00 -07003716 size_t freeLen = reinterpret_cast<char*>(freeEnd) - reinterpret_cast<char*>(freeStart);
Ian Rogers15bf2d32012-08-28 17:33:04 -07003717 if (!native || freeLen < kMaxFreeLen) {
3718 AppendChunk(HPSG_STATE(SOLIDITY_FREE, 0), freeStart, freeLen);
3719 flush = false;
3720 }
3721 }
3722 if (flush) {
3723 startOfNextMemoryChunk_ = NULL;
3724 Flush();
3725 }
3726 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08003727 mirror::Object* obj = reinterpret_cast<mirror::Object*>(start);
Elliott Hughesa2155262011-11-16 16:26:58 -08003728
3729 // Determine the type of this chunk.
3730 // OLD-TODO: if context.merge, see if this chunk is different from the last chunk.
3731 // If it's the same, we should combine them.
Ian Rogers15bf2d32012-08-28 17:33:04 -07003732 uint8_t state = ExamineObject(obj, native);
3733 // dlmalloc's chunk header is 2 * sizeof(size_t), but if the previous chunk is in use for an
3734 // allocation then the first sizeof(size_t) may belong to it.
3735 const size_t dlMallocOverhead = sizeof(size_t);
3736 AppendChunk(state, start, used_bytes + dlMallocOverhead);
Brian Carlstrom2d888622013-07-18 17:02:00 -07003737 startOfNextMemoryChunk_ = reinterpret_cast<char*>(start) + used_bytes + dlMallocOverhead;
Ian Rogers15bf2d32012-08-28 17:33:04 -07003738 }
Elliott Hughesa2155262011-11-16 16:26:58 -08003739
Ian Rogers15bf2d32012-08-28 17:33:04 -07003740 void AppendChunk(uint8_t state, void* ptr, size_t length)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003741 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07003742 // Make sure there's enough room left in the buffer.
3743 // We need to use two bytes for every fractional 256 allocation units used by the chunk plus
3744 // 17 bytes for any header.
3745 size_t needed = (((length/ALLOCATION_UNIT_SIZE + 255) / 256) * 2) + 17;
3746 size_t bytesLeft = buf_.size() - (size_t)(p_ - &buf_[0]);
3747 if (bytesLeft < needed) {
3748 Flush();
3749 }
3750
3751 bytesLeft = buf_.size() - (size_t)(p_ - &buf_[0]);
3752 if (bytesLeft < needed) {
3753 LOG(WARNING) << "Chunk is too big to transmit (chunk_len=" << length << ", "
3754 << needed << " bytes)";
3755 return;
3756 }
3757 EnsureHeader(ptr);
Elliott Hughesa2155262011-11-16 16:26:58 -08003758 // Write out the chunk description.
Ian Rogers15bf2d32012-08-28 17:33:04 -07003759 length /= ALLOCATION_UNIT_SIZE; // Convert to allocation units.
3760 totalAllocationUnits_ += length;
3761 while (length > 256) {
Ian Rogers30fab402012-01-23 15:43:46 -08003762 *p_++ = state | HPSG_PARTIAL;
3763 *p_++ = 255; // length - 1
Ian Rogers15bf2d32012-08-28 17:33:04 -07003764 length -= 256;
Elliott Hughesa2155262011-11-16 16:26:58 -08003765 }
Ian Rogers30fab402012-01-23 15:43:46 -08003766 *p_++ = state;
Ian Rogers15bf2d32012-08-28 17:33:04 -07003767 *p_++ = length - 1;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003768 }
3769
Ian Rogersef7d42f2014-01-06 12:55:46 -08003770 uint8_t ExamineObject(mirror::Object* o, bool is_native_heap)
3771 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Elliott Hughesa2155262011-11-16 16:26:58 -08003772 if (o == NULL) {
3773 return HPSG_STATE(SOLIDITY_FREE, 0);
3774 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003775
Elliott Hughesa2155262011-11-16 16:26:58 -08003776 // It's an allocated chunk. Figure out what it is.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003777
Elliott Hughesa2155262011-11-16 16:26:58 -08003778 // If we're looking at the native heap, we'll just return
3779 // (SOLIDITY_HARD, KIND_NATIVE) for all allocated chunks.
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003780 if (is_native_heap) {
Elliott Hughesa2155262011-11-16 16:26:58 -08003781 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
3782 }
3783
Ian Rogers5bfa60f2012-09-02 21:17:56 -07003784 if (!Runtime::Current()->GetHeap()->IsLiveObjectLocked(o)) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07003785 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003786 }
3787
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003788 mirror::Class* c = o->GetClass();
Elliott Hughesa2155262011-11-16 16:26:58 -08003789 if (c == NULL) {
3790 // The object was probably just created but hasn't been initialized yet.
3791 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
3792 }
3793
Mathieu Chartier590fee92013-09-13 13:46:47 -07003794 if (!Runtime::Current()->GetHeap()->IsValidObjectAddress(c)) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07003795 LOG(ERROR) << "Invalid class for managed heap object: " << o << " " << c;
Elliott Hughesa2155262011-11-16 16:26:58 -08003796 return HPSG_STATE(SOLIDITY_HARD, KIND_UNKNOWN);
3797 }
3798
3799 if (c->IsClassClass()) {
3800 return HPSG_STATE(SOLIDITY_HARD, KIND_CLASS_OBJECT);
3801 }
3802
3803 if (c->IsArrayClass()) {
3804 if (o->IsObjectArray()) {
3805 return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
3806 }
3807 switch (c->GetComponentSize()) {
3808 case 1: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_1);
3809 case 2: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_2);
3810 case 4: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
3811 case 8: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_8);
3812 }
3813 }
3814
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003815 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
3816 }
3817
Ian Rogers30fab402012-01-23 15:43:46 -08003818 std::vector<uint8_t> buf_;
3819 uint8_t* p_;
3820 uint8_t* pieceLenField_;
Ian Rogers15bf2d32012-08-28 17:33:04 -07003821 void* startOfNextMemoryChunk_;
Ian Rogers30fab402012-01-23 15:43:46 -08003822 size_t totalAllocationUnits_;
3823 uint32_t type_;
3824 bool merge_;
3825 bool needHeader_;
3826
Elliott Hughesa2155262011-11-16 16:26:58 -08003827 DISALLOW_COPY_AND_ASSIGN(HeapChunkContext);
3828};
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003829
3830void Dbg::DdmSendHeapSegments(bool native) {
3831 Dbg::HpsgWhen when;
3832 Dbg::HpsgWhat what;
3833 if (!native) {
3834 when = gDdmHpsgWhen;
3835 what = gDdmHpsgWhat;
3836 } else {
3837 when = gDdmNhsgWhen;
3838 what = gDdmNhsgWhat;
3839 }
3840 if (when == HPSG_WHEN_NEVER) {
3841 return;
3842 }
3843
3844 // Figure out what kind of chunks we'll be sending.
3845 CHECK(what == HPSG_WHAT_MERGED_OBJECTS || what == HPSG_WHAT_DISTINCT_OBJECTS) << static_cast<int>(what);
3846
3847 // First, send a heap start chunk.
3848 uint8_t heap_id[4];
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003849 JDWP::Set4BE(&heap_id[0], 1); // Heap id (bogus; we only have one heap).
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003850 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHST") : CHUNK_TYPE("HPST"), sizeof(heap_id), heap_id);
3851
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07003852 Thread* self = Thread::Current();
3853
3854 // To allow the Walk/InspectAll() below to exclusively-lock the
3855 // mutator lock, temporarily release the shared access to the
3856 // mutator lock here by transitioning to the suspended state.
3857 Locks::mutator_lock_->AssertSharedHeld(self);
3858 self->TransitionFromRunnableToSuspended(kSuspended);
3859
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003860 // Send a series of heap segment chunks.
Elliott Hughesa2155262011-11-16 16:26:58 -08003861 HeapChunkContext context((what == HPSG_WHAT_MERGED_OBJECTS), native);
3862 if (native) {
Ian Rogers1d54e732013-05-02 21:10:01 -07003863 dlmalloc_inspect_all(HeapChunkContext::HeapChunkCallback, &context);
Elliott Hughesa2155262011-11-16 16:26:58 -08003864 } else {
Ian Rogers1d54e732013-05-02 21:10:01 -07003865 gc::Heap* heap = Runtime::Current()->GetHeap();
3866 const std::vector<gc::space::ContinuousSpace*>& spaces = heap->GetContinuousSpaces();
Ian Rogers1d54e732013-05-02 21:10:01 -07003867 typedef std::vector<gc::space::ContinuousSpace*>::const_iterator It;
3868 for (It cur = spaces.begin(), end = spaces.end(); cur != end; ++cur) {
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07003869 if ((*cur)->IsMallocSpace()) {
3870 (*cur)->AsMallocSpace()->Walk(HeapChunkContext::HeapChunkCallback, &context);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07003871 }
3872 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07003873 // Walk the large objects, these are not in the AllocSpace.
3874 heap->GetLargeObjectsSpace()->Walk(HeapChunkContext::HeapChunkCallback, &context);
Elliott Hughesa2155262011-11-16 16:26:58 -08003875 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003876
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07003877 // Shared-lock the mutator lock back.
3878 self->TransitionFromSuspendedToRunnable();
3879 Locks::mutator_lock_->AssertSharedHeld(self);
3880
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003881 // Finally, send a heap end chunk.
3882 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHEN") : CHUNK_TYPE("HPEN"), sizeof(heap_id), heap_id);
Elliott Hughes767a1472011-10-26 18:49:02 -07003883}
3884
Elliott Hughesb1a58792013-07-11 18:10:58 -07003885static size_t GetAllocTrackerMax() {
3886#ifdef HAVE_ANDROID_OS
3887 // Check whether there's a system property overriding the number of records.
3888 const char* propertyName = "dalvik.vm.allocTrackerMax";
3889 char allocRecordMaxString[PROPERTY_VALUE_MAX];
3890 if (property_get(propertyName, allocRecordMaxString, "") > 0) {
3891 char* end;
3892 size_t value = strtoul(allocRecordMaxString, &end, 10);
3893 if (*end != '\0') {
Ruben Brunk3e47a742013-09-09 17:56:07 -07003894 LOG(ERROR) << "Ignoring " << propertyName << " '" << allocRecordMaxString
3895 << "' --- invalid";
Elliott Hughesb1a58792013-07-11 18:10:58 -07003896 return kDefaultNumAllocRecords;
3897 }
3898 if (!IsPowerOfTwo(value)) {
Ruben Brunk3e47a742013-09-09 17:56:07 -07003899 LOG(ERROR) << "Ignoring " << propertyName << " '" << allocRecordMaxString
3900 << "' --- not power of two";
Elliott Hughesb1a58792013-07-11 18:10:58 -07003901 return kDefaultNumAllocRecords;
3902 }
3903 return value;
3904 }
3905#endif
3906 return kDefaultNumAllocRecords;
3907}
3908
Elliott Hughes545a0642011-11-08 19:10:03 -08003909void Dbg::SetAllocTrackingEnabled(bool enabled) {
Elliott Hughes545a0642011-11-08 19:10:03 -08003910 if (enabled) {
Sebastien Hertzb98063a2014-03-26 10:57:20 +01003911 {
3912 MutexLock mu(Thread::Current(), *alloc_tracker_lock_);
3913 if (recent_allocation_records_ == NULL) {
3914 alloc_record_max_ = GetAllocTrackerMax();
3915 LOG(INFO) << "Enabling alloc tracker (" << alloc_record_max_ << " entries of "
3916 << kMaxAllocRecordStackDepth << " frames, taking "
3917 << PrettySize(sizeof(AllocRecord) * alloc_record_max_) << ")";
3918 alloc_record_head_ = alloc_record_count_ = 0;
3919 recent_allocation_records_ = new AllocRecord[alloc_record_max_];
3920 CHECK(recent_allocation_records_ != NULL);
3921 }
Elliott Hughes545a0642011-11-08 19:10:03 -08003922 }
Ian Rogersfa824272013-11-05 16:12:57 -08003923 Runtime::Current()->GetInstrumentation()->InstrumentQuickAllocEntryPoints();
Elliott Hughes545a0642011-11-08 19:10:03 -08003924 } else {
Ian Rogersfa824272013-11-05 16:12:57 -08003925 Runtime::Current()->GetInstrumentation()->UninstrumentQuickAllocEntryPoints();
Sebastien Hertzb98063a2014-03-26 10:57:20 +01003926 {
3927 MutexLock mu(Thread::Current(), *alloc_tracker_lock_);
3928 delete[] recent_allocation_records_;
3929 recent_allocation_records_ = NULL;
3930 }
Elliott Hughes545a0642011-11-08 19:10:03 -08003931 }
3932}
3933
Ian Rogers0399dde2012-06-06 17:09:28 -07003934struct AllocRecordStackVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -08003935 AllocRecordStackVisitor(Thread* thread, AllocRecord* record)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003936 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08003937 : StackVisitor(thread, NULL), record(record), depth(0) {}
Elliott Hughes545a0642011-11-08 19:10:03 -08003938
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003939 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
3940 // annotalysis.
3941 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughes545a0642011-11-08 19:10:03 -08003942 if (depth >= kMaxAllocRecordStackDepth) {
Elliott Hughes530fa002012-03-12 11:44:49 -07003943 return false;
Elliott Hughes545a0642011-11-08 19:10:03 -08003944 }
Brian Carlstromea46f952013-07-30 01:26:50 -07003945 mirror::ArtMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07003946 if (!m->IsRuntimeMethod()) {
3947 record->stack[depth].method = m;
3948 record->stack[depth].dex_pc = GetDexPc();
Elliott Hughes530fa002012-03-12 11:44:49 -07003949 ++depth;
Elliott Hughes545a0642011-11-08 19:10:03 -08003950 }
Elliott Hughes530fa002012-03-12 11:44:49 -07003951 return true;
Elliott Hughes545a0642011-11-08 19:10:03 -08003952 }
3953
3954 ~AllocRecordStackVisitor() {
3955 // Clear out any unused stack trace elements.
3956 for (; depth < kMaxAllocRecordStackDepth; ++depth) {
3957 record->stack[depth].method = NULL;
Ian Rogers0399dde2012-06-06 17:09:28 -07003958 record->stack[depth].dex_pc = 0;
Elliott Hughes545a0642011-11-08 19:10:03 -08003959 }
3960 }
3961
3962 AllocRecord* record;
3963 size_t depth;
3964};
3965
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003966void Dbg::RecordAllocation(mirror::Class* type, size_t byte_count) {
Elliott Hughes545a0642011-11-08 19:10:03 -08003967 Thread* self = Thread::Current();
3968 CHECK(self != NULL);
3969
Ian Rogers719d1a32014-03-06 12:13:39 -08003970 MutexLock mu(self, *alloc_tracker_lock_);
Elliott Hughes545a0642011-11-08 19:10:03 -08003971 if (recent_allocation_records_ == NULL) {
3972 return;
3973 }
3974
3975 // Advance and clip.
Ian Rogers719d1a32014-03-06 12:13:39 -08003976 if (++alloc_record_head_ == alloc_record_max_) {
3977 alloc_record_head_ = 0;
Elliott Hughes545a0642011-11-08 19:10:03 -08003978 }
3979
3980 // Fill in the basics.
Ian Rogers719d1a32014-03-06 12:13:39 -08003981 AllocRecord* record = &recent_allocation_records_[alloc_record_head_];
Elliott Hughes545a0642011-11-08 19:10:03 -08003982 record->type = type;
3983 record->byte_count = byte_count;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07003984 record->thin_lock_id = self->GetThreadId();
Elliott Hughes545a0642011-11-08 19:10:03 -08003985
3986 // Fill in the stack trace.
Ian Rogers7a22fa62013-01-23 12:16:16 -08003987 AllocRecordStackVisitor visitor(self, record);
Ian Rogers0399dde2012-06-06 17:09:28 -07003988 visitor.WalkStack();
Elliott Hughes545a0642011-11-08 19:10:03 -08003989
Ian Rogers719d1a32014-03-06 12:13:39 -08003990 if (alloc_record_count_ < alloc_record_max_) {
3991 ++alloc_record_count_;
Elliott Hughes545a0642011-11-08 19:10:03 -08003992 }
3993}
3994
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003995// Returns the index of the head element.
3996//
3997// We point at the most-recently-written record, so if gAllocRecordCount is 1
3998// we want to use the current element. Take "head+1" and subtract count
3999// from it.
4000//
4001// We need to handle underflow in our circular buffer, so we add
Elliott Hughesb1a58792013-07-11 18:10:58 -07004002// gAllocRecordMax and then mask it back down.
Ian Rogers719d1a32014-03-06 12:13:39 -08004003size_t Dbg::HeadIndex() {
4004 return (Dbg::alloc_record_head_ + 1 + Dbg::alloc_record_max_ - Dbg::alloc_record_count_) &
4005 (Dbg::alloc_record_max_ - 1);
Elliott Hughes545a0642011-11-08 19:10:03 -08004006}
4007
4008void Dbg::DumpRecentAllocations() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004009 ScopedObjectAccess soa(Thread::Current());
Ian Rogers719d1a32014-03-06 12:13:39 -08004010 MutexLock mu(soa.Self(), *alloc_tracker_lock_);
Elliott Hughes545a0642011-11-08 19:10:03 -08004011 if (recent_allocation_records_ == NULL) {
4012 LOG(INFO) << "Not recording tracked allocations";
4013 return;
4014 }
4015
4016 // "i" is the head of the list. We want to start at the end of the
4017 // list and move forward to the tail.
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004018 size_t i = HeadIndex();
Ian Rogers719d1a32014-03-06 12:13:39 -08004019 size_t count = alloc_record_count_;
Elliott Hughes545a0642011-11-08 19:10:03 -08004020
Ian Rogers719d1a32014-03-06 12:13:39 -08004021 LOG(INFO) << "Tracked allocations, (head=" << alloc_record_head_ << " count=" << count << ")";
Elliott Hughes545a0642011-11-08 19:10:03 -08004022 while (count--) {
4023 AllocRecord* record = &recent_allocation_records_[i];
4024
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004025 LOG(INFO) << StringPrintf(" Thread %-2d %6zd bytes ", record->thin_lock_id, record->byte_count)
Elliott Hughes545a0642011-11-08 19:10:03 -08004026 << PrettyClass(record->type);
4027
4028 for (size_t stack_frame = 0; stack_frame < kMaxAllocRecordStackDepth; ++stack_frame) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08004029 mirror::ArtMethod* m = record->stack[stack_frame].method;
Elliott Hughes545a0642011-11-08 19:10:03 -08004030 if (m == NULL) {
4031 break;
4032 }
4033 LOG(INFO) << " " << PrettyMethod(m) << " line " << record->stack[stack_frame].LineNumber();
4034 }
4035
4036 // pause periodically to help logcat catch up
4037 if ((count % 5) == 0) {
4038 usleep(40000);
4039 }
4040
Ian Rogers719d1a32014-03-06 12:13:39 -08004041 i = (i + 1) & (alloc_record_max_ - 1);
Elliott Hughes545a0642011-11-08 19:10:03 -08004042 }
4043}
4044
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -07004045void Dbg::UpdateObjectPointers(IsMarkedCallback* callback, void* arg) {
Ian Rogers719d1a32014-03-06 12:13:39 -08004046 if (recent_allocation_records_ != nullptr) {
4047 MutexLock mu(Thread::Current(), *alloc_tracker_lock_);
4048 size_t i = HeadIndex();
4049 size_t count = alloc_record_count_;
4050 while (count--) {
4051 AllocRecord* record = &recent_allocation_records_[i];
4052 DCHECK(record != nullptr);
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -07004053 record->UpdateObjectPointers(callback, arg);
Ian Rogers719d1a32014-03-06 12:13:39 -08004054 i = (i + 1) & (alloc_record_max_ - 1);
Mathieu Chartier412c7fc2014-02-07 12:18:39 -08004055 }
4056 }
4057 if (gRegistry != nullptr) {
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -07004058 gRegistry->UpdateObjectPointers(callback, arg);
Mathieu Chartier412c7fc2014-02-07 12:18:39 -08004059 }
4060}
4061
4062void Dbg::AllowNewObjectRegistryObjects() {
4063 if (gRegistry != nullptr) {
4064 gRegistry->AllowNewObjects();
4065 }
4066}
4067
4068void Dbg::DisallowNewObjectRegistryObjects() {
4069 if (gRegistry != nullptr) {
4070 gRegistry->DisallowNewObjects();
4071 }
4072}
4073
Elliott Hughes545a0642011-11-08 19:10:03 -08004074class StringTable {
4075 public:
4076 StringTable() {
4077 }
4078
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004079 void Add(const char* s) {
Elliott Hughes545a0642011-11-08 19:10:03 -08004080 table_.insert(s);
4081 }
4082
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004083 size_t IndexOf(const char* s) const {
Mathieu Chartier02e25112013-08-14 16:14:24 -07004084 auto it = table_.find(s);
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004085 if (it == table_.end()) {
4086 LOG(FATAL) << "IndexOf(\"" << s << "\") failed";
4087 }
4088 return std::distance(table_.begin(), it);
Elliott Hughes545a0642011-11-08 19:10:03 -08004089 }
4090
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004091 size_t Size() const {
Elliott Hughes545a0642011-11-08 19:10:03 -08004092 return table_.size();
4093 }
4094
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004095 void WriteTo(std::vector<uint8_t>& bytes) const {
Mathieu Chartier02e25112013-08-14 16:14:24 -07004096 for (const std::string& str : table_) {
4097 const char* s = str.c_str();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004098 size_t s_len = CountModifiedUtf8Chars(s);
4099 UniquePtr<uint16_t> s_utf16(new uint16_t[s_len]);
4100 ConvertModifiedUtf8ToUtf16(s_utf16.get(), s);
4101 JDWP::AppendUtf16BE(bytes, s_utf16.get(), s_len);
Elliott Hughes545a0642011-11-08 19:10:03 -08004102 }
4103 }
4104
4105 private:
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004106 std::set<std::string> table_;
Elliott Hughes545a0642011-11-08 19:10:03 -08004107 DISALLOW_COPY_AND_ASSIGN(StringTable);
4108};
4109
4110/*
4111 * The data we send to DDMS contains everything we have recorded.
4112 *
4113 * Message header (all values big-endian):
4114 * (1b) message header len (to allow future expansion); includes itself
4115 * (1b) entry header len
4116 * (1b) stack frame len
4117 * (2b) number of entries
4118 * (4b) offset to string table from start of message
4119 * (2b) number of class name strings
4120 * (2b) number of method name strings
4121 * (2b) number of source file name strings
4122 * For each entry:
4123 * (4b) total allocation size
Elliott Hughes221229c2013-01-08 18:17:50 -08004124 * (2b) thread id
Elliott Hughes545a0642011-11-08 19:10:03 -08004125 * (2b) allocated object's class name index
4126 * (1b) stack depth
4127 * For each stack frame:
4128 * (2b) method's class name
4129 * (2b) method name
4130 * (2b) method source file
4131 * (2b) line number, clipped to 32767; -2 if native; -1 if no source
4132 * (xb) class name strings
4133 * (xb) method name strings
4134 * (xb) source file strings
4135 *
4136 * As with other DDM traffic, strings are sent as a 4-byte length
4137 * followed by UTF-16 data.
4138 *
4139 * We send up 16-bit unsigned indexes into string tables. In theory there
Elliott Hughesb1a58792013-07-11 18:10:58 -07004140 * can be (kMaxAllocRecordStackDepth * gAllocRecordMax) unique strings in
Elliott Hughes545a0642011-11-08 19:10:03 -08004141 * each table, but in practice there should be far fewer.
4142 *
4143 * The chief reason for using a string table here is to keep the size of
4144 * the DDMS message to a minimum. This is partly to make the protocol
4145 * efficient, but also because we have to form the whole thing up all at
4146 * once in a memory buffer.
4147 *
4148 * We use separate string tables for class names, method names, and source
4149 * files to keep the indexes small. There will generally be no overlap
4150 * between the contents of these tables.
4151 */
4152jbyteArray Dbg::GetRecentAllocations() {
4153 if (false) {
4154 DumpRecentAllocations();
4155 }
4156
Ian Rogers50b35e22012-10-04 10:09:15 -07004157 Thread* self = Thread::Current();
Elliott Hughes545a0642011-11-08 19:10:03 -08004158 std::vector<uint8_t> bytes;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004159 {
Ian Rogers719d1a32014-03-06 12:13:39 -08004160 MutexLock mu(self, *alloc_tracker_lock_);
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004161 //
4162 // Part 1: generate string tables.
4163 //
4164 StringTable class_names;
4165 StringTable method_names;
4166 StringTable filenames;
Elliott Hughes545a0642011-11-08 19:10:03 -08004167
Ian Rogers719d1a32014-03-06 12:13:39 -08004168 int count = alloc_record_count_;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004169 int idx = HeadIndex();
4170 while (count--) {
4171 AllocRecord* record = &recent_allocation_records_[idx];
Elliott Hughes545a0642011-11-08 19:10:03 -08004172
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004173 class_names.Add(ClassHelper(record->type).GetDescriptor());
Elliott Hughes545a0642011-11-08 19:10:03 -08004174
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004175 MethodHelper mh;
4176 for (size_t i = 0; i < kMaxAllocRecordStackDepth; i++) {
Brian Carlstromea46f952013-07-30 01:26:50 -07004177 mirror::ArtMethod* m = record->stack[i].method;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004178 if (m != NULL) {
4179 mh.ChangeMethod(m);
4180 class_names.Add(mh.GetDeclaringClassDescriptor());
4181 method_names.Add(mh.GetName());
4182 filenames.Add(mh.GetDeclaringClassSourceFile());
4183 }
4184 }
Elliott Hughes545a0642011-11-08 19:10:03 -08004185
Ian Rogers719d1a32014-03-06 12:13:39 -08004186 idx = (idx + 1) & (alloc_record_max_ - 1);
Elliott Hughes545a0642011-11-08 19:10:03 -08004187 }
4188
Ian Rogers719d1a32014-03-06 12:13:39 -08004189 LOG(INFO) << "allocation records: " << alloc_record_count_;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004190
4191 //
4192 // Part 2: Generate the output and store it in the buffer.
4193 //
4194
4195 // (1b) message header len (to allow future expansion); includes itself
4196 // (1b) entry header len
4197 // (1b) stack frame len
4198 const int kMessageHeaderLen = 15;
4199 const int kEntryHeaderLen = 9;
4200 const int kStackFrameLen = 8;
4201 JDWP::Append1BE(bytes, kMessageHeaderLen);
4202 JDWP::Append1BE(bytes, kEntryHeaderLen);
4203 JDWP::Append1BE(bytes, kStackFrameLen);
4204
4205 // (2b) number of entries
4206 // (4b) offset to string table from start of message
4207 // (2b) number of class name strings
4208 // (2b) number of method name strings
4209 // (2b) number of source file name strings
Ian Rogers719d1a32014-03-06 12:13:39 -08004210 JDWP::Append2BE(bytes, alloc_record_count_);
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004211 size_t string_table_offset = bytes.size();
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004212 JDWP::Append4BE(bytes, 0); // We'll patch this later...
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004213 JDWP::Append2BE(bytes, class_names.Size());
4214 JDWP::Append2BE(bytes, method_names.Size());
4215 JDWP::Append2BE(bytes, filenames.Size());
4216
Ian Rogers719d1a32014-03-06 12:13:39 -08004217 count = alloc_record_count_;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004218 idx = HeadIndex();
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004219 while (count--) {
4220 // For each entry:
4221 // (4b) total allocation size
4222 // (2b) thread id
4223 // (2b) allocated object's class name index
4224 // (1b) stack depth
4225 AllocRecord* record = &recent_allocation_records_[idx];
4226 size_t stack_depth = record->GetDepth();
Mathieu Chartier590fee92013-09-13 13:46:47 -07004227 ClassHelper kh(record->type);
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004228 size_t allocated_object_class_name_index = class_names.IndexOf(kh.GetDescriptor());
4229 JDWP::Append4BE(bytes, record->byte_count);
4230 JDWP::Append2BE(bytes, record->thin_lock_id);
4231 JDWP::Append2BE(bytes, allocated_object_class_name_index);
4232 JDWP::Append1BE(bytes, stack_depth);
4233
4234 MethodHelper mh;
4235 for (size_t stack_frame = 0; stack_frame < stack_depth; ++stack_frame) {
4236 // For each stack frame:
4237 // (2b) method's class name
4238 // (2b) method name
4239 // (2b) method source file
4240 // (2b) line number, clipped to 32767; -2 if native; -1 if no source
4241 mh.ChangeMethod(record->stack[stack_frame].method);
4242 size_t class_name_index = class_names.IndexOf(mh.GetDeclaringClassDescriptor());
4243 size_t method_name_index = method_names.IndexOf(mh.GetName());
4244 size_t file_name_index = filenames.IndexOf(mh.GetDeclaringClassSourceFile());
4245 JDWP::Append2BE(bytes, class_name_index);
4246 JDWP::Append2BE(bytes, method_name_index);
4247 JDWP::Append2BE(bytes, file_name_index);
4248 JDWP::Append2BE(bytes, record->stack[stack_frame].LineNumber());
4249 }
4250
Ian Rogers719d1a32014-03-06 12:13:39 -08004251 idx = (idx + 1) & (alloc_record_max_ - 1);
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004252 }
4253
4254 // (xb) class name strings
4255 // (xb) method name strings
4256 // (xb) source file strings
4257 JDWP::Set4BE(&bytes[string_table_offset], bytes.size());
4258 class_names.WriteTo(bytes);
4259 method_names.WriteTo(bytes);
4260 filenames.WriteTo(bytes);
Elliott Hughes545a0642011-11-08 19:10:03 -08004261 }
Ian Rogers50b35e22012-10-04 10:09:15 -07004262 JNIEnv* env = self->GetJniEnv();
Elliott Hughes545a0642011-11-08 19:10:03 -08004263 jbyteArray result = env->NewByteArray(bytes.size());
4264 if (result != NULL) {
4265 env->SetByteArrayRegion(result, 0, bytes.size(), reinterpret_cast<const jbyte*>(&bytes[0]));
4266 }
4267 return result;
4268}
4269
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004270} // namespace art