blob: a2ebddf2a213fde10ebff9db2ac4a791f43602de [file] [log] [blame]
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "debugger.h"
18
Elliott Hughes3bb81562011-10-21 18:52:59 -070019#include <sys/uio.h>
20
Elliott Hughes545a0642011-11-08 19:10:03 -080021#include <set>
22
23#include "class_linker.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080024#include "class_linker-inl.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070025#include "dex_file-inl.h"
Ian Rogers776ac1f2012-04-13 23:36:36 -070026#include "dex_instruction.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080027#include "gc/card_table-inl.h"
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -070028#include "gc/large_object_space.h"
29#include "gc/space.h"
Jeff Hao5d917302013-02-27 17:57:33 -080030#include "invoke_arg_array_builder.h"
Elliott Hughes64f574f2013-02-20 14:57:12 -080031#include "jdwp/object_registry.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080032#include "mirror/abstract_method-inl.h"
33#include "mirror/class.h"
34#include "mirror/class-inl.h"
35#include "mirror/class_loader.h"
36#include "mirror/field-inl.h"
37#include "mirror/object-inl.h"
38#include "mirror/object_array-inl.h"
39#include "mirror/throwable.h"
Ian Rogers2bcb4a42012-11-08 10:39:18 -080040#include "oat/runtime/context.h"
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080041#include "object_utils.h"
Elliott Hughesa0e18062012-04-13 15:59:59 -070042#include "safe_map.h"
Elliott Hughes64f574f2013-02-20 14:57:12 -080043#include "scoped_thread_state_change.h"
Elliott Hughes6a5bd492011-10-28 14:33:57 -070044#include "ScopedLocalRef.h"
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -070045#include "ScopedPrimitiveArray.h"
Ian Rogers1f539342012-10-03 21:09:42 -070046#include "sirt_ref.h"
Elliott Hughes47fce012011-10-25 18:37:19 -070047#include "stack_indirect_reference_table.h"
Elliott Hughes475fc232011-10-25 15:00:35 -070048#include "thread_list.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080049#include "utf.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070050#include "well_known_classes.h"
Elliott Hughes475fc232011-10-25 15:00:35 -070051
Elliott Hughes872d4ec2011-10-21 17:07:15 -070052namespace art {
53
Elliott Hughes545a0642011-11-08 19:10:03 -080054static const size_t kMaxAllocRecordStackDepth = 16; // Max 255.
Elliott Hughes64f574f2013-02-20 14:57:12 -080055static const size_t kNumAllocRecords = 512; // Must be a power of 2.
Elliott Hughes475fc232011-10-25 15:00:35 -070056
Elliott Hughes545a0642011-11-08 19:10:03 -080057struct AllocRecordStackTraceElement {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080058 mirror::AbstractMethod* method;
Ian Rogers0399dde2012-06-06 17:09:28 -070059 uint32_t dex_pc;
Elliott Hughes545a0642011-11-08 19:10:03 -080060
Ian Rogersb726dcb2012-09-05 08:57:23 -070061 int32_t LineNumber() const SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers0399dde2012-06-06 17:09:28 -070062 return MethodHelper(method).GetLineNumFromDexPC(dex_pc);
Elliott Hughes545a0642011-11-08 19:10:03 -080063 }
64};
65
66struct AllocRecord {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080067 mirror::Class* type;
Elliott Hughes545a0642011-11-08 19:10:03 -080068 size_t byte_count;
69 uint16_t thin_lock_id;
70 AllocRecordStackTraceElement stack[kMaxAllocRecordStackDepth]; // Unused entries have NULL method.
71
72 size_t GetDepth() {
73 size_t depth = 0;
74 while (depth < kMaxAllocRecordStackDepth && stack[depth].method != NULL) {
75 ++depth;
76 }
77 return depth;
78 }
79};
80
Elliott Hughes86964332012-02-15 19:37:42 -080081struct Breakpoint {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080082 mirror::AbstractMethod* method;
Elliott Hughesa656a0f2012-02-21 18:03:44 -080083 uint32_t dex_pc;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080084 Breakpoint(mirror::AbstractMethod* method, uint32_t dex_pc) : method(method), dex_pc(dex_pc) {}
Elliott Hughes86964332012-02-15 19:37:42 -080085};
86
Ian Rogers00f7d0e2012-07-19 15:28:27 -070087static std::ostream& operator<<(std::ostream& os, const Breakpoint& rhs)
Ian Rogersb726dcb2012-09-05 08:57:23 -070088 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes229feb72012-02-23 13:33:29 -080089 os << StringPrintf("Breakpoint[%s @%#x]", PrettyMethod(rhs.method).c_str(), rhs.dex_pc);
Elliott Hughes86964332012-02-15 19:37:42 -080090 return os;
91}
92
93struct SingleStepControl {
94 // Are we single-stepping right now?
95 bool is_active;
96 Thread* thread;
97
98 JDWP::JdwpStepSize step_size;
99 JDWP::JdwpStepDepth step_depth;
100
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800101 const mirror::AbstractMethod* method;
Elliott Hughes2435a572012-02-17 16:07:41 -0800102 int32_t line_number; // Or -1 for native methods.
103 std::set<uint32_t> dex_pcs;
Elliott Hughes86964332012-02-15 19:37:42 -0800104 int stack_depth;
105};
106
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700107// JDWP is allowed unless the Zygote forbids it.
108static bool gJdwpAllowed = true;
109
Elliott Hughesc0f09332012-03-26 13:27:06 -0700110// Was there a -Xrunjdwp or -agentlib:jdwp= argument on the command line?
Elliott Hughes3bb81562011-10-21 18:52:59 -0700111static bool gJdwpConfigured = false;
112
Elliott Hughesc0f09332012-03-26 13:27:06 -0700113// Broken-down JDWP options. (Only valid if IsJdwpConfigured() is true.)
Elliott Hughes376a7a02011-10-24 18:35:55 -0700114static JDWP::JdwpOptions gJdwpOptions;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700115
116// Runtime JDWP state.
117static JDWP::JdwpState* gJdwpState = NULL;
118static bool gDebuggerConnected; // debugger or DDMS is connected.
119static bool gDebuggerActive; // debugger is making requests.
Elliott Hughes86964332012-02-15 19:37:42 -0800120static bool gDisposed; // debugger called VirtualMachine.Dispose, so we should drop the connection.
Elliott Hughes3bb81562011-10-21 18:52:59 -0700121
Elliott Hughes47fce012011-10-25 18:37:19 -0700122static bool gDdmThreadNotification = false;
123
Elliott Hughes767a1472011-10-26 18:49:02 -0700124// DDMS GC-related settings.
125static Dbg::HpifWhen gDdmHpifWhen = Dbg::HPIF_WHEN_NEVER;
126static Dbg::HpsgWhen gDdmHpsgWhen = Dbg::HPSG_WHEN_NEVER;
127static Dbg::HpsgWhat gDdmHpsgWhat;
128static Dbg::HpsgWhen gDdmNhsgWhen = Dbg::HPSG_WHEN_NEVER;
129static Dbg::HpsgWhat gDdmNhsgWhat;
130
Elliott Hughes475fc232011-10-25 15:00:35 -0700131static ObjectRegistry* gRegistry = NULL;
132
Elliott Hughes545a0642011-11-08 19:10:03 -0800133// Recent allocation tracking.
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700134static Mutex gAllocTrackerLock DEFAULT_MUTEX_ACQUIRED_AFTER ("AllocTracker lock");
Elliott Hughesf8349362012-06-18 15:00:06 -0700135AllocRecord* Dbg::recent_allocation_records_ PT_GUARDED_BY(gAllocTrackerLock) = NULL; // TODO: CircularBuffer<AllocRecord>
136static size_t gAllocRecordHead GUARDED_BY(gAllocTrackerLock) = 0;
137static size_t gAllocRecordCount GUARDED_BY(gAllocTrackerLock) = 0;
Elliott Hughes545a0642011-11-08 19:10:03 -0800138
Elliott Hughes86964332012-02-15 19:37:42 -0800139// Breakpoints and single-stepping.
jeffhao09bfc6a2012-12-11 18:11:43 -0800140static std::vector<Breakpoint> gBreakpoints GUARDED_BY(Locks::breakpoint_lock_);
141static SingleStepControl gSingleStepControl GUARDED_BY(Locks::breakpoint_lock_);
Elliott Hughes86964332012-02-15 19:37:42 -0800142
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800143static bool IsBreakpoint(mirror::AbstractMethod* m, uint32_t dex_pc)
jeffhao09bfc6a2012-12-11 18:11:43 -0800144 LOCKS_EXCLUDED(Locks::breakpoint_lock_)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700145 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
jeffhao09bfc6a2012-12-11 18:11:43 -0800146 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Elliott Hughes86964332012-02-15 19:37:42 -0800147 for (size_t i = 0; i < gBreakpoints.size(); ++i) {
Elliott Hughesa656a0f2012-02-21 18:03:44 -0800148 if (gBreakpoints[i].method == m && gBreakpoints[i].dex_pc == dex_pc) {
Elliott Hughes86964332012-02-15 19:37:42 -0800149 VLOG(jdwp) << "Hit breakpoint #" << i << ": " << gBreakpoints[i];
150 return true;
151 }
152 }
153 return false;
154}
155
Elliott Hughes9e0c1752013-01-09 14:02:58 -0800156static bool IsSuspendedForDebugger(ScopedObjectAccessUnchecked& soa, Thread* thread) {
157 MutexLock mu(soa.Self(), *Locks::thread_suspend_count_lock_);
158 // A thread may be suspended for GC; in this code, we really want to know whether
159 // there's a debugger suspension active.
160 return thread->IsSuspended() && thread->GetDebugSuspendCount() > 0;
161}
162
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800163static mirror::Array* DecodeArray(JDWP::RefTypeId id, JDWP::JdwpError& status)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700164 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800165 mirror::Object* o = gRegistry->Get<mirror::Object*>(id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800166 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800167 status = JDWP::ERR_INVALID_OBJECT;
168 return NULL;
169 }
170 if (!o->IsArrayInstance()) {
171 status = JDWP::ERR_INVALID_ARRAY;
172 return NULL;
173 }
174 status = JDWP::ERR_NONE;
175 return o->AsArray();
176}
177
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800178static mirror::Class* DecodeClass(JDWP::RefTypeId id, JDWP::JdwpError& status)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700179 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800180 mirror::Object* o = gRegistry->Get<mirror::Object*>(id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800181 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800182 status = JDWP::ERR_INVALID_OBJECT;
183 return NULL;
184 }
185 if (!o->IsClass()) {
186 status = JDWP::ERR_INVALID_CLASS;
187 return NULL;
188 }
189 status = JDWP::ERR_NONE;
190 return o->AsClass();
191}
192
Elliott Hughes221229c2013-01-08 18:17:50 -0800193static JDWP::JdwpError DecodeThread(ScopedObjectAccessUnchecked& soa, JDWP::ObjectId thread_id, Thread*& thread)
jeffhaoa77f0f62012-12-05 17:19:31 -0800194 EXCLUSIVE_LOCKS_REQUIRED(Locks::thread_list_lock_)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700195 LOCKS_EXCLUDED(Locks::thread_suspend_count_lock_)
196 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800197 mirror::Object* thread_peer = gRegistry->Get<mirror::Object*>(thread_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800198 if (thread_peer == NULL || thread_peer == ObjectRegistry::kInvalidObject) {
Elliott Hughes221229c2013-01-08 18:17:50 -0800199 // This isn't even an object.
200 return JDWP::ERR_INVALID_OBJECT;
Elliott Hughes436e3722012-02-17 20:01:47 -0800201 }
Elliott Hughes221229c2013-01-08 18:17:50 -0800202
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800203 mirror::Class* java_lang_Thread = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_Thread);
Elliott Hughes221229c2013-01-08 18:17:50 -0800204 if (!java_lang_Thread->IsAssignableFrom(thread_peer->GetClass())) {
205 // This isn't a thread.
206 return JDWP::ERR_INVALID_THREAD;
207 }
208
209 thread = Thread::FromManagedThread(soa, thread_peer);
210 if (thread == NULL) {
211 // This is a java.lang.Thread without a Thread*. Must be a zombie.
212 return JDWP::ERR_THREAD_NOT_ALIVE;
213 }
214 return JDWP::ERR_NONE;
Elliott Hughes436e3722012-02-17 20:01:47 -0800215}
216
Elliott Hughes24437992011-11-30 14:49:33 -0800217static JDWP::JdwpTag BasicTagFromDescriptor(const char* descriptor) {
218 // JDWP deliberately uses the descriptor characters' ASCII values for its enum.
219 // Note that by "basic" we mean that we don't get more specific than JT_OBJECT.
220 return static_cast<JDWP::JdwpTag>(descriptor[0]);
221}
222
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800223static JDWP::JdwpTag TagFromClass(mirror::Class* c)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700224 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes86b00102011-12-05 17:54:26 -0800225 CHECK(c != NULL);
Elliott Hughes24437992011-11-30 14:49:33 -0800226 if (c->IsArrayClass()) {
227 return JDWP::JT_ARRAY;
228 }
229
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800230 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Elliott Hughes24437992011-11-30 14:49:33 -0800231 if (c->IsStringClass()) {
232 return JDWP::JT_STRING;
233 } else if (c->IsClassClass()) {
234 return JDWP::JT_CLASS_OBJECT;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800235 } else if (class_linker->FindSystemClass("Ljava/lang/Thread;")->IsAssignableFrom(c)) {
Elliott Hughes24437992011-11-30 14:49:33 -0800236 return JDWP::JT_THREAD;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800237 } else if (class_linker->FindSystemClass("Ljava/lang/ThreadGroup;")->IsAssignableFrom(c)) {
Elliott Hughes24437992011-11-30 14:49:33 -0800238 return JDWP::JT_THREAD_GROUP;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800239 } else if (class_linker->FindSystemClass("Ljava/lang/ClassLoader;")->IsAssignableFrom(c)) {
Elliott Hughes24437992011-11-30 14:49:33 -0800240 return JDWP::JT_CLASS_LOADER;
Elliott Hughes24437992011-11-30 14:49:33 -0800241 } else {
242 return JDWP::JT_OBJECT;
243 }
244}
245
246/*
247 * Objects declared to hold Object might actually hold a more specific
248 * type. The debugger may take a special interest in these (e.g. it
249 * wants to display the contents of Strings), so we want to return an
250 * appropriate tag.
251 *
252 * Null objects are tagged JT_OBJECT.
253 */
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800254static JDWP::JdwpTag TagFromObject(const mirror::Object* o)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700255 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes24437992011-11-30 14:49:33 -0800256 return (o == NULL) ? JDWP::JT_OBJECT : TagFromClass(o->GetClass());
257}
258
259static bool IsPrimitiveTag(JDWP::JdwpTag tag) {
260 switch (tag) {
261 case JDWP::JT_BOOLEAN:
262 case JDWP::JT_BYTE:
263 case JDWP::JT_CHAR:
264 case JDWP::JT_FLOAT:
265 case JDWP::JT_DOUBLE:
266 case JDWP::JT_INT:
267 case JDWP::JT_LONG:
268 case JDWP::JT_SHORT:
269 case JDWP::JT_VOID:
270 return true;
271 default:
272 return false;
273 }
274}
275
Elliott Hughes3bb81562011-10-21 18:52:59 -0700276/*
277 * Handle one of the JDWP name/value pairs.
278 *
279 * JDWP options are:
280 * help: if specified, show help message and bail
281 * transport: may be dt_socket or dt_shmem
282 * address: for dt_socket, "host:port", or just "port" when listening
283 * server: if "y", wait for debugger to attach; if "n", attach to debugger
284 * timeout: how long to wait for debugger to connect / listen
285 *
286 * Useful with server=n (these aren't supported yet):
287 * onthrow=<exception-name>: connect to debugger when exception thrown
288 * onuncaught=y|n: connect to debugger when uncaught exception thrown
289 * launch=<command-line>: launch the debugger itself
290 *
291 * The "transport" option is required, as is "address" if server=n.
292 */
293static bool ParseJdwpOption(const std::string& name, const std::string& value) {
294 if (name == "transport") {
295 if (value == "dt_socket") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700296 gJdwpOptions.transport = JDWP::kJdwpTransportSocket;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700297 } else if (value == "dt_android_adb") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700298 gJdwpOptions.transport = JDWP::kJdwpTransportAndroidAdb;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700299 } else {
300 LOG(ERROR) << "JDWP transport not supported: " << value;
301 return false;
302 }
303 } else if (name == "server") {
304 if (value == "n") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700305 gJdwpOptions.server = false;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700306 } else if (value == "y") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700307 gJdwpOptions.server = true;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700308 } else {
309 LOG(ERROR) << "JDWP option 'server' must be 'y' or 'n'";
310 return false;
311 }
312 } else if (name == "suspend") {
313 if (value == "n") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700314 gJdwpOptions.suspend = false;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700315 } else if (value == "y") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700316 gJdwpOptions.suspend = true;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700317 } else {
318 LOG(ERROR) << "JDWP option 'suspend' must be 'y' or 'n'";
319 return false;
320 }
321 } else if (name == "address") {
322 /* this is either <port> or <host>:<port> */
323 std::string port_string;
Elliott Hughes376a7a02011-10-24 18:35:55 -0700324 gJdwpOptions.host.clear();
Elliott Hughes3bb81562011-10-21 18:52:59 -0700325 std::string::size_type colon = value.find(':');
326 if (colon != std::string::npos) {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700327 gJdwpOptions.host = value.substr(0, colon);
Elliott Hughes3bb81562011-10-21 18:52:59 -0700328 port_string = value.substr(colon + 1);
329 } else {
330 port_string = value;
331 }
332 if (port_string.empty()) {
333 LOG(ERROR) << "JDWP address missing port: " << value;
334 return false;
335 }
336 char* end;
Elliott Hughesba8eee12012-01-24 20:25:24 -0800337 uint64_t port = strtoul(port_string.c_str(), &end, 10);
338 if (*end != '\0' || port > 0xffff) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700339 LOG(ERROR) << "JDWP address has junk in port field: " << value;
340 return false;
341 }
Elliott Hughes376a7a02011-10-24 18:35:55 -0700342 gJdwpOptions.port = port;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700343 } else if (name == "launch" || name == "onthrow" || name == "oncaught" || name == "timeout") {
344 /* valid but unsupported */
345 LOG(INFO) << "Ignoring JDWP option '" << name << "'='" << value << "'";
346 } else {
347 LOG(INFO) << "Ignoring unrecognized JDWP option '" << name << "'='" << value << "'";
348 }
349
350 return true;
351}
352
353/*
354 * Parse the latter half of a -Xrunjdwp/-agentlib:jdwp= string, e.g.:
355 * "transport=dt_socket,address=8000,server=y,suspend=n"
356 */
357bool Dbg::ParseJdwpOptions(const std::string& options) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800358 VLOG(jdwp) << "ParseJdwpOptions: " << options;
Elliott Hughes47fce012011-10-25 18:37:19 -0700359
Elliott Hughes3bb81562011-10-21 18:52:59 -0700360 std::vector<std::string> pairs;
361 Split(options, ',', pairs);
362
363 for (size_t i = 0; i < pairs.size(); ++i) {
364 std::string::size_type equals = pairs[i].find('=');
365 if (equals == std::string::npos) {
366 LOG(ERROR) << "Can't parse JDWP option '" << pairs[i] << "' in '" << options << "'";
367 return false;
368 }
369 ParseJdwpOption(pairs[i].substr(0, equals), pairs[i].substr(equals + 1));
370 }
371
Elliott Hughes376a7a02011-10-24 18:35:55 -0700372 if (gJdwpOptions.transport == JDWP::kJdwpTransportUnknown) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700373 LOG(ERROR) << "Must specify JDWP transport: " << options;
374 }
Elliott Hughes376a7a02011-10-24 18:35:55 -0700375 if (!gJdwpOptions.server && (gJdwpOptions.host.empty() || gJdwpOptions.port == 0)) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700376 LOG(ERROR) << "Must specify JDWP host and port when server=n: " << options;
377 return false;
378 }
379
380 gJdwpConfigured = true;
381 return true;
382}
383
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700384void Dbg::StartJdwp() {
Elliott Hughesc0f09332012-03-26 13:27:06 -0700385 if (!gJdwpAllowed || !IsJdwpConfigured()) {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700386 // No JDWP for you!
387 return;
388 }
389
Elliott Hughes475fc232011-10-25 15:00:35 -0700390 CHECK(gRegistry == NULL);
391 gRegistry = new ObjectRegistry;
392
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700393 // Init JDWP if the debugger is enabled. This may connect out to a
394 // debugger, passively listen for a debugger, or block waiting for a
395 // debugger.
Elliott Hughes376a7a02011-10-24 18:35:55 -0700396 gJdwpState = JDWP::JdwpState::Create(&gJdwpOptions);
397 if (gJdwpState == NULL) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -0800398 // We probably failed because some other process has the port already, which means that
399 // if we don't abort the user is likely to think they're talking to us when they're actually
400 // talking to that other process.
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800401 LOG(FATAL) << "Debugger thread failed to initialize";
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700402 }
403
404 // If a debugger has already attached, send the "welcome" message.
405 // This may cause us to suspend all threads.
Elliott Hughes376a7a02011-10-24 18:35:55 -0700406 if (gJdwpState->IsActive()) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700407 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes376a7a02011-10-24 18:35:55 -0700408 if (!gJdwpState->PostVMStart()) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800409 LOG(WARNING) << "Failed to post 'start' message to debugger";
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700410 }
411 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700412}
413
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700414void Dbg::StopJdwp() {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700415 delete gJdwpState;
Elliott Hughes475fc232011-10-25 15:00:35 -0700416 delete gRegistry;
417 gRegistry = NULL;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700418}
419
Elliott Hughes767a1472011-10-26 18:49:02 -0700420void Dbg::GcDidFinish() {
421 if (gDdmHpifWhen != HPIF_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700422 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes81ff3182012-03-23 20:35:56 -0700423 LOG(DEBUG) << "Sending heap info to DDM";
Elliott Hughes7162ad92011-10-27 14:08:42 -0700424 DdmSendHeapInfo(gDdmHpifWhen);
Elliott Hughes767a1472011-10-26 18:49:02 -0700425 }
426 if (gDdmHpsgWhen != HPSG_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700427 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes81ff3182012-03-23 20:35:56 -0700428 LOG(DEBUG) << "Dumping heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700429 DdmSendHeapSegments(false);
Elliott Hughes767a1472011-10-26 18:49:02 -0700430 }
431 if (gDdmNhsgWhen != HPSG_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700432 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes767a1472011-10-26 18:49:02 -0700433 LOG(DEBUG) << "Dumping native heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700434 DdmSendHeapSegments(true);
Elliott Hughes767a1472011-10-26 18:49:02 -0700435 }
436}
437
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700438void Dbg::SetJdwpAllowed(bool allowed) {
439 gJdwpAllowed = allowed;
440}
441
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700442DebugInvokeReq* Dbg::GetInvokeReq() {
Elliott Hughes475fc232011-10-25 15:00:35 -0700443 return Thread::Current()->GetInvokeReq();
444}
445
446Thread* Dbg::GetDebugThread() {
447 return (gJdwpState != NULL) ? gJdwpState->GetDebugThread() : NULL;
448}
449
450void Dbg::ClearWaitForEventThread() {
451 gJdwpState->ClearWaitForEventThread();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700452}
453
454void Dbg::Connected() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700455 CHECK(!gDebuggerConnected);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800456 VLOG(jdwp) << "JDWP has attached";
Elliott Hughes3bb81562011-10-21 18:52:59 -0700457 gDebuggerConnected = true;
Elliott Hughes86964332012-02-15 19:37:42 -0800458 gDisposed = false;
459}
460
461void Dbg::Disposed() {
462 gDisposed = true;
463}
464
465bool Dbg::IsDisposed() {
466 return gDisposed;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700467}
468
Elliott Hughesc0f09332012-03-26 13:27:06 -0700469static void SetDebuggerUpdatesEnabledCallback(Thread* t, void* user_data) {
470 t->SetDebuggerUpdatesEnabled(*reinterpret_cast<bool*>(user_data));
471}
472
473static void SetDebuggerUpdatesEnabled(bool enabled) {
Ian Rogers50b35e22012-10-04 10:09:15 -0700474 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
Elliott Hughesf8349362012-06-18 15:00:06 -0700475 Runtime::Current()->GetThreadList()->ForEach(SetDebuggerUpdatesEnabledCallback, &enabled);
Elliott Hughesc0f09332012-03-26 13:27:06 -0700476}
477
Elliott Hughesa2155262011-11-16 16:26:58 -0800478void Dbg::GoActive() {
479 // Enable all debugging features, including scans for breakpoints.
480 // This is a no-op if we're already active.
481 // Only called from the JDWP handler thread.
482 if (gDebuggerActive) {
483 return;
484 }
485
486 LOG(INFO) << "Debugger is active";
487
Elliott Hughesc0f09332012-03-26 13:27:06 -0700488 {
489 // TODO: dalvik only warned if there were breakpoints left over. clear in Dbg::Disconnected?
jeffhao09bfc6a2012-12-11 18:11:43 -0800490 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Elliott Hughesc0f09332012-03-26 13:27:06 -0700491 CHECK_EQ(gBreakpoints.size(), 0U);
492 }
Elliott Hughesa2155262011-11-16 16:26:58 -0800493
494 gDebuggerActive = true;
Elliott Hughesc0f09332012-03-26 13:27:06 -0700495 SetDebuggerUpdatesEnabled(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700496}
497
498void Dbg::Disconnected() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700499 CHECK(gDebuggerConnected);
500
Elliott Hughesc0f09332012-03-26 13:27:06 -0700501 LOG(INFO) << "Debugger is no longer active";
Elliott Hughes234ab152011-10-26 14:02:26 -0700502
Elliott Hughesc0f09332012-03-26 13:27:06 -0700503 gDebuggerActive = false;
504 SetDebuggerUpdatesEnabled(false);
Elliott Hughes234ab152011-10-26 14:02:26 -0700505
506 gRegistry->Clear();
507 gDebuggerConnected = false;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700508}
509
Elliott Hughesc0f09332012-03-26 13:27:06 -0700510bool Dbg::IsDebuggerActive() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700511 return gDebuggerActive;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700512}
513
Elliott Hughesc0f09332012-03-26 13:27:06 -0700514bool Dbg::IsJdwpConfigured() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700515 return gJdwpConfigured;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700516}
517
518int64_t Dbg::LastDebuggerActivity() {
Elliott Hughesca951522011-12-05 12:01:32 -0800519 return gJdwpState->LastDebuggerActivity();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700520}
521
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700522void Dbg::UndoDebuggerSuspensions() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700523 Runtime::Current()->GetThreadList()->UndoDebuggerSuspensions();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700524}
525
Elliott Hughes88d63092013-01-09 09:55:54 -0800526std::string Dbg::GetClassName(JDWP::RefTypeId class_id) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800527 mirror::Object* o = gRegistry->Get<mirror::Object*>(class_id);
Elliott Hughes436e3722012-02-17 20:01:47 -0800528 if (o == NULL) {
529 return "NULL";
530 }
Elliott Hughes64f574f2013-02-20 14:57:12 -0800531 if (o == ObjectRegistry::kInvalidObject) {
Elliott Hughes88d63092013-01-09 09:55:54 -0800532 return StringPrintf("invalid object %p", reinterpret_cast<void*>(class_id));
Elliott Hughes436e3722012-02-17 20:01:47 -0800533 }
534 if (!o->IsClass()) {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800535 return StringPrintf("non-class %p", o); // This is only used for debugging output anyway.
536 }
Elliott Hughesc308a5d2012-02-16 17:12:06 -0800537 return DescriptorToName(ClassHelper(o->AsClass()).GetDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700538}
539
Elliott Hughes88d63092013-01-09 09:55:54 -0800540JDWP::JdwpError Dbg::GetClassObject(JDWP::RefTypeId id, JDWP::ObjectId& class_object_id) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800541 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800542 mirror::Class* c = DecodeClass(id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -0800543 if (c == NULL) {
544 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800545 }
Elliott Hughes88d63092013-01-09 09:55:54 -0800546 class_object_id = gRegistry->Add(c);
Elliott Hughes436e3722012-02-17 20:01:47 -0800547 return JDWP::ERR_NONE;
Elliott Hughes86964332012-02-15 19:37:42 -0800548}
549
Elliott Hughes88d63092013-01-09 09:55:54 -0800550JDWP::JdwpError Dbg::GetSuperclass(JDWP::RefTypeId id, JDWP::RefTypeId& superclass_id) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800551 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800552 mirror::Class* c = DecodeClass(id, status);
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800553 if (c == NULL) {
554 return status;
555 }
556 if (c->IsInterface()) {
557 // http://code.google.com/p/android/issues/detail?id=20856
Elliott Hughes88d63092013-01-09 09:55:54 -0800558 superclass_id = 0;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800559 } else {
Elliott Hughes88d63092013-01-09 09:55:54 -0800560 superclass_id = gRegistry->Add(c->GetSuperClass());
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800561 }
562 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700563}
564
Elliott Hughes436e3722012-02-17 20:01:47 -0800565JDWP::JdwpError Dbg::GetClassLoader(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800566 mirror::Object* o = gRegistry->Get<mirror::Object*>(id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800567 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800568 return JDWP::ERR_INVALID_OBJECT;
569 }
570 expandBufAddObjectId(pReply, gRegistry->Add(o->GetClass()->GetClassLoader()));
571 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700572}
573
Elliott Hughes436e3722012-02-17 20:01:47 -0800574JDWP::JdwpError Dbg::GetModifiers(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) {
575 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800576 mirror::Class* c = DecodeClass(id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -0800577 if (c == NULL) {
578 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800579 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800580
581 uint32_t access_flags = c->GetAccessFlags() & kAccJavaFlagsMask;
582
583 // Set ACC_SUPER; dex files don't contain this flag, but all classes are supposed to have it set.
584 // Class.getModifiers doesn't return it, but JDWP does, so we set it here.
585 access_flags |= kAccSuper;
586
587 expandBufAdd4BE(pReply, access_flags);
588
589 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700590}
591
Elliott Hughesf327e072013-01-09 16:01:26 -0800592JDWP::JdwpError Dbg::GetMonitorInfo(JDWP::ObjectId object_id, JDWP::ExpandBuf* reply)
593 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800594 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800595 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughesf327e072013-01-09 16:01:26 -0800596 return JDWP::ERR_INVALID_OBJECT;
597 }
598
599 // Ensure all threads are suspended while we read objects' lock words.
600 Thread* self = Thread::Current();
601 Locks::mutator_lock_->SharedUnlock(self);
602 Locks::mutator_lock_->ExclusiveLock(self);
603
604 MonitorInfo monitor_info(o);
605
606 Locks::mutator_lock_->ExclusiveUnlock(self);
607 Locks::mutator_lock_->SharedLock(self);
608
609 if (monitor_info.owner != NULL) {
610 expandBufAddObjectId(reply, gRegistry->Add(monitor_info.owner->GetPeer()));
611 } else {
612 expandBufAddObjectId(reply, gRegistry->Add(NULL));
613 }
614 expandBufAdd4BE(reply, monitor_info.entry_count);
615 expandBufAdd4BE(reply, monitor_info.waiters.size());
616 for (size_t i = 0; i < monitor_info.waiters.size(); ++i) {
617 expandBufAddObjectId(reply, gRegistry->Add(monitor_info.waiters[i]->GetPeer()));
618 }
619 return JDWP::ERR_NONE;
620}
621
Elliott Hughes734b8c62013-01-11 15:32:45 -0800622JDWP::JdwpError Dbg::GetOwnedMonitors(JDWP::ObjectId thread_id,
623 std::vector<JDWP::ObjectId>& monitors,
624 std::vector<uint32_t>& stack_depths)
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800625 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
626 ScopedObjectAccessUnchecked soa(Thread::Current());
627 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
628 Thread* thread;
629 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
630 if (error != JDWP::ERR_NONE) {
631 return error;
632 }
633 if (!IsSuspendedForDebugger(soa, thread)) {
634 return JDWP::ERR_THREAD_NOT_SUSPENDED;
635 }
636
637 struct OwnedMonitorVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -0800638 OwnedMonitorVisitor(Thread* thread, Context* context)
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800639 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -0800640 : StackVisitor(thread, context), current_stack_depth(0) {}
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800641
642 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
643 // annotalysis.
644 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
645 if (!GetMethod()->IsRuntimeMethod()) {
646 Monitor::VisitLocks(this, AppendOwnedMonitors, this);
Elliott Hughes734b8c62013-01-11 15:32:45 -0800647 ++current_stack_depth;
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800648 }
649 return true;
650 }
651
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800652 static void AppendOwnedMonitors(mirror::Object* owned_monitor, void* arg) {
Ian Rogers7a22fa62013-01-23 12:16:16 -0800653 OwnedMonitorVisitor* visitor = reinterpret_cast<OwnedMonitorVisitor*>(arg);
Elliott Hughes734b8c62013-01-11 15:32:45 -0800654 visitor->monitors.push_back(owned_monitor);
655 visitor->stack_depths.push_back(visitor->current_stack_depth);
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800656 }
657
Elliott Hughes734b8c62013-01-11 15:32:45 -0800658 size_t current_stack_depth;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800659 std::vector<mirror::Object*> monitors;
Elliott Hughes734b8c62013-01-11 15:32:45 -0800660 std::vector<uint32_t> stack_depths;
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800661 };
Ian Rogers7a22fa62013-01-23 12:16:16 -0800662 UniquePtr<Context> context(Context::Create());
663 OwnedMonitorVisitor visitor(thread, context.get());
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800664 visitor.WalkStack();
665
666 for (size_t i = 0; i < visitor.monitors.size(); ++i) {
667 monitors.push_back(gRegistry->Add(visitor.monitors[i]));
Elliott Hughes734b8c62013-01-11 15:32:45 -0800668 stack_depths.push_back(visitor.stack_depths[i]);
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800669 }
670
671 return JDWP::ERR_NONE;
672}
673
Elliott Hughesf9501702013-01-11 11:22:27 -0800674JDWP::JdwpError Dbg::GetContendedMonitor(JDWP::ObjectId thread_id, JDWP::ObjectId& contended_monitor)
675 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
676 ScopedObjectAccessUnchecked soa(Thread::Current());
677 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
678 Thread* thread;
679 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
680 if (error != JDWP::ERR_NONE) {
681 return error;
682 }
683 if (!IsSuspendedForDebugger(soa, thread)) {
684 return JDWP::ERR_THREAD_NOT_SUSPENDED;
685 }
686
687 contended_monitor = gRegistry->Add(Monitor::GetContendedMonitor(thread));
688
689 return JDWP::ERR_NONE;
690}
691
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800692JDWP::JdwpError Dbg::GetInstanceCounts(const std::vector<JDWP::RefTypeId>& class_ids,
693 std::vector<uint64_t>& counts)
694 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
695
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800696 std::vector<mirror::Class*> classes;
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800697 counts.clear();
698 for (size_t i = 0; i < class_ids.size(); ++i) {
699 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800700 mirror::Class* c = DecodeClass(class_ids[i], status);
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800701 if (c == NULL) {
702 return status;
703 }
704 classes.push_back(c);
705 counts.push_back(0);
706 }
707
708 Runtime::Current()->GetHeap()->CountInstances(classes, false, &counts[0]);
709 return JDWP::ERR_NONE;
710}
711
Elliott Hughes3b78c942013-01-15 17:35:41 -0800712JDWP::JdwpError Dbg::GetInstances(JDWP::RefTypeId class_id, int32_t max_count, std::vector<JDWP::ObjectId>& instances)
713 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
714 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800715 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes3b78c942013-01-15 17:35:41 -0800716 if (c == NULL) {
717 return status;
718 }
719
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800720 std::vector<mirror::Object*> raw_instances;
Elliott Hughes3b78c942013-01-15 17:35:41 -0800721 Runtime::Current()->GetHeap()->GetInstances(c, max_count, raw_instances);
722 for (size_t i = 0; i < raw_instances.size(); ++i) {
723 instances.push_back(gRegistry->Add(raw_instances[i]));
724 }
725 return JDWP::ERR_NONE;
726}
727
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800728JDWP::JdwpError Dbg::GetReferringObjects(JDWP::ObjectId object_id, int32_t max_count,
729 std::vector<JDWP::ObjectId>& referring_objects)
730 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800731 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800732 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800733 return JDWP::ERR_INVALID_OBJECT;
734 }
735
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800736 std::vector<mirror::Object*> raw_instances;
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800737 Runtime::Current()->GetHeap()->GetReferringObjects(o, max_count, raw_instances);
738 for (size_t i = 0; i < raw_instances.size(); ++i) {
739 referring_objects.push_back(gRegistry->Add(raw_instances[i]));
740 }
741 return JDWP::ERR_NONE;
742}
743
Elliott Hughes64f574f2013-02-20 14:57:12 -0800744JDWP::JdwpError Dbg::DisableCollection(JDWP::ObjectId object_id)
745 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
746 gRegistry->DisableCollection(object_id);
747 return JDWP::ERR_NONE;
748}
749
750JDWP::JdwpError Dbg::EnableCollection(JDWP::ObjectId object_id)
751 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
752 gRegistry->EnableCollection(object_id);
753 return JDWP::ERR_NONE;
754}
755
756JDWP::JdwpError Dbg::IsCollected(JDWP::ObjectId object_id, bool& is_collected)
757 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
758 is_collected = gRegistry->IsCollected(object_id);
759 return JDWP::ERR_NONE;
760}
761
762void Dbg::DisposeObject(JDWP::ObjectId object_id, uint32_t reference_count)
763 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
764 gRegistry->DisposeObject(object_id, reference_count);
765}
766
Elliott Hughes88d63092013-01-09 09:55:54 -0800767JDWP::JdwpError Dbg::GetReflectedType(JDWP::RefTypeId class_id, JDWP::ExpandBuf* pReply) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800768 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800769 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -0800770 if (c == NULL) {
771 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800772 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800773
774 expandBufAdd1(pReply, c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS);
Elliott Hughes88d63092013-01-09 09:55:54 -0800775 expandBufAddRefTypeId(pReply, class_id);
Elliott Hughes436e3722012-02-17 20:01:47 -0800776 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700777}
778
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800779void Dbg::GetClassList(std::vector<JDWP::RefTypeId>& classes) {
Elliott Hughesa2155262011-11-16 16:26:58 -0800780 // Get the complete list of reference classes (i.e. all classes except
781 // the primitive types).
782 // Returns a newly-allocated buffer full of RefTypeId values.
783 struct ClassListCreator {
Elliott Hughesba8eee12012-01-24 20:25:24 -0800784 explicit ClassListCreator(std::vector<JDWP::RefTypeId>& classes) : classes(classes) {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800785 }
786
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800787 static bool Visit(mirror::Class* c, void* arg) {
Elliott Hughesa2155262011-11-16 16:26:58 -0800788 return reinterpret_cast<ClassListCreator*>(arg)->Visit(c);
789 }
790
Elliott Hughes64f574f2013-02-20 14:57:12 -0800791 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
792 // annotalysis.
793 bool Visit(mirror::Class* c) NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughesa2155262011-11-16 16:26:58 -0800794 if (!c->IsPrimitive()) {
Elliott Hughes64f574f2013-02-20 14:57:12 -0800795 classes.push_back(gRegistry->AddRefType(c));
Elliott Hughesa2155262011-11-16 16:26:58 -0800796 }
797 return true;
798 }
799
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800800 std::vector<JDWP::RefTypeId>& classes;
Elliott Hughesa2155262011-11-16 16:26:58 -0800801 };
802
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800803 ClassListCreator clc(classes);
Elliott Hughesa2155262011-11-16 16:26:58 -0800804 Runtime::Current()->GetClassLinker()->VisitClasses(ClassListCreator::Visit, &clc);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700805}
806
Elliott Hughes88d63092013-01-09 09:55:54 -0800807JDWP::JdwpError Dbg::GetClassInfo(JDWP::RefTypeId class_id, JDWP::JdwpTypeTag* pTypeTag, uint32_t* pStatus, std::string* pDescriptor) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800808 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800809 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -0800810 if (c == NULL) {
811 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800812 }
813
Elliott Hughesa2155262011-11-16 16:26:58 -0800814 if (c->IsArrayClass()) {
815 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
816 *pTypeTag = JDWP::TT_ARRAY;
817 } else {
818 if (c->IsErroneous()) {
819 *pStatus = JDWP::CS_ERROR;
820 } else {
821 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED | JDWP::CS_INITIALIZED;
822 }
823 *pTypeTag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
824 }
825
826 if (pDescriptor != NULL) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800827 *pDescriptor = ClassHelper(c).GetDescriptor();
Elliott Hughesa2155262011-11-16 16:26:58 -0800828 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800829 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700830}
831
Elliott Hughesc3b77c72011-12-15 20:56:48 -0800832void Dbg::FindLoadedClassBySignature(const char* descriptor, std::vector<JDWP::RefTypeId>& ids) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800833 std::vector<mirror::Class*> classes;
Elliott Hughes6fa602d2011-12-02 17:54:25 -0800834 Runtime::Current()->GetClassLinker()->LookupClasses(descriptor, classes);
835 ids.clear();
836 for (size_t i = 0; i < classes.size(); ++i) {
837 ids.push_back(gRegistry->Add(classes[i]));
838 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700839}
840
Elliott Hughes64f574f2013-02-20 14:57:12 -0800841JDWP::JdwpError Dbg::GetReferenceType(JDWP::ObjectId object_id, JDWP::ExpandBuf* pReply)
842 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800843 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800844 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes2435a572012-02-17 16:07:41 -0800845 return JDWP::ERR_INVALID_OBJECT;
Elliott Hughes499c5132011-11-17 14:55:11 -0800846 }
Elliott Hughes2435a572012-02-17 16:07:41 -0800847
848 JDWP::JdwpTypeTag type_tag;
849 if (o->GetClass()->IsArrayClass()) {
850 type_tag = JDWP::TT_ARRAY;
851 } else if (o->GetClass()->IsInterface()) {
852 type_tag = JDWP::TT_INTERFACE;
853 } else {
854 type_tag = JDWP::TT_CLASS;
855 }
Elliott Hughes64f574f2013-02-20 14:57:12 -0800856 JDWP::RefTypeId type_id = gRegistry->AddRefType(o->GetClass());
Elliott Hughes2435a572012-02-17 16:07:41 -0800857
858 expandBufAdd1(pReply, type_tag);
859 expandBufAddRefTypeId(pReply, type_id);
860
861 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700862}
863
Elliott Hughes88d63092013-01-09 09:55:54 -0800864JDWP::JdwpError Dbg::GetSignature(JDWP::RefTypeId class_id, std::string& signature) {
Elliott Hughes1fe7afb2012-02-13 17:23:03 -0800865 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800866 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes1fe7afb2012-02-13 17:23:03 -0800867 if (c == NULL) {
868 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800869 }
Elliott Hughes1fe7afb2012-02-13 17:23:03 -0800870 signature = ClassHelper(c).GetDescriptor();
871 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700872}
873
Elliott Hughes88d63092013-01-09 09:55:54 -0800874JDWP::JdwpError Dbg::GetSourceFile(JDWP::RefTypeId class_id, std::string& result) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800875 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800876 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -0800877 if (c == NULL) {
878 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800879 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800880 result = ClassHelper(c).GetSourceFile();
881 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700882}
883
Elliott Hughes88d63092013-01-09 09:55:54 -0800884JDWP::JdwpError Dbg::GetObjectTag(JDWP::ObjectId object_id, uint8_t& tag) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800885 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800886 if (o == ObjectRegistry::kInvalidObject) {
Elliott Hughes546b9862012-06-20 16:06:13 -0700887 return JDWP::ERR_INVALID_OBJECT;
888 }
889 tag = TagFromObject(o);
890 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700891}
892
Elliott Hughesaed4be92011-12-02 16:16:23 -0800893size_t Dbg::GetTagWidth(JDWP::JdwpTag tag) {
Elliott Hughesdbb40792011-11-18 17:05:22 -0800894 switch (tag) {
895 case JDWP::JT_VOID:
896 return 0;
897 case JDWP::JT_BYTE:
898 case JDWP::JT_BOOLEAN:
899 return 1;
900 case JDWP::JT_CHAR:
901 case JDWP::JT_SHORT:
902 return 2;
903 case JDWP::JT_FLOAT:
904 case JDWP::JT_INT:
905 return 4;
906 case JDWP::JT_ARRAY:
907 case JDWP::JT_OBJECT:
908 case JDWP::JT_STRING:
909 case JDWP::JT_THREAD:
910 case JDWP::JT_THREAD_GROUP:
911 case JDWP::JT_CLASS_LOADER:
912 case JDWP::JT_CLASS_OBJECT:
913 return sizeof(JDWP::ObjectId);
914 case JDWP::JT_DOUBLE:
915 case JDWP::JT_LONG:
916 return 8;
917 default:
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800918 LOG(FATAL) << "Unknown tag " << tag;
Elliott Hughesdbb40792011-11-18 17:05:22 -0800919 return -1;
920 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700921}
922
Elliott Hughes88d63092013-01-09 09:55:54 -0800923JDWP::JdwpError Dbg::GetArrayLength(JDWP::ObjectId array_id, int& length) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800924 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800925 mirror::Array* a = DecodeArray(array_id, status);
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800926 if (a == NULL) {
927 return status;
Elliott Hughes24437992011-11-30 14:49:33 -0800928 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800929 length = a->GetLength();
930 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700931}
932
Elliott Hughes88d63092013-01-09 09:55:54 -0800933JDWP::JdwpError Dbg::OutputArray(JDWP::ObjectId array_id, int offset, int count, JDWP::ExpandBuf* pReply) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800934 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800935 mirror::Array* a = DecodeArray(array_id, status);
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800936 if (a == NULL) {
937 return status;
938 }
Elliott Hughes24437992011-11-30 14:49:33 -0800939
940 if (offset < 0 || count < 0 || offset > a->GetLength() || a->GetLength() - offset < count) {
941 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800942 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughes24437992011-11-30 14:49:33 -0800943 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800944 std::string descriptor(ClassHelper(a->GetClass()).GetDescriptor());
Elliott Hughes24437992011-11-30 14:49:33 -0800945 JDWP::JdwpTag tag = BasicTagFromDescriptor(descriptor.c_str() + 1);
946
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800947 expandBufAdd1(pReply, tag);
948 expandBufAdd4BE(pReply, count);
949
Elliott Hughes24437992011-11-30 14:49:33 -0800950 if (IsPrimitiveTag(tag)) {
951 size_t width = GetTagWidth(tag);
Elliott Hughes24437992011-11-30 14:49:33 -0800952 uint8_t* dst = expandBufAddSpace(pReply, count * width);
953 if (width == 8) {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800954 const uint64_t* src8 = reinterpret_cast<uint64_t*>(a->GetRawData(sizeof(uint64_t)));
Elliott Hughes24437992011-11-30 14:49:33 -0800955 for (int i = 0; i < count; ++i) JDWP::Write8BE(&dst, src8[offset + i]);
956 } else if (width == 4) {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800957 const uint32_t* src4 = reinterpret_cast<uint32_t*>(a->GetRawData(sizeof(uint32_t)));
Elliott Hughes24437992011-11-30 14:49:33 -0800958 for (int i = 0; i < count; ++i) JDWP::Write4BE(&dst, src4[offset + i]);
959 } else if (width == 2) {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800960 const uint16_t* src2 = reinterpret_cast<uint16_t*>(a->GetRawData(sizeof(uint16_t)));
Elliott Hughes24437992011-11-30 14:49:33 -0800961 for (int i = 0; i < count; ++i) JDWP::Write2BE(&dst, src2[offset + i]);
962 } else {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800963 const uint8_t* src = reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint8_t)));
Elliott Hughes24437992011-11-30 14:49:33 -0800964 memcpy(dst, &src[offset * width], count * width);
965 }
966 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800967 mirror::ObjectArray<mirror::Object>* oa = a->AsObjectArray<mirror::Object>();
Elliott Hughes24437992011-11-30 14:49:33 -0800968 for (int i = 0; i < count; ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800969 mirror::Object* element = oa->Get(offset + i);
Elliott Hughes24437992011-11-30 14:49:33 -0800970 JDWP::JdwpTag specific_tag = (element != NULL) ? TagFromObject(element) : tag;
971 expandBufAdd1(pReply, specific_tag);
972 expandBufAddObjectId(pReply, gRegistry->Add(element));
973 }
974 }
975
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800976 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700977}
978
Elliott Hughes4b9702c2013-02-20 18:13:24 -0800979template <typename T> void CopyArrayData(mirror::Array* a, JDWP::Request& src, int offset, int count) {
980 DCHECK(a->GetClass()->IsPrimitiveArray());
981
982 T* dst = &(reinterpret_cast<T*>(a->GetRawData(sizeof(T)))[offset * sizeof(T)]);
983 for (int i = 0; i < count; ++i) {
984 *dst++ = src.ReadValue(sizeof(T));
985 }
986}
987
Elliott Hughes88d63092013-01-09 09:55:54 -0800988JDWP::JdwpError Dbg::SetArrayElements(JDWP::ObjectId array_id, int offset, int count,
Elliott Hughes4b9702c2013-02-20 18:13:24 -0800989 JDWP::Request& request)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700990 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800991 JDWP::JdwpError status;
Elliott Hughes4b9702c2013-02-20 18:13:24 -0800992 mirror::Array* dst = DecodeArray(array_id, status);
993 if (dst == NULL) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800994 return status;
995 }
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800996
Elliott Hughes4b9702c2013-02-20 18:13:24 -0800997 if (offset < 0 || count < 0 || offset > dst->GetLength() || dst->GetLength() - offset < count) {
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800998 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800999 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001000 }
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001001 std::string descriptor(ClassHelper(dst->GetClass()).GetDescriptor());
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001002 JDWP::JdwpTag tag = BasicTagFromDescriptor(descriptor.c_str() + 1);
1003
1004 if (IsPrimitiveTag(tag)) {
1005 size_t width = GetTagWidth(tag);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001006 if (width == 8) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001007 CopyArrayData<uint64_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001008 } else if (width == 4) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001009 CopyArrayData<uint32_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001010 } else if (width == 2) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001011 CopyArrayData<uint16_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001012 } else {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001013 CopyArrayData<uint8_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001014 }
1015 } else {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001016 mirror::ObjectArray<mirror::Object>* oa = dst->AsObjectArray<mirror::Object>();
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001017 for (int i = 0; i < count; ++i) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001018 JDWP::ObjectId id = request.ReadObjectId();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001019 mirror::Object* o = gRegistry->Get<mirror::Object*>(id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001020 if (o == ObjectRegistry::kInvalidObject) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001021 return JDWP::ERR_INVALID_OBJECT;
1022 }
1023 oa->Set(offset + i, o);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001024 }
1025 }
1026
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001027 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001028}
1029
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001030JDWP::ObjectId Dbg::CreateString(const std::string& str) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001031 return gRegistry->Add(mirror::String::AllocFromModifiedUtf8(Thread::Current(), str.c_str()));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001032}
1033
Elliott Hughes88d63092013-01-09 09:55:54 -08001034JDWP::JdwpError Dbg::CreateObject(JDWP::RefTypeId class_id, JDWP::ObjectId& new_object) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001035 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001036 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001037 if (c == NULL) {
1038 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001039 }
Ian Rogers50b35e22012-10-04 10:09:15 -07001040 new_object = gRegistry->Add(c->AllocObject(Thread::Current()));
Elliott Hughes436e3722012-02-17 20:01:47 -08001041 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001042}
1043
Elliott Hughesbf13d362011-12-08 15:51:37 -08001044/*
1045 * Used by Eclipse's "Display" view to evaluate "new byte[5]" to get "(byte[]) [0, 0, 0, 0, 0]".
1046 */
Elliott Hughes88d63092013-01-09 09:55:54 -08001047JDWP::JdwpError Dbg::CreateArrayObject(JDWP::RefTypeId array_class_id, uint32_t length,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001048 JDWP::ObjectId& new_array) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001049 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001050 mirror::Class* c = DecodeClass(array_class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001051 if (c == NULL) {
1052 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001053 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001054 new_array = gRegistry->Add(mirror::Array::Alloc(Thread::Current(), c, length));
Elliott Hughes436e3722012-02-17 20:01:47 -08001055 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001056}
1057
Elliott Hughes88d63092013-01-09 09:55:54 -08001058bool Dbg::MatchType(JDWP::RefTypeId instance_class_id, JDWP::RefTypeId class_id) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001059 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001060 mirror::Class* c1 = DecodeClass(instance_class_id, status);
Elliott Hughesa656a0f2012-02-21 18:03:44 -08001061 CHECK(c1 != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001062 mirror::Class* c2 = DecodeClass(class_id, status);
Elliott Hughesa656a0f2012-02-21 18:03:44 -08001063 CHECK(c2 != NULL);
1064 return c1->IsAssignableFrom(c2);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001065}
1066
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001067static JDWP::FieldId ToFieldId(const mirror::Field* f)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001068 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001069#ifdef MOVING_GARBAGE_COLLECTOR
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001070 UNIMPLEMENTED(FATAL);
Elliott Hughes03181a82011-11-17 17:22:21 -08001071#else
1072 return static_cast<JDWP::FieldId>(reinterpret_cast<uintptr_t>(f));
1073#endif
1074}
1075
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001076static JDWP::MethodId ToMethodId(const mirror::AbstractMethod* m)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001077 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001078#ifdef MOVING_GARBAGE_COLLECTOR
1079 UNIMPLEMENTED(FATAL);
1080#else
1081 return static_cast<JDWP::MethodId>(reinterpret_cast<uintptr_t>(m));
1082#endif
1083}
1084
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001085static mirror::Field* FromFieldId(JDWP::FieldId fid)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001086 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesaed4be92011-12-02 16:16:23 -08001087#ifdef MOVING_GARBAGE_COLLECTOR
1088 UNIMPLEMENTED(FATAL);
1089#else
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001090 return reinterpret_cast<mirror::Field*>(static_cast<uintptr_t>(fid));
Elliott Hughesaed4be92011-12-02 16:16:23 -08001091#endif
1092}
1093
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001094static mirror::AbstractMethod* FromMethodId(JDWP::MethodId mid)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001095 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001096#ifdef MOVING_GARBAGE_COLLECTOR
1097 UNIMPLEMENTED(FATAL);
1098#else
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001099 return reinterpret_cast<mirror::AbstractMethod*>(static_cast<uintptr_t>(mid));
Elliott Hughes03181a82011-11-17 17:22:21 -08001100#endif
1101}
1102
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001103static void SetLocation(JDWP::JdwpLocation& location, mirror::AbstractMethod* m, uint32_t dex_pc)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001104 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001105 if (m == NULL) {
1106 memset(&location, 0, sizeof(location));
1107 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001108 mirror::Class* c = m->GetDeclaringClass();
Elliott Hughes74847412012-06-20 18:10:21 -07001109 location.type_tag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
1110 location.class_id = gRegistry->Add(c);
1111 location.method_id = ToMethodId(m);
Ian Rogers0399dde2012-06-06 17:09:28 -07001112 location.dex_pc = dex_pc;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001113 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08001114}
1115
Elliott Hughesa96836a2013-01-17 12:27:49 -08001116std::string Dbg::GetMethodName(JDWP::MethodId method_id)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001117 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001118 mirror::AbstractMethod* m = FromMethodId(method_id);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001119 return MethodHelper(m).GetName();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001120}
1121
Elliott Hughesa96836a2013-01-17 12:27:49 -08001122std::string Dbg::GetFieldName(JDWP::FieldId field_id)
1123 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001124 mirror::Field* f = FromFieldId(field_id);
Elliott Hughesa96836a2013-01-17 12:27:49 -08001125 return FieldHelper(f).GetName();
1126}
1127
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001128/*
1129 * Augment the access flags for synthetic methods and fields by setting
1130 * the (as described by the spec) "0xf0000000 bit". Also, strip out any
1131 * flags not specified by the Java programming language.
1132 */
1133static uint32_t MangleAccessFlags(uint32_t accessFlags) {
1134 accessFlags &= kAccJavaFlagsMask;
1135 if ((accessFlags & kAccSynthetic) != 0) {
1136 accessFlags |= 0xf0000000;
1137 }
1138 return accessFlags;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001139}
1140
Elliott Hughesdbb40792011-11-18 17:05:22 -08001141static const uint16_t kEclipseWorkaroundSlot = 1000;
1142
1143/*
1144 * Eclipse appears to expect that the "this" reference is in slot zero.
1145 * If it's not, the "variables" display will show two copies of "this",
1146 * possibly because it gets "this" from SF.ThisObject and then displays
1147 * all locals with nonzero slot numbers.
1148 *
1149 * So, we remap the item in slot 0 to 1000, and remap "this" to zero. On
1150 * SF.GetValues / SF.SetValues we map them back.
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001151 *
1152 * TODO: jdb uses the value to determine whether a variable is a local or an argument,
1153 * by checking whether it's less than the number of arguments. To make that work, we'd
1154 * have to "mangle" all the arguments to come first, not just the implicit argument 'this'.
Elliott Hughesdbb40792011-11-18 17:05:22 -08001155 */
1156static uint16_t MangleSlot(uint16_t slot, const char* name) {
1157 uint16_t newSlot = slot;
1158 if (strcmp(name, "this") == 0) {
1159 newSlot = 0;
1160 } else if (slot == 0) {
1161 newSlot = kEclipseWorkaroundSlot;
1162 }
1163 return newSlot;
1164}
1165
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001166static uint16_t DemangleSlot(uint16_t slot, mirror::AbstractMethod* m)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001167 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001168 if (slot == kEclipseWorkaroundSlot) {
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001169 return 0;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001170 } else if (slot == 0) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001171 const DexFile::CodeItem* code_item = MethodHelper(m).GetCodeItem();
Elliott Hughescaf76542012-06-28 16:08:22 -07001172 CHECK(code_item != NULL) << PrettyMethod(m);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001173 return code_item->registers_size_ - code_item->ins_size_;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001174 }
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001175 return slot;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001176}
1177
Elliott Hughes88d63092013-01-09 09:55:54 -08001178JDWP::JdwpError Dbg::OutputDeclaredFields(JDWP::RefTypeId class_id, bool with_generic, JDWP::ExpandBuf* pReply) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001179 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001180 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001181 if (c == NULL) {
1182 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001183 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001184
1185 size_t instance_field_count = c->NumInstanceFields();
1186 size_t static_field_count = c->NumStaticFields();
1187
1188 expandBufAdd4BE(pReply, instance_field_count + static_field_count);
1189
1190 for (size_t i = 0; i < instance_field_count + static_field_count; ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001191 mirror::Field* f = (i < instance_field_count) ? c->GetInstanceField(i) : c->GetStaticField(i - instance_field_count);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001192 FieldHelper fh(f);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001193 expandBufAddFieldId(pReply, ToFieldId(f));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001194 expandBufAddUtf8String(pReply, fh.GetName());
1195 expandBufAddUtf8String(pReply, fh.GetTypeDescriptor());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001196 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001197 static const char genericSignature[1] = "";
1198 expandBufAddUtf8String(pReply, genericSignature);
1199 }
1200 expandBufAdd4BE(pReply, MangleAccessFlags(f->GetAccessFlags()));
1201 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001202 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001203}
1204
Elliott Hughes88d63092013-01-09 09:55:54 -08001205JDWP::JdwpError Dbg::OutputDeclaredMethods(JDWP::RefTypeId class_id, bool with_generic,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001206 JDWP::ExpandBuf* pReply) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001207 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001208 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001209 if (c == NULL) {
1210 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001211 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001212
1213 size_t direct_method_count = c->NumDirectMethods();
1214 size_t virtual_method_count = c->NumVirtualMethods();
1215
1216 expandBufAdd4BE(pReply, direct_method_count + virtual_method_count);
1217
1218 for (size_t i = 0; i < direct_method_count + virtual_method_count; ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001219 mirror::AbstractMethod* m = (i < direct_method_count) ? c->GetDirectMethod(i) : c->GetVirtualMethod(i - direct_method_count);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001220 MethodHelper mh(m);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001221 expandBufAddMethodId(pReply, ToMethodId(m));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001222 expandBufAddUtf8String(pReply, mh.GetName());
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001223 expandBufAddUtf8String(pReply, mh.GetSignature());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001224 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001225 static const char genericSignature[1] = "";
1226 expandBufAddUtf8String(pReply, genericSignature);
1227 }
1228 expandBufAdd4BE(pReply, MangleAccessFlags(m->GetAccessFlags()));
1229 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001230 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001231}
1232
Elliott Hughes88d63092013-01-09 09:55:54 -08001233JDWP::JdwpError Dbg::OutputDeclaredInterfaces(JDWP::RefTypeId class_id, JDWP::ExpandBuf* pReply) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001234 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001235 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001236 if (c == NULL) {
1237 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001238 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001239
1240 ClassHelper kh(c);
Ian Rogersd24e2642012-06-06 21:21:43 -07001241 size_t interface_count = kh.NumDirectInterfaces();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001242 expandBufAdd4BE(pReply, interface_count);
1243 for (size_t i = 0; i < interface_count; ++i) {
Elliott Hughes64f574f2013-02-20 14:57:12 -08001244 expandBufAddRefTypeId(pReply, gRegistry->AddRefType(kh.GetDirectInterface(i)));
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001245 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001246 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001247}
1248
Elliott Hughes88d63092013-01-09 09:55:54 -08001249void Dbg::OutputLineTable(JDWP::RefTypeId, JDWP::MethodId method_id, JDWP::ExpandBuf* pReply)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001250 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001251 struct DebugCallbackContext {
1252 int numItems;
1253 JDWP::ExpandBuf* pReply;
1254
Elliott Hughes2435a572012-02-17 16:07:41 -08001255 static bool Callback(void* context, uint32_t address, uint32_t line_number) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001256 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
1257 expandBufAdd8BE(pContext->pReply, address);
Elliott Hughes2435a572012-02-17 16:07:41 -08001258 expandBufAdd4BE(pContext->pReply, line_number);
Elliott Hughes03181a82011-11-17 17:22:21 -08001259 pContext->numItems++;
1260 return true;
1261 }
1262 };
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001263 mirror::AbstractMethod* m = FromMethodId(method_id);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001264 MethodHelper mh(m);
Elliott Hughes03181a82011-11-17 17:22:21 -08001265 uint64_t start, end;
1266 if (m->IsNative()) {
1267 start = -1;
1268 end = -1;
1269 } else {
1270 start = 0;
jeffhao14f0db92012-12-14 17:50:42 -08001271 // Return the index of the last instruction
1272 end = mh.GetCodeItem()->insns_size_in_code_units_ - 1;
Elliott Hughes03181a82011-11-17 17:22:21 -08001273 }
1274
1275 expandBufAdd8BE(pReply, start);
1276 expandBufAdd8BE(pReply, end);
1277
1278 // Add numLines later
1279 size_t numLinesOffset = expandBufGetLength(pReply);
1280 expandBufAdd4BE(pReply, 0);
1281
1282 DebugCallbackContext context;
1283 context.numItems = 0;
1284 context.pReply = pReply;
1285
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001286 mh.GetDexFile().DecodeDebugInfo(mh.GetCodeItem(), m->IsStatic(), m->GetDexMethodIndex(),
1287 DebugCallbackContext::Callback, NULL, &context);
Elliott Hughes03181a82011-11-17 17:22:21 -08001288
1289 JDWP::Set4BE(expandBufGetBuffer(pReply) + numLinesOffset, context.numItems);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001290}
1291
Elliott Hughes88d63092013-01-09 09:55:54 -08001292void Dbg::OutputVariableTable(JDWP::RefTypeId, JDWP::MethodId method_id, bool with_generic, JDWP::ExpandBuf* pReply) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001293 struct DebugCallbackContext {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001294 JDWP::ExpandBuf* pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001295 size_t variable_count;
1296 bool with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001297
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001298 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 -08001299 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
1300
Elliott Hughesad3da692012-02-24 16:51:35 -08001301 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 -08001302
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001303 slot = MangleSlot(slot, name);
1304
Elliott Hughesdbb40792011-11-18 17:05:22 -08001305 expandBufAdd8BE(pContext->pReply, startAddress);
1306 expandBufAddUtf8String(pContext->pReply, name);
1307 expandBufAddUtf8String(pContext->pReply, descriptor);
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001308 if (pContext->with_generic) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001309 expandBufAddUtf8String(pContext->pReply, signature);
1310 }
1311 expandBufAdd4BE(pContext->pReply, endAddress - startAddress);
1312 expandBufAdd4BE(pContext->pReply, slot);
1313
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001314 ++pContext->variable_count;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001315 }
1316 };
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001317 mirror::AbstractMethod* m = FromMethodId(method_id);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001318 MethodHelper mh(m);
1319 const DexFile::CodeItem* code_item = mh.GetCodeItem();
Elliott Hughesdbb40792011-11-18 17:05:22 -08001320
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001321 // arg_count considers doubles and longs to take 2 units.
1322 // variable_count considers everything to take 1 unit.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001323 std::string shorty(mh.GetShorty());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001324 expandBufAdd4BE(pReply, mirror::AbstractMethod::NumArgRegisters(shorty));
Elliott Hughesdbb40792011-11-18 17:05:22 -08001325
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001326 // We don't know the total number of variables yet, so leave a blank and update it later.
1327 size_t variable_count_offset = expandBufGetLength(pReply);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001328 expandBufAdd4BE(pReply, 0);
1329
1330 DebugCallbackContext context;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001331 context.pReply = pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001332 context.variable_count = 0;
1333 context.with_generic = with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001334
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001335 mh.GetDexFile().DecodeDebugInfo(code_item, m->IsStatic(), m->GetDexMethodIndex(), NULL,
1336 DebugCallbackContext::Callback, &context);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001337
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001338 JDWP::Set4BE(expandBufGetBuffer(pReply) + variable_count_offset, context.variable_count);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001339}
1340
Elliott Hughes9777ba22013-01-17 09:04:19 -08001341JDWP::JdwpError Dbg::GetBytecodes(JDWP::RefTypeId, JDWP::MethodId method_id,
1342 std::vector<uint8_t>& bytecodes)
1343 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001344 mirror::AbstractMethod* m = FromMethodId(method_id);
Elliott Hughes9777ba22013-01-17 09:04:19 -08001345 if (m == NULL) {
1346 return JDWP::ERR_INVALID_METHODID;
1347 }
1348 MethodHelper mh(m);
1349 const DexFile::CodeItem* code_item = mh.GetCodeItem();
1350 size_t byte_count = code_item->insns_size_in_code_units_ * 2;
1351 const uint8_t* begin = reinterpret_cast<const uint8_t*>(code_item->insns_);
1352 const uint8_t* end = begin + byte_count;
1353 for (const uint8_t* p = begin; p != end; ++p) {
1354 bytecodes.push_back(*p);
1355 }
1356 return JDWP::ERR_NONE;
1357}
1358
Elliott Hughes88d63092013-01-09 09:55:54 -08001359JDWP::JdwpTag Dbg::GetFieldBasicTag(JDWP::FieldId field_id) {
1360 return BasicTagFromDescriptor(FieldHelper(FromFieldId(field_id)).GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001361}
1362
Elliott Hughes88d63092013-01-09 09:55:54 -08001363JDWP::JdwpTag Dbg::GetStaticFieldBasicTag(JDWP::FieldId field_id) {
1364 return BasicTagFromDescriptor(FieldHelper(FromFieldId(field_id)).GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001365}
1366
Elliott Hughes88d63092013-01-09 09:55:54 -08001367static JDWP::JdwpError GetFieldValueImpl(JDWP::RefTypeId ref_type_id, JDWP::ObjectId object_id,
1368 JDWP::FieldId field_id, JDWP::ExpandBuf* pReply,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001369 bool is_static)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001370 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes0cf74332012-02-23 23:14:00 -08001371 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001372 mirror::Class* c = DecodeClass(ref_type_id, status);
Elliott Hughes88d63092013-01-09 09:55:54 -08001373 if (ref_type_id != 0 && c == NULL) {
Elliott Hughes0cf74332012-02-23 23:14:00 -08001374 return status;
1375 }
1376
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001377 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001378 if ((!is_static && o == NULL) || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001379 return JDWP::ERR_INVALID_OBJECT;
1380 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001381 mirror::Field* f = FromFieldId(field_id);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001382
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001383 mirror::Class* receiver_class = c;
Elliott Hughes0cf74332012-02-23 23:14:00 -08001384 if (receiver_class == NULL && o != NULL) {
1385 receiver_class = o->GetClass();
1386 }
1387 // TODO: should we give up now if receiver_class is NULL?
1388 if (receiver_class != NULL && !f->GetDeclaringClass()->IsAssignableFrom(receiver_class)) {
1389 LOG(INFO) << "ERR_INVALID_FIELDID: " << PrettyField(f) << " " << PrettyClass(receiver_class);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001390 return JDWP::ERR_INVALID_FIELDID;
1391 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001392
Elliott Hughes0cf74332012-02-23 23:14:00 -08001393 // The RI only enforces the static/non-static mismatch in one direction.
1394 // TODO: should we change the tests and check both?
1395 if (is_static) {
1396 if (!f->IsStatic()) {
1397 return JDWP::ERR_INVALID_FIELDID;
1398 }
1399 } else {
1400 if (f->IsStatic()) {
1401 LOG(WARNING) << "Ignoring non-NULL receiver for ObjectReference.SetValues on static field " << PrettyField(f);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001402 }
1403 }
jeffhao0dfbb7e2012-11-28 15:26:03 -08001404 if (f->IsStatic()) {
1405 o = f->GetDeclaringClass();
1406 }
Elliott Hughes0cf74332012-02-23 23:14:00 -08001407
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001408 JDWP::JdwpTag tag = BasicTagFromDescriptor(FieldHelper(f).GetTypeDescriptor());
Elliott Hughesaed4be92011-12-02 16:16:23 -08001409
1410 if (IsPrimitiveTag(tag)) {
1411 expandBufAdd1(pReply, tag);
1412 if (tag == JDWP::JT_BOOLEAN || tag == JDWP::JT_BYTE) {
1413 expandBufAdd1(pReply, f->Get32(o));
1414 } else if (tag == JDWP::JT_CHAR || tag == JDWP::JT_SHORT) {
1415 expandBufAdd2BE(pReply, f->Get32(o));
1416 } else if (tag == JDWP::JT_FLOAT || tag == JDWP::JT_INT) {
1417 expandBufAdd4BE(pReply, f->Get32(o));
1418 } else if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
1419 expandBufAdd8BE(pReply, f->Get64(o));
1420 } else {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001421 LOG(FATAL) << "Unknown tag: " << tag;
Elliott Hughesaed4be92011-12-02 16:16:23 -08001422 }
1423 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001424 mirror::Object* value = f->GetObject(o);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001425 expandBufAdd1(pReply, TagFromObject(value));
1426 expandBufAddObjectId(pReply, gRegistry->Add(value));
1427 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001428 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001429}
1430
Elliott Hughes88d63092013-01-09 09:55:54 -08001431JDWP::JdwpError Dbg::GetFieldValue(JDWP::ObjectId object_id, JDWP::FieldId field_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001432 JDWP::ExpandBuf* pReply) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001433 return GetFieldValueImpl(0, object_id, field_id, pReply, false);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001434}
1435
Elliott Hughes88d63092013-01-09 09:55:54 -08001436JDWP::JdwpError Dbg::GetStaticFieldValue(JDWP::RefTypeId ref_type_id, JDWP::FieldId field_id, JDWP::ExpandBuf* pReply) {
1437 return GetFieldValueImpl(ref_type_id, 0, field_id, pReply, true);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001438}
1439
Elliott Hughes88d63092013-01-09 09:55:54 -08001440static JDWP::JdwpError SetFieldValueImpl(JDWP::ObjectId object_id, JDWP::FieldId field_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001441 uint64_t value, int width, bool is_static)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001442 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001443 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001444 if ((!is_static && o == NULL) || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001445 return JDWP::ERR_INVALID_OBJECT;
1446 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001447 mirror::Field* f = FromFieldId(field_id);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001448
1449 // The RI only enforces the static/non-static mismatch in one direction.
1450 // TODO: should we change the tests and check both?
1451 if (is_static) {
1452 if (!f->IsStatic()) {
1453 return JDWP::ERR_INVALID_FIELDID;
1454 }
1455 } else {
1456 if (f->IsStatic()) {
1457 LOG(WARNING) << "Ignoring non-NULL receiver for ObjectReference.SetValues on static field " << PrettyField(f);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001458 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001459 }
jeffhao0dfbb7e2012-11-28 15:26:03 -08001460 if (f->IsStatic()) {
1461 o = f->GetDeclaringClass();
1462 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001463
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001464 JDWP::JdwpTag tag = BasicTagFromDescriptor(FieldHelper(f).GetTypeDescriptor());
Elliott Hughesaed4be92011-12-02 16:16:23 -08001465
1466 if (IsPrimitiveTag(tag)) {
1467 if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001468 CHECK_EQ(width, 8);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001469 f->Set64(o, value);
1470 } else {
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001471 CHECK_LE(width, 4);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001472 f->Set32(o, value);
1473 }
1474 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001475 mirror::Object* v = gRegistry->Get<mirror::Object*>(value);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001476 if (v == ObjectRegistry::kInvalidObject) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001477 return JDWP::ERR_INVALID_OBJECT;
1478 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001479 if (v != NULL) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001480 mirror::Class* field_type = FieldHelper(f).GetType();
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001481 if (!field_type->IsAssignableFrom(v->GetClass())) {
1482 return JDWP::ERR_INVALID_OBJECT;
1483 }
1484 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001485 f->SetObject(o, v);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001486 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001487
1488 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001489}
1490
Elliott Hughes88d63092013-01-09 09:55:54 -08001491JDWP::JdwpError Dbg::SetFieldValue(JDWP::ObjectId object_id, JDWP::FieldId field_id, uint64_t value,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001492 int width) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001493 return SetFieldValueImpl(object_id, field_id, value, width, false);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001494}
1495
Elliott Hughes88d63092013-01-09 09:55:54 -08001496JDWP::JdwpError Dbg::SetStaticFieldValue(JDWP::FieldId field_id, uint64_t value, int width) {
1497 return SetFieldValueImpl(0, field_id, value, width, true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001498}
1499
Elliott Hughes88d63092013-01-09 09:55:54 -08001500std::string Dbg::StringToUtf8(JDWP::ObjectId string_id) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001501 mirror::String* s = gRegistry->Get<mirror::String*>(string_id);
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001502 return s->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001503}
1504
Elliott Hughes221229c2013-01-08 18:17:50 -08001505JDWP::JdwpError Dbg::GetThreadName(JDWP::ObjectId thread_id, std::string& name) {
jeffhaoa77f0f62012-12-05 17:19:31 -08001506 ScopedObjectAccessUnchecked soa(Thread::Current());
1507 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001508 Thread* thread;
1509 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1510 if (error != JDWP::ERR_NONE && error != JDWP::ERR_THREAD_NOT_ALIVE) {
1511 return error;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001512 }
Elliott Hughes221229c2013-01-08 18:17:50 -08001513
1514 // We still need to report the zombie threads' names, so we can't just call Thread::GetThreadName.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001515 mirror::Object* thread_object = gRegistry->Get<mirror::Object*>(thread_id);
1516 mirror::Field* java_lang_Thread_name_field =
1517 soa.DecodeField(WellKnownClasses::java_lang_Thread_name);
1518 mirror::String* s =
1519 reinterpret_cast<mirror::String*>(java_lang_Thread_name_field->GetObject(thread_object));
Elliott Hughes221229c2013-01-08 18:17:50 -08001520 if (s != NULL) {
1521 name = s->ToModifiedUtf8();
1522 }
1523 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001524}
1525
Elliott Hughes221229c2013-01-08 18:17:50 -08001526JDWP::JdwpError Dbg::GetThreadGroup(JDWP::ObjectId thread_id, JDWP::ExpandBuf* pReply) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001527 ScopedObjectAccess soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001528 mirror::Object* thread_object = gRegistry->Get<mirror::Object*>(thread_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001529 if (thread_object == ObjectRegistry::kInvalidObject) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001530 return JDWP::ERR_INVALID_OBJECT;
1531 }
1532
1533 // Okay, so it's an object, but is it actually a thread?
Ian Rogers50b35e22012-10-04 10:09:15 -07001534 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001535 Thread* thread;
1536 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1537 if (error == JDWP::ERR_THREAD_NOT_ALIVE) {
1538 // Zombie threads are in the null group.
1539 expandBufAddObjectId(pReply, JDWP::ObjectId(0));
1540 return JDWP::ERR_NONE;
1541 }
1542 if (error != JDWP::ERR_NONE) {
1543 return error;
Elliott Hughes2435a572012-02-17 16:07:41 -08001544 }
Elliott Hughes499c5132011-11-17 14:55:11 -08001545
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001546 mirror::Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/Thread;");
Elliott Hughes499c5132011-11-17 14:55:11 -08001547 CHECK(c != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001548 mirror::Field* f = c->FindInstanceField("group", "Ljava/lang/ThreadGroup;");
Elliott Hughes499c5132011-11-17 14:55:11 -08001549 CHECK(f != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001550 mirror::Object* group = f->GetObject(thread_object);
Elliott Hughes499c5132011-11-17 14:55:11 -08001551 CHECK(group != NULL);
Elliott Hughes2435a572012-02-17 16:07:41 -08001552 JDWP::ObjectId thread_group_id = gRegistry->Add(group);
1553
1554 expandBufAddObjectId(pReply, thread_group_id);
1555 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001556}
1557
Elliott Hughes88d63092013-01-09 09:55:54 -08001558std::string Dbg::GetThreadGroupName(JDWP::ObjectId thread_group_id) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001559 ScopedObjectAccess soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001560 mirror::Object* thread_group = gRegistry->Get<mirror::Object*>(thread_group_id);
Elliott Hughes499c5132011-11-17 14:55:11 -08001561 CHECK(thread_group != NULL);
1562
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001563 mirror::Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/ThreadGroup;");
Elliott Hughes499c5132011-11-17 14:55:11 -08001564 CHECK(c != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001565 mirror::Field* f = c->FindInstanceField("name", "Ljava/lang/String;");
Elliott Hughes499c5132011-11-17 14:55:11 -08001566 CHECK(f != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001567 mirror::String* s = reinterpret_cast<mirror::String*>(f->GetObject(thread_group));
Elliott Hughes499c5132011-11-17 14:55:11 -08001568 return s->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001569}
1570
Elliott Hughes88d63092013-01-09 09:55:54 -08001571JDWP::ObjectId Dbg::GetThreadGroupParent(JDWP::ObjectId thread_group_id) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001572 mirror::Object* thread_group = gRegistry->Get<mirror::Object*>(thread_group_id);
Elliott Hughes4e235312011-12-02 11:34:15 -08001573 CHECK(thread_group != NULL);
1574
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001575 mirror::Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/ThreadGroup;");
Elliott Hughes4e235312011-12-02 11:34:15 -08001576 CHECK(c != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001577 mirror::Field* f = c->FindInstanceField("parent", "Ljava/lang/ThreadGroup;");
Elliott Hughes4e235312011-12-02 11:34:15 -08001578 CHECK(f != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001579 mirror::Object* parent = f->GetObject(thread_group);
Elliott Hughes4e235312011-12-02 11:34:15 -08001580 return gRegistry->Add(parent);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001581}
1582
1583JDWP::ObjectId Dbg::GetSystemThreadGroupId() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001584 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001585 mirror::Field* f = soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_systemThreadGroup);
1586 mirror::Object* group = f->GetObject(f->GetDeclaringClass());
Ian Rogers365c1022012-06-22 15:05:28 -07001587 return gRegistry->Add(group);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001588}
1589
1590JDWP::ObjectId Dbg::GetMainThreadGroupId() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001591 ScopedObjectAccess soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001592 mirror::Field* f = soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_mainThreadGroup);
1593 mirror::Object* group = f->GetObject(f->GetDeclaringClass());
Ian Rogers365c1022012-06-22 15:05:28 -07001594 return gRegistry->Add(group);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001595}
1596
Elliott Hughes221229c2013-01-08 18:17:50 -08001597JDWP::JdwpError Dbg::GetThreadStatus(JDWP::ObjectId thread_id, JDWP::JdwpThreadStatus* pThreadStatus, JDWP::JdwpSuspendStatus* pSuspendStatus) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001598 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes499c5132011-11-17 14:55:11 -08001599
Elliott Hughes9e0c1752013-01-09 14:02:58 -08001600 *pSuspendStatus = JDWP::SUSPEND_STATUS_NOT_SUSPENDED;
1601
Ian Rogers50b35e22012-10-04 10:09:15 -07001602 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001603 Thread* thread;
1604 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1605 if (error != JDWP::ERR_NONE) {
1606 if (error == JDWP::ERR_THREAD_NOT_ALIVE) {
1607 *pThreadStatus = JDWP::TS_ZOMBIE;
Elliott Hughes221229c2013-01-08 18:17:50 -08001608 return JDWP::ERR_NONE;
1609 }
1610 return error;
Elliott Hughes499c5132011-11-17 14:55:11 -08001611 }
1612
Elliott Hughes9e0c1752013-01-09 14:02:58 -08001613 if (IsSuspendedForDebugger(soa, thread)) {
1614 *pSuspendStatus = JDWP::SUSPEND_STATUS_SUSPENDED;
Elliott Hughes499c5132011-11-17 14:55:11 -08001615 }
1616
Elliott Hughes9e0c1752013-01-09 14:02:58 -08001617 switch (thread->GetState()) {
1618 case kBlocked: *pThreadStatus = JDWP::TS_MONITOR; break;
1619 case kNative: *pThreadStatus = JDWP::TS_RUNNING; break;
1620 case kRunnable: *pThreadStatus = JDWP::TS_RUNNING; break;
1621 case kSleeping: *pThreadStatus = JDWP::TS_SLEEPING; break;
1622 case kStarting: *pThreadStatus = JDWP::TS_ZOMBIE; break;
1623 case kSuspended: *pThreadStatus = JDWP::TS_RUNNING; break;
1624 case kTerminated: *pThreadStatus = JDWP::TS_ZOMBIE; break;
1625 case kTimedWaiting: *pThreadStatus = JDWP::TS_WAIT; break;
1626 case kWaitingForDebuggerSend: *pThreadStatus = JDWP::TS_WAIT; break;
1627 case kWaitingForDebuggerSuspension: *pThreadStatus = JDWP::TS_WAIT; break;
1628 case kWaitingForDebuggerToAttach: *pThreadStatus = JDWP::TS_WAIT; break;
1629 case kWaitingForGcToComplete: *pThreadStatus = JDWP::TS_WAIT; break;
1630 case kWaitingForJniOnLoad: *pThreadStatus = JDWP::TS_WAIT; break;
1631 case kWaitingForSignalCatcherOutput: *pThreadStatus = JDWP::TS_WAIT; break;
1632 case kWaitingInMainDebuggerLoop: *pThreadStatus = JDWP::TS_WAIT; break;
1633 case kWaitingInMainSignalCatcherLoop: *pThreadStatus = JDWP::TS_WAIT; break;
1634 case kWaitingPerformingGc: *pThreadStatus = JDWP::TS_WAIT; break;
1635 case kWaiting: *pThreadStatus = JDWP::TS_WAIT; break;
1636 // Don't add a 'default' here so the compiler can spot incompatible enum changes.
1637 }
Elliott Hughes221229c2013-01-08 18:17:50 -08001638 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001639}
1640
Elliott Hughes221229c2013-01-08 18:17:50 -08001641JDWP::JdwpError Dbg::GetThreadDebugSuspendCount(JDWP::ObjectId thread_id, JDWP::ExpandBuf* pReply) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001642 ScopedObjectAccess soa(Thread::Current());
Ian Rogers50b35e22012-10-04 10:09:15 -07001643 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001644 Thread* thread;
1645 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1646 if (error != JDWP::ERR_NONE) {
1647 return error;
Elliott Hughes2435a572012-02-17 16:07:41 -08001648 }
Ian Rogers50b35e22012-10-04 10:09:15 -07001649 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001650 expandBufAdd4BE(pReply, thread->GetDebugSuspendCount());
Elliott Hughes2435a572012-02-17 16:07:41 -08001651 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001652}
1653
Elliott Hughesf9501702013-01-11 11:22:27 -08001654JDWP::JdwpError Dbg::Interrupt(JDWP::ObjectId thread_id) {
1655 ScopedObjectAccess soa(Thread::Current());
1656 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
1657 Thread* thread;
1658 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1659 if (error != JDWP::ERR_NONE) {
1660 return error;
1661 }
1662 thread->Interrupt();
1663 return JDWP::ERR_NONE;
1664}
1665
Elliott Hughescaf76542012-06-28 16:08:22 -07001666void Dbg::GetThreads(JDWP::ObjectId thread_group_id, std::vector<JDWP::ObjectId>& thread_ids) {
Ian Rogers365c1022012-06-22 15:05:28 -07001667 class ThreadListVisitor {
1668 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001669 ThreadListVisitor(const ScopedObjectAccessUnchecked& soa, mirror::Object* desired_thread_group,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001670 std::vector<JDWP::ObjectId>& thread_ids)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001671 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
jeffhao0dfbb7e2012-11-28 15:26:03 -08001672 : soa_(soa), desired_thread_group_(desired_thread_group), thread_ids_(thread_ids) {}
Ian Rogers365c1022012-06-22 15:05:28 -07001673
Elliott Hughesa2155262011-11-16 16:26:58 -08001674 static void Visit(Thread* t, void* arg) {
1675 reinterpret_cast<ThreadListVisitor*>(arg)->Visit(t);
1676 }
1677
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001678 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1679 // annotalysis.
1680 void Visit(Thread* t) NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughesa2155262011-11-16 16:26:58 -08001681 if (t == Dbg::GetDebugThread()) {
1682 // Skip the JDWP thread. Some debuggers get bent out of shape when they can't suspend and
1683 // query all threads, so it's easier if we just don't tell them about this thread.
1684 return;
1685 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001686 mirror::Object* peer = t->GetPeer();
jeffhao0dfbb7e2012-11-28 15:26:03 -08001687 if (IsInDesiredThreadGroup(peer)) {
Ian Rogers120f1c72012-09-28 17:17:10 -07001688 thread_ids_.push_back(gRegistry->Add(peer));
Elliott Hughesa2155262011-11-16 16:26:58 -08001689 }
1690 }
1691
Ian Rogers365c1022012-06-22 15:05:28 -07001692 private:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001693 bool IsInDesiredThreadGroup(mirror::Object* peer)
jeffhao0dfbb7e2012-11-28 15:26:03 -08001694 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
jeffhao0dfbb7e2012-11-28 15:26:03 -08001695 // peer might be NULL if the thread is still starting up.
1696 if (peer == NULL) {
1697 // We can't tell the debugger about this thread yet.
1698 // TODO: if we identified threads to the debugger by their Thread*
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001699 // rather than their peer's mirror::Object*, we could fix this.
jeffhao0dfbb7e2012-11-28 15:26:03 -08001700 // Doing so might help us report ZOMBIE threads too.
1701 return false;
1702 }
jeffhaoc1e04902012-12-13 12:41:10 -08001703 // Do we want threads from all thread groups?
1704 if (desired_thread_group_ == NULL) {
1705 return true;
1706 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001707 mirror::Object* group = soa_.DecodeField(WellKnownClasses::java_lang_Thread_group)->GetObject(peer);
jeffhao0dfbb7e2012-11-28 15:26:03 -08001708 return (group == desired_thread_group_);
1709 }
1710
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07001711 const ScopedObjectAccessUnchecked& soa_;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001712 mirror::Object* const desired_thread_group_;
Elliott Hughescaf76542012-06-28 16:08:22 -07001713 std::vector<JDWP::ObjectId>& thread_ids_;
Elliott Hughesa2155262011-11-16 16:26:58 -08001714 };
1715
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001716 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001717 mirror::Object* thread_group = gRegistry->Get<mirror::Object*>(thread_group_id);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001718 ThreadListVisitor tlv(soa, thread_group, thread_ids);
Ian Rogers50b35e22012-10-04 10:09:15 -07001719 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughesf8349362012-06-18 15:00:06 -07001720 Runtime::Current()->GetThreadList()->ForEach(ThreadListVisitor::Visit, &tlv);
Elliott Hughescaf76542012-06-28 16:08:22 -07001721}
Elliott Hughesa2155262011-11-16 16:26:58 -08001722
Elliott Hughescaf76542012-06-28 16:08:22 -07001723void Dbg::GetChildThreadGroups(JDWP::ObjectId thread_group_id, std::vector<JDWP::ObjectId>& child_thread_group_ids) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001724 ScopedObjectAccess soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001725 mirror::Object* thread_group = gRegistry->Get<mirror::Object*>(thread_group_id);
Elliott Hughescaf76542012-06-28 16:08:22 -07001726
1727 // Get the ArrayList<ThreadGroup> "groups" out of this thread group...
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001728 mirror::Field* groups_field = thread_group->GetClass()->FindInstanceField("groups", "Ljava/util/List;");
1729 mirror::Object* groups_array_list = groups_field->GetObject(thread_group);
Elliott Hughescaf76542012-06-28 16:08:22 -07001730
1731 // Get the array and size out of the ArrayList<ThreadGroup>...
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001732 mirror::Field* array_field = groups_array_list->GetClass()->FindInstanceField("array", "[Ljava/lang/Object;");
1733 mirror::Field* size_field = groups_array_list->GetClass()->FindInstanceField("size", "I");
1734 mirror::ObjectArray<mirror::Object>* groups_array =
1735 array_field->GetObject(groups_array_list)->AsObjectArray<mirror::Object>();
Elliott Hughescaf76542012-06-28 16:08:22 -07001736 const int32_t size = size_field->GetInt(groups_array_list);
1737
1738 // Copy the first 'size' elements out of the array into the result.
1739 for (int32_t i = 0; i < size; ++i) {
1740 child_thread_group_ids.push_back(gRegistry->Add(groups_array->Get(i)));
Elliott Hughesa2155262011-11-16 16:26:58 -08001741 }
1742}
1743
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001744static int GetStackDepth(Thread* thread)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001745 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers0399dde2012-06-06 17:09:28 -07001746 struct CountStackDepthVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -08001747 CountStackDepthVisitor(Thread* thread)
1748 : StackVisitor(thread, NULL), depth(0) {}
Ian Rogers0399dde2012-06-06 17:09:28 -07001749
Elliott Hughes64f574f2013-02-20 14:57:12 -08001750 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1751 // annotalysis.
1752 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07001753 if (!GetMethod()->IsRuntimeMethod()) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -08001754 ++depth;
1755 }
Elliott Hughes530fa002012-03-12 11:44:49 -07001756 return true;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001757 }
1758 size_t depth;
1759 };
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001760
Ian Rogers7a22fa62013-01-23 12:16:16 -08001761 CountStackDepthVisitor visitor(thread);
Ian Rogers0399dde2012-06-06 17:09:28 -07001762 visitor.WalkStack();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001763 return visitor.depth;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001764}
1765
Elliott Hughes221229c2013-01-08 18:17:50 -08001766JDWP::JdwpError Dbg::GetThreadFrameCount(JDWP::ObjectId thread_id, size_t& result) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001767 ScopedObjectAccess soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08001768 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001769 Thread* thread;
1770 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1771 if (error != JDWP::ERR_NONE) {
1772 return error;
1773 }
Elliott Hughesf15f4a02013-01-09 10:09:38 -08001774 if (!IsSuspendedForDebugger(soa, thread)) {
1775 return JDWP::ERR_THREAD_NOT_SUSPENDED;
1776 }
Elliott Hughes221229c2013-01-08 18:17:50 -08001777 result = GetStackDepth(thread);
1778 return JDWP::ERR_NONE;
Elliott Hughes86964332012-02-15 19:37:42 -08001779}
1780
Ian Rogers306057f2012-11-26 12:45:53 -08001781JDWP::JdwpError Dbg::GetThreadFrames(JDWP::ObjectId thread_id, size_t start_frame,
1782 size_t frame_count, JDWP::ExpandBuf* buf) {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001783 class GetFrameVisitor : public StackVisitor {
1784 public:
Ian Rogers7a22fa62013-01-23 12:16:16 -08001785 GetFrameVisitor(Thread* thread, size_t start_frame, size_t frame_count, JDWP::ExpandBuf* buf)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001786 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08001787 : StackVisitor(thread, NULL), depth_(0),
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001788 start_frame_(start_frame), frame_count_(frame_count), buf_(buf) {
1789 expandBufAdd4BE(buf_, frame_count_);
Elliott Hughes03181a82011-11-17 17:22:21 -08001790 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001791
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001792 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1793 // annotalysis.
1794 virtual bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07001795 if (GetMethod()->IsRuntimeMethod()) {
Elliott Hughes530fa002012-03-12 11:44:49 -07001796 return true; // The debugger can't do anything useful with a frame that has no Method*.
Elliott Hughes03181a82011-11-17 17:22:21 -08001797 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001798 if (depth_ >= start_frame_ + frame_count_) {
Elliott Hughes530fa002012-03-12 11:44:49 -07001799 return false;
Elliott Hughes03181a82011-11-17 17:22:21 -08001800 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001801 if (depth_ >= start_frame_) {
1802 JDWP::FrameId frame_id(GetFrameId());
1803 JDWP::JdwpLocation location;
1804 SetLocation(location, GetMethod(), GetDexPc());
Elliott Hughes7baf96f2012-06-22 16:33:50 -07001805 VLOG(jdwp) << StringPrintf(" Frame %3zd: id=%3lld ", depth_, frame_id) << location;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001806 expandBufAdd8BE(buf_, frame_id);
1807 expandBufAddLocation(buf_, location);
1808 }
1809 ++depth_;
Elliott Hughes530fa002012-03-12 11:44:49 -07001810 return true;
Elliott Hughes03181a82011-11-17 17:22:21 -08001811 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001812
1813 private:
1814 size_t depth_;
1815 const size_t start_frame_;
1816 const size_t frame_count_;
1817 JDWP::ExpandBuf* buf_;
Elliott Hughes03181a82011-11-17 17:22:21 -08001818 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001819
1820 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08001821 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001822 Thread* thread;
1823 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1824 if (error != JDWP::ERR_NONE) {
1825 return error;
1826 }
Elliott Hughesf15f4a02013-01-09 10:09:38 -08001827 if (!IsSuspendedForDebugger(soa, thread)) {
1828 return JDWP::ERR_THREAD_NOT_SUSPENDED;
1829 }
Ian Rogers7a22fa62013-01-23 12:16:16 -08001830 GetFrameVisitor visitor(thread, start_frame, frame_count, buf);
Ian Rogers0399dde2012-06-06 17:09:28 -07001831 visitor.WalkStack();
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001832 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001833}
1834
1835JDWP::ObjectId Dbg::GetThreadSelfId() {
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07001836 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogerscfaa4552012-11-26 21:00:08 -08001837 return gRegistry->Add(soa.Self()->GetPeer());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001838}
1839
Elliott Hughes475fc232011-10-25 15:00:35 -07001840void Dbg::SuspendVM() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001841 Runtime::Current()->GetThreadList()->SuspendAllForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001842}
1843
1844void Dbg::ResumeVM() {
Elliott Hughesc61a2672012-06-21 14:52:29 -07001845 Runtime::Current()->GetThreadList()->UndoDebuggerSuspensions();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001846}
1847
Elliott Hughes221229c2013-01-08 18:17:50 -08001848JDWP::JdwpError Dbg::SuspendThread(JDWP::ObjectId thread_id, bool request_suspension) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001849 ScopedLocalRef<jobject> peer(Thread::Current()->GetJniEnv(), NULL);
1850 {
1851 ScopedObjectAccess soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001852 peer.reset(soa.AddLocalReference<jobject>(gRegistry->Get<mirror::Object*>(thread_id)));
Elliott Hughes4e235312011-12-02 11:34:15 -08001853 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001854 if (peer.get() == NULL) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001855 return JDWP::ERR_THREAD_NOT_ALIVE;
1856 }
1857 // Suspend thread to build stack trace.
Elliott Hughesf327e072013-01-09 16:01:26 -08001858 bool timed_out;
1859 Thread* thread = Thread::SuspendForDebugger(peer.get(), request_suspension, &timed_out);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001860 if (thread != NULL) {
1861 return JDWP::ERR_NONE;
Elliott Hughesf327e072013-01-09 16:01:26 -08001862 } else if (timed_out) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001863 return JDWP::ERR_INTERNAL;
1864 } else {
1865 return JDWP::ERR_THREAD_NOT_ALIVE;
1866 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001867}
1868
Elliott Hughes221229c2013-01-08 18:17:50 -08001869void Dbg::ResumeThread(JDWP::ObjectId thread_id) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001870 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001871 mirror::Object* peer = gRegistry->Get<mirror::Object*>(thread_id);
jeffhaoa77f0f62012-12-05 17:19:31 -08001872 Thread* thread;
1873 {
1874 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
1875 thread = Thread::FromManagedThread(soa, peer);
1876 }
Elliott Hughes4e235312011-12-02 11:34:15 -08001877 if (thread == NULL) {
1878 LOG(WARNING) << "No such thread for resume: " << peer;
1879 return;
1880 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001881 bool needs_resume;
1882 {
Ian Rogers50b35e22012-10-04 10:09:15 -07001883 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001884 needs_resume = thread->GetSuspendCount() > 0;
1885 }
1886 if (needs_resume) {
Elliott Hughes546b9862012-06-20 16:06:13 -07001887 Runtime::Current()->GetThreadList()->Resume(thread, true);
1888 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001889}
1890
1891void Dbg::SuspendSelf() {
Elliott Hughes475fc232011-10-25 15:00:35 -07001892 Runtime::Current()->GetThreadList()->SuspendSelfForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001893}
1894
Ian Rogers0399dde2012-06-06 17:09:28 -07001895struct GetThisVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -08001896 GetThisVisitor(Thread* thread, Context* context, JDWP::FrameId frame_id)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001897 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08001898 : StackVisitor(thread, context), this_object(NULL), frame_id(frame_id) {}
Ian Rogers0399dde2012-06-06 17:09:28 -07001899
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001900 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1901 // annotalysis.
1902 virtual bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001903 if (frame_id != GetFrameId()) {
Ian Rogers0399dde2012-06-06 17:09:28 -07001904 return true; // continue
1905 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001906 mirror::AbstractMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07001907 if (m->IsNative() || m->IsStatic()) {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001908 this_object = NULL;
Ian Rogers0399dde2012-06-06 17:09:28 -07001909 } else {
1910 uint16_t reg = DemangleSlot(0, m);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001911 this_object = reinterpret_cast<mirror::Object*>(GetVReg(m, reg, kReferenceVReg));
Ian Rogers0399dde2012-06-06 17:09:28 -07001912 }
1913 return false;
Elliott Hughes86b00102011-12-05 17:54:26 -08001914 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001915
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001916 mirror::Object* this_object;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001917 JDWP::FrameId frame_id;
Ian Rogers0399dde2012-06-06 17:09:28 -07001918};
1919
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001920static mirror::Object* GetThis(Thread* self, mirror::AbstractMethod* m, size_t frame_id)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001921 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughescaf76542012-06-28 16:08:22 -07001922 // TODO: should we return the 'this' we passed through to non-static native methods?
Ian Rogers0399dde2012-06-06 17:09:28 -07001923 if (m->IsNative() || m->IsStatic()) {
1924 return NULL;
1925 }
Elliott Hughescaf76542012-06-28 16:08:22 -07001926
Ian Rogers0399dde2012-06-06 17:09:28 -07001927 UniquePtr<Context> context(Context::Create());
Ian Rogers7a22fa62013-01-23 12:16:16 -08001928 GetThisVisitor visitor(self, context.get(), frame_id);
Elliott Hughescaf76542012-06-28 16:08:22 -07001929 visitor.WalkStack();
1930 return visitor.this_object;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001931}
1932
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001933JDWP::JdwpError Dbg::GetThisObject(JDWP::ObjectId thread_id, JDWP::FrameId frame_id,
1934 JDWP::ObjectId* result) {
1935 ScopedObjectAccessUnchecked soa(Thread::Current());
1936 Thread* thread;
1937 {
Ian Rogers50b35e22012-10-04 10:09:15 -07001938 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001939 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1940 if (error != JDWP::ERR_NONE) {
1941 return error;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001942 }
Elliott Hughes9e0c1752013-01-09 14:02:58 -08001943 if (!IsSuspendedForDebugger(soa, thread)) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001944 return JDWP::ERR_THREAD_NOT_SUSPENDED;
1945 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001946 }
Elliott Hughescaf76542012-06-28 16:08:22 -07001947 UniquePtr<Context> context(Context::Create());
Ian Rogers7a22fa62013-01-23 12:16:16 -08001948 GetThisVisitor visitor(thread, context.get(), frame_id);
Ian Rogers0399dde2012-06-06 17:09:28 -07001949 visitor.WalkStack();
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001950 *result = gRegistry->Add(visitor.this_object);
1951 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001952}
1953
Elliott Hughes88d63092013-01-09 09:55:54 -08001954void Dbg::GetLocalValue(JDWP::ObjectId thread_id, JDWP::FrameId frame_id, int slot, JDWP::JdwpTag tag,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001955 uint8_t* buf, size_t width) {
Ian Rogers0399dde2012-06-06 17:09:28 -07001956 struct GetLocalVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -08001957 GetLocalVisitor(Thread* thread, Context* context, JDWP::FrameId frame_id, int slot,
1958 JDWP::JdwpTag tag, uint8_t* buf, size_t width)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001959 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08001960 : StackVisitor(thread, context), frame_id_(frame_id), slot_(slot), tag_(tag),
Ian Rogersca190662012-06-26 15:45:57 -07001961 buf_(buf), width_(width) {}
1962
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001963 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1964 // annotalysis.
1965 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07001966 if (GetFrameId() != frame_id_) {
1967 return true; // Not our frame, carry on.
Elliott Hughesdbb40792011-11-18 17:05:22 -08001968 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001969 // TODO: check that the tag is compatible with the actual type of the slot!
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001970 mirror::AbstractMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07001971 uint16_t reg = DemangleSlot(slot_, m);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001972
Ian Rogers0399dde2012-06-06 17:09:28 -07001973 switch (tag_) {
1974 case JDWP::JT_BOOLEAN:
1975 {
1976 CHECK_EQ(width_, 1U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001977 uint32_t intVal = GetVReg(m, reg, kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07001978 VLOG(jdwp) << "get boolean local " << reg << " = " << intVal;
1979 JDWP::Set1(buf_+1, intVal != 0);
1980 }
1981 break;
1982 case JDWP::JT_BYTE:
1983 {
1984 CHECK_EQ(width_, 1U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001985 uint32_t intVal = GetVReg(m, reg, kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07001986 VLOG(jdwp) << "get byte local " << reg << " = " << intVal;
1987 JDWP::Set1(buf_+1, intVal);
1988 }
1989 break;
1990 case JDWP::JT_SHORT:
1991 case JDWP::JT_CHAR:
1992 {
1993 CHECK_EQ(width_, 2U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001994 uint32_t intVal = GetVReg(m, reg, kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07001995 VLOG(jdwp) << "get short/char local " << reg << " = " << intVal;
1996 JDWP::Set2BE(buf_+1, intVal);
1997 }
1998 break;
1999 case JDWP::JT_INT:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002000 {
2001 CHECK_EQ(width_, 4U);
2002 uint32_t intVal = GetVReg(m, reg, kIntVReg);
2003 VLOG(jdwp) << "get int local " << reg << " = " << intVal;
2004 JDWP::Set4BE(buf_+1, intVal);
2005 }
2006 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002007 case JDWP::JT_FLOAT:
2008 {
2009 CHECK_EQ(width_, 4U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002010 uint32_t intVal = GetVReg(m, reg, kFloatVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002011 VLOG(jdwp) << "get int/float local " << reg << " = " << intVal;
2012 JDWP::Set4BE(buf_+1, intVal);
2013 }
2014 break;
2015 case JDWP::JT_ARRAY:
2016 {
2017 CHECK_EQ(width_, sizeof(JDWP::ObjectId));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002018 mirror::Object* o = reinterpret_cast<mirror::Object*>(GetVReg(m, reg, kReferenceVReg));
Ian Rogers0399dde2012-06-06 17:09:28 -07002019 VLOG(jdwp) << "get array local " << reg << " = " << o;
2020 if (!Runtime::Current()->GetHeap()->IsHeapAddress(o)) {
2021 LOG(FATAL) << "Register " << reg << " expected to hold array: " << o;
2022 }
2023 JDWP::SetObjectId(buf_+1, gRegistry->Add(o));
2024 }
2025 break;
2026 case JDWP::JT_CLASS_LOADER:
2027 case JDWP::JT_CLASS_OBJECT:
2028 case JDWP::JT_OBJECT:
2029 case JDWP::JT_STRING:
2030 case JDWP::JT_THREAD:
2031 case JDWP::JT_THREAD_GROUP:
2032 {
2033 CHECK_EQ(width_, sizeof(JDWP::ObjectId));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002034 mirror::Object* o = reinterpret_cast<mirror::Object*>(GetVReg(m, reg, kReferenceVReg));
Ian Rogers0399dde2012-06-06 17:09:28 -07002035 VLOG(jdwp) << "get object local " << reg << " = " << o;
2036 if (!Runtime::Current()->GetHeap()->IsHeapAddress(o)) {
2037 LOG(FATAL) << "Register " << reg << " expected to hold object: " << o;
2038 }
2039 tag_ = TagFromObject(o);
2040 JDWP::SetObjectId(buf_+1, gRegistry->Add(o));
2041 }
2042 break;
2043 case JDWP::JT_DOUBLE:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002044 {
2045 CHECK_EQ(width_, 8U);
2046 uint32_t lo = GetVReg(m, reg, kDoubleLoVReg);
2047 uint64_t hi = GetVReg(m, reg + 1, kDoubleHiVReg);
2048 uint64_t longVal = (hi << 32) | lo;
2049 VLOG(jdwp) << "get double/long local " << hi << ":" << lo << " = " << longVal;
2050 JDWP::Set8BE(buf_+1, longVal);
2051 }
2052 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002053 case JDWP::JT_LONG:
2054 {
2055 CHECK_EQ(width_, 8U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002056 uint32_t lo = GetVReg(m, reg, kLongLoVReg);
2057 uint64_t hi = GetVReg(m, reg + 1, kLongHiVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002058 uint64_t longVal = (hi << 32) | lo;
2059 VLOG(jdwp) << "get double/long local " << hi << ":" << lo << " = " << longVal;
2060 JDWP::Set8BE(buf_+1, longVal);
2061 }
2062 break;
2063 default:
2064 LOG(FATAL) << "Unknown tag " << tag_;
2065 break;
2066 }
2067
2068 // Prepend tag, which may have been updated.
2069 JDWP::Set1(buf_, tag_);
2070 return false;
2071 }
2072
2073 const JDWP::FrameId frame_id_;
2074 const int slot_;
2075 JDWP::JdwpTag tag_;
2076 uint8_t* const buf_;
2077 const size_t width_;
2078 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002079
2080 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08002081 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002082 Thread* thread;
2083 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
2084 if (error != JDWP::ERR_NONE) {
2085 return;
2086 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002087 UniquePtr<Context> context(Context::Create());
Ian Rogers7a22fa62013-01-23 12:16:16 -08002088 GetLocalVisitor visitor(thread, context.get(), frame_id, slot, tag, buf, width);
Ian Rogers0399dde2012-06-06 17:09:28 -07002089 visitor.WalkStack();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002090}
2091
Elliott Hughes88d63092013-01-09 09:55:54 -08002092void Dbg::SetLocalValue(JDWP::ObjectId thread_id, JDWP::FrameId frame_id, int slot, JDWP::JdwpTag tag,
Ian Rogers0399dde2012-06-06 17:09:28 -07002093 uint64_t value, size_t width) {
2094 struct SetLocalVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -08002095 SetLocalVisitor(Thread* thread, Context* context,
Ian Rogers0399dde2012-06-06 17:09:28 -07002096 JDWP::FrameId frame_id, int slot, JDWP::JdwpTag tag, uint64_t value,
Ian Rogersca190662012-06-26 15:45:57 -07002097 size_t width)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002098 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08002099 : StackVisitor(thread, context),
Elliott Hughes08fc03a2012-06-26 17:34:00 -07002100 frame_id_(frame_id), slot_(slot), tag_(tag), value_(value), width_(width) {}
Ian Rogersca190662012-06-26 15:45:57 -07002101
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002102 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2103 // annotalysis.
2104 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07002105 if (GetFrameId() != frame_id_) {
2106 return true; // Not our frame, carry on.
2107 }
2108 // TODO: check that the tag is compatible with the actual type of the slot!
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002109 mirror::AbstractMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07002110 uint16_t reg = DemangleSlot(slot_, m);
2111
2112 switch (tag_) {
2113 case JDWP::JT_BOOLEAN:
2114 case JDWP::JT_BYTE:
2115 CHECK_EQ(width_, 1U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002116 SetVReg(m, reg, static_cast<uint32_t>(value_), kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002117 break;
2118 case JDWP::JT_SHORT:
2119 case JDWP::JT_CHAR:
2120 CHECK_EQ(width_, 2U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002121 SetVReg(m, reg, static_cast<uint32_t>(value_), kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002122 break;
2123 case JDWP::JT_INT:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002124 CHECK_EQ(width_, 4U);
2125 SetVReg(m, reg, static_cast<uint32_t>(value_), kIntVReg);
2126 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002127 case JDWP::JT_FLOAT:
2128 CHECK_EQ(width_, 4U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002129 SetVReg(m, reg, static_cast<uint32_t>(value_), kFloatVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002130 break;
2131 case JDWP::JT_ARRAY:
2132 case JDWP::JT_OBJECT:
2133 case JDWP::JT_STRING:
2134 {
2135 CHECK_EQ(width_, sizeof(JDWP::ObjectId));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002136 mirror::Object* o = gRegistry->Get<mirror::Object*>(static_cast<JDWP::ObjectId>(value_));
Elliott Hughes64f574f2013-02-20 14:57:12 -08002137 if (o == ObjectRegistry::kInvalidObject) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002138 UNIMPLEMENTED(FATAL) << "return an error code when given an invalid object to store";
2139 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002140 SetVReg(m, reg, static_cast<uint32_t>(reinterpret_cast<uintptr_t>(o)), kReferenceVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002141 }
2142 break;
2143 case JDWP::JT_DOUBLE:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002144 CHECK_EQ(width_, 8U);
2145 SetVReg(m, reg, static_cast<uint32_t>(value_), kDoubleLoVReg);
2146 SetVReg(m, reg + 1, static_cast<uint32_t>(value_ >> 32), kDoubleHiVReg);
2147 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002148 case JDWP::JT_LONG:
2149 CHECK_EQ(width_, 8U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002150 SetVReg(m, reg, static_cast<uint32_t>(value_), kLongLoVReg);
2151 SetVReg(m, reg + 1, static_cast<uint32_t>(value_ >> 32), kLongHiVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002152 break;
2153 default:
2154 LOG(FATAL) << "Unknown tag " << tag_;
2155 break;
2156 }
2157 return false;
2158 }
2159
2160 const JDWP::FrameId frame_id_;
2161 const int slot_;
2162 const JDWP::JdwpTag tag_;
2163 const uint64_t value_;
2164 const size_t width_;
2165 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002166
2167 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08002168 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002169 Thread* thread;
2170 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
2171 if (error != JDWP::ERR_NONE) {
2172 return;
2173 }
Elliott Hughes08fc03a2012-06-26 17:34:00 -07002174 UniquePtr<Context> context(Context::Create());
Ian Rogers7a22fa62013-01-23 12:16:16 -08002175 SetLocalVisitor visitor(thread, context.get(), frame_id, slot, tag, value, width);
Ian Rogers0399dde2012-06-06 17:09:28 -07002176 visitor.WalkStack();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002177}
2178
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002179void Dbg::PostLocationEvent(const mirror::AbstractMethod* m, int dex_pc, mirror::Object* this_object, int event_flags) {
2180 mirror::Class* c = m->GetDeclaringClass();
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002181
2182 JDWP::JdwpLocation location;
Elliott Hughes74847412012-06-20 18:10:21 -07002183 location.type_tag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
Elliott Hughes64f574f2013-02-20 14:57:12 -08002184 location.class_id = gRegistry->AddRefType(c);
Elliott Hughes74847412012-06-20 18:10:21 -07002185 location.method_id = ToMethodId(m);
Elliott Hughes972a47b2012-02-21 18:16:06 -08002186 location.dex_pc = m->IsNative() ? -1 : dex_pc;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002187
Elliott Hughes64f574f2013-02-20 14:57:12 -08002188 // If 'this_object' isn't already in the registry, we know that we're not looking for it,
2189 // so there's no point adding it to the registry and burning through ids.
2190 JDWP::ObjectId this_id = 0;
2191 if (gRegistry->Contains(this_object)) {
2192 this_id = gRegistry->Add(this_object);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002193 }
Elliott Hughes64f574f2013-02-20 14:57:12 -08002194 gJdwpState->PostLocationEvent(&location, this_id, event_flags);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002195}
2196
Elliott Hughescaf76542012-06-28 16:08:22 -07002197void Dbg::PostException(Thread* thread,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002198 JDWP::FrameId throw_frame_id, mirror::AbstractMethod* throw_method,
2199 uint32_t throw_dex_pc, mirror::AbstractMethod* catch_method,
Elliott Hughes64f574f2013-02-20 14:57:12 -08002200 uint32_t catch_dex_pc, mirror::Throwable* exception_object) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002201 if (!IsDebuggerActive()) {
Ian Rogers0ad5bb82011-12-07 10:16:32 -08002202 return;
2203 }
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002204
Elliott Hughesd07986f2011-12-06 18:27:45 -08002205 JDWP::JdwpLocation throw_location;
Elliott Hughescaf76542012-06-28 16:08:22 -07002206 SetLocation(throw_location, throw_method, throw_dex_pc);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002207 JDWP::JdwpLocation catch_location;
Elliott Hughescaf76542012-06-28 16:08:22 -07002208 SetLocation(catch_location, catch_method, catch_dex_pc);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002209
2210 // We need 'this' for InstanceOnly filters.
Elliott Hughescaf76542012-06-28 16:08:22 -07002211 UniquePtr<Context> context(Context::Create());
Ian Rogers7a22fa62013-01-23 12:16:16 -08002212 GetThisVisitor visitor(thread, context.get(), throw_frame_id);
Elliott Hughescaf76542012-06-28 16:08:22 -07002213 visitor.WalkStack();
2214 JDWP::ObjectId this_id = gRegistry->Add(visitor.this_object);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002215
Elliott Hughes64f574f2013-02-20 14:57:12 -08002216 JDWP::ObjectId exception_id = gRegistry->Add(exception_object);
2217 JDWP::RefTypeId exception_class_id = gRegistry->AddRefType(exception_object->GetClass());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002218
2219 gJdwpState->PostException(&throw_location, exception_id, exception_class_id, &catch_location, this_id);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002220}
2221
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002222void Dbg::PostClassPrepare(mirror::Class* c) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002223 if (!IsDebuggerActive()) {
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002224 return;
2225 }
2226
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08002227 // OLD-TODO - we currently always send both "verified" and "prepared" since
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002228 // debuggers seem to like that. There might be some advantage to honesty,
2229 // since the class may not yet be verified.
2230 int state = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
2231 JDWP::JdwpTypeTag tag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
2232 gJdwpState->PostClassPrepare(tag, gRegistry->Add(c), ClassHelper(c).GetDescriptor(), state);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002233}
2234
Elliott Hughescaf76542012-06-28 16:08:22 -07002235void Dbg::UpdateDebugger(int32_t dex_pc, Thread* self) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002236 if (!IsDebuggerActive() || dex_pc == -2 /* fake method exit */) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002237 return;
2238 }
2239
Elliott Hughescaf76542012-06-28 16:08:22 -07002240 size_t frame_id;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002241 mirror::AbstractMethod* m = self->GetCurrentMethod(NULL, &frame_id);
Elliott Hughescaf76542012-06-28 16:08:22 -07002242 //LOG(INFO) << "UpdateDebugger " << PrettyMethod(m) << "@" << dex_pc << " frame " << frame_id;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002243
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002244 if (dex_pc == -1) {
Elliott Hughes2aa2e392012-02-17 17:15:43 -08002245 // We use a pc of -1 to represent method entry, since we might branch back to pc 0 later.
2246 // This means that for this special notification, there can't be anything else interesting
2247 // going on, so we're done already.
Elliott Hughescaf76542012-06-28 16:08:22 -07002248 Dbg::PostLocationEvent(m, 0, GetThis(self, m, frame_id), kMethodEntry);
Elliott Hughes2aa2e392012-02-17 17:15:43 -08002249 return;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002250 }
2251
Elliott Hughes2aa2e392012-02-17 17:15:43 -08002252 int event_flags = 0;
2253
Elliott Hughes86964332012-02-15 19:37:42 -08002254 if (IsBreakpoint(m, dex_pc)) {
2255 event_flags |= kBreakpoint;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002256 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002257
jeffhao09bfc6a2012-12-11 18:11:43 -08002258 {
2259 // If the debugger is single-stepping one of our threads, check to
2260 // see if we're that thread and we've reached a step point.
2261 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
2262 if (gSingleStepControl.is_active && gSingleStepControl.thread == self) {
2263 CHECK(!m->IsNative());
2264 if (gSingleStepControl.step_depth == JDWP::SD_INTO) {
2265 // Step into method calls. We break when the line number
2266 // or method pointer changes. If we're in SS_MIN mode, we
2267 // always stop.
2268 if (gSingleStepControl.method != m) {
2269 event_flags |= kSingleStep;
2270 VLOG(jdwp) << "SS new method";
2271 } else if (gSingleStepControl.step_size == JDWP::SS_MIN) {
Elliott Hughes86964332012-02-15 19:37:42 -08002272 event_flags |= kSingleStep;
2273 VLOG(jdwp) << "SS new instruction";
Elliott Hughes2435a572012-02-17 16:07:41 -08002274 } else if (gSingleStepControl.dex_pcs.find(dex_pc) == gSingleStepControl.dex_pcs.end()) {
2275 event_flags |= kSingleStep;
2276 VLOG(jdwp) << "SS new line";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002277 }
jeffhao09bfc6a2012-12-11 18:11:43 -08002278 } else if (gSingleStepControl.step_depth == JDWP::SD_OVER) {
2279 // Step over method calls. We break when the line number is
2280 // different and the frame depth is <= the original frame
2281 // depth. (We can't just compare on the method, because we
2282 // might get unrolled past it by an exception, and it's tricky
2283 // to identify recursion.)
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002284
jeffhao09bfc6a2012-12-11 18:11:43 -08002285 int stack_depth = GetStackDepth(self);
Elliott Hughes86964332012-02-15 19:37:42 -08002286
jeffhao09bfc6a2012-12-11 18:11:43 -08002287 if (stack_depth < gSingleStepControl.stack_depth) {
2288 // popped up one or more frames, always trigger
2289 event_flags |= kSingleStep;
2290 VLOG(jdwp) << "SS method pop";
2291 } else if (stack_depth == gSingleStepControl.stack_depth) {
2292 // same depth, see if we moved
2293 if (gSingleStepControl.step_size == JDWP::SS_MIN) {
2294 event_flags |= kSingleStep;
2295 VLOG(jdwp) << "SS new instruction";
2296 } else if (gSingleStepControl.dex_pcs.find(dex_pc) == gSingleStepControl.dex_pcs.end()) {
2297 event_flags |= kSingleStep;
2298 VLOG(jdwp) << "SS new line";
2299 }
2300 }
2301 } else {
2302 CHECK_EQ(gSingleStepControl.step_depth, JDWP::SD_OUT);
2303 // Return from the current method. We break when the frame
2304 // depth pops up.
2305
2306 // This differs from the "method exit" break in that it stops
2307 // with the PC at the next instruction in the returned-to
2308 // function, rather than the end of the returning function.
2309
2310 int stack_depth = GetStackDepth(self);
2311 if (stack_depth < gSingleStepControl.stack_depth) {
2312 event_flags |= kSingleStep;
2313 VLOG(jdwp) << "SS method pop";
2314 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002315 }
2316 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002317 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002318
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002319 // Check to see if this is a "return" instruction. JDWP says we should
2320 // send the event *after* the code has been executed, but it also says
2321 // the location we provide is the last instruction. Since the "return"
2322 // instruction has no interesting side effects, we should be safe.
2323 // (We can't just move this down to the returnFromMethod label because
2324 // we potentially need to combine it with other events.)
2325 // We're also not supposed to generate a method exit event if the method
2326 // terminates "with a thrown exception".
Elliott Hughes86964332012-02-15 19:37:42 -08002327 if (dex_pc >= 0) {
2328 const DexFile::CodeItem* code_item = MethodHelper(m).GetCodeItem();
Elliott Hughescaf76542012-06-28 16:08:22 -07002329 CHECK(code_item != NULL) << PrettyMethod(m) << " @" << dex_pc;
Elliott Hughes86964332012-02-15 19:37:42 -08002330 CHECK_LT(dex_pc, static_cast<int32_t>(code_item->insns_size_in_code_units_));
2331 if (Instruction::At(&code_item->insns_[dex_pc])->IsReturn()) {
2332 event_flags |= kMethodExit;
2333 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002334 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002335
2336 // If there's something interesting going on, see if it matches one
2337 // of the debugger filters.
2338 if (event_flags != 0) {
Elliott Hughescaf76542012-06-28 16:08:22 -07002339 Dbg::PostLocationEvent(m, dex_pc, GetThis(self, m, frame_id), event_flags);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002340 }
2341}
2342
Elliott Hughes86964332012-02-15 19:37:42 -08002343void Dbg::WatchLocation(const JDWP::JdwpLocation* location) {
jeffhao09bfc6a2012-12-11 18:11:43 -08002344 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002345 mirror::AbstractMethod* m = FromMethodId(location->method_id);
Elliott Hughes972a47b2012-02-21 18:16:06 -08002346 gBreakpoints.push_back(Breakpoint(m, location->dex_pc));
Elliott Hughes86964332012-02-15 19:37:42 -08002347 VLOG(jdwp) << "Set breakpoint #" << (gBreakpoints.size() - 1) << ": " << gBreakpoints[gBreakpoints.size() - 1];
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002348}
2349
Elliott Hughes86964332012-02-15 19:37:42 -08002350void Dbg::UnwatchLocation(const JDWP::JdwpLocation* location) {
jeffhao09bfc6a2012-12-11 18:11:43 -08002351 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002352 mirror::AbstractMethod* m = FromMethodId(location->method_id);
Elliott Hughes86964332012-02-15 19:37:42 -08002353 for (size_t i = 0; i < gBreakpoints.size(); ++i) {
Elliott Hughes972a47b2012-02-21 18:16:06 -08002354 if (gBreakpoints[i].method == m && gBreakpoints[i].dex_pc == location->dex_pc) {
Elliott Hughes86964332012-02-15 19:37:42 -08002355 VLOG(jdwp) << "Removed breakpoint #" << i << ": " << gBreakpoints[i];
2356 gBreakpoints.erase(gBreakpoints.begin() + i);
2357 return;
2358 }
2359 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002360}
2361
Elliott Hughes221229c2013-01-08 18:17:50 -08002362JDWP::JdwpError Dbg::ConfigureStep(JDWP::ObjectId thread_id, JDWP::JdwpStepSize step_size,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002363 JDWP::JdwpStepDepth step_depth) {
2364 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08002365 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002366 Thread* thread;
2367 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
2368 if (error != JDWP::ERR_NONE) {
2369 return error;
Elliott Hughes2435a572012-02-17 16:07:41 -08002370 }
Elliott Hughes86964332012-02-15 19:37:42 -08002371
jeffhao09bfc6a2012-12-11 18:11:43 -08002372 MutexLock mu2(soa.Self(), *Locks::breakpoint_lock_);
Elliott Hughes86964332012-02-15 19:37:42 -08002373 // TODO: there's no theoretical reason why we couldn't support single-stepping
2374 // of multiple threads at once, but we never did so historically.
2375 if (gSingleStepControl.thread != NULL && thread != gSingleStepControl.thread) {
2376 LOG(WARNING) << "single-step already active for " << *gSingleStepControl.thread
2377 << "; switching to " << *thread;
2378 }
2379
Elliott Hughes2435a572012-02-17 16:07:41 -08002380 //
2381 // Work out what Method* we're in, the current line number, and how deep the stack currently
2382 // is for step-out.
2383 //
2384
Ian Rogers0399dde2012-06-06 17:09:28 -07002385 struct SingleStepStackVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -08002386 SingleStepStackVisitor(Thread* thread)
jeffhao09bfc6a2012-12-11 18:11:43 -08002387 EXCLUSIVE_LOCKS_REQUIRED(Locks::breakpoint_lock_)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002388 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08002389 : StackVisitor(thread, NULL) {
Elliott Hughes86964332012-02-15 19:37:42 -08002390 gSingleStepControl.method = NULL;
2391 gSingleStepControl.stack_depth = 0;
2392 }
Ian Rogersca190662012-06-26 15:45:57 -07002393
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002394 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2395 // annotalysis.
2396 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
jeffhao09bfc6a2012-12-11 18:11:43 -08002397 Locks::breakpoint_lock_->AssertHeld(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002398 const mirror::AbstractMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07002399 if (!m->IsRuntimeMethod()) {
Elliott Hughes86964332012-02-15 19:37:42 -08002400 ++gSingleStepControl.stack_depth;
2401 if (gSingleStepControl.method == NULL) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002402 const mirror::DexCache* dex_cache = m->GetDeclaringClass()->GetDexCache();
Elliott Hughes2435a572012-02-17 16:07:41 -08002403 gSingleStepControl.method = m;
2404 gSingleStepControl.line_number = -1;
2405 if (dex_cache != NULL) {
Ian Rogers4445a7e2012-10-05 17:19:13 -07002406 const DexFile& dex_file = *dex_cache->GetDexFile();
Ian Rogers0399dde2012-06-06 17:09:28 -07002407 gSingleStepControl.line_number = dex_file.GetLineNumFromPC(m, GetDexPc());
Elliott Hughes2435a572012-02-17 16:07:41 -08002408 }
Elliott Hughes86964332012-02-15 19:37:42 -08002409 }
2410 }
Elliott Hughes530fa002012-03-12 11:44:49 -07002411 return true;
Elliott Hughes86964332012-02-15 19:37:42 -08002412 }
2413 };
Ian Rogers7a22fa62013-01-23 12:16:16 -08002414 SingleStepStackVisitor visitor(thread);
Ian Rogers0399dde2012-06-06 17:09:28 -07002415 visitor.WalkStack();
Elliott Hughes86964332012-02-15 19:37:42 -08002416
Elliott Hughes2435a572012-02-17 16:07:41 -08002417 //
2418 // Find the dex_pc values that correspond to the current line, for line-based single-stepping.
2419 //
2420
2421 struct DebugCallbackContext {
jeffhao09bfc6a2012-12-11 18:11:43 -08002422 DebugCallbackContext() EXCLUSIVE_LOCKS_REQUIRED(Locks::breakpoint_lock_) {
Elliott Hughes2435a572012-02-17 16:07:41 -08002423 last_pc_valid = false;
2424 last_pc = 0;
Elliott Hughes2435a572012-02-17 16:07:41 -08002425 }
2426
jeffhao09bfc6a2012-12-11 18:11:43 -08002427 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2428 // annotalysis.
2429 static bool Callback(void* raw_context, uint32_t address, uint32_t line_number) NO_THREAD_SAFETY_ANALYSIS {
2430 Locks::breakpoint_lock_->AssertHeld(Thread::Current());
Elliott Hughes2435a572012-02-17 16:07:41 -08002431 DebugCallbackContext* context = reinterpret_cast<DebugCallbackContext*>(raw_context);
2432 if (static_cast<int32_t>(line_number) == gSingleStepControl.line_number) {
2433 if (!context->last_pc_valid) {
2434 // Everything from this address until the next line change is ours.
2435 context->last_pc = address;
2436 context->last_pc_valid = true;
2437 }
2438 // Otherwise, if we're already in a valid range for this line,
2439 // just keep going (shouldn't really happen)...
2440 } else if (context->last_pc_valid) { // and the line number is new
2441 // Add everything from the last entry up until here to the set
2442 for (uint32_t dex_pc = context->last_pc; dex_pc < address; ++dex_pc) {
2443 gSingleStepControl.dex_pcs.insert(dex_pc);
2444 }
2445 context->last_pc_valid = false;
2446 }
2447 return false; // There may be multiple entries for any given line.
2448 }
2449
jeffhao09bfc6a2012-12-11 18:11:43 -08002450 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2451 // annotalysis.
2452 ~DebugCallbackContext() NO_THREAD_SAFETY_ANALYSIS {
2453 Locks::breakpoint_lock_->AssertHeld(Thread::Current());
Elliott Hughes2435a572012-02-17 16:07:41 -08002454 // If the line number was the last in the position table...
2455 if (last_pc_valid) {
2456 size_t end = MethodHelper(gSingleStepControl.method).GetCodeItem()->insns_size_in_code_units_;
2457 for (uint32_t dex_pc = last_pc; dex_pc < end; ++dex_pc) {
2458 gSingleStepControl.dex_pcs.insert(dex_pc);
2459 }
2460 }
2461 }
2462
2463 bool last_pc_valid;
2464 uint32_t last_pc;
2465 };
Elliott Hughes3e2e1a22012-02-21 11:33:41 -08002466 gSingleStepControl.dex_pcs.clear();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002467 const mirror::AbstractMethod* m = gSingleStepControl.method;
Elliott Hughes3e2e1a22012-02-21 11:33:41 -08002468 if (m->IsNative()) {
2469 gSingleStepControl.line_number = -1;
2470 } else {
2471 DebugCallbackContext context;
2472 MethodHelper mh(m);
2473 mh.GetDexFile().DecodeDebugInfo(mh.GetCodeItem(), m->IsStatic(), m->GetDexMethodIndex(),
2474 DebugCallbackContext::Callback, NULL, &context);
2475 }
Elliott Hughes2435a572012-02-17 16:07:41 -08002476
2477 //
2478 // Everything else...
2479 //
2480
Elliott Hughes86964332012-02-15 19:37:42 -08002481 gSingleStepControl.thread = thread;
2482 gSingleStepControl.step_size = step_size;
2483 gSingleStepControl.step_depth = step_depth;
2484 gSingleStepControl.is_active = true;
2485
Elliott Hughes2435a572012-02-17 16:07:41 -08002486 if (VLOG_IS_ON(jdwp)) {
2487 VLOG(jdwp) << "Single-step thread: " << *gSingleStepControl.thread;
2488 VLOG(jdwp) << "Single-step step size: " << gSingleStepControl.step_size;
2489 VLOG(jdwp) << "Single-step step depth: " << gSingleStepControl.step_depth;
2490 VLOG(jdwp) << "Single-step current method: " << PrettyMethod(gSingleStepControl.method);
2491 VLOG(jdwp) << "Single-step current line: " << gSingleStepControl.line_number;
2492 VLOG(jdwp) << "Single-step current stack depth: " << gSingleStepControl.stack_depth;
2493 VLOG(jdwp) << "Single-step dex_pc values:";
2494 for (std::set<uint32_t>::iterator it = gSingleStepControl.dex_pcs.begin() ; it != gSingleStepControl.dex_pcs.end(); ++it) {
Elliott Hughes229feb72012-02-23 13:33:29 -08002495 VLOG(jdwp) << StringPrintf(" %#x", *it);
Elliott Hughes2435a572012-02-17 16:07:41 -08002496 }
2497 }
2498
2499 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002500}
2501
Elliott Hughes221229c2013-01-08 18:17:50 -08002502void Dbg::UnconfigureStep(JDWP::ObjectId /*thread_id*/) {
jeffhao09bfc6a2012-12-11 18:11:43 -08002503 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Elliott Hughesf8349362012-06-18 15:00:06 -07002504
Elliott Hughes86964332012-02-15 19:37:42 -08002505 gSingleStepControl.is_active = false;
2506 gSingleStepControl.thread = NULL;
Elliott Hughes2435a572012-02-17 16:07:41 -08002507 gSingleStepControl.dex_pcs.clear();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002508}
2509
Elliott Hughes45651fd2012-02-21 15:48:20 -08002510static char JdwpTagToShortyChar(JDWP::JdwpTag tag) {
2511 switch (tag) {
2512 default:
2513 LOG(FATAL) << "unknown JDWP tag: " << PrintableChar(tag);
2514
2515 // Primitives.
2516 case JDWP::JT_BYTE: return 'B';
2517 case JDWP::JT_CHAR: return 'C';
2518 case JDWP::JT_FLOAT: return 'F';
2519 case JDWP::JT_DOUBLE: return 'D';
2520 case JDWP::JT_INT: return 'I';
2521 case JDWP::JT_LONG: return 'J';
2522 case JDWP::JT_SHORT: return 'S';
2523 case JDWP::JT_VOID: return 'V';
2524 case JDWP::JT_BOOLEAN: return 'Z';
2525
2526 // Reference types.
2527 case JDWP::JT_ARRAY:
2528 case JDWP::JT_OBJECT:
2529 case JDWP::JT_STRING:
2530 case JDWP::JT_THREAD:
2531 case JDWP::JT_THREAD_GROUP:
2532 case JDWP::JT_CLASS_LOADER:
2533 case JDWP::JT_CLASS_OBJECT:
2534 return 'L';
2535 }
2536}
2537
Elliott Hughes88d63092013-01-09 09:55:54 -08002538JDWP::JdwpError Dbg::InvokeMethod(JDWP::ObjectId thread_id, JDWP::ObjectId object_id,
2539 JDWP::RefTypeId class_id, JDWP::MethodId method_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002540 uint32_t arg_count, uint64_t* arg_values,
2541 JDWP::JdwpTag* arg_types, uint32_t options,
2542 JDWP::JdwpTag* pResultTag, uint64_t* pResultValue,
2543 JDWP::ObjectId* pExceptionId) {
Elliott Hughesd07986f2011-12-06 18:27:45 -08002544 ThreadList* thread_list = Runtime::Current()->GetThreadList();
2545
2546 Thread* targetThread = NULL;
2547 DebugInvokeReq* req = NULL;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002548 Thread* self = Thread::Current();
Elliott Hughesd07986f2011-12-06 18:27:45 -08002549 {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002550 ScopedObjectAccessUnchecked soa(self);
Ian Rogers50b35e22012-10-04 10:09:15 -07002551 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002552 JDWP::JdwpError error = DecodeThread(soa, thread_id, targetThread);
2553 if (error != JDWP::ERR_NONE) {
2554 LOG(ERROR) << "InvokeMethod request for invalid thread id " << thread_id;
2555 return error;
Elliott Hughesd07986f2011-12-06 18:27:45 -08002556 }
2557 req = targetThread->GetInvokeReq();
2558 if (!req->ready) {
2559 LOG(ERROR) << "InvokeMethod request for thread not stopped by event: " << *targetThread;
2560 return JDWP::ERR_INVALID_THREAD;
2561 }
2562
2563 /*
2564 * We currently have a bug where we don't successfully resume the
2565 * target thread if the suspend count is too deep. We're expected to
2566 * require one "resume" for each "suspend", but when asked to execute
2567 * a method we have to resume fully and then re-suspend it back to the
2568 * same level. (The easiest way to cause this is to type "suspend"
2569 * multiple times in jdb.)
2570 *
2571 * It's unclear what this means when the event specifies "resume all"
2572 * and some threads are suspended more deeply than others. This is
2573 * a rare problem, so for now we just prevent it from hanging forever
2574 * by rejecting the method invocation request. Without this, we will
2575 * be stuck waiting on a suspended thread.
2576 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002577 int suspend_count;
2578 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002579 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002580 suspend_count = targetThread->GetSuspendCount();
2581 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08002582 if (suspend_count > 1) {
2583 LOG(ERROR) << *targetThread << " suspend count too deep for method invocation: " << suspend_count;
2584 return JDWP::ERR_THREAD_SUSPENDED; // Probably not expected here.
2585 }
2586
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002587 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002588 mirror::Object* receiver = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08002589 if (receiver == ObjectRegistry::kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002590 return JDWP::ERR_INVALID_OBJECT;
2591 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002592
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002593 mirror::Object* thread = gRegistry->Get<mirror::Object*>(thread_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08002594 if (thread == ObjectRegistry::kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002595 return JDWP::ERR_INVALID_OBJECT;
2596 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002597 // TODO: check that 'thread' is actually a java.lang.Thread!
2598
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002599 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes45651fd2012-02-21 15:48:20 -08002600 if (c == NULL) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002601 return status;
2602 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002603
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002604 mirror::AbstractMethod* m = FromMethodId(method_id);
Elliott Hughes45651fd2012-02-21 15:48:20 -08002605 if (m->IsStatic() != (receiver == NULL)) {
2606 return JDWP::ERR_INVALID_METHODID;
2607 }
2608 if (m->IsStatic()) {
2609 if (m->GetDeclaringClass() != c) {
2610 return JDWP::ERR_INVALID_METHODID;
2611 }
2612 } else {
2613 if (!m->GetDeclaringClass()->IsAssignableFrom(c)) {
2614 return JDWP::ERR_INVALID_METHODID;
2615 }
2616 }
2617
2618 // Check the argument list matches the method.
2619 MethodHelper mh(m);
2620 if (mh.GetShortyLength() - 1 != arg_count) {
2621 return JDWP::ERR_ILLEGAL_ARGUMENT;
2622 }
2623 const char* shorty = mh.GetShorty();
2624 for (size_t i = 0; i < arg_count; ++i) {
2625 if (shorty[i + 1] != JdwpTagToShortyChar(arg_types[i])) {
2626 return JDWP::ERR_ILLEGAL_ARGUMENT;
2627 }
2628 }
2629
2630 req->receiver_ = receiver;
2631 req->thread_ = thread;
2632 req->class_ = c;
2633 req->method_ = m;
2634 req->arg_count_ = arg_count;
2635 req->arg_values_ = arg_values;
Elliott Hughesd07986f2011-12-06 18:27:45 -08002636 req->options_ = options;
2637 req->invoke_needed_ = true;
2638 }
2639
2640 // The fact that we've released the thread list lock is a bit risky --- if the thread goes
2641 // away we're sitting high and dry -- but we must release this before the ResumeAllThreads
2642 // call, and it's unwise to hold it during WaitForSuspend.
2643
2644 {
2645 /*
2646 * We change our (JDWP thread) status, which should be THREAD_RUNNING,
Elliott Hughes81ff3182012-03-23 20:35:56 -07002647 * so we can suspend for a GC if the invoke request causes us to
Elliott Hughesd07986f2011-12-06 18:27:45 -08002648 * run out of memory. It's also a good idea to change it before locking
2649 * the invokeReq mutex, although that should never be held for long.
2650 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002651 self->TransitionFromRunnableToSuspended(kWaitingForDebuggerSend);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002652
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002653 VLOG(jdwp) << " Transferring control to event thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002654 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002655 MutexLock mu(self, req->lock_);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002656
2657 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002658 VLOG(jdwp) << " Resuming all threads";
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002659 thread_list->UndoDebuggerSuspensions();
Elliott Hughesd07986f2011-12-06 18:27:45 -08002660 } else {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002661 VLOG(jdwp) << " Resuming event thread only";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002662 thread_list->Resume(targetThread, true);
2663 }
2664
2665 // Wait for the request to finish executing.
2666 while (req->invoke_needed_) {
Ian Rogersc604d732012-10-14 16:09:54 -07002667 req->cond_.Wait(self);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002668 }
2669 }
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002670 VLOG(jdwp) << " Control has returned from event thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002671
2672 /* wait for thread to re-suspend itself */
Elliott Hughes221229c2013-01-08 18:17:50 -08002673 SuspendThread(thread_id, false /* request_suspension */ );
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002674 self->TransitionFromSuspendedToRunnable();
Elliott Hughesd07986f2011-12-06 18:27:45 -08002675 }
2676
2677 /*
2678 * Suspend the threads. We waited for the target thread to suspend
2679 * itself, so all we need to do is suspend the others.
2680 *
2681 * The suspendAllThreads() call will double-suspend the event thread,
2682 * so we want to resume the target thread once to keep the books straight.
2683 */
2684 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002685 self->TransitionFromRunnableToSuspended(kWaitingForDebuggerSuspension);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002686 VLOG(jdwp) << " Suspending all threads";
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002687 thread_list->SuspendAllForDebugger();
2688 self->TransitionFromSuspendedToRunnable();
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002689 VLOG(jdwp) << " Resuming event thread to balance the count";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002690 thread_list->Resume(targetThread, true);
2691 }
2692
2693 // Copy the result.
2694 *pResultTag = req->result_tag;
2695 if (IsPrimitiveTag(req->result_tag)) {
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002696 *pResultValue = req->result_value.GetJ();
Elliott Hughesd07986f2011-12-06 18:27:45 -08002697 } else {
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002698 *pResultValue = gRegistry->Add(req->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002699 }
2700 *pExceptionId = req->exception;
2701 return req->error;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002702}
2703
2704void Dbg::ExecuteMethod(DebugInvokeReq* pReq) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002705 ScopedObjectAccess soa(Thread::Current());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002706
Elliott Hughes81ff3182012-03-23 20:35:56 -07002707 // We can be called while an exception is pending. We need
Elliott Hughesd07986f2011-12-06 18:27:45 -08002708 // to preserve that across the method invocation.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002709 SirtRef<mirror::Throwable> old_exception(soa.Self(), soa.Self()->GetException());
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002710 soa.Self()->ClearException();
Elliott Hughesd07986f2011-12-06 18:27:45 -08002711
2712 // Translate the method through the vtable, unless the debugger wants to suppress it.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002713 mirror::AbstractMethod* m = pReq->method_;
Elliott Hughesd07986f2011-12-06 18:27:45 -08002714 if ((pReq->options_ & JDWP::INVOKE_NONVIRTUAL) == 0 && pReq->receiver_ != NULL) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002715 mirror::AbstractMethod* actual_method = pReq->class_->FindVirtualMethodForVirtualOrInterface(pReq->method_);
Elliott Hughes45651fd2012-02-21 15:48:20 -08002716 if (actual_method != m) {
2717 VLOG(jdwp) << "ExecuteMethod translated " << PrettyMethod(m) << " to " << PrettyMethod(actual_method);
2718 m = actual_method;
2719 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08002720 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002721 VLOG(jdwp) << "ExecuteMethod " << PrettyMethod(m);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002722 CHECK(m != NULL);
2723
2724 CHECK_EQ(sizeof(jvalue), sizeof(uint64_t));
2725
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002726 LOG(INFO) << "self=" << soa.Self() << " pReq->receiver_=" << pReq->receiver_ << " m=" << m
2727 << " #" << pReq->arg_count_ << " " << pReq->arg_values_;
Jeff Hao5d917302013-02-27 17:57:33 -08002728
2729 MethodHelper mh(m);
2730 ArgArray arg_array(mh.GetShorty(), mh.GetShortyLength());
2731 arg_array.BuildArgArray(soa, pReq->receiver_, reinterpret_cast<jvalue*>(pReq->arg_values_));
2732 JValue unused_result;
2733 if (mh.IsReturnFloatOrDouble()) {
2734 InvokeWithArgArray(soa, m, &arg_array, &unused_result, &pReq->result_value);
2735 } else {
2736 InvokeWithArgArray(soa, m, &arg_array, &pReq->result_value, &unused_result);
2737 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08002738
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002739 pReq->exception = gRegistry->Add(soa.Self()->GetException());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002740 pReq->result_tag = BasicTagFromDescriptor(MethodHelper(m).GetShorty());
2741 if (pReq->exception != 0) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002742 mirror::Object* exc = soa.Self()->GetException();
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002743 VLOG(jdwp) << " JDWP invocation returning with exception=" << exc << " " << PrettyTypeOf(exc);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002744 soa.Self()->ClearException();
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002745 pReq->result_value.SetJ(0);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002746 } else if (pReq->result_tag == JDWP::JT_OBJECT) {
2747 /* if no exception thrown, examine object result more closely */
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002748 JDWP::JdwpTag new_tag = TagFromObject(pReq->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002749 if (new_tag != pReq->result_tag) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002750 VLOG(jdwp) << " JDWP promoted result from " << pReq->result_tag << " to " << new_tag;
Elliott Hughesd07986f2011-12-06 18:27:45 -08002751 pReq->result_tag = new_tag;
2752 }
2753
2754 /*
2755 * Register the object. We don't actually need an ObjectId yet,
2756 * but we do need to be sure that the GC won't move or discard the
2757 * object when we switch out of RUNNING. The ObjectId conversion
2758 * will add the object to the "do not touch" list.
2759 *
2760 * We can't use the "tracked allocation" mechanism here because
2761 * the object is going to be handed off to a different thread.
2762 */
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002763 gRegistry->Add(pReq->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002764 }
2765
2766 if (old_exception.get() != NULL) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002767 soa.Self()->SetException(old_exception.get());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002768 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002769}
2770
Elliott Hughesd07986f2011-12-06 18:27:45 -08002771/*
Elliott Hughes4b9702c2013-02-20 18:13:24 -08002772 * "request" contains a full JDWP packet, possibly with multiple chunks. We
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002773 * need to process each, accumulate the replies, and ship the whole thing
2774 * back.
2775 *
2776 * Returns "true" if we have a reply. The reply buffer is newly allocated,
2777 * and includes the chunk type/length, followed by the data.
2778 *
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08002779 * OLD-TODO: we currently assume that the request and reply include a single
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002780 * chunk. If this becomes inconvenient we will need to adapt.
2781 */
Elliott Hughes4b9702c2013-02-20 18:13:24 -08002782bool Dbg::DdmHandlePacket(JDWP::Request& request, uint8_t** pReplyBuf, int* pReplyLen) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002783 Thread* self = Thread::Current();
2784 JNIEnv* env = self->GetJniEnv();
2785
Elliott Hughes4b9702c2013-02-20 18:13:24 -08002786 uint32_t type = request.ReadUnsigned32("type");
2787 uint32_t length = request.ReadUnsigned32("length");
2788
2789 // Create a byte[] corresponding to 'request'.
2790 size_t request_length = request.size();
2791 ScopedLocalRef<jbyteArray> dataArray(env, env->NewByteArray(request_length));
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002792 if (dataArray.get() == NULL) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08002793 LOG(WARNING) << "byte[] allocation failed: " << request_length;
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002794 env->ExceptionClear();
2795 return false;
2796 }
Elliott Hughes4b9702c2013-02-20 18:13:24 -08002797 env->SetByteArrayRegion(dataArray.get(), 0, request_length, reinterpret_cast<const jbyte*>(request.data()));
2798 request.Skip(request_length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002799
2800 // Run through and find all chunks. [Currently just find the first.]
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002801 ScopedByteArrayRO contents(env, dataArray.get());
Elliott Hughes4b9702c2013-02-20 18:13:24 -08002802 if (length != request_length) {
2803 LOG(WARNING) << StringPrintf("bad chunk found (len=%u pktLen=%d)", length, request_length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002804 return false;
2805 }
2806
2807 // Call "private static Chunk dispatch(int type, byte[] data, int offset, int length)".
Elliott Hugheseac76672012-05-24 21:56:51 -07002808 ScopedLocalRef<jobject> chunk(env, env->CallStaticObjectMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
2809 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_dispatch,
Elliott Hughes4b9702c2013-02-20 18:13:24 -08002810 type, dataArray.get(), 0, length));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002811 if (env->ExceptionCheck()) {
2812 LOG(INFO) << StringPrintf("Exception thrown by dispatcher for 0x%08x", type);
2813 env->ExceptionDescribe();
2814 env->ExceptionClear();
2815 return false;
2816 }
2817
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002818 if (chunk.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002819 return false;
2820 }
2821
2822 /*
2823 * Pull the pieces out of the chunk. We copy the results into a
2824 * newly-allocated buffer that the caller can free. We don't want to
2825 * continue using the Chunk object because nothing has a reference to it.
2826 *
2827 * We could avoid this by returning type/data/offset/length and having
2828 * the caller be aware of the object lifetime issues, but that
Elliott Hughes81ff3182012-03-23 20:35:56 -07002829 * integrates the JDWP code more tightly into the rest of the runtime, and doesn't work
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002830 * if we have responses for multiple chunks.
2831 *
2832 * So we're pretty much stuck with copying data around multiple times.
2833 */
Elliott Hugheseac76672012-05-24 21:56:51 -07002834 ScopedLocalRef<jbyteArray> replyData(env, reinterpret_cast<jbyteArray>(env->GetObjectField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_data)));
Elliott Hughes4b9702c2013-02-20 18:13:24 -08002835 jint offset = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_offset);
Elliott Hugheseac76672012-05-24 21:56:51 -07002836 length = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_length);
Elliott Hugheseac76672012-05-24 21:56:51 -07002837 type = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_type);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002838
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002839 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 -07002840 if (length == 0 || replyData.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002841 return false;
2842 }
2843
Elliott Hughes4b9702c2013-02-20 18:13:24 -08002844 const int kChunkHdrLen = 8;
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002845 uint8_t* reply = new uint8_t[length + kChunkHdrLen];
2846 if (reply == NULL) {
2847 LOG(WARNING) << "malloc failed: " << (length + kChunkHdrLen);
2848 return false;
2849 }
Elliott Hughesf7c3b662011-10-27 12:04:56 -07002850 JDWP::Set4BE(reply + 0, type);
2851 JDWP::Set4BE(reply + 4, length);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002852 env->GetByteArrayRegion(replyData.get(), offset, length, reinterpret_cast<jbyte*>(reply + kChunkHdrLen));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002853
2854 *pReplyBuf = reply;
2855 *pReplyLen = length + kChunkHdrLen;
2856
Elliott Hughes4b9702c2013-02-20 18:13:24 -08002857 VLOG(jdwp) << StringPrintf("dvmHandleDdm returning type=%.4s %p len=%d", reinterpret_cast<char*>(reply), reply, length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002858 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002859}
2860
Elliott Hughesa2155262011-11-16 16:26:58 -08002861void Dbg::DdmBroadcast(bool connect) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002862 VLOG(jdwp) << "Broadcasting DDM " << (connect ? "connect" : "disconnect") << "...";
Elliott Hughes47fce012011-10-25 18:37:19 -07002863
2864 Thread* self = Thread::Current();
Ian Rogers50b35e22012-10-04 10:09:15 -07002865 if (self->GetState() != kRunnable) {
2866 LOG(ERROR) << "DDM broadcast in thread state " << self->GetState();
2867 /* try anyway? */
Elliott Hughes47fce012011-10-25 18:37:19 -07002868 }
2869
2870 JNIEnv* env = self->GetJniEnv();
Elliott Hughes47fce012011-10-25 18:37:19 -07002871 jint event = connect ? 1 /*DdmServer.CONNECTED*/ : 2 /*DdmServer.DISCONNECTED*/;
Elliott Hugheseac76672012-05-24 21:56:51 -07002872 env->CallStaticVoidMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
2873 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_broadcast,
2874 event);
Elliott Hughes47fce012011-10-25 18:37:19 -07002875 if (env->ExceptionCheck()) {
2876 LOG(ERROR) << "DdmServer.broadcast " << event << " failed";
2877 env->ExceptionDescribe();
2878 env->ExceptionClear();
2879 }
2880}
2881
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002882void Dbg::DdmConnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08002883 Dbg::DdmBroadcast(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002884}
2885
2886void Dbg::DdmDisconnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08002887 Dbg::DdmBroadcast(false);
Elliott Hughes47fce012011-10-25 18:37:19 -07002888 gDdmThreadNotification = false;
2889}
2890
2891/*
Elliott Hughes82188472011-11-07 18:11:48 -08002892 * Send a notification when a thread starts, stops, or changes its name.
Elliott Hughes47fce012011-10-25 18:37:19 -07002893 *
2894 * Because we broadcast the full set of threads when the notifications are
2895 * first enabled, it's possible for "thread" to be actively executing.
2896 */
Elliott Hughes82188472011-11-07 18:11:48 -08002897void Dbg::DdmSendThreadNotification(Thread* t, uint32_t type) {
Elliott Hughes47fce012011-10-25 18:37:19 -07002898 if (!gDdmThreadNotification) {
2899 return;
2900 }
2901
Elliott Hughes82188472011-11-07 18:11:48 -08002902 if (type == CHUNK_TYPE("THDE")) {
Elliott Hughes47fce012011-10-25 18:37:19 -07002903 uint8_t buf[4];
Elliott Hughesf7c3b662011-10-27 12:04:56 -07002904 JDWP::Set4BE(&buf[0], t->GetThinLockId());
Elliott Hughes47fce012011-10-25 18:37:19 -07002905 Dbg::DdmSendChunk(CHUNK_TYPE("THDE"), 4, buf);
Elliott Hughes82188472011-11-07 18:11:48 -08002906 } else {
2907 CHECK(type == CHUNK_TYPE("THCR") || type == CHUNK_TYPE("THNM")) << type;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002908 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002909 SirtRef<mirror::String> name(soa.Self(), t->GetThreadName(soa));
Elliott Hughes82188472011-11-07 18:11:48 -08002910 size_t char_count = (name.get() != NULL) ? name->GetLength() : 0;
jeffhao725a9572012-11-13 18:20:12 -08002911 const jchar* chars = (name.get() != NULL) ? name->GetCharArray()->GetData() : NULL;
Elliott Hughes82188472011-11-07 18:11:48 -08002912
Elliott Hughes21f32d72011-11-09 17:44:13 -08002913 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08002914 JDWP::Append4BE(bytes, t->GetThinLockId());
2915 JDWP::AppendUtf16BE(bytes, chars, char_count);
Elliott Hughes21f32d72011-11-09 17:44:13 -08002916 CHECK_EQ(bytes.size(), char_count*2 + sizeof(uint32_t)*2);
2917 Dbg::DdmSendChunk(type, bytes);
Elliott Hughes47fce012011-10-25 18:37:19 -07002918 }
2919}
2920
Elliott Hughes47fce012011-10-25 18:37:19 -07002921void Dbg::DdmSetThreadNotification(bool enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002922 // Enable/disable thread notifications.
Elliott Hughes47fce012011-10-25 18:37:19 -07002923 gDdmThreadNotification = enable;
2924 if (enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002925 // Suspend the VM then post thread start notifications for all threads. Threads attaching will
2926 // see a suspension in progress and block until that ends. They then post their own start
2927 // notification.
2928 SuspendVM();
2929 std::list<Thread*> threads;
Ian Rogers50b35e22012-10-04 10:09:15 -07002930 Thread* self = Thread::Current();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002931 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002932 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002933 threads = Runtime::Current()->GetThreadList()->GetList();
2934 }
2935 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002936 ScopedObjectAccess soa(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002937 typedef std::list<Thread*>::const_iterator It; // TODO: C++0x auto
2938 for (It it = threads.begin(), end = threads.end(); it != end; ++it) {
2939 Dbg::DdmSendThreadNotification(*it, CHUNK_TYPE("THCR"));
2940 }
2941 }
2942 ResumeVM();
Elliott Hughes47fce012011-10-25 18:37:19 -07002943 }
2944}
2945
Elliott Hughesa2155262011-11-16 16:26:58 -08002946void Dbg::PostThreadStartOrStop(Thread* t, uint32_t type) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002947 if (IsDebuggerActive()) {
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07002948 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogerscfaa4552012-11-26 21:00:08 -08002949 JDWP::ObjectId id = gRegistry->Add(t->GetPeer());
Elliott Hughes82188472011-11-07 18:11:48 -08002950 gJdwpState->PostThreadChange(id, type == CHUNK_TYPE("THCR"));
Elliott Hughesc0f09332012-03-26 13:27:06 -07002951 // If this thread's just joined the party while we're already debugging, make sure it knows
2952 // to give us updates when it's running.
2953 t->SetDebuggerUpdatesEnabled(true);
Elliott Hughes47fce012011-10-25 18:37:19 -07002954 }
Elliott Hughes82188472011-11-07 18:11:48 -08002955 Dbg::DdmSendThreadNotification(t, type);
Elliott Hughes47fce012011-10-25 18:37:19 -07002956}
2957
2958void Dbg::PostThreadStart(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08002959 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07002960}
2961
2962void Dbg::PostThreadDeath(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08002963 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THDE"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002964}
2965
Elliott Hughes82188472011-11-07 18:11:48 -08002966void Dbg::DdmSendChunk(uint32_t type, size_t byte_count, const uint8_t* buf) {
Elliott Hughes3bb81562011-10-21 18:52:59 -07002967 CHECK(buf != NULL);
2968 iovec vec[1];
2969 vec[0].iov_base = reinterpret_cast<void*>(const_cast<uint8_t*>(buf));
2970 vec[0].iov_len = byte_count;
2971 Dbg::DdmSendChunkV(type, vec, 1);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002972}
2973
Elliott Hughes21f32d72011-11-09 17:44:13 -08002974void Dbg::DdmSendChunk(uint32_t type, const std::vector<uint8_t>& bytes) {
2975 DdmSendChunk(type, bytes.size(), &bytes[0]);
2976}
2977
Elliott Hughescccd84f2011-12-05 16:51:54 -08002978void Dbg::DdmSendChunkV(uint32_t type, const struct iovec* iov, int iov_count) {
Elliott Hughes3bb81562011-10-21 18:52:59 -07002979 if (gJdwpState == NULL) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002980 VLOG(jdwp) << "Debugger thread not active, ignoring DDM send: " << type;
Elliott Hughes3bb81562011-10-21 18:52:59 -07002981 } else {
Elliott Hughescccd84f2011-12-05 16:51:54 -08002982 gJdwpState->DdmSendChunkV(type, iov, iov_count);
Elliott Hughes3bb81562011-10-21 18:52:59 -07002983 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002984}
2985
Elliott Hughes767a1472011-10-26 18:49:02 -07002986int Dbg::DdmHandleHpifChunk(HpifWhen when) {
2987 if (when == HPIF_WHEN_NOW) {
Elliott Hughes7162ad92011-10-27 14:08:42 -07002988 DdmSendHeapInfo(when);
Elliott Hughes767a1472011-10-26 18:49:02 -07002989 return true;
2990 }
2991
2992 if (when != HPIF_WHEN_NEVER && when != HPIF_WHEN_NEXT_GC && when != HPIF_WHEN_EVERY_GC) {
2993 LOG(ERROR) << "invalid HpifWhen value: " << static_cast<int>(when);
2994 return false;
2995 }
2996
2997 gDdmHpifWhen = when;
2998 return true;
2999}
3000
3001bool Dbg::DdmHandleHpsgNhsgChunk(Dbg::HpsgWhen when, Dbg::HpsgWhat what, bool native) {
3002 if (when != HPSG_WHEN_NEVER && when != HPSG_WHEN_EVERY_GC) {
3003 LOG(ERROR) << "invalid HpsgWhen value: " << static_cast<int>(when);
3004 return false;
3005 }
3006
3007 if (what != HPSG_WHAT_MERGED_OBJECTS && what != HPSG_WHAT_DISTINCT_OBJECTS) {
3008 LOG(ERROR) << "invalid HpsgWhat value: " << static_cast<int>(what);
3009 return false;
3010 }
3011
3012 if (native) {
3013 gDdmNhsgWhen = when;
3014 gDdmNhsgWhat = what;
3015 } else {
3016 gDdmHpsgWhen = when;
3017 gDdmHpsgWhat = what;
3018 }
3019 return true;
3020}
3021
Elliott Hughes7162ad92011-10-27 14:08:42 -07003022void Dbg::DdmSendHeapInfo(HpifWhen reason) {
3023 // If there's a one-shot 'when', reset it.
3024 if (reason == gDdmHpifWhen) {
3025 if (gDdmHpifWhen == HPIF_WHEN_NEXT_GC) {
3026 gDdmHpifWhen = HPIF_WHEN_NEVER;
3027 }
3028 }
3029
3030 /*
3031 * Chunk HPIF (client --> server)
3032 *
3033 * Heap Info. General information about the heap,
3034 * suitable for a summary display.
3035 *
3036 * [u4]: number of heaps
3037 *
3038 * For each heap:
3039 * [u4]: heap ID
3040 * [u8]: timestamp in ms since Unix epoch
3041 * [u1]: capture reason (same as 'when' value from server)
3042 * [u4]: max heap size in bytes (-Xmx)
3043 * [u4]: current heap size in bytes
3044 * [u4]: current number of bytes allocated
3045 * [u4]: current number of objects allocated
3046 */
3047 uint8_t heap_count = 1;
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08003048 Heap* heap = Runtime::Current()->GetHeap();
Elliott Hughes21f32d72011-11-09 17:44:13 -08003049 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08003050 JDWP::Append4BE(bytes, heap_count);
3051 JDWP::Append4BE(bytes, 1); // Heap id (bogus; we only have one heap).
3052 JDWP::Append8BE(bytes, MilliTime());
3053 JDWP::Append1BE(bytes, reason);
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08003054 JDWP::Append4BE(bytes, heap->GetMaxMemory()); // Max allowed heap size in bytes.
3055 JDWP::Append4BE(bytes, heap->GetTotalMemory()); // Current heap size in bytes.
3056 JDWP::Append4BE(bytes, heap->GetBytesAllocated());
3057 JDWP::Append4BE(bytes, heap->GetObjectsAllocated());
Elliott Hughes21f32d72011-11-09 17:44:13 -08003058 CHECK_EQ(bytes.size(), 4U + (heap_count * (4 + 8 + 1 + 4 + 4 + 4 + 4)));
3059 Dbg::DdmSendChunk(CHUNK_TYPE("HPIF"), bytes);
Elliott Hughes767a1472011-10-26 18:49:02 -07003060}
3061
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003062enum HpsgSolidity {
3063 SOLIDITY_FREE = 0,
3064 SOLIDITY_HARD = 1,
3065 SOLIDITY_SOFT = 2,
3066 SOLIDITY_WEAK = 3,
3067 SOLIDITY_PHANTOM = 4,
3068 SOLIDITY_FINALIZABLE = 5,
3069 SOLIDITY_SWEEP = 6,
3070};
3071
3072enum HpsgKind {
3073 KIND_OBJECT = 0,
3074 KIND_CLASS_OBJECT = 1,
3075 KIND_ARRAY_1 = 2,
3076 KIND_ARRAY_2 = 3,
3077 KIND_ARRAY_4 = 4,
3078 KIND_ARRAY_8 = 5,
3079 KIND_UNKNOWN = 6,
3080 KIND_NATIVE = 7,
3081};
3082
3083#define HPSG_PARTIAL (1<<7)
3084#define HPSG_STATE(solidity, kind) ((uint8_t)((((kind) & 0x7) << 3) | ((solidity) & 0x7)))
3085
Ian Rogers30fab402012-01-23 15:43:46 -08003086class HeapChunkContext {
3087 public:
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003088 // Maximum chunk size. Obtain this from the formula:
3089 // (((maximum_heap_size / ALLOCATION_UNIT_SIZE) + 255) / 256) * 2
3090 HeapChunkContext(bool merge, bool native)
Ian Rogers30fab402012-01-23 15:43:46 -08003091 : buf_(16384 - 16),
3092 type_(0),
3093 merge_(merge) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003094 Reset();
3095 if (native) {
Ian Rogers30fab402012-01-23 15:43:46 -08003096 type_ = CHUNK_TYPE("NHSG");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003097 } else {
Ian Rogers30fab402012-01-23 15:43:46 -08003098 type_ = merge ? CHUNK_TYPE("HPSG") : CHUNK_TYPE("HPSO");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003099 }
3100 }
3101
3102 ~HeapChunkContext() {
Ian Rogers30fab402012-01-23 15:43:46 -08003103 if (p_ > &buf_[0]) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003104 Flush();
3105 }
3106 }
3107
3108 void EnsureHeader(const void* chunk_ptr) {
Ian Rogers30fab402012-01-23 15:43:46 -08003109 if (!needHeader_) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003110 return;
3111 }
3112
3113 // Start a new HPSx chunk.
Ian Rogers30fab402012-01-23 15:43:46 -08003114 JDWP::Write4BE(&p_, 1); // Heap id (bogus; we only have one heap).
3115 JDWP::Write1BE(&p_, 8); // Size of allocation unit, in bytes.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003116
Ian Rogers30fab402012-01-23 15:43:46 -08003117 JDWP::Write4BE(&p_, reinterpret_cast<uintptr_t>(chunk_ptr)); // virtual address of segment start.
3118 JDWP::Write4BE(&p_, 0); // offset of this piece (relative to the virtual address).
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003119 // [u4]: length of piece, in allocation units
3120 // 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 -08003121 pieceLenField_ = p_;
3122 JDWP::Write4BE(&p_, 0x55555555);
3123 needHeader_ = false;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003124 }
3125
Ian Rogersb726dcb2012-09-05 08:57:23 -07003126 void Flush() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogersd636b062013-01-18 17:51:18 -08003127 if (pieceLenField_ == NULL) {
3128 // Flush immediately post Reset (maybe back-to-back Flush). Ignore.
3129 CHECK(needHeader_);
3130 return;
3131 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003132 // Patch the "length of piece" field.
Ian Rogers30fab402012-01-23 15:43:46 -08003133 CHECK_LE(&buf_[0], pieceLenField_);
3134 CHECK_LE(pieceLenField_, p_);
3135 JDWP::Set4BE(pieceLenField_, totalAllocationUnits_);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003136
Ian Rogers30fab402012-01-23 15:43:46 -08003137 Dbg::DdmSendChunk(type_, p_ - &buf_[0], &buf_[0]);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003138 Reset();
3139 }
3140
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003141 static void HeapChunkCallback(void* start, void* end, size_t used_bytes, void* arg)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003142 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_,
3143 Locks::mutator_lock_) {
Ian Rogers30fab402012-01-23 15:43:46 -08003144 reinterpret_cast<HeapChunkContext*>(arg)->HeapChunkCallback(start, end, used_bytes);
Elliott Hughesa2155262011-11-16 16:26:58 -08003145 }
3146
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003147 private:
Elliott Hughesa2155262011-11-16 16:26:58 -08003148 enum { ALLOCATION_UNIT_SIZE = 8 };
3149
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003150 void Reset() {
Ian Rogers30fab402012-01-23 15:43:46 -08003151 p_ = &buf_[0];
Ian Rogers15bf2d32012-08-28 17:33:04 -07003152 startOfNextMemoryChunk_ = NULL;
Ian Rogers30fab402012-01-23 15:43:46 -08003153 totalAllocationUnits_ = 0;
3154 needHeader_ = true;
3155 pieceLenField_ = NULL;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003156 }
3157
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003158 void HeapChunkCallback(void* start, void* /*end*/, size_t used_bytes)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003159 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_,
3160 Locks::mutator_lock_) {
Ian Rogers30fab402012-01-23 15:43:46 -08003161 // Note: heap call backs cannot manipulate the heap upon which they are crawling, care is taken
3162 // in the following code not to allocate memory, by ensuring buf_ is of the correct size
Ian Rogers15bf2d32012-08-28 17:33:04 -07003163 if (used_bytes == 0) {
3164 if (start == NULL) {
3165 // Reset for start of new heap.
3166 startOfNextMemoryChunk_ = NULL;
3167 Flush();
3168 }
3169 // Only process in use memory so that free region information
3170 // also includes dlmalloc book keeping.
Elliott Hughesa2155262011-11-16 16:26:58 -08003171 return;
Elliott Hughesa2155262011-11-16 16:26:58 -08003172 }
3173
Ian Rogers15bf2d32012-08-28 17:33:04 -07003174 /* If we're looking at the native heap, we'll just return
3175 * (SOLIDITY_HARD, KIND_NATIVE) for all allocated chunks
3176 */
3177 bool native = type_ == CHUNK_TYPE("NHSG");
3178
3179 if (startOfNextMemoryChunk_ != NULL) {
3180 // Transmit any pending free memory. Native free memory of
3181 // over kMaxFreeLen could be because of the use of mmaps, so
3182 // don't report. If not free memory then start a new segment.
3183 bool flush = true;
3184 if (start > startOfNextMemoryChunk_) {
3185 const size_t kMaxFreeLen = 2 * kPageSize;
3186 void* freeStart = startOfNextMemoryChunk_;
3187 void* freeEnd = start;
3188 size_t freeLen = (char*)freeEnd - (char*)freeStart;
3189 if (!native || freeLen < kMaxFreeLen) {
3190 AppendChunk(HPSG_STATE(SOLIDITY_FREE, 0), freeStart, freeLen);
3191 flush = false;
3192 }
3193 }
3194 if (flush) {
3195 startOfNextMemoryChunk_ = NULL;
3196 Flush();
3197 }
3198 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003199 const mirror::Object* obj = reinterpret_cast<const mirror::Object*>(start);
Elliott Hughesa2155262011-11-16 16:26:58 -08003200
3201 // Determine the type of this chunk.
3202 // OLD-TODO: if context.merge, see if this chunk is different from the last chunk.
3203 // If it's the same, we should combine them.
Ian Rogers15bf2d32012-08-28 17:33:04 -07003204 uint8_t state = ExamineObject(obj, native);
3205 // dlmalloc's chunk header is 2 * sizeof(size_t), but if the previous chunk is in use for an
3206 // allocation then the first sizeof(size_t) may belong to it.
3207 const size_t dlMallocOverhead = sizeof(size_t);
3208 AppendChunk(state, start, used_bytes + dlMallocOverhead);
3209 startOfNextMemoryChunk_ = (char*)start + used_bytes + dlMallocOverhead;
3210 }
Elliott Hughesa2155262011-11-16 16:26:58 -08003211
Ian Rogers15bf2d32012-08-28 17:33:04 -07003212 void AppendChunk(uint8_t state, void* ptr, size_t length)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003213 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07003214 // Make sure there's enough room left in the buffer.
3215 // We need to use two bytes for every fractional 256 allocation units used by the chunk plus
3216 // 17 bytes for any header.
3217 size_t needed = (((length/ALLOCATION_UNIT_SIZE + 255) / 256) * 2) + 17;
3218 size_t bytesLeft = buf_.size() - (size_t)(p_ - &buf_[0]);
3219 if (bytesLeft < needed) {
3220 Flush();
3221 }
3222
3223 bytesLeft = buf_.size() - (size_t)(p_ - &buf_[0]);
3224 if (bytesLeft < needed) {
3225 LOG(WARNING) << "Chunk is too big to transmit (chunk_len=" << length << ", "
3226 << needed << " bytes)";
3227 return;
3228 }
3229 EnsureHeader(ptr);
Elliott Hughesa2155262011-11-16 16:26:58 -08003230 // Write out the chunk description.
Ian Rogers15bf2d32012-08-28 17:33:04 -07003231 length /= ALLOCATION_UNIT_SIZE; // Convert to allocation units.
3232 totalAllocationUnits_ += length;
3233 while (length > 256) {
Ian Rogers30fab402012-01-23 15:43:46 -08003234 *p_++ = state | HPSG_PARTIAL;
3235 *p_++ = 255; // length - 1
Ian Rogers15bf2d32012-08-28 17:33:04 -07003236 length -= 256;
Elliott Hughesa2155262011-11-16 16:26:58 -08003237 }
Ian Rogers30fab402012-01-23 15:43:46 -08003238 *p_++ = state;
Ian Rogers15bf2d32012-08-28 17:33:04 -07003239 *p_++ = length - 1;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003240 }
3241
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003242 uint8_t ExamineObject(const mirror::Object* o, bool is_native_heap)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003243 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
Elliott Hughesa2155262011-11-16 16:26:58 -08003244 if (o == NULL) {
3245 return HPSG_STATE(SOLIDITY_FREE, 0);
3246 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003247
Elliott Hughesa2155262011-11-16 16:26:58 -08003248 // It's an allocated chunk. Figure out what it is.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003249
Elliott Hughesa2155262011-11-16 16:26:58 -08003250 // If we're looking at the native heap, we'll just return
3251 // (SOLIDITY_HARD, KIND_NATIVE) for all allocated chunks.
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003252 if (is_native_heap) {
Elliott Hughesa2155262011-11-16 16:26:58 -08003253 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
3254 }
3255
Ian Rogers5bfa60f2012-09-02 21:17:56 -07003256 if (!Runtime::Current()->GetHeap()->IsLiveObjectLocked(o)) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07003257 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003258 }
3259
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003260 mirror::Class* c = o->GetClass();
Elliott Hughesa2155262011-11-16 16:26:58 -08003261 if (c == NULL) {
3262 // The object was probably just created but hasn't been initialized yet.
3263 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
3264 }
3265
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08003266 if (!Runtime::Current()->GetHeap()->IsHeapAddress(c)) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07003267 LOG(ERROR) << "Invalid class for managed heap object: " << o << " " << c;
Elliott Hughesa2155262011-11-16 16:26:58 -08003268 return HPSG_STATE(SOLIDITY_HARD, KIND_UNKNOWN);
3269 }
3270
3271 if (c->IsClassClass()) {
3272 return HPSG_STATE(SOLIDITY_HARD, KIND_CLASS_OBJECT);
3273 }
3274
3275 if (c->IsArrayClass()) {
3276 if (o->IsObjectArray()) {
3277 return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
3278 }
3279 switch (c->GetComponentSize()) {
3280 case 1: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_1);
3281 case 2: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_2);
3282 case 4: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
3283 case 8: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_8);
3284 }
3285 }
3286
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003287 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
3288 }
3289
Ian Rogers30fab402012-01-23 15:43:46 -08003290 std::vector<uint8_t> buf_;
3291 uint8_t* p_;
3292 uint8_t* pieceLenField_;
Ian Rogers15bf2d32012-08-28 17:33:04 -07003293 void* startOfNextMemoryChunk_;
Ian Rogers30fab402012-01-23 15:43:46 -08003294 size_t totalAllocationUnits_;
3295 uint32_t type_;
3296 bool merge_;
3297 bool needHeader_;
3298
Elliott Hughesa2155262011-11-16 16:26:58 -08003299 DISALLOW_COPY_AND_ASSIGN(HeapChunkContext);
3300};
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003301
3302void Dbg::DdmSendHeapSegments(bool native) {
3303 Dbg::HpsgWhen when;
3304 Dbg::HpsgWhat what;
3305 if (!native) {
3306 when = gDdmHpsgWhen;
3307 what = gDdmHpsgWhat;
3308 } else {
3309 when = gDdmNhsgWhen;
3310 what = gDdmNhsgWhat;
3311 }
3312 if (when == HPSG_WHEN_NEVER) {
3313 return;
3314 }
3315
3316 // Figure out what kind of chunks we'll be sending.
3317 CHECK(what == HPSG_WHAT_MERGED_OBJECTS || what == HPSG_WHAT_DISTINCT_OBJECTS) << static_cast<int>(what);
3318
3319 // First, send a heap start chunk.
3320 uint8_t heap_id[4];
3321 JDWP::Set4BE(&heap_id[0], 1); // Heap id (bogus; we only have one heap).
3322 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHST") : CHUNK_TYPE("HPST"), sizeof(heap_id), heap_id);
3323
3324 // Send a series of heap segment chunks.
Elliott Hughesa2155262011-11-16 16:26:58 -08003325 HeapChunkContext context((what == HPSG_WHAT_MERGED_OBJECTS), native);
3326 if (native) {
Ian Rogers30fab402012-01-23 15:43:46 -08003327 // TODO: enable when bionic has moved to dlmalloc 2.8.5
3328 // dlmalloc_inspect_all(HeapChunkContext::HeapChunkCallback, &context);
3329 UNIMPLEMENTED(WARNING) << "Native heap send heap segments";
Elliott Hughesa2155262011-11-16 16:26:58 -08003330 } else {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08003331 Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07003332 const Spaces& spaces = heap->GetSpaces();
Ian Rogers50b35e22012-10-04 10:09:15 -07003333 Thread* self = Thread::Current();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07003334 for (Spaces::const_iterator cur = spaces.begin(); cur != spaces.end(); ++cur) {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07003335 if ((*cur)->IsAllocSpace()) {
Ian Rogers50b35e22012-10-04 10:09:15 -07003336 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07003337 (*cur)->AsAllocSpace()->Walk(HeapChunkContext::HeapChunkCallback, &context);
3338 }
3339 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07003340 // Walk the large objects, these are not in the AllocSpace.
3341 heap->GetLargeObjectsSpace()->Walk(HeapChunkContext::HeapChunkCallback, &context);
Elliott Hughesa2155262011-11-16 16:26:58 -08003342 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003343
3344 // Finally, send a heap end chunk.
3345 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHEN") : CHUNK_TYPE("HPEN"), sizeof(heap_id), heap_id);
Elliott Hughes767a1472011-10-26 18:49:02 -07003346}
3347
Elliott Hughes545a0642011-11-08 19:10:03 -08003348void Dbg::SetAllocTrackingEnabled(bool enabled) {
Ian Rogers50b35e22012-10-04 10:09:15 -07003349 MutexLock mu(Thread::Current(), gAllocTrackerLock);
Elliott Hughes545a0642011-11-08 19:10:03 -08003350 if (enabled) {
3351 if (recent_allocation_records_ == NULL) {
3352 LOG(INFO) << "Enabling alloc tracker (" << kNumAllocRecords << " entries, "
3353 << kMaxAllocRecordStackDepth << " frames --> "
3354 << (sizeof(AllocRecord) * kNumAllocRecords) << " bytes)";
3355 gAllocRecordHead = gAllocRecordCount = 0;
3356 recent_allocation_records_ = new AllocRecord[kNumAllocRecords];
3357 CHECK(recent_allocation_records_ != NULL);
3358 }
3359 } else {
3360 delete[] recent_allocation_records_;
3361 recent_allocation_records_ = NULL;
3362 }
3363}
3364
Ian Rogers0399dde2012-06-06 17:09:28 -07003365struct AllocRecordStackVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -08003366 AllocRecordStackVisitor(Thread* thread, AllocRecord* record)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003367 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08003368 : StackVisitor(thread, NULL), record(record), depth(0) {}
Elliott Hughes545a0642011-11-08 19:10:03 -08003369
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003370 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
3371 // annotalysis.
3372 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughes545a0642011-11-08 19:10:03 -08003373 if (depth >= kMaxAllocRecordStackDepth) {
Elliott Hughes530fa002012-03-12 11:44:49 -07003374 return false;
Elliott Hughes545a0642011-11-08 19:10:03 -08003375 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003376 mirror::AbstractMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07003377 if (!m->IsRuntimeMethod()) {
3378 record->stack[depth].method = m;
3379 record->stack[depth].dex_pc = GetDexPc();
Elliott Hughes530fa002012-03-12 11:44:49 -07003380 ++depth;
Elliott Hughes545a0642011-11-08 19:10:03 -08003381 }
Elliott Hughes530fa002012-03-12 11:44:49 -07003382 return true;
Elliott Hughes545a0642011-11-08 19:10:03 -08003383 }
3384
3385 ~AllocRecordStackVisitor() {
3386 // Clear out any unused stack trace elements.
3387 for (; depth < kMaxAllocRecordStackDepth; ++depth) {
3388 record->stack[depth].method = NULL;
Ian Rogers0399dde2012-06-06 17:09:28 -07003389 record->stack[depth].dex_pc = 0;
Elliott Hughes545a0642011-11-08 19:10:03 -08003390 }
3391 }
3392
3393 AllocRecord* record;
3394 size_t depth;
3395};
3396
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003397void Dbg::RecordAllocation(mirror::Class* type, size_t byte_count) {
Elliott Hughes545a0642011-11-08 19:10:03 -08003398 Thread* self = Thread::Current();
3399 CHECK(self != NULL);
3400
Ian Rogers50b35e22012-10-04 10:09:15 -07003401 MutexLock mu(self, gAllocTrackerLock);
Elliott Hughes545a0642011-11-08 19:10:03 -08003402 if (recent_allocation_records_ == NULL) {
3403 return;
3404 }
3405
3406 // Advance and clip.
3407 if (++gAllocRecordHead == kNumAllocRecords) {
3408 gAllocRecordHead = 0;
3409 }
3410
3411 // Fill in the basics.
3412 AllocRecord* record = &recent_allocation_records_[gAllocRecordHead];
3413 record->type = type;
3414 record->byte_count = byte_count;
3415 record->thin_lock_id = self->GetThinLockId();
3416
3417 // Fill in the stack trace.
Ian Rogers7a22fa62013-01-23 12:16:16 -08003418 AllocRecordStackVisitor visitor(self, record);
Ian Rogers0399dde2012-06-06 17:09:28 -07003419 visitor.WalkStack();
Elliott Hughes545a0642011-11-08 19:10:03 -08003420
3421 if (gAllocRecordCount < kNumAllocRecords) {
3422 ++gAllocRecordCount;
3423 }
3424}
3425
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003426// Returns the index of the head element.
3427//
3428// We point at the most-recently-written record, so if gAllocRecordCount is 1
3429// we want to use the current element. Take "head+1" and subtract count
3430// from it.
3431//
3432// We need to handle underflow in our circular buffer, so we add
3433// kNumAllocRecords and then mask it back down.
Elliott Hughesf8349362012-06-18 15:00:06 -07003434static inline int HeadIndex() EXCLUSIVE_LOCKS_REQUIRED(gAllocTrackerLock) {
Elliott Hughes545a0642011-11-08 19:10:03 -08003435 return (gAllocRecordHead+1 + kNumAllocRecords - gAllocRecordCount) & (kNumAllocRecords-1);
3436}
3437
3438void Dbg::DumpRecentAllocations() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003439 ScopedObjectAccess soa(Thread::Current());
Ian Rogers50b35e22012-10-04 10:09:15 -07003440 MutexLock mu(soa.Self(), gAllocTrackerLock);
Elliott Hughes545a0642011-11-08 19:10:03 -08003441 if (recent_allocation_records_ == NULL) {
3442 LOG(INFO) << "Not recording tracked allocations";
3443 return;
3444 }
3445
3446 // "i" is the head of the list. We want to start at the end of the
3447 // list and move forward to the tail.
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003448 size_t i = HeadIndex();
Elliott Hughes545a0642011-11-08 19:10:03 -08003449 size_t count = gAllocRecordCount;
3450
3451 LOG(INFO) << "Tracked allocations, (head=" << gAllocRecordHead << " count=" << count << ")";
3452 while (count--) {
3453 AllocRecord* record = &recent_allocation_records_[i];
3454
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003455 LOG(INFO) << StringPrintf(" Thread %-2d %6zd bytes ", record->thin_lock_id, record->byte_count)
Elliott Hughes545a0642011-11-08 19:10:03 -08003456 << PrettyClass(record->type);
3457
3458 for (size_t stack_frame = 0; stack_frame < kMaxAllocRecordStackDepth; ++stack_frame) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003459 const mirror::AbstractMethod* m = record->stack[stack_frame].method;
Elliott Hughes545a0642011-11-08 19:10:03 -08003460 if (m == NULL) {
3461 break;
3462 }
3463 LOG(INFO) << " " << PrettyMethod(m) << " line " << record->stack[stack_frame].LineNumber();
3464 }
3465
3466 // pause periodically to help logcat catch up
3467 if ((count % 5) == 0) {
3468 usleep(40000);
3469 }
3470
3471 i = (i + 1) & (kNumAllocRecords-1);
3472 }
3473}
3474
3475class StringTable {
3476 public:
3477 StringTable() {
3478 }
3479
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003480 void Add(const char* s) {
Elliott Hughes545a0642011-11-08 19:10:03 -08003481 table_.insert(s);
3482 }
3483
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003484 size_t IndexOf(const char* s) const {
3485 typedef std::set<std::string>::const_iterator It; // TODO: C++0x auto
3486 It it = table_.find(s);
3487 if (it == table_.end()) {
3488 LOG(FATAL) << "IndexOf(\"" << s << "\") failed";
3489 }
3490 return std::distance(table_.begin(), it);
Elliott Hughes545a0642011-11-08 19:10:03 -08003491 }
3492
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003493 size_t Size() const {
Elliott Hughes545a0642011-11-08 19:10:03 -08003494 return table_.size();
3495 }
3496
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003497 void WriteTo(std::vector<uint8_t>& bytes) const {
3498 typedef std::set<std::string>::const_iterator It; // TODO: C++0x auto
Elliott Hughes545a0642011-11-08 19:10:03 -08003499 for (It it = table_.begin(); it != table_.end(); ++it) {
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003500 const char* s = (*it).c_str();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003501 size_t s_len = CountModifiedUtf8Chars(s);
3502 UniquePtr<uint16_t> s_utf16(new uint16_t[s_len]);
3503 ConvertModifiedUtf8ToUtf16(s_utf16.get(), s);
3504 JDWP::AppendUtf16BE(bytes, s_utf16.get(), s_len);
Elliott Hughes545a0642011-11-08 19:10:03 -08003505 }
3506 }
3507
3508 private:
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003509 std::set<std::string> table_;
Elliott Hughes545a0642011-11-08 19:10:03 -08003510 DISALLOW_COPY_AND_ASSIGN(StringTable);
3511};
3512
3513/*
3514 * The data we send to DDMS contains everything we have recorded.
3515 *
3516 * Message header (all values big-endian):
3517 * (1b) message header len (to allow future expansion); includes itself
3518 * (1b) entry header len
3519 * (1b) stack frame len
3520 * (2b) number of entries
3521 * (4b) offset to string table from start of message
3522 * (2b) number of class name strings
3523 * (2b) number of method name strings
3524 * (2b) number of source file name strings
3525 * For each entry:
3526 * (4b) total allocation size
Elliott Hughes221229c2013-01-08 18:17:50 -08003527 * (2b) thread id
Elliott Hughes545a0642011-11-08 19:10:03 -08003528 * (2b) allocated object's class name index
3529 * (1b) stack depth
3530 * For each stack frame:
3531 * (2b) method's class name
3532 * (2b) method name
3533 * (2b) method source file
3534 * (2b) line number, clipped to 32767; -2 if native; -1 if no source
3535 * (xb) class name strings
3536 * (xb) method name strings
3537 * (xb) source file strings
3538 *
3539 * As with other DDM traffic, strings are sent as a 4-byte length
3540 * followed by UTF-16 data.
3541 *
3542 * We send up 16-bit unsigned indexes into string tables. In theory there
3543 * can be (kMaxAllocRecordStackDepth * kNumAllocRecords) unique strings in
3544 * each table, but in practice there should be far fewer.
3545 *
3546 * The chief reason for using a string table here is to keep the size of
3547 * the DDMS message to a minimum. This is partly to make the protocol
3548 * efficient, but also because we have to form the whole thing up all at
3549 * once in a memory buffer.
3550 *
3551 * We use separate string tables for class names, method names, and source
3552 * files to keep the indexes small. There will generally be no overlap
3553 * between the contents of these tables.
3554 */
3555jbyteArray Dbg::GetRecentAllocations() {
3556 if (false) {
3557 DumpRecentAllocations();
3558 }
3559
Ian Rogers50b35e22012-10-04 10:09:15 -07003560 Thread* self = Thread::Current();
3561 MutexLock mu(self, gAllocTrackerLock);
Elliott Hughes545a0642011-11-08 19:10:03 -08003562
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003563 //
3564 // Part 1: generate string tables.
3565 //
Elliott Hughes545a0642011-11-08 19:10:03 -08003566 StringTable class_names;
3567 StringTable method_names;
3568 StringTable filenames;
3569
3570 int count = gAllocRecordCount;
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003571 int idx = HeadIndex();
Elliott Hughes545a0642011-11-08 19:10:03 -08003572 while (count--) {
3573 AllocRecord* record = &recent_allocation_records_[idx];
3574
Elliott Hughes91250e02011-12-13 22:30:35 -08003575 class_names.Add(ClassHelper(record->type).GetDescriptor());
Elliott Hughes545a0642011-11-08 19:10:03 -08003576
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003577 MethodHelper mh;
Elliott Hughes545a0642011-11-08 19:10:03 -08003578 for (size_t i = 0; i < kMaxAllocRecordStackDepth; i++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003579 mirror::AbstractMethod* m = record->stack[i].method;
Elliott Hughes545a0642011-11-08 19:10:03 -08003580 if (m != NULL) {
Ian Rogersba377812012-05-28 21:16:29 -07003581 mh.ChangeMethod(m);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003582 class_names.Add(mh.GetDeclaringClassDescriptor());
3583 method_names.Add(mh.GetName());
3584 filenames.Add(mh.GetDeclaringClassSourceFile());
Elliott Hughes545a0642011-11-08 19:10:03 -08003585 }
3586 }
3587
3588 idx = (idx + 1) & (kNumAllocRecords-1);
3589 }
3590
3591 LOG(INFO) << "allocation records: " << gAllocRecordCount;
3592
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003593 //
3594 // Part 2: allocate a buffer and generate the output.
3595 //
Elliott Hughes545a0642011-11-08 19:10:03 -08003596 std::vector<uint8_t> bytes;
3597
3598 // (1b) message header len (to allow future expansion); includes itself
3599 // (1b) entry header len
3600 // (1b) stack frame len
3601 const int kMessageHeaderLen = 15;
3602 const int kEntryHeaderLen = 9;
3603 const int kStackFrameLen = 8;
3604 JDWP::Append1BE(bytes, kMessageHeaderLen);
3605 JDWP::Append1BE(bytes, kEntryHeaderLen);
3606 JDWP::Append1BE(bytes, kStackFrameLen);
3607
3608 // (2b) number of entries
3609 // (4b) offset to string table from start of message
3610 // (2b) number of class name strings
3611 // (2b) number of method name strings
3612 // (2b) number of source file name strings
3613 JDWP::Append2BE(bytes, gAllocRecordCount);
3614 size_t string_table_offset = bytes.size();
3615 JDWP::Append4BE(bytes, 0); // We'll patch this later...
3616 JDWP::Append2BE(bytes, class_names.Size());
3617 JDWP::Append2BE(bytes, method_names.Size());
3618 JDWP::Append2BE(bytes, filenames.Size());
3619
3620 count = gAllocRecordCount;
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003621 idx = HeadIndex();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003622 ClassHelper kh;
Elliott Hughes545a0642011-11-08 19:10:03 -08003623 while (count--) {
3624 // For each entry:
3625 // (4b) total allocation size
3626 // (2b) thread id
3627 // (2b) allocated object's class name index
3628 // (1b) stack depth
3629 AllocRecord* record = &recent_allocation_records_[idx];
3630 size_t stack_depth = record->GetDepth();
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003631 kh.ChangeClass(record->type);
3632 size_t allocated_object_class_name_index = class_names.IndexOf(kh.GetDescriptor());
Elliott Hughes545a0642011-11-08 19:10:03 -08003633 JDWP::Append4BE(bytes, record->byte_count);
3634 JDWP::Append2BE(bytes, record->thin_lock_id);
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003635 JDWP::Append2BE(bytes, allocated_object_class_name_index);
Elliott Hughes545a0642011-11-08 19:10:03 -08003636 JDWP::Append1BE(bytes, stack_depth);
3637
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003638 MethodHelper mh;
Elliott Hughes545a0642011-11-08 19:10:03 -08003639 for (size_t stack_frame = 0; stack_frame < stack_depth; ++stack_frame) {
3640 // For each stack frame:
3641 // (2b) method's class name
3642 // (2b) method name
3643 // (2b) method source file
3644 // (2b) line number, clipped to 32767; -2 if native; -1 if no source
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003645 mh.ChangeMethod(record->stack[stack_frame].method);
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003646 size_t class_name_index = class_names.IndexOf(mh.GetDeclaringClassDescriptor());
3647 size_t method_name_index = method_names.IndexOf(mh.GetName());
3648 size_t file_name_index = filenames.IndexOf(mh.GetDeclaringClassSourceFile());
3649 JDWP::Append2BE(bytes, class_name_index);
3650 JDWP::Append2BE(bytes, method_name_index);
3651 JDWP::Append2BE(bytes, file_name_index);
Elliott Hughes545a0642011-11-08 19:10:03 -08003652 JDWP::Append2BE(bytes, record->stack[stack_frame].LineNumber());
3653 }
3654
3655 idx = (idx + 1) & (kNumAllocRecords-1);
3656 }
3657
3658 // (xb) class name strings
3659 // (xb) method name strings
3660 // (xb) source file strings
3661 JDWP::Set4BE(&bytes[string_table_offset], bytes.size());
3662 class_names.WriteTo(bytes);
3663 method_names.WriteTo(bytes);
3664 filenames.WriteTo(bytes);
3665
Ian Rogers50b35e22012-10-04 10:09:15 -07003666 JNIEnv* env = self->GetJniEnv();
Elliott Hughes545a0642011-11-08 19:10:03 -08003667 jbyteArray result = env->NewByteArray(bytes.size());
3668 if (result != NULL) {
3669 env->SetByteArrayRegion(result, 0, bytes.size(), reinterpret_cast<const jbyte*>(&bytes[0]));
3670 }
3671 return result;
3672}
3673
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003674} // namespace art