blob: 6dd2493e22e1c2d4813f3dc0496ab8e916913d88 [file] [log] [blame]
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "debugger.h"
18
Elliott Hughes3bb81562011-10-21 18:52:59 -070019#include <sys/uio.h>
20
Elliott Hughes545a0642011-11-08 19:10:03 -080021#include <set>
22
Ian Rogers166db042013-07-26 12:05:57 -070023#include "arch/context.h"
Elliott Hughes545a0642011-11-08 19:10:03 -080024#include "class_linker.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080025#include "class_linker-inl.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070026#include "dex_file-inl.h"
Ian Rogers776ac1f2012-04-13 23:36:36 -070027#include "dex_instruction.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070028#include "gc/accounting/card_table-inl.h"
29#include "gc/space/large_object_space.h"
30#include "gc/space/space-inl.h"
Elliott Hughes64f574f2013-02-20 14:57:12 -080031#include "jdwp/object_registry.h"
Brian Carlstromea46f952013-07-30 01:26:50 -070032#include "mirror/art_field-inl.h"
33#include "mirror/art_method-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080034#include "mirror/class.h"
35#include "mirror/class-inl.h"
36#include "mirror/class_loader.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080037#include "mirror/object-inl.h"
38#include "mirror/object_array-inl.h"
39#include "mirror/throwable.h"
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080040#include "object_utils.h"
Sebastien Hertza76a6d42014-03-20 16:40:17 +010041#include "quick/inline_method_analyser.h"
Ian Rogers53b8b092014-03-13 23:45:53 -070042#include "reflection.h"
Elliott Hughesa0e18062012-04-13 15:59:59 -070043#include "safe_map.h"
Elliott Hughes64f574f2013-02-20 14:57:12 -080044#include "scoped_thread_state_change.h"
Elliott Hughes6a5bd492011-10-28 14:33:57 -070045#include "ScopedLocalRef.h"
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -070046#include "ScopedPrimitiveArray.h"
Ian Rogers1f539342012-10-03 21:09:42 -070047#include "sirt_ref.h"
Elliott Hughes47fce012011-10-25 18:37:19 -070048#include "stack_indirect_reference_table.h"
Elliott Hughes475fc232011-10-25 15:00:35 -070049#include "thread_list.h"
Ian Rogers62d6c772013-02-27 08:32:07 -080050#include "throw_location.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080051#include "utf.h"
Sebastien Hertza76a6d42014-03-20 16:40:17 +010052#include "verifier/method_verifier-inl.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070053#include "well_known_classes.h"
Elliott Hughes475fc232011-10-25 15:00:35 -070054
Brian Carlstrom3d92d522013-07-12 09:03:08 -070055#ifdef HAVE_ANDROID_OS
56#include "cutils/properties.h"
57#endif
58
Elliott Hughes872d4ec2011-10-21 17:07:15 -070059namespace art {
60
Brian Carlstrom7934ac22013-07-26 10:54:15 -070061static const size_t kMaxAllocRecordStackDepth = 16; // Max 255.
62static const size_t kDefaultNumAllocRecords = 64*1024; // Must be a power of 2.
Elliott Hughes475fc232011-10-25 15:00:35 -070063
Elliott Hughes545a0642011-11-08 19:10:03 -080064struct AllocRecordStackTraceElement {
Brian Carlstromea46f952013-07-30 01:26:50 -070065 mirror::ArtMethod* method;
Ian Rogers0399dde2012-06-06 17:09:28 -070066 uint32_t dex_pc;
Elliott Hughes545a0642011-11-08 19:10:03 -080067
Mathieu Chartier412c7fc2014-02-07 12:18:39 -080068 AllocRecordStackTraceElement() : method(nullptr), dex_pc(0) {
69 }
70
Ian Rogersb726dcb2012-09-05 08:57:23 -070071 int32_t LineNumber() const SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers0399dde2012-06-06 17:09:28 -070072 return MethodHelper(method).GetLineNumFromDexPC(dex_pc);
Elliott Hughes545a0642011-11-08 19:10:03 -080073 }
74};
75
76struct AllocRecord {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080077 mirror::Class* type;
Elliott Hughes545a0642011-11-08 19:10:03 -080078 size_t byte_count;
79 uint16_t thin_lock_id;
Brian Carlstrom7934ac22013-07-26 10:54:15 -070080 AllocRecordStackTraceElement stack[kMaxAllocRecordStackDepth]; // Unused entries have NULL method.
Elliott Hughes545a0642011-11-08 19:10:03 -080081
82 size_t GetDepth() {
83 size_t depth = 0;
84 while (depth < kMaxAllocRecordStackDepth && stack[depth].method != NULL) {
85 ++depth;
86 }
87 return depth;
88 }
Mathieu Chartier412c7fc2014-02-07 12:18:39 -080089
Mathieu Chartier83c8ee02014-01-28 14:50:23 -080090 void UpdateObjectPointers(IsMarkedCallback* callback, void* arg)
Mathieu Chartier412c7fc2014-02-07 12:18:39 -080091 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
92 if (type != nullptr) {
Mathieu Chartier83c8ee02014-01-28 14:50:23 -080093 type = down_cast<mirror::Class*>(callback(type, arg));
Mathieu Chartier412c7fc2014-02-07 12:18:39 -080094 }
95 for (size_t stack_frame = 0; stack_frame < kMaxAllocRecordStackDepth; ++stack_frame) {
96 mirror::ArtMethod*& m = stack[stack_frame].method;
97 if (m == nullptr) {
98 break;
99 }
Mathieu Chartier83c8ee02014-01-28 14:50:23 -0800100 m = down_cast<mirror::ArtMethod*>(callback(m, arg));
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800101 }
102 }
Elliott Hughes545a0642011-11-08 19:10:03 -0800103};
104
Elliott Hughes86964332012-02-15 19:37:42 -0800105struct Breakpoint {
Sebastien Hertza76a6d42014-03-20 16:40:17 +0100106 // The location of this breakpoint.
Brian Carlstromea46f952013-07-30 01:26:50 -0700107 mirror::ArtMethod* method;
Elliott Hughesa656a0f2012-02-21 18:03:44 -0800108 uint32_t dex_pc;
Sebastien Hertza76a6d42014-03-20 16:40:17 +0100109
110 // Indicates whether breakpoint needs full deoptimization or selective deoptimization.
111 bool need_full_deoptimization;
112
113 Breakpoint(mirror::ArtMethod* method, uint32_t dex_pc, bool need_full_deoptimization)
114 : method(method), dex_pc(dex_pc), need_full_deoptimization(need_full_deoptimization) {}
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700115
116 void VisitRoots(RootCallback* callback, void* arg) {
117 if (method != nullptr) {
118 callback(reinterpret_cast<mirror::Object**>(&method), arg, 0, kRootDebugger);
119 }
120 }
Elliott Hughes86964332012-02-15 19:37:42 -0800121};
122
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700123static std::ostream& operator<<(std::ostream& os, const Breakpoint& rhs)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700124 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes229feb72012-02-23 13:33:29 -0800125 os << StringPrintf("Breakpoint[%s @%#x]", PrettyMethod(rhs.method).c_str(), rhs.dex_pc);
Elliott Hughes86964332012-02-15 19:37:42 -0800126 return os;
127}
128
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200129class DebugInstrumentationListener FINAL : public instrumentation::InstrumentationListener {
Ian Rogers62d6c772013-02-27 08:32:07 -0800130 public:
131 DebugInstrumentationListener() {}
132 virtual ~DebugInstrumentationListener() {}
133
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200134 void MethodEntered(Thread* thread, mirror::Object* this_object, mirror::ArtMethod* method,
135 uint32_t dex_pc)
136 OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800137 if (method->IsNative()) {
138 // TODO: post location events is a suspension point and native method entry stubs aren't.
139 return;
140 }
Jeff Hao579b0242013-11-18 13:16:49 -0800141 Dbg::PostLocationEvent(method, 0, this_object, Dbg::kMethodEntry, nullptr);
Ian Rogers62d6c772013-02-27 08:32:07 -0800142 }
143
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200144 void MethodExited(Thread* thread, mirror::Object* this_object, mirror::ArtMethod* method,
145 uint32_t dex_pc, const JValue& return_value)
146 OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800147 if (method->IsNative()) {
148 // TODO: post location events is a suspension point and native method entry stubs aren't.
149 return;
150 }
Jeff Hao579b0242013-11-18 13:16:49 -0800151 Dbg::PostLocationEvent(method, dex_pc, this_object, Dbg::kMethodExit, &return_value);
Ian Rogers62d6c772013-02-27 08:32:07 -0800152 }
153
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200154 void MethodUnwind(Thread* thread, mirror::Object* this_object, mirror::ArtMethod* method,
155 uint32_t dex_pc)
156 OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800157 // We're not recorded to listen to this kind of event, so complain.
158 LOG(ERROR) << "Unexpected method unwind event in debugger " << PrettyMethod(method)
Sebastien Hertz51db44a2013-11-19 10:00:29 +0100159 << " " << dex_pc;
Ian Rogers62d6c772013-02-27 08:32:07 -0800160 }
161
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200162 void DexPcMoved(Thread* thread, mirror::Object* this_object, mirror::ArtMethod* method,
163 uint32_t new_dex_pc)
164 OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800165 Dbg::UpdateDebugger(thread, this_object, method, new_dex_pc);
166 }
167
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200168 void FieldRead(Thread* thread, mirror::Object* this_object, mirror::ArtMethod* method,
169 uint32_t dex_pc, mirror::ArtField* field)
170 OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
171 Dbg::PostFieldAccessEvent(method, dex_pc, this_object, field);
Ian Rogers62d6c772013-02-27 08:32:07 -0800172 }
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200173
174 void FieldWritten(Thread* thread, mirror::Object* this_object, mirror::ArtMethod* method,
175 uint32_t dex_pc, mirror::ArtField* field, const JValue& field_value)
176 OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
177 Dbg::PostFieldModificationEvent(method, dex_pc, this_object, field, &field_value);
178 }
179
180 void ExceptionCaught(Thread* thread, const ThrowLocation& throw_location,
181 mirror::ArtMethod* catch_method, uint32_t catch_dex_pc,
182 mirror::Throwable* exception_object)
183 OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
184 Dbg::PostException(throw_location, catch_method, catch_dex_pc, exception_object);
185 }
186
187 private:
188 DISALLOW_COPY_AND_ASSIGN(DebugInstrumentationListener);
Ian Rogers62d6c772013-02-27 08:32:07 -0800189} gDebugInstrumentationListener;
190
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700191// JDWP is allowed unless the Zygote forbids it.
192static bool gJdwpAllowed = true;
193
Elliott Hughesc0f09332012-03-26 13:27:06 -0700194// Was there a -Xrunjdwp or -agentlib:jdwp= argument on the command line?
Elliott Hughes3bb81562011-10-21 18:52:59 -0700195static bool gJdwpConfigured = false;
196
Elliott Hughesc0f09332012-03-26 13:27:06 -0700197// Broken-down JDWP options. (Only valid if IsJdwpConfigured() is true.)
Elliott Hughes376a7a02011-10-24 18:35:55 -0700198static JDWP::JdwpOptions gJdwpOptions;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700199
200// Runtime JDWP state.
201static JDWP::JdwpState* gJdwpState = NULL;
202static bool gDebuggerConnected; // debugger or DDMS is connected.
203static bool gDebuggerActive; // debugger is making requests.
Elliott Hughes86964332012-02-15 19:37:42 -0800204static bool gDisposed; // debugger called VirtualMachine.Dispose, so we should drop the connection.
Elliott Hughes3bb81562011-10-21 18:52:59 -0700205
Elliott Hughes47fce012011-10-25 18:37:19 -0700206static bool gDdmThreadNotification = false;
207
Elliott Hughes767a1472011-10-26 18:49:02 -0700208// DDMS GC-related settings.
209static Dbg::HpifWhen gDdmHpifWhen = Dbg::HPIF_WHEN_NEVER;
210static Dbg::HpsgWhen gDdmHpsgWhen = Dbg::HPSG_WHEN_NEVER;
211static Dbg::HpsgWhat gDdmHpsgWhat;
212static Dbg::HpsgWhen gDdmNhsgWhen = Dbg::HPSG_WHEN_NEVER;
213static Dbg::HpsgWhat gDdmNhsgWhat;
214
Ian Rogers719d1a32014-03-06 12:13:39 -0800215static ObjectRegistry* gRegistry = nullptr;
Elliott Hughes475fc232011-10-25 15:00:35 -0700216
Elliott Hughes545a0642011-11-08 19:10:03 -0800217// Recent allocation tracking.
Ian Rogers719d1a32014-03-06 12:13:39 -0800218Mutex* Dbg::alloc_tracker_lock_ = nullptr;
219AllocRecord* Dbg::recent_allocation_records_ = nullptr; // TODO: CircularBuffer<AllocRecord>
220size_t Dbg::alloc_record_max_ = 0;
221size_t Dbg::alloc_record_head_ = 0;
222size_t Dbg::alloc_record_count_ = 0;
Elliott Hughes545a0642011-11-08 19:10:03 -0800223
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100224// Deoptimization support.
Sebastien Hertz4d25df32014-03-21 17:44:46 +0100225Mutex* Dbg::deoptimization_lock_ = nullptr;
226std::vector<DeoptimizationRequest> Dbg::deoptimization_requests_;
227size_t Dbg::full_deoptimization_event_count_ = 0;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100228
229// Breakpoints.
jeffhao09bfc6a2012-12-11 18:11:43 -0800230static std::vector<Breakpoint> gBreakpoints GUARDED_BY(Locks::breakpoint_lock_);
Elliott Hughes86964332012-02-15 19:37:42 -0800231
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700232void DebugInvokeReq::VisitRoots(RootCallback* callback, void* arg, uint32_t tid,
233 RootType root_type) {
234 if (receiver != nullptr) {
235 callback(&receiver, arg, tid, root_type);
236 }
237 if (thread != nullptr) {
238 callback(&thread, arg, tid, root_type);
239 }
240 if (klass != nullptr) {
241 callback(reinterpret_cast<mirror::Object**>(&klass), arg, tid, root_type);
242 }
243 if (method != nullptr) {
244 callback(reinterpret_cast<mirror::Object**>(&method), arg, tid, root_type);
245 }
246}
247
248void SingleStepControl::VisitRoots(RootCallback* callback, void* arg, uint32_t tid,
249 RootType root_type) {
250 if (method != nullptr) {
251 callback(reinterpret_cast<mirror::Object**>(&method), arg, tid, root_type);
252 }
253}
254
Sebastien Hertz4d25df32014-03-21 17:44:46 +0100255void DeoptimizationRequest::VisitRoots(RootCallback* callback, void* arg) {
256 if (method != nullptr) {
257 callback(reinterpret_cast<mirror::Object**>(&method), arg, 0, kRootDebugger);
258 }
259}
260
Brian Carlstromea46f952013-07-30 01:26:50 -0700261static bool IsBreakpoint(const mirror::ArtMethod* m, uint32_t dex_pc)
jeffhao09bfc6a2012-12-11 18:11:43 -0800262 LOCKS_EXCLUDED(Locks::breakpoint_lock_)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700263 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
jeffhao09bfc6a2012-12-11 18:11:43 -0800264 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100265 for (size_t i = 0, e = gBreakpoints.size(); i < e; ++i) {
Elliott Hughesa656a0f2012-02-21 18:03:44 -0800266 if (gBreakpoints[i].method == m && gBreakpoints[i].dex_pc == dex_pc) {
Elliott Hughes86964332012-02-15 19:37:42 -0800267 VLOG(jdwp) << "Hit breakpoint #" << i << ": " << gBreakpoints[i];
268 return true;
269 }
270 }
271 return false;
272}
273
Sebastien Hertz52d131d2014-03-13 16:17:40 +0100274static bool IsSuspendedForDebugger(ScopedObjectAccessUnchecked& soa, Thread* thread)
275 LOCKS_EXCLUDED(Locks::thread_suspend_count_lock_) {
Elliott Hughes9e0c1752013-01-09 14:02:58 -0800276 MutexLock mu(soa.Self(), *Locks::thread_suspend_count_lock_);
277 // A thread may be suspended for GC; in this code, we really want to know whether
278 // there's a debugger suspension active.
279 return thread->IsSuspended() && thread->GetDebugSuspendCount() > 0;
280}
281
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800282static mirror::Array* DecodeArray(JDWP::RefTypeId id, JDWP::JdwpError& status)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700283 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800284 mirror::Object* o = gRegistry->Get<mirror::Object*>(id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800285 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800286 status = JDWP::ERR_INVALID_OBJECT;
287 return NULL;
288 }
289 if (!o->IsArrayInstance()) {
290 status = JDWP::ERR_INVALID_ARRAY;
291 return NULL;
292 }
293 status = JDWP::ERR_NONE;
294 return o->AsArray();
295}
296
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800297static mirror::Class* DecodeClass(JDWP::RefTypeId id, JDWP::JdwpError& status)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700298 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800299 mirror::Object* o = gRegistry->Get<mirror::Object*>(id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800300 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800301 status = JDWP::ERR_INVALID_OBJECT;
302 return NULL;
303 }
304 if (!o->IsClass()) {
305 status = JDWP::ERR_INVALID_CLASS;
306 return NULL;
307 }
308 status = JDWP::ERR_NONE;
309 return o->AsClass();
310}
311
Elliott Hughes221229c2013-01-08 18:17:50 -0800312static JDWP::JdwpError DecodeThread(ScopedObjectAccessUnchecked& soa, JDWP::ObjectId thread_id, Thread*& thread)
jeffhaoa77f0f62012-12-05 17:19:31 -0800313 EXCLUSIVE_LOCKS_REQUIRED(Locks::thread_list_lock_)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700314 LOCKS_EXCLUDED(Locks::thread_suspend_count_lock_)
315 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800316 mirror::Object* thread_peer = gRegistry->Get<mirror::Object*>(thread_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800317 if (thread_peer == NULL || thread_peer == ObjectRegistry::kInvalidObject) {
Elliott Hughes221229c2013-01-08 18:17:50 -0800318 // This isn't even an object.
319 return JDWP::ERR_INVALID_OBJECT;
Elliott Hughes436e3722012-02-17 20:01:47 -0800320 }
Elliott Hughes221229c2013-01-08 18:17:50 -0800321
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800322 mirror::Class* java_lang_Thread = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_Thread);
Elliott Hughes221229c2013-01-08 18:17:50 -0800323 if (!java_lang_Thread->IsAssignableFrom(thread_peer->GetClass())) {
324 // This isn't a thread.
325 return JDWP::ERR_INVALID_THREAD;
326 }
327
328 thread = Thread::FromManagedThread(soa, thread_peer);
329 if (thread == NULL) {
330 // This is a java.lang.Thread without a Thread*. Must be a zombie.
331 return JDWP::ERR_THREAD_NOT_ALIVE;
332 }
333 return JDWP::ERR_NONE;
Elliott Hughes436e3722012-02-17 20:01:47 -0800334}
335
Elliott Hughes24437992011-11-30 14:49:33 -0800336static JDWP::JdwpTag BasicTagFromDescriptor(const char* descriptor) {
337 // JDWP deliberately uses the descriptor characters' ASCII values for its enum.
338 // Note that by "basic" we mean that we don't get more specific than JT_OBJECT.
339 return static_cast<JDWP::JdwpTag>(descriptor[0]);
340}
341
Ian Rogers98379392014-02-24 16:53:16 -0800342static JDWP::JdwpTag TagFromClass(const ScopedObjectAccessUnchecked& soa, mirror::Class* c)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700343 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes86b00102011-12-05 17:54:26 -0800344 CHECK(c != NULL);
Elliott Hughes24437992011-11-30 14:49:33 -0800345 if (c->IsArrayClass()) {
346 return JDWP::JT_ARRAY;
347 }
Elliott Hughes24437992011-11-30 14:49:33 -0800348 if (c->IsStringClass()) {
349 return JDWP::JT_STRING;
Elliott Hughes24437992011-11-30 14:49:33 -0800350 }
Ian Rogers98379392014-02-24 16:53:16 -0800351 if (c->IsClassClass()) {
352 return JDWP::JT_CLASS_OBJECT;
353 }
354 {
355 mirror::Class* thread_class = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_Thread);
356 if (thread_class->IsAssignableFrom(c)) {
357 return JDWP::JT_THREAD;
358 }
359 }
360 {
361 mirror::Class* thread_group_class =
362 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_ThreadGroup);
363 if (thread_group_class->IsAssignableFrom(c)) {
364 return JDWP::JT_THREAD_GROUP;
365 }
366 }
367 {
368 mirror::Class* class_loader_class =
369 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_ClassLoader);
370 if (class_loader_class->IsAssignableFrom(c)) {
371 return JDWP::JT_CLASS_LOADER;
372 }
373 }
374 return JDWP::JT_OBJECT;
Elliott Hughes24437992011-11-30 14:49:33 -0800375}
376
377/*
378 * Objects declared to hold Object might actually hold a more specific
379 * type. The debugger may take a special interest in these (e.g. it
380 * wants to display the contents of Strings), so we want to return an
381 * appropriate tag.
382 *
383 * Null objects are tagged JT_OBJECT.
384 */
Ian Rogers98379392014-02-24 16:53:16 -0800385static JDWP::JdwpTag TagFromObject(const ScopedObjectAccessUnchecked& soa, mirror::Object* o)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700386 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers98379392014-02-24 16:53:16 -0800387 return (o == NULL) ? JDWP::JT_OBJECT : TagFromClass(soa, o->GetClass());
Elliott Hughes24437992011-11-30 14:49:33 -0800388}
389
390static bool IsPrimitiveTag(JDWP::JdwpTag tag) {
391 switch (tag) {
392 case JDWP::JT_BOOLEAN:
393 case JDWP::JT_BYTE:
394 case JDWP::JT_CHAR:
395 case JDWP::JT_FLOAT:
396 case JDWP::JT_DOUBLE:
397 case JDWP::JT_INT:
398 case JDWP::JT_LONG:
399 case JDWP::JT_SHORT:
400 case JDWP::JT_VOID:
401 return true;
402 default:
403 return false;
404 }
405}
406
Elliott Hughes3bb81562011-10-21 18:52:59 -0700407/*
408 * Handle one of the JDWP name/value pairs.
409 *
410 * JDWP options are:
411 * help: if specified, show help message and bail
412 * transport: may be dt_socket or dt_shmem
413 * address: for dt_socket, "host:port", or just "port" when listening
414 * server: if "y", wait for debugger to attach; if "n", attach to debugger
415 * timeout: how long to wait for debugger to connect / listen
416 *
417 * Useful with server=n (these aren't supported yet):
418 * onthrow=<exception-name>: connect to debugger when exception thrown
419 * onuncaught=y|n: connect to debugger when uncaught exception thrown
420 * launch=<command-line>: launch the debugger itself
421 *
422 * The "transport" option is required, as is "address" if server=n.
423 */
424static bool ParseJdwpOption(const std::string& name, const std::string& value) {
425 if (name == "transport") {
426 if (value == "dt_socket") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700427 gJdwpOptions.transport = JDWP::kJdwpTransportSocket;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700428 } else if (value == "dt_android_adb") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700429 gJdwpOptions.transport = JDWP::kJdwpTransportAndroidAdb;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700430 } else {
431 LOG(ERROR) << "JDWP transport not supported: " << value;
432 return false;
433 }
434 } else if (name == "server") {
435 if (value == "n") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700436 gJdwpOptions.server = false;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700437 } else if (value == "y") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700438 gJdwpOptions.server = true;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700439 } else {
440 LOG(ERROR) << "JDWP option 'server' must be 'y' or 'n'";
441 return false;
442 }
443 } else if (name == "suspend") {
444 if (value == "n") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700445 gJdwpOptions.suspend = false;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700446 } else if (value == "y") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700447 gJdwpOptions.suspend = true;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700448 } else {
449 LOG(ERROR) << "JDWP option 'suspend' must be 'y' or 'n'";
450 return false;
451 }
452 } else if (name == "address") {
453 /* this is either <port> or <host>:<port> */
454 std::string port_string;
Elliott Hughes376a7a02011-10-24 18:35:55 -0700455 gJdwpOptions.host.clear();
Elliott Hughes3bb81562011-10-21 18:52:59 -0700456 std::string::size_type colon = value.find(':');
457 if (colon != std::string::npos) {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700458 gJdwpOptions.host = value.substr(0, colon);
Elliott Hughes3bb81562011-10-21 18:52:59 -0700459 port_string = value.substr(colon + 1);
460 } else {
461 port_string = value;
462 }
463 if (port_string.empty()) {
464 LOG(ERROR) << "JDWP address missing port: " << value;
465 return false;
466 }
467 char* end;
Elliott Hughesba8eee12012-01-24 20:25:24 -0800468 uint64_t port = strtoul(port_string.c_str(), &end, 10);
469 if (*end != '\0' || port > 0xffff) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700470 LOG(ERROR) << "JDWP address has junk in port field: " << value;
471 return false;
472 }
Elliott Hughes376a7a02011-10-24 18:35:55 -0700473 gJdwpOptions.port = port;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700474 } else if (name == "launch" || name == "onthrow" || name == "oncaught" || name == "timeout") {
475 /* valid but unsupported */
476 LOG(INFO) << "Ignoring JDWP option '" << name << "'='" << value << "'";
477 } else {
478 LOG(INFO) << "Ignoring unrecognized JDWP option '" << name << "'='" << value << "'";
479 }
480
481 return true;
482}
483
484/*
485 * Parse the latter half of a -Xrunjdwp/-agentlib:jdwp= string, e.g.:
486 * "transport=dt_socket,address=8000,server=y,suspend=n"
487 */
488bool Dbg::ParseJdwpOptions(const std::string& options) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800489 VLOG(jdwp) << "ParseJdwpOptions: " << options;
Elliott Hughes47fce012011-10-25 18:37:19 -0700490
Elliott Hughes3bb81562011-10-21 18:52:59 -0700491 std::vector<std::string> pairs;
492 Split(options, ',', pairs);
493
494 for (size_t i = 0; i < pairs.size(); ++i) {
495 std::string::size_type equals = pairs[i].find('=');
496 if (equals == std::string::npos) {
497 LOG(ERROR) << "Can't parse JDWP option '" << pairs[i] << "' in '" << options << "'";
498 return false;
499 }
500 ParseJdwpOption(pairs[i].substr(0, equals), pairs[i].substr(equals + 1));
501 }
502
Elliott Hughes376a7a02011-10-24 18:35:55 -0700503 if (gJdwpOptions.transport == JDWP::kJdwpTransportUnknown) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700504 LOG(ERROR) << "Must specify JDWP transport: " << options;
505 }
Elliott Hughes376a7a02011-10-24 18:35:55 -0700506 if (!gJdwpOptions.server && (gJdwpOptions.host.empty() || gJdwpOptions.port == 0)) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700507 LOG(ERROR) << "Must specify JDWP host and port when server=n: " << options;
508 return false;
509 }
510
511 gJdwpConfigured = true;
512 return true;
513}
514
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700515void Dbg::StartJdwp() {
Elliott Hughesc0f09332012-03-26 13:27:06 -0700516 if (!gJdwpAllowed || !IsJdwpConfigured()) {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700517 // No JDWP for you!
518 return;
519 }
520
Ian Rogers719d1a32014-03-06 12:13:39 -0800521 CHECK(gRegistry == nullptr);
Elliott Hughes475fc232011-10-25 15:00:35 -0700522 gRegistry = new ObjectRegistry;
523
Ian Rogers719d1a32014-03-06 12:13:39 -0800524 alloc_tracker_lock_ = new Mutex("AllocTracker lock");
Sebastien Hertz4d25df32014-03-21 17:44:46 +0100525 deoptimization_lock_ = new Mutex("deoptimization lock", kDeoptimizationLock);
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700526 // Init JDWP if the debugger is enabled. This may connect out to a
527 // debugger, passively listen for a debugger, or block waiting for a
528 // debugger.
Elliott Hughes376a7a02011-10-24 18:35:55 -0700529 gJdwpState = JDWP::JdwpState::Create(&gJdwpOptions);
530 if (gJdwpState == NULL) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -0800531 // We probably failed because some other process has the port already, which means that
532 // if we don't abort the user is likely to think they're talking to us when they're actually
533 // talking to that other process.
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800534 LOG(FATAL) << "Debugger thread failed to initialize";
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700535 }
536
537 // If a debugger has already attached, send the "welcome" message.
538 // This may cause us to suspend all threads.
Elliott Hughes376a7a02011-10-24 18:35:55 -0700539 if (gJdwpState->IsActive()) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700540 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes376a7a02011-10-24 18:35:55 -0700541 if (!gJdwpState->PostVMStart()) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800542 LOG(WARNING) << "Failed to post 'start' message to debugger";
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700543 }
544 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700545}
546
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700547void Dbg::VisitRoots(RootCallback* callback, void* arg) {
Sebastien Hertz4d25df32014-03-21 17:44:46 +0100548 {
549 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
550 for (Breakpoint& bp : gBreakpoints) {
551 bp.VisitRoots(callback, arg);
552 }
553 }
554 if (deoptimization_lock_ != nullptr) { // only true if the debugger is started.
555 MutexLock mu(Thread::Current(), *deoptimization_lock_);
556 for (DeoptimizationRequest& req : deoptimization_requests_) {
557 req.VisitRoots(callback, arg);
558 }
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700559 }
560}
561
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700562void Dbg::StopJdwp() {
Sebastien Hertz0376e6b2014-02-06 18:12:59 +0100563 // Prevent the JDWP thread from processing JDWP incoming packets after we close the connection.
564 Disposed();
Elliott Hughes376a7a02011-10-24 18:35:55 -0700565 delete gJdwpState;
Ian Rogers719d1a32014-03-06 12:13:39 -0800566 gJdwpState = nullptr;
Elliott Hughes475fc232011-10-25 15:00:35 -0700567 delete gRegistry;
Ian Rogers719d1a32014-03-06 12:13:39 -0800568 gRegistry = nullptr;
569 delete alloc_tracker_lock_;
570 alloc_tracker_lock_ = nullptr;
Sebastien Hertz4d25df32014-03-21 17:44:46 +0100571 delete deoptimization_lock_;
572 deoptimization_lock_ = nullptr;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700573}
574
Elliott Hughes767a1472011-10-26 18:49:02 -0700575void Dbg::GcDidFinish() {
576 if (gDdmHpifWhen != HPIF_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700577 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes81ff3182012-03-23 20:35:56 -0700578 LOG(DEBUG) << "Sending heap info to DDM";
Elliott Hughes7162ad92011-10-27 14:08:42 -0700579 DdmSendHeapInfo(gDdmHpifWhen);
Elliott Hughes767a1472011-10-26 18:49:02 -0700580 }
581 if (gDdmHpsgWhen != HPSG_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700582 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes81ff3182012-03-23 20:35:56 -0700583 LOG(DEBUG) << "Dumping heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700584 DdmSendHeapSegments(false);
Elliott Hughes767a1472011-10-26 18:49:02 -0700585 }
586 if (gDdmNhsgWhen != HPSG_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700587 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes767a1472011-10-26 18:49:02 -0700588 LOG(DEBUG) << "Dumping native heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700589 DdmSendHeapSegments(true);
Elliott Hughes767a1472011-10-26 18:49:02 -0700590 }
591}
592
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700593void Dbg::SetJdwpAllowed(bool allowed) {
594 gJdwpAllowed = allowed;
595}
596
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700597DebugInvokeReq* Dbg::GetInvokeReq() {
Elliott Hughes475fc232011-10-25 15:00:35 -0700598 return Thread::Current()->GetInvokeReq();
599}
600
601Thread* Dbg::GetDebugThread() {
602 return (gJdwpState != NULL) ? gJdwpState->GetDebugThread() : NULL;
603}
604
605void Dbg::ClearWaitForEventThread() {
606 gJdwpState->ClearWaitForEventThread();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700607}
608
609void Dbg::Connected() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700610 CHECK(!gDebuggerConnected);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800611 VLOG(jdwp) << "JDWP has attached";
Elliott Hughes3bb81562011-10-21 18:52:59 -0700612 gDebuggerConnected = true;
Elliott Hughes86964332012-02-15 19:37:42 -0800613 gDisposed = false;
614}
615
616void Dbg::Disposed() {
617 gDisposed = true;
618}
619
620bool Dbg::IsDisposed() {
621 return gDisposed;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700622}
623
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200624// All the instrumentation events the debugger is registered for.
625static constexpr uint32_t kListenerEvents = instrumentation::Instrumentation::kMethodEntered |
626 instrumentation::Instrumentation::kMethodExited |
627 instrumentation::Instrumentation::kDexPcMoved |
628 instrumentation::Instrumentation::kFieldRead |
629 instrumentation::Instrumentation::kFieldWritten |
630 instrumentation::Instrumentation::kExceptionCaught;
631
Elliott Hughesa2155262011-11-16 16:26:58 -0800632void Dbg::GoActive() {
633 // Enable all debugging features, including scans for breakpoints.
634 // This is a no-op if we're already active.
635 // Only called from the JDWP handler thread.
636 if (gDebuggerActive) {
637 return;
638 }
639
Elliott Hughesc0f09332012-03-26 13:27:06 -0700640 {
641 // TODO: dalvik only warned if there were breakpoints left over. clear in Dbg::Disconnected?
jeffhao09bfc6a2012-12-11 18:11:43 -0800642 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Elliott Hughesc0f09332012-03-26 13:27:06 -0700643 CHECK_EQ(gBreakpoints.size(), 0U);
644 }
Elliott Hughesa2155262011-11-16 16:26:58 -0800645
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100646 {
Sebastien Hertz4d25df32014-03-21 17:44:46 +0100647 MutexLock mu(Thread::Current(), *deoptimization_lock_);
648 CHECK_EQ(deoptimization_requests_.size(), 0U);
649 CHECK_EQ(full_deoptimization_event_count_, 0U);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100650 }
651
Ian Rogers62d6c772013-02-27 08:32:07 -0800652 Runtime* runtime = Runtime::Current();
653 runtime->GetThreadList()->SuspendAll();
654 Thread* self = Thread::Current();
655 ThreadState old_state = self->SetStateUnsafe(kRunnable);
656 CHECK_NE(old_state, kRunnable);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100657 runtime->GetInstrumentation()->EnableDeoptimization();
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200658 runtime->GetInstrumentation()->AddListener(&gDebugInstrumentationListener, kListenerEvents);
Elliott Hughesa2155262011-11-16 16:26:58 -0800659 gDebuggerActive = true;
Ian Rogers62d6c772013-02-27 08:32:07 -0800660 CHECK_EQ(self->SetStateUnsafe(old_state), kRunnable);
661 runtime->GetThreadList()->ResumeAll();
662
663 LOG(INFO) << "Debugger is active";
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700664}
665
666void Dbg::Disconnected() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700667 CHECK(gDebuggerConnected);
668
Elliott Hughesc0f09332012-03-26 13:27:06 -0700669 LOG(INFO) << "Debugger is no longer active";
Elliott Hughes234ab152011-10-26 14:02:26 -0700670
Ian Rogers62d6c772013-02-27 08:32:07 -0800671 // Suspend all threads and exclusively acquire the mutator lock. Set the state of the thread
672 // to kRunnable to avoid scoped object access transitions. Remove the debugger as a listener
673 // and clear the object registry.
674 Runtime* runtime = Runtime::Current();
675 runtime->GetThreadList()->SuspendAll();
676 Thread* self = Thread::Current();
677 ThreadState old_state = self->SetStateUnsafe(kRunnable);
Sebastien Hertzaaea7342014-02-25 15:10:04 +0100678
679 // Debugger may not be active at this point.
680 if (gDebuggerActive) {
681 {
682 // Since we're going to disable deoptimization, we clear the deoptimization requests queue.
683 // This prevents us from having any pending deoptimization request when the debugger attaches
684 // to us again while no event has been requested yet.
Sebastien Hertz4d25df32014-03-21 17:44:46 +0100685 MutexLock mu(Thread::Current(), *deoptimization_lock_);
686 deoptimization_requests_.clear();
687 full_deoptimization_event_count_ = 0U;
Sebastien Hertzaaea7342014-02-25 15:10:04 +0100688 }
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200689 runtime->GetInstrumentation()->RemoveListener(&gDebugInstrumentationListener, kListenerEvents);
Sebastien Hertzaaea7342014-02-25 15:10:04 +0100690 runtime->GetInstrumentation()->DisableDeoptimization();
691 gDebuggerActive = false;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100692 }
Elliott Hughes234ab152011-10-26 14:02:26 -0700693 gRegistry->Clear();
694 gDebuggerConnected = false;
Ian Rogers62d6c772013-02-27 08:32:07 -0800695 CHECK_EQ(self->SetStateUnsafe(old_state), kRunnable);
696 runtime->GetThreadList()->ResumeAll();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700697}
698
Elliott Hughesc0f09332012-03-26 13:27:06 -0700699bool Dbg::IsDebuggerActive() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700700 return gDebuggerActive;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700701}
702
Elliott Hughesc0f09332012-03-26 13:27:06 -0700703bool Dbg::IsJdwpConfigured() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700704 return gJdwpConfigured;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700705}
706
707int64_t Dbg::LastDebuggerActivity() {
Elliott Hughesca951522011-12-05 12:01:32 -0800708 return gJdwpState->LastDebuggerActivity();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700709}
710
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700711void Dbg::UndoDebuggerSuspensions() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700712 Runtime::Current()->GetThreadList()->UndoDebuggerSuspensions();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700713}
714
Elliott Hughes88d63092013-01-09 09:55:54 -0800715std::string Dbg::GetClassName(JDWP::RefTypeId class_id) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800716 mirror::Object* o = gRegistry->Get<mirror::Object*>(class_id);
Elliott Hughes436e3722012-02-17 20:01:47 -0800717 if (o == NULL) {
718 return "NULL";
719 }
Elliott Hughes64f574f2013-02-20 14:57:12 -0800720 if (o == ObjectRegistry::kInvalidObject) {
Elliott Hughes88d63092013-01-09 09:55:54 -0800721 return StringPrintf("invalid object %p", reinterpret_cast<void*>(class_id));
Elliott Hughes436e3722012-02-17 20:01:47 -0800722 }
723 if (!o->IsClass()) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700724 return StringPrintf("non-class %p", o); // This is only used for debugging output anyway.
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800725 }
Elliott Hughesc308a5d2012-02-16 17:12:06 -0800726 return DescriptorToName(ClassHelper(o->AsClass()).GetDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700727}
728
Elliott Hughes88d63092013-01-09 09:55:54 -0800729JDWP::JdwpError Dbg::GetClassObject(JDWP::RefTypeId id, JDWP::ObjectId& class_object_id) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800730 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800731 mirror::Class* c = DecodeClass(id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -0800732 if (c == NULL) {
733 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800734 }
Elliott Hughes88d63092013-01-09 09:55:54 -0800735 class_object_id = gRegistry->Add(c);
Elliott Hughes436e3722012-02-17 20:01:47 -0800736 return JDWP::ERR_NONE;
Elliott Hughes86964332012-02-15 19:37:42 -0800737}
738
Elliott Hughes88d63092013-01-09 09:55:54 -0800739JDWP::JdwpError Dbg::GetSuperclass(JDWP::RefTypeId id, JDWP::RefTypeId& superclass_id) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800740 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800741 mirror::Class* c = DecodeClass(id, status);
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800742 if (c == NULL) {
743 return status;
744 }
745 if (c->IsInterface()) {
746 // http://code.google.com/p/android/issues/detail?id=20856
Elliott Hughes88d63092013-01-09 09:55:54 -0800747 superclass_id = 0;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800748 } else {
Elliott Hughes88d63092013-01-09 09:55:54 -0800749 superclass_id = gRegistry->Add(c->GetSuperClass());
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800750 }
751 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700752}
753
Elliott Hughes436e3722012-02-17 20:01:47 -0800754JDWP::JdwpError Dbg::GetClassLoader(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800755 mirror::Object* o = gRegistry->Get<mirror::Object*>(id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800756 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800757 return JDWP::ERR_INVALID_OBJECT;
758 }
759 expandBufAddObjectId(pReply, gRegistry->Add(o->GetClass()->GetClassLoader()));
760 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700761}
762
Elliott Hughes436e3722012-02-17 20:01:47 -0800763JDWP::JdwpError Dbg::GetModifiers(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) {
764 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800765 mirror::Class* c = DecodeClass(id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -0800766 if (c == NULL) {
767 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800768 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800769
770 uint32_t access_flags = c->GetAccessFlags() & kAccJavaFlagsMask;
771
Yevgeny Roubande34eea2014-02-15 01:06:03 +0700772 // Set ACC_SUPER. Dex files don't contain this flag but only classes are supposed to have it set,
773 // not interfaces.
Elliott Hughes436e3722012-02-17 20:01:47 -0800774 // Class.getModifiers doesn't return it, but JDWP does, so we set it here.
Yevgeny Roubande34eea2014-02-15 01:06:03 +0700775 if ((access_flags & kAccInterface) == 0) {
776 access_flags |= kAccSuper;
777 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800778
779 expandBufAdd4BE(pReply, access_flags);
780
781 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700782}
783
Elliott Hughesf327e072013-01-09 16:01:26 -0800784JDWP::JdwpError Dbg::GetMonitorInfo(JDWP::ObjectId object_id, JDWP::ExpandBuf* reply)
785 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800786 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800787 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughesf327e072013-01-09 16:01:26 -0800788 return JDWP::ERR_INVALID_OBJECT;
789 }
790
791 // Ensure all threads are suspended while we read objects' lock words.
792 Thread* self = Thread::Current();
Sebastien Hertz54263242014-03-19 18:16:50 +0100793 CHECK_EQ(self->GetState(), kRunnable);
794 self->TransitionFromRunnableToSuspended(kSuspended);
795 Runtime::Current()->GetThreadList()->SuspendAll();
Elliott Hughesf327e072013-01-09 16:01:26 -0800796
797 MonitorInfo monitor_info(o);
798
Sebastien Hertz54263242014-03-19 18:16:50 +0100799 Runtime::Current()->GetThreadList()->ResumeAll();
800 self->TransitionFromSuspendedToRunnable();
Elliott Hughesf327e072013-01-09 16:01:26 -0800801
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700802 if (monitor_info.owner_ != NULL) {
803 expandBufAddObjectId(reply, gRegistry->Add(monitor_info.owner_->GetPeer()));
Elliott Hughesf327e072013-01-09 16:01:26 -0800804 } else {
805 expandBufAddObjectId(reply, gRegistry->Add(NULL));
806 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700807 expandBufAdd4BE(reply, monitor_info.entry_count_);
808 expandBufAdd4BE(reply, monitor_info.waiters_.size());
809 for (size_t i = 0; i < monitor_info.waiters_.size(); ++i) {
810 expandBufAddObjectId(reply, gRegistry->Add(monitor_info.waiters_[i]->GetPeer()));
Elliott Hughesf327e072013-01-09 16:01:26 -0800811 }
812 return JDWP::ERR_NONE;
813}
814
Elliott Hughes734b8c62013-01-11 15:32:45 -0800815JDWP::JdwpError Dbg::GetOwnedMonitors(JDWP::ObjectId thread_id,
816 std::vector<JDWP::ObjectId>& monitors,
Sebastien Hertz52d131d2014-03-13 16:17:40 +0100817 std::vector<uint32_t>& stack_depths) {
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800818 ScopedObjectAccessUnchecked soa(Thread::Current());
819 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
820 Thread* thread;
821 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
822 if (error != JDWP::ERR_NONE) {
823 return error;
824 }
825 if (!IsSuspendedForDebugger(soa, thread)) {
826 return JDWP::ERR_THREAD_NOT_SUSPENDED;
827 }
828
829 struct OwnedMonitorVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -0800830 OwnedMonitorVisitor(Thread* thread, Context* context)
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800831 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -0800832 : StackVisitor(thread, context), current_stack_depth(0) {}
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800833
834 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
835 // annotalysis.
836 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
837 if (!GetMethod()->IsRuntimeMethod()) {
838 Monitor::VisitLocks(this, AppendOwnedMonitors, this);
Elliott Hughes734b8c62013-01-11 15:32:45 -0800839 ++current_stack_depth;
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800840 }
841 return true;
842 }
843
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800844 static void AppendOwnedMonitors(mirror::Object* owned_monitor, void* arg) {
Ian Rogers7a22fa62013-01-23 12:16:16 -0800845 OwnedMonitorVisitor* visitor = reinterpret_cast<OwnedMonitorVisitor*>(arg);
Elliott Hughes734b8c62013-01-11 15:32:45 -0800846 visitor->monitors.push_back(owned_monitor);
847 visitor->stack_depths.push_back(visitor->current_stack_depth);
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800848 }
849
Elliott Hughes734b8c62013-01-11 15:32:45 -0800850 size_t current_stack_depth;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800851 std::vector<mirror::Object*> monitors;
Elliott Hughes734b8c62013-01-11 15:32:45 -0800852 std::vector<uint32_t> stack_depths;
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800853 };
Ian Rogers7a22fa62013-01-23 12:16:16 -0800854 UniquePtr<Context> context(Context::Create());
855 OwnedMonitorVisitor visitor(thread, context.get());
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800856 visitor.WalkStack();
857
858 for (size_t i = 0; i < visitor.monitors.size(); ++i) {
859 monitors.push_back(gRegistry->Add(visitor.monitors[i]));
Elliott Hughes734b8c62013-01-11 15:32:45 -0800860 stack_depths.push_back(visitor.stack_depths[i]);
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800861 }
862
863 return JDWP::ERR_NONE;
864}
865
Sebastien Hertz52d131d2014-03-13 16:17:40 +0100866JDWP::JdwpError Dbg::GetContendedMonitor(JDWP::ObjectId thread_id,
867 JDWP::ObjectId& contended_monitor) {
Elliott Hughesf9501702013-01-11 11:22:27 -0800868 ScopedObjectAccessUnchecked soa(Thread::Current());
869 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
870 Thread* thread;
871 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
872 if (error != JDWP::ERR_NONE) {
873 return error;
874 }
875 if (!IsSuspendedForDebugger(soa, thread)) {
876 return JDWP::ERR_THREAD_NOT_SUSPENDED;
877 }
878
879 contended_monitor = gRegistry->Add(Monitor::GetContendedMonitor(thread));
880
881 return JDWP::ERR_NONE;
882}
883
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800884JDWP::JdwpError Dbg::GetInstanceCounts(const std::vector<JDWP::RefTypeId>& class_ids,
885 std::vector<uint64_t>& counts)
886 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800887 gc::Heap* heap = Runtime::Current()->GetHeap();
888 heap->CollectGarbage(false);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800889 std::vector<mirror::Class*> classes;
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800890 counts.clear();
891 for (size_t i = 0; i < class_ids.size(); ++i) {
892 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800893 mirror::Class* c = DecodeClass(class_ids[i], status);
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800894 if (c == NULL) {
895 return status;
896 }
897 classes.push_back(c);
898 counts.push_back(0);
899 }
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800900 heap->CountInstances(classes, false, &counts[0]);
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800901 return JDWP::ERR_NONE;
902}
903
Elliott Hughes3b78c942013-01-15 17:35:41 -0800904JDWP::JdwpError Dbg::GetInstances(JDWP::RefTypeId class_id, int32_t max_count, std::vector<JDWP::ObjectId>& instances)
905 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800906 gc::Heap* heap = Runtime::Current()->GetHeap();
907 // We only want reachable instances, so do a GC.
908 heap->CollectGarbage(false);
Elliott Hughes3b78c942013-01-15 17:35:41 -0800909 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800910 mirror::Class* c = DecodeClass(class_id, status);
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800911 if (c == nullptr) {
Elliott Hughes3b78c942013-01-15 17:35:41 -0800912 return status;
913 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800914 std::vector<mirror::Object*> raw_instances;
Elliott Hughes3b78c942013-01-15 17:35:41 -0800915 Runtime::Current()->GetHeap()->GetInstances(c, max_count, raw_instances);
916 for (size_t i = 0; i < raw_instances.size(); ++i) {
917 instances.push_back(gRegistry->Add(raw_instances[i]));
918 }
919 return JDWP::ERR_NONE;
920}
921
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800922JDWP::JdwpError Dbg::GetReferringObjects(JDWP::ObjectId object_id, int32_t max_count,
923 std::vector<JDWP::ObjectId>& referring_objects)
924 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800925 gc::Heap* heap = Runtime::Current()->GetHeap();
926 heap->CollectGarbage(false);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800927 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800928 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800929 return JDWP::ERR_INVALID_OBJECT;
930 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800931 std::vector<mirror::Object*> raw_instances;
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800932 heap->GetReferringObjects(o, max_count, raw_instances);
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800933 for (size_t i = 0; i < raw_instances.size(); ++i) {
934 referring_objects.push_back(gRegistry->Add(raw_instances[i]));
935 }
936 return JDWP::ERR_NONE;
937}
938
Elliott Hughes64f574f2013-02-20 14:57:12 -0800939JDWP::JdwpError Dbg::DisableCollection(JDWP::ObjectId object_id)
940 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Sebastien Hertze96060a2013-12-11 12:06:28 +0100941 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
942 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
943 return JDWP::ERR_INVALID_OBJECT;
944 }
Elliott Hughes64f574f2013-02-20 14:57:12 -0800945 gRegistry->DisableCollection(object_id);
946 return JDWP::ERR_NONE;
947}
948
949JDWP::JdwpError Dbg::EnableCollection(JDWP::ObjectId object_id)
950 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Sebastien Hertze96060a2013-12-11 12:06:28 +0100951 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
952 // Unlike DisableCollection, JDWP specs do not state an invalid object causes an error. The RI
953 // also ignores these cases and never return an error. However it's not obvious why this command
954 // should behave differently from DisableCollection and IsCollected commands. So let's be more
955 // strict and return an error if this happens.
956 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
957 return JDWP::ERR_INVALID_OBJECT;
958 }
Elliott Hughes64f574f2013-02-20 14:57:12 -0800959 gRegistry->EnableCollection(object_id);
960 return JDWP::ERR_NONE;
961}
962
963JDWP::JdwpError Dbg::IsCollected(JDWP::ObjectId object_id, bool& is_collected)
964 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Sebastien Hertz65637eb2014-01-10 17:40:02 +0100965 if (object_id == 0) {
966 // Null object id is invalid.
Sebastien Hertze96060a2013-12-11 12:06:28 +0100967 return JDWP::ERR_INVALID_OBJECT;
968 }
Sebastien Hertz65637eb2014-01-10 17:40:02 +0100969 // JDWP specs state an INVALID_OBJECT error is returned if the object ID is not valid. However
970 // the RI seems to ignore this and assume object has been collected.
971 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
972 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
973 is_collected = true;
974 } else {
975 is_collected = gRegistry->IsCollected(object_id);
976 }
Elliott Hughes64f574f2013-02-20 14:57:12 -0800977 return JDWP::ERR_NONE;
978}
979
980void Dbg::DisposeObject(JDWP::ObjectId object_id, uint32_t reference_count)
981 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
982 gRegistry->DisposeObject(object_id, reference_count);
983}
984
Sebastien Hertz4d8fd492014-03-28 16:29:41 +0100985static JDWP::JdwpTypeTag GetTypeTag(mirror::Class* klass)
986 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
987 DCHECK(klass != nullptr);
988 if (klass->IsArrayClass()) {
989 return JDWP::TT_ARRAY;
990 } else if (klass->IsInterface()) {
991 return JDWP::TT_INTERFACE;
992 } else {
993 return JDWP::TT_CLASS;
994 }
995}
996
Elliott Hughes88d63092013-01-09 09:55:54 -0800997JDWP::JdwpError Dbg::GetReflectedType(JDWP::RefTypeId class_id, JDWP::ExpandBuf* pReply) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800998 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800999 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001000 if (c == NULL) {
1001 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001002 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001003
Sebastien Hertz4d8fd492014-03-28 16:29:41 +01001004 JDWP::JdwpTypeTag type_tag = GetTypeTag(c);
1005 expandBufAdd1(pReply, type_tag);
Elliott Hughes88d63092013-01-09 09:55:54 -08001006 expandBufAddRefTypeId(pReply, class_id);
Elliott Hughes436e3722012-02-17 20:01:47 -08001007 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001008}
1009
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001010void Dbg::GetClassList(std::vector<JDWP::RefTypeId>& classes) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001011 // Get the complete list of reference classes (i.e. all classes except
1012 // the primitive types).
1013 // Returns a newly-allocated buffer full of RefTypeId values.
1014 struct ClassListCreator {
Elliott Hughesba8eee12012-01-24 20:25:24 -08001015 explicit ClassListCreator(std::vector<JDWP::RefTypeId>& classes) : classes(classes) {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001016 }
1017
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001018 static bool Visit(mirror::Class* c, void* arg) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001019 return reinterpret_cast<ClassListCreator*>(arg)->Visit(c);
1020 }
1021
Elliott Hughes64f574f2013-02-20 14:57:12 -08001022 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1023 // annotalysis.
1024 bool Visit(mirror::Class* c) NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughesa2155262011-11-16 16:26:58 -08001025 if (!c->IsPrimitive()) {
Elliott Hughes64f574f2013-02-20 14:57:12 -08001026 classes.push_back(gRegistry->AddRefType(c));
Elliott Hughesa2155262011-11-16 16:26:58 -08001027 }
1028 return true;
1029 }
1030
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001031 std::vector<JDWP::RefTypeId>& classes;
Elliott Hughesa2155262011-11-16 16:26:58 -08001032 };
1033
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001034 ClassListCreator clc(classes);
Elliott Hughesa2155262011-11-16 16:26:58 -08001035 Runtime::Current()->GetClassLinker()->VisitClasses(ClassListCreator::Visit, &clc);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001036}
1037
Elliott Hughes88d63092013-01-09 09:55:54 -08001038JDWP::JdwpError Dbg::GetClassInfo(JDWP::RefTypeId class_id, JDWP::JdwpTypeTag* pTypeTag, uint32_t* pStatus, std::string* pDescriptor) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001039 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001040 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001041 if (c == NULL) {
1042 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001043 }
1044
Elliott Hughesa2155262011-11-16 16:26:58 -08001045 if (c->IsArrayClass()) {
1046 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
1047 *pTypeTag = JDWP::TT_ARRAY;
1048 } else {
1049 if (c->IsErroneous()) {
1050 *pStatus = JDWP::CS_ERROR;
1051 } else {
1052 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED | JDWP::CS_INITIALIZED;
1053 }
1054 *pTypeTag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
1055 }
1056
1057 if (pDescriptor != NULL) {
Ian Rogersdfb325e2013-10-30 01:00:44 -07001058 *pDescriptor = ClassHelper(c).GetDescriptor();
Elliott Hughesa2155262011-11-16 16:26:58 -08001059 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001060 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001061}
1062
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001063void Dbg::FindLoadedClassBySignature(const char* descriptor, std::vector<JDWP::RefTypeId>& ids) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001064 std::vector<mirror::Class*> classes;
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001065 Runtime::Current()->GetClassLinker()->LookupClasses(descriptor, classes);
1066 ids.clear();
1067 for (size_t i = 0; i < classes.size(); ++i) {
1068 ids.push_back(gRegistry->Add(classes[i]));
1069 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001070}
1071
Elliott Hughes64f574f2013-02-20 14:57:12 -08001072JDWP::JdwpError Dbg::GetReferenceType(JDWP::ObjectId object_id, JDWP::ExpandBuf* pReply)
1073 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001074 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001075 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001076 return JDWP::ERR_INVALID_OBJECT;
Elliott Hughes499c5132011-11-17 14:55:11 -08001077 }
Elliott Hughes2435a572012-02-17 16:07:41 -08001078
Sebastien Hertz4d8fd492014-03-28 16:29:41 +01001079 JDWP::JdwpTypeTag type_tag = GetTypeTag(o->GetClass());
Elliott Hughes64f574f2013-02-20 14:57:12 -08001080 JDWP::RefTypeId type_id = gRegistry->AddRefType(o->GetClass());
Elliott Hughes2435a572012-02-17 16:07:41 -08001081
1082 expandBufAdd1(pReply, type_tag);
1083 expandBufAddRefTypeId(pReply, type_id);
1084
1085 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001086}
1087
Ian Rogersfc0e94b2013-09-23 23:51:32 -07001088JDWP::JdwpError Dbg::GetSignature(JDWP::RefTypeId class_id, std::string* signature) {
Elliott Hughes1fe7afb2012-02-13 17:23:03 -08001089 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001090 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes1fe7afb2012-02-13 17:23:03 -08001091 if (c == NULL) {
1092 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001093 }
Ian Rogersdfb325e2013-10-30 01:00:44 -07001094 *signature = ClassHelper(c).GetDescriptor();
Elliott Hughes1fe7afb2012-02-13 17:23:03 -08001095 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001096}
1097
Elliott Hughes88d63092013-01-09 09:55:54 -08001098JDWP::JdwpError Dbg::GetSourceFile(JDWP::RefTypeId class_id, std::string& result) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001099 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001100 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001101 if (c == NULL) {
1102 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001103 }
Sebastien Hertzb7054ba2014-03-13 11:52:31 +01001104 if (c->IsProxyClass()) {
1105 return JDWP::ERR_ABSENT_INFORMATION;
1106 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001107 result = ClassHelper(c).GetSourceFile();
1108 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001109}
1110
Elliott Hughes88d63092013-01-09 09:55:54 -08001111JDWP::JdwpError Dbg::GetObjectTag(JDWP::ObjectId object_id, uint8_t& tag) {
Ian Rogers98379392014-02-24 16:53:16 -08001112 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001113 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001114 if (o == ObjectRegistry::kInvalidObject) {
Elliott Hughes546b9862012-06-20 16:06:13 -07001115 return JDWP::ERR_INVALID_OBJECT;
1116 }
Ian Rogers98379392014-02-24 16:53:16 -08001117 tag = TagFromObject(soa, o);
Elliott Hughes546b9862012-06-20 16:06:13 -07001118 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001119}
1120
Elliott Hughesaed4be92011-12-02 16:16:23 -08001121size_t Dbg::GetTagWidth(JDWP::JdwpTag tag) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001122 switch (tag) {
1123 case JDWP::JT_VOID:
1124 return 0;
1125 case JDWP::JT_BYTE:
1126 case JDWP::JT_BOOLEAN:
1127 return 1;
1128 case JDWP::JT_CHAR:
1129 case JDWP::JT_SHORT:
1130 return 2;
1131 case JDWP::JT_FLOAT:
1132 case JDWP::JT_INT:
1133 return 4;
1134 case JDWP::JT_ARRAY:
1135 case JDWP::JT_OBJECT:
1136 case JDWP::JT_STRING:
1137 case JDWP::JT_THREAD:
1138 case JDWP::JT_THREAD_GROUP:
1139 case JDWP::JT_CLASS_LOADER:
1140 case JDWP::JT_CLASS_OBJECT:
1141 return sizeof(JDWP::ObjectId);
1142 case JDWP::JT_DOUBLE:
1143 case JDWP::JT_LONG:
1144 return 8;
1145 default:
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001146 LOG(FATAL) << "Unknown tag " << tag;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001147 return -1;
1148 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001149}
1150
Elliott Hughes88d63092013-01-09 09:55:54 -08001151JDWP::JdwpError Dbg::GetArrayLength(JDWP::ObjectId array_id, int& length) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001152 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001153 mirror::Array* a = DecodeArray(array_id, status);
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001154 if (a == NULL) {
1155 return status;
Elliott Hughes24437992011-11-30 14:49:33 -08001156 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001157 length = a->GetLength();
1158 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001159}
1160
Elliott Hughes88d63092013-01-09 09:55:54 -08001161JDWP::JdwpError Dbg::OutputArray(JDWP::ObjectId array_id, int offset, int count, JDWP::ExpandBuf* pReply) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001162 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001163 mirror::Array* a = DecodeArray(array_id, status);
Ian Rogers98379392014-02-24 16:53:16 -08001164 if (a == nullptr) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001165 return status;
1166 }
Elliott Hughes24437992011-11-30 14:49:33 -08001167
1168 if (offset < 0 || count < 0 || offset > a->GetLength() || a->GetLength() - offset < count) {
1169 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001170 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughes24437992011-11-30 14:49:33 -08001171 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001172 std::string descriptor(ClassHelper(a->GetClass()).GetDescriptor());
Elliott Hughes24437992011-11-30 14:49:33 -08001173 JDWP::JdwpTag tag = BasicTagFromDescriptor(descriptor.c_str() + 1);
1174
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001175 expandBufAdd1(pReply, tag);
1176 expandBufAdd4BE(pReply, count);
1177
Elliott Hughes24437992011-11-30 14:49:33 -08001178 if (IsPrimitiveTag(tag)) {
1179 size_t width = GetTagWidth(tag);
Elliott Hughes24437992011-11-30 14:49:33 -08001180 uint8_t* dst = expandBufAddSpace(pReply, count * width);
1181 if (width == 8) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001182 const uint64_t* src8 = reinterpret_cast<uint64_t*>(a->GetRawData(sizeof(uint64_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001183 for (int i = 0; i < count; ++i) JDWP::Write8BE(&dst, src8[offset + i]);
1184 } else if (width == 4) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001185 const uint32_t* src4 = reinterpret_cast<uint32_t*>(a->GetRawData(sizeof(uint32_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001186 for (int i = 0; i < count; ++i) JDWP::Write4BE(&dst, src4[offset + i]);
1187 } else if (width == 2) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001188 const uint16_t* src2 = reinterpret_cast<uint16_t*>(a->GetRawData(sizeof(uint16_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001189 for (int i = 0; i < count; ++i) JDWP::Write2BE(&dst, src2[offset + i]);
1190 } else {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001191 const uint8_t* src = reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint8_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001192 memcpy(dst, &src[offset * width], count * width);
1193 }
1194 } else {
Ian Rogers98379392014-02-24 16:53:16 -08001195 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001196 mirror::ObjectArray<mirror::Object>* oa = a->AsObjectArray<mirror::Object>();
Elliott Hughes24437992011-11-30 14:49:33 -08001197 for (int i = 0; i < count; ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001198 mirror::Object* element = oa->Get(offset + i);
Ian Rogers98379392014-02-24 16:53:16 -08001199 JDWP::JdwpTag specific_tag = (element != nullptr) ? TagFromObject(soa, element)
1200 : tag;
Elliott Hughes24437992011-11-30 14:49:33 -08001201 expandBufAdd1(pReply, specific_tag);
1202 expandBufAddObjectId(pReply, gRegistry->Add(element));
1203 }
1204 }
1205
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001206 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001207}
1208
Ian Rogersef7d42f2014-01-06 12:55:46 -08001209template <typename T>
1210static void CopyArrayData(mirror::Array* a, JDWP::Request& src, int offset, int count)
1211 NO_THREAD_SAFETY_ANALYSIS {
1212 // TODO: fix when annotalysis correctly handles non-member functions.
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001213 DCHECK(a->GetClass()->IsPrimitiveArray());
1214
Ian Rogersef7d42f2014-01-06 12:55:46 -08001215 T* dst = reinterpret_cast<T*>(a->GetRawData(sizeof(T), offset));
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001216 for (int i = 0; i < count; ++i) {
1217 *dst++ = src.ReadValue(sizeof(T));
1218 }
1219}
1220
Elliott Hughes88d63092013-01-09 09:55:54 -08001221JDWP::JdwpError Dbg::SetArrayElements(JDWP::ObjectId array_id, int offset, int count,
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001222 JDWP::Request& request)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001223 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001224 JDWP::JdwpError status;
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001225 mirror::Array* dst = DecodeArray(array_id, status);
1226 if (dst == NULL) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001227 return status;
1228 }
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001229
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001230 if (offset < 0 || count < 0 || offset > dst->GetLength() || dst->GetLength() - offset < count) {
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001231 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001232 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001233 }
nikolay serdjuk1d66e882014-04-07 13:54:24 +07001234 ClassHelper ch(dst->GetClass());
1235 const char* descriptor = ch.GetDescriptor();
Ian Rogersfc0e94b2013-09-23 23:51:32 -07001236 JDWP::JdwpTag tag = BasicTagFromDescriptor(descriptor + 1);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001237
1238 if (IsPrimitiveTag(tag)) {
1239 size_t width = GetTagWidth(tag);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001240 if (width == 8) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001241 CopyArrayData<uint64_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001242 } else if (width == 4) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001243 CopyArrayData<uint32_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001244 } else if (width == 2) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001245 CopyArrayData<uint16_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001246 } else {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001247 CopyArrayData<uint8_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001248 }
1249 } else {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001250 mirror::ObjectArray<mirror::Object>* oa = dst->AsObjectArray<mirror::Object>();
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001251 for (int i = 0; i < count; ++i) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001252 JDWP::ObjectId id = request.ReadObjectId();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001253 mirror::Object* o = gRegistry->Get<mirror::Object*>(id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001254 if (o == ObjectRegistry::kInvalidObject) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001255 return JDWP::ERR_INVALID_OBJECT;
1256 }
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001257 oa->Set<false>(offset + i, o);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001258 }
1259 }
1260
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001261 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001262}
1263
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001264JDWP::ObjectId Dbg::CreateString(const std::string& str) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001265 return gRegistry->Add(mirror::String::AllocFromModifiedUtf8(Thread::Current(), str.c_str()));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001266}
1267
Elliott Hughes88d63092013-01-09 09:55:54 -08001268JDWP::JdwpError Dbg::CreateObject(JDWP::RefTypeId class_id, JDWP::ObjectId& new_object) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001269 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001270 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001271 if (c == NULL) {
1272 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001273 }
Ian Rogers50b35e22012-10-04 10:09:15 -07001274 new_object = gRegistry->Add(c->AllocObject(Thread::Current()));
Elliott Hughes436e3722012-02-17 20:01:47 -08001275 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001276}
1277
Elliott Hughesbf13d362011-12-08 15:51:37 -08001278/*
1279 * Used by Eclipse's "Display" view to evaluate "new byte[5]" to get "(byte[]) [0, 0, 0, 0, 0]".
1280 */
Elliott Hughes88d63092013-01-09 09:55:54 -08001281JDWP::JdwpError Dbg::CreateArrayObject(JDWP::RefTypeId array_class_id, uint32_t length,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001282 JDWP::ObjectId& new_array) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001283 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001284 mirror::Class* c = DecodeClass(array_class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001285 if (c == NULL) {
1286 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001287 }
Ian Rogers6fac4472014-02-25 17:01:10 -08001288 new_array = gRegistry->Add(mirror::Array::Alloc<true>(Thread::Current(), c, length,
1289 c->GetComponentSize(),
1290 Runtime::Current()->GetHeap()->GetCurrentAllocator()));
Elliott Hughes436e3722012-02-17 20:01:47 -08001291 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001292}
1293
Elliott Hughes88d63092013-01-09 09:55:54 -08001294bool Dbg::MatchType(JDWP::RefTypeId instance_class_id, JDWP::RefTypeId class_id) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001295 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001296 mirror::Class* c1 = DecodeClass(instance_class_id, status);
Elliott Hughesa656a0f2012-02-21 18:03:44 -08001297 CHECK(c1 != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001298 mirror::Class* c2 = DecodeClass(class_id, status);
Elliott Hughesa656a0f2012-02-21 18:03:44 -08001299 CHECK(c2 != NULL);
Sebastien Hertz123756a2013-11-27 15:49:42 +01001300 return c2->IsAssignableFrom(c1);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001301}
1302
Brian Carlstromea46f952013-07-30 01:26:50 -07001303static JDWP::FieldId ToFieldId(const mirror::ArtField* f)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001304 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001305 CHECK(!kMovingFields);
Elliott Hughes03181a82011-11-17 17:22:21 -08001306 return static_cast<JDWP::FieldId>(reinterpret_cast<uintptr_t>(f));
Elliott Hughes03181a82011-11-17 17:22:21 -08001307}
1308
Brian Carlstromea46f952013-07-30 01:26:50 -07001309static JDWP::MethodId ToMethodId(const mirror::ArtMethod* m)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001310 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001311 CHECK(!kMovingMethods);
Elliott Hughes03181a82011-11-17 17:22:21 -08001312 return static_cast<JDWP::MethodId>(reinterpret_cast<uintptr_t>(m));
Elliott Hughes03181a82011-11-17 17:22:21 -08001313}
1314
Brian Carlstromea46f952013-07-30 01:26:50 -07001315static mirror::ArtField* FromFieldId(JDWP::FieldId fid)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001316 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001317 CHECK(!kMovingFields);
Brian Carlstromea46f952013-07-30 01:26:50 -07001318 return reinterpret_cast<mirror::ArtField*>(static_cast<uintptr_t>(fid));
Elliott Hughesaed4be92011-12-02 16:16:23 -08001319}
1320
Brian Carlstromea46f952013-07-30 01:26:50 -07001321static mirror::ArtMethod* FromMethodId(JDWP::MethodId mid)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001322 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001323 CHECK(!kMovingMethods);
Brian Carlstromea46f952013-07-30 01:26:50 -07001324 return reinterpret_cast<mirror::ArtMethod*>(static_cast<uintptr_t>(mid));
Elliott Hughes03181a82011-11-17 17:22:21 -08001325}
1326
Brian Carlstromea46f952013-07-30 01:26:50 -07001327static void SetLocation(JDWP::JdwpLocation& location, mirror::ArtMethod* m, uint32_t dex_pc)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001328 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001329 if (m == NULL) {
1330 memset(&location, 0, sizeof(location));
1331 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001332 mirror::Class* c = m->GetDeclaringClass();
Sebastien Hertz4d8fd492014-03-28 16:29:41 +01001333 location.type_tag = GetTypeTag(c);
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001334 location.class_id = gRegistry->AddRefType(c);
Elliott Hughes74847412012-06-20 18:10:21 -07001335 location.method_id = ToMethodId(m);
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001336 location.dex_pc = (m->IsNative() || m->IsProxyMethod()) ? static_cast<uint64_t>(-1) : dex_pc;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001337 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08001338}
1339
Elliott Hughesa96836a2013-01-17 12:27:49 -08001340std::string Dbg::GetMethodName(JDWP::MethodId method_id)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001341 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001342 mirror::ArtMethod* m = FromMethodId(method_id);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001343 return MethodHelper(m).GetName();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001344}
1345
Elliott Hughesa96836a2013-01-17 12:27:49 -08001346std::string Dbg::GetFieldName(JDWP::FieldId field_id)
1347 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001348 mirror::ArtField* f = FromFieldId(field_id);
Elliott Hughesa96836a2013-01-17 12:27:49 -08001349 return FieldHelper(f).GetName();
1350}
1351
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001352/*
1353 * Augment the access flags for synthetic methods and fields by setting
1354 * the (as described by the spec) "0xf0000000 bit". Also, strip out any
1355 * flags not specified by the Java programming language.
1356 */
1357static uint32_t MangleAccessFlags(uint32_t accessFlags) {
1358 accessFlags &= kAccJavaFlagsMask;
1359 if ((accessFlags & kAccSynthetic) != 0) {
1360 accessFlags |= 0xf0000000;
1361 }
1362 return accessFlags;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001363}
1364
Elliott Hughesdbb40792011-11-18 17:05:22 -08001365/*
Jeff Haob7cefc72013-11-14 14:51:09 -08001366 * Circularly shifts registers so that arguments come first. Debuggers
1367 * expect slots to begin with arguments, but dex code places them at
1368 * the end.
Elliott Hughesdbb40792011-11-18 17:05:22 -08001369 */
Jeff Haob7cefc72013-11-14 14:51:09 -08001370static uint16_t MangleSlot(uint16_t slot, mirror::ArtMethod* m)
1371 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1372 const DexFile::CodeItem* code_item = MethodHelper(m).GetCodeItem();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001373 if (code_item == nullptr) {
1374 // We should not get here for a method without code (native, proxy or abstract). Log it and
1375 // return the slot as is since all registers are arguments.
1376 LOG(WARNING) << "Trying to mangle slot for method without code " << PrettyMethod(m);
1377 return slot;
1378 }
Jeff Haob7cefc72013-11-14 14:51:09 -08001379 uint16_t ins_size = code_item->ins_size_;
1380 uint16_t locals_size = code_item->registers_size_ - ins_size;
1381 if (slot >= locals_size) {
1382 return slot - locals_size;
1383 } else {
1384 return slot + ins_size;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001385 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001386}
1387
Jeff Haob7cefc72013-11-14 14:51:09 -08001388/*
1389 * Circularly shifts registers so that arguments come last. Reverts
1390 * slots to dex style argument placement.
1391 */
Brian Carlstromea46f952013-07-30 01:26:50 -07001392static uint16_t DemangleSlot(uint16_t slot, mirror::ArtMethod* m)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001393 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Jeff Haob7cefc72013-11-14 14:51:09 -08001394 const DexFile::CodeItem* code_item = MethodHelper(m).GetCodeItem();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001395 if (code_item == nullptr) {
1396 // We should not get here for a method without code (native, proxy or abstract). Log it and
1397 // return the slot as is since all registers are arguments.
1398 LOG(WARNING) << "Trying to demangle slot for method without code " << PrettyMethod(m);
1399 return slot;
1400 }
Jeff Haob7cefc72013-11-14 14:51:09 -08001401 uint16_t ins_size = code_item->ins_size_;
1402 uint16_t locals_size = code_item->registers_size_ - ins_size;
1403 if (slot < ins_size) {
1404 return slot + locals_size;
1405 } else {
1406 return slot - ins_size;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001407 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001408}
1409
Elliott Hughes88d63092013-01-09 09:55:54 -08001410JDWP::JdwpError Dbg::OutputDeclaredFields(JDWP::RefTypeId class_id, bool with_generic, JDWP::ExpandBuf* pReply) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001411 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001412 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001413 if (c == NULL) {
1414 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001415 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001416
1417 size_t instance_field_count = c->NumInstanceFields();
1418 size_t static_field_count = c->NumStaticFields();
1419
1420 expandBufAdd4BE(pReply, instance_field_count + static_field_count);
1421
1422 for (size_t i = 0; i < instance_field_count + static_field_count; ++i) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001423 mirror::ArtField* f = (i < instance_field_count) ? c->GetInstanceField(i) : c->GetStaticField(i - instance_field_count);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001424 FieldHelper fh(f);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001425 expandBufAddFieldId(pReply, ToFieldId(f));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001426 expandBufAddUtf8String(pReply, fh.GetName());
1427 expandBufAddUtf8String(pReply, fh.GetTypeDescriptor());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001428 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001429 static const char genericSignature[1] = "";
1430 expandBufAddUtf8String(pReply, genericSignature);
1431 }
1432 expandBufAdd4BE(pReply, MangleAccessFlags(f->GetAccessFlags()));
1433 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001434 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001435}
1436
Elliott Hughes88d63092013-01-09 09:55:54 -08001437JDWP::JdwpError Dbg::OutputDeclaredMethods(JDWP::RefTypeId class_id, bool with_generic,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001438 JDWP::ExpandBuf* pReply) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001439 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001440 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001441 if (c == NULL) {
1442 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001443 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001444
1445 size_t direct_method_count = c->NumDirectMethods();
1446 size_t virtual_method_count = c->NumVirtualMethods();
1447
1448 expandBufAdd4BE(pReply, direct_method_count + virtual_method_count);
1449
1450 for (size_t i = 0; i < direct_method_count + virtual_method_count; ++i) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001451 mirror::ArtMethod* m = (i < direct_method_count) ? c->GetDirectMethod(i) : c->GetVirtualMethod(i - direct_method_count);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001452 MethodHelper mh(m);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001453 expandBufAddMethodId(pReply, ToMethodId(m));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001454 expandBufAddUtf8String(pReply, mh.GetName());
Ian Rogersd91d6d62013-09-25 20:26:14 -07001455 expandBufAddUtf8String(pReply, mh.GetSignature().ToString());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001456 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001457 static const char genericSignature[1] = "";
1458 expandBufAddUtf8String(pReply, genericSignature);
1459 }
1460 expandBufAdd4BE(pReply, MangleAccessFlags(m->GetAccessFlags()));
1461 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001462 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001463}
1464
Elliott Hughes88d63092013-01-09 09:55:54 -08001465JDWP::JdwpError Dbg::OutputDeclaredInterfaces(JDWP::RefTypeId class_id, JDWP::ExpandBuf* pReply) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001466 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001467 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001468 if (c == NULL) {
1469 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001470 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001471
1472 ClassHelper kh(c);
Ian Rogersd24e2642012-06-06 21:21:43 -07001473 size_t interface_count = kh.NumDirectInterfaces();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001474 expandBufAdd4BE(pReply, interface_count);
1475 for (size_t i = 0; i < interface_count; ++i) {
Elliott Hughes64f574f2013-02-20 14:57:12 -08001476 expandBufAddRefTypeId(pReply, gRegistry->AddRefType(kh.GetDirectInterface(i)));
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001477 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001478 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001479}
1480
Elliott Hughes88d63092013-01-09 09:55:54 -08001481void Dbg::OutputLineTable(JDWP::RefTypeId, JDWP::MethodId method_id, JDWP::ExpandBuf* pReply)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001482 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001483 struct DebugCallbackContext {
1484 int numItems;
1485 JDWP::ExpandBuf* pReply;
1486
Elliott Hughes2435a572012-02-17 16:07:41 -08001487 static bool Callback(void* context, uint32_t address, uint32_t line_number) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001488 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
1489 expandBufAdd8BE(pContext->pReply, address);
Elliott Hughes2435a572012-02-17 16:07:41 -08001490 expandBufAdd4BE(pContext->pReply, line_number);
Elliott Hughes03181a82011-11-17 17:22:21 -08001491 pContext->numItems++;
Sebastien Hertzf2910ee2013-10-19 16:39:24 +02001492 return false;
Elliott Hughes03181a82011-11-17 17:22:21 -08001493 }
1494 };
Brian Carlstromea46f952013-07-30 01:26:50 -07001495 mirror::ArtMethod* m = FromMethodId(method_id);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001496 MethodHelper mh(m);
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001497 const DexFile::CodeItem* code_item = mh.GetCodeItem();
Elliott Hughes03181a82011-11-17 17:22:21 -08001498 uint64_t start, end;
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001499 if (code_item == nullptr) {
1500 DCHECK(m->IsNative() || m->IsProxyMethod());
Elliott Hughes03181a82011-11-17 17:22:21 -08001501 start = -1;
1502 end = -1;
1503 } else {
1504 start = 0;
jeffhao14f0db92012-12-14 17:50:42 -08001505 // Return the index of the last instruction
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001506 end = code_item->insns_size_in_code_units_ - 1;
Elliott Hughes03181a82011-11-17 17:22:21 -08001507 }
1508
1509 expandBufAdd8BE(pReply, start);
1510 expandBufAdd8BE(pReply, end);
1511
1512 // Add numLines later
1513 size_t numLinesOffset = expandBufGetLength(pReply);
1514 expandBufAdd4BE(pReply, 0);
1515
1516 DebugCallbackContext context;
1517 context.numItems = 0;
1518 context.pReply = pReply;
1519
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001520 if (code_item != nullptr) {
1521 mh.GetDexFile().DecodeDebugInfo(code_item, m->IsStatic(), m->GetDexMethodIndex(),
1522 DebugCallbackContext::Callback, NULL, &context);
1523 }
Elliott Hughes03181a82011-11-17 17:22:21 -08001524
1525 JDWP::Set4BE(expandBufGetBuffer(pReply) + numLinesOffset, context.numItems);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001526}
1527
Elliott Hughes88d63092013-01-09 09:55:54 -08001528void Dbg::OutputVariableTable(JDWP::RefTypeId, JDWP::MethodId method_id, bool with_generic, JDWP::ExpandBuf* pReply) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001529 struct DebugCallbackContext {
Jeff Haob7cefc72013-11-14 14:51:09 -08001530 mirror::ArtMethod* method;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001531 JDWP::ExpandBuf* pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001532 size_t variable_count;
1533 bool with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001534
Jeff Haob7cefc72013-11-14 14:51:09 -08001535 static void Callback(void* context, uint16_t slot, uint32_t startAddress, uint32_t endAddress, const char* name, const char* descriptor, const char* signature)
1536 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001537 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
1538
Jeff Haob7cefc72013-11-14 14:51:09 -08001539 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 -08001540
Jeff Haob7cefc72013-11-14 14:51:09 -08001541 slot = MangleSlot(slot, pContext->method);
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001542
Elliott Hughesdbb40792011-11-18 17:05:22 -08001543 expandBufAdd8BE(pContext->pReply, startAddress);
1544 expandBufAddUtf8String(pContext->pReply, name);
1545 expandBufAddUtf8String(pContext->pReply, descriptor);
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001546 if (pContext->with_generic) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001547 expandBufAddUtf8String(pContext->pReply, signature);
1548 }
1549 expandBufAdd4BE(pContext->pReply, endAddress - startAddress);
1550 expandBufAdd4BE(pContext->pReply, slot);
1551
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001552 ++pContext->variable_count;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001553 }
1554 };
Brian Carlstromea46f952013-07-30 01:26:50 -07001555 mirror::ArtMethod* m = FromMethodId(method_id);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001556 MethodHelper mh(m);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001557
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001558 // arg_count considers doubles and longs to take 2 units.
1559 // variable_count considers everything to take 1 unit.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001560 std::string shorty(mh.GetShorty());
Brian Carlstromea46f952013-07-30 01:26:50 -07001561 expandBufAdd4BE(pReply, mirror::ArtMethod::NumArgRegisters(shorty));
Elliott Hughesdbb40792011-11-18 17:05:22 -08001562
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001563 // We don't know the total number of variables yet, so leave a blank and update it later.
1564 size_t variable_count_offset = expandBufGetLength(pReply);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001565 expandBufAdd4BE(pReply, 0);
1566
1567 DebugCallbackContext context;
Jeff Haob7cefc72013-11-14 14:51:09 -08001568 context.method = m;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001569 context.pReply = pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001570 context.variable_count = 0;
1571 context.with_generic = with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001572
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001573 const DexFile::CodeItem* code_item = mh.GetCodeItem();
1574 if (code_item != nullptr) {
1575 mh.GetDexFile().DecodeDebugInfo(code_item, m->IsStatic(), m->GetDexMethodIndex(), NULL,
1576 DebugCallbackContext::Callback, &context);
1577 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001578
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001579 JDWP::Set4BE(expandBufGetBuffer(pReply) + variable_count_offset, context.variable_count);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001580}
1581
Jeff Hao579b0242013-11-18 13:16:49 -08001582void Dbg::OutputMethodReturnValue(JDWP::MethodId method_id, const JValue* return_value,
1583 JDWP::ExpandBuf* pReply) {
1584 mirror::ArtMethod* m = FromMethodId(method_id);
1585 JDWP::JdwpTag tag = BasicTagFromDescriptor(MethodHelper(m).GetShorty());
1586 OutputJValue(tag, return_value, pReply);
1587}
1588
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02001589void Dbg::OutputFieldValue(JDWP::FieldId field_id, const JValue* field_value,
1590 JDWP::ExpandBuf* pReply) {
1591 mirror::ArtField* f = FromFieldId(field_id);
1592 JDWP::JdwpTag tag = BasicTagFromDescriptor(FieldHelper(f).GetTypeDescriptor());
1593 OutputJValue(tag, field_value, pReply);
1594}
1595
Elliott Hughes9777ba22013-01-17 09:04:19 -08001596JDWP::JdwpError Dbg::GetBytecodes(JDWP::RefTypeId, JDWP::MethodId method_id,
1597 std::vector<uint8_t>& bytecodes)
1598 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001599 mirror::ArtMethod* m = FromMethodId(method_id);
Elliott Hughes9777ba22013-01-17 09:04:19 -08001600 if (m == NULL) {
1601 return JDWP::ERR_INVALID_METHODID;
1602 }
1603 MethodHelper mh(m);
1604 const DexFile::CodeItem* code_item = mh.GetCodeItem();
1605 size_t byte_count = code_item->insns_size_in_code_units_ * 2;
1606 const uint8_t* begin = reinterpret_cast<const uint8_t*>(code_item->insns_);
1607 const uint8_t* end = begin + byte_count;
1608 for (const uint8_t* p = begin; p != end; ++p) {
1609 bytecodes.push_back(*p);
1610 }
1611 return JDWP::ERR_NONE;
1612}
1613
Elliott Hughes88d63092013-01-09 09:55:54 -08001614JDWP::JdwpTag Dbg::GetFieldBasicTag(JDWP::FieldId field_id) {
1615 return BasicTagFromDescriptor(FieldHelper(FromFieldId(field_id)).GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001616}
1617
Elliott Hughes88d63092013-01-09 09:55:54 -08001618JDWP::JdwpTag Dbg::GetStaticFieldBasicTag(JDWP::FieldId field_id) {
1619 return BasicTagFromDescriptor(FieldHelper(FromFieldId(field_id)).GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001620}
1621
Elliott Hughes88d63092013-01-09 09:55:54 -08001622static JDWP::JdwpError GetFieldValueImpl(JDWP::RefTypeId ref_type_id, JDWP::ObjectId object_id,
1623 JDWP::FieldId field_id, JDWP::ExpandBuf* pReply,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001624 bool is_static)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001625 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes0cf74332012-02-23 23:14:00 -08001626 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001627 mirror::Class* c = DecodeClass(ref_type_id, status);
Elliott Hughes88d63092013-01-09 09:55:54 -08001628 if (ref_type_id != 0 && c == NULL) {
Elliott Hughes0cf74332012-02-23 23:14:00 -08001629 return status;
1630 }
1631
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001632 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001633 if ((!is_static && o == NULL) || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001634 return JDWP::ERR_INVALID_OBJECT;
1635 }
Brian Carlstromea46f952013-07-30 01:26:50 -07001636 mirror::ArtField* f = FromFieldId(field_id);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001637
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001638 mirror::Class* receiver_class = c;
Elliott Hughes0cf74332012-02-23 23:14:00 -08001639 if (receiver_class == NULL && o != NULL) {
1640 receiver_class = o->GetClass();
1641 }
1642 // TODO: should we give up now if receiver_class is NULL?
1643 if (receiver_class != NULL && !f->GetDeclaringClass()->IsAssignableFrom(receiver_class)) {
1644 LOG(INFO) << "ERR_INVALID_FIELDID: " << PrettyField(f) << " " << PrettyClass(receiver_class);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001645 return JDWP::ERR_INVALID_FIELDID;
1646 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001647
Elliott Hughes0cf74332012-02-23 23:14:00 -08001648 // The RI only enforces the static/non-static mismatch in one direction.
1649 // TODO: should we change the tests and check both?
1650 if (is_static) {
1651 if (!f->IsStatic()) {
1652 return JDWP::ERR_INVALID_FIELDID;
1653 }
1654 } else {
1655 if (f->IsStatic()) {
1656 LOG(WARNING) << "Ignoring non-NULL receiver for ObjectReference.SetValues on static field " << PrettyField(f);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001657 }
1658 }
jeffhao0dfbb7e2012-11-28 15:26:03 -08001659 if (f->IsStatic()) {
1660 o = f->GetDeclaringClass();
1661 }
Elliott Hughes0cf74332012-02-23 23:14:00 -08001662
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001663 JDWP::JdwpTag tag = BasicTagFromDescriptor(FieldHelper(f).GetTypeDescriptor());
Jeff Hao579b0242013-11-18 13:16:49 -08001664 JValue field_value;
1665 if (tag == JDWP::JT_VOID) {
1666 LOG(FATAL) << "Unknown tag: " << tag;
1667 } else if (!IsPrimitiveTag(tag)) {
1668 field_value.SetL(f->GetObject(o));
1669 } else if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
1670 field_value.SetJ(f->Get64(o));
Elliott Hughesaed4be92011-12-02 16:16:23 -08001671 } else {
Jeff Hao579b0242013-11-18 13:16:49 -08001672 field_value.SetI(f->Get32(o));
Elliott Hughesaed4be92011-12-02 16:16:23 -08001673 }
Jeff Hao579b0242013-11-18 13:16:49 -08001674 Dbg::OutputJValue(tag, &field_value, pReply);
1675
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001676 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001677}
1678
Elliott Hughes88d63092013-01-09 09:55:54 -08001679JDWP::JdwpError Dbg::GetFieldValue(JDWP::ObjectId object_id, JDWP::FieldId field_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001680 JDWP::ExpandBuf* pReply) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001681 return GetFieldValueImpl(0, object_id, field_id, pReply, false);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001682}
1683
Elliott Hughes88d63092013-01-09 09:55:54 -08001684JDWP::JdwpError Dbg::GetStaticFieldValue(JDWP::RefTypeId ref_type_id, JDWP::FieldId field_id, JDWP::ExpandBuf* pReply) {
1685 return GetFieldValueImpl(ref_type_id, 0, field_id, pReply, true);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001686}
1687
Elliott Hughes88d63092013-01-09 09:55:54 -08001688static JDWP::JdwpError SetFieldValueImpl(JDWP::ObjectId object_id, JDWP::FieldId field_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001689 uint64_t value, int width, bool is_static)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001690 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001691 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001692 if ((!is_static && o == NULL) || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001693 return JDWP::ERR_INVALID_OBJECT;
1694 }
Brian Carlstromea46f952013-07-30 01:26:50 -07001695 mirror::ArtField* f = FromFieldId(field_id);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001696
1697 // The RI only enforces the static/non-static mismatch in one direction.
1698 // TODO: should we change the tests and check both?
1699 if (is_static) {
1700 if (!f->IsStatic()) {
1701 return JDWP::ERR_INVALID_FIELDID;
1702 }
1703 } else {
1704 if (f->IsStatic()) {
1705 LOG(WARNING) << "Ignoring non-NULL receiver for ObjectReference.SetValues on static field " << PrettyField(f);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001706 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001707 }
jeffhao0dfbb7e2012-11-28 15:26:03 -08001708 if (f->IsStatic()) {
1709 o = f->GetDeclaringClass();
1710 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001711
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001712 JDWP::JdwpTag tag = BasicTagFromDescriptor(FieldHelper(f).GetTypeDescriptor());
Elliott Hughesaed4be92011-12-02 16:16:23 -08001713
1714 if (IsPrimitiveTag(tag)) {
1715 if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001716 CHECK_EQ(width, 8);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001717 // Debugging can't use transactional mode (runtime only).
1718 f->Set64<false>(o, value);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001719 } else {
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001720 CHECK_LE(width, 4);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001721 // Debugging can't use transactional mode (runtime only).
1722 f->Set32<false>(o, value);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001723 }
1724 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001725 mirror::Object* v = gRegistry->Get<mirror::Object*>(value);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001726 if (v == ObjectRegistry::kInvalidObject) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001727 return JDWP::ERR_INVALID_OBJECT;
1728 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001729 if (v != NULL) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001730 mirror::Class* field_type = FieldHelper(f).GetType();
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001731 if (!field_type->IsAssignableFrom(v->GetClass())) {
1732 return JDWP::ERR_INVALID_OBJECT;
1733 }
1734 }
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001735 // Debugging can't use transactional mode (runtime only).
1736 f->SetObject<false>(o, v);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001737 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001738
1739 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001740}
1741
Elliott Hughes88d63092013-01-09 09:55:54 -08001742JDWP::JdwpError Dbg::SetFieldValue(JDWP::ObjectId object_id, JDWP::FieldId field_id, uint64_t value,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001743 int width) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001744 return SetFieldValueImpl(object_id, field_id, value, width, false);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001745}
1746
Elliott Hughes88d63092013-01-09 09:55:54 -08001747JDWP::JdwpError Dbg::SetStaticFieldValue(JDWP::FieldId field_id, uint64_t value, int width) {
1748 return SetFieldValueImpl(0, field_id, value, width, true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001749}
1750
Elliott Hughes88d63092013-01-09 09:55:54 -08001751std::string Dbg::StringToUtf8(JDWP::ObjectId string_id) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001752 mirror::String* s = gRegistry->Get<mirror::String*>(string_id);
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001753 return s->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001754}
1755
Jeff Hao579b0242013-11-18 13:16:49 -08001756void Dbg::OutputJValue(JDWP::JdwpTag tag, const JValue* return_value, JDWP::ExpandBuf* pReply) {
1757 if (IsPrimitiveTag(tag)) {
1758 expandBufAdd1(pReply, tag);
1759 if (tag == JDWP::JT_BOOLEAN || tag == JDWP::JT_BYTE) {
1760 expandBufAdd1(pReply, return_value->GetI());
1761 } else if (tag == JDWP::JT_CHAR || tag == JDWP::JT_SHORT) {
1762 expandBufAdd2BE(pReply, return_value->GetI());
1763 } else if (tag == JDWP::JT_FLOAT || tag == JDWP::JT_INT) {
1764 expandBufAdd4BE(pReply, return_value->GetI());
1765 } else if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
1766 expandBufAdd8BE(pReply, return_value->GetJ());
1767 } else {
1768 CHECK_EQ(tag, JDWP::JT_VOID);
1769 }
1770 } else {
Ian Rogers98379392014-02-24 16:53:16 -08001771 ScopedObjectAccessUnchecked soa(Thread::Current());
Jeff Hao579b0242013-11-18 13:16:49 -08001772 mirror::Object* value = return_value->GetL();
Ian Rogers98379392014-02-24 16:53:16 -08001773 expandBufAdd1(pReply, TagFromObject(soa, value));
Jeff Hao579b0242013-11-18 13:16:49 -08001774 expandBufAddObjectId(pReply, gRegistry->Add(value));
1775 }
1776}
1777
Elliott Hughes221229c2013-01-08 18:17:50 -08001778JDWP::JdwpError Dbg::GetThreadName(JDWP::ObjectId thread_id, std::string& name) {
jeffhaoa77f0f62012-12-05 17:19:31 -08001779 ScopedObjectAccessUnchecked soa(Thread::Current());
1780 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001781 Thread* thread;
1782 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1783 if (error != JDWP::ERR_NONE && error != JDWP::ERR_THREAD_NOT_ALIVE) {
1784 return error;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001785 }
Elliott Hughes221229c2013-01-08 18:17:50 -08001786
1787 // We still need to report the zombie threads' names, so we can't just call Thread::GetThreadName.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001788 mirror::Object* thread_object = gRegistry->Get<mirror::Object*>(thread_id);
Brian Carlstromea46f952013-07-30 01:26:50 -07001789 mirror::ArtField* java_lang_Thread_name_field =
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001790 soa.DecodeField(WellKnownClasses::java_lang_Thread_name);
1791 mirror::String* s =
1792 reinterpret_cast<mirror::String*>(java_lang_Thread_name_field->GetObject(thread_object));
Elliott Hughes221229c2013-01-08 18:17:50 -08001793 if (s != NULL) {
1794 name = s->ToModifiedUtf8();
1795 }
1796 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001797}
1798
Elliott Hughes221229c2013-01-08 18:17:50 -08001799JDWP::JdwpError Dbg::GetThreadGroup(JDWP::ObjectId thread_id, JDWP::ExpandBuf* pReply) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001800 ScopedObjectAccess soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001801 mirror::Object* thread_object = gRegistry->Get<mirror::Object*>(thread_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001802 if (thread_object == ObjectRegistry::kInvalidObject) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001803 return JDWP::ERR_INVALID_OBJECT;
1804 }
Ian Rogers98379392014-02-24 16:53:16 -08001805 const char* old_cause = soa.Self()->StartAssertNoThreadSuspension("Debugger: GetThreadGroup");
Elliott Hughes2435a572012-02-17 16:07:41 -08001806 // Okay, so it's an object, but is it actually a thread?
Ian Rogers50b35e22012-10-04 10:09:15 -07001807 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001808 Thread* thread;
1809 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1810 if (error == JDWP::ERR_THREAD_NOT_ALIVE) {
1811 // Zombie threads are in the null group.
1812 expandBufAddObjectId(pReply, JDWP::ObjectId(0));
Sebastien Hertz52d131d2014-03-13 16:17:40 +01001813 error = JDWP::ERR_NONE;
1814 } else if (error == JDWP::ERR_NONE) {
1815 mirror::Class* c = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_Thread);
1816 CHECK(c != nullptr);
1817 mirror::ArtField* f = c->FindInstanceField("group", "Ljava/lang/ThreadGroup;");
1818 CHECK(f != NULL);
1819 mirror::Object* group = f->GetObject(thread_object);
1820 CHECK(group != NULL);
1821 JDWP::ObjectId thread_group_id = gRegistry->Add(group);
1822 expandBufAddObjectId(pReply, thread_group_id);
Elliott Hughes221229c2013-01-08 18:17:50 -08001823 }
Ian Rogers98379392014-02-24 16:53:16 -08001824 soa.Self()->EndAssertNoThreadSuspension(old_cause);
Sebastien Hertz52d131d2014-03-13 16:17:40 +01001825 return error;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001826}
1827
Elliott Hughes88d63092013-01-09 09:55:54 -08001828std::string Dbg::GetThreadGroupName(JDWP::ObjectId thread_group_id) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001829 ScopedObjectAccess soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001830 mirror::Object* thread_group = gRegistry->Get<mirror::Object*>(thread_group_id);
Ian Rogers98379392014-02-24 16:53:16 -08001831 CHECK(thread_group != nullptr);
1832 const char* old_cause = soa.Self()->StartAssertNoThreadSuspension("Debugger: GetThreadGroupName");
1833 mirror::Class* c = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_ThreadGroup);
1834 CHECK(c != nullptr);
Brian Carlstromea46f952013-07-30 01:26:50 -07001835 mirror::ArtField* f = c->FindInstanceField("name", "Ljava/lang/String;");
Elliott Hughes499c5132011-11-17 14:55:11 -08001836 CHECK(f != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001837 mirror::String* s = reinterpret_cast<mirror::String*>(f->GetObject(thread_group));
Ian Rogers98379392014-02-24 16:53:16 -08001838 soa.Self()->EndAssertNoThreadSuspension(old_cause);
Elliott Hughes499c5132011-11-17 14:55:11 -08001839 return s->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001840}
1841
Elliott Hughes88d63092013-01-09 09:55:54 -08001842JDWP::ObjectId Dbg::GetThreadGroupParent(JDWP::ObjectId thread_group_id) {
Ian Rogers98379392014-02-24 16:53:16 -08001843 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001844 mirror::Object* thread_group = gRegistry->Get<mirror::Object*>(thread_group_id);
Ian Rogers98379392014-02-24 16:53:16 -08001845 CHECK(thread_group != nullptr);
1846 const char* old_cause = soa.Self()->StartAssertNoThreadSuspension("Debugger: GetThreadGroupParent");
1847 mirror::Class* c = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_ThreadGroup);
1848 CHECK(c != nullptr);
Brian Carlstromea46f952013-07-30 01:26:50 -07001849 mirror::ArtField* f = c->FindInstanceField("parent", "Ljava/lang/ThreadGroup;");
Elliott Hughes4e235312011-12-02 11:34:15 -08001850 CHECK(f != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001851 mirror::Object* parent = f->GetObject(thread_group);
Ian Rogers98379392014-02-24 16:53:16 -08001852 soa.Self()->EndAssertNoThreadSuspension(old_cause);
Elliott Hughes4e235312011-12-02 11:34:15 -08001853 return gRegistry->Add(parent);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001854}
1855
1856JDWP::ObjectId Dbg::GetSystemThreadGroupId() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001857 ScopedObjectAccessUnchecked soa(Thread::Current());
Brian Carlstromea46f952013-07-30 01:26:50 -07001858 mirror::ArtField* f = soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_systemThreadGroup);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001859 mirror::Object* group = f->GetObject(f->GetDeclaringClass());
Ian Rogers365c1022012-06-22 15:05:28 -07001860 return gRegistry->Add(group);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001861}
1862
1863JDWP::ObjectId Dbg::GetMainThreadGroupId() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001864 ScopedObjectAccess soa(Thread::Current());
Brian Carlstromea46f952013-07-30 01:26:50 -07001865 mirror::ArtField* f = soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_mainThreadGroup);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001866 mirror::Object* group = f->GetObject(f->GetDeclaringClass());
Ian Rogers365c1022012-06-22 15:05:28 -07001867 return gRegistry->Add(group);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001868}
1869
Jeff Hao920af3e2013-08-28 15:46:38 -07001870JDWP::JdwpThreadStatus Dbg::ToJdwpThreadStatus(ThreadState state) {
1871 switch (state) {
1872 case kBlocked:
1873 return JDWP::TS_MONITOR;
1874 case kNative:
1875 case kRunnable:
1876 case kSuspended:
1877 return JDWP::TS_RUNNING;
1878 case kSleeping:
1879 return JDWP::TS_SLEEPING;
1880 case kStarting:
1881 case kTerminated:
1882 return JDWP::TS_ZOMBIE;
1883 case kTimedWaiting:
1884 case kWaitingForDebuggerSend:
1885 case kWaitingForDebuggerSuspension:
1886 case kWaitingForDebuggerToAttach:
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01001887 case kWaitingForDeoptimization:
Jeff Hao920af3e2013-08-28 15:46:38 -07001888 case kWaitingForGcToComplete:
1889 case kWaitingForCheckPointsToRun:
1890 case kWaitingForJniOnLoad:
1891 case kWaitingForSignalCatcherOutput:
1892 case kWaitingInMainDebuggerLoop:
1893 case kWaitingInMainSignalCatcherLoop:
1894 case kWaitingPerformingGc:
1895 case kWaiting:
1896 return JDWP::TS_WAIT;
1897 // Don't add a 'default' here so the compiler can spot incompatible enum changes.
1898 }
1899 LOG(FATAL) << "Unknown thread state: " << state;
1900 return JDWP::TS_ZOMBIE;
1901}
1902
Sebastien Hertz52d131d2014-03-13 16:17:40 +01001903JDWP::JdwpError Dbg::GetThreadStatus(JDWP::ObjectId thread_id, JDWP::JdwpThreadStatus* pThreadStatus,
1904 JDWP::JdwpSuspendStatus* pSuspendStatus) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001905 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes499c5132011-11-17 14:55:11 -08001906
Elliott Hughes9e0c1752013-01-09 14:02:58 -08001907 *pSuspendStatus = JDWP::SUSPEND_STATUS_NOT_SUSPENDED;
1908
Ian Rogers50b35e22012-10-04 10:09:15 -07001909 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001910 Thread* thread;
1911 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1912 if (error != JDWP::ERR_NONE) {
1913 if (error == JDWP::ERR_THREAD_NOT_ALIVE) {
1914 *pThreadStatus = JDWP::TS_ZOMBIE;
Elliott Hughes221229c2013-01-08 18:17:50 -08001915 return JDWP::ERR_NONE;
1916 }
1917 return error;
Elliott Hughes499c5132011-11-17 14:55:11 -08001918 }
1919
Elliott Hughes9e0c1752013-01-09 14:02:58 -08001920 if (IsSuspendedForDebugger(soa, thread)) {
1921 *pSuspendStatus = JDWP::SUSPEND_STATUS_SUSPENDED;
Elliott Hughes499c5132011-11-17 14:55:11 -08001922 }
1923
Jeff Hao920af3e2013-08-28 15:46:38 -07001924 *pThreadStatus = ToJdwpThreadStatus(thread->GetState());
Elliott Hughes221229c2013-01-08 18:17:50 -08001925 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001926}
1927
Elliott Hughes221229c2013-01-08 18:17:50 -08001928JDWP::JdwpError Dbg::GetThreadDebugSuspendCount(JDWP::ObjectId thread_id, JDWP::ExpandBuf* pReply) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001929 ScopedObjectAccess soa(Thread::Current());
Ian Rogers50b35e22012-10-04 10:09:15 -07001930 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001931 Thread* thread;
1932 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1933 if (error != JDWP::ERR_NONE) {
1934 return error;
Elliott Hughes2435a572012-02-17 16:07:41 -08001935 }
Ian Rogers50b35e22012-10-04 10:09:15 -07001936 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001937 expandBufAdd4BE(pReply, thread->GetDebugSuspendCount());
Elliott Hughes2435a572012-02-17 16:07:41 -08001938 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001939}
1940
Elliott Hughesf9501702013-01-11 11:22:27 -08001941JDWP::JdwpError Dbg::Interrupt(JDWP::ObjectId thread_id) {
1942 ScopedObjectAccess soa(Thread::Current());
1943 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
1944 Thread* thread;
1945 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1946 if (error != JDWP::ERR_NONE) {
1947 return error;
1948 }
Ian Rogersdd7624d2014-03-14 17:43:00 -07001949 thread->Interrupt(soa.Self());
Elliott Hughesf9501702013-01-11 11:22:27 -08001950 return JDWP::ERR_NONE;
1951}
1952
Elliott Hughescaf76542012-06-28 16:08:22 -07001953void Dbg::GetThreads(JDWP::ObjectId thread_group_id, std::vector<JDWP::ObjectId>& thread_ids) {
Ian Rogers365c1022012-06-22 15:05:28 -07001954 class ThreadListVisitor {
1955 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001956 ThreadListVisitor(const ScopedObjectAccessUnchecked& soa, mirror::Object* desired_thread_group,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001957 std::vector<JDWP::ObjectId>& thread_ids)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001958 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
jeffhao0dfbb7e2012-11-28 15:26:03 -08001959 : soa_(soa), desired_thread_group_(desired_thread_group), thread_ids_(thread_ids) {}
Ian Rogers365c1022012-06-22 15:05:28 -07001960
Elliott Hughesa2155262011-11-16 16:26:58 -08001961 static void Visit(Thread* t, void* arg) {
1962 reinterpret_cast<ThreadListVisitor*>(arg)->Visit(t);
1963 }
1964
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001965 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1966 // annotalysis.
1967 void Visit(Thread* t) NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughesa2155262011-11-16 16:26:58 -08001968 if (t == Dbg::GetDebugThread()) {
1969 // Skip the JDWP thread. Some debuggers get bent out of shape when they can't suspend and
1970 // query all threads, so it's easier if we just don't tell them about this thread.
1971 return;
1972 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001973 mirror::Object* peer = t->GetPeer();
jeffhao0dfbb7e2012-11-28 15:26:03 -08001974 if (IsInDesiredThreadGroup(peer)) {
Ian Rogers120f1c72012-09-28 17:17:10 -07001975 thread_ids_.push_back(gRegistry->Add(peer));
Elliott Hughesa2155262011-11-16 16:26:58 -08001976 }
1977 }
1978
Ian Rogers365c1022012-06-22 15:05:28 -07001979 private:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001980 bool IsInDesiredThreadGroup(mirror::Object* peer)
jeffhao0dfbb7e2012-11-28 15:26:03 -08001981 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
jeffhao0dfbb7e2012-11-28 15:26:03 -08001982 // peer might be NULL if the thread is still starting up.
1983 if (peer == NULL) {
1984 // We can't tell the debugger about this thread yet.
1985 // TODO: if we identified threads to the debugger by their Thread*
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001986 // rather than their peer's mirror::Object*, we could fix this.
jeffhao0dfbb7e2012-11-28 15:26:03 -08001987 // Doing so might help us report ZOMBIE threads too.
1988 return false;
1989 }
jeffhaoc1e04902012-12-13 12:41:10 -08001990 // Do we want threads from all thread groups?
1991 if (desired_thread_group_ == NULL) {
1992 return true;
1993 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001994 mirror::Object* group = soa_.DecodeField(WellKnownClasses::java_lang_Thread_group)->GetObject(peer);
jeffhao0dfbb7e2012-11-28 15:26:03 -08001995 return (group == desired_thread_group_);
1996 }
1997
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07001998 const ScopedObjectAccessUnchecked& soa_;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001999 mirror::Object* const desired_thread_group_;
Elliott Hughescaf76542012-06-28 16:08:22 -07002000 std::vector<JDWP::ObjectId>& thread_ids_;
Elliott Hughesa2155262011-11-16 16:26:58 -08002001 };
2002
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002003 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002004 mirror::Object* thread_group = gRegistry->Get<mirror::Object*>(thread_group_id);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002005 ThreadListVisitor tlv(soa, thread_group, thread_ids);
Ian Rogers50b35e22012-10-04 10:09:15 -07002006 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughesf8349362012-06-18 15:00:06 -07002007 Runtime::Current()->GetThreadList()->ForEach(ThreadListVisitor::Visit, &tlv);
Elliott Hughescaf76542012-06-28 16:08:22 -07002008}
Elliott Hughesa2155262011-11-16 16:26:58 -08002009
Elliott Hughescaf76542012-06-28 16:08:22 -07002010void Dbg::GetChildThreadGroups(JDWP::ObjectId thread_group_id, std::vector<JDWP::ObjectId>& child_thread_group_ids) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002011 ScopedObjectAccess soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002012 mirror::Object* thread_group = gRegistry->Get<mirror::Object*>(thread_group_id);
Elliott Hughescaf76542012-06-28 16:08:22 -07002013
2014 // Get the ArrayList<ThreadGroup> "groups" out of this thread group...
Brian Carlstromea46f952013-07-30 01:26:50 -07002015 mirror::ArtField* groups_field = thread_group->GetClass()->FindInstanceField("groups", "Ljava/util/List;");
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002016 mirror::Object* groups_array_list = groups_field->GetObject(thread_group);
Elliott Hughescaf76542012-06-28 16:08:22 -07002017
2018 // Get the array and size out of the ArrayList<ThreadGroup>...
Brian Carlstromea46f952013-07-30 01:26:50 -07002019 mirror::ArtField* array_field = groups_array_list->GetClass()->FindInstanceField("array", "[Ljava/lang/Object;");
2020 mirror::ArtField* size_field = groups_array_list->GetClass()->FindInstanceField("size", "I");
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002021 mirror::ObjectArray<mirror::Object>* groups_array =
2022 array_field->GetObject(groups_array_list)->AsObjectArray<mirror::Object>();
Elliott Hughescaf76542012-06-28 16:08:22 -07002023 const int32_t size = size_field->GetInt(groups_array_list);
2024
2025 // Copy the first 'size' elements out of the array into the result.
2026 for (int32_t i = 0; i < size; ++i) {
2027 child_thread_group_ids.push_back(gRegistry->Add(groups_array->Get(i)));
Elliott Hughesa2155262011-11-16 16:26:58 -08002028 }
2029}
2030
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002031static int GetStackDepth(Thread* thread)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002032 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002033 struct CountStackDepthVisitor : public StackVisitor {
Brian Carlstrom93ba8932013-07-17 21:31:49 -07002034 explicit CountStackDepthVisitor(Thread* thread)
Ian Rogers7a22fa62013-01-23 12:16:16 -08002035 : StackVisitor(thread, NULL), depth(0) {}
Ian Rogers0399dde2012-06-06 17:09:28 -07002036
Elliott Hughes64f574f2013-02-20 14:57:12 -08002037 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2038 // annotalysis.
2039 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07002040 if (!GetMethod()->IsRuntimeMethod()) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -08002041 ++depth;
2042 }
Elliott Hughes530fa002012-03-12 11:44:49 -07002043 return true;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08002044 }
2045 size_t depth;
2046 };
Elliott Hughes08fc03a2012-06-26 17:34:00 -07002047
Ian Rogers7a22fa62013-01-23 12:16:16 -08002048 CountStackDepthVisitor visitor(thread);
Ian Rogers0399dde2012-06-06 17:09:28 -07002049 visitor.WalkStack();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08002050 return visitor.depth;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002051}
2052
Elliott Hughes221229c2013-01-08 18:17:50 -08002053JDWP::JdwpError Dbg::GetThreadFrameCount(JDWP::ObjectId thread_id, size_t& result) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002054 ScopedObjectAccess soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08002055 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002056 Thread* thread;
2057 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
2058 if (error != JDWP::ERR_NONE) {
2059 return error;
2060 }
Elliott Hughesf15f4a02013-01-09 10:09:38 -08002061 if (!IsSuspendedForDebugger(soa, thread)) {
2062 return JDWP::ERR_THREAD_NOT_SUSPENDED;
2063 }
Elliott Hughes221229c2013-01-08 18:17:50 -08002064 result = GetStackDepth(thread);
2065 return JDWP::ERR_NONE;
Elliott Hughes86964332012-02-15 19:37:42 -08002066}
2067
Ian Rogers306057f2012-11-26 12:45:53 -08002068JDWP::JdwpError Dbg::GetThreadFrames(JDWP::ObjectId thread_id, size_t start_frame,
2069 size_t frame_count, JDWP::ExpandBuf* buf) {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002070 class GetFrameVisitor : public StackVisitor {
2071 public:
Ian Rogers7a22fa62013-01-23 12:16:16 -08002072 GetFrameVisitor(Thread* thread, size_t start_frame, size_t frame_count, JDWP::ExpandBuf* buf)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002073 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08002074 : StackVisitor(thread, NULL), depth_(0),
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002075 start_frame_(start_frame), frame_count_(frame_count), buf_(buf) {
2076 expandBufAdd4BE(buf_, frame_count_);
Elliott Hughes03181a82011-11-17 17:22:21 -08002077 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002078
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002079 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2080 // annotalysis.
2081 virtual bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07002082 if (GetMethod()->IsRuntimeMethod()) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07002083 return true; // The debugger can't do anything useful with a frame that has no Method*.
Elliott Hughes03181a82011-11-17 17:22:21 -08002084 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002085 if (depth_ >= start_frame_ + frame_count_) {
Elliott Hughes530fa002012-03-12 11:44:49 -07002086 return false;
Elliott Hughes03181a82011-11-17 17:22:21 -08002087 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002088 if (depth_ >= start_frame_) {
2089 JDWP::FrameId frame_id(GetFrameId());
2090 JDWP::JdwpLocation location;
2091 SetLocation(location, GetMethod(), GetDexPc());
Ian Rogersef7d42f2014-01-06 12:55:46 -08002092 VLOG(jdwp) << StringPrintf(" Frame %3zd: id=%3" PRIu64 " ", depth_, frame_id) << location;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002093 expandBufAdd8BE(buf_, frame_id);
2094 expandBufAddLocation(buf_, location);
2095 }
2096 ++depth_;
Elliott Hughes530fa002012-03-12 11:44:49 -07002097 return true;
Elliott Hughes03181a82011-11-17 17:22:21 -08002098 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002099
2100 private:
2101 size_t depth_;
2102 const size_t start_frame_;
2103 const size_t frame_count_;
2104 JDWP::ExpandBuf* buf_;
Elliott Hughes03181a82011-11-17 17:22:21 -08002105 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002106
2107 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08002108 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002109 Thread* thread;
2110 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
2111 if (error != JDWP::ERR_NONE) {
2112 return error;
2113 }
Elliott Hughesf15f4a02013-01-09 10:09:38 -08002114 if (!IsSuspendedForDebugger(soa, thread)) {
2115 return JDWP::ERR_THREAD_NOT_SUSPENDED;
2116 }
Ian Rogers7a22fa62013-01-23 12:16:16 -08002117 GetFrameVisitor visitor(thread, start_frame, frame_count, buf);
Ian Rogers0399dde2012-06-06 17:09:28 -07002118 visitor.WalkStack();
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002119 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002120}
2121
2122JDWP::ObjectId Dbg::GetThreadSelfId() {
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07002123 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogerscfaa4552012-11-26 21:00:08 -08002124 return gRegistry->Add(soa.Self()->GetPeer());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002125}
2126
Elliott Hughes475fc232011-10-25 15:00:35 -07002127void Dbg::SuspendVM() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002128 Runtime::Current()->GetThreadList()->SuspendAllForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002129}
2130
2131void Dbg::ResumeVM() {
Elliott Hughesc61a2672012-06-21 14:52:29 -07002132 Runtime::Current()->GetThreadList()->UndoDebuggerSuspensions();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002133}
2134
Elliott Hughes221229c2013-01-08 18:17:50 -08002135JDWP::JdwpError Dbg::SuspendThread(JDWP::ObjectId thread_id, bool request_suspension) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002136 ScopedLocalRef<jobject> peer(Thread::Current()->GetJniEnv(), NULL);
2137 {
2138 ScopedObjectAccess soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002139 peer.reset(soa.AddLocalReference<jobject>(gRegistry->Get<mirror::Object*>(thread_id)));
Elliott Hughes4e235312011-12-02 11:34:15 -08002140 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002141 if (peer.get() == NULL) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002142 return JDWP::ERR_THREAD_NOT_ALIVE;
2143 }
2144 // Suspend thread to build stack trace.
Elliott Hughesf327e072013-01-09 16:01:26 -08002145 bool timed_out;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07002146 Thread* thread = ThreadList::SuspendThreadByPeer(peer.get(), request_suspension, true,
2147 &timed_out);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002148 if (thread != NULL) {
2149 return JDWP::ERR_NONE;
Elliott Hughesf327e072013-01-09 16:01:26 -08002150 } else if (timed_out) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002151 return JDWP::ERR_INTERNAL;
2152 } else {
2153 return JDWP::ERR_THREAD_NOT_ALIVE;
2154 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002155}
2156
Elliott Hughes221229c2013-01-08 18:17:50 -08002157void Dbg::ResumeThread(JDWP::ObjectId thread_id) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002158 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002159 mirror::Object* peer = gRegistry->Get<mirror::Object*>(thread_id);
jeffhaoa77f0f62012-12-05 17:19:31 -08002160 Thread* thread;
2161 {
2162 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
2163 thread = Thread::FromManagedThread(soa, peer);
2164 }
Elliott Hughes4e235312011-12-02 11:34:15 -08002165 if (thread == NULL) {
2166 LOG(WARNING) << "No such thread for resume: " << peer;
2167 return;
2168 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002169 bool needs_resume;
2170 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002171 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002172 needs_resume = thread->GetSuspendCount() > 0;
2173 }
2174 if (needs_resume) {
Elliott Hughes546b9862012-06-20 16:06:13 -07002175 Runtime::Current()->GetThreadList()->Resume(thread, true);
2176 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002177}
2178
2179void Dbg::SuspendSelf() {
Elliott Hughes475fc232011-10-25 15:00:35 -07002180 Runtime::Current()->GetThreadList()->SuspendSelfForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002181}
2182
Ian Rogers0399dde2012-06-06 17:09:28 -07002183struct GetThisVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -08002184 GetThisVisitor(Thread* thread, Context* context, JDWP::FrameId frame_id)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002185 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08002186 : StackVisitor(thread, context), this_object(NULL), frame_id(frame_id) {}
Ian Rogers0399dde2012-06-06 17:09:28 -07002187
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002188 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2189 // annotalysis.
2190 virtual bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002191 if (frame_id != GetFrameId()) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002192 return true; // continue
Ian Rogers0399dde2012-06-06 17:09:28 -07002193 } else {
Ian Rogers62d6c772013-02-27 08:32:07 -08002194 this_object = GetThisObject();
2195 return false;
Ian Rogers0399dde2012-06-06 17:09:28 -07002196 }
Elliott Hughes86b00102011-12-05 17:54:26 -08002197 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002198
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002199 mirror::Object* this_object;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002200 JDWP::FrameId frame_id;
Ian Rogers0399dde2012-06-06 17:09:28 -07002201};
2202
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002203JDWP::JdwpError Dbg::GetThisObject(JDWP::ObjectId thread_id, JDWP::FrameId frame_id,
2204 JDWP::ObjectId* result) {
2205 ScopedObjectAccessUnchecked soa(Thread::Current());
2206 Thread* thread;
2207 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002208 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002209 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
2210 if (error != JDWP::ERR_NONE) {
2211 return error;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002212 }
Elliott Hughes9e0c1752013-01-09 14:02:58 -08002213 if (!IsSuspendedForDebugger(soa, thread)) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002214 return JDWP::ERR_THREAD_NOT_SUSPENDED;
2215 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002216 }
Elliott Hughescaf76542012-06-28 16:08:22 -07002217 UniquePtr<Context> context(Context::Create());
Ian Rogers7a22fa62013-01-23 12:16:16 -08002218 GetThisVisitor visitor(thread, context.get(), frame_id);
Ian Rogers0399dde2012-06-06 17:09:28 -07002219 visitor.WalkStack();
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002220 *result = gRegistry->Add(visitor.this_object);
2221 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002222}
2223
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002224JDWP::JdwpError Dbg::GetLocalValue(JDWP::ObjectId thread_id, JDWP::FrameId frame_id, int slot,
2225 JDWP::JdwpTag tag, uint8_t* buf, size_t width) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002226 struct GetLocalVisitor : public StackVisitor {
Ian Rogers98379392014-02-24 16:53:16 -08002227 GetLocalVisitor(const ScopedObjectAccessUnchecked& soa, Thread* thread, Context* context,
2228 JDWP::FrameId frame_id, int slot, JDWP::JdwpTag tag, uint8_t* buf, size_t width)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002229 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers98379392014-02-24 16:53:16 -08002230 : StackVisitor(thread, context), soa_(soa), frame_id_(frame_id), slot_(slot), tag_(tag),
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002231 buf_(buf), width_(width), error_(JDWP::ERR_NONE) {}
Ian Rogersca190662012-06-26 15:45:57 -07002232
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002233 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2234 // annotalysis.
2235 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07002236 if (GetFrameId() != frame_id_) {
2237 return true; // Not our frame, carry on.
Elliott Hughesdbb40792011-11-18 17:05:22 -08002238 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002239 // TODO: check that the tag is compatible with the actual type of the slot!
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002240 // TODO: check slot is valid for this method or return INVALID_SLOT error.
Brian Carlstromea46f952013-07-30 01:26:50 -07002241 mirror::ArtMethod* m = GetMethod();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002242 if (m->IsNative()) {
2243 // We can't read local value from native method.
2244 error_ = JDWP::ERR_OPAQUE_FRAME;
2245 return false;
2246 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002247 uint16_t reg = DemangleSlot(slot_, m);
Elliott Hughesdbb40792011-11-18 17:05:22 -08002248
Ian Rogers0399dde2012-06-06 17:09:28 -07002249 switch (tag_) {
2250 case JDWP::JT_BOOLEAN:
2251 {
2252 CHECK_EQ(width_, 1U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002253 uint32_t intVal = GetVReg(m, reg, kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002254 VLOG(jdwp) << "get boolean local " << reg << " = " << intVal;
2255 JDWP::Set1(buf_+1, intVal != 0);
2256 }
2257 break;
2258 case JDWP::JT_BYTE:
2259 {
2260 CHECK_EQ(width_, 1U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002261 uint32_t intVal = GetVReg(m, reg, kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002262 VLOG(jdwp) << "get byte local " << reg << " = " << intVal;
2263 JDWP::Set1(buf_+1, intVal);
2264 }
2265 break;
2266 case JDWP::JT_SHORT:
2267 case JDWP::JT_CHAR:
2268 {
2269 CHECK_EQ(width_, 2U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002270 uint32_t intVal = GetVReg(m, reg, kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002271 VLOG(jdwp) << "get short/char local " << reg << " = " << intVal;
2272 JDWP::Set2BE(buf_+1, intVal);
2273 }
2274 break;
2275 case JDWP::JT_INT:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002276 {
2277 CHECK_EQ(width_, 4U);
2278 uint32_t intVal = GetVReg(m, reg, kIntVReg);
2279 VLOG(jdwp) << "get int local " << reg << " = " << intVal;
2280 JDWP::Set4BE(buf_+1, intVal);
2281 }
2282 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002283 case JDWP::JT_FLOAT:
2284 {
2285 CHECK_EQ(width_, 4U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002286 uint32_t intVal = GetVReg(m, reg, kFloatVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002287 VLOG(jdwp) << "get int/float local " << reg << " = " << intVal;
2288 JDWP::Set4BE(buf_+1, intVal);
2289 }
2290 break;
2291 case JDWP::JT_ARRAY:
2292 {
2293 CHECK_EQ(width_, sizeof(JDWP::ObjectId));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002294 mirror::Object* o = reinterpret_cast<mirror::Object*>(GetVReg(m, reg, kReferenceVReg));
Ian Rogers0399dde2012-06-06 17:09:28 -07002295 VLOG(jdwp) << "get array local " << reg << " = " << o;
Mathieu Chartier590fee92013-09-13 13:46:47 -07002296 if (!Runtime::Current()->GetHeap()->IsValidObjectAddress(o)) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002297 LOG(FATAL) << "Register " << reg << " expected to hold array: " << o;
2298 }
2299 JDWP::SetObjectId(buf_+1, gRegistry->Add(o));
2300 }
2301 break;
2302 case JDWP::JT_CLASS_LOADER:
2303 case JDWP::JT_CLASS_OBJECT:
2304 case JDWP::JT_OBJECT:
2305 case JDWP::JT_STRING:
2306 case JDWP::JT_THREAD:
2307 case JDWP::JT_THREAD_GROUP:
2308 {
2309 CHECK_EQ(width_, sizeof(JDWP::ObjectId));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002310 mirror::Object* o = reinterpret_cast<mirror::Object*>(GetVReg(m, reg, kReferenceVReg));
Ian Rogers0399dde2012-06-06 17:09:28 -07002311 VLOG(jdwp) << "get object local " << reg << " = " << o;
Mathieu Chartier590fee92013-09-13 13:46:47 -07002312 if (!Runtime::Current()->GetHeap()->IsValidObjectAddress(o)) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002313 LOG(FATAL) << "Register " << reg << " expected to hold object: " << o;
2314 }
Ian Rogers98379392014-02-24 16:53:16 -08002315 tag_ = TagFromObject(soa_, o);
Ian Rogers0399dde2012-06-06 17:09:28 -07002316 JDWP::SetObjectId(buf_+1, gRegistry->Add(o));
2317 }
2318 break;
2319 case JDWP::JT_DOUBLE:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002320 {
2321 CHECK_EQ(width_, 8U);
2322 uint32_t lo = GetVReg(m, reg, kDoubleLoVReg);
2323 uint64_t hi = GetVReg(m, reg + 1, kDoubleHiVReg);
2324 uint64_t longVal = (hi << 32) | lo;
2325 VLOG(jdwp) << "get double/long local " << hi << ":" << lo << " = " << longVal;
2326 JDWP::Set8BE(buf_+1, longVal);
2327 }
2328 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002329 case JDWP::JT_LONG:
2330 {
2331 CHECK_EQ(width_, 8U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002332 uint32_t lo = GetVReg(m, reg, kLongLoVReg);
2333 uint64_t hi = GetVReg(m, reg + 1, kLongHiVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002334 uint64_t longVal = (hi << 32) | lo;
2335 VLOG(jdwp) << "get double/long local " << hi << ":" << lo << " = " << longVal;
2336 JDWP::Set8BE(buf_+1, longVal);
2337 }
2338 break;
2339 default:
2340 LOG(FATAL) << "Unknown tag " << tag_;
2341 break;
2342 }
2343
2344 // Prepend tag, which may have been updated.
2345 JDWP::Set1(buf_, tag_);
2346 return false;
2347 }
Ian Rogers98379392014-02-24 16:53:16 -08002348 const ScopedObjectAccessUnchecked& soa_;
Ian Rogers0399dde2012-06-06 17:09:28 -07002349 const JDWP::FrameId frame_id_;
2350 const int slot_;
2351 JDWP::JdwpTag tag_;
2352 uint8_t* const buf_;
2353 const size_t width_;
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002354 JDWP::JdwpError error_;
Ian Rogers0399dde2012-06-06 17:09:28 -07002355 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002356
2357 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08002358 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002359 Thread* thread;
2360 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
2361 if (error != JDWP::ERR_NONE) {
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002362 return error;
Elliott Hughes221229c2013-01-08 18:17:50 -08002363 }
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002364 // TODO check thread is suspended by the debugger ?
Ian Rogers0399dde2012-06-06 17:09:28 -07002365 UniquePtr<Context> context(Context::Create());
Ian Rogers98379392014-02-24 16:53:16 -08002366 GetLocalVisitor visitor(soa, thread, context.get(), frame_id, slot, tag, buf, width);
Ian Rogers0399dde2012-06-06 17:09:28 -07002367 visitor.WalkStack();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002368 return visitor.error_;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002369}
2370
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002371JDWP::JdwpError Dbg::SetLocalValue(JDWP::ObjectId thread_id, JDWP::FrameId frame_id, int slot,
2372 JDWP::JdwpTag tag, uint64_t value, size_t width) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002373 struct SetLocalVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -08002374 SetLocalVisitor(Thread* thread, Context* context,
Ian Rogers0399dde2012-06-06 17:09:28 -07002375 JDWP::FrameId frame_id, int slot, JDWP::JdwpTag tag, uint64_t value,
Ian Rogersca190662012-06-26 15:45:57 -07002376 size_t width)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002377 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08002378 : StackVisitor(thread, context),
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002379 frame_id_(frame_id), slot_(slot), tag_(tag), value_(value), width_(width),
2380 error_(JDWP::ERR_NONE) {}
Ian Rogersca190662012-06-26 15:45:57 -07002381
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002382 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2383 // annotalysis.
2384 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07002385 if (GetFrameId() != frame_id_) {
2386 return true; // Not our frame, carry on.
2387 }
2388 // TODO: check that the tag is compatible with the actual type of the slot!
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002389 // TODO: check slot is valid for this method or return INVALID_SLOT error.
Brian Carlstromea46f952013-07-30 01:26:50 -07002390 mirror::ArtMethod* m = GetMethod();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002391 if (m->IsNative()) {
2392 // We can't read local value from native method.
2393 error_ = JDWP::ERR_OPAQUE_FRAME;
2394 return false;
2395 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002396 uint16_t reg = DemangleSlot(slot_, m);
2397
2398 switch (tag_) {
2399 case JDWP::JT_BOOLEAN:
2400 case JDWP::JT_BYTE:
2401 CHECK_EQ(width_, 1U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002402 SetVReg(m, reg, static_cast<uint32_t>(value_), kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002403 break;
2404 case JDWP::JT_SHORT:
2405 case JDWP::JT_CHAR:
2406 CHECK_EQ(width_, 2U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002407 SetVReg(m, reg, static_cast<uint32_t>(value_), kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002408 break;
2409 case JDWP::JT_INT:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002410 CHECK_EQ(width_, 4U);
2411 SetVReg(m, reg, static_cast<uint32_t>(value_), kIntVReg);
2412 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002413 case JDWP::JT_FLOAT:
2414 CHECK_EQ(width_, 4U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002415 SetVReg(m, reg, static_cast<uint32_t>(value_), kFloatVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002416 break;
2417 case JDWP::JT_ARRAY:
2418 case JDWP::JT_OBJECT:
2419 case JDWP::JT_STRING:
2420 {
2421 CHECK_EQ(width_, sizeof(JDWP::ObjectId));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002422 mirror::Object* o = gRegistry->Get<mirror::Object*>(static_cast<JDWP::ObjectId>(value_));
Elliott Hughes64f574f2013-02-20 14:57:12 -08002423 if (o == ObjectRegistry::kInvalidObject) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002424 UNIMPLEMENTED(FATAL) << "return an error code when given an invalid object to store";
2425 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002426 SetVReg(m, reg, static_cast<uint32_t>(reinterpret_cast<uintptr_t>(o)), kReferenceVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002427 }
2428 break;
2429 case JDWP::JT_DOUBLE:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002430 CHECK_EQ(width_, 8U);
2431 SetVReg(m, reg, static_cast<uint32_t>(value_), kDoubleLoVReg);
2432 SetVReg(m, reg + 1, static_cast<uint32_t>(value_ >> 32), kDoubleHiVReg);
2433 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002434 case JDWP::JT_LONG:
2435 CHECK_EQ(width_, 8U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002436 SetVReg(m, reg, static_cast<uint32_t>(value_), kLongLoVReg);
2437 SetVReg(m, reg + 1, static_cast<uint32_t>(value_ >> 32), kLongHiVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002438 break;
2439 default:
2440 LOG(FATAL) << "Unknown tag " << tag_;
2441 break;
2442 }
2443 return false;
2444 }
2445
2446 const JDWP::FrameId frame_id_;
2447 const int slot_;
2448 const JDWP::JdwpTag tag_;
2449 const uint64_t value_;
2450 const size_t width_;
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002451 JDWP::JdwpError error_;
Ian Rogers0399dde2012-06-06 17:09:28 -07002452 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002453
2454 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08002455 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002456 Thread* thread;
2457 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
2458 if (error != JDWP::ERR_NONE) {
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002459 return error;
Elliott Hughes221229c2013-01-08 18:17:50 -08002460 }
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002461 // TODO check thread is suspended by the debugger ?
Elliott Hughes08fc03a2012-06-26 17:34:00 -07002462 UniquePtr<Context> context(Context::Create());
Ian Rogers7a22fa62013-01-23 12:16:16 -08002463 SetLocalVisitor visitor(thread, context.get(), frame_id, slot, tag, value, width);
Ian Rogers0399dde2012-06-06 17:09:28 -07002464 visitor.WalkStack();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002465 return visitor.error_;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002466}
2467
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002468JDWP::ObjectId Dbg::GetThisObjectIdForEvent(mirror::Object* this_object) {
2469 // If 'this_object' isn't already in the registry, we know that we're not looking for it, so
2470 // there's no point adding it to the registry and burning through ids.
2471 // When registering an event request with an instance filter, we've been given an existing object
2472 // id so it must already be present in the registry when the event fires.
2473 JDWP::ObjectId this_id = 0;
2474 if (this_object != nullptr && gRegistry->Contains(this_object)) {
2475 this_id = gRegistry->Add(this_object);
2476 }
2477 return this_id;
2478}
2479
Ian Rogersef7d42f2014-01-06 12:55:46 -08002480void Dbg::PostLocationEvent(mirror::ArtMethod* m, int dex_pc, mirror::Object* this_object,
Jeff Hao579b0242013-11-18 13:16:49 -08002481 int event_flags, const JValue* return_value) {
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002482 if (!IsDebuggerActive()) {
2483 return;
2484 }
2485 DCHECK(m != nullptr);
2486 DCHECK_EQ(m->IsStatic(), this_object == nullptr);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002487 JDWP::JdwpLocation location;
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002488 SetLocation(location, m, dex_pc);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002489
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002490 // We need 'this' for InstanceOnly filters only.
2491 JDWP::ObjectId this_id = GetThisObjectIdForEvent(this_object);
Jeff Hao579b0242013-11-18 13:16:49 -08002492 gJdwpState->PostLocationEvent(&location, this_id, event_flags, return_value);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002493}
2494
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002495void Dbg::PostFieldAccessEvent(mirror::ArtMethod* m, int dex_pc,
2496 mirror::Object* this_object, mirror::ArtField* f) {
2497 if (!IsDebuggerActive()) {
2498 return;
2499 }
2500 DCHECK(m != nullptr);
2501 DCHECK(f != nullptr);
2502 JDWP::JdwpLocation location;
2503 SetLocation(location, m, dex_pc);
2504
2505 JDWP::RefTypeId type_id = gRegistry->AddRefType(f->GetDeclaringClass());
2506 JDWP::FieldId field_id = ToFieldId(f);
2507 JDWP::ObjectId this_id = gRegistry->Add(this_object);
2508
2509 gJdwpState->PostFieldEvent(&location, type_id, field_id, this_id, nullptr, false);
2510}
2511
2512void Dbg::PostFieldModificationEvent(mirror::ArtMethod* m, int dex_pc,
2513 mirror::Object* this_object, mirror::ArtField* f,
2514 const JValue* field_value) {
2515 if (!IsDebuggerActive()) {
2516 return;
2517 }
2518 DCHECK(m != nullptr);
2519 DCHECK(f != nullptr);
2520 DCHECK(field_value != nullptr);
2521 JDWP::JdwpLocation location;
2522 SetLocation(location, m, dex_pc);
2523
2524 JDWP::RefTypeId type_id = gRegistry->AddRefType(f->GetDeclaringClass());
2525 JDWP::FieldId field_id = ToFieldId(f);
2526 JDWP::ObjectId this_id = gRegistry->Add(this_object);
2527
2528 gJdwpState->PostFieldEvent(&location, type_id, field_id, this_id, field_value, true);
2529}
2530
2531void Dbg::PostException(const ThrowLocation& throw_location,
Brian Carlstromea46f952013-07-30 01:26:50 -07002532 mirror::ArtMethod* catch_method,
Elliott Hughes64f574f2013-02-20 14:57:12 -08002533 uint32_t catch_dex_pc, mirror::Throwable* exception_object) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002534 if (!IsDebuggerActive()) {
Ian Rogers0ad5bb82011-12-07 10:16:32 -08002535 return;
2536 }
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002537
Ian Rogers62d6c772013-02-27 08:32:07 -08002538 JDWP::JdwpLocation jdwp_throw_location;
2539 SetLocation(jdwp_throw_location, throw_location.GetMethod(), throw_location.GetDexPc());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002540 JDWP::JdwpLocation catch_location;
Elliott Hughescaf76542012-06-28 16:08:22 -07002541 SetLocation(catch_location, catch_method, catch_dex_pc);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002542
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +02002543 // We need 'this' for InstanceOnly filters only.
2544 JDWP::ObjectId this_id = GetThisObjectIdForEvent(throw_location.GetThis());
Elliott Hughes64f574f2013-02-20 14:57:12 -08002545 JDWP::ObjectId exception_id = gRegistry->Add(exception_object);
2546 JDWP::RefTypeId exception_class_id = gRegistry->AddRefType(exception_object->GetClass());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002547
Ian Rogers62d6c772013-02-27 08:32:07 -08002548 gJdwpState->PostException(&jdwp_throw_location, exception_id, exception_class_id, &catch_location,
2549 this_id);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002550}
2551
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002552void Dbg::PostClassPrepare(mirror::Class* c) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002553 if (!IsDebuggerActive()) {
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002554 return;
2555 }
2556
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08002557 // OLD-TODO - we currently always send both "verified" and "prepared" since
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002558 // debuggers seem to like that. There might be some advantage to honesty,
2559 // since the class may not yet be verified.
2560 int state = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
Sebastien Hertz4d8fd492014-03-28 16:29:41 +01002561 JDWP::JdwpTypeTag tag = GetTypeTag(c);
Ian Rogersfc0e94b2013-09-23 23:51:32 -07002562 gJdwpState->PostClassPrepare(tag, gRegistry->Add(c),
Ian Rogersdfb325e2013-10-30 01:00:44 -07002563 ClassHelper(c).GetDescriptor(), state);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002564}
2565
Ian Rogers62d6c772013-02-27 08:32:07 -08002566void Dbg::UpdateDebugger(Thread* thread, mirror::Object* this_object,
Ian Rogersef7d42f2014-01-06 12:55:46 -08002567 mirror::ArtMethod* m, uint32_t dex_pc) {
Ian Rogers62d6c772013-02-27 08:32:07 -08002568 if (!IsDebuggerActive() || dex_pc == static_cast<uint32_t>(-2) /* fake method exit */) {
Elliott Hughes2aa2e392012-02-17 17:15:43 -08002569 return;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002570 }
2571
Elliott Hughes2aa2e392012-02-17 17:15:43 -08002572 int event_flags = 0;
2573
Elliott Hughes86964332012-02-15 19:37:42 -08002574 if (IsBreakpoint(m, dex_pc)) {
2575 event_flags |= kBreakpoint;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002576 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002577
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002578 // If the debugger is single-stepping one of our threads, check to
2579 // see if we're that thread and we've reached a step point.
2580 const SingleStepControl* single_step_control = thread->GetSingleStepControl();
2581 DCHECK(single_step_control != nullptr);
2582 if (single_step_control->is_active) {
2583 CHECK(!m->IsNative());
2584 if (single_step_control->step_depth == JDWP::SD_INTO) {
2585 // Step into method calls. We break when the line number
2586 // or method pointer changes. If we're in SS_MIN mode, we
2587 // always stop.
2588 if (single_step_control->method != m) {
2589 event_flags |= kSingleStep;
2590 VLOG(jdwp) << "SS new method";
2591 } else if (single_step_control->step_size == JDWP::SS_MIN) {
2592 event_flags |= kSingleStep;
2593 VLOG(jdwp) << "SS new instruction";
2594 } else if (single_step_control->dex_pcs.find(dex_pc) == single_step_control->dex_pcs.end()) {
2595 event_flags |= kSingleStep;
2596 VLOG(jdwp) << "SS new line";
2597 }
2598 } else if (single_step_control->step_depth == JDWP::SD_OVER) {
2599 // Step over method calls. We break when the line number is
2600 // different and the frame depth is <= the original frame
2601 // depth. (We can't just compare on the method, because we
2602 // might get unrolled past it by an exception, and it's tricky
2603 // to identify recursion.)
2604
2605 int stack_depth = GetStackDepth(thread);
2606
2607 if (stack_depth < single_step_control->stack_depth) {
2608 // Popped up one or more frames, always trigger.
2609 event_flags |= kSingleStep;
2610 VLOG(jdwp) << "SS method pop";
2611 } else if (stack_depth == single_step_control->stack_depth) {
2612 // Same depth, see if we moved.
2613 if (single_step_control->step_size == JDWP::SS_MIN) {
Elliott Hughes86964332012-02-15 19:37:42 -08002614 event_flags |= kSingleStep;
2615 VLOG(jdwp) << "SS new instruction";
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002616 } else if (single_step_control->dex_pcs.find(dex_pc) == single_step_control->dex_pcs.end()) {
Elliott Hughes2435a572012-02-17 16:07:41 -08002617 event_flags |= kSingleStep;
2618 VLOG(jdwp) << "SS new line";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002619 }
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002620 }
2621 } else {
2622 CHECK_EQ(single_step_control->step_depth, JDWP::SD_OUT);
2623 // Return from the current method. We break when the frame
2624 // depth pops up.
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002625
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002626 // This differs from the "method exit" break in that it stops
2627 // with the PC at the next instruction in the returned-to
2628 // function, rather than the end of the returning function.
Elliott Hughes86964332012-02-15 19:37:42 -08002629
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002630 int stack_depth = GetStackDepth(thread);
2631 if (stack_depth < single_step_control->stack_depth) {
2632 event_flags |= kSingleStep;
2633 VLOG(jdwp) << "SS method pop";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002634 }
2635 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002636 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002637
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002638 // If there's something interesting going on, see if it matches one
2639 // of the debugger filters.
2640 if (event_flags != 0) {
Jeff Hao579b0242013-11-18 13:16:49 -08002641 Dbg::PostLocationEvent(m, dex_pc, this_object, event_flags, nullptr);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002642 }
2643}
2644
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002645// Process request while all mutator threads are suspended.
2646void Dbg::ProcessDeoptimizationRequest(const DeoptimizationRequest& request) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002647 instrumentation::Instrumentation* instrumentation = Runtime::Current()->GetInstrumentation();
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002648 switch (request.kind) {
2649 case DeoptimizationRequest::kNothing:
2650 LOG(WARNING) << "Ignoring empty deoptimization request.";
2651 break;
2652 case DeoptimizationRequest::kFullDeoptimization:
2653 VLOG(jdwp) << "Deoptimize the world";
2654 instrumentation->DeoptimizeEverything();
2655 break;
2656 case DeoptimizationRequest::kFullUndeoptimization:
2657 VLOG(jdwp) << "Undeoptimize the world";
2658 instrumentation->UndeoptimizeEverything();
2659 break;
2660 case DeoptimizationRequest::kSelectiveDeoptimization:
2661 VLOG(jdwp) << "Deoptimize method " << PrettyMethod(request.method);
2662 instrumentation->Deoptimize(request.method);
2663 break;
2664 case DeoptimizationRequest::kSelectiveUndeoptimization:
2665 VLOG(jdwp) << "Undeoptimize method " << PrettyMethod(request.method);
2666 instrumentation->Undeoptimize(request.method);
2667 break;
2668 default:
2669 LOG(FATAL) << "Unsupported deoptimization request kind " << request.kind;
2670 break;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002671 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002672}
2673
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002674void Dbg::RequestDeoptimization(const DeoptimizationRequest& req) {
2675 if (req.kind == DeoptimizationRequest::kNothing) {
2676 // Nothing to do.
2677 return;
2678 }
2679 MutexLock mu(Thread::Current(), *deoptimization_lock_);
2680 switch (req.kind) {
2681 case DeoptimizationRequest::kFullDeoptimization: {
2682 DCHECK(req.method == nullptr);
2683 if (full_deoptimization_event_count_ == 0) {
2684 VLOG(jdwp) << "Request full deoptimization";
2685 deoptimization_requests_.push_back(req);
2686 }
2687 ++full_deoptimization_event_count_;
2688 break;
2689 }
2690 case DeoptimizationRequest::kFullUndeoptimization: {
2691 DCHECK(req.method == nullptr);
2692 DCHECK_GT(full_deoptimization_event_count_, 0U);
2693 --full_deoptimization_event_count_;
2694 if (full_deoptimization_event_count_ == 0) {
2695 VLOG(jdwp) << "Request full undeoptimization";
2696 deoptimization_requests_.push_back(req);
2697 }
2698 break;
2699 }
2700 case DeoptimizationRequest::kSelectiveDeoptimization: {
2701 DCHECK(req.method != nullptr);
2702 VLOG(jdwp) << "Request deoptimization of " << PrettyMethod(req.method);
2703 deoptimization_requests_.push_back(req);
2704 break;
2705 }
2706 case DeoptimizationRequest::kSelectiveUndeoptimization: {
2707 DCHECK(req.method != nullptr);
2708 VLOG(jdwp) << "Request undeoptimization of " << PrettyMethod(req.method);
2709 deoptimization_requests_.push_back(req);
2710 break;
2711 }
2712 default: {
2713 LOG(FATAL) << "Unknown deoptimization request kind " << req.kind;
2714 break;
2715 }
2716 }
2717}
2718
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002719void Dbg::ManageDeoptimization() {
2720 Thread* const self = Thread::Current();
2721 {
2722 // Avoid suspend/resume if there is no pending request.
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002723 MutexLock mu(self, *deoptimization_lock_);
2724 if (deoptimization_requests_.empty()) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002725 return;
2726 }
2727 }
2728 CHECK_EQ(self->GetState(), kRunnable);
2729 self->TransitionFromRunnableToSuspended(kWaitingForDeoptimization);
2730 // We need to suspend mutator threads first.
2731 Runtime* const runtime = Runtime::Current();
2732 runtime->GetThreadList()->SuspendAll();
2733 const ThreadState old_state = self->SetStateUnsafe(kRunnable);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002734 {
2735 MutexLock mu(self, *deoptimization_lock_);
2736 for (const DeoptimizationRequest& request : deoptimization_requests_) {
2737 ProcessDeoptimizationRequest(request);
2738 }
2739 deoptimization_requests_.clear();
2740 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002741 CHECK_EQ(self->SetStateUnsafe(old_state), kRunnable);
2742 runtime->GetThreadList()->ResumeAll();
2743 self->TransitionFromSuspendedToRunnable();
2744}
2745
Sebastien Hertza76a6d42014-03-20 16:40:17 +01002746static bool IsMethodPossiblyInlined(Thread* self, mirror::ArtMethod* m)
2747 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2748 MethodHelper mh(m);
2749 const DexFile::CodeItem* code_item = mh.GetCodeItem();
2750 if (code_item == nullptr) {
2751 // TODO We should not be asked to watch location in a native or abstract method so the code item
2752 // should never be null. We could just check we never encounter this case.
2753 return false;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002754 }
Sebastien Hertza76a6d42014-03-20 16:40:17 +01002755 SirtRef<mirror::DexCache> dex_cache(self, mh.GetDexCache());
2756 SirtRef<mirror::ClassLoader> class_loader(self, mh.GetClassLoader());
2757 verifier::MethodVerifier verifier(&mh.GetDexFile(), &dex_cache, &class_loader,
2758 &mh.GetClassDef(), code_item, m->GetDexMethodIndex(), m,
2759 m->GetAccessFlags(), false, true);
2760 // Note: we don't need to verify the method.
2761 return InlineMethodAnalyser::AnalyseMethodCode(&verifier, nullptr);
2762}
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002763
Sebastien Hertza76a6d42014-03-20 16:40:17 +01002764static const Breakpoint* FindFirstBreakpointForMethod(mirror::ArtMethod* m)
2765 EXCLUSIVE_LOCKS_REQUIRED(Locks::breakpoint_lock_) {
2766 for (const Breakpoint& breakpoint : gBreakpoints) {
2767 if (breakpoint.method == m) {
2768 return &breakpoint;
2769 }
2770 }
2771 return nullptr;
2772}
2773
2774// Sanity checks all existing breakpoints on the same method.
2775static void SanityCheckExistingBreakpoints(mirror::ArtMethod* m, bool need_full_deoptimization)
2776 EXCLUSIVE_LOCKS_REQUIRED(Locks::breakpoint_lock_) {
2777 if (kIsDebugBuild) {
2778 for (const Breakpoint& breakpoint : gBreakpoints) {
2779 CHECK_EQ(need_full_deoptimization, breakpoint.need_full_deoptimization);
2780 }
2781 if (need_full_deoptimization) {
2782 // We should have deoptimized everything but not "selectively" deoptimized this method.
2783 CHECK(Runtime::Current()->GetInstrumentation()->AreAllMethodsDeoptimized());
2784 CHECK(!Runtime::Current()->GetInstrumentation()->IsDeoptimized(m));
2785 } else {
2786 // We should have "selectively" deoptimized this method.
2787 // Note: while we have not deoptimized everything for this method, we may have done it for
2788 // another event.
2789 CHECK(Runtime::Current()->GetInstrumentation()->IsDeoptimized(m));
2790 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002791 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002792}
2793
Sebastien Hertza76a6d42014-03-20 16:40:17 +01002794// Installs a breakpoint at the specified location. Also indicates through the deoptimization
2795// request if we need to deoptimize.
2796void Dbg::WatchLocation(const JDWP::JdwpLocation* location, DeoptimizationRequest* req) {
2797 Thread* const self = Thread::Current();
Brian Carlstromea46f952013-07-30 01:26:50 -07002798 mirror::ArtMethod* m = FromMethodId(location->method_id);
Sebastien Hertza76a6d42014-03-20 16:40:17 +01002799 DCHECK(m != nullptr) << "No method for method id " << location->method_id;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002800
Sebastien Hertza76a6d42014-03-20 16:40:17 +01002801 MutexLock mu(self, *Locks::breakpoint_lock_);
2802 const Breakpoint* const existing_breakpoint = FindFirstBreakpointForMethod(m);
2803 bool need_full_deoptimization;
2804 if (existing_breakpoint == nullptr) {
2805 // There is no breakpoint on this method yet: we need to deoptimize. If this method may be
2806 // inlined, we deoptimize everything; otherwise we deoptimize only this method.
2807 need_full_deoptimization = IsMethodPossiblyInlined(self, m);
2808 if (need_full_deoptimization) {
2809 req->kind = DeoptimizationRequest::kFullDeoptimization;
2810 req->method = nullptr;
2811 } else {
2812 req->kind = DeoptimizationRequest::kSelectiveDeoptimization;
2813 req->method = m;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002814 }
Sebastien Hertza76a6d42014-03-20 16:40:17 +01002815 } else {
2816 // There is at least one breakpoint for this method: we don't need to deoptimize.
2817 req->kind = DeoptimizationRequest::kNothing;
2818 req->method = nullptr;
2819
2820 need_full_deoptimization = existing_breakpoint->need_full_deoptimization;
2821 SanityCheckExistingBreakpoints(m, need_full_deoptimization);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002822 }
2823
Sebastien Hertza76a6d42014-03-20 16:40:17 +01002824 gBreakpoints.push_back(Breakpoint(m, location->dex_pc, need_full_deoptimization));
2825 VLOG(jdwp) << "Set breakpoint #" << (gBreakpoints.size() - 1) << ": "
2826 << gBreakpoints[gBreakpoints.size() - 1];
2827}
2828
2829// Uninstalls a breakpoint at the specified location. Also indicates through the deoptimization
2830// request if we need to undeoptimize.
2831void Dbg::UnwatchLocation(const JDWP::JdwpLocation* location, DeoptimizationRequest* req) {
2832 mirror::ArtMethod* m = FromMethodId(location->method_id);
2833 DCHECK(m != nullptr) << "No method for method id " << location->method_id;
2834
2835 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
2836 bool need_full_deoptimization = false;
2837 for (size_t i = 0, e = gBreakpoints.size(); i < e; ++i) {
2838 if (gBreakpoints[i].method == m && gBreakpoints[i].dex_pc == location->dex_pc) {
2839 VLOG(jdwp) << "Removed breakpoint #" << i << ": " << gBreakpoints[i];
2840 need_full_deoptimization = gBreakpoints[i].need_full_deoptimization;
2841 DCHECK_NE(need_full_deoptimization, Runtime::Current()->GetInstrumentation()->IsDeoptimized(m));
2842 gBreakpoints.erase(gBreakpoints.begin() + i);
2843 break;
2844 }
2845 }
2846 const Breakpoint* const existing_breakpoint = FindFirstBreakpointForMethod(m);
2847 if (existing_breakpoint == nullptr) {
2848 // There is no more breakpoint on this method: we need to undeoptimize.
2849 if (need_full_deoptimization) {
2850 // This method required full deoptimization: we need to undeoptimize everything.
2851 req->kind = DeoptimizationRequest::kFullUndeoptimization;
2852 req->method = nullptr;
2853 } else {
2854 // This method required selective deoptimization: we need to undeoptimize only that method.
2855 req->kind = DeoptimizationRequest::kSelectiveUndeoptimization;
2856 req->method = m;
2857 }
2858 } else {
2859 // There is at least one breakpoint for this method: we don't need to undeoptimize.
2860 req->kind = DeoptimizationRequest::kNothing;
2861 req->method = nullptr;
2862 SanityCheckExistingBreakpoints(m, need_full_deoptimization);
Elliott Hughes86964332012-02-15 19:37:42 -08002863 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002864}
2865
Jeff Hao449db332013-04-12 18:30:52 -07002866// Scoped utility class to suspend a thread so that we may do tasks such as walk its stack. Doesn't
2867// cause suspension if the thread is the current thread.
2868class ScopedThreadSuspension {
2869 public:
Ian Rogers33e95662013-05-20 20:29:14 -07002870 ScopedThreadSuspension(Thread* self, JDWP::ObjectId thread_id)
Sebastien Hertz52d131d2014-03-13 16:17:40 +01002871 LOCKS_EXCLUDED(Locks::thread_list_lock_)
Ian Rogers33e95662013-05-20 20:29:14 -07002872 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) :
Jeff Hao449db332013-04-12 18:30:52 -07002873 thread_(NULL),
2874 error_(JDWP::ERR_NONE),
2875 self_suspend_(false),
Ian Rogers33e95662013-05-20 20:29:14 -07002876 other_suspend_(false) {
Jeff Hao449db332013-04-12 18:30:52 -07002877 ScopedObjectAccessUnchecked soa(self);
2878 {
2879 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
2880 error_ = DecodeThread(soa, thread_id, thread_);
2881 }
2882 if (error_ == JDWP::ERR_NONE) {
2883 if (thread_ == soa.Self()) {
2884 self_suspend_ = true;
2885 } else {
2886 soa.Self()->TransitionFromRunnableToSuspended(kWaitingForDebuggerSuspension);
2887 jobject thread_peer = gRegistry->GetJObject(thread_id);
2888 bool timed_out;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07002889 Thread* suspended_thread = ThreadList::SuspendThreadByPeer(thread_peer, true, true,
2890 &timed_out);
Jeff Hao449db332013-04-12 18:30:52 -07002891 CHECK_EQ(soa.Self()->TransitionFromSuspendedToRunnable(), kWaitingForDebuggerSuspension);
2892 if (suspended_thread == NULL) {
2893 // Thread terminated from under us while suspending.
2894 error_ = JDWP::ERR_INVALID_THREAD;
2895 } else {
2896 CHECK_EQ(suspended_thread, thread_);
2897 other_suspend_ = true;
2898 }
2899 }
2900 }
Elliott Hughes2435a572012-02-17 16:07:41 -08002901 }
Elliott Hughes86964332012-02-15 19:37:42 -08002902
Jeff Hao449db332013-04-12 18:30:52 -07002903 Thread* GetThread() const {
2904 return thread_;
2905 }
2906
2907 JDWP::JdwpError GetError() const {
2908 return error_;
2909 }
2910
2911 ~ScopedThreadSuspension() {
2912 if (other_suspend_) {
2913 Runtime::Current()->GetThreadList()->Resume(thread_, true);
2914 }
2915 }
2916
2917 private:
2918 Thread* thread_;
2919 JDWP::JdwpError error_;
2920 bool self_suspend_;
2921 bool other_suspend_;
2922};
2923
2924JDWP::JdwpError Dbg::ConfigureStep(JDWP::ObjectId thread_id, JDWP::JdwpStepSize step_size,
2925 JDWP::JdwpStepDepth step_depth) {
2926 Thread* self = Thread::Current();
2927 ScopedThreadSuspension sts(self, thread_id);
2928 if (sts.GetError() != JDWP::ERR_NONE) {
2929 return sts.GetError();
2930 }
2931
Elliott Hughes2435a572012-02-17 16:07:41 -08002932 //
2933 // Work out what Method* we're in, the current line number, and how deep the stack currently
2934 // is for step-out.
2935 //
2936
Ian Rogers0399dde2012-06-06 17:09:28 -07002937 struct SingleStepStackVisitor : public StackVisitor {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002938 explicit SingleStepStackVisitor(Thread* thread, SingleStepControl* single_step_control,
2939 int32_t* line_number)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002940 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002941 : StackVisitor(thread, NULL), single_step_control_(single_step_control),
2942 line_number_(line_number) {
2943 DCHECK_EQ(single_step_control_, thread->GetSingleStepControl());
2944 single_step_control_->method = NULL;
2945 single_step_control_->stack_depth = 0;
Elliott Hughes86964332012-02-15 19:37:42 -08002946 }
Ian Rogersca190662012-06-26 15:45:57 -07002947
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002948 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2949 // annotalysis.
2950 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002951 mirror::ArtMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07002952 if (!m->IsRuntimeMethod()) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002953 ++single_step_control_->stack_depth;
2954 if (single_step_control_->method == NULL) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002955 mirror::DexCache* dex_cache = m->GetDeclaringClass()->GetDexCache();
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002956 single_step_control_->method = m;
2957 *line_number_ = -1;
Elliott Hughes2435a572012-02-17 16:07:41 -08002958 if (dex_cache != NULL) {
Ian Rogers4445a7e2012-10-05 17:19:13 -07002959 const DexFile& dex_file = *dex_cache->GetDexFile();
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002960 *line_number_ = dex_file.GetLineNumFromPC(m, GetDexPc());
Elliott Hughes2435a572012-02-17 16:07:41 -08002961 }
Elliott Hughes86964332012-02-15 19:37:42 -08002962 }
2963 }
Elliott Hughes530fa002012-03-12 11:44:49 -07002964 return true;
Elliott Hughes86964332012-02-15 19:37:42 -08002965 }
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002966
2967 SingleStepControl* const single_step_control_;
2968 int32_t* const line_number_;
Elliott Hughes86964332012-02-15 19:37:42 -08002969 };
Jeff Hao449db332013-04-12 18:30:52 -07002970
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002971 Thread* const thread = sts.GetThread();
2972 SingleStepControl* const single_step_control = thread->GetSingleStepControl();
2973 DCHECK(single_step_control != nullptr);
2974 int32_t line_number = -1;
2975 SingleStepStackVisitor visitor(thread, single_step_control, &line_number);
Ian Rogers0399dde2012-06-06 17:09:28 -07002976 visitor.WalkStack();
Elliott Hughes86964332012-02-15 19:37:42 -08002977
Elliott Hughes2435a572012-02-17 16:07:41 -08002978 //
2979 // Find the dex_pc values that correspond to the current line, for line-based single-stepping.
2980 //
2981
2982 struct DebugCallbackContext {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002983 explicit DebugCallbackContext(SingleStepControl* single_step_control, int32_t line_number)
2984 : single_step_control_(single_step_control), line_number_(line_number),
2985 last_pc_valid(false), last_pc(0) {
Elliott Hughes2435a572012-02-17 16:07:41 -08002986 }
2987
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002988 static bool Callback(void* raw_context, uint32_t address, uint32_t line_number) {
Elliott Hughes2435a572012-02-17 16:07:41 -08002989 DebugCallbackContext* context = reinterpret_cast<DebugCallbackContext*>(raw_context);
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002990 if (static_cast<int32_t>(line_number) == context->line_number_) {
Elliott Hughes2435a572012-02-17 16:07:41 -08002991 if (!context->last_pc_valid) {
2992 // Everything from this address until the next line change is ours.
2993 context->last_pc = address;
2994 context->last_pc_valid = true;
2995 }
2996 // Otherwise, if we're already in a valid range for this line,
2997 // just keep going (shouldn't really happen)...
Brian Carlstrom7934ac22013-07-26 10:54:15 -07002998 } else if (context->last_pc_valid) { // and the line number is new
Elliott Hughes2435a572012-02-17 16:07:41 -08002999 // Add everything from the last entry up until here to the set
3000 for (uint32_t dex_pc = context->last_pc; dex_pc < address; ++dex_pc) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003001 context->single_step_control_->dex_pcs.insert(dex_pc);
Elliott Hughes2435a572012-02-17 16:07:41 -08003002 }
3003 context->last_pc_valid = false;
3004 }
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003005 return false; // There may be multiple entries for any given line.
Elliott Hughes2435a572012-02-17 16:07:41 -08003006 }
3007
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003008 ~DebugCallbackContext() {
Elliott Hughes2435a572012-02-17 16:07:41 -08003009 // If the line number was the last in the position table...
3010 if (last_pc_valid) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003011 size_t end = MethodHelper(single_step_control_->method).GetCodeItem()->insns_size_in_code_units_;
Elliott Hughes2435a572012-02-17 16:07:41 -08003012 for (uint32_t dex_pc = last_pc; dex_pc < end; ++dex_pc) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003013 single_step_control_->dex_pcs.insert(dex_pc);
Elliott Hughes2435a572012-02-17 16:07:41 -08003014 }
3015 }
3016 }
3017
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003018 SingleStepControl* const single_step_control_;
3019 const int32_t line_number_;
Elliott Hughes2435a572012-02-17 16:07:41 -08003020 bool last_pc_valid;
3021 uint32_t last_pc;
3022 };
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003023 single_step_control->dex_pcs.clear();
Ian Rogersef7d42f2014-01-06 12:55:46 -08003024 mirror::ArtMethod* m = single_step_control->method;
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003025 if (!m->IsNative()) {
3026 DebugCallbackContext context(single_step_control, line_number);
Elliott Hughes3e2e1a22012-02-21 11:33:41 -08003027 MethodHelper mh(m);
3028 mh.GetDexFile().DecodeDebugInfo(mh.GetCodeItem(), m->IsStatic(), m->GetDexMethodIndex(),
3029 DebugCallbackContext::Callback, NULL, &context);
3030 }
Elliott Hughes2435a572012-02-17 16:07:41 -08003031
3032 //
3033 // Everything else...
3034 //
3035
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003036 single_step_control->step_size = step_size;
3037 single_step_control->step_depth = step_depth;
3038 single_step_control->is_active = true;
Elliott Hughes86964332012-02-15 19:37:42 -08003039
Elliott Hughes2435a572012-02-17 16:07:41 -08003040 if (VLOG_IS_ON(jdwp)) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003041 VLOG(jdwp) << "Single-step thread: " << *thread;
3042 VLOG(jdwp) << "Single-step step size: " << single_step_control->step_size;
3043 VLOG(jdwp) << "Single-step step depth: " << single_step_control->step_depth;
3044 VLOG(jdwp) << "Single-step current method: " << PrettyMethod(single_step_control->method);
3045 VLOG(jdwp) << "Single-step current line: " << line_number;
3046 VLOG(jdwp) << "Single-step current stack depth: " << single_step_control->stack_depth;
Elliott Hughes2435a572012-02-17 16:07:41 -08003047 VLOG(jdwp) << "Single-step dex_pc values:";
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003048 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 -08003049 VLOG(jdwp) << StringPrintf(" %#x", *it);
Elliott Hughes2435a572012-02-17 16:07:41 -08003050 }
3051 }
3052
3053 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003054}
3055
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003056void Dbg::UnconfigureStep(JDWP::ObjectId thread_id) {
3057 ScopedObjectAccessUnchecked soa(Thread::Current());
3058 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
3059 Thread* thread;
3060 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
Sebastien Hertz87118ed2013-11-26 17:57:18 +01003061 if (error == JDWP::ERR_NONE) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01003062 SingleStepControl* single_step_control = thread->GetSingleStepControl();
3063 DCHECK(single_step_control != nullptr);
3064 single_step_control->is_active = false;
3065 single_step_control->dex_pcs.clear();
3066 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003067}
3068
Elliott Hughes45651fd2012-02-21 15:48:20 -08003069static char JdwpTagToShortyChar(JDWP::JdwpTag tag) {
3070 switch (tag) {
3071 default:
3072 LOG(FATAL) << "unknown JDWP tag: " << PrintableChar(tag);
3073
3074 // Primitives.
3075 case JDWP::JT_BYTE: return 'B';
3076 case JDWP::JT_CHAR: return 'C';
3077 case JDWP::JT_FLOAT: return 'F';
3078 case JDWP::JT_DOUBLE: return 'D';
3079 case JDWP::JT_INT: return 'I';
3080 case JDWP::JT_LONG: return 'J';
3081 case JDWP::JT_SHORT: return 'S';
3082 case JDWP::JT_VOID: return 'V';
3083 case JDWP::JT_BOOLEAN: return 'Z';
3084
3085 // Reference types.
3086 case JDWP::JT_ARRAY:
3087 case JDWP::JT_OBJECT:
3088 case JDWP::JT_STRING:
3089 case JDWP::JT_THREAD:
3090 case JDWP::JT_THREAD_GROUP:
3091 case JDWP::JT_CLASS_LOADER:
3092 case JDWP::JT_CLASS_OBJECT:
3093 return 'L';
3094 }
3095}
3096
Elliott Hughes88d63092013-01-09 09:55:54 -08003097JDWP::JdwpError Dbg::InvokeMethod(JDWP::ObjectId thread_id, JDWP::ObjectId object_id,
3098 JDWP::RefTypeId class_id, JDWP::MethodId method_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003099 uint32_t arg_count, uint64_t* arg_values,
3100 JDWP::JdwpTag* arg_types, uint32_t options,
3101 JDWP::JdwpTag* pResultTag, uint64_t* pResultValue,
3102 JDWP::ObjectId* pExceptionId) {
Elliott Hughesd07986f2011-12-06 18:27:45 -08003103 ThreadList* thread_list = Runtime::Current()->GetThreadList();
3104
3105 Thread* targetThread = NULL;
3106 DebugInvokeReq* req = NULL;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003107 Thread* self = Thread::Current();
Elliott Hughesd07986f2011-12-06 18:27:45 -08003108 {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003109 ScopedObjectAccessUnchecked soa(self);
Ian Rogers50b35e22012-10-04 10:09:15 -07003110 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08003111 JDWP::JdwpError error = DecodeThread(soa, thread_id, targetThread);
3112 if (error != JDWP::ERR_NONE) {
3113 LOG(ERROR) << "InvokeMethod request for invalid thread id " << thread_id;
3114 return error;
Elliott Hughesd07986f2011-12-06 18:27:45 -08003115 }
3116 req = targetThread->GetInvokeReq();
3117 if (!req->ready) {
3118 LOG(ERROR) << "InvokeMethod request for thread not stopped by event: " << *targetThread;
3119 return JDWP::ERR_INVALID_THREAD;
3120 }
3121
3122 /*
3123 * We currently have a bug where we don't successfully resume the
3124 * target thread if the suspend count is too deep. We're expected to
3125 * require one "resume" for each "suspend", but when asked to execute
3126 * a method we have to resume fully and then re-suspend it back to the
3127 * same level. (The easiest way to cause this is to type "suspend"
3128 * multiple times in jdb.)
3129 *
3130 * It's unclear what this means when the event specifies "resume all"
3131 * and some threads are suspended more deeply than others. This is
3132 * a rare problem, so for now we just prevent it from hanging forever
3133 * by rejecting the method invocation request. Without this, we will
3134 * be stuck waiting on a suspended thread.
3135 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003136 int suspend_count;
3137 {
Ian Rogers50b35e22012-10-04 10:09:15 -07003138 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003139 suspend_count = targetThread->GetSuspendCount();
3140 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08003141 if (suspend_count > 1) {
3142 LOG(ERROR) << *targetThread << " suspend count too deep for method invocation: " << suspend_count;
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003143 return JDWP::ERR_THREAD_SUSPENDED; // Probably not expected here.
Elliott Hughesd07986f2011-12-06 18:27:45 -08003144 }
3145
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08003146 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003147 mirror::Object* receiver = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08003148 if (receiver == ObjectRegistry::kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08003149 return JDWP::ERR_INVALID_OBJECT;
3150 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003151
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003152 mirror::Object* thread = gRegistry->Get<mirror::Object*>(thread_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08003153 if (thread == ObjectRegistry::kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08003154 return JDWP::ERR_INVALID_OBJECT;
3155 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003156 // TODO: check that 'thread' is actually a java.lang.Thread!
3157
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003158 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes45651fd2012-02-21 15:48:20 -08003159 if (c == NULL) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08003160 return status;
3161 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003162
Brian Carlstromea46f952013-07-30 01:26:50 -07003163 mirror::ArtMethod* m = FromMethodId(method_id);
Elliott Hughes45651fd2012-02-21 15:48:20 -08003164 if (m->IsStatic() != (receiver == NULL)) {
3165 return JDWP::ERR_INVALID_METHODID;
3166 }
3167 if (m->IsStatic()) {
3168 if (m->GetDeclaringClass() != c) {
3169 return JDWP::ERR_INVALID_METHODID;
3170 }
3171 } else {
3172 if (!m->GetDeclaringClass()->IsAssignableFrom(c)) {
3173 return JDWP::ERR_INVALID_METHODID;
3174 }
3175 }
3176
3177 // Check the argument list matches the method.
3178 MethodHelper mh(m);
3179 if (mh.GetShortyLength() - 1 != arg_count) {
3180 return JDWP::ERR_ILLEGAL_ARGUMENT;
3181 }
3182 const char* shorty = mh.GetShorty();
Elliott Hughes09201632013-04-15 15:50:07 -07003183 const DexFile::TypeList* types = mh.GetParameterTypeList();
Elliott Hughes45651fd2012-02-21 15:48:20 -08003184 for (size_t i = 0; i < arg_count; ++i) {
3185 if (shorty[i + 1] != JdwpTagToShortyChar(arg_types[i])) {
3186 return JDWP::ERR_ILLEGAL_ARGUMENT;
3187 }
Elliott Hughes09201632013-04-15 15:50:07 -07003188
3189 if (shorty[i + 1] == 'L') {
3190 // Did we really get an argument of an appropriate reference type?
3191 mirror::Class* parameter_type = mh.GetClassFromTypeIdx(types->GetTypeItem(i).type_idx_);
3192 mirror::Object* argument = gRegistry->Get<mirror::Object*>(arg_values[i]);
3193 if (argument == ObjectRegistry::kInvalidObject) {
3194 return JDWP::ERR_INVALID_OBJECT;
3195 }
Sebastien Hertz0630ab52013-11-28 18:53:35 +01003196 if (argument != NULL && !argument->InstanceOf(parameter_type)) {
Elliott Hughes09201632013-04-15 15:50:07 -07003197 return JDWP::ERR_ILLEGAL_ARGUMENT;
3198 }
3199
3200 // Turn the on-the-wire ObjectId into a jobject.
3201 jvalue& v = reinterpret_cast<jvalue&>(arg_values[i]);
3202 v.l = gRegistry->GetJObject(arg_values[i]);
3203 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003204 }
3205
Sebastien Hertzd38667a2013-11-25 15:43:54 +01003206 req->receiver = receiver;
3207 req->thread = thread;
3208 req->klass = c;
3209 req->method = m;
3210 req->arg_count = arg_count;
3211 req->arg_values = arg_values;
3212 req->options = options;
3213 req->invoke_needed = true;
Elliott Hughesd07986f2011-12-06 18:27:45 -08003214 }
3215
3216 // The fact that we've released the thread list lock is a bit risky --- if the thread goes
3217 // away we're sitting high and dry -- but we must release this before the ResumeAllThreads
3218 // call, and it's unwise to hold it during WaitForSuspend.
3219
3220 {
3221 /*
3222 * We change our (JDWP thread) status, which should be THREAD_RUNNING,
Elliott Hughes81ff3182012-03-23 20:35:56 -07003223 * so we can suspend for a GC if the invoke request causes us to
Elliott Hughesd07986f2011-12-06 18:27:45 -08003224 * run out of memory. It's also a good idea to change it before locking
3225 * the invokeReq mutex, although that should never be held for long.
3226 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003227 self->TransitionFromRunnableToSuspended(kWaitingForDebuggerSend);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003228
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003229 VLOG(jdwp) << " Transferring control to event thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08003230 {
Sebastien Hertzd38667a2013-11-25 15:43:54 +01003231 MutexLock mu(self, req->lock);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003232
3233 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003234 VLOG(jdwp) << " Resuming all threads";
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003235 thread_list->UndoDebuggerSuspensions();
Elliott Hughesd07986f2011-12-06 18:27:45 -08003236 } else {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003237 VLOG(jdwp) << " Resuming event thread only";
Elliott Hughesd07986f2011-12-06 18:27:45 -08003238 thread_list->Resume(targetThread, true);
3239 }
3240
3241 // Wait for the request to finish executing.
Sebastien Hertzd38667a2013-11-25 15:43:54 +01003242 while (req->invoke_needed) {
3243 req->cond.Wait(self);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003244 }
3245 }
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003246 VLOG(jdwp) << " Control has returned from event thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08003247
3248 /* wait for thread to re-suspend itself */
Brian Carlstromdf629502013-07-17 22:39:56 -07003249 SuspendThread(thread_id, false /* request_suspension */);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003250 self->TransitionFromSuspendedToRunnable();
Elliott Hughesd07986f2011-12-06 18:27:45 -08003251 }
3252
3253 /*
3254 * Suspend the threads. We waited for the target thread to suspend
3255 * itself, so all we need to do is suspend the others.
3256 *
3257 * The suspendAllThreads() call will double-suspend the event thread,
3258 * so we want to resume the target thread once to keep the books straight.
3259 */
3260 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003261 self->TransitionFromRunnableToSuspended(kWaitingForDebuggerSuspension);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003262 VLOG(jdwp) << " Suspending all threads";
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003263 thread_list->SuspendAllForDebugger();
3264 self->TransitionFromSuspendedToRunnable();
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003265 VLOG(jdwp) << " Resuming event thread to balance the count";
Elliott Hughesd07986f2011-12-06 18:27:45 -08003266 thread_list->Resume(targetThread, true);
3267 }
3268
3269 // Copy the result.
3270 *pResultTag = req->result_tag;
3271 if (IsPrimitiveTag(req->result_tag)) {
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07003272 *pResultValue = req->result_value.GetJ();
Elliott Hughesd07986f2011-12-06 18:27:45 -08003273 } else {
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07003274 *pResultValue = gRegistry->Add(req->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003275 }
3276 *pExceptionId = req->exception;
3277 return req->error;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003278}
3279
3280void Dbg::ExecuteMethod(DebugInvokeReq* pReq) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003281 ScopedObjectAccess soa(Thread::Current());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003282
Elliott Hughes81ff3182012-03-23 20:35:56 -07003283 // We can be called while an exception is pending. We need
Elliott Hughesd07986f2011-12-06 18:27:45 -08003284 // to preserve that across the method invocation.
Ian Rogers62d6c772013-02-27 08:32:07 -08003285 SirtRef<mirror::Object> old_throw_this_object(soa.Self(), NULL);
Brian Carlstromea46f952013-07-30 01:26:50 -07003286 SirtRef<mirror::ArtMethod> old_throw_method(soa.Self(), NULL);
Ian Rogers62d6c772013-02-27 08:32:07 -08003287 SirtRef<mirror::Throwable> old_exception(soa.Self(), NULL);
3288 uint32_t old_throw_dex_pc;
3289 {
3290 ThrowLocation old_throw_location;
3291 mirror::Throwable* old_exception_obj = soa.Self()->GetException(&old_throw_location);
3292 old_throw_this_object.reset(old_throw_location.GetThis());
3293 old_throw_method.reset(old_throw_location.GetMethod());
3294 old_exception.reset(old_exception_obj);
3295 old_throw_dex_pc = old_throw_location.GetDexPc();
3296 soa.Self()->ClearException();
3297 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08003298
3299 // Translate the method through the vtable, unless the debugger wants to suppress it.
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003300 SirtRef<mirror::ArtMethod> m(soa.Self(), pReq->method);
Sebastien Hertzd38667a2013-11-25 15:43:54 +01003301 if ((pReq->options & JDWP::INVOKE_NONVIRTUAL) == 0 && pReq->receiver != NULL) {
Sebastien Hertz83a47d82014-03-20 09:57:40 +01003302 mirror::ArtMethod* actual_method = pReq->klass->FindVirtualMethodForVirtualOrInterface(m.get());
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003303 if (actual_method != m.get()) {
3304 VLOG(jdwp) << "ExecuteMethod translated " << PrettyMethod(m.get()) << " to " << PrettyMethod(actual_method);
3305 m.reset(actual_method);
Elliott Hughes45651fd2012-02-21 15:48:20 -08003306 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08003307 }
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003308 VLOG(jdwp) << "ExecuteMethod " << PrettyMethod(m.get())
Sebastien Hertzd38667a2013-11-25 15:43:54 +01003309 << " receiver=" << pReq->receiver
3310 << " arg_count=" << pReq->arg_count;
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003311 CHECK(m.get() != nullptr);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003312
3313 CHECK_EQ(sizeof(jvalue), sizeof(uint64_t));
3314
Sebastien Hertz83a47d82014-03-20 09:57:40 +01003315 pReq->result_value = InvokeWithJValues(soa, pReq->receiver, soa.EncodeMethod(m.get()),
Ian Rogers53b8b092014-03-13 23:45:53 -07003316 reinterpret_cast<jvalue*>(pReq->arg_values));
Elliott Hughesd07986f2011-12-06 18:27:45 -08003317
Ian Rogers62d6c772013-02-27 08:32:07 -08003318 mirror::Throwable* exception = soa.Self()->GetException(NULL);
3319 soa.Self()->ClearException();
3320 pReq->exception = gRegistry->Add(exception);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003321 pReq->result_tag = BasicTagFromDescriptor(MethodHelper(m.get()).GetShorty());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003322 if (pReq->exception != 0) {
Ian Rogers62d6c772013-02-27 08:32:07 -08003323 VLOG(jdwp) << " JDWP invocation returning with exception=" << exception
3324 << " " << exception->Dump();
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07003325 pReq->result_value.SetJ(0);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003326 } else if (pReq->result_tag == JDWP::JT_OBJECT) {
3327 /* if no exception thrown, examine object result more closely */
Ian Rogers98379392014-02-24 16:53:16 -08003328 JDWP::JdwpTag new_tag = TagFromObject(soa, pReq->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003329 if (new_tag != pReq->result_tag) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003330 VLOG(jdwp) << " JDWP promoted result from " << pReq->result_tag << " to " << new_tag;
Elliott Hughesd07986f2011-12-06 18:27:45 -08003331 pReq->result_tag = new_tag;
3332 }
3333
3334 /*
3335 * Register the object. We don't actually need an ObjectId yet,
3336 * but we do need to be sure that the GC won't move or discard the
3337 * object when we switch out of RUNNING. The ObjectId conversion
3338 * will add the object to the "do not touch" list.
3339 *
3340 * We can't use the "tracked allocation" mechanism here because
3341 * the object is going to be handed off to a different thread.
3342 */
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07003343 gRegistry->Add(pReq->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003344 }
3345
3346 if (old_exception.get() != NULL) {
Ian Rogers62d6c772013-02-27 08:32:07 -08003347 ThrowLocation gc_safe_throw_location(old_throw_this_object.get(), old_throw_method.get(),
3348 old_throw_dex_pc);
3349 soa.Self()->SetException(gc_safe_throw_location, old_exception.get());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003350 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003351}
3352
Elliott Hughesd07986f2011-12-06 18:27:45 -08003353/*
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003354 * "request" contains a full JDWP packet, possibly with multiple chunks. We
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003355 * need to process each, accumulate the replies, and ship the whole thing
3356 * back.
3357 *
3358 * Returns "true" if we have a reply. The reply buffer is newly allocated,
3359 * and includes the chunk type/length, followed by the data.
3360 *
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08003361 * OLD-TODO: we currently assume that the request and reply include a single
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003362 * chunk. If this becomes inconvenient we will need to adapt.
3363 */
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003364bool Dbg::DdmHandlePacket(JDWP::Request& request, uint8_t** pReplyBuf, int* pReplyLen) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003365 Thread* self = Thread::Current();
3366 JNIEnv* env = self->GetJniEnv();
3367
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003368 uint32_t type = request.ReadUnsigned32("type");
3369 uint32_t length = request.ReadUnsigned32("length");
3370
3371 // Create a byte[] corresponding to 'request'.
3372 size_t request_length = request.size();
3373 ScopedLocalRef<jbyteArray> dataArray(env, env->NewByteArray(request_length));
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003374 if (dataArray.get() == NULL) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003375 LOG(WARNING) << "byte[] allocation failed: " << request_length;
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003376 env->ExceptionClear();
3377 return false;
3378 }
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003379 env->SetByteArrayRegion(dataArray.get(), 0, request_length, reinterpret_cast<const jbyte*>(request.data()));
3380 request.Skip(request_length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003381
3382 // Run through and find all chunks. [Currently just find the first.]
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003383 ScopedByteArrayRO contents(env, dataArray.get());
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003384 if (length != request_length) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08003385 LOG(WARNING) << StringPrintf("bad chunk found (len=%u pktLen=%zd)", length, request_length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003386 return false;
3387 }
3388
3389 // Call "private static Chunk dispatch(int type, byte[] data, int offset, int length)".
Elliott Hugheseac76672012-05-24 21:56:51 -07003390 ScopedLocalRef<jobject> chunk(env, env->CallStaticObjectMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
3391 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_dispatch,
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003392 type, dataArray.get(), 0, length));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003393 if (env->ExceptionCheck()) {
3394 LOG(INFO) << StringPrintf("Exception thrown by dispatcher for 0x%08x", type);
3395 env->ExceptionDescribe();
3396 env->ExceptionClear();
3397 return false;
3398 }
3399
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003400 if (chunk.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003401 return false;
3402 }
3403
3404 /*
3405 * Pull the pieces out of the chunk. We copy the results into a
3406 * newly-allocated buffer that the caller can free. We don't want to
3407 * continue using the Chunk object because nothing has a reference to it.
3408 *
3409 * We could avoid this by returning type/data/offset/length and having
3410 * the caller be aware of the object lifetime issues, but that
Elliott Hughes81ff3182012-03-23 20:35:56 -07003411 * integrates the JDWP code more tightly into the rest of the runtime, and doesn't work
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003412 * if we have responses for multiple chunks.
3413 *
3414 * So we're pretty much stuck with copying data around multiple times.
3415 */
Elliott Hugheseac76672012-05-24 21:56:51 -07003416 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 -08003417 jint offset = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_offset);
Elliott Hugheseac76672012-05-24 21:56:51 -07003418 length = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_length);
Elliott Hugheseac76672012-05-24 21:56:51 -07003419 type = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_type);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003420
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003421 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 -07003422 if (length == 0 || replyData.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003423 return false;
3424 }
3425
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003426 const int kChunkHdrLen = 8;
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003427 uint8_t* reply = new uint8_t[length + kChunkHdrLen];
3428 if (reply == NULL) {
3429 LOG(WARNING) << "malloc failed: " << (length + kChunkHdrLen);
3430 return false;
3431 }
Elliott Hughesf7c3b662011-10-27 12:04:56 -07003432 JDWP::Set4BE(reply + 0, type);
3433 JDWP::Set4BE(reply + 4, length);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003434 env->GetByteArrayRegion(replyData.get(), offset, length, reinterpret_cast<jbyte*>(reply + kChunkHdrLen));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003435
3436 *pReplyBuf = reply;
3437 *pReplyLen = length + kChunkHdrLen;
3438
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003439 VLOG(jdwp) << StringPrintf("dvmHandleDdm returning type=%.4s %p len=%d", reinterpret_cast<char*>(reply), reply, length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003440 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003441}
3442
Elliott Hughesa2155262011-11-16 16:26:58 -08003443void Dbg::DdmBroadcast(bool connect) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003444 VLOG(jdwp) << "Broadcasting DDM " << (connect ? "connect" : "disconnect") << "...";
Elliott Hughes47fce012011-10-25 18:37:19 -07003445
3446 Thread* self = Thread::Current();
Ian Rogers50b35e22012-10-04 10:09:15 -07003447 if (self->GetState() != kRunnable) {
3448 LOG(ERROR) << "DDM broadcast in thread state " << self->GetState();
3449 /* try anyway? */
Elliott Hughes47fce012011-10-25 18:37:19 -07003450 }
3451
3452 JNIEnv* env = self->GetJniEnv();
Elliott Hughes47fce012011-10-25 18:37:19 -07003453 jint event = connect ? 1 /*DdmServer.CONNECTED*/ : 2 /*DdmServer.DISCONNECTED*/;
Elliott Hugheseac76672012-05-24 21:56:51 -07003454 env->CallStaticVoidMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
3455 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_broadcast,
3456 event);
Elliott Hughes47fce012011-10-25 18:37:19 -07003457 if (env->ExceptionCheck()) {
3458 LOG(ERROR) << "DdmServer.broadcast " << event << " failed";
3459 env->ExceptionDescribe();
3460 env->ExceptionClear();
3461 }
3462}
3463
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003464void Dbg::DdmConnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08003465 Dbg::DdmBroadcast(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003466}
3467
3468void Dbg::DdmDisconnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08003469 Dbg::DdmBroadcast(false);
Elliott Hughes47fce012011-10-25 18:37:19 -07003470 gDdmThreadNotification = false;
3471}
3472
3473/*
Elliott Hughes82188472011-11-07 18:11:48 -08003474 * Send a notification when a thread starts, stops, or changes its name.
Elliott Hughes47fce012011-10-25 18:37:19 -07003475 *
3476 * Because we broadcast the full set of threads when the notifications are
3477 * first enabled, it's possible for "thread" to be actively executing.
3478 */
Elliott Hughes82188472011-11-07 18:11:48 -08003479void Dbg::DdmSendThreadNotification(Thread* t, uint32_t type) {
Elliott Hughes47fce012011-10-25 18:37:19 -07003480 if (!gDdmThreadNotification) {
3481 return;
3482 }
3483
Elliott Hughes82188472011-11-07 18:11:48 -08003484 if (type == CHUNK_TYPE("THDE")) {
Elliott Hughes47fce012011-10-25 18:37:19 -07003485 uint8_t buf[4];
Ian Rogersd9c4fc92013-10-01 19:45:43 -07003486 JDWP::Set4BE(&buf[0], t->GetThreadId());
Elliott Hughes47fce012011-10-25 18:37:19 -07003487 Dbg::DdmSendChunk(CHUNK_TYPE("THDE"), 4, buf);
Elliott Hughes82188472011-11-07 18:11:48 -08003488 } else {
3489 CHECK(type == CHUNK_TYPE("THCR") || type == CHUNK_TYPE("THNM")) << type;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003490 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003491 SirtRef<mirror::String> name(soa.Self(), t->GetThreadName(soa));
Elliott Hughes82188472011-11-07 18:11:48 -08003492 size_t char_count = (name.get() != NULL) ? name->GetLength() : 0;
jeffhao725a9572012-11-13 18:20:12 -08003493 const jchar* chars = (name.get() != NULL) ? name->GetCharArray()->GetData() : NULL;
Elliott Hughes82188472011-11-07 18:11:48 -08003494
Elliott Hughes21f32d72011-11-09 17:44:13 -08003495 std::vector<uint8_t> bytes;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07003496 JDWP::Append4BE(bytes, t->GetThreadId());
Elliott Hughes545a0642011-11-08 19:10:03 -08003497 JDWP::AppendUtf16BE(bytes, chars, char_count);
Elliott Hughes21f32d72011-11-09 17:44:13 -08003498 CHECK_EQ(bytes.size(), char_count*2 + sizeof(uint32_t)*2);
3499 Dbg::DdmSendChunk(type, bytes);
Elliott Hughes47fce012011-10-25 18:37:19 -07003500 }
3501}
3502
Elliott Hughes47fce012011-10-25 18:37:19 -07003503void Dbg::DdmSetThreadNotification(bool enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003504 // Enable/disable thread notifications.
Elliott Hughes47fce012011-10-25 18:37:19 -07003505 gDdmThreadNotification = enable;
3506 if (enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003507 // Suspend the VM then post thread start notifications for all threads. Threads attaching will
3508 // see a suspension in progress and block until that ends. They then post their own start
3509 // notification.
3510 SuspendVM();
3511 std::list<Thread*> threads;
Ian Rogers50b35e22012-10-04 10:09:15 -07003512 Thread* self = Thread::Current();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003513 {
Ian Rogers50b35e22012-10-04 10:09:15 -07003514 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003515 threads = Runtime::Current()->GetThreadList()->GetList();
3516 }
3517 {
Ian Rogers50b35e22012-10-04 10:09:15 -07003518 ScopedObjectAccess soa(self);
Mathieu Chartier02e25112013-08-14 16:14:24 -07003519 for (Thread* thread : threads) {
3520 Dbg::DdmSendThreadNotification(thread, CHUNK_TYPE("THCR"));
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003521 }
3522 }
3523 ResumeVM();
Elliott Hughes47fce012011-10-25 18:37:19 -07003524 }
3525}
3526
Elliott Hughesa2155262011-11-16 16:26:58 -08003527void Dbg::PostThreadStartOrStop(Thread* t, uint32_t type) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07003528 if (IsDebuggerActive()) {
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07003529 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogerscfaa4552012-11-26 21:00:08 -08003530 JDWP::ObjectId id = gRegistry->Add(t->GetPeer());
Elliott Hughes82188472011-11-07 18:11:48 -08003531 gJdwpState->PostThreadChange(id, type == CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07003532 }
Elliott Hughes82188472011-11-07 18:11:48 -08003533 Dbg::DdmSendThreadNotification(t, type);
Elliott Hughes47fce012011-10-25 18:37:19 -07003534}
3535
3536void Dbg::PostThreadStart(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08003537 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07003538}
3539
3540void Dbg::PostThreadDeath(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08003541 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THDE"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003542}
3543
Elliott Hughes82188472011-11-07 18:11:48 -08003544void Dbg::DdmSendChunk(uint32_t type, size_t byte_count, const uint8_t* buf) {
Elliott Hughes3bb81562011-10-21 18:52:59 -07003545 CHECK(buf != NULL);
3546 iovec vec[1];
3547 vec[0].iov_base = reinterpret_cast<void*>(const_cast<uint8_t*>(buf));
3548 vec[0].iov_len = byte_count;
3549 Dbg::DdmSendChunkV(type, vec, 1);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003550}
3551
Elliott Hughes21f32d72011-11-09 17:44:13 -08003552void Dbg::DdmSendChunk(uint32_t type, const std::vector<uint8_t>& bytes) {
3553 DdmSendChunk(type, bytes.size(), &bytes[0]);
3554}
3555
Brian Carlstromf5293522013-07-19 00:24:00 -07003556void Dbg::DdmSendChunkV(uint32_t type, const iovec* iov, int iov_count) {
Elliott Hughes3bb81562011-10-21 18:52:59 -07003557 if (gJdwpState == NULL) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003558 VLOG(jdwp) << "Debugger thread not active, ignoring DDM send: " << type;
Elliott Hughes3bb81562011-10-21 18:52:59 -07003559 } else {
Elliott Hughescccd84f2011-12-05 16:51:54 -08003560 gJdwpState->DdmSendChunkV(type, iov, iov_count);
Elliott Hughes3bb81562011-10-21 18:52:59 -07003561 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003562}
3563
Elliott Hughes767a1472011-10-26 18:49:02 -07003564int Dbg::DdmHandleHpifChunk(HpifWhen when) {
3565 if (when == HPIF_WHEN_NOW) {
Elliott Hughes7162ad92011-10-27 14:08:42 -07003566 DdmSendHeapInfo(when);
Elliott Hughes767a1472011-10-26 18:49:02 -07003567 return true;
3568 }
3569
3570 if (when != HPIF_WHEN_NEVER && when != HPIF_WHEN_NEXT_GC && when != HPIF_WHEN_EVERY_GC) {
3571 LOG(ERROR) << "invalid HpifWhen value: " << static_cast<int>(when);
3572 return false;
3573 }
3574
3575 gDdmHpifWhen = when;
3576 return true;
3577}
3578
3579bool Dbg::DdmHandleHpsgNhsgChunk(Dbg::HpsgWhen when, Dbg::HpsgWhat what, bool native) {
3580 if (when != HPSG_WHEN_NEVER && when != HPSG_WHEN_EVERY_GC) {
3581 LOG(ERROR) << "invalid HpsgWhen value: " << static_cast<int>(when);
3582 return false;
3583 }
3584
3585 if (what != HPSG_WHAT_MERGED_OBJECTS && what != HPSG_WHAT_DISTINCT_OBJECTS) {
3586 LOG(ERROR) << "invalid HpsgWhat value: " << static_cast<int>(what);
3587 return false;
3588 }
3589
3590 if (native) {
3591 gDdmNhsgWhen = when;
3592 gDdmNhsgWhat = what;
3593 } else {
3594 gDdmHpsgWhen = when;
3595 gDdmHpsgWhat = what;
3596 }
3597 return true;
3598}
3599
Elliott Hughes7162ad92011-10-27 14:08:42 -07003600void Dbg::DdmSendHeapInfo(HpifWhen reason) {
3601 // If there's a one-shot 'when', reset it.
3602 if (reason == gDdmHpifWhen) {
3603 if (gDdmHpifWhen == HPIF_WHEN_NEXT_GC) {
3604 gDdmHpifWhen = HPIF_WHEN_NEVER;
3605 }
3606 }
3607
3608 /*
3609 * Chunk HPIF (client --> server)
3610 *
3611 * Heap Info. General information about the heap,
3612 * suitable for a summary display.
3613 *
3614 * [u4]: number of heaps
3615 *
3616 * For each heap:
3617 * [u4]: heap ID
3618 * [u8]: timestamp in ms since Unix epoch
3619 * [u1]: capture reason (same as 'when' value from server)
3620 * [u4]: max heap size in bytes (-Xmx)
3621 * [u4]: current heap size in bytes
3622 * [u4]: current number of bytes allocated
3623 * [u4]: current number of objects allocated
3624 */
3625 uint8_t heap_count = 1;
Ian Rogers1d54e732013-05-02 21:10:01 -07003626 gc::Heap* heap = Runtime::Current()->GetHeap();
Elliott Hughes21f32d72011-11-09 17:44:13 -08003627 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08003628 JDWP::Append4BE(bytes, heap_count);
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003629 JDWP::Append4BE(bytes, 1); // Heap id (bogus; we only have one heap).
Elliott Hughes545a0642011-11-08 19:10:03 -08003630 JDWP::Append8BE(bytes, MilliTime());
3631 JDWP::Append1BE(bytes, reason);
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003632 JDWP::Append4BE(bytes, heap->GetMaxMemory()); // Max allowed heap size in bytes.
3633 JDWP::Append4BE(bytes, heap->GetTotalMemory()); // Current heap size in bytes.
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08003634 JDWP::Append4BE(bytes, heap->GetBytesAllocated());
3635 JDWP::Append4BE(bytes, heap->GetObjectsAllocated());
Elliott Hughes21f32d72011-11-09 17:44:13 -08003636 CHECK_EQ(bytes.size(), 4U + (heap_count * (4 + 8 + 1 + 4 + 4 + 4 + 4)));
3637 Dbg::DdmSendChunk(CHUNK_TYPE("HPIF"), bytes);
Elliott Hughes767a1472011-10-26 18:49:02 -07003638}
3639
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003640enum HpsgSolidity {
3641 SOLIDITY_FREE = 0,
3642 SOLIDITY_HARD = 1,
3643 SOLIDITY_SOFT = 2,
3644 SOLIDITY_WEAK = 3,
3645 SOLIDITY_PHANTOM = 4,
3646 SOLIDITY_FINALIZABLE = 5,
3647 SOLIDITY_SWEEP = 6,
3648};
3649
3650enum HpsgKind {
3651 KIND_OBJECT = 0,
3652 KIND_CLASS_OBJECT = 1,
3653 KIND_ARRAY_1 = 2,
3654 KIND_ARRAY_2 = 3,
3655 KIND_ARRAY_4 = 4,
3656 KIND_ARRAY_8 = 5,
3657 KIND_UNKNOWN = 6,
3658 KIND_NATIVE = 7,
3659};
3660
3661#define HPSG_PARTIAL (1<<7)
3662#define HPSG_STATE(solidity, kind) ((uint8_t)((((kind) & 0x7) << 3) | ((solidity) & 0x7)))
3663
Ian Rogers30fab402012-01-23 15:43:46 -08003664class HeapChunkContext {
3665 public:
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003666 // Maximum chunk size. Obtain this from the formula:
3667 // (((maximum_heap_size / ALLOCATION_UNIT_SIZE) + 255) / 256) * 2
3668 HeapChunkContext(bool merge, bool native)
Ian Rogers30fab402012-01-23 15:43:46 -08003669 : buf_(16384 - 16),
3670 type_(0),
3671 merge_(merge) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003672 Reset();
3673 if (native) {
Ian Rogers30fab402012-01-23 15:43:46 -08003674 type_ = CHUNK_TYPE("NHSG");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003675 } else {
Ian Rogers30fab402012-01-23 15:43:46 -08003676 type_ = merge ? CHUNK_TYPE("HPSG") : CHUNK_TYPE("HPSO");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003677 }
3678 }
3679
3680 ~HeapChunkContext() {
Ian Rogers30fab402012-01-23 15:43:46 -08003681 if (p_ > &buf_[0]) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003682 Flush();
3683 }
3684 }
3685
3686 void EnsureHeader(const void* chunk_ptr) {
Ian Rogers30fab402012-01-23 15:43:46 -08003687 if (!needHeader_) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003688 return;
3689 }
3690
3691 // Start a new HPSx chunk.
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003692 JDWP::Write4BE(&p_, 1); // Heap id (bogus; we only have one heap).
3693 JDWP::Write1BE(&p_, 8); // Size of allocation unit, in bytes.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003694
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003695 JDWP::Write4BE(&p_, reinterpret_cast<uintptr_t>(chunk_ptr)); // virtual address of segment start.
3696 JDWP::Write4BE(&p_, 0); // offset of this piece (relative to the virtual address).
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003697 // [u4]: length of piece, in allocation units
3698 // 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 -08003699 pieceLenField_ = p_;
3700 JDWP::Write4BE(&p_, 0x55555555);
3701 needHeader_ = false;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003702 }
3703
Ian Rogersb726dcb2012-09-05 08:57:23 -07003704 void Flush() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogersd636b062013-01-18 17:51:18 -08003705 if (pieceLenField_ == NULL) {
3706 // Flush immediately post Reset (maybe back-to-back Flush). Ignore.
3707 CHECK(needHeader_);
3708 return;
3709 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003710 // Patch the "length of piece" field.
Ian Rogers30fab402012-01-23 15:43:46 -08003711 CHECK_LE(&buf_[0], pieceLenField_);
3712 CHECK_LE(pieceLenField_, p_);
3713 JDWP::Set4BE(pieceLenField_, totalAllocationUnits_);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003714
Ian Rogers30fab402012-01-23 15:43:46 -08003715 Dbg::DdmSendChunk(type_, p_ - &buf_[0], &buf_[0]);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003716 Reset();
3717 }
3718
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003719 static void HeapChunkCallback(void* start, void* end, size_t used_bytes, void* arg)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003720 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_,
3721 Locks::mutator_lock_) {
Ian Rogers30fab402012-01-23 15:43:46 -08003722 reinterpret_cast<HeapChunkContext*>(arg)->HeapChunkCallback(start, end, used_bytes);
Elliott Hughesa2155262011-11-16 16:26:58 -08003723 }
3724
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003725 private:
Elliott Hughesa2155262011-11-16 16:26:58 -08003726 enum { ALLOCATION_UNIT_SIZE = 8 };
3727
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003728 void Reset() {
Ian Rogers30fab402012-01-23 15:43:46 -08003729 p_ = &buf_[0];
Ian Rogers15bf2d32012-08-28 17:33:04 -07003730 startOfNextMemoryChunk_ = NULL;
Ian Rogers30fab402012-01-23 15:43:46 -08003731 totalAllocationUnits_ = 0;
3732 needHeader_ = true;
3733 pieceLenField_ = NULL;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003734 }
3735
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003736 void HeapChunkCallback(void* start, void* /*end*/, size_t used_bytes)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003737 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_,
3738 Locks::mutator_lock_) {
Ian Rogers30fab402012-01-23 15:43:46 -08003739 // Note: heap call backs cannot manipulate the heap upon which they are crawling, care is taken
3740 // in the following code not to allocate memory, by ensuring buf_ is of the correct size
Ian Rogers15bf2d32012-08-28 17:33:04 -07003741 if (used_bytes == 0) {
3742 if (start == NULL) {
3743 // Reset for start of new heap.
3744 startOfNextMemoryChunk_ = NULL;
3745 Flush();
3746 }
3747 // Only process in use memory so that free region information
3748 // also includes dlmalloc book keeping.
Elliott Hughesa2155262011-11-16 16:26:58 -08003749 return;
Elliott Hughesa2155262011-11-16 16:26:58 -08003750 }
3751
Ian Rogers15bf2d32012-08-28 17:33:04 -07003752 /* If we're looking at the native heap, we'll just return
3753 * (SOLIDITY_HARD, KIND_NATIVE) for all allocated chunks
3754 */
3755 bool native = type_ == CHUNK_TYPE("NHSG");
3756
3757 if (startOfNextMemoryChunk_ != NULL) {
3758 // Transmit any pending free memory. Native free memory of
3759 // over kMaxFreeLen could be because of the use of mmaps, so
3760 // don't report. If not free memory then start a new segment.
3761 bool flush = true;
3762 if (start > startOfNextMemoryChunk_) {
3763 const size_t kMaxFreeLen = 2 * kPageSize;
3764 void* freeStart = startOfNextMemoryChunk_;
3765 void* freeEnd = start;
Brian Carlstrom2d888622013-07-18 17:02:00 -07003766 size_t freeLen = reinterpret_cast<char*>(freeEnd) - reinterpret_cast<char*>(freeStart);
Ian Rogers15bf2d32012-08-28 17:33:04 -07003767 if (!native || freeLen < kMaxFreeLen) {
3768 AppendChunk(HPSG_STATE(SOLIDITY_FREE, 0), freeStart, freeLen);
3769 flush = false;
3770 }
3771 }
3772 if (flush) {
3773 startOfNextMemoryChunk_ = NULL;
3774 Flush();
3775 }
3776 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08003777 mirror::Object* obj = reinterpret_cast<mirror::Object*>(start);
Elliott Hughesa2155262011-11-16 16:26:58 -08003778
3779 // Determine the type of this chunk.
3780 // OLD-TODO: if context.merge, see if this chunk is different from the last chunk.
3781 // If it's the same, we should combine them.
Ian Rogers15bf2d32012-08-28 17:33:04 -07003782 uint8_t state = ExamineObject(obj, native);
3783 // dlmalloc's chunk header is 2 * sizeof(size_t), but if the previous chunk is in use for an
3784 // allocation then the first sizeof(size_t) may belong to it.
3785 const size_t dlMallocOverhead = sizeof(size_t);
3786 AppendChunk(state, start, used_bytes + dlMallocOverhead);
Brian Carlstrom2d888622013-07-18 17:02:00 -07003787 startOfNextMemoryChunk_ = reinterpret_cast<char*>(start) + used_bytes + dlMallocOverhead;
Ian Rogers15bf2d32012-08-28 17:33:04 -07003788 }
Elliott Hughesa2155262011-11-16 16:26:58 -08003789
Ian Rogers15bf2d32012-08-28 17:33:04 -07003790 void AppendChunk(uint8_t state, void* ptr, size_t length)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003791 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07003792 // Make sure there's enough room left in the buffer.
3793 // We need to use two bytes for every fractional 256 allocation units used by the chunk plus
3794 // 17 bytes for any header.
3795 size_t needed = (((length/ALLOCATION_UNIT_SIZE + 255) / 256) * 2) + 17;
3796 size_t bytesLeft = buf_.size() - (size_t)(p_ - &buf_[0]);
3797 if (bytesLeft < needed) {
3798 Flush();
3799 }
3800
3801 bytesLeft = buf_.size() - (size_t)(p_ - &buf_[0]);
3802 if (bytesLeft < needed) {
3803 LOG(WARNING) << "Chunk is too big to transmit (chunk_len=" << length << ", "
3804 << needed << " bytes)";
3805 return;
3806 }
3807 EnsureHeader(ptr);
Elliott Hughesa2155262011-11-16 16:26:58 -08003808 // Write out the chunk description.
Ian Rogers15bf2d32012-08-28 17:33:04 -07003809 length /= ALLOCATION_UNIT_SIZE; // Convert to allocation units.
3810 totalAllocationUnits_ += length;
3811 while (length > 256) {
Ian Rogers30fab402012-01-23 15:43:46 -08003812 *p_++ = state | HPSG_PARTIAL;
3813 *p_++ = 255; // length - 1
Ian Rogers15bf2d32012-08-28 17:33:04 -07003814 length -= 256;
Elliott Hughesa2155262011-11-16 16:26:58 -08003815 }
Ian Rogers30fab402012-01-23 15:43:46 -08003816 *p_++ = state;
Ian Rogers15bf2d32012-08-28 17:33:04 -07003817 *p_++ = length - 1;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003818 }
3819
Ian Rogersef7d42f2014-01-06 12:55:46 -08003820 uint8_t ExamineObject(mirror::Object* o, bool is_native_heap)
3821 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Elliott Hughesa2155262011-11-16 16:26:58 -08003822 if (o == NULL) {
3823 return HPSG_STATE(SOLIDITY_FREE, 0);
3824 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003825
Elliott Hughesa2155262011-11-16 16:26:58 -08003826 // It's an allocated chunk. Figure out what it is.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003827
Elliott Hughesa2155262011-11-16 16:26:58 -08003828 // If we're looking at the native heap, we'll just return
3829 // (SOLIDITY_HARD, KIND_NATIVE) for all allocated chunks.
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003830 if (is_native_heap) {
Elliott Hughesa2155262011-11-16 16:26:58 -08003831 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
3832 }
3833
Ian Rogers5bfa60f2012-09-02 21:17:56 -07003834 if (!Runtime::Current()->GetHeap()->IsLiveObjectLocked(o)) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07003835 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003836 }
3837
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003838 mirror::Class* c = o->GetClass();
Elliott Hughesa2155262011-11-16 16:26:58 -08003839 if (c == NULL) {
3840 // The object was probably just created but hasn't been initialized yet.
3841 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
3842 }
3843
Mathieu Chartier590fee92013-09-13 13:46:47 -07003844 if (!Runtime::Current()->GetHeap()->IsValidObjectAddress(c)) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07003845 LOG(ERROR) << "Invalid class for managed heap object: " << o << " " << c;
Elliott Hughesa2155262011-11-16 16:26:58 -08003846 return HPSG_STATE(SOLIDITY_HARD, KIND_UNKNOWN);
3847 }
3848
3849 if (c->IsClassClass()) {
3850 return HPSG_STATE(SOLIDITY_HARD, KIND_CLASS_OBJECT);
3851 }
3852
3853 if (c->IsArrayClass()) {
3854 if (o->IsObjectArray()) {
3855 return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
3856 }
3857 switch (c->GetComponentSize()) {
3858 case 1: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_1);
3859 case 2: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_2);
3860 case 4: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
3861 case 8: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_8);
3862 }
3863 }
3864
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003865 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
3866 }
3867
Ian Rogers30fab402012-01-23 15:43:46 -08003868 std::vector<uint8_t> buf_;
3869 uint8_t* p_;
3870 uint8_t* pieceLenField_;
Ian Rogers15bf2d32012-08-28 17:33:04 -07003871 void* startOfNextMemoryChunk_;
Ian Rogers30fab402012-01-23 15:43:46 -08003872 size_t totalAllocationUnits_;
3873 uint32_t type_;
3874 bool merge_;
3875 bool needHeader_;
3876
Elliott Hughesa2155262011-11-16 16:26:58 -08003877 DISALLOW_COPY_AND_ASSIGN(HeapChunkContext);
3878};
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003879
3880void Dbg::DdmSendHeapSegments(bool native) {
3881 Dbg::HpsgWhen when;
3882 Dbg::HpsgWhat what;
3883 if (!native) {
3884 when = gDdmHpsgWhen;
3885 what = gDdmHpsgWhat;
3886 } else {
3887 when = gDdmNhsgWhen;
3888 what = gDdmNhsgWhat;
3889 }
3890 if (when == HPSG_WHEN_NEVER) {
3891 return;
3892 }
3893
3894 // Figure out what kind of chunks we'll be sending.
3895 CHECK(what == HPSG_WHAT_MERGED_OBJECTS || what == HPSG_WHAT_DISTINCT_OBJECTS) << static_cast<int>(what);
3896
3897 // First, send a heap start chunk.
3898 uint8_t heap_id[4];
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003899 JDWP::Set4BE(&heap_id[0], 1); // Heap id (bogus; we only have one heap).
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003900 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHST") : CHUNK_TYPE("HPST"), sizeof(heap_id), heap_id);
3901
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07003902 Thread* self = Thread::Current();
3903
3904 // To allow the Walk/InspectAll() below to exclusively-lock the
3905 // mutator lock, temporarily release the shared access to the
3906 // mutator lock here by transitioning to the suspended state.
3907 Locks::mutator_lock_->AssertSharedHeld(self);
3908 self->TransitionFromRunnableToSuspended(kSuspended);
3909
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003910 // Send a series of heap segment chunks.
Elliott Hughesa2155262011-11-16 16:26:58 -08003911 HeapChunkContext context((what == HPSG_WHAT_MERGED_OBJECTS), native);
3912 if (native) {
Ian Rogers1d54e732013-05-02 21:10:01 -07003913 dlmalloc_inspect_all(HeapChunkContext::HeapChunkCallback, &context);
Elliott Hughesa2155262011-11-16 16:26:58 -08003914 } else {
Ian Rogers1d54e732013-05-02 21:10:01 -07003915 gc::Heap* heap = Runtime::Current()->GetHeap();
3916 const std::vector<gc::space::ContinuousSpace*>& spaces = heap->GetContinuousSpaces();
Ian Rogers1d54e732013-05-02 21:10:01 -07003917 typedef std::vector<gc::space::ContinuousSpace*>::const_iterator It;
3918 for (It cur = spaces.begin(), end = spaces.end(); cur != end; ++cur) {
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07003919 if ((*cur)->IsMallocSpace()) {
3920 (*cur)->AsMallocSpace()->Walk(HeapChunkContext::HeapChunkCallback, &context);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07003921 }
3922 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07003923 // Walk the large objects, these are not in the AllocSpace.
3924 heap->GetLargeObjectsSpace()->Walk(HeapChunkContext::HeapChunkCallback, &context);
Elliott Hughesa2155262011-11-16 16:26:58 -08003925 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003926
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07003927 // Shared-lock the mutator lock back.
3928 self->TransitionFromSuspendedToRunnable();
3929 Locks::mutator_lock_->AssertSharedHeld(self);
3930
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003931 // Finally, send a heap end chunk.
3932 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHEN") : CHUNK_TYPE("HPEN"), sizeof(heap_id), heap_id);
Elliott Hughes767a1472011-10-26 18:49:02 -07003933}
3934
Elliott Hughesb1a58792013-07-11 18:10:58 -07003935static size_t GetAllocTrackerMax() {
3936#ifdef HAVE_ANDROID_OS
3937 // Check whether there's a system property overriding the number of records.
3938 const char* propertyName = "dalvik.vm.allocTrackerMax";
3939 char allocRecordMaxString[PROPERTY_VALUE_MAX];
3940 if (property_get(propertyName, allocRecordMaxString, "") > 0) {
3941 char* end;
3942 size_t value = strtoul(allocRecordMaxString, &end, 10);
3943 if (*end != '\0') {
Ruben Brunk3e47a742013-09-09 17:56:07 -07003944 LOG(ERROR) << "Ignoring " << propertyName << " '" << allocRecordMaxString
3945 << "' --- invalid";
Elliott Hughesb1a58792013-07-11 18:10:58 -07003946 return kDefaultNumAllocRecords;
3947 }
3948 if (!IsPowerOfTwo(value)) {
Ruben Brunk3e47a742013-09-09 17:56:07 -07003949 LOG(ERROR) << "Ignoring " << propertyName << " '" << allocRecordMaxString
3950 << "' --- not power of two";
Elliott Hughesb1a58792013-07-11 18:10:58 -07003951 return kDefaultNumAllocRecords;
3952 }
3953 return value;
3954 }
3955#endif
3956 return kDefaultNumAllocRecords;
3957}
3958
Elliott Hughes545a0642011-11-08 19:10:03 -08003959void Dbg::SetAllocTrackingEnabled(bool enabled) {
Elliott Hughes545a0642011-11-08 19:10:03 -08003960 if (enabled) {
Sebastien Hertzb98063a2014-03-26 10:57:20 +01003961 {
3962 MutexLock mu(Thread::Current(), *alloc_tracker_lock_);
3963 if (recent_allocation_records_ == NULL) {
3964 alloc_record_max_ = GetAllocTrackerMax();
3965 LOG(INFO) << "Enabling alloc tracker (" << alloc_record_max_ << " entries of "
3966 << kMaxAllocRecordStackDepth << " frames, taking "
3967 << PrettySize(sizeof(AllocRecord) * alloc_record_max_) << ")";
3968 alloc_record_head_ = alloc_record_count_ = 0;
3969 recent_allocation_records_ = new AllocRecord[alloc_record_max_];
3970 CHECK(recent_allocation_records_ != NULL);
3971 }
Elliott Hughes545a0642011-11-08 19:10:03 -08003972 }
Ian Rogersfa824272013-11-05 16:12:57 -08003973 Runtime::Current()->GetInstrumentation()->InstrumentQuickAllocEntryPoints();
Elliott Hughes545a0642011-11-08 19:10:03 -08003974 } else {
Ian Rogersfa824272013-11-05 16:12:57 -08003975 Runtime::Current()->GetInstrumentation()->UninstrumentQuickAllocEntryPoints();
Sebastien Hertzb98063a2014-03-26 10:57:20 +01003976 {
3977 MutexLock mu(Thread::Current(), *alloc_tracker_lock_);
3978 delete[] recent_allocation_records_;
3979 recent_allocation_records_ = NULL;
3980 }
Elliott Hughes545a0642011-11-08 19:10:03 -08003981 }
3982}
3983
Ian Rogers0399dde2012-06-06 17:09:28 -07003984struct AllocRecordStackVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -08003985 AllocRecordStackVisitor(Thread* thread, AllocRecord* record)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003986 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08003987 : StackVisitor(thread, NULL), record(record), depth(0) {}
Elliott Hughes545a0642011-11-08 19:10:03 -08003988
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003989 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
3990 // annotalysis.
3991 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughes545a0642011-11-08 19:10:03 -08003992 if (depth >= kMaxAllocRecordStackDepth) {
Elliott Hughes530fa002012-03-12 11:44:49 -07003993 return false;
Elliott Hughes545a0642011-11-08 19:10:03 -08003994 }
Brian Carlstromea46f952013-07-30 01:26:50 -07003995 mirror::ArtMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07003996 if (!m->IsRuntimeMethod()) {
3997 record->stack[depth].method = m;
3998 record->stack[depth].dex_pc = GetDexPc();
Elliott Hughes530fa002012-03-12 11:44:49 -07003999 ++depth;
Elliott Hughes545a0642011-11-08 19:10:03 -08004000 }
Elliott Hughes530fa002012-03-12 11:44:49 -07004001 return true;
Elliott Hughes545a0642011-11-08 19:10:03 -08004002 }
4003
4004 ~AllocRecordStackVisitor() {
4005 // Clear out any unused stack trace elements.
4006 for (; depth < kMaxAllocRecordStackDepth; ++depth) {
4007 record->stack[depth].method = NULL;
Ian Rogers0399dde2012-06-06 17:09:28 -07004008 record->stack[depth].dex_pc = 0;
Elliott Hughes545a0642011-11-08 19:10:03 -08004009 }
4010 }
4011
4012 AllocRecord* record;
4013 size_t depth;
4014};
4015
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004016void Dbg::RecordAllocation(mirror::Class* type, size_t byte_count) {
Elliott Hughes545a0642011-11-08 19:10:03 -08004017 Thread* self = Thread::Current();
4018 CHECK(self != NULL);
4019
Ian Rogers719d1a32014-03-06 12:13:39 -08004020 MutexLock mu(self, *alloc_tracker_lock_);
Elliott Hughes545a0642011-11-08 19:10:03 -08004021 if (recent_allocation_records_ == NULL) {
4022 return;
4023 }
4024
4025 // Advance and clip.
Ian Rogers719d1a32014-03-06 12:13:39 -08004026 if (++alloc_record_head_ == alloc_record_max_) {
4027 alloc_record_head_ = 0;
Elliott Hughes545a0642011-11-08 19:10:03 -08004028 }
4029
4030 // Fill in the basics.
Ian Rogers719d1a32014-03-06 12:13:39 -08004031 AllocRecord* record = &recent_allocation_records_[alloc_record_head_];
Elliott Hughes545a0642011-11-08 19:10:03 -08004032 record->type = type;
4033 record->byte_count = byte_count;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07004034 record->thin_lock_id = self->GetThreadId();
Elliott Hughes545a0642011-11-08 19:10:03 -08004035
4036 // Fill in the stack trace.
Ian Rogers7a22fa62013-01-23 12:16:16 -08004037 AllocRecordStackVisitor visitor(self, record);
Ian Rogers0399dde2012-06-06 17:09:28 -07004038 visitor.WalkStack();
Elliott Hughes545a0642011-11-08 19:10:03 -08004039
Ian Rogers719d1a32014-03-06 12:13:39 -08004040 if (alloc_record_count_ < alloc_record_max_) {
4041 ++alloc_record_count_;
Elliott Hughes545a0642011-11-08 19:10:03 -08004042 }
4043}
4044
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004045// Returns the index of the head element.
4046//
4047// We point at the most-recently-written record, so if gAllocRecordCount is 1
4048// we want to use the current element. Take "head+1" and subtract count
4049// from it.
4050//
4051// We need to handle underflow in our circular buffer, so we add
Elliott Hughesb1a58792013-07-11 18:10:58 -07004052// gAllocRecordMax and then mask it back down.
Ian Rogers719d1a32014-03-06 12:13:39 -08004053size_t Dbg::HeadIndex() {
4054 return (Dbg::alloc_record_head_ + 1 + Dbg::alloc_record_max_ - Dbg::alloc_record_count_) &
4055 (Dbg::alloc_record_max_ - 1);
Elliott Hughes545a0642011-11-08 19:10:03 -08004056}
4057
4058void Dbg::DumpRecentAllocations() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004059 ScopedObjectAccess soa(Thread::Current());
Ian Rogers719d1a32014-03-06 12:13:39 -08004060 MutexLock mu(soa.Self(), *alloc_tracker_lock_);
Elliott Hughes545a0642011-11-08 19:10:03 -08004061 if (recent_allocation_records_ == NULL) {
4062 LOG(INFO) << "Not recording tracked allocations";
4063 return;
4064 }
4065
4066 // "i" is the head of the list. We want to start at the end of the
4067 // list and move forward to the tail.
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004068 size_t i = HeadIndex();
Ian Rogers719d1a32014-03-06 12:13:39 -08004069 size_t count = alloc_record_count_;
Elliott Hughes545a0642011-11-08 19:10:03 -08004070
Ian Rogers719d1a32014-03-06 12:13:39 -08004071 LOG(INFO) << "Tracked allocations, (head=" << alloc_record_head_ << " count=" << count << ")";
Elliott Hughes545a0642011-11-08 19:10:03 -08004072 while (count--) {
4073 AllocRecord* record = &recent_allocation_records_[i];
4074
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004075 LOG(INFO) << StringPrintf(" Thread %-2d %6zd bytes ", record->thin_lock_id, record->byte_count)
Elliott Hughes545a0642011-11-08 19:10:03 -08004076 << PrettyClass(record->type);
4077
4078 for (size_t stack_frame = 0; stack_frame < kMaxAllocRecordStackDepth; ++stack_frame) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08004079 mirror::ArtMethod* m = record->stack[stack_frame].method;
Elliott Hughes545a0642011-11-08 19:10:03 -08004080 if (m == NULL) {
4081 break;
4082 }
4083 LOG(INFO) << " " << PrettyMethod(m) << " line " << record->stack[stack_frame].LineNumber();
4084 }
4085
4086 // pause periodically to help logcat catch up
4087 if ((count % 5) == 0) {
4088 usleep(40000);
4089 }
4090
Ian Rogers719d1a32014-03-06 12:13:39 -08004091 i = (i + 1) & (alloc_record_max_ - 1);
Elliott Hughes545a0642011-11-08 19:10:03 -08004092 }
4093}
4094
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -07004095void Dbg::UpdateObjectPointers(IsMarkedCallback* callback, void* arg) {
Ian Rogers719d1a32014-03-06 12:13:39 -08004096 if (recent_allocation_records_ != nullptr) {
4097 MutexLock mu(Thread::Current(), *alloc_tracker_lock_);
4098 size_t i = HeadIndex();
4099 size_t count = alloc_record_count_;
4100 while (count--) {
4101 AllocRecord* record = &recent_allocation_records_[i];
4102 DCHECK(record != nullptr);
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -07004103 record->UpdateObjectPointers(callback, arg);
Ian Rogers719d1a32014-03-06 12:13:39 -08004104 i = (i + 1) & (alloc_record_max_ - 1);
Mathieu Chartier412c7fc2014-02-07 12:18:39 -08004105 }
4106 }
4107 if (gRegistry != nullptr) {
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -07004108 gRegistry->UpdateObjectPointers(callback, arg);
Mathieu Chartier412c7fc2014-02-07 12:18:39 -08004109 }
4110}
4111
4112void Dbg::AllowNewObjectRegistryObjects() {
4113 if (gRegistry != nullptr) {
4114 gRegistry->AllowNewObjects();
4115 }
4116}
4117
4118void Dbg::DisallowNewObjectRegistryObjects() {
4119 if (gRegistry != nullptr) {
4120 gRegistry->DisallowNewObjects();
4121 }
4122}
4123
Elliott Hughes545a0642011-11-08 19:10:03 -08004124class StringTable {
4125 public:
4126 StringTable() {
4127 }
4128
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004129 void Add(const char* s) {
Elliott Hughes545a0642011-11-08 19:10:03 -08004130 table_.insert(s);
4131 }
4132
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004133 size_t IndexOf(const char* s) const {
Mathieu Chartier02e25112013-08-14 16:14:24 -07004134 auto it = table_.find(s);
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004135 if (it == table_.end()) {
4136 LOG(FATAL) << "IndexOf(\"" << s << "\") failed";
4137 }
4138 return std::distance(table_.begin(), it);
Elliott Hughes545a0642011-11-08 19:10:03 -08004139 }
4140
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004141 size_t Size() const {
Elliott Hughes545a0642011-11-08 19:10:03 -08004142 return table_.size();
4143 }
4144
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004145 void WriteTo(std::vector<uint8_t>& bytes) const {
Mathieu Chartier02e25112013-08-14 16:14:24 -07004146 for (const std::string& str : table_) {
4147 const char* s = str.c_str();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004148 size_t s_len = CountModifiedUtf8Chars(s);
4149 UniquePtr<uint16_t> s_utf16(new uint16_t[s_len]);
4150 ConvertModifiedUtf8ToUtf16(s_utf16.get(), s);
4151 JDWP::AppendUtf16BE(bytes, s_utf16.get(), s_len);
Elliott Hughes545a0642011-11-08 19:10:03 -08004152 }
4153 }
4154
4155 private:
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004156 std::set<std::string> table_;
Elliott Hughes545a0642011-11-08 19:10:03 -08004157 DISALLOW_COPY_AND_ASSIGN(StringTable);
4158};
4159
4160/*
4161 * The data we send to DDMS contains everything we have recorded.
4162 *
4163 * Message header (all values big-endian):
4164 * (1b) message header len (to allow future expansion); includes itself
4165 * (1b) entry header len
4166 * (1b) stack frame len
4167 * (2b) number of entries
4168 * (4b) offset to string table from start of message
4169 * (2b) number of class name strings
4170 * (2b) number of method name strings
4171 * (2b) number of source file name strings
4172 * For each entry:
4173 * (4b) total allocation size
Elliott Hughes221229c2013-01-08 18:17:50 -08004174 * (2b) thread id
Elliott Hughes545a0642011-11-08 19:10:03 -08004175 * (2b) allocated object's class name index
4176 * (1b) stack depth
4177 * For each stack frame:
4178 * (2b) method's class name
4179 * (2b) method name
4180 * (2b) method source file
4181 * (2b) line number, clipped to 32767; -2 if native; -1 if no source
4182 * (xb) class name strings
4183 * (xb) method name strings
4184 * (xb) source file strings
4185 *
4186 * As with other DDM traffic, strings are sent as a 4-byte length
4187 * followed by UTF-16 data.
4188 *
4189 * We send up 16-bit unsigned indexes into string tables. In theory there
Elliott Hughesb1a58792013-07-11 18:10:58 -07004190 * can be (kMaxAllocRecordStackDepth * gAllocRecordMax) unique strings in
Elliott Hughes545a0642011-11-08 19:10:03 -08004191 * each table, but in practice there should be far fewer.
4192 *
4193 * The chief reason for using a string table here is to keep the size of
4194 * the DDMS message to a minimum. This is partly to make the protocol
4195 * efficient, but also because we have to form the whole thing up all at
4196 * once in a memory buffer.
4197 *
4198 * We use separate string tables for class names, method names, and source
4199 * files to keep the indexes small. There will generally be no overlap
4200 * between the contents of these tables.
4201 */
4202jbyteArray Dbg::GetRecentAllocations() {
4203 if (false) {
4204 DumpRecentAllocations();
4205 }
4206
Ian Rogers50b35e22012-10-04 10:09:15 -07004207 Thread* self = Thread::Current();
Elliott Hughes545a0642011-11-08 19:10:03 -08004208 std::vector<uint8_t> bytes;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004209 {
Ian Rogers719d1a32014-03-06 12:13:39 -08004210 MutexLock mu(self, *alloc_tracker_lock_);
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004211 //
4212 // Part 1: generate string tables.
4213 //
4214 StringTable class_names;
4215 StringTable method_names;
4216 StringTable filenames;
Elliott Hughes545a0642011-11-08 19:10:03 -08004217
Ian Rogers719d1a32014-03-06 12:13:39 -08004218 int count = alloc_record_count_;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004219 int idx = HeadIndex();
4220 while (count--) {
4221 AllocRecord* record = &recent_allocation_records_[idx];
Elliott Hughes545a0642011-11-08 19:10:03 -08004222
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004223 class_names.Add(ClassHelper(record->type).GetDescriptor());
Elliott Hughes545a0642011-11-08 19:10:03 -08004224
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004225 MethodHelper mh;
4226 for (size_t i = 0; i < kMaxAllocRecordStackDepth; i++) {
Brian Carlstromea46f952013-07-30 01:26:50 -07004227 mirror::ArtMethod* m = record->stack[i].method;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004228 if (m != NULL) {
4229 mh.ChangeMethod(m);
4230 class_names.Add(mh.GetDeclaringClassDescriptor());
4231 method_names.Add(mh.GetName());
4232 filenames.Add(mh.GetDeclaringClassSourceFile());
4233 }
4234 }
Elliott Hughes545a0642011-11-08 19:10:03 -08004235
Ian Rogers719d1a32014-03-06 12:13:39 -08004236 idx = (idx + 1) & (alloc_record_max_ - 1);
Elliott Hughes545a0642011-11-08 19:10:03 -08004237 }
4238
Ian Rogers719d1a32014-03-06 12:13:39 -08004239 LOG(INFO) << "allocation records: " << alloc_record_count_;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004240
4241 //
4242 // Part 2: Generate the output and store it in the buffer.
4243 //
4244
4245 // (1b) message header len (to allow future expansion); includes itself
4246 // (1b) entry header len
4247 // (1b) stack frame len
4248 const int kMessageHeaderLen = 15;
4249 const int kEntryHeaderLen = 9;
4250 const int kStackFrameLen = 8;
4251 JDWP::Append1BE(bytes, kMessageHeaderLen);
4252 JDWP::Append1BE(bytes, kEntryHeaderLen);
4253 JDWP::Append1BE(bytes, kStackFrameLen);
4254
4255 // (2b) number of entries
4256 // (4b) offset to string table from start of message
4257 // (2b) number of class name strings
4258 // (2b) number of method name strings
4259 // (2b) number of source file name strings
Ian Rogers719d1a32014-03-06 12:13:39 -08004260 JDWP::Append2BE(bytes, alloc_record_count_);
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004261 size_t string_table_offset = bytes.size();
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004262 JDWP::Append4BE(bytes, 0); // We'll patch this later...
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004263 JDWP::Append2BE(bytes, class_names.Size());
4264 JDWP::Append2BE(bytes, method_names.Size());
4265 JDWP::Append2BE(bytes, filenames.Size());
4266
Ian Rogers719d1a32014-03-06 12:13:39 -08004267 count = alloc_record_count_;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004268 idx = HeadIndex();
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004269 while (count--) {
4270 // For each entry:
4271 // (4b) total allocation size
4272 // (2b) thread id
4273 // (2b) allocated object's class name index
4274 // (1b) stack depth
4275 AllocRecord* record = &recent_allocation_records_[idx];
4276 size_t stack_depth = record->GetDepth();
Mathieu Chartier590fee92013-09-13 13:46:47 -07004277 ClassHelper kh(record->type);
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004278 size_t allocated_object_class_name_index = class_names.IndexOf(kh.GetDescriptor());
4279 JDWP::Append4BE(bytes, record->byte_count);
4280 JDWP::Append2BE(bytes, record->thin_lock_id);
4281 JDWP::Append2BE(bytes, allocated_object_class_name_index);
4282 JDWP::Append1BE(bytes, stack_depth);
4283
4284 MethodHelper mh;
4285 for (size_t stack_frame = 0; stack_frame < stack_depth; ++stack_frame) {
4286 // For each stack frame:
4287 // (2b) method's class name
4288 // (2b) method name
4289 // (2b) method source file
4290 // (2b) line number, clipped to 32767; -2 if native; -1 if no source
4291 mh.ChangeMethod(record->stack[stack_frame].method);
4292 size_t class_name_index = class_names.IndexOf(mh.GetDeclaringClassDescriptor());
4293 size_t method_name_index = method_names.IndexOf(mh.GetName());
4294 size_t file_name_index = filenames.IndexOf(mh.GetDeclaringClassSourceFile());
4295 JDWP::Append2BE(bytes, class_name_index);
4296 JDWP::Append2BE(bytes, method_name_index);
4297 JDWP::Append2BE(bytes, file_name_index);
4298 JDWP::Append2BE(bytes, record->stack[stack_frame].LineNumber());
4299 }
4300
Ian Rogers719d1a32014-03-06 12:13:39 -08004301 idx = (idx + 1) & (alloc_record_max_ - 1);
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004302 }
4303
4304 // (xb) class name strings
4305 // (xb) method name strings
4306 // (xb) source file strings
4307 JDWP::Set4BE(&bytes[string_table_offset], bytes.size());
4308 class_names.WriteTo(bytes);
4309 method_names.WriteTo(bytes);
4310 filenames.WriteTo(bytes);
Elliott Hughes545a0642011-11-08 19:10:03 -08004311 }
Ian Rogers50b35e22012-10-04 10:09:15 -07004312 JNIEnv* env = self->GetJniEnv();
Elliott Hughes545a0642011-11-08 19:10:03 -08004313 jbyteArray result = env->NewByteArray(bytes.size());
4314 if (result != NULL) {
4315 env->SetByteArrayRegion(result, 0, bytes.size(), reinterpret_cast<const jbyte*>(&bytes[0]));
4316 }
4317 return result;
4318}
4319
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004320} // namespace art