blob: e3c30f8640497a2a098515907925883e9618e7ce [file] [log] [blame]
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "debugger.h"
18
Elliott Hughes3bb81562011-10-21 18:52:59 -070019#include <sys/uio.h>
20
Elliott Hughes545a0642011-11-08 19:10:03 -080021#include <set>
22
23#include "class_linker.h"
Elliott Hughes1bba14f2011-12-01 18:00:36 -080024#include "class_loader.h"
Ian Rogers776ac1f2012-04-13 23:36:36 -070025#include "dex_instruction.h"
26#if !defined(ART_USE_LLVM_COMPILER)
27#include "oat/runtime/context.h" // For VmapTable
28#endif
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080029#include "object_utils.h"
Elliott Hughesa0e18062012-04-13 15:59:59 -070030#include "safe_map.h"
31#include "scoped_thread_list_lock.h"
Elliott Hughes6a5bd492011-10-28 14:33:57 -070032#include "ScopedLocalRef.h"
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -070033#include "ScopedPrimitiveArray.h"
Ian Rogers30fab402012-01-23 15:43:46 -080034#include "space.h"
Elliott Hughes47fce012011-10-25 18:37:19 -070035#include "stack_indirect_reference_table.h"
Elliott Hughes475fc232011-10-25 15:00:35 -070036#include "thread_list.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070037#include "well_known_classes.h"
Elliott Hughes475fc232011-10-25 15:00:35 -070038
Elliott Hughes872d4ec2011-10-21 17:07:15 -070039namespace art {
40
Elliott Hughes545a0642011-11-08 19:10:03 -080041static const size_t kMaxAllocRecordStackDepth = 16; // Max 255.
42static const size_t kNumAllocRecords = 512; // Must be power of 2.
43
Elliott Hughes436e3722012-02-17 20:01:47 -080044static const uintptr_t kInvalidId = 1;
45static const Object* kInvalidObject = reinterpret_cast<Object*>(kInvalidId);
46
Elliott Hughes475fc232011-10-25 15:00:35 -070047class ObjectRegistry {
48 public:
49 ObjectRegistry() : lock_("ObjectRegistry lock") {
50 }
51
52 JDWP::ObjectId Add(Object* o) {
53 if (o == NULL) {
54 return 0;
55 }
56 JDWP::ObjectId id = static_cast<JDWP::ObjectId>(reinterpret_cast<uintptr_t>(o));
57 MutexLock mu(lock_);
Elliott Hughesa0e18062012-04-13 15:59:59 -070058 map_.Overwrite(id, o);
Elliott Hughes475fc232011-10-25 15:00:35 -070059 return id;
60 }
61
Elliott Hughes234ab152011-10-26 14:02:26 -070062 void Clear() {
63 MutexLock mu(lock_);
64 LOG(DEBUG) << "Debugger has detached; object registry had " << map_.size() << " entries";
65 map_.clear();
66 }
67
Elliott Hughes475fc232011-10-25 15:00:35 -070068 bool Contains(JDWP::ObjectId id) {
69 MutexLock mu(lock_);
70 return map_.find(id) != map_.end();
71 }
72
Elliott Hughesa2155262011-11-16 16:26:58 -080073 template<typename T> T Get(JDWP::ObjectId id) {
Elliott Hughes436e3722012-02-17 20:01:47 -080074 if (id == 0) {
75 return NULL;
76 }
77
Elliott Hughesa2155262011-11-16 16:26:58 -080078 MutexLock mu(lock_);
Elliott Hughesa0e18062012-04-13 15:59:59 -070079 typedef SafeMap<JDWP::ObjectId, Object*>::iterator It; // C++0x auto
Elliott Hughesa2155262011-11-16 16:26:58 -080080 It it = map_.find(id);
Elliott Hughes436e3722012-02-17 20:01:47 -080081 return (it != map_.end()) ? reinterpret_cast<T>(it->second) : reinterpret_cast<T>(kInvalidId);
Elliott Hughesa2155262011-11-16 16:26:58 -080082 }
83
Elliott Hughesbfe487b2011-10-26 15:48:55 -070084 void VisitRoots(Heap::RootVisitor* visitor, void* arg) {
85 MutexLock mu(lock_);
Elliott Hughesa0e18062012-04-13 15:59:59 -070086 typedef SafeMap<JDWP::ObjectId, Object*>::iterator It; // C++0x auto
Elliott Hughesbfe487b2011-10-26 15:48:55 -070087 for (It it = map_.begin(); it != map_.end(); ++it) {
88 visitor(it->second, arg);
89 }
90 }
91
Elliott Hughes475fc232011-10-25 15:00:35 -070092 private:
93 Mutex lock_;
Elliott Hughesa0e18062012-04-13 15:59:59 -070094 SafeMap<JDWP::ObjectId, Object*> map_;
Elliott Hughes475fc232011-10-25 15:00:35 -070095};
96
Elliott Hughes545a0642011-11-08 19:10:03 -080097struct AllocRecordStackTraceElement {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080098 Method* method;
Ian Rogers0399dde2012-06-06 17:09:28 -070099 uint32_t dex_pc;
Elliott Hughes545a0642011-11-08 19:10:03 -0800100
101 int32_t LineNumber() const {
Ian Rogers0399dde2012-06-06 17:09:28 -0700102 return MethodHelper(method).GetLineNumFromDexPC(dex_pc);
Elliott Hughes545a0642011-11-08 19:10:03 -0800103 }
104};
105
106struct AllocRecord {
107 Class* type;
108 size_t byte_count;
109 uint16_t thin_lock_id;
110 AllocRecordStackTraceElement stack[kMaxAllocRecordStackDepth]; // Unused entries have NULL method.
111
112 size_t GetDepth() {
113 size_t depth = 0;
114 while (depth < kMaxAllocRecordStackDepth && stack[depth].method != NULL) {
115 ++depth;
116 }
117 return depth;
118 }
119};
120
Elliott Hughes86964332012-02-15 19:37:42 -0800121struct Breakpoint {
122 Method* method;
Elliott Hughesa656a0f2012-02-21 18:03:44 -0800123 uint32_t dex_pc;
124 Breakpoint(Method* method, uint32_t dex_pc) : method(method), dex_pc(dex_pc) {}
Elliott Hughes86964332012-02-15 19:37:42 -0800125};
126
127static std::ostream& operator<<(std::ostream& os, const Breakpoint& rhs) {
Elliott Hughes229feb72012-02-23 13:33:29 -0800128 os << StringPrintf("Breakpoint[%s @%#x]", PrettyMethod(rhs.method).c_str(), rhs.dex_pc);
Elliott Hughes86964332012-02-15 19:37:42 -0800129 return os;
130}
131
132struct SingleStepControl {
133 // Are we single-stepping right now?
134 bool is_active;
135 Thread* thread;
136
137 JDWP::JdwpStepSize step_size;
138 JDWP::JdwpStepDepth step_depth;
139
140 const Method* method;
Elliott Hughes2435a572012-02-17 16:07:41 -0800141 int32_t line_number; // Or -1 for native methods.
142 std::set<uint32_t> dex_pcs;
Elliott Hughes86964332012-02-15 19:37:42 -0800143 int stack_depth;
144};
145
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700146// JDWP is allowed unless the Zygote forbids it.
147static bool gJdwpAllowed = true;
148
Elliott Hughesc0f09332012-03-26 13:27:06 -0700149// Was there a -Xrunjdwp or -agentlib:jdwp= argument on the command line?
Elliott Hughes3bb81562011-10-21 18:52:59 -0700150static bool gJdwpConfigured = false;
151
Elliott Hughesc0f09332012-03-26 13:27:06 -0700152// Broken-down JDWP options. (Only valid if IsJdwpConfigured() is true.)
Elliott Hughes376a7a02011-10-24 18:35:55 -0700153static JDWP::JdwpOptions gJdwpOptions;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700154
155// Runtime JDWP state.
156static JDWP::JdwpState* gJdwpState = NULL;
157static bool gDebuggerConnected; // debugger or DDMS is connected.
158static bool gDebuggerActive; // debugger is making requests.
Elliott Hughes86964332012-02-15 19:37:42 -0800159static bool gDisposed; // debugger called VirtualMachine.Dispose, so we should drop the connection.
Elliott Hughes3bb81562011-10-21 18:52:59 -0700160
Elliott Hughes47fce012011-10-25 18:37:19 -0700161static bool gDdmThreadNotification = false;
162
Elliott Hughes767a1472011-10-26 18:49:02 -0700163// DDMS GC-related settings.
164static Dbg::HpifWhen gDdmHpifWhen = Dbg::HPIF_WHEN_NEVER;
165static Dbg::HpsgWhen gDdmHpsgWhen = Dbg::HPSG_WHEN_NEVER;
166static Dbg::HpsgWhat gDdmHpsgWhat;
167static Dbg::HpsgWhen gDdmNhsgWhen = Dbg::HPSG_WHEN_NEVER;
168static Dbg::HpsgWhat gDdmNhsgWhat;
169
Elliott Hughes475fc232011-10-25 15:00:35 -0700170static ObjectRegistry* gRegistry = NULL;
171
Elliott Hughes545a0642011-11-08 19:10:03 -0800172// Recent allocation tracking.
173static Mutex gAllocTrackerLock("AllocTracker lock");
Elliott Hughesf8349362012-06-18 15:00:06 -0700174AllocRecord* Dbg::recent_allocation_records_ PT_GUARDED_BY(gAllocTrackerLock) = NULL; // TODO: CircularBuffer<AllocRecord>
175static size_t gAllocRecordHead GUARDED_BY(gAllocTrackerLock) = 0;
176static size_t gAllocRecordCount GUARDED_BY(gAllocTrackerLock) = 0;
Elliott Hughes545a0642011-11-08 19:10:03 -0800177
Elliott Hughes86964332012-02-15 19:37:42 -0800178// Breakpoints and single-stepping.
179static Mutex gBreakpointsLock("breakpoints lock");
Elliott Hughesf8349362012-06-18 15:00:06 -0700180static std::vector<Breakpoint> gBreakpoints GUARDED_BY(gBreakpointsLock);
181static SingleStepControl gSingleStepControl GUARDED_BY(gBreakpointsLock);
Elliott Hughes86964332012-02-15 19:37:42 -0800182
183static bool IsBreakpoint(Method* m, uint32_t dex_pc) {
184 MutexLock mu(gBreakpointsLock);
185 for (size_t i = 0; i < gBreakpoints.size(); ++i) {
Elliott Hughesa656a0f2012-02-21 18:03:44 -0800186 if (gBreakpoints[i].method == m && gBreakpoints[i].dex_pc == dex_pc) {
Elliott Hughes86964332012-02-15 19:37:42 -0800187 VLOG(jdwp) << "Hit breakpoint #" << i << ": " << gBreakpoints[i];
188 return true;
189 }
190 }
191 return false;
192}
193
Elliott Hughes436e3722012-02-17 20:01:47 -0800194static Array* DecodeArray(JDWP::RefTypeId id, JDWP::JdwpError& status) {
195 Object* o = gRegistry->Get<Object*>(id);
196 if (o == NULL || o == kInvalidObject) {
197 status = JDWP::ERR_INVALID_OBJECT;
198 return NULL;
199 }
200 if (!o->IsArrayInstance()) {
201 status = JDWP::ERR_INVALID_ARRAY;
202 return NULL;
203 }
204 status = JDWP::ERR_NONE;
205 return o->AsArray();
206}
207
208static Class* DecodeClass(JDWP::RefTypeId id, JDWP::JdwpError& status) {
209 Object* o = gRegistry->Get<Object*>(id);
210 if (o == NULL || o == kInvalidObject) {
211 status = JDWP::ERR_INVALID_OBJECT;
212 return NULL;
213 }
214 if (!o->IsClass()) {
215 status = JDWP::ERR_INVALID_CLASS;
216 return NULL;
217 }
218 status = JDWP::ERR_NONE;
219 return o->AsClass();
220}
221
222static Thread* DecodeThread(JDWP::ObjectId threadId) {
223 Object* thread_peer = gRegistry->Get<Object*>(threadId);
224 if (thread_peer == NULL || thread_peer == kInvalidObject) {
225 return NULL;
226 }
227 return Thread::FromManagedThread(thread_peer);
228}
229
Elliott Hughes24437992011-11-30 14:49:33 -0800230static JDWP::JdwpTag BasicTagFromDescriptor(const char* descriptor) {
231 // JDWP deliberately uses the descriptor characters' ASCII values for its enum.
232 // Note that by "basic" we mean that we don't get more specific than JT_OBJECT.
233 return static_cast<JDWP::JdwpTag>(descriptor[0]);
234}
235
236static JDWP::JdwpTag TagFromClass(Class* c) {
Elliott Hughes86b00102011-12-05 17:54:26 -0800237 CHECK(c != NULL);
Elliott Hughes24437992011-11-30 14:49:33 -0800238 if (c->IsArrayClass()) {
239 return JDWP::JT_ARRAY;
240 }
241
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800242 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Elliott Hughes24437992011-11-30 14:49:33 -0800243 if (c->IsStringClass()) {
244 return JDWP::JT_STRING;
245 } else if (c->IsClassClass()) {
246 return JDWP::JT_CLASS_OBJECT;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800247 } else if (class_linker->FindSystemClass("Ljava/lang/Thread;")->IsAssignableFrom(c)) {
Elliott Hughes24437992011-11-30 14:49:33 -0800248 return JDWP::JT_THREAD;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800249 } else if (class_linker->FindSystemClass("Ljava/lang/ThreadGroup;")->IsAssignableFrom(c)) {
Elliott Hughes24437992011-11-30 14:49:33 -0800250 return JDWP::JT_THREAD_GROUP;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800251 } else if (class_linker->FindSystemClass("Ljava/lang/ClassLoader;")->IsAssignableFrom(c)) {
Elliott Hughes24437992011-11-30 14:49:33 -0800252 return JDWP::JT_CLASS_LOADER;
Elliott Hughes24437992011-11-30 14:49:33 -0800253 } else {
254 return JDWP::JT_OBJECT;
255 }
256}
257
258/*
259 * Objects declared to hold Object might actually hold a more specific
260 * type. The debugger may take a special interest in these (e.g. it
261 * wants to display the contents of Strings), so we want to return an
262 * appropriate tag.
263 *
264 * Null objects are tagged JT_OBJECT.
265 */
266static JDWP::JdwpTag TagFromObject(const Object* o) {
267 return (o == NULL) ? JDWP::JT_OBJECT : TagFromClass(o->GetClass());
268}
269
270static bool IsPrimitiveTag(JDWP::JdwpTag tag) {
271 switch (tag) {
272 case JDWP::JT_BOOLEAN:
273 case JDWP::JT_BYTE:
274 case JDWP::JT_CHAR:
275 case JDWP::JT_FLOAT:
276 case JDWP::JT_DOUBLE:
277 case JDWP::JT_INT:
278 case JDWP::JT_LONG:
279 case JDWP::JT_SHORT:
280 case JDWP::JT_VOID:
281 return true;
282 default:
283 return false;
284 }
285}
286
Elliott Hughes3bb81562011-10-21 18:52:59 -0700287/*
288 * Handle one of the JDWP name/value pairs.
289 *
290 * JDWP options are:
291 * help: if specified, show help message and bail
292 * transport: may be dt_socket or dt_shmem
293 * address: for dt_socket, "host:port", or just "port" when listening
294 * server: if "y", wait for debugger to attach; if "n", attach to debugger
295 * timeout: how long to wait for debugger to connect / listen
296 *
297 * Useful with server=n (these aren't supported yet):
298 * onthrow=<exception-name>: connect to debugger when exception thrown
299 * onuncaught=y|n: connect to debugger when uncaught exception thrown
300 * launch=<command-line>: launch the debugger itself
301 *
302 * The "transport" option is required, as is "address" if server=n.
303 */
304static bool ParseJdwpOption(const std::string& name, const std::string& value) {
305 if (name == "transport") {
306 if (value == "dt_socket") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700307 gJdwpOptions.transport = JDWP::kJdwpTransportSocket;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700308 } else if (value == "dt_android_adb") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700309 gJdwpOptions.transport = JDWP::kJdwpTransportAndroidAdb;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700310 } else {
311 LOG(ERROR) << "JDWP transport not supported: " << value;
312 return false;
313 }
314 } else if (name == "server") {
315 if (value == "n") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700316 gJdwpOptions.server = false;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700317 } else if (value == "y") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700318 gJdwpOptions.server = true;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700319 } else {
320 LOG(ERROR) << "JDWP option 'server' must be 'y' or 'n'";
321 return false;
322 }
323 } else if (name == "suspend") {
324 if (value == "n") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700325 gJdwpOptions.suspend = false;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700326 } else if (value == "y") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700327 gJdwpOptions.suspend = true;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700328 } else {
329 LOG(ERROR) << "JDWP option 'suspend' must be 'y' or 'n'";
330 return false;
331 }
332 } else if (name == "address") {
333 /* this is either <port> or <host>:<port> */
334 std::string port_string;
Elliott Hughes376a7a02011-10-24 18:35:55 -0700335 gJdwpOptions.host.clear();
Elliott Hughes3bb81562011-10-21 18:52:59 -0700336 std::string::size_type colon = value.find(':');
337 if (colon != std::string::npos) {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700338 gJdwpOptions.host = value.substr(0, colon);
Elliott Hughes3bb81562011-10-21 18:52:59 -0700339 port_string = value.substr(colon + 1);
340 } else {
341 port_string = value;
342 }
343 if (port_string.empty()) {
344 LOG(ERROR) << "JDWP address missing port: " << value;
345 return false;
346 }
347 char* end;
Elliott Hughesba8eee12012-01-24 20:25:24 -0800348 uint64_t port = strtoul(port_string.c_str(), &end, 10);
349 if (*end != '\0' || port > 0xffff) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700350 LOG(ERROR) << "JDWP address has junk in port field: " << value;
351 return false;
352 }
Elliott Hughes376a7a02011-10-24 18:35:55 -0700353 gJdwpOptions.port = port;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700354 } else if (name == "launch" || name == "onthrow" || name == "oncaught" || name == "timeout") {
355 /* valid but unsupported */
356 LOG(INFO) << "Ignoring JDWP option '" << name << "'='" << value << "'";
357 } else {
358 LOG(INFO) << "Ignoring unrecognized JDWP option '" << name << "'='" << value << "'";
359 }
360
361 return true;
362}
363
364/*
365 * Parse the latter half of a -Xrunjdwp/-agentlib:jdwp= string, e.g.:
366 * "transport=dt_socket,address=8000,server=y,suspend=n"
367 */
368bool Dbg::ParseJdwpOptions(const std::string& options) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800369 VLOG(jdwp) << "ParseJdwpOptions: " << options;
Elliott Hughes47fce012011-10-25 18:37:19 -0700370
Elliott Hughes3bb81562011-10-21 18:52:59 -0700371 std::vector<std::string> pairs;
372 Split(options, ',', pairs);
373
374 for (size_t i = 0; i < pairs.size(); ++i) {
375 std::string::size_type equals = pairs[i].find('=');
376 if (equals == std::string::npos) {
377 LOG(ERROR) << "Can't parse JDWP option '" << pairs[i] << "' in '" << options << "'";
378 return false;
379 }
380 ParseJdwpOption(pairs[i].substr(0, equals), pairs[i].substr(equals + 1));
381 }
382
Elliott Hughes376a7a02011-10-24 18:35:55 -0700383 if (gJdwpOptions.transport == JDWP::kJdwpTransportUnknown) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700384 LOG(ERROR) << "Must specify JDWP transport: " << options;
385 }
Elliott Hughes376a7a02011-10-24 18:35:55 -0700386 if (!gJdwpOptions.server && (gJdwpOptions.host.empty() || gJdwpOptions.port == 0)) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700387 LOG(ERROR) << "Must specify JDWP host and port when server=n: " << options;
388 return false;
389 }
390
391 gJdwpConfigured = true;
392 return true;
393}
394
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700395void Dbg::StartJdwp() {
Elliott Hughesc0f09332012-03-26 13:27:06 -0700396 if (!gJdwpAllowed || !IsJdwpConfigured()) {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700397 // No JDWP for you!
398 return;
399 }
400
Elliott Hughes475fc232011-10-25 15:00:35 -0700401 CHECK(gRegistry == NULL);
402 gRegistry = new ObjectRegistry;
403
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700404 // Init JDWP if the debugger is enabled. This may connect out to a
405 // debugger, passively listen for a debugger, or block waiting for a
406 // debugger.
Elliott Hughes376a7a02011-10-24 18:35:55 -0700407 gJdwpState = JDWP::JdwpState::Create(&gJdwpOptions);
408 if (gJdwpState == NULL) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -0800409 // We probably failed because some other process has the port already, which means that
410 // if we don't abort the user is likely to think they're talking to us when they're actually
411 // talking to that other process.
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800412 LOG(FATAL) << "Debugger thread failed to initialize";
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700413 }
414
415 // If a debugger has already attached, send the "welcome" message.
416 // This may cause us to suspend all threads.
Elliott Hughes376a7a02011-10-24 18:35:55 -0700417 if (gJdwpState->IsActive()) {
Elliott Hughes34e06962012-04-09 13:55:55 -0700418 //ScopedThreadStateChange tsc(Thread::Current(), kRunnable);
Elliott Hughes376a7a02011-10-24 18:35:55 -0700419 if (!gJdwpState->PostVMStart()) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800420 LOG(WARNING) << "Failed to post 'start' message to debugger";
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700421 }
422 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700423}
424
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700425void Dbg::StopJdwp() {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700426 delete gJdwpState;
Elliott Hughes475fc232011-10-25 15:00:35 -0700427 delete gRegistry;
428 gRegistry = NULL;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700429}
430
Elliott Hughes767a1472011-10-26 18:49:02 -0700431void Dbg::GcDidFinish() {
432 if (gDdmHpifWhen != HPIF_WHEN_NEVER) {
Elliott Hughes81ff3182012-03-23 20:35:56 -0700433 LOG(DEBUG) << "Sending heap info to DDM";
Elliott Hughes7162ad92011-10-27 14:08:42 -0700434 DdmSendHeapInfo(gDdmHpifWhen);
Elliott Hughes767a1472011-10-26 18:49:02 -0700435 }
436 if (gDdmHpsgWhen != HPSG_WHEN_NEVER) {
Elliott Hughes81ff3182012-03-23 20:35:56 -0700437 LOG(DEBUG) << "Dumping heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700438 DdmSendHeapSegments(false);
Elliott Hughes767a1472011-10-26 18:49:02 -0700439 }
440 if (gDdmNhsgWhen != HPSG_WHEN_NEVER) {
441 LOG(DEBUG) << "Dumping native heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700442 DdmSendHeapSegments(true);
Elliott Hughes767a1472011-10-26 18:49:02 -0700443 }
444}
445
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700446void Dbg::SetJdwpAllowed(bool allowed) {
447 gJdwpAllowed = allowed;
448}
449
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700450DebugInvokeReq* Dbg::GetInvokeReq() {
Elliott Hughes475fc232011-10-25 15:00:35 -0700451 return Thread::Current()->GetInvokeReq();
452}
453
454Thread* Dbg::GetDebugThread() {
455 return (gJdwpState != NULL) ? gJdwpState->GetDebugThread() : NULL;
456}
457
458void Dbg::ClearWaitForEventThread() {
459 gJdwpState->ClearWaitForEventThread();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700460}
461
462void Dbg::Connected() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700463 CHECK(!gDebuggerConnected);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800464 VLOG(jdwp) << "JDWP has attached";
Elliott Hughes3bb81562011-10-21 18:52:59 -0700465 gDebuggerConnected = true;
Elliott Hughes86964332012-02-15 19:37:42 -0800466 gDisposed = false;
467}
468
469void Dbg::Disposed() {
470 gDisposed = true;
471}
472
473bool Dbg::IsDisposed() {
474 return gDisposed;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700475}
476
Elliott Hughesc0f09332012-03-26 13:27:06 -0700477static void SetDebuggerUpdatesEnabledCallback(Thread* t, void* user_data) {
478 t->SetDebuggerUpdatesEnabled(*reinterpret_cast<bool*>(user_data));
479}
480
481static void SetDebuggerUpdatesEnabled(bool enabled) {
Elliott Hughesf8349362012-06-18 15:00:06 -0700482 Runtime::Current()->GetThreadList()->ForEach(SetDebuggerUpdatesEnabledCallback, &enabled);
Elliott Hughesc0f09332012-03-26 13:27:06 -0700483}
484
Elliott Hughesa2155262011-11-16 16:26:58 -0800485void Dbg::GoActive() {
486 // Enable all debugging features, including scans for breakpoints.
487 // This is a no-op if we're already active.
488 // Only called from the JDWP handler thread.
489 if (gDebuggerActive) {
490 return;
491 }
492
493 LOG(INFO) << "Debugger is active";
494
Elliott Hughesc0f09332012-03-26 13:27:06 -0700495 {
496 // TODO: dalvik only warned if there were breakpoints left over. clear in Dbg::Disconnected?
497 MutexLock mu(gBreakpointsLock);
498 CHECK_EQ(gBreakpoints.size(), 0U);
499 }
Elliott Hughesa2155262011-11-16 16:26:58 -0800500
501 gDebuggerActive = true;
Elliott Hughesc0f09332012-03-26 13:27:06 -0700502 SetDebuggerUpdatesEnabled(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700503}
504
505void Dbg::Disconnected() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700506 CHECK(gDebuggerConnected);
507
Elliott Hughesc0f09332012-03-26 13:27:06 -0700508 LOG(INFO) << "Debugger is no longer active";
Elliott Hughes234ab152011-10-26 14:02:26 -0700509
Elliott Hughesc0f09332012-03-26 13:27:06 -0700510 gDebuggerActive = false;
511 SetDebuggerUpdatesEnabled(false);
Elliott Hughes234ab152011-10-26 14:02:26 -0700512
513 gRegistry->Clear();
514 gDebuggerConnected = false;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700515}
516
Elliott Hughesc0f09332012-03-26 13:27:06 -0700517bool Dbg::IsDebuggerActive() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700518 return gDebuggerActive;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700519}
520
Elliott Hughesc0f09332012-03-26 13:27:06 -0700521bool Dbg::IsJdwpConfigured() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700522 return gJdwpConfigured;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700523}
524
525int64_t Dbg::LastDebuggerActivity() {
Elliott Hughesca951522011-12-05 12:01:32 -0800526 return gJdwpState->LastDebuggerActivity();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700527}
528
529int Dbg::ThreadRunning() {
Elliott Hughes34e06962012-04-09 13:55:55 -0700530 return static_cast<int>(Thread::Current()->SetState(kRunnable));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700531}
532
533int Dbg::ThreadWaiting() {
Elliott Hughes34e06962012-04-09 13:55:55 -0700534 return static_cast<int>(Thread::Current()->SetState(kVmWait));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700535}
536
Elliott Hughes6ba581a2011-10-25 11:45:35 -0700537int Dbg::ThreadContinuing(int new_state) {
Elliott Hughes34e06962012-04-09 13:55:55 -0700538 return static_cast<int>(Thread::Current()->SetState(static_cast<ThreadState>(new_state)));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700539}
540
541void Dbg::UndoDebuggerSuspensions() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700542 Runtime::Current()->GetThreadList()->UndoDebuggerSuspensions();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700543}
544
545void Dbg::Exit(int status) {
Elliott Hughes1bba14f2011-12-01 18:00:36 -0800546 exit(status); // This is all dalvik did.
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700547}
548
Elliott Hughesbfe487b2011-10-26 15:48:55 -0700549void Dbg::VisitRoots(Heap::RootVisitor* visitor, void* arg) {
550 if (gRegistry != NULL) {
551 gRegistry->VisitRoots(visitor, arg);
552 }
553}
554
Elliott Hughesc308a5d2012-02-16 17:12:06 -0800555std::string Dbg::GetClassName(JDWP::RefTypeId classId) {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800556 Object* o = gRegistry->Get<Object*>(classId);
Elliott Hughes436e3722012-02-17 20:01:47 -0800557 if (o == NULL) {
558 return "NULL";
559 }
560 if (o == kInvalidObject) {
561 return StringPrintf("invalid object %p", reinterpret_cast<void*>(classId));
562 }
563 if (!o->IsClass()) {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800564 return StringPrintf("non-class %p", o); // This is only used for debugging output anyway.
565 }
Elliott Hughesc308a5d2012-02-16 17:12:06 -0800566 return DescriptorToName(ClassHelper(o->AsClass()).GetDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700567}
568
Elliott Hughes436e3722012-02-17 20:01:47 -0800569JDWP::JdwpError Dbg::GetClassObject(JDWP::RefTypeId id, JDWP::ObjectId& classObjectId) {
570 JDWP::JdwpError status;
571 Class* c = DecodeClass(id, status);
572 if (c == NULL) {
573 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800574 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800575 classObjectId = gRegistry->Add(c);
576 return JDWP::ERR_NONE;
Elliott Hughes86964332012-02-15 19:37:42 -0800577}
578
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800579JDWP::JdwpError Dbg::GetSuperclass(JDWP::RefTypeId id, JDWP::RefTypeId& superclassId) {
580 JDWP::JdwpError status;
581 Class* c = DecodeClass(id, status);
582 if (c == NULL) {
583 return status;
584 }
585 if (c->IsInterface()) {
586 // http://code.google.com/p/android/issues/detail?id=20856
Elliott Hughesa0933622012-04-17 10:46:02 -0700587 superclassId = 0;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800588 } else {
589 superclassId = gRegistry->Add(c->GetSuperClass());
590 }
591 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700592}
593
Elliott Hughes436e3722012-02-17 20:01:47 -0800594JDWP::JdwpError Dbg::GetClassLoader(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) {
Elliott Hughes1bba14f2011-12-01 18:00:36 -0800595 Object* o = gRegistry->Get<Object*>(id);
Elliott Hughes436e3722012-02-17 20:01:47 -0800596 if (o == NULL || o == kInvalidObject) {
597 return JDWP::ERR_INVALID_OBJECT;
598 }
599 expandBufAddObjectId(pReply, gRegistry->Add(o->GetClass()->GetClassLoader()));
600 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700601}
602
Elliott Hughes436e3722012-02-17 20:01:47 -0800603JDWP::JdwpError Dbg::GetModifiers(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) {
604 JDWP::JdwpError status;
605 Class* c = DecodeClass(id, status);
606 if (c == NULL) {
607 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800608 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800609
610 uint32_t access_flags = c->GetAccessFlags() & kAccJavaFlagsMask;
611
612 // Set ACC_SUPER; dex files don't contain this flag, but all classes are supposed to have it set.
613 // Class.getModifiers doesn't return it, but JDWP does, so we set it here.
614 access_flags |= kAccSuper;
615
616 expandBufAdd4BE(pReply, access_flags);
617
618 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700619}
620
Elliott Hughes436e3722012-02-17 20:01:47 -0800621JDWP::JdwpError Dbg::GetReflectedType(JDWP::RefTypeId classId, JDWP::ExpandBuf* pReply) {
622 JDWP::JdwpError status;
623 Class* c = DecodeClass(classId, status);
624 if (c == NULL) {
625 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800626 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800627
628 expandBufAdd1(pReply, c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS);
629 expandBufAddRefTypeId(pReply, classId);
630 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700631}
632
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800633void Dbg::GetClassList(std::vector<JDWP::RefTypeId>& classes) {
Elliott Hughesa2155262011-11-16 16:26:58 -0800634 // Get the complete list of reference classes (i.e. all classes except
635 // the primitive types).
636 // Returns a newly-allocated buffer full of RefTypeId values.
637 struct ClassListCreator {
Elliott Hughesba8eee12012-01-24 20:25:24 -0800638 explicit ClassListCreator(std::vector<JDWP::RefTypeId>& classes) : classes(classes) {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800639 }
640
Elliott Hughesa2155262011-11-16 16:26:58 -0800641 static bool Visit(Class* c, void* arg) {
642 return reinterpret_cast<ClassListCreator*>(arg)->Visit(c);
643 }
644
645 bool Visit(Class* c) {
646 if (!c->IsPrimitive()) {
647 classes.push_back(static_cast<JDWP::RefTypeId>(gRegistry->Add(c)));
648 }
649 return true;
650 }
651
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800652 std::vector<JDWP::RefTypeId>& classes;
Elliott Hughesa2155262011-11-16 16:26:58 -0800653 };
654
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800655 ClassListCreator clc(classes);
Elliott Hughesa2155262011-11-16 16:26:58 -0800656 Runtime::Current()->GetClassLinker()->VisitClasses(ClassListCreator::Visit, &clc);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700657}
658
Elliott Hughes436e3722012-02-17 20:01:47 -0800659JDWP::JdwpError Dbg::GetClassInfo(JDWP::RefTypeId classId, JDWP::JdwpTypeTag* pTypeTag, uint32_t* pStatus, std::string* pDescriptor) {
660 JDWP::JdwpError status;
661 Class* c = DecodeClass(classId, status);
662 if (c == NULL) {
663 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800664 }
665
Elliott Hughesa2155262011-11-16 16:26:58 -0800666 if (c->IsArrayClass()) {
667 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
668 *pTypeTag = JDWP::TT_ARRAY;
669 } else {
670 if (c->IsErroneous()) {
671 *pStatus = JDWP::CS_ERROR;
672 } else {
673 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED | JDWP::CS_INITIALIZED;
674 }
675 *pTypeTag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
676 }
677
678 if (pDescriptor != NULL) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800679 *pDescriptor = ClassHelper(c).GetDescriptor();
Elliott Hughesa2155262011-11-16 16:26:58 -0800680 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800681 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700682}
683
Elliott Hughesc3b77c72011-12-15 20:56:48 -0800684void Dbg::FindLoadedClassBySignature(const char* descriptor, std::vector<JDWP::RefTypeId>& ids) {
Elliott Hughes6fa602d2011-12-02 17:54:25 -0800685 std::vector<Class*> classes;
686 Runtime::Current()->GetClassLinker()->LookupClasses(descriptor, classes);
687 ids.clear();
688 for (size_t i = 0; i < classes.size(); ++i) {
689 ids.push_back(gRegistry->Add(classes[i]));
690 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700691}
692
Elliott Hughes2435a572012-02-17 16:07:41 -0800693JDWP::JdwpError Dbg::GetReferenceType(JDWP::ObjectId objectId, JDWP::ExpandBuf* pReply) {
Elliott Hughes499c5132011-11-17 14:55:11 -0800694 Object* o = gRegistry->Get<Object*>(objectId);
Elliott Hughes436e3722012-02-17 20:01:47 -0800695 if (o == NULL || o == kInvalidObject) {
Elliott Hughes2435a572012-02-17 16:07:41 -0800696 return JDWP::ERR_INVALID_OBJECT;
Elliott Hughes499c5132011-11-17 14:55:11 -0800697 }
Elliott Hughes2435a572012-02-17 16:07:41 -0800698
699 JDWP::JdwpTypeTag type_tag;
700 if (o->GetClass()->IsArrayClass()) {
701 type_tag = JDWP::TT_ARRAY;
702 } else if (o->GetClass()->IsInterface()) {
703 type_tag = JDWP::TT_INTERFACE;
704 } else {
705 type_tag = JDWP::TT_CLASS;
706 }
707 JDWP::RefTypeId type_id = gRegistry->Add(o->GetClass());
708
709 expandBufAdd1(pReply, type_tag);
710 expandBufAddRefTypeId(pReply, type_id);
711
712 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700713}
714
Elliott Hughes436e3722012-02-17 20:01:47 -0800715JDWP::JdwpError Dbg::GetSignature(JDWP::RefTypeId classId, std::string& signature) {
Elliott Hughes1fe7afb2012-02-13 17:23:03 -0800716 JDWP::JdwpError status;
Elliott Hughes436e3722012-02-17 20:01:47 -0800717 Class* c = DecodeClass(classId, status);
Elliott Hughes1fe7afb2012-02-13 17:23:03 -0800718 if (c == NULL) {
719 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800720 }
Elliott Hughes1fe7afb2012-02-13 17:23:03 -0800721 signature = ClassHelper(c).GetDescriptor();
722 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700723}
724
Elliott Hughes436e3722012-02-17 20:01:47 -0800725JDWP::JdwpError Dbg::GetSourceFile(JDWP::RefTypeId classId, std::string& result) {
726 JDWP::JdwpError status;
727 Class* c = DecodeClass(classId, status);
728 if (c == NULL) {
729 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800730 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800731 result = ClassHelper(c).GetSourceFile();
732 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700733}
734
Elliott Hughes546b9862012-06-20 16:06:13 -0700735JDWP::JdwpError Dbg::GetObjectTag(JDWP::ObjectId objectId, uint8_t& tag) {
Elliott Hughes24437992011-11-30 14:49:33 -0800736 Object* o = gRegistry->Get<Object*>(objectId);
Elliott Hughes546b9862012-06-20 16:06:13 -0700737 if (o == kInvalidObject) {
738 return JDWP::ERR_INVALID_OBJECT;
739 }
740 tag = TagFromObject(o);
741 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700742}
743
Elliott Hughesaed4be92011-12-02 16:16:23 -0800744size_t Dbg::GetTagWidth(JDWP::JdwpTag tag) {
Elliott Hughesdbb40792011-11-18 17:05:22 -0800745 switch (tag) {
746 case JDWP::JT_VOID:
747 return 0;
748 case JDWP::JT_BYTE:
749 case JDWP::JT_BOOLEAN:
750 return 1;
751 case JDWP::JT_CHAR:
752 case JDWP::JT_SHORT:
753 return 2;
754 case JDWP::JT_FLOAT:
755 case JDWP::JT_INT:
756 return 4;
757 case JDWP::JT_ARRAY:
758 case JDWP::JT_OBJECT:
759 case JDWP::JT_STRING:
760 case JDWP::JT_THREAD:
761 case JDWP::JT_THREAD_GROUP:
762 case JDWP::JT_CLASS_LOADER:
763 case JDWP::JT_CLASS_OBJECT:
764 return sizeof(JDWP::ObjectId);
765 case JDWP::JT_DOUBLE:
766 case JDWP::JT_LONG:
767 return 8;
768 default:
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800769 LOG(FATAL) << "Unknown tag " << tag;
Elliott Hughesdbb40792011-11-18 17:05:22 -0800770 return -1;
771 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700772}
773
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800774JDWP::JdwpError Dbg::GetArrayLength(JDWP::ObjectId arrayId, int& length) {
775 JDWP::JdwpError status;
776 Array* a = DecodeArray(arrayId, status);
777 if (a == NULL) {
778 return status;
Elliott Hughes24437992011-11-30 14:49:33 -0800779 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800780 length = a->GetLength();
781 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700782}
783
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800784JDWP::JdwpError Dbg::OutputArray(JDWP::ObjectId arrayId, int offset, int count, JDWP::ExpandBuf* pReply) {
785 JDWP::JdwpError status;
786 Array* a = DecodeArray(arrayId, status);
787 if (a == NULL) {
788 return status;
789 }
Elliott Hughes24437992011-11-30 14:49:33 -0800790
791 if (offset < 0 || count < 0 || offset > a->GetLength() || a->GetLength() - offset < count) {
792 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800793 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughes24437992011-11-30 14:49:33 -0800794 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800795 std::string descriptor(ClassHelper(a->GetClass()).GetDescriptor());
Elliott Hughes24437992011-11-30 14:49:33 -0800796 JDWP::JdwpTag tag = BasicTagFromDescriptor(descriptor.c_str() + 1);
797
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800798 expandBufAdd1(pReply, tag);
799 expandBufAdd4BE(pReply, count);
800
Elliott Hughes24437992011-11-30 14:49:33 -0800801 if (IsPrimitiveTag(tag)) {
802 size_t width = GetTagWidth(tag);
Elliott Hughes24437992011-11-30 14:49:33 -0800803 uint8_t* dst = expandBufAddSpace(pReply, count * width);
804 if (width == 8) {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800805 const uint64_t* src8 = reinterpret_cast<uint64_t*>(a->GetRawData(sizeof(uint64_t)));
Elliott Hughes24437992011-11-30 14:49:33 -0800806 for (int i = 0; i < count; ++i) JDWP::Write8BE(&dst, src8[offset + i]);
807 } else if (width == 4) {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800808 const uint32_t* src4 = reinterpret_cast<uint32_t*>(a->GetRawData(sizeof(uint32_t)));
Elliott Hughes24437992011-11-30 14:49:33 -0800809 for (int i = 0; i < count; ++i) JDWP::Write4BE(&dst, src4[offset + i]);
810 } else if (width == 2) {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800811 const uint16_t* src2 = reinterpret_cast<uint16_t*>(a->GetRawData(sizeof(uint16_t)));
Elliott Hughes24437992011-11-30 14:49:33 -0800812 for (int i = 0; i < count; ++i) JDWP::Write2BE(&dst, src2[offset + i]);
813 } else {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800814 const uint8_t* src = reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint8_t)));
Elliott Hughes24437992011-11-30 14:49:33 -0800815 memcpy(dst, &src[offset * width], count * width);
816 }
817 } else {
818 ObjectArray<Object>* oa = a->AsObjectArray<Object>();
819 for (int i = 0; i < count; ++i) {
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800820 Object* element = oa->Get(offset + i);
Elliott Hughes24437992011-11-30 14:49:33 -0800821 JDWP::JdwpTag specific_tag = (element != NULL) ? TagFromObject(element) : tag;
822 expandBufAdd1(pReply, specific_tag);
823 expandBufAddObjectId(pReply, gRegistry->Add(element));
824 }
825 }
826
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800827 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700828}
829
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800830JDWP::JdwpError Dbg::SetArrayElements(JDWP::ObjectId arrayId, int offset, int count, const uint8_t* src) {
831 JDWP::JdwpError status;
832 Array* a = DecodeArray(arrayId, status);
833 if (a == NULL) {
834 return status;
835 }
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800836
837 if (offset < 0 || count < 0 || offset > a->GetLength() || a->GetLength() - offset < count) {
838 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800839 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800840 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800841 std::string descriptor(ClassHelper(a->GetClass()).GetDescriptor());
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800842 JDWP::JdwpTag tag = BasicTagFromDescriptor(descriptor.c_str() + 1);
843
844 if (IsPrimitiveTag(tag)) {
845 size_t width = GetTagWidth(tag);
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800846 if (width == 8) {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800847 uint8_t* dst = &(reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint64_t)))[offset * width]);
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800848 for (int i = 0; i < count; ++i) {
849 // Handle potentially non-aligned memory access one byte at a time for ARM's benefit.
850 uint64_t value;
851 for (size_t j = 0; j < sizeof(uint64_t); ++j) reinterpret_cast<uint8_t*>(&value)[j] = src[j];
852 src += sizeof(uint64_t);
853 JDWP::Write8BE(&dst, value);
854 }
855 } else if (width == 4) {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800856 uint8_t* dst = &(reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint32_t)))[offset * width]);
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800857 const uint32_t* src4 = reinterpret_cast<const uint32_t*>(src);
858 for (int i = 0; i < count; ++i) JDWP::Write4BE(&dst, src4[i]);
859 } else if (width == 2) {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800860 uint8_t* dst = &(reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint16_t)))[offset * width]);
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800861 const uint16_t* src2 = reinterpret_cast<const uint16_t*>(src);
862 for (int i = 0; i < count; ++i) JDWP::Write2BE(&dst, src2[i]);
863 } else {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800864 uint8_t* dst = &(reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint8_t)))[offset * width]);
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800865 memcpy(&dst[offset * width], src, count * width);
866 }
867 } else {
868 ObjectArray<Object>* oa = a->AsObjectArray<Object>();
869 for (int i = 0; i < count; ++i) {
870 JDWP::ObjectId id = JDWP::ReadObjectId(&src);
Elliott Hughes436e3722012-02-17 20:01:47 -0800871 Object* o = gRegistry->Get<Object*>(id);
872 if (o == kInvalidObject) {
873 return JDWP::ERR_INVALID_OBJECT;
874 }
875 oa->Set(offset + i, o);
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800876 }
877 }
878
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800879 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700880}
881
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800882JDWP::ObjectId Dbg::CreateString(const std::string& str) {
883 return gRegistry->Add(String::AllocFromModifiedUtf8(str.c_str()));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700884}
885
Elliott Hughes436e3722012-02-17 20:01:47 -0800886JDWP::JdwpError Dbg::CreateObject(JDWP::RefTypeId classId, JDWP::ObjectId& new_object) {
887 JDWP::JdwpError status;
888 Class* c = DecodeClass(classId, status);
889 if (c == NULL) {
890 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800891 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800892 new_object = gRegistry->Add(c->AllocObject());
893 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700894}
895
Elliott Hughesbf13d362011-12-08 15:51:37 -0800896/*
897 * Used by Eclipse's "Display" view to evaluate "new byte[5]" to get "(byte[]) [0, 0, 0, 0, 0]".
898 */
Elliott Hughes436e3722012-02-17 20:01:47 -0800899JDWP::JdwpError Dbg::CreateArrayObject(JDWP::RefTypeId arrayClassId, uint32_t length, JDWP::ObjectId& new_array) {
900 JDWP::JdwpError status;
901 Class* c = DecodeClass(arrayClassId, status);
902 if (c == NULL) {
903 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800904 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800905 new_array = gRegistry->Add(Array::Alloc(c, length));
906 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700907}
908
909bool Dbg::MatchType(JDWP::RefTypeId instClassId, JDWP::RefTypeId classId) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800910 JDWP::JdwpError status;
911 Class* c1 = DecodeClass(instClassId, status);
Elliott Hughesa656a0f2012-02-21 18:03:44 -0800912 CHECK(c1 != NULL);
Elliott Hughes436e3722012-02-17 20:01:47 -0800913 Class* c2 = DecodeClass(classId, status);
Elliott Hughesa656a0f2012-02-21 18:03:44 -0800914 CHECK(c2 != NULL);
915 return c1->IsAssignableFrom(c2);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700916}
917
Elliott Hughes86964332012-02-15 19:37:42 -0800918static JDWP::FieldId ToFieldId(const Field* f) {
Elliott Hughes03181a82011-11-17 17:22:21 -0800919#ifdef MOVING_GARBAGE_COLLECTOR
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700920 UNIMPLEMENTED(FATAL);
Elliott Hughes03181a82011-11-17 17:22:21 -0800921#else
922 return static_cast<JDWP::FieldId>(reinterpret_cast<uintptr_t>(f));
923#endif
924}
925
Elliott Hughes86964332012-02-15 19:37:42 -0800926static JDWP::MethodId ToMethodId(const Method* m) {
Elliott Hughes03181a82011-11-17 17:22:21 -0800927#ifdef MOVING_GARBAGE_COLLECTOR
928 UNIMPLEMENTED(FATAL);
929#else
930 return static_cast<JDWP::MethodId>(reinterpret_cast<uintptr_t>(m));
931#endif
932}
933
Elliott Hughes86964332012-02-15 19:37:42 -0800934static Field* FromFieldId(JDWP::FieldId fid) {
Elliott Hughesaed4be92011-12-02 16:16:23 -0800935#ifdef MOVING_GARBAGE_COLLECTOR
936 UNIMPLEMENTED(FATAL);
937#else
938 return reinterpret_cast<Field*>(static_cast<uintptr_t>(fid));
939#endif
940}
941
Elliott Hughes86964332012-02-15 19:37:42 -0800942static Method* FromMethodId(JDWP::MethodId mid) {
Elliott Hughes03181a82011-11-17 17:22:21 -0800943#ifdef MOVING_GARBAGE_COLLECTOR
944 UNIMPLEMENTED(FATAL);
945#else
946 return reinterpret_cast<Method*>(static_cast<uintptr_t>(mid));
947#endif
948}
949
Ian Rogers0399dde2012-06-06 17:09:28 -0700950static void SetLocation(JDWP::JdwpLocation& location, Method* m, uint32_t dex_pc) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -0800951 if (m == NULL) {
952 memset(&location, 0, sizeof(location));
953 } else {
954 Class* c = m->GetDeclaringClass();
Elliott Hughes74847412012-06-20 18:10:21 -0700955 location.type_tag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
956 location.class_id = gRegistry->Add(c);
957 location.method_id = ToMethodId(m);
Ian Rogers0399dde2012-06-06 17:09:28 -0700958 location.dex_pc = dex_pc;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -0800959 }
Elliott Hughesd07986f2011-12-06 18:27:45 -0800960}
961
Elliott Hughes436e3722012-02-17 20:01:47 -0800962std::string Dbg::GetMethodName(JDWP::RefTypeId, JDWP::MethodId methodId) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800963 Method* m = FromMethodId(methodId);
964 return MethodHelper(m).GetName();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700965}
966
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800967/*
968 * Augment the access flags for synthetic methods and fields by setting
969 * the (as described by the spec) "0xf0000000 bit". Also, strip out any
970 * flags not specified by the Java programming language.
971 */
972static uint32_t MangleAccessFlags(uint32_t accessFlags) {
973 accessFlags &= kAccJavaFlagsMask;
974 if ((accessFlags & kAccSynthetic) != 0) {
975 accessFlags |= 0xf0000000;
976 }
977 return accessFlags;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700978}
979
Elliott Hughesdbb40792011-11-18 17:05:22 -0800980static const uint16_t kEclipseWorkaroundSlot = 1000;
981
982/*
983 * Eclipse appears to expect that the "this" reference is in slot zero.
984 * If it's not, the "variables" display will show two copies of "this",
985 * possibly because it gets "this" from SF.ThisObject and then displays
986 * all locals with nonzero slot numbers.
987 *
988 * So, we remap the item in slot 0 to 1000, and remap "this" to zero. On
989 * SF.GetValues / SF.SetValues we map them back.
Elliott Hughesc5b734a2011-12-01 17:20:58 -0800990 *
991 * TODO: jdb uses the value to determine whether a variable is a local or an argument,
992 * by checking whether it's less than the number of arguments. To make that work, we'd
993 * have to "mangle" all the arguments to come first, not just the implicit argument 'this'.
Elliott Hughesdbb40792011-11-18 17:05:22 -0800994 */
995static uint16_t MangleSlot(uint16_t slot, const char* name) {
996 uint16_t newSlot = slot;
997 if (strcmp(name, "this") == 0) {
998 newSlot = 0;
999 } else if (slot == 0) {
1000 newSlot = kEclipseWorkaroundSlot;
1001 }
1002 return newSlot;
1003}
1004
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001005static uint16_t DemangleSlot(uint16_t slot, Method* m) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001006 if (slot == kEclipseWorkaroundSlot) {
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001007 return 0;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001008 } else if (slot == 0) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001009 const DexFile::CodeItem* code_item = MethodHelper(m).GetCodeItem();
1010 CHECK(code_item != NULL);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001011 return code_item->registers_size_ - code_item->ins_size_;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001012 }
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001013 return slot;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001014}
1015
Elliott Hughes436e3722012-02-17 20:01:47 -08001016JDWP::JdwpError Dbg::OutputDeclaredFields(JDWP::RefTypeId classId, bool with_generic, JDWP::ExpandBuf* pReply) {
1017 JDWP::JdwpError status;
1018 Class* c = DecodeClass(classId, status);
1019 if (c == NULL) {
1020 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001021 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001022
1023 size_t instance_field_count = c->NumInstanceFields();
1024 size_t static_field_count = c->NumStaticFields();
1025
1026 expandBufAdd4BE(pReply, instance_field_count + static_field_count);
1027
1028 for (size_t i = 0; i < instance_field_count + static_field_count; ++i) {
1029 Field* f = (i < instance_field_count) ? c->GetInstanceField(i) : c->GetStaticField(i - instance_field_count);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001030 FieldHelper fh(f);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001031 expandBufAddFieldId(pReply, ToFieldId(f));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001032 expandBufAddUtf8String(pReply, fh.GetName());
1033 expandBufAddUtf8String(pReply, fh.GetTypeDescriptor());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001034 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001035 static const char genericSignature[1] = "";
1036 expandBufAddUtf8String(pReply, genericSignature);
1037 }
1038 expandBufAdd4BE(pReply, MangleAccessFlags(f->GetAccessFlags()));
1039 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001040 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001041}
1042
Elliott Hughes436e3722012-02-17 20:01:47 -08001043JDWP::JdwpError Dbg::OutputDeclaredMethods(JDWP::RefTypeId classId, bool with_generic, JDWP::ExpandBuf* pReply) {
1044 JDWP::JdwpError status;
1045 Class* c = DecodeClass(classId, status);
1046 if (c == NULL) {
1047 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001048 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001049
1050 size_t direct_method_count = c->NumDirectMethods();
1051 size_t virtual_method_count = c->NumVirtualMethods();
1052
1053 expandBufAdd4BE(pReply, direct_method_count + virtual_method_count);
1054
1055 for (size_t i = 0; i < direct_method_count + virtual_method_count; ++i) {
1056 Method* m = (i < direct_method_count) ? c->GetDirectMethod(i) : c->GetVirtualMethod(i - direct_method_count);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001057 MethodHelper mh(m);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001058 expandBufAddMethodId(pReply, ToMethodId(m));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001059 expandBufAddUtf8String(pReply, mh.GetName());
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001060 expandBufAddUtf8String(pReply, mh.GetSignature());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001061 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001062 static const char genericSignature[1] = "";
1063 expandBufAddUtf8String(pReply, genericSignature);
1064 }
1065 expandBufAdd4BE(pReply, MangleAccessFlags(m->GetAccessFlags()));
1066 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001067 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001068}
1069
Elliott Hughes436e3722012-02-17 20:01:47 -08001070JDWP::JdwpError Dbg::OutputDeclaredInterfaces(JDWP::RefTypeId classId, JDWP::ExpandBuf* pReply) {
1071 JDWP::JdwpError status;
1072 Class* c = DecodeClass(classId, status);
1073 if (c == NULL) {
1074 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001075 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001076
1077 ClassHelper kh(c);
Ian Rogersd24e2642012-06-06 21:21:43 -07001078 size_t interface_count = kh.NumDirectInterfaces();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001079 expandBufAdd4BE(pReply, interface_count);
1080 for (size_t i = 0; i < interface_count; ++i) {
Ian Rogersd24e2642012-06-06 21:21:43 -07001081 expandBufAddRefTypeId(pReply, gRegistry->Add(kh.GetDirectInterface(i)));
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001082 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001083 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001084}
1085
Elliott Hughes436e3722012-02-17 20:01:47 -08001086void Dbg::OutputLineTable(JDWP::RefTypeId, JDWP::MethodId methodId, JDWP::ExpandBuf* pReply) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001087 struct DebugCallbackContext {
1088 int numItems;
1089 JDWP::ExpandBuf* pReply;
1090
Elliott Hughes2435a572012-02-17 16:07:41 -08001091 static bool Callback(void* context, uint32_t address, uint32_t line_number) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001092 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
1093 expandBufAdd8BE(pContext->pReply, address);
Elliott Hughes2435a572012-02-17 16:07:41 -08001094 expandBufAdd4BE(pContext->pReply, line_number);
Elliott Hughes03181a82011-11-17 17:22:21 -08001095 pContext->numItems++;
1096 return true;
1097 }
1098 };
1099
1100 Method* m = FromMethodId(methodId);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001101 MethodHelper mh(m);
Elliott Hughes03181a82011-11-17 17:22:21 -08001102 uint64_t start, end;
1103 if (m->IsNative()) {
1104 start = -1;
1105 end = -1;
1106 } else {
1107 start = 0;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001108 // TODO: what are the units supposed to be? *2?
1109 end = mh.GetCodeItem()->insns_size_in_code_units_;
Elliott Hughes03181a82011-11-17 17:22:21 -08001110 }
1111
1112 expandBufAdd8BE(pReply, start);
1113 expandBufAdd8BE(pReply, end);
1114
1115 // Add numLines later
1116 size_t numLinesOffset = expandBufGetLength(pReply);
1117 expandBufAdd4BE(pReply, 0);
1118
1119 DebugCallbackContext context;
1120 context.numItems = 0;
1121 context.pReply = pReply;
1122
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001123 mh.GetDexFile().DecodeDebugInfo(mh.GetCodeItem(), m->IsStatic(), m->GetDexMethodIndex(),
1124 DebugCallbackContext::Callback, NULL, &context);
Elliott Hughes03181a82011-11-17 17:22:21 -08001125
1126 JDWP::Set4BE(expandBufGetBuffer(pReply) + numLinesOffset, context.numItems);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001127}
1128
Elliott Hughes436e3722012-02-17 20:01:47 -08001129void Dbg::OutputVariableTable(JDWP::RefTypeId, JDWP::MethodId methodId, bool with_generic, JDWP::ExpandBuf* pReply) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001130 struct DebugCallbackContext {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001131 JDWP::ExpandBuf* pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001132 size_t variable_count;
1133 bool with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001134
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001135 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 -08001136 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
1137
Elliott Hughesad3da692012-02-24 16:51:35 -08001138 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 -08001139
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001140 slot = MangleSlot(slot, name);
1141
Elliott Hughesdbb40792011-11-18 17:05:22 -08001142 expandBufAdd8BE(pContext->pReply, startAddress);
1143 expandBufAddUtf8String(pContext->pReply, name);
1144 expandBufAddUtf8String(pContext->pReply, descriptor);
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001145 if (pContext->with_generic) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001146 expandBufAddUtf8String(pContext->pReply, signature);
1147 }
1148 expandBufAdd4BE(pContext->pReply, endAddress - startAddress);
1149 expandBufAdd4BE(pContext->pReply, slot);
1150
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001151 ++pContext->variable_count;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001152 }
1153 };
1154
1155 Method* m = FromMethodId(methodId);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001156 MethodHelper mh(m);
1157 const DexFile::CodeItem* code_item = mh.GetCodeItem();
Elliott Hughesdbb40792011-11-18 17:05:22 -08001158
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001159 // arg_count considers doubles and longs to take 2 units.
1160 // variable_count considers everything to take 1 unit.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001161 std::string shorty(mh.GetShorty());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001162 expandBufAdd4BE(pReply, m->NumArgRegisters(shorty));
Elliott Hughesdbb40792011-11-18 17:05:22 -08001163
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001164 // We don't know the total number of variables yet, so leave a blank and update it later.
1165 size_t variable_count_offset = expandBufGetLength(pReply);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001166 expandBufAdd4BE(pReply, 0);
1167
1168 DebugCallbackContext context;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001169 context.pReply = pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001170 context.variable_count = 0;
1171 context.with_generic = with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001172
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001173 mh.GetDexFile().DecodeDebugInfo(code_item, m->IsStatic(), m->GetDexMethodIndex(), NULL,
1174 DebugCallbackContext::Callback, &context);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001175
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001176 JDWP::Set4BE(expandBufGetBuffer(pReply) + variable_count_offset, context.variable_count);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001177}
1178
Elliott Hughesaed4be92011-12-02 16:16:23 -08001179JDWP::JdwpTag Dbg::GetFieldBasicTag(JDWP::FieldId fieldId) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001180 return BasicTagFromDescriptor(FieldHelper(FromFieldId(fieldId)).GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001181}
1182
Elliott Hughesaed4be92011-12-02 16:16:23 -08001183JDWP::JdwpTag Dbg::GetStaticFieldBasicTag(JDWP::FieldId fieldId) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001184 return BasicTagFromDescriptor(FieldHelper(FromFieldId(fieldId)).GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001185}
1186
Elliott Hughes0cf74332012-02-23 23:14:00 -08001187static JDWP::JdwpError GetFieldValueImpl(JDWP::RefTypeId refTypeId, JDWP::ObjectId objectId, JDWP::FieldId fieldId, JDWP::ExpandBuf* pReply, bool is_static) {
1188 JDWP::JdwpError status;
1189 Class* c = DecodeClass(refTypeId, status);
1190 if (refTypeId != 0 && c == NULL) {
1191 return status;
1192 }
1193
Elliott Hughesaed4be92011-12-02 16:16:23 -08001194 Object* o = gRegistry->Get<Object*>(objectId);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001195 if ((!is_static && o == NULL) || o == kInvalidObject) {
1196 return JDWP::ERR_INVALID_OBJECT;
1197 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001198 Field* f = FromFieldId(fieldId);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001199
1200 Class* receiver_class = c;
1201 if (receiver_class == NULL && o != NULL) {
1202 receiver_class = o->GetClass();
1203 }
1204 // TODO: should we give up now if receiver_class is NULL?
1205 if (receiver_class != NULL && !f->GetDeclaringClass()->IsAssignableFrom(receiver_class)) {
1206 LOG(INFO) << "ERR_INVALID_FIELDID: " << PrettyField(f) << " " << PrettyClass(receiver_class);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001207 return JDWP::ERR_INVALID_FIELDID;
1208 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001209
Elliott Hughes0cf74332012-02-23 23:14:00 -08001210 // The RI only enforces the static/non-static mismatch in one direction.
1211 // TODO: should we change the tests and check both?
1212 if (is_static) {
1213 if (!f->IsStatic()) {
1214 return JDWP::ERR_INVALID_FIELDID;
1215 }
1216 } else {
1217 if (f->IsStatic()) {
1218 LOG(WARNING) << "Ignoring non-NULL receiver for ObjectReference.SetValues on static field " << PrettyField(f);
1219 o = NULL;
1220 }
1221 }
1222
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001223 JDWP::JdwpTag tag = BasicTagFromDescriptor(FieldHelper(f).GetTypeDescriptor());
Elliott Hughesaed4be92011-12-02 16:16:23 -08001224
1225 if (IsPrimitiveTag(tag)) {
1226 expandBufAdd1(pReply, tag);
1227 if (tag == JDWP::JT_BOOLEAN || tag == JDWP::JT_BYTE) {
1228 expandBufAdd1(pReply, f->Get32(o));
1229 } else if (tag == JDWP::JT_CHAR || tag == JDWP::JT_SHORT) {
1230 expandBufAdd2BE(pReply, f->Get32(o));
1231 } else if (tag == JDWP::JT_FLOAT || tag == JDWP::JT_INT) {
1232 expandBufAdd4BE(pReply, f->Get32(o));
1233 } else if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
1234 expandBufAdd8BE(pReply, f->Get64(o));
1235 } else {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001236 LOG(FATAL) << "Unknown tag: " << tag;
Elliott Hughesaed4be92011-12-02 16:16:23 -08001237 }
1238 } else {
1239 Object* value = f->GetObject(o);
1240 expandBufAdd1(pReply, TagFromObject(value));
1241 expandBufAddObjectId(pReply, gRegistry->Add(value));
1242 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001243 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001244}
1245
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001246JDWP::JdwpError Dbg::GetFieldValue(JDWP::ObjectId objectId, JDWP::FieldId fieldId, JDWP::ExpandBuf* pReply) {
Elliott Hughes0cf74332012-02-23 23:14:00 -08001247 return GetFieldValueImpl(0, objectId, fieldId, pReply, false);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001248}
1249
Elliott Hughes0cf74332012-02-23 23:14:00 -08001250JDWP::JdwpError Dbg::GetStaticFieldValue(JDWP::RefTypeId refTypeId, JDWP::FieldId fieldId, JDWP::ExpandBuf* pReply) {
1251 return GetFieldValueImpl(refTypeId, 0, fieldId, pReply, true);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001252}
1253
1254static JDWP::JdwpError SetFieldValueImpl(JDWP::ObjectId objectId, JDWP::FieldId fieldId, uint64_t value, int width, bool is_static) {
Elliott Hughesaed4be92011-12-02 16:16:23 -08001255 Object* o = gRegistry->Get<Object*>(objectId);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001256 if ((!is_static && o == NULL) || o == kInvalidObject) {
1257 return JDWP::ERR_INVALID_OBJECT;
1258 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001259 Field* f = FromFieldId(fieldId);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001260
1261 // The RI only enforces the static/non-static mismatch in one direction.
1262 // TODO: should we change the tests and check both?
1263 if (is_static) {
1264 if (!f->IsStatic()) {
1265 return JDWP::ERR_INVALID_FIELDID;
1266 }
1267 } else {
1268 if (f->IsStatic()) {
1269 LOG(WARNING) << "Ignoring non-NULL receiver for ObjectReference.SetValues on static field " << PrettyField(f);
1270 o = NULL;
1271 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001272 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001273
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001274 JDWP::JdwpTag tag = BasicTagFromDescriptor(FieldHelper(f).GetTypeDescriptor());
Elliott Hughesaed4be92011-12-02 16:16:23 -08001275
1276 if (IsPrimitiveTag(tag)) {
1277 if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001278 CHECK_EQ(width, 8);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001279 f->Set64(o, value);
1280 } else {
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001281 CHECK_LE(width, 4);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001282 f->Set32(o, value);
1283 }
1284 } else {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001285 Object* v = gRegistry->Get<Object*>(value);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001286 if (v == kInvalidObject) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001287 return JDWP::ERR_INVALID_OBJECT;
1288 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001289 if (v != NULL) {
1290 Class* field_type = FieldHelper(f).GetType();
1291 if (!field_type->IsAssignableFrom(v->GetClass())) {
1292 return JDWP::ERR_INVALID_OBJECT;
1293 }
1294 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001295 f->SetObject(o, v);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001296 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001297
1298 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001299}
1300
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001301JDWP::JdwpError Dbg::SetFieldValue(JDWP::ObjectId objectId, JDWP::FieldId fieldId, uint64_t value, int width) {
1302 return SetFieldValueImpl(objectId, fieldId, value, width, false);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001303}
1304
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001305JDWP::JdwpError Dbg::SetStaticFieldValue(JDWP::FieldId fieldId, uint64_t value, int width) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001306 return SetFieldValueImpl(0, fieldId, value, width, true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001307}
1308
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001309std::string Dbg::StringToUtf8(JDWP::ObjectId strId) {
1310 String* s = gRegistry->Get<String*>(strId);
1311 return s->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001312}
1313
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001314bool Dbg::GetThreadName(JDWP::ObjectId threadId, std::string& name) {
1315 ScopedThreadListLock thread_list_lock;
1316 Thread* thread = DecodeThread(threadId);
1317 if (thread == NULL) {
1318 return false;
1319 }
Elliott Hughesffb465f2012-03-01 18:46:05 -08001320 thread->GetThreadName(name);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001321 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001322}
1323
Elliott Hughes2435a572012-02-17 16:07:41 -08001324JDWP::JdwpError Dbg::GetThreadGroup(JDWP::ObjectId threadId, JDWP::ExpandBuf* pReply) {
Elliott Hughes499c5132011-11-17 14:55:11 -08001325 Object* thread = gRegistry->Get<Object*>(threadId);
Elliott Hughes436e3722012-02-17 20:01:47 -08001326 if (thread == kInvalidObject) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001327 return JDWP::ERR_INVALID_OBJECT;
1328 }
1329
1330 // Okay, so it's an object, but is it actually a thread?
Elliott Hughes436e3722012-02-17 20:01:47 -08001331 if (DecodeThread(threadId) == NULL) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001332 return JDWP::ERR_INVALID_THREAD;
1333 }
Elliott Hughes499c5132011-11-17 14:55:11 -08001334
1335 Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/Thread;");
1336 CHECK(c != NULL);
1337 Field* f = c->FindInstanceField("group", "Ljava/lang/ThreadGroup;");
1338 CHECK(f != NULL);
1339 Object* group = f->GetObject(thread);
1340 CHECK(group != NULL);
Elliott Hughes2435a572012-02-17 16:07:41 -08001341 JDWP::ObjectId thread_group_id = gRegistry->Add(group);
1342
1343 expandBufAddObjectId(pReply, thread_group_id);
1344 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001345}
1346
Elliott Hughes499c5132011-11-17 14:55:11 -08001347std::string Dbg::GetThreadGroupName(JDWP::ObjectId threadGroupId) {
1348 Object* thread_group = gRegistry->Get<Object*>(threadGroupId);
1349 CHECK(thread_group != NULL);
1350
1351 Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/ThreadGroup;");
1352 CHECK(c != NULL);
1353 Field* f = c->FindInstanceField("name", "Ljava/lang/String;");
1354 CHECK(f != NULL);
1355 String* s = reinterpret_cast<String*>(f->GetObject(thread_group));
1356 return s->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001357}
1358
1359JDWP::ObjectId Dbg::GetThreadGroupParent(JDWP::ObjectId threadGroupId) {
Elliott Hughes4e235312011-12-02 11:34:15 -08001360 Object* thread_group = gRegistry->Get<Object*>(threadGroupId);
1361 CHECK(thread_group != NULL);
1362
1363 Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/ThreadGroup;");
1364 CHECK(c != NULL);
1365 Field* f = c->FindInstanceField("parent", "Ljava/lang/ThreadGroup;");
1366 CHECK(f != NULL);
1367 Object* parent = f->GetObject(thread_group);
1368 return gRegistry->Add(parent);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001369}
1370
1371JDWP::ObjectId Dbg::GetSystemThreadGroupId() {
Elliott Hughes462c9442012-03-23 18:47:50 -07001372 return gRegistry->Add(Thread::GetSystemThreadGroup());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001373}
1374
1375JDWP::ObjectId Dbg::GetMainThreadGroupId() {
Elliott Hughes462c9442012-03-23 18:47:50 -07001376 return gRegistry->Add(Thread::GetMainThreadGroup());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001377}
1378
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001379bool Dbg::GetThreadStatus(JDWP::ObjectId threadId, JDWP::JdwpThreadStatus* pThreadStatus, JDWP::JdwpSuspendStatus* pSuspendStatus) {
Elliott Hughes499c5132011-11-17 14:55:11 -08001380 ScopedThreadListLock thread_list_lock;
1381
1382 Thread* thread = DecodeThread(threadId);
1383 if (thread == NULL) {
1384 return false;
1385 }
1386
Elliott Hughes3ce4b262012-02-24 11:24:02 -08001387 // TODO: if we're in Thread.sleep(long), we should return TS_SLEEPING,
1388 // even if it's implemented using Object.wait(long).
Elliott Hughes499c5132011-11-17 14:55:11 -08001389 switch (thread->GetState()) {
Elliott Hughes34e06962012-04-09 13:55:55 -07001390 case kTerminated: *pThreadStatus = JDWP::TS_ZOMBIE; break;
1391 case kRunnable: *pThreadStatus = JDWP::TS_RUNNING; break;
1392 case kTimedWaiting: *pThreadStatus = JDWP::TS_WAIT; break;
1393 case kBlocked: *pThreadStatus = JDWP::TS_MONITOR; break;
1394 case kWaiting: *pThreadStatus = JDWP::TS_WAIT; break;
1395 case kStarting: *pThreadStatus = JDWP::TS_ZOMBIE; break;
1396 case kNative: *pThreadStatus = JDWP::TS_RUNNING; break;
1397 case kVmWait: *pThreadStatus = JDWP::TS_WAIT; break;
1398 case kSuspended: *pThreadStatus = JDWP::TS_RUNNING; break;
Elliott Hughescf2b2d42012-03-27 17:11:42 -07001399 // Don't add a 'default' here so the compiler can spot incompatible enum changes.
Elliott Hughes499c5132011-11-17 14:55:11 -08001400 }
1401
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001402 *pSuspendStatus = (thread->IsSuspended() ? JDWP::SUSPEND_STATUS_SUSPENDED : JDWP::SUSPEND_STATUS_NOT_SUSPENDED);
Elliott Hughes499c5132011-11-17 14:55:11 -08001403
1404 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001405}
1406
Elliott Hughes2435a572012-02-17 16:07:41 -08001407JDWP::JdwpError Dbg::GetThreadSuspendCount(JDWP::ObjectId threadId, JDWP::ExpandBuf* pReply) {
1408 Thread* thread = DecodeThread(threadId);
1409 if (thread == NULL) {
1410 return JDWP::ERR_INVALID_THREAD;
1411 }
1412 expandBufAdd4BE(pReply, thread->GetSuspendCount());
1413 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001414}
1415
1416bool Dbg::ThreadExists(JDWP::ObjectId threadId) {
Elliott Hughes761928d2011-11-16 18:33:03 -08001417 return DecodeThread(threadId) != NULL;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001418}
1419
1420bool Dbg::IsSuspended(JDWP::ObjectId threadId) {
Elliott Hughes761928d2011-11-16 18:33:03 -08001421 return DecodeThread(threadId)->IsSuspended();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001422}
1423
Elliott Hughesa2155262011-11-16 16:26:58 -08001424void Dbg::GetThreadGroupThreadsImpl(Object* thread_group, JDWP::ObjectId** ppThreadIds, uint32_t* pThreadCount) {
1425 struct ThreadListVisitor {
1426 static void Visit(Thread* t, void* arg) {
1427 reinterpret_cast<ThreadListVisitor*>(arg)->Visit(t);
1428 }
1429
1430 void Visit(Thread* t) {
1431 if (t == Dbg::GetDebugThread()) {
1432 // Skip the JDWP thread. Some debuggers get bent out of shape when they can't suspend and
1433 // query all threads, so it's easier if we just don't tell them about this thread.
1434 return;
1435 }
1436 if (thread_group == NULL || t->GetThreadGroup() == thread_group) {
1437 threads.push_back(gRegistry->Add(t->GetPeer()));
1438 }
1439 }
1440
1441 Object* thread_group;
1442 std::vector<JDWP::ObjectId> threads;
1443 };
1444
1445 ThreadListVisitor tlv;
1446 tlv.thread_group = thread_group;
1447
Elliott Hughesf8349362012-06-18 15:00:06 -07001448 Runtime::Current()->GetThreadList()->ForEach(ThreadListVisitor::Visit, &tlv);
Elliott Hughesa2155262011-11-16 16:26:58 -08001449
1450 *pThreadCount = tlv.threads.size();
1451 if (*pThreadCount == 0) {
1452 *ppThreadIds = NULL;
1453 } else {
1454 *ppThreadIds = new JDWP::ObjectId[*pThreadCount];
1455 for (size_t i = 0; i < *pThreadCount; ++i) {
1456 (*ppThreadIds)[i] = tlv.threads[i];
1457 }
1458 }
1459}
1460
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001461void Dbg::GetThreadGroupThreads(JDWP::ObjectId threadGroupId, JDWP::ObjectId** ppThreadIds, uint32_t* pThreadCount) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001462 GetThreadGroupThreadsImpl(gRegistry->Get<Object*>(threadGroupId), ppThreadIds, pThreadCount);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001463}
1464
1465void Dbg::GetAllThreads(JDWP::ObjectId** ppThreadIds, uint32_t* pThreadCount) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001466 GetThreadGroupThreadsImpl(NULL, ppThreadIds, pThreadCount);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001467}
1468
Elliott Hughes86964332012-02-15 19:37:42 -08001469static int GetStackDepth(Thread* thread) {
Ian Rogers0399dde2012-06-06 17:09:28 -07001470 struct CountStackDepthVisitor : public StackVisitor {
1471 CountStackDepthVisitor(const ManagedStack* stack,
1472 const std::vector<TraceStackFrame>* trace_stack) :
1473 StackVisitor(stack, trace_stack), depth(0) {}
1474
1475 bool VisitFrame() {
1476 if (!GetMethod()->IsRuntimeMethod()) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -08001477 ++depth;
1478 }
Elliott Hughes530fa002012-03-12 11:44:49 -07001479 return true;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001480 }
1481 size_t depth;
1482 };
Ian Rogers0399dde2012-06-06 17:09:28 -07001483 CountStackDepthVisitor visitor(thread->GetManagedStack(), thread->GetTraceStack());
1484 visitor.WalkStack();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001485 return visitor.depth;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001486}
1487
Elliott Hughes86964332012-02-15 19:37:42 -08001488int Dbg::GetThreadFrameCount(JDWP::ObjectId threadId) {
1489 ScopedThreadListLock thread_list_lock;
1490 return GetStackDepth(DecodeThread(threadId));
1491}
1492
Ian Rogers0399dde2012-06-06 17:09:28 -07001493void Dbg::GetThreadFrame(JDWP::ObjectId threadId, int desired_frame_number, JDWP::FrameId* pFrameId,
1494 JDWP::JdwpLocation* pLoc) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001495 ScopedThreadListLock thread_list_lock;
Ian Rogers0399dde2012-06-06 17:09:28 -07001496 struct GetFrameVisitor : public StackVisitor {
1497 GetFrameVisitor(const ManagedStack* stack, const std::vector<TraceStackFrame>* trace_stack,
1498 int desired_frame_number, JDWP::FrameId* pFrameId, JDWP::JdwpLocation* pLoc) :
1499 StackVisitor(stack, trace_stack), depth(0),
1500 desired_frame_number(desired_frame_number), pFrameId(pFrameId), pLoc(pLoc) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001501 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001502
1503 bool VisitFrame() {
1504 if (GetMethod()->IsRuntimeMethod()) {
Elliott Hughes530fa002012-03-12 11:44:49 -07001505 return true; // The debugger can't do anything useful with a frame that has no Method*.
Elliott Hughes03181a82011-11-17 17:22:21 -08001506 }
Elliott Hughes03181a82011-11-17 17:22:21 -08001507 if (depth == desired_frame_number) {
Ian Rogers0399dde2012-06-06 17:09:28 -07001508 *pFrameId = GetFrameId();
1509 SetLocation(*pLoc, GetMethod(), GetDexPc());
Elliott Hughes530fa002012-03-12 11:44:49 -07001510 return false;
Elliott Hughes03181a82011-11-17 17:22:21 -08001511 }
1512 ++depth;
Elliott Hughes530fa002012-03-12 11:44:49 -07001513 return true;
Elliott Hughes03181a82011-11-17 17:22:21 -08001514 }
Elliott Hughes03181a82011-11-17 17:22:21 -08001515 int depth;
Ian Rogers0399dde2012-06-06 17:09:28 -07001516 const int desired_frame_number;
1517 JDWP::FrameId* const pFrameId;
1518 JDWP::JdwpLocation* const pLoc;
Elliott Hughes03181a82011-11-17 17:22:21 -08001519 };
Ian Rogers0399dde2012-06-06 17:09:28 -07001520 Thread* thread = DecodeThread(threadId);
1521 GetFrameVisitor visitor(thread->GetManagedStack(), thread->GetTraceStack(), desired_frame_number,
1522 pFrameId, pLoc);
1523 visitor.WalkStack();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001524}
1525
1526JDWP::ObjectId Dbg::GetThreadSelfId() {
Elliott Hughes475fc232011-10-25 15:00:35 -07001527 return gRegistry->Add(Thread::Current()->GetPeer());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001528}
1529
Elliott Hughes475fc232011-10-25 15:00:35 -07001530void Dbg::SuspendVM() {
Elliott Hughes34e06962012-04-09 13:55:55 -07001531 ScopedThreadStateChange tsc(Thread::Current(), kRunnable); // TODO: do we really want to change back? should the JDWP thread be Runnable usually?
Elliott Hughes475fc232011-10-25 15:00:35 -07001532 Runtime::Current()->GetThreadList()->SuspendAll(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001533}
1534
1535void Dbg::ResumeVM() {
Elliott Hughesc61a2672012-06-21 14:52:29 -07001536 Runtime::Current()->GetThreadList()->UndoDebuggerSuspensions();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001537}
1538
1539void Dbg::SuspendThread(JDWP::ObjectId threadId) {
Elliott Hughes4e235312011-12-02 11:34:15 -08001540 Object* peer = gRegistry->Get<Object*>(threadId);
1541 ScopedThreadListLock thread_list_lock;
1542 Thread* thread = Thread::FromManagedThread(peer);
1543 if (thread == NULL) {
1544 LOG(WARNING) << "No such thread for suspend: " << peer;
1545 return;
1546 }
1547 Runtime::Current()->GetThreadList()->Suspend(thread, true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001548}
1549
1550void Dbg::ResumeThread(JDWP::ObjectId threadId) {
Elliott Hughes4e235312011-12-02 11:34:15 -08001551 Object* peer = gRegistry->Get<Object*>(threadId);
1552 ScopedThreadListLock thread_list_lock;
1553 Thread* thread = Thread::FromManagedThread(peer);
1554 if (thread == NULL) {
1555 LOG(WARNING) << "No such thread for resume: " << peer;
1556 return;
1557 }
Elliott Hughes546b9862012-06-20 16:06:13 -07001558 if (thread->GetSuspendCount() > 0) {
1559 Runtime::Current()->GetThreadList()->Resume(thread, true);
1560 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001561}
1562
1563void Dbg::SuspendSelf() {
Elliott Hughes475fc232011-10-25 15:00:35 -07001564 Runtime::Current()->GetThreadList()->SuspendSelfForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001565}
1566
Ian Rogers0399dde2012-06-06 17:09:28 -07001567struct GetThisVisitor : public StackVisitor {
1568 GetThisVisitor(const ManagedStack* stack, const std::vector<TraceStackFrame>* trace_stack,
1569 Context* context, JDWP::FrameId frameId) :
1570 StackVisitor(stack, trace_stack, context), thisObject_(NULL), frameId_(frameId) {}
1571
1572
1573 virtual bool VisitFrame() {
1574 if (frameId_ != GetFrameId()) {
1575 return true; // continue
1576 }
1577 Method* m = GetMethod();
1578 if (m->IsNative() || m->IsStatic()) {
1579 thisObject_ = NULL;
1580 } else {
1581 uint16_t reg = DemangleSlot(0, m);
1582 thisObject_ = reinterpret_cast<Object*>(GetVReg(m, reg));
1583 }
1584 return false;
Elliott Hughes86b00102011-12-05 17:54:26 -08001585 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001586
1587 Object* thisObject_;
1588 JDWP::FrameId frameId_;
1589};
1590
1591static Object* GetThis(Method** quickFrame) {
1592 struct FrameIdVisitor : public StackVisitor {
1593 FrameIdVisitor(const ManagedStack* stack, const std::vector<TraceStackFrame>* trace_stack,
1594 Method** m) : StackVisitor(stack, trace_stack),
1595 quick_frame_to_find_(m) , frame_id_(0) {}
1596
1597 virtual bool VisitFrame() {
1598 if (quick_frame_to_find_ != GetCurrentQuickFrame()) {
1599 return true; // Continue.
1600 }
1601 frame_id_ = GetFrameId();
1602 return false; // Stop.
1603 }
1604
1605 Method** const quick_frame_to_find_;
1606 JDWP::FrameId frame_id_;
1607 };
1608
1609 Method* m = *quickFrame;
1610 if (m->IsNative() || m->IsStatic()) {
1611 return NULL;
1612 }
1613 Thread* self = Thread::Current();
1614 const ManagedStack* stack = self->GetManagedStack();
1615 const std::vector<TraceStackFrame>* trace_stack = self->GetTraceStack();
1616 FrameIdVisitor frameIdVisitor(stack, trace_stack, quickFrame);
1617 frameIdVisitor.WalkStack();
1618 UniquePtr<Context> context(Context::Create());
1619 GetThisVisitor getThisVisitor(stack, trace_stack, context.get(), frameIdVisitor.frame_id_);
1620 getThisVisitor.WalkStack();
1621 return getThisVisitor.thisObject_;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001622}
1623
1624void Dbg::GetThisObject(JDWP::FrameId frameId, JDWP::ObjectId* pThisId) {
Ian Rogers0399dde2012-06-06 17:09:28 -07001625 UniquePtr<Context> context(Context::Create());
1626 Thread* self = Thread::Current();
1627 GetThisVisitor visitor(self->GetManagedStack(), self->GetTraceStack(), context.get(), frameId);
1628 visitor.WalkStack();
1629 *pThisId = gRegistry->Add(visitor.thisObject_);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001630}
1631
Ian Rogers0399dde2012-06-06 17:09:28 -07001632void Dbg::GetLocalValue(JDWP::ObjectId threadId, JDWP::FrameId frameId, int slot, JDWP::JdwpTag tag, uint8_t* buf, size_t width) {
1633 struct GetLocalVisitor : public StackVisitor {
1634 GetLocalVisitor(const ManagedStack* stack, const std::vector<TraceStackFrame>* trace_stack,
1635 Context* context, JDWP::FrameId frameId, int slot, JDWP::JdwpTag tag,
1636 uint8_t* buf, size_t width) :
1637 StackVisitor(stack, trace_stack, context), frame_id_(frameId), slot_(slot), tag_(tag),
1638 buf_(buf), width_(width) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001639 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001640 bool VisitFrame() {
1641 if (GetFrameId() != frame_id_) {
1642 return true; // Not our frame, carry on.
Elliott Hughesdbb40792011-11-18 17:05:22 -08001643 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001644 // TODO: check that the tag is compatible with the actual type of the slot!
1645 Method* m = GetMethod();
1646 uint16_t reg = DemangleSlot(slot_, m);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001647
Ian Rogers0399dde2012-06-06 17:09:28 -07001648 switch (tag_) {
1649 case JDWP::JT_BOOLEAN:
1650 {
1651 CHECK_EQ(width_, 1U);
1652 uint32_t intVal = GetVReg(m, reg);
1653 VLOG(jdwp) << "get boolean local " << reg << " = " << intVal;
1654 JDWP::Set1(buf_+1, intVal != 0);
1655 }
1656 break;
1657 case JDWP::JT_BYTE:
1658 {
1659 CHECK_EQ(width_, 1U);
1660 uint32_t intVal = GetVReg(m, reg);
1661 VLOG(jdwp) << "get byte local " << reg << " = " << intVal;
1662 JDWP::Set1(buf_+1, intVal);
1663 }
1664 break;
1665 case JDWP::JT_SHORT:
1666 case JDWP::JT_CHAR:
1667 {
1668 CHECK_EQ(width_, 2U);
1669 uint32_t intVal = GetVReg(m, reg);
1670 VLOG(jdwp) << "get short/char local " << reg << " = " << intVal;
1671 JDWP::Set2BE(buf_+1, intVal);
1672 }
1673 break;
1674 case JDWP::JT_INT:
1675 case JDWP::JT_FLOAT:
1676 {
1677 CHECK_EQ(width_, 4U);
1678 uint32_t intVal = GetVReg(m, reg);
1679 VLOG(jdwp) << "get int/float local " << reg << " = " << intVal;
1680 JDWP::Set4BE(buf_+1, intVal);
1681 }
1682 break;
1683 case JDWP::JT_ARRAY:
1684 {
1685 CHECK_EQ(width_, sizeof(JDWP::ObjectId));
1686 Object* o = reinterpret_cast<Object*>(GetVReg(m, reg));
1687 VLOG(jdwp) << "get array local " << reg << " = " << o;
1688 if (!Runtime::Current()->GetHeap()->IsHeapAddress(o)) {
1689 LOG(FATAL) << "Register " << reg << " expected to hold array: " << o;
1690 }
1691 JDWP::SetObjectId(buf_+1, gRegistry->Add(o));
1692 }
1693 break;
1694 case JDWP::JT_CLASS_LOADER:
1695 case JDWP::JT_CLASS_OBJECT:
1696 case JDWP::JT_OBJECT:
1697 case JDWP::JT_STRING:
1698 case JDWP::JT_THREAD:
1699 case JDWP::JT_THREAD_GROUP:
1700 {
1701 CHECK_EQ(width_, sizeof(JDWP::ObjectId));
1702 Object* o = reinterpret_cast<Object*>(GetVReg(m, reg));
1703 VLOG(jdwp) << "get object local " << reg << " = " << o;
1704 if (!Runtime::Current()->GetHeap()->IsHeapAddress(o)) {
1705 LOG(FATAL) << "Register " << reg << " expected to hold object: " << o;
1706 }
1707 tag_ = TagFromObject(o);
1708 JDWP::SetObjectId(buf_+1, gRegistry->Add(o));
1709 }
1710 break;
1711 case JDWP::JT_DOUBLE:
1712 case JDWP::JT_LONG:
1713 {
1714 CHECK_EQ(width_, 8U);
1715 uint32_t lo = GetVReg(m, reg);
1716 uint64_t hi = GetVReg(m, reg + 1);
1717 uint64_t longVal = (hi << 32) | lo;
1718 VLOG(jdwp) << "get double/long local " << hi << ":" << lo << " = " << longVal;
1719 JDWP::Set8BE(buf_+1, longVal);
1720 }
1721 break;
1722 default:
1723 LOG(FATAL) << "Unknown tag " << tag_;
1724 break;
1725 }
1726
1727 // Prepend tag, which may have been updated.
1728 JDWP::Set1(buf_, tag_);
1729 return false;
1730 }
1731
1732 const JDWP::FrameId frame_id_;
1733 const int slot_;
1734 JDWP::JdwpTag tag_;
1735 uint8_t* const buf_;
1736 const size_t width_;
1737 };
1738 Thread* thread = DecodeThread(threadId);
1739 UniquePtr<Context> context(Context::Create());
1740 GetLocalVisitor visitor(thread->GetManagedStack(), thread->GetTraceStack(), context.get(),
1741 frameId, slot, tag, buf, width);
1742 visitor.WalkStack();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001743}
1744
Ian Rogers0399dde2012-06-06 17:09:28 -07001745void Dbg::SetLocalValue(JDWP::ObjectId threadId, JDWP::FrameId frameId, int slot, JDWP::JdwpTag tag,
1746 uint64_t value, size_t width) {
1747 struct SetLocalVisitor : public StackVisitor {
1748 SetLocalVisitor(const ManagedStack* stack, const std::vector<TraceStackFrame>* trace_stack,
1749 JDWP::FrameId frame_id, int slot, JDWP::JdwpTag tag, uint64_t value,
1750 size_t width) :
1751 StackVisitor(stack, trace_stack), frame_id_(frame_id), slot_(slot), tag_(tag),
1752 value_(value), width_(width) {
Elliott Hughescccd84f2011-12-05 16:51:54 -08001753 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001754 bool VisitFrame() {
1755 if (GetFrameId() != frame_id_) {
1756 return true; // Not our frame, carry on.
1757 }
1758 // TODO: check that the tag is compatible with the actual type of the slot!
1759 Method* m = GetMethod();
1760 uint16_t reg = DemangleSlot(slot_, m);
1761
1762 switch (tag_) {
1763 case JDWP::JT_BOOLEAN:
1764 case JDWP::JT_BYTE:
1765 CHECK_EQ(width_, 1U);
1766 SetVReg(m, reg, static_cast<uint32_t>(value_));
1767 break;
1768 case JDWP::JT_SHORT:
1769 case JDWP::JT_CHAR:
1770 CHECK_EQ(width_, 2U);
1771 SetVReg(m, reg, static_cast<uint32_t>(value_));
1772 break;
1773 case JDWP::JT_INT:
1774 case JDWP::JT_FLOAT:
1775 CHECK_EQ(width_, 4U);
1776 SetVReg(m, reg, static_cast<uint32_t>(value_));
1777 break;
1778 case JDWP::JT_ARRAY:
1779 case JDWP::JT_OBJECT:
1780 case JDWP::JT_STRING:
1781 {
1782 CHECK_EQ(width_, sizeof(JDWP::ObjectId));
1783 Object* o = gRegistry->Get<Object*>(static_cast<JDWP::ObjectId>(value_));
1784 if (o == kInvalidObject) {
1785 UNIMPLEMENTED(FATAL) << "return an error code when given an invalid object to store";
1786 }
1787 SetVReg(m, reg, static_cast<uint32_t>(reinterpret_cast<uintptr_t>(o)));
1788 }
1789 break;
1790 case JDWP::JT_DOUBLE:
1791 case JDWP::JT_LONG:
1792 CHECK_EQ(width_, 8U);
1793 SetVReg(m, reg, static_cast<uint32_t>(value_));
1794 SetVReg(m, reg + 1, static_cast<uint32_t>(value_ >> 32));
1795 break;
1796 default:
1797 LOG(FATAL) << "Unknown tag " << tag_;
1798 break;
1799 }
1800 return false;
1801 }
1802
1803 const JDWP::FrameId frame_id_;
1804 const int slot_;
1805 const JDWP::JdwpTag tag_;
1806 const uint64_t value_;
1807 const size_t width_;
1808 };
1809 Thread* thread = DecodeThread(threadId);
1810 SetLocalVisitor visitor(thread->GetManagedStack(), thread->GetTraceStack(), frameId, slot, tag,
1811 value, width);
1812 visitor.WalkStack();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001813}
1814
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001815void Dbg::PostLocationEvent(const Method* m, int dex_pc, Object* this_object, int event_flags) {
1816 Class* c = m->GetDeclaringClass();
1817
1818 JDWP::JdwpLocation location;
Elliott Hughes74847412012-06-20 18:10:21 -07001819 location.type_tag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
1820 location.class_id = gRegistry->Add(c);
1821 location.method_id = ToMethodId(m);
Elliott Hughes972a47b2012-02-21 18:16:06 -08001822 location.dex_pc = m->IsNative() ? -1 : dex_pc;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001823
1824 // Note we use "NoReg" so we don't keep track of references that are
1825 // never actually sent to the debugger. 'this_id' is only used to
1826 // compare against registered events...
1827 JDWP::ObjectId this_id = static_cast<JDWP::ObjectId>(reinterpret_cast<uintptr_t>(this_object));
1828 if (gJdwpState->PostLocationEvent(&location, this_id, event_flags)) {
1829 // ...unless there's a registered event, in which case we
1830 // need to really track the class and 'this'.
1831 gRegistry->Add(c);
1832 gRegistry->Add(this_object);
1833 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001834}
1835
Ian Rogers0399dde2012-06-06 17:09:28 -07001836void Dbg::PostException(JDWP::FrameId throwFrameId, Method* throwMethod, uint32_t throwDexPc,
1837 Method* catchMethod, uint32_t catchDexPc, Throwable* exception) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07001838 if (!IsDebuggerActive()) {
Ian Rogers0ad5bb82011-12-07 10:16:32 -08001839 return;
1840 }
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001841
Elliott Hughesd07986f2011-12-06 18:27:45 -08001842 JDWP::JdwpLocation throw_location;
Ian Rogers0399dde2012-06-06 17:09:28 -07001843 SetLocation(throw_location, throwMethod, throwDexPc);
Elliott Hughesd07986f2011-12-06 18:27:45 -08001844 JDWP::JdwpLocation catch_location;
Ian Rogers0399dde2012-06-06 17:09:28 -07001845 SetLocation(catch_location, catchMethod, catchDexPc);
Elliott Hughesd07986f2011-12-06 18:27:45 -08001846
1847 // We need 'this' for InstanceOnly filters.
1848 JDWP::ObjectId this_id;
Ian Rogers0399dde2012-06-06 17:09:28 -07001849 GetThisObject(throwFrameId, &this_id);
Elliott Hughesd07986f2011-12-06 18:27:45 -08001850
1851 /*
1852 * Hand the event to the JDWP exception handler. Note we're using the
1853 * "NoReg" objectID on the exception, which is not strictly correct --
1854 * the exception object WILL be passed up to the debugger if the
1855 * debugger is interested in the event. We do this because the current
1856 * implementation of the debugger object registry never throws anything
1857 * away, and some people were experiencing a fatal build up of exception
1858 * objects when dealing with certain libraries.
1859 */
1860 JDWP::ObjectId exception_id = static_cast<JDWP::ObjectId>(reinterpret_cast<uintptr_t>(exception));
1861 JDWP::RefTypeId exception_class_id = gRegistry->Add(exception->GetClass());
1862
1863 gJdwpState->PostException(&throw_location, exception_id, exception_class_id, &catch_location, this_id);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001864}
1865
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001866void Dbg::PostClassPrepare(Class* c) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07001867 if (!IsDebuggerActive()) {
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001868 return;
1869 }
1870
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001871 // OLD-TODO - we currently always send both "verified" and "prepared" since
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001872 // debuggers seem to like that. There might be some advantage to honesty,
1873 // since the class may not yet be verified.
1874 int state = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
1875 JDWP::JdwpTypeTag tag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
1876 gJdwpState->PostClassPrepare(tag, gRegistry->Add(c), ClassHelper(c).GetDescriptor(), state);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001877}
1878
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001879void Dbg::UpdateDebugger(int32_t dex_pc, Thread* self, Method** sp) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07001880 if (!IsDebuggerActive() || dex_pc == -2 /* fake method exit */) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001881 return;
1882 }
1883
Ian Rogers0399dde2012-06-06 17:09:28 -07001884 Method* m = self->GetCurrentMethod();
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001885
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001886 if (dex_pc == -1) {
Elliott Hughes2aa2e392012-02-17 17:15:43 -08001887 // We use a pc of -1 to represent method entry, since we might branch back to pc 0 later.
1888 // This means that for this special notification, there can't be anything else interesting
1889 // going on, so we're done already.
Ian Rogers0399dde2012-06-06 17:09:28 -07001890 Dbg::PostLocationEvent(m, 0, GetThis(sp), kMethodEntry);
Elliott Hughes2aa2e392012-02-17 17:15:43 -08001891 return;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001892 }
1893
Elliott Hughes2aa2e392012-02-17 17:15:43 -08001894 int event_flags = 0;
1895
Elliott Hughes86964332012-02-15 19:37:42 -08001896 if (IsBreakpoint(m, dex_pc)) {
1897 event_flags |= kBreakpoint;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001898 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001899
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001900 // If the debugger is single-stepping one of our threads, check to
1901 // see if we're that thread and we've reached a step point.
Elliott Hughesf8349362012-06-18 15:00:06 -07001902 MutexLock mu(gBreakpointsLock);
Elliott Hughes86964332012-02-15 19:37:42 -08001903 if (gSingleStepControl.is_active && gSingleStepControl.thread == self) {
1904 CHECK(!m->IsNative());
1905 if (gSingleStepControl.step_depth == JDWP::SD_INTO) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001906 // Step into method calls. We break when the line number
1907 // or method pointer changes. If we're in SS_MIN mode, we
1908 // always stop.
Elliott Hughes86964332012-02-15 19:37:42 -08001909 if (gSingleStepControl.method != m) {
1910 event_flags |= kSingleStep;
1911 VLOG(jdwp) << "SS new method";
1912 } else if (gSingleStepControl.step_size == JDWP::SS_MIN) {
1913 event_flags |= kSingleStep;
1914 VLOG(jdwp) << "SS new instruction";
Elliott Hughes2435a572012-02-17 16:07:41 -08001915 } else if (gSingleStepControl.dex_pcs.find(dex_pc) == gSingleStepControl.dex_pcs.end()) {
1916 event_flags |= kSingleStep;
1917 VLOG(jdwp) << "SS new line";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001918 }
Elliott Hughes86964332012-02-15 19:37:42 -08001919 } else if (gSingleStepControl.step_depth == JDWP::SD_OVER) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001920 // Step over method calls. We break when the line number is
1921 // different and the frame depth is <= the original frame
1922 // depth. (We can't just compare on the method, because we
1923 // might get unrolled past it by an exception, and it's tricky
1924 // to identify recursion.)
Elliott Hughes86964332012-02-15 19:37:42 -08001925
1926 // TODO: can we just use the value of 'sp'?
1927 int stack_depth = GetStackDepth(self);
1928
1929 if (stack_depth < gSingleStepControl.stack_depth) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001930 // popped up one or more frames, always trigger
Elliott Hughes86964332012-02-15 19:37:42 -08001931 event_flags |= kSingleStep;
1932 VLOG(jdwp) << "SS method pop";
1933 } else if (stack_depth == gSingleStepControl.stack_depth) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001934 // same depth, see if we moved
Elliott Hughes86964332012-02-15 19:37:42 -08001935 if (gSingleStepControl.step_size == JDWP::SS_MIN) {
1936 event_flags |= kSingleStep;
1937 VLOG(jdwp) << "SS new instruction";
Elliott Hughes2435a572012-02-17 16:07:41 -08001938 } else if (gSingleStepControl.dex_pcs.find(dex_pc) == gSingleStepControl.dex_pcs.end()) {
1939 event_flags |= kSingleStep;
1940 VLOG(jdwp) << "SS new line";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001941 }
1942 }
1943 } else {
Elliott Hughes86964332012-02-15 19:37:42 -08001944 CHECK_EQ(gSingleStepControl.step_depth, JDWP::SD_OUT);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001945 // Return from the current method. We break when the frame
1946 // depth pops up.
1947
1948 // This differs from the "method exit" break in that it stops
1949 // with the PC at the next instruction in the returned-to
1950 // function, rather than the end of the returning function.
Elliott Hughes86964332012-02-15 19:37:42 -08001951
1952 // TODO: can we just use the value of 'sp'?
1953 int stack_depth = GetStackDepth(self);
1954 if (stack_depth < gSingleStepControl.stack_depth) {
1955 event_flags |= kSingleStep;
1956 VLOG(jdwp) << "SS method pop";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001957 }
1958 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001959 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001960
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001961 // Check to see if this is a "return" instruction. JDWP says we should
1962 // send the event *after* the code has been executed, but it also says
1963 // the location we provide is the last instruction. Since the "return"
1964 // instruction has no interesting side effects, we should be safe.
1965 // (We can't just move this down to the returnFromMethod label because
1966 // we potentially need to combine it with other events.)
1967 // We're also not supposed to generate a method exit event if the method
1968 // terminates "with a thrown exception".
Elliott Hughes86964332012-02-15 19:37:42 -08001969 if (dex_pc >= 0) {
1970 const DexFile::CodeItem* code_item = MethodHelper(m).GetCodeItem();
1971 CHECK(code_item != NULL);
1972 CHECK_LT(dex_pc, static_cast<int32_t>(code_item->insns_size_in_code_units_));
1973 if (Instruction::At(&code_item->insns_[dex_pc])->IsReturn()) {
1974 event_flags |= kMethodExit;
1975 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001976 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001977
1978 // If there's something interesting going on, see if it matches one
1979 // of the debugger filters.
1980 if (event_flags != 0) {
Ian Rogers0399dde2012-06-06 17:09:28 -07001981 Dbg::PostLocationEvent(m, dex_pc, GetThis(sp), event_flags);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001982 }
1983}
1984
Elliott Hughes86964332012-02-15 19:37:42 -08001985void Dbg::WatchLocation(const JDWP::JdwpLocation* location) {
1986 MutexLock mu(gBreakpointsLock);
Elliott Hughes74847412012-06-20 18:10:21 -07001987 Method* m = FromMethodId(location->method_id);
Elliott Hughes972a47b2012-02-21 18:16:06 -08001988 gBreakpoints.push_back(Breakpoint(m, location->dex_pc));
Elliott Hughes86964332012-02-15 19:37:42 -08001989 VLOG(jdwp) << "Set breakpoint #" << (gBreakpoints.size() - 1) << ": " << gBreakpoints[gBreakpoints.size() - 1];
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001990}
1991
Elliott Hughes86964332012-02-15 19:37:42 -08001992void Dbg::UnwatchLocation(const JDWP::JdwpLocation* location) {
1993 MutexLock mu(gBreakpointsLock);
Elliott Hughes74847412012-06-20 18:10:21 -07001994 Method* m = FromMethodId(location->method_id);
Elliott Hughes86964332012-02-15 19:37:42 -08001995 for (size_t i = 0; i < gBreakpoints.size(); ++i) {
Elliott Hughes972a47b2012-02-21 18:16:06 -08001996 if (gBreakpoints[i].method == m && gBreakpoints[i].dex_pc == location->dex_pc) {
Elliott Hughes86964332012-02-15 19:37:42 -08001997 VLOG(jdwp) << "Removed breakpoint #" << i << ": " << gBreakpoints[i];
1998 gBreakpoints.erase(gBreakpoints.begin() + i);
1999 return;
2000 }
2001 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002002}
2003
Elliott Hughes2435a572012-02-17 16:07:41 -08002004JDWP::JdwpError Dbg::ConfigureStep(JDWP::ObjectId threadId, JDWP::JdwpStepSize step_size, JDWP::JdwpStepDepth step_depth) {
Elliott Hughes86964332012-02-15 19:37:42 -08002005 Thread* thread = DecodeThread(threadId);
Elliott Hughes2435a572012-02-17 16:07:41 -08002006 if (thread == NULL) {
2007 return JDWP::ERR_INVALID_THREAD;
2008 }
Elliott Hughes86964332012-02-15 19:37:42 -08002009
Elliott Hughesf8349362012-06-18 15:00:06 -07002010 MutexLock mu(gBreakpointsLock);
2011
Elliott Hughes86964332012-02-15 19:37:42 -08002012 // TODO: there's no theoretical reason why we couldn't support single-stepping
2013 // of multiple threads at once, but we never did so historically.
2014 if (gSingleStepControl.thread != NULL && thread != gSingleStepControl.thread) {
2015 LOG(WARNING) << "single-step already active for " << *gSingleStepControl.thread
2016 << "; switching to " << *thread;
2017 }
2018
Elliott Hughes2435a572012-02-17 16:07:41 -08002019 //
2020 // Work out what Method* we're in, the current line number, and how deep the stack currently
2021 // is for step-out.
2022 //
2023
Ian Rogers0399dde2012-06-06 17:09:28 -07002024 struct SingleStepStackVisitor : public StackVisitor {
2025 SingleStepStackVisitor(const ManagedStack* stack,
2026 const std::vector<TraceStackFrame>* trace_stack) :
2027 StackVisitor(stack, trace_stack) {
Elliott Hughesf8349362012-06-18 15:00:06 -07002028 MutexLock mu(gBreakpointsLock); // Keep GCC happy.
Elliott Hughes86964332012-02-15 19:37:42 -08002029 gSingleStepControl.method = NULL;
2030 gSingleStepControl.stack_depth = 0;
2031 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002032 bool VisitFrame() {
Elliott Hughesf8349362012-06-18 15:00:06 -07002033 MutexLock mu(gBreakpointsLock); // Keep GCC happy.
Ian Rogers0399dde2012-06-06 17:09:28 -07002034 const Method* m = GetMethod();
2035 if (!m->IsRuntimeMethod()) {
Elliott Hughes86964332012-02-15 19:37:42 -08002036 ++gSingleStepControl.stack_depth;
2037 if (gSingleStepControl.method == NULL) {
Elliott Hughes2435a572012-02-17 16:07:41 -08002038 const DexCache* dex_cache = m->GetDeclaringClass()->GetDexCache();
2039 gSingleStepControl.method = m;
2040 gSingleStepControl.line_number = -1;
2041 if (dex_cache != NULL) {
2042 const DexFile& dex_file = Runtime::Current()->GetClassLinker()->FindDexFile(dex_cache);
Ian Rogers0399dde2012-06-06 17:09:28 -07002043 gSingleStepControl.line_number = dex_file.GetLineNumFromPC(m, GetDexPc());
Elliott Hughes2435a572012-02-17 16:07:41 -08002044 }
Elliott Hughes86964332012-02-15 19:37:42 -08002045 }
2046 }
Elliott Hughes530fa002012-03-12 11:44:49 -07002047 return true;
Elliott Hughes86964332012-02-15 19:37:42 -08002048 }
2049 };
Ian Rogers0399dde2012-06-06 17:09:28 -07002050 SingleStepStackVisitor visitor(thread->GetManagedStack(), thread->GetTraceStack());
2051 visitor.WalkStack();
Elliott Hughes86964332012-02-15 19:37:42 -08002052
Elliott Hughes2435a572012-02-17 16:07:41 -08002053 //
2054 // Find the dex_pc values that correspond to the current line, for line-based single-stepping.
2055 //
2056
2057 struct DebugCallbackContext {
2058 DebugCallbackContext() {
2059 last_pc_valid = false;
2060 last_pc = 0;
Elliott Hughes2435a572012-02-17 16:07:41 -08002061 }
2062
2063 static bool Callback(void* raw_context, uint32_t address, uint32_t line_number) {
Elliott Hughesf8349362012-06-18 15:00:06 -07002064 MutexLock mu(gBreakpointsLock); // Keep GCC happy.
Elliott Hughes2435a572012-02-17 16:07:41 -08002065 DebugCallbackContext* context = reinterpret_cast<DebugCallbackContext*>(raw_context);
2066 if (static_cast<int32_t>(line_number) == gSingleStepControl.line_number) {
2067 if (!context->last_pc_valid) {
2068 // Everything from this address until the next line change is ours.
2069 context->last_pc = address;
2070 context->last_pc_valid = true;
2071 }
2072 // Otherwise, if we're already in a valid range for this line,
2073 // just keep going (shouldn't really happen)...
2074 } else if (context->last_pc_valid) { // and the line number is new
2075 // Add everything from the last entry up until here to the set
2076 for (uint32_t dex_pc = context->last_pc; dex_pc < address; ++dex_pc) {
2077 gSingleStepControl.dex_pcs.insert(dex_pc);
2078 }
2079 context->last_pc_valid = false;
2080 }
2081 return false; // There may be multiple entries for any given line.
2082 }
2083
2084 ~DebugCallbackContext() {
Elliott Hughesf8349362012-06-18 15:00:06 -07002085 MutexLock mu(gBreakpointsLock); // Keep GCC happy.
Elliott Hughes2435a572012-02-17 16:07:41 -08002086 // If the line number was the last in the position table...
2087 if (last_pc_valid) {
2088 size_t end = MethodHelper(gSingleStepControl.method).GetCodeItem()->insns_size_in_code_units_;
2089 for (uint32_t dex_pc = last_pc; dex_pc < end; ++dex_pc) {
2090 gSingleStepControl.dex_pcs.insert(dex_pc);
2091 }
2092 }
2093 }
2094
2095 bool last_pc_valid;
2096 uint32_t last_pc;
2097 };
Elliott Hughes3e2e1a22012-02-21 11:33:41 -08002098 gSingleStepControl.dex_pcs.clear();
Elliott Hughes2435a572012-02-17 16:07:41 -08002099 const Method* m = gSingleStepControl.method;
Elliott Hughes3e2e1a22012-02-21 11:33:41 -08002100 if (m->IsNative()) {
2101 gSingleStepControl.line_number = -1;
2102 } else {
2103 DebugCallbackContext context;
2104 MethodHelper mh(m);
2105 mh.GetDexFile().DecodeDebugInfo(mh.GetCodeItem(), m->IsStatic(), m->GetDexMethodIndex(),
2106 DebugCallbackContext::Callback, NULL, &context);
2107 }
Elliott Hughes2435a572012-02-17 16:07:41 -08002108
2109 //
2110 // Everything else...
2111 //
2112
Elliott Hughes86964332012-02-15 19:37:42 -08002113 gSingleStepControl.thread = thread;
2114 gSingleStepControl.step_size = step_size;
2115 gSingleStepControl.step_depth = step_depth;
2116 gSingleStepControl.is_active = true;
2117
Elliott Hughes2435a572012-02-17 16:07:41 -08002118 if (VLOG_IS_ON(jdwp)) {
2119 VLOG(jdwp) << "Single-step thread: " << *gSingleStepControl.thread;
2120 VLOG(jdwp) << "Single-step step size: " << gSingleStepControl.step_size;
2121 VLOG(jdwp) << "Single-step step depth: " << gSingleStepControl.step_depth;
2122 VLOG(jdwp) << "Single-step current method: " << PrettyMethod(gSingleStepControl.method);
2123 VLOG(jdwp) << "Single-step current line: " << gSingleStepControl.line_number;
2124 VLOG(jdwp) << "Single-step current stack depth: " << gSingleStepControl.stack_depth;
2125 VLOG(jdwp) << "Single-step dex_pc values:";
2126 for (std::set<uint32_t>::iterator it = gSingleStepControl.dex_pcs.begin() ; it != gSingleStepControl.dex_pcs.end(); ++it) {
Elliott Hughes229feb72012-02-23 13:33:29 -08002127 VLOG(jdwp) << StringPrintf(" %#x", *it);
Elliott Hughes2435a572012-02-17 16:07:41 -08002128 }
2129 }
2130
2131 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002132}
2133
Elliott Hughes1bac54f2012-03-16 12:48:31 -07002134void Dbg::UnconfigureStep(JDWP::ObjectId /*threadId*/) {
Elliott Hughesf8349362012-06-18 15:00:06 -07002135 MutexLock mu(gBreakpointsLock);
2136
Elliott Hughes86964332012-02-15 19:37:42 -08002137 gSingleStepControl.is_active = false;
2138 gSingleStepControl.thread = NULL;
Elliott Hughes2435a572012-02-17 16:07:41 -08002139 gSingleStepControl.dex_pcs.clear();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002140}
2141
Elliott Hughes45651fd2012-02-21 15:48:20 -08002142static char JdwpTagToShortyChar(JDWP::JdwpTag tag) {
2143 switch (tag) {
2144 default:
2145 LOG(FATAL) << "unknown JDWP tag: " << PrintableChar(tag);
2146
2147 // Primitives.
2148 case JDWP::JT_BYTE: return 'B';
2149 case JDWP::JT_CHAR: return 'C';
2150 case JDWP::JT_FLOAT: return 'F';
2151 case JDWP::JT_DOUBLE: return 'D';
2152 case JDWP::JT_INT: return 'I';
2153 case JDWP::JT_LONG: return 'J';
2154 case JDWP::JT_SHORT: return 'S';
2155 case JDWP::JT_VOID: return 'V';
2156 case JDWP::JT_BOOLEAN: return 'Z';
2157
2158 // Reference types.
2159 case JDWP::JT_ARRAY:
2160 case JDWP::JT_OBJECT:
2161 case JDWP::JT_STRING:
2162 case JDWP::JT_THREAD:
2163 case JDWP::JT_THREAD_GROUP:
2164 case JDWP::JT_CLASS_LOADER:
2165 case JDWP::JT_CLASS_OBJECT:
2166 return 'L';
2167 }
2168}
2169
2170JDWP::JdwpError Dbg::InvokeMethod(JDWP::ObjectId threadId, JDWP::ObjectId objectId, JDWP::RefTypeId classId, JDWP::MethodId methodId, uint32_t arg_count, uint64_t* arg_values, JDWP::JdwpTag* arg_types, uint32_t options, JDWP::JdwpTag* pResultTag, uint64_t* pResultValue, JDWP::ObjectId* pExceptionId) {
Elliott Hughesd07986f2011-12-06 18:27:45 -08002171 ThreadList* thread_list = Runtime::Current()->GetThreadList();
2172
2173 Thread* targetThread = NULL;
2174 DebugInvokeReq* req = NULL;
2175 {
2176 ScopedThreadListLock thread_list_lock;
2177 targetThread = DecodeThread(threadId);
2178 if (targetThread == NULL) {
2179 LOG(ERROR) << "InvokeMethod request for non-existent thread " << threadId;
2180 return JDWP::ERR_INVALID_THREAD;
2181 }
2182 req = targetThread->GetInvokeReq();
2183 if (!req->ready) {
2184 LOG(ERROR) << "InvokeMethod request for thread not stopped by event: " << *targetThread;
2185 return JDWP::ERR_INVALID_THREAD;
2186 }
2187
2188 /*
2189 * We currently have a bug where we don't successfully resume the
2190 * target thread if the suspend count is too deep. We're expected to
2191 * require one "resume" for each "suspend", but when asked to execute
2192 * a method we have to resume fully and then re-suspend it back to the
2193 * same level. (The easiest way to cause this is to type "suspend"
2194 * multiple times in jdb.)
2195 *
2196 * It's unclear what this means when the event specifies "resume all"
2197 * and some threads are suspended more deeply than others. This is
2198 * a rare problem, so for now we just prevent it from hanging forever
2199 * by rejecting the method invocation request. Without this, we will
2200 * be stuck waiting on a suspended thread.
2201 */
2202 int suspend_count = targetThread->GetSuspendCount();
2203 if (suspend_count > 1) {
2204 LOG(ERROR) << *targetThread << " suspend count too deep for method invocation: " << suspend_count;
2205 return JDWP::ERR_THREAD_SUSPENDED; // Probably not expected here.
2206 }
2207
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002208 JDWP::JdwpError status;
Elliott Hughes45651fd2012-02-21 15:48:20 -08002209 Object* receiver = gRegistry->Get<Object*>(objectId);
2210 if (receiver == kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002211 return JDWP::ERR_INVALID_OBJECT;
2212 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002213
2214 Object* thread = gRegistry->Get<Object*>(threadId);
2215 if (thread == kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002216 return JDWP::ERR_INVALID_OBJECT;
2217 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002218 // TODO: check that 'thread' is actually a java.lang.Thread!
2219
2220 Class* c = DecodeClass(classId, status);
2221 if (c == NULL) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002222 return status;
2223 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002224
2225 Method* m = FromMethodId(methodId);
2226 if (m->IsStatic() != (receiver == NULL)) {
2227 return JDWP::ERR_INVALID_METHODID;
2228 }
2229 if (m->IsStatic()) {
2230 if (m->GetDeclaringClass() != c) {
2231 return JDWP::ERR_INVALID_METHODID;
2232 }
2233 } else {
2234 if (!m->GetDeclaringClass()->IsAssignableFrom(c)) {
2235 return JDWP::ERR_INVALID_METHODID;
2236 }
2237 }
2238
2239 // Check the argument list matches the method.
2240 MethodHelper mh(m);
2241 if (mh.GetShortyLength() - 1 != arg_count) {
2242 return JDWP::ERR_ILLEGAL_ARGUMENT;
2243 }
2244 const char* shorty = mh.GetShorty();
2245 for (size_t i = 0; i < arg_count; ++i) {
2246 if (shorty[i + 1] != JdwpTagToShortyChar(arg_types[i])) {
2247 return JDWP::ERR_ILLEGAL_ARGUMENT;
2248 }
2249 }
2250
2251 req->receiver_ = receiver;
2252 req->thread_ = thread;
2253 req->class_ = c;
2254 req->method_ = m;
2255 req->arg_count_ = arg_count;
2256 req->arg_values_ = arg_values;
Elliott Hughesd07986f2011-12-06 18:27:45 -08002257 req->options_ = options;
2258 req->invoke_needed_ = true;
2259 }
2260
2261 // The fact that we've released the thread list lock is a bit risky --- if the thread goes
2262 // away we're sitting high and dry -- but we must release this before the ResumeAllThreads
2263 // call, and it's unwise to hold it during WaitForSuspend.
2264
2265 {
2266 /*
2267 * We change our (JDWP thread) status, which should be THREAD_RUNNING,
Elliott Hughes81ff3182012-03-23 20:35:56 -07002268 * so we can suspend for a GC if the invoke request causes us to
Elliott Hughesd07986f2011-12-06 18:27:45 -08002269 * run out of memory. It's also a good idea to change it before locking
2270 * the invokeReq mutex, although that should never be held for long.
2271 */
Elliott Hughes34e06962012-04-09 13:55:55 -07002272 ScopedThreadStateChange tsc(Thread::Current(), kVmWait);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002273
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002274 VLOG(jdwp) << " Transferring control to event thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002275 {
2276 MutexLock mu(req->lock_);
2277
2278 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002279 VLOG(jdwp) << " Resuming all threads";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002280 thread_list->ResumeAll(true);
2281 } else {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002282 VLOG(jdwp) << " Resuming event thread only";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002283 thread_list->Resume(targetThread, true);
2284 }
2285
2286 // Wait for the request to finish executing.
2287 while (req->invoke_needed_) {
2288 req->cond_.Wait(req->lock_);
2289 }
2290 }
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002291 VLOG(jdwp) << " Control has returned from event thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002292
2293 /* wait for thread to re-suspend itself */
2294 targetThread->WaitUntilSuspended();
2295 //dvmWaitForSuspend(targetThread);
2296 }
2297
2298 /*
2299 * Suspend the threads. We waited for the target thread to suspend
2300 * itself, so all we need to do is suspend the others.
2301 *
2302 * The suspendAllThreads() call will double-suspend the event thread,
2303 * so we want to resume the target thread once to keep the books straight.
2304 */
2305 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002306 VLOG(jdwp) << " Suspending all threads";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002307 thread_list->SuspendAll(true);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002308 VLOG(jdwp) << " Resuming event thread to balance the count";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002309 thread_list->Resume(targetThread, true);
2310 }
2311
2312 // Copy the result.
2313 *pResultTag = req->result_tag;
2314 if (IsPrimitiveTag(req->result_tag)) {
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002315 *pResultValue = req->result_value.GetJ();
Elliott Hughesd07986f2011-12-06 18:27:45 -08002316 } else {
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002317 *pResultValue = gRegistry->Add(req->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002318 }
2319 *pExceptionId = req->exception;
2320 return req->error;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002321}
2322
2323void Dbg::ExecuteMethod(DebugInvokeReq* pReq) {
Elliott Hughesd07986f2011-12-06 18:27:45 -08002324 Thread* self = Thread::Current();
2325
Elliott Hughes81ff3182012-03-23 20:35:56 -07002326 // We can be called while an exception is pending. We need
Elliott Hughesd07986f2011-12-06 18:27:45 -08002327 // to preserve that across the method invocation.
2328 SirtRef<Throwable> old_exception(self->GetException());
2329 self->ClearException();
2330
Elliott Hughes34e06962012-04-09 13:55:55 -07002331 ScopedThreadStateChange tsc(self, kRunnable);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002332
2333 // Translate the method through the vtable, unless the debugger wants to suppress it.
2334 Method* m = pReq->method_;
2335 if ((pReq->options_ & JDWP::INVOKE_NONVIRTUAL) == 0 && pReq->receiver_ != NULL) {
Elliott Hughes45651fd2012-02-21 15:48:20 -08002336 Method* actual_method = pReq->class_->FindVirtualMethodForVirtualOrInterface(pReq->method_);
2337 if (actual_method != m) {
2338 VLOG(jdwp) << "ExecuteMethod translated " << PrettyMethod(m) << " to " << PrettyMethod(actual_method);
2339 m = actual_method;
2340 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08002341 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002342 VLOG(jdwp) << "ExecuteMethod " << PrettyMethod(m);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002343 CHECK(m != NULL);
2344
2345 CHECK_EQ(sizeof(jvalue), sizeof(uint64_t));
2346
Elliott Hughes45651fd2012-02-21 15:48:20 -08002347 LOG(INFO) << "self=" << self << " pReq->receiver_=" << pReq->receiver_ << " m=" << m << " #" << pReq->arg_count_ << " " << pReq->arg_values_;
2348 pReq->result_value = InvokeWithJValues(self, pReq->receiver_, m, reinterpret_cast<JValue*>(pReq->arg_values_));
Elliott Hughesd07986f2011-12-06 18:27:45 -08002349
2350 pReq->exception = gRegistry->Add(self->GetException());
2351 pReq->result_tag = BasicTagFromDescriptor(MethodHelper(m).GetShorty());
2352 if (pReq->exception != 0) {
2353 Object* exc = self->GetException();
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002354 VLOG(jdwp) << " JDWP invocation returning with exception=" << exc << " " << PrettyTypeOf(exc);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002355 self->ClearException();
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002356 pReq->result_value.SetJ(0);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002357 } else if (pReq->result_tag == JDWP::JT_OBJECT) {
2358 /* if no exception thrown, examine object result more closely */
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002359 JDWP::JdwpTag new_tag = TagFromObject(pReq->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002360 if (new_tag != pReq->result_tag) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002361 VLOG(jdwp) << " JDWP promoted result from " << pReq->result_tag << " to " << new_tag;
Elliott Hughesd07986f2011-12-06 18:27:45 -08002362 pReq->result_tag = new_tag;
2363 }
2364
2365 /*
2366 * Register the object. We don't actually need an ObjectId yet,
2367 * but we do need to be sure that the GC won't move or discard the
2368 * object when we switch out of RUNNING. The ObjectId conversion
2369 * will add the object to the "do not touch" list.
2370 *
2371 * We can't use the "tracked allocation" mechanism here because
2372 * the object is going to be handed off to a different thread.
2373 */
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002374 gRegistry->Add(pReq->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002375 }
2376
2377 if (old_exception.get() != NULL) {
2378 self->SetException(old_exception.get());
2379 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002380}
2381
Elliott Hughesd07986f2011-12-06 18:27:45 -08002382/*
2383 * Register an object ID that might not have been registered previously.
2384 *
2385 * Normally this wouldn't happen -- the conversion to an ObjectId would
2386 * have added the object to the registry -- but in some cases (e.g.
2387 * throwing exceptions) we really want to do the registration late.
2388 */
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002389void Dbg::RegisterObjectId(JDWP::ObjectId id) {
Elliott Hughesd07986f2011-12-06 18:27:45 -08002390 gRegistry->Add(reinterpret_cast<Object*>(id));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002391}
2392
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002393/*
2394 * "buf" contains a full JDWP packet, possibly with multiple chunks. We
2395 * need to process each, accumulate the replies, and ship the whole thing
2396 * back.
2397 *
2398 * Returns "true" if we have a reply. The reply buffer is newly allocated,
2399 * and includes the chunk type/length, followed by the data.
2400 *
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08002401 * OLD-TODO: we currently assume that the request and reply include a single
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002402 * chunk. If this becomes inconvenient we will need to adapt.
2403 */
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002404bool Dbg::DdmHandlePacket(const uint8_t* buf, int dataLen, uint8_t** pReplyBuf, int* pReplyLen) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002405 CHECK_GE(dataLen, 0);
2406
2407 Thread* self = Thread::Current();
2408 JNIEnv* env = self->GetJniEnv();
2409
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002410 // Create a byte[] corresponding to 'buf'.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002411 ScopedLocalRef<jbyteArray> dataArray(env, env->NewByteArray(dataLen));
2412 if (dataArray.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002413 LOG(WARNING) << "byte[] allocation failed: " << dataLen;
2414 env->ExceptionClear();
2415 return false;
2416 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002417 env->SetByteArrayRegion(dataArray.get(), 0, dataLen, reinterpret_cast<const jbyte*>(buf));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002418
2419 const int kChunkHdrLen = 8;
2420
2421 // Run through and find all chunks. [Currently just find the first.]
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002422 ScopedByteArrayRO contents(env, dataArray.get());
Elliott Hughesf7c3b662011-10-27 12:04:56 -07002423 jint type = JDWP::Get4BE(reinterpret_cast<const uint8_t*>(&contents[0]));
2424 jint length = JDWP::Get4BE(reinterpret_cast<const uint8_t*>(&contents[4]));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002425 jint offset = kChunkHdrLen;
2426 if (offset + length > dataLen) {
2427 LOG(WARNING) << StringPrintf("bad chunk found (len=%u pktLen=%d)", length, dataLen);
2428 return false;
2429 }
2430
2431 // Call "private static Chunk dispatch(int type, byte[] data, int offset, int length)".
Elliott Hugheseac76672012-05-24 21:56:51 -07002432 ScopedLocalRef<jobject> chunk(env, env->CallStaticObjectMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
2433 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_dispatch,
2434 type, dataArray.get(), offset, length));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002435 if (env->ExceptionCheck()) {
2436 LOG(INFO) << StringPrintf("Exception thrown by dispatcher for 0x%08x", type);
2437 env->ExceptionDescribe();
2438 env->ExceptionClear();
2439 return false;
2440 }
2441
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002442 if (chunk.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002443 return false;
2444 }
2445
2446 /*
2447 * Pull the pieces out of the chunk. We copy the results into a
2448 * newly-allocated buffer that the caller can free. We don't want to
2449 * continue using the Chunk object because nothing has a reference to it.
2450 *
2451 * We could avoid this by returning type/data/offset/length and having
2452 * the caller be aware of the object lifetime issues, but that
Elliott Hughes81ff3182012-03-23 20:35:56 -07002453 * integrates the JDWP code more tightly into the rest of the runtime, and doesn't work
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002454 * if we have responses for multiple chunks.
2455 *
2456 * So we're pretty much stuck with copying data around multiple times.
2457 */
Elliott Hugheseac76672012-05-24 21:56:51 -07002458 ScopedLocalRef<jbyteArray> replyData(env, reinterpret_cast<jbyteArray>(env->GetObjectField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_data)));
2459 length = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_length);
2460 offset = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_offset);
2461 type = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_type);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002462
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002463 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 -07002464 if (length == 0 || replyData.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002465 return false;
2466 }
2467
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002468 jsize replyLength = env->GetArrayLength(replyData.get());
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002469 if (offset + length > replyLength) {
2470 LOG(WARNING) << StringPrintf("chunk off=%d len=%d exceeds reply array len %d", offset, length, replyLength);
2471 return false;
2472 }
2473
2474 uint8_t* reply = new uint8_t[length + kChunkHdrLen];
2475 if (reply == NULL) {
2476 LOG(WARNING) << "malloc failed: " << (length + kChunkHdrLen);
2477 return false;
2478 }
Elliott Hughesf7c3b662011-10-27 12:04:56 -07002479 JDWP::Set4BE(reply + 0, type);
2480 JDWP::Set4BE(reply + 4, length);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002481 env->GetByteArrayRegion(replyData.get(), offset, length, reinterpret_cast<jbyte*>(reply + kChunkHdrLen));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002482
2483 *pReplyBuf = reply;
2484 *pReplyLen = length + kChunkHdrLen;
2485
Elliott Hughesba8eee12012-01-24 20:25:24 -08002486 VLOG(jdwp) << StringPrintf("dvmHandleDdm returning type=%.4s buf=%p len=%d", reinterpret_cast<char*>(reply), reply, length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002487 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002488}
2489
Elliott Hughesa2155262011-11-16 16:26:58 -08002490void Dbg::DdmBroadcast(bool connect) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002491 VLOG(jdwp) << "Broadcasting DDM " << (connect ? "connect" : "disconnect") << "...";
Elliott Hughes47fce012011-10-25 18:37:19 -07002492
2493 Thread* self = Thread::Current();
Elliott Hughes34e06962012-04-09 13:55:55 -07002494 if (self->GetState() != kRunnable) {
Elliott Hughes47fce012011-10-25 18:37:19 -07002495 LOG(ERROR) << "DDM broadcast in thread state " << self->GetState();
2496 /* try anyway? */
2497 }
2498
2499 JNIEnv* env = self->GetJniEnv();
Elliott Hughes47fce012011-10-25 18:37:19 -07002500 jint event = connect ? 1 /*DdmServer.CONNECTED*/ : 2 /*DdmServer.DISCONNECTED*/;
Elliott Hugheseac76672012-05-24 21:56:51 -07002501 env->CallStaticVoidMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
2502 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_broadcast,
2503 event);
Elliott Hughes47fce012011-10-25 18:37:19 -07002504 if (env->ExceptionCheck()) {
2505 LOG(ERROR) << "DdmServer.broadcast " << event << " failed";
2506 env->ExceptionDescribe();
2507 env->ExceptionClear();
2508 }
2509}
2510
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002511void Dbg::DdmConnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08002512 Dbg::DdmBroadcast(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002513}
2514
2515void Dbg::DdmDisconnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08002516 Dbg::DdmBroadcast(false);
Elliott Hughes47fce012011-10-25 18:37:19 -07002517 gDdmThreadNotification = false;
2518}
2519
2520/*
Elliott Hughes82188472011-11-07 18:11:48 -08002521 * Send a notification when a thread starts, stops, or changes its name.
Elliott Hughes47fce012011-10-25 18:37:19 -07002522 *
2523 * Because we broadcast the full set of threads when the notifications are
2524 * first enabled, it's possible for "thread" to be actively executing.
2525 */
Elliott Hughes82188472011-11-07 18:11:48 -08002526void Dbg::DdmSendThreadNotification(Thread* t, uint32_t type) {
Elliott Hughes47fce012011-10-25 18:37:19 -07002527 if (!gDdmThreadNotification) {
2528 return;
2529 }
2530
Elliott Hughes82188472011-11-07 18:11:48 -08002531 if (type == CHUNK_TYPE("THDE")) {
Elliott Hughes47fce012011-10-25 18:37:19 -07002532 uint8_t buf[4];
Elliott Hughesf7c3b662011-10-27 12:04:56 -07002533 JDWP::Set4BE(&buf[0], t->GetThinLockId());
Elliott Hughes47fce012011-10-25 18:37:19 -07002534 Dbg::DdmSendChunk(CHUNK_TYPE("THDE"), 4, buf);
Elliott Hughes82188472011-11-07 18:11:48 -08002535 } else {
2536 CHECK(type == CHUNK_TYPE("THCR") || type == CHUNK_TYPE("THNM")) << type;
Elliott Hughes899e7892012-01-24 14:57:32 -08002537 SirtRef<String> name(t->GetThreadName());
Elliott Hughes82188472011-11-07 18:11:48 -08002538 size_t char_count = (name.get() != NULL) ? name->GetLength() : 0;
2539 const jchar* chars = name->GetCharArray()->GetData();
2540
Elliott Hughes21f32d72011-11-09 17:44:13 -08002541 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08002542 JDWP::Append4BE(bytes, t->GetThinLockId());
2543 JDWP::AppendUtf16BE(bytes, chars, char_count);
Elliott Hughes21f32d72011-11-09 17:44:13 -08002544 CHECK_EQ(bytes.size(), char_count*2 + sizeof(uint32_t)*2);
2545 Dbg::DdmSendChunk(type, bytes);
Elliott Hughes47fce012011-10-25 18:37:19 -07002546 }
2547}
2548
Elliott Hughesa2155262011-11-16 16:26:58 -08002549static void DdmSendThreadStartCallback(Thread* t, void*) {
Elliott Hughes82188472011-11-07 18:11:48 -08002550 Dbg::DdmSendThreadNotification(t, CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07002551}
2552
2553void Dbg::DdmSetThreadNotification(bool enable) {
2554 // We lock the thread list to avoid sending duplicate events or missing
2555 // a thread change. We should be okay holding this lock while sending
2556 // the messages out. (We have to hold it while accessing a live thread.)
Elliott Hughesbbd9d832011-11-07 14:40:00 -08002557 ScopedThreadListLock thread_list_lock;
Elliott Hughes47fce012011-10-25 18:37:19 -07002558
2559 gDdmThreadNotification = enable;
2560 if (enable) {
Elliott Hughesbfe487b2011-10-26 15:48:55 -07002561 Runtime::Current()->GetThreadList()->ForEach(DdmSendThreadStartCallback, NULL);
Elliott Hughes47fce012011-10-25 18:37:19 -07002562 }
2563}
2564
Elliott Hughesa2155262011-11-16 16:26:58 -08002565void Dbg::PostThreadStartOrStop(Thread* t, uint32_t type) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002566 if (IsDebuggerActive()) {
Elliott Hughes47fce012011-10-25 18:37:19 -07002567 JDWP::ObjectId id = gRegistry->Add(t->GetPeer());
Elliott Hughes82188472011-11-07 18:11:48 -08002568 gJdwpState->PostThreadChange(id, type == CHUNK_TYPE("THCR"));
Elliott Hughesc0f09332012-03-26 13:27:06 -07002569 // If this thread's just joined the party while we're already debugging, make sure it knows
2570 // to give us updates when it's running.
2571 t->SetDebuggerUpdatesEnabled(true);
Elliott Hughes47fce012011-10-25 18:37:19 -07002572 }
Elliott Hughes82188472011-11-07 18:11:48 -08002573 Dbg::DdmSendThreadNotification(t, type);
Elliott Hughes47fce012011-10-25 18:37:19 -07002574}
2575
2576void Dbg::PostThreadStart(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08002577 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07002578}
2579
2580void Dbg::PostThreadDeath(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08002581 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THDE"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002582}
2583
Elliott Hughes82188472011-11-07 18:11:48 -08002584void Dbg::DdmSendChunk(uint32_t type, size_t byte_count, const uint8_t* buf) {
Elliott Hughes3bb81562011-10-21 18:52:59 -07002585 CHECK(buf != NULL);
2586 iovec vec[1];
2587 vec[0].iov_base = reinterpret_cast<void*>(const_cast<uint8_t*>(buf));
2588 vec[0].iov_len = byte_count;
2589 Dbg::DdmSendChunkV(type, vec, 1);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002590}
2591
Elliott Hughes21f32d72011-11-09 17:44:13 -08002592void Dbg::DdmSendChunk(uint32_t type, const std::vector<uint8_t>& bytes) {
2593 DdmSendChunk(type, bytes.size(), &bytes[0]);
2594}
2595
Elliott Hughescccd84f2011-12-05 16:51:54 -08002596void Dbg::DdmSendChunkV(uint32_t type, const struct iovec* iov, int iov_count) {
Elliott Hughes3bb81562011-10-21 18:52:59 -07002597 if (gJdwpState == NULL) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002598 VLOG(jdwp) << "Debugger thread not active, ignoring DDM send: " << type;
Elliott Hughes3bb81562011-10-21 18:52:59 -07002599 } else {
Elliott Hughescccd84f2011-12-05 16:51:54 -08002600 gJdwpState->DdmSendChunkV(type, iov, iov_count);
Elliott Hughes3bb81562011-10-21 18:52:59 -07002601 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002602}
2603
Elliott Hughes767a1472011-10-26 18:49:02 -07002604int Dbg::DdmHandleHpifChunk(HpifWhen when) {
2605 if (when == HPIF_WHEN_NOW) {
Elliott Hughes7162ad92011-10-27 14:08:42 -07002606 DdmSendHeapInfo(when);
Elliott Hughes767a1472011-10-26 18:49:02 -07002607 return true;
2608 }
2609
2610 if (when != HPIF_WHEN_NEVER && when != HPIF_WHEN_NEXT_GC && when != HPIF_WHEN_EVERY_GC) {
2611 LOG(ERROR) << "invalid HpifWhen value: " << static_cast<int>(when);
2612 return false;
2613 }
2614
2615 gDdmHpifWhen = when;
2616 return true;
2617}
2618
2619bool Dbg::DdmHandleHpsgNhsgChunk(Dbg::HpsgWhen when, Dbg::HpsgWhat what, bool native) {
2620 if (when != HPSG_WHEN_NEVER && when != HPSG_WHEN_EVERY_GC) {
2621 LOG(ERROR) << "invalid HpsgWhen value: " << static_cast<int>(when);
2622 return false;
2623 }
2624
2625 if (what != HPSG_WHAT_MERGED_OBJECTS && what != HPSG_WHAT_DISTINCT_OBJECTS) {
2626 LOG(ERROR) << "invalid HpsgWhat value: " << static_cast<int>(what);
2627 return false;
2628 }
2629
2630 if (native) {
2631 gDdmNhsgWhen = when;
2632 gDdmNhsgWhat = what;
2633 } else {
2634 gDdmHpsgWhen = when;
2635 gDdmHpsgWhat = what;
2636 }
2637 return true;
2638}
2639
Elliott Hughes7162ad92011-10-27 14:08:42 -07002640void Dbg::DdmSendHeapInfo(HpifWhen reason) {
2641 // If there's a one-shot 'when', reset it.
2642 if (reason == gDdmHpifWhen) {
2643 if (gDdmHpifWhen == HPIF_WHEN_NEXT_GC) {
2644 gDdmHpifWhen = HPIF_WHEN_NEVER;
2645 }
2646 }
2647
2648 /*
2649 * Chunk HPIF (client --> server)
2650 *
2651 * Heap Info. General information about the heap,
2652 * suitable for a summary display.
2653 *
2654 * [u4]: number of heaps
2655 *
2656 * For each heap:
2657 * [u4]: heap ID
2658 * [u8]: timestamp in ms since Unix epoch
2659 * [u1]: capture reason (same as 'when' value from server)
2660 * [u4]: max heap size in bytes (-Xmx)
2661 * [u4]: current heap size in bytes
2662 * [u4]: current number of bytes allocated
2663 * [u4]: current number of objects allocated
2664 */
2665 uint8_t heap_count = 1;
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08002666 Heap* heap = Runtime::Current()->GetHeap();
Elliott Hughes21f32d72011-11-09 17:44:13 -08002667 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08002668 JDWP::Append4BE(bytes, heap_count);
2669 JDWP::Append4BE(bytes, 1); // Heap id (bogus; we only have one heap).
2670 JDWP::Append8BE(bytes, MilliTime());
2671 JDWP::Append1BE(bytes, reason);
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08002672 JDWP::Append4BE(bytes, heap->GetMaxMemory()); // Max allowed heap size in bytes.
2673 JDWP::Append4BE(bytes, heap->GetTotalMemory()); // Current heap size in bytes.
2674 JDWP::Append4BE(bytes, heap->GetBytesAllocated());
2675 JDWP::Append4BE(bytes, heap->GetObjectsAllocated());
Elliott Hughes21f32d72011-11-09 17:44:13 -08002676 CHECK_EQ(bytes.size(), 4U + (heap_count * (4 + 8 + 1 + 4 + 4 + 4 + 4)));
2677 Dbg::DdmSendChunk(CHUNK_TYPE("HPIF"), bytes);
Elliott Hughes767a1472011-10-26 18:49:02 -07002678}
2679
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002680enum HpsgSolidity {
2681 SOLIDITY_FREE = 0,
2682 SOLIDITY_HARD = 1,
2683 SOLIDITY_SOFT = 2,
2684 SOLIDITY_WEAK = 3,
2685 SOLIDITY_PHANTOM = 4,
2686 SOLIDITY_FINALIZABLE = 5,
2687 SOLIDITY_SWEEP = 6,
2688};
2689
2690enum HpsgKind {
2691 KIND_OBJECT = 0,
2692 KIND_CLASS_OBJECT = 1,
2693 KIND_ARRAY_1 = 2,
2694 KIND_ARRAY_2 = 3,
2695 KIND_ARRAY_4 = 4,
2696 KIND_ARRAY_8 = 5,
2697 KIND_UNKNOWN = 6,
2698 KIND_NATIVE = 7,
2699};
2700
2701#define HPSG_PARTIAL (1<<7)
2702#define HPSG_STATE(solidity, kind) ((uint8_t)((((kind) & 0x7) << 3) | ((solidity) & 0x7)))
2703
Ian Rogers30fab402012-01-23 15:43:46 -08002704class HeapChunkContext {
2705 public:
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002706 // Maximum chunk size. Obtain this from the formula:
2707 // (((maximum_heap_size / ALLOCATION_UNIT_SIZE) + 255) / 256) * 2
2708 HeapChunkContext(bool merge, bool native)
Ian Rogers30fab402012-01-23 15:43:46 -08002709 : buf_(16384 - 16),
2710 type_(0),
2711 merge_(merge) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002712 Reset();
2713 if (native) {
Ian Rogers30fab402012-01-23 15:43:46 -08002714 type_ = CHUNK_TYPE("NHSG");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002715 } else {
Ian Rogers30fab402012-01-23 15:43:46 -08002716 type_ = merge ? CHUNK_TYPE("HPSG") : CHUNK_TYPE("HPSO");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002717 }
2718 }
2719
2720 ~HeapChunkContext() {
Ian Rogers30fab402012-01-23 15:43:46 -08002721 if (p_ > &buf_[0]) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002722 Flush();
2723 }
2724 }
2725
2726 void EnsureHeader(const void* chunk_ptr) {
Ian Rogers30fab402012-01-23 15:43:46 -08002727 if (!needHeader_) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002728 return;
2729 }
2730
2731 // Start a new HPSx chunk.
Ian Rogers30fab402012-01-23 15:43:46 -08002732 JDWP::Write4BE(&p_, 1); // Heap id (bogus; we only have one heap).
2733 JDWP::Write1BE(&p_, 8); // Size of allocation unit, in bytes.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002734
Ian Rogers30fab402012-01-23 15:43:46 -08002735 JDWP::Write4BE(&p_, reinterpret_cast<uintptr_t>(chunk_ptr)); // virtual address of segment start.
2736 JDWP::Write4BE(&p_, 0); // offset of this piece (relative to the virtual address).
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002737 // [u4]: length of piece, in allocation units
2738 // 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 -08002739 pieceLenField_ = p_;
2740 JDWP::Write4BE(&p_, 0x55555555);
2741 needHeader_ = false;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002742 }
2743
2744 void Flush() {
2745 // Patch the "length of piece" field.
Ian Rogers30fab402012-01-23 15:43:46 -08002746 CHECK_LE(&buf_[0], pieceLenField_);
2747 CHECK_LE(pieceLenField_, p_);
2748 JDWP::Set4BE(pieceLenField_, totalAllocationUnits_);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002749
Ian Rogers30fab402012-01-23 15:43:46 -08002750 Dbg::DdmSendChunk(type_, p_ - &buf_[0], &buf_[0]);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002751 Reset();
2752 }
2753
Ian Rogers30fab402012-01-23 15:43:46 -08002754 static void HeapChunkCallback(void* start, void* end, size_t used_bytes, void* arg) {
2755 reinterpret_cast<HeapChunkContext*>(arg)->HeapChunkCallback(start, end, used_bytes);
Elliott Hughesa2155262011-11-16 16:26:58 -08002756 }
2757
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002758 private:
Elliott Hughesa2155262011-11-16 16:26:58 -08002759 enum { ALLOCATION_UNIT_SIZE = 8 };
2760
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002761 void Reset() {
Ian Rogers30fab402012-01-23 15:43:46 -08002762 p_ = &buf_[0];
2763 totalAllocationUnits_ = 0;
2764 needHeader_ = true;
2765 pieceLenField_ = NULL;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002766 }
2767
Elliott Hughes1bac54f2012-03-16 12:48:31 -07002768 void HeapChunkCallback(void* start, void* /*end*/, size_t used_bytes) {
Ian Rogers30fab402012-01-23 15:43:46 -08002769 // Note: heap call backs cannot manipulate the heap upon which they are crawling, care is taken
2770 // in the following code not to allocate memory, by ensuring buf_ is of the correct size
2771
Elliott Hughes741c9fa2012-06-08 15:51:32 -07002772 void* user_ptr = used_bytes > 0 ? start : NULL;
2773 size_t chunk_len = mspace_usable_size(user_ptr);
Ian Rogers30fab402012-01-23 15:43:46 -08002774
Elliott Hughes741c9fa2012-06-08 15:51:32 -07002775 // Make sure there's enough room left in the buffer.
2776 // We need to use two bytes for every fractional 256 allocation units used by the chunk.
Elliott Hughesa2155262011-11-16 16:26:58 -08002777 {
2778 size_t needed = (((chunk_len/ALLOCATION_UNIT_SIZE + 255) / 256) * 2);
Ian Rogers30fab402012-01-23 15:43:46 -08002779 size_t bytesLeft = buf_.size() - (size_t)(p_ - &buf_[0]);
Elliott Hughesa2155262011-11-16 16:26:58 -08002780 if (bytesLeft < needed) {
2781 Flush();
2782 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002783
Ian Rogers30fab402012-01-23 15:43:46 -08002784 bytesLeft = buf_.size() - (size_t)(p_ - &buf_[0]);
Elliott Hughesa2155262011-11-16 16:26:58 -08002785 if (bytesLeft < needed) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08002786 LOG(WARNING) << "Chunk is too big to transmit (chunk_len=" << chunk_len << ", " << needed << " bytes)";
Elliott Hughesa2155262011-11-16 16:26:58 -08002787 return;
2788 }
2789 }
2790
2791 // OLD-TODO: notice when there's a gap and start a new heap, or at least a new range.
Elliott Hughes741c9fa2012-06-08 15:51:32 -07002792 EnsureHeader(start);
Elliott Hughesa2155262011-11-16 16:26:58 -08002793
2794 // Determine the type of this chunk.
2795 // OLD-TODO: if context.merge, see if this chunk is different from the last chunk.
2796 // If it's the same, we should combine them.
Ian Rogers30fab402012-01-23 15:43:46 -08002797 uint8_t state = ExamineObject(reinterpret_cast<const Object*>(user_ptr), (type_ == CHUNK_TYPE("NHSG")));
Elliott Hughesa2155262011-11-16 16:26:58 -08002798
2799 // Write out the chunk description.
2800 chunk_len /= ALLOCATION_UNIT_SIZE; // convert to allocation units
Ian Rogers30fab402012-01-23 15:43:46 -08002801 totalAllocationUnits_ += chunk_len;
Elliott Hughesa2155262011-11-16 16:26:58 -08002802 while (chunk_len > 256) {
Ian Rogers30fab402012-01-23 15:43:46 -08002803 *p_++ = state | HPSG_PARTIAL;
2804 *p_++ = 255; // length - 1
Elliott Hughesa2155262011-11-16 16:26:58 -08002805 chunk_len -= 256;
2806 }
Ian Rogers30fab402012-01-23 15:43:46 -08002807 *p_++ = state;
2808 *p_++ = chunk_len - 1;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002809 }
2810
Elliott Hughesa2155262011-11-16 16:26:58 -08002811 uint8_t ExamineObject(const Object* o, bool is_native_heap) {
2812 if (o == NULL) {
2813 return HPSG_STATE(SOLIDITY_FREE, 0);
2814 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002815
Elliott Hughesa2155262011-11-16 16:26:58 -08002816 // It's an allocated chunk. Figure out what it is.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002817
Elliott Hughesa2155262011-11-16 16:26:58 -08002818 // If we're looking at the native heap, we'll just return
2819 // (SOLIDITY_HARD, KIND_NATIVE) for all allocated chunks.
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08002820 if (is_native_heap || !Runtime::Current()->GetHeap()->IsLiveObjectLocked(o)) {
Elliott Hughesa2155262011-11-16 16:26:58 -08002821 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
2822 }
2823
2824 Class* c = o->GetClass();
2825 if (c == NULL) {
2826 // The object was probably just created but hasn't been initialized yet.
2827 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
2828 }
2829
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08002830 if (!Runtime::Current()->GetHeap()->IsHeapAddress(c)) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08002831 LOG(WARNING) << "Invalid class for managed heap object: " << o << " " << c;
Elliott Hughesa2155262011-11-16 16:26:58 -08002832 return HPSG_STATE(SOLIDITY_HARD, KIND_UNKNOWN);
2833 }
2834
2835 if (c->IsClassClass()) {
2836 return HPSG_STATE(SOLIDITY_HARD, KIND_CLASS_OBJECT);
2837 }
2838
2839 if (c->IsArrayClass()) {
2840 if (o->IsObjectArray()) {
2841 return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
2842 }
2843 switch (c->GetComponentSize()) {
2844 case 1: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_1);
2845 case 2: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_2);
2846 case 4: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
2847 case 8: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_8);
2848 }
2849 }
2850
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002851 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
2852 }
2853
Ian Rogers30fab402012-01-23 15:43:46 -08002854 std::vector<uint8_t> buf_;
2855 uint8_t* p_;
2856 uint8_t* pieceLenField_;
2857 size_t totalAllocationUnits_;
2858 uint32_t type_;
2859 bool merge_;
2860 bool needHeader_;
2861
Elliott Hughesa2155262011-11-16 16:26:58 -08002862 DISALLOW_COPY_AND_ASSIGN(HeapChunkContext);
2863};
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002864
2865void Dbg::DdmSendHeapSegments(bool native) {
2866 Dbg::HpsgWhen when;
2867 Dbg::HpsgWhat what;
2868 if (!native) {
2869 when = gDdmHpsgWhen;
2870 what = gDdmHpsgWhat;
2871 } else {
2872 when = gDdmNhsgWhen;
2873 what = gDdmNhsgWhat;
2874 }
2875 if (when == HPSG_WHEN_NEVER) {
2876 return;
2877 }
2878
2879 // Figure out what kind of chunks we'll be sending.
2880 CHECK(what == HPSG_WHAT_MERGED_OBJECTS || what == HPSG_WHAT_DISTINCT_OBJECTS) << static_cast<int>(what);
2881
2882 // First, send a heap start chunk.
2883 uint8_t heap_id[4];
2884 JDWP::Set4BE(&heap_id[0], 1); // Heap id (bogus; we only have one heap).
2885 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHST") : CHUNK_TYPE("HPST"), sizeof(heap_id), heap_id);
2886
2887 // Send a series of heap segment chunks.
Elliott Hughesa2155262011-11-16 16:26:58 -08002888 HeapChunkContext context((what == HPSG_WHAT_MERGED_OBJECTS), native);
2889 if (native) {
Ian Rogers30fab402012-01-23 15:43:46 -08002890 // TODO: enable when bionic has moved to dlmalloc 2.8.5
2891 // dlmalloc_inspect_all(HeapChunkContext::HeapChunkCallback, &context);
2892 UNIMPLEMENTED(WARNING) << "Native heap send heap segments";
Elliott Hughesa2155262011-11-16 16:26:58 -08002893 } else {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08002894 Heap* heap = Runtime::Current()->GetHeap();
2895 heap->GetAllocSpace()->Walk(HeapChunkContext::HeapChunkCallback, &context);
Elliott Hughesa2155262011-11-16 16:26:58 -08002896 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002897
2898 // Finally, send a heap end chunk.
2899 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHEN") : CHUNK_TYPE("HPEN"), sizeof(heap_id), heap_id);
Elliott Hughes767a1472011-10-26 18:49:02 -07002900}
2901
Elliott Hughes545a0642011-11-08 19:10:03 -08002902void Dbg::SetAllocTrackingEnabled(bool enabled) {
2903 MutexLock mu(gAllocTrackerLock);
2904 if (enabled) {
2905 if (recent_allocation_records_ == NULL) {
2906 LOG(INFO) << "Enabling alloc tracker (" << kNumAllocRecords << " entries, "
2907 << kMaxAllocRecordStackDepth << " frames --> "
2908 << (sizeof(AllocRecord) * kNumAllocRecords) << " bytes)";
2909 gAllocRecordHead = gAllocRecordCount = 0;
2910 recent_allocation_records_ = new AllocRecord[kNumAllocRecords];
2911 CHECK(recent_allocation_records_ != NULL);
2912 }
2913 } else {
2914 delete[] recent_allocation_records_;
2915 recent_allocation_records_ = NULL;
2916 }
2917}
2918
Ian Rogers0399dde2012-06-06 17:09:28 -07002919struct AllocRecordStackVisitor : public StackVisitor {
2920 AllocRecordStackVisitor(const ManagedStack* stack,
2921 const std::vector<TraceStackFrame>* trace_stack, AllocRecord* record) :
2922 StackVisitor(stack, trace_stack), record(record), depth(0) {
Elliott Hughes545a0642011-11-08 19:10:03 -08002923 }
2924
Ian Rogers0399dde2012-06-06 17:09:28 -07002925 bool VisitFrame() {
Elliott Hughes545a0642011-11-08 19:10:03 -08002926 if (depth >= kMaxAllocRecordStackDepth) {
Elliott Hughes530fa002012-03-12 11:44:49 -07002927 return false;
Elliott Hughes545a0642011-11-08 19:10:03 -08002928 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002929 Method* m = GetMethod();
2930 if (!m->IsRuntimeMethod()) {
2931 record->stack[depth].method = m;
2932 record->stack[depth].dex_pc = GetDexPc();
Elliott Hughes530fa002012-03-12 11:44:49 -07002933 ++depth;
Elliott Hughes545a0642011-11-08 19:10:03 -08002934 }
Elliott Hughes530fa002012-03-12 11:44:49 -07002935 return true;
Elliott Hughes545a0642011-11-08 19:10:03 -08002936 }
2937
2938 ~AllocRecordStackVisitor() {
2939 // Clear out any unused stack trace elements.
2940 for (; depth < kMaxAllocRecordStackDepth; ++depth) {
2941 record->stack[depth].method = NULL;
Ian Rogers0399dde2012-06-06 17:09:28 -07002942 record->stack[depth].dex_pc = 0;
Elliott Hughes545a0642011-11-08 19:10:03 -08002943 }
2944 }
2945
2946 AllocRecord* record;
2947 size_t depth;
2948};
2949
2950void Dbg::RecordAllocation(Class* type, size_t byte_count) {
2951 Thread* self = Thread::Current();
2952 CHECK(self != NULL);
2953
2954 MutexLock mu(gAllocTrackerLock);
2955 if (recent_allocation_records_ == NULL) {
2956 return;
2957 }
2958
2959 // Advance and clip.
2960 if (++gAllocRecordHead == kNumAllocRecords) {
2961 gAllocRecordHead = 0;
2962 }
2963
2964 // Fill in the basics.
2965 AllocRecord* record = &recent_allocation_records_[gAllocRecordHead];
2966 record->type = type;
2967 record->byte_count = byte_count;
2968 record->thin_lock_id = self->GetThinLockId();
2969
2970 // Fill in the stack trace.
Ian Rogers0399dde2012-06-06 17:09:28 -07002971 AllocRecordStackVisitor visitor(self->GetManagedStack(), self->GetTraceStack(), record);
2972 visitor.WalkStack();
Elliott Hughes545a0642011-11-08 19:10:03 -08002973
2974 if (gAllocRecordCount < kNumAllocRecords) {
2975 ++gAllocRecordCount;
2976 }
2977}
2978
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07002979// Returns the index of the head element.
2980//
2981// We point at the most-recently-written record, so if gAllocRecordCount is 1
2982// we want to use the current element. Take "head+1" and subtract count
2983// from it.
2984//
2985// We need to handle underflow in our circular buffer, so we add
2986// kNumAllocRecords and then mask it back down.
Elliott Hughesf8349362012-06-18 15:00:06 -07002987static inline int HeadIndex() EXCLUSIVE_LOCKS_REQUIRED(gAllocTrackerLock) {
Elliott Hughes545a0642011-11-08 19:10:03 -08002988 return (gAllocRecordHead+1 + kNumAllocRecords - gAllocRecordCount) & (kNumAllocRecords-1);
2989}
2990
2991void Dbg::DumpRecentAllocations() {
2992 MutexLock mu(gAllocTrackerLock);
2993 if (recent_allocation_records_ == NULL) {
2994 LOG(INFO) << "Not recording tracked allocations";
2995 return;
2996 }
2997
2998 // "i" is the head of the list. We want to start at the end of the
2999 // list and move forward to the tail.
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003000 size_t i = HeadIndex();
Elliott Hughes545a0642011-11-08 19:10:03 -08003001 size_t count = gAllocRecordCount;
3002
3003 LOG(INFO) << "Tracked allocations, (head=" << gAllocRecordHead << " count=" << count << ")";
3004 while (count--) {
3005 AllocRecord* record = &recent_allocation_records_[i];
3006
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003007 LOG(INFO) << StringPrintf(" Thread %-2d %6zd bytes ", record->thin_lock_id, record->byte_count)
Elliott Hughes545a0642011-11-08 19:10:03 -08003008 << PrettyClass(record->type);
3009
3010 for (size_t stack_frame = 0; stack_frame < kMaxAllocRecordStackDepth; ++stack_frame) {
3011 const Method* m = record->stack[stack_frame].method;
3012 if (m == NULL) {
3013 break;
3014 }
3015 LOG(INFO) << " " << PrettyMethod(m) << " line " << record->stack[stack_frame].LineNumber();
3016 }
3017
3018 // pause periodically to help logcat catch up
3019 if ((count % 5) == 0) {
3020 usleep(40000);
3021 }
3022
3023 i = (i + 1) & (kNumAllocRecords-1);
3024 }
3025}
3026
3027class StringTable {
3028 public:
3029 StringTable() {
3030 }
3031
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003032 void Add(const char* s) {
Elliott Hughes545a0642011-11-08 19:10:03 -08003033 table_.insert(s);
3034 }
3035
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003036 size_t IndexOf(const char* s) const {
3037 typedef std::set<std::string>::const_iterator It; // TODO: C++0x auto
3038 It it = table_.find(s);
3039 if (it == table_.end()) {
3040 LOG(FATAL) << "IndexOf(\"" << s << "\") failed";
3041 }
3042 return std::distance(table_.begin(), it);
Elliott Hughes545a0642011-11-08 19:10:03 -08003043 }
3044
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003045 size_t Size() const {
Elliott Hughes545a0642011-11-08 19:10:03 -08003046 return table_.size();
3047 }
3048
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003049 void WriteTo(std::vector<uint8_t>& bytes) const {
3050 typedef std::set<std::string>::const_iterator It; // TODO: C++0x auto
Elliott Hughes545a0642011-11-08 19:10:03 -08003051 for (It it = table_.begin(); it != table_.end(); ++it) {
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003052 const char* s = (*it).c_str();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003053 size_t s_len = CountModifiedUtf8Chars(s);
3054 UniquePtr<uint16_t> s_utf16(new uint16_t[s_len]);
3055 ConvertModifiedUtf8ToUtf16(s_utf16.get(), s);
3056 JDWP::AppendUtf16BE(bytes, s_utf16.get(), s_len);
Elliott Hughes545a0642011-11-08 19:10:03 -08003057 }
3058 }
3059
3060 private:
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003061 std::set<std::string> table_;
Elliott Hughes545a0642011-11-08 19:10:03 -08003062 DISALLOW_COPY_AND_ASSIGN(StringTable);
3063};
3064
3065/*
3066 * The data we send to DDMS contains everything we have recorded.
3067 *
3068 * Message header (all values big-endian):
3069 * (1b) message header len (to allow future expansion); includes itself
3070 * (1b) entry header len
3071 * (1b) stack frame len
3072 * (2b) number of entries
3073 * (4b) offset to string table from start of message
3074 * (2b) number of class name strings
3075 * (2b) number of method name strings
3076 * (2b) number of source file name strings
3077 * For each entry:
3078 * (4b) total allocation size
3079 * (2b) threadId
3080 * (2b) allocated object's class name index
3081 * (1b) stack depth
3082 * For each stack frame:
3083 * (2b) method's class name
3084 * (2b) method name
3085 * (2b) method source file
3086 * (2b) line number, clipped to 32767; -2 if native; -1 if no source
3087 * (xb) class name strings
3088 * (xb) method name strings
3089 * (xb) source file strings
3090 *
3091 * As with other DDM traffic, strings are sent as a 4-byte length
3092 * followed by UTF-16 data.
3093 *
3094 * We send up 16-bit unsigned indexes into string tables. In theory there
3095 * can be (kMaxAllocRecordStackDepth * kNumAllocRecords) unique strings in
3096 * each table, but in practice there should be far fewer.
3097 *
3098 * The chief reason for using a string table here is to keep the size of
3099 * the DDMS message to a minimum. This is partly to make the protocol
3100 * efficient, but also because we have to form the whole thing up all at
3101 * once in a memory buffer.
3102 *
3103 * We use separate string tables for class names, method names, and source
3104 * files to keep the indexes small. There will generally be no overlap
3105 * between the contents of these tables.
3106 */
3107jbyteArray Dbg::GetRecentAllocations() {
3108 if (false) {
3109 DumpRecentAllocations();
3110 }
3111
3112 MutexLock mu(gAllocTrackerLock);
3113
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003114 //
3115 // Part 1: generate string tables.
3116 //
Elliott Hughes545a0642011-11-08 19:10:03 -08003117 StringTable class_names;
3118 StringTable method_names;
3119 StringTable filenames;
3120
3121 int count = gAllocRecordCount;
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003122 int idx = HeadIndex();
Elliott Hughes545a0642011-11-08 19:10:03 -08003123 while (count--) {
3124 AllocRecord* record = &recent_allocation_records_[idx];
3125
Elliott Hughes91250e02011-12-13 22:30:35 -08003126 class_names.Add(ClassHelper(record->type).GetDescriptor());
Elliott Hughes545a0642011-11-08 19:10:03 -08003127
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003128 MethodHelper mh;
Elliott Hughes545a0642011-11-08 19:10:03 -08003129 for (size_t i = 0; i < kMaxAllocRecordStackDepth; i++) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003130 Method* m = record->stack[i].method;
Elliott Hughes545a0642011-11-08 19:10:03 -08003131 if (m != NULL) {
Ian Rogersba377812012-05-28 21:16:29 -07003132 mh.ChangeMethod(m);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003133 class_names.Add(mh.GetDeclaringClassDescriptor());
3134 method_names.Add(mh.GetName());
3135 filenames.Add(mh.GetDeclaringClassSourceFile());
Elliott Hughes545a0642011-11-08 19:10:03 -08003136 }
3137 }
3138
3139 idx = (idx + 1) & (kNumAllocRecords-1);
3140 }
3141
3142 LOG(INFO) << "allocation records: " << gAllocRecordCount;
3143
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003144 //
3145 // Part 2: allocate a buffer and generate the output.
3146 //
Elliott Hughes545a0642011-11-08 19:10:03 -08003147 std::vector<uint8_t> bytes;
3148
3149 // (1b) message header len (to allow future expansion); includes itself
3150 // (1b) entry header len
3151 // (1b) stack frame len
3152 const int kMessageHeaderLen = 15;
3153 const int kEntryHeaderLen = 9;
3154 const int kStackFrameLen = 8;
3155 JDWP::Append1BE(bytes, kMessageHeaderLen);
3156 JDWP::Append1BE(bytes, kEntryHeaderLen);
3157 JDWP::Append1BE(bytes, kStackFrameLen);
3158
3159 // (2b) number of entries
3160 // (4b) offset to string table from start of message
3161 // (2b) number of class name strings
3162 // (2b) number of method name strings
3163 // (2b) number of source file name strings
3164 JDWP::Append2BE(bytes, gAllocRecordCount);
3165 size_t string_table_offset = bytes.size();
3166 JDWP::Append4BE(bytes, 0); // We'll patch this later...
3167 JDWP::Append2BE(bytes, class_names.Size());
3168 JDWP::Append2BE(bytes, method_names.Size());
3169 JDWP::Append2BE(bytes, filenames.Size());
3170
3171 count = gAllocRecordCount;
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003172 idx = HeadIndex();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003173 ClassHelper kh;
Elliott Hughes545a0642011-11-08 19:10:03 -08003174 while (count--) {
3175 // For each entry:
3176 // (4b) total allocation size
3177 // (2b) thread id
3178 // (2b) allocated object's class name index
3179 // (1b) stack depth
3180 AllocRecord* record = &recent_allocation_records_[idx];
3181 size_t stack_depth = record->GetDepth();
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003182 kh.ChangeClass(record->type);
3183 size_t allocated_object_class_name_index = class_names.IndexOf(kh.GetDescriptor());
Elliott Hughes545a0642011-11-08 19:10:03 -08003184 JDWP::Append4BE(bytes, record->byte_count);
3185 JDWP::Append2BE(bytes, record->thin_lock_id);
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003186 JDWP::Append2BE(bytes, allocated_object_class_name_index);
Elliott Hughes545a0642011-11-08 19:10:03 -08003187 JDWP::Append1BE(bytes, stack_depth);
3188
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003189 MethodHelper mh;
Elliott Hughes545a0642011-11-08 19:10:03 -08003190 for (size_t stack_frame = 0; stack_frame < stack_depth; ++stack_frame) {
3191 // For each stack frame:
3192 // (2b) method's class name
3193 // (2b) method name
3194 // (2b) method source file
3195 // (2b) line number, clipped to 32767; -2 if native; -1 if no source
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003196 mh.ChangeMethod(record->stack[stack_frame].method);
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003197 size_t class_name_index = class_names.IndexOf(mh.GetDeclaringClassDescriptor());
3198 size_t method_name_index = method_names.IndexOf(mh.GetName());
3199 size_t file_name_index = filenames.IndexOf(mh.GetDeclaringClassSourceFile());
3200 JDWP::Append2BE(bytes, class_name_index);
3201 JDWP::Append2BE(bytes, method_name_index);
3202 JDWP::Append2BE(bytes, file_name_index);
Elliott Hughes545a0642011-11-08 19:10:03 -08003203 JDWP::Append2BE(bytes, record->stack[stack_frame].LineNumber());
3204 }
3205
3206 idx = (idx + 1) & (kNumAllocRecords-1);
3207 }
3208
3209 // (xb) class name strings
3210 // (xb) method name strings
3211 // (xb) source file strings
3212 JDWP::Set4BE(&bytes[string_table_offset], bytes.size());
3213 class_names.WriteTo(bytes);
3214 method_names.WriteTo(bytes);
3215 filenames.WriteTo(bytes);
3216
3217 JNIEnv* env = Thread::Current()->GetJniEnv();
3218 jbyteArray result = env->NewByteArray(bytes.size());
3219 if (result != NULL) {
3220 env->SetByteArrayRegion(result, 0, bytes.size(), reinterpret_cast<const jbyte*>(&bytes[0]));
3221 }
3222 return result;
3223}
3224
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003225} // namespace art