blob: 9af9c7a00c2b9fbc705e05e3572383a3e8f6d9b2 [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
234void SingleStepControl::VisitRoots(RootCallback* callback, void* arg, uint32_t tid,
235 RootType root_type) {
236 if (method != nullptr) {
237 callback(reinterpret_cast<mirror::Object**>(&method), arg, tid, root_type);
238 }
239}
240
Sebastien Hertz4d25df32014-03-21 17:44:46 +0100241void DeoptimizationRequest::VisitRoots(RootCallback* callback, void* arg) {
242 if (method != nullptr) {
243 callback(reinterpret_cast<mirror::Object**>(&method), arg, 0, kRootDebugger);
244 }
245}
246
Brian Carlstromea46f952013-07-30 01:26:50 -0700247static bool IsBreakpoint(const mirror::ArtMethod* m, uint32_t dex_pc)
jeffhao09bfc6a2012-12-11 18:11:43 -0800248 LOCKS_EXCLUDED(Locks::breakpoint_lock_)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700249 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
jeffhao09bfc6a2012-12-11 18:11:43 -0800250 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100251 for (size_t i = 0, e = gBreakpoints.size(); i < e; ++i) {
Elliott Hughesa656a0f2012-02-21 18:03:44 -0800252 if (gBreakpoints[i].method == m && gBreakpoints[i].dex_pc == dex_pc) {
Elliott Hughes86964332012-02-15 19:37:42 -0800253 VLOG(jdwp) << "Hit breakpoint #" << i << ": " << gBreakpoints[i];
254 return true;
255 }
256 }
257 return false;
258}
259
Sebastien Hertz52d131d2014-03-13 16:17:40 +0100260static bool IsSuspendedForDebugger(ScopedObjectAccessUnchecked& soa, Thread* thread)
261 LOCKS_EXCLUDED(Locks::thread_suspend_count_lock_) {
Elliott Hughes9e0c1752013-01-09 14:02:58 -0800262 MutexLock mu(soa.Self(), *Locks::thread_suspend_count_lock_);
263 // A thread may be suspended for GC; in this code, we really want to know whether
264 // there's a debugger suspension active.
265 return thread->IsSuspended() && thread->GetDebugSuspendCount() > 0;
266}
267
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800268static mirror::Array* DecodeArray(JDWP::RefTypeId id, JDWP::JdwpError& status)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700269 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800270 mirror::Object* o = gRegistry->Get<mirror::Object*>(id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800271 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800272 status = JDWP::ERR_INVALID_OBJECT;
273 return NULL;
274 }
275 if (!o->IsArrayInstance()) {
276 status = JDWP::ERR_INVALID_ARRAY;
277 return NULL;
278 }
279 status = JDWP::ERR_NONE;
280 return o->AsArray();
281}
282
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800283static mirror::Class* DecodeClass(JDWP::RefTypeId id, JDWP::JdwpError& status)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700284 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800285 mirror::Object* o = gRegistry->Get<mirror::Object*>(id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800286 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800287 status = JDWP::ERR_INVALID_OBJECT;
288 return NULL;
289 }
290 if (!o->IsClass()) {
291 status = JDWP::ERR_INVALID_CLASS;
292 return NULL;
293 }
294 status = JDWP::ERR_NONE;
295 return o->AsClass();
296}
297
Elliott Hughes221229c2013-01-08 18:17:50 -0800298static JDWP::JdwpError DecodeThread(ScopedObjectAccessUnchecked& soa, JDWP::ObjectId thread_id, Thread*& thread)
jeffhaoa77f0f62012-12-05 17:19:31 -0800299 EXCLUSIVE_LOCKS_REQUIRED(Locks::thread_list_lock_)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700300 LOCKS_EXCLUDED(Locks::thread_suspend_count_lock_)
301 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800302 mirror::Object* thread_peer = gRegistry->Get<mirror::Object*>(thread_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800303 if (thread_peer == NULL || thread_peer == ObjectRegistry::kInvalidObject) {
Elliott Hughes221229c2013-01-08 18:17:50 -0800304 // This isn't even an object.
305 return JDWP::ERR_INVALID_OBJECT;
Elliott Hughes436e3722012-02-17 20:01:47 -0800306 }
Elliott Hughes221229c2013-01-08 18:17:50 -0800307
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800308 mirror::Class* java_lang_Thread = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_Thread);
Elliott Hughes221229c2013-01-08 18:17:50 -0800309 if (!java_lang_Thread->IsAssignableFrom(thread_peer->GetClass())) {
310 // This isn't a thread.
311 return JDWP::ERR_INVALID_THREAD;
312 }
313
314 thread = Thread::FromManagedThread(soa, thread_peer);
315 if (thread == NULL) {
316 // This is a java.lang.Thread without a Thread*. Must be a zombie.
317 return JDWP::ERR_THREAD_NOT_ALIVE;
318 }
319 return JDWP::ERR_NONE;
Elliott Hughes436e3722012-02-17 20:01:47 -0800320}
321
Elliott Hughes24437992011-11-30 14:49:33 -0800322static JDWP::JdwpTag BasicTagFromDescriptor(const char* descriptor) {
323 // JDWP deliberately uses the descriptor characters' ASCII values for its enum.
324 // Note that by "basic" we mean that we don't get more specific than JT_OBJECT.
325 return static_cast<JDWP::JdwpTag>(descriptor[0]);
326}
327
Ian Rogers98379392014-02-24 16:53:16 -0800328static JDWP::JdwpTag TagFromClass(const ScopedObjectAccessUnchecked& soa, mirror::Class* c)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700329 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes86b00102011-12-05 17:54:26 -0800330 CHECK(c != NULL);
Elliott Hughes24437992011-11-30 14:49:33 -0800331 if (c->IsArrayClass()) {
332 return JDWP::JT_ARRAY;
333 }
Elliott Hughes24437992011-11-30 14:49:33 -0800334 if (c->IsStringClass()) {
335 return JDWP::JT_STRING;
Elliott Hughes24437992011-11-30 14:49:33 -0800336 }
Ian Rogers98379392014-02-24 16:53:16 -0800337 if (c->IsClassClass()) {
338 return JDWP::JT_CLASS_OBJECT;
339 }
340 {
341 mirror::Class* thread_class = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_Thread);
342 if (thread_class->IsAssignableFrom(c)) {
343 return JDWP::JT_THREAD;
344 }
345 }
346 {
347 mirror::Class* thread_group_class =
348 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_ThreadGroup);
349 if (thread_group_class->IsAssignableFrom(c)) {
350 return JDWP::JT_THREAD_GROUP;
351 }
352 }
353 {
354 mirror::Class* class_loader_class =
355 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_ClassLoader);
356 if (class_loader_class->IsAssignableFrom(c)) {
357 return JDWP::JT_CLASS_LOADER;
358 }
359 }
360 return JDWP::JT_OBJECT;
Elliott Hughes24437992011-11-30 14:49:33 -0800361}
362
363/*
364 * Objects declared to hold Object might actually hold a more specific
365 * type. The debugger may take a special interest in these (e.g. it
366 * wants to display the contents of Strings), so we want to return an
367 * appropriate tag.
368 *
369 * Null objects are tagged JT_OBJECT.
370 */
Ian Rogers98379392014-02-24 16:53:16 -0800371static JDWP::JdwpTag TagFromObject(const ScopedObjectAccessUnchecked& soa, mirror::Object* o)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700372 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers98379392014-02-24 16:53:16 -0800373 return (o == NULL) ? JDWP::JT_OBJECT : TagFromClass(soa, o->GetClass());
Elliott Hughes24437992011-11-30 14:49:33 -0800374}
375
376static bool IsPrimitiveTag(JDWP::JdwpTag tag) {
377 switch (tag) {
378 case JDWP::JT_BOOLEAN:
379 case JDWP::JT_BYTE:
380 case JDWP::JT_CHAR:
381 case JDWP::JT_FLOAT:
382 case JDWP::JT_DOUBLE:
383 case JDWP::JT_INT:
384 case JDWP::JT_LONG:
385 case JDWP::JT_SHORT:
386 case JDWP::JT_VOID:
387 return true;
388 default:
389 return false;
390 }
391}
392
Elliott Hughes3bb81562011-10-21 18:52:59 -0700393/*
394 * Handle one of the JDWP name/value pairs.
395 *
396 * JDWP options are:
397 * help: if specified, show help message and bail
398 * transport: may be dt_socket or dt_shmem
399 * address: for dt_socket, "host:port", or just "port" when listening
400 * server: if "y", wait for debugger to attach; if "n", attach to debugger
401 * timeout: how long to wait for debugger to connect / listen
402 *
403 * Useful with server=n (these aren't supported yet):
404 * onthrow=<exception-name>: connect to debugger when exception thrown
405 * onuncaught=y|n: connect to debugger when uncaught exception thrown
406 * launch=<command-line>: launch the debugger itself
407 *
408 * The "transport" option is required, as is "address" if server=n.
409 */
410static bool ParseJdwpOption(const std::string& name, const std::string& value) {
411 if (name == "transport") {
412 if (value == "dt_socket") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700413 gJdwpOptions.transport = JDWP::kJdwpTransportSocket;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700414 } else if (value == "dt_android_adb") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700415 gJdwpOptions.transport = JDWP::kJdwpTransportAndroidAdb;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700416 } else {
417 LOG(ERROR) << "JDWP transport not supported: " << value;
418 return false;
419 }
420 } else if (name == "server") {
421 if (value == "n") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700422 gJdwpOptions.server = false;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700423 } else if (value == "y") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700424 gJdwpOptions.server = true;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700425 } else {
426 LOG(ERROR) << "JDWP option 'server' must be 'y' or 'n'";
427 return false;
428 }
429 } else if (name == "suspend") {
430 if (value == "n") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700431 gJdwpOptions.suspend = false;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700432 } else if (value == "y") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700433 gJdwpOptions.suspend = true;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700434 } else {
435 LOG(ERROR) << "JDWP option 'suspend' must be 'y' or 'n'";
436 return false;
437 }
438 } else if (name == "address") {
439 /* this is either <port> or <host>:<port> */
440 std::string port_string;
Elliott Hughes376a7a02011-10-24 18:35:55 -0700441 gJdwpOptions.host.clear();
Elliott Hughes3bb81562011-10-21 18:52:59 -0700442 std::string::size_type colon = value.find(':');
443 if (colon != std::string::npos) {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700444 gJdwpOptions.host = value.substr(0, colon);
Elliott Hughes3bb81562011-10-21 18:52:59 -0700445 port_string = value.substr(colon + 1);
446 } else {
447 port_string = value;
448 }
449 if (port_string.empty()) {
450 LOG(ERROR) << "JDWP address missing port: " << value;
451 return false;
452 }
453 char* end;
Elliott Hughesba8eee12012-01-24 20:25:24 -0800454 uint64_t port = strtoul(port_string.c_str(), &end, 10);
455 if (*end != '\0' || port > 0xffff) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700456 LOG(ERROR) << "JDWP address has junk in port field: " << value;
457 return false;
458 }
Elliott Hughes376a7a02011-10-24 18:35:55 -0700459 gJdwpOptions.port = port;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700460 } else if (name == "launch" || name == "onthrow" || name == "oncaught" || name == "timeout") {
461 /* valid but unsupported */
462 LOG(INFO) << "Ignoring JDWP option '" << name << "'='" << value << "'";
463 } else {
464 LOG(INFO) << "Ignoring unrecognized JDWP option '" << name << "'='" << value << "'";
465 }
466
467 return true;
468}
469
470/*
471 * Parse the latter half of a -Xrunjdwp/-agentlib:jdwp= string, e.g.:
472 * "transport=dt_socket,address=8000,server=y,suspend=n"
473 */
474bool Dbg::ParseJdwpOptions(const std::string& options) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800475 VLOG(jdwp) << "ParseJdwpOptions: " << options;
Elliott Hughes47fce012011-10-25 18:37:19 -0700476
Elliott Hughes3bb81562011-10-21 18:52:59 -0700477 std::vector<std::string> pairs;
478 Split(options, ',', pairs);
479
480 for (size_t i = 0; i < pairs.size(); ++i) {
481 std::string::size_type equals = pairs[i].find('=');
482 if (equals == std::string::npos) {
483 LOG(ERROR) << "Can't parse JDWP option '" << pairs[i] << "' in '" << options << "'";
484 return false;
485 }
486 ParseJdwpOption(pairs[i].substr(0, equals), pairs[i].substr(equals + 1));
487 }
488
Elliott Hughes376a7a02011-10-24 18:35:55 -0700489 if (gJdwpOptions.transport == JDWP::kJdwpTransportUnknown) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700490 LOG(ERROR) << "Must specify JDWP transport: " << options;
491 }
Elliott Hughes376a7a02011-10-24 18:35:55 -0700492 if (!gJdwpOptions.server && (gJdwpOptions.host.empty() || gJdwpOptions.port == 0)) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700493 LOG(ERROR) << "Must specify JDWP host and port when server=n: " << options;
494 return false;
495 }
496
497 gJdwpConfigured = true;
498 return true;
499}
500
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700501void Dbg::StartJdwp() {
Elliott Hughesc0f09332012-03-26 13:27:06 -0700502 if (!gJdwpAllowed || !IsJdwpConfigured()) {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700503 // No JDWP for you!
504 return;
505 }
506
Ian Rogers719d1a32014-03-06 12:13:39 -0800507 CHECK(gRegistry == nullptr);
Elliott Hughes475fc232011-10-25 15:00:35 -0700508 gRegistry = new ObjectRegistry;
509
Ian Rogers719d1a32014-03-06 12:13:39 -0800510 alloc_tracker_lock_ = new Mutex("AllocTracker lock");
Sebastien Hertz4d25df32014-03-21 17:44:46 +0100511 deoptimization_lock_ = new Mutex("deoptimization lock", kDeoptimizationLock);
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700512 // Init JDWP if the debugger is enabled. This may connect out to a
513 // debugger, passively listen for a debugger, or block waiting for a
514 // debugger.
Elliott Hughes376a7a02011-10-24 18:35:55 -0700515 gJdwpState = JDWP::JdwpState::Create(&gJdwpOptions);
516 if (gJdwpState == NULL) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -0800517 // We probably failed because some other process has the port already, which means that
518 // if we don't abort the user is likely to think they're talking to us when they're actually
519 // talking to that other process.
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800520 LOG(FATAL) << "Debugger thread failed to initialize";
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700521 }
522
523 // If a debugger has already attached, send the "welcome" message.
524 // This may cause us to suspend all threads.
Elliott Hughes376a7a02011-10-24 18:35:55 -0700525 if (gJdwpState->IsActive()) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700526 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes376a7a02011-10-24 18:35:55 -0700527 if (!gJdwpState->PostVMStart()) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800528 LOG(WARNING) << "Failed to post 'start' message to debugger";
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700529 }
530 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700531}
532
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700533void Dbg::VisitRoots(RootCallback* callback, void* arg) {
Sebastien Hertz4d25df32014-03-21 17:44:46 +0100534 {
535 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
536 for (Breakpoint& bp : gBreakpoints) {
537 bp.VisitRoots(callback, arg);
538 }
539 }
540 if (deoptimization_lock_ != nullptr) { // only true if the debugger is started.
541 MutexLock mu(Thread::Current(), *deoptimization_lock_);
542 for (DeoptimizationRequest& req : deoptimization_requests_) {
543 req.VisitRoots(callback, arg);
544 }
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700545 }
546}
547
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700548void Dbg::StopJdwp() {
Sebastien Hertz0376e6b2014-02-06 18:12:59 +0100549 // Prevent the JDWP thread from processing JDWP incoming packets after we close the connection.
550 Disposed();
Elliott Hughes376a7a02011-10-24 18:35:55 -0700551 delete gJdwpState;
Ian Rogers719d1a32014-03-06 12:13:39 -0800552 gJdwpState = nullptr;
Elliott Hughes475fc232011-10-25 15:00:35 -0700553 delete gRegistry;
Ian Rogers719d1a32014-03-06 12:13:39 -0800554 gRegistry = nullptr;
555 delete alloc_tracker_lock_;
556 alloc_tracker_lock_ = nullptr;
Sebastien Hertz4d25df32014-03-21 17:44:46 +0100557 delete deoptimization_lock_;
558 deoptimization_lock_ = nullptr;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700559}
560
Elliott Hughes767a1472011-10-26 18:49:02 -0700561void Dbg::GcDidFinish() {
562 if (gDdmHpifWhen != HPIF_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700563 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes81ff3182012-03-23 20:35:56 -0700564 LOG(DEBUG) << "Sending heap info to DDM";
Elliott Hughes7162ad92011-10-27 14:08:42 -0700565 DdmSendHeapInfo(gDdmHpifWhen);
Elliott Hughes767a1472011-10-26 18:49:02 -0700566 }
567 if (gDdmHpsgWhen != HPSG_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700568 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes81ff3182012-03-23 20:35:56 -0700569 LOG(DEBUG) << "Dumping heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700570 DdmSendHeapSegments(false);
Elliott Hughes767a1472011-10-26 18:49:02 -0700571 }
572 if (gDdmNhsgWhen != HPSG_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700573 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes767a1472011-10-26 18:49:02 -0700574 LOG(DEBUG) << "Dumping native heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700575 DdmSendHeapSegments(true);
Elliott Hughes767a1472011-10-26 18:49:02 -0700576 }
577}
578
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700579void Dbg::SetJdwpAllowed(bool allowed) {
580 gJdwpAllowed = allowed;
581}
582
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700583DebugInvokeReq* Dbg::GetInvokeReq() {
Elliott Hughes475fc232011-10-25 15:00:35 -0700584 return Thread::Current()->GetInvokeReq();
585}
586
587Thread* Dbg::GetDebugThread() {
588 return (gJdwpState != NULL) ? gJdwpState->GetDebugThread() : NULL;
589}
590
591void Dbg::ClearWaitForEventThread() {
592 gJdwpState->ClearWaitForEventThread();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700593}
594
595void Dbg::Connected() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700596 CHECK(!gDebuggerConnected);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800597 VLOG(jdwp) << "JDWP has attached";
Elliott Hughes3bb81562011-10-21 18:52:59 -0700598 gDebuggerConnected = true;
Elliott Hughes86964332012-02-15 19:37:42 -0800599 gDisposed = false;
600}
601
602void Dbg::Disposed() {
603 gDisposed = true;
604}
605
606bool Dbg::IsDisposed() {
607 return gDisposed;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700608}
609
Elliott Hughesa2155262011-11-16 16:26:58 -0800610void Dbg::GoActive() {
611 // Enable all debugging features, including scans for breakpoints.
612 // This is a no-op if we're already active.
613 // Only called from the JDWP handler thread.
614 if (gDebuggerActive) {
615 return;
616 }
617
Elliott Hughesc0f09332012-03-26 13:27:06 -0700618 {
619 // TODO: dalvik only warned if there were breakpoints left over. clear in Dbg::Disconnected?
jeffhao09bfc6a2012-12-11 18:11:43 -0800620 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Elliott Hughesc0f09332012-03-26 13:27:06 -0700621 CHECK_EQ(gBreakpoints.size(), 0U);
622 }
Elliott Hughesa2155262011-11-16 16:26:58 -0800623
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100624 {
Sebastien Hertz4d25df32014-03-21 17:44:46 +0100625 MutexLock mu(Thread::Current(), *deoptimization_lock_);
626 CHECK_EQ(deoptimization_requests_.size(), 0U);
627 CHECK_EQ(full_deoptimization_event_count_, 0U);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100628 }
629
Ian Rogers62d6c772013-02-27 08:32:07 -0800630 Runtime* runtime = Runtime::Current();
631 runtime->GetThreadList()->SuspendAll();
632 Thread* self = Thread::Current();
633 ThreadState old_state = self->SetStateUnsafe(kRunnable);
634 CHECK_NE(old_state, kRunnable);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100635 runtime->GetInstrumentation()->EnableDeoptimization();
Ian Rogers62d6c772013-02-27 08:32:07 -0800636 runtime->GetInstrumentation()->AddListener(&gDebugInstrumentationListener,
637 instrumentation::Instrumentation::kMethodEntered |
638 instrumentation::Instrumentation::kMethodExited |
Jeff Hao14dd5a82013-04-11 10:23:36 -0700639 instrumentation::Instrumentation::kDexPcMoved |
640 instrumentation::Instrumentation::kExceptionCaught);
Elliott Hughesa2155262011-11-16 16:26:58 -0800641 gDebuggerActive = true;
Ian Rogers62d6c772013-02-27 08:32:07 -0800642 CHECK_EQ(self->SetStateUnsafe(old_state), kRunnable);
643 runtime->GetThreadList()->ResumeAll();
644
645 LOG(INFO) << "Debugger is active";
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700646}
647
648void Dbg::Disconnected() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700649 CHECK(gDebuggerConnected);
650
Elliott Hughesc0f09332012-03-26 13:27:06 -0700651 LOG(INFO) << "Debugger is no longer active";
Elliott Hughes234ab152011-10-26 14:02:26 -0700652
Ian Rogers62d6c772013-02-27 08:32:07 -0800653 // Suspend all threads and exclusively acquire the mutator lock. Set the state of the thread
654 // to kRunnable to avoid scoped object access transitions. Remove the debugger as a listener
655 // and clear the object registry.
656 Runtime* runtime = Runtime::Current();
657 runtime->GetThreadList()->SuspendAll();
658 Thread* self = Thread::Current();
659 ThreadState old_state = self->SetStateUnsafe(kRunnable);
Sebastien Hertzaaea7342014-02-25 15:10:04 +0100660
661 // Debugger may not be active at this point.
662 if (gDebuggerActive) {
663 {
664 // Since we're going to disable deoptimization, we clear the deoptimization requests queue.
665 // This prevents us from having any pending deoptimization request when the debugger attaches
666 // to us again while no event has been requested yet.
Sebastien Hertz4d25df32014-03-21 17:44:46 +0100667 MutexLock mu(Thread::Current(), *deoptimization_lock_);
668 deoptimization_requests_.clear();
669 full_deoptimization_event_count_ = 0U;
Sebastien Hertzaaea7342014-02-25 15:10:04 +0100670 }
671 runtime->GetInstrumentation()->RemoveListener(&gDebugInstrumentationListener,
672 instrumentation::Instrumentation::kMethodEntered |
673 instrumentation::Instrumentation::kMethodExited |
674 instrumentation::Instrumentation::kDexPcMoved |
675 instrumentation::Instrumentation::kExceptionCaught);
676 runtime->GetInstrumentation()->DisableDeoptimization();
677 gDebuggerActive = false;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100678 }
Elliott Hughes234ab152011-10-26 14:02:26 -0700679 gRegistry->Clear();
680 gDebuggerConnected = false;
Ian Rogers62d6c772013-02-27 08:32:07 -0800681 CHECK_EQ(self->SetStateUnsafe(old_state), kRunnable);
682 runtime->GetThreadList()->ResumeAll();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700683}
684
Elliott Hughesc0f09332012-03-26 13:27:06 -0700685bool Dbg::IsDebuggerActive() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700686 return gDebuggerActive;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700687}
688
Elliott Hughesc0f09332012-03-26 13:27:06 -0700689bool Dbg::IsJdwpConfigured() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700690 return gJdwpConfigured;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700691}
692
693int64_t Dbg::LastDebuggerActivity() {
Elliott Hughesca951522011-12-05 12:01:32 -0800694 return gJdwpState->LastDebuggerActivity();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700695}
696
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700697void Dbg::UndoDebuggerSuspensions() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700698 Runtime::Current()->GetThreadList()->UndoDebuggerSuspensions();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700699}
700
Elliott Hughes88d63092013-01-09 09:55:54 -0800701std::string Dbg::GetClassName(JDWP::RefTypeId class_id) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800702 mirror::Object* o = gRegistry->Get<mirror::Object*>(class_id);
Elliott Hughes436e3722012-02-17 20:01:47 -0800703 if (o == NULL) {
704 return "NULL";
705 }
Elliott Hughes64f574f2013-02-20 14:57:12 -0800706 if (o == ObjectRegistry::kInvalidObject) {
Elliott Hughes88d63092013-01-09 09:55:54 -0800707 return StringPrintf("invalid object %p", reinterpret_cast<void*>(class_id));
Elliott Hughes436e3722012-02-17 20:01:47 -0800708 }
709 if (!o->IsClass()) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700710 return StringPrintf("non-class %p", o); // This is only used for debugging output anyway.
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800711 }
Elliott Hughesc308a5d2012-02-16 17:12:06 -0800712 return DescriptorToName(ClassHelper(o->AsClass()).GetDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700713}
714
Elliott Hughes88d63092013-01-09 09:55:54 -0800715JDWP::JdwpError Dbg::GetClassObject(JDWP::RefTypeId id, JDWP::ObjectId& class_object_id) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800716 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800717 mirror::Class* c = DecodeClass(id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -0800718 if (c == NULL) {
719 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800720 }
Elliott Hughes88d63092013-01-09 09:55:54 -0800721 class_object_id = gRegistry->Add(c);
Elliott Hughes436e3722012-02-17 20:01:47 -0800722 return JDWP::ERR_NONE;
Elliott Hughes86964332012-02-15 19:37:42 -0800723}
724
Elliott Hughes88d63092013-01-09 09:55:54 -0800725JDWP::JdwpError Dbg::GetSuperclass(JDWP::RefTypeId id, JDWP::RefTypeId& superclass_id) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800726 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800727 mirror::Class* c = DecodeClass(id, status);
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800728 if (c == NULL) {
729 return status;
730 }
731 if (c->IsInterface()) {
732 // http://code.google.com/p/android/issues/detail?id=20856
Elliott Hughes88d63092013-01-09 09:55:54 -0800733 superclass_id = 0;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800734 } else {
Elliott Hughes88d63092013-01-09 09:55:54 -0800735 superclass_id = gRegistry->Add(c->GetSuperClass());
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800736 }
737 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700738}
739
Elliott Hughes436e3722012-02-17 20:01:47 -0800740JDWP::JdwpError Dbg::GetClassLoader(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800741 mirror::Object* o = gRegistry->Get<mirror::Object*>(id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800742 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800743 return JDWP::ERR_INVALID_OBJECT;
744 }
745 expandBufAddObjectId(pReply, gRegistry->Add(o->GetClass()->GetClassLoader()));
746 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700747}
748
Elliott Hughes436e3722012-02-17 20:01:47 -0800749JDWP::JdwpError Dbg::GetModifiers(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) {
750 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800751 mirror::Class* c = DecodeClass(id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -0800752 if (c == NULL) {
753 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800754 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800755
756 uint32_t access_flags = c->GetAccessFlags() & kAccJavaFlagsMask;
757
Yevgeny Roubande34eea2014-02-15 01:06:03 +0700758 // Set ACC_SUPER. Dex files don't contain this flag but only classes are supposed to have it set,
759 // not interfaces.
Elliott Hughes436e3722012-02-17 20:01:47 -0800760 // Class.getModifiers doesn't return it, but JDWP does, so we set it here.
Yevgeny Roubande34eea2014-02-15 01:06:03 +0700761 if ((access_flags & kAccInterface) == 0) {
762 access_flags |= kAccSuper;
763 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800764
765 expandBufAdd4BE(pReply, access_flags);
766
767 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700768}
769
Elliott Hughesf327e072013-01-09 16:01:26 -0800770JDWP::JdwpError Dbg::GetMonitorInfo(JDWP::ObjectId object_id, JDWP::ExpandBuf* reply)
771 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800772 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800773 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughesf327e072013-01-09 16:01:26 -0800774 return JDWP::ERR_INVALID_OBJECT;
775 }
776
777 // Ensure all threads are suspended while we read objects' lock words.
778 Thread* self = Thread::Current();
Sebastien Hertz54263242014-03-19 18:16:50 +0100779 CHECK_EQ(self->GetState(), kRunnable);
780 self->TransitionFromRunnableToSuspended(kSuspended);
781 Runtime::Current()->GetThreadList()->SuspendAll();
Elliott Hughesf327e072013-01-09 16:01:26 -0800782
783 MonitorInfo monitor_info(o);
784
Sebastien Hertz54263242014-03-19 18:16:50 +0100785 Runtime::Current()->GetThreadList()->ResumeAll();
786 self->TransitionFromSuspendedToRunnable();
Elliott Hughesf327e072013-01-09 16:01:26 -0800787
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700788 if (monitor_info.owner_ != NULL) {
789 expandBufAddObjectId(reply, gRegistry->Add(monitor_info.owner_->GetPeer()));
Elliott Hughesf327e072013-01-09 16:01:26 -0800790 } else {
791 expandBufAddObjectId(reply, gRegistry->Add(NULL));
792 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700793 expandBufAdd4BE(reply, monitor_info.entry_count_);
794 expandBufAdd4BE(reply, monitor_info.waiters_.size());
795 for (size_t i = 0; i < monitor_info.waiters_.size(); ++i) {
796 expandBufAddObjectId(reply, gRegistry->Add(monitor_info.waiters_[i]->GetPeer()));
Elliott Hughesf327e072013-01-09 16:01:26 -0800797 }
798 return JDWP::ERR_NONE;
799}
800
Elliott Hughes734b8c62013-01-11 15:32:45 -0800801JDWP::JdwpError Dbg::GetOwnedMonitors(JDWP::ObjectId thread_id,
802 std::vector<JDWP::ObjectId>& monitors,
Sebastien Hertz52d131d2014-03-13 16:17:40 +0100803 std::vector<uint32_t>& stack_depths) {
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800804 ScopedObjectAccessUnchecked soa(Thread::Current());
805 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
806 Thread* thread;
807 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
808 if (error != JDWP::ERR_NONE) {
809 return error;
810 }
811 if (!IsSuspendedForDebugger(soa, thread)) {
812 return JDWP::ERR_THREAD_NOT_SUSPENDED;
813 }
814
815 struct OwnedMonitorVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -0800816 OwnedMonitorVisitor(Thread* thread, Context* context)
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800817 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -0800818 : StackVisitor(thread, context), current_stack_depth(0) {}
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800819
820 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
821 // annotalysis.
822 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
823 if (!GetMethod()->IsRuntimeMethod()) {
824 Monitor::VisitLocks(this, AppendOwnedMonitors, this);
Elliott Hughes734b8c62013-01-11 15:32:45 -0800825 ++current_stack_depth;
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800826 }
827 return true;
828 }
829
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800830 static void AppendOwnedMonitors(mirror::Object* owned_monitor, void* arg) {
Ian Rogers7a22fa62013-01-23 12:16:16 -0800831 OwnedMonitorVisitor* visitor = reinterpret_cast<OwnedMonitorVisitor*>(arg);
Elliott Hughes734b8c62013-01-11 15:32:45 -0800832 visitor->monitors.push_back(owned_monitor);
833 visitor->stack_depths.push_back(visitor->current_stack_depth);
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800834 }
835
Elliott Hughes734b8c62013-01-11 15:32:45 -0800836 size_t current_stack_depth;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800837 std::vector<mirror::Object*> monitors;
Elliott Hughes734b8c62013-01-11 15:32:45 -0800838 std::vector<uint32_t> stack_depths;
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800839 };
Ian Rogers7a22fa62013-01-23 12:16:16 -0800840 UniquePtr<Context> context(Context::Create());
841 OwnedMonitorVisitor visitor(thread, context.get());
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800842 visitor.WalkStack();
843
844 for (size_t i = 0; i < visitor.monitors.size(); ++i) {
845 monitors.push_back(gRegistry->Add(visitor.monitors[i]));
Elliott Hughes734b8c62013-01-11 15:32:45 -0800846 stack_depths.push_back(visitor.stack_depths[i]);
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800847 }
848
849 return JDWP::ERR_NONE;
850}
851
Sebastien Hertz52d131d2014-03-13 16:17:40 +0100852JDWP::JdwpError Dbg::GetContendedMonitor(JDWP::ObjectId thread_id,
853 JDWP::ObjectId& contended_monitor) {
Elliott Hughesf9501702013-01-11 11:22:27 -0800854 ScopedObjectAccessUnchecked soa(Thread::Current());
855 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
856 Thread* thread;
857 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
858 if (error != JDWP::ERR_NONE) {
859 return error;
860 }
861 if (!IsSuspendedForDebugger(soa, thread)) {
862 return JDWP::ERR_THREAD_NOT_SUSPENDED;
863 }
864
865 contended_monitor = gRegistry->Add(Monitor::GetContendedMonitor(thread));
866
867 return JDWP::ERR_NONE;
868}
869
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800870JDWP::JdwpError Dbg::GetInstanceCounts(const std::vector<JDWP::RefTypeId>& class_ids,
871 std::vector<uint64_t>& counts)
872 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800873 gc::Heap* heap = Runtime::Current()->GetHeap();
874 heap->CollectGarbage(false);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800875 std::vector<mirror::Class*> classes;
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800876 counts.clear();
877 for (size_t i = 0; i < class_ids.size(); ++i) {
878 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800879 mirror::Class* c = DecodeClass(class_ids[i], status);
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800880 if (c == NULL) {
881 return status;
882 }
883 classes.push_back(c);
884 counts.push_back(0);
885 }
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800886 heap->CountInstances(classes, false, &counts[0]);
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800887 return JDWP::ERR_NONE;
888}
889
Elliott Hughes3b78c942013-01-15 17:35:41 -0800890JDWP::JdwpError Dbg::GetInstances(JDWP::RefTypeId class_id, int32_t max_count, std::vector<JDWP::ObjectId>& instances)
891 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800892 gc::Heap* heap = Runtime::Current()->GetHeap();
893 // We only want reachable instances, so do a GC.
894 heap->CollectGarbage(false);
Elliott Hughes3b78c942013-01-15 17:35:41 -0800895 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800896 mirror::Class* c = DecodeClass(class_id, status);
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800897 if (c == nullptr) {
Elliott Hughes3b78c942013-01-15 17:35:41 -0800898 return status;
899 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800900 std::vector<mirror::Object*> raw_instances;
Elliott Hughes3b78c942013-01-15 17:35:41 -0800901 Runtime::Current()->GetHeap()->GetInstances(c, max_count, raw_instances);
902 for (size_t i = 0; i < raw_instances.size(); ++i) {
903 instances.push_back(gRegistry->Add(raw_instances[i]));
904 }
905 return JDWP::ERR_NONE;
906}
907
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800908JDWP::JdwpError Dbg::GetReferringObjects(JDWP::ObjectId object_id, int32_t max_count,
909 std::vector<JDWP::ObjectId>& referring_objects)
910 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800911 gc::Heap* heap = Runtime::Current()->GetHeap();
912 heap->CollectGarbage(false);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800913 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800914 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800915 return JDWP::ERR_INVALID_OBJECT;
916 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800917 std::vector<mirror::Object*> raw_instances;
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800918 heap->GetReferringObjects(o, max_count, raw_instances);
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800919 for (size_t i = 0; i < raw_instances.size(); ++i) {
920 referring_objects.push_back(gRegistry->Add(raw_instances[i]));
921 }
922 return JDWP::ERR_NONE;
923}
924
Elliott Hughes64f574f2013-02-20 14:57:12 -0800925JDWP::JdwpError Dbg::DisableCollection(JDWP::ObjectId object_id)
926 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Sebastien Hertze96060a2013-12-11 12:06:28 +0100927 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
928 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
929 return JDWP::ERR_INVALID_OBJECT;
930 }
Elliott Hughes64f574f2013-02-20 14:57:12 -0800931 gRegistry->DisableCollection(object_id);
932 return JDWP::ERR_NONE;
933}
934
935JDWP::JdwpError Dbg::EnableCollection(JDWP::ObjectId object_id)
936 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Sebastien Hertze96060a2013-12-11 12:06:28 +0100937 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
938 // Unlike DisableCollection, JDWP specs do not state an invalid object causes an error. The RI
939 // also ignores these cases and never return an error. However it's not obvious why this command
940 // should behave differently from DisableCollection and IsCollected commands. So let's be more
941 // strict and return an error if this happens.
942 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
943 return JDWP::ERR_INVALID_OBJECT;
944 }
Elliott Hughes64f574f2013-02-20 14:57:12 -0800945 gRegistry->EnableCollection(object_id);
946 return JDWP::ERR_NONE;
947}
948
949JDWP::JdwpError Dbg::IsCollected(JDWP::ObjectId object_id, bool& is_collected)
950 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Sebastien Hertz65637eb2014-01-10 17:40:02 +0100951 if (object_id == 0) {
952 // Null object id is invalid.
Sebastien Hertze96060a2013-12-11 12:06:28 +0100953 return JDWP::ERR_INVALID_OBJECT;
954 }
Sebastien Hertz65637eb2014-01-10 17:40:02 +0100955 // JDWP specs state an INVALID_OBJECT error is returned if the object ID is not valid. However
956 // the RI seems to ignore this and assume object has been collected.
957 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
958 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
959 is_collected = true;
960 } else {
961 is_collected = gRegistry->IsCollected(object_id);
962 }
Elliott Hughes64f574f2013-02-20 14:57:12 -0800963 return JDWP::ERR_NONE;
964}
965
966void Dbg::DisposeObject(JDWP::ObjectId object_id, uint32_t reference_count)
967 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
968 gRegistry->DisposeObject(object_id, reference_count);
969}
970
Elliott Hughes88d63092013-01-09 09:55:54 -0800971JDWP::JdwpError Dbg::GetReflectedType(JDWP::RefTypeId class_id, JDWP::ExpandBuf* pReply) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800972 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800973 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -0800974 if (c == NULL) {
975 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800976 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800977
978 expandBufAdd1(pReply, c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS);
Elliott Hughes88d63092013-01-09 09:55:54 -0800979 expandBufAddRefTypeId(pReply, class_id);
Elliott Hughes436e3722012-02-17 20:01:47 -0800980 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700981}
982
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800983void Dbg::GetClassList(std::vector<JDWP::RefTypeId>& classes) {
Elliott Hughesa2155262011-11-16 16:26:58 -0800984 // Get the complete list of reference classes (i.e. all classes except
985 // the primitive types).
986 // Returns a newly-allocated buffer full of RefTypeId values.
987 struct ClassListCreator {
Elliott Hughesba8eee12012-01-24 20:25:24 -0800988 explicit ClassListCreator(std::vector<JDWP::RefTypeId>& classes) : classes(classes) {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800989 }
990
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800991 static bool Visit(mirror::Class* c, void* arg) {
Elliott Hughesa2155262011-11-16 16:26:58 -0800992 return reinterpret_cast<ClassListCreator*>(arg)->Visit(c);
993 }
994
Elliott Hughes64f574f2013-02-20 14:57:12 -0800995 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
996 // annotalysis.
997 bool Visit(mirror::Class* c) NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughesa2155262011-11-16 16:26:58 -0800998 if (!c->IsPrimitive()) {
Elliott Hughes64f574f2013-02-20 14:57:12 -0800999 classes.push_back(gRegistry->AddRefType(c));
Elliott Hughesa2155262011-11-16 16:26:58 -08001000 }
1001 return true;
1002 }
1003
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001004 std::vector<JDWP::RefTypeId>& classes;
Elliott Hughesa2155262011-11-16 16:26:58 -08001005 };
1006
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001007 ClassListCreator clc(classes);
Elliott Hughesa2155262011-11-16 16:26:58 -08001008 Runtime::Current()->GetClassLinker()->VisitClasses(ClassListCreator::Visit, &clc);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001009}
1010
Elliott Hughes88d63092013-01-09 09:55:54 -08001011JDWP::JdwpError Dbg::GetClassInfo(JDWP::RefTypeId class_id, JDWP::JdwpTypeTag* pTypeTag, uint32_t* pStatus, std::string* pDescriptor) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001012 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001013 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001014 if (c == NULL) {
1015 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001016 }
1017
Elliott Hughesa2155262011-11-16 16:26:58 -08001018 if (c->IsArrayClass()) {
1019 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
1020 *pTypeTag = JDWP::TT_ARRAY;
1021 } else {
1022 if (c->IsErroneous()) {
1023 *pStatus = JDWP::CS_ERROR;
1024 } else {
1025 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED | JDWP::CS_INITIALIZED;
1026 }
1027 *pTypeTag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
1028 }
1029
1030 if (pDescriptor != NULL) {
Ian Rogersdfb325e2013-10-30 01:00:44 -07001031 *pDescriptor = ClassHelper(c).GetDescriptor();
Elliott Hughesa2155262011-11-16 16:26:58 -08001032 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001033 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001034}
1035
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001036void Dbg::FindLoadedClassBySignature(const char* descriptor, std::vector<JDWP::RefTypeId>& ids) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001037 std::vector<mirror::Class*> classes;
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001038 Runtime::Current()->GetClassLinker()->LookupClasses(descriptor, classes);
1039 ids.clear();
1040 for (size_t i = 0; i < classes.size(); ++i) {
1041 ids.push_back(gRegistry->Add(classes[i]));
1042 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001043}
1044
Elliott Hughes64f574f2013-02-20 14:57:12 -08001045JDWP::JdwpError Dbg::GetReferenceType(JDWP::ObjectId object_id, JDWP::ExpandBuf* pReply)
1046 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001047 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001048 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001049 return JDWP::ERR_INVALID_OBJECT;
Elliott Hughes499c5132011-11-17 14:55:11 -08001050 }
Elliott Hughes2435a572012-02-17 16:07:41 -08001051
1052 JDWP::JdwpTypeTag type_tag;
1053 if (o->GetClass()->IsArrayClass()) {
1054 type_tag = JDWP::TT_ARRAY;
1055 } else if (o->GetClass()->IsInterface()) {
1056 type_tag = JDWP::TT_INTERFACE;
1057 } else {
1058 type_tag = JDWP::TT_CLASS;
1059 }
Elliott Hughes64f574f2013-02-20 14:57:12 -08001060 JDWP::RefTypeId type_id = gRegistry->AddRefType(o->GetClass());
Elliott Hughes2435a572012-02-17 16:07:41 -08001061
1062 expandBufAdd1(pReply, type_tag);
1063 expandBufAddRefTypeId(pReply, type_id);
1064
1065 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001066}
1067
Ian Rogersfc0e94b2013-09-23 23:51:32 -07001068JDWP::JdwpError Dbg::GetSignature(JDWP::RefTypeId class_id, std::string* signature) {
Elliott Hughes1fe7afb2012-02-13 17:23:03 -08001069 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001070 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes1fe7afb2012-02-13 17:23:03 -08001071 if (c == NULL) {
1072 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001073 }
Ian Rogersdfb325e2013-10-30 01:00:44 -07001074 *signature = ClassHelper(c).GetDescriptor();
Elliott Hughes1fe7afb2012-02-13 17:23:03 -08001075 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001076}
1077
Elliott Hughes88d63092013-01-09 09:55:54 -08001078JDWP::JdwpError Dbg::GetSourceFile(JDWP::RefTypeId class_id, std::string& result) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001079 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001080 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001081 if (c == NULL) {
1082 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001083 }
Sebastien Hertzb7054ba2014-03-13 11:52:31 +01001084 if (c->IsProxyClass()) {
1085 return JDWP::ERR_ABSENT_INFORMATION;
1086 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001087 result = ClassHelper(c).GetSourceFile();
1088 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001089}
1090
Elliott Hughes88d63092013-01-09 09:55:54 -08001091JDWP::JdwpError Dbg::GetObjectTag(JDWP::ObjectId object_id, uint8_t& tag) {
Ian Rogers98379392014-02-24 16:53:16 -08001092 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001093 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001094 if (o == ObjectRegistry::kInvalidObject) {
Elliott Hughes546b9862012-06-20 16:06:13 -07001095 return JDWP::ERR_INVALID_OBJECT;
1096 }
Ian Rogers98379392014-02-24 16:53:16 -08001097 tag = TagFromObject(soa, o);
Elliott Hughes546b9862012-06-20 16:06:13 -07001098 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001099}
1100
Elliott Hughesaed4be92011-12-02 16:16:23 -08001101size_t Dbg::GetTagWidth(JDWP::JdwpTag tag) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001102 switch (tag) {
1103 case JDWP::JT_VOID:
1104 return 0;
1105 case JDWP::JT_BYTE:
1106 case JDWP::JT_BOOLEAN:
1107 return 1;
1108 case JDWP::JT_CHAR:
1109 case JDWP::JT_SHORT:
1110 return 2;
1111 case JDWP::JT_FLOAT:
1112 case JDWP::JT_INT:
1113 return 4;
1114 case JDWP::JT_ARRAY:
1115 case JDWP::JT_OBJECT:
1116 case JDWP::JT_STRING:
1117 case JDWP::JT_THREAD:
1118 case JDWP::JT_THREAD_GROUP:
1119 case JDWP::JT_CLASS_LOADER:
1120 case JDWP::JT_CLASS_OBJECT:
1121 return sizeof(JDWP::ObjectId);
1122 case JDWP::JT_DOUBLE:
1123 case JDWP::JT_LONG:
1124 return 8;
1125 default:
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001126 LOG(FATAL) << "Unknown tag " << tag;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001127 return -1;
1128 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001129}
1130
Elliott Hughes88d63092013-01-09 09:55:54 -08001131JDWP::JdwpError Dbg::GetArrayLength(JDWP::ObjectId array_id, int& length) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001132 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001133 mirror::Array* a = DecodeArray(array_id, status);
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001134 if (a == NULL) {
1135 return status;
Elliott Hughes24437992011-11-30 14:49:33 -08001136 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001137 length = a->GetLength();
1138 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001139}
1140
Elliott Hughes88d63092013-01-09 09:55:54 -08001141JDWP::JdwpError Dbg::OutputArray(JDWP::ObjectId array_id, int offset, int count, JDWP::ExpandBuf* pReply) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001142 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001143 mirror::Array* a = DecodeArray(array_id, status);
Ian Rogers98379392014-02-24 16:53:16 -08001144 if (a == nullptr) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001145 return status;
1146 }
Elliott Hughes24437992011-11-30 14:49:33 -08001147
1148 if (offset < 0 || count < 0 || offset > a->GetLength() || a->GetLength() - offset < count) {
1149 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001150 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughes24437992011-11-30 14:49:33 -08001151 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001152 std::string descriptor(ClassHelper(a->GetClass()).GetDescriptor());
Elliott Hughes24437992011-11-30 14:49:33 -08001153 JDWP::JdwpTag tag = BasicTagFromDescriptor(descriptor.c_str() + 1);
1154
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001155 expandBufAdd1(pReply, tag);
1156 expandBufAdd4BE(pReply, count);
1157
Elliott Hughes24437992011-11-30 14:49:33 -08001158 if (IsPrimitiveTag(tag)) {
1159 size_t width = GetTagWidth(tag);
Elliott Hughes24437992011-11-30 14:49:33 -08001160 uint8_t* dst = expandBufAddSpace(pReply, count * width);
1161 if (width == 8) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001162 const uint64_t* src8 = reinterpret_cast<uint64_t*>(a->GetRawData(sizeof(uint64_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001163 for (int i = 0; i < count; ++i) JDWP::Write8BE(&dst, src8[offset + i]);
1164 } else if (width == 4) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001165 const uint32_t* src4 = reinterpret_cast<uint32_t*>(a->GetRawData(sizeof(uint32_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001166 for (int i = 0; i < count; ++i) JDWP::Write4BE(&dst, src4[offset + i]);
1167 } else if (width == 2) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001168 const uint16_t* src2 = reinterpret_cast<uint16_t*>(a->GetRawData(sizeof(uint16_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001169 for (int i = 0; i < count; ++i) JDWP::Write2BE(&dst, src2[offset + i]);
1170 } else {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001171 const uint8_t* src = reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint8_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001172 memcpy(dst, &src[offset * width], count * width);
1173 }
1174 } else {
Ian Rogers98379392014-02-24 16:53:16 -08001175 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001176 mirror::ObjectArray<mirror::Object>* oa = a->AsObjectArray<mirror::Object>();
Elliott Hughes24437992011-11-30 14:49:33 -08001177 for (int i = 0; i < count; ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001178 mirror::Object* element = oa->Get(offset + i);
Ian Rogers98379392014-02-24 16:53:16 -08001179 JDWP::JdwpTag specific_tag = (element != nullptr) ? TagFromObject(soa, element)
1180 : tag;
Elliott Hughes24437992011-11-30 14:49:33 -08001181 expandBufAdd1(pReply, specific_tag);
1182 expandBufAddObjectId(pReply, gRegistry->Add(element));
1183 }
1184 }
1185
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001186 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001187}
1188
Ian Rogersef7d42f2014-01-06 12:55:46 -08001189template <typename T>
1190static void CopyArrayData(mirror::Array* a, JDWP::Request& src, int offset, int count)
1191 NO_THREAD_SAFETY_ANALYSIS {
1192 // TODO: fix when annotalysis correctly handles non-member functions.
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001193 DCHECK(a->GetClass()->IsPrimitiveArray());
1194
Ian Rogersef7d42f2014-01-06 12:55:46 -08001195 T* dst = reinterpret_cast<T*>(a->GetRawData(sizeof(T), offset));
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001196 for (int i = 0; i < count; ++i) {
1197 *dst++ = src.ReadValue(sizeof(T));
1198 }
1199}
1200
Elliott Hughes88d63092013-01-09 09:55:54 -08001201JDWP::JdwpError Dbg::SetArrayElements(JDWP::ObjectId array_id, int offset, int count,
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001202 JDWP::Request& request)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001203 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001204 JDWP::JdwpError status;
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001205 mirror::Array* dst = DecodeArray(array_id, status);
1206 if (dst == NULL) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001207 return status;
1208 }
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001209
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001210 if (offset < 0 || count < 0 || offset > dst->GetLength() || dst->GetLength() - offset < count) {
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001211 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001212 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001213 }
Ian Rogersfc0e94b2013-09-23 23:51:32 -07001214 const char* descriptor = ClassHelper(dst->GetClass()).GetDescriptor();
1215 JDWP::JdwpTag tag = BasicTagFromDescriptor(descriptor + 1);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001216
1217 if (IsPrimitiveTag(tag)) {
1218 size_t width = GetTagWidth(tag);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001219 if (width == 8) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001220 CopyArrayData<uint64_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001221 } else if (width == 4) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001222 CopyArrayData<uint32_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001223 } else if (width == 2) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001224 CopyArrayData<uint16_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001225 } else {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001226 CopyArrayData<uint8_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001227 }
1228 } else {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001229 mirror::ObjectArray<mirror::Object>* oa = dst->AsObjectArray<mirror::Object>();
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001230 for (int i = 0; i < count; ++i) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001231 JDWP::ObjectId id = request.ReadObjectId();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001232 mirror::Object* o = gRegistry->Get<mirror::Object*>(id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001233 if (o == ObjectRegistry::kInvalidObject) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001234 return JDWP::ERR_INVALID_OBJECT;
1235 }
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001236 oa->Set<false>(offset + i, o);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001237 }
1238 }
1239
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001240 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001241}
1242
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001243JDWP::ObjectId Dbg::CreateString(const std::string& str) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001244 return gRegistry->Add(mirror::String::AllocFromModifiedUtf8(Thread::Current(), str.c_str()));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001245}
1246
Elliott Hughes88d63092013-01-09 09:55:54 -08001247JDWP::JdwpError Dbg::CreateObject(JDWP::RefTypeId class_id, JDWP::ObjectId& new_object) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001248 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001249 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001250 if (c == NULL) {
1251 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001252 }
Ian Rogers50b35e22012-10-04 10:09:15 -07001253 new_object = gRegistry->Add(c->AllocObject(Thread::Current()));
Elliott Hughes436e3722012-02-17 20:01:47 -08001254 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001255}
1256
Elliott Hughesbf13d362011-12-08 15:51:37 -08001257/*
1258 * Used by Eclipse's "Display" view to evaluate "new byte[5]" to get "(byte[]) [0, 0, 0, 0, 0]".
1259 */
Elliott Hughes88d63092013-01-09 09:55:54 -08001260JDWP::JdwpError Dbg::CreateArrayObject(JDWP::RefTypeId array_class_id, uint32_t length,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001261 JDWP::ObjectId& new_array) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001262 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001263 mirror::Class* c = DecodeClass(array_class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001264 if (c == NULL) {
1265 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001266 }
Ian Rogers6fac4472014-02-25 17:01:10 -08001267 new_array = gRegistry->Add(mirror::Array::Alloc<true>(Thread::Current(), c, length,
1268 c->GetComponentSize(),
1269 Runtime::Current()->GetHeap()->GetCurrentAllocator()));
Elliott Hughes436e3722012-02-17 20:01:47 -08001270 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001271}
1272
Elliott Hughes88d63092013-01-09 09:55:54 -08001273bool Dbg::MatchType(JDWP::RefTypeId instance_class_id, JDWP::RefTypeId class_id) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001274 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001275 mirror::Class* c1 = DecodeClass(instance_class_id, status);
Elliott Hughesa656a0f2012-02-21 18:03:44 -08001276 CHECK(c1 != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001277 mirror::Class* c2 = DecodeClass(class_id, status);
Elliott Hughesa656a0f2012-02-21 18:03:44 -08001278 CHECK(c2 != NULL);
Sebastien Hertz123756a2013-11-27 15:49:42 +01001279 return c2->IsAssignableFrom(c1);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001280}
1281
Brian Carlstromea46f952013-07-30 01:26:50 -07001282static JDWP::FieldId ToFieldId(const mirror::ArtField* f)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001283 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001284 CHECK(!kMovingFields);
Elliott Hughes03181a82011-11-17 17:22:21 -08001285 return static_cast<JDWP::FieldId>(reinterpret_cast<uintptr_t>(f));
Elliott Hughes03181a82011-11-17 17:22:21 -08001286}
1287
Brian Carlstromea46f952013-07-30 01:26:50 -07001288static JDWP::MethodId ToMethodId(const mirror::ArtMethod* m)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001289 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001290 CHECK(!kMovingMethods);
Elliott Hughes03181a82011-11-17 17:22:21 -08001291 return static_cast<JDWP::MethodId>(reinterpret_cast<uintptr_t>(m));
Elliott Hughes03181a82011-11-17 17:22:21 -08001292}
1293
Brian Carlstromea46f952013-07-30 01:26:50 -07001294static mirror::ArtField* FromFieldId(JDWP::FieldId fid)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001295 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001296 CHECK(!kMovingFields);
Brian Carlstromea46f952013-07-30 01:26:50 -07001297 return reinterpret_cast<mirror::ArtField*>(static_cast<uintptr_t>(fid));
Elliott Hughesaed4be92011-12-02 16:16:23 -08001298}
1299
Brian Carlstromea46f952013-07-30 01:26:50 -07001300static mirror::ArtMethod* FromMethodId(JDWP::MethodId mid)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001301 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001302 CHECK(!kMovingMethods);
Brian Carlstromea46f952013-07-30 01:26:50 -07001303 return reinterpret_cast<mirror::ArtMethod*>(static_cast<uintptr_t>(mid));
Elliott Hughes03181a82011-11-17 17:22:21 -08001304}
1305
Brian Carlstromea46f952013-07-30 01:26:50 -07001306static void SetLocation(JDWP::JdwpLocation& location, mirror::ArtMethod* m, uint32_t dex_pc)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001307 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001308 if (m == NULL) {
1309 memset(&location, 0, sizeof(location));
1310 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001311 mirror::Class* c = m->GetDeclaringClass();
Elliott Hughes74847412012-06-20 18:10:21 -07001312 location.type_tag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001313 location.class_id = gRegistry->AddRefType(c);
Elliott Hughes74847412012-06-20 18:10:21 -07001314 location.method_id = ToMethodId(m);
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001315 location.dex_pc = (m->IsNative() || m->IsProxyMethod()) ? static_cast<uint64_t>(-1) : dex_pc;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001316 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08001317}
1318
Elliott Hughesa96836a2013-01-17 12:27:49 -08001319std::string Dbg::GetMethodName(JDWP::MethodId method_id)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001320 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001321 mirror::ArtMethod* m = FromMethodId(method_id);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001322 return MethodHelper(m).GetName();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001323}
1324
Elliott Hughesa96836a2013-01-17 12:27:49 -08001325std::string Dbg::GetFieldName(JDWP::FieldId field_id)
1326 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001327 mirror::ArtField* f = FromFieldId(field_id);
Elliott Hughesa96836a2013-01-17 12:27:49 -08001328 return FieldHelper(f).GetName();
1329}
1330
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001331/*
1332 * Augment the access flags for synthetic methods and fields by setting
1333 * the (as described by the spec) "0xf0000000 bit". Also, strip out any
1334 * flags not specified by the Java programming language.
1335 */
1336static uint32_t MangleAccessFlags(uint32_t accessFlags) {
1337 accessFlags &= kAccJavaFlagsMask;
1338 if ((accessFlags & kAccSynthetic) != 0) {
1339 accessFlags |= 0xf0000000;
1340 }
1341 return accessFlags;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001342}
1343
Elliott Hughesdbb40792011-11-18 17:05:22 -08001344/*
Jeff Haob7cefc72013-11-14 14:51:09 -08001345 * Circularly shifts registers so that arguments come first. Debuggers
1346 * expect slots to begin with arguments, but dex code places them at
1347 * the end.
Elliott Hughesdbb40792011-11-18 17:05:22 -08001348 */
Jeff Haob7cefc72013-11-14 14:51:09 -08001349static uint16_t MangleSlot(uint16_t slot, mirror::ArtMethod* m)
1350 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1351 const DexFile::CodeItem* code_item = MethodHelper(m).GetCodeItem();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001352 if (code_item == nullptr) {
1353 // We should not get here for a method without code (native, proxy or abstract). Log it and
1354 // return the slot as is since all registers are arguments.
1355 LOG(WARNING) << "Trying to mangle slot for method without code " << PrettyMethod(m);
1356 return slot;
1357 }
Jeff Haob7cefc72013-11-14 14:51:09 -08001358 uint16_t ins_size = code_item->ins_size_;
1359 uint16_t locals_size = code_item->registers_size_ - ins_size;
1360 if (slot >= locals_size) {
1361 return slot - locals_size;
1362 } else {
1363 return slot + ins_size;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001364 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001365}
1366
Jeff Haob7cefc72013-11-14 14:51:09 -08001367/*
1368 * Circularly shifts registers so that arguments come last. Reverts
1369 * slots to dex style argument placement.
1370 */
Brian Carlstromea46f952013-07-30 01:26:50 -07001371static uint16_t DemangleSlot(uint16_t slot, mirror::ArtMethod* m)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001372 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Jeff Haob7cefc72013-11-14 14:51:09 -08001373 const DexFile::CodeItem* code_item = MethodHelper(m).GetCodeItem();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001374 if (code_item == nullptr) {
1375 // We should not get here for a method without code (native, proxy or abstract). Log it and
1376 // return the slot as is since all registers are arguments.
1377 LOG(WARNING) << "Trying to demangle slot for method without code " << PrettyMethod(m);
1378 return slot;
1379 }
Jeff Haob7cefc72013-11-14 14:51:09 -08001380 uint16_t ins_size = code_item->ins_size_;
1381 uint16_t locals_size = code_item->registers_size_ - ins_size;
1382 if (slot < ins_size) {
1383 return slot + locals_size;
1384 } else {
1385 return slot - ins_size;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001386 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001387}
1388
Elliott Hughes88d63092013-01-09 09:55:54 -08001389JDWP::JdwpError Dbg::OutputDeclaredFields(JDWP::RefTypeId class_id, bool with_generic, JDWP::ExpandBuf* pReply) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001390 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001391 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001392 if (c == NULL) {
1393 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001394 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001395
1396 size_t instance_field_count = c->NumInstanceFields();
1397 size_t static_field_count = c->NumStaticFields();
1398
1399 expandBufAdd4BE(pReply, instance_field_count + static_field_count);
1400
1401 for (size_t i = 0; i < instance_field_count + static_field_count; ++i) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001402 mirror::ArtField* f = (i < instance_field_count) ? c->GetInstanceField(i) : c->GetStaticField(i - instance_field_count);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001403 FieldHelper fh(f);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001404 expandBufAddFieldId(pReply, ToFieldId(f));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001405 expandBufAddUtf8String(pReply, fh.GetName());
1406 expandBufAddUtf8String(pReply, fh.GetTypeDescriptor());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001407 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001408 static const char genericSignature[1] = "";
1409 expandBufAddUtf8String(pReply, genericSignature);
1410 }
1411 expandBufAdd4BE(pReply, MangleAccessFlags(f->GetAccessFlags()));
1412 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001413 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001414}
1415
Elliott Hughes88d63092013-01-09 09:55:54 -08001416JDWP::JdwpError Dbg::OutputDeclaredMethods(JDWP::RefTypeId class_id, bool with_generic,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001417 JDWP::ExpandBuf* pReply) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001418 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001419 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001420 if (c == NULL) {
1421 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001422 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001423
1424 size_t direct_method_count = c->NumDirectMethods();
1425 size_t virtual_method_count = c->NumVirtualMethods();
1426
1427 expandBufAdd4BE(pReply, direct_method_count + virtual_method_count);
1428
1429 for (size_t i = 0; i < direct_method_count + virtual_method_count; ++i) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001430 mirror::ArtMethod* m = (i < direct_method_count) ? c->GetDirectMethod(i) : c->GetVirtualMethod(i - direct_method_count);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001431 MethodHelper mh(m);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001432 expandBufAddMethodId(pReply, ToMethodId(m));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001433 expandBufAddUtf8String(pReply, mh.GetName());
Ian Rogersd91d6d62013-09-25 20:26:14 -07001434 expandBufAddUtf8String(pReply, mh.GetSignature().ToString());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001435 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001436 static const char genericSignature[1] = "";
1437 expandBufAddUtf8String(pReply, genericSignature);
1438 }
1439 expandBufAdd4BE(pReply, MangleAccessFlags(m->GetAccessFlags()));
1440 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001441 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001442}
1443
Elliott Hughes88d63092013-01-09 09:55:54 -08001444JDWP::JdwpError Dbg::OutputDeclaredInterfaces(JDWP::RefTypeId class_id, JDWP::ExpandBuf* pReply) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001445 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001446 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001447 if (c == NULL) {
1448 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001449 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001450
1451 ClassHelper kh(c);
Ian Rogersd24e2642012-06-06 21:21:43 -07001452 size_t interface_count = kh.NumDirectInterfaces();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001453 expandBufAdd4BE(pReply, interface_count);
1454 for (size_t i = 0; i < interface_count; ++i) {
Elliott Hughes64f574f2013-02-20 14:57:12 -08001455 expandBufAddRefTypeId(pReply, gRegistry->AddRefType(kh.GetDirectInterface(i)));
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001456 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001457 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001458}
1459
Elliott Hughes88d63092013-01-09 09:55:54 -08001460void Dbg::OutputLineTable(JDWP::RefTypeId, JDWP::MethodId method_id, JDWP::ExpandBuf* pReply)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001461 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001462 struct DebugCallbackContext {
1463 int numItems;
1464 JDWP::ExpandBuf* pReply;
1465
Elliott Hughes2435a572012-02-17 16:07:41 -08001466 static bool Callback(void* context, uint32_t address, uint32_t line_number) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001467 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
1468 expandBufAdd8BE(pContext->pReply, address);
Elliott Hughes2435a572012-02-17 16:07:41 -08001469 expandBufAdd4BE(pContext->pReply, line_number);
Elliott Hughes03181a82011-11-17 17:22:21 -08001470 pContext->numItems++;
Sebastien Hertzf2910ee2013-10-19 16:39:24 +02001471 return false;
Elliott Hughes03181a82011-11-17 17:22:21 -08001472 }
1473 };
Brian Carlstromea46f952013-07-30 01:26:50 -07001474 mirror::ArtMethod* m = FromMethodId(method_id);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001475 MethodHelper mh(m);
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001476 const DexFile::CodeItem* code_item = mh.GetCodeItem();
Elliott Hughes03181a82011-11-17 17:22:21 -08001477 uint64_t start, end;
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001478 if (code_item == nullptr) {
1479 DCHECK(m->IsNative() || m->IsProxyMethod());
Elliott Hughes03181a82011-11-17 17:22:21 -08001480 start = -1;
1481 end = -1;
1482 } else {
1483 start = 0;
jeffhao14f0db92012-12-14 17:50:42 -08001484 // Return the index of the last instruction
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001485 end = code_item->insns_size_in_code_units_ - 1;
Elliott Hughes03181a82011-11-17 17:22:21 -08001486 }
1487
1488 expandBufAdd8BE(pReply, start);
1489 expandBufAdd8BE(pReply, end);
1490
1491 // Add numLines later
1492 size_t numLinesOffset = expandBufGetLength(pReply);
1493 expandBufAdd4BE(pReply, 0);
1494
1495 DebugCallbackContext context;
1496 context.numItems = 0;
1497 context.pReply = pReply;
1498
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001499 if (code_item != nullptr) {
1500 mh.GetDexFile().DecodeDebugInfo(code_item, m->IsStatic(), m->GetDexMethodIndex(),
1501 DebugCallbackContext::Callback, NULL, &context);
1502 }
Elliott Hughes03181a82011-11-17 17:22:21 -08001503
1504 JDWP::Set4BE(expandBufGetBuffer(pReply) + numLinesOffset, context.numItems);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001505}
1506
Elliott Hughes88d63092013-01-09 09:55:54 -08001507void Dbg::OutputVariableTable(JDWP::RefTypeId, JDWP::MethodId method_id, bool with_generic, JDWP::ExpandBuf* pReply) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001508 struct DebugCallbackContext {
Jeff Haob7cefc72013-11-14 14:51:09 -08001509 mirror::ArtMethod* method;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001510 JDWP::ExpandBuf* pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001511 size_t variable_count;
1512 bool with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001513
Jeff Haob7cefc72013-11-14 14:51:09 -08001514 static void Callback(void* context, uint16_t slot, uint32_t startAddress, uint32_t endAddress, const char* name, const char* descriptor, const char* signature)
1515 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001516 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
1517
Jeff Haob7cefc72013-11-14 14:51:09 -08001518 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 -08001519
Jeff Haob7cefc72013-11-14 14:51:09 -08001520 slot = MangleSlot(slot, pContext->method);
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001521
Elliott Hughesdbb40792011-11-18 17:05:22 -08001522 expandBufAdd8BE(pContext->pReply, startAddress);
1523 expandBufAddUtf8String(pContext->pReply, name);
1524 expandBufAddUtf8String(pContext->pReply, descriptor);
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001525 if (pContext->with_generic) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001526 expandBufAddUtf8String(pContext->pReply, signature);
1527 }
1528 expandBufAdd4BE(pContext->pReply, endAddress - startAddress);
1529 expandBufAdd4BE(pContext->pReply, slot);
1530
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001531 ++pContext->variable_count;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001532 }
1533 };
Brian Carlstromea46f952013-07-30 01:26:50 -07001534 mirror::ArtMethod* m = FromMethodId(method_id);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001535 MethodHelper mh(m);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001536
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001537 // arg_count considers doubles and longs to take 2 units.
1538 // variable_count considers everything to take 1 unit.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001539 std::string shorty(mh.GetShorty());
Brian Carlstromea46f952013-07-30 01:26:50 -07001540 expandBufAdd4BE(pReply, mirror::ArtMethod::NumArgRegisters(shorty));
Elliott Hughesdbb40792011-11-18 17:05:22 -08001541
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001542 // We don't know the total number of variables yet, so leave a blank and update it later.
1543 size_t variable_count_offset = expandBufGetLength(pReply);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001544 expandBufAdd4BE(pReply, 0);
1545
1546 DebugCallbackContext context;
Jeff Haob7cefc72013-11-14 14:51:09 -08001547 context.method = m;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001548 context.pReply = pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001549 context.variable_count = 0;
1550 context.with_generic = with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001551
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001552 const DexFile::CodeItem* code_item = mh.GetCodeItem();
1553 if (code_item != nullptr) {
1554 mh.GetDexFile().DecodeDebugInfo(code_item, m->IsStatic(), m->GetDexMethodIndex(), NULL,
1555 DebugCallbackContext::Callback, &context);
1556 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001557
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001558 JDWP::Set4BE(expandBufGetBuffer(pReply) + variable_count_offset, context.variable_count);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001559}
1560
Jeff Hao579b0242013-11-18 13:16:49 -08001561void Dbg::OutputMethodReturnValue(JDWP::MethodId method_id, const JValue* return_value,
1562 JDWP::ExpandBuf* pReply) {
1563 mirror::ArtMethod* m = FromMethodId(method_id);
1564 JDWP::JdwpTag tag = BasicTagFromDescriptor(MethodHelper(m).GetShorty());
1565 OutputJValue(tag, return_value, pReply);
1566}
1567
Elliott Hughes9777ba22013-01-17 09:04:19 -08001568JDWP::JdwpError Dbg::GetBytecodes(JDWP::RefTypeId, JDWP::MethodId method_id,
1569 std::vector<uint8_t>& bytecodes)
1570 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001571 mirror::ArtMethod* m = FromMethodId(method_id);
Elliott Hughes9777ba22013-01-17 09:04:19 -08001572 if (m == NULL) {
1573 return JDWP::ERR_INVALID_METHODID;
1574 }
1575 MethodHelper mh(m);
1576 const DexFile::CodeItem* code_item = mh.GetCodeItem();
1577 size_t byte_count = code_item->insns_size_in_code_units_ * 2;
1578 const uint8_t* begin = reinterpret_cast<const uint8_t*>(code_item->insns_);
1579 const uint8_t* end = begin + byte_count;
1580 for (const uint8_t* p = begin; p != end; ++p) {
1581 bytecodes.push_back(*p);
1582 }
1583 return JDWP::ERR_NONE;
1584}
1585
Elliott Hughes88d63092013-01-09 09:55:54 -08001586JDWP::JdwpTag Dbg::GetFieldBasicTag(JDWP::FieldId field_id) {
1587 return BasicTagFromDescriptor(FieldHelper(FromFieldId(field_id)).GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001588}
1589
Elliott Hughes88d63092013-01-09 09:55:54 -08001590JDWP::JdwpTag Dbg::GetStaticFieldBasicTag(JDWP::FieldId field_id) {
1591 return BasicTagFromDescriptor(FieldHelper(FromFieldId(field_id)).GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001592}
1593
Elliott Hughes88d63092013-01-09 09:55:54 -08001594static JDWP::JdwpError GetFieldValueImpl(JDWP::RefTypeId ref_type_id, JDWP::ObjectId object_id,
1595 JDWP::FieldId field_id, JDWP::ExpandBuf* pReply,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001596 bool is_static)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001597 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes0cf74332012-02-23 23:14:00 -08001598 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001599 mirror::Class* c = DecodeClass(ref_type_id, status);
Elliott Hughes88d63092013-01-09 09:55:54 -08001600 if (ref_type_id != 0 && c == NULL) {
Elliott Hughes0cf74332012-02-23 23:14:00 -08001601 return status;
1602 }
1603
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001604 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001605 if ((!is_static && o == NULL) || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001606 return JDWP::ERR_INVALID_OBJECT;
1607 }
Brian Carlstromea46f952013-07-30 01:26:50 -07001608 mirror::ArtField* f = FromFieldId(field_id);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001609
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001610 mirror::Class* receiver_class = c;
Elliott Hughes0cf74332012-02-23 23:14:00 -08001611 if (receiver_class == NULL && o != NULL) {
1612 receiver_class = o->GetClass();
1613 }
1614 // TODO: should we give up now if receiver_class is NULL?
1615 if (receiver_class != NULL && !f->GetDeclaringClass()->IsAssignableFrom(receiver_class)) {
1616 LOG(INFO) << "ERR_INVALID_FIELDID: " << PrettyField(f) << " " << PrettyClass(receiver_class);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001617 return JDWP::ERR_INVALID_FIELDID;
1618 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001619
Elliott Hughes0cf74332012-02-23 23:14:00 -08001620 // The RI only enforces the static/non-static mismatch in one direction.
1621 // TODO: should we change the tests and check both?
1622 if (is_static) {
1623 if (!f->IsStatic()) {
1624 return JDWP::ERR_INVALID_FIELDID;
1625 }
1626 } else {
1627 if (f->IsStatic()) {
1628 LOG(WARNING) << "Ignoring non-NULL receiver for ObjectReference.SetValues on static field " << PrettyField(f);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001629 }
1630 }
jeffhao0dfbb7e2012-11-28 15:26:03 -08001631 if (f->IsStatic()) {
1632 o = f->GetDeclaringClass();
1633 }
Elliott Hughes0cf74332012-02-23 23:14:00 -08001634
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001635 JDWP::JdwpTag tag = BasicTagFromDescriptor(FieldHelper(f).GetTypeDescriptor());
Jeff Hao579b0242013-11-18 13:16:49 -08001636 JValue field_value;
1637 if (tag == JDWP::JT_VOID) {
1638 LOG(FATAL) << "Unknown tag: " << tag;
1639 } else if (!IsPrimitiveTag(tag)) {
1640 field_value.SetL(f->GetObject(o));
1641 } else if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
1642 field_value.SetJ(f->Get64(o));
Elliott Hughesaed4be92011-12-02 16:16:23 -08001643 } else {
Jeff Hao579b0242013-11-18 13:16:49 -08001644 field_value.SetI(f->Get32(o));
Elliott Hughesaed4be92011-12-02 16:16:23 -08001645 }
Jeff Hao579b0242013-11-18 13:16:49 -08001646 Dbg::OutputJValue(tag, &field_value, pReply);
1647
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001648 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001649}
1650
Elliott Hughes88d63092013-01-09 09:55:54 -08001651JDWP::JdwpError Dbg::GetFieldValue(JDWP::ObjectId object_id, JDWP::FieldId field_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001652 JDWP::ExpandBuf* pReply) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001653 return GetFieldValueImpl(0, object_id, field_id, pReply, false);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001654}
1655
Elliott Hughes88d63092013-01-09 09:55:54 -08001656JDWP::JdwpError Dbg::GetStaticFieldValue(JDWP::RefTypeId ref_type_id, JDWP::FieldId field_id, JDWP::ExpandBuf* pReply) {
1657 return GetFieldValueImpl(ref_type_id, 0, field_id, pReply, true);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001658}
1659
Elliott Hughes88d63092013-01-09 09:55:54 -08001660static JDWP::JdwpError SetFieldValueImpl(JDWP::ObjectId object_id, JDWP::FieldId field_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001661 uint64_t value, int width, bool is_static)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001662 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001663 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001664 if ((!is_static && o == NULL) || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001665 return JDWP::ERR_INVALID_OBJECT;
1666 }
Brian Carlstromea46f952013-07-30 01:26:50 -07001667 mirror::ArtField* f = FromFieldId(field_id);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001668
1669 // The RI only enforces the static/non-static mismatch in one direction.
1670 // TODO: should we change the tests and check both?
1671 if (is_static) {
1672 if (!f->IsStatic()) {
1673 return JDWP::ERR_INVALID_FIELDID;
1674 }
1675 } else {
1676 if (f->IsStatic()) {
1677 LOG(WARNING) << "Ignoring non-NULL receiver for ObjectReference.SetValues on static field " << PrettyField(f);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001678 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001679 }
jeffhao0dfbb7e2012-11-28 15:26:03 -08001680 if (f->IsStatic()) {
1681 o = f->GetDeclaringClass();
1682 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001683
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001684 JDWP::JdwpTag tag = BasicTagFromDescriptor(FieldHelper(f).GetTypeDescriptor());
Elliott Hughesaed4be92011-12-02 16:16:23 -08001685
1686 if (IsPrimitiveTag(tag)) {
1687 if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001688 CHECK_EQ(width, 8);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001689 // Debugging can't use transactional mode (runtime only).
1690 f->Set64<false>(o, value);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001691 } else {
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001692 CHECK_LE(width, 4);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001693 // Debugging can't use transactional mode (runtime only).
1694 f->Set32<false>(o, value);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001695 }
1696 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001697 mirror::Object* v = gRegistry->Get<mirror::Object*>(value);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001698 if (v == ObjectRegistry::kInvalidObject) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001699 return JDWP::ERR_INVALID_OBJECT;
1700 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001701 if (v != NULL) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001702 mirror::Class* field_type = FieldHelper(f).GetType();
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001703 if (!field_type->IsAssignableFrom(v->GetClass())) {
1704 return JDWP::ERR_INVALID_OBJECT;
1705 }
1706 }
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001707 // Debugging can't use transactional mode (runtime only).
1708 f->SetObject<false>(o, v);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001709 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001710
1711 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001712}
1713
Elliott Hughes88d63092013-01-09 09:55:54 -08001714JDWP::JdwpError Dbg::SetFieldValue(JDWP::ObjectId object_id, JDWP::FieldId field_id, uint64_t value,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001715 int width) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001716 return SetFieldValueImpl(object_id, field_id, value, width, false);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001717}
1718
Elliott Hughes88d63092013-01-09 09:55:54 -08001719JDWP::JdwpError Dbg::SetStaticFieldValue(JDWP::FieldId field_id, uint64_t value, int width) {
1720 return SetFieldValueImpl(0, field_id, value, width, true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001721}
1722
Elliott Hughes88d63092013-01-09 09:55:54 -08001723std::string Dbg::StringToUtf8(JDWP::ObjectId string_id) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001724 mirror::String* s = gRegistry->Get<mirror::String*>(string_id);
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001725 return s->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001726}
1727
Jeff Hao579b0242013-11-18 13:16:49 -08001728void Dbg::OutputJValue(JDWP::JdwpTag tag, const JValue* return_value, JDWP::ExpandBuf* pReply) {
1729 if (IsPrimitiveTag(tag)) {
1730 expandBufAdd1(pReply, tag);
1731 if (tag == JDWP::JT_BOOLEAN || tag == JDWP::JT_BYTE) {
1732 expandBufAdd1(pReply, return_value->GetI());
1733 } else if (tag == JDWP::JT_CHAR || tag == JDWP::JT_SHORT) {
1734 expandBufAdd2BE(pReply, return_value->GetI());
1735 } else if (tag == JDWP::JT_FLOAT || tag == JDWP::JT_INT) {
1736 expandBufAdd4BE(pReply, return_value->GetI());
1737 } else if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
1738 expandBufAdd8BE(pReply, return_value->GetJ());
1739 } else {
1740 CHECK_EQ(tag, JDWP::JT_VOID);
1741 }
1742 } else {
Ian Rogers98379392014-02-24 16:53:16 -08001743 ScopedObjectAccessUnchecked soa(Thread::Current());
Jeff Hao579b0242013-11-18 13:16:49 -08001744 mirror::Object* value = return_value->GetL();
Ian Rogers98379392014-02-24 16:53:16 -08001745 expandBufAdd1(pReply, TagFromObject(soa, value));
Jeff Hao579b0242013-11-18 13:16:49 -08001746 expandBufAddObjectId(pReply, gRegistry->Add(value));
1747 }
1748}
1749
Elliott Hughes221229c2013-01-08 18:17:50 -08001750JDWP::JdwpError Dbg::GetThreadName(JDWP::ObjectId thread_id, std::string& name) {
jeffhaoa77f0f62012-12-05 17:19:31 -08001751 ScopedObjectAccessUnchecked soa(Thread::Current());
1752 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001753 Thread* thread;
1754 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1755 if (error != JDWP::ERR_NONE && error != JDWP::ERR_THREAD_NOT_ALIVE) {
1756 return error;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001757 }
Elliott Hughes221229c2013-01-08 18:17:50 -08001758
1759 // We still need to report the zombie threads' names, so we can't just call Thread::GetThreadName.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001760 mirror::Object* thread_object = gRegistry->Get<mirror::Object*>(thread_id);
Brian Carlstromea46f952013-07-30 01:26:50 -07001761 mirror::ArtField* java_lang_Thread_name_field =
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001762 soa.DecodeField(WellKnownClasses::java_lang_Thread_name);
1763 mirror::String* s =
1764 reinterpret_cast<mirror::String*>(java_lang_Thread_name_field->GetObject(thread_object));
Elliott Hughes221229c2013-01-08 18:17:50 -08001765 if (s != NULL) {
1766 name = s->ToModifiedUtf8();
1767 }
1768 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001769}
1770
Elliott Hughes221229c2013-01-08 18:17:50 -08001771JDWP::JdwpError Dbg::GetThreadGroup(JDWP::ObjectId thread_id, JDWP::ExpandBuf* pReply) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001772 ScopedObjectAccess soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001773 mirror::Object* thread_object = gRegistry->Get<mirror::Object*>(thread_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001774 if (thread_object == ObjectRegistry::kInvalidObject) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001775 return JDWP::ERR_INVALID_OBJECT;
1776 }
Ian Rogers98379392014-02-24 16:53:16 -08001777 const char* old_cause = soa.Self()->StartAssertNoThreadSuspension("Debugger: GetThreadGroup");
Elliott Hughes2435a572012-02-17 16:07:41 -08001778 // Okay, so it's an object, but is it actually a thread?
Ian Rogers50b35e22012-10-04 10:09:15 -07001779 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001780 Thread* thread;
1781 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1782 if (error == JDWP::ERR_THREAD_NOT_ALIVE) {
1783 // Zombie threads are in the null group.
1784 expandBufAddObjectId(pReply, JDWP::ObjectId(0));
Sebastien Hertz52d131d2014-03-13 16:17:40 +01001785 error = JDWP::ERR_NONE;
1786 } else if (error == JDWP::ERR_NONE) {
1787 mirror::Class* c = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_Thread);
1788 CHECK(c != nullptr);
1789 mirror::ArtField* f = c->FindInstanceField("group", "Ljava/lang/ThreadGroup;");
1790 CHECK(f != NULL);
1791 mirror::Object* group = f->GetObject(thread_object);
1792 CHECK(group != NULL);
1793 JDWP::ObjectId thread_group_id = gRegistry->Add(group);
1794 expandBufAddObjectId(pReply, thread_group_id);
Elliott Hughes221229c2013-01-08 18:17:50 -08001795 }
Ian Rogers98379392014-02-24 16:53:16 -08001796 soa.Self()->EndAssertNoThreadSuspension(old_cause);
Sebastien Hertz52d131d2014-03-13 16:17:40 +01001797 return error;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001798}
1799
Elliott Hughes88d63092013-01-09 09:55:54 -08001800std::string Dbg::GetThreadGroupName(JDWP::ObjectId thread_group_id) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001801 ScopedObjectAccess soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001802 mirror::Object* thread_group = gRegistry->Get<mirror::Object*>(thread_group_id);
Ian Rogers98379392014-02-24 16:53:16 -08001803 CHECK(thread_group != nullptr);
1804 const char* old_cause = soa.Self()->StartAssertNoThreadSuspension("Debugger: GetThreadGroupName");
1805 mirror::Class* c = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_ThreadGroup);
1806 CHECK(c != nullptr);
Brian Carlstromea46f952013-07-30 01:26:50 -07001807 mirror::ArtField* f = c->FindInstanceField("name", "Ljava/lang/String;");
Elliott Hughes499c5132011-11-17 14:55:11 -08001808 CHECK(f != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001809 mirror::String* s = reinterpret_cast<mirror::String*>(f->GetObject(thread_group));
Ian Rogers98379392014-02-24 16:53:16 -08001810 soa.Self()->EndAssertNoThreadSuspension(old_cause);
Elliott Hughes499c5132011-11-17 14:55:11 -08001811 return s->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001812}
1813
Elliott Hughes88d63092013-01-09 09:55:54 -08001814JDWP::ObjectId Dbg::GetThreadGroupParent(JDWP::ObjectId thread_group_id) {
Ian Rogers98379392014-02-24 16:53:16 -08001815 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001816 mirror::Object* thread_group = gRegistry->Get<mirror::Object*>(thread_group_id);
Ian Rogers98379392014-02-24 16:53:16 -08001817 CHECK(thread_group != nullptr);
1818 const char* old_cause = soa.Self()->StartAssertNoThreadSuspension("Debugger: GetThreadGroupParent");
1819 mirror::Class* c = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_ThreadGroup);
1820 CHECK(c != nullptr);
Brian Carlstromea46f952013-07-30 01:26:50 -07001821 mirror::ArtField* f = c->FindInstanceField("parent", "Ljava/lang/ThreadGroup;");
Elliott Hughes4e235312011-12-02 11:34:15 -08001822 CHECK(f != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001823 mirror::Object* parent = f->GetObject(thread_group);
Ian Rogers98379392014-02-24 16:53:16 -08001824 soa.Self()->EndAssertNoThreadSuspension(old_cause);
Elliott Hughes4e235312011-12-02 11:34:15 -08001825 return gRegistry->Add(parent);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001826}
1827
1828JDWP::ObjectId Dbg::GetSystemThreadGroupId() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001829 ScopedObjectAccessUnchecked soa(Thread::Current());
Brian Carlstromea46f952013-07-30 01:26:50 -07001830 mirror::ArtField* f = soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_systemThreadGroup);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001831 mirror::Object* group = f->GetObject(f->GetDeclaringClass());
Ian Rogers365c1022012-06-22 15:05:28 -07001832 return gRegistry->Add(group);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001833}
1834
1835JDWP::ObjectId Dbg::GetMainThreadGroupId() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001836 ScopedObjectAccess soa(Thread::Current());
Brian Carlstromea46f952013-07-30 01:26:50 -07001837 mirror::ArtField* f = soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_mainThreadGroup);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001838 mirror::Object* group = f->GetObject(f->GetDeclaringClass());
Ian Rogers365c1022012-06-22 15:05:28 -07001839 return gRegistry->Add(group);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001840}
1841
Jeff Hao920af3e2013-08-28 15:46:38 -07001842JDWP::JdwpThreadStatus Dbg::ToJdwpThreadStatus(ThreadState state) {
1843 switch (state) {
1844 case kBlocked:
1845 return JDWP::TS_MONITOR;
1846 case kNative:
1847 case kRunnable:
1848 case kSuspended:
1849 return JDWP::TS_RUNNING;
1850 case kSleeping:
1851 return JDWP::TS_SLEEPING;
1852 case kStarting:
1853 case kTerminated:
1854 return JDWP::TS_ZOMBIE;
1855 case kTimedWaiting:
1856 case kWaitingForDebuggerSend:
1857 case kWaitingForDebuggerSuspension:
1858 case kWaitingForDebuggerToAttach:
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01001859 case kWaitingForDeoptimization:
Jeff Hao920af3e2013-08-28 15:46:38 -07001860 case kWaitingForGcToComplete:
1861 case kWaitingForCheckPointsToRun:
1862 case kWaitingForJniOnLoad:
1863 case kWaitingForSignalCatcherOutput:
1864 case kWaitingInMainDebuggerLoop:
1865 case kWaitingInMainSignalCatcherLoop:
1866 case kWaitingPerformingGc:
1867 case kWaiting:
1868 return JDWP::TS_WAIT;
1869 // Don't add a 'default' here so the compiler can spot incompatible enum changes.
1870 }
1871 LOG(FATAL) << "Unknown thread state: " << state;
1872 return JDWP::TS_ZOMBIE;
1873}
1874
Sebastien Hertz52d131d2014-03-13 16:17:40 +01001875JDWP::JdwpError Dbg::GetThreadStatus(JDWP::ObjectId thread_id, JDWP::JdwpThreadStatus* pThreadStatus,
1876 JDWP::JdwpSuspendStatus* pSuspendStatus) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001877 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes499c5132011-11-17 14:55:11 -08001878
Elliott Hughes9e0c1752013-01-09 14:02:58 -08001879 *pSuspendStatus = JDWP::SUSPEND_STATUS_NOT_SUSPENDED;
1880
Ian Rogers50b35e22012-10-04 10:09:15 -07001881 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001882 Thread* thread;
1883 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1884 if (error != JDWP::ERR_NONE) {
1885 if (error == JDWP::ERR_THREAD_NOT_ALIVE) {
1886 *pThreadStatus = JDWP::TS_ZOMBIE;
Elliott Hughes221229c2013-01-08 18:17:50 -08001887 return JDWP::ERR_NONE;
1888 }
1889 return error;
Elliott Hughes499c5132011-11-17 14:55:11 -08001890 }
1891
Elliott Hughes9e0c1752013-01-09 14:02:58 -08001892 if (IsSuspendedForDebugger(soa, thread)) {
1893 *pSuspendStatus = JDWP::SUSPEND_STATUS_SUSPENDED;
Elliott Hughes499c5132011-11-17 14:55:11 -08001894 }
1895
Jeff Hao920af3e2013-08-28 15:46:38 -07001896 *pThreadStatus = ToJdwpThreadStatus(thread->GetState());
Elliott Hughes221229c2013-01-08 18:17:50 -08001897 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001898}
1899
Elliott Hughes221229c2013-01-08 18:17:50 -08001900JDWP::JdwpError Dbg::GetThreadDebugSuspendCount(JDWP::ObjectId thread_id, JDWP::ExpandBuf* pReply) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001901 ScopedObjectAccess soa(Thread::Current());
Ian Rogers50b35e22012-10-04 10:09:15 -07001902 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001903 Thread* thread;
1904 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1905 if (error != JDWP::ERR_NONE) {
1906 return error;
Elliott Hughes2435a572012-02-17 16:07:41 -08001907 }
Ian Rogers50b35e22012-10-04 10:09:15 -07001908 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001909 expandBufAdd4BE(pReply, thread->GetDebugSuspendCount());
Elliott Hughes2435a572012-02-17 16:07:41 -08001910 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001911}
1912
Elliott Hughesf9501702013-01-11 11:22:27 -08001913JDWP::JdwpError Dbg::Interrupt(JDWP::ObjectId thread_id) {
1914 ScopedObjectAccess soa(Thread::Current());
1915 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
1916 Thread* thread;
1917 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1918 if (error != JDWP::ERR_NONE) {
1919 return error;
1920 }
1921 thread->Interrupt();
1922 return JDWP::ERR_NONE;
1923}
1924
Elliott Hughescaf76542012-06-28 16:08:22 -07001925void Dbg::GetThreads(JDWP::ObjectId thread_group_id, std::vector<JDWP::ObjectId>& thread_ids) {
Ian Rogers365c1022012-06-22 15:05:28 -07001926 class ThreadListVisitor {
1927 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001928 ThreadListVisitor(const ScopedObjectAccessUnchecked& soa, mirror::Object* desired_thread_group,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001929 std::vector<JDWP::ObjectId>& thread_ids)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001930 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
jeffhao0dfbb7e2012-11-28 15:26:03 -08001931 : soa_(soa), desired_thread_group_(desired_thread_group), thread_ids_(thread_ids) {}
Ian Rogers365c1022012-06-22 15:05:28 -07001932
Elliott Hughesa2155262011-11-16 16:26:58 -08001933 static void Visit(Thread* t, void* arg) {
1934 reinterpret_cast<ThreadListVisitor*>(arg)->Visit(t);
1935 }
1936
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001937 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1938 // annotalysis.
1939 void Visit(Thread* t) NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughesa2155262011-11-16 16:26:58 -08001940 if (t == Dbg::GetDebugThread()) {
1941 // Skip the JDWP thread. Some debuggers get bent out of shape when they can't suspend and
1942 // query all threads, so it's easier if we just don't tell them about this thread.
1943 return;
1944 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001945 mirror::Object* peer = t->GetPeer();
jeffhao0dfbb7e2012-11-28 15:26:03 -08001946 if (IsInDesiredThreadGroup(peer)) {
Ian Rogers120f1c72012-09-28 17:17:10 -07001947 thread_ids_.push_back(gRegistry->Add(peer));
Elliott Hughesa2155262011-11-16 16:26:58 -08001948 }
1949 }
1950
Ian Rogers365c1022012-06-22 15:05:28 -07001951 private:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001952 bool IsInDesiredThreadGroup(mirror::Object* peer)
jeffhao0dfbb7e2012-11-28 15:26:03 -08001953 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
jeffhao0dfbb7e2012-11-28 15:26:03 -08001954 // peer might be NULL if the thread is still starting up.
1955 if (peer == NULL) {
1956 // We can't tell the debugger about this thread yet.
1957 // TODO: if we identified threads to the debugger by their Thread*
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001958 // rather than their peer's mirror::Object*, we could fix this.
jeffhao0dfbb7e2012-11-28 15:26:03 -08001959 // Doing so might help us report ZOMBIE threads too.
1960 return false;
1961 }
jeffhaoc1e04902012-12-13 12:41:10 -08001962 // Do we want threads from all thread groups?
1963 if (desired_thread_group_ == NULL) {
1964 return true;
1965 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001966 mirror::Object* group = soa_.DecodeField(WellKnownClasses::java_lang_Thread_group)->GetObject(peer);
jeffhao0dfbb7e2012-11-28 15:26:03 -08001967 return (group == desired_thread_group_);
1968 }
1969
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07001970 const ScopedObjectAccessUnchecked& soa_;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001971 mirror::Object* const desired_thread_group_;
Elliott Hughescaf76542012-06-28 16:08:22 -07001972 std::vector<JDWP::ObjectId>& thread_ids_;
Elliott Hughesa2155262011-11-16 16:26:58 -08001973 };
1974
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001975 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001976 mirror::Object* thread_group = gRegistry->Get<mirror::Object*>(thread_group_id);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001977 ThreadListVisitor tlv(soa, thread_group, thread_ids);
Ian Rogers50b35e22012-10-04 10:09:15 -07001978 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughesf8349362012-06-18 15:00:06 -07001979 Runtime::Current()->GetThreadList()->ForEach(ThreadListVisitor::Visit, &tlv);
Elliott Hughescaf76542012-06-28 16:08:22 -07001980}
Elliott Hughesa2155262011-11-16 16:26:58 -08001981
Elliott Hughescaf76542012-06-28 16:08:22 -07001982void Dbg::GetChildThreadGroups(JDWP::ObjectId thread_group_id, std::vector<JDWP::ObjectId>& child_thread_group_ids) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001983 ScopedObjectAccess soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001984 mirror::Object* thread_group = gRegistry->Get<mirror::Object*>(thread_group_id);
Elliott Hughescaf76542012-06-28 16:08:22 -07001985
1986 // Get the ArrayList<ThreadGroup> "groups" out of this thread group...
Brian Carlstromea46f952013-07-30 01:26:50 -07001987 mirror::ArtField* groups_field = thread_group->GetClass()->FindInstanceField("groups", "Ljava/util/List;");
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001988 mirror::Object* groups_array_list = groups_field->GetObject(thread_group);
Elliott Hughescaf76542012-06-28 16:08:22 -07001989
1990 // Get the array and size out of the ArrayList<ThreadGroup>...
Brian Carlstromea46f952013-07-30 01:26:50 -07001991 mirror::ArtField* array_field = groups_array_list->GetClass()->FindInstanceField("array", "[Ljava/lang/Object;");
1992 mirror::ArtField* size_field = groups_array_list->GetClass()->FindInstanceField("size", "I");
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001993 mirror::ObjectArray<mirror::Object>* groups_array =
1994 array_field->GetObject(groups_array_list)->AsObjectArray<mirror::Object>();
Elliott Hughescaf76542012-06-28 16:08:22 -07001995 const int32_t size = size_field->GetInt(groups_array_list);
1996
1997 // Copy the first 'size' elements out of the array into the result.
1998 for (int32_t i = 0; i < size; ++i) {
1999 child_thread_group_ids.push_back(gRegistry->Add(groups_array->Get(i)));
Elliott Hughesa2155262011-11-16 16:26:58 -08002000 }
2001}
2002
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002003static int GetStackDepth(Thread* thread)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002004 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002005 struct CountStackDepthVisitor : public StackVisitor {
Brian Carlstrom93ba8932013-07-17 21:31:49 -07002006 explicit CountStackDepthVisitor(Thread* thread)
Ian Rogers7a22fa62013-01-23 12:16:16 -08002007 : StackVisitor(thread, NULL), depth(0) {}
Ian Rogers0399dde2012-06-06 17:09:28 -07002008
Elliott Hughes64f574f2013-02-20 14:57:12 -08002009 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2010 // annotalysis.
2011 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07002012 if (!GetMethod()->IsRuntimeMethod()) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -08002013 ++depth;
2014 }
Elliott Hughes530fa002012-03-12 11:44:49 -07002015 return true;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08002016 }
2017 size_t depth;
2018 };
Elliott Hughes08fc03a2012-06-26 17:34:00 -07002019
Ian Rogers7a22fa62013-01-23 12:16:16 -08002020 CountStackDepthVisitor visitor(thread);
Ian Rogers0399dde2012-06-06 17:09:28 -07002021 visitor.WalkStack();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08002022 return visitor.depth;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002023}
2024
Elliott Hughes221229c2013-01-08 18:17:50 -08002025JDWP::JdwpError Dbg::GetThreadFrameCount(JDWP::ObjectId thread_id, size_t& result) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002026 ScopedObjectAccess soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08002027 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002028 Thread* thread;
2029 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
2030 if (error != JDWP::ERR_NONE) {
2031 return error;
2032 }
Elliott Hughesf15f4a02013-01-09 10:09:38 -08002033 if (!IsSuspendedForDebugger(soa, thread)) {
2034 return JDWP::ERR_THREAD_NOT_SUSPENDED;
2035 }
Elliott Hughes221229c2013-01-08 18:17:50 -08002036 result = GetStackDepth(thread);
2037 return JDWP::ERR_NONE;
Elliott Hughes86964332012-02-15 19:37:42 -08002038}
2039
Ian Rogers306057f2012-11-26 12:45:53 -08002040JDWP::JdwpError Dbg::GetThreadFrames(JDWP::ObjectId thread_id, size_t start_frame,
2041 size_t frame_count, JDWP::ExpandBuf* buf) {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002042 class GetFrameVisitor : public StackVisitor {
2043 public:
Ian Rogers7a22fa62013-01-23 12:16:16 -08002044 GetFrameVisitor(Thread* thread, size_t start_frame, size_t frame_count, JDWP::ExpandBuf* buf)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002045 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08002046 : StackVisitor(thread, NULL), depth_(0),
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002047 start_frame_(start_frame), frame_count_(frame_count), buf_(buf) {
2048 expandBufAdd4BE(buf_, frame_count_);
Elliott Hughes03181a82011-11-17 17:22:21 -08002049 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002050
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002051 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2052 // annotalysis.
2053 virtual bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07002054 if (GetMethod()->IsRuntimeMethod()) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07002055 return true; // The debugger can't do anything useful with a frame that has no Method*.
Elliott Hughes03181a82011-11-17 17:22:21 -08002056 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002057 if (depth_ >= start_frame_ + frame_count_) {
Elliott Hughes530fa002012-03-12 11:44:49 -07002058 return false;
Elliott Hughes03181a82011-11-17 17:22:21 -08002059 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002060 if (depth_ >= start_frame_) {
2061 JDWP::FrameId frame_id(GetFrameId());
2062 JDWP::JdwpLocation location;
2063 SetLocation(location, GetMethod(), GetDexPc());
Ian Rogersef7d42f2014-01-06 12:55:46 -08002064 VLOG(jdwp) << StringPrintf(" Frame %3zd: id=%3" PRIu64 " ", depth_, frame_id) << location;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002065 expandBufAdd8BE(buf_, frame_id);
2066 expandBufAddLocation(buf_, location);
2067 }
2068 ++depth_;
Elliott Hughes530fa002012-03-12 11:44:49 -07002069 return true;
Elliott Hughes03181a82011-11-17 17:22:21 -08002070 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002071
2072 private:
2073 size_t depth_;
2074 const size_t start_frame_;
2075 const size_t frame_count_;
2076 JDWP::ExpandBuf* buf_;
Elliott Hughes03181a82011-11-17 17:22:21 -08002077 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002078
2079 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08002080 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002081 Thread* thread;
2082 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
2083 if (error != JDWP::ERR_NONE) {
2084 return error;
2085 }
Elliott Hughesf15f4a02013-01-09 10:09:38 -08002086 if (!IsSuspendedForDebugger(soa, thread)) {
2087 return JDWP::ERR_THREAD_NOT_SUSPENDED;
2088 }
Ian Rogers7a22fa62013-01-23 12:16:16 -08002089 GetFrameVisitor visitor(thread, start_frame, frame_count, buf);
Ian Rogers0399dde2012-06-06 17:09:28 -07002090 visitor.WalkStack();
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002091 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002092}
2093
2094JDWP::ObjectId Dbg::GetThreadSelfId() {
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07002095 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogerscfaa4552012-11-26 21:00:08 -08002096 return gRegistry->Add(soa.Self()->GetPeer());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002097}
2098
Elliott Hughes475fc232011-10-25 15:00:35 -07002099void Dbg::SuspendVM() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002100 Runtime::Current()->GetThreadList()->SuspendAllForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002101}
2102
2103void Dbg::ResumeVM() {
Elliott Hughesc61a2672012-06-21 14:52:29 -07002104 Runtime::Current()->GetThreadList()->UndoDebuggerSuspensions();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002105}
2106
Elliott Hughes221229c2013-01-08 18:17:50 -08002107JDWP::JdwpError Dbg::SuspendThread(JDWP::ObjectId thread_id, bool request_suspension) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002108 ScopedLocalRef<jobject> peer(Thread::Current()->GetJniEnv(), NULL);
2109 {
2110 ScopedObjectAccess soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002111 peer.reset(soa.AddLocalReference<jobject>(gRegistry->Get<mirror::Object*>(thread_id)));
Elliott Hughes4e235312011-12-02 11:34:15 -08002112 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002113 if (peer.get() == NULL) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002114 return JDWP::ERR_THREAD_NOT_ALIVE;
2115 }
2116 // Suspend thread to build stack trace.
Elliott Hughesf327e072013-01-09 16:01:26 -08002117 bool timed_out;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07002118 Thread* thread = ThreadList::SuspendThreadByPeer(peer.get(), request_suspension, true,
2119 &timed_out);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002120 if (thread != NULL) {
2121 return JDWP::ERR_NONE;
Elliott Hughesf327e072013-01-09 16:01:26 -08002122 } else if (timed_out) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002123 return JDWP::ERR_INTERNAL;
2124 } else {
2125 return JDWP::ERR_THREAD_NOT_ALIVE;
2126 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002127}
2128
Elliott Hughes221229c2013-01-08 18:17:50 -08002129void Dbg::ResumeThread(JDWP::ObjectId thread_id) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002130 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002131 mirror::Object* peer = gRegistry->Get<mirror::Object*>(thread_id);
jeffhaoa77f0f62012-12-05 17:19:31 -08002132 Thread* thread;
2133 {
2134 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
2135 thread = Thread::FromManagedThread(soa, peer);
2136 }
Elliott Hughes4e235312011-12-02 11:34:15 -08002137 if (thread == NULL) {
2138 LOG(WARNING) << "No such thread for resume: " << peer;
2139 return;
2140 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002141 bool needs_resume;
2142 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002143 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002144 needs_resume = thread->GetSuspendCount() > 0;
2145 }
2146 if (needs_resume) {
Elliott Hughes546b9862012-06-20 16:06:13 -07002147 Runtime::Current()->GetThreadList()->Resume(thread, true);
2148 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002149}
2150
2151void Dbg::SuspendSelf() {
Elliott Hughes475fc232011-10-25 15:00:35 -07002152 Runtime::Current()->GetThreadList()->SuspendSelfForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002153}
2154
Ian Rogers0399dde2012-06-06 17:09:28 -07002155struct GetThisVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -08002156 GetThisVisitor(Thread* thread, Context* context, JDWP::FrameId frame_id)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002157 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08002158 : StackVisitor(thread, context), this_object(NULL), frame_id(frame_id) {}
Ian Rogers0399dde2012-06-06 17:09:28 -07002159
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002160 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2161 // annotalysis.
2162 virtual bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002163 if (frame_id != GetFrameId()) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002164 return true; // continue
Ian Rogers0399dde2012-06-06 17:09:28 -07002165 } else {
Ian Rogers62d6c772013-02-27 08:32:07 -08002166 this_object = GetThisObject();
2167 return false;
Ian Rogers0399dde2012-06-06 17:09:28 -07002168 }
Elliott Hughes86b00102011-12-05 17:54:26 -08002169 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002170
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002171 mirror::Object* this_object;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002172 JDWP::FrameId frame_id;
Ian Rogers0399dde2012-06-06 17:09:28 -07002173};
2174
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002175JDWP::JdwpError Dbg::GetThisObject(JDWP::ObjectId thread_id, JDWP::FrameId frame_id,
2176 JDWP::ObjectId* result) {
2177 ScopedObjectAccessUnchecked soa(Thread::Current());
2178 Thread* thread;
2179 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002180 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002181 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
2182 if (error != JDWP::ERR_NONE) {
2183 return error;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002184 }
Elliott Hughes9e0c1752013-01-09 14:02:58 -08002185 if (!IsSuspendedForDebugger(soa, thread)) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002186 return JDWP::ERR_THREAD_NOT_SUSPENDED;
2187 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002188 }
Elliott Hughescaf76542012-06-28 16:08:22 -07002189 UniquePtr<Context> context(Context::Create());
Ian Rogers7a22fa62013-01-23 12:16:16 -08002190 GetThisVisitor visitor(thread, context.get(), frame_id);
Ian Rogers0399dde2012-06-06 17:09:28 -07002191 visitor.WalkStack();
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002192 *result = gRegistry->Add(visitor.this_object);
2193 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002194}
2195
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002196JDWP::JdwpError Dbg::GetLocalValue(JDWP::ObjectId thread_id, JDWP::FrameId frame_id, int slot,
2197 JDWP::JdwpTag tag, uint8_t* buf, size_t width) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002198 struct GetLocalVisitor : public StackVisitor {
Ian Rogers98379392014-02-24 16:53:16 -08002199 GetLocalVisitor(const ScopedObjectAccessUnchecked& soa, Thread* thread, Context* context,
2200 JDWP::FrameId frame_id, int slot, JDWP::JdwpTag tag, uint8_t* buf, size_t width)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002201 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers98379392014-02-24 16:53:16 -08002202 : StackVisitor(thread, context), soa_(soa), frame_id_(frame_id), slot_(slot), tag_(tag),
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002203 buf_(buf), width_(width), error_(JDWP::ERR_NONE) {}
Ian Rogersca190662012-06-26 15:45:57 -07002204
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002205 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2206 // annotalysis.
2207 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07002208 if (GetFrameId() != frame_id_) {
2209 return true; // Not our frame, carry on.
Elliott Hughesdbb40792011-11-18 17:05:22 -08002210 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002211 // TODO: check that the tag is compatible with the actual type of the slot!
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002212 // TODO: check slot is valid for this method or return INVALID_SLOT error.
Brian Carlstromea46f952013-07-30 01:26:50 -07002213 mirror::ArtMethod* m = GetMethod();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002214 if (m->IsNative()) {
2215 // We can't read local value from native method.
2216 error_ = JDWP::ERR_OPAQUE_FRAME;
2217 return false;
2218 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002219 uint16_t reg = DemangleSlot(slot_, m);
Elliott Hughesdbb40792011-11-18 17:05:22 -08002220
Ian Rogers0399dde2012-06-06 17:09:28 -07002221 switch (tag_) {
2222 case JDWP::JT_BOOLEAN:
2223 {
2224 CHECK_EQ(width_, 1U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002225 uint32_t intVal = GetVReg(m, reg, kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002226 VLOG(jdwp) << "get boolean local " << reg << " = " << intVal;
2227 JDWP::Set1(buf_+1, intVal != 0);
2228 }
2229 break;
2230 case JDWP::JT_BYTE:
2231 {
2232 CHECK_EQ(width_, 1U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002233 uint32_t intVal = GetVReg(m, reg, kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002234 VLOG(jdwp) << "get byte local " << reg << " = " << intVal;
2235 JDWP::Set1(buf_+1, intVal);
2236 }
2237 break;
2238 case JDWP::JT_SHORT:
2239 case JDWP::JT_CHAR:
2240 {
2241 CHECK_EQ(width_, 2U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002242 uint32_t intVal = GetVReg(m, reg, kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002243 VLOG(jdwp) << "get short/char local " << reg << " = " << intVal;
2244 JDWP::Set2BE(buf_+1, intVal);
2245 }
2246 break;
2247 case JDWP::JT_INT:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002248 {
2249 CHECK_EQ(width_, 4U);
2250 uint32_t intVal = GetVReg(m, reg, kIntVReg);
2251 VLOG(jdwp) << "get int local " << reg << " = " << intVal;
2252 JDWP::Set4BE(buf_+1, intVal);
2253 }
2254 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002255 case JDWP::JT_FLOAT:
2256 {
2257 CHECK_EQ(width_, 4U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002258 uint32_t intVal = GetVReg(m, reg, kFloatVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002259 VLOG(jdwp) << "get int/float local " << reg << " = " << intVal;
2260 JDWP::Set4BE(buf_+1, intVal);
2261 }
2262 break;
2263 case JDWP::JT_ARRAY:
2264 {
2265 CHECK_EQ(width_, sizeof(JDWP::ObjectId));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002266 mirror::Object* o = reinterpret_cast<mirror::Object*>(GetVReg(m, reg, kReferenceVReg));
Ian Rogers0399dde2012-06-06 17:09:28 -07002267 VLOG(jdwp) << "get array local " << reg << " = " << o;
Mathieu Chartier590fee92013-09-13 13:46:47 -07002268 if (!Runtime::Current()->GetHeap()->IsValidObjectAddress(o)) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002269 LOG(FATAL) << "Register " << reg << " expected to hold array: " << o;
2270 }
2271 JDWP::SetObjectId(buf_+1, gRegistry->Add(o));
2272 }
2273 break;
2274 case JDWP::JT_CLASS_LOADER:
2275 case JDWP::JT_CLASS_OBJECT:
2276 case JDWP::JT_OBJECT:
2277 case JDWP::JT_STRING:
2278 case JDWP::JT_THREAD:
2279 case JDWP::JT_THREAD_GROUP:
2280 {
2281 CHECK_EQ(width_, sizeof(JDWP::ObjectId));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002282 mirror::Object* o = reinterpret_cast<mirror::Object*>(GetVReg(m, reg, kReferenceVReg));
Ian Rogers0399dde2012-06-06 17:09:28 -07002283 VLOG(jdwp) << "get object local " << reg << " = " << o;
Mathieu Chartier590fee92013-09-13 13:46:47 -07002284 if (!Runtime::Current()->GetHeap()->IsValidObjectAddress(o)) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002285 LOG(FATAL) << "Register " << reg << " expected to hold object: " << o;
2286 }
Ian Rogers98379392014-02-24 16:53:16 -08002287 tag_ = TagFromObject(soa_, o);
Ian Rogers0399dde2012-06-06 17:09:28 -07002288 JDWP::SetObjectId(buf_+1, gRegistry->Add(o));
2289 }
2290 break;
2291 case JDWP::JT_DOUBLE:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002292 {
2293 CHECK_EQ(width_, 8U);
2294 uint32_t lo = GetVReg(m, reg, kDoubleLoVReg);
2295 uint64_t hi = GetVReg(m, reg + 1, kDoubleHiVReg);
2296 uint64_t longVal = (hi << 32) | lo;
2297 VLOG(jdwp) << "get double/long local " << hi << ":" << lo << " = " << longVal;
2298 JDWP::Set8BE(buf_+1, longVal);
2299 }
2300 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002301 case JDWP::JT_LONG:
2302 {
2303 CHECK_EQ(width_, 8U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002304 uint32_t lo = GetVReg(m, reg, kLongLoVReg);
2305 uint64_t hi = GetVReg(m, reg + 1, kLongHiVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002306 uint64_t longVal = (hi << 32) | lo;
2307 VLOG(jdwp) << "get double/long local " << hi << ":" << lo << " = " << longVal;
2308 JDWP::Set8BE(buf_+1, longVal);
2309 }
2310 break;
2311 default:
2312 LOG(FATAL) << "Unknown tag " << tag_;
2313 break;
2314 }
2315
2316 // Prepend tag, which may have been updated.
2317 JDWP::Set1(buf_, tag_);
2318 return false;
2319 }
Ian Rogers98379392014-02-24 16:53:16 -08002320 const ScopedObjectAccessUnchecked& soa_;
Ian Rogers0399dde2012-06-06 17:09:28 -07002321 const JDWP::FrameId frame_id_;
2322 const int slot_;
2323 JDWP::JdwpTag tag_;
2324 uint8_t* const buf_;
2325 const size_t width_;
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002326 JDWP::JdwpError error_;
Ian Rogers0399dde2012-06-06 17:09:28 -07002327 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002328
2329 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08002330 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002331 Thread* thread;
2332 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
2333 if (error != JDWP::ERR_NONE) {
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002334 return error;
Elliott Hughes221229c2013-01-08 18:17:50 -08002335 }
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002336 // TODO check thread is suspended by the debugger ?
Ian Rogers0399dde2012-06-06 17:09:28 -07002337 UniquePtr<Context> context(Context::Create());
Ian Rogers98379392014-02-24 16:53:16 -08002338 GetLocalVisitor visitor(soa, thread, context.get(), frame_id, slot, tag, buf, width);
Ian Rogers0399dde2012-06-06 17:09:28 -07002339 visitor.WalkStack();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002340 return visitor.error_;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002341}
2342
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002343JDWP::JdwpError Dbg::SetLocalValue(JDWP::ObjectId thread_id, JDWP::FrameId frame_id, int slot,
2344 JDWP::JdwpTag tag, uint64_t value, size_t width) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002345 struct SetLocalVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -08002346 SetLocalVisitor(Thread* thread, Context* context,
Ian Rogers0399dde2012-06-06 17:09:28 -07002347 JDWP::FrameId frame_id, int slot, JDWP::JdwpTag tag, uint64_t value,
Ian Rogersca190662012-06-26 15:45:57 -07002348 size_t width)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002349 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08002350 : StackVisitor(thread, context),
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002351 frame_id_(frame_id), slot_(slot), tag_(tag), value_(value), width_(width),
2352 error_(JDWP::ERR_NONE) {}
Ian Rogersca190662012-06-26 15:45:57 -07002353
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002354 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2355 // annotalysis.
2356 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07002357 if (GetFrameId() != frame_id_) {
2358 return true; // Not our frame, carry on.
2359 }
2360 // TODO: check that the tag is compatible with the actual type of the slot!
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002361 // TODO: check slot is valid for this method or return INVALID_SLOT error.
Brian Carlstromea46f952013-07-30 01:26:50 -07002362 mirror::ArtMethod* m = GetMethod();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002363 if (m->IsNative()) {
2364 // We can't read local value from native method.
2365 error_ = JDWP::ERR_OPAQUE_FRAME;
2366 return false;
2367 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002368 uint16_t reg = DemangleSlot(slot_, m);
2369
2370 switch (tag_) {
2371 case JDWP::JT_BOOLEAN:
2372 case JDWP::JT_BYTE:
2373 CHECK_EQ(width_, 1U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002374 SetVReg(m, reg, static_cast<uint32_t>(value_), kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002375 break;
2376 case JDWP::JT_SHORT:
2377 case JDWP::JT_CHAR:
2378 CHECK_EQ(width_, 2U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002379 SetVReg(m, reg, static_cast<uint32_t>(value_), kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002380 break;
2381 case JDWP::JT_INT:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002382 CHECK_EQ(width_, 4U);
2383 SetVReg(m, reg, static_cast<uint32_t>(value_), kIntVReg);
2384 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002385 case JDWP::JT_FLOAT:
2386 CHECK_EQ(width_, 4U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002387 SetVReg(m, reg, static_cast<uint32_t>(value_), kFloatVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002388 break;
2389 case JDWP::JT_ARRAY:
2390 case JDWP::JT_OBJECT:
2391 case JDWP::JT_STRING:
2392 {
2393 CHECK_EQ(width_, sizeof(JDWP::ObjectId));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002394 mirror::Object* o = gRegistry->Get<mirror::Object*>(static_cast<JDWP::ObjectId>(value_));
Elliott Hughes64f574f2013-02-20 14:57:12 -08002395 if (o == ObjectRegistry::kInvalidObject) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002396 UNIMPLEMENTED(FATAL) << "return an error code when given an invalid object to store";
2397 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002398 SetVReg(m, reg, static_cast<uint32_t>(reinterpret_cast<uintptr_t>(o)), kReferenceVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002399 }
2400 break;
2401 case JDWP::JT_DOUBLE:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002402 CHECK_EQ(width_, 8U);
2403 SetVReg(m, reg, static_cast<uint32_t>(value_), kDoubleLoVReg);
2404 SetVReg(m, reg + 1, static_cast<uint32_t>(value_ >> 32), kDoubleHiVReg);
2405 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002406 case JDWP::JT_LONG:
2407 CHECK_EQ(width_, 8U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002408 SetVReg(m, reg, static_cast<uint32_t>(value_), kLongLoVReg);
2409 SetVReg(m, reg + 1, static_cast<uint32_t>(value_ >> 32), kLongHiVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002410 break;
2411 default:
2412 LOG(FATAL) << "Unknown tag " << tag_;
2413 break;
2414 }
2415 return false;
2416 }
2417
2418 const JDWP::FrameId frame_id_;
2419 const int slot_;
2420 const JDWP::JdwpTag tag_;
2421 const uint64_t value_;
2422 const size_t width_;
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002423 JDWP::JdwpError error_;
Ian Rogers0399dde2012-06-06 17:09:28 -07002424 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002425
2426 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08002427 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002428 Thread* thread;
2429 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
2430 if (error != JDWP::ERR_NONE) {
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002431 return error;
Elliott Hughes221229c2013-01-08 18:17:50 -08002432 }
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002433 // TODO check thread is suspended by the debugger ?
Elliott Hughes08fc03a2012-06-26 17:34:00 -07002434 UniquePtr<Context> context(Context::Create());
Ian Rogers7a22fa62013-01-23 12:16:16 -08002435 SetLocalVisitor visitor(thread, context.get(), frame_id, slot, tag, value, width);
Ian Rogers0399dde2012-06-06 17:09:28 -07002436 visitor.WalkStack();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002437 return visitor.error_;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002438}
2439
Ian Rogersef7d42f2014-01-06 12:55:46 -08002440void Dbg::PostLocationEvent(mirror::ArtMethod* m, int dex_pc, mirror::Object* this_object,
Jeff Hao579b0242013-11-18 13:16:49 -08002441 int event_flags, const JValue* return_value) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002442 JDWP::JdwpLocation location;
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002443 SetLocation(location, m, dex_pc);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002444
Elliott Hughes64f574f2013-02-20 14:57:12 -08002445 // If 'this_object' isn't already in the registry, we know that we're not looking for it,
2446 // so there's no point adding it to the registry and burning through ids.
2447 JDWP::ObjectId this_id = 0;
2448 if (gRegistry->Contains(this_object)) {
2449 this_id = gRegistry->Add(this_object);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002450 }
Jeff Hao579b0242013-11-18 13:16:49 -08002451 gJdwpState->PostLocationEvent(&location, this_id, event_flags, return_value);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002452}
2453
Ian Rogers62d6c772013-02-27 08:32:07 -08002454void Dbg::PostException(Thread* thread, const ThrowLocation& throw_location,
Brian Carlstromea46f952013-07-30 01:26:50 -07002455 mirror::ArtMethod* catch_method,
Elliott Hughes64f574f2013-02-20 14:57:12 -08002456 uint32_t catch_dex_pc, mirror::Throwable* exception_object) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002457 if (!IsDebuggerActive()) {
Ian Rogers0ad5bb82011-12-07 10:16:32 -08002458 return;
2459 }
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002460
Ian Rogers62d6c772013-02-27 08:32:07 -08002461 JDWP::JdwpLocation jdwp_throw_location;
2462 SetLocation(jdwp_throw_location, throw_location.GetMethod(), throw_location.GetDexPc());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002463 JDWP::JdwpLocation catch_location;
Elliott Hughescaf76542012-06-28 16:08:22 -07002464 SetLocation(catch_location, catch_method, catch_dex_pc);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002465
2466 // We need 'this' for InstanceOnly filters.
Ian Rogers62d6c772013-02-27 08:32:07 -08002467 JDWP::ObjectId this_id = gRegistry->Add(throw_location.GetThis());
Elliott Hughes64f574f2013-02-20 14:57:12 -08002468 JDWP::ObjectId exception_id = gRegistry->Add(exception_object);
2469 JDWP::RefTypeId exception_class_id = gRegistry->AddRefType(exception_object->GetClass());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002470
Ian Rogers62d6c772013-02-27 08:32:07 -08002471 gJdwpState->PostException(&jdwp_throw_location, exception_id, exception_class_id, &catch_location,
2472 this_id);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002473}
2474
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002475void Dbg::PostClassPrepare(mirror::Class* c) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002476 if (!IsDebuggerActive()) {
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002477 return;
2478 }
2479
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08002480 // OLD-TODO - we currently always send both "verified" and "prepared" since
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002481 // debuggers seem to like that. There might be some advantage to honesty,
2482 // since the class may not yet be verified.
2483 int state = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
2484 JDWP::JdwpTypeTag tag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
Ian Rogersfc0e94b2013-09-23 23:51:32 -07002485 gJdwpState->PostClassPrepare(tag, gRegistry->Add(c),
Ian Rogersdfb325e2013-10-30 01:00:44 -07002486 ClassHelper(c).GetDescriptor(), state);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002487}
2488
Ian Rogers62d6c772013-02-27 08:32:07 -08002489void Dbg::UpdateDebugger(Thread* thread, mirror::Object* this_object,
Ian Rogersef7d42f2014-01-06 12:55:46 -08002490 mirror::ArtMethod* m, uint32_t dex_pc) {
Ian Rogers62d6c772013-02-27 08:32:07 -08002491 if (!IsDebuggerActive() || dex_pc == static_cast<uint32_t>(-2) /* fake method exit */) {
Elliott Hughes2aa2e392012-02-17 17:15:43 -08002492 return;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002493 }
2494
Elliott Hughes2aa2e392012-02-17 17:15:43 -08002495 int event_flags = 0;
2496
Elliott Hughes86964332012-02-15 19:37:42 -08002497 if (IsBreakpoint(m, dex_pc)) {
2498 event_flags |= kBreakpoint;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002499 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002500
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002501 // If the debugger is single-stepping one of our threads, check to
2502 // see if we're that thread and we've reached a step point.
2503 const SingleStepControl* single_step_control = thread->GetSingleStepControl();
2504 DCHECK(single_step_control != nullptr);
2505 if (single_step_control->is_active) {
2506 CHECK(!m->IsNative());
2507 if (single_step_control->step_depth == JDWP::SD_INTO) {
2508 // Step into method calls. We break when the line number
2509 // or method pointer changes. If we're in SS_MIN mode, we
2510 // always stop.
2511 if (single_step_control->method != m) {
2512 event_flags |= kSingleStep;
2513 VLOG(jdwp) << "SS new method";
2514 } else if (single_step_control->step_size == JDWP::SS_MIN) {
2515 event_flags |= kSingleStep;
2516 VLOG(jdwp) << "SS new instruction";
2517 } else if (single_step_control->dex_pcs.find(dex_pc) == single_step_control->dex_pcs.end()) {
2518 event_flags |= kSingleStep;
2519 VLOG(jdwp) << "SS new line";
2520 }
2521 } else if (single_step_control->step_depth == JDWP::SD_OVER) {
2522 // Step over method calls. We break when the line number is
2523 // different and the frame depth is <= the original frame
2524 // depth. (We can't just compare on the method, because we
2525 // might get unrolled past it by an exception, and it's tricky
2526 // to identify recursion.)
2527
2528 int stack_depth = GetStackDepth(thread);
2529
2530 if (stack_depth < single_step_control->stack_depth) {
2531 // Popped up one or more frames, always trigger.
2532 event_flags |= kSingleStep;
2533 VLOG(jdwp) << "SS method pop";
2534 } else if (stack_depth == single_step_control->stack_depth) {
2535 // Same depth, see if we moved.
2536 if (single_step_control->step_size == JDWP::SS_MIN) {
Elliott Hughes86964332012-02-15 19:37:42 -08002537 event_flags |= kSingleStep;
2538 VLOG(jdwp) << "SS new instruction";
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002539 } else if (single_step_control->dex_pcs.find(dex_pc) == single_step_control->dex_pcs.end()) {
Elliott Hughes2435a572012-02-17 16:07:41 -08002540 event_flags |= kSingleStep;
2541 VLOG(jdwp) << "SS new line";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002542 }
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002543 }
2544 } else {
2545 CHECK_EQ(single_step_control->step_depth, JDWP::SD_OUT);
2546 // Return from the current method. We break when the frame
2547 // depth pops up.
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002548
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002549 // This differs from the "method exit" break in that it stops
2550 // with the PC at the next instruction in the returned-to
2551 // function, rather than the end of the returning function.
Elliott Hughes86964332012-02-15 19:37:42 -08002552
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002553 int stack_depth = GetStackDepth(thread);
2554 if (stack_depth < single_step_control->stack_depth) {
2555 event_flags |= kSingleStep;
2556 VLOG(jdwp) << "SS method pop";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002557 }
2558 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002559 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002560
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002561 // If there's something interesting going on, see if it matches one
2562 // of the debugger filters.
2563 if (event_flags != 0) {
Jeff Hao579b0242013-11-18 13:16:49 -08002564 Dbg::PostLocationEvent(m, dex_pc, this_object, event_flags, nullptr);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002565 }
2566}
2567
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002568// Process request while all mutator threads are suspended.
2569void Dbg::ProcessDeoptimizationRequest(const DeoptimizationRequest& request) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002570 instrumentation::Instrumentation* instrumentation = Runtime::Current()->GetInstrumentation();
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002571 switch (request.kind) {
2572 case DeoptimizationRequest::kNothing:
2573 LOG(WARNING) << "Ignoring empty deoptimization request.";
2574 break;
2575 case DeoptimizationRequest::kFullDeoptimization:
2576 VLOG(jdwp) << "Deoptimize the world";
2577 instrumentation->DeoptimizeEverything();
2578 break;
2579 case DeoptimizationRequest::kFullUndeoptimization:
2580 VLOG(jdwp) << "Undeoptimize the world";
2581 instrumentation->UndeoptimizeEverything();
2582 break;
2583 case DeoptimizationRequest::kSelectiveDeoptimization:
2584 VLOG(jdwp) << "Deoptimize method " << PrettyMethod(request.method);
2585 instrumentation->Deoptimize(request.method);
2586 break;
2587 case DeoptimizationRequest::kSelectiveUndeoptimization:
2588 VLOG(jdwp) << "Undeoptimize method " << PrettyMethod(request.method);
2589 instrumentation->Undeoptimize(request.method);
2590 break;
2591 default:
2592 LOG(FATAL) << "Unsupported deoptimization request kind " << request.kind;
2593 break;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002594 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002595}
2596
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002597void Dbg::RequestDeoptimization(const DeoptimizationRequest& req) {
2598 if (req.kind == DeoptimizationRequest::kNothing) {
2599 // Nothing to do.
2600 return;
2601 }
2602 MutexLock mu(Thread::Current(), *deoptimization_lock_);
2603 switch (req.kind) {
2604 case DeoptimizationRequest::kFullDeoptimization: {
2605 DCHECK(req.method == nullptr);
2606 if (full_deoptimization_event_count_ == 0) {
2607 VLOG(jdwp) << "Request full deoptimization";
2608 deoptimization_requests_.push_back(req);
2609 }
2610 ++full_deoptimization_event_count_;
2611 break;
2612 }
2613 case DeoptimizationRequest::kFullUndeoptimization: {
2614 DCHECK(req.method == nullptr);
2615 DCHECK_GT(full_deoptimization_event_count_, 0U);
2616 --full_deoptimization_event_count_;
2617 if (full_deoptimization_event_count_ == 0) {
2618 VLOG(jdwp) << "Request full undeoptimization";
2619 deoptimization_requests_.push_back(req);
2620 }
2621 break;
2622 }
2623 case DeoptimizationRequest::kSelectiveDeoptimization: {
2624 DCHECK(req.method != nullptr);
2625 VLOG(jdwp) << "Request deoptimization of " << PrettyMethod(req.method);
2626 deoptimization_requests_.push_back(req);
2627 break;
2628 }
2629 case DeoptimizationRequest::kSelectiveUndeoptimization: {
2630 DCHECK(req.method != nullptr);
2631 VLOG(jdwp) << "Request undeoptimization of " << PrettyMethod(req.method);
2632 deoptimization_requests_.push_back(req);
2633 break;
2634 }
2635 default: {
2636 LOG(FATAL) << "Unknown deoptimization request kind " << req.kind;
2637 break;
2638 }
2639 }
2640}
2641
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002642void Dbg::ManageDeoptimization() {
2643 Thread* const self = Thread::Current();
2644 {
2645 // Avoid suspend/resume if there is no pending request.
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002646 MutexLock mu(self, *deoptimization_lock_);
2647 if (deoptimization_requests_.empty()) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002648 return;
2649 }
2650 }
2651 CHECK_EQ(self->GetState(), kRunnable);
2652 self->TransitionFromRunnableToSuspended(kWaitingForDeoptimization);
2653 // We need to suspend mutator threads first.
2654 Runtime* const runtime = Runtime::Current();
2655 runtime->GetThreadList()->SuspendAll();
2656 const ThreadState old_state = self->SetStateUnsafe(kRunnable);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002657 {
2658 MutexLock mu(self, *deoptimization_lock_);
2659 for (const DeoptimizationRequest& request : deoptimization_requests_) {
2660 ProcessDeoptimizationRequest(request);
2661 }
2662 deoptimization_requests_.clear();
2663 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002664 CHECK_EQ(self->SetStateUnsafe(old_state), kRunnable);
2665 runtime->GetThreadList()->ResumeAll();
2666 self->TransitionFromSuspendedToRunnable();
2667}
2668
Sebastien Hertza76a6d42014-03-20 16:40:17 +01002669static bool IsMethodPossiblyInlined(Thread* self, mirror::ArtMethod* m)
2670 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2671 MethodHelper mh(m);
2672 const DexFile::CodeItem* code_item = mh.GetCodeItem();
2673 if (code_item == nullptr) {
2674 // TODO We should not be asked to watch location in a native or abstract method so the code item
2675 // should never be null. We could just check we never encounter this case.
2676 return false;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002677 }
Sebastien Hertza76a6d42014-03-20 16:40:17 +01002678 SirtRef<mirror::DexCache> dex_cache(self, mh.GetDexCache());
2679 SirtRef<mirror::ClassLoader> class_loader(self, mh.GetClassLoader());
2680 verifier::MethodVerifier verifier(&mh.GetDexFile(), &dex_cache, &class_loader,
2681 &mh.GetClassDef(), code_item, m->GetDexMethodIndex(), m,
2682 m->GetAccessFlags(), false, true);
2683 // Note: we don't need to verify the method.
2684 return InlineMethodAnalyser::AnalyseMethodCode(&verifier, nullptr);
2685}
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002686
Sebastien Hertza76a6d42014-03-20 16:40:17 +01002687static const Breakpoint* FindFirstBreakpointForMethod(mirror::ArtMethod* m)
2688 EXCLUSIVE_LOCKS_REQUIRED(Locks::breakpoint_lock_) {
2689 for (const Breakpoint& breakpoint : gBreakpoints) {
2690 if (breakpoint.method == m) {
2691 return &breakpoint;
2692 }
2693 }
2694 return nullptr;
2695}
2696
2697// Sanity checks all existing breakpoints on the same method.
2698static void SanityCheckExistingBreakpoints(mirror::ArtMethod* m, bool need_full_deoptimization)
2699 EXCLUSIVE_LOCKS_REQUIRED(Locks::breakpoint_lock_) {
2700 if (kIsDebugBuild) {
2701 for (const Breakpoint& breakpoint : gBreakpoints) {
2702 CHECK_EQ(need_full_deoptimization, breakpoint.need_full_deoptimization);
2703 }
2704 if (need_full_deoptimization) {
2705 // We should have deoptimized everything but not "selectively" deoptimized this method.
2706 CHECK(Runtime::Current()->GetInstrumentation()->AreAllMethodsDeoptimized());
2707 CHECK(!Runtime::Current()->GetInstrumentation()->IsDeoptimized(m));
2708 } else {
2709 // We should have "selectively" deoptimized this method.
2710 // Note: while we have not deoptimized everything for this method, we may have done it for
2711 // another event.
2712 CHECK(Runtime::Current()->GetInstrumentation()->IsDeoptimized(m));
2713 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002714 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002715}
2716
Sebastien Hertza76a6d42014-03-20 16:40:17 +01002717// Installs a breakpoint at the specified location. Also indicates through the deoptimization
2718// request if we need to deoptimize.
2719void Dbg::WatchLocation(const JDWP::JdwpLocation* location, DeoptimizationRequest* req) {
2720 Thread* const self = Thread::Current();
Brian Carlstromea46f952013-07-30 01:26:50 -07002721 mirror::ArtMethod* m = FromMethodId(location->method_id);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01002722 DCHECK(m != nullptr) << "No method for method id " << location->method_id;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002723
Sebastien Hertza76a6d42014-03-20 16:40:17 +01002724 MutexLock mu(self, *Locks::breakpoint_lock_);
2725 const Breakpoint* const existing_breakpoint = FindFirstBreakpointForMethod(m);
2726 bool need_full_deoptimization;
2727 if (existing_breakpoint == nullptr) {
2728 // There is no breakpoint on this method yet: we need to deoptimize. If this method may be
2729 // inlined, we deoptimize everything; otherwise we deoptimize only this method.
2730 need_full_deoptimization = IsMethodPossiblyInlined(self, m);
2731 if (need_full_deoptimization) {
2732 req->kind = DeoptimizationRequest::kFullDeoptimization;
2733 req->method = nullptr;
2734 } else {
2735 req->kind = DeoptimizationRequest::kSelectiveDeoptimization;
2736 req->method = m;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002737 }
Sebastien Hertza76a6d42014-03-20 16:40:17 +01002738 } else {
2739 // There is at least one breakpoint for this method: we don't need to deoptimize.
2740 req->kind = DeoptimizationRequest::kNothing;
2741 req->method = nullptr;
2742
2743 need_full_deoptimization = existing_breakpoint->need_full_deoptimization;
2744 SanityCheckExistingBreakpoints(m, need_full_deoptimization);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002745 }
2746
Sebastien Hertza76a6d42014-03-20 16:40:17 +01002747 gBreakpoints.push_back(Breakpoint(m, location->dex_pc, need_full_deoptimization));
2748 VLOG(jdwp) << "Set breakpoint #" << (gBreakpoints.size() - 1) << ": "
2749 << gBreakpoints[gBreakpoints.size() - 1];
2750}
2751
2752// Uninstalls a breakpoint at the specified location. Also indicates through the deoptimization
2753// request if we need to undeoptimize.
2754void Dbg::UnwatchLocation(const JDWP::JdwpLocation* location, DeoptimizationRequest* req) {
2755 mirror::ArtMethod* m = FromMethodId(location->method_id);
2756 DCHECK(m != nullptr) << "No method for method id " << location->method_id;
2757
2758 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
2759 bool need_full_deoptimization = false;
2760 for (size_t i = 0, e = gBreakpoints.size(); i < e; ++i) {
2761 if (gBreakpoints[i].method == m && gBreakpoints[i].dex_pc == location->dex_pc) {
2762 VLOG(jdwp) << "Removed breakpoint #" << i << ": " << gBreakpoints[i];
2763 need_full_deoptimization = gBreakpoints[i].need_full_deoptimization;
2764 DCHECK_NE(need_full_deoptimization, Runtime::Current()->GetInstrumentation()->IsDeoptimized(m));
2765 gBreakpoints.erase(gBreakpoints.begin() + i);
2766 break;
2767 }
2768 }
2769 const Breakpoint* const existing_breakpoint = FindFirstBreakpointForMethod(m);
2770 if (existing_breakpoint == nullptr) {
2771 // There is no more breakpoint on this method: we need to undeoptimize.
2772 if (need_full_deoptimization) {
2773 // This method required full deoptimization: we need to undeoptimize everything.
2774 req->kind = DeoptimizationRequest::kFullUndeoptimization;
2775 req->method = nullptr;
2776 } else {
2777 // This method required selective deoptimization: we need to undeoptimize only that method.
2778 req->kind = DeoptimizationRequest::kSelectiveUndeoptimization;
2779 req->method = m;
2780 }
2781 } else {
2782 // There is at least one breakpoint for this method: we don't need to undeoptimize.
2783 req->kind = DeoptimizationRequest::kNothing;
2784 req->method = nullptr;
2785 SanityCheckExistingBreakpoints(m, need_full_deoptimization);
Elliott Hughes86964332012-02-15 19:37:42 -08002786 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002787}
2788
Jeff Hao449db332013-04-12 18:30:52 -07002789// Scoped utility class to suspend a thread so that we may do tasks such as walk its stack. Doesn't
2790// cause suspension if the thread is the current thread.
2791class ScopedThreadSuspension {
2792 public:
Ian Rogers33e95662013-05-20 20:29:14 -07002793 ScopedThreadSuspension(Thread* self, JDWP::ObjectId thread_id)
Sebastien Hertz52d131d2014-03-13 16:17:40 +01002794 LOCKS_EXCLUDED(Locks::thread_list_lock_)
Ian Rogers33e95662013-05-20 20:29:14 -07002795 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) :
Jeff Hao449db332013-04-12 18:30:52 -07002796 thread_(NULL),
2797 error_(JDWP::ERR_NONE),
2798 self_suspend_(false),
Ian Rogers33e95662013-05-20 20:29:14 -07002799 other_suspend_(false) {
Jeff Hao449db332013-04-12 18:30:52 -07002800 ScopedObjectAccessUnchecked soa(self);
2801 {
2802 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
2803 error_ = DecodeThread(soa, thread_id, thread_);
2804 }
2805 if (error_ == JDWP::ERR_NONE) {
2806 if (thread_ == soa.Self()) {
2807 self_suspend_ = true;
2808 } else {
2809 soa.Self()->TransitionFromRunnableToSuspended(kWaitingForDebuggerSuspension);
2810 jobject thread_peer = gRegistry->GetJObject(thread_id);
2811 bool timed_out;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07002812 Thread* suspended_thread = ThreadList::SuspendThreadByPeer(thread_peer, true, true,
2813 &timed_out);
Jeff Hao449db332013-04-12 18:30:52 -07002814 CHECK_EQ(soa.Self()->TransitionFromSuspendedToRunnable(), kWaitingForDebuggerSuspension);
2815 if (suspended_thread == NULL) {
2816 // Thread terminated from under us while suspending.
2817 error_ = JDWP::ERR_INVALID_THREAD;
2818 } else {
2819 CHECK_EQ(suspended_thread, thread_);
2820 other_suspend_ = true;
2821 }
2822 }
2823 }
Elliott Hughes2435a572012-02-17 16:07:41 -08002824 }
Elliott Hughes86964332012-02-15 19:37:42 -08002825
Jeff Hao449db332013-04-12 18:30:52 -07002826 Thread* GetThread() const {
2827 return thread_;
2828 }
2829
2830 JDWP::JdwpError GetError() const {
2831 return error_;
2832 }
2833
2834 ~ScopedThreadSuspension() {
2835 if (other_suspend_) {
2836 Runtime::Current()->GetThreadList()->Resume(thread_, true);
2837 }
2838 }
2839
2840 private:
2841 Thread* thread_;
2842 JDWP::JdwpError error_;
2843 bool self_suspend_;
2844 bool other_suspend_;
2845};
2846
2847JDWP::JdwpError Dbg::ConfigureStep(JDWP::ObjectId thread_id, JDWP::JdwpStepSize step_size,
2848 JDWP::JdwpStepDepth step_depth) {
2849 Thread* self = Thread::Current();
2850 ScopedThreadSuspension sts(self, thread_id);
2851 if (sts.GetError() != JDWP::ERR_NONE) {
2852 return sts.GetError();
2853 }
2854
Elliott Hughes2435a572012-02-17 16:07:41 -08002855 //
2856 // Work out what Method* we're in, the current line number, and how deep the stack currently
2857 // is for step-out.
2858 //
2859
Ian Rogers0399dde2012-06-06 17:09:28 -07002860 struct SingleStepStackVisitor : public StackVisitor {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002861 explicit SingleStepStackVisitor(Thread* thread, SingleStepControl* single_step_control,
2862 int32_t* line_number)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002863 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002864 : StackVisitor(thread, NULL), single_step_control_(single_step_control),
2865 line_number_(line_number) {
2866 DCHECK_EQ(single_step_control_, thread->GetSingleStepControl());
2867 single_step_control_->method = NULL;
2868 single_step_control_->stack_depth = 0;
Elliott Hughes86964332012-02-15 19:37:42 -08002869 }
Ian Rogersca190662012-06-26 15:45:57 -07002870
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002871 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2872 // annotalysis.
2873 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002874 mirror::ArtMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07002875 if (!m->IsRuntimeMethod()) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002876 ++single_step_control_->stack_depth;
2877 if (single_step_control_->method == NULL) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002878 mirror::DexCache* dex_cache = m->GetDeclaringClass()->GetDexCache();
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002879 single_step_control_->method = m;
2880 *line_number_ = -1;
Elliott Hughes2435a572012-02-17 16:07:41 -08002881 if (dex_cache != NULL) {
Ian Rogers4445a7e2012-10-05 17:19:13 -07002882 const DexFile& dex_file = *dex_cache->GetDexFile();
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002883 *line_number_ = dex_file.GetLineNumFromPC(m, GetDexPc());
Elliott Hughes2435a572012-02-17 16:07:41 -08002884 }
Elliott Hughes86964332012-02-15 19:37:42 -08002885 }
2886 }
Elliott Hughes530fa002012-03-12 11:44:49 -07002887 return true;
Elliott Hughes86964332012-02-15 19:37:42 -08002888 }
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002889
2890 SingleStepControl* const single_step_control_;
2891 int32_t* const line_number_;
Elliott Hughes86964332012-02-15 19:37:42 -08002892 };
Jeff Hao449db332013-04-12 18:30:52 -07002893
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002894 Thread* const thread = sts.GetThread();
2895 SingleStepControl* const single_step_control = thread->GetSingleStepControl();
2896 DCHECK(single_step_control != nullptr);
2897 int32_t line_number = -1;
2898 SingleStepStackVisitor visitor(thread, single_step_control, &line_number);
Ian Rogers0399dde2012-06-06 17:09:28 -07002899 visitor.WalkStack();
Elliott Hughes86964332012-02-15 19:37:42 -08002900
Elliott Hughes2435a572012-02-17 16:07:41 -08002901 //
2902 // Find the dex_pc values that correspond to the current line, for line-based single-stepping.
2903 //
2904
2905 struct DebugCallbackContext {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002906 explicit DebugCallbackContext(SingleStepControl* single_step_control, int32_t line_number)
2907 : single_step_control_(single_step_control), line_number_(line_number),
2908 last_pc_valid(false), last_pc(0) {
Elliott Hughes2435a572012-02-17 16:07:41 -08002909 }
2910
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002911 static bool Callback(void* raw_context, uint32_t address, uint32_t line_number) {
Elliott Hughes2435a572012-02-17 16:07:41 -08002912 DebugCallbackContext* context = reinterpret_cast<DebugCallbackContext*>(raw_context);
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002913 if (static_cast<int32_t>(line_number) == context->line_number_) {
Elliott Hughes2435a572012-02-17 16:07:41 -08002914 if (!context->last_pc_valid) {
2915 // Everything from this address until the next line change is ours.
2916 context->last_pc = address;
2917 context->last_pc_valid = true;
2918 }
2919 // Otherwise, if we're already in a valid range for this line,
2920 // just keep going (shouldn't really happen)...
Brian Carlstrom7934ac22013-07-26 10:54:15 -07002921 } else if (context->last_pc_valid) { // and the line number is new
Elliott Hughes2435a572012-02-17 16:07:41 -08002922 // Add everything from the last entry up until here to the set
2923 for (uint32_t dex_pc = context->last_pc; dex_pc < address; ++dex_pc) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002924 context->single_step_control_->dex_pcs.insert(dex_pc);
Elliott Hughes2435a572012-02-17 16:07:41 -08002925 }
2926 context->last_pc_valid = false;
2927 }
Brian Carlstrom7934ac22013-07-26 10:54:15 -07002928 return false; // There may be multiple entries for any given line.
Elliott Hughes2435a572012-02-17 16:07:41 -08002929 }
2930
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002931 ~DebugCallbackContext() {
Elliott Hughes2435a572012-02-17 16:07:41 -08002932 // If the line number was the last in the position table...
2933 if (last_pc_valid) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002934 size_t end = MethodHelper(single_step_control_->method).GetCodeItem()->insns_size_in_code_units_;
Elliott Hughes2435a572012-02-17 16:07:41 -08002935 for (uint32_t dex_pc = last_pc; dex_pc < end; ++dex_pc) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002936 single_step_control_->dex_pcs.insert(dex_pc);
Elliott Hughes2435a572012-02-17 16:07:41 -08002937 }
2938 }
2939 }
2940
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002941 SingleStepControl* const single_step_control_;
2942 const int32_t line_number_;
Elliott Hughes2435a572012-02-17 16:07:41 -08002943 bool last_pc_valid;
2944 uint32_t last_pc;
2945 };
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002946 single_step_control->dex_pcs.clear();
Ian Rogersef7d42f2014-01-06 12:55:46 -08002947 mirror::ArtMethod* m = single_step_control->method;
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002948 if (!m->IsNative()) {
2949 DebugCallbackContext context(single_step_control, line_number);
Elliott Hughes3e2e1a22012-02-21 11:33:41 -08002950 MethodHelper mh(m);
2951 mh.GetDexFile().DecodeDebugInfo(mh.GetCodeItem(), m->IsStatic(), m->GetDexMethodIndex(),
2952 DebugCallbackContext::Callback, NULL, &context);
2953 }
Elliott Hughes2435a572012-02-17 16:07:41 -08002954
2955 //
2956 // Everything else...
2957 //
2958
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002959 single_step_control->step_size = step_size;
2960 single_step_control->step_depth = step_depth;
2961 single_step_control->is_active = true;
Elliott Hughes86964332012-02-15 19:37:42 -08002962
Elliott Hughes2435a572012-02-17 16:07:41 -08002963 if (VLOG_IS_ON(jdwp)) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002964 VLOG(jdwp) << "Single-step thread: " << *thread;
2965 VLOG(jdwp) << "Single-step step size: " << single_step_control->step_size;
2966 VLOG(jdwp) << "Single-step step depth: " << single_step_control->step_depth;
2967 VLOG(jdwp) << "Single-step current method: " << PrettyMethod(single_step_control->method);
2968 VLOG(jdwp) << "Single-step current line: " << line_number;
2969 VLOG(jdwp) << "Single-step current stack depth: " << single_step_control->stack_depth;
Elliott Hughes2435a572012-02-17 16:07:41 -08002970 VLOG(jdwp) << "Single-step dex_pc values:";
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002971 for (std::set<uint32_t>::iterator it = single_step_control->dex_pcs.begin(); it != single_step_control->dex_pcs.end(); ++it) {
Elliott Hughes229feb72012-02-23 13:33:29 -08002972 VLOG(jdwp) << StringPrintf(" %#x", *it);
Elliott Hughes2435a572012-02-17 16:07:41 -08002973 }
2974 }
2975
2976 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002977}
2978
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002979void Dbg::UnconfigureStep(JDWP::ObjectId thread_id) {
2980 ScopedObjectAccessUnchecked soa(Thread::Current());
2981 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
2982 Thread* thread;
2983 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
Sebastien Hertz87118ed2013-11-26 17:57:18 +01002984 if (error == JDWP::ERR_NONE) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002985 SingleStepControl* single_step_control = thread->GetSingleStepControl();
2986 DCHECK(single_step_control != nullptr);
2987 single_step_control->is_active = false;
2988 single_step_control->dex_pcs.clear();
2989 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002990}
2991
Elliott Hughes45651fd2012-02-21 15:48:20 -08002992static char JdwpTagToShortyChar(JDWP::JdwpTag tag) {
2993 switch (tag) {
2994 default:
2995 LOG(FATAL) << "unknown JDWP tag: " << PrintableChar(tag);
2996
2997 // Primitives.
2998 case JDWP::JT_BYTE: return 'B';
2999 case JDWP::JT_CHAR: return 'C';
3000 case JDWP::JT_FLOAT: return 'F';
3001 case JDWP::JT_DOUBLE: return 'D';
3002 case JDWP::JT_INT: return 'I';
3003 case JDWP::JT_LONG: return 'J';
3004 case JDWP::JT_SHORT: return 'S';
3005 case JDWP::JT_VOID: return 'V';
3006 case JDWP::JT_BOOLEAN: return 'Z';
3007
3008 // Reference types.
3009 case JDWP::JT_ARRAY:
3010 case JDWP::JT_OBJECT:
3011 case JDWP::JT_STRING:
3012 case JDWP::JT_THREAD:
3013 case JDWP::JT_THREAD_GROUP:
3014 case JDWP::JT_CLASS_LOADER:
3015 case JDWP::JT_CLASS_OBJECT:
3016 return 'L';
3017 }
3018}
3019
Elliott Hughes88d63092013-01-09 09:55:54 -08003020JDWP::JdwpError Dbg::InvokeMethod(JDWP::ObjectId thread_id, JDWP::ObjectId object_id,
3021 JDWP::RefTypeId class_id, JDWP::MethodId method_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003022 uint32_t arg_count, uint64_t* arg_values,
3023 JDWP::JdwpTag* arg_types, uint32_t options,
3024 JDWP::JdwpTag* pResultTag, uint64_t* pResultValue,
3025 JDWP::ObjectId* pExceptionId) {
Elliott Hughesd07986f2011-12-06 18:27:45 -08003026 ThreadList* thread_list = Runtime::Current()->GetThreadList();
3027
3028 Thread* targetThread = NULL;
3029 DebugInvokeReq* req = NULL;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003030 Thread* self = Thread::Current();
Elliott Hughesd07986f2011-12-06 18:27:45 -08003031 {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003032 ScopedObjectAccessUnchecked soa(self);
Ian Rogers50b35e22012-10-04 10:09:15 -07003033 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08003034 JDWP::JdwpError error = DecodeThread(soa, thread_id, targetThread);
3035 if (error != JDWP::ERR_NONE) {
3036 LOG(ERROR) << "InvokeMethod request for invalid thread id " << thread_id;
3037 return error;
Elliott Hughesd07986f2011-12-06 18:27:45 -08003038 }
3039 req = targetThread->GetInvokeReq();
3040 if (!req->ready) {
3041 LOG(ERROR) << "InvokeMethod request for thread not stopped by event: " << *targetThread;
3042 return JDWP::ERR_INVALID_THREAD;
3043 }
3044
3045 /*
3046 * We currently have a bug where we don't successfully resume the
3047 * target thread if the suspend count is too deep. We're expected to
3048 * require one "resume" for each "suspend", but when asked to execute
3049 * a method we have to resume fully and then re-suspend it back to the
3050 * same level. (The easiest way to cause this is to type "suspend"
3051 * multiple times in jdb.)
3052 *
3053 * It's unclear what this means when the event specifies "resume all"
3054 * and some threads are suspended more deeply than others. This is
3055 * a rare problem, so for now we just prevent it from hanging forever
3056 * by rejecting the method invocation request. Without this, we will
3057 * be stuck waiting on a suspended thread.
3058 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003059 int suspend_count;
3060 {
Ian Rogers50b35e22012-10-04 10:09:15 -07003061 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003062 suspend_count = targetThread->GetSuspendCount();
3063 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08003064 if (suspend_count > 1) {
3065 LOG(ERROR) << *targetThread << " suspend count too deep for method invocation: " << suspend_count;
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003066 return JDWP::ERR_THREAD_SUSPENDED; // Probably not expected here.
Elliott Hughesd07986f2011-12-06 18:27:45 -08003067 }
3068
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08003069 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003070 mirror::Object* receiver = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08003071 if (receiver == ObjectRegistry::kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08003072 return JDWP::ERR_INVALID_OBJECT;
3073 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003074
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003075 mirror::Object* thread = gRegistry->Get<mirror::Object*>(thread_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08003076 if (thread == ObjectRegistry::kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08003077 return JDWP::ERR_INVALID_OBJECT;
3078 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003079 // TODO: check that 'thread' is actually a java.lang.Thread!
3080
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003081 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes45651fd2012-02-21 15:48:20 -08003082 if (c == NULL) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08003083 return status;
3084 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003085
Brian Carlstromea46f952013-07-30 01:26:50 -07003086 mirror::ArtMethod* m = FromMethodId(method_id);
Elliott Hughes45651fd2012-02-21 15:48:20 -08003087 if (m->IsStatic() != (receiver == NULL)) {
3088 return JDWP::ERR_INVALID_METHODID;
3089 }
3090 if (m->IsStatic()) {
3091 if (m->GetDeclaringClass() != c) {
3092 return JDWP::ERR_INVALID_METHODID;
3093 }
3094 } else {
3095 if (!m->GetDeclaringClass()->IsAssignableFrom(c)) {
3096 return JDWP::ERR_INVALID_METHODID;
3097 }
3098 }
3099
3100 // Check the argument list matches the method.
3101 MethodHelper mh(m);
3102 if (mh.GetShortyLength() - 1 != arg_count) {
3103 return JDWP::ERR_ILLEGAL_ARGUMENT;
3104 }
3105 const char* shorty = mh.GetShorty();
Elliott Hughes09201632013-04-15 15:50:07 -07003106 const DexFile::TypeList* types = mh.GetParameterTypeList();
Elliott Hughes45651fd2012-02-21 15:48:20 -08003107 for (size_t i = 0; i < arg_count; ++i) {
3108 if (shorty[i + 1] != JdwpTagToShortyChar(arg_types[i])) {
3109 return JDWP::ERR_ILLEGAL_ARGUMENT;
3110 }
Elliott Hughes09201632013-04-15 15:50:07 -07003111
3112 if (shorty[i + 1] == 'L') {
3113 // Did we really get an argument of an appropriate reference type?
3114 mirror::Class* parameter_type = mh.GetClassFromTypeIdx(types->GetTypeItem(i).type_idx_);
3115 mirror::Object* argument = gRegistry->Get<mirror::Object*>(arg_values[i]);
3116 if (argument == ObjectRegistry::kInvalidObject) {
3117 return JDWP::ERR_INVALID_OBJECT;
3118 }
Sebastien Hertz0630ab52013-11-28 18:53:35 +01003119 if (argument != NULL && !argument->InstanceOf(parameter_type)) {
Elliott Hughes09201632013-04-15 15:50:07 -07003120 return JDWP::ERR_ILLEGAL_ARGUMENT;
3121 }
3122
3123 // Turn the on-the-wire ObjectId into a jobject.
3124 jvalue& v = reinterpret_cast<jvalue&>(arg_values[i]);
3125 v.l = gRegistry->GetJObject(arg_values[i]);
3126 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003127 }
3128
Sebastien Hertzd38667a2013-11-25 15:43:54 +01003129 req->receiver = receiver;
3130 req->thread = thread;
3131 req->klass = c;
3132 req->method = m;
3133 req->arg_count = arg_count;
3134 req->arg_values = arg_values;
3135 req->options = options;
3136 req->invoke_needed = true;
Elliott Hughesd07986f2011-12-06 18:27:45 -08003137 }
3138
3139 // The fact that we've released the thread list lock is a bit risky --- if the thread goes
3140 // away we're sitting high and dry -- but we must release this before the ResumeAllThreads
3141 // call, and it's unwise to hold it during WaitForSuspend.
3142
3143 {
3144 /*
3145 * We change our (JDWP thread) status, which should be THREAD_RUNNING,
Elliott Hughes81ff3182012-03-23 20:35:56 -07003146 * so we can suspend for a GC if the invoke request causes us to
Elliott Hughesd07986f2011-12-06 18:27:45 -08003147 * run out of memory. It's also a good idea to change it before locking
3148 * the invokeReq mutex, although that should never be held for long.
3149 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003150 self->TransitionFromRunnableToSuspended(kWaitingForDebuggerSend);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003151
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003152 VLOG(jdwp) << " Transferring control to event thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08003153 {
Sebastien Hertzd38667a2013-11-25 15:43:54 +01003154 MutexLock mu(self, req->lock);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003155
3156 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003157 VLOG(jdwp) << " Resuming all threads";
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003158 thread_list->UndoDebuggerSuspensions();
Elliott Hughesd07986f2011-12-06 18:27:45 -08003159 } else {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003160 VLOG(jdwp) << " Resuming event thread only";
Elliott Hughesd07986f2011-12-06 18:27:45 -08003161 thread_list->Resume(targetThread, true);
3162 }
3163
3164 // Wait for the request to finish executing.
Sebastien Hertzd38667a2013-11-25 15:43:54 +01003165 while (req->invoke_needed) {
3166 req->cond.Wait(self);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003167 }
3168 }
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003169 VLOG(jdwp) << " Control has returned from event thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08003170
3171 /* wait for thread to re-suspend itself */
Brian Carlstromdf629502013-07-17 22:39:56 -07003172 SuspendThread(thread_id, false /* request_suspension */);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003173 self->TransitionFromSuspendedToRunnable();
Elliott Hughesd07986f2011-12-06 18:27:45 -08003174 }
3175
3176 /*
3177 * Suspend the threads. We waited for the target thread to suspend
3178 * itself, so all we need to do is suspend the others.
3179 *
3180 * The suspendAllThreads() call will double-suspend the event thread,
3181 * so we want to resume the target thread once to keep the books straight.
3182 */
3183 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003184 self->TransitionFromRunnableToSuspended(kWaitingForDebuggerSuspension);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003185 VLOG(jdwp) << " Suspending all threads";
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003186 thread_list->SuspendAllForDebugger();
3187 self->TransitionFromSuspendedToRunnable();
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003188 VLOG(jdwp) << " Resuming event thread to balance the count";
Elliott Hughesd07986f2011-12-06 18:27:45 -08003189 thread_list->Resume(targetThread, true);
3190 }
3191
3192 // Copy the result.
3193 *pResultTag = req->result_tag;
3194 if (IsPrimitiveTag(req->result_tag)) {
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07003195 *pResultValue = req->result_value.GetJ();
Elliott Hughesd07986f2011-12-06 18:27:45 -08003196 } else {
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07003197 *pResultValue = gRegistry->Add(req->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003198 }
3199 *pExceptionId = req->exception;
3200 return req->error;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003201}
3202
3203void Dbg::ExecuteMethod(DebugInvokeReq* pReq) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003204 ScopedObjectAccess soa(Thread::Current());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003205
Elliott Hughes81ff3182012-03-23 20:35:56 -07003206 // We can be called while an exception is pending. We need
Elliott Hughesd07986f2011-12-06 18:27:45 -08003207 // to preserve that across the method invocation.
Ian Rogers62d6c772013-02-27 08:32:07 -08003208 SirtRef<mirror::Object> old_throw_this_object(soa.Self(), NULL);
Brian Carlstromea46f952013-07-30 01:26:50 -07003209 SirtRef<mirror::ArtMethod> old_throw_method(soa.Self(), NULL);
Ian Rogers62d6c772013-02-27 08:32:07 -08003210 SirtRef<mirror::Throwable> old_exception(soa.Self(), NULL);
3211 uint32_t old_throw_dex_pc;
3212 {
3213 ThrowLocation old_throw_location;
3214 mirror::Throwable* old_exception_obj = soa.Self()->GetException(&old_throw_location);
3215 old_throw_this_object.reset(old_throw_location.GetThis());
3216 old_throw_method.reset(old_throw_location.GetMethod());
3217 old_exception.reset(old_exception_obj);
3218 old_throw_dex_pc = old_throw_location.GetDexPc();
3219 soa.Self()->ClearException();
3220 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08003221
3222 // Translate the method through the vtable, unless the debugger wants to suppress it.
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003223 SirtRef<mirror::ArtMethod> m(soa.Self(), pReq->method);
Sebastien Hertzd38667a2013-11-25 15:43:54 +01003224 if ((pReq->options & JDWP::INVOKE_NONVIRTUAL) == 0 && pReq->receiver != NULL) {
Sebastien Hertz83a47d82014-03-20 09:57:40 +01003225 mirror::ArtMethod* actual_method = pReq->klass->FindVirtualMethodForVirtualOrInterface(m.get());
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003226 if (actual_method != m.get()) {
3227 VLOG(jdwp) << "ExecuteMethod translated " << PrettyMethod(m.get()) << " to " << PrettyMethod(actual_method);
3228 m.reset(actual_method);
Elliott Hughes45651fd2012-02-21 15:48:20 -08003229 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08003230 }
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003231 VLOG(jdwp) << "ExecuteMethod " << PrettyMethod(m.get())
Sebastien Hertzd38667a2013-11-25 15:43:54 +01003232 << " receiver=" << pReq->receiver
3233 << " arg_count=" << pReq->arg_count;
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003234 CHECK(m.get() != nullptr);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003235
3236 CHECK_EQ(sizeof(jvalue), sizeof(uint64_t));
3237
Sebastien Hertz83a47d82014-03-20 09:57:40 +01003238 pReq->result_value = InvokeWithJValues(soa, pReq->receiver, soa.EncodeMethod(m.get()),
Ian Rogers53b8b092014-03-13 23:45:53 -07003239 reinterpret_cast<jvalue*>(pReq->arg_values));
Elliott Hughesd07986f2011-12-06 18:27:45 -08003240
Ian Rogers62d6c772013-02-27 08:32:07 -08003241 mirror::Throwable* exception = soa.Self()->GetException(NULL);
3242 soa.Self()->ClearException();
3243 pReq->exception = gRegistry->Add(exception);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003244 pReq->result_tag = BasicTagFromDescriptor(MethodHelper(m.get()).GetShorty());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003245 if (pReq->exception != 0) {
Ian Rogers62d6c772013-02-27 08:32:07 -08003246 VLOG(jdwp) << " JDWP invocation returning with exception=" << exception
3247 << " " << exception->Dump();
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07003248 pReq->result_value.SetJ(0);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003249 } else if (pReq->result_tag == JDWP::JT_OBJECT) {
3250 /* if no exception thrown, examine object result more closely */
Ian Rogers98379392014-02-24 16:53:16 -08003251 JDWP::JdwpTag new_tag = TagFromObject(soa, pReq->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003252 if (new_tag != pReq->result_tag) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003253 VLOG(jdwp) << " JDWP promoted result from " << pReq->result_tag << " to " << new_tag;
Elliott Hughesd07986f2011-12-06 18:27:45 -08003254 pReq->result_tag = new_tag;
3255 }
3256
3257 /*
3258 * Register the object. We don't actually need an ObjectId yet,
3259 * but we do need to be sure that the GC won't move or discard the
3260 * object when we switch out of RUNNING. The ObjectId conversion
3261 * will add the object to the "do not touch" list.
3262 *
3263 * We can't use the "tracked allocation" mechanism here because
3264 * the object is going to be handed off to a different thread.
3265 */
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07003266 gRegistry->Add(pReq->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003267 }
3268
3269 if (old_exception.get() != NULL) {
Ian Rogers62d6c772013-02-27 08:32:07 -08003270 ThrowLocation gc_safe_throw_location(old_throw_this_object.get(), old_throw_method.get(),
3271 old_throw_dex_pc);
3272 soa.Self()->SetException(gc_safe_throw_location, old_exception.get());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003273 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003274}
3275
Elliott Hughesd07986f2011-12-06 18:27:45 -08003276/*
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003277 * "request" contains a full JDWP packet, possibly with multiple chunks. We
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003278 * need to process each, accumulate the replies, and ship the whole thing
3279 * back.
3280 *
3281 * Returns "true" if we have a reply. The reply buffer is newly allocated,
3282 * and includes the chunk type/length, followed by the data.
3283 *
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08003284 * OLD-TODO: we currently assume that the request and reply include a single
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003285 * chunk. If this becomes inconvenient we will need to adapt.
3286 */
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003287bool Dbg::DdmHandlePacket(JDWP::Request& request, uint8_t** pReplyBuf, int* pReplyLen) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003288 Thread* self = Thread::Current();
3289 JNIEnv* env = self->GetJniEnv();
3290
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003291 uint32_t type = request.ReadUnsigned32("type");
3292 uint32_t length = request.ReadUnsigned32("length");
3293
3294 // Create a byte[] corresponding to 'request'.
3295 size_t request_length = request.size();
3296 ScopedLocalRef<jbyteArray> dataArray(env, env->NewByteArray(request_length));
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003297 if (dataArray.get() == NULL) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003298 LOG(WARNING) << "byte[] allocation failed: " << request_length;
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003299 env->ExceptionClear();
3300 return false;
3301 }
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003302 env->SetByteArrayRegion(dataArray.get(), 0, request_length, reinterpret_cast<const jbyte*>(request.data()));
3303 request.Skip(request_length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003304
3305 // Run through and find all chunks. [Currently just find the first.]
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003306 ScopedByteArrayRO contents(env, dataArray.get());
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003307 if (length != request_length) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08003308 LOG(WARNING) << StringPrintf("bad chunk found (len=%u pktLen=%zd)", length, request_length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003309 return false;
3310 }
3311
3312 // Call "private static Chunk dispatch(int type, byte[] data, int offset, int length)".
Elliott Hugheseac76672012-05-24 21:56:51 -07003313 ScopedLocalRef<jobject> chunk(env, env->CallStaticObjectMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
3314 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_dispatch,
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003315 type, dataArray.get(), 0, length));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003316 if (env->ExceptionCheck()) {
3317 LOG(INFO) << StringPrintf("Exception thrown by dispatcher for 0x%08x", type);
3318 env->ExceptionDescribe();
3319 env->ExceptionClear();
3320 return false;
3321 }
3322
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003323 if (chunk.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003324 return false;
3325 }
3326
3327 /*
3328 * Pull the pieces out of the chunk. We copy the results into a
3329 * newly-allocated buffer that the caller can free. We don't want to
3330 * continue using the Chunk object because nothing has a reference to it.
3331 *
3332 * We could avoid this by returning type/data/offset/length and having
3333 * the caller be aware of the object lifetime issues, but that
Elliott Hughes81ff3182012-03-23 20:35:56 -07003334 * integrates the JDWP code more tightly into the rest of the runtime, and doesn't work
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003335 * if we have responses for multiple chunks.
3336 *
3337 * So we're pretty much stuck with copying data around multiple times.
3338 */
Elliott Hugheseac76672012-05-24 21:56:51 -07003339 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 -08003340 jint offset = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_offset);
Elliott Hugheseac76672012-05-24 21:56:51 -07003341 length = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_length);
Elliott Hugheseac76672012-05-24 21:56:51 -07003342 type = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_type);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003343
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003344 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 -07003345 if (length == 0 || replyData.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003346 return false;
3347 }
3348
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003349 const int kChunkHdrLen = 8;
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003350 uint8_t* reply = new uint8_t[length + kChunkHdrLen];
3351 if (reply == NULL) {
3352 LOG(WARNING) << "malloc failed: " << (length + kChunkHdrLen);
3353 return false;
3354 }
Elliott Hughesf7c3b662011-10-27 12:04:56 -07003355 JDWP::Set4BE(reply + 0, type);
3356 JDWP::Set4BE(reply + 4, length);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003357 env->GetByteArrayRegion(replyData.get(), offset, length, reinterpret_cast<jbyte*>(reply + kChunkHdrLen));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003358
3359 *pReplyBuf = reply;
3360 *pReplyLen = length + kChunkHdrLen;
3361
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003362 VLOG(jdwp) << StringPrintf("dvmHandleDdm returning type=%.4s %p len=%d", reinterpret_cast<char*>(reply), reply, length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003363 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003364}
3365
Elliott Hughesa2155262011-11-16 16:26:58 -08003366void Dbg::DdmBroadcast(bool connect) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003367 VLOG(jdwp) << "Broadcasting DDM " << (connect ? "connect" : "disconnect") << "...";
Elliott Hughes47fce012011-10-25 18:37:19 -07003368
3369 Thread* self = Thread::Current();
Ian Rogers50b35e22012-10-04 10:09:15 -07003370 if (self->GetState() != kRunnable) {
3371 LOG(ERROR) << "DDM broadcast in thread state " << self->GetState();
3372 /* try anyway? */
Elliott Hughes47fce012011-10-25 18:37:19 -07003373 }
3374
3375 JNIEnv* env = self->GetJniEnv();
Elliott Hughes47fce012011-10-25 18:37:19 -07003376 jint event = connect ? 1 /*DdmServer.CONNECTED*/ : 2 /*DdmServer.DISCONNECTED*/;
Elliott Hugheseac76672012-05-24 21:56:51 -07003377 env->CallStaticVoidMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
3378 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_broadcast,
3379 event);
Elliott Hughes47fce012011-10-25 18:37:19 -07003380 if (env->ExceptionCheck()) {
3381 LOG(ERROR) << "DdmServer.broadcast " << event << " failed";
3382 env->ExceptionDescribe();
3383 env->ExceptionClear();
3384 }
3385}
3386
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003387void Dbg::DdmConnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08003388 Dbg::DdmBroadcast(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003389}
3390
3391void Dbg::DdmDisconnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08003392 Dbg::DdmBroadcast(false);
Elliott Hughes47fce012011-10-25 18:37:19 -07003393 gDdmThreadNotification = false;
3394}
3395
3396/*
Elliott Hughes82188472011-11-07 18:11:48 -08003397 * Send a notification when a thread starts, stops, or changes its name.
Elliott Hughes47fce012011-10-25 18:37:19 -07003398 *
3399 * Because we broadcast the full set of threads when the notifications are
3400 * first enabled, it's possible for "thread" to be actively executing.
3401 */
Elliott Hughes82188472011-11-07 18:11:48 -08003402void Dbg::DdmSendThreadNotification(Thread* t, uint32_t type) {
Elliott Hughes47fce012011-10-25 18:37:19 -07003403 if (!gDdmThreadNotification) {
3404 return;
3405 }
3406
Elliott Hughes82188472011-11-07 18:11:48 -08003407 if (type == CHUNK_TYPE("THDE")) {
Elliott Hughes47fce012011-10-25 18:37:19 -07003408 uint8_t buf[4];
Ian Rogersd9c4fc92013-10-01 19:45:43 -07003409 JDWP::Set4BE(&buf[0], t->GetThreadId());
Elliott Hughes47fce012011-10-25 18:37:19 -07003410 Dbg::DdmSendChunk(CHUNK_TYPE("THDE"), 4, buf);
Elliott Hughes82188472011-11-07 18:11:48 -08003411 } else {
3412 CHECK(type == CHUNK_TYPE("THCR") || type == CHUNK_TYPE("THNM")) << type;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003413 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003414 SirtRef<mirror::String> name(soa.Self(), t->GetThreadName(soa));
Elliott Hughes82188472011-11-07 18:11:48 -08003415 size_t char_count = (name.get() != NULL) ? name->GetLength() : 0;
jeffhao725a9572012-11-13 18:20:12 -08003416 const jchar* chars = (name.get() != NULL) ? name->GetCharArray()->GetData() : NULL;
Elliott Hughes82188472011-11-07 18:11:48 -08003417
Elliott Hughes21f32d72011-11-09 17:44:13 -08003418 std::vector<uint8_t> bytes;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07003419 JDWP::Append4BE(bytes, t->GetThreadId());
Elliott Hughes545a0642011-11-08 19:10:03 -08003420 JDWP::AppendUtf16BE(bytes, chars, char_count);
Elliott Hughes21f32d72011-11-09 17:44:13 -08003421 CHECK_EQ(bytes.size(), char_count*2 + sizeof(uint32_t)*2);
3422 Dbg::DdmSendChunk(type, bytes);
Elliott Hughes47fce012011-10-25 18:37:19 -07003423 }
3424}
3425
Elliott Hughes47fce012011-10-25 18:37:19 -07003426void Dbg::DdmSetThreadNotification(bool enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003427 // Enable/disable thread notifications.
Elliott Hughes47fce012011-10-25 18:37:19 -07003428 gDdmThreadNotification = enable;
3429 if (enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003430 // Suspend the VM then post thread start notifications for all threads. Threads attaching will
3431 // see a suspension in progress and block until that ends. They then post their own start
3432 // notification.
3433 SuspendVM();
3434 std::list<Thread*> threads;
Ian Rogers50b35e22012-10-04 10:09:15 -07003435 Thread* self = Thread::Current();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003436 {
Ian Rogers50b35e22012-10-04 10:09:15 -07003437 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003438 threads = Runtime::Current()->GetThreadList()->GetList();
3439 }
3440 {
Ian Rogers50b35e22012-10-04 10:09:15 -07003441 ScopedObjectAccess soa(self);
Mathieu Chartier02e25112013-08-14 16:14:24 -07003442 for (Thread* thread : threads) {
3443 Dbg::DdmSendThreadNotification(thread, CHUNK_TYPE("THCR"));
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003444 }
3445 }
3446 ResumeVM();
Elliott Hughes47fce012011-10-25 18:37:19 -07003447 }
3448}
3449
Elliott Hughesa2155262011-11-16 16:26:58 -08003450void Dbg::PostThreadStartOrStop(Thread* t, uint32_t type) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07003451 if (IsDebuggerActive()) {
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07003452 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogerscfaa4552012-11-26 21:00:08 -08003453 JDWP::ObjectId id = gRegistry->Add(t->GetPeer());
Elliott Hughes82188472011-11-07 18:11:48 -08003454 gJdwpState->PostThreadChange(id, type == CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07003455 }
Elliott Hughes82188472011-11-07 18:11:48 -08003456 Dbg::DdmSendThreadNotification(t, type);
Elliott Hughes47fce012011-10-25 18:37:19 -07003457}
3458
3459void Dbg::PostThreadStart(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08003460 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07003461}
3462
3463void Dbg::PostThreadDeath(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08003464 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THDE"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003465}
3466
Elliott Hughes82188472011-11-07 18:11:48 -08003467void Dbg::DdmSendChunk(uint32_t type, size_t byte_count, const uint8_t* buf) {
Elliott Hughes3bb81562011-10-21 18:52:59 -07003468 CHECK(buf != NULL);
3469 iovec vec[1];
3470 vec[0].iov_base = reinterpret_cast<void*>(const_cast<uint8_t*>(buf));
3471 vec[0].iov_len = byte_count;
3472 Dbg::DdmSendChunkV(type, vec, 1);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003473}
3474
Elliott Hughes21f32d72011-11-09 17:44:13 -08003475void Dbg::DdmSendChunk(uint32_t type, const std::vector<uint8_t>& bytes) {
3476 DdmSendChunk(type, bytes.size(), &bytes[0]);
3477}
3478
Brian Carlstromf5293522013-07-19 00:24:00 -07003479void Dbg::DdmSendChunkV(uint32_t type, const iovec* iov, int iov_count) {
Elliott Hughes3bb81562011-10-21 18:52:59 -07003480 if (gJdwpState == NULL) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003481 VLOG(jdwp) << "Debugger thread not active, ignoring DDM send: " << type;
Elliott Hughes3bb81562011-10-21 18:52:59 -07003482 } else {
Elliott Hughescccd84f2011-12-05 16:51:54 -08003483 gJdwpState->DdmSendChunkV(type, iov, iov_count);
Elliott Hughes3bb81562011-10-21 18:52:59 -07003484 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003485}
3486
Elliott Hughes767a1472011-10-26 18:49:02 -07003487int Dbg::DdmHandleHpifChunk(HpifWhen when) {
3488 if (when == HPIF_WHEN_NOW) {
Elliott Hughes7162ad92011-10-27 14:08:42 -07003489 DdmSendHeapInfo(when);
Elliott Hughes767a1472011-10-26 18:49:02 -07003490 return true;
3491 }
3492
3493 if (when != HPIF_WHEN_NEVER && when != HPIF_WHEN_NEXT_GC && when != HPIF_WHEN_EVERY_GC) {
3494 LOG(ERROR) << "invalid HpifWhen value: " << static_cast<int>(when);
3495 return false;
3496 }
3497
3498 gDdmHpifWhen = when;
3499 return true;
3500}
3501
3502bool Dbg::DdmHandleHpsgNhsgChunk(Dbg::HpsgWhen when, Dbg::HpsgWhat what, bool native) {
3503 if (when != HPSG_WHEN_NEVER && when != HPSG_WHEN_EVERY_GC) {
3504 LOG(ERROR) << "invalid HpsgWhen value: " << static_cast<int>(when);
3505 return false;
3506 }
3507
3508 if (what != HPSG_WHAT_MERGED_OBJECTS && what != HPSG_WHAT_DISTINCT_OBJECTS) {
3509 LOG(ERROR) << "invalid HpsgWhat value: " << static_cast<int>(what);
3510 return false;
3511 }
3512
3513 if (native) {
3514 gDdmNhsgWhen = when;
3515 gDdmNhsgWhat = what;
3516 } else {
3517 gDdmHpsgWhen = when;
3518 gDdmHpsgWhat = what;
3519 }
3520 return true;
3521}
3522
Elliott Hughes7162ad92011-10-27 14:08:42 -07003523void Dbg::DdmSendHeapInfo(HpifWhen reason) {
3524 // If there's a one-shot 'when', reset it.
3525 if (reason == gDdmHpifWhen) {
3526 if (gDdmHpifWhen == HPIF_WHEN_NEXT_GC) {
3527 gDdmHpifWhen = HPIF_WHEN_NEVER;
3528 }
3529 }
3530
3531 /*
3532 * Chunk HPIF (client --> server)
3533 *
3534 * Heap Info. General information about the heap,
3535 * suitable for a summary display.
3536 *
3537 * [u4]: number of heaps
3538 *
3539 * For each heap:
3540 * [u4]: heap ID
3541 * [u8]: timestamp in ms since Unix epoch
3542 * [u1]: capture reason (same as 'when' value from server)
3543 * [u4]: max heap size in bytes (-Xmx)
3544 * [u4]: current heap size in bytes
3545 * [u4]: current number of bytes allocated
3546 * [u4]: current number of objects allocated
3547 */
3548 uint8_t heap_count = 1;
Ian Rogers1d54e732013-05-02 21:10:01 -07003549 gc::Heap* heap = Runtime::Current()->GetHeap();
Elliott Hughes21f32d72011-11-09 17:44:13 -08003550 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08003551 JDWP::Append4BE(bytes, heap_count);
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003552 JDWP::Append4BE(bytes, 1); // Heap id (bogus; we only have one heap).
Elliott Hughes545a0642011-11-08 19:10:03 -08003553 JDWP::Append8BE(bytes, MilliTime());
3554 JDWP::Append1BE(bytes, reason);
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003555 JDWP::Append4BE(bytes, heap->GetMaxMemory()); // Max allowed heap size in bytes.
3556 JDWP::Append4BE(bytes, heap->GetTotalMemory()); // Current heap size in bytes.
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08003557 JDWP::Append4BE(bytes, heap->GetBytesAllocated());
3558 JDWP::Append4BE(bytes, heap->GetObjectsAllocated());
Elliott Hughes21f32d72011-11-09 17:44:13 -08003559 CHECK_EQ(bytes.size(), 4U + (heap_count * (4 + 8 + 1 + 4 + 4 + 4 + 4)));
3560 Dbg::DdmSendChunk(CHUNK_TYPE("HPIF"), bytes);
Elliott Hughes767a1472011-10-26 18:49:02 -07003561}
3562
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003563enum HpsgSolidity {
3564 SOLIDITY_FREE = 0,
3565 SOLIDITY_HARD = 1,
3566 SOLIDITY_SOFT = 2,
3567 SOLIDITY_WEAK = 3,
3568 SOLIDITY_PHANTOM = 4,
3569 SOLIDITY_FINALIZABLE = 5,
3570 SOLIDITY_SWEEP = 6,
3571};
3572
3573enum HpsgKind {
3574 KIND_OBJECT = 0,
3575 KIND_CLASS_OBJECT = 1,
3576 KIND_ARRAY_1 = 2,
3577 KIND_ARRAY_2 = 3,
3578 KIND_ARRAY_4 = 4,
3579 KIND_ARRAY_8 = 5,
3580 KIND_UNKNOWN = 6,
3581 KIND_NATIVE = 7,
3582};
3583
3584#define HPSG_PARTIAL (1<<7)
3585#define HPSG_STATE(solidity, kind) ((uint8_t)((((kind) & 0x7) << 3) | ((solidity) & 0x7)))
3586
Ian Rogers30fab402012-01-23 15:43:46 -08003587class HeapChunkContext {
3588 public:
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003589 // Maximum chunk size. Obtain this from the formula:
3590 // (((maximum_heap_size / ALLOCATION_UNIT_SIZE) + 255) / 256) * 2
3591 HeapChunkContext(bool merge, bool native)
Ian Rogers30fab402012-01-23 15:43:46 -08003592 : buf_(16384 - 16),
3593 type_(0),
3594 merge_(merge) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003595 Reset();
3596 if (native) {
Ian Rogers30fab402012-01-23 15:43:46 -08003597 type_ = CHUNK_TYPE("NHSG");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003598 } else {
Ian Rogers30fab402012-01-23 15:43:46 -08003599 type_ = merge ? CHUNK_TYPE("HPSG") : CHUNK_TYPE("HPSO");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003600 }
3601 }
3602
3603 ~HeapChunkContext() {
Ian Rogers30fab402012-01-23 15:43:46 -08003604 if (p_ > &buf_[0]) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003605 Flush();
3606 }
3607 }
3608
3609 void EnsureHeader(const void* chunk_ptr) {
Ian Rogers30fab402012-01-23 15:43:46 -08003610 if (!needHeader_) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003611 return;
3612 }
3613
3614 // Start a new HPSx chunk.
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003615 JDWP::Write4BE(&p_, 1); // Heap id (bogus; we only have one heap).
3616 JDWP::Write1BE(&p_, 8); // Size of allocation unit, in bytes.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003617
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003618 JDWP::Write4BE(&p_, reinterpret_cast<uintptr_t>(chunk_ptr)); // virtual address of segment start.
3619 JDWP::Write4BE(&p_, 0); // offset of this piece (relative to the virtual address).
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003620 // [u4]: length of piece, in allocation units
3621 // 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 -08003622 pieceLenField_ = p_;
3623 JDWP::Write4BE(&p_, 0x55555555);
3624 needHeader_ = false;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003625 }
3626
Ian Rogersb726dcb2012-09-05 08:57:23 -07003627 void Flush() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogersd636b062013-01-18 17:51:18 -08003628 if (pieceLenField_ == NULL) {
3629 // Flush immediately post Reset (maybe back-to-back Flush). Ignore.
3630 CHECK(needHeader_);
3631 return;
3632 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003633 // Patch the "length of piece" field.
Ian Rogers30fab402012-01-23 15:43:46 -08003634 CHECK_LE(&buf_[0], pieceLenField_);
3635 CHECK_LE(pieceLenField_, p_);
3636 JDWP::Set4BE(pieceLenField_, totalAllocationUnits_);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003637
Ian Rogers30fab402012-01-23 15:43:46 -08003638 Dbg::DdmSendChunk(type_, p_ - &buf_[0], &buf_[0]);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003639 Reset();
3640 }
3641
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003642 static void HeapChunkCallback(void* start, void* end, size_t used_bytes, void* arg)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003643 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_,
3644 Locks::mutator_lock_) {
Ian Rogers30fab402012-01-23 15:43:46 -08003645 reinterpret_cast<HeapChunkContext*>(arg)->HeapChunkCallback(start, end, used_bytes);
Elliott Hughesa2155262011-11-16 16:26:58 -08003646 }
3647
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003648 private:
Elliott Hughesa2155262011-11-16 16:26:58 -08003649 enum { ALLOCATION_UNIT_SIZE = 8 };
3650
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003651 void Reset() {
Ian Rogers30fab402012-01-23 15:43:46 -08003652 p_ = &buf_[0];
Ian Rogers15bf2d32012-08-28 17:33:04 -07003653 startOfNextMemoryChunk_ = NULL;
Ian Rogers30fab402012-01-23 15:43:46 -08003654 totalAllocationUnits_ = 0;
3655 needHeader_ = true;
3656 pieceLenField_ = NULL;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003657 }
3658
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003659 void HeapChunkCallback(void* start, void* /*end*/, size_t used_bytes)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003660 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_,
3661 Locks::mutator_lock_) {
Ian Rogers30fab402012-01-23 15:43:46 -08003662 // Note: heap call backs cannot manipulate the heap upon which they are crawling, care is taken
3663 // in the following code not to allocate memory, by ensuring buf_ is of the correct size
Ian Rogers15bf2d32012-08-28 17:33:04 -07003664 if (used_bytes == 0) {
3665 if (start == NULL) {
3666 // Reset for start of new heap.
3667 startOfNextMemoryChunk_ = NULL;
3668 Flush();
3669 }
3670 // Only process in use memory so that free region information
3671 // also includes dlmalloc book keeping.
Elliott Hughesa2155262011-11-16 16:26:58 -08003672 return;
Elliott Hughesa2155262011-11-16 16:26:58 -08003673 }
3674
Ian Rogers15bf2d32012-08-28 17:33:04 -07003675 /* If we're looking at the native heap, we'll just return
3676 * (SOLIDITY_HARD, KIND_NATIVE) for all allocated chunks
3677 */
3678 bool native = type_ == CHUNK_TYPE("NHSG");
3679
3680 if (startOfNextMemoryChunk_ != NULL) {
3681 // Transmit any pending free memory. Native free memory of
3682 // over kMaxFreeLen could be because of the use of mmaps, so
3683 // don't report. If not free memory then start a new segment.
3684 bool flush = true;
3685 if (start > startOfNextMemoryChunk_) {
3686 const size_t kMaxFreeLen = 2 * kPageSize;
3687 void* freeStart = startOfNextMemoryChunk_;
3688 void* freeEnd = start;
Brian Carlstrom2d888622013-07-18 17:02:00 -07003689 size_t freeLen = reinterpret_cast<char*>(freeEnd) - reinterpret_cast<char*>(freeStart);
Ian Rogers15bf2d32012-08-28 17:33:04 -07003690 if (!native || freeLen < kMaxFreeLen) {
3691 AppendChunk(HPSG_STATE(SOLIDITY_FREE, 0), freeStart, freeLen);
3692 flush = false;
3693 }
3694 }
3695 if (flush) {
3696 startOfNextMemoryChunk_ = NULL;
3697 Flush();
3698 }
3699 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08003700 mirror::Object* obj = reinterpret_cast<mirror::Object*>(start);
Elliott Hughesa2155262011-11-16 16:26:58 -08003701
3702 // Determine the type of this chunk.
3703 // OLD-TODO: if context.merge, see if this chunk is different from the last chunk.
3704 // If it's the same, we should combine them.
Ian Rogers15bf2d32012-08-28 17:33:04 -07003705 uint8_t state = ExamineObject(obj, native);
3706 // dlmalloc's chunk header is 2 * sizeof(size_t), but if the previous chunk is in use for an
3707 // allocation then the first sizeof(size_t) may belong to it.
3708 const size_t dlMallocOverhead = sizeof(size_t);
3709 AppendChunk(state, start, used_bytes + dlMallocOverhead);
Brian Carlstrom2d888622013-07-18 17:02:00 -07003710 startOfNextMemoryChunk_ = reinterpret_cast<char*>(start) + used_bytes + dlMallocOverhead;
Ian Rogers15bf2d32012-08-28 17:33:04 -07003711 }
Elliott Hughesa2155262011-11-16 16:26:58 -08003712
Ian Rogers15bf2d32012-08-28 17:33:04 -07003713 void AppendChunk(uint8_t state, void* ptr, size_t length)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003714 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07003715 // Make sure there's enough room left in the buffer.
3716 // We need to use two bytes for every fractional 256 allocation units used by the chunk plus
3717 // 17 bytes for any header.
3718 size_t needed = (((length/ALLOCATION_UNIT_SIZE + 255) / 256) * 2) + 17;
3719 size_t bytesLeft = buf_.size() - (size_t)(p_ - &buf_[0]);
3720 if (bytesLeft < needed) {
3721 Flush();
3722 }
3723
3724 bytesLeft = buf_.size() - (size_t)(p_ - &buf_[0]);
3725 if (bytesLeft < needed) {
3726 LOG(WARNING) << "Chunk is too big to transmit (chunk_len=" << length << ", "
3727 << needed << " bytes)";
3728 return;
3729 }
3730 EnsureHeader(ptr);
Elliott Hughesa2155262011-11-16 16:26:58 -08003731 // Write out the chunk description.
Ian Rogers15bf2d32012-08-28 17:33:04 -07003732 length /= ALLOCATION_UNIT_SIZE; // Convert to allocation units.
3733 totalAllocationUnits_ += length;
3734 while (length > 256) {
Ian Rogers30fab402012-01-23 15:43:46 -08003735 *p_++ = state | HPSG_PARTIAL;
3736 *p_++ = 255; // length - 1
Ian Rogers15bf2d32012-08-28 17:33:04 -07003737 length -= 256;
Elliott Hughesa2155262011-11-16 16:26:58 -08003738 }
Ian Rogers30fab402012-01-23 15:43:46 -08003739 *p_++ = state;
Ian Rogers15bf2d32012-08-28 17:33:04 -07003740 *p_++ = length - 1;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003741 }
3742
Ian Rogersef7d42f2014-01-06 12:55:46 -08003743 uint8_t ExamineObject(mirror::Object* o, bool is_native_heap)
3744 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Elliott Hughesa2155262011-11-16 16:26:58 -08003745 if (o == NULL) {
3746 return HPSG_STATE(SOLIDITY_FREE, 0);
3747 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003748
Elliott Hughesa2155262011-11-16 16:26:58 -08003749 // It's an allocated chunk. Figure out what it is.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003750
Elliott Hughesa2155262011-11-16 16:26:58 -08003751 // If we're looking at the native heap, we'll just return
3752 // (SOLIDITY_HARD, KIND_NATIVE) for all allocated chunks.
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003753 if (is_native_heap) {
Elliott Hughesa2155262011-11-16 16:26:58 -08003754 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
3755 }
3756
Ian Rogers5bfa60f2012-09-02 21:17:56 -07003757 if (!Runtime::Current()->GetHeap()->IsLiveObjectLocked(o)) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07003758 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003759 }
3760
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003761 mirror::Class* c = o->GetClass();
Elliott Hughesa2155262011-11-16 16:26:58 -08003762 if (c == NULL) {
3763 // The object was probably just created but hasn't been initialized yet.
3764 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
3765 }
3766
Mathieu Chartier590fee92013-09-13 13:46:47 -07003767 if (!Runtime::Current()->GetHeap()->IsValidObjectAddress(c)) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07003768 LOG(ERROR) << "Invalid class for managed heap object: " << o << " " << c;
Elliott Hughesa2155262011-11-16 16:26:58 -08003769 return HPSG_STATE(SOLIDITY_HARD, KIND_UNKNOWN);
3770 }
3771
3772 if (c->IsClassClass()) {
3773 return HPSG_STATE(SOLIDITY_HARD, KIND_CLASS_OBJECT);
3774 }
3775
3776 if (c->IsArrayClass()) {
3777 if (o->IsObjectArray()) {
3778 return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
3779 }
3780 switch (c->GetComponentSize()) {
3781 case 1: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_1);
3782 case 2: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_2);
3783 case 4: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
3784 case 8: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_8);
3785 }
3786 }
3787
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003788 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
3789 }
3790
Ian Rogers30fab402012-01-23 15:43:46 -08003791 std::vector<uint8_t> buf_;
3792 uint8_t* p_;
3793 uint8_t* pieceLenField_;
Ian Rogers15bf2d32012-08-28 17:33:04 -07003794 void* startOfNextMemoryChunk_;
Ian Rogers30fab402012-01-23 15:43:46 -08003795 size_t totalAllocationUnits_;
3796 uint32_t type_;
3797 bool merge_;
3798 bool needHeader_;
3799
Elliott Hughesa2155262011-11-16 16:26:58 -08003800 DISALLOW_COPY_AND_ASSIGN(HeapChunkContext);
3801};
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003802
3803void Dbg::DdmSendHeapSegments(bool native) {
3804 Dbg::HpsgWhen when;
3805 Dbg::HpsgWhat what;
3806 if (!native) {
3807 when = gDdmHpsgWhen;
3808 what = gDdmHpsgWhat;
3809 } else {
3810 when = gDdmNhsgWhen;
3811 what = gDdmNhsgWhat;
3812 }
3813 if (when == HPSG_WHEN_NEVER) {
3814 return;
3815 }
3816
3817 // Figure out what kind of chunks we'll be sending.
3818 CHECK(what == HPSG_WHAT_MERGED_OBJECTS || what == HPSG_WHAT_DISTINCT_OBJECTS) << static_cast<int>(what);
3819
3820 // First, send a heap start chunk.
3821 uint8_t heap_id[4];
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003822 JDWP::Set4BE(&heap_id[0], 1); // Heap id (bogus; we only have one heap).
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003823 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHST") : CHUNK_TYPE("HPST"), sizeof(heap_id), heap_id);
3824
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07003825 Thread* self = Thread::Current();
3826
3827 // To allow the Walk/InspectAll() below to exclusively-lock the
3828 // mutator lock, temporarily release the shared access to the
3829 // mutator lock here by transitioning to the suspended state.
3830 Locks::mutator_lock_->AssertSharedHeld(self);
3831 self->TransitionFromRunnableToSuspended(kSuspended);
3832
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003833 // Send a series of heap segment chunks.
Elliott Hughesa2155262011-11-16 16:26:58 -08003834 HeapChunkContext context((what == HPSG_WHAT_MERGED_OBJECTS), native);
3835 if (native) {
Ian Rogers1d54e732013-05-02 21:10:01 -07003836 dlmalloc_inspect_all(HeapChunkContext::HeapChunkCallback, &context);
Elliott Hughesa2155262011-11-16 16:26:58 -08003837 } else {
Ian Rogers1d54e732013-05-02 21:10:01 -07003838 gc::Heap* heap = Runtime::Current()->GetHeap();
3839 const std::vector<gc::space::ContinuousSpace*>& spaces = heap->GetContinuousSpaces();
Ian Rogers62d6c772013-02-27 08:32:07 -08003840 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Ian Rogers1d54e732013-05-02 21:10:01 -07003841 typedef std::vector<gc::space::ContinuousSpace*>::const_iterator It;
3842 for (It cur = spaces.begin(), end = spaces.end(); cur != end; ++cur) {
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07003843 if ((*cur)->IsMallocSpace()) {
3844 (*cur)->AsMallocSpace()->Walk(HeapChunkContext::HeapChunkCallback, &context);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07003845 }
3846 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07003847 // Walk the large objects, these are not in the AllocSpace.
3848 heap->GetLargeObjectsSpace()->Walk(HeapChunkContext::HeapChunkCallback, &context);
Elliott Hughesa2155262011-11-16 16:26:58 -08003849 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003850
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07003851 // Shared-lock the mutator lock back.
3852 self->TransitionFromSuspendedToRunnable();
3853 Locks::mutator_lock_->AssertSharedHeld(self);
3854
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003855 // Finally, send a heap end chunk.
3856 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHEN") : CHUNK_TYPE("HPEN"), sizeof(heap_id), heap_id);
Elliott Hughes767a1472011-10-26 18:49:02 -07003857}
3858
Elliott Hughesb1a58792013-07-11 18:10:58 -07003859static size_t GetAllocTrackerMax() {
3860#ifdef HAVE_ANDROID_OS
3861 // Check whether there's a system property overriding the number of records.
3862 const char* propertyName = "dalvik.vm.allocTrackerMax";
3863 char allocRecordMaxString[PROPERTY_VALUE_MAX];
3864 if (property_get(propertyName, allocRecordMaxString, "") > 0) {
3865 char* end;
3866 size_t value = strtoul(allocRecordMaxString, &end, 10);
3867 if (*end != '\0') {
Ruben Brunk3e47a742013-09-09 17:56:07 -07003868 LOG(ERROR) << "Ignoring " << propertyName << " '" << allocRecordMaxString
3869 << "' --- invalid";
Elliott Hughesb1a58792013-07-11 18:10:58 -07003870 return kDefaultNumAllocRecords;
3871 }
3872 if (!IsPowerOfTwo(value)) {
Ruben Brunk3e47a742013-09-09 17:56:07 -07003873 LOG(ERROR) << "Ignoring " << propertyName << " '" << allocRecordMaxString
3874 << "' --- not power of two";
Elliott Hughesb1a58792013-07-11 18:10:58 -07003875 return kDefaultNumAllocRecords;
3876 }
3877 return value;
3878 }
3879#endif
3880 return kDefaultNumAllocRecords;
3881}
3882
Elliott Hughes545a0642011-11-08 19:10:03 -08003883void Dbg::SetAllocTrackingEnabled(bool enabled) {
Elliott Hughes545a0642011-11-08 19:10:03 -08003884 if (enabled) {
Sebastien Hertzb98063a2014-03-26 10:57:20 +01003885 {
3886 MutexLock mu(Thread::Current(), *alloc_tracker_lock_);
3887 if (recent_allocation_records_ == NULL) {
3888 alloc_record_max_ = GetAllocTrackerMax();
3889 LOG(INFO) << "Enabling alloc tracker (" << alloc_record_max_ << " entries of "
3890 << kMaxAllocRecordStackDepth << " frames, taking "
3891 << PrettySize(sizeof(AllocRecord) * alloc_record_max_) << ")";
3892 alloc_record_head_ = alloc_record_count_ = 0;
3893 recent_allocation_records_ = new AllocRecord[alloc_record_max_];
3894 CHECK(recent_allocation_records_ != NULL);
3895 }
Elliott Hughes545a0642011-11-08 19:10:03 -08003896 }
Ian Rogersfa824272013-11-05 16:12:57 -08003897 Runtime::Current()->GetInstrumentation()->InstrumentQuickAllocEntryPoints();
Elliott Hughes545a0642011-11-08 19:10:03 -08003898 } else {
Ian Rogersfa824272013-11-05 16:12:57 -08003899 Runtime::Current()->GetInstrumentation()->UninstrumentQuickAllocEntryPoints();
Sebastien Hertzb98063a2014-03-26 10:57:20 +01003900 {
3901 MutexLock mu(Thread::Current(), *alloc_tracker_lock_);
3902 delete[] recent_allocation_records_;
3903 recent_allocation_records_ = NULL;
3904 }
Elliott Hughes545a0642011-11-08 19:10:03 -08003905 }
3906}
3907
Ian Rogers0399dde2012-06-06 17:09:28 -07003908struct AllocRecordStackVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -08003909 AllocRecordStackVisitor(Thread* thread, AllocRecord* record)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003910 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08003911 : StackVisitor(thread, NULL), record(record), depth(0) {}
Elliott Hughes545a0642011-11-08 19:10:03 -08003912
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003913 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
3914 // annotalysis.
3915 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughes545a0642011-11-08 19:10:03 -08003916 if (depth >= kMaxAllocRecordStackDepth) {
Elliott Hughes530fa002012-03-12 11:44:49 -07003917 return false;
Elliott Hughes545a0642011-11-08 19:10:03 -08003918 }
Brian Carlstromea46f952013-07-30 01:26:50 -07003919 mirror::ArtMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07003920 if (!m->IsRuntimeMethod()) {
3921 record->stack[depth].method = m;
3922 record->stack[depth].dex_pc = GetDexPc();
Elliott Hughes530fa002012-03-12 11:44:49 -07003923 ++depth;
Elliott Hughes545a0642011-11-08 19:10:03 -08003924 }
Elliott Hughes530fa002012-03-12 11:44:49 -07003925 return true;
Elliott Hughes545a0642011-11-08 19:10:03 -08003926 }
3927
3928 ~AllocRecordStackVisitor() {
3929 // Clear out any unused stack trace elements.
3930 for (; depth < kMaxAllocRecordStackDepth; ++depth) {
3931 record->stack[depth].method = NULL;
Ian Rogers0399dde2012-06-06 17:09:28 -07003932 record->stack[depth].dex_pc = 0;
Elliott Hughes545a0642011-11-08 19:10:03 -08003933 }
3934 }
3935
3936 AllocRecord* record;
3937 size_t depth;
3938};
3939
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003940void Dbg::RecordAllocation(mirror::Class* type, size_t byte_count) {
Elliott Hughes545a0642011-11-08 19:10:03 -08003941 Thread* self = Thread::Current();
3942 CHECK(self != NULL);
3943
Ian Rogers719d1a32014-03-06 12:13:39 -08003944 MutexLock mu(self, *alloc_tracker_lock_);
Elliott Hughes545a0642011-11-08 19:10:03 -08003945 if (recent_allocation_records_ == NULL) {
3946 return;
3947 }
3948
3949 // Advance and clip.
Ian Rogers719d1a32014-03-06 12:13:39 -08003950 if (++alloc_record_head_ == alloc_record_max_) {
3951 alloc_record_head_ = 0;
Elliott Hughes545a0642011-11-08 19:10:03 -08003952 }
3953
3954 // Fill in the basics.
Ian Rogers719d1a32014-03-06 12:13:39 -08003955 AllocRecord* record = &recent_allocation_records_[alloc_record_head_];
Elliott Hughes545a0642011-11-08 19:10:03 -08003956 record->type = type;
3957 record->byte_count = byte_count;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07003958 record->thin_lock_id = self->GetThreadId();
Elliott Hughes545a0642011-11-08 19:10:03 -08003959
3960 // Fill in the stack trace.
Ian Rogers7a22fa62013-01-23 12:16:16 -08003961 AllocRecordStackVisitor visitor(self, record);
Ian Rogers0399dde2012-06-06 17:09:28 -07003962 visitor.WalkStack();
Elliott Hughes545a0642011-11-08 19:10:03 -08003963
Ian Rogers719d1a32014-03-06 12:13:39 -08003964 if (alloc_record_count_ < alloc_record_max_) {
3965 ++alloc_record_count_;
Elliott Hughes545a0642011-11-08 19:10:03 -08003966 }
3967}
3968
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003969// Returns the index of the head element.
3970//
3971// We point at the most-recently-written record, so if gAllocRecordCount is 1
3972// we want to use the current element. Take "head+1" and subtract count
3973// from it.
3974//
3975// We need to handle underflow in our circular buffer, so we add
Elliott Hughesb1a58792013-07-11 18:10:58 -07003976// gAllocRecordMax and then mask it back down.
Ian Rogers719d1a32014-03-06 12:13:39 -08003977size_t Dbg::HeadIndex() {
3978 return (Dbg::alloc_record_head_ + 1 + Dbg::alloc_record_max_ - Dbg::alloc_record_count_) &
3979 (Dbg::alloc_record_max_ - 1);
Elliott Hughes545a0642011-11-08 19:10:03 -08003980}
3981
3982void Dbg::DumpRecentAllocations() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003983 ScopedObjectAccess soa(Thread::Current());
Ian Rogers719d1a32014-03-06 12:13:39 -08003984 MutexLock mu(soa.Self(), *alloc_tracker_lock_);
Elliott Hughes545a0642011-11-08 19:10:03 -08003985 if (recent_allocation_records_ == NULL) {
3986 LOG(INFO) << "Not recording tracked allocations";
3987 return;
3988 }
3989
3990 // "i" is the head of the list. We want to start at the end of the
3991 // list and move forward to the tail.
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003992 size_t i = HeadIndex();
Ian Rogers719d1a32014-03-06 12:13:39 -08003993 size_t count = alloc_record_count_;
Elliott Hughes545a0642011-11-08 19:10:03 -08003994
Ian Rogers719d1a32014-03-06 12:13:39 -08003995 LOG(INFO) << "Tracked allocations, (head=" << alloc_record_head_ << " count=" << count << ")";
Elliott Hughes545a0642011-11-08 19:10:03 -08003996 while (count--) {
3997 AllocRecord* record = &recent_allocation_records_[i];
3998
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003999 LOG(INFO) << StringPrintf(" Thread %-2d %6zd bytes ", record->thin_lock_id, record->byte_count)
Elliott Hughes545a0642011-11-08 19:10:03 -08004000 << PrettyClass(record->type);
4001
4002 for (size_t stack_frame = 0; stack_frame < kMaxAllocRecordStackDepth; ++stack_frame) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08004003 mirror::ArtMethod* m = record->stack[stack_frame].method;
Elliott Hughes545a0642011-11-08 19:10:03 -08004004 if (m == NULL) {
4005 break;
4006 }
4007 LOG(INFO) << " " << PrettyMethod(m) << " line " << record->stack[stack_frame].LineNumber();
4008 }
4009
4010 // pause periodically to help logcat catch up
4011 if ((count % 5) == 0) {
4012 usleep(40000);
4013 }
4014
Ian Rogers719d1a32014-03-06 12:13:39 -08004015 i = (i + 1) & (alloc_record_max_ - 1);
Elliott Hughes545a0642011-11-08 19:10:03 -08004016 }
4017}
4018
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -07004019void Dbg::UpdateObjectPointers(IsMarkedCallback* callback, void* arg) {
Ian Rogers719d1a32014-03-06 12:13:39 -08004020 if (recent_allocation_records_ != nullptr) {
4021 MutexLock mu(Thread::Current(), *alloc_tracker_lock_);
4022 size_t i = HeadIndex();
4023 size_t count = alloc_record_count_;
4024 while (count--) {
4025 AllocRecord* record = &recent_allocation_records_[i];
4026 DCHECK(record != nullptr);
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -07004027 record->UpdateObjectPointers(callback, arg);
Ian Rogers719d1a32014-03-06 12:13:39 -08004028 i = (i + 1) & (alloc_record_max_ - 1);
Mathieu Chartier412c7fc2014-02-07 12:18:39 -08004029 }
4030 }
4031 if (gRegistry != nullptr) {
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -07004032 gRegistry->UpdateObjectPointers(callback, arg);
Mathieu Chartier412c7fc2014-02-07 12:18:39 -08004033 }
4034}
4035
4036void Dbg::AllowNewObjectRegistryObjects() {
4037 if (gRegistry != nullptr) {
4038 gRegistry->AllowNewObjects();
4039 }
4040}
4041
4042void Dbg::DisallowNewObjectRegistryObjects() {
4043 if (gRegistry != nullptr) {
4044 gRegistry->DisallowNewObjects();
4045 }
4046}
4047
Elliott Hughes545a0642011-11-08 19:10:03 -08004048class StringTable {
4049 public:
4050 StringTable() {
4051 }
4052
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004053 void Add(const char* s) {
Elliott Hughes545a0642011-11-08 19:10:03 -08004054 table_.insert(s);
4055 }
4056
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004057 size_t IndexOf(const char* s) const {
Mathieu Chartier02e25112013-08-14 16:14:24 -07004058 auto it = table_.find(s);
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004059 if (it == table_.end()) {
4060 LOG(FATAL) << "IndexOf(\"" << s << "\") failed";
4061 }
4062 return std::distance(table_.begin(), it);
Elliott Hughes545a0642011-11-08 19:10:03 -08004063 }
4064
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004065 size_t Size() const {
Elliott Hughes545a0642011-11-08 19:10:03 -08004066 return table_.size();
4067 }
4068
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004069 void WriteTo(std::vector<uint8_t>& bytes) const {
Mathieu Chartier02e25112013-08-14 16:14:24 -07004070 for (const std::string& str : table_) {
4071 const char* s = str.c_str();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004072 size_t s_len = CountModifiedUtf8Chars(s);
4073 UniquePtr<uint16_t> s_utf16(new uint16_t[s_len]);
4074 ConvertModifiedUtf8ToUtf16(s_utf16.get(), s);
4075 JDWP::AppendUtf16BE(bytes, s_utf16.get(), s_len);
Elliott Hughes545a0642011-11-08 19:10:03 -08004076 }
4077 }
4078
4079 private:
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004080 std::set<std::string> table_;
Elliott Hughes545a0642011-11-08 19:10:03 -08004081 DISALLOW_COPY_AND_ASSIGN(StringTable);
4082};
4083
4084/*
4085 * The data we send to DDMS contains everything we have recorded.
4086 *
4087 * Message header (all values big-endian):
4088 * (1b) message header len (to allow future expansion); includes itself
4089 * (1b) entry header len
4090 * (1b) stack frame len
4091 * (2b) number of entries
4092 * (4b) offset to string table from start of message
4093 * (2b) number of class name strings
4094 * (2b) number of method name strings
4095 * (2b) number of source file name strings
4096 * For each entry:
4097 * (4b) total allocation size
Elliott Hughes221229c2013-01-08 18:17:50 -08004098 * (2b) thread id
Elliott Hughes545a0642011-11-08 19:10:03 -08004099 * (2b) allocated object's class name index
4100 * (1b) stack depth
4101 * For each stack frame:
4102 * (2b) method's class name
4103 * (2b) method name
4104 * (2b) method source file
4105 * (2b) line number, clipped to 32767; -2 if native; -1 if no source
4106 * (xb) class name strings
4107 * (xb) method name strings
4108 * (xb) source file strings
4109 *
4110 * As with other DDM traffic, strings are sent as a 4-byte length
4111 * followed by UTF-16 data.
4112 *
4113 * We send up 16-bit unsigned indexes into string tables. In theory there
Elliott Hughesb1a58792013-07-11 18:10:58 -07004114 * can be (kMaxAllocRecordStackDepth * gAllocRecordMax) unique strings in
Elliott Hughes545a0642011-11-08 19:10:03 -08004115 * each table, but in practice there should be far fewer.
4116 *
4117 * The chief reason for using a string table here is to keep the size of
4118 * the DDMS message to a minimum. This is partly to make the protocol
4119 * efficient, but also because we have to form the whole thing up all at
4120 * once in a memory buffer.
4121 *
4122 * We use separate string tables for class names, method names, and source
4123 * files to keep the indexes small. There will generally be no overlap
4124 * between the contents of these tables.
4125 */
4126jbyteArray Dbg::GetRecentAllocations() {
4127 if (false) {
4128 DumpRecentAllocations();
4129 }
4130
Ian Rogers50b35e22012-10-04 10:09:15 -07004131 Thread* self = Thread::Current();
Elliott Hughes545a0642011-11-08 19:10:03 -08004132 std::vector<uint8_t> bytes;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004133 {
Ian Rogers719d1a32014-03-06 12:13:39 -08004134 MutexLock mu(self, *alloc_tracker_lock_);
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004135 //
4136 // Part 1: generate string tables.
4137 //
4138 StringTable class_names;
4139 StringTable method_names;
4140 StringTable filenames;
Elliott Hughes545a0642011-11-08 19:10:03 -08004141
Ian Rogers719d1a32014-03-06 12:13:39 -08004142 int count = alloc_record_count_;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004143 int idx = HeadIndex();
4144 while (count--) {
4145 AllocRecord* record = &recent_allocation_records_[idx];
Elliott Hughes545a0642011-11-08 19:10:03 -08004146
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004147 class_names.Add(ClassHelper(record->type).GetDescriptor());
Elliott Hughes545a0642011-11-08 19:10:03 -08004148
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004149 MethodHelper mh;
4150 for (size_t i = 0; i < kMaxAllocRecordStackDepth; i++) {
Brian Carlstromea46f952013-07-30 01:26:50 -07004151 mirror::ArtMethod* m = record->stack[i].method;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004152 if (m != NULL) {
4153 mh.ChangeMethod(m);
4154 class_names.Add(mh.GetDeclaringClassDescriptor());
4155 method_names.Add(mh.GetName());
4156 filenames.Add(mh.GetDeclaringClassSourceFile());
4157 }
4158 }
Elliott Hughes545a0642011-11-08 19:10:03 -08004159
Ian Rogers719d1a32014-03-06 12:13:39 -08004160 idx = (idx + 1) & (alloc_record_max_ - 1);
Elliott Hughes545a0642011-11-08 19:10:03 -08004161 }
4162
Ian Rogers719d1a32014-03-06 12:13:39 -08004163 LOG(INFO) << "allocation records: " << alloc_record_count_;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004164
4165 //
4166 // Part 2: Generate the output and store it in the buffer.
4167 //
4168
4169 // (1b) message header len (to allow future expansion); includes itself
4170 // (1b) entry header len
4171 // (1b) stack frame len
4172 const int kMessageHeaderLen = 15;
4173 const int kEntryHeaderLen = 9;
4174 const int kStackFrameLen = 8;
4175 JDWP::Append1BE(bytes, kMessageHeaderLen);
4176 JDWP::Append1BE(bytes, kEntryHeaderLen);
4177 JDWP::Append1BE(bytes, kStackFrameLen);
4178
4179 // (2b) number of entries
4180 // (4b) offset to string table from start of message
4181 // (2b) number of class name strings
4182 // (2b) number of method name strings
4183 // (2b) number of source file name strings
Ian Rogers719d1a32014-03-06 12:13:39 -08004184 JDWP::Append2BE(bytes, alloc_record_count_);
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004185 size_t string_table_offset = bytes.size();
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004186 JDWP::Append4BE(bytes, 0); // We'll patch this later...
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004187 JDWP::Append2BE(bytes, class_names.Size());
4188 JDWP::Append2BE(bytes, method_names.Size());
4189 JDWP::Append2BE(bytes, filenames.Size());
4190
Ian Rogers719d1a32014-03-06 12:13:39 -08004191 count = alloc_record_count_;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004192 idx = HeadIndex();
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004193 while (count--) {
4194 // For each entry:
4195 // (4b) total allocation size
4196 // (2b) thread id
4197 // (2b) allocated object's class name index
4198 // (1b) stack depth
4199 AllocRecord* record = &recent_allocation_records_[idx];
4200 size_t stack_depth = record->GetDepth();
Mathieu Chartier590fee92013-09-13 13:46:47 -07004201 ClassHelper kh(record->type);
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004202 size_t allocated_object_class_name_index = class_names.IndexOf(kh.GetDescriptor());
4203 JDWP::Append4BE(bytes, record->byte_count);
4204 JDWP::Append2BE(bytes, record->thin_lock_id);
4205 JDWP::Append2BE(bytes, allocated_object_class_name_index);
4206 JDWP::Append1BE(bytes, stack_depth);
4207
4208 MethodHelper mh;
4209 for (size_t stack_frame = 0; stack_frame < stack_depth; ++stack_frame) {
4210 // For each stack frame:
4211 // (2b) method's class name
4212 // (2b) method name
4213 // (2b) method source file
4214 // (2b) line number, clipped to 32767; -2 if native; -1 if no source
4215 mh.ChangeMethod(record->stack[stack_frame].method);
4216 size_t class_name_index = class_names.IndexOf(mh.GetDeclaringClassDescriptor());
4217 size_t method_name_index = method_names.IndexOf(mh.GetName());
4218 size_t file_name_index = filenames.IndexOf(mh.GetDeclaringClassSourceFile());
4219 JDWP::Append2BE(bytes, class_name_index);
4220 JDWP::Append2BE(bytes, method_name_index);
4221 JDWP::Append2BE(bytes, file_name_index);
4222 JDWP::Append2BE(bytes, record->stack[stack_frame].LineNumber());
4223 }
4224
Ian Rogers719d1a32014-03-06 12:13:39 -08004225 idx = (idx + 1) & (alloc_record_max_ - 1);
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004226 }
4227
4228 // (xb) class name strings
4229 // (xb) method name strings
4230 // (xb) source file strings
4231 JDWP::Set4BE(&bytes[string_table_offset], bytes.size());
4232 class_names.WriteTo(bytes);
4233 method_names.WriteTo(bytes);
4234 filenames.WriteTo(bytes);
Elliott Hughes545a0642011-11-08 19:10:03 -08004235 }
Ian Rogers50b35e22012-10-04 10:09:15 -07004236 JNIEnv* env = self->GetJniEnv();
Elliott Hughes545a0642011-11-08 19:10:03 -08004237 jbyteArray result = env->NewByteArray(bytes.size());
4238 if (result != NULL) {
4239 env->SetByteArrayRegion(result, 0, bytes.size(), reinterpret_cast<const jbyte*>(&bytes[0]));
4240 }
4241 return result;
4242}
4243
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004244} // namespace art