blob: 09c930a3745b557257b81f94b3ed4c27bd7789ab [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"
Jeff Hao5d917302013-02-27 17:57:33 -080029#include "invoke_arg_array_builder.h"
Elliott Hughes64f574f2013-02-20 14:57:12 -080030#include "jdwp/object_registry.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080031#include "mirror/abstract_method-inl.h"
32#include "mirror/class.h"
33#include "mirror/class-inl.h"
34#include "mirror/class_loader.h"
35#include "mirror/field-inl.h"
36#include "mirror/object-inl.h"
37#include "mirror/object_array-inl.h"
38#include "mirror/throwable.h"
Ian Rogers2bcb4a42012-11-08 10:39:18 -080039#include "oat/runtime/context.h"
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080040#include "object_utils.h"
Elliott Hughesa0e18062012-04-13 15:59:59 -070041#include "safe_map.h"
Elliott Hughes64f574f2013-02-20 14:57:12 -080042#include "scoped_thread_state_change.h"
Elliott Hughes6a5bd492011-10-28 14:33:57 -070043#include "ScopedLocalRef.h"
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -070044#include "ScopedPrimitiveArray.h"
Ian Rogers1f539342012-10-03 21:09:42 -070045#include "sirt_ref.h"
Elliott Hughes47fce012011-10-25 18:37:19 -070046#include "stack_indirect_reference_table.h"
Elliott Hughes475fc232011-10-25 15:00:35 -070047#include "thread_list.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080048#include "utf.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070049#include "well_known_classes.h"
Elliott Hughes475fc232011-10-25 15:00:35 -070050
Elliott Hughes872d4ec2011-10-21 17:07:15 -070051namespace art {
52
Elliott Hughes545a0642011-11-08 19:10:03 -080053static const size_t kMaxAllocRecordStackDepth = 16; // Max 255.
Elliott Hughes64f574f2013-02-20 14:57:12 -080054static const size_t kNumAllocRecords = 512; // Must be a power of 2.
Elliott Hughes475fc232011-10-25 15:00:35 -070055
Elliott Hughes545a0642011-11-08 19:10:03 -080056struct AllocRecordStackTraceElement {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080057 mirror::AbstractMethod* method;
Ian Rogers0399dde2012-06-06 17:09:28 -070058 uint32_t dex_pc;
Elliott Hughes545a0642011-11-08 19:10:03 -080059
Ian Rogersb726dcb2012-09-05 08:57:23 -070060 int32_t LineNumber() const SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers0399dde2012-06-06 17:09:28 -070061 return MethodHelper(method).GetLineNumFromDexPC(dex_pc);
Elliott Hughes545a0642011-11-08 19:10:03 -080062 }
63};
64
65struct AllocRecord {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080066 mirror::Class* type;
Elliott Hughes545a0642011-11-08 19:10:03 -080067 size_t byte_count;
68 uint16_t thin_lock_id;
69 AllocRecordStackTraceElement stack[kMaxAllocRecordStackDepth]; // Unused entries have NULL method.
70
71 size_t GetDepth() {
72 size_t depth = 0;
73 while (depth < kMaxAllocRecordStackDepth && stack[depth].method != NULL) {
74 ++depth;
75 }
76 return depth;
77 }
78};
79
Elliott Hughes86964332012-02-15 19:37:42 -080080struct Breakpoint {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080081 mirror::AbstractMethod* method;
Elliott Hughesa656a0f2012-02-21 18:03:44 -080082 uint32_t dex_pc;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080083 Breakpoint(mirror::AbstractMethod* method, uint32_t dex_pc) : method(method), dex_pc(dex_pc) {}
Elliott Hughes86964332012-02-15 19:37:42 -080084};
85
Ian Rogers00f7d0e2012-07-19 15:28:27 -070086static std::ostream& operator<<(std::ostream& os, const Breakpoint& rhs)
Ian Rogersb726dcb2012-09-05 08:57:23 -070087 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes229feb72012-02-23 13:33:29 -080088 os << StringPrintf("Breakpoint[%s @%#x]", PrettyMethod(rhs.method).c_str(), rhs.dex_pc);
Elliott Hughes86964332012-02-15 19:37:42 -080089 return os;
90}
91
92struct SingleStepControl {
93 // Are we single-stepping right now?
94 bool is_active;
95 Thread* thread;
96
97 JDWP::JdwpStepSize step_size;
98 JDWP::JdwpStepDepth step_depth;
99
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800100 const mirror::AbstractMethod* method;
Elliott Hughes2435a572012-02-17 16:07:41 -0800101 int32_t line_number; // Or -1 for native methods.
102 std::set<uint32_t> dex_pcs;
Elliott Hughes86964332012-02-15 19:37:42 -0800103 int stack_depth;
104};
105
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700106// JDWP is allowed unless the Zygote forbids it.
107static bool gJdwpAllowed = true;
108
Elliott Hughesc0f09332012-03-26 13:27:06 -0700109// Was there a -Xrunjdwp or -agentlib:jdwp= argument on the command line?
Elliott Hughes3bb81562011-10-21 18:52:59 -0700110static bool gJdwpConfigured = false;
111
Elliott Hughesc0f09332012-03-26 13:27:06 -0700112// Broken-down JDWP options. (Only valid if IsJdwpConfigured() is true.)
Elliott Hughes376a7a02011-10-24 18:35:55 -0700113static JDWP::JdwpOptions gJdwpOptions;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700114
115// Runtime JDWP state.
116static JDWP::JdwpState* gJdwpState = NULL;
117static bool gDebuggerConnected; // debugger or DDMS is connected.
118static bool gDebuggerActive; // debugger is making requests.
Elliott Hughes86964332012-02-15 19:37:42 -0800119static bool gDisposed; // debugger called VirtualMachine.Dispose, so we should drop the connection.
Elliott Hughes3bb81562011-10-21 18:52:59 -0700120
Elliott Hughes47fce012011-10-25 18:37:19 -0700121static bool gDdmThreadNotification = false;
122
Elliott Hughes767a1472011-10-26 18:49:02 -0700123// DDMS GC-related settings.
124static Dbg::HpifWhen gDdmHpifWhen = Dbg::HPIF_WHEN_NEVER;
125static Dbg::HpsgWhen gDdmHpsgWhen = Dbg::HPSG_WHEN_NEVER;
126static Dbg::HpsgWhat gDdmHpsgWhat;
127static Dbg::HpsgWhen gDdmNhsgWhen = Dbg::HPSG_WHEN_NEVER;
128static Dbg::HpsgWhat gDdmNhsgWhat;
129
Elliott Hughes475fc232011-10-25 15:00:35 -0700130static ObjectRegistry* gRegistry = NULL;
131
Elliott Hughes545a0642011-11-08 19:10:03 -0800132// Recent allocation tracking.
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700133static Mutex gAllocTrackerLock DEFAULT_MUTEX_ACQUIRED_AFTER ("AllocTracker lock");
Elliott Hughesf8349362012-06-18 15:00:06 -0700134AllocRecord* Dbg::recent_allocation_records_ PT_GUARDED_BY(gAllocTrackerLock) = NULL; // TODO: CircularBuffer<AllocRecord>
135static size_t gAllocRecordHead GUARDED_BY(gAllocTrackerLock) = 0;
136static size_t gAllocRecordCount GUARDED_BY(gAllocTrackerLock) = 0;
Elliott Hughes545a0642011-11-08 19:10:03 -0800137
Elliott Hughes86964332012-02-15 19:37:42 -0800138// Breakpoints and single-stepping.
jeffhao09bfc6a2012-12-11 18:11:43 -0800139static std::vector<Breakpoint> gBreakpoints GUARDED_BY(Locks::breakpoint_lock_);
140static SingleStepControl gSingleStepControl GUARDED_BY(Locks::breakpoint_lock_);
Elliott Hughes86964332012-02-15 19:37:42 -0800141
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800142static bool IsBreakpoint(mirror::AbstractMethod* m, uint32_t dex_pc)
jeffhao09bfc6a2012-12-11 18:11:43 -0800143 LOCKS_EXCLUDED(Locks::breakpoint_lock_)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700144 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
jeffhao09bfc6a2012-12-11 18:11:43 -0800145 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Elliott Hughes86964332012-02-15 19:37:42 -0800146 for (size_t i = 0; i < gBreakpoints.size(); ++i) {
Elliott Hughesa656a0f2012-02-21 18:03:44 -0800147 if (gBreakpoints[i].method == m && gBreakpoints[i].dex_pc == dex_pc) {
Elliott Hughes86964332012-02-15 19:37:42 -0800148 VLOG(jdwp) << "Hit breakpoint #" << i << ": " << gBreakpoints[i];
149 return true;
150 }
151 }
152 return false;
153}
154
Elliott Hughes9e0c1752013-01-09 14:02:58 -0800155static bool IsSuspendedForDebugger(ScopedObjectAccessUnchecked& soa, Thread* thread) {
156 MutexLock mu(soa.Self(), *Locks::thread_suspend_count_lock_);
157 // A thread may be suspended for GC; in this code, we really want to know whether
158 // there's a debugger suspension active.
159 return thread->IsSuspended() && thread->GetDebugSuspendCount() > 0;
160}
161
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800162static mirror::Array* DecodeArray(JDWP::RefTypeId id, JDWP::JdwpError& status)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700163 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800164 mirror::Object* o = gRegistry->Get<mirror::Object*>(id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800165 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800166 status = JDWP::ERR_INVALID_OBJECT;
167 return NULL;
168 }
169 if (!o->IsArrayInstance()) {
170 status = JDWP::ERR_INVALID_ARRAY;
171 return NULL;
172 }
173 status = JDWP::ERR_NONE;
174 return o->AsArray();
175}
176
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800177static mirror::Class* DecodeClass(JDWP::RefTypeId id, JDWP::JdwpError& status)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700178 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800179 mirror::Object* o = gRegistry->Get<mirror::Object*>(id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800180 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800181 status = JDWP::ERR_INVALID_OBJECT;
182 return NULL;
183 }
184 if (!o->IsClass()) {
185 status = JDWP::ERR_INVALID_CLASS;
186 return NULL;
187 }
188 status = JDWP::ERR_NONE;
189 return o->AsClass();
190}
191
Elliott Hughes221229c2013-01-08 18:17:50 -0800192static JDWP::JdwpError DecodeThread(ScopedObjectAccessUnchecked& soa, JDWP::ObjectId thread_id, Thread*& thread)
jeffhaoa77f0f62012-12-05 17:19:31 -0800193 EXCLUSIVE_LOCKS_REQUIRED(Locks::thread_list_lock_)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700194 LOCKS_EXCLUDED(Locks::thread_suspend_count_lock_)
195 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800196 mirror::Object* thread_peer = gRegistry->Get<mirror::Object*>(thread_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800197 if (thread_peer == NULL || thread_peer == ObjectRegistry::kInvalidObject) {
Elliott Hughes221229c2013-01-08 18:17:50 -0800198 // This isn't even an object.
199 return JDWP::ERR_INVALID_OBJECT;
Elliott Hughes436e3722012-02-17 20:01:47 -0800200 }
Elliott Hughes221229c2013-01-08 18:17:50 -0800201
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800202 mirror::Class* java_lang_Thread = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_Thread);
Elliott Hughes221229c2013-01-08 18:17:50 -0800203 if (!java_lang_Thread->IsAssignableFrom(thread_peer->GetClass())) {
204 // This isn't a thread.
205 return JDWP::ERR_INVALID_THREAD;
206 }
207
208 thread = Thread::FromManagedThread(soa, thread_peer);
209 if (thread == NULL) {
210 // This is a java.lang.Thread without a Thread*. Must be a zombie.
211 return JDWP::ERR_THREAD_NOT_ALIVE;
212 }
213 return JDWP::ERR_NONE;
Elliott Hughes436e3722012-02-17 20:01:47 -0800214}
215
Elliott Hughes24437992011-11-30 14:49:33 -0800216static JDWP::JdwpTag BasicTagFromDescriptor(const char* descriptor) {
217 // JDWP deliberately uses the descriptor characters' ASCII values for its enum.
218 // Note that by "basic" we mean that we don't get more specific than JT_OBJECT.
219 return static_cast<JDWP::JdwpTag>(descriptor[0]);
220}
221
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800222static JDWP::JdwpTag TagFromClass(mirror::Class* c)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700223 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes86b00102011-12-05 17:54:26 -0800224 CHECK(c != NULL);
Elliott Hughes24437992011-11-30 14:49:33 -0800225 if (c->IsArrayClass()) {
226 return JDWP::JT_ARRAY;
227 }
228
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800229 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Elliott Hughes24437992011-11-30 14:49:33 -0800230 if (c->IsStringClass()) {
231 return JDWP::JT_STRING;
232 } else if (c->IsClassClass()) {
233 return JDWP::JT_CLASS_OBJECT;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800234 } else if (class_linker->FindSystemClass("Ljava/lang/Thread;")->IsAssignableFrom(c)) {
Elliott Hughes24437992011-11-30 14:49:33 -0800235 return JDWP::JT_THREAD;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800236 } else if (class_linker->FindSystemClass("Ljava/lang/ThreadGroup;")->IsAssignableFrom(c)) {
Elliott Hughes24437992011-11-30 14:49:33 -0800237 return JDWP::JT_THREAD_GROUP;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800238 } else if (class_linker->FindSystemClass("Ljava/lang/ClassLoader;")->IsAssignableFrom(c)) {
Elliott Hughes24437992011-11-30 14:49:33 -0800239 return JDWP::JT_CLASS_LOADER;
Elliott Hughes24437992011-11-30 14:49:33 -0800240 } else {
241 return JDWP::JT_OBJECT;
242 }
243}
244
245/*
246 * Objects declared to hold Object might actually hold a more specific
247 * type. The debugger may take a special interest in these (e.g. it
248 * wants to display the contents of Strings), so we want to return an
249 * appropriate tag.
250 *
251 * Null objects are tagged JT_OBJECT.
252 */
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800253static JDWP::JdwpTag TagFromObject(const mirror::Object* o)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700254 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes24437992011-11-30 14:49:33 -0800255 return (o == NULL) ? JDWP::JT_OBJECT : TagFromClass(o->GetClass());
256}
257
258static bool IsPrimitiveTag(JDWP::JdwpTag tag) {
259 switch (tag) {
260 case JDWP::JT_BOOLEAN:
261 case JDWP::JT_BYTE:
262 case JDWP::JT_CHAR:
263 case JDWP::JT_FLOAT:
264 case JDWP::JT_DOUBLE:
265 case JDWP::JT_INT:
266 case JDWP::JT_LONG:
267 case JDWP::JT_SHORT:
268 case JDWP::JT_VOID:
269 return true;
270 default:
271 return false;
272 }
273}
274
Elliott Hughes3bb81562011-10-21 18:52:59 -0700275/*
276 * Handle one of the JDWP name/value pairs.
277 *
278 * JDWP options are:
279 * help: if specified, show help message and bail
280 * transport: may be dt_socket or dt_shmem
281 * address: for dt_socket, "host:port", or just "port" when listening
282 * server: if "y", wait for debugger to attach; if "n", attach to debugger
283 * timeout: how long to wait for debugger to connect / listen
284 *
285 * Useful with server=n (these aren't supported yet):
286 * onthrow=<exception-name>: connect to debugger when exception thrown
287 * onuncaught=y|n: connect to debugger when uncaught exception thrown
288 * launch=<command-line>: launch the debugger itself
289 *
290 * The "transport" option is required, as is "address" if server=n.
291 */
292static bool ParseJdwpOption(const std::string& name, const std::string& value) {
293 if (name == "transport") {
294 if (value == "dt_socket") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700295 gJdwpOptions.transport = JDWP::kJdwpTransportSocket;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700296 } else if (value == "dt_android_adb") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700297 gJdwpOptions.transport = JDWP::kJdwpTransportAndroidAdb;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700298 } else {
299 LOG(ERROR) << "JDWP transport not supported: " << value;
300 return false;
301 }
302 } else if (name == "server") {
303 if (value == "n") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700304 gJdwpOptions.server = false;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700305 } else if (value == "y") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700306 gJdwpOptions.server = true;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700307 } else {
308 LOG(ERROR) << "JDWP option 'server' must be 'y' or 'n'";
309 return false;
310 }
311 } else if (name == "suspend") {
312 if (value == "n") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700313 gJdwpOptions.suspend = false;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700314 } else if (value == "y") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700315 gJdwpOptions.suspend = true;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700316 } else {
317 LOG(ERROR) << "JDWP option 'suspend' must be 'y' or 'n'";
318 return false;
319 }
320 } else if (name == "address") {
321 /* this is either <port> or <host>:<port> */
322 std::string port_string;
Elliott Hughes376a7a02011-10-24 18:35:55 -0700323 gJdwpOptions.host.clear();
Elliott Hughes3bb81562011-10-21 18:52:59 -0700324 std::string::size_type colon = value.find(':');
325 if (colon != std::string::npos) {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700326 gJdwpOptions.host = value.substr(0, colon);
Elliott Hughes3bb81562011-10-21 18:52:59 -0700327 port_string = value.substr(colon + 1);
328 } else {
329 port_string = value;
330 }
331 if (port_string.empty()) {
332 LOG(ERROR) << "JDWP address missing port: " << value;
333 return false;
334 }
335 char* end;
Elliott Hughesba8eee12012-01-24 20:25:24 -0800336 uint64_t port = strtoul(port_string.c_str(), &end, 10);
337 if (*end != '\0' || port > 0xffff) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700338 LOG(ERROR) << "JDWP address has junk in port field: " << value;
339 return false;
340 }
Elliott Hughes376a7a02011-10-24 18:35:55 -0700341 gJdwpOptions.port = port;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700342 } else if (name == "launch" || name == "onthrow" || name == "oncaught" || name == "timeout") {
343 /* valid but unsupported */
344 LOG(INFO) << "Ignoring JDWP option '" << name << "'='" << value << "'";
345 } else {
346 LOG(INFO) << "Ignoring unrecognized JDWP option '" << name << "'='" << value << "'";
347 }
348
349 return true;
350}
351
352/*
353 * Parse the latter half of a -Xrunjdwp/-agentlib:jdwp= string, e.g.:
354 * "transport=dt_socket,address=8000,server=y,suspend=n"
355 */
356bool Dbg::ParseJdwpOptions(const std::string& options) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800357 VLOG(jdwp) << "ParseJdwpOptions: " << options;
Elliott Hughes47fce012011-10-25 18:37:19 -0700358
Elliott Hughes3bb81562011-10-21 18:52:59 -0700359 std::vector<std::string> pairs;
360 Split(options, ',', pairs);
361
362 for (size_t i = 0; i < pairs.size(); ++i) {
363 std::string::size_type equals = pairs[i].find('=');
364 if (equals == std::string::npos) {
365 LOG(ERROR) << "Can't parse JDWP option '" << pairs[i] << "' in '" << options << "'";
366 return false;
367 }
368 ParseJdwpOption(pairs[i].substr(0, equals), pairs[i].substr(equals + 1));
369 }
370
Elliott Hughes376a7a02011-10-24 18:35:55 -0700371 if (gJdwpOptions.transport == JDWP::kJdwpTransportUnknown) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700372 LOG(ERROR) << "Must specify JDWP transport: " << options;
373 }
Elliott Hughes376a7a02011-10-24 18:35:55 -0700374 if (!gJdwpOptions.server && (gJdwpOptions.host.empty() || gJdwpOptions.port == 0)) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700375 LOG(ERROR) << "Must specify JDWP host and port when server=n: " << options;
376 return false;
377 }
378
379 gJdwpConfigured = true;
380 return true;
381}
382
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700383void Dbg::StartJdwp() {
Elliott Hughesc0f09332012-03-26 13:27:06 -0700384 if (!gJdwpAllowed || !IsJdwpConfigured()) {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700385 // No JDWP for you!
386 return;
387 }
388
Elliott Hughes475fc232011-10-25 15:00:35 -0700389 CHECK(gRegistry == NULL);
390 gRegistry = new ObjectRegistry;
391
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700392 // Init JDWP if the debugger is enabled. This may connect out to a
393 // debugger, passively listen for a debugger, or block waiting for a
394 // debugger.
Elliott Hughes376a7a02011-10-24 18:35:55 -0700395 gJdwpState = JDWP::JdwpState::Create(&gJdwpOptions);
396 if (gJdwpState == NULL) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -0800397 // We probably failed because some other process has the port already, which means that
398 // if we don't abort the user is likely to think they're talking to us when they're actually
399 // talking to that other process.
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800400 LOG(FATAL) << "Debugger thread failed to initialize";
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700401 }
402
403 // If a debugger has already attached, send the "welcome" message.
404 // This may cause us to suspend all threads.
Elliott Hughes376a7a02011-10-24 18:35:55 -0700405 if (gJdwpState->IsActive()) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700406 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes376a7a02011-10-24 18:35:55 -0700407 if (!gJdwpState->PostVMStart()) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800408 LOG(WARNING) << "Failed to post 'start' message to debugger";
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700409 }
410 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700411}
412
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700413void Dbg::StopJdwp() {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700414 delete gJdwpState;
Elliott Hughes475fc232011-10-25 15:00:35 -0700415 delete gRegistry;
416 gRegistry = NULL;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700417}
418
Elliott Hughes767a1472011-10-26 18:49:02 -0700419void Dbg::GcDidFinish() {
420 if (gDdmHpifWhen != HPIF_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700421 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes81ff3182012-03-23 20:35:56 -0700422 LOG(DEBUG) << "Sending heap info to DDM";
Elliott Hughes7162ad92011-10-27 14:08:42 -0700423 DdmSendHeapInfo(gDdmHpifWhen);
Elliott Hughes767a1472011-10-26 18:49:02 -0700424 }
425 if (gDdmHpsgWhen != HPSG_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700426 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes81ff3182012-03-23 20:35:56 -0700427 LOG(DEBUG) << "Dumping heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700428 DdmSendHeapSegments(false);
Elliott Hughes767a1472011-10-26 18:49:02 -0700429 }
430 if (gDdmNhsgWhen != HPSG_WHEN_NEVER) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700431 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes767a1472011-10-26 18:49:02 -0700432 LOG(DEBUG) << "Dumping native heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700433 DdmSendHeapSegments(true);
Elliott Hughes767a1472011-10-26 18:49:02 -0700434 }
435}
436
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700437void Dbg::SetJdwpAllowed(bool allowed) {
438 gJdwpAllowed = allowed;
439}
440
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700441DebugInvokeReq* Dbg::GetInvokeReq() {
Elliott Hughes475fc232011-10-25 15:00:35 -0700442 return Thread::Current()->GetInvokeReq();
443}
444
445Thread* Dbg::GetDebugThread() {
446 return (gJdwpState != NULL) ? gJdwpState->GetDebugThread() : NULL;
447}
448
449void Dbg::ClearWaitForEventThread() {
450 gJdwpState->ClearWaitForEventThread();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700451}
452
453void Dbg::Connected() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700454 CHECK(!gDebuggerConnected);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800455 VLOG(jdwp) << "JDWP has attached";
Elliott Hughes3bb81562011-10-21 18:52:59 -0700456 gDebuggerConnected = true;
Elliott Hughes86964332012-02-15 19:37:42 -0800457 gDisposed = false;
458}
459
460void Dbg::Disposed() {
461 gDisposed = true;
462}
463
464bool Dbg::IsDisposed() {
465 return gDisposed;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700466}
467
Elliott Hughesc0f09332012-03-26 13:27:06 -0700468static void SetDebuggerUpdatesEnabledCallback(Thread* t, void* user_data) {
469 t->SetDebuggerUpdatesEnabled(*reinterpret_cast<bool*>(user_data));
470}
471
472static void SetDebuggerUpdatesEnabled(bool enabled) {
Ian Rogers50b35e22012-10-04 10:09:15 -0700473 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
Elliott Hughesf8349362012-06-18 15:00:06 -0700474 Runtime::Current()->GetThreadList()->ForEach(SetDebuggerUpdatesEnabledCallback, &enabled);
Elliott Hughesc0f09332012-03-26 13:27:06 -0700475}
476
Elliott Hughesa2155262011-11-16 16:26:58 -0800477void Dbg::GoActive() {
478 // Enable all debugging features, including scans for breakpoints.
479 // This is a no-op if we're already active.
480 // Only called from the JDWP handler thread.
481 if (gDebuggerActive) {
482 return;
483 }
484
485 LOG(INFO) << "Debugger is active";
486
Elliott Hughesc0f09332012-03-26 13:27:06 -0700487 {
488 // TODO: dalvik only warned if there were breakpoints left over. clear in Dbg::Disconnected?
jeffhao09bfc6a2012-12-11 18:11:43 -0800489 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Elliott Hughesc0f09332012-03-26 13:27:06 -0700490 CHECK_EQ(gBreakpoints.size(), 0U);
491 }
Elliott Hughesa2155262011-11-16 16:26:58 -0800492
493 gDebuggerActive = true;
Elliott Hughesc0f09332012-03-26 13:27:06 -0700494 SetDebuggerUpdatesEnabled(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700495}
496
497void Dbg::Disconnected() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700498 CHECK(gDebuggerConnected);
499
Elliott Hughesc0f09332012-03-26 13:27:06 -0700500 LOG(INFO) << "Debugger is no longer active";
Elliott Hughes234ab152011-10-26 14:02:26 -0700501
Elliott Hughesc0f09332012-03-26 13:27:06 -0700502 gDebuggerActive = false;
503 SetDebuggerUpdatesEnabled(false);
Elliott Hughes234ab152011-10-26 14:02:26 -0700504
505 gRegistry->Clear();
506 gDebuggerConnected = false;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700507}
508
Elliott Hughesc0f09332012-03-26 13:27:06 -0700509bool Dbg::IsDebuggerActive() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700510 return gDebuggerActive;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700511}
512
Elliott Hughesc0f09332012-03-26 13:27:06 -0700513bool Dbg::IsJdwpConfigured() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700514 return gJdwpConfigured;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700515}
516
517int64_t Dbg::LastDebuggerActivity() {
Elliott Hughesca951522011-12-05 12:01:32 -0800518 return gJdwpState->LastDebuggerActivity();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700519}
520
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700521void Dbg::UndoDebuggerSuspensions() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700522 Runtime::Current()->GetThreadList()->UndoDebuggerSuspensions();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700523}
524
Elliott Hughes88d63092013-01-09 09:55:54 -0800525std::string Dbg::GetClassName(JDWP::RefTypeId class_id) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800526 mirror::Object* o = gRegistry->Get<mirror::Object*>(class_id);
Elliott Hughes436e3722012-02-17 20:01:47 -0800527 if (o == NULL) {
528 return "NULL";
529 }
Elliott Hughes64f574f2013-02-20 14:57:12 -0800530 if (o == ObjectRegistry::kInvalidObject) {
Elliott Hughes88d63092013-01-09 09:55:54 -0800531 return StringPrintf("invalid object %p", reinterpret_cast<void*>(class_id));
Elliott Hughes436e3722012-02-17 20:01:47 -0800532 }
533 if (!o->IsClass()) {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800534 return StringPrintf("non-class %p", o); // This is only used for debugging output anyway.
535 }
Elliott Hughesc308a5d2012-02-16 17:12:06 -0800536 return DescriptorToName(ClassHelper(o->AsClass()).GetDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700537}
538
Elliott Hughes88d63092013-01-09 09:55:54 -0800539JDWP::JdwpError Dbg::GetClassObject(JDWP::RefTypeId id, JDWP::ObjectId& class_object_id) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800540 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800541 mirror::Class* c = DecodeClass(id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -0800542 if (c == NULL) {
543 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800544 }
Elliott Hughes88d63092013-01-09 09:55:54 -0800545 class_object_id = gRegistry->Add(c);
Elliott Hughes436e3722012-02-17 20:01:47 -0800546 return JDWP::ERR_NONE;
Elliott Hughes86964332012-02-15 19:37:42 -0800547}
548
Elliott Hughes88d63092013-01-09 09:55:54 -0800549JDWP::JdwpError Dbg::GetSuperclass(JDWP::RefTypeId id, JDWP::RefTypeId& superclass_id) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800550 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800551 mirror::Class* c = DecodeClass(id, status);
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800552 if (c == NULL) {
553 return status;
554 }
555 if (c->IsInterface()) {
556 // http://code.google.com/p/android/issues/detail?id=20856
Elliott Hughes88d63092013-01-09 09:55:54 -0800557 superclass_id = 0;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800558 } else {
Elliott Hughes88d63092013-01-09 09:55:54 -0800559 superclass_id = gRegistry->Add(c->GetSuperClass());
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800560 }
561 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700562}
563
Elliott Hughes436e3722012-02-17 20:01:47 -0800564JDWP::JdwpError Dbg::GetClassLoader(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800565 mirror::Object* o = gRegistry->Get<mirror::Object*>(id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800566 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800567 return JDWP::ERR_INVALID_OBJECT;
568 }
569 expandBufAddObjectId(pReply, gRegistry->Add(o->GetClass()->GetClassLoader()));
570 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700571}
572
Elliott Hughes436e3722012-02-17 20:01:47 -0800573JDWP::JdwpError Dbg::GetModifiers(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) {
574 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800575 mirror::Class* c = DecodeClass(id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -0800576 if (c == NULL) {
577 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800578 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800579
580 uint32_t access_flags = c->GetAccessFlags() & kAccJavaFlagsMask;
581
582 // Set ACC_SUPER; dex files don't contain this flag, but all classes are supposed to have it set.
583 // Class.getModifiers doesn't return it, but JDWP does, so we set it here.
584 access_flags |= kAccSuper;
585
586 expandBufAdd4BE(pReply, access_flags);
587
588 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700589}
590
Elliott Hughesf327e072013-01-09 16:01:26 -0800591JDWP::JdwpError Dbg::GetMonitorInfo(JDWP::ObjectId object_id, JDWP::ExpandBuf* reply)
592 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800593 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800594 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughesf327e072013-01-09 16:01:26 -0800595 return JDWP::ERR_INVALID_OBJECT;
596 }
597
598 // Ensure all threads are suspended while we read objects' lock words.
599 Thread* self = Thread::Current();
600 Locks::mutator_lock_->SharedUnlock(self);
601 Locks::mutator_lock_->ExclusiveLock(self);
602
603 MonitorInfo monitor_info(o);
604
605 Locks::mutator_lock_->ExclusiveUnlock(self);
606 Locks::mutator_lock_->SharedLock(self);
607
608 if (monitor_info.owner != NULL) {
609 expandBufAddObjectId(reply, gRegistry->Add(monitor_info.owner->GetPeer()));
610 } else {
611 expandBufAddObjectId(reply, gRegistry->Add(NULL));
612 }
613 expandBufAdd4BE(reply, monitor_info.entry_count);
614 expandBufAdd4BE(reply, monitor_info.waiters.size());
615 for (size_t i = 0; i < monitor_info.waiters.size(); ++i) {
616 expandBufAddObjectId(reply, gRegistry->Add(monitor_info.waiters[i]->GetPeer()));
617 }
618 return JDWP::ERR_NONE;
619}
620
Elliott Hughes734b8c62013-01-11 15:32:45 -0800621JDWP::JdwpError Dbg::GetOwnedMonitors(JDWP::ObjectId thread_id,
622 std::vector<JDWP::ObjectId>& monitors,
623 std::vector<uint32_t>& stack_depths)
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800624 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
625 ScopedObjectAccessUnchecked soa(Thread::Current());
626 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
627 Thread* thread;
628 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
629 if (error != JDWP::ERR_NONE) {
630 return error;
631 }
632 if (!IsSuspendedForDebugger(soa, thread)) {
633 return JDWP::ERR_THREAD_NOT_SUSPENDED;
634 }
635
636 struct OwnedMonitorVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -0800637 OwnedMonitorVisitor(Thread* thread, Context* context)
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800638 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -0800639 : StackVisitor(thread, context), current_stack_depth(0) {}
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800640
641 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
642 // annotalysis.
643 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
644 if (!GetMethod()->IsRuntimeMethod()) {
645 Monitor::VisitLocks(this, AppendOwnedMonitors, this);
Elliott Hughes734b8c62013-01-11 15:32:45 -0800646 ++current_stack_depth;
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800647 }
648 return true;
649 }
650
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800651 static void AppendOwnedMonitors(mirror::Object* owned_monitor, void* arg) {
Ian Rogers7a22fa62013-01-23 12:16:16 -0800652 OwnedMonitorVisitor* visitor = reinterpret_cast<OwnedMonitorVisitor*>(arg);
Elliott Hughes734b8c62013-01-11 15:32:45 -0800653 visitor->monitors.push_back(owned_monitor);
654 visitor->stack_depths.push_back(visitor->current_stack_depth);
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800655 }
656
Elliott Hughes734b8c62013-01-11 15:32:45 -0800657 size_t current_stack_depth;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800658 std::vector<mirror::Object*> monitors;
Elliott Hughes734b8c62013-01-11 15:32:45 -0800659 std::vector<uint32_t> stack_depths;
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800660 };
Ian Rogers7a22fa62013-01-23 12:16:16 -0800661 UniquePtr<Context> context(Context::Create());
662 OwnedMonitorVisitor visitor(thread, context.get());
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800663 visitor.WalkStack();
664
665 for (size_t i = 0; i < visitor.monitors.size(); ++i) {
666 monitors.push_back(gRegistry->Add(visitor.monitors[i]));
Elliott Hughes734b8c62013-01-11 15:32:45 -0800667 stack_depths.push_back(visitor.stack_depths[i]);
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800668 }
669
670 return JDWP::ERR_NONE;
671}
672
Elliott Hughesf9501702013-01-11 11:22:27 -0800673JDWP::JdwpError Dbg::GetContendedMonitor(JDWP::ObjectId thread_id, JDWP::ObjectId& contended_monitor)
674 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
675 ScopedObjectAccessUnchecked soa(Thread::Current());
676 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
677 Thread* thread;
678 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
679 if (error != JDWP::ERR_NONE) {
680 return error;
681 }
682 if (!IsSuspendedForDebugger(soa, thread)) {
683 return JDWP::ERR_THREAD_NOT_SUSPENDED;
684 }
685
686 contended_monitor = gRegistry->Add(Monitor::GetContendedMonitor(thread));
687
688 return JDWP::ERR_NONE;
689}
690
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800691JDWP::JdwpError Dbg::GetInstanceCounts(const std::vector<JDWP::RefTypeId>& class_ids,
692 std::vector<uint64_t>& counts)
693 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
694
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800695 std::vector<mirror::Class*> classes;
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800696 counts.clear();
697 for (size_t i = 0; i < class_ids.size(); ++i) {
698 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800699 mirror::Class* c = DecodeClass(class_ids[i], status);
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800700 if (c == NULL) {
701 return status;
702 }
703 classes.push_back(c);
704 counts.push_back(0);
705 }
706
707 Runtime::Current()->GetHeap()->CountInstances(classes, false, &counts[0]);
708 return JDWP::ERR_NONE;
709}
710
Elliott Hughes3b78c942013-01-15 17:35:41 -0800711JDWP::JdwpError Dbg::GetInstances(JDWP::RefTypeId class_id, int32_t max_count, std::vector<JDWP::ObjectId>& instances)
712 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
713 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800714 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes3b78c942013-01-15 17:35:41 -0800715 if (c == NULL) {
716 return status;
717 }
718
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800719 std::vector<mirror::Object*> raw_instances;
Elliott Hughes3b78c942013-01-15 17:35:41 -0800720 Runtime::Current()->GetHeap()->GetInstances(c, max_count, raw_instances);
721 for (size_t i = 0; i < raw_instances.size(); ++i) {
722 instances.push_back(gRegistry->Add(raw_instances[i]));
723 }
724 return JDWP::ERR_NONE;
725}
726
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800727JDWP::JdwpError Dbg::GetReferringObjects(JDWP::ObjectId object_id, int32_t max_count,
728 std::vector<JDWP::ObjectId>& referring_objects)
729 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800730 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800731 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800732 return JDWP::ERR_INVALID_OBJECT;
733 }
734
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800735 std::vector<mirror::Object*> raw_instances;
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800736 Runtime::Current()->GetHeap()->GetReferringObjects(o, max_count, raw_instances);
737 for (size_t i = 0; i < raw_instances.size(); ++i) {
738 referring_objects.push_back(gRegistry->Add(raw_instances[i]));
739 }
740 return JDWP::ERR_NONE;
741}
742
Elliott Hughes64f574f2013-02-20 14:57:12 -0800743JDWP::JdwpError Dbg::DisableCollection(JDWP::ObjectId object_id)
744 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
745 gRegistry->DisableCollection(object_id);
746 return JDWP::ERR_NONE;
747}
748
749JDWP::JdwpError Dbg::EnableCollection(JDWP::ObjectId object_id)
750 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
751 gRegistry->EnableCollection(object_id);
752 return JDWP::ERR_NONE;
753}
754
755JDWP::JdwpError Dbg::IsCollected(JDWP::ObjectId object_id, bool& is_collected)
756 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
757 is_collected = gRegistry->IsCollected(object_id);
758 return JDWP::ERR_NONE;
759}
760
761void Dbg::DisposeObject(JDWP::ObjectId object_id, uint32_t reference_count)
762 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
763 gRegistry->DisposeObject(object_id, reference_count);
764}
765
Elliott Hughes88d63092013-01-09 09:55:54 -0800766JDWP::JdwpError Dbg::GetReflectedType(JDWP::RefTypeId class_id, JDWP::ExpandBuf* pReply) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800767 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800768 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -0800769 if (c == NULL) {
770 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800771 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800772
773 expandBufAdd1(pReply, c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS);
Elliott Hughes88d63092013-01-09 09:55:54 -0800774 expandBufAddRefTypeId(pReply, class_id);
Elliott Hughes436e3722012-02-17 20:01:47 -0800775 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700776}
777
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800778void Dbg::GetClassList(std::vector<JDWP::RefTypeId>& classes) {
Elliott Hughesa2155262011-11-16 16:26:58 -0800779 // Get the complete list of reference classes (i.e. all classes except
780 // the primitive types).
781 // Returns a newly-allocated buffer full of RefTypeId values.
782 struct ClassListCreator {
Elliott Hughesba8eee12012-01-24 20:25:24 -0800783 explicit ClassListCreator(std::vector<JDWP::RefTypeId>& classes) : classes(classes) {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800784 }
785
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800786 static bool Visit(mirror::Class* c, void* arg) {
Elliott Hughesa2155262011-11-16 16:26:58 -0800787 return reinterpret_cast<ClassListCreator*>(arg)->Visit(c);
788 }
789
Elliott Hughes64f574f2013-02-20 14:57:12 -0800790 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
791 // annotalysis.
792 bool Visit(mirror::Class* c) NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughesa2155262011-11-16 16:26:58 -0800793 if (!c->IsPrimitive()) {
Elliott Hughes64f574f2013-02-20 14:57:12 -0800794 classes.push_back(gRegistry->AddRefType(c));
Elliott Hughesa2155262011-11-16 16:26:58 -0800795 }
796 return true;
797 }
798
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800799 std::vector<JDWP::RefTypeId>& classes;
Elliott Hughesa2155262011-11-16 16:26:58 -0800800 };
801
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800802 ClassListCreator clc(classes);
Elliott Hughesa2155262011-11-16 16:26:58 -0800803 Runtime::Current()->GetClassLinker()->VisitClasses(ClassListCreator::Visit, &clc);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700804}
805
Elliott Hughes88d63092013-01-09 09:55:54 -0800806JDWP::JdwpError Dbg::GetClassInfo(JDWP::RefTypeId class_id, JDWP::JdwpTypeTag* pTypeTag, uint32_t* pStatus, std::string* pDescriptor) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800807 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800808 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -0800809 if (c == NULL) {
810 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800811 }
812
Elliott Hughesa2155262011-11-16 16:26:58 -0800813 if (c->IsArrayClass()) {
814 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
815 *pTypeTag = JDWP::TT_ARRAY;
816 } else {
817 if (c->IsErroneous()) {
818 *pStatus = JDWP::CS_ERROR;
819 } else {
820 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED | JDWP::CS_INITIALIZED;
821 }
822 *pTypeTag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
823 }
824
825 if (pDescriptor != NULL) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800826 *pDescriptor = ClassHelper(c).GetDescriptor();
Elliott Hughesa2155262011-11-16 16:26:58 -0800827 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800828 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700829}
830
Elliott Hughesc3b77c72011-12-15 20:56:48 -0800831void Dbg::FindLoadedClassBySignature(const char* descriptor, std::vector<JDWP::RefTypeId>& ids) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800832 std::vector<mirror::Class*> classes;
Elliott Hughes6fa602d2011-12-02 17:54:25 -0800833 Runtime::Current()->GetClassLinker()->LookupClasses(descriptor, classes);
834 ids.clear();
835 for (size_t i = 0; i < classes.size(); ++i) {
836 ids.push_back(gRegistry->Add(classes[i]));
837 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700838}
839
Elliott Hughes64f574f2013-02-20 14:57:12 -0800840JDWP::JdwpError Dbg::GetReferenceType(JDWP::ObjectId object_id, JDWP::ExpandBuf* pReply)
841 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800842 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800843 if (o == NULL || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes2435a572012-02-17 16:07:41 -0800844 return JDWP::ERR_INVALID_OBJECT;
Elliott Hughes499c5132011-11-17 14:55:11 -0800845 }
Elliott Hughes2435a572012-02-17 16:07:41 -0800846
847 JDWP::JdwpTypeTag type_tag;
848 if (o->GetClass()->IsArrayClass()) {
849 type_tag = JDWP::TT_ARRAY;
850 } else if (o->GetClass()->IsInterface()) {
851 type_tag = JDWP::TT_INTERFACE;
852 } else {
853 type_tag = JDWP::TT_CLASS;
854 }
Elliott Hughes64f574f2013-02-20 14:57:12 -0800855 JDWP::RefTypeId type_id = gRegistry->AddRefType(o->GetClass());
Elliott Hughes2435a572012-02-17 16:07:41 -0800856
857 expandBufAdd1(pReply, type_tag);
858 expandBufAddRefTypeId(pReply, type_id);
859
860 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700861}
862
Elliott Hughes88d63092013-01-09 09:55:54 -0800863JDWP::JdwpError Dbg::GetSignature(JDWP::RefTypeId class_id, std::string& signature) {
Elliott Hughes1fe7afb2012-02-13 17:23:03 -0800864 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800865 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes1fe7afb2012-02-13 17:23:03 -0800866 if (c == NULL) {
867 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800868 }
Elliott Hughes1fe7afb2012-02-13 17:23:03 -0800869 signature = ClassHelper(c).GetDescriptor();
870 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700871}
872
Elliott Hughes88d63092013-01-09 09:55:54 -0800873JDWP::JdwpError Dbg::GetSourceFile(JDWP::RefTypeId class_id, std::string& result) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800874 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800875 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -0800876 if (c == NULL) {
877 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800878 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800879 result = ClassHelper(c).GetSourceFile();
880 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700881}
882
Elliott Hughes88d63092013-01-09 09:55:54 -0800883JDWP::JdwpError Dbg::GetObjectTag(JDWP::ObjectId object_id, uint8_t& tag) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800884 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -0800885 if (o == ObjectRegistry::kInvalidObject) {
Elliott Hughes546b9862012-06-20 16:06:13 -0700886 return JDWP::ERR_INVALID_OBJECT;
887 }
888 tag = TagFromObject(o);
889 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700890}
891
Elliott Hughesaed4be92011-12-02 16:16:23 -0800892size_t Dbg::GetTagWidth(JDWP::JdwpTag tag) {
Elliott Hughesdbb40792011-11-18 17:05:22 -0800893 switch (tag) {
894 case JDWP::JT_VOID:
895 return 0;
896 case JDWP::JT_BYTE:
897 case JDWP::JT_BOOLEAN:
898 return 1;
899 case JDWP::JT_CHAR:
900 case JDWP::JT_SHORT:
901 return 2;
902 case JDWP::JT_FLOAT:
903 case JDWP::JT_INT:
904 return 4;
905 case JDWP::JT_ARRAY:
906 case JDWP::JT_OBJECT:
907 case JDWP::JT_STRING:
908 case JDWP::JT_THREAD:
909 case JDWP::JT_THREAD_GROUP:
910 case JDWP::JT_CLASS_LOADER:
911 case JDWP::JT_CLASS_OBJECT:
912 return sizeof(JDWP::ObjectId);
913 case JDWP::JT_DOUBLE:
914 case JDWP::JT_LONG:
915 return 8;
916 default:
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800917 LOG(FATAL) << "Unknown tag " << tag;
Elliott Hughesdbb40792011-11-18 17:05:22 -0800918 return -1;
919 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700920}
921
Elliott Hughes88d63092013-01-09 09:55:54 -0800922JDWP::JdwpError Dbg::GetArrayLength(JDWP::ObjectId array_id, int& length) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800923 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800924 mirror::Array* a = DecodeArray(array_id, status);
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800925 if (a == NULL) {
926 return status;
Elliott Hughes24437992011-11-30 14:49:33 -0800927 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800928 length = a->GetLength();
929 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700930}
931
Elliott Hughes88d63092013-01-09 09:55:54 -0800932JDWP::JdwpError Dbg::OutputArray(JDWP::ObjectId array_id, int offset, int count, JDWP::ExpandBuf* pReply) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800933 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800934 mirror::Array* a = DecodeArray(array_id, status);
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800935 if (a == NULL) {
936 return status;
937 }
Elliott Hughes24437992011-11-30 14:49:33 -0800938
939 if (offset < 0 || count < 0 || offset > a->GetLength() || a->GetLength() - offset < count) {
940 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800941 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughes24437992011-11-30 14:49:33 -0800942 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800943 std::string descriptor(ClassHelper(a->GetClass()).GetDescriptor());
Elliott Hughes24437992011-11-30 14:49:33 -0800944 JDWP::JdwpTag tag = BasicTagFromDescriptor(descriptor.c_str() + 1);
945
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800946 expandBufAdd1(pReply, tag);
947 expandBufAdd4BE(pReply, count);
948
Elliott Hughes24437992011-11-30 14:49:33 -0800949 if (IsPrimitiveTag(tag)) {
950 size_t width = GetTagWidth(tag);
Elliott Hughes24437992011-11-30 14:49:33 -0800951 uint8_t* dst = expandBufAddSpace(pReply, count * width);
952 if (width == 8) {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800953 const uint64_t* src8 = reinterpret_cast<uint64_t*>(a->GetRawData(sizeof(uint64_t)));
Elliott Hughes24437992011-11-30 14:49:33 -0800954 for (int i = 0; i < count; ++i) JDWP::Write8BE(&dst, src8[offset + i]);
955 } else if (width == 4) {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800956 const uint32_t* src4 = reinterpret_cast<uint32_t*>(a->GetRawData(sizeof(uint32_t)));
Elliott Hughes24437992011-11-30 14:49:33 -0800957 for (int i = 0; i < count; ++i) JDWP::Write4BE(&dst, src4[offset + i]);
958 } else if (width == 2) {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800959 const uint16_t* src2 = reinterpret_cast<uint16_t*>(a->GetRawData(sizeof(uint16_t)));
Elliott Hughes24437992011-11-30 14:49:33 -0800960 for (int i = 0; i < count; ++i) JDWP::Write2BE(&dst, src2[offset + i]);
961 } else {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800962 const uint8_t* src = reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint8_t)));
Elliott Hughes24437992011-11-30 14:49:33 -0800963 memcpy(dst, &src[offset * width], count * width);
964 }
965 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800966 mirror::ObjectArray<mirror::Object>* oa = a->AsObjectArray<mirror::Object>();
Elliott Hughes24437992011-11-30 14:49:33 -0800967 for (int i = 0; i < count; ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800968 mirror::Object* element = oa->Get(offset + i);
Elliott Hughes24437992011-11-30 14:49:33 -0800969 JDWP::JdwpTag specific_tag = (element != NULL) ? TagFromObject(element) : tag;
970 expandBufAdd1(pReply, specific_tag);
971 expandBufAddObjectId(pReply, gRegistry->Add(element));
972 }
973 }
974
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800975 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700976}
977
Elliott Hughes4b9702c2013-02-20 18:13:24 -0800978template <typename T> void CopyArrayData(mirror::Array* a, JDWP::Request& src, int offset, int count) {
979 DCHECK(a->GetClass()->IsPrimitiveArray());
980
981 T* dst = &(reinterpret_cast<T*>(a->GetRawData(sizeof(T)))[offset * sizeof(T)]);
982 for (int i = 0; i < count; ++i) {
983 *dst++ = src.ReadValue(sizeof(T));
984 }
985}
986
Elliott Hughes88d63092013-01-09 09:55:54 -0800987JDWP::JdwpError Dbg::SetArrayElements(JDWP::ObjectId array_id, int offset, int count,
Elliott Hughes4b9702c2013-02-20 18:13:24 -0800988 JDWP::Request& request)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700989 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800990 JDWP::JdwpError status;
Elliott Hughes4b9702c2013-02-20 18:13:24 -0800991 mirror::Array* dst = DecodeArray(array_id, status);
992 if (dst == NULL) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800993 return status;
994 }
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800995
Elliott Hughes4b9702c2013-02-20 18:13:24 -0800996 if (offset < 0 || count < 0 || offset > dst->GetLength() || dst->GetLength() - offset < count) {
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800997 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800998 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800999 }
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001000 std::string descriptor(ClassHelper(dst->GetClass()).GetDescriptor());
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001001 JDWP::JdwpTag tag = BasicTagFromDescriptor(descriptor.c_str() + 1);
1002
1003 if (IsPrimitiveTag(tag)) {
1004 size_t width = GetTagWidth(tag);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001005 if (width == 8) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001006 CopyArrayData<uint64_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001007 } else if (width == 4) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001008 CopyArrayData<uint32_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001009 } else if (width == 2) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001010 CopyArrayData<uint16_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001011 } else {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001012 CopyArrayData<uint8_t>(dst, request, offset, count);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001013 }
1014 } else {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001015 mirror::ObjectArray<mirror::Object>* oa = dst->AsObjectArray<mirror::Object>();
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001016 for (int i = 0; i < count; ++i) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08001017 JDWP::ObjectId id = request.ReadObjectId();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001018 mirror::Object* o = gRegistry->Get<mirror::Object*>(id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001019 if (o == ObjectRegistry::kInvalidObject) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001020 return JDWP::ERR_INVALID_OBJECT;
1021 }
1022 oa->Set(offset + i, o);
Elliott Hughesf03b8f62011-12-02 14:26:25 -08001023 }
1024 }
1025
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001026 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001027}
1028
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001029JDWP::ObjectId Dbg::CreateString(const std::string& str) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001030 return gRegistry->Add(mirror::String::AllocFromModifiedUtf8(Thread::Current(), str.c_str()));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001031}
1032
Elliott Hughes88d63092013-01-09 09:55:54 -08001033JDWP::JdwpError Dbg::CreateObject(JDWP::RefTypeId class_id, JDWP::ObjectId& new_object) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001034 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001035 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001036 if (c == NULL) {
1037 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001038 }
Ian Rogers50b35e22012-10-04 10:09:15 -07001039 new_object = gRegistry->Add(c->AllocObject(Thread::Current()));
Elliott Hughes436e3722012-02-17 20:01:47 -08001040 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001041}
1042
Elliott Hughesbf13d362011-12-08 15:51:37 -08001043/*
1044 * Used by Eclipse's "Display" view to evaluate "new byte[5]" to get "(byte[]) [0, 0, 0, 0, 0]".
1045 */
Elliott Hughes88d63092013-01-09 09:55:54 -08001046JDWP::JdwpError Dbg::CreateArrayObject(JDWP::RefTypeId array_class_id, uint32_t length,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001047 JDWP::ObjectId& new_array) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001048 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001049 mirror::Class* c = DecodeClass(array_class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001050 if (c == NULL) {
1051 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001052 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001053 new_array = gRegistry->Add(mirror::Array::Alloc(Thread::Current(), c, length));
Elliott Hughes436e3722012-02-17 20:01:47 -08001054 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001055}
1056
Elliott Hughes88d63092013-01-09 09:55:54 -08001057bool Dbg::MatchType(JDWP::RefTypeId instance_class_id, JDWP::RefTypeId class_id) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001058 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001059 mirror::Class* c1 = DecodeClass(instance_class_id, status);
Elliott Hughesa656a0f2012-02-21 18:03:44 -08001060 CHECK(c1 != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001061 mirror::Class* c2 = DecodeClass(class_id, status);
Elliott Hughesa656a0f2012-02-21 18:03:44 -08001062 CHECK(c2 != NULL);
1063 return c1->IsAssignableFrom(c2);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001064}
1065
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001066static JDWP::FieldId ToFieldId(const mirror::Field* f)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001067 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001068#ifdef MOVING_GARBAGE_COLLECTOR
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001069 UNIMPLEMENTED(FATAL);
Elliott Hughes03181a82011-11-17 17:22:21 -08001070#else
1071 return static_cast<JDWP::FieldId>(reinterpret_cast<uintptr_t>(f));
1072#endif
1073}
1074
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001075static JDWP::MethodId ToMethodId(const mirror::AbstractMethod* m)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001076 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001077#ifdef MOVING_GARBAGE_COLLECTOR
1078 UNIMPLEMENTED(FATAL);
1079#else
1080 return static_cast<JDWP::MethodId>(reinterpret_cast<uintptr_t>(m));
1081#endif
1082}
1083
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001084static mirror::Field* FromFieldId(JDWP::FieldId fid)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001085 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesaed4be92011-12-02 16:16:23 -08001086#ifdef MOVING_GARBAGE_COLLECTOR
1087 UNIMPLEMENTED(FATAL);
1088#else
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001089 return reinterpret_cast<mirror::Field*>(static_cast<uintptr_t>(fid));
Elliott Hughesaed4be92011-12-02 16:16:23 -08001090#endif
1091}
1092
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001093static mirror::AbstractMethod* FromMethodId(JDWP::MethodId mid)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001094 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001095#ifdef MOVING_GARBAGE_COLLECTOR
1096 UNIMPLEMENTED(FATAL);
1097#else
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001098 return reinterpret_cast<mirror::AbstractMethod*>(static_cast<uintptr_t>(mid));
Elliott Hughes03181a82011-11-17 17:22:21 -08001099#endif
1100}
1101
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001102static void SetLocation(JDWP::JdwpLocation& location, mirror::AbstractMethod* m, uint32_t dex_pc)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001103 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001104 if (m == NULL) {
1105 memset(&location, 0, sizeof(location));
1106 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001107 mirror::Class* c = m->GetDeclaringClass();
Elliott Hughes74847412012-06-20 18:10:21 -07001108 location.type_tag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
1109 location.class_id = gRegistry->Add(c);
1110 location.method_id = ToMethodId(m);
Ian Rogers0399dde2012-06-06 17:09:28 -07001111 location.dex_pc = dex_pc;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001112 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08001113}
1114
Elliott Hughesa96836a2013-01-17 12:27:49 -08001115std::string Dbg::GetMethodName(JDWP::MethodId method_id)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001116 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001117 mirror::AbstractMethod* m = FromMethodId(method_id);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001118 return MethodHelper(m).GetName();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001119}
1120
Elliott Hughesa96836a2013-01-17 12:27:49 -08001121std::string Dbg::GetFieldName(JDWP::FieldId field_id)
1122 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001123 mirror::Field* f = FromFieldId(field_id);
Elliott Hughesa96836a2013-01-17 12:27:49 -08001124 return FieldHelper(f).GetName();
1125}
1126
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001127/*
1128 * Augment the access flags for synthetic methods and fields by setting
1129 * the (as described by the spec) "0xf0000000 bit". Also, strip out any
1130 * flags not specified by the Java programming language.
1131 */
1132static uint32_t MangleAccessFlags(uint32_t accessFlags) {
1133 accessFlags &= kAccJavaFlagsMask;
1134 if ((accessFlags & kAccSynthetic) != 0) {
1135 accessFlags |= 0xf0000000;
1136 }
1137 return accessFlags;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001138}
1139
Elliott Hughesdbb40792011-11-18 17:05:22 -08001140static const uint16_t kEclipseWorkaroundSlot = 1000;
1141
1142/*
1143 * Eclipse appears to expect that the "this" reference is in slot zero.
1144 * If it's not, the "variables" display will show two copies of "this",
1145 * possibly because it gets "this" from SF.ThisObject and then displays
1146 * all locals with nonzero slot numbers.
1147 *
1148 * So, we remap the item in slot 0 to 1000, and remap "this" to zero. On
1149 * SF.GetValues / SF.SetValues we map them back.
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001150 *
1151 * TODO: jdb uses the value to determine whether a variable is a local or an argument,
1152 * by checking whether it's less than the number of arguments. To make that work, we'd
1153 * have to "mangle" all the arguments to come first, not just the implicit argument 'this'.
Elliott Hughesdbb40792011-11-18 17:05:22 -08001154 */
1155static uint16_t MangleSlot(uint16_t slot, const char* name) {
1156 uint16_t newSlot = slot;
1157 if (strcmp(name, "this") == 0) {
1158 newSlot = 0;
1159 } else if (slot == 0) {
1160 newSlot = kEclipseWorkaroundSlot;
1161 }
1162 return newSlot;
1163}
1164
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001165static uint16_t DemangleSlot(uint16_t slot, mirror::AbstractMethod* m)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001166 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001167 if (slot == kEclipseWorkaroundSlot) {
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001168 return 0;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001169 } else if (slot == 0) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001170 const DexFile::CodeItem* code_item = MethodHelper(m).GetCodeItem();
Elliott Hughescaf76542012-06-28 16:08:22 -07001171 CHECK(code_item != NULL) << PrettyMethod(m);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001172 return code_item->registers_size_ - code_item->ins_size_;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001173 }
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001174 return slot;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001175}
1176
Elliott Hughes88d63092013-01-09 09:55:54 -08001177JDWP::JdwpError Dbg::OutputDeclaredFields(JDWP::RefTypeId class_id, bool with_generic, JDWP::ExpandBuf* pReply) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001178 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001179 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001180 if (c == NULL) {
1181 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001182 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001183
1184 size_t instance_field_count = c->NumInstanceFields();
1185 size_t static_field_count = c->NumStaticFields();
1186
1187 expandBufAdd4BE(pReply, instance_field_count + static_field_count);
1188
1189 for (size_t i = 0; i < instance_field_count + static_field_count; ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001190 mirror::Field* f = (i < instance_field_count) ? c->GetInstanceField(i) : c->GetStaticField(i - instance_field_count);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001191 FieldHelper fh(f);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001192 expandBufAddFieldId(pReply, ToFieldId(f));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001193 expandBufAddUtf8String(pReply, fh.GetName());
1194 expandBufAddUtf8String(pReply, fh.GetTypeDescriptor());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001195 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001196 static const char genericSignature[1] = "";
1197 expandBufAddUtf8String(pReply, genericSignature);
1198 }
1199 expandBufAdd4BE(pReply, MangleAccessFlags(f->GetAccessFlags()));
1200 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001201 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001202}
1203
Elliott Hughes88d63092013-01-09 09:55:54 -08001204JDWP::JdwpError Dbg::OutputDeclaredMethods(JDWP::RefTypeId class_id, bool with_generic,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001205 JDWP::ExpandBuf* pReply) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001206 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001207 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001208 if (c == NULL) {
1209 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001210 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001211
1212 size_t direct_method_count = c->NumDirectMethods();
1213 size_t virtual_method_count = c->NumVirtualMethods();
1214
1215 expandBufAdd4BE(pReply, direct_method_count + virtual_method_count);
1216
1217 for (size_t i = 0; i < direct_method_count + virtual_method_count; ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001218 mirror::AbstractMethod* m = (i < direct_method_count) ? c->GetDirectMethod(i) : c->GetVirtualMethod(i - direct_method_count);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001219 MethodHelper mh(m);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001220 expandBufAddMethodId(pReply, ToMethodId(m));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001221 expandBufAddUtf8String(pReply, mh.GetName());
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001222 expandBufAddUtf8String(pReply, mh.GetSignature());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001223 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001224 static const char genericSignature[1] = "";
1225 expandBufAddUtf8String(pReply, genericSignature);
1226 }
1227 expandBufAdd4BE(pReply, MangleAccessFlags(m->GetAccessFlags()));
1228 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001229 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001230}
1231
Elliott Hughes88d63092013-01-09 09:55:54 -08001232JDWP::JdwpError Dbg::OutputDeclaredInterfaces(JDWP::RefTypeId class_id, JDWP::ExpandBuf* pReply) {
Elliott Hughes436e3722012-02-17 20:01:47 -08001233 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001234 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes436e3722012-02-17 20:01:47 -08001235 if (c == NULL) {
1236 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001237 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001238
1239 ClassHelper kh(c);
Ian Rogersd24e2642012-06-06 21:21:43 -07001240 size_t interface_count = kh.NumDirectInterfaces();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001241 expandBufAdd4BE(pReply, interface_count);
1242 for (size_t i = 0; i < interface_count; ++i) {
Elliott Hughes64f574f2013-02-20 14:57:12 -08001243 expandBufAddRefTypeId(pReply, gRegistry->AddRefType(kh.GetDirectInterface(i)));
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001244 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001245 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001246}
1247
Elliott Hughes88d63092013-01-09 09:55:54 -08001248void Dbg::OutputLineTable(JDWP::RefTypeId, JDWP::MethodId method_id, JDWP::ExpandBuf* pReply)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001249 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001250 struct DebugCallbackContext {
1251 int numItems;
1252 JDWP::ExpandBuf* pReply;
1253
Elliott Hughes2435a572012-02-17 16:07:41 -08001254 static bool Callback(void* context, uint32_t address, uint32_t line_number) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001255 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
1256 expandBufAdd8BE(pContext->pReply, address);
Elliott Hughes2435a572012-02-17 16:07:41 -08001257 expandBufAdd4BE(pContext->pReply, line_number);
Elliott Hughes03181a82011-11-17 17:22:21 -08001258 pContext->numItems++;
1259 return true;
1260 }
1261 };
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001262 mirror::AbstractMethod* m = FromMethodId(method_id);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001263 MethodHelper mh(m);
Elliott Hughes03181a82011-11-17 17:22:21 -08001264 uint64_t start, end;
1265 if (m->IsNative()) {
1266 start = -1;
1267 end = -1;
1268 } else {
1269 start = 0;
jeffhao14f0db92012-12-14 17:50:42 -08001270 // Return the index of the last instruction
1271 end = mh.GetCodeItem()->insns_size_in_code_units_ - 1;
Elliott Hughes03181a82011-11-17 17:22:21 -08001272 }
1273
1274 expandBufAdd8BE(pReply, start);
1275 expandBufAdd8BE(pReply, end);
1276
1277 // Add numLines later
1278 size_t numLinesOffset = expandBufGetLength(pReply);
1279 expandBufAdd4BE(pReply, 0);
1280
1281 DebugCallbackContext context;
1282 context.numItems = 0;
1283 context.pReply = pReply;
1284
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001285 mh.GetDexFile().DecodeDebugInfo(mh.GetCodeItem(), m->IsStatic(), m->GetDexMethodIndex(),
1286 DebugCallbackContext::Callback, NULL, &context);
Elliott Hughes03181a82011-11-17 17:22:21 -08001287
1288 JDWP::Set4BE(expandBufGetBuffer(pReply) + numLinesOffset, context.numItems);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001289}
1290
Elliott Hughes88d63092013-01-09 09:55:54 -08001291void Dbg::OutputVariableTable(JDWP::RefTypeId, JDWP::MethodId method_id, bool with_generic, JDWP::ExpandBuf* pReply) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001292 struct DebugCallbackContext {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001293 JDWP::ExpandBuf* pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001294 size_t variable_count;
1295 bool with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001296
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001297 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 -08001298 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
1299
Elliott Hughesad3da692012-02-24 16:51:35 -08001300 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 -08001301
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001302 slot = MangleSlot(slot, name);
1303
Elliott Hughesdbb40792011-11-18 17:05:22 -08001304 expandBufAdd8BE(pContext->pReply, startAddress);
1305 expandBufAddUtf8String(pContext->pReply, name);
1306 expandBufAddUtf8String(pContext->pReply, descriptor);
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001307 if (pContext->with_generic) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001308 expandBufAddUtf8String(pContext->pReply, signature);
1309 }
1310 expandBufAdd4BE(pContext->pReply, endAddress - startAddress);
1311 expandBufAdd4BE(pContext->pReply, slot);
1312
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001313 ++pContext->variable_count;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001314 }
1315 };
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001316 mirror::AbstractMethod* m = FromMethodId(method_id);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001317 MethodHelper mh(m);
1318 const DexFile::CodeItem* code_item = mh.GetCodeItem();
Elliott Hughesdbb40792011-11-18 17:05:22 -08001319
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001320 // arg_count considers doubles and longs to take 2 units.
1321 // variable_count considers everything to take 1 unit.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001322 std::string shorty(mh.GetShorty());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001323 expandBufAdd4BE(pReply, mirror::AbstractMethod::NumArgRegisters(shorty));
Elliott Hughesdbb40792011-11-18 17:05:22 -08001324
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001325 // We don't know the total number of variables yet, so leave a blank and update it later.
1326 size_t variable_count_offset = expandBufGetLength(pReply);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001327 expandBufAdd4BE(pReply, 0);
1328
1329 DebugCallbackContext context;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001330 context.pReply = pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001331 context.variable_count = 0;
1332 context.with_generic = with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001333
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001334 mh.GetDexFile().DecodeDebugInfo(code_item, m->IsStatic(), m->GetDexMethodIndex(), NULL,
1335 DebugCallbackContext::Callback, &context);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001336
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001337 JDWP::Set4BE(expandBufGetBuffer(pReply) + variable_count_offset, context.variable_count);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001338}
1339
Elliott Hughes9777ba22013-01-17 09:04:19 -08001340JDWP::JdwpError Dbg::GetBytecodes(JDWP::RefTypeId, JDWP::MethodId method_id,
1341 std::vector<uint8_t>& bytecodes)
1342 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001343 mirror::AbstractMethod* m = FromMethodId(method_id);
Elliott Hughes9777ba22013-01-17 09:04:19 -08001344 if (m == NULL) {
1345 return JDWP::ERR_INVALID_METHODID;
1346 }
1347 MethodHelper mh(m);
1348 const DexFile::CodeItem* code_item = mh.GetCodeItem();
1349 size_t byte_count = code_item->insns_size_in_code_units_ * 2;
1350 const uint8_t* begin = reinterpret_cast<const uint8_t*>(code_item->insns_);
1351 const uint8_t* end = begin + byte_count;
1352 for (const uint8_t* p = begin; p != end; ++p) {
1353 bytecodes.push_back(*p);
1354 }
1355 return JDWP::ERR_NONE;
1356}
1357
Elliott Hughes88d63092013-01-09 09:55:54 -08001358JDWP::JdwpTag Dbg::GetFieldBasicTag(JDWP::FieldId field_id) {
1359 return BasicTagFromDescriptor(FieldHelper(FromFieldId(field_id)).GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001360}
1361
Elliott Hughes88d63092013-01-09 09:55:54 -08001362JDWP::JdwpTag Dbg::GetStaticFieldBasicTag(JDWP::FieldId field_id) {
1363 return BasicTagFromDescriptor(FieldHelper(FromFieldId(field_id)).GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001364}
1365
Elliott Hughes88d63092013-01-09 09:55:54 -08001366static JDWP::JdwpError GetFieldValueImpl(JDWP::RefTypeId ref_type_id, JDWP::ObjectId object_id,
1367 JDWP::FieldId field_id, JDWP::ExpandBuf* pReply,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001368 bool is_static)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001369 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes0cf74332012-02-23 23:14:00 -08001370 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001371 mirror::Class* c = DecodeClass(ref_type_id, status);
Elliott Hughes88d63092013-01-09 09:55:54 -08001372 if (ref_type_id != 0 && c == NULL) {
Elliott Hughes0cf74332012-02-23 23:14:00 -08001373 return status;
1374 }
1375
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001376 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001377 if ((!is_static && o == NULL) || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001378 return JDWP::ERR_INVALID_OBJECT;
1379 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001380 mirror::Field* f = FromFieldId(field_id);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001381
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001382 mirror::Class* receiver_class = c;
Elliott Hughes0cf74332012-02-23 23:14:00 -08001383 if (receiver_class == NULL && o != NULL) {
1384 receiver_class = o->GetClass();
1385 }
1386 // TODO: should we give up now if receiver_class is NULL?
1387 if (receiver_class != NULL && !f->GetDeclaringClass()->IsAssignableFrom(receiver_class)) {
1388 LOG(INFO) << "ERR_INVALID_FIELDID: " << PrettyField(f) << " " << PrettyClass(receiver_class);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001389 return JDWP::ERR_INVALID_FIELDID;
1390 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001391
Elliott Hughes0cf74332012-02-23 23:14:00 -08001392 // The RI only enforces the static/non-static mismatch in one direction.
1393 // TODO: should we change the tests and check both?
1394 if (is_static) {
1395 if (!f->IsStatic()) {
1396 return JDWP::ERR_INVALID_FIELDID;
1397 }
1398 } else {
1399 if (f->IsStatic()) {
1400 LOG(WARNING) << "Ignoring non-NULL receiver for ObjectReference.SetValues on static field " << PrettyField(f);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001401 }
1402 }
jeffhao0dfbb7e2012-11-28 15:26:03 -08001403 if (f->IsStatic()) {
1404 o = f->GetDeclaringClass();
1405 }
Elliott Hughes0cf74332012-02-23 23:14:00 -08001406
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001407 JDWP::JdwpTag tag = BasicTagFromDescriptor(FieldHelper(f).GetTypeDescriptor());
Elliott Hughesaed4be92011-12-02 16:16:23 -08001408
1409 if (IsPrimitiveTag(tag)) {
1410 expandBufAdd1(pReply, tag);
1411 if (tag == JDWP::JT_BOOLEAN || tag == JDWP::JT_BYTE) {
1412 expandBufAdd1(pReply, f->Get32(o));
1413 } else if (tag == JDWP::JT_CHAR || tag == JDWP::JT_SHORT) {
1414 expandBufAdd2BE(pReply, f->Get32(o));
1415 } else if (tag == JDWP::JT_FLOAT || tag == JDWP::JT_INT) {
1416 expandBufAdd4BE(pReply, f->Get32(o));
1417 } else if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
1418 expandBufAdd8BE(pReply, f->Get64(o));
1419 } else {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001420 LOG(FATAL) << "Unknown tag: " << tag;
Elliott Hughesaed4be92011-12-02 16:16:23 -08001421 }
1422 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001423 mirror::Object* value = f->GetObject(o);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001424 expandBufAdd1(pReply, TagFromObject(value));
1425 expandBufAddObjectId(pReply, gRegistry->Add(value));
1426 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001427 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001428}
1429
Elliott Hughes88d63092013-01-09 09:55:54 -08001430JDWP::JdwpError Dbg::GetFieldValue(JDWP::ObjectId object_id, JDWP::FieldId field_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001431 JDWP::ExpandBuf* pReply) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001432 return GetFieldValueImpl(0, object_id, field_id, pReply, false);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001433}
1434
Elliott Hughes88d63092013-01-09 09:55:54 -08001435JDWP::JdwpError Dbg::GetStaticFieldValue(JDWP::RefTypeId ref_type_id, JDWP::FieldId field_id, JDWP::ExpandBuf* pReply) {
1436 return GetFieldValueImpl(ref_type_id, 0, field_id, pReply, true);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001437}
1438
Elliott Hughes88d63092013-01-09 09:55:54 -08001439static JDWP::JdwpError SetFieldValueImpl(JDWP::ObjectId object_id, JDWP::FieldId field_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001440 uint64_t value, int width, bool is_static)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001441 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001442 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001443 if ((!is_static && o == NULL) || o == ObjectRegistry::kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001444 return JDWP::ERR_INVALID_OBJECT;
1445 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001446 mirror::Field* f = FromFieldId(field_id);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001447
1448 // The RI only enforces the static/non-static mismatch in one direction.
1449 // TODO: should we change the tests and check both?
1450 if (is_static) {
1451 if (!f->IsStatic()) {
1452 return JDWP::ERR_INVALID_FIELDID;
1453 }
1454 } else {
1455 if (f->IsStatic()) {
1456 LOG(WARNING) << "Ignoring non-NULL receiver for ObjectReference.SetValues on static field " << PrettyField(f);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001457 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001458 }
jeffhao0dfbb7e2012-11-28 15:26:03 -08001459 if (f->IsStatic()) {
1460 o = f->GetDeclaringClass();
1461 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001462
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001463 JDWP::JdwpTag tag = BasicTagFromDescriptor(FieldHelper(f).GetTypeDescriptor());
Elliott Hughesaed4be92011-12-02 16:16:23 -08001464
1465 if (IsPrimitiveTag(tag)) {
1466 if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001467 CHECK_EQ(width, 8);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001468 f->Set64(o, value);
1469 } else {
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001470 CHECK_LE(width, 4);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001471 f->Set32(o, value);
1472 }
1473 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001474 mirror::Object* v = gRegistry->Get<mirror::Object*>(value);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001475 if (v == ObjectRegistry::kInvalidObject) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001476 return JDWP::ERR_INVALID_OBJECT;
1477 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001478 if (v != NULL) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001479 mirror::Class* field_type = FieldHelper(f).GetType();
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001480 if (!field_type->IsAssignableFrom(v->GetClass())) {
1481 return JDWP::ERR_INVALID_OBJECT;
1482 }
1483 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001484 f->SetObject(o, v);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001485 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001486
1487 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001488}
1489
Elliott Hughes88d63092013-01-09 09:55:54 -08001490JDWP::JdwpError Dbg::SetFieldValue(JDWP::ObjectId object_id, JDWP::FieldId field_id, uint64_t value,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001491 int width) {
Elliott Hughes88d63092013-01-09 09:55:54 -08001492 return SetFieldValueImpl(object_id, field_id, value, width, false);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001493}
1494
Elliott Hughes88d63092013-01-09 09:55:54 -08001495JDWP::JdwpError Dbg::SetStaticFieldValue(JDWP::FieldId field_id, uint64_t value, int width) {
1496 return SetFieldValueImpl(0, field_id, value, width, true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001497}
1498
Elliott Hughes88d63092013-01-09 09:55:54 -08001499std::string Dbg::StringToUtf8(JDWP::ObjectId string_id) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001500 mirror::String* s = gRegistry->Get<mirror::String*>(string_id);
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001501 return s->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001502}
1503
Elliott Hughes221229c2013-01-08 18:17:50 -08001504JDWP::JdwpError Dbg::GetThreadName(JDWP::ObjectId thread_id, std::string& name) {
jeffhaoa77f0f62012-12-05 17:19:31 -08001505 ScopedObjectAccessUnchecked soa(Thread::Current());
1506 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001507 Thread* thread;
1508 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1509 if (error != JDWP::ERR_NONE && error != JDWP::ERR_THREAD_NOT_ALIVE) {
1510 return error;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001511 }
Elliott Hughes221229c2013-01-08 18:17:50 -08001512
1513 // We still need to report the zombie threads' names, so we can't just call Thread::GetThreadName.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001514 mirror::Object* thread_object = gRegistry->Get<mirror::Object*>(thread_id);
1515 mirror::Field* java_lang_Thread_name_field =
1516 soa.DecodeField(WellKnownClasses::java_lang_Thread_name);
1517 mirror::String* s =
1518 reinterpret_cast<mirror::String*>(java_lang_Thread_name_field->GetObject(thread_object));
Elliott Hughes221229c2013-01-08 18:17:50 -08001519 if (s != NULL) {
1520 name = s->ToModifiedUtf8();
1521 }
1522 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001523}
1524
Elliott Hughes221229c2013-01-08 18:17:50 -08001525JDWP::JdwpError Dbg::GetThreadGroup(JDWP::ObjectId thread_id, JDWP::ExpandBuf* pReply) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001526 ScopedObjectAccess soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001527 mirror::Object* thread_object = gRegistry->Get<mirror::Object*>(thread_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08001528 if (thread_object == ObjectRegistry::kInvalidObject) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001529 return JDWP::ERR_INVALID_OBJECT;
1530 }
1531
1532 // Okay, so it's an object, but is it actually a thread?
Ian Rogers50b35e22012-10-04 10:09:15 -07001533 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001534 Thread* thread;
1535 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1536 if (error == JDWP::ERR_THREAD_NOT_ALIVE) {
1537 // Zombie threads are in the null group.
1538 expandBufAddObjectId(pReply, JDWP::ObjectId(0));
1539 return JDWP::ERR_NONE;
1540 }
1541 if (error != JDWP::ERR_NONE) {
1542 return error;
Elliott Hughes2435a572012-02-17 16:07:41 -08001543 }
Elliott Hughes499c5132011-11-17 14:55:11 -08001544
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001545 mirror::Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/Thread;");
Elliott Hughes499c5132011-11-17 14:55:11 -08001546 CHECK(c != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001547 mirror::Field* f = c->FindInstanceField("group", "Ljava/lang/ThreadGroup;");
Elliott Hughes499c5132011-11-17 14:55:11 -08001548 CHECK(f != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001549 mirror::Object* group = f->GetObject(thread_object);
Elliott Hughes499c5132011-11-17 14:55:11 -08001550 CHECK(group != NULL);
Elliott Hughes2435a572012-02-17 16:07:41 -08001551 JDWP::ObjectId thread_group_id = gRegistry->Add(group);
1552
1553 expandBufAddObjectId(pReply, thread_group_id);
1554 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001555}
1556
Elliott Hughes88d63092013-01-09 09:55:54 -08001557std::string Dbg::GetThreadGroupName(JDWP::ObjectId thread_group_id) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001558 ScopedObjectAccess soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001559 mirror::Object* thread_group = gRegistry->Get<mirror::Object*>(thread_group_id);
Elliott Hughes499c5132011-11-17 14:55:11 -08001560 CHECK(thread_group != NULL);
1561
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001562 mirror::Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/ThreadGroup;");
Elliott Hughes499c5132011-11-17 14:55:11 -08001563 CHECK(c != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001564 mirror::Field* f = c->FindInstanceField("name", "Ljava/lang/String;");
Elliott Hughes499c5132011-11-17 14:55:11 -08001565 CHECK(f != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001566 mirror::String* s = reinterpret_cast<mirror::String*>(f->GetObject(thread_group));
Elliott Hughes499c5132011-11-17 14:55:11 -08001567 return s->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001568}
1569
Elliott Hughes88d63092013-01-09 09:55:54 -08001570JDWP::ObjectId Dbg::GetThreadGroupParent(JDWP::ObjectId thread_group_id) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001571 mirror::Object* thread_group = gRegistry->Get<mirror::Object*>(thread_group_id);
Elliott Hughes4e235312011-12-02 11:34:15 -08001572 CHECK(thread_group != NULL);
1573
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001574 mirror::Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/ThreadGroup;");
Elliott Hughes4e235312011-12-02 11:34:15 -08001575 CHECK(c != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001576 mirror::Field* f = c->FindInstanceField("parent", "Ljava/lang/ThreadGroup;");
Elliott Hughes4e235312011-12-02 11:34:15 -08001577 CHECK(f != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001578 mirror::Object* parent = f->GetObject(thread_group);
Elliott Hughes4e235312011-12-02 11:34:15 -08001579 return gRegistry->Add(parent);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001580}
1581
1582JDWP::ObjectId Dbg::GetSystemThreadGroupId() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001583 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001584 mirror::Field* f = soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_systemThreadGroup);
1585 mirror::Object* group = f->GetObject(f->GetDeclaringClass());
Ian Rogers365c1022012-06-22 15:05:28 -07001586 return gRegistry->Add(group);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001587}
1588
1589JDWP::ObjectId Dbg::GetMainThreadGroupId() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001590 ScopedObjectAccess soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001591 mirror::Field* f = soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_mainThreadGroup);
1592 mirror::Object* group = f->GetObject(f->GetDeclaringClass());
Ian Rogers365c1022012-06-22 15:05:28 -07001593 return gRegistry->Add(group);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001594}
1595
Elliott Hughes221229c2013-01-08 18:17:50 -08001596JDWP::JdwpError Dbg::GetThreadStatus(JDWP::ObjectId thread_id, JDWP::JdwpThreadStatus* pThreadStatus, JDWP::JdwpSuspendStatus* pSuspendStatus) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001597 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes499c5132011-11-17 14:55:11 -08001598
Elliott Hughes9e0c1752013-01-09 14:02:58 -08001599 *pSuspendStatus = JDWP::SUSPEND_STATUS_NOT_SUSPENDED;
1600
Ian Rogers50b35e22012-10-04 10:09:15 -07001601 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001602 Thread* thread;
1603 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1604 if (error != JDWP::ERR_NONE) {
1605 if (error == JDWP::ERR_THREAD_NOT_ALIVE) {
1606 *pThreadStatus = JDWP::TS_ZOMBIE;
Elliott Hughes221229c2013-01-08 18:17:50 -08001607 return JDWP::ERR_NONE;
1608 }
1609 return error;
Elliott Hughes499c5132011-11-17 14:55:11 -08001610 }
1611
Elliott Hughes9e0c1752013-01-09 14:02:58 -08001612 if (IsSuspendedForDebugger(soa, thread)) {
1613 *pSuspendStatus = JDWP::SUSPEND_STATUS_SUSPENDED;
Elliott Hughes499c5132011-11-17 14:55:11 -08001614 }
1615
Elliott Hughes9e0c1752013-01-09 14:02:58 -08001616 switch (thread->GetState()) {
1617 case kBlocked: *pThreadStatus = JDWP::TS_MONITOR; break;
1618 case kNative: *pThreadStatus = JDWP::TS_RUNNING; break;
1619 case kRunnable: *pThreadStatus = JDWP::TS_RUNNING; break;
1620 case kSleeping: *pThreadStatus = JDWP::TS_SLEEPING; break;
1621 case kStarting: *pThreadStatus = JDWP::TS_ZOMBIE; break;
1622 case kSuspended: *pThreadStatus = JDWP::TS_RUNNING; break;
1623 case kTerminated: *pThreadStatus = JDWP::TS_ZOMBIE; break;
1624 case kTimedWaiting: *pThreadStatus = JDWP::TS_WAIT; break;
1625 case kWaitingForDebuggerSend: *pThreadStatus = JDWP::TS_WAIT; break;
1626 case kWaitingForDebuggerSuspension: *pThreadStatus = JDWP::TS_WAIT; break;
1627 case kWaitingForDebuggerToAttach: *pThreadStatus = JDWP::TS_WAIT; break;
1628 case kWaitingForGcToComplete: *pThreadStatus = JDWP::TS_WAIT; break;
1629 case kWaitingForJniOnLoad: *pThreadStatus = JDWP::TS_WAIT; break;
1630 case kWaitingForSignalCatcherOutput: *pThreadStatus = JDWP::TS_WAIT; break;
1631 case kWaitingInMainDebuggerLoop: *pThreadStatus = JDWP::TS_WAIT; break;
1632 case kWaitingInMainSignalCatcherLoop: *pThreadStatus = JDWP::TS_WAIT; break;
1633 case kWaitingPerformingGc: *pThreadStatus = JDWP::TS_WAIT; break;
1634 case kWaiting: *pThreadStatus = JDWP::TS_WAIT; break;
1635 // Don't add a 'default' here so the compiler can spot incompatible enum changes.
1636 }
Elliott Hughes221229c2013-01-08 18:17:50 -08001637 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001638}
1639
Elliott Hughes221229c2013-01-08 18:17:50 -08001640JDWP::JdwpError Dbg::GetThreadDebugSuspendCount(JDWP::ObjectId thread_id, JDWP::ExpandBuf* pReply) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001641 ScopedObjectAccess soa(Thread::Current());
Ian Rogers50b35e22012-10-04 10:09:15 -07001642 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001643 Thread* thread;
1644 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1645 if (error != JDWP::ERR_NONE) {
1646 return error;
Elliott Hughes2435a572012-02-17 16:07:41 -08001647 }
Ian Rogers50b35e22012-10-04 10:09:15 -07001648 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001649 expandBufAdd4BE(pReply, thread->GetDebugSuspendCount());
Elliott Hughes2435a572012-02-17 16:07:41 -08001650 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001651}
1652
Elliott Hughesf9501702013-01-11 11:22:27 -08001653JDWP::JdwpError Dbg::Interrupt(JDWP::ObjectId thread_id) {
1654 ScopedObjectAccess soa(Thread::Current());
1655 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
1656 Thread* thread;
1657 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1658 if (error != JDWP::ERR_NONE) {
1659 return error;
1660 }
1661 thread->Interrupt();
1662 return JDWP::ERR_NONE;
1663}
1664
Elliott Hughescaf76542012-06-28 16:08:22 -07001665void Dbg::GetThreads(JDWP::ObjectId thread_group_id, std::vector<JDWP::ObjectId>& thread_ids) {
Ian Rogers365c1022012-06-22 15:05:28 -07001666 class ThreadListVisitor {
1667 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001668 ThreadListVisitor(const ScopedObjectAccessUnchecked& soa, mirror::Object* desired_thread_group,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001669 std::vector<JDWP::ObjectId>& thread_ids)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001670 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
jeffhao0dfbb7e2012-11-28 15:26:03 -08001671 : soa_(soa), desired_thread_group_(desired_thread_group), thread_ids_(thread_ids) {}
Ian Rogers365c1022012-06-22 15:05:28 -07001672
Elliott Hughesa2155262011-11-16 16:26:58 -08001673 static void Visit(Thread* t, void* arg) {
1674 reinterpret_cast<ThreadListVisitor*>(arg)->Visit(t);
1675 }
1676
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001677 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1678 // annotalysis.
1679 void Visit(Thread* t) NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughesa2155262011-11-16 16:26:58 -08001680 if (t == Dbg::GetDebugThread()) {
1681 // Skip the JDWP thread. Some debuggers get bent out of shape when they can't suspend and
1682 // query all threads, so it's easier if we just don't tell them about this thread.
1683 return;
1684 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001685 mirror::Object* peer = t->GetPeer();
jeffhao0dfbb7e2012-11-28 15:26:03 -08001686 if (IsInDesiredThreadGroup(peer)) {
Ian Rogers120f1c72012-09-28 17:17:10 -07001687 thread_ids_.push_back(gRegistry->Add(peer));
Elliott Hughesa2155262011-11-16 16:26:58 -08001688 }
1689 }
1690
Ian Rogers365c1022012-06-22 15:05:28 -07001691 private:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001692 bool IsInDesiredThreadGroup(mirror::Object* peer)
jeffhao0dfbb7e2012-11-28 15:26:03 -08001693 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
jeffhao0dfbb7e2012-11-28 15:26:03 -08001694 // peer might be NULL if the thread is still starting up.
1695 if (peer == NULL) {
1696 // We can't tell the debugger about this thread yet.
1697 // TODO: if we identified threads to the debugger by their Thread*
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001698 // rather than their peer's mirror::Object*, we could fix this.
jeffhao0dfbb7e2012-11-28 15:26:03 -08001699 // Doing so might help us report ZOMBIE threads too.
1700 return false;
1701 }
jeffhaoc1e04902012-12-13 12:41:10 -08001702 // Do we want threads from all thread groups?
1703 if (desired_thread_group_ == NULL) {
1704 return true;
1705 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001706 mirror::Object* group = soa_.DecodeField(WellKnownClasses::java_lang_Thread_group)->GetObject(peer);
jeffhao0dfbb7e2012-11-28 15:26:03 -08001707 return (group == desired_thread_group_);
1708 }
1709
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07001710 const ScopedObjectAccessUnchecked& soa_;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001711 mirror::Object* const desired_thread_group_;
Elliott Hughescaf76542012-06-28 16:08:22 -07001712 std::vector<JDWP::ObjectId>& thread_ids_;
Elliott Hughesa2155262011-11-16 16:26:58 -08001713 };
1714
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001715 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001716 mirror::Object* thread_group = gRegistry->Get<mirror::Object*>(thread_group_id);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001717 ThreadListVisitor tlv(soa, thread_group, thread_ids);
Ian Rogers50b35e22012-10-04 10:09:15 -07001718 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughesf8349362012-06-18 15:00:06 -07001719 Runtime::Current()->GetThreadList()->ForEach(ThreadListVisitor::Visit, &tlv);
Elliott Hughescaf76542012-06-28 16:08:22 -07001720}
Elliott Hughesa2155262011-11-16 16:26:58 -08001721
Elliott Hughescaf76542012-06-28 16:08:22 -07001722void Dbg::GetChildThreadGroups(JDWP::ObjectId thread_group_id, std::vector<JDWP::ObjectId>& child_thread_group_ids) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001723 ScopedObjectAccess soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001724 mirror::Object* thread_group = gRegistry->Get<mirror::Object*>(thread_group_id);
Elliott Hughescaf76542012-06-28 16:08:22 -07001725
1726 // Get the ArrayList<ThreadGroup> "groups" out of this thread group...
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001727 mirror::Field* groups_field = thread_group->GetClass()->FindInstanceField("groups", "Ljava/util/List;");
1728 mirror::Object* groups_array_list = groups_field->GetObject(thread_group);
Elliott Hughescaf76542012-06-28 16:08:22 -07001729
1730 // Get the array and size out of the ArrayList<ThreadGroup>...
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001731 mirror::Field* array_field = groups_array_list->GetClass()->FindInstanceField("array", "[Ljava/lang/Object;");
1732 mirror::Field* size_field = groups_array_list->GetClass()->FindInstanceField("size", "I");
1733 mirror::ObjectArray<mirror::Object>* groups_array =
1734 array_field->GetObject(groups_array_list)->AsObjectArray<mirror::Object>();
Elliott Hughescaf76542012-06-28 16:08:22 -07001735 const int32_t size = size_field->GetInt(groups_array_list);
1736
1737 // Copy the first 'size' elements out of the array into the result.
1738 for (int32_t i = 0; i < size; ++i) {
1739 child_thread_group_ids.push_back(gRegistry->Add(groups_array->Get(i)));
Elliott Hughesa2155262011-11-16 16:26:58 -08001740 }
1741}
1742
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001743static int GetStackDepth(Thread* thread)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001744 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers0399dde2012-06-06 17:09:28 -07001745 struct CountStackDepthVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -08001746 CountStackDepthVisitor(Thread* thread)
1747 : StackVisitor(thread, NULL), depth(0) {}
Ian Rogers0399dde2012-06-06 17:09:28 -07001748
Elliott Hughes64f574f2013-02-20 14:57:12 -08001749 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1750 // annotalysis.
1751 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07001752 if (!GetMethod()->IsRuntimeMethod()) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -08001753 ++depth;
1754 }
Elliott Hughes530fa002012-03-12 11:44:49 -07001755 return true;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001756 }
1757 size_t depth;
1758 };
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001759
Ian Rogers7a22fa62013-01-23 12:16:16 -08001760 CountStackDepthVisitor visitor(thread);
Ian Rogers0399dde2012-06-06 17:09:28 -07001761 visitor.WalkStack();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001762 return visitor.depth;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001763}
1764
Elliott Hughes221229c2013-01-08 18:17:50 -08001765JDWP::JdwpError Dbg::GetThreadFrameCount(JDWP::ObjectId thread_id, size_t& result) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001766 ScopedObjectAccess soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08001767 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001768 Thread* thread;
1769 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1770 if (error != JDWP::ERR_NONE) {
1771 return error;
1772 }
Elliott Hughesf15f4a02013-01-09 10:09:38 -08001773 if (!IsSuspendedForDebugger(soa, thread)) {
1774 return JDWP::ERR_THREAD_NOT_SUSPENDED;
1775 }
Elliott Hughes221229c2013-01-08 18:17:50 -08001776 result = GetStackDepth(thread);
1777 return JDWP::ERR_NONE;
Elliott Hughes86964332012-02-15 19:37:42 -08001778}
1779
Ian Rogers306057f2012-11-26 12:45:53 -08001780JDWP::JdwpError Dbg::GetThreadFrames(JDWP::ObjectId thread_id, size_t start_frame,
1781 size_t frame_count, JDWP::ExpandBuf* buf) {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001782 class GetFrameVisitor : public StackVisitor {
1783 public:
Ian Rogers7a22fa62013-01-23 12:16:16 -08001784 GetFrameVisitor(Thread* thread, size_t start_frame, size_t frame_count, JDWP::ExpandBuf* buf)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001785 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08001786 : StackVisitor(thread, NULL), depth_(0),
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001787 start_frame_(start_frame), frame_count_(frame_count), buf_(buf) {
1788 expandBufAdd4BE(buf_, frame_count_);
Elliott Hughes03181a82011-11-17 17:22:21 -08001789 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001790
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001791 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1792 // annotalysis.
1793 virtual bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07001794 if (GetMethod()->IsRuntimeMethod()) {
Elliott Hughes530fa002012-03-12 11:44:49 -07001795 return true; // The debugger can't do anything useful with a frame that has no Method*.
Elliott Hughes03181a82011-11-17 17:22:21 -08001796 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001797 if (depth_ >= start_frame_ + frame_count_) {
Elliott Hughes530fa002012-03-12 11:44:49 -07001798 return false;
Elliott Hughes03181a82011-11-17 17:22:21 -08001799 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001800 if (depth_ >= start_frame_) {
1801 JDWP::FrameId frame_id(GetFrameId());
1802 JDWP::JdwpLocation location;
1803 SetLocation(location, GetMethod(), GetDexPc());
Elliott Hughes7baf96f2012-06-22 16:33:50 -07001804 VLOG(jdwp) << StringPrintf(" Frame %3zd: id=%3lld ", depth_, frame_id) << location;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001805 expandBufAdd8BE(buf_, frame_id);
1806 expandBufAddLocation(buf_, location);
1807 }
1808 ++depth_;
Elliott Hughes530fa002012-03-12 11:44:49 -07001809 return true;
Elliott Hughes03181a82011-11-17 17:22:21 -08001810 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001811
1812 private:
1813 size_t depth_;
1814 const size_t start_frame_;
1815 const size_t frame_count_;
1816 JDWP::ExpandBuf* buf_;
Elliott Hughes03181a82011-11-17 17:22:21 -08001817 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001818
1819 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08001820 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001821 Thread* thread;
1822 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1823 if (error != JDWP::ERR_NONE) {
1824 return error;
1825 }
Elliott Hughesf15f4a02013-01-09 10:09:38 -08001826 if (!IsSuspendedForDebugger(soa, thread)) {
1827 return JDWP::ERR_THREAD_NOT_SUSPENDED;
1828 }
Ian Rogers7a22fa62013-01-23 12:16:16 -08001829 GetFrameVisitor visitor(thread, start_frame, frame_count, buf);
Ian Rogers0399dde2012-06-06 17:09:28 -07001830 visitor.WalkStack();
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001831 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001832}
1833
1834JDWP::ObjectId Dbg::GetThreadSelfId() {
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07001835 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogerscfaa4552012-11-26 21:00:08 -08001836 return gRegistry->Add(soa.Self()->GetPeer());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001837}
1838
Elliott Hughes475fc232011-10-25 15:00:35 -07001839void Dbg::SuspendVM() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001840 Runtime::Current()->GetThreadList()->SuspendAllForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001841}
1842
1843void Dbg::ResumeVM() {
Elliott Hughesc61a2672012-06-21 14:52:29 -07001844 Runtime::Current()->GetThreadList()->UndoDebuggerSuspensions();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001845}
1846
Elliott Hughes221229c2013-01-08 18:17:50 -08001847JDWP::JdwpError Dbg::SuspendThread(JDWP::ObjectId thread_id, bool request_suspension) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001848 ScopedLocalRef<jobject> peer(Thread::Current()->GetJniEnv(), NULL);
1849 {
1850 ScopedObjectAccess soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001851 peer.reset(soa.AddLocalReference<jobject>(gRegistry->Get<mirror::Object*>(thread_id)));
Elliott Hughes4e235312011-12-02 11:34:15 -08001852 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001853 if (peer.get() == NULL) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001854 return JDWP::ERR_THREAD_NOT_ALIVE;
1855 }
1856 // Suspend thread to build stack trace.
Elliott Hughesf327e072013-01-09 16:01:26 -08001857 bool timed_out;
1858 Thread* thread = Thread::SuspendForDebugger(peer.get(), request_suspension, &timed_out);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001859 if (thread != NULL) {
1860 return JDWP::ERR_NONE;
Elliott Hughesf327e072013-01-09 16:01:26 -08001861 } else if (timed_out) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001862 return JDWP::ERR_INTERNAL;
1863 } else {
1864 return JDWP::ERR_THREAD_NOT_ALIVE;
1865 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001866}
1867
Elliott Hughes221229c2013-01-08 18:17:50 -08001868void Dbg::ResumeThread(JDWP::ObjectId thread_id) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001869 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001870 mirror::Object* peer = gRegistry->Get<mirror::Object*>(thread_id);
jeffhaoa77f0f62012-12-05 17:19:31 -08001871 Thread* thread;
1872 {
1873 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
1874 thread = Thread::FromManagedThread(soa, peer);
1875 }
Elliott Hughes4e235312011-12-02 11:34:15 -08001876 if (thread == NULL) {
1877 LOG(WARNING) << "No such thread for resume: " << peer;
1878 return;
1879 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001880 bool needs_resume;
1881 {
Ian Rogers50b35e22012-10-04 10:09:15 -07001882 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001883 needs_resume = thread->GetSuspendCount() > 0;
1884 }
1885 if (needs_resume) {
Elliott Hughes546b9862012-06-20 16:06:13 -07001886 Runtime::Current()->GetThreadList()->Resume(thread, true);
1887 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001888}
1889
1890void Dbg::SuspendSelf() {
Elliott Hughes475fc232011-10-25 15:00:35 -07001891 Runtime::Current()->GetThreadList()->SuspendSelfForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001892}
1893
Ian Rogers0399dde2012-06-06 17:09:28 -07001894struct GetThisVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -08001895 GetThisVisitor(Thread* thread, Context* context, JDWP::FrameId frame_id)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001896 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08001897 : StackVisitor(thread, context), this_object(NULL), frame_id(frame_id) {}
Ian Rogers0399dde2012-06-06 17:09:28 -07001898
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001899 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1900 // annotalysis.
1901 virtual bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001902 if (frame_id != GetFrameId()) {
Ian Rogers0399dde2012-06-06 17:09:28 -07001903 return true; // continue
1904 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001905 mirror::AbstractMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07001906 if (m->IsNative() || m->IsStatic()) {
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001907 this_object = NULL;
Ian Rogers0399dde2012-06-06 17:09:28 -07001908 } else {
1909 uint16_t reg = DemangleSlot(0, m);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001910 this_object = reinterpret_cast<mirror::Object*>(GetVReg(m, reg, kReferenceVReg));
Ian Rogers0399dde2012-06-06 17:09:28 -07001911 }
1912 return false;
Elliott Hughes86b00102011-12-05 17:54:26 -08001913 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001914
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001915 mirror::Object* this_object;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001916 JDWP::FrameId frame_id;
Ian Rogers0399dde2012-06-06 17:09:28 -07001917};
1918
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001919static mirror::Object* GetThis(Thread* self, mirror::AbstractMethod* m, size_t frame_id)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001920 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughescaf76542012-06-28 16:08:22 -07001921 // TODO: should we return the 'this' we passed through to non-static native methods?
Ian Rogers0399dde2012-06-06 17:09:28 -07001922 if (m->IsNative() || m->IsStatic()) {
1923 return NULL;
1924 }
Elliott Hughescaf76542012-06-28 16:08:22 -07001925
Ian Rogers0399dde2012-06-06 17:09:28 -07001926 UniquePtr<Context> context(Context::Create());
Ian Rogers7a22fa62013-01-23 12:16:16 -08001927 GetThisVisitor visitor(self, context.get(), frame_id);
Elliott Hughescaf76542012-06-28 16:08:22 -07001928 visitor.WalkStack();
1929 return visitor.this_object;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001930}
1931
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001932JDWP::JdwpError Dbg::GetThisObject(JDWP::ObjectId thread_id, JDWP::FrameId frame_id,
1933 JDWP::ObjectId* result) {
1934 ScopedObjectAccessUnchecked soa(Thread::Current());
1935 Thread* thread;
1936 {
Ian Rogers50b35e22012-10-04 10:09:15 -07001937 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08001938 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
1939 if (error != JDWP::ERR_NONE) {
1940 return error;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001941 }
Elliott Hughes9e0c1752013-01-09 14:02:58 -08001942 if (!IsSuspendedForDebugger(soa, thread)) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001943 return JDWP::ERR_THREAD_NOT_SUSPENDED;
1944 }
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001945 }
Elliott Hughescaf76542012-06-28 16:08:22 -07001946 UniquePtr<Context> context(Context::Create());
Ian Rogers7a22fa62013-01-23 12:16:16 -08001947 GetThisVisitor visitor(thread, context.get(), frame_id);
Ian Rogers0399dde2012-06-06 17:09:28 -07001948 visitor.WalkStack();
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001949 *result = gRegistry->Add(visitor.this_object);
1950 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001951}
1952
Elliott Hughes88d63092013-01-09 09:55:54 -08001953void Dbg::GetLocalValue(JDWP::ObjectId thread_id, JDWP::FrameId frame_id, int slot, JDWP::JdwpTag tag,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001954 uint8_t* buf, size_t width) {
Ian Rogers0399dde2012-06-06 17:09:28 -07001955 struct GetLocalVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -08001956 GetLocalVisitor(Thread* thread, Context* context, JDWP::FrameId frame_id, int slot,
1957 JDWP::JdwpTag tag, uint8_t* buf, size_t width)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001958 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08001959 : StackVisitor(thread, context), frame_id_(frame_id), slot_(slot), tag_(tag),
Ian Rogersca190662012-06-26 15:45:57 -07001960 buf_(buf), width_(width) {}
1961
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001962 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
1963 // annotalysis.
1964 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07001965 if (GetFrameId() != frame_id_) {
1966 return true; // Not our frame, carry on.
Elliott Hughesdbb40792011-11-18 17:05:22 -08001967 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001968 // TODO: check that the tag is compatible with the actual type of the slot!
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001969 mirror::AbstractMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07001970 uint16_t reg = DemangleSlot(slot_, m);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001971
Ian Rogers0399dde2012-06-06 17:09:28 -07001972 switch (tag_) {
1973 case JDWP::JT_BOOLEAN:
1974 {
1975 CHECK_EQ(width_, 1U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001976 uint32_t intVal = GetVReg(m, reg, kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07001977 VLOG(jdwp) << "get boolean local " << reg << " = " << intVal;
1978 JDWP::Set1(buf_+1, intVal != 0);
1979 }
1980 break;
1981 case JDWP::JT_BYTE:
1982 {
1983 CHECK_EQ(width_, 1U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001984 uint32_t intVal = GetVReg(m, reg, kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07001985 VLOG(jdwp) << "get byte local " << reg << " = " << intVal;
1986 JDWP::Set1(buf_+1, intVal);
1987 }
1988 break;
1989 case JDWP::JT_SHORT:
1990 case JDWP::JT_CHAR:
1991 {
1992 CHECK_EQ(width_, 2U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001993 uint32_t intVal = GetVReg(m, reg, kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07001994 VLOG(jdwp) << "get short/char local " << reg << " = " << intVal;
1995 JDWP::Set2BE(buf_+1, intVal);
1996 }
1997 break;
1998 case JDWP::JT_INT:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001999 {
2000 CHECK_EQ(width_, 4U);
2001 uint32_t intVal = GetVReg(m, reg, kIntVReg);
2002 VLOG(jdwp) << "get int local " << reg << " = " << intVal;
2003 JDWP::Set4BE(buf_+1, intVal);
2004 }
2005 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002006 case JDWP::JT_FLOAT:
2007 {
2008 CHECK_EQ(width_, 4U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002009 uint32_t intVal = GetVReg(m, reg, kFloatVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002010 VLOG(jdwp) << "get int/float local " << reg << " = " << intVal;
2011 JDWP::Set4BE(buf_+1, intVal);
2012 }
2013 break;
2014 case JDWP::JT_ARRAY:
2015 {
2016 CHECK_EQ(width_, sizeof(JDWP::ObjectId));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002017 mirror::Object* o = reinterpret_cast<mirror::Object*>(GetVReg(m, reg, kReferenceVReg));
Ian Rogers0399dde2012-06-06 17:09:28 -07002018 VLOG(jdwp) << "get array local " << reg << " = " << o;
2019 if (!Runtime::Current()->GetHeap()->IsHeapAddress(o)) {
2020 LOG(FATAL) << "Register " << reg << " expected to hold array: " << o;
2021 }
2022 JDWP::SetObjectId(buf_+1, gRegistry->Add(o));
2023 }
2024 break;
2025 case JDWP::JT_CLASS_LOADER:
2026 case JDWP::JT_CLASS_OBJECT:
2027 case JDWP::JT_OBJECT:
2028 case JDWP::JT_STRING:
2029 case JDWP::JT_THREAD:
2030 case JDWP::JT_THREAD_GROUP:
2031 {
2032 CHECK_EQ(width_, sizeof(JDWP::ObjectId));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002033 mirror::Object* o = reinterpret_cast<mirror::Object*>(GetVReg(m, reg, kReferenceVReg));
Ian Rogers0399dde2012-06-06 17:09:28 -07002034 VLOG(jdwp) << "get object local " << reg << " = " << o;
2035 if (!Runtime::Current()->GetHeap()->IsHeapAddress(o)) {
2036 LOG(FATAL) << "Register " << reg << " expected to hold object: " << o;
2037 }
2038 tag_ = TagFromObject(o);
2039 JDWP::SetObjectId(buf_+1, gRegistry->Add(o));
2040 }
2041 break;
2042 case JDWP::JT_DOUBLE:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002043 {
2044 CHECK_EQ(width_, 8U);
2045 uint32_t lo = GetVReg(m, reg, kDoubleLoVReg);
2046 uint64_t hi = GetVReg(m, reg + 1, kDoubleHiVReg);
2047 uint64_t longVal = (hi << 32) | lo;
2048 VLOG(jdwp) << "get double/long local " << hi << ":" << lo << " = " << longVal;
2049 JDWP::Set8BE(buf_+1, longVal);
2050 }
2051 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002052 case JDWP::JT_LONG:
2053 {
2054 CHECK_EQ(width_, 8U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002055 uint32_t lo = GetVReg(m, reg, kLongLoVReg);
2056 uint64_t hi = GetVReg(m, reg + 1, kLongHiVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002057 uint64_t longVal = (hi << 32) | lo;
2058 VLOG(jdwp) << "get double/long local " << hi << ":" << lo << " = " << longVal;
2059 JDWP::Set8BE(buf_+1, longVal);
2060 }
2061 break;
2062 default:
2063 LOG(FATAL) << "Unknown tag " << tag_;
2064 break;
2065 }
2066
2067 // Prepend tag, which may have been updated.
2068 JDWP::Set1(buf_, tag_);
2069 return false;
2070 }
2071
2072 const JDWP::FrameId frame_id_;
2073 const int slot_;
2074 JDWP::JdwpTag tag_;
2075 uint8_t* const buf_;
2076 const size_t width_;
2077 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002078
2079 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08002080 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002081 Thread* thread;
2082 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
2083 if (error != JDWP::ERR_NONE) {
2084 return;
2085 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002086 UniquePtr<Context> context(Context::Create());
Ian Rogers7a22fa62013-01-23 12:16:16 -08002087 GetLocalVisitor visitor(thread, context.get(), frame_id, slot, tag, buf, width);
Ian Rogers0399dde2012-06-06 17:09:28 -07002088 visitor.WalkStack();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002089}
2090
Elliott Hughes88d63092013-01-09 09:55:54 -08002091void Dbg::SetLocalValue(JDWP::ObjectId thread_id, JDWP::FrameId frame_id, int slot, JDWP::JdwpTag tag,
Ian Rogers0399dde2012-06-06 17:09:28 -07002092 uint64_t value, size_t width) {
2093 struct SetLocalVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -08002094 SetLocalVisitor(Thread* thread, Context* context,
Ian Rogers0399dde2012-06-06 17:09:28 -07002095 JDWP::FrameId frame_id, int slot, JDWP::JdwpTag tag, uint64_t value,
Ian Rogersca190662012-06-26 15:45:57 -07002096 size_t width)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002097 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08002098 : StackVisitor(thread, context),
Elliott Hughes08fc03a2012-06-26 17:34:00 -07002099 frame_id_(frame_id), slot_(slot), tag_(tag), value_(value), width_(width) {}
Ian Rogersca190662012-06-26 15:45:57 -07002100
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002101 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2102 // annotalysis.
2103 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers0399dde2012-06-06 17:09:28 -07002104 if (GetFrameId() != frame_id_) {
2105 return true; // Not our frame, carry on.
2106 }
2107 // TODO: check that the tag is compatible with the actual type of the slot!
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002108 mirror::AbstractMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07002109 uint16_t reg = DemangleSlot(slot_, m);
2110
2111 switch (tag_) {
2112 case JDWP::JT_BOOLEAN:
2113 case JDWP::JT_BYTE:
2114 CHECK_EQ(width_, 1U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002115 SetVReg(m, reg, static_cast<uint32_t>(value_), kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002116 break;
2117 case JDWP::JT_SHORT:
2118 case JDWP::JT_CHAR:
2119 CHECK_EQ(width_, 2U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002120 SetVReg(m, reg, static_cast<uint32_t>(value_), kIntVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002121 break;
2122 case JDWP::JT_INT:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002123 CHECK_EQ(width_, 4U);
2124 SetVReg(m, reg, static_cast<uint32_t>(value_), kIntVReg);
2125 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002126 case JDWP::JT_FLOAT:
2127 CHECK_EQ(width_, 4U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002128 SetVReg(m, reg, static_cast<uint32_t>(value_), kFloatVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002129 break;
2130 case JDWP::JT_ARRAY:
2131 case JDWP::JT_OBJECT:
2132 case JDWP::JT_STRING:
2133 {
2134 CHECK_EQ(width_, sizeof(JDWP::ObjectId));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002135 mirror::Object* o = gRegistry->Get<mirror::Object*>(static_cast<JDWP::ObjectId>(value_));
Elliott Hughes64f574f2013-02-20 14:57:12 -08002136 if (o == ObjectRegistry::kInvalidObject) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002137 UNIMPLEMENTED(FATAL) << "return an error code when given an invalid object to store";
2138 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002139 SetVReg(m, reg, static_cast<uint32_t>(reinterpret_cast<uintptr_t>(o)), kReferenceVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002140 }
2141 break;
2142 case JDWP::JT_DOUBLE:
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002143 CHECK_EQ(width_, 8U);
2144 SetVReg(m, reg, static_cast<uint32_t>(value_), kDoubleLoVReg);
2145 SetVReg(m, reg + 1, static_cast<uint32_t>(value_ >> 32), kDoubleHiVReg);
2146 break;
Ian Rogers0399dde2012-06-06 17:09:28 -07002147 case JDWP::JT_LONG:
2148 CHECK_EQ(width_, 8U);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002149 SetVReg(m, reg, static_cast<uint32_t>(value_), kLongLoVReg);
2150 SetVReg(m, reg + 1, static_cast<uint32_t>(value_ >> 32), kLongHiVReg);
Ian Rogers0399dde2012-06-06 17:09:28 -07002151 break;
2152 default:
2153 LOG(FATAL) << "Unknown tag " << tag_;
2154 break;
2155 }
2156 return false;
2157 }
2158
2159 const JDWP::FrameId frame_id_;
2160 const int slot_;
2161 const JDWP::JdwpTag tag_;
2162 const uint64_t value_;
2163 const size_t width_;
2164 };
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002165
2166 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08002167 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002168 Thread* thread;
2169 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
2170 if (error != JDWP::ERR_NONE) {
2171 return;
2172 }
Elliott Hughes08fc03a2012-06-26 17:34:00 -07002173 UniquePtr<Context> context(Context::Create());
Ian Rogers7a22fa62013-01-23 12:16:16 -08002174 SetLocalVisitor visitor(thread, context.get(), frame_id, slot, tag, value, width);
Ian Rogers0399dde2012-06-06 17:09:28 -07002175 visitor.WalkStack();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002176}
2177
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002178void Dbg::PostLocationEvent(const mirror::AbstractMethod* m, int dex_pc, mirror::Object* this_object, int event_flags) {
2179 mirror::Class* c = m->GetDeclaringClass();
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002180
2181 JDWP::JdwpLocation location;
Elliott Hughes74847412012-06-20 18:10:21 -07002182 location.type_tag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
Elliott Hughes64f574f2013-02-20 14:57:12 -08002183 location.class_id = gRegistry->AddRefType(c);
Elliott Hughes74847412012-06-20 18:10:21 -07002184 location.method_id = ToMethodId(m);
Elliott Hughes972a47b2012-02-21 18:16:06 -08002185 location.dex_pc = m->IsNative() ? -1 : dex_pc;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002186
Elliott Hughes64f574f2013-02-20 14:57:12 -08002187 // If 'this_object' isn't already in the registry, we know that we're not looking for it,
2188 // so there's no point adding it to the registry and burning through ids.
2189 JDWP::ObjectId this_id = 0;
2190 if (gRegistry->Contains(this_object)) {
2191 this_id = gRegistry->Add(this_object);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002192 }
Elliott Hughes64f574f2013-02-20 14:57:12 -08002193 gJdwpState->PostLocationEvent(&location, this_id, event_flags);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002194}
2195
Elliott Hughescaf76542012-06-28 16:08:22 -07002196void Dbg::PostException(Thread* thread,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002197 JDWP::FrameId throw_frame_id, mirror::AbstractMethod* throw_method,
2198 uint32_t throw_dex_pc, mirror::AbstractMethod* catch_method,
Elliott Hughes64f574f2013-02-20 14:57:12 -08002199 uint32_t catch_dex_pc, mirror::Throwable* exception_object) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002200 if (!IsDebuggerActive()) {
Ian Rogers0ad5bb82011-12-07 10:16:32 -08002201 return;
2202 }
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002203
Elliott Hughesd07986f2011-12-06 18:27:45 -08002204 JDWP::JdwpLocation throw_location;
Elliott Hughescaf76542012-06-28 16:08:22 -07002205 SetLocation(throw_location, throw_method, throw_dex_pc);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002206 JDWP::JdwpLocation catch_location;
Elliott Hughescaf76542012-06-28 16:08:22 -07002207 SetLocation(catch_location, catch_method, catch_dex_pc);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002208
2209 // We need 'this' for InstanceOnly filters.
Elliott Hughescaf76542012-06-28 16:08:22 -07002210 UniquePtr<Context> context(Context::Create());
Ian Rogers7a22fa62013-01-23 12:16:16 -08002211 GetThisVisitor visitor(thread, context.get(), throw_frame_id);
Elliott Hughescaf76542012-06-28 16:08:22 -07002212 visitor.WalkStack();
2213 JDWP::ObjectId this_id = gRegistry->Add(visitor.this_object);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002214
Elliott Hughes64f574f2013-02-20 14:57:12 -08002215 JDWP::ObjectId exception_id = gRegistry->Add(exception_object);
2216 JDWP::RefTypeId exception_class_id = gRegistry->AddRefType(exception_object->GetClass());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002217
2218 gJdwpState->PostException(&throw_location, exception_id, exception_class_id, &catch_location, this_id);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002219}
2220
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002221void Dbg::PostClassPrepare(mirror::Class* c) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002222 if (!IsDebuggerActive()) {
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002223 return;
2224 }
2225
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08002226 // OLD-TODO - we currently always send both "verified" and "prepared" since
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002227 // debuggers seem to like that. There might be some advantage to honesty,
2228 // since the class may not yet be verified.
2229 int state = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
2230 JDWP::JdwpTypeTag tag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
2231 gJdwpState->PostClassPrepare(tag, gRegistry->Add(c), ClassHelper(c).GetDescriptor(), state);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002232}
2233
Elliott Hughescaf76542012-06-28 16:08:22 -07002234void Dbg::UpdateDebugger(int32_t dex_pc, Thread* self) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002235 if (!IsDebuggerActive() || dex_pc == -2 /* fake method exit */) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002236 return;
2237 }
2238
Elliott Hughescaf76542012-06-28 16:08:22 -07002239 size_t frame_id;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002240 mirror::AbstractMethod* m = self->GetCurrentMethod(NULL, &frame_id);
Elliott Hughescaf76542012-06-28 16:08:22 -07002241 //LOG(INFO) << "UpdateDebugger " << PrettyMethod(m) << "@" << dex_pc << " frame " << frame_id;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002242
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002243 if (dex_pc == -1) {
Elliott Hughes2aa2e392012-02-17 17:15:43 -08002244 // We use a pc of -1 to represent method entry, since we might branch back to pc 0 later.
2245 // This means that for this special notification, there can't be anything else interesting
2246 // going on, so we're done already.
Elliott Hughescaf76542012-06-28 16:08:22 -07002247 Dbg::PostLocationEvent(m, 0, GetThis(self, m, frame_id), kMethodEntry);
Elliott Hughes2aa2e392012-02-17 17:15:43 -08002248 return;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002249 }
2250
Elliott Hughes2aa2e392012-02-17 17:15:43 -08002251 int event_flags = 0;
2252
Elliott Hughes86964332012-02-15 19:37:42 -08002253 if (IsBreakpoint(m, dex_pc)) {
2254 event_flags |= kBreakpoint;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002255 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002256
jeffhao09bfc6a2012-12-11 18:11:43 -08002257 {
2258 // If the debugger is single-stepping one of our threads, check to
2259 // see if we're that thread and we've reached a step point.
2260 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
2261 if (gSingleStepControl.is_active && gSingleStepControl.thread == self) {
2262 CHECK(!m->IsNative());
2263 if (gSingleStepControl.step_depth == JDWP::SD_INTO) {
2264 // Step into method calls. We break when the line number
2265 // or method pointer changes. If we're in SS_MIN mode, we
2266 // always stop.
2267 if (gSingleStepControl.method != m) {
2268 event_flags |= kSingleStep;
2269 VLOG(jdwp) << "SS new method";
2270 } else if (gSingleStepControl.step_size == JDWP::SS_MIN) {
Elliott Hughes86964332012-02-15 19:37:42 -08002271 event_flags |= kSingleStep;
2272 VLOG(jdwp) << "SS new instruction";
Elliott Hughes2435a572012-02-17 16:07:41 -08002273 } else if (gSingleStepControl.dex_pcs.find(dex_pc) == gSingleStepControl.dex_pcs.end()) {
2274 event_flags |= kSingleStep;
2275 VLOG(jdwp) << "SS new line";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002276 }
jeffhao09bfc6a2012-12-11 18:11:43 -08002277 } else if (gSingleStepControl.step_depth == JDWP::SD_OVER) {
2278 // Step over method calls. We break when the line number is
2279 // different and the frame depth is <= the original frame
2280 // depth. (We can't just compare on the method, because we
2281 // might get unrolled past it by an exception, and it's tricky
2282 // to identify recursion.)
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002283
jeffhao09bfc6a2012-12-11 18:11:43 -08002284 int stack_depth = GetStackDepth(self);
Elliott Hughes86964332012-02-15 19:37:42 -08002285
jeffhao09bfc6a2012-12-11 18:11:43 -08002286 if (stack_depth < gSingleStepControl.stack_depth) {
2287 // popped up one or more frames, always trigger
2288 event_flags |= kSingleStep;
2289 VLOG(jdwp) << "SS method pop";
2290 } else if (stack_depth == gSingleStepControl.stack_depth) {
2291 // same depth, see if we moved
2292 if (gSingleStepControl.step_size == JDWP::SS_MIN) {
2293 event_flags |= kSingleStep;
2294 VLOG(jdwp) << "SS new instruction";
2295 } else if (gSingleStepControl.dex_pcs.find(dex_pc) == gSingleStepControl.dex_pcs.end()) {
2296 event_flags |= kSingleStep;
2297 VLOG(jdwp) << "SS new line";
2298 }
2299 }
2300 } else {
2301 CHECK_EQ(gSingleStepControl.step_depth, JDWP::SD_OUT);
2302 // Return from the current method. We break when the frame
2303 // depth pops up.
2304
2305 // This differs from the "method exit" break in that it stops
2306 // with the PC at the next instruction in the returned-to
2307 // function, rather than the end of the returning function.
2308
2309 int stack_depth = GetStackDepth(self);
2310 if (stack_depth < gSingleStepControl.stack_depth) {
2311 event_flags |= kSingleStep;
2312 VLOG(jdwp) << "SS method pop";
2313 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002314 }
2315 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002316 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002317
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002318 // Check to see if this is a "return" instruction. JDWP says we should
2319 // send the event *after* the code has been executed, but it also says
2320 // the location we provide is the last instruction. Since the "return"
2321 // instruction has no interesting side effects, we should be safe.
2322 // (We can't just move this down to the returnFromMethod label because
2323 // we potentially need to combine it with other events.)
2324 // We're also not supposed to generate a method exit event if the method
2325 // terminates "with a thrown exception".
Elliott Hughes86964332012-02-15 19:37:42 -08002326 if (dex_pc >= 0) {
2327 const DexFile::CodeItem* code_item = MethodHelper(m).GetCodeItem();
Elliott Hughescaf76542012-06-28 16:08:22 -07002328 CHECK(code_item != NULL) << PrettyMethod(m) << " @" << dex_pc;
Elliott Hughes86964332012-02-15 19:37:42 -08002329 CHECK_LT(dex_pc, static_cast<int32_t>(code_item->insns_size_in_code_units_));
2330 if (Instruction::At(&code_item->insns_[dex_pc])->IsReturn()) {
2331 event_flags |= kMethodExit;
2332 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002333 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002334
2335 // If there's something interesting going on, see if it matches one
2336 // of the debugger filters.
2337 if (event_flags != 0) {
Elliott Hughescaf76542012-06-28 16:08:22 -07002338 Dbg::PostLocationEvent(m, dex_pc, GetThis(self, m, frame_id), event_flags);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08002339 }
2340}
2341
Elliott Hughes86964332012-02-15 19:37:42 -08002342void Dbg::WatchLocation(const JDWP::JdwpLocation* location) {
jeffhao09bfc6a2012-12-11 18:11:43 -08002343 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002344 mirror::AbstractMethod* m = FromMethodId(location->method_id);
Elliott Hughes972a47b2012-02-21 18:16:06 -08002345 gBreakpoints.push_back(Breakpoint(m, location->dex_pc));
Elliott Hughes86964332012-02-15 19:37:42 -08002346 VLOG(jdwp) << "Set breakpoint #" << (gBreakpoints.size() - 1) << ": " << gBreakpoints[gBreakpoints.size() - 1];
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002347}
2348
Elliott Hughes86964332012-02-15 19:37:42 -08002349void Dbg::UnwatchLocation(const JDWP::JdwpLocation* location) {
jeffhao09bfc6a2012-12-11 18:11:43 -08002350 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002351 mirror::AbstractMethod* m = FromMethodId(location->method_id);
Elliott Hughes86964332012-02-15 19:37:42 -08002352 for (size_t i = 0; i < gBreakpoints.size(); ++i) {
Elliott Hughes972a47b2012-02-21 18:16:06 -08002353 if (gBreakpoints[i].method == m && gBreakpoints[i].dex_pc == location->dex_pc) {
Elliott Hughes86964332012-02-15 19:37:42 -08002354 VLOG(jdwp) << "Removed breakpoint #" << i << ": " << gBreakpoints[i];
2355 gBreakpoints.erase(gBreakpoints.begin() + i);
2356 return;
2357 }
2358 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002359}
2360
Elliott Hughes221229c2013-01-08 18:17:50 -08002361JDWP::JdwpError Dbg::ConfigureStep(JDWP::ObjectId thread_id, JDWP::JdwpStepSize step_size,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002362 JDWP::JdwpStepDepth step_depth) {
2363 ScopedObjectAccessUnchecked soa(Thread::Current());
jeffhaoa77f0f62012-12-05 17:19:31 -08002364 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002365 Thread* thread;
2366 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread);
2367 if (error != JDWP::ERR_NONE) {
2368 return error;
Elliott Hughes2435a572012-02-17 16:07:41 -08002369 }
Elliott Hughes86964332012-02-15 19:37:42 -08002370
jeffhao09bfc6a2012-12-11 18:11:43 -08002371 MutexLock mu2(soa.Self(), *Locks::breakpoint_lock_);
Elliott Hughes86964332012-02-15 19:37:42 -08002372 // TODO: there's no theoretical reason why we couldn't support single-stepping
2373 // of multiple threads at once, but we never did so historically.
2374 if (gSingleStepControl.thread != NULL && thread != gSingleStepControl.thread) {
2375 LOG(WARNING) << "single-step already active for " << *gSingleStepControl.thread
2376 << "; switching to " << *thread;
2377 }
2378
Elliott Hughes2435a572012-02-17 16:07:41 -08002379 //
2380 // Work out what Method* we're in, the current line number, and how deep the stack currently
2381 // is for step-out.
2382 //
2383
Ian Rogers0399dde2012-06-06 17:09:28 -07002384 struct SingleStepStackVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -08002385 SingleStepStackVisitor(Thread* thread)
jeffhao09bfc6a2012-12-11 18:11:43 -08002386 EXCLUSIVE_LOCKS_REQUIRED(Locks::breakpoint_lock_)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002387 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08002388 : StackVisitor(thread, NULL) {
Elliott Hughes86964332012-02-15 19:37:42 -08002389 gSingleStepControl.method = NULL;
2390 gSingleStepControl.stack_depth = 0;
2391 }
Ian Rogersca190662012-06-26 15:45:57 -07002392
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002393 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2394 // annotalysis.
2395 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
jeffhao09bfc6a2012-12-11 18:11:43 -08002396 Locks::breakpoint_lock_->AssertHeld(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002397 const mirror::AbstractMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07002398 if (!m->IsRuntimeMethod()) {
Elliott Hughes86964332012-02-15 19:37:42 -08002399 ++gSingleStepControl.stack_depth;
2400 if (gSingleStepControl.method == NULL) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002401 const mirror::DexCache* dex_cache = m->GetDeclaringClass()->GetDexCache();
Elliott Hughes2435a572012-02-17 16:07:41 -08002402 gSingleStepControl.method = m;
2403 gSingleStepControl.line_number = -1;
2404 if (dex_cache != NULL) {
Ian Rogers4445a7e2012-10-05 17:19:13 -07002405 const DexFile& dex_file = *dex_cache->GetDexFile();
Ian Rogers0399dde2012-06-06 17:09:28 -07002406 gSingleStepControl.line_number = dex_file.GetLineNumFromPC(m, GetDexPc());
Elliott Hughes2435a572012-02-17 16:07:41 -08002407 }
Elliott Hughes86964332012-02-15 19:37:42 -08002408 }
2409 }
Elliott Hughes530fa002012-03-12 11:44:49 -07002410 return true;
Elliott Hughes86964332012-02-15 19:37:42 -08002411 }
2412 };
Ian Rogers7a22fa62013-01-23 12:16:16 -08002413 SingleStepStackVisitor visitor(thread);
Ian Rogers0399dde2012-06-06 17:09:28 -07002414 visitor.WalkStack();
Elliott Hughes86964332012-02-15 19:37:42 -08002415
Elliott Hughes2435a572012-02-17 16:07:41 -08002416 //
2417 // Find the dex_pc values that correspond to the current line, for line-based single-stepping.
2418 //
2419
2420 struct DebugCallbackContext {
jeffhao09bfc6a2012-12-11 18:11:43 -08002421 DebugCallbackContext() EXCLUSIVE_LOCKS_REQUIRED(Locks::breakpoint_lock_) {
Elliott Hughes2435a572012-02-17 16:07:41 -08002422 last_pc_valid = false;
2423 last_pc = 0;
Elliott Hughes2435a572012-02-17 16:07:41 -08002424 }
2425
jeffhao09bfc6a2012-12-11 18:11:43 -08002426 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2427 // annotalysis.
2428 static bool Callback(void* raw_context, uint32_t address, uint32_t line_number) NO_THREAD_SAFETY_ANALYSIS {
2429 Locks::breakpoint_lock_->AssertHeld(Thread::Current());
Elliott Hughes2435a572012-02-17 16:07:41 -08002430 DebugCallbackContext* context = reinterpret_cast<DebugCallbackContext*>(raw_context);
2431 if (static_cast<int32_t>(line_number) == gSingleStepControl.line_number) {
2432 if (!context->last_pc_valid) {
2433 // Everything from this address until the next line change is ours.
2434 context->last_pc = address;
2435 context->last_pc_valid = true;
2436 }
2437 // Otherwise, if we're already in a valid range for this line,
2438 // just keep going (shouldn't really happen)...
2439 } else if (context->last_pc_valid) { // and the line number is new
2440 // Add everything from the last entry up until here to the set
2441 for (uint32_t dex_pc = context->last_pc; dex_pc < address; ++dex_pc) {
2442 gSingleStepControl.dex_pcs.insert(dex_pc);
2443 }
2444 context->last_pc_valid = false;
2445 }
2446 return false; // There may be multiple entries for any given line.
2447 }
2448
jeffhao09bfc6a2012-12-11 18:11:43 -08002449 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
2450 // annotalysis.
2451 ~DebugCallbackContext() NO_THREAD_SAFETY_ANALYSIS {
2452 Locks::breakpoint_lock_->AssertHeld(Thread::Current());
Elliott Hughes2435a572012-02-17 16:07:41 -08002453 // If the line number was the last in the position table...
2454 if (last_pc_valid) {
2455 size_t end = MethodHelper(gSingleStepControl.method).GetCodeItem()->insns_size_in_code_units_;
2456 for (uint32_t dex_pc = last_pc; dex_pc < end; ++dex_pc) {
2457 gSingleStepControl.dex_pcs.insert(dex_pc);
2458 }
2459 }
2460 }
2461
2462 bool last_pc_valid;
2463 uint32_t last_pc;
2464 };
Elliott Hughes3e2e1a22012-02-21 11:33:41 -08002465 gSingleStepControl.dex_pcs.clear();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002466 const mirror::AbstractMethod* m = gSingleStepControl.method;
Elliott Hughes3e2e1a22012-02-21 11:33:41 -08002467 if (m->IsNative()) {
2468 gSingleStepControl.line_number = -1;
2469 } else {
2470 DebugCallbackContext context;
2471 MethodHelper mh(m);
2472 mh.GetDexFile().DecodeDebugInfo(mh.GetCodeItem(), m->IsStatic(), m->GetDexMethodIndex(),
2473 DebugCallbackContext::Callback, NULL, &context);
2474 }
Elliott Hughes2435a572012-02-17 16:07:41 -08002475
2476 //
2477 // Everything else...
2478 //
2479
Elliott Hughes86964332012-02-15 19:37:42 -08002480 gSingleStepControl.thread = thread;
2481 gSingleStepControl.step_size = step_size;
2482 gSingleStepControl.step_depth = step_depth;
2483 gSingleStepControl.is_active = true;
2484
Elliott Hughes2435a572012-02-17 16:07:41 -08002485 if (VLOG_IS_ON(jdwp)) {
2486 VLOG(jdwp) << "Single-step thread: " << *gSingleStepControl.thread;
2487 VLOG(jdwp) << "Single-step step size: " << gSingleStepControl.step_size;
2488 VLOG(jdwp) << "Single-step step depth: " << gSingleStepControl.step_depth;
2489 VLOG(jdwp) << "Single-step current method: " << PrettyMethod(gSingleStepControl.method);
2490 VLOG(jdwp) << "Single-step current line: " << gSingleStepControl.line_number;
2491 VLOG(jdwp) << "Single-step current stack depth: " << gSingleStepControl.stack_depth;
2492 VLOG(jdwp) << "Single-step dex_pc values:";
2493 for (std::set<uint32_t>::iterator it = gSingleStepControl.dex_pcs.begin() ; it != gSingleStepControl.dex_pcs.end(); ++it) {
Elliott Hughes229feb72012-02-23 13:33:29 -08002494 VLOG(jdwp) << StringPrintf(" %#x", *it);
Elliott Hughes2435a572012-02-17 16:07:41 -08002495 }
2496 }
2497
2498 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002499}
2500
Elliott Hughes221229c2013-01-08 18:17:50 -08002501void Dbg::UnconfigureStep(JDWP::ObjectId /*thread_id*/) {
jeffhao09bfc6a2012-12-11 18:11:43 -08002502 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_);
Elliott Hughesf8349362012-06-18 15:00:06 -07002503
Elliott Hughes86964332012-02-15 19:37:42 -08002504 gSingleStepControl.is_active = false;
2505 gSingleStepControl.thread = NULL;
Elliott Hughes2435a572012-02-17 16:07:41 -08002506 gSingleStepControl.dex_pcs.clear();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002507}
2508
Elliott Hughes45651fd2012-02-21 15:48:20 -08002509static char JdwpTagToShortyChar(JDWP::JdwpTag tag) {
2510 switch (tag) {
2511 default:
2512 LOG(FATAL) << "unknown JDWP tag: " << PrintableChar(tag);
2513
2514 // Primitives.
2515 case JDWP::JT_BYTE: return 'B';
2516 case JDWP::JT_CHAR: return 'C';
2517 case JDWP::JT_FLOAT: return 'F';
2518 case JDWP::JT_DOUBLE: return 'D';
2519 case JDWP::JT_INT: return 'I';
2520 case JDWP::JT_LONG: return 'J';
2521 case JDWP::JT_SHORT: return 'S';
2522 case JDWP::JT_VOID: return 'V';
2523 case JDWP::JT_BOOLEAN: return 'Z';
2524
2525 // Reference types.
2526 case JDWP::JT_ARRAY:
2527 case JDWP::JT_OBJECT:
2528 case JDWP::JT_STRING:
2529 case JDWP::JT_THREAD:
2530 case JDWP::JT_THREAD_GROUP:
2531 case JDWP::JT_CLASS_LOADER:
2532 case JDWP::JT_CLASS_OBJECT:
2533 return 'L';
2534 }
2535}
2536
Elliott Hughes88d63092013-01-09 09:55:54 -08002537JDWP::JdwpError Dbg::InvokeMethod(JDWP::ObjectId thread_id, JDWP::ObjectId object_id,
2538 JDWP::RefTypeId class_id, JDWP::MethodId method_id,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002539 uint32_t arg_count, uint64_t* arg_values,
2540 JDWP::JdwpTag* arg_types, uint32_t options,
2541 JDWP::JdwpTag* pResultTag, uint64_t* pResultValue,
2542 JDWP::ObjectId* pExceptionId) {
Elliott Hughesd07986f2011-12-06 18:27:45 -08002543 ThreadList* thread_list = Runtime::Current()->GetThreadList();
2544
2545 Thread* targetThread = NULL;
2546 DebugInvokeReq* req = NULL;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002547 Thread* self = Thread::Current();
Elliott Hughesd07986f2011-12-06 18:27:45 -08002548 {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002549 ScopedObjectAccessUnchecked soa(self);
Ian Rogers50b35e22012-10-04 10:09:15 -07002550 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Elliott Hughes221229c2013-01-08 18:17:50 -08002551 JDWP::JdwpError error = DecodeThread(soa, thread_id, targetThread);
2552 if (error != JDWP::ERR_NONE) {
2553 LOG(ERROR) << "InvokeMethod request for invalid thread id " << thread_id;
2554 return error;
Elliott Hughesd07986f2011-12-06 18:27:45 -08002555 }
2556 req = targetThread->GetInvokeReq();
2557 if (!req->ready) {
2558 LOG(ERROR) << "InvokeMethod request for thread not stopped by event: " << *targetThread;
2559 return JDWP::ERR_INVALID_THREAD;
2560 }
2561
2562 /*
2563 * We currently have a bug where we don't successfully resume the
2564 * target thread if the suspend count is too deep. We're expected to
2565 * require one "resume" for each "suspend", but when asked to execute
2566 * a method we have to resume fully and then re-suspend it back to the
2567 * same level. (The easiest way to cause this is to type "suspend"
2568 * multiple times in jdb.)
2569 *
2570 * It's unclear what this means when the event specifies "resume all"
2571 * and some threads are suspended more deeply than others. This is
2572 * a rare problem, so for now we just prevent it from hanging forever
2573 * by rejecting the method invocation request. Without this, we will
2574 * be stuck waiting on a suspended thread.
2575 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002576 int suspend_count;
2577 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002578 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002579 suspend_count = targetThread->GetSuspendCount();
2580 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08002581 if (suspend_count > 1) {
2582 LOG(ERROR) << *targetThread << " suspend count too deep for method invocation: " << suspend_count;
2583 return JDWP::ERR_THREAD_SUSPENDED; // Probably not expected here.
2584 }
2585
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002586 JDWP::JdwpError status;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002587 mirror::Object* receiver = gRegistry->Get<mirror::Object*>(object_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08002588 if (receiver == ObjectRegistry::kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002589 return JDWP::ERR_INVALID_OBJECT;
2590 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002591
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002592 mirror::Object* thread = gRegistry->Get<mirror::Object*>(thread_id);
Elliott Hughes64f574f2013-02-20 14:57:12 -08002593 if (thread == ObjectRegistry::kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002594 return JDWP::ERR_INVALID_OBJECT;
2595 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002596 // TODO: check that 'thread' is actually a java.lang.Thread!
2597
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002598 mirror::Class* c = DecodeClass(class_id, status);
Elliott Hughes45651fd2012-02-21 15:48:20 -08002599 if (c == NULL) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002600 return status;
2601 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002602
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002603 mirror::AbstractMethod* m = FromMethodId(method_id);
Elliott Hughes45651fd2012-02-21 15:48:20 -08002604 if (m->IsStatic() != (receiver == NULL)) {
2605 return JDWP::ERR_INVALID_METHODID;
2606 }
2607 if (m->IsStatic()) {
2608 if (m->GetDeclaringClass() != c) {
2609 return JDWP::ERR_INVALID_METHODID;
2610 }
2611 } else {
2612 if (!m->GetDeclaringClass()->IsAssignableFrom(c)) {
2613 return JDWP::ERR_INVALID_METHODID;
2614 }
2615 }
2616
2617 // Check the argument list matches the method.
2618 MethodHelper mh(m);
2619 if (mh.GetShortyLength() - 1 != arg_count) {
2620 return JDWP::ERR_ILLEGAL_ARGUMENT;
2621 }
2622 const char* shorty = mh.GetShorty();
2623 for (size_t i = 0; i < arg_count; ++i) {
2624 if (shorty[i + 1] != JdwpTagToShortyChar(arg_types[i])) {
2625 return JDWP::ERR_ILLEGAL_ARGUMENT;
2626 }
2627 }
2628
2629 req->receiver_ = receiver;
2630 req->thread_ = thread;
2631 req->class_ = c;
2632 req->method_ = m;
2633 req->arg_count_ = arg_count;
2634 req->arg_values_ = arg_values;
Elliott Hughesd07986f2011-12-06 18:27:45 -08002635 req->options_ = options;
2636 req->invoke_needed_ = true;
2637 }
2638
2639 // The fact that we've released the thread list lock is a bit risky --- if the thread goes
2640 // away we're sitting high and dry -- but we must release this before the ResumeAllThreads
2641 // call, and it's unwise to hold it during WaitForSuspend.
2642
2643 {
2644 /*
2645 * We change our (JDWP thread) status, which should be THREAD_RUNNING,
Elliott Hughes81ff3182012-03-23 20:35:56 -07002646 * so we can suspend for a GC if the invoke request causes us to
Elliott Hughesd07986f2011-12-06 18:27:45 -08002647 * run out of memory. It's also a good idea to change it before locking
2648 * the invokeReq mutex, although that should never be held for long.
2649 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002650 self->TransitionFromRunnableToSuspended(kWaitingForDebuggerSend);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002651
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002652 VLOG(jdwp) << " Transferring control to event thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002653 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002654 MutexLock mu(self, req->lock_);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002655
2656 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002657 VLOG(jdwp) << " Resuming all threads";
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002658 thread_list->UndoDebuggerSuspensions();
Elliott Hughesd07986f2011-12-06 18:27:45 -08002659 } else {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002660 VLOG(jdwp) << " Resuming event thread only";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002661 thread_list->Resume(targetThread, true);
2662 }
2663
2664 // Wait for the request to finish executing.
2665 while (req->invoke_needed_) {
Ian Rogersc604d732012-10-14 16:09:54 -07002666 req->cond_.Wait(self);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002667 }
2668 }
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002669 VLOG(jdwp) << " Control has returned from event thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002670
2671 /* wait for thread to re-suspend itself */
Elliott Hughes221229c2013-01-08 18:17:50 -08002672 SuspendThread(thread_id, false /* request_suspension */ );
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002673 self->TransitionFromSuspendedToRunnable();
Elliott Hughesd07986f2011-12-06 18:27:45 -08002674 }
2675
2676 /*
2677 * Suspend the threads. We waited for the target thread to suspend
2678 * itself, so all we need to do is suspend the others.
2679 *
2680 * The suspendAllThreads() call will double-suspend the event thread,
2681 * so we want to resume the target thread once to keep the books straight.
2682 */
2683 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002684 self->TransitionFromRunnableToSuspended(kWaitingForDebuggerSuspension);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002685 VLOG(jdwp) << " Suspending all threads";
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002686 thread_list->SuspendAllForDebugger();
2687 self->TransitionFromSuspendedToRunnable();
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002688 VLOG(jdwp) << " Resuming event thread to balance the count";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002689 thread_list->Resume(targetThread, true);
2690 }
2691
2692 // Copy the result.
2693 *pResultTag = req->result_tag;
2694 if (IsPrimitiveTag(req->result_tag)) {
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002695 *pResultValue = req->result_value.GetJ();
Elliott Hughesd07986f2011-12-06 18:27:45 -08002696 } else {
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002697 *pResultValue = gRegistry->Add(req->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002698 }
2699 *pExceptionId = req->exception;
2700 return req->error;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002701}
2702
2703void Dbg::ExecuteMethod(DebugInvokeReq* pReq) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002704 ScopedObjectAccess soa(Thread::Current());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002705
Elliott Hughes81ff3182012-03-23 20:35:56 -07002706 // We can be called while an exception is pending. We need
Elliott Hughesd07986f2011-12-06 18:27:45 -08002707 // to preserve that across the method invocation.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002708 SirtRef<mirror::Throwable> old_exception(soa.Self(), soa.Self()->GetException());
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002709 soa.Self()->ClearException();
Elliott Hughesd07986f2011-12-06 18:27:45 -08002710
2711 // Translate the method through the vtable, unless the debugger wants to suppress it.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002712 mirror::AbstractMethod* m = pReq->method_;
Elliott Hughesd07986f2011-12-06 18:27:45 -08002713 if ((pReq->options_ & JDWP::INVOKE_NONVIRTUAL) == 0 && pReq->receiver_ != NULL) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002714 mirror::AbstractMethod* actual_method = pReq->class_->FindVirtualMethodForVirtualOrInterface(pReq->method_);
Elliott Hughes45651fd2012-02-21 15:48:20 -08002715 if (actual_method != m) {
2716 VLOG(jdwp) << "ExecuteMethod translated " << PrettyMethod(m) << " to " << PrettyMethod(actual_method);
2717 m = actual_method;
2718 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08002719 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002720 VLOG(jdwp) << "ExecuteMethod " << PrettyMethod(m);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002721 CHECK(m != NULL);
2722
2723 CHECK_EQ(sizeof(jvalue), sizeof(uint64_t));
2724
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002725 LOG(INFO) << "self=" << soa.Self() << " pReq->receiver_=" << pReq->receiver_ << " m=" << m
2726 << " #" << pReq->arg_count_ << " " << pReq->arg_values_;
Jeff Hao5d917302013-02-27 17:57:33 -08002727
2728 MethodHelper mh(m);
2729 ArgArray arg_array(mh.GetShorty(), mh.GetShortyLength());
2730 arg_array.BuildArgArray(soa, pReq->receiver_, reinterpret_cast<jvalue*>(pReq->arg_values_));
2731 JValue unused_result;
2732 if (mh.IsReturnFloatOrDouble()) {
2733 InvokeWithArgArray(soa, m, &arg_array, &unused_result, &pReq->result_value);
2734 } else {
2735 InvokeWithArgArray(soa, m, &arg_array, &pReq->result_value, &unused_result);
2736 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08002737
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002738 pReq->exception = gRegistry->Add(soa.Self()->GetException());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002739 pReq->result_tag = BasicTagFromDescriptor(MethodHelper(m).GetShorty());
2740 if (pReq->exception != 0) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002741 mirror::Object* exc = soa.Self()->GetException();
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002742 VLOG(jdwp) << " JDWP invocation returning with exception=" << exc << " " << PrettyTypeOf(exc);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002743 soa.Self()->ClearException();
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002744 pReq->result_value.SetJ(0);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002745 } else if (pReq->result_tag == JDWP::JT_OBJECT) {
2746 /* if no exception thrown, examine object result more closely */
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002747 JDWP::JdwpTag new_tag = TagFromObject(pReq->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002748 if (new_tag != pReq->result_tag) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002749 VLOG(jdwp) << " JDWP promoted result from " << pReq->result_tag << " to " << new_tag;
Elliott Hughesd07986f2011-12-06 18:27:45 -08002750 pReq->result_tag = new_tag;
2751 }
2752
2753 /*
2754 * Register the object. We don't actually need an ObjectId yet,
2755 * but we do need to be sure that the GC won't move or discard the
2756 * object when we switch out of RUNNING. The ObjectId conversion
2757 * will add the object to the "do not touch" list.
2758 *
2759 * We can't use the "tracked allocation" mechanism here because
2760 * the object is going to be handed off to a different thread.
2761 */
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002762 gRegistry->Add(pReq->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002763 }
2764
2765 if (old_exception.get() != NULL) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002766 soa.Self()->SetException(old_exception.get());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002767 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002768}
2769
Elliott Hughesd07986f2011-12-06 18:27:45 -08002770/*
Elliott Hughes4b9702c2013-02-20 18:13:24 -08002771 * "request" contains a full JDWP packet, possibly with multiple chunks. We
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002772 * need to process each, accumulate the replies, and ship the whole thing
2773 * back.
2774 *
2775 * Returns "true" if we have a reply. The reply buffer is newly allocated,
2776 * and includes the chunk type/length, followed by the data.
2777 *
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08002778 * OLD-TODO: we currently assume that the request and reply include a single
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002779 * chunk. If this becomes inconvenient we will need to adapt.
2780 */
Elliott Hughes4b9702c2013-02-20 18:13:24 -08002781bool Dbg::DdmHandlePacket(JDWP::Request& request, uint8_t** pReplyBuf, int* pReplyLen) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002782 Thread* self = Thread::Current();
2783 JNIEnv* env = self->GetJniEnv();
2784
Elliott Hughes4b9702c2013-02-20 18:13:24 -08002785 uint32_t type = request.ReadUnsigned32("type");
2786 uint32_t length = request.ReadUnsigned32("length");
2787
2788 // Create a byte[] corresponding to 'request'.
2789 size_t request_length = request.size();
2790 ScopedLocalRef<jbyteArray> dataArray(env, env->NewByteArray(request_length));
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002791 if (dataArray.get() == NULL) {
Elliott Hughes4b9702c2013-02-20 18:13:24 -08002792 LOG(WARNING) << "byte[] allocation failed: " << request_length;
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002793 env->ExceptionClear();
2794 return false;
2795 }
Elliott Hughes4b9702c2013-02-20 18:13:24 -08002796 env->SetByteArrayRegion(dataArray.get(), 0, request_length, reinterpret_cast<const jbyte*>(request.data()));
2797 request.Skip(request_length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002798
2799 // Run through and find all chunks. [Currently just find the first.]
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002800 ScopedByteArrayRO contents(env, dataArray.get());
Elliott Hughes4b9702c2013-02-20 18:13:24 -08002801 if (length != request_length) {
2802 LOG(WARNING) << StringPrintf("bad chunk found (len=%u pktLen=%d)", length, request_length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002803 return false;
2804 }
2805
2806 // Call "private static Chunk dispatch(int type, byte[] data, int offset, int length)".
Elliott Hugheseac76672012-05-24 21:56:51 -07002807 ScopedLocalRef<jobject> chunk(env, env->CallStaticObjectMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
2808 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_dispatch,
Elliott Hughes4b9702c2013-02-20 18:13:24 -08002809 type, dataArray.get(), 0, length));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002810 if (env->ExceptionCheck()) {
2811 LOG(INFO) << StringPrintf("Exception thrown by dispatcher for 0x%08x", type);
2812 env->ExceptionDescribe();
2813 env->ExceptionClear();
2814 return false;
2815 }
2816
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002817 if (chunk.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002818 return false;
2819 }
2820
2821 /*
2822 * Pull the pieces out of the chunk. We copy the results into a
2823 * newly-allocated buffer that the caller can free. We don't want to
2824 * continue using the Chunk object because nothing has a reference to it.
2825 *
2826 * We could avoid this by returning type/data/offset/length and having
2827 * the caller be aware of the object lifetime issues, but that
Elliott Hughes81ff3182012-03-23 20:35:56 -07002828 * integrates the JDWP code more tightly into the rest of the runtime, and doesn't work
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002829 * if we have responses for multiple chunks.
2830 *
2831 * So we're pretty much stuck with copying data around multiple times.
2832 */
Elliott Hugheseac76672012-05-24 21:56:51 -07002833 ScopedLocalRef<jbyteArray> replyData(env, reinterpret_cast<jbyteArray>(env->GetObjectField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_data)));
Elliott Hughes4b9702c2013-02-20 18:13:24 -08002834 jint offset = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_offset);
Elliott Hugheseac76672012-05-24 21:56:51 -07002835 length = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_length);
Elliott Hugheseac76672012-05-24 21:56:51 -07002836 type = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_type);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002837
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002838 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 -07002839 if (length == 0 || replyData.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002840 return false;
2841 }
2842
Elliott Hughes4b9702c2013-02-20 18:13:24 -08002843 const int kChunkHdrLen = 8;
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002844 uint8_t* reply = new uint8_t[length + kChunkHdrLen];
2845 if (reply == NULL) {
2846 LOG(WARNING) << "malloc failed: " << (length + kChunkHdrLen);
2847 return false;
2848 }
Elliott Hughesf7c3b662011-10-27 12:04:56 -07002849 JDWP::Set4BE(reply + 0, type);
2850 JDWP::Set4BE(reply + 4, length);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002851 env->GetByteArrayRegion(replyData.get(), offset, length, reinterpret_cast<jbyte*>(reply + kChunkHdrLen));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002852
2853 *pReplyBuf = reply;
2854 *pReplyLen = length + kChunkHdrLen;
2855
Elliott Hughes4b9702c2013-02-20 18:13:24 -08002856 VLOG(jdwp) << StringPrintf("dvmHandleDdm returning type=%.4s %p len=%d", reinterpret_cast<char*>(reply), reply, length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002857 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002858}
2859
Elliott Hughesa2155262011-11-16 16:26:58 -08002860void Dbg::DdmBroadcast(bool connect) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002861 VLOG(jdwp) << "Broadcasting DDM " << (connect ? "connect" : "disconnect") << "...";
Elliott Hughes47fce012011-10-25 18:37:19 -07002862
2863 Thread* self = Thread::Current();
Ian Rogers50b35e22012-10-04 10:09:15 -07002864 if (self->GetState() != kRunnable) {
2865 LOG(ERROR) << "DDM broadcast in thread state " << self->GetState();
2866 /* try anyway? */
Elliott Hughes47fce012011-10-25 18:37:19 -07002867 }
2868
2869 JNIEnv* env = self->GetJniEnv();
Elliott Hughes47fce012011-10-25 18:37:19 -07002870 jint event = connect ? 1 /*DdmServer.CONNECTED*/ : 2 /*DdmServer.DISCONNECTED*/;
Elliott Hugheseac76672012-05-24 21:56:51 -07002871 env->CallStaticVoidMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
2872 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_broadcast,
2873 event);
Elliott Hughes47fce012011-10-25 18:37:19 -07002874 if (env->ExceptionCheck()) {
2875 LOG(ERROR) << "DdmServer.broadcast " << event << " failed";
2876 env->ExceptionDescribe();
2877 env->ExceptionClear();
2878 }
2879}
2880
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002881void Dbg::DdmConnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08002882 Dbg::DdmBroadcast(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002883}
2884
2885void Dbg::DdmDisconnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08002886 Dbg::DdmBroadcast(false);
Elliott Hughes47fce012011-10-25 18:37:19 -07002887 gDdmThreadNotification = false;
2888}
2889
2890/*
Elliott Hughes82188472011-11-07 18:11:48 -08002891 * Send a notification when a thread starts, stops, or changes its name.
Elliott Hughes47fce012011-10-25 18:37:19 -07002892 *
2893 * Because we broadcast the full set of threads when the notifications are
2894 * first enabled, it's possible for "thread" to be actively executing.
2895 */
Elliott Hughes82188472011-11-07 18:11:48 -08002896void Dbg::DdmSendThreadNotification(Thread* t, uint32_t type) {
Elliott Hughes47fce012011-10-25 18:37:19 -07002897 if (!gDdmThreadNotification) {
2898 return;
2899 }
2900
Elliott Hughes82188472011-11-07 18:11:48 -08002901 if (type == CHUNK_TYPE("THDE")) {
Elliott Hughes47fce012011-10-25 18:37:19 -07002902 uint8_t buf[4];
Elliott Hughesf7c3b662011-10-27 12:04:56 -07002903 JDWP::Set4BE(&buf[0], t->GetThinLockId());
Elliott Hughes47fce012011-10-25 18:37:19 -07002904 Dbg::DdmSendChunk(CHUNK_TYPE("THDE"), 4, buf);
Elliott Hughes82188472011-11-07 18:11:48 -08002905 } else {
2906 CHECK(type == CHUNK_TYPE("THCR") || type == CHUNK_TYPE("THNM")) << type;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002907 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002908 SirtRef<mirror::String> name(soa.Self(), t->GetThreadName(soa));
Elliott Hughes82188472011-11-07 18:11:48 -08002909 size_t char_count = (name.get() != NULL) ? name->GetLength() : 0;
jeffhao725a9572012-11-13 18:20:12 -08002910 const jchar* chars = (name.get() != NULL) ? name->GetCharArray()->GetData() : NULL;
Elliott Hughes82188472011-11-07 18:11:48 -08002911
Elliott Hughes21f32d72011-11-09 17:44:13 -08002912 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08002913 JDWP::Append4BE(bytes, t->GetThinLockId());
2914 JDWP::AppendUtf16BE(bytes, chars, char_count);
Elliott Hughes21f32d72011-11-09 17:44:13 -08002915 CHECK_EQ(bytes.size(), char_count*2 + sizeof(uint32_t)*2);
2916 Dbg::DdmSendChunk(type, bytes);
Elliott Hughes47fce012011-10-25 18:37:19 -07002917 }
2918}
2919
Elliott Hughes47fce012011-10-25 18:37:19 -07002920void Dbg::DdmSetThreadNotification(bool enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002921 // Enable/disable thread notifications.
Elliott Hughes47fce012011-10-25 18:37:19 -07002922 gDdmThreadNotification = enable;
2923 if (enable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002924 // Suspend the VM then post thread start notifications for all threads. Threads attaching will
2925 // see a suspension in progress and block until that ends. They then post their own start
2926 // notification.
2927 SuspendVM();
2928 std::list<Thread*> threads;
Ian Rogers50b35e22012-10-04 10:09:15 -07002929 Thread* self = Thread::Current();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002930 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002931 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002932 threads = Runtime::Current()->GetThreadList()->GetList();
2933 }
2934 {
Ian Rogers50b35e22012-10-04 10:09:15 -07002935 ScopedObjectAccess soa(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002936 typedef std::list<Thread*>::const_iterator It; // TODO: C++0x auto
2937 for (It it = threads.begin(), end = threads.end(); it != end; ++it) {
2938 Dbg::DdmSendThreadNotification(*it, CHUNK_TYPE("THCR"));
2939 }
2940 }
2941 ResumeVM();
Elliott Hughes47fce012011-10-25 18:37:19 -07002942 }
2943}
2944
Elliott Hughesa2155262011-11-16 16:26:58 -08002945void Dbg::PostThreadStartOrStop(Thread* t, uint32_t type) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002946 if (IsDebuggerActive()) {
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07002947 ScopedObjectAccessUnchecked soa(Thread::Current());
Ian Rogerscfaa4552012-11-26 21:00:08 -08002948 JDWP::ObjectId id = gRegistry->Add(t->GetPeer());
Elliott Hughes82188472011-11-07 18:11:48 -08002949 gJdwpState->PostThreadChange(id, type == CHUNK_TYPE("THCR"));
Elliott Hughesc0f09332012-03-26 13:27:06 -07002950 // If this thread's just joined the party while we're already debugging, make sure it knows
2951 // to give us updates when it's running.
2952 t->SetDebuggerUpdatesEnabled(true);
Elliott Hughes47fce012011-10-25 18:37:19 -07002953 }
Elliott Hughes82188472011-11-07 18:11:48 -08002954 Dbg::DdmSendThreadNotification(t, type);
Elliott Hughes47fce012011-10-25 18:37:19 -07002955}
2956
2957void Dbg::PostThreadStart(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08002958 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07002959}
2960
2961void Dbg::PostThreadDeath(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08002962 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THDE"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002963}
2964
Elliott Hughes82188472011-11-07 18:11:48 -08002965void Dbg::DdmSendChunk(uint32_t type, size_t byte_count, const uint8_t* buf) {
Elliott Hughes3bb81562011-10-21 18:52:59 -07002966 CHECK(buf != NULL);
2967 iovec vec[1];
2968 vec[0].iov_base = reinterpret_cast<void*>(const_cast<uint8_t*>(buf));
2969 vec[0].iov_len = byte_count;
2970 Dbg::DdmSendChunkV(type, vec, 1);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002971}
2972
Elliott Hughes21f32d72011-11-09 17:44:13 -08002973void Dbg::DdmSendChunk(uint32_t type, const std::vector<uint8_t>& bytes) {
2974 DdmSendChunk(type, bytes.size(), &bytes[0]);
2975}
2976
Elliott Hughescccd84f2011-12-05 16:51:54 -08002977void Dbg::DdmSendChunkV(uint32_t type, const struct iovec* iov, int iov_count) {
Elliott Hughes3bb81562011-10-21 18:52:59 -07002978 if (gJdwpState == NULL) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002979 VLOG(jdwp) << "Debugger thread not active, ignoring DDM send: " << type;
Elliott Hughes3bb81562011-10-21 18:52:59 -07002980 } else {
Elliott Hughescccd84f2011-12-05 16:51:54 -08002981 gJdwpState->DdmSendChunkV(type, iov, iov_count);
Elliott Hughes3bb81562011-10-21 18:52:59 -07002982 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002983}
2984
Elliott Hughes767a1472011-10-26 18:49:02 -07002985int Dbg::DdmHandleHpifChunk(HpifWhen when) {
2986 if (when == HPIF_WHEN_NOW) {
Elliott Hughes7162ad92011-10-27 14:08:42 -07002987 DdmSendHeapInfo(when);
Elliott Hughes767a1472011-10-26 18:49:02 -07002988 return true;
2989 }
2990
2991 if (when != HPIF_WHEN_NEVER && when != HPIF_WHEN_NEXT_GC && when != HPIF_WHEN_EVERY_GC) {
2992 LOG(ERROR) << "invalid HpifWhen value: " << static_cast<int>(when);
2993 return false;
2994 }
2995
2996 gDdmHpifWhen = when;
2997 return true;
2998}
2999
3000bool Dbg::DdmHandleHpsgNhsgChunk(Dbg::HpsgWhen when, Dbg::HpsgWhat what, bool native) {
3001 if (when != HPSG_WHEN_NEVER && when != HPSG_WHEN_EVERY_GC) {
3002 LOG(ERROR) << "invalid HpsgWhen value: " << static_cast<int>(when);
3003 return false;
3004 }
3005
3006 if (what != HPSG_WHAT_MERGED_OBJECTS && what != HPSG_WHAT_DISTINCT_OBJECTS) {
3007 LOG(ERROR) << "invalid HpsgWhat value: " << static_cast<int>(what);
3008 return false;
3009 }
3010
3011 if (native) {
3012 gDdmNhsgWhen = when;
3013 gDdmNhsgWhat = what;
3014 } else {
3015 gDdmHpsgWhen = when;
3016 gDdmHpsgWhat = what;
3017 }
3018 return true;
3019}
3020
Elliott Hughes7162ad92011-10-27 14:08:42 -07003021void Dbg::DdmSendHeapInfo(HpifWhen reason) {
3022 // If there's a one-shot 'when', reset it.
3023 if (reason == gDdmHpifWhen) {
3024 if (gDdmHpifWhen == HPIF_WHEN_NEXT_GC) {
3025 gDdmHpifWhen = HPIF_WHEN_NEVER;
3026 }
3027 }
3028
3029 /*
3030 * Chunk HPIF (client --> server)
3031 *
3032 * Heap Info. General information about the heap,
3033 * suitable for a summary display.
3034 *
3035 * [u4]: number of heaps
3036 *
3037 * For each heap:
3038 * [u4]: heap ID
3039 * [u8]: timestamp in ms since Unix epoch
3040 * [u1]: capture reason (same as 'when' value from server)
3041 * [u4]: max heap size in bytes (-Xmx)
3042 * [u4]: current heap size in bytes
3043 * [u4]: current number of bytes allocated
3044 * [u4]: current number of objects allocated
3045 */
3046 uint8_t heap_count = 1;
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08003047 Heap* heap = Runtime::Current()->GetHeap();
Elliott Hughes21f32d72011-11-09 17:44:13 -08003048 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08003049 JDWP::Append4BE(bytes, heap_count);
3050 JDWP::Append4BE(bytes, 1); // Heap id (bogus; we only have one heap).
3051 JDWP::Append8BE(bytes, MilliTime());
3052 JDWP::Append1BE(bytes, reason);
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08003053 JDWP::Append4BE(bytes, heap->GetMaxMemory()); // Max allowed heap size in bytes.
3054 JDWP::Append4BE(bytes, heap->GetTotalMemory()); // Current heap size in bytes.
3055 JDWP::Append4BE(bytes, heap->GetBytesAllocated());
3056 JDWP::Append4BE(bytes, heap->GetObjectsAllocated());
Elliott Hughes21f32d72011-11-09 17:44:13 -08003057 CHECK_EQ(bytes.size(), 4U + (heap_count * (4 + 8 + 1 + 4 + 4 + 4 + 4)));
3058 Dbg::DdmSendChunk(CHUNK_TYPE("HPIF"), bytes);
Elliott Hughes767a1472011-10-26 18:49:02 -07003059}
3060
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003061enum HpsgSolidity {
3062 SOLIDITY_FREE = 0,
3063 SOLIDITY_HARD = 1,
3064 SOLIDITY_SOFT = 2,
3065 SOLIDITY_WEAK = 3,
3066 SOLIDITY_PHANTOM = 4,
3067 SOLIDITY_FINALIZABLE = 5,
3068 SOLIDITY_SWEEP = 6,
3069};
3070
3071enum HpsgKind {
3072 KIND_OBJECT = 0,
3073 KIND_CLASS_OBJECT = 1,
3074 KIND_ARRAY_1 = 2,
3075 KIND_ARRAY_2 = 3,
3076 KIND_ARRAY_4 = 4,
3077 KIND_ARRAY_8 = 5,
3078 KIND_UNKNOWN = 6,
3079 KIND_NATIVE = 7,
3080};
3081
3082#define HPSG_PARTIAL (1<<7)
3083#define HPSG_STATE(solidity, kind) ((uint8_t)((((kind) & 0x7) << 3) | ((solidity) & 0x7)))
3084
Ian Rogers30fab402012-01-23 15:43:46 -08003085class HeapChunkContext {
3086 public:
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003087 // Maximum chunk size. Obtain this from the formula:
3088 // (((maximum_heap_size / ALLOCATION_UNIT_SIZE) + 255) / 256) * 2
3089 HeapChunkContext(bool merge, bool native)
Ian Rogers30fab402012-01-23 15:43:46 -08003090 : buf_(16384 - 16),
3091 type_(0),
3092 merge_(merge) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003093 Reset();
3094 if (native) {
Ian Rogers30fab402012-01-23 15:43:46 -08003095 type_ = CHUNK_TYPE("NHSG");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003096 } else {
Ian Rogers30fab402012-01-23 15:43:46 -08003097 type_ = merge ? CHUNK_TYPE("HPSG") : CHUNK_TYPE("HPSO");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003098 }
3099 }
3100
3101 ~HeapChunkContext() {
Ian Rogers30fab402012-01-23 15:43:46 -08003102 if (p_ > &buf_[0]) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003103 Flush();
3104 }
3105 }
3106
3107 void EnsureHeader(const void* chunk_ptr) {
Ian Rogers30fab402012-01-23 15:43:46 -08003108 if (!needHeader_) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003109 return;
3110 }
3111
3112 // Start a new HPSx chunk.
Ian Rogers30fab402012-01-23 15:43:46 -08003113 JDWP::Write4BE(&p_, 1); // Heap id (bogus; we only have one heap).
3114 JDWP::Write1BE(&p_, 8); // Size of allocation unit, in bytes.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003115
Ian Rogers30fab402012-01-23 15:43:46 -08003116 JDWP::Write4BE(&p_, reinterpret_cast<uintptr_t>(chunk_ptr)); // virtual address of segment start.
3117 JDWP::Write4BE(&p_, 0); // offset of this piece (relative to the virtual address).
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003118 // [u4]: length of piece, in allocation units
3119 // 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 -08003120 pieceLenField_ = p_;
3121 JDWP::Write4BE(&p_, 0x55555555);
3122 needHeader_ = false;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003123 }
3124
Ian Rogersb726dcb2012-09-05 08:57:23 -07003125 void Flush() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogersd636b062013-01-18 17:51:18 -08003126 if (pieceLenField_ == NULL) {
3127 // Flush immediately post Reset (maybe back-to-back Flush). Ignore.
3128 CHECK(needHeader_);
3129 return;
3130 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003131 // Patch the "length of piece" field.
Ian Rogers30fab402012-01-23 15:43:46 -08003132 CHECK_LE(&buf_[0], pieceLenField_);
3133 CHECK_LE(pieceLenField_, p_);
3134 JDWP::Set4BE(pieceLenField_, totalAllocationUnits_);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003135
Ian Rogers30fab402012-01-23 15:43:46 -08003136 Dbg::DdmSendChunk(type_, p_ - &buf_[0], &buf_[0]);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003137 Reset();
3138 }
3139
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003140 static void HeapChunkCallback(void* start, void* end, size_t used_bytes, void* arg)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003141 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_,
3142 Locks::mutator_lock_) {
Ian Rogers30fab402012-01-23 15:43:46 -08003143 reinterpret_cast<HeapChunkContext*>(arg)->HeapChunkCallback(start, end, used_bytes);
Elliott Hughesa2155262011-11-16 16:26:58 -08003144 }
3145
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003146 private:
Elliott Hughesa2155262011-11-16 16:26:58 -08003147 enum { ALLOCATION_UNIT_SIZE = 8 };
3148
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003149 void Reset() {
Ian Rogers30fab402012-01-23 15:43:46 -08003150 p_ = &buf_[0];
Ian Rogers15bf2d32012-08-28 17:33:04 -07003151 startOfNextMemoryChunk_ = NULL;
Ian Rogers30fab402012-01-23 15:43:46 -08003152 totalAllocationUnits_ = 0;
3153 needHeader_ = true;
3154 pieceLenField_ = NULL;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003155 }
3156
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003157 void HeapChunkCallback(void* start, void* /*end*/, size_t used_bytes)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003158 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_,
3159 Locks::mutator_lock_) {
Ian Rogers30fab402012-01-23 15:43:46 -08003160 // Note: heap call backs cannot manipulate the heap upon which they are crawling, care is taken
3161 // in the following code not to allocate memory, by ensuring buf_ is of the correct size
Ian Rogers15bf2d32012-08-28 17:33:04 -07003162 if (used_bytes == 0) {
3163 if (start == NULL) {
3164 // Reset for start of new heap.
3165 startOfNextMemoryChunk_ = NULL;
3166 Flush();
3167 }
3168 // Only process in use memory so that free region information
3169 // also includes dlmalloc book keeping.
Elliott Hughesa2155262011-11-16 16:26:58 -08003170 return;
Elliott Hughesa2155262011-11-16 16:26:58 -08003171 }
3172
Ian Rogers15bf2d32012-08-28 17:33:04 -07003173 /* If we're looking at the native heap, we'll just return
3174 * (SOLIDITY_HARD, KIND_NATIVE) for all allocated chunks
3175 */
3176 bool native = type_ == CHUNK_TYPE("NHSG");
3177
3178 if (startOfNextMemoryChunk_ != NULL) {
3179 // Transmit any pending free memory. Native free memory of
3180 // over kMaxFreeLen could be because of the use of mmaps, so
3181 // don't report. If not free memory then start a new segment.
3182 bool flush = true;
3183 if (start > startOfNextMemoryChunk_) {
3184 const size_t kMaxFreeLen = 2 * kPageSize;
3185 void* freeStart = startOfNextMemoryChunk_;
3186 void* freeEnd = start;
3187 size_t freeLen = (char*)freeEnd - (char*)freeStart;
3188 if (!native || freeLen < kMaxFreeLen) {
3189 AppendChunk(HPSG_STATE(SOLIDITY_FREE, 0), freeStart, freeLen);
3190 flush = false;
3191 }
3192 }
3193 if (flush) {
3194 startOfNextMemoryChunk_ = NULL;
3195 Flush();
3196 }
3197 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003198 const mirror::Object* obj = reinterpret_cast<const mirror::Object*>(start);
Elliott Hughesa2155262011-11-16 16:26:58 -08003199
3200 // Determine the type of this chunk.
3201 // OLD-TODO: if context.merge, see if this chunk is different from the last chunk.
3202 // If it's the same, we should combine them.
Ian Rogers15bf2d32012-08-28 17:33:04 -07003203 uint8_t state = ExamineObject(obj, native);
3204 // dlmalloc's chunk header is 2 * sizeof(size_t), but if the previous chunk is in use for an
3205 // allocation then the first sizeof(size_t) may belong to it.
3206 const size_t dlMallocOverhead = sizeof(size_t);
3207 AppendChunk(state, start, used_bytes + dlMallocOverhead);
3208 startOfNextMemoryChunk_ = (char*)start + used_bytes + dlMallocOverhead;
3209 }
Elliott Hughesa2155262011-11-16 16:26:58 -08003210
Ian Rogers15bf2d32012-08-28 17:33:04 -07003211 void AppendChunk(uint8_t state, void* ptr, size_t length)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003212 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07003213 // Make sure there's enough room left in the buffer.
3214 // We need to use two bytes for every fractional 256 allocation units used by the chunk plus
3215 // 17 bytes for any header.
3216 size_t needed = (((length/ALLOCATION_UNIT_SIZE + 255) / 256) * 2) + 17;
3217 size_t bytesLeft = buf_.size() - (size_t)(p_ - &buf_[0]);
3218 if (bytesLeft < needed) {
3219 Flush();
3220 }
3221
3222 bytesLeft = buf_.size() - (size_t)(p_ - &buf_[0]);
3223 if (bytesLeft < needed) {
3224 LOG(WARNING) << "Chunk is too big to transmit (chunk_len=" << length << ", "
3225 << needed << " bytes)";
3226 return;
3227 }
3228 EnsureHeader(ptr);
Elliott Hughesa2155262011-11-16 16:26:58 -08003229 // Write out the chunk description.
Ian Rogers15bf2d32012-08-28 17:33:04 -07003230 length /= ALLOCATION_UNIT_SIZE; // Convert to allocation units.
3231 totalAllocationUnits_ += length;
3232 while (length > 256) {
Ian Rogers30fab402012-01-23 15:43:46 -08003233 *p_++ = state | HPSG_PARTIAL;
3234 *p_++ = 255; // length - 1
Ian Rogers15bf2d32012-08-28 17:33:04 -07003235 length -= 256;
Elliott Hughesa2155262011-11-16 16:26:58 -08003236 }
Ian Rogers30fab402012-01-23 15:43:46 -08003237 *p_++ = state;
Ian Rogers15bf2d32012-08-28 17:33:04 -07003238 *p_++ = length - 1;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003239 }
3240
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003241 uint8_t ExamineObject(const mirror::Object* o, bool is_native_heap)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003242 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
Elliott Hughesa2155262011-11-16 16:26:58 -08003243 if (o == NULL) {
3244 return HPSG_STATE(SOLIDITY_FREE, 0);
3245 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003246
Elliott Hughesa2155262011-11-16 16:26:58 -08003247 // It's an allocated chunk. Figure out what it is.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003248
Elliott Hughesa2155262011-11-16 16:26:58 -08003249 // If we're looking at the native heap, we'll just return
3250 // (SOLIDITY_HARD, KIND_NATIVE) for all allocated chunks.
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003251 if (is_native_heap) {
Elliott Hughesa2155262011-11-16 16:26:58 -08003252 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
3253 }
3254
Ian Rogers5bfa60f2012-09-02 21:17:56 -07003255 if (!Runtime::Current()->GetHeap()->IsLiveObjectLocked(o)) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07003256 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003257 }
3258
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003259 mirror::Class* c = o->GetClass();
Elliott Hughesa2155262011-11-16 16:26:58 -08003260 if (c == NULL) {
3261 // The object was probably just created but hasn't been initialized yet.
3262 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
3263 }
3264
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08003265 if (!Runtime::Current()->GetHeap()->IsHeapAddress(c)) {
Ian Rogers15bf2d32012-08-28 17:33:04 -07003266 LOG(ERROR) << "Invalid class for managed heap object: " << o << " " << c;
Elliott Hughesa2155262011-11-16 16:26:58 -08003267 return HPSG_STATE(SOLIDITY_HARD, KIND_UNKNOWN);
3268 }
3269
3270 if (c->IsClassClass()) {
3271 return HPSG_STATE(SOLIDITY_HARD, KIND_CLASS_OBJECT);
3272 }
3273
3274 if (c->IsArrayClass()) {
3275 if (o->IsObjectArray()) {
3276 return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
3277 }
3278 switch (c->GetComponentSize()) {
3279 case 1: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_1);
3280 case 2: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_2);
3281 case 4: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
3282 case 8: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_8);
3283 }
3284 }
3285
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003286 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
3287 }
3288
Ian Rogers30fab402012-01-23 15:43:46 -08003289 std::vector<uint8_t> buf_;
3290 uint8_t* p_;
3291 uint8_t* pieceLenField_;
Ian Rogers15bf2d32012-08-28 17:33:04 -07003292 void* startOfNextMemoryChunk_;
Ian Rogers30fab402012-01-23 15:43:46 -08003293 size_t totalAllocationUnits_;
3294 uint32_t type_;
3295 bool merge_;
3296 bool needHeader_;
3297
Elliott Hughesa2155262011-11-16 16:26:58 -08003298 DISALLOW_COPY_AND_ASSIGN(HeapChunkContext);
3299};
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003300
3301void Dbg::DdmSendHeapSegments(bool native) {
3302 Dbg::HpsgWhen when;
3303 Dbg::HpsgWhat what;
3304 if (!native) {
3305 when = gDdmHpsgWhen;
3306 what = gDdmHpsgWhat;
3307 } else {
3308 when = gDdmNhsgWhen;
3309 what = gDdmNhsgWhat;
3310 }
3311 if (when == HPSG_WHEN_NEVER) {
3312 return;
3313 }
3314
3315 // Figure out what kind of chunks we'll be sending.
3316 CHECK(what == HPSG_WHAT_MERGED_OBJECTS || what == HPSG_WHAT_DISTINCT_OBJECTS) << static_cast<int>(what);
3317
3318 // First, send a heap start chunk.
3319 uint8_t heap_id[4];
3320 JDWP::Set4BE(&heap_id[0], 1); // Heap id (bogus; we only have one heap).
3321 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHST") : CHUNK_TYPE("HPST"), sizeof(heap_id), heap_id);
3322
3323 // Send a series of heap segment chunks.
Elliott Hughesa2155262011-11-16 16:26:58 -08003324 HeapChunkContext context((what == HPSG_WHAT_MERGED_OBJECTS), native);
3325 if (native) {
Ian Rogers30fab402012-01-23 15:43:46 -08003326 // TODO: enable when bionic has moved to dlmalloc 2.8.5
3327 // dlmalloc_inspect_all(HeapChunkContext::HeapChunkCallback, &context);
3328 UNIMPLEMENTED(WARNING) << "Native heap send heap segments";
Elliott Hughesa2155262011-11-16 16:26:58 -08003329 } else {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08003330 Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07003331 const Spaces& spaces = heap->GetSpaces();
Ian Rogers50b35e22012-10-04 10:09:15 -07003332 Thread* self = Thread::Current();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07003333 for (Spaces::const_iterator cur = spaces.begin(); cur != spaces.end(); ++cur) {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07003334 if ((*cur)->IsAllocSpace()) {
Ian Rogers50b35e22012-10-04 10:09:15 -07003335 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07003336 (*cur)->AsAllocSpace()->Walk(HeapChunkContext::HeapChunkCallback, &context);
3337 }
3338 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07003339 // Walk the large objects, these are not in the AllocSpace.
3340 heap->GetLargeObjectsSpace()->Walk(HeapChunkContext::HeapChunkCallback, &context);
Elliott Hughesa2155262011-11-16 16:26:58 -08003341 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07003342
3343 // Finally, send a heap end chunk.
3344 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHEN") : CHUNK_TYPE("HPEN"), sizeof(heap_id), heap_id);
Elliott Hughes767a1472011-10-26 18:49:02 -07003345}
3346
Elliott Hughes545a0642011-11-08 19:10:03 -08003347void Dbg::SetAllocTrackingEnabled(bool enabled) {
Ian Rogers50b35e22012-10-04 10:09:15 -07003348 MutexLock mu(Thread::Current(), gAllocTrackerLock);
Elliott Hughes545a0642011-11-08 19:10:03 -08003349 if (enabled) {
3350 if (recent_allocation_records_ == NULL) {
3351 LOG(INFO) << "Enabling alloc tracker (" << kNumAllocRecords << " entries, "
3352 << kMaxAllocRecordStackDepth << " frames --> "
3353 << (sizeof(AllocRecord) * kNumAllocRecords) << " bytes)";
3354 gAllocRecordHead = gAllocRecordCount = 0;
3355 recent_allocation_records_ = new AllocRecord[kNumAllocRecords];
3356 CHECK(recent_allocation_records_ != NULL);
3357 }
3358 } else {
3359 delete[] recent_allocation_records_;
3360 recent_allocation_records_ = NULL;
3361 }
3362}
3363
Ian Rogers0399dde2012-06-06 17:09:28 -07003364struct AllocRecordStackVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -08003365 AllocRecordStackVisitor(Thread* thread, AllocRecord* record)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003366 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08003367 : StackVisitor(thread, NULL), record(record), depth(0) {}
Elliott Hughes545a0642011-11-08 19:10:03 -08003368
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003369 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses
3370 // annotalysis.
3371 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS {
Elliott Hughes545a0642011-11-08 19:10:03 -08003372 if (depth >= kMaxAllocRecordStackDepth) {
Elliott Hughes530fa002012-03-12 11:44:49 -07003373 return false;
Elliott Hughes545a0642011-11-08 19:10:03 -08003374 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003375 mirror::AbstractMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07003376 if (!m->IsRuntimeMethod()) {
3377 record->stack[depth].method = m;
3378 record->stack[depth].dex_pc = GetDexPc();
Elliott Hughes530fa002012-03-12 11:44:49 -07003379 ++depth;
Elliott Hughes545a0642011-11-08 19:10:03 -08003380 }
Elliott Hughes530fa002012-03-12 11:44:49 -07003381 return true;
Elliott Hughes545a0642011-11-08 19:10:03 -08003382 }
3383
3384 ~AllocRecordStackVisitor() {
3385 // Clear out any unused stack trace elements.
3386 for (; depth < kMaxAllocRecordStackDepth; ++depth) {
3387 record->stack[depth].method = NULL;
Ian Rogers0399dde2012-06-06 17:09:28 -07003388 record->stack[depth].dex_pc = 0;
Elliott Hughes545a0642011-11-08 19:10:03 -08003389 }
3390 }
3391
3392 AllocRecord* record;
3393 size_t depth;
3394};
3395
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003396void Dbg::RecordAllocation(mirror::Class* type, size_t byte_count) {
Elliott Hughes545a0642011-11-08 19:10:03 -08003397 Thread* self = Thread::Current();
3398 CHECK(self != NULL);
3399
Ian Rogers50b35e22012-10-04 10:09:15 -07003400 MutexLock mu(self, gAllocTrackerLock);
Elliott Hughes545a0642011-11-08 19:10:03 -08003401 if (recent_allocation_records_ == NULL) {
3402 return;
3403 }
3404
3405 // Advance and clip.
3406 if (++gAllocRecordHead == kNumAllocRecords) {
3407 gAllocRecordHead = 0;
3408 }
3409
3410 // Fill in the basics.
3411 AllocRecord* record = &recent_allocation_records_[gAllocRecordHead];
3412 record->type = type;
3413 record->byte_count = byte_count;
3414 record->thin_lock_id = self->GetThinLockId();
3415
3416 // Fill in the stack trace.
Ian Rogers7a22fa62013-01-23 12:16:16 -08003417 AllocRecordStackVisitor visitor(self, record);
Ian Rogers0399dde2012-06-06 17:09:28 -07003418 visitor.WalkStack();
Elliott Hughes545a0642011-11-08 19:10:03 -08003419
3420 if (gAllocRecordCount < kNumAllocRecords) {
3421 ++gAllocRecordCount;
3422 }
3423}
3424
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003425// Returns the index of the head element.
3426//
3427// We point at the most-recently-written record, so if gAllocRecordCount is 1
3428// we want to use the current element. Take "head+1" and subtract count
3429// from it.
3430//
3431// We need to handle underflow in our circular buffer, so we add
3432// kNumAllocRecords and then mask it back down.
Elliott Hughesf8349362012-06-18 15:00:06 -07003433static inline int HeadIndex() EXCLUSIVE_LOCKS_REQUIRED(gAllocTrackerLock) {
Elliott Hughes545a0642011-11-08 19:10:03 -08003434 return (gAllocRecordHead+1 + kNumAllocRecords - gAllocRecordCount) & (kNumAllocRecords-1);
3435}
3436
3437void Dbg::DumpRecentAllocations() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003438 ScopedObjectAccess soa(Thread::Current());
Ian Rogers50b35e22012-10-04 10:09:15 -07003439 MutexLock mu(soa.Self(), gAllocTrackerLock);
Elliott Hughes545a0642011-11-08 19:10:03 -08003440 if (recent_allocation_records_ == NULL) {
3441 LOG(INFO) << "Not recording tracked allocations";
3442 return;
3443 }
3444
3445 // "i" is the head of the list. We want to start at the end of the
3446 // list and move forward to the tail.
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003447 size_t i = HeadIndex();
Elliott Hughes545a0642011-11-08 19:10:03 -08003448 size_t count = gAllocRecordCount;
3449
3450 LOG(INFO) << "Tracked allocations, (head=" << gAllocRecordHead << " count=" << count << ")";
3451 while (count--) {
3452 AllocRecord* record = &recent_allocation_records_[i];
3453
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003454 LOG(INFO) << StringPrintf(" Thread %-2d %6zd bytes ", record->thin_lock_id, record->byte_count)
Elliott Hughes545a0642011-11-08 19:10:03 -08003455 << PrettyClass(record->type);
3456
3457 for (size_t stack_frame = 0; stack_frame < kMaxAllocRecordStackDepth; ++stack_frame) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003458 const mirror::AbstractMethod* m = record->stack[stack_frame].method;
Elliott Hughes545a0642011-11-08 19:10:03 -08003459 if (m == NULL) {
3460 break;
3461 }
3462 LOG(INFO) << " " << PrettyMethod(m) << " line " << record->stack[stack_frame].LineNumber();
3463 }
3464
3465 // pause periodically to help logcat catch up
3466 if ((count % 5) == 0) {
3467 usleep(40000);
3468 }
3469
3470 i = (i + 1) & (kNumAllocRecords-1);
3471 }
3472}
3473
3474class StringTable {
3475 public:
3476 StringTable() {
3477 }
3478
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003479 void Add(const char* s) {
Elliott Hughes545a0642011-11-08 19:10:03 -08003480 table_.insert(s);
3481 }
3482
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003483 size_t IndexOf(const char* s) const {
3484 typedef std::set<std::string>::const_iterator It; // TODO: C++0x auto
3485 It it = table_.find(s);
3486 if (it == table_.end()) {
3487 LOG(FATAL) << "IndexOf(\"" << s << "\") failed";
3488 }
3489 return std::distance(table_.begin(), it);
Elliott Hughes545a0642011-11-08 19:10:03 -08003490 }
3491
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003492 size_t Size() const {
Elliott Hughes545a0642011-11-08 19:10:03 -08003493 return table_.size();
3494 }
3495
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003496 void WriteTo(std::vector<uint8_t>& bytes) const {
3497 typedef std::set<std::string>::const_iterator It; // TODO: C++0x auto
Elliott Hughes545a0642011-11-08 19:10:03 -08003498 for (It it = table_.begin(); it != table_.end(); ++it) {
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003499 const char* s = (*it).c_str();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003500 size_t s_len = CountModifiedUtf8Chars(s);
3501 UniquePtr<uint16_t> s_utf16(new uint16_t[s_len]);
3502 ConvertModifiedUtf8ToUtf16(s_utf16.get(), s);
3503 JDWP::AppendUtf16BE(bytes, s_utf16.get(), s_len);
Elliott Hughes545a0642011-11-08 19:10:03 -08003504 }
3505 }
3506
3507 private:
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003508 std::set<std::string> table_;
Elliott Hughes545a0642011-11-08 19:10:03 -08003509 DISALLOW_COPY_AND_ASSIGN(StringTable);
3510};
3511
3512/*
3513 * The data we send to DDMS contains everything we have recorded.
3514 *
3515 * Message header (all values big-endian):
3516 * (1b) message header len (to allow future expansion); includes itself
3517 * (1b) entry header len
3518 * (1b) stack frame len
3519 * (2b) number of entries
3520 * (4b) offset to string table from start of message
3521 * (2b) number of class name strings
3522 * (2b) number of method name strings
3523 * (2b) number of source file name strings
3524 * For each entry:
3525 * (4b) total allocation size
Elliott Hughes221229c2013-01-08 18:17:50 -08003526 * (2b) thread id
Elliott Hughes545a0642011-11-08 19:10:03 -08003527 * (2b) allocated object's class name index
3528 * (1b) stack depth
3529 * For each stack frame:
3530 * (2b) method's class name
3531 * (2b) method name
3532 * (2b) method source file
3533 * (2b) line number, clipped to 32767; -2 if native; -1 if no source
3534 * (xb) class name strings
3535 * (xb) method name strings
3536 * (xb) source file strings
3537 *
3538 * As with other DDM traffic, strings are sent as a 4-byte length
3539 * followed by UTF-16 data.
3540 *
3541 * We send up 16-bit unsigned indexes into string tables. In theory there
3542 * can be (kMaxAllocRecordStackDepth * kNumAllocRecords) unique strings in
3543 * each table, but in practice there should be far fewer.
3544 *
3545 * The chief reason for using a string table here is to keep the size of
3546 * the DDMS message to a minimum. This is partly to make the protocol
3547 * efficient, but also because we have to form the whole thing up all at
3548 * once in a memory buffer.
3549 *
3550 * We use separate string tables for class names, method names, and source
3551 * files to keep the indexes small. There will generally be no overlap
3552 * between the contents of these tables.
3553 */
3554jbyteArray Dbg::GetRecentAllocations() {
3555 if (false) {
3556 DumpRecentAllocations();
3557 }
3558
Ian Rogers50b35e22012-10-04 10:09:15 -07003559 Thread* self = Thread::Current();
3560 MutexLock mu(self, gAllocTrackerLock);
Elliott Hughes545a0642011-11-08 19:10:03 -08003561
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003562 //
3563 // Part 1: generate string tables.
3564 //
Elliott Hughes545a0642011-11-08 19:10:03 -08003565 StringTable class_names;
3566 StringTable method_names;
3567 StringTable filenames;
3568
3569 int count = gAllocRecordCount;
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003570 int idx = HeadIndex();
Elliott Hughes545a0642011-11-08 19:10:03 -08003571 while (count--) {
3572 AllocRecord* record = &recent_allocation_records_[idx];
3573
Elliott Hughes91250e02011-12-13 22:30:35 -08003574 class_names.Add(ClassHelper(record->type).GetDescriptor());
Elliott Hughes545a0642011-11-08 19:10:03 -08003575
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003576 MethodHelper mh;
Elliott Hughes545a0642011-11-08 19:10:03 -08003577 for (size_t i = 0; i < kMaxAllocRecordStackDepth; i++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003578 mirror::AbstractMethod* m = record->stack[i].method;
Elliott Hughes545a0642011-11-08 19:10:03 -08003579 if (m != NULL) {
Ian Rogersba377812012-05-28 21:16:29 -07003580 mh.ChangeMethod(m);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003581 class_names.Add(mh.GetDeclaringClassDescriptor());
3582 method_names.Add(mh.GetName());
3583 filenames.Add(mh.GetDeclaringClassSourceFile());
Elliott Hughes545a0642011-11-08 19:10:03 -08003584 }
3585 }
3586
3587 idx = (idx + 1) & (kNumAllocRecords-1);
3588 }
3589
3590 LOG(INFO) << "allocation records: " << gAllocRecordCount;
3591
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003592 //
3593 // Part 2: allocate a buffer and generate the output.
3594 //
Elliott Hughes545a0642011-11-08 19:10:03 -08003595 std::vector<uint8_t> bytes;
3596
3597 // (1b) message header len (to allow future expansion); includes itself
3598 // (1b) entry header len
3599 // (1b) stack frame len
3600 const int kMessageHeaderLen = 15;
3601 const int kEntryHeaderLen = 9;
3602 const int kStackFrameLen = 8;
3603 JDWP::Append1BE(bytes, kMessageHeaderLen);
3604 JDWP::Append1BE(bytes, kEntryHeaderLen);
3605 JDWP::Append1BE(bytes, kStackFrameLen);
3606
3607 // (2b) number of entries
3608 // (4b) offset to string table from start of message
3609 // (2b) number of class name strings
3610 // (2b) number of method name strings
3611 // (2b) number of source file name strings
3612 JDWP::Append2BE(bytes, gAllocRecordCount);
3613 size_t string_table_offset = bytes.size();
3614 JDWP::Append4BE(bytes, 0); // We'll patch this later...
3615 JDWP::Append2BE(bytes, class_names.Size());
3616 JDWP::Append2BE(bytes, method_names.Size());
3617 JDWP::Append2BE(bytes, filenames.Size());
3618
3619 count = gAllocRecordCount;
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003620 idx = HeadIndex();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003621 ClassHelper kh;
Elliott Hughes545a0642011-11-08 19:10:03 -08003622 while (count--) {
3623 // For each entry:
3624 // (4b) total allocation size
3625 // (2b) thread id
3626 // (2b) allocated object's class name index
3627 // (1b) stack depth
3628 AllocRecord* record = &recent_allocation_records_[idx];
3629 size_t stack_depth = record->GetDepth();
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003630 kh.ChangeClass(record->type);
3631 size_t allocated_object_class_name_index = class_names.IndexOf(kh.GetDescriptor());
Elliott Hughes545a0642011-11-08 19:10:03 -08003632 JDWP::Append4BE(bytes, record->byte_count);
3633 JDWP::Append2BE(bytes, record->thin_lock_id);
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003634 JDWP::Append2BE(bytes, allocated_object_class_name_index);
Elliott Hughes545a0642011-11-08 19:10:03 -08003635 JDWP::Append1BE(bytes, stack_depth);
3636
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003637 MethodHelper mh;
Elliott Hughes545a0642011-11-08 19:10:03 -08003638 for (size_t stack_frame = 0; stack_frame < stack_depth; ++stack_frame) {
3639 // For each stack frame:
3640 // (2b) method's class name
3641 // (2b) method name
3642 // (2b) method source file
3643 // (2b) line number, clipped to 32767; -2 if native; -1 if no source
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003644 mh.ChangeMethod(record->stack[stack_frame].method);
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003645 size_t class_name_index = class_names.IndexOf(mh.GetDeclaringClassDescriptor());
3646 size_t method_name_index = method_names.IndexOf(mh.GetName());
3647 size_t file_name_index = filenames.IndexOf(mh.GetDeclaringClassSourceFile());
3648 JDWP::Append2BE(bytes, class_name_index);
3649 JDWP::Append2BE(bytes, method_name_index);
3650 JDWP::Append2BE(bytes, file_name_index);
Elliott Hughes545a0642011-11-08 19:10:03 -08003651 JDWP::Append2BE(bytes, record->stack[stack_frame].LineNumber());
3652 }
3653
3654 idx = (idx + 1) & (kNumAllocRecords-1);
3655 }
3656
3657 // (xb) class name strings
3658 // (xb) method name strings
3659 // (xb) source file strings
3660 JDWP::Set4BE(&bytes[string_table_offset], bytes.size());
3661 class_names.WriteTo(bytes);
3662 method_names.WriteTo(bytes);
3663 filenames.WriteTo(bytes);
3664
Ian Rogers50b35e22012-10-04 10:09:15 -07003665 JNIEnv* env = self->GetJniEnv();
Elliott Hughes545a0642011-11-08 19:10:03 -08003666 jbyteArray result = env->NewByteArray(bytes.size());
3667 if (result != NULL) {
3668 env->SetByteArrayRegion(result, 0, bytes.size(), reinterpret_cast<const jbyte*>(&bytes[0]));
3669 }
3670 return result;
3671}
3672
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003673} // namespace art