blob: 8549ae0f25dcd5c5449e994b032ae8ea833857b8 [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;
Elliott Hughes545a0642011-11-08 19:10:03 -080099 uintptr_t raw_pc;
100
101 int32_t LineNumber() const {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800102 return MethodHelper(method).GetLineNumFromNativePC(raw_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");
174AllocRecord* Dbg::recent_allocation_records_ = NULL; // TODO: CircularBuffer<AllocRecord>
175static size_t gAllocRecordHead = 0;
176static size_t gAllocRecordCount = 0;
177
Elliott Hughes86964332012-02-15 19:37:42 -0800178// Breakpoints and single-stepping.
179static Mutex gBreakpointsLock("breakpoints lock");
180static std::vector<Breakpoint> gBreakpoints;
181static SingleStepControl gSingleStepControl;
182
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) {
482 Runtime* runtime = Runtime::Current();
483 ScopedThreadListLock thread_list_lock;
484 runtime->GetThreadList()->ForEach(SetDebuggerUpdatesEnabledCallback, &enabled);
485}
486
Elliott Hughesa2155262011-11-16 16:26:58 -0800487void Dbg::GoActive() {
488 // Enable all debugging features, including scans for breakpoints.
489 // This is a no-op if we're already active.
490 // Only called from the JDWP handler thread.
491 if (gDebuggerActive) {
492 return;
493 }
494
495 LOG(INFO) << "Debugger is active";
496
Elliott Hughesc0f09332012-03-26 13:27:06 -0700497 {
498 // TODO: dalvik only warned if there were breakpoints left over. clear in Dbg::Disconnected?
499 MutexLock mu(gBreakpointsLock);
500 CHECK_EQ(gBreakpoints.size(), 0U);
501 }
Elliott Hughesa2155262011-11-16 16:26:58 -0800502
503 gDebuggerActive = true;
Elliott Hughesc0f09332012-03-26 13:27:06 -0700504 SetDebuggerUpdatesEnabled(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700505}
506
507void Dbg::Disconnected() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700508 CHECK(gDebuggerConnected);
509
Elliott Hughesc0f09332012-03-26 13:27:06 -0700510 LOG(INFO) << "Debugger is no longer active";
Elliott Hughes234ab152011-10-26 14:02:26 -0700511
Elliott Hughesc0f09332012-03-26 13:27:06 -0700512 gDebuggerActive = false;
513 SetDebuggerUpdatesEnabled(false);
Elliott Hughes234ab152011-10-26 14:02:26 -0700514
515 gRegistry->Clear();
516 gDebuggerConnected = false;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700517}
518
Elliott Hughesc0f09332012-03-26 13:27:06 -0700519bool Dbg::IsDebuggerActive() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700520 return gDebuggerActive;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700521}
522
Elliott Hughesc0f09332012-03-26 13:27:06 -0700523bool Dbg::IsJdwpConfigured() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700524 return gJdwpConfigured;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700525}
526
527int64_t Dbg::LastDebuggerActivity() {
Elliott Hughesca951522011-12-05 12:01:32 -0800528 return gJdwpState->LastDebuggerActivity();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700529}
530
531int Dbg::ThreadRunning() {
Elliott Hughes34e06962012-04-09 13:55:55 -0700532 return static_cast<int>(Thread::Current()->SetState(kRunnable));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700533}
534
535int Dbg::ThreadWaiting() {
Elliott Hughes34e06962012-04-09 13:55:55 -0700536 return static_cast<int>(Thread::Current()->SetState(kVmWait));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700537}
538
Elliott Hughes6ba581a2011-10-25 11:45:35 -0700539int Dbg::ThreadContinuing(int new_state) {
Elliott Hughes34e06962012-04-09 13:55:55 -0700540 return static_cast<int>(Thread::Current()->SetState(static_cast<ThreadState>(new_state)));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700541}
542
543void Dbg::UndoDebuggerSuspensions() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700544 Runtime::Current()->GetThreadList()->UndoDebuggerSuspensions();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700545}
546
547void Dbg::Exit(int status) {
Elliott Hughes1bba14f2011-12-01 18:00:36 -0800548 exit(status); // This is all dalvik did.
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700549}
550
Elliott Hughesbfe487b2011-10-26 15:48:55 -0700551void Dbg::VisitRoots(Heap::RootVisitor* visitor, void* arg) {
552 if (gRegistry != NULL) {
553 gRegistry->VisitRoots(visitor, arg);
554 }
555}
556
Elliott Hughesc308a5d2012-02-16 17:12:06 -0800557std::string Dbg::GetClassName(JDWP::RefTypeId classId) {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800558 Object* o = gRegistry->Get<Object*>(classId);
Elliott Hughes436e3722012-02-17 20:01:47 -0800559 if (o == NULL) {
560 return "NULL";
561 }
562 if (o == kInvalidObject) {
563 return StringPrintf("invalid object %p", reinterpret_cast<void*>(classId));
564 }
565 if (!o->IsClass()) {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800566 return StringPrintf("non-class %p", o); // This is only used for debugging output anyway.
567 }
Elliott Hughesc308a5d2012-02-16 17:12:06 -0800568 return DescriptorToName(ClassHelper(o->AsClass()).GetDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700569}
570
Elliott Hughes436e3722012-02-17 20:01:47 -0800571JDWP::JdwpError Dbg::GetClassObject(JDWP::RefTypeId id, JDWP::ObjectId& classObjectId) {
572 JDWP::JdwpError status;
573 Class* c = DecodeClass(id, status);
574 if (c == NULL) {
575 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800576 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800577 classObjectId = gRegistry->Add(c);
578 return JDWP::ERR_NONE;
Elliott Hughes86964332012-02-15 19:37:42 -0800579}
580
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800581JDWP::JdwpError Dbg::GetSuperclass(JDWP::RefTypeId id, JDWP::RefTypeId& superclassId) {
582 JDWP::JdwpError status;
583 Class* c = DecodeClass(id, status);
584 if (c == NULL) {
585 return status;
586 }
587 if (c->IsInterface()) {
588 // http://code.google.com/p/android/issues/detail?id=20856
Elliott Hughesa0933622012-04-17 10:46:02 -0700589 superclassId = 0;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800590 } else {
591 superclassId = gRegistry->Add(c->GetSuperClass());
592 }
593 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700594}
595
Elliott Hughes436e3722012-02-17 20:01:47 -0800596JDWP::JdwpError Dbg::GetClassLoader(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) {
Elliott Hughes1bba14f2011-12-01 18:00:36 -0800597 Object* o = gRegistry->Get<Object*>(id);
Elliott Hughes436e3722012-02-17 20:01:47 -0800598 if (o == NULL || o == kInvalidObject) {
599 return JDWP::ERR_INVALID_OBJECT;
600 }
601 expandBufAddObjectId(pReply, gRegistry->Add(o->GetClass()->GetClassLoader()));
602 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700603}
604
Elliott Hughes436e3722012-02-17 20:01:47 -0800605JDWP::JdwpError Dbg::GetModifiers(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) {
606 JDWP::JdwpError status;
607 Class* c = DecodeClass(id, status);
608 if (c == NULL) {
609 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800610 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800611
612 uint32_t access_flags = c->GetAccessFlags() & kAccJavaFlagsMask;
613
614 // Set ACC_SUPER; dex files don't contain this flag, but all classes are supposed to have it set.
615 // Class.getModifiers doesn't return it, but JDWP does, so we set it here.
616 access_flags |= kAccSuper;
617
618 expandBufAdd4BE(pReply, access_flags);
619
620 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700621}
622
Elliott Hughes436e3722012-02-17 20:01:47 -0800623JDWP::JdwpError Dbg::GetReflectedType(JDWP::RefTypeId classId, JDWP::ExpandBuf* pReply) {
624 JDWP::JdwpError status;
625 Class* c = DecodeClass(classId, status);
626 if (c == NULL) {
627 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800628 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800629
630 expandBufAdd1(pReply, c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS);
631 expandBufAddRefTypeId(pReply, classId);
632 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700633}
634
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800635void Dbg::GetClassList(std::vector<JDWP::RefTypeId>& classes) {
Elliott Hughesa2155262011-11-16 16:26:58 -0800636 // Get the complete list of reference classes (i.e. all classes except
637 // the primitive types).
638 // Returns a newly-allocated buffer full of RefTypeId values.
639 struct ClassListCreator {
Elliott Hughesba8eee12012-01-24 20:25:24 -0800640 explicit ClassListCreator(std::vector<JDWP::RefTypeId>& classes) : classes(classes) {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800641 }
642
Elliott Hughesa2155262011-11-16 16:26:58 -0800643 static bool Visit(Class* c, void* arg) {
644 return reinterpret_cast<ClassListCreator*>(arg)->Visit(c);
645 }
646
647 bool Visit(Class* c) {
648 if (!c->IsPrimitive()) {
649 classes.push_back(static_cast<JDWP::RefTypeId>(gRegistry->Add(c)));
650 }
651 return true;
652 }
653
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800654 std::vector<JDWP::RefTypeId>& classes;
Elliott Hughesa2155262011-11-16 16:26:58 -0800655 };
656
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800657 ClassListCreator clc(classes);
Elliott Hughesa2155262011-11-16 16:26:58 -0800658 Runtime::Current()->GetClassLinker()->VisitClasses(ClassListCreator::Visit, &clc);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700659}
660
Elliott Hughes436e3722012-02-17 20:01:47 -0800661JDWP::JdwpError Dbg::GetClassInfo(JDWP::RefTypeId classId, JDWP::JdwpTypeTag* pTypeTag, uint32_t* pStatus, std::string* pDescriptor) {
662 JDWP::JdwpError status;
663 Class* c = DecodeClass(classId, status);
664 if (c == NULL) {
665 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800666 }
667
Elliott Hughesa2155262011-11-16 16:26:58 -0800668 if (c->IsArrayClass()) {
669 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
670 *pTypeTag = JDWP::TT_ARRAY;
671 } else {
672 if (c->IsErroneous()) {
673 *pStatus = JDWP::CS_ERROR;
674 } else {
675 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED | JDWP::CS_INITIALIZED;
676 }
677 *pTypeTag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
678 }
679
680 if (pDescriptor != NULL) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800681 *pDescriptor = ClassHelper(c).GetDescriptor();
Elliott Hughesa2155262011-11-16 16:26:58 -0800682 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800683 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700684}
685
Elliott Hughesc3b77c72011-12-15 20:56:48 -0800686void Dbg::FindLoadedClassBySignature(const char* descriptor, std::vector<JDWP::RefTypeId>& ids) {
Elliott Hughes6fa602d2011-12-02 17:54:25 -0800687 std::vector<Class*> classes;
688 Runtime::Current()->GetClassLinker()->LookupClasses(descriptor, classes);
689 ids.clear();
690 for (size_t i = 0; i < classes.size(); ++i) {
691 ids.push_back(gRegistry->Add(classes[i]));
692 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700693}
694
Elliott Hughes2435a572012-02-17 16:07:41 -0800695JDWP::JdwpError Dbg::GetReferenceType(JDWP::ObjectId objectId, JDWP::ExpandBuf* pReply) {
Elliott Hughes499c5132011-11-17 14:55:11 -0800696 Object* o = gRegistry->Get<Object*>(objectId);
Elliott Hughes436e3722012-02-17 20:01:47 -0800697 if (o == NULL || o == kInvalidObject) {
Elliott Hughes2435a572012-02-17 16:07:41 -0800698 return JDWP::ERR_INVALID_OBJECT;
Elliott Hughes499c5132011-11-17 14:55:11 -0800699 }
Elliott Hughes2435a572012-02-17 16:07:41 -0800700
701 JDWP::JdwpTypeTag type_tag;
702 if (o->GetClass()->IsArrayClass()) {
703 type_tag = JDWP::TT_ARRAY;
704 } else if (o->GetClass()->IsInterface()) {
705 type_tag = JDWP::TT_INTERFACE;
706 } else {
707 type_tag = JDWP::TT_CLASS;
708 }
709 JDWP::RefTypeId type_id = gRegistry->Add(o->GetClass());
710
711 expandBufAdd1(pReply, type_tag);
712 expandBufAddRefTypeId(pReply, type_id);
713
714 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700715}
716
Elliott Hughes436e3722012-02-17 20:01:47 -0800717JDWP::JdwpError Dbg::GetSignature(JDWP::RefTypeId classId, std::string& signature) {
Elliott Hughes1fe7afb2012-02-13 17:23:03 -0800718 JDWP::JdwpError status;
Elliott Hughes436e3722012-02-17 20:01:47 -0800719 Class* c = DecodeClass(classId, status);
Elliott Hughes1fe7afb2012-02-13 17:23:03 -0800720 if (c == NULL) {
721 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800722 }
Elliott Hughes1fe7afb2012-02-13 17:23:03 -0800723 signature = ClassHelper(c).GetDescriptor();
724 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700725}
726
Elliott Hughes436e3722012-02-17 20:01:47 -0800727JDWP::JdwpError Dbg::GetSourceFile(JDWP::RefTypeId classId, std::string& result) {
728 JDWP::JdwpError status;
729 Class* c = DecodeClass(classId, status);
730 if (c == NULL) {
731 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800732 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800733 result = ClassHelper(c).GetSourceFile();
734 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700735}
736
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700737uint8_t Dbg::GetObjectTag(JDWP::ObjectId objectId) {
Elliott Hughes24437992011-11-30 14:49:33 -0800738 Object* o = gRegistry->Get<Object*>(objectId);
739 return TagFromObject(o);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700740}
741
Elliott Hughesaed4be92011-12-02 16:16:23 -0800742size_t Dbg::GetTagWidth(JDWP::JdwpTag tag) {
Elliott Hughesdbb40792011-11-18 17:05:22 -0800743 switch (tag) {
744 case JDWP::JT_VOID:
745 return 0;
746 case JDWP::JT_BYTE:
747 case JDWP::JT_BOOLEAN:
748 return 1;
749 case JDWP::JT_CHAR:
750 case JDWP::JT_SHORT:
751 return 2;
752 case JDWP::JT_FLOAT:
753 case JDWP::JT_INT:
754 return 4;
755 case JDWP::JT_ARRAY:
756 case JDWP::JT_OBJECT:
757 case JDWP::JT_STRING:
758 case JDWP::JT_THREAD:
759 case JDWP::JT_THREAD_GROUP:
760 case JDWP::JT_CLASS_LOADER:
761 case JDWP::JT_CLASS_OBJECT:
762 return sizeof(JDWP::ObjectId);
763 case JDWP::JT_DOUBLE:
764 case JDWP::JT_LONG:
765 return 8;
766 default:
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800767 LOG(FATAL) << "Unknown tag " << tag;
Elliott Hughesdbb40792011-11-18 17:05:22 -0800768 return -1;
769 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700770}
771
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800772JDWP::JdwpError Dbg::GetArrayLength(JDWP::ObjectId arrayId, int& length) {
773 JDWP::JdwpError status;
774 Array* a = DecodeArray(arrayId, status);
775 if (a == NULL) {
776 return status;
Elliott Hughes24437992011-11-30 14:49:33 -0800777 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800778 length = a->GetLength();
779 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700780}
781
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800782JDWP::JdwpError Dbg::OutputArray(JDWP::ObjectId arrayId, int offset, int count, JDWP::ExpandBuf* pReply) {
783 JDWP::JdwpError status;
784 Array* a = DecodeArray(arrayId, status);
785 if (a == NULL) {
786 return status;
787 }
Elliott Hughes24437992011-11-30 14:49:33 -0800788
789 if (offset < 0 || count < 0 || offset > a->GetLength() || a->GetLength() - offset < count) {
790 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800791 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughes24437992011-11-30 14:49:33 -0800792 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800793 std::string descriptor(ClassHelper(a->GetClass()).GetDescriptor());
Elliott Hughes24437992011-11-30 14:49:33 -0800794 JDWP::JdwpTag tag = BasicTagFromDescriptor(descriptor.c_str() + 1);
795
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800796 expandBufAdd1(pReply, tag);
797 expandBufAdd4BE(pReply, count);
798
Elliott Hughes24437992011-11-30 14:49:33 -0800799 if (IsPrimitiveTag(tag)) {
800 size_t width = GetTagWidth(tag);
Elliott Hughes24437992011-11-30 14:49:33 -0800801 uint8_t* dst = expandBufAddSpace(pReply, count * width);
802 if (width == 8) {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800803 const uint64_t* src8 = reinterpret_cast<uint64_t*>(a->GetRawData(sizeof(uint64_t)));
Elliott Hughes24437992011-11-30 14:49:33 -0800804 for (int i = 0; i < count; ++i) JDWP::Write8BE(&dst, src8[offset + i]);
805 } else if (width == 4) {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800806 const uint32_t* src4 = reinterpret_cast<uint32_t*>(a->GetRawData(sizeof(uint32_t)));
Elliott Hughes24437992011-11-30 14:49:33 -0800807 for (int i = 0; i < count; ++i) JDWP::Write4BE(&dst, src4[offset + i]);
808 } else if (width == 2) {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800809 const uint16_t* src2 = reinterpret_cast<uint16_t*>(a->GetRawData(sizeof(uint16_t)));
Elliott Hughes24437992011-11-30 14:49:33 -0800810 for (int i = 0; i < count; ++i) JDWP::Write2BE(&dst, src2[offset + i]);
811 } else {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800812 const uint8_t* src = reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint8_t)));
Elliott Hughes24437992011-11-30 14:49:33 -0800813 memcpy(dst, &src[offset * width], count * width);
814 }
815 } else {
816 ObjectArray<Object>* oa = a->AsObjectArray<Object>();
817 for (int i = 0; i < count; ++i) {
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800818 Object* element = oa->Get(offset + i);
Elliott Hughes24437992011-11-30 14:49:33 -0800819 JDWP::JdwpTag specific_tag = (element != NULL) ? TagFromObject(element) : tag;
820 expandBufAdd1(pReply, specific_tag);
821 expandBufAddObjectId(pReply, gRegistry->Add(element));
822 }
823 }
824
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800825 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700826}
827
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800828JDWP::JdwpError Dbg::SetArrayElements(JDWP::ObjectId arrayId, int offset, int count, const uint8_t* src) {
829 JDWP::JdwpError status;
830 Array* a = DecodeArray(arrayId, status);
831 if (a == NULL) {
832 return status;
833 }
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800834
835 if (offset < 0 || count < 0 || offset > a->GetLength() || a->GetLength() - offset < count) {
836 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800837 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800838 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800839 std::string descriptor(ClassHelper(a->GetClass()).GetDescriptor());
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800840 JDWP::JdwpTag tag = BasicTagFromDescriptor(descriptor.c_str() + 1);
841
842 if (IsPrimitiveTag(tag)) {
843 size_t width = GetTagWidth(tag);
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800844 if (width == 8) {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800845 uint8_t* dst = &(reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint64_t)))[offset * width]);
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800846 for (int i = 0; i < count; ++i) {
847 // Handle potentially non-aligned memory access one byte at a time for ARM's benefit.
848 uint64_t value;
849 for (size_t j = 0; j < sizeof(uint64_t); ++j) reinterpret_cast<uint8_t*>(&value)[j] = src[j];
850 src += sizeof(uint64_t);
851 JDWP::Write8BE(&dst, value);
852 }
853 } else if (width == 4) {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800854 uint8_t* dst = &(reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint32_t)))[offset * width]);
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800855 const uint32_t* src4 = reinterpret_cast<const uint32_t*>(src);
856 for (int i = 0; i < count; ++i) JDWP::Write4BE(&dst, src4[i]);
857 } else if (width == 2) {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800858 uint8_t* dst = &(reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint16_t)))[offset * width]);
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800859 const uint16_t* src2 = reinterpret_cast<const uint16_t*>(src);
860 for (int i = 0; i < count; ++i) JDWP::Write2BE(&dst, src2[i]);
861 } else {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800862 uint8_t* dst = &(reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint8_t)))[offset * width]);
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800863 memcpy(&dst[offset * width], src, count * width);
864 }
865 } else {
866 ObjectArray<Object>* oa = a->AsObjectArray<Object>();
867 for (int i = 0; i < count; ++i) {
868 JDWP::ObjectId id = JDWP::ReadObjectId(&src);
Elliott Hughes436e3722012-02-17 20:01:47 -0800869 Object* o = gRegistry->Get<Object*>(id);
870 if (o == kInvalidObject) {
871 return JDWP::ERR_INVALID_OBJECT;
872 }
873 oa->Set(offset + i, o);
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800874 }
875 }
876
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800877 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700878}
879
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800880JDWP::ObjectId Dbg::CreateString(const std::string& str) {
881 return gRegistry->Add(String::AllocFromModifiedUtf8(str.c_str()));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700882}
883
Elliott Hughes436e3722012-02-17 20:01:47 -0800884JDWP::JdwpError Dbg::CreateObject(JDWP::RefTypeId classId, JDWP::ObjectId& new_object) {
885 JDWP::JdwpError status;
886 Class* c = DecodeClass(classId, status);
887 if (c == NULL) {
888 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800889 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800890 new_object = gRegistry->Add(c->AllocObject());
891 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700892}
893
Elliott Hughesbf13d362011-12-08 15:51:37 -0800894/*
895 * Used by Eclipse's "Display" view to evaluate "new byte[5]" to get "(byte[]) [0, 0, 0, 0, 0]".
896 */
Elliott Hughes436e3722012-02-17 20:01:47 -0800897JDWP::JdwpError Dbg::CreateArrayObject(JDWP::RefTypeId arrayClassId, uint32_t length, JDWP::ObjectId& new_array) {
898 JDWP::JdwpError status;
899 Class* c = DecodeClass(arrayClassId, status);
900 if (c == NULL) {
901 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800902 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800903 new_array = gRegistry->Add(Array::Alloc(c, length));
904 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700905}
906
907bool Dbg::MatchType(JDWP::RefTypeId instClassId, JDWP::RefTypeId classId) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800908 JDWP::JdwpError status;
909 Class* c1 = DecodeClass(instClassId, status);
Elliott Hughesa656a0f2012-02-21 18:03:44 -0800910 CHECK(c1 != NULL);
Elliott Hughes436e3722012-02-17 20:01:47 -0800911 Class* c2 = DecodeClass(classId, status);
Elliott Hughesa656a0f2012-02-21 18:03:44 -0800912 CHECK(c2 != NULL);
913 return c1->IsAssignableFrom(c2);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700914}
915
Elliott Hughes86964332012-02-15 19:37:42 -0800916static JDWP::FieldId ToFieldId(const Field* f) {
Elliott Hughes03181a82011-11-17 17:22:21 -0800917#ifdef MOVING_GARBAGE_COLLECTOR
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700918 UNIMPLEMENTED(FATAL);
Elliott Hughes03181a82011-11-17 17:22:21 -0800919#else
920 return static_cast<JDWP::FieldId>(reinterpret_cast<uintptr_t>(f));
921#endif
922}
923
Elliott Hughes86964332012-02-15 19:37:42 -0800924static JDWP::MethodId ToMethodId(const Method* m) {
Elliott Hughes03181a82011-11-17 17:22:21 -0800925#ifdef MOVING_GARBAGE_COLLECTOR
926 UNIMPLEMENTED(FATAL);
927#else
928 return static_cast<JDWP::MethodId>(reinterpret_cast<uintptr_t>(m));
929#endif
930}
931
Elliott Hughes86964332012-02-15 19:37:42 -0800932static Field* FromFieldId(JDWP::FieldId fid) {
Elliott Hughesaed4be92011-12-02 16:16:23 -0800933#ifdef MOVING_GARBAGE_COLLECTOR
934 UNIMPLEMENTED(FATAL);
935#else
936 return reinterpret_cast<Field*>(static_cast<uintptr_t>(fid));
937#endif
938}
939
Elliott Hughes86964332012-02-15 19:37:42 -0800940static Method* FromMethodId(JDWP::MethodId mid) {
Elliott Hughes03181a82011-11-17 17:22:21 -0800941#ifdef MOVING_GARBAGE_COLLECTOR
942 UNIMPLEMENTED(FATAL);
943#else
944 return reinterpret_cast<Method*>(static_cast<uintptr_t>(mid));
945#endif
946}
947
Elliott Hughes86964332012-02-15 19:37:42 -0800948static void SetLocation(JDWP::JdwpLocation& location, Method* m, uintptr_t native_pc) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -0800949 if (m == NULL) {
950 memset(&location, 0, sizeof(location));
951 } else {
952 Class* c = m->GetDeclaringClass();
953 location.typeTag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
954 location.classId = gRegistry->Add(c);
955 location.methodId = ToMethodId(m);
Elliott Hughes972a47b2012-02-21 18:16:06 -0800956 location.dex_pc = m->IsNative() ? -1 : m->ToDexPC(native_pc);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -0800957 }
Elliott Hughesd07986f2011-12-06 18:27:45 -0800958}
959
Elliott Hughes436e3722012-02-17 20:01:47 -0800960std::string Dbg::GetMethodName(JDWP::RefTypeId, JDWP::MethodId methodId) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800961 Method* m = FromMethodId(methodId);
962 return MethodHelper(m).GetName();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700963}
964
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800965/*
966 * Augment the access flags for synthetic methods and fields by setting
967 * the (as described by the spec) "0xf0000000 bit". Also, strip out any
968 * flags not specified by the Java programming language.
969 */
970static uint32_t MangleAccessFlags(uint32_t accessFlags) {
971 accessFlags &= kAccJavaFlagsMask;
972 if ((accessFlags & kAccSynthetic) != 0) {
973 accessFlags |= 0xf0000000;
974 }
975 return accessFlags;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700976}
977
Elliott Hughesdbb40792011-11-18 17:05:22 -0800978static const uint16_t kEclipseWorkaroundSlot = 1000;
979
980/*
981 * Eclipse appears to expect that the "this" reference is in slot zero.
982 * If it's not, the "variables" display will show two copies of "this",
983 * possibly because it gets "this" from SF.ThisObject and then displays
984 * all locals with nonzero slot numbers.
985 *
986 * So, we remap the item in slot 0 to 1000, and remap "this" to zero. On
987 * SF.GetValues / SF.SetValues we map them back.
Elliott Hughesc5b734a2011-12-01 17:20:58 -0800988 *
989 * TODO: jdb uses the value to determine whether a variable is a local or an argument,
990 * by checking whether it's less than the number of arguments. To make that work, we'd
991 * have to "mangle" all the arguments to come first, not just the implicit argument 'this'.
Elliott Hughesdbb40792011-11-18 17:05:22 -0800992 */
993static uint16_t MangleSlot(uint16_t slot, const char* name) {
994 uint16_t newSlot = slot;
995 if (strcmp(name, "this") == 0) {
996 newSlot = 0;
997 } else if (slot == 0) {
998 newSlot = kEclipseWorkaroundSlot;
999 }
1000 return newSlot;
1001}
1002
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001003static uint16_t DemangleSlot(uint16_t slot, Method* m) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001004 if (slot == kEclipseWorkaroundSlot) {
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001005 return 0;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001006 } else if (slot == 0) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001007 const DexFile::CodeItem* code_item = MethodHelper(m).GetCodeItem();
1008 CHECK(code_item != NULL);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001009 return code_item->registers_size_ - code_item->ins_size_;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001010 }
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001011 return slot;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001012}
1013
Elliott Hughes436e3722012-02-17 20:01:47 -08001014JDWP::JdwpError Dbg::OutputDeclaredFields(JDWP::RefTypeId classId, bool with_generic, JDWP::ExpandBuf* pReply) {
1015 JDWP::JdwpError status;
1016 Class* c = DecodeClass(classId, status);
1017 if (c == NULL) {
1018 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001019 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001020
1021 size_t instance_field_count = c->NumInstanceFields();
1022 size_t static_field_count = c->NumStaticFields();
1023
1024 expandBufAdd4BE(pReply, instance_field_count + static_field_count);
1025
1026 for (size_t i = 0; i < instance_field_count + static_field_count; ++i) {
1027 Field* f = (i < instance_field_count) ? c->GetInstanceField(i) : c->GetStaticField(i - instance_field_count);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001028 FieldHelper fh(f);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001029 expandBufAddFieldId(pReply, ToFieldId(f));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001030 expandBufAddUtf8String(pReply, fh.GetName());
1031 expandBufAddUtf8String(pReply, fh.GetTypeDescriptor());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001032 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001033 static const char genericSignature[1] = "";
1034 expandBufAddUtf8String(pReply, genericSignature);
1035 }
1036 expandBufAdd4BE(pReply, MangleAccessFlags(f->GetAccessFlags()));
1037 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001038 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001039}
1040
Elliott Hughes436e3722012-02-17 20:01:47 -08001041JDWP::JdwpError Dbg::OutputDeclaredMethods(JDWP::RefTypeId classId, bool with_generic, JDWP::ExpandBuf* pReply) {
1042 JDWP::JdwpError status;
1043 Class* c = DecodeClass(classId, status);
1044 if (c == NULL) {
1045 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001046 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001047
1048 size_t direct_method_count = c->NumDirectMethods();
1049 size_t virtual_method_count = c->NumVirtualMethods();
1050
1051 expandBufAdd4BE(pReply, direct_method_count + virtual_method_count);
1052
1053 for (size_t i = 0; i < direct_method_count + virtual_method_count; ++i) {
1054 Method* m = (i < direct_method_count) ? c->GetDirectMethod(i) : c->GetVirtualMethod(i - direct_method_count);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001055 MethodHelper mh(m);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001056 expandBufAddMethodId(pReply, ToMethodId(m));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001057 expandBufAddUtf8String(pReply, mh.GetName());
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001058 expandBufAddUtf8String(pReply, mh.GetSignature());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001059 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001060 static const char genericSignature[1] = "";
1061 expandBufAddUtf8String(pReply, genericSignature);
1062 }
1063 expandBufAdd4BE(pReply, MangleAccessFlags(m->GetAccessFlags()));
1064 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001065 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001066}
1067
Elliott Hughes436e3722012-02-17 20:01:47 -08001068JDWP::JdwpError Dbg::OutputDeclaredInterfaces(JDWP::RefTypeId classId, JDWP::ExpandBuf* pReply) {
1069 JDWP::JdwpError status;
1070 Class* c = DecodeClass(classId, status);
1071 if (c == NULL) {
1072 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001073 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001074
1075 ClassHelper kh(c);
Ian Rogersd24e2642012-06-06 21:21:43 -07001076 size_t interface_count = kh.NumDirectInterfaces();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001077 expandBufAdd4BE(pReply, interface_count);
1078 for (size_t i = 0; i < interface_count; ++i) {
Ian Rogersd24e2642012-06-06 21:21:43 -07001079 expandBufAddRefTypeId(pReply, gRegistry->Add(kh.GetDirectInterface(i)));
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001080 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001081 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001082}
1083
Elliott Hughes436e3722012-02-17 20:01:47 -08001084void Dbg::OutputLineTable(JDWP::RefTypeId, JDWP::MethodId methodId, JDWP::ExpandBuf* pReply) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001085 struct DebugCallbackContext {
1086 int numItems;
1087 JDWP::ExpandBuf* pReply;
1088
Elliott Hughes2435a572012-02-17 16:07:41 -08001089 static bool Callback(void* context, uint32_t address, uint32_t line_number) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001090 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
1091 expandBufAdd8BE(pContext->pReply, address);
Elliott Hughes2435a572012-02-17 16:07:41 -08001092 expandBufAdd4BE(pContext->pReply, line_number);
Elliott Hughes03181a82011-11-17 17:22:21 -08001093 pContext->numItems++;
1094 return true;
1095 }
1096 };
1097
1098 Method* m = FromMethodId(methodId);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001099 MethodHelper mh(m);
Elliott Hughes03181a82011-11-17 17:22:21 -08001100 uint64_t start, end;
1101 if (m->IsNative()) {
1102 start = -1;
1103 end = -1;
1104 } else {
1105 start = 0;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001106 // TODO: what are the units supposed to be? *2?
1107 end = mh.GetCodeItem()->insns_size_in_code_units_;
Elliott Hughes03181a82011-11-17 17:22:21 -08001108 }
1109
1110 expandBufAdd8BE(pReply, start);
1111 expandBufAdd8BE(pReply, end);
1112
1113 // Add numLines later
1114 size_t numLinesOffset = expandBufGetLength(pReply);
1115 expandBufAdd4BE(pReply, 0);
1116
1117 DebugCallbackContext context;
1118 context.numItems = 0;
1119 context.pReply = pReply;
1120
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001121 mh.GetDexFile().DecodeDebugInfo(mh.GetCodeItem(), m->IsStatic(), m->GetDexMethodIndex(),
1122 DebugCallbackContext::Callback, NULL, &context);
Elliott Hughes03181a82011-11-17 17:22:21 -08001123
1124 JDWP::Set4BE(expandBufGetBuffer(pReply) + numLinesOffset, context.numItems);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001125}
1126
Elliott Hughes436e3722012-02-17 20:01:47 -08001127void Dbg::OutputVariableTable(JDWP::RefTypeId, JDWP::MethodId methodId, bool with_generic, JDWP::ExpandBuf* pReply) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001128 struct DebugCallbackContext {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001129 JDWP::ExpandBuf* pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001130 size_t variable_count;
1131 bool with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001132
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001133 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 -08001134 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
1135
Elliott Hughesad3da692012-02-24 16:51:35 -08001136 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 -08001137
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001138 slot = MangleSlot(slot, name);
1139
Elliott Hughesdbb40792011-11-18 17:05:22 -08001140 expandBufAdd8BE(pContext->pReply, startAddress);
1141 expandBufAddUtf8String(pContext->pReply, name);
1142 expandBufAddUtf8String(pContext->pReply, descriptor);
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001143 if (pContext->with_generic) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001144 expandBufAddUtf8String(pContext->pReply, signature);
1145 }
1146 expandBufAdd4BE(pContext->pReply, endAddress - startAddress);
1147 expandBufAdd4BE(pContext->pReply, slot);
1148
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001149 ++pContext->variable_count;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001150 }
1151 };
1152
1153 Method* m = FromMethodId(methodId);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001154 MethodHelper mh(m);
1155 const DexFile::CodeItem* code_item = mh.GetCodeItem();
Elliott Hughesdbb40792011-11-18 17:05:22 -08001156
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001157 // arg_count considers doubles and longs to take 2 units.
1158 // variable_count considers everything to take 1 unit.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001159 std::string shorty(mh.GetShorty());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001160 expandBufAdd4BE(pReply, m->NumArgRegisters(shorty));
Elliott Hughesdbb40792011-11-18 17:05:22 -08001161
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001162 // We don't know the total number of variables yet, so leave a blank and update it later.
1163 size_t variable_count_offset = expandBufGetLength(pReply);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001164 expandBufAdd4BE(pReply, 0);
1165
1166 DebugCallbackContext context;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001167 context.pReply = pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001168 context.variable_count = 0;
1169 context.with_generic = with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001170
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001171 mh.GetDexFile().DecodeDebugInfo(code_item, m->IsStatic(), m->GetDexMethodIndex(), NULL,
1172 DebugCallbackContext::Callback, &context);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001173
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001174 JDWP::Set4BE(expandBufGetBuffer(pReply) + variable_count_offset, context.variable_count);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001175}
1176
Elliott Hughesaed4be92011-12-02 16:16:23 -08001177JDWP::JdwpTag Dbg::GetFieldBasicTag(JDWP::FieldId fieldId) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001178 return BasicTagFromDescriptor(FieldHelper(FromFieldId(fieldId)).GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001179}
1180
Elliott Hughesaed4be92011-12-02 16:16:23 -08001181JDWP::JdwpTag Dbg::GetStaticFieldBasicTag(JDWP::FieldId fieldId) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001182 return BasicTagFromDescriptor(FieldHelper(FromFieldId(fieldId)).GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001183}
1184
Elliott Hughes0cf74332012-02-23 23:14:00 -08001185static JDWP::JdwpError GetFieldValueImpl(JDWP::RefTypeId refTypeId, JDWP::ObjectId objectId, JDWP::FieldId fieldId, JDWP::ExpandBuf* pReply, bool is_static) {
1186 JDWP::JdwpError status;
1187 Class* c = DecodeClass(refTypeId, status);
1188 if (refTypeId != 0 && c == NULL) {
1189 return status;
1190 }
1191
Elliott Hughesaed4be92011-12-02 16:16:23 -08001192 Object* o = gRegistry->Get<Object*>(objectId);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001193 if ((!is_static && o == NULL) || o == kInvalidObject) {
1194 return JDWP::ERR_INVALID_OBJECT;
1195 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001196 Field* f = FromFieldId(fieldId);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001197
1198 Class* receiver_class = c;
1199 if (receiver_class == NULL && o != NULL) {
1200 receiver_class = o->GetClass();
1201 }
1202 // TODO: should we give up now if receiver_class is NULL?
1203 if (receiver_class != NULL && !f->GetDeclaringClass()->IsAssignableFrom(receiver_class)) {
1204 LOG(INFO) << "ERR_INVALID_FIELDID: " << PrettyField(f) << " " << PrettyClass(receiver_class);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001205 return JDWP::ERR_INVALID_FIELDID;
1206 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001207
Elliott Hughes0cf74332012-02-23 23:14:00 -08001208 // The RI only enforces the static/non-static mismatch in one direction.
1209 // TODO: should we change the tests and check both?
1210 if (is_static) {
1211 if (!f->IsStatic()) {
1212 return JDWP::ERR_INVALID_FIELDID;
1213 }
1214 } else {
1215 if (f->IsStatic()) {
1216 LOG(WARNING) << "Ignoring non-NULL receiver for ObjectReference.SetValues on static field " << PrettyField(f);
1217 o = NULL;
1218 }
1219 }
1220
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001221 JDWP::JdwpTag tag = BasicTagFromDescriptor(FieldHelper(f).GetTypeDescriptor());
Elliott Hughesaed4be92011-12-02 16:16:23 -08001222
1223 if (IsPrimitiveTag(tag)) {
1224 expandBufAdd1(pReply, tag);
1225 if (tag == JDWP::JT_BOOLEAN || tag == JDWP::JT_BYTE) {
1226 expandBufAdd1(pReply, f->Get32(o));
1227 } else if (tag == JDWP::JT_CHAR || tag == JDWP::JT_SHORT) {
1228 expandBufAdd2BE(pReply, f->Get32(o));
1229 } else if (tag == JDWP::JT_FLOAT || tag == JDWP::JT_INT) {
1230 expandBufAdd4BE(pReply, f->Get32(o));
1231 } else if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
1232 expandBufAdd8BE(pReply, f->Get64(o));
1233 } else {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001234 LOG(FATAL) << "Unknown tag: " << tag;
Elliott Hughesaed4be92011-12-02 16:16:23 -08001235 }
1236 } else {
1237 Object* value = f->GetObject(o);
1238 expandBufAdd1(pReply, TagFromObject(value));
1239 expandBufAddObjectId(pReply, gRegistry->Add(value));
1240 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001241 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001242}
1243
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001244JDWP::JdwpError Dbg::GetFieldValue(JDWP::ObjectId objectId, JDWP::FieldId fieldId, JDWP::ExpandBuf* pReply) {
Elliott Hughes0cf74332012-02-23 23:14:00 -08001245 return GetFieldValueImpl(0, objectId, fieldId, pReply, false);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001246}
1247
Elliott Hughes0cf74332012-02-23 23:14:00 -08001248JDWP::JdwpError Dbg::GetStaticFieldValue(JDWP::RefTypeId refTypeId, JDWP::FieldId fieldId, JDWP::ExpandBuf* pReply) {
1249 return GetFieldValueImpl(refTypeId, 0, fieldId, pReply, true);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001250}
1251
1252static JDWP::JdwpError SetFieldValueImpl(JDWP::ObjectId objectId, JDWP::FieldId fieldId, uint64_t value, int width, bool is_static) {
Elliott Hughesaed4be92011-12-02 16:16:23 -08001253 Object* o = gRegistry->Get<Object*>(objectId);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001254 if ((!is_static && o == NULL) || o == kInvalidObject) {
1255 return JDWP::ERR_INVALID_OBJECT;
1256 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001257 Field* f = FromFieldId(fieldId);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001258
1259 // The RI only enforces the static/non-static mismatch in one direction.
1260 // TODO: should we change the tests and check both?
1261 if (is_static) {
1262 if (!f->IsStatic()) {
1263 return JDWP::ERR_INVALID_FIELDID;
1264 }
1265 } else {
1266 if (f->IsStatic()) {
1267 LOG(WARNING) << "Ignoring non-NULL receiver for ObjectReference.SetValues on static field " << PrettyField(f);
1268 o = NULL;
1269 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001270 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001271
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001272 JDWP::JdwpTag tag = BasicTagFromDescriptor(FieldHelper(f).GetTypeDescriptor());
Elliott Hughesaed4be92011-12-02 16:16:23 -08001273
1274 if (IsPrimitiveTag(tag)) {
1275 if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001276 CHECK_EQ(width, 8);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001277 f->Set64(o, value);
1278 } else {
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001279 CHECK_LE(width, 4);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001280 f->Set32(o, value);
1281 }
1282 } else {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001283 Object* v = gRegistry->Get<Object*>(value);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001284 if (v == kInvalidObject) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001285 return JDWP::ERR_INVALID_OBJECT;
1286 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001287 if (v != NULL) {
1288 Class* field_type = FieldHelper(f).GetType();
1289 if (!field_type->IsAssignableFrom(v->GetClass())) {
1290 return JDWP::ERR_INVALID_OBJECT;
1291 }
1292 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001293 f->SetObject(o, v);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001294 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001295
1296 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001297}
1298
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001299JDWP::JdwpError Dbg::SetFieldValue(JDWP::ObjectId objectId, JDWP::FieldId fieldId, uint64_t value, int width) {
1300 return SetFieldValueImpl(objectId, fieldId, value, width, false);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001301}
1302
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001303JDWP::JdwpError Dbg::SetStaticFieldValue(JDWP::FieldId fieldId, uint64_t value, int width) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001304 return SetFieldValueImpl(0, fieldId, value, width, true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001305}
1306
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001307std::string Dbg::StringToUtf8(JDWP::ObjectId strId) {
1308 String* s = gRegistry->Get<String*>(strId);
1309 return s->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001310}
1311
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001312bool Dbg::GetThreadName(JDWP::ObjectId threadId, std::string& name) {
1313 ScopedThreadListLock thread_list_lock;
1314 Thread* thread = DecodeThread(threadId);
1315 if (thread == NULL) {
1316 return false;
1317 }
Elliott Hughesffb465f2012-03-01 18:46:05 -08001318 thread->GetThreadName(name);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001319 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001320}
1321
Elliott Hughes2435a572012-02-17 16:07:41 -08001322JDWP::JdwpError Dbg::GetThreadGroup(JDWP::ObjectId threadId, JDWP::ExpandBuf* pReply) {
Elliott Hughes499c5132011-11-17 14:55:11 -08001323 Object* thread = gRegistry->Get<Object*>(threadId);
Elliott Hughes436e3722012-02-17 20:01:47 -08001324 if (thread == kInvalidObject) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001325 return JDWP::ERR_INVALID_OBJECT;
1326 }
1327
1328 // Okay, so it's an object, but is it actually a thread?
Elliott Hughes436e3722012-02-17 20:01:47 -08001329 if (DecodeThread(threadId) == NULL) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001330 return JDWP::ERR_INVALID_THREAD;
1331 }
Elliott Hughes499c5132011-11-17 14:55:11 -08001332
1333 Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/Thread;");
1334 CHECK(c != NULL);
1335 Field* f = c->FindInstanceField("group", "Ljava/lang/ThreadGroup;");
1336 CHECK(f != NULL);
1337 Object* group = f->GetObject(thread);
1338 CHECK(group != NULL);
Elliott Hughes2435a572012-02-17 16:07:41 -08001339 JDWP::ObjectId thread_group_id = gRegistry->Add(group);
1340
1341 expandBufAddObjectId(pReply, thread_group_id);
1342 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001343}
1344
Elliott Hughes499c5132011-11-17 14:55:11 -08001345std::string Dbg::GetThreadGroupName(JDWP::ObjectId threadGroupId) {
1346 Object* thread_group = gRegistry->Get<Object*>(threadGroupId);
1347 CHECK(thread_group != NULL);
1348
1349 Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/ThreadGroup;");
1350 CHECK(c != NULL);
1351 Field* f = c->FindInstanceField("name", "Ljava/lang/String;");
1352 CHECK(f != NULL);
1353 String* s = reinterpret_cast<String*>(f->GetObject(thread_group));
1354 return s->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001355}
1356
1357JDWP::ObjectId Dbg::GetThreadGroupParent(JDWP::ObjectId threadGroupId) {
Elliott Hughes4e235312011-12-02 11:34:15 -08001358 Object* thread_group = gRegistry->Get<Object*>(threadGroupId);
1359 CHECK(thread_group != NULL);
1360
1361 Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/ThreadGroup;");
1362 CHECK(c != NULL);
1363 Field* f = c->FindInstanceField("parent", "Ljava/lang/ThreadGroup;");
1364 CHECK(f != NULL);
1365 Object* parent = f->GetObject(thread_group);
1366 return gRegistry->Add(parent);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001367}
1368
1369JDWP::ObjectId Dbg::GetSystemThreadGroupId() {
Elliott Hughes462c9442012-03-23 18:47:50 -07001370 return gRegistry->Add(Thread::GetSystemThreadGroup());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001371}
1372
1373JDWP::ObjectId Dbg::GetMainThreadGroupId() {
Elliott Hughes462c9442012-03-23 18:47:50 -07001374 return gRegistry->Add(Thread::GetMainThreadGroup());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001375}
1376
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001377bool Dbg::GetThreadStatus(JDWP::ObjectId threadId, JDWP::JdwpThreadStatus* pThreadStatus, JDWP::JdwpSuspendStatus* pSuspendStatus) {
Elliott Hughes499c5132011-11-17 14:55:11 -08001378 ScopedThreadListLock thread_list_lock;
1379
1380 Thread* thread = DecodeThread(threadId);
1381 if (thread == NULL) {
1382 return false;
1383 }
1384
Elliott Hughes3ce4b262012-02-24 11:24:02 -08001385 // TODO: if we're in Thread.sleep(long), we should return TS_SLEEPING,
1386 // even if it's implemented using Object.wait(long).
Elliott Hughes499c5132011-11-17 14:55:11 -08001387 switch (thread->GetState()) {
Elliott Hughes34e06962012-04-09 13:55:55 -07001388 case kTerminated: *pThreadStatus = JDWP::TS_ZOMBIE; break;
1389 case kRunnable: *pThreadStatus = JDWP::TS_RUNNING; break;
1390 case kTimedWaiting: *pThreadStatus = JDWP::TS_WAIT; break;
1391 case kBlocked: *pThreadStatus = JDWP::TS_MONITOR; break;
1392 case kWaiting: *pThreadStatus = JDWP::TS_WAIT; break;
1393 case kStarting: *pThreadStatus = JDWP::TS_ZOMBIE; break;
1394 case kNative: *pThreadStatus = JDWP::TS_RUNNING; break;
1395 case kVmWait: *pThreadStatus = JDWP::TS_WAIT; break;
1396 case kSuspended: *pThreadStatus = JDWP::TS_RUNNING; break;
Elliott Hughescf2b2d42012-03-27 17:11:42 -07001397 // Don't add a 'default' here so the compiler can spot incompatible enum changes.
Elliott Hughes499c5132011-11-17 14:55:11 -08001398 }
1399
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001400 *pSuspendStatus = (thread->IsSuspended() ? JDWP::SUSPEND_STATUS_SUSPENDED : JDWP::SUSPEND_STATUS_NOT_SUSPENDED);
Elliott Hughes499c5132011-11-17 14:55:11 -08001401
1402 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001403}
1404
Elliott Hughes2435a572012-02-17 16:07:41 -08001405JDWP::JdwpError Dbg::GetThreadSuspendCount(JDWP::ObjectId threadId, JDWP::ExpandBuf* pReply) {
1406 Thread* thread = DecodeThread(threadId);
1407 if (thread == NULL) {
1408 return JDWP::ERR_INVALID_THREAD;
1409 }
1410 expandBufAdd4BE(pReply, thread->GetSuspendCount());
1411 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001412}
1413
1414bool Dbg::ThreadExists(JDWP::ObjectId threadId) {
Elliott Hughes761928d2011-11-16 18:33:03 -08001415 return DecodeThread(threadId) != NULL;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001416}
1417
1418bool Dbg::IsSuspended(JDWP::ObjectId threadId) {
Elliott Hughes761928d2011-11-16 18:33:03 -08001419 return DecodeThread(threadId)->IsSuspended();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001420}
1421
Elliott Hughesa2155262011-11-16 16:26:58 -08001422void Dbg::GetThreadGroupThreadsImpl(Object* thread_group, JDWP::ObjectId** ppThreadIds, uint32_t* pThreadCount) {
1423 struct ThreadListVisitor {
1424 static void Visit(Thread* t, void* arg) {
1425 reinterpret_cast<ThreadListVisitor*>(arg)->Visit(t);
1426 }
1427
1428 void Visit(Thread* t) {
1429 if (t == Dbg::GetDebugThread()) {
1430 // Skip the JDWP thread. Some debuggers get bent out of shape when they can't suspend and
1431 // query all threads, so it's easier if we just don't tell them about this thread.
1432 return;
1433 }
1434 if (thread_group == NULL || t->GetThreadGroup() == thread_group) {
1435 threads.push_back(gRegistry->Add(t->GetPeer()));
1436 }
1437 }
1438
1439 Object* thread_group;
1440 std::vector<JDWP::ObjectId> threads;
1441 };
1442
1443 ThreadListVisitor tlv;
1444 tlv.thread_group = thread_group;
1445
1446 {
1447 ScopedThreadListLock thread_list_lock;
1448 Runtime::Current()->GetThreadList()->ForEach(ThreadListVisitor::Visit, &tlv);
1449 }
1450
1451 *pThreadCount = tlv.threads.size();
1452 if (*pThreadCount == 0) {
1453 *ppThreadIds = NULL;
1454 } else {
1455 *ppThreadIds = new JDWP::ObjectId[*pThreadCount];
1456 for (size_t i = 0; i < *pThreadCount; ++i) {
1457 (*ppThreadIds)[i] = tlv.threads[i];
1458 }
1459 }
1460}
1461
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001462void Dbg::GetThreadGroupThreads(JDWP::ObjectId threadGroupId, JDWP::ObjectId** ppThreadIds, uint32_t* pThreadCount) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001463 GetThreadGroupThreadsImpl(gRegistry->Get<Object*>(threadGroupId), ppThreadIds, pThreadCount);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001464}
1465
1466void Dbg::GetAllThreads(JDWP::ObjectId** ppThreadIds, uint32_t* pThreadCount) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001467 GetThreadGroupThreadsImpl(NULL, ppThreadIds, pThreadCount);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001468}
1469
Elliott Hughes86964332012-02-15 19:37:42 -08001470static int GetStackDepth(Thread* thread) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001471 struct CountStackDepthVisitor : public Thread::StackVisitor {
1472 CountStackDepthVisitor() : depth(0) {}
Elliott Hughes530fa002012-03-12 11:44:49 -07001473 bool VisitFrame(const Frame& f, uintptr_t) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -08001474 if (f.HasMethod()) {
1475 ++depth;
1476 }
Elliott Hughes530fa002012-03-12 11:44:49 -07001477 return true;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001478 }
1479 size_t depth;
1480 };
1481 CountStackDepthVisitor visitor;
Elliott Hughes86964332012-02-15 19:37:42 -08001482 thread->WalkStack(&visitor);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001483 return visitor.depth;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001484}
1485
Elliott Hughes86964332012-02-15 19:37:42 -08001486int Dbg::GetThreadFrameCount(JDWP::ObjectId threadId) {
1487 ScopedThreadListLock thread_list_lock;
1488 return GetStackDepth(DecodeThread(threadId));
1489}
1490
Elliott Hughes530fa002012-03-12 11:44:49 -07001491void Dbg::GetThreadFrame(JDWP::ObjectId threadId, int desired_frame_number, JDWP::FrameId* pFrameId, JDWP::JdwpLocation* pLoc) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001492 ScopedThreadListLock thread_list_lock;
1493 struct GetFrameVisitor : public Thread::StackVisitor {
1494 GetFrameVisitor(int desired_frame_number, JDWP::FrameId* pFrameId, JDWP::JdwpLocation* pLoc)
Elliott Hughes530fa002012-03-12 11:44:49 -07001495 : depth(0), desired_frame_number(desired_frame_number), pFrameId(pFrameId), pLoc(pLoc) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001496 }
Elliott Hughes530fa002012-03-12 11:44:49 -07001497 bool VisitFrame(const Frame& f, uintptr_t pc) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001498 if (!f.HasMethod()) {
Elliott Hughes530fa002012-03-12 11:44:49 -07001499 return true; // The debugger can't do anything useful with a frame that has no Method*.
Elliott Hughes03181a82011-11-17 17:22:21 -08001500 }
Elliott Hughes03181a82011-11-17 17:22:21 -08001501 if (depth == desired_frame_number) {
1502 *pFrameId = reinterpret_cast<JDWP::FrameId>(f.GetSP());
Elliott Hughesd07986f2011-12-06 18:27:45 -08001503 SetLocation(*pLoc, f.GetMethod(), pc);
Elliott Hughes530fa002012-03-12 11:44:49 -07001504 return false;
Elliott Hughes03181a82011-11-17 17:22:21 -08001505 }
1506 ++depth;
Elliott Hughes530fa002012-03-12 11:44:49 -07001507 return true;
Elliott Hughes03181a82011-11-17 17:22:21 -08001508 }
Elliott Hughes03181a82011-11-17 17:22:21 -08001509 int depth;
1510 int desired_frame_number;
1511 JDWP::FrameId* pFrameId;
1512 JDWP::JdwpLocation* pLoc;
1513 };
1514 GetFrameVisitor visitor(desired_frame_number, pFrameId, pLoc);
1515 visitor.desired_frame_number = desired_frame_number;
1516 DecodeThread(threadId)->WalkStack(&visitor);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001517}
1518
1519JDWP::ObjectId Dbg::GetThreadSelfId() {
Elliott Hughes475fc232011-10-25 15:00:35 -07001520 return gRegistry->Add(Thread::Current()->GetPeer());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001521}
1522
Elliott Hughes475fc232011-10-25 15:00:35 -07001523void Dbg::SuspendVM() {
Elliott Hughes34e06962012-04-09 13:55:55 -07001524 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 -07001525 Runtime::Current()->GetThreadList()->SuspendAll(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001526}
1527
1528void Dbg::ResumeVM() {
Elliott Hughes475fc232011-10-25 15:00:35 -07001529 Runtime::Current()->GetThreadList()->ResumeAll(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001530}
1531
1532void Dbg::SuspendThread(JDWP::ObjectId threadId) {
Elliott Hughes4e235312011-12-02 11:34:15 -08001533 Object* peer = gRegistry->Get<Object*>(threadId);
1534 ScopedThreadListLock thread_list_lock;
1535 Thread* thread = Thread::FromManagedThread(peer);
1536 if (thread == NULL) {
1537 LOG(WARNING) << "No such thread for suspend: " << peer;
1538 return;
1539 }
1540 Runtime::Current()->GetThreadList()->Suspend(thread, true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001541}
1542
1543void Dbg::ResumeThread(JDWP::ObjectId threadId) {
Elliott Hughes4e235312011-12-02 11:34:15 -08001544 Object* peer = gRegistry->Get<Object*>(threadId);
1545 ScopedThreadListLock thread_list_lock;
1546 Thread* thread = Thread::FromManagedThread(peer);
1547 if (thread == NULL) {
1548 LOG(WARNING) << "No such thread for resume: " << peer;
1549 return;
1550 }
1551 Runtime::Current()->GetThreadList()->Resume(thread, true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001552}
1553
1554void Dbg::SuspendSelf() {
Elliott Hughes475fc232011-10-25 15:00:35 -07001555 Runtime::Current()->GetThreadList()->SuspendSelfForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001556}
1557
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001558static Object* GetThis(Frame& f) {
Elliott Hughes86b00102011-12-05 17:54:26 -08001559 Method* m = f.GetMethod();
Elliott Hughes86b00102011-12-05 17:54:26 -08001560 Object* o = NULL;
1561 if (!m->IsNative() && !m->IsStatic()) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001562 uint16_t reg = DemangleSlot(0, m);
Elliott Hughes86b00102011-12-05 17:54:26 -08001563 o = reinterpret_cast<Object*>(f.GetVReg(m, reg));
1564 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001565 return o;
1566}
1567
1568void Dbg::GetThisObject(JDWP::FrameId frameId, JDWP::ObjectId* pThisId) {
1569 Method** sp = reinterpret_cast<Method**>(frameId);
1570 Frame f(sp);
1571 Object* o = GetThis(f);
Elliott Hughes86b00102011-12-05 17:54:26 -08001572 *pThisId = gRegistry->Add(o);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001573}
1574
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001575void Dbg::GetLocalValue(JDWP::ObjectId /*threadId*/, JDWP::FrameId frameId, int slot, JDWP::JdwpTag tag, uint8_t* buf, size_t width) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001576 Method** sp = reinterpret_cast<Method**>(frameId);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001577 Frame f(sp);
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001578 Method* m = f.GetMethod();
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001579 uint16_t reg = DemangleSlot(slot, m);
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001580
Ian Rogers776ac1f2012-04-13 23:36:36 -07001581#if defined(ART_USE_LLVM_COMPILER)
1582 UNIMPLEMENTED(FATAL);
1583#else
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001584 const VmapTable vmap_table(m->GetVmapTableRaw());
1585 uint32_t vmap_offset;
1586 if (vmap_table.IsInContext(reg, vmap_offset)) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001587 UNIMPLEMENTED(FATAL) << "Don't know how to pull locals from callee save frames: " << vmap_offset;
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001588 }
Ian Rogers776ac1f2012-04-13 23:36:36 -07001589#endif
Elliott Hughesdbb40792011-11-18 17:05:22 -08001590
Elliott Hughesad3da692012-02-24 16:51:35 -08001591 // TODO: check that the tag is compatible with the actual type of the slot!
1592
Elliott Hughesdbb40792011-11-18 17:05:22 -08001593 switch (tag) {
1594 case JDWP::JT_BOOLEAN:
1595 {
Elliott Hughescccd84f2011-12-05 16:51:54 -08001596 CHECK_EQ(width, 1U);
Elliott Hughes1bba14f2011-12-01 18:00:36 -08001597 uint32_t intVal = f.GetVReg(m, reg);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001598 VLOG(jdwp) << "get boolean local " << reg << " = " << intVal;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001599 JDWP::Set1(buf+1, intVal != 0);
1600 }
1601 break;
1602 case JDWP::JT_BYTE:
1603 {
Elliott Hughescccd84f2011-12-05 16:51:54 -08001604 CHECK_EQ(width, 1U);
Elliott Hughes1bba14f2011-12-01 18:00:36 -08001605 uint32_t intVal = f.GetVReg(m, reg);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001606 VLOG(jdwp) << "get byte local " << reg << " = " << intVal;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001607 JDWP::Set1(buf+1, intVal);
1608 }
1609 break;
1610 case JDWP::JT_SHORT:
1611 case JDWP::JT_CHAR:
1612 {
Elliott Hughescccd84f2011-12-05 16:51:54 -08001613 CHECK_EQ(width, 2U);
Elliott Hughes1bba14f2011-12-01 18:00:36 -08001614 uint32_t intVal = f.GetVReg(m, reg);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001615 VLOG(jdwp) << "get short/char local " << reg << " = " << intVal;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001616 JDWP::Set2BE(buf+1, intVal);
1617 }
1618 break;
1619 case JDWP::JT_INT:
1620 case JDWP::JT_FLOAT:
1621 {
Elliott Hughescccd84f2011-12-05 16:51:54 -08001622 CHECK_EQ(width, 4U);
Elliott Hughes1bba14f2011-12-01 18:00:36 -08001623 uint32_t intVal = f.GetVReg(m, reg);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001624 VLOG(jdwp) << "get int/float local " << reg << " = " << intVal;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001625 JDWP::Set4BE(buf+1, intVal);
1626 }
1627 break;
1628 case JDWP::JT_ARRAY:
1629 {
Elliott Hughescccd84f2011-12-05 16:51:54 -08001630 CHECK_EQ(width, sizeof(JDWP::ObjectId));
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001631 Object* o = reinterpret_cast<Object*>(f.GetVReg(m, reg));
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001632 VLOG(jdwp) << "get array local " << reg << " = " << o;
Elliott Hughes88c5c352012-03-15 18:49:48 -07001633 if (!Runtime::Current()->GetHeap()->IsHeapAddress(o)) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001634 LOG(FATAL) << "Register " << reg << " expected to hold array: " << o;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001635 }
1636 JDWP::SetObjectId(buf+1, gRegistry->Add(o));
1637 }
1638 break;
Elliott Hughesad3da692012-02-24 16:51:35 -08001639 case JDWP::JT_CLASS_LOADER:
1640 case JDWP::JT_CLASS_OBJECT:
Elliott Hughesdbb40792011-11-18 17:05:22 -08001641 case JDWP::JT_OBJECT:
Elliott Hughesad3da692012-02-24 16:51:35 -08001642 case JDWP::JT_STRING:
1643 case JDWP::JT_THREAD:
1644 case JDWP::JT_THREAD_GROUP:
Elliott Hughesdbb40792011-11-18 17:05:22 -08001645 {
Elliott Hughescccd84f2011-12-05 16:51:54 -08001646 CHECK_EQ(width, sizeof(JDWP::ObjectId));
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001647 Object* o = reinterpret_cast<Object*>(f.GetVReg(m, reg));
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001648 VLOG(jdwp) << "get object local " << reg << " = " << o;
Elliott Hughes88c5c352012-03-15 18:49:48 -07001649 if (!Runtime::Current()->GetHeap()->IsHeapAddress(o)) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001650 LOG(FATAL) << "Register " << reg << " expected to hold object: " << o;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001651 }
1652 tag = TagFromObject(o);
1653 JDWP::SetObjectId(buf+1, gRegistry->Add(o));
1654 }
1655 break;
1656 case JDWP::JT_DOUBLE:
1657 case JDWP::JT_LONG:
1658 {
Elliott Hughescccd84f2011-12-05 16:51:54 -08001659 CHECK_EQ(width, 8U);
Elliott Hughes1bba14f2011-12-01 18:00:36 -08001660 uint32_t lo = f.GetVReg(m, reg);
1661 uint64_t hi = f.GetVReg(m, reg + 1);
1662 uint64_t longVal = (hi << 32) | lo;
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001663 VLOG(jdwp) << "get double/long local " << hi << ":" << lo << " = " << longVal;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001664 JDWP::Set8BE(buf+1, longVal);
1665 }
1666 break;
1667 default:
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001668 LOG(FATAL) << "Unknown tag " << tag;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001669 break;
1670 }
1671
1672 // Prepend tag, which may have been updated.
1673 JDWP::Set1(buf, tag);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001674}
1675
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001676void Dbg::SetLocalValue(JDWP::ObjectId /*threadId*/, JDWP::FrameId frameId, int slot, JDWP::JdwpTag tag, uint64_t value, size_t width) {
Elliott Hughescccd84f2011-12-05 16:51:54 -08001677 Method** sp = reinterpret_cast<Method**>(frameId);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001678 Frame f(sp);
Elliott Hughescccd84f2011-12-05 16:51:54 -08001679 Method* m = f.GetMethod();
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001680 uint16_t reg = DemangleSlot(slot, m);
Elliott Hughescccd84f2011-12-05 16:51:54 -08001681
Ian Rogers776ac1f2012-04-13 23:36:36 -07001682#if defined(ART_USE_LLVM_COMPILER)
1683 UNIMPLEMENTED(FATAL);
1684#else
Elliott Hughescccd84f2011-12-05 16:51:54 -08001685 const VmapTable vmap_table(m->GetVmapTableRaw());
1686 uint32_t vmap_offset;
1687 if (vmap_table.IsInContext(reg, vmap_offset)) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001688 UNIMPLEMENTED(FATAL) << "Don't know how to pull locals from callee save frames: " << vmap_offset;
Elliott Hughescccd84f2011-12-05 16:51:54 -08001689 }
Ian Rogers776ac1f2012-04-13 23:36:36 -07001690#endif
Elliott Hughescccd84f2011-12-05 16:51:54 -08001691
Elliott Hughesad3da692012-02-24 16:51:35 -08001692 // TODO: check that the tag is compatible with the actual type of the slot!
1693
Elliott Hughescccd84f2011-12-05 16:51:54 -08001694 switch (tag) {
1695 case JDWP::JT_BOOLEAN:
1696 case JDWP::JT_BYTE:
1697 CHECK_EQ(width, 1U);
1698 f.SetVReg(m, reg, static_cast<uint32_t>(value));
1699 break;
1700 case JDWP::JT_SHORT:
1701 case JDWP::JT_CHAR:
1702 CHECK_EQ(width, 2U);
1703 f.SetVReg(m, reg, static_cast<uint32_t>(value));
1704 break;
1705 case JDWP::JT_INT:
1706 case JDWP::JT_FLOAT:
1707 CHECK_EQ(width, 4U);
1708 f.SetVReg(m, reg, static_cast<uint32_t>(value));
1709 break;
1710 case JDWP::JT_ARRAY:
1711 case JDWP::JT_OBJECT:
1712 case JDWP::JT_STRING:
1713 {
1714 CHECK_EQ(width, sizeof(JDWP::ObjectId));
1715 Object* o = gRegistry->Get<Object*>(static_cast<JDWP::ObjectId>(value));
Elliott Hughesad3da692012-02-24 16:51:35 -08001716 if (o == kInvalidObject) {
1717 UNIMPLEMENTED(FATAL) << "return an error code when given an invalid object to store";
1718 }
Elliott Hughescccd84f2011-12-05 16:51:54 -08001719 f.SetVReg(m, reg, static_cast<uint32_t>(reinterpret_cast<uintptr_t>(o)));
1720 }
1721 break;
1722 case JDWP::JT_DOUBLE:
1723 case JDWP::JT_LONG:
1724 CHECK_EQ(width, 8U);
1725 f.SetVReg(m, reg, static_cast<uint32_t>(value));
1726 f.SetVReg(m, reg + 1, static_cast<uint32_t>(value >> 32));
1727 break;
1728 default:
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001729 LOG(FATAL) << "Unknown tag " << tag;
Elliott Hughescccd84f2011-12-05 16:51:54 -08001730 break;
1731 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001732}
1733
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001734void Dbg::PostLocationEvent(const Method* m, int dex_pc, Object* this_object, int event_flags) {
1735 Class* c = m->GetDeclaringClass();
1736
1737 JDWP::JdwpLocation location;
1738 location.typeTag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
1739 location.classId = gRegistry->Add(c);
1740 location.methodId = ToMethodId(m);
Elliott Hughes972a47b2012-02-21 18:16:06 -08001741 location.dex_pc = m->IsNative() ? -1 : dex_pc;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001742
1743 // Note we use "NoReg" so we don't keep track of references that are
1744 // never actually sent to the debugger. 'this_id' is only used to
1745 // compare against registered events...
1746 JDWP::ObjectId this_id = static_cast<JDWP::ObjectId>(reinterpret_cast<uintptr_t>(this_object));
1747 if (gJdwpState->PostLocationEvent(&location, this_id, event_flags)) {
1748 // ...unless there's a registered event, in which case we
1749 // need to really track the class and 'this'.
1750 gRegistry->Add(c);
1751 gRegistry->Add(this_object);
1752 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001753}
1754
Elliott Hughesd07986f2011-12-06 18:27:45 -08001755void Dbg::PostException(Method** sp, Method* throwMethod, uintptr_t throwNativePc, Method* catchMethod, uintptr_t catchNativePc, Object* exception) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07001756 if (!IsDebuggerActive()) {
Ian Rogers0ad5bb82011-12-07 10:16:32 -08001757 return;
1758 }
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001759
Elliott Hughesd07986f2011-12-06 18:27:45 -08001760 JDWP::JdwpLocation throw_location;
1761 SetLocation(throw_location, throwMethod, throwNativePc);
1762 JDWP::JdwpLocation catch_location;
1763 SetLocation(catch_location, catchMethod, catchNativePc);
1764
1765 // We need 'this' for InstanceOnly filters.
1766 JDWP::ObjectId this_id;
1767 GetThisObject(reinterpret_cast<JDWP::FrameId>(sp), &this_id);
1768
1769 /*
1770 * Hand the event to the JDWP exception handler. Note we're using the
1771 * "NoReg" objectID on the exception, which is not strictly correct --
1772 * the exception object WILL be passed up to the debugger if the
1773 * debugger is interested in the event. We do this because the current
1774 * implementation of the debugger object registry never throws anything
1775 * away, and some people were experiencing a fatal build up of exception
1776 * objects when dealing with certain libraries.
1777 */
1778 JDWP::ObjectId exception_id = static_cast<JDWP::ObjectId>(reinterpret_cast<uintptr_t>(exception));
1779 JDWP::RefTypeId exception_class_id = gRegistry->Add(exception->GetClass());
1780
1781 gJdwpState->PostException(&throw_location, exception_id, exception_class_id, &catch_location, this_id);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001782}
1783
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001784void Dbg::PostClassPrepare(Class* c) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07001785 if (!IsDebuggerActive()) {
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001786 return;
1787 }
1788
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001789 // OLD-TODO - we currently always send both "verified" and "prepared" since
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001790 // debuggers seem to like that. There might be some advantage to honesty,
1791 // since the class may not yet be verified.
1792 int state = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
1793 JDWP::JdwpTypeTag tag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
1794 gJdwpState->PostClassPrepare(tag, gRegistry->Add(c), ClassHelper(c).GetDescriptor(), state);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001795}
1796
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001797void Dbg::UpdateDebugger(int32_t dex_pc, Thread* self, Method** sp) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07001798 if (!IsDebuggerActive() || dex_pc == -2 /* fake method exit */) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001799 return;
1800 }
1801
Elliott Hughes86964332012-02-15 19:37:42 -08001802 Frame f(sp);
1803 f.Next(); // Skip callee save frame.
1804 Method* m = f.GetMethod();
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001805
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001806 if (dex_pc == -1) {
Elliott Hughes2aa2e392012-02-17 17:15:43 -08001807 // We use a pc of -1 to represent method entry, since we might branch back to pc 0 later.
1808 // This means that for this special notification, there can't be anything else interesting
1809 // going on, so we're done already.
1810 Dbg::PostLocationEvent(m, 0, GetThis(f), kMethodEntry);
1811 return;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001812 }
1813
Elliott Hughes2aa2e392012-02-17 17:15:43 -08001814 int event_flags = 0;
1815
Elliott Hughes86964332012-02-15 19:37:42 -08001816 if (IsBreakpoint(m, dex_pc)) {
1817 event_flags |= kBreakpoint;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001818 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001819
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001820 // If the debugger is single-stepping one of our threads, check to
1821 // see if we're that thread and we've reached a step point.
Elliott Hughes86964332012-02-15 19:37:42 -08001822 if (gSingleStepControl.is_active && gSingleStepControl.thread == self) {
1823 CHECK(!m->IsNative());
1824 if (gSingleStepControl.step_depth == JDWP::SD_INTO) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001825 // Step into method calls. We break when the line number
1826 // or method pointer changes. If we're in SS_MIN mode, we
1827 // always stop.
Elliott Hughes86964332012-02-15 19:37:42 -08001828 if (gSingleStepControl.method != m) {
1829 event_flags |= kSingleStep;
1830 VLOG(jdwp) << "SS new method";
1831 } else if (gSingleStepControl.step_size == JDWP::SS_MIN) {
1832 event_flags |= kSingleStep;
1833 VLOG(jdwp) << "SS new instruction";
Elliott Hughes2435a572012-02-17 16:07:41 -08001834 } else if (gSingleStepControl.dex_pcs.find(dex_pc) == gSingleStepControl.dex_pcs.end()) {
1835 event_flags |= kSingleStep;
1836 VLOG(jdwp) << "SS new line";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001837 }
Elliott Hughes86964332012-02-15 19:37:42 -08001838 } else if (gSingleStepControl.step_depth == JDWP::SD_OVER) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001839 // Step over method calls. We break when the line number is
1840 // different and the frame depth is <= the original frame
1841 // depth. (We can't just compare on the method, because we
1842 // might get unrolled past it by an exception, and it's tricky
1843 // to identify recursion.)
Elliott Hughes86964332012-02-15 19:37:42 -08001844
1845 // TODO: can we just use the value of 'sp'?
1846 int stack_depth = GetStackDepth(self);
1847
1848 if (stack_depth < gSingleStepControl.stack_depth) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001849 // popped up one or more frames, always trigger
Elliott Hughes86964332012-02-15 19:37:42 -08001850 event_flags |= kSingleStep;
1851 VLOG(jdwp) << "SS method pop";
1852 } else if (stack_depth == gSingleStepControl.stack_depth) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001853 // same depth, see if we moved
Elliott Hughes86964332012-02-15 19:37:42 -08001854 if (gSingleStepControl.step_size == JDWP::SS_MIN) {
1855 event_flags |= kSingleStep;
1856 VLOG(jdwp) << "SS new instruction";
Elliott Hughes2435a572012-02-17 16:07:41 -08001857 } else if (gSingleStepControl.dex_pcs.find(dex_pc) == gSingleStepControl.dex_pcs.end()) {
1858 event_flags |= kSingleStep;
1859 VLOG(jdwp) << "SS new line";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001860 }
1861 }
1862 } else {
Elliott Hughes86964332012-02-15 19:37:42 -08001863 CHECK_EQ(gSingleStepControl.step_depth, JDWP::SD_OUT);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001864 // Return from the current method. We break when the frame
1865 // depth pops up.
1866
1867 // This differs from the "method exit" break in that it stops
1868 // with the PC at the next instruction in the returned-to
1869 // function, rather than the end of the returning function.
Elliott Hughes86964332012-02-15 19:37:42 -08001870
1871 // TODO: can we just use the value of 'sp'?
1872 int stack_depth = GetStackDepth(self);
1873 if (stack_depth < gSingleStepControl.stack_depth) {
1874 event_flags |= kSingleStep;
1875 VLOG(jdwp) << "SS method pop";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001876 }
1877 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001878 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001879
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001880 // Check to see if this is a "return" instruction. JDWP says we should
1881 // send the event *after* the code has been executed, but it also says
1882 // the location we provide is the last instruction. Since the "return"
1883 // instruction has no interesting side effects, we should be safe.
1884 // (We can't just move this down to the returnFromMethod label because
1885 // we potentially need to combine it with other events.)
1886 // We're also not supposed to generate a method exit event if the method
1887 // terminates "with a thrown exception".
Elliott Hughes86964332012-02-15 19:37:42 -08001888 if (dex_pc >= 0) {
1889 const DexFile::CodeItem* code_item = MethodHelper(m).GetCodeItem();
1890 CHECK(code_item != NULL);
1891 CHECK_LT(dex_pc, static_cast<int32_t>(code_item->insns_size_in_code_units_));
1892 if (Instruction::At(&code_item->insns_[dex_pc])->IsReturn()) {
1893 event_flags |= kMethodExit;
1894 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001895 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001896
1897 // If there's something interesting going on, see if it matches one
1898 // of the debugger filters.
1899 if (event_flags != 0) {
Elliott Hughes86964332012-02-15 19:37:42 -08001900 Dbg::PostLocationEvent(m, dex_pc, GetThis(f), event_flags);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001901 }
1902}
1903
Elliott Hughes86964332012-02-15 19:37:42 -08001904void Dbg::WatchLocation(const JDWP::JdwpLocation* location) {
1905 MutexLock mu(gBreakpointsLock);
1906 Method* m = FromMethodId(location->methodId);
Elliott Hughes972a47b2012-02-21 18:16:06 -08001907 gBreakpoints.push_back(Breakpoint(m, location->dex_pc));
Elliott Hughes86964332012-02-15 19:37:42 -08001908 VLOG(jdwp) << "Set breakpoint #" << (gBreakpoints.size() - 1) << ": " << gBreakpoints[gBreakpoints.size() - 1];
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001909}
1910
Elliott Hughes86964332012-02-15 19:37:42 -08001911void Dbg::UnwatchLocation(const JDWP::JdwpLocation* location) {
1912 MutexLock mu(gBreakpointsLock);
1913 Method* m = FromMethodId(location->methodId);
1914 for (size_t i = 0; i < gBreakpoints.size(); ++i) {
Elliott Hughes972a47b2012-02-21 18:16:06 -08001915 if (gBreakpoints[i].method == m && gBreakpoints[i].dex_pc == location->dex_pc) {
Elliott Hughes86964332012-02-15 19:37:42 -08001916 VLOG(jdwp) << "Removed breakpoint #" << i << ": " << gBreakpoints[i];
1917 gBreakpoints.erase(gBreakpoints.begin() + i);
1918 return;
1919 }
1920 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001921}
1922
Elliott Hughes2435a572012-02-17 16:07:41 -08001923JDWP::JdwpError Dbg::ConfigureStep(JDWP::ObjectId threadId, JDWP::JdwpStepSize step_size, JDWP::JdwpStepDepth step_depth) {
Elliott Hughes86964332012-02-15 19:37:42 -08001924 Thread* thread = DecodeThread(threadId);
Elliott Hughes2435a572012-02-17 16:07:41 -08001925 if (thread == NULL) {
1926 return JDWP::ERR_INVALID_THREAD;
1927 }
Elliott Hughes86964332012-02-15 19:37:42 -08001928
1929 // TODO: there's no theoretical reason why we couldn't support single-stepping
1930 // of multiple threads at once, but we never did so historically.
1931 if (gSingleStepControl.thread != NULL && thread != gSingleStepControl.thread) {
1932 LOG(WARNING) << "single-step already active for " << *gSingleStepControl.thread
1933 << "; switching to " << *thread;
1934 }
1935
Elliott Hughes2435a572012-02-17 16:07:41 -08001936 //
1937 // Work out what Method* we're in, the current line number, and how deep the stack currently
1938 // is for step-out.
1939 //
1940
Elliott Hughes86964332012-02-15 19:37:42 -08001941 struct SingleStepStackVisitor : public Thread::StackVisitor {
1942 SingleStepStackVisitor() {
1943 gSingleStepControl.method = NULL;
1944 gSingleStepControl.stack_depth = 0;
1945 }
Elliott Hughes530fa002012-03-12 11:44:49 -07001946 bool VisitFrame(const Frame& f, uintptr_t pc) {
Elliott Hughes86964332012-02-15 19:37:42 -08001947 if (f.HasMethod()) {
1948 ++gSingleStepControl.stack_depth;
1949 if (gSingleStepControl.method == NULL) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001950 const Method* m = f.GetMethod();
1951 const DexCache* dex_cache = m->GetDeclaringClass()->GetDexCache();
1952 gSingleStepControl.method = m;
1953 gSingleStepControl.line_number = -1;
1954 if (dex_cache != NULL) {
1955 const DexFile& dex_file = Runtime::Current()->GetClassLinker()->FindDexFile(dex_cache);
1956 gSingleStepControl.line_number = dex_file.GetLineNumFromPC(m, m->ToDexPC(pc));
1957 }
Elliott Hughes86964332012-02-15 19:37:42 -08001958 }
1959 }
Elliott Hughes530fa002012-03-12 11:44:49 -07001960 return true;
Elliott Hughes86964332012-02-15 19:37:42 -08001961 }
1962 };
1963 SingleStepStackVisitor visitor;
1964 thread->WalkStack(&visitor);
1965
Elliott Hughes2435a572012-02-17 16:07:41 -08001966 //
1967 // Find the dex_pc values that correspond to the current line, for line-based single-stepping.
1968 //
1969
1970 struct DebugCallbackContext {
1971 DebugCallbackContext() {
1972 last_pc_valid = false;
1973 last_pc = 0;
Elliott Hughes2435a572012-02-17 16:07:41 -08001974 }
1975
1976 static bool Callback(void* raw_context, uint32_t address, uint32_t line_number) {
1977 DebugCallbackContext* context = reinterpret_cast<DebugCallbackContext*>(raw_context);
1978 if (static_cast<int32_t>(line_number) == gSingleStepControl.line_number) {
1979 if (!context->last_pc_valid) {
1980 // Everything from this address until the next line change is ours.
1981 context->last_pc = address;
1982 context->last_pc_valid = true;
1983 }
1984 // Otherwise, if we're already in a valid range for this line,
1985 // just keep going (shouldn't really happen)...
1986 } else if (context->last_pc_valid) { // and the line number is new
1987 // Add everything from the last entry up until here to the set
1988 for (uint32_t dex_pc = context->last_pc; dex_pc < address; ++dex_pc) {
1989 gSingleStepControl.dex_pcs.insert(dex_pc);
1990 }
1991 context->last_pc_valid = false;
1992 }
1993 return false; // There may be multiple entries for any given line.
1994 }
1995
1996 ~DebugCallbackContext() {
1997 // If the line number was the last in the position table...
1998 if (last_pc_valid) {
1999 size_t end = MethodHelper(gSingleStepControl.method).GetCodeItem()->insns_size_in_code_units_;
2000 for (uint32_t dex_pc = last_pc; dex_pc < end; ++dex_pc) {
2001 gSingleStepControl.dex_pcs.insert(dex_pc);
2002 }
2003 }
2004 }
2005
2006 bool last_pc_valid;
2007 uint32_t last_pc;
2008 };
Elliott Hughes3e2e1a22012-02-21 11:33:41 -08002009 gSingleStepControl.dex_pcs.clear();
Elliott Hughes2435a572012-02-17 16:07:41 -08002010 const Method* m = gSingleStepControl.method;
Elliott Hughes3e2e1a22012-02-21 11:33:41 -08002011 if (m->IsNative()) {
2012 gSingleStepControl.line_number = -1;
2013 } else {
2014 DebugCallbackContext context;
2015 MethodHelper mh(m);
2016 mh.GetDexFile().DecodeDebugInfo(mh.GetCodeItem(), m->IsStatic(), m->GetDexMethodIndex(),
2017 DebugCallbackContext::Callback, NULL, &context);
2018 }
Elliott Hughes2435a572012-02-17 16:07:41 -08002019
2020 //
2021 // Everything else...
2022 //
2023
Elliott Hughes86964332012-02-15 19:37:42 -08002024 gSingleStepControl.thread = thread;
2025 gSingleStepControl.step_size = step_size;
2026 gSingleStepControl.step_depth = step_depth;
2027 gSingleStepControl.is_active = true;
2028
Elliott Hughes2435a572012-02-17 16:07:41 -08002029 if (VLOG_IS_ON(jdwp)) {
2030 VLOG(jdwp) << "Single-step thread: " << *gSingleStepControl.thread;
2031 VLOG(jdwp) << "Single-step step size: " << gSingleStepControl.step_size;
2032 VLOG(jdwp) << "Single-step step depth: " << gSingleStepControl.step_depth;
2033 VLOG(jdwp) << "Single-step current method: " << PrettyMethod(gSingleStepControl.method);
2034 VLOG(jdwp) << "Single-step current line: " << gSingleStepControl.line_number;
2035 VLOG(jdwp) << "Single-step current stack depth: " << gSingleStepControl.stack_depth;
2036 VLOG(jdwp) << "Single-step dex_pc values:";
2037 for (std::set<uint32_t>::iterator it = gSingleStepControl.dex_pcs.begin() ; it != gSingleStepControl.dex_pcs.end(); ++it) {
Elliott Hughes229feb72012-02-23 13:33:29 -08002038 VLOG(jdwp) << StringPrintf(" %#x", *it);
Elliott Hughes2435a572012-02-17 16:07:41 -08002039 }
2040 }
2041
2042 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002043}
2044
Elliott Hughes1bac54f2012-03-16 12:48:31 -07002045void Dbg::UnconfigureStep(JDWP::ObjectId /*threadId*/) {
Elliott Hughes86964332012-02-15 19:37:42 -08002046 gSingleStepControl.is_active = false;
2047 gSingleStepControl.thread = NULL;
Elliott Hughes2435a572012-02-17 16:07:41 -08002048 gSingleStepControl.dex_pcs.clear();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002049}
2050
Elliott Hughes45651fd2012-02-21 15:48:20 -08002051static char JdwpTagToShortyChar(JDWP::JdwpTag tag) {
2052 switch (tag) {
2053 default:
2054 LOG(FATAL) << "unknown JDWP tag: " << PrintableChar(tag);
2055
2056 // Primitives.
2057 case JDWP::JT_BYTE: return 'B';
2058 case JDWP::JT_CHAR: return 'C';
2059 case JDWP::JT_FLOAT: return 'F';
2060 case JDWP::JT_DOUBLE: return 'D';
2061 case JDWP::JT_INT: return 'I';
2062 case JDWP::JT_LONG: return 'J';
2063 case JDWP::JT_SHORT: return 'S';
2064 case JDWP::JT_VOID: return 'V';
2065 case JDWP::JT_BOOLEAN: return 'Z';
2066
2067 // Reference types.
2068 case JDWP::JT_ARRAY:
2069 case JDWP::JT_OBJECT:
2070 case JDWP::JT_STRING:
2071 case JDWP::JT_THREAD:
2072 case JDWP::JT_THREAD_GROUP:
2073 case JDWP::JT_CLASS_LOADER:
2074 case JDWP::JT_CLASS_OBJECT:
2075 return 'L';
2076 }
2077}
2078
2079JDWP::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 -08002080 ThreadList* thread_list = Runtime::Current()->GetThreadList();
2081
2082 Thread* targetThread = NULL;
2083 DebugInvokeReq* req = NULL;
2084 {
2085 ScopedThreadListLock thread_list_lock;
2086 targetThread = DecodeThread(threadId);
2087 if (targetThread == NULL) {
2088 LOG(ERROR) << "InvokeMethod request for non-existent thread " << threadId;
2089 return JDWP::ERR_INVALID_THREAD;
2090 }
2091 req = targetThread->GetInvokeReq();
2092 if (!req->ready) {
2093 LOG(ERROR) << "InvokeMethod request for thread not stopped by event: " << *targetThread;
2094 return JDWP::ERR_INVALID_THREAD;
2095 }
2096
2097 /*
2098 * We currently have a bug where we don't successfully resume the
2099 * target thread if the suspend count is too deep. We're expected to
2100 * require one "resume" for each "suspend", but when asked to execute
2101 * a method we have to resume fully and then re-suspend it back to the
2102 * same level. (The easiest way to cause this is to type "suspend"
2103 * multiple times in jdb.)
2104 *
2105 * It's unclear what this means when the event specifies "resume all"
2106 * and some threads are suspended more deeply than others. This is
2107 * a rare problem, so for now we just prevent it from hanging forever
2108 * by rejecting the method invocation request. Without this, we will
2109 * be stuck waiting on a suspended thread.
2110 */
2111 int suspend_count = targetThread->GetSuspendCount();
2112 if (suspend_count > 1) {
2113 LOG(ERROR) << *targetThread << " suspend count too deep for method invocation: " << suspend_count;
2114 return JDWP::ERR_THREAD_SUSPENDED; // Probably not expected here.
2115 }
2116
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002117 JDWP::JdwpError status;
Elliott Hughes45651fd2012-02-21 15:48:20 -08002118 Object* receiver = gRegistry->Get<Object*>(objectId);
2119 if (receiver == kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002120 return JDWP::ERR_INVALID_OBJECT;
2121 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002122
2123 Object* thread = gRegistry->Get<Object*>(threadId);
2124 if (thread == kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002125 return JDWP::ERR_INVALID_OBJECT;
2126 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002127 // TODO: check that 'thread' is actually a java.lang.Thread!
2128
2129 Class* c = DecodeClass(classId, status);
2130 if (c == NULL) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002131 return status;
2132 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002133
2134 Method* m = FromMethodId(methodId);
2135 if (m->IsStatic() != (receiver == NULL)) {
2136 return JDWP::ERR_INVALID_METHODID;
2137 }
2138 if (m->IsStatic()) {
2139 if (m->GetDeclaringClass() != c) {
2140 return JDWP::ERR_INVALID_METHODID;
2141 }
2142 } else {
2143 if (!m->GetDeclaringClass()->IsAssignableFrom(c)) {
2144 return JDWP::ERR_INVALID_METHODID;
2145 }
2146 }
2147
2148 // Check the argument list matches the method.
2149 MethodHelper mh(m);
2150 if (mh.GetShortyLength() - 1 != arg_count) {
2151 return JDWP::ERR_ILLEGAL_ARGUMENT;
2152 }
2153 const char* shorty = mh.GetShorty();
2154 for (size_t i = 0; i < arg_count; ++i) {
2155 if (shorty[i + 1] != JdwpTagToShortyChar(arg_types[i])) {
2156 return JDWP::ERR_ILLEGAL_ARGUMENT;
2157 }
2158 }
2159
2160 req->receiver_ = receiver;
2161 req->thread_ = thread;
2162 req->class_ = c;
2163 req->method_ = m;
2164 req->arg_count_ = arg_count;
2165 req->arg_values_ = arg_values;
Elliott Hughesd07986f2011-12-06 18:27:45 -08002166 req->options_ = options;
2167 req->invoke_needed_ = true;
2168 }
2169
2170 // The fact that we've released the thread list lock is a bit risky --- if the thread goes
2171 // away we're sitting high and dry -- but we must release this before the ResumeAllThreads
2172 // call, and it's unwise to hold it during WaitForSuspend.
2173
2174 {
2175 /*
2176 * We change our (JDWP thread) status, which should be THREAD_RUNNING,
Elliott Hughes81ff3182012-03-23 20:35:56 -07002177 * so we can suspend for a GC if the invoke request causes us to
Elliott Hughesd07986f2011-12-06 18:27:45 -08002178 * run out of memory. It's also a good idea to change it before locking
2179 * the invokeReq mutex, although that should never be held for long.
2180 */
Elliott Hughes34e06962012-04-09 13:55:55 -07002181 ScopedThreadStateChange tsc(Thread::Current(), kVmWait);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002182
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002183 VLOG(jdwp) << " Transferring control to event thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002184 {
2185 MutexLock mu(req->lock_);
2186
2187 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002188 VLOG(jdwp) << " Resuming all threads";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002189 thread_list->ResumeAll(true);
2190 } else {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002191 VLOG(jdwp) << " Resuming event thread only";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002192 thread_list->Resume(targetThread, true);
2193 }
2194
2195 // Wait for the request to finish executing.
2196 while (req->invoke_needed_) {
2197 req->cond_.Wait(req->lock_);
2198 }
2199 }
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002200 VLOG(jdwp) << " Control has returned from event thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002201
2202 /* wait for thread to re-suspend itself */
2203 targetThread->WaitUntilSuspended();
2204 //dvmWaitForSuspend(targetThread);
2205 }
2206
2207 /*
2208 * Suspend the threads. We waited for the target thread to suspend
2209 * itself, so all we need to do is suspend the others.
2210 *
2211 * The suspendAllThreads() call will double-suspend the event thread,
2212 * so we want to resume the target thread once to keep the books straight.
2213 */
2214 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002215 VLOG(jdwp) << " Suspending all threads";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002216 thread_list->SuspendAll(true);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002217 VLOG(jdwp) << " Resuming event thread to balance the count";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002218 thread_list->Resume(targetThread, true);
2219 }
2220
2221 // Copy the result.
2222 *pResultTag = req->result_tag;
2223 if (IsPrimitiveTag(req->result_tag)) {
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002224 *pResultValue = req->result_value.GetJ();
Elliott Hughesd07986f2011-12-06 18:27:45 -08002225 } else {
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002226 *pResultValue = gRegistry->Add(req->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002227 }
2228 *pExceptionId = req->exception;
2229 return req->error;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002230}
2231
2232void Dbg::ExecuteMethod(DebugInvokeReq* pReq) {
Elliott Hughesd07986f2011-12-06 18:27:45 -08002233 Thread* self = Thread::Current();
2234
Elliott Hughes81ff3182012-03-23 20:35:56 -07002235 // We can be called while an exception is pending. We need
Elliott Hughesd07986f2011-12-06 18:27:45 -08002236 // to preserve that across the method invocation.
2237 SirtRef<Throwable> old_exception(self->GetException());
2238 self->ClearException();
2239
Elliott Hughes34e06962012-04-09 13:55:55 -07002240 ScopedThreadStateChange tsc(self, kRunnable);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002241
2242 // Translate the method through the vtable, unless the debugger wants to suppress it.
2243 Method* m = pReq->method_;
2244 if ((pReq->options_ & JDWP::INVOKE_NONVIRTUAL) == 0 && pReq->receiver_ != NULL) {
Elliott Hughes45651fd2012-02-21 15:48:20 -08002245 Method* actual_method = pReq->class_->FindVirtualMethodForVirtualOrInterface(pReq->method_);
2246 if (actual_method != m) {
2247 VLOG(jdwp) << "ExecuteMethod translated " << PrettyMethod(m) << " to " << PrettyMethod(actual_method);
2248 m = actual_method;
2249 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08002250 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002251 VLOG(jdwp) << "ExecuteMethod " << PrettyMethod(m);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002252 CHECK(m != NULL);
2253
2254 CHECK_EQ(sizeof(jvalue), sizeof(uint64_t));
2255
Elliott Hughes45651fd2012-02-21 15:48:20 -08002256 LOG(INFO) << "self=" << self << " pReq->receiver_=" << pReq->receiver_ << " m=" << m << " #" << pReq->arg_count_ << " " << pReq->arg_values_;
2257 pReq->result_value = InvokeWithJValues(self, pReq->receiver_, m, reinterpret_cast<JValue*>(pReq->arg_values_));
Elliott Hughesd07986f2011-12-06 18:27:45 -08002258
2259 pReq->exception = gRegistry->Add(self->GetException());
2260 pReq->result_tag = BasicTagFromDescriptor(MethodHelper(m).GetShorty());
2261 if (pReq->exception != 0) {
2262 Object* exc = self->GetException();
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002263 VLOG(jdwp) << " JDWP invocation returning with exception=" << exc << " " << PrettyTypeOf(exc);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002264 self->ClearException();
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002265 pReq->result_value.SetJ(0);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002266 } else if (pReq->result_tag == JDWP::JT_OBJECT) {
2267 /* if no exception thrown, examine object result more closely */
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002268 JDWP::JdwpTag new_tag = TagFromObject(pReq->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002269 if (new_tag != pReq->result_tag) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002270 VLOG(jdwp) << " JDWP promoted result from " << pReq->result_tag << " to " << new_tag;
Elliott Hughesd07986f2011-12-06 18:27:45 -08002271 pReq->result_tag = new_tag;
2272 }
2273
2274 /*
2275 * Register the object. We don't actually need an ObjectId yet,
2276 * but we do need to be sure that the GC won't move or discard the
2277 * object when we switch out of RUNNING. The ObjectId conversion
2278 * will add the object to the "do not touch" list.
2279 *
2280 * We can't use the "tracked allocation" mechanism here because
2281 * the object is going to be handed off to a different thread.
2282 */
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07002283 gRegistry->Add(pReq->result_value.GetL());
Elliott Hughesd07986f2011-12-06 18:27:45 -08002284 }
2285
2286 if (old_exception.get() != NULL) {
2287 self->SetException(old_exception.get());
2288 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002289}
2290
Elliott Hughesd07986f2011-12-06 18:27:45 -08002291/*
2292 * Register an object ID that might not have been registered previously.
2293 *
2294 * Normally this wouldn't happen -- the conversion to an ObjectId would
2295 * have added the object to the registry -- but in some cases (e.g.
2296 * throwing exceptions) we really want to do the registration late.
2297 */
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002298void Dbg::RegisterObjectId(JDWP::ObjectId id) {
Elliott Hughesd07986f2011-12-06 18:27:45 -08002299 gRegistry->Add(reinterpret_cast<Object*>(id));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002300}
2301
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002302/*
2303 * "buf" contains a full JDWP packet, possibly with multiple chunks. We
2304 * need to process each, accumulate the replies, and ship the whole thing
2305 * back.
2306 *
2307 * Returns "true" if we have a reply. The reply buffer is newly allocated,
2308 * and includes the chunk type/length, followed by the data.
2309 *
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08002310 * OLD-TODO: we currently assume that the request and reply include a single
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002311 * chunk. If this becomes inconvenient we will need to adapt.
2312 */
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002313bool Dbg::DdmHandlePacket(const uint8_t* buf, int dataLen, uint8_t** pReplyBuf, int* pReplyLen) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002314 CHECK_GE(dataLen, 0);
2315
2316 Thread* self = Thread::Current();
2317 JNIEnv* env = self->GetJniEnv();
2318
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002319 // Create a byte[] corresponding to 'buf'.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002320 ScopedLocalRef<jbyteArray> dataArray(env, env->NewByteArray(dataLen));
2321 if (dataArray.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002322 LOG(WARNING) << "byte[] allocation failed: " << dataLen;
2323 env->ExceptionClear();
2324 return false;
2325 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002326 env->SetByteArrayRegion(dataArray.get(), 0, dataLen, reinterpret_cast<const jbyte*>(buf));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002327
2328 const int kChunkHdrLen = 8;
2329
2330 // Run through and find all chunks. [Currently just find the first.]
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002331 ScopedByteArrayRO contents(env, dataArray.get());
Elliott Hughesf7c3b662011-10-27 12:04:56 -07002332 jint type = JDWP::Get4BE(reinterpret_cast<const uint8_t*>(&contents[0]));
2333 jint length = JDWP::Get4BE(reinterpret_cast<const uint8_t*>(&contents[4]));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002334 jint offset = kChunkHdrLen;
2335 if (offset + length > dataLen) {
2336 LOG(WARNING) << StringPrintf("bad chunk found (len=%u pktLen=%d)", length, dataLen);
2337 return false;
2338 }
2339
2340 // Call "private static Chunk dispatch(int type, byte[] data, int offset, int length)".
Elliott Hugheseac76672012-05-24 21:56:51 -07002341 ScopedLocalRef<jobject> chunk(env, env->CallStaticObjectMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
2342 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_dispatch,
2343 type, dataArray.get(), offset, length));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002344 if (env->ExceptionCheck()) {
2345 LOG(INFO) << StringPrintf("Exception thrown by dispatcher for 0x%08x", type);
2346 env->ExceptionDescribe();
2347 env->ExceptionClear();
2348 return false;
2349 }
2350
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002351 if (chunk.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002352 return false;
2353 }
2354
2355 /*
2356 * Pull the pieces out of the chunk. We copy the results into a
2357 * newly-allocated buffer that the caller can free. We don't want to
2358 * continue using the Chunk object because nothing has a reference to it.
2359 *
2360 * We could avoid this by returning type/data/offset/length and having
2361 * the caller be aware of the object lifetime issues, but that
Elliott Hughes81ff3182012-03-23 20:35:56 -07002362 * integrates the JDWP code more tightly into the rest of the runtime, and doesn't work
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002363 * if we have responses for multiple chunks.
2364 *
2365 * So we're pretty much stuck with copying data around multiple times.
2366 */
Elliott Hugheseac76672012-05-24 21:56:51 -07002367 ScopedLocalRef<jbyteArray> replyData(env, reinterpret_cast<jbyteArray>(env->GetObjectField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_data)));
2368 length = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_length);
2369 offset = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_offset);
2370 type = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_type);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002371
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002372 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 -07002373 if (length == 0 || replyData.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002374 return false;
2375 }
2376
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002377 jsize replyLength = env->GetArrayLength(replyData.get());
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002378 if (offset + length > replyLength) {
2379 LOG(WARNING) << StringPrintf("chunk off=%d len=%d exceeds reply array len %d", offset, length, replyLength);
2380 return false;
2381 }
2382
2383 uint8_t* reply = new uint8_t[length + kChunkHdrLen];
2384 if (reply == NULL) {
2385 LOG(WARNING) << "malloc failed: " << (length + kChunkHdrLen);
2386 return false;
2387 }
Elliott Hughesf7c3b662011-10-27 12:04:56 -07002388 JDWP::Set4BE(reply + 0, type);
2389 JDWP::Set4BE(reply + 4, length);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002390 env->GetByteArrayRegion(replyData.get(), offset, length, reinterpret_cast<jbyte*>(reply + kChunkHdrLen));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002391
2392 *pReplyBuf = reply;
2393 *pReplyLen = length + kChunkHdrLen;
2394
Elliott Hughesba8eee12012-01-24 20:25:24 -08002395 VLOG(jdwp) << StringPrintf("dvmHandleDdm returning type=%.4s buf=%p len=%d", reinterpret_cast<char*>(reply), reply, length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002396 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002397}
2398
Elliott Hughesa2155262011-11-16 16:26:58 -08002399void Dbg::DdmBroadcast(bool connect) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002400 VLOG(jdwp) << "Broadcasting DDM " << (connect ? "connect" : "disconnect") << "...";
Elliott Hughes47fce012011-10-25 18:37:19 -07002401
2402 Thread* self = Thread::Current();
Elliott Hughes34e06962012-04-09 13:55:55 -07002403 if (self->GetState() != kRunnable) {
Elliott Hughes47fce012011-10-25 18:37:19 -07002404 LOG(ERROR) << "DDM broadcast in thread state " << self->GetState();
2405 /* try anyway? */
2406 }
2407
2408 JNIEnv* env = self->GetJniEnv();
Elliott Hughes47fce012011-10-25 18:37:19 -07002409 jint event = connect ? 1 /*DdmServer.CONNECTED*/ : 2 /*DdmServer.DISCONNECTED*/;
Elliott Hugheseac76672012-05-24 21:56:51 -07002410 env->CallStaticVoidMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
2411 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_broadcast,
2412 event);
Elliott Hughes47fce012011-10-25 18:37:19 -07002413 if (env->ExceptionCheck()) {
2414 LOG(ERROR) << "DdmServer.broadcast " << event << " failed";
2415 env->ExceptionDescribe();
2416 env->ExceptionClear();
2417 }
2418}
2419
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002420void Dbg::DdmConnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08002421 Dbg::DdmBroadcast(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002422}
2423
2424void Dbg::DdmDisconnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08002425 Dbg::DdmBroadcast(false);
Elliott Hughes47fce012011-10-25 18:37:19 -07002426 gDdmThreadNotification = false;
2427}
2428
2429/*
Elliott Hughes82188472011-11-07 18:11:48 -08002430 * Send a notification when a thread starts, stops, or changes its name.
Elliott Hughes47fce012011-10-25 18:37:19 -07002431 *
2432 * Because we broadcast the full set of threads when the notifications are
2433 * first enabled, it's possible for "thread" to be actively executing.
2434 */
Elliott Hughes82188472011-11-07 18:11:48 -08002435void Dbg::DdmSendThreadNotification(Thread* t, uint32_t type) {
Elliott Hughes47fce012011-10-25 18:37:19 -07002436 if (!gDdmThreadNotification) {
2437 return;
2438 }
2439
Elliott Hughes82188472011-11-07 18:11:48 -08002440 if (type == CHUNK_TYPE("THDE")) {
Elliott Hughes47fce012011-10-25 18:37:19 -07002441 uint8_t buf[4];
Elliott Hughesf7c3b662011-10-27 12:04:56 -07002442 JDWP::Set4BE(&buf[0], t->GetThinLockId());
Elliott Hughes47fce012011-10-25 18:37:19 -07002443 Dbg::DdmSendChunk(CHUNK_TYPE("THDE"), 4, buf);
Elliott Hughes82188472011-11-07 18:11:48 -08002444 } else {
2445 CHECK(type == CHUNK_TYPE("THCR") || type == CHUNK_TYPE("THNM")) << type;
Elliott Hughes899e7892012-01-24 14:57:32 -08002446 SirtRef<String> name(t->GetThreadName());
Elliott Hughes82188472011-11-07 18:11:48 -08002447 size_t char_count = (name.get() != NULL) ? name->GetLength() : 0;
2448 const jchar* chars = name->GetCharArray()->GetData();
2449
Elliott Hughes21f32d72011-11-09 17:44:13 -08002450 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08002451 JDWP::Append4BE(bytes, t->GetThinLockId());
2452 JDWP::AppendUtf16BE(bytes, chars, char_count);
Elliott Hughes21f32d72011-11-09 17:44:13 -08002453 CHECK_EQ(bytes.size(), char_count*2 + sizeof(uint32_t)*2);
2454 Dbg::DdmSendChunk(type, bytes);
Elliott Hughes47fce012011-10-25 18:37:19 -07002455 }
2456}
2457
Elliott Hughesa2155262011-11-16 16:26:58 -08002458static void DdmSendThreadStartCallback(Thread* t, void*) {
Elliott Hughes82188472011-11-07 18:11:48 -08002459 Dbg::DdmSendThreadNotification(t, CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07002460}
2461
2462void Dbg::DdmSetThreadNotification(bool enable) {
2463 // We lock the thread list to avoid sending duplicate events or missing
2464 // a thread change. We should be okay holding this lock while sending
2465 // the messages out. (We have to hold it while accessing a live thread.)
Elliott Hughesbbd9d832011-11-07 14:40:00 -08002466 ScopedThreadListLock thread_list_lock;
Elliott Hughes47fce012011-10-25 18:37:19 -07002467
2468 gDdmThreadNotification = enable;
2469 if (enable) {
Elliott Hughesbfe487b2011-10-26 15:48:55 -07002470 Runtime::Current()->GetThreadList()->ForEach(DdmSendThreadStartCallback, NULL);
Elliott Hughes47fce012011-10-25 18:37:19 -07002471 }
2472}
2473
Elliott Hughesa2155262011-11-16 16:26:58 -08002474void Dbg::PostThreadStartOrStop(Thread* t, uint32_t type) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002475 if (IsDebuggerActive()) {
Elliott Hughes47fce012011-10-25 18:37:19 -07002476 JDWP::ObjectId id = gRegistry->Add(t->GetPeer());
Elliott Hughes82188472011-11-07 18:11:48 -08002477 gJdwpState->PostThreadChange(id, type == CHUNK_TYPE("THCR"));
Elliott Hughesc0f09332012-03-26 13:27:06 -07002478 // If this thread's just joined the party while we're already debugging, make sure it knows
2479 // to give us updates when it's running.
2480 t->SetDebuggerUpdatesEnabled(true);
Elliott Hughes47fce012011-10-25 18:37:19 -07002481 }
Elliott Hughes82188472011-11-07 18:11:48 -08002482 Dbg::DdmSendThreadNotification(t, type);
Elliott Hughes47fce012011-10-25 18:37:19 -07002483}
2484
2485void Dbg::PostThreadStart(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08002486 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07002487}
2488
2489void Dbg::PostThreadDeath(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08002490 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THDE"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002491}
2492
Elliott Hughes82188472011-11-07 18:11:48 -08002493void Dbg::DdmSendChunk(uint32_t type, size_t byte_count, const uint8_t* buf) {
Elliott Hughes3bb81562011-10-21 18:52:59 -07002494 CHECK(buf != NULL);
2495 iovec vec[1];
2496 vec[0].iov_base = reinterpret_cast<void*>(const_cast<uint8_t*>(buf));
2497 vec[0].iov_len = byte_count;
2498 Dbg::DdmSendChunkV(type, vec, 1);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002499}
2500
Elliott Hughes21f32d72011-11-09 17:44:13 -08002501void Dbg::DdmSendChunk(uint32_t type, const std::vector<uint8_t>& bytes) {
2502 DdmSendChunk(type, bytes.size(), &bytes[0]);
2503}
2504
Elliott Hughescccd84f2011-12-05 16:51:54 -08002505void Dbg::DdmSendChunkV(uint32_t type, const struct iovec* iov, int iov_count) {
Elliott Hughes3bb81562011-10-21 18:52:59 -07002506 if (gJdwpState == NULL) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002507 VLOG(jdwp) << "Debugger thread not active, ignoring DDM send: " << type;
Elliott Hughes3bb81562011-10-21 18:52:59 -07002508 } else {
Elliott Hughescccd84f2011-12-05 16:51:54 -08002509 gJdwpState->DdmSendChunkV(type, iov, iov_count);
Elliott Hughes3bb81562011-10-21 18:52:59 -07002510 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002511}
2512
Elliott Hughes767a1472011-10-26 18:49:02 -07002513int Dbg::DdmHandleHpifChunk(HpifWhen when) {
2514 if (when == HPIF_WHEN_NOW) {
Elliott Hughes7162ad92011-10-27 14:08:42 -07002515 DdmSendHeapInfo(when);
Elliott Hughes767a1472011-10-26 18:49:02 -07002516 return true;
2517 }
2518
2519 if (when != HPIF_WHEN_NEVER && when != HPIF_WHEN_NEXT_GC && when != HPIF_WHEN_EVERY_GC) {
2520 LOG(ERROR) << "invalid HpifWhen value: " << static_cast<int>(when);
2521 return false;
2522 }
2523
2524 gDdmHpifWhen = when;
2525 return true;
2526}
2527
2528bool Dbg::DdmHandleHpsgNhsgChunk(Dbg::HpsgWhen when, Dbg::HpsgWhat what, bool native) {
2529 if (when != HPSG_WHEN_NEVER && when != HPSG_WHEN_EVERY_GC) {
2530 LOG(ERROR) << "invalid HpsgWhen value: " << static_cast<int>(when);
2531 return false;
2532 }
2533
2534 if (what != HPSG_WHAT_MERGED_OBJECTS && what != HPSG_WHAT_DISTINCT_OBJECTS) {
2535 LOG(ERROR) << "invalid HpsgWhat value: " << static_cast<int>(what);
2536 return false;
2537 }
2538
2539 if (native) {
2540 gDdmNhsgWhen = when;
2541 gDdmNhsgWhat = what;
2542 } else {
2543 gDdmHpsgWhen = when;
2544 gDdmHpsgWhat = what;
2545 }
2546 return true;
2547}
2548
Elliott Hughes7162ad92011-10-27 14:08:42 -07002549void Dbg::DdmSendHeapInfo(HpifWhen reason) {
2550 // If there's a one-shot 'when', reset it.
2551 if (reason == gDdmHpifWhen) {
2552 if (gDdmHpifWhen == HPIF_WHEN_NEXT_GC) {
2553 gDdmHpifWhen = HPIF_WHEN_NEVER;
2554 }
2555 }
2556
2557 /*
2558 * Chunk HPIF (client --> server)
2559 *
2560 * Heap Info. General information about the heap,
2561 * suitable for a summary display.
2562 *
2563 * [u4]: number of heaps
2564 *
2565 * For each heap:
2566 * [u4]: heap ID
2567 * [u8]: timestamp in ms since Unix epoch
2568 * [u1]: capture reason (same as 'when' value from server)
2569 * [u4]: max heap size in bytes (-Xmx)
2570 * [u4]: current heap size in bytes
2571 * [u4]: current number of bytes allocated
2572 * [u4]: current number of objects allocated
2573 */
2574 uint8_t heap_count = 1;
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08002575 Heap* heap = Runtime::Current()->GetHeap();
Elliott Hughes21f32d72011-11-09 17:44:13 -08002576 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08002577 JDWP::Append4BE(bytes, heap_count);
2578 JDWP::Append4BE(bytes, 1); // Heap id (bogus; we only have one heap).
2579 JDWP::Append8BE(bytes, MilliTime());
2580 JDWP::Append1BE(bytes, reason);
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08002581 JDWP::Append4BE(bytes, heap->GetMaxMemory()); // Max allowed heap size in bytes.
2582 JDWP::Append4BE(bytes, heap->GetTotalMemory()); // Current heap size in bytes.
2583 JDWP::Append4BE(bytes, heap->GetBytesAllocated());
2584 JDWP::Append4BE(bytes, heap->GetObjectsAllocated());
Elliott Hughes21f32d72011-11-09 17:44:13 -08002585 CHECK_EQ(bytes.size(), 4U + (heap_count * (4 + 8 + 1 + 4 + 4 + 4 + 4)));
2586 Dbg::DdmSendChunk(CHUNK_TYPE("HPIF"), bytes);
Elliott Hughes767a1472011-10-26 18:49:02 -07002587}
2588
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002589enum HpsgSolidity {
2590 SOLIDITY_FREE = 0,
2591 SOLIDITY_HARD = 1,
2592 SOLIDITY_SOFT = 2,
2593 SOLIDITY_WEAK = 3,
2594 SOLIDITY_PHANTOM = 4,
2595 SOLIDITY_FINALIZABLE = 5,
2596 SOLIDITY_SWEEP = 6,
2597};
2598
2599enum HpsgKind {
2600 KIND_OBJECT = 0,
2601 KIND_CLASS_OBJECT = 1,
2602 KIND_ARRAY_1 = 2,
2603 KIND_ARRAY_2 = 3,
2604 KIND_ARRAY_4 = 4,
2605 KIND_ARRAY_8 = 5,
2606 KIND_UNKNOWN = 6,
2607 KIND_NATIVE = 7,
2608};
2609
2610#define HPSG_PARTIAL (1<<7)
2611#define HPSG_STATE(solidity, kind) ((uint8_t)((((kind) & 0x7) << 3) | ((solidity) & 0x7)))
2612
Ian Rogers30fab402012-01-23 15:43:46 -08002613class HeapChunkContext {
2614 public:
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002615 // Maximum chunk size. Obtain this from the formula:
2616 // (((maximum_heap_size / ALLOCATION_UNIT_SIZE) + 255) / 256) * 2
2617 HeapChunkContext(bool merge, bool native)
Ian Rogers30fab402012-01-23 15:43:46 -08002618 : buf_(16384 - 16),
2619 type_(0),
2620 merge_(merge) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002621 Reset();
2622 if (native) {
Ian Rogers30fab402012-01-23 15:43:46 -08002623 type_ = CHUNK_TYPE("NHSG");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002624 } else {
Ian Rogers30fab402012-01-23 15:43:46 -08002625 type_ = merge ? CHUNK_TYPE("HPSG") : CHUNK_TYPE("HPSO");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002626 }
2627 }
2628
2629 ~HeapChunkContext() {
Ian Rogers30fab402012-01-23 15:43:46 -08002630 if (p_ > &buf_[0]) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002631 Flush();
2632 }
2633 }
2634
2635 void EnsureHeader(const void* chunk_ptr) {
Ian Rogers30fab402012-01-23 15:43:46 -08002636 if (!needHeader_) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002637 return;
2638 }
2639
2640 // Start a new HPSx chunk.
Ian Rogers30fab402012-01-23 15:43:46 -08002641 JDWP::Write4BE(&p_, 1); // Heap id (bogus; we only have one heap).
2642 JDWP::Write1BE(&p_, 8); // Size of allocation unit, in bytes.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002643
Ian Rogers30fab402012-01-23 15:43:46 -08002644 JDWP::Write4BE(&p_, reinterpret_cast<uintptr_t>(chunk_ptr)); // virtual address of segment start.
2645 JDWP::Write4BE(&p_, 0); // offset of this piece (relative to the virtual address).
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002646 // [u4]: length of piece, in allocation units
2647 // 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 -08002648 pieceLenField_ = p_;
2649 JDWP::Write4BE(&p_, 0x55555555);
2650 needHeader_ = false;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002651 }
2652
2653 void Flush() {
2654 // Patch the "length of piece" field.
Ian Rogers30fab402012-01-23 15:43:46 -08002655 CHECK_LE(&buf_[0], pieceLenField_);
2656 CHECK_LE(pieceLenField_, p_);
2657 JDWP::Set4BE(pieceLenField_, totalAllocationUnits_);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002658
Ian Rogers30fab402012-01-23 15:43:46 -08002659 Dbg::DdmSendChunk(type_, p_ - &buf_[0], &buf_[0]);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002660 Reset();
2661 }
2662
Ian Rogers30fab402012-01-23 15:43:46 -08002663 static void HeapChunkCallback(void* start, void* end, size_t used_bytes, void* arg) {
2664 reinterpret_cast<HeapChunkContext*>(arg)->HeapChunkCallback(start, end, used_bytes);
Elliott Hughesa2155262011-11-16 16:26:58 -08002665 }
2666
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002667 private:
Elliott Hughesa2155262011-11-16 16:26:58 -08002668 enum { ALLOCATION_UNIT_SIZE = 8 };
2669
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002670 void Reset() {
Ian Rogers30fab402012-01-23 15:43:46 -08002671 p_ = &buf_[0];
2672 totalAllocationUnits_ = 0;
2673 needHeader_ = true;
2674 pieceLenField_ = NULL;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002675 }
2676
Elliott Hughes1bac54f2012-03-16 12:48:31 -07002677 void HeapChunkCallback(void* start, void* /*end*/, size_t used_bytes) {
Ian Rogers30fab402012-01-23 15:43:46 -08002678 // Note: heap call backs cannot manipulate the heap upon which they are crawling, care is taken
2679 // in the following code not to allocate memory, by ensuring buf_ is of the correct size
2680
Elliott Hughes741c9fa2012-06-08 15:51:32 -07002681 void* user_ptr = used_bytes > 0 ? start : NULL;
2682 size_t chunk_len = mspace_usable_size(user_ptr);
Ian Rogers30fab402012-01-23 15:43:46 -08002683
Elliott Hughes741c9fa2012-06-08 15:51:32 -07002684 // Make sure there's enough room left in the buffer.
2685 // We need to use two bytes for every fractional 256 allocation units used by the chunk.
Elliott Hughesa2155262011-11-16 16:26:58 -08002686 {
2687 size_t needed = (((chunk_len/ALLOCATION_UNIT_SIZE + 255) / 256) * 2);
Ian Rogers30fab402012-01-23 15:43:46 -08002688 size_t bytesLeft = buf_.size() - (size_t)(p_ - &buf_[0]);
Elliott Hughesa2155262011-11-16 16:26:58 -08002689 if (bytesLeft < needed) {
2690 Flush();
2691 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002692
Ian Rogers30fab402012-01-23 15:43:46 -08002693 bytesLeft = buf_.size() - (size_t)(p_ - &buf_[0]);
Elliott Hughesa2155262011-11-16 16:26:58 -08002694 if (bytesLeft < needed) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08002695 LOG(WARNING) << "Chunk is too big to transmit (chunk_len=" << chunk_len << ", " << needed << " bytes)";
Elliott Hughesa2155262011-11-16 16:26:58 -08002696 return;
2697 }
2698 }
2699
2700 // 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 -07002701 EnsureHeader(start);
Elliott Hughesa2155262011-11-16 16:26:58 -08002702
2703 // Determine the type of this chunk.
2704 // OLD-TODO: if context.merge, see if this chunk is different from the last chunk.
2705 // If it's the same, we should combine them.
Ian Rogers30fab402012-01-23 15:43:46 -08002706 uint8_t state = ExamineObject(reinterpret_cast<const Object*>(user_ptr), (type_ == CHUNK_TYPE("NHSG")));
Elliott Hughesa2155262011-11-16 16:26:58 -08002707
2708 // Write out the chunk description.
2709 chunk_len /= ALLOCATION_UNIT_SIZE; // convert to allocation units
Ian Rogers30fab402012-01-23 15:43:46 -08002710 totalAllocationUnits_ += chunk_len;
Elliott Hughesa2155262011-11-16 16:26:58 -08002711 while (chunk_len > 256) {
Ian Rogers30fab402012-01-23 15:43:46 -08002712 *p_++ = state | HPSG_PARTIAL;
2713 *p_++ = 255; // length - 1
Elliott Hughesa2155262011-11-16 16:26:58 -08002714 chunk_len -= 256;
2715 }
Ian Rogers30fab402012-01-23 15:43:46 -08002716 *p_++ = state;
2717 *p_++ = chunk_len - 1;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002718 }
2719
Elliott Hughesa2155262011-11-16 16:26:58 -08002720 uint8_t ExamineObject(const Object* o, bool is_native_heap) {
2721 if (o == NULL) {
2722 return HPSG_STATE(SOLIDITY_FREE, 0);
2723 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002724
Elliott Hughesa2155262011-11-16 16:26:58 -08002725 // It's an allocated chunk. Figure out what it is.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002726
Elliott Hughesa2155262011-11-16 16:26:58 -08002727 // If we're looking at the native heap, we'll just return
2728 // (SOLIDITY_HARD, KIND_NATIVE) for all allocated chunks.
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08002729 if (is_native_heap || !Runtime::Current()->GetHeap()->IsLiveObjectLocked(o)) {
Elliott Hughesa2155262011-11-16 16:26:58 -08002730 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
2731 }
2732
2733 Class* c = o->GetClass();
2734 if (c == NULL) {
2735 // The object was probably just created but hasn't been initialized yet.
2736 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
2737 }
2738
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08002739 if (!Runtime::Current()->GetHeap()->IsHeapAddress(c)) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08002740 LOG(WARNING) << "Invalid class for managed heap object: " << o << " " << c;
Elliott Hughesa2155262011-11-16 16:26:58 -08002741 return HPSG_STATE(SOLIDITY_HARD, KIND_UNKNOWN);
2742 }
2743
2744 if (c->IsClassClass()) {
2745 return HPSG_STATE(SOLIDITY_HARD, KIND_CLASS_OBJECT);
2746 }
2747
2748 if (c->IsArrayClass()) {
2749 if (o->IsObjectArray()) {
2750 return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
2751 }
2752 switch (c->GetComponentSize()) {
2753 case 1: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_1);
2754 case 2: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_2);
2755 case 4: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
2756 case 8: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_8);
2757 }
2758 }
2759
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002760 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
2761 }
2762
Ian Rogers30fab402012-01-23 15:43:46 -08002763 std::vector<uint8_t> buf_;
2764 uint8_t* p_;
2765 uint8_t* pieceLenField_;
2766 size_t totalAllocationUnits_;
2767 uint32_t type_;
2768 bool merge_;
2769 bool needHeader_;
2770
Elliott Hughesa2155262011-11-16 16:26:58 -08002771 DISALLOW_COPY_AND_ASSIGN(HeapChunkContext);
2772};
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002773
2774void Dbg::DdmSendHeapSegments(bool native) {
2775 Dbg::HpsgWhen when;
2776 Dbg::HpsgWhat what;
2777 if (!native) {
2778 when = gDdmHpsgWhen;
2779 what = gDdmHpsgWhat;
2780 } else {
2781 when = gDdmNhsgWhen;
2782 what = gDdmNhsgWhat;
2783 }
2784 if (when == HPSG_WHEN_NEVER) {
2785 return;
2786 }
2787
2788 // Figure out what kind of chunks we'll be sending.
2789 CHECK(what == HPSG_WHAT_MERGED_OBJECTS || what == HPSG_WHAT_DISTINCT_OBJECTS) << static_cast<int>(what);
2790
2791 // First, send a heap start chunk.
2792 uint8_t heap_id[4];
2793 JDWP::Set4BE(&heap_id[0], 1); // Heap id (bogus; we only have one heap).
2794 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHST") : CHUNK_TYPE("HPST"), sizeof(heap_id), heap_id);
2795
2796 // Send a series of heap segment chunks.
Elliott Hughesa2155262011-11-16 16:26:58 -08002797 HeapChunkContext context((what == HPSG_WHAT_MERGED_OBJECTS), native);
2798 if (native) {
Ian Rogers30fab402012-01-23 15:43:46 -08002799 // TODO: enable when bionic has moved to dlmalloc 2.8.5
2800 // dlmalloc_inspect_all(HeapChunkContext::HeapChunkCallback, &context);
2801 UNIMPLEMENTED(WARNING) << "Native heap send heap segments";
Elliott Hughesa2155262011-11-16 16:26:58 -08002802 } else {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08002803 Heap* heap = Runtime::Current()->GetHeap();
2804 heap->GetAllocSpace()->Walk(HeapChunkContext::HeapChunkCallback, &context);
Elliott Hughesa2155262011-11-16 16:26:58 -08002805 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002806
2807 // Finally, send a heap end chunk.
2808 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHEN") : CHUNK_TYPE("HPEN"), sizeof(heap_id), heap_id);
Elliott Hughes767a1472011-10-26 18:49:02 -07002809}
2810
Elliott Hughes545a0642011-11-08 19:10:03 -08002811void Dbg::SetAllocTrackingEnabled(bool enabled) {
2812 MutexLock mu(gAllocTrackerLock);
2813 if (enabled) {
2814 if (recent_allocation_records_ == NULL) {
2815 LOG(INFO) << "Enabling alloc tracker (" << kNumAllocRecords << " entries, "
2816 << kMaxAllocRecordStackDepth << " frames --> "
2817 << (sizeof(AllocRecord) * kNumAllocRecords) << " bytes)";
2818 gAllocRecordHead = gAllocRecordCount = 0;
2819 recent_allocation_records_ = new AllocRecord[kNumAllocRecords];
2820 CHECK(recent_allocation_records_ != NULL);
2821 }
2822 } else {
2823 delete[] recent_allocation_records_;
2824 recent_allocation_records_ = NULL;
2825 }
2826}
2827
2828struct AllocRecordStackVisitor : public Thread::StackVisitor {
Elliott Hughesba8eee12012-01-24 20:25:24 -08002829 explicit AllocRecordStackVisitor(AllocRecord* record) : record(record), depth(0) {
Elliott Hughes545a0642011-11-08 19:10:03 -08002830 }
2831
Elliott Hughes530fa002012-03-12 11:44:49 -07002832 bool VisitFrame(const Frame& f, uintptr_t pc) {
Elliott Hughes545a0642011-11-08 19:10:03 -08002833 if (depth >= kMaxAllocRecordStackDepth) {
Elliott Hughes530fa002012-03-12 11:44:49 -07002834 return false;
Elliott Hughes545a0642011-11-08 19:10:03 -08002835 }
Elliott Hughes530fa002012-03-12 11:44:49 -07002836 if (f.HasMethod()) {
2837 record->stack[depth].method = f.GetMethod();
2838 record->stack[depth].raw_pc = pc;
2839 ++depth;
Elliott Hughes545a0642011-11-08 19:10:03 -08002840 }
Elliott Hughes530fa002012-03-12 11:44:49 -07002841 return true;
Elliott Hughes545a0642011-11-08 19:10:03 -08002842 }
2843
2844 ~AllocRecordStackVisitor() {
2845 // Clear out any unused stack trace elements.
2846 for (; depth < kMaxAllocRecordStackDepth; ++depth) {
2847 record->stack[depth].method = NULL;
2848 record->stack[depth].raw_pc = 0;
2849 }
2850 }
2851
2852 AllocRecord* record;
2853 size_t depth;
2854};
2855
2856void Dbg::RecordAllocation(Class* type, size_t byte_count) {
2857 Thread* self = Thread::Current();
2858 CHECK(self != NULL);
2859
2860 MutexLock mu(gAllocTrackerLock);
2861 if (recent_allocation_records_ == NULL) {
2862 return;
2863 }
2864
2865 // Advance and clip.
2866 if (++gAllocRecordHead == kNumAllocRecords) {
2867 gAllocRecordHead = 0;
2868 }
2869
2870 // Fill in the basics.
2871 AllocRecord* record = &recent_allocation_records_[gAllocRecordHead];
2872 record->type = type;
2873 record->byte_count = byte_count;
2874 record->thin_lock_id = self->GetThinLockId();
2875
2876 // Fill in the stack trace.
2877 AllocRecordStackVisitor visitor(record);
2878 self->WalkStack(&visitor);
2879
2880 if (gAllocRecordCount < kNumAllocRecords) {
2881 ++gAllocRecordCount;
2882 }
2883}
2884
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07002885// Returns the index of the head element.
2886//
2887// We point at the most-recently-written record, so if gAllocRecordCount is 1
2888// we want to use the current element. Take "head+1" and subtract count
2889// from it.
2890//
2891// We need to handle underflow in our circular buffer, so we add
2892// kNumAllocRecords and then mask it back down.
2893static inline int HeadIndex() {
Elliott Hughes545a0642011-11-08 19:10:03 -08002894 return (gAllocRecordHead+1 + kNumAllocRecords - gAllocRecordCount) & (kNumAllocRecords-1);
2895}
2896
2897void Dbg::DumpRecentAllocations() {
2898 MutexLock mu(gAllocTrackerLock);
2899 if (recent_allocation_records_ == NULL) {
2900 LOG(INFO) << "Not recording tracked allocations";
2901 return;
2902 }
2903
2904 // "i" is the head of the list. We want to start at the end of the
2905 // list and move forward to the tail.
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07002906 size_t i = HeadIndex();
Elliott Hughes545a0642011-11-08 19:10:03 -08002907 size_t count = gAllocRecordCount;
2908
2909 LOG(INFO) << "Tracked allocations, (head=" << gAllocRecordHead << " count=" << count << ")";
2910 while (count--) {
2911 AllocRecord* record = &recent_allocation_records_[i];
2912
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07002913 LOG(INFO) << StringPrintf(" Thread %-2d %6zd bytes ", record->thin_lock_id, record->byte_count)
Elliott Hughes545a0642011-11-08 19:10:03 -08002914 << PrettyClass(record->type);
2915
2916 for (size_t stack_frame = 0; stack_frame < kMaxAllocRecordStackDepth; ++stack_frame) {
2917 const Method* m = record->stack[stack_frame].method;
2918 if (m == NULL) {
2919 break;
2920 }
2921 LOG(INFO) << " " << PrettyMethod(m) << " line " << record->stack[stack_frame].LineNumber();
2922 }
2923
2924 // pause periodically to help logcat catch up
2925 if ((count % 5) == 0) {
2926 usleep(40000);
2927 }
2928
2929 i = (i + 1) & (kNumAllocRecords-1);
2930 }
2931}
2932
2933class StringTable {
2934 public:
2935 StringTable() {
2936 }
2937
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002938 void Add(const char* s) {
Elliott Hughes545a0642011-11-08 19:10:03 -08002939 table_.insert(s);
2940 }
2941
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07002942 size_t IndexOf(const char* s) const {
2943 typedef std::set<std::string>::const_iterator It; // TODO: C++0x auto
2944 It it = table_.find(s);
2945 if (it == table_.end()) {
2946 LOG(FATAL) << "IndexOf(\"" << s << "\") failed";
2947 }
2948 return std::distance(table_.begin(), it);
Elliott Hughes545a0642011-11-08 19:10:03 -08002949 }
2950
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07002951 size_t Size() const {
Elliott Hughes545a0642011-11-08 19:10:03 -08002952 return table_.size();
2953 }
2954
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07002955 void WriteTo(std::vector<uint8_t>& bytes) const {
2956 typedef std::set<std::string>::const_iterator It; // TODO: C++0x auto
Elliott Hughes545a0642011-11-08 19:10:03 -08002957 for (It it = table_.begin(); it != table_.end(); ++it) {
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07002958 const char* s = (*it).c_str();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002959 size_t s_len = CountModifiedUtf8Chars(s);
2960 UniquePtr<uint16_t> s_utf16(new uint16_t[s_len]);
2961 ConvertModifiedUtf8ToUtf16(s_utf16.get(), s);
2962 JDWP::AppendUtf16BE(bytes, s_utf16.get(), s_len);
Elliott Hughes545a0642011-11-08 19:10:03 -08002963 }
2964 }
2965
2966 private:
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07002967 std::set<std::string> table_;
Elliott Hughes545a0642011-11-08 19:10:03 -08002968 DISALLOW_COPY_AND_ASSIGN(StringTable);
2969};
2970
2971/*
2972 * The data we send to DDMS contains everything we have recorded.
2973 *
2974 * Message header (all values big-endian):
2975 * (1b) message header len (to allow future expansion); includes itself
2976 * (1b) entry header len
2977 * (1b) stack frame len
2978 * (2b) number of entries
2979 * (4b) offset to string table from start of message
2980 * (2b) number of class name strings
2981 * (2b) number of method name strings
2982 * (2b) number of source file name strings
2983 * For each entry:
2984 * (4b) total allocation size
2985 * (2b) threadId
2986 * (2b) allocated object's class name index
2987 * (1b) stack depth
2988 * For each stack frame:
2989 * (2b) method's class name
2990 * (2b) method name
2991 * (2b) method source file
2992 * (2b) line number, clipped to 32767; -2 if native; -1 if no source
2993 * (xb) class name strings
2994 * (xb) method name strings
2995 * (xb) source file strings
2996 *
2997 * As with other DDM traffic, strings are sent as a 4-byte length
2998 * followed by UTF-16 data.
2999 *
3000 * We send up 16-bit unsigned indexes into string tables. In theory there
3001 * can be (kMaxAllocRecordStackDepth * kNumAllocRecords) unique strings in
3002 * each table, but in practice there should be far fewer.
3003 *
3004 * The chief reason for using a string table here is to keep the size of
3005 * the DDMS message to a minimum. This is partly to make the protocol
3006 * efficient, but also because we have to form the whole thing up all at
3007 * once in a memory buffer.
3008 *
3009 * We use separate string tables for class names, method names, and source
3010 * files to keep the indexes small. There will generally be no overlap
3011 * between the contents of these tables.
3012 */
3013jbyteArray Dbg::GetRecentAllocations() {
3014 if (false) {
3015 DumpRecentAllocations();
3016 }
3017
3018 MutexLock mu(gAllocTrackerLock);
3019
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003020 //
3021 // Part 1: generate string tables.
3022 //
Elliott Hughes545a0642011-11-08 19:10:03 -08003023 StringTable class_names;
3024 StringTable method_names;
3025 StringTable filenames;
3026
3027 int count = gAllocRecordCount;
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003028 int idx = HeadIndex();
Elliott Hughes545a0642011-11-08 19:10:03 -08003029 while (count--) {
3030 AllocRecord* record = &recent_allocation_records_[idx];
3031
Elliott Hughes91250e02011-12-13 22:30:35 -08003032 class_names.Add(ClassHelper(record->type).GetDescriptor());
Elliott Hughes545a0642011-11-08 19:10:03 -08003033
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003034 MethodHelper mh;
Elliott Hughes545a0642011-11-08 19:10:03 -08003035 for (size_t i = 0; i < kMaxAllocRecordStackDepth; i++) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003036 Method* m = record->stack[i].method;
Elliott Hughes545a0642011-11-08 19:10:03 -08003037 if (m != NULL) {
Ian Rogersba377812012-05-28 21:16:29 -07003038 mh.ChangeMethod(m);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003039 class_names.Add(mh.GetDeclaringClassDescriptor());
3040 method_names.Add(mh.GetName());
3041 filenames.Add(mh.GetDeclaringClassSourceFile());
Elliott Hughes545a0642011-11-08 19:10:03 -08003042 }
3043 }
3044
3045 idx = (idx + 1) & (kNumAllocRecords-1);
3046 }
3047
3048 LOG(INFO) << "allocation records: " << gAllocRecordCount;
3049
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003050 //
3051 // Part 2: allocate a buffer and generate the output.
3052 //
Elliott Hughes545a0642011-11-08 19:10:03 -08003053 std::vector<uint8_t> bytes;
3054
3055 // (1b) message header len (to allow future expansion); includes itself
3056 // (1b) entry header len
3057 // (1b) stack frame len
3058 const int kMessageHeaderLen = 15;
3059 const int kEntryHeaderLen = 9;
3060 const int kStackFrameLen = 8;
3061 JDWP::Append1BE(bytes, kMessageHeaderLen);
3062 JDWP::Append1BE(bytes, kEntryHeaderLen);
3063 JDWP::Append1BE(bytes, kStackFrameLen);
3064
3065 // (2b) number of entries
3066 // (4b) offset to string table from start of message
3067 // (2b) number of class name strings
3068 // (2b) number of method name strings
3069 // (2b) number of source file name strings
3070 JDWP::Append2BE(bytes, gAllocRecordCount);
3071 size_t string_table_offset = bytes.size();
3072 JDWP::Append4BE(bytes, 0); // We'll patch this later...
3073 JDWP::Append2BE(bytes, class_names.Size());
3074 JDWP::Append2BE(bytes, method_names.Size());
3075 JDWP::Append2BE(bytes, filenames.Size());
3076
3077 count = gAllocRecordCount;
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003078 idx = HeadIndex();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003079 ClassHelper kh;
Elliott Hughes545a0642011-11-08 19:10:03 -08003080 while (count--) {
3081 // For each entry:
3082 // (4b) total allocation size
3083 // (2b) thread id
3084 // (2b) allocated object's class name index
3085 // (1b) stack depth
3086 AllocRecord* record = &recent_allocation_records_[idx];
3087 size_t stack_depth = record->GetDepth();
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003088 kh.ChangeClass(record->type);
3089 size_t allocated_object_class_name_index = class_names.IndexOf(kh.GetDescriptor());
Elliott Hughes545a0642011-11-08 19:10:03 -08003090 JDWP::Append4BE(bytes, record->byte_count);
3091 JDWP::Append2BE(bytes, record->thin_lock_id);
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003092 JDWP::Append2BE(bytes, allocated_object_class_name_index);
Elliott Hughes545a0642011-11-08 19:10:03 -08003093 JDWP::Append1BE(bytes, stack_depth);
3094
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003095 MethodHelper mh;
Elliott Hughes545a0642011-11-08 19:10:03 -08003096 for (size_t stack_frame = 0; stack_frame < stack_depth; ++stack_frame) {
3097 // For each stack frame:
3098 // (2b) method's class name
3099 // (2b) method name
3100 // (2b) method source file
3101 // (2b) line number, clipped to 32767; -2 if native; -1 if no source
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003102 mh.ChangeMethod(record->stack[stack_frame].method);
Elliott Hughesa8f93cb2012-06-08 17:08:48 -07003103 size_t class_name_index = class_names.IndexOf(mh.GetDeclaringClassDescriptor());
3104 size_t method_name_index = method_names.IndexOf(mh.GetName());
3105 size_t file_name_index = filenames.IndexOf(mh.GetDeclaringClassSourceFile());
3106 JDWP::Append2BE(bytes, class_name_index);
3107 JDWP::Append2BE(bytes, method_name_index);
3108 JDWP::Append2BE(bytes, file_name_index);
Elliott Hughes545a0642011-11-08 19:10:03 -08003109 JDWP::Append2BE(bytes, record->stack[stack_frame].LineNumber());
3110 }
3111
3112 idx = (idx + 1) & (kNumAllocRecords-1);
3113 }
3114
3115 // (xb) class name strings
3116 // (xb) method name strings
3117 // (xb) source file strings
3118 JDWP::Set4BE(&bytes[string_table_offset], bytes.size());
3119 class_names.WriteTo(bytes);
3120 method_names.WriteTo(bytes);
3121 filenames.WriteTo(bytes);
3122
3123 JNIEnv* env = Thread::Current()->GetJniEnv();
3124 jbyteArray result = env->NewByteArray(bytes.size());
3125 if (result != NULL) {
3126 env->SetByteArrayRegion(result, 0, bytes.size(), reinterpret_cast<const jbyte*>(&bytes[0]));
3127 }
3128 return result;
3129}
3130
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003131} // namespace art