blob: 12d403450ff48a1597835a6634952872a4e67877 [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"
Ian Rogers30fab402012-01-23 15:43:46 -080030#include "space.h"
Elliott Hughes47fce012011-10-25 18:37:19 -070031#include "stack_indirect_reference_table.h"
Elliott Hughes475fc232011-10-25 15:00:35 -070032#include "thread_list.h"
33
Elliott Hughes6a5bd492011-10-28 14:33:57 -070034extern "C" void dlmalloc_walk_heap(void(*)(const void*, size_t, const void*, size_t, void*), void*);
35#ifndef HAVE_ANDROID_OS
36void dlmalloc_walk_heap(void(*)(const void*, size_t, const void*, size_t, void*), void*) {
37 // No-op for glibc.
38}
39#endif
40
Elliott Hughes872d4ec2011-10-21 17:07:15 -070041namespace art {
42
Elliott Hughes545a0642011-11-08 19:10:03 -080043static const size_t kMaxAllocRecordStackDepth = 16; // Max 255.
44static const size_t kNumAllocRecords = 512; // Must be power of 2.
45
Elliott Hughes475fc232011-10-25 15:00:35 -070046class ObjectRegistry {
47 public:
48 ObjectRegistry() : lock_("ObjectRegistry lock") {
49 }
50
51 JDWP::ObjectId Add(Object* o) {
52 if (o == NULL) {
53 return 0;
54 }
55 JDWP::ObjectId id = static_cast<JDWP::ObjectId>(reinterpret_cast<uintptr_t>(o));
56 MutexLock mu(lock_);
57 map_[id] = o;
58 return id;
59 }
60
Elliott Hughes234ab152011-10-26 14:02:26 -070061 void Clear() {
62 MutexLock mu(lock_);
63 LOG(DEBUG) << "Debugger has detached; object registry had " << map_.size() << " entries";
64 map_.clear();
65 }
66
Elliott Hughes475fc232011-10-25 15:00:35 -070067 bool Contains(JDWP::ObjectId id) {
68 MutexLock mu(lock_);
69 return map_.find(id) != map_.end();
70 }
71
Elliott Hughesa2155262011-11-16 16:26:58 -080072 template<typename T> T Get(JDWP::ObjectId id) {
73 MutexLock mu(lock_);
74 typedef std::map<JDWP::ObjectId, Object*>::iterator It; // C++0x auto
75 It it = map_.find(id);
76 return (it != map_.end()) ? reinterpret_cast<T>(it->second) : NULL;
77 }
78
Elliott Hughesbfe487b2011-10-26 15:48:55 -070079 void VisitRoots(Heap::RootVisitor* visitor, void* arg) {
80 MutexLock mu(lock_);
81 typedef std::map<JDWP::ObjectId, Object*>::iterator It; // C++0x auto
82 for (It it = map_.begin(); it != map_.end(); ++it) {
83 visitor(it->second, arg);
84 }
85 }
86
Elliott Hughes475fc232011-10-25 15:00:35 -070087 private:
88 Mutex lock_;
89 std::map<JDWP::ObjectId, Object*> map_;
90};
91
Elliott Hughes545a0642011-11-08 19:10:03 -080092struct AllocRecordStackTraceElement {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080093 Method* method;
Elliott Hughes545a0642011-11-08 19:10:03 -080094 uintptr_t raw_pc;
95
96 int32_t LineNumber() const {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080097 return MethodHelper(method).GetLineNumFromNativePC(raw_pc);
Elliott Hughes545a0642011-11-08 19:10:03 -080098 }
99};
100
101struct AllocRecord {
102 Class* type;
103 size_t byte_count;
104 uint16_t thin_lock_id;
105 AllocRecordStackTraceElement stack[kMaxAllocRecordStackDepth]; // Unused entries have NULL method.
106
107 size_t GetDepth() {
108 size_t depth = 0;
109 while (depth < kMaxAllocRecordStackDepth && stack[depth].method != NULL) {
110 ++depth;
111 }
112 return depth;
113 }
114};
115
Elliott Hughes86964332012-02-15 19:37:42 -0800116struct Breakpoint {
117 Method* method;
118 uint32_t pc;
119 Breakpoint(Method* method, uint32_t pc) : method(method), pc(pc) {}
120};
121
122static std::ostream& operator<<(std::ostream& os, const Breakpoint& rhs) {
123 os << "Breakpoint[" << PrettyMethod(rhs.method) << " @" << rhs.pc << "]";
124 return os;
125}
126
127struct SingleStepControl {
128 // Are we single-stepping right now?
129 bool is_active;
130 Thread* thread;
131
132 JDWP::JdwpStepSize step_size;
133 JDWP::JdwpStepDepth step_depth;
134
135 const Method* method;
Elliott Hughes2435a572012-02-17 16:07:41 -0800136 int32_t line_number; // Or -1 for native methods.
137 std::set<uint32_t> dex_pcs;
Elliott Hughes86964332012-02-15 19:37:42 -0800138 int stack_depth;
139};
140
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700141// JDWP is allowed unless the Zygote forbids it.
142static bool gJdwpAllowed = true;
143
Elliott Hughes3bb81562011-10-21 18:52:59 -0700144// Was there a -Xrunjdwp or -agent argument on the command-line?
145static bool gJdwpConfigured = false;
146
147// Broken-down JDWP options. (Only valid if gJdwpConfigured is true.)
Elliott Hughes376a7a02011-10-24 18:35:55 -0700148static JDWP::JdwpOptions gJdwpOptions;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700149
150// Runtime JDWP state.
151static JDWP::JdwpState* gJdwpState = NULL;
152static bool gDebuggerConnected; // debugger or DDMS is connected.
153static bool gDebuggerActive; // debugger is making requests.
Elliott Hughes86964332012-02-15 19:37:42 -0800154static bool gDisposed; // debugger called VirtualMachine.Dispose, so we should drop the connection.
Elliott Hughes3bb81562011-10-21 18:52:59 -0700155
Elliott Hughes47fce012011-10-25 18:37:19 -0700156static bool gDdmThreadNotification = false;
157
Elliott Hughes767a1472011-10-26 18:49:02 -0700158// DDMS GC-related settings.
159static Dbg::HpifWhen gDdmHpifWhen = Dbg::HPIF_WHEN_NEVER;
160static Dbg::HpsgWhen gDdmHpsgWhen = Dbg::HPSG_WHEN_NEVER;
161static Dbg::HpsgWhat gDdmHpsgWhat;
162static Dbg::HpsgWhen gDdmNhsgWhen = Dbg::HPSG_WHEN_NEVER;
163static Dbg::HpsgWhat gDdmNhsgWhat;
164
Elliott Hughes475fc232011-10-25 15:00:35 -0700165static ObjectRegistry* gRegistry = NULL;
166
Elliott Hughes545a0642011-11-08 19:10:03 -0800167// Recent allocation tracking.
168static Mutex gAllocTrackerLock("AllocTracker lock");
169AllocRecord* Dbg::recent_allocation_records_ = NULL; // TODO: CircularBuffer<AllocRecord>
170static size_t gAllocRecordHead = 0;
171static size_t gAllocRecordCount = 0;
172
Elliott Hughes86964332012-02-15 19:37:42 -0800173// Breakpoints and single-stepping.
174static Mutex gBreakpointsLock("breakpoints lock");
175static std::vector<Breakpoint> gBreakpoints;
176static SingleStepControl gSingleStepControl;
177
178static bool IsBreakpoint(Method* m, uint32_t dex_pc) {
179 MutexLock mu(gBreakpointsLock);
180 for (size_t i = 0; i < gBreakpoints.size(); ++i) {
181 if (gBreakpoints[i].method == m && gBreakpoints[i].pc == dex_pc) {
182 VLOG(jdwp) << "Hit breakpoint #" << i << ": " << gBreakpoints[i];
183 return true;
184 }
185 }
186 return false;
187}
188
Elliott Hughes24437992011-11-30 14:49:33 -0800189static JDWP::JdwpTag BasicTagFromDescriptor(const char* descriptor) {
190 // JDWP deliberately uses the descriptor characters' ASCII values for its enum.
191 // Note that by "basic" we mean that we don't get more specific than JT_OBJECT.
192 return static_cast<JDWP::JdwpTag>(descriptor[0]);
193}
194
195static JDWP::JdwpTag TagFromClass(Class* c) {
Elliott Hughes86b00102011-12-05 17:54:26 -0800196 CHECK(c != NULL);
Elliott Hughes24437992011-11-30 14:49:33 -0800197 if (c->IsArrayClass()) {
198 return JDWP::JT_ARRAY;
199 }
200
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800201 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Elliott Hughes24437992011-11-30 14:49:33 -0800202 if (c->IsStringClass()) {
203 return JDWP::JT_STRING;
204 } else if (c->IsClassClass()) {
205 return JDWP::JT_CLASS_OBJECT;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800206 } else if (class_linker->FindSystemClass("Ljava/lang/Thread;")->IsAssignableFrom(c)) {
Elliott Hughes24437992011-11-30 14:49:33 -0800207 return JDWP::JT_THREAD;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800208 } else if (class_linker->FindSystemClass("Ljava/lang/ThreadGroup;")->IsAssignableFrom(c)) {
Elliott Hughes24437992011-11-30 14:49:33 -0800209 return JDWP::JT_THREAD_GROUP;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800210 } else if (class_linker->FindSystemClass("Ljava/lang/ClassLoader;")->IsAssignableFrom(c)) {
Elliott Hughes24437992011-11-30 14:49:33 -0800211 return JDWP::JT_CLASS_LOADER;
Elliott Hughes24437992011-11-30 14:49:33 -0800212 } else {
213 return JDWP::JT_OBJECT;
214 }
215}
216
217/*
218 * Objects declared to hold Object might actually hold a more specific
219 * type. The debugger may take a special interest in these (e.g. it
220 * wants to display the contents of Strings), so we want to return an
221 * appropriate tag.
222 *
223 * Null objects are tagged JT_OBJECT.
224 */
225static JDWP::JdwpTag TagFromObject(const Object* o) {
226 return (o == NULL) ? JDWP::JT_OBJECT : TagFromClass(o->GetClass());
227}
228
229static bool IsPrimitiveTag(JDWP::JdwpTag tag) {
230 switch (tag) {
231 case JDWP::JT_BOOLEAN:
232 case JDWP::JT_BYTE:
233 case JDWP::JT_CHAR:
234 case JDWP::JT_FLOAT:
235 case JDWP::JT_DOUBLE:
236 case JDWP::JT_INT:
237 case JDWP::JT_LONG:
238 case JDWP::JT_SHORT:
239 case JDWP::JT_VOID:
240 return true;
241 default:
242 return false;
243 }
244}
245
Elliott Hughes3bb81562011-10-21 18:52:59 -0700246/*
247 * Handle one of the JDWP name/value pairs.
248 *
249 * JDWP options are:
250 * help: if specified, show help message and bail
251 * transport: may be dt_socket or dt_shmem
252 * address: for dt_socket, "host:port", or just "port" when listening
253 * server: if "y", wait for debugger to attach; if "n", attach to debugger
254 * timeout: how long to wait for debugger to connect / listen
255 *
256 * Useful with server=n (these aren't supported yet):
257 * onthrow=<exception-name>: connect to debugger when exception thrown
258 * onuncaught=y|n: connect to debugger when uncaught exception thrown
259 * launch=<command-line>: launch the debugger itself
260 *
261 * The "transport" option is required, as is "address" if server=n.
262 */
263static bool ParseJdwpOption(const std::string& name, const std::string& value) {
264 if (name == "transport") {
265 if (value == "dt_socket") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700266 gJdwpOptions.transport = JDWP::kJdwpTransportSocket;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700267 } else if (value == "dt_android_adb") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700268 gJdwpOptions.transport = JDWP::kJdwpTransportAndroidAdb;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700269 } else {
270 LOG(ERROR) << "JDWP transport not supported: " << value;
271 return false;
272 }
273 } else if (name == "server") {
274 if (value == "n") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700275 gJdwpOptions.server = false;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700276 } else if (value == "y") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700277 gJdwpOptions.server = true;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700278 } else {
279 LOG(ERROR) << "JDWP option 'server' must be 'y' or 'n'";
280 return false;
281 }
282 } else if (name == "suspend") {
283 if (value == "n") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700284 gJdwpOptions.suspend = false;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700285 } else if (value == "y") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700286 gJdwpOptions.suspend = true;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700287 } else {
288 LOG(ERROR) << "JDWP option 'suspend' must be 'y' or 'n'";
289 return false;
290 }
291 } else if (name == "address") {
292 /* this is either <port> or <host>:<port> */
293 std::string port_string;
Elliott Hughes376a7a02011-10-24 18:35:55 -0700294 gJdwpOptions.host.clear();
Elliott Hughes3bb81562011-10-21 18:52:59 -0700295 std::string::size_type colon = value.find(':');
296 if (colon != std::string::npos) {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700297 gJdwpOptions.host = value.substr(0, colon);
Elliott Hughes3bb81562011-10-21 18:52:59 -0700298 port_string = value.substr(colon + 1);
299 } else {
300 port_string = value;
301 }
302 if (port_string.empty()) {
303 LOG(ERROR) << "JDWP address missing port: " << value;
304 return false;
305 }
306 char* end;
Elliott Hughesba8eee12012-01-24 20:25:24 -0800307 uint64_t port = strtoul(port_string.c_str(), &end, 10);
308 if (*end != '\0' || port > 0xffff) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700309 LOG(ERROR) << "JDWP address has junk in port field: " << value;
310 return false;
311 }
Elliott Hughes376a7a02011-10-24 18:35:55 -0700312 gJdwpOptions.port = port;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700313 } else if (name == "launch" || name == "onthrow" || name == "oncaught" || name == "timeout") {
314 /* valid but unsupported */
315 LOG(INFO) << "Ignoring JDWP option '" << name << "'='" << value << "'";
316 } else {
317 LOG(INFO) << "Ignoring unrecognized JDWP option '" << name << "'='" << value << "'";
318 }
319
320 return true;
321}
322
323/*
324 * Parse the latter half of a -Xrunjdwp/-agentlib:jdwp= string, e.g.:
325 * "transport=dt_socket,address=8000,server=y,suspend=n"
326 */
327bool Dbg::ParseJdwpOptions(const std::string& options) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800328 VLOG(jdwp) << "ParseJdwpOptions: " << options;
Elliott Hughes47fce012011-10-25 18:37:19 -0700329
Elliott Hughes3bb81562011-10-21 18:52:59 -0700330 std::vector<std::string> pairs;
331 Split(options, ',', pairs);
332
333 for (size_t i = 0; i < pairs.size(); ++i) {
334 std::string::size_type equals = pairs[i].find('=');
335 if (equals == std::string::npos) {
336 LOG(ERROR) << "Can't parse JDWP option '" << pairs[i] << "' in '" << options << "'";
337 return false;
338 }
339 ParseJdwpOption(pairs[i].substr(0, equals), pairs[i].substr(equals + 1));
340 }
341
Elliott Hughes376a7a02011-10-24 18:35:55 -0700342 if (gJdwpOptions.transport == JDWP::kJdwpTransportUnknown) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700343 LOG(ERROR) << "Must specify JDWP transport: " << options;
344 }
Elliott Hughes376a7a02011-10-24 18:35:55 -0700345 if (!gJdwpOptions.server && (gJdwpOptions.host.empty() || gJdwpOptions.port == 0)) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700346 LOG(ERROR) << "Must specify JDWP host and port when server=n: " << options;
347 return false;
348 }
349
350 gJdwpConfigured = true;
351 return true;
352}
353
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700354void Dbg::StartJdwp() {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700355 if (!gJdwpAllowed || !gJdwpConfigured) {
356 // No JDWP for you!
357 return;
358 }
359
Elliott Hughes475fc232011-10-25 15:00:35 -0700360 CHECK(gRegistry == NULL);
361 gRegistry = new ObjectRegistry;
362
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700363 // Init JDWP if the debugger is enabled. This may connect out to a
364 // debugger, passively listen for a debugger, or block waiting for a
365 // debugger.
Elliott Hughes376a7a02011-10-24 18:35:55 -0700366 gJdwpState = JDWP::JdwpState::Create(&gJdwpOptions);
367 if (gJdwpState == NULL) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -0800368 // We probably failed because some other process has the port already, which means that
369 // if we don't abort the user is likely to think they're talking to us when they're actually
370 // talking to that other process.
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800371 LOG(FATAL) << "Debugger thread failed to initialize";
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700372 }
373
374 // If a debugger has already attached, send the "welcome" message.
375 // This may cause us to suspend all threads.
Elliott Hughes376a7a02011-10-24 18:35:55 -0700376 if (gJdwpState->IsActive()) {
Elliott Hughesa2155262011-11-16 16:26:58 -0800377 //ScopedThreadStateChange tsc(Thread::Current(), Thread::kRunnable);
Elliott Hughes376a7a02011-10-24 18:35:55 -0700378 if (!gJdwpState->PostVMStart()) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800379 LOG(WARNING) << "Failed to post 'start' message to debugger";
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700380 }
381 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700382}
383
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700384void Dbg::StopJdwp() {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700385 delete gJdwpState;
Elliott Hughes475fc232011-10-25 15:00:35 -0700386 delete gRegistry;
387 gRegistry = NULL;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700388}
389
Elliott Hughes767a1472011-10-26 18:49:02 -0700390void Dbg::GcDidFinish() {
391 if (gDdmHpifWhen != HPIF_WHEN_NEVER) {
392 LOG(DEBUG) << "Sending VM heap info to DDM";
Elliott Hughes7162ad92011-10-27 14:08:42 -0700393 DdmSendHeapInfo(gDdmHpifWhen);
Elliott Hughes767a1472011-10-26 18:49:02 -0700394 }
395 if (gDdmHpsgWhen != HPSG_WHEN_NEVER) {
396 LOG(DEBUG) << "Dumping VM heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700397 DdmSendHeapSegments(false);
Elliott Hughes767a1472011-10-26 18:49:02 -0700398 }
399 if (gDdmNhsgWhen != HPSG_WHEN_NEVER) {
400 LOG(DEBUG) << "Dumping native heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700401 DdmSendHeapSegments(true);
Elliott Hughes767a1472011-10-26 18:49:02 -0700402 }
403}
404
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700405void Dbg::SetJdwpAllowed(bool allowed) {
406 gJdwpAllowed = allowed;
407}
408
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700409DebugInvokeReq* Dbg::GetInvokeReq() {
Elliott Hughes475fc232011-10-25 15:00:35 -0700410 return Thread::Current()->GetInvokeReq();
411}
412
413Thread* Dbg::GetDebugThread() {
414 return (gJdwpState != NULL) ? gJdwpState->GetDebugThread() : NULL;
415}
416
417void Dbg::ClearWaitForEventThread() {
418 gJdwpState->ClearWaitForEventThread();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700419}
420
421void Dbg::Connected() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700422 CHECK(!gDebuggerConnected);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800423 VLOG(jdwp) << "JDWP has attached";
Elliott Hughes3bb81562011-10-21 18:52:59 -0700424 gDebuggerConnected = true;
Elliott Hughes86964332012-02-15 19:37:42 -0800425 gDisposed = false;
426}
427
428void Dbg::Disposed() {
429 gDisposed = true;
430}
431
432bool Dbg::IsDisposed() {
433 return gDisposed;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700434}
435
Elliott Hughesa2155262011-11-16 16:26:58 -0800436void Dbg::GoActive() {
437 // Enable all debugging features, including scans for breakpoints.
438 // This is a no-op if we're already active.
439 // Only called from the JDWP handler thread.
440 if (gDebuggerActive) {
441 return;
442 }
443
444 LOG(INFO) << "Debugger is active";
445
446 // TODO: CHECK we don't have any outstanding breakpoints.
447
448 gDebuggerActive = true;
449
450 //dvmEnableAllSubMode(kSubModeDebuggerActive);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700451}
452
453void Dbg::Disconnected() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700454 CHECK(gDebuggerConnected);
455
456 gDebuggerActive = false;
457
458 //dvmDisableAllSubMode(kSubModeDebuggerActive);
459
460 gRegistry->Clear();
461 gDebuggerConnected = false;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700462}
463
464bool Dbg::IsDebuggerConnected() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700465 return gDebuggerActive;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700466}
467
468bool Dbg::IsDebuggingEnabled() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700469 return gJdwpConfigured;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700470}
471
472int64_t Dbg::LastDebuggerActivity() {
Elliott Hughesca951522011-12-05 12:01:32 -0800473 return gJdwpState->LastDebuggerActivity();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700474}
475
476int Dbg::ThreadRunning() {
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700477 return static_cast<int>(Thread::Current()->SetState(Thread::kRunnable));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700478}
479
480int Dbg::ThreadWaiting() {
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700481 return static_cast<int>(Thread::Current()->SetState(Thread::kVmWait));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700482}
483
Elliott Hughes6ba581a2011-10-25 11:45:35 -0700484int Dbg::ThreadContinuing(int new_state) {
485 return static_cast<int>(Thread::Current()->SetState(static_cast<Thread::State>(new_state)));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700486}
487
488void Dbg::UndoDebuggerSuspensions() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700489 Runtime::Current()->GetThreadList()->UndoDebuggerSuspensions();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700490}
491
492void Dbg::Exit(int status) {
Elliott Hughes1bba14f2011-12-01 18:00:36 -0800493 exit(status); // This is all dalvik did.
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700494}
495
Elliott Hughesbfe487b2011-10-26 15:48:55 -0700496void Dbg::VisitRoots(Heap::RootVisitor* visitor, void* arg) {
497 if (gRegistry != NULL) {
498 gRegistry->VisitRoots(visitor, arg);
499 }
500}
501
Elliott Hughesc308a5d2012-02-16 17:12:06 -0800502std::string Dbg::GetClassName(JDWP::RefTypeId classId) {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800503 Object* o = gRegistry->Get<Object*>(classId);
504 if (o == NULL || !o->IsClass()) {
505 return StringPrintf("non-class %p", o); // This is only used for debugging output anyway.
506 }
Elliott Hughesc308a5d2012-02-16 17:12:06 -0800507 return DescriptorToName(ClassHelper(o->AsClass()).GetDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700508}
509
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800510bool Dbg::GetClassObject(JDWP::RefTypeId id, JDWP::ObjectId& classObjectId) {
511 Object* o = gRegistry->Get<Object*>(id);
512 if (o == NULL || !o->IsClass()) {
513 return false;
514 }
515 classObjectId = gRegistry->Add(o);
516 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700517}
518
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800519static Array* DecodeArray(JDWP::RefTypeId id, JDWP::JdwpError& status) {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800520 Object* o = gRegistry->Get<Object*>(id);
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800521 if (o == NULL) {
522 status = JDWP::ERR_INVALID_OBJECT;
523 return NULL;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800524 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800525 if (!o->IsArrayInstance()) {
526 status = JDWP::ERR_INVALID_ARRAY;
527 return NULL;
528 }
529 status = JDWP::ERR_NONE;
530 return o->AsArray();
531}
532
533// TODO: this should probably be used everywhere we're converting a RefTypeId to a Class*.
534static Class* DecodeClass(JDWP::RefTypeId id, JDWP::JdwpError& status) {
535 Object* o = gRegistry->Get<Object*>(id);
536 if (o == NULL) {
537 status = JDWP::ERR_INVALID_OBJECT;
538 return NULL;
539 }
540 if (!o->IsClass()) {
541 status = JDWP::ERR_INVALID_CLASS;
542 return NULL;
543 }
544 status = JDWP::ERR_NONE;
545 return o->AsClass();
546}
547
Elliott Hughes86964332012-02-15 19:37:42 -0800548static Thread* DecodeThread(JDWP::ObjectId threadId) {
549 Object* thread_peer = gRegistry->Get<Object*>(threadId);
Elliott Hughes2435a572012-02-17 16:07:41 -0800550 if (thread_peer == NULL) {
551 return NULL;
552 }
Elliott Hughes86964332012-02-15 19:37:42 -0800553 return Thread::FromManagedThread(thread_peer);
554}
555
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800556JDWP::JdwpError Dbg::GetSuperclass(JDWP::RefTypeId id, JDWP::RefTypeId& superclassId) {
557 JDWP::JdwpError status;
558 Class* c = DecodeClass(id, status);
559 if (c == NULL) {
560 return status;
561 }
562 if (c->IsInterface()) {
563 // http://code.google.com/p/android/issues/detail?id=20856
564 superclassId = NULL;
565 } else {
566 superclassId = gRegistry->Add(c->GetSuperClass());
567 }
568 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700569}
570
571JDWP::ObjectId Dbg::GetClassLoader(JDWP::RefTypeId id) {
Elliott Hughes1bba14f2011-12-01 18:00:36 -0800572 Object* o = gRegistry->Get<Object*>(id);
573 return gRegistry->Add(o->GetClass()->GetClassLoader());
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700574}
575
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800576bool Dbg::GetAccessFlags(JDWP::RefTypeId id, uint32_t& access_flags) {
577 Object* o = gRegistry->Get<Object*>(id);
578 if (o == NULL || !o->IsClass()) {
579 return false;
580 }
581 access_flags = o->AsClass()->GetAccessFlags() & kAccJavaFlagsMask;
582 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700583}
584
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800585bool Dbg::IsInterface(JDWP::RefTypeId classId, bool& is_interface) {
586 Object* o = gRegistry->Get<Object*>(classId);
587 if (o == NULL || !o->IsClass()) {
588 return false;
589 }
590 is_interface = o->AsClass()->IsInterface();
591 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700592}
593
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800594void Dbg::GetClassList(std::vector<JDWP::RefTypeId>& classes) {
Elliott Hughesa2155262011-11-16 16:26:58 -0800595 // Get the complete list of reference classes (i.e. all classes except
596 // the primitive types).
597 // Returns a newly-allocated buffer full of RefTypeId values.
598 struct ClassListCreator {
Elliott Hughesba8eee12012-01-24 20:25:24 -0800599 explicit ClassListCreator(std::vector<JDWP::RefTypeId>& classes) : classes(classes) {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800600 }
601
Elliott Hughesa2155262011-11-16 16:26:58 -0800602 static bool Visit(Class* c, void* arg) {
603 return reinterpret_cast<ClassListCreator*>(arg)->Visit(c);
604 }
605
606 bool Visit(Class* c) {
607 if (!c->IsPrimitive()) {
608 classes.push_back(static_cast<JDWP::RefTypeId>(gRegistry->Add(c)));
609 }
610 return true;
611 }
612
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800613 std::vector<JDWP::RefTypeId>& classes;
Elliott Hughesa2155262011-11-16 16:26:58 -0800614 };
615
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800616 ClassListCreator clc(classes);
Elliott Hughesa2155262011-11-16 16:26:58 -0800617 Runtime::Current()->GetClassLinker()->VisitClasses(ClassListCreator::Visit, &clc);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700618}
619
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800620bool Dbg::GetClassInfo(JDWP::RefTypeId classId, JDWP::JdwpTypeTag* pTypeTag, uint32_t* pStatus, std::string* pDescriptor) {
621 Object* o = gRegistry->Get<Object*>(classId);
622 if (o == NULL || !o->IsClass()) {
623 return false;
624 }
625
626 Class* c = o->AsClass();
Elliott Hughesa2155262011-11-16 16:26:58 -0800627 if (c->IsArrayClass()) {
628 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
629 *pTypeTag = JDWP::TT_ARRAY;
630 } else {
631 if (c->IsErroneous()) {
632 *pStatus = JDWP::CS_ERROR;
633 } else {
634 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED | JDWP::CS_INITIALIZED;
635 }
636 *pTypeTag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
637 }
638
639 if (pDescriptor != NULL) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800640 *pDescriptor = ClassHelper(c).GetDescriptor();
Elliott Hughesa2155262011-11-16 16:26:58 -0800641 }
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800642 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700643}
644
Elliott Hughesc3b77c72011-12-15 20:56:48 -0800645void Dbg::FindLoadedClassBySignature(const char* descriptor, std::vector<JDWP::RefTypeId>& ids) {
Elliott Hughes6fa602d2011-12-02 17:54:25 -0800646 std::vector<Class*> classes;
647 Runtime::Current()->GetClassLinker()->LookupClasses(descriptor, classes);
648 ids.clear();
649 for (size_t i = 0; i < classes.size(); ++i) {
650 ids.push_back(gRegistry->Add(classes[i]));
651 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700652}
653
Elliott Hughes2435a572012-02-17 16:07:41 -0800654JDWP::JdwpError Dbg::GetReferenceType(JDWP::ObjectId objectId, JDWP::ExpandBuf* pReply) {
Elliott Hughes499c5132011-11-17 14:55:11 -0800655 Object* o = gRegistry->Get<Object*>(objectId);
Elliott Hughes2435a572012-02-17 16:07:41 -0800656 if (o == NULL) {
657 return JDWP::ERR_INVALID_OBJECT;
Elliott Hughes499c5132011-11-17 14:55:11 -0800658 }
Elliott Hughes2435a572012-02-17 16:07:41 -0800659
660 JDWP::JdwpTypeTag type_tag;
661 if (o->GetClass()->IsArrayClass()) {
662 type_tag = JDWP::TT_ARRAY;
663 } else if (o->GetClass()->IsInterface()) {
664 type_tag = JDWP::TT_INTERFACE;
665 } else {
666 type_tag = JDWP::TT_CLASS;
667 }
668 JDWP::RefTypeId type_id = gRegistry->Add(o->GetClass());
669
670 expandBufAdd1(pReply, type_tag);
671 expandBufAddRefTypeId(pReply, type_id);
672
673 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700674}
675
Elliott Hughes1fe7afb2012-02-13 17:23:03 -0800676JDWP::JdwpError Dbg::GetSignature(JDWP::RefTypeId refTypeId, std::string& signature) {
677 JDWP::JdwpError status;
678 Class* c = DecodeClass(refTypeId, status);
679 if (c == NULL) {
680 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800681 }
Elliott Hughes1fe7afb2012-02-13 17:23:03 -0800682 signature = ClassHelper(c).GetDescriptor();
683 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700684}
685
Elliott Hughes03181a82011-11-17 17:22:21 -0800686bool Dbg::GetSourceFile(JDWP::RefTypeId refTypeId, std::string& result) {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800687 Object* o = gRegistry->Get<Object*>(refTypeId);
688 if (o == NULL || !o->IsClass()) {
689 return false;
690 }
691 result = ClassHelper(o->AsClass()).GetSourceFile();
692 return result != NULL;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700693}
694
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700695uint8_t Dbg::GetObjectTag(JDWP::ObjectId objectId) {
Elliott Hughes24437992011-11-30 14:49:33 -0800696 Object* o = gRegistry->Get<Object*>(objectId);
697 return TagFromObject(o);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700698}
699
Elliott Hughesaed4be92011-12-02 16:16:23 -0800700size_t Dbg::GetTagWidth(JDWP::JdwpTag tag) {
Elliott Hughesdbb40792011-11-18 17:05:22 -0800701 switch (tag) {
702 case JDWP::JT_VOID:
703 return 0;
704 case JDWP::JT_BYTE:
705 case JDWP::JT_BOOLEAN:
706 return 1;
707 case JDWP::JT_CHAR:
708 case JDWP::JT_SHORT:
709 return 2;
710 case JDWP::JT_FLOAT:
711 case JDWP::JT_INT:
712 return 4;
713 case JDWP::JT_ARRAY:
714 case JDWP::JT_OBJECT:
715 case JDWP::JT_STRING:
716 case JDWP::JT_THREAD:
717 case JDWP::JT_THREAD_GROUP:
718 case JDWP::JT_CLASS_LOADER:
719 case JDWP::JT_CLASS_OBJECT:
720 return sizeof(JDWP::ObjectId);
721 case JDWP::JT_DOUBLE:
722 case JDWP::JT_LONG:
723 return 8;
724 default:
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800725 LOG(FATAL) << "Unknown tag " << tag;
Elliott Hughesdbb40792011-11-18 17:05:22 -0800726 return -1;
727 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700728}
729
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800730JDWP::JdwpError Dbg::GetArrayLength(JDWP::ObjectId arrayId, int& length) {
731 JDWP::JdwpError status;
732 Array* a = DecodeArray(arrayId, status);
733 if (a == NULL) {
734 return status;
Elliott Hughes24437992011-11-30 14:49:33 -0800735 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800736 length = a->GetLength();
737 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700738}
739
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800740JDWP::JdwpError Dbg::OutputArray(JDWP::ObjectId arrayId, int offset, int count, JDWP::ExpandBuf* pReply) {
741 JDWP::JdwpError status;
742 Array* a = DecodeArray(arrayId, status);
743 if (a == NULL) {
744 return status;
745 }
Elliott Hughes24437992011-11-30 14:49:33 -0800746
747 if (offset < 0 || count < 0 || offset > a->GetLength() || a->GetLength() - offset < count) {
748 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800749 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughes24437992011-11-30 14:49:33 -0800750 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800751 std::string descriptor(ClassHelper(a->GetClass()).GetDescriptor());
Elliott Hughes24437992011-11-30 14:49:33 -0800752 JDWP::JdwpTag tag = BasicTagFromDescriptor(descriptor.c_str() + 1);
753
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800754 expandBufAdd1(pReply, tag);
755 expandBufAdd4BE(pReply, count);
756
Elliott Hughes24437992011-11-30 14:49:33 -0800757 if (IsPrimitiveTag(tag)) {
758 size_t width = GetTagWidth(tag);
759 const uint8_t* src = reinterpret_cast<uint8_t*>(a->GetRawData());
760 uint8_t* dst = expandBufAddSpace(pReply, count * width);
761 if (width == 8) {
762 const uint64_t* src8 = reinterpret_cast<const uint64_t*>(src);
763 for (int i = 0; i < count; ++i) JDWP::Write8BE(&dst, src8[offset + i]);
764 } else if (width == 4) {
765 const uint32_t* src4 = reinterpret_cast<const uint32_t*>(src);
766 for (int i = 0; i < count; ++i) JDWP::Write4BE(&dst, src4[offset + i]);
767 } else if (width == 2) {
768 const uint16_t* src2 = reinterpret_cast<const uint16_t*>(src);
769 for (int i = 0; i < count; ++i) JDWP::Write2BE(&dst, src2[offset + i]);
770 } else {
771 memcpy(dst, &src[offset * width], count * width);
772 }
773 } else {
774 ObjectArray<Object>* oa = a->AsObjectArray<Object>();
775 for (int i = 0; i < count; ++i) {
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800776 Object* element = oa->Get(offset + i);
Elliott Hughes24437992011-11-30 14:49:33 -0800777 JDWP::JdwpTag specific_tag = (element != NULL) ? TagFromObject(element) : tag;
778 expandBufAdd1(pReply, specific_tag);
779 expandBufAddObjectId(pReply, gRegistry->Add(element));
780 }
781 }
782
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800783 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700784}
785
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800786JDWP::JdwpError Dbg::SetArrayElements(JDWP::ObjectId arrayId, int offset, int count, const uint8_t* src) {
787 JDWP::JdwpError status;
788 Array* a = DecodeArray(arrayId, status);
789 if (a == NULL) {
790 return status;
791 }
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800792
793 if (offset < 0 || count < 0 || offset > a->GetLength() || a->GetLength() - offset < count) {
794 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800795 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800796 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800797 std::string descriptor(ClassHelper(a->GetClass()).GetDescriptor());
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800798 JDWP::JdwpTag tag = BasicTagFromDescriptor(descriptor.c_str() + 1);
799
800 if (IsPrimitiveTag(tag)) {
801 size_t width = GetTagWidth(tag);
802 uint8_t* dst = &(reinterpret_cast<uint8_t*>(a->GetRawData())[offset * width]);
803 if (width == 8) {
804 for (int i = 0; i < count; ++i) {
805 // Handle potentially non-aligned memory access one byte at a time for ARM's benefit.
806 uint64_t value;
807 for (size_t j = 0; j < sizeof(uint64_t); ++j) reinterpret_cast<uint8_t*>(&value)[j] = src[j];
808 src += sizeof(uint64_t);
809 JDWP::Write8BE(&dst, value);
810 }
811 } else if (width == 4) {
812 const uint32_t* src4 = reinterpret_cast<const uint32_t*>(src);
813 for (int i = 0; i < count; ++i) JDWP::Write4BE(&dst, src4[i]);
814 } else if (width == 2) {
815 const uint16_t* src2 = reinterpret_cast<const uint16_t*>(src);
816 for (int i = 0; i < count; ++i) JDWP::Write2BE(&dst, src2[i]);
817 } else {
818 memcpy(&dst[offset * width], src, count * width);
819 }
820 } else {
821 ObjectArray<Object>* oa = a->AsObjectArray<Object>();
822 for (int i = 0; i < count; ++i) {
823 JDWP::ObjectId id = JDWP::ReadObjectId(&src);
824 oa->Set(offset + i, gRegistry->Get<Object*>(id));
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 Hughes7b3cdfc2011-12-08 21:28:17 -0800831JDWP::ObjectId Dbg::CreateString(const std::string& str) {
832 return gRegistry->Add(String::AllocFromModifiedUtf8(str.c_str()));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700833}
834
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800835bool Dbg::CreateObject(JDWP::RefTypeId classId, JDWP::ObjectId& new_object) {
836 Object* o = gRegistry->Get<Object*>(classId);
837 if (o == NULL || !o->IsClass()) {
838 return false;
839 }
840 new_object = gRegistry->Add(o->AsClass()->AllocObject());
841 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700842}
843
Elliott Hughesbf13d362011-12-08 15:51:37 -0800844/*
845 * Used by Eclipse's "Display" view to evaluate "new byte[5]" to get "(byte[]) [0, 0, 0, 0, 0]".
846 */
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800847bool Dbg::CreateArrayObject(JDWP::RefTypeId arrayTypeId, uint32_t length, JDWP::ObjectId& new_array) {
848 Object* o = gRegistry->Get<Object*>(arrayTypeId);
849 if (o == NULL || !o->IsClass()) {
850 return false;
851 }
852 new_array = gRegistry->Add(Array::Alloc(o->AsClass(), length));
853 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700854}
855
856bool Dbg::MatchType(JDWP::RefTypeId instClassId, JDWP::RefTypeId classId) {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800857 // TODO: error handling if the RefTypeIds aren't actually Class*s.
Elliott Hughesd07986f2011-12-06 18:27:45 -0800858 return gRegistry->Get<Class*>(instClassId)->InstanceOf(gRegistry->Get<Class*>(classId));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700859}
860
Elliott Hughes86964332012-02-15 19:37:42 -0800861static JDWP::FieldId ToFieldId(const Field* f) {
Elliott Hughes03181a82011-11-17 17:22:21 -0800862#ifdef MOVING_GARBAGE_COLLECTOR
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700863 UNIMPLEMENTED(FATAL);
Elliott Hughes03181a82011-11-17 17:22:21 -0800864#else
865 return static_cast<JDWP::FieldId>(reinterpret_cast<uintptr_t>(f));
866#endif
867}
868
Elliott Hughes86964332012-02-15 19:37:42 -0800869static JDWP::MethodId ToMethodId(const Method* m) {
Elliott Hughes03181a82011-11-17 17:22:21 -0800870#ifdef MOVING_GARBAGE_COLLECTOR
871 UNIMPLEMENTED(FATAL);
872#else
873 return static_cast<JDWP::MethodId>(reinterpret_cast<uintptr_t>(m));
874#endif
875}
876
Elliott Hughes86964332012-02-15 19:37:42 -0800877static Field* FromFieldId(JDWP::FieldId fid) {
Elliott Hughesaed4be92011-12-02 16:16:23 -0800878#ifdef MOVING_GARBAGE_COLLECTOR
879 UNIMPLEMENTED(FATAL);
880#else
881 return reinterpret_cast<Field*>(static_cast<uintptr_t>(fid));
882#endif
883}
884
Elliott Hughes86964332012-02-15 19:37:42 -0800885static Method* FromMethodId(JDWP::MethodId mid) {
Elliott Hughes03181a82011-11-17 17:22:21 -0800886#ifdef MOVING_GARBAGE_COLLECTOR
887 UNIMPLEMENTED(FATAL);
888#else
889 return reinterpret_cast<Method*>(static_cast<uintptr_t>(mid));
890#endif
891}
892
Elliott Hughes86964332012-02-15 19:37:42 -0800893static void SetLocation(JDWP::JdwpLocation& location, Method* m, uintptr_t native_pc) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -0800894 if (m == NULL) {
895 memset(&location, 0, sizeof(location));
896 } else {
897 Class* c = m->GetDeclaringClass();
898 location.typeTag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
899 location.classId = gRegistry->Add(c);
900 location.methodId = ToMethodId(m);
901 location.idx = m->IsNative() ? -1 : m->ToDexPC(native_pc);
902 }
Elliott Hughesd07986f2011-12-06 18:27:45 -0800903}
904
Elliott Hughes03181a82011-11-17 17:22:21 -0800905std::string Dbg::GetMethodName(JDWP::RefTypeId refTypeId, JDWP::MethodId methodId) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800906 Method* m = FromMethodId(methodId);
907 return MethodHelper(m).GetName();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700908}
909
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800910/*
911 * Augment the access flags for synthetic methods and fields by setting
912 * the (as described by the spec) "0xf0000000 bit". Also, strip out any
913 * flags not specified by the Java programming language.
914 */
915static uint32_t MangleAccessFlags(uint32_t accessFlags) {
916 accessFlags &= kAccJavaFlagsMask;
917 if ((accessFlags & kAccSynthetic) != 0) {
918 accessFlags |= 0xf0000000;
919 }
920 return accessFlags;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700921}
922
Elliott Hughesdbb40792011-11-18 17:05:22 -0800923static const uint16_t kEclipseWorkaroundSlot = 1000;
924
925/*
926 * Eclipse appears to expect that the "this" reference is in slot zero.
927 * If it's not, the "variables" display will show two copies of "this",
928 * possibly because it gets "this" from SF.ThisObject and then displays
929 * all locals with nonzero slot numbers.
930 *
931 * So, we remap the item in slot 0 to 1000, and remap "this" to zero. On
932 * SF.GetValues / SF.SetValues we map them back.
Elliott Hughesc5b734a2011-12-01 17:20:58 -0800933 *
934 * TODO: jdb uses the value to determine whether a variable is a local or an argument,
935 * by checking whether it's less than the number of arguments. To make that work, we'd
936 * have to "mangle" all the arguments to come first, not just the implicit argument 'this'.
Elliott Hughesdbb40792011-11-18 17:05:22 -0800937 */
938static uint16_t MangleSlot(uint16_t slot, const char* name) {
939 uint16_t newSlot = slot;
940 if (strcmp(name, "this") == 0) {
941 newSlot = 0;
942 } else if (slot == 0) {
943 newSlot = kEclipseWorkaroundSlot;
944 }
945 return newSlot;
946}
947
Elliott Hughes91bf6cd2012-02-14 17:27:48 -0800948static uint16_t DemangleSlot(uint16_t slot, Method* m) {
Elliott Hughesdbb40792011-11-18 17:05:22 -0800949 if (slot == kEclipseWorkaroundSlot) {
Elliott Hughes68fdbd02011-11-29 19:22:47 -0800950 return 0;
Elliott Hughesdbb40792011-11-18 17:05:22 -0800951 } else if (slot == 0) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -0800952 const DexFile::CodeItem* code_item = MethodHelper(m).GetCodeItem();
953 CHECK(code_item != NULL);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800954 return code_item->registers_size_ - code_item->ins_size_;
Elliott Hughesdbb40792011-11-18 17:05:22 -0800955 }
Elliott Hughes68fdbd02011-11-29 19:22:47 -0800956 return slot;
Elliott Hughesdbb40792011-11-18 17:05:22 -0800957}
958
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800959bool Dbg::OutputDeclaredFields(JDWP::RefTypeId refTypeId, bool with_generic, JDWP::ExpandBuf* pReply) {
960 Object* o = gRegistry->Get<Object*>(refTypeId);
961 if (o == NULL || !o->IsClass()) {
962 return false;
963 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800964
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800965 Class* c = o->AsClass();
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800966 size_t instance_field_count = c->NumInstanceFields();
967 size_t static_field_count = c->NumStaticFields();
968
969 expandBufAdd4BE(pReply, instance_field_count + static_field_count);
970
971 for (size_t i = 0; i < instance_field_count + static_field_count; ++i) {
972 Field* f = (i < instance_field_count) ? c->GetInstanceField(i) : c->GetStaticField(i - instance_field_count);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800973 FieldHelper fh(f);
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800974 expandBufAddFieldId(pReply, ToFieldId(f));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800975 expandBufAddUtf8String(pReply, fh.GetName());
976 expandBufAddUtf8String(pReply, fh.GetTypeDescriptor());
Elliott Hughesc5b734a2011-12-01 17:20:58 -0800977 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800978 static const char genericSignature[1] = "";
979 expandBufAddUtf8String(pReply, genericSignature);
980 }
981 expandBufAdd4BE(pReply, MangleAccessFlags(f->GetAccessFlags()));
982 }
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800983 return true;
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800984}
985
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800986bool Dbg::OutputDeclaredMethods(JDWP::RefTypeId refTypeId, bool with_generic, JDWP::ExpandBuf* pReply) {
987 Object* o = gRegistry->Get<Object*>(refTypeId);
988 if (o == NULL || !o->IsClass()) {
989 return false;
990 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800991
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800992 Class* c = o->AsClass();
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800993 size_t direct_method_count = c->NumDirectMethods();
994 size_t virtual_method_count = c->NumVirtualMethods();
995
996 expandBufAdd4BE(pReply, direct_method_count + virtual_method_count);
997
998 for (size_t i = 0; i < direct_method_count + virtual_method_count; ++i) {
999 Method* m = (i < direct_method_count) ? c->GetDirectMethod(i) : c->GetVirtualMethod(i - direct_method_count);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001000 MethodHelper mh(m);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001001 expandBufAddMethodId(pReply, ToMethodId(m));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001002 expandBufAddUtf8String(pReply, mh.GetName());
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001003 expandBufAddUtf8String(pReply, mh.GetSignature());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001004 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001005 static const char genericSignature[1] = "";
1006 expandBufAddUtf8String(pReply, genericSignature);
1007 }
1008 expandBufAdd4BE(pReply, MangleAccessFlags(m->GetAccessFlags()));
1009 }
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001010 return true;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001011}
1012
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001013bool Dbg::OutputDeclaredInterfaces(JDWP::RefTypeId refTypeId, JDWP::ExpandBuf* pReply) {
1014 Object* o = gRegistry->Get<Object*>(refTypeId);
1015 if (o == NULL || !o->IsClass()) {
1016 return false;
1017 }
1018 ClassHelper kh(o->AsClass());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001019 size_t interface_count = kh.NumInterfaces();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001020 expandBufAdd4BE(pReply, interface_count);
1021 for (size_t i = 0; i < interface_count; ++i) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001022 expandBufAddRefTypeId(pReply, gRegistry->Add(kh.GetInterface(i)));
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001023 }
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001024 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001025}
1026
1027void Dbg::OutputLineTable(JDWP::RefTypeId refTypeId, JDWP::MethodId methodId, JDWP::ExpandBuf* pReply) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001028 struct DebugCallbackContext {
1029 int numItems;
1030 JDWP::ExpandBuf* pReply;
1031
Elliott Hughes2435a572012-02-17 16:07:41 -08001032 static bool Callback(void* context, uint32_t address, uint32_t line_number) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001033 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
1034 expandBufAdd8BE(pContext->pReply, address);
Elliott Hughes2435a572012-02-17 16:07:41 -08001035 expandBufAdd4BE(pContext->pReply, line_number);
Elliott Hughes03181a82011-11-17 17:22:21 -08001036 pContext->numItems++;
1037 return true;
1038 }
1039 };
1040
1041 Method* m = FromMethodId(methodId);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001042 MethodHelper mh(m);
Elliott Hughes03181a82011-11-17 17:22:21 -08001043 uint64_t start, end;
1044 if (m->IsNative()) {
1045 start = -1;
1046 end = -1;
1047 } else {
1048 start = 0;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001049 // TODO: what are the units supposed to be? *2?
1050 end = mh.GetCodeItem()->insns_size_in_code_units_;
Elliott Hughes03181a82011-11-17 17:22:21 -08001051 }
1052
1053 expandBufAdd8BE(pReply, start);
1054 expandBufAdd8BE(pReply, end);
1055
1056 // Add numLines later
1057 size_t numLinesOffset = expandBufGetLength(pReply);
1058 expandBufAdd4BE(pReply, 0);
1059
1060 DebugCallbackContext context;
1061 context.numItems = 0;
1062 context.pReply = pReply;
1063
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001064 mh.GetDexFile().DecodeDebugInfo(mh.GetCodeItem(), m->IsStatic(), m->GetDexMethodIndex(),
1065 DebugCallbackContext::Callback, NULL, &context);
Elliott Hughes03181a82011-11-17 17:22:21 -08001066
1067 JDWP::Set4BE(expandBufGetBuffer(pReply) + numLinesOffset, context.numItems);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001068}
1069
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001070void Dbg::OutputVariableTable(JDWP::RefTypeId refTypeId, JDWP::MethodId methodId, bool with_generic, JDWP::ExpandBuf* pReply) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001071 struct DebugCallbackContext {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001072 JDWP::ExpandBuf* pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001073 size_t variable_count;
1074 bool with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001075
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001076 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 -08001077 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
1078
Elliott Hughesaa6e1cd2012-01-18 19:26:06 -08001079 VLOG(jdwp) << StringPrintf(" %2zd: %d(%d) '%s' '%s' '%s' slot=%d", pContext->variable_count, startAddress, endAddress - startAddress, name, descriptor, signature, slot);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001080
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001081 slot = MangleSlot(slot, name);
1082
Elliott Hughesdbb40792011-11-18 17:05:22 -08001083 expandBufAdd8BE(pContext->pReply, startAddress);
1084 expandBufAddUtf8String(pContext->pReply, name);
1085 expandBufAddUtf8String(pContext->pReply, descriptor);
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001086 if (pContext->with_generic) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001087 expandBufAddUtf8String(pContext->pReply, signature);
1088 }
1089 expandBufAdd4BE(pContext->pReply, endAddress - startAddress);
1090 expandBufAdd4BE(pContext->pReply, slot);
1091
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001092 ++pContext->variable_count;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001093 }
1094 };
1095
1096 Method* m = FromMethodId(methodId);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001097 MethodHelper mh(m);
1098 const DexFile::CodeItem* code_item = mh.GetCodeItem();
Elliott Hughesdbb40792011-11-18 17:05:22 -08001099
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001100 // arg_count considers doubles and longs to take 2 units.
1101 // variable_count considers everything to take 1 unit.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001102 std::string shorty(mh.GetShorty());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001103 expandBufAdd4BE(pReply, m->NumArgRegisters(shorty));
Elliott Hughesdbb40792011-11-18 17:05:22 -08001104
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001105 // We don't know the total number of variables yet, so leave a blank and update it later.
1106 size_t variable_count_offset = expandBufGetLength(pReply);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001107 expandBufAdd4BE(pReply, 0);
1108
1109 DebugCallbackContext context;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001110 context.pReply = pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001111 context.variable_count = 0;
1112 context.with_generic = with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001113
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001114 mh.GetDexFile().DecodeDebugInfo(code_item, m->IsStatic(), m->GetDexMethodIndex(), NULL,
1115 DebugCallbackContext::Callback, &context);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001116
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001117 JDWP::Set4BE(expandBufGetBuffer(pReply) + variable_count_offset, context.variable_count);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001118}
1119
Elliott Hughesaed4be92011-12-02 16:16:23 -08001120JDWP::JdwpTag Dbg::GetFieldBasicTag(JDWP::FieldId fieldId) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001121 return BasicTagFromDescriptor(FieldHelper(FromFieldId(fieldId)).GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001122}
1123
Elliott Hughesaed4be92011-12-02 16:16:23 -08001124JDWP::JdwpTag Dbg::GetStaticFieldBasicTag(JDWP::FieldId fieldId) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001125 return BasicTagFromDescriptor(FieldHelper(FromFieldId(fieldId)).GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001126}
1127
1128void Dbg::GetFieldValue(JDWP::ObjectId objectId, JDWP::FieldId fieldId, JDWP::ExpandBuf* pReply) {
Elliott Hughesaed4be92011-12-02 16:16:23 -08001129 Object* o = gRegistry->Get<Object*>(objectId);
1130 Field* f = FromFieldId(fieldId);
1131
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001132 JDWP::JdwpTag tag = BasicTagFromDescriptor(FieldHelper(f).GetTypeDescriptor());
Elliott Hughesaed4be92011-12-02 16:16:23 -08001133
1134 if (IsPrimitiveTag(tag)) {
1135 expandBufAdd1(pReply, tag);
1136 if (tag == JDWP::JT_BOOLEAN || tag == JDWP::JT_BYTE) {
1137 expandBufAdd1(pReply, f->Get32(o));
1138 } else if (tag == JDWP::JT_CHAR || tag == JDWP::JT_SHORT) {
1139 expandBufAdd2BE(pReply, f->Get32(o));
1140 } else if (tag == JDWP::JT_FLOAT || tag == JDWP::JT_INT) {
1141 expandBufAdd4BE(pReply, f->Get32(o));
1142 } else if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
1143 expandBufAdd8BE(pReply, f->Get64(o));
1144 } else {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001145 LOG(FATAL) << "Unknown tag: " << tag;
Elliott Hughesaed4be92011-12-02 16:16:23 -08001146 }
1147 } else {
1148 Object* value = f->GetObject(o);
1149 expandBufAdd1(pReply, TagFromObject(value));
1150 expandBufAddObjectId(pReply, gRegistry->Add(value));
1151 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001152}
1153
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001154JDWP::JdwpError Dbg::SetFieldValue(JDWP::ObjectId objectId, JDWP::FieldId fieldId, uint64_t value, int width) {
Elliott Hughesaed4be92011-12-02 16:16:23 -08001155 Object* o = gRegistry->Get<Object*>(objectId);
1156 Field* f = FromFieldId(fieldId);
1157
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001158 JDWP::JdwpTag tag = BasicTagFromDescriptor(FieldHelper(f).GetTypeDescriptor());
Elliott Hughesaed4be92011-12-02 16:16:23 -08001159
1160 if (IsPrimitiveTag(tag)) {
1161 if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
1162 f->Set64(o, value);
1163 } else {
1164 f->Set32(o, value);
1165 }
1166 } else {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001167 Object* v = gRegistry->Get<Object*>(value);
1168 Class* field_type = FieldHelper(f).GetType();
1169 if (!field_type->IsAssignableFrom(v->GetClass())) {
1170 return JDWP::ERR_INVALID_OBJECT;
1171 }
1172 f->SetObject(o, v);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001173 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001174
1175 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001176}
1177
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001178void Dbg::GetStaticFieldValue(JDWP::FieldId fieldId, JDWP::ExpandBuf* pReply) {
1179 GetFieldValue(0, fieldId, pReply);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001180}
1181
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001182JDWP::JdwpError Dbg::SetStaticFieldValue(JDWP::FieldId fieldId, uint64_t value, int width) {
1183 return SetFieldValue(0, fieldId, value, width);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001184}
1185
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001186std::string Dbg::StringToUtf8(JDWP::ObjectId strId) {
1187 String* s = gRegistry->Get<String*>(strId);
1188 return s->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001189}
1190
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001191bool Dbg::GetThreadName(JDWP::ObjectId threadId, std::string& name) {
1192 ScopedThreadListLock thread_list_lock;
1193 Thread* thread = DecodeThread(threadId);
1194 if (thread == NULL) {
1195 return false;
1196 }
Elliott Hughes899e7892012-01-24 14:57:32 -08001197 StringAppendF(&name, "<%d> %s", thread->GetThinLockId(), thread->GetThreadName()->ToModifiedUtf8().c_str());
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001198 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001199}
1200
Elliott Hughes2435a572012-02-17 16:07:41 -08001201JDWP::JdwpError Dbg::GetThreadGroup(JDWP::ObjectId threadId, JDWP::ExpandBuf* pReply) {
Elliott Hughes499c5132011-11-17 14:55:11 -08001202 Object* thread = gRegistry->Get<Object*>(threadId);
Elliott Hughes2435a572012-02-17 16:07:41 -08001203 if (thread != NULL) {
1204 return JDWP::ERR_INVALID_OBJECT;
1205 }
1206
1207 // Okay, so it's an object, but is it actually a thread?
1208 if (DecodeThread(threadId)) {
1209 return JDWP::ERR_INVALID_THREAD;
1210 }
Elliott Hughes499c5132011-11-17 14:55:11 -08001211
1212 Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/Thread;");
1213 CHECK(c != NULL);
1214 Field* f = c->FindInstanceField("group", "Ljava/lang/ThreadGroup;");
1215 CHECK(f != NULL);
1216 Object* group = f->GetObject(thread);
1217 CHECK(group != NULL);
Elliott Hughes2435a572012-02-17 16:07:41 -08001218 JDWP::ObjectId thread_group_id = gRegistry->Add(group);
1219
1220 expandBufAddObjectId(pReply, thread_group_id);
1221 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001222}
1223
Elliott Hughes499c5132011-11-17 14:55:11 -08001224std::string Dbg::GetThreadGroupName(JDWP::ObjectId threadGroupId) {
1225 Object* thread_group = gRegistry->Get<Object*>(threadGroupId);
1226 CHECK(thread_group != NULL);
1227
1228 Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/ThreadGroup;");
1229 CHECK(c != NULL);
1230 Field* f = c->FindInstanceField("name", "Ljava/lang/String;");
1231 CHECK(f != NULL);
1232 String* s = reinterpret_cast<String*>(f->GetObject(thread_group));
1233 return s->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001234}
1235
1236JDWP::ObjectId Dbg::GetThreadGroupParent(JDWP::ObjectId threadGroupId) {
Elliott Hughes4e235312011-12-02 11:34:15 -08001237 Object* thread_group = gRegistry->Get<Object*>(threadGroupId);
1238 CHECK(thread_group != NULL);
1239
1240 Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/ThreadGroup;");
1241 CHECK(c != NULL);
1242 Field* f = c->FindInstanceField("parent", "Ljava/lang/ThreadGroup;");
1243 CHECK(f != NULL);
1244 Object* parent = f->GetObject(thread_group);
1245 return gRegistry->Add(parent);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001246}
1247
Elliott Hughes499c5132011-11-17 14:55:11 -08001248static Object* GetStaticThreadGroup(const char* field_name) {
1249 Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/ThreadGroup;");
1250 CHECK(c != NULL);
1251 Field* f = c->FindStaticField(field_name, "Ljava/lang/ThreadGroup;");
1252 CHECK(f != NULL);
1253 Object* group = f->GetObject(NULL);
1254 CHECK(group != NULL);
1255 return group;
1256}
1257
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001258JDWP::ObjectId Dbg::GetSystemThreadGroupId() {
Elliott Hughes499c5132011-11-17 14:55:11 -08001259 return gRegistry->Add(GetStaticThreadGroup("mSystem"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001260}
1261
1262JDWP::ObjectId Dbg::GetMainThreadGroupId() {
Elliott Hughes499c5132011-11-17 14:55:11 -08001263 return gRegistry->Add(GetStaticThreadGroup("mMain"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001264}
1265
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001266bool Dbg::GetThreadStatus(JDWP::ObjectId threadId, JDWP::JdwpThreadStatus* pThreadStatus, JDWP::JdwpSuspendStatus* pSuspendStatus) {
Elliott Hughes499c5132011-11-17 14:55:11 -08001267 ScopedThreadListLock thread_list_lock;
1268
1269 Thread* thread = DecodeThread(threadId);
1270 if (thread == NULL) {
1271 return false;
1272 }
1273
1274 switch (thread->GetState()) {
1275 case Thread::kTerminated: *pThreadStatus = JDWP::TS_ZOMBIE; break;
1276 case Thread::kRunnable: *pThreadStatus = JDWP::TS_RUNNING; break;
1277 case Thread::kTimedWaiting: *pThreadStatus = JDWP::TS_SLEEPING; break;
1278 case Thread::kBlocked: *pThreadStatus = JDWP::TS_MONITOR; break;
1279 case Thread::kWaiting: *pThreadStatus = JDWP::TS_WAIT; break;
1280 case Thread::kInitializing: *pThreadStatus = JDWP::TS_ZOMBIE; break;
1281 case Thread::kStarting: *pThreadStatus = JDWP::TS_ZOMBIE; break;
1282 case Thread::kNative: *pThreadStatus = JDWP::TS_RUNNING; break;
1283 case Thread::kVmWait: *pThreadStatus = JDWP::TS_WAIT; break;
1284 case Thread::kSuspended: *pThreadStatus = JDWP::TS_RUNNING; break;
1285 default:
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001286 LOG(FATAL) << "Unknown thread state " << thread->GetState();
Elliott Hughes499c5132011-11-17 14:55:11 -08001287 }
1288
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001289 *pSuspendStatus = (thread->IsSuspended() ? JDWP::SUSPEND_STATUS_SUSPENDED : JDWP::SUSPEND_STATUS_NOT_SUSPENDED);
Elliott Hughes499c5132011-11-17 14:55:11 -08001290
1291 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001292}
1293
Elliott Hughes2435a572012-02-17 16:07:41 -08001294JDWP::JdwpError Dbg::GetThreadSuspendCount(JDWP::ObjectId threadId, JDWP::ExpandBuf* pReply) {
1295 Thread* thread = DecodeThread(threadId);
1296 if (thread == NULL) {
1297 return JDWP::ERR_INVALID_THREAD;
1298 }
1299 expandBufAdd4BE(pReply, thread->GetSuspendCount());
1300 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001301}
1302
1303bool Dbg::ThreadExists(JDWP::ObjectId threadId) {
Elliott Hughes761928d2011-11-16 18:33:03 -08001304 return DecodeThread(threadId) != NULL;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001305}
1306
1307bool Dbg::IsSuspended(JDWP::ObjectId threadId) {
Elliott Hughes761928d2011-11-16 18:33:03 -08001308 return DecodeThread(threadId)->IsSuspended();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001309}
1310
Elliott Hughesa2155262011-11-16 16:26:58 -08001311void Dbg::GetThreadGroupThreadsImpl(Object* thread_group, JDWP::ObjectId** ppThreadIds, uint32_t* pThreadCount) {
1312 struct ThreadListVisitor {
1313 static void Visit(Thread* t, void* arg) {
1314 reinterpret_cast<ThreadListVisitor*>(arg)->Visit(t);
1315 }
1316
1317 void Visit(Thread* t) {
1318 if (t == Dbg::GetDebugThread()) {
1319 // Skip the JDWP thread. Some debuggers get bent out of shape when they can't suspend and
1320 // query all threads, so it's easier if we just don't tell them about this thread.
1321 return;
1322 }
1323 if (thread_group == NULL || t->GetThreadGroup() == thread_group) {
1324 threads.push_back(gRegistry->Add(t->GetPeer()));
1325 }
1326 }
1327
1328 Object* thread_group;
1329 std::vector<JDWP::ObjectId> threads;
1330 };
1331
1332 ThreadListVisitor tlv;
1333 tlv.thread_group = thread_group;
1334
1335 {
1336 ScopedThreadListLock thread_list_lock;
1337 Runtime::Current()->GetThreadList()->ForEach(ThreadListVisitor::Visit, &tlv);
1338 }
1339
1340 *pThreadCount = tlv.threads.size();
1341 if (*pThreadCount == 0) {
1342 *ppThreadIds = NULL;
1343 } else {
1344 *ppThreadIds = new JDWP::ObjectId[*pThreadCount];
1345 for (size_t i = 0; i < *pThreadCount; ++i) {
1346 (*ppThreadIds)[i] = tlv.threads[i];
1347 }
1348 }
1349}
1350
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001351void Dbg::GetThreadGroupThreads(JDWP::ObjectId threadGroupId, JDWP::ObjectId** ppThreadIds, uint32_t* pThreadCount) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001352 GetThreadGroupThreadsImpl(gRegistry->Get<Object*>(threadGroupId), ppThreadIds, pThreadCount);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001353}
1354
1355void Dbg::GetAllThreads(JDWP::ObjectId** ppThreadIds, uint32_t* pThreadCount) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001356 GetThreadGroupThreadsImpl(NULL, ppThreadIds, pThreadCount);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001357}
1358
Elliott Hughes86964332012-02-15 19:37:42 -08001359static int GetStackDepth(Thread* thread) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001360 struct CountStackDepthVisitor : public Thread::StackVisitor {
1361 CountStackDepthVisitor() : depth(0) {}
Elliott Hughesf8a2df72011-12-01 12:19:54 -08001362 virtual void VisitFrame(const Frame& f, uintptr_t) {
1363 // TODO: we'll need to skip callee-save frames too.
1364 if (f.HasMethod()) {
1365 ++depth;
1366 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001367 }
1368 size_t depth;
1369 };
1370 CountStackDepthVisitor visitor;
Elliott Hughes86964332012-02-15 19:37:42 -08001371 thread->WalkStack(&visitor);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001372 return visitor.depth;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001373}
1374
Elliott Hughes86964332012-02-15 19:37:42 -08001375int Dbg::GetThreadFrameCount(JDWP::ObjectId threadId) {
1376 ScopedThreadListLock thread_list_lock;
1377 return GetStackDepth(DecodeThread(threadId));
1378}
1379
Elliott Hughes03181a82011-11-17 17:22:21 -08001380bool Dbg::GetThreadFrame(JDWP::ObjectId threadId, int desired_frame_number, JDWP::FrameId* pFrameId, JDWP::JdwpLocation* pLoc) {
1381 ScopedThreadListLock thread_list_lock;
1382 struct GetFrameVisitor : public Thread::StackVisitor {
1383 GetFrameVisitor(int desired_frame_number, JDWP::FrameId* pFrameId, JDWP::JdwpLocation* pLoc)
Elliott Hughesba8eee12012-01-24 20:25:24 -08001384 : found(false), depth(0), desired_frame_number(desired_frame_number), pFrameId(pFrameId), pLoc(pLoc) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001385 }
1386 virtual void VisitFrame(const Frame& f, uintptr_t pc) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -08001387 // TODO: we'll need to skip callee-save frames too.
Elliott Hughes03181a82011-11-17 17:22:21 -08001388 if (!f.HasMethod()) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -08001389 return; // The debugger can't do anything useful with a frame that has no Method*.
Elliott Hughes03181a82011-11-17 17:22:21 -08001390 }
1391
1392 if (depth == desired_frame_number) {
1393 *pFrameId = reinterpret_cast<JDWP::FrameId>(f.GetSP());
Elliott Hughesd07986f2011-12-06 18:27:45 -08001394 SetLocation(*pLoc, f.GetMethod(), pc);
Elliott Hughes03181a82011-11-17 17:22:21 -08001395 found = true;
1396 }
1397 ++depth;
1398 }
1399 bool found;
1400 int depth;
1401 int desired_frame_number;
1402 JDWP::FrameId* pFrameId;
1403 JDWP::JdwpLocation* pLoc;
1404 };
1405 GetFrameVisitor visitor(desired_frame_number, pFrameId, pLoc);
1406 visitor.desired_frame_number = desired_frame_number;
1407 DecodeThread(threadId)->WalkStack(&visitor);
1408 return visitor.found;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001409}
1410
1411JDWP::ObjectId Dbg::GetThreadSelfId() {
Elliott Hughes475fc232011-10-25 15:00:35 -07001412 return gRegistry->Add(Thread::Current()->GetPeer());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001413}
1414
Elliott Hughes475fc232011-10-25 15:00:35 -07001415void Dbg::SuspendVM() {
Elliott Hughesa2155262011-11-16 16:26:58 -08001416 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 -07001417 Runtime::Current()->GetThreadList()->SuspendAll(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001418}
1419
1420void Dbg::ResumeVM() {
Elliott Hughes475fc232011-10-25 15:00:35 -07001421 Runtime::Current()->GetThreadList()->ResumeAll(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001422}
1423
1424void Dbg::SuspendThread(JDWP::ObjectId threadId) {
Elliott Hughes4e235312011-12-02 11:34:15 -08001425 Object* peer = gRegistry->Get<Object*>(threadId);
1426 ScopedThreadListLock thread_list_lock;
1427 Thread* thread = Thread::FromManagedThread(peer);
1428 if (thread == NULL) {
1429 LOG(WARNING) << "No such thread for suspend: " << peer;
1430 return;
1431 }
1432 Runtime::Current()->GetThreadList()->Suspend(thread, true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001433}
1434
1435void Dbg::ResumeThread(JDWP::ObjectId threadId) {
Elliott Hughes4e235312011-12-02 11:34:15 -08001436 Object* peer = gRegistry->Get<Object*>(threadId);
1437 ScopedThreadListLock thread_list_lock;
1438 Thread* thread = Thread::FromManagedThread(peer);
1439 if (thread == NULL) {
1440 LOG(WARNING) << "No such thread for resume: " << peer;
1441 return;
1442 }
1443 Runtime::Current()->GetThreadList()->Resume(thread, true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001444}
1445
1446void Dbg::SuspendSelf() {
Elliott Hughes475fc232011-10-25 15:00:35 -07001447 Runtime::Current()->GetThreadList()->SuspendSelfForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001448}
1449
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001450static Object* GetThis(Frame& f) {
Elliott Hughes86b00102011-12-05 17:54:26 -08001451 Method* m = f.GetMethod();
Elliott Hughes86b00102011-12-05 17:54:26 -08001452 Object* o = NULL;
1453 if (!m->IsNative() && !m->IsStatic()) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001454 uint16_t reg = DemangleSlot(0, m);
Elliott Hughes86b00102011-12-05 17:54:26 -08001455 o = reinterpret_cast<Object*>(f.GetVReg(m, reg));
1456 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001457 return o;
1458}
1459
1460void Dbg::GetThisObject(JDWP::FrameId frameId, JDWP::ObjectId* pThisId) {
1461 Method** sp = reinterpret_cast<Method**>(frameId);
1462 Frame f(sp);
1463 Object* o = GetThis(f);
Elliott Hughes86b00102011-12-05 17:54:26 -08001464 *pThisId = gRegistry->Add(o);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001465}
1466
Elliott Hughescccd84f2011-12-05 16:51:54 -08001467void 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 -08001468 Method** sp = reinterpret_cast<Method**>(frameId);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001469 Frame f(sp);
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001470 Method* m = f.GetMethod();
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001471 uint16_t reg = DemangleSlot(slot, m);
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001472
1473 const VmapTable vmap_table(m->GetVmapTableRaw());
1474 uint32_t vmap_offset;
1475 if (vmap_table.IsInContext(reg, vmap_offset)) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001476 UNIMPLEMENTED(FATAL) << "Don't know how to pull locals from callee save frames: " << vmap_offset;
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001477 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001478
1479 switch (tag) {
1480 case JDWP::JT_BOOLEAN:
1481 {
Elliott Hughescccd84f2011-12-05 16:51:54 -08001482 CHECK_EQ(width, 1U);
Elliott Hughes1bba14f2011-12-01 18:00:36 -08001483 uint32_t intVal = f.GetVReg(m, reg);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001484 VLOG(jdwp) << "get boolean local " << reg << " = " << intVal;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001485 JDWP::Set1(buf+1, intVal != 0);
1486 }
1487 break;
1488 case JDWP::JT_BYTE:
1489 {
Elliott Hughescccd84f2011-12-05 16:51:54 -08001490 CHECK_EQ(width, 1U);
Elliott Hughes1bba14f2011-12-01 18:00:36 -08001491 uint32_t intVal = f.GetVReg(m, reg);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001492 VLOG(jdwp) << "get byte local " << reg << " = " << intVal;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001493 JDWP::Set1(buf+1, intVal);
1494 }
1495 break;
1496 case JDWP::JT_SHORT:
1497 case JDWP::JT_CHAR:
1498 {
Elliott Hughescccd84f2011-12-05 16:51:54 -08001499 CHECK_EQ(width, 2U);
Elliott Hughes1bba14f2011-12-01 18:00:36 -08001500 uint32_t intVal = f.GetVReg(m, reg);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001501 VLOG(jdwp) << "get short/char local " << reg << " = " << intVal;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001502 JDWP::Set2BE(buf+1, intVal);
1503 }
1504 break;
1505 case JDWP::JT_INT:
1506 case JDWP::JT_FLOAT:
1507 {
Elliott Hughescccd84f2011-12-05 16:51:54 -08001508 CHECK_EQ(width, 4U);
Elliott Hughes1bba14f2011-12-01 18:00:36 -08001509 uint32_t intVal = f.GetVReg(m, reg);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001510 VLOG(jdwp) << "get int/float local " << reg << " = " << intVal;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001511 JDWP::Set4BE(buf+1, intVal);
1512 }
1513 break;
1514 case JDWP::JT_ARRAY:
1515 {
Elliott Hughescccd84f2011-12-05 16:51:54 -08001516 CHECK_EQ(width, sizeof(JDWP::ObjectId));
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001517 Object* o = reinterpret_cast<Object*>(f.GetVReg(m, reg));
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001518 VLOG(jdwp) << "get array local " << reg << " = " << o;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001519 if (o != NULL && !Heap::IsHeapAddress(o)) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001520 LOG(FATAL) << "Register " << reg << " expected to hold array: " << o;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001521 }
1522 JDWP::SetObjectId(buf+1, gRegistry->Add(o));
1523 }
1524 break;
1525 case JDWP::JT_OBJECT:
1526 {
Elliott Hughescccd84f2011-12-05 16:51:54 -08001527 CHECK_EQ(width, sizeof(JDWP::ObjectId));
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001528 Object* o = reinterpret_cast<Object*>(f.GetVReg(m, reg));
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001529 VLOG(jdwp) << "get object local " << reg << " = " << o;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001530 if (o != NULL && !Heap::IsHeapAddress(o)) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001531 LOG(FATAL) << "Register " << reg << " expected to hold object: " << o;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001532 }
1533 tag = TagFromObject(o);
1534 JDWP::SetObjectId(buf+1, gRegistry->Add(o));
1535 }
1536 break;
1537 case JDWP::JT_DOUBLE:
1538 case JDWP::JT_LONG:
1539 {
Elliott Hughescccd84f2011-12-05 16:51:54 -08001540 CHECK_EQ(width, 8U);
Elliott Hughes1bba14f2011-12-01 18:00:36 -08001541 uint32_t lo = f.GetVReg(m, reg);
1542 uint64_t hi = f.GetVReg(m, reg + 1);
1543 uint64_t longVal = (hi << 32) | lo;
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001544 VLOG(jdwp) << "get double/long local " << hi << ":" << lo << " = " << longVal;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001545 JDWP::Set8BE(buf+1, longVal);
1546 }
1547 break;
1548 default:
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001549 LOG(FATAL) << "Unknown tag " << tag;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001550 break;
1551 }
1552
1553 // Prepend tag, which may have been updated.
1554 JDWP::Set1(buf, tag);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001555}
1556
Elliott Hughesdbb40792011-11-18 17:05:22 -08001557void 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 -08001558 Method** sp = reinterpret_cast<Method**>(frameId);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001559 Frame f(sp);
Elliott Hughescccd84f2011-12-05 16:51:54 -08001560 Method* m = f.GetMethod();
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001561 uint16_t reg = DemangleSlot(slot, m);
Elliott Hughescccd84f2011-12-05 16:51:54 -08001562
1563 const VmapTable vmap_table(m->GetVmapTableRaw());
1564 uint32_t vmap_offset;
1565 if (vmap_table.IsInContext(reg, vmap_offset)) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001566 UNIMPLEMENTED(FATAL) << "Don't know how to pull locals from callee save frames: " << vmap_offset;
Elliott Hughescccd84f2011-12-05 16:51:54 -08001567 }
1568
1569 switch (tag) {
1570 case JDWP::JT_BOOLEAN:
1571 case JDWP::JT_BYTE:
1572 CHECK_EQ(width, 1U);
1573 f.SetVReg(m, reg, static_cast<uint32_t>(value));
1574 break;
1575 case JDWP::JT_SHORT:
1576 case JDWP::JT_CHAR:
1577 CHECK_EQ(width, 2U);
1578 f.SetVReg(m, reg, static_cast<uint32_t>(value));
1579 break;
1580 case JDWP::JT_INT:
1581 case JDWP::JT_FLOAT:
1582 CHECK_EQ(width, 4U);
1583 f.SetVReg(m, reg, static_cast<uint32_t>(value));
1584 break;
1585 case JDWP::JT_ARRAY:
1586 case JDWP::JT_OBJECT:
1587 case JDWP::JT_STRING:
1588 {
1589 CHECK_EQ(width, sizeof(JDWP::ObjectId));
1590 Object* o = gRegistry->Get<Object*>(static_cast<JDWP::ObjectId>(value));
1591 f.SetVReg(m, reg, static_cast<uint32_t>(reinterpret_cast<uintptr_t>(o)));
1592 }
1593 break;
1594 case JDWP::JT_DOUBLE:
1595 case JDWP::JT_LONG:
1596 CHECK_EQ(width, 8U);
1597 f.SetVReg(m, reg, static_cast<uint32_t>(value));
1598 f.SetVReg(m, reg + 1, static_cast<uint32_t>(value >> 32));
1599 break;
1600 default:
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001601 LOG(FATAL) << "Unknown tag " << tag;
Elliott Hughescccd84f2011-12-05 16:51:54 -08001602 break;
1603 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001604}
1605
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001606void Dbg::PostLocationEvent(const Method* m, int dex_pc, Object* this_object, int event_flags) {
1607 Class* c = m->GetDeclaringClass();
1608
1609 JDWP::JdwpLocation location;
1610 location.typeTag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
1611 location.classId = gRegistry->Add(c);
1612 location.methodId = ToMethodId(m);
1613 location.idx = m->IsNative() ? -1 : dex_pc;
1614
1615 // Note we use "NoReg" so we don't keep track of references that are
1616 // never actually sent to the debugger. 'this_id' is only used to
1617 // compare against registered events...
1618 JDWP::ObjectId this_id = static_cast<JDWP::ObjectId>(reinterpret_cast<uintptr_t>(this_object));
1619 if (gJdwpState->PostLocationEvent(&location, this_id, event_flags)) {
1620 // ...unless there's a registered event, in which case we
1621 // need to really track the class and 'this'.
1622 gRegistry->Add(c);
1623 gRegistry->Add(this_object);
1624 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001625}
1626
Elliott Hughesd07986f2011-12-06 18:27:45 -08001627void Dbg::PostException(Method** sp, Method* throwMethod, uintptr_t throwNativePc, Method* catchMethod, uintptr_t catchNativePc, Object* exception) {
Ian Rogers0ad5bb82011-12-07 10:16:32 -08001628 if (!gDebuggerActive) {
1629 return;
1630 }
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001631
Elliott Hughesd07986f2011-12-06 18:27:45 -08001632 JDWP::JdwpLocation throw_location;
1633 SetLocation(throw_location, throwMethod, throwNativePc);
1634 JDWP::JdwpLocation catch_location;
1635 SetLocation(catch_location, catchMethod, catchNativePc);
1636
1637 // We need 'this' for InstanceOnly filters.
1638 JDWP::ObjectId this_id;
1639 GetThisObject(reinterpret_cast<JDWP::FrameId>(sp), &this_id);
1640
1641 /*
1642 * Hand the event to the JDWP exception handler. Note we're using the
1643 * "NoReg" objectID on the exception, which is not strictly correct --
1644 * the exception object WILL be passed up to the debugger if the
1645 * debugger is interested in the event. We do this because the current
1646 * implementation of the debugger object registry never throws anything
1647 * away, and some people were experiencing a fatal build up of exception
1648 * objects when dealing with certain libraries.
1649 */
1650 JDWP::ObjectId exception_id = static_cast<JDWP::ObjectId>(reinterpret_cast<uintptr_t>(exception));
1651 JDWP::RefTypeId exception_class_id = gRegistry->Add(exception->GetClass());
1652
1653 gJdwpState->PostException(&throw_location, exception_id, exception_class_id, &catch_location, this_id);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001654}
1655
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001656void Dbg::PostClassPrepare(Class* c) {
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001657 if (!gDebuggerActive) {
1658 return;
1659 }
1660
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001661 // OLD-TODO - we currently always send both "verified" and "prepared" since
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001662 // debuggers seem to like that. There might be some advantage to honesty,
1663 // since the class may not yet be verified.
1664 int state = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
1665 JDWP::JdwpTypeTag tag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
1666 gJdwpState->PostClassPrepare(tag, gRegistry->Add(c), ClassHelper(c).GetDescriptor(), state);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001667}
1668
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001669void Dbg::UpdateDebugger(int32_t dex_pc, Thread* self, Method** sp) {
1670 if (!gDebuggerActive) {
1671 return;
1672 }
1673
Elliott Hughes86964332012-02-15 19:37:42 -08001674 Frame f(sp);
1675 f.Next(); // Skip callee save frame.
1676 Method* m = f.GetMethod();
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001677 int event_flags = 0;
1678
1679 // Update xtra.currentPc on every instruction. We need to do this if
1680 // there's a chance that we could get suspended. This can happen if
1681 // event_flags != 0 here, or somebody manually requests a suspend
1682 // (which gets handled at PERIOD_CHECKS time). One place where this
1683 // needs to be correct is in dvmAddSingleStep().
1684 //dvmExportPC(pc, fp);
1685
1686 // We use a pc of -1 to represent method entry, since we might branch back to pc 0 later.
1687 if (dex_pc == -1) {
1688 event_flags |= kMethodEntry;
1689 }
1690
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001691 // See if we have a breakpoint here.
1692 // Depending on the "mods" associated with event(s) on this address,
1693 // we may or may not actually send a message to the debugger.
Elliott Hughes86964332012-02-15 19:37:42 -08001694 if (IsBreakpoint(m, dex_pc)) {
1695 event_flags |= kBreakpoint;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001696 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001697
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001698 // If the debugger is single-stepping one of our threads, check to
1699 // see if we're that thread and we've reached a step point.
Elliott Hughes86964332012-02-15 19:37:42 -08001700 if (gSingleStepControl.is_active && gSingleStepControl.thread == self) {
1701 CHECK(!m->IsNative());
1702 if (gSingleStepControl.step_depth == JDWP::SD_INTO) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001703 // Step into method calls. We break when the line number
1704 // or method pointer changes. If we're in SS_MIN mode, we
1705 // always stop.
Elliott Hughes86964332012-02-15 19:37:42 -08001706 if (gSingleStepControl.method != m) {
1707 event_flags |= kSingleStep;
1708 VLOG(jdwp) << "SS new method";
1709 } else if (gSingleStepControl.step_size == JDWP::SS_MIN) {
1710 event_flags |= kSingleStep;
1711 VLOG(jdwp) << "SS new instruction";
Elliott Hughes2435a572012-02-17 16:07:41 -08001712 } else if (gSingleStepControl.dex_pcs.find(dex_pc) == gSingleStepControl.dex_pcs.end()) {
1713 event_flags |= kSingleStep;
1714 VLOG(jdwp) << "SS new line";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001715 }
Elliott Hughes86964332012-02-15 19:37:42 -08001716 } else if (gSingleStepControl.step_depth == JDWP::SD_OVER) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001717 // Step over method calls. We break when the line number is
1718 // different and the frame depth is <= the original frame
1719 // depth. (We can't just compare on the method, because we
1720 // might get unrolled past it by an exception, and it's tricky
1721 // to identify recursion.)
Elliott Hughes86964332012-02-15 19:37:42 -08001722
1723 // TODO: can we just use the value of 'sp'?
1724 int stack_depth = GetStackDepth(self);
1725
1726 if (stack_depth < gSingleStepControl.stack_depth) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001727 // popped up one or more frames, always trigger
Elliott Hughes86964332012-02-15 19:37:42 -08001728 event_flags |= kSingleStep;
1729 VLOG(jdwp) << "SS method pop";
1730 } else if (stack_depth == gSingleStepControl.stack_depth) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001731 // same depth, see if we moved
Elliott Hughes86964332012-02-15 19:37:42 -08001732 if (gSingleStepControl.step_size == JDWP::SS_MIN) {
1733 event_flags |= kSingleStep;
1734 VLOG(jdwp) << "SS new instruction";
Elliott Hughes2435a572012-02-17 16:07:41 -08001735 } else if (gSingleStepControl.dex_pcs.find(dex_pc) == gSingleStepControl.dex_pcs.end()) {
1736 event_flags |= kSingleStep;
1737 VLOG(jdwp) << "SS new line";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001738 }
1739 }
1740 } else {
Elliott Hughes86964332012-02-15 19:37:42 -08001741 CHECK_EQ(gSingleStepControl.step_depth, JDWP::SD_OUT);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001742 // Return from the current method. We break when the frame
1743 // depth pops up.
1744
1745 // This differs from the "method exit" break in that it stops
1746 // with the PC at the next instruction in the returned-to
1747 // function, rather than the end of the returning function.
Elliott Hughes86964332012-02-15 19:37:42 -08001748
1749 // TODO: can we just use the value of 'sp'?
1750 int stack_depth = GetStackDepth(self);
1751 if (stack_depth < gSingleStepControl.stack_depth) {
1752 event_flags |= kSingleStep;
1753 VLOG(jdwp) << "SS method pop";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001754 }
1755 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001756 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001757
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001758 // Check to see if this is a "return" instruction. JDWP says we should
1759 // send the event *after* the code has been executed, but it also says
1760 // the location we provide is the last instruction. Since the "return"
1761 // instruction has no interesting side effects, we should be safe.
1762 // (We can't just move this down to the returnFromMethod label because
1763 // we potentially need to combine it with other events.)
1764 // We're also not supposed to generate a method exit event if the method
1765 // terminates "with a thrown exception".
Elliott Hughes86964332012-02-15 19:37:42 -08001766 if (dex_pc >= 0) {
1767 const DexFile::CodeItem* code_item = MethodHelper(m).GetCodeItem();
1768 CHECK(code_item != NULL);
1769 CHECK_LT(dex_pc, static_cast<int32_t>(code_item->insns_size_in_code_units_));
1770 if (Instruction::At(&code_item->insns_[dex_pc])->IsReturn()) {
1771 event_flags |= kMethodExit;
1772 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001773 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001774
1775 // If there's something interesting going on, see if it matches one
1776 // of the debugger filters.
1777 if (event_flags != 0) {
Elliott Hughes86964332012-02-15 19:37:42 -08001778 Dbg::PostLocationEvent(m, dex_pc, GetThis(f), event_flags);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001779 }
1780}
1781
Elliott Hughes86964332012-02-15 19:37:42 -08001782void Dbg::WatchLocation(const JDWP::JdwpLocation* location) {
1783 MutexLock mu(gBreakpointsLock);
1784 Method* m = FromMethodId(location->methodId);
1785 gBreakpoints.push_back(Breakpoint(m, location->idx));
1786 VLOG(jdwp) << "Set breakpoint #" << (gBreakpoints.size() - 1) << ": " << gBreakpoints[gBreakpoints.size() - 1];
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001787}
1788
Elliott Hughes86964332012-02-15 19:37:42 -08001789void Dbg::UnwatchLocation(const JDWP::JdwpLocation* location) {
1790 MutexLock mu(gBreakpointsLock);
1791 Method* m = FromMethodId(location->methodId);
1792 for (size_t i = 0; i < gBreakpoints.size(); ++i) {
1793 if (gBreakpoints[i].method == m && gBreakpoints[i].pc == location->idx) {
1794 VLOG(jdwp) << "Removed breakpoint #" << i << ": " << gBreakpoints[i];
1795 gBreakpoints.erase(gBreakpoints.begin() + i);
1796 return;
1797 }
1798 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001799}
1800
Elliott Hughes2435a572012-02-17 16:07:41 -08001801JDWP::JdwpError Dbg::ConfigureStep(JDWP::ObjectId threadId, JDWP::JdwpStepSize step_size, JDWP::JdwpStepDepth step_depth) {
Elliott Hughes86964332012-02-15 19:37:42 -08001802 Thread* thread = DecodeThread(threadId);
Elliott Hughes2435a572012-02-17 16:07:41 -08001803 if (thread == NULL) {
1804 return JDWP::ERR_INVALID_THREAD;
1805 }
Elliott Hughes86964332012-02-15 19:37:42 -08001806
1807 // TODO: there's no theoretical reason why we couldn't support single-stepping
1808 // of multiple threads at once, but we never did so historically.
1809 if (gSingleStepControl.thread != NULL && thread != gSingleStepControl.thread) {
1810 LOG(WARNING) << "single-step already active for " << *gSingleStepControl.thread
1811 << "; switching to " << *thread;
1812 }
1813
Elliott Hughes2435a572012-02-17 16:07:41 -08001814 //
1815 // Work out what Method* we're in, the current line number, and how deep the stack currently
1816 // is for step-out.
1817 //
1818
Elliott Hughes86964332012-02-15 19:37:42 -08001819 struct SingleStepStackVisitor : public Thread::StackVisitor {
1820 SingleStepStackVisitor() {
1821 gSingleStepControl.method = NULL;
1822 gSingleStepControl.stack_depth = 0;
1823 }
Elliott Hughes2435a572012-02-17 16:07:41 -08001824 virtual void VisitFrame(const Frame& f, uintptr_t pc) {
Elliott Hughes86964332012-02-15 19:37:42 -08001825 // TODO: we'll need to skip callee-save frames too.
1826 if (f.HasMethod()) {
1827 ++gSingleStepControl.stack_depth;
1828 if (gSingleStepControl.method == NULL) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001829 const Method* m = f.GetMethod();
1830 const DexCache* dex_cache = m->GetDeclaringClass()->GetDexCache();
1831 gSingleStepControl.method = m;
1832 gSingleStepControl.line_number = -1;
1833 if (dex_cache != NULL) {
1834 const DexFile& dex_file = Runtime::Current()->GetClassLinker()->FindDexFile(dex_cache);
1835 gSingleStepControl.line_number = dex_file.GetLineNumFromPC(m, m->ToDexPC(pc));
1836 }
Elliott Hughes86964332012-02-15 19:37:42 -08001837 }
1838 }
1839 }
1840 };
1841 SingleStepStackVisitor visitor;
1842 thread->WalkStack(&visitor);
1843
Elliott Hughes2435a572012-02-17 16:07:41 -08001844 //
1845 // Find the dex_pc values that correspond to the current line, for line-based single-stepping.
1846 //
1847
1848 struct DebugCallbackContext {
1849 DebugCallbackContext() {
1850 last_pc_valid = false;
1851 last_pc = 0;
1852 gSingleStepControl.dex_pcs.clear();
1853 }
1854
1855 static bool Callback(void* raw_context, uint32_t address, uint32_t line_number) {
1856 DebugCallbackContext* context = reinterpret_cast<DebugCallbackContext*>(raw_context);
1857 if (static_cast<int32_t>(line_number) == gSingleStepControl.line_number) {
1858 if (!context->last_pc_valid) {
1859 // Everything from this address until the next line change is ours.
1860 context->last_pc = address;
1861 context->last_pc_valid = true;
1862 }
1863 // Otherwise, if we're already in a valid range for this line,
1864 // just keep going (shouldn't really happen)...
1865 } else if (context->last_pc_valid) { // and the line number is new
1866 // Add everything from the last entry up until here to the set
1867 for (uint32_t dex_pc = context->last_pc; dex_pc < address; ++dex_pc) {
1868 gSingleStepControl.dex_pcs.insert(dex_pc);
1869 }
1870 context->last_pc_valid = false;
1871 }
1872 return false; // There may be multiple entries for any given line.
1873 }
1874
1875 ~DebugCallbackContext() {
1876 // If the line number was the last in the position table...
1877 if (last_pc_valid) {
1878 size_t end = MethodHelper(gSingleStepControl.method).GetCodeItem()->insns_size_in_code_units_;
1879 for (uint32_t dex_pc = last_pc; dex_pc < end; ++dex_pc) {
1880 gSingleStepControl.dex_pcs.insert(dex_pc);
1881 }
1882 }
1883 }
1884
1885 bool last_pc_valid;
1886 uint32_t last_pc;
1887 };
1888 DebugCallbackContext context;
1889 const Method* m = gSingleStepControl.method;
1890 MethodHelper mh(m);
1891 mh.GetDexFile().DecodeDebugInfo(mh.GetCodeItem(), m->IsStatic(), m->GetDexMethodIndex(),
1892 DebugCallbackContext::Callback, NULL, &context);
1893
1894 //
1895 // Everything else...
1896 //
1897
Elliott Hughes86964332012-02-15 19:37:42 -08001898 gSingleStepControl.thread = thread;
1899 gSingleStepControl.step_size = step_size;
1900 gSingleStepControl.step_depth = step_depth;
1901 gSingleStepControl.is_active = true;
1902
Elliott Hughes2435a572012-02-17 16:07:41 -08001903 if (VLOG_IS_ON(jdwp)) {
1904 VLOG(jdwp) << "Single-step thread: " << *gSingleStepControl.thread;
1905 VLOG(jdwp) << "Single-step step size: " << gSingleStepControl.step_size;
1906 VLOG(jdwp) << "Single-step step depth: " << gSingleStepControl.step_depth;
1907 VLOG(jdwp) << "Single-step current method: " << PrettyMethod(gSingleStepControl.method);
1908 VLOG(jdwp) << "Single-step current line: " << gSingleStepControl.line_number;
1909 VLOG(jdwp) << "Single-step current stack depth: " << gSingleStepControl.stack_depth;
1910 VLOG(jdwp) << "Single-step dex_pc values:";
1911 for (std::set<uint32_t>::iterator it = gSingleStepControl.dex_pcs.begin() ; it != gSingleStepControl.dex_pcs.end(); ++it) {
1912 VLOG(jdwp) << " " << *it;
1913 }
1914 }
1915
1916 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001917}
1918
1919void Dbg::UnconfigureStep(JDWP::ObjectId threadId) {
Elliott Hughes86964332012-02-15 19:37:42 -08001920 gSingleStepControl.is_active = false;
1921 gSingleStepControl.thread = NULL;
Elliott Hughes2435a572012-02-17 16:07:41 -08001922 gSingleStepControl.dex_pcs.clear();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001923}
1924
Elliott Hughesd07986f2011-12-06 18:27:45 -08001925JDWP::JdwpError Dbg::InvokeMethod(JDWP::ObjectId threadId, JDWP::ObjectId objectId, JDWP::RefTypeId classId, JDWP::MethodId methodId, uint32_t numArgs, uint64_t* argArray, uint32_t options, JDWP::JdwpTag* pResultTag, uint64_t* pResultValue, JDWP::ObjectId* pExceptionId) {
1926 ThreadList* thread_list = Runtime::Current()->GetThreadList();
1927
1928 Thread* targetThread = NULL;
1929 DebugInvokeReq* req = NULL;
1930 {
1931 ScopedThreadListLock thread_list_lock;
1932 targetThread = DecodeThread(threadId);
1933 if (targetThread == NULL) {
1934 LOG(ERROR) << "InvokeMethod request for non-existent thread " << threadId;
1935 return JDWP::ERR_INVALID_THREAD;
1936 }
1937 req = targetThread->GetInvokeReq();
1938 if (!req->ready) {
1939 LOG(ERROR) << "InvokeMethod request for thread not stopped by event: " << *targetThread;
1940 return JDWP::ERR_INVALID_THREAD;
1941 }
1942
1943 /*
1944 * We currently have a bug where we don't successfully resume the
1945 * target thread if the suspend count is too deep. We're expected to
1946 * require one "resume" for each "suspend", but when asked to execute
1947 * a method we have to resume fully and then re-suspend it back to the
1948 * same level. (The easiest way to cause this is to type "suspend"
1949 * multiple times in jdb.)
1950 *
1951 * It's unclear what this means when the event specifies "resume all"
1952 * and some threads are suspended more deeply than others. This is
1953 * a rare problem, so for now we just prevent it from hanging forever
1954 * by rejecting the method invocation request. Without this, we will
1955 * be stuck waiting on a suspended thread.
1956 */
1957 int suspend_count = targetThread->GetSuspendCount();
1958 if (suspend_count > 1) {
1959 LOG(ERROR) << *targetThread << " suspend count too deep for method invocation: " << suspend_count;
1960 return JDWP::ERR_THREAD_SUSPENDED; // Probably not expected here.
1961 }
1962
1963 /*
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001964 * OLD-TODO: ought to screen the various IDs, and verify that the argument
Elliott Hughesd07986f2011-12-06 18:27:45 -08001965 * list is valid.
1966 */
1967 req->receiver_ = gRegistry->Get<Object*>(objectId);
1968 req->thread_ = gRegistry->Get<Object*>(threadId);
1969 req->class_ = gRegistry->Get<Class*>(classId);
1970 req->method_ = FromMethodId(methodId);
1971 req->num_args_ = numArgs;
1972 req->arg_array_ = argArray;
1973 req->options_ = options;
1974 req->invoke_needed_ = true;
1975 }
1976
1977 // The fact that we've released the thread list lock is a bit risky --- if the thread goes
1978 // away we're sitting high and dry -- but we must release this before the ResumeAllThreads
1979 // call, and it's unwise to hold it during WaitForSuspend.
1980
1981 {
1982 /*
1983 * We change our (JDWP thread) status, which should be THREAD_RUNNING,
1984 * so the VM can suspend for a GC if the invoke request causes us to
1985 * run out of memory. It's also a good idea to change it before locking
1986 * the invokeReq mutex, although that should never be held for long.
1987 */
1988 ScopedThreadStateChange tsc(Thread::Current(), Thread::kVmWait);
1989
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001990 VLOG(jdwp) << " Transferring control to event thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08001991 {
1992 MutexLock mu(req->lock_);
1993
1994 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001995 VLOG(jdwp) << " Resuming all threads";
Elliott Hughesd07986f2011-12-06 18:27:45 -08001996 thread_list->ResumeAll(true);
1997 } else {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001998 VLOG(jdwp) << " Resuming event thread only";
Elliott Hughesd07986f2011-12-06 18:27:45 -08001999 thread_list->Resume(targetThread, true);
2000 }
2001
2002 // Wait for the request to finish executing.
2003 while (req->invoke_needed_) {
2004 req->cond_.Wait(req->lock_);
2005 }
2006 }
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002007 VLOG(jdwp) << " Control has returned from event thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002008
2009 /* wait for thread to re-suspend itself */
2010 targetThread->WaitUntilSuspended();
2011 //dvmWaitForSuspend(targetThread);
2012 }
2013
2014 /*
2015 * Suspend the threads. We waited for the target thread to suspend
2016 * itself, so all we need to do is suspend the others.
2017 *
2018 * The suspendAllThreads() call will double-suspend the event thread,
2019 * so we want to resume the target thread once to keep the books straight.
2020 */
2021 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002022 VLOG(jdwp) << " Suspending all threads";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002023 thread_list->SuspendAll(true);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002024 VLOG(jdwp) << " Resuming event thread to balance the count";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002025 thread_list->Resume(targetThread, true);
2026 }
2027
2028 // Copy the result.
2029 *pResultTag = req->result_tag;
2030 if (IsPrimitiveTag(req->result_tag)) {
2031 *pResultValue = req->result_value.j;
2032 } else {
2033 *pResultValue = gRegistry->Add(req->result_value.l);
2034 }
2035 *pExceptionId = req->exception;
2036 return req->error;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002037}
2038
2039void Dbg::ExecuteMethod(DebugInvokeReq* pReq) {
Elliott Hughesd07986f2011-12-06 18:27:45 -08002040 Thread* self = Thread::Current();
2041
2042 // We can be called while an exception is pending in the VM. We need
2043 // to preserve that across the method invocation.
2044 SirtRef<Throwable> old_exception(self->GetException());
2045 self->ClearException();
2046
2047 ScopedThreadStateChange tsc(self, Thread::kRunnable);
2048
2049 // Translate the method through the vtable, unless the debugger wants to suppress it.
2050 Method* m = pReq->method_;
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002051 VLOG(jdwp) << "ExecuteMethod " << PrettyMethod(m);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002052 if ((pReq->options_ & JDWP::INVOKE_NONVIRTUAL) == 0 && pReq->receiver_ != NULL) {
2053 m = pReq->class_->FindVirtualMethodForVirtualOrInterface(pReq->method_);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002054 VLOG(jdwp) << "ExecuteMethod " << PrettyMethod(m);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002055 }
2056 CHECK(m != NULL);
2057
2058 CHECK_EQ(sizeof(jvalue), sizeof(uint64_t));
2059
2060 pReq->result_value = InvokeWithJValues(self, pReq->receiver_, m, reinterpret_cast<JValue*>(pReq->arg_array_));
2061
2062 pReq->exception = gRegistry->Add(self->GetException());
2063 pReq->result_tag = BasicTagFromDescriptor(MethodHelper(m).GetShorty());
2064 if (pReq->exception != 0) {
2065 Object* exc = self->GetException();
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002066 VLOG(jdwp) << " JDWP invocation returning with exception=" << exc << " " << PrettyTypeOf(exc);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002067 self->ClearException();
2068 pReq->result_value.j = 0;
2069 } else if (pReq->result_tag == JDWP::JT_OBJECT) {
2070 /* if no exception thrown, examine object result more closely */
2071 JDWP::JdwpTag new_tag = TagFromObject(pReq->result_value.l);
2072 if (new_tag != pReq->result_tag) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002073 VLOG(jdwp) << " JDWP promoted result from " << pReq->result_tag << " to " << new_tag;
Elliott Hughesd07986f2011-12-06 18:27:45 -08002074 pReq->result_tag = new_tag;
2075 }
2076
2077 /*
2078 * Register the object. We don't actually need an ObjectId yet,
2079 * but we do need to be sure that the GC won't move or discard the
2080 * object when we switch out of RUNNING. The ObjectId conversion
2081 * will add the object to the "do not touch" list.
2082 *
2083 * We can't use the "tracked allocation" mechanism here because
2084 * the object is going to be handed off to a different thread.
2085 */
2086 gRegistry->Add(pReq->result_value.l);
2087 }
2088
2089 if (old_exception.get() != NULL) {
2090 self->SetException(old_exception.get());
2091 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002092}
2093
Elliott Hughesd07986f2011-12-06 18:27:45 -08002094/*
2095 * Register an object ID that might not have been registered previously.
2096 *
2097 * Normally this wouldn't happen -- the conversion to an ObjectId would
2098 * have added the object to the registry -- but in some cases (e.g.
2099 * throwing exceptions) we really want to do the registration late.
2100 */
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002101void Dbg::RegisterObjectId(JDWP::ObjectId id) {
Elliott Hughesd07986f2011-12-06 18:27:45 -08002102 gRegistry->Add(reinterpret_cast<Object*>(id));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002103}
2104
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002105/*
2106 * "buf" contains a full JDWP packet, possibly with multiple chunks. We
2107 * need to process each, accumulate the replies, and ship the whole thing
2108 * back.
2109 *
2110 * Returns "true" if we have a reply. The reply buffer is newly allocated,
2111 * and includes the chunk type/length, followed by the data.
2112 *
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08002113 * OLD-TODO: we currently assume that the request and reply include a single
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002114 * chunk. If this becomes inconvenient we will need to adapt.
2115 */
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002116bool Dbg::DdmHandlePacket(const uint8_t* buf, int dataLen, uint8_t** pReplyBuf, int* pReplyLen) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002117 CHECK_GE(dataLen, 0);
2118
2119 Thread* self = Thread::Current();
2120 JNIEnv* env = self->GetJniEnv();
2121
Elliott Hughes844f9a02012-01-24 20:19:58 -08002122 static jclass Chunk_class = CacheClass(env, "org/apache/harmony/dalvik/ddmc/Chunk");
2123 static jclass DdmServer_class = CacheClass(env, "org/apache/harmony/dalvik/ddmc/DdmServer");
2124 static jmethodID dispatch_mid = env->GetStaticMethodID(DdmServer_class, "dispatch", "(I[BII)Lorg/apache/harmony/dalvik/ddmc/Chunk;");
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002125 static jfieldID data_fid = env->GetFieldID(Chunk_class, "data", "[B");
2126 static jfieldID length_fid = env->GetFieldID(Chunk_class, "length", "I");
2127 static jfieldID offset_fid = env->GetFieldID(Chunk_class, "offset", "I");
2128 static jfieldID type_fid = env->GetFieldID(Chunk_class, "type", "I");
2129
2130 // Create a byte[] corresponding to 'buf'.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002131 ScopedLocalRef<jbyteArray> dataArray(env, env->NewByteArray(dataLen));
2132 if (dataArray.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002133 LOG(WARNING) << "byte[] allocation failed: " << dataLen;
2134 env->ExceptionClear();
2135 return false;
2136 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002137 env->SetByteArrayRegion(dataArray.get(), 0, dataLen, reinterpret_cast<const jbyte*>(buf));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002138
2139 const int kChunkHdrLen = 8;
2140
2141 // Run through and find all chunks. [Currently just find the first.]
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002142 ScopedByteArrayRO contents(env, dataArray.get());
Elliott Hughesf7c3b662011-10-27 12:04:56 -07002143 jint type = JDWP::Get4BE(reinterpret_cast<const uint8_t*>(&contents[0]));
2144 jint length = JDWP::Get4BE(reinterpret_cast<const uint8_t*>(&contents[4]));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002145 jint offset = kChunkHdrLen;
2146 if (offset + length > dataLen) {
2147 LOG(WARNING) << StringPrintf("bad chunk found (len=%u pktLen=%d)", length, dataLen);
2148 return false;
2149 }
2150
2151 // Call "private static Chunk dispatch(int type, byte[] data, int offset, int length)".
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002152 ScopedLocalRef<jobject> chunk(env, env->CallStaticObjectMethod(DdmServer_class, dispatch_mid, type, dataArray.get(), offset, length));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002153 if (env->ExceptionCheck()) {
2154 LOG(INFO) << StringPrintf("Exception thrown by dispatcher for 0x%08x", type);
2155 env->ExceptionDescribe();
2156 env->ExceptionClear();
2157 return false;
2158 }
2159
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002160 if (chunk.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002161 return false;
2162 }
2163
2164 /*
2165 * Pull the pieces out of the chunk. We copy the results into a
2166 * newly-allocated buffer that the caller can free. We don't want to
2167 * continue using the Chunk object because nothing has a reference to it.
2168 *
2169 * We could avoid this by returning type/data/offset/length and having
2170 * the caller be aware of the object lifetime issues, but that
2171 * integrates the JDWP code more tightly into the VM, and doesn't work
2172 * if we have responses for multiple chunks.
2173 *
2174 * So we're pretty much stuck with copying data around multiple times.
2175 */
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002176 ScopedLocalRef<jbyteArray> replyData(env, reinterpret_cast<jbyteArray>(env->GetObjectField(chunk.get(), data_fid)));
2177 length = env->GetIntField(chunk.get(), length_fid);
2178 offset = env->GetIntField(chunk.get(), offset_fid);
2179 type = env->GetIntField(chunk.get(), type_fid);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002180
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002181 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 -07002182 if (length == 0 || replyData.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002183 return false;
2184 }
2185
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002186 jsize replyLength = env->GetArrayLength(replyData.get());
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002187 if (offset + length > replyLength) {
2188 LOG(WARNING) << StringPrintf("chunk off=%d len=%d exceeds reply array len %d", offset, length, replyLength);
2189 return false;
2190 }
2191
2192 uint8_t* reply = new uint8_t[length + kChunkHdrLen];
2193 if (reply == NULL) {
2194 LOG(WARNING) << "malloc failed: " << (length + kChunkHdrLen);
2195 return false;
2196 }
Elliott Hughesf7c3b662011-10-27 12:04:56 -07002197 JDWP::Set4BE(reply + 0, type);
2198 JDWP::Set4BE(reply + 4, length);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002199 env->GetByteArrayRegion(replyData.get(), offset, length, reinterpret_cast<jbyte*>(reply + kChunkHdrLen));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002200
2201 *pReplyBuf = reply;
2202 *pReplyLen = length + kChunkHdrLen;
2203
Elliott Hughesba8eee12012-01-24 20:25:24 -08002204 VLOG(jdwp) << StringPrintf("dvmHandleDdm returning type=%.4s buf=%p len=%d", reinterpret_cast<char*>(reply), reply, length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002205 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002206}
2207
Elliott Hughesa2155262011-11-16 16:26:58 -08002208void Dbg::DdmBroadcast(bool connect) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002209 VLOG(jdwp) << "Broadcasting DDM " << (connect ? "connect" : "disconnect") << "...";
Elliott Hughes47fce012011-10-25 18:37:19 -07002210
2211 Thread* self = Thread::Current();
2212 if (self->GetState() != Thread::kRunnable) {
2213 LOG(ERROR) << "DDM broadcast in thread state " << self->GetState();
2214 /* try anyway? */
2215 }
2216
2217 JNIEnv* env = self->GetJniEnv();
Elliott Hughes844f9a02012-01-24 20:19:58 -08002218 static jclass DdmServer_class = CacheClass(env, "org/apache/harmony/dalvik/ddmc/DdmServer");
Elliott Hughes47fce012011-10-25 18:37:19 -07002219 static jmethodID broadcast_mid = env->GetStaticMethodID(DdmServer_class, "broadcast", "(I)V");
2220 jint event = connect ? 1 /*DdmServer.CONNECTED*/ : 2 /*DdmServer.DISCONNECTED*/;
2221 env->CallStaticVoidMethod(DdmServer_class, broadcast_mid, event);
2222 if (env->ExceptionCheck()) {
2223 LOG(ERROR) << "DdmServer.broadcast " << event << " failed";
2224 env->ExceptionDescribe();
2225 env->ExceptionClear();
2226 }
2227}
2228
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002229void Dbg::DdmConnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08002230 Dbg::DdmBroadcast(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002231}
2232
2233void Dbg::DdmDisconnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08002234 Dbg::DdmBroadcast(false);
Elliott Hughes47fce012011-10-25 18:37:19 -07002235 gDdmThreadNotification = false;
2236}
2237
2238/*
Elliott Hughes82188472011-11-07 18:11:48 -08002239 * Send a notification when a thread starts, stops, or changes its name.
Elliott Hughes47fce012011-10-25 18:37:19 -07002240 *
2241 * Because we broadcast the full set of threads when the notifications are
2242 * first enabled, it's possible for "thread" to be actively executing.
2243 */
Elliott Hughes82188472011-11-07 18:11:48 -08002244void Dbg::DdmSendThreadNotification(Thread* t, uint32_t type) {
Elliott Hughes47fce012011-10-25 18:37:19 -07002245 if (!gDdmThreadNotification) {
2246 return;
2247 }
2248
Elliott Hughes82188472011-11-07 18:11:48 -08002249 if (type == CHUNK_TYPE("THDE")) {
Elliott Hughes47fce012011-10-25 18:37:19 -07002250 uint8_t buf[4];
Elliott Hughesf7c3b662011-10-27 12:04:56 -07002251 JDWP::Set4BE(&buf[0], t->GetThinLockId());
Elliott Hughes47fce012011-10-25 18:37:19 -07002252 Dbg::DdmSendChunk(CHUNK_TYPE("THDE"), 4, buf);
Elliott Hughes82188472011-11-07 18:11:48 -08002253 } else {
2254 CHECK(type == CHUNK_TYPE("THCR") || type == CHUNK_TYPE("THNM")) << type;
Elliott Hughes899e7892012-01-24 14:57:32 -08002255 SirtRef<String> name(t->GetThreadName());
Elliott Hughes82188472011-11-07 18:11:48 -08002256 size_t char_count = (name.get() != NULL) ? name->GetLength() : 0;
2257 const jchar* chars = name->GetCharArray()->GetData();
2258
Elliott Hughes21f32d72011-11-09 17:44:13 -08002259 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08002260 JDWP::Append4BE(bytes, t->GetThinLockId());
2261 JDWP::AppendUtf16BE(bytes, chars, char_count);
Elliott Hughes21f32d72011-11-09 17:44:13 -08002262 CHECK_EQ(bytes.size(), char_count*2 + sizeof(uint32_t)*2);
2263 Dbg::DdmSendChunk(type, bytes);
Elliott Hughes47fce012011-10-25 18:37:19 -07002264 }
2265}
2266
Elliott Hughesa2155262011-11-16 16:26:58 -08002267static void DdmSendThreadStartCallback(Thread* t, void*) {
Elliott Hughes82188472011-11-07 18:11:48 -08002268 Dbg::DdmSendThreadNotification(t, CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07002269}
2270
2271void Dbg::DdmSetThreadNotification(bool enable) {
2272 // We lock the thread list to avoid sending duplicate events or missing
2273 // a thread change. We should be okay holding this lock while sending
2274 // the messages out. (We have to hold it while accessing a live thread.)
Elliott Hughesbbd9d832011-11-07 14:40:00 -08002275 ScopedThreadListLock thread_list_lock;
Elliott Hughes47fce012011-10-25 18:37:19 -07002276
2277 gDdmThreadNotification = enable;
2278 if (enable) {
Elliott Hughesbfe487b2011-10-26 15:48:55 -07002279 Runtime::Current()->GetThreadList()->ForEach(DdmSendThreadStartCallback, NULL);
Elliott Hughes47fce012011-10-25 18:37:19 -07002280 }
2281}
2282
Elliott Hughesa2155262011-11-16 16:26:58 -08002283void Dbg::PostThreadStartOrStop(Thread* t, uint32_t type) {
Elliott Hughes47fce012011-10-25 18:37:19 -07002284 if (gDebuggerActive) {
2285 JDWP::ObjectId id = gRegistry->Add(t->GetPeer());
Elliott Hughes82188472011-11-07 18:11:48 -08002286 gJdwpState->PostThreadChange(id, type == CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07002287 }
Elliott Hughes82188472011-11-07 18:11:48 -08002288 Dbg::DdmSendThreadNotification(t, type);
Elliott Hughes47fce012011-10-25 18:37:19 -07002289}
2290
2291void Dbg::PostThreadStart(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08002292 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07002293}
2294
2295void Dbg::PostThreadDeath(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08002296 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THDE"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002297}
2298
Elliott Hughes82188472011-11-07 18:11:48 -08002299void Dbg::DdmSendChunk(uint32_t type, size_t byte_count, const uint8_t* buf) {
Elliott Hughes3bb81562011-10-21 18:52:59 -07002300 CHECK(buf != NULL);
2301 iovec vec[1];
2302 vec[0].iov_base = reinterpret_cast<void*>(const_cast<uint8_t*>(buf));
2303 vec[0].iov_len = byte_count;
2304 Dbg::DdmSendChunkV(type, vec, 1);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002305}
2306
Elliott Hughes21f32d72011-11-09 17:44:13 -08002307void Dbg::DdmSendChunk(uint32_t type, const std::vector<uint8_t>& bytes) {
2308 DdmSendChunk(type, bytes.size(), &bytes[0]);
2309}
2310
Elliott Hughescccd84f2011-12-05 16:51:54 -08002311void Dbg::DdmSendChunkV(uint32_t type, const struct iovec* iov, int iov_count) {
Elliott Hughes3bb81562011-10-21 18:52:59 -07002312 if (gJdwpState == NULL) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002313 VLOG(jdwp) << "Debugger thread not active, ignoring DDM send: " << type;
Elliott Hughes3bb81562011-10-21 18:52:59 -07002314 } else {
Elliott Hughescccd84f2011-12-05 16:51:54 -08002315 gJdwpState->DdmSendChunkV(type, iov, iov_count);
Elliott Hughes3bb81562011-10-21 18:52:59 -07002316 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002317}
2318
Elliott Hughes767a1472011-10-26 18:49:02 -07002319int Dbg::DdmHandleHpifChunk(HpifWhen when) {
2320 if (when == HPIF_WHEN_NOW) {
Elliott Hughes7162ad92011-10-27 14:08:42 -07002321 DdmSendHeapInfo(when);
Elliott Hughes767a1472011-10-26 18:49:02 -07002322 return true;
2323 }
2324
2325 if (when != HPIF_WHEN_NEVER && when != HPIF_WHEN_NEXT_GC && when != HPIF_WHEN_EVERY_GC) {
2326 LOG(ERROR) << "invalid HpifWhen value: " << static_cast<int>(when);
2327 return false;
2328 }
2329
2330 gDdmHpifWhen = when;
2331 return true;
2332}
2333
2334bool Dbg::DdmHandleHpsgNhsgChunk(Dbg::HpsgWhen when, Dbg::HpsgWhat what, bool native) {
2335 if (when != HPSG_WHEN_NEVER && when != HPSG_WHEN_EVERY_GC) {
2336 LOG(ERROR) << "invalid HpsgWhen value: " << static_cast<int>(when);
2337 return false;
2338 }
2339
2340 if (what != HPSG_WHAT_MERGED_OBJECTS && what != HPSG_WHAT_DISTINCT_OBJECTS) {
2341 LOG(ERROR) << "invalid HpsgWhat value: " << static_cast<int>(what);
2342 return false;
2343 }
2344
2345 if (native) {
2346 gDdmNhsgWhen = when;
2347 gDdmNhsgWhat = what;
2348 } else {
2349 gDdmHpsgWhen = when;
2350 gDdmHpsgWhat = what;
2351 }
2352 return true;
2353}
2354
Elliott Hughes7162ad92011-10-27 14:08:42 -07002355void Dbg::DdmSendHeapInfo(HpifWhen reason) {
2356 // If there's a one-shot 'when', reset it.
2357 if (reason == gDdmHpifWhen) {
2358 if (gDdmHpifWhen == HPIF_WHEN_NEXT_GC) {
2359 gDdmHpifWhen = HPIF_WHEN_NEVER;
2360 }
2361 }
2362
2363 /*
2364 * Chunk HPIF (client --> server)
2365 *
2366 * Heap Info. General information about the heap,
2367 * suitable for a summary display.
2368 *
2369 * [u4]: number of heaps
2370 *
2371 * For each heap:
2372 * [u4]: heap ID
2373 * [u8]: timestamp in ms since Unix epoch
2374 * [u1]: capture reason (same as 'when' value from server)
2375 * [u4]: max heap size in bytes (-Xmx)
2376 * [u4]: current heap size in bytes
2377 * [u4]: current number of bytes allocated
2378 * [u4]: current number of objects allocated
2379 */
2380 uint8_t heap_count = 1;
Elliott Hughes21f32d72011-11-09 17:44:13 -08002381 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08002382 JDWP::Append4BE(bytes, heap_count);
2383 JDWP::Append4BE(bytes, 1); // Heap id (bogus; we only have one heap).
2384 JDWP::Append8BE(bytes, MilliTime());
2385 JDWP::Append1BE(bytes, reason);
2386 JDWP::Append4BE(bytes, Heap::GetMaxMemory()); // Max allowed heap size in bytes.
2387 JDWP::Append4BE(bytes, Heap::GetTotalMemory()); // Current heap size in bytes.
2388 JDWP::Append4BE(bytes, Heap::GetBytesAllocated());
2389 JDWP::Append4BE(bytes, Heap::GetObjectsAllocated());
Elliott Hughes21f32d72011-11-09 17:44:13 -08002390 CHECK_EQ(bytes.size(), 4U + (heap_count * (4 + 8 + 1 + 4 + 4 + 4 + 4)));
2391 Dbg::DdmSendChunk(CHUNK_TYPE("HPIF"), bytes);
Elliott Hughes767a1472011-10-26 18:49:02 -07002392}
2393
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002394enum HpsgSolidity {
2395 SOLIDITY_FREE = 0,
2396 SOLIDITY_HARD = 1,
2397 SOLIDITY_SOFT = 2,
2398 SOLIDITY_WEAK = 3,
2399 SOLIDITY_PHANTOM = 4,
2400 SOLIDITY_FINALIZABLE = 5,
2401 SOLIDITY_SWEEP = 6,
2402};
2403
2404enum HpsgKind {
2405 KIND_OBJECT = 0,
2406 KIND_CLASS_OBJECT = 1,
2407 KIND_ARRAY_1 = 2,
2408 KIND_ARRAY_2 = 3,
2409 KIND_ARRAY_4 = 4,
2410 KIND_ARRAY_8 = 5,
2411 KIND_UNKNOWN = 6,
2412 KIND_NATIVE = 7,
2413};
2414
2415#define HPSG_PARTIAL (1<<7)
2416#define HPSG_STATE(solidity, kind) ((uint8_t)((((kind) & 0x7) << 3) | ((solidity) & 0x7)))
2417
Ian Rogers30fab402012-01-23 15:43:46 -08002418class HeapChunkContext {
2419 public:
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002420 // Maximum chunk size. Obtain this from the formula:
2421 // (((maximum_heap_size / ALLOCATION_UNIT_SIZE) + 255) / 256) * 2
2422 HeapChunkContext(bool merge, bool native)
Ian Rogers30fab402012-01-23 15:43:46 -08002423 : buf_(16384 - 16),
2424 type_(0),
2425 merge_(merge) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002426 Reset();
2427 if (native) {
Ian Rogers30fab402012-01-23 15:43:46 -08002428 type_ = CHUNK_TYPE("NHSG");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002429 } else {
Ian Rogers30fab402012-01-23 15:43:46 -08002430 type_ = merge ? CHUNK_TYPE("HPSG") : CHUNK_TYPE("HPSO");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002431 }
2432 }
2433
2434 ~HeapChunkContext() {
Ian Rogers30fab402012-01-23 15:43:46 -08002435 if (p_ > &buf_[0]) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002436 Flush();
2437 }
2438 }
2439
2440 void EnsureHeader(const void* chunk_ptr) {
Ian Rogers30fab402012-01-23 15:43:46 -08002441 if (!needHeader_) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002442 return;
2443 }
2444
2445 // Start a new HPSx chunk.
Ian Rogers30fab402012-01-23 15:43:46 -08002446 JDWP::Write4BE(&p_, 1); // Heap id (bogus; we only have one heap).
2447 JDWP::Write1BE(&p_, 8); // Size of allocation unit, in bytes.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002448
Ian Rogers30fab402012-01-23 15:43:46 -08002449 JDWP::Write4BE(&p_, reinterpret_cast<uintptr_t>(chunk_ptr)); // virtual address of segment start.
2450 JDWP::Write4BE(&p_, 0); // offset of this piece (relative to the virtual address).
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002451 // [u4]: length of piece, in allocation units
2452 // 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 -08002453 pieceLenField_ = p_;
2454 JDWP::Write4BE(&p_, 0x55555555);
2455 needHeader_ = false;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002456 }
2457
2458 void Flush() {
2459 // Patch the "length of piece" field.
Ian Rogers30fab402012-01-23 15:43:46 -08002460 CHECK_LE(&buf_[0], pieceLenField_);
2461 CHECK_LE(pieceLenField_, p_);
2462 JDWP::Set4BE(pieceLenField_, totalAllocationUnits_);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002463
Ian Rogers30fab402012-01-23 15:43:46 -08002464 Dbg::DdmSendChunk(type_, p_ - &buf_[0], &buf_[0]);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002465 Reset();
2466 }
2467
Ian Rogers30fab402012-01-23 15:43:46 -08002468 static void HeapChunkCallback(void* start, void* end, size_t used_bytes, void* arg) {
2469 reinterpret_cast<HeapChunkContext*>(arg)->HeapChunkCallback(start, end, used_bytes);
Elliott Hughesa2155262011-11-16 16:26:58 -08002470 }
2471
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002472 private:
Elliott Hughesa2155262011-11-16 16:26:58 -08002473 enum { ALLOCATION_UNIT_SIZE = 8 };
2474
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002475 void Reset() {
Ian Rogers30fab402012-01-23 15:43:46 -08002476 p_ = &buf_[0];
2477 totalAllocationUnits_ = 0;
2478 needHeader_ = true;
2479 pieceLenField_ = NULL;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002480 }
2481
Ian Rogers30fab402012-01-23 15:43:46 -08002482 void HeapChunkCallback(void* start, void* end, size_t used_bytes) {
2483 // Note: heap call backs cannot manipulate the heap upon which they are crawling, care is taken
2484 // in the following code not to allocate memory, by ensuring buf_ is of the correct size
2485
2486 const void* user_ptr = used_bytes > 0 ? const_cast<void*>(start) : NULL;
2487 // from malloc.c mem2chunk(mem)
2488 const void* chunk_ptr =
2489 reinterpret_cast<const void*>(reinterpret_cast<const char*>(const_cast<void*>(start)) -
2490 (2 * sizeof(size_t)));
2491 // from malloc.c chunksize
2492 size_t chunk_len = (*reinterpret_cast<size_t* const*>(chunk_ptr))[1] & ~7;
2493
2494
2495 //size_t chunk_len = malloc_usable_size(user_ptr);
Elliott Hughesa2155262011-11-16 16:26:58 -08002496 CHECK_EQ((chunk_len & (ALLOCATION_UNIT_SIZE-1)), 0U);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002497
Elliott Hughesa2155262011-11-16 16:26:58 -08002498 /* Make sure there's enough room left in the buffer.
2499 * We need to use two bytes for every fractional 256
2500 * allocation units used by the chunk.
2501 */
2502 {
2503 size_t needed = (((chunk_len/ALLOCATION_UNIT_SIZE + 255) / 256) * 2);
Ian Rogers30fab402012-01-23 15:43:46 -08002504 size_t bytesLeft = buf_.size() - (size_t)(p_ - &buf_[0]);
Elliott Hughesa2155262011-11-16 16:26:58 -08002505 if (bytesLeft < needed) {
2506 Flush();
2507 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002508
Ian Rogers30fab402012-01-23 15:43:46 -08002509 bytesLeft = buf_.size() - (size_t)(p_ - &buf_[0]);
Elliott Hughesa2155262011-11-16 16:26:58 -08002510 if (bytesLeft < needed) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08002511 LOG(WARNING) << "Chunk is too big to transmit (chunk_len=" << chunk_len << ", " << needed << " bytes)";
Elliott Hughesa2155262011-11-16 16:26:58 -08002512 return;
2513 }
2514 }
2515
2516 // OLD-TODO: notice when there's a gap and start a new heap, or at least a new range.
2517 EnsureHeader(chunk_ptr);
2518
2519 // Determine the type of this chunk.
2520 // OLD-TODO: if context.merge, see if this chunk is different from the last chunk.
2521 // If it's the same, we should combine them.
Ian Rogers30fab402012-01-23 15:43:46 -08002522 uint8_t state = ExamineObject(reinterpret_cast<const Object*>(user_ptr), (type_ == CHUNK_TYPE("NHSG")));
Elliott Hughesa2155262011-11-16 16:26:58 -08002523
2524 // Write out the chunk description.
2525 chunk_len /= ALLOCATION_UNIT_SIZE; // convert to allocation units
Ian Rogers30fab402012-01-23 15:43:46 -08002526 totalAllocationUnits_ += chunk_len;
Elliott Hughesa2155262011-11-16 16:26:58 -08002527 while (chunk_len > 256) {
Ian Rogers30fab402012-01-23 15:43:46 -08002528 *p_++ = state | HPSG_PARTIAL;
2529 *p_++ = 255; // length - 1
Elliott Hughesa2155262011-11-16 16:26:58 -08002530 chunk_len -= 256;
2531 }
Ian Rogers30fab402012-01-23 15:43:46 -08002532 *p_++ = state;
2533 *p_++ = chunk_len - 1;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002534 }
2535
Elliott Hughesa2155262011-11-16 16:26:58 -08002536 uint8_t ExamineObject(const Object* o, bool is_native_heap) {
2537 if (o == NULL) {
2538 return HPSG_STATE(SOLIDITY_FREE, 0);
2539 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002540
Elliott Hughesa2155262011-11-16 16:26:58 -08002541 // It's an allocated chunk. Figure out what it is.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002542
Elliott Hughesa2155262011-11-16 16:26:58 -08002543 // If we're looking at the native heap, we'll just return
2544 // (SOLIDITY_HARD, KIND_NATIVE) for all allocated chunks.
2545 if (is_native_heap || !Heap::IsLiveObjectLocked(o)) {
2546 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
2547 }
2548
2549 Class* c = o->GetClass();
2550 if (c == NULL) {
2551 // The object was probably just created but hasn't been initialized yet.
2552 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
2553 }
2554
2555 if (!Heap::IsHeapAddress(c)) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08002556 LOG(WARNING) << "Invalid class for managed heap object: " << o << " " << c;
Elliott Hughesa2155262011-11-16 16:26:58 -08002557 return HPSG_STATE(SOLIDITY_HARD, KIND_UNKNOWN);
2558 }
2559
2560 if (c->IsClassClass()) {
2561 return HPSG_STATE(SOLIDITY_HARD, KIND_CLASS_OBJECT);
2562 }
2563
2564 if (c->IsArrayClass()) {
2565 if (o->IsObjectArray()) {
2566 return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
2567 }
2568 switch (c->GetComponentSize()) {
2569 case 1: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_1);
2570 case 2: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_2);
2571 case 4: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
2572 case 8: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_8);
2573 }
2574 }
2575
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002576 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
2577 }
2578
Ian Rogers30fab402012-01-23 15:43:46 -08002579 std::vector<uint8_t> buf_;
2580 uint8_t* p_;
2581 uint8_t* pieceLenField_;
2582 size_t totalAllocationUnits_;
2583 uint32_t type_;
2584 bool merge_;
2585 bool needHeader_;
2586
Elliott Hughesa2155262011-11-16 16:26:58 -08002587 DISALLOW_COPY_AND_ASSIGN(HeapChunkContext);
2588};
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002589
2590void Dbg::DdmSendHeapSegments(bool native) {
2591 Dbg::HpsgWhen when;
2592 Dbg::HpsgWhat what;
2593 if (!native) {
2594 when = gDdmHpsgWhen;
2595 what = gDdmHpsgWhat;
2596 } else {
2597 when = gDdmNhsgWhen;
2598 what = gDdmNhsgWhat;
2599 }
2600 if (when == HPSG_WHEN_NEVER) {
2601 return;
2602 }
2603
2604 // Figure out what kind of chunks we'll be sending.
2605 CHECK(what == HPSG_WHAT_MERGED_OBJECTS || what == HPSG_WHAT_DISTINCT_OBJECTS) << static_cast<int>(what);
2606
2607 // First, send a heap start chunk.
2608 uint8_t heap_id[4];
2609 JDWP::Set4BE(&heap_id[0], 1); // Heap id (bogus; we only have one heap).
2610 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHST") : CHUNK_TYPE("HPST"), sizeof(heap_id), heap_id);
2611
2612 // Send a series of heap segment chunks.
Elliott Hughesa2155262011-11-16 16:26:58 -08002613 HeapChunkContext context((what == HPSG_WHAT_MERGED_OBJECTS), native);
2614 if (native) {
Ian Rogers30fab402012-01-23 15:43:46 -08002615 // TODO: enable when bionic has moved to dlmalloc 2.8.5
2616 // dlmalloc_inspect_all(HeapChunkContext::HeapChunkCallback, &context);
2617 UNIMPLEMENTED(WARNING) << "Native heap send heap segments";
Elliott Hughesa2155262011-11-16 16:26:58 -08002618 } else {
Ian Rogers30fab402012-01-23 15:43:46 -08002619 Heap::GetAllocSpace()->Walk(HeapChunkContext::HeapChunkCallback, &context);
Elliott Hughesa2155262011-11-16 16:26:58 -08002620 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002621
2622 // Finally, send a heap end chunk.
2623 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHEN") : CHUNK_TYPE("HPEN"), sizeof(heap_id), heap_id);
Elliott Hughes767a1472011-10-26 18:49:02 -07002624}
2625
Elliott Hughes545a0642011-11-08 19:10:03 -08002626void Dbg::SetAllocTrackingEnabled(bool enabled) {
2627 MutexLock mu(gAllocTrackerLock);
2628 if (enabled) {
2629 if (recent_allocation_records_ == NULL) {
2630 LOG(INFO) << "Enabling alloc tracker (" << kNumAllocRecords << " entries, "
2631 << kMaxAllocRecordStackDepth << " frames --> "
2632 << (sizeof(AllocRecord) * kNumAllocRecords) << " bytes)";
2633 gAllocRecordHead = gAllocRecordCount = 0;
2634 recent_allocation_records_ = new AllocRecord[kNumAllocRecords];
2635 CHECK(recent_allocation_records_ != NULL);
2636 }
2637 } else {
2638 delete[] recent_allocation_records_;
2639 recent_allocation_records_ = NULL;
2640 }
2641}
2642
2643struct AllocRecordStackVisitor : public Thread::StackVisitor {
Elliott Hughesba8eee12012-01-24 20:25:24 -08002644 explicit AllocRecordStackVisitor(AllocRecord* record) : record(record), depth(0) {
Elliott Hughes545a0642011-11-08 19:10:03 -08002645 }
2646
2647 virtual void VisitFrame(const Frame& f, uintptr_t pc) {
2648 if (depth >= kMaxAllocRecordStackDepth) {
2649 return;
2650 }
2651 Method* m = f.GetMethod();
2652 if (m == NULL || m->IsCalleeSaveMethod()) {
2653 return;
2654 }
2655 record->stack[depth].method = m;
2656 record->stack[depth].raw_pc = pc;
2657 ++depth;
2658 }
2659
2660 ~AllocRecordStackVisitor() {
2661 // Clear out any unused stack trace elements.
2662 for (; depth < kMaxAllocRecordStackDepth; ++depth) {
2663 record->stack[depth].method = NULL;
2664 record->stack[depth].raw_pc = 0;
2665 }
2666 }
2667
2668 AllocRecord* record;
2669 size_t depth;
2670};
2671
2672void Dbg::RecordAllocation(Class* type, size_t byte_count) {
2673 Thread* self = Thread::Current();
2674 CHECK(self != NULL);
2675
2676 MutexLock mu(gAllocTrackerLock);
2677 if (recent_allocation_records_ == NULL) {
2678 return;
2679 }
2680
2681 // Advance and clip.
2682 if (++gAllocRecordHead == kNumAllocRecords) {
2683 gAllocRecordHead = 0;
2684 }
2685
2686 // Fill in the basics.
2687 AllocRecord* record = &recent_allocation_records_[gAllocRecordHead];
2688 record->type = type;
2689 record->byte_count = byte_count;
2690 record->thin_lock_id = self->GetThinLockId();
2691
2692 // Fill in the stack trace.
2693 AllocRecordStackVisitor visitor(record);
2694 self->WalkStack(&visitor);
2695
2696 if (gAllocRecordCount < kNumAllocRecords) {
2697 ++gAllocRecordCount;
2698 }
2699}
2700
2701/*
2702 * Return the index of the head element.
2703 *
2704 * We point at the most-recently-written record, so if allocRecordCount is 1
2705 * we want to use the current element. Take "head+1" and subtract count
2706 * from it.
2707 *
2708 * We need to handle underflow in our circular buffer, so we add
2709 * kNumAllocRecords and then mask it back down.
2710 */
2711inline static int headIndex() {
2712 return (gAllocRecordHead+1 + kNumAllocRecords - gAllocRecordCount) & (kNumAllocRecords-1);
2713}
2714
2715void Dbg::DumpRecentAllocations() {
2716 MutexLock mu(gAllocTrackerLock);
2717 if (recent_allocation_records_ == NULL) {
2718 LOG(INFO) << "Not recording tracked allocations";
2719 return;
2720 }
2721
2722 // "i" is the head of the list. We want to start at the end of the
2723 // list and move forward to the tail.
2724 size_t i = headIndex();
2725 size_t count = gAllocRecordCount;
2726
2727 LOG(INFO) << "Tracked allocations, (head=" << gAllocRecordHead << " count=" << count << ")";
2728 while (count--) {
2729 AllocRecord* record = &recent_allocation_records_[i];
2730
Elliott Hughesaa6e1cd2012-01-18 19:26:06 -08002731 LOG(INFO) << StringPrintf(" T=%-2d %6zd ", record->thin_lock_id, record->byte_count)
Elliott Hughes545a0642011-11-08 19:10:03 -08002732 << PrettyClass(record->type);
2733
2734 for (size_t stack_frame = 0; stack_frame < kMaxAllocRecordStackDepth; ++stack_frame) {
2735 const Method* m = record->stack[stack_frame].method;
2736 if (m == NULL) {
2737 break;
2738 }
2739 LOG(INFO) << " " << PrettyMethod(m) << " line " << record->stack[stack_frame].LineNumber();
2740 }
2741
2742 // pause periodically to help logcat catch up
2743 if ((count % 5) == 0) {
2744 usleep(40000);
2745 }
2746
2747 i = (i + 1) & (kNumAllocRecords-1);
2748 }
2749}
2750
2751class StringTable {
2752 public:
2753 StringTable() {
2754 }
2755
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002756 void Add(const char* s) {
Elliott Hughes545a0642011-11-08 19:10:03 -08002757 table_.insert(s);
2758 }
2759
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002760 size_t IndexOf(const char* s) {
Elliott Hughes545a0642011-11-08 19:10:03 -08002761 return std::distance(table_.begin(), table_.find(s));
2762 }
2763
2764 size_t Size() {
2765 return table_.size();
2766 }
2767
2768 void WriteTo(std::vector<uint8_t>& bytes) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002769 typedef std::set<const char*>::const_iterator It; // TODO: C++0x auto
Elliott Hughes545a0642011-11-08 19:10:03 -08002770 for (It it = table_.begin(); it != table_.end(); ++it) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002771 const char* s = *it;
2772 size_t s_len = CountModifiedUtf8Chars(s);
2773 UniquePtr<uint16_t> s_utf16(new uint16_t[s_len]);
2774 ConvertModifiedUtf8ToUtf16(s_utf16.get(), s);
2775 JDWP::AppendUtf16BE(bytes, s_utf16.get(), s_len);
Elliott Hughes545a0642011-11-08 19:10:03 -08002776 }
2777 }
2778
2779 private:
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002780 std::set<const char*> table_;
Elliott Hughes545a0642011-11-08 19:10:03 -08002781 DISALLOW_COPY_AND_ASSIGN(StringTable);
2782};
2783
2784/*
2785 * The data we send to DDMS contains everything we have recorded.
2786 *
2787 * Message header (all values big-endian):
2788 * (1b) message header len (to allow future expansion); includes itself
2789 * (1b) entry header len
2790 * (1b) stack frame len
2791 * (2b) number of entries
2792 * (4b) offset to string table from start of message
2793 * (2b) number of class name strings
2794 * (2b) number of method name strings
2795 * (2b) number of source file name strings
2796 * For each entry:
2797 * (4b) total allocation size
2798 * (2b) threadId
2799 * (2b) allocated object's class name index
2800 * (1b) stack depth
2801 * For each stack frame:
2802 * (2b) method's class name
2803 * (2b) method name
2804 * (2b) method source file
2805 * (2b) line number, clipped to 32767; -2 if native; -1 if no source
2806 * (xb) class name strings
2807 * (xb) method name strings
2808 * (xb) source file strings
2809 *
2810 * As with other DDM traffic, strings are sent as a 4-byte length
2811 * followed by UTF-16 data.
2812 *
2813 * We send up 16-bit unsigned indexes into string tables. In theory there
2814 * can be (kMaxAllocRecordStackDepth * kNumAllocRecords) unique strings in
2815 * each table, but in practice there should be far fewer.
2816 *
2817 * The chief reason for using a string table here is to keep the size of
2818 * the DDMS message to a minimum. This is partly to make the protocol
2819 * efficient, but also because we have to form the whole thing up all at
2820 * once in a memory buffer.
2821 *
2822 * We use separate string tables for class names, method names, and source
2823 * files to keep the indexes small. There will generally be no overlap
2824 * between the contents of these tables.
2825 */
2826jbyteArray Dbg::GetRecentAllocations() {
2827 if (false) {
2828 DumpRecentAllocations();
2829 }
2830
2831 MutexLock mu(gAllocTrackerLock);
2832
2833 /*
2834 * Part 1: generate string tables.
2835 */
2836 StringTable class_names;
2837 StringTable method_names;
2838 StringTable filenames;
2839
2840 int count = gAllocRecordCount;
2841 int idx = headIndex();
2842 while (count--) {
2843 AllocRecord* record = &recent_allocation_records_[idx];
2844
Elliott Hughes91250e02011-12-13 22:30:35 -08002845 class_names.Add(ClassHelper(record->type).GetDescriptor());
Elliott Hughes545a0642011-11-08 19:10:03 -08002846
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002847 MethodHelper mh;
Elliott Hughes545a0642011-11-08 19:10:03 -08002848 for (size_t i = 0; i < kMaxAllocRecordStackDepth; i++) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002849 Method* m = record->stack[i].method;
2850 mh.ChangeMethod(m);
Elliott Hughes545a0642011-11-08 19:10:03 -08002851 if (m != NULL) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002852 class_names.Add(mh.GetDeclaringClassDescriptor());
2853 method_names.Add(mh.GetName());
2854 filenames.Add(mh.GetDeclaringClassSourceFile());
Elliott Hughes545a0642011-11-08 19:10:03 -08002855 }
2856 }
2857
2858 idx = (idx + 1) & (kNumAllocRecords-1);
2859 }
2860
2861 LOG(INFO) << "allocation records: " << gAllocRecordCount;
2862
2863 /*
2864 * Part 2: allocate a buffer and generate the output.
2865 */
2866 std::vector<uint8_t> bytes;
2867
2868 // (1b) message header len (to allow future expansion); includes itself
2869 // (1b) entry header len
2870 // (1b) stack frame len
2871 const int kMessageHeaderLen = 15;
2872 const int kEntryHeaderLen = 9;
2873 const int kStackFrameLen = 8;
2874 JDWP::Append1BE(bytes, kMessageHeaderLen);
2875 JDWP::Append1BE(bytes, kEntryHeaderLen);
2876 JDWP::Append1BE(bytes, kStackFrameLen);
2877
2878 // (2b) number of entries
2879 // (4b) offset to string table from start of message
2880 // (2b) number of class name strings
2881 // (2b) number of method name strings
2882 // (2b) number of source file name strings
2883 JDWP::Append2BE(bytes, gAllocRecordCount);
2884 size_t string_table_offset = bytes.size();
2885 JDWP::Append4BE(bytes, 0); // We'll patch this later...
2886 JDWP::Append2BE(bytes, class_names.Size());
2887 JDWP::Append2BE(bytes, method_names.Size());
2888 JDWP::Append2BE(bytes, filenames.Size());
2889
2890 count = gAllocRecordCount;
2891 idx = headIndex();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002892 ClassHelper kh;
Elliott Hughes545a0642011-11-08 19:10:03 -08002893 while (count--) {
2894 // For each entry:
2895 // (4b) total allocation size
2896 // (2b) thread id
2897 // (2b) allocated object's class name index
2898 // (1b) stack depth
2899 AllocRecord* record = &recent_allocation_records_[idx];
2900 size_t stack_depth = record->GetDepth();
2901 JDWP::Append4BE(bytes, record->byte_count);
2902 JDWP::Append2BE(bytes, record->thin_lock_id);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002903 kh.ChangeClass(record->type);
Elliott Hughes91250e02011-12-13 22:30:35 -08002904 JDWP::Append2BE(bytes, class_names.IndexOf(kh.GetDescriptor()));
Elliott Hughes545a0642011-11-08 19:10:03 -08002905 JDWP::Append1BE(bytes, stack_depth);
2906
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002907 MethodHelper mh;
Elliott Hughes545a0642011-11-08 19:10:03 -08002908 for (size_t stack_frame = 0; stack_frame < stack_depth; ++stack_frame) {
2909 // For each stack frame:
2910 // (2b) method's class name
2911 // (2b) method name
2912 // (2b) method source file
2913 // (2b) line number, clipped to 32767; -2 if native; -1 if no source
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002914 mh.ChangeMethod(record->stack[stack_frame].method);
2915 JDWP::Append2BE(bytes, class_names.IndexOf(mh.GetDeclaringClassDescriptor()));
2916 JDWP::Append2BE(bytes, method_names.IndexOf(mh.GetName()));
2917 JDWP::Append2BE(bytes, filenames.IndexOf(mh.GetDeclaringClassSourceFile()));
Elliott Hughes545a0642011-11-08 19:10:03 -08002918 JDWP::Append2BE(bytes, record->stack[stack_frame].LineNumber());
2919 }
2920
2921 idx = (idx + 1) & (kNumAllocRecords-1);
2922 }
2923
2924 // (xb) class name strings
2925 // (xb) method name strings
2926 // (xb) source file strings
2927 JDWP::Set4BE(&bytes[string_table_offset], bytes.size());
2928 class_names.WriteTo(bytes);
2929 method_names.WriteTo(bytes);
2930 filenames.WriteTo(bytes);
2931
2932 JNIEnv* env = Thread::Current()->GetJniEnv();
2933 jbyteArray result = env->NewByteArray(bytes.size());
2934 if (result != NULL) {
2935 env->SetByteArrayRegion(result, 0, bytes.size(), reinterpret_cast<const jbyte*>(&bytes[0]));
2936 }
2937 return result;
2938}
2939
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002940} // namespace art