blob: b2ea527dea7d881ec82f58b3c19659def7390956 [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 Hughes68fdbd02011-11-29 19:22:47 -080025#include "context.h"
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080026#include "object_utils.h"
Elliott Hughes6a5bd492011-10-28 14:33:57 -070027#include "ScopedLocalRef.h"
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -070028#include "ScopedPrimitiveArray.h"
Elliott Hughes47fce012011-10-25 18:37:19 -070029#include "stack_indirect_reference_table.h"
Elliott Hughes475fc232011-10-25 15:00:35 -070030#include "thread_list.h"
31
Elliott Hughes6a5bd492011-10-28 14:33:57 -070032extern "C" void dlmalloc_walk_heap(void(*)(const void*, size_t, const void*, size_t, void*), void*);
33#ifndef HAVE_ANDROID_OS
34void dlmalloc_walk_heap(void(*)(const void*, size_t, const void*, size_t, void*), void*) {
35 // No-op for glibc.
36}
37#endif
38
Elliott Hughes872d4ec2011-10-21 17:07:15 -070039namespace art {
40
Elliott Hughes545a0642011-11-08 19:10:03 -080041static const size_t kMaxAllocRecordStackDepth = 16; // Max 255.
42static const size_t kNumAllocRecords = 512; // Must be power of 2.
43
Elliott Hughes475fc232011-10-25 15:00:35 -070044class ObjectRegistry {
45 public:
46 ObjectRegistry() : lock_("ObjectRegistry lock") {
47 }
48
49 JDWP::ObjectId Add(Object* o) {
50 if (o == NULL) {
51 return 0;
52 }
53 JDWP::ObjectId id = static_cast<JDWP::ObjectId>(reinterpret_cast<uintptr_t>(o));
54 MutexLock mu(lock_);
55 map_[id] = o;
56 return id;
57 }
58
Elliott Hughes234ab152011-10-26 14:02:26 -070059 void Clear() {
60 MutexLock mu(lock_);
61 LOG(DEBUG) << "Debugger has detached; object registry had " << map_.size() << " entries";
62 map_.clear();
63 }
64
Elliott Hughes475fc232011-10-25 15:00:35 -070065 bool Contains(JDWP::ObjectId id) {
66 MutexLock mu(lock_);
67 return map_.find(id) != map_.end();
68 }
69
Elliott Hughesa2155262011-11-16 16:26:58 -080070 template<typename T> T Get(JDWP::ObjectId id) {
71 MutexLock mu(lock_);
72 typedef std::map<JDWP::ObjectId, Object*>::iterator It; // C++0x auto
73 It it = map_.find(id);
74 return (it != map_.end()) ? reinterpret_cast<T>(it->second) : NULL;
75 }
76
Elliott Hughesbfe487b2011-10-26 15:48:55 -070077 void VisitRoots(Heap::RootVisitor* visitor, void* arg) {
78 MutexLock mu(lock_);
79 typedef std::map<JDWP::ObjectId, Object*>::iterator It; // C++0x auto
80 for (It it = map_.begin(); it != map_.end(); ++it) {
81 visitor(it->second, arg);
82 }
83 }
84
Elliott Hughes475fc232011-10-25 15:00:35 -070085 private:
86 Mutex lock_;
87 std::map<JDWP::ObjectId, Object*> map_;
88};
89
Elliott Hughes545a0642011-11-08 19:10:03 -080090struct AllocRecordStackTraceElement {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080091 Method* method;
Elliott Hughes545a0642011-11-08 19:10:03 -080092 uintptr_t raw_pc;
93
94 int32_t LineNumber() const {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080095 return MethodHelper(method).GetLineNumFromNativePC(raw_pc);
Elliott Hughes545a0642011-11-08 19:10:03 -080096 }
97};
98
99struct AllocRecord {
100 Class* type;
101 size_t byte_count;
102 uint16_t thin_lock_id;
103 AllocRecordStackTraceElement stack[kMaxAllocRecordStackDepth]; // Unused entries have NULL method.
104
105 size_t GetDepth() {
106 size_t depth = 0;
107 while (depth < kMaxAllocRecordStackDepth && stack[depth].method != NULL) {
108 ++depth;
109 }
110 return depth;
111 }
112};
113
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700114// JDWP is allowed unless the Zygote forbids it.
115static bool gJdwpAllowed = true;
116
Elliott Hughes3bb81562011-10-21 18:52:59 -0700117// Was there a -Xrunjdwp or -agent argument on the command-line?
118static bool gJdwpConfigured = false;
119
120// Broken-down JDWP options. (Only valid if gJdwpConfigured is true.)
Elliott Hughes376a7a02011-10-24 18:35:55 -0700121static JDWP::JdwpOptions gJdwpOptions;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700122
123// Runtime JDWP state.
124static JDWP::JdwpState* gJdwpState = NULL;
125static bool gDebuggerConnected; // debugger or DDMS is connected.
126static bool gDebuggerActive; // debugger is making requests.
127
Elliott Hughes47fce012011-10-25 18:37:19 -0700128static bool gDdmThreadNotification = false;
129
Elliott Hughes767a1472011-10-26 18:49:02 -0700130// DDMS GC-related settings.
131static Dbg::HpifWhen gDdmHpifWhen = Dbg::HPIF_WHEN_NEVER;
132static Dbg::HpsgWhen gDdmHpsgWhen = Dbg::HPSG_WHEN_NEVER;
133static Dbg::HpsgWhat gDdmHpsgWhat;
134static Dbg::HpsgWhen gDdmNhsgWhen = Dbg::HPSG_WHEN_NEVER;
135static Dbg::HpsgWhat gDdmNhsgWhat;
136
Elliott Hughes475fc232011-10-25 15:00:35 -0700137static ObjectRegistry* gRegistry = NULL;
138
Elliott Hughes545a0642011-11-08 19:10:03 -0800139// Recent allocation tracking.
140static Mutex gAllocTrackerLock("AllocTracker lock");
141AllocRecord* Dbg::recent_allocation_records_ = NULL; // TODO: CircularBuffer<AllocRecord>
142static size_t gAllocRecordHead = 0;
143static size_t gAllocRecordCount = 0;
144
Elliott Hughes24437992011-11-30 14:49:33 -0800145static JDWP::JdwpTag BasicTagFromDescriptor(const char* descriptor) {
146 // JDWP deliberately uses the descriptor characters' ASCII values for its enum.
147 // Note that by "basic" we mean that we don't get more specific than JT_OBJECT.
148 return static_cast<JDWP::JdwpTag>(descriptor[0]);
149}
150
151static JDWP::JdwpTag TagFromClass(Class* c) {
Elliott Hughes86b00102011-12-05 17:54:26 -0800152 CHECK(c != NULL);
Elliott Hughes24437992011-11-30 14:49:33 -0800153 if (c->IsArrayClass()) {
154 return JDWP::JT_ARRAY;
155 }
156
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800157 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Elliott Hughes24437992011-11-30 14:49:33 -0800158 if (c->IsStringClass()) {
159 return JDWP::JT_STRING;
160 } else if (c->IsClassClass()) {
161 return JDWP::JT_CLASS_OBJECT;
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800162 } else if (c->InstanceOf(class_linker->FindSystemClass("Ljava/lang/Thread;"))) {
Elliott Hughes24437992011-11-30 14:49:33 -0800163 return JDWP::JT_THREAD;
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800164 } else if (c->InstanceOf(class_linker->FindSystemClass("Ljava/lang/ThreadGroup;"))) {
Elliott Hughes24437992011-11-30 14:49:33 -0800165 return JDWP::JT_THREAD_GROUP;
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800166 } else if (c->InstanceOf(class_linker->FindSystemClass("Ljava/lang/ClassLoader;"))) {
Elliott Hughes24437992011-11-30 14:49:33 -0800167 return JDWP::JT_CLASS_LOADER;
Elliott Hughes24437992011-11-30 14:49:33 -0800168 } else {
169 return JDWP::JT_OBJECT;
170 }
171}
172
173/*
174 * Objects declared to hold Object might actually hold a more specific
175 * type. The debugger may take a special interest in these (e.g. it
176 * wants to display the contents of Strings), so we want to return an
177 * appropriate tag.
178 *
179 * Null objects are tagged JT_OBJECT.
180 */
181static JDWP::JdwpTag TagFromObject(const Object* o) {
182 return (o == NULL) ? JDWP::JT_OBJECT : TagFromClass(o->GetClass());
183}
184
185static bool IsPrimitiveTag(JDWP::JdwpTag tag) {
186 switch (tag) {
187 case JDWP::JT_BOOLEAN:
188 case JDWP::JT_BYTE:
189 case JDWP::JT_CHAR:
190 case JDWP::JT_FLOAT:
191 case JDWP::JT_DOUBLE:
192 case JDWP::JT_INT:
193 case JDWP::JT_LONG:
194 case JDWP::JT_SHORT:
195 case JDWP::JT_VOID:
196 return true;
197 default:
198 return false;
199 }
200}
201
Elliott Hughes3bb81562011-10-21 18:52:59 -0700202/*
203 * Handle one of the JDWP name/value pairs.
204 *
205 * JDWP options are:
206 * help: if specified, show help message and bail
207 * transport: may be dt_socket or dt_shmem
208 * address: for dt_socket, "host:port", or just "port" when listening
209 * server: if "y", wait for debugger to attach; if "n", attach to debugger
210 * timeout: how long to wait for debugger to connect / listen
211 *
212 * Useful with server=n (these aren't supported yet):
213 * onthrow=<exception-name>: connect to debugger when exception thrown
214 * onuncaught=y|n: connect to debugger when uncaught exception thrown
215 * launch=<command-line>: launch the debugger itself
216 *
217 * The "transport" option is required, as is "address" if server=n.
218 */
219static bool ParseJdwpOption(const std::string& name, const std::string& value) {
220 if (name == "transport") {
221 if (value == "dt_socket") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700222 gJdwpOptions.transport = JDWP::kJdwpTransportSocket;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700223 } else if (value == "dt_android_adb") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700224 gJdwpOptions.transport = JDWP::kJdwpTransportAndroidAdb;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700225 } else {
226 LOG(ERROR) << "JDWP transport not supported: " << value;
227 return false;
228 }
229 } else if (name == "server") {
230 if (value == "n") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700231 gJdwpOptions.server = false;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700232 } else if (value == "y") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700233 gJdwpOptions.server = true;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700234 } else {
235 LOG(ERROR) << "JDWP option 'server' must be 'y' or 'n'";
236 return false;
237 }
238 } else if (name == "suspend") {
239 if (value == "n") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700240 gJdwpOptions.suspend = false;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700241 } else if (value == "y") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700242 gJdwpOptions.suspend = true;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700243 } else {
244 LOG(ERROR) << "JDWP option 'suspend' must be 'y' or 'n'";
245 return false;
246 }
247 } else if (name == "address") {
248 /* this is either <port> or <host>:<port> */
249 std::string port_string;
Elliott Hughes376a7a02011-10-24 18:35:55 -0700250 gJdwpOptions.host.clear();
Elliott Hughes3bb81562011-10-21 18:52:59 -0700251 std::string::size_type colon = value.find(':');
252 if (colon != std::string::npos) {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700253 gJdwpOptions.host = value.substr(0, colon);
Elliott Hughes3bb81562011-10-21 18:52:59 -0700254 port_string = value.substr(colon + 1);
255 } else {
256 port_string = value;
257 }
258 if (port_string.empty()) {
259 LOG(ERROR) << "JDWP address missing port: " << value;
260 return false;
261 }
262 char* end;
263 long port = strtol(port_string.c_str(), &end, 10);
264 if (*end != '\0') {
265 LOG(ERROR) << "JDWP address has junk in port field: " << value;
266 return false;
267 }
Elliott Hughes376a7a02011-10-24 18:35:55 -0700268 gJdwpOptions.port = port;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700269 } else if (name == "launch" || name == "onthrow" || name == "oncaught" || name == "timeout") {
270 /* valid but unsupported */
271 LOG(INFO) << "Ignoring JDWP option '" << name << "'='" << value << "'";
272 } else {
273 LOG(INFO) << "Ignoring unrecognized JDWP option '" << name << "'='" << value << "'";
274 }
275
276 return true;
277}
278
279/*
280 * Parse the latter half of a -Xrunjdwp/-agentlib:jdwp= string, e.g.:
281 * "transport=dt_socket,address=8000,server=y,suspend=n"
282 */
283bool Dbg::ParseJdwpOptions(const std::string& options) {
Elliott Hughes47fce012011-10-25 18:37:19 -0700284 LOG(VERBOSE) << "ParseJdwpOptions: " << options;
285
Elliott Hughes3bb81562011-10-21 18:52:59 -0700286 std::vector<std::string> pairs;
287 Split(options, ',', pairs);
288
289 for (size_t i = 0; i < pairs.size(); ++i) {
290 std::string::size_type equals = pairs[i].find('=');
291 if (equals == std::string::npos) {
292 LOG(ERROR) << "Can't parse JDWP option '" << pairs[i] << "' in '" << options << "'";
293 return false;
294 }
295 ParseJdwpOption(pairs[i].substr(0, equals), pairs[i].substr(equals + 1));
296 }
297
Elliott Hughes376a7a02011-10-24 18:35:55 -0700298 if (gJdwpOptions.transport == JDWP::kJdwpTransportUnknown) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700299 LOG(ERROR) << "Must specify JDWP transport: " << options;
300 }
Elliott Hughes376a7a02011-10-24 18:35:55 -0700301 if (!gJdwpOptions.server && (gJdwpOptions.host.empty() || gJdwpOptions.port == 0)) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700302 LOG(ERROR) << "Must specify JDWP host and port when server=n: " << options;
303 return false;
304 }
305
306 gJdwpConfigured = true;
307 return true;
308}
309
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700310void Dbg::StartJdwp() {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700311 if (!gJdwpAllowed || !gJdwpConfigured) {
312 // No JDWP for you!
313 return;
314 }
315
Elliott Hughes475fc232011-10-25 15:00:35 -0700316 CHECK(gRegistry == NULL);
317 gRegistry = new ObjectRegistry;
318
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700319 // Init JDWP if the debugger is enabled. This may connect out to a
320 // debugger, passively listen for a debugger, or block waiting for a
321 // debugger.
Elliott Hughes376a7a02011-10-24 18:35:55 -0700322 gJdwpState = JDWP::JdwpState::Create(&gJdwpOptions);
323 if (gJdwpState == NULL) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -0800324 // We probably failed because some other process has the port already, which means that
325 // if we don't abort the user is likely to think they're talking to us when they're actually
326 // talking to that other process.
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800327 LOG(FATAL) << "Debugger thread failed to initialize";
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700328 }
329
330 // If a debugger has already attached, send the "welcome" message.
331 // This may cause us to suspend all threads.
Elliott Hughes376a7a02011-10-24 18:35:55 -0700332 if (gJdwpState->IsActive()) {
Elliott Hughesa2155262011-11-16 16:26:58 -0800333 //ScopedThreadStateChange tsc(Thread::Current(), Thread::kRunnable);
Elliott Hughes376a7a02011-10-24 18:35:55 -0700334 if (!gJdwpState->PostVMStart()) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800335 LOG(WARNING) << "Failed to post 'start' message to debugger";
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700336 }
337 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700338}
339
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700340void Dbg::StopJdwp() {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700341 delete gJdwpState;
Elliott Hughes475fc232011-10-25 15:00:35 -0700342 delete gRegistry;
343 gRegistry = NULL;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700344}
345
Elliott Hughes767a1472011-10-26 18:49:02 -0700346void Dbg::GcDidFinish() {
347 if (gDdmHpifWhen != HPIF_WHEN_NEVER) {
348 LOG(DEBUG) << "Sending VM heap info to DDM";
Elliott Hughes7162ad92011-10-27 14:08:42 -0700349 DdmSendHeapInfo(gDdmHpifWhen);
Elliott Hughes767a1472011-10-26 18:49:02 -0700350 }
351 if (gDdmHpsgWhen != HPSG_WHEN_NEVER) {
352 LOG(DEBUG) << "Dumping VM heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700353 DdmSendHeapSegments(false);
Elliott Hughes767a1472011-10-26 18:49:02 -0700354 }
355 if (gDdmNhsgWhen != HPSG_WHEN_NEVER) {
356 LOG(DEBUG) << "Dumping native heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700357 DdmSendHeapSegments(true);
Elliott Hughes767a1472011-10-26 18:49:02 -0700358 }
359}
360
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700361void Dbg::SetJdwpAllowed(bool allowed) {
362 gJdwpAllowed = allowed;
363}
364
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700365DebugInvokeReq* Dbg::GetInvokeReq() {
Elliott Hughes475fc232011-10-25 15:00:35 -0700366 return Thread::Current()->GetInvokeReq();
367}
368
369Thread* Dbg::GetDebugThread() {
370 return (gJdwpState != NULL) ? gJdwpState->GetDebugThread() : NULL;
371}
372
373void Dbg::ClearWaitForEventThread() {
374 gJdwpState->ClearWaitForEventThread();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700375}
376
377void Dbg::Connected() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700378 CHECK(!gDebuggerConnected);
379 LOG(VERBOSE) << "JDWP has attached";
380 gDebuggerConnected = true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700381}
382
Elliott Hughesa2155262011-11-16 16:26:58 -0800383void Dbg::GoActive() {
384 // Enable all debugging features, including scans for breakpoints.
385 // This is a no-op if we're already active.
386 // Only called from the JDWP handler thread.
387 if (gDebuggerActive) {
388 return;
389 }
390
391 LOG(INFO) << "Debugger is active";
392
393 // TODO: CHECK we don't have any outstanding breakpoints.
394
395 gDebuggerActive = true;
396
397 //dvmEnableAllSubMode(kSubModeDebuggerActive);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700398}
399
400void Dbg::Disconnected() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700401 CHECK(gDebuggerConnected);
402
403 gDebuggerActive = false;
404
405 //dvmDisableAllSubMode(kSubModeDebuggerActive);
406
407 gRegistry->Clear();
408 gDebuggerConnected = false;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700409}
410
411bool Dbg::IsDebuggerConnected() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700412 return gDebuggerActive;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700413}
414
415bool Dbg::IsDebuggingEnabled() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700416 return gJdwpConfigured;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700417}
418
419int64_t Dbg::LastDebuggerActivity() {
Elliott Hughesca951522011-12-05 12:01:32 -0800420 return gJdwpState->LastDebuggerActivity();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700421}
422
423int Dbg::ThreadRunning() {
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700424 return static_cast<int>(Thread::Current()->SetState(Thread::kRunnable));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700425}
426
427int Dbg::ThreadWaiting() {
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700428 return static_cast<int>(Thread::Current()->SetState(Thread::kVmWait));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700429}
430
Elliott Hughes6ba581a2011-10-25 11:45:35 -0700431int Dbg::ThreadContinuing(int new_state) {
432 return static_cast<int>(Thread::Current()->SetState(static_cast<Thread::State>(new_state)));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700433}
434
435void Dbg::UndoDebuggerSuspensions() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700436 Runtime::Current()->GetThreadList()->UndoDebuggerSuspensions();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700437}
438
439void Dbg::Exit(int status) {
Elliott Hughes1bba14f2011-12-01 18:00:36 -0800440 exit(status); // This is all dalvik did.
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700441}
442
Elliott Hughesbfe487b2011-10-26 15:48:55 -0700443void Dbg::VisitRoots(Heap::RootVisitor* visitor, void* arg) {
444 if (gRegistry != NULL) {
445 gRegistry->VisitRoots(visitor, arg);
446 }
447}
448
Elliott Hughesa2155262011-11-16 16:26:58 -0800449std::string Dbg::GetClassDescriptor(JDWP::RefTypeId classId) {
450 Class* c = gRegistry->Get<Class*>(classId);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800451 return ClassHelper(c).GetDescriptor();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700452}
453
454JDWP::ObjectId Dbg::GetClassObject(JDWP::RefTypeId id) {
455 UNIMPLEMENTED(FATAL);
456 return 0;
457}
458
459JDWP::RefTypeId Dbg::GetSuperclass(JDWP::RefTypeId id) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800460 Class* c = gRegistry->Get<Class*>(id);
461 return gRegistry->Add(c->GetSuperClass());
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700462}
463
464JDWP::ObjectId Dbg::GetClassLoader(JDWP::RefTypeId id) {
Elliott Hughes1bba14f2011-12-01 18:00:36 -0800465 Object* o = gRegistry->Get<Object*>(id);
466 return gRegistry->Add(o->GetClass()->GetClassLoader());
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700467}
468
469uint32_t Dbg::GetAccessFlags(JDWP::RefTypeId id) {
Elliott Hughes6fa602d2011-12-02 17:54:25 -0800470 Class* c = gRegistry->Get<Class*>(id);
471 return c->GetAccessFlags() & kAccJavaFlagsMask;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700472}
473
Elliott Hughesaed4be92011-12-02 16:16:23 -0800474bool Dbg::IsInterface(JDWP::RefTypeId classId) {
475 Class* c = gRegistry->Get<Class*>(classId);
476 return c->IsInterface();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700477}
478
Elliott Hughesa2155262011-11-16 16:26:58 -0800479void Dbg::GetClassList(uint32_t* pClassCount, JDWP::RefTypeId** pClasses) {
480 // Get the complete list of reference classes (i.e. all classes except
481 // the primitive types).
482 // Returns a newly-allocated buffer full of RefTypeId values.
483 struct ClassListCreator {
484 static bool Visit(Class* c, void* arg) {
485 return reinterpret_cast<ClassListCreator*>(arg)->Visit(c);
486 }
487
488 bool Visit(Class* c) {
489 if (!c->IsPrimitive()) {
490 classes.push_back(static_cast<JDWP::RefTypeId>(gRegistry->Add(c)));
491 }
492 return true;
493 }
494
495 std::vector<JDWP::RefTypeId> classes;
496 };
497
498 ClassListCreator clc;
499 Runtime::Current()->GetClassLinker()->VisitClasses(ClassListCreator::Visit, &clc);
500 *pClassCount = clc.classes.size();
501 *pClasses = new JDWP::RefTypeId[clc.classes.size()];
502 for (size_t i = 0; i < clc.classes.size(); ++i) {
503 (*pClasses)[i] = clc.classes[i];
504 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700505}
506
507void Dbg::GetVisibleClassList(JDWP::ObjectId classLoaderId, uint32_t* pNumClasses, JDWP::RefTypeId** pClassRefBuf) {
508 UNIMPLEMENTED(FATAL);
509}
510
Elliott Hughes6fa602d2011-12-02 17:54:25 -0800511void Dbg::GetClassInfo(JDWP::RefTypeId classId, JDWP::JdwpTypeTag* pTypeTag, uint32_t* pStatus, std::string* pDescriptor) {
Elliott Hughesa2155262011-11-16 16:26:58 -0800512 Class* c = gRegistry->Get<Class*>(classId);
513 if (c->IsArrayClass()) {
514 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
515 *pTypeTag = JDWP::TT_ARRAY;
516 } else {
517 if (c->IsErroneous()) {
518 *pStatus = JDWP::CS_ERROR;
519 } else {
520 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED | JDWP::CS_INITIALIZED;
521 }
522 *pTypeTag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
523 }
524
525 if (pDescriptor != NULL) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800526 *pDescriptor = ClassHelper(c).GetDescriptor();
Elliott Hughesa2155262011-11-16 16:26:58 -0800527 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700528}
529
Elliott Hughes6fa602d2011-12-02 17:54:25 -0800530void Dbg::FindLoadedClassBySignature(const char* descriptor, std::vector<JDWP::RefTypeId>& ids) {
531 std::vector<Class*> classes;
532 Runtime::Current()->GetClassLinker()->LookupClasses(descriptor, classes);
533 ids.clear();
534 for (size_t i = 0; i < classes.size(); ++i) {
535 ids.push_back(gRegistry->Add(classes[i]));
536 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700537}
538
Elliott Hughes6fa602d2011-12-02 17:54:25 -0800539void Dbg::GetObjectType(JDWP::ObjectId objectId, JDWP::JdwpTypeTag* pRefTypeTag, JDWP::RefTypeId* pRefTypeId) {
Elliott Hughes499c5132011-11-17 14:55:11 -0800540 Object* o = gRegistry->Get<Object*>(objectId);
541 if (o->GetClass()->IsArrayClass()) {
542 *pRefTypeTag = JDWP::TT_ARRAY;
543 } else if (o->GetClass()->IsInterface()) {
544 *pRefTypeTag = JDWP::TT_INTERFACE;
545 } else {
546 *pRefTypeTag = JDWP::TT_CLASS;
547 }
548 *pRefTypeId = gRegistry->Add(o->GetClass());
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700549}
550
551uint8_t Dbg::GetClassObjectType(JDWP::RefTypeId refTypeId) {
552 UNIMPLEMENTED(FATAL);
553 return 0;
554}
555
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800556std::string Dbg::GetSignature(JDWP::RefTypeId refTypeId) {
557 Class* c = gRegistry->Get<Class*>(refTypeId);
558 CHECK(c != NULL);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800559 return ClassHelper(c).GetDescriptor();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700560}
561
Elliott Hughes03181a82011-11-17 17:22:21 -0800562bool Dbg::GetSourceFile(JDWP::RefTypeId refTypeId, std::string& result) {
563 Class* c = gRegistry->Get<Class*>(refTypeId);
564 CHECK(c != NULL);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800565 result = ClassHelper(c).GetSourceFile();
566 return result == NULL;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700567}
568
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700569uint8_t Dbg::GetObjectTag(JDWP::ObjectId objectId) {
Elliott Hughes24437992011-11-30 14:49:33 -0800570 Object* o = gRegistry->Get<Object*>(objectId);
571 return TagFromObject(o);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700572}
573
Elliott Hughesaed4be92011-12-02 16:16:23 -0800574size_t Dbg::GetTagWidth(JDWP::JdwpTag tag) {
Elliott Hughesdbb40792011-11-18 17:05:22 -0800575 switch (tag) {
576 case JDWP::JT_VOID:
577 return 0;
578 case JDWP::JT_BYTE:
579 case JDWP::JT_BOOLEAN:
580 return 1;
581 case JDWP::JT_CHAR:
582 case JDWP::JT_SHORT:
583 return 2;
584 case JDWP::JT_FLOAT:
585 case JDWP::JT_INT:
586 return 4;
587 case JDWP::JT_ARRAY:
588 case JDWP::JT_OBJECT:
589 case JDWP::JT_STRING:
590 case JDWP::JT_THREAD:
591 case JDWP::JT_THREAD_GROUP:
592 case JDWP::JT_CLASS_LOADER:
593 case JDWP::JT_CLASS_OBJECT:
594 return sizeof(JDWP::ObjectId);
595 case JDWP::JT_DOUBLE:
596 case JDWP::JT_LONG:
597 return 8;
598 default:
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800599 LOG(FATAL) << "Unknown tag " << tag;
Elliott Hughesdbb40792011-11-18 17:05:22 -0800600 return -1;
601 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700602}
603
604int Dbg::GetArrayLength(JDWP::ObjectId arrayId) {
Elliott Hughes68fdbd02011-11-29 19:22:47 -0800605 Object* o = gRegistry->Get<Object*>(arrayId);
606 Array* a = o->AsArray();
607 return a->GetLength();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700608}
609
610uint8_t Dbg::GetArrayElementTag(JDWP::ObjectId arrayId) {
Elliott Hughes24437992011-11-30 14:49:33 -0800611 Object* o = gRegistry->Get<Object*>(arrayId);
612 Array* a = o->AsArray();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800613 std::string descriptor(ClassHelper(a->GetClass()).GetDescriptor());
Elliott Hughes24437992011-11-30 14:49:33 -0800614 JDWP::JdwpTag tag = BasicTagFromDescriptor(descriptor.c_str() + 1);
615 if (!IsPrimitiveTag(tag)) {
616 tag = TagFromClass(a->GetClass()->GetComponentType());
617 }
618 return tag;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700619}
620
Elliott Hughes24437992011-11-30 14:49:33 -0800621bool Dbg::OutputArray(JDWP::ObjectId arrayId, int offset, int count, JDWP::ExpandBuf* pReply) {
622 Object* o = gRegistry->Get<Object*>(arrayId);
623 Array* a = o->AsArray();
624
625 if (offset < 0 || count < 0 || offset > a->GetLength() || a->GetLength() - offset < count) {
626 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
627 return false;
628 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800629 std::string descriptor(ClassHelper(a->GetClass()).GetDescriptor());
Elliott Hughes24437992011-11-30 14:49:33 -0800630 JDWP::JdwpTag tag = BasicTagFromDescriptor(descriptor.c_str() + 1);
631
632 if (IsPrimitiveTag(tag)) {
633 size_t width = GetTagWidth(tag);
634 const uint8_t* src = reinterpret_cast<uint8_t*>(a->GetRawData());
635 uint8_t* dst = expandBufAddSpace(pReply, count * width);
636 if (width == 8) {
637 const uint64_t* src8 = reinterpret_cast<const uint64_t*>(src);
638 for (int i = 0; i < count; ++i) JDWP::Write8BE(&dst, src8[offset + i]);
639 } else if (width == 4) {
640 const uint32_t* src4 = reinterpret_cast<const uint32_t*>(src);
641 for (int i = 0; i < count; ++i) JDWP::Write4BE(&dst, src4[offset + i]);
642 } else if (width == 2) {
643 const uint16_t* src2 = reinterpret_cast<const uint16_t*>(src);
644 for (int i = 0; i < count; ++i) JDWP::Write2BE(&dst, src2[offset + i]);
645 } else {
646 memcpy(dst, &src[offset * width], count * width);
647 }
648 } else {
649 ObjectArray<Object>* oa = a->AsObjectArray<Object>();
650 for (int i = 0; i < count; ++i) {
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800651 Object* element = oa->Get(offset + i);
Elliott Hughes24437992011-11-30 14:49:33 -0800652 JDWP::JdwpTag specific_tag = (element != NULL) ? TagFromObject(element) : tag;
653 expandBufAdd1(pReply, specific_tag);
654 expandBufAddObjectId(pReply, gRegistry->Add(element));
655 }
656 }
657
658 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700659}
660
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800661bool Dbg::SetArrayElements(JDWP::ObjectId arrayId, int offset, int count, const uint8_t* src) {
662 Object* o = gRegistry->Get<Object*>(arrayId);
663 Array* a = o->AsArray();
664
665 if (offset < 0 || count < 0 || offset > a->GetLength() || a->GetLength() - offset < count) {
666 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
667 return false;
668 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800669 std::string descriptor(ClassHelper(a->GetClass()).GetDescriptor());
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800670 JDWP::JdwpTag tag = BasicTagFromDescriptor(descriptor.c_str() + 1);
671
672 if (IsPrimitiveTag(tag)) {
673 size_t width = GetTagWidth(tag);
674 uint8_t* dst = &(reinterpret_cast<uint8_t*>(a->GetRawData())[offset * width]);
675 if (width == 8) {
676 for (int i = 0; i < count; ++i) {
677 // Handle potentially non-aligned memory access one byte at a time for ARM's benefit.
678 uint64_t value;
679 for (size_t j = 0; j < sizeof(uint64_t); ++j) reinterpret_cast<uint8_t*>(&value)[j] = src[j];
680 src += sizeof(uint64_t);
681 JDWP::Write8BE(&dst, value);
682 }
683 } else if (width == 4) {
684 const uint32_t* src4 = reinterpret_cast<const uint32_t*>(src);
685 for (int i = 0; i < count; ++i) JDWP::Write4BE(&dst, src4[i]);
686 } else if (width == 2) {
687 const uint16_t* src2 = reinterpret_cast<const uint16_t*>(src);
688 for (int i = 0; i < count; ++i) JDWP::Write2BE(&dst, src2[i]);
689 } else {
690 memcpy(&dst[offset * width], src, count * width);
691 }
692 } else {
693 ObjectArray<Object>* oa = a->AsObjectArray<Object>();
694 for (int i = 0; i < count; ++i) {
695 JDWP::ObjectId id = JDWP::ReadObjectId(&src);
696 oa->Set(offset + i, gRegistry->Get<Object*>(id));
697 }
698 }
699
700 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700701}
702
703JDWP::ObjectId Dbg::CreateString(const char* str) {
Elliott Hughescccd84f2011-12-05 16:51:54 -0800704 return gRegistry->Add(String::AllocFromModifiedUtf8(str));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700705}
706
707JDWP::ObjectId Dbg::CreateObject(JDWP::RefTypeId classId) {
Elliott Hughescccd84f2011-12-05 16:51:54 -0800708 Class* c = gRegistry->Get<Class*>(classId);
709 return gRegistry->Add(c->AllocObject());
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700710}
711
Elliott Hughesbf13d362011-12-08 15:51:37 -0800712/*
713 * Used by Eclipse's "Display" view to evaluate "new byte[5]" to get "(byte[]) [0, 0, 0, 0, 0]".
714 */
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700715JDWP::ObjectId Dbg::CreateArrayObject(JDWP::RefTypeId arrayTypeId, uint32_t length) {
Elliott Hughesbf13d362011-12-08 15:51:37 -0800716 Class* array_class = gRegistry->Get<Class*>(arrayTypeId);
717 CHECK(array_class->IsArrayClass()) << PrettyClass(array_class);
718 return gRegistry->Add(Array::Alloc(array_class, length));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700719}
720
721bool Dbg::MatchType(JDWP::RefTypeId instClassId, JDWP::RefTypeId classId) {
Elliott Hughesd07986f2011-12-06 18:27:45 -0800722 return gRegistry->Get<Class*>(instClassId)->InstanceOf(gRegistry->Get<Class*>(classId));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700723}
724
Elliott Hughes03181a82011-11-17 17:22:21 -0800725JDWP::FieldId ToFieldId(Field* f) {
726#ifdef MOVING_GARBAGE_COLLECTOR
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700727 UNIMPLEMENTED(FATAL);
Elliott Hughes03181a82011-11-17 17:22:21 -0800728#else
729 return static_cast<JDWP::FieldId>(reinterpret_cast<uintptr_t>(f));
730#endif
731}
732
733JDWP::MethodId ToMethodId(Method* m) {
734#ifdef MOVING_GARBAGE_COLLECTOR
735 UNIMPLEMENTED(FATAL);
736#else
737 return static_cast<JDWP::MethodId>(reinterpret_cast<uintptr_t>(m));
738#endif
739}
740
Elliott Hughesaed4be92011-12-02 16:16:23 -0800741Field* FromFieldId(JDWP::FieldId fid) {
742#ifdef MOVING_GARBAGE_COLLECTOR
743 UNIMPLEMENTED(FATAL);
744#else
745 return reinterpret_cast<Field*>(static_cast<uintptr_t>(fid));
746#endif
747}
748
Elliott Hughes03181a82011-11-17 17:22:21 -0800749Method* FromMethodId(JDWP::MethodId mid) {
750#ifdef MOVING_GARBAGE_COLLECTOR
751 UNIMPLEMENTED(FATAL);
752#else
753 return reinterpret_cast<Method*>(static_cast<uintptr_t>(mid));
754#endif
755}
756
Elliott Hughesd07986f2011-12-06 18:27:45 -0800757void SetLocation(JDWP::JdwpLocation& location, Method* m, uintptr_t native_pc) {
758 Class* c = m->GetDeclaringClass();
759 location.typeTag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
760 location.classId = gRegistry->Add(c);
761 location.methodId = ToMethodId(m);
762 location.idx = m->IsNative() ? -1 : m->ToDexPC(native_pc);
763}
764
Elliott Hughes03181a82011-11-17 17:22:21 -0800765std::string Dbg::GetMethodName(JDWP::RefTypeId refTypeId, JDWP::MethodId methodId) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800766 Method* m = FromMethodId(methodId);
767 return MethodHelper(m).GetName();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700768}
769
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800770/*
771 * Augment the access flags for synthetic methods and fields by setting
772 * the (as described by the spec) "0xf0000000 bit". Also, strip out any
773 * flags not specified by the Java programming language.
774 */
775static uint32_t MangleAccessFlags(uint32_t accessFlags) {
776 accessFlags &= kAccJavaFlagsMask;
777 if ((accessFlags & kAccSynthetic) != 0) {
778 accessFlags |= 0xf0000000;
779 }
780 return accessFlags;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700781}
782
Elliott Hughesdbb40792011-11-18 17:05:22 -0800783static const uint16_t kEclipseWorkaroundSlot = 1000;
784
785/*
786 * Eclipse appears to expect that the "this" reference is in slot zero.
787 * If it's not, the "variables" display will show two copies of "this",
788 * possibly because it gets "this" from SF.ThisObject and then displays
789 * all locals with nonzero slot numbers.
790 *
791 * So, we remap the item in slot 0 to 1000, and remap "this" to zero. On
792 * SF.GetValues / SF.SetValues we map them back.
Elliott Hughesc5b734a2011-12-01 17:20:58 -0800793 *
794 * TODO: jdb uses the value to determine whether a variable is a local or an argument,
795 * by checking whether it's less than the number of arguments. To make that work, we'd
796 * have to "mangle" all the arguments to come first, not just the implicit argument 'this'.
Elliott Hughesdbb40792011-11-18 17:05:22 -0800797 */
798static uint16_t MangleSlot(uint16_t slot, const char* name) {
799 uint16_t newSlot = slot;
800 if (strcmp(name, "this") == 0) {
801 newSlot = 0;
802 } else if (slot == 0) {
803 newSlot = kEclipseWorkaroundSlot;
804 }
805 return newSlot;
806}
807
Elliott Hughes68fdbd02011-11-29 19:22:47 -0800808static uint16_t DemangleSlot(uint16_t slot, Frame& f) {
Elliott Hughesdbb40792011-11-18 17:05:22 -0800809 if (slot == kEclipseWorkaroundSlot) {
Elliott Hughes68fdbd02011-11-29 19:22:47 -0800810 return 0;
Elliott Hughesdbb40792011-11-18 17:05:22 -0800811 } else if (slot == 0) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800812 const DexFile::CodeItem* code_item = MethodHelper(f.GetMethod()).GetCodeItem();
813 return code_item->registers_size_ - code_item->ins_size_;
Elliott Hughesdbb40792011-11-18 17:05:22 -0800814 }
Elliott Hughes68fdbd02011-11-29 19:22:47 -0800815 return slot;
Elliott Hughesdbb40792011-11-18 17:05:22 -0800816}
817
Elliott Hughesc5b734a2011-12-01 17:20:58 -0800818void Dbg::OutputDeclaredFields(JDWP::RefTypeId refTypeId, bool with_generic, JDWP::ExpandBuf* pReply) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800819 Class* c = gRegistry->Get<Class*>(refTypeId);
820 CHECK(c != NULL);
821
822 size_t instance_field_count = c->NumInstanceFields();
823 size_t static_field_count = c->NumStaticFields();
824
825 expandBufAdd4BE(pReply, instance_field_count + static_field_count);
826
827 for (size_t i = 0; i < instance_field_count + static_field_count; ++i) {
828 Field* f = (i < instance_field_count) ? c->GetInstanceField(i) : c->GetStaticField(i - instance_field_count);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800829 FieldHelper fh(f);
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800830 expandBufAddFieldId(pReply, ToFieldId(f));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800831 expandBufAddUtf8String(pReply, fh.GetName());
832 expandBufAddUtf8String(pReply, fh.GetTypeDescriptor());
Elliott Hughesc5b734a2011-12-01 17:20:58 -0800833 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800834 static const char genericSignature[1] = "";
835 expandBufAddUtf8String(pReply, genericSignature);
836 }
837 expandBufAdd4BE(pReply, MangleAccessFlags(f->GetAccessFlags()));
838 }
839}
840
Elliott Hughesc5b734a2011-12-01 17:20:58 -0800841void Dbg::OutputDeclaredMethods(JDWP::RefTypeId refTypeId, bool with_generic, JDWP::ExpandBuf* pReply) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800842 Class* c = gRegistry->Get<Class*>(refTypeId);
843 CHECK(c != NULL);
844
845 size_t direct_method_count = c->NumDirectMethods();
846 size_t virtual_method_count = c->NumVirtualMethods();
847
848 expandBufAdd4BE(pReply, direct_method_count + virtual_method_count);
849
850 for (size_t i = 0; i < direct_method_count + virtual_method_count; ++i) {
851 Method* m = (i < direct_method_count) ? c->GetDirectMethod(i) : c->GetVirtualMethod(i - direct_method_count);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800852 MethodHelper mh(m);
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800853 expandBufAddMethodId(pReply, ToMethodId(m));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800854 expandBufAddUtf8String(pReply, mh.GetName());
Elliott Hughes4740cdf2011-12-07 14:07:12 -0800855 expandBufAddUtf8String(pReply, mh.GetSignature());
Elliott Hughesc5b734a2011-12-01 17:20:58 -0800856 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800857 static const char genericSignature[1] = "";
858 expandBufAddUtf8String(pReply, genericSignature);
859 }
860 expandBufAdd4BE(pReply, MangleAccessFlags(m->GetAccessFlags()));
861 }
862}
863
864void Dbg::OutputDeclaredInterfaces(JDWP::RefTypeId refTypeId, JDWP::ExpandBuf* pReply) {
865 Class* c = gRegistry->Get<Class*>(refTypeId);
866 CHECK(c != NULL);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800867 ClassHelper kh(c);
868 size_t interface_count = kh.NumInterfaces();
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800869 expandBufAdd4BE(pReply, interface_count);
870 for (size_t i = 0; i < interface_count; ++i) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800871 expandBufAddRefTypeId(pReply, gRegistry->Add(kh.GetInterface(i)));
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800872 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700873}
874
875void Dbg::OutputLineTable(JDWP::RefTypeId refTypeId, JDWP::MethodId methodId, JDWP::ExpandBuf* pReply) {
Elliott Hughes03181a82011-11-17 17:22:21 -0800876 struct DebugCallbackContext {
877 int numItems;
878 JDWP::ExpandBuf* pReply;
879
880 static bool Callback(void* context, uint32_t address, uint32_t lineNum) {
881 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
882 expandBufAdd8BE(pContext->pReply, address);
883 expandBufAdd4BE(pContext->pReply, lineNum);
884 pContext->numItems++;
885 return true;
886 }
887 };
888
889 Method* m = FromMethodId(methodId);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800890 MethodHelper mh(m);
Elliott Hughes03181a82011-11-17 17:22:21 -0800891 uint64_t start, end;
892 if (m->IsNative()) {
893 start = -1;
894 end = -1;
895 } else {
896 start = 0;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800897 // TODO: what are the units supposed to be? *2?
898 end = mh.GetCodeItem()->insns_size_in_code_units_;
Elliott Hughes03181a82011-11-17 17:22:21 -0800899 }
900
901 expandBufAdd8BE(pReply, start);
902 expandBufAdd8BE(pReply, end);
903
904 // Add numLines later
905 size_t numLinesOffset = expandBufGetLength(pReply);
906 expandBufAdd4BE(pReply, 0);
907
908 DebugCallbackContext context;
909 context.numItems = 0;
910 context.pReply = pReply;
911
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800912 mh.GetDexFile().DecodeDebugInfo(mh.GetCodeItem(), m->IsStatic(), m->GetDexMethodIndex(),
913 DebugCallbackContext::Callback, NULL, &context);
Elliott Hughes03181a82011-11-17 17:22:21 -0800914
915 JDWP::Set4BE(expandBufGetBuffer(pReply) + numLinesOffset, context.numItems);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700916}
917
Elliott Hughesc5b734a2011-12-01 17:20:58 -0800918void Dbg::OutputVariableTable(JDWP::RefTypeId refTypeId, JDWP::MethodId methodId, bool with_generic, JDWP::ExpandBuf* pReply) {
Elliott Hughesdbb40792011-11-18 17:05:22 -0800919 struct DebugCallbackContext {
Elliott Hughesdbb40792011-11-18 17:05:22 -0800920 JDWP::ExpandBuf* pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -0800921 size_t variable_count;
922 bool with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -0800923
Elliott Hughesc5b734a2011-12-01 17:20:58 -0800924 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 -0800925 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
926
Elliott Hughesc5b734a2011-12-01 17:20:58 -0800927 LOG(VERBOSE) << StringPrintf(" %2d: %d(%d) '%s' '%s' '%s' slot=%d", pContext->variable_count, startAddress, endAddress - startAddress, name, descriptor, signature, slot);
Elliott Hughesdbb40792011-11-18 17:05:22 -0800928
Elliott Hughes68fdbd02011-11-29 19:22:47 -0800929 slot = MangleSlot(slot, name);
930
Elliott Hughesdbb40792011-11-18 17:05:22 -0800931 expandBufAdd8BE(pContext->pReply, startAddress);
932 expandBufAddUtf8String(pContext->pReply, name);
933 expandBufAddUtf8String(pContext->pReply, descriptor);
Elliott Hughesc5b734a2011-12-01 17:20:58 -0800934 if (pContext->with_generic) {
Elliott Hughesdbb40792011-11-18 17:05:22 -0800935 expandBufAddUtf8String(pContext->pReply, signature);
936 }
937 expandBufAdd4BE(pContext->pReply, endAddress - startAddress);
938 expandBufAdd4BE(pContext->pReply, slot);
939
Elliott Hughesc5b734a2011-12-01 17:20:58 -0800940 ++pContext->variable_count;
Elliott Hughesdbb40792011-11-18 17:05:22 -0800941 }
942 };
943
944 Method* m = FromMethodId(methodId);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800945 MethodHelper mh(m);
946 const DexFile::CodeItem* code_item = mh.GetCodeItem();
Elliott Hughesdbb40792011-11-18 17:05:22 -0800947
Elliott Hughesc5b734a2011-12-01 17:20:58 -0800948 // arg_count considers doubles and longs to take 2 units.
949 // variable_count considers everything to take 1 unit.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800950 std::string shorty(mh.GetShorty());
Elliott Hughesc5b734a2011-12-01 17:20:58 -0800951 expandBufAdd4BE(pReply, m->NumArgRegisters(shorty));
Elliott Hughesdbb40792011-11-18 17:05:22 -0800952
Elliott Hughesc5b734a2011-12-01 17:20:58 -0800953 // We don't know the total number of variables yet, so leave a blank and update it later.
954 size_t variable_count_offset = expandBufGetLength(pReply);
Elliott Hughesdbb40792011-11-18 17:05:22 -0800955 expandBufAdd4BE(pReply, 0);
956
957 DebugCallbackContext context;
Elliott Hughesdbb40792011-11-18 17:05:22 -0800958 context.pReply = pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -0800959 context.variable_count = 0;
960 context.with_generic = with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -0800961
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800962 mh.GetDexFile().DecodeDebugInfo(code_item, m->IsStatic(), m->GetDexMethodIndex(), NULL,
963 DebugCallbackContext::Callback, &context);
Elliott Hughesdbb40792011-11-18 17:05:22 -0800964
Elliott Hughesc5b734a2011-12-01 17:20:58 -0800965 JDWP::Set4BE(expandBufGetBuffer(pReply) + variable_count_offset, context.variable_count);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700966}
967
Elliott Hughesaed4be92011-12-02 16:16:23 -0800968JDWP::JdwpTag Dbg::GetFieldBasicTag(JDWP::FieldId fieldId) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800969 return BasicTagFromDescriptor(FieldHelper(FromFieldId(fieldId)).GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700970}
971
Elliott Hughesaed4be92011-12-02 16:16:23 -0800972JDWP::JdwpTag Dbg::GetStaticFieldBasicTag(JDWP::FieldId fieldId) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800973 return BasicTagFromDescriptor(FieldHelper(FromFieldId(fieldId)).GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700974}
975
976void Dbg::GetFieldValue(JDWP::ObjectId objectId, JDWP::FieldId fieldId, JDWP::ExpandBuf* pReply) {
Elliott Hughesaed4be92011-12-02 16:16:23 -0800977 Object* o = gRegistry->Get<Object*>(objectId);
978 Field* f = FromFieldId(fieldId);
979
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800980 JDWP::JdwpTag tag = BasicTagFromDescriptor(FieldHelper(f).GetTypeDescriptor());
Elliott Hughesaed4be92011-12-02 16:16:23 -0800981
982 if (IsPrimitiveTag(tag)) {
983 expandBufAdd1(pReply, tag);
984 if (tag == JDWP::JT_BOOLEAN || tag == JDWP::JT_BYTE) {
985 expandBufAdd1(pReply, f->Get32(o));
986 } else if (tag == JDWP::JT_CHAR || tag == JDWP::JT_SHORT) {
987 expandBufAdd2BE(pReply, f->Get32(o));
988 } else if (tag == JDWP::JT_FLOAT || tag == JDWP::JT_INT) {
989 expandBufAdd4BE(pReply, f->Get32(o));
990 } else if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
991 expandBufAdd8BE(pReply, f->Get64(o));
992 } else {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800993 LOG(FATAL) << "Unknown tag: " << tag;
Elliott Hughesaed4be92011-12-02 16:16:23 -0800994 }
995 } else {
996 Object* value = f->GetObject(o);
997 expandBufAdd1(pReply, TagFromObject(value));
998 expandBufAddObjectId(pReply, gRegistry->Add(value));
999 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001000}
1001
1002void Dbg::SetFieldValue(JDWP::ObjectId objectId, JDWP::FieldId fieldId, uint64_t value, int width) {
Elliott Hughesaed4be92011-12-02 16:16:23 -08001003 Object* o = gRegistry->Get<Object*>(objectId);
1004 Field* f = FromFieldId(fieldId);
1005
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001006 JDWP::JdwpTag tag = BasicTagFromDescriptor(FieldHelper(f).GetTypeDescriptor());
Elliott Hughesaed4be92011-12-02 16:16:23 -08001007
1008 if (IsPrimitiveTag(tag)) {
1009 if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
1010 f->Set64(o, value);
1011 } else {
1012 f->Set32(o, value);
1013 }
1014 } else {
1015 f->SetObject(o, gRegistry->Get<Object*>(value));
1016 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001017}
1018
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001019void Dbg::GetStaticFieldValue(JDWP::FieldId fieldId, JDWP::ExpandBuf* pReply) {
1020 GetFieldValue(0, fieldId, pReply);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001021}
1022
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001023void Dbg::SetStaticFieldValue(JDWP::FieldId fieldId, uint64_t value, int width) {
1024 SetFieldValue(0, fieldId, value, width);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001025}
1026
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001027std::string Dbg::StringToUtf8(JDWP::ObjectId strId) {
1028 String* s = gRegistry->Get<String*>(strId);
1029 return s->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001030}
1031
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001032Thread* DecodeThread(JDWP::ObjectId threadId) {
1033 Object* thread_peer = gRegistry->Get<Object*>(threadId);
1034 CHECK(thread_peer != NULL);
1035 return Thread::FromManagedThread(thread_peer);
1036}
1037
1038bool Dbg::GetThreadName(JDWP::ObjectId threadId, std::string& name) {
1039 ScopedThreadListLock thread_list_lock;
1040 Thread* thread = DecodeThread(threadId);
1041 if (thread == NULL) {
1042 return false;
1043 }
1044 StringAppendF(&name, "<%d> %s", thread->GetThinLockId(), thread->GetName()->ToModifiedUtf8().c_str());
1045 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001046}
1047
1048JDWP::ObjectId Dbg::GetThreadGroup(JDWP::ObjectId threadId) {
Elliott Hughes499c5132011-11-17 14:55:11 -08001049 Object* thread = gRegistry->Get<Object*>(threadId);
1050 CHECK(thread != NULL);
1051
1052 Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/Thread;");
1053 CHECK(c != NULL);
1054 Field* f = c->FindInstanceField("group", "Ljava/lang/ThreadGroup;");
1055 CHECK(f != NULL);
1056 Object* group = f->GetObject(thread);
1057 CHECK(group != NULL);
1058 return gRegistry->Add(group);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001059}
1060
Elliott Hughes499c5132011-11-17 14:55:11 -08001061std::string Dbg::GetThreadGroupName(JDWP::ObjectId threadGroupId) {
1062 Object* thread_group = gRegistry->Get<Object*>(threadGroupId);
1063 CHECK(thread_group != NULL);
1064
1065 Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/ThreadGroup;");
1066 CHECK(c != NULL);
1067 Field* f = c->FindInstanceField("name", "Ljava/lang/String;");
1068 CHECK(f != NULL);
1069 String* s = reinterpret_cast<String*>(f->GetObject(thread_group));
1070 return s->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001071}
1072
1073JDWP::ObjectId Dbg::GetThreadGroupParent(JDWP::ObjectId threadGroupId) {
Elliott Hughes4e235312011-12-02 11:34:15 -08001074 Object* thread_group = gRegistry->Get<Object*>(threadGroupId);
1075 CHECK(thread_group != NULL);
1076
1077 Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/ThreadGroup;");
1078 CHECK(c != NULL);
1079 Field* f = c->FindInstanceField("parent", "Ljava/lang/ThreadGroup;");
1080 CHECK(f != NULL);
1081 Object* parent = f->GetObject(thread_group);
1082 return gRegistry->Add(parent);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001083}
1084
Elliott Hughes499c5132011-11-17 14:55:11 -08001085static Object* GetStaticThreadGroup(const char* field_name) {
1086 Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/ThreadGroup;");
1087 CHECK(c != NULL);
1088 Field* f = c->FindStaticField(field_name, "Ljava/lang/ThreadGroup;");
1089 CHECK(f != NULL);
1090 Object* group = f->GetObject(NULL);
1091 CHECK(group != NULL);
1092 return group;
1093}
1094
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001095JDWP::ObjectId Dbg::GetSystemThreadGroupId() {
Elliott Hughes499c5132011-11-17 14:55:11 -08001096 return gRegistry->Add(GetStaticThreadGroup("mSystem"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001097}
1098
1099JDWP::ObjectId Dbg::GetMainThreadGroupId() {
Elliott Hughes499c5132011-11-17 14:55:11 -08001100 return gRegistry->Add(GetStaticThreadGroup("mMain"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001101}
1102
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001103bool Dbg::GetThreadStatus(JDWP::ObjectId threadId, JDWP::JdwpThreadStatus* pThreadStatus, JDWP::JdwpSuspendStatus* pSuspendStatus) {
Elliott Hughes499c5132011-11-17 14:55:11 -08001104 ScopedThreadListLock thread_list_lock;
1105
1106 Thread* thread = DecodeThread(threadId);
1107 if (thread == NULL) {
1108 return false;
1109 }
1110
1111 switch (thread->GetState()) {
1112 case Thread::kTerminated: *pThreadStatus = JDWP::TS_ZOMBIE; break;
1113 case Thread::kRunnable: *pThreadStatus = JDWP::TS_RUNNING; break;
1114 case Thread::kTimedWaiting: *pThreadStatus = JDWP::TS_SLEEPING; break;
1115 case Thread::kBlocked: *pThreadStatus = JDWP::TS_MONITOR; break;
1116 case Thread::kWaiting: *pThreadStatus = JDWP::TS_WAIT; break;
1117 case Thread::kInitializing: *pThreadStatus = JDWP::TS_ZOMBIE; break;
1118 case Thread::kStarting: *pThreadStatus = JDWP::TS_ZOMBIE; break;
1119 case Thread::kNative: *pThreadStatus = JDWP::TS_RUNNING; break;
1120 case Thread::kVmWait: *pThreadStatus = JDWP::TS_WAIT; break;
1121 case Thread::kSuspended: *pThreadStatus = JDWP::TS_RUNNING; break;
1122 default:
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001123 LOG(FATAL) << "Unknown thread state " << thread->GetState();
Elliott Hughes499c5132011-11-17 14:55:11 -08001124 }
1125
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001126 *pSuspendStatus = (thread->IsSuspended() ? JDWP::SUSPEND_STATUS_SUSPENDED : JDWP::SUSPEND_STATUS_NOT_SUSPENDED);
Elliott Hughes499c5132011-11-17 14:55:11 -08001127
1128 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001129}
1130
1131uint32_t Dbg::GetThreadSuspendCount(JDWP::ObjectId threadId) {
Elliott Hughesd07986f2011-12-06 18:27:45 -08001132 return DecodeThread(threadId)->GetSuspendCount();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001133}
1134
1135bool Dbg::ThreadExists(JDWP::ObjectId threadId) {
Elliott Hughes761928d2011-11-16 18:33:03 -08001136 return DecodeThread(threadId) != NULL;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001137}
1138
1139bool Dbg::IsSuspended(JDWP::ObjectId threadId) {
Elliott Hughes761928d2011-11-16 18:33:03 -08001140 return DecodeThread(threadId)->IsSuspended();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001141}
1142
Elliott Hughesa2155262011-11-16 16:26:58 -08001143void Dbg::GetThreadGroupThreadsImpl(Object* thread_group, JDWP::ObjectId** ppThreadIds, uint32_t* pThreadCount) {
1144 struct ThreadListVisitor {
1145 static void Visit(Thread* t, void* arg) {
1146 reinterpret_cast<ThreadListVisitor*>(arg)->Visit(t);
1147 }
1148
1149 void Visit(Thread* t) {
1150 if (t == Dbg::GetDebugThread()) {
1151 // Skip the JDWP thread. Some debuggers get bent out of shape when they can't suspend and
1152 // query all threads, so it's easier if we just don't tell them about this thread.
1153 return;
1154 }
1155 if (thread_group == NULL || t->GetThreadGroup() == thread_group) {
1156 threads.push_back(gRegistry->Add(t->GetPeer()));
1157 }
1158 }
1159
1160 Object* thread_group;
1161 std::vector<JDWP::ObjectId> threads;
1162 };
1163
1164 ThreadListVisitor tlv;
1165 tlv.thread_group = thread_group;
1166
1167 {
1168 ScopedThreadListLock thread_list_lock;
1169 Runtime::Current()->GetThreadList()->ForEach(ThreadListVisitor::Visit, &tlv);
1170 }
1171
1172 *pThreadCount = tlv.threads.size();
1173 if (*pThreadCount == 0) {
1174 *ppThreadIds = NULL;
1175 } else {
1176 *ppThreadIds = new JDWP::ObjectId[*pThreadCount];
1177 for (size_t i = 0; i < *pThreadCount; ++i) {
1178 (*ppThreadIds)[i] = tlv.threads[i];
1179 }
1180 }
1181}
1182
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001183void Dbg::GetThreadGroupThreads(JDWP::ObjectId threadGroupId, JDWP::ObjectId** ppThreadIds, uint32_t* pThreadCount) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001184 GetThreadGroupThreadsImpl(gRegistry->Get<Object*>(threadGroupId), ppThreadIds, pThreadCount);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001185}
1186
1187void Dbg::GetAllThreads(JDWP::ObjectId** ppThreadIds, uint32_t* pThreadCount) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001188 GetThreadGroupThreadsImpl(NULL, ppThreadIds, pThreadCount);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001189}
1190
1191int Dbg::GetThreadFrameCount(JDWP::ObjectId threadId) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001192 ScopedThreadListLock thread_list_lock;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001193 struct CountStackDepthVisitor : public Thread::StackVisitor {
1194 CountStackDepthVisitor() : depth(0) {}
Elliott Hughesf8a2df72011-12-01 12:19:54 -08001195 virtual void VisitFrame(const Frame& f, uintptr_t) {
1196 // TODO: we'll need to skip callee-save frames too.
1197 if (f.HasMethod()) {
1198 ++depth;
1199 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001200 }
1201 size_t depth;
1202 };
1203 CountStackDepthVisitor visitor;
1204 DecodeThread(threadId)->WalkStack(&visitor);
1205 return visitor.depth;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001206}
1207
Elliott Hughes03181a82011-11-17 17:22:21 -08001208bool Dbg::GetThreadFrame(JDWP::ObjectId threadId, int desired_frame_number, JDWP::FrameId* pFrameId, JDWP::JdwpLocation* pLoc) {
1209 ScopedThreadListLock thread_list_lock;
1210 struct GetFrameVisitor : public Thread::StackVisitor {
1211 GetFrameVisitor(int desired_frame_number, JDWP::FrameId* pFrameId, JDWP::JdwpLocation* pLoc)
1212 : found(false) ,depth(0), desired_frame_number(desired_frame_number), pFrameId(pFrameId), pLoc(pLoc) {
1213 }
1214 virtual void VisitFrame(const Frame& f, uintptr_t pc) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -08001215 // TODO: we'll need to skip callee-save frames too.
Elliott Hughes03181a82011-11-17 17:22:21 -08001216 if (!f.HasMethod()) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -08001217 return; // The debugger can't do anything useful with a frame that has no Method*.
Elliott Hughes03181a82011-11-17 17:22:21 -08001218 }
1219
1220 if (depth == desired_frame_number) {
1221 *pFrameId = reinterpret_cast<JDWP::FrameId>(f.GetSP());
Elliott Hughesd07986f2011-12-06 18:27:45 -08001222 SetLocation(*pLoc, f.GetMethod(), pc);
Elliott Hughes03181a82011-11-17 17:22:21 -08001223 found = true;
1224 }
1225 ++depth;
1226 }
1227 bool found;
1228 int depth;
1229 int desired_frame_number;
1230 JDWP::FrameId* pFrameId;
1231 JDWP::JdwpLocation* pLoc;
1232 };
1233 GetFrameVisitor visitor(desired_frame_number, pFrameId, pLoc);
1234 visitor.desired_frame_number = desired_frame_number;
1235 DecodeThread(threadId)->WalkStack(&visitor);
1236 return visitor.found;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001237}
1238
1239JDWP::ObjectId Dbg::GetThreadSelfId() {
Elliott Hughes475fc232011-10-25 15:00:35 -07001240 return gRegistry->Add(Thread::Current()->GetPeer());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001241}
1242
Elliott Hughes475fc232011-10-25 15:00:35 -07001243void Dbg::SuspendVM() {
Elliott Hughesa2155262011-11-16 16:26:58 -08001244 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 -07001245 Runtime::Current()->GetThreadList()->SuspendAll(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001246}
1247
1248void Dbg::ResumeVM() {
Elliott Hughes475fc232011-10-25 15:00:35 -07001249 Runtime::Current()->GetThreadList()->ResumeAll(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001250}
1251
1252void Dbg::SuspendThread(JDWP::ObjectId threadId) {
Elliott Hughes4e235312011-12-02 11:34:15 -08001253 Object* peer = gRegistry->Get<Object*>(threadId);
1254 ScopedThreadListLock thread_list_lock;
1255 Thread* thread = Thread::FromManagedThread(peer);
1256 if (thread == NULL) {
1257 LOG(WARNING) << "No such thread for suspend: " << peer;
1258 return;
1259 }
1260 Runtime::Current()->GetThreadList()->Suspend(thread, true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001261}
1262
1263void Dbg::ResumeThread(JDWP::ObjectId threadId) {
Elliott Hughes4e235312011-12-02 11:34:15 -08001264 Object* peer = gRegistry->Get<Object*>(threadId);
1265 ScopedThreadListLock thread_list_lock;
1266 Thread* thread = Thread::FromManagedThread(peer);
1267 if (thread == NULL) {
1268 LOG(WARNING) << "No such thread for resume: " << peer;
1269 return;
1270 }
1271 Runtime::Current()->GetThreadList()->Resume(thread, true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001272}
1273
1274void Dbg::SuspendSelf() {
Elliott Hughes475fc232011-10-25 15:00:35 -07001275 Runtime::Current()->GetThreadList()->SuspendSelfForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001276}
1277
Elliott Hughesd07986f2011-12-06 18:27:45 -08001278bool Dbg::GetThisObject(JDWP::FrameId frameId, JDWP::ObjectId* pThisId) {
Elliott Hughes86b00102011-12-05 17:54:26 -08001279 Method** sp = reinterpret_cast<Method**>(frameId);
1280 Frame f;
1281 f.SetSP(sp);
Elliott Hughes86b00102011-12-05 17:54:26 -08001282 Method* m = f.GetMethod();
1283
1284 Object* o = NULL;
1285 if (!m->IsNative() && !m->IsStatic()) {
Elliott Hughesd07986f2011-12-06 18:27:45 -08001286 uint16_t reg = DemangleSlot(0, f);
Elliott Hughes86b00102011-12-05 17:54:26 -08001287 o = reinterpret_cast<Object*>(f.GetVReg(m, reg));
1288 }
1289 *pThisId = gRegistry->Add(o);
1290 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001291}
1292
Elliott Hughescccd84f2011-12-05 16:51:54 -08001293void 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 -08001294 Method** sp = reinterpret_cast<Method**>(frameId);
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001295 Frame f;
1296 f.SetSP(sp);
1297 uint16_t reg = DemangleSlot(slot, f);
1298 Method* m = f.GetMethod();
1299
1300 const VmapTable vmap_table(m->GetVmapTableRaw());
1301 uint32_t vmap_offset;
1302 if (vmap_table.IsInContext(reg, vmap_offset)) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001303 UNIMPLEMENTED(FATAL) << "Don't know how to pull locals from callee save frames: " << vmap_offset;
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001304 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001305
1306 switch (tag) {
1307 case JDWP::JT_BOOLEAN:
1308 {
Elliott Hughescccd84f2011-12-05 16:51:54 -08001309 CHECK_EQ(width, 1U);
Elliott Hughes1bba14f2011-12-01 18:00:36 -08001310 uint32_t intVal = f.GetVReg(m, reg);
1311 LOG(VERBOSE) << "get boolean local " << reg << " = " << intVal;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001312 JDWP::Set1(buf+1, intVal != 0);
1313 }
1314 break;
1315 case JDWP::JT_BYTE:
1316 {
Elliott Hughescccd84f2011-12-05 16:51:54 -08001317 CHECK_EQ(width, 1U);
Elliott Hughes1bba14f2011-12-01 18:00:36 -08001318 uint32_t intVal = f.GetVReg(m, reg);
1319 LOG(VERBOSE) << "get byte local " << reg << " = " << intVal;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001320 JDWP::Set1(buf+1, intVal);
1321 }
1322 break;
1323 case JDWP::JT_SHORT:
1324 case JDWP::JT_CHAR:
1325 {
Elliott Hughescccd84f2011-12-05 16:51:54 -08001326 CHECK_EQ(width, 2U);
Elliott Hughes1bba14f2011-12-01 18:00:36 -08001327 uint32_t intVal = f.GetVReg(m, reg);
1328 LOG(VERBOSE) << "get short/char local " << reg << " = " << intVal;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001329 JDWP::Set2BE(buf+1, intVal);
1330 }
1331 break;
1332 case JDWP::JT_INT:
1333 case JDWP::JT_FLOAT:
1334 {
Elliott Hughescccd84f2011-12-05 16:51:54 -08001335 CHECK_EQ(width, 4U);
Elliott Hughes1bba14f2011-12-01 18:00:36 -08001336 uint32_t intVal = f.GetVReg(m, reg);
1337 LOG(VERBOSE) << "get int/float local " << reg << " = " << intVal;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001338 JDWP::Set4BE(buf+1, intVal);
1339 }
1340 break;
1341 case JDWP::JT_ARRAY:
1342 {
Elliott Hughescccd84f2011-12-05 16:51:54 -08001343 CHECK_EQ(width, sizeof(JDWP::ObjectId));
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001344 Object* o = reinterpret_cast<Object*>(f.GetVReg(m, reg));
Elliott Hughes1bba14f2011-12-01 18:00:36 -08001345 LOG(VERBOSE) << "get array local " << reg << " = " << o;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001346 if (o != NULL && !Heap::IsHeapAddress(o)) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001347 LOG(FATAL) << "Register " << reg << " expected to hold array: " << o;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001348 }
1349 JDWP::SetObjectId(buf+1, gRegistry->Add(o));
1350 }
1351 break;
1352 case JDWP::JT_OBJECT:
1353 {
Elliott Hughescccd84f2011-12-05 16:51:54 -08001354 CHECK_EQ(width, sizeof(JDWP::ObjectId));
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001355 Object* o = reinterpret_cast<Object*>(f.GetVReg(m, reg));
Elliott Hughes1bba14f2011-12-01 18:00:36 -08001356 LOG(VERBOSE) << "get object local " << reg << " = " << o;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001357 if (o != NULL && !Heap::IsHeapAddress(o)) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001358 LOG(FATAL) << "Register " << reg << " expected to hold object: " << o;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001359 }
1360 tag = TagFromObject(o);
1361 JDWP::SetObjectId(buf+1, gRegistry->Add(o));
1362 }
1363 break;
1364 case JDWP::JT_DOUBLE:
1365 case JDWP::JT_LONG:
1366 {
Elliott Hughescccd84f2011-12-05 16:51:54 -08001367 CHECK_EQ(width, 8U);
Elliott Hughes1bba14f2011-12-01 18:00:36 -08001368 uint32_t lo = f.GetVReg(m, reg);
1369 uint64_t hi = f.GetVReg(m, reg + 1);
1370 uint64_t longVal = (hi << 32) | lo;
1371 LOG(VERBOSE) << "get double/long local " << hi << ":" << lo << " = " << longVal;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001372 JDWP::Set8BE(buf+1, longVal);
1373 }
1374 break;
1375 default:
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001376 LOG(FATAL) << "Unknown tag " << tag;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001377 break;
1378 }
1379
1380 // Prepend tag, which may have been updated.
1381 JDWP::Set1(buf, tag);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001382}
1383
Elliott Hughesdbb40792011-11-18 17:05:22 -08001384void 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 -08001385 Method** sp = reinterpret_cast<Method**>(frameId);
1386 Frame f;
1387 f.SetSP(sp);
1388 uint16_t reg = DemangleSlot(slot, f);
1389 Method* m = f.GetMethod();
1390
1391 const VmapTable vmap_table(m->GetVmapTableRaw());
1392 uint32_t vmap_offset;
1393 if (vmap_table.IsInContext(reg, vmap_offset)) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001394 UNIMPLEMENTED(FATAL) << "Don't know how to pull locals from callee save frames: " << vmap_offset;
Elliott Hughescccd84f2011-12-05 16:51:54 -08001395 }
1396
1397 switch (tag) {
1398 case JDWP::JT_BOOLEAN:
1399 case JDWP::JT_BYTE:
1400 CHECK_EQ(width, 1U);
1401 f.SetVReg(m, reg, static_cast<uint32_t>(value));
1402 break;
1403 case JDWP::JT_SHORT:
1404 case JDWP::JT_CHAR:
1405 CHECK_EQ(width, 2U);
1406 f.SetVReg(m, reg, static_cast<uint32_t>(value));
1407 break;
1408 case JDWP::JT_INT:
1409 case JDWP::JT_FLOAT:
1410 CHECK_EQ(width, 4U);
1411 f.SetVReg(m, reg, static_cast<uint32_t>(value));
1412 break;
1413 case JDWP::JT_ARRAY:
1414 case JDWP::JT_OBJECT:
1415 case JDWP::JT_STRING:
1416 {
1417 CHECK_EQ(width, sizeof(JDWP::ObjectId));
1418 Object* o = gRegistry->Get<Object*>(static_cast<JDWP::ObjectId>(value));
1419 f.SetVReg(m, reg, static_cast<uint32_t>(reinterpret_cast<uintptr_t>(o)));
1420 }
1421 break;
1422 case JDWP::JT_DOUBLE:
1423 case JDWP::JT_LONG:
1424 CHECK_EQ(width, 8U);
1425 f.SetVReg(m, reg, static_cast<uint32_t>(value));
1426 f.SetVReg(m, reg + 1, static_cast<uint32_t>(value >> 32));
1427 break;
1428 default:
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001429 LOG(FATAL) << "Unknown tag " << tag;
Elliott Hughescccd84f2011-12-05 16:51:54 -08001430 break;
1431 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001432}
1433
1434void Dbg::PostLocationEvent(const Method* method, int pcOffset, Object* thisPtr, int eventFlags) {
1435 UNIMPLEMENTED(FATAL);
1436}
1437
Elliott Hughesd07986f2011-12-06 18:27:45 -08001438void Dbg::PostException(Method** sp, Method* throwMethod, uintptr_t throwNativePc, Method* catchMethod, uintptr_t catchNativePc, Object* exception) {
Ian Rogers0ad5bb82011-12-07 10:16:32 -08001439 if (!gDebuggerActive) {
1440 return;
1441 }
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001442
Elliott Hughesd07986f2011-12-06 18:27:45 -08001443 JDWP::JdwpLocation throw_location;
1444 SetLocation(throw_location, throwMethod, throwNativePc);
1445 JDWP::JdwpLocation catch_location;
1446 SetLocation(catch_location, catchMethod, catchNativePc);
1447
1448 // We need 'this' for InstanceOnly filters.
1449 JDWP::ObjectId this_id;
1450 GetThisObject(reinterpret_cast<JDWP::FrameId>(sp), &this_id);
1451
1452 /*
1453 * Hand the event to the JDWP exception handler. Note we're using the
1454 * "NoReg" objectID on the exception, which is not strictly correct --
1455 * the exception object WILL be passed up to the debugger if the
1456 * debugger is interested in the event. We do this because the current
1457 * implementation of the debugger object registry never throws anything
1458 * away, and some people were experiencing a fatal build up of exception
1459 * objects when dealing with certain libraries.
1460 */
1461 JDWP::ObjectId exception_id = static_cast<JDWP::ObjectId>(reinterpret_cast<uintptr_t>(exception));
1462 JDWP::RefTypeId exception_class_id = gRegistry->Add(exception->GetClass());
1463
1464 gJdwpState->PostException(&throw_location, exception_id, exception_class_id, &catch_location, this_id);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001465}
1466
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001467void Dbg::PostClassPrepare(Class* c) {
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001468 if (!gDebuggerActive) {
1469 return;
1470 }
1471
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001472 // OLD-TODO - we currently always send both "verified" and "prepared" since
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001473 // debuggers seem to like that. There might be some advantage to honesty,
1474 // since the class may not yet be verified.
1475 int state = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
1476 JDWP::JdwpTypeTag tag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
1477 gJdwpState->PostClassPrepare(tag, gRegistry->Add(c), ClassHelper(c).GetDescriptor(), state);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001478}
1479
1480bool Dbg::WatchLocation(const JDWP::JdwpLocation* pLoc) {
1481 UNIMPLEMENTED(FATAL);
1482 return false;
1483}
1484
1485void Dbg::UnwatchLocation(const JDWP::JdwpLocation* pLoc) {
1486 UNIMPLEMENTED(FATAL);
1487}
1488
1489bool Dbg::ConfigureStep(JDWP::ObjectId threadId, JDWP::JdwpStepSize size, JDWP::JdwpStepDepth depth) {
1490 UNIMPLEMENTED(FATAL);
1491 return false;
1492}
1493
1494void Dbg::UnconfigureStep(JDWP::ObjectId threadId) {
1495 UNIMPLEMENTED(FATAL);
1496}
1497
Elliott Hughesd07986f2011-12-06 18:27:45 -08001498JDWP::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) {
1499 ThreadList* thread_list = Runtime::Current()->GetThreadList();
1500
1501 Thread* targetThread = NULL;
1502 DebugInvokeReq* req = NULL;
1503 {
1504 ScopedThreadListLock thread_list_lock;
1505 targetThread = DecodeThread(threadId);
1506 if (targetThread == NULL) {
1507 LOG(ERROR) << "InvokeMethod request for non-existent thread " << threadId;
1508 return JDWP::ERR_INVALID_THREAD;
1509 }
1510 req = targetThread->GetInvokeReq();
1511 if (!req->ready) {
1512 LOG(ERROR) << "InvokeMethod request for thread not stopped by event: " << *targetThread;
1513 return JDWP::ERR_INVALID_THREAD;
1514 }
1515
1516 /*
1517 * We currently have a bug where we don't successfully resume the
1518 * target thread if the suspend count is too deep. We're expected to
1519 * require one "resume" for each "suspend", but when asked to execute
1520 * a method we have to resume fully and then re-suspend it back to the
1521 * same level. (The easiest way to cause this is to type "suspend"
1522 * multiple times in jdb.)
1523 *
1524 * It's unclear what this means when the event specifies "resume all"
1525 * and some threads are suspended more deeply than others. This is
1526 * a rare problem, so for now we just prevent it from hanging forever
1527 * by rejecting the method invocation request. Without this, we will
1528 * be stuck waiting on a suspended thread.
1529 */
1530 int suspend_count = targetThread->GetSuspendCount();
1531 if (suspend_count > 1) {
1532 LOG(ERROR) << *targetThread << " suspend count too deep for method invocation: " << suspend_count;
1533 return JDWP::ERR_THREAD_SUSPENDED; // Probably not expected here.
1534 }
1535
1536 /*
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001537 * OLD-TODO: ought to screen the various IDs, and verify that the argument
Elliott Hughesd07986f2011-12-06 18:27:45 -08001538 * list is valid.
1539 */
1540 req->receiver_ = gRegistry->Get<Object*>(objectId);
1541 req->thread_ = gRegistry->Get<Object*>(threadId);
1542 req->class_ = gRegistry->Get<Class*>(classId);
1543 req->method_ = FromMethodId(methodId);
1544 req->num_args_ = numArgs;
1545 req->arg_array_ = argArray;
1546 req->options_ = options;
1547 req->invoke_needed_ = true;
1548 }
1549
1550 // The fact that we've released the thread list lock is a bit risky --- if the thread goes
1551 // away we're sitting high and dry -- but we must release this before the ResumeAllThreads
1552 // call, and it's unwise to hold it during WaitForSuspend.
1553
1554 {
1555 /*
1556 * We change our (JDWP thread) status, which should be THREAD_RUNNING,
1557 * so the VM can suspend for a GC if the invoke request causes us to
1558 * run out of memory. It's also a good idea to change it before locking
1559 * the invokeReq mutex, although that should never be held for long.
1560 */
1561 ScopedThreadStateChange tsc(Thread::Current(), Thread::kVmWait);
1562
1563 LOG(VERBOSE) << " Transferring control to event thread";
1564 {
1565 MutexLock mu(req->lock_);
1566
1567 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
1568 LOG(VERBOSE) << " Resuming all threads";
1569 thread_list->ResumeAll(true);
1570 } else {
1571 LOG(VERBOSE) << " Resuming event thread only";
1572 thread_list->Resume(targetThread, true);
1573 }
1574
1575 // Wait for the request to finish executing.
1576 while (req->invoke_needed_) {
1577 req->cond_.Wait(req->lock_);
1578 }
1579 }
1580 LOG(VERBOSE) << " Control has returned from event thread";
1581
1582 /* wait for thread to re-suspend itself */
1583 targetThread->WaitUntilSuspended();
1584 //dvmWaitForSuspend(targetThread);
1585 }
1586
1587 /*
1588 * Suspend the threads. We waited for the target thread to suspend
1589 * itself, so all we need to do is suspend the others.
1590 *
1591 * The suspendAllThreads() call will double-suspend the event thread,
1592 * so we want to resume the target thread once to keep the books straight.
1593 */
1594 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
1595 LOG(VERBOSE) << " Suspending all threads";
1596 thread_list->SuspendAll(true);
1597 LOG(VERBOSE) << " Resuming event thread to balance the count";
1598 thread_list->Resume(targetThread, true);
1599 }
1600
1601 // Copy the result.
1602 *pResultTag = req->result_tag;
1603 if (IsPrimitiveTag(req->result_tag)) {
1604 *pResultValue = req->result_value.j;
1605 } else {
1606 *pResultValue = gRegistry->Add(req->result_value.l);
1607 }
1608 *pExceptionId = req->exception;
1609 return req->error;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001610}
1611
1612void Dbg::ExecuteMethod(DebugInvokeReq* pReq) {
Elliott Hughesd07986f2011-12-06 18:27:45 -08001613 Thread* self = Thread::Current();
1614
1615 // We can be called while an exception is pending in the VM. We need
1616 // to preserve that across the method invocation.
1617 SirtRef<Throwable> old_exception(self->GetException());
1618 self->ClearException();
1619
1620 ScopedThreadStateChange tsc(self, Thread::kRunnable);
1621
1622 // Translate the method through the vtable, unless the debugger wants to suppress it.
1623 Method* m = pReq->method_;
1624 if ((pReq->options_ & JDWP::INVOKE_NONVIRTUAL) == 0 && pReq->receiver_ != NULL) {
1625 m = pReq->class_->FindVirtualMethodForVirtualOrInterface(pReq->method_);
1626 }
1627 CHECK(m != NULL);
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001628 LOG(VERBOSE) << "ExecuteMethod " << PrettyMethod(m);
Elliott Hughesd07986f2011-12-06 18:27:45 -08001629
1630 CHECK_EQ(sizeof(jvalue), sizeof(uint64_t));
1631
1632 pReq->result_value = InvokeWithJValues(self, pReq->receiver_, m, reinterpret_cast<JValue*>(pReq->arg_array_));
1633
1634 pReq->exception = gRegistry->Add(self->GetException());
1635 pReq->result_tag = BasicTagFromDescriptor(MethodHelper(m).GetShorty());
1636 if (pReq->exception != 0) {
1637 Object* exc = self->GetException();
1638 LOG(VERBOSE) << " JDWP invocation returning with exception=" << exc << " " << PrettyTypeOf(exc);
1639 self->ClearException();
1640 pReq->result_value.j = 0;
1641 } else if (pReq->result_tag == JDWP::JT_OBJECT) {
1642 /* if no exception thrown, examine object result more closely */
1643 JDWP::JdwpTag new_tag = TagFromObject(pReq->result_value.l);
1644 if (new_tag != pReq->result_tag) {
1645 LOG(VERBOSE) << " JDWP promoted result from " << pReq->result_tag << " to " << new_tag;
1646 pReq->result_tag = new_tag;
1647 }
1648
1649 /*
1650 * Register the object. We don't actually need an ObjectId yet,
1651 * but we do need to be sure that the GC won't move or discard the
1652 * object when we switch out of RUNNING. The ObjectId conversion
1653 * will add the object to the "do not touch" list.
1654 *
1655 * We can't use the "tracked allocation" mechanism here because
1656 * the object is going to be handed off to a different thread.
1657 */
1658 gRegistry->Add(pReq->result_value.l);
1659 }
1660
1661 if (old_exception.get() != NULL) {
1662 self->SetException(old_exception.get());
1663 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001664}
1665
Elliott Hughesd07986f2011-12-06 18:27:45 -08001666/*
1667 * Register an object ID that might not have been registered previously.
1668 *
1669 * Normally this wouldn't happen -- the conversion to an ObjectId would
1670 * have added the object to the registry -- but in some cases (e.g.
1671 * throwing exceptions) we really want to do the registration late.
1672 */
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001673void Dbg::RegisterObjectId(JDWP::ObjectId id) {
Elliott Hughesd07986f2011-12-06 18:27:45 -08001674 gRegistry->Add(reinterpret_cast<Object*>(id));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001675}
1676
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001677/*
1678 * "buf" contains a full JDWP packet, possibly with multiple chunks. We
1679 * need to process each, accumulate the replies, and ship the whole thing
1680 * back.
1681 *
1682 * Returns "true" if we have a reply. The reply buffer is newly allocated,
1683 * and includes the chunk type/length, followed by the data.
1684 *
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001685 * OLD-TODO: we currently assume that the request and reply include a single
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001686 * chunk. If this becomes inconvenient we will need to adapt.
1687 */
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001688bool Dbg::DdmHandlePacket(const uint8_t* buf, int dataLen, uint8_t** pReplyBuf, int* pReplyLen) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001689 CHECK_GE(dataLen, 0);
1690
1691 Thread* self = Thread::Current();
1692 JNIEnv* env = self->GetJniEnv();
1693
1694 static jclass Chunk_class = env->FindClass("org/apache/harmony/dalvik/ddmc/Chunk");
1695 static jclass DdmServer_class = env->FindClass("org/apache/harmony/dalvik/ddmc/DdmServer");
1696 static jmethodID dispatch_mid = env->GetStaticMethodID(DdmServer_class, "dispatch",
1697 "(I[BII)Lorg/apache/harmony/dalvik/ddmc/Chunk;");
1698 static jfieldID data_fid = env->GetFieldID(Chunk_class, "data", "[B");
1699 static jfieldID length_fid = env->GetFieldID(Chunk_class, "length", "I");
1700 static jfieldID offset_fid = env->GetFieldID(Chunk_class, "offset", "I");
1701 static jfieldID type_fid = env->GetFieldID(Chunk_class, "type", "I");
1702
1703 // Create a byte[] corresponding to 'buf'.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001704 ScopedLocalRef<jbyteArray> dataArray(env, env->NewByteArray(dataLen));
1705 if (dataArray.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001706 LOG(WARNING) << "byte[] allocation failed: " << dataLen;
1707 env->ExceptionClear();
1708 return false;
1709 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001710 env->SetByteArrayRegion(dataArray.get(), 0, dataLen, reinterpret_cast<const jbyte*>(buf));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001711
1712 const int kChunkHdrLen = 8;
1713
1714 // Run through and find all chunks. [Currently just find the first.]
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001715 ScopedByteArrayRO contents(env, dataArray.get());
Elliott Hughesf7c3b662011-10-27 12:04:56 -07001716 jint type = JDWP::Get4BE(reinterpret_cast<const uint8_t*>(&contents[0]));
1717 jint length = JDWP::Get4BE(reinterpret_cast<const uint8_t*>(&contents[4]));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001718 jint offset = kChunkHdrLen;
1719 if (offset + length > dataLen) {
1720 LOG(WARNING) << StringPrintf("bad chunk found (len=%u pktLen=%d)", length, dataLen);
1721 return false;
1722 }
1723
1724 // Call "private static Chunk dispatch(int type, byte[] data, int offset, int length)".
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001725 ScopedLocalRef<jobject> chunk(env, env->CallStaticObjectMethod(DdmServer_class, dispatch_mid, type, dataArray.get(), offset, length));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001726 if (env->ExceptionCheck()) {
1727 LOG(INFO) << StringPrintf("Exception thrown by dispatcher for 0x%08x", type);
1728 env->ExceptionDescribe();
1729 env->ExceptionClear();
1730 return false;
1731 }
1732
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001733 if (chunk.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001734 return false;
1735 }
1736
1737 /*
1738 * Pull the pieces out of the chunk. We copy the results into a
1739 * newly-allocated buffer that the caller can free. We don't want to
1740 * continue using the Chunk object because nothing has a reference to it.
1741 *
1742 * We could avoid this by returning type/data/offset/length and having
1743 * the caller be aware of the object lifetime issues, but that
1744 * integrates the JDWP code more tightly into the VM, and doesn't work
1745 * if we have responses for multiple chunks.
1746 *
1747 * So we're pretty much stuck with copying data around multiple times.
1748 */
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001749 ScopedLocalRef<jbyteArray> replyData(env, reinterpret_cast<jbyteArray>(env->GetObjectField(chunk.get(), data_fid)));
1750 length = env->GetIntField(chunk.get(), length_fid);
1751 offset = env->GetIntField(chunk.get(), offset_fid);
1752 type = env->GetIntField(chunk.get(), type_fid);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001753
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001754 LOG(VERBOSE) << StringPrintf("DDM reply: type=0x%08x data=%p offset=%d length=%d", type, replyData.get(), offset, length);
1755 if (length == 0 || replyData.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001756 return false;
1757 }
1758
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001759 jsize replyLength = env->GetArrayLength(replyData.get());
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001760 if (offset + length > replyLength) {
1761 LOG(WARNING) << StringPrintf("chunk off=%d len=%d exceeds reply array len %d", offset, length, replyLength);
1762 return false;
1763 }
1764
1765 uint8_t* reply = new uint8_t[length + kChunkHdrLen];
1766 if (reply == NULL) {
1767 LOG(WARNING) << "malloc failed: " << (length + kChunkHdrLen);
1768 return false;
1769 }
Elliott Hughesf7c3b662011-10-27 12:04:56 -07001770 JDWP::Set4BE(reply + 0, type);
1771 JDWP::Set4BE(reply + 4, length);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001772 env->GetByteArrayRegion(replyData.get(), offset, length, reinterpret_cast<jbyte*>(reply + kChunkHdrLen));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001773
1774 *pReplyBuf = reply;
1775 *pReplyLen = length + kChunkHdrLen;
1776
1777 LOG(VERBOSE) << StringPrintf("dvmHandleDdm returning type=%.4s buf=%p len=%d", (char*) reply, reply, length);
1778 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001779}
1780
Elliott Hughesa2155262011-11-16 16:26:58 -08001781void Dbg::DdmBroadcast(bool connect) {
Elliott Hughes47fce012011-10-25 18:37:19 -07001782 LOG(VERBOSE) << "Broadcasting DDM " << (connect ? "connect" : "disconnect") << "...";
1783
1784 Thread* self = Thread::Current();
1785 if (self->GetState() != Thread::kRunnable) {
1786 LOG(ERROR) << "DDM broadcast in thread state " << self->GetState();
1787 /* try anyway? */
1788 }
1789
1790 JNIEnv* env = self->GetJniEnv();
1791 static jclass DdmServer_class = env->FindClass("org/apache/harmony/dalvik/ddmc/DdmServer");
1792 static jmethodID broadcast_mid = env->GetStaticMethodID(DdmServer_class, "broadcast", "(I)V");
1793 jint event = connect ? 1 /*DdmServer.CONNECTED*/ : 2 /*DdmServer.DISCONNECTED*/;
1794 env->CallStaticVoidMethod(DdmServer_class, broadcast_mid, event);
1795 if (env->ExceptionCheck()) {
1796 LOG(ERROR) << "DdmServer.broadcast " << event << " failed";
1797 env->ExceptionDescribe();
1798 env->ExceptionClear();
1799 }
1800}
1801
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001802void Dbg::DdmConnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08001803 Dbg::DdmBroadcast(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001804}
1805
1806void Dbg::DdmDisconnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08001807 Dbg::DdmBroadcast(false);
Elliott Hughes47fce012011-10-25 18:37:19 -07001808 gDdmThreadNotification = false;
1809}
1810
1811/*
Elliott Hughes82188472011-11-07 18:11:48 -08001812 * Send a notification when a thread starts, stops, or changes its name.
Elliott Hughes47fce012011-10-25 18:37:19 -07001813 *
1814 * Because we broadcast the full set of threads when the notifications are
1815 * first enabled, it's possible for "thread" to be actively executing.
1816 */
Elliott Hughes82188472011-11-07 18:11:48 -08001817void Dbg::DdmSendThreadNotification(Thread* t, uint32_t type) {
Elliott Hughes47fce012011-10-25 18:37:19 -07001818 if (!gDdmThreadNotification) {
1819 return;
1820 }
1821
Elliott Hughes82188472011-11-07 18:11:48 -08001822 if (type == CHUNK_TYPE("THDE")) {
Elliott Hughes47fce012011-10-25 18:37:19 -07001823 uint8_t buf[4];
Elliott Hughesf7c3b662011-10-27 12:04:56 -07001824 JDWP::Set4BE(&buf[0], t->GetThinLockId());
Elliott Hughes47fce012011-10-25 18:37:19 -07001825 Dbg::DdmSendChunk(CHUNK_TYPE("THDE"), 4, buf);
Elliott Hughes82188472011-11-07 18:11:48 -08001826 } else {
1827 CHECK(type == CHUNK_TYPE("THCR") || type == CHUNK_TYPE("THNM")) << type;
1828 SirtRef<String> name(t->GetName());
1829 size_t char_count = (name.get() != NULL) ? name->GetLength() : 0;
1830 const jchar* chars = name->GetCharArray()->GetData();
1831
Elliott Hughes21f32d72011-11-09 17:44:13 -08001832 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08001833 JDWP::Append4BE(bytes, t->GetThinLockId());
1834 JDWP::AppendUtf16BE(bytes, chars, char_count);
Elliott Hughes21f32d72011-11-09 17:44:13 -08001835 CHECK_EQ(bytes.size(), char_count*2 + sizeof(uint32_t)*2);
1836 Dbg::DdmSendChunk(type, bytes);
Elliott Hughes47fce012011-10-25 18:37:19 -07001837 }
1838}
1839
Elliott Hughesa2155262011-11-16 16:26:58 -08001840static void DdmSendThreadStartCallback(Thread* t, void*) {
Elliott Hughes82188472011-11-07 18:11:48 -08001841 Dbg::DdmSendThreadNotification(t, CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07001842}
1843
1844void Dbg::DdmSetThreadNotification(bool enable) {
1845 // We lock the thread list to avoid sending duplicate events or missing
1846 // a thread change. We should be okay holding this lock while sending
1847 // the messages out. (We have to hold it while accessing a live thread.)
Elliott Hughesbbd9d832011-11-07 14:40:00 -08001848 ScopedThreadListLock thread_list_lock;
Elliott Hughes47fce012011-10-25 18:37:19 -07001849
1850 gDdmThreadNotification = enable;
1851 if (enable) {
Elliott Hughesbfe487b2011-10-26 15:48:55 -07001852 Runtime::Current()->GetThreadList()->ForEach(DdmSendThreadStartCallback, NULL);
Elliott Hughes47fce012011-10-25 18:37:19 -07001853 }
1854}
1855
Elliott Hughesa2155262011-11-16 16:26:58 -08001856void Dbg::PostThreadStartOrStop(Thread* t, uint32_t type) {
Elliott Hughes47fce012011-10-25 18:37:19 -07001857 if (gDebuggerActive) {
1858 JDWP::ObjectId id = gRegistry->Add(t->GetPeer());
Elliott Hughes82188472011-11-07 18:11:48 -08001859 gJdwpState->PostThreadChange(id, type == CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07001860 }
Elliott Hughes82188472011-11-07 18:11:48 -08001861 Dbg::DdmSendThreadNotification(t, type);
Elliott Hughes47fce012011-10-25 18:37:19 -07001862}
1863
1864void Dbg::PostThreadStart(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001865 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07001866}
1867
1868void Dbg::PostThreadDeath(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001869 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THDE"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001870}
1871
Elliott Hughes82188472011-11-07 18:11:48 -08001872void Dbg::DdmSendChunk(uint32_t type, size_t byte_count, const uint8_t* buf) {
Elliott Hughes3bb81562011-10-21 18:52:59 -07001873 CHECK(buf != NULL);
1874 iovec vec[1];
1875 vec[0].iov_base = reinterpret_cast<void*>(const_cast<uint8_t*>(buf));
1876 vec[0].iov_len = byte_count;
1877 Dbg::DdmSendChunkV(type, vec, 1);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001878}
1879
Elliott Hughes21f32d72011-11-09 17:44:13 -08001880void Dbg::DdmSendChunk(uint32_t type, const std::vector<uint8_t>& bytes) {
1881 DdmSendChunk(type, bytes.size(), &bytes[0]);
1882}
1883
Elliott Hughescccd84f2011-12-05 16:51:54 -08001884void Dbg::DdmSendChunkV(uint32_t type, const struct iovec* iov, int iov_count) {
Elliott Hughes3bb81562011-10-21 18:52:59 -07001885 if (gJdwpState == NULL) {
1886 LOG(VERBOSE) << "Debugger thread not active, ignoring DDM send: " << type;
1887 } else {
Elliott Hughescccd84f2011-12-05 16:51:54 -08001888 gJdwpState->DdmSendChunkV(type, iov, iov_count);
Elliott Hughes3bb81562011-10-21 18:52:59 -07001889 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001890}
1891
Elliott Hughes767a1472011-10-26 18:49:02 -07001892int Dbg::DdmHandleHpifChunk(HpifWhen when) {
1893 if (when == HPIF_WHEN_NOW) {
Elliott Hughes7162ad92011-10-27 14:08:42 -07001894 DdmSendHeapInfo(when);
Elliott Hughes767a1472011-10-26 18:49:02 -07001895 return true;
1896 }
1897
1898 if (when != HPIF_WHEN_NEVER && when != HPIF_WHEN_NEXT_GC && when != HPIF_WHEN_EVERY_GC) {
1899 LOG(ERROR) << "invalid HpifWhen value: " << static_cast<int>(when);
1900 return false;
1901 }
1902
1903 gDdmHpifWhen = when;
1904 return true;
1905}
1906
1907bool Dbg::DdmHandleHpsgNhsgChunk(Dbg::HpsgWhen when, Dbg::HpsgWhat what, bool native) {
1908 if (when != HPSG_WHEN_NEVER && when != HPSG_WHEN_EVERY_GC) {
1909 LOG(ERROR) << "invalid HpsgWhen value: " << static_cast<int>(when);
1910 return false;
1911 }
1912
1913 if (what != HPSG_WHAT_MERGED_OBJECTS && what != HPSG_WHAT_DISTINCT_OBJECTS) {
1914 LOG(ERROR) << "invalid HpsgWhat value: " << static_cast<int>(what);
1915 return false;
1916 }
1917
1918 if (native) {
1919 gDdmNhsgWhen = when;
1920 gDdmNhsgWhat = what;
1921 } else {
1922 gDdmHpsgWhen = when;
1923 gDdmHpsgWhat = what;
1924 }
1925 return true;
1926}
1927
Elliott Hughes7162ad92011-10-27 14:08:42 -07001928void Dbg::DdmSendHeapInfo(HpifWhen reason) {
1929 // If there's a one-shot 'when', reset it.
1930 if (reason == gDdmHpifWhen) {
1931 if (gDdmHpifWhen == HPIF_WHEN_NEXT_GC) {
1932 gDdmHpifWhen = HPIF_WHEN_NEVER;
1933 }
1934 }
1935
1936 /*
1937 * Chunk HPIF (client --> server)
1938 *
1939 * Heap Info. General information about the heap,
1940 * suitable for a summary display.
1941 *
1942 * [u4]: number of heaps
1943 *
1944 * For each heap:
1945 * [u4]: heap ID
1946 * [u8]: timestamp in ms since Unix epoch
1947 * [u1]: capture reason (same as 'when' value from server)
1948 * [u4]: max heap size in bytes (-Xmx)
1949 * [u4]: current heap size in bytes
1950 * [u4]: current number of bytes allocated
1951 * [u4]: current number of objects allocated
1952 */
1953 uint8_t heap_count = 1;
Elliott Hughes21f32d72011-11-09 17:44:13 -08001954 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08001955 JDWP::Append4BE(bytes, heap_count);
1956 JDWP::Append4BE(bytes, 1); // Heap id (bogus; we only have one heap).
1957 JDWP::Append8BE(bytes, MilliTime());
1958 JDWP::Append1BE(bytes, reason);
1959 JDWP::Append4BE(bytes, Heap::GetMaxMemory()); // Max allowed heap size in bytes.
1960 JDWP::Append4BE(bytes, Heap::GetTotalMemory()); // Current heap size in bytes.
1961 JDWP::Append4BE(bytes, Heap::GetBytesAllocated());
1962 JDWP::Append4BE(bytes, Heap::GetObjectsAllocated());
Elliott Hughes21f32d72011-11-09 17:44:13 -08001963 CHECK_EQ(bytes.size(), 4U + (heap_count * (4 + 8 + 1 + 4 + 4 + 4 + 4)));
1964 Dbg::DdmSendChunk(CHUNK_TYPE("HPIF"), bytes);
Elliott Hughes767a1472011-10-26 18:49:02 -07001965}
1966
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001967enum HpsgSolidity {
1968 SOLIDITY_FREE = 0,
1969 SOLIDITY_HARD = 1,
1970 SOLIDITY_SOFT = 2,
1971 SOLIDITY_WEAK = 3,
1972 SOLIDITY_PHANTOM = 4,
1973 SOLIDITY_FINALIZABLE = 5,
1974 SOLIDITY_SWEEP = 6,
1975};
1976
1977enum HpsgKind {
1978 KIND_OBJECT = 0,
1979 KIND_CLASS_OBJECT = 1,
1980 KIND_ARRAY_1 = 2,
1981 KIND_ARRAY_2 = 3,
1982 KIND_ARRAY_4 = 4,
1983 KIND_ARRAY_8 = 5,
1984 KIND_UNKNOWN = 6,
1985 KIND_NATIVE = 7,
1986};
1987
1988#define HPSG_PARTIAL (1<<7)
1989#define HPSG_STATE(solidity, kind) ((uint8_t)((((kind) & 0x7) << 3) | ((solidity) & 0x7)))
1990
1991struct HeapChunkContext {
1992 std::vector<uint8_t> buf;
1993 uint8_t* p;
1994 uint8_t* pieceLenField;
1995 size_t totalAllocationUnits;
Elliott Hughes82188472011-11-07 18:11:48 -08001996 uint32_t type;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001997 bool merge;
1998 bool needHeader;
1999
2000 // Maximum chunk size. Obtain this from the formula:
2001 // (((maximum_heap_size / ALLOCATION_UNIT_SIZE) + 255) / 256) * 2
2002 HeapChunkContext(bool merge, bool native)
2003 : buf(16384 - 16),
2004 type(0),
2005 merge(merge) {
2006 Reset();
2007 if (native) {
2008 type = CHUNK_TYPE("NHSG");
2009 } else {
2010 type = merge ? CHUNK_TYPE("HPSG") : CHUNK_TYPE("HPSO");
2011 }
2012 }
2013
2014 ~HeapChunkContext() {
2015 if (p > &buf[0]) {
2016 Flush();
2017 }
2018 }
2019
2020 void EnsureHeader(const void* chunk_ptr) {
2021 if (!needHeader) {
2022 return;
2023 }
2024
2025 // Start a new HPSx chunk.
2026 JDWP::Write4BE(&p, 1); // Heap id (bogus; we only have one heap).
2027 JDWP::Write1BE(&p, 8); // Size of allocation unit, in bytes.
2028
2029 JDWP::Write4BE(&p, reinterpret_cast<uintptr_t>(chunk_ptr)); // virtual address of segment start.
2030 JDWP::Write4BE(&p, 0); // offset of this piece (relative to the virtual address).
2031 // [u4]: length of piece, in allocation units
2032 // We won't know this until we're done, so save the offset and stuff in a dummy value.
2033 pieceLenField = p;
2034 JDWP::Write4BE(&p, 0x55555555);
2035 needHeader = false;
2036 }
2037
2038 void Flush() {
2039 // Patch the "length of piece" field.
2040 CHECK_LE(&buf[0], pieceLenField);
2041 CHECK_LE(pieceLenField, p);
2042 JDWP::Set4BE(pieceLenField, totalAllocationUnits);
2043
2044 Dbg::DdmSendChunk(type, p - &buf[0], &buf[0]);
2045 Reset();
2046 }
2047
Elliott Hughesa2155262011-11-16 16:26:58 -08002048 static void HeapChunkCallback(const void* chunk_ptr, size_t chunk_len, const void* user_ptr, size_t user_len, void* arg) {
2049 reinterpret_cast<HeapChunkContext*>(arg)->HeapChunkCallback(chunk_ptr, chunk_len, user_ptr, user_len);
2050 }
2051
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002052 private:
Elliott Hughesa2155262011-11-16 16:26:58 -08002053 enum { ALLOCATION_UNIT_SIZE = 8 };
2054
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002055 void Reset() {
2056 p = &buf[0];
2057 totalAllocationUnits = 0;
2058 needHeader = true;
2059 pieceLenField = NULL;
2060 }
2061
Elliott Hughesa2155262011-11-16 16:26:58 -08002062 void HeapChunkCallback(const void* chunk_ptr, size_t chunk_len, const void* user_ptr, size_t user_len) {
2063 CHECK_EQ((chunk_len & (ALLOCATION_UNIT_SIZE-1)), 0U);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002064
Elliott Hughesa2155262011-11-16 16:26:58 -08002065 /* Make sure there's enough room left in the buffer.
2066 * We need to use two bytes for every fractional 256
2067 * allocation units used by the chunk.
2068 */
2069 {
2070 size_t needed = (((chunk_len/ALLOCATION_UNIT_SIZE + 255) / 256) * 2);
2071 size_t bytesLeft = buf.size() - (size_t)(p - &buf[0]);
2072 if (bytesLeft < needed) {
2073 Flush();
2074 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002075
Elliott Hughesa2155262011-11-16 16:26:58 -08002076 bytesLeft = buf.size() - (size_t)(p - &buf[0]);
2077 if (bytesLeft < needed) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08002078 LOG(WARNING) << "Chunk is too big to transmit (chunk_len=" << chunk_len << ", " << needed << " bytes)";
Elliott Hughesa2155262011-11-16 16:26:58 -08002079 return;
2080 }
2081 }
2082
2083 // OLD-TODO: notice when there's a gap and start a new heap, or at least a new range.
2084 EnsureHeader(chunk_ptr);
2085
2086 // Determine the type of this chunk.
2087 // OLD-TODO: if context.merge, see if this chunk is different from the last chunk.
2088 // If it's the same, we should combine them.
2089 uint8_t state = ExamineObject(reinterpret_cast<const Object*>(user_ptr), (type == CHUNK_TYPE("NHSG")));
2090
2091 // Write out the chunk description.
2092 chunk_len /= ALLOCATION_UNIT_SIZE; // convert to allocation units
2093 totalAllocationUnits += chunk_len;
2094 while (chunk_len > 256) {
2095 *p++ = state | HPSG_PARTIAL;
2096 *p++ = 255; // length - 1
2097 chunk_len -= 256;
2098 }
2099 *p++ = state;
2100 *p++ = chunk_len - 1;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002101 }
2102
Elliott Hughesa2155262011-11-16 16:26:58 -08002103 uint8_t ExamineObject(const Object* o, bool is_native_heap) {
2104 if (o == NULL) {
2105 return HPSG_STATE(SOLIDITY_FREE, 0);
2106 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002107
Elliott Hughesa2155262011-11-16 16:26:58 -08002108 // It's an allocated chunk. Figure out what it is.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002109
Elliott Hughesa2155262011-11-16 16:26:58 -08002110 // If we're looking at the native heap, we'll just return
2111 // (SOLIDITY_HARD, KIND_NATIVE) for all allocated chunks.
2112 if (is_native_heap || !Heap::IsLiveObjectLocked(o)) {
2113 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
2114 }
2115
2116 Class* c = o->GetClass();
2117 if (c == NULL) {
2118 // The object was probably just created but hasn't been initialized yet.
2119 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
2120 }
2121
2122 if (!Heap::IsHeapAddress(c)) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08002123 LOG(WARNING) << "Invalid class for managed heap object: " << o << " " << c;
Elliott Hughesa2155262011-11-16 16:26:58 -08002124 return HPSG_STATE(SOLIDITY_HARD, KIND_UNKNOWN);
2125 }
2126
2127 if (c->IsClassClass()) {
2128 return HPSG_STATE(SOLIDITY_HARD, KIND_CLASS_OBJECT);
2129 }
2130
2131 if (c->IsArrayClass()) {
2132 if (o->IsObjectArray()) {
2133 return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
2134 }
2135 switch (c->GetComponentSize()) {
2136 case 1: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_1);
2137 case 2: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_2);
2138 case 4: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
2139 case 8: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_8);
2140 }
2141 }
2142
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002143 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
2144 }
2145
Elliott Hughesa2155262011-11-16 16:26:58 -08002146 DISALLOW_COPY_AND_ASSIGN(HeapChunkContext);
2147};
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002148
2149void Dbg::DdmSendHeapSegments(bool native) {
2150 Dbg::HpsgWhen when;
2151 Dbg::HpsgWhat what;
2152 if (!native) {
2153 when = gDdmHpsgWhen;
2154 what = gDdmHpsgWhat;
2155 } else {
2156 when = gDdmNhsgWhen;
2157 what = gDdmNhsgWhat;
2158 }
2159 if (when == HPSG_WHEN_NEVER) {
2160 return;
2161 }
2162
2163 // Figure out what kind of chunks we'll be sending.
2164 CHECK(what == HPSG_WHAT_MERGED_OBJECTS || what == HPSG_WHAT_DISTINCT_OBJECTS) << static_cast<int>(what);
2165
2166 // First, send a heap start chunk.
2167 uint8_t heap_id[4];
2168 JDWP::Set4BE(&heap_id[0], 1); // Heap id (bogus; we only have one heap).
2169 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHST") : CHUNK_TYPE("HPST"), sizeof(heap_id), heap_id);
2170
2171 // Send a series of heap segment chunks.
Elliott Hughesa2155262011-11-16 16:26:58 -08002172 HeapChunkContext context((what == HPSG_WHAT_MERGED_OBJECTS), native);
2173 if (native) {
2174 dlmalloc_walk_heap(HeapChunkContext::HeapChunkCallback, &context);
2175 } else {
2176 Heap::WalkHeap(HeapChunkContext::HeapChunkCallback, &context);
2177 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002178
2179 // Finally, send a heap end chunk.
2180 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHEN") : CHUNK_TYPE("HPEN"), sizeof(heap_id), heap_id);
Elliott Hughes767a1472011-10-26 18:49:02 -07002181}
2182
Elliott Hughes545a0642011-11-08 19:10:03 -08002183void Dbg::SetAllocTrackingEnabled(bool enabled) {
2184 MutexLock mu(gAllocTrackerLock);
2185 if (enabled) {
2186 if (recent_allocation_records_ == NULL) {
2187 LOG(INFO) << "Enabling alloc tracker (" << kNumAllocRecords << " entries, "
2188 << kMaxAllocRecordStackDepth << " frames --> "
2189 << (sizeof(AllocRecord) * kNumAllocRecords) << " bytes)";
2190 gAllocRecordHead = gAllocRecordCount = 0;
2191 recent_allocation_records_ = new AllocRecord[kNumAllocRecords];
2192 CHECK(recent_allocation_records_ != NULL);
2193 }
2194 } else {
2195 delete[] recent_allocation_records_;
2196 recent_allocation_records_ = NULL;
2197 }
2198}
2199
2200struct AllocRecordStackVisitor : public Thread::StackVisitor {
2201 AllocRecordStackVisitor(AllocRecord* record) : record(record), depth(0) {
2202 }
2203
2204 virtual void VisitFrame(const Frame& f, uintptr_t pc) {
2205 if (depth >= kMaxAllocRecordStackDepth) {
2206 return;
2207 }
2208 Method* m = f.GetMethod();
2209 if (m == NULL || m->IsCalleeSaveMethod()) {
2210 return;
2211 }
2212 record->stack[depth].method = m;
2213 record->stack[depth].raw_pc = pc;
2214 ++depth;
2215 }
2216
2217 ~AllocRecordStackVisitor() {
2218 // Clear out any unused stack trace elements.
2219 for (; depth < kMaxAllocRecordStackDepth; ++depth) {
2220 record->stack[depth].method = NULL;
2221 record->stack[depth].raw_pc = 0;
2222 }
2223 }
2224
2225 AllocRecord* record;
2226 size_t depth;
2227};
2228
2229void Dbg::RecordAllocation(Class* type, size_t byte_count) {
2230 Thread* self = Thread::Current();
2231 CHECK(self != NULL);
2232
2233 MutexLock mu(gAllocTrackerLock);
2234 if (recent_allocation_records_ == NULL) {
2235 return;
2236 }
2237
2238 // Advance and clip.
2239 if (++gAllocRecordHead == kNumAllocRecords) {
2240 gAllocRecordHead = 0;
2241 }
2242
2243 // Fill in the basics.
2244 AllocRecord* record = &recent_allocation_records_[gAllocRecordHead];
2245 record->type = type;
2246 record->byte_count = byte_count;
2247 record->thin_lock_id = self->GetThinLockId();
2248
2249 // Fill in the stack trace.
2250 AllocRecordStackVisitor visitor(record);
2251 self->WalkStack(&visitor);
2252
2253 if (gAllocRecordCount < kNumAllocRecords) {
2254 ++gAllocRecordCount;
2255 }
2256}
2257
2258/*
2259 * Return the index of the head element.
2260 *
2261 * We point at the most-recently-written record, so if allocRecordCount is 1
2262 * we want to use the current element. Take "head+1" and subtract count
2263 * from it.
2264 *
2265 * We need to handle underflow in our circular buffer, so we add
2266 * kNumAllocRecords and then mask it back down.
2267 */
2268inline static int headIndex() {
2269 return (gAllocRecordHead+1 + kNumAllocRecords - gAllocRecordCount) & (kNumAllocRecords-1);
2270}
2271
2272void Dbg::DumpRecentAllocations() {
2273 MutexLock mu(gAllocTrackerLock);
2274 if (recent_allocation_records_ == NULL) {
2275 LOG(INFO) << "Not recording tracked allocations";
2276 return;
2277 }
2278
2279 // "i" is the head of the list. We want to start at the end of the
2280 // list and move forward to the tail.
2281 size_t i = headIndex();
2282 size_t count = gAllocRecordCount;
2283
2284 LOG(INFO) << "Tracked allocations, (head=" << gAllocRecordHead << " count=" << count << ")";
2285 while (count--) {
2286 AllocRecord* record = &recent_allocation_records_[i];
2287
2288 LOG(INFO) << StringPrintf(" T=%-2d %6d ", record->thin_lock_id, record->byte_count)
2289 << PrettyClass(record->type);
2290
2291 for (size_t stack_frame = 0; stack_frame < kMaxAllocRecordStackDepth; ++stack_frame) {
2292 const Method* m = record->stack[stack_frame].method;
2293 if (m == NULL) {
2294 break;
2295 }
2296 LOG(INFO) << " " << PrettyMethod(m) << " line " << record->stack[stack_frame].LineNumber();
2297 }
2298
2299 // pause periodically to help logcat catch up
2300 if ((count % 5) == 0) {
2301 usleep(40000);
2302 }
2303
2304 i = (i + 1) & (kNumAllocRecords-1);
2305 }
2306}
2307
2308class StringTable {
2309 public:
2310 StringTable() {
2311 }
2312
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002313 void Add(const char* s) {
Elliott Hughes545a0642011-11-08 19:10:03 -08002314 table_.insert(s);
2315 }
2316
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002317 size_t IndexOf(const char* s) {
Elliott Hughes545a0642011-11-08 19:10:03 -08002318 return std::distance(table_.begin(), table_.find(s));
2319 }
2320
2321 size_t Size() {
2322 return table_.size();
2323 }
2324
2325 void WriteTo(std::vector<uint8_t>& bytes) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002326 typedef std::set<const char*>::const_iterator It; // TODO: C++0x auto
Elliott Hughes545a0642011-11-08 19:10:03 -08002327 for (It it = table_.begin(); it != table_.end(); ++it) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002328 const char* s = *it;
2329 size_t s_len = CountModifiedUtf8Chars(s);
2330 UniquePtr<uint16_t> s_utf16(new uint16_t[s_len]);
2331 ConvertModifiedUtf8ToUtf16(s_utf16.get(), s);
2332 JDWP::AppendUtf16BE(bytes, s_utf16.get(), s_len);
Elliott Hughes545a0642011-11-08 19:10:03 -08002333 }
2334 }
2335
2336 private:
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002337 std::set<const char*> table_;
Elliott Hughes545a0642011-11-08 19:10:03 -08002338 DISALLOW_COPY_AND_ASSIGN(StringTable);
2339};
2340
2341/*
2342 * The data we send to DDMS contains everything we have recorded.
2343 *
2344 * Message header (all values big-endian):
2345 * (1b) message header len (to allow future expansion); includes itself
2346 * (1b) entry header len
2347 * (1b) stack frame len
2348 * (2b) number of entries
2349 * (4b) offset to string table from start of message
2350 * (2b) number of class name strings
2351 * (2b) number of method name strings
2352 * (2b) number of source file name strings
2353 * For each entry:
2354 * (4b) total allocation size
2355 * (2b) threadId
2356 * (2b) allocated object's class name index
2357 * (1b) stack depth
2358 * For each stack frame:
2359 * (2b) method's class name
2360 * (2b) method name
2361 * (2b) method source file
2362 * (2b) line number, clipped to 32767; -2 if native; -1 if no source
2363 * (xb) class name strings
2364 * (xb) method name strings
2365 * (xb) source file strings
2366 *
2367 * As with other DDM traffic, strings are sent as a 4-byte length
2368 * followed by UTF-16 data.
2369 *
2370 * We send up 16-bit unsigned indexes into string tables. In theory there
2371 * can be (kMaxAllocRecordStackDepth * kNumAllocRecords) unique strings in
2372 * each table, but in practice there should be far fewer.
2373 *
2374 * The chief reason for using a string table here is to keep the size of
2375 * the DDMS message to a minimum. This is partly to make the protocol
2376 * efficient, but also because we have to form the whole thing up all at
2377 * once in a memory buffer.
2378 *
2379 * We use separate string tables for class names, method names, and source
2380 * files to keep the indexes small. There will generally be no overlap
2381 * between the contents of these tables.
2382 */
2383jbyteArray Dbg::GetRecentAllocations() {
2384 if (false) {
2385 DumpRecentAllocations();
2386 }
2387
2388 MutexLock mu(gAllocTrackerLock);
2389
2390 /*
2391 * Part 1: generate string tables.
2392 */
2393 StringTable class_names;
2394 StringTable method_names;
2395 StringTable filenames;
2396
2397 int count = gAllocRecordCount;
2398 int idx = headIndex();
2399 while (count--) {
2400 AllocRecord* record = &recent_allocation_records_[idx];
2401
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002402 class_names.Add(ClassHelper(record->type).GetDescriptor().c_str());
Elliott Hughes545a0642011-11-08 19:10:03 -08002403
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002404 MethodHelper mh;
Elliott Hughes545a0642011-11-08 19:10:03 -08002405 for (size_t i = 0; i < kMaxAllocRecordStackDepth; i++) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002406 Method* m = record->stack[i].method;
2407 mh.ChangeMethod(m);
Elliott Hughes545a0642011-11-08 19:10:03 -08002408 if (m != NULL) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002409 class_names.Add(mh.GetDeclaringClassDescriptor());
2410 method_names.Add(mh.GetName());
2411 filenames.Add(mh.GetDeclaringClassSourceFile());
Elliott Hughes545a0642011-11-08 19:10:03 -08002412 }
2413 }
2414
2415 idx = (idx + 1) & (kNumAllocRecords-1);
2416 }
2417
2418 LOG(INFO) << "allocation records: " << gAllocRecordCount;
2419
2420 /*
2421 * Part 2: allocate a buffer and generate the output.
2422 */
2423 std::vector<uint8_t> bytes;
2424
2425 // (1b) message header len (to allow future expansion); includes itself
2426 // (1b) entry header len
2427 // (1b) stack frame len
2428 const int kMessageHeaderLen = 15;
2429 const int kEntryHeaderLen = 9;
2430 const int kStackFrameLen = 8;
2431 JDWP::Append1BE(bytes, kMessageHeaderLen);
2432 JDWP::Append1BE(bytes, kEntryHeaderLen);
2433 JDWP::Append1BE(bytes, kStackFrameLen);
2434
2435 // (2b) number of entries
2436 // (4b) offset to string table from start of message
2437 // (2b) number of class name strings
2438 // (2b) number of method name strings
2439 // (2b) number of source file name strings
2440 JDWP::Append2BE(bytes, gAllocRecordCount);
2441 size_t string_table_offset = bytes.size();
2442 JDWP::Append4BE(bytes, 0); // We'll patch this later...
2443 JDWP::Append2BE(bytes, class_names.Size());
2444 JDWP::Append2BE(bytes, method_names.Size());
2445 JDWP::Append2BE(bytes, filenames.Size());
2446
2447 count = gAllocRecordCount;
2448 idx = headIndex();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002449 ClassHelper kh;
Elliott Hughes545a0642011-11-08 19:10:03 -08002450 while (count--) {
2451 // For each entry:
2452 // (4b) total allocation size
2453 // (2b) thread id
2454 // (2b) allocated object's class name index
2455 // (1b) stack depth
2456 AllocRecord* record = &recent_allocation_records_[idx];
2457 size_t stack_depth = record->GetDepth();
2458 JDWP::Append4BE(bytes, record->byte_count);
2459 JDWP::Append2BE(bytes, record->thin_lock_id);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002460 kh.ChangeClass(record->type);
2461 JDWP::Append2BE(bytes, class_names.IndexOf(kh.GetDescriptor().c_str()));
Elliott Hughes545a0642011-11-08 19:10:03 -08002462 JDWP::Append1BE(bytes, stack_depth);
2463
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002464 MethodHelper mh;
Elliott Hughes545a0642011-11-08 19:10:03 -08002465 for (size_t stack_frame = 0; stack_frame < stack_depth; ++stack_frame) {
2466 // For each stack frame:
2467 // (2b) method's class name
2468 // (2b) method name
2469 // (2b) method source file
2470 // (2b) line number, clipped to 32767; -2 if native; -1 if no source
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002471 mh.ChangeMethod(record->stack[stack_frame].method);
2472 JDWP::Append2BE(bytes, class_names.IndexOf(mh.GetDeclaringClassDescriptor()));
2473 JDWP::Append2BE(bytes, method_names.IndexOf(mh.GetName()));
2474 JDWP::Append2BE(bytes, filenames.IndexOf(mh.GetDeclaringClassSourceFile()));
Elliott Hughes545a0642011-11-08 19:10:03 -08002475 JDWP::Append2BE(bytes, record->stack[stack_frame].LineNumber());
2476 }
2477
2478 idx = (idx + 1) & (kNumAllocRecords-1);
2479 }
2480
2481 // (xb) class name strings
2482 // (xb) method name strings
2483 // (xb) source file strings
2484 JDWP::Set4BE(&bytes[string_table_offset], bytes.size());
2485 class_names.WriteTo(bytes);
2486 method_names.WriteTo(bytes);
2487 filenames.WriteTo(bytes);
2488
2489 JNIEnv* env = Thread::Current()->GetJniEnv();
2490 jbyteArray result = env->NewByteArray(bytes.size());
2491 if (result != NULL) {
2492 env->SetByteArrayRegion(result, 0, bytes.size(), reinterpret_cast<const jbyte*>(&bytes[0]));
2493 }
2494 return result;
2495}
2496
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002497} // namespace art