blob: 569ea8139da1c06525e876e5a1b037e068a2d5d3 [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"
Elliott Hughes86964332012-02-15 19:37:42 -080025#include "dex_verifier.h" // For Instruction.
Elliott Hughes68fdbd02011-11-29 19:22:47 -080026#include "context.h"
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080027#include "object_utils.h"
Elliott Hughes6a5bd492011-10-28 14:33:57 -070028#include "ScopedLocalRef.h"
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -070029#include "ScopedPrimitiveArray.h"
Elliott Hughes88c5c352012-03-15 18:49:48 -070030#include "scoped_thread_list_lock.h"
Ian Rogers30fab402012-01-23 15:43:46 -080031#include "space.h"
Elliott Hughes47fce012011-10-25 18:37:19 -070032#include "stack_indirect_reference_table.h"
Elliott Hughes475fc232011-10-25 15:00:35 -070033#include "thread_list.h"
34
Elliott Hughes6a5bd492011-10-28 14:33:57 -070035extern "C" void dlmalloc_walk_heap(void(*)(const void*, size_t, const void*, size_t, void*), void*);
36#ifndef HAVE_ANDROID_OS
37void dlmalloc_walk_heap(void(*)(const void*, size_t, const void*, size_t, void*), void*) {
38 // No-op for glibc.
39}
40#endif
41
Elliott Hughes872d4ec2011-10-21 17:07:15 -070042namespace art {
43
Elliott Hughes545a0642011-11-08 19:10:03 -080044static const size_t kMaxAllocRecordStackDepth = 16; // Max 255.
45static const size_t kNumAllocRecords = 512; // Must be power of 2.
46
Elliott Hughes436e3722012-02-17 20:01:47 -080047static const uintptr_t kInvalidId = 1;
48static const Object* kInvalidObject = reinterpret_cast<Object*>(kInvalidId);
49
Elliott Hughes475fc232011-10-25 15:00:35 -070050class ObjectRegistry {
51 public:
52 ObjectRegistry() : lock_("ObjectRegistry lock") {
53 }
54
55 JDWP::ObjectId Add(Object* o) {
56 if (o == NULL) {
57 return 0;
58 }
59 JDWP::ObjectId id = static_cast<JDWP::ObjectId>(reinterpret_cast<uintptr_t>(o));
60 MutexLock mu(lock_);
61 map_[id] = o;
62 return id;
63 }
64
Elliott Hughes234ab152011-10-26 14:02:26 -070065 void Clear() {
66 MutexLock mu(lock_);
67 LOG(DEBUG) << "Debugger has detached; object registry had " << map_.size() << " entries";
68 map_.clear();
69 }
70
Elliott Hughes475fc232011-10-25 15:00:35 -070071 bool Contains(JDWP::ObjectId id) {
72 MutexLock mu(lock_);
73 return map_.find(id) != map_.end();
74 }
75
Elliott Hughesa2155262011-11-16 16:26:58 -080076 template<typename T> T Get(JDWP::ObjectId id) {
Elliott Hughes436e3722012-02-17 20:01:47 -080077 if (id == 0) {
78 return NULL;
79 }
80
Elliott Hughesa2155262011-11-16 16:26:58 -080081 MutexLock mu(lock_);
82 typedef std::map<JDWP::ObjectId, Object*>::iterator It; // C++0x auto
83 It it = map_.find(id);
Elliott Hughes436e3722012-02-17 20:01:47 -080084 return (it != map_.end()) ? reinterpret_cast<T>(it->second) : reinterpret_cast<T>(kInvalidId);
Elliott Hughesa2155262011-11-16 16:26:58 -080085 }
86
Elliott Hughesbfe487b2011-10-26 15:48:55 -070087 void VisitRoots(Heap::RootVisitor* visitor, void* arg) {
88 MutexLock mu(lock_);
89 typedef std::map<JDWP::ObjectId, Object*>::iterator It; // C++0x auto
90 for (It it = map_.begin(); it != map_.end(); ++it) {
91 visitor(it->second, arg);
92 }
93 }
94
Elliott Hughes475fc232011-10-25 15:00:35 -070095 private:
96 Mutex lock_;
97 std::map<JDWP::ObjectId, Object*> map_;
98};
99
Elliott Hughes545a0642011-11-08 19:10:03 -0800100struct AllocRecordStackTraceElement {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800101 Method* method;
Elliott Hughes545a0642011-11-08 19:10:03 -0800102 uintptr_t raw_pc;
103
104 int32_t LineNumber() const {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800105 return MethodHelper(method).GetLineNumFromNativePC(raw_pc);
Elliott Hughes545a0642011-11-08 19:10:03 -0800106 }
107};
108
109struct AllocRecord {
110 Class* type;
111 size_t byte_count;
112 uint16_t thin_lock_id;
113 AllocRecordStackTraceElement stack[kMaxAllocRecordStackDepth]; // Unused entries have NULL method.
114
115 size_t GetDepth() {
116 size_t depth = 0;
117 while (depth < kMaxAllocRecordStackDepth && stack[depth].method != NULL) {
118 ++depth;
119 }
120 return depth;
121 }
122};
123
Elliott Hughes86964332012-02-15 19:37:42 -0800124struct Breakpoint {
125 Method* method;
Elliott Hughesa656a0f2012-02-21 18:03:44 -0800126 uint32_t dex_pc;
127 Breakpoint(Method* method, uint32_t dex_pc) : method(method), dex_pc(dex_pc) {}
Elliott Hughes86964332012-02-15 19:37:42 -0800128};
129
130static std::ostream& operator<<(std::ostream& os, const Breakpoint& rhs) {
Elliott Hughes229feb72012-02-23 13:33:29 -0800131 os << StringPrintf("Breakpoint[%s @%#x]", PrettyMethod(rhs.method).c_str(), rhs.dex_pc);
Elliott Hughes86964332012-02-15 19:37:42 -0800132 return os;
133}
134
135struct SingleStepControl {
136 // Are we single-stepping right now?
137 bool is_active;
138 Thread* thread;
139
140 JDWP::JdwpStepSize step_size;
141 JDWP::JdwpStepDepth step_depth;
142
143 const Method* method;
Elliott Hughes2435a572012-02-17 16:07:41 -0800144 int32_t line_number; // Or -1 for native methods.
145 std::set<uint32_t> dex_pcs;
Elliott Hughes86964332012-02-15 19:37:42 -0800146 int stack_depth;
147};
148
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700149// JDWP is allowed unless the Zygote forbids it.
150static bool gJdwpAllowed = true;
151
Elliott Hughesc0f09332012-03-26 13:27:06 -0700152// Was there a -Xrunjdwp or -agentlib:jdwp= argument on the command line?
Elliott Hughes3bb81562011-10-21 18:52:59 -0700153static bool gJdwpConfigured = false;
154
Elliott Hughesc0f09332012-03-26 13:27:06 -0700155// Broken-down JDWP options. (Only valid if IsJdwpConfigured() is true.)
Elliott Hughes376a7a02011-10-24 18:35:55 -0700156static JDWP::JdwpOptions gJdwpOptions;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700157
158// Runtime JDWP state.
159static JDWP::JdwpState* gJdwpState = NULL;
160static bool gDebuggerConnected; // debugger or DDMS is connected.
161static bool gDebuggerActive; // debugger is making requests.
Elliott Hughes86964332012-02-15 19:37:42 -0800162static bool gDisposed; // debugger called VirtualMachine.Dispose, so we should drop the connection.
Elliott Hughes3bb81562011-10-21 18:52:59 -0700163
Elliott Hughes47fce012011-10-25 18:37:19 -0700164static bool gDdmThreadNotification = false;
165
Elliott Hughes767a1472011-10-26 18:49:02 -0700166// DDMS GC-related settings.
167static Dbg::HpifWhen gDdmHpifWhen = Dbg::HPIF_WHEN_NEVER;
168static Dbg::HpsgWhen gDdmHpsgWhen = Dbg::HPSG_WHEN_NEVER;
169static Dbg::HpsgWhat gDdmHpsgWhat;
170static Dbg::HpsgWhen gDdmNhsgWhen = Dbg::HPSG_WHEN_NEVER;
171static Dbg::HpsgWhat gDdmNhsgWhat;
172
Elliott Hughes475fc232011-10-25 15:00:35 -0700173static ObjectRegistry* gRegistry = NULL;
174
Elliott Hughes545a0642011-11-08 19:10:03 -0800175// Recent allocation tracking.
176static Mutex gAllocTrackerLock("AllocTracker lock");
177AllocRecord* Dbg::recent_allocation_records_ = NULL; // TODO: CircularBuffer<AllocRecord>
178static size_t gAllocRecordHead = 0;
179static size_t gAllocRecordCount = 0;
180
Elliott Hughes86964332012-02-15 19:37:42 -0800181// Breakpoints and single-stepping.
182static Mutex gBreakpointsLock("breakpoints lock");
183static std::vector<Breakpoint> gBreakpoints;
184static SingleStepControl gSingleStepControl;
185
186static bool IsBreakpoint(Method* m, uint32_t dex_pc) {
187 MutexLock mu(gBreakpointsLock);
188 for (size_t i = 0; i < gBreakpoints.size(); ++i) {
Elliott Hughesa656a0f2012-02-21 18:03:44 -0800189 if (gBreakpoints[i].method == m && gBreakpoints[i].dex_pc == dex_pc) {
Elliott Hughes86964332012-02-15 19:37:42 -0800190 VLOG(jdwp) << "Hit breakpoint #" << i << ": " << gBreakpoints[i];
191 return true;
192 }
193 }
194 return false;
195}
196
Elliott Hughes436e3722012-02-17 20:01:47 -0800197static Array* DecodeArray(JDWP::RefTypeId id, JDWP::JdwpError& status) {
198 Object* o = gRegistry->Get<Object*>(id);
199 if (o == NULL || o == kInvalidObject) {
200 status = JDWP::ERR_INVALID_OBJECT;
201 return NULL;
202 }
203 if (!o->IsArrayInstance()) {
204 status = JDWP::ERR_INVALID_ARRAY;
205 return NULL;
206 }
207 status = JDWP::ERR_NONE;
208 return o->AsArray();
209}
210
211static Class* DecodeClass(JDWP::RefTypeId id, JDWP::JdwpError& status) {
212 Object* o = gRegistry->Get<Object*>(id);
213 if (o == NULL || o == kInvalidObject) {
214 status = JDWP::ERR_INVALID_OBJECT;
215 return NULL;
216 }
217 if (!o->IsClass()) {
218 status = JDWP::ERR_INVALID_CLASS;
219 return NULL;
220 }
221 status = JDWP::ERR_NONE;
222 return o->AsClass();
223}
224
225static Thread* DecodeThread(JDWP::ObjectId threadId) {
226 Object* thread_peer = gRegistry->Get<Object*>(threadId);
227 if (thread_peer == NULL || thread_peer == kInvalidObject) {
228 return NULL;
229 }
230 return Thread::FromManagedThread(thread_peer);
231}
232
Elliott Hughes24437992011-11-30 14:49:33 -0800233static JDWP::JdwpTag BasicTagFromDescriptor(const char* descriptor) {
234 // JDWP deliberately uses the descriptor characters' ASCII values for its enum.
235 // Note that by "basic" we mean that we don't get more specific than JT_OBJECT.
236 return static_cast<JDWP::JdwpTag>(descriptor[0]);
237}
238
239static JDWP::JdwpTag TagFromClass(Class* c) {
Elliott Hughes86b00102011-12-05 17:54:26 -0800240 CHECK(c != NULL);
Elliott Hughes24437992011-11-30 14:49:33 -0800241 if (c->IsArrayClass()) {
242 return JDWP::JT_ARRAY;
243 }
244
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800245 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Elliott Hughes24437992011-11-30 14:49:33 -0800246 if (c->IsStringClass()) {
247 return JDWP::JT_STRING;
248 } else if (c->IsClassClass()) {
249 return JDWP::JT_CLASS_OBJECT;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800250 } else if (class_linker->FindSystemClass("Ljava/lang/Thread;")->IsAssignableFrom(c)) {
Elliott Hughes24437992011-11-30 14:49:33 -0800251 return JDWP::JT_THREAD;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800252 } else if (class_linker->FindSystemClass("Ljava/lang/ThreadGroup;")->IsAssignableFrom(c)) {
Elliott Hughes24437992011-11-30 14:49:33 -0800253 return JDWP::JT_THREAD_GROUP;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800254 } else if (class_linker->FindSystemClass("Ljava/lang/ClassLoader;")->IsAssignableFrom(c)) {
Elliott Hughes24437992011-11-30 14:49:33 -0800255 return JDWP::JT_CLASS_LOADER;
Elliott Hughes24437992011-11-30 14:49:33 -0800256 } else {
257 return JDWP::JT_OBJECT;
258 }
259}
260
261/*
262 * Objects declared to hold Object might actually hold a more specific
263 * type. The debugger may take a special interest in these (e.g. it
264 * wants to display the contents of Strings), so we want to return an
265 * appropriate tag.
266 *
267 * Null objects are tagged JT_OBJECT.
268 */
269static JDWP::JdwpTag TagFromObject(const Object* o) {
270 return (o == NULL) ? JDWP::JT_OBJECT : TagFromClass(o->GetClass());
271}
272
273static bool IsPrimitiveTag(JDWP::JdwpTag tag) {
274 switch (tag) {
275 case JDWP::JT_BOOLEAN:
276 case JDWP::JT_BYTE:
277 case JDWP::JT_CHAR:
278 case JDWP::JT_FLOAT:
279 case JDWP::JT_DOUBLE:
280 case JDWP::JT_INT:
281 case JDWP::JT_LONG:
282 case JDWP::JT_SHORT:
283 case JDWP::JT_VOID:
284 return true;
285 default:
286 return false;
287 }
288}
289
Elliott Hughes3bb81562011-10-21 18:52:59 -0700290/*
291 * Handle one of the JDWP name/value pairs.
292 *
293 * JDWP options are:
294 * help: if specified, show help message and bail
295 * transport: may be dt_socket or dt_shmem
296 * address: for dt_socket, "host:port", or just "port" when listening
297 * server: if "y", wait for debugger to attach; if "n", attach to debugger
298 * timeout: how long to wait for debugger to connect / listen
299 *
300 * Useful with server=n (these aren't supported yet):
301 * onthrow=<exception-name>: connect to debugger when exception thrown
302 * onuncaught=y|n: connect to debugger when uncaught exception thrown
303 * launch=<command-line>: launch the debugger itself
304 *
305 * The "transport" option is required, as is "address" if server=n.
306 */
307static bool ParseJdwpOption(const std::string& name, const std::string& value) {
308 if (name == "transport") {
309 if (value == "dt_socket") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700310 gJdwpOptions.transport = JDWP::kJdwpTransportSocket;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700311 } else if (value == "dt_android_adb") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700312 gJdwpOptions.transport = JDWP::kJdwpTransportAndroidAdb;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700313 } else {
314 LOG(ERROR) << "JDWP transport not supported: " << value;
315 return false;
316 }
317 } else if (name == "server") {
318 if (value == "n") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700319 gJdwpOptions.server = false;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700320 } else if (value == "y") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700321 gJdwpOptions.server = true;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700322 } else {
323 LOG(ERROR) << "JDWP option 'server' must be 'y' or 'n'";
324 return false;
325 }
326 } else if (name == "suspend") {
327 if (value == "n") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700328 gJdwpOptions.suspend = false;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700329 } else if (value == "y") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700330 gJdwpOptions.suspend = true;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700331 } else {
332 LOG(ERROR) << "JDWP option 'suspend' must be 'y' or 'n'";
333 return false;
334 }
335 } else if (name == "address") {
336 /* this is either <port> or <host>:<port> */
337 std::string port_string;
Elliott Hughes376a7a02011-10-24 18:35:55 -0700338 gJdwpOptions.host.clear();
Elliott Hughes3bb81562011-10-21 18:52:59 -0700339 std::string::size_type colon = value.find(':');
340 if (colon != std::string::npos) {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700341 gJdwpOptions.host = value.substr(0, colon);
Elliott Hughes3bb81562011-10-21 18:52:59 -0700342 port_string = value.substr(colon + 1);
343 } else {
344 port_string = value;
345 }
346 if (port_string.empty()) {
347 LOG(ERROR) << "JDWP address missing port: " << value;
348 return false;
349 }
350 char* end;
Elliott Hughesba8eee12012-01-24 20:25:24 -0800351 uint64_t port = strtoul(port_string.c_str(), &end, 10);
352 if (*end != '\0' || port > 0xffff) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700353 LOG(ERROR) << "JDWP address has junk in port field: " << value;
354 return false;
355 }
Elliott Hughes376a7a02011-10-24 18:35:55 -0700356 gJdwpOptions.port = port;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700357 } else if (name == "launch" || name == "onthrow" || name == "oncaught" || name == "timeout") {
358 /* valid but unsupported */
359 LOG(INFO) << "Ignoring JDWP option '" << name << "'='" << value << "'";
360 } else {
361 LOG(INFO) << "Ignoring unrecognized JDWP option '" << name << "'='" << value << "'";
362 }
363
364 return true;
365}
366
367/*
368 * Parse the latter half of a -Xrunjdwp/-agentlib:jdwp= string, e.g.:
369 * "transport=dt_socket,address=8000,server=y,suspend=n"
370 */
371bool Dbg::ParseJdwpOptions(const std::string& options) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800372 VLOG(jdwp) << "ParseJdwpOptions: " << options;
Elliott Hughes47fce012011-10-25 18:37:19 -0700373
Elliott Hughes3bb81562011-10-21 18:52:59 -0700374 std::vector<std::string> pairs;
375 Split(options, ',', pairs);
376
377 for (size_t i = 0; i < pairs.size(); ++i) {
378 std::string::size_type equals = pairs[i].find('=');
379 if (equals == std::string::npos) {
380 LOG(ERROR) << "Can't parse JDWP option '" << pairs[i] << "' in '" << options << "'";
381 return false;
382 }
383 ParseJdwpOption(pairs[i].substr(0, equals), pairs[i].substr(equals + 1));
384 }
385
Elliott Hughes376a7a02011-10-24 18:35:55 -0700386 if (gJdwpOptions.transport == JDWP::kJdwpTransportUnknown) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700387 LOG(ERROR) << "Must specify JDWP transport: " << options;
388 }
Elliott Hughes376a7a02011-10-24 18:35:55 -0700389 if (!gJdwpOptions.server && (gJdwpOptions.host.empty() || gJdwpOptions.port == 0)) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700390 LOG(ERROR) << "Must specify JDWP host and port when server=n: " << options;
391 return false;
392 }
393
394 gJdwpConfigured = true;
395 return true;
396}
397
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700398void Dbg::StartJdwp() {
Elliott Hughesc0f09332012-03-26 13:27:06 -0700399 if (!gJdwpAllowed || !IsJdwpConfigured()) {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700400 // No JDWP for you!
401 return;
402 }
403
Elliott Hughes475fc232011-10-25 15:00:35 -0700404 CHECK(gRegistry == NULL);
405 gRegistry = new ObjectRegistry;
406
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700407 // Init JDWP if the debugger is enabled. This may connect out to a
408 // debugger, passively listen for a debugger, or block waiting for a
409 // debugger.
Elliott Hughes376a7a02011-10-24 18:35:55 -0700410 gJdwpState = JDWP::JdwpState::Create(&gJdwpOptions);
411 if (gJdwpState == NULL) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -0800412 // We probably failed because some other process has the port already, which means that
413 // if we don't abort the user is likely to think they're talking to us when they're actually
414 // talking to that other process.
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800415 LOG(FATAL) << "Debugger thread failed to initialize";
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700416 }
417
418 // If a debugger has already attached, send the "welcome" message.
419 // This may cause us to suspend all threads.
Elliott Hughes376a7a02011-10-24 18:35:55 -0700420 if (gJdwpState->IsActive()) {
Elliott Hughesa2155262011-11-16 16:26:58 -0800421 //ScopedThreadStateChange tsc(Thread::Current(), Thread::kRunnable);
Elliott Hughes376a7a02011-10-24 18:35:55 -0700422 if (!gJdwpState->PostVMStart()) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800423 LOG(WARNING) << "Failed to post 'start' message to debugger";
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700424 }
425 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700426}
427
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700428void Dbg::StopJdwp() {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700429 delete gJdwpState;
Elliott Hughes475fc232011-10-25 15:00:35 -0700430 delete gRegistry;
431 gRegistry = NULL;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700432}
433
Elliott Hughes767a1472011-10-26 18:49:02 -0700434void Dbg::GcDidFinish() {
435 if (gDdmHpifWhen != HPIF_WHEN_NEVER) {
Elliott Hughes81ff3182012-03-23 20:35:56 -0700436 LOG(DEBUG) << "Sending heap info to DDM";
Elliott Hughes7162ad92011-10-27 14:08:42 -0700437 DdmSendHeapInfo(gDdmHpifWhen);
Elliott Hughes767a1472011-10-26 18:49:02 -0700438 }
439 if (gDdmHpsgWhen != HPSG_WHEN_NEVER) {
Elliott Hughes81ff3182012-03-23 20:35:56 -0700440 LOG(DEBUG) << "Dumping heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700441 DdmSendHeapSegments(false);
Elliott Hughes767a1472011-10-26 18:49:02 -0700442 }
443 if (gDdmNhsgWhen != HPSG_WHEN_NEVER) {
444 LOG(DEBUG) << "Dumping native heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700445 DdmSendHeapSegments(true);
Elliott Hughes767a1472011-10-26 18:49:02 -0700446 }
447}
448
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700449void Dbg::SetJdwpAllowed(bool allowed) {
450 gJdwpAllowed = allowed;
451}
452
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700453DebugInvokeReq* Dbg::GetInvokeReq() {
Elliott Hughes475fc232011-10-25 15:00:35 -0700454 return Thread::Current()->GetInvokeReq();
455}
456
457Thread* Dbg::GetDebugThread() {
458 return (gJdwpState != NULL) ? gJdwpState->GetDebugThread() : NULL;
459}
460
461void Dbg::ClearWaitForEventThread() {
462 gJdwpState->ClearWaitForEventThread();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700463}
464
465void Dbg::Connected() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700466 CHECK(!gDebuggerConnected);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800467 VLOG(jdwp) << "JDWP has attached";
Elliott Hughes3bb81562011-10-21 18:52:59 -0700468 gDebuggerConnected = true;
Elliott Hughes86964332012-02-15 19:37:42 -0800469 gDisposed = false;
470}
471
472void Dbg::Disposed() {
473 gDisposed = true;
474}
475
476bool Dbg::IsDisposed() {
477 return gDisposed;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700478}
479
Elliott Hughesc0f09332012-03-26 13:27:06 -0700480static void SetDebuggerUpdatesEnabledCallback(Thread* t, void* user_data) {
481 t->SetDebuggerUpdatesEnabled(*reinterpret_cast<bool*>(user_data));
482}
483
484static void SetDebuggerUpdatesEnabled(bool enabled) {
485 Runtime* runtime = Runtime::Current();
486 ScopedThreadListLock thread_list_lock;
487 runtime->GetThreadList()->ForEach(SetDebuggerUpdatesEnabledCallback, &enabled);
488}
489
Elliott Hughesa2155262011-11-16 16:26:58 -0800490void Dbg::GoActive() {
491 // Enable all debugging features, including scans for breakpoints.
492 // This is a no-op if we're already active.
493 // Only called from the JDWP handler thread.
494 if (gDebuggerActive) {
495 return;
496 }
497
498 LOG(INFO) << "Debugger is active";
499
Elliott Hughesc0f09332012-03-26 13:27:06 -0700500 {
501 // TODO: dalvik only warned if there were breakpoints left over. clear in Dbg::Disconnected?
502 MutexLock mu(gBreakpointsLock);
503 CHECK_EQ(gBreakpoints.size(), 0U);
504 }
Elliott Hughesa2155262011-11-16 16:26:58 -0800505
506 gDebuggerActive = true;
Elliott Hughesc0f09332012-03-26 13:27:06 -0700507 SetDebuggerUpdatesEnabled(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700508}
509
510void Dbg::Disconnected() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700511 CHECK(gDebuggerConnected);
512
Elliott Hughesc0f09332012-03-26 13:27:06 -0700513 LOG(INFO) << "Debugger is no longer active";
Elliott Hughes234ab152011-10-26 14:02:26 -0700514
Elliott Hughesc0f09332012-03-26 13:27:06 -0700515 gDebuggerActive = false;
516 SetDebuggerUpdatesEnabled(false);
Elliott Hughes234ab152011-10-26 14:02:26 -0700517
518 gRegistry->Clear();
519 gDebuggerConnected = false;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700520}
521
Elliott Hughesc0f09332012-03-26 13:27:06 -0700522bool Dbg::IsDebuggerActive() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700523 return gDebuggerActive;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700524}
525
Elliott Hughesc0f09332012-03-26 13:27:06 -0700526bool Dbg::IsJdwpConfigured() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700527 return gJdwpConfigured;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700528}
529
530int64_t Dbg::LastDebuggerActivity() {
Elliott Hughesca951522011-12-05 12:01:32 -0800531 return gJdwpState->LastDebuggerActivity();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700532}
533
534int Dbg::ThreadRunning() {
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700535 return static_cast<int>(Thread::Current()->SetState(Thread::kRunnable));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700536}
537
538int Dbg::ThreadWaiting() {
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700539 return static_cast<int>(Thread::Current()->SetState(Thread::kVmWait));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700540}
541
Elliott Hughes6ba581a2011-10-25 11:45:35 -0700542int Dbg::ThreadContinuing(int new_state) {
543 return static_cast<int>(Thread::Current()->SetState(static_cast<Thread::State>(new_state)));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700544}
545
546void Dbg::UndoDebuggerSuspensions() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700547 Runtime::Current()->GetThreadList()->UndoDebuggerSuspensions();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700548}
549
550void Dbg::Exit(int status) {
Elliott Hughes1bba14f2011-12-01 18:00:36 -0800551 exit(status); // This is all dalvik did.
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700552}
553
Elliott Hughesbfe487b2011-10-26 15:48:55 -0700554void Dbg::VisitRoots(Heap::RootVisitor* visitor, void* arg) {
555 if (gRegistry != NULL) {
556 gRegistry->VisitRoots(visitor, arg);
557 }
558}
559
Elliott Hughesc308a5d2012-02-16 17:12:06 -0800560std::string Dbg::GetClassName(JDWP::RefTypeId classId) {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800561 Object* o = gRegistry->Get<Object*>(classId);
Elliott Hughes436e3722012-02-17 20:01:47 -0800562 if (o == NULL) {
563 return "NULL";
564 }
565 if (o == kInvalidObject) {
566 return StringPrintf("invalid object %p", reinterpret_cast<void*>(classId));
567 }
568 if (!o->IsClass()) {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800569 return StringPrintf("non-class %p", o); // This is only used for debugging output anyway.
570 }
Elliott Hughesc308a5d2012-02-16 17:12:06 -0800571 return DescriptorToName(ClassHelper(o->AsClass()).GetDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700572}
573
Elliott Hughes436e3722012-02-17 20:01:47 -0800574JDWP::JdwpError Dbg::GetClassObject(JDWP::RefTypeId id, JDWP::ObjectId& classObjectId) {
575 JDWP::JdwpError status;
576 Class* c = DecodeClass(id, status);
577 if (c == NULL) {
578 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800579 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800580 classObjectId = gRegistry->Add(c);
581 return JDWP::ERR_NONE;
Elliott Hughes86964332012-02-15 19:37:42 -0800582}
583
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800584JDWP::JdwpError Dbg::GetSuperclass(JDWP::RefTypeId id, JDWP::RefTypeId& superclassId) {
585 JDWP::JdwpError status;
586 Class* c = DecodeClass(id, status);
587 if (c == NULL) {
588 return status;
589 }
590 if (c->IsInterface()) {
591 // http://code.google.com/p/android/issues/detail?id=20856
592 superclassId = NULL;
593 } else {
594 superclassId = gRegistry->Add(c->GetSuperClass());
595 }
596 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700597}
598
Elliott Hughes436e3722012-02-17 20:01:47 -0800599JDWP::JdwpError Dbg::GetClassLoader(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) {
Elliott Hughes1bba14f2011-12-01 18:00:36 -0800600 Object* o = gRegistry->Get<Object*>(id);
Elliott Hughes436e3722012-02-17 20:01:47 -0800601 if (o == NULL || o == kInvalidObject) {
602 return JDWP::ERR_INVALID_OBJECT;
603 }
604 expandBufAddObjectId(pReply, gRegistry->Add(o->GetClass()->GetClassLoader()));
605 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700606}
607
Elliott Hughes436e3722012-02-17 20:01:47 -0800608JDWP::JdwpError Dbg::GetModifiers(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) {
609 JDWP::JdwpError status;
610 Class* c = DecodeClass(id, status);
611 if (c == NULL) {
612 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800613 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800614
615 uint32_t access_flags = c->GetAccessFlags() & kAccJavaFlagsMask;
616
617 // Set ACC_SUPER; dex files don't contain this flag, but all classes are supposed to have it set.
618 // Class.getModifiers doesn't return it, but JDWP does, so we set it here.
619 access_flags |= kAccSuper;
620
621 expandBufAdd4BE(pReply, access_flags);
622
623 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700624}
625
Elliott Hughes436e3722012-02-17 20:01:47 -0800626JDWP::JdwpError Dbg::GetReflectedType(JDWP::RefTypeId classId, JDWP::ExpandBuf* pReply) {
627 JDWP::JdwpError status;
628 Class* c = DecodeClass(classId, status);
629 if (c == NULL) {
630 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800631 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800632
633 expandBufAdd1(pReply, c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS);
634 expandBufAddRefTypeId(pReply, classId);
635 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700636}
637
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800638void Dbg::GetClassList(std::vector<JDWP::RefTypeId>& classes) {
Elliott Hughesa2155262011-11-16 16:26:58 -0800639 // Get the complete list of reference classes (i.e. all classes except
640 // the primitive types).
641 // Returns a newly-allocated buffer full of RefTypeId values.
642 struct ClassListCreator {
Elliott Hughesba8eee12012-01-24 20:25:24 -0800643 explicit ClassListCreator(std::vector<JDWP::RefTypeId>& classes) : classes(classes) {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800644 }
645
Elliott Hughesa2155262011-11-16 16:26:58 -0800646 static bool Visit(Class* c, void* arg) {
647 return reinterpret_cast<ClassListCreator*>(arg)->Visit(c);
648 }
649
650 bool Visit(Class* c) {
651 if (!c->IsPrimitive()) {
652 classes.push_back(static_cast<JDWP::RefTypeId>(gRegistry->Add(c)));
653 }
654 return true;
655 }
656
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800657 std::vector<JDWP::RefTypeId>& classes;
Elliott Hughesa2155262011-11-16 16:26:58 -0800658 };
659
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800660 ClassListCreator clc(classes);
Elliott Hughesa2155262011-11-16 16:26:58 -0800661 Runtime::Current()->GetClassLinker()->VisitClasses(ClassListCreator::Visit, &clc);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700662}
663
Elliott Hughes436e3722012-02-17 20:01:47 -0800664JDWP::JdwpError Dbg::GetClassInfo(JDWP::RefTypeId classId, JDWP::JdwpTypeTag* pTypeTag, uint32_t* pStatus, std::string* pDescriptor) {
665 JDWP::JdwpError status;
666 Class* c = DecodeClass(classId, status);
667 if (c == NULL) {
668 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800669 }
670
Elliott Hughesa2155262011-11-16 16:26:58 -0800671 if (c->IsArrayClass()) {
672 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
673 *pTypeTag = JDWP::TT_ARRAY;
674 } else {
675 if (c->IsErroneous()) {
676 *pStatus = JDWP::CS_ERROR;
677 } else {
678 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED | JDWP::CS_INITIALIZED;
679 }
680 *pTypeTag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
681 }
682
683 if (pDescriptor != NULL) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800684 *pDescriptor = ClassHelper(c).GetDescriptor();
Elliott Hughesa2155262011-11-16 16:26:58 -0800685 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800686 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700687}
688
Elliott Hughesc3b77c72011-12-15 20:56:48 -0800689void Dbg::FindLoadedClassBySignature(const char* descriptor, std::vector<JDWP::RefTypeId>& ids) {
Elliott Hughes6fa602d2011-12-02 17:54:25 -0800690 std::vector<Class*> classes;
691 Runtime::Current()->GetClassLinker()->LookupClasses(descriptor, classes);
692 ids.clear();
693 for (size_t i = 0; i < classes.size(); ++i) {
694 ids.push_back(gRegistry->Add(classes[i]));
695 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700696}
697
Elliott Hughes2435a572012-02-17 16:07:41 -0800698JDWP::JdwpError Dbg::GetReferenceType(JDWP::ObjectId objectId, JDWP::ExpandBuf* pReply) {
Elliott Hughes499c5132011-11-17 14:55:11 -0800699 Object* o = gRegistry->Get<Object*>(objectId);
Elliott Hughes436e3722012-02-17 20:01:47 -0800700 if (o == NULL || o == kInvalidObject) {
Elliott Hughes2435a572012-02-17 16:07:41 -0800701 return JDWP::ERR_INVALID_OBJECT;
Elliott Hughes499c5132011-11-17 14:55:11 -0800702 }
Elliott Hughes2435a572012-02-17 16:07:41 -0800703
704 JDWP::JdwpTypeTag type_tag;
705 if (o->GetClass()->IsArrayClass()) {
706 type_tag = JDWP::TT_ARRAY;
707 } else if (o->GetClass()->IsInterface()) {
708 type_tag = JDWP::TT_INTERFACE;
709 } else {
710 type_tag = JDWP::TT_CLASS;
711 }
712 JDWP::RefTypeId type_id = gRegistry->Add(o->GetClass());
713
714 expandBufAdd1(pReply, type_tag);
715 expandBufAddRefTypeId(pReply, type_id);
716
717 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700718}
719
Elliott Hughes436e3722012-02-17 20:01:47 -0800720JDWP::JdwpError Dbg::GetSignature(JDWP::RefTypeId classId, std::string& signature) {
Elliott Hughes1fe7afb2012-02-13 17:23:03 -0800721 JDWP::JdwpError status;
Elliott Hughes436e3722012-02-17 20:01:47 -0800722 Class* c = DecodeClass(classId, status);
Elliott Hughes1fe7afb2012-02-13 17:23:03 -0800723 if (c == NULL) {
724 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800725 }
Elliott Hughes1fe7afb2012-02-13 17:23:03 -0800726 signature = ClassHelper(c).GetDescriptor();
727 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700728}
729
Elliott Hughes436e3722012-02-17 20:01:47 -0800730JDWP::JdwpError Dbg::GetSourceFile(JDWP::RefTypeId classId, std::string& result) {
731 JDWP::JdwpError status;
732 Class* c = DecodeClass(classId, status);
733 if (c == NULL) {
734 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800735 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800736 result = ClassHelper(c).GetSourceFile();
737 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700738}
739
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700740uint8_t Dbg::GetObjectTag(JDWP::ObjectId objectId) {
Elliott Hughes24437992011-11-30 14:49:33 -0800741 Object* o = gRegistry->Get<Object*>(objectId);
742 return TagFromObject(o);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700743}
744
Elliott Hughesaed4be92011-12-02 16:16:23 -0800745size_t Dbg::GetTagWidth(JDWP::JdwpTag tag) {
Elliott Hughesdbb40792011-11-18 17:05:22 -0800746 switch (tag) {
747 case JDWP::JT_VOID:
748 return 0;
749 case JDWP::JT_BYTE:
750 case JDWP::JT_BOOLEAN:
751 return 1;
752 case JDWP::JT_CHAR:
753 case JDWP::JT_SHORT:
754 return 2;
755 case JDWP::JT_FLOAT:
756 case JDWP::JT_INT:
757 return 4;
758 case JDWP::JT_ARRAY:
759 case JDWP::JT_OBJECT:
760 case JDWP::JT_STRING:
761 case JDWP::JT_THREAD:
762 case JDWP::JT_THREAD_GROUP:
763 case JDWP::JT_CLASS_LOADER:
764 case JDWP::JT_CLASS_OBJECT:
765 return sizeof(JDWP::ObjectId);
766 case JDWP::JT_DOUBLE:
767 case JDWP::JT_LONG:
768 return 8;
769 default:
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800770 LOG(FATAL) << "Unknown tag " << tag;
Elliott Hughesdbb40792011-11-18 17:05:22 -0800771 return -1;
772 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700773}
774
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800775JDWP::JdwpError Dbg::GetArrayLength(JDWP::ObjectId arrayId, int& length) {
776 JDWP::JdwpError status;
777 Array* a = DecodeArray(arrayId, status);
778 if (a == NULL) {
779 return status;
Elliott Hughes24437992011-11-30 14:49:33 -0800780 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800781 length = a->GetLength();
782 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700783}
784
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800785JDWP::JdwpError Dbg::OutputArray(JDWP::ObjectId arrayId, int offset, int count, JDWP::ExpandBuf* pReply) {
786 JDWP::JdwpError status;
787 Array* a = DecodeArray(arrayId, status);
788 if (a == NULL) {
789 return status;
790 }
Elliott Hughes24437992011-11-30 14:49:33 -0800791
792 if (offset < 0 || count < 0 || offset > a->GetLength() || a->GetLength() - offset < count) {
793 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800794 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughes24437992011-11-30 14:49:33 -0800795 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800796 std::string descriptor(ClassHelper(a->GetClass()).GetDescriptor());
Elliott Hughes24437992011-11-30 14:49:33 -0800797 JDWP::JdwpTag tag = BasicTagFromDescriptor(descriptor.c_str() + 1);
798
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800799 expandBufAdd1(pReply, tag);
800 expandBufAdd4BE(pReply, count);
801
Elliott Hughes24437992011-11-30 14:49:33 -0800802 if (IsPrimitiveTag(tag)) {
803 size_t width = GetTagWidth(tag);
Elliott Hughes24437992011-11-30 14:49:33 -0800804 uint8_t* dst = expandBufAddSpace(pReply, count * width);
805 if (width == 8) {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800806 const uint64_t* src8 = reinterpret_cast<uint64_t*>(a->GetRawData(sizeof(uint64_t)));
Elliott Hughes24437992011-11-30 14:49:33 -0800807 for (int i = 0; i < count; ++i) JDWP::Write8BE(&dst, src8[offset + i]);
808 } else if (width == 4) {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800809 const uint32_t* src4 = reinterpret_cast<uint32_t*>(a->GetRawData(sizeof(uint32_t)));
Elliott Hughes24437992011-11-30 14:49:33 -0800810 for (int i = 0; i < count; ++i) JDWP::Write4BE(&dst, src4[offset + i]);
811 } else if (width == 2) {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800812 const uint16_t* src2 = reinterpret_cast<uint16_t*>(a->GetRawData(sizeof(uint16_t)));
Elliott Hughes24437992011-11-30 14:49:33 -0800813 for (int i = 0; i < count; ++i) JDWP::Write2BE(&dst, src2[offset + i]);
814 } else {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800815 const uint8_t* src = reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint8_t)));
Elliott Hughes24437992011-11-30 14:49:33 -0800816 memcpy(dst, &src[offset * width], count * width);
817 }
818 } else {
819 ObjectArray<Object>* oa = a->AsObjectArray<Object>();
820 for (int i = 0; i < count; ++i) {
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800821 Object* element = oa->Get(offset + i);
Elliott Hughes24437992011-11-30 14:49:33 -0800822 JDWP::JdwpTag specific_tag = (element != NULL) ? TagFromObject(element) : tag;
823 expandBufAdd1(pReply, specific_tag);
824 expandBufAddObjectId(pReply, gRegistry->Add(element));
825 }
826 }
827
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800828 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700829}
830
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800831JDWP::JdwpError Dbg::SetArrayElements(JDWP::ObjectId arrayId, int offset, int count, const uint8_t* src) {
832 JDWP::JdwpError status;
833 Array* a = DecodeArray(arrayId, status);
834 if (a == NULL) {
835 return status;
836 }
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800837
838 if (offset < 0 || count < 0 || offset > a->GetLength() || a->GetLength() - offset < count) {
839 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800840 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800841 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800842 std::string descriptor(ClassHelper(a->GetClass()).GetDescriptor());
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800843 JDWP::JdwpTag tag = BasicTagFromDescriptor(descriptor.c_str() + 1);
844
845 if (IsPrimitiveTag(tag)) {
846 size_t width = GetTagWidth(tag);
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800847 if (width == 8) {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800848 uint8_t* dst = &(reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint64_t)))[offset * width]);
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800849 for (int i = 0; i < count; ++i) {
850 // Handle potentially non-aligned memory access one byte at a time for ARM's benefit.
851 uint64_t value;
852 for (size_t j = 0; j < sizeof(uint64_t); ++j) reinterpret_cast<uint8_t*>(&value)[j] = src[j];
853 src += sizeof(uint64_t);
854 JDWP::Write8BE(&dst, value);
855 }
856 } else if (width == 4) {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800857 uint8_t* dst = &(reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint32_t)))[offset * width]);
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800858 const uint32_t* src4 = reinterpret_cast<const uint32_t*>(src);
859 for (int i = 0; i < count; ++i) JDWP::Write4BE(&dst, src4[i]);
860 } else if (width == 2) {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800861 uint8_t* dst = &(reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint16_t)))[offset * width]);
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800862 const uint16_t* src2 = reinterpret_cast<const uint16_t*>(src);
863 for (int i = 0; i < count; ++i) JDWP::Write2BE(&dst, src2[i]);
864 } else {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800865 uint8_t* dst = &(reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint8_t)))[offset * width]);
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800866 memcpy(&dst[offset * width], src, count * width);
867 }
868 } else {
869 ObjectArray<Object>* oa = a->AsObjectArray<Object>();
870 for (int i = 0; i < count; ++i) {
871 JDWP::ObjectId id = JDWP::ReadObjectId(&src);
Elliott Hughes436e3722012-02-17 20:01:47 -0800872 Object* o = gRegistry->Get<Object*>(id);
873 if (o == kInvalidObject) {
874 return JDWP::ERR_INVALID_OBJECT;
875 }
876 oa->Set(offset + i, o);
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800877 }
878 }
879
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800880 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700881}
882
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800883JDWP::ObjectId Dbg::CreateString(const std::string& str) {
884 return gRegistry->Add(String::AllocFromModifiedUtf8(str.c_str()));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700885}
886
Elliott Hughes436e3722012-02-17 20:01:47 -0800887JDWP::JdwpError Dbg::CreateObject(JDWP::RefTypeId classId, JDWP::ObjectId& new_object) {
888 JDWP::JdwpError status;
889 Class* c = DecodeClass(classId, status);
890 if (c == NULL) {
891 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800892 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800893 new_object = gRegistry->Add(c->AllocObject());
894 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700895}
896
Elliott Hughesbf13d362011-12-08 15:51:37 -0800897/*
898 * Used by Eclipse's "Display" view to evaluate "new byte[5]" to get "(byte[]) [0, 0, 0, 0, 0]".
899 */
Elliott Hughes436e3722012-02-17 20:01:47 -0800900JDWP::JdwpError Dbg::CreateArrayObject(JDWP::RefTypeId arrayClassId, uint32_t length, JDWP::ObjectId& new_array) {
901 JDWP::JdwpError status;
902 Class* c = DecodeClass(arrayClassId, status);
903 if (c == NULL) {
904 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800905 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800906 new_array = gRegistry->Add(Array::Alloc(c, length));
907 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700908}
909
910bool Dbg::MatchType(JDWP::RefTypeId instClassId, JDWP::RefTypeId classId) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800911 JDWP::JdwpError status;
912 Class* c1 = DecodeClass(instClassId, status);
Elliott Hughesa656a0f2012-02-21 18:03:44 -0800913 CHECK(c1 != NULL);
Elliott Hughes436e3722012-02-17 20:01:47 -0800914 Class* c2 = DecodeClass(classId, status);
Elliott Hughesa656a0f2012-02-21 18:03:44 -0800915 CHECK(c2 != NULL);
916 return c1->IsAssignableFrom(c2);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700917}
918
Elliott Hughes86964332012-02-15 19:37:42 -0800919static JDWP::FieldId ToFieldId(const Field* f) {
Elliott Hughes03181a82011-11-17 17:22:21 -0800920#ifdef MOVING_GARBAGE_COLLECTOR
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700921 UNIMPLEMENTED(FATAL);
Elliott Hughes03181a82011-11-17 17:22:21 -0800922#else
923 return static_cast<JDWP::FieldId>(reinterpret_cast<uintptr_t>(f));
924#endif
925}
926
Elliott Hughes86964332012-02-15 19:37:42 -0800927static JDWP::MethodId ToMethodId(const Method* m) {
Elliott Hughes03181a82011-11-17 17:22:21 -0800928#ifdef MOVING_GARBAGE_COLLECTOR
929 UNIMPLEMENTED(FATAL);
930#else
931 return static_cast<JDWP::MethodId>(reinterpret_cast<uintptr_t>(m));
932#endif
933}
934
Elliott Hughes86964332012-02-15 19:37:42 -0800935static Field* FromFieldId(JDWP::FieldId fid) {
Elliott Hughesaed4be92011-12-02 16:16:23 -0800936#ifdef MOVING_GARBAGE_COLLECTOR
937 UNIMPLEMENTED(FATAL);
938#else
939 return reinterpret_cast<Field*>(static_cast<uintptr_t>(fid));
940#endif
941}
942
Elliott Hughes86964332012-02-15 19:37:42 -0800943static Method* FromMethodId(JDWP::MethodId mid) {
Elliott Hughes03181a82011-11-17 17:22:21 -0800944#ifdef MOVING_GARBAGE_COLLECTOR
945 UNIMPLEMENTED(FATAL);
946#else
947 return reinterpret_cast<Method*>(static_cast<uintptr_t>(mid));
948#endif
949}
950
Elliott Hughes86964332012-02-15 19:37:42 -0800951static void SetLocation(JDWP::JdwpLocation& location, Method* m, uintptr_t native_pc) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -0800952 if (m == NULL) {
953 memset(&location, 0, sizeof(location));
954 } else {
955 Class* c = m->GetDeclaringClass();
956 location.typeTag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
957 location.classId = gRegistry->Add(c);
958 location.methodId = ToMethodId(m);
Elliott Hughes972a47b2012-02-21 18:16:06 -0800959 location.dex_pc = m->IsNative() ? -1 : m->ToDexPC(native_pc);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -0800960 }
Elliott Hughesd07986f2011-12-06 18:27:45 -0800961}
962
Elliott Hughes436e3722012-02-17 20:01:47 -0800963std::string Dbg::GetMethodName(JDWP::RefTypeId, JDWP::MethodId methodId) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800964 Method* m = FromMethodId(methodId);
965 return MethodHelper(m).GetName();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700966}
967
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800968/*
969 * Augment the access flags for synthetic methods and fields by setting
970 * the (as described by the spec) "0xf0000000 bit". Also, strip out any
971 * flags not specified by the Java programming language.
972 */
973static uint32_t MangleAccessFlags(uint32_t accessFlags) {
974 accessFlags &= kAccJavaFlagsMask;
975 if ((accessFlags & kAccSynthetic) != 0) {
976 accessFlags |= 0xf0000000;
977 }
978 return accessFlags;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700979}
980
Elliott Hughesdbb40792011-11-18 17:05:22 -0800981static const uint16_t kEclipseWorkaroundSlot = 1000;
982
983/*
984 * Eclipse appears to expect that the "this" reference is in slot zero.
985 * If it's not, the "variables" display will show two copies of "this",
986 * possibly because it gets "this" from SF.ThisObject and then displays
987 * all locals with nonzero slot numbers.
988 *
989 * So, we remap the item in slot 0 to 1000, and remap "this" to zero. On
990 * SF.GetValues / SF.SetValues we map them back.
Elliott Hughesc5b734a2011-12-01 17:20:58 -0800991 *
992 * TODO: jdb uses the value to determine whether a variable is a local or an argument,
993 * by checking whether it's less than the number of arguments. To make that work, we'd
994 * have to "mangle" all the arguments to come first, not just the implicit argument 'this'.
Elliott Hughesdbb40792011-11-18 17:05:22 -0800995 */
996static uint16_t MangleSlot(uint16_t slot, const char* name) {
997 uint16_t newSlot = slot;
998 if (strcmp(name, "this") == 0) {
999 newSlot = 0;
1000 } else if (slot == 0) {
1001 newSlot = kEclipseWorkaroundSlot;
1002 }
1003 return newSlot;
1004}
1005
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001006static uint16_t DemangleSlot(uint16_t slot, Method* m) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001007 if (slot == kEclipseWorkaroundSlot) {
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001008 return 0;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001009 } else if (slot == 0) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001010 const DexFile::CodeItem* code_item = MethodHelper(m).GetCodeItem();
1011 CHECK(code_item != NULL);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001012 return code_item->registers_size_ - code_item->ins_size_;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001013 }
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001014 return slot;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001015}
1016
Elliott Hughes436e3722012-02-17 20:01:47 -08001017JDWP::JdwpError Dbg::OutputDeclaredFields(JDWP::RefTypeId classId, bool with_generic, JDWP::ExpandBuf* pReply) {
1018 JDWP::JdwpError status;
1019 Class* c = DecodeClass(classId, status);
1020 if (c == NULL) {
1021 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001022 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001023
1024 size_t instance_field_count = c->NumInstanceFields();
1025 size_t static_field_count = c->NumStaticFields();
1026
1027 expandBufAdd4BE(pReply, instance_field_count + static_field_count);
1028
1029 for (size_t i = 0; i < instance_field_count + static_field_count; ++i) {
1030 Field* f = (i < instance_field_count) ? c->GetInstanceField(i) : c->GetStaticField(i - instance_field_count);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001031 FieldHelper fh(f);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001032 expandBufAddFieldId(pReply, ToFieldId(f));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001033 expandBufAddUtf8String(pReply, fh.GetName());
1034 expandBufAddUtf8String(pReply, fh.GetTypeDescriptor());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001035 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001036 static const char genericSignature[1] = "";
1037 expandBufAddUtf8String(pReply, genericSignature);
1038 }
1039 expandBufAdd4BE(pReply, MangleAccessFlags(f->GetAccessFlags()));
1040 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001041 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001042}
1043
Elliott Hughes436e3722012-02-17 20:01:47 -08001044JDWP::JdwpError Dbg::OutputDeclaredMethods(JDWP::RefTypeId classId, bool with_generic, JDWP::ExpandBuf* pReply) {
1045 JDWP::JdwpError status;
1046 Class* c = DecodeClass(classId, status);
1047 if (c == NULL) {
1048 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001049 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001050
1051 size_t direct_method_count = c->NumDirectMethods();
1052 size_t virtual_method_count = c->NumVirtualMethods();
1053
1054 expandBufAdd4BE(pReply, direct_method_count + virtual_method_count);
1055
1056 for (size_t i = 0; i < direct_method_count + virtual_method_count; ++i) {
1057 Method* m = (i < direct_method_count) ? c->GetDirectMethod(i) : c->GetVirtualMethod(i - direct_method_count);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001058 MethodHelper mh(m);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001059 expandBufAddMethodId(pReply, ToMethodId(m));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001060 expandBufAddUtf8String(pReply, mh.GetName());
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001061 expandBufAddUtf8String(pReply, mh.GetSignature());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001062 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001063 static const char genericSignature[1] = "";
1064 expandBufAddUtf8String(pReply, genericSignature);
1065 }
1066 expandBufAdd4BE(pReply, MangleAccessFlags(m->GetAccessFlags()));
1067 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001068 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001069}
1070
Elliott Hughes436e3722012-02-17 20:01:47 -08001071JDWP::JdwpError Dbg::OutputDeclaredInterfaces(JDWP::RefTypeId classId, JDWP::ExpandBuf* pReply) {
1072 JDWP::JdwpError status;
1073 Class* c = DecodeClass(classId, status);
1074 if (c == NULL) {
1075 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001076 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001077
1078 ClassHelper kh(c);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001079 size_t interface_count = kh.NumInterfaces();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001080 expandBufAdd4BE(pReply, interface_count);
1081 for (size_t i = 0; i < interface_count; ++i) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001082 expandBufAddRefTypeId(pReply, gRegistry->Add(kh.GetInterface(i)));
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001083 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001084 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001085}
1086
Elliott Hughes436e3722012-02-17 20:01:47 -08001087void Dbg::OutputLineTable(JDWP::RefTypeId, JDWP::MethodId methodId, JDWP::ExpandBuf* pReply) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001088 struct DebugCallbackContext {
1089 int numItems;
1090 JDWP::ExpandBuf* pReply;
1091
Elliott Hughes2435a572012-02-17 16:07:41 -08001092 static bool Callback(void* context, uint32_t address, uint32_t line_number) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001093 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
1094 expandBufAdd8BE(pContext->pReply, address);
Elliott Hughes2435a572012-02-17 16:07:41 -08001095 expandBufAdd4BE(pContext->pReply, line_number);
Elliott Hughes03181a82011-11-17 17:22:21 -08001096 pContext->numItems++;
1097 return true;
1098 }
1099 };
1100
1101 Method* m = FromMethodId(methodId);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001102 MethodHelper mh(m);
Elliott Hughes03181a82011-11-17 17:22:21 -08001103 uint64_t start, end;
1104 if (m->IsNative()) {
1105 start = -1;
1106 end = -1;
1107 } else {
1108 start = 0;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001109 // TODO: what are the units supposed to be? *2?
1110 end = mh.GetCodeItem()->insns_size_in_code_units_;
Elliott Hughes03181a82011-11-17 17:22:21 -08001111 }
1112
1113 expandBufAdd8BE(pReply, start);
1114 expandBufAdd8BE(pReply, end);
1115
1116 // Add numLines later
1117 size_t numLinesOffset = expandBufGetLength(pReply);
1118 expandBufAdd4BE(pReply, 0);
1119
1120 DebugCallbackContext context;
1121 context.numItems = 0;
1122 context.pReply = pReply;
1123
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001124 mh.GetDexFile().DecodeDebugInfo(mh.GetCodeItem(), m->IsStatic(), m->GetDexMethodIndex(),
1125 DebugCallbackContext::Callback, NULL, &context);
Elliott Hughes03181a82011-11-17 17:22:21 -08001126
1127 JDWP::Set4BE(expandBufGetBuffer(pReply) + numLinesOffset, context.numItems);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001128}
1129
Elliott Hughes436e3722012-02-17 20:01:47 -08001130void Dbg::OutputVariableTable(JDWP::RefTypeId, JDWP::MethodId methodId, bool with_generic, JDWP::ExpandBuf* pReply) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001131 struct DebugCallbackContext {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001132 JDWP::ExpandBuf* pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001133 size_t variable_count;
1134 bool with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001135
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001136 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 -08001137 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
1138
Elliott Hughesad3da692012-02-24 16:51:35 -08001139 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 -08001140
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001141 slot = MangleSlot(slot, name);
1142
Elliott Hughesdbb40792011-11-18 17:05:22 -08001143 expandBufAdd8BE(pContext->pReply, startAddress);
1144 expandBufAddUtf8String(pContext->pReply, name);
1145 expandBufAddUtf8String(pContext->pReply, descriptor);
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001146 if (pContext->with_generic) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001147 expandBufAddUtf8String(pContext->pReply, signature);
1148 }
1149 expandBufAdd4BE(pContext->pReply, endAddress - startAddress);
1150 expandBufAdd4BE(pContext->pReply, slot);
1151
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001152 ++pContext->variable_count;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001153 }
1154 };
1155
1156 Method* m = FromMethodId(methodId);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001157 MethodHelper mh(m);
1158 const DexFile::CodeItem* code_item = mh.GetCodeItem();
Elliott Hughesdbb40792011-11-18 17:05:22 -08001159
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001160 // arg_count considers doubles and longs to take 2 units.
1161 // variable_count considers everything to take 1 unit.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001162 std::string shorty(mh.GetShorty());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001163 expandBufAdd4BE(pReply, m->NumArgRegisters(shorty));
Elliott Hughesdbb40792011-11-18 17:05:22 -08001164
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001165 // We don't know the total number of variables yet, so leave a blank and update it later.
1166 size_t variable_count_offset = expandBufGetLength(pReply);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001167 expandBufAdd4BE(pReply, 0);
1168
1169 DebugCallbackContext context;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001170 context.pReply = pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001171 context.variable_count = 0;
1172 context.with_generic = with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001173
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001174 mh.GetDexFile().DecodeDebugInfo(code_item, m->IsStatic(), m->GetDexMethodIndex(), NULL,
1175 DebugCallbackContext::Callback, &context);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001176
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001177 JDWP::Set4BE(expandBufGetBuffer(pReply) + variable_count_offset, context.variable_count);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001178}
1179
Elliott Hughesaed4be92011-12-02 16:16:23 -08001180JDWP::JdwpTag Dbg::GetFieldBasicTag(JDWP::FieldId fieldId) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001181 return BasicTagFromDescriptor(FieldHelper(FromFieldId(fieldId)).GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001182}
1183
Elliott Hughesaed4be92011-12-02 16:16:23 -08001184JDWP::JdwpTag Dbg::GetStaticFieldBasicTag(JDWP::FieldId fieldId) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001185 return BasicTagFromDescriptor(FieldHelper(FromFieldId(fieldId)).GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001186}
1187
Elliott Hughes0cf74332012-02-23 23:14:00 -08001188static JDWP::JdwpError GetFieldValueImpl(JDWP::RefTypeId refTypeId, JDWP::ObjectId objectId, JDWP::FieldId fieldId, JDWP::ExpandBuf* pReply, bool is_static) {
1189 JDWP::JdwpError status;
1190 Class* c = DecodeClass(refTypeId, status);
1191 if (refTypeId != 0 && c == NULL) {
1192 return status;
1193 }
1194
Elliott Hughesaed4be92011-12-02 16:16:23 -08001195 Object* o = gRegistry->Get<Object*>(objectId);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001196 if ((!is_static && o == NULL) || o == kInvalidObject) {
1197 return JDWP::ERR_INVALID_OBJECT;
1198 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001199 Field* f = FromFieldId(fieldId);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001200
1201 Class* receiver_class = c;
1202 if (receiver_class == NULL && o != NULL) {
1203 receiver_class = o->GetClass();
1204 }
1205 // TODO: should we give up now if receiver_class is NULL?
1206 if (receiver_class != NULL && !f->GetDeclaringClass()->IsAssignableFrom(receiver_class)) {
1207 LOG(INFO) << "ERR_INVALID_FIELDID: " << PrettyField(f) << " " << PrettyClass(receiver_class);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001208 return JDWP::ERR_INVALID_FIELDID;
1209 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001210
Elliott Hughes0cf74332012-02-23 23:14:00 -08001211 // The RI only enforces the static/non-static mismatch in one direction.
1212 // TODO: should we change the tests and check both?
1213 if (is_static) {
1214 if (!f->IsStatic()) {
1215 return JDWP::ERR_INVALID_FIELDID;
1216 }
1217 } else {
1218 if (f->IsStatic()) {
1219 LOG(WARNING) << "Ignoring non-NULL receiver for ObjectReference.SetValues on static field " << PrettyField(f);
1220 o = NULL;
1221 }
1222 }
1223
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001224 JDWP::JdwpTag tag = BasicTagFromDescriptor(FieldHelper(f).GetTypeDescriptor());
Elliott Hughesaed4be92011-12-02 16:16:23 -08001225
1226 if (IsPrimitiveTag(tag)) {
1227 expandBufAdd1(pReply, tag);
1228 if (tag == JDWP::JT_BOOLEAN || tag == JDWP::JT_BYTE) {
1229 expandBufAdd1(pReply, f->Get32(o));
1230 } else if (tag == JDWP::JT_CHAR || tag == JDWP::JT_SHORT) {
1231 expandBufAdd2BE(pReply, f->Get32(o));
1232 } else if (tag == JDWP::JT_FLOAT || tag == JDWP::JT_INT) {
1233 expandBufAdd4BE(pReply, f->Get32(o));
1234 } else if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
1235 expandBufAdd8BE(pReply, f->Get64(o));
1236 } else {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001237 LOG(FATAL) << "Unknown tag: " << tag;
Elliott Hughesaed4be92011-12-02 16:16:23 -08001238 }
1239 } else {
1240 Object* value = f->GetObject(o);
1241 expandBufAdd1(pReply, TagFromObject(value));
1242 expandBufAddObjectId(pReply, gRegistry->Add(value));
1243 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001244 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001245}
1246
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001247JDWP::JdwpError Dbg::GetFieldValue(JDWP::ObjectId objectId, JDWP::FieldId fieldId, JDWP::ExpandBuf* pReply) {
Elliott Hughes0cf74332012-02-23 23:14:00 -08001248 return GetFieldValueImpl(0, objectId, fieldId, pReply, false);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001249}
1250
Elliott Hughes0cf74332012-02-23 23:14:00 -08001251JDWP::JdwpError Dbg::GetStaticFieldValue(JDWP::RefTypeId refTypeId, JDWP::FieldId fieldId, JDWP::ExpandBuf* pReply) {
1252 return GetFieldValueImpl(refTypeId, 0, fieldId, pReply, true);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001253}
1254
1255static JDWP::JdwpError SetFieldValueImpl(JDWP::ObjectId objectId, JDWP::FieldId fieldId, uint64_t value, int width, bool is_static) {
Elliott Hughesaed4be92011-12-02 16:16:23 -08001256 Object* o = gRegistry->Get<Object*>(objectId);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001257 if ((!is_static && o == NULL) || o == kInvalidObject) {
1258 return JDWP::ERR_INVALID_OBJECT;
1259 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001260 Field* f = FromFieldId(fieldId);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001261
1262 // The RI only enforces the static/non-static mismatch in one direction.
1263 // TODO: should we change the tests and check both?
1264 if (is_static) {
1265 if (!f->IsStatic()) {
1266 return JDWP::ERR_INVALID_FIELDID;
1267 }
1268 } else {
1269 if (f->IsStatic()) {
1270 LOG(WARNING) << "Ignoring non-NULL receiver for ObjectReference.SetValues on static field " << PrettyField(f);
1271 o = NULL;
1272 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001273 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001274
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001275 JDWP::JdwpTag tag = BasicTagFromDescriptor(FieldHelper(f).GetTypeDescriptor());
Elliott Hughesaed4be92011-12-02 16:16:23 -08001276
1277 if (IsPrimitiveTag(tag)) {
1278 if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001279 CHECK_EQ(width, 8);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001280 f->Set64(o, value);
1281 } else {
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001282 CHECK_LE(width, 4);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001283 f->Set32(o, value);
1284 }
1285 } else {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001286 Object* v = gRegistry->Get<Object*>(value);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001287 if (v == kInvalidObject) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001288 return JDWP::ERR_INVALID_OBJECT;
1289 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001290 if (v != NULL) {
1291 Class* field_type = FieldHelper(f).GetType();
1292 if (!field_type->IsAssignableFrom(v->GetClass())) {
1293 return JDWP::ERR_INVALID_OBJECT;
1294 }
1295 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001296 f->SetObject(o, v);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001297 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001298
1299 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001300}
1301
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001302JDWP::JdwpError Dbg::SetFieldValue(JDWP::ObjectId objectId, JDWP::FieldId fieldId, uint64_t value, int width) {
1303 return SetFieldValueImpl(objectId, fieldId, value, width, false);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001304}
1305
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001306JDWP::JdwpError Dbg::SetStaticFieldValue(JDWP::FieldId fieldId, uint64_t value, int width) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001307 return SetFieldValueImpl(0, fieldId, value, width, true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001308}
1309
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001310std::string Dbg::StringToUtf8(JDWP::ObjectId strId) {
1311 String* s = gRegistry->Get<String*>(strId);
1312 return s->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001313}
1314
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001315bool Dbg::GetThreadName(JDWP::ObjectId threadId, std::string& name) {
1316 ScopedThreadListLock thread_list_lock;
1317 Thread* thread = DecodeThread(threadId);
1318 if (thread == NULL) {
1319 return false;
1320 }
Elliott Hughesffb465f2012-03-01 18:46:05 -08001321 thread->GetThreadName(name);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001322 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001323}
1324
Elliott Hughes2435a572012-02-17 16:07:41 -08001325JDWP::JdwpError Dbg::GetThreadGroup(JDWP::ObjectId threadId, JDWP::ExpandBuf* pReply) {
Elliott Hughes499c5132011-11-17 14:55:11 -08001326 Object* thread = gRegistry->Get<Object*>(threadId);
Elliott Hughes436e3722012-02-17 20:01:47 -08001327 if (thread == kInvalidObject) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001328 return JDWP::ERR_INVALID_OBJECT;
1329 }
1330
1331 // Okay, so it's an object, but is it actually a thread?
Elliott Hughes436e3722012-02-17 20:01:47 -08001332 if (DecodeThread(threadId) == NULL) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001333 return JDWP::ERR_INVALID_THREAD;
1334 }
Elliott Hughes499c5132011-11-17 14:55:11 -08001335
1336 Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/Thread;");
1337 CHECK(c != NULL);
1338 Field* f = c->FindInstanceField("group", "Ljava/lang/ThreadGroup;");
1339 CHECK(f != NULL);
1340 Object* group = f->GetObject(thread);
1341 CHECK(group != NULL);
Elliott Hughes2435a572012-02-17 16:07:41 -08001342 JDWP::ObjectId thread_group_id = gRegistry->Add(group);
1343
1344 expandBufAddObjectId(pReply, thread_group_id);
1345 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001346}
1347
Elliott Hughes499c5132011-11-17 14:55:11 -08001348std::string Dbg::GetThreadGroupName(JDWP::ObjectId threadGroupId) {
1349 Object* thread_group = gRegistry->Get<Object*>(threadGroupId);
1350 CHECK(thread_group != NULL);
1351
1352 Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/ThreadGroup;");
1353 CHECK(c != NULL);
1354 Field* f = c->FindInstanceField("name", "Ljava/lang/String;");
1355 CHECK(f != NULL);
1356 String* s = reinterpret_cast<String*>(f->GetObject(thread_group));
1357 return s->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001358}
1359
1360JDWP::ObjectId Dbg::GetThreadGroupParent(JDWP::ObjectId threadGroupId) {
Elliott Hughes4e235312011-12-02 11:34:15 -08001361 Object* thread_group = gRegistry->Get<Object*>(threadGroupId);
1362 CHECK(thread_group != NULL);
1363
1364 Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/ThreadGroup;");
1365 CHECK(c != NULL);
1366 Field* f = c->FindInstanceField("parent", "Ljava/lang/ThreadGroup;");
1367 CHECK(f != NULL);
1368 Object* parent = f->GetObject(thread_group);
1369 return gRegistry->Add(parent);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001370}
1371
1372JDWP::ObjectId Dbg::GetSystemThreadGroupId() {
Elliott Hughes462c9442012-03-23 18:47:50 -07001373 return gRegistry->Add(Thread::GetSystemThreadGroup());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001374}
1375
1376JDWP::ObjectId Dbg::GetMainThreadGroupId() {
Elliott Hughes462c9442012-03-23 18:47:50 -07001377 return gRegistry->Add(Thread::GetMainThreadGroup());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001378}
1379
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001380bool Dbg::GetThreadStatus(JDWP::ObjectId threadId, JDWP::JdwpThreadStatus* pThreadStatus, JDWP::JdwpSuspendStatus* pSuspendStatus) {
Elliott Hughes499c5132011-11-17 14:55:11 -08001381 ScopedThreadListLock thread_list_lock;
1382
1383 Thread* thread = DecodeThread(threadId);
1384 if (thread == NULL) {
1385 return false;
1386 }
1387
Elliott Hughes3ce4b262012-02-24 11:24:02 -08001388 // TODO: if we're in Thread.sleep(long), we should return TS_SLEEPING,
1389 // even if it's implemented using Object.wait(long).
Elliott Hughes499c5132011-11-17 14:55:11 -08001390 switch (thread->GetState()) {
1391 case Thread::kTerminated: *pThreadStatus = JDWP::TS_ZOMBIE; break;
1392 case Thread::kRunnable: *pThreadStatus = JDWP::TS_RUNNING; break;
Elliott Hughes3ce4b262012-02-24 11:24:02 -08001393 case Thread::kTimedWaiting: *pThreadStatus = JDWP::TS_WAIT; break;
Elliott Hughes499c5132011-11-17 14:55:11 -08001394 case Thread::kBlocked: *pThreadStatus = JDWP::TS_MONITOR; break;
1395 case Thread::kWaiting: *pThreadStatus = JDWP::TS_WAIT; break;
Elliott Hughes499c5132011-11-17 14:55:11 -08001396 case Thread::kStarting: *pThreadStatus = JDWP::TS_ZOMBIE; break;
1397 case Thread::kNative: *pThreadStatus = JDWP::TS_RUNNING; break;
1398 case Thread::kVmWait: *pThreadStatus = JDWP::TS_WAIT; break;
1399 case Thread::kSuspended: *pThreadStatus = JDWP::TS_RUNNING; break;
1400 default:
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001401 LOG(FATAL) << "Unknown thread state " << thread->GetState();
Elliott Hughes499c5132011-11-17 14:55:11 -08001402 }
1403
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001404 *pSuspendStatus = (thread->IsSuspended() ? JDWP::SUSPEND_STATUS_SUSPENDED : JDWP::SUSPEND_STATUS_NOT_SUSPENDED);
Elliott Hughes499c5132011-11-17 14:55:11 -08001405
1406 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001407}
1408
Elliott Hughes2435a572012-02-17 16:07:41 -08001409JDWP::JdwpError Dbg::GetThreadSuspendCount(JDWP::ObjectId threadId, JDWP::ExpandBuf* pReply) {
1410 Thread* thread = DecodeThread(threadId);
1411 if (thread == NULL) {
1412 return JDWP::ERR_INVALID_THREAD;
1413 }
1414 expandBufAdd4BE(pReply, thread->GetSuspendCount());
1415 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001416}
1417
1418bool Dbg::ThreadExists(JDWP::ObjectId threadId) {
Elliott Hughes761928d2011-11-16 18:33:03 -08001419 return DecodeThread(threadId) != NULL;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001420}
1421
1422bool Dbg::IsSuspended(JDWP::ObjectId threadId) {
Elliott Hughes761928d2011-11-16 18:33:03 -08001423 return DecodeThread(threadId)->IsSuspended();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001424}
1425
Elliott Hughesa2155262011-11-16 16:26:58 -08001426void Dbg::GetThreadGroupThreadsImpl(Object* thread_group, JDWP::ObjectId** ppThreadIds, uint32_t* pThreadCount) {
1427 struct ThreadListVisitor {
1428 static void Visit(Thread* t, void* arg) {
1429 reinterpret_cast<ThreadListVisitor*>(arg)->Visit(t);
1430 }
1431
1432 void Visit(Thread* t) {
1433 if (t == Dbg::GetDebugThread()) {
1434 // Skip the JDWP thread. Some debuggers get bent out of shape when they can't suspend and
1435 // query all threads, so it's easier if we just don't tell them about this thread.
1436 return;
1437 }
1438 if (thread_group == NULL || t->GetThreadGroup() == thread_group) {
1439 threads.push_back(gRegistry->Add(t->GetPeer()));
1440 }
1441 }
1442
1443 Object* thread_group;
1444 std::vector<JDWP::ObjectId> threads;
1445 };
1446
1447 ThreadListVisitor tlv;
1448 tlv.thread_group = thread_group;
1449
1450 {
1451 ScopedThreadListLock thread_list_lock;
1452 Runtime::Current()->GetThreadList()->ForEach(ThreadListVisitor::Visit, &tlv);
1453 }
1454
1455 *pThreadCount = tlv.threads.size();
1456 if (*pThreadCount == 0) {
1457 *ppThreadIds = NULL;
1458 } else {
1459 *ppThreadIds = new JDWP::ObjectId[*pThreadCount];
1460 for (size_t i = 0; i < *pThreadCount; ++i) {
1461 (*ppThreadIds)[i] = tlv.threads[i];
1462 }
1463 }
1464}
1465
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001466void Dbg::GetThreadGroupThreads(JDWP::ObjectId threadGroupId, JDWP::ObjectId** ppThreadIds, uint32_t* pThreadCount) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001467 GetThreadGroupThreadsImpl(gRegistry->Get<Object*>(threadGroupId), ppThreadIds, pThreadCount);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001468}
1469
1470void Dbg::GetAllThreads(JDWP::ObjectId** ppThreadIds, uint32_t* pThreadCount) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001471 GetThreadGroupThreadsImpl(NULL, ppThreadIds, pThreadCount);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001472}
1473
Elliott Hughes86964332012-02-15 19:37:42 -08001474static int GetStackDepth(Thread* thread) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001475 struct CountStackDepthVisitor : public Thread::StackVisitor {
1476 CountStackDepthVisitor() : depth(0) {}
Elliott Hughes530fa002012-03-12 11:44:49 -07001477 bool VisitFrame(const Frame& f, uintptr_t) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -08001478 if (f.HasMethod()) {
1479 ++depth;
1480 }
Elliott Hughes530fa002012-03-12 11:44:49 -07001481 return true;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001482 }
1483 size_t depth;
1484 };
1485 CountStackDepthVisitor visitor;
Elliott Hughes86964332012-02-15 19:37:42 -08001486 thread->WalkStack(&visitor);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001487 return visitor.depth;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001488}
1489
Elliott Hughes86964332012-02-15 19:37:42 -08001490int Dbg::GetThreadFrameCount(JDWP::ObjectId threadId) {
1491 ScopedThreadListLock thread_list_lock;
1492 return GetStackDepth(DecodeThread(threadId));
1493}
1494
Elliott Hughes530fa002012-03-12 11:44:49 -07001495void Dbg::GetThreadFrame(JDWP::ObjectId threadId, int desired_frame_number, JDWP::FrameId* pFrameId, JDWP::JdwpLocation* pLoc) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001496 ScopedThreadListLock thread_list_lock;
1497 struct GetFrameVisitor : public Thread::StackVisitor {
1498 GetFrameVisitor(int desired_frame_number, JDWP::FrameId* pFrameId, JDWP::JdwpLocation* pLoc)
Elliott Hughes530fa002012-03-12 11:44:49 -07001499 : depth(0), desired_frame_number(desired_frame_number), pFrameId(pFrameId), pLoc(pLoc) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001500 }
Elliott Hughes530fa002012-03-12 11:44:49 -07001501 bool VisitFrame(const Frame& f, uintptr_t pc) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001502 if (!f.HasMethod()) {
Elliott Hughes530fa002012-03-12 11:44:49 -07001503 return true; // The debugger can't do anything useful with a frame that has no Method*.
Elliott Hughes03181a82011-11-17 17:22:21 -08001504 }
Elliott Hughes03181a82011-11-17 17:22:21 -08001505 if (depth == desired_frame_number) {
1506 *pFrameId = reinterpret_cast<JDWP::FrameId>(f.GetSP());
Elliott Hughesd07986f2011-12-06 18:27:45 -08001507 SetLocation(*pLoc, f.GetMethod(), pc);
Elliott Hughes530fa002012-03-12 11:44:49 -07001508 return false;
Elliott Hughes03181a82011-11-17 17:22:21 -08001509 }
1510 ++depth;
Elliott Hughes530fa002012-03-12 11:44:49 -07001511 return true;
Elliott Hughes03181a82011-11-17 17:22:21 -08001512 }
Elliott Hughes03181a82011-11-17 17:22:21 -08001513 int depth;
1514 int desired_frame_number;
1515 JDWP::FrameId* pFrameId;
1516 JDWP::JdwpLocation* pLoc;
1517 };
1518 GetFrameVisitor visitor(desired_frame_number, pFrameId, pLoc);
1519 visitor.desired_frame_number = desired_frame_number;
1520 DecodeThread(threadId)->WalkStack(&visitor);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001521}
1522
1523JDWP::ObjectId Dbg::GetThreadSelfId() {
Elliott Hughes475fc232011-10-25 15:00:35 -07001524 return gRegistry->Add(Thread::Current()->GetPeer());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001525}
1526
Elliott Hughes475fc232011-10-25 15:00:35 -07001527void Dbg::SuspendVM() {
Elliott Hughesa2155262011-11-16 16:26:58 -08001528 ScopedThreadStateChange tsc(Thread::Current(), Thread::kRunnable); // TODO: do we really want to change back? should the JDWP thread be Runnable usually?
Elliott Hughes475fc232011-10-25 15:00:35 -07001529 Runtime::Current()->GetThreadList()->SuspendAll(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001530}
1531
1532void Dbg::ResumeVM() {
Elliott Hughes475fc232011-10-25 15:00:35 -07001533 Runtime::Current()->GetThreadList()->ResumeAll(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001534}
1535
1536void Dbg::SuspendThread(JDWP::ObjectId threadId) {
Elliott Hughes4e235312011-12-02 11:34:15 -08001537 Object* peer = gRegistry->Get<Object*>(threadId);
1538 ScopedThreadListLock thread_list_lock;
1539 Thread* thread = Thread::FromManagedThread(peer);
1540 if (thread == NULL) {
1541 LOG(WARNING) << "No such thread for suspend: " << peer;
1542 return;
1543 }
1544 Runtime::Current()->GetThreadList()->Suspend(thread, true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001545}
1546
1547void Dbg::ResumeThread(JDWP::ObjectId threadId) {
Elliott Hughes4e235312011-12-02 11:34:15 -08001548 Object* peer = gRegistry->Get<Object*>(threadId);
1549 ScopedThreadListLock thread_list_lock;
1550 Thread* thread = Thread::FromManagedThread(peer);
1551 if (thread == NULL) {
1552 LOG(WARNING) << "No such thread for resume: " << peer;
1553 return;
1554 }
1555 Runtime::Current()->GetThreadList()->Resume(thread, true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001556}
1557
1558void Dbg::SuspendSelf() {
Elliott Hughes475fc232011-10-25 15:00:35 -07001559 Runtime::Current()->GetThreadList()->SuspendSelfForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001560}
1561
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001562static Object* GetThis(Frame& f) {
Elliott Hughes86b00102011-12-05 17:54:26 -08001563 Method* m = f.GetMethod();
Elliott Hughes86b00102011-12-05 17:54:26 -08001564 Object* o = NULL;
1565 if (!m->IsNative() && !m->IsStatic()) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001566 uint16_t reg = DemangleSlot(0, m);
Elliott Hughes86b00102011-12-05 17:54:26 -08001567 o = reinterpret_cast<Object*>(f.GetVReg(m, reg));
1568 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001569 return o;
1570}
1571
1572void Dbg::GetThisObject(JDWP::FrameId frameId, JDWP::ObjectId* pThisId) {
1573 Method** sp = reinterpret_cast<Method**>(frameId);
1574 Frame f(sp);
1575 Object* o = GetThis(f);
Elliott Hughes86b00102011-12-05 17:54:26 -08001576 *pThisId = gRegistry->Add(o);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001577}
1578
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001579void 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 -08001580 Method** sp = reinterpret_cast<Method**>(frameId);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001581 Frame f(sp);
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001582 Method* m = f.GetMethod();
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001583 uint16_t reg = DemangleSlot(slot, m);
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001584
1585 const VmapTable vmap_table(m->GetVmapTableRaw());
1586 uint32_t vmap_offset;
1587 if (vmap_table.IsInContext(reg, vmap_offset)) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001588 UNIMPLEMENTED(FATAL) << "Don't know how to pull locals from callee save frames: " << vmap_offset;
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001589 }
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
1682 const VmapTable vmap_table(m->GetVmapTableRaw());
1683 uint32_t vmap_offset;
1684 if (vmap_table.IsInContext(reg, vmap_offset)) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001685 UNIMPLEMENTED(FATAL) << "Don't know how to pull locals from callee save frames: " << vmap_offset;
Elliott Hughescccd84f2011-12-05 16:51:54 -08001686 }
1687
Elliott Hughesad3da692012-02-24 16:51:35 -08001688 // TODO: check that the tag is compatible with the actual type of the slot!
1689
Elliott Hughescccd84f2011-12-05 16:51:54 -08001690 switch (tag) {
1691 case JDWP::JT_BOOLEAN:
1692 case JDWP::JT_BYTE:
1693 CHECK_EQ(width, 1U);
1694 f.SetVReg(m, reg, static_cast<uint32_t>(value));
1695 break;
1696 case JDWP::JT_SHORT:
1697 case JDWP::JT_CHAR:
1698 CHECK_EQ(width, 2U);
1699 f.SetVReg(m, reg, static_cast<uint32_t>(value));
1700 break;
1701 case JDWP::JT_INT:
1702 case JDWP::JT_FLOAT:
1703 CHECK_EQ(width, 4U);
1704 f.SetVReg(m, reg, static_cast<uint32_t>(value));
1705 break;
1706 case JDWP::JT_ARRAY:
1707 case JDWP::JT_OBJECT:
1708 case JDWP::JT_STRING:
1709 {
1710 CHECK_EQ(width, sizeof(JDWP::ObjectId));
1711 Object* o = gRegistry->Get<Object*>(static_cast<JDWP::ObjectId>(value));
Elliott Hughesad3da692012-02-24 16:51:35 -08001712 if (o == kInvalidObject) {
1713 UNIMPLEMENTED(FATAL) << "return an error code when given an invalid object to store";
1714 }
Elliott Hughescccd84f2011-12-05 16:51:54 -08001715 f.SetVReg(m, reg, static_cast<uint32_t>(reinterpret_cast<uintptr_t>(o)));
1716 }
1717 break;
1718 case JDWP::JT_DOUBLE:
1719 case JDWP::JT_LONG:
1720 CHECK_EQ(width, 8U);
1721 f.SetVReg(m, reg, static_cast<uint32_t>(value));
1722 f.SetVReg(m, reg + 1, static_cast<uint32_t>(value >> 32));
1723 break;
1724 default:
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001725 LOG(FATAL) << "Unknown tag " << tag;
Elliott Hughescccd84f2011-12-05 16:51:54 -08001726 break;
1727 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001728}
1729
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001730void Dbg::PostLocationEvent(const Method* m, int dex_pc, Object* this_object, int event_flags) {
1731 Class* c = m->GetDeclaringClass();
1732
1733 JDWP::JdwpLocation location;
1734 location.typeTag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
1735 location.classId = gRegistry->Add(c);
1736 location.methodId = ToMethodId(m);
Elliott Hughes972a47b2012-02-21 18:16:06 -08001737 location.dex_pc = m->IsNative() ? -1 : dex_pc;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001738
1739 // Note we use "NoReg" so we don't keep track of references that are
1740 // never actually sent to the debugger. 'this_id' is only used to
1741 // compare against registered events...
1742 JDWP::ObjectId this_id = static_cast<JDWP::ObjectId>(reinterpret_cast<uintptr_t>(this_object));
1743 if (gJdwpState->PostLocationEvent(&location, this_id, event_flags)) {
1744 // ...unless there's a registered event, in which case we
1745 // need to really track the class and 'this'.
1746 gRegistry->Add(c);
1747 gRegistry->Add(this_object);
1748 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001749}
1750
Elliott Hughesd07986f2011-12-06 18:27:45 -08001751void Dbg::PostException(Method** sp, Method* throwMethod, uintptr_t throwNativePc, Method* catchMethod, uintptr_t catchNativePc, Object* exception) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07001752 if (!IsDebuggerActive()) {
Ian Rogers0ad5bb82011-12-07 10:16:32 -08001753 return;
1754 }
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001755
Elliott Hughesd07986f2011-12-06 18:27:45 -08001756 JDWP::JdwpLocation throw_location;
1757 SetLocation(throw_location, throwMethod, throwNativePc);
1758 JDWP::JdwpLocation catch_location;
1759 SetLocation(catch_location, catchMethod, catchNativePc);
1760
1761 // We need 'this' for InstanceOnly filters.
1762 JDWP::ObjectId this_id;
1763 GetThisObject(reinterpret_cast<JDWP::FrameId>(sp), &this_id);
1764
1765 /*
1766 * Hand the event to the JDWP exception handler. Note we're using the
1767 * "NoReg" objectID on the exception, which is not strictly correct --
1768 * the exception object WILL be passed up to the debugger if the
1769 * debugger is interested in the event. We do this because the current
1770 * implementation of the debugger object registry never throws anything
1771 * away, and some people were experiencing a fatal build up of exception
1772 * objects when dealing with certain libraries.
1773 */
1774 JDWP::ObjectId exception_id = static_cast<JDWP::ObjectId>(reinterpret_cast<uintptr_t>(exception));
1775 JDWP::RefTypeId exception_class_id = gRegistry->Add(exception->GetClass());
1776
1777 gJdwpState->PostException(&throw_location, exception_id, exception_class_id, &catch_location, this_id);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001778}
1779
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001780void Dbg::PostClassPrepare(Class* c) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07001781 if (!IsDebuggerActive()) {
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001782 return;
1783 }
1784
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001785 // OLD-TODO - we currently always send both "verified" and "prepared" since
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001786 // debuggers seem to like that. There might be some advantage to honesty,
1787 // since the class may not yet be verified.
1788 int state = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
1789 JDWP::JdwpTypeTag tag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
1790 gJdwpState->PostClassPrepare(tag, gRegistry->Add(c), ClassHelper(c).GetDescriptor(), state);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001791}
1792
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001793void Dbg::UpdateDebugger(int32_t dex_pc, Thread* self, Method** sp) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07001794 if (!IsDebuggerActive() || dex_pc == -2 /* fake method exit */) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001795 return;
1796 }
1797
Elliott Hughes86964332012-02-15 19:37:42 -08001798 Frame f(sp);
1799 f.Next(); // Skip callee save frame.
1800 Method* m = f.GetMethod();
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001801
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001802 if (dex_pc == -1) {
Elliott Hughes2aa2e392012-02-17 17:15:43 -08001803 // We use a pc of -1 to represent method entry, since we might branch back to pc 0 later.
1804 // This means that for this special notification, there can't be anything else interesting
1805 // going on, so we're done already.
1806 Dbg::PostLocationEvent(m, 0, GetThis(f), kMethodEntry);
1807 return;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001808 }
1809
Elliott Hughes2aa2e392012-02-17 17:15:43 -08001810 int event_flags = 0;
1811
Elliott Hughes86964332012-02-15 19:37:42 -08001812 if (IsBreakpoint(m, dex_pc)) {
1813 event_flags |= kBreakpoint;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001814 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001815
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001816 // If the debugger is single-stepping one of our threads, check to
1817 // see if we're that thread and we've reached a step point.
Elliott Hughes86964332012-02-15 19:37:42 -08001818 if (gSingleStepControl.is_active && gSingleStepControl.thread == self) {
1819 CHECK(!m->IsNative());
1820 if (gSingleStepControl.step_depth == JDWP::SD_INTO) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001821 // Step into method calls. We break when the line number
1822 // or method pointer changes. If we're in SS_MIN mode, we
1823 // always stop.
Elliott Hughes86964332012-02-15 19:37:42 -08001824 if (gSingleStepControl.method != m) {
1825 event_flags |= kSingleStep;
1826 VLOG(jdwp) << "SS new method";
1827 } else if (gSingleStepControl.step_size == JDWP::SS_MIN) {
1828 event_flags |= kSingleStep;
1829 VLOG(jdwp) << "SS new instruction";
Elliott Hughes2435a572012-02-17 16:07:41 -08001830 } else if (gSingleStepControl.dex_pcs.find(dex_pc) == gSingleStepControl.dex_pcs.end()) {
1831 event_flags |= kSingleStep;
1832 VLOG(jdwp) << "SS new line";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001833 }
Elliott Hughes86964332012-02-15 19:37:42 -08001834 } else if (gSingleStepControl.step_depth == JDWP::SD_OVER) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001835 // Step over method calls. We break when the line number is
1836 // different and the frame depth is <= the original frame
1837 // depth. (We can't just compare on the method, because we
1838 // might get unrolled past it by an exception, and it's tricky
1839 // to identify recursion.)
Elliott Hughes86964332012-02-15 19:37:42 -08001840
1841 // TODO: can we just use the value of 'sp'?
1842 int stack_depth = GetStackDepth(self);
1843
1844 if (stack_depth < gSingleStepControl.stack_depth) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001845 // popped up one or more frames, always trigger
Elliott Hughes86964332012-02-15 19:37:42 -08001846 event_flags |= kSingleStep;
1847 VLOG(jdwp) << "SS method pop";
1848 } else if (stack_depth == gSingleStepControl.stack_depth) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001849 // same depth, see if we moved
Elliott Hughes86964332012-02-15 19:37:42 -08001850 if (gSingleStepControl.step_size == JDWP::SS_MIN) {
1851 event_flags |= kSingleStep;
1852 VLOG(jdwp) << "SS new instruction";
Elliott Hughes2435a572012-02-17 16:07:41 -08001853 } else if (gSingleStepControl.dex_pcs.find(dex_pc) == gSingleStepControl.dex_pcs.end()) {
1854 event_flags |= kSingleStep;
1855 VLOG(jdwp) << "SS new line";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001856 }
1857 }
1858 } else {
Elliott Hughes86964332012-02-15 19:37:42 -08001859 CHECK_EQ(gSingleStepControl.step_depth, JDWP::SD_OUT);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001860 // Return from the current method. We break when the frame
1861 // depth pops up.
1862
1863 // This differs from the "method exit" break in that it stops
1864 // with the PC at the next instruction in the returned-to
1865 // function, rather than the end of the returning function.
Elliott Hughes86964332012-02-15 19:37:42 -08001866
1867 // TODO: can we just use the value of 'sp'?
1868 int stack_depth = GetStackDepth(self);
1869 if (stack_depth < gSingleStepControl.stack_depth) {
1870 event_flags |= kSingleStep;
1871 VLOG(jdwp) << "SS method pop";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001872 }
1873 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001874 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001875
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001876 // Check to see if this is a "return" instruction. JDWP says we should
1877 // send the event *after* the code has been executed, but it also says
1878 // the location we provide is the last instruction. Since the "return"
1879 // instruction has no interesting side effects, we should be safe.
1880 // (We can't just move this down to the returnFromMethod label because
1881 // we potentially need to combine it with other events.)
1882 // We're also not supposed to generate a method exit event if the method
1883 // terminates "with a thrown exception".
Elliott Hughes86964332012-02-15 19:37:42 -08001884 if (dex_pc >= 0) {
1885 const DexFile::CodeItem* code_item = MethodHelper(m).GetCodeItem();
1886 CHECK(code_item != NULL);
1887 CHECK_LT(dex_pc, static_cast<int32_t>(code_item->insns_size_in_code_units_));
1888 if (Instruction::At(&code_item->insns_[dex_pc])->IsReturn()) {
1889 event_flags |= kMethodExit;
1890 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001891 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001892
1893 // If there's something interesting going on, see if it matches one
1894 // of the debugger filters.
1895 if (event_flags != 0) {
Elliott Hughes86964332012-02-15 19:37:42 -08001896 Dbg::PostLocationEvent(m, dex_pc, GetThis(f), event_flags);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001897 }
1898}
1899
Elliott Hughes86964332012-02-15 19:37:42 -08001900void Dbg::WatchLocation(const JDWP::JdwpLocation* location) {
1901 MutexLock mu(gBreakpointsLock);
1902 Method* m = FromMethodId(location->methodId);
Elliott Hughes972a47b2012-02-21 18:16:06 -08001903 gBreakpoints.push_back(Breakpoint(m, location->dex_pc));
Elliott Hughes86964332012-02-15 19:37:42 -08001904 VLOG(jdwp) << "Set breakpoint #" << (gBreakpoints.size() - 1) << ": " << gBreakpoints[gBreakpoints.size() - 1];
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001905}
1906
Elliott Hughes86964332012-02-15 19:37:42 -08001907void Dbg::UnwatchLocation(const JDWP::JdwpLocation* location) {
1908 MutexLock mu(gBreakpointsLock);
1909 Method* m = FromMethodId(location->methodId);
1910 for (size_t i = 0; i < gBreakpoints.size(); ++i) {
Elliott Hughes972a47b2012-02-21 18:16:06 -08001911 if (gBreakpoints[i].method == m && gBreakpoints[i].dex_pc == location->dex_pc) {
Elliott Hughes86964332012-02-15 19:37:42 -08001912 VLOG(jdwp) << "Removed breakpoint #" << i << ": " << gBreakpoints[i];
1913 gBreakpoints.erase(gBreakpoints.begin() + i);
1914 return;
1915 }
1916 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001917}
1918
Elliott Hughes2435a572012-02-17 16:07:41 -08001919JDWP::JdwpError Dbg::ConfigureStep(JDWP::ObjectId threadId, JDWP::JdwpStepSize step_size, JDWP::JdwpStepDepth step_depth) {
Elliott Hughes86964332012-02-15 19:37:42 -08001920 Thread* thread = DecodeThread(threadId);
Elliott Hughes2435a572012-02-17 16:07:41 -08001921 if (thread == NULL) {
1922 return JDWP::ERR_INVALID_THREAD;
1923 }
Elliott Hughes86964332012-02-15 19:37:42 -08001924
1925 // TODO: there's no theoretical reason why we couldn't support single-stepping
1926 // of multiple threads at once, but we never did so historically.
1927 if (gSingleStepControl.thread != NULL && thread != gSingleStepControl.thread) {
1928 LOG(WARNING) << "single-step already active for " << *gSingleStepControl.thread
1929 << "; switching to " << *thread;
1930 }
1931
Elliott Hughes2435a572012-02-17 16:07:41 -08001932 //
1933 // Work out what Method* we're in, the current line number, and how deep the stack currently
1934 // is for step-out.
1935 //
1936
Elliott Hughes86964332012-02-15 19:37:42 -08001937 struct SingleStepStackVisitor : public Thread::StackVisitor {
1938 SingleStepStackVisitor() {
1939 gSingleStepControl.method = NULL;
1940 gSingleStepControl.stack_depth = 0;
1941 }
Elliott Hughes530fa002012-03-12 11:44:49 -07001942 bool VisitFrame(const Frame& f, uintptr_t pc) {
Elliott Hughes86964332012-02-15 19:37:42 -08001943 if (f.HasMethod()) {
1944 ++gSingleStepControl.stack_depth;
1945 if (gSingleStepControl.method == NULL) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001946 const Method* m = f.GetMethod();
1947 const DexCache* dex_cache = m->GetDeclaringClass()->GetDexCache();
1948 gSingleStepControl.method = m;
1949 gSingleStepControl.line_number = -1;
1950 if (dex_cache != NULL) {
1951 const DexFile& dex_file = Runtime::Current()->GetClassLinker()->FindDexFile(dex_cache);
1952 gSingleStepControl.line_number = dex_file.GetLineNumFromPC(m, m->ToDexPC(pc));
1953 }
Elliott Hughes86964332012-02-15 19:37:42 -08001954 }
1955 }
Elliott Hughes530fa002012-03-12 11:44:49 -07001956 return true;
Elliott Hughes86964332012-02-15 19:37:42 -08001957 }
1958 };
1959 SingleStepStackVisitor visitor;
1960 thread->WalkStack(&visitor);
1961
Elliott Hughes2435a572012-02-17 16:07:41 -08001962 //
1963 // Find the dex_pc values that correspond to the current line, for line-based single-stepping.
1964 //
1965
1966 struct DebugCallbackContext {
1967 DebugCallbackContext() {
1968 last_pc_valid = false;
1969 last_pc = 0;
Elliott Hughes2435a572012-02-17 16:07:41 -08001970 }
1971
1972 static bool Callback(void* raw_context, uint32_t address, uint32_t line_number) {
1973 DebugCallbackContext* context = reinterpret_cast<DebugCallbackContext*>(raw_context);
1974 if (static_cast<int32_t>(line_number) == gSingleStepControl.line_number) {
1975 if (!context->last_pc_valid) {
1976 // Everything from this address until the next line change is ours.
1977 context->last_pc = address;
1978 context->last_pc_valid = true;
1979 }
1980 // Otherwise, if we're already in a valid range for this line,
1981 // just keep going (shouldn't really happen)...
1982 } else if (context->last_pc_valid) { // and the line number is new
1983 // Add everything from the last entry up until here to the set
1984 for (uint32_t dex_pc = context->last_pc; dex_pc < address; ++dex_pc) {
1985 gSingleStepControl.dex_pcs.insert(dex_pc);
1986 }
1987 context->last_pc_valid = false;
1988 }
1989 return false; // There may be multiple entries for any given line.
1990 }
1991
1992 ~DebugCallbackContext() {
1993 // If the line number was the last in the position table...
1994 if (last_pc_valid) {
1995 size_t end = MethodHelper(gSingleStepControl.method).GetCodeItem()->insns_size_in_code_units_;
1996 for (uint32_t dex_pc = last_pc; dex_pc < end; ++dex_pc) {
1997 gSingleStepControl.dex_pcs.insert(dex_pc);
1998 }
1999 }
2000 }
2001
2002 bool last_pc_valid;
2003 uint32_t last_pc;
2004 };
Elliott Hughes3e2e1a22012-02-21 11:33:41 -08002005 gSingleStepControl.dex_pcs.clear();
Elliott Hughes2435a572012-02-17 16:07:41 -08002006 const Method* m = gSingleStepControl.method;
Elliott Hughes3e2e1a22012-02-21 11:33:41 -08002007 if (m->IsNative()) {
2008 gSingleStepControl.line_number = -1;
2009 } else {
2010 DebugCallbackContext context;
2011 MethodHelper mh(m);
2012 mh.GetDexFile().DecodeDebugInfo(mh.GetCodeItem(), m->IsStatic(), m->GetDexMethodIndex(),
2013 DebugCallbackContext::Callback, NULL, &context);
2014 }
Elliott Hughes2435a572012-02-17 16:07:41 -08002015
2016 //
2017 // Everything else...
2018 //
2019
Elliott Hughes86964332012-02-15 19:37:42 -08002020 gSingleStepControl.thread = thread;
2021 gSingleStepControl.step_size = step_size;
2022 gSingleStepControl.step_depth = step_depth;
2023 gSingleStepControl.is_active = true;
2024
Elliott Hughes2435a572012-02-17 16:07:41 -08002025 if (VLOG_IS_ON(jdwp)) {
2026 VLOG(jdwp) << "Single-step thread: " << *gSingleStepControl.thread;
2027 VLOG(jdwp) << "Single-step step size: " << gSingleStepControl.step_size;
2028 VLOG(jdwp) << "Single-step step depth: " << gSingleStepControl.step_depth;
2029 VLOG(jdwp) << "Single-step current method: " << PrettyMethod(gSingleStepControl.method);
2030 VLOG(jdwp) << "Single-step current line: " << gSingleStepControl.line_number;
2031 VLOG(jdwp) << "Single-step current stack depth: " << gSingleStepControl.stack_depth;
2032 VLOG(jdwp) << "Single-step dex_pc values:";
2033 for (std::set<uint32_t>::iterator it = gSingleStepControl.dex_pcs.begin() ; it != gSingleStepControl.dex_pcs.end(); ++it) {
Elliott Hughes229feb72012-02-23 13:33:29 -08002034 VLOG(jdwp) << StringPrintf(" %#x", *it);
Elliott Hughes2435a572012-02-17 16:07:41 -08002035 }
2036 }
2037
2038 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002039}
2040
Elliott Hughes1bac54f2012-03-16 12:48:31 -07002041void Dbg::UnconfigureStep(JDWP::ObjectId /*threadId*/) {
Elliott Hughes86964332012-02-15 19:37:42 -08002042 gSingleStepControl.is_active = false;
2043 gSingleStepControl.thread = NULL;
Elliott Hughes2435a572012-02-17 16:07:41 -08002044 gSingleStepControl.dex_pcs.clear();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002045}
2046
Elliott Hughes45651fd2012-02-21 15:48:20 -08002047static char JdwpTagToShortyChar(JDWP::JdwpTag tag) {
2048 switch (tag) {
2049 default:
2050 LOG(FATAL) << "unknown JDWP tag: " << PrintableChar(tag);
2051
2052 // Primitives.
2053 case JDWP::JT_BYTE: return 'B';
2054 case JDWP::JT_CHAR: return 'C';
2055 case JDWP::JT_FLOAT: return 'F';
2056 case JDWP::JT_DOUBLE: return 'D';
2057 case JDWP::JT_INT: return 'I';
2058 case JDWP::JT_LONG: return 'J';
2059 case JDWP::JT_SHORT: return 'S';
2060 case JDWP::JT_VOID: return 'V';
2061 case JDWP::JT_BOOLEAN: return 'Z';
2062
2063 // Reference types.
2064 case JDWP::JT_ARRAY:
2065 case JDWP::JT_OBJECT:
2066 case JDWP::JT_STRING:
2067 case JDWP::JT_THREAD:
2068 case JDWP::JT_THREAD_GROUP:
2069 case JDWP::JT_CLASS_LOADER:
2070 case JDWP::JT_CLASS_OBJECT:
2071 return 'L';
2072 }
2073}
2074
2075JDWP::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 -08002076 ThreadList* thread_list = Runtime::Current()->GetThreadList();
2077
2078 Thread* targetThread = NULL;
2079 DebugInvokeReq* req = NULL;
2080 {
2081 ScopedThreadListLock thread_list_lock;
2082 targetThread = DecodeThread(threadId);
2083 if (targetThread == NULL) {
2084 LOG(ERROR) << "InvokeMethod request for non-existent thread " << threadId;
2085 return JDWP::ERR_INVALID_THREAD;
2086 }
2087 req = targetThread->GetInvokeReq();
2088 if (!req->ready) {
2089 LOG(ERROR) << "InvokeMethod request for thread not stopped by event: " << *targetThread;
2090 return JDWP::ERR_INVALID_THREAD;
2091 }
2092
2093 /*
2094 * We currently have a bug where we don't successfully resume the
2095 * target thread if the suspend count is too deep. We're expected to
2096 * require one "resume" for each "suspend", but when asked to execute
2097 * a method we have to resume fully and then re-suspend it back to the
2098 * same level. (The easiest way to cause this is to type "suspend"
2099 * multiple times in jdb.)
2100 *
2101 * It's unclear what this means when the event specifies "resume all"
2102 * and some threads are suspended more deeply than others. This is
2103 * a rare problem, so for now we just prevent it from hanging forever
2104 * by rejecting the method invocation request. Without this, we will
2105 * be stuck waiting on a suspended thread.
2106 */
2107 int suspend_count = targetThread->GetSuspendCount();
2108 if (suspend_count > 1) {
2109 LOG(ERROR) << *targetThread << " suspend count too deep for method invocation: " << suspend_count;
2110 return JDWP::ERR_THREAD_SUSPENDED; // Probably not expected here.
2111 }
2112
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002113 JDWP::JdwpError status;
Elliott Hughes45651fd2012-02-21 15:48:20 -08002114 Object* receiver = gRegistry->Get<Object*>(objectId);
2115 if (receiver == kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002116 return JDWP::ERR_INVALID_OBJECT;
2117 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002118
2119 Object* thread = gRegistry->Get<Object*>(threadId);
2120 if (thread == kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002121 return JDWP::ERR_INVALID_OBJECT;
2122 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002123 // TODO: check that 'thread' is actually a java.lang.Thread!
2124
2125 Class* c = DecodeClass(classId, status);
2126 if (c == NULL) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002127 return status;
2128 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002129
2130 Method* m = FromMethodId(methodId);
2131 if (m->IsStatic() != (receiver == NULL)) {
2132 return JDWP::ERR_INVALID_METHODID;
2133 }
2134 if (m->IsStatic()) {
2135 if (m->GetDeclaringClass() != c) {
2136 return JDWP::ERR_INVALID_METHODID;
2137 }
2138 } else {
2139 if (!m->GetDeclaringClass()->IsAssignableFrom(c)) {
2140 return JDWP::ERR_INVALID_METHODID;
2141 }
2142 }
2143
2144 // Check the argument list matches the method.
2145 MethodHelper mh(m);
2146 if (mh.GetShortyLength() - 1 != arg_count) {
2147 return JDWP::ERR_ILLEGAL_ARGUMENT;
2148 }
2149 const char* shorty = mh.GetShorty();
2150 for (size_t i = 0; i < arg_count; ++i) {
2151 if (shorty[i + 1] != JdwpTagToShortyChar(arg_types[i])) {
2152 return JDWP::ERR_ILLEGAL_ARGUMENT;
2153 }
2154 }
2155
2156 req->receiver_ = receiver;
2157 req->thread_ = thread;
2158 req->class_ = c;
2159 req->method_ = m;
2160 req->arg_count_ = arg_count;
2161 req->arg_values_ = arg_values;
Elliott Hughesd07986f2011-12-06 18:27:45 -08002162 req->options_ = options;
2163 req->invoke_needed_ = true;
2164 }
2165
2166 // The fact that we've released the thread list lock is a bit risky --- if the thread goes
2167 // away we're sitting high and dry -- but we must release this before the ResumeAllThreads
2168 // call, and it's unwise to hold it during WaitForSuspend.
2169
2170 {
2171 /*
2172 * We change our (JDWP thread) status, which should be THREAD_RUNNING,
Elliott Hughes81ff3182012-03-23 20:35:56 -07002173 * so we can suspend for a GC if the invoke request causes us to
Elliott Hughesd07986f2011-12-06 18:27:45 -08002174 * run out of memory. It's also a good idea to change it before locking
2175 * the invokeReq mutex, although that should never be held for long.
2176 */
2177 ScopedThreadStateChange tsc(Thread::Current(), Thread::kVmWait);
2178
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002179 VLOG(jdwp) << " Transferring control to event thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002180 {
2181 MutexLock mu(req->lock_);
2182
2183 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002184 VLOG(jdwp) << " Resuming all threads";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002185 thread_list->ResumeAll(true);
2186 } else {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002187 VLOG(jdwp) << " Resuming event thread only";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002188 thread_list->Resume(targetThread, true);
2189 }
2190
2191 // Wait for the request to finish executing.
2192 while (req->invoke_needed_) {
2193 req->cond_.Wait(req->lock_);
2194 }
2195 }
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002196 VLOG(jdwp) << " Control has returned from event thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002197
2198 /* wait for thread to re-suspend itself */
2199 targetThread->WaitUntilSuspended();
2200 //dvmWaitForSuspend(targetThread);
2201 }
2202
2203 /*
2204 * Suspend the threads. We waited for the target thread to suspend
2205 * itself, so all we need to do is suspend the others.
2206 *
2207 * The suspendAllThreads() call will double-suspend the event thread,
2208 * so we want to resume the target thread once to keep the books straight.
2209 */
2210 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002211 VLOG(jdwp) << " Suspending all threads";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002212 thread_list->SuspendAll(true);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002213 VLOG(jdwp) << " Resuming event thread to balance the count";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002214 thread_list->Resume(targetThread, true);
2215 }
2216
2217 // Copy the result.
2218 *pResultTag = req->result_tag;
2219 if (IsPrimitiveTag(req->result_tag)) {
2220 *pResultValue = req->result_value.j;
2221 } else {
2222 *pResultValue = gRegistry->Add(req->result_value.l);
2223 }
2224 *pExceptionId = req->exception;
2225 return req->error;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002226}
2227
2228void Dbg::ExecuteMethod(DebugInvokeReq* pReq) {
Elliott Hughesd07986f2011-12-06 18:27:45 -08002229 Thread* self = Thread::Current();
2230
Elliott Hughes81ff3182012-03-23 20:35:56 -07002231 // We can be called while an exception is pending. We need
Elliott Hughesd07986f2011-12-06 18:27:45 -08002232 // to preserve that across the method invocation.
2233 SirtRef<Throwable> old_exception(self->GetException());
2234 self->ClearException();
2235
2236 ScopedThreadStateChange tsc(self, Thread::kRunnable);
2237
2238 // Translate the method through the vtable, unless the debugger wants to suppress it.
2239 Method* m = pReq->method_;
2240 if ((pReq->options_ & JDWP::INVOKE_NONVIRTUAL) == 0 && pReq->receiver_ != NULL) {
Elliott Hughes45651fd2012-02-21 15:48:20 -08002241 Method* actual_method = pReq->class_->FindVirtualMethodForVirtualOrInterface(pReq->method_);
2242 if (actual_method != m) {
2243 VLOG(jdwp) << "ExecuteMethod translated " << PrettyMethod(m) << " to " << PrettyMethod(actual_method);
2244 m = actual_method;
2245 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08002246 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002247 VLOG(jdwp) << "ExecuteMethod " << PrettyMethod(m);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002248 CHECK(m != NULL);
2249
2250 CHECK_EQ(sizeof(jvalue), sizeof(uint64_t));
2251
Elliott Hughes45651fd2012-02-21 15:48:20 -08002252 LOG(INFO) << "self=" << self << " pReq->receiver_=" << pReq->receiver_ << " m=" << m << " #" << pReq->arg_count_ << " " << pReq->arg_values_;
2253 pReq->result_value = InvokeWithJValues(self, pReq->receiver_, m, reinterpret_cast<JValue*>(pReq->arg_values_));
Elliott Hughesd07986f2011-12-06 18:27:45 -08002254
2255 pReq->exception = gRegistry->Add(self->GetException());
2256 pReq->result_tag = BasicTagFromDescriptor(MethodHelper(m).GetShorty());
2257 if (pReq->exception != 0) {
2258 Object* exc = self->GetException();
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002259 VLOG(jdwp) << " JDWP invocation returning with exception=" << exc << " " << PrettyTypeOf(exc);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002260 self->ClearException();
2261 pReq->result_value.j = 0;
2262 } else if (pReq->result_tag == JDWP::JT_OBJECT) {
2263 /* if no exception thrown, examine object result more closely */
2264 JDWP::JdwpTag new_tag = TagFromObject(pReq->result_value.l);
2265 if (new_tag != pReq->result_tag) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002266 VLOG(jdwp) << " JDWP promoted result from " << pReq->result_tag << " to " << new_tag;
Elliott Hughesd07986f2011-12-06 18:27:45 -08002267 pReq->result_tag = new_tag;
2268 }
2269
2270 /*
2271 * Register the object. We don't actually need an ObjectId yet,
2272 * but we do need to be sure that the GC won't move or discard the
2273 * object when we switch out of RUNNING. The ObjectId conversion
2274 * will add the object to the "do not touch" list.
2275 *
2276 * We can't use the "tracked allocation" mechanism here because
2277 * the object is going to be handed off to a different thread.
2278 */
2279 gRegistry->Add(pReq->result_value.l);
2280 }
2281
2282 if (old_exception.get() != NULL) {
2283 self->SetException(old_exception.get());
2284 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002285}
2286
Elliott Hughesd07986f2011-12-06 18:27:45 -08002287/*
2288 * Register an object ID that might not have been registered previously.
2289 *
2290 * Normally this wouldn't happen -- the conversion to an ObjectId would
2291 * have added the object to the registry -- but in some cases (e.g.
2292 * throwing exceptions) we really want to do the registration late.
2293 */
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002294void Dbg::RegisterObjectId(JDWP::ObjectId id) {
Elliott Hughesd07986f2011-12-06 18:27:45 -08002295 gRegistry->Add(reinterpret_cast<Object*>(id));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002296}
2297
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002298/*
2299 * "buf" contains a full JDWP packet, possibly with multiple chunks. We
2300 * need to process each, accumulate the replies, and ship the whole thing
2301 * back.
2302 *
2303 * Returns "true" if we have a reply. The reply buffer is newly allocated,
2304 * and includes the chunk type/length, followed by the data.
2305 *
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08002306 * OLD-TODO: we currently assume that the request and reply include a single
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002307 * chunk. If this becomes inconvenient we will need to adapt.
2308 */
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002309bool Dbg::DdmHandlePacket(const uint8_t* buf, int dataLen, uint8_t** pReplyBuf, int* pReplyLen) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002310 CHECK_GE(dataLen, 0);
2311
2312 Thread* self = Thread::Current();
2313 JNIEnv* env = self->GetJniEnv();
2314
Elliott Hughes844f9a02012-01-24 20:19:58 -08002315 static jclass Chunk_class = CacheClass(env, "org/apache/harmony/dalvik/ddmc/Chunk");
2316 static jclass DdmServer_class = CacheClass(env, "org/apache/harmony/dalvik/ddmc/DdmServer");
2317 static jmethodID dispatch_mid = env->GetStaticMethodID(DdmServer_class, "dispatch", "(I[BII)Lorg/apache/harmony/dalvik/ddmc/Chunk;");
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002318 static jfieldID data_fid = env->GetFieldID(Chunk_class, "data", "[B");
2319 static jfieldID length_fid = env->GetFieldID(Chunk_class, "length", "I");
2320 static jfieldID offset_fid = env->GetFieldID(Chunk_class, "offset", "I");
2321 static jfieldID type_fid = env->GetFieldID(Chunk_class, "type", "I");
2322
2323 // Create a byte[] corresponding to 'buf'.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002324 ScopedLocalRef<jbyteArray> dataArray(env, env->NewByteArray(dataLen));
2325 if (dataArray.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002326 LOG(WARNING) << "byte[] allocation failed: " << dataLen;
2327 env->ExceptionClear();
2328 return false;
2329 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002330 env->SetByteArrayRegion(dataArray.get(), 0, dataLen, reinterpret_cast<const jbyte*>(buf));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002331
2332 const int kChunkHdrLen = 8;
2333
2334 // Run through and find all chunks. [Currently just find the first.]
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002335 ScopedByteArrayRO contents(env, dataArray.get());
Elliott Hughesf7c3b662011-10-27 12:04:56 -07002336 jint type = JDWP::Get4BE(reinterpret_cast<const uint8_t*>(&contents[0]));
2337 jint length = JDWP::Get4BE(reinterpret_cast<const uint8_t*>(&contents[4]));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002338 jint offset = kChunkHdrLen;
2339 if (offset + length > dataLen) {
2340 LOG(WARNING) << StringPrintf("bad chunk found (len=%u pktLen=%d)", length, dataLen);
2341 return false;
2342 }
2343
2344 // Call "private static Chunk dispatch(int type, byte[] data, int offset, int length)".
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002345 ScopedLocalRef<jobject> chunk(env, env->CallStaticObjectMethod(DdmServer_class, dispatch_mid, type, dataArray.get(), offset, length));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002346 if (env->ExceptionCheck()) {
2347 LOG(INFO) << StringPrintf("Exception thrown by dispatcher for 0x%08x", type);
2348 env->ExceptionDescribe();
2349 env->ExceptionClear();
2350 return false;
2351 }
2352
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002353 if (chunk.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002354 return false;
2355 }
2356
2357 /*
2358 * Pull the pieces out of the chunk. We copy the results into a
2359 * newly-allocated buffer that the caller can free. We don't want to
2360 * continue using the Chunk object because nothing has a reference to it.
2361 *
2362 * We could avoid this by returning type/data/offset/length and having
2363 * the caller be aware of the object lifetime issues, but that
Elliott Hughes81ff3182012-03-23 20:35:56 -07002364 * integrates the JDWP code more tightly into the rest of the runtime, and doesn't work
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002365 * if we have responses for multiple chunks.
2366 *
2367 * So we're pretty much stuck with copying data around multiple times.
2368 */
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002369 ScopedLocalRef<jbyteArray> replyData(env, reinterpret_cast<jbyteArray>(env->GetObjectField(chunk.get(), data_fid)));
2370 length = env->GetIntField(chunk.get(), length_fid);
2371 offset = env->GetIntField(chunk.get(), offset_fid);
2372 type = env->GetIntField(chunk.get(), type_fid);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002373
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002374 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 -07002375 if (length == 0 || replyData.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002376 return false;
2377 }
2378
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002379 jsize replyLength = env->GetArrayLength(replyData.get());
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002380 if (offset + length > replyLength) {
2381 LOG(WARNING) << StringPrintf("chunk off=%d len=%d exceeds reply array len %d", offset, length, replyLength);
2382 return false;
2383 }
2384
2385 uint8_t* reply = new uint8_t[length + kChunkHdrLen];
2386 if (reply == NULL) {
2387 LOG(WARNING) << "malloc failed: " << (length + kChunkHdrLen);
2388 return false;
2389 }
Elliott Hughesf7c3b662011-10-27 12:04:56 -07002390 JDWP::Set4BE(reply + 0, type);
2391 JDWP::Set4BE(reply + 4, length);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002392 env->GetByteArrayRegion(replyData.get(), offset, length, reinterpret_cast<jbyte*>(reply + kChunkHdrLen));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002393
2394 *pReplyBuf = reply;
2395 *pReplyLen = length + kChunkHdrLen;
2396
Elliott Hughesba8eee12012-01-24 20:25:24 -08002397 VLOG(jdwp) << StringPrintf("dvmHandleDdm returning type=%.4s buf=%p len=%d", reinterpret_cast<char*>(reply), reply, length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002398 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002399}
2400
Elliott Hughesa2155262011-11-16 16:26:58 -08002401void Dbg::DdmBroadcast(bool connect) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002402 VLOG(jdwp) << "Broadcasting DDM " << (connect ? "connect" : "disconnect") << "...";
Elliott Hughes47fce012011-10-25 18:37:19 -07002403
2404 Thread* self = Thread::Current();
2405 if (self->GetState() != Thread::kRunnable) {
2406 LOG(ERROR) << "DDM broadcast in thread state " << self->GetState();
2407 /* try anyway? */
2408 }
2409
2410 JNIEnv* env = self->GetJniEnv();
Elliott Hughes844f9a02012-01-24 20:19:58 -08002411 static jclass DdmServer_class = CacheClass(env, "org/apache/harmony/dalvik/ddmc/DdmServer");
Elliott Hughes47fce012011-10-25 18:37:19 -07002412 static jmethodID broadcast_mid = env->GetStaticMethodID(DdmServer_class, "broadcast", "(I)V");
2413 jint event = connect ? 1 /*DdmServer.CONNECTED*/ : 2 /*DdmServer.DISCONNECTED*/;
2414 env->CallStaticVoidMethod(DdmServer_class, broadcast_mid, event);
2415 if (env->ExceptionCheck()) {
2416 LOG(ERROR) << "DdmServer.broadcast " << event << " failed";
2417 env->ExceptionDescribe();
2418 env->ExceptionClear();
2419 }
2420}
2421
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002422void Dbg::DdmConnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08002423 Dbg::DdmBroadcast(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002424}
2425
2426void Dbg::DdmDisconnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08002427 Dbg::DdmBroadcast(false);
Elliott Hughes47fce012011-10-25 18:37:19 -07002428 gDdmThreadNotification = false;
2429}
2430
2431/*
Elliott Hughes82188472011-11-07 18:11:48 -08002432 * Send a notification when a thread starts, stops, or changes its name.
Elliott Hughes47fce012011-10-25 18:37:19 -07002433 *
2434 * Because we broadcast the full set of threads when the notifications are
2435 * first enabled, it's possible for "thread" to be actively executing.
2436 */
Elliott Hughes82188472011-11-07 18:11:48 -08002437void Dbg::DdmSendThreadNotification(Thread* t, uint32_t type) {
Elliott Hughes47fce012011-10-25 18:37:19 -07002438 if (!gDdmThreadNotification) {
2439 return;
2440 }
2441
Elliott Hughes82188472011-11-07 18:11:48 -08002442 if (type == CHUNK_TYPE("THDE")) {
Elliott Hughes47fce012011-10-25 18:37:19 -07002443 uint8_t buf[4];
Elliott Hughesf7c3b662011-10-27 12:04:56 -07002444 JDWP::Set4BE(&buf[0], t->GetThinLockId());
Elliott Hughes47fce012011-10-25 18:37:19 -07002445 Dbg::DdmSendChunk(CHUNK_TYPE("THDE"), 4, buf);
Elliott Hughes82188472011-11-07 18:11:48 -08002446 } else {
2447 CHECK(type == CHUNK_TYPE("THCR") || type == CHUNK_TYPE("THNM")) << type;
Elliott Hughes899e7892012-01-24 14:57:32 -08002448 SirtRef<String> name(t->GetThreadName());
Elliott Hughes82188472011-11-07 18:11:48 -08002449 size_t char_count = (name.get() != NULL) ? name->GetLength() : 0;
2450 const jchar* chars = name->GetCharArray()->GetData();
2451
Elliott Hughes21f32d72011-11-09 17:44:13 -08002452 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08002453 JDWP::Append4BE(bytes, t->GetThinLockId());
2454 JDWP::AppendUtf16BE(bytes, chars, char_count);
Elliott Hughes21f32d72011-11-09 17:44:13 -08002455 CHECK_EQ(bytes.size(), char_count*2 + sizeof(uint32_t)*2);
2456 Dbg::DdmSendChunk(type, bytes);
Elliott Hughes47fce012011-10-25 18:37:19 -07002457 }
2458}
2459
Elliott Hughesa2155262011-11-16 16:26:58 -08002460static void DdmSendThreadStartCallback(Thread* t, void*) {
Elliott Hughes82188472011-11-07 18:11:48 -08002461 Dbg::DdmSendThreadNotification(t, CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07002462}
2463
2464void Dbg::DdmSetThreadNotification(bool enable) {
2465 // We lock the thread list to avoid sending duplicate events or missing
2466 // a thread change. We should be okay holding this lock while sending
2467 // the messages out. (We have to hold it while accessing a live thread.)
Elliott Hughesbbd9d832011-11-07 14:40:00 -08002468 ScopedThreadListLock thread_list_lock;
Elliott Hughes47fce012011-10-25 18:37:19 -07002469
2470 gDdmThreadNotification = enable;
2471 if (enable) {
Elliott Hughesbfe487b2011-10-26 15:48:55 -07002472 Runtime::Current()->GetThreadList()->ForEach(DdmSendThreadStartCallback, NULL);
Elliott Hughes47fce012011-10-25 18:37:19 -07002473 }
2474}
2475
Elliott Hughesa2155262011-11-16 16:26:58 -08002476void Dbg::PostThreadStartOrStop(Thread* t, uint32_t type) {
Elliott Hughesc0f09332012-03-26 13:27:06 -07002477 if (IsDebuggerActive()) {
Elliott Hughes47fce012011-10-25 18:37:19 -07002478 JDWP::ObjectId id = gRegistry->Add(t->GetPeer());
Elliott Hughes82188472011-11-07 18:11:48 -08002479 gJdwpState->PostThreadChange(id, type == CHUNK_TYPE("THCR"));
Elliott Hughesc0f09332012-03-26 13:27:06 -07002480 // If this thread's just joined the party while we're already debugging, make sure it knows
2481 // to give us updates when it's running.
2482 t->SetDebuggerUpdatesEnabled(true);
Elliott Hughes47fce012011-10-25 18:37:19 -07002483 }
Elliott Hughes82188472011-11-07 18:11:48 -08002484 Dbg::DdmSendThreadNotification(t, type);
Elliott Hughes47fce012011-10-25 18:37:19 -07002485}
2486
2487void Dbg::PostThreadStart(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08002488 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07002489}
2490
2491void Dbg::PostThreadDeath(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08002492 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THDE"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002493}
2494
Elliott Hughes82188472011-11-07 18:11:48 -08002495void Dbg::DdmSendChunk(uint32_t type, size_t byte_count, const uint8_t* buf) {
Elliott Hughes3bb81562011-10-21 18:52:59 -07002496 CHECK(buf != NULL);
2497 iovec vec[1];
2498 vec[0].iov_base = reinterpret_cast<void*>(const_cast<uint8_t*>(buf));
2499 vec[0].iov_len = byte_count;
2500 Dbg::DdmSendChunkV(type, vec, 1);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002501}
2502
Elliott Hughes21f32d72011-11-09 17:44:13 -08002503void Dbg::DdmSendChunk(uint32_t type, const std::vector<uint8_t>& bytes) {
2504 DdmSendChunk(type, bytes.size(), &bytes[0]);
2505}
2506
Elliott Hughescccd84f2011-12-05 16:51:54 -08002507void Dbg::DdmSendChunkV(uint32_t type, const struct iovec* iov, int iov_count) {
Elliott Hughes3bb81562011-10-21 18:52:59 -07002508 if (gJdwpState == NULL) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002509 VLOG(jdwp) << "Debugger thread not active, ignoring DDM send: " << type;
Elliott Hughes3bb81562011-10-21 18:52:59 -07002510 } else {
Elliott Hughescccd84f2011-12-05 16:51:54 -08002511 gJdwpState->DdmSendChunkV(type, iov, iov_count);
Elliott Hughes3bb81562011-10-21 18:52:59 -07002512 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002513}
2514
Elliott Hughes767a1472011-10-26 18:49:02 -07002515int Dbg::DdmHandleHpifChunk(HpifWhen when) {
2516 if (when == HPIF_WHEN_NOW) {
Elliott Hughes7162ad92011-10-27 14:08:42 -07002517 DdmSendHeapInfo(when);
Elliott Hughes767a1472011-10-26 18:49:02 -07002518 return true;
2519 }
2520
2521 if (when != HPIF_WHEN_NEVER && when != HPIF_WHEN_NEXT_GC && when != HPIF_WHEN_EVERY_GC) {
2522 LOG(ERROR) << "invalid HpifWhen value: " << static_cast<int>(when);
2523 return false;
2524 }
2525
2526 gDdmHpifWhen = when;
2527 return true;
2528}
2529
2530bool Dbg::DdmHandleHpsgNhsgChunk(Dbg::HpsgWhen when, Dbg::HpsgWhat what, bool native) {
2531 if (when != HPSG_WHEN_NEVER && when != HPSG_WHEN_EVERY_GC) {
2532 LOG(ERROR) << "invalid HpsgWhen value: " << static_cast<int>(when);
2533 return false;
2534 }
2535
2536 if (what != HPSG_WHAT_MERGED_OBJECTS && what != HPSG_WHAT_DISTINCT_OBJECTS) {
2537 LOG(ERROR) << "invalid HpsgWhat value: " << static_cast<int>(what);
2538 return false;
2539 }
2540
2541 if (native) {
2542 gDdmNhsgWhen = when;
2543 gDdmNhsgWhat = what;
2544 } else {
2545 gDdmHpsgWhen = when;
2546 gDdmHpsgWhat = what;
2547 }
2548 return true;
2549}
2550
Elliott Hughes7162ad92011-10-27 14:08:42 -07002551void Dbg::DdmSendHeapInfo(HpifWhen reason) {
2552 // If there's a one-shot 'when', reset it.
2553 if (reason == gDdmHpifWhen) {
2554 if (gDdmHpifWhen == HPIF_WHEN_NEXT_GC) {
2555 gDdmHpifWhen = HPIF_WHEN_NEVER;
2556 }
2557 }
2558
2559 /*
2560 * Chunk HPIF (client --> server)
2561 *
2562 * Heap Info. General information about the heap,
2563 * suitable for a summary display.
2564 *
2565 * [u4]: number of heaps
2566 *
2567 * For each heap:
2568 * [u4]: heap ID
2569 * [u8]: timestamp in ms since Unix epoch
2570 * [u1]: capture reason (same as 'when' value from server)
2571 * [u4]: max heap size in bytes (-Xmx)
2572 * [u4]: current heap size in bytes
2573 * [u4]: current number of bytes allocated
2574 * [u4]: current number of objects allocated
2575 */
2576 uint8_t heap_count = 1;
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08002577 Heap* heap = Runtime::Current()->GetHeap();
Elliott Hughes21f32d72011-11-09 17:44:13 -08002578 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08002579 JDWP::Append4BE(bytes, heap_count);
2580 JDWP::Append4BE(bytes, 1); // Heap id (bogus; we only have one heap).
2581 JDWP::Append8BE(bytes, MilliTime());
2582 JDWP::Append1BE(bytes, reason);
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08002583 JDWP::Append4BE(bytes, heap->GetMaxMemory()); // Max allowed heap size in bytes.
2584 JDWP::Append4BE(bytes, heap->GetTotalMemory()); // Current heap size in bytes.
2585 JDWP::Append4BE(bytes, heap->GetBytesAllocated());
2586 JDWP::Append4BE(bytes, heap->GetObjectsAllocated());
Elliott Hughes21f32d72011-11-09 17:44:13 -08002587 CHECK_EQ(bytes.size(), 4U + (heap_count * (4 + 8 + 1 + 4 + 4 + 4 + 4)));
2588 Dbg::DdmSendChunk(CHUNK_TYPE("HPIF"), bytes);
Elliott Hughes767a1472011-10-26 18:49:02 -07002589}
2590
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002591enum HpsgSolidity {
2592 SOLIDITY_FREE = 0,
2593 SOLIDITY_HARD = 1,
2594 SOLIDITY_SOFT = 2,
2595 SOLIDITY_WEAK = 3,
2596 SOLIDITY_PHANTOM = 4,
2597 SOLIDITY_FINALIZABLE = 5,
2598 SOLIDITY_SWEEP = 6,
2599};
2600
2601enum HpsgKind {
2602 KIND_OBJECT = 0,
2603 KIND_CLASS_OBJECT = 1,
2604 KIND_ARRAY_1 = 2,
2605 KIND_ARRAY_2 = 3,
2606 KIND_ARRAY_4 = 4,
2607 KIND_ARRAY_8 = 5,
2608 KIND_UNKNOWN = 6,
2609 KIND_NATIVE = 7,
2610};
2611
2612#define HPSG_PARTIAL (1<<7)
2613#define HPSG_STATE(solidity, kind) ((uint8_t)((((kind) & 0x7) << 3) | ((solidity) & 0x7)))
2614
Ian Rogers30fab402012-01-23 15:43:46 -08002615class HeapChunkContext {
2616 public:
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002617 // Maximum chunk size. Obtain this from the formula:
2618 // (((maximum_heap_size / ALLOCATION_UNIT_SIZE) + 255) / 256) * 2
2619 HeapChunkContext(bool merge, bool native)
Ian Rogers30fab402012-01-23 15:43:46 -08002620 : buf_(16384 - 16),
2621 type_(0),
2622 merge_(merge) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002623 Reset();
2624 if (native) {
Ian Rogers30fab402012-01-23 15:43:46 -08002625 type_ = CHUNK_TYPE("NHSG");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002626 } else {
Ian Rogers30fab402012-01-23 15:43:46 -08002627 type_ = merge ? CHUNK_TYPE("HPSG") : CHUNK_TYPE("HPSO");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002628 }
2629 }
2630
2631 ~HeapChunkContext() {
Ian Rogers30fab402012-01-23 15:43:46 -08002632 if (p_ > &buf_[0]) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002633 Flush();
2634 }
2635 }
2636
2637 void EnsureHeader(const void* chunk_ptr) {
Ian Rogers30fab402012-01-23 15:43:46 -08002638 if (!needHeader_) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002639 return;
2640 }
2641
2642 // Start a new HPSx chunk.
Ian Rogers30fab402012-01-23 15:43:46 -08002643 JDWP::Write4BE(&p_, 1); // Heap id (bogus; we only have one heap).
2644 JDWP::Write1BE(&p_, 8); // Size of allocation unit, in bytes.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002645
Ian Rogers30fab402012-01-23 15:43:46 -08002646 JDWP::Write4BE(&p_, reinterpret_cast<uintptr_t>(chunk_ptr)); // virtual address of segment start.
2647 JDWP::Write4BE(&p_, 0); // offset of this piece (relative to the virtual address).
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002648 // [u4]: length of piece, in allocation units
2649 // 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 -08002650 pieceLenField_ = p_;
2651 JDWP::Write4BE(&p_, 0x55555555);
2652 needHeader_ = false;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002653 }
2654
2655 void Flush() {
2656 // Patch the "length of piece" field.
Ian Rogers30fab402012-01-23 15:43:46 -08002657 CHECK_LE(&buf_[0], pieceLenField_);
2658 CHECK_LE(pieceLenField_, p_);
2659 JDWP::Set4BE(pieceLenField_, totalAllocationUnits_);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002660
Ian Rogers30fab402012-01-23 15:43:46 -08002661 Dbg::DdmSendChunk(type_, p_ - &buf_[0], &buf_[0]);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002662 Reset();
2663 }
2664
Ian Rogers30fab402012-01-23 15:43:46 -08002665 static void HeapChunkCallback(void* start, void* end, size_t used_bytes, void* arg) {
2666 reinterpret_cast<HeapChunkContext*>(arg)->HeapChunkCallback(start, end, used_bytes);
Elliott Hughesa2155262011-11-16 16:26:58 -08002667 }
2668
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002669 private:
Elliott Hughesa2155262011-11-16 16:26:58 -08002670 enum { ALLOCATION_UNIT_SIZE = 8 };
2671
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002672 void Reset() {
Ian Rogers30fab402012-01-23 15:43:46 -08002673 p_ = &buf_[0];
2674 totalAllocationUnits_ = 0;
2675 needHeader_ = true;
2676 pieceLenField_ = NULL;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002677 }
2678
Elliott Hughes1bac54f2012-03-16 12:48:31 -07002679 void HeapChunkCallback(void* start, void* /*end*/, size_t used_bytes) {
Ian Rogers30fab402012-01-23 15:43:46 -08002680 // Note: heap call backs cannot manipulate the heap upon which they are crawling, care is taken
2681 // in the following code not to allocate memory, by ensuring buf_ is of the correct size
2682
2683 const void* user_ptr = used_bytes > 0 ? const_cast<void*>(start) : NULL;
2684 // from malloc.c mem2chunk(mem)
2685 const void* chunk_ptr =
2686 reinterpret_cast<const void*>(reinterpret_cast<const char*>(const_cast<void*>(start)) -
2687 (2 * sizeof(size_t)));
2688 // from malloc.c chunksize
2689 size_t chunk_len = (*reinterpret_cast<size_t* const*>(chunk_ptr))[1] & ~7;
2690
2691
2692 //size_t chunk_len = malloc_usable_size(user_ptr);
Elliott Hughesa2155262011-11-16 16:26:58 -08002693 CHECK_EQ((chunk_len & (ALLOCATION_UNIT_SIZE-1)), 0U);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002694
Elliott Hughesa2155262011-11-16 16:26:58 -08002695 /* Make sure there's enough room left in the buffer.
2696 * We need to use two bytes for every fractional 256
2697 * allocation units used by the chunk.
2698 */
2699 {
2700 size_t needed = (((chunk_len/ALLOCATION_UNIT_SIZE + 255) / 256) * 2);
Ian Rogers30fab402012-01-23 15:43:46 -08002701 size_t bytesLeft = buf_.size() - (size_t)(p_ - &buf_[0]);
Elliott Hughesa2155262011-11-16 16:26:58 -08002702 if (bytesLeft < needed) {
2703 Flush();
2704 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002705
Ian Rogers30fab402012-01-23 15:43:46 -08002706 bytesLeft = buf_.size() - (size_t)(p_ - &buf_[0]);
Elliott Hughesa2155262011-11-16 16:26:58 -08002707 if (bytesLeft < needed) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08002708 LOG(WARNING) << "Chunk is too big to transmit (chunk_len=" << chunk_len << ", " << needed << " bytes)";
Elliott Hughesa2155262011-11-16 16:26:58 -08002709 return;
2710 }
2711 }
2712
2713 // OLD-TODO: notice when there's a gap and start a new heap, or at least a new range.
2714 EnsureHeader(chunk_ptr);
2715
2716 // Determine the type of this chunk.
2717 // OLD-TODO: if context.merge, see if this chunk is different from the last chunk.
2718 // If it's the same, we should combine them.
Ian Rogers30fab402012-01-23 15:43:46 -08002719 uint8_t state = ExamineObject(reinterpret_cast<const Object*>(user_ptr), (type_ == CHUNK_TYPE("NHSG")));
Elliott Hughesa2155262011-11-16 16:26:58 -08002720
2721 // Write out the chunk description.
2722 chunk_len /= ALLOCATION_UNIT_SIZE; // convert to allocation units
Ian Rogers30fab402012-01-23 15:43:46 -08002723 totalAllocationUnits_ += chunk_len;
Elliott Hughesa2155262011-11-16 16:26:58 -08002724 while (chunk_len > 256) {
Ian Rogers30fab402012-01-23 15:43:46 -08002725 *p_++ = state | HPSG_PARTIAL;
2726 *p_++ = 255; // length - 1
Elliott Hughesa2155262011-11-16 16:26:58 -08002727 chunk_len -= 256;
2728 }
Ian Rogers30fab402012-01-23 15:43:46 -08002729 *p_++ = state;
2730 *p_++ = chunk_len - 1;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002731 }
2732
Elliott Hughesa2155262011-11-16 16:26:58 -08002733 uint8_t ExamineObject(const Object* o, bool is_native_heap) {
2734 if (o == NULL) {
2735 return HPSG_STATE(SOLIDITY_FREE, 0);
2736 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002737
Elliott Hughesa2155262011-11-16 16:26:58 -08002738 // It's an allocated chunk. Figure out what it is.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002739
Elliott Hughesa2155262011-11-16 16:26:58 -08002740 // If we're looking at the native heap, we'll just return
2741 // (SOLIDITY_HARD, KIND_NATIVE) for all allocated chunks.
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08002742 if (is_native_heap || !Runtime::Current()->GetHeap()->IsLiveObjectLocked(o)) {
Elliott Hughesa2155262011-11-16 16:26:58 -08002743 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
2744 }
2745
2746 Class* c = o->GetClass();
2747 if (c == NULL) {
2748 // The object was probably just created but hasn't been initialized yet.
2749 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
2750 }
2751
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08002752 if (!Runtime::Current()->GetHeap()->IsHeapAddress(c)) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08002753 LOG(WARNING) << "Invalid class for managed heap object: " << o << " " << c;
Elliott Hughesa2155262011-11-16 16:26:58 -08002754 return HPSG_STATE(SOLIDITY_HARD, KIND_UNKNOWN);
2755 }
2756
2757 if (c->IsClassClass()) {
2758 return HPSG_STATE(SOLIDITY_HARD, KIND_CLASS_OBJECT);
2759 }
2760
2761 if (c->IsArrayClass()) {
2762 if (o->IsObjectArray()) {
2763 return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
2764 }
2765 switch (c->GetComponentSize()) {
2766 case 1: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_1);
2767 case 2: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_2);
2768 case 4: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
2769 case 8: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_8);
2770 }
2771 }
2772
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002773 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
2774 }
2775
Ian Rogers30fab402012-01-23 15:43:46 -08002776 std::vector<uint8_t> buf_;
2777 uint8_t* p_;
2778 uint8_t* pieceLenField_;
2779 size_t totalAllocationUnits_;
2780 uint32_t type_;
2781 bool merge_;
2782 bool needHeader_;
2783
Elliott Hughesa2155262011-11-16 16:26:58 -08002784 DISALLOW_COPY_AND_ASSIGN(HeapChunkContext);
2785};
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002786
2787void Dbg::DdmSendHeapSegments(bool native) {
2788 Dbg::HpsgWhen when;
2789 Dbg::HpsgWhat what;
2790 if (!native) {
2791 when = gDdmHpsgWhen;
2792 what = gDdmHpsgWhat;
2793 } else {
2794 when = gDdmNhsgWhen;
2795 what = gDdmNhsgWhat;
2796 }
2797 if (when == HPSG_WHEN_NEVER) {
2798 return;
2799 }
2800
2801 // Figure out what kind of chunks we'll be sending.
2802 CHECK(what == HPSG_WHAT_MERGED_OBJECTS || what == HPSG_WHAT_DISTINCT_OBJECTS) << static_cast<int>(what);
2803
2804 // First, send a heap start chunk.
2805 uint8_t heap_id[4];
2806 JDWP::Set4BE(&heap_id[0], 1); // Heap id (bogus; we only have one heap).
2807 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHST") : CHUNK_TYPE("HPST"), sizeof(heap_id), heap_id);
2808
2809 // Send a series of heap segment chunks.
Elliott Hughesa2155262011-11-16 16:26:58 -08002810 HeapChunkContext context((what == HPSG_WHAT_MERGED_OBJECTS), native);
2811 if (native) {
Ian Rogers30fab402012-01-23 15:43:46 -08002812 // TODO: enable when bionic has moved to dlmalloc 2.8.5
2813 // dlmalloc_inspect_all(HeapChunkContext::HeapChunkCallback, &context);
2814 UNIMPLEMENTED(WARNING) << "Native heap send heap segments";
Elliott Hughesa2155262011-11-16 16:26:58 -08002815 } else {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08002816 Heap* heap = Runtime::Current()->GetHeap();
2817 heap->GetAllocSpace()->Walk(HeapChunkContext::HeapChunkCallback, &context);
Elliott Hughesa2155262011-11-16 16:26:58 -08002818 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002819
2820 // Finally, send a heap end chunk.
2821 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHEN") : CHUNK_TYPE("HPEN"), sizeof(heap_id), heap_id);
Elliott Hughes767a1472011-10-26 18:49:02 -07002822}
2823
Elliott Hughes545a0642011-11-08 19:10:03 -08002824void Dbg::SetAllocTrackingEnabled(bool enabled) {
2825 MutexLock mu(gAllocTrackerLock);
2826 if (enabled) {
2827 if (recent_allocation_records_ == NULL) {
2828 LOG(INFO) << "Enabling alloc tracker (" << kNumAllocRecords << " entries, "
2829 << kMaxAllocRecordStackDepth << " frames --> "
2830 << (sizeof(AllocRecord) * kNumAllocRecords) << " bytes)";
2831 gAllocRecordHead = gAllocRecordCount = 0;
2832 recent_allocation_records_ = new AllocRecord[kNumAllocRecords];
2833 CHECK(recent_allocation_records_ != NULL);
2834 }
2835 } else {
2836 delete[] recent_allocation_records_;
2837 recent_allocation_records_ = NULL;
2838 }
2839}
2840
2841struct AllocRecordStackVisitor : public Thread::StackVisitor {
Elliott Hughesba8eee12012-01-24 20:25:24 -08002842 explicit AllocRecordStackVisitor(AllocRecord* record) : record(record), depth(0) {
Elliott Hughes545a0642011-11-08 19:10:03 -08002843 }
2844
Elliott Hughes530fa002012-03-12 11:44:49 -07002845 bool VisitFrame(const Frame& f, uintptr_t pc) {
Elliott Hughes545a0642011-11-08 19:10:03 -08002846 if (depth >= kMaxAllocRecordStackDepth) {
Elliott Hughes530fa002012-03-12 11:44:49 -07002847 return false;
Elliott Hughes545a0642011-11-08 19:10:03 -08002848 }
Elliott Hughes530fa002012-03-12 11:44:49 -07002849 if (f.HasMethod()) {
2850 record->stack[depth].method = f.GetMethod();
2851 record->stack[depth].raw_pc = pc;
2852 ++depth;
Elliott Hughes545a0642011-11-08 19:10:03 -08002853 }
Elliott Hughes530fa002012-03-12 11:44:49 -07002854 return true;
Elliott Hughes545a0642011-11-08 19:10:03 -08002855 }
2856
2857 ~AllocRecordStackVisitor() {
2858 // Clear out any unused stack trace elements.
2859 for (; depth < kMaxAllocRecordStackDepth; ++depth) {
2860 record->stack[depth].method = NULL;
2861 record->stack[depth].raw_pc = 0;
2862 }
2863 }
2864
2865 AllocRecord* record;
2866 size_t depth;
2867};
2868
2869void Dbg::RecordAllocation(Class* type, size_t byte_count) {
2870 Thread* self = Thread::Current();
2871 CHECK(self != NULL);
2872
2873 MutexLock mu(gAllocTrackerLock);
2874 if (recent_allocation_records_ == NULL) {
2875 return;
2876 }
2877
2878 // Advance and clip.
2879 if (++gAllocRecordHead == kNumAllocRecords) {
2880 gAllocRecordHead = 0;
2881 }
2882
2883 // Fill in the basics.
2884 AllocRecord* record = &recent_allocation_records_[gAllocRecordHead];
2885 record->type = type;
2886 record->byte_count = byte_count;
2887 record->thin_lock_id = self->GetThinLockId();
2888
2889 // Fill in the stack trace.
2890 AllocRecordStackVisitor visitor(record);
2891 self->WalkStack(&visitor);
2892
2893 if (gAllocRecordCount < kNumAllocRecords) {
2894 ++gAllocRecordCount;
2895 }
2896}
2897
2898/*
2899 * Return the index of the head element.
2900 *
2901 * We point at the most-recently-written record, so if allocRecordCount is 1
2902 * we want to use the current element. Take "head+1" and subtract count
2903 * from it.
2904 *
2905 * We need to handle underflow in our circular buffer, so we add
2906 * kNumAllocRecords and then mask it back down.
2907 */
2908inline static int headIndex() {
2909 return (gAllocRecordHead+1 + kNumAllocRecords - gAllocRecordCount) & (kNumAllocRecords-1);
2910}
2911
2912void Dbg::DumpRecentAllocations() {
2913 MutexLock mu(gAllocTrackerLock);
2914 if (recent_allocation_records_ == NULL) {
2915 LOG(INFO) << "Not recording tracked allocations";
2916 return;
2917 }
2918
2919 // "i" is the head of the list. We want to start at the end of the
2920 // list and move forward to the tail.
2921 size_t i = headIndex();
2922 size_t count = gAllocRecordCount;
2923
2924 LOG(INFO) << "Tracked allocations, (head=" << gAllocRecordHead << " count=" << count << ")";
2925 while (count--) {
2926 AllocRecord* record = &recent_allocation_records_[i];
2927
Elliott Hughesaa6e1cd2012-01-18 19:26:06 -08002928 LOG(INFO) << StringPrintf(" T=%-2d %6zd ", record->thin_lock_id, record->byte_count)
Elliott Hughes545a0642011-11-08 19:10:03 -08002929 << PrettyClass(record->type);
2930
2931 for (size_t stack_frame = 0; stack_frame < kMaxAllocRecordStackDepth; ++stack_frame) {
2932 const Method* m = record->stack[stack_frame].method;
2933 if (m == NULL) {
2934 break;
2935 }
2936 LOG(INFO) << " " << PrettyMethod(m) << " line " << record->stack[stack_frame].LineNumber();
2937 }
2938
2939 // pause periodically to help logcat catch up
2940 if ((count % 5) == 0) {
2941 usleep(40000);
2942 }
2943
2944 i = (i + 1) & (kNumAllocRecords-1);
2945 }
2946}
2947
2948class StringTable {
2949 public:
2950 StringTable() {
2951 }
2952
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002953 void Add(const char* s) {
Elliott Hughes545a0642011-11-08 19:10:03 -08002954 table_.insert(s);
2955 }
2956
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002957 size_t IndexOf(const char* s) {
Elliott Hughes545a0642011-11-08 19:10:03 -08002958 return std::distance(table_.begin(), table_.find(s));
2959 }
2960
2961 size_t Size() {
2962 return table_.size();
2963 }
2964
2965 void WriteTo(std::vector<uint8_t>& bytes) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002966 typedef std::set<const char*>::const_iterator It; // TODO: C++0x auto
Elliott Hughes545a0642011-11-08 19:10:03 -08002967 for (It it = table_.begin(); it != table_.end(); ++it) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002968 const char* s = *it;
2969 size_t s_len = CountModifiedUtf8Chars(s);
2970 UniquePtr<uint16_t> s_utf16(new uint16_t[s_len]);
2971 ConvertModifiedUtf8ToUtf16(s_utf16.get(), s);
2972 JDWP::AppendUtf16BE(bytes, s_utf16.get(), s_len);
Elliott Hughes545a0642011-11-08 19:10:03 -08002973 }
2974 }
2975
2976 private:
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002977 std::set<const char*> table_;
Elliott Hughes545a0642011-11-08 19:10:03 -08002978 DISALLOW_COPY_AND_ASSIGN(StringTable);
2979};
2980
2981/*
2982 * The data we send to DDMS contains everything we have recorded.
2983 *
2984 * Message header (all values big-endian):
2985 * (1b) message header len (to allow future expansion); includes itself
2986 * (1b) entry header len
2987 * (1b) stack frame len
2988 * (2b) number of entries
2989 * (4b) offset to string table from start of message
2990 * (2b) number of class name strings
2991 * (2b) number of method name strings
2992 * (2b) number of source file name strings
2993 * For each entry:
2994 * (4b) total allocation size
2995 * (2b) threadId
2996 * (2b) allocated object's class name index
2997 * (1b) stack depth
2998 * For each stack frame:
2999 * (2b) method's class name
3000 * (2b) method name
3001 * (2b) method source file
3002 * (2b) line number, clipped to 32767; -2 if native; -1 if no source
3003 * (xb) class name strings
3004 * (xb) method name strings
3005 * (xb) source file strings
3006 *
3007 * As with other DDM traffic, strings are sent as a 4-byte length
3008 * followed by UTF-16 data.
3009 *
3010 * We send up 16-bit unsigned indexes into string tables. In theory there
3011 * can be (kMaxAllocRecordStackDepth * kNumAllocRecords) unique strings in
3012 * each table, but in practice there should be far fewer.
3013 *
3014 * The chief reason for using a string table here is to keep the size of
3015 * the DDMS message to a minimum. This is partly to make the protocol
3016 * efficient, but also because we have to form the whole thing up all at
3017 * once in a memory buffer.
3018 *
3019 * We use separate string tables for class names, method names, and source
3020 * files to keep the indexes small. There will generally be no overlap
3021 * between the contents of these tables.
3022 */
3023jbyteArray Dbg::GetRecentAllocations() {
3024 if (false) {
3025 DumpRecentAllocations();
3026 }
3027
3028 MutexLock mu(gAllocTrackerLock);
3029
3030 /*
3031 * Part 1: generate string tables.
3032 */
3033 StringTable class_names;
3034 StringTable method_names;
3035 StringTable filenames;
3036
3037 int count = gAllocRecordCount;
3038 int idx = headIndex();
3039 while (count--) {
3040 AllocRecord* record = &recent_allocation_records_[idx];
3041
Elliott Hughes91250e02011-12-13 22:30:35 -08003042 class_names.Add(ClassHelper(record->type).GetDescriptor());
Elliott Hughes545a0642011-11-08 19:10:03 -08003043
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003044 MethodHelper mh;
Elliott Hughes545a0642011-11-08 19:10:03 -08003045 for (size_t i = 0; i < kMaxAllocRecordStackDepth; i++) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003046 Method* m = record->stack[i].method;
3047 mh.ChangeMethod(m);
Elliott Hughes545a0642011-11-08 19:10:03 -08003048 if (m != NULL) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003049 class_names.Add(mh.GetDeclaringClassDescriptor());
3050 method_names.Add(mh.GetName());
3051 filenames.Add(mh.GetDeclaringClassSourceFile());
Elliott Hughes545a0642011-11-08 19:10:03 -08003052 }
3053 }
3054
3055 idx = (idx + 1) & (kNumAllocRecords-1);
3056 }
3057
3058 LOG(INFO) << "allocation records: " << gAllocRecordCount;
3059
3060 /*
3061 * Part 2: allocate a buffer and generate the output.
3062 */
3063 std::vector<uint8_t> bytes;
3064
3065 // (1b) message header len (to allow future expansion); includes itself
3066 // (1b) entry header len
3067 // (1b) stack frame len
3068 const int kMessageHeaderLen = 15;
3069 const int kEntryHeaderLen = 9;
3070 const int kStackFrameLen = 8;
3071 JDWP::Append1BE(bytes, kMessageHeaderLen);
3072 JDWP::Append1BE(bytes, kEntryHeaderLen);
3073 JDWP::Append1BE(bytes, kStackFrameLen);
3074
3075 // (2b) number of entries
3076 // (4b) offset to string table from start of message
3077 // (2b) number of class name strings
3078 // (2b) number of method name strings
3079 // (2b) number of source file name strings
3080 JDWP::Append2BE(bytes, gAllocRecordCount);
3081 size_t string_table_offset = bytes.size();
3082 JDWP::Append4BE(bytes, 0); // We'll patch this later...
3083 JDWP::Append2BE(bytes, class_names.Size());
3084 JDWP::Append2BE(bytes, method_names.Size());
3085 JDWP::Append2BE(bytes, filenames.Size());
3086
3087 count = gAllocRecordCount;
3088 idx = headIndex();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003089 ClassHelper kh;
Elliott Hughes545a0642011-11-08 19:10:03 -08003090 while (count--) {
3091 // For each entry:
3092 // (4b) total allocation size
3093 // (2b) thread id
3094 // (2b) allocated object's class name index
3095 // (1b) stack depth
3096 AllocRecord* record = &recent_allocation_records_[idx];
3097 size_t stack_depth = record->GetDepth();
3098 JDWP::Append4BE(bytes, record->byte_count);
3099 JDWP::Append2BE(bytes, record->thin_lock_id);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003100 kh.ChangeClass(record->type);
Elliott Hughes91250e02011-12-13 22:30:35 -08003101 JDWP::Append2BE(bytes, class_names.IndexOf(kh.GetDescriptor()));
Elliott Hughes545a0642011-11-08 19:10:03 -08003102 JDWP::Append1BE(bytes, stack_depth);
3103
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003104 MethodHelper mh;
Elliott Hughes545a0642011-11-08 19:10:03 -08003105 for (size_t stack_frame = 0; stack_frame < stack_depth; ++stack_frame) {
3106 // For each stack frame:
3107 // (2b) method's class name
3108 // (2b) method name
3109 // (2b) method source file
3110 // (2b) line number, clipped to 32767; -2 if native; -1 if no source
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003111 mh.ChangeMethod(record->stack[stack_frame].method);
3112 JDWP::Append2BE(bytes, class_names.IndexOf(mh.GetDeclaringClassDescriptor()));
3113 JDWP::Append2BE(bytes, method_names.IndexOf(mh.GetName()));
3114 JDWP::Append2BE(bytes, filenames.IndexOf(mh.GetDeclaringClassSourceFile()));
Elliott Hughes545a0642011-11-08 19:10:03 -08003115 JDWP::Append2BE(bytes, record->stack[stack_frame].LineNumber());
3116 }
3117
3118 idx = (idx + 1) & (kNumAllocRecords-1);
3119 }
3120
3121 // (xb) class name strings
3122 // (xb) method name strings
3123 // (xb) source file strings
3124 JDWP::Set4BE(&bytes[string_table_offset], bytes.size());
3125 class_names.WriteTo(bytes);
3126 method_names.WriteTo(bytes);
3127 filenames.WriteTo(bytes);
3128
3129 JNIEnv* env = Thread::Current()->GetJniEnv();
3130 jbyteArray result = env->NewByteArray(bytes.size());
3131 if (result != NULL) {
3132 env->SetByteArrayRegion(result, 0, bytes.size(), reinterpret_cast<const jbyte*>(&bytes[0]));
3133 }
3134 return result;
3135}
3136
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003137} // namespace art