blob: 62019fa025d382e021d259551cd69c84d2e27470 [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"
Ian Rogers53b8b092014-03-13 23:45:53 -070041#include "reflection.h"
Elliott Hughesa0e18062012-04-13 15:59:59 -070042#include "safe_map.h"
Elliott Hughes64f574f2013-02-20 14:57:12 -080043#include "scoped_thread_state_change.h"
Elliott Hughes6a5bd492011-10-28 14:33:57 -070044#include "ScopedLocalRef.h"
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -070045#include "ScopedPrimitiveArray.h"
Ian Rogers1f539342012-10-03 21:09:42 -070046#include "sirt_ref.h"
Elliott Hughes47fce012011-10-25 18:37:19 -070047#include "stack_indirect_reference_table.h"
Elliott Hughes475fc232011-10-25 15:00:35 -070048#include "thread_list.h"
Ian Rogers62d6c772013-02-27 08:32:07 -080049#include "throw_location.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080050#include "utf.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070051#include "well_known_classes.h"
Elliott Hughes475fc232011-10-25 15:00:35 -070052
Brian Carlstrom3d92d522013-07-12 09:03:08 -070053#ifdef HAVE_ANDROID_OS
54#include "cutils/properties.h"
55#endif
56
Elliott Hughes872d4ec2011-10-21 17:07:15 -070057namespace art {
58
Brian Carlstrom7934ac22013-07-26 10:54:15 -070059static const size_t kMaxAllocRecordStackDepth = 16; // Max 255.
60static const size_t kDefaultNumAllocRecords = 64*1024; // Must be a power of 2.
Elliott Hughes475fc232011-10-25 15:00:35 -070061
Elliott Hughes545a0642011-11-08 19:10:03 -080062struct AllocRecordStackTraceElement {
Brian Carlstromea46f952013-07-30 01:26:50 -070063 mirror::ArtMethod* method;
Ian Rogers0399dde2012-06-06 17:09:28 -070064 uint32_t dex_pc;
Elliott Hughes545a0642011-11-08 19:10:03 -080065
Mathieu Chartier412c7fc2014-02-07 12:18:39 -080066 AllocRecordStackTraceElement() : method(nullptr), dex_pc(0) {
67 }
68
Ian Rogersb726dcb2012-09-05 08:57:23 -070069 int32_t LineNumber() const SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers0399dde2012-06-06 17:09:28 -070070 return MethodHelper(method).GetLineNumFromDexPC(dex_pc);
Elliott Hughes545a0642011-11-08 19:10:03 -080071 }
72};
73
74struct AllocRecord {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080075 mirror::Class* type;
Elliott Hughes545a0642011-11-08 19:10:03 -080076 size_t byte_count;
77 uint16_t thin_lock_id;
Brian Carlstrom7934ac22013-07-26 10:54:15 -070078 AllocRecordStackTraceElement stack[kMaxAllocRecordStackDepth]; // Unused entries have NULL method.
Elliott Hughes545a0642011-11-08 19:10:03 -080079
80 size_t GetDepth() {
81 size_t depth = 0;
82 while (depth < kMaxAllocRecordStackDepth && stack[depth].method != NULL) {
83 ++depth;
84 }
85 return depth;
86 }
Mathieu Chartier412c7fc2014-02-07 12:18:39 -080087
Mathieu Chartier83c8ee02014-01-28 14:50:23 -080088 void UpdateObjectPointers(IsMarkedCallback* callback, void* arg)
Mathieu Chartier412c7fc2014-02-07 12:18:39 -080089 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
90 if (type != nullptr) {
Mathieu Chartier83c8ee02014-01-28 14:50:23 -080091 type = down_cast<mirror::Class*>(callback(type, arg));
Mathieu Chartier412c7fc2014-02-07 12:18:39 -080092 }
93 for (size_t stack_frame = 0; stack_frame < kMaxAllocRecordStackDepth; ++stack_frame) {
94 mirror::ArtMethod*& m = stack[stack_frame].method;
95 if (m == nullptr) {
96 break;
97 }
Mathieu Chartier83c8ee02014-01-28 14:50:23 -080098 m = down_cast<mirror::ArtMethod*>(callback(m, arg));
Mathieu Chartier412c7fc2014-02-07 12:18:39 -080099 }
100 }
Elliott Hughes545a0642011-11-08 19:10:03 -0800101};
102
Elliott Hughes86964332012-02-15 19:37:42 -0800103struct Breakpoint {
Brian Carlstromea46f952013-07-30 01:26:50 -0700104 mirror::ArtMethod* method;
Elliott Hughesa656a0f2012-02-21 18:03:44 -0800105 uint32_t dex_pc;
Brian Carlstromea46f952013-07-30 01:26:50 -0700106 Breakpoint(mirror::ArtMethod* method, uint32_t dex_pc) : method(method), dex_pc(dex_pc) {}
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700107
108 void VisitRoots(RootCallback* callback, void* arg) {
109 if (method != nullptr) {
110 callback(reinterpret_cast<mirror::Object**>(&method), arg, 0, kRootDebugger);
111 }
112 }
Elliott Hughes86964332012-02-15 19:37:42 -0800113};
114
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700115static std::ostream& operator<<(std::ostream& os, const Breakpoint& rhs)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700116 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes229feb72012-02-23 13:33:29 -0800117 os << StringPrintf("Breakpoint[%s @%#x]", PrettyMethod(rhs.method).c_str(), rhs.dex_pc);
Elliott Hughes86964332012-02-15 19:37:42 -0800118 return os;
119}
120
Ian Rogers62d6c772013-02-27 08:32:07 -0800121class DebugInstrumentationListener : public instrumentation::InstrumentationListener {
122 public:
123 DebugInstrumentationListener() {}
124 virtual ~DebugInstrumentationListener() {}
125
126 virtual void MethodEntered(Thread* thread, mirror::Object* this_object,
Ian Rogersef7d42f2014-01-06 12:55:46 -0800127 mirror::ArtMethod* method, uint32_t dex_pc)
Ian Rogers62d6c772013-02-27 08:32:07 -0800128 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
129 if (method->IsNative()) {
130 // TODO: post location events is a suspension point and native method entry stubs aren't.
131 return;
132 }
Jeff Hao579b0242013-11-18 13:16:49 -0800133 Dbg::PostLocationEvent(method, 0, this_object, Dbg::kMethodEntry, nullptr);
Ian Rogers62d6c772013-02-27 08:32:07 -0800134 }
135
136 virtual void MethodExited(Thread* thread, mirror::Object* this_object,
Ian Rogersef7d42f2014-01-06 12:55:46 -0800137 mirror::ArtMethod* method,
Ian Rogers62d6c772013-02-27 08:32:07 -0800138 uint32_t dex_pc, const JValue& return_value)
139 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800140 if (method->IsNative()) {
141 // TODO: post location events is a suspension point and native method entry stubs aren't.
142 return;
143 }
Jeff Hao579b0242013-11-18 13:16:49 -0800144 Dbg::PostLocationEvent(method, dex_pc, this_object, Dbg::kMethodExit, &return_value);
Ian Rogers62d6c772013-02-27 08:32:07 -0800145 }
146
Sebastien Hertz51db44a2013-11-19 10:00:29 +0100147 virtual void MethodUnwind(Thread* thread, mirror::Object* this_object,
Ian Rogersef7d42f2014-01-06 12:55:46 -0800148 mirror::ArtMethod* method, uint32_t dex_pc)
Sebastien Hertz51db44a2013-11-19 10:00:29 +0100149 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800150 // We're not recorded to listen to this kind of event, so complain.
151 LOG(ERROR) << "Unexpected method unwind event in debugger " << PrettyMethod(method)
Sebastien Hertz51db44a2013-11-19 10:00:29 +0100152 << " " << dex_pc;
Ian Rogers62d6c772013-02-27 08:32:07 -0800153 }
154
155 virtual void DexPcMoved(Thread* thread, mirror::Object* this_object,
Ian Rogersef7d42f2014-01-06 12:55:46 -0800156 mirror::ArtMethod* method, uint32_t new_dex_pc)
Ian Rogers62d6c772013-02-27 08:32:07 -0800157 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
158 Dbg::UpdateDebugger(thread, this_object, method, new_dex_pc);
159 }
160
161 virtual void ExceptionCaught(Thread* thread, const ThrowLocation& throw_location,
Brian Carlstromea46f952013-07-30 01:26:50 -0700162 mirror::ArtMethod* catch_method, uint32_t catch_dex_pc,
Ian Rogers62d6c772013-02-27 08:32:07 -0800163 mirror::Throwable* exception_object)
164 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
165 Dbg::PostException(thread, throw_location, catch_method, catch_dex_pc, exception_object);
166 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800167} gDebugInstrumentationListener;
168
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700169// JDWP is allowed unless the Zygote forbids it.
170static bool gJdwpAllowed = true;
171
Elliott Hughesc0f09332012-03-26 13:27:06 -0700172// Was there a -Xrunjdwp or -agentlib:jdwp= argument on the command line?
Elliott Hughes3bb81562011-10-21 18:52:59 -0700173static bool gJdwpConfigured = false;
174
Elliott Hughesc0f09332012-03-26 13:27:06 -0700175// Broken-down JDWP options. (Only valid if IsJdwpConfigured() is true.)
Elliott Hughes376a7a02011-10-24 18:35:55 -0700176static JDWP::JdwpOptions gJdwpOptions;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700177
178// Runtime JDWP state.
179static JDWP::JdwpState* gJdwpState = NULL;
180static bool gDebuggerConnected; // debugger or DDMS is connected.
181static bool gDebuggerActive; // debugger is making requests.
Elliott Hughes86964332012-02-15 19:37:42 -0800182static bool gDisposed; // debugger called VirtualMachine.Dispose, so we should drop the connection.
Elliott Hughes3bb81562011-10-21 18:52:59 -0700183
Elliott Hughes47fce012011-10-25 18:37:19 -0700184static bool gDdmThreadNotification = false;
185
Elliott Hughes767a1472011-10-26 18:49:02 -0700186// DDMS GC-related settings.
187static Dbg::HpifWhen gDdmHpifWhen = Dbg::HPIF_WHEN_NEVER;
188static Dbg::HpsgWhen gDdmHpsgWhen = Dbg::HPSG_WHEN_NEVER;
189static Dbg::HpsgWhat gDdmHpsgWhat;
190static Dbg::HpsgWhen gDdmNhsgWhen = Dbg::HPSG_WHEN_NEVER;
191static Dbg::HpsgWhat gDdmNhsgWhat;
192
Ian Rogers719d1a32014-03-06 12:13:39 -0800193static ObjectRegistry* gRegistry = nullptr;
Elliott Hughes475fc232011-10-25 15:00:35 -0700194
Elliott Hughes545a0642011-11-08 19:10:03 -0800195// Recent allocation tracking.
Ian Rogers719d1a32014-03-06 12:13:39 -0800196Mutex* Dbg::alloc_tracker_lock_ = nullptr;
197AllocRecord* Dbg::recent_allocation_records_ = nullptr; // TODO: CircularBuffer<AllocRecord>
198size_t Dbg::alloc_record_max_ = 0;
199size_t Dbg::alloc_record_head_ = 0;
200size_t Dbg::alloc_record_count_ = 0;
Elliott Hughes545a0642011-11-08 19:10:03 -0800201
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100202// Deoptimization support.
Sebastien Hertz4d25df32014-03-21 17:44:46 +0100203Mutex* Dbg::deoptimization_lock_ = nullptr;
204std::vector<DeoptimizationRequest> Dbg::deoptimization_requests_;
205size_t Dbg::full_deoptimization_event_count_ = 0;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100206
207// Breakpoints.
jeffhao09bfc6a2012-12-11 18:11:43 -0800208static std::vector<Breakpoint> gBreakpoints GUARDED_BY(Locks::breakpoint_lock_);
Elliott Hughes86964332012-02-15 19:37:42 -0800209
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700210void DebugInvokeReq::VisitRoots(RootCallback* callback, void* arg, uint32_t tid,
211 RootType root_type) {
212 if (receiver != nullptr) {
213 callback(&receiver, arg, tid, root_type);
214 }
215 if (thread != nullptr) {
216 callback(&thread, arg, tid, root_type);
217 }
218 if (klass != nullptr) {
219 callback(reinterpret_cast<mirror::Object**>(&klass), arg, tid, root_type);
220 }
221 if (method != nullptr) {
222 callback(reinterpret_cast<mirror::Object**>(&method), arg, tid, root_type);
223 }
224}
225
226void SingleStepControl::VisitRoots(RootCallback* callback, void* arg, uint32_t tid,
227 RootType root_type) {
228 if (method != nullptr) {
229 callback(reinterpret_cast<mirror::Object**>(&method), arg, tid, root_type);
230 }
231}
232
Sebastien Hertz4d25df32014-03-21 17:44:46 +0100233void DeoptimizationRequest::VisitRoots(RootCallback* callback, void* arg) {
234 if (method != nullptr) {
235 callback(reinterpret_cast<mirror::Object**>(&method), arg, 0, kRootDebugger);
236 }
237}
238
Brian Carlstromea46f952013-07-30 01:26:50 -0700239static bool IsBreakpoint(const mirror::ArtMethod* m, uint32_t dex_pc)
jeffhao09bfc6a2012-12-11 18:11:43 -0800240 LOCKS_EXCLUDED(Locks::breakpoint_lock_)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700241 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
jeffhao09bfc6a2012-12-11 18:11:43 -0800242 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100243 for (size_t i = 0, e = gBreakpoints.size(); i < e; ++i) {
Elliott Hughesa656a0f2012-02-21 18:03:44 -0800244 if (gBreakpoints[i].method == m && gBreakpoints[i].dex_pc == dex_pc) {
Elliott Hughes86964332012-02-15 19:37:42 -0800245 VLOG(jdwp) << "Hit breakpoint #" << i << ": " << gBreakpoints[i];
246 return true;
247 }
248 }
249 return false;
250}
251
Sebastien Hertz52d131d2014-03-13 16:17:40 +0100252static bool IsSuspendedForDebugger(ScopedObjectAccessUnchecked& soa, Thread* thread)
253 LOCKS_EXCLUDED(Locks::thread_suspend_count_lock_) {
Elliott Hughes9e0c1752013-01-09 14:02:58 -0800254 MutexLock mu(soa.Self(), *Locks::thread_suspend_count_lock_);
255 // A thread may be suspended for GC; in this code, we really want to know whether
256 // there's a debugger suspension active.
257 return thread->IsSuspended() && thread->GetDebugSuspendCount() > 0;
258}
259
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800260static mirror::Array* DecodeArray(JDWP::RefTypeId id, JDWP::JdwpError& status)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700261 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800262 mirror::Object* o = gRegistry->Get<mirror::Object*>(id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800263 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800264 status = JDWP::ERR_INVALID_OBJECT;
265 return NULL;
266 }
267 if (!o->IsArrayInstance()) {
268 status = JDWP::ERR_INVALID_ARRAY;
269 return NULL;
270 }
271 status = JDWP::ERR_NONE;
272 return o->AsArray();
273}
274
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800275static mirror::Class* DecodeClass(JDWP::RefTypeId id, JDWP::JdwpError& status)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700276 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800277 mirror::Object* o = gRegistry->Get<mirror::Object*>(id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800278 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800279 status = JDWP::ERR_INVALID_OBJECT;
280 return NULL;
281 }
282 if (!o->IsClass()) {
283 status = JDWP::ERR_INVALID_CLASS;
284 return NULL;
285 }
286 status = JDWP::ERR_NONE;
287 return o->AsClass();
288}
289
Elliott Hughes221229c2013-01-08 18:17:50 -0800290static JDWP::JdwpError DecodeThread(ScopedObjectAccessUnchecked& soa, JDWP::ObjectId thread_id, Thread*& thread)
jeffhaoa77f0f62012-12-05 17:19:31 -0800291 EXCLUSIVE_LOCKS_REQUIRED(Locks::thread_list_lock_)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700292 LOCKS_EXCLUDED(Locks::thread_suspend_count_lock_)
293 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800294 mirror::Object* thread_peer = gRegistry->Get<mirror::Object*>(thread_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800295 if (thread_peer == NULL || thread_peer == ObjectRegistry::kInvalidObject) {
Elliott Hughes221229c2013-01-08 18:17:50 -0800296 // This isn't even an object.
297 return JDWP::ERR_INVALID_OBJECT;
Elliott Hughes436e3722012-02-17 20:01:47 -0800298 }
Elliott Hughes221229c2013-01-08 18:17:50 -0800299
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800300 mirror::Class* java_lang_Thread = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_Thread);
Elliott Hughes221229c2013-01-08 18:17:50 -0800301 if (!java_lang_Thread->IsAssignableFrom(thread_peer->GetClass())) {
302 // This isn't a thread.
303 return JDWP::ERR_INVALID_THREAD;
304 }
305
306 thread = Thread::FromManagedThread(soa, thread_peer);
307 if (thread == NULL) {
308 // This is a java.lang.Thread without a Thread*. Must be a zombie.
309 return JDWP::ERR_THREAD_NOT_ALIVE;
310 }
311 return JDWP::ERR_NONE;
Elliott Hughes436e3722012-02-17 20:01:47 -0800312}
313
Elliott Hughes24437992011-11-30 14:49:33 -0800314static JDWP::JdwpTag BasicTagFromDescriptor(const char* descriptor) {
315 // JDWP deliberately uses the descriptor characters' ASCII values for its enum.
316 // Note that by "basic" we mean that we don't get more specific than JT_OBJECT.
317 return static_cast<JDWP::JdwpTag>(descriptor[0]);
318}
319
Ian Rogers98379392014-02-24 16:53:16 -0800320static JDWP::JdwpTag TagFromClass(const ScopedObjectAccessUnchecked& soa, mirror::Class* c)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700321 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes86b00102011-12-05 17:54:26 -0800322 CHECK(c != NULL);
Elliott Hughes24437992011-11-30 14:49:33 -0800323 if (c->IsArrayClass()) {
324 return JDWP::JT_ARRAY;
325 }
Elliott Hughes24437992011-11-30 14:49:33 -0800326 if (c->IsStringClass()) {
327 return JDWP::JT_STRING;
Elliott Hughes24437992011-11-30 14:49:33 -0800328 }
Ian Rogers98379392014-02-24 16:53:16 -0800329 if (c->IsClassClass()) {
330 return JDWP::JT_CLASS_OBJECT;
331 }
332 {
333 mirror::Class* thread_class = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_Thread);
334 if (thread_class->IsAssignableFrom(c)) {
335 return JDWP::JT_THREAD;
336 }
337 }
338 {
339 mirror::Class* thread_group_class =
340 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_ThreadGroup);
341 if (thread_group_class->IsAssignableFrom(c)) {
342 return JDWP::JT_THREAD_GROUP;
343 }
344 }
345 {
346 mirror::Class* class_loader_class =
347 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_ClassLoader);
348 if (class_loader_class->IsAssignableFrom(c)) {
349 return JDWP::JT_CLASS_LOADER;
350 }
351 }
352 return JDWP::JT_OBJECT;
Elliott Hughes24437992011-11-30 14:49:33 -0800353}
354
355/*
356 * Objects declared to hold Object might actually hold a more specific
357 * type. The debugger may take a special interest in these (e.g. it
358 * wants to display the contents of Strings), so we want to return an
359 * appropriate tag.
360 *
361 * Null objects are tagged JT_OBJECT.
362 */
Ian Rogers98379392014-02-24 16:53:16 -0800363static JDWP::JdwpTag TagFromObject(const ScopedObjectAccessUnchecked& soa, mirror::Object* o)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700364 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers98379392014-02-24 16:53:16 -0800365 return (o == NULL) ? JDWP::JT_OBJECT : TagFromClass(soa, o->GetClass());
Elliott Hughes24437992011-11-30 14:49:33 -0800366}
367
368static bool IsPrimitiveTag(JDWP::JdwpTag tag) {
369 switch (tag) {
370 case JDWP::JT_BOOLEAN:
371 case JDWP::JT_BYTE:
372 case JDWP::JT_CHAR:
373 case JDWP::JT_FLOAT:
374 case JDWP::JT_DOUBLE:
375 case JDWP::JT_INT:
376 case JDWP::JT_LONG:
377 case JDWP::JT_SHORT:
378 case JDWP::JT_VOID:
379 return true;
380 default:
381 return false;
382 }
383}
384
Elliott Hughes3bb81562011-10-21 18:52:59 -0700385/*
386 * Handle one of the JDWP name/value pairs.
387 *
388 * JDWP options are:
389 * help: if specified, show help message and bail
390 * transport: may be dt_socket or dt_shmem
391 * address: for dt_socket, "host:port", or just "port" when listening
392 * server: if "y", wait for debugger to attach; if "n", attach to debugger
393 * timeout: how long to wait for debugger to connect / listen
394 *
395 * Useful with server=n (these aren't supported yet):
396 * onthrow=<exception-name>: connect to debugger when exception thrown
397 * onuncaught=y|n: connect to debugger when uncaught exception thrown
398 * launch=<command-line>: launch the debugger itself
399 *
400 * The "transport" option is required, as is "address" if server=n.
401 */
402static bool ParseJdwpOption(const std::string& name, const std::string& value) {
403 if (name == "transport") {
404 if (value == "dt_socket") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700405 gJdwpOptions.transport = JDWP::kJdwpTransportSocket;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700406 } else if (value == "dt_android_adb") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700407 gJdwpOptions.transport = JDWP::kJdwpTransportAndroidAdb;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700408 } else {
409 LOG(ERROR) << "JDWP transport not supported: " << value;
410 return false;
411 }
412 } else if (name == "server") {
413 if (value == "n") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700414 gJdwpOptions.server = false;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700415 } else if (value == "y") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700416 gJdwpOptions.server = true;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700417 } else {
418 LOG(ERROR) << "JDWP option 'server' must be 'y' or 'n'";
419 return false;
420 }
421 } else if (name == "suspend") {
422 if (value == "n") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700423 gJdwpOptions.suspend = false;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700424 } else if (value == "y") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700425 gJdwpOptions.suspend = true;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700426 } else {
427 LOG(ERROR) << "JDWP option 'suspend' must be 'y' or 'n'";
428 return false;
429 }
430 } else if (name == "address") {
431 /* this is either <port> or <host>:<port> */
432 std::string port_string;
Elliott Hughes376a7a02011-10-24 18:35:55 -0700433 gJdwpOptions.host.clear();
Elliott Hughes3bb81562011-10-21 18:52:59 -0700434 std::string::size_type colon = value.find(':');
435 if (colon != std::string::npos) {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700436 gJdwpOptions.host = value.substr(0, colon);
Elliott Hughes3bb81562011-10-21 18:52:59 -0700437 port_string = value.substr(colon + 1);
438 } else {
439 port_string = value;
440 }
441 if (port_string.empty()) {
442 LOG(ERROR) << "JDWP address missing port: " << value;
443 return false;
444 }
445 char* end;
Elliott Hughesba8eee12012-01-24 20:25:24 -0800446 uint64_t port = strtoul(port_string.c_str(), &end, 10);
447 if (*end != '\0' || port > 0xffff) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700448 LOG(ERROR) << "JDWP address has junk in port field: " << value;
449 return false;
450 }
Elliott Hughes376a7a02011-10-24 18:35:55 -0700451 gJdwpOptions.port = port;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700452 } else if (name == "launch" || name == "onthrow" || name == "oncaught" || name == "timeout") {
453 /* valid but unsupported */
454 LOG(INFO) << "Ignoring JDWP option '" << name << "'='" << value << "'";
455 } else {
456 LOG(INFO) << "Ignoring unrecognized JDWP option '" << name << "'='" << value << "'";
457 }
458
459 return true;
460}
461
462/*
463 * Parse the latter half of a -Xrunjdwp/-agentlib:jdwp= string, e.g.:
464 * "transport=dt_socket,address=8000,server=y,suspend=n"
465 */
466bool Dbg::ParseJdwpOptions(const std::string& options) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800467 VLOG(jdwp) << "ParseJdwpOptions: " << options;
Elliott Hughes47fce012011-10-25 18:37:19 -0700468
Elliott Hughes3bb81562011-10-21 18:52:59 -0700469 std::vector<std::string> pairs;
470 Split(options, ',', pairs);
471
472 for (size_t i = 0; i < pairs.size(); ++i) {
473 std::string::size_type equals = pairs[i].find('=');
474 if (equals == std::string::npos) {
475 LOG(ERROR) << "Can't parse JDWP option '" << pairs[i] << "' in '" << options << "'";
476 return false;
477 }
478 ParseJdwpOption(pairs[i].substr(0, equals), pairs[i].substr(equals + 1));
479 }
480
Elliott Hughes376a7a02011-10-24 18:35:55 -0700481 if (gJdwpOptions.transport == JDWP::kJdwpTransportUnknown) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700482 LOG(ERROR) << "Must specify JDWP transport: " << options;
483 }
Elliott Hughes376a7a02011-10-24 18:35:55 -0700484 if (!gJdwpOptions.server && (gJdwpOptions.host.empty() || gJdwpOptions.port == 0)) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700485 LOG(ERROR) << "Must specify JDWP host and port when server=n: " << options;
486 return false;
487 }
488
489 gJdwpConfigured = true;
490 return true;
491}
492
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700493void Dbg::StartJdwp() {
Elliott Hughesc0f09332012-03-26 13:27:06 -0700494 if (!gJdwpAllowed || !IsJdwpConfigured()) {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700495 // No JDWP for you!
496 return;
497 }
498
Ian Rogers719d1a32014-03-06 12:13:39 -0800499 CHECK(gRegistry == nullptr);
Elliott Hughes475fc232011-10-25 15:00:35 -0700500 gRegistry = new ObjectRegistry;
501
Ian Rogers719d1a32014-03-06 12:13:39 -0800502 alloc_tracker_lock_ = new Mutex("AllocTracker lock");
Sebastien Hertz4d25df32014-03-21 17:44:46 +0100503 deoptimization_lock_ = new Mutex("deoptimization lock", kDeoptimizationLock);
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700504 // Init JDWP if the debugger is enabled. This may connect out to a
505 // debugger, passively listen for a debugger, or block waiting for a
506 // debugger.
Elliott Hughes376a7a02011-10-24 18:35:55 -0700507 gJdwpState = JDWP::JdwpState::Create(&gJdwpOptions);
508 if (gJdwpState == NULL) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -0800509 // We probably failed because some other process has the port already, which means that
510 // if we don't abort the user is likely to think they're talking to us when they're actually
511 // talking to that other process.
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800512 LOG(FATAL) << "Debugger thread failed to initialize";
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700513 }
514
515 // If a debugger has already attached, send the "welcome" message.
516 // This may cause us to suspend all threads.
Elliott Hughes376a7a02011-10-24 18:35:55 -0700517 if (gJdwpState->IsActive()) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700518 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes376a7a02011-10-24 18:35:55 -0700519 if (!gJdwpState->PostVMStart()) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800520 LOG(WARNING) << "Failed to post 'start' message to debugger";
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700521 }
522 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700523}
524
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700525void Dbg::VisitRoots(RootCallback* callback, void* arg) {
Sebastien Hertz4d25df32014-03-21 17:44:46 +0100526 {
527 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
528 for (Breakpoint& bp : gBreakpoints) {
529 bp.VisitRoots(callback, arg);
530 }
531 }
532 if (deoptimization_lock_ != nullptr) { // only true if the debugger is started.
533 MutexLock mu(Thread::Current(), *deoptimization_lock_);
534 for (DeoptimizationRequest& req : deoptimization_requests_) {
535 req.VisitRoots(callback, arg);
536 }
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700537 }
538}
539
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700540void Dbg::StopJdwp() {
Sebastien Hertz0376e6b2014-02-06 18:12:59 +0100541 // Prevent the JDWP thread from processing JDWP incoming packets after we close the connection.
542 Disposed();
Elliott Hughes376a7a02011-10-24 18:35:55 -0700543 delete gJdwpState;
Ian Rogers719d1a32014-03-06 12:13:39 -0800544 gJdwpState = nullptr;
Elliott Hughes475fc232011-10-25 15:00:35 -0700545 delete gRegistry;
Ian Rogers719d1a32014-03-06 12:13:39 -0800546 gRegistry = nullptr;
547 delete alloc_tracker_lock_;
548 alloc_tracker_lock_ = nullptr;
Sebastien Hertz4d25df32014-03-21 17:44:46 +0100549 delete deoptimization_lock_;
550 deoptimization_lock_ = nullptr;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700551}
552
Elliott Hughes767a1472011-10-26 18:49:02 -0700553void Dbg::GcDidFinish() {
554 if (gDdmHpifWhen != HPIF_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700555 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes81ff3182012-03-23 20:35:56 -0700556 LOG(DEBUG) << "Sending heap info to DDM";
Elliott Hughes7162ad92011-10-27 14:08:42 -0700557 DdmSendHeapInfo(gDdmHpifWhen);
Elliott Hughes767a1472011-10-26 18:49:02 -0700558 }
559 if (gDdmHpsgWhen != HPSG_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700560 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes81ff3182012-03-23 20:35:56 -0700561 LOG(DEBUG) << "Dumping heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700562 DdmSendHeapSegments(false);
Elliott Hughes767a1472011-10-26 18:49:02 -0700563 }
564 if (gDdmNhsgWhen != HPSG_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700565 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes767a1472011-10-26 18:49:02 -0700566 LOG(DEBUG) << "Dumping native heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700567 DdmSendHeapSegments(true);
Elliott Hughes767a1472011-10-26 18:49:02 -0700568 }
569}
570
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700571void Dbg::SetJdwpAllowed(bool allowed) {
572 gJdwpAllowed = allowed;
573}
574
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700575DebugInvokeReq* Dbg::GetInvokeReq() {
Elliott Hughes475fc232011-10-25 15:00:35 -0700576 return Thread::Current()->GetInvokeReq();
577}
578
579Thread* Dbg::GetDebugThread() {
580 return (gJdwpState != NULL) ? gJdwpState->GetDebugThread() : NULL;
581}
582
583void Dbg::ClearWaitForEventThread() {
584 gJdwpState->ClearWaitForEventThread();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700585}
586
587void Dbg::Connected() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700588 CHECK(!gDebuggerConnected);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800589 VLOG(jdwp) << "JDWP has attached";
Elliott Hughes3bb81562011-10-21 18:52:59 -0700590 gDebuggerConnected = true;
Elliott Hughes86964332012-02-15 19:37:42 -0800591 gDisposed = false;
592}
593
594void Dbg::Disposed() {
595 gDisposed = true;
596}
597
598bool Dbg::IsDisposed() {
599 return gDisposed;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700600}
601
Elliott Hughesa2155262011-11-16 16:26:58 -0800602void Dbg::GoActive() {
603 // Enable all debugging features, including scans for breakpoints.
604 // This is a no-op if we're already active.
605 // Only called from the JDWP handler thread.
606 if (gDebuggerActive) {
607 return;
608 }
609
Elliott Hughesc0f09332012-03-26 13:27:06 -0700610 {
611 // TODO: dalvik only warned if there were breakpoints left over. clear in Dbg::Disconnected?
jeffhao09bfc6a2012-12-11 18:11:43 -0800612 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Elliott Hughesc0f09332012-03-26 13:27:06 -0700613 CHECK_EQ(gBreakpoints.size(), 0U);
614 }
Elliott Hughesa2155262011-11-16 16:26:58 -0800615
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100616 {
Sebastien Hertz4d25df32014-03-21 17:44:46 +0100617 MutexLock mu(Thread::Current(), *deoptimization_lock_);
618 CHECK_EQ(deoptimization_requests_.size(), 0U);
619 CHECK_EQ(full_deoptimization_event_count_, 0U);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100620 }
621
Ian Rogers62d6c772013-02-27 08:32:07 -0800622 Runtime* runtime = Runtime::Current();
623 runtime->GetThreadList()->SuspendAll();
624 Thread* self = Thread::Current();
625 ThreadState old_state = self->SetStateUnsafe(kRunnable);
626 CHECK_NE(old_state, kRunnable);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100627 runtime->GetInstrumentation()->EnableDeoptimization();
Ian Rogers62d6c772013-02-27 08:32:07 -0800628 runtime->GetInstrumentation()->AddListener(&gDebugInstrumentationListener,
629 instrumentation::Instrumentation::kMethodEntered |
630 instrumentation::Instrumentation::kMethodExited |
Jeff Hao14dd5a82013-04-11 10:23:36 -0700631 instrumentation::Instrumentation::kDexPcMoved |
632 instrumentation::Instrumentation::kExceptionCaught);
Elliott Hughesa2155262011-11-16 16:26:58 -0800633 gDebuggerActive = true;
Ian Rogers62d6c772013-02-27 08:32:07 -0800634 CHECK_EQ(self->SetStateUnsafe(old_state), kRunnable);
635 runtime->GetThreadList()->ResumeAll();
636
637 LOG(INFO) << "Debugger is active";
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700638}
639
640void Dbg::Disconnected() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700641 CHECK(gDebuggerConnected);
642
Elliott Hughesc0f09332012-03-26 13:27:06 -0700643 LOG(INFO) << "Debugger is no longer active";
Elliott Hughes234ab152011-10-26 14:02:26 -0700644
Ian Rogers62d6c772013-02-27 08:32:07 -0800645 // Suspend all threads and exclusively acquire the mutator lock. Set the state of the thread
646 // to kRunnable to avoid scoped object access transitions. Remove the debugger as a listener
647 // and clear the object registry.
648 Runtime* runtime = Runtime::Current();
649 runtime->GetThreadList()->SuspendAll();
650 Thread* self = Thread::Current();
651 ThreadState old_state = self->SetStateUnsafe(kRunnable);
Sebastien Hertzaaea7342014-02-25 15:10:04 +0100652
653 // Debugger may not be active at this point.
654 if (gDebuggerActive) {
655 {
656 // Since we're going to disable deoptimization, we clear the deoptimization requests queue.
657 // This prevents us from having any pending deoptimization request when the debugger attaches
658 // to us again while no event has been requested yet.
Sebastien Hertz4d25df32014-03-21 17:44:46 +0100659 MutexLock mu(Thread::Current(), *deoptimization_lock_);
660 deoptimization_requests_.clear();
661 full_deoptimization_event_count_ = 0U;
Sebastien Hertzaaea7342014-02-25 15:10:04 +0100662 }
663 runtime->GetInstrumentation()->RemoveListener(&gDebugInstrumentationListener,
664 instrumentation::Instrumentation::kMethodEntered |
665 instrumentation::Instrumentation::kMethodExited |
666 instrumentation::Instrumentation::kDexPcMoved |
667 instrumentation::Instrumentation::kExceptionCaught);
668 runtime->GetInstrumentation()->DisableDeoptimization();
669 gDebuggerActive = false;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100670 }
Elliott Hughes234ab152011-10-26 14:02:26 -0700671 gRegistry->Clear();
672 gDebuggerConnected = false;
Ian Rogers62d6c772013-02-27 08:32:07 -0800673 CHECK_EQ(self->SetStateUnsafe(old_state), kRunnable);
674 runtime->GetThreadList()->ResumeAll();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700675}
676
Elliott Hughesc0f09332012-03-26 13:27:06 -0700677bool Dbg::IsDebuggerActive() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700678 return gDebuggerActive;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700679}
680
Elliott Hughesc0f09332012-03-26 13:27:06 -0700681bool Dbg::IsJdwpConfigured() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700682 return gJdwpConfigured;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700683}
684
685int64_t Dbg::LastDebuggerActivity() {
Elliott Hughesca951522011-12-05 12:01:32 -0800686 return gJdwpState->LastDebuggerActivity();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700687}
688
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700689void Dbg::UndoDebuggerSuspensions() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700690 Runtime::Current()->GetThreadList()->UndoDebuggerSuspensions();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700691}
692
Elliott Hughes88d63092013-01-09 09:55:54 -0800693std::string Dbg::GetClassName(JDWP::RefTypeId class_id) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800694 mirror::Object* o = gRegistry->Get<mirror::Object*>(class_id);
Elliott Hughes436e3722012-02-17 20:01:47 -0800695 if (o == NULL) {
696 return "NULL";
697 }
Elliott Hughes64f574f2013-02-20 14:57:12 -0800698 if (o == ObjectRegistry::kInvalidObject) {
Elliott Hughes88d63092013-01-09 09:55:54 -0800699 return StringPrintf("invalid object %p", reinterpret_cast<void*>(class_id));
Elliott Hughes436e3722012-02-17 20:01:47 -0800700 }
701 if (!o->IsClass()) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700702 return StringPrintf("non-class %p", o); // This is only used for debugging output anyway.
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800703 }
Elliott Hughesc308a5d2012-02-16 17:12:06 -0800704 return DescriptorToName(ClassHelper(o->AsClass()).GetDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700705}
706
Elliott Hughes88d63092013-01-09 09:55:54 -0800707JDWP::JdwpError Dbg::GetClassObject(JDWP::RefTypeId id, JDWP::ObjectId& class_object_id) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800708 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800709 mirror::Class* c = DecodeClass(id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -0800710 if (c == NULL) {
711 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800712 }
Elliott Hughes88d63092013-01-09 09:55:54 -0800713 class_object_id = gRegistry->Add(c);
Elliott Hughes436e3722012-02-17 20:01:47 -0800714 return JDWP::ERR_NONE;
Elliott Hughes86964332012-02-15 19:37:42 -0800715}
716
Elliott Hughes88d63092013-01-09 09:55:54 -0800717JDWP::JdwpError Dbg::GetSuperclass(JDWP::RefTypeId id, JDWP::RefTypeId& superclass_id) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800718 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800719 mirror::Class* c = DecodeClass(id, status);
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800720 if (c == NULL) {
721 return status;
722 }
723 if (c->IsInterface()) {
724 // http://code.google.com/p/android/issues/detail?id=20856
Elliott Hughes88d63092013-01-09 09:55:54 -0800725 superclass_id = 0;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800726 } else {
Elliott Hughes88d63092013-01-09 09:55:54 -0800727 superclass_id = gRegistry->Add(c->GetSuperClass());
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800728 }
729 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700730}
731
Elliott Hughes436e3722012-02-17 20:01:47 -0800732JDWP::JdwpError Dbg::GetClassLoader(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800733 mirror::Object* o = gRegistry->Get<mirror::Object*>(id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800734 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800735 return JDWP::ERR_INVALID_OBJECT;
736 }
737 expandBufAddObjectId(pReply, gRegistry->Add(o->GetClass()->GetClassLoader()));
738 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700739}
740
Elliott Hughes436e3722012-02-17 20:01:47 -0800741JDWP::JdwpError Dbg::GetModifiers(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) {
742 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800743 mirror::Class* c = DecodeClass(id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -0800744 if (c == NULL) {
745 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800746 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800747
748 uint32_t access_flags = c->GetAccessFlags() & kAccJavaFlagsMask;
749
Yevgeny Roubande34eea2014-02-15 01:06:03 +0700750 // Set ACC_SUPER. Dex files don't contain this flag but only classes are supposed to have it set,
751 // not interfaces.
Elliott Hughes436e3722012-02-17 20:01:47 -0800752 // Class.getModifiers doesn't return it, but JDWP does, so we set it here.
Yevgeny Roubande34eea2014-02-15 01:06:03 +0700753 if ((access_flags & kAccInterface) == 0) {
754 access_flags |= kAccSuper;
755 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800756
757 expandBufAdd4BE(pReply, access_flags);
758
759 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700760}
761
Elliott Hughesf327e072013-01-09 16:01:26 -0800762JDWP::JdwpError Dbg::GetMonitorInfo(JDWP::ObjectId object_id, JDWP::ExpandBuf* reply)
763 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800764 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800765 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughesf327e072013-01-09 16:01:26 -0800766 return JDWP::ERR_INVALID_OBJECT;
767 }
768
769 // Ensure all threads are suspended while we read objects' lock words.
770 Thread* self = Thread::Current();
Sebastien Hertz54263242014-03-19 18:16:50 +0100771 CHECK_EQ(self->GetState(), kRunnable);
772 self->TransitionFromRunnableToSuspended(kSuspended);
773 Runtime::Current()->GetThreadList()->SuspendAll();
Elliott Hughesf327e072013-01-09 16:01:26 -0800774
775 MonitorInfo monitor_info(o);
776
Sebastien Hertz54263242014-03-19 18:16:50 +0100777 Runtime::Current()->GetThreadList()->ResumeAll();
778 self->TransitionFromSuspendedToRunnable();
Elliott Hughesf327e072013-01-09 16:01:26 -0800779
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700780 if (monitor_info.owner_ != NULL) {
781 expandBufAddObjectId(reply, gRegistry->Add(monitor_info.owner_->GetPeer()));
Elliott Hughesf327e072013-01-09 16:01:26 -0800782 } else {
783 expandBufAddObjectId(reply, gRegistry->Add(NULL));
784 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700785 expandBufAdd4BE(reply, monitor_info.entry_count_);
786 expandBufAdd4BE(reply, monitor_info.waiters_.size());
787 for (size_t i = 0; i < monitor_info.waiters_.size(); ++i) {
788 expandBufAddObjectId(reply, gRegistry->Add(monitor_info.waiters_[i]->GetPeer()));
Elliott Hughesf327e072013-01-09 16:01:26 -0800789 }
790 return JDWP::ERR_NONE;
791}
792
Elliott Hughes734b8c62013-01-11 15:32:45 -0800793JDWP::JdwpError Dbg::GetOwnedMonitors(JDWP::ObjectId thread_id,
794 std::vector<JDWP::ObjectId>& monitors,
Sebastien Hertz52d131d2014-03-13 16:17:40 +0100795 std::vector<uint32_t>& stack_depths) {
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800796 ScopedObjectAccessUnchecked soa(Thread::Current());
797 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
798 Thread* thread;
799 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
800 if (error != JDWP::ERR_NONE) {
801 return error;
802 }
803 if (!IsSuspendedForDebugger(soa, thread)) {
804 return JDWP::ERR_THREAD_NOT_SUSPENDED;
805 }
806
807 struct OwnedMonitorVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -0800808 OwnedMonitorVisitor(Thread* thread, Context* context)
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800809 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -0800810 : StackVisitor(thread, context), current_stack_depth(0) {}
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800811
812 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
813 // annotalysis.
814 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
815 if (!GetMethod()->IsRuntimeMethod()) {
816 Monitor::VisitLocks(this, AppendOwnedMonitors, this);
Elliott Hughes734b8c62013-01-11 15:32:45 -0800817 ++current_stack_depth;
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800818 }
819 return true;
820 }
821
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800822 static void AppendOwnedMonitors(mirror::Object* owned_monitor, void* arg) {
Ian Rogers7a22fa62013-01-23 12:16:16 -0800823 OwnedMonitorVisitor* visitor = reinterpret_cast<OwnedMonitorVisitor*>(arg);
Elliott Hughes734b8c62013-01-11 15:32:45 -0800824 visitor->monitors.push_back(owned_monitor);
825 visitor->stack_depths.push_back(visitor->current_stack_depth);
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800826 }
827
Elliott Hughes734b8c62013-01-11 15:32:45 -0800828 size_t current_stack_depth;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800829 std::vector<mirror::Object*> monitors;
Elliott Hughes734b8c62013-01-11 15:32:45 -0800830 std::vector<uint32_t> stack_depths;
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800831 };
Ian Rogers7a22fa62013-01-23 12:16:16 -0800832 UniquePtr<Context> context(Context::Create());
833 OwnedMonitorVisitor visitor(thread, context.get());
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800834 visitor.WalkStack();
835
836 for (size_t i = 0; i < visitor.monitors.size(); ++i) {
837 monitors.push_back(gRegistry->Add(visitor.monitors[i]));
Elliott Hughes734b8c62013-01-11 15:32:45 -0800838 stack_depths.push_back(visitor.stack_depths[i]);
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800839 }
840
841 return JDWP::ERR_NONE;
842}
843
Sebastien Hertz52d131d2014-03-13 16:17:40 +0100844JDWP::JdwpError Dbg::GetContendedMonitor(JDWP::ObjectId thread_id,
845 JDWP::ObjectId& contended_monitor) {
Elliott Hughesf9501702013-01-11 11:22:27 -0800846 ScopedObjectAccessUnchecked soa(Thread::Current());
847 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
848 Thread* thread;
849 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
850 if (error != JDWP::ERR_NONE) {
851 return error;
852 }
853 if (!IsSuspendedForDebugger(soa, thread)) {
854 return JDWP::ERR_THREAD_NOT_SUSPENDED;
855 }
856
857 contended_monitor = gRegistry->Add(Monitor::GetContendedMonitor(thread));
858
859 return JDWP::ERR_NONE;
860}
861
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800862JDWP::JdwpError Dbg::GetInstanceCounts(const std::vector<JDWP::RefTypeId>& class_ids,
863 std::vector<uint64_t>& counts)
864 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800865 gc::Heap* heap = Runtime::Current()->GetHeap();
866 heap->CollectGarbage(false);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800867 std::vector<mirror::Class*> classes;
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800868 counts.clear();
869 for (size_t i = 0; i < class_ids.size(); ++i) {
870 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800871 mirror::Class* c = DecodeClass(class_ids[i], status);
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800872 if (c == NULL) {
873 return status;
874 }
875 classes.push_back(c);
876 counts.push_back(0);
877 }
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800878 heap->CountInstances(classes, false, &counts[0]);
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800879 return JDWP::ERR_NONE;
880}
881
Elliott Hughes3b78c942013-01-15 17:35:41 -0800882JDWP::JdwpError Dbg::GetInstances(JDWP::RefTypeId class_id, int32_t max_count, std::vector<JDWP::ObjectId>& instances)
883 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800884 gc::Heap* heap = Runtime::Current()->GetHeap();
885 // We only want reachable instances, so do a GC.
886 heap->CollectGarbage(false);
Elliott Hughes3b78c942013-01-15 17:35:41 -0800887 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800888 mirror::Class* c = DecodeClass(class_id, status);
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800889 if (c == nullptr) {
Elliott Hughes3b78c942013-01-15 17:35:41 -0800890 return status;
891 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800892 std::vector<mirror::Object*> raw_instances;
Elliott Hughes3b78c942013-01-15 17:35:41 -0800893 Runtime::Current()->GetHeap()->GetInstances(c, max_count, raw_instances);
894 for (size_t i = 0; i < raw_instances.size(); ++i) {
895 instances.push_back(gRegistry->Add(raw_instances[i]));
896 }
897 return JDWP::ERR_NONE;
898}
899
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800900JDWP::JdwpError Dbg::GetReferringObjects(JDWP::ObjectId object_id, int32_t max_count,
901 std::vector<JDWP::ObjectId>& referring_objects)
902 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800903 gc::Heap* heap = Runtime::Current()->GetHeap();
904 heap->CollectGarbage(false);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800905 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800906 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800907 return JDWP::ERR_INVALID_OBJECT;
908 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800909 std::vector<mirror::Object*> raw_instances;
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800910 heap->GetReferringObjects(o, max_count, raw_instances);
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800911 for (size_t i = 0; i < raw_instances.size(); ++i) {
912 referring_objects.push_back(gRegistry->Add(raw_instances[i]));
913 }
914 return JDWP::ERR_NONE;
915}
916
Elliott Hughes64f574f2013-02-20 14:57:12 -0800917JDWP::JdwpError Dbg::DisableCollection(JDWP::ObjectId object_id)
918 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Sebastien Hertze96060a2013-12-11 12:06:28 +0100919 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
920 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
921 return JDWP::ERR_INVALID_OBJECT;
922 }
Elliott Hughes64f574f2013-02-20 14:57:12 -0800923 gRegistry->DisableCollection(object_id);
924 return JDWP::ERR_NONE;
925}
926
927JDWP::JdwpError Dbg::EnableCollection(JDWP::ObjectId object_id)
928 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Sebastien Hertze96060a2013-12-11 12:06:28 +0100929 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
930 // Unlike DisableCollection, JDWP specs do not state an invalid object causes an error. The RI
931 // also ignores these cases and never return an error. However it's not obvious why this command
932 // should behave differently from DisableCollection and IsCollected commands. So let's be more
933 // strict and return an error if this happens.
934 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
935 return JDWP::ERR_INVALID_OBJECT;
936 }
Elliott Hughes64f574f2013-02-20 14:57:12 -0800937 gRegistry->EnableCollection(object_id);
938 return JDWP::ERR_NONE;
939}
940
941JDWP::JdwpError Dbg::IsCollected(JDWP::ObjectId object_id, bool& is_collected)
942 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Sebastien Hertz65637eb2014-01-10 17:40:02 +0100943 if (object_id == 0) {
944 // Null object id is invalid.
Sebastien Hertze96060a2013-12-11 12:06:28 +0100945 return JDWP::ERR_INVALID_OBJECT;
946 }
Sebastien Hertz65637eb2014-01-10 17:40:02 +0100947 // JDWP specs state an INVALID_OBJECT error is returned if the object ID is not valid. However
948 // the RI seems to ignore this and assume object has been collected.
949 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
950 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
951 is_collected = true;
952 } else {
953 is_collected = gRegistry->IsCollected(object_id);
954 }
Elliott Hughes64f574f2013-02-20 14:57:12 -0800955 return JDWP::ERR_NONE;
956}
957
958void Dbg::DisposeObject(JDWP::ObjectId object_id, uint32_t reference_count)
959 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
960 gRegistry->DisposeObject(object_id, reference_count);
961}
962
Elliott Hughes88d63092013-01-09 09:55:54 -0800963JDWP::JdwpError Dbg::GetReflectedType(JDWP::RefTypeId class_id, JDWP::ExpandBuf* pReply) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800964 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800965 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -0800966 if (c == NULL) {
967 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800968 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800969
970 expandBufAdd1(pReply, c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS);
Elliott Hughes88d63092013-01-09 09:55:54 -0800971 expandBufAddRefTypeId(pReply, class_id);
Elliott Hughes436e3722012-02-17 20:01:47 -0800972 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700973}
974
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800975void Dbg::GetClassList(std::vector<JDWP::RefTypeId>& classes) {
Elliott Hughesa2155262011-11-16 16:26:58 -0800976 // Get the complete list of reference classes (i.e. all classes except
977 // the primitive types).
978 // Returns a newly-allocated buffer full of RefTypeId values.
979 struct ClassListCreator {
Elliott Hughesba8eee12012-01-24 20:25:24 -0800980 explicit ClassListCreator(std::vector<JDWP::RefTypeId>& classes) : classes(classes) {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800981 }
982
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800983 static bool Visit(mirror::Class* c, void* arg) {
Elliott Hughesa2155262011-11-16 16:26:58 -0800984 return reinterpret_cast<ClassListCreator*>(arg)->Visit(c);
985 }
986
Elliott Hughes64f574f2013-02-20 14:57:12 -0800987 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
988 // annotalysis.
989 bool Visit(mirror::Class* c) NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughesa2155262011-11-16 16:26:58 -0800990 if (!c->IsPrimitive()) {
Elliott Hughes64f574f2013-02-20 14:57:12 -0800991 classes.push_back(gRegistry->AddRefType(c));
Elliott Hughesa2155262011-11-16 16:26:58 -0800992 }
993 return true;
994 }
995
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800996 std::vector<JDWP::RefTypeId>& classes;
Elliott Hughesa2155262011-11-16 16:26:58 -0800997 };
998
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800999 ClassListCreator clc(classes);
Elliott Hughesa2155262011-11-16 16:26:58 -08001000 Runtime::Current()->GetClassLinker()->VisitClasses(ClassListCreator::Visit, &clc);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001001}
1002
Elliott Hughes88d63092013-01-09 09:55:54 -08001003JDWP::JdwpError Dbg::GetClassInfo(JDWP::RefTypeId class_id, JDWP::JdwpTypeTag* pTypeTag, uint32_t* pStatus, std::string* pDescriptor) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001004 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001005 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001006 if (c == NULL) {
1007 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001008 }
1009
Elliott Hughesa2155262011-11-16 16:26:58 -08001010 if (c->IsArrayClass()) {
1011 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
1012 *pTypeTag = JDWP::TT_ARRAY;
1013 } else {
1014 if (c->IsErroneous()) {
1015 *pStatus = JDWP::CS_ERROR;
1016 } else {
1017 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED | JDWP::CS_INITIALIZED;
1018 }
1019 *pTypeTag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
1020 }
1021
1022 if (pDescriptor != NULL) {
Ian Rogersdfb325e2013-10-30 01:00:44 -07001023 *pDescriptor = ClassHelper(c).GetDescriptor();
Elliott Hughesa2155262011-11-16 16:26:58 -08001024 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001025 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001026}
1027
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001028void Dbg::FindLoadedClassBySignature(const char* descriptor, std::vector<JDWP::RefTypeId>& ids) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001029 std::vector<mirror::Class*> classes;
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001030 Runtime::Current()->GetClassLinker()->LookupClasses(descriptor, classes);
1031 ids.clear();
1032 for (size_t i = 0; i < classes.size(); ++i) {
1033 ids.push_back(gRegistry->Add(classes[i]));
1034 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001035}
1036
Elliott Hughes64f574f2013-02-20 14:57:12 -08001037JDWP::JdwpError Dbg::GetReferenceType(JDWP::ObjectId object_id, JDWP::ExpandBuf* pReply)
1038 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001039 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001040 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001041 return JDWP::ERR_INVALID_OBJECT;
Elliott Hughes499c5132011-11-17 14:55:11 -08001042 }
Elliott Hughes2435a572012-02-17 16:07:41 -08001043
1044 JDWP::JdwpTypeTag type_tag;
1045 if (o->GetClass()->IsArrayClass()) {
1046 type_tag = JDWP::TT_ARRAY;
1047 } else if (o->GetClass()->IsInterface()) {
1048 type_tag = JDWP::TT_INTERFACE;
1049 } else {
1050 type_tag = JDWP::TT_CLASS;
1051 }
Elliott Hughes64f574f2013-02-20 14:57:12 -08001052 JDWP::RefTypeId type_id = gRegistry->AddRefType(o->GetClass());
Elliott Hughes2435a572012-02-17 16:07:41 -08001053
1054 expandBufAdd1(pReply, type_tag);
1055 expandBufAddRefTypeId(pReply, type_id);
1056
1057 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001058}
1059
Ian Rogersfc0e94b2013-09-23 23:51:32 -07001060JDWP::JdwpError Dbg::GetSignature(JDWP::RefTypeId class_id, std::string* signature) {
Elliott Hughes1fe7afb2012-02-13 17:23:03 -08001061 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001062 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes1fe7afb2012-02-13 17:23:03 -08001063 if (c == NULL) {
1064 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001065 }
Ian Rogersdfb325e2013-10-30 01:00:44 -07001066 *signature = ClassHelper(c).GetDescriptor();
Elliott Hughes1fe7afb2012-02-13 17:23:03 -08001067 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001068}
1069
Elliott Hughes88d63092013-01-09 09:55:54 -08001070JDWP::JdwpError Dbg::GetSourceFile(JDWP::RefTypeId class_id, std::string& result) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001071 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001072 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001073 if (c == NULL) {
1074 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001075 }
Sebastien Hertzb7054ba2014-03-13 11:52:31 +01001076 if (c->IsProxyClass()) {
1077 return JDWP::ERR_ABSENT_INFORMATION;
1078 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001079 result = ClassHelper(c).GetSourceFile();
1080 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001081}
1082
Elliott Hughes88d63092013-01-09 09:55:54 -08001083JDWP::JdwpError Dbg::GetObjectTag(JDWP::ObjectId object_id, uint8_t& tag) {
Ian Rogers98379392014-02-24 16:53:16 -08001084 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001085 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001086 if (o == ObjectRegistry::kInvalidObject) {
Elliott Hughes546b9862012-06-20 16:06:13 -07001087 return JDWP::ERR_INVALID_OBJECT;
1088 }
Ian Rogers98379392014-02-24 16:53:16 -08001089 tag = TagFromObject(soa, o);
Elliott Hughes546b9862012-06-20 16:06:13 -07001090 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001091}
1092
Elliott Hughesaed4be92011-12-02 16:16:23 -08001093size_t Dbg::GetTagWidth(JDWP::JdwpTag tag) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001094 switch (tag) {
1095 case JDWP::JT_VOID:
1096 return 0;
1097 case JDWP::JT_BYTE:
1098 case JDWP::JT_BOOLEAN:
1099 return 1;
1100 case JDWP::JT_CHAR:
1101 case JDWP::JT_SHORT:
1102 return 2;
1103 case JDWP::JT_FLOAT:
1104 case JDWP::JT_INT:
1105 return 4;
1106 case JDWP::JT_ARRAY:
1107 case JDWP::JT_OBJECT:
1108 case JDWP::JT_STRING:
1109 case JDWP::JT_THREAD:
1110 case JDWP::JT_THREAD_GROUP:
1111 case JDWP::JT_CLASS_LOADER:
1112 case JDWP::JT_CLASS_OBJECT:
1113 return sizeof(JDWP::ObjectId);
1114 case JDWP::JT_DOUBLE:
1115 case JDWP::JT_LONG:
1116 return 8;
1117 default:
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001118 LOG(FATAL) << "Unknown tag " << tag;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001119 return -1;
1120 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001121}
1122
Elliott Hughes88d63092013-01-09 09:55:54 -08001123JDWP::JdwpError Dbg::GetArrayLength(JDWP::ObjectId array_id, int& length) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001124 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001125 mirror::Array* a = DecodeArray(array_id, status);
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001126 if (a == NULL) {
1127 return status;
Elliott Hughes24437992011-11-30 14:49:33 -08001128 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001129 length = a->GetLength();
1130 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001131}
1132
Elliott Hughes88d63092013-01-09 09:55:54 -08001133JDWP::JdwpError Dbg::OutputArray(JDWP::ObjectId array_id, int offset, int count, JDWP::ExpandBuf* pReply) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001134 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001135 mirror::Array* a = DecodeArray(array_id, status);
Ian Rogers98379392014-02-24 16:53:16 -08001136 if (a == nullptr) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001137 return status;
1138 }
Elliott Hughes24437992011-11-30 14:49:33 -08001139
1140 if (offset < 0 || count < 0 || offset > a->GetLength() || a->GetLength() - offset < count) {
1141 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001142 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughes24437992011-11-30 14:49:33 -08001143 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001144 std::string descriptor(ClassHelper(a->GetClass()).GetDescriptor());
Elliott Hughes24437992011-11-30 14:49:33 -08001145 JDWP::JdwpTag tag = BasicTagFromDescriptor(descriptor.c_str() + 1);
1146
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001147 expandBufAdd1(pReply, tag);
1148 expandBufAdd4BE(pReply, count);
1149
Elliott Hughes24437992011-11-30 14:49:33 -08001150 if (IsPrimitiveTag(tag)) {
1151 size_t width = GetTagWidth(tag);
Elliott Hughes24437992011-11-30 14:49:33 -08001152 uint8_t* dst = expandBufAddSpace(pReply, count * width);
1153 if (width == 8) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001154 const uint64_t* src8 = reinterpret_cast<uint64_t*>(a->GetRawData(sizeof(uint64_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001155 for (int i = 0; i < count; ++i) JDWP::Write8BE(&dst, src8[offset + i]);
1156 } else if (width == 4) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001157 const uint32_t* src4 = reinterpret_cast<uint32_t*>(a->GetRawData(sizeof(uint32_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001158 for (int i = 0; i < count; ++i) JDWP::Write4BE(&dst, src4[offset + i]);
1159 } else if (width == 2) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001160 const uint16_t* src2 = reinterpret_cast<uint16_t*>(a->GetRawData(sizeof(uint16_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001161 for (int i = 0; i < count; ++i) JDWP::Write2BE(&dst, src2[offset + i]);
1162 } else {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001163 const uint8_t* src = reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint8_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001164 memcpy(dst, &src[offset * width], count * width);
1165 }
1166 } else {
Ian Rogers98379392014-02-24 16:53:16 -08001167 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001168 mirror::ObjectArray<mirror::Object>* oa = a->AsObjectArray<mirror::Object>();
Elliott Hughes24437992011-11-30 14:49:33 -08001169 for (int i = 0; i < count; ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001170 mirror::Object* element = oa->Get(offset + i);
Ian Rogers98379392014-02-24 16:53:16 -08001171 JDWP::JdwpTag specific_tag = (element != nullptr) ? TagFromObject(soa, element)
1172 : tag;
Elliott Hughes24437992011-11-30 14:49:33 -08001173 expandBufAdd1(pReply, specific_tag);
1174 expandBufAddObjectId(pReply, gRegistry->Add(element));
1175 }
1176 }
1177
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001178 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001179}
1180
Ian Rogersef7d42f2014-01-06 12:55:46 -08001181template <typename T>
1182static void CopyArrayData(mirror::Array* a, JDWP::Request& src, int offset, int count)
1183 NO_THREAD_SAFETY_ANALYSIS {
1184 // TODO: fix when annotalysis correctly handles non-member functions.
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001185 DCHECK(a->GetClass()->IsPrimitiveArray());
1186
Ian Rogersef7d42f2014-01-06 12:55:46 -08001187 T* dst = reinterpret_cast<T*>(a->GetRawData(sizeof(T), offset));
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001188 for (int i = 0; i < count; ++i) {
1189 *dst++ = src.ReadValue(sizeof(T));
1190 }
1191}
1192
Elliott Hughes88d63092013-01-09 09:55:54 -08001193JDWP::JdwpError Dbg::SetArrayElements(JDWP::ObjectId array_id, int offset, int count,
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001194 JDWP::Request& request)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001195 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001196 JDWP::JdwpError status;
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001197 mirror::Array* dst = DecodeArray(array_id, status);
1198 if (dst == NULL) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001199 return status;
1200 }
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001201
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001202 if (offset < 0 || count < 0 || offset > dst->GetLength() || dst->GetLength() - offset < count) {
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001203 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001204 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001205 }
Ian Rogersfc0e94b2013-09-23 23:51:32 -07001206 const char* descriptor = ClassHelper(dst->GetClass()).GetDescriptor();
1207 JDWP::JdwpTag tag = BasicTagFromDescriptor(descriptor + 1);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001208
1209 if (IsPrimitiveTag(tag)) {
1210 size_t width = GetTagWidth(tag);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001211 if (width == 8) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001212 CopyArrayData<uint64_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001213 } else if (width == 4) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001214 CopyArrayData<uint32_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001215 } else if (width == 2) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001216 CopyArrayData<uint16_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001217 } else {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001218 CopyArrayData<uint8_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001219 }
1220 } else {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001221 mirror::ObjectArray<mirror::Object>* oa = dst->AsObjectArray<mirror::Object>();
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001222 for (int i = 0; i < count; ++i) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001223 JDWP::ObjectId id = request.ReadObjectId();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001224 mirror::Object* o = gRegistry->Get<mirror::Object*>(id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001225 if (o == ObjectRegistry::kInvalidObject) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001226 return JDWP::ERR_INVALID_OBJECT;
1227 }
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001228 oa->Set<false>(offset + i, o);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001229 }
1230 }
1231
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001232 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001233}
1234
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001235JDWP::ObjectId Dbg::CreateString(const std::string& str) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001236 return gRegistry->Add(mirror::String::AllocFromModifiedUtf8(Thread::Current(), str.c_str()));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001237}
1238
Elliott Hughes88d63092013-01-09 09:55:54 -08001239JDWP::JdwpError Dbg::CreateObject(JDWP::RefTypeId class_id, JDWP::ObjectId& new_object) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001240 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001241 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001242 if (c == NULL) {
1243 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001244 }
Ian Rogers50b35e22012-10-04 10:09:15 -07001245 new_object = gRegistry->Add(c->AllocObject(Thread::Current()));
Elliott Hughes436e3722012-02-17 20:01:47 -08001246 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001247}
1248
Elliott Hughesbf13d362011-12-08 15:51:37 -08001249/*
1250 * Used by Eclipse's "Display" view to evaluate "new byte[5]" to get "(byte[]) [0, 0, 0, 0, 0]".
1251 */
Elliott Hughes88d63092013-01-09 09:55:54 -08001252JDWP::JdwpError Dbg::CreateArrayObject(JDWP::RefTypeId array_class_id, uint32_t length,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001253 JDWP::ObjectId& new_array) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001254 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001255 mirror::Class* c = DecodeClass(array_class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001256 if (c == NULL) {
1257 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001258 }
Ian Rogers6fac4472014-02-25 17:01:10 -08001259 new_array = gRegistry->Add(mirror::Array::Alloc<true>(Thread::Current(), c, length,
1260 c->GetComponentSize(),
1261 Runtime::Current()->GetHeap()->GetCurrentAllocator()));
Elliott Hughes436e3722012-02-17 20:01:47 -08001262 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001263}
1264
Elliott Hughes88d63092013-01-09 09:55:54 -08001265bool Dbg::MatchType(JDWP::RefTypeId instance_class_id, JDWP::RefTypeId class_id) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001266 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001267 mirror::Class* c1 = DecodeClass(instance_class_id, status);
Elliott Hughesa656a0f2012-02-21 18:03:44 -08001268 CHECK(c1 != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001269 mirror::Class* c2 = DecodeClass(class_id, status);
Elliott Hughesa656a0f2012-02-21 18:03:44 -08001270 CHECK(c2 != NULL);
Sebastien Hertz123756a2013-11-27 15:49:42 +01001271 return c2->IsAssignableFrom(c1);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001272}
1273
Brian Carlstromea46f952013-07-30 01:26:50 -07001274static JDWP::FieldId ToFieldId(const mirror::ArtField* f)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001275 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001276 CHECK(!kMovingFields);
Elliott Hughes03181a82011-11-17 17:22:21 -08001277 return static_cast<JDWP::FieldId>(reinterpret_cast<uintptr_t>(f));
Elliott Hughes03181a82011-11-17 17:22:21 -08001278}
1279
Brian Carlstromea46f952013-07-30 01:26:50 -07001280static JDWP::MethodId ToMethodId(const mirror::ArtMethod* m)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001281 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001282 CHECK(!kMovingMethods);
Elliott Hughes03181a82011-11-17 17:22:21 -08001283 return static_cast<JDWP::MethodId>(reinterpret_cast<uintptr_t>(m));
Elliott Hughes03181a82011-11-17 17:22:21 -08001284}
1285
Brian Carlstromea46f952013-07-30 01:26:50 -07001286static mirror::ArtField* FromFieldId(JDWP::FieldId fid)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001287 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001288 CHECK(!kMovingFields);
Brian Carlstromea46f952013-07-30 01:26:50 -07001289 return reinterpret_cast<mirror::ArtField*>(static_cast<uintptr_t>(fid));
Elliott Hughesaed4be92011-12-02 16:16:23 -08001290}
1291
Brian Carlstromea46f952013-07-30 01:26:50 -07001292static mirror::ArtMethod* FromMethodId(JDWP::MethodId mid)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001293 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001294 CHECK(!kMovingMethods);
Brian Carlstromea46f952013-07-30 01:26:50 -07001295 return reinterpret_cast<mirror::ArtMethod*>(static_cast<uintptr_t>(mid));
Elliott Hughes03181a82011-11-17 17:22:21 -08001296}
1297
Brian Carlstromea46f952013-07-30 01:26:50 -07001298static void SetLocation(JDWP::JdwpLocation& location, mirror::ArtMethod* m, uint32_t dex_pc)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001299 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001300 if (m == NULL) {
1301 memset(&location, 0, sizeof(location));
1302 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001303 mirror::Class* c = m->GetDeclaringClass();
Elliott Hughes74847412012-06-20 18:10:21 -07001304 location.type_tag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001305 location.class_id = gRegistry->AddRefType(c);
Elliott Hughes74847412012-06-20 18:10:21 -07001306 location.method_id = ToMethodId(m);
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001307 location.dex_pc = (m->IsNative() || m->IsProxyMethod()) ? static_cast<uint64_t>(-1) : dex_pc;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001308 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08001309}
1310
Elliott Hughesa96836a2013-01-17 12:27:49 -08001311std::string Dbg::GetMethodName(JDWP::MethodId method_id)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001312 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001313 mirror::ArtMethod* m = FromMethodId(method_id);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001314 return MethodHelper(m).GetName();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001315}
1316
Elliott Hughesa96836a2013-01-17 12:27:49 -08001317std::string Dbg::GetFieldName(JDWP::FieldId field_id)
1318 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001319 mirror::ArtField* f = FromFieldId(field_id);
Elliott Hughesa96836a2013-01-17 12:27:49 -08001320 return FieldHelper(f).GetName();
1321}
1322
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001323/*
1324 * Augment the access flags for synthetic methods and fields by setting
1325 * the (as described by the spec) "0xf0000000 bit". Also, strip out any
1326 * flags not specified by the Java programming language.
1327 */
1328static uint32_t MangleAccessFlags(uint32_t accessFlags) {
1329 accessFlags &= kAccJavaFlagsMask;
1330 if ((accessFlags & kAccSynthetic) != 0) {
1331 accessFlags |= 0xf0000000;
1332 }
1333 return accessFlags;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001334}
1335
Elliott Hughesdbb40792011-11-18 17:05:22 -08001336/*
Jeff Haob7cefc72013-11-14 14:51:09 -08001337 * Circularly shifts registers so that arguments come first. Debuggers
1338 * expect slots to begin with arguments, but dex code places them at
1339 * the end.
Elliott Hughesdbb40792011-11-18 17:05:22 -08001340 */
Jeff Haob7cefc72013-11-14 14:51:09 -08001341static uint16_t MangleSlot(uint16_t slot, mirror::ArtMethod* m)
1342 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1343 const DexFile::CodeItem* code_item = MethodHelper(m).GetCodeItem();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001344 if (code_item == nullptr) {
1345 // We should not get here for a method without code (native, proxy or abstract). Log it and
1346 // return the slot as is since all registers are arguments.
1347 LOG(WARNING) << "Trying to mangle slot for method without code " << PrettyMethod(m);
1348 return slot;
1349 }
Jeff Haob7cefc72013-11-14 14:51:09 -08001350 uint16_t ins_size = code_item->ins_size_;
1351 uint16_t locals_size = code_item->registers_size_ - ins_size;
1352 if (slot >= locals_size) {
1353 return slot - locals_size;
1354 } else {
1355 return slot + ins_size;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001356 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001357}
1358
Jeff Haob7cefc72013-11-14 14:51:09 -08001359/*
1360 * Circularly shifts registers so that arguments come last. Reverts
1361 * slots to dex style argument placement.
1362 */
Brian Carlstromea46f952013-07-30 01:26:50 -07001363static uint16_t DemangleSlot(uint16_t slot, mirror::ArtMethod* m)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001364 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Jeff Haob7cefc72013-11-14 14:51:09 -08001365 const DexFile::CodeItem* code_item = MethodHelper(m).GetCodeItem();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001366 if (code_item == nullptr) {
1367 // We should not get here for a method without code (native, proxy or abstract). Log it and
1368 // return the slot as is since all registers are arguments.
1369 LOG(WARNING) << "Trying to demangle slot for method without code " << PrettyMethod(m);
1370 return slot;
1371 }
Jeff Haob7cefc72013-11-14 14:51:09 -08001372 uint16_t ins_size = code_item->ins_size_;
1373 uint16_t locals_size = code_item->registers_size_ - ins_size;
1374 if (slot < ins_size) {
1375 return slot + locals_size;
1376 } else {
1377 return slot - ins_size;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001378 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001379}
1380
Elliott Hughes88d63092013-01-09 09:55:54 -08001381JDWP::JdwpError Dbg::OutputDeclaredFields(JDWP::RefTypeId class_id, bool with_generic, JDWP::ExpandBuf* pReply) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001382 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001383 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001384 if (c == NULL) {
1385 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001386 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001387
1388 size_t instance_field_count = c->NumInstanceFields();
1389 size_t static_field_count = c->NumStaticFields();
1390
1391 expandBufAdd4BE(pReply, instance_field_count + static_field_count);
1392
1393 for (size_t i = 0; i < instance_field_count + static_field_count; ++i) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001394 mirror::ArtField* f = (i < instance_field_count) ? c->GetInstanceField(i) : c->GetStaticField(i - instance_field_count);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001395 FieldHelper fh(f);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001396 expandBufAddFieldId(pReply, ToFieldId(f));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001397 expandBufAddUtf8String(pReply, fh.GetName());
1398 expandBufAddUtf8String(pReply, fh.GetTypeDescriptor());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001399 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001400 static const char genericSignature[1] = "";
1401 expandBufAddUtf8String(pReply, genericSignature);
1402 }
1403 expandBufAdd4BE(pReply, MangleAccessFlags(f->GetAccessFlags()));
1404 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001405 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001406}
1407
Elliott Hughes88d63092013-01-09 09:55:54 -08001408JDWP::JdwpError Dbg::OutputDeclaredMethods(JDWP::RefTypeId class_id, bool with_generic,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001409 JDWP::ExpandBuf* pReply) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001410 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001411 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001412 if (c == NULL) {
1413 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001414 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001415
1416 size_t direct_method_count = c->NumDirectMethods();
1417 size_t virtual_method_count = c->NumVirtualMethods();
1418
1419 expandBufAdd4BE(pReply, direct_method_count + virtual_method_count);
1420
1421 for (size_t i = 0; i < direct_method_count + virtual_method_count; ++i) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001422 mirror::ArtMethod* m = (i < direct_method_count) ? c->GetDirectMethod(i) : c->GetVirtualMethod(i - direct_method_count);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001423 MethodHelper mh(m);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001424 expandBufAddMethodId(pReply, ToMethodId(m));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001425 expandBufAddUtf8String(pReply, mh.GetName());
Ian Rogersd91d6d62013-09-25 20:26:14 -07001426 expandBufAddUtf8String(pReply, mh.GetSignature().ToString());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001427 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001428 static const char genericSignature[1] = "";
1429 expandBufAddUtf8String(pReply, genericSignature);
1430 }
1431 expandBufAdd4BE(pReply, MangleAccessFlags(m->GetAccessFlags()));
1432 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001433 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001434}
1435
Elliott Hughes88d63092013-01-09 09:55:54 -08001436JDWP::JdwpError Dbg::OutputDeclaredInterfaces(JDWP::RefTypeId class_id, JDWP::ExpandBuf* pReply) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001437 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001438 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001439 if (c == NULL) {
1440 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001441 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001442
1443 ClassHelper kh(c);
Ian Rogersd24e2642012-06-06 21:21:43 -07001444 size_t interface_count = kh.NumDirectInterfaces();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001445 expandBufAdd4BE(pReply, interface_count);
1446 for (size_t i = 0; i < interface_count; ++i) {
Elliott Hughes64f574f2013-02-20 14:57:12 -08001447 expandBufAddRefTypeId(pReply, gRegistry->AddRefType(kh.GetDirectInterface(i)));
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001448 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001449 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001450}
1451
Elliott Hughes88d63092013-01-09 09:55:54 -08001452void Dbg::OutputLineTable(JDWP::RefTypeId, JDWP::MethodId method_id, JDWP::ExpandBuf* pReply)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001453 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001454 struct DebugCallbackContext {
1455 int numItems;
1456 JDWP::ExpandBuf* pReply;
1457
Elliott Hughes2435a572012-02-17 16:07:41 -08001458 static bool Callback(void* context, uint32_t address, uint32_t line_number) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001459 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
1460 expandBufAdd8BE(pContext->pReply, address);
Elliott Hughes2435a572012-02-17 16:07:41 -08001461 expandBufAdd4BE(pContext->pReply, line_number);
Elliott Hughes03181a82011-11-17 17:22:21 -08001462 pContext->numItems++;
Sebastien Hertzf2910ee2013-10-19 16:39:24 +02001463 return false;
Elliott Hughes03181a82011-11-17 17:22:21 -08001464 }
1465 };
Brian Carlstromea46f952013-07-30 01:26:50 -07001466 mirror::ArtMethod* m = FromMethodId(method_id);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001467 MethodHelper mh(m);
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001468 const DexFile::CodeItem* code_item = mh.GetCodeItem();
Elliott Hughes03181a82011-11-17 17:22:21 -08001469 uint64_t start, end;
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001470 if (code_item == nullptr) {
1471 DCHECK(m->IsNative() || m->IsProxyMethod());
Elliott Hughes03181a82011-11-17 17:22:21 -08001472 start = -1;
1473 end = -1;
1474 } else {
1475 start = 0;
jeffhao14f0db92012-12-14 17:50:42 -08001476 // Return the index of the last instruction
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001477 end = code_item->insns_size_in_code_units_ - 1;
Elliott Hughes03181a82011-11-17 17:22:21 -08001478 }
1479
1480 expandBufAdd8BE(pReply, start);
1481 expandBufAdd8BE(pReply, end);
1482
1483 // Add numLines later
1484 size_t numLinesOffset = expandBufGetLength(pReply);
1485 expandBufAdd4BE(pReply, 0);
1486
1487 DebugCallbackContext context;
1488 context.numItems = 0;
1489 context.pReply = pReply;
1490
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001491 if (code_item != nullptr) {
1492 mh.GetDexFile().DecodeDebugInfo(code_item, m->IsStatic(), m->GetDexMethodIndex(),
1493 DebugCallbackContext::Callback, NULL, &context);
1494 }
Elliott Hughes03181a82011-11-17 17:22:21 -08001495
1496 JDWP::Set4BE(expandBufGetBuffer(pReply) + numLinesOffset, context.numItems);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001497}
1498
Elliott Hughes88d63092013-01-09 09:55:54 -08001499void Dbg::OutputVariableTable(JDWP::RefTypeId, JDWP::MethodId method_id, bool with_generic, JDWP::ExpandBuf* pReply) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001500 struct DebugCallbackContext {
Jeff Haob7cefc72013-11-14 14:51:09 -08001501 mirror::ArtMethod* method;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001502 JDWP::ExpandBuf* pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001503 size_t variable_count;
1504 bool with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001505
Jeff Haob7cefc72013-11-14 14:51:09 -08001506 static void Callback(void* context, uint16_t slot, uint32_t startAddress, uint32_t endAddress, const char* name, const char* descriptor, const char* signature)
1507 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001508 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
1509
Jeff Haob7cefc72013-11-14 14:51:09 -08001510 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 -08001511
Jeff Haob7cefc72013-11-14 14:51:09 -08001512 slot = MangleSlot(slot, pContext->method);
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001513
Elliott Hughesdbb40792011-11-18 17:05:22 -08001514 expandBufAdd8BE(pContext->pReply, startAddress);
1515 expandBufAddUtf8String(pContext->pReply, name);
1516 expandBufAddUtf8String(pContext->pReply, descriptor);
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001517 if (pContext->with_generic) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001518 expandBufAddUtf8String(pContext->pReply, signature);
1519 }
1520 expandBufAdd4BE(pContext->pReply, endAddress - startAddress);
1521 expandBufAdd4BE(pContext->pReply, slot);
1522
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001523 ++pContext->variable_count;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001524 }
1525 };
Brian Carlstromea46f952013-07-30 01:26:50 -07001526 mirror::ArtMethod* m = FromMethodId(method_id);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001527 MethodHelper mh(m);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001528
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001529 // arg_count considers doubles and longs to take 2 units.
1530 // variable_count considers everything to take 1 unit.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001531 std::string shorty(mh.GetShorty());
Brian Carlstromea46f952013-07-30 01:26:50 -07001532 expandBufAdd4BE(pReply, mirror::ArtMethod::NumArgRegisters(shorty));
Elliott Hughesdbb40792011-11-18 17:05:22 -08001533
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001534 // We don't know the total number of variables yet, so leave a blank and update it later.
1535 size_t variable_count_offset = expandBufGetLength(pReply);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001536 expandBufAdd4BE(pReply, 0);
1537
1538 DebugCallbackContext context;
Jeff Haob7cefc72013-11-14 14:51:09 -08001539 context.method = m;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001540 context.pReply = pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001541 context.variable_count = 0;
1542 context.with_generic = with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001543
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001544 const DexFile::CodeItem* code_item = mh.GetCodeItem();
1545 if (code_item != nullptr) {
1546 mh.GetDexFile().DecodeDebugInfo(code_item, m->IsStatic(), m->GetDexMethodIndex(), NULL,
1547 DebugCallbackContext::Callback, &context);
1548 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001549
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001550 JDWP::Set4BE(expandBufGetBuffer(pReply) + variable_count_offset, context.variable_count);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001551}
1552
Jeff Hao579b0242013-11-18 13:16:49 -08001553void Dbg::OutputMethodReturnValue(JDWP::MethodId method_id, const JValue* return_value,
1554 JDWP::ExpandBuf* pReply) {
1555 mirror::ArtMethod* m = FromMethodId(method_id);
1556 JDWP::JdwpTag tag = BasicTagFromDescriptor(MethodHelper(m).GetShorty());
1557 OutputJValue(tag, return_value, pReply);
1558}
1559
Elliott Hughes9777ba22013-01-17 09:04:19 -08001560JDWP::JdwpError Dbg::GetBytecodes(JDWP::RefTypeId, JDWP::MethodId method_id,
1561 std::vector<uint8_t>& bytecodes)
1562 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001563 mirror::ArtMethod* m = FromMethodId(method_id);
Elliott Hughes9777ba22013-01-17 09:04:19 -08001564 if (m == NULL) {
1565 return JDWP::ERR_INVALID_METHODID;
1566 }
1567 MethodHelper mh(m);
1568 const DexFile::CodeItem* code_item = mh.GetCodeItem();
1569 size_t byte_count = code_item->insns_size_in_code_units_ * 2;
1570 const uint8_t* begin = reinterpret_cast<const uint8_t*>(code_item->insns_);
1571 const uint8_t* end = begin + byte_count;
1572 for (const uint8_t* p = begin; p != end; ++p) {
1573 bytecodes.push_back(*p);
1574 }
1575 return JDWP::ERR_NONE;
1576}
1577
Elliott Hughes88d63092013-01-09 09:55:54 -08001578JDWP::JdwpTag Dbg::GetFieldBasicTag(JDWP::FieldId field_id) {
1579 return BasicTagFromDescriptor(FieldHelper(FromFieldId(field_id)).GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001580}
1581
Elliott Hughes88d63092013-01-09 09:55:54 -08001582JDWP::JdwpTag Dbg::GetStaticFieldBasicTag(JDWP::FieldId field_id) {
1583 return BasicTagFromDescriptor(FieldHelper(FromFieldId(field_id)).GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001584}
1585
Elliott Hughes88d63092013-01-09 09:55:54 -08001586static JDWP::JdwpError GetFieldValueImpl(JDWP::RefTypeId ref_type_id, JDWP::ObjectId object_id,
1587 JDWP::FieldId field_id, JDWP::ExpandBuf* pReply,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001588 bool is_static)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001589 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes0cf74332012-02-23 23:14:00 -08001590 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001591 mirror::Class* c = DecodeClass(ref_type_id, status);
Elliott Hughes88d63092013-01-09 09:55:54 -08001592 if (ref_type_id != 0 && c == NULL) {
Elliott Hughes0cf74332012-02-23 23:14:00 -08001593 return status;
1594 }
1595
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001596 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001597 if ((!is_static && o == NULL) || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001598 return JDWP::ERR_INVALID_OBJECT;
1599 }
Brian Carlstromea46f952013-07-30 01:26:50 -07001600 mirror::ArtField* f = FromFieldId(field_id);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001601
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001602 mirror::Class* receiver_class = c;
Elliott Hughes0cf74332012-02-23 23:14:00 -08001603 if (receiver_class == NULL && o != NULL) {
1604 receiver_class = o->GetClass();
1605 }
1606 // TODO: should we give up now if receiver_class is NULL?
1607 if (receiver_class != NULL && !f->GetDeclaringClass()->IsAssignableFrom(receiver_class)) {
1608 LOG(INFO) << "ERR_INVALID_FIELDID: " << PrettyField(f) << " " << PrettyClass(receiver_class);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001609 return JDWP::ERR_INVALID_FIELDID;
1610 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001611
Elliott Hughes0cf74332012-02-23 23:14:00 -08001612 // The RI only enforces the static/non-static mismatch in one direction.
1613 // TODO: should we change the tests and check both?
1614 if (is_static) {
1615 if (!f->IsStatic()) {
1616 return JDWP::ERR_INVALID_FIELDID;
1617 }
1618 } else {
1619 if (f->IsStatic()) {
1620 LOG(WARNING) << "Ignoring non-NULL receiver for ObjectReference.SetValues on static field " << PrettyField(f);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001621 }
1622 }
jeffhao0dfbb7e2012-11-28 15:26:03 -08001623 if (f->IsStatic()) {
1624 o = f->GetDeclaringClass();
1625 }
Elliott Hughes0cf74332012-02-23 23:14:00 -08001626
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001627 JDWP::JdwpTag tag = BasicTagFromDescriptor(FieldHelper(f).GetTypeDescriptor());
Jeff Hao579b0242013-11-18 13:16:49 -08001628 JValue field_value;
1629 if (tag == JDWP::JT_VOID) {
1630 LOG(FATAL) << "Unknown tag: " << tag;
1631 } else if (!IsPrimitiveTag(tag)) {
1632 field_value.SetL(f->GetObject(o));
1633 } else if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
1634 field_value.SetJ(f->Get64(o));
Elliott Hughesaed4be92011-12-02 16:16:23 -08001635 } else {
Jeff Hao579b0242013-11-18 13:16:49 -08001636 field_value.SetI(f->Get32(o));
Elliott Hughesaed4be92011-12-02 16:16:23 -08001637 }
Jeff Hao579b0242013-11-18 13:16:49 -08001638 Dbg::OutputJValue(tag, &field_value, pReply);
1639
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001640 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001641}
1642
Elliott Hughes88d63092013-01-09 09:55:54 -08001643JDWP::JdwpError Dbg::GetFieldValue(JDWP::ObjectId object_id, JDWP::FieldId field_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001644 JDWP::ExpandBuf* pReply) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001645 return GetFieldValueImpl(0, object_id, field_id, pReply, false);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001646}
1647
Elliott Hughes88d63092013-01-09 09:55:54 -08001648JDWP::JdwpError Dbg::GetStaticFieldValue(JDWP::RefTypeId ref_type_id, JDWP::FieldId field_id, JDWP::ExpandBuf* pReply) {
1649 return GetFieldValueImpl(ref_type_id, 0, field_id, pReply, true);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001650}
1651
Elliott Hughes88d63092013-01-09 09:55:54 -08001652static JDWP::JdwpError SetFieldValueImpl(JDWP::ObjectId object_id, JDWP::FieldId field_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001653 uint64_t value, int width, bool is_static)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001654 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001655 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001656 if ((!is_static && o == NULL) || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001657 return JDWP::ERR_INVALID_OBJECT;
1658 }
Brian Carlstromea46f952013-07-30 01:26:50 -07001659 mirror::ArtField* f = FromFieldId(field_id);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001660
1661 // The RI only enforces the static/non-static mismatch in one direction.
1662 // TODO: should we change the tests and check both?
1663 if (is_static) {
1664 if (!f->IsStatic()) {
1665 return JDWP::ERR_INVALID_FIELDID;
1666 }
1667 } else {
1668 if (f->IsStatic()) {
1669 LOG(WARNING) << "Ignoring non-NULL receiver for ObjectReference.SetValues on static field " << PrettyField(f);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001670 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001671 }
jeffhao0dfbb7e2012-11-28 15:26:03 -08001672 if (f->IsStatic()) {
1673 o = f->GetDeclaringClass();
1674 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001675
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001676 JDWP::JdwpTag tag = BasicTagFromDescriptor(FieldHelper(f).GetTypeDescriptor());
Elliott Hughesaed4be92011-12-02 16:16:23 -08001677
1678 if (IsPrimitiveTag(tag)) {
1679 if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001680 CHECK_EQ(width, 8);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001681 // Debugging can't use transactional mode (runtime only).
1682 f->Set64<false>(o, value);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001683 } else {
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001684 CHECK_LE(width, 4);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001685 // Debugging can't use transactional mode (runtime only).
1686 f->Set32<false>(o, value);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001687 }
1688 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001689 mirror::Object* v = gRegistry->Get<mirror::Object*>(value);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001690 if (v == ObjectRegistry::kInvalidObject) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001691 return JDWP::ERR_INVALID_OBJECT;
1692 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001693 if (v != NULL) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001694 mirror::Class* field_type = FieldHelper(f).GetType();
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001695 if (!field_type->IsAssignableFrom(v->GetClass())) {
1696 return JDWP::ERR_INVALID_OBJECT;
1697 }
1698 }
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001699 // Debugging can't use transactional mode (runtime only).
1700 f->SetObject<false>(o, v);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001701 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001702
1703 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001704}
1705
Elliott Hughes88d63092013-01-09 09:55:54 -08001706JDWP::JdwpError Dbg::SetFieldValue(JDWP::ObjectId object_id, JDWP::FieldId field_id, uint64_t value,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001707 int width) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001708 return SetFieldValueImpl(object_id, field_id, value, width, false);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001709}
1710
Elliott Hughes88d63092013-01-09 09:55:54 -08001711JDWP::JdwpError Dbg::SetStaticFieldValue(JDWP::FieldId field_id, uint64_t value, int width) {
1712 return SetFieldValueImpl(0, field_id, value, width, true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001713}
1714
Elliott Hughes88d63092013-01-09 09:55:54 -08001715std::string Dbg::StringToUtf8(JDWP::ObjectId string_id) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001716 mirror::String* s = gRegistry->Get<mirror::String*>(string_id);
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001717 return s->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001718}
1719
Jeff Hao579b0242013-11-18 13:16:49 -08001720void Dbg::OutputJValue(JDWP::JdwpTag tag, const JValue* return_value, JDWP::ExpandBuf* pReply) {
1721 if (IsPrimitiveTag(tag)) {
1722 expandBufAdd1(pReply, tag);
1723 if (tag == JDWP::JT_BOOLEAN || tag == JDWP::JT_BYTE) {
1724 expandBufAdd1(pReply, return_value->GetI());
1725 } else if (tag == JDWP::JT_CHAR || tag == JDWP::JT_SHORT) {
1726 expandBufAdd2BE(pReply, return_value->GetI());
1727 } else if (tag == JDWP::JT_FLOAT || tag == JDWP::JT_INT) {
1728 expandBufAdd4BE(pReply, return_value->GetI());
1729 } else if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
1730 expandBufAdd8BE(pReply, return_value->GetJ());
1731 } else {
1732 CHECK_EQ(tag, JDWP::JT_VOID);
1733 }
1734 } else {
Ian Rogers98379392014-02-24 16:53:16 -08001735 ScopedObjectAccessUnchecked soa(Thread::Current());
Jeff Hao579b0242013-11-18 13:16:49 -08001736 mirror::Object* value = return_value->GetL();
Ian Rogers98379392014-02-24 16:53:16 -08001737 expandBufAdd1(pReply, TagFromObject(soa, value));
Jeff Hao579b0242013-11-18 13:16:49 -08001738 expandBufAddObjectId(pReply, gRegistry->Add(value));
1739 }
1740}
1741
Elliott Hughes221229c2013-01-08 18:17:50 -08001742JDWP::JdwpError Dbg::GetThreadName(JDWP::ObjectId thread_id, std::string& name) {
jeffhaoa77f0f62012-12-05 17:19:31 -08001743 ScopedObjectAccessUnchecked soa(Thread::Current());
1744 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001745 Thread* thread;
1746 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1747 if (error != JDWP::ERR_NONE && error != JDWP::ERR_THREAD_NOT_ALIVE) {
1748 return error;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001749 }
Elliott Hughes221229c2013-01-08 18:17:50 -08001750
1751 // We still need to report the zombie threads' names, so we can't just call Thread::GetThreadName.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001752 mirror::Object* thread_object = gRegistry->Get<mirror::Object*>(thread_id);
Brian Carlstromea46f952013-07-30 01:26:50 -07001753 mirror::ArtField* java_lang_Thread_name_field =
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001754 soa.DecodeField(WellKnownClasses::java_lang_Thread_name);
1755 mirror::String* s =
1756 reinterpret_cast<mirror::String*>(java_lang_Thread_name_field->GetObject(thread_object));
Elliott Hughes221229c2013-01-08 18:17:50 -08001757 if (s != NULL) {
1758 name = s->ToModifiedUtf8();
1759 }
1760 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001761}
1762
Elliott Hughes221229c2013-01-08 18:17:50 -08001763JDWP::JdwpError Dbg::GetThreadGroup(JDWP::ObjectId thread_id, JDWP::ExpandBuf* pReply) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001764 ScopedObjectAccess soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001765 mirror::Object* thread_object = gRegistry->Get<mirror::Object*>(thread_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001766 if (thread_object == ObjectRegistry::kInvalidObject) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001767 return JDWP::ERR_INVALID_OBJECT;
1768 }
Ian Rogers98379392014-02-24 16:53:16 -08001769 const char* old_cause = soa.Self()->StartAssertNoThreadSuspension("Debugger: GetThreadGroup");
Elliott Hughes2435a572012-02-17 16:07:41 -08001770 // Okay, so it's an object, but is it actually a thread?
Ian Rogers50b35e22012-10-04 10:09:15 -07001771 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001772 Thread* thread;
1773 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1774 if (error == JDWP::ERR_THREAD_NOT_ALIVE) {
1775 // Zombie threads are in the null group.
1776 expandBufAddObjectId(pReply, JDWP::ObjectId(0));
Sebastien Hertz52d131d2014-03-13 16:17:40 +01001777 error = JDWP::ERR_NONE;
1778 } else if (error == JDWP::ERR_NONE) {
1779 mirror::Class* c = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_Thread);
1780 CHECK(c != nullptr);
1781 mirror::ArtField* f = c->FindInstanceField("group", "Ljava/lang/ThreadGroup;");
1782 CHECK(f != NULL);
1783 mirror::Object* group = f->GetObject(thread_object);
1784 CHECK(group != NULL);
1785 JDWP::ObjectId thread_group_id = gRegistry->Add(group);
1786 expandBufAddObjectId(pReply, thread_group_id);
Elliott Hughes221229c2013-01-08 18:17:50 -08001787 }
Ian Rogers98379392014-02-24 16:53:16 -08001788 soa.Self()->EndAssertNoThreadSuspension(old_cause);
Sebastien Hertz52d131d2014-03-13 16:17:40 +01001789 return error;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001790}
1791
Elliott Hughes88d63092013-01-09 09:55:54 -08001792std::string Dbg::GetThreadGroupName(JDWP::ObjectId thread_group_id) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001793 ScopedObjectAccess soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001794 mirror::Object* thread_group = gRegistry->Get<mirror::Object*>(thread_group_id);
Ian Rogers98379392014-02-24 16:53:16 -08001795 CHECK(thread_group != nullptr);
1796 const char* old_cause = soa.Self()->StartAssertNoThreadSuspension("Debugger: GetThreadGroupName");
1797 mirror::Class* c = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_ThreadGroup);
1798 CHECK(c != nullptr);
Brian Carlstromea46f952013-07-30 01:26:50 -07001799 mirror::ArtField* f = c->FindInstanceField("name", "Ljava/lang/String;");
Elliott Hughes499c5132011-11-17 14:55:11 -08001800 CHECK(f != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001801 mirror::String* s = reinterpret_cast<mirror::String*>(f->GetObject(thread_group));
Ian Rogers98379392014-02-24 16:53:16 -08001802 soa.Self()->EndAssertNoThreadSuspension(old_cause);
Elliott Hughes499c5132011-11-17 14:55:11 -08001803 return s->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001804}
1805
Elliott Hughes88d63092013-01-09 09:55:54 -08001806JDWP::ObjectId Dbg::GetThreadGroupParent(JDWP::ObjectId thread_group_id) {
Ian Rogers98379392014-02-24 16:53:16 -08001807 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001808 mirror::Object* thread_group = gRegistry->Get<mirror::Object*>(thread_group_id);
Ian Rogers98379392014-02-24 16:53:16 -08001809 CHECK(thread_group != nullptr);
1810 const char* old_cause = soa.Self()->StartAssertNoThreadSuspension("Debugger: GetThreadGroupParent");
1811 mirror::Class* c = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_ThreadGroup);
1812 CHECK(c != nullptr);
Brian Carlstromea46f952013-07-30 01:26:50 -07001813 mirror::ArtField* f = c->FindInstanceField("parent", "Ljava/lang/ThreadGroup;");
Elliott Hughes4e235312011-12-02 11:34:15 -08001814 CHECK(f != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001815 mirror::Object* parent = f->GetObject(thread_group);
Ian Rogers98379392014-02-24 16:53:16 -08001816 soa.Self()->EndAssertNoThreadSuspension(old_cause);
Elliott Hughes4e235312011-12-02 11:34:15 -08001817 return gRegistry->Add(parent);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001818}
1819
1820JDWP::ObjectId Dbg::GetSystemThreadGroupId() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001821 ScopedObjectAccessUnchecked soa(Thread::Current());
Brian Carlstromea46f952013-07-30 01:26:50 -07001822 mirror::ArtField* f = soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_systemThreadGroup);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001823 mirror::Object* group = f->GetObject(f->GetDeclaringClass());
Ian Rogers365c1022012-06-22 15:05:28 -07001824 return gRegistry->Add(group);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001825}
1826
1827JDWP::ObjectId Dbg::GetMainThreadGroupId() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001828 ScopedObjectAccess soa(Thread::Current());
Brian Carlstromea46f952013-07-30 01:26:50 -07001829 mirror::ArtField* f = soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_mainThreadGroup);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001830 mirror::Object* group = f->GetObject(f->GetDeclaringClass());
Ian Rogers365c1022012-06-22 15:05:28 -07001831 return gRegistry->Add(group);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001832}
1833
Jeff Hao920af3e2013-08-28 15:46:38 -07001834JDWP::JdwpThreadStatus Dbg::ToJdwpThreadStatus(ThreadState state) {
1835 switch (state) {
1836 case kBlocked:
1837 return JDWP::TS_MONITOR;
1838 case kNative:
1839 case kRunnable:
1840 case kSuspended:
1841 return JDWP::TS_RUNNING;
1842 case kSleeping:
1843 return JDWP::TS_SLEEPING;
1844 case kStarting:
1845 case kTerminated:
1846 return JDWP::TS_ZOMBIE;
1847 case kTimedWaiting:
1848 case kWaitingForDebuggerSend:
1849 case kWaitingForDebuggerSuspension:
1850 case kWaitingForDebuggerToAttach:
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01001851 case kWaitingForDeoptimization:
Jeff Hao920af3e2013-08-28 15:46:38 -07001852 case kWaitingForGcToComplete:
1853 case kWaitingForCheckPointsToRun:
1854 case kWaitingForJniOnLoad:
1855 case kWaitingForSignalCatcherOutput:
1856 case kWaitingInMainDebuggerLoop:
1857 case kWaitingInMainSignalCatcherLoop:
1858 case kWaitingPerformingGc:
1859 case kWaiting:
1860 return JDWP::TS_WAIT;
1861 // Don't add a 'default' here so the compiler can spot incompatible enum changes.
1862 }
1863 LOG(FATAL) << "Unknown thread state: " << state;
1864 return JDWP::TS_ZOMBIE;
1865}
1866
Sebastien Hertz52d131d2014-03-13 16:17:40 +01001867JDWP::JdwpError Dbg::GetThreadStatus(JDWP::ObjectId thread_id, JDWP::JdwpThreadStatus* pThreadStatus,
1868 JDWP::JdwpSuspendStatus* pSuspendStatus) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001869 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes499c5132011-11-17 14:55:11 -08001870
Elliott Hughes9e0c1752013-01-09 14:02:58 -08001871 *pSuspendStatus = JDWP::SUSPEND_STATUS_NOT_SUSPENDED;
1872
Ian Rogers50b35e22012-10-04 10:09:15 -07001873 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001874 Thread* thread;
1875 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1876 if (error != JDWP::ERR_NONE) {
1877 if (error == JDWP::ERR_THREAD_NOT_ALIVE) {
1878 *pThreadStatus = JDWP::TS_ZOMBIE;
Elliott Hughes221229c2013-01-08 18:17:50 -08001879 return JDWP::ERR_NONE;
1880 }
1881 return error;
Elliott Hughes499c5132011-11-17 14:55:11 -08001882 }
1883
Elliott Hughes9e0c1752013-01-09 14:02:58 -08001884 if (IsSuspendedForDebugger(soa, thread)) {
1885 *pSuspendStatus = JDWP::SUSPEND_STATUS_SUSPENDED;
Elliott Hughes499c5132011-11-17 14:55:11 -08001886 }
1887
Jeff Hao920af3e2013-08-28 15:46:38 -07001888 *pThreadStatus = ToJdwpThreadStatus(thread->GetState());
Elliott Hughes221229c2013-01-08 18:17:50 -08001889 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001890}
1891
Elliott Hughes221229c2013-01-08 18:17:50 -08001892JDWP::JdwpError Dbg::GetThreadDebugSuspendCount(JDWP::ObjectId thread_id, JDWP::ExpandBuf* pReply) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001893 ScopedObjectAccess soa(Thread::Current());
Ian Rogers50b35e22012-10-04 10:09:15 -07001894 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001895 Thread* thread;
1896 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1897 if (error != JDWP::ERR_NONE) {
1898 return error;
Elliott Hughes2435a572012-02-17 16:07:41 -08001899 }
Ian Rogers50b35e22012-10-04 10:09:15 -07001900 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001901 expandBufAdd4BE(pReply, thread->GetDebugSuspendCount());
Elliott Hughes2435a572012-02-17 16:07:41 -08001902 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001903}
1904
Elliott Hughesf9501702013-01-11 11:22:27 -08001905JDWP::JdwpError Dbg::Interrupt(JDWP::ObjectId thread_id) {
1906 ScopedObjectAccess soa(Thread::Current());
1907 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
1908 Thread* thread;
1909 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1910 if (error != JDWP::ERR_NONE) {
1911 return error;
1912 }
1913 thread->Interrupt();
1914 return JDWP::ERR_NONE;
1915}
1916
Elliott Hughescaf76542012-06-28 16:08:22 -07001917void Dbg::GetThreads(JDWP::ObjectId thread_group_id, std::vector<JDWP::ObjectId>& thread_ids) {
Ian Rogers365c1022012-06-22 15:05:28 -07001918 class ThreadListVisitor {
1919 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001920 ThreadListVisitor(const ScopedObjectAccessUnchecked& soa, mirror::Object* desired_thread_group,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001921 std::vector<JDWP::ObjectId>& thread_ids)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001922 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
jeffhao0dfbb7e2012-11-28 15:26:03 -08001923 : soa_(soa), desired_thread_group_(desired_thread_group), thread_ids_(thread_ids) {}
Ian Rogers365c1022012-06-22 15:05:28 -07001924
Elliott Hughesa2155262011-11-16 16:26:58 -08001925 static void Visit(Thread* t, void* arg) {
1926 reinterpret_cast<ThreadListVisitor*>(arg)->Visit(t);
1927 }
1928
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001929 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1930 // annotalysis.
1931 void Visit(Thread* t) NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughesa2155262011-11-16 16:26:58 -08001932 if (t == Dbg::GetDebugThread()) {
1933 // Skip the JDWP thread. Some debuggers get bent out of shape when they can't suspend and
1934 // query all threads, so it's easier if we just don't tell them about this thread.
1935 return;
1936 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001937 mirror::Object* peer = t->GetPeer();
jeffhao0dfbb7e2012-11-28 15:26:03 -08001938 if (IsInDesiredThreadGroup(peer)) {
Ian Rogers120f1c72012-09-28 17:17:10 -07001939 thread_ids_.push_back(gRegistry->Add(peer));
Elliott Hughesa2155262011-11-16 16:26:58 -08001940 }
1941 }
1942
Ian Rogers365c1022012-06-22 15:05:28 -07001943 private:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001944 bool IsInDesiredThreadGroup(mirror::Object* peer)
jeffhao0dfbb7e2012-11-28 15:26:03 -08001945 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
jeffhao0dfbb7e2012-11-28 15:26:03 -08001946 // peer might be NULL if the thread is still starting up.
1947 if (peer == NULL) {
1948 // We can't tell the debugger about this thread yet.
1949 // TODO: if we identified threads to the debugger by their Thread*
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001950 // rather than their peer's mirror::Object*, we could fix this.
jeffhao0dfbb7e2012-11-28 15:26:03 -08001951 // Doing so might help us report ZOMBIE threads too.
1952 return false;
1953 }
jeffhaoc1e04902012-12-13 12:41:10 -08001954 // Do we want threads from all thread groups?
1955 if (desired_thread_group_ == NULL) {
1956 return true;
1957 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001958 mirror::Object* group = soa_.DecodeField(WellKnownClasses::java_lang_Thread_group)->GetObject(peer);
jeffhao0dfbb7e2012-11-28 15:26:03 -08001959 return (group == desired_thread_group_);
1960 }
1961
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07001962 const ScopedObjectAccessUnchecked& soa_;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001963 mirror::Object* const desired_thread_group_;
Elliott Hughescaf76542012-06-28 16:08:22 -07001964 std::vector<JDWP::ObjectId>& thread_ids_;
Elliott Hughesa2155262011-11-16 16:26:58 -08001965 };
1966
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001967 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001968 mirror::Object* thread_group = gRegistry->Get<mirror::Object*>(thread_group_id);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001969 ThreadListVisitor tlv(soa, thread_group, thread_ids);
Ian Rogers50b35e22012-10-04 10:09:15 -07001970 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughesf8349362012-06-18 15:00:06 -07001971 Runtime::Current()->GetThreadList()->ForEach(ThreadListVisitor::Visit, &tlv);
Elliott Hughescaf76542012-06-28 16:08:22 -07001972}
Elliott Hughesa2155262011-11-16 16:26:58 -08001973
Elliott Hughescaf76542012-06-28 16:08:22 -07001974void Dbg::GetChildThreadGroups(JDWP::ObjectId thread_group_id, std::vector<JDWP::ObjectId>& child_thread_group_ids) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001975 ScopedObjectAccess soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001976 mirror::Object* thread_group = gRegistry->Get<mirror::Object*>(thread_group_id);
Elliott Hughescaf76542012-06-28 16:08:22 -07001977
1978 // Get the ArrayList<ThreadGroup> "groups" out of this thread group...
Brian Carlstromea46f952013-07-30 01:26:50 -07001979 mirror::ArtField* groups_field = thread_group->GetClass()->FindInstanceField("groups", "Ljava/util/List;");
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001980 mirror::Object* groups_array_list = groups_field->GetObject(thread_group);
Elliott Hughescaf76542012-06-28 16:08:22 -07001981
1982 // Get the array and size out of the ArrayList<ThreadGroup>...
Brian Carlstromea46f952013-07-30 01:26:50 -07001983 mirror::ArtField* array_field = groups_array_list->GetClass()->FindInstanceField("array", "[Ljava/lang/Object;");
1984 mirror::ArtField* size_field = groups_array_list->GetClass()->FindInstanceField("size", "I");
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001985 mirror::ObjectArray<mirror::Object>* groups_array =
1986 array_field->GetObject(groups_array_list)->AsObjectArray<mirror::Object>();
Elliott Hughescaf76542012-06-28 16:08:22 -07001987 const int32_t size = size_field->GetInt(groups_array_list);
1988
1989 // Copy the first 'size' elements out of the array into the result.
1990 for (int32_t i = 0; i < size; ++i) {
1991 child_thread_group_ids.push_back(gRegistry->Add(groups_array->Get(i)));
Elliott Hughesa2155262011-11-16 16:26:58 -08001992 }
1993}
1994
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001995static int GetStackDepth(Thread* thread)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001996 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers0399dde2012-06-06 17:09:28 -07001997 struct CountStackDepthVisitor : public StackVisitor {
Brian Carlstrom93ba8932013-07-17 21:31:49 -07001998 explicit CountStackDepthVisitor(Thread* thread)
Ian Rogers7a22fa62013-01-23 12:16:16 -08001999 : StackVisitor(thread, NULL), depth(0) {}
Ian Rogers0399dde2012-06-06 17:09:28 -07002000
Elliott Hughes64f574f2013-02-20 14:57:12 -08002001 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2002 // annotalysis.
2003 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07002004 if (!GetMethod()->IsRuntimeMethod()) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -08002005 ++depth;
2006 }
Elliott Hughes530fa002012-03-12 11:44:49 -07002007 return true;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08002008 }
2009 size_t depth;
2010 };
Elliott Hughes08fc03a2012-06-26 17:34:00 -07002011
Ian Rogers7a22fa62013-01-23 12:16:16 -08002012 CountStackDepthVisitor visitor(thread);
Ian Rogers0399dde2012-06-06 17:09:28 -07002013 visitor.WalkStack();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08002014 return visitor.depth;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002015}
2016
Elliott Hughes221229c2013-01-08 18:17:50 -08002017JDWP::JdwpError Dbg::GetThreadFrameCount(JDWP::ObjectId thread_id, size_t& result) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002018 ScopedObjectAccess soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08002019 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002020 Thread* thread;
2021 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
2022 if (error != JDWP::ERR_NONE) {
2023 return error;
2024 }
Elliott Hughesf15f4a02013-01-09 10:09:38 -08002025 if (!IsSuspendedForDebugger(soa, thread)) {
2026 return JDWP::ERR_THREAD_NOT_SUSPENDED;
2027 }
Elliott Hughes221229c2013-01-08 18:17:50 -08002028 result = GetStackDepth(thread);
2029 return JDWP::ERR_NONE;
Elliott Hughes86964332012-02-15 19:37:42 -08002030}
2031
Ian Rogers306057f2012-11-26 12:45:53 -08002032JDWP::JdwpError Dbg::GetThreadFrames(JDWP::ObjectId thread_id, size_t start_frame,
2033 size_t frame_count, JDWP::ExpandBuf* buf) {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002034 class GetFrameVisitor : public StackVisitor {
2035 public:
Ian Rogers7a22fa62013-01-23 12:16:16 -08002036 GetFrameVisitor(Thread* thread, size_t start_frame, size_t frame_count, JDWP::ExpandBuf* buf)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002037 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08002038 : StackVisitor(thread, NULL), depth_(0),
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002039 start_frame_(start_frame), frame_count_(frame_count), buf_(buf) {
2040 expandBufAdd4BE(buf_, frame_count_);
Elliott Hughes03181a82011-11-17 17:22:21 -08002041 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002042
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002043 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2044 // annotalysis.
2045 virtual bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07002046 if (GetMethod()->IsRuntimeMethod()) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07002047 return true; // The debugger can't do anything useful with a frame that has no Method*.
Elliott Hughes03181a82011-11-17 17:22:21 -08002048 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002049 if (depth_ >= start_frame_ + frame_count_) {
Elliott Hughes530fa002012-03-12 11:44:49 -07002050 return false;
Elliott Hughes03181a82011-11-17 17:22:21 -08002051 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002052 if (depth_ >= start_frame_) {
2053 JDWP::FrameId frame_id(GetFrameId());
2054 JDWP::JdwpLocation location;
2055 SetLocation(location, GetMethod(), GetDexPc());
Ian Rogersef7d42f2014-01-06 12:55:46 -08002056 VLOG(jdwp) << StringPrintf(" Frame %3zd: id=%3" PRIu64 " ", depth_, frame_id) << location;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002057 expandBufAdd8BE(buf_, frame_id);
2058 expandBufAddLocation(buf_, location);
2059 }
2060 ++depth_;
Elliott Hughes530fa002012-03-12 11:44:49 -07002061 return true;
Elliott Hughes03181a82011-11-17 17:22:21 -08002062 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002063
2064 private:
2065 size_t depth_;
2066 const size_t start_frame_;
2067 const size_t frame_count_;
2068 JDWP::ExpandBuf* buf_;
Elliott Hughes03181a82011-11-17 17:22:21 -08002069 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002070
2071 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08002072 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002073 Thread* thread;
2074 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
2075 if (error != JDWP::ERR_NONE) {
2076 return error;
2077 }
Elliott Hughesf15f4a02013-01-09 10:09:38 -08002078 if (!IsSuspendedForDebugger(soa, thread)) {
2079 return JDWP::ERR_THREAD_NOT_SUSPENDED;
2080 }
Ian Rogers7a22fa62013-01-23 12:16:16 -08002081 GetFrameVisitor visitor(thread, start_frame, frame_count, buf);
Ian Rogers0399dde2012-06-06 17:09:28 -07002082 visitor.WalkStack();
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002083 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002084}
2085
2086JDWP::ObjectId Dbg::GetThreadSelfId() {
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07002087 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogerscfaa4552012-11-26 21:00:08 -08002088 return gRegistry->Add(soa.Self()->GetPeer());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002089}
2090
Elliott Hughes475fc232011-10-25 15:00:35 -07002091void Dbg::SuspendVM() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002092 Runtime::Current()->GetThreadList()->SuspendAllForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002093}
2094
2095void Dbg::ResumeVM() {
Elliott Hughesc61a2672012-06-21 14:52:29 -07002096 Runtime::Current()->GetThreadList()->UndoDebuggerSuspensions();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002097}
2098
Elliott Hughes221229c2013-01-08 18:17:50 -08002099JDWP::JdwpError Dbg::SuspendThread(JDWP::ObjectId thread_id, bool request_suspension) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002100 ScopedLocalRef<jobject> peer(Thread::Current()->GetJniEnv(), NULL);
2101 {
2102 ScopedObjectAccess soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002103 peer.reset(soa.AddLocalReference<jobject>(gRegistry->Get<mirror::Object*>(thread_id)));
Elliott Hughes4e235312011-12-02 11:34:15 -08002104 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002105 if (peer.get() == NULL) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002106 return JDWP::ERR_THREAD_NOT_ALIVE;
2107 }
2108 // Suspend thread to build stack trace.
Elliott Hughesf327e072013-01-09 16:01:26 -08002109 bool timed_out;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07002110 Thread* thread = ThreadList::SuspendThreadByPeer(peer.get(), request_suspension, true,
2111 &timed_out);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002112 if (thread != NULL) {
2113 return JDWP::ERR_NONE;
Elliott Hughesf327e072013-01-09 16:01:26 -08002114 } else if (timed_out) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002115 return JDWP::ERR_INTERNAL;
2116 } else {
2117 return JDWP::ERR_THREAD_NOT_ALIVE;
2118 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002119}
2120
Elliott Hughes221229c2013-01-08 18:17:50 -08002121void Dbg::ResumeThread(JDWP::ObjectId thread_id) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002122 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002123 mirror::Object* peer = gRegistry->Get<mirror::Object*>(thread_id);
jeffhaoa77f0f62012-12-05 17:19:31 -08002124 Thread* thread;
2125 {
2126 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
2127 thread = Thread::FromManagedThread(soa, peer);
2128 }
Elliott Hughes4e235312011-12-02 11:34:15 -08002129 if (thread == NULL) {
2130 LOG(WARNING) << "No such thread for resume: " << peer;
2131 return;
2132 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002133 bool needs_resume;
2134 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002135 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002136 needs_resume = thread->GetSuspendCount() > 0;
2137 }
2138 if (needs_resume) {
Elliott Hughes546b9862012-06-20 16:06:13 -07002139 Runtime::Current()->GetThreadList()->Resume(thread, true);
2140 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002141}
2142
2143void Dbg::SuspendSelf() {
Elliott Hughes475fc232011-10-25 15:00:35 -07002144 Runtime::Current()->GetThreadList()->SuspendSelfForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002145}
2146
Ian Rogers0399dde2012-06-06 17:09:28 -07002147struct GetThisVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -08002148 GetThisVisitor(Thread* thread, Context* context, JDWP::FrameId frame_id)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002149 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08002150 : StackVisitor(thread, context), this_object(NULL), frame_id(frame_id) {}
Ian Rogers0399dde2012-06-06 17:09:28 -07002151
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002152 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2153 // annotalysis.
2154 virtual bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002155 if (frame_id != GetFrameId()) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002156 return true; // continue
Ian Rogers0399dde2012-06-06 17:09:28 -07002157 } else {
Ian Rogers62d6c772013-02-27 08:32:07 -08002158 this_object = GetThisObject();
2159 return false;
Ian Rogers0399dde2012-06-06 17:09:28 -07002160 }
Elliott Hughes86b00102011-12-05 17:54:26 -08002161 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002162
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002163 mirror::Object* this_object;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002164 JDWP::FrameId frame_id;
Ian Rogers0399dde2012-06-06 17:09:28 -07002165};
2166
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002167JDWP::JdwpError Dbg::GetThisObject(JDWP::ObjectId thread_id, JDWP::FrameId frame_id,
2168 JDWP::ObjectId* result) {
2169 ScopedObjectAccessUnchecked soa(Thread::Current());
2170 Thread* thread;
2171 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002172 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002173 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
2174 if (error != JDWP::ERR_NONE) {
2175 return error;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002176 }
Elliott Hughes9e0c1752013-01-09 14:02:58 -08002177 if (!IsSuspendedForDebugger(soa, thread)) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002178 return JDWP::ERR_THREAD_NOT_SUSPENDED;
2179 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002180 }
Elliott Hughescaf76542012-06-28 16:08:22 -07002181 UniquePtr<Context> context(Context::Create());
Ian Rogers7a22fa62013-01-23 12:16:16 -08002182 GetThisVisitor visitor(thread, context.get(), frame_id);
Ian Rogers0399dde2012-06-06 17:09:28 -07002183 visitor.WalkStack();
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002184 *result = gRegistry->Add(visitor.this_object);
2185 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002186}
2187
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002188JDWP::JdwpError Dbg::GetLocalValue(JDWP::ObjectId thread_id, JDWP::FrameId frame_id, int slot,
2189 JDWP::JdwpTag tag, uint8_t* buf, size_t width) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002190 struct GetLocalVisitor : public StackVisitor {
Ian Rogers98379392014-02-24 16:53:16 -08002191 GetLocalVisitor(const ScopedObjectAccessUnchecked& soa, Thread* thread, Context* context,
2192 JDWP::FrameId frame_id, int slot, JDWP::JdwpTag tag, uint8_t* buf, size_t width)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002193 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers98379392014-02-24 16:53:16 -08002194 : StackVisitor(thread, context), soa_(soa), frame_id_(frame_id), slot_(slot), tag_(tag),
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002195 buf_(buf), width_(width), error_(JDWP::ERR_NONE) {}
Ian Rogersca190662012-06-26 15:45:57 -07002196
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002197 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2198 // annotalysis.
2199 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07002200 if (GetFrameId() != frame_id_) {
2201 return true; // Not our frame, carry on.
Elliott Hughesdbb40792011-11-18 17:05:22 -08002202 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002203 // TODO: check that the tag is compatible with the actual type of the slot!
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002204 // TODO: check slot is valid for this method or return INVALID_SLOT error.
Brian Carlstromea46f952013-07-30 01:26:50 -07002205 mirror::ArtMethod* m = GetMethod();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002206 if (m->IsNative()) {
2207 // We can't read local value from native method.
2208 error_ = JDWP::ERR_OPAQUE_FRAME;
2209 return false;
2210 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002211 uint16_t reg = DemangleSlot(slot_, m);
Elliott Hughesdbb40792011-11-18 17:05:22 -08002212
Ian Rogers0399dde2012-06-06 17:09:28 -07002213 switch (tag_) {
2214 case JDWP::JT_BOOLEAN:
2215 {
2216 CHECK_EQ(width_, 1U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002217 uint32_t intVal = GetVReg(m, reg, kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002218 VLOG(jdwp) << "get boolean local " << reg << " = " << intVal;
2219 JDWP::Set1(buf_+1, intVal != 0);
2220 }
2221 break;
2222 case JDWP::JT_BYTE:
2223 {
2224 CHECK_EQ(width_, 1U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002225 uint32_t intVal = GetVReg(m, reg, kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002226 VLOG(jdwp) << "get byte local " << reg << " = " << intVal;
2227 JDWP::Set1(buf_+1, intVal);
2228 }
2229 break;
2230 case JDWP::JT_SHORT:
2231 case JDWP::JT_CHAR:
2232 {
2233 CHECK_EQ(width_, 2U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002234 uint32_t intVal = GetVReg(m, reg, kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002235 VLOG(jdwp) << "get short/char local " << reg << " = " << intVal;
2236 JDWP::Set2BE(buf_+1, intVal);
2237 }
2238 break;
2239 case JDWP::JT_INT:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002240 {
2241 CHECK_EQ(width_, 4U);
2242 uint32_t intVal = GetVReg(m, reg, kIntVReg);
2243 VLOG(jdwp) << "get int local " << reg << " = " << intVal;
2244 JDWP::Set4BE(buf_+1, intVal);
2245 }
2246 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002247 case JDWP::JT_FLOAT:
2248 {
2249 CHECK_EQ(width_, 4U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002250 uint32_t intVal = GetVReg(m, reg, kFloatVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002251 VLOG(jdwp) << "get int/float local " << reg << " = " << intVal;
2252 JDWP::Set4BE(buf_+1, intVal);
2253 }
2254 break;
2255 case JDWP::JT_ARRAY:
2256 {
2257 CHECK_EQ(width_, sizeof(JDWP::ObjectId));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002258 mirror::Object* o = reinterpret_cast<mirror::Object*>(GetVReg(m, reg, kReferenceVReg));
Ian Rogers0399dde2012-06-06 17:09:28 -07002259 VLOG(jdwp) << "get array local " << reg << " = " << o;
Mathieu Chartier590fee92013-09-13 13:46:47 -07002260 if (!Runtime::Current()->GetHeap()->IsValidObjectAddress(o)) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002261 LOG(FATAL) << "Register " << reg << " expected to hold array: " << o;
2262 }
2263 JDWP::SetObjectId(buf_+1, gRegistry->Add(o));
2264 }
2265 break;
2266 case JDWP::JT_CLASS_LOADER:
2267 case JDWP::JT_CLASS_OBJECT:
2268 case JDWP::JT_OBJECT:
2269 case JDWP::JT_STRING:
2270 case JDWP::JT_THREAD:
2271 case JDWP::JT_THREAD_GROUP:
2272 {
2273 CHECK_EQ(width_, sizeof(JDWP::ObjectId));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002274 mirror::Object* o = reinterpret_cast<mirror::Object*>(GetVReg(m, reg, kReferenceVReg));
Ian Rogers0399dde2012-06-06 17:09:28 -07002275 VLOG(jdwp) << "get object local " << reg << " = " << o;
Mathieu Chartier590fee92013-09-13 13:46:47 -07002276 if (!Runtime::Current()->GetHeap()->IsValidObjectAddress(o)) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002277 LOG(FATAL) << "Register " << reg << " expected to hold object: " << o;
2278 }
Ian Rogers98379392014-02-24 16:53:16 -08002279 tag_ = TagFromObject(soa_, o);
Ian Rogers0399dde2012-06-06 17:09:28 -07002280 JDWP::SetObjectId(buf_+1, gRegistry->Add(o));
2281 }
2282 break;
2283 case JDWP::JT_DOUBLE:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002284 {
2285 CHECK_EQ(width_, 8U);
2286 uint32_t lo = GetVReg(m, reg, kDoubleLoVReg);
2287 uint64_t hi = GetVReg(m, reg + 1, kDoubleHiVReg);
2288 uint64_t longVal = (hi << 32) | lo;
2289 VLOG(jdwp) << "get double/long local " << hi << ":" << lo << " = " << longVal;
2290 JDWP::Set8BE(buf_+1, longVal);
2291 }
2292 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002293 case JDWP::JT_LONG:
2294 {
2295 CHECK_EQ(width_, 8U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002296 uint32_t lo = GetVReg(m, reg, kLongLoVReg);
2297 uint64_t hi = GetVReg(m, reg + 1, kLongHiVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002298 uint64_t longVal = (hi << 32) | lo;
2299 VLOG(jdwp) << "get double/long local " << hi << ":" << lo << " = " << longVal;
2300 JDWP::Set8BE(buf_+1, longVal);
2301 }
2302 break;
2303 default:
2304 LOG(FATAL) << "Unknown tag " << tag_;
2305 break;
2306 }
2307
2308 // Prepend tag, which may have been updated.
2309 JDWP::Set1(buf_, tag_);
2310 return false;
2311 }
Ian Rogers98379392014-02-24 16:53:16 -08002312 const ScopedObjectAccessUnchecked& soa_;
Ian Rogers0399dde2012-06-06 17:09:28 -07002313 const JDWP::FrameId frame_id_;
2314 const int slot_;
2315 JDWP::JdwpTag tag_;
2316 uint8_t* const buf_;
2317 const size_t width_;
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002318 JDWP::JdwpError error_;
Ian Rogers0399dde2012-06-06 17:09:28 -07002319 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002320
2321 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08002322 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002323 Thread* thread;
2324 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
2325 if (error != JDWP::ERR_NONE) {
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002326 return error;
Elliott Hughes221229c2013-01-08 18:17:50 -08002327 }
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002328 // TODO check thread is suspended by the debugger ?
Ian Rogers0399dde2012-06-06 17:09:28 -07002329 UniquePtr<Context> context(Context::Create());
Ian Rogers98379392014-02-24 16:53:16 -08002330 GetLocalVisitor visitor(soa, thread, context.get(), frame_id, slot, tag, buf, width);
Ian Rogers0399dde2012-06-06 17:09:28 -07002331 visitor.WalkStack();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002332 return visitor.error_;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002333}
2334
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002335JDWP::JdwpError Dbg::SetLocalValue(JDWP::ObjectId thread_id, JDWP::FrameId frame_id, int slot,
2336 JDWP::JdwpTag tag, uint64_t value, size_t width) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002337 struct SetLocalVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -08002338 SetLocalVisitor(Thread* thread, Context* context,
Ian Rogers0399dde2012-06-06 17:09:28 -07002339 JDWP::FrameId frame_id, int slot, JDWP::JdwpTag tag, uint64_t value,
Ian Rogersca190662012-06-26 15:45:57 -07002340 size_t width)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002341 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08002342 : StackVisitor(thread, context),
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002343 frame_id_(frame_id), slot_(slot), tag_(tag), value_(value), width_(width),
2344 error_(JDWP::ERR_NONE) {}
Ian Rogersca190662012-06-26 15:45:57 -07002345
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002346 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2347 // annotalysis.
2348 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07002349 if (GetFrameId() != frame_id_) {
2350 return true; // Not our frame, carry on.
2351 }
2352 // TODO: check that the tag is compatible with the actual type of the slot!
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002353 // TODO: check slot is valid for this method or return INVALID_SLOT error.
Brian Carlstromea46f952013-07-30 01:26:50 -07002354 mirror::ArtMethod* m = GetMethod();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002355 if (m->IsNative()) {
2356 // We can't read local value from native method.
2357 error_ = JDWP::ERR_OPAQUE_FRAME;
2358 return false;
2359 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002360 uint16_t reg = DemangleSlot(slot_, m);
2361
2362 switch (tag_) {
2363 case JDWP::JT_BOOLEAN:
2364 case JDWP::JT_BYTE:
2365 CHECK_EQ(width_, 1U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002366 SetVReg(m, reg, static_cast<uint32_t>(value_), kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002367 break;
2368 case JDWP::JT_SHORT:
2369 case JDWP::JT_CHAR:
2370 CHECK_EQ(width_, 2U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002371 SetVReg(m, reg, static_cast<uint32_t>(value_), kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002372 break;
2373 case JDWP::JT_INT:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002374 CHECK_EQ(width_, 4U);
2375 SetVReg(m, reg, static_cast<uint32_t>(value_), kIntVReg);
2376 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002377 case JDWP::JT_FLOAT:
2378 CHECK_EQ(width_, 4U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002379 SetVReg(m, reg, static_cast<uint32_t>(value_), kFloatVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002380 break;
2381 case JDWP::JT_ARRAY:
2382 case JDWP::JT_OBJECT:
2383 case JDWP::JT_STRING:
2384 {
2385 CHECK_EQ(width_, sizeof(JDWP::ObjectId));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002386 mirror::Object* o = gRegistry->Get<mirror::Object*>(static_cast<JDWP::ObjectId>(value_));
Elliott Hughes64f574f2013-02-20 14:57:12 -08002387 if (o == ObjectRegistry::kInvalidObject) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002388 UNIMPLEMENTED(FATAL) << "return an error code when given an invalid object to store";
2389 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002390 SetVReg(m, reg, static_cast<uint32_t>(reinterpret_cast<uintptr_t>(o)), kReferenceVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002391 }
2392 break;
2393 case JDWP::JT_DOUBLE:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002394 CHECK_EQ(width_, 8U);
2395 SetVReg(m, reg, static_cast<uint32_t>(value_), kDoubleLoVReg);
2396 SetVReg(m, reg + 1, static_cast<uint32_t>(value_ >> 32), kDoubleHiVReg);
2397 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002398 case JDWP::JT_LONG:
2399 CHECK_EQ(width_, 8U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002400 SetVReg(m, reg, static_cast<uint32_t>(value_), kLongLoVReg);
2401 SetVReg(m, reg + 1, static_cast<uint32_t>(value_ >> 32), kLongHiVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002402 break;
2403 default:
2404 LOG(FATAL) << "Unknown tag " << tag_;
2405 break;
2406 }
2407 return false;
2408 }
2409
2410 const JDWP::FrameId frame_id_;
2411 const int slot_;
2412 const JDWP::JdwpTag tag_;
2413 const uint64_t value_;
2414 const size_t width_;
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002415 JDWP::JdwpError error_;
Ian Rogers0399dde2012-06-06 17:09:28 -07002416 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002417
2418 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08002419 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002420 Thread* thread;
2421 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
2422 if (error != JDWP::ERR_NONE) {
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002423 return error;
Elliott Hughes221229c2013-01-08 18:17:50 -08002424 }
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002425 // TODO check thread is suspended by the debugger ?
Elliott Hughes08fc03a2012-06-26 17:34:00 -07002426 UniquePtr<Context> context(Context::Create());
Ian Rogers7a22fa62013-01-23 12:16:16 -08002427 SetLocalVisitor visitor(thread, context.get(), frame_id, slot, tag, value, width);
Ian Rogers0399dde2012-06-06 17:09:28 -07002428 visitor.WalkStack();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002429 return visitor.error_;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002430}
2431
Ian Rogersef7d42f2014-01-06 12:55:46 -08002432void Dbg::PostLocationEvent(mirror::ArtMethod* m, int dex_pc, mirror::Object* this_object,
Jeff Hao579b0242013-11-18 13:16:49 -08002433 int event_flags, const JValue* return_value) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002434 JDWP::JdwpLocation location;
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002435 SetLocation(location, m, dex_pc);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002436
Elliott Hughes64f574f2013-02-20 14:57:12 -08002437 // If 'this_object' isn't already in the registry, we know that we're not looking for it,
2438 // so there's no point adding it to the registry and burning through ids.
2439 JDWP::ObjectId this_id = 0;
2440 if (gRegistry->Contains(this_object)) {
2441 this_id = gRegistry->Add(this_object);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002442 }
Jeff Hao579b0242013-11-18 13:16:49 -08002443 gJdwpState->PostLocationEvent(&location, this_id, event_flags, return_value);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002444}
2445
Ian Rogers62d6c772013-02-27 08:32:07 -08002446void Dbg::PostException(Thread* thread, const ThrowLocation& throw_location,
Brian Carlstromea46f952013-07-30 01:26:50 -07002447 mirror::ArtMethod* catch_method,
Elliott Hughes64f574f2013-02-20 14:57:12 -08002448 uint32_t catch_dex_pc, mirror::Throwable* exception_object) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002449 if (!IsDebuggerActive()) {
Ian Rogers0ad5bb82011-12-07 10:16:32 -08002450 return;
2451 }
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002452
Ian Rogers62d6c772013-02-27 08:32:07 -08002453 JDWP::JdwpLocation jdwp_throw_location;
2454 SetLocation(jdwp_throw_location, throw_location.GetMethod(), throw_location.GetDexPc());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002455 JDWP::JdwpLocation catch_location;
Elliott Hughescaf76542012-06-28 16:08:22 -07002456 SetLocation(catch_location, catch_method, catch_dex_pc);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002457
2458 // We need 'this' for InstanceOnly filters.
Ian Rogers62d6c772013-02-27 08:32:07 -08002459 JDWP::ObjectId this_id = gRegistry->Add(throw_location.GetThis());
Elliott Hughes64f574f2013-02-20 14:57:12 -08002460 JDWP::ObjectId exception_id = gRegistry->Add(exception_object);
2461 JDWP::RefTypeId exception_class_id = gRegistry->AddRefType(exception_object->GetClass());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002462
Ian Rogers62d6c772013-02-27 08:32:07 -08002463 gJdwpState->PostException(&jdwp_throw_location, exception_id, exception_class_id, &catch_location,
2464 this_id);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002465}
2466
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002467void Dbg::PostClassPrepare(mirror::Class* c) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002468 if (!IsDebuggerActive()) {
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002469 return;
2470 }
2471
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08002472 // OLD-TODO - we currently always send both "verified" and "prepared" since
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002473 // debuggers seem to like that. There might be some advantage to honesty,
2474 // since the class may not yet be verified.
2475 int state = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
2476 JDWP::JdwpTypeTag tag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
Ian Rogersfc0e94b2013-09-23 23:51:32 -07002477 gJdwpState->PostClassPrepare(tag, gRegistry->Add(c),
Ian Rogersdfb325e2013-10-30 01:00:44 -07002478 ClassHelper(c).GetDescriptor(), state);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002479}
2480
Ian Rogers62d6c772013-02-27 08:32:07 -08002481void Dbg::UpdateDebugger(Thread* thread, mirror::Object* this_object,
Ian Rogersef7d42f2014-01-06 12:55:46 -08002482 mirror::ArtMethod* m, uint32_t dex_pc) {
Ian Rogers62d6c772013-02-27 08:32:07 -08002483 if (!IsDebuggerActive() || dex_pc == static_cast<uint32_t>(-2) /* fake method exit */) {
Elliott Hughes2aa2e392012-02-17 17:15:43 -08002484 return;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002485 }
2486
Elliott Hughes2aa2e392012-02-17 17:15:43 -08002487 int event_flags = 0;
2488
Elliott Hughes86964332012-02-15 19:37:42 -08002489 if (IsBreakpoint(m, dex_pc)) {
2490 event_flags |= kBreakpoint;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002491 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002492
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002493 // If the debugger is single-stepping one of our threads, check to
2494 // see if we're that thread and we've reached a step point.
2495 const SingleStepControl* single_step_control = thread->GetSingleStepControl();
2496 DCHECK(single_step_control != nullptr);
2497 if (single_step_control->is_active) {
2498 CHECK(!m->IsNative());
2499 if (single_step_control->step_depth == JDWP::SD_INTO) {
2500 // Step into method calls. We break when the line number
2501 // or method pointer changes. If we're in SS_MIN mode, we
2502 // always stop.
2503 if (single_step_control->method != m) {
2504 event_flags |= kSingleStep;
2505 VLOG(jdwp) << "SS new method";
2506 } else if (single_step_control->step_size == JDWP::SS_MIN) {
2507 event_flags |= kSingleStep;
2508 VLOG(jdwp) << "SS new instruction";
2509 } else if (single_step_control->dex_pcs.find(dex_pc) == single_step_control->dex_pcs.end()) {
2510 event_flags |= kSingleStep;
2511 VLOG(jdwp) << "SS new line";
2512 }
2513 } else if (single_step_control->step_depth == JDWP::SD_OVER) {
2514 // Step over method calls. We break when the line number is
2515 // different and the frame depth is <= the original frame
2516 // depth. (We can't just compare on the method, because we
2517 // might get unrolled past it by an exception, and it's tricky
2518 // to identify recursion.)
2519
2520 int stack_depth = GetStackDepth(thread);
2521
2522 if (stack_depth < single_step_control->stack_depth) {
2523 // Popped up one or more frames, always trigger.
2524 event_flags |= kSingleStep;
2525 VLOG(jdwp) << "SS method pop";
2526 } else if (stack_depth == single_step_control->stack_depth) {
2527 // Same depth, see if we moved.
2528 if (single_step_control->step_size == JDWP::SS_MIN) {
Elliott Hughes86964332012-02-15 19:37:42 -08002529 event_flags |= kSingleStep;
2530 VLOG(jdwp) << "SS new instruction";
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002531 } else if (single_step_control->dex_pcs.find(dex_pc) == single_step_control->dex_pcs.end()) {
Elliott Hughes2435a572012-02-17 16:07:41 -08002532 event_flags |= kSingleStep;
2533 VLOG(jdwp) << "SS new line";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002534 }
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002535 }
2536 } else {
2537 CHECK_EQ(single_step_control->step_depth, JDWP::SD_OUT);
2538 // Return from the current method. We break when the frame
2539 // depth pops up.
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002540
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002541 // This differs from the "method exit" break in that it stops
2542 // with the PC at the next instruction in the returned-to
2543 // function, rather than the end of the returning function.
Elliott Hughes86964332012-02-15 19:37:42 -08002544
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002545 int stack_depth = GetStackDepth(thread);
2546 if (stack_depth < single_step_control->stack_depth) {
2547 event_flags |= kSingleStep;
2548 VLOG(jdwp) << "SS method pop";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002549 }
2550 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002551 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002552
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002553 // If there's something interesting going on, see if it matches one
2554 // of the debugger filters.
2555 if (event_flags != 0) {
Jeff Hao579b0242013-11-18 13:16:49 -08002556 Dbg::PostLocationEvent(m, dex_pc, this_object, event_flags, nullptr);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002557 }
2558}
2559
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002560// Process request while all mutator threads are suspended.
2561void Dbg::ProcessDeoptimizationRequest(const DeoptimizationRequest& request) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002562 instrumentation::Instrumentation* instrumentation = Runtime::Current()->GetInstrumentation();
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002563 switch (request.kind) {
2564 case DeoptimizationRequest::kNothing:
2565 LOG(WARNING) << "Ignoring empty deoptimization request.";
2566 break;
2567 case DeoptimizationRequest::kFullDeoptimization:
2568 VLOG(jdwp) << "Deoptimize the world";
2569 instrumentation->DeoptimizeEverything();
2570 break;
2571 case DeoptimizationRequest::kFullUndeoptimization:
2572 VLOG(jdwp) << "Undeoptimize the world";
2573 instrumentation->UndeoptimizeEverything();
2574 break;
2575 case DeoptimizationRequest::kSelectiveDeoptimization:
2576 VLOG(jdwp) << "Deoptimize method " << PrettyMethod(request.method);
2577 instrumentation->Deoptimize(request.method);
2578 break;
2579 case DeoptimizationRequest::kSelectiveUndeoptimization:
2580 VLOG(jdwp) << "Undeoptimize method " << PrettyMethod(request.method);
2581 instrumentation->Undeoptimize(request.method);
2582 break;
2583 default:
2584 LOG(FATAL) << "Unsupported deoptimization request kind " << request.kind;
2585 break;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002586 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002587}
2588
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002589void Dbg::RequestDeoptimization(const DeoptimizationRequest& req) {
2590 if (req.kind == DeoptimizationRequest::kNothing) {
2591 // Nothing to do.
2592 return;
2593 }
2594 MutexLock mu(Thread::Current(), *deoptimization_lock_);
2595 switch (req.kind) {
2596 case DeoptimizationRequest::kFullDeoptimization: {
2597 DCHECK(req.method == nullptr);
2598 if (full_deoptimization_event_count_ == 0) {
2599 VLOG(jdwp) << "Request full deoptimization";
2600 deoptimization_requests_.push_back(req);
2601 }
2602 ++full_deoptimization_event_count_;
2603 break;
2604 }
2605 case DeoptimizationRequest::kFullUndeoptimization: {
2606 DCHECK(req.method == nullptr);
2607 DCHECK_GT(full_deoptimization_event_count_, 0U);
2608 --full_deoptimization_event_count_;
2609 if (full_deoptimization_event_count_ == 0) {
2610 VLOG(jdwp) << "Request full undeoptimization";
2611 deoptimization_requests_.push_back(req);
2612 }
2613 break;
2614 }
2615 case DeoptimizationRequest::kSelectiveDeoptimization: {
2616 DCHECK(req.method != nullptr);
2617 VLOG(jdwp) << "Request deoptimization of " << PrettyMethod(req.method);
2618 deoptimization_requests_.push_back(req);
2619 break;
2620 }
2621 case DeoptimizationRequest::kSelectiveUndeoptimization: {
2622 DCHECK(req.method != nullptr);
2623 VLOG(jdwp) << "Request undeoptimization of " << PrettyMethod(req.method);
2624 deoptimization_requests_.push_back(req);
2625 break;
2626 }
2627 default: {
2628 LOG(FATAL) << "Unknown deoptimization request kind " << req.kind;
2629 break;
2630 }
2631 }
2632}
2633
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002634void Dbg::ManageDeoptimization() {
2635 Thread* const self = Thread::Current();
2636 {
2637 // Avoid suspend/resume if there is no pending request.
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002638 MutexLock mu(self, *deoptimization_lock_);
2639 if (deoptimization_requests_.empty()) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002640 return;
2641 }
2642 }
2643 CHECK_EQ(self->GetState(), kRunnable);
2644 self->TransitionFromRunnableToSuspended(kWaitingForDeoptimization);
2645 // We need to suspend mutator threads first.
2646 Runtime* const runtime = Runtime::Current();
2647 runtime->GetThreadList()->SuspendAll();
2648 const ThreadState old_state = self->SetStateUnsafe(kRunnable);
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002649 {
2650 MutexLock mu(self, *deoptimization_lock_);
2651 for (const DeoptimizationRequest& request : deoptimization_requests_) {
2652 ProcessDeoptimizationRequest(request);
2653 }
2654 deoptimization_requests_.clear();
2655 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002656 CHECK_EQ(self->SetStateUnsafe(old_state), kRunnable);
2657 runtime->GetThreadList()->ResumeAll();
2658 self->TransitionFromSuspendedToRunnable();
2659}
2660
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002661void Dbg::WatchLocation(const JDWP::JdwpLocation* location, DeoptimizationRequest* req) {
2662 // TODO we don't need to deoptimize a method if it's not compiled since it already runs with the
2663 // interpreter.
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002664 bool need_deoptimization = true;
Brian Carlstromea46f952013-07-30 01:26:50 -07002665 mirror::ArtMethod* m = FromMethodId(location->method_id);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002666 {
2667 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
2668
2669 // If there is no breakpoint on this method yet, we need to deoptimize it.
2670 for (const Breakpoint& breakpoint : gBreakpoints) {
2671 if (breakpoint.method == m) {
2672 // We already set a breakpoint on this method, hence we deoptimized it.
2673 DCHECK(Runtime::Current()->GetInstrumentation()->IsDeoptimized(m));
2674 need_deoptimization = false;
2675 break;
2676 }
2677 }
2678
2679 gBreakpoints.push_back(Breakpoint(m, location->dex_pc));
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002680 VLOG(jdwp) << "Set breakpoint #" << (gBreakpoints.size() - 1) << ": "
2681 << gBreakpoints[gBreakpoints.size() - 1];
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002682 }
2683
2684 if (need_deoptimization) {
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002685 req->kind = DeoptimizationRequest::kSelectiveDeoptimization;
2686 req->method = m;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002687 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002688}
2689
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002690void Dbg::UnwatchLocation(const JDWP::JdwpLocation* location, DeoptimizationRequest* req) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002691 bool can_undeoptimize = true;
Brian Carlstromea46f952013-07-30 01:26:50 -07002692 mirror::ArtMethod* m = FromMethodId(location->method_id);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002693 DCHECK(Runtime::Current()->GetInstrumentation()->IsDeoptimized(m));
2694 {
2695 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
2696 for (size_t i = 0, e = gBreakpoints.size(); i < e; ++i) {
2697 if (gBreakpoints[i].method == m && gBreakpoints[i].dex_pc == location->dex_pc) {
2698 VLOG(jdwp) << "Removed breakpoint #" << i << ": " << gBreakpoints[i];
2699 gBreakpoints.erase(gBreakpoints.begin() + i);
2700 break;
2701 }
Elliott Hughes86964332012-02-15 19:37:42 -08002702 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002703
2704 // If there is no breakpoint on this method, we can undeoptimize it.
2705 for (const Breakpoint& breakpoint : gBreakpoints) {
2706 if (breakpoint.method == m) {
2707 can_undeoptimize = false;
2708 break;
2709 }
2710 }
2711 }
2712
2713 if (can_undeoptimize) {
2714 // Request its undeoptimization. This will be done after updating the JDWP event list.
Sebastien Hertz4d25df32014-03-21 17:44:46 +01002715 req->kind = DeoptimizationRequest::kSelectiveUndeoptimization;
2716 req->method = m;
Elliott Hughes86964332012-02-15 19:37:42 -08002717 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002718}
2719
Jeff Hao449db332013-04-12 18:30:52 -07002720// Scoped utility class to suspend a thread so that we may do tasks such as walk its stack. Doesn't
2721// cause suspension if the thread is the current thread.
2722class ScopedThreadSuspension {
2723 public:
Ian Rogers33e95662013-05-20 20:29:14 -07002724 ScopedThreadSuspension(Thread* self, JDWP::ObjectId thread_id)
Sebastien Hertz52d131d2014-03-13 16:17:40 +01002725 LOCKS_EXCLUDED(Locks::thread_list_lock_)
Ian Rogers33e95662013-05-20 20:29:14 -07002726 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) :
Jeff Hao449db332013-04-12 18:30:52 -07002727 thread_(NULL),
2728 error_(JDWP::ERR_NONE),
2729 self_suspend_(false),
Ian Rogers33e95662013-05-20 20:29:14 -07002730 other_suspend_(false) {
Jeff Hao449db332013-04-12 18:30:52 -07002731 ScopedObjectAccessUnchecked soa(self);
2732 {
2733 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
2734 error_ = DecodeThread(soa, thread_id, thread_);
2735 }
2736 if (error_ == JDWP::ERR_NONE) {
2737 if (thread_ == soa.Self()) {
2738 self_suspend_ = true;
2739 } else {
2740 soa.Self()->TransitionFromRunnableToSuspended(kWaitingForDebuggerSuspension);
2741 jobject thread_peer = gRegistry->GetJObject(thread_id);
2742 bool timed_out;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07002743 Thread* suspended_thread = ThreadList::SuspendThreadByPeer(thread_peer, true, true,
2744 &timed_out);
Jeff Hao449db332013-04-12 18:30:52 -07002745 CHECK_EQ(soa.Self()->TransitionFromSuspendedToRunnable(), kWaitingForDebuggerSuspension);
2746 if (suspended_thread == NULL) {
2747 // Thread terminated from under us while suspending.
2748 error_ = JDWP::ERR_INVALID_THREAD;
2749 } else {
2750 CHECK_EQ(suspended_thread, thread_);
2751 other_suspend_ = true;
2752 }
2753 }
2754 }
Elliott Hughes2435a572012-02-17 16:07:41 -08002755 }
Elliott Hughes86964332012-02-15 19:37:42 -08002756
Jeff Hao449db332013-04-12 18:30:52 -07002757 Thread* GetThread() const {
2758 return thread_;
2759 }
2760
2761 JDWP::JdwpError GetError() const {
2762 return error_;
2763 }
2764
2765 ~ScopedThreadSuspension() {
2766 if (other_suspend_) {
2767 Runtime::Current()->GetThreadList()->Resume(thread_, true);
2768 }
2769 }
2770
2771 private:
2772 Thread* thread_;
2773 JDWP::JdwpError error_;
2774 bool self_suspend_;
2775 bool other_suspend_;
2776};
2777
2778JDWP::JdwpError Dbg::ConfigureStep(JDWP::ObjectId thread_id, JDWP::JdwpStepSize step_size,
2779 JDWP::JdwpStepDepth step_depth) {
2780 Thread* self = Thread::Current();
2781 ScopedThreadSuspension sts(self, thread_id);
2782 if (sts.GetError() != JDWP::ERR_NONE) {
2783 return sts.GetError();
2784 }
2785
Elliott Hughes2435a572012-02-17 16:07:41 -08002786 //
2787 // Work out what Method* we're in, the current line number, and how deep the stack currently
2788 // is for step-out.
2789 //
2790
Ian Rogers0399dde2012-06-06 17:09:28 -07002791 struct SingleStepStackVisitor : public StackVisitor {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002792 explicit SingleStepStackVisitor(Thread* thread, SingleStepControl* single_step_control,
2793 int32_t* line_number)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002794 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002795 : StackVisitor(thread, NULL), single_step_control_(single_step_control),
2796 line_number_(line_number) {
2797 DCHECK_EQ(single_step_control_, thread->GetSingleStepControl());
2798 single_step_control_->method = NULL;
2799 single_step_control_->stack_depth = 0;
Elliott Hughes86964332012-02-15 19:37:42 -08002800 }
Ian Rogersca190662012-06-26 15:45:57 -07002801
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002802 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2803 // annotalysis.
2804 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002805 mirror::ArtMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07002806 if (!m->IsRuntimeMethod()) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002807 ++single_step_control_->stack_depth;
2808 if (single_step_control_->method == NULL) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002809 mirror::DexCache* dex_cache = m->GetDeclaringClass()->GetDexCache();
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002810 single_step_control_->method = m;
2811 *line_number_ = -1;
Elliott Hughes2435a572012-02-17 16:07:41 -08002812 if (dex_cache != NULL) {
Ian Rogers4445a7e2012-10-05 17:19:13 -07002813 const DexFile& dex_file = *dex_cache->GetDexFile();
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002814 *line_number_ = dex_file.GetLineNumFromPC(m, GetDexPc());
Elliott Hughes2435a572012-02-17 16:07:41 -08002815 }
Elliott Hughes86964332012-02-15 19:37:42 -08002816 }
2817 }
Elliott Hughes530fa002012-03-12 11:44:49 -07002818 return true;
Elliott Hughes86964332012-02-15 19:37:42 -08002819 }
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002820
2821 SingleStepControl* const single_step_control_;
2822 int32_t* const line_number_;
Elliott Hughes86964332012-02-15 19:37:42 -08002823 };
Jeff Hao449db332013-04-12 18:30:52 -07002824
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002825 Thread* const thread = sts.GetThread();
2826 SingleStepControl* const single_step_control = thread->GetSingleStepControl();
2827 DCHECK(single_step_control != nullptr);
2828 int32_t line_number = -1;
2829 SingleStepStackVisitor visitor(thread, single_step_control, &line_number);
Ian Rogers0399dde2012-06-06 17:09:28 -07002830 visitor.WalkStack();
Elliott Hughes86964332012-02-15 19:37:42 -08002831
Elliott Hughes2435a572012-02-17 16:07:41 -08002832 //
2833 // Find the dex_pc values that correspond to the current line, for line-based single-stepping.
2834 //
2835
2836 struct DebugCallbackContext {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002837 explicit DebugCallbackContext(SingleStepControl* single_step_control, int32_t line_number)
2838 : single_step_control_(single_step_control), line_number_(line_number),
2839 last_pc_valid(false), last_pc(0) {
Elliott Hughes2435a572012-02-17 16:07:41 -08002840 }
2841
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002842 static bool Callback(void* raw_context, uint32_t address, uint32_t line_number) {
Elliott Hughes2435a572012-02-17 16:07:41 -08002843 DebugCallbackContext* context = reinterpret_cast<DebugCallbackContext*>(raw_context);
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002844 if (static_cast<int32_t>(line_number) == context->line_number_) {
Elliott Hughes2435a572012-02-17 16:07:41 -08002845 if (!context->last_pc_valid) {
2846 // Everything from this address until the next line change is ours.
2847 context->last_pc = address;
2848 context->last_pc_valid = true;
2849 }
2850 // Otherwise, if we're already in a valid range for this line,
2851 // just keep going (shouldn't really happen)...
Brian Carlstrom7934ac22013-07-26 10:54:15 -07002852 } else if (context->last_pc_valid) { // and the line number is new
Elliott Hughes2435a572012-02-17 16:07:41 -08002853 // Add everything from the last entry up until here to the set
2854 for (uint32_t dex_pc = context->last_pc; dex_pc < address; ++dex_pc) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002855 context->single_step_control_->dex_pcs.insert(dex_pc);
Elliott Hughes2435a572012-02-17 16:07:41 -08002856 }
2857 context->last_pc_valid = false;
2858 }
Brian Carlstrom7934ac22013-07-26 10:54:15 -07002859 return false; // There may be multiple entries for any given line.
Elliott Hughes2435a572012-02-17 16:07:41 -08002860 }
2861
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002862 ~DebugCallbackContext() {
Elliott Hughes2435a572012-02-17 16:07:41 -08002863 // If the line number was the last in the position table...
2864 if (last_pc_valid) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002865 size_t end = MethodHelper(single_step_control_->method).GetCodeItem()->insns_size_in_code_units_;
Elliott Hughes2435a572012-02-17 16:07:41 -08002866 for (uint32_t dex_pc = last_pc; dex_pc < end; ++dex_pc) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002867 single_step_control_->dex_pcs.insert(dex_pc);
Elliott Hughes2435a572012-02-17 16:07:41 -08002868 }
2869 }
2870 }
2871
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002872 SingleStepControl* const single_step_control_;
2873 const int32_t line_number_;
Elliott Hughes2435a572012-02-17 16:07:41 -08002874 bool last_pc_valid;
2875 uint32_t last_pc;
2876 };
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002877 single_step_control->dex_pcs.clear();
Ian Rogersef7d42f2014-01-06 12:55:46 -08002878 mirror::ArtMethod* m = single_step_control->method;
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002879 if (!m->IsNative()) {
2880 DebugCallbackContext context(single_step_control, line_number);
Elliott Hughes3e2e1a22012-02-21 11:33:41 -08002881 MethodHelper mh(m);
2882 mh.GetDexFile().DecodeDebugInfo(mh.GetCodeItem(), m->IsStatic(), m->GetDexMethodIndex(),
2883 DebugCallbackContext::Callback, NULL, &context);
2884 }
Elliott Hughes2435a572012-02-17 16:07:41 -08002885
2886 //
2887 // Everything else...
2888 //
2889
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002890 single_step_control->step_size = step_size;
2891 single_step_control->step_depth = step_depth;
2892 single_step_control->is_active = true;
Elliott Hughes86964332012-02-15 19:37:42 -08002893
Elliott Hughes2435a572012-02-17 16:07:41 -08002894 if (VLOG_IS_ON(jdwp)) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002895 VLOG(jdwp) << "Single-step thread: " << *thread;
2896 VLOG(jdwp) << "Single-step step size: " << single_step_control->step_size;
2897 VLOG(jdwp) << "Single-step step depth: " << single_step_control->step_depth;
2898 VLOG(jdwp) << "Single-step current method: " << PrettyMethod(single_step_control->method);
2899 VLOG(jdwp) << "Single-step current line: " << line_number;
2900 VLOG(jdwp) << "Single-step current stack depth: " << single_step_control->stack_depth;
Elliott Hughes2435a572012-02-17 16:07:41 -08002901 VLOG(jdwp) << "Single-step dex_pc values:";
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002902 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 -08002903 VLOG(jdwp) << StringPrintf(" %#x", *it);
Elliott Hughes2435a572012-02-17 16:07:41 -08002904 }
2905 }
2906
2907 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002908}
2909
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002910void Dbg::UnconfigureStep(JDWP::ObjectId thread_id) {
2911 ScopedObjectAccessUnchecked soa(Thread::Current());
2912 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
2913 Thread* thread;
2914 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
Sebastien Hertz87118ed2013-11-26 17:57:18 +01002915 if (error == JDWP::ERR_NONE) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002916 SingleStepControl* single_step_control = thread->GetSingleStepControl();
2917 DCHECK(single_step_control != nullptr);
2918 single_step_control->is_active = false;
2919 single_step_control->dex_pcs.clear();
2920 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002921}
2922
Elliott Hughes45651fd2012-02-21 15:48:20 -08002923static char JdwpTagToShortyChar(JDWP::JdwpTag tag) {
2924 switch (tag) {
2925 default:
2926 LOG(FATAL) << "unknown JDWP tag: " << PrintableChar(tag);
2927
2928 // Primitives.
2929 case JDWP::JT_BYTE: return 'B';
2930 case JDWP::JT_CHAR: return 'C';
2931 case JDWP::JT_FLOAT: return 'F';
2932 case JDWP::JT_DOUBLE: return 'D';
2933 case JDWP::JT_INT: return 'I';
2934 case JDWP::JT_LONG: return 'J';
2935 case JDWP::JT_SHORT: return 'S';
2936 case JDWP::JT_VOID: return 'V';
2937 case JDWP::JT_BOOLEAN: return 'Z';
2938
2939 // Reference types.
2940 case JDWP::JT_ARRAY:
2941 case JDWP::JT_OBJECT:
2942 case JDWP::JT_STRING:
2943 case JDWP::JT_THREAD:
2944 case JDWP::JT_THREAD_GROUP:
2945 case JDWP::JT_CLASS_LOADER:
2946 case JDWP::JT_CLASS_OBJECT:
2947 return 'L';
2948 }
2949}
2950
Elliott Hughes88d63092013-01-09 09:55:54 -08002951JDWP::JdwpError Dbg::InvokeMethod(JDWP::ObjectId thread_id, JDWP::ObjectId object_id,
2952 JDWP::RefTypeId class_id, JDWP::MethodId method_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002953 uint32_t arg_count, uint64_t* arg_values,
2954 JDWP::JdwpTag* arg_types, uint32_t options,
2955 JDWP::JdwpTag* pResultTag, uint64_t* pResultValue,
2956 JDWP::ObjectId* pExceptionId) {
Elliott Hughesd07986f2011-12-06 18:27:45 -08002957 ThreadList* thread_list = Runtime::Current()->GetThreadList();
2958
2959 Thread* targetThread = NULL;
2960 DebugInvokeReq* req = NULL;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002961 Thread* self = Thread::Current();
Elliott Hughesd07986f2011-12-06 18:27:45 -08002962 {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002963 ScopedObjectAccessUnchecked soa(self);
Ian Rogers50b35e22012-10-04 10:09:15 -07002964 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002965 JDWP::JdwpError error = DecodeThread(soa, thread_id, targetThread);
2966 if (error != JDWP::ERR_NONE) {
2967 LOG(ERROR) << "InvokeMethod request for invalid thread id " << thread_id;
2968 return error;
Elliott Hughesd07986f2011-12-06 18:27:45 -08002969 }
2970 req = targetThread->GetInvokeReq();
2971 if (!req->ready) {
2972 LOG(ERROR) << "InvokeMethod request for thread not stopped by event: " << *targetThread;
2973 return JDWP::ERR_INVALID_THREAD;
2974 }
2975
2976 /*
2977 * We currently have a bug where we don't successfully resume the
2978 * target thread if the suspend count is too deep. We're expected to
2979 * require one "resume" for each "suspend", but when asked to execute
2980 * a method we have to resume fully and then re-suspend it back to the
2981 * same level. (The easiest way to cause this is to type "suspend"
2982 * multiple times in jdb.)
2983 *
2984 * It's unclear what this means when the event specifies "resume all"
2985 * and some threads are suspended more deeply than others. This is
2986 * a rare problem, so for now we just prevent it from hanging forever
2987 * by rejecting the method invocation request. Without this, we will
2988 * be stuck waiting on a suspended thread.
2989 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002990 int suspend_count;
2991 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002992 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002993 suspend_count = targetThread->GetSuspendCount();
2994 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08002995 if (suspend_count > 1) {
2996 LOG(ERROR) << *targetThread << " suspend count too deep for method invocation: " << suspend_count;
Brian Carlstrom7934ac22013-07-26 10:54:15 -07002997 return JDWP::ERR_THREAD_SUSPENDED; // Probably not expected here.
Elliott Hughesd07986f2011-12-06 18:27:45 -08002998 }
2999
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08003000 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003001 mirror::Object* receiver = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08003002 if (receiver == ObjectRegistry::kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08003003 return JDWP::ERR_INVALID_OBJECT;
3004 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003005
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003006 mirror::Object* thread = gRegistry->Get<mirror::Object*>(thread_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08003007 if (thread == ObjectRegistry::kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08003008 return JDWP::ERR_INVALID_OBJECT;
3009 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003010 // TODO: check that 'thread' is actually a java.lang.Thread!
3011
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003012 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes45651fd2012-02-21 15:48:20 -08003013 if (c == NULL) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08003014 return status;
3015 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003016
Brian Carlstromea46f952013-07-30 01:26:50 -07003017 mirror::ArtMethod* m = FromMethodId(method_id);
Elliott Hughes45651fd2012-02-21 15:48:20 -08003018 if (m->IsStatic() != (receiver == NULL)) {
3019 return JDWP::ERR_INVALID_METHODID;
3020 }
3021 if (m->IsStatic()) {
3022 if (m->GetDeclaringClass() != c) {
3023 return JDWP::ERR_INVALID_METHODID;
3024 }
3025 } else {
3026 if (!m->GetDeclaringClass()->IsAssignableFrom(c)) {
3027 return JDWP::ERR_INVALID_METHODID;
3028 }
3029 }
3030
3031 // Check the argument list matches the method.
3032 MethodHelper mh(m);
3033 if (mh.GetShortyLength() - 1 != arg_count) {
3034 return JDWP::ERR_ILLEGAL_ARGUMENT;
3035 }
3036 const char* shorty = mh.GetShorty();
Elliott Hughes09201632013-04-15 15:50:07 -07003037 const DexFile::TypeList* types = mh.GetParameterTypeList();
Elliott Hughes45651fd2012-02-21 15:48:20 -08003038 for (size_t i = 0; i < arg_count; ++i) {
3039 if (shorty[i + 1] != JdwpTagToShortyChar(arg_types[i])) {
3040 return JDWP::ERR_ILLEGAL_ARGUMENT;
3041 }
Elliott Hughes09201632013-04-15 15:50:07 -07003042
3043 if (shorty[i + 1] == 'L') {
3044 // Did we really get an argument of an appropriate reference type?
3045 mirror::Class* parameter_type = mh.GetClassFromTypeIdx(types->GetTypeItem(i).type_idx_);
3046 mirror::Object* argument = gRegistry->Get<mirror::Object*>(arg_values[i]);
3047 if (argument == ObjectRegistry::kInvalidObject) {
3048 return JDWP::ERR_INVALID_OBJECT;
3049 }
Sebastien Hertz0630ab52013-11-28 18:53:35 +01003050 if (argument != NULL && !argument->InstanceOf(parameter_type)) {
Elliott Hughes09201632013-04-15 15:50:07 -07003051 return JDWP::ERR_ILLEGAL_ARGUMENT;
3052 }
3053
3054 // Turn the on-the-wire ObjectId into a jobject.
3055 jvalue& v = reinterpret_cast<jvalue&>(arg_values[i]);
3056 v.l = gRegistry->GetJObject(arg_values[i]);
3057 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003058 }
3059
Sebastien Hertzd38667a2013-11-25 15:43:54 +01003060 req->receiver = receiver;
3061 req->thread = thread;
3062 req->klass = c;
3063 req->method = m;
3064 req->arg_count = arg_count;
3065 req->arg_values = arg_values;
3066 req->options = options;
3067 req->invoke_needed = true;
Elliott Hughesd07986f2011-12-06 18:27:45 -08003068 }
3069
3070 // The fact that we've released the thread list lock is a bit risky --- if the thread goes
3071 // away we're sitting high and dry -- but we must release this before the ResumeAllThreads
3072 // call, and it's unwise to hold it during WaitForSuspend.
3073
3074 {
3075 /*
3076 * We change our (JDWP thread) status, which should be THREAD_RUNNING,
Elliott Hughes81ff3182012-03-23 20:35:56 -07003077 * so we can suspend for a GC if the invoke request causes us to
Elliott Hughesd07986f2011-12-06 18:27:45 -08003078 * run out of memory. It's also a good idea to change it before locking
3079 * the invokeReq mutex, although that should never be held for long.
3080 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003081 self->TransitionFromRunnableToSuspended(kWaitingForDebuggerSend);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003082
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003083 VLOG(jdwp) << " Transferring control to event thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08003084 {
Sebastien Hertzd38667a2013-11-25 15:43:54 +01003085 MutexLock mu(self, req->lock);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003086
3087 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003088 VLOG(jdwp) << " Resuming all threads";
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003089 thread_list->UndoDebuggerSuspensions();
Elliott Hughesd07986f2011-12-06 18:27:45 -08003090 } else {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003091 VLOG(jdwp) << " Resuming event thread only";
Elliott Hughesd07986f2011-12-06 18:27:45 -08003092 thread_list->Resume(targetThread, true);
3093 }
3094
3095 // Wait for the request to finish executing.
Sebastien Hertzd38667a2013-11-25 15:43:54 +01003096 while (req->invoke_needed) {
3097 req->cond.Wait(self);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003098 }
3099 }
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003100 VLOG(jdwp) << " Control has returned from event thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08003101
3102 /* wait for thread to re-suspend itself */
Brian Carlstromdf629502013-07-17 22:39:56 -07003103 SuspendThread(thread_id, false /* request_suspension */);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003104 self->TransitionFromSuspendedToRunnable();
Elliott Hughesd07986f2011-12-06 18:27:45 -08003105 }
3106
3107 /*
3108 * Suspend the threads. We waited for the target thread to suspend
3109 * itself, so all we need to do is suspend the others.
3110 *
3111 * The suspendAllThreads() call will double-suspend the event thread,
3112 * so we want to resume the target thread once to keep the books straight.
3113 */
3114 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003115 self->TransitionFromRunnableToSuspended(kWaitingForDebuggerSuspension);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003116 VLOG(jdwp) << " Suspending all threads";
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003117 thread_list->SuspendAllForDebugger();
3118 self->TransitionFromSuspendedToRunnable();
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003119 VLOG(jdwp) << " Resuming event thread to balance the count";
Elliott Hughesd07986f2011-12-06 18:27:45 -08003120 thread_list->Resume(targetThread, true);
3121 }
3122
3123 // Copy the result.
3124 *pResultTag = req->result_tag;
3125 if (IsPrimitiveTag(req->result_tag)) {
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07003126 *pResultValue = req->result_value.GetJ();
Elliott Hughesd07986f2011-12-06 18:27:45 -08003127 } else {
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07003128 *pResultValue = gRegistry->Add(req->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003129 }
3130 *pExceptionId = req->exception;
3131 return req->error;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003132}
3133
3134void Dbg::ExecuteMethod(DebugInvokeReq* pReq) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003135 ScopedObjectAccess soa(Thread::Current());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003136
Elliott Hughes81ff3182012-03-23 20:35:56 -07003137 // We can be called while an exception is pending. We need
Elliott Hughesd07986f2011-12-06 18:27:45 -08003138 // to preserve that across the method invocation.
Ian Rogers62d6c772013-02-27 08:32:07 -08003139 SirtRef<mirror::Object> old_throw_this_object(soa.Self(), NULL);
Brian Carlstromea46f952013-07-30 01:26:50 -07003140 SirtRef<mirror::ArtMethod> old_throw_method(soa.Self(), NULL);
Ian Rogers62d6c772013-02-27 08:32:07 -08003141 SirtRef<mirror::Throwable> old_exception(soa.Self(), NULL);
3142 uint32_t old_throw_dex_pc;
3143 {
3144 ThrowLocation old_throw_location;
3145 mirror::Throwable* old_exception_obj = soa.Self()->GetException(&old_throw_location);
3146 old_throw_this_object.reset(old_throw_location.GetThis());
3147 old_throw_method.reset(old_throw_location.GetMethod());
3148 old_exception.reset(old_exception_obj);
3149 old_throw_dex_pc = old_throw_location.GetDexPc();
3150 soa.Self()->ClearException();
3151 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08003152
3153 // Translate the method through the vtable, unless the debugger wants to suppress it.
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003154 SirtRef<mirror::ArtMethod> m(soa.Self(), pReq->method);
Sebastien Hertzd38667a2013-11-25 15:43:54 +01003155 if ((pReq->options & JDWP::INVOKE_NONVIRTUAL) == 0 && pReq->receiver != NULL) {
Sebastien Hertz83a47d82014-03-20 09:57:40 +01003156 mirror::ArtMethod* actual_method = pReq->klass->FindVirtualMethodForVirtualOrInterface(m.get());
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003157 if (actual_method != m.get()) {
3158 VLOG(jdwp) << "ExecuteMethod translated " << PrettyMethod(m.get()) << " to " << PrettyMethod(actual_method);
3159 m.reset(actual_method);
Elliott Hughes45651fd2012-02-21 15:48:20 -08003160 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08003161 }
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003162 VLOG(jdwp) << "ExecuteMethod " << PrettyMethod(m.get())
Sebastien Hertzd38667a2013-11-25 15:43:54 +01003163 << " receiver=" << pReq->receiver
3164 << " arg_count=" << pReq->arg_count;
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003165 CHECK(m.get() != nullptr);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003166
3167 CHECK_EQ(sizeof(jvalue), sizeof(uint64_t));
3168
Sebastien Hertz83a47d82014-03-20 09:57:40 +01003169 pReq->result_value = InvokeWithJValues(soa, pReq->receiver, soa.EncodeMethod(m.get()),
Ian Rogers53b8b092014-03-13 23:45:53 -07003170 reinterpret_cast<jvalue*>(pReq->arg_values));
Elliott Hughesd07986f2011-12-06 18:27:45 -08003171
Ian Rogers62d6c772013-02-27 08:32:07 -08003172 mirror::Throwable* exception = soa.Self()->GetException(NULL);
3173 soa.Self()->ClearException();
3174 pReq->exception = gRegistry->Add(exception);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003175 pReq->result_tag = BasicTagFromDescriptor(MethodHelper(m.get()).GetShorty());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003176 if (pReq->exception != 0) {
Ian Rogers62d6c772013-02-27 08:32:07 -08003177 VLOG(jdwp) << " JDWP invocation returning with exception=" << exception
3178 << " " << exception->Dump();
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07003179 pReq->result_value.SetJ(0);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003180 } else if (pReq->result_tag == JDWP::JT_OBJECT) {
3181 /* if no exception thrown, examine object result more closely */
Ian Rogers98379392014-02-24 16:53:16 -08003182 JDWP::JdwpTag new_tag = TagFromObject(soa, pReq->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003183 if (new_tag != pReq->result_tag) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003184 VLOG(jdwp) << " JDWP promoted result from " << pReq->result_tag << " to " << new_tag;
Elliott Hughesd07986f2011-12-06 18:27:45 -08003185 pReq->result_tag = new_tag;
3186 }
3187
3188 /*
3189 * Register the object. We don't actually need an ObjectId yet,
3190 * but we do need to be sure that the GC won't move or discard the
3191 * object when we switch out of RUNNING. The ObjectId conversion
3192 * will add the object to the "do not touch" list.
3193 *
3194 * We can't use the "tracked allocation" mechanism here because
3195 * the object is going to be handed off to a different thread.
3196 */
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07003197 gRegistry->Add(pReq->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003198 }
3199
3200 if (old_exception.get() != NULL) {
Ian Rogers62d6c772013-02-27 08:32:07 -08003201 ThrowLocation gc_safe_throw_location(old_throw_this_object.get(), old_throw_method.get(),
3202 old_throw_dex_pc);
3203 soa.Self()->SetException(gc_safe_throw_location, old_exception.get());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003204 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003205}
3206
Elliott Hughesd07986f2011-12-06 18:27:45 -08003207/*
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003208 * "request" contains a full JDWP packet, possibly with multiple chunks. We
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003209 * need to process each, accumulate the replies, and ship the whole thing
3210 * back.
3211 *
3212 * Returns "true" if we have a reply. The reply buffer is newly allocated,
3213 * and includes the chunk type/length, followed by the data.
3214 *
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08003215 * OLD-TODO: we currently assume that the request and reply include a single
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003216 * chunk. If this becomes inconvenient we will need to adapt.
3217 */
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003218bool Dbg::DdmHandlePacket(JDWP::Request& request, uint8_t** pReplyBuf, int* pReplyLen) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003219 Thread* self = Thread::Current();
3220 JNIEnv* env = self->GetJniEnv();
3221
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003222 uint32_t type = request.ReadUnsigned32("type");
3223 uint32_t length = request.ReadUnsigned32("length");
3224
3225 // Create a byte[] corresponding to 'request'.
3226 size_t request_length = request.size();
3227 ScopedLocalRef<jbyteArray> dataArray(env, env->NewByteArray(request_length));
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003228 if (dataArray.get() == NULL) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003229 LOG(WARNING) << "byte[] allocation failed: " << request_length;
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003230 env->ExceptionClear();
3231 return false;
3232 }
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003233 env->SetByteArrayRegion(dataArray.get(), 0, request_length, reinterpret_cast<const jbyte*>(request.data()));
3234 request.Skip(request_length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003235
3236 // Run through and find all chunks. [Currently just find the first.]
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003237 ScopedByteArrayRO contents(env, dataArray.get());
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003238 if (length != request_length) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08003239 LOG(WARNING) << StringPrintf("bad chunk found (len=%u pktLen=%zd)", length, request_length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003240 return false;
3241 }
3242
3243 // Call "private static Chunk dispatch(int type, byte[] data, int offset, int length)".
Elliott Hugheseac76672012-05-24 21:56:51 -07003244 ScopedLocalRef<jobject> chunk(env, env->CallStaticObjectMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
3245 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_dispatch,
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003246 type, dataArray.get(), 0, length));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003247 if (env->ExceptionCheck()) {
3248 LOG(INFO) << StringPrintf("Exception thrown by dispatcher for 0x%08x", type);
3249 env->ExceptionDescribe();
3250 env->ExceptionClear();
3251 return false;
3252 }
3253
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003254 if (chunk.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003255 return false;
3256 }
3257
3258 /*
3259 * Pull the pieces out of the chunk. We copy the results into a
3260 * newly-allocated buffer that the caller can free. We don't want to
3261 * continue using the Chunk object because nothing has a reference to it.
3262 *
3263 * We could avoid this by returning type/data/offset/length and having
3264 * the caller be aware of the object lifetime issues, but that
Elliott Hughes81ff3182012-03-23 20:35:56 -07003265 * integrates the JDWP code more tightly into the rest of the runtime, and doesn't work
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003266 * if we have responses for multiple chunks.
3267 *
3268 * So we're pretty much stuck with copying data around multiple times.
3269 */
Elliott Hugheseac76672012-05-24 21:56:51 -07003270 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 -08003271 jint offset = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_offset);
Elliott Hugheseac76672012-05-24 21:56:51 -07003272 length = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_length);
Elliott Hugheseac76672012-05-24 21:56:51 -07003273 type = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_type);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003274
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003275 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 -07003276 if (length == 0 || replyData.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003277 return false;
3278 }
3279
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003280 const int kChunkHdrLen = 8;
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003281 uint8_t* reply = new uint8_t[length + kChunkHdrLen];
3282 if (reply == NULL) {
3283 LOG(WARNING) << "malloc failed: " << (length + kChunkHdrLen);
3284 return false;
3285 }
Elliott Hughesf7c3b662011-10-27 12:04:56 -07003286 JDWP::Set4BE(reply + 0, type);
3287 JDWP::Set4BE(reply + 4, length);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003288 env->GetByteArrayRegion(replyData.get(), offset, length, reinterpret_cast<jbyte*>(reply + kChunkHdrLen));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003289
3290 *pReplyBuf = reply;
3291 *pReplyLen = length + kChunkHdrLen;
3292
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003293 VLOG(jdwp) << StringPrintf("dvmHandleDdm returning type=%.4s %p len=%d", reinterpret_cast<char*>(reply), reply, length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003294 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003295}
3296
Elliott Hughesa2155262011-11-16 16:26:58 -08003297void Dbg::DdmBroadcast(bool connect) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003298 VLOG(jdwp) << "Broadcasting DDM " << (connect ? "connect" : "disconnect") << "...";
Elliott Hughes47fce012011-10-25 18:37:19 -07003299
3300 Thread* self = Thread::Current();
Ian Rogers50b35e22012-10-04 10:09:15 -07003301 if (self->GetState() != kRunnable) {
3302 LOG(ERROR) << "DDM broadcast in thread state " << self->GetState();
3303 /* try anyway? */
Elliott Hughes47fce012011-10-25 18:37:19 -07003304 }
3305
3306 JNIEnv* env = self->GetJniEnv();
Elliott Hughes47fce012011-10-25 18:37:19 -07003307 jint event = connect ? 1 /*DdmServer.CONNECTED*/ : 2 /*DdmServer.DISCONNECTED*/;
Elliott Hugheseac76672012-05-24 21:56:51 -07003308 env->CallStaticVoidMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
3309 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_broadcast,
3310 event);
Elliott Hughes47fce012011-10-25 18:37:19 -07003311 if (env->ExceptionCheck()) {
3312 LOG(ERROR) << "DdmServer.broadcast " << event << " failed";
3313 env->ExceptionDescribe();
3314 env->ExceptionClear();
3315 }
3316}
3317
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003318void Dbg::DdmConnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08003319 Dbg::DdmBroadcast(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003320}
3321
3322void Dbg::DdmDisconnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08003323 Dbg::DdmBroadcast(false);
Elliott Hughes47fce012011-10-25 18:37:19 -07003324 gDdmThreadNotification = false;
3325}
3326
3327/*
Elliott Hughes82188472011-11-07 18:11:48 -08003328 * Send a notification when a thread starts, stops, or changes its name.
Elliott Hughes47fce012011-10-25 18:37:19 -07003329 *
3330 * Because we broadcast the full set of threads when the notifications are
3331 * first enabled, it's possible for "thread" to be actively executing.
3332 */
Elliott Hughes82188472011-11-07 18:11:48 -08003333void Dbg::DdmSendThreadNotification(Thread* t, uint32_t type) {
Elliott Hughes47fce012011-10-25 18:37:19 -07003334 if (!gDdmThreadNotification) {
3335 return;
3336 }
3337
Elliott Hughes82188472011-11-07 18:11:48 -08003338 if (type == CHUNK_TYPE("THDE")) {
Elliott Hughes47fce012011-10-25 18:37:19 -07003339 uint8_t buf[4];
Ian Rogersd9c4fc92013-10-01 19:45:43 -07003340 JDWP::Set4BE(&buf[0], t->GetThreadId());
Elliott Hughes47fce012011-10-25 18:37:19 -07003341 Dbg::DdmSendChunk(CHUNK_TYPE("THDE"), 4, buf);
Elliott Hughes82188472011-11-07 18:11:48 -08003342 } else {
3343 CHECK(type == CHUNK_TYPE("THCR") || type == CHUNK_TYPE("THNM")) << type;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003344 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003345 SirtRef<mirror::String> name(soa.Self(), t->GetThreadName(soa));
Elliott Hughes82188472011-11-07 18:11:48 -08003346 size_t char_count = (name.get() != NULL) ? name->GetLength() : 0;
jeffhao725a9572012-11-13 18:20:12 -08003347 const jchar* chars = (name.get() != NULL) ? name->GetCharArray()->GetData() : NULL;
Elliott Hughes82188472011-11-07 18:11:48 -08003348
Elliott Hughes21f32d72011-11-09 17:44:13 -08003349 std::vector<uint8_t> bytes;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07003350 JDWP::Append4BE(bytes, t->GetThreadId());
Elliott Hughes545a0642011-11-08 19:10:03 -08003351 JDWP::AppendUtf16BE(bytes, chars, char_count);
Elliott Hughes21f32d72011-11-09 17:44:13 -08003352 CHECK_EQ(bytes.size(), char_count*2 + sizeof(uint32_t)*2);
3353 Dbg::DdmSendChunk(type, bytes);
Elliott Hughes47fce012011-10-25 18:37:19 -07003354 }
3355}
3356
Elliott Hughes47fce012011-10-25 18:37:19 -07003357void Dbg::DdmSetThreadNotification(bool enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003358 // Enable/disable thread notifications.
Elliott Hughes47fce012011-10-25 18:37:19 -07003359 gDdmThreadNotification = enable;
3360 if (enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003361 // Suspend the VM then post thread start notifications for all threads. Threads attaching will
3362 // see a suspension in progress and block until that ends. They then post their own start
3363 // notification.
3364 SuspendVM();
3365 std::list<Thread*> threads;
Ian Rogers50b35e22012-10-04 10:09:15 -07003366 Thread* self = Thread::Current();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003367 {
Ian Rogers50b35e22012-10-04 10:09:15 -07003368 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003369 threads = Runtime::Current()->GetThreadList()->GetList();
3370 }
3371 {
Ian Rogers50b35e22012-10-04 10:09:15 -07003372 ScopedObjectAccess soa(self);
Mathieu Chartier02e25112013-08-14 16:14:24 -07003373 for (Thread* thread : threads) {
3374 Dbg::DdmSendThreadNotification(thread, CHUNK_TYPE("THCR"));
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003375 }
3376 }
3377 ResumeVM();
Elliott Hughes47fce012011-10-25 18:37:19 -07003378 }
3379}
3380
Elliott Hughesa2155262011-11-16 16:26:58 -08003381void Dbg::PostThreadStartOrStop(Thread* t, uint32_t type) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07003382 if (IsDebuggerActive()) {
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07003383 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogerscfaa4552012-11-26 21:00:08 -08003384 JDWP::ObjectId id = gRegistry->Add(t->GetPeer());
Elliott Hughes82188472011-11-07 18:11:48 -08003385 gJdwpState->PostThreadChange(id, type == CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07003386 }
Elliott Hughes82188472011-11-07 18:11:48 -08003387 Dbg::DdmSendThreadNotification(t, type);
Elliott Hughes47fce012011-10-25 18:37:19 -07003388}
3389
3390void Dbg::PostThreadStart(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08003391 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07003392}
3393
3394void Dbg::PostThreadDeath(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08003395 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THDE"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003396}
3397
Elliott Hughes82188472011-11-07 18:11:48 -08003398void Dbg::DdmSendChunk(uint32_t type, size_t byte_count, const uint8_t* buf) {
Elliott Hughes3bb81562011-10-21 18:52:59 -07003399 CHECK(buf != NULL);
3400 iovec vec[1];
3401 vec[0].iov_base = reinterpret_cast<void*>(const_cast<uint8_t*>(buf));
3402 vec[0].iov_len = byte_count;
3403 Dbg::DdmSendChunkV(type, vec, 1);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003404}
3405
Elliott Hughes21f32d72011-11-09 17:44:13 -08003406void Dbg::DdmSendChunk(uint32_t type, const std::vector<uint8_t>& bytes) {
3407 DdmSendChunk(type, bytes.size(), &bytes[0]);
3408}
3409
Brian Carlstromf5293522013-07-19 00:24:00 -07003410void Dbg::DdmSendChunkV(uint32_t type, const iovec* iov, int iov_count) {
Elliott Hughes3bb81562011-10-21 18:52:59 -07003411 if (gJdwpState == NULL) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003412 VLOG(jdwp) << "Debugger thread not active, ignoring DDM send: " << type;
Elliott Hughes3bb81562011-10-21 18:52:59 -07003413 } else {
Elliott Hughescccd84f2011-12-05 16:51:54 -08003414 gJdwpState->DdmSendChunkV(type, iov, iov_count);
Elliott Hughes3bb81562011-10-21 18:52:59 -07003415 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003416}
3417
Elliott Hughes767a1472011-10-26 18:49:02 -07003418int Dbg::DdmHandleHpifChunk(HpifWhen when) {
3419 if (when == HPIF_WHEN_NOW) {
Elliott Hughes7162ad92011-10-27 14:08:42 -07003420 DdmSendHeapInfo(when);
Elliott Hughes767a1472011-10-26 18:49:02 -07003421 return true;
3422 }
3423
3424 if (when != HPIF_WHEN_NEVER && when != HPIF_WHEN_NEXT_GC && when != HPIF_WHEN_EVERY_GC) {
3425 LOG(ERROR) << "invalid HpifWhen value: " << static_cast<int>(when);
3426 return false;
3427 }
3428
3429 gDdmHpifWhen = when;
3430 return true;
3431}
3432
3433bool Dbg::DdmHandleHpsgNhsgChunk(Dbg::HpsgWhen when, Dbg::HpsgWhat what, bool native) {
3434 if (when != HPSG_WHEN_NEVER && when != HPSG_WHEN_EVERY_GC) {
3435 LOG(ERROR) << "invalid HpsgWhen value: " << static_cast<int>(when);
3436 return false;
3437 }
3438
3439 if (what != HPSG_WHAT_MERGED_OBJECTS && what != HPSG_WHAT_DISTINCT_OBJECTS) {
3440 LOG(ERROR) << "invalid HpsgWhat value: " << static_cast<int>(what);
3441 return false;
3442 }
3443
3444 if (native) {
3445 gDdmNhsgWhen = when;
3446 gDdmNhsgWhat = what;
3447 } else {
3448 gDdmHpsgWhen = when;
3449 gDdmHpsgWhat = what;
3450 }
3451 return true;
3452}
3453
Elliott Hughes7162ad92011-10-27 14:08:42 -07003454void Dbg::DdmSendHeapInfo(HpifWhen reason) {
3455 // If there's a one-shot 'when', reset it.
3456 if (reason == gDdmHpifWhen) {
3457 if (gDdmHpifWhen == HPIF_WHEN_NEXT_GC) {
3458 gDdmHpifWhen = HPIF_WHEN_NEVER;
3459 }
3460 }
3461
3462 /*
3463 * Chunk HPIF (client --> server)
3464 *
3465 * Heap Info. General information about the heap,
3466 * suitable for a summary display.
3467 *
3468 * [u4]: number of heaps
3469 *
3470 * For each heap:
3471 * [u4]: heap ID
3472 * [u8]: timestamp in ms since Unix epoch
3473 * [u1]: capture reason (same as 'when' value from server)
3474 * [u4]: max heap size in bytes (-Xmx)
3475 * [u4]: current heap size in bytes
3476 * [u4]: current number of bytes allocated
3477 * [u4]: current number of objects allocated
3478 */
3479 uint8_t heap_count = 1;
Ian Rogers1d54e732013-05-02 21:10:01 -07003480 gc::Heap* heap = Runtime::Current()->GetHeap();
Elliott Hughes21f32d72011-11-09 17:44:13 -08003481 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08003482 JDWP::Append4BE(bytes, heap_count);
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003483 JDWP::Append4BE(bytes, 1); // Heap id (bogus; we only have one heap).
Elliott Hughes545a0642011-11-08 19:10:03 -08003484 JDWP::Append8BE(bytes, MilliTime());
3485 JDWP::Append1BE(bytes, reason);
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003486 JDWP::Append4BE(bytes, heap->GetMaxMemory()); // Max allowed heap size in bytes.
3487 JDWP::Append4BE(bytes, heap->GetTotalMemory()); // Current heap size in bytes.
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08003488 JDWP::Append4BE(bytes, heap->GetBytesAllocated());
3489 JDWP::Append4BE(bytes, heap->GetObjectsAllocated());
Elliott Hughes21f32d72011-11-09 17:44:13 -08003490 CHECK_EQ(bytes.size(), 4U + (heap_count * (4 + 8 + 1 + 4 + 4 + 4 + 4)));
3491 Dbg::DdmSendChunk(CHUNK_TYPE("HPIF"), bytes);
Elliott Hughes767a1472011-10-26 18:49:02 -07003492}
3493
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003494enum HpsgSolidity {
3495 SOLIDITY_FREE = 0,
3496 SOLIDITY_HARD = 1,
3497 SOLIDITY_SOFT = 2,
3498 SOLIDITY_WEAK = 3,
3499 SOLIDITY_PHANTOM = 4,
3500 SOLIDITY_FINALIZABLE = 5,
3501 SOLIDITY_SWEEP = 6,
3502};
3503
3504enum HpsgKind {
3505 KIND_OBJECT = 0,
3506 KIND_CLASS_OBJECT = 1,
3507 KIND_ARRAY_1 = 2,
3508 KIND_ARRAY_2 = 3,
3509 KIND_ARRAY_4 = 4,
3510 KIND_ARRAY_8 = 5,
3511 KIND_UNKNOWN = 6,
3512 KIND_NATIVE = 7,
3513};
3514
3515#define HPSG_PARTIAL (1<<7)
3516#define HPSG_STATE(solidity, kind) ((uint8_t)((((kind) & 0x7) << 3) | ((solidity) & 0x7)))
3517
Ian Rogers30fab402012-01-23 15:43:46 -08003518class HeapChunkContext {
3519 public:
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003520 // Maximum chunk size. Obtain this from the formula:
3521 // (((maximum_heap_size / ALLOCATION_UNIT_SIZE) + 255) / 256) * 2
3522 HeapChunkContext(bool merge, bool native)
Ian Rogers30fab402012-01-23 15:43:46 -08003523 : buf_(16384 - 16),
3524 type_(0),
3525 merge_(merge) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003526 Reset();
3527 if (native) {
Ian Rogers30fab402012-01-23 15:43:46 -08003528 type_ = CHUNK_TYPE("NHSG");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003529 } else {
Ian Rogers30fab402012-01-23 15:43:46 -08003530 type_ = merge ? CHUNK_TYPE("HPSG") : CHUNK_TYPE("HPSO");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003531 }
3532 }
3533
3534 ~HeapChunkContext() {
Ian Rogers30fab402012-01-23 15:43:46 -08003535 if (p_ > &buf_[0]) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003536 Flush();
3537 }
3538 }
3539
3540 void EnsureHeader(const void* chunk_ptr) {
Ian Rogers30fab402012-01-23 15:43:46 -08003541 if (!needHeader_) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003542 return;
3543 }
3544
3545 // Start a new HPSx chunk.
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003546 JDWP::Write4BE(&p_, 1); // Heap id (bogus; we only have one heap).
3547 JDWP::Write1BE(&p_, 8); // Size of allocation unit, in bytes.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003548
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003549 JDWP::Write4BE(&p_, reinterpret_cast<uintptr_t>(chunk_ptr)); // virtual address of segment start.
3550 JDWP::Write4BE(&p_, 0); // offset of this piece (relative to the virtual address).
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003551 // [u4]: length of piece, in allocation units
3552 // 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 -08003553 pieceLenField_ = p_;
3554 JDWP::Write4BE(&p_, 0x55555555);
3555 needHeader_ = false;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003556 }
3557
Ian Rogersb726dcb2012-09-05 08:57:23 -07003558 void Flush() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogersd636b062013-01-18 17:51:18 -08003559 if (pieceLenField_ == NULL) {
3560 // Flush immediately post Reset (maybe back-to-back Flush). Ignore.
3561 CHECK(needHeader_);
3562 return;
3563 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003564 // Patch the "length of piece" field.
Ian Rogers30fab402012-01-23 15:43:46 -08003565 CHECK_LE(&buf_[0], pieceLenField_);
3566 CHECK_LE(pieceLenField_, p_);
3567 JDWP::Set4BE(pieceLenField_, totalAllocationUnits_);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003568
Ian Rogers30fab402012-01-23 15:43:46 -08003569 Dbg::DdmSendChunk(type_, p_ - &buf_[0], &buf_[0]);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003570 Reset();
3571 }
3572
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003573 static void HeapChunkCallback(void* start, void* end, size_t used_bytes, void* arg)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003574 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_,
3575 Locks::mutator_lock_) {
Ian Rogers30fab402012-01-23 15:43:46 -08003576 reinterpret_cast<HeapChunkContext*>(arg)->HeapChunkCallback(start, end, used_bytes);
Elliott Hughesa2155262011-11-16 16:26:58 -08003577 }
3578
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003579 private:
Elliott Hughesa2155262011-11-16 16:26:58 -08003580 enum { ALLOCATION_UNIT_SIZE = 8 };
3581
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003582 void Reset() {
Ian Rogers30fab402012-01-23 15:43:46 -08003583 p_ = &buf_[0];
Ian Rogers15bf2d32012-08-28 17:33:04 -07003584 startOfNextMemoryChunk_ = NULL;
Ian Rogers30fab402012-01-23 15:43:46 -08003585 totalAllocationUnits_ = 0;
3586 needHeader_ = true;
3587 pieceLenField_ = NULL;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003588 }
3589
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003590 void HeapChunkCallback(void* start, void* /*end*/, size_t used_bytes)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003591 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_,
3592 Locks::mutator_lock_) {
Ian Rogers30fab402012-01-23 15:43:46 -08003593 // Note: heap call backs cannot manipulate the heap upon which they are crawling, care is taken
3594 // in the following code not to allocate memory, by ensuring buf_ is of the correct size
Ian Rogers15bf2d32012-08-28 17:33:04 -07003595 if (used_bytes == 0) {
3596 if (start == NULL) {
3597 // Reset for start of new heap.
3598 startOfNextMemoryChunk_ = NULL;
3599 Flush();
3600 }
3601 // Only process in use memory so that free region information
3602 // also includes dlmalloc book keeping.
Elliott Hughesa2155262011-11-16 16:26:58 -08003603 return;
Elliott Hughesa2155262011-11-16 16:26:58 -08003604 }
3605
Ian Rogers15bf2d32012-08-28 17:33:04 -07003606 /* If we're looking at the native heap, we'll just return
3607 * (SOLIDITY_HARD, KIND_NATIVE) for all allocated chunks
3608 */
3609 bool native = type_ == CHUNK_TYPE("NHSG");
3610
3611 if (startOfNextMemoryChunk_ != NULL) {
3612 // Transmit any pending free memory. Native free memory of
3613 // over kMaxFreeLen could be because of the use of mmaps, so
3614 // don't report. If not free memory then start a new segment.
3615 bool flush = true;
3616 if (start > startOfNextMemoryChunk_) {
3617 const size_t kMaxFreeLen = 2 * kPageSize;
3618 void* freeStart = startOfNextMemoryChunk_;
3619 void* freeEnd = start;
Brian Carlstrom2d888622013-07-18 17:02:00 -07003620 size_t freeLen = reinterpret_cast<char*>(freeEnd) - reinterpret_cast<char*>(freeStart);
Ian Rogers15bf2d32012-08-28 17:33:04 -07003621 if (!native || freeLen < kMaxFreeLen) {
3622 AppendChunk(HPSG_STATE(SOLIDITY_FREE, 0), freeStart, freeLen);
3623 flush = false;
3624 }
3625 }
3626 if (flush) {
3627 startOfNextMemoryChunk_ = NULL;
3628 Flush();
3629 }
3630 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08003631 mirror::Object* obj = reinterpret_cast<mirror::Object*>(start);
Elliott Hughesa2155262011-11-16 16:26:58 -08003632
3633 // Determine the type of this chunk.
3634 // OLD-TODO: if context.merge, see if this chunk is different from the last chunk.
3635 // If it's the same, we should combine them.
Ian Rogers15bf2d32012-08-28 17:33:04 -07003636 uint8_t state = ExamineObject(obj, native);
3637 // dlmalloc's chunk header is 2 * sizeof(size_t), but if the previous chunk is in use for an
3638 // allocation then the first sizeof(size_t) may belong to it.
3639 const size_t dlMallocOverhead = sizeof(size_t);
3640 AppendChunk(state, start, used_bytes + dlMallocOverhead);
Brian Carlstrom2d888622013-07-18 17:02:00 -07003641 startOfNextMemoryChunk_ = reinterpret_cast<char*>(start) + used_bytes + dlMallocOverhead;
Ian Rogers15bf2d32012-08-28 17:33:04 -07003642 }
Elliott Hughesa2155262011-11-16 16:26:58 -08003643
Ian Rogers15bf2d32012-08-28 17:33:04 -07003644 void AppendChunk(uint8_t state, void* ptr, size_t length)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003645 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07003646 // Make sure there's enough room left in the buffer.
3647 // We need to use two bytes for every fractional 256 allocation units used by the chunk plus
3648 // 17 bytes for any header.
3649 size_t needed = (((length/ALLOCATION_UNIT_SIZE + 255) / 256) * 2) + 17;
3650 size_t bytesLeft = buf_.size() - (size_t)(p_ - &buf_[0]);
3651 if (bytesLeft < needed) {
3652 Flush();
3653 }
3654
3655 bytesLeft = buf_.size() - (size_t)(p_ - &buf_[0]);
3656 if (bytesLeft < needed) {
3657 LOG(WARNING) << "Chunk is too big to transmit (chunk_len=" << length << ", "
3658 << needed << " bytes)";
3659 return;
3660 }
3661 EnsureHeader(ptr);
Elliott Hughesa2155262011-11-16 16:26:58 -08003662 // Write out the chunk description.
Ian Rogers15bf2d32012-08-28 17:33:04 -07003663 length /= ALLOCATION_UNIT_SIZE; // Convert to allocation units.
3664 totalAllocationUnits_ += length;
3665 while (length > 256) {
Ian Rogers30fab402012-01-23 15:43:46 -08003666 *p_++ = state | HPSG_PARTIAL;
3667 *p_++ = 255; // length - 1
Ian Rogers15bf2d32012-08-28 17:33:04 -07003668 length -= 256;
Elliott Hughesa2155262011-11-16 16:26:58 -08003669 }
Ian Rogers30fab402012-01-23 15:43:46 -08003670 *p_++ = state;
Ian Rogers15bf2d32012-08-28 17:33:04 -07003671 *p_++ = length - 1;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003672 }
3673
Ian Rogersef7d42f2014-01-06 12:55:46 -08003674 uint8_t ExamineObject(mirror::Object* o, bool is_native_heap)
3675 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Elliott Hughesa2155262011-11-16 16:26:58 -08003676 if (o == NULL) {
3677 return HPSG_STATE(SOLIDITY_FREE, 0);
3678 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003679
Elliott Hughesa2155262011-11-16 16:26:58 -08003680 // It's an allocated chunk. Figure out what it is.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003681
Elliott Hughesa2155262011-11-16 16:26:58 -08003682 // If we're looking at the native heap, we'll just return
3683 // (SOLIDITY_HARD, KIND_NATIVE) for all allocated chunks.
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003684 if (is_native_heap) {
Elliott Hughesa2155262011-11-16 16:26:58 -08003685 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
3686 }
3687
Ian Rogers5bfa60f2012-09-02 21:17:56 -07003688 if (!Runtime::Current()->GetHeap()->IsLiveObjectLocked(o)) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07003689 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003690 }
3691
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003692 mirror::Class* c = o->GetClass();
Elliott Hughesa2155262011-11-16 16:26:58 -08003693 if (c == NULL) {
3694 // The object was probably just created but hasn't been initialized yet.
3695 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
3696 }
3697
Mathieu Chartier590fee92013-09-13 13:46:47 -07003698 if (!Runtime::Current()->GetHeap()->IsValidObjectAddress(c)) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07003699 LOG(ERROR) << "Invalid class for managed heap object: " << o << " " << c;
Elliott Hughesa2155262011-11-16 16:26:58 -08003700 return HPSG_STATE(SOLIDITY_HARD, KIND_UNKNOWN);
3701 }
3702
3703 if (c->IsClassClass()) {
3704 return HPSG_STATE(SOLIDITY_HARD, KIND_CLASS_OBJECT);
3705 }
3706
3707 if (c->IsArrayClass()) {
3708 if (o->IsObjectArray()) {
3709 return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
3710 }
3711 switch (c->GetComponentSize()) {
3712 case 1: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_1);
3713 case 2: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_2);
3714 case 4: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
3715 case 8: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_8);
3716 }
3717 }
3718
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003719 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
3720 }
3721
Ian Rogers30fab402012-01-23 15:43:46 -08003722 std::vector<uint8_t> buf_;
3723 uint8_t* p_;
3724 uint8_t* pieceLenField_;
Ian Rogers15bf2d32012-08-28 17:33:04 -07003725 void* startOfNextMemoryChunk_;
Ian Rogers30fab402012-01-23 15:43:46 -08003726 size_t totalAllocationUnits_;
3727 uint32_t type_;
3728 bool merge_;
3729 bool needHeader_;
3730
Elliott Hughesa2155262011-11-16 16:26:58 -08003731 DISALLOW_COPY_AND_ASSIGN(HeapChunkContext);
3732};
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003733
3734void Dbg::DdmSendHeapSegments(bool native) {
3735 Dbg::HpsgWhen when;
3736 Dbg::HpsgWhat what;
3737 if (!native) {
3738 when = gDdmHpsgWhen;
3739 what = gDdmHpsgWhat;
3740 } else {
3741 when = gDdmNhsgWhen;
3742 what = gDdmNhsgWhat;
3743 }
3744 if (when == HPSG_WHEN_NEVER) {
3745 return;
3746 }
3747
3748 // Figure out what kind of chunks we'll be sending.
3749 CHECK(what == HPSG_WHAT_MERGED_OBJECTS || what == HPSG_WHAT_DISTINCT_OBJECTS) << static_cast<int>(what);
3750
3751 // First, send a heap start chunk.
3752 uint8_t heap_id[4];
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003753 JDWP::Set4BE(&heap_id[0], 1); // Heap id (bogus; we only have one heap).
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003754 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHST") : CHUNK_TYPE("HPST"), sizeof(heap_id), heap_id);
3755
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07003756 Thread* self = Thread::Current();
3757
3758 // To allow the Walk/InspectAll() below to exclusively-lock the
3759 // mutator lock, temporarily release the shared access to the
3760 // mutator lock here by transitioning to the suspended state.
3761 Locks::mutator_lock_->AssertSharedHeld(self);
3762 self->TransitionFromRunnableToSuspended(kSuspended);
3763
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003764 // Send a series of heap segment chunks.
Elliott Hughesa2155262011-11-16 16:26:58 -08003765 HeapChunkContext context((what == HPSG_WHAT_MERGED_OBJECTS), native);
3766 if (native) {
Ian Rogers1d54e732013-05-02 21:10:01 -07003767 dlmalloc_inspect_all(HeapChunkContext::HeapChunkCallback, &context);
Elliott Hughesa2155262011-11-16 16:26:58 -08003768 } else {
Ian Rogers1d54e732013-05-02 21:10:01 -07003769 gc::Heap* heap = Runtime::Current()->GetHeap();
3770 const std::vector<gc::space::ContinuousSpace*>& spaces = heap->GetContinuousSpaces();
Ian Rogers62d6c772013-02-27 08:32:07 -08003771 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Ian Rogers1d54e732013-05-02 21:10:01 -07003772 typedef std::vector<gc::space::ContinuousSpace*>::const_iterator It;
3773 for (It cur = spaces.begin(), end = spaces.end(); cur != end; ++cur) {
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07003774 if ((*cur)->IsMallocSpace()) {
3775 (*cur)->AsMallocSpace()->Walk(HeapChunkContext::HeapChunkCallback, &context);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07003776 }
3777 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07003778 // Walk the large objects, these are not in the AllocSpace.
3779 heap->GetLargeObjectsSpace()->Walk(HeapChunkContext::HeapChunkCallback, &context);
Elliott Hughesa2155262011-11-16 16:26:58 -08003780 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003781
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07003782 // Shared-lock the mutator lock back.
3783 self->TransitionFromSuspendedToRunnable();
3784 Locks::mutator_lock_->AssertSharedHeld(self);
3785
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003786 // Finally, send a heap end chunk.
3787 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHEN") : CHUNK_TYPE("HPEN"), sizeof(heap_id), heap_id);
Elliott Hughes767a1472011-10-26 18:49:02 -07003788}
3789
Elliott Hughesb1a58792013-07-11 18:10:58 -07003790static size_t GetAllocTrackerMax() {
3791#ifdef HAVE_ANDROID_OS
3792 // Check whether there's a system property overriding the number of records.
3793 const char* propertyName = "dalvik.vm.allocTrackerMax";
3794 char allocRecordMaxString[PROPERTY_VALUE_MAX];
3795 if (property_get(propertyName, allocRecordMaxString, "") > 0) {
3796 char* end;
3797 size_t value = strtoul(allocRecordMaxString, &end, 10);
3798 if (*end != '\0') {
Ruben Brunk3e47a742013-09-09 17:56:07 -07003799 LOG(ERROR) << "Ignoring " << propertyName << " '" << allocRecordMaxString
3800 << "' --- invalid";
Elliott Hughesb1a58792013-07-11 18:10:58 -07003801 return kDefaultNumAllocRecords;
3802 }
3803 if (!IsPowerOfTwo(value)) {
Ruben Brunk3e47a742013-09-09 17:56:07 -07003804 LOG(ERROR) << "Ignoring " << propertyName << " '" << allocRecordMaxString
3805 << "' --- not power of two";
Elliott Hughesb1a58792013-07-11 18:10:58 -07003806 return kDefaultNumAllocRecords;
3807 }
3808 return value;
3809 }
3810#endif
3811 return kDefaultNumAllocRecords;
3812}
3813
Elliott Hughes545a0642011-11-08 19:10:03 -08003814void Dbg::SetAllocTrackingEnabled(bool enabled) {
Ian Rogers719d1a32014-03-06 12:13:39 -08003815 MutexLock mu(Thread::Current(), *alloc_tracker_lock_);
Elliott Hughes545a0642011-11-08 19:10:03 -08003816 if (enabled) {
3817 if (recent_allocation_records_ == NULL) {
Ian Rogers719d1a32014-03-06 12:13:39 -08003818 alloc_record_max_ = GetAllocTrackerMax();
3819 LOG(INFO) << "Enabling alloc tracker (" << alloc_record_max_ << " entries of "
Elliott Hughesb1a58792013-07-11 18:10:58 -07003820 << kMaxAllocRecordStackDepth << " frames, taking "
Ian Rogers719d1a32014-03-06 12:13:39 -08003821 << PrettySize(sizeof(AllocRecord) * alloc_record_max_) << ")";
3822 alloc_record_head_ = alloc_record_count_ = 0;
3823 recent_allocation_records_ = new AllocRecord[alloc_record_max_];
Elliott Hughes545a0642011-11-08 19:10:03 -08003824 CHECK(recent_allocation_records_ != NULL);
3825 }
Ian Rogersfa824272013-11-05 16:12:57 -08003826 Runtime::Current()->GetInstrumentation()->InstrumentQuickAllocEntryPoints();
Elliott Hughes545a0642011-11-08 19:10:03 -08003827 } else {
Ian Rogersfa824272013-11-05 16:12:57 -08003828 Runtime::Current()->GetInstrumentation()->UninstrumentQuickAllocEntryPoints();
Elliott Hughes545a0642011-11-08 19:10:03 -08003829 delete[] recent_allocation_records_;
3830 recent_allocation_records_ = NULL;
3831 }
3832}
3833
Ian Rogers0399dde2012-06-06 17:09:28 -07003834struct AllocRecordStackVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -08003835 AllocRecordStackVisitor(Thread* thread, AllocRecord* record)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003836 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08003837 : StackVisitor(thread, NULL), record(record), depth(0) {}
Elliott Hughes545a0642011-11-08 19:10:03 -08003838
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003839 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
3840 // annotalysis.
3841 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughes545a0642011-11-08 19:10:03 -08003842 if (depth >= kMaxAllocRecordStackDepth) {
Elliott Hughes530fa002012-03-12 11:44:49 -07003843 return false;
Elliott Hughes545a0642011-11-08 19:10:03 -08003844 }
Brian Carlstromea46f952013-07-30 01:26:50 -07003845 mirror::ArtMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07003846 if (!m->IsRuntimeMethod()) {
3847 record->stack[depth].method = m;
3848 record->stack[depth].dex_pc = GetDexPc();
Elliott Hughes530fa002012-03-12 11:44:49 -07003849 ++depth;
Elliott Hughes545a0642011-11-08 19:10:03 -08003850 }
Elliott Hughes530fa002012-03-12 11:44:49 -07003851 return true;
Elliott Hughes545a0642011-11-08 19:10:03 -08003852 }
3853
3854 ~AllocRecordStackVisitor() {
3855 // Clear out any unused stack trace elements.
3856 for (; depth < kMaxAllocRecordStackDepth; ++depth) {
3857 record->stack[depth].method = NULL;
Ian Rogers0399dde2012-06-06 17:09:28 -07003858 record->stack[depth].dex_pc = 0;
Elliott Hughes545a0642011-11-08 19:10:03 -08003859 }
3860 }
3861
3862 AllocRecord* record;
3863 size_t depth;
3864};
3865
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003866void Dbg::RecordAllocation(mirror::Class* type, size_t byte_count) {
Elliott Hughes545a0642011-11-08 19:10:03 -08003867 Thread* self = Thread::Current();
3868 CHECK(self != NULL);
3869
Ian Rogers719d1a32014-03-06 12:13:39 -08003870 MutexLock mu(self, *alloc_tracker_lock_);
Elliott Hughes545a0642011-11-08 19:10:03 -08003871 if (recent_allocation_records_ == NULL) {
3872 return;
3873 }
3874
3875 // Advance and clip.
Ian Rogers719d1a32014-03-06 12:13:39 -08003876 if (++alloc_record_head_ == alloc_record_max_) {
3877 alloc_record_head_ = 0;
Elliott Hughes545a0642011-11-08 19:10:03 -08003878 }
3879
3880 // Fill in the basics.
Ian Rogers719d1a32014-03-06 12:13:39 -08003881 AllocRecord* record = &recent_allocation_records_[alloc_record_head_];
Elliott Hughes545a0642011-11-08 19:10:03 -08003882 record->type = type;
3883 record->byte_count = byte_count;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07003884 record->thin_lock_id = self->GetThreadId();
Elliott Hughes545a0642011-11-08 19:10:03 -08003885
3886 // Fill in the stack trace.
Ian Rogers7a22fa62013-01-23 12:16:16 -08003887 AllocRecordStackVisitor visitor(self, record);
Ian Rogers0399dde2012-06-06 17:09:28 -07003888 visitor.WalkStack();
Elliott Hughes545a0642011-11-08 19:10:03 -08003889
Ian Rogers719d1a32014-03-06 12:13:39 -08003890 if (alloc_record_count_ < alloc_record_max_) {
3891 ++alloc_record_count_;
Elliott Hughes545a0642011-11-08 19:10:03 -08003892 }
3893}
3894
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003895// Returns the index of the head element.
3896//
3897// We point at the most-recently-written record, so if gAllocRecordCount is 1
3898// we want to use the current element. Take "head+1" and subtract count
3899// from it.
3900//
3901// We need to handle underflow in our circular buffer, so we add
Elliott Hughesb1a58792013-07-11 18:10:58 -07003902// gAllocRecordMax and then mask it back down.
Ian Rogers719d1a32014-03-06 12:13:39 -08003903size_t Dbg::HeadIndex() {
3904 return (Dbg::alloc_record_head_ + 1 + Dbg::alloc_record_max_ - Dbg::alloc_record_count_) &
3905 (Dbg::alloc_record_max_ - 1);
Elliott Hughes545a0642011-11-08 19:10:03 -08003906}
3907
3908void Dbg::DumpRecentAllocations() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003909 ScopedObjectAccess soa(Thread::Current());
Ian Rogers719d1a32014-03-06 12:13:39 -08003910 MutexLock mu(soa.Self(), *alloc_tracker_lock_);
Elliott Hughes545a0642011-11-08 19:10:03 -08003911 if (recent_allocation_records_ == NULL) {
3912 LOG(INFO) << "Not recording tracked allocations";
3913 return;
3914 }
3915
3916 // "i" is the head of the list. We want to start at the end of the
3917 // list and move forward to the tail.
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003918 size_t i = HeadIndex();
Ian Rogers719d1a32014-03-06 12:13:39 -08003919 size_t count = alloc_record_count_;
Elliott Hughes545a0642011-11-08 19:10:03 -08003920
Ian Rogers719d1a32014-03-06 12:13:39 -08003921 LOG(INFO) << "Tracked allocations, (head=" << alloc_record_head_ << " count=" << count << ")";
Elliott Hughes545a0642011-11-08 19:10:03 -08003922 while (count--) {
3923 AllocRecord* record = &recent_allocation_records_[i];
3924
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003925 LOG(INFO) << StringPrintf(" Thread %-2d %6zd bytes ", record->thin_lock_id, record->byte_count)
Elliott Hughes545a0642011-11-08 19:10:03 -08003926 << PrettyClass(record->type);
3927
3928 for (size_t stack_frame = 0; stack_frame < kMaxAllocRecordStackDepth; ++stack_frame) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08003929 mirror::ArtMethod* m = record->stack[stack_frame].method;
Elliott Hughes545a0642011-11-08 19:10:03 -08003930 if (m == NULL) {
3931 break;
3932 }
3933 LOG(INFO) << " " << PrettyMethod(m) << " line " << record->stack[stack_frame].LineNumber();
3934 }
3935
3936 // pause periodically to help logcat catch up
3937 if ((count % 5) == 0) {
3938 usleep(40000);
3939 }
3940
Ian Rogers719d1a32014-03-06 12:13:39 -08003941 i = (i + 1) & (alloc_record_max_ - 1);
Elliott Hughes545a0642011-11-08 19:10:03 -08003942 }
3943}
3944
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -07003945void Dbg::UpdateObjectPointers(IsMarkedCallback* callback, void* arg) {
Ian Rogers719d1a32014-03-06 12:13:39 -08003946 if (recent_allocation_records_ != nullptr) {
3947 MutexLock mu(Thread::Current(), *alloc_tracker_lock_);
3948 size_t i = HeadIndex();
3949 size_t count = alloc_record_count_;
3950 while (count--) {
3951 AllocRecord* record = &recent_allocation_records_[i];
3952 DCHECK(record != nullptr);
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -07003953 record->UpdateObjectPointers(callback, arg);
Ian Rogers719d1a32014-03-06 12:13:39 -08003954 i = (i + 1) & (alloc_record_max_ - 1);
Mathieu Chartier412c7fc2014-02-07 12:18:39 -08003955 }
3956 }
3957 if (gRegistry != nullptr) {
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -07003958 gRegistry->UpdateObjectPointers(callback, arg);
Mathieu Chartier412c7fc2014-02-07 12:18:39 -08003959 }
3960}
3961
3962void Dbg::AllowNewObjectRegistryObjects() {
3963 if (gRegistry != nullptr) {
3964 gRegistry->AllowNewObjects();
3965 }
3966}
3967
3968void Dbg::DisallowNewObjectRegistryObjects() {
3969 if (gRegistry != nullptr) {
3970 gRegistry->DisallowNewObjects();
3971 }
3972}
3973
Elliott Hughes545a0642011-11-08 19:10:03 -08003974class StringTable {
3975 public:
3976 StringTable() {
3977 }
3978
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003979 void Add(const char* s) {
Elliott Hughes545a0642011-11-08 19:10:03 -08003980 table_.insert(s);
3981 }
3982
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003983 size_t IndexOf(const char* s) const {
Mathieu Chartier02e25112013-08-14 16:14:24 -07003984 auto it = table_.find(s);
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003985 if (it == table_.end()) {
3986 LOG(FATAL) << "IndexOf(\"" << s << "\") failed";
3987 }
3988 return std::distance(table_.begin(), it);
Elliott Hughes545a0642011-11-08 19:10:03 -08003989 }
3990
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003991 size_t Size() const {
Elliott Hughes545a0642011-11-08 19:10:03 -08003992 return table_.size();
3993 }
3994
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003995 void WriteTo(std::vector<uint8_t>& bytes) const {
Mathieu Chartier02e25112013-08-14 16:14:24 -07003996 for (const std::string& str : table_) {
3997 const char* s = str.c_str();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003998 size_t s_len = CountModifiedUtf8Chars(s);
3999 UniquePtr<uint16_t> s_utf16(new uint16_t[s_len]);
4000 ConvertModifiedUtf8ToUtf16(s_utf16.get(), s);
4001 JDWP::AppendUtf16BE(bytes, s_utf16.get(), s_len);
Elliott Hughes545a0642011-11-08 19:10:03 -08004002 }
4003 }
4004
4005 private:
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07004006 std::set<std::string> table_;
Elliott Hughes545a0642011-11-08 19:10:03 -08004007 DISALLOW_COPY_AND_ASSIGN(StringTable);
4008};
4009
4010/*
4011 * The data we send to DDMS contains everything we have recorded.
4012 *
4013 * Message header (all values big-endian):
4014 * (1b) message header len (to allow future expansion); includes itself
4015 * (1b) entry header len
4016 * (1b) stack frame len
4017 * (2b) number of entries
4018 * (4b) offset to string table from start of message
4019 * (2b) number of class name strings
4020 * (2b) number of method name strings
4021 * (2b) number of source file name strings
4022 * For each entry:
4023 * (4b) total allocation size
Elliott Hughes221229c2013-01-08 18:17:50 -08004024 * (2b) thread id
Elliott Hughes545a0642011-11-08 19:10:03 -08004025 * (2b) allocated object's class name index
4026 * (1b) stack depth
4027 * For each stack frame:
4028 * (2b) method's class name
4029 * (2b) method name
4030 * (2b) method source file
4031 * (2b) line number, clipped to 32767; -2 if native; -1 if no source
4032 * (xb) class name strings
4033 * (xb) method name strings
4034 * (xb) source file strings
4035 *
4036 * As with other DDM traffic, strings are sent as a 4-byte length
4037 * followed by UTF-16 data.
4038 *
4039 * We send up 16-bit unsigned indexes into string tables. In theory there
Elliott Hughesb1a58792013-07-11 18:10:58 -07004040 * can be (kMaxAllocRecordStackDepth * gAllocRecordMax) unique strings in
Elliott Hughes545a0642011-11-08 19:10:03 -08004041 * each table, but in practice there should be far fewer.
4042 *
4043 * The chief reason for using a string table here is to keep the size of
4044 * the DDMS message to a minimum. This is partly to make the protocol
4045 * efficient, but also because we have to form the whole thing up all at
4046 * once in a memory buffer.
4047 *
4048 * We use separate string tables for class names, method names, and source
4049 * files to keep the indexes small. There will generally be no overlap
4050 * between the contents of these tables.
4051 */
4052jbyteArray Dbg::GetRecentAllocations() {
4053 if (false) {
4054 DumpRecentAllocations();
4055 }
4056
Ian Rogers50b35e22012-10-04 10:09:15 -07004057 Thread* self = Thread::Current();
Elliott Hughes545a0642011-11-08 19:10:03 -08004058 std::vector<uint8_t> bytes;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004059 {
Ian Rogers719d1a32014-03-06 12:13:39 -08004060 MutexLock mu(self, *alloc_tracker_lock_);
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004061 //
4062 // Part 1: generate string tables.
4063 //
4064 StringTable class_names;
4065 StringTable method_names;
4066 StringTable filenames;
Elliott Hughes545a0642011-11-08 19:10:03 -08004067
Ian Rogers719d1a32014-03-06 12:13:39 -08004068 int count = alloc_record_count_;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004069 int idx = HeadIndex();
4070 while (count--) {
4071 AllocRecord* record = &recent_allocation_records_[idx];
Elliott Hughes545a0642011-11-08 19:10:03 -08004072
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004073 class_names.Add(ClassHelper(record->type).GetDescriptor());
Elliott Hughes545a0642011-11-08 19:10:03 -08004074
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004075 MethodHelper mh;
4076 for (size_t i = 0; i < kMaxAllocRecordStackDepth; i++) {
Brian Carlstromea46f952013-07-30 01:26:50 -07004077 mirror::ArtMethod* m = record->stack[i].method;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004078 if (m != NULL) {
4079 mh.ChangeMethod(m);
4080 class_names.Add(mh.GetDeclaringClassDescriptor());
4081 method_names.Add(mh.GetName());
4082 filenames.Add(mh.GetDeclaringClassSourceFile());
4083 }
4084 }
Elliott Hughes545a0642011-11-08 19:10:03 -08004085
Ian Rogers719d1a32014-03-06 12:13:39 -08004086 idx = (idx + 1) & (alloc_record_max_ - 1);
Elliott Hughes545a0642011-11-08 19:10:03 -08004087 }
4088
Ian Rogers719d1a32014-03-06 12:13:39 -08004089 LOG(INFO) << "allocation records: " << alloc_record_count_;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004090
4091 //
4092 // Part 2: Generate the output and store it in the buffer.
4093 //
4094
4095 // (1b) message header len (to allow future expansion); includes itself
4096 // (1b) entry header len
4097 // (1b) stack frame len
4098 const int kMessageHeaderLen = 15;
4099 const int kEntryHeaderLen = 9;
4100 const int kStackFrameLen = 8;
4101 JDWP::Append1BE(bytes, kMessageHeaderLen);
4102 JDWP::Append1BE(bytes, kEntryHeaderLen);
4103 JDWP::Append1BE(bytes, kStackFrameLen);
4104
4105 // (2b) number of entries
4106 // (4b) offset to string table from start of message
4107 // (2b) number of class name strings
4108 // (2b) number of method name strings
4109 // (2b) number of source file name strings
Ian Rogers719d1a32014-03-06 12:13:39 -08004110 JDWP::Append2BE(bytes, alloc_record_count_);
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004111 size_t string_table_offset = bytes.size();
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004112 JDWP::Append4BE(bytes, 0); // We'll patch this later...
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004113 JDWP::Append2BE(bytes, class_names.Size());
4114 JDWP::Append2BE(bytes, method_names.Size());
4115 JDWP::Append2BE(bytes, filenames.Size());
4116
Ian Rogers719d1a32014-03-06 12:13:39 -08004117 count = alloc_record_count_;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004118 idx = HeadIndex();
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004119 while (count--) {
4120 // For each entry:
4121 // (4b) total allocation size
4122 // (2b) thread id
4123 // (2b) allocated object's class name index
4124 // (1b) stack depth
4125 AllocRecord* record = &recent_allocation_records_[idx];
4126 size_t stack_depth = record->GetDepth();
Mathieu Chartier590fee92013-09-13 13:46:47 -07004127 ClassHelper kh(record->type);
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004128 size_t allocated_object_class_name_index = class_names.IndexOf(kh.GetDescriptor());
4129 JDWP::Append4BE(bytes, record->byte_count);
4130 JDWP::Append2BE(bytes, record->thin_lock_id);
4131 JDWP::Append2BE(bytes, allocated_object_class_name_index);
4132 JDWP::Append1BE(bytes, stack_depth);
4133
4134 MethodHelper mh;
4135 for (size_t stack_frame = 0; stack_frame < stack_depth; ++stack_frame) {
4136 // For each stack frame:
4137 // (2b) method's class name
4138 // (2b) method name
4139 // (2b) method source file
4140 // (2b) line number, clipped to 32767; -2 if native; -1 if no source
4141 mh.ChangeMethod(record->stack[stack_frame].method);
4142 size_t class_name_index = class_names.IndexOf(mh.GetDeclaringClassDescriptor());
4143 size_t method_name_index = method_names.IndexOf(mh.GetName());
4144 size_t file_name_index = filenames.IndexOf(mh.GetDeclaringClassSourceFile());
4145 JDWP::Append2BE(bytes, class_name_index);
4146 JDWP::Append2BE(bytes, method_name_index);
4147 JDWP::Append2BE(bytes, file_name_index);
4148 JDWP::Append2BE(bytes, record->stack[stack_frame].LineNumber());
4149 }
4150
Ian Rogers719d1a32014-03-06 12:13:39 -08004151 idx = (idx + 1) & (alloc_record_max_ - 1);
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004152 }
4153
4154 // (xb) class name strings
4155 // (xb) method name strings
4156 // (xb) source file strings
4157 JDWP::Set4BE(&bytes[string_table_offset], bytes.size());
4158 class_names.WriteTo(bytes);
4159 method_names.WriteTo(bytes);
4160 filenames.WriteTo(bytes);
Elliott Hughes545a0642011-11-08 19:10:03 -08004161 }
Ian Rogers50b35e22012-10-04 10:09:15 -07004162 JNIEnv* env = self->GetJniEnv();
Elliott Hughes545a0642011-11-08 19:10:03 -08004163 jbyteArray result = env->NewByteArray(bytes.size());
4164 if (result != NULL) {
4165 env->SetByteArrayRegion(result, 0, bytes.size(), reinterpret_cast<const jbyte*>(&bytes[0]));
4166 }
4167 return result;
4168}
4169
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004170} // namespace art