blob: cd1081d6a0a2ab7d9731aa46e270cf2bba53c56a [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;
136 int line; // May be -1.
137 //const AddressSet* pAddressSet; /* if non-null, address set for line */
138 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 Hughesa2155262011-11-16 16:26:58 -0800502std::string Dbg::GetClassDescriptor(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 }
507 return 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);
550 CHECK(thread_peer != NULL);
551 return Thread::FromManagedThread(thread_peer);
552}
553
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800554JDWP::JdwpError Dbg::GetSuperclass(JDWP::RefTypeId id, JDWP::RefTypeId& superclassId) {
555 JDWP::JdwpError status;
556 Class* c = DecodeClass(id, status);
557 if (c == NULL) {
558 return status;
559 }
560 if (c->IsInterface()) {
561 // http://code.google.com/p/android/issues/detail?id=20856
562 superclassId = NULL;
563 } else {
564 superclassId = gRegistry->Add(c->GetSuperClass());
565 }
566 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700567}
568
569JDWP::ObjectId Dbg::GetClassLoader(JDWP::RefTypeId id) {
Elliott Hughes1bba14f2011-12-01 18:00:36 -0800570 Object* o = gRegistry->Get<Object*>(id);
571 return gRegistry->Add(o->GetClass()->GetClassLoader());
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700572}
573
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800574bool Dbg::GetAccessFlags(JDWP::RefTypeId id, uint32_t& access_flags) {
575 Object* o = gRegistry->Get<Object*>(id);
576 if (o == NULL || !o->IsClass()) {
577 return false;
578 }
579 access_flags = o->AsClass()->GetAccessFlags() & kAccJavaFlagsMask;
580 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700581}
582
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800583bool Dbg::IsInterface(JDWP::RefTypeId classId, bool& is_interface) {
584 Object* o = gRegistry->Get<Object*>(classId);
585 if (o == NULL || !o->IsClass()) {
586 return false;
587 }
588 is_interface = o->AsClass()->IsInterface();
589 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700590}
591
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800592void Dbg::GetClassList(std::vector<JDWP::RefTypeId>& classes) {
Elliott Hughesa2155262011-11-16 16:26:58 -0800593 // Get the complete list of reference classes (i.e. all classes except
594 // the primitive types).
595 // Returns a newly-allocated buffer full of RefTypeId values.
596 struct ClassListCreator {
Elliott Hughesba8eee12012-01-24 20:25:24 -0800597 explicit ClassListCreator(std::vector<JDWP::RefTypeId>& classes) : classes(classes) {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800598 }
599
Elliott Hughesa2155262011-11-16 16:26:58 -0800600 static bool Visit(Class* c, void* arg) {
601 return reinterpret_cast<ClassListCreator*>(arg)->Visit(c);
602 }
603
604 bool Visit(Class* c) {
605 if (!c->IsPrimitive()) {
606 classes.push_back(static_cast<JDWP::RefTypeId>(gRegistry->Add(c)));
607 }
608 return true;
609 }
610
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800611 std::vector<JDWP::RefTypeId>& classes;
Elliott Hughesa2155262011-11-16 16:26:58 -0800612 };
613
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800614 ClassListCreator clc(classes);
Elliott Hughesa2155262011-11-16 16:26:58 -0800615 Runtime::Current()->GetClassLinker()->VisitClasses(ClassListCreator::Visit, &clc);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700616}
617
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800618bool Dbg::GetClassInfo(JDWP::RefTypeId classId, JDWP::JdwpTypeTag* pTypeTag, uint32_t* pStatus, std::string* pDescriptor) {
619 Object* o = gRegistry->Get<Object*>(classId);
620 if (o == NULL || !o->IsClass()) {
621 return false;
622 }
623
624 Class* c = o->AsClass();
Elliott Hughesa2155262011-11-16 16:26:58 -0800625 if (c->IsArrayClass()) {
626 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
627 *pTypeTag = JDWP::TT_ARRAY;
628 } else {
629 if (c->IsErroneous()) {
630 *pStatus = JDWP::CS_ERROR;
631 } else {
632 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED | JDWP::CS_INITIALIZED;
633 }
634 *pTypeTag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
635 }
636
637 if (pDescriptor != NULL) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800638 *pDescriptor = ClassHelper(c).GetDescriptor();
Elliott Hughesa2155262011-11-16 16:26:58 -0800639 }
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800640 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700641}
642
Elliott Hughesc3b77c72011-12-15 20:56:48 -0800643void Dbg::FindLoadedClassBySignature(const char* descriptor, std::vector<JDWP::RefTypeId>& ids) {
Elliott Hughes6fa602d2011-12-02 17:54:25 -0800644 std::vector<Class*> classes;
645 Runtime::Current()->GetClassLinker()->LookupClasses(descriptor, classes);
646 ids.clear();
647 for (size_t i = 0; i < classes.size(); ++i) {
648 ids.push_back(gRegistry->Add(classes[i]));
649 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700650}
651
Elliott Hughes6fa602d2011-12-02 17:54:25 -0800652void Dbg::GetObjectType(JDWP::ObjectId objectId, JDWP::JdwpTypeTag* pRefTypeTag, JDWP::RefTypeId* pRefTypeId) {
Elliott Hughes499c5132011-11-17 14:55:11 -0800653 Object* o = gRegistry->Get<Object*>(objectId);
654 if (o->GetClass()->IsArrayClass()) {
655 *pRefTypeTag = JDWP::TT_ARRAY;
656 } else if (o->GetClass()->IsInterface()) {
657 *pRefTypeTag = JDWP::TT_INTERFACE;
658 } else {
659 *pRefTypeTag = JDWP::TT_CLASS;
660 }
661 *pRefTypeId = gRegistry->Add(o->GetClass());
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700662}
663
Elliott Hughes1fe7afb2012-02-13 17:23:03 -0800664JDWP::JdwpError Dbg::GetSignature(JDWP::RefTypeId refTypeId, std::string& signature) {
665 JDWP::JdwpError status;
666 Class* c = DecodeClass(refTypeId, status);
667 if (c == NULL) {
668 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800669 }
Elliott Hughes1fe7afb2012-02-13 17:23:03 -0800670 signature = ClassHelper(c).GetDescriptor();
671 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700672}
673
Elliott Hughes03181a82011-11-17 17:22:21 -0800674bool Dbg::GetSourceFile(JDWP::RefTypeId refTypeId, std::string& result) {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800675 Object* o = gRegistry->Get<Object*>(refTypeId);
676 if (o == NULL || !o->IsClass()) {
677 return false;
678 }
679 result = ClassHelper(o->AsClass()).GetSourceFile();
680 return result != NULL;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700681}
682
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700683uint8_t Dbg::GetObjectTag(JDWP::ObjectId objectId) {
Elliott Hughes24437992011-11-30 14:49:33 -0800684 Object* o = gRegistry->Get<Object*>(objectId);
685 return TagFromObject(o);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700686}
687
Elliott Hughesaed4be92011-12-02 16:16:23 -0800688size_t Dbg::GetTagWidth(JDWP::JdwpTag tag) {
Elliott Hughesdbb40792011-11-18 17:05:22 -0800689 switch (tag) {
690 case JDWP::JT_VOID:
691 return 0;
692 case JDWP::JT_BYTE:
693 case JDWP::JT_BOOLEAN:
694 return 1;
695 case JDWP::JT_CHAR:
696 case JDWP::JT_SHORT:
697 return 2;
698 case JDWP::JT_FLOAT:
699 case JDWP::JT_INT:
700 return 4;
701 case JDWP::JT_ARRAY:
702 case JDWP::JT_OBJECT:
703 case JDWP::JT_STRING:
704 case JDWP::JT_THREAD:
705 case JDWP::JT_THREAD_GROUP:
706 case JDWP::JT_CLASS_LOADER:
707 case JDWP::JT_CLASS_OBJECT:
708 return sizeof(JDWP::ObjectId);
709 case JDWP::JT_DOUBLE:
710 case JDWP::JT_LONG:
711 return 8;
712 default:
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800713 LOG(FATAL) << "Unknown tag " << tag;
Elliott Hughesdbb40792011-11-18 17:05:22 -0800714 return -1;
715 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700716}
717
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800718JDWP::JdwpError Dbg::GetArrayLength(JDWP::ObjectId arrayId, int& length) {
719 JDWP::JdwpError status;
720 Array* a = DecodeArray(arrayId, status);
721 if (a == NULL) {
722 return status;
Elliott Hughes24437992011-11-30 14:49:33 -0800723 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800724 length = a->GetLength();
725 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700726}
727
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800728JDWP::JdwpError Dbg::OutputArray(JDWP::ObjectId arrayId, int offset, int count, JDWP::ExpandBuf* pReply) {
729 JDWP::JdwpError status;
730 Array* a = DecodeArray(arrayId, status);
731 if (a == NULL) {
732 return status;
733 }
Elliott Hughes24437992011-11-30 14:49:33 -0800734
735 if (offset < 0 || count < 0 || offset > a->GetLength() || a->GetLength() - offset < count) {
736 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800737 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughes24437992011-11-30 14:49:33 -0800738 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800739 std::string descriptor(ClassHelper(a->GetClass()).GetDescriptor());
Elliott Hughes24437992011-11-30 14:49:33 -0800740 JDWP::JdwpTag tag = BasicTagFromDescriptor(descriptor.c_str() + 1);
741
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800742 expandBufAdd1(pReply, tag);
743 expandBufAdd4BE(pReply, count);
744
Elliott Hughes24437992011-11-30 14:49:33 -0800745 if (IsPrimitiveTag(tag)) {
746 size_t width = GetTagWidth(tag);
747 const uint8_t* src = reinterpret_cast<uint8_t*>(a->GetRawData());
748 uint8_t* dst = expandBufAddSpace(pReply, count * width);
749 if (width == 8) {
750 const uint64_t* src8 = reinterpret_cast<const uint64_t*>(src);
751 for (int i = 0; i < count; ++i) JDWP::Write8BE(&dst, src8[offset + i]);
752 } else if (width == 4) {
753 const uint32_t* src4 = reinterpret_cast<const uint32_t*>(src);
754 for (int i = 0; i < count; ++i) JDWP::Write4BE(&dst, src4[offset + i]);
755 } else if (width == 2) {
756 const uint16_t* src2 = reinterpret_cast<const uint16_t*>(src);
757 for (int i = 0; i < count; ++i) JDWP::Write2BE(&dst, src2[offset + i]);
758 } else {
759 memcpy(dst, &src[offset * width], count * width);
760 }
761 } else {
762 ObjectArray<Object>* oa = a->AsObjectArray<Object>();
763 for (int i = 0; i < count; ++i) {
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800764 Object* element = oa->Get(offset + i);
Elliott Hughes24437992011-11-30 14:49:33 -0800765 JDWP::JdwpTag specific_tag = (element != NULL) ? TagFromObject(element) : tag;
766 expandBufAdd1(pReply, specific_tag);
767 expandBufAddObjectId(pReply, gRegistry->Add(element));
768 }
769 }
770
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800771 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700772}
773
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800774JDWP::JdwpError Dbg::SetArrayElements(JDWP::ObjectId arrayId, int offset, int count, const uint8_t* src) {
775 JDWP::JdwpError status;
776 Array* a = DecodeArray(arrayId, status);
777 if (a == NULL) {
778 return status;
779 }
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800780
781 if (offset < 0 || count < 0 || offset > a->GetLength() || a->GetLength() - offset < count) {
782 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800783 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800784 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800785 std::string descriptor(ClassHelper(a->GetClass()).GetDescriptor());
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800786 JDWP::JdwpTag tag = BasicTagFromDescriptor(descriptor.c_str() + 1);
787
788 if (IsPrimitiveTag(tag)) {
789 size_t width = GetTagWidth(tag);
790 uint8_t* dst = &(reinterpret_cast<uint8_t*>(a->GetRawData())[offset * width]);
791 if (width == 8) {
792 for (int i = 0; i < count; ++i) {
793 // Handle potentially non-aligned memory access one byte at a time for ARM's benefit.
794 uint64_t value;
795 for (size_t j = 0; j < sizeof(uint64_t); ++j) reinterpret_cast<uint8_t*>(&value)[j] = src[j];
796 src += sizeof(uint64_t);
797 JDWP::Write8BE(&dst, value);
798 }
799 } else if (width == 4) {
800 const uint32_t* src4 = reinterpret_cast<const uint32_t*>(src);
801 for (int i = 0; i < count; ++i) JDWP::Write4BE(&dst, src4[i]);
802 } else if (width == 2) {
803 const uint16_t* src2 = reinterpret_cast<const uint16_t*>(src);
804 for (int i = 0; i < count; ++i) JDWP::Write2BE(&dst, src2[i]);
805 } else {
806 memcpy(&dst[offset * width], src, count * width);
807 }
808 } else {
809 ObjectArray<Object>* oa = a->AsObjectArray<Object>();
810 for (int i = 0; i < count; ++i) {
811 JDWP::ObjectId id = JDWP::ReadObjectId(&src);
812 oa->Set(offset + i, gRegistry->Get<Object*>(id));
813 }
814 }
815
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800816 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700817}
818
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800819JDWP::ObjectId Dbg::CreateString(const std::string& str) {
820 return gRegistry->Add(String::AllocFromModifiedUtf8(str.c_str()));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700821}
822
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800823bool Dbg::CreateObject(JDWP::RefTypeId classId, JDWP::ObjectId& new_object) {
824 Object* o = gRegistry->Get<Object*>(classId);
825 if (o == NULL || !o->IsClass()) {
826 return false;
827 }
828 new_object = gRegistry->Add(o->AsClass()->AllocObject());
829 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700830}
831
Elliott Hughesbf13d362011-12-08 15:51:37 -0800832/*
833 * Used by Eclipse's "Display" view to evaluate "new byte[5]" to get "(byte[]) [0, 0, 0, 0, 0]".
834 */
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800835bool Dbg::CreateArrayObject(JDWP::RefTypeId arrayTypeId, uint32_t length, JDWP::ObjectId& new_array) {
836 Object* o = gRegistry->Get<Object*>(arrayTypeId);
837 if (o == NULL || !o->IsClass()) {
838 return false;
839 }
840 new_array = gRegistry->Add(Array::Alloc(o->AsClass(), length));
841 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700842}
843
844bool Dbg::MatchType(JDWP::RefTypeId instClassId, JDWP::RefTypeId classId) {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800845 // TODO: error handling if the RefTypeIds aren't actually Class*s.
Elliott Hughesd07986f2011-12-06 18:27:45 -0800846 return gRegistry->Get<Class*>(instClassId)->InstanceOf(gRegistry->Get<Class*>(classId));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700847}
848
Elliott Hughes86964332012-02-15 19:37:42 -0800849static JDWP::FieldId ToFieldId(const Field* f) {
Elliott Hughes03181a82011-11-17 17:22:21 -0800850#ifdef MOVING_GARBAGE_COLLECTOR
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700851 UNIMPLEMENTED(FATAL);
Elliott Hughes03181a82011-11-17 17:22:21 -0800852#else
853 return static_cast<JDWP::FieldId>(reinterpret_cast<uintptr_t>(f));
854#endif
855}
856
Elliott Hughes86964332012-02-15 19:37:42 -0800857static JDWP::MethodId ToMethodId(const Method* m) {
Elliott Hughes03181a82011-11-17 17:22:21 -0800858#ifdef MOVING_GARBAGE_COLLECTOR
859 UNIMPLEMENTED(FATAL);
860#else
861 return static_cast<JDWP::MethodId>(reinterpret_cast<uintptr_t>(m));
862#endif
863}
864
Elliott Hughes86964332012-02-15 19:37:42 -0800865static Field* FromFieldId(JDWP::FieldId fid) {
Elliott Hughesaed4be92011-12-02 16:16:23 -0800866#ifdef MOVING_GARBAGE_COLLECTOR
867 UNIMPLEMENTED(FATAL);
868#else
869 return reinterpret_cast<Field*>(static_cast<uintptr_t>(fid));
870#endif
871}
872
Elliott Hughes86964332012-02-15 19:37:42 -0800873static Method* FromMethodId(JDWP::MethodId mid) {
Elliott Hughes03181a82011-11-17 17:22:21 -0800874#ifdef MOVING_GARBAGE_COLLECTOR
875 UNIMPLEMENTED(FATAL);
876#else
877 return reinterpret_cast<Method*>(static_cast<uintptr_t>(mid));
878#endif
879}
880
Elliott Hughes86964332012-02-15 19:37:42 -0800881static void SetLocation(JDWP::JdwpLocation& location, Method* m, uintptr_t native_pc) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -0800882 if (m == NULL) {
883 memset(&location, 0, sizeof(location));
884 } else {
885 Class* c = m->GetDeclaringClass();
886 location.typeTag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
887 location.classId = gRegistry->Add(c);
888 location.methodId = ToMethodId(m);
889 location.idx = m->IsNative() ? -1 : m->ToDexPC(native_pc);
890 }
Elliott Hughesd07986f2011-12-06 18:27:45 -0800891}
892
Elliott Hughes03181a82011-11-17 17:22:21 -0800893std::string Dbg::GetMethodName(JDWP::RefTypeId refTypeId, JDWP::MethodId methodId) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800894 Method* m = FromMethodId(methodId);
895 return MethodHelper(m).GetName();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700896}
897
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800898/*
899 * Augment the access flags for synthetic methods and fields by setting
900 * the (as described by the spec) "0xf0000000 bit". Also, strip out any
901 * flags not specified by the Java programming language.
902 */
903static uint32_t MangleAccessFlags(uint32_t accessFlags) {
904 accessFlags &= kAccJavaFlagsMask;
905 if ((accessFlags & kAccSynthetic) != 0) {
906 accessFlags |= 0xf0000000;
907 }
908 return accessFlags;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700909}
910
Elliott Hughesdbb40792011-11-18 17:05:22 -0800911static const uint16_t kEclipseWorkaroundSlot = 1000;
912
913/*
914 * Eclipse appears to expect that the "this" reference is in slot zero.
915 * If it's not, the "variables" display will show two copies of "this",
916 * possibly because it gets "this" from SF.ThisObject and then displays
917 * all locals with nonzero slot numbers.
918 *
919 * So, we remap the item in slot 0 to 1000, and remap "this" to zero. On
920 * SF.GetValues / SF.SetValues we map them back.
Elliott Hughesc5b734a2011-12-01 17:20:58 -0800921 *
922 * TODO: jdb uses the value to determine whether a variable is a local or an argument,
923 * by checking whether it's less than the number of arguments. To make that work, we'd
924 * have to "mangle" all the arguments to come first, not just the implicit argument 'this'.
Elliott Hughesdbb40792011-11-18 17:05:22 -0800925 */
926static uint16_t MangleSlot(uint16_t slot, const char* name) {
927 uint16_t newSlot = slot;
928 if (strcmp(name, "this") == 0) {
929 newSlot = 0;
930 } else if (slot == 0) {
931 newSlot = kEclipseWorkaroundSlot;
932 }
933 return newSlot;
934}
935
Elliott Hughes91bf6cd2012-02-14 17:27:48 -0800936static uint16_t DemangleSlot(uint16_t slot, Method* m) {
Elliott Hughesdbb40792011-11-18 17:05:22 -0800937 if (slot == kEclipseWorkaroundSlot) {
Elliott Hughes68fdbd02011-11-29 19:22:47 -0800938 return 0;
Elliott Hughesdbb40792011-11-18 17:05:22 -0800939 } else if (slot == 0) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -0800940 const DexFile::CodeItem* code_item = MethodHelper(m).GetCodeItem();
941 CHECK(code_item != NULL);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800942 return code_item->registers_size_ - code_item->ins_size_;
Elliott Hughesdbb40792011-11-18 17:05:22 -0800943 }
Elliott Hughes68fdbd02011-11-29 19:22:47 -0800944 return slot;
Elliott Hughesdbb40792011-11-18 17:05:22 -0800945}
946
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800947bool Dbg::OutputDeclaredFields(JDWP::RefTypeId refTypeId, bool with_generic, JDWP::ExpandBuf* pReply) {
948 Object* o = gRegistry->Get<Object*>(refTypeId);
949 if (o == NULL || !o->IsClass()) {
950 return false;
951 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800952
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800953 Class* c = o->AsClass();
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800954 size_t instance_field_count = c->NumInstanceFields();
955 size_t static_field_count = c->NumStaticFields();
956
957 expandBufAdd4BE(pReply, instance_field_count + static_field_count);
958
959 for (size_t i = 0; i < instance_field_count + static_field_count; ++i) {
960 Field* f = (i < instance_field_count) ? c->GetInstanceField(i) : c->GetStaticField(i - instance_field_count);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800961 FieldHelper fh(f);
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800962 expandBufAddFieldId(pReply, ToFieldId(f));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800963 expandBufAddUtf8String(pReply, fh.GetName());
964 expandBufAddUtf8String(pReply, fh.GetTypeDescriptor());
Elliott Hughesc5b734a2011-12-01 17:20:58 -0800965 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800966 static const char genericSignature[1] = "";
967 expandBufAddUtf8String(pReply, genericSignature);
968 }
969 expandBufAdd4BE(pReply, MangleAccessFlags(f->GetAccessFlags()));
970 }
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800971 return true;
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800972}
973
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800974bool Dbg::OutputDeclaredMethods(JDWP::RefTypeId refTypeId, bool with_generic, JDWP::ExpandBuf* pReply) {
975 Object* o = gRegistry->Get<Object*>(refTypeId);
976 if (o == NULL || !o->IsClass()) {
977 return false;
978 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800979
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800980 Class* c = o->AsClass();
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800981 size_t direct_method_count = c->NumDirectMethods();
982 size_t virtual_method_count = c->NumVirtualMethods();
983
984 expandBufAdd4BE(pReply, direct_method_count + virtual_method_count);
985
986 for (size_t i = 0; i < direct_method_count + virtual_method_count; ++i) {
987 Method* m = (i < direct_method_count) ? c->GetDirectMethod(i) : c->GetVirtualMethod(i - direct_method_count);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800988 MethodHelper mh(m);
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800989 expandBufAddMethodId(pReply, ToMethodId(m));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800990 expandBufAddUtf8String(pReply, mh.GetName());
Elliott Hughes4740cdf2011-12-07 14:07:12 -0800991 expandBufAddUtf8String(pReply, mh.GetSignature());
Elliott Hughesc5b734a2011-12-01 17:20:58 -0800992 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800993 static const char genericSignature[1] = "";
994 expandBufAddUtf8String(pReply, genericSignature);
995 }
996 expandBufAdd4BE(pReply, MangleAccessFlags(m->GetAccessFlags()));
997 }
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800998 return true;
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800999}
1000
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001001bool Dbg::OutputDeclaredInterfaces(JDWP::RefTypeId refTypeId, JDWP::ExpandBuf* pReply) {
1002 Object* o = gRegistry->Get<Object*>(refTypeId);
1003 if (o == NULL || !o->IsClass()) {
1004 return false;
1005 }
1006 ClassHelper kh(o->AsClass());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001007 size_t interface_count = kh.NumInterfaces();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001008 expandBufAdd4BE(pReply, interface_count);
1009 for (size_t i = 0; i < interface_count; ++i) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001010 expandBufAddRefTypeId(pReply, gRegistry->Add(kh.GetInterface(i)));
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001011 }
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001012 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001013}
1014
1015void Dbg::OutputLineTable(JDWP::RefTypeId refTypeId, JDWP::MethodId methodId, JDWP::ExpandBuf* pReply) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001016 struct DebugCallbackContext {
1017 int numItems;
1018 JDWP::ExpandBuf* pReply;
1019
1020 static bool Callback(void* context, uint32_t address, uint32_t lineNum) {
1021 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
1022 expandBufAdd8BE(pContext->pReply, address);
1023 expandBufAdd4BE(pContext->pReply, lineNum);
1024 pContext->numItems++;
1025 return true;
1026 }
1027 };
1028
1029 Method* m = FromMethodId(methodId);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001030 MethodHelper mh(m);
Elliott Hughes03181a82011-11-17 17:22:21 -08001031 uint64_t start, end;
1032 if (m->IsNative()) {
1033 start = -1;
1034 end = -1;
1035 } else {
1036 start = 0;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001037 // TODO: what are the units supposed to be? *2?
1038 end = mh.GetCodeItem()->insns_size_in_code_units_;
Elliott Hughes03181a82011-11-17 17:22:21 -08001039 }
1040
1041 expandBufAdd8BE(pReply, start);
1042 expandBufAdd8BE(pReply, end);
1043
1044 // Add numLines later
1045 size_t numLinesOffset = expandBufGetLength(pReply);
1046 expandBufAdd4BE(pReply, 0);
1047
1048 DebugCallbackContext context;
1049 context.numItems = 0;
1050 context.pReply = pReply;
1051
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001052 mh.GetDexFile().DecodeDebugInfo(mh.GetCodeItem(), m->IsStatic(), m->GetDexMethodIndex(),
1053 DebugCallbackContext::Callback, NULL, &context);
Elliott Hughes03181a82011-11-17 17:22:21 -08001054
1055 JDWP::Set4BE(expandBufGetBuffer(pReply) + numLinesOffset, context.numItems);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001056}
1057
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001058void Dbg::OutputVariableTable(JDWP::RefTypeId refTypeId, JDWP::MethodId methodId, bool with_generic, JDWP::ExpandBuf* pReply) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001059 struct DebugCallbackContext {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001060 JDWP::ExpandBuf* pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001061 size_t variable_count;
1062 bool with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001063
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001064 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 -08001065 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
1066
Elliott Hughesaa6e1cd2012-01-18 19:26:06 -08001067 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 -08001068
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001069 slot = MangleSlot(slot, name);
1070
Elliott Hughesdbb40792011-11-18 17:05:22 -08001071 expandBufAdd8BE(pContext->pReply, startAddress);
1072 expandBufAddUtf8String(pContext->pReply, name);
1073 expandBufAddUtf8String(pContext->pReply, descriptor);
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001074 if (pContext->with_generic) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001075 expandBufAddUtf8String(pContext->pReply, signature);
1076 }
1077 expandBufAdd4BE(pContext->pReply, endAddress - startAddress);
1078 expandBufAdd4BE(pContext->pReply, slot);
1079
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001080 ++pContext->variable_count;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001081 }
1082 };
1083
1084 Method* m = FromMethodId(methodId);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001085 MethodHelper mh(m);
1086 const DexFile::CodeItem* code_item = mh.GetCodeItem();
Elliott Hughesdbb40792011-11-18 17:05:22 -08001087
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001088 // arg_count considers doubles and longs to take 2 units.
1089 // variable_count considers everything to take 1 unit.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001090 std::string shorty(mh.GetShorty());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001091 expandBufAdd4BE(pReply, m->NumArgRegisters(shorty));
Elliott Hughesdbb40792011-11-18 17:05:22 -08001092
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001093 // We don't know the total number of variables yet, so leave a blank and update it later.
1094 size_t variable_count_offset = expandBufGetLength(pReply);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001095 expandBufAdd4BE(pReply, 0);
1096
1097 DebugCallbackContext context;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001098 context.pReply = pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001099 context.variable_count = 0;
1100 context.with_generic = with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001101
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001102 mh.GetDexFile().DecodeDebugInfo(code_item, m->IsStatic(), m->GetDexMethodIndex(), NULL,
1103 DebugCallbackContext::Callback, &context);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001104
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001105 JDWP::Set4BE(expandBufGetBuffer(pReply) + variable_count_offset, context.variable_count);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001106}
1107
Elliott Hughesaed4be92011-12-02 16:16:23 -08001108JDWP::JdwpTag Dbg::GetFieldBasicTag(JDWP::FieldId fieldId) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001109 return BasicTagFromDescriptor(FieldHelper(FromFieldId(fieldId)).GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001110}
1111
Elliott Hughesaed4be92011-12-02 16:16:23 -08001112JDWP::JdwpTag Dbg::GetStaticFieldBasicTag(JDWP::FieldId fieldId) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001113 return BasicTagFromDescriptor(FieldHelper(FromFieldId(fieldId)).GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001114}
1115
1116void Dbg::GetFieldValue(JDWP::ObjectId objectId, JDWP::FieldId fieldId, JDWP::ExpandBuf* pReply) {
Elliott Hughesaed4be92011-12-02 16:16:23 -08001117 Object* o = gRegistry->Get<Object*>(objectId);
1118 Field* f = FromFieldId(fieldId);
1119
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001120 JDWP::JdwpTag tag = BasicTagFromDescriptor(FieldHelper(f).GetTypeDescriptor());
Elliott Hughesaed4be92011-12-02 16:16:23 -08001121
1122 if (IsPrimitiveTag(tag)) {
1123 expandBufAdd1(pReply, tag);
1124 if (tag == JDWP::JT_BOOLEAN || tag == JDWP::JT_BYTE) {
1125 expandBufAdd1(pReply, f->Get32(o));
1126 } else if (tag == JDWP::JT_CHAR || tag == JDWP::JT_SHORT) {
1127 expandBufAdd2BE(pReply, f->Get32(o));
1128 } else if (tag == JDWP::JT_FLOAT || tag == JDWP::JT_INT) {
1129 expandBufAdd4BE(pReply, f->Get32(o));
1130 } else if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
1131 expandBufAdd8BE(pReply, f->Get64(o));
1132 } else {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001133 LOG(FATAL) << "Unknown tag: " << tag;
Elliott Hughesaed4be92011-12-02 16:16:23 -08001134 }
1135 } else {
1136 Object* value = f->GetObject(o);
1137 expandBufAdd1(pReply, TagFromObject(value));
1138 expandBufAddObjectId(pReply, gRegistry->Add(value));
1139 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001140}
1141
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001142JDWP::JdwpError Dbg::SetFieldValue(JDWP::ObjectId objectId, JDWP::FieldId fieldId, uint64_t value, int width) {
Elliott Hughesaed4be92011-12-02 16:16:23 -08001143 Object* o = gRegistry->Get<Object*>(objectId);
1144 Field* f = FromFieldId(fieldId);
1145
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001146 JDWP::JdwpTag tag = BasicTagFromDescriptor(FieldHelper(f).GetTypeDescriptor());
Elliott Hughesaed4be92011-12-02 16:16:23 -08001147
1148 if (IsPrimitiveTag(tag)) {
1149 if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
1150 f->Set64(o, value);
1151 } else {
1152 f->Set32(o, value);
1153 }
1154 } else {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001155 Object* v = gRegistry->Get<Object*>(value);
1156 Class* field_type = FieldHelper(f).GetType();
1157 if (!field_type->IsAssignableFrom(v->GetClass())) {
1158 return JDWP::ERR_INVALID_OBJECT;
1159 }
1160 f->SetObject(o, v);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001161 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001162
1163 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001164}
1165
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001166void Dbg::GetStaticFieldValue(JDWP::FieldId fieldId, JDWP::ExpandBuf* pReply) {
1167 GetFieldValue(0, fieldId, pReply);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001168}
1169
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001170JDWP::JdwpError Dbg::SetStaticFieldValue(JDWP::FieldId fieldId, uint64_t value, int width) {
1171 return SetFieldValue(0, fieldId, value, width);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001172}
1173
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001174std::string Dbg::StringToUtf8(JDWP::ObjectId strId) {
1175 String* s = gRegistry->Get<String*>(strId);
1176 return s->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001177}
1178
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001179bool Dbg::GetThreadName(JDWP::ObjectId threadId, std::string& name) {
1180 ScopedThreadListLock thread_list_lock;
1181 Thread* thread = DecodeThread(threadId);
1182 if (thread == NULL) {
1183 return false;
1184 }
Elliott Hughes899e7892012-01-24 14:57:32 -08001185 StringAppendF(&name, "<%d> %s", thread->GetThinLockId(), thread->GetThreadName()->ToModifiedUtf8().c_str());
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001186 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001187}
1188
1189JDWP::ObjectId Dbg::GetThreadGroup(JDWP::ObjectId threadId) {
Elliott Hughes499c5132011-11-17 14:55:11 -08001190 Object* thread = gRegistry->Get<Object*>(threadId);
1191 CHECK(thread != NULL);
1192
1193 Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/Thread;");
1194 CHECK(c != NULL);
1195 Field* f = c->FindInstanceField("group", "Ljava/lang/ThreadGroup;");
1196 CHECK(f != NULL);
1197 Object* group = f->GetObject(thread);
1198 CHECK(group != NULL);
1199 return gRegistry->Add(group);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001200}
1201
Elliott Hughes499c5132011-11-17 14:55:11 -08001202std::string Dbg::GetThreadGroupName(JDWP::ObjectId threadGroupId) {
1203 Object* thread_group = gRegistry->Get<Object*>(threadGroupId);
1204 CHECK(thread_group != NULL);
1205
1206 Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/ThreadGroup;");
1207 CHECK(c != NULL);
1208 Field* f = c->FindInstanceField("name", "Ljava/lang/String;");
1209 CHECK(f != NULL);
1210 String* s = reinterpret_cast<String*>(f->GetObject(thread_group));
1211 return s->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001212}
1213
1214JDWP::ObjectId Dbg::GetThreadGroupParent(JDWP::ObjectId threadGroupId) {
Elliott Hughes4e235312011-12-02 11:34:15 -08001215 Object* thread_group = gRegistry->Get<Object*>(threadGroupId);
1216 CHECK(thread_group != NULL);
1217
1218 Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/ThreadGroup;");
1219 CHECK(c != NULL);
1220 Field* f = c->FindInstanceField("parent", "Ljava/lang/ThreadGroup;");
1221 CHECK(f != NULL);
1222 Object* parent = f->GetObject(thread_group);
1223 return gRegistry->Add(parent);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001224}
1225
Elliott Hughes499c5132011-11-17 14:55:11 -08001226static Object* GetStaticThreadGroup(const char* field_name) {
1227 Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/ThreadGroup;");
1228 CHECK(c != NULL);
1229 Field* f = c->FindStaticField(field_name, "Ljava/lang/ThreadGroup;");
1230 CHECK(f != NULL);
1231 Object* group = f->GetObject(NULL);
1232 CHECK(group != NULL);
1233 return group;
1234}
1235
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001236JDWP::ObjectId Dbg::GetSystemThreadGroupId() {
Elliott Hughes499c5132011-11-17 14:55:11 -08001237 return gRegistry->Add(GetStaticThreadGroup("mSystem"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001238}
1239
1240JDWP::ObjectId Dbg::GetMainThreadGroupId() {
Elliott Hughes499c5132011-11-17 14:55:11 -08001241 return gRegistry->Add(GetStaticThreadGroup("mMain"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001242}
1243
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001244bool Dbg::GetThreadStatus(JDWP::ObjectId threadId, JDWP::JdwpThreadStatus* pThreadStatus, JDWP::JdwpSuspendStatus* pSuspendStatus) {
Elliott Hughes499c5132011-11-17 14:55:11 -08001245 ScopedThreadListLock thread_list_lock;
1246
1247 Thread* thread = DecodeThread(threadId);
1248 if (thread == NULL) {
1249 return false;
1250 }
1251
1252 switch (thread->GetState()) {
1253 case Thread::kTerminated: *pThreadStatus = JDWP::TS_ZOMBIE; break;
1254 case Thread::kRunnable: *pThreadStatus = JDWP::TS_RUNNING; break;
1255 case Thread::kTimedWaiting: *pThreadStatus = JDWP::TS_SLEEPING; break;
1256 case Thread::kBlocked: *pThreadStatus = JDWP::TS_MONITOR; break;
1257 case Thread::kWaiting: *pThreadStatus = JDWP::TS_WAIT; break;
1258 case Thread::kInitializing: *pThreadStatus = JDWP::TS_ZOMBIE; break;
1259 case Thread::kStarting: *pThreadStatus = JDWP::TS_ZOMBIE; break;
1260 case Thread::kNative: *pThreadStatus = JDWP::TS_RUNNING; break;
1261 case Thread::kVmWait: *pThreadStatus = JDWP::TS_WAIT; break;
1262 case Thread::kSuspended: *pThreadStatus = JDWP::TS_RUNNING; break;
1263 default:
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001264 LOG(FATAL) << "Unknown thread state " << thread->GetState();
Elliott Hughes499c5132011-11-17 14:55:11 -08001265 }
1266
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001267 *pSuspendStatus = (thread->IsSuspended() ? JDWP::SUSPEND_STATUS_SUSPENDED : JDWP::SUSPEND_STATUS_NOT_SUSPENDED);
Elliott Hughes499c5132011-11-17 14:55:11 -08001268
1269 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001270}
1271
1272uint32_t Dbg::GetThreadSuspendCount(JDWP::ObjectId threadId) {
Elliott Hughesd07986f2011-12-06 18:27:45 -08001273 return DecodeThread(threadId)->GetSuspendCount();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001274}
1275
1276bool Dbg::ThreadExists(JDWP::ObjectId threadId) {
Elliott Hughes761928d2011-11-16 18:33:03 -08001277 return DecodeThread(threadId) != NULL;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001278}
1279
1280bool Dbg::IsSuspended(JDWP::ObjectId threadId) {
Elliott Hughes761928d2011-11-16 18:33:03 -08001281 return DecodeThread(threadId)->IsSuspended();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001282}
1283
Elliott Hughesa2155262011-11-16 16:26:58 -08001284void Dbg::GetThreadGroupThreadsImpl(Object* thread_group, JDWP::ObjectId** ppThreadIds, uint32_t* pThreadCount) {
1285 struct ThreadListVisitor {
1286 static void Visit(Thread* t, void* arg) {
1287 reinterpret_cast<ThreadListVisitor*>(arg)->Visit(t);
1288 }
1289
1290 void Visit(Thread* t) {
1291 if (t == Dbg::GetDebugThread()) {
1292 // Skip the JDWP thread. Some debuggers get bent out of shape when they can't suspend and
1293 // query all threads, so it's easier if we just don't tell them about this thread.
1294 return;
1295 }
1296 if (thread_group == NULL || t->GetThreadGroup() == thread_group) {
1297 threads.push_back(gRegistry->Add(t->GetPeer()));
1298 }
1299 }
1300
1301 Object* thread_group;
1302 std::vector<JDWP::ObjectId> threads;
1303 };
1304
1305 ThreadListVisitor tlv;
1306 tlv.thread_group = thread_group;
1307
1308 {
1309 ScopedThreadListLock thread_list_lock;
1310 Runtime::Current()->GetThreadList()->ForEach(ThreadListVisitor::Visit, &tlv);
1311 }
1312
1313 *pThreadCount = tlv.threads.size();
1314 if (*pThreadCount == 0) {
1315 *ppThreadIds = NULL;
1316 } else {
1317 *ppThreadIds = new JDWP::ObjectId[*pThreadCount];
1318 for (size_t i = 0; i < *pThreadCount; ++i) {
1319 (*ppThreadIds)[i] = tlv.threads[i];
1320 }
1321 }
1322}
1323
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001324void Dbg::GetThreadGroupThreads(JDWP::ObjectId threadGroupId, JDWP::ObjectId** ppThreadIds, uint32_t* pThreadCount) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001325 GetThreadGroupThreadsImpl(gRegistry->Get<Object*>(threadGroupId), ppThreadIds, pThreadCount);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001326}
1327
1328void Dbg::GetAllThreads(JDWP::ObjectId** ppThreadIds, uint32_t* pThreadCount) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001329 GetThreadGroupThreadsImpl(NULL, ppThreadIds, pThreadCount);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001330}
1331
Elliott Hughes86964332012-02-15 19:37:42 -08001332static int GetStackDepth(Thread* thread) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001333 struct CountStackDepthVisitor : public Thread::StackVisitor {
1334 CountStackDepthVisitor() : depth(0) {}
Elliott Hughesf8a2df72011-12-01 12:19:54 -08001335 virtual void VisitFrame(const Frame& f, uintptr_t) {
1336 // TODO: we'll need to skip callee-save frames too.
1337 if (f.HasMethod()) {
1338 ++depth;
1339 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001340 }
1341 size_t depth;
1342 };
1343 CountStackDepthVisitor visitor;
Elliott Hughes86964332012-02-15 19:37:42 -08001344 thread->WalkStack(&visitor);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001345 return visitor.depth;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001346}
1347
Elliott Hughes86964332012-02-15 19:37:42 -08001348int Dbg::GetThreadFrameCount(JDWP::ObjectId threadId) {
1349 ScopedThreadListLock thread_list_lock;
1350 return GetStackDepth(DecodeThread(threadId));
1351}
1352
Elliott Hughes03181a82011-11-17 17:22:21 -08001353bool Dbg::GetThreadFrame(JDWP::ObjectId threadId, int desired_frame_number, JDWP::FrameId* pFrameId, JDWP::JdwpLocation* pLoc) {
1354 ScopedThreadListLock thread_list_lock;
1355 struct GetFrameVisitor : public Thread::StackVisitor {
1356 GetFrameVisitor(int desired_frame_number, JDWP::FrameId* pFrameId, JDWP::JdwpLocation* pLoc)
Elliott Hughesba8eee12012-01-24 20:25:24 -08001357 : found(false), depth(0), desired_frame_number(desired_frame_number), pFrameId(pFrameId), pLoc(pLoc) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001358 }
1359 virtual void VisitFrame(const Frame& f, uintptr_t pc) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -08001360 // TODO: we'll need to skip callee-save frames too.
Elliott Hughes03181a82011-11-17 17:22:21 -08001361 if (!f.HasMethod()) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -08001362 return; // The debugger can't do anything useful with a frame that has no Method*.
Elliott Hughes03181a82011-11-17 17:22:21 -08001363 }
1364
1365 if (depth == desired_frame_number) {
1366 *pFrameId = reinterpret_cast<JDWP::FrameId>(f.GetSP());
Elliott Hughesd07986f2011-12-06 18:27:45 -08001367 SetLocation(*pLoc, f.GetMethod(), pc);
Elliott Hughes03181a82011-11-17 17:22:21 -08001368 found = true;
1369 }
1370 ++depth;
1371 }
1372 bool found;
1373 int depth;
1374 int desired_frame_number;
1375 JDWP::FrameId* pFrameId;
1376 JDWP::JdwpLocation* pLoc;
1377 };
1378 GetFrameVisitor visitor(desired_frame_number, pFrameId, pLoc);
1379 visitor.desired_frame_number = desired_frame_number;
1380 DecodeThread(threadId)->WalkStack(&visitor);
1381 return visitor.found;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001382}
1383
1384JDWP::ObjectId Dbg::GetThreadSelfId() {
Elliott Hughes475fc232011-10-25 15:00:35 -07001385 return gRegistry->Add(Thread::Current()->GetPeer());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001386}
1387
Elliott Hughes475fc232011-10-25 15:00:35 -07001388void Dbg::SuspendVM() {
Elliott Hughesa2155262011-11-16 16:26:58 -08001389 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 -07001390 Runtime::Current()->GetThreadList()->SuspendAll(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001391}
1392
1393void Dbg::ResumeVM() {
Elliott Hughes475fc232011-10-25 15:00:35 -07001394 Runtime::Current()->GetThreadList()->ResumeAll(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001395}
1396
1397void Dbg::SuspendThread(JDWP::ObjectId threadId) {
Elliott Hughes4e235312011-12-02 11:34:15 -08001398 Object* peer = gRegistry->Get<Object*>(threadId);
1399 ScopedThreadListLock thread_list_lock;
1400 Thread* thread = Thread::FromManagedThread(peer);
1401 if (thread == NULL) {
1402 LOG(WARNING) << "No such thread for suspend: " << peer;
1403 return;
1404 }
1405 Runtime::Current()->GetThreadList()->Suspend(thread, true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001406}
1407
1408void Dbg::ResumeThread(JDWP::ObjectId threadId) {
Elliott Hughes4e235312011-12-02 11:34:15 -08001409 Object* peer = gRegistry->Get<Object*>(threadId);
1410 ScopedThreadListLock thread_list_lock;
1411 Thread* thread = Thread::FromManagedThread(peer);
1412 if (thread == NULL) {
1413 LOG(WARNING) << "No such thread for resume: " << peer;
1414 return;
1415 }
1416 Runtime::Current()->GetThreadList()->Resume(thread, true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001417}
1418
1419void Dbg::SuspendSelf() {
Elliott Hughes475fc232011-10-25 15:00:35 -07001420 Runtime::Current()->GetThreadList()->SuspendSelfForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001421}
1422
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001423static Object* GetThis(Frame& f) {
Elliott Hughes86b00102011-12-05 17:54:26 -08001424 Method* m = f.GetMethod();
Elliott Hughes86b00102011-12-05 17:54:26 -08001425 Object* o = NULL;
1426 if (!m->IsNative() && !m->IsStatic()) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001427 uint16_t reg = DemangleSlot(0, m);
Elliott Hughes86b00102011-12-05 17:54:26 -08001428 o = reinterpret_cast<Object*>(f.GetVReg(m, reg));
1429 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001430 return o;
1431}
1432
1433void Dbg::GetThisObject(JDWP::FrameId frameId, JDWP::ObjectId* pThisId) {
1434 Method** sp = reinterpret_cast<Method**>(frameId);
1435 Frame f(sp);
1436 Object* o = GetThis(f);
Elliott Hughes86b00102011-12-05 17:54:26 -08001437 *pThisId = gRegistry->Add(o);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001438}
1439
Elliott Hughescccd84f2011-12-05 16:51:54 -08001440void 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 -08001441 Method** sp = reinterpret_cast<Method**>(frameId);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001442 Frame f(sp);
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001443 Method* m = f.GetMethod();
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001444 uint16_t reg = DemangleSlot(slot, m);
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001445
1446 const VmapTable vmap_table(m->GetVmapTableRaw());
1447 uint32_t vmap_offset;
1448 if (vmap_table.IsInContext(reg, vmap_offset)) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001449 UNIMPLEMENTED(FATAL) << "Don't know how to pull locals from callee save frames: " << vmap_offset;
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001450 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001451
1452 switch (tag) {
1453 case JDWP::JT_BOOLEAN:
1454 {
Elliott Hughescccd84f2011-12-05 16:51:54 -08001455 CHECK_EQ(width, 1U);
Elliott Hughes1bba14f2011-12-01 18:00:36 -08001456 uint32_t intVal = f.GetVReg(m, reg);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001457 VLOG(jdwp) << "get boolean local " << reg << " = " << intVal;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001458 JDWP::Set1(buf+1, intVal != 0);
1459 }
1460 break;
1461 case JDWP::JT_BYTE:
1462 {
Elliott Hughescccd84f2011-12-05 16:51:54 -08001463 CHECK_EQ(width, 1U);
Elliott Hughes1bba14f2011-12-01 18:00:36 -08001464 uint32_t intVal = f.GetVReg(m, reg);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001465 VLOG(jdwp) << "get byte local " << reg << " = " << intVal;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001466 JDWP::Set1(buf+1, intVal);
1467 }
1468 break;
1469 case JDWP::JT_SHORT:
1470 case JDWP::JT_CHAR:
1471 {
Elliott Hughescccd84f2011-12-05 16:51:54 -08001472 CHECK_EQ(width, 2U);
Elliott Hughes1bba14f2011-12-01 18:00:36 -08001473 uint32_t intVal = f.GetVReg(m, reg);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001474 VLOG(jdwp) << "get short/char local " << reg << " = " << intVal;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001475 JDWP::Set2BE(buf+1, intVal);
1476 }
1477 break;
1478 case JDWP::JT_INT:
1479 case JDWP::JT_FLOAT:
1480 {
Elliott Hughescccd84f2011-12-05 16:51:54 -08001481 CHECK_EQ(width, 4U);
Elliott Hughes1bba14f2011-12-01 18:00:36 -08001482 uint32_t intVal = f.GetVReg(m, reg);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001483 VLOG(jdwp) << "get int/float local " << reg << " = " << intVal;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001484 JDWP::Set4BE(buf+1, intVal);
1485 }
1486 break;
1487 case JDWP::JT_ARRAY:
1488 {
Elliott Hughescccd84f2011-12-05 16:51:54 -08001489 CHECK_EQ(width, sizeof(JDWP::ObjectId));
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001490 Object* o = reinterpret_cast<Object*>(f.GetVReg(m, reg));
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001491 VLOG(jdwp) << "get array local " << reg << " = " << o;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001492 if (o != NULL && !Heap::IsHeapAddress(o)) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001493 LOG(FATAL) << "Register " << reg << " expected to hold array: " << o;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001494 }
1495 JDWP::SetObjectId(buf+1, gRegistry->Add(o));
1496 }
1497 break;
1498 case JDWP::JT_OBJECT:
1499 {
Elliott Hughescccd84f2011-12-05 16:51:54 -08001500 CHECK_EQ(width, sizeof(JDWP::ObjectId));
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001501 Object* o = reinterpret_cast<Object*>(f.GetVReg(m, reg));
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001502 VLOG(jdwp) << "get object local " << reg << " = " << o;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001503 if (o != NULL && !Heap::IsHeapAddress(o)) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001504 LOG(FATAL) << "Register " << reg << " expected to hold object: " << o;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001505 }
1506 tag = TagFromObject(o);
1507 JDWP::SetObjectId(buf+1, gRegistry->Add(o));
1508 }
1509 break;
1510 case JDWP::JT_DOUBLE:
1511 case JDWP::JT_LONG:
1512 {
Elliott Hughescccd84f2011-12-05 16:51:54 -08001513 CHECK_EQ(width, 8U);
Elliott Hughes1bba14f2011-12-01 18:00:36 -08001514 uint32_t lo = f.GetVReg(m, reg);
1515 uint64_t hi = f.GetVReg(m, reg + 1);
1516 uint64_t longVal = (hi << 32) | lo;
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001517 VLOG(jdwp) << "get double/long local " << hi << ":" << lo << " = " << longVal;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001518 JDWP::Set8BE(buf+1, longVal);
1519 }
1520 break;
1521 default:
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001522 LOG(FATAL) << "Unknown tag " << tag;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001523 break;
1524 }
1525
1526 // Prepend tag, which may have been updated.
1527 JDWP::Set1(buf, tag);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001528}
1529
Elliott Hughesdbb40792011-11-18 17:05:22 -08001530void 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 -08001531 Method** sp = reinterpret_cast<Method**>(frameId);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001532 Frame f(sp);
Elliott Hughescccd84f2011-12-05 16:51:54 -08001533 Method* m = f.GetMethod();
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001534 uint16_t reg = DemangleSlot(slot, m);
Elliott Hughescccd84f2011-12-05 16:51:54 -08001535
1536 const VmapTable vmap_table(m->GetVmapTableRaw());
1537 uint32_t vmap_offset;
1538 if (vmap_table.IsInContext(reg, vmap_offset)) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001539 UNIMPLEMENTED(FATAL) << "Don't know how to pull locals from callee save frames: " << vmap_offset;
Elliott Hughescccd84f2011-12-05 16:51:54 -08001540 }
1541
1542 switch (tag) {
1543 case JDWP::JT_BOOLEAN:
1544 case JDWP::JT_BYTE:
1545 CHECK_EQ(width, 1U);
1546 f.SetVReg(m, reg, static_cast<uint32_t>(value));
1547 break;
1548 case JDWP::JT_SHORT:
1549 case JDWP::JT_CHAR:
1550 CHECK_EQ(width, 2U);
1551 f.SetVReg(m, reg, static_cast<uint32_t>(value));
1552 break;
1553 case JDWP::JT_INT:
1554 case JDWP::JT_FLOAT:
1555 CHECK_EQ(width, 4U);
1556 f.SetVReg(m, reg, static_cast<uint32_t>(value));
1557 break;
1558 case JDWP::JT_ARRAY:
1559 case JDWP::JT_OBJECT:
1560 case JDWP::JT_STRING:
1561 {
1562 CHECK_EQ(width, sizeof(JDWP::ObjectId));
1563 Object* o = gRegistry->Get<Object*>(static_cast<JDWP::ObjectId>(value));
1564 f.SetVReg(m, reg, static_cast<uint32_t>(reinterpret_cast<uintptr_t>(o)));
1565 }
1566 break;
1567 case JDWP::JT_DOUBLE:
1568 case JDWP::JT_LONG:
1569 CHECK_EQ(width, 8U);
1570 f.SetVReg(m, reg, static_cast<uint32_t>(value));
1571 f.SetVReg(m, reg + 1, static_cast<uint32_t>(value >> 32));
1572 break;
1573 default:
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001574 LOG(FATAL) << "Unknown tag " << tag;
Elliott Hughescccd84f2011-12-05 16:51:54 -08001575 break;
1576 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001577}
1578
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001579void Dbg::PostLocationEvent(const Method* m, int dex_pc, Object* this_object, int event_flags) {
1580 Class* c = m->GetDeclaringClass();
1581
1582 JDWP::JdwpLocation location;
1583 location.typeTag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
1584 location.classId = gRegistry->Add(c);
1585 location.methodId = ToMethodId(m);
1586 location.idx = m->IsNative() ? -1 : dex_pc;
1587
1588 // Note we use "NoReg" so we don't keep track of references that are
1589 // never actually sent to the debugger. 'this_id' is only used to
1590 // compare against registered events...
1591 JDWP::ObjectId this_id = static_cast<JDWP::ObjectId>(reinterpret_cast<uintptr_t>(this_object));
1592 if (gJdwpState->PostLocationEvent(&location, this_id, event_flags)) {
1593 // ...unless there's a registered event, in which case we
1594 // need to really track the class and 'this'.
1595 gRegistry->Add(c);
1596 gRegistry->Add(this_object);
1597 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001598}
1599
Elliott Hughesd07986f2011-12-06 18:27:45 -08001600void Dbg::PostException(Method** sp, Method* throwMethod, uintptr_t throwNativePc, Method* catchMethod, uintptr_t catchNativePc, Object* exception) {
Ian Rogers0ad5bb82011-12-07 10:16:32 -08001601 if (!gDebuggerActive) {
1602 return;
1603 }
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001604
Elliott Hughesd07986f2011-12-06 18:27:45 -08001605 JDWP::JdwpLocation throw_location;
1606 SetLocation(throw_location, throwMethod, throwNativePc);
1607 JDWP::JdwpLocation catch_location;
1608 SetLocation(catch_location, catchMethod, catchNativePc);
1609
1610 // We need 'this' for InstanceOnly filters.
1611 JDWP::ObjectId this_id;
1612 GetThisObject(reinterpret_cast<JDWP::FrameId>(sp), &this_id);
1613
1614 /*
1615 * Hand the event to the JDWP exception handler. Note we're using the
1616 * "NoReg" objectID on the exception, which is not strictly correct --
1617 * the exception object WILL be passed up to the debugger if the
1618 * debugger is interested in the event. We do this because the current
1619 * implementation of the debugger object registry never throws anything
1620 * away, and some people were experiencing a fatal build up of exception
1621 * objects when dealing with certain libraries.
1622 */
1623 JDWP::ObjectId exception_id = static_cast<JDWP::ObjectId>(reinterpret_cast<uintptr_t>(exception));
1624 JDWP::RefTypeId exception_class_id = gRegistry->Add(exception->GetClass());
1625
1626 gJdwpState->PostException(&throw_location, exception_id, exception_class_id, &catch_location, this_id);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001627}
1628
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001629void Dbg::PostClassPrepare(Class* c) {
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001630 if (!gDebuggerActive) {
1631 return;
1632 }
1633
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001634 // OLD-TODO - we currently always send both "verified" and "prepared" since
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001635 // debuggers seem to like that. There might be some advantage to honesty,
1636 // since the class may not yet be verified.
1637 int state = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
1638 JDWP::JdwpTypeTag tag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
1639 gJdwpState->PostClassPrepare(tag, gRegistry->Add(c), ClassHelper(c).GetDescriptor(), state);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001640}
1641
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001642void Dbg::UpdateDebugger(int32_t dex_pc, Thread* self, Method** sp) {
1643 if (!gDebuggerActive) {
1644 return;
1645 }
1646
Elliott Hughes86964332012-02-15 19:37:42 -08001647 Frame f(sp);
1648 f.Next(); // Skip callee save frame.
1649 Method* m = f.GetMethod();
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001650 int event_flags = 0;
1651
1652 // Update xtra.currentPc on every instruction. We need to do this if
1653 // there's a chance that we could get suspended. This can happen if
1654 // event_flags != 0 here, or somebody manually requests a suspend
1655 // (which gets handled at PERIOD_CHECKS time). One place where this
1656 // needs to be correct is in dvmAddSingleStep().
1657 //dvmExportPC(pc, fp);
1658
1659 // We use a pc of -1 to represent method entry, since we might branch back to pc 0 later.
1660 if (dex_pc == -1) {
1661 event_flags |= kMethodEntry;
1662 }
1663
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001664 // See if we have a breakpoint here.
1665 // Depending on the "mods" associated with event(s) on this address,
1666 // we may or may not actually send a message to the debugger.
Elliott Hughes86964332012-02-15 19:37:42 -08001667 if (IsBreakpoint(m, dex_pc)) {
1668 event_flags |= kBreakpoint;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001669 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001670
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001671 // If the debugger is single-stepping one of our threads, check to
1672 // see if we're that thread and we've reached a step point.
Elliott Hughes86964332012-02-15 19:37:42 -08001673 if (gSingleStepControl.is_active && gSingleStepControl.thread == self) {
1674 CHECK(!m->IsNative());
1675 if (gSingleStepControl.step_depth == JDWP::SD_INTO) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001676 // Step into method calls. We break when the line number
1677 // or method pointer changes. If we're in SS_MIN mode, we
1678 // always stop.
Elliott Hughes86964332012-02-15 19:37:42 -08001679 if (gSingleStepControl.method != m) {
1680 event_flags |= kSingleStep;
1681 VLOG(jdwp) << "SS new method";
1682 } else if (gSingleStepControl.step_size == JDWP::SS_MIN) {
1683 event_flags |= kSingleStep;
1684 VLOG(jdwp) << "SS new instruction";
1685// } else if (!dvmAddressSetGet(gSingleStepControl.pAddressSet, pc - method->insns)) {
1686// event_flags |= kSingleStep;
1687// VLOG(jdwp) << "SS new line";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001688 }
Elliott Hughes86964332012-02-15 19:37:42 -08001689 } else if (gSingleStepControl.step_depth == JDWP::SD_OVER) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001690 // Step over method calls. We break when the line number is
1691 // different and the frame depth is <= the original frame
1692 // depth. (We can't just compare on the method, because we
1693 // might get unrolled past it by an exception, and it's tricky
1694 // to identify recursion.)
Elliott Hughes86964332012-02-15 19:37:42 -08001695
1696 // TODO: can we just use the value of 'sp'?
1697 int stack_depth = GetStackDepth(self);
1698
1699 if (stack_depth < gSingleStepControl.stack_depth) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001700 // popped up one or more frames, always trigger
Elliott Hughes86964332012-02-15 19:37:42 -08001701 event_flags |= kSingleStep;
1702 VLOG(jdwp) << "SS method pop";
1703 } else if (stack_depth == gSingleStepControl.stack_depth) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001704 // same depth, see if we moved
Elliott Hughes86964332012-02-15 19:37:42 -08001705 if (gSingleStepControl.step_size == JDWP::SS_MIN) {
1706 event_flags |= kSingleStep;
1707 VLOG(jdwp) << "SS new instruction";
1708// } else if (!dvmAddressSetGet(gSingleStepControl.pAddressSet, pc - method->insns)) {
1709// event_flags |= kSingleStep;
1710// VLOG(jdwp) << "SS new line";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001711 }
1712 }
1713 } else {
Elliott Hughes86964332012-02-15 19:37:42 -08001714 CHECK_EQ(gSingleStepControl.step_depth, JDWP::SD_OUT);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001715 // Return from the current method. We break when the frame
1716 // depth pops up.
1717
1718 // This differs from the "method exit" break in that it stops
1719 // with the PC at the next instruction in the returned-to
1720 // function, rather than the end of the returning function.
Elliott Hughes86964332012-02-15 19:37:42 -08001721
1722 // TODO: can we just use the value of 'sp'?
1723 int stack_depth = GetStackDepth(self);
1724 if (stack_depth < gSingleStepControl.stack_depth) {
1725 event_flags |= kSingleStep;
1726 VLOG(jdwp) << "SS method pop";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001727 }
1728 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001729 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001730
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001731 // Check to see if this is a "return" instruction. JDWP says we should
1732 // send the event *after* the code has been executed, but it also says
1733 // the location we provide is the last instruction. Since the "return"
1734 // instruction has no interesting side effects, we should be safe.
1735 // (We can't just move this down to the returnFromMethod label because
1736 // we potentially need to combine it with other events.)
1737 // We're also not supposed to generate a method exit event if the method
1738 // terminates "with a thrown exception".
Elliott Hughes86964332012-02-15 19:37:42 -08001739 if (dex_pc >= 0) {
1740 const DexFile::CodeItem* code_item = MethodHelper(m).GetCodeItem();
1741 CHECK(code_item != NULL);
1742 CHECK_LT(dex_pc, static_cast<int32_t>(code_item->insns_size_in_code_units_));
1743 if (Instruction::At(&code_item->insns_[dex_pc])->IsReturn()) {
1744 event_flags |= kMethodExit;
1745 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001746 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001747
1748 // If there's something interesting going on, see if it matches one
1749 // of the debugger filters.
1750 if (event_flags != 0) {
Elliott Hughes86964332012-02-15 19:37:42 -08001751 Dbg::PostLocationEvent(m, dex_pc, GetThis(f), event_flags);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001752 }
1753}
1754
Elliott Hughes86964332012-02-15 19:37:42 -08001755void Dbg::WatchLocation(const JDWP::JdwpLocation* location) {
1756 MutexLock mu(gBreakpointsLock);
1757 Method* m = FromMethodId(location->methodId);
1758 gBreakpoints.push_back(Breakpoint(m, location->idx));
1759 VLOG(jdwp) << "Set breakpoint #" << (gBreakpoints.size() - 1) << ": " << gBreakpoints[gBreakpoints.size() - 1];
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001760}
1761
Elliott Hughes86964332012-02-15 19:37:42 -08001762void Dbg::UnwatchLocation(const JDWP::JdwpLocation* location) {
1763 MutexLock mu(gBreakpointsLock);
1764 Method* m = FromMethodId(location->methodId);
1765 for (size_t i = 0; i < gBreakpoints.size(); ++i) {
1766 if (gBreakpoints[i].method == m && gBreakpoints[i].pc == location->idx) {
1767 VLOG(jdwp) << "Removed breakpoint #" << i << ": " << gBreakpoints[i];
1768 gBreakpoints.erase(gBreakpoints.begin() + i);
1769 return;
1770 }
1771 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001772}
1773
Elliott Hughes86964332012-02-15 19:37:42 -08001774bool Dbg::ConfigureStep(JDWP::ObjectId threadId, JDWP::JdwpStepSize step_size, JDWP::JdwpStepDepth step_depth) {
1775 Thread* thread = DecodeThread(threadId);
1776
1777 // TODO: there's no theoretical reason why we couldn't support single-stepping
1778 // of multiple threads at once, but we never did so historically.
1779 if (gSingleStepControl.thread != NULL && thread != gSingleStepControl.thread) {
1780 LOG(WARNING) << "single-step already active for " << *gSingleStepControl.thread
1781 << "; switching to " << *thread;
1782 }
1783
1784 struct SingleStepStackVisitor : public Thread::StackVisitor {
1785 SingleStepStackVisitor() {
1786 gSingleStepControl.method = NULL;
1787 gSingleStepControl.stack_depth = 0;
1788 }
1789 virtual void VisitFrame(const Frame& f, uintptr_t) {
1790 // TODO: we'll need to skip callee-save frames too.
1791 if (f.HasMethod()) {
1792 ++gSingleStepControl.stack_depth;
1793 if (gSingleStepControl.method == NULL) {
1794 gSingleStepControl.method = f.GetMethod();
1795 }
1796 }
1797 }
1798 };
1799 SingleStepStackVisitor visitor;
1800 thread->WalkStack(&visitor);
1801
1802 gSingleStepControl.thread = thread;
1803 gSingleStepControl.step_size = step_size;
1804 gSingleStepControl.step_depth = step_depth;
1805 gSingleStepControl.is_active = true;
1806
1807 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001808}
1809
1810void Dbg::UnconfigureStep(JDWP::ObjectId threadId) {
Elliott Hughes86964332012-02-15 19:37:42 -08001811 gSingleStepControl.is_active = false;
1812 gSingleStepControl.thread = NULL;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001813}
1814
Elliott Hughesd07986f2011-12-06 18:27:45 -08001815JDWP::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) {
1816 ThreadList* thread_list = Runtime::Current()->GetThreadList();
1817
1818 Thread* targetThread = NULL;
1819 DebugInvokeReq* req = NULL;
1820 {
1821 ScopedThreadListLock thread_list_lock;
1822 targetThread = DecodeThread(threadId);
1823 if (targetThread == NULL) {
1824 LOG(ERROR) << "InvokeMethod request for non-existent thread " << threadId;
1825 return JDWP::ERR_INVALID_THREAD;
1826 }
1827 req = targetThread->GetInvokeReq();
1828 if (!req->ready) {
1829 LOG(ERROR) << "InvokeMethod request for thread not stopped by event: " << *targetThread;
1830 return JDWP::ERR_INVALID_THREAD;
1831 }
1832
1833 /*
1834 * We currently have a bug where we don't successfully resume the
1835 * target thread if the suspend count is too deep. We're expected to
1836 * require one "resume" for each "suspend", but when asked to execute
1837 * a method we have to resume fully and then re-suspend it back to the
1838 * same level. (The easiest way to cause this is to type "suspend"
1839 * multiple times in jdb.)
1840 *
1841 * It's unclear what this means when the event specifies "resume all"
1842 * and some threads are suspended more deeply than others. This is
1843 * a rare problem, so for now we just prevent it from hanging forever
1844 * by rejecting the method invocation request. Without this, we will
1845 * be stuck waiting on a suspended thread.
1846 */
1847 int suspend_count = targetThread->GetSuspendCount();
1848 if (suspend_count > 1) {
1849 LOG(ERROR) << *targetThread << " suspend count too deep for method invocation: " << suspend_count;
1850 return JDWP::ERR_THREAD_SUSPENDED; // Probably not expected here.
1851 }
1852
1853 /*
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001854 * OLD-TODO: ought to screen the various IDs, and verify that the argument
Elliott Hughesd07986f2011-12-06 18:27:45 -08001855 * list is valid.
1856 */
1857 req->receiver_ = gRegistry->Get<Object*>(objectId);
1858 req->thread_ = gRegistry->Get<Object*>(threadId);
1859 req->class_ = gRegistry->Get<Class*>(classId);
1860 req->method_ = FromMethodId(methodId);
1861 req->num_args_ = numArgs;
1862 req->arg_array_ = argArray;
1863 req->options_ = options;
1864 req->invoke_needed_ = true;
1865 }
1866
1867 // The fact that we've released the thread list lock is a bit risky --- if the thread goes
1868 // away we're sitting high and dry -- but we must release this before the ResumeAllThreads
1869 // call, and it's unwise to hold it during WaitForSuspend.
1870
1871 {
1872 /*
1873 * We change our (JDWP thread) status, which should be THREAD_RUNNING,
1874 * so the VM can suspend for a GC if the invoke request causes us to
1875 * run out of memory. It's also a good idea to change it before locking
1876 * the invokeReq mutex, although that should never be held for long.
1877 */
1878 ScopedThreadStateChange tsc(Thread::Current(), Thread::kVmWait);
1879
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001880 VLOG(jdwp) << " Transferring control to event thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08001881 {
1882 MutexLock mu(req->lock_);
1883
1884 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001885 VLOG(jdwp) << " Resuming all threads";
Elliott Hughesd07986f2011-12-06 18:27:45 -08001886 thread_list->ResumeAll(true);
1887 } else {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001888 VLOG(jdwp) << " Resuming event thread only";
Elliott Hughesd07986f2011-12-06 18:27:45 -08001889 thread_list->Resume(targetThread, true);
1890 }
1891
1892 // Wait for the request to finish executing.
1893 while (req->invoke_needed_) {
1894 req->cond_.Wait(req->lock_);
1895 }
1896 }
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001897 VLOG(jdwp) << " Control has returned from event thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08001898
1899 /* wait for thread to re-suspend itself */
1900 targetThread->WaitUntilSuspended();
1901 //dvmWaitForSuspend(targetThread);
1902 }
1903
1904 /*
1905 * Suspend the threads. We waited for the target thread to suspend
1906 * itself, so all we need to do is suspend the others.
1907 *
1908 * The suspendAllThreads() call will double-suspend the event thread,
1909 * so we want to resume the target thread once to keep the books straight.
1910 */
1911 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001912 VLOG(jdwp) << " Suspending all threads";
Elliott Hughesd07986f2011-12-06 18:27:45 -08001913 thread_list->SuspendAll(true);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001914 VLOG(jdwp) << " Resuming event thread to balance the count";
Elliott Hughesd07986f2011-12-06 18:27:45 -08001915 thread_list->Resume(targetThread, true);
1916 }
1917
1918 // Copy the result.
1919 *pResultTag = req->result_tag;
1920 if (IsPrimitiveTag(req->result_tag)) {
1921 *pResultValue = req->result_value.j;
1922 } else {
1923 *pResultValue = gRegistry->Add(req->result_value.l);
1924 }
1925 *pExceptionId = req->exception;
1926 return req->error;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001927}
1928
1929void Dbg::ExecuteMethod(DebugInvokeReq* pReq) {
Elliott Hughesd07986f2011-12-06 18:27:45 -08001930 Thread* self = Thread::Current();
1931
1932 // We can be called while an exception is pending in the VM. We need
1933 // to preserve that across the method invocation.
1934 SirtRef<Throwable> old_exception(self->GetException());
1935 self->ClearException();
1936
1937 ScopedThreadStateChange tsc(self, Thread::kRunnable);
1938
1939 // Translate the method through the vtable, unless the debugger wants to suppress it.
1940 Method* m = pReq->method_;
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001941 VLOG(jdwp) << "ExecuteMethod " << PrettyMethod(m);
Elliott Hughesd07986f2011-12-06 18:27:45 -08001942 if ((pReq->options_ & JDWP::INVOKE_NONVIRTUAL) == 0 && pReq->receiver_ != NULL) {
1943 m = pReq->class_->FindVirtualMethodForVirtualOrInterface(pReq->method_);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001944 VLOG(jdwp) << "ExecuteMethod " << PrettyMethod(m);
Elliott Hughesd07986f2011-12-06 18:27:45 -08001945 }
1946 CHECK(m != NULL);
1947
1948 CHECK_EQ(sizeof(jvalue), sizeof(uint64_t));
1949
1950 pReq->result_value = InvokeWithJValues(self, pReq->receiver_, m, reinterpret_cast<JValue*>(pReq->arg_array_));
1951
1952 pReq->exception = gRegistry->Add(self->GetException());
1953 pReq->result_tag = BasicTagFromDescriptor(MethodHelper(m).GetShorty());
1954 if (pReq->exception != 0) {
1955 Object* exc = self->GetException();
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001956 VLOG(jdwp) << " JDWP invocation returning with exception=" << exc << " " << PrettyTypeOf(exc);
Elliott Hughesd07986f2011-12-06 18:27:45 -08001957 self->ClearException();
1958 pReq->result_value.j = 0;
1959 } else if (pReq->result_tag == JDWP::JT_OBJECT) {
1960 /* if no exception thrown, examine object result more closely */
1961 JDWP::JdwpTag new_tag = TagFromObject(pReq->result_value.l);
1962 if (new_tag != pReq->result_tag) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001963 VLOG(jdwp) << " JDWP promoted result from " << pReq->result_tag << " to " << new_tag;
Elliott Hughesd07986f2011-12-06 18:27:45 -08001964 pReq->result_tag = new_tag;
1965 }
1966
1967 /*
1968 * Register the object. We don't actually need an ObjectId yet,
1969 * but we do need to be sure that the GC won't move or discard the
1970 * object when we switch out of RUNNING. The ObjectId conversion
1971 * will add the object to the "do not touch" list.
1972 *
1973 * We can't use the "tracked allocation" mechanism here because
1974 * the object is going to be handed off to a different thread.
1975 */
1976 gRegistry->Add(pReq->result_value.l);
1977 }
1978
1979 if (old_exception.get() != NULL) {
1980 self->SetException(old_exception.get());
1981 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001982}
1983
Elliott Hughesd07986f2011-12-06 18:27:45 -08001984/*
1985 * Register an object ID that might not have been registered previously.
1986 *
1987 * Normally this wouldn't happen -- the conversion to an ObjectId would
1988 * have added the object to the registry -- but in some cases (e.g.
1989 * throwing exceptions) we really want to do the registration late.
1990 */
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001991void Dbg::RegisterObjectId(JDWP::ObjectId id) {
Elliott Hughesd07986f2011-12-06 18:27:45 -08001992 gRegistry->Add(reinterpret_cast<Object*>(id));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001993}
1994
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001995/*
1996 * "buf" contains a full JDWP packet, possibly with multiple chunks. We
1997 * need to process each, accumulate the replies, and ship the whole thing
1998 * back.
1999 *
2000 * Returns "true" if we have a reply. The reply buffer is newly allocated,
2001 * and includes the chunk type/length, followed by the data.
2002 *
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08002003 * OLD-TODO: we currently assume that the request and reply include a single
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002004 * chunk. If this becomes inconvenient we will need to adapt.
2005 */
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002006bool Dbg::DdmHandlePacket(const uint8_t* buf, int dataLen, uint8_t** pReplyBuf, int* pReplyLen) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002007 CHECK_GE(dataLen, 0);
2008
2009 Thread* self = Thread::Current();
2010 JNIEnv* env = self->GetJniEnv();
2011
Elliott Hughes844f9a02012-01-24 20:19:58 -08002012 static jclass Chunk_class = CacheClass(env, "org/apache/harmony/dalvik/ddmc/Chunk");
2013 static jclass DdmServer_class = CacheClass(env, "org/apache/harmony/dalvik/ddmc/DdmServer");
2014 static jmethodID dispatch_mid = env->GetStaticMethodID(DdmServer_class, "dispatch", "(I[BII)Lorg/apache/harmony/dalvik/ddmc/Chunk;");
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002015 static jfieldID data_fid = env->GetFieldID(Chunk_class, "data", "[B");
2016 static jfieldID length_fid = env->GetFieldID(Chunk_class, "length", "I");
2017 static jfieldID offset_fid = env->GetFieldID(Chunk_class, "offset", "I");
2018 static jfieldID type_fid = env->GetFieldID(Chunk_class, "type", "I");
2019
2020 // Create a byte[] corresponding to 'buf'.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002021 ScopedLocalRef<jbyteArray> dataArray(env, env->NewByteArray(dataLen));
2022 if (dataArray.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002023 LOG(WARNING) << "byte[] allocation failed: " << dataLen;
2024 env->ExceptionClear();
2025 return false;
2026 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002027 env->SetByteArrayRegion(dataArray.get(), 0, dataLen, reinterpret_cast<const jbyte*>(buf));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002028
2029 const int kChunkHdrLen = 8;
2030
2031 // Run through and find all chunks. [Currently just find the first.]
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002032 ScopedByteArrayRO contents(env, dataArray.get());
Elliott Hughesf7c3b662011-10-27 12:04:56 -07002033 jint type = JDWP::Get4BE(reinterpret_cast<const uint8_t*>(&contents[0]));
2034 jint length = JDWP::Get4BE(reinterpret_cast<const uint8_t*>(&contents[4]));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002035 jint offset = kChunkHdrLen;
2036 if (offset + length > dataLen) {
2037 LOG(WARNING) << StringPrintf("bad chunk found (len=%u pktLen=%d)", length, dataLen);
2038 return false;
2039 }
2040
2041 // Call "private static Chunk dispatch(int type, byte[] data, int offset, int length)".
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002042 ScopedLocalRef<jobject> chunk(env, env->CallStaticObjectMethod(DdmServer_class, dispatch_mid, type, dataArray.get(), offset, length));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002043 if (env->ExceptionCheck()) {
2044 LOG(INFO) << StringPrintf("Exception thrown by dispatcher for 0x%08x", type);
2045 env->ExceptionDescribe();
2046 env->ExceptionClear();
2047 return false;
2048 }
2049
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002050 if (chunk.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002051 return false;
2052 }
2053
2054 /*
2055 * Pull the pieces out of the chunk. We copy the results into a
2056 * newly-allocated buffer that the caller can free. We don't want to
2057 * continue using the Chunk object because nothing has a reference to it.
2058 *
2059 * We could avoid this by returning type/data/offset/length and having
2060 * the caller be aware of the object lifetime issues, but that
2061 * integrates the JDWP code more tightly into the VM, and doesn't work
2062 * if we have responses for multiple chunks.
2063 *
2064 * So we're pretty much stuck with copying data around multiple times.
2065 */
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002066 ScopedLocalRef<jbyteArray> replyData(env, reinterpret_cast<jbyteArray>(env->GetObjectField(chunk.get(), data_fid)));
2067 length = env->GetIntField(chunk.get(), length_fid);
2068 offset = env->GetIntField(chunk.get(), offset_fid);
2069 type = env->GetIntField(chunk.get(), type_fid);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002070
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002071 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 -07002072 if (length == 0 || replyData.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002073 return false;
2074 }
2075
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002076 jsize replyLength = env->GetArrayLength(replyData.get());
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002077 if (offset + length > replyLength) {
2078 LOG(WARNING) << StringPrintf("chunk off=%d len=%d exceeds reply array len %d", offset, length, replyLength);
2079 return false;
2080 }
2081
2082 uint8_t* reply = new uint8_t[length + kChunkHdrLen];
2083 if (reply == NULL) {
2084 LOG(WARNING) << "malloc failed: " << (length + kChunkHdrLen);
2085 return false;
2086 }
Elliott Hughesf7c3b662011-10-27 12:04:56 -07002087 JDWP::Set4BE(reply + 0, type);
2088 JDWP::Set4BE(reply + 4, length);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002089 env->GetByteArrayRegion(replyData.get(), offset, length, reinterpret_cast<jbyte*>(reply + kChunkHdrLen));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002090
2091 *pReplyBuf = reply;
2092 *pReplyLen = length + kChunkHdrLen;
2093
Elliott Hughesba8eee12012-01-24 20:25:24 -08002094 VLOG(jdwp) << StringPrintf("dvmHandleDdm returning type=%.4s buf=%p len=%d", reinterpret_cast<char*>(reply), reply, length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002095 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002096}
2097
Elliott Hughesa2155262011-11-16 16:26:58 -08002098void Dbg::DdmBroadcast(bool connect) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002099 VLOG(jdwp) << "Broadcasting DDM " << (connect ? "connect" : "disconnect") << "...";
Elliott Hughes47fce012011-10-25 18:37:19 -07002100
2101 Thread* self = Thread::Current();
2102 if (self->GetState() != Thread::kRunnable) {
2103 LOG(ERROR) << "DDM broadcast in thread state " << self->GetState();
2104 /* try anyway? */
2105 }
2106
2107 JNIEnv* env = self->GetJniEnv();
Elliott Hughes844f9a02012-01-24 20:19:58 -08002108 static jclass DdmServer_class = CacheClass(env, "org/apache/harmony/dalvik/ddmc/DdmServer");
Elliott Hughes47fce012011-10-25 18:37:19 -07002109 static jmethodID broadcast_mid = env->GetStaticMethodID(DdmServer_class, "broadcast", "(I)V");
2110 jint event = connect ? 1 /*DdmServer.CONNECTED*/ : 2 /*DdmServer.DISCONNECTED*/;
2111 env->CallStaticVoidMethod(DdmServer_class, broadcast_mid, event);
2112 if (env->ExceptionCheck()) {
2113 LOG(ERROR) << "DdmServer.broadcast " << event << " failed";
2114 env->ExceptionDescribe();
2115 env->ExceptionClear();
2116 }
2117}
2118
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002119void Dbg::DdmConnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08002120 Dbg::DdmBroadcast(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002121}
2122
2123void Dbg::DdmDisconnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08002124 Dbg::DdmBroadcast(false);
Elliott Hughes47fce012011-10-25 18:37:19 -07002125 gDdmThreadNotification = false;
2126}
2127
2128/*
Elliott Hughes82188472011-11-07 18:11:48 -08002129 * Send a notification when a thread starts, stops, or changes its name.
Elliott Hughes47fce012011-10-25 18:37:19 -07002130 *
2131 * Because we broadcast the full set of threads when the notifications are
2132 * first enabled, it's possible for "thread" to be actively executing.
2133 */
Elliott Hughes82188472011-11-07 18:11:48 -08002134void Dbg::DdmSendThreadNotification(Thread* t, uint32_t type) {
Elliott Hughes47fce012011-10-25 18:37:19 -07002135 if (!gDdmThreadNotification) {
2136 return;
2137 }
2138
Elliott Hughes82188472011-11-07 18:11:48 -08002139 if (type == CHUNK_TYPE("THDE")) {
Elliott Hughes47fce012011-10-25 18:37:19 -07002140 uint8_t buf[4];
Elliott Hughesf7c3b662011-10-27 12:04:56 -07002141 JDWP::Set4BE(&buf[0], t->GetThinLockId());
Elliott Hughes47fce012011-10-25 18:37:19 -07002142 Dbg::DdmSendChunk(CHUNK_TYPE("THDE"), 4, buf);
Elliott Hughes82188472011-11-07 18:11:48 -08002143 } else {
2144 CHECK(type == CHUNK_TYPE("THCR") || type == CHUNK_TYPE("THNM")) << type;
Elliott Hughes899e7892012-01-24 14:57:32 -08002145 SirtRef<String> name(t->GetThreadName());
Elliott Hughes82188472011-11-07 18:11:48 -08002146 size_t char_count = (name.get() != NULL) ? name->GetLength() : 0;
2147 const jchar* chars = name->GetCharArray()->GetData();
2148
Elliott Hughes21f32d72011-11-09 17:44:13 -08002149 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08002150 JDWP::Append4BE(bytes, t->GetThinLockId());
2151 JDWP::AppendUtf16BE(bytes, chars, char_count);
Elliott Hughes21f32d72011-11-09 17:44:13 -08002152 CHECK_EQ(bytes.size(), char_count*2 + sizeof(uint32_t)*2);
2153 Dbg::DdmSendChunk(type, bytes);
Elliott Hughes47fce012011-10-25 18:37:19 -07002154 }
2155}
2156
Elliott Hughesa2155262011-11-16 16:26:58 -08002157static void DdmSendThreadStartCallback(Thread* t, void*) {
Elliott Hughes82188472011-11-07 18:11:48 -08002158 Dbg::DdmSendThreadNotification(t, CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07002159}
2160
2161void Dbg::DdmSetThreadNotification(bool enable) {
2162 // We lock the thread list to avoid sending duplicate events or missing
2163 // a thread change. We should be okay holding this lock while sending
2164 // the messages out. (We have to hold it while accessing a live thread.)
Elliott Hughesbbd9d832011-11-07 14:40:00 -08002165 ScopedThreadListLock thread_list_lock;
Elliott Hughes47fce012011-10-25 18:37:19 -07002166
2167 gDdmThreadNotification = enable;
2168 if (enable) {
Elliott Hughesbfe487b2011-10-26 15:48:55 -07002169 Runtime::Current()->GetThreadList()->ForEach(DdmSendThreadStartCallback, NULL);
Elliott Hughes47fce012011-10-25 18:37:19 -07002170 }
2171}
2172
Elliott Hughesa2155262011-11-16 16:26:58 -08002173void Dbg::PostThreadStartOrStop(Thread* t, uint32_t type) {
Elliott Hughes47fce012011-10-25 18:37:19 -07002174 if (gDebuggerActive) {
2175 JDWP::ObjectId id = gRegistry->Add(t->GetPeer());
Elliott Hughes82188472011-11-07 18:11:48 -08002176 gJdwpState->PostThreadChange(id, type == CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07002177 }
Elliott Hughes82188472011-11-07 18:11:48 -08002178 Dbg::DdmSendThreadNotification(t, type);
Elliott Hughes47fce012011-10-25 18:37:19 -07002179}
2180
2181void Dbg::PostThreadStart(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08002182 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07002183}
2184
2185void Dbg::PostThreadDeath(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08002186 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THDE"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002187}
2188
Elliott Hughes82188472011-11-07 18:11:48 -08002189void Dbg::DdmSendChunk(uint32_t type, size_t byte_count, const uint8_t* buf) {
Elliott Hughes3bb81562011-10-21 18:52:59 -07002190 CHECK(buf != NULL);
2191 iovec vec[1];
2192 vec[0].iov_base = reinterpret_cast<void*>(const_cast<uint8_t*>(buf));
2193 vec[0].iov_len = byte_count;
2194 Dbg::DdmSendChunkV(type, vec, 1);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002195}
2196
Elliott Hughes21f32d72011-11-09 17:44:13 -08002197void Dbg::DdmSendChunk(uint32_t type, const std::vector<uint8_t>& bytes) {
2198 DdmSendChunk(type, bytes.size(), &bytes[0]);
2199}
2200
Elliott Hughescccd84f2011-12-05 16:51:54 -08002201void Dbg::DdmSendChunkV(uint32_t type, const struct iovec* iov, int iov_count) {
Elliott Hughes3bb81562011-10-21 18:52:59 -07002202 if (gJdwpState == NULL) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002203 VLOG(jdwp) << "Debugger thread not active, ignoring DDM send: " << type;
Elliott Hughes3bb81562011-10-21 18:52:59 -07002204 } else {
Elliott Hughescccd84f2011-12-05 16:51:54 -08002205 gJdwpState->DdmSendChunkV(type, iov, iov_count);
Elliott Hughes3bb81562011-10-21 18:52:59 -07002206 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002207}
2208
Elliott Hughes767a1472011-10-26 18:49:02 -07002209int Dbg::DdmHandleHpifChunk(HpifWhen when) {
2210 if (when == HPIF_WHEN_NOW) {
Elliott Hughes7162ad92011-10-27 14:08:42 -07002211 DdmSendHeapInfo(when);
Elliott Hughes767a1472011-10-26 18:49:02 -07002212 return true;
2213 }
2214
2215 if (when != HPIF_WHEN_NEVER && when != HPIF_WHEN_NEXT_GC && when != HPIF_WHEN_EVERY_GC) {
2216 LOG(ERROR) << "invalid HpifWhen value: " << static_cast<int>(when);
2217 return false;
2218 }
2219
2220 gDdmHpifWhen = when;
2221 return true;
2222}
2223
2224bool Dbg::DdmHandleHpsgNhsgChunk(Dbg::HpsgWhen when, Dbg::HpsgWhat what, bool native) {
2225 if (when != HPSG_WHEN_NEVER && when != HPSG_WHEN_EVERY_GC) {
2226 LOG(ERROR) << "invalid HpsgWhen value: " << static_cast<int>(when);
2227 return false;
2228 }
2229
2230 if (what != HPSG_WHAT_MERGED_OBJECTS && what != HPSG_WHAT_DISTINCT_OBJECTS) {
2231 LOG(ERROR) << "invalid HpsgWhat value: " << static_cast<int>(what);
2232 return false;
2233 }
2234
2235 if (native) {
2236 gDdmNhsgWhen = when;
2237 gDdmNhsgWhat = what;
2238 } else {
2239 gDdmHpsgWhen = when;
2240 gDdmHpsgWhat = what;
2241 }
2242 return true;
2243}
2244
Elliott Hughes7162ad92011-10-27 14:08:42 -07002245void Dbg::DdmSendHeapInfo(HpifWhen reason) {
2246 // If there's a one-shot 'when', reset it.
2247 if (reason == gDdmHpifWhen) {
2248 if (gDdmHpifWhen == HPIF_WHEN_NEXT_GC) {
2249 gDdmHpifWhen = HPIF_WHEN_NEVER;
2250 }
2251 }
2252
2253 /*
2254 * Chunk HPIF (client --> server)
2255 *
2256 * Heap Info. General information about the heap,
2257 * suitable for a summary display.
2258 *
2259 * [u4]: number of heaps
2260 *
2261 * For each heap:
2262 * [u4]: heap ID
2263 * [u8]: timestamp in ms since Unix epoch
2264 * [u1]: capture reason (same as 'when' value from server)
2265 * [u4]: max heap size in bytes (-Xmx)
2266 * [u4]: current heap size in bytes
2267 * [u4]: current number of bytes allocated
2268 * [u4]: current number of objects allocated
2269 */
2270 uint8_t heap_count = 1;
Elliott Hughes21f32d72011-11-09 17:44:13 -08002271 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08002272 JDWP::Append4BE(bytes, heap_count);
2273 JDWP::Append4BE(bytes, 1); // Heap id (bogus; we only have one heap).
2274 JDWP::Append8BE(bytes, MilliTime());
2275 JDWP::Append1BE(bytes, reason);
2276 JDWP::Append4BE(bytes, Heap::GetMaxMemory()); // Max allowed heap size in bytes.
2277 JDWP::Append4BE(bytes, Heap::GetTotalMemory()); // Current heap size in bytes.
2278 JDWP::Append4BE(bytes, Heap::GetBytesAllocated());
2279 JDWP::Append4BE(bytes, Heap::GetObjectsAllocated());
Elliott Hughes21f32d72011-11-09 17:44:13 -08002280 CHECK_EQ(bytes.size(), 4U + (heap_count * (4 + 8 + 1 + 4 + 4 + 4 + 4)));
2281 Dbg::DdmSendChunk(CHUNK_TYPE("HPIF"), bytes);
Elliott Hughes767a1472011-10-26 18:49:02 -07002282}
2283
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002284enum HpsgSolidity {
2285 SOLIDITY_FREE = 0,
2286 SOLIDITY_HARD = 1,
2287 SOLIDITY_SOFT = 2,
2288 SOLIDITY_WEAK = 3,
2289 SOLIDITY_PHANTOM = 4,
2290 SOLIDITY_FINALIZABLE = 5,
2291 SOLIDITY_SWEEP = 6,
2292};
2293
2294enum HpsgKind {
2295 KIND_OBJECT = 0,
2296 KIND_CLASS_OBJECT = 1,
2297 KIND_ARRAY_1 = 2,
2298 KIND_ARRAY_2 = 3,
2299 KIND_ARRAY_4 = 4,
2300 KIND_ARRAY_8 = 5,
2301 KIND_UNKNOWN = 6,
2302 KIND_NATIVE = 7,
2303};
2304
2305#define HPSG_PARTIAL (1<<7)
2306#define HPSG_STATE(solidity, kind) ((uint8_t)((((kind) & 0x7) << 3) | ((solidity) & 0x7)))
2307
Ian Rogers30fab402012-01-23 15:43:46 -08002308class HeapChunkContext {
2309 public:
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002310 // Maximum chunk size. Obtain this from the formula:
2311 // (((maximum_heap_size / ALLOCATION_UNIT_SIZE) + 255) / 256) * 2
2312 HeapChunkContext(bool merge, bool native)
Ian Rogers30fab402012-01-23 15:43:46 -08002313 : buf_(16384 - 16),
2314 type_(0),
2315 merge_(merge) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002316 Reset();
2317 if (native) {
Ian Rogers30fab402012-01-23 15:43:46 -08002318 type_ = CHUNK_TYPE("NHSG");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002319 } else {
Ian Rogers30fab402012-01-23 15:43:46 -08002320 type_ = merge ? CHUNK_TYPE("HPSG") : CHUNK_TYPE("HPSO");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002321 }
2322 }
2323
2324 ~HeapChunkContext() {
Ian Rogers30fab402012-01-23 15:43:46 -08002325 if (p_ > &buf_[0]) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002326 Flush();
2327 }
2328 }
2329
2330 void EnsureHeader(const void* chunk_ptr) {
Ian Rogers30fab402012-01-23 15:43:46 -08002331 if (!needHeader_) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002332 return;
2333 }
2334
2335 // Start a new HPSx chunk.
Ian Rogers30fab402012-01-23 15:43:46 -08002336 JDWP::Write4BE(&p_, 1); // Heap id (bogus; we only have one heap).
2337 JDWP::Write1BE(&p_, 8); // Size of allocation unit, in bytes.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002338
Ian Rogers30fab402012-01-23 15:43:46 -08002339 JDWP::Write4BE(&p_, reinterpret_cast<uintptr_t>(chunk_ptr)); // virtual address of segment start.
2340 JDWP::Write4BE(&p_, 0); // offset of this piece (relative to the virtual address).
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002341 // [u4]: length of piece, in allocation units
2342 // 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 -08002343 pieceLenField_ = p_;
2344 JDWP::Write4BE(&p_, 0x55555555);
2345 needHeader_ = false;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002346 }
2347
2348 void Flush() {
2349 // Patch the "length of piece" field.
Ian Rogers30fab402012-01-23 15:43:46 -08002350 CHECK_LE(&buf_[0], pieceLenField_);
2351 CHECK_LE(pieceLenField_, p_);
2352 JDWP::Set4BE(pieceLenField_, totalAllocationUnits_);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002353
Ian Rogers30fab402012-01-23 15:43:46 -08002354 Dbg::DdmSendChunk(type_, p_ - &buf_[0], &buf_[0]);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002355 Reset();
2356 }
2357
Ian Rogers30fab402012-01-23 15:43:46 -08002358 static void HeapChunkCallback(void* start, void* end, size_t used_bytes, void* arg) {
2359 reinterpret_cast<HeapChunkContext*>(arg)->HeapChunkCallback(start, end, used_bytes);
Elliott Hughesa2155262011-11-16 16:26:58 -08002360 }
2361
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002362 private:
Elliott Hughesa2155262011-11-16 16:26:58 -08002363 enum { ALLOCATION_UNIT_SIZE = 8 };
2364
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002365 void Reset() {
Ian Rogers30fab402012-01-23 15:43:46 -08002366 p_ = &buf_[0];
2367 totalAllocationUnits_ = 0;
2368 needHeader_ = true;
2369 pieceLenField_ = NULL;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002370 }
2371
Ian Rogers30fab402012-01-23 15:43:46 -08002372 void HeapChunkCallback(void* start, void* end, size_t used_bytes) {
2373 // Note: heap call backs cannot manipulate the heap upon which they are crawling, care is taken
2374 // in the following code not to allocate memory, by ensuring buf_ is of the correct size
2375
2376 const void* user_ptr = used_bytes > 0 ? const_cast<void*>(start) : NULL;
2377 // from malloc.c mem2chunk(mem)
2378 const void* chunk_ptr =
2379 reinterpret_cast<const void*>(reinterpret_cast<const char*>(const_cast<void*>(start)) -
2380 (2 * sizeof(size_t)));
2381 // from malloc.c chunksize
2382 size_t chunk_len = (*reinterpret_cast<size_t* const*>(chunk_ptr))[1] & ~7;
2383
2384
2385 //size_t chunk_len = malloc_usable_size(user_ptr);
Elliott Hughesa2155262011-11-16 16:26:58 -08002386 CHECK_EQ((chunk_len & (ALLOCATION_UNIT_SIZE-1)), 0U);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002387
Elliott Hughesa2155262011-11-16 16:26:58 -08002388 /* Make sure there's enough room left in the buffer.
2389 * We need to use two bytes for every fractional 256
2390 * allocation units used by the chunk.
2391 */
2392 {
2393 size_t needed = (((chunk_len/ALLOCATION_UNIT_SIZE + 255) / 256) * 2);
Ian Rogers30fab402012-01-23 15:43:46 -08002394 size_t bytesLeft = buf_.size() - (size_t)(p_ - &buf_[0]);
Elliott Hughesa2155262011-11-16 16:26:58 -08002395 if (bytesLeft < needed) {
2396 Flush();
2397 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002398
Ian Rogers30fab402012-01-23 15:43:46 -08002399 bytesLeft = buf_.size() - (size_t)(p_ - &buf_[0]);
Elliott Hughesa2155262011-11-16 16:26:58 -08002400 if (bytesLeft < needed) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08002401 LOG(WARNING) << "Chunk is too big to transmit (chunk_len=" << chunk_len << ", " << needed << " bytes)";
Elliott Hughesa2155262011-11-16 16:26:58 -08002402 return;
2403 }
2404 }
2405
2406 // OLD-TODO: notice when there's a gap and start a new heap, or at least a new range.
2407 EnsureHeader(chunk_ptr);
2408
2409 // Determine the type of this chunk.
2410 // OLD-TODO: if context.merge, see if this chunk is different from the last chunk.
2411 // If it's the same, we should combine them.
Ian Rogers30fab402012-01-23 15:43:46 -08002412 uint8_t state = ExamineObject(reinterpret_cast<const Object*>(user_ptr), (type_ == CHUNK_TYPE("NHSG")));
Elliott Hughesa2155262011-11-16 16:26:58 -08002413
2414 // Write out the chunk description.
2415 chunk_len /= ALLOCATION_UNIT_SIZE; // convert to allocation units
Ian Rogers30fab402012-01-23 15:43:46 -08002416 totalAllocationUnits_ += chunk_len;
Elliott Hughesa2155262011-11-16 16:26:58 -08002417 while (chunk_len > 256) {
Ian Rogers30fab402012-01-23 15:43:46 -08002418 *p_++ = state | HPSG_PARTIAL;
2419 *p_++ = 255; // length - 1
Elliott Hughesa2155262011-11-16 16:26:58 -08002420 chunk_len -= 256;
2421 }
Ian Rogers30fab402012-01-23 15:43:46 -08002422 *p_++ = state;
2423 *p_++ = chunk_len - 1;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002424 }
2425
Elliott Hughesa2155262011-11-16 16:26:58 -08002426 uint8_t ExamineObject(const Object* o, bool is_native_heap) {
2427 if (o == NULL) {
2428 return HPSG_STATE(SOLIDITY_FREE, 0);
2429 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002430
Elliott Hughesa2155262011-11-16 16:26:58 -08002431 // It's an allocated chunk. Figure out what it is.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002432
Elliott Hughesa2155262011-11-16 16:26:58 -08002433 // If we're looking at the native heap, we'll just return
2434 // (SOLIDITY_HARD, KIND_NATIVE) for all allocated chunks.
2435 if (is_native_heap || !Heap::IsLiveObjectLocked(o)) {
2436 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
2437 }
2438
2439 Class* c = o->GetClass();
2440 if (c == NULL) {
2441 // The object was probably just created but hasn't been initialized yet.
2442 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
2443 }
2444
2445 if (!Heap::IsHeapAddress(c)) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08002446 LOG(WARNING) << "Invalid class for managed heap object: " << o << " " << c;
Elliott Hughesa2155262011-11-16 16:26:58 -08002447 return HPSG_STATE(SOLIDITY_HARD, KIND_UNKNOWN);
2448 }
2449
2450 if (c->IsClassClass()) {
2451 return HPSG_STATE(SOLIDITY_HARD, KIND_CLASS_OBJECT);
2452 }
2453
2454 if (c->IsArrayClass()) {
2455 if (o->IsObjectArray()) {
2456 return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
2457 }
2458 switch (c->GetComponentSize()) {
2459 case 1: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_1);
2460 case 2: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_2);
2461 case 4: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
2462 case 8: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_8);
2463 }
2464 }
2465
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002466 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
2467 }
2468
Ian Rogers30fab402012-01-23 15:43:46 -08002469 std::vector<uint8_t> buf_;
2470 uint8_t* p_;
2471 uint8_t* pieceLenField_;
2472 size_t totalAllocationUnits_;
2473 uint32_t type_;
2474 bool merge_;
2475 bool needHeader_;
2476
Elliott Hughesa2155262011-11-16 16:26:58 -08002477 DISALLOW_COPY_AND_ASSIGN(HeapChunkContext);
2478};
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002479
2480void Dbg::DdmSendHeapSegments(bool native) {
2481 Dbg::HpsgWhen when;
2482 Dbg::HpsgWhat what;
2483 if (!native) {
2484 when = gDdmHpsgWhen;
2485 what = gDdmHpsgWhat;
2486 } else {
2487 when = gDdmNhsgWhen;
2488 what = gDdmNhsgWhat;
2489 }
2490 if (when == HPSG_WHEN_NEVER) {
2491 return;
2492 }
2493
2494 // Figure out what kind of chunks we'll be sending.
2495 CHECK(what == HPSG_WHAT_MERGED_OBJECTS || what == HPSG_WHAT_DISTINCT_OBJECTS) << static_cast<int>(what);
2496
2497 // First, send a heap start chunk.
2498 uint8_t heap_id[4];
2499 JDWP::Set4BE(&heap_id[0], 1); // Heap id (bogus; we only have one heap).
2500 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHST") : CHUNK_TYPE("HPST"), sizeof(heap_id), heap_id);
2501
2502 // Send a series of heap segment chunks.
Elliott Hughesa2155262011-11-16 16:26:58 -08002503 HeapChunkContext context((what == HPSG_WHAT_MERGED_OBJECTS), native);
2504 if (native) {
Ian Rogers30fab402012-01-23 15:43:46 -08002505 // TODO: enable when bionic has moved to dlmalloc 2.8.5
2506 // dlmalloc_inspect_all(HeapChunkContext::HeapChunkCallback, &context);
2507 UNIMPLEMENTED(WARNING) << "Native heap send heap segments";
Elliott Hughesa2155262011-11-16 16:26:58 -08002508 } else {
Ian Rogers30fab402012-01-23 15:43:46 -08002509 Heap::GetAllocSpace()->Walk(HeapChunkContext::HeapChunkCallback, &context);
Elliott Hughesa2155262011-11-16 16:26:58 -08002510 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002511
2512 // Finally, send a heap end chunk.
2513 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHEN") : CHUNK_TYPE("HPEN"), sizeof(heap_id), heap_id);
Elliott Hughes767a1472011-10-26 18:49:02 -07002514}
2515
Elliott Hughes545a0642011-11-08 19:10:03 -08002516void Dbg::SetAllocTrackingEnabled(bool enabled) {
2517 MutexLock mu(gAllocTrackerLock);
2518 if (enabled) {
2519 if (recent_allocation_records_ == NULL) {
2520 LOG(INFO) << "Enabling alloc tracker (" << kNumAllocRecords << " entries, "
2521 << kMaxAllocRecordStackDepth << " frames --> "
2522 << (sizeof(AllocRecord) * kNumAllocRecords) << " bytes)";
2523 gAllocRecordHead = gAllocRecordCount = 0;
2524 recent_allocation_records_ = new AllocRecord[kNumAllocRecords];
2525 CHECK(recent_allocation_records_ != NULL);
2526 }
2527 } else {
2528 delete[] recent_allocation_records_;
2529 recent_allocation_records_ = NULL;
2530 }
2531}
2532
2533struct AllocRecordStackVisitor : public Thread::StackVisitor {
Elliott Hughesba8eee12012-01-24 20:25:24 -08002534 explicit AllocRecordStackVisitor(AllocRecord* record) : record(record), depth(0) {
Elliott Hughes545a0642011-11-08 19:10:03 -08002535 }
2536
2537 virtual void VisitFrame(const Frame& f, uintptr_t pc) {
2538 if (depth >= kMaxAllocRecordStackDepth) {
2539 return;
2540 }
2541 Method* m = f.GetMethod();
2542 if (m == NULL || m->IsCalleeSaveMethod()) {
2543 return;
2544 }
2545 record->stack[depth].method = m;
2546 record->stack[depth].raw_pc = pc;
2547 ++depth;
2548 }
2549
2550 ~AllocRecordStackVisitor() {
2551 // Clear out any unused stack trace elements.
2552 for (; depth < kMaxAllocRecordStackDepth; ++depth) {
2553 record->stack[depth].method = NULL;
2554 record->stack[depth].raw_pc = 0;
2555 }
2556 }
2557
2558 AllocRecord* record;
2559 size_t depth;
2560};
2561
2562void Dbg::RecordAllocation(Class* type, size_t byte_count) {
2563 Thread* self = Thread::Current();
2564 CHECK(self != NULL);
2565
2566 MutexLock mu(gAllocTrackerLock);
2567 if (recent_allocation_records_ == NULL) {
2568 return;
2569 }
2570
2571 // Advance and clip.
2572 if (++gAllocRecordHead == kNumAllocRecords) {
2573 gAllocRecordHead = 0;
2574 }
2575
2576 // Fill in the basics.
2577 AllocRecord* record = &recent_allocation_records_[gAllocRecordHead];
2578 record->type = type;
2579 record->byte_count = byte_count;
2580 record->thin_lock_id = self->GetThinLockId();
2581
2582 // Fill in the stack trace.
2583 AllocRecordStackVisitor visitor(record);
2584 self->WalkStack(&visitor);
2585
2586 if (gAllocRecordCount < kNumAllocRecords) {
2587 ++gAllocRecordCount;
2588 }
2589}
2590
2591/*
2592 * Return the index of the head element.
2593 *
2594 * We point at the most-recently-written record, so if allocRecordCount is 1
2595 * we want to use the current element. Take "head+1" and subtract count
2596 * from it.
2597 *
2598 * We need to handle underflow in our circular buffer, so we add
2599 * kNumAllocRecords and then mask it back down.
2600 */
2601inline static int headIndex() {
2602 return (gAllocRecordHead+1 + kNumAllocRecords - gAllocRecordCount) & (kNumAllocRecords-1);
2603}
2604
2605void Dbg::DumpRecentAllocations() {
2606 MutexLock mu(gAllocTrackerLock);
2607 if (recent_allocation_records_ == NULL) {
2608 LOG(INFO) << "Not recording tracked allocations";
2609 return;
2610 }
2611
2612 // "i" is the head of the list. We want to start at the end of the
2613 // list and move forward to the tail.
2614 size_t i = headIndex();
2615 size_t count = gAllocRecordCount;
2616
2617 LOG(INFO) << "Tracked allocations, (head=" << gAllocRecordHead << " count=" << count << ")";
2618 while (count--) {
2619 AllocRecord* record = &recent_allocation_records_[i];
2620
Elliott Hughesaa6e1cd2012-01-18 19:26:06 -08002621 LOG(INFO) << StringPrintf(" T=%-2d %6zd ", record->thin_lock_id, record->byte_count)
Elliott Hughes545a0642011-11-08 19:10:03 -08002622 << PrettyClass(record->type);
2623
2624 for (size_t stack_frame = 0; stack_frame < kMaxAllocRecordStackDepth; ++stack_frame) {
2625 const Method* m = record->stack[stack_frame].method;
2626 if (m == NULL) {
2627 break;
2628 }
2629 LOG(INFO) << " " << PrettyMethod(m) << " line " << record->stack[stack_frame].LineNumber();
2630 }
2631
2632 // pause periodically to help logcat catch up
2633 if ((count % 5) == 0) {
2634 usleep(40000);
2635 }
2636
2637 i = (i + 1) & (kNumAllocRecords-1);
2638 }
2639}
2640
2641class StringTable {
2642 public:
2643 StringTable() {
2644 }
2645
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002646 void Add(const char* s) {
Elliott Hughes545a0642011-11-08 19:10:03 -08002647 table_.insert(s);
2648 }
2649
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002650 size_t IndexOf(const char* s) {
Elliott Hughes545a0642011-11-08 19:10:03 -08002651 return std::distance(table_.begin(), table_.find(s));
2652 }
2653
2654 size_t Size() {
2655 return table_.size();
2656 }
2657
2658 void WriteTo(std::vector<uint8_t>& bytes) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002659 typedef std::set<const char*>::const_iterator It; // TODO: C++0x auto
Elliott Hughes545a0642011-11-08 19:10:03 -08002660 for (It it = table_.begin(); it != table_.end(); ++it) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002661 const char* s = *it;
2662 size_t s_len = CountModifiedUtf8Chars(s);
2663 UniquePtr<uint16_t> s_utf16(new uint16_t[s_len]);
2664 ConvertModifiedUtf8ToUtf16(s_utf16.get(), s);
2665 JDWP::AppendUtf16BE(bytes, s_utf16.get(), s_len);
Elliott Hughes545a0642011-11-08 19:10:03 -08002666 }
2667 }
2668
2669 private:
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002670 std::set<const char*> table_;
Elliott Hughes545a0642011-11-08 19:10:03 -08002671 DISALLOW_COPY_AND_ASSIGN(StringTable);
2672};
2673
2674/*
2675 * The data we send to DDMS contains everything we have recorded.
2676 *
2677 * Message header (all values big-endian):
2678 * (1b) message header len (to allow future expansion); includes itself
2679 * (1b) entry header len
2680 * (1b) stack frame len
2681 * (2b) number of entries
2682 * (4b) offset to string table from start of message
2683 * (2b) number of class name strings
2684 * (2b) number of method name strings
2685 * (2b) number of source file name strings
2686 * For each entry:
2687 * (4b) total allocation size
2688 * (2b) threadId
2689 * (2b) allocated object's class name index
2690 * (1b) stack depth
2691 * For each stack frame:
2692 * (2b) method's class name
2693 * (2b) method name
2694 * (2b) method source file
2695 * (2b) line number, clipped to 32767; -2 if native; -1 if no source
2696 * (xb) class name strings
2697 * (xb) method name strings
2698 * (xb) source file strings
2699 *
2700 * As with other DDM traffic, strings are sent as a 4-byte length
2701 * followed by UTF-16 data.
2702 *
2703 * We send up 16-bit unsigned indexes into string tables. In theory there
2704 * can be (kMaxAllocRecordStackDepth * kNumAllocRecords) unique strings in
2705 * each table, but in practice there should be far fewer.
2706 *
2707 * The chief reason for using a string table here is to keep the size of
2708 * the DDMS message to a minimum. This is partly to make the protocol
2709 * efficient, but also because we have to form the whole thing up all at
2710 * once in a memory buffer.
2711 *
2712 * We use separate string tables for class names, method names, and source
2713 * files to keep the indexes small. There will generally be no overlap
2714 * between the contents of these tables.
2715 */
2716jbyteArray Dbg::GetRecentAllocations() {
2717 if (false) {
2718 DumpRecentAllocations();
2719 }
2720
2721 MutexLock mu(gAllocTrackerLock);
2722
2723 /*
2724 * Part 1: generate string tables.
2725 */
2726 StringTable class_names;
2727 StringTable method_names;
2728 StringTable filenames;
2729
2730 int count = gAllocRecordCount;
2731 int idx = headIndex();
2732 while (count--) {
2733 AllocRecord* record = &recent_allocation_records_[idx];
2734
Elliott Hughes91250e02011-12-13 22:30:35 -08002735 class_names.Add(ClassHelper(record->type).GetDescriptor());
Elliott Hughes545a0642011-11-08 19:10:03 -08002736
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002737 MethodHelper mh;
Elliott Hughes545a0642011-11-08 19:10:03 -08002738 for (size_t i = 0; i < kMaxAllocRecordStackDepth; i++) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002739 Method* m = record->stack[i].method;
2740 mh.ChangeMethod(m);
Elliott Hughes545a0642011-11-08 19:10:03 -08002741 if (m != NULL) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002742 class_names.Add(mh.GetDeclaringClassDescriptor());
2743 method_names.Add(mh.GetName());
2744 filenames.Add(mh.GetDeclaringClassSourceFile());
Elliott Hughes545a0642011-11-08 19:10:03 -08002745 }
2746 }
2747
2748 idx = (idx + 1) & (kNumAllocRecords-1);
2749 }
2750
2751 LOG(INFO) << "allocation records: " << gAllocRecordCount;
2752
2753 /*
2754 * Part 2: allocate a buffer and generate the output.
2755 */
2756 std::vector<uint8_t> bytes;
2757
2758 // (1b) message header len (to allow future expansion); includes itself
2759 // (1b) entry header len
2760 // (1b) stack frame len
2761 const int kMessageHeaderLen = 15;
2762 const int kEntryHeaderLen = 9;
2763 const int kStackFrameLen = 8;
2764 JDWP::Append1BE(bytes, kMessageHeaderLen);
2765 JDWP::Append1BE(bytes, kEntryHeaderLen);
2766 JDWP::Append1BE(bytes, kStackFrameLen);
2767
2768 // (2b) number of entries
2769 // (4b) offset to string table from start of message
2770 // (2b) number of class name strings
2771 // (2b) number of method name strings
2772 // (2b) number of source file name strings
2773 JDWP::Append2BE(bytes, gAllocRecordCount);
2774 size_t string_table_offset = bytes.size();
2775 JDWP::Append4BE(bytes, 0); // We'll patch this later...
2776 JDWP::Append2BE(bytes, class_names.Size());
2777 JDWP::Append2BE(bytes, method_names.Size());
2778 JDWP::Append2BE(bytes, filenames.Size());
2779
2780 count = gAllocRecordCount;
2781 idx = headIndex();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002782 ClassHelper kh;
Elliott Hughes545a0642011-11-08 19:10:03 -08002783 while (count--) {
2784 // For each entry:
2785 // (4b) total allocation size
2786 // (2b) thread id
2787 // (2b) allocated object's class name index
2788 // (1b) stack depth
2789 AllocRecord* record = &recent_allocation_records_[idx];
2790 size_t stack_depth = record->GetDepth();
2791 JDWP::Append4BE(bytes, record->byte_count);
2792 JDWP::Append2BE(bytes, record->thin_lock_id);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002793 kh.ChangeClass(record->type);
Elliott Hughes91250e02011-12-13 22:30:35 -08002794 JDWP::Append2BE(bytes, class_names.IndexOf(kh.GetDescriptor()));
Elliott Hughes545a0642011-11-08 19:10:03 -08002795 JDWP::Append1BE(bytes, stack_depth);
2796
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002797 MethodHelper mh;
Elliott Hughes545a0642011-11-08 19:10:03 -08002798 for (size_t stack_frame = 0; stack_frame < stack_depth; ++stack_frame) {
2799 // For each stack frame:
2800 // (2b) method's class name
2801 // (2b) method name
2802 // (2b) method source file
2803 // (2b) line number, clipped to 32767; -2 if native; -1 if no source
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002804 mh.ChangeMethod(record->stack[stack_frame].method);
2805 JDWP::Append2BE(bytes, class_names.IndexOf(mh.GetDeclaringClassDescriptor()));
2806 JDWP::Append2BE(bytes, method_names.IndexOf(mh.GetName()));
2807 JDWP::Append2BE(bytes, filenames.IndexOf(mh.GetDeclaringClassSourceFile()));
Elliott Hughes545a0642011-11-08 19:10:03 -08002808 JDWP::Append2BE(bytes, record->stack[stack_frame].LineNumber());
2809 }
2810
2811 idx = (idx + 1) & (kNumAllocRecords-1);
2812 }
2813
2814 // (xb) class name strings
2815 // (xb) method name strings
2816 // (xb) source file strings
2817 JDWP::Set4BE(&bytes[string_table_offset], bytes.size());
2818 class_names.WriteTo(bytes);
2819 method_names.WriteTo(bytes);
2820 filenames.WriteTo(bytes);
2821
2822 JNIEnv* env = Thread::Current()->GetJniEnv();
2823 jbyteArray result = env->NewByteArray(bytes.size());
2824 if (result != NULL) {
2825 env->SetByteArrayRegion(result, 0, bytes.size(), reinterpret_cast<const jbyte*>(&bytes[0]));
2826 }
2827 return result;
2828}
2829
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002830} // namespace art