blob: c18d5c6e0182e2f48ab9033cf54eb9cf8d65ff95 [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.
203struct MethodInstrumentationRequest {
204 bool deoptimize;
205
206 // Method for selective deoptimization. NULL means full deoptimization.
207 mirror::ArtMethod* method;
208
209 MethodInstrumentationRequest(bool deoptimize, mirror::ArtMethod* method)
210 : deoptimize(deoptimize), method(method) {}
211};
212// TODO we need to visit associated methods as roots.
213static std::vector<MethodInstrumentationRequest> gDeoptimizationRequests GUARDED_BY(Locks::deoptimization_lock_);
214
215// Breakpoints.
jeffhao09bfc6a2012-12-11 18:11:43 -0800216static std::vector<Breakpoint> gBreakpoints GUARDED_BY(Locks::breakpoint_lock_);
Elliott Hughes86964332012-02-15 19:37:42 -0800217
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700218void DebugInvokeReq::VisitRoots(RootCallback* callback, void* arg, uint32_t tid,
219 RootType root_type) {
220 if (receiver != nullptr) {
221 callback(&receiver, arg, tid, root_type);
222 }
223 if (thread != nullptr) {
224 callback(&thread, arg, tid, root_type);
225 }
226 if (klass != nullptr) {
227 callback(reinterpret_cast<mirror::Object**>(&klass), arg, tid, root_type);
228 }
229 if (method != nullptr) {
230 callback(reinterpret_cast<mirror::Object**>(&method), arg, tid, root_type);
231 }
232}
233
234void SingleStepControl::VisitRoots(RootCallback* callback, void* arg, uint32_t tid,
235 RootType root_type) {
236 if (method != nullptr) {
237 callback(reinterpret_cast<mirror::Object**>(&method), arg, tid, root_type);
238 }
239}
240
Brian Carlstromea46f952013-07-30 01:26:50 -0700241static bool IsBreakpoint(const mirror::ArtMethod* m, uint32_t dex_pc)
jeffhao09bfc6a2012-12-11 18:11:43 -0800242 LOCKS_EXCLUDED(Locks::breakpoint_lock_)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700243 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
jeffhao09bfc6a2012-12-11 18:11:43 -0800244 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100245 for (size_t i = 0, e = gBreakpoints.size(); i < e; ++i) {
Elliott Hughesa656a0f2012-02-21 18:03:44 -0800246 if (gBreakpoints[i].method == m && gBreakpoints[i].dex_pc == dex_pc) {
Elliott Hughes86964332012-02-15 19:37:42 -0800247 VLOG(jdwp) << "Hit breakpoint #" << i << ": " << gBreakpoints[i];
248 return true;
249 }
250 }
251 return false;
252}
253
Sebastien Hertz52d131d2014-03-13 16:17:40 +0100254static bool IsSuspendedForDebugger(ScopedObjectAccessUnchecked& soa, Thread* thread)
255 LOCKS_EXCLUDED(Locks::thread_suspend_count_lock_) {
Elliott Hughes9e0c1752013-01-09 14:02:58 -0800256 MutexLock mu(soa.Self(), *Locks::thread_suspend_count_lock_);
257 // A thread may be suspended for GC; in this code, we really want to know whether
258 // there's a debugger suspension active.
259 return thread->IsSuspended() && thread->GetDebugSuspendCount() > 0;
260}
261
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800262static mirror::Array* DecodeArray(JDWP::RefTypeId id, JDWP::JdwpError& status)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700263 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800264 mirror::Object* o = gRegistry->Get<mirror::Object*>(id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800265 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800266 status = JDWP::ERR_INVALID_OBJECT;
267 return NULL;
268 }
269 if (!o->IsArrayInstance()) {
270 status = JDWP::ERR_INVALID_ARRAY;
271 return NULL;
272 }
273 status = JDWP::ERR_NONE;
274 return o->AsArray();
275}
276
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800277static mirror::Class* DecodeClass(JDWP::RefTypeId id, JDWP::JdwpError& status)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700278 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800279 mirror::Object* o = gRegistry->Get<mirror::Object*>(id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800280 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800281 status = JDWP::ERR_INVALID_OBJECT;
282 return NULL;
283 }
284 if (!o->IsClass()) {
285 status = JDWP::ERR_INVALID_CLASS;
286 return NULL;
287 }
288 status = JDWP::ERR_NONE;
289 return o->AsClass();
290}
291
Elliott Hughes221229c2013-01-08 18:17:50 -0800292static JDWP::JdwpError DecodeThread(ScopedObjectAccessUnchecked& soa, JDWP::ObjectId thread_id, Thread*& thread)
jeffhaoa77f0f62012-12-05 17:19:31 -0800293 EXCLUSIVE_LOCKS_REQUIRED(Locks::thread_list_lock_)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700294 LOCKS_EXCLUDED(Locks::thread_suspend_count_lock_)
295 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800296 mirror::Object* thread_peer = gRegistry->Get<mirror::Object*>(thread_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800297 if (thread_peer == NULL || thread_peer == ObjectRegistry::kInvalidObject) {
Elliott Hughes221229c2013-01-08 18:17:50 -0800298 // This isn't even an object.
299 return JDWP::ERR_INVALID_OBJECT;
Elliott Hughes436e3722012-02-17 20:01:47 -0800300 }
Elliott Hughes221229c2013-01-08 18:17:50 -0800301
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800302 mirror::Class* java_lang_Thread = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_Thread);
Elliott Hughes221229c2013-01-08 18:17:50 -0800303 if (!java_lang_Thread->IsAssignableFrom(thread_peer->GetClass())) {
304 // This isn't a thread.
305 return JDWP::ERR_INVALID_THREAD;
306 }
307
308 thread = Thread::FromManagedThread(soa, thread_peer);
309 if (thread == NULL) {
310 // This is a java.lang.Thread without a Thread*. Must be a zombie.
311 return JDWP::ERR_THREAD_NOT_ALIVE;
312 }
313 return JDWP::ERR_NONE;
Elliott Hughes436e3722012-02-17 20:01:47 -0800314}
315
Elliott Hughes24437992011-11-30 14:49:33 -0800316static JDWP::JdwpTag BasicTagFromDescriptor(const char* descriptor) {
317 // JDWP deliberately uses the descriptor characters' ASCII values for its enum.
318 // Note that by "basic" we mean that we don't get more specific than JT_OBJECT.
319 return static_cast<JDWP::JdwpTag>(descriptor[0]);
320}
321
Ian Rogers98379392014-02-24 16:53:16 -0800322static JDWP::JdwpTag TagFromClass(const ScopedObjectAccessUnchecked& soa, mirror::Class* c)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700323 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes86b00102011-12-05 17:54:26 -0800324 CHECK(c != NULL);
Elliott Hughes24437992011-11-30 14:49:33 -0800325 if (c->IsArrayClass()) {
326 return JDWP::JT_ARRAY;
327 }
Elliott Hughes24437992011-11-30 14:49:33 -0800328 if (c->IsStringClass()) {
329 return JDWP::JT_STRING;
Elliott Hughes24437992011-11-30 14:49:33 -0800330 }
Ian Rogers98379392014-02-24 16:53:16 -0800331 if (c->IsClassClass()) {
332 return JDWP::JT_CLASS_OBJECT;
333 }
334 {
335 mirror::Class* thread_class = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_Thread);
336 if (thread_class->IsAssignableFrom(c)) {
337 return JDWP::JT_THREAD;
338 }
339 }
340 {
341 mirror::Class* thread_group_class =
342 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_ThreadGroup);
343 if (thread_group_class->IsAssignableFrom(c)) {
344 return JDWP::JT_THREAD_GROUP;
345 }
346 }
347 {
348 mirror::Class* class_loader_class =
349 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_ClassLoader);
350 if (class_loader_class->IsAssignableFrom(c)) {
351 return JDWP::JT_CLASS_LOADER;
352 }
353 }
354 return JDWP::JT_OBJECT;
Elliott Hughes24437992011-11-30 14:49:33 -0800355}
356
357/*
358 * Objects declared to hold Object might actually hold a more specific
359 * type. The debugger may take a special interest in these (e.g. it
360 * wants to display the contents of Strings), so we want to return an
361 * appropriate tag.
362 *
363 * Null objects are tagged JT_OBJECT.
364 */
Ian Rogers98379392014-02-24 16:53:16 -0800365static JDWP::JdwpTag TagFromObject(const ScopedObjectAccessUnchecked& soa, mirror::Object* o)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700366 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers98379392014-02-24 16:53:16 -0800367 return (o == NULL) ? JDWP::JT_OBJECT : TagFromClass(soa, o->GetClass());
Elliott Hughes24437992011-11-30 14:49:33 -0800368}
369
370static bool IsPrimitiveTag(JDWP::JdwpTag tag) {
371 switch (tag) {
372 case JDWP::JT_BOOLEAN:
373 case JDWP::JT_BYTE:
374 case JDWP::JT_CHAR:
375 case JDWP::JT_FLOAT:
376 case JDWP::JT_DOUBLE:
377 case JDWP::JT_INT:
378 case JDWP::JT_LONG:
379 case JDWP::JT_SHORT:
380 case JDWP::JT_VOID:
381 return true;
382 default:
383 return false;
384 }
385}
386
Elliott Hughes3bb81562011-10-21 18:52:59 -0700387/*
388 * Handle one of the JDWP name/value pairs.
389 *
390 * JDWP options are:
391 * help: if specified, show help message and bail
392 * transport: may be dt_socket or dt_shmem
393 * address: for dt_socket, "host:port", or just "port" when listening
394 * server: if "y", wait for debugger to attach; if "n", attach to debugger
395 * timeout: how long to wait for debugger to connect / listen
396 *
397 * Useful with server=n (these aren't supported yet):
398 * onthrow=<exception-name>: connect to debugger when exception thrown
399 * onuncaught=y|n: connect to debugger when uncaught exception thrown
400 * launch=<command-line>: launch the debugger itself
401 *
402 * The "transport" option is required, as is "address" if server=n.
403 */
404static bool ParseJdwpOption(const std::string& name, const std::string& value) {
405 if (name == "transport") {
406 if (value == "dt_socket") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700407 gJdwpOptions.transport = JDWP::kJdwpTransportSocket;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700408 } else if (value == "dt_android_adb") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700409 gJdwpOptions.transport = JDWP::kJdwpTransportAndroidAdb;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700410 } else {
411 LOG(ERROR) << "JDWP transport not supported: " << value;
412 return false;
413 }
414 } else if (name == "server") {
415 if (value == "n") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700416 gJdwpOptions.server = false;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700417 } else if (value == "y") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700418 gJdwpOptions.server = true;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700419 } else {
420 LOG(ERROR) << "JDWP option 'server' must be 'y' or 'n'";
421 return false;
422 }
423 } else if (name == "suspend") {
424 if (value == "n") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700425 gJdwpOptions.suspend = false;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700426 } else if (value == "y") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700427 gJdwpOptions.suspend = true;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700428 } else {
429 LOG(ERROR) << "JDWP option 'suspend' must be 'y' or 'n'";
430 return false;
431 }
432 } else if (name == "address") {
433 /* this is either <port> or <host>:<port> */
434 std::string port_string;
Elliott Hughes376a7a02011-10-24 18:35:55 -0700435 gJdwpOptions.host.clear();
Elliott Hughes3bb81562011-10-21 18:52:59 -0700436 std::string::size_type colon = value.find(':');
437 if (colon != std::string::npos) {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700438 gJdwpOptions.host = value.substr(0, colon);
Elliott Hughes3bb81562011-10-21 18:52:59 -0700439 port_string = value.substr(colon + 1);
440 } else {
441 port_string = value;
442 }
443 if (port_string.empty()) {
444 LOG(ERROR) << "JDWP address missing port: " << value;
445 return false;
446 }
447 char* end;
Elliott Hughesba8eee12012-01-24 20:25:24 -0800448 uint64_t port = strtoul(port_string.c_str(), &end, 10);
449 if (*end != '\0' || port > 0xffff) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700450 LOG(ERROR) << "JDWP address has junk in port field: " << value;
451 return false;
452 }
Elliott Hughes376a7a02011-10-24 18:35:55 -0700453 gJdwpOptions.port = port;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700454 } else if (name == "launch" || name == "onthrow" || name == "oncaught" || name == "timeout") {
455 /* valid but unsupported */
456 LOG(INFO) << "Ignoring JDWP option '" << name << "'='" << value << "'";
457 } else {
458 LOG(INFO) << "Ignoring unrecognized JDWP option '" << name << "'='" << value << "'";
459 }
460
461 return true;
462}
463
464/*
465 * Parse the latter half of a -Xrunjdwp/-agentlib:jdwp= string, e.g.:
466 * "transport=dt_socket,address=8000,server=y,suspend=n"
467 */
468bool Dbg::ParseJdwpOptions(const std::string& options) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800469 VLOG(jdwp) << "ParseJdwpOptions: " << options;
Elliott Hughes47fce012011-10-25 18:37:19 -0700470
Elliott Hughes3bb81562011-10-21 18:52:59 -0700471 std::vector<std::string> pairs;
472 Split(options, ',', pairs);
473
474 for (size_t i = 0; i < pairs.size(); ++i) {
475 std::string::size_type equals = pairs[i].find('=');
476 if (equals == std::string::npos) {
477 LOG(ERROR) << "Can't parse JDWP option '" << pairs[i] << "' in '" << options << "'";
478 return false;
479 }
480 ParseJdwpOption(pairs[i].substr(0, equals), pairs[i].substr(equals + 1));
481 }
482
Elliott Hughes376a7a02011-10-24 18:35:55 -0700483 if (gJdwpOptions.transport == JDWP::kJdwpTransportUnknown) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700484 LOG(ERROR) << "Must specify JDWP transport: " << options;
485 }
Elliott Hughes376a7a02011-10-24 18:35:55 -0700486 if (!gJdwpOptions.server && (gJdwpOptions.host.empty() || gJdwpOptions.port == 0)) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700487 LOG(ERROR) << "Must specify JDWP host and port when server=n: " << options;
488 return false;
489 }
490
491 gJdwpConfigured = true;
492 return true;
493}
494
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700495void Dbg::StartJdwp() {
Elliott Hughesc0f09332012-03-26 13:27:06 -0700496 if (!gJdwpAllowed || !IsJdwpConfigured()) {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700497 // No JDWP for you!
498 return;
499 }
500
Ian Rogers719d1a32014-03-06 12:13:39 -0800501 CHECK(gRegistry == nullptr);
Elliott Hughes475fc232011-10-25 15:00:35 -0700502 gRegistry = new ObjectRegistry;
503
Ian Rogers719d1a32014-03-06 12:13:39 -0800504 alloc_tracker_lock_ = new Mutex("AllocTracker lock");
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700505 // Init JDWP if the debugger is enabled. This may connect out to a
506 // debugger, passively listen for a debugger, or block waiting for a
507 // debugger.
Elliott Hughes376a7a02011-10-24 18:35:55 -0700508 gJdwpState = JDWP::JdwpState::Create(&gJdwpOptions);
509 if (gJdwpState == NULL) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -0800510 // We probably failed because some other process has the port already, which means that
511 // if we don't abort the user is likely to think they're talking to us when they're actually
512 // talking to that other process.
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800513 LOG(FATAL) << "Debugger thread failed to initialize";
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700514 }
515
516 // If a debugger has already attached, send the "welcome" message.
517 // This may cause us to suspend all threads.
Elliott Hughes376a7a02011-10-24 18:35:55 -0700518 if (gJdwpState->IsActive()) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700519 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes376a7a02011-10-24 18:35:55 -0700520 if (!gJdwpState->PostVMStart()) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800521 LOG(WARNING) << "Failed to post 'start' message to debugger";
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700522 }
523 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700524}
525
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700526void Dbg::VisitRoots(RootCallback* callback, void* arg) {
527 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
528 for (Breakpoint& bp : gBreakpoints) {
529 bp.VisitRoots(callback, arg);
530 }
531}
532
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700533void Dbg::StopJdwp() {
Sebastien Hertz0376e6b2014-02-06 18:12:59 +0100534 // Prevent the JDWP thread from processing JDWP incoming packets after we close the connection.
535 Disposed();
Elliott Hughes376a7a02011-10-24 18:35:55 -0700536 delete gJdwpState;
Ian Rogers719d1a32014-03-06 12:13:39 -0800537 gJdwpState = nullptr;
Elliott Hughes475fc232011-10-25 15:00:35 -0700538 delete gRegistry;
Ian Rogers719d1a32014-03-06 12:13:39 -0800539 gRegistry = nullptr;
540 delete alloc_tracker_lock_;
541 alloc_tracker_lock_ = nullptr;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700542}
543
Elliott Hughes767a1472011-10-26 18:49:02 -0700544void Dbg::GcDidFinish() {
545 if (gDdmHpifWhen != HPIF_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700546 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes81ff3182012-03-23 20:35:56 -0700547 LOG(DEBUG) << "Sending heap info to DDM";
Elliott Hughes7162ad92011-10-27 14:08:42 -0700548 DdmSendHeapInfo(gDdmHpifWhen);
Elliott Hughes767a1472011-10-26 18:49:02 -0700549 }
550 if (gDdmHpsgWhen != HPSG_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700551 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes81ff3182012-03-23 20:35:56 -0700552 LOG(DEBUG) << "Dumping heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700553 DdmSendHeapSegments(false);
Elliott Hughes767a1472011-10-26 18:49:02 -0700554 }
555 if (gDdmNhsgWhen != HPSG_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700556 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes767a1472011-10-26 18:49:02 -0700557 LOG(DEBUG) << "Dumping native heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700558 DdmSendHeapSegments(true);
Elliott Hughes767a1472011-10-26 18:49:02 -0700559 }
560}
561
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700562void Dbg::SetJdwpAllowed(bool allowed) {
563 gJdwpAllowed = allowed;
564}
565
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700566DebugInvokeReq* Dbg::GetInvokeReq() {
Elliott Hughes475fc232011-10-25 15:00:35 -0700567 return Thread::Current()->GetInvokeReq();
568}
569
570Thread* Dbg::GetDebugThread() {
571 return (gJdwpState != NULL) ? gJdwpState->GetDebugThread() : NULL;
572}
573
574void Dbg::ClearWaitForEventThread() {
575 gJdwpState->ClearWaitForEventThread();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700576}
577
578void Dbg::Connected() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700579 CHECK(!gDebuggerConnected);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800580 VLOG(jdwp) << "JDWP has attached";
Elliott Hughes3bb81562011-10-21 18:52:59 -0700581 gDebuggerConnected = true;
Elliott Hughes86964332012-02-15 19:37:42 -0800582 gDisposed = false;
583}
584
585void Dbg::Disposed() {
586 gDisposed = true;
587}
588
589bool Dbg::IsDisposed() {
590 return gDisposed;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700591}
592
Elliott Hughesa2155262011-11-16 16:26:58 -0800593void Dbg::GoActive() {
594 // Enable all debugging features, including scans for breakpoints.
595 // This is a no-op if we're already active.
596 // Only called from the JDWP handler thread.
597 if (gDebuggerActive) {
598 return;
599 }
600
Elliott Hughesc0f09332012-03-26 13:27:06 -0700601 {
602 // TODO: dalvik only warned if there were breakpoints left over. clear in Dbg::Disconnected?
jeffhao09bfc6a2012-12-11 18:11:43 -0800603 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Elliott Hughesc0f09332012-03-26 13:27:06 -0700604 CHECK_EQ(gBreakpoints.size(), 0U);
605 }
Elliott Hughesa2155262011-11-16 16:26:58 -0800606
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100607 {
608 MutexLock mu(Thread::Current(), *Locks::deoptimization_lock_);
609 CHECK_EQ(gDeoptimizationRequests.size(), 0U);
610 }
611
Ian Rogers62d6c772013-02-27 08:32:07 -0800612 Runtime* runtime = Runtime::Current();
613 runtime->GetThreadList()->SuspendAll();
614 Thread* self = Thread::Current();
615 ThreadState old_state = self->SetStateUnsafe(kRunnable);
616 CHECK_NE(old_state, kRunnable);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100617 runtime->GetInstrumentation()->EnableDeoptimization();
Ian Rogers62d6c772013-02-27 08:32:07 -0800618 runtime->GetInstrumentation()->AddListener(&gDebugInstrumentationListener,
619 instrumentation::Instrumentation::kMethodEntered |
620 instrumentation::Instrumentation::kMethodExited |
Jeff Hao14dd5a82013-04-11 10:23:36 -0700621 instrumentation::Instrumentation::kDexPcMoved |
622 instrumentation::Instrumentation::kExceptionCaught);
Elliott Hughesa2155262011-11-16 16:26:58 -0800623 gDebuggerActive = true;
Ian Rogers62d6c772013-02-27 08:32:07 -0800624 CHECK_EQ(self->SetStateUnsafe(old_state), kRunnable);
625 runtime->GetThreadList()->ResumeAll();
626
627 LOG(INFO) << "Debugger is active";
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700628}
629
630void Dbg::Disconnected() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700631 CHECK(gDebuggerConnected);
632
Elliott Hughesc0f09332012-03-26 13:27:06 -0700633 LOG(INFO) << "Debugger is no longer active";
Elliott Hughes234ab152011-10-26 14:02:26 -0700634
Ian Rogers62d6c772013-02-27 08:32:07 -0800635 // Suspend all threads and exclusively acquire the mutator lock. Set the state of the thread
636 // to kRunnable to avoid scoped object access transitions. Remove the debugger as a listener
637 // and clear the object registry.
638 Runtime* runtime = Runtime::Current();
639 runtime->GetThreadList()->SuspendAll();
640 Thread* self = Thread::Current();
641 ThreadState old_state = self->SetStateUnsafe(kRunnable);
Sebastien Hertzaaea7342014-02-25 15:10:04 +0100642
643 // Debugger may not be active at this point.
644 if (gDebuggerActive) {
645 {
646 // Since we're going to disable deoptimization, we clear the deoptimization requests queue.
647 // This prevents us from having any pending deoptimization request when the debugger attaches
648 // to us again while no event has been requested yet.
649 MutexLock mu(Thread::Current(), *Locks::deoptimization_lock_);
650 gDeoptimizationRequests.clear();
651 }
652 runtime->GetInstrumentation()->RemoveListener(&gDebugInstrumentationListener,
653 instrumentation::Instrumentation::kMethodEntered |
654 instrumentation::Instrumentation::kMethodExited |
655 instrumentation::Instrumentation::kDexPcMoved |
656 instrumentation::Instrumentation::kExceptionCaught);
657 runtime->GetInstrumentation()->DisableDeoptimization();
658 gDebuggerActive = false;
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100659 }
Elliott Hughes234ab152011-10-26 14:02:26 -0700660 gRegistry->Clear();
661 gDebuggerConnected = false;
Ian Rogers62d6c772013-02-27 08:32:07 -0800662 CHECK_EQ(self->SetStateUnsafe(old_state), kRunnable);
663 runtime->GetThreadList()->ResumeAll();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700664}
665
Elliott Hughesc0f09332012-03-26 13:27:06 -0700666bool Dbg::IsDebuggerActive() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700667 return gDebuggerActive;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700668}
669
Elliott Hughesc0f09332012-03-26 13:27:06 -0700670bool Dbg::IsJdwpConfigured() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700671 return gJdwpConfigured;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700672}
673
674int64_t Dbg::LastDebuggerActivity() {
Elliott Hughesca951522011-12-05 12:01:32 -0800675 return gJdwpState->LastDebuggerActivity();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700676}
677
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700678void Dbg::UndoDebuggerSuspensions() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700679 Runtime::Current()->GetThreadList()->UndoDebuggerSuspensions();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700680}
681
Elliott Hughes88d63092013-01-09 09:55:54 -0800682std::string Dbg::GetClassName(JDWP::RefTypeId class_id) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800683 mirror::Object* o = gRegistry->Get<mirror::Object*>(class_id);
Elliott Hughes436e3722012-02-17 20:01:47 -0800684 if (o == NULL) {
685 return "NULL";
686 }
Elliott Hughes64f574f2013-02-20 14:57:12 -0800687 if (o == ObjectRegistry::kInvalidObject) {
Elliott Hughes88d63092013-01-09 09:55:54 -0800688 return StringPrintf("invalid object %p", reinterpret_cast<void*>(class_id));
Elliott Hughes436e3722012-02-17 20:01:47 -0800689 }
690 if (!o->IsClass()) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700691 return StringPrintf("non-class %p", o); // This is only used for debugging output anyway.
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800692 }
Elliott Hughesc308a5d2012-02-16 17:12:06 -0800693 return DescriptorToName(ClassHelper(o->AsClass()).GetDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700694}
695
Elliott Hughes88d63092013-01-09 09:55:54 -0800696JDWP::JdwpError Dbg::GetClassObject(JDWP::RefTypeId id, JDWP::ObjectId& class_object_id) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800697 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800698 mirror::Class* c = DecodeClass(id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -0800699 if (c == NULL) {
700 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800701 }
Elliott Hughes88d63092013-01-09 09:55:54 -0800702 class_object_id = gRegistry->Add(c);
Elliott Hughes436e3722012-02-17 20:01:47 -0800703 return JDWP::ERR_NONE;
Elliott Hughes86964332012-02-15 19:37:42 -0800704}
705
Elliott Hughes88d63092013-01-09 09:55:54 -0800706JDWP::JdwpError Dbg::GetSuperclass(JDWP::RefTypeId id, JDWP::RefTypeId& superclass_id) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800707 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800708 mirror::Class* c = DecodeClass(id, status);
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800709 if (c == NULL) {
710 return status;
711 }
712 if (c->IsInterface()) {
713 // http://code.google.com/p/android/issues/detail?id=20856
Elliott Hughes88d63092013-01-09 09:55:54 -0800714 superclass_id = 0;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800715 } else {
Elliott Hughes88d63092013-01-09 09:55:54 -0800716 superclass_id = gRegistry->Add(c->GetSuperClass());
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800717 }
718 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700719}
720
Elliott Hughes436e3722012-02-17 20:01:47 -0800721JDWP::JdwpError Dbg::GetClassLoader(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800722 mirror::Object* o = gRegistry->Get<mirror::Object*>(id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800723 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800724 return JDWP::ERR_INVALID_OBJECT;
725 }
726 expandBufAddObjectId(pReply, gRegistry->Add(o->GetClass()->GetClassLoader()));
727 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700728}
729
Elliott Hughes436e3722012-02-17 20:01:47 -0800730JDWP::JdwpError Dbg::GetModifiers(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) {
731 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800732 mirror::Class* c = DecodeClass(id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -0800733 if (c == NULL) {
734 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800735 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800736
737 uint32_t access_flags = c->GetAccessFlags() & kAccJavaFlagsMask;
738
Yevgeny Roubande34eea2014-02-15 01:06:03 +0700739 // Set ACC_SUPER. Dex files don't contain this flag but only classes are supposed to have it set,
740 // not interfaces.
Elliott Hughes436e3722012-02-17 20:01:47 -0800741 // Class.getModifiers doesn't return it, but JDWP does, so we set it here.
Yevgeny Roubande34eea2014-02-15 01:06:03 +0700742 if ((access_flags & kAccInterface) == 0) {
743 access_flags |= kAccSuper;
744 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800745
746 expandBufAdd4BE(pReply, access_flags);
747
748 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700749}
750
Elliott Hughesf327e072013-01-09 16:01:26 -0800751JDWP::JdwpError Dbg::GetMonitorInfo(JDWP::ObjectId object_id, JDWP::ExpandBuf* reply)
752 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800753 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800754 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughesf327e072013-01-09 16:01:26 -0800755 return JDWP::ERR_INVALID_OBJECT;
756 }
757
758 // Ensure all threads are suspended while we read objects' lock words.
759 Thread* self = Thread::Current();
Sebastien Hertz54263242014-03-19 18:16:50 +0100760 CHECK_EQ(self->GetState(), kRunnable);
761 self->TransitionFromRunnableToSuspended(kSuspended);
762 Runtime::Current()->GetThreadList()->SuspendAll();
Elliott Hughesf327e072013-01-09 16:01:26 -0800763
764 MonitorInfo monitor_info(o);
765
Sebastien Hertz54263242014-03-19 18:16:50 +0100766 Runtime::Current()->GetThreadList()->ResumeAll();
767 self->TransitionFromSuspendedToRunnable();
Elliott Hughesf327e072013-01-09 16:01:26 -0800768
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700769 if (monitor_info.owner_ != NULL) {
770 expandBufAddObjectId(reply, gRegistry->Add(monitor_info.owner_->GetPeer()));
Elliott Hughesf327e072013-01-09 16:01:26 -0800771 } else {
772 expandBufAddObjectId(reply, gRegistry->Add(NULL));
773 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700774 expandBufAdd4BE(reply, monitor_info.entry_count_);
775 expandBufAdd4BE(reply, monitor_info.waiters_.size());
776 for (size_t i = 0; i < monitor_info.waiters_.size(); ++i) {
777 expandBufAddObjectId(reply, gRegistry->Add(monitor_info.waiters_[i]->GetPeer()));
Elliott Hughesf327e072013-01-09 16:01:26 -0800778 }
779 return JDWP::ERR_NONE;
780}
781
Elliott Hughes734b8c62013-01-11 15:32:45 -0800782JDWP::JdwpError Dbg::GetOwnedMonitors(JDWP::ObjectId thread_id,
783 std::vector<JDWP::ObjectId>& monitors,
Sebastien Hertz52d131d2014-03-13 16:17:40 +0100784 std::vector<uint32_t>& stack_depths) {
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800785 ScopedObjectAccessUnchecked soa(Thread::Current());
786 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
787 Thread* thread;
788 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
789 if (error != JDWP::ERR_NONE) {
790 return error;
791 }
792 if (!IsSuspendedForDebugger(soa, thread)) {
793 return JDWP::ERR_THREAD_NOT_SUSPENDED;
794 }
795
796 struct OwnedMonitorVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -0800797 OwnedMonitorVisitor(Thread* thread, Context* context)
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800798 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -0800799 : StackVisitor(thread, context), current_stack_depth(0) {}
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800800
801 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
802 // annotalysis.
803 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
804 if (!GetMethod()->IsRuntimeMethod()) {
805 Monitor::VisitLocks(this, AppendOwnedMonitors, this);
Elliott Hughes734b8c62013-01-11 15:32:45 -0800806 ++current_stack_depth;
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800807 }
808 return true;
809 }
810
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800811 static void AppendOwnedMonitors(mirror::Object* owned_monitor, void* arg) {
Ian Rogers7a22fa62013-01-23 12:16:16 -0800812 OwnedMonitorVisitor* visitor = reinterpret_cast<OwnedMonitorVisitor*>(arg);
Elliott Hughes734b8c62013-01-11 15:32:45 -0800813 visitor->monitors.push_back(owned_monitor);
814 visitor->stack_depths.push_back(visitor->current_stack_depth);
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800815 }
816
Elliott Hughes734b8c62013-01-11 15:32:45 -0800817 size_t current_stack_depth;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800818 std::vector<mirror::Object*> monitors;
Elliott Hughes734b8c62013-01-11 15:32:45 -0800819 std::vector<uint32_t> stack_depths;
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800820 };
Ian Rogers7a22fa62013-01-23 12:16:16 -0800821 UniquePtr<Context> context(Context::Create());
822 OwnedMonitorVisitor visitor(thread, context.get());
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800823 visitor.WalkStack();
824
825 for (size_t i = 0; i < visitor.monitors.size(); ++i) {
826 monitors.push_back(gRegistry->Add(visitor.monitors[i]));
Elliott Hughes734b8c62013-01-11 15:32:45 -0800827 stack_depths.push_back(visitor.stack_depths[i]);
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800828 }
829
830 return JDWP::ERR_NONE;
831}
832
Sebastien Hertz52d131d2014-03-13 16:17:40 +0100833JDWP::JdwpError Dbg::GetContendedMonitor(JDWP::ObjectId thread_id,
834 JDWP::ObjectId& contended_monitor) {
Elliott Hughesf9501702013-01-11 11:22:27 -0800835 ScopedObjectAccessUnchecked soa(Thread::Current());
836 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
837 Thread* thread;
838 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
839 if (error != JDWP::ERR_NONE) {
840 return error;
841 }
842 if (!IsSuspendedForDebugger(soa, thread)) {
843 return JDWP::ERR_THREAD_NOT_SUSPENDED;
844 }
845
846 contended_monitor = gRegistry->Add(Monitor::GetContendedMonitor(thread));
847
848 return JDWP::ERR_NONE;
849}
850
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800851JDWP::JdwpError Dbg::GetInstanceCounts(const std::vector<JDWP::RefTypeId>& class_ids,
852 std::vector<uint64_t>& counts)
853 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800854 gc::Heap* heap = Runtime::Current()->GetHeap();
855 heap->CollectGarbage(false);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800856 std::vector<mirror::Class*> classes;
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800857 counts.clear();
858 for (size_t i = 0; i < class_ids.size(); ++i) {
859 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800860 mirror::Class* c = DecodeClass(class_ids[i], status);
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800861 if (c == NULL) {
862 return status;
863 }
864 classes.push_back(c);
865 counts.push_back(0);
866 }
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800867 heap->CountInstances(classes, false, &counts[0]);
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800868 return JDWP::ERR_NONE;
869}
870
Elliott Hughes3b78c942013-01-15 17:35:41 -0800871JDWP::JdwpError Dbg::GetInstances(JDWP::RefTypeId class_id, int32_t max_count, std::vector<JDWP::ObjectId>& instances)
872 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800873 gc::Heap* heap = Runtime::Current()->GetHeap();
874 // We only want reachable instances, so do a GC.
875 heap->CollectGarbage(false);
Elliott Hughes3b78c942013-01-15 17:35:41 -0800876 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800877 mirror::Class* c = DecodeClass(class_id, status);
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800878 if (c == nullptr) {
Elliott Hughes3b78c942013-01-15 17:35:41 -0800879 return status;
880 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800881 std::vector<mirror::Object*> raw_instances;
Elliott Hughes3b78c942013-01-15 17:35:41 -0800882 Runtime::Current()->GetHeap()->GetInstances(c, max_count, raw_instances);
883 for (size_t i = 0; i < raw_instances.size(); ++i) {
884 instances.push_back(gRegistry->Add(raw_instances[i]));
885 }
886 return JDWP::ERR_NONE;
887}
888
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800889JDWP::JdwpError Dbg::GetReferringObjects(JDWP::ObjectId object_id, int32_t max_count,
890 std::vector<JDWP::ObjectId>& referring_objects)
891 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800892 gc::Heap* heap = Runtime::Current()->GetHeap();
893 heap->CollectGarbage(false);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800894 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800895 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800896 return JDWP::ERR_INVALID_OBJECT;
897 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800898 std::vector<mirror::Object*> raw_instances;
Mathieu Chartier412c7fc2014-02-07 12:18:39 -0800899 heap->GetReferringObjects(o, max_count, raw_instances);
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800900 for (size_t i = 0; i < raw_instances.size(); ++i) {
901 referring_objects.push_back(gRegistry->Add(raw_instances[i]));
902 }
903 return JDWP::ERR_NONE;
904}
905
Elliott Hughes64f574f2013-02-20 14:57:12 -0800906JDWP::JdwpError Dbg::DisableCollection(JDWP::ObjectId object_id)
907 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Sebastien Hertze96060a2013-12-11 12:06:28 +0100908 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
909 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
910 return JDWP::ERR_INVALID_OBJECT;
911 }
Elliott Hughes64f574f2013-02-20 14:57:12 -0800912 gRegistry->DisableCollection(object_id);
913 return JDWP::ERR_NONE;
914}
915
916JDWP::JdwpError Dbg::EnableCollection(JDWP::ObjectId object_id)
917 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Sebastien Hertze96060a2013-12-11 12:06:28 +0100918 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
919 // Unlike DisableCollection, JDWP specs do not state an invalid object causes an error. The RI
920 // also ignores these cases and never return an error. However it's not obvious why this command
921 // should behave differently from DisableCollection and IsCollected commands. So let's be more
922 // strict and return an error if this happens.
923 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
924 return JDWP::ERR_INVALID_OBJECT;
925 }
Elliott Hughes64f574f2013-02-20 14:57:12 -0800926 gRegistry->EnableCollection(object_id);
927 return JDWP::ERR_NONE;
928}
929
930JDWP::JdwpError Dbg::IsCollected(JDWP::ObjectId object_id, bool& is_collected)
931 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Sebastien Hertz65637eb2014-01-10 17:40:02 +0100932 if (object_id == 0) {
933 // Null object id is invalid.
Sebastien Hertze96060a2013-12-11 12:06:28 +0100934 return JDWP::ERR_INVALID_OBJECT;
935 }
Sebastien Hertz65637eb2014-01-10 17:40:02 +0100936 // JDWP specs state an INVALID_OBJECT error is returned if the object ID is not valid. However
937 // the RI seems to ignore this and assume object has been collected.
938 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
939 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
940 is_collected = true;
941 } else {
942 is_collected = gRegistry->IsCollected(object_id);
943 }
Elliott Hughes64f574f2013-02-20 14:57:12 -0800944 return JDWP::ERR_NONE;
945}
946
947void Dbg::DisposeObject(JDWP::ObjectId object_id, uint32_t reference_count)
948 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
949 gRegistry->DisposeObject(object_id, reference_count);
950}
951
Elliott Hughes88d63092013-01-09 09:55:54 -0800952JDWP::JdwpError Dbg::GetReflectedType(JDWP::RefTypeId class_id, JDWP::ExpandBuf* pReply) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800953 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800954 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -0800955 if (c == NULL) {
956 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800957 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800958
959 expandBufAdd1(pReply, c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS);
Elliott Hughes88d63092013-01-09 09:55:54 -0800960 expandBufAddRefTypeId(pReply, class_id);
Elliott Hughes436e3722012-02-17 20:01:47 -0800961 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700962}
963
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800964void Dbg::GetClassList(std::vector<JDWP::RefTypeId>& classes) {
Elliott Hughesa2155262011-11-16 16:26:58 -0800965 // Get the complete list of reference classes (i.e. all classes except
966 // the primitive types).
967 // Returns a newly-allocated buffer full of RefTypeId values.
968 struct ClassListCreator {
Elliott Hughesba8eee12012-01-24 20:25:24 -0800969 explicit ClassListCreator(std::vector<JDWP::RefTypeId>& classes) : classes(classes) {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800970 }
971
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800972 static bool Visit(mirror::Class* c, void* arg) {
Elliott Hughesa2155262011-11-16 16:26:58 -0800973 return reinterpret_cast<ClassListCreator*>(arg)->Visit(c);
974 }
975
Elliott Hughes64f574f2013-02-20 14:57:12 -0800976 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
977 // annotalysis.
978 bool Visit(mirror::Class* c) NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughesa2155262011-11-16 16:26:58 -0800979 if (!c->IsPrimitive()) {
Elliott Hughes64f574f2013-02-20 14:57:12 -0800980 classes.push_back(gRegistry->AddRefType(c));
Elliott Hughesa2155262011-11-16 16:26:58 -0800981 }
982 return true;
983 }
984
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800985 std::vector<JDWP::RefTypeId>& classes;
Elliott Hughesa2155262011-11-16 16:26:58 -0800986 };
987
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800988 ClassListCreator clc(classes);
Elliott Hughesa2155262011-11-16 16:26:58 -0800989 Runtime::Current()->GetClassLinker()->VisitClasses(ClassListCreator::Visit, &clc);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700990}
991
Elliott Hughes88d63092013-01-09 09:55:54 -0800992JDWP::JdwpError Dbg::GetClassInfo(JDWP::RefTypeId class_id, JDWP::JdwpTypeTag* pTypeTag, uint32_t* pStatus, std::string* pDescriptor) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800993 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800994 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -0800995 if (c == NULL) {
996 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800997 }
998
Elliott Hughesa2155262011-11-16 16:26:58 -0800999 if (c->IsArrayClass()) {
1000 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
1001 *pTypeTag = JDWP::TT_ARRAY;
1002 } else {
1003 if (c->IsErroneous()) {
1004 *pStatus = JDWP::CS_ERROR;
1005 } else {
1006 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED | JDWP::CS_INITIALIZED;
1007 }
1008 *pTypeTag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
1009 }
1010
1011 if (pDescriptor != NULL) {
Ian Rogersdfb325e2013-10-30 01:00:44 -07001012 *pDescriptor = ClassHelper(c).GetDescriptor();
Elliott Hughesa2155262011-11-16 16:26:58 -08001013 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001014 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001015}
1016
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001017void Dbg::FindLoadedClassBySignature(const char* descriptor, std::vector<JDWP::RefTypeId>& ids) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001018 std::vector<mirror::Class*> classes;
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001019 Runtime::Current()->GetClassLinker()->LookupClasses(descriptor, classes);
1020 ids.clear();
1021 for (size_t i = 0; i < classes.size(); ++i) {
1022 ids.push_back(gRegistry->Add(classes[i]));
1023 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001024}
1025
Elliott Hughes64f574f2013-02-20 14:57:12 -08001026JDWP::JdwpError Dbg::GetReferenceType(JDWP::ObjectId object_id, JDWP::ExpandBuf* pReply)
1027 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001028 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001029 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001030 return JDWP::ERR_INVALID_OBJECT;
Elliott Hughes499c5132011-11-17 14:55:11 -08001031 }
Elliott Hughes2435a572012-02-17 16:07:41 -08001032
1033 JDWP::JdwpTypeTag type_tag;
1034 if (o->GetClass()->IsArrayClass()) {
1035 type_tag = JDWP::TT_ARRAY;
1036 } else if (o->GetClass()->IsInterface()) {
1037 type_tag = JDWP::TT_INTERFACE;
1038 } else {
1039 type_tag = JDWP::TT_CLASS;
1040 }
Elliott Hughes64f574f2013-02-20 14:57:12 -08001041 JDWP::RefTypeId type_id = gRegistry->AddRefType(o->GetClass());
Elliott Hughes2435a572012-02-17 16:07:41 -08001042
1043 expandBufAdd1(pReply, type_tag);
1044 expandBufAddRefTypeId(pReply, type_id);
1045
1046 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001047}
1048
Ian Rogersfc0e94b2013-09-23 23:51:32 -07001049JDWP::JdwpError Dbg::GetSignature(JDWP::RefTypeId class_id, std::string* signature) {
Elliott Hughes1fe7afb2012-02-13 17:23:03 -08001050 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001051 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes1fe7afb2012-02-13 17:23:03 -08001052 if (c == NULL) {
1053 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001054 }
Ian Rogersdfb325e2013-10-30 01:00:44 -07001055 *signature = ClassHelper(c).GetDescriptor();
Elliott Hughes1fe7afb2012-02-13 17:23:03 -08001056 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001057}
1058
Elliott Hughes88d63092013-01-09 09:55:54 -08001059JDWP::JdwpError Dbg::GetSourceFile(JDWP::RefTypeId class_id, std::string& result) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001060 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001061 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001062 if (c == NULL) {
1063 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001064 }
Sebastien Hertzb7054ba2014-03-13 11:52:31 +01001065 if (c->IsProxyClass()) {
1066 return JDWP::ERR_ABSENT_INFORMATION;
1067 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001068 result = ClassHelper(c).GetSourceFile();
1069 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001070}
1071
Elliott Hughes88d63092013-01-09 09:55:54 -08001072JDWP::JdwpError Dbg::GetObjectTag(JDWP::ObjectId object_id, uint8_t& tag) {
Ian Rogers98379392014-02-24 16:53:16 -08001073 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001074 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001075 if (o == ObjectRegistry::kInvalidObject) {
Elliott Hughes546b9862012-06-20 16:06:13 -07001076 return JDWP::ERR_INVALID_OBJECT;
1077 }
Ian Rogers98379392014-02-24 16:53:16 -08001078 tag = TagFromObject(soa, o);
Elliott Hughes546b9862012-06-20 16:06:13 -07001079 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001080}
1081
Elliott Hughesaed4be92011-12-02 16:16:23 -08001082size_t Dbg::GetTagWidth(JDWP::JdwpTag tag) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001083 switch (tag) {
1084 case JDWP::JT_VOID:
1085 return 0;
1086 case JDWP::JT_BYTE:
1087 case JDWP::JT_BOOLEAN:
1088 return 1;
1089 case JDWP::JT_CHAR:
1090 case JDWP::JT_SHORT:
1091 return 2;
1092 case JDWP::JT_FLOAT:
1093 case JDWP::JT_INT:
1094 return 4;
1095 case JDWP::JT_ARRAY:
1096 case JDWP::JT_OBJECT:
1097 case JDWP::JT_STRING:
1098 case JDWP::JT_THREAD:
1099 case JDWP::JT_THREAD_GROUP:
1100 case JDWP::JT_CLASS_LOADER:
1101 case JDWP::JT_CLASS_OBJECT:
1102 return sizeof(JDWP::ObjectId);
1103 case JDWP::JT_DOUBLE:
1104 case JDWP::JT_LONG:
1105 return 8;
1106 default:
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001107 LOG(FATAL) << "Unknown tag " << tag;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001108 return -1;
1109 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001110}
1111
Elliott Hughes88d63092013-01-09 09:55:54 -08001112JDWP::JdwpError Dbg::GetArrayLength(JDWP::ObjectId array_id, int& length) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001113 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001114 mirror::Array* a = DecodeArray(array_id, status);
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001115 if (a == NULL) {
1116 return status;
Elliott Hughes24437992011-11-30 14:49:33 -08001117 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001118 length = a->GetLength();
1119 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001120}
1121
Elliott Hughes88d63092013-01-09 09:55:54 -08001122JDWP::JdwpError Dbg::OutputArray(JDWP::ObjectId array_id, int offset, int count, JDWP::ExpandBuf* pReply) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001123 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001124 mirror::Array* a = DecodeArray(array_id, status);
Ian Rogers98379392014-02-24 16:53:16 -08001125 if (a == nullptr) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001126 return status;
1127 }
Elliott Hughes24437992011-11-30 14:49:33 -08001128
1129 if (offset < 0 || count < 0 || offset > a->GetLength() || a->GetLength() - offset < count) {
1130 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001131 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughes24437992011-11-30 14:49:33 -08001132 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001133 std::string descriptor(ClassHelper(a->GetClass()).GetDescriptor());
Elliott Hughes24437992011-11-30 14:49:33 -08001134 JDWP::JdwpTag tag = BasicTagFromDescriptor(descriptor.c_str() + 1);
1135
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001136 expandBufAdd1(pReply, tag);
1137 expandBufAdd4BE(pReply, count);
1138
Elliott Hughes24437992011-11-30 14:49:33 -08001139 if (IsPrimitiveTag(tag)) {
1140 size_t width = GetTagWidth(tag);
Elliott Hughes24437992011-11-30 14:49:33 -08001141 uint8_t* dst = expandBufAddSpace(pReply, count * width);
1142 if (width == 8) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001143 const uint64_t* src8 = reinterpret_cast<uint64_t*>(a->GetRawData(sizeof(uint64_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001144 for (int i = 0; i < count; ++i) JDWP::Write8BE(&dst, src8[offset + i]);
1145 } else if (width == 4) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001146 const uint32_t* src4 = reinterpret_cast<uint32_t*>(a->GetRawData(sizeof(uint32_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001147 for (int i = 0; i < count; ++i) JDWP::Write4BE(&dst, src4[offset + i]);
1148 } else if (width == 2) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001149 const uint16_t* src2 = reinterpret_cast<uint16_t*>(a->GetRawData(sizeof(uint16_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001150 for (int i = 0; i < count; ++i) JDWP::Write2BE(&dst, src2[offset + i]);
1151 } else {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001152 const uint8_t* src = reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint8_t), 0));
Elliott Hughes24437992011-11-30 14:49:33 -08001153 memcpy(dst, &src[offset * width], count * width);
1154 }
1155 } else {
Ian Rogers98379392014-02-24 16:53:16 -08001156 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001157 mirror::ObjectArray<mirror::Object>* oa = a->AsObjectArray<mirror::Object>();
Elliott Hughes24437992011-11-30 14:49:33 -08001158 for (int i = 0; i < count; ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001159 mirror::Object* element = oa->Get(offset + i);
Ian Rogers98379392014-02-24 16:53:16 -08001160 JDWP::JdwpTag specific_tag = (element != nullptr) ? TagFromObject(soa, element)
1161 : tag;
Elliott Hughes24437992011-11-30 14:49:33 -08001162 expandBufAdd1(pReply, specific_tag);
1163 expandBufAddObjectId(pReply, gRegistry->Add(element));
1164 }
1165 }
1166
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001167 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001168}
1169
Ian Rogersef7d42f2014-01-06 12:55:46 -08001170template <typename T>
1171static void CopyArrayData(mirror::Array* a, JDWP::Request& src, int offset, int count)
1172 NO_THREAD_SAFETY_ANALYSIS {
1173 // TODO: fix when annotalysis correctly handles non-member functions.
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001174 DCHECK(a->GetClass()->IsPrimitiveArray());
1175
Ian Rogersef7d42f2014-01-06 12:55:46 -08001176 T* dst = reinterpret_cast<T*>(a->GetRawData(sizeof(T), offset));
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001177 for (int i = 0; i < count; ++i) {
1178 *dst++ = src.ReadValue(sizeof(T));
1179 }
1180}
1181
Elliott Hughes88d63092013-01-09 09:55:54 -08001182JDWP::JdwpError Dbg::SetArrayElements(JDWP::ObjectId array_id, int offset, int count,
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001183 JDWP::Request& request)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001184 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001185 JDWP::JdwpError status;
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001186 mirror::Array* dst = DecodeArray(array_id, status);
1187 if (dst == NULL) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001188 return status;
1189 }
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001190
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001191 if (offset < 0 || count < 0 || offset > dst->GetLength() || dst->GetLength() - offset < count) {
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001192 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001193 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001194 }
Ian Rogersfc0e94b2013-09-23 23:51:32 -07001195 const char* descriptor = ClassHelper(dst->GetClass()).GetDescriptor();
1196 JDWP::JdwpTag tag = BasicTagFromDescriptor(descriptor + 1);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001197
1198 if (IsPrimitiveTag(tag)) {
1199 size_t width = GetTagWidth(tag);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001200 if (width == 8) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001201 CopyArrayData<uint64_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001202 } else if (width == 4) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001203 CopyArrayData<uint32_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001204 } else if (width == 2) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001205 CopyArrayData<uint16_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001206 } else {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001207 CopyArrayData<uint8_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001208 }
1209 } else {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001210 mirror::ObjectArray<mirror::Object>* oa = dst->AsObjectArray<mirror::Object>();
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001211 for (int i = 0; i < count; ++i) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001212 JDWP::ObjectId id = request.ReadObjectId();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001213 mirror::Object* o = gRegistry->Get<mirror::Object*>(id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001214 if (o == ObjectRegistry::kInvalidObject) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001215 return JDWP::ERR_INVALID_OBJECT;
1216 }
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001217 oa->Set<false>(offset + i, o);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001218 }
1219 }
1220
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001221 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001222}
1223
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001224JDWP::ObjectId Dbg::CreateString(const std::string& str) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001225 return gRegistry->Add(mirror::String::AllocFromModifiedUtf8(Thread::Current(), str.c_str()));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001226}
1227
Elliott Hughes88d63092013-01-09 09:55:54 -08001228JDWP::JdwpError Dbg::CreateObject(JDWP::RefTypeId class_id, JDWP::ObjectId& new_object) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001229 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001230 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001231 if (c == NULL) {
1232 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001233 }
Ian Rogers50b35e22012-10-04 10:09:15 -07001234 new_object = gRegistry->Add(c->AllocObject(Thread::Current()));
Elliott Hughes436e3722012-02-17 20:01:47 -08001235 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001236}
1237
Elliott Hughesbf13d362011-12-08 15:51:37 -08001238/*
1239 * Used by Eclipse's "Display" view to evaluate "new byte[5]" to get "(byte[]) [0, 0, 0, 0, 0]".
1240 */
Elliott Hughes88d63092013-01-09 09:55:54 -08001241JDWP::JdwpError Dbg::CreateArrayObject(JDWP::RefTypeId array_class_id, uint32_t length,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001242 JDWP::ObjectId& new_array) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001243 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001244 mirror::Class* c = DecodeClass(array_class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001245 if (c == NULL) {
1246 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001247 }
Ian Rogers6fac4472014-02-25 17:01:10 -08001248 new_array = gRegistry->Add(mirror::Array::Alloc<true>(Thread::Current(), c, length,
1249 c->GetComponentSize(),
1250 Runtime::Current()->GetHeap()->GetCurrentAllocator()));
Elliott Hughes436e3722012-02-17 20:01:47 -08001251 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001252}
1253
Elliott Hughes88d63092013-01-09 09:55:54 -08001254bool Dbg::MatchType(JDWP::RefTypeId instance_class_id, JDWP::RefTypeId class_id) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001255 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001256 mirror::Class* c1 = DecodeClass(instance_class_id, status);
Elliott Hughesa656a0f2012-02-21 18:03:44 -08001257 CHECK(c1 != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001258 mirror::Class* c2 = DecodeClass(class_id, status);
Elliott Hughesa656a0f2012-02-21 18:03:44 -08001259 CHECK(c2 != NULL);
Sebastien Hertz123756a2013-11-27 15:49:42 +01001260 return c2->IsAssignableFrom(c1);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001261}
1262
Brian Carlstromea46f952013-07-30 01:26:50 -07001263static JDWP::FieldId ToFieldId(const mirror::ArtField* f)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001264 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001265 CHECK(!kMovingFields);
Elliott Hughes03181a82011-11-17 17:22:21 -08001266 return static_cast<JDWP::FieldId>(reinterpret_cast<uintptr_t>(f));
Elliott Hughes03181a82011-11-17 17:22:21 -08001267}
1268
Brian Carlstromea46f952013-07-30 01:26:50 -07001269static JDWP::MethodId ToMethodId(const mirror::ArtMethod* m)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001270 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001271 CHECK(!kMovingMethods);
Elliott Hughes03181a82011-11-17 17:22:21 -08001272 return static_cast<JDWP::MethodId>(reinterpret_cast<uintptr_t>(m));
Elliott Hughes03181a82011-11-17 17:22:21 -08001273}
1274
Brian Carlstromea46f952013-07-30 01:26:50 -07001275static mirror::ArtField* FromFieldId(JDWP::FieldId fid)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001276 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001277 CHECK(!kMovingFields);
Brian Carlstromea46f952013-07-30 01:26:50 -07001278 return reinterpret_cast<mirror::ArtField*>(static_cast<uintptr_t>(fid));
Elliott Hughesaed4be92011-12-02 16:16:23 -08001279}
1280
Brian Carlstromea46f952013-07-30 01:26:50 -07001281static mirror::ArtMethod* FromMethodId(JDWP::MethodId mid)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001282 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001283 CHECK(!kMovingMethods);
Brian Carlstromea46f952013-07-30 01:26:50 -07001284 return reinterpret_cast<mirror::ArtMethod*>(static_cast<uintptr_t>(mid));
Elliott Hughes03181a82011-11-17 17:22:21 -08001285}
1286
Brian Carlstromea46f952013-07-30 01:26:50 -07001287static void SetLocation(JDWP::JdwpLocation& location, mirror::ArtMethod* m, uint32_t dex_pc)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001288 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001289 if (m == NULL) {
1290 memset(&location, 0, sizeof(location));
1291 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001292 mirror::Class* c = m->GetDeclaringClass();
Elliott Hughes74847412012-06-20 18:10:21 -07001293 location.type_tag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001294 location.class_id = gRegistry->AddRefType(c);
Elliott Hughes74847412012-06-20 18:10:21 -07001295 location.method_id = ToMethodId(m);
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001296 location.dex_pc = (m->IsNative() || m->IsProxyMethod()) ? static_cast<uint64_t>(-1) : dex_pc;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001297 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08001298}
1299
Elliott Hughesa96836a2013-01-17 12:27:49 -08001300std::string Dbg::GetMethodName(JDWP::MethodId method_id)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001301 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001302 mirror::ArtMethod* m = FromMethodId(method_id);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001303 return MethodHelper(m).GetName();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001304}
1305
Elliott Hughesa96836a2013-01-17 12:27:49 -08001306std::string Dbg::GetFieldName(JDWP::FieldId field_id)
1307 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001308 mirror::ArtField* f = FromFieldId(field_id);
Elliott Hughesa96836a2013-01-17 12:27:49 -08001309 return FieldHelper(f).GetName();
1310}
1311
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001312/*
1313 * Augment the access flags for synthetic methods and fields by setting
1314 * the (as described by the spec) "0xf0000000 bit". Also, strip out any
1315 * flags not specified by the Java programming language.
1316 */
1317static uint32_t MangleAccessFlags(uint32_t accessFlags) {
1318 accessFlags &= kAccJavaFlagsMask;
1319 if ((accessFlags & kAccSynthetic) != 0) {
1320 accessFlags |= 0xf0000000;
1321 }
1322 return accessFlags;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001323}
1324
Elliott Hughesdbb40792011-11-18 17:05:22 -08001325/*
Jeff Haob7cefc72013-11-14 14:51:09 -08001326 * Circularly shifts registers so that arguments come first. Debuggers
1327 * expect slots to begin with arguments, but dex code places them at
1328 * the end.
Elliott Hughesdbb40792011-11-18 17:05:22 -08001329 */
Jeff Haob7cefc72013-11-14 14:51:09 -08001330static uint16_t MangleSlot(uint16_t slot, mirror::ArtMethod* m)
1331 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1332 const DexFile::CodeItem* code_item = MethodHelper(m).GetCodeItem();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001333 if (code_item == nullptr) {
1334 // We should not get here for a method without code (native, proxy or abstract). Log it and
1335 // return the slot as is since all registers are arguments.
1336 LOG(WARNING) << "Trying to mangle slot for method without code " << PrettyMethod(m);
1337 return slot;
1338 }
Jeff Haob7cefc72013-11-14 14:51:09 -08001339 uint16_t ins_size = code_item->ins_size_;
1340 uint16_t locals_size = code_item->registers_size_ - ins_size;
1341 if (slot >= locals_size) {
1342 return slot - locals_size;
1343 } else {
1344 return slot + ins_size;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001345 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001346}
1347
Jeff Haob7cefc72013-11-14 14:51:09 -08001348/*
1349 * Circularly shifts registers so that arguments come last. Reverts
1350 * slots to dex style argument placement.
1351 */
Brian Carlstromea46f952013-07-30 01:26:50 -07001352static uint16_t DemangleSlot(uint16_t slot, mirror::ArtMethod* m)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001353 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Jeff Haob7cefc72013-11-14 14:51:09 -08001354 const DexFile::CodeItem* code_item = MethodHelper(m).GetCodeItem();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001355 if (code_item == nullptr) {
1356 // We should not get here for a method without code (native, proxy or abstract). Log it and
1357 // return the slot as is since all registers are arguments.
1358 LOG(WARNING) << "Trying to demangle slot for method without code " << PrettyMethod(m);
1359 return slot;
1360 }
Jeff Haob7cefc72013-11-14 14:51:09 -08001361 uint16_t ins_size = code_item->ins_size_;
1362 uint16_t locals_size = code_item->registers_size_ - ins_size;
1363 if (slot < ins_size) {
1364 return slot + locals_size;
1365 } else {
1366 return slot - ins_size;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001367 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001368}
1369
Elliott Hughes88d63092013-01-09 09:55:54 -08001370JDWP::JdwpError Dbg::OutputDeclaredFields(JDWP::RefTypeId class_id, bool with_generic, JDWP::ExpandBuf* pReply) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001371 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001372 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001373 if (c == NULL) {
1374 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001375 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001376
1377 size_t instance_field_count = c->NumInstanceFields();
1378 size_t static_field_count = c->NumStaticFields();
1379
1380 expandBufAdd4BE(pReply, instance_field_count + static_field_count);
1381
1382 for (size_t i = 0; i < instance_field_count + static_field_count; ++i) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001383 mirror::ArtField* f = (i < instance_field_count) ? c->GetInstanceField(i) : c->GetStaticField(i - instance_field_count);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001384 FieldHelper fh(f);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001385 expandBufAddFieldId(pReply, ToFieldId(f));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001386 expandBufAddUtf8String(pReply, fh.GetName());
1387 expandBufAddUtf8String(pReply, fh.GetTypeDescriptor());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001388 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001389 static const char genericSignature[1] = "";
1390 expandBufAddUtf8String(pReply, genericSignature);
1391 }
1392 expandBufAdd4BE(pReply, MangleAccessFlags(f->GetAccessFlags()));
1393 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001394 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001395}
1396
Elliott Hughes88d63092013-01-09 09:55:54 -08001397JDWP::JdwpError Dbg::OutputDeclaredMethods(JDWP::RefTypeId class_id, bool with_generic,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001398 JDWP::ExpandBuf* pReply) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001399 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001400 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001401 if (c == NULL) {
1402 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001403 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001404
1405 size_t direct_method_count = c->NumDirectMethods();
1406 size_t virtual_method_count = c->NumVirtualMethods();
1407
1408 expandBufAdd4BE(pReply, direct_method_count + virtual_method_count);
1409
1410 for (size_t i = 0; i < direct_method_count + virtual_method_count; ++i) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001411 mirror::ArtMethod* m = (i < direct_method_count) ? c->GetDirectMethod(i) : c->GetVirtualMethod(i - direct_method_count);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001412 MethodHelper mh(m);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001413 expandBufAddMethodId(pReply, ToMethodId(m));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001414 expandBufAddUtf8String(pReply, mh.GetName());
Ian Rogersd91d6d62013-09-25 20:26:14 -07001415 expandBufAddUtf8String(pReply, mh.GetSignature().ToString());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001416 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001417 static const char genericSignature[1] = "";
1418 expandBufAddUtf8String(pReply, genericSignature);
1419 }
1420 expandBufAdd4BE(pReply, MangleAccessFlags(m->GetAccessFlags()));
1421 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001422 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001423}
1424
Elliott Hughes88d63092013-01-09 09:55:54 -08001425JDWP::JdwpError Dbg::OutputDeclaredInterfaces(JDWP::RefTypeId class_id, JDWP::ExpandBuf* pReply) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001426 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001427 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001428 if (c == NULL) {
1429 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001430 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001431
1432 ClassHelper kh(c);
Ian Rogersd24e2642012-06-06 21:21:43 -07001433 size_t interface_count = kh.NumDirectInterfaces();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001434 expandBufAdd4BE(pReply, interface_count);
1435 for (size_t i = 0; i < interface_count; ++i) {
Elliott Hughes64f574f2013-02-20 14:57:12 -08001436 expandBufAddRefTypeId(pReply, gRegistry->AddRefType(kh.GetDirectInterface(i)));
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001437 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001438 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001439}
1440
Elliott Hughes88d63092013-01-09 09:55:54 -08001441void Dbg::OutputLineTable(JDWP::RefTypeId, JDWP::MethodId method_id, JDWP::ExpandBuf* pReply)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001442 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001443 struct DebugCallbackContext {
1444 int numItems;
1445 JDWP::ExpandBuf* pReply;
1446
Elliott Hughes2435a572012-02-17 16:07:41 -08001447 static bool Callback(void* context, uint32_t address, uint32_t line_number) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001448 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
1449 expandBufAdd8BE(pContext->pReply, address);
Elliott Hughes2435a572012-02-17 16:07:41 -08001450 expandBufAdd4BE(pContext->pReply, line_number);
Elliott Hughes03181a82011-11-17 17:22:21 -08001451 pContext->numItems++;
Sebastien Hertzf2910ee2013-10-19 16:39:24 +02001452 return false;
Elliott Hughes03181a82011-11-17 17:22:21 -08001453 }
1454 };
Brian Carlstromea46f952013-07-30 01:26:50 -07001455 mirror::ArtMethod* m = FromMethodId(method_id);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001456 MethodHelper mh(m);
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001457 const DexFile::CodeItem* code_item = mh.GetCodeItem();
Elliott Hughes03181a82011-11-17 17:22:21 -08001458 uint64_t start, end;
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001459 if (code_item == nullptr) {
1460 DCHECK(m->IsNative() || m->IsProxyMethod());
Elliott Hughes03181a82011-11-17 17:22:21 -08001461 start = -1;
1462 end = -1;
1463 } else {
1464 start = 0;
jeffhao14f0db92012-12-14 17:50:42 -08001465 // Return the index of the last instruction
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001466 end = code_item->insns_size_in_code_units_ - 1;
Elliott Hughes03181a82011-11-17 17:22:21 -08001467 }
1468
1469 expandBufAdd8BE(pReply, start);
1470 expandBufAdd8BE(pReply, end);
1471
1472 // Add numLines later
1473 size_t numLinesOffset = expandBufGetLength(pReply);
1474 expandBufAdd4BE(pReply, 0);
1475
1476 DebugCallbackContext context;
1477 context.numItems = 0;
1478 context.pReply = pReply;
1479
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001480 if (code_item != nullptr) {
1481 mh.GetDexFile().DecodeDebugInfo(code_item, m->IsStatic(), m->GetDexMethodIndex(),
1482 DebugCallbackContext::Callback, NULL, &context);
1483 }
Elliott Hughes03181a82011-11-17 17:22:21 -08001484
1485 JDWP::Set4BE(expandBufGetBuffer(pReply) + numLinesOffset, context.numItems);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001486}
1487
Elliott Hughes88d63092013-01-09 09:55:54 -08001488void Dbg::OutputVariableTable(JDWP::RefTypeId, JDWP::MethodId method_id, bool with_generic, JDWP::ExpandBuf* pReply) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001489 struct DebugCallbackContext {
Jeff Haob7cefc72013-11-14 14:51:09 -08001490 mirror::ArtMethod* method;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001491 JDWP::ExpandBuf* pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001492 size_t variable_count;
1493 bool with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001494
Jeff Haob7cefc72013-11-14 14:51:09 -08001495 static void Callback(void* context, uint16_t slot, uint32_t startAddress, uint32_t endAddress, const char* name, const char* descriptor, const char* signature)
1496 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001497 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
1498
Jeff Haob7cefc72013-11-14 14:51:09 -08001499 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 -08001500
Jeff Haob7cefc72013-11-14 14:51:09 -08001501 slot = MangleSlot(slot, pContext->method);
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001502
Elliott Hughesdbb40792011-11-18 17:05:22 -08001503 expandBufAdd8BE(pContext->pReply, startAddress);
1504 expandBufAddUtf8String(pContext->pReply, name);
1505 expandBufAddUtf8String(pContext->pReply, descriptor);
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001506 if (pContext->with_generic) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001507 expandBufAddUtf8String(pContext->pReply, signature);
1508 }
1509 expandBufAdd4BE(pContext->pReply, endAddress - startAddress);
1510 expandBufAdd4BE(pContext->pReply, slot);
1511
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001512 ++pContext->variable_count;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001513 }
1514 };
Brian Carlstromea46f952013-07-30 01:26:50 -07001515 mirror::ArtMethod* m = FromMethodId(method_id);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001516 MethodHelper mh(m);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001517
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001518 // arg_count considers doubles and longs to take 2 units.
1519 // variable_count considers everything to take 1 unit.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001520 std::string shorty(mh.GetShorty());
Brian Carlstromea46f952013-07-30 01:26:50 -07001521 expandBufAdd4BE(pReply, mirror::ArtMethod::NumArgRegisters(shorty));
Elliott Hughesdbb40792011-11-18 17:05:22 -08001522
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001523 // We don't know the total number of variables yet, so leave a blank and update it later.
1524 size_t variable_count_offset = expandBufGetLength(pReply);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001525 expandBufAdd4BE(pReply, 0);
1526
1527 DebugCallbackContext context;
Jeff Haob7cefc72013-11-14 14:51:09 -08001528 context.method = m;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001529 context.pReply = pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001530 context.variable_count = 0;
1531 context.with_generic = with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001532
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01001533 const DexFile::CodeItem* code_item = mh.GetCodeItem();
1534 if (code_item != nullptr) {
1535 mh.GetDexFile().DecodeDebugInfo(code_item, m->IsStatic(), m->GetDexMethodIndex(), NULL,
1536 DebugCallbackContext::Callback, &context);
1537 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001538
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001539 JDWP::Set4BE(expandBufGetBuffer(pReply) + variable_count_offset, context.variable_count);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001540}
1541
Jeff Hao579b0242013-11-18 13:16:49 -08001542void Dbg::OutputMethodReturnValue(JDWP::MethodId method_id, const JValue* return_value,
1543 JDWP::ExpandBuf* pReply) {
1544 mirror::ArtMethod* m = FromMethodId(method_id);
1545 JDWP::JdwpTag tag = BasicTagFromDescriptor(MethodHelper(m).GetShorty());
1546 OutputJValue(tag, return_value, pReply);
1547}
1548
Elliott Hughes9777ba22013-01-17 09:04:19 -08001549JDWP::JdwpError Dbg::GetBytecodes(JDWP::RefTypeId, JDWP::MethodId method_id,
1550 std::vector<uint8_t>& bytecodes)
1551 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001552 mirror::ArtMethod* m = FromMethodId(method_id);
Elliott Hughes9777ba22013-01-17 09:04:19 -08001553 if (m == NULL) {
1554 return JDWP::ERR_INVALID_METHODID;
1555 }
1556 MethodHelper mh(m);
1557 const DexFile::CodeItem* code_item = mh.GetCodeItem();
1558 size_t byte_count = code_item->insns_size_in_code_units_ * 2;
1559 const uint8_t* begin = reinterpret_cast<const uint8_t*>(code_item->insns_);
1560 const uint8_t* end = begin + byte_count;
1561 for (const uint8_t* p = begin; p != end; ++p) {
1562 bytecodes.push_back(*p);
1563 }
1564 return JDWP::ERR_NONE;
1565}
1566
Elliott Hughes88d63092013-01-09 09:55:54 -08001567JDWP::JdwpTag Dbg::GetFieldBasicTag(JDWP::FieldId field_id) {
1568 return BasicTagFromDescriptor(FieldHelper(FromFieldId(field_id)).GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001569}
1570
Elliott Hughes88d63092013-01-09 09:55:54 -08001571JDWP::JdwpTag Dbg::GetStaticFieldBasicTag(JDWP::FieldId field_id) {
1572 return BasicTagFromDescriptor(FieldHelper(FromFieldId(field_id)).GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001573}
1574
Elliott Hughes88d63092013-01-09 09:55:54 -08001575static JDWP::JdwpError GetFieldValueImpl(JDWP::RefTypeId ref_type_id, JDWP::ObjectId object_id,
1576 JDWP::FieldId field_id, JDWP::ExpandBuf* pReply,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001577 bool is_static)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001578 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes0cf74332012-02-23 23:14:00 -08001579 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001580 mirror::Class* c = DecodeClass(ref_type_id, status);
Elliott Hughes88d63092013-01-09 09:55:54 -08001581 if (ref_type_id != 0 && c == NULL) {
Elliott Hughes0cf74332012-02-23 23:14:00 -08001582 return status;
1583 }
1584
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001585 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001586 if ((!is_static && o == NULL) || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001587 return JDWP::ERR_INVALID_OBJECT;
1588 }
Brian Carlstromea46f952013-07-30 01:26:50 -07001589 mirror::ArtField* f = FromFieldId(field_id);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001590
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001591 mirror::Class* receiver_class = c;
Elliott Hughes0cf74332012-02-23 23:14:00 -08001592 if (receiver_class == NULL && o != NULL) {
1593 receiver_class = o->GetClass();
1594 }
1595 // TODO: should we give up now if receiver_class is NULL?
1596 if (receiver_class != NULL && !f->GetDeclaringClass()->IsAssignableFrom(receiver_class)) {
1597 LOG(INFO) << "ERR_INVALID_FIELDID: " << PrettyField(f) << " " << PrettyClass(receiver_class);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001598 return JDWP::ERR_INVALID_FIELDID;
1599 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001600
Elliott Hughes0cf74332012-02-23 23:14:00 -08001601 // The RI only enforces the static/non-static mismatch in one direction.
1602 // TODO: should we change the tests and check both?
1603 if (is_static) {
1604 if (!f->IsStatic()) {
1605 return JDWP::ERR_INVALID_FIELDID;
1606 }
1607 } else {
1608 if (f->IsStatic()) {
1609 LOG(WARNING) << "Ignoring non-NULL receiver for ObjectReference.SetValues on static field " << PrettyField(f);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001610 }
1611 }
jeffhao0dfbb7e2012-11-28 15:26:03 -08001612 if (f->IsStatic()) {
1613 o = f->GetDeclaringClass();
1614 }
Elliott Hughes0cf74332012-02-23 23:14:00 -08001615
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001616 JDWP::JdwpTag tag = BasicTagFromDescriptor(FieldHelper(f).GetTypeDescriptor());
Jeff Hao579b0242013-11-18 13:16:49 -08001617 JValue field_value;
1618 if (tag == JDWP::JT_VOID) {
1619 LOG(FATAL) << "Unknown tag: " << tag;
1620 } else if (!IsPrimitiveTag(tag)) {
1621 field_value.SetL(f->GetObject(o));
1622 } else if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
1623 field_value.SetJ(f->Get64(o));
Elliott Hughesaed4be92011-12-02 16:16:23 -08001624 } else {
Jeff Hao579b0242013-11-18 13:16:49 -08001625 field_value.SetI(f->Get32(o));
Elliott Hughesaed4be92011-12-02 16:16:23 -08001626 }
Jeff Hao579b0242013-11-18 13:16:49 -08001627 Dbg::OutputJValue(tag, &field_value, pReply);
1628
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001629 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001630}
1631
Elliott Hughes88d63092013-01-09 09:55:54 -08001632JDWP::JdwpError Dbg::GetFieldValue(JDWP::ObjectId object_id, JDWP::FieldId field_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001633 JDWP::ExpandBuf* pReply) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001634 return GetFieldValueImpl(0, object_id, field_id, pReply, false);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001635}
1636
Elliott Hughes88d63092013-01-09 09:55:54 -08001637JDWP::JdwpError Dbg::GetStaticFieldValue(JDWP::RefTypeId ref_type_id, JDWP::FieldId field_id, JDWP::ExpandBuf* pReply) {
1638 return GetFieldValueImpl(ref_type_id, 0, field_id, pReply, true);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001639}
1640
Elliott Hughes88d63092013-01-09 09:55:54 -08001641static JDWP::JdwpError SetFieldValueImpl(JDWP::ObjectId object_id, JDWP::FieldId field_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001642 uint64_t value, int width, bool is_static)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001643 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001644 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001645 if ((!is_static && o == NULL) || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001646 return JDWP::ERR_INVALID_OBJECT;
1647 }
Brian Carlstromea46f952013-07-30 01:26:50 -07001648 mirror::ArtField* f = FromFieldId(field_id);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001649
1650 // The RI only enforces the static/non-static mismatch in one direction.
1651 // TODO: should we change the tests and check both?
1652 if (is_static) {
1653 if (!f->IsStatic()) {
1654 return JDWP::ERR_INVALID_FIELDID;
1655 }
1656 } else {
1657 if (f->IsStatic()) {
1658 LOG(WARNING) << "Ignoring non-NULL receiver for ObjectReference.SetValues on static field " << PrettyField(f);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001659 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001660 }
jeffhao0dfbb7e2012-11-28 15:26:03 -08001661 if (f->IsStatic()) {
1662 o = f->GetDeclaringClass();
1663 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001664
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001665 JDWP::JdwpTag tag = BasicTagFromDescriptor(FieldHelper(f).GetTypeDescriptor());
Elliott Hughesaed4be92011-12-02 16:16:23 -08001666
1667 if (IsPrimitiveTag(tag)) {
1668 if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001669 CHECK_EQ(width, 8);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001670 // Debugging can't use transactional mode (runtime only).
1671 f->Set64<false>(o, value);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001672 } else {
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001673 CHECK_LE(width, 4);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001674 // Debugging can't use transactional mode (runtime only).
1675 f->Set32<false>(o, value);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001676 }
1677 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001678 mirror::Object* v = gRegistry->Get<mirror::Object*>(value);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001679 if (v == ObjectRegistry::kInvalidObject) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001680 return JDWP::ERR_INVALID_OBJECT;
1681 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001682 if (v != NULL) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001683 mirror::Class* field_type = FieldHelper(f).GetType();
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001684 if (!field_type->IsAssignableFrom(v->GetClass())) {
1685 return JDWP::ERR_INVALID_OBJECT;
1686 }
1687 }
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001688 // Debugging can't use transactional mode (runtime only).
1689 f->SetObject<false>(o, v);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001690 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001691
1692 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001693}
1694
Elliott Hughes88d63092013-01-09 09:55:54 -08001695JDWP::JdwpError Dbg::SetFieldValue(JDWP::ObjectId object_id, JDWP::FieldId field_id, uint64_t value,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001696 int width) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001697 return SetFieldValueImpl(object_id, field_id, value, width, false);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001698}
1699
Elliott Hughes88d63092013-01-09 09:55:54 -08001700JDWP::JdwpError Dbg::SetStaticFieldValue(JDWP::FieldId field_id, uint64_t value, int width) {
1701 return SetFieldValueImpl(0, field_id, value, width, true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001702}
1703
Elliott Hughes88d63092013-01-09 09:55:54 -08001704std::string Dbg::StringToUtf8(JDWP::ObjectId string_id) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001705 mirror::String* s = gRegistry->Get<mirror::String*>(string_id);
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001706 return s->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001707}
1708
Jeff Hao579b0242013-11-18 13:16:49 -08001709void Dbg::OutputJValue(JDWP::JdwpTag tag, const JValue* return_value, JDWP::ExpandBuf* pReply) {
1710 if (IsPrimitiveTag(tag)) {
1711 expandBufAdd1(pReply, tag);
1712 if (tag == JDWP::JT_BOOLEAN || tag == JDWP::JT_BYTE) {
1713 expandBufAdd1(pReply, return_value->GetI());
1714 } else if (tag == JDWP::JT_CHAR || tag == JDWP::JT_SHORT) {
1715 expandBufAdd2BE(pReply, return_value->GetI());
1716 } else if (tag == JDWP::JT_FLOAT || tag == JDWP::JT_INT) {
1717 expandBufAdd4BE(pReply, return_value->GetI());
1718 } else if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
1719 expandBufAdd8BE(pReply, return_value->GetJ());
1720 } else {
1721 CHECK_EQ(tag, JDWP::JT_VOID);
1722 }
1723 } else {
Ian Rogers98379392014-02-24 16:53:16 -08001724 ScopedObjectAccessUnchecked soa(Thread::Current());
Jeff Hao579b0242013-11-18 13:16:49 -08001725 mirror::Object* value = return_value->GetL();
Ian Rogers98379392014-02-24 16:53:16 -08001726 expandBufAdd1(pReply, TagFromObject(soa, value));
Jeff Hao579b0242013-11-18 13:16:49 -08001727 expandBufAddObjectId(pReply, gRegistry->Add(value));
1728 }
1729}
1730
Elliott Hughes221229c2013-01-08 18:17:50 -08001731JDWP::JdwpError Dbg::GetThreadName(JDWP::ObjectId thread_id, std::string& name) {
jeffhaoa77f0f62012-12-05 17:19:31 -08001732 ScopedObjectAccessUnchecked soa(Thread::Current());
1733 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001734 Thread* thread;
1735 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1736 if (error != JDWP::ERR_NONE && error != JDWP::ERR_THREAD_NOT_ALIVE) {
1737 return error;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001738 }
Elliott Hughes221229c2013-01-08 18:17:50 -08001739
1740 // We still need to report the zombie threads' names, so we can't just call Thread::GetThreadName.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001741 mirror::Object* thread_object = gRegistry->Get<mirror::Object*>(thread_id);
Brian Carlstromea46f952013-07-30 01:26:50 -07001742 mirror::ArtField* java_lang_Thread_name_field =
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001743 soa.DecodeField(WellKnownClasses::java_lang_Thread_name);
1744 mirror::String* s =
1745 reinterpret_cast<mirror::String*>(java_lang_Thread_name_field->GetObject(thread_object));
Elliott Hughes221229c2013-01-08 18:17:50 -08001746 if (s != NULL) {
1747 name = s->ToModifiedUtf8();
1748 }
1749 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001750}
1751
Elliott Hughes221229c2013-01-08 18:17:50 -08001752JDWP::JdwpError Dbg::GetThreadGroup(JDWP::ObjectId thread_id, JDWP::ExpandBuf* pReply) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001753 ScopedObjectAccess soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001754 mirror::Object* thread_object = gRegistry->Get<mirror::Object*>(thread_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001755 if (thread_object == ObjectRegistry::kInvalidObject) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001756 return JDWP::ERR_INVALID_OBJECT;
1757 }
Ian Rogers98379392014-02-24 16:53:16 -08001758 const char* old_cause = soa.Self()->StartAssertNoThreadSuspension("Debugger: GetThreadGroup");
Elliott Hughes2435a572012-02-17 16:07:41 -08001759 // Okay, so it's an object, but is it actually a thread?
Ian Rogers50b35e22012-10-04 10:09:15 -07001760 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001761 Thread* thread;
1762 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1763 if (error == JDWP::ERR_THREAD_NOT_ALIVE) {
1764 // Zombie threads are in the null group.
1765 expandBufAddObjectId(pReply, JDWP::ObjectId(0));
Sebastien Hertz52d131d2014-03-13 16:17:40 +01001766 error = JDWP::ERR_NONE;
1767 } else if (error == JDWP::ERR_NONE) {
1768 mirror::Class* c = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_Thread);
1769 CHECK(c != nullptr);
1770 mirror::ArtField* f = c->FindInstanceField("group", "Ljava/lang/ThreadGroup;");
1771 CHECK(f != NULL);
1772 mirror::Object* group = f->GetObject(thread_object);
1773 CHECK(group != NULL);
1774 JDWP::ObjectId thread_group_id = gRegistry->Add(group);
1775 expandBufAddObjectId(pReply, thread_group_id);
Elliott Hughes221229c2013-01-08 18:17:50 -08001776 }
Ian Rogers98379392014-02-24 16:53:16 -08001777 soa.Self()->EndAssertNoThreadSuspension(old_cause);
Sebastien Hertz52d131d2014-03-13 16:17:40 +01001778 return error;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001779}
1780
Elliott Hughes88d63092013-01-09 09:55:54 -08001781std::string Dbg::GetThreadGroupName(JDWP::ObjectId thread_group_id) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001782 ScopedObjectAccess soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001783 mirror::Object* thread_group = gRegistry->Get<mirror::Object*>(thread_group_id);
Ian Rogers98379392014-02-24 16:53:16 -08001784 CHECK(thread_group != nullptr);
1785 const char* old_cause = soa.Self()->StartAssertNoThreadSuspension("Debugger: GetThreadGroupName");
1786 mirror::Class* c = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_ThreadGroup);
1787 CHECK(c != nullptr);
Brian Carlstromea46f952013-07-30 01:26:50 -07001788 mirror::ArtField* f = c->FindInstanceField("name", "Ljava/lang/String;");
Elliott Hughes499c5132011-11-17 14:55:11 -08001789 CHECK(f != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001790 mirror::String* s = reinterpret_cast<mirror::String*>(f->GetObject(thread_group));
Ian Rogers98379392014-02-24 16:53:16 -08001791 soa.Self()->EndAssertNoThreadSuspension(old_cause);
Elliott Hughes499c5132011-11-17 14:55:11 -08001792 return s->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001793}
1794
Elliott Hughes88d63092013-01-09 09:55:54 -08001795JDWP::ObjectId Dbg::GetThreadGroupParent(JDWP::ObjectId thread_group_id) {
Ian Rogers98379392014-02-24 16:53:16 -08001796 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001797 mirror::Object* thread_group = gRegistry->Get<mirror::Object*>(thread_group_id);
Ian Rogers98379392014-02-24 16:53:16 -08001798 CHECK(thread_group != nullptr);
1799 const char* old_cause = soa.Self()->StartAssertNoThreadSuspension("Debugger: GetThreadGroupParent");
1800 mirror::Class* c = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_ThreadGroup);
1801 CHECK(c != nullptr);
Brian Carlstromea46f952013-07-30 01:26:50 -07001802 mirror::ArtField* f = c->FindInstanceField("parent", "Ljava/lang/ThreadGroup;");
Elliott Hughes4e235312011-12-02 11:34:15 -08001803 CHECK(f != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001804 mirror::Object* parent = f->GetObject(thread_group);
Ian Rogers98379392014-02-24 16:53:16 -08001805 soa.Self()->EndAssertNoThreadSuspension(old_cause);
Elliott Hughes4e235312011-12-02 11:34:15 -08001806 return gRegistry->Add(parent);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001807}
1808
1809JDWP::ObjectId Dbg::GetSystemThreadGroupId() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001810 ScopedObjectAccessUnchecked soa(Thread::Current());
Brian Carlstromea46f952013-07-30 01:26:50 -07001811 mirror::ArtField* f = soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_systemThreadGroup);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001812 mirror::Object* group = f->GetObject(f->GetDeclaringClass());
Ian Rogers365c1022012-06-22 15:05:28 -07001813 return gRegistry->Add(group);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001814}
1815
1816JDWP::ObjectId Dbg::GetMainThreadGroupId() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001817 ScopedObjectAccess soa(Thread::Current());
Brian Carlstromea46f952013-07-30 01:26:50 -07001818 mirror::ArtField* f = soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_mainThreadGroup);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001819 mirror::Object* group = f->GetObject(f->GetDeclaringClass());
Ian Rogers365c1022012-06-22 15:05:28 -07001820 return gRegistry->Add(group);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001821}
1822
Jeff Hao920af3e2013-08-28 15:46:38 -07001823JDWP::JdwpThreadStatus Dbg::ToJdwpThreadStatus(ThreadState state) {
1824 switch (state) {
1825 case kBlocked:
1826 return JDWP::TS_MONITOR;
1827 case kNative:
1828 case kRunnable:
1829 case kSuspended:
1830 return JDWP::TS_RUNNING;
1831 case kSleeping:
1832 return JDWP::TS_SLEEPING;
1833 case kStarting:
1834 case kTerminated:
1835 return JDWP::TS_ZOMBIE;
1836 case kTimedWaiting:
1837 case kWaitingForDebuggerSend:
1838 case kWaitingForDebuggerSuspension:
1839 case kWaitingForDebuggerToAttach:
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01001840 case kWaitingForDeoptimization:
Jeff Hao920af3e2013-08-28 15:46:38 -07001841 case kWaitingForGcToComplete:
1842 case kWaitingForCheckPointsToRun:
1843 case kWaitingForJniOnLoad:
1844 case kWaitingForSignalCatcherOutput:
1845 case kWaitingInMainDebuggerLoop:
1846 case kWaitingInMainSignalCatcherLoop:
1847 case kWaitingPerformingGc:
1848 case kWaiting:
1849 return JDWP::TS_WAIT;
1850 // Don't add a 'default' here so the compiler can spot incompatible enum changes.
1851 }
1852 LOG(FATAL) << "Unknown thread state: " << state;
1853 return JDWP::TS_ZOMBIE;
1854}
1855
Sebastien Hertz52d131d2014-03-13 16:17:40 +01001856JDWP::JdwpError Dbg::GetThreadStatus(JDWP::ObjectId thread_id, JDWP::JdwpThreadStatus* pThreadStatus,
1857 JDWP::JdwpSuspendStatus* pSuspendStatus) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001858 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes499c5132011-11-17 14:55:11 -08001859
Elliott Hughes9e0c1752013-01-09 14:02:58 -08001860 *pSuspendStatus = JDWP::SUSPEND_STATUS_NOT_SUSPENDED;
1861
Ian Rogers50b35e22012-10-04 10:09:15 -07001862 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001863 Thread* thread;
1864 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1865 if (error != JDWP::ERR_NONE) {
1866 if (error == JDWP::ERR_THREAD_NOT_ALIVE) {
1867 *pThreadStatus = JDWP::TS_ZOMBIE;
Elliott Hughes221229c2013-01-08 18:17:50 -08001868 return JDWP::ERR_NONE;
1869 }
1870 return error;
Elliott Hughes499c5132011-11-17 14:55:11 -08001871 }
1872
Elliott Hughes9e0c1752013-01-09 14:02:58 -08001873 if (IsSuspendedForDebugger(soa, thread)) {
1874 *pSuspendStatus = JDWP::SUSPEND_STATUS_SUSPENDED;
Elliott Hughes499c5132011-11-17 14:55:11 -08001875 }
1876
Jeff Hao920af3e2013-08-28 15:46:38 -07001877 *pThreadStatus = ToJdwpThreadStatus(thread->GetState());
Elliott Hughes221229c2013-01-08 18:17:50 -08001878 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001879}
1880
Elliott Hughes221229c2013-01-08 18:17:50 -08001881JDWP::JdwpError Dbg::GetThreadDebugSuspendCount(JDWP::ObjectId thread_id, JDWP::ExpandBuf* pReply) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001882 ScopedObjectAccess soa(Thread::Current());
Ian Rogers50b35e22012-10-04 10:09:15 -07001883 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001884 Thread* thread;
1885 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1886 if (error != JDWP::ERR_NONE) {
1887 return error;
Elliott Hughes2435a572012-02-17 16:07:41 -08001888 }
Ian Rogers50b35e22012-10-04 10:09:15 -07001889 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001890 expandBufAdd4BE(pReply, thread->GetDebugSuspendCount());
Elliott Hughes2435a572012-02-17 16:07:41 -08001891 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001892}
1893
Elliott Hughesf9501702013-01-11 11:22:27 -08001894JDWP::JdwpError Dbg::Interrupt(JDWP::ObjectId thread_id) {
1895 ScopedObjectAccess soa(Thread::Current());
1896 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
1897 Thread* thread;
1898 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1899 if (error != JDWP::ERR_NONE) {
1900 return error;
1901 }
1902 thread->Interrupt();
1903 return JDWP::ERR_NONE;
1904}
1905
Elliott Hughescaf76542012-06-28 16:08:22 -07001906void Dbg::GetThreads(JDWP::ObjectId thread_group_id, std::vector<JDWP::ObjectId>& thread_ids) {
Ian Rogers365c1022012-06-22 15:05:28 -07001907 class ThreadListVisitor {
1908 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001909 ThreadListVisitor(const ScopedObjectAccessUnchecked& soa, mirror::Object* desired_thread_group,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001910 std::vector<JDWP::ObjectId>& thread_ids)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001911 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
jeffhao0dfbb7e2012-11-28 15:26:03 -08001912 : soa_(soa), desired_thread_group_(desired_thread_group), thread_ids_(thread_ids) {}
Ian Rogers365c1022012-06-22 15:05:28 -07001913
Elliott Hughesa2155262011-11-16 16:26:58 -08001914 static void Visit(Thread* t, void* arg) {
1915 reinterpret_cast<ThreadListVisitor*>(arg)->Visit(t);
1916 }
1917
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001918 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1919 // annotalysis.
1920 void Visit(Thread* t) NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughesa2155262011-11-16 16:26:58 -08001921 if (t == Dbg::GetDebugThread()) {
1922 // Skip the JDWP thread. Some debuggers get bent out of shape when they can't suspend and
1923 // query all threads, so it's easier if we just don't tell them about this thread.
1924 return;
1925 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001926 mirror::Object* peer = t->GetPeer();
jeffhao0dfbb7e2012-11-28 15:26:03 -08001927 if (IsInDesiredThreadGroup(peer)) {
Ian Rogers120f1c72012-09-28 17:17:10 -07001928 thread_ids_.push_back(gRegistry->Add(peer));
Elliott Hughesa2155262011-11-16 16:26:58 -08001929 }
1930 }
1931
Ian Rogers365c1022012-06-22 15:05:28 -07001932 private:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001933 bool IsInDesiredThreadGroup(mirror::Object* peer)
jeffhao0dfbb7e2012-11-28 15:26:03 -08001934 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
jeffhao0dfbb7e2012-11-28 15:26:03 -08001935 // peer might be NULL if the thread is still starting up.
1936 if (peer == NULL) {
1937 // We can't tell the debugger about this thread yet.
1938 // TODO: if we identified threads to the debugger by their Thread*
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001939 // rather than their peer's mirror::Object*, we could fix this.
jeffhao0dfbb7e2012-11-28 15:26:03 -08001940 // Doing so might help us report ZOMBIE threads too.
1941 return false;
1942 }
jeffhaoc1e04902012-12-13 12:41:10 -08001943 // Do we want threads from all thread groups?
1944 if (desired_thread_group_ == NULL) {
1945 return true;
1946 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001947 mirror::Object* group = soa_.DecodeField(WellKnownClasses::java_lang_Thread_group)->GetObject(peer);
jeffhao0dfbb7e2012-11-28 15:26:03 -08001948 return (group == desired_thread_group_);
1949 }
1950
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07001951 const ScopedObjectAccessUnchecked& soa_;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001952 mirror::Object* const desired_thread_group_;
Elliott Hughescaf76542012-06-28 16:08:22 -07001953 std::vector<JDWP::ObjectId>& thread_ids_;
Elliott Hughesa2155262011-11-16 16:26:58 -08001954 };
1955
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001956 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001957 mirror::Object* thread_group = gRegistry->Get<mirror::Object*>(thread_group_id);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001958 ThreadListVisitor tlv(soa, thread_group, thread_ids);
Ian Rogers50b35e22012-10-04 10:09:15 -07001959 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughesf8349362012-06-18 15:00:06 -07001960 Runtime::Current()->GetThreadList()->ForEach(ThreadListVisitor::Visit, &tlv);
Elliott Hughescaf76542012-06-28 16:08:22 -07001961}
Elliott Hughesa2155262011-11-16 16:26:58 -08001962
Elliott Hughescaf76542012-06-28 16:08:22 -07001963void Dbg::GetChildThreadGroups(JDWP::ObjectId thread_group_id, std::vector<JDWP::ObjectId>& child_thread_group_ids) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001964 ScopedObjectAccess soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001965 mirror::Object* thread_group = gRegistry->Get<mirror::Object*>(thread_group_id);
Elliott Hughescaf76542012-06-28 16:08:22 -07001966
1967 // Get the ArrayList<ThreadGroup> "groups" out of this thread group...
Brian Carlstromea46f952013-07-30 01:26:50 -07001968 mirror::ArtField* groups_field = thread_group->GetClass()->FindInstanceField("groups", "Ljava/util/List;");
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001969 mirror::Object* groups_array_list = groups_field->GetObject(thread_group);
Elliott Hughescaf76542012-06-28 16:08:22 -07001970
1971 // Get the array and size out of the ArrayList<ThreadGroup>...
Brian Carlstromea46f952013-07-30 01:26:50 -07001972 mirror::ArtField* array_field = groups_array_list->GetClass()->FindInstanceField("array", "[Ljava/lang/Object;");
1973 mirror::ArtField* size_field = groups_array_list->GetClass()->FindInstanceField("size", "I");
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001974 mirror::ObjectArray<mirror::Object>* groups_array =
1975 array_field->GetObject(groups_array_list)->AsObjectArray<mirror::Object>();
Elliott Hughescaf76542012-06-28 16:08:22 -07001976 const int32_t size = size_field->GetInt(groups_array_list);
1977
1978 // Copy the first 'size' elements out of the array into the result.
1979 for (int32_t i = 0; i < size; ++i) {
1980 child_thread_group_ids.push_back(gRegistry->Add(groups_array->Get(i)));
Elliott Hughesa2155262011-11-16 16:26:58 -08001981 }
1982}
1983
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001984static int GetStackDepth(Thread* thread)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001985 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers0399dde2012-06-06 17:09:28 -07001986 struct CountStackDepthVisitor : public StackVisitor {
Brian Carlstrom93ba8932013-07-17 21:31:49 -07001987 explicit CountStackDepthVisitor(Thread* thread)
Ian Rogers7a22fa62013-01-23 12:16:16 -08001988 : StackVisitor(thread, NULL), depth(0) {}
Ian Rogers0399dde2012-06-06 17:09:28 -07001989
Elliott Hughes64f574f2013-02-20 14:57:12 -08001990 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1991 // annotalysis.
1992 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07001993 if (!GetMethod()->IsRuntimeMethod()) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -08001994 ++depth;
1995 }
Elliott Hughes530fa002012-03-12 11:44:49 -07001996 return true;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001997 }
1998 size_t depth;
1999 };
Elliott Hughes08fc03a2012-06-26 17:34:00 -07002000
Ian Rogers7a22fa62013-01-23 12:16:16 -08002001 CountStackDepthVisitor visitor(thread);
Ian Rogers0399dde2012-06-06 17:09:28 -07002002 visitor.WalkStack();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08002003 return visitor.depth;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002004}
2005
Elliott Hughes221229c2013-01-08 18:17:50 -08002006JDWP::JdwpError Dbg::GetThreadFrameCount(JDWP::ObjectId thread_id, size_t& result) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002007 ScopedObjectAccess soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08002008 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002009 Thread* thread;
2010 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
2011 if (error != JDWP::ERR_NONE) {
2012 return error;
2013 }
Elliott Hughesf15f4a02013-01-09 10:09:38 -08002014 if (!IsSuspendedForDebugger(soa, thread)) {
2015 return JDWP::ERR_THREAD_NOT_SUSPENDED;
2016 }
Elliott Hughes221229c2013-01-08 18:17:50 -08002017 result = GetStackDepth(thread);
2018 return JDWP::ERR_NONE;
Elliott Hughes86964332012-02-15 19:37:42 -08002019}
2020
Ian Rogers306057f2012-11-26 12:45:53 -08002021JDWP::JdwpError Dbg::GetThreadFrames(JDWP::ObjectId thread_id, size_t start_frame,
2022 size_t frame_count, JDWP::ExpandBuf* buf) {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002023 class GetFrameVisitor : public StackVisitor {
2024 public:
Ian Rogers7a22fa62013-01-23 12:16:16 -08002025 GetFrameVisitor(Thread* thread, size_t start_frame, size_t frame_count, JDWP::ExpandBuf* buf)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002026 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08002027 : StackVisitor(thread, NULL), depth_(0),
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002028 start_frame_(start_frame), frame_count_(frame_count), buf_(buf) {
2029 expandBufAdd4BE(buf_, frame_count_);
Elliott Hughes03181a82011-11-17 17:22:21 -08002030 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002031
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002032 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2033 // annotalysis.
2034 virtual bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07002035 if (GetMethod()->IsRuntimeMethod()) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07002036 return true; // The debugger can't do anything useful with a frame that has no Method*.
Elliott Hughes03181a82011-11-17 17:22:21 -08002037 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002038 if (depth_ >= start_frame_ + frame_count_) {
Elliott Hughes530fa002012-03-12 11:44:49 -07002039 return false;
Elliott Hughes03181a82011-11-17 17:22:21 -08002040 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002041 if (depth_ >= start_frame_) {
2042 JDWP::FrameId frame_id(GetFrameId());
2043 JDWP::JdwpLocation location;
2044 SetLocation(location, GetMethod(), GetDexPc());
Ian Rogersef7d42f2014-01-06 12:55:46 -08002045 VLOG(jdwp) << StringPrintf(" Frame %3zd: id=%3" PRIu64 " ", depth_, frame_id) << location;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002046 expandBufAdd8BE(buf_, frame_id);
2047 expandBufAddLocation(buf_, location);
2048 }
2049 ++depth_;
Elliott Hughes530fa002012-03-12 11:44:49 -07002050 return true;
Elliott Hughes03181a82011-11-17 17:22:21 -08002051 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002052
2053 private:
2054 size_t depth_;
2055 const size_t start_frame_;
2056 const size_t frame_count_;
2057 JDWP::ExpandBuf* buf_;
Elliott Hughes03181a82011-11-17 17:22:21 -08002058 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002059
2060 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08002061 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002062 Thread* thread;
2063 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
2064 if (error != JDWP::ERR_NONE) {
2065 return error;
2066 }
Elliott Hughesf15f4a02013-01-09 10:09:38 -08002067 if (!IsSuspendedForDebugger(soa, thread)) {
2068 return JDWP::ERR_THREAD_NOT_SUSPENDED;
2069 }
Ian Rogers7a22fa62013-01-23 12:16:16 -08002070 GetFrameVisitor visitor(thread, start_frame, frame_count, buf);
Ian Rogers0399dde2012-06-06 17:09:28 -07002071 visitor.WalkStack();
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002072 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002073}
2074
2075JDWP::ObjectId Dbg::GetThreadSelfId() {
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07002076 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogerscfaa4552012-11-26 21:00:08 -08002077 return gRegistry->Add(soa.Self()->GetPeer());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002078}
2079
Elliott Hughes475fc232011-10-25 15:00:35 -07002080void Dbg::SuspendVM() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002081 Runtime::Current()->GetThreadList()->SuspendAllForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002082}
2083
2084void Dbg::ResumeVM() {
Elliott Hughesc61a2672012-06-21 14:52:29 -07002085 Runtime::Current()->GetThreadList()->UndoDebuggerSuspensions();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002086}
2087
Elliott Hughes221229c2013-01-08 18:17:50 -08002088JDWP::JdwpError Dbg::SuspendThread(JDWP::ObjectId thread_id, bool request_suspension) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002089 ScopedLocalRef<jobject> peer(Thread::Current()->GetJniEnv(), NULL);
2090 {
2091 ScopedObjectAccess soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002092 peer.reset(soa.AddLocalReference<jobject>(gRegistry->Get<mirror::Object*>(thread_id)));
Elliott Hughes4e235312011-12-02 11:34:15 -08002093 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002094 if (peer.get() == NULL) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002095 return JDWP::ERR_THREAD_NOT_ALIVE;
2096 }
2097 // Suspend thread to build stack trace.
Elliott Hughesf327e072013-01-09 16:01:26 -08002098 bool timed_out;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07002099 Thread* thread = ThreadList::SuspendThreadByPeer(peer.get(), request_suspension, true,
2100 &timed_out);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002101 if (thread != NULL) {
2102 return JDWP::ERR_NONE;
Elliott Hughesf327e072013-01-09 16:01:26 -08002103 } else if (timed_out) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002104 return JDWP::ERR_INTERNAL;
2105 } else {
2106 return JDWP::ERR_THREAD_NOT_ALIVE;
2107 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002108}
2109
Elliott Hughes221229c2013-01-08 18:17:50 -08002110void Dbg::ResumeThread(JDWP::ObjectId thread_id) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002111 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002112 mirror::Object* peer = gRegistry->Get<mirror::Object*>(thread_id);
jeffhaoa77f0f62012-12-05 17:19:31 -08002113 Thread* thread;
2114 {
2115 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
2116 thread = Thread::FromManagedThread(soa, peer);
2117 }
Elliott Hughes4e235312011-12-02 11:34:15 -08002118 if (thread == NULL) {
2119 LOG(WARNING) << "No such thread for resume: " << peer;
2120 return;
2121 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002122 bool needs_resume;
2123 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002124 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002125 needs_resume = thread->GetSuspendCount() > 0;
2126 }
2127 if (needs_resume) {
Elliott Hughes546b9862012-06-20 16:06:13 -07002128 Runtime::Current()->GetThreadList()->Resume(thread, true);
2129 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002130}
2131
2132void Dbg::SuspendSelf() {
Elliott Hughes475fc232011-10-25 15:00:35 -07002133 Runtime::Current()->GetThreadList()->SuspendSelfForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002134}
2135
Ian Rogers0399dde2012-06-06 17:09:28 -07002136struct GetThisVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -08002137 GetThisVisitor(Thread* thread, Context* context, JDWP::FrameId frame_id)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002138 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08002139 : StackVisitor(thread, context), this_object(NULL), frame_id(frame_id) {}
Ian Rogers0399dde2012-06-06 17:09:28 -07002140
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002141 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2142 // annotalysis.
2143 virtual bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002144 if (frame_id != GetFrameId()) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002145 return true; // continue
Ian Rogers0399dde2012-06-06 17:09:28 -07002146 } else {
Ian Rogers62d6c772013-02-27 08:32:07 -08002147 this_object = GetThisObject();
2148 return false;
Ian Rogers0399dde2012-06-06 17:09:28 -07002149 }
Elliott Hughes86b00102011-12-05 17:54:26 -08002150 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002151
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002152 mirror::Object* this_object;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002153 JDWP::FrameId frame_id;
Ian Rogers0399dde2012-06-06 17:09:28 -07002154};
2155
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002156JDWP::JdwpError Dbg::GetThisObject(JDWP::ObjectId thread_id, JDWP::FrameId frame_id,
2157 JDWP::ObjectId* result) {
2158 ScopedObjectAccessUnchecked soa(Thread::Current());
2159 Thread* thread;
2160 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002161 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002162 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
2163 if (error != JDWP::ERR_NONE) {
2164 return error;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002165 }
Elliott Hughes9e0c1752013-01-09 14:02:58 -08002166 if (!IsSuspendedForDebugger(soa, thread)) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002167 return JDWP::ERR_THREAD_NOT_SUSPENDED;
2168 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002169 }
Elliott Hughescaf76542012-06-28 16:08:22 -07002170 UniquePtr<Context> context(Context::Create());
Ian Rogers7a22fa62013-01-23 12:16:16 -08002171 GetThisVisitor visitor(thread, context.get(), frame_id);
Ian Rogers0399dde2012-06-06 17:09:28 -07002172 visitor.WalkStack();
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07002173 *result = gRegistry->Add(visitor.this_object);
2174 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002175}
2176
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002177JDWP::JdwpError Dbg::GetLocalValue(JDWP::ObjectId thread_id, JDWP::FrameId frame_id, int slot,
2178 JDWP::JdwpTag tag, uint8_t* buf, size_t width) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002179 struct GetLocalVisitor : public StackVisitor {
Ian Rogers98379392014-02-24 16:53:16 -08002180 GetLocalVisitor(const ScopedObjectAccessUnchecked& soa, Thread* thread, Context* context,
2181 JDWP::FrameId frame_id, int slot, JDWP::JdwpTag tag, uint8_t* buf, size_t width)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002182 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers98379392014-02-24 16:53:16 -08002183 : StackVisitor(thread, context), soa_(soa), frame_id_(frame_id), slot_(slot), tag_(tag),
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002184 buf_(buf), width_(width), error_(JDWP::ERR_NONE) {}
Ian Rogersca190662012-06-26 15:45:57 -07002185
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002186 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2187 // annotalysis.
2188 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07002189 if (GetFrameId() != frame_id_) {
2190 return true; // Not our frame, carry on.
Elliott Hughesdbb40792011-11-18 17:05:22 -08002191 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002192 // TODO: check that the tag is compatible with the actual type of the slot!
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002193 // TODO: check slot is valid for this method or return INVALID_SLOT error.
Brian Carlstromea46f952013-07-30 01:26:50 -07002194 mirror::ArtMethod* m = GetMethod();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002195 if (m->IsNative()) {
2196 // We can't read local value from native method.
2197 error_ = JDWP::ERR_OPAQUE_FRAME;
2198 return false;
2199 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002200 uint16_t reg = DemangleSlot(slot_, m);
Elliott Hughesdbb40792011-11-18 17:05:22 -08002201
Ian Rogers0399dde2012-06-06 17:09:28 -07002202 switch (tag_) {
2203 case JDWP::JT_BOOLEAN:
2204 {
2205 CHECK_EQ(width_, 1U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002206 uint32_t intVal = GetVReg(m, reg, kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002207 VLOG(jdwp) << "get boolean local " << reg << " = " << intVal;
2208 JDWP::Set1(buf_+1, intVal != 0);
2209 }
2210 break;
2211 case JDWP::JT_BYTE:
2212 {
2213 CHECK_EQ(width_, 1U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002214 uint32_t intVal = GetVReg(m, reg, kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002215 VLOG(jdwp) << "get byte local " << reg << " = " << intVal;
2216 JDWP::Set1(buf_+1, intVal);
2217 }
2218 break;
2219 case JDWP::JT_SHORT:
2220 case JDWP::JT_CHAR:
2221 {
2222 CHECK_EQ(width_, 2U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002223 uint32_t intVal = GetVReg(m, reg, kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002224 VLOG(jdwp) << "get short/char local " << reg << " = " << intVal;
2225 JDWP::Set2BE(buf_+1, intVal);
2226 }
2227 break;
2228 case JDWP::JT_INT:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002229 {
2230 CHECK_EQ(width_, 4U);
2231 uint32_t intVal = GetVReg(m, reg, kIntVReg);
2232 VLOG(jdwp) << "get int local " << reg << " = " << intVal;
2233 JDWP::Set4BE(buf_+1, intVal);
2234 }
2235 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002236 case JDWP::JT_FLOAT:
2237 {
2238 CHECK_EQ(width_, 4U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002239 uint32_t intVal = GetVReg(m, reg, kFloatVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002240 VLOG(jdwp) << "get int/float local " << reg << " = " << intVal;
2241 JDWP::Set4BE(buf_+1, intVal);
2242 }
2243 break;
2244 case JDWP::JT_ARRAY:
2245 {
2246 CHECK_EQ(width_, sizeof(JDWP::ObjectId));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002247 mirror::Object* o = reinterpret_cast<mirror::Object*>(GetVReg(m, reg, kReferenceVReg));
Ian Rogers0399dde2012-06-06 17:09:28 -07002248 VLOG(jdwp) << "get array local " << reg << " = " << o;
Mathieu Chartier590fee92013-09-13 13:46:47 -07002249 if (!Runtime::Current()->GetHeap()->IsValidObjectAddress(o)) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002250 LOG(FATAL) << "Register " << reg << " expected to hold array: " << o;
2251 }
2252 JDWP::SetObjectId(buf_+1, gRegistry->Add(o));
2253 }
2254 break;
2255 case JDWP::JT_CLASS_LOADER:
2256 case JDWP::JT_CLASS_OBJECT:
2257 case JDWP::JT_OBJECT:
2258 case JDWP::JT_STRING:
2259 case JDWP::JT_THREAD:
2260 case JDWP::JT_THREAD_GROUP:
2261 {
2262 CHECK_EQ(width_, sizeof(JDWP::ObjectId));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002263 mirror::Object* o = reinterpret_cast<mirror::Object*>(GetVReg(m, reg, kReferenceVReg));
Ian Rogers0399dde2012-06-06 17:09:28 -07002264 VLOG(jdwp) << "get object local " << reg << " = " << o;
Mathieu Chartier590fee92013-09-13 13:46:47 -07002265 if (!Runtime::Current()->GetHeap()->IsValidObjectAddress(o)) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002266 LOG(FATAL) << "Register " << reg << " expected to hold object: " << o;
2267 }
Ian Rogers98379392014-02-24 16:53:16 -08002268 tag_ = TagFromObject(soa_, o);
Ian Rogers0399dde2012-06-06 17:09:28 -07002269 JDWP::SetObjectId(buf_+1, gRegistry->Add(o));
2270 }
2271 break;
2272 case JDWP::JT_DOUBLE:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002273 {
2274 CHECK_EQ(width_, 8U);
2275 uint32_t lo = GetVReg(m, reg, kDoubleLoVReg);
2276 uint64_t hi = GetVReg(m, reg + 1, kDoubleHiVReg);
2277 uint64_t longVal = (hi << 32) | lo;
2278 VLOG(jdwp) << "get double/long local " << hi << ":" << lo << " = " << longVal;
2279 JDWP::Set8BE(buf_+1, longVal);
2280 }
2281 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002282 case JDWP::JT_LONG:
2283 {
2284 CHECK_EQ(width_, 8U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002285 uint32_t lo = GetVReg(m, reg, kLongLoVReg);
2286 uint64_t hi = GetVReg(m, reg + 1, kLongHiVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002287 uint64_t longVal = (hi << 32) | lo;
2288 VLOG(jdwp) << "get double/long local " << hi << ":" << lo << " = " << longVal;
2289 JDWP::Set8BE(buf_+1, longVal);
2290 }
2291 break;
2292 default:
2293 LOG(FATAL) << "Unknown tag " << tag_;
2294 break;
2295 }
2296
2297 // Prepend tag, which may have been updated.
2298 JDWP::Set1(buf_, tag_);
2299 return false;
2300 }
Ian Rogers98379392014-02-24 16:53:16 -08002301 const ScopedObjectAccessUnchecked& soa_;
Ian Rogers0399dde2012-06-06 17:09:28 -07002302 const JDWP::FrameId frame_id_;
2303 const int slot_;
2304 JDWP::JdwpTag tag_;
2305 uint8_t* const buf_;
2306 const size_t width_;
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002307 JDWP::JdwpError error_;
Ian Rogers0399dde2012-06-06 17:09:28 -07002308 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002309
2310 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08002311 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002312 Thread* thread;
2313 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
2314 if (error != JDWP::ERR_NONE) {
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002315 return error;
Elliott Hughes221229c2013-01-08 18:17:50 -08002316 }
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002317 // TODO check thread is suspended by the debugger ?
Ian Rogers0399dde2012-06-06 17:09:28 -07002318 UniquePtr<Context> context(Context::Create());
Ian Rogers98379392014-02-24 16:53:16 -08002319 GetLocalVisitor visitor(soa, thread, context.get(), frame_id, slot, tag, buf, width);
Ian Rogers0399dde2012-06-06 17:09:28 -07002320 visitor.WalkStack();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002321 return visitor.error_;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002322}
2323
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002324JDWP::JdwpError Dbg::SetLocalValue(JDWP::ObjectId thread_id, JDWP::FrameId frame_id, int slot,
2325 JDWP::JdwpTag tag, uint64_t value, size_t width) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002326 struct SetLocalVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -08002327 SetLocalVisitor(Thread* thread, Context* context,
Ian Rogers0399dde2012-06-06 17:09:28 -07002328 JDWP::FrameId frame_id, int slot, JDWP::JdwpTag tag, uint64_t value,
Ian Rogersca190662012-06-26 15:45:57 -07002329 size_t width)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002330 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08002331 : StackVisitor(thread, context),
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002332 frame_id_(frame_id), slot_(slot), tag_(tag), value_(value), width_(width),
2333 error_(JDWP::ERR_NONE) {}
Ian Rogersca190662012-06-26 15:45:57 -07002334
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002335 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2336 // annotalysis.
2337 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07002338 if (GetFrameId() != frame_id_) {
2339 return true; // Not our frame, carry on.
2340 }
2341 // TODO: check that the tag is compatible with the actual type of the slot!
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002342 // TODO: check slot is valid for this method or return INVALID_SLOT error.
Brian Carlstromea46f952013-07-30 01:26:50 -07002343 mirror::ArtMethod* m = GetMethod();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002344 if (m->IsNative()) {
2345 // We can't read local value from native method.
2346 error_ = JDWP::ERR_OPAQUE_FRAME;
2347 return false;
2348 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002349 uint16_t reg = DemangleSlot(slot_, m);
2350
2351 switch (tag_) {
2352 case JDWP::JT_BOOLEAN:
2353 case JDWP::JT_BYTE:
2354 CHECK_EQ(width_, 1U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002355 SetVReg(m, reg, static_cast<uint32_t>(value_), kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002356 break;
2357 case JDWP::JT_SHORT:
2358 case JDWP::JT_CHAR:
2359 CHECK_EQ(width_, 2U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002360 SetVReg(m, reg, static_cast<uint32_t>(value_), kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002361 break;
2362 case JDWP::JT_INT:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002363 CHECK_EQ(width_, 4U);
2364 SetVReg(m, reg, static_cast<uint32_t>(value_), kIntVReg);
2365 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002366 case JDWP::JT_FLOAT:
2367 CHECK_EQ(width_, 4U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002368 SetVReg(m, reg, static_cast<uint32_t>(value_), kFloatVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002369 break;
2370 case JDWP::JT_ARRAY:
2371 case JDWP::JT_OBJECT:
2372 case JDWP::JT_STRING:
2373 {
2374 CHECK_EQ(width_, sizeof(JDWP::ObjectId));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002375 mirror::Object* o = gRegistry->Get<mirror::Object*>(static_cast<JDWP::ObjectId>(value_));
Elliott Hughes64f574f2013-02-20 14:57:12 -08002376 if (o == ObjectRegistry::kInvalidObject) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002377 UNIMPLEMENTED(FATAL) << "return an error code when given an invalid object to store";
2378 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002379 SetVReg(m, reg, static_cast<uint32_t>(reinterpret_cast<uintptr_t>(o)), kReferenceVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002380 }
2381 break;
2382 case JDWP::JT_DOUBLE:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002383 CHECK_EQ(width_, 8U);
2384 SetVReg(m, reg, static_cast<uint32_t>(value_), kDoubleLoVReg);
2385 SetVReg(m, reg + 1, static_cast<uint32_t>(value_ >> 32), kDoubleHiVReg);
2386 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002387 case JDWP::JT_LONG:
2388 CHECK_EQ(width_, 8U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002389 SetVReg(m, reg, static_cast<uint32_t>(value_), kLongLoVReg);
2390 SetVReg(m, reg + 1, static_cast<uint32_t>(value_ >> 32), kLongHiVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002391 break;
2392 default:
2393 LOG(FATAL) << "Unknown tag " << tag_;
2394 break;
2395 }
2396 return false;
2397 }
2398
2399 const JDWP::FrameId frame_id_;
2400 const int slot_;
2401 const JDWP::JdwpTag tag_;
2402 const uint64_t value_;
2403 const size_t width_;
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002404 JDWP::JdwpError error_;
Ian Rogers0399dde2012-06-06 17:09:28 -07002405 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002406
2407 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08002408 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002409 Thread* thread;
2410 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
2411 if (error != JDWP::ERR_NONE) {
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002412 return error;
Elliott Hughes221229c2013-01-08 18:17:50 -08002413 }
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002414 // TODO check thread is suspended by the debugger ?
Elliott Hughes08fc03a2012-06-26 17:34:00 -07002415 UniquePtr<Context> context(Context::Create());
Ian Rogers7a22fa62013-01-23 12:16:16 -08002416 SetLocalVisitor visitor(thread, context.get(), frame_id, slot, tag, value, width);
Ian Rogers0399dde2012-06-06 17:09:28 -07002417 visitor.WalkStack();
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002418 return visitor.error_;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002419}
2420
Ian Rogersef7d42f2014-01-06 12:55:46 -08002421void Dbg::PostLocationEvent(mirror::ArtMethod* m, int dex_pc, mirror::Object* this_object,
Jeff Hao579b0242013-11-18 13:16:49 -08002422 int event_flags, const JValue* return_value) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002423 JDWP::JdwpLocation location;
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +01002424 SetLocation(location, m, dex_pc);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002425
Elliott Hughes64f574f2013-02-20 14:57:12 -08002426 // If 'this_object' isn't already in the registry, we know that we're not looking for it,
2427 // so there's no point adding it to the registry and burning through ids.
2428 JDWP::ObjectId this_id = 0;
2429 if (gRegistry->Contains(this_object)) {
2430 this_id = gRegistry->Add(this_object);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002431 }
Jeff Hao579b0242013-11-18 13:16:49 -08002432 gJdwpState->PostLocationEvent(&location, this_id, event_flags, return_value);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002433}
2434
Ian Rogers62d6c772013-02-27 08:32:07 -08002435void Dbg::PostException(Thread* thread, const ThrowLocation& throw_location,
Brian Carlstromea46f952013-07-30 01:26:50 -07002436 mirror::ArtMethod* catch_method,
Elliott Hughes64f574f2013-02-20 14:57:12 -08002437 uint32_t catch_dex_pc, mirror::Throwable* exception_object) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002438 if (!IsDebuggerActive()) {
Ian Rogers0ad5bb82011-12-07 10:16:32 -08002439 return;
2440 }
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002441
Ian Rogers62d6c772013-02-27 08:32:07 -08002442 JDWP::JdwpLocation jdwp_throw_location;
2443 SetLocation(jdwp_throw_location, throw_location.GetMethod(), throw_location.GetDexPc());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002444 JDWP::JdwpLocation catch_location;
Elliott Hughescaf76542012-06-28 16:08:22 -07002445 SetLocation(catch_location, catch_method, catch_dex_pc);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002446
2447 // We need 'this' for InstanceOnly filters.
Ian Rogers62d6c772013-02-27 08:32:07 -08002448 JDWP::ObjectId this_id = gRegistry->Add(throw_location.GetThis());
Elliott Hughes64f574f2013-02-20 14:57:12 -08002449 JDWP::ObjectId exception_id = gRegistry->Add(exception_object);
2450 JDWP::RefTypeId exception_class_id = gRegistry->AddRefType(exception_object->GetClass());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002451
Ian Rogers62d6c772013-02-27 08:32:07 -08002452 gJdwpState->PostException(&jdwp_throw_location, exception_id, exception_class_id, &catch_location,
2453 this_id);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002454}
2455
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002456void Dbg::PostClassPrepare(mirror::Class* c) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002457 if (!IsDebuggerActive()) {
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002458 return;
2459 }
2460
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08002461 // OLD-TODO - we currently always send both "verified" and "prepared" since
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002462 // debuggers seem to like that. There might be some advantage to honesty,
2463 // since the class may not yet be verified.
2464 int state = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
2465 JDWP::JdwpTypeTag tag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
Ian Rogersfc0e94b2013-09-23 23:51:32 -07002466 gJdwpState->PostClassPrepare(tag, gRegistry->Add(c),
Ian Rogersdfb325e2013-10-30 01:00:44 -07002467 ClassHelper(c).GetDescriptor(), state);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002468}
2469
Ian Rogers62d6c772013-02-27 08:32:07 -08002470void Dbg::UpdateDebugger(Thread* thread, mirror::Object* this_object,
Ian Rogersef7d42f2014-01-06 12:55:46 -08002471 mirror::ArtMethod* m, uint32_t dex_pc) {
Ian Rogers62d6c772013-02-27 08:32:07 -08002472 if (!IsDebuggerActive() || dex_pc == static_cast<uint32_t>(-2) /* fake method exit */) {
Elliott Hughes2aa2e392012-02-17 17:15:43 -08002473 return;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002474 }
2475
Elliott Hughes2aa2e392012-02-17 17:15:43 -08002476 int event_flags = 0;
2477
Elliott Hughes86964332012-02-15 19:37:42 -08002478 if (IsBreakpoint(m, dex_pc)) {
2479 event_flags |= kBreakpoint;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002480 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002481
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002482 // If the debugger is single-stepping one of our threads, check to
2483 // see if we're that thread and we've reached a step point.
2484 const SingleStepControl* single_step_control = thread->GetSingleStepControl();
2485 DCHECK(single_step_control != nullptr);
2486 if (single_step_control->is_active) {
2487 CHECK(!m->IsNative());
2488 if (single_step_control->step_depth == JDWP::SD_INTO) {
2489 // Step into method calls. We break when the line number
2490 // or method pointer changes. If we're in SS_MIN mode, we
2491 // always stop.
2492 if (single_step_control->method != m) {
2493 event_flags |= kSingleStep;
2494 VLOG(jdwp) << "SS new method";
2495 } else if (single_step_control->step_size == JDWP::SS_MIN) {
2496 event_flags |= kSingleStep;
2497 VLOG(jdwp) << "SS new instruction";
2498 } else if (single_step_control->dex_pcs.find(dex_pc) == single_step_control->dex_pcs.end()) {
2499 event_flags |= kSingleStep;
2500 VLOG(jdwp) << "SS new line";
2501 }
2502 } else if (single_step_control->step_depth == JDWP::SD_OVER) {
2503 // Step over method calls. We break when the line number is
2504 // different and the frame depth is <= the original frame
2505 // depth. (We can't just compare on the method, because we
2506 // might get unrolled past it by an exception, and it's tricky
2507 // to identify recursion.)
2508
2509 int stack_depth = GetStackDepth(thread);
2510
2511 if (stack_depth < single_step_control->stack_depth) {
2512 // Popped up one or more frames, always trigger.
2513 event_flags |= kSingleStep;
2514 VLOG(jdwp) << "SS method pop";
2515 } else if (stack_depth == single_step_control->stack_depth) {
2516 // Same depth, see if we moved.
2517 if (single_step_control->step_size == JDWP::SS_MIN) {
Elliott Hughes86964332012-02-15 19:37:42 -08002518 event_flags |= kSingleStep;
2519 VLOG(jdwp) << "SS new instruction";
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002520 } else if (single_step_control->dex_pcs.find(dex_pc) == single_step_control->dex_pcs.end()) {
Elliott Hughes2435a572012-02-17 16:07:41 -08002521 event_flags |= kSingleStep;
2522 VLOG(jdwp) << "SS new line";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002523 }
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002524 }
2525 } else {
2526 CHECK_EQ(single_step_control->step_depth, JDWP::SD_OUT);
2527 // Return from the current method. We break when the frame
2528 // depth pops up.
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002529
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002530 // This differs from the "method exit" break in that it stops
2531 // with the PC at the next instruction in the returned-to
2532 // function, rather than the end of the returning function.
Elliott Hughes86964332012-02-15 19:37:42 -08002533
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002534 int stack_depth = GetStackDepth(thread);
2535 if (stack_depth < single_step_control->stack_depth) {
2536 event_flags |= kSingleStep;
2537 VLOG(jdwp) << "SS method pop";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002538 }
2539 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002540 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002541
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002542 // If there's something interesting going on, see if it matches one
2543 // of the debugger filters.
2544 if (event_flags != 0) {
Jeff Hao579b0242013-11-18 13:16:49 -08002545 Dbg::PostLocationEvent(m, dex_pc, this_object, event_flags, nullptr);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002546 }
2547}
2548
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002549static void ProcessDeoptimizationRequests()
2550 LOCKS_EXCLUDED(Locks::deoptimization_lock_)
2551 EXCLUSIVE_LOCKS_REQUIRED(Locks::mutator_lock_) {
2552 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
2553 MutexLock mu(Thread::Current(), *Locks::deoptimization_lock_);
2554 instrumentation::Instrumentation* instrumentation = Runtime::Current()->GetInstrumentation();
2555 for (const MethodInstrumentationRequest& request : gDeoptimizationRequests) {
2556 mirror::ArtMethod* const method = request.method;
2557 if (method != nullptr) {
2558 // Selective deoptimization.
2559 if (request.deoptimize) {
2560 VLOG(jdwp) << "Deoptimize method " << PrettyMethod(method);
2561 instrumentation->Deoptimize(method);
2562 } else {
2563 VLOG(jdwp) << "Undeoptimize method " << PrettyMethod(method);
2564 instrumentation->Undeoptimize(method);
2565 }
2566 } else {
2567 // Full deoptimization.
2568 if (request.deoptimize) {
2569 VLOG(jdwp) << "Deoptimize the world";
2570 instrumentation->DeoptimizeEverything();
2571 } else {
2572 VLOG(jdwp) << "Undeoptimize the world";
2573 instrumentation->UndeoptimizeEverything();
2574 }
2575 }
2576 }
2577 gDeoptimizationRequests.clear();
2578}
2579
2580// Process deoptimization requests after suspending all mutator threads.
2581void Dbg::ManageDeoptimization() {
2582 Thread* const self = Thread::Current();
2583 {
2584 // Avoid suspend/resume if there is no pending request.
2585 MutexLock mu(self, *Locks::deoptimization_lock_);
2586 if (gDeoptimizationRequests.empty()) {
2587 return;
2588 }
2589 }
2590 CHECK_EQ(self->GetState(), kRunnable);
2591 self->TransitionFromRunnableToSuspended(kWaitingForDeoptimization);
2592 // We need to suspend mutator threads first.
2593 Runtime* const runtime = Runtime::Current();
2594 runtime->GetThreadList()->SuspendAll();
2595 const ThreadState old_state = self->SetStateUnsafe(kRunnable);
2596 ProcessDeoptimizationRequests();
2597 CHECK_EQ(self->SetStateUnsafe(old_state), kRunnable);
2598 runtime->GetThreadList()->ResumeAll();
2599 self->TransitionFromSuspendedToRunnable();
2600}
2601
2602// Enable full deoptimization.
2603void Dbg::EnableFullDeoptimization() {
2604 MutexLock mu(Thread::Current(), *Locks::deoptimization_lock_);
2605 VLOG(jdwp) << "Request full deoptimization";
2606 gDeoptimizationRequests.push_back(MethodInstrumentationRequest(true, nullptr));
2607}
2608
2609// Disable full deoptimization.
2610void Dbg::DisableFullDeoptimization() {
2611 MutexLock mu(Thread::Current(), *Locks::deoptimization_lock_);
2612 VLOG(jdwp) << "Request full undeoptimization";
2613 gDeoptimizationRequests.push_back(MethodInstrumentationRequest(false, nullptr));
2614}
2615
Elliott Hughes86964332012-02-15 19:37:42 -08002616void Dbg::WatchLocation(const JDWP::JdwpLocation* location) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002617 bool need_deoptimization = true;
Brian Carlstromea46f952013-07-30 01:26:50 -07002618 mirror::ArtMethod* m = FromMethodId(location->method_id);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002619 {
2620 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
2621
2622 // If there is no breakpoint on this method yet, we need to deoptimize it.
2623 for (const Breakpoint& breakpoint : gBreakpoints) {
2624 if (breakpoint.method == m) {
2625 // We already set a breakpoint on this method, hence we deoptimized it.
2626 DCHECK(Runtime::Current()->GetInstrumentation()->IsDeoptimized(m));
2627 need_deoptimization = false;
2628 break;
2629 }
2630 }
2631
2632 gBreakpoints.push_back(Breakpoint(m, location->dex_pc));
2633 VLOG(jdwp) << "Set breakpoint #" << (gBreakpoints.size() - 1) << ": " << gBreakpoints[gBreakpoints.size() - 1];
2634 }
2635
2636 if (need_deoptimization) {
2637 // Request its deoptimization. This will be done after updating the JDWP event list.
2638 MutexLock mu(Thread::Current(), *Locks::deoptimization_lock_);
2639 gDeoptimizationRequests.push_back(MethodInstrumentationRequest(true, m));
2640 VLOG(jdwp) << "Request deoptimization of " << PrettyMethod(m);
2641 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002642}
2643
Elliott Hughes86964332012-02-15 19:37:42 -08002644void Dbg::UnwatchLocation(const JDWP::JdwpLocation* location) {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002645 bool can_undeoptimize = true;
Brian Carlstromea46f952013-07-30 01:26:50 -07002646 mirror::ArtMethod* m = FromMethodId(location->method_id);
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002647 DCHECK(Runtime::Current()->GetInstrumentation()->IsDeoptimized(m));
2648 {
2649 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
2650 for (size_t i = 0, e = gBreakpoints.size(); i < e; ++i) {
2651 if (gBreakpoints[i].method == m && gBreakpoints[i].dex_pc == location->dex_pc) {
2652 VLOG(jdwp) << "Removed breakpoint #" << i << ": " << gBreakpoints[i];
2653 gBreakpoints.erase(gBreakpoints.begin() + i);
2654 break;
2655 }
Elliott Hughes86964332012-02-15 19:37:42 -08002656 }
Sebastien Hertz138dbfc2013-12-04 18:15:25 +01002657
2658 // If there is no breakpoint on this method, we can undeoptimize it.
2659 for (const Breakpoint& breakpoint : gBreakpoints) {
2660 if (breakpoint.method == m) {
2661 can_undeoptimize = false;
2662 break;
2663 }
2664 }
2665 }
2666
2667 if (can_undeoptimize) {
2668 // Request its undeoptimization. This will be done after updating the JDWP event list.
2669 MutexLock mu(Thread::Current(), *Locks::deoptimization_lock_);
2670 gDeoptimizationRequests.push_back(MethodInstrumentationRequest(false, m));
2671 VLOG(jdwp) << "Request undeoptimization of " << PrettyMethod(m);
Elliott Hughes86964332012-02-15 19:37:42 -08002672 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002673}
2674
Jeff Hao449db332013-04-12 18:30:52 -07002675// Scoped utility class to suspend a thread so that we may do tasks such as walk its stack. Doesn't
2676// cause suspension if the thread is the current thread.
2677class ScopedThreadSuspension {
2678 public:
Ian Rogers33e95662013-05-20 20:29:14 -07002679 ScopedThreadSuspension(Thread* self, JDWP::ObjectId thread_id)
Sebastien Hertz52d131d2014-03-13 16:17:40 +01002680 LOCKS_EXCLUDED(Locks::thread_list_lock_)
Ian Rogers33e95662013-05-20 20:29:14 -07002681 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) :
Jeff Hao449db332013-04-12 18:30:52 -07002682 thread_(NULL),
2683 error_(JDWP::ERR_NONE),
2684 self_suspend_(false),
Ian Rogers33e95662013-05-20 20:29:14 -07002685 other_suspend_(false) {
Jeff Hao449db332013-04-12 18:30:52 -07002686 ScopedObjectAccessUnchecked soa(self);
2687 {
2688 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
2689 error_ = DecodeThread(soa, thread_id, thread_);
2690 }
2691 if (error_ == JDWP::ERR_NONE) {
2692 if (thread_ == soa.Self()) {
2693 self_suspend_ = true;
2694 } else {
2695 soa.Self()->TransitionFromRunnableToSuspended(kWaitingForDebuggerSuspension);
2696 jobject thread_peer = gRegistry->GetJObject(thread_id);
2697 bool timed_out;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07002698 Thread* suspended_thread = ThreadList::SuspendThreadByPeer(thread_peer, true, true,
2699 &timed_out);
Jeff Hao449db332013-04-12 18:30:52 -07002700 CHECK_EQ(soa.Self()->TransitionFromSuspendedToRunnable(), kWaitingForDebuggerSuspension);
2701 if (suspended_thread == NULL) {
2702 // Thread terminated from under us while suspending.
2703 error_ = JDWP::ERR_INVALID_THREAD;
2704 } else {
2705 CHECK_EQ(suspended_thread, thread_);
2706 other_suspend_ = true;
2707 }
2708 }
2709 }
Elliott Hughes2435a572012-02-17 16:07:41 -08002710 }
Elliott Hughes86964332012-02-15 19:37:42 -08002711
Jeff Hao449db332013-04-12 18:30:52 -07002712 Thread* GetThread() const {
2713 return thread_;
2714 }
2715
2716 JDWP::JdwpError GetError() const {
2717 return error_;
2718 }
2719
2720 ~ScopedThreadSuspension() {
2721 if (other_suspend_) {
2722 Runtime::Current()->GetThreadList()->Resume(thread_, true);
2723 }
2724 }
2725
2726 private:
2727 Thread* thread_;
2728 JDWP::JdwpError error_;
2729 bool self_suspend_;
2730 bool other_suspend_;
2731};
2732
2733JDWP::JdwpError Dbg::ConfigureStep(JDWP::ObjectId thread_id, JDWP::JdwpStepSize step_size,
2734 JDWP::JdwpStepDepth step_depth) {
2735 Thread* self = Thread::Current();
2736 ScopedThreadSuspension sts(self, thread_id);
2737 if (sts.GetError() != JDWP::ERR_NONE) {
2738 return sts.GetError();
2739 }
2740
Elliott Hughes2435a572012-02-17 16:07:41 -08002741 //
2742 // Work out what Method* we're in, the current line number, and how deep the stack currently
2743 // is for step-out.
2744 //
2745
Ian Rogers0399dde2012-06-06 17:09:28 -07002746 struct SingleStepStackVisitor : public StackVisitor {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002747 explicit SingleStepStackVisitor(Thread* thread, SingleStepControl* single_step_control,
2748 int32_t* line_number)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002749 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002750 : StackVisitor(thread, NULL), single_step_control_(single_step_control),
2751 line_number_(line_number) {
2752 DCHECK_EQ(single_step_control_, thread->GetSingleStepControl());
2753 single_step_control_->method = NULL;
2754 single_step_control_->stack_depth = 0;
Elliott Hughes86964332012-02-15 19:37:42 -08002755 }
Ian Rogersca190662012-06-26 15:45:57 -07002756
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002757 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2758 // annotalysis.
2759 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002760 mirror::ArtMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07002761 if (!m->IsRuntimeMethod()) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002762 ++single_step_control_->stack_depth;
2763 if (single_step_control_->method == NULL) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002764 mirror::DexCache* dex_cache = m->GetDeclaringClass()->GetDexCache();
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002765 single_step_control_->method = m;
2766 *line_number_ = -1;
Elliott Hughes2435a572012-02-17 16:07:41 -08002767 if (dex_cache != NULL) {
Ian Rogers4445a7e2012-10-05 17:19:13 -07002768 const DexFile& dex_file = *dex_cache->GetDexFile();
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002769 *line_number_ = dex_file.GetLineNumFromPC(m, GetDexPc());
Elliott Hughes2435a572012-02-17 16:07:41 -08002770 }
Elliott Hughes86964332012-02-15 19:37:42 -08002771 }
2772 }
Elliott Hughes530fa002012-03-12 11:44:49 -07002773 return true;
Elliott Hughes86964332012-02-15 19:37:42 -08002774 }
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002775
2776 SingleStepControl* const single_step_control_;
2777 int32_t* const line_number_;
Elliott Hughes86964332012-02-15 19:37:42 -08002778 };
Jeff Hao449db332013-04-12 18:30:52 -07002779
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002780 Thread* const thread = sts.GetThread();
2781 SingleStepControl* const single_step_control = thread->GetSingleStepControl();
2782 DCHECK(single_step_control != nullptr);
2783 int32_t line_number = -1;
2784 SingleStepStackVisitor visitor(thread, single_step_control, &line_number);
Ian Rogers0399dde2012-06-06 17:09:28 -07002785 visitor.WalkStack();
Elliott Hughes86964332012-02-15 19:37:42 -08002786
Elliott Hughes2435a572012-02-17 16:07:41 -08002787 //
2788 // Find the dex_pc values that correspond to the current line, for line-based single-stepping.
2789 //
2790
2791 struct DebugCallbackContext {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002792 explicit DebugCallbackContext(SingleStepControl* single_step_control, int32_t line_number)
2793 : single_step_control_(single_step_control), line_number_(line_number),
2794 last_pc_valid(false), last_pc(0) {
Elliott Hughes2435a572012-02-17 16:07:41 -08002795 }
2796
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002797 static bool Callback(void* raw_context, uint32_t address, uint32_t line_number) {
Elliott Hughes2435a572012-02-17 16:07:41 -08002798 DebugCallbackContext* context = reinterpret_cast<DebugCallbackContext*>(raw_context);
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002799 if (static_cast<int32_t>(line_number) == context->line_number_) {
Elliott Hughes2435a572012-02-17 16:07:41 -08002800 if (!context->last_pc_valid) {
2801 // Everything from this address until the next line change is ours.
2802 context->last_pc = address;
2803 context->last_pc_valid = true;
2804 }
2805 // Otherwise, if we're already in a valid range for this line,
2806 // just keep going (shouldn't really happen)...
Brian Carlstrom7934ac22013-07-26 10:54:15 -07002807 } else if (context->last_pc_valid) { // and the line number is new
Elliott Hughes2435a572012-02-17 16:07:41 -08002808 // Add everything from the last entry up until here to the set
2809 for (uint32_t dex_pc = context->last_pc; dex_pc < address; ++dex_pc) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002810 context->single_step_control_->dex_pcs.insert(dex_pc);
Elliott Hughes2435a572012-02-17 16:07:41 -08002811 }
2812 context->last_pc_valid = false;
2813 }
Brian Carlstrom7934ac22013-07-26 10:54:15 -07002814 return false; // There may be multiple entries for any given line.
Elliott Hughes2435a572012-02-17 16:07:41 -08002815 }
2816
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002817 ~DebugCallbackContext() {
Elliott Hughes2435a572012-02-17 16:07:41 -08002818 // If the line number was the last in the position table...
2819 if (last_pc_valid) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002820 size_t end = MethodHelper(single_step_control_->method).GetCodeItem()->insns_size_in_code_units_;
Elliott Hughes2435a572012-02-17 16:07:41 -08002821 for (uint32_t dex_pc = last_pc; dex_pc < end; ++dex_pc) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002822 single_step_control_->dex_pcs.insert(dex_pc);
Elliott Hughes2435a572012-02-17 16:07:41 -08002823 }
2824 }
2825 }
2826
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002827 SingleStepControl* const single_step_control_;
2828 const int32_t line_number_;
Elliott Hughes2435a572012-02-17 16:07:41 -08002829 bool last_pc_valid;
2830 uint32_t last_pc;
2831 };
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002832 single_step_control->dex_pcs.clear();
Ian Rogersef7d42f2014-01-06 12:55:46 -08002833 mirror::ArtMethod* m = single_step_control->method;
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002834 if (!m->IsNative()) {
2835 DebugCallbackContext context(single_step_control, line_number);
Elliott Hughes3e2e1a22012-02-21 11:33:41 -08002836 MethodHelper mh(m);
2837 mh.GetDexFile().DecodeDebugInfo(mh.GetCodeItem(), m->IsStatic(), m->GetDexMethodIndex(),
2838 DebugCallbackContext::Callback, NULL, &context);
2839 }
Elliott Hughes2435a572012-02-17 16:07:41 -08002840
2841 //
2842 // Everything else...
2843 //
2844
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002845 single_step_control->step_size = step_size;
2846 single_step_control->step_depth = step_depth;
2847 single_step_control->is_active = true;
Elliott Hughes86964332012-02-15 19:37:42 -08002848
Elliott Hughes2435a572012-02-17 16:07:41 -08002849 if (VLOG_IS_ON(jdwp)) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002850 VLOG(jdwp) << "Single-step thread: " << *thread;
2851 VLOG(jdwp) << "Single-step step size: " << single_step_control->step_size;
2852 VLOG(jdwp) << "Single-step step depth: " << single_step_control->step_depth;
2853 VLOG(jdwp) << "Single-step current method: " << PrettyMethod(single_step_control->method);
2854 VLOG(jdwp) << "Single-step current line: " << line_number;
2855 VLOG(jdwp) << "Single-step current stack depth: " << single_step_control->stack_depth;
Elliott Hughes2435a572012-02-17 16:07:41 -08002856 VLOG(jdwp) << "Single-step dex_pc values:";
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002857 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 -08002858 VLOG(jdwp) << StringPrintf(" %#x", *it);
Elliott Hughes2435a572012-02-17 16:07:41 -08002859 }
2860 }
2861
2862 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002863}
2864
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002865void Dbg::UnconfigureStep(JDWP::ObjectId thread_id) {
2866 ScopedObjectAccessUnchecked soa(Thread::Current());
2867 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
2868 Thread* thread;
2869 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
Sebastien Hertz87118ed2013-11-26 17:57:18 +01002870 if (error == JDWP::ERR_NONE) {
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01002871 SingleStepControl* single_step_control = thread->GetSingleStepControl();
2872 DCHECK(single_step_control != nullptr);
2873 single_step_control->is_active = false;
2874 single_step_control->dex_pcs.clear();
2875 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002876}
2877
Elliott Hughes45651fd2012-02-21 15:48:20 -08002878static char JdwpTagToShortyChar(JDWP::JdwpTag tag) {
2879 switch (tag) {
2880 default:
2881 LOG(FATAL) << "unknown JDWP tag: " << PrintableChar(tag);
2882
2883 // Primitives.
2884 case JDWP::JT_BYTE: return 'B';
2885 case JDWP::JT_CHAR: return 'C';
2886 case JDWP::JT_FLOAT: return 'F';
2887 case JDWP::JT_DOUBLE: return 'D';
2888 case JDWP::JT_INT: return 'I';
2889 case JDWP::JT_LONG: return 'J';
2890 case JDWP::JT_SHORT: return 'S';
2891 case JDWP::JT_VOID: return 'V';
2892 case JDWP::JT_BOOLEAN: return 'Z';
2893
2894 // Reference types.
2895 case JDWP::JT_ARRAY:
2896 case JDWP::JT_OBJECT:
2897 case JDWP::JT_STRING:
2898 case JDWP::JT_THREAD:
2899 case JDWP::JT_THREAD_GROUP:
2900 case JDWP::JT_CLASS_LOADER:
2901 case JDWP::JT_CLASS_OBJECT:
2902 return 'L';
2903 }
2904}
2905
Elliott Hughes88d63092013-01-09 09:55:54 -08002906JDWP::JdwpError Dbg::InvokeMethod(JDWP::ObjectId thread_id, JDWP::ObjectId object_id,
2907 JDWP::RefTypeId class_id, JDWP::MethodId method_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002908 uint32_t arg_count, uint64_t* arg_values,
2909 JDWP::JdwpTag* arg_types, uint32_t options,
2910 JDWP::JdwpTag* pResultTag, uint64_t* pResultValue,
2911 JDWP::ObjectId* pExceptionId) {
Elliott Hughesd07986f2011-12-06 18:27:45 -08002912 ThreadList* thread_list = Runtime::Current()->GetThreadList();
2913
2914 Thread* targetThread = NULL;
2915 DebugInvokeReq* req = NULL;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002916 Thread* self = Thread::Current();
Elliott Hughesd07986f2011-12-06 18:27:45 -08002917 {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002918 ScopedObjectAccessUnchecked soa(self);
Ian Rogers50b35e22012-10-04 10:09:15 -07002919 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002920 JDWP::JdwpError error = DecodeThread(soa, thread_id, targetThread);
2921 if (error != JDWP::ERR_NONE) {
2922 LOG(ERROR) << "InvokeMethod request for invalid thread id " << thread_id;
2923 return error;
Elliott Hughesd07986f2011-12-06 18:27:45 -08002924 }
2925 req = targetThread->GetInvokeReq();
2926 if (!req->ready) {
2927 LOG(ERROR) << "InvokeMethod request for thread not stopped by event: " << *targetThread;
2928 return JDWP::ERR_INVALID_THREAD;
2929 }
2930
2931 /*
2932 * We currently have a bug where we don't successfully resume the
2933 * target thread if the suspend count is too deep. We're expected to
2934 * require one "resume" for each "suspend", but when asked to execute
2935 * a method we have to resume fully and then re-suspend it back to the
2936 * same level. (The easiest way to cause this is to type "suspend"
2937 * multiple times in jdb.)
2938 *
2939 * It's unclear what this means when the event specifies "resume all"
2940 * and some threads are suspended more deeply than others. This is
2941 * a rare problem, so for now we just prevent it from hanging forever
2942 * by rejecting the method invocation request. Without this, we will
2943 * be stuck waiting on a suspended thread.
2944 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002945 int suspend_count;
2946 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002947 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002948 suspend_count = targetThread->GetSuspendCount();
2949 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08002950 if (suspend_count > 1) {
2951 LOG(ERROR) << *targetThread << " suspend count too deep for method invocation: " << suspend_count;
Brian Carlstrom7934ac22013-07-26 10:54:15 -07002952 return JDWP::ERR_THREAD_SUSPENDED; // Probably not expected here.
Elliott Hughesd07986f2011-12-06 18:27:45 -08002953 }
2954
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002955 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002956 mirror::Object* receiver = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08002957 if (receiver == ObjectRegistry::kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002958 return JDWP::ERR_INVALID_OBJECT;
2959 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002960
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002961 mirror::Object* thread = gRegistry->Get<mirror::Object*>(thread_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08002962 if (thread == ObjectRegistry::kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002963 return JDWP::ERR_INVALID_OBJECT;
2964 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002965 // TODO: check that 'thread' is actually a java.lang.Thread!
2966
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002967 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes45651fd2012-02-21 15:48:20 -08002968 if (c == NULL) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002969 return status;
2970 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002971
Brian Carlstromea46f952013-07-30 01:26:50 -07002972 mirror::ArtMethod* m = FromMethodId(method_id);
Elliott Hughes45651fd2012-02-21 15:48:20 -08002973 if (m->IsStatic() != (receiver == NULL)) {
2974 return JDWP::ERR_INVALID_METHODID;
2975 }
2976 if (m->IsStatic()) {
2977 if (m->GetDeclaringClass() != c) {
2978 return JDWP::ERR_INVALID_METHODID;
2979 }
2980 } else {
2981 if (!m->GetDeclaringClass()->IsAssignableFrom(c)) {
2982 return JDWP::ERR_INVALID_METHODID;
2983 }
2984 }
2985
2986 // Check the argument list matches the method.
2987 MethodHelper mh(m);
2988 if (mh.GetShortyLength() - 1 != arg_count) {
2989 return JDWP::ERR_ILLEGAL_ARGUMENT;
2990 }
2991 const char* shorty = mh.GetShorty();
Elliott Hughes09201632013-04-15 15:50:07 -07002992 const DexFile::TypeList* types = mh.GetParameterTypeList();
Elliott Hughes45651fd2012-02-21 15:48:20 -08002993 for (size_t i = 0; i < arg_count; ++i) {
2994 if (shorty[i + 1] != JdwpTagToShortyChar(arg_types[i])) {
2995 return JDWP::ERR_ILLEGAL_ARGUMENT;
2996 }
Elliott Hughes09201632013-04-15 15:50:07 -07002997
2998 if (shorty[i + 1] == 'L') {
2999 // Did we really get an argument of an appropriate reference type?
3000 mirror::Class* parameter_type = mh.GetClassFromTypeIdx(types->GetTypeItem(i).type_idx_);
3001 mirror::Object* argument = gRegistry->Get<mirror::Object*>(arg_values[i]);
3002 if (argument == ObjectRegistry::kInvalidObject) {
3003 return JDWP::ERR_INVALID_OBJECT;
3004 }
Sebastien Hertz0630ab52013-11-28 18:53:35 +01003005 if (argument != NULL && !argument->InstanceOf(parameter_type)) {
Elliott Hughes09201632013-04-15 15:50:07 -07003006 return JDWP::ERR_ILLEGAL_ARGUMENT;
3007 }
3008
3009 // Turn the on-the-wire ObjectId into a jobject.
3010 jvalue& v = reinterpret_cast<jvalue&>(arg_values[i]);
3011 v.l = gRegistry->GetJObject(arg_values[i]);
3012 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08003013 }
3014
Sebastien Hertzd38667a2013-11-25 15:43:54 +01003015 req->receiver = receiver;
3016 req->thread = thread;
3017 req->klass = c;
3018 req->method = m;
3019 req->arg_count = arg_count;
3020 req->arg_values = arg_values;
3021 req->options = options;
3022 req->invoke_needed = true;
Elliott Hughesd07986f2011-12-06 18:27:45 -08003023 }
3024
3025 // The fact that we've released the thread list lock is a bit risky --- if the thread goes
3026 // away we're sitting high and dry -- but we must release this before the ResumeAllThreads
3027 // call, and it's unwise to hold it during WaitForSuspend.
3028
3029 {
3030 /*
3031 * We change our (JDWP thread) status, which should be THREAD_RUNNING,
Elliott Hughes81ff3182012-03-23 20:35:56 -07003032 * so we can suspend for a GC if the invoke request causes us to
Elliott Hughesd07986f2011-12-06 18:27:45 -08003033 * run out of memory. It's also a good idea to change it before locking
3034 * the invokeReq mutex, although that should never be held for long.
3035 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003036 self->TransitionFromRunnableToSuspended(kWaitingForDebuggerSend);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003037
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003038 VLOG(jdwp) << " Transferring control to event thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08003039 {
Sebastien Hertzd38667a2013-11-25 15:43:54 +01003040 MutexLock mu(self, req->lock);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003041
3042 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003043 VLOG(jdwp) << " Resuming all threads";
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003044 thread_list->UndoDebuggerSuspensions();
Elliott Hughesd07986f2011-12-06 18:27:45 -08003045 } else {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003046 VLOG(jdwp) << " Resuming event thread only";
Elliott Hughesd07986f2011-12-06 18:27:45 -08003047 thread_list->Resume(targetThread, true);
3048 }
3049
3050 // Wait for the request to finish executing.
Sebastien Hertzd38667a2013-11-25 15:43:54 +01003051 while (req->invoke_needed) {
3052 req->cond.Wait(self);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003053 }
3054 }
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003055 VLOG(jdwp) << " Control has returned from event thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08003056
3057 /* wait for thread to re-suspend itself */
Brian Carlstromdf629502013-07-17 22:39:56 -07003058 SuspendThread(thread_id, false /* request_suspension */);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003059 self->TransitionFromSuspendedToRunnable();
Elliott Hughesd07986f2011-12-06 18:27:45 -08003060 }
3061
3062 /*
3063 * Suspend the threads. We waited for the target thread to suspend
3064 * itself, so all we need to do is suspend the others.
3065 *
3066 * The suspendAllThreads() call will double-suspend the event thread,
3067 * so we want to resume the target thread once to keep the books straight.
3068 */
3069 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003070 self->TransitionFromRunnableToSuspended(kWaitingForDebuggerSuspension);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003071 VLOG(jdwp) << " Suspending all threads";
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003072 thread_list->SuspendAllForDebugger();
3073 self->TransitionFromSuspendedToRunnable();
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003074 VLOG(jdwp) << " Resuming event thread to balance the count";
Elliott Hughesd07986f2011-12-06 18:27:45 -08003075 thread_list->Resume(targetThread, true);
3076 }
3077
3078 // Copy the result.
3079 *pResultTag = req->result_tag;
3080 if (IsPrimitiveTag(req->result_tag)) {
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07003081 *pResultValue = req->result_value.GetJ();
Elliott Hughesd07986f2011-12-06 18:27:45 -08003082 } else {
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07003083 *pResultValue = gRegistry->Add(req->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003084 }
3085 *pExceptionId = req->exception;
3086 return req->error;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003087}
3088
3089void Dbg::ExecuteMethod(DebugInvokeReq* pReq) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003090 ScopedObjectAccess soa(Thread::Current());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003091
Elliott Hughes81ff3182012-03-23 20:35:56 -07003092 // We can be called while an exception is pending. We need
Elliott Hughesd07986f2011-12-06 18:27:45 -08003093 // to preserve that across the method invocation.
Ian Rogers62d6c772013-02-27 08:32:07 -08003094 SirtRef<mirror::Object> old_throw_this_object(soa.Self(), NULL);
Brian Carlstromea46f952013-07-30 01:26:50 -07003095 SirtRef<mirror::ArtMethod> old_throw_method(soa.Self(), NULL);
Ian Rogers62d6c772013-02-27 08:32:07 -08003096 SirtRef<mirror::Throwable> old_exception(soa.Self(), NULL);
3097 uint32_t old_throw_dex_pc;
3098 {
3099 ThrowLocation old_throw_location;
3100 mirror::Throwable* old_exception_obj = soa.Self()->GetException(&old_throw_location);
3101 old_throw_this_object.reset(old_throw_location.GetThis());
3102 old_throw_method.reset(old_throw_location.GetMethod());
3103 old_exception.reset(old_exception_obj);
3104 old_throw_dex_pc = old_throw_location.GetDexPc();
3105 soa.Self()->ClearException();
3106 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08003107
3108 // Translate the method through the vtable, unless the debugger wants to suppress it.
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003109 SirtRef<mirror::ArtMethod> m(soa.Self(), pReq->method);
Sebastien Hertzd38667a2013-11-25 15:43:54 +01003110 if ((pReq->options & JDWP::INVOKE_NONVIRTUAL) == 0 && pReq->receiver != NULL) {
Sebastien Hertz83a47d82014-03-20 09:57:40 +01003111 mirror::ArtMethod* actual_method = pReq->klass->FindVirtualMethodForVirtualOrInterface(m.get());
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003112 if (actual_method != m.get()) {
3113 VLOG(jdwp) << "ExecuteMethod translated " << PrettyMethod(m.get()) << " to " << PrettyMethod(actual_method);
3114 m.reset(actual_method);
Elliott Hughes45651fd2012-02-21 15:48:20 -08003115 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08003116 }
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003117 VLOG(jdwp) << "ExecuteMethod " << PrettyMethod(m.get())
Sebastien Hertzd38667a2013-11-25 15:43:54 +01003118 << " receiver=" << pReq->receiver
3119 << " arg_count=" << pReq->arg_count;
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003120 CHECK(m.get() != nullptr);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003121
3122 CHECK_EQ(sizeof(jvalue), sizeof(uint64_t));
3123
Sebastien Hertz83a47d82014-03-20 09:57:40 +01003124 pReq->result_value = InvokeWithJValues(soa, pReq->receiver, soa.EncodeMethod(m.get()),
Ian Rogers53b8b092014-03-13 23:45:53 -07003125 reinterpret_cast<jvalue*>(pReq->arg_values));
Elliott Hughesd07986f2011-12-06 18:27:45 -08003126
Ian Rogers62d6c772013-02-27 08:32:07 -08003127 mirror::Throwable* exception = soa.Self()->GetException(NULL);
3128 soa.Self()->ClearException();
3129 pReq->exception = gRegistry->Add(exception);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003130 pReq->result_tag = BasicTagFromDescriptor(MethodHelper(m.get()).GetShorty());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003131 if (pReq->exception != 0) {
Ian Rogers62d6c772013-02-27 08:32:07 -08003132 VLOG(jdwp) << " JDWP invocation returning with exception=" << exception
3133 << " " << exception->Dump();
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07003134 pReq->result_value.SetJ(0);
Elliott Hughesd07986f2011-12-06 18:27:45 -08003135 } else if (pReq->result_tag == JDWP::JT_OBJECT) {
3136 /* if no exception thrown, examine object result more closely */
Ian Rogers98379392014-02-24 16:53:16 -08003137 JDWP::JdwpTag new_tag = TagFromObject(soa, pReq->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003138 if (new_tag != pReq->result_tag) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003139 VLOG(jdwp) << " JDWP promoted result from " << pReq->result_tag << " to " << new_tag;
Elliott Hughesd07986f2011-12-06 18:27:45 -08003140 pReq->result_tag = new_tag;
3141 }
3142
3143 /*
3144 * Register the object. We don't actually need an ObjectId yet,
3145 * but we do need to be sure that the GC won't move or discard the
3146 * object when we switch out of RUNNING. The ObjectId conversion
3147 * will add the object to the "do not touch" list.
3148 *
3149 * We can't use the "tracked allocation" mechanism here because
3150 * the object is going to be handed off to a different thread.
3151 */
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07003152 gRegistry->Add(pReq->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003153 }
3154
3155 if (old_exception.get() != NULL) {
Ian Rogers62d6c772013-02-27 08:32:07 -08003156 ThrowLocation gc_safe_throw_location(old_throw_this_object.get(), old_throw_method.get(),
3157 old_throw_dex_pc);
3158 soa.Self()->SetException(gc_safe_throw_location, old_exception.get());
Elliott Hughesd07986f2011-12-06 18:27:45 -08003159 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003160}
3161
Elliott Hughesd07986f2011-12-06 18:27:45 -08003162/*
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003163 * "request" contains a full JDWP packet, possibly with multiple chunks. We
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003164 * need to process each, accumulate the replies, and ship the whole thing
3165 * back.
3166 *
3167 * Returns "true" if we have a reply. The reply buffer is newly allocated,
3168 * and includes the chunk type/length, followed by the data.
3169 *
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08003170 * OLD-TODO: we currently assume that the request and reply include a single
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003171 * chunk. If this becomes inconvenient we will need to adapt.
3172 */
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003173bool Dbg::DdmHandlePacket(JDWP::Request& request, uint8_t** pReplyBuf, int* pReplyLen) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003174 Thread* self = Thread::Current();
3175 JNIEnv* env = self->GetJniEnv();
3176
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003177 uint32_t type = request.ReadUnsigned32("type");
3178 uint32_t length = request.ReadUnsigned32("length");
3179
3180 // Create a byte[] corresponding to 'request'.
3181 size_t request_length = request.size();
3182 ScopedLocalRef<jbyteArray> dataArray(env, env->NewByteArray(request_length));
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003183 if (dataArray.get() == NULL) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003184 LOG(WARNING) << "byte[] allocation failed: " << request_length;
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003185 env->ExceptionClear();
3186 return false;
3187 }
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003188 env->SetByteArrayRegion(dataArray.get(), 0, request_length, reinterpret_cast<const jbyte*>(request.data()));
3189 request.Skip(request_length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003190
3191 // Run through and find all chunks. [Currently just find the first.]
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003192 ScopedByteArrayRO contents(env, dataArray.get());
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003193 if (length != request_length) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08003194 LOG(WARNING) << StringPrintf("bad chunk found (len=%u pktLen=%zd)", length, request_length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003195 return false;
3196 }
3197
3198 // Call "private static Chunk dispatch(int type, byte[] data, int offset, int length)".
Elliott Hugheseac76672012-05-24 21:56:51 -07003199 ScopedLocalRef<jobject> chunk(env, env->CallStaticObjectMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
3200 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_dispatch,
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003201 type, dataArray.get(), 0, length));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003202 if (env->ExceptionCheck()) {
3203 LOG(INFO) << StringPrintf("Exception thrown by dispatcher for 0x%08x", type);
3204 env->ExceptionDescribe();
3205 env->ExceptionClear();
3206 return false;
3207 }
3208
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003209 if (chunk.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003210 return false;
3211 }
3212
3213 /*
3214 * Pull the pieces out of the chunk. We copy the results into a
3215 * newly-allocated buffer that the caller can free. We don't want to
3216 * continue using the Chunk object because nothing has a reference to it.
3217 *
3218 * We could avoid this by returning type/data/offset/length and having
3219 * the caller be aware of the object lifetime issues, but that
Elliott Hughes81ff3182012-03-23 20:35:56 -07003220 * integrates the JDWP code more tightly into the rest of the runtime, and doesn't work
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003221 * if we have responses for multiple chunks.
3222 *
3223 * So we're pretty much stuck with copying data around multiple times.
3224 */
Elliott Hugheseac76672012-05-24 21:56:51 -07003225 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 -08003226 jint offset = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_offset);
Elliott Hugheseac76672012-05-24 21:56:51 -07003227 length = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_length);
Elliott Hugheseac76672012-05-24 21:56:51 -07003228 type = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_type);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003229
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003230 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 -07003231 if (length == 0 || replyData.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003232 return false;
3233 }
3234
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003235 const int kChunkHdrLen = 8;
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003236 uint8_t* reply = new uint8_t[length + kChunkHdrLen];
3237 if (reply == NULL) {
3238 LOG(WARNING) << "malloc failed: " << (length + kChunkHdrLen);
3239 return false;
3240 }
Elliott Hughesf7c3b662011-10-27 12:04:56 -07003241 JDWP::Set4BE(reply + 0, type);
3242 JDWP::Set4BE(reply + 4, length);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003243 env->GetByteArrayRegion(replyData.get(), offset, length, reinterpret_cast<jbyte*>(reply + kChunkHdrLen));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003244
3245 *pReplyBuf = reply;
3246 *pReplyLen = length + kChunkHdrLen;
3247
Elliott Hughes4b9702c2013-02-20 18:13:24 -08003248 VLOG(jdwp) << StringPrintf("dvmHandleDdm returning type=%.4s %p len=%d", reinterpret_cast<char*>(reply), reply, length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07003249 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003250}
3251
Elliott Hughesa2155262011-11-16 16:26:58 -08003252void Dbg::DdmBroadcast(bool connect) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003253 VLOG(jdwp) << "Broadcasting DDM " << (connect ? "connect" : "disconnect") << "...";
Elliott Hughes47fce012011-10-25 18:37:19 -07003254
3255 Thread* self = Thread::Current();
Ian Rogers50b35e22012-10-04 10:09:15 -07003256 if (self->GetState() != kRunnable) {
3257 LOG(ERROR) << "DDM broadcast in thread state " << self->GetState();
3258 /* try anyway? */
Elliott Hughes47fce012011-10-25 18:37:19 -07003259 }
3260
3261 JNIEnv* env = self->GetJniEnv();
Elliott Hughes47fce012011-10-25 18:37:19 -07003262 jint event = connect ? 1 /*DdmServer.CONNECTED*/ : 2 /*DdmServer.DISCONNECTED*/;
Elliott Hugheseac76672012-05-24 21:56:51 -07003263 env->CallStaticVoidMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
3264 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_broadcast,
3265 event);
Elliott Hughes47fce012011-10-25 18:37:19 -07003266 if (env->ExceptionCheck()) {
3267 LOG(ERROR) << "DdmServer.broadcast " << event << " failed";
3268 env->ExceptionDescribe();
3269 env->ExceptionClear();
3270 }
3271}
3272
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003273void Dbg::DdmConnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08003274 Dbg::DdmBroadcast(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003275}
3276
3277void Dbg::DdmDisconnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08003278 Dbg::DdmBroadcast(false);
Elliott Hughes47fce012011-10-25 18:37:19 -07003279 gDdmThreadNotification = false;
3280}
3281
3282/*
Elliott Hughes82188472011-11-07 18:11:48 -08003283 * Send a notification when a thread starts, stops, or changes its name.
Elliott Hughes47fce012011-10-25 18:37:19 -07003284 *
3285 * Because we broadcast the full set of threads when the notifications are
3286 * first enabled, it's possible for "thread" to be actively executing.
3287 */
Elliott Hughes82188472011-11-07 18:11:48 -08003288void Dbg::DdmSendThreadNotification(Thread* t, uint32_t type) {
Elliott Hughes47fce012011-10-25 18:37:19 -07003289 if (!gDdmThreadNotification) {
3290 return;
3291 }
3292
Elliott Hughes82188472011-11-07 18:11:48 -08003293 if (type == CHUNK_TYPE("THDE")) {
Elliott Hughes47fce012011-10-25 18:37:19 -07003294 uint8_t buf[4];
Ian Rogersd9c4fc92013-10-01 19:45:43 -07003295 JDWP::Set4BE(&buf[0], t->GetThreadId());
Elliott Hughes47fce012011-10-25 18:37:19 -07003296 Dbg::DdmSendChunk(CHUNK_TYPE("THDE"), 4, buf);
Elliott Hughes82188472011-11-07 18:11:48 -08003297 } else {
3298 CHECK(type == CHUNK_TYPE("THCR") || type == CHUNK_TYPE("THNM")) << type;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003299 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003300 SirtRef<mirror::String> name(soa.Self(), t->GetThreadName(soa));
Elliott Hughes82188472011-11-07 18:11:48 -08003301 size_t char_count = (name.get() != NULL) ? name->GetLength() : 0;
jeffhao725a9572012-11-13 18:20:12 -08003302 const jchar* chars = (name.get() != NULL) ? name->GetCharArray()->GetData() : NULL;
Elliott Hughes82188472011-11-07 18:11:48 -08003303
Elliott Hughes21f32d72011-11-09 17:44:13 -08003304 std::vector<uint8_t> bytes;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07003305 JDWP::Append4BE(bytes, t->GetThreadId());
Elliott Hughes545a0642011-11-08 19:10:03 -08003306 JDWP::AppendUtf16BE(bytes, chars, char_count);
Elliott Hughes21f32d72011-11-09 17:44:13 -08003307 CHECK_EQ(bytes.size(), char_count*2 + sizeof(uint32_t)*2);
3308 Dbg::DdmSendChunk(type, bytes);
Elliott Hughes47fce012011-10-25 18:37:19 -07003309 }
3310}
3311
Elliott Hughes47fce012011-10-25 18:37:19 -07003312void Dbg::DdmSetThreadNotification(bool enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003313 // Enable/disable thread notifications.
Elliott Hughes47fce012011-10-25 18:37:19 -07003314 gDdmThreadNotification = enable;
3315 if (enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003316 // Suspend the VM then post thread start notifications for all threads. Threads attaching will
3317 // see a suspension in progress and block until that ends. They then post their own start
3318 // notification.
3319 SuspendVM();
3320 std::list<Thread*> threads;
Ian Rogers50b35e22012-10-04 10:09:15 -07003321 Thread* self = Thread::Current();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003322 {
Ian Rogers50b35e22012-10-04 10:09:15 -07003323 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003324 threads = Runtime::Current()->GetThreadList()->GetList();
3325 }
3326 {
Ian Rogers50b35e22012-10-04 10:09:15 -07003327 ScopedObjectAccess soa(self);
Mathieu Chartier02e25112013-08-14 16:14:24 -07003328 for (Thread* thread : threads) {
3329 Dbg::DdmSendThreadNotification(thread, CHUNK_TYPE("THCR"));
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003330 }
3331 }
3332 ResumeVM();
Elliott Hughes47fce012011-10-25 18:37:19 -07003333 }
3334}
3335
Elliott Hughesa2155262011-11-16 16:26:58 -08003336void Dbg::PostThreadStartOrStop(Thread* t, uint32_t type) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07003337 if (IsDebuggerActive()) {
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07003338 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogerscfaa4552012-11-26 21:00:08 -08003339 JDWP::ObjectId id = gRegistry->Add(t->GetPeer());
Elliott Hughes82188472011-11-07 18:11:48 -08003340 gJdwpState->PostThreadChange(id, type == CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07003341 }
Elliott Hughes82188472011-11-07 18:11:48 -08003342 Dbg::DdmSendThreadNotification(t, type);
Elliott Hughes47fce012011-10-25 18:37:19 -07003343}
3344
3345void Dbg::PostThreadStart(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08003346 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07003347}
3348
3349void Dbg::PostThreadDeath(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08003350 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THDE"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003351}
3352
Elliott Hughes82188472011-11-07 18:11:48 -08003353void Dbg::DdmSendChunk(uint32_t type, size_t byte_count, const uint8_t* buf) {
Elliott Hughes3bb81562011-10-21 18:52:59 -07003354 CHECK(buf != NULL);
3355 iovec vec[1];
3356 vec[0].iov_base = reinterpret_cast<void*>(const_cast<uint8_t*>(buf));
3357 vec[0].iov_len = byte_count;
3358 Dbg::DdmSendChunkV(type, vec, 1);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003359}
3360
Elliott Hughes21f32d72011-11-09 17:44:13 -08003361void Dbg::DdmSendChunk(uint32_t type, const std::vector<uint8_t>& bytes) {
3362 DdmSendChunk(type, bytes.size(), &bytes[0]);
3363}
3364
Brian Carlstromf5293522013-07-19 00:24:00 -07003365void Dbg::DdmSendChunkV(uint32_t type, const iovec* iov, int iov_count) {
Elliott Hughes3bb81562011-10-21 18:52:59 -07003366 if (gJdwpState == NULL) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003367 VLOG(jdwp) << "Debugger thread not active, ignoring DDM send: " << type;
Elliott Hughes3bb81562011-10-21 18:52:59 -07003368 } else {
Elliott Hughescccd84f2011-12-05 16:51:54 -08003369 gJdwpState->DdmSendChunkV(type, iov, iov_count);
Elliott Hughes3bb81562011-10-21 18:52:59 -07003370 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003371}
3372
Elliott Hughes767a1472011-10-26 18:49:02 -07003373int Dbg::DdmHandleHpifChunk(HpifWhen when) {
3374 if (when == HPIF_WHEN_NOW) {
Elliott Hughes7162ad92011-10-27 14:08:42 -07003375 DdmSendHeapInfo(when);
Elliott Hughes767a1472011-10-26 18:49:02 -07003376 return true;
3377 }
3378
3379 if (when != HPIF_WHEN_NEVER && when != HPIF_WHEN_NEXT_GC && when != HPIF_WHEN_EVERY_GC) {
3380 LOG(ERROR) << "invalid HpifWhen value: " << static_cast<int>(when);
3381 return false;
3382 }
3383
3384 gDdmHpifWhen = when;
3385 return true;
3386}
3387
3388bool Dbg::DdmHandleHpsgNhsgChunk(Dbg::HpsgWhen when, Dbg::HpsgWhat what, bool native) {
3389 if (when != HPSG_WHEN_NEVER && when != HPSG_WHEN_EVERY_GC) {
3390 LOG(ERROR) << "invalid HpsgWhen value: " << static_cast<int>(when);
3391 return false;
3392 }
3393
3394 if (what != HPSG_WHAT_MERGED_OBJECTS && what != HPSG_WHAT_DISTINCT_OBJECTS) {
3395 LOG(ERROR) << "invalid HpsgWhat value: " << static_cast<int>(what);
3396 return false;
3397 }
3398
3399 if (native) {
3400 gDdmNhsgWhen = when;
3401 gDdmNhsgWhat = what;
3402 } else {
3403 gDdmHpsgWhen = when;
3404 gDdmHpsgWhat = what;
3405 }
3406 return true;
3407}
3408
Elliott Hughes7162ad92011-10-27 14:08:42 -07003409void Dbg::DdmSendHeapInfo(HpifWhen reason) {
3410 // If there's a one-shot 'when', reset it.
3411 if (reason == gDdmHpifWhen) {
3412 if (gDdmHpifWhen == HPIF_WHEN_NEXT_GC) {
3413 gDdmHpifWhen = HPIF_WHEN_NEVER;
3414 }
3415 }
3416
3417 /*
3418 * Chunk HPIF (client --> server)
3419 *
3420 * Heap Info. General information about the heap,
3421 * suitable for a summary display.
3422 *
3423 * [u4]: number of heaps
3424 *
3425 * For each heap:
3426 * [u4]: heap ID
3427 * [u8]: timestamp in ms since Unix epoch
3428 * [u1]: capture reason (same as 'when' value from server)
3429 * [u4]: max heap size in bytes (-Xmx)
3430 * [u4]: current heap size in bytes
3431 * [u4]: current number of bytes allocated
3432 * [u4]: current number of objects allocated
3433 */
3434 uint8_t heap_count = 1;
Ian Rogers1d54e732013-05-02 21:10:01 -07003435 gc::Heap* heap = Runtime::Current()->GetHeap();
Elliott Hughes21f32d72011-11-09 17:44:13 -08003436 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08003437 JDWP::Append4BE(bytes, heap_count);
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003438 JDWP::Append4BE(bytes, 1); // Heap id (bogus; we only have one heap).
Elliott Hughes545a0642011-11-08 19:10:03 -08003439 JDWP::Append8BE(bytes, MilliTime());
3440 JDWP::Append1BE(bytes, reason);
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003441 JDWP::Append4BE(bytes, heap->GetMaxMemory()); // Max allowed heap size in bytes.
3442 JDWP::Append4BE(bytes, heap->GetTotalMemory()); // Current heap size in bytes.
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08003443 JDWP::Append4BE(bytes, heap->GetBytesAllocated());
3444 JDWP::Append4BE(bytes, heap->GetObjectsAllocated());
Elliott Hughes21f32d72011-11-09 17:44:13 -08003445 CHECK_EQ(bytes.size(), 4U + (heap_count * (4 + 8 + 1 + 4 + 4 + 4 + 4)));
3446 Dbg::DdmSendChunk(CHUNK_TYPE("HPIF"), bytes);
Elliott Hughes767a1472011-10-26 18:49:02 -07003447}
3448
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003449enum HpsgSolidity {
3450 SOLIDITY_FREE = 0,
3451 SOLIDITY_HARD = 1,
3452 SOLIDITY_SOFT = 2,
3453 SOLIDITY_WEAK = 3,
3454 SOLIDITY_PHANTOM = 4,
3455 SOLIDITY_FINALIZABLE = 5,
3456 SOLIDITY_SWEEP = 6,
3457};
3458
3459enum HpsgKind {
3460 KIND_OBJECT = 0,
3461 KIND_CLASS_OBJECT = 1,
3462 KIND_ARRAY_1 = 2,
3463 KIND_ARRAY_2 = 3,
3464 KIND_ARRAY_4 = 4,
3465 KIND_ARRAY_8 = 5,
3466 KIND_UNKNOWN = 6,
3467 KIND_NATIVE = 7,
3468};
3469
3470#define HPSG_PARTIAL (1<<7)
3471#define HPSG_STATE(solidity, kind) ((uint8_t)((((kind) & 0x7) << 3) | ((solidity) & 0x7)))
3472
Ian Rogers30fab402012-01-23 15:43:46 -08003473class HeapChunkContext {
3474 public:
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003475 // Maximum chunk size. Obtain this from the formula:
3476 // (((maximum_heap_size / ALLOCATION_UNIT_SIZE) + 255) / 256) * 2
3477 HeapChunkContext(bool merge, bool native)
Ian Rogers30fab402012-01-23 15:43:46 -08003478 : buf_(16384 - 16),
3479 type_(0),
3480 merge_(merge) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003481 Reset();
3482 if (native) {
Ian Rogers30fab402012-01-23 15:43:46 -08003483 type_ = CHUNK_TYPE("NHSG");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003484 } else {
Ian Rogers30fab402012-01-23 15:43:46 -08003485 type_ = merge ? CHUNK_TYPE("HPSG") : CHUNK_TYPE("HPSO");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003486 }
3487 }
3488
3489 ~HeapChunkContext() {
Ian Rogers30fab402012-01-23 15:43:46 -08003490 if (p_ > &buf_[0]) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003491 Flush();
3492 }
3493 }
3494
3495 void EnsureHeader(const void* chunk_ptr) {
Ian Rogers30fab402012-01-23 15:43:46 -08003496 if (!needHeader_) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003497 return;
3498 }
3499
3500 // Start a new HPSx chunk.
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003501 JDWP::Write4BE(&p_, 1); // Heap id (bogus; we only have one heap).
3502 JDWP::Write1BE(&p_, 8); // Size of allocation unit, in bytes.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003503
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003504 JDWP::Write4BE(&p_, reinterpret_cast<uintptr_t>(chunk_ptr)); // virtual address of segment start.
3505 JDWP::Write4BE(&p_, 0); // offset of this piece (relative to the virtual address).
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003506 // [u4]: length of piece, in allocation units
3507 // 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 -08003508 pieceLenField_ = p_;
3509 JDWP::Write4BE(&p_, 0x55555555);
3510 needHeader_ = false;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003511 }
3512
Ian Rogersb726dcb2012-09-05 08:57:23 -07003513 void Flush() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogersd636b062013-01-18 17:51:18 -08003514 if (pieceLenField_ == NULL) {
3515 // Flush immediately post Reset (maybe back-to-back Flush). Ignore.
3516 CHECK(needHeader_);
3517 return;
3518 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003519 // Patch the "length of piece" field.
Ian Rogers30fab402012-01-23 15:43:46 -08003520 CHECK_LE(&buf_[0], pieceLenField_);
3521 CHECK_LE(pieceLenField_, p_);
3522 JDWP::Set4BE(pieceLenField_, totalAllocationUnits_);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003523
Ian Rogers30fab402012-01-23 15:43:46 -08003524 Dbg::DdmSendChunk(type_, p_ - &buf_[0], &buf_[0]);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003525 Reset();
3526 }
3527
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003528 static void HeapChunkCallback(void* start, void* end, size_t used_bytes, void* arg)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003529 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_,
3530 Locks::mutator_lock_) {
Ian Rogers30fab402012-01-23 15:43:46 -08003531 reinterpret_cast<HeapChunkContext*>(arg)->HeapChunkCallback(start, end, used_bytes);
Elliott Hughesa2155262011-11-16 16:26:58 -08003532 }
3533
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003534 private:
Elliott Hughesa2155262011-11-16 16:26:58 -08003535 enum { ALLOCATION_UNIT_SIZE = 8 };
3536
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003537 void Reset() {
Ian Rogers30fab402012-01-23 15:43:46 -08003538 p_ = &buf_[0];
Ian Rogers15bf2d32012-08-28 17:33:04 -07003539 startOfNextMemoryChunk_ = NULL;
Ian Rogers30fab402012-01-23 15:43:46 -08003540 totalAllocationUnits_ = 0;
3541 needHeader_ = true;
3542 pieceLenField_ = NULL;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003543 }
3544
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003545 void HeapChunkCallback(void* start, void* /*end*/, size_t used_bytes)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003546 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_,
3547 Locks::mutator_lock_) {
Ian Rogers30fab402012-01-23 15:43:46 -08003548 // Note: heap call backs cannot manipulate the heap upon which they are crawling, care is taken
3549 // in the following code not to allocate memory, by ensuring buf_ is of the correct size
Ian Rogers15bf2d32012-08-28 17:33:04 -07003550 if (used_bytes == 0) {
3551 if (start == NULL) {
3552 // Reset for start of new heap.
3553 startOfNextMemoryChunk_ = NULL;
3554 Flush();
3555 }
3556 // Only process in use memory so that free region information
3557 // also includes dlmalloc book keeping.
Elliott Hughesa2155262011-11-16 16:26:58 -08003558 return;
Elliott Hughesa2155262011-11-16 16:26:58 -08003559 }
3560
Ian Rogers15bf2d32012-08-28 17:33:04 -07003561 /* If we're looking at the native heap, we'll just return
3562 * (SOLIDITY_HARD, KIND_NATIVE) for all allocated chunks
3563 */
3564 bool native = type_ == CHUNK_TYPE("NHSG");
3565
3566 if (startOfNextMemoryChunk_ != NULL) {
3567 // Transmit any pending free memory. Native free memory of
3568 // over kMaxFreeLen could be because of the use of mmaps, so
3569 // don't report. If not free memory then start a new segment.
3570 bool flush = true;
3571 if (start > startOfNextMemoryChunk_) {
3572 const size_t kMaxFreeLen = 2 * kPageSize;
3573 void* freeStart = startOfNextMemoryChunk_;
3574 void* freeEnd = start;
Brian Carlstrom2d888622013-07-18 17:02:00 -07003575 size_t freeLen = reinterpret_cast<char*>(freeEnd) - reinterpret_cast<char*>(freeStart);
Ian Rogers15bf2d32012-08-28 17:33:04 -07003576 if (!native || freeLen < kMaxFreeLen) {
3577 AppendChunk(HPSG_STATE(SOLIDITY_FREE, 0), freeStart, freeLen);
3578 flush = false;
3579 }
3580 }
3581 if (flush) {
3582 startOfNextMemoryChunk_ = NULL;
3583 Flush();
3584 }
3585 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08003586 mirror::Object* obj = reinterpret_cast<mirror::Object*>(start);
Elliott Hughesa2155262011-11-16 16:26:58 -08003587
3588 // Determine the type of this chunk.
3589 // OLD-TODO: if context.merge, see if this chunk is different from the last chunk.
3590 // If it's the same, we should combine them.
Ian Rogers15bf2d32012-08-28 17:33:04 -07003591 uint8_t state = ExamineObject(obj, native);
3592 // dlmalloc's chunk header is 2 * sizeof(size_t), but if the previous chunk is in use for an
3593 // allocation then the first sizeof(size_t) may belong to it.
3594 const size_t dlMallocOverhead = sizeof(size_t);
3595 AppendChunk(state, start, used_bytes + dlMallocOverhead);
Brian Carlstrom2d888622013-07-18 17:02:00 -07003596 startOfNextMemoryChunk_ = reinterpret_cast<char*>(start) + used_bytes + dlMallocOverhead;
Ian Rogers15bf2d32012-08-28 17:33:04 -07003597 }
Elliott Hughesa2155262011-11-16 16:26:58 -08003598
Ian Rogers15bf2d32012-08-28 17:33:04 -07003599 void AppendChunk(uint8_t state, void* ptr, size_t length)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003600 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07003601 // Make sure there's enough room left in the buffer.
3602 // We need to use two bytes for every fractional 256 allocation units used by the chunk plus
3603 // 17 bytes for any header.
3604 size_t needed = (((length/ALLOCATION_UNIT_SIZE + 255) / 256) * 2) + 17;
3605 size_t bytesLeft = buf_.size() - (size_t)(p_ - &buf_[0]);
3606 if (bytesLeft < needed) {
3607 Flush();
3608 }
3609
3610 bytesLeft = buf_.size() - (size_t)(p_ - &buf_[0]);
3611 if (bytesLeft < needed) {
3612 LOG(WARNING) << "Chunk is too big to transmit (chunk_len=" << length << ", "
3613 << needed << " bytes)";
3614 return;
3615 }
3616 EnsureHeader(ptr);
Elliott Hughesa2155262011-11-16 16:26:58 -08003617 // Write out the chunk description.
Ian Rogers15bf2d32012-08-28 17:33:04 -07003618 length /= ALLOCATION_UNIT_SIZE; // Convert to allocation units.
3619 totalAllocationUnits_ += length;
3620 while (length > 256) {
Ian Rogers30fab402012-01-23 15:43:46 -08003621 *p_++ = state | HPSG_PARTIAL;
3622 *p_++ = 255; // length - 1
Ian Rogers15bf2d32012-08-28 17:33:04 -07003623 length -= 256;
Elliott Hughesa2155262011-11-16 16:26:58 -08003624 }
Ian Rogers30fab402012-01-23 15:43:46 -08003625 *p_++ = state;
Ian Rogers15bf2d32012-08-28 17:33:04 -07003626 *p_++ = length - 1;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003627 }
3628
Ian Rogersef7d42f2014-01-06 12:55:46 -08003629 uint8_t ExamineObject(mirror::Object* o, bool is_native_heap)
3630 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Elliott Hughesa2155262011-11-16 16:26:58 -08003631 if (o == NULL) {
3632 return HPSG_STATE(SOLIDITY_FREE, 0);
3633 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003634
Elliott Hughesa2155262011-11-16 16:26:58 -08003635 // It's an allocated chunk. Figure out what it is.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003636
Elliott Hughesa2155262011-11-16 16:26:58 -08003637 // If we're looking at the native heap, we'll just return
3638 // (SOLIDITY_HARD, KIND_NATIVE) for all allocated chunks.
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003639 if (is_native_heap) {
Elliott Hughesa2155262011-11-16 16:26:58 -08003640 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
3641 }
3642
Ian Rogers5bfa60f2012-09-02 21:17:56 -07003643 if (!Runtime::Current()->GetHeap()->IsLiveObjectLocked(o)) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07003644 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003645 }
3646
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003647 mirror::Class* c = o->GetClass();
Elliott Hughesa2155262011-11-16 16:26:58 -08003648 if (c == NULL) {
3649 // The object was probably just created but hasn't been initialized yet.
3650 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
3651 }
3652
Mathieu Chartier590fee92013-09-13 13:46:47 -07003653 if (!Runtime::Current()->GetHeap()->IsValidObjectAddress(c)) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07003654 LOG(ERROR) << "Invalid class for managed heap object: " << o << " " << c;
Elliott Hughesa2155262011-11-16 16:26:58 -08003655 return HPSG_STATE(SOLIDITY_HARD, KIND_UNKNOWN);
3656 }
3657
3658 if (c->IsClassClass()) {
3659 return HPSG_STATE(SOLIDITY_HARD, KIND_CLASS_OBJECT);
3660 }
3661
3662 if (c->IsArrayClass()) {
3663 if (o->IsObjectArray()) {
3664 return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
3665 }
3666 switch (c->GetComponentSize()) {
3667 case 1: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_1);
3668 case 2: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_2);
3669 case 4: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
3670 case 8: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_8);
3671 }
3672 }
3673
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003674 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
3675 }
3676
Ian Rogers30fab402012-01-23 15:43:46 -08003677 std::vector<uint8_t> buf_;
3678 uint8_t* p_;
3679 uint8_t* pieceLenField_;
Ian Rogers15bf2d32012-08-28 17:33:04 -07003680 void* startOfNextMemoryChunk_;
Ian Rogers30fab402012-01-23 15:43:46 -08003681 size_t totalAllocationUnits_;
3682 uint32_t type_;
3683 bool merge_;
3684 bool needHeader_;
3685
Elliott Hughesa2155262011-11-16 16:26:58 -08003686 DISALLOW_COPY_AND_ASSIGN(HeapChunkContext);
3687};
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003688
3689void Dbg::DdmSendHeapSegments(bool native) {
3690 Dbg::HpsgWhen when;
3691 Dbg::HpsgWhat what;
3692 if (!native) {
3693 when = gDdmHpsgWhen;
3694 what = gDdmHpsgWhat;
3695 } else {
3696 when = gDdmNhsgWhen;
3697 what = gDdmNhsgWhat;
3698 }
3699 if (when == HPSG_WHEN_NEVER) {
3700 return;
3701 }
3702
3703 // Figure out what kind of chunks we'll be sending.
3704 CHECK(what == HPSG_WHAT_MERGED_OBJECTS || what == HPSG_WHAT_DISTINCT_OBJECTS) << static_cast<int>(what);
3705
3706 // First, send a heap start chunk.
3707 uint8_t heap_id[4];
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003708 JDWP::Set4BE(&heap_id[0], 1); // Heap id (bogus; we only have one heap).
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003709 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHST") : CHUNK_TYPE("HPST"), sizeof(heap_id), heap_id);
3710
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07003711 Thread* self = Thread::Current();
3712
3713 // To allow the Walk/InspectAll() below to exclusively-lock the
3714 // mutator lock, temporarily release the shared access to the
3715 // mutator lock here by transitioning to the suspended state.
3716 Locks::mutator_lock_->AssertSharedHeld(self);
3717 self->TransitionFromRunnableToSuspended(kSuspended);
3718
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003719 // Send a series of heap segment chunks.
Elliott Hughesa2155262011-11-16 16:26:58 -08003720 HeapChunkContext context((what == HPSG_WHAT_MERGED_OBJECTS), native);
3721 if (native) {
Ian Rogers1d54e732013-05-02 21:10:01 -07003722 dlmalloc_inspect_all(HeapChunkContext::HeapChunkCallback, &context);
Elliott Hughesa2155262011-11-16 16:26:58 -08003723 } else {
Ian Rogers1d54e732013-05-02 21:10:01 -07003724 gc::Heap* heap = Runtime::Current()->GetHeap();
3725 const std::vector<gc::space::ContinuousSpace*>& spaces = heap->GetContinuousSpaces();
Ian Rogers62d6c772013-02-27 08:32:07 -08003726 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Ian Rogers1d54e732013-05-02 21:10:01 -07003727 typedef std::vector<gc::space::ContinuousSpace*>::const_iterator It;
3728 for (It cur = spaces.begin(), end = spaces.end(); cur != end; ++cur) {
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07003729 if ((*cur)->IsMallocSpace()) {
3730 (*cur)->AsMallocSpace()->Walk(HeapChunkContext::HeapChunkCallback, &context);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07003731 }
3732 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07003733 // Walk the large objects, these are not in the AllocSpace.
3734 heap->GetLargeObjectsSpace()->Walk(HeapChunkContext::HeapChunkCallback, &context);
Elliott Hughesa2155262011-11-16 16:26:58 -08003735 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003736
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07003737 // Shared-lock the mutator lock back.
3738 self->TransitionFromSuspendedToRunnable();
3739 Locks::mutator_lock_->AssertSharedHeld(self);
3740
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003741 // Finally, send a heap end chunk.
3742 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHEN") : CHUNK_TYPE("HPEN"), sizeof(heap_id), heap_id);
Elliott Hughes767a1472011-10-26 18:49:02 -07003743}
3744
Elliott Hughesb1a58792013-07-11 18:10:58 -07003745static size_t GetAllocTrackerMax() {
3746#ifdef HAVE_ANDROID_OS
3747 // Check whether there's a system property overriding the number of records.
3748 const char* propertyName = "dalvik.vm.allocTrackerMax";
3749 char allocRecordMaxString[PROPERTY_VALUE_MAX];
3750 if (property_get(propertyName, allocRecordMaxString, "") > 0) {
3751 char* end;
3752 size_t value = strtoul(allocRecordMaxString, &end, 10);
3753 if (*end != '\0') {
Ruben Brunk3e47a742013-09-09 17:56:07 -07003754 LOG(ERROR) << "Ignoring " << propertyName << " '" << allocRecordMaxString
3755 << "' --- invalid";
Elliott Hughesb1a58792013-07-11 18:10:58 -07003756 return kDefaultNumAllocRecords;
3757 }
3758 if (!IsPowerOfTwo(value)) {
Ruben Brunk3e47a742013-09-09 17:56:07 -07003759 LOG(ERROR) << "Ignoring " << propertyName << " '" << allocRecordMaxString
3760 << "' --- not power of two";
Elliott Hughesb1a58792013-07-11 18:10:58 -07003761 return kDefaultNumAllocRecords;
3762 }
3763 return value;
3764 }
3765#endif
3766 return kDefaultNumAllocRecords;
3767}
3768
Elliott Hughes545a0642011-11-08 19:10:03 -08003769void Dbg::SetAllocTrackingEnabled(bool enabled) {
Ian Rogers719d1a32014-03-06 12:13:39 -08003770 MutexLock mu(Thread::Current(), *alloc_tracker_lock_);
Elliott Hughes545a0642011-11-08 19:10:03 -08003771 if (enabled) {
3772 if (recent_allocation_records_ == NULL) {
Ian Rogers719d1a32014-03-06 12:13:39 -08003773 alloc_record_max_ = GetAllocTrackerMax();
3774 LOG(INFO) << "Enabling alloc tracker (" << alloc_record_max_ << " entries of "
Elliott Hughesb1a58792013-07-11 18:10:58 -07003775 << kMaxAllocRecordStackDepth << " frames, taking "
Ian Rogers719d1a32014-03-06 12:13:39 -08003776 << PrettySize(sizeof(AllocRecord) * alloc_record_max_) << ")";
3777 alloc_record_head_ = alloc_record_count_ = 0;
3778 recent_allocation_records_ = new AllocRecord[alloc_record_max_];
Elliott Hughes545a0642011-11-08 19:10:03 -08003779 CHECK(recent_allocation_records_ != NULL);
3780 }
Ian Rogersfa824272013-11-05 16:12:57 -08003781 Runtime::Current()->GetInstrumentation()->InstrumentQuickAllocEntryPoints();
Elliott Hughes545a0642011-11-08 19:10:03 -08003782 } else {
Ian Rogersfa824272013-11-05 16:12:57 -08003783 Runtime::Current()->GetInstrumentation()->UninstrumentQuickAllocEntryPoints();
Elliott Hughes545a0642011-11-08 19:10:03 -08003784 delete[] recent_allocation_records_;
3785 recent_allocation_records_ = NULL;
3786 }
3787}
3788
Ian Rogers0399dde2012-06-06 17:09:28 -07003789struct AllocRecordStackVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -08003790 AllocRecordStackVisitor(Thread* thread, AllocRecord* record)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003791 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08003792 : StackVisitor(thread, NULL), record(record), depth(0) {}
Elliott Hughes545a0642011-11-08 19:10:03 -08003793
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003794 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
3795 // annotalysis.
3796 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughes545a0642011-11-08 19:10:03 -08003797 if (depth >= kMaxAllocRecordStackDepth) {
Elliott Hughes530fa002012-03-12 11:44:49 -07003798 return false;
Elliott Hughes545a0642011-11-08 19:10:03 -08003799 }
Brian Carlstromea46f952013-07-30 01:26:50 -07003800 mirror::ArtMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07003801 if (!m->IsRuntimeMethod()) {
3802 record->stack[depth].method = m;
3803 record->stack[depth].dex_pc = GetDexPc();
Elliott Hughes530fa002012-03-12 11:44:49 -07003804 ++depth;
Elliott Hughes545a0642011-11-08 19:10:03 -08003805 }
Elliott Hughes530fa002012-03-12 11:44:49 -07003806 return true;
Elliott Hughes545a0642011-11-08 19:10:03 -08003807 }
3808
3809 ~AllocRecordStackVisitor() {
3810 // Clear out any unused stack trace elements.
3811 for (; depth < kMaxAllocRecordStackDepth; ++depth) {
3812 record->stack[depth].method = NULL;
Ian Rogers0399dde2012-06-06 17:09:28 -07003813 record->stack[depth].dex_pc = 0;
Elliott Hughes545a0642011-11-08 19:10:03 -08003814 }
3815 }
3816
3817 AllocRecord* record;
3818 size_t depth;
3819};
3820
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003821void Dbg::RecordAllocation(mirror::Class* type, size_t byte_count) {
Elliott Hughes545a0642011-11-08 19:10:03 -08003822 Thread* self = Thread::Current();
3823 CHECK(self != NULL);
3824
Ian Rogers719d1a32014-03-06 12:13:39 -08003825 MutexLock mu(self, *alloc_tracker_lock_);
Elliott Hughes545a0642011-11-08 19:10:03 -08003826 if (recent_allocation_records_ == NULL) {
3827 return;
3828 }
3829
3830 // Advance and clip.
Ian Rogers719d1a32014-03-06 12:13:39 -08003831 if (++alloc_record_head_ == alloc_record_max_) {
3832 alloc_record_head_ = 0;
Elliott Hughes545a0642011-11-08 19:10:03 -08003833 }
3834
3835 // Fill in the basics.
Ian Rogers719d1a32014-03-06 12:13:39 -08003836 AllocRecord* record = &recent_allocation_records_[alloc_record_head_];
Elliott Hughes545a0642011-11-08 19:10:03 -08003837 record->type = type;
3838 record->byte_count = byte_count;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07003839 record->thin_lock_id = self->GetThreadId();
Elliott Hughes545a0642011-11-08 19:10:03 -08003840
3841 // Fill in the stack trace.
Ian Rogers7a22fa62013-01-23 12:16:16 -08003842 AllocRecordStackVisitor visitor(self, record);
Ian Rogers0399dde2012-06-06 17:09:28 -07003843 visitor.WalkStack();
Elliott Hughes545a0642011-11-08 19:10:03 -08003844
Ian Rogers719d1a32014-03-06 12:13:39 -08003845 if (alloc_record_count_ < alloc_record_max_) {
3846 ++alloc_record_count_;
Elliott Hughes545a0642011-11-08 19:10:03 -08003847 }
3848}
3849
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003850// Returns the index of the head element.
3851//
3852// We point at the most-recently-written record, so if gAllocRecordCount is 1
3853// we want to use the current element. Take "head+1" and subtract count
3854// from it.
3855//
3856// We need to handle underflow in our circular buffer, so we add
Elliott Hughesb1a58792013-07-11 18:10:58 -07003857// gAllocRecordMax and then mask it back down.
Ian Rogers719d1a32014-03-06 12:13:39 -08003858size_t Dbg::HeadIndex() {
3859 return (Dbg::alloc_record_head_ + 1 + Dbg::alloc_record_max_ - Dbg::alloc_record_count_) &
3860 (Dbg::alloc_record_max_ - 1);
Elliott Hughes545a0642011-11-08 19:10:03 -08003861}
3862
3863void Dbg::DumpRecentAllocations() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003864 ScopedObjectAccess soa(Thread::Current());
Ian Rogers719d1a32014-03-06 12:13:39 -08003865 MutexLock mu(soa.Self(), *alloc_tracker_lock_);
Elliott Hughes545a0642011-11-08 19:10:03 -08003866 if (recent_allocation_records_ == NULL) {
3867 LOG(INFO) << "Not recording tracked allocations";
3868 return;
3869 }
3870
3871 // "i" is the head of the list. We want to start at the end of the
3872 // list and move forward to the tail.
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003873 size_t i = HeadIndex();
Ian Rogers719d1a32014-03-06 12:13:39 -08003874 size_t count = alloc_record_count_;
Elliott Hughes545a0642011-11-08 19:10:03 -08003875
Ian Rogers719d1a32014-03-06 12:13:39 -08003876 LOG(INFO) << "Tracked allocations, (head=" << alloc_record_head_ << " count=" << count << ")";
Elliott Hughes545a0642011-11-08 19:10:03 -08003877 while (count--) {
3878 AllocRecord* record = &recent_allocation_records_[i];
3879
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003880 LOG(INFO) << StringPrintf(" Thread %-2d %6zd bytes ", record->thin_lock_id, record->byte_count)
Elliott Hughes545a0642011-11-08 19:10:03 -08003881 << PrettyClass(record->type);
3882
3883 for (size_t stack_frame = 0; stack_frame < kMaxAllocRecordStackDepth; ++stack_frame) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08003884 mirror::ArtMethod* m = record->stack[stack_frame].method;
Elliott Hughes545a0642011-11-08 19:10:03 -08003885 if (m == NULL) {
3886 break;
3887 }
3888 LOG(INFO) << " " << PrettyMethod(m) << " line " << record->stack[stack_frame].LineNumber();
3889 }
3890
3891 // pause periodically to help logcat catch up
3892 if ((count % 5) == 0) {
3893 usleep(40000);
3894 }
3895
Ian Rogers719d1a32014-03-06 12:13:39 -08003896 i = (i + 1) & (alloc_record_max_ - 1);
Elliott Hughes545a0642011-11-08 19:10:03 -08003897 }
3898}
3899
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -07003900void Dbg::UpdateObjectPointers(IsMarkedCallback* callback, void* arg) {
Ian Rogers719d1a32014-03-06 12:13:39 -08003901 if (recent_allocation_records_ != nullptr) {
3902 MutexLock mu(Thread::Current(), *alloc_tracker_lock_);
3903 size_t i = HeadIndex();
3904 size_t count = alloc_record_count_;
3905 while (count--) {
3906 AllocRecord* record = &recent_allocation_records_[i];
3907 DCHECK(record != nullptr);
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -07003908 record->UpdateObjectPointers(callback, arg);
Ian Rogers719d1a32014-03-06 12:13:39 -08003909 i = (i + 1) & (alloc_record_max_ - 1);
Mathieu Chartier412c7fc2014-02-07 12:18:39 -08003910 }
3911 }
3912 if (gRegistry != nullptr) {
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -07003913 gRegistry->UpdateObjectPointers(callback, arg);
Mathieu Chartier412c7fc2014-02-07 12:18:39 -08003914 }
3915}
3916
3917void Dbg::AllowNewObjectRegistryObjects() {
3918 if (gRegistry != nullptr) {
3919 gRegistry->AllowNewObjects();
3920 }
3921}
3922
3923void Dbg::DisallowNewObjectRegistryObjects() {
3924 if (gRegistry != nullptr) {
3925 gRegistry->DisallowNewObjects();
3926 }
3927}
3928
Elliott Hughes545a0642011-11-08 19:10:03 -08003929class StringTable {
3930 public:
3931 StringTable() {
3932 }
3933
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003934 void Add(const char* s) {
Elliott Hughes545a0642011-11-08 19:10:03 -08003935 table_.insert(s);
3936 }
3937
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003938 size_t IndexOf(const char* s) const {
Mathieu Chartier02e25112013-08-14 16:14:24 -07003939 auto it = table_.find(s);
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003940 if (it == table_.end()) {
3941 LOG(FATAL) << "IndexOf(\"" << s << "\") failed";
3942 }
3943 return std::distance(table_.begin(), it);
Elliott Hughes545a0642011-11-08 19:10:03 -08003944 }
3945
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003946 size_t Size() const {
Elliott Hughes545a0642011-11-08 19:10:03 -08003947 return table_.size();
3948 }
3949
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003950 void WriteTo(std::vector<uint8_t>& bytes) const {
Mathieu Chartier02e25112013-08-14 16:14:24 -07003951 for (const std::string& str : table_) {
3952 const char* s = str.c_str();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003953 size_t s_len = CountModifiedUtf8Chars(s);
3954 UniquePtr<uint16_t> s_utf16(new uint16_t[s_len]);
3955 ConvertModifiedUtf8ToUtf16(s_utf16.get(), s);
3956 JDWP::AppendUtf16BE(bytes, s_utf16.get(), s_len);
Elliott Hughes545a0642011-11-08 19:10:03 -08003957 }
3958 }
3959
3960 private:
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003961 std::set<std::string> table_;
Elliott Hughes545a0642011-11-08 19:10:03 -08003962 DISALLOW_COPY_AND_ASSIGN(StringTable);
3963};
3964
3965/*
3966 * The data we send to DDMS contains everything we have recorded.
3967 *
3968 * Message header (all values big-endian):
3969 * (1b) message header len (to allow future expansion); includes itself
3970 * (1b) entry header len
3971 * (1b) stack frame len
3972 * (2b) number of entries
3973 * (4b) offset to string table from start of message
3974 * (2b) number of class name strings
3975 * (2b) number of method name strings
3976 * (2b) number of source file name strings
3977 * For each entry:
3978 * (4b) total allocation size
Elliott Hughes221229c2013-01-08 18:17:50 -08003979 * (2b) thread id
Elliott Hughes545a0642011-11-08 19:10:03 -08003980 * (2b) allocated object's class name index
3981 * (1b) stack depth
3982 * For each stack frame:
3983 * (2b) method's class name
3984 * (2b) method name
3985 * (2b) method source file
3986 * (2b) line number, clipped to 32767; -2 if native; -1 if no source
3987 * (xb) class name strings
3988 * (xb) method name strings
3989 * (xb) source file strings
3990 *
3991 * As with other DDM traffic, strings are sent as a 4-byte length
3992 * followed by UTF-16 data.
3993 *
3994 * We send up 16-bit unsigned indexes into string tables. In theory there
Elliott Hughesb1a58792013-07-11 18:10:58 -07003995 * can be (kMaxAllocRecordStackDepth * gAllocRecordMax) unique strings in
Elliott Hughes545a0642011-11-08 19:10:03 -08003996 * each table, but in practice there should be far fewer.
3997 *
3998 * The chief reason for using a string table here is to keep the size of
3999 * the DDMS message to a minimum. This is partly to make the protocol
4000 * efficient, but also because we have to form the whole thing up all at
4001 * once in a memory buffer.
4002 *
4003 * We use separate string tables for class names, method names, and source
4004 * files to keep the indexes small. There will generally be no overlap
4005 * between the contents of these tables.
4006 */
4007jbyteArray Dbg::GetRecentAllocations() {
4008 if (false) {
4009 DumpRecentAllocations();
4010 }
4011
Ian Rogers50b35e22012-10-04 10:09:15 -07004012 Thread* self = Thread::Current();
Elliott Hughes545a0642011-11-08 19:10:03 -08004013 std::vector<uint8_t> bytes;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004014 {
Ian Rogers719d1a32014-03-06 12:13:39 -08004015 MutexLock mu(self, *alloc_tracker_lock_);
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004016 //
4017 // Part 1: generate string tables.
4018 //
4019 StringTable class_names;
4020 StringTable method_names;
4021 StringTable filenames;
Elliott Hughes545a0642011-11-08 19:10:03 -08004022
Ian Rogers719d1a32014-03-06 12:13:39 -08004023 int count = alloc_record_count_;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004024 int idx = HeadIndex();
4025 while (count--) {
4026 AllocRecord* record = &recent_allocation_records_[idx];
Elliott Hughes545a0642011-11-08 19:10:03 -08004027
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004028 class_names.Add(ClassHelper(record->type).GetDescriptor());
Elliott Hughes545a0642011-11-08 19:10:03 -08004029
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004030 MethodHelper mh;
4031 for (size_t i = 0; i < kMaxAllocRecordStackDepth; i++) {
Brian Carlstromea46f952013-07-30 01:26:50 -07004032 mirror::ArtMethod* m = record->stack[i].method;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004033 if (m != NULL) {
4034 mh.ChangeMethod(m);
4035 class_names.Add(mh.GetDeclaringClassDescriptor());
4036 method_names.Add(mh.GetName());
4037 filenames.Add(mh.GetDeclaringClassSourceFile());
4038 }
4039 }
Elliott Hughes545a0642011-11-08 19:10:03 -08004040
Ian Rogers719d1a32014-03-06 12:13:39 -08004041 idx = (idx + 1) & (alloc_record_max_ - 1);
Elliott Hughes545a0642011-11-08 19:10:03 -08004042 }
4043
Ian Rogers719d1a32014-03-06 12:13:39 -08004044 LOG(INFO) << "allocation records: " << alloc_record_count_;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004045
4046 //
4047 // Part 2: Generate the output and store it in the buffer.
4048 //
4049
4050 // (1b) message header len (to allow future expansion); includes itself
4051 // (1b) entry header len
4052 // (1b) stack frame len
4053 const int kMessageHeaderLen = 15;
4054 const int kEntryHeaderLen = 9;
4055 const int kStackFrameLen = 8;
4056 JDWP::Append1BE(bytes, kMessageHeaderLen);
4057 JDWP::Append1BE(bytes, kEntryHeaderLen);
4058 JDWP::Append1BE(bytes, kStackFrameLen);
4059
4060 // (2b) number of entries
4061 // (4b) offset to string table from start of message
4062 // (2b) number of class name strings
4063 // (2b) number of method name strings
4064 // (2b) number of source file name strings
Ian Rogers719d1a32014-03-06 12:13:39 -08004065 JDWP::Append2BE(bytes, alloc_record_count_);
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004066 size_t string_table_offset = bytes.size();
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004067 JDWP::Append4BE(bytes, 0); // We'll patch this later...
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004068 JDWP::Append2BE(bytes, class_names.Size());
4069 JDWP::Append2BE(bytes, method_names.Size());
4070 JDWP::Append2BE(bytes, filenames.Size());
4071
Ian Rogers719d1a32014-03-06 12:13:39 -08004072 count = alloc_record_count_;
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004073 idx = HeadIndex();
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004074 while (count--) {
4075 // For each entry:
4076 // (4b) total allocation size
4077 // (2b) thread id
4078 // (2b) allocated object's class name index
4079 // (1b) stack depth
4080 AllocRecord* record = &recent_allocation_records_[idx];
4081 size_t stack_depth = record->GetDepth();
Mathieu Chartier590fee92013-09-13 13:46:47 -07004082 ClassHelper kh(record->type);
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004083 size_t allocated_object_class_name_index = class_names.IndexOf(kh.GetDescriptor());
4084 JDWP::Append4BE(bytes, record->byte_count);
4085 JDWP::Append2BE(bytes, record->thin_lock_id);
4086 JDWP::Append2BE(bytes, allocated_object_class_name_index);
4087 JDWP::Append1BE(bytes, stack_depth);
4088
4089 MethodHelper mh;
4090 for (size_t stack_frame = 0; stack_frame < stack_depth; ++stack_frame) {
4091 // For each stack frame:
4092 // (2b) method's class name
4093 // (2b) method name
4094 // (2b) method source file
4095 // (2b) line number, clipped to 32767; -2 if native; -1 if no source
4096 mh.ChangeMethod(record->stack[stack_frame].method);
4097 size_t class_name_index = class_names.IndexOf(mh.GetDeclaringClassDescriptor());
4098 size_t method_name_index = method_names.IndexOf(mh.GetName());
4099 size_t file_name_index = filenames.IndexOf(mh.GetDeclaringClassSourceFile());
4100 JDWP::Append2BE(bytes, class_name_index);
4101 JDWP::Append2BE(bytes, method_name_index);
4102 JDWP::Append2BE(bytes, file_name_index);
4103 JDWP::Append2BE(bytes, record->stack[stack_frame].LineNumber());
4104 }
4105
Ian Rogers719d1a32014-03-06 12:13:39 -08004106 idx = (idx + 1) & (alloc_record_max_ - 1);
Mathieu Chartier46e811b2013-07-10 17:09:14 -07004107 }
4108
4109 // (xb) class name strings
4110 // (xb) method name strings
4111 // (xb) source file strings
4112 JDWP::Set4BE(&bytes[string_table_offset], bytes.size());
4113 class_names.WriteTo(bytes);
4114 method_names.WriteTo(bytes);
4115 filenames.WriteTo(bytes);
Elliott Hughes545a0642011-11-08 19:10:03 -08004116 }
Ian Rogers50b35e22012-10-04 10:09:15 -07004117 JNIEnv* env = self->GetJniEnv();
Elliott Hughes545a0642011-11-08 19:10:03 -08004118 jbyteArray result = env->NewByteArray(bytes.size());
4119 if (result != NULL) {
4120 env->SetByteArrayRegion(result, 0, bytes.size(), reinterpret_cast<const jbyte*>(&bytes[0]));
4121 }
4122 return result;
4123}
4124
Elliott Hughes872d4ec2011-10-21 17:07:15 -07004125} // namespace art