blob: 1e1e7b660946676b50fb512b8e2fd62bfba4a44d [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"
Elliott Hughes1bba14f2011-12-01 18:00:36 -080024#include "class_loader.h"
Ian Rogers776ac1f2012-04-13 23:36:36 -070025#include "dex_instruction.h"
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -070026#include "gc/large_object_space.h"
27#include "gc/space.h"
Ian Rogers776ac1f2012-04-13 23:36:36 -070028#if !defined(ART_USE_LLVM_COMPILER)
29#include "oat/runtime/context.h" // For VmapTable
30#endif
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080031#include "object_utils.h"
Elliott Hughesa0e18062012-04-13 15:59:59 -070032#include "safe_map.h"
Elliott Hughes6a5bd492011-10-28 14:33:57 -070033#include "ScopedLocalRef.h"
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -070034#include "ScopedPrimitiveArray.h"
Ian Rogers00f7d0e2012-07-19 15:28:27 -070035#include "scoped_thread_state_change.h"
Ian Rogers1f539342012-10-03 21:09:42 -070036#include "sirt_ref.h"
Elliott Hughes47fce012011-10-25 18:37:19 -070037#include "stack_indirect_reference_table.h"
Elliott Hughes475fc232011-10-25 15:00:35 -070038#include "thread_list.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070039#include "well_known_classes.h"
Elliott Hughes475fc232011-10-25 15:00:35 -070040
Elliott Hughes872d4ec2011-10-21 17:07:15 -070041namespace art {
42
Elliott Hughes545a0642011-11-08 19:10:03 -080043static const size_t kMaxAllocRecordStackDepth = 16; // Max 255.
44static const size_t kNumAllocRecords = 512; // Must be power of 2.
45
Elliott Hughes436e3722012-02-17 20:01:47 -080046static const uintptr_t kInvalidId = 1;
47static const Object* kInvalidObject = reinterpret_cast<Object*>(kInvalidId);
48
Elliott Hughes475fc232011-10-25 15:00:35 -070049class ObjectRegistry {
50 public:
51 ObjectRegistry() : lock_("ObjectRegistry lock") {
52 }
53
54 JDWP::ObjectId Add(Object* o) {
55 if (o == NULL) {
56 return 0;
57 }
58 JDWP::ObjectId id = static_cast<JDWP::ObjectId>(reinterpret_cast<uintptr_t>(o));
Ian Rogers50b35e22012-10-04 10:09:15 -070059 MutexLock mu(Thread::Current(), lock_);
Elliott Hughesa0e18062012-04-13 15:59:59 -070060 map_.Overwrite(id, o);
Elliott Hughes475fc232011-10-25 15:00:35 -070061 return id;
62 }
63
Elliott Hughes234ab152011-10-26 14:02:26 -070064 void Clear() {
Ian Rogers50b35e22012-10-04 10:09:15 -070065 MutexLock mu(Thread::Current(), lock_);
Elliott Hughes234ab152011-10-26 14:02:26 -070066 LOG(DEBUG) << "Debugger has detached; object registry had " << map_.size() << " entries";
67 map_.clear();
68 }
69
Elliott Hughes475fc232011-10-25 15:00:35 -070070 bool Contains(JDWP::ObjectId id) {
Ian Rogers50b35e22012-10-04 10:09:15 -070071 MutexLock mu(Thread::Current(), lock_);
Elliott Hughes475fc232011-10-25 15:00:35 -070072 return map_.find(id) != map_.end();
73 }
74
Elliott Hughesa2155262011-11-16 16:26:58 -080075 template<typename T> T Get(JDWP::ObjectId id) {
Elliott Hughes436e3722012-02-17 20:01:47 -080076 if (id == 0) {
77 return NULL;
78 }
79
Ian Rogers50b35e22012-10-04 10:09:15 -070080 MutexLock mu(Thread::Current(), lock_);
Elliott Hughesa0e18062012-04-13 15:59:59 -070081 typedef SafeMap<JDWP::ObjectId, Object*>::iterator It; // C++0x auto
Elliott Hughesa2155262011-11-16 16:26:58 -080082 It it = map_.find(id);
Elliott Hughes436e3722012-02-17 20:01:47 -080083 return (it != map_.end()) ? reinterpret_cast<T>(it->second) : reinterpret_cast<T>(kInvalidId);
Elliott Hughesa2155262011-11-16 16:26:58 -080084 }
85
Elliott Hughesbfe487b2011-10-26 15:48:55 -070086 void VisitRoots(Heap::RootVisitor* visitor, void* arg) {
Ian Rogers50b35e22012-10-04 10:09:15 -070087 MutexLock mu(Thread::Current(), lock_);
Elliott Hughesa0e18062012-04-13 15:59:59 -070088 typedef SafeMap<JDWP::ObjectId, Object*>::iterator It; // C++0x auto
Elliott Hughesbfe487b2011-10-26 15:48:55 -070089 for (It it = map_.begin(); it != map_.end(); ++it) {
90 visitor(it->second, arg);
91 }
92 }
93
Elliott Hughes475fc232011-10-25 15:00:35 -070094 private:
Ian Rogers00f7d0e2012-07-19 15:28:27 -070095 Mutex lock_ DEFAULT_MUTEX_ACQUIRED_AFTER;
Elliott Hughesa0e18062012-04-13 15:59:59 -070096 SafeMap<JDWP::ObjectId, Object*> map_;
Elliott Hughes475fc232011-10-25 15:00:35 -070097};
98
Elliott Hughes545a0642011-11-08 19:10:03 -080099struct AllocRecordStackTraceElement {
Mathieu Chartier66f19252012-09-18 08:57:04 -0700100 AbstractMethod* method;
Ian Rogers0399dde2012-06-06 17:09:28 -0700101 uint32_t dex_pc;
Elliott Hughes545a0642011-11-08 19:10:03 -0800102
Ian Rogersb726dcb2012-09-05 08:57:23 -0700103 int32_t LineNumber() const SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers0399dde2012-06-06 17:09:28 -0700104 return MethodHelper(method).GetLineNumFromDexPC(dex_pc);
Elliott Hughes545a0642011-11-08 19:10:03 -0800105 }
106};
107
108struct AllocRecord {
109 Class* type;
110 size_t byte_count;
111 uint16_t thin_lock_id;
112 AllocRecordStackTraceElement stack[kMaxAllocRecordStackDepth]; // Unused entries have NULL method.
113
114 size_t GetDepth() {
115 size_t depth = 0;
116 while (depth < kMaxAllocRecordStackDepth && stack[depth].method != NULL) {
117 ++depth;
118 }
119 return depth;
120 }
121};
122
Elliott Hughes86964332012-02-15 19:37:42 -0800123struct Breakpoint {
Mathieu Chartier66f19252012-09-18 08:57:04 -0700124 AbstractMethod* method;
Elliott Hughesa656a0f2012-02-21 18:03:44 -0800125 uint32_t dex_pc;
Mathieu Chartier66f19252012-09-18 08:57:04 -0700126 Breakpoint(AbstractMethod* method, uint32_t dex_pc) : method(method), dex_pc(dex_pc) {}
Elliott Hughes86964332012-02-15 19:37:42 -0800127};
128
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700129static std::ostream& operator<<(std::ostream& os, const Breakpoint& rhs)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700130 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes229feb72012-02-23 13:33:29 -0800131 os << StringPrintf("Breakpoint[%s @%#x]", PrettyMethod(rhs.method).c_str(), rhs.dex_pc);
Elliott Hughes86964332012-02-15 19:37:42 -0800132 return os;
133}
134
135struct SingleStepControl {
136 // Are we single-stepping right now?
137 bool is_active;
138 Thread* thread;
139
140 JDWP::JdwpStepSize step_size;
141 JDWP::JdwpStepDepth step_depth;
142
Mathieu Chartier66f19252012-09-18 08:57:04 -0700143 const AbstractMethod* method;
Elliott Hughes2435a572012-02-17 16:07:41 -0800144 int32_t line_number; // Or -1 for native methods.
145 std::set<uint32_t> dex_pcs;
Elliott Hughes86964332012-02-15 19:37:42 -0800146 int stack_depth;
147};
148
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700149// JDWP is allowed unless the Zygote forbids it.
150static bool gJdwpAllowed = true;
151
Elliott Hughesc0f09332012-03-26 13:27:06 -0700152// Was there a -Xrunjdwp or -agentlib:jdwp= argument on the command line?
Elliott Hughes3bb81562011-10-21 18:52:59 -0700153static bool gJdwpConfigured = false;
154
Elliott Hughesc0f09332012-03-26 13:27:06 -0700155// Broken-down JDWP options. (Only valid if IsJdwpConfigured() is true.)
Elliott Hughes376a7a02011-10-24 18:35:55 -0700156static JDWP::JdwpOptions gJdwpOptions;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700157
158// Runtime JDWP state.
159static JDWP::JdwpState* gJdwpState = NULL;
160static bool gDebuggerConnected; // debugger or DDMS is connected.
161static bool gDebuggerActive; // debugger is making requests.
Elliott Hughes86964332012-02-15 19:37:42 -0800162static bool gDisposed; // debugger called VirtualMachine.Dispose, so we should drop the connection.
Elliott Hughes3bb81562011-10-21 18:52:59 -0700163
Elliott Hughes47fce012011-10-25 18:37:19 -0700164static bool gDdmThreadNotification = false;
165
Elliott Hughes767a1472011-10-26 18:49:02 -0700166// DDMS GC-related settings.
167static Dbg::HpifWhen gDdmHpifWhen = Dbg::HPIF_WHEN_NEVER;
168static Dbg::HpsgWhen gDdmHpsgWhen = Dbg::HPSG_WHEN_NEVER;
169static Dbg::HpsgWhat gDdmHpsgWhat;
170static Dbg::HpsgWhen gDdmNhsgWhen = Dbg::HPSG_WHEN_NEVER;
171static Dbg::HpsgWhat gDdmNhsgWhat;
172
Elliott Hughes475fc232011-10-25 15:00:35 -0700173static ObjectRegistry* gRegistry = NULL;
174
Elliott Hughes545a0642011-11-08 19:10:03 -0800175// Recent allocation tracking.
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700176static Mutex gAllocTrackerLock DEFAULT_MUTEX_ACQUIRED_AFTER ("AllocTracker lock");
Elliott Hughesf8349362012-06-18 15:00:06 -0700177AllocRecord* Dbg::recent_allocation_records_ PT_GUARDED_BY(gAllocTrackerLock) = NULL; // TODO: CircularBuffer<AllocRecord>
178static size_t gAllocRecordHead GUARDED_BY(gAllocTrackerLock) = 0;
179static size_t gAllocRecordCount GUARDED_BY(gAllocTrackerLock) = 0;
Elliott Hughes545a0642011-11-08 19:10:03 -0800180
Elliott Hughes86964332012-02-15 19:37:42 -0800181// Breakpoints and single-stepping.
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700182static Mutex gBreakpointsLock DEFAULT_MUTEX_ACQUIRED_AFTER ("breakpoints lock");
Elliott Hughesf8349362012-06-18 15:00:06 -0700183static std::vector<Breakpoint> gBreakpoints GUARDED_BY(gBreakpointsLock);
184static SingleStepControl gSingleStepControl GUARDED_BY(gBreakpointsLock);
Elliott Hughes86964332012-02-15 19:37:42 -0800185
Mathieu Chartier66f19252012-09-18 08:57:04 -0700186static bool IsBreakpoint(AbstractMethod* m, uint32_t dex_pc)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700187 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers50b35e22012-10-04 10:09:15 -0700188 MutexLock mu(Thread::Current(), gBreakpointsLock);
Elliott Hughes86964332012-02-15 19:37:42 -0800189 for (size_t i = 0; i < gBreakpoints.size(); ++i) {
Elliott Hughesa656a0f2012-02-21 18:03:44 -0800190 if (gBreakpoints[i].method == m && gBreakpoints[i].dex_pc == dex_pc) {
Elliott Hughes86964332012-02-15 19:37:42 -0800191 VLOG(jdwp) << "Hit breakpoint #" << i << ": " << gBreakpoints[i];
192 return true;
193 }
194 }
195 return false;
196}
197
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700198static Array* DecodeArray(JDWP::RefTypeId id, JDWP::JdwpError& status)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700199 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800200 Object* o = gRegistry->Get<Object*>(id);
201 if (o == NULL || o == kInvalidObject) {
202 status = JDWP::ERR_INVALID_OBJECT;
203 return NULL;
204 }
205 if (!o->IsArrayInstance()) {
206 status = JDWP::ERR_INVALID_ARRAY;
207 return NULL;
208 }
209 status = JDWP::ERR_NONE;
210 return o->AsArray();
211}
212
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700213static Class* DecodeClass(JDWP::RefTypeId id, JDWP::JdwpError& status)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700214 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800215 Object* o = gRegistry->Get<Object*>(id);
216 if (o == NULL || o == kInvalidObject) {
217 status = JDWP::ERR_INVALID_OBJECT;
218 return NULL;
219 }
220 if (!o->IsClass()) {
221 status = JDWP::ERR_INVALID_CLASS;
222 return NULL;
223 }
224 status = JDWP::ERR_NONE;
225 return o->AsClass();
226}
227
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700228static Thread* DecodeThread(ScopedObjectAccessUnchecked& soa, JDWP::ObjectId threadId)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700229 LOCKS_EXCLUDED(Locks::thread_suspend_count_lock_)
230 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800231 Object* thread_peer = gRegistry->Get<Object*>(threadId);
232 if (thread_peer == NULL || thread_peer == kInvalidObject) {
233 return NULL;
234 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700235 Thread* thread = Thread::FromManagedThread(soa, thread_peer);
236 return thread;
Elliott Hughes436e3722012-02-17 20:01:47 -0800237}
238
Elliott Hughes24437992011-11-30 14:49:33 -0800239static JDWP::JdwpTag BasicTagFromDescriptor(const char* descriptor) {
240 // JDWP deliberately uses the descriptor characters' ASCII values for its enum.
241 // Note that by "basic" we mean that we don't get more specific than JT_OBJECT.
242 return static_cast<JDWP::JdwpTag>(descriptor[0]);
243}
244
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700245static JDWP::JdwpTag TagFromClass(Class* c)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700246 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes86b00102011-12-05 17:54:26 -0800247 CHECK(c != NULL);
Elliott Hughes24437992011-11-30 14:49:33 -0800248 if (c->IsArrayClass()) {
249 return JDWP::JT_ARRAY;
250 }
251
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800252 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Elliott Hughes24437992011-11-30 14:49:33 -0800253 if (c->IsStringClass()) {
254 return JDWP::JT_STRING;
255 } else if (c->IsClassClass()) {
256 return JDWP::JT_CLASS_OBJECT;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800257 } else if (class_linker->FindSystemClass("Ljava/lang/Thread;")->IsAssignableFrom(c)) {
Elliott Hughes24437992011-11-30 14:49:33 -0800258 return JDWP::JT_THREAD;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800259 } else if (class_linker->FindSystemClass("Ljava/lang/ThreadGroup;")->IsAssignableFrom(c)) {
Elliott Hughes24437992011-11-30 14:49:33 -0800260 return JDWP::JT_THREAD_GROUP;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800261 } else if (class_linker->FindSystemClass("Ljava/lang/ClassLoader;")->IsAssignableFrom(c)) {
Elliott Hughes24437992011-11-30 14:49:33 -0800262 return JDWP::JT_CLASS_LOADER;
Elliott Hughes24437992011-11-30 14:49:33 -0800263 } else {
264 return JDWP::JT_OBJECT;
265 }
266}
267
268/*
269 * Objects declared to hold Object might actually hold a more specific
270 * type. The debugger may take a special interest in these (e.g. it
271 * wants to display the contents of Strings), so we want to return an
272 * appropriate tag.
273 *
274 * Null objects are tagged JT_OBJECT.
275 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700276static JDWP::JdwpTag TagFromObject(const Object* o)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700277 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes24437992011-11-30 14:49:33 -0800278 return (o == NULL) ? JDWP::JT_OBJECT : TagFromClass(o->GetClass());
279}
280
281static bool IsPrimitiveTag(JDWP::JdwpTag tag) {
282 switch (tag) {
283 case JDWP::JT_BOOLEAN:
284 case JDWP::JT_BYTE:
285 case JDWP::JT_CHAR:
286 case JDWP::JT_FLOAT:
287 case JDWP::JT_DOUBLE:
288 case JDWP::JT_INT:
289 case JDWP::JT_LONG:
290 case JDWP::JT_SHORT:
291 case JDWP::JT_VOID:
292 return true;
293 default:
294 return false;
295 }
296}
297
Elliott Hughes3bb81562011-10-21 18:52:59 -0700298/*
299 * Handle one of the JDWP name/value pairs.
300 *
301 * JDWP options are:
302 * help: if specified, show help message and bail
303 * transport: may be dt_socket or dt_shmem
304 * address: for dt_socket, "host:port", or just "port" when listening
305 * server: if "y", wait for debugger to attach; if "n", attach to debugger
306 * timeout: how long to wait for debugger to connect / listen
307 *
308 * Useful with server=n (these aren't supported yet):
309 * onthrow=<exception-name>: connect to debugger when exception thrown
310 * onuncaught=y|n: connect to debugger when uncaught exception thrown
311 * launch=<command-line>: launch the debugger itself
312 *
313 * The "transport" option is required, as is "address" if server=n.
314 */
315static bool ParseJdwpOption(const std::string& name, const std::string& value) {
316 if (name == "transport") {
317 if (value == "dt_socket") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700318 gJdwpOptions.transport = JDWP::kJdwpTransportSocket;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700319 } else if (value == "dt_android_adb") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700320 gJdwpOptions.transport = JDWP::kJdwpTransportAndroidAdb;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700321 } else {
322 LOG(ERROR) << "JDWP transport not supported: " << value;
323 return false;
324 }
325 } else if (name == "server") {
326 if (value == "n") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700327 gJdwpOptions.server = false;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700328 } else if (value == "y") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700329 gJdwpOptions.server = true;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700330 } else {
331 LOG(ERROR) << "JDWP option 'server' must be 'y' or 'n'";
332 return false;
333 }
334 } else if (name == "suspend") {
335 if (value == "n") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700336 gJdwpOptions.suspend = false;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700337 } else if (value == "y") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700338 gJdwpOptions.suspend = true;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700339 } else {
340 LOG(ERROR) << "JDWP option 'suspend' must be 'y' or 'n'";
341 return false;
342 }
343 } else if (name == "address") {
344 /* this is either <port> or <host>:<port> */
345 std::string port_string;
Elliott Hughes376a7a02011-10-24 18:35:55 -0700346 gJdwpOptions.host.clear();
Elliott Hughes3bb81562011-10-21 18:52:59 -0700347 std::string::size_type colon = value.find(':');
348 if (colon != std::string::npos) {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700349 gJdwpOptions.host = value.substr(0, colon);
Elliott Hughes3bb81562011-10-21 18:52:59 -0700350 port_string = value.substr(colon + 1);
351 } else {
352 port_string = value;
353 }
354 if (port_string.empty()) {
355 LOG(ERROR) << "JDWP address missing port: " << value;
356 return false;
357 }
358 char* end;
Elliott Hughesba8eee12012-01-24 20:25:24 -0800359 uint64_t port = strtoul(port_string.c_str(), &end, 10);
360 if (*end != '\0' || port > 0xffff) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700361 LOG(ERROR) << "JDWP address has junk in port field: " << value;
362 return false;
363 }
Elliott Hughes376a7a02011-10-24 18:35:55 -0700364 gJdwpOptions.port = port;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700365 } else if (name == "launch" || name == "onthrow" || name == "oncaught" || name == "timeout") {
366 /* valid but unsupported */
367 LOG(INFO) << "Ignoring JDWP option '" << name << "'='" << value << "'";
368 } else {
369 LOG(INFO) << "Ignoring unrecognized JDWP option '" << name << "'='" << value << "'";
370 }
371
372 return true;
373}
374
375/*
376 * Parse the latter half of a -Xrunjdwp/-agentlib:jdwp= string, e.g.:
377 * "transport=dt_socket,address=8000,server=y,suspend=n"
378 */
379bool Dbg::ParseJdwpOptions(const std::string& options) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800380 VLOG(jdwp) << "ParseJdwpOptions: " << options;
Elliott Hughes47fce012011-10-25 18:37:19 -0700381
Elliott Hughes3bb81562011-10-21 18:52:59 -0700382 std::vector<std::string> pairs;
383 Split(options, ',', pairs);
384
385 for (size_t i = 0; i < pairs.size(); ++i) {
386 std::string::size_type equals = pairs[i].find('=');
387 if (equals == std::string::npos) {
388 LOG(ERROR) << "Can't parse JDWP option '" << pairs[i] << "' in '" << options << "'";
389 return false;
390 }
391 ParseJdwpOption(pairs[i].substr(0, equals), pairs[i].substr(equals + 1));
392 }
393
Elliott Hughes376a7a02011-10-24 18:35:55 -0700394 if (gJdwpOptions.transport == JDWP::kJdwpTransportUnknown) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700395 LOG(ERROR) << "Must specify JDWP transport: " << options;
396 }
Elliott Hughes376a7a02011-10-24 18:35:55 -0700397 if (!gJdwpOptions.server && (gJdwpOptions.host.empty() || gJdwpOptions.port == 0)) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700398 LOG(ERROR) << "Must specify JDWP host and port when server=n: " << options;
399 return false;
400 }
401
402 gJdwpConfigured = true;
403 return true;
404}
405
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700406void Dbg::StartJdwp() {
Elliott Hughesc0f09332012-03-26 13:27:06 -0700407 if (!gJdwpAllowed || !IsJdwpConfigured()) {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700408 // No JDWP for you!
409 return;
410 }
411
Elliott Hughes475fc232011-10-25 15:00:35 -0700412 CHECK(gRegistry == NULL);
413 gRegistry = new ObjectRegistry;
414
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700415 // Init JDWP if the debugger is enabled. This may connect out to a
416 // debugger, passively listen for a debugger, or block waiting for a
417 // debugger.
Elliott Hughes376a7a02011-10-24 18:35:55 -0700418 gJdwpState = JDWP::JdwpState::Create(&gJdwpOptions);
419 if (gJdwpState == NULL) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -0800420 // We probably failed because some other process has the port already, which means that
421 // if we don't abort the user is likely to think they're talking to us when they're actually
422 // talking to that other process.
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800423 LOG(FATAL) << "Debugger thread failed to initialize";
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700424 }
425
426 // If a debugger has already attached, send the "welcome" message.
427 // This may cause us to suspend all threads.
Elliott Hughes376a7a02011-10-24 18:35:55 -0700428 if (gJdwpState->IsActive()) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700429 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes376a7a02011-10-24 18:35:55 -0700430 if (!gJdwpState->PostVMStart()) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800431 LOG(WARNING) << "Failed to post 'start' message to debugger";
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700432 }
433 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700434}
435
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700436void Dbg::StopJdwp() {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700437 delete gJdwpState;
Elliott Hughes475fc232011-10-25 15:00:35 -0700438 delete gRegistry;
439 gRegistry = NULL;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700440}
441
Elliott Hughes767a1472011-10-26 18:49:02 -0700442void Dbg::GcDidFinish() {
443 if (gDdmHpifWhen != HPIF_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700444 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes81ff3182012-03-23 20:35:56 -0700445 LOG(DEBUG) << "Sending heap info to DDM";
Elliott Hughes7162ad92011-10-27 14:08:42 -0700446 DdmSendHeapInfo(gDdmHpifWhen);
Elliott Hughes767a1472011-10-26 18:49:02 -0700447 }
448 if (gDdmHpsgWhen != HPSG_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700449 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes81ff3182012-03-23 20:35:56 -0700450 LOG(DEBUG) << "Dumping heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700451 DdmSendHeapSegments(false);
Elliott Hughes767a1472011-10-26 18:49:02 -0700452 }
453 if (gDdmNhsgWhen != HPSG_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700454 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes767a1472011-10-26 18:49:02 -0700455 LOG(DEBUG) << "Dumping native heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700456 DdmSendHeapSegments(true);
Elliott Hughes767a1472011-10-26 18:49:02 -0700457 }
458}
459
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700460void Dbg::SetJdwpAllowed(bool allowed) {
461 gJdwpAllowed = allowed;
462}
463
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700464DebugInvokeReq* Dbg::GetInvokeReq() {
Elliott Hughes475fc232011-10-25 15:00:35 -0700465 return Thread::Current()->GetInvokeReq();
466}
467
468Thread* Dbg::GetDebugThread() {
469 return (gJdwpState != NULL) ? gJdwpState->GetDebugThread() : NULL;
470}
471
472void Dbg::ClearWaitForEventThread() {
473 gJdwpState->ClearWaitForEventThread();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700474}
475
476void Dbg::Connected() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700477 CHECK(!gDebuggerConnected);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800478 VLOG(jdwp) << "JDWP has attached";
Elliott Hughes3bb81562011-10-21 18:52:59 -0700479 gDebuggerConnected = true;
Elliott Hughes86964332012-02-15 19:37:42 -0800480 gDisposed = false;
481}
482
483void Dbg::Disposed() {
484 gDisposed = true;
485}
486
487bool Dbg::IsDisposed() {
488 return gDisposed;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700489}
490
Elliott Hughesc0f09332012-03-26 13:27:06 -0700491static void SetDebuggerUpdatesEnabledCallback(Thread* t, void* user_data) {
492 t->SetDebuggerUpdatesEnabled(*reinterpret_cast<bool*>(user_data));
493}
494
495static void SetDebuggerUpdatesEnabled(bool enabled) {
Ian Rogers50b35e22012-10-04 10:09:15 -0700496 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
Elliott Hughesf8349362012-06-18 15:00:06 -0700497 Runtime::Current()->GetThreadList()->ForEach(SetDebuggerUpdatesEnabledCallback, &enabled);
Elliott Hughesc0f09332012-03-26 13:27:06 -0700498}
499
Elliott Hughesa2155262011-11-16 16:26:58 -0800500void Dbg::GoActive() {
501 // Enable all debugging features, including scans for breakpoints.
502 // This is a no-op if we're already active.
503 // Only called from the JDWP handler thread.
504 if (gDebuggerActive) {
505 return;
506 }
507
508 LOG(INFO) << "Debugger is active";
509
Elliott Hughesc0f09332012-03-26 13:27:06 -0700510 {
511 // TODO: dalvik only warned if there were breakpoints left over. clear in Dbg::Disconnected?
Ian Rogers50b35e22012-10-04 10:09:15 -0700512 MutexLock mu(Thread::Current(), gBreakpointsLock);
Elliott Hughesc0f09332012-03-26 13:27:06 -0700513 CHECK_EQ(gBreakpoints.size(), 0U);
514 }
Elliott Hughesa2155262011-11-16 16:26:58 -0800515
516 gDebuggerActive = true;
Elliott Hughesc0f09332012-03-26 13:27:06 -0700517 SetDebuggerUpdatesEnabled(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700518}
519
520void Dbg::Disconnected() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700521 CHECK(gDebuggerConnected);
522
Elliott Hughesc0f09332012-03-26 13:27:06 -0700523 LOG(INFO) << "Debugger is no longer active";
Elliott Hughes234ab152011-10-26 14:02:26 -0700524
Elliott Hughesc0f09332012-03-26 13:27:06 -0700525 gDebuggerActive = false;
526 SetDebuggerUpdatesEnabled(false);
Elliott Hughes234ab152011-10-26 14:02:26 -0700527
528 gRegistry->Clear();
529 gDebuggerConnected = false;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700530}
531
Elliott Hughesc0f09332012-03-26 13:27:06 -0700532bool Dbg::IsDebuggerActive() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700533 return gDebuggerActive;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700534}
535
Elliott Hughesc0f09332012-03-26 13:27:06 -0700536bool Dbg::IsJdwpConfigured() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700537 return gJdwpConfigured;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700538}
539
540int64_t Dbg::LastDebuggerActivity() {
Elliott Hughesca951522011-12-05 12:01:32 -0800541 return gJdwpState->LastDebuggerActivity();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700542}
543
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700544void Dbg::UndoDebuggerSuspensions() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700545 Runtime::Current()->GetThreadList()->UndoDebuggerSuspensions();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700546}
547
548void Dbg::Exit(int status) {
Elliott Hughes1bba14f2011-12-01 18:00:36 -0800549 exit(status); // This is all dalvik did.
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700550}
551
Elliott Hughesbfe487b2011-10-26 15:48:55 -0700552void Dbg::VisitRoots(Heap::RootVisitor* visitor, void* arg) {
553 if (gRegistry != NULL) {
554 gRegistry->VisitRoots(visitor, arg);
555 }
556}
557
Elliott Hughesc308a5d2012-02-16 17:12:06 -0800558std::string Dbg::GetClassName(JDWP::RefTypeId classId) {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800559 Object* o = gRegistry->Get<Object*>(classId);
Elliott Hughes436e3722012-02-17 20:01:47 -0800560 if (o == NULL) {
561 return "NULL";
562 }
563 if (o == kInvalidObject) {
564 return StringPrintf("invalid object %p", reinterpret_cast<void*>(classId));
565 }
566 if (!o->IsClass()) {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800567 return StringPrintf("non-class %p", o); // This is only used for debugging output anyway.
568 }
Elliott Hughesc308a5d2012-02-16 17:12:06 -0800569 return DescriptorToName(ClassHelper(o->AsClass()).GetDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700570}
571
Elliott Hughes436e3722012-02-17 20:01:47 -0800572JDWP::JdwpError Dbg::GetClassObject(JDWP::RefTypeId id, JDWP::ObjectId& classObjectId) {
573 JDWP::JdwpError status;
574 Class* c = DecodeClass(id, status);
575 if (c == NULL) {
576 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800577 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800578 classObjectId = gRegistry->Add(c);
579 return JDWP::ERR_NONE;
Elliott Hughes86964332012-02-15 19:37:42 -0800580}
581
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800582JDWP::JdwpError Dbg::GetSuperclass(JDWP::RefTypeId id, JDWP::RefTypeId& superclassId) {
583 JDWP::JdwpError status;
584 Class* c = DecodeClass(id, status);
585 if (c == NULL) {
586 return status;
587 }
588 if (c->IsInterface()) {
589 // http://code.google.com/p/android/issues/detail?id=20856
Elliott Hughesa0933622012-04-17 10:46:02 -0700590 superclassId = 0;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800591 } else {
592 superclassId = gRegistry->Add(c->GetSuperClass());
593 }
594 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700595}
596
Elliott Hughes436e3722012-02-17 20:01:47 -0800597JDWP::JdwpError Dbg::GetClassLoader(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) {
Elliott Hughes1bba14f2011-12-01 18:00:36 -0800598 Object* o = gRegistry->Get<Object*>(id);
Elliott Hughes436e3722012-02-17 20:01:47 -0800599 if (o == NULL || o == kInvalidObject) {
600 return JDWP::ERR_INVALID_OBJECT;
601 }
602 expandBufAddObjectId(pReply, gRegistry->Add(o->GetClass()->GetClassLoader()));
603 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700604}
605
Elliott Hughes436e3722012-02-17 20:01:47 -0800606JDWP::JdwpError Dbg::GetModifiers(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) {
607 JDWP::JdwpError status;
608 Class* c = DecodeClass(id, status);
609 if (c == NULL) {
610 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800611 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800612
613 uint32_t access_flags = c->GetAccessFlags() & kAccJavaFlagsMask;
614
615 // Set ACC_SUPER; dex files don't contain this flag, but all classes are supposed to have it set.
616 // Class.getModifiers doesn't return it, but JDWP does, so we set it here.
617 access_flags |= kAccSuper;
618
619 expandBufAdd4BE(pReply, access_flags);
620
621 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700622}
623
Elliott Hughes436e3722012-02-17 20:01:47 -0800624JDWP::JdwpError Dbg::GetReflectedType(JDWP::RefTypeId classId, JDWP::ExpandBuf* pReply) {
625 JDWP::JdwpError status;
626 Class* c = DecodeClass(classId, status);
627 if (c == NULL) {
628 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800629 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800630
631 expandBufAdd1(pReply, c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS);
632 expandBufAddRefTypeId(pReply, classId);
633 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700634}
635
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800636void Dbg::GetClassList(std::vector<JDWP::RefTypeId>& classes) {
Elliott Hughesa2155262011-11-16 16:26:58 -0800637 // Get the complete list of reference classes (i.e. all classes except
638 // the primitive types).
639 // Returns a newly-allocated buffer full of RefTypeId values.
640 struct ClassListCreator {
Elliott Hughesba8eee12012-01-24 20:25:24 -0800641 explicit ClassListCreator(std::vector<JDWP::RefTypeId>& classes) : classes(classes) {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800642 }
643
Elliott Hughesa2155262011-11-16 16:26:58 -0800644 static bool Visit(Class* c, void* arg) {
645 return reinterpret_cast<ClassListCreator*>(arg)->Visit(c);
646 }
647
648 bool Visit(Class* c) {
649 if (!c->IsPrimitive()) {
650 classes.push_back(static_cast<JDWP::RefTypeId>(gRegistry->Add(c)));
651 }
652 return true;
653 }
654
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800655 std::vector<JDWP::RefTypeId>& classes;
Elliott Hughesa2155262011-11-16 16:26:58 -0800656 };
657
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800658 ClassListCreator clc(classes);
Elliott Hughesa2155262011-11-16 16:26:58 -0800659 Runtime::Current()->GetClassLinker()->VisitClasses(ClassListCreator::Visit, &clc);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700660}
661
Elliott Hughes436e3722012-02-17 20:01:47 -0800662JDWP::JdwpError Dbg::GetClassInfo(JDWP::RefTypeId classId, JDWP::JdwpTypeTag* pTypeTag, uint32_t* pStatus, std::string* pDescriptor) {
663 JDWP::JdwpError status;
664 Class* c = DecodeClass(classId, status);
665 if (c == NULL) {
666 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800667 }
668
Elliott Hughesa2155262011-11-16 16:26:58 -0800669 if (c->IsArrayClass()) {
670 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
671 *pTypeTag = JDWP::TT_ARRAY;
672 } else {
673 if (c->IsErroneous()) {
674 *pStatus = JDWP::CS_ERROR;
675 } else {
676 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED | JDWP::CS_INITIALIZED;
677 }
678 *pTypeTag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
679 }
680
681 if (pDescriptor != NULL) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800682 *pDescriptor = ClassHelper(c).GetDescriptor();
Elliott Hughesa2155262011-11-16 16:26:58 -0800683 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800684 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700685}
686
Elliott Hughesc3b77c72011-12-15 20:56:48 -0800687void Dbg::FindLoadedClassBySignature(const char* descriptor, std::vector<JDWP::RefTypeId>& ids) {
Elliott Hughes6fa602d2011-12-02 17:54:25 -0800688 std::vector<Class*> classes;
689 Runtime::Current()->GetClassLinker()->LookupClasses(descriptor, classes);
690 ids.clear();
691 for (size_t i = 0; i < classes.size(); ++i) {
692 ids.push_back(gRegistry->Add(classes[i]));
693 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700694}
695
Elliott Hughes2435a572012-02-17 16:07:41 -0800696JDWP::JdwpError Dbg::GetReferenceType(JDWP::ObjectId objectId, JDWP::ExpandBuf* pReply) {
Elliott Hughes499c5132011-11-17 14:55:11 -0800697 Object* o = gRegistry->Get<Object*>(objectId);
Elliott Hughes436e3722012-02-17 20:01:47 -0800698 if (o == NULL || o == kInvalidObject) {
Elliott Hughes2435a572012-02-17 16:07:41 -0800699 return JDWP::ERR_INVALID_OBJECT;
Elliott Hughes499c5132011-11-17 14:55:11 -0800700 }
Elliott Hughes2435a572012-02-17 16:07:41 -0800701
702 JDWP::JdwpTypeTag type_tag;
703 if (o->GetClass()->IsArrayClass()) {
704 type_tag = JDWP::TT_ARRAY;
705 } else if (o->GetClass()->IsInterface()) {
706 type_tag = JDWP::TT_INTERFACE;
707 } else {
708 type_tag = JDWP::TT_CLASS;
709 }
710 JDWP::RefTypeId type_id = gRegistry->Add(o->GetClass());
711
712 expandBufAdd1(pReply, type_tag);
713 expandBufAddRefTypeId(pReply, type_id);
714
715 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700716}
717
Elliott Hughes436e3722012-02-17 20:01:47 -0800718JDWP::JdwpError Dbg::GetSignature(JDWP::RefTypeId classId, std::string& signature) {
Elliott Hughes1fe7afb2012-02-13 17:23:03 -0800719 JDWP::JdwpError status;
Elliott Hughes436e3722012-02-17 20:01:47 -0800720 Class* c = DecodeClass(classId, status);
Elliott Hughes1fe7afb2012-02-13 17:23:03 -0800721 if (c == NULL) {
722 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800723 }
Elliott Hughes1fe7afb2012-02-13 17:23:03 -0800724 signature = ClassHelper(c).GetDescriptor();
725 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700726}
727
Elliott Hughes436e3722012-02-17 20:01:47 -0800728JDWP::JdwpError Dbg::GetSourceFile(JDWP::RefTypeId classId, std::string& result) {
729 JDWP::JdwpError status;
730 Class* c = DecodeClass(classId, status);
731 if (c == NULL) {
732 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800733 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800734 result = ClassHelper(c).GetSourceFile();
735 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700736}
737
Elliott Hughes546b9862012-06-20 16:06:13 -0700738JDWP::JdwpError Dbg::GetObjectTag(JDWP::ObjectId objectId, uint8_t& tag) {
Elliott Hughes24437992011-11-30 14:49:33 -0800739 Object* o = gRegistry->Get<Object*>(objectId);
Elliott Hughes546b9862012-06-20 16:06:13 -0700740 if (o == kInvalidObject) {
741 return JDWP::ERR_INVALID_OBJECT;
742 }
743 tag = TagFromObject(o);
744 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700745}
746
Elliott Hughesaed4be92011-12-02 16:16:23 -0800747size_t Dbg::GetTagWidth(JDWP::JdwpTag tag) {
Elliott Hughesdbb40792011-11-18 17:05:22 -0800748 switch (tag) {
749 case JDWP::JT_VOID:
750 return 0;
751 case JDWP::JT_BYTE:
752 case JDWP::JT_BOOLEAN:
753 return 1;
754 case JDWP::JT_CHAR:
755 case JDWP::JT_SHORT:
756 return 2;
757 case JDWP::JT_FLOAT:
758 case JDWP::JT_INT:
759 return 4;
760 case JDWP::JT_ARRAY:
761 case JDWP::JT_OBJECT:
762 case JDWP::JT_STRING:
763 case JDWP::JT_THREAD:
764 case JDWP::JT_THREAD_GROUP:
765 case JDWP::JT_CLASS_LOADER:
766 case JDWP::JT_CLASS_OBJECT:
767 return sizeof(JDWP::ObjectId);
768 case JDWP::JT_DOUBLE:
769 case JDWP::JT_LONG:
770 return 8;
771 default:
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800772 LOG(FATAL) << "Unknown tag " << tag;
Elliott Hughesdbb40792011-11-18 17:05:22 -0800773 return -1;
774 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700775}
776
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800777JDWP::JdwpError Dbg::GetArrayLength(JDWP::ObjectId arrayId, int& length) {
778 JDWP::JdwpError status;
779 Array* a = DecodeArray(arrayId, status);
780 if (a == NULL) {
781 return status;
Elliott Hughes24437992011-11-30 14:49:33 -0800782 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800783 length = a->GetLength();
784 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700785}
786
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800787JDWP::JdwpError Dbg::OutputArray(JDWP::ObjectId arrayId, int offset, int count, JDWP::ExpandBuf* pReply) {
788 JDWP::JdwpError status;
789 Array* a = DecodeArray(arrayId, status);
790 if (a == NULL) {
791 return status;
792 }
Elliott Hughes24437992011-11-30 14:49:33 -0800793
794 if (offset < 0 || count < 0 || offset > a->GetLength() || a->GetLength() - offset < count) {
795 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800796 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughes24437992011-11-30 14:49:33 -0800797 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800798 std::string descriptor(ClassHelper(a->GetClass()).GetDescriptor());
Elliott Hughes24437992011-11-30 14:49:33 -0800799 JDWP::JdwpTag tag = BasicTagFromDescriptor(descriptor.c_str() + 1);
800
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800801 expandBufAdd1(pReply, tag);
802 expandBufAdd4BE(pReply, count);
803
Elliott Hughes24437992011-11-30 14:49:33 -0800804 if (IsPrimitiveTag(tag)) {
805 size_t width = GetTagWidth(tag);
Elliott Hughes24437992011-11-30 14:49:33 -0800806 uint8_t* dst = expandBufAddSpace(pReply, count * width);
807 if (width == 8) {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800808 const uint64_t* src8 = reinterpret_cast<uint64_t*>(a->GetRawData(sizeof(uint64_t)));
Elliott Hughes24437992011-11-30 14:49:33 -0800809 for (int i = 0; i < count; ++i) JDWP::Write8BE(&dst, src8[offset + i]);
810 } else if (width == 4) {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800811 const uint32_t* src4 = reinterpret_cast<uint32_t*>(a->GetRawData(sizeof(uint32_t)));
Elliott Hughes24437992011-11-30 14:49:33 -0800812 for (int i = 0; i < count; ++i) JDWP::Write4BE(&dst, src4[offset + i]);
813 } else if (width == 2) {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800814 const uint16_t* src2 = reinterpret_cast<uint16_t*>(a->GetRawData(sizeof(uint16_t)));
Elliott Hughes24437992011-11-30 14:49:33 -0800815 for (int i = 0; i < count; ++i) JDWP::Write2BE(&dst, src2[offset + i]);
816 } else {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800817 const uint8_t* src = reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint8_t)));
Elliott Hughes24437992011-11-30 14:49:33 -0800818 memcpy(dst, &src[offset * width], count * width);
819 }
820 } else {
821 ObjectArray<Object>* oa = a->AsObjectArray<Object>();
822 for (int i = 0; i < count; ++i) {
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800823 Object* element = oa->Get(offset + i);
Elliott Hughes24437992011-11-30 14:49:33 -0800824 JDWP::JdwpTag specific_tag = (element != NULL) ? TagFromObject(element) : tag;
825 expandBufAdd1(pReply, specific_tag);
826 expandBufAddObjectId(pReply, gRegistry->Add(element));
827 }
828 }
829
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800830 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700831}
832
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700833JDWP::JdwpError Dbg::SetArrayElements(JDWP::ObjectId arrayId, int offset, int count,
834 const uint8_t* src)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700835 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800836 JDWP::JdwpError status;
837 Array* a = DecodeArray(arrayId, status);
838 if (a == NULL) {
839 return status;
840 }
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800841
842 if (offset < 0 || count < 0 || offset > a->GetLength() || a->GetLength() - offset < count) {
843 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800844 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800845 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800846 std::string descriptor(ClassHelper(a->GetClass()).GetDescriptor());
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800847 JDWP::JdwpTag tag = BasicTagFromDescriptor(descriptor.c_str() + 1);
848
849 if (IsPrimitiveTag(tag)) {
850 size_t width = GetTagWidth(tag);
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800851 if (width == 8) {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800852 uint8_t* dst = &(reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint64_t)))[offset * width]);
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800853 for (int i = 0; i < count; ++i) {
854 // Handle potentially non-aligned memory access one byte at a time for ARM's benefit.
855 uint64_t value;
856 for (size_t j = 0; j < sizeof(uint64_t); ++j) reinterpret_cast<uint8_t*>(&value)[j] = src[j];
857 src += sizeof(uint64_t);
858 JDWP::Write8BE(&dst, value);
859 }
860 } else if (width == 4) {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800861 uint8_t* dst = &(reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint32_t)))[offset * width]);
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800862 const uint32_t* src4 = reinterpret_cast<const uint32_t*>(src);
863 for (int i = 0; i < count; ++i) JDWP::Write4BE(&dst, src4[i]);
864 } else if (width == 2) {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800865 uint8_t* dst = &(reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint16_t)))[offset * width]);
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800866 const uint16_t* src2 = reinterpret_cast<const uint16_t*>(src);
867 for (int i = 0; i < count; ++i) JDWP::Write2BE(&dst, src2[i]);
868 } else {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800869 uint8_t* dst = &(reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint8_t)))[offset * width]);
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800870 memcpy(&dst[offset * width], src, count * width);
871 }
872 } else {
873 ObjectArray<Object>* oa = a->AsObjectArray<Object>();
874 for (int i = 0; i < count; ++i) {
875 JDWP::ObjectId id = JDWP::ReadObjectId(&src);
Elliott Hughes436e3722012-02-17 20:01:47 -0800876 Object* o = gRegistry->Get<Object*>(id);
877 if (o == kInvalidObject) {
878 return JDWP::ERR_INVALID_OBJECT;
879 }
880 oa->Set(offset + i, o);
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800881 }
882 }
883
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800884 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700885}
886
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800887JDWP::ObjectId Dbg::CreateString(const std::string& str) {
Ian Rogers50b35e22012-10-04 10:09:15 -0700888 return gRegistry->Add(String::AllocFromModifiedUtf8(Thread::Current(), str.c_str()));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700889}
890
Elliott Hughes436e3722012-02-17 20:01:47 -0800891JDWP::JdwpError Dbg::CreateObject(JDWP::RefTypeId classId, JDWP::ObjectId& new_object) {
892 JDWP::JdwpError status;
893 Class* c = DecodeClass(classId, status);
894 if (c == NULL) {
895 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800896 }
Ian Rogers50b35e22012-10-04 10:09:15 -0700897 new_object = gRegistry->Add(c->AllocObject(Thread::Current()));
Elliott Hughes436e3722012-02-17 20:01:47 -0800898 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700899}
900
Elliott Hughesbf13d362011-12-08 15:51:37 -0800901/*
902 * Used by Eclipse's "Display" view to evaluate "new byte[5]" to get "(byte[]) [0, 0, 0, 0, 0]".
903 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700904JDWP::JdwpError Dbg::CreateArrayObject(JDWP::RefTypeId arrayClassId, uint32_t length,
905 JDWP::ObjectId& new_array) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800906 JDWP::JdwpError status;
907 Class* c = DecodeClass(arrayClassId, status);
908 if (c == NULL) {
909 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800910 }
Ian Rogers50b35e22012-10-04 10:09:15 -0700911 new_array = gRegistry->Add(Array::Alloc(Thread::Current(), c, length));
Elliott Hughes436e3722012-02-17 20:01:47 -0800912 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700913}
914
915bool Dbg::MatchType(JDWP::RefTypeId instClassId, JDWP::RefTypeId classId) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800916 JDWP::JdwpError status;
917 Class* c1 = DecodeClass(instClassId, status);
Elliott Hughesa656a0f2012-02-21 18:03:44 -0800918 CHECK(c1 != NULL);
Elliott Hughes436e3722012-02-17 20:01:47 -0800919 Class* c2 = DecodeClass(classId, status);
Elliott Hughesa656a0f2012-02-21 18:03:44 -0800920 CHECK(c2 != NULL);
921 return c1->IsAssignableFrom(c2);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700922}
923
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700924static JDWP::FieldId ToFieldId(const Field* f)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700925 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes03181a82011-11-17 17:22:21 -0800926#ifdef MOVING_GARBAGE_COLLECTOR
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700927 UNIMPLEMENTED(FATAL);
Elliott Hughes03181a82011-11-17 17:22:21 -0800928#else
929 return static_cast<JDWP::FieldId>(reinterpret_cast<uintptr_t>(f));
930#endif
931}
932
Mathieu Chartier66f19252012-09-18 08:57:04 -0700933static JDWP::MethodId ToMethodId(const AbstractMethod* m)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700934 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes03181a82011-11-17 17:22:21 -0800935#ifdef MOVING_GARBAGE_COLLECTOR
936 UNIMPLEMENTED(FATAL);
937#else
938 return static_cast<JDWP::MethodId>(reinterpret_cast<uintptr_t>(m));
939#endif
940}
941
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700942static Field* FromFieldId(JDWP::FieldId fid)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700943 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesaed4be92011-12-02 16:16:23 -0800944#ifdef MOVING_GARBAGE_COLLECTOR
945 UNIMPLEMENTED(FATAL);
946#else
947 return reinterpret_cast<Field*>(static_cast<uintptr_t>(fid));
948#endif
949}
950
Mathieu Chartier66f19252012-09-18 08:57:04 -0700951static AbstractMethod* FromMethodId(JDWP::MethodId mid)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700952 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes03181a82011-11-17 17:22:21 -0800953#ifdef MOVING_GARBAGE_COLLECTOR
954 UNIMPLEMENTED(FATAL);
955#else
Mathieu Chartier66f19252012-09-18 08:57:04 -0700956 return reinterpret_cast<AbstractMethod*>(static_cast<uintptr_t>(mid));
Elliott Hughes03181a82011-11-17 17:22:21 -0800957#endif
958}
959
Mathieu Chartier66f19252012-09-18 08:57:04 -0700960static void SetLocation(JDWP::JdwpLocation& location, AbstractMethod* m, uint32_t dex_pc)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700961 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -0800962 if (m == NULL) {
963 memset(&location, 0, sizeof(location));
964 } else {
965 Class* c = m->GetDeclaringClass();
Elliott Hughes74847412012-06-20 18:10:21 -0700966 location.type_tag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
967 location.class_id = gRegistry->Add(c);
968 location.method_id = ToMethodId(m);
Ian Rogers0399dde2012-06-06 17:09:28 -0700969 location.dex_pc = dex_pc;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -0800970 }
Elliott Hughesd07986f2011-12-06 18:27:45 -0800971}
972
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700973std::string Dbg::GetMethodName(JDWP::RefTypeId, JDWP::MethodId methodId)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700974 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier66f19252012-09-18 08:57:04 -0700975 AbstractMethod* m = FromMethodId(methodId);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800976 return MethodHelper(m).GetName();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700977}
978
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800979/*
980 * Augment the access flags for synthetic methods and fields by setting
981 * the (as described by the spec) "0xf0000000 bit". Also, strip out any
982 * flags not specified by the Java programming language.
983 */
984static uint32_t MangleAccessFlags(uint32_t accessFlags) {
985 accessFlags &= kAccJavaFlagsMask;
986 if ((accessFlags & kAccSynthetic) != 0) {
987 accessFlags |= 0xf0000000;
988 }
989 return accessFlags;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700990}
991
Elliott Hughesdbb40792011-11-18 17:05:22 -0800992static const uint16_t kEclipseWorkaroundSlot = 1000;
993
994/*
995 * Eclipse appears to expect that the "this" reference is in slot zero.
996 * If it's not, the "variables" display will show two copies of "this",
997 * possibly because it gets "this" from SF.ThisObject and then displays
998 * all locals with nonzero slot numbers.
999 *
1000 * So, we remap the item in slot 0 to 1000, and remap "this" to zero. On
1001 * SF.GetValues / SF.SetValues we map them back.
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001002 *
1003 * TODO: jdb uses the value to determine whether a variable is a local or an argument,
1004 * by checking whether it's less than the number of arguments. To make that work, we'd
1005 * have to "mangle" all the arguments to come first, not just the implicit argument 'this'.
Elliott Hughesdbb40792011-11-18 17:05:22 -08001006 */
1007static uint16_t MangleSlot(uint16_t slot, const char* name) {
1008 uint16_t newSlot = slot;
1009 if (strcmp(name, "this") == 0) {
1010 newSlot = 0;
1011 } else if (slot == 0) {
1012 newSlot = kEclipseWorkaroundSlot;
1013 }
1014 return newSlot;
1015}
1016
Mathieu Chartier66f19252012-09-18 08:57:04 -07001017static uint16_t DemangleSlot(uint16_t slot, AbstractMethod* m)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001018 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001019 if (slot == kEclipseWorkaroundSlot) {
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001020 return 0;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001021 } else if (slot == 0) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001022 const DexFile::CodeItem* code_item = MethodHelper(m).GetCodeItem();
Elliott Hughescaf76542012-06-28 16:08:22 -07001023 CHECK(code_item != NULL) << PrettyMethod(m);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001024 return code_item->registers_size_ - code_item->ins_size_;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001025 }
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001026 return slot;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001027}
1028
Elliott Hughes436e3722012-02-17 20:01:47 -08001029JDWP::JdwpError Dbg::OutputDeclaredFields(JDWP::RefTypeId classId, bool with_generic, JDWP::ExpandBuf* pReply) {
1030 JDWP::JdwpError status;
1031 Class* c = DecodeClass(classId, status);
1032 if (c == NULL) {
1033 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001034 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001035
1036 size_t instance_field_count = c->NumInstanceFields();
1037 size_t static_field_count = c->NumStaticFields();
1038
1039 expandBufAdd4BE(pReply, instance_field_count + static_field_count);
1040
1041 for (size_t i = 0; i < instance_field_count + static_field_count; ++i) {
1042 Field* f = (i < instance_field_count) ? c->GetInstanceField(i) : c->GetStaticField(i - instance_field_count);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001043 FieldHelper fh(f);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001044 expandBufAddFieldId(pReply, ToFieldId(f));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001045 expandBufAddUtf8String(pReply, fh.GetName());
1046 expandBufAddUtf8String(pReply, fh.GetTypeDescriptor());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001047 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001048 static const char genericSignature[1] = "";
1049 expandBufAddUtf8String(pReply, genericSignature);
1050 }
1051 expandBufAdd4BE(pReply, MangleAccessFlags(f->GetAccessFlags()));
1052 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001053 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001054}
1055
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001056JDWP::JdwpError Dbg::OutputDeclaredMethods(JDWP::RefTypeId classId, bool with_generic,
1057 JDWP::ExpandBuf* pReply) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001058 JDWP::JdwpError status;
1059 Class* c = DecodeClass(classId, status);
1060 if (c == NULL) {
1061 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001062 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001063
1064 size_t direct_method_count = c->NumDirectMethods();
1065 size_t virtual_method_count = c->NumVirtualMethods();
1066
1067 expandBufAdd4BE(pReply, direct_method_count + virtual_method_count);
1068
1069 for (size_t i = 0; i < direct_method_count + virtual_method_count; ++i) {
Mathieu Chartier66f19252012-09-18 08:57:04 -07001070 AbstractMethod* m = (i < direct_method_count) ? c->GetDirectMethod(i) : c->GetVirtualMethod(i - direct_method_count);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001071 MethodHelper mh(m);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001072 expandBufAddMethodId(pReply, ToMethodId(m));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001073 expandBufAddUtf8String(pReply, mh.GetName());
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001074 expandBufAddUtf8String(pReply, mh.GetSignature());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001075 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001076 static const char genericSignature[1] = "";
1077 expandBufAddUtf8String(pReply, genericSignature);
1078 }
1079 expandBufAdd4BE(pReply, MangleAccessFlags(m->GetAccessFlags()));
1080 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001081 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001082}
1083
Elliott Hughes436e3722012-02-17 20:01:47 -08001084JDWP::JdwpError Dbg::OutputDeclaredInterfaces(JDWP::RefTypeId classId, JDWP::ExpandBuf* pReply) {
1085 JDWP::JdwpError status;
1086 Class* c = DecodeClass(classId, status);
1087 if (c == NULL) {
1088 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001089 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001090
1091 ClassHelper kh(c);
Ian Rogersd24e2642012-06-06 21:21:43 -07001092 size_t interface_count = kh.NumDirectInterfaces();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001093 expandBufAdd4BE(pReply, interface_count);
1094 for (size_t i = 0; i < interface_count; ++i) {
Ian Rogersd24e2642012-06-06 21:21:43 -07001095 expandBufAddRefTypeId(pReply, gRegistry->Add(kh.GetDirectInterface(i)));
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001096 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001097 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001098}
1099
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001100void Dbg::OutputLineTable(JDWP::RefTypeId, JDWP::MethodId methodId, JDWP::ExpandBuf* pReply)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001101 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001102 struct DebugCallbackContext {
1103 int numItems;
1104 JDWP::ExpandBuf* pReply;
1105
Elliott Hughes2435a572012-02-17 16:07:41 -08001106 static bool Callback(void* context, uint32_t address, uint32_t line_number) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001107 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
1108 expandBufAdd8BE(pContext->pReply, address);
Elliott Hughes2435a572012-02-17 16:07:41 -08001109 expandBufAdd4BE(pContext->pReply, line_number);
Elliott Hughes03181a82011-11-17 17:22:21 -08001110 pContext->numItems++;
1111 return true;
1112 }
1113 };
Mathieu Chartier66f19252012-09-18 08:57:04 -07001114 AbstractMethod* m = FromMethodId(methodId);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001115 MethodHelper mh(m);
Elliott Hughes03181a82011-11-17 17:22:21 -08001116 uint64_t start, end;
1117 if (m->IsNative()) {
1118 start = -1;
1119 end = -1;
1120 } else {
1121 start = 0;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001122 // TODO: what are the units supposed to be? *2?
1123 end = mh.GetCodeItem()->insns_size_in_code_units_;
Elliott Hughes03181a82011-11-17 17:22:21 -08001124 }
1125
1126 expandBufAdd8BE(pReply, start);
1127 expandBufAdd8BE(pReply, end);
1128
1129 // Add numLines later
1130 size_t numLinesOffset = expandBufGetLength(pReply);
1131 expandBufAdd4BE(pReply, 0);
1132
1133 DebugCallbackContext context;
1134 context.numItems = 0;
1135 context.pReply = pReply;
1136
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001137 mh.GetDexFile().DecodeDebugInfo(mh.GetCodeItem(), m->IsStatic(), m->GetDexMethodIndex(),
1138 DebugCallbackContext::Callback, NULL, &context);
Elliott Hughes03181a82011-11-17 17:22:21 -08001139
1140 JDWP::Set4BE(expandBufGetBuffer(pReply) + numLinesOffset, context.numItems);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001141}
1142
Elliott Hughes436e3722012-02-17 20:01:47 -08001143void Dbg::OutputVariableTable(JDWP::RefTypeId, JDWP::MethodId methodId, bool with_generic, JDWP::ExpandBuf* pReply) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001144 struct DebugCallbackContext {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001145 JDWP::ExpandBuf* pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001146 size_t variable_count;
1147 bool with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001148
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001149 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 -08001150 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
1151
Elliott Hughesad3da692012-02-24 16:51:35 -08001152 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 -08001153
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001154 slot = MangleSlot(slot, name);
1155
Elliott Hughesdbb40792011-11-18 17:05:22 -08001156 expandBufAdd8BE(pContext->pReply, startAddress);
1157 expandBufAddUtf8String(pContext->pReply, name);
1158 expandBufAddUtf8String(pContext->pReply, descriptor);
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001159 if (pContext->with_generic) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001160 expandBufAddUtf8String(pContext->pReply, signature);
1161 }
1162 expandBufAdd4BE(pContext->pReply, endAddress - startAddress);
1163 expandBufAdd4BE(pContext->pReply, slot);
1164
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001165 ++pContext->variable_count;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001166 }
1167 };
Mathieu Chartier66f19252012-09-18 08:57:04 -07001168 AbstractMethod* m = FromMethodId(methodId);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001169 MethodHelper mh(m);
1170 const DexFile::CodeItem* code_item = mh.GetCodeItem();
Elliott Hughesdbb40792011-11-18 17:05:22 -08001171
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001172 // arg_count considers doubles and longs to take 2 units.
1173 // variable_count considers everything to take 1 unit.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001174 std::string shorty(mh.GetShorty());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001175 expandBufAdd4BE(pReply, m->NumArgRegisters(shorty));
Elliott Hughesdbb40792011-11-18 17:05:22 -08001176
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001177 // We don't know the total number of variables yet, so leave a blank and update it later.
1178 size_t variable_count_offset = expandBufGetLength(pReply);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001179 expandBufAdd4BE(pReply, 0);
1180
1181 DebugCallbackContext context;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001182 context.pReply = pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001183 context.variable_count = 0;
1184 context.with_generic = with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001185
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001186 mh.GetDexFile().DecodeDebugInfo(code_item, m->IsStatic(), m->GetDexMethodIndex(), NULL,
1187 DebugCallbackContext::Callback, &context);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001188
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001189 JDWP::Set4BE(expandBufGetBuffer(pReply) + variable_count_offset, context.variable_count);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001190}
1191
Elliott Hughesaed4be92011-12-02 16:16:23 -08001192JDWP::JdwpTag Dbg::GetFieldBasicTag(JDWP::FieldId fieldId) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001193 return BasicTagFromDescriptor(FieldHelper(FromFieldId(fieldId)).GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001194}
1195
Elliott Hughesaed4be92011-12-02 16:16:23 -08001196JDWP::JdwpTag Dbg::GetStaticFieldBasicTag(JDWP::FieldId fieldId) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001197 return BasicTagFromDescriptor(FieldHelper(FromFieldId(fieldId)).GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001198}
1199
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001200static JDWP::JdwpError GetFieldValueImpl(JDWP::RefTypeId refTypeId, JDWP::ObjectId objectId,
1201 JDWP::FieldId fieldId, JDWP::ExpandBuf* pReply,
1202 bool is_static)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001203 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes0cf74332012-02-23 23:14:00 -08001204 JDWP::JdwpError status;
1205 Class* c = DecodeClass(refTypeId, status);
1206 if (refTypeId != 0 && c == NULL) {
1207 return status;
1208 }
1209
Elliott Hughesaed4be92011-12-02 16:16:23 -08001210 Object* o = gRegistry->Get<Object*>(objectId);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001211 if ((!is_static && o == NULL) || o == kInvalidObject) {
1212 return JDWP::ERR_INVALID_OBJECT;
1213 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001214 Field* f = FromFieldId(fieldId);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001215
1216 Class* receiver_class = c;
1217 if (receiver_class == NULL && o != NULL) {
1218 receiver_class = o->GetClass();
1219 }
1220 // TODO: should we give up now if receiver_class is NULL?
1221 if (receiver_class != NULL && !f->GetDeclaringClass()->IsAssignableFrom(receiver_class)) {
1222 LOG(INFO) << "ERR_INVALID_FIELDID: " << PrettyField(f) << " " << PrettyClass(receiver_class);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001223 return JDWP::ERR_INVALID_FIELDID;
1224 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001225
Elliott Hughes0cf74332012-02-23 23:14:00 -08001226 // The RI only enforces the static/non-static mismatch in one direction.
1227 // TODO: should we change the tests and check both?
1228 if (is_static) {
1229 if (!f->IsStatic()) {
1230 return JDWP::ERR_INVALID_FIELDID;
1231 }
1232 } else {
1233 if (f->IsStatic()) {
1234 LOG(WARNING) << "Ignoring non-NULL receiver for ObjectReference.SetValues on static field " << PrettyField(f);
1235 o = NULL;
1236 }
1237 }
1238
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001239 JDWP::JdwpTag tag = BasicTagFromDescriptor(FieldHelper(f).GetTypeDescriptor());
Elliott Hughesaed4be92011-12-02 16:16:23 -08001240
1241 if (IsPrimitiveTag(tag)) {
1242 expandBufAdd1(pReply, tag);
1243 if (tag == JDWP::JT_BOOLEAN || tag == JDWP::JT_BYTE) {
1244 expandBufAdd1(pReply, f->Get32(o));
1245 } else if (tag == JDWP::JT_CHAR || tag == JDWP::JT_SHORT) {
1246 expandBufAdd2BE(pReply, f->Get32(o));
1247 } else if (tag == JDWP::JT_FLOAT || tag == JDWP::JT_INT) {
1248 expandBufAdd4BE(pReply, f->Get32(o));
1249 } else if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
1250 expandBufAdd8BE(pReply, f->Get64(o));
1251 } else {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001252 LOG(FATAL) << "Unknown tag: " << tag;
Elliott Hughesaed4be92011-12-02 16:16:23 -08001253 }
1254 } else {
1255 Object* value = f->GetObject(o);
1256 expandBufAdd1(pReply, TagFromObject(value));
1257 expandBufAddObjectId(pReply, gRegistry->Add(value));
1258 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001259 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001260}
1261
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001262JDWP::JdwpError Dbg::GetFieldValue(JDWP::ObjectId objectId, JDWP::FieldId fieldId,
1263 JDWP::ExpandBuf* pReply) {
Elliott Hughes0cf74332012-02-23 23:14:00 -08001264 return GetFieldValueImpl(0, objectId, fieldId, pReply, false);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001265}
1266
Elliott Hughes0cf74332012-02-23 23:14:00 -08001267JDWP::JdwpError Dbg::GetStaticFieldValue(JDWP::RefTypeId refTypeId, JDWP::FieldId fieldId, JDWP::ExpandBuf* pReply) {
1268 return GetFieldValueImpl(refTypeId, 0, fieldId, pReply, true);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001269}
1270
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001271static JDWP::JdwpError SetFieldValueImpl(JDWP::ObjectId objectId, JDWP::FieldId fieldId,
1272 uint64_t value, int width, bool is_static)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001273 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesaed4be92011-12-02 16:16:23 -08001274 Object* o = gRegistry->Get<Object*>(objectId);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001275 if ((!is_static && o == NULL) || o == kInvalidObject) {
1276 return JDWP::ERR_INVALID_OBJECT;
1277 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001278 Field* f = FromFieldId(fieldId);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001279
1280 // The RI only enforces the static/non-static mismatch in one direction.
1281 // TODO: should we change the tests and check both?
1282 if (is_static) {
1283 if (!f->IsStatic()) {
1284 return JDWP::ERR_INVALID_FIELDID;
1285 }
1286 } else {
1287 if (f->IsStatic()) {
1288 LOG(WARNING) << "Ignoring non-NULL receiver for ObjectReference.SetValues on static field " << PrettyField(f);
1289 o = NULL;
1290 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001291 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001292
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001293 JDWP::JdwpTag tag = BasicTagFromDescriptor(FieldHelper(f).GetTypeDescriptor());
Elliott Hughesaed4be92011-12-02 16:16:23 -08001294
1295 if (IsPrimitiveTag(tag)) {
1296 if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001297 CHECK_EQ(width, 8);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001298 f->Set64(o, value);
1299 } else {
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001300 CHECK_LE(width, 4);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001301 f->Set32(o, value);
1302 }
1303 } else {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001304 Object* v = gRegistry->Get<Object*>(value);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001305 if (v == kInvalidObject) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001306 return JDWP::ERR_INVALID_OBJECT;
1307 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001308 if (v != NULL) {
1309 Class* field_type = FieldHelper(f).GetType();
1310 if (!field_type->IsAssignableFrom(v->GetClass())) {
1311 return JDWP::ERR_INVALID_OBJECT;
1312 }
1313 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001314 f->SetObject(o, v);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001315 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001316
1317 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001318}
1319
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001320JDWP::JdwpError Dbg::SetFieldValue(JDWP::ObjectId objectId, JDWP::FieldId fieldId, uint64_t value,
1321 int width) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001322 return SetFieldValueImpl(objectId, fieldId, value, width, false);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001323}
1324
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001325JDWP::JdwpError Dbg::SetStaticFieldValue(JDWP::FieldId fieldId, uint64_t value, int width) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001326 return SetFieldValueImpl(0, fieldId, value, width, true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001327}
1328
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001329std::string Dbg::StringToUtf8(JDWP::ObjectId strId) {
1330 String* s = gRegistry->Get<String*>(strId);
1331 return s->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001332}
1333
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001334bool Dbg::GetThreadName(JDWP::ObjectId threadId, std::string& name) {
Ian Rogers50b35e22012-10-04 10:09:15 -07001335 Thread* self = Thread::Current();
1336 MutexLock mu(self, *Locks::thread_list_lock_);
1337 ScopedObjectAccessUnchecked soa(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001338 Thread* thread = DecodeThread(soa, threadId);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001339 if (thread == NULL) {
1340 return false;
1341 }
Elliott Hughesffb465f2012-03-01 18:46:05 -08001342 thread->GetThreadName(name);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001343 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001344}
1345
Elliott Hughes2435a572012-02-17 16:07:41 -08001346JDWP::JdwpError Dbg::GetThreadGroup(JDWP::ObjectId threadId, JDWP::ExpandBuf* pReply) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001347 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes499c5132011-11-17 14:55:11 -08001348 Object* thread = gRegistry->Get<Object*>(threadId);
Elliott Hughes436e3722012-02-17 20:01:47 -08001349 if (thread == kInvalidObject) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001350 return JDWP::ERR_INVALID_OBJECT;
1351 }
1352
1353 // Okay, so it's an object, but is it actually a thread?
Ian Rogers50b35e22012-10-04 10:09:15 -07001354 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001355 if (DecodeThread(soa, threadId) == NULL) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001356 return JDWP::ERR_INVALID_THREAD;
1357 }
Elliott Hughes499c5132011-11-17 14:55:11 -08001358
1359 Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/Thread;");
1360 CHECK(c != NULL);
1361 Field* f = c->FindInstanceField("group", "Ljava/lang/ThreadGroup;");
1362 CHECK(f != NULL);
1363 Object* group = f->GetObject(thread);
1364 CHECK(group != NULL);
Elliott Hughes2435a572012-02-17 16:07:41 -08001365 JDWP::ObjectId thread_group_id = gRegistry->Add(group);
1366
1367 expandBufAddObjectId(pReply, thread_group_id);
1368 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001369}
1370
Elliott Hughes499c5132011-11-17 14:55:11 -08001371std::string Dbg::GetThreadGroupName(JDWP::ObjectId threadGroupId) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001372 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes499c5132011-11-17 14:55:11 -08001373 Object* thread_group = gRegistry->Get<Object*>(threadGroupId);
1374 CHECK(thread_group != NULL);
1375
1376 Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/ThreadGroup;");
1377 CHECK(c != NULL);
1378 Field* f = c->FindInstanceField("name", "Ljava/lang/String;");
1379 CHECK(f != NULL);
1380 String* s = reinterpret_cast<String*>(f->GetObject(thread_group));
1381 return s->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001382}
1383
1384JDWP::ObjectId Dbg::GetThreadGroupParent(JDWP::ObjectId threadGroupId) {
Elliott Hughes4e235312011-12-02 11:34:15 -08001385 Object* thread_group = gRegistry->Get<Object*>(threadGroupId);
1386 CHECK(thread_group != NULL);
1387
1388 Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/ThreadGroup;");
1389 CHECK(c != NULL);
1390 Field* f = c->FindInstanceField("parent", "Ljava/lang/ThreadGroup;");
1391 CHECK(f != NULL);
1392 Object* parent = f->GetObject(thread_group);
1393 return gRegistry->Add(parent);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001394}
1395
1396JDWP::ObjectId Dbg::GetSystemThreadGroupId() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001397 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers365c1022012-06-22 15:05:28 -07001398 Object* group =
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001399 soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_systemThreadGroup)->GetObject(NULL);
Ian Rogers365c1022012-06-22 15:05:28 -07001400 return gRegistry->Add(group);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001401}
1402
1403JDWP::ObjectId Dbg::GetMainThreadGroupId() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001404 ScopedObjectAccess soa(Thread::Current());
Ian Rogers365c1022012-06-22 15:05:28 -07001405 Object* group =
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001406 soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_mainThreadGroup)->GetObject(NULL);
Ian Rogers365c1022012-06-22 15:05:28 -07001407 return gRegistry->Add(group);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001408}
1409
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001410bool Dbg::GetThreadStatus(JDWP::ObjectId threadId, JDWP::JdwpThreadStatus* pThreadStatus, JDWP::JdwpSuspendStatus* pSuspendStatus) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001411 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes499c5132011-11-17 14:55:11 -08001412
Ian Rogers50b35e22012-10-04 10:09:15 -07001413 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001414 Thread* thread = DecodeThread(soa, threadId);
Elliott Hughes499c5132011-11-17 14:55:11 -08001415 if (thread == NULL) {
1416 return false;
1417 }
1418
Ian Rogers50b35e22012-10-04 10:09:15 -07001419 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001420
Elliott Hughes3ce4b262012-02-24 11:24:02 -08001421 // TODO: if we're in Thread.sleep(long), we should return TS_SLEEPING,
1422 // even if it's implemented using Object.wait(long).
Elliott Hughes499c5132011-11-17 14:55:11 -08001423 switch (thread->GetState()) {
Elliott Hughes34e06962012-04-09 13:55:55 -07001424 case kTerminated: *pThreadStatus = JDWP::TS_ZOMBIE; break;
1425 case kRunnable: *pThreadStatus = JDWP::TS_RUNNING; break;
1426 case kTimedWaiting: *pThreadStatus = JDWP::TS_WAIT; break;
1427 case kBlocked: *pThreadStatus = JDWP::TS_MONITOR; break;
1428 case kWaiting: *pThreadStatus = JDWP::TS_WAIT; break;
1429 case kStarting: *pThreadStatus = JDWP::TS_ZOMBIE; break;
1430 case kNative: *pThreadStatus = JDWP::TS_RUNNING; break;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001431 case kWaitingForGcToComplete: // Fall-through.
1432 case kWaitingPerformingGc: // Fall-through.
1433 case kWaitingForDebuggerSend: // Fall-through.
1434 case kWaitingForDebuggerToAttach: // Fall-through.
1435 case kWaitingInMainDebuggerLoop: // Fall-through.
1436 case kWaitingForDebuggerSuspension: // Fall-through.
1437 case kWaitingForJniOnLoad: // Fall-through.
1438 case kWaitingForSignalCatcherOutput: // Fall-through.
1439 case kWaitingInMainSignalCatcherLoop:
1440 *pThreadStatus = JDWP::TS_WAIT; break;
Elliott Hughes34e06962012-04-09 13:55:55 -07001441 case kSuspended: *pThreadStatus = JDWP::TS_RUNNING; break;
Elliott Hughescf2b2d42012-03-27 17:11:42 -07001442 // Don't add a 'default' here so the compiler can spot incompatible enum changes.
Elliott Hughes499c5132011-11-17 14:55:11 -08001443 }
1444
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001445 *pSuspendStatus = (thread->IsSuspended() ? JDWP::SUSPEND_STATUS_SUSPENDED : JDWP::SUSPEND_STATUS_NOT_SUSPENDED);
Elliott Hughes499c5132011-11-17 14:55:11 -08001446
1447 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001448}
1449
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001450JDWP::JdwpError Dbg::GetThreadDebugSuspendCount(JDWP::ObjectId threadId, JDWP::ExpandBuf* pReply) {
1451 ScopedObjectAccess soa(Thread::Current());
1452
Ian Rogers50b35e22012-10-04 10:09:15 -07001453 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001454 Thread* thread = DecodeThread(soa, threadId);
Elliott Hughes2435a572012-02-17 16:07:41 -08001455 if (thread == NULL) {
1456 return JDWP::ERR_INVALID_THREAD;
1457 }
Ian Rogers50b35e22012-10-04 10:09:15 -07001458 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001459 expandBufAdd4BE(pReply, thread->GetDebugSuspendCount());
Elliott Hughes2435a572012-02-17 16:07:41 -08001460 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001461}
1462
1463bool Dbg::ThreadExists(JDWP::ObjectId threadId) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001464 ScopedObjectAccess soa(Thread::Current());
Ian Rogers50b35e22012-10-04 10:09:15 -07001465 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001466 return DecodeThread(soa, threadId) != NULL;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001467}
1468
1469bool Dbg::IsSuspended(JDWP::ObjectId threadId) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001470 ScopedObjectAccess soa(Thread::Current());
Ian Rogers50b35e22012-10-04 10:09:15 -07001471 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001472 Thread* thread = DecodeThread(soa, threadId);
1473 CHECK(thread != NULL);
Ian Rogers50b35e22012-10-04 10:09:15 -07001474 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001475 return thread->IsSuspended();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001476}
1477
Elliott Hughescaf76542012-06-28 16:08:22 -07001478void Dbg::GetThreads(JDWP::ObjectId thread_group_id, std::vector<JDWP::ObjectId>& thread_ids) {
Ian Rogers365c1022012-06-22 15:05:28 -07001479 class ThreadListVisitor {
1480 public:
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07001481 ThreadListVisitor(const ScopedObjectAccessUnchecked& soa, Object* thread_group,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001482 std::vector<JDWP::ObjectId>& thread_ids)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001483 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07001484 : soa_(soa), thread_group_(thread_group), thread_ids_(thread_ids) {}
Ian Rogers365c1022012-06-22 15:05:28 -07001485
Elliott Hughesa2155262011-11-16 16:26:58 -08001486 static void Visit(Thread* t, void* arg) {
1487 reinterpret_cast<ThreadListVisitor*>(arg)->Visit(t);
1488 }
1489
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001490 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1491 // annotalysis.
1492 void Visit(Thread* t) NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughesa2155262011-11-16 16:26:58 -08001493 if (t == Dbg::GetDebugThread()) {
1494 // Skip the JDWP thread. Some debuggers get bent out of shape when they can't suspend and
1495 // query all threads, so it's easier if we just don't tell them about this thread.
1496 return;
1497 }
Ian Rogers120f1c72012-09-28 17:17:10 -07001498 bool should_add = (thread_group_ == NULL);
1499 Object* peer = soa_.Decode<Object*>(t->GetPeer());
1500 if (!should_add) {
1501 Object* group = soa_.DecodeField(WellKnownClasses::java_lang_Thread_group)->GetObject(peer);
1502 should_add = (group == thread_group_);
1503 }
1504 if (should_add) {
1505 thread_ids_.push_back(gRegistry->Add(peer));
Elliott Hughesa2155262011-11-16 16:26:58 -08001506 }
1507 }
1508
Ian Rogers365c1022012-06-22 15:05:28 -07001509 private:
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07001510 const ScopedObjectAccessUnchecked& soa_;
Ian Rogers365c1022012-06-22 15:05:28 -07001511 Object* const thread_group_;
Elliott Hughescaf76542012-06-28 16:08:22 -07001512 std::vector<JDWP::ObjectId>& thread_ids_;
Elliott Hughesa2155262011-11-16 16:26:58 -08001513 };
1514
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001515 ScopedObjectAccessUnchecked soa(Thread::Current());
Elliott Hughescaf76542012-06-28 16:08:22 -07001516 Object* thread_group = gRegistry->Get<Object*>(thread_group_id);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001517 ThreadListVisitor tlv(soa, thread_group, thread_ids);
Ian Rogers50b35e22012-10-04 10:09:15 -07001518 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughesf8349362012-06-18 15:00:06 -07001519 Runtime::Current()->GetThreadList()->ForEach(ThreadListVisitor::Visit, &tlv);
Elliott Hughescaf76542012-06-28 16:08:22 -07001520}
Elliott Hughesa2155262011-11-16 16:26:58 -08001521
Elliott Hughescaf76542012-06-28 16:08:22 -07001522void Dbg::GetChildThreadGroups(JDWP::ObjectId thread_group_id, std::vector<JDWP::ObjectId>& child_thread_group_ids) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001523 ScopedObjectAccess soa(Thread::Current());
Elliott Hughescaf76542012-06-28 16:08:22 -07001524 Object* thread_group = gRegistry->Get<Object*>(thread_group_id);
1525
1526 // Get the ArrayList<ThreadGroup> "groups" out of this thread group...
1527 Field* groups_field = thread_group->GetClass()->FindInstanceField("groups", "Ljava/util/List;");
1528 Object* groups_array_list = groups_field->GetObject(thread_group);
1529
1530 // Get the array and size out of the ArrayList<ThreadGroup>...
1531 Field* array_field = groups_array_list->GetClass()->FindInstanceField("array", "[Ljava/lang/Object;");
1532 Field* size_field = groups_array_list->GetClass()->FindInstanceField("size", "I");
1533 ObjectArray<Object>* groups_array = array_field->GetObject(groups_array_list)->AsObjectArray<Object>();
1534 const int32_t size = size_field->GetInt(groups_array_list);
1535
1536 // Copy the first 'size' elements out of the array into the result.
1537 for (int32_t i = 0; i < size; ++i) {
1538 child_thread_group_ids.push_back(gRegistry->Add(groups_array->Get(i)));
Elliott Hughesa2155262011-11-16 16:26:58 -08001539 }
1540}
1541
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001542static int GetStackDepth(Thread* thread)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001543 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers0399dde2012-06-06 17:09:28 -07001544 struct CountStackDepthVisitor : public StackVisitor {
1545 CountStackDepthVisitor(const ManagedStack* stack,
Ian Rogersca190662012-06-26 15:45:57 -07001546 const std::vector<TraceStackFrame>* trace_stack)
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001547 : StackVisitor(stack, trace_stack, NULL), depth(0) {}
Ian Rogers0399dde2012-06-06 17:09:28 -07001548
1549 bool VisitFrame() {
1550 if (!GetMethod()->IsRuntimeMethod()) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -08001551 ++depth;
1552 }
Elliott Hughes530fa002012-03-12 11:44:49 -07001553 return true;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001554 }
1555 size_t depth;
1556 };
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001557
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001558 if (kIsDebugBuild) {
Ian Rogers50b35e22012-10-04 10:09:15 -07001559 MutexLock mu(Thread::Current(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001560 CHECK(thread->IsSuspended());
1561 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001562 CountStackDepthVisitor visitor(thread->GetManagedStack(), thread->GetTraceStack());
1563 visitor.WalkStack();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001564 return visitor.depth;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001565}
1566
Elliott Hughes86964332012-02-15 19:37:42 -08001567int Dbg::GetThreadFrameCount(JDWP::ObjectId threadId) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001568 ScopedObjectAccess soa(Thread::Current());
1569 return GetStackDepth(DecodeThread(soa, threadId));
Elliott Hughes86964332012-02-15 19:37:42 -08001570}
1571
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001572JDWP::JdwpError Dbg::GetThreadFrames(JDWP::ObjectId thread_id, size_t start_frame, size_t frame_count, JDWP::ExpandBuf* buf) {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001573 class GetFrameVisitor : public StackVisitor {
1574 public:
Ian Rogers0399dde2012-06-06 17:09:28 -07001575 GetFrameVisitor(const ManagedStack* stack, const std::vector<TraceStackFrame>* trace_stack,
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001576 size_t start_frame, size_t frame_count, JDWP::ExpandBuf* buf)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001577 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001578 : StackVisitor(stack, trace_stack, NULL), depth_(0),
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001579 start_frame_(start_frame), frame_count_(frame_count), buf_(buf) {
1580 expandBufAdd4BE(buf_, frame_count_);
Elliott Hughes03181a82011-11-17 17:22:21 -08001581 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001582
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001583 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1584 // annotalysis.
1585 virtual bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07001586 if (GetMethod()->IsRuntimeMethod()) {
Elliott Hughes530fa002012-03-12 11:44:49 -07001587 return true; // The debugger can't do anything useful with a frame that has no Method*.
Elliott Hughes03181a82011-11-17 17:22:21 -08001588 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001589 if (depth_ >= start_frame_ + frame_count_) {
Elliott Hughes530fa002012-03-12 11:44:49 -07001590 return false;
Elliott Hughes03181a82011-11-17 17:22:21 -08001591 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001592 if (depth_ >= start_frame_) {
1593 JDWP::FrameId frame_id(GetFrameId());
1594 JDWP::JdwpLocation location;
1595 SetLocation(location, GetMethod(), GetDexPc());
Elliott Hughes7baf96f2012-06-22 16:33:50 -07001596 VLOG(jdwp) << StringPrintf(" Frame %3zd: id=%3lld ", depth_, frame_id) << location;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001597 expandBufAdd8BE(buf_, frame_id);
1598 expandBufAddLocation(buf_, location);
1599 }
1600 ++depth_;
Elliott Hughes530fa002012-03-12 11:44:49 -07001601 return true;
Elliott Hughes03181a82011-11-17 17:22:21 -08001602 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001603
1604 private:
1605 size_t depth_;
1606 const size_t start_frame_;
1607 const size_t frame_count_;
1608 JDWP::ExpandBuf* buf_;
Elliott Hughes03181a82011-11-17 17:22:21 -08001609 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001610
1611 ScopedObjectAccessUnchecked soa(Thread::Current());
1612 Thread* thread = DecodeThread(soa, thread_id); // Caller already checked thread is suspended.
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001613 GetFrameVisitor visitor(thread->GetManagedStack(), thread->GetTraceStack(), start_frame, frame_count, buf);
Ian Rogers0399dde2012-06-06 17:09:28 -07001614 visitor.WalkStack();
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001615 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001616}
1617
1618JDWP::ObjectId Dbg::GetThreadSelfId() {
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07001619 ScopedObjectAccessUnchecked soa(Thread::Current());
1620 return gRegistry->Add(soa.Decode<Object*>(Thread::Current()->GetPeer()));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001621}
1622
Elliott Hughes475fc232011-10-25 15:00:35 -07001623void Dbg::SuspendVM() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001624 Runtime::Current()->GetThreadList()->SuspendAllForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001625}
1626
1627void Dbg::ResumeVM() {
Elliott Hughesc61a2672012-06-21 14:52:29 -07001628 Runtime::Current()->GetThreadList()->UndoDebuggerSuspensions();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001629}
1630
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001631JDWP::JdwpError Dbg::SuspendThread(JDWP::ObjectId threadId, bool request_suspension) {
1632
1633 bool timeout;
1634 ScopedLocalRef<jobject> peer(Thread::Current()->GetJniEnv(), NULL);
1635 {
1636 ScopedObjectAccess soa(Thread::Current());
1637 peer.reset(soa.AddLocalReference<jobject>(gRegistry->Get<Object*>(threadId)));
Elliott Hughes4e235312011-12-02 11:34:15 -08001638 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001639 if (peer.get() == NULL) {
1640 LOG(WARNING) << "No such thread for suspend: " << threadId;
1641 return JDWP::ERR_THREAD_NOT_ALIVE;
1642 }
1643 // Suspend thread to build stack trace.
1644 Thread* thread = Thread::SuspendForDebugger(peer.get(), request_suspension, &timeout);
1645 if (thread != NULL) {
1646 return JDWP::ERR_NONE;
1647 } else if (timeout) {
1648 return JDWP::ERR_INTERNAL;
1649 } else {
1650 return JDWP::ERR_THREAD_NOT_ALIVE;
1651 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001652}
1653
1654void Dbg::ResumeThread(JDWP::ObjectId threadId) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001655 ScopedObjectAccessUnchecked soa(Thread::Current());
Elliott Hughes4e235312011-12-02 11:34:15 -08001656 Object* peer = gRegistry->Get<Object*>(threadId);
Ian Rogers50b35e22012-10-04 10:09:15 -07001657 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001658 Thread* thread = Thread::FromManagedThread(soa, peer);
Elliott Hughes4e235312011-12-02 11:34:15 -08001659 if (thread == NULL) {
1660 LOG(WARNING) << "No such thread for resume: " << peer;
1661 return;
1662 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001663 bool needs_resume;
1664 {
Ian Rogers50b35e22012-10-04 10:09:15 -07001665 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001666 needs_resume = thread->GetSuspendCount() > 0;
1667 }
1668 if (needs_resume) {
Elliott Hughes546b9862012-06-20 16:06:13 -07001669 Runtime::Current()->GetThreadList()->Resume(thread, true);
1670 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001671}
1672
1673void Dbg::SuspendSelf() {
Elliott Hughes475fc232011-10-25 15:00:35 -07001674 Runtime::Current()->GetThreadList()->SuspendSelfForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001675}
1676
Ian Rogers0399dde2012-06-06 17:09:28 -07001677struct GetThisVisitor : public StackVisitor {
1678 GetThisVisitor(const ManagedStack* stack, const std::vector<TraceStackFrame>* trace_stack,
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001679 Context* context, JDWP::FrameId frameId)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001680 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001681 : StackVisitor(stack, trace_stack, context), this_object(NULL), frame_id(frameId) {}
Ian Rogers0399dde2012-06-06 17:09:28 -07001682
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001683 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1684 // annotalysis.
1685 virtual bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001686 if (frame_id != GetFrameId()) {
Ian Rogers0399dde2012-06-06 17:09:28 -07001687 return true; // continue
1688 }
Mathieu Chartier66f19252012-09-18 08:57:04 -07001689 AbstractMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07001690 if (m->IsNative() || m->IsStatic()) {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001691 this_object = NULL;
Ian Rogers0399dde2012-06-06 17:09:28 -07001692 } else {
1693 uint16_t reg = DemangleSlot(0, m);
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001694 this_object = reinterpret_cast<Object*>(GetVReg(m, reg));
Ian Rogers0399dde2012-06-06 17:09:28 -07001695 }
1696 return false;
Elliott Hughes86b00102011-12-05 17:54:26 -08001697 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001698
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001699 Object* this_object;
1700 JDWP::FrameId frame_id;
Ian Rogers0399dde2012-06-06 17:09:28 -07001701};
1702
Mathieu Chartier66f19252012-09-18 08:57:04 -07001703static Object* GetThis(Thread* self, AbstractMethod* m, size_t frame_id)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001704 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughescaf76542012-06-28 16:08:22 -07001705 // TODO: should we return the 'this' we passed through to non-static native methods?
Ian Rogers0399dde2012-06-06 17:09:28 -07001706 if (m->IsNative() || m->IsStatic()) {
1707 return NULL;
1708 }
Elliott Hughescaf76542012-06-28 16:08:22 -07001709
Ian Rogers0399dde2012-06-06 17:09:28 -07001710 UniquePtr<Context> context(Context::Create());
Elliott Hughescaf76542012-06-28 16:08:22 -07001711 GetThisVisitor visitor(self->GetManagedStack(), self->GetTraceStack(), context.get(), frame_id);
1712 visitor.WalkStack();
1713 return visitor.this_object;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001714}
1715
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001716JDWP::JdwpError Dbg::GetThisObject(JDWP::ObjectId thread_id, JDWP::FrameId frame_id,
1717 JDWP::ObjectId* result) {
1718 ScopedObjectAccessUnchecked soa(Thread::Current());
1719 Thread* thread;
1720 {
Ian Rogers50b35e22012-10-04 10:09:15 -07001721 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001722 thread = DecodeThread(soa, thread_id);
1723 if (thread == NULL) {
1724 return JDWP::ERR_INVALID_THREAD;
1725 }
Ian Rogers50b35e22012-10-04 10:09:15 -07001726 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001727 if (!thread->IsSuspended()) {
1728 return JDWP::ERR_THREAD_NOT_SUSPENDED;
1729 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001730 }
Elliott Hughescaf76542012-06-28 16:08:22 -07001731 UniquePtr<Context> context(Context::Create());
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001732 GetThisVisitor visitor(thread->GetManagedStack(), thread->GetTraceStack(), context.get(), frame_id);
Ian Rogers0399dde2012-06-06 17:09:28 -07001733 visitor.WalkStack();
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001734 *result = gRegistry->Add(visitor.this_object);
1735 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001736}
1737
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001738void Dbg::GetLocalValue(JDWP::ObjectId threadId, JDWP::FrameId frameId, int slot, JDWP::JdwpTag tag,
1739 uint8_t* buf, size_t width) {
Ian Rogers0399dde2012-06-06 17:09:28 -07001740 struct GetLocalVisitor : public StackVisitor {
1741 GetLocalVisitor(const ManagedStack* stack, const std::vector<TraceStackFrame>* trace_stack,
1742 Context* context, JDWP::FrameId frameId, int slot, JDWP::JdwpTag tag,
Ian Rogersca190662012-06-26 15:45:57 -07001743 uint8_t* buf, size_t width)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001744 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogersca190662012-06-26 15:45:57 -07001745 : StackVisitor(stack, trace_stack, context), frame_id_(frameId), slot_(slot), tag_(tag),
1746 buf_(buf), width_(width) {}
1747
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001748 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1749 // annotalysis.
1750 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07001751 if (GetFrameId() != frame_id_) {
1752 return true; // Not our frame, carry on.
Elliott Hughesdbb40792011-11-18 17:05:22 -08001753 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001754 // TODO: check that the tag is compatible with the actual type of the slot!
Mathieu Chartier66f19252012-09-18 08:57:04 -07001755 AbstractMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07001756 uint16_t reg = DemangleSlot(slot_, m);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001757
Ian Rogers0399dde2012-06-06 17:09:28 -07001758 switch (tag_) {
1759 case JDWP::JT_BOOLEAN:
1760 {
1761 CHECK_EQ(width_, 1U);
1762 uint32_t intVal = GetVReg(m, reg);
1763 VLOG(jdwp) << "get boolean local " << reg << " = " << intVal;
1764 JDWP::Set1(buf_+1, intVal != 0);
1765 }
1766 break;
1767 case JDWP::JT_BYTE:
1768 {
1769 CHECK_EQ(width_, 1U);
1770 uint32_t intVal = GetVReg(m, reg);
1771 VLOG(jdwp) << "get byte local " << reg << " = " << intVal;
1772 JDWP::Set1(buf_+1, intVal);
1773 }
1774 break;
1775 case JDWP::JT_SHORT:
1776 case JDWP::JT_CHAR:
1777 {
1778 CHECK_EQ(width_, 2U);
1779 uint32_t intVal = GetVReg(m, reg);
1780 VLOG(jdwp) << "get short/char local " << reg << " = " << intVal;
1781 JDWP::Set2BE(buf_+1, intVal);
1782 }
1783 break;
1784 case JDWP::JT_INT:
1785 case JDWP::JT_FLOAT:
1786 {
1787 CHECK_EQ(width_, 4U);
1788 uint32_t intVal = GetVReg(m, reg);
1789 VLOG(jdwp) << "get int/float local " << reg << " = " << intVal;
1790 JDWP::Set4BE(buf_+1, intVal);
1791 }
1792 break;
1793 case JDWP::JT_ARRAY:
1794 {
1795 CHECK_EQ(width_, sizeof(JDWP::ObjectId));
1796 Object* o = reinterpret_cast<Object*>(GetVReg(m, reg));
1797 VLOG(jdwp) << "get array local " << reg << " = " << o;
1798 if (!Runtime::Current()->GetHeap()->IsHeapAddress(o)) {
1799 LOG(FATAL) << "Register " << reg << " expected to hold array: " << o;
1800 }
1801 JDWP::SetObjectId(buf_+1, gRegistry->Add(o));
1802 }
1803 break;
1804 case JDWP::JT_CLASS_LOADER:
1805 case JDWP::JT_CLASS_OBJECT:
1806 case JDWP::JT_OBJECT:
1807 case JDWP::JT_STRING:
1808 case JDWP::JT_THREAD:
1809 case JDWP::JT_THREAD_GROUP:
1810 {
1811 CHECK_EQ(width_, sizeof(JDWP::ObjectId));
1812 Object* o = reinterpret_cast<Object*>(GetVReg(m, reg));
1813 VLOG(jdwp) << "get object local " << reg << " = " << o;
1814 if (!Runtime::Current()->GetHeap()->IsHeapAddress(o)) {
1815 LOG(FATAL) << "Register " << reg << " expected to hold object: " << o;
1816 }
1817 tag_ = TagFromObject(o);
1818 JDWP::SetObjectId(buf_+1, gRegistry->Add(o));
1819 }
1820 break;
1821 case JDWP::JT_DOUBLE:
1822 case JDWP::JT_LONG:
1823 {
1824 CHECK_EQ(width_, 8U);
1825 uint32_t lo = GetVReg(m, reg);
1826 uint64_t hi = GetVReg(m, reg + 1);
1827 uint64_t longVal = (hi << 32) | lo;
1828 VLOG(jdwp) << "get double/long local " << hi << ":" << lo << " = " << longVal;
1829 JDWP::Set8BE(buf_+1, longVal);
1830 }
1831 break;
1832 default:
1833 LOG(FATAL) << "Unknown tag " << tag_;
1834 break;
1835 }
1836
1837 // Prepend tag, which may have been updated.
1838 JDWP::Set1(buf_, tag_);
1839 return false;
1840 }
1841
1842 const JDWP::FrameId frame_id_;
1843 const int slot_;
1844 JDWP::JdwpTag tag_;
1845 uint8_t* const buf_;
1846 const size_t width_;
1847 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001848
1849 ScopedObjectAccessUnchecked soa(Thread::Current());
1850 Thread* thread = DecodeThread(soa, threadId);
Ian Rogers0399dde2012-06-06 17:09:28 -07001851 UniquePtr<Context> context(Context::Create());
1852 GetLocalVisitor visitor(thread->GetManagedStack(), thread->GetTraceStack(), context.get(),
1853 frameId, slot, tag, buf, width);
1854 visitor.WalkStack();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001855}
1856
Ian Rogers0399dde2012-06-06 17:09:28 -07001857void Dbg::SetLocalValue(JDWP::ObjectId threadId, JDWP::FrameId frameId, int slot, JDWP::JdwpTag tag,
1858 uint64_t value, size_t width) {
1859 struct SetLocalVisitor : public StackVisitor {
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001860 SetLocalVisitor(const ManagedStack* stack, const std::vector<TraceStackFrame>* trace_stack, Context* context,
Ian Rogers0399dde2012-06-06 17:09:28 -07001861 JDWP::FrameId frame_id, int slot, JDWP::JdwpTag tag, uint64_t value,
Ian Rogersca190662012-06-26 15:45:57 -07001862 size_t width)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001863 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001864 : StackVisitor(stack, trace_stack, context),
1865 frame_id_(frame_id), slot_(slot), tag_(tag), value_(value), width_(width) {}
Ian Rogersca190662012-06-26 15:45:57 -07001866
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001867 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1868 // annotalysis.
1869 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07001870 if (GetFrameId() != frame_id_) {
1871 return true; // Not our frame, carry on.
1872 }
1873 // TODO: check that the tag is compatible with the actual type of the slot!
Mathieu Chartier66f19252012-09-18 08:57:04 -07001874 AbstractMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07001875 uint16_t reg = DemangleSlot(slot_, m);
1876
1877 switch (tag_) {
1878 case JDWP::JT_BOOLEAN:
1879 case JDWP::JT_BYTE:
1880 CHECK_EQ(width_, 1U);
1881 SetVReg(m, reg, static_cast<uint32_t>(value_));
1882 break;
1883 case JDWP::JT_SHORT:
1884 case JDWP::JT_CHAR:
1885 CHECK_EQ(width_, 2U);
1886 SetVReg(m, reg, static_cast<uint32_t>(value_));
1887 break;
1888 case JDWP::JT_INT:
1889 case JDWP::JT_FLOAT:
1890 CHECK_EQ(width_, 4U);
1891 SetVReg(m, reg, static_cast<uint32_t>(value_));
1892 break;
1893 case JDWP::JT_ARRAY:
1894 case JDWP::JT_OBJECT:
1895 case JDWP::JT_STRING:
1896 {
1897 CHECK_EQ(width_, sizeof(JDWP::ObjectId));
1898 Object* o = gRegistry->Get<Object*>(static_cast<JDWP::ObjectId>(value_));
1899 if (o == kInvalidObject) {
1900 UNIMPLEMENTED(FATAL) << "return an error code when given an invalid object to store";
1901 }
1902 SetVReg(m, reg, static_cast<uint32_t>(reinterpret_cast<uintptr_t>(o)));
1903 }
1904 break;
1905 case JDWP::JT_DOUBLE:
1906 case JDWP::JT_LONG:
1907 CHECK_EQ(width_, 8U);
1908 SetVReg(m, reg, static_cast<uint32_t>(value_));
1909 SetVReg(m, reg + 1, static_cast<uint32_t>(value_ >> 32));
1910 break;
1911 default:
1912 LOG(FATAL) << "Unknown tag " << tag_;
1913 break;
1914 }
1915 return false;
1916 }
1917
1918 const JDWP::FrameId frame_id_;
1919 const int slot_;
1920 const JDWP::JdwpTag tag_;
1921 const uint64_t value_;
1922 const size_t width_;
1923 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001924
1925 ScopedObjectAccessUnchecked soa(Thread::Current());
1926 Thread* thread = DecodeThread(soa, threadId);
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001927 UniquePtr<Context> context(Context::Create());
1928 SetLocalVisitor visitor(thread->GetManagedStack(), thread->GetTraceStack(), context.get(),
1929 frameId, slot, tag, value, width);
Ian Rogers0399dde2012-06-06 17:09:28 -07001930 visitor.WalkStack();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001931}
1932
Mathieu Chartier66f19252012-09-18 08:57:04 -07001933void Dbg::PostLocationEvent(const AbstractMethod* m, int dex_pc, Object* this_object, int event_flags) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001934 Class* c = m->GetDeclaringClass();
1935
1936 JDWP::JdwpLocation location;
Elliott Hughes74847412012-06-20 18:10:21 -07001937 location.type_tag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
1938 location.class_id = gRegistry->Add(c);
1939 location.method_id = ToMethodId(m);
Elliott Hughes972a47b2012-02-21 18:16:06 -08001940 location.dex_pc = m->IsNative() ? -1 : dex_pc;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001941
1942 // Note we use "NoReg" so we don't keep track of references that are
1943 // never actually sent to the debugger. 'this_id' is only used to
1944 // compare against registered events...
1945 JDWP::ObjectId this_id = static_cast<JDWP::ObjectId>(reinterpret_cast<uintptr_t>(this_object));
1946 if (gJdwpState->PostLocationEvent(&location, this_id, event_flags)) {
1947 // ...unless there's a registered event, in which case we
1948 // need to really track the class and 'this'.
1949 gRegistry->Add(c);
1950 gRegistry->Add(this_object);
1951 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001952}
1953
Elliott Hughescaf76542012-06-28 16:08:22 -07001954void Dbg::PostException(Thread* thread,
Mathieu Chartier66f19252012-09-18 08:57:04 -07001955 JDWP::FrameId throw_frame_id, AbstractMethod* throw_method, uint32_t throw_dex_pc,
1956 AbstractMethod* catch_method, uint32_t catch_dex_pc, Throwable* exception) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07001957 if (!IsDebuggerActive()) {
Ian Rogers0ad5bb82011-12-07 10:16:32 -08001958 return;
1959 }
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001960
Elliott Hughesd07986f2011-12-06 18:27:45 -08001961 JDWP::JdwpLocation throw_location;
Elliott Hughescaf76542012-06-28 16:08:22 -07001962 SetLocation(throw_location, throw_method, throw_dex_pc);
Elliott Hughesd07986f2011-12-06 18:27:45 -08001963 JDWP::JdwpLocation catch_location;
Elliott Hughescaf76542012-06-28 16:08:22 -07001964 SetLocation(catch_location, catch_method, catch_dex_pc);
Elliott Hughesd07986f2011-12-06 18:27:45 -08001965
1966 // We need 'this' for InstanceOnly filters.
Elliott Hughescaf76542012-06-28 16:08:22 -07001967 UniquePtr<Context> context(Context::Create());
1968 GetThisVisitor visitor(thread->GetManagedStack(), thread->GetTraceStack(), context.get(), throw_frame_id);
1969 visitor.WalkStack();
1970 JDWP::ObjectId this_id = gRegistry->Add(visitor.this_object);
Elliott Hughesd07986f2011-12-06 18:27:45 -08001971
1972 /*
1973 * Hand the event to the JDWP exception handler. Note we're using the
1974 * "NoReg" objectID on the exception, which is not strictly correct --
1975 * the exception object WILL be passed up to the debugger if the
1976 * debugger is interested in the event. We do this because the current
1977 * implementation of the debugger object registry never throws anything
1978 * away, and some people were experiencing a fatal build up of exception
1979 * objects when dealing with certain libraries.
1980 */
1981 JDWP::ObjectId exception_id = static_cast<JDWP::ObjectId>(reinterpret_cast<uintptr_t>(exception));
1982 JDWP::RefTypeId exception_class_id = gRegistry->Add(exception->GetClass());
1983
1984 gJdwpState->PostException(&throw_location, exception_id, exception_class_id, &catch_location, this_id);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001985}
1986
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001987void Dbg::PostClassPrepare(Class* c) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07001988 if (!IsDebuggerActive()) {
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001989 return;
1990 }
1991
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001992 // OLD-TODO - we currently always send both "verified" and "prepared" since
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001993 // debuggers seem to like that. There might be some advantage to honesty,
1994 // since the class may not yet be verified.
1995 int state = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
1996 JDWP::JdwpTypeTag tag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
1997 gJdwpState->PostClassPrepare(tag, gRegistry->Add(c), ClassHelper(c).GetDescriptor(), state);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001998}
1999
Elliott Hughescaf76542012-06-28 16:08:22 -07002000void Dbg::UpdateDebugger(int32_t dex_pc, Thread* self) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002001 if (!IsDebuggerActive() || dex_pc == -2 /* fake method exit */) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002002 return;
2003 }
2004
Elliott Hughescaf76542012-06-28 16:08:22 -07002005 size_t frame_id;
Mathieu Chartier66f19252012-09-18 08:57:04 -07002006 AbstractMethod* m = self->GetCurrentMethod(NULL, &frame_id);
Elliott Hughescaf76542012-06-28 16:08:22 -07002007 //LOG(INFO) << "UpdateDebugger " << PrettyMethod(m) << "@" << dex_pc << " frame " << frame_id;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002008
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002009 if (dex_pc == -1) {
Elliott Hughes2aa2e392012-02-17 17:15:43 -08002010 // We use a pc of -1 to represent method entry, since we might branch back to pc 0 later.
2011 // This means that for this special notification, there can't be anything else interesting
2012 // going on, so we're done already.
Elliott Hughescaf76542012-06-28 16:08:22 -07002013 Dbg::PostLocationEvent(m, 0, GetThis(self, m, frame_id), kMethodEntry);
Elliott Hughes2aa2e392012-02-17 17:15:43 -08002014 return;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002015 }
2016
Elliott Hughes2aa2e392012-02-17 17:15:43 -08002017 int event_flags = 0;
2018
Elliott Hughes86964332012-02-15 19:37:42 -08002019 if (IsBreakpoint(m, dex_pc)) {
2020 event_flags |= kBreakpoint;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002021 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002022
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002023 // If the debugger is single-stepping one of our threads, check to
2024 // see if we're that thread and we've reached a step point.
Ian Rogers50b35e22012-10-04 10:09:15 -07002025 MutexLock mu(Thread::Current(), gBreakpointsLock);
Elliott Hughes86964332012-02-15 19:37:42 -08002026 if (gSingleStepControl.is_active && gSingleStepControl.thread == self) {
2027 CHECK(!m->IsNative());
2028 if (gSingleStepControl.step_depth == JDWP::SD_INTO) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002029 // Step into method calls. We break when the line number
2030 // or method pointer changes. If we're in SS_MIN mode, we
2031 // always stop.
Elliott Hughes86964332012-02-15 19:37:42 -08002032 if (gSingleStepControl.method != m) {
2033 event_flags |= kSingleStep;
2034 VLOG(jdwp) << "SS new method";
2035 } else if (gSingleStepControl.step_size == JDWP::SS_MIN) {
2036 event_flags |= kSingleStep;
2037 VLOG(jdwp) << "SS new instruction";
Elliott Hughes2435a572012-02-17 16:07:41 -08002038 } else if (gSingleStepControl.dex_pcs.find(dex_pc) == gSingleStepControl.dex_pcs.end()) {
2039 event_flags |= kSingleStep;
2040 VLOG(jdwp) << "SS new line";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002041 }
Elliott Hughes86964332012-02-15 19:37:42 -08002042 } else if (gSingleStepControl.step_depth == JDWP::SD_OVER) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002043 // Step over method calls. We break when the line number is
2044 // different and the frame depth is <= the original frame
2045 // depth. (We can't just compare on the method, because we
2046 // might get unrolled past it by an exception, and it's tricky
2047 // to identify recursion.)
Elliott Hughes86964332012-02-15 19:37:42 -08002048
2049 // TODO: can we just use the value of 'sp'?
2050 int stack_depth = GetStackDepth(self);
2051
2052 if (stack_depth < gSingleStepControl.stack_depth) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002053 // popped up one or more frames, always trigger
Elliott Hughes86964332012-02-15 19:37:42 -08002054 event_flags |= kSingleStep;
2055 VLOG(jdwp) << "SS method pop";
2056 } else if (stack_depth == gSingleStepControl.stack_depth) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002057 // same depth, see if we moved
Elliott Hughes86964332012-02-15 19:37:42 -08002058 if (gSingleStepControl.step_size == JDWP::SS_MIN) {
2059 event_flags |= kSingleStep;
2060 VLOG(jdwp) << "SS new instruction";
Elliott Hughes2435a572012-02-17 16:07:41 -08002061 } else if (gSingleStepControl.dex_pcs.find(dex_pc) == gSingleStepControl.dex_pcs.end()) {
2062 event_flags |= kSingleStep;
2063 VLOG(jdwp) << "SS new line";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002064 }
2065 }
2066 } else {
Elliott Hughes86964332012-02-15 19:37:42 -08002067 CHECK_EQ(gSingleStepControl.step_depth, JDWP::SD_OUT);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002068 // Return from the current method. We break when the frame
2069 // depth pops up.
2070
2071 // This differs from the "method exit" break in that it stops
2072 // with the PC at the next instruction in the returned-to
2073 // function, rather than the end of the returning function.
Elliott Hughes86964332012-02-15 19:37:42 -08002074
2075 // TODO: can we just use the value of 'sp'?
2076 int stack_depth = GetStackDepth(self);
2077 if (stack_depth < gSingleStepControl.stack_depth) {
2078 event_flags |= kSingleStep;
2079 VLOG(jdwp) << "SS method pop";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002080 }
2081 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002082 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002083
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002084 // Check to see if this is a "return" instruction. JDWP says we should
2085 // send the event *after* the code has been executed, but it also says
2086 // the location we provide is the last instruction. Since the "return"
2087 // instruction has no interesting side effects, we should be safe.
2088 // (We can't just move this down to the returnFromMethod label because
2089 // we potentially need to combine it with other events.)
2090 // We're also not supposed to generate a method exit event if the method
2091 // terminates "with a thrown exception".
Elliott Hughes86964332012-02-15 19:37:42 -08002092 if (dex_pc >= 0) {
2093 const DexFile::CodeItem* code_item = MethodHelper(m).GetCodeItem();
Elliott Hughescaf76542012-06-28 16:08:22 -07002094 CHECK(code_item != NULL) << PrettyMethod(m) << " @" << dex_pc;
Elliott Hughes86964332012-02-15 19:37:42 -08002095 CHECK_LT(dex_pc, static_cast<int32_t>(code_item->insns_size_in_code_units_));
2096 if (Instruction::At(&code_item->insns_[dex_pc])->IsReturn()) {
2097 event_flags |= kMethodExit;
2098 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002099 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002100
2101 // If there's something interesting going on, see if it matches one
2102 // of the debugger filters.
2103 if (event_flags != 0) {
Elliott Hughescaf76542012-06-28 16:08:22 -07002104 Dbg::PostLocationEvent(m, dex_pc, GetThis(self, m, frame_id), event_flags);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002105 }
2106}
2107
Elliott Hughes86964332012-02-15 19:37:42 -08002108void Dbg::WatchLocation(const JDWP::JdwpLocation* location) {
Ian Rogers50b35e22012-10-04 10:09:15 -07002109 MutexLock mu(Thread::Current(), gBreakpointsLock);
Mathieu Chartier66f19252012-09-18 08:57:04 -07002110 AbstractMethod* m = FromMethodId(location->method_id);
Elliott Hughes972a47b2012-02-21 18:16:06 -08002111 gBreakpoints.push_back(Breakpoint(m, location->dex_pc));
Elliott Hughes86964332012-02-15 19:37:42 -08002112 VLOG(jdwp) << "Set breakpoint #" << (gBreakpoints.size() - 1) << ": " << gBreakpoints[gBreakpoints.size() - 1];
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002113}
2114
Elliott Hughes86964332012-02-15 19:37:42 -08002115void Dbg::UnwatchLocation(const JDWP::JdwpLocation* location) {
Ian Rogers50b35e22012-10-04 10:09:15 -07002116 MutexLock mu(Thread::Current(), gBreakpointsLock);
Mathieu Chartier66f19252012-09-18 08:57:04 -07002117 AbstractMethod* m = FromMethodId(location->method_id);
Elliott Hughes86964332012-02-15 19:37:42 -08002118 for (size_t i = 0; i < gBreakpoints.size(); ++i) {
Elliott Hughes972a47b2012-02-21 18:16:06 -08002119 if (gBreakpoints[i].method == m && gBreakpoints[i].dex_pc == location->dex_pc) {
Elliott Hughes86964332012-02-15 19:37:42 -08002120 VLOG(jdwp) << "Removed breakpoint #" << i << ": " << gBreakpoints[i];
2121 gBreakpoints.erase(gBreakpoints.begin() + i);
2122 return;
2123 }
2124 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002125}
2126
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002127JDWP::JdwpError Dbg::ConfigureStep(JDWP::ObjectId threadId, JDWP::JdwpStepSize step_size,
2128 JDWP::JdwpStepDepth step_depth) {
2129 ScopedObjectAccessUnchecked soa(Thread::Current());
2130 Thread* thread = DecodeThread(soa, threadId);
Elliott Hughes2435a572012-02-17 16:07:41 -08002131 if (thread == NULL) {
2132 return JDWP::ERR_INVALID_THREAD;
2133 }
Elliott Hughes86964332012-02-15 19:37:42 -08002134
Ian Rogers50b35e22012-10-04 10:09:15 -07002135 MutexLock mu(soa.Self(), gBreakpointsLock);
Elliott Hughes86964332012-02-15 19:37:42 -08002136 // TODO: there's no theoretical reason why we couldn't support single-stepping
2137 // of multiple threads at once, but we never did so historically.
2138 if (gSingleStepControl.thread != NULL && thread != gSingleStepControl.thread) {
2139 LOG(WARNING) << "single-step already active for " << *gSingleStepControl.thread
2140 << "; switching to " << *thread;
2141 }
2142
Elliott Hughes2435a572012-02-17 16:07:41 -08002143 //
2144 // Work out what Method* we're in, the current line number, and how deep the stack currently
2145 // is for step-out.
2146 //
2147
Ian Rogers0399dde2012-06-06 17:09:28 -07002148 struct SingleStepStackVisitor : public StackVisitor {
2149 SingleStepStackVisitor(const ManagedStack* stack,
Ian Rogersca190662012-06-26 15:45:57 -07002150 const std::vector<TraceStackFrame>* trace_stack)
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002151 EXCLUSIVE_LOCKS_REQUIRED(gBreakpointsLock)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002152 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Elliott Hughes08fc03a2012-06-26 17:34:00 -07002153 : StackVisitor(stack, trace_stack, NULL) {
Ian Rogers50b35e22012-10-04 10:09:15 -07002154 gBreakpointsLock.AssertHeld(Thread::Current());
Elliott Hughes86964332012-02-15 19:37:42 -08002155 gSingleStepControl.method = NULL;
2156 gSingleStepControl.stack_depth = 0;
2157 }
Ian Rogersca190662012-06-26 15:45:57 -07002158
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002159 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2160 // annotalysis.
2161 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers50b35e22012-10-04 10:09:15 -07002162 gBreakpointsLock.AssertHeld(Thread::Current());
Mathieu Chartier66f19252012-09-18 08:57:04 -07002163 const AbstractMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07002164 if (!m->IsRuntimeMethod()) {
Elliott Hughes86964332012-02-15 19:37:42 -08002165 ++gSingleStepControl.stack_depth;
2166 if (gSingleStepControl.method == NULL) {
Elliott Hughes2435a572012-02-17 16:07:41 -08002167 const DexCache* dex_cache = m->GetDeclaringClass()->GetDexCache();
2168 gSingleStepControl.method = m;
2169 gSingleStepControl.line_number = -1;
2170 if (dex_cache != NULL) {
Ian Rogers4445a7e2012-10-05 17:19:13 -07002171 const DexFile& dex_file = *dex_cache->GetDexFile();
Ian Rogers0399dde2012-06-06 17:09:28 -07002172 gSingleStepControl.line_number = dex_file.GetLineNumFromPC(m, GetDexPc());
Elliott Hughes2435a572012-02-17 16:07:41 -08002173 }
Elliott Hughes86964332012-02-15 19:37:42 -08002174 }
2175 }
Elliott Hughes530fa002012-03-12 11:44:49 -07002176 return true;
Elliott Hughes86964332012-02-15 19:37:42 -08002177 }
2178 };
Ian Rogers0399dde2012-06-06 17:09:28 -07002179 SingleStepStackVisitor visitor(thread->GetManagedStack(), thread->GetTraceStack());
2180 visitor.WalkStack();
Elliott Hughes86964332012-02-15 19:37:42 -08002181
Elliott Hughes2435a572012-02-17 16:07:41 -08002182 //
2183 // Find the dex_pc values that correspond to the current line, for line-based single-stepping.
2184 //
2185
2186 struct DebugCallbackContext {
2187 DebugCallbackContext() {
2188 last_pc_valid = false;
2189 last_pc = 0;
Elliott Hughes2435a572012-02-17 16:07:41 -08002190 }
2191
2192 static bool Callback(void* raw_context, uint32_t address, uint32_t line_number) {
Ian Rogers50b35e22012-10-04 10:09:15 -07002193 MutexLock mu(Thread::Current(), gBreakpointsLock); // Keep GCC happy.
Elliott Hughes2435a572012-02-17 16:07:41 -08002194 DebugCallbackContext* context = reinterpret_cast<DebugCallbackContext*>(raw_context);
2195 if (static_cast<int32_t>(line_number) == gSingleStepControl.line_number) {
2196 if (!context->last_pc_valid) {
2197 // Everything from this address until the next line change is ours.
2198 context->last_pc = address;
2199 context->last_pc_valid = true;
2200 }
2201 // Otherwise, if we're already in a valid range for this line,
2202 // just keep going (shouldn't really happen)...
2203 } else if (context->last_pc_valid) { // and the line number is new
2204 // Add everything from the last entry up until here to the set
2205 for (uint32_t dex_pc = context->last_pc; dex_pc < address; ++dex_pc) {
2206 gSingleStepControl.dex_pcs.insert(dex_pc);
2207 }
2208 context->last_pc_valid = false;
2209 }
2210 return false; // There may be multiple entries for any given line.
2211 }
2212
2213 ~DebugCallbackContext() {
Ian Rogers50b35e22012-10-04 10:09:15 -07002214 MutexLock mu(Thread::Current(), gBreakpointsLock); // Keep GCC happy.
Elliott Hughes2435a572012-02-17 16:07:41 -08002215 // If the line number was the last in the position table...
2216 if (last_pc_valid) {
2217 size_t end = MethodHelper(gSingleStepControl.method).GetCodeItem()->insns_size_in_code_units_;
2218 for (uint32_t dex_pc = last_pc; dex_pc < end; ++dex_pc) {
2219 gSingleStepControl.dex_pcs.insert(dex_pc);
2220 }
2221 }
2222 }
2223
2224 bool last_pc_valid;
2225 uint32_t last_pc;
2226 };
Elliott Hughes3e2e1a22012-02-21 11:33:41 -08002227 gSingleStepControl.dex_pcs.clear();
Mathieu Chartier66f19252012-09-18 08:57:04 -07002228 const AbstractMethod* m = gSingleStepControl.method;
Elliott Hughes3e2e1a22012-02-21 11:33:41 -08002229 if (m->IsNative()) {
2230 gSingleStepControl.line_number = -1;
2231 } else {
2232 DebugCallbackContext context;
2233 MethodHelper mh(m);
2234 mh.GetDexFile().DecodeDebugInfo(mh.GetCodeItem(), m->IsStatic(), m->GetDexMethodIndex(),
2235 DebugCallbackContext::Callback, NULL, &context);
2236 }
Elliott Hughes2435a572012-02-17 16:07:41 -08002237
2238 //
2239 // Everything else...
2240 //
2241
Elliott Hughes86964332012-02-15 19:37:42 -08002242 gSingleStepControl.thread = thread;
2243 gSingleStepControl.step_size = step_size;
2244 gSingleStepControl.step_depth = step_depth;
2245 gSingleStepControl.is_active = true;
2246
Elliott Hughes2435a572012-02-17 16:07:41 -08002247 if (VLOG_IS_ON(jdwp)) {
2248 VLOG(jdwp) << "Single-step thread: " << *gSingleStepControl.thread;
2249 VLOG(jdwp) << "Single-step step size: " << gSingleStepControl.step_size;
2250 VLOG(jdwp) << "Single-step step depth: " << gSingleStepControl.step_depth;
2251 VLOG(jdwp) << "Single-step current method: " << PrettyMethod(gSingleStepControl.method);
2252 VLOG(jdwp) << "Single-step current line: " << gSingleStepControl.line_number;
2253 VLOG(jdwp) << "Single-step current stack depth: " << gSingleStepControl.stack_depth;
2254 VLOG(jdwp) << "Single-step dex_pc values:";
2255 for (std::set<uint32_t>::iterator it = gSingleStepControl.dex_pcs.begin() ; it != gSingleStepControl.dex_pcs.end(); ++it) {
Elliott Hughes229feb72012-02-23 13:33:29 -08002256 VLOG(jdwp) << StringPrintf(" %#x", *it);
Elliott Hughes2435a572012-02-17 16:07:41 -08002257 }
2258 }
2259
2260 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002261}
2262
Elliott Hughes1bac54f2012-03-16 12:48:31 -07002263void Dbg::UnconfigureStep(JDWP::ObjectId /*threadId*/) {
Ian Rogers50b35e22012-10-04 10:09:15 -07002264 MutexLock mu(Thread::Current(), gBreakpointsLock);
Elliott Hughesf8349362012-06-18 15:00:06 -07002265
Elliott Hughes86964332012-02-15 19:37:42 -08002266 gSingleStepControl.is_active = false;
2267 gSingleStepControl.thread = NULL;
Elliott Hughes2435a572012-02-17 16:07:41 -08002268 gSingleStepControl.dex_pcs.clear();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002269}
2270
Elliott Hughes45651fd2012-02-21 15:48:20 -08002271static char JdwpTagToShortyChar(JDWP::JdwpTag tag) {
2272 switch (tag) {
2273 default:
2274 LOG(FATAL) << "unknown JDWP tag: " << PrintableChar(tag);
2275
2276 // Primitives.
2277 case JDWP::JT_BYTE: return 'B';
2278 case JDWP::JT_CHAR: return 'C';
2279 case JDWP::JT_FLOAT: return 'F';
2280 case JDWP::JT_DOUBLE: return 'D';
2281 case JDWP::JT_INT: return 'I';
2282 case JDWP::JT_LONG: return 'J';
2283 case JDWP::JT_SHORT: return 'S';
2284 case JDWP::JT_VOID: return 'V';
2285 case JDWP::JT_BOOLEAN: return 'Z';
2286
2287 // Reference types.
2288 case JDWP::JT_ARRAY:
2289 case JDWP::JT_OBJECT:
2290 case JDWP::JT_STRING:
2291 case JDWP::JT_THREAD:
2292 case JDWP::JT_THREAD_GROUP:
2293 case JDWP::JT_CLASS_LOADER:
2294 case JDWP::JT_CLASS_OBJECT:
2295 return 'L';
2296 }
2297}
2298
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002299JDWP::JdwpError Dbg::InvokeMethod(JDWP::ObjectId threadId, JDWP::ObjectId objectId,
2300 JDWP::RefTypeId classId, JDWP::MethodId methodId,
2301 uint32_t arg_count, uint64_t* arg_values,
2302 JDWP::JdwpTag* arg_types, uint32_t options,
2303 JDWP::JdwpTag* pResultTag, uint64_t* pResultValue,
2304 JDWP::ObjectId* pExceptionId) {
Elliott Hughesd07986f2011-12-06 18:27:45 -08002305 ThreadList* thread_list = Runtime::Current()->GetThreadList();
2306
2307 Thread* targetThread = NULL;
2308 DebugInvokeReq* req = NULL;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002309 Thread* self = Thread::Current();
Elliott Hughesd07986f2011-12-06 18:27:45 -08002310 {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002311 ScopedObjectAccessUnchecked soa(self);
Ian Rogers50b35e22012-10-04 10:09:15 -07002312 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002313 targetThread = DecodeThread(soa, threadId);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002314 if (targetThread == NULL) {
2315 LOG(ERROR) << "InvokeMethod request for non-existent thread " << threadId;
2316 return JDWP::ERR_INVALID_THREAD;
2317 }
2318 req = targetThread->GetInvokeReq();
2319 if (!req->ready) {
2320 LOG(ERROR) << "InvokeMethod request for thread not stopped by event: " << *targetThread;
2321 return JDWP::ERR_INVALID_THREAD;
2322 }
2323
2324 /*
2325 * We currently have a bug where we don't successfully resume the
2326 * target thread if the suspend count is too deep. We're expected to
2327 * require one "resume" for each "suspend", but when asked to execute
2328 * a method we have to resume fully and then re-suspend it back to the
2329 * same level. (The easiest way to cause this is to type "suspend"
2330 * multiple times in jdb.)
2331 *
2332 * It's unclear what this means when the event specifies "resume all"
2333 * and some threads are suspended more deeply than others. This is
2334 * a rare problem, so for now we just prevent it from hanging forever
2335 * by rejecting the method invocation request. Without this, we will
2336 * be stuck waiting on a suspended thread.
2337 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002338 int suspend_count;
2339 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002340 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002341 suspend_count = targetThread->GetSuspendCount();
2342 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08002343 if (suspend_count > 1) {
2344 LOG(ERROR) << *targetThread << " suspend count too deep for method invocation: " << suspend_count;
2345 return JDWP::ERR_THREAD_SUSPENDED; // Probably not expected here.
2346 }
2347
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002348 JDWP::JdwpError status;
Elliott Hughes45651fd2012-02-21 15:48:20 -08002349 Object* receiver = gRegistry->Get<Object*>(objectId);
2350 if (receiver == kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002351 return JDWP::ERR_INVALID_OBJECT;
2352 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002353
2354 Object* thread = gRegistry->Get<Object*>(threadId);
2355 if (thread == kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002356 return JDWP::ERR_INVALID_OBJECT;
2357 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002358 // TODO: check that 'thread' is actually a java.lang.Thread!
2359
2360 Class* c = DecodeClass(classId, status);
2361 if (c == NULL) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002362 return status;
2363 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002364
Mathieu Chartier66f19252012-09-18 08:57:04 -07002365 AbstractMethod* m = FromMethodId(methodId);
Elliott Hughes45651fd2012-02-21 15:48:20 -08002366 if (m->IsStatic() != (receiver == NULL)) {
2367 return JDWP::ERR_INVALID_METHODID;
2368 }
2369 if (m->IsStatic()) {
2370 if (m->GetDeclaringClass() != c) {
2371 return JDWP::ERR_INVALID_METHODID;
2372 }
2373 } else {
2374 if (!m->GetDeclaringClass()->IsAssignableFrom(c)) {
2375 return JDWP::ERR_INVALID_METHODID;
2376 }
2377 }
2378
2379 // Check the argument list matches the method.
2380 MethodHelper mh(m);
2381 if (mh.GetShortyLength() - 1 != arg_count) {
2382 return JDWP::ERR_ILLEGAL_ARGUMENT;
2383 }
2384 const char* shorty = mh.GetShorty();
2385 for (size_t i = 0; i < arg_count; ++i) {
2386 if (shorty[i + 1] != JdwpTagToShortyChar(arg_types[i])) {
2387 return JDWP::ERR_ILLEGAL_ARGUMENT;
2388 }
2389 }
2390
2391 req->receiver_ = receiver;
2392 req->thread_ = thread;
2393 req->class_ = c;
2394 req->method_ = m;
2395 req->arg_count_ = arg_count;
2396 req->arg_values_ = arg_values;
Elliott Hughesd07986f2011-12-06 18:27:45 -08002397 req->options_ = options;
2398 req->invoke_needed_ = true;
2399 }
2400
2401 // The fact that we've released the thread list lock is a bit risky --- if the thread goes
2402 // away we're sitting high and dry -- but we must release this before the ResumeAllThreads
2403 // call, and it's unwise to hold it during WaitForSuspend.
2404
2405 {
2406 /*
2407 * We change our (JDWP thread) status, which should be THREAD_RUNNING,
Elliott Hughes81ff3182012-03-23 20:35:56 -07002408 * so we can suspend for a GC if the invoke request causes us to
Elliott Hughesd07986f2011-12-06 18:27:45 -08002409 * run out of memory. It's also a good idea to change it before locking
2410 * the invokeReq mutex, although that should never be held for long.
2411 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002412 self->TransitionFromRunnableToSuspended(kWaitingForDebuggerSend);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002413
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002414 VLOG(jdwp) << " Transferring control to event thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002415 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002416 MutexLock mu(self, req->lock_);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002417
2418 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002419 VLOG(jdwp) << " Resuming all threads";
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002420 thread_list->UndoDebuggerSuspensions();
Elliott Hughesd07986f2011-12-06 18:27:45 -08002421 } else {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002422 VLOG(jdwp) << " Resuming event thread only";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002423 thread_list->Resume(targetThread, true);
2424 }
2425
2426 // Wait for the request to finish executing.
2427 while (req->invoke_needed_) {
Ian Rogers81d425b2012-09-27 16:03:43 -07002428 req->cond_.Wait(self, req->lock_);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002429 }
2430 }
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002431 VLOG(jdwp) << " Control has returned from event thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002432
2433 /* wait for thread to re-suspend itself */
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002434 SuspendThread(threadId, false /* request_suspension */ );
2435 self->TransitionFromSuspendedToRunnable();
Elliott Hughesd07986f2011-12-06 18:27:45 -08002436 }
2437
2438 /*
2439 * Suspend the threads. We waited for the target thread to suspend
2440 * itself, so all we need to do is suspend the others.
2441 *
2442 * The suspendAllThreads() call will double-suspend the event thread,
2443 * so we want to resume the target thread once to keep the books straight.
2444 */
2445 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002446 self->TransitionFromRunnableToSuspended(kWaitingForDebuggerSuspension);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002447 VLOG(jdwp) << " Suspending all threads";
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002448 thread_list->SuspendAllForDebugger();
2449 self->TransitionFromSuspendedToRunnable();
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002450 VLOG(jdwp) << " Resuming event thread to balance the count";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002451 thread_list->Resume(targetThread, true);
2452 }
2453
2454 // Copy the result.
2455 *pResultTag = req->result_tag;
2456 if (IsPrimitiveTag(req->result_tag)) {
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002457 *pResultValue = req->result_value.GetJ();
Elliott Hughesd07986f2011-12-06 18:27:45 -08002458 } else {
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002459 *pResultValue = gRegistry->Add(req->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002460 }
2461 *pExceptionId = req->exception;
2462 return req->error;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002463}
2464
2465void Dbg::ExecuteMethod(DebugInvokeReq* pReq) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002466 ScopedObjectAccess soa(Thread::Current());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002467
Elliott Hughes81ff3182012-03-23 20:35:56 -07002468 // We can be called while an exception is pending. We need
Elliott Hughesd07986f2011-12-06 18:27:45 -08002469 // to preserve that across the method invocation.
Ian Rogers1f539342012-10-03 21:09:42 -07002470 SirtRef<Throwable> old_exception(soa.Self(), soa.Self()->GetException());
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002471 soa.Self()->ClearException();
Elliott Hughesd07986f2011-12-06 18:27:45 -08002472
2473 // Translate the method through the vtable, unless the debugger wants to suppress it.
Mathieu Chartier66f19252012-09-18 08:57:04 -07002474 AbstractMethod* m = pReq->method_;
Elliott Hughesd07986f2011-12-06 18:27:45 -08002475 if ((pReq->options_ & JDWP::INVOKE_NONVIRTUAL) == 0 && pReq->receiver_ != NULL) {
Mathieu Chartier66f19252012-09-18 08:57:04 -07002476 AbstractMethod* actual_method = pReq->class_->FindVirtualMethodForVirtualOrInterface(pReq->method_);
Elliott Hughes45651fd2012-02-21 15:48:20 -08002477 if (actual_method != m) {
2478 VLOG(jdwp) << "ExecuteMethod translated " << PrettyMethod(m) << " to " << PrettyMethod(actual_method);
2479 m = actual_method;
2480 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08002481 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002482 VLOG(jdwp) << "ExecuteMethod " << PrettyMethod(m);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002483 CHECK(m != NULL);
2484
2485 CHECK_EQ(sizeof(jvalue), sizeof(uint64_t));
2486
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002487 LOG(INFO) << "self=" << soa.Self() << " pReq->receiver_=" << pReq->receiver_ << " m=" << m
2488 << " #" << pReq->arg_count_ << " " << pReq->arg_values_;
2489 pReq->result_value = InvokeWithJValues(soa, pReq->receiver_, m,
2490 reinterpret_cast<JValue*>(pReq->arg_values_));
Elliott Hughesd07986f2011-12-06 18:27:45 -08002491
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002492 pReq->exception = gRegistry->Add(soa.Self()->GetException());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002493 pReq->result_tag = BasicTagFromDescriptor(MethodHelper(m).GetShorty());
2494 if (pReq->exception != 0) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002495 Object* exc = soa.Self()->GetException();
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002496 VLOG(jdwp) << " JDWP invocation returning with exception=" << exc << " " << PrettyTypeOf(exc);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002497 soa.Self()->ClearException();
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002498 pReq->result_value.SetJ(0);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002499 } else if (pReq->result_tag == JDWP::JT_OBJECT) {
2500 /* if no exception thrown, examine object result more closely */
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002501 JDWP::JdwpTag new_tag = TagFromObject(pReq->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002502 if (new_tag != pReq->result_tag) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002503 VLOG(jdwp) << " JDWP promoted result from " << pReq->result_tag << " to " << new_tag;
Elliott Hughesd07986f2011-12-06 18:27:45 -08002504 pReq->result_tag = new_tag;
2505 }
2506
2507 /*
2508 * Register the object. We don't actually need an ObjectId yet,
2509 * but we do need to be sure that the GC won't move or discard the
2510 * object when we switch out of RUNNING. The ObjectId conversion
2511 * will add the object to the "do not touch" list.
2512 *
2513 * We can't use the "tracked allocation" mechanism here because
2514 * the object is going to be handed off to a different thread.
2515 */
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002516 gRegistry->Add(pReq->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002517 }
2518
2519 if (old_exception.get() != NULL) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002520 soa.Self()->SetException(old_exception.get());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002521 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002522}
2523
Elliott Hughesd07986f2011-12-06 18:27:45 -08002524/*
2525 * Register an object ID that might not have been registered previously.
2526 *
2527 * Normally this wouldn't happen -- the conversion to an ObjectId would
2528 * have added the object to the registry -- but in some cases (e.g.
2529 * throwing exceptions) we really want to do the registration late.
2530 */
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002531void Dbg::RegisterObjectId(JDWP::ObjectId id) {
Elliott Hughesd07986f2011-12-06 18:27:45 -08002532 gRegistry->Add(reinterpret_cast<Object*>(id));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002533}
2534
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002535/*
2536 * "buf" contains a full JDWP packet, possibly with multiple chunks. We
2537 * need to process each, accumulate the replies, and ship the whole thing
2538 * back.
2539 *
2540 * Returns "true" if we have a reply. The reply buffer is newly allocated,
2541 * and includes the chunk type/length, followed by the data.
2542 *
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08002543 * OLD-TODO: we currently assume that the request and reply include a single
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002544 * chunk. If this becomes inconvenient we will need to adapt.
2545 */
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002546bool Dbg::DdmHandlePacket(const uint8_t* buf, int dataLen, uint8_t** pReplyBuf, int* pReplyLen) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002547 CHECK_GE(dataLen, 0);
2548
2549 Thread* self = Thread::Current();
2550 JNIEnv* env = self->GetJniEnv();
2551
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002552 // Create a byte[] corresponding to 'buf'.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002553 ScopedLocalRef<jbyteArray> dataArray(env, env->NewByteArray(dataLen));
2554 if (dataArray.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002555 LOG(WARNING) << "byte[] allocation failed: " << dataLen;
2556 env->ExceptionClear();
2557 return false;
2558 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002559 env->SetByteArrayRegion(dataArray.get(), 0, dataLen, reinterpret_cast<const jbyte*>(buf));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002560
2561 const int kChunkHdrLen = 8;
2562
2563 // Run through and find all chunks. [Currently just find the first.]
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002564 ScopedByteArrayRO contents(env, dataArray.get());
Elliott Hughesf7c3b662011-10-27 12:04:56 -07002565 jint type = JDWP::Get4BE(reinterpret_cast<const uint8_t*>(&contents[0]));
2566 jint length = JDWP::Get4BE(reinterpret_cast<const uint8_t*>(&contents[4]));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002567 jint offset = kChunkHdrLen;
2568 if (offset + length > dataLen) {
2569 LOG(WARNING) << StringPrintf("bad chunk found (len=%u pktLen=%d)", length, dataLen);
2570 return false;
2571 }
2572
2573 // Call "private static Chunk dispatch(int type, byte[] data, int offset, int length)".
Elliott Hugheseac76672012-05-24 21:56:51 -07002574 ScopedLocalRef<jobject> chunk(env, env->CallStaticObjectMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
2575 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_dispatch,
2576 type, dataArray.get(), offset, length));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002577 if (env->ExceptionCheck()) {
2578 LOG(INFO) << StringPrintf("Exception thrown by dispatcher for 0x%08x", type);
2579 env->ExceptionDescribe();
2580 env->ExceptionClear();
2581 return false;
2582 }
2583
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002584 if (chunk.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002585 return false;
2586 }
2587
2588 /*
2589 * Pull the pieces out of the chunk. We copy the results into a
2590 * newly-allocated buffer that the caller can free. We don't want to
2591 * continue using the Chunk object because nothing has a reference to it.
2592 *
2593 * We could avoid this by returning type/data/offset/length and having
2594 * the caller be aware of the object lifetime issues, but that
Elliott Hughes81ff3182012-03-23 20:35:56 -07002595 * integrates the JDWP code more tightly into the rest of the runtime, and doesn't work
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002596 * if we have responses for multiple chunks.
2597 *
2598 * So we're pretty much stuck with copying data around multiple times.
2599 */
Elliott Hugheseac76672012-05-24 21:56:51 -07002600 ScopedLocalRef<jbyteArray> replyData(env, reinterpret_cast<jbyteArray>(env->GetObjectField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_data)));
2601 length = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_length);
2602 offset = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_offset);
2603 type = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_type);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002604
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002605 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 -07002606 if (length == 0 || replyData.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002607 return false;
2608 }
2609
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002610 jsize replyLength = env->GetArrayLength(replyData.get());
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002611 if (offset + length > replyLength) {
2612 LOG(WARNING) << StringPrintf("chunk off=%d len=%d exceeds reply array len %d", offset, length, replyLength);
2613 return false;
2614 }
2615
2616 uint8_t* reply = new uint8_t[length + kChunkHdrLen];
2617 if (reply == NULL) {
2618 LOG(WARNING) << "malloc failed: " << (length + kChunkHdrLen);
2619 return false;
2620 }
Elliott Hughesf7c3b662011-10-27 12:04:56 -07002621 JDWP::Set4BE(reply + 0, type);
2622 JDWP::Set4BE(reply + 4, length);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002623 env->GetByteArrayRegion(replyData.get(), offset, length, reinterpret_cast<jbyte*>(reply + kChunkHdrLen));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002624
2625 *pReplyBuf = reply;
2626 *pReplyLen = length + kChunkHdrLen;
2627
Elliott Hughesba8eee12012-01-24 20:25:24 -08002628 VLOG(jdwp) << StringPrintf("dvmHandleDdm returning type=%.4s buf=%p len=%d", reinterpret_cast<char*>(reply), reply, length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002629 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002630}
2631
Elliott Hughesa2155262011-11-16 16:26:58 -08002632void Dbg::DdmBroadcast(bool connect) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002633 VLOG(jdwp) << "Broadcasting DDM " << (connect ? "connect" : "disconnect") << "...";
Elliott Hughes47fce012011-10-25 18:37:19 -07002634
2635 Thread* self = Thread::Current();
Ian Rogers50b35e22012-10-04 10:09:15 -07002636 if (self->GetState() != kRunnable) {
2637 LOG(ERROR) << "DDM broadcast in thread state " << self->GetState();
2638 /* try anyway? */
Elliott Hughes47fce012011-10-25 18:37:19 -07002639 }
2640
2641 JNIEnv* env = self->GetJniEnv();
Elliott Hughes47fce012011-10-25 18:37:19 -07002642 jint event = connect ? 1 /*DdmServer.CONNECTED*/ : 2 /*DdmServer.DISCONNECTED*/;
Elliott Hugheseac76672012-05-24 21:56:51 -07002643 env->CallStaticVoidMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
2644 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_broadcast,
2645 event);
Elliott Hughes47fce012011-10-25 18:37:19 -07002646 if (env->ExceptionCheck()) {
2647 LOG(ERROR) << "DdmServer.broadcast " << event << " failed";
2648 env->ExceptionDescribe();
2649 env->ExceptionClear();
2650 }
2651}
2652
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002653void Dbg::DdmConnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08002654 Dbg::DdmBroadcast(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002655}
2656
2657void Dbg::DdmDisconnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08002658 Dbg::DdmBroadcast(false);
Elliott Hughes47fce012011-10-25 18:37:19 -07002659 gDdmThreadNotification = false;
2660}
2661
2662/*
Elliott Hughes82188472011-11-07 18:11:48 -08002663 * Send a notification when a thread starts, stops, or changes its name.
Elliott Hughes47fce012011-10-25 18:37:19 -07002664 *
2665 * Because we broadcast the full set of threads when the notifications are
2666 * first enabled, it's possible for "thread" to be actively executing.
2667 */
Elliott Hughes82188472011-11-07 18:11:48 -08002668void Dbg::DdmSendThreadNotification(Thread* t, uint32_t type) {
Elliott Hughes47fce012011-10-25 18:37:19 -07002669 if (!gDdmThreadNotification) {
2670 return;
2671 }
2672
Elliott Hughes82188472011-11-07 18:11:48 -08002673 if (type == CHUNK_TYPE("THDE")) {
Elliott Hughes47fce012011-10-25 18:37:19 -07002674 uint8_t buf[4];
Elliott Hughesf7c3b662011-10-27 12:04:56 -07002675 JDWP::Set4BE(&buf[0], t->GetThinLockId());
Elliott Hughes47fce012011-10-25 18:37:19 -07002676 Dbg::DdmSendChunk(CHUNK_TYPE("THDE"), 4, buf);
Elliott Hughes82188472011-11-07 18:11:48 -08002677 } else {
2678 CHECK(type == CHUNK_TYPE("THCR") || type == CHUNK_TYPE("THNM")) << type;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002679 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers1f539342012-10-03 21:09:42 -07002680 SirtRef<String> name(soa.Self(), t->GetThreadName(soa));
Elliott Hughes82188472011-11-07 18:11:48 -08002681 size_t char_count = (name.get() != NULL) ? name->GetLength() : 0;
2682 const jchar* chars = name->GetCharArray()->GetData();
2683
Elliott Hughes21f32d72011-11-09 17:44:13 -08002684 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08002685 JDWP::Append4BE(bytes, t->GetThinLockId());
2686 JDWP::AppendUtf16BE(bytes, chars, char_count);
Elliott Hughes21f32d72011-11-09 17:44:13 -08002687 CHECK_EQ(bytes.size(), char_count*2 + sizeof(uint32_t)*2);
2688 Dbg::DdmSendChunk(type, bytes);
Elliott Hughes47fce012011-10-25 18:37:19 -07002689 }
2690}
2691
Elliott Hughes47fce012011-10-25 18:37:19 -07002692void Dbg::DdmSetThreadNotification(bool enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002693 // Enable/disable thread notifications.
Elliott Hughes47fce012011-10-25 18:37:19 -07002694 gDdmThreadNotification = enable;
2695 if (enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002696 // Suspend the VM then post thread start notifications for all threads. Threads attaching will
2697 // see a suspension in progress and block until that ends. They then post their own start
2698 // notification.
2699 SuspendVM();
2700 std::list<Thread*> threads;
Ian Rogers50b35e22012-10-04 10:09:15 -07002701 Thread* self = Thread::Current();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002702 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002703 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002704 threads = Runtime::Current()->GetThreadList()->GetList();
2705 }
2706 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002707 ScopedObjectAccess soa(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002708 typedef std::list<Thread*>::const_iterator It; // TODO: C++0x auto
2709 for (It it = threads.begin(), end = threads.end(); it != end; ++it) {
2710 Dbg::DdmSendThreadNotification(*it, CHUNK_TYPE("THCR"));
2711 }
2712 }
2713 ResumeVM();
Elliott Hughes47fce012011-10-25 18:37:19 -07002714 }
2715}
2716
Elliott Hughesa2155262011-11-16 16:26:58 -08002717void Dbg::PostThreadStartOrStop(Thread* t, uint32_t type) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002718 if (IsDebuggerActive()) {
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07002719 ScopedObjectAccessUnchecked soa(Thread::Current());
2720 JDWP::ObjectId id = gRegistry->Add(soa.Decode<Object*>(t->GetPeer()));
Elliott Hughes82188472011-11-07 18:11:48 -08002721 gJdwpState->PostThreadChange(id, type == CHUNK_TYPE("THCR"));
Elliott Hughesc0f09332012-03-26 13:27:06 -07002722 // If this thread's just joined the party while we're already debugging, make sure it knows
2723 // to give us updates when it's running.
2724 t->SetDebuggerUpdatesEnabled(true);
Elliott Hughes47fce012011-10-25 18:37:19 -07002725 }
Elliott Hughes82188472011-11-07 18:11:48 -08002726 Dbg::DdmSendThreadNotification(t, type);
Elliott Hughes47fce012011-10-25 18:37:19 -07002727}
2728
2729void Dbg::PostThreadStart(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08002730 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07002731}
2732
2733void Dbg::PostThreadDeath(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08002734 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THDE"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002735}
2736
Elliott Hughes82188472011-11-07 18:11:48 -08002737void Dbg::DdmSendChunk(uint32_t type, size_t byte_count, const uint8_t* buf) {
Elliott Hughes3bb81562011-10-21 18:52:59 -07002738 CHECK(buf != NULL);
2739 iovec vec[1];
2740 vec[0].iov_base = reinterpret_cast<void*>(const_cast<uint8_t*>(buf));
2741 vec[0].iov_len = byte_count;
2742 Dbg::DdmSendChunkV(type, vec, 1);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002743}
2744
Elliott Hughes21f32d72011-11-09 17:44:13 -08002745void Dbg::DdmSendChunk(uint32_t type, const std::vector<uint8_t>& bytes) {
2746 DdmSendChunk(type, bytes.size(), &bytes[0]);
2747}
2748
Elliott Hughescccd84f2011-12-05 16:51:54 -08002749void Dbg::DdmSendChunkV(uint32_t type, const struct iovec* iov, int iov_count) {
Elliott Hughes3bb81562011-10-21 18:52:59 -07002750 if (gJdwpState == NULL) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002751 VLOG(jdwp) << "Debugger thread not active, ignoring DDM send: " << type;
Elliott Hughes3bb81562011-10-21 18:52:59 -07002752 } else {
Elliott Hughescccd84f2011-12-05 16:51:54 -08002753 gJdwpState->DdmSendChunkV(type, iov, iov_count);
Elliott Hughes3bb81562011-10-21 18:52:59 -07002754 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002755}
2756
Elliott Hughes767a1472011-10-26 18:49:02 -07002757int Dbg::DdmHandleHpifChunk(HpifWhen when) {
2758 if (when == HPIF_WHEN_NOW) {
Elliott Hughes7162ad92011-10-27 14:08:42 -07002759 DdmSendHeapInfo(when);
Elliott Hughes767a1472011-10-26 18:49:02 -07002760 return true;
2761 }
2762
2763 if (when != HPIF_WHEN_NEVER && when != HPIF_WHEN_NEXT_GC && when != HPIF_WHEN_EVERY_GC) {
2764 LOG(ERROR) << "invalid HpifWhen value: " << static_cast<int>(when);
2765 return false;
2766 }
2767
2768 gDdmHpifWhen = when;
2769 return true;
2770}
2771
2772bool Dbg::DdmHandleHpsgNhsgChunk(Dbg::HpsgWhen when, Dbg::HpsgWhat what, bool native) {
2773 if (when != HPSG_WHEN_NEVER && when != HPSG_WHEN_EVERY_GC) {
2774 LOG(ERROR) << "invalid HpsgWhen value: " << static_cast<int>(when);
2775 return false;
2776 }
2777
2778 if (what != HPSG_WHAT_MERGED_OBJECTS && what != HPSG_WHAT_DISTINCT_OBJECTS) {
2779 LOG(ERROR) << "invalid HpsgWhat value: " << static_cast<int>(what);
2780 return false;
2781 }
2782
2783 if (native) {
2784 gDdmNhsgWhen = when;
2785 gDdmNhsgWhat = what;
2786 } else {
2787 gDdmHpsgWhen = when;
2788 gDdmHpsgWhat = what;
2789 }
2790 return true;
2791}
2792
Elliott Hughes7162ad92011-10-27 14:08:42 -07002793void Dbg::DdmSendHeapInfo(HpifWhen reason) {
2794 // If there's a one-shot 'when', reset it.
2795 if (reason == gDdmHpifWhen) {
2796 if (gDdmHpifWhen == HPIF_WHEN_NEXT_GC) {
2797 gDdmHpifWhen = HPIF_WHEN_NEVER;
2798 }
2799 }
2800
2801 /*
2802 * Chunk HPIF (client --> server)
2803 *
2804 * Heap Info. General information about the heap,
2805 * suitable for a summary display.
2806 *
2807 * [u4]: number of heaps
2808 *
2809 * For each heap:
2810 * [u4]: heap ID
2811 * [u8]: timestamp in ms since Unix epoch
2812 * [u1]: capture reason (same as 'when' value from server)
2813 * [u4]: max heap size in bytes (-Xmx)
2814 * [u4]: current heap size in bytes
2815 * [u4]: current number of bytes allocated
2816 * [u4]: current number of objects allocated
2817 */
2818 uint8_t heap_count = 1;
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08002819 Heap* heap = Runtime::Current()->GetHeap();
Elliott Hughes21f32d72011-11-09 17:44:13 -08002820 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08002821 JDWP::Append4BE(bytes, heap_count);
2822 JDWP::Append4BE(bytes, 1); // Heap id (bogus; we only have one heap).
2823 JDWP::Append8BE(bytes, MilliTime());
2824 JDWP::Append1BE(bytes, reason);
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08002825 JDWP::Append4BE(bytes, heap->GetMaxMemory()); // Max allowed heap size in bytes.
2826 JDWP::Append4BE(bytes, heap->GetTotalMemory()); // Current heap size in bytes.
2827 JDWP::Append4BE(bytes, heap->GetBytesAllocated());
2828 JDWP::Append4BE(bytes, heap->GetObjectsAllocated());
Elliott Hughes21f32d72011-11-09 17:44:13 -08002829 CHECK_EQ(bytes.size(), 4U + (heap_count * (4 + 8 + 1 + 4 + 4 + 4 + 4)));
2830 Dbg::DdmSendChunk(CHUNK_TYPE("HPIF"), bytes);
Elliott Hughes767a1472011-10-26 18:49:02 -07002831}
2832
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002833enum HpsgSolidity {
2834 SOLIDITY_FREE = 0,
2835 SOLIDITY_HARD = 1,
2836 SOLIDITY_SOFT = 2,
2837 SOLIDITY_WEAK = 3,
2838 SOLIDITY_PHANTOM = 4,
2839 SOLIDITY_FINALIZABLE = 5,
2840 SOLIDITY_SWEEP = 6,
2841};
2842
2843enum HpsgKind {
2844 KIND_OBJECT = 0,
2845 KIND_CLASS_OBJECT = 1,
2846 KIND_ARRAY_1 = 2,
2847 KIND_ARRAY_2 = 3,
2848 KIND_ARRAY_4 = 4,
2849 KIND_ARRAY_8 = 5,
2850 KIND_UNKNOWN = 6,
2851 KIND_NATIVE = 7,
2852};
2853
2854#define HPSG_PARTIAL (1<<7)
2855#define HPSG_STATE(solidity, kind) ((uint8_t)((((kind) & 0x7) << 3) | ((solidity) & 0x7)))
2856
Ian Rogers30fab402012-01-23 15:43:46 -08002857class HeapChunkContext {
2858 public:
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002859 // Maximum chunk size. Obtain this from the formula:
2860 // (((maximum_heap_size / ALLOCATION_UNIT_SIZE) + 255) / 256) * 2
2861 HeapChunkContext(bool merge, bool native)
Ian Rogers30fab402012-01-23 15:43:46 -08002862 : buf_(16384 - 16),
2863 type_(0),
2864 merge_(merge) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002865 Reset();
2866 if (native) {
Ian Rogers30fab402012-01-23 15:43:46 -08002867 type_ = CHUNK_TYPE("NHSG");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002868 } else {
Ian Rogers30fab402012-01-23 15:43:46 -08002869 type_ = merge ? CHUNK_TYPE("HPSG") : CHUNK_TYPE("HPSO");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002870 }
2871 }
2872
2873 ~HeapChunkContext() {
Ian Rogers30fab402012-01-23 15:43:46 -08002874 if (p_ > &buf_[0]) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002875 Flush();
2876 }
2877 }
2878
2879 void EnsureHeader(const void* chunk_ptr) {
Ian Rogers30fab402012-01-23 15:43:46 -08002880 if (!needHeader_) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002881 return;
2882 }
2883
2884 // Start a new HPSx chunk.
Ian Rogers30fab402012-01-23 15:43:46 -08002885 JDWP::Write4BE(&p_, 1); // Heap id (bogus; we only have one heap).
2886 JDWP::Write1BE(&p_, 8); // Size of allocation unit, in bytes.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002887
Ian Rogers30fab402012-01-23 15:43:46 -08002888 JDWP::Write4BE(&p_, reinterpret_cast<uintptr_t>(chunk_ptr)); // virtual address of segment start.
2889 JDWP::Write4BE(&p_, 0); // offset of this piece (relative to the virtual address).
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002890 // [u4]: length of piece, in allocation units
2891 // 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 -08002892 pieceLenField_ = p_;
2893 JDWP::Write4BE(&p_, 0x55555555);
2894 needHeader_ = false;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002895 }
2896
Ian Rogersb726dcb2012-09-05 08:57:23 -07002897 void Flush() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002898 // Patch the "length of piece" field.
Ian Rogers30fab402012-01-23 15:43:46 -08002899 CHECK_LE(&buf_[0], pieceLenField_);
2900 CHECK_LE(pieceLenField_, p_);
2901 JDWP::Set4BE(pieceLenField_, totalAllocationUnits_);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002902
Ian Rogers30fab402012-01-23 15:43:46 -08002903 Dbg::DdmSendChunk(type_, p_ - &buf_[0], &buf_[0]);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002904 Reset();
2905 }
2906
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002907 static void HeapChunkCallback(void* start, void* end, size_t used_bytes, void* arg)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002908 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_,
2909 Locks::mutator_lock_) {
Ian Rogers30fab402012-01-23 15:43:46 -08002910 reinterpret_cast<HeapChunkContext*>(arg)->HeapChunkCallback(start, end, used_bytes);
Elliott Hughesa2155262011-11-16 16:26:58 -08002911 }
2912
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002913 private:
Elliott Hughesa2155262011-11-16 16:26:58 -08002914 enum { ALLOCATION_UNIT_SIZE = 8 };
2915
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002916 void Reset() {
Ian Rogers30fab402012-01-23 15:43:46 -08002917 p_ = &buf_[0];
Ian Rogers15bf2d32012-08-28 17:33:04 -07002918 startOfNextMemoryChunk_ = NULL;
Ian Rogers30fab402012-01-23 15:43:46 -08002919 totalAllocationUnits_ = 0;
2920 needHeader_ = true;
2921 pieceLenField_ = NULL;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002922 }
2923
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002924 void HeapChunkCallback(void* start, void* /*end*/, size_t used_bytes)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002925 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_,
2926 Locks::mutator_lock_) {
Ian Rogers30fab402012-01-23 15:43:46 -08002927 // Note: heap call backs cannot manipulate the heap upon which they are crawling, care is taken
2928 // in the following code not to allocate memory, by ensuring buf_ is of the correct size
Ian Rogers15bf2d32012-08-28 17:33:04 -07002929 if (used_bytes == 0) {
2930 if (start == NULL) {
2931 // Reset for start of new heap.
2932 startOfNextMemoryChunk_ = NULL;
2933 Flush();
2934 }
2935 // Only process in use memory so that free region information
2936 // also includes dlmalloc book keeping.
Elliott Hughesa2155262011-11-16 16:26:58 -08002937 return;
Elliott Hughesa2155262011-11-16 16:26:58 -08002938 }
2939
Ian Rogers15bf2d32012-08-28 17:33:04 -07002940 /* If we're looking at the native heap, we'll just return
2941 * (SOLIDITY_HARD, KIND_NATIVE) for all allocated chunks
2942 */
2943 bool native = type_ == CHUNK_TYPE("NHSG");
2944
2945 if (startOfNextMemoryChunk_ != NULL) {
2946 // Transmit any pending free memory. Native free memory of
2947 // over kMaxFreeLen could be because of the use of mmaps, so
2948 // don't report. If not free memory then start a new segment.
2949 bool flush = true;
2950 if (start > startOfNextMemoryChunk_) {
2951 const size_t kMaxFreeLen = 2 * kPageSize;
2952 void* freeStart = startOfNextMemoryChunk_;
2953 void* freeEnd = start;
2954 size_t freeLen = (char*)freeEnd - (char*)freeStart;
2955 if (!native || freeLen < kMaxFreeLen) {
2956 AppendChunk(HPSG_STATE(SOLIDITY_FREE, 0), freeStart, freeLen);
2957 flush = false;
2958 }
2959 }
2960 if (flush) {
2961 startOfNextMemoryChunk_ = NULL;
2962 Flush();
2963 }
2964 }
2965 const Object *obj = (const Object *)start;
Elliott Hughesa2155262011-11-16 16:26:58 -08002966
2967 // Determine the type of this chunk.
2968 // OLD-TODO: if context.merge, see if this chunk is different from the last chunk.
2969 // If it's the same, we should combine them.
Ian Rogers15bf2d32012-08-28 17:33:04 -07002970 uint8_t state = ExamineObject(obj, native);
2971 // dlmalloc's chunk header is 2 * sizeof(size_t), but if the previous chunk is in use for an
2972 // allocation then the first sizeof(size_t) may belong to it.
2973 const size_t dlMallocOverhead = sizeof(size_t);
2974 AppendChunk(state, start, used_bytes + dlMallocOverhead);
2975 startOfNextMemoryChunk_ = (char*)start + used_bytes + dlMallocOverhead;
2976 }
Elliott Hughesa2155262011-11-16 16:26:58 -08002977
Ian Rogers15bf2d32012-08-28 17:33:04 -07002978 void AppendChunk(uint8_t state, void* ptr, size_t length)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002979 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07002980 // Make sure there's enough room left in the buffer.
2981 // We need to use two bytes for every fractional 256 allocation units used by the chunk plus
2982 // 17 bytes for any header.
2983 size_t needed = (((length/ALLOCATION_UNIT_SIZE + 255) / 256) * 2) + 17;
2984 size_t bytesLeft = buf_.size() - (size_t)(p_ - &buf_[0]);
2985 if (bytesLeft < needed) {
2986 Flush();
2987 }
2988
2989 bytesLeft = buf_.size() - (size_t)(p_ - &buf_[0]);
2990 if (bytesLeft < needed) {
2991 LOG(WARNING) << "Chunk is too big to transmit (chunk_len=" << length << ", "
2992 << needed << " bytes)";
2993 return;
2994 }
2995 EnsureHeader(ptr);
Elliott Hughesa2155262011-11-16 16:26:58 -08002996 // Write out the chunk description.
Ian Rogers15bf2d32012-08-28 17:33:04 -07002997 length /= ALLOCATION_UNIT_SIZE; // Convert to allocation units.
2998 totalAllocationUnits_ += length;
2999 while (length > 256) {
Ian Rogers30fab402012-01-23 15:43:46 -08003000 *p_++ = state | HPSG_PARTIAL;
3001 *p_++ = 255; // length - 1
Ian Rogers15bf2d32012-08-28 17:33:04 -07003002 length -= 256;
Elliott Hughesa2155262011-11-16 16:26:58 -08003003 }
Ian Rogers30fab402012-01-23 15:43:46 -08003004 *p_++ = state;
Ian Rogers15bf2d32012-08-28 17:33:04 -07003005 *p_++ = length - 1;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003006 }
3007
Ian Rogers5bfa60f2012-09-02 21:17:56 -07003008 uint8_t ExamineObject(const Object* o, bool is_native_heap)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003009 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
Elliott Hughesa2155262011-11-16 16:26:58 -08003010 if (o == NULL) {
3011 return HPSG_STATE(SOLIDITY_FREE, 0);
3012 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003013
Elliott Hughesa2155262011-11-16 16:26:58 -08003014 // It's an allocated chunk. Figure out what it is.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003015
Elliott Hughesa2155262011-11-16 16:26:58 -08003016 // If we're looking at the native heap, we'll just return
3017 // (SOLIDITY_HARD, KIND_NATIVE) for all allocated chunks.
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003018 if (is_native_heap) {
Elliott Hughesa2155262011-11-16 16:26:58 -08003019 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
3020 }
3021
Ian Rogers5bfa60f2012-09-02 21:17:56 -07003022 if (!Runtime::Current()->GetHeap()->IsLiveObjectLocked(o)) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07003023 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003024 }
3025
Elliott Hughesa2155262011-11-16 16:26:58 -08003026 Class* c = o->GetClass();
3027 if (c == NULL) {
3028 // The object was probably just created but hasn't been initialized yet.
3029 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
3030 }
3031
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08003032 if (!Runtime::Current()->GetHeap()->IsHeapAddress(c)) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07003033 LOG(ERROR) << "Invalid class for managed heap object: " << o << " " << c;
Elliott Hughesa2155262011-11-16 16:26:58 -08003034 return HPSG_STATE(SOLIDITY_HARD, KIND_UNKNOWN);
3035 }
3036
3037 if (c->IsClassClass()) {
3038 return HPSG_STATE(SOLIDITY_HARD, KIND_CLASS_OBJECT);
3039 }
3040
3041 if (c->IsArrayClass()) {
3042 if (o->IsObjectArray()) {
3043 return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
3044 }
3045 switch (c->GetComponentSize()) {
3046 case 1: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_1);
3047 case 2: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_2);
3048 case 4: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
3049 case 8: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_8);
3050 }
3051 }
3052
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003053 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
3054 }
3055
Ian Rogers30fab402012-01-23 15:43:46 -08003056 std::vector<uint8_t> buf_;
3057 uint8_t* p_;
3058 uint8_t* pieceLenField_;
Ian Rogers15bf2d32012-08-28 17:33:04 -07003059 void* startOfNextMemoryChunk_;
Ian Rogers30fab402012-01-23 15:43:46 -08003060 size_t totalAllocationUnits_;
3061 uint32_t type_;
3062 bool merge_;
3063 bool needHeader_;
3064
Elliott Hughesa2155262011-11-16 16:26:58 -08003065 DISALLOW_COPY_AND_ASSIGN(HeapChunkContext);
3066};
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003067
3068void Dbg::DdmSendHeapSegments(bool native) {
3069 Dbg::HpsgWhen when;
3070 Dbg::HpsgWhat what;
3071 if (!native) {
3072 when = gDdmHpsgWhen;
3073 what = gDdmHpsgWhat;
3074 } else {
3075 when = gDdmNhsgWhen;
3076 what = gDdmNhsgWhat;
3077 }
3078 if (when == HPSG_WHEN_NEVER) {
3079 return;
3080 }
3081
3082 // Figure out what kind of chunks we'll be sending.
3083 CHECK(what == HPSG_WHAT_MERGED_OBJECTS || what == HPSG_WHAT_DISTINCT_OBJECTS) << static_cast<int>(what);
3084
3085 // First, send a heap start chunk.
3086 uint8_t heap_id[4];
3087 JDWP::Set4BE(&heap_id[0], 1); // Heap id (bogus; we only have one heap).
3088 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHST") : CHUNK_TYPE("HPST"), sizeof(heap_id), heap_id);
3089
3090 // Send a series of heap segment chunks.
Elliott Hughesa2155262011-11-16 16:26:58 -08003091 HeapChunkContext context((what == HPSG_WHAT_MERGED_OBJECTS), native);
3092 if (native) {
Ian Rogers30fab402012-01-23 15:43:46 -08003093 // TODO: enable when bionic has moved to dlmalloc 2.8.5
3094 // dlmalloc_inspect_all(HeapChunkContext::HeapChunkCallback, &context);
3095 UNIMPLEMENTED(WARNING) << "Native heap send heap segments";
Elliott Hughesa2155262011-11-16 16:26:58 -08003096 } else {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08003097 Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07003098 const Spaces& spaces = heap->GetSpaces();
Ian Rogers50b35e22012-10-04 10:09:15 -07003099 Thread* self = Thread::Current();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07003100 for (Spaces::const_iterator cur = spaces.begin(); cur != spaces.end(); ++cur) {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07003101 if ((*cur)->IsAllocSpace()) {
Ian Rogers50b35e22012-10-04 10:09:15 -07003102 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07003103 (*cur)->AsAllocSpace()->Walk(HeapChunkContext::HeapChunkCallback, &context);
3104 }
3105 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07003106 // Walk the large objects, these are not in the AllocSpace.
3107 heap->GetLargeObjectsSpace()->Walk(HeapChunkContext::HeapChunkCallback, &context);
Elliott Hughesa2155262011-11-16 16:26:58 -08003108 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003109
3110 // Finally, send a heap end chunk.
3111 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHEN") : CHUNK_TYPE("HPEN"), sizeof(heap_id), heap_id);
Elliott Hughes767a1472011-10-26 18:49:02 -07003112}
3113
Elliott Hughes545a0642011-11-08 19:10:03 -08003114void Dbg::SetAllocTrackingEnabled(bool enabled) {
Ian Rogers50b35e22012-10-04 10:09:15 -07003115 MutexLock mu(Thread::Current(), gAllocTrackerLock);
Elliott Hughes545a0642011-11-08 19:10:03 -08003116 if (enabled) {
3117 if (recent_allocation_records_ == NULL) {
3118 LOG(INFO) << "Enabling alloc tracker (" << kNumAllocRecords << " entries, "
3119 << kMaxAllocRecordStackDepth << " frames --> "
3120 << (sizeof(AllocRecord) * kNumAllocRecords) << " bytes)";
3121 gAllocRecordHead = gAllocRecordCount = 0;
3122 recent_allocation_records_ = new AllocRecord[kNumAllocRecords];
3123 CHECK(recent_allocation_records_ != NULL);
3124 }
3125 } else {
3126 delete[] recent_allocation_records_;
3127 recent_allocation_records_ = NULL;
3128 }
3129}
3130
Ian Rogers0399dde2012-06-06 17:09:28 -07003131struct AllocRecordStackVisitor : public StackVisitor {
3132 AllocRecordStackVisitor(const ManagedStack* stack,
Ian Rogersca190662012-06-26 15:45:57 -07003133 const std::vector<TraceStackFrame>* trace_stack, AllocRecord* record)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003134 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Elliott Hughes08fc03a2012-06-26 17:34:00 -07003135 : StackVisitor(stack, trace_stack, NULL), record(record), depth(0) {}
Elliott Hughes545a0642011-11-08 19:10:03 -08003136
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003137 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
3138 // annotalysis.
3139 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughes545a0642011-11-08 19:10:03 -08003140 if (depth >= kMaxAllocRecordStackDepth) {
Elliott Hughes530fa002012-03-12 11:44:49 -07003141 return false;
Elliott Hughes545a0642011-11-08 19:10:03 -08003142 }
Mathieu Chartier66f19252012-09-18 08:57:04 -07003143 AbstractMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07003144 if (!m->IsRuntimeMethod()) {
3145 record->stack[depth].method = m;
3146 record->stack[depth].dex_pc = GetDexPc();
Elliott Hughes530fa002012-03-12 11:44:49 -07003147 ++depth;
Elliott Hughes545a0642011-11-08 19:10:03 -08003148 }
Elliott Hughes530fa002012-03-12 11:44:49 -07003149 return true;
Elliott Hughes545a0642011-11-08 19:10:03 -08003150 }
3151
3152 ~AllocRecordStackVisitor() {
3153 // Clear out any unused stack trace elements.
3154 for (; depth < kMaxAllocRecordStackDepth; ++depth) {
3155 record->stack[depth].method = NULL;
Ian Rogers0399dde2012-06-06 17:09:28 -07003156 record->stack[depth].dex_pc = 0;
Elliott Hughes545a0642011-11-08 19:10:03 -08003157 }
3158 }
3159
3160 AllocRecord* record;
3161 size_t depth;
3162};
3163
3164void Dbg::RecordAllocation(Class* type, size_t byte_count) {
3165 Thread* self = Thread::Current();
3166 CHECK(self != NULL);
3167
Ian Rogers50b35e22012-10-04 10:09:15 -07003168 MutexLock mu(self, gAllocTrackerLock);
Elliott Hughes545a0642011-11-08 19:10:03 -08003169 if (recent_allocation_records_ == NULL) {
3170 return;
3171 }
3172
3173 // Advance and clip.
3174 if (++gAllocRecordHead == kNumAllocRecords) {
3175 gAllocRecordHead = 0;
3176 }
3177
3178 // Fill in the basics.
3179 AllocRecord* record = &recent_allocation_records_[gAllocRecordHead];
3180 record->type = type;
3181 record->byte_count = byte_count;
3182 record->thin_lock_id = self->GetThinLockId();
3183
3184 // Fill in the stack trace.
Ian Rogers0399dde2012-06-06 17:09:28 -07003185 AllocRecordStackVisitor visitor(self->GetManagedStack(), self->GetTraceStack(), record);
3186 visitor.WalkStack();
Elliott Hughes545a0642011-11-08 19:10:03 -08003187
3188 if (gAllocRecordCount < kNumAllocRecords) {
3189 ++gAllocRecordCount;
3190 }
3191}
3192
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003193// Returns the index of the head element.
3194//
3195// We point at the most-recently-written record, so if gAllocRecordCount is 1
3196// we want to use the current element. Take "head+1" and subtract count
3197// from it.
3198//
3199// We need to handle underflow in our circular buffer, so we add
3200// kNumAllocRecords and then mask it back down.
Elliott Hughesf8349362012-06-18 15:00:06 -07003201static inline int HeadIndex() EXCLUSIVE_LOCKS_REQUIRED(gAllocTrackerLock) {
Elliott Hughes545a0642011-11-08 19:10:03 -08003202 return (gAllocRecordHead+1 + kNumAllocRecords - gAllocRecordCount) & (kNumAllocRecords-1);
3203}
3204
3205void Dbg::DumpRecentAllocations() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003206 ScopedObjectAccess soa(Thread::Current());
Ian Rogers50b35e22012-10-04 10:09:15 -07003207 MutexLock mu(soa.Self(), gAllocTrackerLock);
Elliott Hughes545a0642011-11-08 19:10:03 -08003208 if (recent_allocation_records_ == NULL) {
3209 LOG(INFO) << "Not recording tracked allocations";
3210 return;
3211 }
3212
3213 // "i" is the head of the list. We want to start at the end of the
3214 // list and move forward to the tail.
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003215 size_t i = HeadIndex();
Elliott Hughes545a0642011-11-08 19:10:03 -08003216 size_t count = gAllocRecordCount;
3217
3218 LOG(INFO) << "Tracked allocations, (head=" << gAllocRecordHead << " count=" << count << ")";
3219 while (count--) {
3220 AllocRecord* record = &recent_allocation_records_[i];
3221
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003222 LOG(INFO) << StringPrintf(" Thread %-2d %6zd bytes ", record->thin_lock_id, record->byte_count)
Elliott Hughes545a0642011-11-08 19:10:03 -08003223 << PrettyClass(record->type);
3224
3225 for (size_t stack_frame = 0; stack_frame < kMaxAllocRecordStackDepth; ++stack_frame) {
Mathieu Chartier66f19252012-09-18 08:57:04 -07003226 const AbstractMethod* m = record->stack[stack_frame].method;
Elliott Hughes545a0642011-11-08 19:10:03 -08003227 if (m == NULL) {
3228 break;
3229 }
3230 LOG(INFO) << " " << PrettyMethod(m) << " line " << record->stack[stack_frame].LineNumber();
3231 }
3232
3233 // pause periodically to help logcat catch up
3234 if ((count % 5) == 0) {
3235 usleep(40000);
3236 }
3237
3238 i = (i + 1) & (kNumAllocRecords-1);
3239 }
3240}
3241
3242class StringTable {
3243 public:
3244 StringTable() {
3245 }
3246
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003247 void Add(const char* s) {
Elliott Hughes545a0642011-11-08 19:10:03 -08003248 table_.insert(s);
3249 }
3250
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003251 size_t IndexOf(const char* s) const {
3252 typedef std::set<std::string>::const_iterator It; // TODO: C++0x auto
3253 It it = table_.find(s);
3254 if (it == table_.end()) {
3255 LOG(FATAL) << "IndexOf(\"" << s << "\") failed";
3256 }
3257 return std::distance(table_.begin(), it);
Elliott Hughes545a0642011-11-08 19:10:03 -08003258 }
3259
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003260 size_t Size() const {
Elliott Hughes545a0642011-11-08 19:10:03 -08003261 return table_.size();
3262 }
3263
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003264 void WriteTo(std::vector<uint8_t>& bytes) const {
3265 typedef std::set<std::string>::const_iterator It; // TODO: C++0x auto
Elliott Hughes545a0642011-11-08 19:10:03 -08003266 for (It it = table_.begin(); it != table_.end(); ++it) {
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003267 const char* s = (*it).c_str();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003268 size_t s_len = CountModifiedUtf8Chars(s);
3269 UniquePtr<uint16_t> s_utf16(new uint16_t[s_len]);
3270 ConvertModifiedUtf8ToUtf16(s_utf16.get(), s);
3271 JDWP::AppendUtf16BE(bytes, s_utf16.get(), s_len);
Elliott Hughes545a0642011-11-08 19:10:03 -08003272 }
3273 }
3274
3275 private:
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003276 std::set<std::string> table_;
Elliott Hughes545a0642011-11-08 19:10:03 -08003277 DISALLOW_COPY_AND_ASSIGN(StringTable);
3278};
3279
3280/*
3281 * The data we send to DDMS contains everything we have recorded.
3282 *
3283 * Message header (all values big-endian):
3284 * (1b) message header len (to allow future expansion); includes itself
3285 * (1b) entry header len
3286 * (1b) stack frame len
3287 * (2b) number of entries
3288 * (4b) offset to string table from start of message
3289 * (2b) number of class name strings
3290 * (2b) number of method name strings
3291 * (2b) number of source file name strings
3292 * For each entry:
3293 * (4b) total allocation size
3294 * (2b) threadId
3295 * (2b) allocated object's class name index
3296 * (1b) stack depth
3297 * For each stack frame:
3298 * (2b) method's class name
3299 * (2b) method name
3300 * (2b) method source file
3301 * (2b) line number, clipped to 32767; -2 if native; -1 if no source
3302 * (xb) class name strings
3303 * (xb) method name strings
3304 * (xb) source file strings
3305 *
3306 * As with other DDM traffic, strings are sent as a 4-byte length
3307 * followed by UTF-16 data.
3308 *
3309 * We send up 16-bit unsigned indexes into string tables. In theory there
3310 * can be (kMaxAllocRecordStackDepth * kNumAllocRecords) unique strings in
3311 * each table, but in practice there should be far fewer.
3312 *
3313 * The chief reason for using a string table here is to keep the size of
3314 * the DDMS message to a minimum. This is partly to make the protocol
3315 * efficient, but also because we have to form the whole thing up all at
3316 * once in a memory buffer.
3317 *
3318 * We use separate string tables for class names, method names, and source
3319 * files to keep the indexes small. There will generally be no overlap
3320 * between the contents of these tables.
3321 */
3322jbyteArray Dbg::GetRecentAllocations() {
3323 if (false) {
3324 DumpRecentAllocations();
3325 }
3326
Ian Rogers50b35e22012-10-04 10:09:15 -07003327 Thread* self = Thread::Current();
3328 MutexLock mu(self, gAllocTrackerLock);
Elliott Hughes545a0642011-11-08 19:10:03 -08003329
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003330 //
3331 // Part 1: generate string tables.
3332 //
Elliott Hughes545a0642011-11-08 19:10:03 -08003333 StringTable class_names;
3334 StringTable method_names;
3335 StringTable filenames;
3336
3337 int count = gAllocRecordCount;
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003338 int idx = HeadIndex();
Elliott Hughes545a0642011-11-08 19:10:03 -08003339 while (count--) {
3340 AllocRecord* record = &recent_allocation_records_[idx];
3341
Elliott Hughes91250e02011-12-13 22:30:35 -08003342 class_names.Add(ClassHelper(record->type).GetDescriptor());
Elliott Hughes545a0642011-11-08 19:10:03 -08003343
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003344 MethodHelper mh;
Elliott Hughes545a0642011-11-08 19:10:03 -08003345 for (size_t i = 0; i < kMaxAllocRecordStackDepth; i++) {
Mathieu Chartier66f19252012-09-18 08:57:04 -07003346 AbstractMethod* m = record->stack[i].method;
Elliott Hughes545a0642011-11-08 19:10:03 -08003347 if (m != NULL) {
Ian Rogersba377812012-05-28 21:16:29 -07003348 mh.ChangeMethod(m);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003349 class_names.Add(mh.GetDeclaringClassDescriptor());
3350 method_names.Add(mh.GetName());
3351 filenames.Add(mh.GetDeclaringClassSourceFile());
Elliott Hughes545a0642011-11-08 19:10:03 -08003352 }
3353 }
3354
3355 idx = (idx + 1) & (kNumAllocRecords-1);
3356 }
3357
3358 LOG(INFO) << "allocation records: " << gAllocRecordCount;
3359
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003360 //
3361 // Part 2: allocate a buffer and generate the output.
3362 //
Elliott Hughes545a0642011-11-08 19:10:03 -08003363 std::vector<uint8_t> bytes;
3364
3365 // (1b) message header len (to allow future expansion); includes itself
3366 // (1b) entry header len
3367 // (1b) stack frame len
3368 const int kMessageHeaderLen = 15;
3369 const int kEntryHeaderLen = 9;
3370 const int kStackFrameLen = 8;
3371 JDWP::Append1BE(bytes, kMessageHeaderLen);
3372 JDWP::Append1BE(bytes, kEntryHeaderLen);
3373 JDWP::Append1BE(bytes, kStackFrameLen);
3374
3375 // (2b) number of entries
3376 // (4b) offset to string table from start of message
3377 // (2b) number of class name strings
3378 // (2b) number of method name strings
3379 // (2b) number of source file name strings
3380 JDWP::Append2BE(bytes, gAllocRecordCount);
3381 size_t string_table_offset = bytes.size();
3382 JDWP::Append4BE(bytes, 0); // We'll patch this later...
3383 JDWP::Append2BE(bytes, class_names.Size());
3384 JDWP::Append2BE(bytes, method_names.Size());
3385 JDWP::Append2BE(bytes, filenames.Size());
3386
3387 count = gAllocRecordCount;
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003388 idx = HeadIndex();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003389 ClassHelper kh;
Elliott Hughes545a0642011-11-08 19:10:03 -08003390 while (count--) {
3391 // For each entry:
3392 // (4b) total allocation size
3393 // (2b) thread id
3394 // (2b) allocated object's class name index
3395 // (1b) stack depth
3396 AllocRecord* record = &recent_allocation_records_[idx];
3397 size_t stack_depth = record->GetDepth();
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003398 kh.ChangeClass(record->type);
3399 size_t allocated_object_class_name_index = class_names.IndexOf(kh.GetDescriptor());
Elliott Hughes545a0642011-11-08 19:10:03 -08003400 JDWP::Append4BE(bytes, record->byte_count);
3401 JDWP::Append2BE(bytes, record->thin_lock_id);
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003402 JDWP::Append2BE(bytes, allocated_object_class_name_index);
Elliott Hughes545a0642011-11-08 19:10:03 -08003403 JDWP::Append1BE(bytes, stack_depth);
3404
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003405 MethodHelper mh;
Elliott Hughes545a0642011-11-08 19:10:03 -08003406 for (size_t stack_frame = 0; stack_frame < stack_depth; ++stack_frame) {
3407 // For each stack frame:
3408 // (2b) method's class name
3409 // (2b) method name
3410 // (2b) method source file
3411 // (2b) line number, clipped to 32767; -2 if native; -1 if no source
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003412 mh.ChangeMethod(record->stack[stack_frame].method);
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003413 size_t class_name_index = class_names.IndexOf(mh.GetDeclaringClassDescriptor());
3414 size_t method_name_index = method_names.IndexOf(mh.GetName());
3415 size_t file_name_index = filenames.IndexOf(mh.GetDeclaringClassSourceFile());
3416 JDWP::Append2BE(bytes, class_name_index);
3417 JDWP::Append2BE(bytes, method_name_index);
3418 JDWP::Append2BE(bytes, file_name_index);
Elliott Hughes545a0642011-11-08 19:10:03 -08003419 JDWP::Append2BE(bytes, record->stack[stack_frame].LineNumber());
3420 }
3421
3422 idx = (idx + 1) & (kNumAllocRecords-1);
3423 }
3424
3425 // (xb) class name strings
3426 // (xb) method name strings
3427 // (xb) source file strings
3428 JDWP::Set4BE(&bytes[string_table_offset], bytes.size());
3429 class_names.WriteTo(bytes);
3430 method_names.WriteTo(bytes);
3431 filenames.WriteTo(bytes);
3432
Ian Rogers50b35e22012-10-04 10:09:15 -07003433 JNIEnv* env = self->GetJniEnv();
Elliott Hughes545a0642011-11-08 19:10:03 -08003434 jbyteArray result = env->NewByteArray(bytes.size());
3435 if (result != NULL) {
3436 env->SetByteArrayRegion(result, 0, bytes.size(), reinterpret_cast<const jbyte*>(&bytes[0]));
3437 }
3438 return result;
3439}
3440
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003441} // namespace art