blob: 697c7cd31dd660fe5f9c81e8786ea6059ca4a6e8 [file] [log] [blame]
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "debugger.h"
18
Elliott Hughes3bb81562011-10-21 18:52:59 -070019#include <sys/uio.h>
20
Elliott Hughes545a0642011-11-08 19:10:03 -080021#include <set>
22
23#include "class_linker.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080024#include "class_linker-inl.h"
Ian Rogers776ac1f2012-04-13 23:36:36 -070025#include "dex_instruction.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080026#include "gc/card_table-inl.h"
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -070027#include "gc/large_object_space.h"
28#include "gc/space.h"
Elliott Hughes64f574f2013-02-20 14:57:12 -080029#include "jdwp/object_registry.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080030#include "mirror/abstract_method-inl.h"
31#include "mirror/class.h"
32#include "mirror/class-inl.h"
33#include "mirror/class_loader.h"
34#include "mirror/field-inl.h"
35#include "mirror/object-inl.h"
36#include "mirror/object_array-inl.h"
37#include "mirror/throwable.h"
Ian Rogers2bcb4a42012-11-08 10:39:18 -080038#include "oat/runtime/context.h"
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080039#include "object_utils.h"
Elliott Hughesa0e18062012-04-13 15:59:59 -070040#include "safe_map.h"
Elliott Hughes64f574f2013-02-20 14:57:12 -080041#include "scoped_thread_state_change.h"
Elliott Hughes6a5bd492011-10-28 14:33:57 -070042#include "ScopedLocalRef.h"
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -070043#include "ScopedPrimitiveArray.h"
Ian Rogers1f539342012-10-03 21:09:42 -070044#include "sirt_ref.h"
Elliott Hughes47fce012011-10-25 18:37:19 -070045#include "stack_indirect_reference_table.h"
Elliott Hughes475fc232011-10-25 15:00:35 -070046#include "thread_list.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080047#include "utf.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070048#include "well_known_classes.h"
Elliott Hughes475fc232011-10-25 15:00:35 -070049
Elliott Hughes872d4ec2011-10-21 17:07:15 -070050namespace art {
51
Elliott Hughes545a0642011-11-08 19:10:03 -080052static const size_t kMaxAllocRecordStackDepth = 16; // Max 255.
Elliott Hughes64f574f2013-02-20 14:57:12 -080053static const size_t kNumAllocRecords = 512; // Must be a power of 2.
Elliott Hughes475fc232011-10-25 15:00:35 -070054
Elliott Hughes545a0642011-11-08 19:10:03 -080055struct AllocRecordStackTraceElement {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080056 mirror::AbstractMethod* method;
Ian Rogers0399dde2012-06-06 17:09:28 -070057 uint32_t dex_pc;
Elliott Hughes545a0642011-11-08 19:10:03 -080058
Ian Rogersb726dcb2012-09-05 08:57:23 -070059 int32_t LineNumber() const SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers0399dde2012-06-06 17:09:28 -070060 return MethodHelper(method).GetLineNumFromDexPC(dex_pc);
Elliott Hughes545a0642011-11-08 19:10:03 -080061 }
62};
63
64struct AllocRecord {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080065 mirror::Class* type;
Elliott Hughes545a0642011-11-08 19:10:03 -080066 size_t byte_count;
67 uint16_t thin_lock_id;
68 AllocRecordStackTraceElement stack[kMaxAllocRecordStackDepth]; // Unused entries have NULL method.
69
70 size_t GetDepth() {
71 size_t depth = 0;
72 while (depth < kMaxAllocRecordStackDepth && stack[depth].method != NULL) {
73 ++depth;
74 }
75 return depth;
76 }
77};
78
Elliott Hughes86964332012-02-15 19:37:42 -080079struct Breakpoint {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080080 mirror::AbstractMethod* method;
Elliott Hughesa656a0f2012-02-21 18:03:44 -080081 uint32_t dex_pc;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080082 Breakpoint(mirror::AbstractMethod* method, uint32_t dex_pc) : method(method), dex_pc(dex_pc) {}
Elliott Hughes86964332012-02-15 19:37:42 -080083};
84
Ian Rogers00f7d0e2012-07-19 15:28:27 -070085static std::ostream& operator<<(std::ostream& os, const Breakpoint& rhs)
Ian Rogersb726dcb2012-09-05 08:57:23 -070086 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes229feb72012-02-23 13:33:29 -080087 os << StringPrintf("Breakpoint[%s @%#x]", PrettyMethod(rhs.method).c_str(), rhs.dex_pc);
Elliott Hughes86964332012-02-15 19:37:42 -080088 return os;
89}
90
91struct SingleStepControl {
92 // Are we single-stepping right now?
93 bool is_active;
94 Thread* thread;
95
96 JDWP::JdwpStepSize step_size;
97 JDWP::JdwpStepDepth step_depth;
98
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080099 const mirror::AbstractMethod* method;
Elliott Hughes2435a572012-02-17 16:07:41 -0800100 int32_t line_number; // Or -1 for native methods.
101 std::set<uint32_t> dex_pcs;
Elliott Hughes86964332012-02-15 19:37:42 -0800102 int stack_depth;
103};
104
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700105// JDWP is allowed unless the Zygote forbids it.
106static bool gJdwpAllowed = true;
107
Elliott Hughesc0f09332012-03-26 13:27:06 -0700108// Was there a -Xrunjdwp or -agentlib:jdwp= argument on the command line?
Elliott Hughes3bb81562011-10-21 18:52:59 -0700109static bool gJdwpConfigured = false;
110
Elliott Hughesc0f09332012-03-26 13:27:06 -0700111// Broken-down JDWP options. (Only valid if IsJdwpConfigured() is true.)
Elliott Hughes376a7a02011-10-24 18:35:55 -0700112static JDWP::JdwpOptions gJdwpOptions;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700113
114// Runtime JDWP state.
115static JDWP::JdwpState* gJdwpState = NULL;
116static bool gDebuggerConnected; // debugger or DDMS is connected.
117static bool gDebuggerActive; // debugger is making requests.
Elliott Hughes86964332012-02-15 19:37:42 -0800118static bool gDisposed; // debugger called VirtualMachine.Dispose, so we should drop the connection.
Elliott Hughes3bb81562011-10-21 18:52:59 -0700119
Elliott Hughes47fce012011-10-25 18:37:19 -0700120static bool gDdmThreadNotification = false;
121
Elliott Hughes767a1472011-10-26 18:49:02 -0700122// DDMS GC-related settings.
123static Dbg::HpifWhen gDdmHpifWhen = Dbg::HPIF_WHEN_NEVER;
124static Dbg::HpsgWhen gDdmHpsgWhen = Dbg::HPSG_WHEN_NEVER;
125static Dbg::HpsgWhat gDdmHpsgWhat;
126static Dbg::HpsgWhen gDdmNhsgWhen = Dbg::HPSG_WHEN_NEVER;
127static Dbg::HpsgWhat gDdmNhsgWhat;
128
Elliott Hughes475fc232011-10-25 15:00:35 -0700129static ObjectRegistry* gRegistry = NULL;
130
Elliott Hughes545a0642011-11-08 19:10:03 -0800131// Recent allocation tracking.
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700132static Mutex gAllocTrackerLock DEFAULT_MUTEX_ACQUIRED_AFTER ("AllocTracker lock");
Elliott Hughesf8349362012-06-18 15:00:06 -0700133AllocRecord* Dbg::recent_allocation_records_ PT_GUARDED_BY(gAllocTrackerLock) = NULL; // TODO: CircularBuffer<AllocRecord>
134static size_t gAllocRecordHead GUARDED_BY(gAllocTrackerLock) = 0;
135static size_t gAllocRecordCount GUARDED_BY(gAllocTrackerLock) = 0;
Elliott Hughes545a0642011-11-08 19:10:03 -0800136
Elliott Hughes86964332012-02-15 19:37:42 -0800137// Breakpoints and single-stepping.
jeffhao09bfc6a2012-12-11 18:11:43 -0800138static std::vector<Breakpoint> gBreakpoints GUARDED_BY(Locks::breakpoint_lock_);
139static SingleStepControl gSingleStepControl GUARDED_BY(Locks::breakpoint_lock_);
Elliott Hughes86964332012-02-15 19:37:42 -0800140
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800141static bool IsBreakpoint(mirror::AbstractMethod* m, uint32_t dex_pc)
jeffhao09bfc6a2012-12-11 18:11:43 -0800142 LOCKS_EXCLUDED(Locks::breakpoint_lock_)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700143 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
jeffhao09bfc6a2012-12-11 18:11:43 -0800144 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Elliott Hughes86964332012-02-15 19:37:42 -0800145 for (size_t i = 0; i < gBreakpoints.size(); ++i) {
Elliott Hughesa656a0f2012-02-21 18:03:44 -0800146 if (gBreakpoints[i].method == m && gBreakpoints[i].dex_pc == dex_pc) {
Elliott Hughes86964332012-02-15 19:37:42 -0800147 VLOG(jdwp) << "Hit breakpoint #" << i << ": " << gBreakpoints[i];
148 return true;
149 }
150 }
151 return false;
152}
153
Elliott Hughes9e0c1752013-01-09 14:02:58 -0800154static bool IsSuspendedForDebugger(ScopedObjectAccessUnchecked& soa, Thread* thread) {
155 MutexLock mu(soa.Self(), *Locks::thread_suspend_count_lock_);
156 // A thread may be suspended for GC; in this code, we really want to know whether
157 // there's a debugger suspension active.
158 return thread->IsSuspended() && thread->GetDebugSuspendCount() > 0;
159}
160
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800161static mirror::Array* DecodeArray(JDWP::RefTypeId id, JDWP::JdwpError& status)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700162 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800163 mirror::Object* o = gRegistry->Get<mirror::Object*>(id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800164 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800165 status = JDWP::ERR_INVALID_OBJECT;
166 return NULL;
167 }
168 if (!o->IsArrayInstance()) {
169 status = JDWP::ERR_INVALID_ARRAY;
170 return NULL;
171 }
172 status = JDWP::ERR_NONE;
173 return o->AsArray();
174}
175
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800176static mirror::Class* DecodeClass(JDWP::RefTypeId id, JDWP::JdwpError& status)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700177 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800178 mirror::Object* o = gRegistry->Get<mirror::Object*>(id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800179 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800180 status = JDWP::ERR_INVALID_OBJECT;
181 return NULL;
182 }
183 if (!o->IsClass()) {
184 status = JDWP::ERR_INVALID_CLASS;
185 return NULL;
186 }
187 status = JDWP::ERR_NONE;
188 return o->AsClass();
189}
190
Elliott Hughes221229c2013-01-08 18:17:50 -0800191static JDWP::JdwpError DecodeThread(ScopedObjectAccessUnchecked& soa, JDWP::ObjectId thread_id, Thread*& thread)
jeffhaoa77f0f62012-12-05 17:19:31 -0800192 EXCLUSIVE_LOCKS_REQUIRED(Locks::thread_list_lock_)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700193 LOCKS_EXCLUDED(Locks::thread_suspend_count_lock_)
194 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800195 mirror::Object* thread_peer = gRegistry->Get<mirror::Object*>(thread_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800196 if (thread_peer == NULL || thread_peer == ObjectRegistry::kInvalidObject) {
Elliott Hughes221229c2013-01-08 18:17:50 -0800197 // This isn't even an object.
198 return JDWP::ERR_INVALID_OBJECT;
Elliott Hughes436e3722012-02-17 20:01:47 -0800199 }
Elliott Hughes221229c2013-01-08 18:17:50 -0800200
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800201 mirror::Class* java_lang_Thread = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_Thread);
Elliott Hughes221229c2013-01-08 18:17:50 -0800202 if (!java_lang_Thread->IsAssignableFrom(thread_peer->GetClass())) {
203 // This isn't a thread.
204 return JDWP::ERR_INVALID_THREAD;
205 }
206
207 thread = Thread::FromManagedThread(soa, thread_peer);
208 if (thread == NULL) {
209 // This is a java.lang.Thread without a Thread*. Must be a zombie.
210 return JDWP::ERR_THREAD_NOT_ALIVE;
211 }
212 return JDWP::ERR_NONE;
Elliott Hughes436e3722012-02-17 20:01:47 -0800213}
214
Elliott Hughes24437992011-11-30 14:49:33 -0800215static JDWP::JdwpTag BasicTagFromDescriptor(const char* descriptor) {
216 // JDWP deliberately uses the descriptor characters' ASCII values for its enum.
217 // Note that by "basic" we mean that we don't get more specific than JT_OBJECT.
218 return static_cast<JDWP::JdwpTag>(descriptor[0]);
219}
220
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800221static JDWP::JdwpTag TagFromClass(mirror::Class* c)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700222 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes86b00102011-12-05 17:54:26 -0800223 CHECK(c != NULL);
Elliott Hughes24437992011-11-30 14:49:33 -0800224 if (c->IsArrayClass()) {
225 return JDWP::JT_ARRAY;
226 }
227
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800228 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Elliott Hughes24437992011-11-30 14:49:33 -0800229 if (c->IsStringClass()) {
230 return JDWP::JT_STRING;
231 } else if (c->IsClassClass()) {
232 return JDWP::JT_CLASS_OBJECT;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800233 } else if (class_linker->FindSystemClass("Ljava/lang/Thread;")->IsAssignableFrom(c)) {
Elliott Hughes24437992011-11-30 14:49:33 -0800234 return JDWP::JT_THREAD;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800235 } else if (class_linker->FindSystemClass("Ljava/lang/ThreadGroup;")->IsAssignableFrom(c)) {
Elliott Hughes24437992011-11-30 14:49:33 -0800236 return JDWP::JT_THREAD_GROUP;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800237 } else if (class_linker->FindSystemClass("Ljava/lang/ClassLoader;")->IsAssignableFrom(c)) {
Elliott Hughes24437992011-11-30 14:49:33 -0800238 return JDWP::JT_CLASS_LOADER;
Elliott Hughes24437992011-11-30 14:49:33 -0800239 } else {
240 return JDWP::JT_OBJECT;
241 }
242}
243
244/*
245 * Objects declared to hold Object might actually hold a more specific
246 * type. The debugger may take a special interest in these (e.g. it
247 * wants to display the contents of Strings), so we want to return an
248 * appropriate tag.
249 *
250 * Null objects are tagged JT_OBJECT.
251 */
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800252static JDWP::JdwpTag TagFromObject(const mirror::Object* o)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700253 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes24437992011-11-30 14:49:33 -0800254 return (o == NULL) ? JDWP::JT_OBJECT : TagFromClass(o->GetClass());
255}
256
257static bool IsPrimitiveTag(JDWP::JdwpTag tag) {
258 switch (tag) {
259 case JDWP::JT_BOOLEAN:
260 case JDWP::JT_BYTE:
261 case JDWP::JT_CHAR:
262 case JDWP::JT_FLOAT:
263 case JDWP::JT_DOUBLE:
264 case JDWP::JT_INT:
265 case JDWP::JT_LONG:
266 case JDWP::JT_SHORT:
267 case JDWP::JT_VOID:
268 return true;
269 default:
270 return false;
271 }
272}
273
Elliott Hughes3bb81562011-10-21 18:52:59 -0700274/*
275 * Handle one of the JDWP name/value pairs.
276 *
277 * JDWP options are:
278 * help: if specified, show help message and bail
279 * transport: may be dt_socket or dt_shmem
280 * address: for dt_socket, "host:port", or just "port" when listening
281 * server: if "y", wait for debugger to attach; if "n", attach to debugger
282 * timeout: how long to wait for debugger to connect / listen
283 *
284 * Useful with server=n (these aren't supported yet):
285 * onthrow=<exception-name>: connect to debugger when exception thrown
286 * onuncaught=y|n: connect to debugger when uncaught exception thrown
287 * launch=<command-line>: launch the debugger itself
288 *
289 * The "transport" option is required, as is "address" if server=n.
290 */
291static bool ParseJdwpOption(const std::string& name, const std::string& value) {
292 if (name == "transport") {
293 if (value == "dt_socket") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700294 gJdwpOptions.transport = JDWP::kJdwpTransportSocket;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700295 } else if (value == "dt_android_adb") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700296 gJdwpOptions.transport = JDWP::kJdwpTransportAndroidAdb;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700297 } else {
298 LOG(ERROR) << "JDWP transport not supported: " << value;
299 return false;
300 }
301 } else if (name == "server") {
302 if (value == "n") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700303 gJdwpOptions.server = false;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700304 } else if (value == "y") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700305 gJdwpOptions.server = true;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700306 } else {
307 LOG(ERROR) << "JDWP option 'server' must be 'y' or 'n'";
308 return false;
309 }
310 } else if (name == "suspend") {
311 if (value == "n") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700312 gJdwpOptions.suspend = false;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700313 } else if (value == "y") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700314 gJdwpOptions.suspend = true;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700315 } else {
316 LOG(ERROR) << "JDWP option 'suspend' must be 'y' or 'n'";
317 return false;
318 }
319 } else if (name == "address") {
320 /* this is either <port> or <host>:<port> */
321 std::string port_string;
Elliott Hughes376a7a02011-10-24 18:35:55 -0700322 gJdwpOptions.host.clear();
Elliott Hughes3bb81562011-10-21 18:52:59 -0700323 std::string::size_type colon = value.find(':');
324 if (colon != std::string::npos) {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700325 gJdwpOptions.host = value.substr(0, colon);
Elliott Hughes3bb81562011-10-21 18:52:59 -0700326 port_string = value.substr(colon + 1);
327 } else {
328 port_string = value;
329 }
330 if (port_string.empty()) {
331 LOG(ERROR) << "JDWP address missing port: " << value;
332 return false;
333 }
334 char* end;
Elliott Hughesba8eee12012-01-24 20:25:24 -0800335 uint64_t port = strtoul(port_string.c_str(), &end, 10);
336 if (*end != '\0' || port > 0xffff) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700337 LOG(ERROR) << "JDWP address has junk in port field: " << value;
338 return false;
339 }
Elliott Hughes376a7a02011-10-24 18:35:55 -0700340 gJdwpOptions.port = port;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700341 } else if (name == "launch" || name == "onthrow" || name == "oncaught" || name == "timeout") {
342 /* valid but unsupported */
343 LOG(INFO) << "Ignoring JDWP option '" << name << "'='" << value << "'";
344 } else {
345 LOG(INFO) << "Ignoring unrecognized JDWP option '" << name << "'='" << value << "'";
346 }
347
348 return true;
349}
350
351/*
352 * Parse the latter half of a -Xrunjdwp/-agentlib:jdwp= string, e.g.:
353 * "transport=dt_socket,address=8000,server=y,suspend=n"
354 */
355bool Dbg::ParseJdwpOptions(const std::string& options) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800356 VLOG(jdwp) << "ParseJdwpOptions: " << options;
Elliott Hughes47fce012011-10-25 18:37:19 -0700357
Elliott Hughes3bb81562011-10-21 18:52:59 -0700358 std::vector<std::string> pairs;
359 Split(options, ',', pairs);
360
361 for (size_t i = 0; i < pairs.size(); ++i) {
362 std::string::size_type equals = pairs[i].find('=');
363 if (equals == std::string::npos) {
364 LOG(ERROR) << "Can't parse JDWP option '" << pairs[i] << "' in '" << options << "'";
365 return false;
366 }
367 ParseJdwpOption(pairs[i].substr(0, equals), pairs[i].substr(equals + 1));
368 }
369
Elliott Hughes376a7a02011-10-24 18:35:55 -0700370 if (gJdwpOptions.transport == JDWP::kJdwpTransportUnknown) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700371 LOG(ERROR) << "Must specify JDWP transport: " << options;
372 }
Elliott Hughes376a7a02011-10-24 18:35:55 -0700373 if (!gJdwpOptions.server && (gJdwpOptions.host.empty() || gJdwpOptions.port == 0)) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700374 LOG(ERROR) << "Must specify JDWP host and port when server=n: " << options;
375 return false;
376 }
377
378 gJdwpConfigured = true;
379 return true;
380}
381
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700382void Dbg::StartJdwp() {
Elliott Hughesc0f09332012-03-26 13:27:06 -0700383 if (!gJdwpAllowed || !IsJdwpConfigured()) {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700384 // No JDWP for you!
385 return;
386 }
387
Elliott Hughes475fc232011-10-25 15:00:35 -0700388 CHECK(gRegistry == NULL);
389 gRegistry = new ObjectRegistry;
390
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700391 // Init JDWP if the debugger is enabled. This may connect out to a
392 // debugger, passively listen for a debugger, or block waiting for a
393 // debugger.
Elliott Hughes376a7a02011-10-24 18:35:55 -0700394 gJdwpState = JDWP::JdwpState::Create(&gJdwpOptions);
395 if (gJdwpState == NULL) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -0800396 // We probably failed because some other process has the port already, which means that
397 // if we don't abort the user is likely to think they're talking to us when they're actually
398 // talking to that other process.
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800399 LOG(FATAL) << "Debugger thread failed to initialize";
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700400 }
401
402 // If a debugger has already attached, send the "welcome" message.
403 // This may cause us to suspend all threads.
Elliott Hughes376a7a02011-10-24 18:35:55 -0700404 if (gJdwpState->IsActive()) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700405 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes376a7a02011-10-24 18:35:55 -0700406 if (!gJdwpState->PostVMStart()) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800407 LOG(WARNING) << "Failed to post 'start' message to debugger";
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700408 }
409 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700410}
411
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700412void Dbg::StopJdwp() {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700413 delete gJdwpState;
Elliott Hughes475fc232011-10-25 15:00:35 -0700414 delete gRegistry;
415 gRegistry = NULL;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700416}
417
Elliott Hughes767a1472011-10-26 18:49:02 -0700418void Dbg::GcDidFinish() {
419 if (gDdmHpifWhen != HPIF_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700420 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes81ff3182012-03-23 20:35:56 -0700421 LOG(DEBUG) << "Sending heap info to DDM";
Elliott Hughes7162ad92011-10-27 14:08:42 -0700422 DdmSendHeapInfo(gDdmHpifWhen);
Elliott Hughes767a1472011-10-26 18:49:02 -0700423 }
424 if (gDdmHpsgWhen != HPSG_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700425 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes81ff3182012-03-23 20:35:56 -0700426 LOG(DEBUG) << "Dumping heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700427 DdmSendHeapSegments(false);
Elliott Hughes767a1472011-10-26 18:49:02 -0700428 }
429 if (gDdmNhsgWhen != HPSG_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700430 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes767a1472011-10-26 18:49:02 -0700431 LOG(DEBUG) << "Dumping native heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700432 DdmSendHeapSegments(true);
Elliott Hughes767a1472011-10-26 18:49:02 -0700433 }
434}
435
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700436void Dbg::SetJdwpAllowed(bool allowed) {
437 gJdwpAllowed = allowed;
438}
439
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700440DebugInvokeReq* Dbg::GetInvokeReq() {
Elliott Hughes475fc232011-10-25 15:00:35 -0700441 return Thread::Current()->GetInvokeReq();
442}
443
444Thread* Dbg::GetDebugThread() {
445 return (gJdwpState != NULL) ? gJdwpState->GetDebugThread() : NULL;
446}
447
448void Dbg::ClearWaitForEventThread() {
449 gJdwpState->ClearWaitForEventThread();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700450}
451
452void Dbg::Connected() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700453 CHECK(!gDebuggerConnected);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800454 VLOG(jdwp) << "JDWP has attached";
Elliott Hughes3bb81562011-10-21 18:52:59 -0700455 gDebuggerConnected = true;
Elliott Hughes86964332012-02-15 19:37:42 -0800456 gDisposed = false;
457}
458
459void Dbg::Disposed() {
460 gDisposed = true;
461}
462
463bool Dbg::IsDisposed() {
464 return gDisposed;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700465}
466
Elliott Hughesc0f09332012-03-26 13:27:06 -0700467static void SetDebuggerUpdatesEnabledCallback(Thread* t, void* user_data) {
468 t->SetDebuggerUpdatesEnabled(*reinterpret_cast<bool*>(user_data));
469}
470
471static void SetDebuggerUpdatesEnabled(bool enabled) {
Ian Rogers50b35e22012-10-04 10:09:15 -0700472 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
Elliott Hughesf8349362012-06-18 15:00:06 -0700473 Runtime::Current()->GetThreadList()->ForEach(SetDebuggerUpdatesEnabledCallback, &enabled);
Elliott Hughesc0f09332012-03-26 13:27:06 -0700474}
475
Elliott Hughesa2155262011-11-16 16:26:58 -0800476void Dbg::GoActive() {
477 // Enable all debugging features, including scans for breakpoints.
478 // This is a no-op if we're already active.
479 // Only called from the JDWP handler thread.
480 if (gDebuggerActive) {
481 return;
482 }
483
484 LOG(INFO) << "Debugger is active";
485
Elliott Hughesc0f09332012-03-26 13:27:06 -0700486 {
487 // TODO: dalvik only warned if there were breakpoints left over. clear in Dbg::Disconnected?
jeffhao09bfc6a2012-12-11 18:11:43 -0800488 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Elliott Hughesc0f09332012-03-26 13:27:06 -0700489 CHECK_EQ(gBreakpoints.size(), 0U);
490 }
Elliott Hughesa2155262011-11-16 16:26:58 -0800491
492 gDebuggerActive = true;
Elliott Hughesc0f09332012-03-26 13:27:06 -0700493 SetDebuggerUpdatesEnabled(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700494}
495
496void Dbg::Disconnected() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700497 CHECK(gDebuggerConnected);
498
Elliott Hughesc0f09332012-03-26 13:27:06 -0700499 LOG(INFO) << "Debugger is no longer active";
Elliott Hughes234ab152011-10-26 14:02:26 -0700500
Elliott Hughesc0f09332012-03-26 13:27:06 -0700501 gDebuggerActive = false;
502 SetDebuggerUpdatesEnabled(false);
Elliott Hughes234ab152011-10-26 14:02:26 -0700503
504 gRegistry->Clear();
505 gDebuggerConnected = false;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700506}
507
Elliott Hughesc0f09332012-03-26 13:27:06 -0700508bool Dbg::IsDebuggerActive() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700509 return gDebuggerActive;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700510}
511
Elliott Hughesc0f09332012-03-26 13:27:06 -0700512bool Dbg::IsJdwpConfigured() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700513 return gJdwpConfigured;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700514}
515
516int64_t Dbg::LastDebuggerActivity() {
Elliott Hughesca951522011-12-05 12:01:32 -0800517 return gJdwpState->LastDebuggerActivity();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700518}
519
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700520void Dbg::UndoDebuggerSuspensions() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700521 Runtime::Current()->GetThreadList()->UndoDebuggerSuspensions();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700522}
523
Elliott Hughes88d63092013-01-09 09:55:54 -0800524std::string Dbg::GetClassName(JDWP::RefTypeId class_id) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800525 mirror::Object* o = gRegistry->Get<mirror::Object*>(class_id);
Elliott Hughes436e3722012-02-17 20:01:47 -0800526 if (o == NULL) {
527 return "NULL";
528 }
Elliott Hughes64f574f2013-02-20 14:57:12 -0800529 if (o == ObjectRegistry::kInvalidObject) {
Elliott Hughes88d63092013-01-09 09:55:54 -0800530 return StringPrintf("invalid object %p", reinterpret_cast<void*>(class_id));
Elliott Hughes436e3722012-02-17 20:01:47 -0800531 }
532 if (!o->IsClass()) {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800533 return StringPrintf("non-class %p", o); // This is only used for debugging output anyway.
534 }
Elliott Hughesc308a5d2012-02-16 17:12:06 -0800535 return DescriptorToName(ClassHelper(o->AsClass()).GetDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700536}
537
Elliott Hughes88d63092013-01-09 09:55:54 -0800538JDWP::JdwpError Dbg::GetClassObject(JDWP::RefTypeId id, JDWP::ObjectId& class_object_id) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800539 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800540 mirror::Class* c = DecodeClass(id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -0800541 if (c == NULL) {
542 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800543 }
Elliott Hughes88d63092013-01-09 09:55:54 -0800544 class_object_id = gRegistry->Add(c);
Elliott Hughes436e3722012-02-17 20:01:47 -0800545 return JDWP::ERR_NONE;
Elliott Hughes86964332012-02-15 19:37:42 -0800546}
547
Elliott Hughes88d63092013-01-09 09:55:54 -0800548JDWP::JdwpError Dbg::GetSuperclass(JDWP::RefTypeId id, JDWP::RefTypeId& superclass_id) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800549 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800550 mirror::Class* c = DecodeClass(id, status);
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800551 if (c == NULL) {
552 return status;
553 }
554 if (c->IsInterface()) {
555 // http://code.google.com/p/android/issues/detail?id=20856
Elliott Hughes88d63092013-01-09 09:55:54 -0800556 superclass_id = 0;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800557 } else {
Elliott Hughes88d63092013-01-09 09:55:54 -0800558 superclass_id = gRegistry->Add(c->GetSuperClass());
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800559 }
560 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700561}
562
Elliott Hughes436e3722012-02-17 20:01:47 -0800563JDWP::JdwpError Dbg::GetClassLoader(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800564 mirror::Object* o = gRegistry->Get<mirror::Object*>(id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800565 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800566 return JDWP::ERR_INVALID_OBJECT;
567 }
568 expandBufAddObjectId(pReply, gRegistry->Add(o->GetClass()->GetClassLoader()));
569 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700570}
571
Elliott Hughes436e3722012-02-17 20:01:47 -0800572JDWP::JdwpError Dbg::GetModifiers(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) {
573 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800574 mirror::Class* c = DecodeClass(id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -0800575 if (c == NULL) {
576 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800577 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800578
579 uint32_t access_flags = c->GetAccessFlags() & kAccJavaFlagsMask;
580
581 // Set ACC_SUPER; dex files don't contain this flag, but all classes are supposed to have it set.
582 // Class.getModifiers doesn't return it, but JDWP does, so we set it here.
583 access_flags |= kAccSuper;
584
585 expandBufAdd4BE(pReply, access_flags);
586
587 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700588}
589
Elliott Hughesf327e072013-01-09 16:01:26 -0800590JDWP::JdwpError Dbg::GetMonitorInfo(JDWP::ObjectId object_id, JDWP::ExpandBuf* reply)
591 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800592 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800593 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughesf327e072013-01-09 16:01:26 -0800594 return JDWP::ERR_INVALID_OBJECT;
595 }
596
597 // Ensure all threads are suspended while we read objects' lock words.
598 Thread* self = Thread::Current();
599 Locks::mutator_lock_->SharedUnlock(self);
600 Locks::mutator_lock_->ExclusiveLock(self);
601
602 MonitorInfo monitor_info(o);
603
604 Locks::mutator_lock_->ExclusiveUnlock(self);
605 Locks::mutator_lock_->SharedLock(self);
606
607 if (monitor_info.owner != NULL) {
608 expandBufAddObjectId(reply, gRegistry->Add(monitor_info.owner->GetPeer()));
609 } else {
610 expandBufAddObjectId(reply, gRegistry->Add(NULL));
611 }
612 expandBufAdd4BE(reply, monitor_info.entry_count);
613 expandBufAdd4BE(reply, monitor_info.waiters.size());
614 for (size_t i = 0; i < monitor_info.waiters.size(); ++i) {
615 expandBufAddObjectId(reply, gRegistry->Add(monitor_info.waiters[i]->GetPeer()));
616 }
617 return JDWP::ERR_NONE;
618}
619
Elliott Hughes734b8c62013-01-11 15:32:45 -0800620JDWP::JdwpError Dbg::GetOwnedMonitors(JDWP::ObjectId thread_id,
621 std::vector<JDWP::ObjectId>& monitors,
622 std::vector<uint32_t>& stack_depths)
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800623 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
624 ScopedObjectAccessUnchecked soa(Thread::Current());
625 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
626 Thread* thread;
627 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
628 if (error != JDWP::ERR_NONE) {
629 return error;
630 }
631 if (!IsSuspendedForDebugger(soa, thread)) {
632 return JDWP::ERR_THREAD_NOT_SUSPENDED;
633 }
634
635 struct OwnedMonitorVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -0800636 OwnedMonitorVisitor(Thread* thread, Context* context)
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800637 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -0800638 : StackVisitor(thread, context), current_stack_depth(0) {}
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800639
640 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
641 // annotalysis.
642 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
643 if (!GetMethod()->IsRuntimeMethod()) {
644 Monitor::VisitLocks(this, AppendOwnedMonitors, this);
Elliott Hughes734b8c62013-01-11 15:32:45 -0800645 ++current_stack_depth;
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800646 }
647 return true;
648 }
649
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800650 static void AppendOwnedMonitors(mirror::Object* owned_monitor, void* arg) {
Ian Rogers7a22fa62013-01-23 12:16:16 -0800651 OwnedMonitorVisitor* visitor = reinterpret_cast<OwnedMonitorVisitor*>(arg);
Elliott Hughes734b8c62013-01-11 15:32:45 -0800652 visitor->monitors.push_back(owned_monitor);
653 visitor->stack_depths.push_back(visitor->current_stack_depth);
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800654 }
655
Elliott Hughes734b8c62013-01-11 15:32:45 -0800656 size_t current_stack_depth;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800657 std::vector<mirror::Object*> monitors;
Elliott Hughes734b8c62013-01-11 15:32:45 -0800658 std::vector<uint32_t> stack_depths;
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800659 };
Ian Rogers7a22fa62013-01-23 12:16:16 -0800660 UniquePtr<Context> context(Context::Create());
661 OwnedMonitorVisitor visitor(thread, context.get());
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800662 visitor.WalkStack();
663
664 for (size_t i = 0; i < visitor.monitors.size(); ++i) {
665 monitors.push_back(gRegistry->Add(visitor.monitors[i]));
Elliott Hughes734b8c62013-01-11 15:32:45 -0800666 stack_depths.push_back(visitor.stack_depths[i]);
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800667 }
668
669 return JDWP::ERR_NONE;
670}
671
Elliott Hughesf9501702013-01-11 11:22:27 -0800672JDWP::JdwpError Dbg::GetContendedMonitor(JDWP::ObjectId thread_id, JDWP::ObjectId& contended_monitor)
673 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
674 ScopedObjectAccessUnchecked soa(Thread::Current());
675 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
676 Thread* thread;
677 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
678 if (error != JDWP::ERR_NONE) {
679 return error;
680 }
681 if (!IsSuspendedForDebugger(soa, thread)) {
682 return JDWP::ERR_THREAD_NOT_SUSPENDED;
683 }
684
685 contended_monitor = gRegistry->Add(Monitor::GetContendedMonitor(thread));
686
687 return JDWP::ERR_NONE;
688}
689
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800690JDWP::JdwpError Dbg::GetInstanceCounts(const std::vector<JDWP::RefTypeId>& class_ids,
691 std::vector<uint64_t>& counts)
692 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
693
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800694 std::vector<mirror::Class*> classes;
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800695 counts.clear();
696 for (size_t i = 0; i < class_ids.size(); ++i) {
697 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800698 mirror::Class* c = DecodeClass(class_ids[i], status);
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800699 if (c == NULL) {
700 return status;
701 }
702 classes.push_back(c);
703 counts.push_back(0);
704 }
705
706 Runtime::Current()->GetHeap()->CountInstances(classes, false, &counts[0]);
707 return JDWP::ERR_NONE;
708}
709
Elliott Hughes3b78c942013-01-15 17:35:41 -0800710JDWP::JdwpError Dbg::GetInstances(JDWP::RefTypeId class_id, int32_t max_count, std::vector<JDWP::ObjectId>& instances)
711 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
712 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800713 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes3b78c942013-01-15 17:35:41 -0800714 if (c == NULL) {
715 return status;
716 }
717
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800718 std::vector<mirror::Object*> raw_instances;
Elliott Hughes3b78c942013-01-15 17:35:41 -0800719 Runtime::Current()->GetHeap()->GetInstances(c, max_count, raw_instances);
720 for (size_t i = 0; i < raw_instances.size(); ++i) {
721 instances.push_back(gRegistry->Add(raw_instances[i]));
722 }
723 return JDWP::ERR_NONE;
724}
725
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800726JDWP::JdwpError Dbg::GetReferringObjects(JDWP::ObjectId object_id, int32_t max_count,
727 std::vector<JDWP::ObjectId>& referring_objects)
728 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800729 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800730 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800731 return JDWP::ERR_INVALID_OBJECT;
732 }
733
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800734 std::vector<mirror::Object*> raw_instances;
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800735 Runtime::Current()->GetHeap()->GetReferringObjects(o, max_count, raw_instances);
736 for (size_t i = 0; i < raw_instances.size(); ++i) {
737 referring_objects.push_back(gRegistry->Add(raw_instances[i]));
738 }
739 return JDWP::ERR_NONE;
740}
741
Elliott Hughes64f574f2013-02-20 14:57:12 -0800742JDWP::JdwpError Dbg::DisableCollection(JDWP::ObjectId object_id)
743 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
744 gRegistry->DisableCollection(object_id);
745 return JDWP::ERR_NONE;
746}
747
748JDWP::JdwpError Dbg::EnableCollection(JDWP::ObjectId object_id)
749 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
750 gRegistry->EnableCollection(object_id);
751 return JDWP::ERR_NONE;
752}
753
754JDWP::JdwpError Dbg::IsCollected(JDWP::ObjectId object_id, bool& is_collected)
755 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
756 is_collected = gRegistry->IsCollected(object_id);
757 return JDWP::ERR_NONE;
758}
759
760void Dbg::DisposeObject(JDWP::ObjectId object_id, uint32_t reference_count)
761 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
762 gRegistry->DisposeObject(object_id, reference_count);
763}
764
Elliott Hughes88d63092013-01-09 09:55:54 -0800765JDWP::JdwpError Dbg::GetReflectedType(JDWP::RefTypeId class_id, JDWP::ExpandBuf* pReply) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800766 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800767 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -0800768 if (c == NULL) {
769 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800770 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800771
772 expandBufAdd1(pReply, c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS);
Elliott Hughes88d63092013-01-09 09:55:54 -0800773 expandBufAddRefTypeId(pReply, class_id);
Elliott Hughes436e3722012-02-17 20:01:47 -0800774 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700775}
776
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800777void Dbg::GetClassList(std::vector<JDWP::RefTypeId>& classes) {
Elliott Hughesa2155262011-11-16 16:26:58 -0800778 // Get the complete list of reference classes (i.e. all classes except
779 // the primitive types).
780 // Returns a newly-allocated buffer full of RefTypeId values.
781 struct ClassListCreator {
Elliott Hughesba8eee12012-01-24 20:25:24 -0800782 explicit ClassListCreator(std::vector<JDWP::RefTypeId>& classes) : classes(classes) {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800783 }
784
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800785 static bool Visit(mirror::Class* c, void* arg) {
Elliott Hughesa2155262011-11-16 16:26:58 -0800786 return reinterpret_cast<ClassListCreator*>(arg)->Visit(c);
787 }
788
Elliott Hughes64f574f2013-02-20 14:57:12 -0800789 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
790 // annotalysis.
791 bool Visit(mirror::Class* c) NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughesa2155262011-11-16 16:26:58 -0800792 if (!c->IsPrimitive()) {
Elliott Hughes64f574f2013-02-20 14:57:12 -0800793 classes.push_back(gRegistry->AddRefType(c));
Elliott Hughesa2155262011-11-16 16:26:58 -0800794 }
795 return true;
796 }
797
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800798 std::vector<JDWP::RefTypeId>& classes;
Elliott Hughesa2155262011-11-16 16:26:58 -0800799 };
800
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800801 ClassListCreator clc(classes);
Elliott Hughesa2155262011-11-16 16:26:58 -0800802 Runtime::Current()->GetClassLinker()->VisitClasses(ClassListCreator::Visit, &clc);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700803}
804
Elliott Hughes88d63092013-01-09 09:55:54 -0800805JDWP::JdwpError Dbg::GetClassInfo(JDWP::RefTypeId class_id, JDWP::JdwpTypeTag* pTypeTag, uint32_t* pStatus, std::string* pDescriptor) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800806 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800807 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -0800808 if (c == NULL) {
809 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800810 }
811
Elliott Hughesa2155262011-11-16 16:26:58 -0800812 if (c->IsArrayClass()) {
813 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
814 *pTypeTag = JDWP::TT_ARRAY;
815 } else {
816 if (c->IsErroneous()) {
817 *pStatus = JDWP::CS_ERROR;
818 } else {
819 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED | JDWP::CS_INITIALIZED;
820 }
821 *pTypeTag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
822 }
823
824 if (pDescriptor != NULL) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800825 *pDescriptor = ClassHelper(c).GetDescriptor();
Elliott Hughesa2155262011-11-16 16:26:58 -0800826 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800827 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700828}
829
Elliott Hughesc3b77c72011-12-15 20:56:48 -0800830void Dbg::FindLoadedClassBySignature(const char* descriptor, std::vector<JDWP::RefTypeId>& ids) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800831 std::vector<mirror::Class*> classes;
Elliott Hughes6fa602d2011-12-02 17:54:25 -0800832 Runtime::Current()->GetClassLinker()->LookupClasses(descriptor, classes);
833 ids.clear();
834 for (size_t i = 0; i < classes.size(); ++i) {
835 ids.push_back(gRegistry->Add(classes[i]));
836 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700837}
838
Elliott Hughes64f574f2013-02-20 14:57:12 -0800839JDWP::JdwpError Dbg::GetReferenceType(JDWP::ObjectId object_id, JDWP::ExpandBuf* pReply)
840 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800841 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800842 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes2435a572012-02-17 16:07:41 -0800843 return JDWP::ERR_INVALID_OBJECT;
Elliott Hughes499c5132011-11-17 14:55:11 -0800844 }
Elliott Hughes2435a572012-02-17 16:07:41 -0800845
846 JDWP::JdwpTypeTag type_tag;
847 if (o->GetClass()->IsArrayClass()) {
848 type_tag = JDWP::TT_ARRAY;
849 } else if (o->GetClass()->IsInterface()) {
850 type_tag = JDWP::TT_INTERFACE;
851 } else {
852 type_tag = JDWP::TT_CLASS;
853 }
Elliott Hughes64f574f2013-02-20 14:57:12 -0800854 JDWP::RefTypeId type_id = gRegistry->AddRefType(o->GetClass());
Elliott Hughes2435a572012-02-17 16:07:41 -0800855
856 expandBufAdd1(pReply, type_tag);
857 expandBufAddRefTypeId(pReply, type_id);
858
859 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700860}
861
Elliott Hughes88d63092013-01-09 09:55:54 -0800862JDWP::JdwpError Dbg::GetSignature(JDWP::RefTypeId class_id, std::string& signature) {
Elliott Hughes1fe7afb2012-02-13 17:23:03 -0800863 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800864 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes1fe7afb2012-02-13 17:23:03 -0800865 if (c == NULL) {
866 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800867 }
Elliott Hughes1fe7afb2012-02-13 17:23:03 -0800868 signature = ClassHelper(c).GetDescriptor();
869 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700870}
871
Elliott Hughes88d63092013-01-09 09:55:54 -0800872JDWP::JdwpError Dbg::GetSourceFile(JDWP::RefTypeId class_id, std::string& result) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800873 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800874 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -0800875 if (c == NULL) {
876 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800877 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800878 result = ClassHelper(c).GetSourceFile();
879 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700880}
881
Elliott Hughes88d63092013-01-09 09:55:54 -0800882JDWP::JdwpError Dbg::GetObjectTag(JDWP::ObjectId object_id, uint8_t& tag) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800883 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800884 if (o == ObjectRegistry::kInvalidObject) {
Elliott Hughes546b9862012-06-20 16:06:13 -0700885 return JDWP::ERR_INVALID_OBJECT;
886 }
887 tag = TagFromObject(o);
888 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700889}
890
Elliott Hughesaed4be92011-12-02 16:16:23 -0800891size_t Dbg::GetTagWidth(JDWP::JdwpTag tag) {
Elliott Hughesdbb40792011-11-18 17:05:22 -0800892 switch (tag) {
893 case JDWP::JT_VOID:
894 return 0;
895 case JDWP::JT_BYTE:
896 case JDWP::JT_BOOLEAN:
897 return 1;
898 case JDWP::JT_CHAR:
899 case JDWP::JT_SHORT:
900 return 2;
901 case JDWP::JT_FLOAT:
902 case JDWP::JT_INT:
903 return 4;
904 case JDWP::JT_ARRAY:
905 case JDWP::JT_OBJECT:
906 case JDWP::JT_STRING:
907 case JDWP::JT_THREAD:
908 case JDWP::JT_THREAD_GROUP:
909 case JDWP::JT_CLASS_LOADER:
910 case JDWP::JT_CLASS_OBJECT:
911 return sizeof(JDWP::ObjectId);
912 case JDWP::JT_DOUBLE:
913 case JDWP::JT_LONG:
914 return 8;
915 default:
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800916 LOG(FATAL) << "Unknown tag " << tag;
Elliott Hughesdbb40792011-11-18 17:05:22 -0800917 return -1;
918 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700919}
920
Elliott Hughes88d63092013-01-09 09:55:54 -0800921JDWP::JdwpError Dbg::GetArrayLength(JDWP::ObjectId array_id, int& length) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800922 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800923 mirror::Array* a = DecodeArray(array_id, status);
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800924 if (a == NULL) {
925 return status;
Elliott Hughes24437992011-11-30 14:49:33 -0800926 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800927 length = a->GetLength();
928 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700929}
930
Elliott Hughes88d63092013-01-09 09:55:54 -0800931JDWP::JdwpError Dbg::OutputArray(JDWP::ObjectId array_id, int offset, int count, JDWP::ExpandBuf* pReply) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800932 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800933 mirror::Array* a = DecodeArray(array_id, status);
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800934 if (a == NULL) {
935 return status;
936 }
Elliott Hughes24437992011-11-30 14:49:33 -0800937
938 if (offset < 0 || count < 0 || offset > a->GetLength() || a->GetLength() - offset < count) {
939 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800940 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughes24437992011-11-30 14:49:33 -0800941 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800942 std::string descriptor(ClassHelper(a->GetClass()).GetDescriptor());
Elliott Hughes24437992011-11-30 14:49:33 -0800943 JDWP::JdwpTag tag = BasicTagFromDescriptor(descriptor.c_str() + 1);
944
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800945 expandBufAdd1(pReply, tag);
946 expandBufAdd4BE(pReply, count);
947
Elliott Hughes24437992011-11-30 14:49:33 -0800948 if (IsPrimitiveTag(tag)) {
949 size_t width = GetTagWidth(tag);
Elliott Hughes24437992011-11-30 14:49:33 -0800950 uint8_t* dst = expandBufAddSpace(pReply, count * width);
951 if (width == 8) {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800952 const uint64_t* src8 = reinterpret_cast<uint64_t*>(a->GetRawData(sizeof(uint64_t)));
Elliott Hughes24437992011-11-30 14:49:33 -0800953 for (int i = 0; i < count; ++i) JDWP::Write8BE(&dst, src8[offset + i]);
954 } else if (width == 4) {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800955 const uint32_t* src4 = reinterpret_cast<uint32_t*>(a->GetRawData(sizeof(uint32_t)));
Elliott Hughes24437992011-11-30 14:49:33 -0800956 for (int i = 0; i < count; ++i) JDWP::Write4BE(&dst, src4[offset + i]);
957 } else if (width == 2) {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800958 const uint16_t* src2 = reinterpret_cast<uint16_t*>(a->GetRawData(sizeof(uint16_t)));
Elliott Hughes24437992011-11-30 14:49:33 -0800959 for (int i = 0; i < count; ++i) JDWP::Write2BE(&dst, src2[offset + i]);
960 } else {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800961 const uint8_t* src = reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint8_t)));
Elliott Hughes24437992011-11-30 14:49:33 -0800962 memcpy(dst, &src[offset * width], count * width);
963 }
964 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800965 mirror::ObjectArray<mirror::Object>* oa = a->AsObjectArray<mirror::Object>();
Elliott Hughes24437992011-11-30 14:49:33 -0800966 for (int i = 0; i < count; ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800967 mirror::Object* element = oa->Get(offset + i);
Elliott Hughes24437992011-11-30 14:49:33 -0800968 JDWP::JdwpTag specific_tag = (element != NULL) ? TagFromObject(element) : tag;
969 expandBufAdd1(pReply, specific_tag);
970 expandBufAddObjectId(pReply, gRegistry->Add(element));
971 }
972 }
973
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800974 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700975}
976
Elliott Hughes88d63092013-01-09 09:55:54 -0800977JDWP::JdwpError Dbg::SetArrayElements(JDWP::ObjectId array_id, int offset, int count,
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700978 const uint8_t* src)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700979 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800980 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800981 mirror::Array* a = DecodeArray(array_id, status);
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800982 if (a == NULL) {
983 return status;
984 }
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800985
986 if (offset < 0 || count < 0 || offset > a->GetLength() || a->GetLength() - offset < count) {
987 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800988 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800989 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800990 std::string descriptor(ClassHelper(a->GetClass()).GetDescriptor());
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800991 JDWP::JdwpTag tag = BasicTagFromDescriptor(descriptor.c_str() + 1);
992
993 if (IsPrimitiveTag(tag)) {
994 size_t width = GetTagWidth(tag);
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800995 if (width == 8) {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800996 uint8_t* dst = &(reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint64_t)))[offset * width]);
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800997 for (int i = 0; i < count; ++i) {
998 // Handle potentially non-aligned memory access one byte at a time for ARM's benefit.
999 uint64_t value;
1000 for (size_t j = 0; j < sizeof(uint64_t); ++j) reinterpret_cast<uint8_t*>(&value)[j] = src[j];
1001 src += sizeof(uint64_t);
1002 JDWP::Write8BE(&dst, value);
1003 }
1004 } else if (width == 4) {
Ian Rogersa15e67d2012-02-28 13:51:55 -08001005 uint8_t* dst = &(reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint32_t)))[offset * width]);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001006 const uint32_t* src4 = reinterpret_cast<const uint32_t*>(src);
1007 for (int i = 0; i < count; ++i) JDWP::Write4BE(&dst, src4[i]);
1008 } else if (width == 2) {
Ian Rogersa15e67d2012-02-28 13:51:55 -08001009 uint8_t* dst = &(reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint16_t)))[offset * width]);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001010 const uint16_t* src2 = reinterpret_cast<const uint16_t*>(src);
1011 for (int i = 0; i < count; ++i) JDWP::Write2BE(&dst, src2[i]);
1012 } else {
Ian Rogersa15e67d2012-02-28 13:51:55 -08001013 uint8_t* dst = &(reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint8_t)))[offset * width]);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001014 memcpy(&dst[offset * width], src, count * width);
1015 }
1016 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001017 mirror::ObjectArray<mirror::Object>* oa = a->AsObjectArray<mirror::Object>();
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001018 for (int i = 0; i < count; ++i) {
1019 JDWP::ObjectId id = JDWP::ReadObjectId(&src);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001020 mirror::Object* o = gRegistry->Get<mirror::Object*>(id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001021 if (o == ObjectRegistry::kInvalidObject) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001022 return JDWP::ERR_INVALID_OBJECT;
1023 }
1024 oa->Set(offset + i, o);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001025 }
1026 }
1027
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001028 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001029}
1030
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001031JDWP::ObjectId Dbg::CreateString(const std::string& str) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001032 return gRegistry->Add(mirror::String::AllocFromModifiedUtf8(Thread::Current(), str.c_str()));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001033}
1034
Elliott Hughes88d63092013-01-09 09:55:54 -08001035JDWP::JdwpError Dbg::CreateObject(JDWP::RefTypeId class_id, JDWP::ObjectId& new_object) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001036 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001037 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001038 if (c == NULL) {
1039 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001040 }
Ian Rogers50b35e22012-10-04 10:09:15 -07001041 new_object = gRegistry->Add(c->AllocObject(Thread::Current()));
Elliott Hughes436e3722012-02-17 20:01:47 -08001042 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001043}
1044
Elliott Hughesbf13d362011-12-08 15:51:37 -08001045/*
1046 * Used by Eclipse's "Display" view to evaluate "new byte[5]" to get "(byte[]) [0, 0, 0, 0, 0]".
1047 */
Elliott Hughes88d63092013-01-09 09:55:54 -08001048JDWP::JdwpError Dbg::CreateArrayObject(JDWP::RefTypeId array_class_id, uint32_t length,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001049 JDWP::ObjectId& new_array) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001050 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001051 mirror::Class* c = DecodeClass(array_class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001052 if (c == NULL) {
1053 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001054 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001055 new_array = gRegistry->Add(mirror::Array::Alloc(Thread::Current(), c, length));
Elliott Hughes436e3722012-02-17 20:01:47 -08001056 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001057}
1058
Elliott Hughes88d63092013-01-09 09:55:54 -08001059bool Dbg::MatchType(JDWP::RefTypeId instance_class_id, JDWP::RefTypeId class_id) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001060 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001061 mirror::Class* c1 = DecodeClass(instance_class_id, status);
Elliott Hughesa656a0f2012-02-21 18:03:44 -08001062 CHECK(c1 != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001063 mirror::Class* c2 = DecodeClass(class_id, status);
Elliott Hughesa656a0f2012-02-21 18:03:44 -08001064 CHECK(c2 != NULL);
1065 return c1->IsAssignableFrom(c2);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001066}
1067
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001068static JDWP::FieldId ToFieldId(const mirror::Field* f)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001069 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001070#ifdef MOVING_GARBAGE_COLLECTOR
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001071 UNIMPLEMENTED(FATAL);
Elliott Hughes03181a82011-11-17 17:22:21 -08001072#else
1073 return static_cast<JDWP::FieldId>(reinterpret_cast<uintptr_t>(f));
1074#endif
1075}
1076
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001077static JDWP::MethodId ToMethodId(const mirror::AbstractMethod* m)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001078 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001079#ifdef MOVING_GARBAGE_COLLECTOR
1080 UNIMPLEMENTED(FATAL);
1081#else
1082 return static_cast<JDWP::MethodId>(reinterpret_cast<uintptr_t>(m));
1083#endif
1084}
1085
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001086static mirror::Field* FromFieldId(JDWP::FieldId fid)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001087 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesaed4be92011-12-02 16:16:23 -08001088#ifdef MOVING_GARBAGE_COLLECTOR
1089 UNIMPLEMENTED(FATAL);
1090#else
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001091 return reinterpret_cast<mirror::Field*>(static_cast<uintptr_t>(fid));
Elliott Hughesaed4be92011-12-02 16:16:23 -08001092#endif
1093}
1094
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001095static mirror::AbstractMethod* FromMethodId(JDWP::MethodId mid)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001096 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001097#ifdef MOVING_GARBAGE_COLLECTOR
1098 UNIMPLEMENTED(FATAL);
1099#else
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001100 return reinterpret_cast<mirror::AbstractMethod*>(static_cast<uintptr_t>(mid));
Elliott Hughes03181a82011-11-17 17:22:21 -08001101#endif
1102}
1103
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001104static void SetLocation(JDWP::JdwpLocation& location, mirror::AbstractMethod* m, uint32_t dex_pc)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001105 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001106 if (m == NULL) {
1107 memset(&location, 0, sizeof(location));
1108 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001109 mirror::Class* c = m->GetDeclaringClass();
Elliott Hughes74847412012-06-20 18:10:21 -07001110 location.type_tag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
1111 location.class_id = gRegistry->Add(c);
1112 location.method_id = ToMethodId(m);
Ian Rogers0399dde2012-06-06 17:09:28 -07001113 location.dex_pc = dex_pc;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001114 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08001115}
1116
Elliott Hughesa96836a2013-01-17 12:27:49 -08001117std::string Dbg::GetMethodName(JDWP::MethodId method_id)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001118 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001119 mirror::AbstractMethod* m = FromMethodId(method_id);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001120 return MethodHelper(m).GetName();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001121}
1122
Elliott Hughesa96836a2013-01-17 12:27:49 -08001123std::string Dbg::GetFieldName(JDWP::FieldId field_id)
1124 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001125 mirror::Field* f = FromFieldId(field_id);
Elliott Hughesa96836a2013-01-17 12:27:49 -08001126 return FieldHelper(f).GetName();
1127}
1128
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001129/*
1130 * Augment the access flags for synthetic methods and fields by setting
1131 * the (as described by the spec) "0xf0000000 bit". Also, strip out any
1132 * flags not specified by the Java programming language.
1133 */
1134static uint32_t MangleAccessFlags(uint32_t accessFlags) {
1135 accessFlags &= kAccJavaFlagsMask;
1136 if ((accessFlags & kAccSynthetic) != 0) {
1137 accessFlags |= 0xf0000000;
1138 }
1139 return accessFlags;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001140}
1141
Elliott Hughesdbb40792011-11-18 17:05:22 -08001142static const uint16_t kEclipseWorkaroundSlot = 1000;
1143
1144/*
1145 * Eclipse appears to expect that the "this" reference is in slot zero.
1146 * If it's not, the "variables" display will show two copies of "this",
1147 * possibly because it gets "this" from SF.ThisObject and then displays
1148 * all locals with nonzero slot numbers.
1149 *
1150 * So, we remap the item in slot 0 to 1000, and remap "this" to zero. On
1151 * SF.GetValues / SF.SetValues we map them back.
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001152 *
1153 * TODO: jdb uses the value to determine whether a variable is a local or an argument,
1154 * by checking whether it's less than the number of arguments. To make that work, we'd
1155 * have to "mangle" all the arguments to come first, not just the implicit argument 'this'.
Elliott Hughesdbb40792011-11-18 17:05:22 -08001156 */
1157static uint16_t MangleSlot(uint16_t slot, const char* name) {
1158 uint16_t newSlot = slot;
1159 if (strcmp(name, "this") == 0) {
1160 newSlot = 0;
1161 } else if (slot == 0) {
1162 newSlot = kEclipseWorkaroundSlot;
1163 }
1164 return newSlot;
1165}
1166
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001167static uint16_t DemangleSlot(uint16_t slot, mirror::AbstractMethod* m)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001168 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001169 if (slot == kEclipseWorkaroundSlot) {
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001170 return 0;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001171 } else if (slot == 0) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001172 const DexFile::CodeItem* code_item = MethodHelper(m).GetCodeItem();
Elliott Hughescaf76542012-06-28 16:08:22 -07001173 CHECK(code_item != NULL) << PrettyMethod(m);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001174 return code_item->registers_size_ - code_item->ins_size_;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001175 }
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001176 return slot;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001177}
1178
Elliott Hughes88d63092013-01-09 09:55:54 -08001179JDWP::JdwpError Dbg::OutputDeclaredFields(JDWP::RefTypeId class_id, bool with_generic, JDWP::ExpandBuf* pReply) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001180 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001181 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001182 if (c == NULL) {
1183 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001184 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001185
1186 size_t instance_field_count = c->NumInstanceFields();
1187 size_t static_field_count = c->NumStaticFields();
1188
1189 expandBufAdd4BE(pReply, instance_field_count + static_field_count);
1190
1191 for (size_t i = 0; i < instance_field_count + static_field_count; ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001192 mirror::Field* f = (i < instance_field_count) ? c->GetInstanceField(i) : c->GetStaticField(i - instance_field_count);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001193 FieldHelper fh(f);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001194 expandBufAddFieldId(pReply, ToFieldId(f));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001195 expandBufAddUtf8String(pReply, fh.GetName());
1196 expandBufAddUtf8String(pReply, fh.GetTypeDescriptor());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001197 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001198 static const char genericSignature[1] = "";
1199 expandBufAddUtf8String(pReply, genericSignature);
1200 }
1201 expandBufAdd4BE(pReply, MangleAccessFlags(f->GetAccessFlags()));
1202 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001203 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001204}
1205
Elliott Hughes88d63092013-01-09 09:55:54 -08001206JDWP::JdwpError Dbg::OutputDeclaredMethods(JDWP::RefTypeId class_id, bool with_generic,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001207 JDWP::ExpandBuf* pReply) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001208 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001209 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001210 if (c == NULL) {
1211 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001212 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001213
1214 size_t direct_method_count = c->NumDirectMethods();
1215 size_t virtual_method_count = c->NumVirtualMethods();
1216
1217 expandBufAdd4BE(pReply, direct_method_count + virtual_method_count);
1218
1219 for (size_t i = 0; i < direct_method_count + virtual_method_count; ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001220 mirror::AbstractMethod* m = (i < direct_method_count) ? c->GetDirectMethod(i) : c->GetVirtualMethod(i - direct_method_count);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001221 MethodHelper mh(m);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001222 expandBufAddMethodId(pReply, ToMethodId(m));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001223 expandBufAddUtf8String(pReply, mh.GetName());
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001224 expandBufAddUtf8String(pReply, mh.GetSignature());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001225 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001226 static const char genericSignature[1] = "";
1227 expandBufAddUtf8String(pReply, genericSignature);
1228 }
1229 expandBufAdd4BE(pReply, MangleAccessFlags(m->GetAccessFlags()));
1230 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001231 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001232}
1233
Elliott Hughes88d63092013-01-09 09:55:54 -08001234JDWP::JdwpError Dbg::OutputDeclaredInterfaces(JDWP::RefTypeId class_id, JDWP::ExpandBuf* pReply) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001235 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001236 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001237 if (c == NULL) {
1238 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001239 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001240
1241 ClassHelper kh(c);
Ian Rogersd24e2642012-06-06 21:21:43 -07001242 size_t interface_count = kh.NumDirectInterfaces();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001243 expandBufAdd4BE(pReply, interface_count);
1244 for (size_t i = 0; i < interface_count; ++i) {
Elliott Hughes64f574f2013-02-20 14:57:12 -08001245 expandBufAddRefTypeId(pReply, gRegistry->AddRefType(kh.GetDirectInterface(i)));
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001246 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001247 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001248}
1249
Elliott Hughes88d63092013-01-09 09:55:54 -08001250void Dbg::OutputLineTable(JDWP::RefTypeId, JDWP::MethodId method_id, JDWP::ExpandBuf* pReply)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001251 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001252 struct DebugCallbackContext {
1253 int numItems;
1254 JDWP::ExpandBuf* pReply;
1255
Elliott Hughes2435a572012-02-17 16:07:41 -08001256 static bool Callback(void* context, uint32_t address, uint32_t line_number) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001257 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
1258 expandBufAdd8BE(pContext->pReply, address);
Elliott Hughes2435a572012-02-17 16:07:41 -08001259 expandBufAdd4BE(pContext->pReply, line_number);
Elliott Hughes03181a82011-11-17 17:22:21 -08001260 pContext->numItems++;
1261 return true;
1262 }
1263 };
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001264 mirror::AbstractMethod* m = FromMethodId(method_id);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001265 MethodHelper mh(m);
Elliott Hughes03181a82011-11-17 17:22:21 -08001266 uint64_t start, end;
1267 if (m->IsNative()) {
1268 start = -1;
1269 end = -1;
1270 } else {
1271 start = 0;
jeffhao14f0db92012-12-14 17:50:42 -08001272 // Return the index of the last instruction
1273 end = mh.GetCodeItem()->insns_size_in_code_units_ - 1;
Elliott Hughes03181a82011-11-17 17:22:21 -08001274 }
1275
1276 expandBufAdd8BE(pReply, start);
1277 expandBufAdd8BE(pReply, end);
1278
1279 // Add numLines later
1280 size_t numLinesOffset = expandBufGetLength(pReply);
1281 expandBufAdd4BE(pReply, 0);
1282
1283 DebugCallbackContext context;
1284 context.numItems = 0;
1285 context.pReply = pReply;
1286
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001287 mh.GetDexFile().DecodeDebugInfo(mh.GetCodeItem(), m->IsStatic(), m->GetDexMethodIndex(),
1288 DebugCallbackContext::Callback, NULL, &context);
Elliott Hughes03181a82011-11-17 17:22:21 -08001289
1290 JDWP::Set4BE(expandBufGetBuffer(pReply) + numLinesOffset, context.numItems);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001291}
1292
Elliott Hughes88d63092013-01-09 09:55:54 -08001293void Dbg::OutputVariableTable(JDWP::RefTypeId, JDWP::MethodId method_id, bool with_generic, JDWP::ExpandBuf* pReply) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001294 struct DebugCallbackContext {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001295 JDWP::ExpandBuf* pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001296 size_t variable_count;
1297 bool with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001298
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001299 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 -08001300 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
1301
Elliott Hughesad3da692012-02-24 16:51:35 -08001302 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 -08001303
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001304 slot = MangleSlot(slot, name);
1305
Elliott Hughesdbb40792011-11-18 17:05:22 -08001306 expandBufAdd8BE(pContext->pReply, startAddress);
1307 expandBufAddUtf8String(pContext->pReply, name);
1308 expandBufAddUtf8String(pContext->pReply, descriptor);
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001309 if (pContext->with_generic) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001310 expandBufAddUtf8String(pContext->pReply, signature);
1311 }
1312 expandBufAdd4BE(pContext->pReply, endAddress - startAddress);
1313 expandBufAdd4BE(pContext->pReply, slot);
1314
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001315 ++pContext->variable_count;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001316 }
1317 };
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001318 mirror::AbstractMethod* m = FromMethodId(method_id);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001319 MethodHelper mh(m);
1320 const DexFile::CodeItem* code_item = mh.GetCodeItem();
Elliott Hughesdbb40792011-11-18 17:05:22 -08001321
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001322 // arg_count considers doubles and longs to take 2 units.
1323 // variable_count considers everything to take 1 unit.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001324 std::string shorty(mh.GetShorty());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001325 expandBufAdd4BE(pReply, mirror::AbstractMethod::NumArgRegisters(shorty));
Elliott Hughesdbb40792011-11-18 17:05:22 -08001326
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001327 // We don't know the total number of variables yet, so leave a blank and update it later.
1328 size_t variable_count_offset = expandBufGetLength(pReply);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001329 expandBufAdd4BE(pReply, 0);
1330
1331 DebugCallbackContext context;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001332 context.pReply = pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001333 context.variable_count = 0;
1334 context.with_generic = with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001335
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001336 mh.GetDexFile().DecodeDebugInfo(code_item, m->IsStatic(), m->GetDexMethodIndex(), NULL,
1337 DebugCallbackContext::Callback, &context);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001338
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001339 JDWP::Set4BE(expandBufGetBuffer(pReply) + variable_count_offset, context.variable_count);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001340}
1341
Elliott Hughes9777ba22013-01-17 09:04:19 -08001342JDWP::JdwpError Dbg::GetBytecodes(JDWP::RefTypeId, JDWP::MethodId method_id,
1343 std::vector<uint8_t>& bytecodes)
1344 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001345 mirror::AbstractMethod* m = FromMethodId(method_id);
Elliott Hughes9777ba22013-01-17 09:04:19 -08001346 if (m == NULL) {
1347 return JDWP::ERR_INVALID_METHODID;
1348 }
1349 MethodHelper mh(m);
1350 const DexFile::CodeItem* code_item = mh.GetCodeItem();
1351 size_t byte_count = code_item->insns_size_in_code_units_ * 2;
1352 const uint8_t* begin = reinterpret_cast<const uint8_t*>(code_item->insns_);
1353 const uint8_t* end = begin + byte_count;
1354 for (const uint8_t* p = begin; p != end; ++p) {
1355 bytecodes.push_back(*p);
1356 }
1357 return JDWP::ERR_NONE;
1358}
1359
Elliott Hughes88d63092013-01-09 09:55:54 -08001360JDWP::JdwpTag Dbg::GetFieldBasicTag(JDWP::FieldId field_id) {
1361 return BasicTagFromDescriptor(FieldHelper(FromFieldId(field_id)).GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001362}
1363
Elliott Hughes88d63092013-01-09 09:55:54 -08001364JDWP::JdwpTag Dbg::GetStaticFieldBasicTag(JDWP::FieldId field_id) {
1365 return BasicTagFromDescriptor(FieldHelper(FromFieldId(field_id)).GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001366}
1367
Elliott Hughes88d63092013-01-09 09:55:54 -08001368static JDWP::JdwpError GetFieldValueImpl(JDWP::RefTypeId ref_type_id, JDWP::ObjectId object_id,
1369 JDWP::FieldId field_id, JDWP::ExpandBuf* pReply,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001370 bool is_static)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001371 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes0cf74332012-02-23 23:14:00 -08001372 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001373 mirror::Class* c = DecodeClass(ref_type_id, status);
Elliott Hughes88d63092013-01-09 09:55:54 -08001374 if (ref_type_id != 0 && c == NULL) {
Elliott Hughes0cf74332012-02-23 23:14:00 -08001375 return status;
1376 }
1377
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001378 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001379 if ((!is_static && o == NULL) || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001380 return JDWP::ERR_INVALID_OBJECT;
1381 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001382 mirror::Field* f = FromFieldId(field_id);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001383
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001384 mirror::Class* receiver_class = c;
Elliott Hughes0cf74332012-02-23 23:14:00 -08001385 if (receiver_class == NULL && o != NULL) {
1386 receiver_class = o->GetClass();
1387 }
1388 // TODO: should we give up now if receiver_class is NULL?
1389 if (receiver_class != NULL && !f->GetDeclaringClass()->IsAssignableFrom(receiver_class)) {
1390 LOG(INFO) << "ERR_INVALID_FIELDID: " << PrettyField(f) << " " << PrettyClass(receiver_class);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001391 return JDWP::ERR_INVALID_FIELDID;
1392 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001393
Elliott Hughes0cf74332012-02-23 23:14:00 -08001394 // The RI only enforces the static/non-static mismatch in one direction.
1395 // TODO: should we change the tests and check both?
1396 if (is_static) {
1397 if (!f->IsStatic()) {
1398 return JDWP::ERR_INVALID_FIELDID;
1399 }
1400 } else {
1401 if (f->IsStatic()) {
1402 LOG(WARNING) << "Ignoring non-NULL receiver for ObjectReference.SetValues on static field " << PrettyField(f);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001403 }
1404 }
jeffhao0dfbb7e2012-11-28 15:26:03 -08001405 if (f->IsStatic()) {
1406 o = f->GetDeclaringClass();
1407 }
Elliott Hughes0cf74332012-02-23 23:14:00 -08001408
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001409 JDWP::JdwpTag tag = BasicTagFromDescriptor(FieldHelper(f).GetTypeDescriptor());
Elliott Hughesaed4be92011-12-02 16:16:23 -08001410
1411 if (IsPrimitiveTag(tag)) {
1412 expandBufAdd1(pReply, tag);
1413 if (tag == JDWP::JT_BOOLEAN || tag == JDWP::JT_BYTE) {
1414 expandBufAdd1(pReply, f->Get32(o));
1415 } else if (tag == JDWP::JT_CHAR || tag == JDWP::JT_SHORT) {
1416 expandBufAdd2BE(pReply, f->Get32(o));
1417 } else if (tag == JDWP::JT_FLOAT || tag == JDWP::JT_INT) {
1418 expandBufAdd4BE(pReply, f->Get32(o));
1419 } else if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
1420 expandBufAdd8BE(pReply, f->Get64(o));
1421 } else {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001422 LOG(FATAL) << "Unknown tag: " << tag;
Elliott Hughesaed4be92011-12-02 16:16:23 -08001423 }
1424 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001425 mirror::Object* value = f->GetObject(o);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001426 expandBufAdd1(pReply, TagFromObject(value));
1427 expandBufAddObjectId(pReply, gRegistry->Add(value));
1428 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001429 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001430}
1431
Elliott Hughes88d63092013-01-09 09:55:54 -08001432JDWP::JdwpError Dbg::GetFieldValue(JDWP::ObjectId object_id, JDWP::FieldId field_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001433 JDWP::ExpandBuf* pReply) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001434 return GetFieldValueImpl(0, object_id, field_id, pReply, false);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001435}
1436
Elliott Hughes88d63092013-01-09 09:55:54 -08001437JDWP::JdwpError Dbg::GetStaticFieldValue(JDWP::RefTypeId ref_type_id, JDWP::FieldId field_id, JDWP::ExpandBuf* pReply) {
1438 return GetFieldValueImpl(ref_type_id, 0, field_id, pReply, true);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001439}
1440
Elliott Hughes88d63092013-01-09 09:55:54 -08001441static JDWP::JdwpError SetFieldValueImpl(JDWP::ObjectId object_id, JDWP::FieldId field_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001442 uint64_t value, int width, bool is_static)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001443 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001444 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001445 if ((!is_static && o == NULL) || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001446 return JDWP::ERR_INVALID_OBJECT;
1447 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001448 mirror::Field* f = FromFieldId(field_id);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001449
1450 // The RI only enforces the static/non-static mismatch in one direction.
1451 // TODO: should we change the tests and check both?
1452 if (is_static) {
1453 if (!f->IsStatic()) {
1454 return JDWP::ERR_INVALID_FIELDID;
1455 }
1456 } else {
1457 if (f->IsStatic()) {
1458 LOG(WARNING) << "Ignoring non-NULL receiver for ObjectReference.SetValues on static field " << PrettyField(f);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001459 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001460 }
jeffhao0dfbb7e2012-11-28 15:26:03 -08001461 if (f->IsStatic()) {
1462 o = f->GetDeclaringClass();
1463 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001464
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001465 JDWP::JdwpTag tag = BasicTagFromDescriptor(FieldHelper(f).GetTypeDescriptor());
Elliott Hughesaed4be92011-12-02 16:16:23 -08001466
1467 if (IsPrimitiveTag(tag)) {
1468 if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001469 CHECK_EQ(width, 8);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001470 f->Set64(o, value);
1471 } else {
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001472 CHECK_LE(width, 4);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001473 f->Set32(o, value);
1474 }
1475 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001476 mirror::Object* v = gRegistry->Get<mirror::Object*>(value);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001477 if (v == ObjectRegistry::kInvalidObject) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001478 return JDWP::ERR_INVALID_OBJECT;
1479 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001480 if (v != NULL) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001481 mirror::Class* field_type = FieldHelper(f).GetType();
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001482 if (!field_type->IsAssignableFrom(v->GetClass())) {
1483 return JDWP::ERR_INVALID_OBJECT;
1484 }
1485 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001486 f->SetObject(o, v);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001487 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001488
1489 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001490}
1491
Elliott Hughes88d63092013-01-09 09:55:54 -08001492JDWP::JdwpError Dbg::SetFieldValue(JDWP::ObjectId object_id, JDWP::FieldId field_id, uint64_t value,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001493 int width) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001494 return SetFieldValueImpl(object_id, field_id, value, width, false);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001495}
1496
Elliott Hughes88d63092013-01-09 09:55:54 -08001497JDWP::JdwpError Dbg::SetStaticFieldValue(JDWP::FieldId field_id, uint64_t value, int width) {
1498 return SetFieldValueImpl(0, field_id, value, width, true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001499}
1500
Elliott Hughes88d63092013-01-09 09:55:54 -08001501std::string Dbg::StringToUtf8(JDWP::ObjectId string_id) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001502 mirror::String* s = gRegistry->Get<mirror::String*>(string_id);
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001503 return s->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001504}
1505
Elliott Hughes221229c2013-01-08 18:17:50 -08001506JDWP::JdwpError Dbg::GetThreadName(JDWP::ObjectId thread_id, std::string& name) {
jeffhaoa77f0f62012-12-05 17:19:31 -08001507 ScopedObjectAccessUnchecked soa(Thread::Current());
1508 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001509 Thread* thread;
1510 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1511 if (error != JDWP::ERR_NONE && error != JDWP::ERR_THREAD_NOT_ALIVE) {
1512 return error;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001513 }
Elliott Hughes221229c2013-01-08 18:17:50 -08001514
1515 // We still need to report the zombie threads' names, so we can't just call Thread::GetThreadName.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001516 mirror::Object* thread_object = gRegistry->Get<mirror::Object*>(thread_id);
1517 mirror::Field* java_lang_Thread_name_field =
1518 soa.DecodeField(WellKnownClasses::java_lang_Thread_name);
1519 mirror::String* s =
1520 reinterpret_cast<mirror::String*>(java_lang_Thread_name_field->GetObject(thread_object));
Elliott Hughes221229c2013-01-08 18:17:50 -08001521 if (s != NULL) {
1522 name = s->ToModifiedUtf8();
1523 }
1524 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001525}
1526
Elliott Hughes221229c2013-01-08 18:17:50 -08001527JDWP::JdwpError Dbg::GetThreadGroup(JDWP::ObjectId thread_id, JDWP::ExpandBuf* pReply) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001528 ScopedObjectAccess soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001529 mirror::Object* thread_object = gRegistry->Get<mirror::Object*>(thread_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001530 if (thread_object == ObjectRegistry::kInvalidObject) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001531 return JDWP::ERR_INVALID_OBJECT;
1532 }
1533
1534 // Okay, so it's an object, but is it actually a thread?
Ian Rogers50b35e22012-10-04 10:09:15 -07001535 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001536 Thread* thread;
1537 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1538 if (error == JDWP::ERR_THREAD_NOT_ALIVE) {
1539 // Zombie threads are in the null group.
1540 expandBufAddObjectId(pReply, JDWP::ObjectId(0));
1541 return JDWP::ERR_NONE;
1542 }
1543 if (error != JDWP::ERR_NONE) {
1544 return error;
Elliott Hughes2435a572012-02-17 16:07:41 -08001545 }
Elliott Hughes499c5132011-11-17 14:55:11 -08001546
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001547 mirror::Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/Thread;");
Elliott Hughes499c5132011-11-17 14:55:11 -08001548 CHECK(c != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001549 mirror::Field* f = c->FindInstanceField("group", "Ljava/lang/ThreadGroup;");
Elliott Hughes499c5132011-11-17 14:55:11 -08001550 CHECK(f != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001551 mirror::Object* group = f->GetObject(thread_object);
Elliott Hughes499c5132011-11-17 14:55:11 -08001552 CHECK(group != NULL);
Elliott Hughes2435a572012-02-17 16:07:41 -08001553 JDWP::ObjectId thread_group_id = gRegistry->Add(group);
1554
1555 expandBufAddObjectId(pReply, thread_group_id);
1556 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001557}
1558
Elliott Hughes88d63092013-01-09 09:55:54 -08001559std::string Dbg::GetThreadGroupName(JDWP::ObjectId thread_group_id) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001560 ScopedObjectAccess soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001561 mirror::Object* thread_group = gRegistry->Get<mirror::Object*>(thread_group_id);
Elliott Hughes499c5132011-11-17 14:55:11 -08001562 CHECK(thread_group != NULL);
1563
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001564 mirror::Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/ThreadGroup;");
Elliott Hughes499c5132011-11-17 14:55:11 -08001565 CHECK(c != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001566 mirror::Field* f = c->FindInstanceField("name", "Ljava/lang/String;");
Elliott Hughes499c5132011-11-17 14:55:11 -08001567 CHECK(f != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001568 mirror::String* s = reinterpret_cast<mirror::String*>(f->GetObject(thread_group));
Elliott Hughes499c5132011-11-17 14:55:11 -08001569 return s->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001570}
1571
Elliott Hughes88d63092013-01-09 09:55:54 -08001572JDWP::ObjectId Dbg::GetThreadGroupParent(JDWP::ObjectId thread_group_id) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001573 mirror::Object* thread_group = gRegistry->Get<mirror::Object*>(thread_group_id);
Elliott Hughes4e235312011-12-02 11:34:15 -08001574 CHECK(thread_group != NULL);
1575
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001576 mirror::Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/ThreadGroup;");
Elliott Hughes4e235312011-12-02 11:34:15 -08001577 CHECK(c != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001578 mirror::Field* f = c->FindInstanceField("parent", "Ljava/lang/ThreadGroup;");
Elliott Hughes4e235312011-12-02 11:34:15 -08001579 CHECK(f != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001580 mirror::Object* parent = f->GetObject(thread_group);
Elliott Hughes4e235312011-12-02 11:34:15 -08001581 return gRegistry->Add(parent);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001582}
1583
1584JDWP::ObjectId Dbg::GetSystemThreadGroupId() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001585 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001586 mirror::Field* f = soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_systemThreadGroup);
1587 mirror::Object* group = f->GetObject(f->GetDeclaringClass());
Ian Rogers365c1022012-06-22 15:05:28 -07001588 return gRegistry->Add(group);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001589}
1590
1591JDWP::ObjectId Dbg::GetMainThreadGroupId() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001592 ScopedObjectAccess soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001593 mirror::Field* f = soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_mainThreadGroup);
1594 mirror::Object* group = f->GetObject(f->GetDeclaringClass());
Ian Rogers365c1022012-06-22 15:05:28 -07001595 return gRegistry->Add(group);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001596}
1597
Elliott Hughes221229c2013-01-08 18:17:50 -08001598JDWP::JdwpError Dbg::GetThreadStatus(JDWP::ObjectId thread_id, JDWP::JdwpThreadStatus* pThreadStatus, JDWP::JdwpSuspendStatus* pSuspendStatus) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001599 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes499c5132011-11-17 14:55:11 -08001600
Elliott Hughes9e0c1752013-01-09 14:02:58 -08001601 *pSuspendStatus = JDWP::SUSPEND_STATUS_NOT_SUSPENDED;
1602
Ian Rogers50b35e22012-10-04 10:09:15 -07001603 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001604 Thread* thread;
1605 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1606 if (error != JDWP::ERR_NONE) {
1607 if (error == JDWP::ERR_THREAD_NOT_ALIVE) {
1608 *pThreadStatus = JDWP::TS_ZOMBIE;
Elliott Hughes221229c2013-01-08 18:17:50 -08001609 return JDWP::ERR_NONE;
1610 }
1611 return error;
Elliott Hughes499c5132011-11-17 14:55:11 -08001612 }
1613
Elliott Hughes9e0c1752013-01-09 14:02:58 -08001614 if (IsSuspendedForDebugger(soa, thread)) {
1615 *pSuspendStatus = JDWP::SUSPEND_STATUS_SUSPENDED;
Elliott Hughes499c5132011-11-17 14:55:11 -08001616 }
1617
Elliott Hughes9e0c1752013-01-09 14:02:58 -08001618 switch (thread->GetState()) {
1619 case kBlocked: *pThreadStatus = JDWP::TS_MONITOR; break;
1620 case kNative: *pThreadStatus = JDWP::TS_RUNNING; break;
1621 case kRunnable: *pThreadStatus = JDWP::TS_RUNNING; break;
1622 case kSleeping: *pThreadStatus = JDWP::TS_SLEEPING; break;
1623 case kStarting: *pThreadStatus = JDWP::TS_ZOMBIE; break;
1624 case kSuspended: *pThreadStatus = JDWP::TS_RUNNING; break;
1625 case kTerminated: *pThreadStatus = JDWP::TS_ZOMBIE; break;
1626 case kTimedWaiting: *pThreadStatus = JDWP::TS_WAIT; break;
1627 case kWaitingForDebuggerSend: *pThreadStatus = JDWP::TS_WAIT; break;
1628 case kWaitingForDebuggerSuspension: *pThreadStatus = JDWP::TS_WAIT; break;
1629 case kWaitingForDebuggerToAttach: *pThreadStatus = JDWP::TS_WAIT; break;
1630 case kWaitingForGcToComplete: *pThreadStatus = JDWP::TS_WAIT; break;
1631 case kWaitingForJniOnLoad: *pThreadStatus = JDWP::TS_WAIT; break;
1632 case kWaitingForSignalCatcherOutput: *pThreadStatus = JDWP::TS_WAIT; break;
1633 case kWaitingInMainDebuggerLoop: *pThreadStatus = JDWP::TS_WAIT; break;
1634 case kWaitingInMainSignalCatcherLoop: *pThreadStatus = JDWP::TS_WAIT; break;
1635 case kWaitingPerformingGc: *pThreadStatus = JDWP::TS_WAIT; break;
1636 case kWaiting: *pThreadStatus = JDWP::TS_WAIT; break;
1637 // Don't add a 'default' here so the compiler can spot incompatible enum changes.
1638 }
Elliott Hughes221229c2013-01-08 18:17:50 -08001639 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001640}
1641
Elliott Hughes221229c2013-01-08 18:17:50 -08001642JDWP::JdwpError Dbg::GetThreadDebugSuspendCount(JDWP::ObjectId thread_id, JDWP::ExpandBuf* pReply) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001643 ScopedObjectAccess soa(Thread::Current());
Ian Rogers50b35e22012-10-04 10:09:15 -07001644 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001645 Thread* thread;
1646 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1647 if (error != JDWP::ERR_NONE) {
1648 return error;
Elliott Hughes2435a572012-02-17 16:07:41 -08001649 }
Ian Rogers50b35e22012-10-04 10:09:15 -07001650 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001651 expandBufAdd4BE(pReply, thread->GetDebugSuspendCount());
Elliott Hughes2435a572012-02-17 16:07:41 -08001652 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001653}
1654
Elliott Hughesf9501702013-01-11 11:22:27 -08001655JDWP::JdwpError Dbg::Interrupt(JDWP::ObjectId thread_id) {
1656 ScopedObjectAccess soa(Thread::Current());
1657 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
1658 Thread* thread;
1659 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1660 if (error != JDWP::ERR_NONE) {
1661 return error;
1662 }
1663 thread->Interrupt();
1664 return JDWP::ERR_NONE;
1665}
1666
Elliott Hughescaf76542012-06-28 16:08:22 -07001667void Dbg::GetThreads(JDWP::ObjectId thread_group_id, std::vector<JDWP::ObjectId>& thread_ids) {
Ian Rogers365c1022012-06-22 15:05:28 -07001668 class ThreadListVisitor {
1669 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001670 ThreadListVisitor(const ScopedObjectAccessUnchecked& soa, mirror::Object* desired_thread_group,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001671 std::vector<JDWP::ObjectId>& thread_ids)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001672 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
jeffhao0dfbb7e2012-11-28 15:26:03 -08001673 : soa_(soa), desired_thread_group_(desired_thread_group), thread_ids_(thread_ids) {}
Ian Rogers365c1022012-06-22 15:05:28 -07001674
Elliott Hughesa2155262011-11-16 16:26:58 -08001675 static void Visit(Thread* t, void* arg) {
1676 reinterpret_cast<ThreadListVisitor*>(arg)->Visit(t);
1677 }
1678
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001679 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1680 // annotalysis.
1681 void Visit(Thread* t) NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughesa2155262011-11-16 16:26:58 -08001682 if (t == Dbg::GetDebugThread()) {
1683 // Skip the JDWP thread. Some debuggers get bent out of shape when they can't suspend and
1684 // query all threads, so it's easier if we just don't tell them about this thread.
1685 return;
1686 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001687 mirror::Object* peer = t->GetPeer();
jeffhao0dfbb7e2012-11-28 15:26:03 -08001688 if (IsInDesiredThreadGroup(peer)) {
Ian Rogers120f1c72012-09-28 17:17:10 -07001689 thread_ids_.push_back(gRegistry->Add(peer));
Elliott Hughesa2155262011-11-16 16:26:58 -08001690 }
1691 }
1692
Ian Rogers365c1022012-06-22 15:05:28 -07001693 private:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001694 bool IsInDesiredThreadGroup(mirror::Object* peer)
jeffhao0dfbb7e2012-11-28 15:26:03 -08001695 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
jeffhao0dfbb7e2012-11-28 15:26:03 -08001696 // peer might be NULL if the thread is still starting up.
1697 if (peer == NULL) {
1698 // We can't tell the debugger about this thread yet.
1699 // TODO: if we identified threads to the debugger by their Thread*
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001700 // rather than their peer's mirror::Object*, we could fix this.
jeffhao0dfbb7e2012-11-28 15:26:03 -08001701 // Doing so might help us report ZOMBIE threads too.
1702 return false;
1703 }
jeffhaoc1e04902012-12-13 12:41:10 -08001704 // Do we want threads from all thread groups?
1705 if (desired_thread_group_ == NULL) {
1706 return true;
1707 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001708 mirror::Object* group = soa_.DecodeField(WellKnownClasses::java_lang_Thread_group)->GetObject(peer);
jeffhao0dfbb7e2012-11-28 15:26:03 -08001709 return (group == desired_thread_group_);
1710 }
1711
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07001712 const ScopedObjectAccessUnchecked& soa_;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001713 mirror::Object* const desired_thread_group_;
Elliott Hughescaf76542012-06-28 16:08:22 -07001714 std::vector<JDWP::ObjectId>& thread_ids_;
Elliott Hughesa2155262011-11-16 16:26:58 -08001715 };
1716
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001717 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001718 mirror::Object* thread_group = gRegistry->Get<mirror::Object*>(thread_group_id);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001719 ThreadListVisitor tlv(soa, thread_group, thread_ids);
Ian Rogers50b35e22012-10-04 10:09:15 -07001720 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughesf8349362012-06-18 15:00:06 -07001721 Runtime::Current()->GetThreadList()->ForEach(ThreadListVisitor::Visit, &tlv);
Elliott Hughescaf76542012-06-28 16:08:22 -07001722}
Elliott Hughesa2155262011-11-16 16:26:58 -08001723
Elliott Hughescaf76542012-06-28 16:08:22 -07001724void Dbg::GetChildThreadGroups(JDWP::ObjectId thread_group_id, std::vector<JDWP::ObjectId>& child_thread_group_ids) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001725 ScopedObjectAccess soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001726 mirror::Object* thread_group = gRegistry->Get<mirror::Object*>(thread_group_id);
Elliott Hughescaf76542012-06-28 16:08:22 -07001727
1728 // Get the ArrayList<ThreadGroup> "groups" out of this thread group...
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001729 mirror::Field* groups_field = thread_group->GetClass()->FindInstanceField("groups", "Ljava/util/List;");
1730 mirror::Object* groups_array_list = groups_field->GetObject(thread_group);
Elliott Hughescaf76542012-06-28 16:08:22 -07001731
1732 // Get the array and size out of the ArrayList<ThreadGroup>...
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001733 mirror::Field* array_field = groups_array_list->GetClass()->FindInstanceField("array", "[Ljava/lang/Object;");
1734 mirror::Field* size_field = groups_array_list->GetClass()->FindInstanceField("size", "I");
1735 mirror::ObjectArray<mirror::Object>* groups_array =
1736 array_field->GetObject(groups_array_list)->AsObjectArray<mirror::Object>();
Elliott Hughescaf76542012-06-28 16:08:22 -07001737 const int32_t size = size_field->GetInt(groups_array_list);
1738
1739 // Copy the first 'size' elements out of the array into the result.
1740 for (int32_t i = 0; i < size; ++i) {
1741 child_thread_group_ids.push_back(gRegistry->Add(groups_array->Get(i)));
Elliott Hughesa2155262011-11-16 16:26:58 -08001742 }
1743}
1744
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001745static int GetStackDepth(Thread* thread)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001746 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers0399dde2012-06-06 17:09:28 -07001747 struct CountStackDepthVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -08001748 CountStackDepthVisitor(Thread* thread)
1749 : StackVisitor(thread, NULL), depth(0) {}
Ian Rogers0399dde2012-06-06 17:09:28 -07001750
Elliott Hughes64f574f2013-02-20 14:57:12 -08001751 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1752 // annotalysis.
1753 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07001754 if (!GetMethod()->IsRuntimeMethod()) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -08001755 ++depth;
1756 }
Elliott Hughes530fa002012-03-12 11:44:49 -07001757 return true;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001758 }
1759 size_t depth;
1760 };
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001761
Ian Rogers7a22fa62013-01-23 12:16:16 -08001762 CountStackDepthVisitor visitor(thread);
Ian Rogers0399dde2012-06-06 17:09:28 -07001763 visitor.WalkStack();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001764 return visitor.depth;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001765}
1766
Elliott Hughes221229c2013-01-08 18:17:50 -08001767JDWP::JdwpError Dbg::GetThreadFrameCount(JDWP::ObjectId thread_id, size_t& result) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001768 ScopedObjectAccess soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08001769 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001770 Thread* thread;
1771 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1772 if (error != JDWP::ERR_NONE) {
1773 return error;
1774 }
Elliott Hughesf15f4a02013-01-09 10:09:38 -08001775 if (!IsSuspendedForDebugger(soa, thread)) {
1776 return JDWP::ERR_THREAD_NOT_SUSPENDED;
1777 }
Elliott Hughes221229c2013-01-08 18:17:50 -08001778 result = GetStackDepth(thread);
1779 return JDWP::ERR_NONE;
Elliott Hughes86964332012-02-15 19:37:42 -08001780}
1781
Ian Rogers306057f2012-11-26 12:45:53 -08001782JDWP::JdwpError Dbg::GetThreadFrames(JDWP::ObjectId thread_id, size_t start_frame,
1783 size_t frame_count, JDWP::ExpandBuf* buf) {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001784 class GetFrameVisitor : public StackVisitor {
1785 public:
Ian Rogers7a22fa62013-01-23 12:16:16 -08001786 GetFrameVisitor(Thread* thread, size_t start_frame, size_t frame_count, JDWP::ExpandBuf* buf)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001787 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08001788 : StackVisitor(thread, NULL), depth_(0),
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001789 start_frame_(start_frame), frame_count_(frame_count), buf_(buf) {
1790 expandBufAdd4BE(buf_, frame_count_);
Elliott Hughes03181a82011-11-17 17:22:21 -08001791 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001792
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001793 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1794 // annotalysis.
1795 virtual bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07001796 if (GetMethod()->IsRuntimeMethod()) {
Elliott Hughes530fa002012-03-12 11:44:49 -07001797 return true; // The debugger can't do anything useful with a frame that has no Method*.
Elliott Hughes03181a82011-11-17 17:22:21 -08001798 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001799 if (depth_ >= start_frame_ + frame_count_) {
Elliott Hughes530fa002012-03-12 11:44:49 -07001800 return false;
Elliott Hughes03181a82011-11-17 17:22:21 -08001801 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001802 if (depth_ >= start_frame_) {
1803 JDWP::FrameId frame_id(GetFrameId());
1804 JDWP::JdwpLocation location;
1805 SetLocation(location, GetMethod(), GetDexPc());
Elliott Hughes7baf96f2012-06-22 16:33:50 -07001806 VLOG(jdwp) << StringPrintf(" Frame %3zd: id=%3lld ", depth_, frame_id) << location;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001807 expandBufAdd8BE(buf_, frame_id);
1808 expandBufAddLocation(buf_, location);
1809 }
1810 ++depth_;
Elliott Hughes530fa002012-03-12 11:44:49 -07001811 return true;
Elliott Hughes03181a82011-11-17 17:22:21 -08001812 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001813
1814 private:
1815 size_t depth_;
1816 const size_t start_frame_;
1817 const size_t frame_count_;
1818 JDWP::ExpandBuf* buf_;
Elliott Hughes03181a82011-11-17 17:22:21 -08001819 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001820
1821 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08001822 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001823 Thread* thread;
1824 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1825 if (error != JDWP::ERR_NONE) {
1826 return error;
1827 }
Elliott Hughesf15f4a02013-01-09 10:09:38 -08001828 if (!IsSuspendedForDebugger(soa, thread)) {
1829 return JDWP::ERR_THREAD_NOT_SUSPENDED;
1830 }
Ian Rogers7a22fa62013-01-23 12:16:16 -08001831 GetFrameVisitor visitor(thread, start_frame, frame_count, buf);
Ian Rogers0399dde2012-06-06 17:09:28 -07001832 visitor.WalkStack();
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001833 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001834}
1835
1836JDWP::ObjectId Dbg::GetThreadSelfId() {
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07001837 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogerscfaa4552012-11-26 21:00:08 -08001838 return gRegistry->Add(soa.Self()->GetPeer());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001839}
1840
Elliott Hughes475fc232011-10-25 15:00:35 -07001841void Dbg::SuspendVM() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001842 Runtime::Current()->GetThreadList()->SuspendAllForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001843}
1844
1845void Dbg::ResumeVM() {
Elliott Hughesc61a2672012-06-21 14:52:29 -07001846 Runtime::Current()->GetThreadList()->UndoDebuggerSuspensions();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001847}
1848
Elliott Hughes221229c2013-01-08 18:17:50 -08001849JDWP::JdwpError Dbg::SuspendThread(JDWP::ObjectId thread_id, bool request_suspension) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001850 ScopedLocalRef<jobject> peer(Thread::Current()->GetJniEnv(), NULL);
1851 {
1852 ScopedObjectAccess soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001853 peer.reset(soa.AddLocalReference<jobject>(gRegistry->Get<mirror::Object*>(thread_id)));
Elliott Hughes4e235312011-12-02 11:34:15 -08001854 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001855 if (peer.get() == NULL) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001856 return JDWP::ERR_THREAD_NOT_ALIVE;
1857 }
1858 // Suspend thread to build stack trace.
Elliott Hughesf327e072013-01-09 16:01:26 -08001859 bool timed_out;
1860 Thread* thread = Thread::SuspendForDebugger(peer.get(), request_suspension, &timed_out);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001861 if (thread != NULL) {
1862 return JDWP::ERR_NONE;
Elliott Hughesf327e072013-01-09 16:01:26 -08001863 } else if (timed_out) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001864 return JDWP::ERR_INTERNAL;
1865 } else {
1866 return JDWP::ERR_THREAD_NOT_ALIVE;
1867 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001868}
1869
Elliott Hughes221229c2013-01-08 18:17:50 -08001870void Dbg::ResumeThread(JDWP::ObjectId thread_id) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001871 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001872 mirror::Object* peer = gRegistry->Get<mirror::Object*>(thread_id);
jeffhaoa77f0f62012-12-05 17:19:31 -08001873 Thread* thread;
1874 {
1875 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
1876 thread = Thread::FromManagedThread(soa, peer);
1877 }
Elliott Hughes4e235312011-12-02 11:34:15 -08001878 if (thread == NULL) {
1879 LOG(WARNING) << "No such thread for resume: " << peer;
1880 return;
1881 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001882 bool needs_resume;
1883 {
Ian Rogers50b35e22012-10-04 10:09:15 -07001884 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001885 needs_resume = thread->GetSuspendCount() > 0;
1886 }
1887 if (needs_resume) {
Elliott Hughes546b9862012-06-20 16:06:13 -07001888 Runtime::Current()->GetThreadList()->Resume(thread, true);
1889 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001890}
1891
1892void Dbg::SuspendSelf() {
Elliott Hughes475fc232011-10-25 15:00:35 -07001893 Runtime::Current()->GetThreadList()->SuspendSelfForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001894}
1895
Ian Rogers0399dde2012-06-06 17:09:28 -07001896struct GetThisVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -08001897 GetThisVisitor(Thread* thread, Context* context, JDWP::FrameId frame_id)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001898 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08001899 : StackVisitor(thread, context), this_object(NULL), frame_id(frame_id) {}
Ian Rogers0399dde2012-06-06 17:09:28 -07001900
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001901 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1902 // annotalysis.
1903 virtual bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001904 if (frame_id != GetFrameId()) {
Ian Rogers0399dde2012-06-06 17:09:28 -07001905 return true; // continue
1906 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001907 mirror::AbstractMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07001908 if (m->IsNative() || m->IsStatic()) {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001909 this_object = NULL;
Ian Rogers0399dde2012-06-06 17:09:28 -07001910 } else {
1911 uint16_t reg = DemangleSlot(0, m);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001912 this_object = reinterpret_cast<mirror::Object*>(GetVReg(m, reg, kReferenceVReg));
Ian Rogers0399dde2012-06-06 17:09:28 -07001913 }
1914 return false;
Elliott Hughes86b00102011-12-05 17:54:26 -08001915 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001916
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001917 mirror::Object* this_object;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001918 JDWP::FrameId frame_id;
Ian Rogers0399dde2012-06-06 17:09:28 -07001919};
1920
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001921static mirror::Object* GetThis(Thread* self, mirror::AbstractMethod* m, size_t frame_id)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001922 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughescaf76542012-06-28 16:08:22 -07001923 // TODO: should we return the 'this' we passed through to non-static native methods?
Ian Rogers0399dde2012-06-06 17:09:28 -07001924 if (m->IsNative() || m->IsStatic()) {
1925 return NULL;
1926 }
Elliott Hughescaf76542012-06-28 16:08:22 -07001927
Ian Rogers0399dde2012-06-06 17:09:28 -07001928 UniquePtr<Context> context(Context::Create());
Ian Rogers7a22fa62013-01-23 12:16:16 -08001929 GetThisVisitor visitor(self, context.get(), frame_id);
Elliott Hughescaf76542012-06-28 16:08:22 -07001930 visitor.WalkStack();
1931 return visitor.this_object;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001932}
1933
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001934JDWP::JdwpError Dbg::GetThisObject(JDWP::ObjectId thread_id, JDWP::FrameId frame_id,
1935 JDWP::ObjectId* result) {
1936 ScopedObjectAccessUnchecked soa(Thread::Current());
1937 Thread* thread;
1938 {
Ian Rogers50b35e22012-10-04 10:09:15 -07001939 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001940 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1941 if (error != JDWP::ERR_NONE) {
1942 return error;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001943 }
Elliott Hughes9e0c1752013-01-09 14:02:58 -08001944 if (!IsSuspendedForDebugger(soa, thread)) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001945 return JDWP::ERR_THREAD_NOT_SUSPENDED;
1946 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001947 }
Elliott Hughescaf76542012-06-28 16:08:22 -07001948 UniquePtr<Context> context(Context::Create());
Ian Rogers7a22fa62013-01-23 12:16:16 -08001949 GetThisVisitor visitor(thread, context.get(), frame_id);
Ian Rogers0399dde2012-06-06 17:09:28 -07001950 visitor.WalkStack();
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001951 *result = gRegistry->Add(visitor.this_object);
1952 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001953}
1954
Elliott Hughes88d63092013-01-09 09:55:54 -08001955void Dbg::GetLocalValue(JDWP::ObjectId thread_id, JDWP::FrameId frame_id, int slot, JDWP::JdwpTag tag,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001956 uint8_t* buf, size_t width) {
Ian Rogers0399dde2012-06-06 17:09:28 -07001957 struct GetLocalVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -08001958 GetLocalVisitor(Thread* thread, Context* context, JDWP::FrameId frame_id, int slot,
1959 JDWP::JdwpTag tag, uint8_t* buf, size_t width)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001960 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08001961 : StackVisitor(thread, context), frame_id_(frame_id), slot_(slot), tag_(tag),
Ian Rogersca190662012-06-26 15:45:57 -07001962 buf_(buf), width_(width) {}
1963
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001964 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1965 // annotalysis.
1966 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07001967 if (GetFrameId() != frame_id_) {
1968 return true; // Not our frame, carry on.
Elliott Hughesdbb40792011-11-18 17:05:22 -08001969 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001970 // TODO: check that the tag is compatible with the actual type of the slot!
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001971 mirror::AbstractMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07001972 uint16_t reg = DemangleSlot(slot_, m);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001973
Ian Rogers0399dde2012-06-06 17:09:28 -07001974 switch (tag_) {
1975 case JDWP::JT_BOOLEAN:
1976 {
1977 CHECK_EQ(width_, 1U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001978 uint32_t intVal = GetVReg(m, reg, kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07001979 VLOG(jdwp) << "get boolean local " << reg << " = " << intVal;
1980 JDWP::Set1(buf_+1, intVal != 0);
1981 }
1982 break;
1983 case JDWP::JT_BYTE:
1984 {
1985 CHECK_EQ(width_, 1U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001986 uint32_t intVal = GetVReg(m, reg, kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07001987 VLOG(jdwp) << "get byte local " << reg << " = " << intVal;
1988 JDWP::Set1(buf_+1, intVal);
1989 }
1990 break;
1991 case JDWP::JT_SHORT:
1992 case JDWP::JT_CHAR:
1993 {
1994 CHECK_EQ(width_, 2U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001995 uint32_t intVal = GetVReg(m, reg, kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07001996 VLOG(jdwp) << "get short/char local " << reg << " = " << intVal;
1997 JDWP::Set2BE(buf_+1, intVal);
1998 }
1999 break;
2000 case JDWP::JT_INT:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002001 {
2002 CHECK_EQ(width_, 4U);
2003 uint32_t intVal = GetVReg(m, reg, kIntVReg);
2004 VLOG(jdwp) << "get int local " << reg << " = " << intVal;
2005 JDWP::Set4BE(buf_+1, intVal);
2006 }
2007 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002008 case JDWP::JT_FLOAT:
2009 {
2010 CHECK_EQ(width_, 4U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002011 uint32_t intVal = GetVReg(m, reg, kFloatVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002012 VLOG(jdwp) << "get int/float local " << reg << " = " << intVal;
2013 JDWP::Set4BE(buf_+1, intVal);
2014 }
2015 break;
2016 case JDWP::JT_ARRAY:
2017 {
2018 CHECK_EQ(width_, sizeof(JDWP::ObjectId));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002019 mirror::Object* o = reinterpret_cast<mirror::Object*>(GetVReg(m, reg, kReferenceVReg));
Ian Rogers0399dde2012-06-06 17:09:28 -07002020 VLOG(jdwp) << "get array local " << reg << " = " << o;
2021 if (!Runtime::Current()->GetHeap()->IsHeapAddress(o)) {
2022 LOG(FATAL) << "Register " << reg << " expected to hold array: " << o;
2023 }
2024 JDWP::SetObjectId(buf_+1, gRegistry->Add(o));
2025 }
2026 break;
2027 case JDWP::JT_CLASS_LOADER:
2028 case JDWP::JT_CLASS_OBJECT:
2029 case JDWP::JT_OBJECT:
2030 case JDWP::JT_STRING:
2031 case JDWP::JT_THREAD:
2032 case JDWP::JT_THREAD_GROUP:
2033 {
2034 CHECK_EQ(width_, sizeof(JDWP::ObjectId));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002035 mirror::Object* o = reinterpret_cast<mirror::Object*>(GetVReg(m, reg, kReferenceVReg));
Ian Rogers0399dde2012-06-06 17:09:28 -07002036 VLOG(jdwp) << "get object local " << reg << " = " << o;
2037 if (!Runtime::Current()->GetHeap()->IsHeapAddress(o)) {
2038 LOG(FATAL) << "Register " << reg << " expected to hold object: " << o;
2039 }
2040 tag_ = TagFromObject(o);
2041 JDWP::SetObjectId(buf_+1, gRegistry->Add(o));
2042 }
2043 break;
2044 case JDWP::JT_DOUBLE:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002045 {
2046 CHECK_EQ(width_, 8U);
2047 uint32_t lo = GetVReg(m, reg, kDoubleLoVReg);
2048 uint64_t hi = GetVReg(m, reg + 1, kDoubleHiVReg);
2049 uint64_t longVal = (hi << 32) | lo;
2050 VLOG(jdwp) << "get double/long local " << hi << ":" << lo << " = " << longVal;
2051 JDWP::Set8BE(buf_+1, longVal);
2052 }
2053 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002054 case JDWP::JT_LONG:
2055 {
2056 CHECK_EQ(width_, 8U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002057 uint32_t lo = GetVReg(m, reg, kLongLoVReg);
2058 uint64_t hi = GetVReg(m, reg + 1, kLongHiVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002059 uint64_t longVal = (hi << 32) | lo;
2060 VLOG(jdwp) << "get double/long local " << hi << ":" << lo << " = " << longVal;
2061 JDWP::Set8BE(buf_+1, longVal);
2062 }
2063 break;
2064 default:
2065 LOG(FATAL) << "Unknown tag " << tag_;
2066 break;
2067 }
2068
2069 // Prepend tag, which may have been updated.
2070 JDWP::Set1(buf_, tag_);
2071 return false;
2072 }
2073
2074 const JDWP::FrameId frame_id_;
2075 const int slot_;
2076 JDWP::JdwpTag tag_;
2077 uint8_t* const buf_;
2078 const size_t width_;
2079 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002080
2081 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08002082 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002083 Thread* thread;
2084 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
2085 if (error != JDWP::ERR_NONE) {
2086 return;
2087 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002088 UniquePtr<Context> context(Context::Create());
Ian Rogers7a22fa62013-01-23 12:16:16 -08002089 GetLocalVisitor visitor(thread, context.get(), frame_id, slot, tag, buf, width);
Ian Rogers0399dde2012-06-06 17:09:28 -07002090 visitor.WalkStack();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002091}
2092
Elliott Hughes88d63092013-01-09 09:55:54 -08002093void Dbg::SetLocalValue(JDWP::ObjectId thread_id, JDWP::FrameId frame_id, int slot, JDWP::JdwpTag tag,
Ian Rogers0399dde2012-06-06 17:09:28 -07002094 uint64_t value, size_t width) {
2095 struct SetLocalVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -08002096 SetLocalVisitor(Thread* thread, Context* context,
Ian Rogers0399dde2012-06-06 17:09:28 -07002097 JDWP::FrameId frame_id, int slot, JDWP::JdwpTag tag, uint64_t value,
Ian Rogersca190662012-06-26 15:45:57 -07002098 size_t width)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002099 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08002100 : StackVisitor(thread, context),
Elliott Hughes08fc03a2012-06-26 17:34:00 -07002101 frame_id_(frame_id), slot_(slot), tag_(tag), value_(value), width_(width) {}
Ian Rogersca190662012-06-26 15:45:57 -07002102
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002103 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2104 // annotalysis.
2105 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07002106 if (GetFrameId() != frame_id_) {
2107 return true; // Not our frame, carry on.
2108 }
2109 // TODO: check that the tag is compatible with the actual type of the slot!
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002110 mirror::AbstractMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07002111 uint16_t reg = DemangleSlot(slot_, m);
2112
2113 switch (tag_) {
2114 case JDWP::JT_BOOLEAN:
2115 case JDWP::JT_BYTE:
2116 CHECK_EQ(width_, 1U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002117 SetVReg(m, reg, static_cast<uint32_t>(value_), kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002118 break;
2119 case JDWP::JT_SHORT:
2120 case JDWP::JT_CHAR:
2121 CHECK_EQ(width_, 2U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002122 SetVReg(m, reg, static_cast<uint32_t>(value_), kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002123 break;
2124 case JDWP::JT_INT:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002125 CHECK_EQ(width_, 4U);
2126 SetVReg(m, reg, static_cast<uint32_t>(value_), kIntVReg);
2127 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002128 case JDWP::JT_FLOAT:
2129 CHECK_EQ(width_, 4U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002130 SetVReg(m, reg, static_cast<uint32_t>(value_), kFloatVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002131 break;
2132 case JDWP::JT_ARRAY:
2133 case JDWP::JT_OBJECT:
2134 case JDWP::JT_STRING:
2135 {
2136 CHECK_EQ(width_, sizeof(JDWP::ObjectId));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002137 mirror::Object* o = gRegistry->Get<mirror::Object*>(static_cast<JDWP::ObjectId>(value_));
Elliott Hughes64f574f2013-02-20 14:57:12 -08002138 if (o == ObjectRegistry::kInvalidObject) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002139 UNIMPLEMENTED(FATAL) << "return an error code when given an invalid object to store";
2140 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002141 SetVReg(m, reg, static_cast<uint32_t>(reinterpret_cast<uintptr_t>(o)), kReferenceVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002142 }
2143 break;
2144 case JDWP::JT_DOUBLE:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002145 CHECK_EQ(width_, 8U);
2146 SetVReg(m, reg, static_cast<uint32_t>(value_), kDoubleLoVReg);
2147 SetVReg(m, reg + 1, static_cast<uint32_t>(value_ >> 32), kDoubleHiVReg);
2148 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002149 case JDWP::JT_LONG:
2150 CHECK_EQ(width_, 8U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002151 SetVReg(m, reg, static_cast<uint32_t>(value_), kLongLoVReg);
2152 SetVReg(m, reg + 1, static_cast<uint32_t>(value_ >> 32), kLongHiVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002153 break;
2154 default:
2155 LOG(FATAL) << "Unknown tag " << tag_;
2156 break;
2157 }
2158 return false;
2159 }
2160
2161 const JDWP::FrameId frame_id_;
2162 const int slot_;
2163 const JDWP::JdwpTag tag_;
2164 const uint64_t value_;
2165 const size_t width_;
2166 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002167
2168 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08002169 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002170 Thread* thread;
2171 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
2172 if (error != JDWP::ERR_NONE) {
2173 return;
2174 }
Elliott Hughes08fc03a2012-06-26 17:34:00 -07002175 UniquePtr<Context> context(Context::Create());
Ian Rogers7a22fa62013-01-23 12:16:16 -08002176 SetLocalVisitor visitor(thread, context.get(), frame_id, slot, tag, value, width);
Ian Rogers0399dde2012-06-06 17:09:28 -07002177 visitor.WalkStack();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002178}
2179
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002180void Dbg::PostLocationEvent(const mirror::AbstractMethod* m, int dex_pc, mirror::Object* this_object, int event_flags) {
2181 mirror::Class* c = m->GetDeclaringClass();
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002182
2183 JDWP::JdwpLocation location;
Elliott Hughes74847412012-06-20 18:10:21 -07002184 location.type_tag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
Elliott Hughes64f574f2013-02-20 14:57:12 -08002185 location.class_id = gRegistry->AddRefType(c);
Elliott Hughes74847412012-06-20 18:10:21 -07002186 location.method_id = ToMethodId(m);
Elliott Hughes972a47b2012-02-21 18:16:06 -08002187 location.dex_pc = m->IsNative() ? -1 : dex_pc;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002188
Elliott Hughes64f574f2013-02-20 14:57:12 -08002189 // If 'this_object' isn't already in the registry, we know that we're not looking for it,
2190 // so there's no point adding it to the registry and burning through ids.
2191 JDWP::ObjectId this_id = 0;
2192 if (gRegistry->Contains(this_object)) {
2193 this_id = gRegistry->Add(this_object);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002194 }
Elliott Hughes64f574f2013-02-20 14:57:12 -08002195 gJdwpState->PostLocationEvent(&location, this_id, event_flags);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002196}
2197
Elliott Hughescaf76542012-06-28 16:08:22 -07002198void Dbg::PostException(Thread* thread,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002199 JDWP::FrameId throw_frame_id, mirror::AbstractMethod* throw_method,
2200 uint32_t throw_dex_pc, mirror::AbstractMethod* catch_method,
Elliott Hughes64f574f2013-02-20 14:57:12 -08002201 uint32_t catch_dex_pc, mirror::Throwable* exception_object) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002202 if (!IsDebuggerActive()) {
Ian Rogers0ad5bb82011-12-07 10:16:32 -08002203 return;
2204 }
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002205
Elliott Hughesd07986f2011-12-06 18:27:45 -08002206 JDWP::JdwpLocation throw_location;
Elliott Hughescaf76542012-06-28 16:08:22 -07002207 SetLocation(throw_location, throw_method, throw_dex_pc);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002208 JDWP::JdwpLocation catch_location;
Elliott Hughescaf76542012-06-28 16:08:22 -07002209 SetLocation(catch_location, catch_method, catch_dex_pc);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002210
2211 // We need 'this' for InstanceOnly filters.
Elliott Hughescaf76542012-06-28 16:08:22 -07002212 UniquePtr<Context> context(Context::Create());
Ian Rogers7a22fa62013-01-23 12:16:16 -08002213 GetThisVisitor visitor(thread, context.get(), throw_frame_id);
Elliott Hughescaf76542012-06-28 16:08:22 -07002214 visitor.WalkStack();
2215 JDWP::ObjectId this_id = gRegistry->Add(visitor.this_object);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002216
Elliott Hughes64f574f2013-02-20 14:57:12 -08002217 JDWP::ObjectId exception_id = gRegistry->Add(exception_object);
2218 JDWP::RefTypeId exception_class_id = gRegistry->AddRefType(exception_object->GetClass());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002219
2220 gJdwpState->PostException(&throw_location, exception_id, exception_class_id, &catch_location, this_id);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002221}
2222
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002223void Dbg::PostClassPrepare(mirror::Class* c) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002224 if (!IsDebuggerActive()) {
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002225 return;
2226 }
2227
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08002228 // OLD-TODO - we currently always send both "verified" and "prepared" since
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002229 // debuggers seem to like that. There might be some advantage to honesty,
2230 // since the class may not yet be verified.
2231 int state = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
2232 JDWP::JdwpTypeTag tag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
2233 gJdwpState->PostClassPrepare(tag, gRegistry->Add(c), ClassHelper(c).GetDescriptor(), state);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002234}
2235
Elliott Hughescaf76542012-06-28 16:08:22 -07002236void Dbg::UpdateDebugger(int32_t dex_pc, Thread* self) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002237 if (!IsDebuggerActive() || dex_pc == -2 /* fake method exit */) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002238 return;
2239 }
2240
Elliott Hughescaf76542012-06-28 16:08:22 -07002241 size_t frame_id;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002242 mirror::AbstractMethod* m = self->GetCurrentMethod(NULL, &frame_id);
Elliott Hughescaf76542012-06-28 16:08:22 -07002243 //LOG(INFO) << "UpdateDebugger " << PrettyMethod(m) << "@" << dex_pc << " frame " << frame_id;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002244
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002245 if (dex_pc == -1) {
Elliott Hughes2aa2e392012-02-17 17:15:43 -08002246 // We use a pc of -1 to represent method entry, since we might branch back to pc 0 later.
2247 // This means that for this special notification, there can't be anything else interesting
2248 // going on, so we're done already.
Elliott Hughescaf76542012-06-28 16:08:22 -07002249 Dbg::PostLocationEvent(m, 0, GetThis(self, m, frame_id), kMethodEntry);
Elliott Hughes2aa2e392012-02-17 17:15:43 -08002250 return;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002251 }
2252
Elliott Hughes2aa2e392012-02-17 17:15:43 -08002253 int event_flags = 0;
2254
Elliott Hughes86964332012-02-15 19:37:42 -08002255 if (IsBreakpoint(m, dex_pc)) {
2256 event_flags |= kBreakpoint;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002257 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002258
jeffhao09bfc6a2012-12-11 18:11:43 -08002259 {
2260 // If the debugger is single-stepping one of our threads, check to
2261 // see if we're that thread and we've reached a step point.
2262 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
2263 if (gSingleStepControl.is_active && gSingleStepControl.thread == self) {
2264 CHECK(!m->IsNative());
2265 if (gSingleStepControl.step_depth == JDWP::SD_INTO) {
2266 // Step into method calls. We break when the line number
2267 // or method pointer changes. If we're in SS_MIN mode, we
2268 // always stop.
2269 if (gSingleStepControl.method != m) {
2270 event_flags |= kSingleStep;
2271 VLOG(jdwp) << "SS new method";
2272 } else if (gSingleStepControl.step_size == JDWP::SS_MIN) {
Elliott Hughes86964332012-02-15 19:37:42 -08002273 event_flags |= kSingleStep;
2274 VLOG(jdwp) << "SS new instruction";
Elliott Hughes2435a572012-02-17 16:07:41 -08002275 } else if (gSingleStepControl.dex_pcs.find(dex_pc) == gSingleStepControl.dex_pcs.end()) {
2276 event_flags |= kSingleStep;
2277 VLOG(jdwp) << "SS new line";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002278 }
jeffhao09bfc6a2012-12-11 18:11:43 -08002279 } else if (gSingleStepControl.step_depth == JDWP::SD_OVER) {
2280 // Step over method calls. We break when the line number is
2281 // different and the frame depth is <= the original frame
2282 // depth. (We can't just compare on the method, because we
2283 // might get unrolled past it by an exception, and it's tricky
2284 // to identify recursion.)
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002285
jeffhao09bfc6a2012-12-11 18:11:43 -08002286 int stack_depth = GetStackDepth(self);
Elliott Hughes86964332012-02-15 19:37:42 -08002287
jeffhao09bfc6a2012-12-11 18:11:43 -08002288 if (stack_depth < gSingleStepControl.stack_depth) {
2289 // popped up one or more frames, always trigger
2290 event_flags |= kSingleStep;
2291 VLOG(jdwp) << "SS method pop";
2292 } else if (stack_depth == gSingleStepControl.stack_depth) {
2293 // same depth, see if we moved
2294 if (gSingleStepControl.step_size == JDWP::SS_MIN) {
2295 event_flags |= kSingleStep;
2296 VLOG(jdwp) << "SS new instruction";
2297 } else if (gSingleStepControl.dex_pcs.find(dex_pc) == gSingleStepControl.dex_pcs.end()) {
2298 event_flags |= kSingleStep;
2299 VLOG(jdwp) << "SS new line";
2300 }
2301 }
2302 } else {
2303 CHECK_EQ(gSingleStepControl.step_depth, JDWP::SD_OUT);
2304 // Return from the current method. We break when the frame
2305 // depth pops up.
2306
2307 // This differs from the "method exit" break in that it stops
2308 // with the PC at the next instruction in the returned-to
2309 // function, rather than the end of the returning function.
2310
2311 int stack_depth = GetStackDepth(self);
2312 if (stack_depth < gSingleStepControl.stack_depth) {
2313 event_flags |= kSingleStep;
2314 VLOG(jdwp) << "SS method pop";
2315 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002316 }
2317 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002318 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002319
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002320 // Check to see if this is a "return" instruction. JDWP says we should
2321 // send the event *after* the code has been executed, but it also says
2322 // the location we provide is the last instruction. Since the "return"
2323 // instruction has no interesting side effects, we should be safe.
2324 // (We can't just move this down to the returnFromMethod label because
2325 // we potentially need to combine it with other events.)
2326 // We're also not supposed to generate a method exit event if the method
2327 // terminates "with a thrown exception".
Elliott Hughes86964332012-02-15 19:37:42 -08002328 if (dex_pc >= 0) {
2329 const DexFile::CodeItem* code_item = MethodHelper(m).GetCodeItem();
Elliott Hughescaf76542012-06-28 16:08:22 -07002330 CHECK(code_item != NULL) << PrettyMethod(m) << " @" << dex_pc;
Elliott Hughes86964332012-02-15 19:37:42 -08002331 CHECK_LT(dex_pc, static_cast<int32_t>(code_item->insns_size_in_code_units_));
2332 if (Instruction::At(&code_item->insns_[dex_pc])->IsReturn()) {
2333 event_flags |= kMethodExit;
2334 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002335 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002336
2337 // If there's something interesting going on, see if it matches one
2338 // of the debugger filters.
2339 if (event_flags != 0) {
Elliott Hughescaf76542012-06-28 16:08:22 -07002340 Dbg::PostLocationEvent(m, dex_pc, GetThis(self, m, frame_id), event_flags);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002341 }
2342}
2343
Elliott Hughes86964332012-02-15 19:37:42 -08002344void Dbg::WatchLocation(const JDWP::JdwpLocation* location) {
jeffhao09bfc6a2012-12-11 18:11:43 -08002345 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002346 mirror::AbstractMethod* m = FromMethodId(location->method_id);
Elliott Hughes972a47b2012-02-21 18:16:06 -08002347 gBreakpoints.push_back(Breakpoint(m, location->dex_pc));
Elliott Hughes86964332012-02-15 19:37:42 -08002348 VLOG(jdwp) << "Set breakpoint #" << (gBreakpoints.size() - 1) << ": " << gBreakpoints[gBreakpoints.size() - 1];
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002349}
2350
Elliott Hughes86964332012-02-15 19:37:42 -08002351void Dbg::UnwatchLocation(const JDWP::JdwpLocation* location) {
jeffhao09bfc6a2012-12-11 18:11:43 -08002352 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002353 mirror::AbstractMethod* m = FromMethodId(location->method_id);
Elliott Hughes86964332012-02-15 19:37:42 -08002354 for (size_t i = 0; i < gBreakpoints.size(); ++i) {
Elliott Hughes972a47b2012-02-21 18:16:06 -08002355 if (gBreakpoints[i].method == m && gBreakpoints[i].dex_pc == location->dex_pc) {
Elliott Hughes86964332012-02-15 19:37:42 -08002356 VLOG(jdwp) << "Removed breakpoint #" << i << ": " << gBreakpoints[i];
2357 gBreakpoints.erase(gBreakpoints.begin() + i);
2358 return;
2359 }
2360 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002361}
2362
Elliott Hughes221229c2013-01-08 18:17:50 -08002363JDWP::JdwpError Dbg::ConfigureStep(JDWP::ObjectId thread_id, JDWP::JdwpStepSize step_size,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002364 JDWP::JdwpStepDepth step_depth) {
2365 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08002366 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002367 Thread* thread;
2368 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
2369 if (error != JDWP::ERR_NONE) {
2370 return error;
Elliott Hughes2435a572012-02-17 16:07:41 -08002371 }
Elliott Hughes86964332012-02-15 19:37:42 -08002372
jeffhao09bfc6a2012-12-11 18:11:43 -08002373 MutexLock mu2(soa.Self(), *Locks::breakpoint_lock_);
Elliott Hughes86964332012-02-15 19:37:42 -08002374 // TODO: there's no theoretical reason why we couldn't support single-stepping
2375 // of multiple threads at once, but we never did so historically.
2376 if (gSingleStepControl.thread != NULL && thread != gSingleStepControl.thread) {
2377 LOG(WARNING) << "single-step already active for " << *gSingleStepControl.thread
2378 << "; switching to " << *thread;
2379 }
2380
Elliott Hughes2435a572012-02-17 16:07:41 -08002381 //
2382 // Work out what Method* we're in, the current line number, and how deep the stack currently
2383 // is for step-out.
2384 //
2385
Ian Rogers0399dde2012-06-06 17:09:28 -07002386 struct SingleStepStackVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -08002387 SingleStepStackVisitor(Thread* thread)
jeffhao09bfc6a2012-12-11 18:11:43 -08002388 EXCLUSIVE_LOCKS_REQUIRED(Locks::breakpoint_lock_)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002389 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08002390 : StackVisitor(thread, NULL) {
Elliott Hughes86964332012-02-15 19:37:42 -08002391 gSingleStepControl.method = NULL;
2392 gSingleStepControl.stack_depth = 0;
2393 }
Ian Rogersca190662012-06-26 15:45:57 -07002394
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002395 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2396 // annotalysis.
2397 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
jeffhao09bfc6a2012-12-11 18:11:43 -08002398 Locks::breakpoint_lock_->AssertHeld(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002399 const mirror::AbstractMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07002400 if (!m->IsRuntimeMethod()) {
Elliott Hughes86964332012-02-15 19:37:42 -08002401 ++gSingleStepControl.stack_depth;
2402 if (gSingleStepControl.method == NULL) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002403 const mirror::DexCache* dex_cache = m->GetDeclaringClass()->GetDexCache();
Elliott Hughes2435a572012-02-17 16:07:41 -08002404 gSingleStepControl.method = m;
2405 gSingleStepControl.line_number = -1;
2406 if (dex_cache != NULL) {
Ian Rogers4445a7e2012-10-05 17:19:13 -07002407 const DexFile& dex_file = *dex_cache->GetDexFile();
Ian Rogers0399dde2012-06-06 17:09:28 -07002408 gSingleStepControl.line_number = dex_file.GetLineNumFromPC(m, GetDexPc());
Elliott Hughes2435a572012-02-17 16:07:41 -08002409 }
Elliott Hughes86964332012-02-15 19:37:42 -08002410 }
2411 }
Elliott Hughes530fa002012-03-12 11:44:49 -07002412 return true;
Elliott Hughes86964332012-02-15 19:37:42 -08002413 }
2414 };
Ian Rogers7a22fa62013-01-23 12:16:16 -08002415 SingleStepStackVisitor visitor(thread);
Ian Rogers0399dde2012-06-06 17:09:28 -07002416 visitor.WalkStack();
Elliott Hughes86964332012-02-15 19:37:42 -08002417
Elliott Hughes2435a572012-02-17 16:07:41 -08002418 //
2419 // Find the dex_pc values that correspond to the current line, for line-based single-stepping.
2420 //
2421
2422 struct DebugCallbackContext {
jeffhao09bfc6a2012-12-11 18:11:43 -08002423 DebugCallbackContext() EXCLUSIVE_LOCKS_REQUIRED(Locks::breakpoint_lock_) {
Elliott Hughes2435a572012-02-17 16:07:41 -08002424 last_pc_valid = false;
2425 last_pc = 0;
Elliott Hughes2435a572012-02-17 16:07:41 -08002426 }
2427
jeffhao09bfc6a2012-12-11 18:11:43 -08002428 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2429 // annotalysis.
2430 static bool Callback(void* raw_context, uint32_t address, uint32_t line_number) NO_THREAD_SAFETY_ANALYSIS {
2431 Locks::breakpoint_lock_->AssertHeld(Thread::Current());
Elliott Hughes2435a572012-02-17 16:07:41 -08002432 DebugCallbackContext* context = reinterpret_cast<DebugCallbackContext*>(raw_context);
2433 if (static_cast<int32_t>(line_number) == gSingleStepControl.line_number) {
2434 if (!context->last_pc_valid) {
2435 // Everything from this address until the next line change is ours.
2436 context->last_pc = address;
2437 context->last_pc_valid = true;
2438 }
2439 // Otherwise, if we're already in a valid range for this line,
2440 // just keep going (shouldn't really happen)...
2441 } else if (context->last_pc_valid) { // and the line number is new
2442 // Add everything from the last entry up until here to the set
2443 for (uint32_t dex_pc = context->last_pc; dex_pc < address; ++dex_pc) {
2444 gSingleStepControl.dex_pcs.insert(dex_pc);
2445 }
2446 context->last_pc_valid = false;
2447 }
2448 return false; // There may be multiple entries for any given line.
2449 }
2450
jeffhao09bfc6a2012-12-11 18:11:43 -08002451 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2452 // annotalysis.
2453 ~DebugCallbackContext() NO_THREAD_SAFETY_ANALYSIS {
2454 Locks::breakpoint_lock_->AssertHeld(Thread::Current());
Elliott Hughes2435a572012-02-17 16:07:41 -08002455 // If the line number was the last in the position table...
2456 if (last_pc_valid) {
2457 size_t end = MethodHelper(gSingleStepControl.method).GetCodeItem()->insns_size_in_code_units_;
2458 for (uint32_t dex_pc = last_pc; dex_pc < end; ++dex_pc) {
2459 gSingleStepControl.dex_pcs.insert(dex_pc);
2460 }
2461 }
2462 }
2463
2464 bool last_pc_valid;
2465 uint32_t last_pc;
2466 };
Elliott Hughes3e2e1a22012-02-21 11:33:41 -08002467 gSingleStepControl.dex_pcs.clear();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002468 const mirror::AbstractMethod* m = gSingleStepControl.method;
Elliott Hughes3e2e1a22012-02-21 11:33:41 -08002469 if (m->IsNative()) {
2470 gSingleStepControl.line_number = -1;
2471 } else {
2472 DebugCallbackContext context;
2473 MethodHelper mh(m);
2474 mh.GetDexFile().DecodeDebugInfo(mh.GetCodeItem(), m->IsStatic(), m->GetDexMethodIndex(),
2475 DebugCallbackContext::Callback, NULL, &context);
2476 }
Elliott Hughes2435a572012-02-17 16:07:41 -08002477
2478 //
2479 // Everything else...
2480 //
2481
Elliott Hughes86964332012-02-15 19:37:42 -08002482 gSingleStepControl.thread = thread;
2483 gSingleStepControl.step_size = step_size;
2484 gSingleStepControl.step_depth = step_depth;
2485 gSingleStepControl.is_active = true;
2486
Elliott Hughes2435a572012-02-17 16:07:41 -08002487 if (VLOG_IS_ON(jdwp)) {
2488 VLOG(jdwp) << "Single-step thread: " << *gSingleStepControl.thread;
2489 VLOG(jdwp) << "Single-step step size: " << gSingleStepControl.step_size;
2490 VLOG(jdwp) << "Single-step step depth: " << gSingleStepControl.step_depth;
2491 VLOG(jdwp) << "Single-step current method: " << PrettyMethod(gSingleStepControl.method);
2492 VLOG(jdwp) << "Single-step current line: " << gSingleStepControl.line_number;
2493 VLOG(jdwp) << "Single-step current stack depth: " << gSingleStepControl.stack_depth;
2494 VLOG(jdwp) << "Single-step dex_pc values:";
2495 for (std::set<uint32_t>::iterator it = gSingleStepControl.dex_pcs.begin() ; it != gSingleStepControl.dex_pcs.end(); ++it) {
Elliott Hughes229feb72012-02-23 13:33:29 -08002496 VLOG(jdwp) << StringPrintf(" %#x", *it);
Elliott Hughes2435a572012-02-17 16:07:41 -08002497 }
2498 }
2499
2500 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002501}
2502
Elliott Hughes221229c2013-01-08 18:17:50 -08002503void Dbg::UnconfigureStep(JDWP::ObjectId /*thread_id*/) {
jeffhao09bfc6a2012-12-11 18:11:43 -08002504 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Elliott Hughesf8349362012-06-18 15:00:06 -07002505
Elliott Hughes86964332012-02-15 19:37:42 -08002506 gSingleStepControl.is_active = false;
2507 gSingleStepControl.thread = NULL;
Elliott Hughes2435a572012-02-17 16:07:41 -08002508 gSingleStepControl.dex_pcs.clear();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002509}
2510
Elliott Hughes45651fd2012-02-21 15:48:20 -08002511static char JdwpTagToShortyChar(JDWP::JdwpTag tag) {
2512 switch (tag) {
2513 default:
2514 LOG(FATAL) << "unknown JDWP tag: " << PrintableChar(tag);
2515
2516 // Primitives.
2517 case JDWP::JT_BYTE: return 'B';
2518 case JDWP::JT_CHAR: return 'C';
2519 case JDWP::JT_FLOAT: return 'F';
2520 case JDWP::JT_DOUBLE: return 'D';
2521 case JDWP::JT_INT: return 'I';
2522 case JDWP::JT_LONG: return 'J';
2523 case JDWP::JT_SHORT: return 'S';
2524 case JDWP::JT_VOID: return 'V';
2525 case JDWP::JT_BOOLEAN: return 'Z';
2526
2527 // Reference types.
2528 case JDWP::JT_ARRAY:
2529 case JDWP::JT_OBJECT:
2530 case JDWP::JT_STRING:
2531 case JDWP::JT_THREAD:
2532 case JDWP::JT_THREAD_GROUP:
2533 case JDWP::JT_CLASS_LOADER:
2534 case JDWP::JT_CLASS_OBJECT:
2535 return 'L';
2536 }
2537}
2538
Elliott Hughes88d63092013-01-09 09:55:54 -08002539JDWP::JdwpError Dbg::InvokeMethod(JDWP::ObjectId thread_id, JDWP::ObjectId object_id,
2540 JDWP::RefTypeId class_id, JDWP::MethodId method_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002541 uint32_t arg_count, uint64_t* arg_values,
2542 JDWP::JdwpTag* arg_types, uint32_t options,
2543 JDWP::JdwpTag* pResultTag, uint64_t* pResultValue,
2544 JDWP::ObjectId* pExceptionId) {
Elliott Hughesd07986f2011-12-06 18:27:45 -08002545 ThreadList* thread_list = Runtime::Current()->GetThreadList();
2546
2547 Thread* targetThread = NULL;
2548 DebugInvokeReq* req = NULL;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002549 Thread* self = Thread::Current();
Elliott Hughesd07986f2011-12-06 18:27:45 -08002550 {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002551 ScopedObjectAccessUnchecked soa(self);
Ian Rogers50b35e22012-10-04 10:09:15 -07002552 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002553 JDWP::JdwpError error = DecodeThread(soa, thread_id, targetThread);
2554 if (error != JDWP::ERR_NONE) {
2555 LOG(ERROR) << "InvokeMethod request for invalid thread id " << thread_id;
2556 return error;
Elliott Hughesd07986f2011-12-06 18:27:45 -08002557 }
2558 req = targetThread->GetInvokeReq();
2559 if (!req->ready) {
2560 LOG(ERROR) << "InvokeMethod request for thread not stopped by event: " << *targetThread;
2561 return JDWP::ERR_INVALID_THREAD;
2562 }
2563
2564 /*
2565 * We currently have a bug where we don't successfully resume the
2566 * target thread if the suspend count is too deep. We're expected to
2567 * require one "resume" for each "suspend", but when asked to execute
2568 * a method we have to resume fully and then re-suspend it back to the
2569 * same level. (The easiest way to cause this is to type "suspend"
2570 * multiple times in jdb.)
2571 *
2572 * It's unclear what this means when the event specifies "resume all"
2573 * and some threads are suspended more deeply than others. This is
2574 * a rare problem, so for now we just prevent it from hanging forever
2575 * by rejecting the method invocation request. Without this, we will
2576 * be stuck waiting on a suspended thread.
2577 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002578 int suspend_count;
2579 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002580 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002581 suspend_count = targetThread->GetSuspendCount();
2582 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08002583 if (suspend_count > 1) {
2584 LOG(ERROR) << *targetThread << " suspend count too deep for method invocation: " << suspend_count;
2585 return JDWP::ERR_THREAD_SUSPENDED; // Probably not expected here.
2586 }
2587
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002588 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002589 mirror::Object* receiver = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08002590 if (receiver == ObjectRegistry::kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002591 return JDWP::ERR_INVALID_OBJECT;
2592 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002593
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002594 mirror::Object* thread = gRegistry->Get<mirror::Object*>(thread_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08002595 if (thread == ObjectRegistry::kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002596 return JDWP::ERR_INVALID_OBJECT;
2597 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002598 // TODO: check that 'thread' is actually a java.lang.Thread!
2599
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002600 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes45651fd2012-02-21 15:48:20 -08002601 if (c == NULL) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002602 return status;
2603 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002604
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002605 mirror::AbstractMethod* m = FromMethodId(method_id);
Elliott Hughes45651fd2012-02-21 15:48:20 -08002606 if (m->IsStatic() != (receiver == NULL)) {
2607 return JDWP::ERR_INVALID_METHODID;
2608 }
2609 if (m->IsStatic()) {
2610 if (m->GetDeclaringClass() != c) {
2611 return JDWP::ERR_INVALID_METHODID;
2612 }
2613 } else {
2614 if (!m->GetDeclaringClass()->IsAssignableFrom(c)) {
2615 return JDWP::ERR_INVALID_METHODID;
2616 }
2617 }
2618
2619 // Check the argument list matches the method.
2620 MethodHelper mh(m);
2621 if (mh.GetShortyLength() - 1 != arg_count) {
2622 return JDWP::ERR_ILLEGAL_ARGUMENT;
2623 }
2624 const char* shorty = mh.GetShorty();
2625 for (size_t i = 0; i < arg_count; ++i) {
2626 if (shorty[i + 1] != JdwpTagToShortyChar(arg_types[i])) {
2627 return JDWP::ERR_ILLEGAL_ARGUMENT;
2628 }
2629 }
2630
2631 req->receiver_ = receiver;
2632 req->thread_ = thread;
2633 req->class_ = c;
2634 req->method_ = m;
2635 req->arg_count_ = arg_count;
2636 req->arg_values_ = arg_values;
Elliott Hughesd07986f2011-12-06 18:27:45 -08002637 req->options_ = options;
2638 req->invoke_needed_ = true;
2639 }
2640
2641 // The fact that we've released the thread list lock is a bit risky --- if the thread goes
2642 // away we're sitting high and dry -- but we must release this before the ResumeAllThreads
2643 // call, and it's unwise to hold it during WaitForSuspend.
2644
2645 {
2646 /*
2647 * We change our (JDWP thread) status, which should be THREAD_RUNNING,
Elliott Hughes81ff3182012-03-23 20:35:56 -07002648 * so we can suspend for a GC if the invoke request causes us to
Elliott Hughesd07986f2011-12-06 18:27:45 -08002649 * run out of memory. It's also a good idea to change it before locking
2650 * the invokeReq mutex, although that should never be held for long.
2651 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002652 self->TransitionFromRunnableToSuspended(kWaitingForDebuggerSend);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002653
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002654 VLOG(jdwp) << " Transferring control to event thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002655 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002656 MutexLock mu(self, req->lock_);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002657
2658 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002659 VLOG(jdwp) << " Resuming all threads";
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002660 thread_list->UndoDebuggerSuspensions();
Elliott Hughesd07986f2011-12-06 18:27:45 -08002661 } else {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002662 VLOG(jdwp) << " Resuming event thread only";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002663 thread_list->Resume(targetThread, true);
2664 }
2665
2666 // Wait for the request to finish executing.
2667 while (req->invoke_needed_) {
Ian Rogersc604d732012-10-14 16:09:54 -07002668 req->cond_.Wait(self);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002669 }
2670 }
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002671 VLOG(jdwp) << " Control has returned from event thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002672
2673 /* wait for thread to re-suspend itself */
Elliott Hughes221229c2013-01-08 18:17:50 -08002674 SuspendThread(thread_id, false /* request_suspension */ );
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002675 self->TransitionFromSuspendedToRunnable();
Elliott Hughesd07986f2011-12-06 18:27:45 -08002676 }
2677
2678 /*
2679 * Suspend the threads. We waited for the target thread to suspend
2680 * itself, so all we need to do is suspend the others.
2681 *
2682 * The suspendAllThreads() call will double-suspend the event thread,
2683 * so we want to resume the target thread once to keep the books straight.
2684 */
2685 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002686 self->TransitionFromRunnableToSuspended(kWaitingForDebuggerSuspension);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002687 VLOG(jdwp) << " Suspending all threads";
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002688 thread_list->SuspendAllForDebugger();
2689 self->TransitionFromSuspendedToRunnable();
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002690 VLOG(jdwp) << " Resuming event thread to balance the count";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002691 thread_list->Resume(targetThread, true);
2692 }
2693
2694 // Copy the result.
2695 *pResultTag = req->result_tag;
2696 if (IsPrimitiveTag(req->result_tag)) {
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002697 *pResultValue = req->result_value.GetJ();
Elliott Hughesd07986f2011-12-06 18:27:45 -08002698 } else {
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002699 *pResultValue = gRegistry->Add(req->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002700 }
2701 *pExceptionId = req->exception;
2702 return req->error;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002703}
2704
2705void Dbg::ExecuteMethod(DebugInvokeReq* pReq) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002706 ScopedObjectAccess soa(Thread::Current());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002707
Elliott Hughes81ff3182012-03-23 20:35:56 -07002708 // We can be called while an exception is pending. We need
Elliott Hughesd07986f2011-12-06 18:27:45 -08002709 // to preserve that across the method invocation.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002710 SirtRef<mirror::Throwable> old_exception(soa.Self(), soa.Self()->GetException());
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002711 soa.Self()->ClearException();
Elliott Hughesd07986f2011-12-06 18:27:45 -08002712
2713 // Translate the method through the vtable, unless the debugger wants to suppress it.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002714 mirror::AbstractMethod* m = pReq->method_;
Elliott Hughesd07986f2011-12-06 18:27:45 -08002715 if ((pReq->options_ & JDWP::INVOKE_NONVIRTUAL) == 0 && pReq->receiver_ != NULL) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002716 mirror::AbstractMethod* actual_method = pReq->class_->FindVirtualMethodForVirtualOrInterface(pReq->method_);
Elliott Hughes45651fd2012-02-21 15:48:20 -08002717 if (actual_method != m) {
2718 VLOG(jdwp) << "ExecuteMethod translated " << PrettyMethod(m) << " to " << PrettyMethod(actual_method);
2719 m = actual_method;
2720 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08002721 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002722 VLOG(jdwp) << "ExecuteMethod " << PrettyMethod(m);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002723 CHECK(m != NULL);
2724
2725 CHECK_EQ(sizeof(jvalue), sizeof(uint64_t));
2726
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002727 LOG(INFO) << "self=" << soa.Self() << " pReq->receiver_=" << pReq->receiver_ << " m=" << m
2728 << " #" << pReq->arg_count_ << " " << pReq->arg_values_;
2729 pReq->result_value = InvokeWithJValues(soa, pReq->receiver_, m,
2730 reinterpret_cast<JValue*>(pReq->arg_values_));
Elliott Hughesd07986f2011-12-06 18:27:45 -08002731
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002732 pReq->exception = gRegistry->Add(soa.Self()->GetException());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002733 pReq->result_tag = BasicTagFromDescriptor(MethodHelper(m).GetShorty());
2734 if (pReq->exception != 0) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002735 mirror::Object* exc = soa.Self()->GetException();
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002736 VLOG(jdwp) << " JDWP invocation returning with exception=" << exc << " " << PrettyTypeOf(exc);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002737 soa.Self()->ClearException();
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002738 pReq->result_value.SetJ(0);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002739 } else if (pReq->result_tag == JDWP::JT_OBJECT) {
2740 /* if no exception thrown, examine object result more closely */
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002741 JDWP::JdwpTag new_tag = TagFromObject(pReq->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002742 if (new_tag != pReq->result_tag) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002743 VLOG(jdwp) << " JDWP promoted result from " << pReq->result_tag << " to " << new_tag;
Elliott Hughesd07986f2011-12-06 18:27:45 -08002744 pReq->result_tag = new_tag;
2745 }
2746
2747 /*
2748 * Register the object. We don't actually need an ObjectId yet,
2749 * but we do need to be sure that the GC won't move or discard the
2750 * object when we switch out of RUNNING. The ObjectId conversion
2751 * will add the object to the "do not touch" list.
2752 *
2753 * We can't use the "tracked allocation" mechanism here because
2754 * the object is going to be handed off to a different thread.
2755 */
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002756 gRegistry->Add(pReq->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002757 }
2758
2759 if (old_exception.get() != NULL) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002760 soa.Self()->SetException(old_exception.get());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002761 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002762}
2763
Elliott Hughesd07986f2011-12-06 18:27:45 -08002764/*
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002765 * "buf" contains a full JDWP packet, possibly with multiple chunks. We
2766 * need to process each, accumulate the replies, and ship the whole thing
2767 * back.
2768 *
2769 * Returns "true" if we have a reply. The reply buffer is newly allocated,
2770 * and includes the chunk type/length, followed by the data.
2771 *
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08002772 * OLD-TODO: we currently assume that the request and reply include a single
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002773 * chunk. If this becomes inconvenient we will need to adapt.
2774 */
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002775bool Dbg::DdmHandlePacket(const uint8_t* buf, int dataLen, uint8_t** pReplyBuf, int* pReplyLen) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002776 CHECK_GE(dataLen, 0);
2777
2778 Thread* self = Thread::Current();
2779 JNIEnv* env = self->GetJniEnv();
2780
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002781 // Create a byte[] corresponding to 'buf'.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002782 ScopedLocalRef<jbyteArray> dataArray(env, env->NewByteArray(dataLen));
2783 if (dataArray.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002784 LOG(WARNING) << "byte[] allocation failed: " << dataLen;
2785 env->ExceptionClear();
2786 return false;
2787 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002788 env->SetByteArrayRegion(dataArray.get(), 0, dataLen, reinterpret_cast<const jbyte*>(buf));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002789
2790 const int kChunkHdrLen = 8;
2791
2792 // Run through and find all chunks. [Currently just find the first.]
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002793 ScopedByteArrayRO contents(env, dataArray.get());
Elliott Hughesf7c3b662011-10-27 12:04:56 -07002794 jint type = JDWP::Get4BE(reinterpret_cast<const uint8_t*>(&contents[0]));
2795 jint length = JDWP::Get4BE(reinterpret_cast<const uint8_t*>(&contents[4]));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002796 jint offset = kChunkHdrLen;
2797 if (offset + length > dataLen) {
2798 LOG(WARNING) << StringPrintf("bad chunk found (len=%u pktLen=%d)", length, dataLen);
2799 return false;
2800 }
2801
2802 // Call "private static Chunk dispatch(int type, byte[] data, int offset, int length)".
Elliott Hugheseac76672012-05-24 21:56:51 -07002803 ScopedLocalRef<jobject> chunk(env, env->CallStaticObjectMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
2804 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_dispatch,
2805 type, dataArray.get(), offset, length));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002806 if (env->ExceptionCheck()) {
2807 LOG(INFO) << StringPrintf("Exception thrown by dispatcher for 0x%08x", type);
2808 env->ExceptionDescribe();
2809 env->ExceptionClear();
2810 return false;
2811 }
2812
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002813 if (chunk.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002814 return false;
2815 }
2816
2817 /*
2818 * Pull the pieces out of the chunk. We copy the results into a
2819 * newly-allocated buffer that the caller can free. We don't want to
2820 * continue using the Chunk object because nothing has a reference to it.
2821 *
2822 * We could avoid this by returning type/data/offset/length and having
2823 * the caller be aware of the object lifetime issues, but that
Elliott Hughes81ff3182012-03-23 20:35:56 -07002824 * integrates the JDWP code more tightly into the rest of the runtime, and doesn't work
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002825 * if we have responses for multiple chunks.
2826 *
2827 * So we're pretty much stuck with copying data around multiple times.
2828 */
Elliott Hugheseac76672012-05-24 21:56:51 -07002829 ScopedLocalRef<jbyteArray> replyData(env, reinterpret_cast<jbyteArray>(env->GetObjectField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_data)));
2830 length = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_length);
2831 offset = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_offset);
2832 type = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_type);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002833
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002834 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 -07002835 if (length == 0 || replyData.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002836 return false;
2837 }
2838
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002839 jsize replyLength = env->GetArrayLength(replyData.get());
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002840 if (offset + length > replyLength) {
2841 LOG(WARNING) << StringPrintf("chunk off=%d len=%d exceeds reply array len %d", offset, length, replyLength);
2842 return false;
2843 }
2844
2845 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 Hughesba8eee12012-01-24 20:25:24 -08002857 VLOG(jdwp) << StringPrintf("dvmHandleDdm returning type=%.4s buf=%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