blob: 4c47e00a60fb4c23c87b4514415a9871b4f16efc [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"
Ian Rogers30fab402012-01-23 15:43:46 -080029#include "space.h"
Elliott Hughes47fce012011-10-25 18:37:19 -070030#include "stack_indirect_reference_table.h"
Elliott Hughes475fc232011-10-25 15:00:35 -070031#include "thread_list.h"
32
Elliott Hughes6a5bd492011-10-28 14:33:57 -070033extern "C" void dlmalloc_walk_heap(void(*)(const void*, size_t, const void*, size_t, void*), void*);
34#ifndef HAVE_ANDROID_OS
35void dlmalloc_walk_heap(void(*)(const void*, size_t, const void*, size_t, void*), void*) {
36 // No-op for glibc.
37}
38#endif
39
Elliott Hughes872d4ec2011-10-21 17:07:15 -070040namespace art {
41
Elliott Hughes545a0642011-11-08 19:10:03 -080042static const size_t kMaxAllocRecordStackDepth = 16; // Max 255.
43static const size_t kNumAllocRecords = 512; // Must be power of 2.
44
Elliott Hughes475fc232011-10-25 15:00:35 -070045class ObjectRegistry {
46 public:
47 ObjectRegistry() : lock_("ObjectRegistry lock") {
48 }
49
50 JDWP::ObjectId Add(Object* o) {
51 if (o == NULL) {
52 return 0;
53 }
54 JDWP::ObjectId id = static_cast<JDWP::ObjectId>(reinterpret_cast<uintptr_t>(o));
55 MutexLock mu(lock_);
56 map_[id] = o;
57 return id;
58 }
59
Elliott Hughes234ab152011-10-26 14:02:26 -070060 void Clear() {
61 MutexLock mu(lock_);
62 LOG(DEBUG) << "Debugger has detached; object registry had " << map_.size() << " entries";
63 map_.clear();
64 }
65
Elliott Hughes475fc232011-10-25 15:00:35 -070066 bool Contains(JDWP::ObjectId id) {
67 MutexLock mu(lock_);
68 return map_.find(id) != map_.end();
69 }
70
Elliott Hughesa2155262011-11-16 16:26:58 -080071 template<typename T> T Get(JDWP::ObjectId id) {
72 MutexLock mu(lock_);
73 typedef std::map<JDWP::ObjectId, Object*>::iterator It; // C++0x auto
74 It it = map_.find(id);
75 return (it != map_.end()) ? reinterpret_cast<T>(it->second) : NULL;
76 }
77
Elliott Hughesbfe487b2011-10-26 15:48:55 -070078 void VisitRoots(Heap::RootVisitor* visitor, void* arg) {
79 MutexLock mu(lock_);
80 typedef std::map<JDWP::ObjectId, Object*>::iterator It; // C++0x auto
81 for (It it = map_.begin(); it != map_.end(); ++it) {
82 visitor(it->second, arg);
83 }
84 }
85
Elliott Hughes475fc232011-10-25 15:00:35 -070086 private:
87 Mutex lock_;
88 std::map<JDWP::ObjectId, Object*> map_;
89};
90
Elliott Hughes545a0642011-11-08 19:10:03 -080091struct AllocRecordStackTraceElement {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080092 Method* method;
Elliott Hughes545a0642011-11-08 19:10:03 -080093 uintptr_t raw_pc;
94
95 int32_t LineNumber() const {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080096 return MethodHelper(method).GetLineNumFromNativePC(raw_pc);
Elliott Hughes545a0642011-11-08 19:10:03 -080097 }
98};
99
100struct AllocRecord {
101 Class* type;
102 size_t byte_count;
103 uint16_t thin_lock_id;
104 AllocRecordStackTraceElement stack[kMaxAllocRecordStackDepth]; // Unused entries have NULL method.
105
106 size_t GetDepth() {
107 size_t depth = 0;
108 while (depth < kMaxAllocRecordStackDepth && stack[depth].method != NULL) {
109 ++depth;
110 }
111 return depth;
112 }
113};
114
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700115// JDWP is allowed unless the Zygote forbids it.
116static bool gJdwpAllowed = true;
117
Elliott Hughes3bb81562011-10-21 18:52:59 -0700118// Was there a -Xrunjdwp or -agent argument on the command-line?
119static bool gJdwpConfigured = false;
120
121// Broken-down JDWP options. (Only valid if gJdwpConfigured is true.)
Elliott Hughes376a7a02011-10-24 18:35:55 -0700122static JDWP::JdwpOptions gJdwpOptions;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700123
124// Runtime JDWP state.
125static JDWP::JdwpState* gJdwpState = NULL;
126static bool gDebuggerConnected; // debugger or DDMS is connected.
127static bool gDebuggerActive; // debugger is making requests.
128
Elliott Hughes47fce012011-10-25 18:37:19 -0700129static bool gDdmThreadNotification = false;
130
Elliott Hughes767a1472011-10-26 18:49:02 -0700131// DDMS GC-related settings.
132static Dbg::HpifWhen gDdmHpifWhen = Dbg::HPIF_WHEN_NEVER;
133static Dbg::HpsgWhen gDdmHpsgWhen = Dbg::HPSG_WHEN_NEVER;
134static Dbg::HpsgWhat gDdmHpsgWhat;
135static Dbg::HpsgWhen gDdmNhsgWhen = Dbg::HPSG_WHEN_NEVER;
136static Dbg::HpsgWhat gDdmNhsgWhat;
137
Elliott Hughes475fc232011-10-25 15:00:35 -0700138static ObjectRegistry* gRegistry = NULL;
139
Elliott Hughes545a0642011-11-08 19:10:03 -0800140// Recent allocation tracking.
141static Mutex gAllocTrackerLock("AllocTracker lock");
142AllocRecord* Dbg::recent_allocation_records_ = NULL; // TODO: CircularBuffer<AllocRecord>
143static size_t gAllocRecordHead = 0;
144static size_t gAllocRecordCount = 0;
145
Elliott Hughes24437992011-11-30 14:49:33 -0800146static JDWP::JdwpTag BasicTagFromDescriptor(const char* descriptor) {
147 // JDWP deliberately uses the descriptor characters' ASCII values for its enum.
148 // Note that by "basic" we mean that we don't get more specific than JT_OBJECT.
149 return static_cast<JDWP::JdwpTag>(descriptor[0]);
150}
151
152static JDWP::JdwpTag TagFromClass(Class* c) {
Elliott Hughes86b00102011-12-05 17:54:26 -0800153 CHECK(c != NULL);
Elliott Hughes24437992011-11-30 14:49:33 -0800154 if (c->IsArrayClass()) {
155 return JDWP::JT_ARRAY;
156 }
157
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800158 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Elliott Hughes24437992011-11-30 14:49:33 -0800159 if (c->IsStringClass()) {
160 return JDWP::JT_STRING;
161 } else if (c->IsClassClass()) {
162 return JDWP::JT_CLASS_OBJECT;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800163 } else if (class_linker->FindSystemClass("Ljava/lang/Thread;")->IsAssignableFrom(c)) {
Elliott Hughes24437992011-11-30 14:49:33 -0800164 return JDWP::JT_THREAD;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800165 } else if (class_linker->FindSystemClass("Ljava/lang/ThreadGroup;")->IsAssignableFrom(c)) {
Elliott Hughes24437992011-11-30 14:49:33 -0800166 return JDWP::JT_THREAD_GROUP;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800167 } else if (class_linker->FindSystemClass("Ljava/lang/ClassLoader;")->IsAssignableFrom(c)) {
Elliott Hughes24437992011-11-30 14:49:33 -0800168 return JDWP::JT_CLASS_LOADER;
Elliott Hughes24437992011-11-30 14:49:33 -0800169 } else {
170 return JDWP::JT_OBJECT;
171 }
172}
173
174/*
175 * Objects declared to hold Object might actually hold a more specific
176 * type. The debugger may take a special interest in these (e.g. it
177 * wants to display the contents of Strings), so we want to return an
178 * appropriate tag.
179 *
180 * Null objects are tagged JT_OBJECT.
181 */
182static JDWP::JdwpTag TagFromObject(const Object* o) {
183 return (o == NULL) ? JDWP::JT_OBJECT : TagFromClass(o->GetClass());
184}
185
186static bool IsPrimitiveTag(JDWP::JdwpTag tag) {
187 switch (tag) {
188 case JDWP::JT_BOOLEAN:
189 case JDWP::JT_BYTE:
190 case JDWP::JT_CHAR:
191 case JDWP::JT_FLOAT:
192 case JDWP::JT_DOUBLE:
193 case JDWP::JT_INT:
194 case JDWP::JT_LONG:
195 case JDWP::JT_SHORT:
196 case JDWP::JT_VOID:
197 return true;
198 default:
199 return false;
200 }
201}
202
Elliott Hughes3bb81562011-10-21 18:52:59 -0700203/*
204 * Handle one of the JDWP name/value pairs.
205 *
206 * JDWP options are:
207 * help: if specified, show help message and bail
208 * transport: may be dt_socket or dt_shmem
209 * address: for dt_socket, "host:port", or just "port" when listening
210 * server: if "y", wait for debugger to attach; if "n", attach to debugger
211 * timeout: how long to wait for debugger to connect / listen
212 *
213 * Useful with server=n (these aren't supported yet):
214 * onthrow=<exception-name>: connect to debugger when exception thrown
215 * onuncaught=y|n: connect to debugger when uncaught exception thrown
216 * launch=<command-line>: launch the debugger itself
217 *
218 * The "transport" option is required, as is "address" if server=n.
219 */
220static bool ParseJdwpOption(const std::string& name, const std::string& value) {
221 if (name == "transport") {
222 if (value == "dt_socket") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700223 gJdwpOptions.transport = JDWP::kJdwpTransportSocket;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700224 } else if (value == "dt_android_adb") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700225 gJdwpOptions.transport = JDWP::kJdwpTransportAndroidAdb;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700226 } else {
227 LOG(ERROR) << "JDWP transport not supported: " << value;
228 return false;
229 }
230 } else if (name == "server") {
231 if (value == "n") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700232 gJdwpOptions.server = false;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700233 } else if (value == "y") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700234 gJdwpOptions.server = true;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700235 } else {
236 LOG(ERROR) << "JDWP option 'server' must be 'y' or 'n'";
237 return false;
238 }
239 } else if (name == "suspend") {
240 if (value == "n") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700241 gJdwpOptions.suspend = false;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700242 } else if (value == "y") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700243 gJdwpOptions.suspend = true;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700244 } else {
245 LOG(ERROR) << "JDWP option 'suspend' must be 'y' or 'n'";
246 return false;
247 }
248 } else if (name == "address") {
249 /* this is either <port> or <host>:<port> */
250 std::string port_string;
Elliott Hughes376a7a02011-10-24 18:35:55 -0700251 gJdwpOptions.host.clear();
Elliott Hughes3bb81562011-10-21 18:52:59 -0700252 std::string::size_type colon = value.find(':');
253 if (colon != std::string::npos) {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700254 gJdwpOptions.host = value.substr(0, colon);
Elliott Hughes3bb81562011-10-21 18:52:59 -0700255 port_string = value.substr(colon + 1);
256 } else {
257 port_string = value;
258 }
259 if (port_string.empty()) {
260 LOG(ERROR) << "JDWP address missing port: " << value;
261 return false;
262 }
263 char* end;
Elliott Hughesba8eee12012-01-24 20:25:24 -0800264 uint64_t port = strtoul(port_string.c_str(), &end, 10);
265 if (*end != '\0' || port > 0xffff) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700266 LOG(ERROR) << "JDWP address has junk in port field: " << value;
267 return false;
268 }
Elliott Hughes376a7a02011-10-24 18:35:55 -0700269 gJdwpOptions.port = port;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700270 } else if (name == "launch" || name == "onthrow" || name == "oncaught" || name == "timeout") {
271 /* valid but unsupported */
272 LOG(INFO) << "Ignoring JDWP option '" << name << "'='" << value << "'";
273 } else {
274 LOG(INFO) << "Ignoring unrecognized JDWP option '" << name << "'='" << value << "'";
275 }
276
277 return true;
278}
279
280/*
281 * Parse the latter half of a -Xrunjdwp/-agentlib:jdwp= string, e.g.:
282 * "transport=dt_socket,address=8000,server=y,suspend=n"
283 */
284bool Dbg::ParseJdwpOptions(const std::string& options) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800285 VLOG(jdwp) << "ParseJdwpOptions: " << options;
Elliott Hughes47fce012011-10-25 18:37:19 -0700286
Elliott Hughes3bb81562011-10-21 18:52:59 -0700287 std::vector<std::string> pairs;
288 Split(options, ',', pairs);
289
290 for (size_t i = 0; i < pairs.size(); ++i) {
291 std::string::size_type equals = pairs[i].find('=');
292 if (equals == std::string::npos) {
293 LOG(ERROR) << "Can't parse JDWP option '" << pairs[i] << "' in '" << options << "'";
294 return false;
295 }
296 ParseJdwpOption(pairs[i].substr(0, equals), pairs[i].substr(equals + 1));
297 }
298
Elliott Hughes376a7a02011-10-24 18:35:55 -0700299 if (gJdwpOptions.transport == JDWP::kJdwpTransportUnknown) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700300 LOG(ERROR) << "Must specify JDWP transport: " << options;
301 }
Elliott Hughes376a7a02011-10-24 18:35:55 -0700302 if (!gJdwpOptions.server && (gJdwpOptions.host.empty() || gJdwpOptions.port == 0)) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700303 LOG(ERROR) << "Must specify JDWP host and port when server=n: " << options;
304 return false;
305 }
306
307 gJdwpConfigured = true;
308 return true;
309}
310
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700311void Dbg::StartJdwp() {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700312 if (!gJdwpAllowed || !gJdwpConfigured) {
313 // No JDWP for you!
314 return;
315 }
316
Elliott Hughes475fc232011-10-25 15:00:35 -0700317 CHECK(gRegistry == NULL);
318 gRegistry = new ObjectRegistry;
319
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700320 // Init JDWP if the debugger is enabled. This may connect out to a
321 // debugger, passively listen for a debugger, or block waiting for a
322 // debugger.
Elliott Hughes376a7a02011-10-24 18:35:55 -0700323 gJdwpState = JDWP::JdwpState::Create(&gJdwpOptions);
324 if (gJdwpState == NULL) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -0800325 // We probably failed because some other process has the port already, which means that
326 // if we don't abort the user is likely to think they're talking to us when they're actually
327 // talking to that other process.
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800328 LOG(FATAL) << "Debugger thread failed to initialize";
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700329 }
330
331 // If a debugger has already attached, send the "welcome" message.
332 // This may cause us to suspend all threads.
Elliott Hughes376a7a02011-10-24 18:35:55 -0700333 if (gJdwpState->IsActive()) {
Elliott Hughesa2155262011-11-16 16:26:58 -0800334 //ScopedThreadStateChange tsc(Thread::Current(), Thread::kRunnable);
Elliott Hughes376a7a02011-10-24 18:35:55 -0700335 if (!gJdwpState->PostVMStart()) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800336 LOG(WARNING) << "Failed to post 'start' message to debugger";
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700337 }
338 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700339}
340
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700341void Dbg::StopJdwp() {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700342 delete gJdwpState;
Elliott Hughes475fc232011-10-25 15:00:35 -0700343 delete gRegistry;
344 gRegistry = NULL;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700345}
346
Elliott Hughes767a1472011-10-26 18:49:02 -0700347void Dbg::GcDidFinish() {
348 if (gDdmHpifWhen != HPIF_WHEN_NEVER) {
349 LOG(DEBUG) << "Sending VM heap info to DDM";
Elliott Hughes7162ad92011-10-27 14:08:42 -0700350 DdmSendHeapInfo(gDdmHpifWhen);
Elliott Hughes767a1472011-10-26 18:49:02 -0700351 }
352 if (gDdmHpsgWhen != HPSG_WHEN_NEVER) {
353 LOG(DEBUG) << "Dumping VM heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700354 DdmSendHeapSegments(false);
Elliott Hughes767a1472011-10-26 18:49:02 -0700355 }
356 if (gDdmNhsgWhen != HPSG_WHEN_NEVER) {
357 LOG(DEBUG) << "Dumping native heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700358 DdmSendHeapSegments(true);
Elliott Hughes767a1472011-10-26 18:49:02 -0700359 }
360}
361
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700362void Dbg::SetJdwpAllowed(bool allowed) {
363 gJdwpAllowed = allowed;
364}
365
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700366DebugInvokeReq* Dbg::GetInvokeReq() {
Elliott Hughes475fc232011-10-25 15:00:35 -0700367 return Thread::Current()->GetInvokeReq();
368}
369
370Thread* Dbg::GetDebugThread() {
371 return (gJdwpState != NULL) ? gJdwpState->GetDebugThread() : NULL;
372}
373
374void Dbg::ClearWaitForEventThread() {
375 gJdwpState->ClearWaitForEventThread();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700376}
377
378void Dbg::Connected() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700379 CHECK(!gDebuggerConnected);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800380 VLOG(jdwp) << "JDWP has attached";
Elliott Hughes3bb81562011-10-21 18:52:59 -0700381 gDebuggerConnected = true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700382}
383
Elliott Hughesa2155262011-11-16 16:26:58 -0800384void Dbg::GoActive() {
385 // Enable all debugging features, including scans for breakpoints.
386 // This is a no-op if we're already active.
387 // Only called from the JDWP handler thread.
388 if (gDebuggerActive) {
389 return;
390 }
391
392 LOG(INFO) << "Debugger is active";
393
394 // TODO: CHECK we don't have any outstanding breakpoints.
395
396 gDebuggerActive = true;
397
398 //dvmEnableAllSubMode(kSubModeDebuggerActive);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700399}
400
401void Dbg::Disconnected() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700402 CHECK(gDebuggerConnected);
403
404 gDebuggerActive = false;
405
406 //dvmDisableAllSubMode(kSubModeDebuggerActive);
407
408 gRegistry->Clear();
409 gDebuggerConnected = false;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700410}
411
412bool Dbg::IsDebuggerConnected() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700413 return gDebuggerActive;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700414}
415
416bool Dbg::IsDebuggingEnabled() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700417 return gJdwpConfigured;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700418}
419
420int64_t Dbg::LastDebuggerActivity() {
Elliott Hughesca951522011-12-05 12:01:32 -0800421 return gJdwpState->LastDebuggerActivity();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700422}
423
424int Dbg::ThreadRunning() {
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700425 return static_cast<int>(Thread::Current()->SetState(Thread::kRunnable));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700426}
427
428int Dbg::ThreadWaiting() {
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700429 return static_cast<int>(Thread::Current()->SetState(Thread::kVmWait));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700430}
431
Elliott Hughes6ba581a2011-10-25 11:45:35 -0700432int Dbg::ThreadContinuing(int new_state) {
433 return static_cast<int>(Thread::Current()->SetState(static_cast<Thread::State>(new_state)));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700434}
435
436void Dbg::UndoDebuggerSuspensions() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700437 Runtime::Current()->GetThreadList()->UndoDebuggerSuspensions();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700438}
439
440void Dbg::Exit(int status) {
Elliott Hughes1bba14f2011-12-01 18:00:36 -0800441 exit(status); // This is all dalvik did.
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700442}
443
Elliott Hughesbfe487b2011-10-26 15:48:55 -0700444void Dbg::VisitRoots(Heap::RootVisitor* visitor, void* arg) {
445 if (gRegistry != NULL) {
446 gRegistry->VisitRoots(visitor, arg);
447 }
448}
449
Elliott Hughesa2155262011-11-16 16:26:58 -0800450std::string Dbg::GetClassDescriptor(JDWP::RefTypeId classId) {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800451 Object* o = gRegistry->Get<Object*>(classId);
452 if (o == NULL || !o->IsClass()) {
453 return StringPrintf("non-class %p", o); // This is only used for debugging output anyway.
454 }
455 return ClassHelper(o->AsClass()).GetDescriptor();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700456}
457
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800458bool Dbg::GetClassObject(JDWP::RefTypeId id, JDWP::ObjectId& classObjectId) {
459 Object* o = gRegistry->Get<Object*>(id);
460 if (o == NULL || !o->IsClass()) {
461 return false;
462 }
463 classObjectId = gRegistry->Add(o);
464 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700465}
466
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800467static Array* DecodeArray(JDWP::RefTypeId id, JDWP::JdwpError& status) {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800468 Object* o = gRegistry->Get<Object*>(id);
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800469 if (o == NULL) {
470 status = JDWP::ERR_INVALID_OBJECT;
471 return NULL;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800472 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800473 if (!o->IsArrayInstance()) {
474 status = JDWP::ERR_INVALID_ARRAY;
475 return NULL;
476 }
477 status = JDWP::ERR_NONE;
478 return o->AsArray();
479}
480
481// TODO: this should probably be used everywhere we're converting a RefTypeId to a Class*.
482static Class* DecodeClass(JDWP::RefTypeId id, JDWP::JdwpError& status) {
483 Object* o = gRegistry->Get<Object*>(id);
484 if (o == NULL) {
485 status = JDWP::ERR_INVALID_OBJECT;
486 return NULL;
487 }
488 if (!o->IsClass()) {
489 status = JDWP::ERR_INVALID_CLASS;
490 return NULL;
491 }
492 status = JDWP::ERR_NONE;
493 return o->AsClass();
494}
495
496JDWP::JdwpError Dbg::GetSuperclass(JDWP::RefTypeId id, JDWP::RefTypeId& superclassId) {
497 JDWP::JdwpError status;
498 Class* c = DecodeClass(id, status);
499 if (c == NULL) {
500 return status;
501 }
502 if (c->IsInterface()) {
503 // http://code.google.com/p/android/issues/detail?id=20856
504 superclassId = NULL;
505 } else {
506 superclassId = gRegistry->Add(c->GetSuperClass());
507 }
508 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700509}
510
511JDWP::ObjectId Dbg::GetClassLoader(JDWP::RefTypeId id) {
Elliott Hughes1bba14f2011-12-01 18:00:36 -0800512 Object* o = gRegistry->Get<Object*>(id);
513 return gRegistry->Add(o->GetClass()->GetClassLoader());
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700514}
515
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800516bool Dbg::GetAccessFlags(JDWP::RefTypeId id, uint32_t& access_flags) {
517 Object* o = gRegistry->Get<Object*>(id);
518 if (o == NULL || !o->IsClass()) {
519 return false;
520 }
521 access_flags = o->AsClass()->GetAccessFlags() & kAccJavaFlagsMask;
522 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700523}
524
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800525bool Dbg::IsInterface(JDWP::RefTypeId classId, bool& is_interface) {
526 Object* o = gRegistry->Get<Object*>(classId);
527 if (o == NULL || !o->IsClass()) {
528 return false;
529 }
530 is_interface = o->AsClass()->IsInterface();
531 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700532}
533
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800534void Dbg::GetClassList(std::vector<JDWP::RefTypeId>& classes) {
Elliott Hughesa2155262011-11-16 16:26:58 -0800535 // Get the complete list of reference classes (i.e. all classes except
536 // the primitive types).
537 // Returns a newly-allocated buffer full of RefTypeId values.
538 struct ClassListCreator {
Elliott Hughesba8eee12012-01-24 20:25:24 -0800539 explicit ClassListCreator(std::vector<JDWP::RefTypeId>& classes) : classes(classes) {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800540 }
541
Elliott Hughesa2155262011-11-16 16:26:58 -0800542 static bool Visit(Class* c, void* arg) {
543 return reinterpret_cast<ClassListCreator*>(arg)->Visit(c);
544 }
545
546 bool Visit(Class* c) {
547 if (!c->IsPrimitive()) {
548 classes.push_back(static_cast<JDWP::RefTypeId>(gRegistry->Add(c)));
549 }
550 return true;
551 }
552
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800553 std::vector<JDWP::RefTypeId>& classes;
Elliott Hughesa2155262011-11-16 16:26:58 -0800554 };
555
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800556 ClassListCreator clc(classes);
Elliott Hughesa2155262011-11-16 16:26:58 -0800557 Runtime::Current()->GetClassLinker()->VisitClasses(ClassListCreator::Visit, &clc);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700558}
559
560void Dbg::GetVisibleClassList(JDWP::ObjectId classLoaderId, uint32_t* pNumClasses, JDWP::RefTypeId** pClassRefBuf) {
561 UNIMPLEMENTED(FATAL);
562}
563
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800564bool Dbg::GetClassInfo(JDWP::RefTypeId classId, JDWP::JdwpTypeTag* pTypeTag, uint32_t* pStatus, std::string* pDescriptor) {
565 Object* o = gRegistry->Get<Object*>(classId);
566 if (o == NULL || !o->IsClass()) {
567 return false;
568 }
569
570 Class* c = o->AsClass();
Elliott Hughesa2155262011-11-16 16:26:58 -0800571 if (c->IsArrayClass()) {
572 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
573 *pTypeTag = JDWP::TT_ARRAY;
574 } else {
575 if (c->IsErroneous()) {
576 *pStatus = JDWP::CS_ERROR;
577 } else {
578 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED | JDWP::CS_INITIALIZED;
579 }
580 *pTypeTag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
581 }
582
583 if (pDescriptor != NULL) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800584 *pDescriptor = ClassHelper(c).GetDescriptor();
Elliott Hughesa2155262011-11-16 16:26:58 -0800585 }
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800586 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700587}
588
Elliott Hughesc3b77c72011-12-15 20:56:48 -0800589void Dbg::FindLoadedClassBySignature(const char* descriptor, std::vector<JDWP::RefTypeId>& ids) {
Elliott Hughes6fa602d2011-12-02 17:54:25 -0800590 std::vector<Class*> classes;
591 Runtime::Current()->GetClassLinker()->LookupClasses(descriptor, classes);
592 ids.clear();
593 for (size_t i = 0; i < classes.size(); ++i) {
594 ids.push_back(gRegistry->Add(classes[i]));
595 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700596}
597
Elliott Hughes6fa602d2011-12-02 17:54:25 -0800598void Dbg::GetObjectType(JDWP::ObjectId objectId, JDWP::JdwpTypeTag* pRefTypeTag, JDWP::RefTypeId* pRefTypeId) {
Elliott Hughes499c5132011-11-17 14:55:11 -0800599 Object* o = gRegistry->Get<Object*>(objectId);
600 if (o->GetClass()->IsArrayClass()) {
601 *pRefTypeTag = JDWP::TT_ARRAY;
602 } else if (o->GetClass()->IsInterface()) {
603 *pRefTypeTag = JDWP::TT_INTERFACE;
604 } else {
605 *pRefTypeTag = JDWP::TT_CLASS;
606 }
607 *pRefTypeId = gRegistry->Add(o->GetClass());
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700608}
609
610uint8_t Dbg::GetClassObjectType(JDWP::RefTypeId refTypeId) {
611 UNIMPLEMENTED(FATAL);
612 return 0;
613}
614
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800615bool Dbg::GetSignature(JDWP::RefTypeId refTypeId, std::string& signature) {
616 Object* o = gRegistry->Get<Object*>(refTypeId);
617 if (o == NULL || !o->IsClass()) {
618 return false;
619 }
620 signature = ClassHelper(o->AsClass()).GetDescriptor();
621 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700622}
623
Elliott Hughes03181a82011-11-17 17:22:21 -0800624bool Dbg::GetSourceFile(JDWP::RefTypeId refTypeId, std::string& result) {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800625 Object* o = gRegistry->Get<Object*>(refTypeId);
626 if (o == NULL || !o->IsClass()) {
627 return false;
628 }
629 result = ClassHelper(o->AsClass()).GetSourceFile();
630 return result != NULL;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700631}
632
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700633uint8_t Dbg::GetObjectTag(JDWP::ObjectId objectId) {
Elliott Hughes24437992011-11-30 14:49:33 -0800634 Object* o = gRegistry->Get<Object*>(objectId);
635 return TagFromObject(o);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700636}
637
Elliott Hughesaed4be92011-12-02 16:16:23 -0800638size_t Dbg::GetTagWidth(JDWP::JdwpTag tag) {
Elliott Hughesdbb40792011-11-18 17:05:22 -0800639 switch (tag) {
640 case JDWP::JT_VOID:
641 return 0;
642 case JDWP::JT_BYTE:
643 case JDWP::JT_BOOLEAN:
644 return 1;
645 case JDWP::JT_CHAR:
646 case JDWP::JT_SHORT:
647 return 2;
648 case JDWP::JT_FLOAT:
649 case JDWP::JT_INT:
650 return 4;
651 case JDWP::JT_ARRAY:
652 case JDWP::JT_OBJECT:
653 case JDWP::JT_STRING:
654 case JDWP::JT_THREAD:
655 case JDWP::JT_THREAD_GROUP:
656 case JDWP::JT_CLASS_LOADER:
657 case JDWP::JT_CLASS_OBJECT:
658 return sizeof(JDWP::ObjectId);
659 case JDWP::JT_DOUBLE:
660 case JDWP::JT_LONG:
661 return 8;
662 default:
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800663 LOG(FATAL) << "Unknown tag " << tag;
Elliott Hughesdbb40792011-11-18 17:05:22 -0800664 return -1;
665 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700666}
667
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800668JDWP::JdwpError Dbg::GetArrayLength(JDWP::ObjectId arrayId, int& length) {
669 JDWP::JdwpError status;
670 Array* a = DecodeArray(arrayId, status);
671 if (a == NULL) {
672 return status;
Elliott Hughes24437992011-11-30 14:49:33 -0800673 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800674 length = a->GetLength();
675 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700676}
677
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800678JDWP::JdwpError Dbg::OutputArray(JDWP::ObjectId arrayId, int offset, int count, JDWP::ExpandBuf* pReply) {
679 JDWP::JdwpError status;
680 Array* a = DecodeArray(arrayId, status);
681 if (a == NULL) {
682 return status;
683 }
Elliott Hughes24437992011-11-30 14:49:33 -0800684
685 if (offset < 0 || count < 0 || offset > a->GetLength() || a->GetLength() - offset < count) {
686 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800687 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughes24437992011-11-30 14:49:33 -0800688 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800689 std::string descriptor(ClassHelper(a->GetClass()).GetDescriptor());
Elliott Hughes24437992011-11-30 14:49:33 -0800690 JDWP::JdwpTag tag = BasicTagFromDescriptor(descriptor.c_str() + 1);
691
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800692 expandBufAdd1(pReply, tag);
693 expandBufAdd4BE(pReply, count);
694
Elliott Hughes24437992011-11-30 14:49:33 -0800695 if (IsPrimitiveTag(tag)) {
696 size_t width = GetTagWidth(tag);
697 const uint8_t* src = reinterpret_cast<uint8_t*>(a->GetRawData());
698 uint8_t* dst = expandBufAddSpace(pReply, count * width);
699 if (width == 8) {
700 const uint64_t* src8 = reinterpret_cast<const uint64_t*>(src);
701 for (int i = 0; i < count; ++i) JDWP::Write8BE(&dst, src8[offset + i]);
702 } else if (width == 4) {
703 const uint32_t* src4 = reinterpret_cast<const uint32_t*>(src);
704 for (int i = 0; i < count; ++i) JDWP::Write4BE(&dst, src4[offset + i]);
705 } else if (width == 2) {
706 const uint16_t* src2 = reinterpret_cast<const uint16_t*>(src);
707 for (int i = 0; i < count; ++i) JDWP::Write2BE(&dst, src2[offset + i]);
708 } else {
709 memcpy(dst, &src[offset * width], count * width);
710 }
711 } else {
712 ObjectArray<Object>* oa = a->AsObjectArray<Object>();
713 for (int i = 0; i < count; ++i) {
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800714 Object* element = oa->Get(offset + i);
Elliott Hughes24437992011-11-30 14:49:33 -0800715 JDWP::JdwpTag specific_tag = (element != NULL) ? TagFromObject(element) : tag;
716 expandBufAdd1(pReply, specific_tag);
717 expandBufAddObjectId(pReply, gRegistry->Add(element));
718 }
719 }
720
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800721 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700722}
723
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800724JDWP::JdwpError Dbg::SetArrayElements(JDWP::ObjectId arrayId, int offset, int count, const uint8_t* src) {
725 JDWP::JdwpError status;
726 Array* a = DecodeArray(arrayId, status);
727 if (a == NULL) {
728 return status;
729 }
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800730
731 if (offset < 0 || count < 0 || offset > a->GetLength() || a->GetLength() - offset < count) {
732 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800733 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800734 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800735 std::string descriptor(ClassHelper(a->GetClass()).GetDescriptor());
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800736 JDWP::JdwpTag tag = BasicTagFromDescriptor(descriptor.c_str() + 1);
737
738 if (IsPrimitiveTag(tag)) {
739 size_t width = GetTagWidth(tag);
740 uint8_t* dst = &(reinterpret_cast<uint8_t*>(a->GetRawData())[offset * width]);
741 if (width == 8) {
742 for (int i = 0; i < count; ++i) {
743 // Handle potentially non-aligned memory access one byte at a time for ARM's benefit.
744 uint64_t value;
745 for (size_t j = 0; j < sizeof(uint64_t); ++j) reinterpret_cast<uint8_t*>(&value)[j] = src[j];
746 src += sizeof(uint64_t);
747 JDWP::Write8BE(&dst, value);
748 }
749 } else if (width == 4) {
750 const uint32_t* src4 = reinterpret_cast<const uint32_t*>(src);
751 for (int i = 0; i < count; ++i) JDWP::Write4BE(&dst, src4[i]);
752 } else if (width == 2) {
753 const uint16_t* src2 = reinterpret_cast<const uint16_t*>(src);
754 for (int i = 0; i < count; ++i) JDWP::Write2BE(&dst, src2[i]);
755 } else {
756 memcpy(&dst[offset * width], src, count * width);
757 }
758 } else {
759 ObjectArray<Object>* oa = a->AsObjectArray<Object>();
760 for (int i = 0; i < count; ++i) {
761 JDWP::ObjectId id = JDWP::ReadObjectId(&src);
762 oa->Set(offset + i, gRegistry->Get<Object*>(id));
763 }
764 }
765
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800766 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700767}
768
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800769JDWP::ObjectId Dbg::CreateString(const std::string& str) {
770 return gRegistry->Add(String::AllocFromModifiedUtf8(str.c_str()));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700771}
772
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800773bool Dbg::CreateObject(JDWP::RefTypeId classId, JDWP::ObjectId& new_object) {
774 Object* o = gRegistry->Get<Object*>(classId);
775 if (o == NULL || !o->IsClass()) {
776 return false;
777 }
778 new_object = gRegistry->Add(o->AsClass()->AllocObject());
779 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700780}
781
Elliott Hughesbf13d362011-12-08 15:51:37 -0800782/*
783 * Used by Eclipse's "Display" view to evaluate "new byte[5]" to get "(byte[]) [0, 0, 0, 0, 0]".
784 */
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800785bool Dbg::CreateArrayObject(JDWP::RefTypeId arrayTypeId, uint32_t length, JDWP::ObjectId& new_array) {
786 Object* o = gRegistry->Get<Object*>(arrayTypeId);
787 if (o == NULL || !o->IsClass()) {
788 return false;
789 }
790 new_array = gRegistry->Add(Array::Alloc(o->AsClass(), length));
791 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700792}
793
794bool Dbg::MatchType(JDWP::RefTypeId instClassId, JDWP::RefTypeId classId) {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800795 // TODO: error handling if the RefTypeIds aren't actually Class*s.
Elliott Hughesd07986f2011-12-06 18:27:45 -0800796 return gRegistry->Get<Class*>(instClassId)->InstanceOf(gRegistry->Get<Class*>(classId));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700797}
798
Elliott Hughes03181a82011-11-17 17:22:21 -0800799JDWP::FieldId ToFieldId(Field* f) {
800#ifdef MOVING_GARBAGE_COLLECTOR
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700801 UNIMPLEMENTED(FATAL);
Elliott Hughes03181a82011-11-17 17:22:21 -0800802#else
803 return static_cast<JDWP::FieldId>(reinterpret_cast<uintptr_t>(f));
804#endif
805}
806
807JDWP::MethodId ToMethodId(Method* m) {
808#ifdef MOVING_GARBAGE_COLLECTOR
809 UNIMPLEMENTED(FATAL);
810#else
811 return static_cast<JDWP::MethodId>(reinterpret_cast<uintptr_t>(m));
812#endif
813}
814
Elliott Hughesaed4be92011-12-02 16:16:23 -0800815Field* FromFieldId(JDWP::FieldId fid) {
816#ifdef MOVING_GARBAGE_COLLECTOR
817 UNIMPLEMENTED(FATAL);
818#else
819 return reinterpret_cast<Field*>(static_cast<uintptr_t>(fid));
820#endif
821}
822
Elliott Hughes03181a82011-11-17 17:22:21 -0800823Method* FromMethodId(JDWP::MethodId mid) {
824#ifdef MOVING_GARBAGE_COLLECTOR
825 UNIMPLEMENTED(FATAL);
826#else
827 return reinterpret_cast<Method*>(static_cast<uintptr_t>(mid));
828#endif
829}
830
Elliott Hughesd07986f2011-12-06 18:27:45 -0800831void SetLocation(JDWP::JdwpLocation& location, Method* m, uintptr_t native_pc) {
832 Class* c = m->GetDeclaringClass();
833 location.typeTag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
834 location.classId = gRegistry->Add(c);
835 location.methodId = ToMethodId(m);
836 location.idx = m->IsNative() ? -1 : m->ToDexPC(native_pc);
837}
838
Elliott Hughes03181a82011-11-17 17:22:21 -0800839std::string Dbg::GetMethodName(JDWP::RefTypeId refTypeId, JDWP::MethodId methodId) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800840 Method* m = FromMethodId(methodId);
841 return MethodHelper(m).GetName();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700842}
843
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800844/*
845 * Augment the access flags for synthetic methods and fields by setting
846 * the (as described by the spec) "0xf0000000 bit". Also, strip out any
847 * flags not specified by the Java programming language.
848 */
849static uint32_t MangleAccessFlags(uint32_t accessFlags) {
850 accessFlags &= kAccJavaFlagsMask;
851 if ((accessFlags & kAccSynthetic) != 0) {
852 accessFlags |= 0xf0000000;
853 }
854 return accessFlags;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700855}
856
Elliott Hughesdbb40792011-11-18 17:05:22 -0800857static const uint16_t kEclipseWorkaroundSlot = 1000;
858
859/*
860 * Eclipse appears to expect that the "this" reference is in slot zero.
861 * If it's not, the "variables" display will show two copies of "this",
862 * possibly because it gets "this" from SF.ThisObject and then displays
863 * all locals with nonzero slot numbers.
864 *
865 * So, we remap the item in slot 0 to 1000, and remap "this" to zero. On
866 * SF.GetValues / SF.SetValues we map them back.
Elliott Hughesc5b734a2011-12-01 17:20:58 -0800867 *
868 * TODO: jdb uses the value to determine whether a variable is a local or an argument,
869 * by checking whether it's less than the number of arguments. To make that work, we'd
870 * have to "mangle" all the arguments to come first, not just the implicit argument 'this'.
Elliott Hughesdbb40792011-11-18 17:05:22 -0800871 */
872static uint16_t MangleSlot(uint16_t slot, const char* name) {
873 uint16_t newSlot = slot;
874 if (strcmp(name, "this") == 0) {
875 newSlot = 0;
876 } else if (slot == 0) {
877 newSlot = kEclipseWorkaroundSlot;
878 }
879 return newSlot;
880}
881
Elliott Hughes68fdbd02011-11-29 19:22:47 -0800882static uint16_t DemangleSlot(uint16_t slot, Frame& f) {
Elliott Hughesdbb40792011-11-18 17:05:22 -0800883 if (slot == kEclipseWorkaroundSlot) {
Elliott Hughes68fdbd02011-11-29 19:22:47 -0800884 return 0;
Elliott Hughesdbb40792011-11-18 17:05:22 -0800885 } else if (slot == 0) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800886 const DexFile::CodeItem* code_item = MethodHelper(f.GetMethod()).GetCodeItem();
887 return code_item->registers_size_ - code_item->ins_size_;
Elliott Hughesdbb40792011-11-18 17:05:22 -0800888 }
Elliott Hughes68fdbd02011-11-29 19:22:47 -0800889 return slot;
Elliott Hughesdbb40792011-11-18 17:05:22 -0800890}
891
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800892bool Dbg::OutputDeclaredFields(JDWP::RefTypeId refTypeId, bool with_generic, JDWP::ExpandBuf* pReply) {
893 Object* o = gRegistry->Get<Object*>(refTypeId);
894 if (o == NULL || !o->IsClass()) {
895 return false;
896 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800897
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800898 Class* c = o->AsClass();
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800899 size_t instance_field_count = c->NumInstanceFields();
900 size_t static_field_count = c->NumStaticFields();
901
902 expandBufAdd4BE(pReply, instance_field_count + static_field_count);
903
904 for (size_t i = 0; i < instance_field_count + static_field_count; ++i) {
905 Field* f = (i < instance_field_count) ? c->GetInstanceField(i) : c->GetStaticField(i - instance_field_count);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800906 FieldHelper fh(f);
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800907 expandBufAddFieldId(pReply, ToFieldId(f));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800908 expandBufAddUtf8String(pReply, fh.GetName());
909 expandBufAddUtf8String(pReply, fh.GetTypeDescriptor());
Elliott Hughesc5b734a2011-12-01 17:20:58 -0800910 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800911 static const char genericSignature[1] = "";
912 expandBufAddUtf8String(pReply, genericSignature);
913 }
914 expandBufAdd4BE(pReply, MangleAccessFlags(f->GetAccessFlags()));
915 }
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800916 return true;
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800917}
918
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800919bool Dbg::OutputDeclaredMethods(JDWP::RefTypeId refTypeId, bool with_generic, JDWP::ExpandBuf* pReply) {
920 Object* o = gRegistry->Get<Object*>(refTypeId);
921 if (o == NULL || !o->IsClass()) {
922 return false;
923 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800924
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800925 Class* c = o->AsClass();
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800926 size_t direct_method_count = c->NumDirectMethods();
927 size_t virtual_method_count = c->NumVirtualMethods();
928
929 expandBufAdd4BE(pReply, direct_method_count + virtual_method_count);
930
931 for (size_t i = 0; i < direct_method_count + virtual_method_count; ++i) {
932 Method* m = (i < direct_method_count) ? c->GetDirectMethod(i) : c->GetVirtualMethod(i - direct_method_count);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800933 MethodHelper mh(m);
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800934 expandBufAddMethodId(pReply, ToMethodId(m));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800935 expandBufAddUtf8String(pReply, mh.GetName());
Elliott Hughes4740cdf2011-12-07 14:07:12 -0800936 expandBufAddUtf8String(pReply, mh.GetSignature());
Elliott Hughesc5b734a2011-12-01 17:20:58 -0800937 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800938 static const char genericSignature[1] = "";
939 expandBufAddUtf8String(pReply, genericSignature);
940 }
941 expandBufAdd4BE(pReply, MangleAccessFlags(m->GetAccessFlags()));
942 }
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800943 return true;
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800944}
945
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800946bool Dbg::OutputDeclaredInterfaces(JDWP::RefTypeId refTypeId, JDWP::ExpandBuf* pReply) {
947 Object* o = gRegistry->Get<Object*>(refTypeId);
948 if (o == NULL || !o->IsClass()) {
949 return false;
950 }
951 ClassHelper kh(o->AsClass());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800952 size_t interface_count = kh.NumInterfaces();
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800953 expandBufAdd4BE(pReply, interface_count);
954 for (size_t i = 0; i < interface_count; ++i) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800955 expandBufAddRefTypeId(pReply, gRegistry->Add(kh.GetInterface(i)));
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800956 }
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800957 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700958}
959
960void Dbg::OutputLineTable(JDWP::RefTypeId refTypeId, JDWP::MethodId methodId, JDWP::ExpandBuf* pReply) {
Elliott Hughes03181a82011-11-17 17:22:21 -0800961 struct DebugCallbackContext {
962 int numItems;
963 JDWP::ExpandBuf* pReply;
964
965 static bool Callback(void* context, uint32_t address, uint32_t lineNum) {
966 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
967 expandBufAdd8BE(pContext->pReply, address);
968 expandBufAdd4BE(pContext->pReply, lineNum);
969 pContext->numItems++;
970 return true;
971 }
972 };
973
974 Method* m = FromMethodId(methodId);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800975 MethodHelper mh(m);
Elliott Hughes03181a82011-11-17 17:22:21 -0800976 uint64_t start, end;
977 if (m->IsNative()) {
978 start = -1;
979 end = -1;
980 } else {
981 start = 0;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800982 // TODO: what are the units supposed to be? *2?
983 end = mh.GetCodeItem()->insns_size_in_code_units_;
Elliott Hughes03181a82011-11-17 17:22:21 -0800984 }
985
986 expandBufAdd8BE(pReply, start);
987 expandBufAdd8BE(pReply, end);
988
989 // Add numLines later
990 size_t numLinesOffset = expandBufGetLength(pReply);
991 expandBufAdd4BE(pReply, 0);
992
993 DebugCallbackContext context;
994 context.numItems = 0;
995 context.pReply = pReply;
996
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800997 mh.GetDexFile().DecodeDebugInfo(mh.GetCodeItem(), m->IsStatic(), m->GetDexMethodIndex(),
998 DebugCallbackContext::Callback, NULL, &context);
Elliott Hughes03181a82011-11-17 17:22:21 -0800999
1000 JDWP::Set4BE(expandBufGetBuffer(pReply) + numLinesOffset, context.numItems);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001001}
1002
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001003void Dbg::OutputVariableTable(JDWP::RefTypeId refTypeId, JDWP::MethodId methodId, bool with_generic, JDWP::ExpandBuf* pReply) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001004 struct DebugCallbackContext {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001005 JDWP::ExpandBuf* pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001006 size_t variable_count;
1007 bool with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001008
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001009 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 -08001010 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
1011
Elliott Hughesaa6e1cd2012-01-18 19:26:06 -08001012 VLOG(jdwp) << StringPrintf(" %2zd: %d(%d) '%s' '%s' '%s' slot=%d", pContext->variable_count, startAddress, endAddress - startAddress, name, descriptor, signature, slot);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001013
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001014 slot = MangleSlot(slot, name);
1015
Elliott Hughesdbb40792011-11-18 17:05:22 -08001016 expandBufAdd8BE(pContext->pReply, startAddress);
1017 expandBufAddUtf8String(pContext->pReply, name);
1018 expandBufAddUtf8String(pContext->pReply, descriptor);
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001019 if (pContext->with_generic) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001020 expandBufAddUtf8String(pContext->pReply, signature);
1021 }
1022 expandBufAdd4BE(pContext->pReply, endAddress - startAddress);
1023 expandBufAdd4BE(pContext->pReply, slot);
1024
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001025 ++pContext->variable_count;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001026 }
1027 };
1028
1029 Method* m = FromMethodId(methodId);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001030 MethodHelper mh(m);
1031 const DexFile::CodeItem* code_item = mh.GetCodeItem();
Elliott Hughesdbb40792011-11-18 17:05:22 -08001032
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001033 // arg_count considers doubles and longs to take 2 units.
1034 // variable_count considers everything to take 1 unit.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001035 std::string shorty(mh.GetShorty());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001036 expandBufAdd4BE(pReply, m->NumArgRegisters(shorty));
Elliott Hughesdbb40792011-11-18 17:05:22 -08001037
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001038 // We don't know the total number of variables yet, so leave a blank and update it later.
1039 size_t variable_count_offset = expandBufGetLength(pReply);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001040 expandBufAdd4BE(pReply, 0);
1041
1042 DebugCallbackContext context;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001043 context.pReply = pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001044 context.variable_count = 0;
1045 context.with_generic = with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001046
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001047 mh.GetDexFile().DecodeDebugInfo(code_item, m->IsStatic(), m->GetDexMethodIndex(), NULL,
1048 DebugCallbackContext::Callback, &context);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001049
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001050 JDWP::Set4BE(expandBufGetBuffer(pReply) + variable_count_offset, context.variable_count);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001051}
1052
Elliott Hughesaed4be92011-12-02 16:16:23 -08001053JDWP::JdwpTag Dbg::GetFieldBasicTag(JDWP::FieldId fieldId) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001054 return BasicTagFromDescriptor(FieldHelper(FromFieldId(fieldId)).GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001055}
1056
Elliott Hughesaed4be92011-12-02 16:16:23 -08001057JDWP::JdwpTag Dbg::GetStaticFieldBasicTag(JDWP::FieldId fieldId) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001058 return BasicTagFromDescriptor(FieldHelper(FromFieldId(fieldId)).GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001059}
1060
1061void Dbg::GetFieldValue(JDWP::ObjectId objectId, JDWP::FieldId fieldId, JDWP::ExpandBuf* pReply) {
Elliott Hughesaed4be92011-12-02 16:16:23 -08001062 Object* o = gRegistry->Get<Object*>(objectId);
1063 Field* f = FromFieldId(fieldId);
1064
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001065 JDWP::JdwpTag tag = BasicTagFromDescriptor(FieldHelper(f).GetTypeDescriptor());
Elliott Hughesaed4be92011-12-02 16:16:23 -08001066
1067 if (IsPrimitiveTag(tag)) {
1068 expandBufAdd1(pReply, tag);
1069 if (tag == JDWP::JT_BOOLEAN || tag == JDWP::JT_BYTE) {
1070 expandBufAdd1(pReply, f->Get32(o));
1071 } else if (tag == JDWP::JT_CHAR || tag == JDWP::JT_SHORT) {
1072 expandBufAdd2BE(pReply, f->Get32(o));
1073 } else if (tag == JDWP::JT_FLOAT || tag == JDWP::JT_INT) {
1074 expandBufAdd4BE(pReply, f->Get32(o));
1075 } else if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
1076 expandBufAdd8BE(pReply, f->Get64(o));
1077 } else {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001078 LOG(FATAL) << "Unknown tag: " << tag;
Elliott Hughesaed4be92011-12-02 16:16:23 -08001079 }
1080 } else {
1081 Object* value = f->GetObject(o);
1082 expandBufAdd1(pReply, TagFromObject(value));
1083 expandBufAddObjectId(pReply, gRegistry->Add(value));
1084 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001085}
1086
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001087JDWP::JdwpError Dbg::SetFieldValue(JDWP::ObjectId objectId, JDWP::FieldId fieldId, uint64_t value, int width) {
Elliott Hughesaed4be92011-12-02 16:16:23 -08001088 Object* o = gRegistry->Get<Object*>(objectId);
1089 Field* f = FromFieldId(fieldId);
1090
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001091 JDWP::JdwpTag tag = BasicTagFromDescriptor(FieldHelper(f).GetTypeDescriptor());
Elliott Hughesaed4be92011-12-02 16:16:23 -08001092
1093 if (IsPrimitiveTag(tag)) {
1094 if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
1095 f->Set64(o, value);
1096 } else {
1097 f->Set32(o, value);
1098 }
1099 } else {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001100 Object* v = gRegistry->Get<Object*>(value);
1101 Class* field_type = FieldHelper(f).GetType();
1102 if (!field_type->IsAssignableFrom(v->GetClass())) {
1103 return JDWP::ERR_INVALID_OBJECT;
1104 }
1105 f->SetObject(o, v);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001106 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001107
1108 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001109}
1110
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001111void Dbg::GetStaticFieldValue(JDWP::FieldId fieldId, JDWP::ExpandBuf* pReply) {
1112 GetFieldValue(0, fieldId, pReply);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001113}
1114
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001115JDWP::JdwpError Dbg::SetStaticFieldValue(JDWP::FieldId fieldId, uint64_t value, int width) {
1116 return SetFieldValue(0, fieldId, value, width);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001117}
1118
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001119std::string Dbg::StringToUtf8(JDWP::ObjectId strId) {
1120 String* s = gRegistry->Get<String*>(strId);
1121 return s->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001122}
1123
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001124Thread* DecodeThread(JDWP::ObjectId threadId) {
1125 Object* thread_peer = gRegistry->Get<Object*>(threadId);
1126 CHECK(thread_peer != NULL);
1127 return Thread::FromManagedThread(thread_peer);
1128}
1129
1130bool Dbg::GetThreadName(JDWP::ObjectId threadId, std::string& name) {
1131 ScopedThreadListLock thread_list_lock;
1132 Thread* thread = DecodeThread(threadId);
1133 if (thread == NULL) {
1134 return false;
1135 }
Elliott Hughes899e7892012-01-24 14:57:32 -08001136 StringAppendF(&name, "<%d> %s", thread->GetThinLockId(), thread->GetThreadName()->ToModifiedUtf8().c_str());
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001137 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001138}
1139
1140JDWP::ObjectId Dbg::GetThreadGroup(JDWP::ObjectId threadId) {
Elliott Hughes499c5132011-11-17 14:55:11 -08001141 Object* thread = gRegistry->Get<Object*>(threadId);
1142 CHECK(thread != NULL);
1143
1144 Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/Thread;");
1145 CHECK(c != NULL);
1146 Field* f = c->FindInstanceField("group", "Ljava/lang/ThreadGroup;");
1147 CHECK(f != NULL);
1148 Object* group = f->GetObject(thread);
1149 CHECK(group != NULL);
1150 return gRegistry->Add(group);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001151}
1152
Elliott Hughes499c5132011-11-17 14:55:11 -08001153std::string Dbg::GetThreadGroupName(JDWP::ObjectId threadGroupId) {
1154 Object* thread_group = gRegistry->Get<Object*>(threadGroupId);
1155 CHECK(thread_group != NULL);
1156
1157 Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/ThreadGroup;");
1158 CHECK(c != NULL);
1159 Field* f = c->FindInstanceField("name", "Ljava/lang/String;");
1160 CHECK(f != NULL);
1161 String* s = reinterpret_cast<String*>(f->GetObject(thread_group));
1162 return s->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001163}
1164
1165JDWP::ObjectId Dbg::GetThreadGroupParent(JDWP::ObjectId threadGroupId) {
Elliott Hughes4e235312011-12-02 11:34:15 -08001166 Object* thread_group = gRegistry->Get<Object*>(threadGroupId);
1167 CHECK(thread_group != NULL);
1168
1169 Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/ThreadGroup;");
1170 CHECK(c != NULL);
1171 Field* f = c->FindInstanceField("parent", "Ljava/lang/ThreadGroup;");
1172 CHECK(f != NULL);
1173 Object* parent = f->GetObject(thread_group);
1174 return gRegistry->Add(parent);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001175}
1176
Elliott Hughes499c5132011-11-17 14:55:11 -08001177static Object* GetStaticThreadGroup(const char* field_name) {
1178 Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/ThreadGroup;");
1179 CHECK(c != NULL);
1180 Field* f = c->FindStaticField(field_name, "Ljava/lang/ThreadGroup;");
1181 CHECK(f != NULL);
1182 Object* group = f->GetObject(NULL);
1183 CHECK(group != NULL);
1184 return group;
1185}
1186
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001187JDWP::ObjectId Dbg::GetSystemThreadGroupId() {
Elliott Hughes499c5132011-11-17 14:55:11 -08001188 return gRegistry->Add(GetStaticThreadGroup("mSystem"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001189}
1190
1191JDWP::ObjectId Dbg::GetMainThreadGroupId() {
Elliott Hughes499c5132011-11-17 14:55:11 -08001192 return gRegistry->Add(GetStaticThreadGroup("mMain"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001193}
1194
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001195bool Dbg::GetThreadStatus(JDWP::ObjectId threadId, JDWP::JdwpThreadStatus* pThreadStatus, JDWP::JdwpSuspendStatus* pSuspendStatus) {
Elliott Hughes499c5132011-11-17 14:55:11 -08001196 ScopedThreadListLock thread_list_lock;
1197
1198 Thread* thread = DecodeThread(threadId);
1199 if (thread == NULL) {
1200 return false;
1201 }
1202
1203 switch (thread->GetState()) {
1204 case Thread::kTerminated: *pThreadStatus = JDWP::TS_ZOMBIE; break;
1205 case Thread::kRunnable: *pThreadStatus = JDWP::TS_RUNNING; break;
1206 case Thread::kTimedWaiting: *pThreadStatus = JDWP::TS_SLEEPING; break;
1207 case Thread::kBlocked: *pThreadStatus = JDWP::TS_MONITOR; break;
1208 case Thread::kWaiting: *pThreadStatus = JDWP::TS_WAIT; break;
1209 case Thread::kInitializing: *pThreadStatus = JDWP::TS_ZOMBIE; break;
1210 case Thread::kStarting: *pThreadStatus = JDWP::TS_ZOMBIE; break;
1211 case Thread::kNative: *pThreadStatus = JDWP::TS_RUNNING; break;
1212 case Thread::kVmWait: *pThreadStatus = JDWP::TS_WAIT; break;
1213 case Thread::kSuspended: *pThreadStatus = JDWP::TS_RUNNING; break;
1214 default:
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001215 LOG(FATAL) << "Unknown thread state " << thread->GetState();
Elliott Hughes499c5132011-11-17 14:55:11 -08001216 }
1217
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001218 *pSuspendStatus = (thread->IsSuspended() ? JDWP::SUSPEND_STATUS_SUSPENDED : JDWP::SUSPEND_STATUS_NOT_SUSPENDED);
Elliott Hughes499c5132011-11-17 14:55:11 -08001219
1220 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001221}
1222
1223uint32_t Dbg::GetThreadSuspendCount(JDWP::ObjectId threadId) {
Elliott Hughesd07986f2011-12-06 18:27:45 -08001224 return DecodeThread(threadId)->GetSuspendCount();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001225}
1226
1227bool Dbg::ThreadExists(JDWP::ObjectId threadId) {
Elliott Hughes761928d2011-11-16 18:33:03 -08001228 return DecodeThread(threadId) != NULL;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001229}
1230
1231bool Dbg::IsSuspended(JDWP::ObjectId threadId) {
Elliott Hughes761928d2011-11-16 18:33:03 -08001232 return DecodeThread(threadId)->IsSuspended();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001233}
1234
Elliott Hughesa2155262011-11-16 16:26:58 -08001235void Dbg::GetThreadGroupThreadsImpl(Object* thread_group, JDWP::ObjectId** ppThreadIds, uint32_t* pThreadCount) {
1236 struct ThreadListVisitor {
1237 static void Visit(Thread* t, void* arg) {
1238 reinterpret_cast<ThreadListVisitor*>(arg)->Visit(t);
1239 }
1240
1241 void Visit(Thread* t) {
1242 if (t == Dbg::GetDebugThread()) {
1243 // Skip the JDWP thread. Some debuggers get bent out of shape when they can't suspend and
1244 // query all threads, so it's easier if we just don't tell them about this thread.
1245 return;
1246 }
1247 if (thread_group == NULL || t->GetThreadGroup() == thread_group) {
1248 threads.push_back(gRegistry->Add(t->GetPeer()));
1249 }
1250 }
1251
1252 Object* thread_group;
1253 std::vector<JDWP::ObjectId> threads;
1254 };
1255
1256 ThreadListVisitor tlv;
1257 tlv.thread_group = thread_group;
1258
1259 {
1260 ScopedThreadListLock thread_list_lock;
1261 Runtime::Current()->GetThreadList()->ForEach(ThreadListVisitor::Visit, &tlv);
1262 }
1263
1264 *pThreadCount = tlv.threads.size();
1265 if (*pThreadCount == 0) {
1266 *ppThreadIds = NULL;
1267 } else {
1268 *ppThreadIds = new JDWP::ObjectId[*pThreadCount];
1269 for (size_t i = 0; i < *pThreadCount; ++i) {
1270 (*ppThreadIds)[i] = tlv.threads[i];
1271 }
1272 }
1273}
1274
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001275void Dbg::GetThreadGroupThreads(JDWP::ObjectId threadGroupId, JDWP::ObjectId** ppThreadIds, uint32_t* pThreadCount) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001276 GetThreadGroupThreadsImpl(gRegistry->Get<Object*>(threadGroupId), ppThreadIds, pThreadCount);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001277}
1278
1279void Dbg::GetAllThreads(JDWP::ObjectId** ppThreadIds, uint32_t* pThreadCount) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001280 GetThreadGroupThreadsImpl(NULL, ppThreadIds, pThreadCount);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001281}
1282
1283int Dbg::GetThreadFrameCount(JDWP::ObjectId threadId) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001284 ScopedThreadListLock thread_list_lock;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001285 struct CountStackDepthVisitor : public Thread::StackVisitor {
1286 CountStackDepthVisitor() : depth(0) {}
Elliott Hughesf8a2df72011-12-01 12:19:54 -08001287 virtual void VisitFrame(const Frame& f, uintptr_t) {
1288 // TODO: we'll need to skip callee-save frames too.
1289 if (f.HasMethod()) {
1290 ++depth;
1291 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001292 }
1293 size_t depth;
1294 };
1295 CountStackDepthVisitor visitor;
1296 DecodeThread(threadId)->WalkStack(&visitor);
1297 return visitor.depth;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001298}
1299
Elliott Hughes03181a82011-11-17 17:22:21 -08001300bool Dbg::GetThreadFrame(JDWP::ObjectId threadId, int desired_frame_number, JDWP::FrameId* pFrameId, JDWP::JdwpLocation* pLoc) {
1301 ScopedThreadListLock thread_list_lock;
1302 struct GetFrameVisitor : public Thread::StackVisitor {
1303 GetFrameVisitor(int desired_frame_number, JDWP::FrameId* pFrameId, JDWP::JdwpLocation* pLoc)
Elliott Hughesba8eee12012-01-24 20:25:24 -08001304 : found(false), depth(0), desired_frame_number(desired_frame_number), pFrameId(pFrameId), pLoc(pLoc) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001305 }
1306 virtual void VisitFrame(const Frame& f, uintptr_t pc) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -08001307 // TODO: we'll need to skip callee-save frames too.
Elliott Hughes03181a82011-11-17 17:22:21 -08001308 if (!f.HasMethod()) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -08001309 return; // The debugger can't do anything useful with a frame that has no Method*.
Elliott Hughes03181a82011-11-17 17:22:21 -08001310 }
1311
1312 if (depth == desired_frame_number) {
1313 *pFrameId = reinterpret_cast<JDWP::FrameId>(f.GetSP());
Elliott Hughesd07986f2011-12-06 18:27:45 -08001314 SetLocation(*pLoc, f.GetMethod(), pc);
Elliott Hughes03181a82011-11-17 17:22:21 -08001315 found = true;
1316 }
1317 ++depth;
1318 }
1319 bool found;
1320 int depth;
1321 int desired_frame_number;
1322 JDWP::FrameId* pFrameId;
1323 JDWP::JdwpLocation* pLoc;
1324 };
1325 GetFrameVisitor visitor(desired_frame_number, pFrameId, pLoc);
1326 visitor.desired_frame_number = desired_frame_number;
1327 DecodeThread(threadId)->WalkStack(&visitor);
1328 return visitor.found;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001329}
1330
1331JDWP::ObjectId Dbg::GetThreadSelfId() {
Elliott Hughes475fc232011-10-25 15:00:35 -07001332 return gRegistry->Add(Thread::Current()->GetPeer());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001333}
1334
Elliott Hughes475fc232011-10-25 15:00:35 -07001335void Dbg::SuspendVM() {
Elliott Hughesa2155262011-11-16 16:26:58 -08001336 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 -07001337 Runtime::Current()->GetThreadList()->SuspendAll(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001338}
1339
1340void Dbg::ResumeVM() {
Elliott Hughes475fc232011-10-25 15:00:35 -07001341 Runtime::Current()->GetThreadList()->ResumeAll(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001342}
1343
1344void Dbg::SuspendThread(JDWP::ObjectId threadId) {
Elliott Hughes4e235312011-12-02 11:34:15 -08001345 Object* peer = gRegistry->Get<Object*>(threadId);
1346 ScopedThreadListLock thread_list_lock;
1347 Thread* thread = Thread::FromManagedThread(peer);
1348 if (thread == NULL) {
1349 LOG(WARNING) << "No such thread for suspend: " << peer;
1350 return;
1351 }
1352 Runtime::Current()->GetThreadList()->Suspend(thread, true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001353}
1354
1355void Dbg::ResumeThread(JDWP::ObjectId threadId) {
Elliott Hughes4e235312011-12-02 11:34:15 -08001356 Object* peer = gRegistry->Get<Object*>(threadId);
1357 ScopedThreadListLock thread_list_lock;
1358 Thread* thread = Thread::FromManagedThread(peer);
1359 if (thread == NULL) {
1360 LOG(WARNING) << "No such thread for resume: " << peer;
1361 return;
1362 }
1363 Runtime::Current()->GetThreadList()->Resume(thread, true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001364}
1365
1366void Dbg::SuspendSelf() {
Elliott Hughes475fc232011-10-25 15:00:35 -07001367 Runtime::Current()->GetThreadList()->SuspendSelfForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001368}
1369
Elliott Hughesd07986f2011-12-06 18:27:45 -08001370bool Dbg::GetThisObject(JDWP::FrameId frameId, JDWP::ObjectId* pThisId) {
Elliott Hughes86b00102011-12-05 17:54:26 -08001371 Method** sp = reinterpret_cast<Method**>(frameId);
1372 Frame f;
1373 f.SetSP(sp);
Elliott Hughes86b00102011-12-05 17:54:26 -08001374 Method* m = f.GetMethod();
1375
1376 Object* o = NULL;
1377 if (!m->IsNative() && !m->IsStatic()) {
Elliott Hughesd07986f2011-12-06 18:27:45 -08001378 uint16_t reg = DemangleSlot(0, f);
Elliott Hughes86b00102011-12-05 17:54:26 -08001379 o = reinterpret_cast<Object*>(f.GetVReg(m, reg));
1380 }
1381 *pThisId = gRegistry->Add(o);
1382 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001383}
1384
Elliott Hughescccd84f2011-12-05 16:51:54 -08001385void 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 -08001386 Method** sp = reinterpret_cast<Method**>(frameId);
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001387 Frame f;
1388 f.SetSP(sp);
1389 uint16_t reg = DemangleSlot(slot, f);
1390 Method* m = f.GetMethod();
1391
1392 const VmapTable vmap_table(m->GetVmapTableRaw());
1393 uint32_t vmap_offset;
1394 if (vmap_table.IsInContext(reg, vmap_offset)) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001395 UNIMPLEMENTED(FATAL) << "Don't know how to pull locals from callee save frames: " << vmap_offset;
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001396 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001397
1398 switch (tag) {
1399 case JDWP::JT_BOOLEAN:
1400 {
Elliott Hughescccd84f2011-12-05 16:51:54 -08001401 CHECK_EQ(width, 1U);
Elliott Hughes1bba14f2011-12-01 18:00:36 -08001402 uint32_t intVal = f.GetVReg(m, reg);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001403 VLOG(jdwp) << "get boolean local " << reg << " = " << intVal;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001404 JDWP::Set1(buf+1, intVal != 0);
1405 }
1406 break;
1407 case JDWP::JT_BYTE:
1408 {
Elliott Hughescccd84f2011-12-05 16:51:54 -08001409 CHECK_EQ(width, 1U);
Elliott Hughes1bba14f2011-12-01 18:00:36 -08001410 uint32_t intVal = f.GetVReg(m, reg);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001411 VLOG(jdwp) << "get byte local " << reg << " = " << intVal;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001412 JDWP::Set1(buf+1, intVal);
1413 }
1414 break;
1415 case JDWP::JT_SHORT:
1416 case JDWP::JT_CHAR:
1417 {
Elliott Hughescccd84f2011-12-05 16:51:54 -08001418 CHECK_EQ(width, 2U);
Elliott Hughes1bba14f2011-12-01 18:00:36 -08001419 uint32_t intVal = f.GetVReg(m, reg);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001420 VLOG(jdwp) << "get short/char local " << reg << " = " << intVal;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001421 JDWP::Set2BE(buf+1, intVal);
1422 }
1423 break;
1424 case JDWP::JT_INT:
1425 case JDWP::JT_FLOAT:
1426 {
Elliott Hughescccd84f2011-12-05 16:51:54 -08001427 CHECK_EQ(width, 4U);
Elliott Hughes1bba14f2011-12-01 18:00:36 -08001428 uint32_t intVal = f.GetVReg(m, reg);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001429 VLOG(jdwp) << "get int/float local " << reg << " = " << intVal;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001430 JDWP::Set4BE(buf+1, intVal);
1431 }
1432 break;
1433 case JDWP::JT_ARRAY:
1434 {
Elliott Hughescccd84f2011-12-05 16:51:54 -08001435 CHECK_EQ(width, sizeof(JDWP::ObjectId));
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001436 Object* o = reinterpret_cast<Object*>(f.GetVReg(m, reg));
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001437 VLOG(jdwp) << "get array local " << reg << " = " << o;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001438 if (o != NULL && !Heap::IsHeapAddress(o)) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001439 LOG(FATAL) << "Register " << reg << " expected to hold array: " << o;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001440 }
1441 JDWP::SetObjectId(buf+1, gRegistry->Add(o));
1442 }
1443 break;
1444 case JDWP::JT_OBJECT:
1445 {
Elliott Hughescccd84f2011-12-05 16:51:54 -08001446 CHECK_EQ(width, sizeof(JDWP::ObjectId));
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001447 Object* o = reinterpret_cast<Object*>(f.GetVReg(m, reg));
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001448 VLOG(jdwp) << "get object local " << reg << " = " << o;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001449 if (o != NULL && !Heap::IsHeapAddress(o)) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001450 LOG(FATAL) << "Register " << reg << " expected to hold object: " << o;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001451 }
1452 tag = TagFromObject(o);
1453 JDWP::SetObjectId(buf+1, gRegistry->Add(o));
1454 }
1455 break;
1456 case JDWP::JT_DOUBLE:
1457 case JDWP::JT_LONG:
1458 {
Elliott Hughescccd84f2011-12-05 16:51:54 -08001459 CHECK_EQ(width, 8U);
Elliott Hughes1bba14f2011-12-01 18:00:36 -08001460 uint32_t lo = f.GetVReg(m, reg);
1461 uint64_t hi = f.GetVReg(m, reg + 1);
1462 uint64_t longVal = (hi << 32) | lo;
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001463 VLOG(jdwp) << "get double/long local " << hi << ":" << lo << " = " << longVal;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001464 JDWP::Set8BE(buf+1, longVal);
1465 }
1466 break;
1467 default:
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001468 LOG(FATAL) << "Unknown tag " << tag;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001469 break;
1470 }
1471
1472 // Prepend tag, which may have been updated.
1473 JDWP::Set1(buf, tag);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001474}
1475
Elliott Hughesdbb40792011-11-18 17:05:22 -08001476void 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 -08001477 Method** sp = reinterpret_cast<Method**>(frameId);
1478 Frame f;
1479 f.SetSP(sp);
1480 uint16_t reg = DemangleSlot(slot, f);
1481 Method* m = f.GetMethod();
1482
1483 const VmapTable vmap_table(m->GetVmapTableRaw());
1484 uint32_t vmap_offset;
1485 if (vmap_table.IsInContext(reg, vmap_offset)) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001486 UNIMPLEMENTED(FATAL) << "Don't know how to pull locals from callee save frames: " << vmap_offset;
Elliott Hughescccd84f2011-12-05 16:51:54 -08001487 }
1488
1489 switch (tag) {
1490 case JDWP::JT_BOOLEAN:
1491 case JDWP::JT_BYTE:
1492 CHECK_EQ(width, 1U);
1493 f.SetVReg(m, reg, static_cast<uint32_t>(value));
1494 break;
1495 case JDWP::JT_SHORT:
1496 case JDWP::JT_CHAR:
1497 CHECK_EQ(width, 2U);
1498 f.SetVReg(m, reg, static_cast<uint32_t>(value));
1499 break;
1500 case JDWP::JT_INT:
1501 case JDWP::JT_FLOAT:
1502 CHECK_EQ(width, 4U);
1503 f.SetVReg(m, reg, static_cast<uint32_t>(value));
1504 break;
1505 case JDWP::JT_ARRAY:
1506 case JDWP::JT_OBJECT:
1507 case JDWP::JT_STRING:
1508 {
1509 CHECK_EQ(width, sizeof(JDWP::ObjectId));
1510 Object* o = gRegistry->Get<Object*>(static_cast<JDWP::ObjectId>(value));
1511 f.SetVReg(m, reg, static_cast<uint32_t>(reinterpret_cast<uintptr_t>(o)));
1512 }
1513 break;
1514 case JDWP::JT_DOUBLE:
1515 case JDWP::JT_LONG:
1516 CHECK_EQ(width, 8U);
1517 f.SetVReg(m, reg, static_cast<uint32_t>(value));
1518 f.SetVReg(m, reg + 1, static_cast<uint32_t>(value >> 32));
1519 break;
1520 default:
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001521 LOG(FATAL) << "Unknown tag " << tag;
Elliott Hughescccd84f2011-12-05 16:51:54 -08001522 break;
1523 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001524}
1525
1526void Dbg::PostLocationEvent(const Method* method, int pcOffset, Object* thisPtr, int eventFlags) {
1527 UNIMPLEMENTED(FATAL);
1528}
1529
Elliott Hughesd07986f2011-12-06 18:27:45 -08001530void Dbg::PostException(Method** sp, Method* throwMethod, uintptr_t throwNativePc, Method* catchMethod, uintptr_t catchNativePc, Object* exception) {
Ian Rogers0ad5bb82011-12-07 10:16:32 -08001531 if (!gDebuggerActive) {
1532 return;
1533 }
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001534
Elliott Hughesd07986f2011-12-06 18:27:45 -08001535 JDWP::JdwpLocation throw_location;
1536 SetLocation(throw_location, throwMethod, throwNativePc);
1537 JDWP::JdwpLocation catch_location;
1538 SetLocation(catch_location, catchMethod, catchNativePc);
1539
1540 // We need 'this' for InstanceOnly filters.
1541 JDWP::ObjectId this_id;
1542 GetThisObject(reinterpret_cast<JDWP::FrameId>(sp), &this_id);
1543
1544 /*
1545 * Hand the event to the JDWP exception handler. Note we're using the
1546 * "NoReg" objectID on the exception, which is not strictly correct --
1547 * the exception object WILL be passed up to the debugger if the
1548 * debugger is interested in the event. We do this because the current
1549 * implementation of the debugger object registry never throws anything
1550 * away, and some people were experiencing a fatal build up of exception
1551 * objects when dealing with certain libraries.
1552 */
1553 JDWP::ObjectId exception_id = static_cast<JDWP::ObjectId>(reinterpret_cast<uintptr_t>(exception));
1554 JDWP::RefTypeId exception_class_id = gRegistry->Add(exception->GetClass());
1555
1556 gJdwpState->PostException(&throw_location, exception_id, exception_class_id, &catch_location, this_id);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001557}
1558
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001559void Dbg::PostClassPrepare(Class* c) {
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001560 if (!gDebuggerActive) {
1561 return;
1562 }
1563
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001564 // OLD-TODO - we currently always send both "verified" and "prepared" since
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001565 // debuggers seem to like that. There might be some advantage to honesty,
1566 // since the class may not yet be verified.
1567 int state = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
1568 JDWP::JdwpTypeTag tag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
1569 gJdwpState->PostClassPrepare(tag, gRegistry->Add(c), ClassHelper(c).GetDescriptor(), state);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001570}
1571
1572bool Dbg::WatchLocation(const JDWP::JdwpLocation* pLoc) {
1573 UNIMPLEMENTED(FATAL);
1574 return false;
1575}
1576
1577void Dbg::UnwatchLocation(const JDWP::JdwpLocation* pLoc) {
1578 UNIMPLEMENTED(FATAL);
1579}
1580
1581bool Dbg::ConfigureStep(JDWP::ObjectId threadId, JDWP::JdwpStepSize size, JDWP::JdwpStepDepth depth) {
1582 UNIMPLEMENTED(FATAL);
1583 return false;
1584}
1585
1586void Dbg::UnconfigureStep(JDWP::ObjectId threadId) {
1587 UNIMPLEMENTED(FATAL);
1588}
1589
Elliott Hughesd07986f2011-12-06 18:27:45 -08001590JDWP::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) {
1591 ThreadList* thread_list = Runtime::Current()->GetThreadList();
1592
1593 Thread* targetThread = NULL;
1594 DebugInvokeReq* req = NULL;
1595 {
1596 ScopedThreadListLock thread_list_lock;
1597 targetThread = DecodeThread(threadId);
1598 if (targetThread == NULL) {
1599 LOG(ERROR) << "InvokeMethod request for non-existent thread " << threadId;
1600 return JDWP::ERR_INVALID_THREAD;
1601 }
1602 req = targetThread->GetInvokeReq();
1603 if (!req->ready) {
1604 LOG(ERROR) << "InvokeMethod request for thread not stopped by event: " << *targetThread;
1605 return JDWP::ERR_INVALID_THREAD;
1606 }
1607
1608 /*
1609 * We currently have a bug where we don't successfully resume the
1610 * target thread if the suspend count is too deep. We're expected to
1611 * require one "resume" for each "suspend", but when asked to execute
1612 * a method we have to resume fully and then re-suspend it back to the
1613 * same level. (The easiest way to cause this is to type "suspend"
1614 * multiple times in jdb.)
1615 *
1616 * It's unclear what this means when the event specifies "resume all"
1617 * and some threads are suspended more deeply than others. This is
1618 * a rare problem, so for now we just prevent it from hanging forever
1619 * by rejecting the method invocation request. Without this, we will
1620 * be stuck waiting on a suspended thread.
1621 */
1622 int suspend_count = targetThread->GetSuspendCount();
1623 if (suspend_count > 1) {
1624 LOG(ERROR) << *targetThread << " suspend count too deep for method invocation: " << suspend_count;
1625 return JDWP::ERR_THREAD_SUSPENDED; // Probably not expected here.
1626 }
1627
1628 /*
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001629 * OLD-TODO: ought to screen the various IDs, and verify that the argument
Elliott Hughesd07986f2011-12-06 18:27:45 -08001630 * list is valid.
1631 */
1632 req->receiver_ = gRegistry->Get<Object*>(objectId);
1633 req->thread_ = gRegistry->Get<Object*>(threadId);
1634 req->class_ = gRegistry->Get<Class*>(classId);
1635 req->method_ = FromMethodId(methodId);
1636 req->num_args_ = numArgs;
1637 req->arg_array_ = argArray;
1638 req->options_ = options;
1639 req->invoke_needed_ = true;
1640 }
1641
1642 // The fact that we've released the thread list lock is a bit risky --- if the thread goes
1643 // away we're sitting high and dry -- but we must release this before the ResumeAllThreads
1644 // call, and it's unwise to hold it during WaitForSuspend.
1645
1646 {
1647 /*
1648 * We change our (JDWP thread) status, which should be THREAD_RUNNING,
1649 * so the VM can suspend for a GC if the invoke request causes us to
1650 * run out of memory. It's also a good idea to change it before locking
1651 * the invokeReq mutex, although that should never be held for long.
1652 */
1653 ScopedThreadStateChange tsc(Thread::Current(), Thread::kVmWait);
1654
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001655 VLOG(jdwp) << " Transferring control to event thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08001656 {
1657 MutexLock mu(req->lock_);
1658
1659 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001660 VLOG(jdwp) << " Resuming all threads";
Elliott Hughesd07986f2011-12-06 18:27:45 -08001661 thread_list->ResumeAll(true);
1662 } else {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001663 VLOG(jdwp) << " Resuming event thread only";
Elliott Hughesd07986f2011-12-06 18:27:45 -08001664 thread_list->Resume(targetThread, true);
1665 }
1666
1667 // Wait for the request to finish executing.
1668 while (req->invoke_needed_) {
1669 req->cond_.Wait(req->lock_);
1670 }
1671 }
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001672 VLOG(jdwp) << " Control has returned from event thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08001673
1674 /* wait for thread to re-suspend itself */
1675 targetThread->WaitUntilSuspended();
1676 //dvmWaitForSuspend(targetThread);
1677 }
1678
1679 /*
1680 * Suspend the threads. We waited for the target thread to suspend
1681 * itself, so all we need to do is suspend the others.
1682 *
1683 * The suspendAllThreads() call will double-suspend the event thread,
1684 * so we want to resume the target thread once to keep the books straight.
1685 */
1686 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001687 VLOG(jdwp) << " Suspending all threads";
Elliott Hughesd07986f2011-12-06 18:27:45 -08001688 thread_list->SuspendAll(true);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001689 VLOG(jdwp) << " Resuming event thread to balance the count";
Elliott Hughesd07986f2011-12-06 18:27:45 -08001690 thread_list->Resume(targetThread, true);
1691 }
1692
1693 // Copy the result.
1694 *pResultTag = req->result_tag;
1695 if (IsPrimitiveTag(req->result_tag)) {
1696 *pResultValue = req->result_value.j;
1697 } else {
1698 *pResultValue = gRegistry->Add(req->result_value.l);
1699 }
1700 *pExceptionId = req->exception;
1701 return req->error;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001702}
1703
1704void Dbg::ExecuteMethod(DebugInvokeReq* pReq) {
Elliott Hughesd07986f2011-12-06 18:27:45 -08001705 Thread* self = Thread::Current();
1706
1707 // We can be called while an exception is pending in the VM. We need
1708 // to preserve that across the method invocation.
1709 SirtRef<Throwable> old_exception(self->GetException());
1710 self->ClearException();
1711
1712 ScopedThreadStateChange tsc(self, Thread::kRunnable);
1713
1714 // Translate the method through the vtable, unless the debugger wants to suppress it.
1715 Method* m = pReq->method_;
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001716 VLOG(jdwp) << "ExecuteMethod " << PrettyMethod(m);
Elliott Hughesd07986f2011-12-06 18:27:45 -08001717 if ((pReq->options_ & JDWP::INVOKE_NONVIRTUAL) == 0 && pReq->receiver_ != NULL) {
1718 m = pReq->class_->FindVirtualMethodForVirtualOrInterface(pReq->method_);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001719 VLOG(jdwp) << "ExecuteMethod " << PrettyMethod(m);
Elliott Hughesd07986f2011-12-06 18:27:45 -08001720 }
1721 CHECK(m != NULL);
1722
1723 CHECK_EQ(sizeof(jvalue), sizeof(uint64_t));
1724
1725 pReq->result_value = InvokeWithJValues(self, pReq->receiver_, m, reinterpret_cast<JValue*>(pReq->arg_array_));
1726
1727 pReq->exception = gRegistry->Add(self->GetException());
1728 pReq->result_tag = BasicTagFromDescriptor(MethodHelper(m).GetShorty());
1729 if (pReq->exception != 0) {
1730 Object* exc = self->GetException();
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001731 VLOG(jdwp) << " JDWP invocation returning with exception=" << exc << " " << PrettyTypeOf(exc);
Elliott Hughesd07986f2011-12-06 18:27:45 -08001732 self->ClearException();
1733 pReq->result_value.j = 0;
1734 } else if (pReq->result_tag == JDWP::JT_OBJECT) {
1735 /* if no exception thrown, examine object result more closely */
1736 JDWP::JdwpTag new_tag = TagFromObject(pReq->result_value.l);
1737 if (new_tag != pReq->result_tag) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001738 VLOG(jdwp) << " JDWP promoted result from " << pReq->result_tag << " to " << new_tag;
Elliott Hughesd07986f2011-12-06 18:27:45 -08001739 pReq->result_tag = new_tag;
1740 }
1741
1742 /*
1743 * Register the object. We don't actually need an ObjectId yet,
1744 * but we do need to be sure that the GC won't move or discard the
1745 * object when we switch out of RUNNING. The ObjectId conversion
1746 * will add the object to the "do not touch" list.
1747 *
1748 * We can't use the "tracked allocation" mechanism here because
1749 * the object is going to be handed off to a different thread.
1750 */
1751 gRegistry->Add(pReq->result_value.l);
1752 }
1753
1754 if (old_exception.get() != NULL) {
1755 self->SetException(old_exception.get());
1756 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001757}
1758
Elliott Hughesd07986f2011-12-06 18:27:45 -08001759/*
1760 * Register an object ID that might not have been registered previously.
1761 *
1762 * Normally this wouldn't happen -- the conversion to an ObjectId would
1763 * have added the object to the registry -- but in some cases (e.g.
1764 * throwing exceptions) we really want to do the registration late.
1765 */
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001766void Dbg::RegisterObjectId(JDWP::ObjectId id) {
Elliott Hughesd07986f2011-12-06 18:27:45 -08001767 gRegistry->Add(reinterpret_cast<Object*>(id));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001768}
1769
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001770/*
1771 * "buf" contains a full JDWP packet, possibly with multiple chunks. We
1772 * need to process each, accumulate the replies, and ship the whole thing
1773 * back.
1774 *
1775 * Returns "true" if we have a reply. The reply buffer is newly allocated,
1776 * and includes the chunk type/length, followed by the data.
1777 *
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001778 * OLD-TODO: we currently assume that the request and reply include a single
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001779 * chunk. If this becomes inconvenient we will need to adapt.
1780 */
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001781bool Dbg::DdmHandlePacket(const uint8_t* buf, int dataLen, uint8_t** pReplyBuf, int* pReplyLen) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001782 CHECK_GE(dataLen, 0);
1783
1784 Thread* self = Thread::Current();
1785 JNIEnv* env = self->GetJniEnv();
1786
Elliott Hughes844f9a02012-01-24 20:19:58 -08001787 static jclass Chunk_class = CacheClass(env, "org/apache/harmony/dalvik/ddmc/Chunk");
1788 static jclass DdmServer_class = CacheClass(env, "org/apache/harmony/dalvik/ddmc/DdmServer");
1789 static jmethodID dispatch_mid = env->GetStaticMethodID(DdmServer_class, "dispatch", "(I[BII)Lorg/apache/harmony/dalvik/ddmc/Chunk;");
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001790 static jfieldID data_fid = env->GetFieldID(Chunk_class, "data", "[B");
1791 static jfieldID length_fid = env->GetFieldID(Chunk_class, "length", "I");
1792 static jfieldID offset_fid = env->GetFieldID(Chunk_class, "offset", "I");
1793 static jfieldID type_fid = env->GetFieldID(Chunk_class, "type", "I");
1794
1795 // Create a byte[] corresponding to 'buf'.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001796 ScopedLocalRef<jbyteArray> dataArray(env, env->NewByteArray(dataLen));
1797 if (dataArray.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001798 LOG(WARNING) << "byte[] allocation failed: " << dataLen;
1799 env->ExceptionClear();
1800 return false;
1801 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001802 env->SetByteArrayRegion(dataArray.get(), 0, dataLen, reinterpret_cast<const jbyte*>(buf));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001803
1804 const int kChunkHdrLen = 8;
1805
1806 // Run through and find all chunks. [Currently just find the first.]
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001807 ScopedByteArrayRO contents(env, dataArray.get());
Elliott Hughesf7c3b662011-10-27 12:04:56 -07001808 jint type = JDWP::Get4BE(reinterpret_cast<const uint8_t*>(&contents[0]));
1809 jint length = JDWP::Get4BE(reinterpret_cast<const uint8_t*>(&contents[4]));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001810 jint offset = kChunkHdrLen;
1811 if (offset + length > dataLen) {
1812 LOG(WARNING) << StringPrintf("bad chunk found (len=%u pktLen=%d)", length, dataLen);
1813 return false;
1814 }
1815
1816 // Call "private static Chunk dispatch(int type, byte[] data, int offset, int length)".
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001817 ScopedLocalRef<jobject> chunk(env, env->CallStaticObjectMethod(DdmServer_class, dispatch_mid, type, dataArray.get(), offset, length));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001818 if (env->ExceptionCheck()) {
1819 LOG(INFO) << StringPrintf("Exception thrown by dispatcher for 0x%08x", type);
1820 env->ExceptionDescribe();
1821 env->ExceptionClear();
1822 return false;
1823 }
1824
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001825 if (chunk.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001826 return false;
1827 }
1828
1829 /*
1830 * Pull the pieces out of the chunk. We copy the results into a
1831 * newly-allocated buffer that the caller can free. We don't want to
1832 * continue using the Chunk object because nothing has a reference to it.
1833 *
1834 * We could avoid this by returning type/data/offset/length and having
1835 * the caller be aware of the object lifetime issues, but that
1836 * integrates the JDWP code more tightly into the VM, and doesn't work
1837 * if we have responses for multiple chunks.
1838 *
1839 * So we're pretty much stuck with copying data around multiple times.
1840 */
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001841 ScopedLocalRef<jbyteArray> replyData(env, reinterpret_cast<jbyteArray>(env->GetObjectField(chunk.get(), data_fid)));
1842 length = env->GetIntField(chunk.get(), length_fid);
1843 offset = env->GetIntField(chunk.get(), offset_fid);
1844 type = env->GetIntField(chunk.get(), type_fid);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001845
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001846 VLOG(jdwp) << StringPrintf("DDM reply: type=0x%08x data=%p offset=%d length=%d", type, replyData.get(), offset, length);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001847 if (length == 0 || replyData.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001848 return false;
1849 }
1850
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001851 jsize replyLength = env->GetArrayLength(replyData.get());
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001852 if (offset + length > replyLength) {
1853 LOG(WARNING) << StringPrintf("chunk off=%d len=%d exceeds reply array len %d", offset, length, replyLength);
1854 return false;
1855 }
1856
1857 uint8_t* reply = new uint8_t[length + kChunkHdrLen];
1858 if (reply == NULL) {
1859 LOG(WARNING) << "malloc failed: " << (length + kChunkHdrLen);
1860 return false;
1861 }
Elliott Hughesf7c3b662011-10-27 12:04:56 -07001862 JDWP::Set4BE(reply + 0, type);
1863 JDWP::Set4BE(reply + 4, length);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001864 env->GetByteArrayRegion(replyData.get(), offset, length, reinterpret_cast<jbyte*>(reply + kChunkHdrLen));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001865
1866 *pReplyBuf = reply;
1867 *pReplyLen = length + kChunkHdrLen;
1868
Elliott Hughesba8eee12012-01-24 20:25:24 -08001869 VLOG(jdwp) << StringPrintf("dvmHandleDdm returning type=%.4s buf=%p len=%d", reinterpret_cast<char*>(reply), reply, length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001870 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001871}
1872
Elliott Hughesa2155262011-11-16 16:26:58 -08001873void Dbg::DdmBroadcast(bool connect) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001874 VLOG(jdwp) << "Broadcasting DDM " << (connect ? "connect" : "disconnect") << "...";
Elliott Hughes47fce012011-10-25 18:37:19 -07001875
1876 Thread* self = Thread::Current();
1877 if (self->GetState() != Thread::kRunnable) {
1878 LOG(ERROR) << "DDM broadcast in thread state " << self->GetState();
1879 /* try anyway? */
1880 }
1881
1882 JNIEnv* env = self->GetJniEnv();
Elliott Hughes844f9a02012-01-24 20:19:58 -08001883 static jclass DdmServer_class = CacheClass(env, "org/apache/harmony/dalvik/ddmc/DdmServer");
Elliott Hughes47fce012011-10-25 18:37:19 -07001884 static jmethodID broadcast_mid = env->GetStaticMethodID(DdmServer_class, "broadcast", "(I)V");
1885 jint event = connect ? 1 /*DdmServer.CONNECTED*/ : 2 /*DdmServer.DISCONNECTED*/;
1886 env->CallStaticVoidMethod(DdmServer_class, broadcast_mid, event);
1887 if (env->ExceptionCheck()) {
1888 LOG(ERROR) << "DdmServer.broadcast " << event << " failed";
1889 env->ExceptionDescribe();
1890 env->ExceptionClear();
1891 }
1892}
1893
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001894void Dbg::DdmConnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08001895 Dbg::DdmBroadcast(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001896}
1897
1898void Dbg::DdmDisconnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08001899 Dbg::DdmBroadcast(false);
Elliott Hughes47fce012011-10-25 18:37:19 -07001900 gDdmThreadNotification = false;
1901}
1902
1903/*
Elliott Hughes82188472011-11-07 18:11:48 -08001904 * Send a notification when a thread starts, stops, or changes its name.
Elliott Hughes47fce012011-10-25 18:37:19 -07001905 *
1906 * Because we broadcast the full set of threads when the notifications are
1907 * first enabled, it's possible for "thread" to be actively executing.
1908 */
Elliott Hughes82188472011-11-07 18:11:48 -08001909void Dbg::DdmSendThreadNotification(Thread* t, uint32_t type) {
Elliott Hughes47fce012011-10-25 18:37:19 -07001910 if (!gDdmThreadNotification) {
1911 return;
1912 }
1913
Elliott Hughes82188472011-11-07 18:11:48 -08001914 if (type == CHUNK_TYPE("THDE")) {
Elliott Hughes47fce012011-10-25 18:37:19 -07001915 uint8_t buf[4];
Elliott Hughesf7c3b662011-10-27 12:04:56 -07001916 JDWP::Set4BE(&buf[0], t->GetThinLockId());
Elliott Hughes47fce012011-10-25 18:37:19 -07001917 Dbg::DdmSendChunk(CHUNK_TYPE("THDE"), 4, buf);
Elliott Hughes82188472011-11-07 18:11:48 -08001918 } else {
1919 CHECK(type == CHUNK_TYPE("THCR") || type == CHUNK_TYPE("THNM")) << type;
Elliott Hughes899e7892012-01-24 14:57:32 -08001920 SirtRef<String> name(t->GetThreadName());
Elliott Hughes82188472011-11-07 18:11:48 -08001921 size_t char_count = (name.get() != NULL) ? name->GetLength() : 0;
1922 const jchar* chars = name->GetCharArray()->GetData();
1923
Elliott Hughes21f32d72011-11-09 17:44:13 -08001924 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08001925 JDWP::Append4BE(bytes, t->GetThinLockId());
1926 JDWP::AppendUtf16BE(bytes, chars, char_count);
Elliott Hughes21f32d72011-11-09 17:44:13 -08001927 CHECK_EQ(bytes.size(), char_count*2 + sizeof(uint32_t)*2);
1928 Dbg::DdmSendChunk(type, bytes);
Elliott Hughes47fce012011-10-25 18:37:19 -07001929 }
1930}
1931
Elliott Hughesa2155262011-11-16 16:26:58 -08001932static void DdmSendThreadStartCallback(Thread* t, void*) {
Elliott Hughes82188472011-11-07 18:11:48 -08001933 Dbg::DdmSendThreadNotification(t, CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07001934}
1935
1936void Dbg::DdmSetThreadNotification(bool enable) {
1937 // We lock the thread list to avoid sending duplicate events or missing
1938 // a thread change. We should be okay holding this lock while sending
1939 // the messages out. (We have to hold it while accessing a live thread.)
Elliott Hughesbbd9d832011-11-07 14:40:00 -08001940 ScopedThreadListLock thread_list_lock;
Elliott Hughes47fce012011-10-25 18:37:19 -07001941
1942 gDdmThreadNotification = enable;
1943 if (enable) {
Elliott Hughesbfe487b2011-10-26 15:48:55 -07001944 Runtime::Current()->GetThreadList()->ForEach(DdmSendThreadStartCallback, NULL);
Elliott Hughes47fce012011-10-25 18:37:19 -07001945 }
1946}
1947
Elliott Hughesa2155262011-11-16 16:26:58 -08001948void Dbg::PostThreadStartOrStop(Thread* t, uint32_t type) {
Elliott Hughes47fce012011-10-25 18:37:19 -07001949 if (gDebuggerActive) {
1950 JDWP::ObjectId id = gRegistry->Add(t->GetPeer());
Elliott Hughes82188472011-11-07 18:11:48 -08001951 gJdwpState->PostThreadChange(id, type == CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07001952 }
Elliott Hughes82188472011-11-07 18:11:48 -08001953 Dbg::DdmSendThreadNotification(t, type);
Elliott Hughes47fce012011-10-25 18:37:19 -07001954}
1955
1956void Dbg::PostThreadStart(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001957 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07001958}
1959
1960void Dbg::PostThreadDeath(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001961 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THDE"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001962}
1963
Elliott Hughes82188472011-11-07 18:11:48 -08001964void Dbg::DdmSendChunk(uint32_t type, size_t byte_count, const uint8_t* buf) {
Elliott Hughes3bb81562011-10-21 18:52:59 -07001965 CHECK(buf != NULL);
1966 iovec vec[1];
1967 vec[0].iov_base = reinterpret_cast<void*>(const_cast<uint8_t*>(buf));
1968 vec[0].iov_len = byte_count;
1969 Dbg::DdmSendChunkV(type, vec, 1);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001970}
1971
Elliott Hughes21f32d72011-11-09 17:44:13 -08001972void Dbg::DdmSendChunk(uint32_t type, const std::vector<uint8_t>& bytes) {
1973 DdmSendChunk(type, bytes.size(), &bytes[0]);
1974}
1975
Elliott Hughescccd84f2011-12-05 16:51:54 -08001976void Dbg::DdmSendChunkV(uint32_t type, const struct iovec* iov, int iov_count) {
Elliott Hughes3bb81562011-10-21 18:52:59 -07001977 if (gJdwpState == NULL) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001978 VLOG(jdwp) << "Debugger thread not active, ignoring DDM send: " << type;
Elliott Hughes3bb81562011-10-21 18:52:59 -07001979 } else {
Elliott Hughescccd84f2011-12-05 16:51:54 -08001980 gJdwpState->DdmSendChunkV(type, iov, iov_count);
Elliott Hughes3bb81562011-10-21 18:52:59 -07001981 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001982}
1983
Elliott Hughes767a1472011-10-26 18:49:02 -07001984int Dbg::DdmHandleHpifChunk(HpifWhen when) {
1985 if (when == HPIF_WHEN_NOW) {
Elliott Hughes7162ad92011-10-27 14:08:42 -07001986 DdmSendHeapInfo(when);
Elliott Hughes767a1472011-10-26 18:49:02 -07001987 return true;
1988 }
1989
1990 if (when != HPIF_WHEN_NEVER && when != HPIF_WHEN_NEXT_GC && when != HPIF_WHEN_EVERY_GC) {
1991 LOG(ERROR) << "invalid HpifWhen value: " << static_cast<int>(when);
1992 return false;
1993 }
1994
1995 gDdmHpifWhen = when;
1996 return true;
1997}
1998
1999bool Dbg::DdmHandleHpsgNhsgChunk(Dbg::HpsgWhen when, Dbg::HpsgWhat what, bool native) {
2000 if (when != HPSG_WHEN_NEVER && when != HPSG_WHEN_EVERY_GC) {
2001 LOG(ERROR) << "invalid HpsgWhen value: " << static_cast<int>(when);
2002 return false;
2003 }
2004
2005 if (what != HPSG_WHAT_MERGED_OBJECTS && what != HPSG_WHAT_DISTINCT_OBJECTS) {
2006 LOG(ERROR) << "invalid HpsgWhat value: " << static_cast<int>(what);
2007 return false;
2008 }
2009
2010 if (native) {
2011 gDdmNhsgWhen = when;
2012 gDdmNhsgWhat = what;
2013 } else {
2014 gDdmHpsgWhen = when;
2015 gDdmHpsgWhat = what;
2016 }
2017 return true;
2018}
2019
Elliott Hughes7162ad92011-10-27 14:08:42 -07002020void Dbg::DdmSendHeapInfo(HpifWhen reason) {
2021 // If there's a one-shot 'when', reset it.
2022 if (reason == gDdmHpifWhen) {
2023 if (gDdmHpifWhen == HPIF_WHEN_NEXT_GC) {
2024 gDdmHpifWhen = HPIF_WHEN_NEVER;
2025 }
2026 }
2027
2028 /*
2029 * Chunk HPIF (client --> server)
2030 *
2031 * Heap Info. General information about the heap,
2032 * suitable for a summary display.
2033 *
2034 * [u4]: number of heaps
2035 *
2036 * For each heap:
2037 * [u4]: heap ID
2038 * [u8]: timestamp in ms since Unix epoch
2039 * [u1]: capture reason (same as 'when' value from server)
2040 * [u4]: max heap size in bytes (-Xmx)
2041 * [u4]: current heap size in bytes
2042 * [u4]: current number of bytes allocated
2043 * [u4]: current number of objects allocated
2044 */
2045 uint8_t heap_count = 1;
Elliott Hughes21f32d72011-11-09 17:44:13 -08002046 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08002047 JDWP::Append4BE(bytes, heap_count);
2048 JDWP::Append4BE(bytes, 1); // Heap id (bogus; we only have one heap).
2049 JDWP::Append8BE(bytes, MilliTime());
2050 JDWP::Append1BE(bytes, reason);
2051 JDWP::Append4BE(bytes, Heap::GetMaxMemory()); // Max allowed heap size in bytes.
2052 JDWP::Append4BE(bytes, Heap::GetTotalMemory()); // Current heap size in bytes.
2053 JDWP::Append4BE(bytes, Heap::GetBytesAllocated());
2054 JDWP::Append4BE(bytes, Heap::GetObjectsAllocated());
Elliott Hughes21f32d72011-11-09 17:44:13 -08002055 CHECK_EQ(bytes.size(), 4U + (heap_count * (4 + 8 + 1 + 4 + 4 + 4 + 4)));
2056 Dbg::DdmSendChunk(CHUNK_TYPE("HPIF"), bytes);
Elliott Hughes767a1472011-10-26 18:49:02 -07002057}
2058
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002059enum HpsgSolidity {
2060 SOLIDITY_FREE = 0,
2061 SOLIDITY_HARD = 1,
2062 SOLIDITY_SOFT = 2,
2063 SOLIDITY_WEAK = 3,
2064 SOLIDITY_PHANTOM = 4,
2065 SOLIDITY_FINALIZABLE = 5,
2066 SOLIDITY_SWEEP = 6,
2067};
2068
2069enum HpsgKind {
2070 KIND_OBJECT = 0,
2071 KIND_CLASS_OBJECT = 1,
2072 KIND_ARRAY_1 = 2,
2073 KIND_ARRAY_2 = 3,
2074 KIND_ARRAY_4 = 4,
2075 KIND_ARRAY_8 = 5,
2076 KIND_UNKNOWN = 6,
2077 KIND_NATIVE = 7,
2078};
2079
2080#define HPSG_PARTIAL (1<<7)
2081#define HPSG_STATE(solidity, kind) ((uint8_t)((((kind) & 0x7) << 3) | ((solidity) & 0x7)))
2082
Ian Rogers30fab402012-01-23 15:43:46 -08002083class HeapChunkContext {
2084 public:
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002085 // Maximum chunk size. Obtain this from the formula:
2086 // (((maximum_heap_size / ALLOCATION_UNIT_SIZE) + 255) / 256) * 2
2087 HeapChunkContext(bool merge, bool native)
Ian Rogers30fab402012-01-23 15:43:46 -08002088 : buf_(16384 - 16),
2089 type_(0),
2090 merge_(merge) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002091 Reset();
2092 if (native) {
Ian Rogers30fab402012-01-23 15:43:46 -08002093 type_ = CHUNK_TYPE("NHSG");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002094 } else {
Ian Rogers30fab402012-01-23 15:43:46 -08002095 type_ = merge ? CHUNK_TYPE("HPSG") : CHUNK_TYPE("HPSO");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002096 }
2097 }
2098
2099 ~HeapChunkContext() {
Ian Rogers30fab402012-01-23 15:43:46 -08002100 if (p_ > &buf_[0]) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002101 Flush();
2102 }
2103 }
2104
2105 void EnsureHeader(const void* chunk_ptr) {
Ian Rogers30fab402012-01-23 15:43:46 -08002106 if (!needHeader_) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002107 return;
2108 }
2109
2110 // Start a new HPSx chunk.
Ian Rogers30fab402012-01-23 15:43:46 -08002111 JDWP::Write4BE(&p_, 1); // Heap id (bogus; we only have one heap).
2112 JDWP::Write1BE(&p_, 8); // Size of allocation unit, in bytes.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002113
Ian Rogers30fab402012-01-23 15:43:46 -08002114 JDWP::Write4BE(&p_, reinterpret_cast<uintptr_t>(chunk_ptr)); // virtual address of segment start.
2115 JDWP::Write4BE(&p_, 0); // offset of this piece (relative to the virtual address).
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002116 // [u4]: length of piece, in allocation units
2117 // We won't know this until we're done, so save the offset and stuff in a dummy value.
Ian Rogers30fab402012-01-23 15:43:46 -08002118 pieceLenField_ = p_;
2119 JDWP::Write4BE(&p_, 0x55555555);
2120 needHeader_ = false;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002121 }
2122
2123 void Flush() {
2124 // Patch the "length of piece" field.
Ian Rogers30fab402012-01-23 15:43:46 -08002125 CHECK_LE(&buf_[0], pieceLenField_);
2126 CHECK_LE(pieceLenField_, p_);
2127 JDWP::Set4BE(pieceLenField_, totalAllocationUnits_);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002128
Ian Rogers30fab402012-01-23 15:43:46 -08002129 Dbg::DdmSendChunk(type_, p_ - &buf_[0], &buf_[0]);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002130 Reset();
2131 }
2132
Ian Rogers30fab402012-01-23 15:43:46 -08002133 static void HeapChunkCallback(void* start, void* end, size_t used_bytes, void* arg) {
2134 reinterpret_cast<HeapChunkContext*>(arg)->HeapChunkCallback(start, end, used_bytes);
Elliott Hughesa2155262011-11-16 16:26:58 -08002135 }
2136
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002137 private:
Elliott Hughesa2155262011-11-16 16:26:58 -08002138 enum { ALLOCATION_UNIT_SIZE = 8 };
2139
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002140 void Reset() {
Ian Rogers30fab402012-01-23 15:43:46 -08002141 p_ = &buf_[0];
2142 totalAllocationUnits_ = 0;
2143 needHeader_ = true;
2144 pieceLenField_ = NULL;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002145 }
2146
Ian Rogers30fab402012-01-23 15:43:46 -08002147 void HeapChunkCallback(void* start, void* end, size_t used_bytes) {
2148 // Note: heap call backs cannot manipulate the heap upon which they are crawling, care is taken
2149 // in the following code not to allocate memory, by ensuring buf_ is of the correct size
2150
2151 const void* user_ptr = used_bytes > 0 ? const_cast<void*>(start) : NULL;
2152 // from malloc.c mem2chunk(mem)
2153 const void* chunk_ptr =
2154 reinterpret_cast<const void*>(reinterpret_cast<const char*>(const_cast<void*>(start)) -
2155 (2 * sizeof(size_t)));
2156 // from malloc.c chunksize
2157 size_t chunk_len = (*reinterpret_cast<size_t* const*>(chunk_ptr))[1] & ~7;
2158
2159
2160 //size_t chunk_len = malloc_usable_size(user_ptr);
Elliott Hughesa2155262011-11-16 16:26:58 -08002161 CHECK_EQ((chunk_len & (ALLOCATION_UNIT_SIZE-1)), 0U);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002162
Elliott Hughesa2155262011-11-16 16:26:58 -08002163 /* Make sure there's enough room left in the buffer.
2164 * We need to use two bytes for every fractional 256
2165 * allocation units used by the chunk.
2166 */
2167 {
2168 size_t needed = (((chunk_len/ALLOCATION_UNIT_SIZE + 255) / 256) * 2);
Ian Rogers30fab402012-01-23 15:43:46 -08002169 size_t bytesLeft = buf_.size() - (size_t)(p_ - &buf_[0]);
Elliott Hughesa2155262011-11-16 16:26:58 -08002170 if (bytesLeft < needed) {
2171 Flush();
2172 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002173
Ian Rogers30fab402012-01-23 15:43:46 -08002174 bytesLeft = buf_.size() - (size_t)(p_ - &buf_[0]);
Elliott Hughesa2155262011-11-16 16:26:58 -08002175 if (bytesLeft < needed) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08002176 LOG(WARNING) << "Chunk is too big to transmit (chunk_len=" << chunk_len << ", " << needed << " bytes)";
Elliott Hughesa2155262011-11-16 16:26:58 -08002177 return;
2178 }
2179 }
2180
2181 // OLD-TODO: notice when there's a gap and start a new heap, or at least a new range.
2182 EnsureHeader(chunk_ptr);
2183
2184 // Determine the type of this chunk.
2185 // OLD-TODO: if context.merge, see if this chunk is different from the last chunk.
2186 // If it's the same, we should combine them.
Ian Rogers30fab402012-01-23 15:43:46 -08002187 uint8_t state = ExamineObject(reinterpret_cast<const Object*>(user_ptr), (type_ == CHUNK_TYPE("NHSG")));
Elliott Hughesa2155262011-11-16 16:26:58 -08002188
2189 // Write out the chunk description.
2190 chunk_len /= ALLOCATION_UNIT_SIZE; // convert to allocation units
Ian Rogers30fab402012-01-23 15:43:46 -08002191 totalAllocationUnits_ += chunk_len;
Elliott Hughesa2155262011-11-16 16:26:58 -08002192 while (chunk_len > 256) {
Ian Rogers30fab402012-01-23 15:43:46 -08002193 *p_++ = state | HPSG_PARTIAL;
2194 *p_++ = 255; // length - 1
Elliott Hughesa2155262011-11-16 16:26:58 -08002195 chunk_len -= 256;
2196 }
Ian Rogers30fab402012-01-23 15:43:46 -08002197 *p_++ = state;
2198 *p_++ = chunk_len - 1;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002199 }
2200
Elliott Hughesa2155262011-11-16 16:26:58 -08002201 uint8_t ExamineObject(const Object* o, bool is_native_heap) {
2202 if (o == NULL) {
2203 return HPSG_STATE(SOLIDITY_FREE, 0);
2204 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002205
Elliott Hughesa2155262011-11-16 16:26:58 -08002206 // It's an allocated chunk. Figure out what it is.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002207
Elliott Hughesa2155262011-11-16 16:26:58 -08002208 // If we're looking at the native heap, we'll just return
2209 // (SOLIDITY_HARD, KIND_NATIVE) for all allocated chunks.
2210 if (is_native_heap || !Heap::IsLiveObjectLocked(o)) {
2211 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
2212 }
2213
2214 Class* c = o->GetClass();
2215 if (c == NULL) {
2216 // The object was probably just created but hasn't been initialized yet.
2217 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
2218 }
2219
2220 if (!Heap::IsHeapAddress(c)) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08002221 LOG(WARNING) << "Invalid class for managed heap object: " << o << " " << c;
Elliott Hughesa2155262011-11-16 16:26:58 -08002222 return HPSG_STATE(SOLIDITY_HARD, KIND_UNKNOWN);
2223 }
2224
2225 if (c->IsClassClass()) {
2226 return HPSG_STATE(SOLIDITY_HARD, KIND_CLASS_OBJECT);
2227 }
2228
2229 if (c->IsArrayClass()) {
2230 if (o->IsObjectArray()) {
2231 return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
2232 }
2233 switch (c->GetComponentSize()) {
2234 case 1: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_1);
2235 case 2: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_2);
2236 case 4: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
2237 case 8: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_8);
2238 }
2239 }
2240
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002241 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
2242 }
2243
Ian Rogers30fab402012-01-23 15:43:46 -08002244 std::vector<uint8_t> buf_;
2245 uint8_t* p_;
2246 uint8_t* pieceLenField_;
2247 size_t totalAllocationUnits_;
2248 uint32_t type_;
2249 bool merge_;
2250 bool needHeader_;
2251
Elliott Hughesa2155262011-11-16 16:26:58 -08002252 DISALLOW_COPY_AND_ASSIGN(HeapChunkContext);
2253};
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002254
2255void Dbg::DdmSendHeapSegments(bool native) {
2256 Dbg::HpsgWhen when;
2257 Dbg::HpsgWhat what;
2258 if (!native) {
2259 when = gDdmHpsgWhen;
2260 what = gDdmHpsgWhat;
2261 } else {
2262 when = gDdmNhsgWhen;
2263 what = gDdmNhsgWhat;
2264 }
2265 if (when == HPSG_WHEN_NEVER) {
2266 return;
2267 }
2268
2269 // Figure out what kind of chunks we'll be sending.
2270 CHECK(what == HPSG_WHAT_MERGED_OBJECTS || what == HPSG_WHAT_DISTINCT_OBJECTS) << static_cast<int>(what);
2271
2272 // First, send a heap start chunk.
2273 uint8_t heap_id[4];
2274 JDWP::Set4BE(&heap_id[0], 1); // Heap id (bogus; we only have one heap).
2275 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHST") : CHUNK_TYPE("HPST"), sizeof(heap_id), heap_id);
2276
2277 // Send a series of heap segment chunks.
Elliott Hughesa2155262011-11-16 16:26:58 -08002278 HeapChunkContext context((what == HPSG_WHAT_MERGED_OBJECTS), native);
2279 if (native) {
Ian Rogers30fab402012-01-23 15:43:46 -08002280 // TODO: enable when bionic has moved to dlmalloc 2.8.5
2281 // dlmalloc_inspect_all(HeapChunkContext::HeapChunkCallback, &context);
2282 UNIMPLEMENTED(WARNING) << "Native heap send heap segments";
Elliott Hughesa2155262011-11-16 16:26:58 -08002283 } else {
Ian Rogers30fab402012-01-23 15:43:46 -08002284 Heap::GetAllocSpace()->Walk(HeapChunkContext::HeapChunkCallback, &context);
Elliott Hughesa2155262011-11-16 16:26:58 -08002285 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002286
2287 // Finally, send a heap end chunk.
2288 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHEN") : CHUNK_TYPE("HPEN"), sizeof(heap_id), heap_id);
Elliott Hughes767a1472011-10-26 18:49:02 -07002289}
2290
Elliott Hughes545a0642011-11-08 19:10:03 -08002291void Dbg::SetAllocTrackingEnabled(bool enabled) {
2292 MutexLock mu(gAllocTrackerLock);
2293 if (enabled) {
2294 if (recent_allocation_records_ == NULL) {
2295 LOG(INFO) << "Enabling alloc tracker (" << kNumAllocRecords << " entries, "
2296 << kMaxAllocRecordStackDepth << " frames --> "
2297 << (sizeof(AllocRecord) * kNumAllocRecords) << " bytes)";
2298 gAllocRecordHead = gAllocRecordCount = 0;
2299 recent_allocation_records_ = new AllocRecord[kNumAllocRecords];
2300 CHECK(recent_allocation_records_ != NULL);
2301 }
2302 } else {
2303 delete[] recent_allocation_records_;
2304 recent_allocation_records_ = NULL;
2305 }
2306}
2307
2308struct AllocRecordStackVisitor : public Thread::StackVisitor {
Elliott Hughesba8eee12012-01-24 20:25:24 -08002309 explicit AllocRecordStackVisitor(AllocRecord* record) : record(record), depth(0) {
Elliott Hughes545a0642011-11-08 19:10:03 -08002310 }
2311
2312 virtual void VisitFrame(const Frame& f, uintptr_t pc) {
2313 if (depth >= kMaxAllocRecordStackDepth) {
2314 return;
2315 }
2316 Method* m = f.GetMethod();
2317 if (m == NULL || m->IsCalleeSaveMethod()) {
2318 return;
2319 }
2320 record->stack[depth].method = m;
2321 record->stack[depth].raw_pc = pc;
2322 ++depth;
2323 }
2324
2325 ~AllocRecordStackVisitor() {
2326 // Clear out any unused stack trace elements.
2327 for (; depth < kMaxAllocRecordStackDepth; ++depth) {
2328 record->stack[depth].method = NULL;
2329 record->stack[depth].raw_pc = 0;
2330 }
2331 }
2332
2333 AllocRecord* record;
2334 size_t depth;
2335};
2336
2337void Dbg::RecordAllocation(Class* type, size_t byte_count) {
2338 Thread* self = Thread::Current();
2339 CHECK(self != NULL);
2340
2341 MutexLock mu(gAllocTrackerLock);
2342 if (recent_allocation_records_ == NULL) {
2343 return;
2344 }
2345
2346 // Advance and clip.
2347 if (++gAllocRecordHead == kNumAllocRecords) {
2348 gAllocRecordHead = 0;
2349 }
2350
2351 // Fill in the basics.
2352 AllocRecord* record = &recent_allocation_records_[gAllocRecordHead];
2353 record->type = type;
2354 record->byte_count = byte_count;
2355 record->thin_lock_id = self->GetThinLockId();
2356
2357 // Fill in the stack trace.
2358 AllocRecordStackVisitor visitor(record);
2359 self->WalkStack(&visitor);
2360
2361 if (gAllocRecordCount < kNumAllocRecords) {
2362 ++gAllocRecordCount;
2363 }
2364}
2365
2366/*
2367 * Return the index of the head element.
2368 *
2369 * We point at the most-recently-written record, so if allocRecordCount is 1
2370 * we want to use the current element. Take "head+1" and subtract count
2371 * from it.
2372 *
2373 * We need to handle underflow in our circular buffer, so we add
2374 * kNumAllocRecords and then mask it back down.
2375 */
2376inline static int headIndex() {
2377 return (gAllocRecordHead+1 + kNumAllocRecords - gAllocRecordCount) & (kNumAllocRecords-1);
2378}
2379
2380void Dbg::DumpRecentAllocations() {
2381 MutexLock mu(gAllocTrackerLock);
2382 if (recent_allocation_records_ == NULL) {
2383 LOG(INFO) << "Not recording tracked allocations";
2384 return;
2385 }
2386
2387 // "i" is the head of the list. We want to start at the end of the
2388 // list and move forward to the tail.
2389 size_t i = headIndex();
2390 size_t count = gAllocRecordCount;
2391
2392 LOG(INFO) << "Tracked allocations, (head=" << gAllocRecordHead << " count=" << count << ")";
2393 while (count--) {
2394 AllocRecord* record = &recent_allocation_records_[i];
2395
Elliott Hughesaa6e1cd2012-01-18 19:26:06 -08002396 LOG(INFO) << StringPrintf(" T=%-2d %6zd ", record->thin_lock_id, record->byte_count)
Elliott Hughes545a0642011-11-08 19:10:03 -08002397 << PrettyClass(record->type);
2398
2399 for (size_t stack_frame = 0; stack_frame < kMaxAllocRecordStackDepth; ++stack_frame) {
2400 const Method* m = record->stack[stack_frame].method;
2401 if (m == NULL) {
2402 break;
2403 }
2404 LOG(INFO) << " " << PrettyMethod(m) << " line " << record->stack[stack_frame].LineNumber();
2405 }
2406
2407 // pause periodically to help logcat catch up
2408 if ((count % 5) == 0) {
2409 usleep(40000);
2410 }
2411
2412 i = (i + 1) & (kNumAllocRecords-1);
2413 }
2414}
2415
2416class StringTable {
2417 public:
2418 StringTable() {
2419 }
2420
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002421 void Add(const char* s) {
Elliott Hughes545a0642011-11-08 19:10:03 -08002422 table_.insert(s);
2423 }
2424
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002425 size_t IndexOf(const char* s) {
Elliott Hughes545a0642011-11-08 19:10:03 -08002426 return std::distance(table_.begin(), table_.find(s));
2427 }
2428
2429 size_t Size() {
2430 return table_.size();
2431 }
2432
2433 void WriteTo(std::vector<uint8_t>& bytes) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002434 typedef std::set<const char*>::const_iterator It; // TODO: C++0x auto
Elliott Hughes545a0642011-11-08 19:10:03 -08002435 for (It it = table_.begin(); it != table_.end(); ++it) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002436 const char* s = *it;
2437 size_t s_len = CountModifiedUtf8Chars(s);
2438 UniquePtr<uint16_t> s_utf16(new uint16_t[s_len]);
2439 ConvertModifiedUtf8ToUtf16(s_utf16.get(), s);
2440 JDWP::AppendUtf16BE(bytes, s_utf16.get(), s_len);
Elliott Hughes545a0642011-11-08 19:10:03 -08002441 }
2442 }
2443
2444 private:
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002445 std::set<const char*> table_;
Elliott Hughes545a0642011-11-08 19:10:03 -08002446 DISALLOW_COPY_AND_ASSIGN(StringTable);
2447};
2448
2449/*
2450 * The data we send to DDMS contains everything we have recorded.
2451 *
2452 * Message header (all values big-endian):
2453 * (1b) message header len (to allow future expansion); includes itself
2454 * (1b) entry header len
2455 * (1b) stack frame len
2456 * (2b) number of entries
2457 * (4b) offset to string table from start of message
2458 * (2b) number of class name strings
2459 * (2b) number of method name strings
2460 * (2b) number of source file name strings
2461 * For each entry:
2462 * (4b) total allocation size
2463 * (2b) threadId
2464 * (2b) allocated object's class name index
2465 * (1b) stack depth
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
2471 * (xb) class name strings
2472 * (xb) method name strings
2473 * (xb) source file strings
2474 *
2475 * As with other DDM traffic, strings are sent as a 4-byte length
2476 * followed by UTF-16 data.
2477 *
2478 * We send up 16-bit unsigned indexes into string tables. In theory there
2479 * can be (kMaxAllocRecordStackDepth * kNumAllocRecords) unique strings in
2480 * each table, but in practice there should be far fewer.
2481 *
2482 * The chief reason for using a string table here is to keep the size of
2483 * the DDMS message to a minimum. This is partly to make the protocol
2484 * efficient, but also because we have to form the whole thing up all at
2485 * once in a memory buffer.
2486 *
2487 * We use separate string tables for class names, method names, and source
2488 * files to keep the indexes small. There will generally be no overlap
2489 * between the contents of these tables.
2490 */
2491jbyteArray Dbg::GetRecentAllocations() {
2492 if (false) {
2493 DumpRecentAllocations();
2494 }
2495
2496 MutexLock mu(gAllocTrackerLock);
2497
2498 /*
2499 * Part 1: generate string tables.
2500 */
2501 StringTable class_names;
2502 StringTable method_names;
2503 StringTable filenames;
2504
2505 int count = gAllocRecordCount;
2506 int idx = headIndex();
2507 while (count--) {
2508 AllocRecord* record = &recent_allocation_records_[idx];
2509
Elliott Hughes91250e02011-12-13 22:30:35 -08002510 class_names.Add(ClassHelper(record->type).GetDescriptor());
Elliott Hughes545a0642011-11-08 19:10:03 -08002511
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002512 MethodHelper mh;
Elliott Hughes545a0642011-11-08 19:10:03 -08002513 for (size_t i = 0; i < kMaxAllocRecordStackDepth; i++) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002514 Method* m = record->stack[i].method;
2515 mh.ChangeMethod(m);
Elliott Hughes545a0642011-11-08 19:10:03 -08002516 if (m != NULL) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002517 class_names.Add(mh.GetDeclaringClassDescriptor());
2518 method_names.Add(mh.GetName());
2519 filenames.Add(mh.GetDeclaringClassSourceFile());
Elliott Hughes545a0642011-11-08 19:10:03 -08002520 }
2521 }
2522
2523 idx = (idx + 1) & (kNumAllocRecords-1);
2524 }
2525
2526 LOG(INFO) << "allocation records: " << gAllocRecordCount;
2527
2528 /*
2529 * Part 2: allocate a buffer and generate the output.
2530 */
2531 std::vector<uint8_t> bytes;
2532
2533 // (1b) message header len (to allow future expansion); includes itself
2534 // (1b) entry header len
2535 // (1b) stack frame len
2536 const int kMessageHeaderLen = 15;
2537 const int kEntryHeaderLen = 9;
2538 const int kStackFrameLen = 8;
2539 JDWP::Append1BE(bytes, kMessageHeaderLen);
2540 JDWP::Append1BE(bytes, kEntryHeaderLen);
2541 JDWP::Append1BE(bytes, kStackFrameLen);
2542
2543 // (2b) number of entries
2544 // (4b) offset to string table from start of message
2545 // (2b) number of class name strings
2546 // (2b) number of method name strings
2547 // (2b) number of source file name strings
2548 JDWP::Append2BE(bytes, gAllocRecordCount);
2549 size_t string_table_offset = bytes.size();
2550 JDWP::Append4BE(bytes, 0); // We'll patch this later...
2551 JDWP::Append2BE(bytes, class_names.Size());
2552 JDWP::Append2BE(bytes, method_names.Size());
2553 JDWP::Append2BE(bytes, filenames.Size());
2554
2555 count = gAllocRecordCount;
2556 idx = headIndex();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002557 ClassHelper kh;
Elliott Hughes545a0642011-11-08 19:10:03 -08002558 while (count--) {
2559 // For each entry:
2560 // (4b) total allocation size
2561 // (2b) thread id
2562 // (2b) allocated object's class name index
2563 // (1b) stack depth
2564 AllocRecord* record = &recent_allocation_records_[idx];
2565 size_t stack_depth = record->GetDepth();
2566 JDWP::Append4BE(bytes, record->byte_count);
2567 JDWP::Append2BE(bytes, record->thin_lock_id);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002568 kh.ChangeClass(record->type);
Elliott Hughes91250e02011-12-13 22:30:35 -08002569 JDWP::Append2BE(bytes, class_names.IndexOf(kh.GetDescriptor()));
Elliott Hughes545a0642011-11-08 19:10:03 -08002570 JDWP::Append1BE(bytes, stack_depth);
2571
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002572 MethodHelper mh;
Elliott Hughes545a0642011-11-08 19:10:03 -08002573 for (size_t stack_frame = 0; stack_frame < stack_depth; ++stack_frame) {
2574 // For each stack frame:
2575 // (2b) method's class name
2576 // (2b) method name
2577 // (2b) method source file
2578 // (2b) line number, clipped to 32767; -2 if native; -1 if no source
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002579 mh.ChangeMethod(record->stack[stack_frame].method);
2580 JDWP::Append2BE(bytes, class_names.IndexOf(mh.GetDeclaringClassDescriptor()));
2581 JDWP::Append2BE(bytes, method_names.IndexOf(mh.GetName()));
2582 JDWP::Append2BE(bytes, filenames.IndexOf(mh.GetDeclaringClassSourceFile()));
Elliott Hughes545a0642011-11-08 19:10:03 -08002583 JDWP::Append2BE(bytes, record->stack[stack_frame].LineNumber());
2584 }
2585
2586 idx = (idx + 1) & (kNumAllocRecords-1);
2587 }
2588
2589 // (xb) class name strings
2590 // (xb) method name strings
2591 // (xb) source file strings
2592 JDWP::Set4BE(&bytes[string_table_offset], bytes.size());
2593 class_names.WriteTo(bytes);
2594 method_names.WriteTo(bytes);
2595 filenames.WriteTo(bytes);
2596
2597 JNIEnv* env = Thread::Current()->GetJniEnv();
2598 jbyteArray result = env->NewByteArray(bytes.size());
2599 if (result != NULL) {
2600 env->SetByteArrayRegion(result, 0, bytes.size(), reinterpret_cast<const jbyte*>(&bytes[0]));
2601 }
2602 return result;
2603}
2604
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002605} // namespace art