blob: 312172569c87fdee26dfc845f85f99dc5b95c920 [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
23#include "class_linker.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080024#include "class_linker-inl.h"
Ian Rogers776ac1f2012-04-13 23:36:36 -070025#include "dex_instruction.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080026#include "gc/card_table-inl.h"
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -070027#include "gc/large_object_space.h"
28#include "gc/space.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080029#include "mirror/abstract_method-inl.h"
30#include "mirror/class.h"
31#include "mirror/class-inl.h"
32#include "mirror/class_loader.h"
33#include "mirror/field-inl.h"
34#include "mirror/object-inl.h"
35#include "mirror/object_array-inl.h"
36#include "mirror/throwable.h"
Ian Rogers2bcb4a42012-11-08 10:39:18 -080037#include "oat/runtime/context.h"
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080038#include "object_utils.h"
Elliott Hughesa0e18062012-04-13 15:59:59 -070039#include "safe_map.h"
Elliott Hughes6a5bd492011-10-28 14:33:57 -070040#include "ScopedLocalRef.h"
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -070041#include "ScopedPrimitiveArray.h"
Ian Rogers00f7d0e2012-07-19 15:28:27 -070042#include "scoped_thread_state_change.h"
Ian Rogers1f539342012-10-03 21:09:42 -070043#include "sirt_ref.h"
Elliott Hughes47fce012011-10-25 18:37:19 -070044#include "stack_indirect_reference_table.h"
Elliott Hughes475fc232011-10-25 15:00:35 -070045#include "thread_list.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080046#include "utf.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070047#include "well_known_classes.h"
Elliott Hughes475fc232011-10-25 15:00:35 -070048
Elliott Hughes872d4ec2011-10-21 17:07:15 -070049namespace art {
50
Elliott Hughes545a0642011-11-08 19:10:03 -080051static const size_t kMaxAllocRecordStackDepth = 16; // Max 255.
52static const size_t kNumAllocRecords = 512; // Must be power of 2.
53
Elliott Hughes436e3722012-02-17 20:01:47 -080054static const uintptr_t kInvalidId = 1;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080055static const mirror::Object* kInvalidObject = reinterpret_cast<mirror::Object*>(kInvalidId);
Elliott Hughes436e3722012-02-17 20:01:47 -080056
Elliott Hughes475fc232011-10-25 15:00:35 -070057class ObjectRegistry {
58 public:
59 ObjectRegistry() : lock_("ObjectRegistry lock") {
60 }
61
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080062 JDWP::ObjectId Add(mirror::Object* o) {
Elliott Hughes475fc232011-10-25 15:00:35 -070063 if (o == NULL) {
64 return 0;
65 }
66 JDWP::ObjectId id = static_cast<JDWP::ObjectId>(reinterpret_cast<uintptr_t>(o));
Ian Rogers50b35e22012-10-04 10:09:15 -070067 MutexLock mu(Thread::Current(), lock_);
Elliott Hughesa0e18062012-04-13 15:59:59 -070068 map_.Overwrite(id, o);
Elliott Hughes475fc232011-10-25 15:00:35 -070069 return id;
70 }
71
Elliott Hughes234ab152011-10-26 14:02:26 -070072 void Clear() {
Ian Rogers50b35e22012-10-04 10:09:15 -070073 MutexLock mu(Thread::Current(), lock_);
Elliott Hughes234ab152011-10-26 14:02:26 -070074 LOG(DEBUG) << "Debugger has detached; object registry had " << map_.size() << " entries";
75 map_.clear();
76 }
77
Elliott Hughes475fc232011-10-25 15:00:35 -070078 bool Contains(JDWP::ObjectId id) {
Ian Rogers50b35e22012-10-04 10:09:15 -070079 MutexLock mu(Thread::Current(), lock_);
Elliott Hughes475fc232011-10-25 15:00:35 -070080 return map_.find(id) != map_.end();
81 }
82
Elliott Hughesa2155262011-11-16 16:26:58 -080083 template<typename T> T Get(JDWP::ObjectId id) {
Elliott Hughes436e3722012-02-17 20:01:47 -080084 if (id == 0) {
85 return NULL;
86 }
87
Ian Rogers50b35e22012-10-04 10:09:15 -070088 MutexLock mu(Thread::Current(), lock_);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080089 typedef SafeMap<JDWP::ObjectId, mirror::Object*>::iterator It; // C++0x auto
Elliott Hughesa2155262011-11-16 16:26:58 -080090 It it = map_.find(id);
Elliott Hughes436e3722012-02-17 20:01:47 -080091 return (it != map_.end()) ? reinterpret_cast<T>(it->second) : reinterpret_cast<T>(kInvalidId);
Elliott Hughesa2155262011-11-16 16:26:58 -080092 }
93
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080094 void VisitRoots(RootVisitor* visitor, void* arg) {
Ian Rogers50b35e22012-10-04 10:09:15 -070095 MutexLock mu(Thread::Current(), lock_);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080096 typedef SafeMap<JDWP::ObjectId, mirror::Object*>::iterator It; // C++0x auto
Elliott Hughesbfe487b2011-10-26 15:48:55 -070097 for (It it = map_.begin(); it != map_.end(); ++it) {
98 visitor(it->second, arg);
99 }
100 }
101
Elliott Hughes475fc232011-10-25 15:00:35 -0700102 private:
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700103 Mutex lock_ DEFAULT_MUTEX_ACQUIRED_AFTER;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800104 SafeMap<JDWP::ObjectId, mirror::Object*> map_;
Elliott Hughes475fc232011-10-25 15:00:35 -0700105};
106
Elliott Hughes545a0642011-11-08 19:10:03 -0800107struct AllocRecordStackTraceElement {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800108 mirror::AbstractMethod* method;
Ian Rogers0399dde2012-06-06 17:09:28 -0700109 uint32_t dex_pc;
Elliott Hughes545a0642011-11-08 19:10:03 -0800110
Ian Rogersb726dcb2012-09-05 08:57:23 -0700111 int32_t LineNumber() const SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers0399dde2012-06-06 17:09:28 -0700112 return MethodHelper(method).GetLineNumFromDexPC(dex_pc);
Elliott Hughes545a0642011-11-08 19:10:03 -0800113 }
114};
115
116struct AllocRecord {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800117 mirror::Class* type;
Elliott Hughes545a0642011-11-08 19:10:03 -0800118 size_t byte_count;
119 uint16_t thin_lock_id;
120 AllocRecordStackTraceElement stack[kMaxAllocRecordStackDepth]; // Unused entries have NULL method.
121
122 size_t GetDepth() {
123 size_t depth = 0;
124 while (depth < kMaxAllocRecordStackDepth && stack[depth].method != NULL) {
125 ++depth;
126 }
127 return depth;
128 }
129};
130
Elliott Hughes86964332012-02-15 19:37:42 -0800131struct Breakpoint {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800132 mirror::AbstractMethod* method;
Elliott Hughesa656a0f2012-02-21 18:03:44 -0800133 uint32_t dex_pc;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800134 Breakpoint(mirror::AbstractMethod* method, uint32_t dex_pc) : method(method), dex_pc(dex_pc) {}
Elliott Hughes86964332012-02-15 19:37:42 -0800135};
136
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700137static std::ostream& operator<<(std::ostream& os, const Breakpoint& rhs)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700138 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes229feb72012-02-23 13:33:29 -0800139 os << StringPrintf("Breakpoint[%s @%#x]", PrettyMethod(rhs.method).c_str(), rhs.dex_pc);
Elliott Hughes86964332012-02-15 19:37:42 -0800140 return os;
141}
142
143struct SingleStepControl {
144 // Are we single-stepping right now?
145 bool is_active;
146 Thread* thread;
147
148 JDWP::JdwpStepSize step_size;
149 JDWP::JdwpStepDepth step_depth;
150
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800151 const mirror::AbstractMethod* method;
Elliott Hughes2435a572012-02-17 16:07:41 -0800152 int32_t line_number; // Or -1 for native methods.
153 std::set<uint32_t> dex_pcs;
Elliott Hughes86964332012-02-15 19:37:42 -0800154 int stack_depth;
155};
156
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700157// JDWP is allowed unless the Zygote forbids it.
158static bool gJdwpAllowed = true;
159
Elliott Hughesc0f09332012-03-26 13:27:06 -0700160// Was there a -Xrunjdwp or -agentlib:jdwp= argument on the command line?
Elliott Hughes3bb81562011-10-21 18:52:59 -0700161static bool gJdwpConfigured = false;
162
Elliott Hughesc0f09332012-03-26 13:27:06 -0700163// Broken-down JDWP options. (Only valid if IsJdwpConfigured() is true.)
Elliott Hughes376a7a02011-10-24 18:35:55 -0700164static JDWP::JdwpOptions gJdwpOptions;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700165
166// Runtime JDWP state.
167static JDWP::JdwpState* gJdwpState = NULL;
168static bool gDebuggerConnected; // debugger or DDMS is connected.
169static bool gDebuggerActive; // debugger is making requests.
Elliott Hughes86964332012-02-15 19:37:42 -0800170static bool gDisposed; // debugger called VirtualMachine.Dispose, so we should drop the connection.
Elliott Hughes3bb81562011-10-21 18:52:59 -0700171
Elliott Hughes47fce012011-10-25 18:37:19 -0700172static bool gDdmThreadNotification = false;
173
Elliott Hughes767a1472011-10-26 18:49:02 -0700174// DDMS GC-related settings.
175static Dbg::HpifWhen gDdmHpifWhen = Dbg::HPIF_WHEN_NEVER;
176static Dbg::HpsgWhen gDdmHpsgWhen = Dbg::HPSG_WHEN_NEVER;
177static Dbg::HpsgWhat gDdmHpsgWhat;
178static Dbg::HpsgWhen gDdmNhsgWhen = Dbg::HPSG_WHEN_NEVER;
179static Dbg::HpsgWhat gDdmNhsgWhat;
180
Elliott Hughes475fc232011-10-25 15:00:35 -0700181static ObjectRegistry* gRegistry = NULL;
182
Elliott Hughes545a0642011-11-08 19:10:03 -0800183// Recent allocation tracking.
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700184static Mutex gAllocTrackerLock DEFAULT_MUTEX_ACQUIRED_AFTER ("AllocTracker lock");
Elliott Hughesf8349362012-06-18 15:00:06 -0700185AllocRecord* Dbg::recent_allocation_records_ PT_GUARDED_BY(gAllocTrackerLock) = NULL; // TODO: CircularBuffer<AllocRecord>
186static size_t gAllocRecordHead GUARDED_BY(gAllocTrackerLock) = 0;
187static size_t gAllocRecordCount GUARDED_BY(gAllocTrackerLock) = 0;
Elliott Hughes545a0642011-11-08 19:10:03 -0800188
Elliott Hughes86964332012-02-15 19:37:42 -0800189// Breakpoints and single-stepping.
jeffhao09bfc6a2012-12-11 18:11:43 -0800190static std::vector<Breakpoint> gBreakpoints GUARDED_BY(Locks::breakpoint_lock_);
191static SingleStepControl gSingleStepControl GUARDED_BY(Locks::breakpoint_lock_);
Elliott Hughes86964332012-02-15 19:37:42 -0800192
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800193static bool IsBreakpoint(mirror::AbstractMethod* m, uint32_t dex_pc)
jeffhao09bfc6a2012-12-11 18:11:43 -0800194 LOCKS_EXCLUDED(Locks::breakpoint_lock_)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700195 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
jeffhao09bfc6a2012-12-11 18:11:43 -0800196 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Elliott Hughes86964332012-02-15 19:37:42 -0800197 for (size_t i = 0; i < gBreakpoints.size(); ++i) {
Elliott Hughesa656a0f2012-02-21 18:03:44 -0800198 if (gBreakpoints[i].method == m && gBreakpoints[i].dex_pc == dex_pc) {
Elliott Hughes86964332012-02-15 19:37:42 -0800199 VLOG(jdwp) << "Hit breakpoint #" << i << ": " << gBreakpoints[i];
200 return true;
201 }
202 }
203 return false;
204}
205
Elliott Hughes9e0c1752013-01-09 14:02:58 -0800206static bool IsSuspendedForDebugger(ScopedObjectAccessUnchecked& soa, Thread* thread) {
207 MutexLock mu(soa.Self(), *Locks::thread_suspend_count_lock_);
208 // A thread may be suspended for GC; in this code, we really want to know whether
209 // there's a debugger suspension active.
210 return thread->IsSuspended() && thread->GetDebugSuspendCount() > 0;
211}
212
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800213static mirror::Array* DecodeArray(JDWP::RefTypeId id, JDWP::JdwpError& status)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700214 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800215 mirror::Object* o = gRegistry->Get<mirror::Object*>(id);
Elliott Hughes436e3722012-02-17 20:01:47 -0800216 if (o == NULL || o == kInvalidObject) {
217 status = JDWP::ERR_INVALID_OBJECT;
218 return NULL;
219 }
220 if (!o->IsArrayInstance()) {
221 status = JDWP::ERR_INVALID_ARRAY;
222 return NULL;
223 }
224 status = JDWP::ERR_NONE;
225 return o->AsArray();
226}
227
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800228static mirror::Class* DecodeClass(JDWP::RefTypeId id, JDWP::JdwpError& status)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700229 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800230 mirror::Object* o = gRegistry->Get<mirror::Object*>(id);
Elliott Hughes436e3722012-02-17 20:01:47 -0800231 if (o == NULL || o == kInvalidObject) {
232 status = JDWP::ERR_INVALID_OBJECT;
233 return NULL;
234 }
235 if (!o->IsClass()) {
236 status = JDWP::ERR_INVALID_CLASS;
237 return NULL;
238 }
239 status = JDWP::ERR_NONE;
240 return o->AsClass();
241}
242
Elliott Hughes221229c2013-01-08 18:17:50 -0800243static JDWP::JdwpError DecodeThread(ScopedObjectAccessUnchecked& soa, JDWP::ObjectId thread_id, Thread*& thread)
jeffhaoa77f0f62012-12-05 17:19:31 -0800244 EXCLUSIVE_LOCKS_REQUIRED(Locks::thread_list_lock_)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700245 LOCKS_EXCLUDED(Locks::thread_suspend_count_lock_)
246 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800247 mirror::Object* thread_peer = gRegistry->Get<mirror::Object*>(thread_id);
Elliott Hughes436e3722012-02-17 20:01:47 -0800248 if (thread_peer == NULL || thread_peer == kInvalidObject) {
Elliott Hughes221229c2013-01-08 18:17:50 -0800249 // This isn't even an object.
250 return JDWP::ERR_INVALID_OBJECT;
Elliott Hughes436e3722012-02-17 20:01:47 -0800251 }
Elliott Hughes221229c2013-01-08 18:17:50 -0800252
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800253 mirror::Class* java_lang_Thread = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_Thread);
Elliott Hughes221229c2013-01-08 18:17:50 -0800254 if (!java_lang_Thread->IsAssignableFrom(thread_peer->GetClass())) {
255 // This isn't a thread.
256 return JDWP::ERR_INVALID_THREAD;
257 }
258
259 thread = Thread::FromManagedThread(soa, thread_peer);
260 if (thread == NULL) {
261 // This is a java.lang.Thread without a Thread*. Must be a zombie.
262 return JDWP::ERR_THREAD_NOT_ALIVE;
263 }
264 return JDWP::ERR_NONE;
Elliott Hughes436e3722012-02-17 20:01:47 -0800265}
266
Elliott Hughes24437992011-11-30 14:49:33 -0800267static JDWP::JdwpTag BasicTagFromDescriptor(const char* descriptor) {
268 // JDWP deliberately uses the descriptor characters' ASCII values for its enum.
269 // Note that by "basic" we mean that we don't get more specific than JT_OBJECT.
270 return static_cast<JDWP::JdwpTag>(descriptor[0]);
271}
272
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800273static JDWP::JdwpTag TagFromClass(mirror::Class* c)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700274 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes86b00102011-12-05 17:54:26 -0800275 CHECK(c != NULL);
Elliott Hughes24437992011-11-30 14:49:33 -0800276 if (c->IsArrayClass()) {
277 return JDWP::JT_ARRAY;
278 }
279
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800280 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Elliott Hughes24437992011-11-30 14:49:33 -0800281 if (c->IsStringClass()) {
282 return JDWP::JT_STRING;
283 } else if (c->IsClassClass()) {
284 return JDWP::JT_CLASS_OBJECT;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800285 } else if (class_linker->FindSystemClass("Ljava/lang/Thread;")->IsAssignableFrom(c)) {
Elliott Hughes24437992011-11-30 14:49:33 -0800286 return JDWP::JT_THREAD;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800287 } else if (class_linker->FindSystemClass("Ljava/lang/ThreadGroup;")->IsAssignableFrom(c)) {
Elliott Hughes24437992011-11-30 14:49:33 -0800288 return JDWP::JT_THREAD_GROUP;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800289 } else if (class_linker->FindSystemClass("Ljava/lang/ClassLoader;")->IsAssignableFrom(c)) {
Elliott Hughes24437992011-11-30 14:49:33 -0800290 return JDWP::JT_CLASS_LOADER;
Elliott Hughes24437992011-11-30 14:49:33 -0800291 } else {
292 return JDWP::JT_OBJECT;
293 }
294}
295
296/*
297 * Objects declared to hold Object might actually hold a more specific
298 * type. The debugger may take a special interest in these (e.g. it
299 * wants to display the contents of Strings), so we want to return an
300 * appropriate tag.
301 *
302 * Null objects are tagged JT_OBJECT.
303 */
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800304static JDWP::JdwpTag TagFromObject(const mirror::Object* o)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700305 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes24437992011-11-30 14:49:33 -0800306 return (o == NULL) ? JDWP::JT_OBJECT : TagFromClass(o->GetClass());
307}
308
309static bool IsPrimitiveTag(JDWP::JdwpTag tag) {
310 switch (tag) {
311 case JDWP::JT_BOOLEAN:
312 case JDWP::JT_BYTE:
313 case JDWP::JT_CHAR:
314 case JDWP::JT_FLOAT:
315 case JDWP::JT_DOUBLE:
316 case JDWP::JT_INT:
317 case JDWP::JT_LONG:
318 case JDWP::JT_SHORT:
319 case JDWP::JT_VOID:
320 return true;
321 default:
322 return false;
323 }
324}
325
Elliott Hughes3bb81562011-10-21 18:52:59 -0700326/*
327 * Handle one of the JDWP name/value pairs.
328 *
329 * JDWP options are:
330 * help: if specified, show help message and bail
331 * transport: may be dt_socket or dt_shmem
332 * address: for dt_socket, "host:port", or just "port" when listening
333 * server: if "y", wait for debugger to attach; if "n", attach to debugger
334 * timeout: how long to wait for debugger to connect / listen
335 *
336 * Useful with server=n (these aren't supported yet):
337 * onthrow=<exception-name>: connect to debugger when exception thrown
338 * onuncaught=y|n: connect to debugger when uncaught exception thrown
339 * launch=<command-line>: launch the debugger itself
340 *
341 * The "transport" option is required, as is "address" if server=n.
342 */
343static bool ParseJdwpOption(const std::string& name, const std::string& value) {
344 if (name == "transport") {
345 if (value == "dt_socket") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700346 gJdwpOptions.transport = JDWP::kJdwpTransportSocket;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700347 } else if (value == "dt_android_adb") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700348 gJdwpOptions.transport = JDWP::kJdwpTransportAndroidAdb;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700349 } else {
350 LOG(ERROR) << "JDWP transport not supported: " << value;
351 return false;
352 }
353 } else if (name == "server") {
354 if (value == "n") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700355 gJdwpOptions.server = false;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700356 } else if (value == "y") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700357 gJdwpOptions.server = true;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700358 } else {
359 LOG(ERROR) << "JDWP option 'server' must be 'y' or 'n'";
360 return false;
361 }
362 } else if (name == "suspend") {
363 if (value == "n") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700364 gJdwpOptions.suspend = false;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700365 } else if (value == "y") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700366 gJdwpOptions.suspend = true;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700367 } else {
368 LOG(ERROR) << "JDWP option 'suspend' must be 'y' or 'n'";
369 return false;
370 }
371 } else if (name == "address") {
372 /* this is either <port> or <host>:<port> */
373 std::string port_string;
Elliott Hughes376a7a02011-10-24 18:35:55 -0700374 gJdwpOptions.host.clear();
Elliott Hughes3bb81562011-10-21 18:52:59 -0700375 std::string::size_type colon = value.find(':');
376 if (colon != std::string::npos) {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700377 gJdwpOptions.host = value.substr(0, colon);
Elliott Hughes3bb81562011-10-21 18:52:59 -0700378 port_string = value.substr(colon + 1);
379 } else {
380 port_string = value;
381 }
382 if (port_string.empty()) {
383 LOG(ERROR) << "JDWP address missing port: " << value;
384 return false;
385 }
386 char* end;
Elliott Hughesba8eee12012-01-24 20:25:24 -0800387 uint64_t port = strtoul(port_string.c_str(), &end, 10);
388 if (*end != '\0' || port > 0xffff) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700389 LOG(ERROR) << "JDWP address has junk in port field: " << value;
390 return false;
391 }
Elliott Hughes376a7a02011-10-24 18:35:55 -0700392 gJdwpOptions.port = port;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700393 } else if (name == "launch" || name == "onthrow" || name == "oncaught" || name == "timeout") {
394 /* valid but unsupported */
395 LOG(INFO) << "Ignoring JDWP option '" << name << "'='" << value << "'";
396 } else {
397 LOG(INFO) << "Ignoring unrecognized JDWP option '" << name << "'='" << value << "'";
398 }
399
400 return true;
401}
402
403/*
404 * Parse the latter half of a -Xrunjdwp/-agentlib:jdwp= string, e.g.:
405 * "transport=dt_socket,address=8000,server=y,suspend=n"
406 */
407bool Dbg::ParseJdwpOptions(const std::string& options) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800408 VLOG(jdwp) << "ParseJdwpOptions: " << options;
Elliott Hughes47fce012011-10-25 18:37:19 -0700409
Elliott Hughes3bb81562011-10-21 18:52:59 -0700410 std::vector<std::string> pairs;
411 Split(options, ',', pairs);
412
413 for (size_t i = 0; i < pairs.size(); ++i) {
414 std::string::size_type equals = pairs[i].find('=');
415 if (equals == std::string::npos) {
416 LOG(ERROR) << "Can't parse JDWP option '" << pairs[i] << "' in '" << options << "'";
417 return false;
418 }
419 ParseJdwpOption(pairs[i].substr(0, equals), pairs[i].substr(equals + 1));
420 }
421
Elliott Hughes376a7a02011-10-24 18:35:55 -0700422 if (gJdwpOptions.transport == JDWP::kJdwpTransportUnknown) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700423 LOG(ERROR) << "Must specify JDWP transport: " << options;
424 }
Elliott Hughes376a7a02011-10-24 18:35:55 -0700425 if (!gJdwpOptions.server && (gJdwpOptions.host.empty() || gJdwpOptions.port == 0)) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700426 LOG(ERROR) << "Must specify JDWP host and port when server=n: " << options;
427 return false;
428 }
429
430 gJdwpConfigured = true;
431 return true;
432}
433
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700434void Dbg::StartJdwp() {
Elliott Hughesc0f09332012-03-26 13:27:06 -0700435 if (!gJdwpAllowed || !IsJdwpConfigured()) {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700436 // No JDWP for you!
437 return;
438 }
439
Elliott Hughes475fc232011-10-25 15:00:35 -0700440 CHECK(gRegistry == NULL);
441 gRegistry = new ObjectRegistry;
442
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700443 // Init JDWP if the debugger is enabled. This may connect out to a
444 // debugger, passively listen for a debugger, or block waiting for a
445 // debugger.
Elliott Hughes376a7a02011-10-24 18:35:55 -0700446 gJdwpState = JDWP::JdwpState::Create(&gJdwpOptions);
447 if (gJdwpState == NULL) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -0800448 // We probably failed because some other process has the port already, which means that
449 // if we don't abort the user is likely to think they're talking to us when they're actually
450 // talking to that other process.
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800451 LOG(FATAL) << "Debugger thread failed to initialize";
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700452 }
453
454 // If a debugger has already attached, send the "welcome" message.
455 // This may cause us to suspend all threads.
Elliott Hughes376a7a02011-10-24 18:35:55 -0700456 if (gJdwpState->IsActive()) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700457 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes376a7a02011-10-24 18:35:55 -0700458 if (!gJdwpState->PostVMStart()) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800459 LOG(WARNING) << "Failed to post 'start' message to debugger";
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700460 }
461 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700462}
463
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700464void Dbg::StopJdwp() {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700465 delete gJdwpState;
Elliott Hughes475fc232011-10-25 15:00:35 -0700466 delete gRegistry;
467 gRegistry = NULL;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700468}
469
Elliott Hughes767a1472011-10-26 18:49:02 -0700470void Dbg::GcDidFinish() {
471 if (gDdmHpifWhen != HPIF_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700472 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes81ff3182012-03-23 20:35:56 -0700473 LOG(DEBUG) << "Sending heap info to DDM";
Elliott Hughes7162ad92011-10-27 14:08:42 -0700474 DdmSendHeapInfo(gDdmHpifWhen);
Elliott Hughes767a1472011-10-26 18:49:02 -0700475 }
476 if (gDdmHpsgWhen != HPSG_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700477 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes81ff3182012-03-23 20:35:56 -0700478 LOG(DEBUG) << "Dumping heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700479 DdmSendHeapSegments(false);
Elliott Hughes767a1472011-10-26 18:49:02 -0700480 }
481 if (gDdmNhsgWhen != HPSG_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700482 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes767a1472011-10-26 18:49:02 -0700483 LOG(DEBUG) << "Dumping native heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700484 DdmSendHeapSegments(true);
Elliott Hughes767a1472011-10-26 18:49:02 -0700485 }
486}
487
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700488void Dbg::SetJdwpAllowed(bool allowed) {
489 gJdwpAllowed = allowed;
490}
491
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700492DebugInvokeReq* Dbg::GetInvokeReq() {
Elliott Hughes475fc232011-10-25 15:00:35 -0700493 return Thread::Current()->GetInvokeReq();
494}
495
496Thread* Dbg::GetDebugThread() {
497 return (gJdwpState != NULL) ? gJdwpState->GetDebugThread() : NULL;
498}
499
500void Dbg::ClearWaitForEventThread() {
501 gJdwpState->ClearWaitForEventThread();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700502}
503
504void Dbg::Connected() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700505 CHECK(!gDebuggerConnected);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800506 VLOG(jdwp) << "JDWP has attached";
Elliott Hughes3bb81562011-10-21 18:52:59 -0700507 gDebuggerConnected = true;
Elliott Hughes86964332012-02-15 19:37:42 -0800508 gDisposed = false;
509}
510
511void Dbg::Disposed() {
512 gDisposed = true;
513}
514
515bool Dbg::IsDisposed() {
516 return gDisposed;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700517}
518
Elliott Hughesc0f09332012-03-26 13:27:06 -0700519static void SetDebuggerUpdatesEnabledCallback(Thread* t, void* user_data) {
520 t->SetDebuggerUpdatesEnabled(*reinterpret_cast<bool*>(user_data));
521}
522
523static void SetDebuggerUpdatesEnabled(bool enabled) {
Ian Rogers50b35e22012-10-04 10:09:15 -0700524 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
Elliott Hughesf8349362012-06-18 15:00:06 -0700525 Runtime::Current()->GetThreadList()->ForEach(SetDebuggerUpdatesEnabledCallback, &enabled);
Elliott Hughesc0f09332012-03-26 13:27:06 -0700526}
527
Elliott Hughesa2155262011-11-16 16:26:58 -0800528void Dbg::GoActive() {
529 // Enable all debugging features, including scans for breakpoints.
530 // This is a no-op if we're already active.
531 // Only called from the JDWP handler thread.
532 if (gDebuggerActive) {
533 return;
534 }
535
536 LOG(INFO) << "Debugger is active";
537
Elliott Hughesc0f09332012-03-26 13:27:06 -0700538 {
539 // TODO: dalvik only warned if there were breakpoints left over. clear in Dbg::Disconnected?
jeffhao09bfc6a2012-12-11 18:11:43 -0800540 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Elliott Hughesc0f09332012-03-26 13:27:06 -0700541 CHECK_EQ(gBreakpoints.size(), 0U);
542 }
Elliott Hughesa2155262011-11-16 16:26:58 -0800543
544 gDebuggerActive = true;
Elliott Hughesc0f09332012-03-26 13:27:06 -0700545 SetDebuggerUpdatesEnabled(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700546}
547
548void Dbg::Disconnected() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700549 CHECK(gDebuggerConnected);
550
Elliott Hughesc0f09332012-03-26 13:27:06 -0700551 LOG(INFO) << "Debugger is no longer active";
Elliott Hughes234ab152011-10-26 14:02:26 -0700552
Elliott Hughesc0f09332012-03-26 13:27:06 -0700553 gDebuggerActive = false;
554 SetDebuggerUpdatesEnabled(false);
Elliott Hughes234ab152011-10-26 14:02:26 -0700555
556 gRegistry->Clear();
557 gDebuggerConnected = false;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700558}
559
Elliott Hughesc0f09332012-03-26 13:27:06 -0700560bool Dbg::IsDebuggerActive() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700561 return gDebuggerActive;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700562}
563
Elliott Hughesc0f09332012-03-26 13:27:06 -0700564bool Dbg::IsJdwpConfigured() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700565 return gJdwpConfigured;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700566}
567
568int64_t Dbg::LastDebuggerActivity() {
Elliott Hughesca951522011-12-05 12:01:32 -0800569 return gJdwpState->LastDebuggerActivity();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700570}
571
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700572void Dbg::UndoDebuggerSuspensions() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700573 Runtime::Current()->GetThreadList()->UndoDebuggerSuspensions();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700574}
575
576void Dbg::Exit(int status) {
Elliott Hughes1bba14f2011-12-01 18:00:36 -0800577 exit(status); // This is all dalvik did.
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700578}
579
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800580void Dbg::VisitRoots(RootVisitor* visitor, void* arg) {
Elliott Hughesbfe487b2011-10-26 15:48:55 -0700581 if (gRegistry != NULL) {
582 gRegistry->VisitRoots(visitor, arg);
583 }
584}
585
Elliott Hughes88d63092013-01-09 09:55:54 -0800586std::string Dbg::GetClassName(JDWP::RefTypeId class_id) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800587 mirror::Object* o = gRegistry->Get<mirror::Object*>(class_id);
Elliott Hughes436e3722012-02-17 20:01:47 -0800588 if (o == NULL) {
589 return "NULL";
590 }
591 if (o == kInvalidObject) {
Elliott Hughes88d63092013-01-09 09:55:54 -0800592 return StringPrintf("invalid object %p", reinterpret_cast<void*>(class_id));
Elliott Hughes436e3722012-02-17 20:01:47 -0800593 }
594 if (!o->IsClass()) {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800595 return StringPrintf("non-class %p", o); // This is only used for debugging output anyway.
596 }
Elliott Hughesc308a5d2012-02-16 17:12:06 -0800597 return DescriptorToName(ClassHelper(o->AsClass()).GetDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700598}
599
Elliott Hughes88d63092013-01-09 09:55:54 -0800600JDWP::JdwpError Dbg::GetClassObject(JDWP::RefTypeId id, JDWP::ObjectId& class_object_id) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800601 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800602 mirror::Class* c = DecodeClass(id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -0800603 if (c == NULL) {
604 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800605 }
Elliott Hughes88d63092013-01-09 09:55:54 -0800606 class_object_id = gRegistry->Add(c);
Elliott Hughes436e3722012-02-17 20:01:47 -0800607 return JDWP::ERR_NONE;
Elliott Hughes86964332012-02-15 19:37:42 -0800608}
609
Elliott Hughes88d63092013-01-09 09:55:54 -0800610JDWP::JdwpError Dbg::GetSuperclass(JDWP::RefTypeId id, JDWP::RefTypeId& superclass_id) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800611 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800612 mirror::Class* c = DecodeClass(id, status);
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800613 if (c == NULL) {
614 return status;
615 }
616 if (c->IsInterface()) {
617 // http://code.google.com/p/android/issues/detail?id=20856
Elliott Hughes88d63092013-01-09 09:55:54 -0800618 superclass_id = 0;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800619 } else {
Elliott Hughes88d63092013-01-09 09:55:54 -0800620 superclass_id = gRegistry->Add(c->GetSuperClass());
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800621 }
622 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700623}
624
Elliott Hughes436e3722012-02-17 20:01:47 -0800625JDWP::JdwpError Dbg::GetClassLoader(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800626 mirror::Object* o = gRegistry->Get<mirror::Object*>(id);
Elliott Hughes436e3722012-02-17 20:01:47 -0800627 if (o == NULL || o == kInvalidObject) {
628 return JDWP::ERR_INVALID_OBJECT;
629 }
630 expandBufAddObjectId(pReply, gRegistry->Add(o->GetClass()->GetClassLoader()));
631 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700632}
633
Elliott Hughes436e3722012-02-17 20:01:47 -0800634JDWP::JdwpError Dbg::GetModifiers(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) {
635 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800636 mirror::Class* c = DecodeClass(id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -0800637 if (c == NULL) {
638 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800639 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800640
641 uint32_t access_flags = c->GetAccessFlags() & kAccJavaFlagsMask;
642
643 // Set ACC_SUPER; dex files don't contain this flag, but all classes are supposed to have it set.
644 // Class.getModifiers doesn't return it, but JDWP does, so we set it here.
645 access_flags |= kAccSuper;
646
647 expandBufAdd4BE(pReply, access_flags);
648
649 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700650}
651
Elliott Hughesf327e072013-01-09 16:01:26 -0800652JDWP::JdwpError Dbg::GetMonitorInfo(JDWP::ObjectId object_id, JDWP::ExpandBuf* reply)
653 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800654 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughesf327e072013-01-09 16:01:26 -0800655 if (o == NULL || o == kInvalidObject) {
656 return JDWP::ERR_INVALID_OBJECT;
657 }
658
659 // Ensure all threads are suspended while we read objects' lock words.
660 Thread* self = Thread::Current();
661 Locks::mutator_lock_->SharedUnlock(self);
662 Locks::mutator_lock_->ExclusiveLock(self);
663
664 MonitorInfo monitor_info(o);
665
666 Locks::mutator_lock_->ExclusiveUnlock(self);
667 Locks::mutator_lock_->SharedLock(self);
668
669 if (monitor_info.owner != NULL) {
670 expandBufAddObjectId(reply, gRegistry->Add(monitor_info.owner->GetPeer()));
671 } else {
672 expandBufAddObjectId(reply, gRegistry->Add(NULL));
673 }
674 expandBufAdd4BE(reply, monitor_info.entry_count);
675 expandBufAdd4BE(reply, monitor_info.waiters.size());
676 for (size_t i = 0; i < monitor_info.waiters.size(); ++i) {
677 expandBufAddObjectId(reply, gRegistry->Add(monitor_info.waiters[i]->GetPeer()));
678 }
679 return JDWP::ERR_NONE;
680}
681
Elliott Hughes734b8c62013-01-11 15:32:45 -0800682JDWP::JdwpError Dbg::GetOwnedMonitors(JDWP::ObjectId thread_id,
683 std::vector<JDWP::ObjectId>& monitors,
684 std::vector<uint32_t>& stack_depths)
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800685 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
686 ScopedObjectAccessUnchecked soa(Thread::Current());
687 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
688 Thread* thread;
689 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
690 if (error != JDWP::ERR_NONE) {
691 return error;
692 }
693 if (!IsSuspendedForDebugger(soa, thread)) {
694 return JDWP::ERR_THREAD_NOT_SUSPENDED;
695 }
696
697 struct OwnedMonitorVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -0800698 OwnedMonitorVisitor(Thread* thread, Context* context)
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800699 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -0800700 : StackVisitor(thread, context), current_stack_depth(0) {}
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800701
702 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
703 // annotalysis.
704 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
705 if (!GetMethod()->IsRuntimeMethod()) {
706 Monitor::VisitLocks(this, AppendOwnedMonitors, this);
Elliott Hughes734b8c62013-01-11 15:32:45 -0800707 ++current_stack_depth;
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800708 }
709 return true;
710 }
711
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800712 static void AppendOwnedMonitors(mirror::Object* owned_monitor, void* arg) {
Ian Rogers7a22fa62013-01-23 12:16:16 -0800713 OwnedMonitorVisitor* visitor = reinterpret_cast<OwnedMonitorVisitor*>(arg);
Elliott Hughes734b8c62013-01-11 15:32:45 -0800714 visitor->monitors.push_back(owned_monitor);
715 visitor->stack_depths.push_back(visitor->current_stack_depth);
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800716 }
717
Elliott Hughes734b8c62013-01-11 15:32:45 -0800718 size_t current_stack_depth;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800719 std::vector<mirror::Object*> monitors;
Elliott Hughes734b8c62013-01-11 15:32:45 -0800720 std::vector<uint32_t> stack_depths;
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800721 };
Ian Rogers7a22fa62013-01-23 12:16:16 -0800722 UniquePtr<Context> context(Context::Create());
723 OwnedMonitorVisitor visitor(thread, context.get());
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800724 visitor.WalkStack();
725
726 for (size_t i = 0; i < visitor.monitors.size(); ++i) {
727 monitors.push_back(gRegistry->Add(visitor.monitors[i]));
Elliott Hughes734b8c62013-01-11 15:32:45 -0800728 stack_depths.push_back(visitor.stack_depths[i]);
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800729 }
730
731 return JDWP::ERR_NONE;
732}
733
Elliott Hughesf9501702013-01-11 11:22:27 -0800734JDWP::JdwpError Dbg::GetContendedMonitor(JDWP::ObjectId thread_id, JDWP::ObjectId& contended_monitor)
735 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
736 ScopedObjectAccessUnchecked soa(Thread::Current());
737 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
738 Thread* thread;
739 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
740 if (error != JDWP::ERR_NONE) {
741 return error;
742 }
743 if (!IsSuspendedForDebugger(soa, thread)) {
744 return JDWP::ERR_THREAD_NOT_SUSPENDED;
745 }
746
747 contended_monitor = gRegistry->Add(Monitor::GetContendedMonitor(thread));
748
749 return JDWP::ERR_NONE;
750}
751
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800752JDWP::JdwpError Dbg::GetInstanceCounts(const std::vector<JDWP::RefTypeId>& class_ids,
753 std::vector<uint64_t>& counts)
754 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
755
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800756 std::vector<mirror::Class*> classes;
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800757 counts.clear();
758 for (size_t i = 0; i < class_ids.size(); ++i) {
759 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800760 mirror::Class* c = DecodeClass(class_ids[i], status);
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800761 if (c == NULL) {
762 return status;
763 }
764 classes.push_back(c);
765 counts.push_back(0);
766 }
767
768 Runtime::Current()->GetHeap()->CountInstances(classes, false, &counts[0]);
769 return JDWP::ERR_NONE;
770}
771
Elliott Hughes3b78c942013-01-15 17:35:41 -0800772JDWP::JdwpError Dbg::GetInstances(JDWP::RefTypeId class_id, int32_t max_count, std::vector<JDWP::ObjectId>& instances)
773 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
774 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800775 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes3b78c942013-01-15 17:35:41 -0800776 if (c == NULL) {
777 return status;
778 }
779
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800780 std::vector<mirror::Object*> raw_instances;
Elliott Hughes3b78c942013-01-15 17:35:41 -0800781 Runtime::Current()->GetHeap()->GetInstances(c, max_count, raw_instances);
782 for (size_t i = 0; i < raw_instances.size(); ++i) {
783 instances.push_back(gRegistry->Add(raw_instances[i]));
784 }
785 return JDWP::ERR_NONE;
786}
787
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800788JDWP::JdwpError Dbg::GetReferringObjects(JDWP::ObjectId object_id, int32_t max_count,
789 std::vector<JDWP::ObjectId>& referring_objects)
790 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800791 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800792 if (o == NULL || o == kInvalidObject) {
793 return JDWP::ERR_INVALID_OBJECT;
794 }
795
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800796 std::vector<mirror::Object*> raw_instances;
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800797 Runtime::Current()->GetHeap()->GetReferringObjects(o, max_count, raw_instances);
798 for (size_t i = 0; i < raw_instances.size(); ++i) {
799 referring_objects.push_back(gRegistry->Add(raw_instances[i]));
800 }
801 return JDWP::ERR_NONE;
802}
803
Elliott Hughes88d63092013-01-09 09:55:54 -0800804JDWP::JdwpError Dbg::GetReflectedType(JDWP::RefTypeId class_id, JDWP::ExpandBuf* pReply) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800805 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800806 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -0800807 if (c == NULL) {
808 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800809 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800810
811 expandBufAdd1(pReply, c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS);
Elliott Hughes88d63092013-01-09 09:55:54 -0800812 expandBufAddRefTypeId(pReply, class_id);
Elliott Hughes436e3722012-02-17 20:01:47 -0800813 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700814}
815
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800816void Dbg::GetClassList(std::vector<JDWP::RefTypeId>& classes) {
Elliott Hughesa2155262011-11-16 16:26:58 -0800817 // Get the complete list of reference classes (i.e. all classes except
818 // the primitive types).
819 // Returns a newly-allocated buffer full of RefTypeId values.
820 struct ClassListCreator {
Elliott Hughesba8eee12012-01-24 20:25:24 -0800821 explicit ClassListCreator(std::vector<JDWP::RefTypeId>& classes) : classes(classes) {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800822 }
823
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800824 static bool Visit(mirror::Class* c, void* arg) {
Elliott Hughesa2155262011-11-16 16:26:58 -0800825 return reinterpret_cast<ClassListCreator*>(arg)->Visit(c);
826 }
827
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800828 bool Visit(mirror::Class* c) {
Elliott Hughesa2155262011-11-16 16:26:58 -0800829 if (!c->IsPrimitive()) {
830 classes.push_back(static_cast<JDWP::RefTypeId>(gRegistry->Add(c)));
831 }
832 return true;
833 }
834
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800835 std::vector<JDWP::RefTypeId>& classes;
Elliott Hughesa2155262011-11-16 16:26:58 -0800836 };
837
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800838 ClassListCreator clc(classes);
Elliott Hughesa2155262011-11-16 16:26:58 -0800839 Runtime::Current()->GetClassLinker()->VisitClasses(ClassListCreator::Visit, &clc);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700840}
841
Elliott Hughes88d63092013-01-09 09:55:54 -0800842JDWP::JdwpError Dbg::GetClassInfo(JDWP::RefTypeId class_id, JDWP::JdwpTypeTag* pTypeTag, uint32_t* pStatus, std::string* pDescriptor) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800843 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800844 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -0800845 if (c == NULL) {
846 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800847 }
848
Elliott Hughesa2155262011-11-16 16:26:58 -0800849 if (c->IsArrayClass()) {
850 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
851 *pTypeTag = JDWP::TT_ARRAY;
852 } else {
853 if (c->IsErroneous()) {
854 *pStatus = JDWP::CS_ERROR;
855 } else {
856 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED | JDWP::CS_INITIALIZED;
857 }
858 *pTypeTag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
859 }
860
861 if (pDescriptor != NULL) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800862 *pDescriptor = ClassHelper(c).GetDescriptor();
Elliott Hughesa2155262011-11-16 16:26:58 -0800863 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800864 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700865}
866
Elliott Hughesc3b77c72011-12-15 20:56:48 -0800867void Dbg::FindLoadedClassBySignature(const char* descriptor, std::vector<JDWP::RefTypeId>& ids) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800868 std::vector<mirror::Class*> classes;
Elliott Hughes6fa602d2011-12-02 17:54:25 -0800869 Runtime::Current()->GetClassLinker()->LookupClasses(descriptor, classes);
870 ids.clear();
871 for (size_t i = 0; i < classes.size(); ++i) {
872 ids.push_back(gRegistry->Add(classes[i]));
873 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700874}
875
Elliott Hughes88d63092013-01-09 09:55:54 -0800876JDWP::JdwpError Dbg::GetReferenceType(JDWP::ObjectId object_id, JDWP::ExpandBuf* pReply) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800877 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes436e3722012-02-17 20:01:47 -0800878 if (o == NULL || o == kInvalidObject) {
Elliott Hughes2435a572012-02-17 16:07:41 -0800879 return JDWP::ERR_INVALID_OBJECT;
Elliott Hughes499c5132011-11-17 14:55:11 -0800880 }
Elliott Hughes2435a572012-02-17 16:07:41 -0800881
882 JDWP::JdwpTypeTag type_tag;
883 if (o->GetClass()->IsArrayClass()) {
884 type_tag = JDWP::TT_ARRAY;
885 } else if (o->GetClass()->IsInterface()) {
886 type_tag = JDWP::TT_INTERFACE;
887 } else {
888 type_tag = JDWP::TT_CLASS;
889 }
890 JDWP::RefTypeId type_id = gRegistry->Add(o->GetClass());
891
892 expandBufAdd1(pReply, type_tag);
893 expandBufAddRefTypeId(pReply, type_id);
894
895 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700896}
897
Elliott Hughes88d63092013-01-09 09:55:54 -0800898JDWP::JdwpError Dbg::GetSignature(JDWP::RefTypeId class_id, std::string& signature) {
Elliott Hughes1fe7afb2012-02-13 17:23:03 -0800899 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800900 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes1fe7afb2012-02-13 17:23:03 -0800901 if (c == NULL) {
902 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800903 }
Elliott Hughes1fe7afb2012-02-13 17:23:03 -0800904 signature = ClassHelper(c).GetDescriptor();
905 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700906}
907
Elliott Hughes88d63092013-01-09 09:55:54 -0800908JDWP::JdwpError Dbg::GetSourceFile(JDWP::RefTypeId class_id, std::string& result) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800909 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800910 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -0800911 if (c == NULL) {
912 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800913 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800914 result = ClassHelper(c).GetSourceFile();
915 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700916}
917
Elliott Hughes88d63092013-01-09 09:55:54 -0800918JDWP::JdwpError Dbg::GetObjectTag(JDWP::ObjectId object_id, uint8_t& tag) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800919 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes546b9862012-06-20 16:06:13 -0700920 if (o == kInvalidObject) {
921 return JDWP::ERR_INVALID_OBJECT;
922 }
923 tag = TagFromObject(o);
924 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700925}
926
Elliott Hughesaed4be92011-12-02 16:16:23 -0800927size_t Dbg::GetTagWidth(JDWP::JdwpTag tag) {
Elliott Hughesdbb40792011-11-18 17:05:22 -0800928 switch (tag) {
929 case JDWP::JT_VOID:
930 return 0;
931 case JDWP::JT_BYTE:
932 case JDWP::JT_BOOLEAN:
933 return 1;
934 case JDWP::JT_CHAR:
935 case JDWP::JT_SHORT:
936 return 2;
937 case JDWP::JT_FLOAT:
938 case JDWP::JT_INT:
939 return 4;
940 case JDWP::JT_ARRAY:
941 case JDWP::JT_OBJECT:
942 case JDWP::JT_STRING:
943 case JDWP::JT_THREAD:
944 case JDWP::JT_THREAD_GROUP:
945 case JDWP::JT_CLASS_LOADER:
946 case JDWP::JT_CLASS_OBJECT:
947 return sizeof(JDWP::ObjectId);
948 case JDWP::JT_DOUBLE:
949 case JDWP::JT_LONG:
950 return 8;
951 default:
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800952 LOG(FATAL) << "Unknown tag " << tag;
Elliott Hughesdbb40792011-11-18 17:05:22 -0800953 return -1;
954 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700955}
956
Elliott Hughes88d63092013-01-09 09:55:54 -0800957JDWP::JdwpError Dbg::GetArrayLength(JDWP::ObjectId array_id, int& length) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800958 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800959 mirror::Array* a = DecodeArray(array_id, status);
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800960 if (a == NULL) {
961 return status;
Elliott Hughes24437992011-11-30 14:49:33 -0800962 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800963 length = a->GetLength();
964 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700965}
966
Elliott Hughes88d63092013-01-09 09:55:54 -0800967JDWP::JdwpError Dbg::OutputArray(JDWP::ObjectId array_id, int offset, int count, JDWP::ExpandBuf* pReply) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800968 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800969 mirror::Array* a = DecodeArray(array_id, status);
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800970 if (a == NULL) {
971 return status;
972 }
Elliott Hughes24437992011-11-30 14:49:33 -0800973
974 if (offset < 0 || count < 0 || offset > a->GetLength() || a->GetLength() - offset < count) {
975 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800976 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughes24437992011-11-30 14:49:33 -0800977 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800978 std::string descriptor(ClassHelper(a->GetClass()).GetDescriptor());
Elliott Hughes24437992011-11-30 14:49:33 -0800979 JDWP::JdwpTag tag = BasicTagFromDescriptor(descriptor.c_str() + 1);
980
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800981 expandBufAdd1(pReply, tag);
982 expandBufAdd4BE(pReply, count);
983
Elliott Hughes24437992011-11-30 14:49:33 -0800984 if (IsPrimitiveTag(tag)) {
985 size_t width = GetTagWidth(tag);
Elliott Hughes24437992011-11-30 14:49:33 -0800986 uint8_t* dst = expandBufAddSpace(pReply, count * width);
987 if (width == 8) {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800988 const uint64_t* src8 = reinterpret_cast<uint64_t*>(a->GetRawData(sizeof(uint64_t)));
Elliott Hughes24437992011-11-30 14:49:33 -0800989 for (int i = 0; i < count; ++i) JDWP::Write8BE(&dst, src8[offset + i]);
990 } else if (width == 4) {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800991 const uint32_t* src4 = reinterpret_cast<uint32_t*>(a->GetRawData(sizeof(uint32_t)));
Elliott Hughes24437992011-11-30 14:49:33 -0800992 for (int i = 0; i < count; ++i) JDWP::Write4BE(&dst, src4[offset + i]);
993 } else if (width == 2) {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800994 const uint16_t* src2 = reinterpret_cast<uint16_t*>(a->GetRawData(sizeof(uint16_t)));
Elliott Hughes24437992011-11-30 14:49:33 -0800995 for (int i = 0; i < count; ++i) JDWP::Write2BE(&dst, src2[offset + i]);
996 } else {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800997 const uint8_t* src = reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint8_t)));
Elliott Hughes24437992011-11-30 14:49:33 -0800998 memcpy(dst, &src[offset * width], count * width);
999 }
1000 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001001 mirror::ObjectArray<mirror::Object>* oa = a->AsObjectArray<mirror::Object>();
Elliott Hughes24437992011-11-30 14:49:33 -08001002 for (int i = 0; i < count; ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001003 mirror::Object* element = oa->Get(offset + i);
Elliott Hughes24437992011-11-30 14:49:33 -08001004 JDWP::JdwpTag specific_tag = (element != NULL) ? TagFromObject(element) : tag;
1005 expandBufAdd1(pReply, specific_tag);
1006 expandBufAddObjectId(pReply, gRegistry->Add(element));
1007 }
1008 }
1009
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001010 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001011}
1012
Elliott Hughes88d63092013-01-09 09:55:54 -08001013JDWP::JdwpError Dbg::SetArrayElements(JDWP::ObjectId array_id, int offset, int count,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001014 const uint8_t* src)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001015 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001016 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001017 mirror::Array* a = DecodeArray(array_id, status);
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001018 if (a == NULL) {
1019 return status;
1020 }
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001021
1022 if (offset < 0 || count < 0 || offset > a->GetLength() || a->GetLength() - offset < count) {
1023 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001024 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001025 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001026 std::string descriptor(ClassHelper(a->GetClass()).GetDescriptor());
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001027 JDWP::JdwpTag tag = BasicTagFromDescriptor(descriptor.c_str() + 1);
1028
1029 if (IsPrimitiveTag(tag)) {
1030 size_t width = GetTagWidth(tag);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001031 if (width == 8) {
Ian Rogersa15e67d2012-02-28 13:51:55 -08001032 uint8_t* dst = &(reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint64_t)))[offset * width]);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001033 for (int i = 0; i < count; ++i) {
1034 // Handle potentially non-aligned memory access one byte at a time for ARM's benefit.
1035 uint64_t value;
1036 for (size_t j = 0; j < sizeof(uint64_t); ++j) reinterpret_cast<uint8_t*>(&value)[j] = src[j];
1037 src += sizeof(uint64_t);
1038 JDWP::Write8BE(&dst, value);
1039 }
1040 } else if (width == 4) {
Ian Rogersa15e67d2012-02-28 13:51:55 -08001041 uint8_t* dst = &(reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint32_t)))[offset * width]);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001042 const uint32_t* src4 = reinterpret_cast<const uint32_t*>(src);
1043 for (int i = 0; i < count; ++i) JDWP::Write4BE(&dst, src4[i]);
1044 } else if (width == 2) {
Ian Rogersa15e67d2012-02-28 13:51:55 -08001045 uint8_t* dst = &(reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint16_t)))[offset * width]);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001046 const uint16_t* src2 = reinterpret_cast<const uint16_t*>(src);
1047 for (int i = 0; i < count; ++i) JDWP::Write2BE(&dst, src2[i]);
1048 } else {
Ian Rogersa15e67d2012-02-28 13:51:55 -08001049 uint8_t* dst = &(reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint8_t)))[offset * width]);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001050 memcpy(&dst[offset * width], src, count * width);
1051 }
1052 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001053 mirror::ObjectArray<mirror::Object>* oa = a->AsObjectArray<mirror::Object>();
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001054 for (int i = 0; i < count; ++i) {
1055 JDWP::ObjectId id = JDWP::ReadObjectId(&src);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001056 mirror::Object* o = gRegistry->Get<mirror::Object*>(id);
Elliott Hughes436e3722012-02-17 20:01:47 -08001057 if (o == kInvalidObject) {
1058 return JDWP::ERR_INVALID_OBJECT;
1059 }
1060 oa->Set(offset + i, o);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001061 }
1062 }
1063
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001064 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001065}
1066
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001067JDWP::ObjectId Dbg::CreateString(const std::string& str) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001068 return gRegistry->Add(mirror::String::AllocFromModifiedUtf8(Thread::Current(), str.c_str()));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001069}
1070
Elliott Hughes88d63092013-01-09 09:55:54 -08001071JDWP::JdwpError Dbg::CreateObject(JDWP::RefTypeId class_id, JDWP::ObjectId& new_object) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001072 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001073 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001074 if (c == NULL) {
1075 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001076 }
Ian Rogers50b35e22012-10-04 10:09:15 -07001077 new_object = gRegistry->Add(c->AllocObject(Thread::Current()));
Elliott Hughes436e3722012-02-17 20:01:47 -08001078 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001079}
1080
Elliott Hughesbf13d362011-12-08 15:51:37 -08001081/*
1082 * Used by Eclipse's "Display" view to evaluate "new byte[5]" to get "(byte[]) [0, 0, 0, 0, 0]".
1083 */
Elliott Hughes88d63092013-01-09 09:55:54 -08001084JDWP::JdwpError Dbg::CreateArrayObject(JDWP::RefTypeId array_class_id, uint32_t length,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001085 JDWP::ObjectId& new_array) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001086 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001087 mirror::Class* c = DecodeClass(array_class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001088 if (c == NULL) {
1089 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001090 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001091 new_array = gRegistry->Add(mirror::Array::Alloc(Thread::Current(), c, length));
Elliott Hughes436e3722012-02-17 20:01:47 -08001092 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001093}
1094
Elliott Hughes88d63092013-01-09 09:55:54 -08001095bool Dbg::MatchType(JDWP::RefTypeId instance_class_id, JDWP::RefTypeId class_id) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001096 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001097 mirror::Class* c1 = DecodeClass(instance_class_id, status);
Elliott Hughesa656a0f2012-02-21 18:03:44 -08001098 CHECK(c1 != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001099 mirror::Class* c2 = DecodeClass(class_id, status);
Elliott Hughesa656a0f2012-02-21 18:03:44 -08001100 CHECK(c2 != NULL);
1101 return c1->IsAssignableFrom(c2);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001102}
1103
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001104static JDWP::FieldId ToFieldId(const mirror::Field* f)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001105 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001106#ifdef MOVING_GARBAGE_COLLECTOR
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001107 UNIMPLEMENTED(FATAL);
Elliott Hughes03181a82011-11-17 17:22:21 -08001108#else
1109 return static_cast<JDWP::FieldId>(reinterpret_cast<uintptr_t>(f));
1110#endif
1111}
1112
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001113static JDWP::MethodId ToMethodId(const mirror::AbstractMethod* m)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001114 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001115#ifdef MOVING_GARBAGE_COLLECTOR
1116 UNIMPLEMENTED(FATAL);
1117#else
1118 return static_cast<JDWP::MethodId>(reinterpret_cast<uintptr_t>(m));
1119#endif
1120}
1121
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001122static mirror::Field* FromFieldId(JDWP::FieldId fid)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001123 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesaed4be92011-12-02 16:16:23 -08001124#ifdef MOVING_GARBAGE_COLLECTOR
1125 UNIMPLEMENTED(FATAL);
1126#else
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001127 return reinterpret_cast<mirror::Field*>(static_cast<uintptr_t>(fid));
Elliott Hughesaed4be92011-12-02 16:16:23 -08001128#endif
1129}
1130
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001131static mirror::AbstractMethod* FromMethodId(JDWP::MethodId mid)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001132 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001133#ifdef MOVING_GARBAGE_COLLECTOR
1134 UNIMPLEMENTED(FATAL);
1135#else
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001136 return reinterpret_cast<mirror::AbstractMethod*>(static_cast<uintptr_t>(mid));
Elliott Hughes03181a82011-11-17 17:22:21 -08001137#endif
1138}
1139
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001140static void SetLocation(JDWP::JdwpLocation& location, mirror::AbstractMethod* m, uint32_t dex_pc)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001141 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001142 if (m == NULL) {
1143 memset(&location, 0, sizeof(location));
1144 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001145 mirror::Class* c = m->GetDeclaringClass();
Elliott Hughes74847412012-06-20 18:10:21 -07001146 location.type_tag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
1147 location.class_id = gRegistry->Add(c);
1148 location.method_id = ToMethodId(m);
Ian Rogers0399dde2012-06-06 17:09:28 -07001149 location.dex_pc = dex_pc;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001150 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08001151}
1152
Elliott Hughesa96836a2013-01-17 12:27:49 -08001153std::string Dbg::GetMethodName(JDWP::MethodId method_id)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001154 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001155 mirror::AbstractMethod* m = FromMethodId(method_id);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001156 return MethodHelper(m).GetName();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001157}
1158
Elliott Hughesa96836a2013-01-17 12:27:49 -08001159std::string Dbg::GetFieldName(JDWP::FieldId field_id)
1160 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001161 mirror::Field* f = FromFieldId(field_id);
Elliott Hughesa96836a2013-01-17 12:27:49 -08001162 return FieldHelper(f).GetName();
1163}
1164
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001165/*
1166 * Augment the access flags for synthetic methods and fields by setting
1167 * the (as described by the spec) "0xf0000000 bit". Also, strip out any
1168 * flags not specified by the Java programming language.
1169 */
1170static uint32_t MangleAccessFlags(uint32_t accessFlags) {
1171 accessFlags &= kAccJavaFlagsMask;
1172 if ((accessFlags & kAccSynthetic) != 0) {
1173 accessFlags |= 0xf0000000;
1174 }
1175 return accessFlags;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001176}
1177
Elliott Hughesdbb40792011-11-18 17:05:22 -08001178static const uint16_t kEclipseWorkaroundSlot = 1000;
1179
1180/*
1181 * Eclipse appears to expect that the "this" reference is in slot zero.
1182 * If it's not, the "variables" display will show two copies of "this",
1183 * possibly because it gets "this" from SF.ThisObject and then displays
1184 * all locals with nonzero slot numbers.
1185 *
1186 * So, we remap the item in slot 0 to 1000, and remap "this" to zero. On
1187 * SF.GetValues / SF.SetValues we map them back.
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001188 *
1189 * TODO: jdb uses the value to determine whether a variable is a local or an argument,
1190 * by checking whether it's less than the number of arguments. To make that work, we'd
1191 * have to "mangle" all the arguments to come first, not just the implicit argument 'this'.
Elliott Hughesdbb40792011-11-18 17:05:22 -08001192 */
1193static uint16_t MangleSlot(uint16_t slot, const char* name) {
1194 uint16_t newSlot = slot;
1195 if (strcmp(name, "this") == 0) {
1196 newSlot = 0;
1197 } else if (slot == 0) {
1198 newSlot = kEclipseWorkaroundSlot;
1199 }
1200 return newSlot;
1201}
1202
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001203static uint16_t DemangleSlot(uint16_t slot, mirror::AbstractMethod* m)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001204 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001205 if (slot == kEclipseWorkaroundSlot) {
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001206 return 0;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001207 } else if (slot == 0) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001208 const DexFile::CodeItem* code_item = MethodHelper(m).GetCodeItem();
Elliott Hughescaf76542012-06-28 16:08:22 -07001209 CHECK(code_item != NULL) << PrettyMethod(m);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001210 return code_item->registers_size_ - code_item->ins_size_;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001211 }
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001212 return slot;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001213}
1214
Elliott Hughes88d63092013-01-09 09:55:54 -08001215JDWP::JdwpError Dbg::OutputDeclaredFields(JDWP::RefTypeId class_id, bool with_generic, JDWP::ExpandBuf* pReply) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001216 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001217 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001218 if (c == NULL) {
1219 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001220 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001221
1222 size_t instance_field_count = c->NumInstanceFields();
1223 size_t static_field_count = c->NumStaticFields();
1224
1225 expandBufAdd4BE(pReply, instance_field_count + static_field_count);
1226
1227 for (size_t i = 0; i < instance_field_count + static_field_count; ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001228 mirror::Field* f = (i < instance_field_count) ? c->GetInstanceField(i) : c->GetStaticField(i - instance_field_count);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001229 FieldHelper fh(f);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001230 expandBufAddFieldId(pReply, ToFieldId(f));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001231 expandBufAddUtf8String(pReply, fh.GetName());
1232 expandBufAddUtf8String(pReply, fh.GetTypeDescriptor());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001233 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001234 static const char genericSignature[1] = "";
1235 expandBufAddUtf8String(pReply, genericSignature);
1236 }
1237 expandBufAdd4BE(pReply, MangleAccessFlags(f->GetAccessFlags()));
1238 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001239 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001240}
1241
Elliott Hughes88d63092013-01-09 09:55:54 -08001242JDWP::JdwpError Dbg::OutputDeclaredMethods(JDWP::RefTypeId class_id, bool with_generic,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001243 JDWP::ExpandBuf* pReply) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001244 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001245 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001246 if (c == NULL) {
1247 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001248 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001249
1250 size_t direct_method_count = c->NumDirectMethods();
1251 size_t virtual_method_count = c->NumVirtualMethods();
1252
1253 expandBufAdd4BE(pReply, direct_method_count + virtual_method_count);
1254
1255 for (size_t i = 0; i < direct_method_count + virtual_method_count; ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001256 mirror::AbstractMethod* m = (i < direct_method_count) ? c->GetDirectMethod(i) : c->GetVirtualMethod(i - direct_method_count);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001257 MethodHelper mh(m);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001258 expandBufAddMethodId(pReply, ToMethodId(m));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001259 expandBufAddUtf8String(pReply, mh.GetName());
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001260 expandBufAddUtf8String(pReply, mh.GetSignature());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001261 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001262 static const char genericSignature[1] = "";
1263 expandBufAddUtf8String(pReply, genericSignature);
1264 }
1265 expandBufAdd4BE(pReply, MangleAccessFlags(m->GetAccessFlags()));
1266 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001267 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001268}
1269
Elliott Hughes88d63092013-01-09 09:55:54 -08001270JDWP::JdwpError Dbg::OutputDeclaredInterfaces(JDWP::RefTypeId class_id, JDWP::ExpandBuf* pReply) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001271 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001272 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001273 if (c == NULL) {
1274 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001275 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001276
1277 ClassHelper kh(c);
Ian Rogersd24e2642012-06-06 21:21:43 -07001278 size_t interface_count = kh.NumDirectInterfaces();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001279 expandBufAdd4BE(pReply, interface_count);
1280 for (size_t i = 0; i < interface_count; ++i) {
Ian Rogersd24e2642012-06-06 21:21:43 -07001281 expandBufAddRefTypeId(pReply, gRegistry->Add(kh.GetDirectInterface(i)));
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001282 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001283 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001284}
1285
Elliott Hughes88d63092013-01-09 09:55:54 -08001286void Dbg::OutputLineTable(JDWP::RefTypeId, JDWP::MethodId method_id, JDWP::ExpandBuf* pReply)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001287 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001288 struct DebugCallbackContext {
1289 int numItems;
1290 JDWP::ExpandBuf* pReply;
1291
Elliott Hughes2435a572012-02-17 16:07:41 -08001292 static bool Callback(void* context, uint32_t address, uint32_t line_number) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001293 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
1294 expandBufAdd8BE(pContext->pReply, address);
Elliott Hughes2435a572012-02-17 16:07:41 -08001295 expandBufAdd4BE(pContext->pReply, line_number);
Elliott Hughes03181a82011-11-17 17:22:21 -08001296 pContext->numItems++;
1297 return true;
1298 }
1299 };
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001300 mirror::AbstractMethod* m = FromMethodId(method_id);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001301 MethodHelper mh(m);
Elliott Hughes03181a82011-11-17 17:22:21 -08001302 uint64_t start, end;
1303 if (m->IsNative()) {
1304 start = -1;
1305 end = -1;
1306 } else {
1307 start = 0;
jeffhao14f0db92012-12-14 17:50:42 -08001308 // Return the index of the last instruction
1309 end = mh.GetCodeItem()->insns_size_in_code_units_ - 1;
Elliott Hughes03181a82011-11-17 17:22:21 -08001310 }
1311
1312 expandBufAdd8BE(pReply, start);
1313 expandBufAdd8BE(pReply, end);
1314
1315 // Add numLines later
1316 size_t numLinesOffset = expandBufGetLength(pReply);
1317 expandBufAdd4BE(pReply, 0);
1318
1319 DebugCallbackContext context;
1320 context.numItems = 0;
1321 context.pReply = pReply;
1322
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001323 mh.GetDexFile().DecodeDebugInfo(mh.GetCodeItem(), m->IsStatic(), m->GetDexMethodIndex(),
1324 DebugCallbackContext::Callback, NULL, &context);
Elliott Hughes03181a82011-11-17 17:22:21 -08001325
1326 JDWP::Set4BE(expandBufGetBuffer(pReply) + numLinesOffset, context.numItems);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001327}
1328
Elliott Hughes88d63092013-01-09 09:55:54 -08001329void Dbg::OutputVariableTable(JDWP::RefTypeId, JDWP::MethodId method_id, bool with_generic, JDWP::ExpandBuf* pReply) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001330 struct DebugCallbackContext {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001331 JDWP::ExpandBuf* pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001332 size_t variable_count;
1333 bool with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001334
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001335 static void Callback(void* context, uint16_t slot, uint32_t startAddress, uint32_t endAddress, const char* name, const char* descriptor, const char* signature) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001336 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
1337
Elliott Hughesad3da692012-02-24 16:51:35 -08001338 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, name));
Elliott Hughesdbb40792011-11-18 17:05:22 -08001339
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001340 slot = MangleSlot(slot, name);
1341
Elliott Hughesdbb40792011-11-18 17:05:22 -08001342 expandBufAdd8BE(pContext->pReply, startAddress);
1343 expandBufAddUtf8String(pContext->pReply, name);
1344 expandBufAddUtf8String(pContext->pReply, descriptor);
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001345 if (pContext->with_generic) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001346 expandBufAddUtf8String(pContext->pReply, signature);
1347 }
1348 expandBufAdd4BE(pContext->pReply, endAddress - startAddress);
1349 expandBufAdd4BE(pContext->pReply, slot);
1350
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001351 ++pContext->variable_count;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001352 }
1353 };
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001354 mirror::AbstractMethod* m = FromMethodId(method_id);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001355 MethodHelper mh(m);
1356 const DexFile::CodeItem* code_item = mh.GetCodeItem();
Elliott Hughesdbb40792011-11-18 17:05:22 -08001357
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001358 // arg_count considers doubles and longs to take 2 units.
1359 // variable_count considers everything to take 1 unit.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001360 std::string shorty(mh.GetShorty());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001361 expandBufAdd4BE(pReply, mirror::AbstractMethod::NumArgRegisters(shorty));
Elliott Hughesdbb40792011-11-18 17:05:22 -08001362
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001363 // We don't know the total number of variables yet, so leave a blank and update it later.
1364 size_t variable_count_offset = expandBufGetLength(pReply);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001365 expandBufAdd4BE(pReply, 0);
1366
1367 DebugCallbackContext context;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001368 context.pReply = pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001369 context.variable_count = 0;
1370 context.with_generic = with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001371
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001372 mh.GetDexFile().DecodeDebugInfo(code_item, m->IsStatic(), m->GetDexMethodIndex(), NULL,
1373 DebugCallbackContext::Callback, &context);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001374
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001375 JDWP::Set4BE(expandBufGetBuffer(pReply) + variable_count_offset, context.variable_count);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001376}
1377
Elliott Hughes9777ba22013-01-17 09:04:19 -08001378JDWP::JdwpError Dbg::GetBytecodes(JDWP::RefTypeId, JDWP::MethodId method_id,
1379 std::vector<uint8_t>& bytecodes)
1380 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001381 mirror::AbstractMethod* m = FromMethodId(method_id);
Elliott Hughes9777ba22013-01-17 09:04:19 -08001382 if (m == NULL) {
1383 return JDWP::ERR_INVALID_METHODID;
1384 }
1385 MethodHelper mh(m);
1386 const DexFile::CodeItem* code_item = mh.GetCodeItem();
1387 size_t byte_count = code_item->insns_size_in_code_units_ * 2;
1388 const uint8_t* begin = reinterpret_cast<const uint8_t*>(code_item->insns_);
1389 const uint8_t* end = begin + byte_count;
1390 for (const uint8_t* p = begin; p != end; ++p) {
1391 bytecodes.push_back(*p);
1392 }
1393 return JDWP::ERR_NONE;
1394}
1395
Elliott Hughes88d63092013-01-09 09:55:54 -08001396JDWP::JdwpTag Dbg::GetFieldBasicTag(JDWP::FieldId field_id) {
1397 return BasicTagFromDescriptor(FieldHelper(FromFieldId(field_id)).GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001398}
1399
Elliott Hughes88d63092013-01-09 09:55:54 -08001400JDWP::JdwpTag Dbg::GetStaticFieldBasicTag(JDWP::FieldId field_id) {
1401 return BasicTagFromDescriptor(FieldHelper(FromFieldId(field_id)).GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001402}
1403
Elliott Hughes88d63092013-01-09 09:55:54 -08001404static JDWP::JdwpError GetFieldValueImpl(JDWP::RefTypeId ref_type_id, JDWP::ObjectId object_id,
1405 JDWP::FieldId field_id, JDWP::ExpandBuf* pReply,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001406 bool is_static)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001407 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes0cf74332012-02-23 23:14:00 -08001408 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001409 mirror::Class* c = DecodeClass(ref_type_id, status);
Elliott Hughes88d63092013-01-09 09:55:54 -08001410 if (ref_type_id != 0 && c == NULL) {
Elliott Hughes0cf74332012-02-23 23:14:00 -08001411 return status;
1412 }
1413
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001414 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001415 if ((!is_static && o == NULL) || o == kInvalidObject) {
1416 return JDWP::ERR_INVALID_OBJECT;
1417 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001418 mirror::Field* f = FromFieldId(field_id);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001419
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001420 mirror::Class* receiver_class = c;
Elliott Hughes0cf74332012-02-23 23:14:00 -08001421 if (receiver_class == NULL && o != NULL) {
1422 receiver_class = o->GetClass();
1423 }
1424 // TODO: should we give up now if receiver_class is NULL?
1425 if (receiver_class != NULL && !f->GetDeclaringClass()->IsAssignableFrom(receiver_class)) {
1426 LOG(INFO) << "ERR_INVALID_FIELDID: " << PrettyField(f) << " " << PrettyClass(receiver_class);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001427 return JDWP::ERR_INVALID_FIELDID;
1428 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001429
Elliott Hughes0cf74332012-02-23 23:14:00 -08001430 // The RI only enforces the static/non-static mismatch in one direction.
1431 // TODO: should we change the tests and check both?
1432 if (is_static) {
1433 if (!f->IsStatic()) {
1434 return JDWP::ERR_INVALID_FIELDID;
1435 }
1436 } else {
1437 if (f->IsStatic()) {
1438 LOG(WARNING) << "Ignoring non-NULL receiver for ObjectReference.SetValues on static field " << PrettyField(f);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001439 }
1440 }
jeffhao0dfbb7e2012-11-28 15:26:03 -08001441 if (f->IsStatic()) {
1442 o = f->GetDeclaringClass();
1443 }
Elliott Hughes0cf74332012-02-23 23:14:00 -08001444
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001445 JDWP::JdwpTag tag = BasicTagFromDescriptor(FieldHelper(f).GetTypeDescriptor());
Elliott Hughesaed4be92011-12-02 16:16:23 -08001446
1447 if (IsPrimitiveTag(tag)) {
1448 expandBufAdd1(pReply, tag);
1449 if (tag == JDWP::JT_BOOLEAN || tag == JDWP::JT_BYTE) {
1450 expandBufAdd1(pReply, f->Get32(o));
1451 } else if (tag == JDWP::JT_CHAR || tag == JDWP::JT_SHORT) {
1452 expandBufAdd2BE(pReply, f->Get32(o));
1453 } else if (tag == JDWP::JT_FLOAT || tag == JDWP::JT_INT) {
1454 expandBufAdd4BE(pReply, f->Get32(o));
1455 } else if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
1456 expandBufAdd8BE(pReply, f->Get64(o));
1457 } else {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001458 LOG(FATAL) << "Unknown tag: " << tag;
Elliott Hughesaed4be92011-12-02 16:16:23 -08001459 }
1460 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001461 mirror::Object* value = f->GetObject(o);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001462 expandBufAdd1(pReply, TagFromObject(value));
1463 expandBufAddObjectId(pReply, gRegistry->Add(value));
1464 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001465 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001466}
1467
Elliott Hughes88d63092013-01-09 09:55:54 -08001468JDWP::JdwpError Dbg::GetFieldValue(JDWP::ObjectId object_id, JDWP::FieldId field_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001469 JDWP::ExpandBuf* pReply) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001470 return GetFieldValueImpl(0, object_id, field_id, pReply, false);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001471}
1472
Elliott Hughes88d63092013-01-09 09:55:54 -08001473JDWP::JdwpError Dbg::GetStaticFieldValue(JDWP::RefTypeId ref_type_id, JDWP::FieldId field_id, JDWP::ExpandBuf* pReply) {
1474 return GetFieldValueImpl(ref_type_id, 0, field_id, pReply, true);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001475}
1476
Elliott Hughes88d63092013-01-09 09:55:54 -08001477static JDWP::JdwpError SetFieldValueImpl(JDWP::ObjectId object_id, JDWP::FieldId field_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001478 uint64_t value, int width, bool is_static)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001479 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001480 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001481 if ((!is_static && o == NULL) || o == kInvalidObject) {
1482 return JDWP::ERR_INVALID_OBJECT;
1483 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001484 mirror::Field* f = FromFieldId(field_id);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001485
1486 // The RI only enforces the static/non-static mismatch in one direction.
1487 // TODO: should we change the tests and check both?
1488 if (is_static) {
1489 if (!f->IsStatic()) {
1490 return JDWP::ERR_INVALID_FIELDID;
1491 }
1492 } else {
1493 if (f->IsStatic()) {
1494 LOG(WARNING) << "Ignoring non-NULL receiver for ObjectReference.SetValues on static field " << PrettyField(f);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001495 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001496 }
jeffhao0dfbb7e2012-11-28 15:26:03 -08001497 if (f->IsStatic()) {
1498 o = f->GetDeclaringClass();
1499 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001500
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001501 JDWP::JdwpTag tag = BasicTagFromDescriptor(FieldHelper(f).GetTypeDescriptor());
Elliott Hughesaed4be92011-12-02 16:16:23 -08001502
1503 if (IsPrimitiveTag(tag)) {
1504 if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001505 CHECK_EQ(width, 8);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001506 f->Set64(o, value);
1507 } else {
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001508 CHECK_LE(width, 4);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001509 f->Set32(o, value);
1510 }
1511 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001512 mirror::Object* v = gRegistry->Get<mirror::Object*>(value);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001513 if (v == kInvalidObject) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001514 return JDWP::ERR_INVALID_OBJECT;
1515 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001516 if (v != NULL) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001517 mirror::Class* field_type = FieldHelper(f).GetType();
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001518 if (!field_type->IsAssignableFrom(v->GetClass())) {
1519 return JDWP::ERR_INVALID_OBJECT;
1520 }
1521 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001522 f->SetObject(o, v);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001523 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001524
1525 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001526}
1527
Elliott Hughes88d63092013-01-09 09:55:54 -08001528JDWP::JdwpError Dbg::SetFieldValue(JDWP::ObjectId object_id, JDWP::FieldId field_id, uint64_t value,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001529 int width) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001530 return SetFieldValueImpl(object_id, field_id, value, width, false);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001531}
1532
Elliott Hughes88d63092013-01-09 09:55:54 -08001533JDWP::JdwpError Dbg::SetStaticFieldValue(JDWP::FieldId field_id, uint64_t value, int width) {
1534 return SetFieldValueImpl(0, field_id, value, width, true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001535}
1536
Elliott Hughes88d63092013-01-09 09:55:54 -08001537std::string Dbg::StringToUtf8(JDWP::ObjectId string_id) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001538 mirror::String* s = gRegistry->Get<mirror::String*>(string_id);
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001539 return s->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001540}
1541
Elliott Hughes221229c2013-01-08 18:17:50 -08001542JDWP::JdwpError Dbg::GetThreadName(JDWP::ObjectId thread_id, std::string& name) {
jeffhaoa77f0f62012-12-05 17:19:31 -08001543 ScopedObjectAccessUnchecked soa(Thread::Current());
1544 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001545 Thread* thread;
1546 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1547 if (error != JDWP::ERR_NONE && error != JDWP::ERR_THREAD_NOT_ALIVE) {
1548 return error;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001549 }
Elliott Hughes221229c2013-01-08 18:17:50 -08001550
1551 // We still need to report the zombie threads' names, so we can't just call Thread::GetThreadName.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001552 mirror::Object* thread_object = gRegistry->Get<mirror::Object*>(thread_id);
1553 mirror::Field* java_lang_Thread_name_field =
1554 soa.DecodeField(WellKnownClasses::java_lang_Thread_name);
1555 mirror::String* s =
1556 reinterpret_cast<mirror::String*>(java_lang_Thread_name_field->GetObject(thread_object));
Elliott Hughes221229c2013-01-08 18:17:50 -08001557 if (s != NULL) {
1558 name = s->ToModifiedUtf8();
1559 }
1560 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001561}
1562
Elliott Hughes221229c2013-01-08 18:17:50 -08001563JDWP::JdwpError Dbg::GetThreadGroup(JDWP::ObjectId thread_id, JDWP::ExpandBuf* pReply) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001564 ScopedObjectAccess soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001565 mirror::Object* thread_object = gRegistry->Get<mirror::Object*>(thread_id);
Elliott Hughes221229c2013-01-08 18:17:50 -08001566 if (thread_object == kInvalidObject) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001567 return JDWP::ERR_INVALID_OBJECT;
1568 }
1569
1570 // Okay, so it's an object, but is it actually a thread?
Ian Rogers50b35e22012-10-04 10:09:15 -07001571 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001572 Thread* thread;
1573 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1574 if (error == JDWP::ERR_THREAD_NOT_ALIVE) {
1575 // Zombie threads are in the null group.
1576 expandBufAddObjectId(pReply, JDWP::ObjectId(0));
1577 return JDWP::ERR_NONE;
1578 }
1579 if (error != JDWP::ERR_NONE) {
1580 return error;
Elliott Hughes2435a572012-02-17 16:07:41 -08001581 }
Elliott Hughes499c5132011-11-17 14:55:11 -08001582
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001583 mirror::Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/Thread;");
Elliott Hughes499c5132011-11-17 14:55:11 -08001584 CHECK(c != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001585 mirror::Field* f = c->FindInstanceField("group", "Ljava/lang/ThreadGroup;");
Elliott Hughes499c5132011-11-17 14:55:11 -08001586 CHECK(f != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001587 mirror::Object* group = f->GetObject(thread_object);
Elliott Hughes499c5132011-11-17 14:55:11 -08001588 CHECK(group != NULL);
Elliott Hughes2435a572012-02-17 16:07:41 -08001589 JDWP::ObjectId thread_group_id = gRegistry->Add(group);
1590
1591 expandBufAddObjectId(pReply, thread_group_id);
1592 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001593}
1594
Elliott Hughes88d63092013-01-09 09:55:54 -08001595std::string Dbg::GetThreadGroupName(JDWP::ObjectId thread_group_id) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001596 ScopedObjectAccess soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001597 mirror::Object* thread_group = gRegistry->Get<mirror::Object*>(thread_group_id);
Elliott Hughes499c5132011-11-17 14:55:11 -08001598 CHECK(thread_group != NULL);
1599
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001600 mirror::Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/ThreadGroup;");
Elliott Hughes499c5132011-11-17 14:55:11 -08001601 CHECK(c != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001602 mirror::Field* f = c->FindInstanceField("name", "Ljava/lang/String;");
Elliott Hughes499c5132011-11-17 14:55:11 -08001603 CHECK(f != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001604 mirror::String* s = reinterpret_cast<mirror::String*>(f->GetObject(thread_group));
Elliott Hughes499c5132011-11-17 14:55:11 -08001605 return s->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001606}
1607
Elliott Hughes88d63092013-01-09 09:55:54 -08001608JDWP::ObjectId Dbg::GetThreadGroupParent(JDWP::ObjectId thread_group_id) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001609 mirror::Object* thread_group = gRegistry->Get<mirror::Object*>(thread_group_id);
Elliott Hughes4e235312011-12-02 11:34:15 -08001610 CHECK(thread_group != NULL);
1611
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001612 mirror::Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/ThreadGroup;");
Elliott Hughes4e235312011-12-02 11:34:15 -08001613 CHECK(c != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001614 mirror::Field* f = c->FindInstanceField("parent", "Ljava/lang/ThreadGroup;");
Elliott Hughes4e235312011-12-02 11:34:15 -08001615 CHECK(f != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001616 mirror::Object* parent = f->GetObject(thread_group);
Elliott Hughes4e235312011-12-02 11:34:15 -08001617 return gRegistry->Add(parent);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001618}
1619
1620JDWP::ObjectId Dbg::GetSystemThreadGroupId() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001621 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001622 mirror::Field* f = soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_systemThreadGroup);
1623 mirror::Object* group = f->GetObject(f->GetDeclaringClass());
Ian Rogers365c1022012-06-22 15:05:28 -07001624 return gRegistry->Add(group);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001625}
1626
1627JDWP::ObjectId Dbg::GetMainThreadGroupId() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001628 ScopedObjectAccess soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001629 mirror::Field* f = soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_mainThreadGroup);
1630 mirror::Object* group = f->GetObject(f->GetDeclaringClass());
Ian Rogers365c1022012-06-22 15:05:28 -07001631 return gRegistry->Add(group);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001632}
1633
Elliott Hughes221229c2013-01-08 18:17:50 -08001634JDWP::JdwpError Dbg::GetThreadStatus(JDWP::ObjectId thread_id, JDWP::JdwpThreadStatus* pThreadStatus, JDWP::JdwpSuspendStatus* pSuspendStatus) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001635 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes499c5132011-11-17 14:55:11 -08001636
Elliott Hughes9e0c1752013-01-09 14:02:58 -08001637 *pSuspendStatus = JDWP::SUSPEND_STATUS_NOT_SUSPENDED;
1638
Ian Rogers50b35e22012-10-04 10:09:15 -07001639 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001640 Thread* thread;
1641 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1642 if (error != JDWP::ERR_NONE) {
1643 if (error == JDWP::ERR_THREAD_NOT_ALIVE) {
1644 *pThreadStatus = JDWP::TS_ZOMBIE;
Elliott Hughes221229c2013-01-08 18:17:50 -08001645 return JDWP::ERR_NONE;
1646 }
1647 return error;
Elliott Hughes499c5132011-11-17 14:55:11 -08001648 }
1649
Elliott Hughes9e0c1752013-01-09 14:02:58 -08001650 if (IsSuspendedForDebugger(soa, thread)) {
1651 *pSuspendStatus = JDWP::SUSPEND_STATUS_SUSPENDED;
Elliott Hughes499c5132011-11-17 14:55:11 -08001652 }
1653
Elliott Hughes9e0c1752013-01-09 14:02:58 -08001654 switch (thread->GetState()) {
1655 case kBlocked: *pThreadStatus = JDWP::TS_MONITOR; break;
1656 case kNative: *pThreadStatus = JDWP::TS_RUNNING; break;
1657 case kRunnable: *pThreadStatus = JDWP::TS_RUNNING; break;
1658 case kSleeping: *pThreadStatus = JDWP::TS_SLEEPING; break;
1659 case kStarting: *pThreadStatus = JDWP::TS_ZOMBIE; break;
1660 case kSuspended: *pThreadStatus = JDWP::TS_RUNNING; break;
1661 case kTerminated: *pThreadStatus = JDWP::TS_ZOMBIE; break;
1662 case kTimedWaiting: *pThreadStatus = JDWP::TS_WAIT; break;
1663 case kWaitingForDebuggerSend: *pThreadStatus = JDWP::TS_WAIT; break;
1664 case kWaitingForDebuggerSuspension: *pThreadStatus = JDWP::TS_WAIT; break;
1665 case kWaitingForDebuggerToAttach: *pThreadStatus = JDWP::TS_WAIT; break;
1666 case kWaitingForGcToComplete: *pThreadStatus = JDWP::TS_WAIT; break;
1667 case kWaitingForJniOnLoad: *pThreadStatus = JDWP::TS_WAIT; break;
1668 case kWaitingForSignalCatcherOutput: *pThreadStatus = JDWP::TS_WAIT; break;
1669 case kWaitingInMainDebuggerLoop: *pThreadStatus = JDWP::TS_WAIT; break;
1670 case kWaitingInMainSignalCatcherLoop: *pThreadStatus = JDWP::TS_WAIT; break;
1671 case kWaitingPerformingGc: *pThreadStatus = JDWP::TS_WAIT; break;
1672 case kWaiting: *pThreadStatus = JDWP::TS_WAIT; break;
1673 // Don't add a 'default' here so the compiler can spot incompatible enum changes.
1674 }
Elliott Hughes221229c2013-01-08 18:17:50 -08001675 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001676}
1677
Elliott Hughes221229c2013-01-08 18:17:50 -08001678JDWP::JdwpError Dbg::GetThreadDebugSuspendCount(JDWP::ObjectId thread_id, JDWP::ExpandBuf* pReply) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001679 ScopedObjectAccess soa(Thread::Current());
Ian Rogers50b35e22012-10-04 10:09:15 -07001680 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001681 Thread* thread;
1682 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1683 if (error != JDWP::ERR_NONE) {
1684 return error;
Elliott Hughes2435a572012-02-17 16:07:41 -08001685 }
Ian Rogers50b35e22012-10-04 10:09:15 -07001686 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001687 expandBufAdd4BE(pReply, thread->GetDebugSuspendCount());
Elliott Hughes2435a572012-02-17 16:07:41 -08001688 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001689}
1690
Elliott Hughesf9501702013-01-11 11:22:27 -08001691JDWP::JdwpError Dbg::Interrupt(JDWP::ObjectId thread_id) {
1692 ScopedObjectAccess soa(Thread::Current());
1693 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
1694 Thread* thread;
1695 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1696 if (error != JDWP::ERR_NONE) {
1697 return error;
1698 }
1699 thread->Interrupt();
1700 return JDWP::ERR_NONE;
1701}
1702
Elliott Hughescaf76542012-06-28 16:08:22 -07001703void Dbg::GetThreads(JDWP::ObjectId thread_group_id, std::vector<JDWP::ObjectId>& thread_ids) {
Ian Rogers365c1022012-06-22 15:05:28 -07001704 class ThreadListVisitor {
1705 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001706 ThreadListVisitor(const ScopedObjectAccessUnchecked& soa, mirror::Object* desired_thread_group,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001707 std::vector<JDWP::ObjectId>& thread_ids)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001708 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
jeffhao0dfbb7e2012-11-28 15:26:03 -08001709 : soa_(soa), desired_thread_group_(desired_thread_group), thread_ids_(thread_ids) {}
Ian Rogers365c1022012-06-22 15:05:28 -07001710
Elliott Hughesa2155262011-11-16 16:26:58 -08001711 static void Visit(Thread* t, void* arg) {
1712 reinterpret_cast<ThreadListVisitor*>(arg)->Visit(t);
1713 }
1714
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001715 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1716 // annotalysis.
1717 void Visit(Thread* t) NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughesa2155262011-11-16 16:26:58 -08001718 if (t == Dbg::GetDebugThread()) {
1719 // Skip the JDWP thread. Some debuggers get bent out of shape when they can't suspend and
1720 // query all threads, so it's easier if we just don't tell them about this thread.
1721 return;
1722 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001723 mirror::Object* peer = t->GetPeer();
jeffhao0dfbb7e2012-11-28 15:26:03 -08001724 if (IsInDesiredThreadGroup(peer)) {
Ian Rogers120f1c72012-09-28 17:17:10 -07001725 thread_ids_.push_back(gRegistry->Add(peer));
Elliott Hughesa2155262011-11-16 16:26:58 -08001726 }
1727 }
1728
Ian Rogers365c1022012-06-22 15:05:28 -07001729 private:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001730 bool IsInDesiredThreadGroup(mirror::Object* peer)
jeffhao0dfbb7e2012-11-28 15:26:03 -08001731 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
jeffhao0dfbb7e2012-11-28 15:26:03 -08001732 // peer might be NULL if the thread is still starting up.
1733 if (peer == NULL) {
1734 // We can't tell the debugger about this thread yet.
1735 // TODO: if we identified threads to the debugger by their Thread*
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001736 // rather than their peer's mirror::Object*, we could fix this.
jeffhao0dfbb7e2012-11-28 15:26:03 -08001737 // Doing so might help us report ZOMBIE threads too.
1738 return false;
1739 }
jeffhaoc1e04902012-12-13 12:41:10 -08001740 // Do we want threads from all thread groups?
1741 if (desired_thread_group_ == NULL) {
1742 return true;
1743 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001744 mirror::Object* group = soa_.DecodeField(WellKnownClasses::java_lang_Thread_group)->GetObject(peer);
jeffhao0dfbb7e2012-11-28 15:26:03 -08001745 return (group == desired_thread_group_);
1746 }
1747
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07001748 const ScopedObjectAccessUnchecked& soa_;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001749 mirror::Object* const desired_thread_group_;
Elliott Hughescaf76542012-06-28 16:08:22 -07001750 std::vector<JDWP::ObjectId>& thread_ids_;
Elliott Hughesa2155262011-11-16 16:26:58 -08001751 };
1752
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001753 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001754 mirror::Object* thread_group = gRegistry->Get<mirror::Object*>(thread_group_id);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001755 ThreadListVisitor tlv(soa, thread_group, thread_ids);
Ian Rogers50b35e22012-10-04 10:09:15 -07001756 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughesf8349362012-06-18 15:00:06 -07001757 Runtime::Current()->GetThreadList()->ForEach(ThreadListVisitor::Visit, &tlv);
Elliott Hughescaf76542012-06-28 16:08:22 -07001758}
Elliott Hughesa2155262011-11-16 16:26:58 -08001759
Elliott Hughescaf76542012-06-28 16:08:22 -07001760void Dbg::GetChildThreadGroups(JDWP::ObjectId thread_group_id, std::vector<JDWP::ObjectId>& child_thread_group_ids) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001761 ScopedObjectAccess soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001762 mirror::Object* thread_group = gRegistry->Get<mirror::Object*>(thread_group_id);
Elliott Hughescaf76542012-06-28 16:08:22 -07001763
1764 // Get the ArrayList<ThreadGroup> "groups" out of this thread group...
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001765 mirror::Field* groups_field = thread_group->GetClass()->FindInstanceField("groups", "Ljava/util/List;");
1766 mirror::Object* groups_array_list = groups_field->GetObject(thread_group);
Elliott Hughescaf76542012-06-28 16:08:22 -07001767
1768 // Get the array and size out of the ArrayList<ThreadGroup>...
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001769 mirror::Field* array_field = groups_array_list->GetClass()->FindInstanceField("array", "[Ljava/lang/Object;");
1770 mirror::Field* size_field = groups_array_list->GetClass()->FindInstanceField("size", "I");
1771 mirror::ObjectArray<mirror::Object>* groups_array =
1772 array_field->GetObject(groups_array_list)->AsObjectArray<mirror::Object>();
Elliott Hughescaf76542012-06-28 16:08:22 -07001773 const int32_t size = size_field->GetInt(groups_array_list);
1774
1775 // Copy the first 'size' elements out of the array into the result.
1776 for (int32_t i = 0; i < size; ++i) {
1777 child_thread_group_ids.push_back(gRegistry->Add(groups_array->Get(i)));
Elliott Hughesa2155262011-11-16 16:26:58 -08001778 }
1779}
1780
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001781static int GetStackDepth(Thread* thread)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001782 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers0399dde2012-06-06 17:09:28 -07001783 struct CountStackDepthVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -08001784 CountStackDepthVisitor(Thread* thread)
1785 : StackVisitor(thread, NULL), depth(0) {}
Ian Rogers0399dde2012-06-06 17:09:28 -07001786
1787 bool VisitFrame() {
1788 if (!GetMethod()->IsRuntimeMethod()) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -08001789 ++depth;
1790 }
Elliott Hughes530fa002012-03-12 11:44:49 -07001791 return true;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001792 }
1793 size_t depth;
1794 };
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001795
Ian Rogers7a22fa62013-01-23 12:16:16 -08001796 CountStackDepthVisitor visitor(thread);
Ian Rogers0399dde2012-06-06 17:09:28 -07001797 visitor.WalkStack();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001798 return visitor.depth;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001799}
1800
Elliott Hughes221229c2013-01-08 18:17:50 -08001801JDWP::JdwpError Dbg::GetThreadFrameCount(JDWP::ObjectId thread_id, size_t& result) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001802 ScopedObjectAccess soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08001803 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001804 Thread* thread;
1805 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1806 if (error != JDWP::ERR_NONE) {
1807 return error;
1808 }
Elliott Hughesf15f4a02013-01-09 10:09:38 -08001809 if (!IsSuspendedForDebugger(soa, thread)) {
1810 return JDWP::ERR_THREAD_NOT_SUSPENDED;
1811 }
Elliott Hughes221229c2013-01-08 18:17:50 -08001812 result = GetStackDepth(thread);
1813 return JDWP::ERR_NONE;
Elliott Hughes86964332012-02-15 19:37:42 -08001814}
1815
Ian Rogers306057f2012-11-26 12:45:53 -08001816JDWP::JdwpError Dbg::GetThreadFrames(JDWP::ObjectId thread_id, size_t start_frame,
1817 size_t frame_count, JDWP::ExpandBuf* buf) {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001818 class GetFrameVisitor : public StackVisitor {
1819 public:
Ian Rogers7a22fa62013-01-23 12:16:16 -08001820 GetFrameVisitor(Thread* thread, size_t start_frame, size_t frame_count, JDWP::ExpandBuf* buf)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001821 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08001822 : StackVisitor(thread, NULL), depth_(0),
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001823 start_frame_(start_frame), frame_count_(frame_count), buf_(buf) {
1824 expandBufAdd4BE(buf_, frame_count_);
Elliott Hughes03181a82011-11-17 17:22:21 -08001825 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001826
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001827 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1828 // annotalysis.
1829 virtual bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07001830 if (GetMethod()->IsRuntimeMethod()) {
Elliott Hughes530fa002012-03-12 11:44:49 -07001831 return true; // The debugger can't do anything useful with a frame that has no Method*.
Elliott Hughes03181a82011-11-17 17:22:21 -08001832 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001833 if (depth_ >= start_frame_ + frame_count_) {
Elliott Hughes530fa002012-03-12 11:44:49 -07001834 return false;
Elliott Hughes03181a82011-11-17 17:22:21 -08001835 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001836 if (depth_ >= start_frame_) {
1837 JDWP::FrameId frame_id(GetFrameId());
1838 JDWP::JdwpLocation location;
1839 SetLocation(location, GetMethod(), GetDexPc());
Elliott Hughes7baf96f2012-06-22 16:33:50 -07001840 VLOG(jdwp) << StringPrintf(" Frame %3zd: id=%3lld ", depth_, frame_id) << location;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001841 expandBufAdd8BE(buf_, frame_id);
1842 expandBufAddLocation(buf_, location);
1843 }
1844 ++depth_;
Elliott Hughes530fa002012-03-12 11:44:49 -07001845 return true;
Elliott Hughes03181a82011-11-17 17:22:21 -08001846 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001847
1848 private:
1849 size_t depth_;
1850 const size_t start_frame_;
1851 const size_t frame_count_;
1852 JDWP::ExpandBuf* buf_;
Elliott Hughes03181a82011-11-17 17:22:21 -08001853 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001854
1855 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08001856 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001857 Thread* thread;
1858 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1859 if (error != JDWP::ERR_NONE) {
1860 return error;
1861 }
Elliott Hughesf15f4a02013-01-09 10:09:38 -08001862 if (!IsSuspendedForDebugger(soa, thread)) {
1863 return JDWP::ERR_THREAD_NOT_SUSPENDED;
1864 }
Ian Rogers7a22fa62013-01-23 12:16:16 -08001865 GetFrameVisitor visitor(thread, start_frame, frame_count, buf);
Ian Rogers0399dde2012-06-06 17:09:28 -07001866 visitor.WalkStack();
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001867 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001868}
1869
1870JDWP::ObjectId Dbg::GetThreadSelfId() {
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07001871 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogerscfaa4552012-11-26 21:00:08 -08001872 return gRegistry->Add(soa.Self()->GetPeer());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001873}
1874
Elliott Hughes475fc232011-10-25 15:00:35 -07001875void Dbg::SuspendVM() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001876 Runtime::Current()->GetThreadList()->SuspendAllForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001877}
1878
1879void Dbg::ResumeVM() {
Elliott Hughesc61a2672012-06-21 14:52:29 -07001880 Runtime::Current()->GetThreadList()->UndoDebuggerSuspensions();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001881}
1882
Elliott Hughes221229c2013-01-08 18:17:50 -08001883JDWP::JdwpError Dbg::SuspendThread(JDWP::ObjectId thread_id, bool request_suspension) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001884 ScopedLocalRef<jobject> peer(Thread::Current()->GetJniEnv(), NULL);
1885 {
1886 ScopedObjectAccess soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001887 peer.reset(soa.AddLocalReference<jobject>(gRegistry->Get<mirror::Object*>(thread_id)));
Elliott Hughes4e235312011-12-02 11:34:15 -08001888 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001889 if (peer.get() == NULL) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001890 return JDWP::ERR_THREAD_NOT_ALIVE;
1891 }
1892 // Suspend thread to build stack trace.
Elliott Hughesf327e072013-01-09 16:01:26 -08001893 bool timed_out;
1894 Thread* thread = Thread::SuspendForDebugger(peer.get(), request_suspension, &timed_out);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001895 if (thread != NULL) {
1896 return JDWP::ERR_NONE;
Elliott Hughesf327e072013-01-09 16:01:26 -08001897 } else if (timed_out) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001898 return JDWP::ERR_INTERNAL;
1899 } else {
1900 return JDWP::ERR_THREAD_NOT_ALIVE;
1901 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001902}
1903
Elliott Hughes221229c2013-01-08 18:17:50 -08001904void Dbg::ResumeThread(JDWP::ObjectId thread_id) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001905 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001906 mirror::Object* peer = gRegistry->Get<mirror::Object*>(thread_id);
jeffhaoa77f0f62012-12-05 17:19:31 -08001907 Thread* thread;
1908 {
1909 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
1910 thread = Thread::FromManagedThread(soa, peer);
1911 }
Elliott Hughes4e235312011-12-02 11:34:15 -08001912 if (thread == NULL) {
1913 LOG(WARNING) << "No such thread for resume: " << peer;
1914 return;
1915 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001916 bool needs_resume;
1917 {
Ian Rogers50b35e22012-10-04 10:09:15 -07001918 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001919 needs_resume = thread->GetSuspendCount() > 0;
1920 }
1921 if (needs_resume) {
Elliott Hughes546b9862012-06-20 16:06:13 -07001922 Runtime::Current()->GetThreadList()->Resume(thread, true);
1923 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001924}
1925
1926void Dbg::SuspendSelf() {
Elliott Hughes475fc232011-10-25 15:00:35 -07001927 Runtime::Current()->GetThreadList()->SuspendSelfForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001928}
1929
Ian Rogers0399dde2012-06-06 17:09:28 -07001930struct GetThisVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -08001931 GetThisVisitor(Thread* thread, Context* context, JDWP::FrameId frame_id)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001932 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08001933 : StackVisitor(thread, context), this_object(NULL), frame_id(frame_id) {}
Ian Rogers0399dde2012-06-06 17:09:28 -07001934
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001935 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1936 // annotalysis.
1937 virtual bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001938 if (frame_id != GetFrameId()) {
Ian Rogers0399dde2012-06-06 17:09:28 -07001939 return true; // continue
1940 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001941 mirror::AbstractMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07001942 if (m->IsNative() || m->IsStatic()) {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001943 this_object = NULL;
Ian Rogers0399dde2012-06-06 17:09:28 -07001944 } else {
1945 uint16_t reg = DemangleSlot(0, m);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001946 this_object = reinterpret_cast<mirror::Object*>(GetVReg(m, reg, kReferenceVReg));
Ian Rogers0399dde2012-06-06 17:09:28 -07001947 }
1948 return false;
Elliott Hughes86b00102011-12-05 17:54:26 -08001949 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001950
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001951 mirror::Object* this_object;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001952 JDWP::FrameId frame_id;
Ian Rogers0399dde2012-06-06 17:09:28 -07001953};
1954
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001955static mirror::Object* GetThis(Thread* self, mirror::AbstractMethod* m, size_t frame_id)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001956 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughescaf76542012-06-28 16:08:22 -07001957 // TODO: should we return the 'this' we passed through to non-static native methods?
Ian Rogers0399dde2012-06-06 17:09:28 -07001958 if (m->IsNative() || m->IsStatic()) {
1959 return NULL;
1960 }
Elliott Hughescaf76542012-06-28 16:08:22 -07001961
Ian Rogers0399dde2012-06-06 17:09:28 -07001962 UniquePtr<Context> context(Context::Create());
Ian Rogers7a22fa62013-01-23 12:16:16 -08001963 GetThisVisitor visitor(self, context.get(), frame_id);
Elliott Hughescaf76542012-06-28 16:08:22 -07001964 visitor.WalkStack();
1965 return visitor.this_object;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001966}
1967
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001968JDWP::JdwpError Dbg::GetThisObject(JDWP::ObjectId thread_id, JDWP::FrameId frame_id,
1969 JDWP::ObjectId* result) {
1970 ScopedObjectAccessUnchecked soa(Thread::Current());
1971 Thread* thread;
1972 {
Ian Rogers50b35e22012-10-04 10:09:15 -07001973 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001974 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1975 if (error != JDWP::ERR_NONE) {
1976 return error;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001977 }
Elliott Hughes9e0c1752013-01-09 14:02:58 -08001978 if (!IsSuspendedForDebugger(soa, thread)) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001979 return JDWP::ERR_THREAD_NOT_SUSPENDED;
1980 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001981 }
Elliott Hughescaf76542012-06-28 16:08:22 -07001982 UniquePtr<Context> context(Context::Create());
Ian Rogers7a22fa62013-01-23 12:16:16 -08001983 GetThisVisitor visitor(thread, context.get(), frame_id);
Ian Rogers0399dde2012-06-06 17:09:28 -07001984 visitor.WalkStack();
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001985 *result = gRegistry->Add(visitor.this_object);
1986 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001987}
1988
Elliott Hughes88d63092013-01-09 09:55:54 -08001989void Dbg::GetLocalValue(JDWP::ObjectId thread_id, JDWP::FrameId frame_id, int slot, JDWP::JdwpTag tag,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001990 uint8_t* buf, size_t width) {
Ian Rogers0399dde2012-06-06 17:09:28 -07001991 struct GetLocalVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -08001992 GetLocalVisitor(Thread* thread, Context* context, JDWP::FrameId frame_id, int slot,
1993 JDWP::JdwpTag tag, uint8_t* buf, size_t width)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001994 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08001995 : StackVisitor(thread, context), frame_id_(frame_id), slot_(slot), tag_(tag),
Ian Rogersca190662012-06-26 15:45:57 -07001996 buf_(buf), width_(width) {}
1997
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001998 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1999 // annotalysis.
2000 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07002001 if (GetFrameId() != frame_id_) {
2002 return true; // Not our frame, carry on.
Elliott Hughesdbb40792011-11-18 17:05:22 -08002003 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002004 // TODO: check that the tag is compatible with the actual type of the slot!
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002005 mirror::AbstractMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07002006 uint16_t reg = DemangleSlot(slot_, m);
Elliott Hughesdbb40792011-11-18 17:05:22 -08002007
Ian Rogers0399dde2012-06-06 17:09:28 -07002008 switch (tag_) {
2009 case JDWP::JT_BOOLEAN:
2010 {
2011 CHECK_EQ(width_, 1U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002012 uint32_t intVal = GetVReg(m, reg, kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002013 VLOG(jdwp) << "get boolean local " << reg << " = " << intVal;
2014 JDWP::Set1(buf_+1, intVal != 0);
2015 }
2016 break;
2017 case JDWP::JT_BYTE:
2018 {
2019 CHECK_EQ(width_, 1U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002020 uint32_t intVal = GetVReg(m, reg, kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002021 VLOG(jdwp) << "get byte local " << reg << " = " << intVal;
2022 JDWP::Set1(buf_+1, intVal);
2023 }
2024 break;
2025 case JDWP::JT_SHORT:
2026 case JDWP::JT_CHAR:
2027 {
2028 CHECK_EQ(width_, 2U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002029 uint32_t intVal = GetVReg(m, reg, kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002030 VLOG(jdwp) << "get short/char local " << reg << " = " << intVal;
2031 JDWP::Set2BE(buf_+1, intVal);
2032 }
2033 break;
2034 case JDWP::JT_INT:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002035 {
2036 CHECK_EQ(width_, 4U);
2037 uint32_t intVal = GetVReg(m, reg, kIntVReg);
2038 VLOG(jdwp) << "get int local " << reg << " = " << intVal;
2039 JDWP::Set4BE(buf_+1, intVal);
2040 }
2041 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002042 case JDWP::JT_FLOAT:
2043 {
2044 CHECK_EQ(width_, 4U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002045 uint32_t intVal = GetVReg(m, reg, kFloatVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002046 VLOG(jdwp) << "get int/float local " << reg << " = " << intVal;
2047 JDWP::Set4BE(buf_+1, intVal);
2048 }
2049 break;
2050 case JDWP::JT_ARRAY:
2051 {
2052 CHECK_EQ(width_, sizeof(JDWP::ObjectId));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002053 mirror::Object* o = reinterpret_cast<mirror::Object*>(GetVReg(m, reg, kReferenceVReg));
Ian Rogers0399dde2012-06-06 17:09:28 -07002054 VLOG(jdwp) << "get array local " << reg << " = " << o;
2055 if (!Runtime::Current()->GetHeap()->IsHeapAddress(o)) {
2056 LOG(FATAL) << "Register " << reg << " expected to hold array: " << o;
2057 }
2058 JDWP::SetObjectId(buf_+1, gRegistry->Add(o));
2059 }
2060 break;
2061 case JDWP::JT_CLASS_LOADER:
2062 case JDWP::JT_CLASS_OBJECT:
2063 case JDWP::JT_OBJECT:
2064 case JDWP::JT_STRING:
2065 case JDWP::JT_THREAD:
2066 case JDWP::JT_THREAD_GROUP:
2067 {
2068 CHECK_EQ(width_, sizeof(JDWP::ObjectId));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002069 mirror::Object* o = reinterpret_cast<mirror::Object*>(GetVReg(m, reg, kReferenceVReg));
Ian Rogers0399dde2012-06-06 17:09:28 -07002070 VLOG(jdwp) << "get object local " << reg << " = " << o;
2071 if (!Runtime::Current()->GetHeap()->IsHeapAddress(o)) {
2072 LOG(FATAL) << "Register " << reg << " expected to hold object: " << o;
2073 }
2074 tag_ = TagFromObject(o);
2075 JDWP::SetObjectId(buf_+1, gRegistry->Add(o));
2076 }
2077 break;
2078 case JDWP::JT_DOUBLE:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002079 {
2080 CHECK_EQ(width_, 8U);
2081 uint32_t lo = GetVReg(m, reg, kDoubleLoVReg);
2082 uint64_t hi = GetVReg(m, reg + 1, kDoubleHiVReg);
2083 uint64_t longVal = (hi << 32) | lo;
2084 VLOG(jdwp) << "get double/long local " << hi << ":" << lo << " = " << longVal;
2085 JDWP::Set8BE(buf_+1, longVal);
2086 }
2087 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002088 case JDWP::JT_LONG:
2089 {
2090 CHECK_EQ(width_, 8U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002091 uint32_t lo = GetVReg(m, reg, kLongLoVReg);
2092 uint64_t hi = GetVReg(m, reg + 1, kLongHiVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002093 uint64_t longVal = (hi << 32) | lo;
2094 VLOG(jdwp) << "get double/long local " << hi << ":" << lo << " = " << longVal;
2095 JDWP::Set8BE(buf_+1, longVal);
2096 }
2097 break;
2098 default:
2099 LOG(FATAL) << "Unknown tag " << tag_;
2100 break;
2101 }
2102
2103 // Prepend tag, which may have been updated.
2104 JDWP::Set1(buf_, tag_);
2105 return false;
2106 }
2107
2108 const JDWP::FrameId frame_id_;
2109 const int slot_;
2110 JDWP::JdwpTag tag_;
2111 uint8_t* const buf_;
2112 const size_t width_;
2113 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002114
2115 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08002116 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002117 Thread* thread;
2118 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
2119 if (error != JDWP::ERR_NONE) {
2120 return;
2121 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002122 UniquePtr<Context> context(Context::Create());
Ian Rogers7a22fa62013-01-23 12:16:16 -08002123 GetLocalVisitor visitor(thread, context.get(), frame_id, slot, tag, buf, width);
Ian Rogers0399dde2012-06-06 17:09:28 -07002124 visitor.WalkStack();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002125}
2126
Elliott Hughes88d63092013-01-09 09:55:54 -08002127void Dbg::SetLocalValue(JDWP::ObjectId thread_id, JDWP::FrameId frame_id, int slot, JDWP::JdwpTag tag,
Ian Rogers0399dde2012-06-06 17:09:28 -07002128 uint64_t value, size_t width) {
2129 struct SetLocalVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -08002130 SetLocalVisitor(Thread* thread, Context* context,
Ian Rogers0399dde2012-06-06 17:09:28 -07002131 JDWP::FrameId frame_id, int slot, JDWP::JdwpTag tag, uint64_t value,
Ian Rogersca190662012-06-26 15:45:57 -07002132 size_t width)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002133 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08002134 : StackVisitor(thread, context),
Elliott Hughes08fc03a2012-06-26 17:34:00 -07002135 frame_id_(frame_id), slot_(slot), tag_(tag), value_(value), width_(width) {}
Ian Rogersca190662012-06-26 15:45:57 -07002136
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002137 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2138 // annotalysis.
2139 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07002140 if (GetFrameId() != frame_id_) {
2141 return true; // Not our frame, carry on.
2142 }
2143 // TODO: check that the tag is compatible with the actual type of the slot!
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002144 mirror::AbstractMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07002145 uint16_t reg = DemangleSlot(slot_, m);
2146
2147 switch (tag_) {
2148 case JDWP::JT_BOOLEAN:
2149 case JDWP::JT_BYTE:
2150 CHECK_EQ(width_, 1U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002151 SetVReg(m, reg, static_cast<uint32_t>(value_), kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002152 break;
2153 case JDWP::JT_SHORT:
2154 case JDWP::JT_CHAR:
2155 CHECK_EQ(width_, 2U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002156 SetVReg(m, reg, static_cast<uint32_t>(value_), kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002157 break;
2158 case JDWP::JT_INT:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002159 CHECK_EQ(width_, 4U);
2160 SetVReg(m, reg, static_cast<uint32_t>(value_), kIntVReg);
2161 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002162 case JDWP::JT_FLOAT:
2163 CHECK_EQ(width_, 4U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002164 SetVReg(m, reg, static_cast<uint32_t>(value_), kFloatVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002165 break;
2166 case JDWP::JT_ARRAY:
2167 case JDWP::JT_OBJECT:
2168 case JDWP::JT_STRING:
2169 {
2170 CHECK_EQ(width_, sizeof(JDWP::ObjectId));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002171 mirror::Object* o = gRegistry->Get<mirror::Object*>(static_cast<JDWP::ObjectId>(value_));
Ian Rogers0399dde2012-06-06 17:09:28 -07002172 if (o == kInvalidObject) {
2173 UNIMPLEMENTED(FATAL) << "return an error code when given an invalid object to store";
2174 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002175 SetVReg(m, reg, static_cast<uint32_t>(reinterpret_cast<uintptr_t>(o)), kReferenceVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002176 }
2177 break;
2178 case JDWP::JT_DOUBLE:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002179 CHECK_EQ(width_, 8U);
2180 SetVReg(m, reg, static_cast<uint32_t>(value_), kDoubleLoVReg);
2181 SetVReg(m, reg + 1, static_cast<uint32_t>(value_ >> 32), kDoubleHiVReg);
2182 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002183 case JDWP::JT_LONG:
2184 CHECK_EQ(width_, 8U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002185 SetVReg(m, reg, static_cast<uint32_t>(value_), kLongLoVReg);
2186 SetVReg(m, reg + 1, static_cast<uint32_t>(value_ >> 32), kLongHiVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002187 break;
2188 default:
2189 LOG(FATAL) << "Unknown tag " << tag_;
2190 break;
2191 }
2192 return false;
2193 }
2194
2195 const JDWP::FrameId frame_id_;
2196 const int slot_;
2197 const JDWP::JdwpTag tag_;
2198 const uint64_t value_;
2199 const size_t width_;
2200 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002201
2202 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08002203 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002204 Thread* thread;
2205 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
2206 if (error != JDWP::ERR_NONE) {
2207 return;
2208 }
Elliott Hughes08fc03a2012-06-26 17:34:00 -07002209 UniquePtr<Context> context(Context::Create());
Ian Rogers7a22fa62013-01-23 12:16:16 -08002210 SetLocalVisitor visitor(thread, context.get(), frame_id, slot, tag, value, width);
Ian Rogers0399dde2012-06-06 17:09:28 -07002211 visitor.WalkStack();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002212}
2213
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002214void Dbg::PostLocationEvent(const mirror::AbstractMethod* m, int dex_pc, mirror::Object* this_object, int event_flags) {
2215 mirror::Class* c = m->GetDeclaringClass();
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002216
2217 JDWP::JdwpLocation location;
Elliott Hughes74847412012-06-20 18:10:21 -07002218 location.type_tag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
2219 location.class_id = gRegistry->Add(c);
2220 location.method_id = ToMethodId(m);
Elliott Hughes972a47b2012-02-21 18:16:06 -08002221 location.dex_pc = m->IsNative() ? -1 : dex_pc;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002222
2223 // Note we use "NoReg" so we don't keep track of references that are
2224 // never actually sent to the debugger. 'this_id' is only used to
2225 // compare against registered events...
2226 JDWP::ObjectId this_id = static_cast<JDWP::ObjectId>(reinterpret_cast<uintptr_t>(this_object));
2227 if (gJdwpState->PostLocationEvent(&location, this_id, event_flags)) {
2228 // ...unless there's a registered event, in which case we
2229 // need to really track the class and 'this'.
2230 gRegistry->Add(c);
2231 gRegistry->Add(this_object);
2232 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002233}
2234
Elliott Hughescaf76542012-06-28 16:08:22 -07002235void Dbg::PostException(Thread* thread,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002236 JDWP::FrameId throw_frame_id, mirror::AbstractMethod* throw_method,
2237 uint32_t throw_dex_pc, mirror::AbstractMethod* catch_method,
2238 uint32_t catch_dex_pc, mirror::Throwable* exception) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002239 if (!IsDebuggerActive()) {
Ian Rogers0ad5bb82011-12-07 10:16:32 -08002240 return;
2241 }
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002242
Elliott Hughesd07986f2011-12-06 18:27:45 -08002243 JDWP::JdwpLocation throw_location;
Elliott Hughescaf76542012-06-28 16:08:22 -07002244 SetLocation(throw_location, throw_method, throw_dex_pc);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002245 JDWP::JdwpLocation catch_location;
Elliott Hughescaf76542012-06-28 16:08:22 -07002246 SetLocation(catch_location, catch_method, catch_dex_pc);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002247
2248 // We need 'this' for InstanceOnly filters.
Elliott Hughescaf76542012-06-28 16:08:22 -07002249 UniquePtr<Context> context(Context::Create());
Ian Rogers7a22fa62013-01-23 12:16:16 -08002250 GetThisVisitor visitor(thread, context.get(), throw_frame_id);
Elliott Hughescaf76542012-06-28 16:08:22 -07002251 visitor.WalkStack();
2252 JDWP::ObjectId this_id = gRegistry->Add(visitor.this_object);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002253
2254 /*
2255 * Hand the event to the JDWP exception handler. Note we're using the
2256 * "NoReg" objectID on the exception, which is not strictly correct --
2257 * the exception object WILL be passed up to the debugger if the
2258 * debugger is interested in the event. We do this because the current
2259 * implementation of the debugger object registry never throws anything
2260 * away, and some people were experiencing a fatal build up of exception
2261 * objects when dealing with certain libraries.
2262 */
2263 JDWP::ObjectId exception_id = static_cast<JDWP::ObjectId>(reinterpret_cast<uintptr_t>(exception));
2264 JDWP::RefTypeId exception_class_id = gRegistry->Add(exception->GetClass());
2265
2266 gJdwpState->PostException(&throw_location, exception_id, exception_class_id, &catch_location, this_id);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002267}
2268
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002269void Dbg::PostClassPrepare(mirror::Class* c) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002270 if (!IsDebuggerActive()) {
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002271 return;
2272 }
2273
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08002274 // OLD-TODO - we currently always send both "verified" and "prepared" since
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002275 // debuggers seem to like that. There might be some advantage to honesty,
2276 // since the class may not yet be verified.
2277 int state = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
2278 JDWP::JdwpTypeTag tag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
2279 gJdwpState->PostClassPrepare(tag, gRegistry->Add(c), ClassHelper(c).GetDescriptor(), state);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002280}
2281
Elliott Hughescaf76542012-06-28 16:08:22 -07002282void Dbg::UpdateDebugger(int32_t dex_pc, Thread* self) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002283 if (!IsDebuggerActive() || dex_pc == -2 /* fake method exit */) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002284 return;
2285 }
2286
Elliott Hughescaf76542012-06-28 16:08:22 -07002287 size_t frame_id;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002288 mirror::AbstractMethod* m = self->GetCurrentMethod(NULL, &frame_id);
Elliott Hughescaf76542012-06-28 16:08:22 -07002289 //LOG(INFO) << "UpdateDebugger " << PrettyMethod(m) << "@" << dex_pc << " frame " << frame_id;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002290
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002291 if (dex_pc == -1) {
Elliott Hughes2aa2e392012-02-17 17:15:43 -08002292 // We use a pc of -1 to represent method entry, since we might branch back to pc 0 later.
2293 // This means that for this special notification, there can't be anything else interesting
2294 // going on, so we're done already.
Elliott Hughescaf76542012-06-28 16:08:22 -07002295 Dbg::PostLocationEvent(m, 0, GetThis(self, m, frame_id), kMethodEntry);
Elliott Hughes2aa2e392012-02-17 17:15:43 -08002296 return;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002297 }
2298
Elliott Hughes2aa2e392012-02-17 17:15:43 -08002299 int event_flags = 0;
2300
Elliott Hughes86964332012-02-15 19:37:42 -08002301 if (IsBreakpoint(m, dex_pc)) {
2302 event_flags |= kBreakpoint;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002303 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002304
jeffhao09bfc6a2012-12-11 18:11:43 -08002305 {
2306 // If the debugger is single-stepping one of our threads, check to
2307 // see if we're that thread and we've reached a step point.
2308 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
2309 if (gSingleStepControl.is_active && gSingleStepControl.thread == self) {
2310 CHECK(!m->IsNative());
2311 if (gSingleStepControl.step_depth == JDWP::SD_INTO) {
2312 // Step into method calls. We break when the line number
2313 // or method pointer changes. If we're in SS_MIN mode, we
2314 // always stop.
2315 if (gSingleStepControl.method != m) {
2316 event_flags |= kSingleStep;
2317 VLOG(jdwp) << "SS new method";
2318 } else if (gSingleStepControl.step_size == JDWP::SS_MIN) {
Elliott Hughes86964332012-02-15 19:37:42 -08002319 event_flags |= kSingleStep;
2320 VLOG(jdwp) << "SS new instruction";
Elliott Hughes2435a572012-02-17 16:07:41 -08002321 } else if (gSingleStepControl.dex_pcs.find(dex_pc) == gSingleStepControl.dex_pcs.end()) {
2322 event_flags |= kSingleStep;
2323 VLOG(jdwp) << "SS new line";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002324 }
jeffhao09bfc6a2012-12-11 18:11:43 -08002325 } else if (gSingleStepControl.step_depth == JDWP::SD_OVER) {
2326 // Step over method calls. We break when the line number is
2327 // different and the frame depth is <= the original frame
2328 // depth. (We can't just compare on the method, because we
2329 // might get unrolled past it by an exception, and it's tricky
2330 // to identify recursion.)
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002331
jeffhao09bfc6a2012-12-11 18:11:43 -08002332 int stack_depth = GetStackDepth(self);
Elliott Hughes86964332012-02-15 19:37:42 -08002333
jeffhao09bfc6a2012-12-11 18:11:43 -08002334 if (stack_depth < gSingleStepControl.stack_depth) {
2335 // popped up one or more frames, always trigger
2336 event_flags |= kSingleStep;
2337 VLOG(jdwp) << "SS method pop";
2338 } else if (stack_depth == gSingleStepControl.stack_depth) {
2339 // same depth, see if we moved
2340 if (gSingleStepControl.step_size == JDWP::SS_MIN) {
2341 event_flags |= kSingleStep;
2342 VLOG(jdwp) << "SS new instruction";
2343 } else if (gSingleStepControl.dex_pcs.find(dex_pc) == gSingleStepControl.dex_pcs.end()) {
2344 event_flags |= kSingleStep;
2345 VLOG(jdwp) << "SS new line";
2346 }
2347 }
2348 } else {
2349 CHECK_EQ(gSingleStepControl.step_depth, JDWP::SD_OUT);
2350 // Return from the current method. We break when the frame
2351 // depth pops up.
2352
2353 // This differs from the "method exit" break in that it stops
2354 // with the PC at the next instruction in the returned-to
2355 // function, rather than the end of the returning function.
2356
2357 int stack_depth = GetStackDepth(self);
2358 if (stack_depth < gSingleStepControl.stack_depth) {
2359 event_flags |= kSingleStep;
2360 VLOG(jdwp) << "SS method pop";
2361 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002362 }
2363 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002364 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002365
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002366 // Check to see if this is a "return" instruction. JDWP says we should
2367 // send the event *after* the code has been executed, but it also says
2368 // the location we provide is the last instruction. Since the "return"
2369 // instruction has no interesting side effects, we should be safe.
2370 // (We can't just move this down to the returnFromMethod label because
2371 // we potentially need to combine it with other events.)
2372 // We're also not supposed to generate a method exit event if the method
2373 // terminates "with a thrown exception".
Elliott Hughes86964332012-02-15 19:37:42 -08002374 if (dex_pc >= 0) {
2375 const DexFile::CodeItem* code_item = MethodHelper(m).GetCodeItem();
Elliott Hughescaf76542012-06-28 16:08:22 -07002376 CHECK(code_item != NULL) << PrettyMethod(m) << " @" << dex_pc;
Elliott Hughes86964332012-02-15 19:37:42 -08002377 CHECK_LT(dex_pc, static_cast<int32_t>(code_item->insns_size_in_code_units_));
2378 if (Instruction::At(&code_item->insns_[dex_pc])->IsReturn()) {
2379 event_flags |= kMethodExit;
2380 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002381 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002382
2383 // If there's something interesting going on, see if it matches one
2384 // of the debugger filters.
2385 if (event_flags != 0) {
Elliott Hughescaf76542012-06-28 16:08:22 -07002386 Dbg::PostLocationEvent(m, dex_pc, GetThis(self, m, frame_id), event_flags);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002387 }
2388}
2389
Elliott Hughes86964332012-02-15 19:37:42 -08002390void Dbg::WatchLocation(const JDWP::JdwpLocation* location) {
jeffhao09bfc6a2012-12-11 18:11:43 -08002391 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002392 mirror::AbstractMethod* m = FromMethodId(location->method_id);
Elliott Hughes972a47b2012-02-21 18:16:06 -08002393 gBreakpoints.push_back(Breakpoint(m, location->dex_pc));
Elliott Hughes86964332012-02-15 19:37:42 -08002394 VLOG(jdwp) << "Set breakpoint #" << (gBreakpoints.size() - 1) << ": " << gBreakpoints[gBreakpoints.size() - 1];
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002395}
2396
Elliott Hughes86964332012-02-15 19:37:42 -08002397void Dbg::UnwatchLocation(const JDWP::JdwpLocation* location) {
jeffhao09bfc6a2012-12-11 18:11:43 -08002398 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002399 mirror::AbstractMethod* m = FromMethodId(location->method_id);
Elliott Hughes86964332012-02-15 19:37:42 -08002400 for (size_t i = 0; i < gBreakpoints.size(); ++i) {
Elliott Hughes972a47b2012-02-21 18:16:06 -08002401 if (gBreakpoints[i].method == m && gBreakpoints[i].dex_pc == location->dex_pc) {
Elliott Hughes86964332012-02-15 19:37:42 -08002402 VLOG(jdwp) << "Removed breakpoint #" << i << ": " << gBreakpoints[i];
2403 gBreakpoints.erase(gBreakpoints.begin() + i);
2404 return;
2405 }
2406 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002407}
2408
Elliott Hughes221229c2013-01-08 18:17:50 -08002409JDWP::JdwpError Dbg::ConfigureStep(JDWP::ObjectId thread_id, JDWP::JdwpStepSize step_size,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002410 JDWP::JdwpStepDepth step_depth) {
2411 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08002412 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002413 Thread* thread;
2414 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
2415 if (error != JDWP::ERR_NONE) {
2416 return error;
Elliott Hughes2435a572012-02-17 16:07:41 -08002417 }
Elliott Hughes86964332012-02-15 19:37:42 -08002418
jeffhao09bfc6a2012-12-11 18:11:43 -08002419 MutexLock mu2(soa.Self(), *Locks::breakpoint_lock_);
Elliott Hughes86964332012-02-15 19:37:42 -08002420 // TODO: there's no theoretical reason why we couldn't support single-stepping
2421 // of multiple threads at once, but we never did so historically.
2422 if (gSingleStepControl.thread != NULL && thread != gSingleStepControl.thread) {
2423 LOG(WARNING) << "single-step already active for " << *gSingleStepControl.thread
2424 << "; switching to " << *thread;
2425 }
2426
Elliott Hughes2435a572012-02-17 16:07:41 -08002427 //
2428 // Work out what Method* we're in, the current line number, and how deep the stack currently
2429 // is for step-out.
2430 //
2431
Ian Rogers0399dde2012-06-06 17:09:28 -07002432 struct SingleStepStackVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -08002433 SingleStepStackVisitor(Thread* thread)
jeffhao09bfc6a2012-12-11 18:11:43 -08002434 EXCLUSIVE_LOCKS_REQUIRED(Locks::breakpoint_lock_)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002435 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08002436 : StackVisitor(thread, NULL) {
Elliott Hughes86964332012-02-15 19:37:42 -08002437 gSingleStepControl.method = NULL;
2438 gSingleStepControl.stack_depth = 0;
2439 }
Ian Rogersca190662012-06-26 15:45:57 -07002440
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002441 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2442 // annotalysis.
2443 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
jeffhao09bfc6a2012-12-11 18:11:43 -08002444 Locks::breakpoint_lock_->AssertHeld(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002445 const mirror::AbstractMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07002446 if (!m->IsRuntimeMethod()) {
Elliott Hughes86964332012-02-15 19:37:42 -08002447 ++gSingleStepControl.stack_depth;
2448 if (gSingleStepControl.method == NULL) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002449 const mirror::DexCache* dex_cache = m->GetDeclaringClass()->GetDexCache();
Elliott Hughes2435a572012-02-17 16:07:41 -08002450 gSingleStepControl.method = m;
2451 gSingleStepControl.line_number = -1;
2452 if (dex_cache != NULL) {
Ian Rogers4445a7e2012-10-05 17:19:13 -07002453 const DexFile& dex_file = *dex_cache->GetDexFile();
Ian Rogers0399dde2012-06-06 17:09:28 -07002454 gSingleStepControl.line_number = dex_file.GetLineNumFromPC(m, GetDexPc());
Elliott Hughes2435a572012-02-17 16:07:41 -08002455 }
Elliott Hughes86964332012-02-15 19:37:42 -08002456 }
2457 }
Elliott Hughes530fa002012-03-12 11:44:49 -07002458 return true;
Elliott Hughes86964332012-02-15 19:37:42 -08002459 }
2460 };
Ian Rogers7a22fa62013-01-23 12:16:16 -08002461 SingleStepStackVisitor visitor(thread);
Ian Rogers0399dde2012-06-06 17:09:28 -07002462 visitor.WalkStack();
Elliott Hughes86964332012-02-15 19:37:42 -08002463
Elliott Hughes2435a572012-02-17 16:07:41 -08002464 //
2465 // Find the dex_pc values that correspond to the current line, for line-based single-stepping.
2466 //
2467
2468 struct DebugCallbackContext {
jeffhao09bfc6a2012-12-11 18:11:43 -08002469 DebugCallbackContext() EXCLUSIVE_LOCKS_REQUIRED(Locks::breakpoint_lock_) {
Elliott Hughes2435a572012-02-17 16:07:41 -08002470 last_pc_valid = false;
2471 last_pc = 0;
Elliott Hughes2435a572012-02-17 16:07:41 -08002472 }
2473
jeffhao09bfc6a2012-12-11 18:11:43 -08002474 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2475 // annotalysis.
2476 static bool Callback(void* raw_context, uint32_t address, uint32_t line_number) NO_THREAD_SAFETY_ANALYSIS {
2477 Locks::breakpoint_lock_->AssertHeld(Thread::Current());
Elliott Hughes2435a572012-02-17 16:07:41 -08002478 DebugCallbackContext* context = reinterpret_cast<DebugCallbackContext*>(raw_context);
2479 if (static_cast<int32_t>(line_number) == gSingleStepControl.line_number) {
2480 if (!context->last_pc_valid) {
2481 // Everything from this address until the next line change is ours.
2482 context->last_pc = address;
2483 context->last_pc_valid = true;
2484 }
2485 // Otherwise, if we're already in a valid range for this line,
2486 // just keep going (shouldn't really happen)...
2487 } else if (context->last_pc_valid) { // and the line number is new
2488 // Add everything from the last entry up until here to the set
2489 for (uint32_t dex_pc = context->last_pc; dex_pc < address; ++dex_pc) {
2490 gSingleStepControl.dex_pcs.insert(dex_pc);
2491 }
2492 context->last_pc_valid = false;
2493 }
2494 return false; // There may be multiple entries for any given line.
2495 }
2496
jeffhao09bfc6a2012-12-11 18:11:43 -08002497 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2498 // annotalysis.
2499 ~DebugCallbackContext() NO_THREAD_SAFETY_ANALYSIS {
2500 Locks::breakpoint_lock_->AssertHeld(Thread::Current());
Elliott Hughes2435a572012-02-17 16:07:41 -08002501 // If the line number was the last in the position table...
2502 if (last_pc_valid) {
2503 size_t end = MethodHelper(gSingleStepControl.method).GetCodeItem()->insns_size_in_code_units_;
2504 for (uint32_t dex_pc = last_pc; dex_pc < end; ++dex_pc) {
2505 gSingleStepControl.dex_pcs.insert(dex_pc);
2506 }
2507 }
2508 }
2509
2510 bool last_pc_valid;
2511 uint32_t last_pc;
2512 };
Elliott Hughes3e2e1a22012-02-21 11:33:41 -08002513 gSingleStepControl.dex_pcs.clear();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002514 const mirror::AbstractMethod* m = gSingleStepControl.method;
Elliott Hughes3e2e1a22012-02-21 11:33:41 -08002515 if (m->IsNative()) {
2516 gSingleStepControl.line_number = -1;
2517 } else {
2518 DebugCallbackContext context;
2519 MethodHelper mh(m);
2520 mh.GetDexFile().DecodeDebugInfo(mh.GetCodeItem(), m->IsStatic(), m->GetDexMethodIndex(),
2521 DebugCallbackContext::Callback, NULL, &context);
2522 }
Elliott Hughes2435a572012-02-17 16:07:41 -08002523
2524 //
2525 // Everything else...
2526 //
2527
Elliott Hughes86964332012-02-15 19:37:42 -08002528 gSingleStepControl.thread = thread;
2529 gSingleStepControl.step_size = step_size;
2530 gSingleStepControl.step_depth = step_depth;
2531 gSingleStepControl.is_active = true;
2532
Elliott Hughes2435a572012-02-17 16:07:41 -08002533 if (VLOG_IS_ON(jdwp)) {
2534 VLOG(jdwp) << "Single-step thread: " << *gSingleStepControl.thread;
2535 VLOG(jdwp) << "Single-step step size: " << gSingleStepControl.step_size;
2536 VLOG(jdwp) << "Single-step step depth: " << gSingleStepControl.step_depth;
2537 VLOG(jdwp) << "Single-step current method: " << PrettyMethod(gSingleStepControl.method);
2538 VLOG(jdwp) << "Single-step current line: " << gSingleStepControl.line_number;
2539 VLOG(jdwp) << "Single-step current stack depth: " << gSingleStepControl.stack_depth;
2540 VLOG(jdwp) << "Single-step dex_pc values:";
2541 for (std::set<uint32_t>::iterator it = gSingleStepControl.dex_pcs.begin() ; it != gSingleStepControl.dex_pcs.end(); ++it) {
Elliott Hughes229feb72012-02-23 13:33:29 -08002542 VLOG(jdwp) << StringPrintf(" %#x", *it);
Elliott Hughes2435a572012-02-17 16:07:41 -08002543 }
2544 }
2545
2546 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002547}
2548
Elliott Hughes221229c2013-01-08 18:17:50 -08002549void Dbg::UnconfigureStep(JDWP::ObjectId /*thread_id*/) {
jeffhao09bfc6a2012-12-11 18:11:43 -08002550 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Elliott Hughesf8349362012-06-18 15:00:06 -07002551
Elliott Hughes86964332012-02-15 19:37:42 -08002552 gSingleStepControl.is_active = false;
2553 gSingleStepControl.thread = NULL;
Elliott Hughes2435a572012-02-17 16:07:41 -08002554 gSingleStepControl.dex_pcs.clear();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002555}
2556
Elliott Hughes45651fd2012-02-21 15:48:20 -08002557static char JdwpTagToShortyChar(JDWP::JdwpTag tag) {
2558 switch (tag) {
2559 default:
2560 LOG(FATAL) << "unknown JDWP tag: " << PrintableChar(tag);
2561
2562 // Primitives.
2563 case JDWP::JT_BYTE: return 'B';
2564 case JDWP::JT_CHAR: return 'C';
2565 case JDWP::JT_FLOAT: return 'F';
2566 case JDWP::JT_DOUBLE: return 'D';
2567 case JDWP::JT_INT: return 'I';
2568 case JDWP::JT_LONG: return 'J';
2569 case JDWP::JT_SHORT: return 'S';
2570 case JDWP::JT_VOID: return 'V';
2571 case JDWP::JT_BOOLEAN: return 'Z';
2572
2573 // Reference types.
2574 case JDWP::JT_ARRAY:
2575 case JDWP::JT_OBJECT:
2576 case JDWP::JT_STRING:
2577 case JDWP::JT_THREAD:
2578 case JDWP::JT_THREAD_GROUP:
2579 case JDWP::JT_CLASS_LOADER:
2580 case JDWP::JT_CLASS_OBJECT:
2581 return 'L';
2582 }
2583}
2584
Elliott Hughes88d63092013-01-09 09:55:54 -08002585JDWP::JdwpError Dbg::InvokeMethod(JDWP::ObjectId thread_id, JDWP::ObjectId object_id,
2586 JDWP::RefTypeId class_id, JDWP::MethodId method_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002587 uint32_t arg_count, uint64_t* arg_values,
2588 JDWP::JdwpTag* arg_types, uint32_t options,
2589 JDWP::JdwpTag* pResultTag, uint64_t* pResultValue,
2590 JDWP::ObjectId* pExceptionId) {
Elliott Hughesd07986f2011-12-06 18:27:45 -08002591 ThreadList* thread_list = Runtime::Current()->GetThreadList();
2592
2593 Thread* targetThread = NULL;
2594 DebugInvokeReq* req = NULL;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002595 Thread* self = Thread::Current();
Elliott Hughesd07986f2011-12-06 18:27:45 -08002596 {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002597 ScopedObjectAccessUnchecked soa(self);
Ian Rogers50b35e22012-10-04 10:09:15 -07002598 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002599 JDWP::JdwpError error = DecodeThread(soa, thread_id, targetThread);
2600 if (error != JDWP::ERR_NONE) {
2601 LOG(ERROR) << "InvokeMethod request for invalid thread id " << thread_id;
2602 return error;
Elliott Hughesd07986f2011-12-06 18:27:45 -08002603 }
2604 req = targetThread->GetInvokeReq();
2605 if (!req->ready) {
2606 LOG(ERROR) << "InvokeMethod request for thread not stopped by event: " << *targetThread;
2607 return JDWP::ERR_INVALID_THREAD;
2608 }
2609
2610 /*
2611 * We currently have a bug where we don't successfully resume the
2612 * target thread if the suspend count is too deep. We're expected to
2613 * require one "resume" for each "suspend", but when asked to execute
2614 * a method we have to resume fully and then re-suspend it back to the
2615 * same level. (The easiest way to cause this is to type "suspend"
2616 * multiple times in jdb.)
2617 *
2618 * It's unclear what this means when the event specifies "resume all"
2619 * and some threads are suspended more deeply than others. This is
2620 * a rare problem, so for now we just prevent it from hanging forever
2621 * by rejecting the method invocation request. Without this, we will
2622 * be stuck waiting on a suspended thread.
2623 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002624 int suspend_count;
2625 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002626 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002627 suspend_count = targetThread->GetSuspendCount();
2628 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08002629 if (suspend_count > 1) {
2630 LOG(ERROR) << *targetThread << " suspend count too deep for method invocation: " << suspend_count;
2631 return JDWP::ERR_THREAD_SUSPENDED; // Probably not expected here.
2632 }
2633
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002634 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002635 mirror::Object* receiver = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes45651fd2012-02-21 15:48:20 -08002636 if (receiver == kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002637 return JDWP::ERR_INVALID_OBJECT;
2638 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002639
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002640 mirror::Object* thread = gRegistry->Get<mirror::Object*>(thread_id);
Elliott Hughes45651fd2012-02-21 15:48:20 -08002641 if (thread == kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002642 return JDWP::ERR_INVALID_OBJECT;
2643 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002644 // TODO: check that 'thread' is actually a java.lang.Thread!
2645
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002646 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes45651fd2012-02-21 15:48:20 -08002647 if (c == NULL) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002648 return status;
2649 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002650
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002651 mirror::AbstractMethod* m = FromMethodId(method_id);
Elliott Hughes45651fd2012-02-21 15:48:20 -08002652 if (m->IsStatic() != (receiver == NULL)) {
2653 return JDWP::ERR_INVALID_METHODID;
2654 }
2655 if (m->IsStatic()) {
2656 if (m->GetDeclaringClass() != c) {
2657 return JDWP::ERR_INVALID_METHODID;
2658 }
2659 } else {
2660 if (!m->GetDeclaringClass()->IsAssignableFrom(c)) {
2661 return JDWP::ERR_INVALID_METHODID;
2662 }
2663 }
2664
2665 // Check the argument list matches the method.
2666 MethodHelper mh(m);
2667 if (mh.GetShortyLength() - 1 != arg_count) {
2668 return JDWP::ERR_ILLEGAL_ARGUMENT;
2669 }
2670 const char* shorty = mh.GetShorty();
2671 for (size_t i = 0; i < arg_count; ++i) {
2672 if (shorty[i + 1] != JdwpTagToShortyChar(arg_types[i])) {
2673 return JDWP::ERR_ILLEGAL_ARGUMENT;
2674 }
2675 }
2676
2677 req->receiver_ = receiver;
2678 req->thread_ = thread;
2679 req->class_ = c;
2680 req->method_ = m;
2681 req->arg_count_ = arg_count;
2682 req->arg_values_ = arg_values;
Elliott Hughesd07986f2011-12-06 18:27:45 -08002683 req->options_ = options;
2684 req->invoke_needed_ = true;
2685 }
2686
2687 // The fact that we've released the thread list lock is a bit risky --- if the thread goes
2688 // away we're sitting high and dry -- but we must release this before the ResumeAllThreads
2689 // call, and it's unwise to hold it during WaitForSuspend.
2690
2691 {
2692 /*
2693 * We change our (JDWP thread) status, which should be THREAD_RUNNING,
Elliott Hughes81ff3182012-03-23 20:35:56 -07002694 * so we can suspend for a GC if the invoke request causes us to
Elliott Hughesd07986f2011-12-06 18:27:45 -08002695 * run out of memory. It's also a good idea to change it before locking
2696 * the invokeReq mutex, although that should never be held for long.
2697 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002698 self->TransitionFromRunnableToSuspended(kWaitingForDebuggerSend);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002699
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002700 VLOG(jdwp) << " Transferring control to event thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002701 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002702 MutexLock mu(self, req->lock_);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002703
2704 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002705 VLOG(jdwp) << " Resuming all threads";
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002706 thread_list->UndoDebuggerSuspensions();
Elliott Hughesd07986f2011-12-06 18:27:45 -08002707 } else {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002708 VLOG(jdwp) << " Resuming event thread only";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002709 thread_list->Resume(targetThread, true);
2710 }
2711
2712 // Wait for the request to finish executing.
2713 while (req->invoke_needed_) {
Ian Rogersc604d732012-10-14 16:09:54 -07002714 req->cond_.Wait(self);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002715 }
2716 }
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002717 VLOG(jdwp) << " Control has returned from event thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002718
2719 /* wait for thread to re-suspend itself */
Elliott Hughes221229c2013-01-08 18:17:50 -08002720 SuspendThread(thread_id, false /* request_suspension */ );
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002721 self->TransitionFromSuspendedToRunnable();
Elliott Hughesd07986f2011-12-06 18:27:45 -08002722 }
2723
2724 /*
2725 * Suspend the threads. We waited for the target thread to suspend
2726 * itself, so all we need to do is suspend the others.
2727 *
2728 * The suspendAllThreads() call will double-suspend the event thread,
2729 * so we want to resume the target thread once to keep the books straight.
2730 */
2731 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002732 self->TransitionFromRunnableToSuspended(kWaitingForDebuggerSuspension);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002733 VLOG(jdwp) << " Suspending all threads";
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002734 thread_list->SuspendAllForDebugger();
2735 self->TransitionFromSuspendedToRunnable();
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002736 VLOG(jdwp) << " Resuming event thread to balance the count";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002737 thread_list->Resume(targetThread, true);
2738 }
2739
2740 // Copy the result.
2741 *pResultTag = req->result_tag;
2742 if (IsPrimitiveTag(req->result_tag)) {
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002743 *pResultValue = req->result_value.GetJ();
Elliott Hughesd07986f2011-12-06 18:27:45 -08002744 } else {
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002745 *pResultValue = gRegistry->Add(req->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002746 }
2747 *pExceptionId = req->exception;
2748 return req->error;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002749}
2750
2751void Dbg::ExecuteMethod(DebugInvokeReq* pReq) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002752 ScopedObjectAccess soa(Thread::Current());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002753
Elliott Hughes81ff3182012-03-23 20:35:56 -07002754 // We can be called while an exception is pending. We need
Elliott Hughesd07986f2011-12-06 18:27:45 -08002755 // to preserve that across the method invocation.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002756 SirtRef<mirror::Throwable> old_exception(soa.Self(), soa.Self()->GetException());
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002757 soa.Self()->ClearException();
Elliott Hughesd07986f2011-12-06 18:27:45 -08002758
2759 // Translate the method through the vtable, unless the debugger wants to suppress it.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002760 mirror::AbstractMethod* m = pReq->method_;
Elliott Hughesd07986f2011-12-06 18:27:45 -08002761 if ((pReq->options_ & JDWP::INVOKE_NONVIRTUAL) == 0 && pReq->receiver_ != NULL) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002762 mirror::AbstractMethod* actual_method = pReq->class_->FindVirtualMethodForVirtualOrInterface(pReq->method_);
Elliott Hughes45651fd2012-02-21 15:48:20 -08002763 if (actual_method != m) {
2764 VLOG(jdwp) << "ExecuteMethod translated " << PrettyMethod(m) << " to " << PrettyMethod(actual_method);
2765 m = actual_method;
2766 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08002767 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002768 VLOG(jdwp) << "ExecuteMethod " << PrettyMethod(m);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002769 CHECK(m != NULL);
2770
2771 CHECK_EQ(sizeof(jvalue), sizeof(uint64_t));
2772
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002773 LOG(INFO) << "self=" << soa.Self() << " pReq->receiver_=" << pReq->receiver_ << " m=" << m
2774 << " #" << pReq->arg_count_ << " " << pReq->arg_values_;
2775 pReq->result_value = InvokeWithJValues(soa, pReq->receiver_, m,
2776 reinterpret_cast<JValue*>(pReq->arg_values_));
Elliott Hughesd07986f2011-12-06 18:27:45 -08002777
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002778 pReq->exception = gRegistry->Add(soa.Self()->GetException());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002779 pReq->result_tag = BasicTagFromDescriptor(MethodHelper(m).GetShorty());
2780 if (pReq->exception != 0) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002781 mirror::Object* exc = soa.Self()->GetException();
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002782 VLOG(jdwp) << " JDWP invocation returning with exception=" << exc << " " << PrettyTypeOf(exc);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002783 soa.Self()->ClearException();
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002784 pReq->result_value.SetJ(0);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002785 } else if (pReq->result_tag == JDWP::JT_OBJECT) {
2786 /* if no exception thrown, examine object result more closely */
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002787 JDWP::JdwpTag new_tag = TagFromObject(pReq->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002788 if (new_tag != pReq->result_tag) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002789 VLOG(jdwp) << " JDWP promoted result from " << pReq->result_tag << " to " << new_tag;
Elliott Hughesd07986f2011-12-06 18:27:45 -08002790 pReq->result_tag = new_tag;
2791 }
2792
2793 /*
2794 * Register the object. We don't actually need an ObjectId yet,
2795 * but we do need to be sure that the GC won't move or discard the
2796 * object when we switch out of RUNNING. The ObjectId conversion
2797 * will add the object to the "do not touch" list.
2798 *
2799 * We can't use the "tracked allocation" mechanism here because
2800 * the object is going to be handed off to a different thread.
2801 */
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002802 gRegistry->Add(pReq->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002803 }
2804
2805 if (old_exception.get() != NULL) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002806 soa.Self()->SetException(old_exception.get());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002807 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002808}
2809
Elliott Hughesd07986f2011-12-06 18:27:45 -08002810/*
2811 * Register an object ID that might not have been registered previously.
2812 *
2813 * Normally this wouldn't happen -- the conversion to an ObjectId would
2814 * have added the object to the registry -- but in some cases (e.g.
2815 * throwing exceptions) we really want to do the registration late.
2816 */
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002817void Dbg::RegisterObjectId(JDWP::ObjectId id) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002818 gRegistry->Add(reinterpret_cast<mirror::Object*>(id));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002819}
2820
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002821/*
2822 * "buf" contains a full JDWP packet, possibly with multiple chunks. We
2823 * need to process each, accumulate the replies, and ship the whole thing
2824 * back.
2825 *
2826 * Returns "true" if we have a reply. The reply buffer is newly allocated,
2827 * and includes the chunk type/length, followed by the data.
2828 *
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08002829 * OLD-TODO: we currently assume that the request and reply include a single
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002830 * chunk. If this becomes inconvenient we will need to adapt.
2831 */
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002832bool Dbg::DdmHandlePacket(const uint8_t* buf, int dataLen, uint8_t** pReplyBuf, int* pReplyLen) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002833 CHECK_GE(dataLen, 0);
2834
2835 Thread* self = Thread::Current();
2836 JNIEnv* env = self->GetJniEnv();
2837
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002838 // Create a byte[] corresponding to 'buf'.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002839 ScopedLocalRef<jbyteArray> dataArray(env, env->NewByteArray(dataLen));
2840 if (dataArray.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002841 LOG(WARNING) << "byte[] allocation failed: " << dataLen;
2842 env->ExceptionClear();
2843 return false;
2844 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002845 env->SetByteArrayRegion(dataArray.get(), 0, dataLen, reinterpret_cast<const jbyte*>(buf));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002846
2847 const int kChunkHdrLen = 8;
2848
2849 // Run through and find all chunks. [Currently just find the first.]
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002850 ScopedByteArrayRO contents(env, dataArray.get());
Elliott Hughesf7c3b662011-10-27 12:04:56 -07002851 jint type = JDWP::Get4BE(reinterpret_cast<const uint8_t*>(&contents[0]));
2852 jint length = JDWP::Get4BE(reinterpret_cast<const uint8_t*>(&contents[4]));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002853 jint offset = kChunkHdrLen;
2854 if (offset + length > dataLen) {
2855 LOG(WARNING) << StringPrintf("bad chunk found (len=%u pktLen=%d)", length, dataLen);
2856 return false;
2857 }
2858
2859 // Call "private static Chunk dispatch(int type, byte[] data, int offset, int length)".
Elliott Hugheseac76672012-05-24 21:56:51 -07002860 ScopedLocalRef<jobject> chunk(env, env->CallStaticObjectMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
2861 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_dispatch,
2862 type, dataArray.get(), offset, length));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002863 if (env->ExceptionCheck()) {
2864 LOG(INFO) << StringPrintf("Exception thrown by dispatcher for 0x%08x", type);
2865 env->ExceptionDescribe();
2866 env->ExceptionClear();
2867 return false;
2868 }
2869
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002870 if (chunk.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002871 return false;
2872 }
2873
2874 /*
2875 * Pull the pieces out of the chunk. We copy the results into a
2876 * newly-allocated buffer that the caller can free. We don't want to
2877 * continue using the Chunk object because nothing has a reference to it.
2878 *
2879 * We could avoid this by returning type/data/offset/length and having
2880 * the caller be aware of the object lifetime issues, but that
Elliott Hughes81ff3182012-03-23 20:35:56 -07002881 * integrates the JDWP code more tightly into the rest of the runtime, and doesn't work
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002882 * if we have responses for multiple chunks.
2883 *
2884 * So we're pretty much stuck with copying data around multiple times.
2885 */
Elliott Hugheseac76672012-05-24 21:56:51 -07002886 ScopedLocalRef<jbyteArray> replyData(env, reinterpret_cast<jbyteArray>(env->GetObjectField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_data)));
2887 length = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_length);
2888 offset = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_offset);
2889 type = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_type);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002890
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002891 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 -07002892 if (length == 0 || replyData.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002893 return false;
2894 }
2895
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002896 jsize replyLength = env->GetArrayLength(replyData.get());
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002897 if (offset + length > replyLength) {
2898 LOG(WARNING) << StringPrintf("chunk off=%d len=%d exceeds reply array len %d", offset, length, replyLength);
2899 return false;
2900 }
2901
2902 uint8_t* reply = new uint8_t[length + kChunkHdrLen];
2903 if (reply == NULL) {
2904 LOG(WARNING) << "malloc failed: " << (length + kChunkHdrLen);
2905 return false;
2906 }
Elliott Hughesf7c3b662011-10-27 12:04:56 -07002907 JDWP::Set4BE(reply + 0, type);
2908 JDWP::Set4BE(reply + 4, length);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002909 env->GetByteArrayRegion(replyData.get(), offset, length, reinterpret_cast<jbyte*>(reply + kChunkHdrLen));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002910
2911 *pReplyBuf = reply;
2912 *pReplyLen = length + kChunkHdrLen;
2913
Elliott Hughesba8eee12012-01-24 20:25:24 -08002914 VLOG(jdwp) << StringPrintf("dvmHandleDdm returning type=%.4s buf=%p len=%d", reinterpret_cast<char*>(reply), reply, length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002915 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002916}
2917
Elliott Hughesa2155262011-11-16 16:26:58 -08002918void Dbg::DdmBroadcast(bool connect) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002919 VLOG(jdwp) << "Broadcasting DDM " << (connect ? "connect" : "disconnect") << "...";
Elliott Hughes47fce012011-10-25 18:37:19 -07002920
2921 Thread* self = Thread::Current();
Ian Rogers50b35e22012-10-04 10:09:15 -07002922 if (self->GetState() != kRunnable) {
2923 LOG(ERROR) << "DDM broadcast in thread state " << self->GetState();
2924 /* try anyway? */
Elliott Hughes47fce012011-10-25 18:37:19 -07002925 }
2926
2927 JNIEnv* env = self->GetJniEnv();
Elliott Hughes47fce012011-10-25 18:37:19 -07002928 jint event = connect ? 1 /*DdmServer.CONNECTED*/ : 2 /*DdmServer.DISCONNECTED*/;
Elliott Hugheseac76672012-05-24 21:56:51 -07002929 env->CallStaticVoidMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
2930 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_broadcast,
2931 event);
Elliott Hughes47fce012011-10-25 18:37:19 -07002932 if (env->ExceptionCheck()) {
2933 LOG(ERROR) << "DdmServer.broadcast " << event << " failed";
2934 env->ExceptionDescribe();
2935 env->ExceptionClear();
2936 }
2937}
2938
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002939void Dbg::DdmConnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08002940 Dbg::DdmBroadcast(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002941}
2942
2943void Dbg::DdmDisconnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08002944 Dbg::DdmBroadcast(false);
Elliott Hughes47fce012011-10-25 18:37:19 -07002945 gDdmThreadNotification = false;
2946}
2947
2948/*
Elliott Hughes82188472011-11-07 18:11:48 -08002949 * Send a notification when a thread starts, stops, or changes its name.
Elliott Hughes47fce012011-10-25 18:37:19 -07002950 *
2951 * Because we broadcast the full set of threads when the notifications are
2952 * first enabled, it's possible for "thread" to be actively executing.
2953 */
Elliott Hughes82188472011-11-07 18:11:48 -08002954void Dbg::DdmSendThreadNotification(Thread* t, uint32_t type) {
Elliott Hughes47fce012011-10-25 18:37:19 -07002955 if (!gDdmThreadNotification) {
2956 return;
2957 }
2958
Elliott Hughes82188472011-11-07 18:11:48 -08002959 if (type == CHUNK_TYPE("THDE")) {
Elliott Hughes47fce012011-10-25 18:37:19 -07002960 uint8_t buf[4];
Elliott Hughesf7c3b662011-10-27 12:04:56 -07002961 JDWP::Set4BE(&buf[0], t->GetThinLockId());
Elliott Hughes47fce012011-10-25 18:37:19 -07002962 Dbg::DdmSendChunk(CHUNK_TYPE("THDE"), 4, buf);
Elliott Hughes82188472011-11-07 18:11:48 -08002963 } else {
2964 CHECK(type == CHUNK_TYPE("THCR") || type == CHUNK_TYPE("THNM")) << type;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002965 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002966 SirtRef<mirror::String> name(soa.Self(), t->GetThreadName(soa));
Elliott Hughes82188472011-11-07 18:11:48 -08002967 size_t char_count = (name.get() != NULL) ? name->GetLength() : 0;
jeffhao725a9572012-11-13 18:20:12 -08002968 const jchar* chars = (name.get() != NULL) ? name->GetCharArray()->GetData() : NULL;
Elliott Hughes82188472011-11-07 18:11:48 -08002969
Elliott Hughes21f32d72011-11-09 17:44:13 -08002970 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08002971 JDWP::Append4BE(bytes, t->GetThinLockId());
2972 JDWP::AppendUtf16BE(bytes, chars, char_count);
Elliott Hughes21f32d72011-11-09 17:44:13 -08002973 CHECK_EQ(bytes.size(), char_count*2 + sizeof(uint32_t)*2);
2974 Dbg::DdmSendChunk(type, bytes);
Elliott Hughes47fce012011-10-25 18:37:19 -07002975 }
2976}
2977
Elliott Hughes47fce012011-10-25 18:37:19 -07002978void Dbg::DdmSetThreadNotification(bool enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002979 // Enable/disable thread notifications.
Elliott Hughes47fce012011-10-25 18:37:19 -07002980 gDdmThreadNotification = enable;
2981 if (enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002982 // Suspend the VM then post thread start notifications for all threads. Threads attaching will
2983 // see a suspension in progress and block until that ends. They then post their own start
2984 // notification.
2985 SuspendVM();
2986 std::list<Thread*> threads;
Ian Rogers50b35e22012-10-04 10:09:15 -07002987 Thread* self = Thread::Current();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002988 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002989 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002990 threads = Runtime::Current()->GetThreadList()->GetList();
2991 }
2992 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002993 ScopedObjectAccess soa(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002994 typedef std::list<Thread*>::const_iterator It; // TODO: C++0x auto
2995 for (It it = threads.begin(), end = threads.end(); it != end; ++it) {
2996 Dbg::DdmSendThreadNotification(*it, CHUNK_TYPE("THCR"));
2997 }
2998 }
2999 ResumeVM();
Elliott Hughes47fce012011-10-25 18:37:19 -07003000 }
3001}
3002
Elliott Hughesa2155262011-11-16 16:26:58 -08003003void Dbg::PostThreadStartOrStop(Thread* t, uint32_t type) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07003004 if (IsDebuggerActive()) {
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07003005 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogerscfaa4552012-11-26 21:00:08 -08003006 JDWP::ObjectId id = gRegistry->Add(t->GetPeer());
Elliott Hughes82188472011-11-07 18:11:48 -08003007 gJdwpState->PostThreadChange(id, type == CHUNK_TYPE("THCR"));
Elliott Hughesc0f09332012-03-26 13:27:06 -07003008 // If this thread's just joined the party while we're already debugging, make sure it knows
3009 // to give us updates when it's running.
3010 t->SetDebuggerUpdatesEnabled(true);
Elliott Hughes47fce012011-10-25 18:37:19 -07003011 }
Elliott Hughes82188472011-11-07 18:11:48 -08003012 Dbg::DdmSendThreadNotification(t, type);
Elliott Hughes47fce012011-10-25 18:37:19 -07003013}
3014
3015void Dbg::PostThreadStart(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08003016 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07003017}
3018
3019void Dbg::PostThreadDeath(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08003020 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THDE"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003021}
3022
Elliott Hughes82188472011-11-07 18:11:48 -08003023void Dbg::DdmSendChunk(uint32_t type, size_t byte_count, const uint8_t* buf) {
Elliott Hughes3bb81562011-10-21 18:52:59 -07003024 CHECK(buf != NULL);
3025 iovec vec[1];
3026 vec[0].iov_base = reinterpret_cast<void*>(const_cast<uint8_t*>(buf));
3027 vec[0].iov_len = byte_count;
3028 Dbg::DdmSendChunkV(type, vec, 1);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003029}
3030
Elliott Hughes21f32d72011-11-09 17:44:13 -08003031void Dbg::DdmSendChunk(uint32_t type, const std::vector<uint8_t>& bytes) {
3032 DdmSendChunk(type, bytes.size(), &bytes[0]);
3033}
3034
Elliott Hughescccd84f2011-12-05 16:51:54 -08003035void Dbg::DdmSendChunkV(uint32_t type, const struct iovec* iov, int iov_count) {
Elliott Hughes3bb81562011-10-21 18:52:59 -07003036 if (gJdwpState == NULL) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003037 VLOG(jdwp) << "Debugger thread not active, ignoring DDM send: " << type;
Elliott Hughes3bb81562011-10-21 18:52:59 -07003038 } else {
Elliott Hughescccd84f2011-12-05 16:51:54 -08003039 gJdwpState->DdmSendChunkV(type, iov, iov_count);
Elliott Hughes3bb81562011-10-21 18:52:59 -07003040 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003041}
3042
Elliott Hughes767a1472011-10-26 18:49:02 -07003043int Dbg::DdmHandleHpifChunk(HpifWhen when) {
3044 if (when == HPIF_WHEN_NOW) {
Elliott Hughes7162ad92011-10-27 14:08:42 -07003045 DdmSendHeapInfo(when);
Elliott Hughes767a1472011-10-26 18:49:02 -07003046 return true;
3047 }
3048
3049 if (when != HPIF_WHEN_NEVER && when != HPIF_WHEN_NEXT_GC && when != HPIF_WHEN_EVERY_GC) {
3050 LOG(ERROR) << "invalid HpifWhen value: " << static_cast<int>(when);
3051 return false;
3052 }
3053
3054 gDdmHpifWhen = when;
3055 return true;
3056}
3057
3058bool Dbg::DdmHandleHpsgNhsgChunk(Dbg::HpsgWhen when, Dbg::HpsgWhat what, bool native) {
3059 if (when != HPSG_WHEN_NEVER && when != HPSG_WHEN_EVERY_GC) {
3060 LOG(ERROR) << "invalid HpsgWhen value: " << static_cast<int>(when);
3061 return false;
3062 }
3063
3064 if (what != HPSG_WHAT_MERGED_OBJECTS && what != HPSG_WHAT_DISTINCT_OBJECTS) {
3065 LOG(ERROR) << "invalid HpsgWhat value: " << static_cast<int>(what);
3066 return false;
3067 }
3068
3069 if (native) {
3070 gDdmNhsgWhen = when;
3071 gDdmNhsgWhat = what;
3072 } else {
3073 gDdmHpsgWhen = when;
3074 gDdmHpsgWhat = what;
3075 }
3076 return true;
3077}
3078
Elliott Hughes7162ad92011-10-27 14:08:42 -07003079void Dbg::DdmSendHeapInfo(HpifWhen reason) {
3080 // If there's a one-shot 'when', reset it.
3081 if (reason == gDdmHpifWhen) {
3082 if (gDdmHpifWhen == HPIF_WHEN_NEXT_GC) {
3083 gDdmHpifWhen = HPIF_WHEN_NEVER;
3084 }
3085 }
3086
3087 /*
3088 * Chunk HPIF (client --> server)
3089 *
3090 * Heap Info. General information about the heap,
3091 * suitable for a summary display.
3092 *
3093 * [u4]: number of heaps
3094 *
3095 * For each heap:
3096 * [u4]: heap ID
3097 * [u8]: timestamp in ms since Unix epoch
3098 * [u1]: capture reason (same as 'when' value from server)
3099 * [u4]: max heap size in bytes (-Xmx)
3100 * [u4]: current heap size in bytes
3101 * [u4]: current number of bytes allocated
3102 * [u4]: current number of objects allocated
3103 */
3104 uint8_t heap_count = 1;
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08003105 Heap* heap = Runtime::Current()->GetHeap();
Elliott Hughes21f32d72011-11-09 17:44:13 -08003106 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08003107 JDWP::Append4BE(bytes, heap_count);
3108 JDWP::Append4BE(bytes, 1); // Heap id (bogus; we only have one heap).
3109 JDWP::Append8BE(bytes, MilliTime());
3110 JDWP::Append1BE(bytes, reason);
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08003111 JDWP::Append4BE(bytes, heap->GetMaxMemory()); // Max allowed heap size in bytes.
3112 JDWP::Append4BE(bytes, heap->GetTotalMemory()); // Current heap size in bytes.
3113 JDWP::Append4BE(bytes, heap->GetBytesAllocated());
3114 JDWP::Append4BE(bytes, heap->GetObjectsAllocated());
Elliott Hughes21f32d72011-11-09 17:44:13 -08003115 CHECK_EQ(bytes.size(), 4U + (heap_count * (4 + 8 + 1 + 4 + 4 + 4 + 4)));
3116 Dbg::DdmSendChunk(CHUNK_TYPE("HPIF"), bytes);
Elliott Hughes767a1472011-10-26 18:49:02 -07003117}
3118
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003119enum HpsgSolidity {
3120 SOLIDITY_FREE = 0,
3121 SOLIDITY_HARD = 1,
3122 SOLIDITY_SOFT = 2,
3123 SOLIDITY_WEAK = 3,
3124 SOLIDITY_PHANTOM = 4,
3125 SOLIDITY_FINALIZABLE = 5,
3126 SOLIDITY_SWEEP = 6,
3127};
3128
3129enum HpsgKind {
3130 KIND_OBJECT = 0,
3131 KIND_CLASS_OBJECT = 1,
3132 KIND_ARRAY_1 = 2,
3133 KIND_ARRAY_2 = 3,
3134 KIND_ARRAY_4 = 4,
3135 KIND_ARRAY_8 = 5,
3136 KIND_UNKNOWN = 6,
3137 KIND_NATIVE = 7,
3138};
3139
3140#define HPSG_PARTIAL (1<<7)
3141#define HPSG_STATE(solidity, kind) ((uint8_t)((((kind) & 0x7) << 3) | ((solidity) & 0x7)))
3142
Ian Rogers30fab402012-01-23 15:43:46 -08003143class HeapChunkContext {
3144 public:
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003145 // Maximum chunk size. Obtain this from the formula:
3146 // (((maximum_heap_size / ALLOCATION_UNIT_SIZE) + 255) / 256) * 2
3147 HeapChunkContext(bool merge, bool native)
Ian Rogers30fab402012-01-23 15:43:46 -08003148 : buf_(16384 - 16),
3149 type_(0),
3150 merge_(merge) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003151 Reset();
3152 if (native) {
Ian Rogers30fab402012-01-23 15:43:46 -08003153 type_ = CHUNK_TYPE("NHSG");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003154 } else {
Ian Rogers30fab402012-01-23 15:43:46 -08003155 type_ = merge ? CHUNK_TYPE("HPSG") : CHUNK_TYPE("HPSO");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003156 }
3157 }
3158
3159 ~HeapChunkContext() {
Ian Rogers30fab402012-01-23 15:43:46 -08003160 if (p_ > &buf_[0]) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003161 Flush();
3162 }
3163 }
3164
3165 void EnsureHeader(const void* chunk_ptr) {
Ian Rogers30fab402012-01-23 15:43:46 -08003166 if (!needHeader_) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003167 return;
3168 }
3169
3170 // Start a new HPSx chunk.
Ian Rogers30fab402012-01-23 15:43:46 -08003171 JDWP::Write4BE(&p_, 1); // Heap id (bogus; we only have one heap).
3172 JDWP::Write1BE(&p_, 8); // Size of allocation unit, in bytes.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003173
Ian Rogers30fab402012-01-23 15:43:46 -08003174 JDWP::Write4BE(&p_, reinterpret_cast<uintptr_t>(chunk_ptr)); // virtual address of segment start.
3175 JDWP::Write4BE(&p_, 0); // offset of this piece (relative to the virtual address).
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003176 // [u4]: length of piece, in allocation units
3177 // 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 -08003178 pieceLenField_ = p_;
3179 JDWP::Write4BE(&p_, 0x55555555);
3180 needHeader_ = false;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003181 }
3182
Ian Rogersb726dcb2012-09-05 08:57:23 -07003183 void Flush() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogersd636b062013-01-18 17:51:18 -08003184 if (pieceLenField_ == NULL) {
3185 // Flush immediately post Reset (maybe back-to-back Flush). Ignore.
3186 CHECK(needHeader_);
3187 return;
3188 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003189 // Patch the "length of piece" field.
Ian Rogers30fab402012-01-23 15:43:46 -08003190 CHECK_LE(&buf_[0], pieceLenField_);
3191 CHECK_LE(pieceLenField_, p_);
3192 JDWP::Set4BE(pieceLenField_, totalAllocationUnits_);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003193
Ian Rogers30fab402012-01-23 15:43:46 -08003194 Dbg::DdmSendChunk(type_, p_ - &buf_[0], &buf_[0]);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003195 Reset();
3196 }
3197
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003198 static void HeapChunkCallback(void* start, void* end, size_t used_bytes, void* arg)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003199 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_,
3200 Locks::mutator_lock_) {
Ian Rogers30fab402012-01-23 15:43:46 -08003201 reinterpret_cast<HeapChunkContext*>(arg)->HeapChunkCallback(start, end, used_bytes);
Elliott Hughesa2155262011-11-16 16:26:58 -08003202 }
3203
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003204 private:
Elliott Hughesa2155262011-11-16 16:26:58 -08003205 enum { ALLOCATION_UNIT_SIZE = 8 };
3206
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003207 void Reset() {
Ian Rogers30fab402012-01-23 15:43:46 -08003208 p_ = &buf_[0];
Ian Rogers15bf2d32012-08-28 17:33:04 -07003209 startOfNextMemoryChunk_ = NULL;
Ian Rogers30fab402012-01-23 15:43:46 -08003210 totalAllocationUnits_ = 0;
3211 needHeader_ = true;
3212 pieceLenField_ = NULL;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003213 }
3214
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003215 void HeapChunkCallback(void* start, void* /*end*/, size_t used_bytes)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003216 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_,
3217 Locks::mutator_lock_) {
Ian Rogers30fab402012-01-23 15:43:46 -08003218 // Note: heap call backs cannot manipulate the heap upon which they are crawling, care is taken
3219 // in the following code not to allocate memory, by ensuring buf_ is of the correct size
Ian Rogers15bf2d32012-08-28 17:33:04 -07003220 if (used_bytes == 0) {
3221 if (start == NULL) {
3222 // Reset for start of new heap.
3223 startOfNextMemoryChunk_ = NULL;
3224 Flush();
3225 }
3226 // Only process in use memory so that free region information
3227 // also includes dlmalloc book keeping.
Elliott Hughesa2155262011-11-16 16:26:58 -08003228 return;
Elliott Hughesa2155262011-11-16 16:26:58 -08003229 }
3230
Ian Rogers15bf2d32012-08-28 17:33:04 -07003231 /* If we're looking at the native heap, we'll just return
3232 * (SOLIDITY_HARD, KIND_NATIVE) for all allocated chunks
3233 */
3234 bool native = type_ == CHUNK_TYPE("NHSG");
3235
3236 if (startOfNextMemoryChunk_ != NULL) {
3237 // Transmit any pending free memory. Native free memory of
3238 // over kMaxFreeLen could be because of the use of mmaps, so
3239 // don't report. If not free memory then start a new segment.
3240 bool flush = true;
3241 if (start > startOfNextMemoryChunk_) {
3242 const size_t kMaxFreeLen = 2 * kPageSize;
3243 void* freeStart = startOfNextMemoryChunk_;
3244 void* freeEnd = start;
3245 size_t freeLen = (char*)freeEnd - (char*)freeStart;
3246 if (!native || freeLen < kMaxFreeLen) {
3247 AppendChunk(HPSG_STATE(SOLIDITY_FREE, 0), freeStart, freeLen);
3248 flush = false;
3249 }
3250 }
3251 if (flush) {
3252 startOfNextMemoryChunk_ = NULL;
3253 Flush();
3254 }
3255 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003256 const mirror::Object* obj = reinterpret_cast<const mirror::Object*>(start);
Elliott Hughesa2155262011-11-16 16:26:58 -08003257
3258 // Determine the type of this chunk.
3259 // OLD-TODO: if context.merge, see if this chunk is different from the last chunk.
3260 // If it's the same, we should combine them.
Ian Rogers15bf2d32012-08-28 17:33:04 -07003261 uint8_t state = ExamineObject(obj, native);
3262 // dlmalloc's chunk header is 2 * sizeof(size_t), but if the previous chunk is in use for an
3263 // allocation then the first sizeof(size_t) may belong to it.
3264 const size_t dlMallocOverhead = sizeof(size_t);
3265 AppendChunk(state, start, used_bytes + dlMallocOverhead);
3266 startOfNextMemoryChunk_ = (char*)start + used_bytes + dlMallocOverhead;
3267 }
Elliott Hughesa2155262011-11-16 16:26:58 -08003268
Ian Rogers15bf2d32012-08-28 17:33:04 -07003269 void AppendChunk(uint8_t state, void* ptr, size_t length)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003270 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07003271 // Make sure there's enough room left in the buffer.
3272 // We need to use two bytes for every fractional 256 allocation units used by the chunk plus
3273 // 17 bytes for any header.
3274 size_t needed = (((length/ALLOCATION_UNIT_SIZE + 255) / 256) * 2) + 17;
3275 size_t bytesLeft = buf_.size() - (size_t)(p_ - &buf_[0]);
3276 if (bytesLeft < needed) {
3277 Flush();
3278 }
3279
3280 bytesLeft = buf_.size() - (size_t)(p_ - &buf_[0]);
3281 if (bytesLeft < needed) {
3282 LOG(WARNING) << "Chunk is too big to transmit (chunk_len=" << length << ", "
3283 << needed << " bytes)";
3284 return;
3285 }
3286 EnsureHeader(ptr);
Elliott Hughesa2155262011-11-16 16:26:58 -08003287 // Write out the chunk description.
Ian Rogers15bf2d32012-08-28 17:33:04 -07003288 length /= ALLOCATION_UNIT_SIZE; // Convert to allocation units.
3289 totalAllocationUnits_ += length;
3290 while (length > 256) {
Ian Rogers30fab402012-01-23 15:43:46 -08003291 *p_++ = state | HPSG_PARTIAL;
3292 *p_++ = 255; // length - 1
Ian Rogers15bf2d32012-08-28 17:33:04 -07003293 length -= 256;
Elliott Hughesa2155262011-11-16 16:26:58 -08003294 }
Ian Rogers30fab402012-01-23 15:43:46 -08003295 *p_++ = state;
Ian Rogers15bf2d32012-08-28 17:33:04 -07003296 *p_++ = length - 1;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003297 }
3298
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003299 uint8_t ExamineObject(const mirror::Object* o, bool is_native_heap)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003300 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
Elliott Hughesa2155262011-11-16 16:26:58 -08003301 if (o == NULL) {
3302 return HPSG_STATE(SOLIDITY_FREE, 0);
3303 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003304
Elliott Hughesa2155262011-11-16 16:26:58 -08003305 // It's an allocated chunk. Figure out what it is.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003306
Elliott Hughesa2155262011-11-16 16:26:58 -08003307 // If we're looking at the native heap, we'll just return
3308 // (SOLIDITY_HARD, KIND_NATIVE) for all allocated chunks.
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003309 if (is_native_heap) {
Elliott Hughesa2155262011-11-16 16:26:58 -08003310 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
3311 }
3312
Ian Rogers5bfa60f2012-09-02 21:17:56 -07003313 if (!Runtime::Current()->GetHeap()->IsLiveObjectLocked(o)) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07003314 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003315 }
3316
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003317 mirror::Class* c = o->GetClass();
Elliott Hughesa2155262011-11-16 16:26:58 -08003318 if (c == NULL) {
3319 // The object was probably just created but hasn't been initialized yet.
3320 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
3321 }
3322
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08003323 if (!Runtime::Current()->GetHeap()->IsHeapAddress(c)) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07003324 LOG(ERROR) << "Invalid class for managed heap object: " << o << " " << c;
Elliott Hughesa2155262011-11-16 16:26:58 -08003325 return HPSG_STATE(SOLIDITY_HARD, KIND_UNKNOWN);
3326 }
3327
3328 if (c->IsClassClass()) {
3329 return HPSG_STATE(SOLIDITY_HARD, KIND_CLASS_OBJECT);
3330 }
3331
3332 if (c->IsArrayClass()) {
3333 if (o->IsObjectArray()) {
3334 return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
3335 }
3336 switch (c->GetComponentSize()) {
3337 case 1: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_1);
3338 case 2: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_2);
3339 case 4: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
3340 case 8: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_8);
3341 }
3342 }
3343
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003344 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
3345 }
3346
Ian Rogers30fab402012-01-23 15:43:46 -08003347 std::vector<uint8_t> buf_;
3348 uint8_t* p_;
3349 uint8_t* pieceLenField_;
Ian Rogers15bf2d32012-08-28 17:33:04 -07003350 void* startOfNextMemoryChunk_;
Ian Rogers30fab402012-01-23 15:43:46 -08003351 size_t totalAllocationUnits_;
3352 uint32_t type_;
3353 bool merge_;
3354 bool needHeader_;
3355
Elliott Hughesa2155262011-11-16 16:26:58 -08003356 DISALLOW_COPY_AND_ASSIGN(HeapChunkContext);
3357};
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003358
3359void Dbg::DdmSendHeapSegments(bool native) {
3360 Dbg::HpsgWhen when;
3361 Dbg::HpsgWhat what;
3362 if (!native) {
3363 when = gDdmHpsgWhen;
3364 what = gDdmHpsgWhat;
3365 } else {
3366 when = gDdmNhsgWhen;
3367 what = gDdmNhsgWhat;
3368 }
3369 if (when == HPSG_WHEN_NEVER) {
3370 return;
3371 }
3372
3373 // Figure out what kind of chunks we'll be sending.
3374 CHECK(what == HPSG_WHAT_MERGED_OBJECTS || what == HPSG_WHAT_DISTINCT_OBJECTS) << static_cast<int>(what);
3375
3376 // First, send a heap start chunk.
3377 uint8_t heap_id[4];
3378 JDWP::Set4BE(&heap_id[0], 1); // Heap id (bogus; we only have one heap).
3379 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHST") : CHUNK_TYPE("HPST"), sizeof(heap_id), heap_id);
3380
3381 // Send a series of heap segment chunks.
Elliott Hughesa2155262011-11-16 16:26:58 -08003382 HeapChunkContext context((what == HPSG_WHAT_MERGED_OBJECTS), native);
3383 if (native) {
Ian Rogers30fab402012-01-23 15:43:46 -08003384 // TODO: enable when bionic has moved to dlmalloc 2.8.5
3385 // dlmalloc_inspect_all(HeapChunkContext::HeapChunkCallback, &context);
3386 UNIMPLEMENTED(WARNING) << "Native heap send heap segments";
Elliott Hughesa2155262011-11-16 16:26:58 -08003387 } else {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08003388 Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07003389 const Spaces& spaces = heap->GetSpaces();
Ian Rogers50b35e22012-10-04 10:09:15 -07003390 Thread* self = Thread::Current();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07003391 for (Spaces::const_iterator cur = spaces.begin(); cur != spaces.end(); ++cur) {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07003392 if ((*cur)->IsAllocSpace()) {
Ian Rogers50b35e22012-10-04 10:09:15 -07003393 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07003394 (*cur)->AsAllocSpace()->Walk(HeapChunkContext::HeapChunkCallback, &context);
3395 }
3396 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07003397 // Walk the large objects, these are not in the AllocSpace.
3398 heap->GetLargeObjectsSpace()->Walk(HeapChunkContext::HeapChunkCallback, &context);
Elliott Hughesa2155262011-11-16 16:26:58 -08003399 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003400
3401 // Finally, send a heap end chunk.
3402 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHEN") : CHUNK_TYPE("HPEN"), sizeof(heap_id), heap_id);
Elliott Hughes767a1472011-10-26 18:49:02 -07003403}
3404
Elliott Hughes545a0642011-11-08 19:10:03 -08003405void Dbg::SetAllocTrackingEnabled(bool enabled) {
Ian Rogers50b35e22012-10-04 10:09:15 -07003406 MutexLock mu(Thread::Current(), gAllocTrackerLock);
Elliott Hughes545a0642011-11-08 19:10:03 -08003407 if (enabled) {
3408 if (recent_allocation_records_ == NULL) {
3409 LOG(INFO) << "Enabling alloc tracker (" << kNumAllocRecords << " entries, "
3410 << kMaxAllocRecordStackDepth << " frames --> "
3411 << (sizeof(AllocRecord) * kNumAllocRecords) << " bytes)";
3412 gAllocRecordHead = gAllocRecordCount = 0;
3413 recent_allocation_records_ = new AllocRecord[kNumAllocRecords];
3414 CHECK(recent_allocation_records_ != NULL);
3415 }
3416 } else {
3417 delete[] recent_allocation_records_;
3418 recent_allocation_records_ = NULL;
3419 }
3420}
3421
Ian Rogers0399dde2012-06-06 17:09:28 -07003422struct AllocRecordStackVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -08003423 AllocRecordStackVisitor(Thread* thread, AllocRecord* record)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003424 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08003425 : StackVisitor(thread, NULL), record(record), depth(0) {}
Elliott Hughes545a0642011-11-08 19:10:03 -08003426
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003427 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
3428 // annotalysis.
3429 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughes545a0642011-11-08 19:10:03 -08003430 if (depth >= kMaxAllocRecordStackDepth) {
Elliott Hughes530fa002012-03-12 11:44:49 -07003431 return false;
Elliott Hughes545a0642011-11-08 19:10:03 -08003432 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003433 mirror::AbstractMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07003434 if (!m->IsRuntimeMethod()) {
3435 record->stack[depth].method = m;
3436 record->stack[depth].dex_pc = GetDexPc();
Elliott Hughes530fa002012-03-12 11:44:49 -07003437 ++depth;
Elliott Hughes545a0642011-11-08 19:10:03 -08003438 }
Elliott Hughes530fa002012-03-12 11:44:49 -07003439 return true;
Elliott Hughes545a0642011-11-08 19:10:03 -08003440 }
3441
3442 ~AllocRecordStackVisitor() {
3443 // Clear out any unused stack trace elements.
3444 for (; depth < kMaxAllocRecordStackDepth; ++depth) {
3445 record->stack[depth].method = NULL;
Ian Rogers0399dde2012-06-06 17:09:28 -07003446 record->stack[depth].dex_pc = 0;
Elliott Hughes545a0642011-11-08 19:10:03 -08003447 }
3448 }
3449
3450 AllocRecord* record;
3451 size_t depth;
3452};
3453
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003454void Dbg::RecordAllocation(mirror::Class* type, size_t byte_count) {
Elliott Hughes545a0642011-11-08 19:10:03 -08003455 Thread* self = Thread::Current();
3456 CHECK(self != NULL);
3457
Ian Rogers50b35e22012-10-04 10:09:15 -07003458 MutexLock mu(self, gAllocTrackerLock);
Elliott Hughes545a0642011-11-08 19:10:03 -08003459 if (recent_allocation_records_ == NULL) {
3460 return;
3461 }
3462
3463 // Advance and clip.
3464 if (++gAllocRecordHead == kNumAllocRecords) {
3465 gAllocRecordHead = 0;
3466 }
3467
3468 // Fill in the basics.
3469 AllocRecord* record = &recent_allocation_records_[gAllocRecordHead];
3470 record->type = type;
3471 record->byte_count = byte_count;
3472 record->thin_lock_id = self->GetThinLockId();
3473
3474 // Fill in the stack trace.
Ian Rogers7a22fa62013-01-23 12:16:16 -08003475 AllocRecordStackVisitor visitor(self, record);
Ian Rogers0399dde2012-06-06 17:09:28 -07003476 visitor.WalkStack();
Elliott Hughes545a0642011-11-08 19:10:03 -08003477
3478 if (gAllocRecordCount < kNumAllocRecords) {
3479 ++gAllocRecordCount;
3480 }
3481}
3482
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003483// Returns the index of the head element.
3484//
3485// We point at the most-recently-written record, so if gAllocRecordCount is 1
3486// we want to use the current element. Take "head+1" and subtract count
3487// from it.
3488//
3489// We need to handle underflow in our circular buffer, so we add
3490// kNumAllocRecords and then mask it back down.
Elliott Hughesf8349362012-06-18 15:00:06 -07003491static inline int HeadIndex() EXCLUSIVE_LOCKS_REQUIRED(gAllocTrackerLock) {
Elliott Hughes545a0642011-11-08 19:10:03 -08003492 return (gAllocRecordHead+1 + kNumAllocRecords - gAllocRecordCount) & (kNumAllocRecords-1);
3493}
3494
3495void Dbg::DumpRecentAllocations() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003496 ScopedObjectAccess soa(Thread::Current());
Ian Rogers50b35e22012-10-04 10:09:15 -07003497 MutexLock mu(soa.Self(), gAllocTrackerLock);
Elliott Hughes545a0642011-11-08 19:10:03 -08003498 if (recent_allocation_records_ == NULL) {
3499 LOG(INFO) << "Not recording tracked allocations";
3500 return;
3501 }
3502
3503 // "i" is the head of the list. We want to start at the end of the
3504 // list and move forward to the tail.
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003505 size_t i = HeadIndex();
Elliott Hughes545a0642011-11-08 19:10:03 -08003506 size_t count = gAllocRecordCount;
3507
3508 LOG(INFO) << "Tracked allocations, (head=" << gAllocRecordHead << " count=" << count << ")";
3509 while (count--) {
3510 AllocRecord* record = &recent_allocation_records_[i];
3511
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003512 LOG(INFO) << StringPrintf(" Thread %-2d %6zd bytes ", record->thin_lock_id, record->byte_count)
Elliott Hughes545a0642011-11-08 19:10:03 -08003513 << PrettyClass(record->type);
3514
3515 for (size_t stack_frame = 0; stack_frame < kMaxAllocRecordStackDepth; ++stack_frame) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003516 const mirror::AbstractMethod* m = record->stack[stack_frame].method;
Elliott Hughes545a0642011-11-08 19:10:03 -08003517 if (m == NULL) {
3518 break;
3519 }
3520 LOG(INFO) << " " << PrettyMethod(m) << " line " << record->stack[stack_frame].LineNumber();
3521 }
3522
3523 // pause periodically to help logcat catch up
3524 if ((count % 5) == 0) {
3525 usleep(40000);
3526 }
3527
3528 i = (i + 1) & (kNumAllocRecords-1);
3529 }
3530}
3531
3532class StringTable {
3533 public:
3534 StringTable() {
3535 }
3536
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003537 void Add(const char* s) {
Elliott Hughes545a0642011-11-08 19:10:03 -08003538 table_.insert(s);
3539 }
3540
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003541 size_t IndexOf(const char* s) const {
3542 typedef std::set<std::string>::const_iterator It; // TODO: C++0x auto
3543 It it = table_.find(s);
3544 if (it == table_.end()) {
3545 LOG(FATAL) << "IndexOf(\"" << s << "\") failed";
3546 }
3547 return std::distance(table_.begin(), it);
Elliott Hughes545a0642011-11-08 19:10:03 -08003548 }
3549
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003550 size_t Size() const {
Elliott Hughes545a0642011-11-08 19:10:03 -08003551 return table_.size();
3552 }
3553
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003554 void WriteTo(std::vector<uint8_t>& bytes) const {
3555 typedef std::set<std::string>::const_iterator It; // TODO: C++0x auto
Elliott Hughes545a0642011-11-08 19:10:03 -08003556 for (It it = table_.begin(); it != table_.end(); ++it) {
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003557 const char* s = (*it).c_str();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003558 size_t s_len = CountModifiedUtf8Chars(s);
3559 UniquePtr<uint16_t> s_utf16(new uint16_t[s_len]);
3560 ConvertModifiedUtf8ToUtf16(s_utf16.get(), s);
3561 JDWP::AppendUtf16BE(bytes, s_utf16.get(), s_len);
Elliott Hughes545a0642011-11-08 19:10:03 -08003562 }
3563 }
3564
3565 private:
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003566 std::set<std::string> table_;
Elliott Hughes545a0642011-11-08 19:10:03 -08003567 DISALLOW_COPY_AND_ASSIGN(StringTable);
3568};
3569
3570/*
3571 * The data we send to DDMS contains everything we have recorded.
3572 *
3573 * Message header (all values big-endian):
3574 * (1b) message header len (to allow future expansion); includes itself
3575 * (1b) entry header len
3576 * (1b) stack frame len
3577 * (2b) number of entries
3578 * (4b) offset to string table from start of message
3579 * (2b) number of class name strings
3580 * (2b) number of method name strings
3581 * (2b) number of source file name strings
3582 * For each entry:
3583 * (4b) total allocation size
Elliott Hughes221229c2013-01-08 18:17:50 -08003584 * (2b) thread id
Elliott Hughes545a0642011-11-08 19:10:03 -08003585 * (2b) allocated object's class name index
3586 * (1b) stack depth
3587 * For each stack frame:
3588 * (2b) method's class name
3589 * (2b) method name
3590 * (2b) method source file
3591 * (2b) line number, clipped to 32767; -2 if native; -1 if no source
3592 * (xb) class name strings
3593 * (xb) method name strings
3594 * (xb) source file strings
3595 *
3596 * As with other DDM traffic, strings are sent as a 4-byte length
3597 * followed by UTF-16 data.
3598 *
3599 * We send up 16-bit unsigned indexes into string tables. In theory there
3600 * can be (kMaxAllocRecordStackDepth * kNumAllocRecords) unique strings in
3601 * each table, but in practice there should be far fewer.
3602 *
3603 * The chief reason for using a string table here is to keep the size of
3604 * the DDMS message to a minimum. This is partly to make the protocol
3605 * efficient, but also because we have to form the whole thing up all at
3606 * once in a memory buffer.
3607 *
3608 * We use separate string tables for class names, method names, and source
3609 * files to keep the indexes small. There will generally be no overlap
3610 * between the contents of these tables.
3611 */
3612jbyteArray Dbg::GetRecentAllocations() {
3613 if (false) {
3614 DumpRecentAllocations();
3615 }
3616
Ian Rogers50b35e22012-10-04 10:09:15 -07003617 Thread* self = Thread::Current();
3618 MutexLock mu(self, gAllocTrackerLock);
Elliott Hughes545a0642011-11-08 19:10:03 -08003619
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003620 //
3621 // Part 1: generate string tables.
3622 //
Elliott Hughes545a0642011-11-08 19:10:03 -08003623 StringTable class_names;
3624 StringTable method_names;
3625 StringTable filenames;
3626
3627 int count = gAllocRecordCount;
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003628 int idx = HeadIndex();
Elliott Hughes545a0642011-11-08 19:10:03 -08003629 while (count--) {
3630 AllocRecord* record = &recent_allocation_records_[idx];
3631
Elliott Hughes91250e02011-12-13 22:30:35 -08003632 class_names.Add(ClassHelper(record->type).GetDescriptor());
Elliott Hughes545a0642011-11-08 19:10:03 -08003633
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003634 MethodHelper mh;
Elliott Hughes545a0642011-11-08 19:10:03 -08003635 for (size_t i = 0; i < kMaxAllocRecordStackDepth; i++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003636 mirror::AbstractMethod* m = record->stack[i].method;
Elliott Hughes545a0642011-11-08 19:10:03 -08003637 if (m != NULL) {
Ian Rogersba377812012-05-28 21:16:29 -07003638 mh.ChangeMethod(m);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003639 class_names.Add(mh.GetDeclaringClassDescriptor());
3640 method_names.Add(mh.GetName());
3641 filenames.Add(mh.GetDeclaringClassSourceFile());
Elliott Hughes545a0642011-11-08 19:10:03 -08003642 }
3643 }
3644
3645 idx = (idx + 1) & (kNumAllocRecords-1);
3646 }
3647
3648 LOG(INFO) << "allocation records: " << gAllocRecordCount;
3649
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003650 //
3651 // Part 2: allocate a buffer and generate the output.
3652 //
Elliott Hughes545a0642011-11-08 19:10:03 -08003653 std::vector<uint8_t> bytes;
3654
3655 // (1b) message header len (to allow future expansion); includes itself
3656 // (1b) entry header len
3657 // (1b) stack frame len
3658 const int kMessageHeaderLen = 15;
3659 const int kEntryHeaderLen = 9;
3660 const int kStackFrameLen = 8;
3661 JDWP::Append1BE(bytes, kMessageHeaderLen);
3662 JDWP::Append1BE(bytes, kEntryHeaderLen);
3663 JDWP::Append1BE(bytes, kStackFrameLen);
3664
3665 // (2b) number of entries
3666 // (4b) offset to string table from start of message
3667 // (2b) number of class name strings
3668 // (2b) number of method name strings
3669 // (2b) number of source file name strings
3670 JDWP::Append2BE(bytes, gAllocRecordCount);
3671 size_t string_table_offset = bytes.size();
3672 JDWP::Append4BE(bytes, 0); // We'll patch this later...
3673 JDWP::Append2BE(bytes, class_names.Size());
3674 JDWP::Append2BE(bytes, method_names.Size());
3675 JDWP::Append2BE(bytes, filenames.Size());
3676
3677 count = gAllocRecordCount;
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003678 idx = HeadIndex();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003679 ClassHelper kh;
Elliott Hughes545a0642011-11-08 19:10:03 -08003680 while (count--) {
3681 // For each entry:
3682 // (4b) total allocation size
3683 // (2b) thread id
3684 // (2b) allocated object's class name index
3685 // (1b) stack depth
3686 AllocRecord* record = &recent_allocation_records_[idx];
3687 size_t stack_depth = record->GetDepth();
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003688 kh.ChangeClass(record->type);
3689 size_t allocated_object_class_name_index = class_names.IndexOf(kh.GetDescriptor());
Elliott Hughes545a0642011-11-08 19:10:03 -08003690 JDWP::Append4BE(bytes, record->byte_count);
3691 JDWP::Append2BE(bytes, record->thin_lock_id);
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003692 JDWP::Append2BE(bytes, allocated_object_class_name_index);
Elliott Hughes545a0642011-11-08 19:10:03 -08003693 JDWP::Append1BE(bytes, stack_depth);
3694
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003695 MethodHelper mh;
Elliott Hughes545a0642011-11-08 19:10:03 -08003696 for (size_t stack_frame = 0; stack_frame < stack_depth; ++stack_frame) {
3697 // For each stack frame:
3698 // (2b) method's class name
3699 // (2b) method name
3700 // (2b) method source file
3701 // (2b) line number, clipped to 32767; -2 if native; -1 if no source
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003702 mh.ChangeMethod(record->stack[stack_frame].method);
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003703 size_t class_name_index = class_names.IndexOf(mh.GetDeclaringClassDescriptor());
3704 size_t method_name_index = method_names.IndexOf(mh.GetName());
3705 size_t file_name_index = filenames.IndexOf(mh.GetDeclaringClassSourceFile());
3706 JDWP::Append2BE(bytes, class_name_index);
3707 JDWP::Append2BE(bytes, method_name_index);
3708 JDWP::Append2BE(bytes, file_name_index);
Elliott Hughes545a0642011-11-08 19:10:03 -08003709 JDWP::Append2BE(bytes, record->stack[stack_frame].LineNumber());
3710 }
3711
3712 idx = (idx + 1) & (kNumAllocRecords-1);
3713 }
3714
3715 // (xb) class name strings
3716 // (xb) method name strings
3717 // (xb) source file strings
3718 JDWP::Set4BE(&bytes[string_table_offset], bytes.size());
3719 class_names.WriteTo(bytes);
3720 method_names.WriteTo(bytes);
3721 filenames.WriteTo(bytes);
3722
Ian Rogers50b35e22012-10-04 10:09:15 -07003723 JNIEnv* env = self->GetJniEnv();
Elliott Hughes545a0642011-11-08 19:10:03 -08003724 jbyteArray result = env->NewByteArray(bytes.size());
3725 if (result != NULL) {
3726 env->SetByteArrayRegion(result, 0, bytes.size(), reinterpret_cast<const jbyte*>(&bytes[0]));
3727 }
3728 return result;
3729}
3730
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003731} // namespace art