blob: 40405ebe2dd83b7b85006124fe24525303dfd8a3 [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 Hughes1fe7afb2012-02-13 17:23:03 -0800615JDWP::JdwpError Dbg::GetSignature(JDWP::RefTypeId refTypeId, std::string& signature) {
616 JDWP::JdwpError status;
617 Class* c = DecodeClass(refTypeId, status);
618 if (c == NULL) {
619 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800620 }
Elliott Hughes1fe7afb2012-02-13 17:23:03 -0800621 signature = ClassHelper(c).GetDescriptor();
622 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700623}
624
Elliott Hughes03181a82011-11-17 17:22:21 -0800625bool Dbg::GetSourceFile(JDWP::RefTypeId refTypeId, std::string& result) {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800626 Object* o = gRegistry->Get<Object*>(refTypeId);
627 if (o == NULL || !o->IsClass()) {
628 return false;
629 }
630 result = ClassHelper(o->AsClass()).GetSourceFile();
631 return result != NULL;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700632}
633
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700634uint8_t Dbg::GetObjectTag(JDWP::ObjectId objectId) {
Elliott Hughes24437992011-11-30 14:49:33 -0800635 Object* o = gRegistry->Get<Object*>(objectId);
636 return TagFromObject(o);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700637}
638
Elliott Hughesaed4be92011-12-02 16:16:23 -0800639size_t Dbg::GetTagWidth(JDWP::JdwpTag tag) {
Elliott Hughesdbb40792011-11-18 17:05:22 -0800640 switch (tag) {
641 case JDWP::JT_VOID:
642 return 0;
643 case JDWP::JT_BYTE:
644 case JDWP::JT_BOOLEAN:
645 return 1;
646 case JDWP::JT_CHAR:
647 case JDWP::JT_SHORT:
648 return 2;
649 case JDWP::JT_FLOAT:
650 case JDWP::JT_INT:
651 return 4;
652 case JDWP::JT_ARRAY:
653 case JDWP::JT_OBJECT:
654 case JDWP::JT_STRING:
655 case JDWP::JT_THREAD:
656 case JDWP::JT_THREAD_GROUP:
657 case JDWP::JT_CLASS_LOADER:
658 case JDWP::JT_CLASS_OBJECT:
659 return sizeof(JDWP::ObjectId);
660 case JDWP::JT_DOUBLE:
661 case JDWP::JT_LONG:
662 return 8;
663 default:
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800664 LOG(FATAL) << "Unknown tag " << tag;
Elliott Hughesdbb40792011-11-18 17:05:22 -0800665 return -1;
666 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700667}
668
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800669JDWP::JdwpError Dbg::GetArrayLength(JDWP::ObjectId arrayId, int& length) {
670 JDWP::JdwpError status;
671 Array* a = DecodeArray(arrayId, status);
672 if (a == NULL) {
673 return status;
Elliott Hughes24437992011-11-30 14:49:33 -0800674 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800675 length = a->GetLength();
676 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700677}
678
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800679JDWP::JdwpError Dbg::OutputArray(JDWP::ObjectId arrayId, int offset, int count, JDWP::ExpandBuf* pReply) {
680 JDWP::JdwpError status;
681 Array* a = DecodeArray(arrayId, status);
682 if (a == NULL) {
683 return status;
684 }
Elliott Hughes24437992011-11-30 14:49:33 -0800685
686 if (offset < 0 || count < 0 || offset > a->GetLength() || a->GetLength() - offset < count) {
687 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800688 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughes24437992011-11-30 14:49:33 -0800689 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800690 std::string descriptor(ClassHelper(a->GetClass()).GetDescriptor());
Elliott Hughes24437992011-11-30 14:49:33 -0800691 JDWP::JdwpTag tag = BasicTagFromDescriptor(descriptor.c_str() + 1);
692
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800693 expandBufAdd1(pReply, tag);
694 expandBufAdd4BE(pReply, count);
695
Elliott Hughes24437992011-11-30 14:49:33 -0800696 if (IsPrimitiveTag(tag)) {
697 size_t width = GetTagWidth(tag);
698 const uint8_t* src = reinterpret_cast<uint8_t*>(a->GetRawData());
699 uint8_t* dst = expandBufAddSpace(pReply, count * width);
700 if (width == 8) {
701 const uint64_t* src8 = reinterpret_cast<const uint64_t*>(src);
702 for (int i = 0; i < count; ++i) JDWP::Write8BE(&dst, src8[offset + i]);
703 } else if (width == 4) {
704 const uint32_t* src4 = reinterpret_cast<const uint32_t*>(src);
705 for (int i = 0; i < count; ++i) JDWP::Write4BE(&dst, src4[offset + i]);
706 } else if (width == 2) {
707 const uint16_t* src2 = reinterpret_cast<const uint16_t*>(src);
708 for (int i = 0; i < count; ++i) JDWP::Write2BE(&dst, src2[offset + i]);
709 } else {
710 memcpy(dst, &src[offset * width], count * width);
711 }
712 } else {
713 ObjectArray<Object>* oa = a->AsObjectArray<Object>();
714 for (int i = 0; i < count; ++i) {
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800715 Object* element = oa->Get(offset + i);
Elliott Hughes24437992011-11-30 14:49:33 -0800716 JDWP::JdwpTag specific_tag = (element != NULL) ? TagFromObject(element) : tag;
717 expandBufAdd1(pReply, specific_tag);
718 expandBufAddObjectId(pReply, gRegistry->Add(element));
719 }
720 }
721
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800722 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700723}
724
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800725JDWP::JdwpError Dbg::SetArrayElements(JDWP::ObjectId arrayId, int offset, int count, const uint8_t* src) {
726 JDWP::JdwpError status;
727 Array* a = DecodeArray(arrayId, status);
728 if (a == NULL) {
729 return status;
730 }
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800731
732 if (offset < 0 || count < 0 || offset > a->GetLength() || a->GetLength() - offset < count) {
733 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800734 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800735 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800736 std::string descriptor(ClassHelper(a->GetClass()).GetDescriptor());
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800737 JDWP::JdwpTag tag = BasicTagFromDescriptor(descriptor.c_str() + 1);
738
739 if (IsPrimitiveTag(tag)) {
740 size_t width = GetTagWidth(tag);
741 uint8_t* dst = &(reinterpret_cast<uint8_t*>(a->GetRawData())[offset * width]);
742 if (width == 8) {
743 for (int i = 0; i < count; ++i) {
744 // Handle potentially non-aligned memory access one byte at a time for ARM's benefit.
745 uint64_t value;
746 for (size_t j = 0; j < sizeof(uint64_t); ++j) reinterpret_cast<uint8_t*>(&value)[j] = src[j];
747 src += sizeof(uint64_t);
748 JDWP::Write8BE(&dst, value);
749 }
750 } else if (width == 4) {
751 const uint32_t* src4 = reinterpret_cast<const uint32_t*>(src);
752 for (int i = 0; i < count; ++i) JDWP::Write4BE(&dst, src4[i]);
753 } else if (width == 2) {
754 const uint16_t* src2 = reinterpret_cast<const uint16_t*>(src);
755 for (int i = 0; i < count; ++i) JDWP::Write2BE(&dst, src2[i]);
756 } else {
757 memcpy(&dst[offset * width], src, count * width);
758 }
759 } else {
760 ObjectArray<Object>* oa = a->AsObjectArray<Object>();
761 for (int i = 0; i < count; ++i) {
762 JDWP::ObjectId id = JDWP::ReadObjectId(&src);
763 oa->Set(offset + i, gRegistry->Get<Object*>(id));
764 }
765 }
766
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800767 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700768}
769
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800770JDWP::ObjectId Dbg::CreateString(const std::string& str) {
771 return gRegistry->Add(String::AllocFromModifiedUtf8(str.c_str()));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700772}
773
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800774bool Dbg::CreateObject(JDWP::RefTypeId classId, JDWP::ObjectId& new_object) {
775 Object* o = gRegistry->Get<Object*>(classId);
776 if (o == NULL || !o->IsClass()) {
777 return false;
778 }
779 new_object = gRegistry->Add(o->AsClass()->AllocObject());
780 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700781}
782
Elliott Hughesbf13d362011-12-08 15:51:37 -0800783/*
784 * Used by Eclipse's "Display" view to evaluate "new byte[5]" to get "(byte[]) [0, 0, 0, 0, 0]".
785 */
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800786bool Dbg::CreateArrayObject(JDWP::RefTypeId arrayTypeId, uint32_t length, JDWP::ObjectId& new_array) {
787 Object* o = gRegistry->Get<Object*>(arrayTypeId);
788 if (o == NULL || !o->IsClass()) {
789 return false;
790 }
791 new_array = gRegistry->Add(Array::Alloc(o->AsClass(), length));
792 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700793}
794
795bool Dbg::MatchType(JDWP::RefTypeId instClassId, JDWP::RefTypeId classId) {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800796 // TODO: error handling if the RefTypeIds aren't actually Class*s.
Elliott Hughesd07986f2011-12-06 18:27:45 -0800797 return gRegistry->Get<Class*>(instClassId)->InstanceOf(gRegistry->Get<Class*>(classId));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700798}
799
Elliott Hughes03181a82011-11-17 17:22:21 -0800800JDWP::FieldId ToFieldId(Field* f) {
801#ifdef MOVING_GARBAGE_COLLECTOR
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700802 UNIMPLEMENTED(FATAL);
Elliott Hughes03181a82011-11-17 17:22:21 -0800803#else
804 return static_cast<JDWP::FieldId>(reinterpret_cast<uintptr_t>(f));
805#endif
806}
807
808JDWP::MethodId ToMethodId(Method* m) {
809#ifdef MOVING_GARBAGE_COLLECTOR
810 UNIMPLEMENTED(FATAL);
811#else
812 return static_cast<JDWP::MethodId>(reinterpret_cast<uintptr_t>(m));
813#endif
814}
815
Elliott Hughesaed4be92011-12-02 16:16:23 -0800816Field* FromFieldId(JDWP::FieldId fid) {
817#ifdef MOVING_GARBAGE_COLLECTOR
818 UNIMPLEMENTED(FATAL);
819#else
820 return reinterpret_cast<Field*>(static_cast<uintptr_t>(fid));
821#endif
822}
823
Elliott Hughes03181a82011-11-17 17:22:21 -0800824Method* FromMethodId(JDWP::MethodId mid) {
825#ifdef MOVING_GARBAGE_COLLECTOR
826 UNIMPLEMENTED(FATAL);
827#else
828 return reinterpret_cast<Method*>(static_cast<uintptr_t>(mid));
829#endif
830}
831
Elliott Hughesd07986f2011-12-06 18:27:45 -0800832void SetLocation(JDWP::JdwpLocation& location, Method* m, uintptr_t native_pc) {
833 Class* c = m->GetDeclaringClass();
834 location.typeTag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
835 location.classId = gRegistry->Add(c);
836 location.methodId = ToMethodId(m);
837 location.idx = m->IsNative() ? -1 : m->ToDexPC(native_pc);
838}
839
Elliott Hughes03181a82011-11-17 17:22:21 -0800840std::string Dbg::GetMethodName(JDWP::RefTypeId refTypeId, JDWP::MethodId methodId) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800841 Method* m = FromMethodId(methodId);
842 return MethodHelper(m).GetName();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700843}
844
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800845/*
846 * Augment the access flags for synthetic methods and fields by setting
847 * the (as described by the spec) "0xf0000000 bit". Also, strip out any
848 * flags not specified by the Java programming language.
849 */
850static uint32_t MangleAccessFlags(uint32_t accessFlags) {
851 accessFlags &= kAccJavaFlagsMask;
852 if ((accessFlags & kAccSynthetic) != 0) {
853 accessFlags |= 0xf0000000;
854 }
855 return accessFlags;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700856}
857
Elliott Hughesdbb40792011-11-18 17:05:22 -0800858static const uint16_t kEclipseWorkaroundSlot = 1000;
859
860/*
861 * Eclipse appears to expect that the "this" reference is in slot zero.
862 * If it's not, the "variables" display will show two copies of "this",
863 * possibly because it gets "this" from SF.ThisObject and then displays
864 * all locals with nonzero slot numbers.
865 *
866 * So, we remap the item in slot 0 to 1000, and remap "this" to zero. On
867 * SF.GetValues / SF.SetValues we map them back.
Elliott Hughesc5b734a2011-12-01 17:20:58 -0800868 *
869 * TODO: jdb uses the value to determine whether a variable is a local or an argument,
870 * by checking whether it's less than the number of arguments. To make that work, we'd
871 * have to "mangle" all the arguments to come first, not just the implicit argument 'this'.
Elliott Hughesdbb40792011-11-18 17:05:22 -0800872 */
873static uint16_t MangleSlot(uint16_t slot, const char* name) {
874 uint16_t newSlot = slot;
875 if (strcmp(name, "this") == 0) {
876 newSlot = 0;
877 } else if (slot == 0) {
878 newSlot = kEclipseWorkaroundSlot;
879 }
880 return newSlot;
881}
882
Elliott Hughes68fdbd02011-11-29 19:22:47 -0800883static uint16_t DemangleSlot(uint16_t slot, Frame& f) {
Elliott Hughesdbb40792011-11-18 17:05:22 -0800884 if (slot == kEclipseWorkaroundSlot) {
Elliott Hughes68fdbd02011-11-29 19:22:47 -0800885 return 0;
Elliott Hughesdbb40792011-11-18 17:05:22 -0800886 } else if (slot == 0) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800887 const DexFile::CodeItem* code_item = MethodHelper(f.GetMethod()).GetCodeItem();
888 return code_item->registers_size_ - code_item->ins_size_;
Elliott Hughesdbb40792011-11-18 17:05:22 -0800889 }
Elliott Hughes68fdbd02011-11-29 19:22:47 -0800890 return slot;
Elliott Hughesdbb40792011-11-18 17:05:22 -0800891}
892
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800893bool Dbg::OutputDeclaredFields(JDWP::RefTypeId refTypeId, bool with_generic, JDWP::ExpandBuf* pReply) {
894 Object* o = gRegistry->Get<Object*>(refTypeId);
895 if (o == NULL || !o->IsClass()) {
896 return false;
897 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800898
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800899 Class* c = o->AsClass();
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800900 size_t instance_field_count = c->NumInstanceFields();
901 size_t static_field_count = c->NumStaticFields();
902
903 expandBufAdd4BE(pReply, instance_field_count + static_field_count);
904
905 for (size_t i = 0; i < instance_field_count + static_field_count; ++i) {
906 Field* f = (i < instance_field_count) ? c->GetInstanceField(i) : c->GetStaticField(i - instance_field_count);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800907 FieldHelper fh(f);
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800908 expandBufAddFieldId(pReply, ToFieldId(f));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800909 expandBufAddUtf8String(pReply, fh.GetName());
910 expandBufAddUtf8String(pReply, fh.GetTypeDescriptor());
Elliott Hughesc5b734a2011-12-01 17:20:58 -0800911 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800912 static const char genericSignature[1] = "";
913 expandBufAddUtf8String(pReply, genericSignature);
914 }
915 expandBufAdd4BE(pReply, MangleAccessFlags(f->GetAccessFlags()));
916 }
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800917 return true;
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800918}
919
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800920bool Dbg::OutputDeclaredMethods(JDWP::RefTypeId refTypeId, bool with_generic, JDWP::ExpandBuf* pReply) {
921 Object* o = gRegistry->Get<Object*>(refTypeId);
922 if (o == NULL || !o->IsClass()) {
923 return false;
924 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800925
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800926 Class* c = o->AsClass();
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800927 size_t direct_method_count = c->NumDirectMethods();
928 size_t virtual_method_count = c->NumVirtualMethods();
929
930 expandBufAdd4BE(pReply, direct_method_count + virtual_method_count);
931
932 for (size_t i = 0; i < direct_method_count + virtual_method_count; ++i) {
933 Method* m = (i < direct_method_count) ? c->GetDirectMethod(i) : c->GetVirtualMethod(i - direct_method_count);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800934 MethodHelper mh(m);
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800935 expandBufAddMethodId(pReply, ToMethodId(m));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800936 expandBufAddUtf8String(pReply, mh.GetName());
Elliott Hughes4740cdf2011-12-07 14:07:12 -0800937 expandBufAddUtf8String(pReply, mh.GetSignature());
Elliott Hughesc5b734a2011-12-01 17:20:58 -0800938 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800939 static const char genericSignature[1] = "";
940 expandBufAddUtf8String(pReply, genericSignature);
941 }
942 expandBufAdd4BE(pReply, MangleAccessFlags(m->GetAccessFlags()));
943 }
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800944 return true;
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800945}
946
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800947bool Dbg::OutputDeclaredInterfaces(JDWP::RefTypeId refTypeId, JDWP::ExpandBuf* pReply) {
948 Object* o = gRegistry->Get<Object*>(refTypeId);
949 if (o == NULL || !o->IsClass()) {
950 return false;
951 }
952 ClassHelper kh(o->AsClass());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800953 size_t interface_count = kh.NumInterfaces();
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800954 expandBufAdd4BE(pReply, interface_count);
955 for (size_t i = 0; i < interface_count; ++i) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800956 expandBufAddRefTypeId(pReply, gRegistry->Add(kh.GetInterface(i)));
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800957 }
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800958 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700959}
960
961void Dbg::OutputLineTable(JDWP::RefTypeId refTypeId, JDWP::MethodId methodId, JDWP::ExpandBuf* pReply) {
Elliott Hughes03181a82011-11-17 17:22:21 -0800962 struct DebugCallbackContext {
963 int numItems;
964 JDWP::ExpandBuf* pReply;
965
966 static bool Callback(void* context, uint32_t address, uint32_t lineNum) {
967 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
968 expandBufAdd8BE(pContext->pReply, address);
969 expandBufAdd4BE(pContext->pReply, lineNum);
970 pContext->numItems++;
971 return true;
972 }
973 };
974
975 Method* m = FromMethodId(methodId);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800976 MethodHelper mh(m);
Elliott Hughes03181a82011-11-17 17:22:21 -0800977 uint64_t start, end;
978 if (m->IsNative()) {
979 start = -1;
980 end = -1;
981 } else {
982 start = 0;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800983 // TODO: what are the units supposed to be? *2?
984 end = mh.GetCodeItem()->insns_size_in_code_units_;
Elliott Hughes03181a82011-11-17 17:22:21 -0800985 }
986
987 expandBufAdd8BE(pReply, start);
988 expandBufAdd8BE(pReply, end);
989
990 // Add numLines later
991 size_t numLinesOffset = expandBufGetLength(pReply);
992 expandBufAdd4BE(pReply, 0);
993
994 DebugCallbackContext context;
995 context.numItems = 0;
996 context.pReply = pReply;
997
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800998 mh.GetDexFile().DecodeDebugInfo(mh.GetCodeItem(), m->IsStatic(), m->GetDexMethodIndex(),
999 DebugCallbackContext::Callback, NULL, &context);
Elliott Hughes03181a82011-11-17 17:22:21 -08001000
1001 JDWP::Set4BE(expandBufGetBuffer(pReply) + numLinesOffset, context.numItems);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001002}
1003
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001004void Dbg::OutputVariableTable(JDWP::RefTypeId refTypeId, JDWP::MethodId methodId, bool with_generic, JDWP::ExpandBuf* pReply) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001005 struct DebugCallbackContext {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001006 JDWP::ExpandBuf* pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001007 size_t variable_count;
1008 bool with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001009
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001010 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 -08001011 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
1012
Elliott Hughesaa6e1cd2012-01-18 19:26:06 -08001013 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 -08001014
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001015 slot = MangleSlot(slot, name);
1016
Elliott Hughesdbb40792011-11-18 17:05:22 -08001017 expandBufAdd8BE(pContext->pReply, startAddress);
1018 expandBufAddUtf8String(pContext->pReply, name);
1019 expandBufAddUtf8String(pContext->pReply, descriptor);
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001020 if (pContext->with_generic) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001021 expandBufAddUtf8String(pContext->pReply, signature);
1022 }
1023 expandBufAdd4BE(pContext->pReply, endAddress - startAddress);
1024 expandBufAdd4BE(pContext->pReply, slot);
1025
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001026 ++pContext->variable_count;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001027 }
1028 };
1029
1030 Method* m = FromMethodId(methodId);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001031 MethodHelper mh(m);
1032 const DexFile::CodeItem* code_item = mh.GetCodeItem();
Elliott Hughesdbb40792011-11-18 17:05:22 -08001033
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001034 // arg_count considers doubles and longs to take 2 units.
1035 // variable_count considers everything to take 1 unit.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001036 std::string shorty(mh.GetShorty());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001037 expandBufAdd4BE(pReply, m->NumArgRegisters(shorty));
Elliott Hughesdbb40792011-11-18 17:05:22 -08001038
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001039 // We don't know the total number of variables yet, so leave a blank and update it later.
1040 size_t variable_count_offset = expandBufGetLength(pReply);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001041 expandBufAdd4BE(pReply, 0);
1042
1043 DebugCallbackContext context;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001044 context.pReply = pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001045 context.variable_count = 0;
1046 context.with_generic = with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001047
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001048 mh.GetDexFile().DecodeDebugInfo(code_item, m->IsStatic(), m->GetDexMethodIndex(), NULL,
1049 DebugCallbackContext::Callback, &context);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001050
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001051 JDWP::Set4BE(expandBufGetBuffer(pReply) + variable_count_offset, context.variable_count);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001052}
1053
Elliott Hughesaed4be92011-12-02 16:16:23 -08001054JDWP::JdwpTag Dbg::GetFieldBasicTag(JDWP::FieldId fieldId) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001055 return BasicTagFromDescriptor(FieldHelper(FromFieldId(fieldId)).GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001056}
1057
Elliott Hughesaed4be92011-12-02 16:16:23 -08001058JDWP::JdwpTag Dbg::GetStaticFieldBasicTag(JDWP::FieldId fieldId) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001059 return BasicTagFromDescriptor(FieldHelper(FromFieldId(fieldId)).GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001060}
1061
1062void Dbg::GetFieldValue(JDWP::ObjectId objectId, JDWP::FieldId fieldId, JDWP::ExpandBuf* pReply) {
Elliott Hughesaed4be92011-12-02 16:16:23 -08001063 Object* o = gRegistry->Get<Object*>(objectId);
1064 Field* f = FromFieldId(fieldId);
1065
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001066 JDWP::JdwpTag tag = BasicTagFromDescriptor(FieldHelper(f).GetTypeDescriptor());
Elliott Hughesaed4be92011-12-02 16:16:23 -08001067
1068 if (IsPrimitiveTag(tag)) {
1069 expandBufAdd1(pReply, tag);
1070 if (tag == JDWP::JT_BOOLEAN || tag == JDWP::JT_BYTE) {
1071 expandBufAdd1(pReply, f->Get32(o));
1072 } else if (tag == JDWP::JT_CHAR || tag == JDWP::JT_SHORT) {
1073 expandBufAdd2BE(pReply, f->Get32(o));
1074 } else if (tag == JDWP::JT_FLOAT || tag == JDWP::JT_INT) {
1075 expandBufAdd4BE(pReply, f->Get32(o));
1076 } else if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
1077 expandBufAdd8BE(pReply, f->Get64(o));
1078 } else {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001079 LOG(FATAL) << "Unknown tag: " << tag;
Elliott Hughesaed4be92011-12-02 16:16:23 -08001080 }
1081 } else {
1082 Object* value = f->GetObject(o);
1083 expandBufAdd1(pReply, TagFromObject(value));
1084 expandBufAddObjectId(pReply, gRegistry->Add(value));
1085 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001086}
1087
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001088JDWP::JdwpError Dbg::SetFieldValue(JDWP::ObjectId objectId, JDWP::FieldId fieldId, uint64_t value, int width) {
Elliott Hughesaed4be92011-12-02 16:16:23 -08001089 Object* o = gRegistry->Get<Object*>(objectId);
1090 Field* f = FromFieldId(fieldId);
1091
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001092 JDWP::JdwpTag tag = BasicTagFromDescriptor(FieldHelper(f).GetTypeDescriptor());
Elliott Hughesaed4be92011-12-02 16:16:23 -08001093
1094 if (IsPrimitiveTag(tag)) {
1095 if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
1096 f->Set64(o, value);
1097 } else {
1098 f->Set32(o, value);
1099 }
1100 } else {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001101 Object* v = gRegistry->Get<Object*>(value);
1102 Class* field_type = FieldHelper(f).GetType();
1103 if (!field_type->IsAssignableFrom(v->GetClass())) {
1104 return JDWP::ERR_INVALID_OBJECT;
1105 }
1106 f->SetObject(o, v);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001107 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001108
1109 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001110}
1111
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001112void Dbg::GetStaticFieldValue(JDWP::FieldId fieldId, JDWP::ExpandBuf* pReply) {
1113 GetFieldValue(0, fieldId, pReply);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001114}
1115
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001116JDWP::JdwpError Dbg::SetStaticFieldValue(JDWP::FieldId fieldId, uint64_t value, int width) {
1117 return SetFieldValue(0, fieldId, value, width);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001118}
1119
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001120std::string Dbg::StringToUtf8(JDWP::ObjectId strId) {
1121 String* s = gRegistry->Get<String*>(strId);
1122 return s->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001123}
1124
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001125Thread* DecodeThread(JDWP::ObjectId threadId) {
1126 Object* thread_peer = gRegistry->Get<Object*>(threadId);
1127 CHECK(thread_peer != NULL);
1128 return Thread::FromManagedThread(thread_peer);
1129}
1130
1131bool Dbg::GetThreadName(JDWP::ObjectId threadId, std::string& name) {
1132 ScopedThreadListLock thread_list_lock;
1133 Thread* thread = DecodeThread(threadId);
1134 if (thread == NULL) {
1135 return false;
1136 }
Elliott Hughes899e7892012-01-24 14:57:32 -08001137 StringAppendF(&name, "<%d> %s", thread->GetThinLockId(), thread->GetThreadName()->ToModifiedUtf8().c_str());
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001138 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001139}
1140
1141JDWP::ObjectId Dbg::GetThreadGroup(JDWP::ObjectId threadId) {
Elliott Hughes499c5132011-11-17 14:55:11 -08001142 Object* thread = gRegistry->Get<Object*>(threadId);
1143 CHECK(thread != NULL);
1144
1145 Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/Thread;");
1146 CHECK(c != NULL);
1147 Field* f = c->FindInstanceField("group", "Ljava/lang/ThreadGroup;");
1148 CHECK(f != NULL);
1149 Object* group = f->GetObject(thread);
1150 CHECK(group != NULL);
1151 return gRegistry->Add(group);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001152}
1153
Elliott Hughes499c5132011-11-17 14:55:11 -08001154std::string Dbg::GetThreadGroupName(JDWP::ObjectId threadGroupId) {
1155 Object* thread_group = gRegistry->Get<Object*>(threadGroupId);
1156 CHECK(thread_group != NULL);
1157
1158 Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/ThreadGroup;");
1159 CHECK(c != NULL);
1160 Field* f = c->FindInstanceField("name", "Ljava/lang/String;");
1161 CHECK(f != NULL);
1162 String* s = reinterpret_cast<String*>(f->GetObject(thread_group));
1163 return s->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001164}
1165
1166JDWP::ObjectId Dbg::GetThreadGroupParent(JDWP::ObjectId threadGroupId) {
Elliott Hughes4e235312011-12-02 11:34:15 -08001167 Object* thread_group = gRegistry->Get<Object*>(threadGroupId);
1168 CHECK(thread_group != NULL);
1169
1170 Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/ThreadGroup;");
1171 CHECK(c != NULL);
1172 Field* f = c->FindInstanceField("parent", "Ljava/lang/ThreadGroup;");
1173 CHECK(f != NULL);
1174 Object* parent = f->GetObject(thread_group);
1175 return gRegistry->Add(parent);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001176}
1177
Elliott Hughes499c5132011-11-17 14:55:11 -08001178static Object* GetStaticThreadGroup(const char* field_name) {
1179 Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/ThreadGroup;");
1180 CHECK(c != NULL);
1181 Field* f = c->FindStaticField(field_name, "Ljava/lang/ThreadGroup;");
1182 CHECK(f != NULL);
1183 Object* group = f->GetObject(NULL);
1184 CHECK(group != NULL);
1185 return group;
1186}
1187
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001188JDWP::ObjectId Dbg::GetSystemThreadGroupId() {
Elliott Hughes499c5132011-11-17 14:55:11 -08001189 return gRegistry->Add(GetStaticThreadGroup("mSystem"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001190}
1191
1192JDWP::ObjectId Dbg::GetMainThreadGroupId() {
Elliott Hughes499c5132011-11-17 14:55:11 -08001193 return gRegistry->Add(GetStaticThreadGroup("mMain"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001194}
1195
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001196bool Dbg::GetThreadStatus(JDWP::ObjectId threadId, JDWP::JdwpThreadStatus* pThreadStatus, JDWP::JdwpSuspendStatus* pSuspendStatus) {
Elliott Hughes499c5132011-11-17 14:55:11 -08001197 ScopedThreadListLock thread_list_lock;
1198
1199 Thread* thread = DecodeThread(threadId);
1200 if (thread == NULL) {
1201 return false;
1202 }
1203
1204 switch (thread->GetState()) {
1205 case Thread::kTerminated: *pThreadStatus = JDWP::TS_ZOMBIE; break;
1206 case Thread::kRunnable: *pThreadStatus = JDWP::TS_RUNNING; break;
1207 case Thread::kTimedWaiting: *pThreadStatus = JDWP::TS_SLEEPING; break;
1208 case Thread::kBlocked: *pThreadStatus = JDWP::TS_MONITOR; break;
1209 case Thread::kWaiting: *pThreadStatus = JDWP::TS_WAIT; break;
1210 case Thread::kInitializing: *pThreadStatus = JDWP::TS_ZOMBIE; break;
1211 case Thread::kStarting: *pThreadStatus = JDWP::TS_ZOMBIE; break;
1212 case Thread::kNative: *pThreadStatus = JDWP::TS_RUNNING; break;
1213 case Thread::kVmWait: *pThreadStatus = JDWP::TS_WAIT; break;
1214 case Thread::kSuspended: *pThreadStatus = JDWP::TS_RUNNING; break;
1215 default:
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001216 LOG(FATAL) << "Unknown thread state " << thread->GetState();
Elliott Hughes499c5132011-11-17 14:55:11 -08001217 }
1218
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001219 *pSuspendStatus = (thread->IsSuspended() ? JDWP::SUSPEND_STATUS_SUSPENDED : JDWP::SUSPEND_STATUS_NOT_SUSPENDED);
Elliott Hughes499c5132011-11-17 14:55:11 -08001220
1221 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001222}
1223
1224uint32_t Dbg::GetThreadSuspendCount(JDWP::ObjectId threadId) {
Elliott Hughesd07986f2011-12-06 18:27:45 -08001225 return DecodeThread(threadId)->GetSuspendCount();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001226}
1227
1228bool Dbg::ThreadExists(JDWP::ObjectId threadId) {
Elliott Hughes761928d2011-11-16 18:33:03 -08001229 return DecodeThread(threadId) != NULL;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001230}
1231
1232bool Dbg::IsSuspended(JDWP::ObjectId threadId) {
Elliott Hughes761928d2011-11-16 18:33:03 -08001233 return DecodeThread(threadId)->IsSuspended();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001234}
1235
Elliott Hughesa2155262011-11-16 16:26:58 -08001236void Dbg::GetThreadGroupThreadsImpl(Object* thread_group, JDWP::ObjectId** ppThreadIds, uint32_t* pThreadCount) {
1237 struct ThreadListVisitor {
1238 static void Visit(Thread* t, void* arg) {
1239 reinterpret_cast<ThreadListVisitor*>(arg)->Visit(t);
1240 }
1241
1242 void Visit(Thread* t) {
1243 if (t == Dbg::GetDebugThread()) {
1244 // Skip the JDWP thread. Some debuggers get bent out of shape when they can't suspend and
1245 // query all threads, so it's easier if we just don't tell them about this thread.
1246 return;
1247 }
1248 if (thread_group == NULL || t->GetThreadGroup() == thread_group) {
1249 threads.push_back(gRegistry->Add(t->GetPeer()));
1250 }
1251 }
1252
1253 Object* thread_group;
1254 std::vector<JDWP::ObjectId> threads;
1255 };
1256
1257 ThreadListVisitor tlv;
1258 tlv.thread_group = thread_group;
1259
1260 {
1261 ScopedThreadListLock thread_list_lock;
1262 Runtime::Current()->GetThreadList()->ForEach(ThreadListVisitor::Visit, &tlv);
1263 }
1264
1265 *pThreadCount = tlv.threads.size();
1266 if (*pThreadCount == 0) {
1267 *ppThreadIds = NULL;
1268 } else {
1269 *ppThreadIds = new JDWP::ObjectId[*pThreadCount];
1270 for (size_t i = 0; i < *pThreadCount; ++i) {
1271 (*ppThreadIds)[i] = tlv.threads[i];
1272 }
1273 }
1274}
1275
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001276void Dbg::GetThreadGroupThreads(JDWP::ObjectId threadGroupId, JDWP::ObjectId** ppThreadIds, uint32_t* pThreadCount) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001277 GetThreadGroupThreadsImpl(gRegistry->Get<Object*>(threadGroupId), ppThreadIds, pThreadCount);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001278}
1279
1280void Dbg::GetAllThreads(JDWP::ObjectId** ppThreadIds, uint32_t* pThreadCount) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001281 GetThreadGroupThreadsImpl(NULL, ppThreadIds, pThreadCount);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001282}
1283
1284int Dbg::GetThreadFrameCount(JDWP::ObjectId threadId) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001285 ScopedThreadListLock thread_list_lock;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001286 struct CountStackDepthVisitor : public Thread::StackVisitor {
1287 CountStackDepthVisitor() : depth(0) {}
Elliott Hughesf8a2df72011-12-01 12:19:54 -08001288 virtual void VisitFrame(const Frame& f, uintptr_t) {
1289 // TODO: we'll need to skip callee-save frames too.
1290 if (f.HasMethod()) {
1291 ++depth;
1292 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001293 }
1294 size_t depth;
1295 };
1296 CountStackDepthVisitor visitor;
1297 DecodeThread(threadId)->WalkStack(&visitor);
1298 return visitor.depth;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001299}
1300
Elliott Hughes03181a82011-11-17 17:22:21 -08001301bool Dbg::GetThreadFrame(JDWP::ObjectId threadId, int desired_frame_number, JDWP::FrameId* pFrameId, JDWP::JdwpLocation* pLoc) {
1302 ScopedThreadListLock thread_list_lock;
1303 struct GetFrameVisitor : public Thread::StackVisitor {
1304 GetFrameVisitor(int desired_frame_number, JDWP::FrameId* pFrameId, JDWP::JdwpLocation* pLoc)
Elliott Hughesba8eee12012-01-24 20:25:24 -08001305 : found(false), depth(0), desired_frame_number(desired_frame_number), pFrameId(pFrameId), pLoc(pLoc) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001306 }
1307 virtual void VisitFrame(const Frame& f, uintptr_t pc) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -08001308 // TODO: we'll need to skip callee-save frames too.
Elliott Hughes03181a82011-11-17 17:22:21 -08001309 if (!f.HasMethod()) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -08001310 return; // The debugger can't do anything useful with a frame that has no Method*.
Elliott Hughes03181a82011-11-17 17:22:21 -08001311 }
1312
1313 if (depth == desired_frame_number) {
1314 *pFrameId = reinterpret_cast<JDWP::FrameId>(f.GetSP());
Elliott Hughesd07986f2011-12-06 18:27:45 -08001315 SetLocation(*pLoc, f.GetMethod(), pc);
Elliott Hughes03181a82011-11-17 17:22:21 -08001316 found = true;
1317 }
1318 ++depth;
1319 }
1320 bool found;
1321 int depth;
1322 int desired_frame_number;
1323 JDWP::FrameId* pFrameId;
1324 JDWP::JdwpLocation* pLoc;
1325 };
1326 GetFrameVisitor visitor(desired_frame_number, pFrameId, pLoc);
1327 visitor.desired_frame_number = desired_frame_number;
1328 DecodeThread(threadId)->WalkStack(&visitor);
1329 return visitor.found;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001330}
1331
1332JDWP::ObjectId Dbg::GetThreadSelfId() {
Elliott Hughes475fc232011-10-25 15:00:35 -07001333 return gRegistry->Add(Thread::Current()->GetPeer());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001334}
1335
Elliott Hughes475fc232011-10-25 15:00:35 -07001336void Dbg::SuspendVM() {
Elliott Hughesa2155262011-11-16 16:26:58 -08001337 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 -07001338 Runtime::Current()->GetThreadList()->SuspendAll(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001339}
1340
1341void Dbg::ResumeVM() {
Elliott Hughes475fc232011-10-25 15:00:35 -07001342 Runtime::Current()->GetThreadList()->ResumeAll(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001343}
1344
1345void Dbg::SuspendThread(JDWP::ObjectId threadId) {
Elliott Hughes4e235312011-12-02 11:34:15 -08001346 Object* peer = gRegistry->Get<Object*>(threadId);
1347 ScopedThreadListLock thread_list_lock;
1348 Thread* thread = Thread::FromManagedThread(peer);
1349 if (thread == NULL) {
1350 LOG(WARNING) << "No such thread for suspend: " << peer;
1351 return;
1352 }
1353 Runtime::Current()->GetThreadList()->Suspend(thread, true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001354}
1355
1356void Dbg::ResumeThread(JDWP::ObjectId threadId) {
Elliott Hughes4e235312011-12-02 11:34:15 -08001357 Object* peer = gRegistry->Get<Object*>(threadId);
1358 ScopedThreadListLock thread_list_lock;
1359 Thread* thread = Thread::FromManagedThread(peer);
1360 if (thread == NULL) {
1361 LOG(WARNING) << "No such thread for resume: " << peer;
1362 return;
1363 }
1364 Runtime::Current()->GetThreadList()->Resume(thread, true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001365}
1366
1367void Dbg::SuspendSelf() {
Elliott Hughes475fc232011-10-25 15:00:35 -07001368 Runtime::Current()->GetThreadList()->SuspendSelfForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001369}
1370
Elliott Hughesd07986f2011-12-06 18:27:45 -08001371bool Dbg::GetThisObject(JDWP::FrameId frameId, JDWP::ObjectId* pThisId) {
Elliott Hughes86b00102011-12-05 17:54:26 -08001372 Method** sp = reinterpret_cast<Method**>(frameId);
1373 Frame f;
1374 f.SetSP(sp);
Elliott Hughes86b00102011-12-05 17:54:26 -08001375 Method* m = f.GetMethod();
1376
1377 Object* o = NULL;
1378 if (!m->IsNative() && !m->IsStatic()) {
Elliott Hughesd07986f2011-12-06 18:27:45 -08001379 uint16_t reg = DemangleSlot(0, f);
Elliott Hughes86b00102011-12-05 17:54:26 -08001380 o = reinterpret_cast<Object*>(f.GetVReg(m, reg));
1381 }
1382 *pThisId = gRegistry->Add(o);
1383 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001384}
1385
Elliott Hughescccd84f2011-12-05 16:51:54 -08001386void 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 -08001387 Method** sp = reinterpret_cast<Method**>(frameId);
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001388 Frame f;
1389 f.SetSP(sp);
1390 uint16_t reg = DemangleSlot(slot, f);
1391 Method* m = f.GetMethod();
1392
1393 const VmapTable vmap_table(m->GetVmapTableRaw());
1394 uint32_t vmap_offset;
1395 if (vmap_table.IsInContext(reg, vmap_offset)) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001396 UNIMPLEMENTED(FATAL) << "Don't know how to pull locals from callee save frames: " << vmap_offset;
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001397 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001398
1399 switch (tag) {
1400 case JDWP::JT_BOOLEAN:
1401 {
Elliott Hughescccd84f2011-12-05 16:51:54 -08001402 CHECK_EQ(width, 1U);
Elliott Hughes1bba14f2011-12-01 18:00:36 -08001403 uint32_t intVal = f.GetVReg(m, reg);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001404 VLOG(jdwp) << "get boolean local " << reg << " = " << intVal;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001405 JDWP::Set1(buf+1, intVal != 0);
1406 }
1407 break;
1408 case JDWP::JT_BYTE:
1409 {
Elliott Hughescccd84f2011-12-05 16:51:54 -08001410 CHECK_EQ(width, 1U);
Elliott Hughes1bba14f2011-12-01 18:00:36 -08001411 uint32_t intVal = f.GetVReg(m, reg);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001412 VLOG(jdwp) << "get byte local " << reg << " = " << intVal;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001413 JDWP::Set1(buf+1, intVal);
1414 }
1415 break;
1416 case JDWP::JT_SHORT:
1417 case JDWP::JT_CHAR:
1418 {
Elliott Hughescccd84f2011-12-05 16:51:54 -08001419 CHECK_EQ(width, 2U);
Elliott Hughes1bba14f2011-12-01 18:00:36 -08001420 uint32_t intVal = f.GetVReg(m, reg);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001421 VLOG(jdwp) << "get short/char local " << reg << " = " << intVal;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001422 JDWP::Set2BE(buf+1, intVal);
1423 }
1424 break;
1425 case JDWP::JT_INT:
1426 case JDWP::JT_FLOAT:
1427 {
Elliott Hughescccd84f2011-12-05 16:51:54 -08001428 CHECK_EQ(width, 4U);
Elliott Hughes1bba14f2011-12-01 18:00:36 -08001429 uint32_t intVal = f.GetVReg(m, reg);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001430 VLOG(jdwp) << "get int/float local " << reg << " = " << intVal;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001431 JDWP::Set4BE(buf+1, intVal);
1432 }
1433 break;
1434 case JDWP::JT_ARRAY:
1435 {
Elliott Hughescccd84f2011-12-05 16:51:54 -08001436 CHECK_EQ(width, sizeof(JDWP::ObjectId));
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001437 Object* o = reinterpret_cast<Object*>(f.GetVReg(m, reg));
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001438 VLOG(jdwp) << "get array local " << reg << " = " << o;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001439 if (o != NULL && !Heap::IsHeapAddress(o)) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001440 LOG(FATAL) << "Register " << reg << " expected to hold array: " << o;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001441 }
1442 JDWP::SetObjectId(buf+1, gRegistry->Add(o));
1443 }
1444 break;
1445 case JDWP::JT_OBJECT:
1446 {
Elliott Hughescccd84f2011-12-05 16:51:54 -08001447 CHECK_EQ(width, sizeof(JDWP::ObjectId));
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001448 Object* o = reinterpret_cast<Object*>(f.GetVReg(m, reg));
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001449 VLOG(jdwp) << "get object local " << reg << " = " << o;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001450 if (o != NULL && !Heap::IsHeapAddress(o)) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001451 LOG(FATAL) << "Register " << reg << " expected to hold object: " << o;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001452 }
1453 tag = TagFromObject(o);
1454 JDWP::SetObjectId(buf+1, gRegistry->Add(o));
1455 }
1456 break;
1457 case JDWP::JT_DOUBLE:
1458 case JDWP::JT_LONG:
1459 {
Elliott Hughescccd84f2011-12-05 16:51:54 -08001460 CHECK_EQ(width, 8U);
Elliott Hughes1bba14f2011-12-01 18:00:36 -08001461 uint32_t lo = f.GetVReg(m, reg);
1462 uint64_t hi = f.GetVReg(m, reg + 1);
1463 uint64_t longVal = (hi << 32) | lo;
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001464 VLOG(jdwp) << "get double/long local " << hi << ":" << lo << " = " << longVal;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001465 JDWP::Set8BE(buf+1, longVal);
1466 }
1467 break;
1468 default:
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001469 LOG(FATAL) << "Unknown tag " << tag;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001470 break;
1471 }
1472
1473 // Prepend tag, which may have been updated.
1474 JDWP::Set1(buf, tag);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001475}
1476
Elliott Hughesdbb40792011-11-18 17:05:22 -08001477void 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 -08001478 Method** sp = reinterpret_cast<Method**>(frameId);
1479 Frame f;
1480 f.SetSP(sp);
1481 uint16_t reg = DemangleSlot(slot, f);
1482 Method* m = f.GetMethod();
1483
1484 const VmapTable vmap_table(m->GetVmapTableRaw());
1485 uint32_t vmap_offset;
1486 if (vmap_table.IsInContext(reg, vmap_offset)) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001487 UNIMPLEMENTED(FATAL) << "Don't know how to pull locals from callee save frames: " << vmap_offset;
Elliott Hughescccd84f2011-12-05 16:51:54 -08001488 }
1489
1490 switch (tag) {
1491 case JDWP::JT_BOOLEAN:
1492 case JDWP::JT_BYTE:
1493 CHECK_EQ(width, 1U);
1494 f.SetVReg(m, reg, static_cast<uint32_t>(value));
1495 break;
1496 case JDWP::JT_SHORT:
1497 case JDWP::JT_CHAR:
1498 CHECK_EQ(width, 2U);
1499 f.SetVReg(m, reg, static_cast<uint32_t>(value));
1500 break;
1501 case JDWP::JT_INT:
1502 case JDWP::JT_FLOAT:
1503 CHECK_EQ(width, 4U);
1504 f.SetVReg(m, reg, static_cast<uint32_t>(value));
1505 break;
1506 case JDWP::JT_ARRAY:
1507 case JDWP::JT_OBJECT:
1508 case JDWP::JT_STRING:
1509 {
1510 CHECK_EQ(width, sizeof(JDWP::ObjectId));
1511 Object* o = gRegistry->Get<Object*>(static_cast<JDWP::ObjectId>(value));
1512 f.SetVReg(m, reg, static_cast<uint32_t>(reinterpret_cast<uintptr_t>(o)));
1513 }
1514 break;
1515 case JDWP::JT_DOUBLE:
1516 case JDWP::JT_LONG:
1517 CHECK_EQ(width, 8U);
1518 f.SetVReg(m, reg, static_cast<uint32_t>(value));
1519 f.SetVReg(m, reg + 1, static_cast<uint32_t>(value >> 32));
1520 break;
1521 default:
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001522 LOG(FATAL) << "Unknown tag " << tag;
Elliott Hughescccd84f2011-12-05 16:51:54 -08001523 break;
1524 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001525}
1526
1527void Dbg::PostLocationEvent(const Method* method, int pcOffset, Object* thisPtr, int eventFlags) {
1528 UNIMPLEMENTED(FATAL);
1529}
1530
Elliott Hughesd07986f2011-12-06 18:27:45 -08001531void Dbg::PostException(Method** sp, Method* throwMethod, uintptr_t throwNativePc, Method* catchMethod, uintptr_t catchNativePc, Object* exception) {
Ian Rogers0ad5bb82011-12-07 10:16:32 -08001532 if (!gDebuggerActive) {
1533 return;
1534 }
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001535
Elliott Hughesd07986f2011-12-06 18:27:45 -08001536 JDWP::JdwpLocation throw_location;
1537 SetLocation(throw_location, throwMethod, throwNativePc);
1538 JDWP::JdwpLocation catch_location;
1539 SetLocation(catch_location, catchMethod, catchNativePc);
1540
1541 // We need 'this' for InstanceOnly filters.
1542 JDWP::ObjectId this_id;
1543 GetThisObject(reinterpret_cast<JDWP::FrameId>(sp), &this_id);
1544
1545 /*
1546 * Hand the event to the JDWP exception handler. Note we're using the
1547 * "NoReg" objectID on the exception, which is not strictly correct --
1548 * the exception object WILL be passed up to the debugger if the
1549 * debugger is interested in the event. We do this because the current
1550 * implementation of the debugger object registry never throws anything
1551 * away, and some people were experiencing a fatal build up of exception
1552 * objects when dealing with certain libraries.
1553 */
1554 JDWP::ObjectId exception_id = static_cast<JDWP::ObjectId>(reinterpret_cast<uintptr_t>(exception));
1555 JDWP::RefTypeId exception_class_id = gRegistry->Add(exception->GetClass());
1556
1557 gJdwpState->PostException(&throw_location, exception_id, exception_class_id, &catch_location, this_id);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001558}
1559
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001560void Dbg::PostClassPrepare(Class* c) {
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001561 if (!gDebuggerActive) {
1562 return;
1563 }
1564
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001565 // OLD-TODO - we currently always send both "verified" and "prepared" since
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001566 // debuggers seem to like that. There might be some advantage to honesty,
1567 // since the class may not yet be verified.
1568 int state = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
1569 JDWP::JdwpTypeTag tag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
1570 gJdwpState->PostClassPrepare(tag, gRegistry->Add(c), ClassHelper(c).GetDescriptor(), state);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001571}
1572
1573bool Dbg::WatchLocation(const JDWP::JdwpLocation* pLoc) {
1574 UNIMPLEMENTED(FATAL);
1575 return false;
1576}
1577
1578void Dbg::UnwatchLocation(const JDWP::JdwpLocation* pLoc) {
1579 UNIMPLEMENTED(FATAL);
1580}
1581
1582bool Dbg::ConfigureStep(JDWP::ObjectId threadId, JDWP::JdwpStepSize size, JDWP::JdwpStepDepth depth) {
1583 UNIMPLEMENTED(FATAL);
1584 return false;
1585}
1586
1587void Dbg::UnconfigureStep(JDWP::ObjectId threadId) {
1588 UNIMPLEMENTED(FATAL);
1589}
1590
Elliott Hughesd07986f2011-12-06 18:27:45 -08001591JDWP::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) {
1592 ThreadList* thread_list = Runtime::Current()->GetThreadList();
1593
1594 Thread* targetThread = NULL;
1595 DebugInvokeReq* req = NULL;
1596 {
1597 ScopedThreadListLock thread_list_lock;
1598 targetThread = DecodeThread(threadId);
1599 if (targetThread == NULL) {
1600 LOG(ERROR) << "InvokeMethod request for non-existent thread " << threadId;
1601 return JDWP::ERR_INVALID_THREAD;
1602 }
1603 req = targetThread->GetInvokeReq();
1604 if (!req->ready) {
1605 LOG(ERROR) << "InvokeMethod request for thread not stopped by event: " << *targetThread;
1606 return JDWP::ERR_INVALID_THREAD;
1607 }
1608
1609 /*
1610 * We currently have a bug where we don't successfully resume the
1611 * target thread if the suspend count is too deep. We're expected to
1612 * require one "resume" for each "suspend", but when asked to execute
1613 * a method we have to resume fully and then re-suspend it back to the
1614 * same level. (The easiest way to cause this is to type "suspend"
1615 * multiple times in jdb.)
1616 *
1617 * It's unclear what this means when the event specifies "resume all"
1618 * and some threads are suspended more deeply than others. This is
1619 * a rare problem, so for now we just prevent it from hanging forever
1620 * by rejecting the method invocation request. Without this, we will
1621 * be stuck waiting on a suspended thread.
1622 */
1623 int suspend_count = targetThread->GetSuspendCount();
1624 if (suspend_count > 1) {
1625 LOG(ERROR) << *targetThread << " suspend count too deep for method invocation: " << suspend_count;
1626 return JDWP::ERR_THREAD_SUSPENDED; // Probably not expected here.
1627 }
1628
1629 /*
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001630 * OLD-TODO: ought to screen the various IDs, and verify that the argument
Elliott Hughesd07986f2011-12-06 18:27:45 -08001631 * list is valid.
1632 */
1633 req->receiver_ = gRegistry->Get<Object*>(objectId);
1634 req->thread_ = gRegistry->Get<Object*>(threadId);
1635 req->class_ = gRegistry->Get<Class*>(classId);
1636 req->method_ = FromMethodId(methodId);
1637 req->num_args_ = numArgs;
1638 req->arg_array_ = argArray;
1639 req->options_ = options;
1640 req->invoke_needed_ = true;
1641 }
1642
1643 // The fact that we've released the thread list lock is a bit risky --- if the thread goes
1644 // away we're sitting high and dry -- but we must release this before the ResumeAllThreads
1645 // call, and it's unwise to hold it during WaitForSuspend.
1646
1647 {
1648 /*
1649 * We change our (JDWP thread) status, which should be THREAD_RUNNING,
1650 * so the VM can suspend for a GC if the invoke request causes us to
1651 * run out of memory. It's also a good idea to change it before locking
1652 * the invokeReq mutex, although that should never be held for long.
1653 */
1654 ScopedThreadStateChange tsc(Thread::Current(), Thread::kVmWait);
1655
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001656 VLOG(jdwp) << " Transferring control to event thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08001657 {
1658 MutexLock mu(req->lock_);
1659
1660 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001661 VLOG(jdwp) << " Resuming all threads";
Elliott Hughesd07986f2011-12-06 18:27:45 -08001662 thread_list->ResumeAll(true);
1663 } else {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001664 VLOG(jdwp) << " Resuming event thread only";
Elliott Hughesd07986f2011-12-06 18:27:45 -08001665 thread_list->Resume(targetThread, true);
1666 }
1667
1668 // Wait for the request to finish executing.
1669 while (req->invoke_needed_) {
1670 req->cond_.Wait(req->lock_);
1671 }
1672 }
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001673 VLOG(jdwp) << " Control has returned from event thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08001674
1675 /* wait for thread to re-suspend itself */
1676 targetThread->WaitUntilSuspended();
1677 //dvmWaitForSuspend(targetThread);
1678 }
1679
1680 /*
1681 * Suspend the threads. We waited for the target thread to suspend
1682 * itself, so all we need to do is suspend the others.
1683 *
1684 * The suspendAllThreads() call will double-suspend the event thread,
1685 * so we want to resume the target thread once to keep the books straight.
1686 */
1687 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001688 VLOG(jdwp) << " Suspending all threads";
Elliott Hughesd07986f2011-12-06 18:27:45 -08001689 thread_list->SuspendAll(true);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001690 VLOG(jdwp) << " Resuming event thread to balance the count";
Elliott Hughesd07986f2011-12-06 18:27:45 -08001691 thread_list->Resume(targetThread, true);
1692 }
1693
1694 // Copy the result.
1695 *pResultTag = req->result_tag;
1696 if (IsPrimitiveTag(req->result_tag)) {
1697 *pResultValue = req->result_value.j;
1698 } else {
1699 *pResultValue = gRegistry->Add(req->result_value.l);
1700 }
1701 *pExceptionId = req->exception;
1702 return req->error;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001703}
1704
1705void Dbg::ExecuteMethod(DebugInvokeReq* pReq) {
Elliott Hughesd07986f2011-12-06 18:27:45 -08001706 Thread* self = Thread::Current();
1707
1708 // We can be called while an exception is pending in the VM. We need
1709 // to preserve that across the method invocation.
1710 SirtRef<Throwable> old_exception(self->GetException());
1711 self->ClearException();
1712
1713 ScopedThreadStateChange tsc(self, Thread::kRunnable);
1714
1715 // Translate the method through the vtable, unless the debugger wants to suppress it.
1716 Method* m = pReq->method_;
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001717 VLOG(jdwp) << "ExecuteMethod " << PrettyMethod(m);
Elliott Hughesd07986f2011-12-06 18:27:45 -08001718 if ((pReq->options_ & JDWP::INVOKE_NONVIRTUAL) == 0 && pReq->receiver_ != NULL) {
1719 m = pReq->class_->FindVirtualMethodForVirtualOrInterface(pReq->method_);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001720 VLOG(jdwp) << "ExecuteMethod " << PrettyMethod(m);
Elliott Hughesd07986f2011-12-06 18:27:45 -08001721 }
1722 CHECK(m != NULL);
1723
1724 CHECK_EQ(sizeof(jvalue), sizeof(uint64_t));
1725
1726 pReq->result_value = InvokeWithJValues(self, pReq->receiver_, m, reinterpret_cast<JValue*>(pReq->arg_array_));
1727
1728 pReq->exception = gRegistry->Add(self->GetException());
1729 pReq->result_tag = BasicTagFromDescriptor(MethodHelper(m).GetShorty());
1730 if (pReq->exception != 0) {
1731 Object* exc = self->GetException();
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001732 VLOG(jdwp) << " JDWP invocation returning with exception=" << exc << " " << PrettyTypeOf(exc);
Elliott Hughesd07986f2011-12-06 18:27:45 -08001733 self->ClearException();
1734 pReq->result_value.j = 0;
1735 } else if (pReq->result_tag == JDWP::JT_OBJECT) {
1736 /* if no exception thrown, examine object result more closely */
1737 JDWP::JdwpTag new_tag = TagFromObject(pReq->result_value.l);
1738 if (new_tag != pReq->result_tag) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001739 VLOG(jdwp) << " JDWP promoted result from " << pReq->result_tag << " to " << new_tag;
Elliott Hughesd07986f2011-12-06 18:27:45 -08001740 pReq->result_tag = new_tag;
1741 }
1742
1743 /*
1744 * Register the object. We don't actually need an ObjectId yet,
1745 * but we do need to be sure that the GC won't move or discard the
1746 * object when we switch out of RUNNING. The ObjectId conversion
1747 * will add the object to the "do not touch" list.
1748 *
1749 * We can't use the "tracked allocation" mechanism here because
1750 * the object is going to be handed off to a different thread.
1751 */
1752 gRegistry->Add(pReq->result_value.l);
1753 }
1754
1755 if (old_exception.get() != NULL) {
1756 self->SetException(old_exception.get());
1757 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001758}
1759
Elliott Hughesd07986f2011-12-06 18:27:45 -08001760/*
1761 * Register an object ID that might not have been registered previously.
1762 *
1763 * Normally this wouldn't happen -- the conversion to an ObjectId would
1764 * have added the object to the registry -- but in some cases (e.g.
1765 * throwing exceptions) we really want to do the registration late.
1766 */
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001767void Dbg::RegisterObjectId(JDWP::ObjectId id) {
Elliott Hughesd07986f2011-12-06 18:27:45 -08001768 gRegistry->Add(reinterpret_cast<Object*>(id));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001769}
1770
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001771/*
1772 * "buf" contains a full JDWP packet, possibly with multiple chunks. We
1773 * need to process each, accumulate the replies, and ship the whole thing
1774 * back.
1775 *
1776 * Returns "true" if we have a reply. The reply buffer is newly allocated,
1777 * and includes the chunk type/length, followed by the data.
1778 *
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001779 * OLD-TODO: we currently assume that the request and reply include a single
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001780 * chunk. If this becomes inconvenient we will need to adapt.
1781 */
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001782bool Dbg::DdmHandlePacket(const uint8_t* buf, int dataLen, uint8_t** pReplyBuf, int* pReplyLen) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001783 CHECK_GE(dataLen, 0);
1784
1785 Thread* self = Thread::Current();
1786 JNIEnv* env = self->GetJniEnv();
1787
Elliott Hughes844f9a02012-01-24 20:19:58 -08001788 static jclass Chunk_class = CacheClass(env, "org/apache/harmony/dalvik/ddmc/Chunk");
1789 static jclass DdmServer_class = CacheClass(env, "org/apache/harmony/dalvik/ddmc/DdmServer");
1790 static jmethodID dispatch_mid = env->GetStaticMethodID(DdmServer_class, "dispatch", "(I[BII)Lorg/apache/harmony/dalvik/ddmc/Chunk;");
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001791 static jfieldID data_fid = env->GetFieldID(Chunk_class, "data", "[B");
1792 static jfieldID length_fid = env->GetFieldID(Chunk_class, "length", "I");
1793 static jfieldID offset_fid = env->GetFieldID(Chunk_class, "offset", "I");
1794 static jfieldID type_fid = env->GetFieldID(Chunk_class, "type", "I");
1795
1796 // Create a byte[] corresponding to 'buf'.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001797 ScopedLocalRef<jbyteArray> dataArray(env, env->NewByteArray(dataLen));
1798 if (dataArray.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001799 LOG(WARNING) << "byte[] allocation failed: " << dataLen;
1800 env->ExceptionClear();
1801 return false;
1802 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001803 env->SetByteArrayRegion(dataArray.get(), 0, dataLen, reinterpret_cast<const jbyte*>(buf));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001804
1805 const int kChunkHdrLen = 8;
1806
1807 // Run through and find all chunks. [Currently just find the first.]
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001808 ScopedByteArrayRO contents(env, dataArray.get());
Elliott Hughesf7c3b662011-10-27 12:04:56 -07001809 jint type = JDWP::Get4BE(reinterpret_cast<const uint8_t*>(&contents[0]));
1810 jint length = JDWP::Get4BE(reinterpret_cast<const uint8_t*>(&contents[4]));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001811 jint offset = kChunkHdrLen;
1812 if (offset + length > dataLen) {
1813 LOG(WARNING) << StringPrintf("bad chunk found (len=%u pktLen=%d)", length, dataLen);
1814 return false;
1815 }
1816
1817 // Call "private static Chunk dispatch(int type, byte[] data, int offset, int length)".
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001818 ScopedLocalRef<jobject> chunk(env, env->CallStaticObjectMethod(DdmServer_class, dispatch_mid, type, dataArray.get(), offset, length));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001819 if (env->ExceptionCheck()) {
1820 LOG(INFO) << StringPrintf("Exception thrown by dispatcher for 0x%08x", type);
1821 env->ExceptionDescribe();
1822 env->ExceptionClear();
1823 return false;
1824 }
1825
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001826 if (chunk.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001827 return false;
1828 }
1829
1830 /*
1831 * Pull the pieces out of the chunk. We copy the results into a
1832 * newly-allocated buffer that the caller can free. We don't want to
1833 * continue using the Chunk object because nothing has a reference to it.
1834 *
1835 * We could avoid this by returning type/data/offset/length and having
1836 * the caller be aware of the object lifetime issues, but that
1837 * integrates the JDWP code more tightly into the VM, and doesn't work
1838 * if we have responses for multiple chunks.
1839 *
1840 * So we're pretty much stuck with copying data around multiple times.
1841 */
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001842 ScopedLocalRef<jbyteArray> replyData(env, reinterpret_cast<jbyteArray>(env->GetObjectField(chunk.get(), data_fid)));
1843 length = env->GetIntField(chunk.get(), length_fid);
1844 offset = env->GetIntField(chunk.get(), offset_fid);
1845 type = env->GetIntField(chunk.get(), type_fid);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001846
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001847 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 -07001848 if (length == 0 || replyData.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001849 return false;
1850 }
1851
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001852 jsize replyLength = env->GetArrayLength(replyData.get());
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001853 if (offset + length > replyLength) {
1854 LOG(WARNING) << StringPrintf("chunk off=%d len=%d exceeds reply array len %d", offset, length, replyLength);
1855 return false;
1856 }
1857
1858 uint8_t* reply = new uint8_t[length + kChunkHdrLen];
1859 if (reply == NULL) {
1860 LOG(WARNING) << "malloc failed: " << (length + kChunkHdrLen);
1861 return false;
1862 }
Elliott Hughesf7c3b662011-10-27 12:04:56 -07001863 JDWP::Set4BE(reply + 0, type);
1864 JDWP::Set4BE(reply + 4, length);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001865 env->GetByteArrayRegion(replyData.get(), offset, length, reinterpret_cast<jbyte*>(reply + kChunkHdrLen));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001866
1867 *pReplyBuf = reply;
1868 *pReplyLen = length + kChunkHdrLen;
1869
Elliott Hughesba8eee12012-01-24 20:25:24 -08001870 VLOG(jdwp) << StringPrintf("dvmHandleDdm returning type=%.4s buf=%p len=%d", reinterpret_cast<char*>(reply), reply, length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001871 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001872}
1873
Elliott Hughesa2155262011-11-16 16:26:58 -08001874void Dbg::DdmBroadcast(bool connect) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001875 VLOG(jdwp) << "Broadcasting DDM " << (connect ? "connect" : "disconnect") << "...";
Elliott Hughes47fce012011-10-25 18:37:19 -07001876
1877 Thread* self = Thread::Current();
1878 if (self->GetState() != Thread::kRunnable) {
1879 LOG(ERROR) << "DDM broadcast in thread state " << self->GetState();
1880 /* try anyway? */
1881 }
1882
1883 JNIEnv* env = self->GetJniEnv();
Elliott Hughes844f9a02012-01-24 20:19:58 -08001884 static jclass DdmServer_class = CacheClass(env, "org/apache/harmony/dalvik/ddmc/DdmServer");
Elliott Hughes47fce012011-10-25 18:37:19 -07001885 static jmethodID broadcast_mid = env->GetStaticMethodID(DdmServer_class, "broadcast", "(I)V");
1886 jint event = connect ? 1 /*DdmServer.CONNECTED*/ : 2 /*DdmServer.DISCONNECTED*/;
1887 env->CallStaticVoidMethod(DdmServer_class, broadcast_mid, event);
1888 if (env->ExceptionCheck()) {
1889 LOG(ERROR) << "DdmServer.broadcast " << event << " failed";
1890 env->ExceptionDescribe();
1891 env->ExceptionClear();
1892 }
1893}
1894
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001895void Dbg::DdmConnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08001896 Dbg::DdmBroadcast(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001897}
1898
1899void Dbg::DdmDisconnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08001900 Dbg::DdmBroadcast(false);
Elliott Hughes47fce012011-10-25 18:37:19 -07001901 gDdmThreadNotification = false;
1902}
1903
1904/*
Elliott Hughes82188472011-11-07 18:11:48 -08001905 * Send a notification when a thread starts, stops, or changes its name.
Elliott Hughes47fce012011-10-25 18:37:19 -07001906 *
1907 * Because we broadcast the full set of threads when the notifications are
1908 * first enabled, it's possible for "thread" to be actively executing.
1909 */
Elliott Hughes82188472011-11-07 18:11:48 -08001910void Dbg::DdmSendThreadNotification(Thread* t, uint32_t type) {
Elliott Hughes47fce012011-10-25 18:37:19 -07001911 if (!gDdmThreadNotification) {
1912 return;
1913 }
1914
Elliott Hughes82188472011-11-07 18:11:48 -08001915 if (type == CHUNK_TYPE("THDE")) {
Elliott Hughes47fce012011-10-25 18:37:19 -07001916 uint8_t buf[4];
Elliott Hughesf7c3b662011-10-27 12:04:56 -07001917 JDWP::Set4BE(&buf[0], t->GetThinLockId());
Elliott Hughes47fce012011-10-25 18:37:19 -07001918 Dbg::DdmSendChunk(CHUNK_TYPE("THDE"), 4, buf);
Elliott Hughes82188472011-11-07 18:11:48 -08001919 } else {
1920 CHECK(type == CHUNK_TYPE("THCR") || type == CHUNK_TYPE("THNM")) << type;
Elliott Hughes899e7892012-01-24 14:57:32 -08001921 SirtRef<String> name(t->GetThreadName());
Elliott Hughes82188472011-11-07 18:11:48 -08001922 size_t char_count = (name.get() != NULL) ? name->GetLength() : 0;
1923 const jchar* chars = name->GetCharArray()->GetData();
1924
Elliott Hughes21f32d72011-11-09 17:44:13 -08001925 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08001926 JDWP::Append4BE(bytes, t->GetThinLockId());
1927 JDWP::AppendUtf16BE(bytes, chars, char_count);
Elliott Hughes21f32d72011-11-09 17:44:13 -08001928 CHECK_EQ(bytes.size(), char_count*2 + sizeof(uint32_t)*2);
1929 Dbg::DdmSendChunk(type, bytes);
Elliott Hughes47fce012011-10-25 18:37:19 -07001930 }
1931}
1932
Elliott Hughesa2155262011-11-16 16:26:58 -08001933static void DdmSendThreadStartCallback(Thread* t, void*) {
Elliott Hughes82188472011-11-07 18:11:48 -08001934 Dbg::DdmSendThreadNotification(t, CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07001935}
1936
1937void Dbg::DdmSetThreadNotification(bool enable) {
1938 // We lock the thread list to avoid sending duplicate events or missing
1939 // a thread change. We should be okay holding this lock while sending
1940 // the messages out. (We have to hold it while accessing a live thread.)
Elliott Hughesbbd9d832011-11-07 14:40:00 -08001941 ScopedThreadListLock thread_list_lock;
Elliott Hughes47fce012011-10-25 18:37:19 -07001942
1943 gDdmThreadNotification = enable;
1944 if (enable) {
Elliott Hughesbfe487b2011-10-26 15:48:55 -07001945 Runtime::Current()->GetThreadList()->ForEach(DdmSendThreadStartCallback, NULL);
Elliott Hughes47fce012011-10-25 18:37:19 -07001946 }
1947}
1948
Elliott Hughesa2155262011-11-16 16:26:58 -08001949void Dbg::PostThreadStartOrStop(Thread* t, uint32_t type) {
Elliott Hughes47fce012011-10-25 18:37:19 -07001950 if (gDebuggerActive) {
1951 JDWP::ObjectId id = gRegistry->Add(t->GetPeer());
Elliott Hughes82188472011-11-07 18:11:48 -08001952 gJdwpState->PostThreadChange(id, type == CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07001953 }
Elliott Hughes82188472011-11-07 18:11:48 -08001954 Dbg::DdmSendThreadNotification(t, type);
Elliott Hughes47fce012011-10-25 18:37:19 -07001955}
1956
1957void Dbg::PostThreadStart(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001958 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07001959}
1960
1961void Dbg::PostThreadDeath(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001962 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THDE"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001963}
1964
Elliott Hughes82188472011-11-07 18:11:48 -08001965void Dbg::DdmSendChunk(uint32_t type, size_t byte_count, const uint8_t* buf) {
Elliott Hughes3bb81562011-10-21 18:52:59 -07001966 CHECK(buf != NULL);
1967 iovec vec[1];
1968 vec[0].iov_base = reinterpret_cast<void*>(const_cast<uint8_t*>(buf));
1969 vec[0].iov_len = byte_count;
1970 Dbg::DdmSendChunkV(type, vec, 1);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001971}
1972
Elliott Hughes21f32d72011-11-09 17:44:13 -08001973void Dbg::DdmSendChunk(uint32_t type, const std::vector<uint8_t>& bytes) {
1974 DdmSendChunk(type, bytes.size(), &bytes[0]);
1975}
1976
Elliott Hughescccd84f2011-12-05 16:51:54 -08001977void Dbg::DdmSendChunkV(uint32_t type, const struct iovec* iov, int iov_count) {
Elliott Hughes3bb81562011-10-21 18:52:59 -07001978 if (gJdwpState == NULL) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001979 VLOG(jdwp) << "Debugger thread not active, ignoring DDM send: " << type;
Elliott Hughes3bb81562011-10-21 18:52:59 -07001980 } else {
Elliott Hughescccd84f2011-12-05 16:51:54 -08001981 gJdwpState->DdmSendChunkV(type, iov, iov_count);
Elliott Hughes3bb81562011-10-21 18:52:59 -07001982 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001983}
1984
Elliott Hughes767a1472011-10-26 18:49:02 -07001985int Dbg::DdmHandleHpifChunk(HpifWhen when) {
1986 if (when == HPIF_WHEN_NOW) {
Elliott Hughes7162ad92011-10-27 14:08:42 -07001987 DdmSendHeapInfo(when);
Elliott Hughes767a1472011-10-26 18:49:02 -07001988 return true;
1989 }
1990
1991 if (when != HPIF_WHEN_NEVER && when != HPIF_WHEN_NEXT_GC && when != HPIF_WHEN_EVERY_GC) {
1992 LOG(ERROR) << "invalid HpifWhen value: " << static_cast<int>(when);
1993 return false;
1994 }
1995
1996 gDdmHpifWhen = when;
1997 return true;
1998}
1999
2000bool Dbg::DdmHandleHpsgNhsgChunk(Dbg::HpsgWhen when, Dbg::HpsgWhat what, bool native) {
2001 if (when != HPSG_WHEN_NEVER && when != HPSG_WHEN_EVERY_GC) {
2002 LOG(ERROR) << "invalid HpsgWhen value: " << static_cast<int>(when);
2003 return false;
2004 }
2005
2006 if (what != HPSG_WHAT_MERGED_OBJECTS && what != HPSG_WHAT_DISTINCT_OBJECTS) {
2007 LOG(ERROR) << "invalid HpsgWhat value: " << static_cast<int>(what);
2008 return false;
2009 }
2010
2011 if (native) {
2012 gDdmNhsgWhen = when;
2013 gDdmNhsgWhat = what;
2014 } else {
2015 gDdmHpsgWhen = when;
2016 gDdmHpsgWhat = what;
2017 }
2018 return true;
2019}
2020
Elliott Hughes7162ad92011-10-27 14:08:42 -07002021void Dbg::DdmSendHeapInfo(HpifWhen reason) {
2022 // If there's a one-shot 'when', reset it.
2023 if (reason == gDdmHpifWhen) {
2024 if (gDdmHpifWhen == HPIF_WHEN_NEXT_GC) {
2025 gDdmHpifWhen = HPIF_WHEN_NEVER;
2026 }
2027 }
2028
2029 /*
2030 * Chunk HPIF (client --> server)
2031 *
2032 * Heap Info. General information about the heap,
2033 * suitable for a summary display.
2034 *
2035 * [u4]: number of heaps
2036 *
2037 * For each heap:
2038 * [u4]: heap ID
2039 * [u8]: timestamp in ms since Unix epoch
2040 * [u1]: capture reason (same as 'when' value from server)
2041 * [u4]: max heap size in bytes (-Xmx)
2042 * [u4]: current heap size in bytes
2043 * [u4]: current number of bytes allocated
2044 * [u4]: current number of objects allocated
2045 */
2046 uint8_t heap_count = 1;
Elliott Hughes21f32d72011-11-09 17:44:13 -08002047 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08002048 JDWP::Append4BE(bytes, heap_count);
2049 JDWP::Append4BE(bytes, 1); // Heap id (bogus; we only have one heap).
2050 JDWP::Append8BE(bytes, MilliTime());
2051 JDWP::Append1BE(bytes, reason);
2052 JDWP::Append4BE(bytes, Heap::GetMaxMemory()); // Max allowed heap size in bytes.
2053 JDWP::Append4BE(bytes, Heap::GetTotalMemory()); // Current heap size in bytes.
2054 JDWP::Append4BE(bytes, Heap::GetBytesAllocated());
2055 JDWP::Append4BE(bytes, Heap::GetObjectsAllocated());
Elliott Hughes21f32d72011-11-09 17:44:13 -08002056 CHECK_EQ(bytes.size(), 4U + (heap_count * (4 + 8 + 1 + 4 + 4 + 4 + 4)));
2057 Dbg::DdmSendChunk(CHUNK_TYPE("HPIF"), bytes);
Elliott Hughes767a1472011-10-26 18:49:02 -07002058}
2059
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002060enum HpsgSolidity {
2061 SOLIDITY_FREE = 0,
2062 SOLIDITY_HARD = 1,
2063 SOLIDITY_SOFT = 2,
2064 SOLIDITY_WEAK = 3,
2065 SOLIDITY_PHANTOM = 4,
2066 SOLIDITY_FINALIZABLE = 5,
2067 SOLIDITY_SWEEP = 6,
2068};
2069
2070enum HpsgKind {
2071 KIND_OBJECT = 0,
2072 KIND_CLASS_OBJECT = 1,
2073 KIND_ARRAY_1 = 2,
2074 KIND_ARRAY_2 = 3,
2075 KIND_ARRAY_4 = 4,
2076 KIND_ARRAY_8 = 5,
2077 KIND_UNKNOWN = 6,
2078 KIND_NATIVE = 7,
2079};
2080
2081#define HPSG_PARTIAL (1<<7)
2082#define HPSG_STATE(solidity, kind) ((uint8_t)((((kind) & 0x7) << 3) | ((solidity) & 0x7)))
2083
Ian Rogers30fab402012-01-23 15:43:46 -08002084class HeapChunkContext {
2085 public:
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002086 // Maximum chunk size. Obtain this from the formula:
2087 // (((maximum_heap_size / ALLOCATION_UNIT_SIZE) + 255) / 256) * 2
2088 HeapChunkContext(bool merge, bool native)
Ian Rogers30fab402012-01-23 15:43:46 -08002089 : buf_(16384 - 16),
2090 type_(0),
2091 merge_(merge) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002092 Reset();
2093 if (native) {
Ian Rogers30fab402012-01-23 15:43:46 -08002094 type_ = CHUNK_TYPE("NHSG");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002095 } else {
Ian Rogers30fab402012-01-23 15:43:46 -08002096 type_ = merge ? CHUNK_TYPE("HPSG") : CHUNK_TYPE("HPSO");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002097 }
2098 }
2099
2100 ~HeapChunkContext() {
Ian Rogers30fab402012-01-23 15:43:46 -08002101 if (p_ > &buf_[0]) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002102 Flush();
2103 }
2104 }
2105
2106 void EnsureHeader(const void* chunk_ptr) {
Ian Rogers30fab402012-01-23 15:43:46 -08002107 if (!needHeader_) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002108 return;
2109 }
2110
2111 // Start a new HPSx chunk.
Ian Rogers30fab402012-01-23 15:43:46 -08002112 JDWP::Write4BE(&p_, 1); // Heap id (bogus; we only have one heap).
2113 JDWP::Write1BE(&p_, 8); // Size of allocation unit, in bytes.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002114
Ian Rogers30fab402012-01-23 15:43:46 -08002115 JDWP::Write4BE(&p_, reinterpret_cast<uintptr_t>(chunk_ptr)); // virtual address of segment start.
2116 JDWP::Write4BE(&p_, 0); // offset of this piece (relative to the virtual address).
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002117 // [u4]: length of piece, in allocation units
2118 // 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 -08002119 pieceLenField_ = p_;
2120 JDWP::Write4BE(&p_, 0x55555555);
2121 needHeader_ = false;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002122 }
2123
2124 void Flush() {
2125 // Patch the "length of piece" field.
Ian Rogers30fab402012-01-23 15:43:46 -08002126 CHECK_LE(&buf_[0], pieceLenField_);
2127 CHECK_LE(pieceLenField_, p_);
2128 JDWP::Set4BE(pieceLenField_, totalAllocationUnits_);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002129
Ian Rogers30fab402012-01-23 15:43:46 -08002130 Dbg::DdmSendChunk(type_, p_ - &buf_[0], &buf_[0]);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002131 Reset();
2132 }
2133
Ian Rogers30fab402012-01-23 15:43:46 -08002134 static void HeapChunkCallback(void* start, void* end, size_t used_bytes, void* arg) {
2135 reinterpret_cast<HeapChunkContext*>(arg)->HeapChunkCallback(start, end, used_bytes);
Elliott Hughesa2155262011-11-16 16:26:58 -08002136 }
2137
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002138 private:
Elliott Hughesa2155262011-11-16 16:26:58 -08002139 enum { ALLOCATION_UNIT_SIZE = 8 };
2140
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002141 void Reset() {
Ian Rogers30fab402012-01-23 15:43:46 -08002142 p_ = &buf_[0];
2143 totalAllocationUnits_ = 0;
2144 needHeader_ = true;
2145 pieceLenField_ = NULL;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002146 }
2147
Ian Rogers30fab402012-01-23 15:43:46 -08002148 void HeapChunkCallback(void* start, void* end, size_t used_bytes) {
2149 // Note: heap call backs cannot manipulate the heap upon which they are crawling, care is taken
2150 // in the following code not to allocate memory, by ensuring buf_ is of the correct size
2151
2152 const void* user_ptr = used_bytes > 0 ? const_cast<void*>(start) : NULL;
2153 // from malloc.c mem2chunk(mem)
2154 const void* chunk_ptr =
2155 reinterpret_cast<const void*>(reinterpret_cast<const char*>(const_cast<void*>(start)) -
2156 (2 * sizeof(size_t)));
2157 // from malloc.c chunksize
2158 size_t chunk_len = (*reinterpret_cast<size_t* const*>(chunk_ptr))[1] & ~7;
2159
2160
2161 //size_t chunk_len = malloc_usable_size(user_ptr);
Elliott Hughesa2155262011-11-16 16:26:58 -08002162 CHECK_EQ((chunk_len & (ALLOCATION_UNIT_SIZE-1)), 0U);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002163
Elliott Hughesa2155262011-11-16 16:26:58 -08002164 /* Make sure there's enough room left in the buffer.
2165 * We need to use two bytes for every fractional 256
2166 * allocation units used by the chunk.
2167 */
2168 {
2169 size_t needed = (((chunk_len/ALLOCATION_UNIT_SIZE + 255) / 256) * 2);
Ian Rogers30fab402012-01-23 15:43:46 -08002170 size_t bytesLeft = buf_.size() - (size_t)(p_ - &buf_[0]);
Elliott Hughesa2155262011-11-16 16:26:58 -08002171 if (bytesLeft < needed) {
2172 Flush();
2173 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002174
Ian Rogers30fab402012-01-23 15:43:46 -08002175 bytesLeft = buf_.size() - (size_t)(p_ - &buf_[0]);
Elliott Hughesa2155262011-11-16 16:26:58 -08002176 if (bytesLeft < needed) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08002177 LOG(WARNING) << "Chunk is too big to transmit (chunk_len=" << chunk_len << ", " << needed << " bytes)";
Elliott Hughesa2155262011-11-16 16:26:58 -08002178 return;
2179 }
2180 }
2181
2182 // OLD-TODO: notice when there's a gap and start a new heap, or at least a new range.
2183 EnsureHeader(chunk_ptr);
2184
2185 // Determine the type of this chunk.
2186 // OLD-TODO: if context.merge, see if this chunk is different from the last chunk.
2187 // If it's the same, we should combine them.
Ian Rogers30fab402012-01-23 15:43:46 -08002188 uint8_t state = ExamineObject(reinterpret_cast<const Object*>(user_ptr), (type_ == CHUNK_TYPE("NHSG")));
Elliott Hughesa2155262011-11-16 16:26:58 -08002189
2190 // Write out the chunk description.
2191 chunk_len /= ALLOCATION_UNIT_SIZE; // convert to allocation units
Ian Rogers30fab402012-01-23 15:43:46 -08002192 totalAllocationUnits_ += chunk_len;
Elliott Hughesa2155262011-11-16 16:26:58 -08002193 while (chunk_len > 256) {
Ian Rogers30fab402012-01-23 15:43:46 -08002194 *p_++ = state | HPSG_PARTIAL;
2195 *p_++ = 255; // length - 1
Elliott Hughesa2155262011-11-16 16:26:58 -08002196 chunk_len -= 256;
2197 }
Ian Rogers30fab402012-01-23 15:43:46 -08002198 *p_++ = state;
2199 *p_++ = chunk_len - 1;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002200 }
2201
Elliott Hughesa2155262011-11-16 16:26:58 -08002202 uint8_t ExamineObject(const Object* o, bool is_native_heap) {
2203 if (o == NULL) {
2204 return HPSG_STATE(SOLIDITY_FREE, 0);
2205 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002206
Elliott Hughesa2155262011-11-16 16:26:58 -08002207 // It's an allocated chunk. Figure out what it is.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002208
Elliott Hughesa2155262011-11-16 16:26:58 -08002209 // If we're looking at the native heap, we'll just return
2210 // (SOLIDITY_HARD, KIND_NATIVE) for all allocated chunks.
2211 if (is_native_heap || !Heap::IsLiveObjectLocked(o)) {
2212 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
2213 }
2214
2215 Class* c = o->GetClass();
2216 if (c == NULL) {
2217 // The object was probably just created but hasn't been initialized yet.
2218 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
2219 }
2220
2221 if (!Heap::IsHeapAddress(c)) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08002222 LOG(WARNING) << "Invalid class for managed heap object: " << o << " " << c;
Elliott Hughesa2155262011-11-16 16:26:58 -08002223 return HPSG_STATE(SOLIDITY_HARD, KIND_UNKNOWN);
2224 }
2225
2226 if (c->IsClassClass()) {
2227 return HPSG_STATE(SOLIDITY_HARD, KIND_CLASS_OBJECT);
2228 }
2229
2230 if (c->IsArrayClass()) {
2231 if (o->IsObjectArray()) {
2232 return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
2233 }
2234 switch (c->GetComponentSize()) {
2235 case 1: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_1);
2236 case 2: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_2);
2237 case 4: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
2238 case 8: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_8);
2239 }
2240 }
2241
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002242 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
2243 }
2244
Ian Rogers30fab402012-01-23 15:43:46 -08002245 std::vector<uint8_t> buf_;
2246 uint8_t* p_;
2247 uint8_t* pieceLenField_;
2248 size_t totalAllocationUnits_;
2249 uint32_t type_;
2250 bool merge_;
2251 bool needHeader_;
2252
Elliott Hughesa2155262011-11-16 16:26:58 -08002253 DISALLOW_COPY_AND_ASSIGN(HeapChunkContext);
2254};
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002255
2256void Dbg::DdmSendHeapSegments(bool native) {
2257 Dbg::HpsgWhen when;
2258 Dbg::HpsgWhat what;
2259 if (!native) {
2260 when = gDdmHpsgWhen;
2261 what = gDdmHpsgWhat;
2262 } else {
2263 when = gDdmNhsgWhen;
2264 what = gDdmNhsgWhat;
2265 }
2266 if (when == HPSG_WHEN_NEVER) {
2267 return;
2268 }
2269
2270 // Figure out what kind of chunks we'll be sending.
2271 CHECK(what == HPSG_WHAT_MERGED_OBJECTS || what == HPSG_WHAT_DISTINCT_OBJECTS) << static_cast<int>(what);
2272
2273 // First, send a heap start chunk.
2274 uint8_t heap_id[4];
2275 JDWP::Set4BE(&heap_id[0], 1); // Heap id (bogus; we only have one heap).
2276 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHST") : CHUNK_TYPE("HPST"), sizeof(heap_id), heap_id);
2277
2278 // Send a series of heap segment chunks.
Elliott Hughesa2155262011-11-16 16:26:58 -08002279 HeapChunkContext context((what == HPSG_WHAT_MERGED_OBJECTS), native);
2280 if (native) {
Ian Rogers30fab402012-01-23 15:43:46 -08002281 // TODO: enable when bionic has moved to dlmalloc 2.8.5
2282 // dlmalloc_inspect_all(HeapChunkContext::HeapChunkCallback, &context);
2283 UNIMPLEMENTED(WARNING) << "Native heap send heap segments";
Elliott Hughesa2155262011-11-16 16:26:58 -08002284 } else {
Ian Rogers30fab402012-01-23 15:43:46 -08002285 Heap::GetAllocSpace()->Walk(HeapChunkContext::HeapChunkCallback, &context);
Elliott Hughesa2155262011-11-16 16:26:58 -08002286 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002287
2288 // Finally, send a heap end chunk.
2289 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHEN") : CHUNK_TYPE("HPEN"), sizeof(heap_id), heap_id);
Elliott Hughes767a1472011-10-26 18:49:02 -07002290}
2291
Elliott Hughes545a0642011-11-08 19:10:03 -08002292void Dbg::SetAllocTrackingEnabled(bool enabled) {
2293 MutexLock mu(gAllocTrackerLock);
2294 if (enabled) {
2295 if (recent_allocation_records_ == NULL) {
2296 LOG(INFO) << "Enabling alloc tracker (" << kNumAllocRecords << " entries, "
2297 << kMaxAllocRecordStackDepth << " frames --> "
2298 << (sizeof(AllocRecord) * kNumAllocRecords) << " bytes)";
2299 gAllocRecordHead = gAllocRecordCount = 0;
2300 recent_allocation_records_ = new AllocRecord[kNumAllocRecords];
2301 CHECK(recent_allocation_records_ != NULL);
2302 }
2303 } else {
2304 delete[] recent_allocation_records_;
2305 recent_allocation_records_ = NULL;
2306 }
2307}
2308
2309struct AllocRecordStackVisitor : public Thread::StackVisitor {
Elliott Hughesba8eee12012-01-24 20:25:24 -08002310 explicit AllocRecordStackVisitor(AllocRecord* record) : record(record), depth(0) {
Elliott Hughes545a0642011-11-08 19:10:03 -08002311 }
2312
2313 virtual void VisitFrame(const Frame& f, uintptr_t pc) {
2314 if (depth >= kMaxAllocRecordStackDepth) {
2315 return;
2316 }
2317 Method* m = f.GetMethod();
2318 if (m == NULL || m->IsCalleeSaveMethod()) {
2319 return;
2320 }
2321 record->stack[depth].method = m;
2322 record->stack[depth].raw_pc = pc;
2323 ++depth;
2324 }
2325
2326 ~AllocRecordStackVisitor() {
2327 // Clear out any unused stack trace elements.
2328 for (; depth < kMaxAllocRecordStackDepth; ++depth) {
2329 record->stack[depth].method = NULL;
2330 record->stack[depth].raw_pc = 0;
2331 }
2332 }
2333
2334 AllocRecord* record;
2335 size_t depth;
2336};
2337
2338void Dbg::RecordAllocation(Class* type, size_t byte_count) {
2339 Thread* self = Thread::Current();
2340 CHECK(self != NULL);
2341
2342 MutexLock mu(gAllocTrackerLock);
2343 if (recent_allocation_records_ == NULL) {
2344 return;
2345 }
2346
2347 // Advance and clip.
2348 if (++gAllocRecordHead == kNumAllocRecords) {
2349 gAllocRecordHead = 0;
2350 }
2351
2352 // Fill in the basics.
2353 AllocRecord* record = &recent_allocation_records_[gAllocRecordHead];
2354 record->type = type;
2355 record->byte_count = byte_count;
2356 record->thin_lock_id = self->GetThinLockId();
2357
2358 // Fill in the stack trace.
2359 AllocRecordStackVisitor visitor(record);
2360 self->WalkStack(&visitor);
2361
2362 if (gAllocRecordCount < kNumAllocRecords) {
2363 ++gAllocRecordCount;
2364 }
2365}
2366
2367/*
2368 * Return the index of the head element.
2369 *
2370 * We point at the most-recently-written record, so if allocRecordCount is 1
2371 * we want to use the current element. Take "head+1" and subtract count
2372 * from it.
2373 *
2374 * We need to handle underflow in our circular buffer, so we add
2375 * kNumAllocRecords and then mask it back down.
2376 */
2377inline static int headIndex() {
2378 return (gAllocRecordHead+1 + kNumAllocRecords - gAllocRecordCount) & (kNumAllocRecords-1);
2379}
2380
2381void Dbg::DumpRecentAllocations() {
2382 MutexLock mu(gAllocTrackerLock);
2383 if (recent_allocation_records_ == NULL) {
2384 LOG(INFO) << "Not recording tracked allocations";
2385 return;
2386 }
2387
2388 // "i" is the head of the list. We want to start at the end of the
2389 // list and move forward to the tail.
2390 size_t i = headIndex();
2391 size_t count = gAllocRecordCount;
2392
2393 LOG(INFO) << "Tracked allocations, (head=" << gAllocRecordHead << " count=" << count << ")";
2394 while (count--) {
2395 AllocRecord* record = &recent_allocation_records_[i];
2396
Elliott Hughesaa6e1cd2012-01-18 19:26:06 -08002397 LOG(INFO) << StringPrintf(" T=%-2d %6zd ", record->thin_lock_id, record->byte_count)
Elliott Hughes545a0642011-11-08 19:10:03 -08002398 << PrettyClass(record->type);
2399
2400 for (size_t stack_frame = 0; stack_frame < kMaxAllocRecordStackDepth; ++stack_frame) {
2401 const Method* m = record->stack[stack_frame].method;
2402 if (m == NULL) {
2403 break;
2404 }
2405 LOG(INFO) << " " << PrettyMethod(m) << " line " << record->stack[stack_frame].LineNumber();
2406 }
2407
2408 // pause periodically to help logcat catch up
2409 if ((count % 5) == 0) {
2410 usleep(40000);
2411 }
2412
2413 i = (i + 1) & (kNumAllocRecords-1);
2414 }
2415}
2416
2417class StringTable {
2418 public:
2419 StringTable() {
2420 }
2421
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002422 void Add(const char* s) {
Elliott Hughes545a0642011-11-08 19:10:03 -08002423 table_.insert(s);
2424 }
2425
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002426 size_t IndexOf(const char* s) {
Elliott Hughes545a0642011-11-08 19:10:03 -08002427 return std::distance(table_.begin(), table_.find(s));
2428 }
2429
2430 size_t Size() {
2431 return table_.size();
2432 }
2433
2434 void WriteTo(std::vector<uint8_t>& bytes) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002435 typedef std::set<const char*>::const_iterator It; // TODO: C++0x auto
Elliott Hughes545a0642011-11-08 19:10:03 -08002436 for (It it = table_.begin(); it != table_.end(); ++it) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002437 const char* s = *it;
2438 size_t s_len = CountModifiedUtf8Chars(s);
2439 UniquePtr<uint16_t> s_utf16(new uint16_t[s_len]);
2440 ConvertModifiedUtf8ToUtf16(s_utf16.get(), s);
2441 JDWP::AppendUtf16BE(bytes, s_utf16.get(), s_len);
Elliott Hughes545a0642011-11-08 19:10:03 -08002442 }
2443 }
2444
2445 private:
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002446 std::set<const char*> table_;
Elliott Hughes545a0642011-11-08 19:10:03 -08002447 DISALLOW_COPY_AND_ASSIGN(StringTable);
2448};
2449
2450/*
2451 * The data we send to DDMS contains everything we have recorded.
2452 *
2453 * Message header (all values big-endian):
2454 * (1b) message header len (to allow future expansion); includes itself
2455 * (1b) entry header len
2456 * (1b) stack frame len
2457 * (2b) number of entries
2458 * (4b) offset to string table from start of message
2459 * (2b) number of class name strings
2460 * (2b) number of method name strings
2461 * (2b) number of source file name strings
2462 * For each entry:
2463 * (4b) total allocation size
2464 * (2b) threadId
2465 * (2b) allocated object's class name index
2466 * (1b) stack depth
2467 * For each stack frame:
2468 * (2b) method's class name
2469 * (2b) method name
2470 * (2b) method source file
2471 * (2b) line number, clipped to 32767; -2 if native; -1 if no source
2472 * (xb) class name strings
2473 * (xb) method name strings
2474 * (xb) source file strings
2475 *
2476 * As with other DDM traffic, strings are sent as a 4-byte length
2477 * followed by UTF-16 data.
2478 *
2479 * We send up 16-bit unsigned indexes into string tables. In theory there
2480 * can be (kMaxAllocRecordStackDepth * kNumAllocRecords) unique strings in
2481 * each table, but in practice there should be far fewer.
2482 *
2483 * The chief reason for using a string table here is to keep the size of
2484 * the DDMS message to a minimum. This is partly to make the protocol
2485 * efficient, but also because we have to form the whole thing up all at
2486 * once in a memory buffer.
2487 *
2488 * We use separate string tables for class names, method names, and source
2489 * files to keep the indexes small. There will generally be no overlap
2490 * between the contents of these tables.
2491 */
2492jbyteArray Dbg::GetRecentAllocations() {
2493 if (false) {
2494 DumpRecentAllocations();
2495 }
2496
2497 MutexLock mu(gAllocTrackerLock);
2498
2499 /*
2500 * Part 1: generate string tables.
2501 */
2502 StringTable class_names;
2503 StringTable method_names;
2504 StringTable filenames;
2505
2506 int count = gAllocRecordCount;
2507 int idx = headIndex();
2508 while (count--) {
2509 AllocRecord* record = &recent_allocation_records_[idx];
2510
Elliott Hughes91250e02011-12-13 22:30:35 -08002511 class_names.Add(ClassHelper(record->type).GetDescriptor());
Elliott Hughes545a0642011-11-08 19:10:03 -08002512
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002513 MethodHelper mh;
Elliott Hughes545a0642011-11-08 19:10:03 -08002514 for (size_t i = 0; i < kMaxAllocRecordStackDepth; i++) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002515 Method* m = record->stack[i].method;
2516 mh.ChangeMethod(m);
Elliott Hughes545a0642011-11-08 19:10:03 -08002517 if (m != NULL) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002518 class_names.Add(mh.GetDeclaringClassDescriptor());
2519 method_names.Add(mh.GetName());
2520 filenames.Add(mh.GetDeclaringClassSourceFile());
Elliott Hughes545a0642011-11-08 19:10:03 -08002521 }
2522 }
2523
2524 idx = (idx + 1) & (kNumAllocRecords-1);
2525 }
2526
2527 LOG(INFO) << "allocation records: " << gAllocRecordCount;
2528
2529 /*
2530 * Part 2: allocate a buffer and generate the output.
2531 */
2532 std::vector<uint8_t> bytes;
2533
2534 // (1b) message header len (to allow future expansion); includes itself
2535 // (1b) entry header len
2536 // (1b) stack frame len
2537 const int kMessageHeaderLen = 15;
2538 const int kEntryHeaderLen = 9;
2539 const int kStackFrameLen = 8;
2540 JDWP::Append1BE(bytes, kMessageHeaderLen);
2541 JDWP::Append1BE(bytes, kEntryHeaderLen);
2542 JDWP::Append1BE(bytes, kStackFrameLen);
2543
2544 // (2b) number of entries
2545 // (4b) offset to string table from start of message
2546 // (2b) number of class name strings
2547 // (2b) number of method name strings
2548 // (2b) number of source file name strings
2549 JDWP::Append2BE(bytes, gAllocRecordCount);
2550 size_t string_table_offset = bytes.size();
2551 JDWP::Append4BE(bytes, 0); // We'll patch this later...
2552 JDWP::Append2BE(bytes, class_names.Size());
2553 JDWP::Append2BE(bytes, method_names.Size());
2554 JDWP::Append2BE(bytes, filenames.Size());
2555
2556 count = gAllocRecordCount;
2557 idx = headIndex();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002558 ClassHelper kh;
Elliott Hughes545a0642011-11-08 19:10:03 -08002559 while (count--) {
2560 // For each entry:
2561 // (4b) total allocation size
2562 // (2b) thread id
2563 // (2b) allocated object's class name index
2564 // (1b) stack depth
2565 AllocRecord* record = &recent_allocation_records_[idx];
2566 size_t stack_depth = record->GetDepth();
2567 JDWP::Append4BE(bytes, record->byte_count);
2568 JDWP::Append2BE(bytes, record->thin_lock_id);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002569 kh.ChangeClass(record->type);
Elliott Hughes91250e02011-12-13 22:30:35 -08002570 JDWP::Append2BE(bytes, class_names.IndexOf(kh.GetDescriptor()));
Elliott Hughes545a0642011-11-08 19:10:03 -08002571 JDWP::Append1BE(bytes, stack_depth);
2572
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002573 MethodHelper mh;
Elliott Hughes545a0642011-11-08 19:10:03 -08002574 for (size_t stack_frame = 0; stack_frame < stack_depth; ++stack_frame) {
2575 // For each stack frame:
2576 // (2b) method's class name
2577 // (2b) method name
2578 // (2b) method source file
2579 // (2b) line number, clipped to 32767; -2 if native; -1 if no source
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002580 mh.ChangeMethod(record->stack[stack_frame].method);
2581 JDWP::Append2BE(bytes, class_names.IndexOf(mh.GetDeclaringClassDescriptor()));
2582 JDWP::Append2BE(bytes, method_names.IndexOf(mh.GetName()));
2583 JDWP::Append2BE(bytes, filenames.IndexOf(mh.GetDeclaringClassSourceFile()));
Elliott Hughes545a0642011-11-08 19:10:03 -08002584 JDWP::Append2BE(bytes, record->stack[stack_frame].LineNumber());
2585 }
2586
2587 idx = (idx + 1) & (kNumAllocRecords-1);
2588 }
2589
2590 // (xb) class name strings
2591 // (xb) method name strings
2592 // (xb) source file strings
2593 JDWP::Set4BE(&bytes[string_table_offset], bytes.size());
2594 class_names.WriteTo(bytes);
2595 method_names.WriteTo(bytes);
2596 filenames.WriteTo(bytes);
2597
2598 JNIEnv* env = Thread::Current()->GetJniEnv();
2599 jbyteArray result = env->NewByteArray(bytes.size());
2600 if (result != NULL) {
2601 env->SetByteArrayRegion(result, 0, bytes.size(), reinterpret_cast<const jbyte*>(&bytes[0]));
2602 }
2603 return result;
2604}
2605
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002606} // namespace art