blob: ef3ac88e9d74aae834bdece353e35e87b9d61b68 [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 Hughes3d30d9b2011-12-07 17:35:48 -0800163 } else if (c->InstanceOf(class_linker->FindSystemClass("Ljava/lang/Thread;"))) {
Elliott Hughes24437992011-11-30 14:49:33 -0800164 return JDWP::JT_THREAD;
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800165 } else if (c->InstanceOf(class_linker->FindSystemClass("Ljava/lang/ThreadGroup;"))) {
Elliott Hughes24437992011-11-30 14:49:33 -0800166 return JDWP::JT_THREAD_GROUP;
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800167 } else if (c->InstanceOf(class_linker->FindSystemClass("Ljava/lang/ClassLoader;"))) {
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 Hughes7b3cdfc2011-12-08 21:28:17 -0800467bool Dbg::GetSuperclass(JDWP::RefTypeId id, JDWP::RefTypeId& superclassId) {
468 Object* o = gRegistry->Get<Object*>(id);
469 if (o == NULL || !o->IsClass()) {
470 return false;
471 }
472 superclassId = gRegistry->Add(o->AsClass()->GetSuperClass());
473 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700474}
475
476JDWP::ObjectId Dbg::GetClassLoader(JDWP::RefTypeId id) {
Elliott Hughes1bba14f2011-12-01 18:00:36 -0800477 Object* o = gRegistry->Get<Object*>(id);
478 return gRegistry->Add(o->GetClass()->GetClassLoader());
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700479}
480
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800481bool Dbg::GetAccessFlags(JDWP::RefTypeId id, uint32_t& access_flags) {
482 Object* o = gRegistry->Get<Object*>(id);
483 if (o == NULL || !o->IsClass()) {
484 return false;
485 }
486 access_flags = o->AsClass()->GetAccessFlags() & kAccJavaFlagsMask;
487 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700488}
489
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800490bool Dbg::IsInterface(JDWP::RefTypeId classId, bool& is_interface) {
491 Object* o = gRegistry->Get<Object*>(classId);
492 if (o == NULL || !o->IsClass()) {
493 return false;
494 }
495 is_interface = o->AsClass()->IsInterface();
496 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700497}
498
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800499void Dbg::GetClassList(std::vector<JDWP::RefTypeId>& classes) {
Elliott Hughesa2155262011-11-16 16:26:58 -0800500 // Get the complete list of reference classes (i.e. all classes except
501 // the primitive types).
502 // Returns a newly-allocated buffer full of RefTypeId values.
503 struct ClassListCreator {
Elliott Hughesba8eee12012-01-24 20:25:24 -0800504 explicit ClassListCreator(std::vector<JDWP::RefTypeId>& classes) : classes(classes) {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800505 }
506
Elliott Hughesa2155262011-11-16 16:26:58 -0800507 static bool Visit(Class* c, void* arg) {
508 return reinterpret_cast<ClassListCreator*>(arg)->Visit(c);
509 }
510
511 bool Visit(Class* c) {
512 if (!c->IsPrimitive()) {
513 classes.push_back(static_cast<JDWP::RefTypeId>(gRegistry->Add(c)));
514 }
515 return true;
516 }
517
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800518 std::vector<JDWP::RefTypeId>& classes;
Elliott Hughesa2155262011-11-16 16:26:58 -0800519 };
520
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800521 ClassListCreator clc(classes);
Elliott Hughesa2155262011-11-16 16:26:58 -0800522 Runtime::Current()->GetClassLinker()->VisitClasses(ClassListCreator::Visit, &clc);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700523}
524
525void Dbg::GetVisibleClassList(JDWP::ObjectId classLoaderId, uint32_t* pNumClasses, JDWP::RefTypeId** pClassRefBuf) {
526 UNIMPLEMENTED(FATAL);
527}
528
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800529bool Dbg::GetClassInfo(JDWP::RefTypeId classId, JDWP::JdwpTypeTag* pTypeTag, uint32_t* pStatus, std::string* pDescriptor) {
530 Object* o = gRegistry->Get<Object*>(classId);
531 if (o == NULL || !o->IsClass()) {
532 return false;
533 }
534
535 Class* c = o->AsClass();
Elliott Hughesa2155262011-11-16 16:26:58 -0800536 if (c->IsArrayClass()) {
537 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
538 *pTypeTag = JDWP::TT_ARRAY;
539 } else {
540 if (c->IsErroneous()) {
541 *pStatus = JDWP::CS_ERROR;
542 } else {
543 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED | JDWP::CS_INITIALIZED;
544 }
545 *pTypeTag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
546 }
547
548 if (pDescriptor != NULL) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800549 *pDescriptor = ClassHelper(c).GetDescriptor();
Elliott Hughesa2155262011-11-16 16:26:58 -0800550 }
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800551 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700552}
553
Elliott Hughesc3b77c72011-12-15 20:56:48 -0800554void Dbg::FindLoadedClassBySignature(const char* descriptor, std::vector<JDWP::RefTypeId>& ids) {
Elliott Hughes6fa602d2011-12-02 17:54:25 -0800555 std::vector<Class*> classes;
556 Runtime::Current()->GetClassLinker()->LookupClasses(descriptor, classes);
557 ids.clear();
558 for (size_t i = 0; i < classes.size(); ++i) {
559 ids.push_back(gRegistry->Add(classes[i]));
560 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700561}
562
Elliott Hughes6fa602d2011-12-02 17:54:25 -0800563void Dbg::GetObjectType(JDWP::ObjectId objectId, JDWP::JdwpTypeTag* pRefTypeTag, JDWP::RefTypeId* pRefTypeId) {
Elliott Hughes499c5132011-11-17 14:55:11 -0800564 Object* o = gRegistry->Get<Object*>(objectId);
565 if (o->GetClass()->IsArrayClass()) {
566 *pRefTypeTag = JDWP::TT_ARRAY;
567 } else if (o->GetClass()->IsInterface()) {
568 *pRefTypeTag = JDWP::TT_INTERFACE;
569 } else {
570 *pRefTypeTag = JDWP::TT_CLASS;
571 }
572 *pRefTypeId = gRegistry->Add(o->GetClass());
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700573}
574
575uint8_t Dbg::GetClassObjectType(JDWP::RefTypeId refTypeId) {
576 UNIMPLEMENTED(FATAL);
577 return 0;
578}
579
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800580bool Dbg::GetSignature(JDWP::RefTypeId refTypeId, std::string& signature) {
581 Object* o = gRegistry->Get<Object*>(refTypeId);
582 if (o == NULL || !o->IsClass()) {
583 return false;
584 }
585 signature = ClassHelper(o->AsClass()).GetDescriptor();
586 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700587}
588
Elliott Hughes03181a82011-11-17 17:22:21 -0800589bool Dbg::GetSourceFile(JDWP::RefTypeId refTypeId, std::string& result) {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800590 Object* o = gRegistry->Get<Object*>(refTypeId);
591 if (o == NULL || !o->IsClass()) {
592 return false;
593 }
594 result = ClassHelper(o->AsClass()).GetSourceFile();
595 return result != NULL;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700596}
597
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700598uint8_t Dbg::GetObjectTag(JDWP::ObjectId objectId) {
Elliott Hughes24437992011-11-30 14:49:33 -0800599 Object* o = gRegistry->Get<Object*>(objectId);
600 return TagFromObject(o);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700601}
602
Elliott Hughesaed4be92011-12-02 16:16:23 -0800603size_t Dbg::GetTagWidth(JDWP::JdwpTag tag) {
Elliott Hughesdbb40792011-11-18 17:05:22 -0800604 switch (tag) {
605 case JDWP::JT_VOID:
606 return 0;
607 case JDWP::JT_BYTE:
608 case JDWP::JT_BOOLEAN:
609 return 1;
610 case JDWP::JT_CHAR:
611 case JDWP::JT_SHORT:
612 return 2;
613 case JDWP::JT_FLOAT:
614 case JDWP::JT_INT:
615 return 4;
616 case JDWP::JT_ARRAY:
617 case JDWP::JT_OBJECT:
618 case JDWP::JT_STRING:
619 case JDWP::JT_THREAD:
620 case JDWP::JT_THREAD_GROUP:
621 case JDWP::JT_CLASS_LOADER:
622 case JDWP::JT_CLASS_OBJECT:
623 return sizeof(JDWP::ObjectId);
624 case JDWP::JT_DOUBLE:
625 case JDWP::JT_LONG:
626 return 8;
627 default:
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800628 LOG(FATAL) << "Unknown tag " << tag;
Elliott Hughesdbb40792011-11-18 17:05:22 -0800629 return -1;
630 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700631}
632
633int Dbg::GetArrayLength(JDWP::ObjectId arrayId) {
Elliott Hughes68fdbd02011-11-29 19:22:47 -0800634 Object* o = gRegistry->Get<Object*>(arrayId);
635 Array* a = o->AsArray();
636 return a->GetLength();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700637}
638
639uint8_t Dbg::GetArrayElementTag(JDWP::ObjectId arrayId) {
Elliott Hughes24437992011-11-30 14:49:33 -0800640 Object* o = gRegistry->Get<Object*>(arrayId);
641 Array* a = o->AsArray();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800642 std::string descriptor(ClassHelper(a->GetClass()).GetDescriptor());
Elliott Hughes24437992011-11-30 14:49:33 -0800643 JDWP::JdwpTag tag = BasicTagFromDescriptor(descriptor.c_str() + 1);
644 if (!IsPrimitiveTag(tag)) {
645 tag = TagFromClass(a->GetClass()->GetComponentType());
646 }
647 return tag;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700648}
649
Elliott Hughes24437992011-11-30 14:49:33 -0800650bool Dbg::OutputArray(JDWP::ObjectId arrayId, int offset, int count, JDWP::ExpandBuf* pReply) {
651 Object* o = gRegistry->Get<Object*>(arrayId);
652 Array* a = o->AsArray();
653
654 if (offset < 0 || count < 0 || offset > a->GetLength() || a->GetLength() - offset < count) {
655 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
656 return false;
657 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800658 std::string descriptor(ClassHelper(a->GetClass()).GetDescriptor());
Elliott Hughes24437992011-11-30 14:49:33 -0800659 JDWP::JdwpTag tag = BasicTagFromDescriptor(descriptor.c_str() + 1);
660
661 if (IsPrimitiveTag(tag)) {
662 size_t width = GetTagWidth(tag);
663 const uint8_t* src = reinterpret_cast<uint8_t*>(a->GetRawData());
664 uint8_t* dst = expandBufAddSpace(pReply, count * width);
665 if (width == 8) {
666 const uint64_t* src8 = reinterpret_cast<const uint64_t*>(src);
667 for (int i = 0; i < count; ++i) JDWP::Write8BE(&dst, src8[offset + i]);
668 } else if (width == 4) {
669 const uint32_t* src4 = reinterpret_cast<const uint32_t*>(src);
670 for (int i = 0; i < count; ++i) JDWP::Write4BE(&dst, src4[offset + i]);
671 } else if (width == 2) {
672 const uint16_t* src2 = reinterpret_cast<const uint16_t*>(src);
673 for (int i = 0; i < count; ++i) JDWP::Write2BE(&dst, src2[offset + i]);
674 } else {
675 memcpy(dst, &src[offset * width], count * width);
676 }
677 } else {
678 ObjectArray<Object>* oa = a->AsObjectArray<Object>();
679 for (int i = 0; i < count; ++i) {
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800680 Object* element = oa->Get(offset + i);
Elliott Hughes24437992011-11-30 14:49:33 -0800681 JDWP::JdwpTag specific_tag = (element != NULL) ? TagFromObject(element) : tag;
682 expandBufAdd1(pReply, specific_tag);
683 expandBufAddObjectId(pReply, gRegistry->Add(element));
684 }
685 }
686
687 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700688}
689
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800690bool Dbg::SetArrayElements(JDWP::ObjectId arrayId, int offset, int count, const uint8_t* src) {
691 Object* o = gRegistry->Get<Object*>(arrayId);
692 Array* a = o->AsArray();
693
694 if (offset < 0 || count < 0 || offset > a->GetLength() || a->GetLength() - offset < count) {
695 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
696 return false;
697 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800698 std::string descriptor(ClassHelper(a->GetClass()).GetDescriptor());
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800699 JDWP::JdwpTag tag = BasicTagFromDescriptor(descriptor.c_str() + 1);
700
701 if (IsPrimitiveTag(tag)) {
702 size_t width = GetTagWidth(tag);
703 uint8_t* dst = &(reinterpret_cast<uint8_t*>(a->GetRawData())[offset * width]);
704 if (width == 8) {
705 for (int i = 0; i < count; ++i) {
706 // Handle potentially non-aligned memory access one byte at a time for ARM's benefit.
707 uint64_t value;
708 for (size_t j = 0; j < sizeof(uint64_t); ++j) reinterpret_cast<uint8_t*>(&value)[j] = src[j];
709 src += sizeof(uint64_t);
710 JDWP::Write8BE(&dst, value);
711 }
712 } else if (width == 4) {
713 const uint32_t* src4 = reinterpret_cast<const uint32_t*>(src);
714 for (int i = 0; i < count; ++i) JDWP::Write4BE(&dst, src4[i]);
715 } else if (width == 2) {
716 const uint16_t* src2 = reinterpret_cast<const uint16_t*>(src);
717 for (int i = 0; i < count; ++i) JDWP::Write2BE(&dst, src2[i]);
718 } else {
719 memcpy(&dst[offset * width], src, count * width);
720 }
721 } else {
722 ObjectArray<Object>* oa = a->AsObjectArray<Object>();
723 for (int i = 0; i < count; ++i) {
724 JDWP::ObjectId id = JDWP::ReadObjectId(&src);
725 oa->Set(offset + i, gRegistry->Get<Object*>(id));
726 }
727 }
728
729 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700730}
731
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800732JDWP::ObjectId Dbg::CreateString(const std::string& str) {
733 return gRegistry->Add(String::AllocFromModifiedUtf8(str.c_str()));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700734}
735
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800736bool Dbg::CreateObject(JDWP::RefTypeId classId, JDWP::ObjectId& new_object) {
737 Object* o = gRegistry->Get<Object*>(classId);
738 if (o == NULL || !o->IsClass()) {
739 return false;
740 }
741 new_object = gRegistry->Add(o->AsClass()->AllocObject());
742 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700743}
744
Elliott Hughesbf13d362011-12-08 15:51:37 -0800745/*
746 * Used by Eclipse's "Display" view to evaluate "new byte[5]" to get "(byte[]) [0, 0, 0, 0, 0]".
747 */
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800748bool Dbg::CreateArrayObject(JDWP::RefTypeId arrayTypeId, uint32_t length, JDWP::ObjectId& new_array) {
749 Object* o = gRegistry->Get<Object*>(arrayTypeId);
750 if (o == NULL || !o->IsClass()) {
751 return false;
752 }
753 new_array = gRegistry->Add(Array::Alloc(o->AsClass(), length));
754 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700755}
756
757bool Dbg::MatchType(JDWP::RefTypeId instClassId, JDWP::RefTypeId classId) {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800758 // TODO: error handling if the RefTypeIds aren't actually Class*s.
Elliott Hughesd07986f2011-12-06 18:27:45 -0800759 return gRegistry->Get<Class*>(instClassId)->InstanceOf(gRegistry->Get<Class*>(classId));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700760}
761
Elliott Hughes03181a82011-11-17 17:22:21 -0800762JDWP::FieldId ToFieldId(Field* f) {
763#ifdef MOVING_GARBAGE_COLLECTOR
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700764 UNIMPLEMENTED(FATAL);
Elliott Hughes03181a82011-11-17 17:22:21 -0800765#else
766 return static_cast<JDWP::FieldId>(reinterpret_cast<uintptr_t>(f));
767#endif
768}
769
770JDWP::MethodId ToMethodId(Method* m) {
771#ifdef MOVING_GARBAGE_COLLECTOR
772 UNIMPLEMENTED(FATAL);
773#else
774 return static_cast<JDWP::MethodId>(reinterpret_cast<uintptr_t>(m));
775#endif
776}
777
Elliott Hughesaed4be92011-12-02 16:16:23 -0800778Field* FromFieldId(JDWP::FieldId fid) {
779#ifdef MOVING_GARBAGE_COLLECTOR
780 UNIMPLEMENTED(FATAL);
781#else
782 return reinterpret_cast<Field*>(static_cast<uintptr_t>(fid));
783#endif
784}
785
Elliott Hughes03181a82011-11-17 17:22:21 -0800786Method* FromMethodId(JDWP::MethodId mid) {
787#ifdef MOVING_GARBAGE_COLLECTOR
788 UNIMPLEMENTED(FATAL);
789#else
790 return reinterpret_cast<Method*>(static_cast<uintptr_t>(mid));
791#endif
792}
793
Elliott Hughesd07986f2011-12-06 18:27:45 -0800794void SetLocation(JDWP::JdwpLocation& location, Method* m, uintptr_t native_pc) {
795 Class* c = m->GetDeclaringClass();
796 location.typeTag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
797 location.classId = gRegistry->Add(c);
798 location.methodId = ToMethodId(m);
799 location.idx = m->IsNative() ? -1 : m->ToDexPC(native_pc);
800}
801
Elliott Hughes03181a82011-11-17 17:22:21 -0800802std::string Dbg::GetMethodName(JDWP::RefTypeId refTypeId, JDWP::MethodId methodId) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800803 Method* m = FromMethodId(methodId);
804 return MethodHelper(m).GetName();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700805}
806
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800807/*
808 * Augment the access flags for synthetic methods and fields by setting
809 * the (as described by the spec) "0xf0000000 bit". Also, strip out any
810 * flags not specified by the Java programming language.
811 */
812static uint32_t MangleAccessFlags(uint32_t accessFlags) {
813 accessFlags &= kAccJavaFlagsMask;
814 if ((accessFlags & kAccSynthetic) != 0) {
815 accessFlags |= 0xf0000000;
816 }
817 return accessFlags;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700818}
819
Elliott Hughesdbb40792011-11-18 17:05:22 -0800820static const uint16_t kEclipseWorkaroundSlot = 1000;
821
822/*
823 * Eclipse appears to expect that the "this" reference is in slot zero.
824 * If it's not, the "variables" display will show two copies of "this",
825 * possibly because it gets "this" from SF.ThisObject and then displays
826 * all locals with nonzero slot numbers.
827 *
828 * So, we remap the item in slot 0 to 1000, and remap "this" to zero. On
829 * SF.GetValues / SF.SetValues we map them back.
Elliott Hughesc5b734a2011-12-01 17:20:58 -0800830 *
831 * TODO: jdb uses the value to determine whether a variable is a local or an argument,
832 * by checking whether it's less than the number of arguments. To make that work, we'd
833 * have to "mangle" all the arguments to come first, not just the implicit argument 'this'.
Elliott Hughesdbb40792011-11-18 17:05:22 -0800834 */
835static uint16_t MangleSlot(uint16_t slot, const char* name) {
836 uint16_t newSlot = slot;
837 if (strcmp(name, "this") == 0) {
838 newSlot = 0;
839 } else if (slot == 0) {
840 newSlot = kEclipseWorkaroundSlot;
841 }
842 return newSlot;
843}
844
Elliott Hughes68fdbd02011-11-29 19:22:47 -0800845static uint16_t DemangleSlot(uint16_t slot, Frame& f) {
Elliott Hughesdbb40792011-11-18 17:05:22 -0800846 if (slot == kEclipseWorkaroundSlot) {
Elliott Hughes68fdbd02011-11-29 19:22:47 -0800847 return 0;
Elliott Hughesdbb40792011-11-18 17:05:22 -0800848 } else if (slot == 0) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800849 const DexFile::CodeItem* code_item = MethodHelper(f.GetMethod()).GetCodeItem();
850 return code_item->registers_size_ - code_item->ins_size_;
Elliott Hughesdbb40792011-11-18 17:05:22 -0800851 }
Elliott Hughes68fdbd02011-11-29 19:22:47 -0800852 return slot;
Elliott Hughesdbb40792011-11-18 17:05:22 -0800853}
854
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800855bool Dbg::OutputDeclaredFields(JDWP::RefTypeId refTypeId, bool with_generic, JDWP::ExpandBuf* pReply) {
856 Object* o = gRegistry->Get<Object*>(refTypeId);
857 if (o == NULL || !o->IsClass()) {
858 return false;
859 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800860
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800861 Class* c = o->AsClass();
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800862 size_t instance_field_count = c->NumInstanceFields();
863 size_t static_field_count = c->NumStaticFields();
864
865 expandBufAdd4BE(pReply, instance_field_count + static_field_count);
866
867 for (size_t i = 0; i < instance_field_count + static_field_count; ++i) {
868 Field* f = (i < instance_field_count) ? c->GetInstanceField(i) : c->GetStaticField(i - instance_field_count);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800869 FieldHelper fh(f);
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800870 expandBufAddFieldId(pReply, ToFieldId(f));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800871 expandBufAddUtf8String(pReply, fh.GetName());
872 expandBufAddUtf8String(pReply, fh.GetTypeDescriptor());
Elliott Hughesc5b734a2011-12-01 17:20:58 -0800873 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800874 static const char genericSignature[1] = "";
875 expandBufAddUtf8String(pReply, genericSignature);
876 }
877 expandBufAdd4BE(pReply, MangleAccessFlags(f->GetAccessFlags()));
878 }
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800879 return true;
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800880}
881
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800882bool Dbg::OutputDeclaredMethods(JDWP::RefTypeId refTypeId, bool with_generic, JDWP::ExpandBuf* pReply) {
883 Object* o = gRegistry->Get<Object*>(refTypeId);
884 if (o == NULL || !o->IsClass()) {
885 return false;
886 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800887
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800888 Class* c = o->AsClass();
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800889 size_t direct_method_count = c->NumDirectMethods();
890 size_t virtual_method_count = c->NumVirtualMethods();
891
892 expandBufAdd4BE(pReply, direct_method_count + virtual_method_count);
893
894 for (size_t i = 0; i < direct_method_count + virtual_method_count; ++i) {
895 Method* m = (i < direct_method_count) ? c->GetDirectMethod(i) : c->GetVirtualMethod(i - direct_method_count);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800896 MethodHelper mh(m);
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800897 expandBufAddMethodId(pReply, ToMethodId(m));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800898 expandBufAddUtf8String(pReply, mh.GetName());
Elliott Hughes4740cdf2011-12-07 14:07:12 -0800899 expandBufAddUtf8String(pReply, mh.GetSignature());
Elliott Hughesc5b734a2011-12-01 17:20:58 -0800900 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800901 static const char genericSignature[1] = "";
902 expandBufAddUtf8String(pReply, genericSignature);
903 }
904 expandBufAdd4BE(pReply, MangleAccessFlags(m->GetAccessFlags()));
905 }
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800906 return true;
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800907}
908
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800909bool Dbg::OutputDeclaredInterfaces(JDWP::RefTypeId refTypeId, JDWP::ExpandBuf* pReply) {
910 Object* o = gRegistry->Get<Object*>(refTypeId);
911 if (o == NULL || !o->IsClass()) {
912 return false;
913 }
914 ClassHelper kh(o->AsClass());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800915 size_t interface_count = kh.NumInterfaces();
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800916 expandBufAdd4BE(pReply, interface_count);
917 for (size_t i = 0; i < interface_count; ++i) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800918 expandBufAddRefTypeId(pReply, gRegistry->Add(kh.GetInterface(i)));
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800919 }
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800920 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700921}
922
923void Dbg::OutputLineTable(JDWP::RefTypeId refTypeId, JDWP::MethodId methodId, JDWP::ExpandBuf* pReply) {
Elliott Hughes03181a82011-11-17 17:22:21 -0800924 struct DebugCallbackContext {
925 int numItems;
926 JDWP::ExpandBuf* pReply;
927
928 static bool Callback(void* context, uint32_t address, uint32_t lineNum) {
929 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
930 expandBufAdd8BE(pContext->pReply, address);
931 expandBufAdd4BE(pContext->pReply, lineNum);
932 pContext->numItems++;
933 return true;
934 }
935 };
936
937 Method* m = FromMethodId(methodId);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800938 MethodHelper mh(m);
Elliott Hughes03181a82011-11-17 17:22:21 -0800939 uint64_t start, end;
940 if (m->IsNative()) {
941 start = -1;
942 end = -1;
943 } else {
944 start = 0;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800945 // TODO: what are the units supposed to be? *2?
946 end = mh.GetCodeItem()->insns_size_in_code_units_;
Elliott Hughes03181a82011-11-17 17:22:21 -0800947 }
948
949 expandBufAdd8BE(pReply, start);
950 expandBufAdd8BE(pReply, end);
951
952 // Add numLines later
953 size_t numLinesOffset = expandBufGetLength(pReply);
954 expandBufAdd4BE(pReply, 0);
955
956 DebugCallbackContext context;
957 context.numItems = 0;
958 context.pReply = pReply;
959
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800960 mh.GetDexFile().DecodeDebugInfo(mh.GetCodeItem(), m->IsStatic(), m->GetDexMethodIndex(),
961 DebugCallbackContext::Callback, NULL, &context);
Elliott Hughes03181a82011-11-17 17:22:21 -0800962
963 JDWP::Set4BE(expandBufGetBuffer(pReply) + numLinesOffset, context.numItems);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700964}
965
Elliott Hughesc5b734a2011-12-01 17:20:58 -0800966void Dbg::OutputVariableTable(JDWP::RefTypeId refTypeId, JDWP::MethodId methodId, bool with_generic, JDWP::ExpandBuf* pReply) {
Elliott Hughesdbb40792011-11-18 17:05:22 -0800967 struct DebugCallbackContext {
Elliott Hughesdbb40792011-11-18 17:05:22 -0800968 JDWP::ExpandBuf* pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -0800969 size_t variable_count;
970 bool with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -0800971
Elliott Hughesc5b734a2011-12-01 17:20:58 -0800972 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 -0800973 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
974
Elliott Hughesaa6e1cd2012-01-18 19:26:06 -0800975 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 -0800976
Elliott Hughes68fdbd02011-11-29 19:22:47 -0800977 slot = MangleSlot(slot, name);
978
Elliott Hughesdbb40792011-11-18 17:05:22 -0800979 expandBufAdd8BE(pContext->pReply, startAddress);
980 expandBufAddUtf8String(pContext->pReply, name);
981 expandBufAddUtf8String(pContext->pReply, descriptor);
Elliott Hughesc5b734a2011-12-01 17:20:58 -0800982 if (pContext->with_generic) {
Elliott Hughesdbb40792011-11-18 17:05:22 -0800983 expandBufAddUtf8String(pContext->pReply, signature);
984 }
985 expandBufAdd4BE(pContext->pReply, endAddress - startAddress);
986 expandBufAdd4BE(pContext->pReply, slot);
987
Elliott Hughesc5b734a2011-12-01 17:20:58 -0800988 ++pContext->variable_count;
Elliott Hughesdbb40792011-11-18 17:05:22 -0800989 }
990 };
991
992 Method* m = FromMethodId(methodId);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800993 MethodHelper mh(m);
994 const DexFile::CodeItem* code_item = mh.GetCodeItem();
Elliott Hughesdbb40792011-11-18 17:05:22 -0800995
Elliott Hughesc5b734a2011-12-01 17:20:58 -0800996 // arg_count considers doubles and longs to take 2 units.
997 // variable_count considers everything to take 1 unit.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800998 std::string shorty(mh.GetShorty());
Elliott Hughesc5b734a2011-12-01 17:20:58 -0800999 expandBufAdd4BE(pReply, m->NumArgRegisters(shorty));
Elliott Hughesdbb40792011-11-18 17:05:22 -08001000
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001001 // We don't know the total number of variables yet, so leave a blank and update it later.
1002 size_t variable_count_offset = expandBufGetLength(pReply);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001003 expandBufAdd4BE(pReply, 0);
1004
1005 DebugCallbackContext context;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001006 context.pReply = pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001007 context.variable_count = 0;
1008 context.with_generic = with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001009
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001010 mh.GetDexFile().DecodeDebugInfo(code_item, m->IsStatic(), m->GetDexMethodIndex(), NULL,
1011 DebugCallbackContext::Callback, &context);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001012
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001013 JDWP::Set4BE(expandBufGetBuffer(pReply) + variable_count_offset, context.variable_count);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001014}
1015
Elliott Hughesaed4be92011-12-02 16:16:23 -08001016JDWP::JdwpTag Dbg::GetFieldBasicTag(JDWP::FieldId fieldId) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001017 return BasicTagFromDescriptor(FieldHelper(FromFieldId(fieldId)).GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001018}
1019
Elliott Hughesaed4be92011-12-02 16:16:23 -08001020JDWP::JdwpTag Dbg::GetStaticFieldBasicTag(JDWP::FieldId fieldId) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001021 return BasicTagFromDescriptor(FieldHelper(FromFieldId(fieldId)).GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001022}
1023
1024void Dbg::GetFieldValue(JDWP::ObjectId objectId, JDWP::FieldId fieldId, JDWP::ExpandBuf* pReply) {
Elliott Hughesaed4be92011-12-02 16:16:23 -08001025 Object* o = gRegistry->Get<Object*>(objectId);
1026 Field* f = FromFieldId(fieldId);
1027
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001028 JDWP::JdwpTag tag = BasicTagFromDescriptor(FieldHelper(f).GetTypeDescriptor());
Elliott Hughesaed4be92011-12-02 16:16:23 -08001029
1030 if (IsPrimitiveTag(tag)) {
1031 expandBufAdd1(pReply, tag);
1032 if (tag == JDWP::JT_BOOLEAN || tag == JDWP::JT_BYTE) {
1033 expandBufAdd1(pReply, f->Get32(o));
1034 } else if (tag == JDWP::JT_CHAR || tag == JDWP::JT_SHORT) {
1035 expandBufAdd2BE(pReply, f->Get32(o));
1036 } else if (tag == JDWP::JT_FLOAT || tag == JDWP::JT_INT) {
1037 expandBufAdd4BE(pReply, f->Get32(o));
1038 } else if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
1039 expandBufAdd8BE(pReply, f->Get64(o));
1040 } else {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001041 LOG(FATAL) << "Unknown tag: " << tag;
Elliott Hughesaed4be92011-12-02 16:16:23 -08001042 }
1043 } else {
1044 Object* value = f->GetObject(o);
1045 expandBufAdd1(pReply, TagFromObject(value));
1046 expandBufAddObjectId(pReply, gRegistry->Add(value));
1047 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001048}
1049
1050void Dbg::SetFieldValue(JDWP::ObjectId objectId, JDWP::FieldId fieldId, uint64_t value, int width) {
Elliott Hughesaed4be92011-12-02 16:16:23 -08001051 Object* o = gRegistry->Get<Object*>(objectId);
1052 Field* f = FromFieldId(fieldId);
1053
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001054 JDWP::JdwpTag tag = BasicTagFromDescriptor(FieldHelper(f).GetTypeDescriptor());
Elliott Hughesaed4be92011-12-02 16:16:23 -08001055
1056 if (IsPrimitiveTag(tag)) {
1057 if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
1058 f->Set64(o, value);
1059 } else {
1060 f->Set32(o, value);
1061 }
1062 } else {
1063 f->SetObject(o, gRegistry->Get<Object*>(value));
1064 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001065}
1066
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001067void Dbg::GetStaticFieldValue(JDWP::FieldId fieldId, JDWP::ExpandBuf* pReply) {
1068 GetFieldValue(0, fieldId, pReply);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001069}
1070
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001071void Dbg::SetStaticFieldValue(JDWP::FieldId fieldId, uint64_t value, int width) {
1072 SetFieldValue(0, fieldId, value, width);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001073}
1074
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001075std::string Dbg::StringToUtf8(JDWP::ObjectId strId) {
1076 String* s = gRegistry->Get<String*>(strId);
1077 return s->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001078}
1079
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001080Thread* DecodeThread(JDWP::ObjectId threadId) {
1081 Object* thread_peer = gRegistry->Get<Object*>(threadId);
1082 CHECK(thread_peer != NULL);
1083 return Thread::FromManagedThread(thread_peer);
1084}
1085
1086bool Dbg::GetThreadName(JDWP::ObjectId threadId, std::string& name) {
1087 ScopedThreadListLock thread_list_lock;
1088 Thread* thread = DecodeThread(threadId);
1089 if (thread == NULL) {
1090 return false;
1091 }
Elliott Hughes899e7892012-01-24 14:57:32 -08001092 StringAppendF(&name, "<%d> %s", thread->GetThinLockId(), thread->GetThreadName()->ToModifiedUtf8().c_str());
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001093 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001094}
1095
1096JDWP::ObjectId Dbg::GetThreadGroup(JDWP::ObjectId threadId) {
Elliott Hughes499c5132011-11-17 14:55:11 -08001097 Object* thread = gRegistry->Get<Object*>(threadId);
1098 CHECK(thread != NULL);
1099
1100 Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/Thread;");
1101 CHECK(c != NULL);
1102 Field* f = c->FindInstanceField("group", "Ljava/lang/ThreadGroup;");
1103 CHECK(f != NULL);
1104 Object* group = f->GetObject(thread);
1105 CHECK(group != NULL);
1106 return gRegistry->Add(group);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001107}
1108
Elliott Hughes499c5132011-11-17 14:55:11 -08001109std::string Dbg::GetThreadGroupName(JDWP::ObjectId threadGroupId) {
1110 Object* thread_group = gRegistry->Get<Object*>(threadGroupId);
1111 CHECK(thread_group != NULL);
1112
1113 Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/ThreadGroup;");
1114 CHECK(c != NULL);
1115 Field* f = c->FindInstanceField("name", "Ljava/lang/String;");
1116 CHECK(f != NULL);
1117 String* s = reinterpret_cast<String*>(f->GetObject(thread_group));
1118 return s->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001119}
1120
1121JDWP::ObjectId Dbg::GetThreadGroupParent(JDWP::ObjectId threadGroupId) {
Elliott Hughes4e235312011-12-02 11:34:15 -08001122 Object* thread_group = gRegistry->Get<Object*>(threadGroupId);
1123 CHECK(thread_group != NULL);
1124
1125 Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/ThreadGroup;");
1126 CHECK(c != NULL);
1127 Field* f = c->FindInstanceField("parent", "Ljava/lang/ThreadGroup;");
1128 CHECK(f != NULL);
1129 Object* parent = f->GetObject(thread_group);
1130 return gRegistry->Add(parent);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001131}
1132
Elliott Hughes499c5132011-11-17 14:55:11 -08001133static Object* GetStaticThreadGroup(const char* field_name) {
1134 Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/ThreadGroup;");
1135 CHECK(c != NULL);
1136 Field* f = c->FindStaticField(field_name, "Ljava/lang/ThreadGroup;");
1137 CHECK(f != NULL);
1138 Object* group = f->GetObject(NULL);
1139 CHECK(group != NULL);
1140 return group;
1141}
1142
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001143JDWP::ObjectId Dbg::GetSystemThreadGroupId() {
Elliott Hughes499c5132011-11-17 14:55:11 -08001144 return gRegistry->Add(GetStaticThreadGroup("mSystem"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001145}
1146
1147JDWP::ObjectId Dbg::GetMainThreadGroupId() {
Elliott Hughes499c5132011-11-17 14:55:11 -08001148 return gRegistry->Add(GetStaticThreadGroup("mMain"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001149}
1150
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001151bool Dbg::GetThreadStatus(JDWP::ObjectId threadId, JDWP::JdwpThreadStatus* pThreadStatus, JDWP::JdwpSuspendStatus* pSuspendStatus) {
Elliott Hughes499c5132011-11-17 14:55:11 -08001152 ScopedThreadListLock thread_list_lock;
1153
1154 Thread* thread = DecodeThread(threadId);
1155 if (thread == NULL) {
1156 return false;
1157 }
1158
1159 switch (thread->GetState()) {
1160 case Thread::kTerminated: *pThreadStatus = JDWP::TS_ZOMBIE; break;
1161 case Thread::kRunnable: *pThreadStatus = JDWP::TS_RUNNING; break;
1162 case Thread::kTimedWaiting: *pThreadStatus = JDWP::TS_SLEEPING; break;
1163 case Thread::kBlocked: *pThreadStatus = JDWP::TS_MONITOR; break;
1164 case Thread::kWaiting: *pThreadStatus = JDWP::TS_WAIT; break;
1165 case Thread::kInitializing: *pThreadStatus = JDWP::TS_ZOMBIE; break;
1166 case Thread::kStarting: *pThreadStatus = JDWP::TS_ZOMBIE; break;
1167 case Thread::kNative: *pThreadStatus = JDWP::TS_RUNNING; break;
1168 case Thread::kVmWait: *pThreadStatus = JDWP::TS_WAIT; break;
1169 case Thread::kSuspended: *pThreadStatus = JDWP::TS_RUNNING; break;
1170 default:
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001171 LOG(FATAL) << "Unknown thread state " << thread->GetState();
Elliott Hughes499c5132011-11-17 14:55:11 -08001172 }
1173
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001174 *pSuspendStatus = (thread->IsSuspended() ? JDWP::SUSPEND_STATUS_SUSPENDED : JDWP::SUSPEND_STATUS_NOT_SUSPENDED);
Elliott Hughes499c5132011-11-17 14:55:11 -08001175
1176 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001177}
1178
1179uint32_t Dbg::GetThreadSuspendCount(JDWP::ObjectId threadId) {
Elliott Hughesd07986f2011-12-06 18:27:45 -08001180 return DecodeThread(threadId)->GetSuspendCount();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001181}
1182
1183bool Dbg::ThreadExists(JDWP::ObjectId threadId) {
Elliott Hughes761928d2011-11-16 18:33:03 -08001184 return DecodeThread(threadId) != NULL;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001185}
1186
1187bool Dbg::IsSuspended(JDWP::ObjectId threadId) {
Elliott Hughes761928d2011-11-16 18:33:03 -08001188 return DecodeThread(threadId)->IsSuspended();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001189}
1190
Elliott Hughesa2155262011-11-16 16:26:58 -08001191void Dbg::GetThreadGroupThreadsImpl(Object* thread_group, JDWP::ObjectId** ppThreadIds, uint32_t* pThreadCount) {
1192 struct ThreadListVisitor {
1193 static void Visit(Thread* t, void* arg) {
1194 reinterpret_cast<ThreadListVisitor*>(arg)->Visit(t);
1195 }
1196
1197 void Visit(Thread* t) {
1198 if (t == Dbg::GetDebugThread()) {
1199 // Skip the JDWP thread. Some debuggers get bent out of shape when they can't suspend and
1200 // query all threads, so it's easier if we just don't tell them about this thread.
1201 return;
1202 }
1203 if (thread_group == NULL || t->GetThreadGroup() == thread_group) {
1204 threads.push_back(gRegistry->Add(t->GetPeer()));
1205 }
1206 }
1207
1208 Object* thread_group;
1209 std::vector<JDWP::ObjectId> threads;
1210 };
1211
1212 ThreadListVisitor tlv;
1213 tlv.thread_group = thread_group;
1214
1215 {
1216 ScopedThreadListLock thread_list_lock;
1217 Runtime::Current()->GetThreadList()->ForEach(ThreadListVisitor::Visit, &tlv);
1218 }
1219
1220 *pThreadCount = tlv.threads.size();
1221 if (*pThreadCount == 0) {
1222 *ppThreadIds = NULL;
1223 } else {
1224 *ppThreadIds = new JDWP::ObjectId[*pThreadCount];
1225 for (size_t i = 0; i < *pThreadCount; ++i) {
1226 (*ppThreadIds)[i] = tlv.threads[i];
1227 }
1228 }
1229}
1230
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001231void Dbg::GetThreadGroupThreads(JDWP::ObjectId threadGroupId, JDWP::ObjectId** ppThreadIds, uint32_t* pThreadCount) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001232 GetThreadGroupThreadsImpl(gRegistry->Get<Object*>(threadGroupId), ppThreadIds, pThreadCount);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001233}
1234
1235void Dbg::GetAllThreads(JDWP::ObjectId** ppThreadIds, uint32_t* pThreadCount) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001236 GetThreadGroupThreadsImpl(NULL, ppThreadIds, pThreadCount);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001237}
1238
1239int Dbg::GetThreadFrameCount(JDWP::ObjectId threadId) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001240 ScopedThreadListLock thread_list_lock;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001241 struct CountStackDepthVisitor : public Thread::StackVisitor {
1242 CountStackDepthVisitor() : depth(0) {}
Elliott Hughesf8a2df72011-12-01 12:19:54 -08001243 virtual void VisitFrame(const Frame& f, uintptr_t) {
1244 // TODO: we'll need to skip callee-save frames too.
1245 if (f.HasMethod()) {
1246 ++depth;
1247 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001248 }
1249 size_t depth;
1250 };
1251 CountStackDepthVisitor visitor;
1252 DecodeThread(threadId)->WalkStack(&visitor);
1253 return visitor.depth;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001254}
1255
Elliott Hughes03181a82011-11-17 17:22:21 -08001256bool Dbg::GetThreadFrame(JDWP::ObjectId threadId, int desired_frame_number, JDWP::FrameId* pFrameId, JDWP::JdwpLocation* pLoc) {
1257 ScopedThreadListLock thread_list_lock;
1258 struct GetFrameVisitor : public Thread::StackVisitor {
1259 GetFrameVisitor(int desired_frame_number, JDWP::FrameId* pFrameId, JDWP::JdwpLocation* pLoc)
Elliott Hughesba8eee12012-01-24 20:25:24 -08001260 : found(false), depth(0), desired_frame_number(desired_frame_number), pFrameId(pFrameId), pLoc(pLoc) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001261 }
1262 virtual void VisitFrame(const Frame& f, uintptr_t pc) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -08001263 // TODO: we'll need to skip callee-save frames too.
Elliott Hughes03181a82011-11-17 17:22:21 -08001264 if (!f.HasMethod()) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -08001265 return; // The debugger can't do anything useful with a frame that has no Method*.
Elliott Hughes03181a82011-11-17 17:22:21 -08001266 }
1267
1268 if (depth == desired_frame_number) {
1269 *pFrameId = reinterpret_cast<JDWP::FrameId>(f.GetSP());
Elliott Hughesd07986f2011-12-06 18:27:45 -08001270 SetLocation(*pLoc, f.GetMethod(), pc);
Elliott Hughes03181a82011-11-17 17:22:21 -08001271 found = true;
1272 }
1273 ++depth;
1274 }
1275 bool found;
1276 int depth;
1277 int desired_frame_number;
1278 JDWP::FrameId* pFrameId;
1279 JDWP::JdwpLocation* pLoc;
1280 };
1281 GetFrameVisitor visitor(desired_frame_number, pFrameId, pLoc);
1282 visitor.desired_frame_number = desired_frame_number;
1283 DecodeThread(threadId)->WalkStack(&visitor);
1284 return visitor.found;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001285}
1286
1287JDWP::ObjectId Dbg::GetThreadSelfId() {
Elliott Hughes475fc232011-10-25 15:00:35 -07001288 return gRegistry->Add(Thread::Current()->GetPeer());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001289}
1290
Elliott Hughes475fc232011-10-25 15:00:35 -07001291void Dbg::SuspendVM() {
Elliott Hughesa2155262011-11-16 16:26:58 -08001292 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 -07001293 Runtime::Current()->GetThreadList()->SuspendAll(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001294}
1295
1296void Dbg::ResumeVM() {
Elliott Hughes475fc232011-10-25 15:00:35 -07001297 Runtime::Current()->GetThreadList()->ResumeAll(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001298}
1299
1300void Dbg::SuspendThread(JDWP::ObjectId threadId) {
Elliott Hughes4e235312011-12-02 11:34:15 -08001301 Object* peer = gRegistry->Get<Object*>(threadId);
1302 ScopedThreadListLock thread_list_lock;
1303 Thread* thread = Thread::FromManagedThread(peer);
1304 if (thread == NULL) {
1305 LOG(WARNING) << "No such thread for suspend: " << peer;
1306 return;
1307 }
1308 Runtime::Current()->GetThreadList()->Suspend(thread, true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001309}
1310
1311void Dbg::ResumeThread(JDWP::ObjectId threadId) {
Elliott Hughes4e235312011-12-02 11:34:15 -08001312 Object* peer = gRegistry->Get<Object*>(threadId);
1313 ScopedThreadListLock thread_list_lock;
1314 Thread* thread = Thread::FromManagedThread(peer);
1315 if (thread == NULL) {
1316 LOG(WARNING) << "No such thread for resume: " << peer;
1317 return;
1318 }
1319 Runtime::Current()->GetThreadList()->Resume(thread, true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001320}
1321
1322void Dbg::SuspendSelf() {
Elliott Hughes475fc232011-10-25 15:00:35 -07001323 Runtime::Current()->GetThreadList()->SuspendSelfForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001324}
1325
Elliott Hughesd07986f2011-12-06 18:27:45 -08001326bool Dbg::GetThisObject(JDWP::FrameId frameId, JDWP::ObjectId* pThisId) {
Elliott Hughes86b00102011-12-05 17:54:26 -08001327 Method** sp = reinterpret_cast<Method**>(frameId);
1328 Frame f;
1329 f.SetSP(sp);
Elliott Hughes86b00102011-12-05 17:54:26 -08001330 Method* m = f.GetMethod();
1331
1332 Object* o = NULL;
1333 if (!m->IsNative() && !m->IsStatic()) {
Elliott Hughesd07986f2011-12-06 18:27:45 -08001334 uint16_t reg = DemangleSlot(0, f);
Elliott Hughes86b00102011-12-05 17:54:26 -08001335 o = reinterpret_cast<Object*>(f.GetVReg(m, reg));
1336 }
1337 *pThisId = gRegistry->Add(o);
1338 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001339}
1340
Elliott Hughescccd84f2011-12-05 16:51:54 -08001341void 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 -08001342 Method** sp = reinterpret_cast<Method**>(frameId);
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001343 Frame f;
1344 f.SetSP(sp);
1345 uint16_t reg = DemangleSlot(slot, f);
1346 Method* m = f.GetMethod();
1347
1348 const VmapTable vmap_table(m->GetVmapTableRaw());
1349 uint32_t vmap_offset;
1350 if (vmap_table.IsInContext(reg, vmap_offset)) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001351 UNIMPLEMENTED(FATAL) << "Don't know how to pull locals from callee save frames: " << vmap_offset;
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001352 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001353
1354 switch (tag) {
1355 case JDWP::JT_BOOLEAN:
1356 {
Elliott Hughescccd84f2011-12-05 16:51:54 -08001357 CHECK_EQ(width, 1U);
Elliott Hughes1bba14f2011-12-01 18:00:36 -08001358 uint32_t intVal = f.GetVReg(m, reg);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001359 VLOG(jdwp) << "get boolean local " << reg << " = " << intVal;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001360 JDWP::Set1(buf+1, intVal != 0);
1361 }
1362 break;
1363 case JDWP::JT_BYTE:
1364 {
Elliott Hughescccd84f2011-12-05 16:51:54 -08001365 CHECK_EQ(width, 1U);
Elliott Hughes1bba14f2011-12-01 18:00:36 -08001366 uint32_t intVal = f.GetVReg(m, reg);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001367 VLOG(jdwp) << "get byte local " << reg << " = " << intVal;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001368 JDWP::Set1(buf+1, intVal);
1369 }
1370 break;
1371 case JDWP::JT_SHORT:
1372 case JDWP::JT_CHAR:
1373 {
Elliott Hughescccd84f2011-12-05 16:51:54 -08001374 CHECK_EQ(width, 2U);
Elliott Hughes1bba14f2011-12-01 18:00:36 -08001375 uint32_t intVal = f.GetVReg(m, reg);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001376 VLOG(jdwp) << "get short/char local " << reg << " = " << intVal;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001377 JDWP::Set2BE(buf+1, intVal);
1378 }
1379 break;
1380 case JDWP::JT_INT:
1381 case JDWP::JT_FLOAT:
1382 {
Elliott Hughescccd84f2011-12-05 16:51:54 -08001383 CHECK_EQ(width, 4U);
Elliott Hughes1bba14f2011-12-01 18:00:36 -08001384 uint32_t intVal = f.GetVReg(m, reg);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001385 VLOG(jdwp) << "get int/float local " << reg << " = " << intVal;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001386 JDWP::Set4BE(buf+1, intVal);
1387 }
1388 break;
1389 case JDWP::JT_ARRAY:
1390 {
Elliott Hughescccd84f2011-12-05 16:51:54 -08001391 CHECK_EQ(width, sizeof(JDWP::ObjectId));
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001392 Object* o = reinterpret_cast<Object*>(f.GetVReg(m, reg));
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001393 VLOG(jdwp) << "get array local " << reg << " = " << o;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001394 if (o != NULL && !Heap::IsHeapAddress(o)) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001395 LOG(FATAL) << "Register " << reg << " expected to hold array: " << o;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001396 }
1397 JDWP::SetObjectId(buf+1, gRegistry->Add(o));
1398 }
1399 break;
1400 case JDWP::JT_OBJECT:
1401 {
Elliott Hughescccd84f2011-12-05 16:51:54 -08001402 CHECK_EQ(width, sizeof(JDWP::ObjectId));
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001403 Object* o = reinterpret_cast<Object*>(f.GetVReg(m, reg));
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001404 VLOG(jdwp) << "get object local " << reg << " = " << o;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001405 if (o != NULL && !Heap::IsHeapAddress(o)) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001406 LOG(FATAL) << "Register " << reg << " expected to hold object: " << o;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001407 }
1408 tag = TagFromObject(o);
1409 JDWP::SetObjectId(buf+1, gRegistry->Add(o));
1410 }
1411 break;
1412 case JDWP::JT_DOUBLE:
1413 case JDWP::JT_LONG:
1414 {
Elliott Hughescccd84f2011-12-05 16:51:54 -08001415 CHECK_EQ(width, 8U);
Elliott Hughes1bba14f2011-12-01 18:00:36 -08001416 uint32_t lo = f.GetVReg(m, reg);
1417 uint64_t hi = f.GetVReg(m, reg + 1);
1418 uint64_t longVal = (hi << 32) | lo;
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001419 VLOG(jdwp) << "get double/long local " << hi << ":" << lo << " = " << longVal;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001420 JDWP::Set8BE(buf+1, longVal);
1421 }
1422 break;
1423 default:
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001424 LOG(FATAL) << "Unknown tag " << tag;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001425 break;
1426 }
1427
1428 // Prepend tag, which may have been updated.
1429 JDWP::Set1(buf, tag);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001430}
1431
Elliott Hughesdbb40792011-11-18 17:05:22 -08001432void 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 -08001433 Method** sp = reinterpret_cast<Method**>(frameId);
1434 Frame f;
1435 f.SetSP(sp);
1436 uint16_t reg = DemangleSlot(slot, f);
1437 Method* m = f.GetMethod();
1438
1439 const VmapTable vmap_table(m->GetVmapTableRaw());
1440 uint32_t vmap_offset;
1441 if (vmap_table.IsInContext(reg, vmap_offset)) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001442 UNIMPLEMENTED(FATAL) << "Don't know how to pull locals from callee save frames: " << vmap_offset;
Elliott Hughescccd84f2011-12-05 16:51:54 -08001443 }
1444
1445 switch (tag) {
1446 case JDWP::JT_BOOLEAN:
1447 case JDWP::JT_BYTE:
1448 CHECK_EQ(width, 1U);
1449 f.SetVReg(m, reg, static_cast<uint32_t>(value));
1450 break;
1451 case JDWP::JT_SHORT:
1452 case JDWP::JT_CHAR:
1453 CHECK_EQ(width, 2U);
1454 f.SetVReg(m, reg, static_cast<uint32_t>(value));
1455 break;
1456 case JDWP::JT_INT:
1457 case JDWP::JT_FLOAT:
1458 CHECK_EQ(width, 4U);
1459 f.SetVReg(m, reg, static_cast<uint32_t>(value));
1460 break;
1461 case JDWP::JT_ARRAY:
1462 case JDWP::JT_OBJECT:
1463 case JDWP::JT_STRING:
1464 {
1465 CHECK_EQ(width, sizeof(JDWP::ObjectId));
1466 Object* o = gRegistry->Get<Object*>(static_cast<JDWP::ObjectId>(value));
1467 f.SetVReg(m, reg, static_cast<uint32_t>(reinterpret_cast<uintptr_t>(o)));
1468 }
1469 break;
1470 case JDWP::JT_DOUBLE:
1471 case JDWP::JT_LONG:
1472 CHECK_EQ(width, 8U);
1473 f.SetVReg(m, reg, static_cast<uint32_t>(value));
1474 f.SetVReg(m, reg + 1, static_cast<uint32_t>(value >> 32));
1475 break;
1476 default:
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001477 LOG(FATAL) << "Unknown tag " << tag;
Elliott Hughescccd84f2011-12-05 16:51:54 -08001478 break;
1479 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001480}
1481
1482void Dbg::PostLocationEvent(const Method* method, int pcOffset, Object* thisPtr, int eventFlags) {
1483 UNIMPLEMENTED(FATAL);
1484}
1485
Elliott Hughesd07986f2011-12-06 18:27:45 -08001486void Dbg::PostException(Method** sp, Method* throwMethod, uintptr_t throwNativePc, Method* catchMethod, uintptr_t catchNativePc, Object* exception) {
Ian Rogers0ad5bb82011-12-07 10:16:32 -08001487 if (!gDebuggerActive) {
1488 return;
1489 }
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001490
Elliott Hughesd07986f2011-12-06 18:27:45 -08001491 JDWP::JdwpLocation throw_location;
1492 SetLocation(throw_location, throwMethod, throwNativePc);
1493 JDWP::JdwpLocation catch_location;
1494 SetLocation(catch_location, catchMethod, catchNativePc);
1495
1496 // We need 'this' for InstanceOnly filters.
1497 JDWP::ObjectId this_id;
1498 GetThisObject(reinterpret_cast<JDWP::FrameId>(sp), &this_id);
1499
1500 /*
1501 * Hand the event to the JDWP exception handler. Note we're using the
1502 * "NoReg" objectID on the exception, which is not strictly correct --
1503 * the exception object WILL be passed up to the debugger if the
1504 * debugger is interested in the event. We do this because the current
1505 * implementation of the debugger object registry never throws anything
1506 * away, and some people were experiencing a fatal build up of exception
1507 * objects when dealing with certain libraries.
1508 */
1509 JDWP::ObjectId exception_id = static_cast<JDWP::ObjectId>(reinterpret_cast<uintptr_t>(exception));
1510 JDWP::RefTypeId exception_class_id = gRegistry->Add(exception->GetClass());
1511
1512 gJdwpState->PostException(&throw_location, exception_id, exception_class_id, &catch_location, this_id);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001513}
1514
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001515void Dbg::PostClassPrepare(Class* c) {
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001516 if (!gDebuggerActive) {
1517 return;
1518 }
1519
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001520 // OLD-TODO - we currently always send both "verified" and "prepared" since
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001521 // debuggers seem to like that. There might be some advantage to honesty,
1522 // since the class may not yet be verified.
1523 int state = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
1524 JDWP::JdwpTypeTag tag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
1525 gJdwpState->PostClassPrepare(tag, gRegistry->Add(c), ClassHelper(c).GetDescriptor(), state);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001526}
1527
1528bool Dbg::WatchLocation(const JDWP::JdwpLocation* pLoc) {
1529 UNIMPLEMENTED(FATAL);
1530 return false;
1531}
1532
1533void Dbg::UnwatchLocation(const JDWP::JdwpLocation* pLoc) {
1534 UNIMPLEMENTED(FATAL);
1535}
1536
1537bool Dbg::ConfigureStep(JDWP::ObjectId threadId, JDWP::JdwpStepSize size, JDWP::JdwpStepDepth depth) {
1538 UNIMPLEMENTED(FATAL);
1539 return false;
1540}
1541
1542void Dbg::UnconfigureStep(JDWP::ObjectId threadId) {
1543 UNIMPLEMENTED(FATAL);
1544}
1545
Elliott Hughesd07986f2011-12-06 18:27:45 -08001546JDWP::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) {
1547 ThreadList* thread_list = Runtime::Current()->GetThreadList();
1548
1549 Thread* targetThread = NULL;
1550 DebugInvokeReq* req = NULL;
1551 {
1552 ScopedThreadListLock thread_list_lock;
1553 targetThread = DecodeThread(threadId);
1554 if (targetThread == NULL) {
1555 LOG(ERROR) << "InvokeMethod request for non-existent thread " << threadId;
1556 return JDWP::ERR_INVALID_THREAD;
1557 }
1558 req = targetThread->GetInvokeReq();
1559 if (!req->ready) {
1560 LOG(ERROR) << "InvokeMethod request for thread not stopped by event: " << *targetThread;
1561 return JDWP::ERR_INVALID_THREAD;
1562 }
1563
1564 /*
1565 * We currently have a bug where we don't successfully resume the
1566 * target thread if the suspend count is too deep. We're expected to
1567 * require one "resume" for each "suspend", but when asked to execute
1568 * a method we have to resume fully and then re-suspend it back to the
1569 * same level. (The easiest way to cause this is to type "suspend"
1570 * multiple times in jdb.)
1571 *
1572 * It's unclear what this means when the event specifies "resume all"
1573 * and some threads are suspended more deeply than others. This is
1574 * a rare problem, so for now we just prevent it from hanging forever
1575 * by rejecting the method invocation request. Without this, we will
1576 * be stuck waiting on a suspended thread.
1577 */
1578 int suspend_count = targetThread->GetSuspendCount();
1579 if (suspend_count > 1) {
1580 LOG(ERROR) << *targetThread << " suspend count too deep for method invocation: " << suspend_count;
1581 return JDWP::ERR_THREAD_SUSPENDED; // Probably not expected here.
1582 }
1583
1584 /*
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001585 * OLD-TODO: ought to screen the various IDs, and verify that the argument
Elliott Hughesd07986f2011-12-06 18:27:45 -08001586 * list is valid.
1587 */
1588 req->receiver_ = gRegistry->Get<Object*>(objectId);
1589 req->thread_ = gRegistry->Get<Object*>(threadId);
1590 req->class_ = gRegistry->Get<Class*>(classId);
1591 req->method_ = FromMethodId(methodId);
1592 req->num_args_ = numArgs;
1593 req->arg_array_ = argArray;
1594 req->options_ = options;
1595 req->invoke_needed_ = true;
1596 }
1597
1598 // The fact that we've released the thread list lock is a bit risky --- if the thread goes
1599 // away we're sitting high and dry -- but we must release this before the ResumeAllThreads
1600 // call, and it's unwise to hold it during WaitForSuspend.
1601
1602 {
1603 /*
1604 * We change our (JDWP thread) status, which should be THREAD_RUNNING,
1605 * so the VM can suspend for a GC if the invoke request causes us to
1606 * run out of memory. It's also a good idea to change it before locking
1607 * the invokeReq mutex, although that should never be held for long.
1608 */
1609 ScopedThreadStateChange tsc(Thread::Current(), Thread::kVmWait);
1610
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001611 VLOG(jdwp) << " Transferring control to event thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08001612 {
1613 MutexLock mu(req->lock_);
1614
1615 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001616 VLOG(jdwp) << " Resuming all threads";
Elliott Hughesd07986f2011-12-06 18:27:45 -08001617 thread_list->ResumeAll(true);
1618 } else {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001619 VLOG(jdwp) << " Resuming event thread only";
Elliott Hughesd07986f2011-12-06 18:27:45 -08001620 thread_list->Resume(targetThread, true);
1621 }
1622
1623 // Wait for the request to finish executing.
1624 while (req->invoke_needed_) {
1625 req->cond_.Wait(req->lock_);
1626 }
1627 }
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001628 VLOG(jdwp) << " Control has returned from event thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08001629
1630 /* wait for thread to re-suspend itself */
1631 targetThread->WaitUntilSuspended();
1632 //dvmWaitForSuspend(targetThread);
1633 }
1634
1635 /*
1636 * Suspend the threads. We waited for the target thread to suspend
1637 * itself, so all we need to do is suspend the others.
1638 *
1639 * The suspendAllThreads() call will double-suspend the event thread,
1640 * so we want to resume the target thread once to keep the books straight.
1641 */
1642 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001643 VLOG(jdwp) << " Suspending all threads";
Elliott Hughesd07986f2011-12-06 18:27:45 -08001644 thread_list->SuspendAll(true);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001645 VLOG(jdwp) << " Resuming event thread to balance the count";
Elliott Hughesd07986f2011-12-06 18:27:45 -08001646 thread_list->Resume(targetThread, true);
1647 }
1648
1649 // Copy the result.
1650 *pResultTag = req->result_tag;
1651 if (IsPrimitiveTag(req->result_tag)) {
1652 *pResultValue = req->result_value.j;
1653 } else {
1654 *pResultValue = gRegistry->Add(req->result_value.l);
1655 }
1656 *pExceptionId = req->exception;
1657 return req->error;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001658}
1659
1660void Dbg::ExecuteMethod(DebugInvokeReq* pReq) {
Elliott Hughesd07986f2011-12-06 18:27:45 -08001661 Thread* self = Thread::Current();
1662
1663 // We can be called while an exception is pending in the VM. We need
1664 // to preserve that across the method invocation.
1665 SirtRef<Throwable> old_exception(self->GetException());
1666 self->ClearException();
1667
1668 ScopedThreadStateChange tsc(self, Thread::kRunnable);
1669
1670 // Translate the method through the vtable, unless the debugger wants to suppress it.
1671 Method* m = pReq->method_;
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001672 VLOG(jdwp) << "ExecuteMethod " << PrettyMethod(m);
Elliott Hughesd07986f2011-12-06 18:27:45 -08001673 if ((pReq->options_ & JDWP::INVOKE_NONVIRTUAL) == 0 && pReq->receiver_ != NULL) {
1674 m = pReq->class_->FindVirtualMethodForVirtualOrInterface(pReq->method_);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001675 VLOG(jdwp) << "ExecuteMethod " << PrettyMethod(m);
Elliott Hughesd07986f2011-12-06 18:27:45 -08001676 }
1677 CHECK(m != NULL);
1678
1679 CHECK_EQ(sizeof(jvalue), sizeof(uint64_t));
1680
1681 pReq->result_value = InvokeWithJValues(self, pReq->receiver_, m, reinterpret_cast<JValue*>(pReq->arg_array_));
1682
1683 pReq->exception = gRegistry->Add(self->GetException());
1684 pReq->result_tag = BasicTagFromDescriptor(MethodHelper(m).GetShorty());
1685 if (pReq->exception != 0) {
1686 Object* exc = self->GetException();
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001687 VLOG(jdwp) << " JDWP invocation returning with exception=" << exc << " " << PrettyTypeOf(exc);
Elliott Hughesd07986f2011-12-06 18:27:45 -08001688 self->ClearException();
1689 pReq->result_value.j = 0;
1690 } else if (pReq->result_tag == JDWP::JT_OBJECT) {
1691 /* if no exception thrown, examine object result more closely */
1692 JDWP::JdwpTag new_tag = TagFromObject(pReq->result_value.l);
1693 if (new_tag != pReq->result_tag) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001694 VLOG(jdwp) << " JDWP promoted result from " << pReq->result_tag << " to " << new_tag;
Elliott Hughesd07986f2011-12-06 18:27:45 -08001695 pReq->result_tag = new_tag;
1696 }
1697
1698 /*
1699 * Register the object. We don't actually need an ObjectId yet,
1700 * but we do need to be sure that the GC won't move or discard the
1701 * object when we switch out of RUNNING. The ObjectId conversion
1702 * will add the object to the "do not touch" list.
1703 *
1704 * We can't use the "tracked allocation" mechanism here because
1705 * the object is going to be handed off to a different thread.
1706 */
1707 gRegistry->Add(pReq->result_value.l);
1708 }
1709
1710 if (old_exception.get() != NULL) {
1711 self->SetException(old_exception.get());
1712 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001713}
1714
Elliott Hughesd07986f2011-12-06 18:27:45 -08001715/*
1716 * Register an object ID that might not have been registered previously.
1717 *
1718 * Normally this wouldn't happen -- the conversion to an ObjectId would
1719 * have added the object to the registry -- but in some cases (e.g.
1720 * throwing exceptions) we really want to do the registration late.
1721 */
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001722void Dbg::RegisterObjectId(JDWP::ObjectId id) {
Elliott Hughesd07986f2011-12-06 18:27:45 -08001723 gRegistry->Add(reinterpret_cast<Object*>(id));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001724}
1725
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001726/*
1727 * "buf" contains a full JDWP packet, possibly with multiple chunks. We
1728 * need to process each, accumulate the replies, and ship the whole thing
1729 * back.
1730 *
1731 * Returns "true" if we have a reply. The reply buffer is newly allocated,
1732 * and includes the chunk type/length, followed by the data.
1733 *
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001734 * OLD-TODO: we currently assume that the request and reply include a single
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001735 * chunk. If this becomes inconvenient we will need to adapt.
1736 */
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001737bool Dbg::DdmHandlePacket(const uint8_t* buf, int dataLen, uint8_t** pReplyBuf, int* pReplyLen) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001738 CHECK_GE(dataLen, 0);
1739
1740 Thread* self = Thread::Current();
1741 JNIEnv* env = self->GetJniEnv();
1742
Elliott Hughes844f9a02012-01-24 20:19:58 -08001743 static jclass Chunk_class = CacheClass(env, "org/apache/harmony/dalvik/ddmc/Chunk");
1744 static jclass DdmServer_class = CacheClass(env, "org/apache/harmony/dalvik/ddmc/DdmServer");
1745 static jmethodID dispatch_mid = env->GetStaticMethodID(DdmServer_class, "dispatch", "(I[BII)Lorg/apache/harmony/dalvik/ddmc/Chunk;");
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001746 static jfieldID data_fid = env->GetFieldID(Chunk_class, "data", "[B");
1747 static jfieldID length_fid = env->GetFieldID(Chunk_class, "length", "I");
1748 static jfieldID offset_fid = env->GetFieldID(Chunk_class, "offset", "I");
1749 static jfieldID type_fid = env->GetFieldID(Chunk_class, "type", "I");
1750
1751 // Create a byte[] corresponding to 'buf'.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001752 ScopedLocalRef<jbyteArray> dataArray(env, env->NewByteArray(dataLen));
1753 if (dataArray.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001754 LOG(WARNING) << "byte[] allocation failed: " << dataLen;
1755 env->ExceptionClear();
1756 return false;
1757 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001758 env->SetByteArrayRegion(dataArray.get(), 0, dataLen, reinterpret_cast<const jbyte*>(buf));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001759
1760 const int kChunkHdrLen = 8;
1761
1762 // Run through and find all chunks. [Currently just find the first.]
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001763 ScopedByteArrayRO contents(env, dataArray.get());
Elliott Hughesf7c3b662011-10-27 12:04:56 -07001764 jint type = JDWP::Get4BE(reinterpret_cast<const uint8_t*>(&contents[0]));
1765 jint length = JDWP::Get4BE(reinterpret_cast<const uint8_t*>(&contents[4]));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001766 jint offset = kChunkHdrLen;
1767 if (offset + length > dataLen) {
1768 LOG(WARNING) << StringPrintf("bad chunk found (len=%u pktLen=%d)", length, dataLen);
1769 return false;
1770 }
1771
1772 // Call "private static Chunk dispatch(int type, byte[] data, int offset, int length)".
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001773 ScopedLocalRef<jobject> chunk(env, env->CallStaticObjectMethod(DdmServer_class, dispatch_mid, type, dataArray.get(), offset, length));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001774 if (env->ExceptionCheck()) {
1775 LOG(INFO) << StringPrintf("Exception thrown by dispatcher for 0x%08x", type);
1776 env->ExceptionDescribe();
1777 env->ExceptionClear();
1778 return false;
1779 }
1780
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001781 if (chunk.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001782 return false;
1783 }
1784
1785 /*
1786 * Pull the pieces out of the chunk. We copy the results into a
1787 * newly-allocated buffer that the caller can free. We don't want to
1788 * continue using the Chunk object because nothing has a reference to it.
1789 *
1790 * We could avoid this by returning type/data/offset/length and having
1791 * the caller be aware of the object lifetime issues, but that
1792 * integrates the JDWP code more tightly into the VM, and doesn't work
1793 * if we have responses for multiple chunks.
1794 *
1795 * So we're pretty much stuck with copying data around multiple times.
1796 */
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001797 ScopedLocalRef<jbyteArray> replyData(env, reinterpret_cast<jbyteArray>(env->GetObjectField(chunk.get(), data_fid)));
1798 length = env->GetIntField(chunk.get(), length_fid);
1799 offset = env->GetIntField(chunk.get(), offset_fid);
1800 type = env->GetIntField(chunk.get(), type_fid);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001801
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001802 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 -07001803 if (length == 0 || replyData.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001804 return false;
1805 }
1806
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001807 jsize replyLength = env->GetArrayLength(replyData.get());
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001808 if (offset + length > replyLength) {
1809 LOG(WARNING) << StringPrintf("chunk off=%d len=%d exceeds reply array len %d", offset, length, replyLength);
1810 return false;
1811 }
1812
1813 uint8_t* reply = new uint8_t[length + kChunkHdrLen];
1814 if (reply == NULL) {
1815 LOG(WARNING) << "malloc failed: " << (length + kChunkHdrLen);
1816 return false;
1817 }
Elliott Hughesf7c3b662011-10-27 12:04:56 -07001818 JDWP::Set4BE(reply + 0, type);
1819 JDWP::Set4BE(reply + 4, length);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001820 env->GetByteArrayRegion(replyData.get(), offset, length, reinterpret_cast<jbyte*>(reply + kChunkHdrLen));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001821
1822 *pReplyBuf = reply;
1823 *pReplyLen = length + kChunkHdrLen;
1824
Elliott Hughesba8eee12012-01-24 20:25:24 -08001825 VLOG(jdwp) << StringPrintf("dvmHandleDdm returning type=%.4s buf=%p len=%d", reinterpret_cast<char*>(reply), reply, length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001826 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001827}
1828
Elliott Hughesa2155262011-11-16 16:26:58 -08001829void Dbg::DdmBroadcast(bool connect) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001830 VLOG(jdwp) << "Broadcasting DDM " << (connect ? "connect" : "disconnect") << "...";
Elliott Hughes47fce012011-10-25 18:37:19 -07001831
1832 Thread* self = Thread::Current();
1833 if (self->GetState() != Thread::kRunnable) {
1834 LOG(ERROR) << "DDM broadcast in thread state " << self->GetState();
1835 /* try anyway? */
1836 }
1837
1838 JNIEnv* env = self->GetJniEnv();
Elliott Hughes844f9a02012-01-24 20:19:58 -08001839 static jclass DdmServer_class = CacheClass(env, "org/apache/harmony/dalvik/ddmc/DdmServer");
Elliott Hughes47fce012011-10-25 18:37:19 -07001840 static jmethodID broadcast_mid = env->GetStaticMethodID(DdmServer_class, "broadcast", "(I)V");
1841 jint event = connect ? 1 /*DdmServer.CONNECTED*/ : 2 /*DdmServer.DISCONNECTED*/;
1842 env->CallStaticVoidMethod(DdmServer_class, broadcast_mid, event);
1843 if (env->ExceptionCheck()) {
1844 LOG(ERROR) << "DdmServer.broadcast " << event << " failed";
1845 env->ExceptionDescribe();
1846 env->ExceptionClear();
1847 }
1848}
1849
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001850void Dbg::DdmConnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08001851 Dbg::DdmBroadcast(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001852}
1853
1854void Dbg::DdmDisconnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08001855 Dbg::DdmBroadcast(false);
Elliott Hughes47fce012011-10-25 18:37:19 -07001856 gDdmThreadNotification = false;
1857}
1858
1859/*
Elliott Hughes82188472011-11-07 18:11:48 -08001860 * Send a notification when a thread starts, stops, or changes its name.
Elliott Hughes47fce012011-10-25 18:37:19 -07001861 *
1862 * Because we broadcast the full set of threads when the notifications are
1863 * first enabled, it's possible for "thread" to be actively executing.
1864 */
Elliott Hughes82188472011-11-07 18:11:48 -08001865void Dbg::DdmSendThreadNotification(Thread* t, uint32_t type) {
Elliott Hughes47fce012011-10-25 18:37:19 -07001866 if (!gDdmThreadNotification) {
1867 return;
1868 }
1869
Elliott Hughes82188472011-11-07 18:11:48 -08001870 if (type == CHUNK_TYPE("THDE")) {
Elliott Hughes47fce012011-10-25 18:37:19 -07001871 uint8_t buf[4];
Elliott Hughesf7c3b662011-10-27 12:04:56 -07001872 JDWP::Set4BE(&buf[0], t->GetThinLockId());
Elliott Hughes47fce012011-10-25 18:37:19 -07001873 Dbg::DdmSendChunk(CHUNK_TYPE("THDE"), 4, buf);
Elliott Hughes82188472011-11-07 18:11:48 -08001874 } else {
1875 CHECK(type == CHUNK_TYPE("THCR") || type == CHUNK_TYPE("THNM")) << type;
Elliott Hughes899e7892012-01-24 14:57:32 -08001876 SirtRef<String> name(t->GetThreadName());
Elliott Hughes82188472011-11-07 18:11:48 -08001877 size_t char_count = (name.get() != NULL) ? name->GetLength() : 0;
1878 const jchar* chars = name->GetCharArray()->GetData();
1879
Elliott Hughes21f32d72011-11-09 17:44:13 -08001880 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08001881 JDWP::Append4BE(bytes, t->GetThinLockId());
1882 JDWP::AppendUtf16BE(bytes, chars, char_count);
Elliott Hughes21f32d72011-11-09 17:44:13 -08001883 CHECK_EQ(bytes.size(), char_count*2 + sizeof(uint32_t)*2);
1884 Dbg::DdmSendChunk(type, bytes);
Elliott Hughes47fce012011-10-25 18:37:19 -07001885 }
1886}
1887
Elliott Hughesa2155262011-11-16 16:26:58 -08001888static void DdmSendThreadStartCallback(Thread* t, void*) {
Elliott Hughes82188472011-11-07 18:11:48 -08001889 Dbg::DdmSendThreadNotification(t, CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07001890}
1891
1892void Dbg::DdmSetThreadNotification(bool enable) {
1893 // We lock the thread list to avoid sending duplicate events or missing
1894 // a thread change. We should be okay holding this lock while sending
1895 // the messages out. (We have to hold it while accessing a live thread.)
Elliott Hughesbbd9d832011-11-07 14:40:00 -08001896 ScopedThreadListLock thread_list_lock;
Elliott Hughes47fce012011-10-25 18:37:19 -07001897
1898 gDdmThreadNotification = enable;
1899 if (enable) {
Elliott Hughesbfe487b2011-10-26 15:48:55 -07001900 Runtime::Current()->GetThreadList()->ForEach(DdmSendThreadStartCallback, NULL);
Elliott Hughes47fce012011-10-25 18:37:19 -07001901 }
1902}
1903
Elliott Hughesa2155262011-11-16 16:26:58 -08001904void Dbg::PostThreadStartOrStop(Thread* t, uint32_t type) {
Elliott Hughes47fce012011-10-25 18:37:19 -07001905 if (gDebuggerActive) {
1906 JDWP::ObjectId id = gRegistry->Add(t->GetPeer());
Elliott Hughes82188472011-11-07 18:11:48 -08001907 gJdwpState->PostThreadChange(id, type == CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07001908 }
Elliott Hughes82188472011-11-07 18:11:48 -08001909 Dbg::DdmSendThreadNotification(t, type);
Elliott Hughes47fce012011-10-25 18:37:19 -07001910}
1911
1912void Dbg::PostThreadStart(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001913 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07001914}
1915
1916void Dbg::PostThreadDeath(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001917 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THDE"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001918}
1919
Elliott Hughes82188472011-11-07 18:11:48 -08001920void Dbg::DdmSendChunk(uint32_t type, size_t byte_count, const uint8_t* buf) {
Elliott Hughes3bb81562011-10-21 18:52:59 -07001921 CHECK(buf != NULL);
1922 iovec vec[1];
1923 vec[0].iov_base = reinterpret_cast<void*>(const_cast<uint8_t*>(buf));
1924 vec[0].iov_len = byte_count;
1925 Dbg::DdmSendChunkV(type, vec, 1);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001926}
1927
Elliott Hughes21f32d72011-11-09 17:44:13 -08001928void Dbg::DdmSendChunk(uint32_t type, const std::vector<uint8_t>& bytes) {
1929 DdmSendChunk(type, bytes.size(), &bytes[0]);
1930}
1931
Elliott Hughescccd84f2011-12-05 16:51:54 -08001932void Dbg::DdmSendChunkV(uint32_t type, const struct iovec* iov, int iov_count) {
Elliott Hughes3bb81562011-10-21 18:52:59 -07001933 if (gJdwpState == NULL) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001934 VLOG(jdwp) << "Debugger thread not active, ignoring DDM send: " << type;
Elliott Hughes3bb81562011-10-21 18:52:59 -07001935 } else {
Elliott Hughescccd84f2011-12-05 16:51:54 -08001936 gJdwpState->DdmSendChunkV(type, iov, iov_count);
Elliott Hughes3bb81562011-10-21 18:52:59 -07001937 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001938}
1939
Elliott Hughes767a1472011-10-26 18:49:02 -07001940int Dbg::DdmHandleHpifChunk(HpifWhen when) {
1941 if (when == HPIF_WHEN_NOW) {
Elliott Hughes7162ad92011-10-27 14:08:42 -07001942 DdmSendHeapInfo(when);
Elliott Hughes767a1472011-10-26 18:49:02 -07001943 return true;
1944 }
1945
1946 if (when != HPIF_WHEN_NEVER && when != HPIF_WHEN_NEXT_GC && when != HPIF_WHEN_EVERY_GC) {
1947 LOG(ERROR) << "invalid HpifWhen value: " << static_cast<int>(when);
1948 return false;
1949 }
1950
1951 gDdmHpifWhen = when;
1952 return true;
1953}
1954
1955bool Dbg::DdmHandleHpsgNhsgChunk(Dbg::HpsgWhen when, Dbg::HpsgWhat what, bool native) {
1956 if (when != HPSG_WHEN_NEVER && when != HPSG_WHEN_EVERY_GC) {
1957 LOG(ERROR) << "invalid HpsgWhen value: " << static_cast<int>(when);
1958 return false;
1959 }
1960
1961 if (what != HPSG_WHAT_MERGED_OBJECTS && what != HPSG_WHAT_DISTINCT_OBJECTS) {
1962 LOG(ERROR) << "invalid HpsgWhat value: " << static_cast<int>(what);
1963 return false;
1964 }
1965
1966 if (native) {
1967 gDdmNhsgWhen = when;
1968 gDdmNhsgWhat = what;
1969 } else {
1970 gDdmHpsgWhen = when;
1971 gDdmHpsgWhat = what;
1972 }
1973 return true;
1974}
1975
Elliott Hughes7162ad92011-10-27 14:08:42 -07001976void Dbg::DdmSendHeapInfo(HpifWhen reason) {
1977 // If there's a one-shot 'when', reset it.
1978 if (reason == gDdmHpifWhen) {
1979 if (gDdmHpifWhen == HPIF_WHEN_NEXT_GC) {
1980 gDdmHpifWhen = HPIF_WHEN_NEVER;
1981 }
1982 }
1983
1984 /*
1985 * Chunk HPIF (client --> server)
1986 *
1987 * Heap Info. General information about the heap,
1988 * suitable for a summary display.
1989 *
1990 * [u4]: number of heaps
1991 *
1992 * For each heap:
1993 * [u4]: heap ID
1994 * [u8]: timestamp in ms since Unix epoch
1995 * [u1]: capture reason (same as 'when' value from server)
1996 * [u4]: max heap size in bytes (-Xmx)
1997 * [u4]: current heap size in bytes
1998 * [u4]: current number of bytes allocated
1999 * [u4]: current number of objects allocated
2000 */
2001 uint8_t heap_count = 1;
Elliott Hughes21f32d72011-11-09 17:44:13 -08002002 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08002003 JDWP::Append4BE(bytes, heap_count);
2004 JDWP::Append4BE(bytes, 1); // Heap id (bogus; we only have one heap).
2005 JDWP::Append8BE(bytes, MilliTime());
2006 JDWP::Append1BE(bytes, reason);
2007 JDWP::Append4BE(bytes, Heap::GetMaxMemory()); // Max allowed heap size in bytes.
2008 JDWP::Append4BE(bytes, Heap::GetTotalMemory()); // Current heap size in bytes.
2009 JDWP::Append4BE(bytes, Heap::GetBytesAllocated());
2010 JDWP::Append4BE(bytes, Heap::GetObjectsAllocated());
Elliott Hughes21f32d72011-11-09 17:44:13 -08002011 CHECK_EQ(bytes.size(), 4U + (heap_count * (4 + 8 + 1 + 4 + 4 + 4 + 4)));
2012 Dbg::DdmSendChunk(CHUNK_TYPE("HPIF"), bytes);
Elliott Hughes767a1472011-10-26 18:49:02 -07002013}
2014
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002015enum HpsgSolidity {
2016 SOLIDITY_FREE = 0,
2017 SOLIDITY_HARD = 1,
2018 SOLIDITY_SOFT = 2,
2019 SOLIDITY_WEAK = 3,
2020 SOLIDITY_PHANTOM = 4,
2021 SOLIDITY_FINALIZABLE = 5,
2022 SOLIDITY_SWEEP = 6,
2023};
2024
2025enum HpsgKind {
2026 KIND_OBJECT = 0,
2027 KIND_CLASS_OBJECT = 1,
2028 KIND_ARRAY_1 = 2,
2029 KIND_ARRAY_2 = 3,
2030 KIND_ARRAY_4 = 4,
2031 KIND_ARRAY_8 = 5,
2032 KIND_UNKNOWN = 6,
2033 KIND_NATIVE = 7,
2034};
2035
2036#define HPSG_PARTIAL (1<<7)
2037#define HPSG_STATE(solidity, kind) ((uint8_t)((((kind) & 0x7) << 3) | ((solidity) & 0x7)))
2038
Ian Rogers30fab402012-01-23 15:43:46 -08002039class HeapChunkContext {
2040 public:
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002041 // Maximum chunk size. Obtain this from the formula:
2042 // (((maximum_heap_size / ALLOCATION_UNIT_SIZE) + 255) / 256) * 2
2043 HeapChunkContext(bool merge, bool native)
Ian Rogers30fab402012-01-23 15:43:46 -08002044 : buf_(16384 - 16),
2045 type_(0),
2046 merge_(merge) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002047 Reset();
2048 if (native) {
Ian Rogers30fab402012-01-23 15:43:46 -08002049 type_ = CHUNK_TYPE("NHSG");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002050 } else {
Ian Rogers30fab402012-01-23 15:43:46 -08002051 type_ = merge ? CHUNK_TYPE("HPSG") : CHUNK_TYPE("HPSO");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002052 }
2053 }
2054
2055 ~HeapChunkContext() {
Ian Rogers30fab402012-01-23 15:43:46 -08002056 if (p_ > &buf_[0]) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002057 Flush();
2058 }
2059 }
2060
2061 void EnsureHeader(const void* chunk_ptr) {
Ian Rogers30fab402012-01-23 15:43:46 -08002062 if (!needHeader_) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002063 return;
2064 }
2065
2066 // Start a new HPSx chunk.
Ian Rogers30fab402012-01-23 15:43:46 -08002067 JDWP::Write4BE(&p_, 1); // Heap id (bogus; we only have one heap).
2068 JDWP::Write1BE(&p_, 8); // Size of allocation unit, in bytes.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002069
Ian Rogers30fab402012-01-23 15:43:46 -08002070 JDWP::Write4BE(&p_, reinterpret_cast<uintptr_t>(chunk_ptr)); // virtual address of segment start.
2071 JDWP::Write4BE(&p_, 0); // offset of this piece (relative to the virtual address).
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002072 // [u4]: length of piece, in allocation units
2073 // 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 -08002074 pieceLenField_ = p_;
2075 JDWP::Write4BE(&p_, 0x55555555);
2076 needHeader_ = false;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002077 }
2078
2079 void Flush() {
2080 // Patch the "length of piece" field.
Ian Rogers30fab402012-01-23 15:43:46 -08002081 CHECK_LE(&buf_[0], pieceLenField_);
2082 CHECK_LE(pieceLenField_, p_);
2083 JDWP::Set4BE(pieceLenField_, totalAllocationUnits_);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002084
Ian Rogers30fab402012-01-23 15:43:46 -08002085 Dbg::DdmSendChunk(type_, p_ - &buf_[0], &buf_[0]);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002086 Reset();
2087 }
2088
Ian Rogers30fab402012-01-23 15:43:46 -08002089 static void HeapChunkCallback(void* start, void* end, size_t used_bytes, void* arg) {
2090 reinterpret_cast<HeapChunkContext*>(arg)->HeapChunkCallback(start, end, used_bytes);
Elliott Hughesa2155262011-11-16 16:26:58 -08002091 }
2092
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002093 private:
Elliott Hughesa2155262011-11-16 16:26:58 -08002094 enum { ALLOCATION_UNIT_SIZE = 8 };
2095
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002096 void Reset() {
Ian Rogers30fab402012-01-23 15:43:46 -08002097 p_ = &buf_[0];
2098 totalAllocationUnits_ = 0;
2099 needHeader_ = true;
2100 pieceLenField_ = NULL;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002101 }
2102
Ian Rogers30fab402012-01-23 15:43:46 -08002103 void HeapChunkCallback(void* start, void* end, size_t used_bytes) {
2104 // Note: heap call backs cannot manipulate the heap upon which they are crawling, care is taken
2105 // in the following code not to allocate memory, by ensuring buf_ is of the correct size
2106
2107 const void* user_ptr = used_bytes > 0 ? const_cast<void*>(start) : NULL;
2108 // from malloc.c mem2chunk(mem)
2109 const void* chunk_ptr =
2110 reinterpret_cast<const void*>(reinterpret_cast<const char*>(const_cast<void*>(start)) -
2111 (2 * sizeof(size_t)));
2112 // from malloc.c chunksize
2113 size_t chunk_len = (*reinterpret_cast<size_t* const*>(chunk_ptr))[1] & ~7;
2114
2115
2116 //size_t chunk_len = malloc_usable_size(user_ptr);
Elliott Hughesa2155262011-11-16 16:26:58 -08002117 CHECK_EQ((chunk_len & (ALLOCATION_UNIT_SIZE-1)), 0U);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002118
Elliott Hughesa2155262011-11-16 16:26:58 -08002119 /* Make sure there's enough room left in the buffer.
2120 * We need to use two bytes for every fractional 256
2121 * allocation units used by the chunk.
2122 */
2123 {
2124 size_t needed = (((chunk_len/ALLOCATION_UNIT_SIZE + 255) / 256) * 2);
Ian Rogers30fab402012-01-23 15:43:46 -08002125 size_t bytesLeft = buf_.size() - (size_t)(p_ - &buf_[0]);
Elliott Hughesa2155262011-11-16 16:26:58 -08002126 if (bytesLeft < needed) {
2127 Flush();
2128 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002129
Ian Rogers30fab402012-01-23 15:43:46 -08002130 bytesLeft = buf_.size() - (size_t)(p_ - &buf_[0]);
Elliott Hughesa2155262011-11-16 16:26:58 -08002131 if (bytesLeft < needed) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08002132 LOG(WARNING) << "Chunk is too big to transmit (chunk_len=" << chunk_len << ", " << needed << " bytes)";
Elliott Hughesa2155262011-11-16 16:26:58 -08002133 return;
2134 }
2135 }
2136
2137 // OLD-TODO: notice when there's a gap and start a new heap, or at least a new range.
2138 EnsureHeader(chunk_ptr);
2139
2140 // Determine the type of this chunk.
2141 // OLD-TODO: if context.merge, see if this chunk is different from the last chunk.
2142 // If it's the same, we should combine them.
Ian Rogers30fab402012-01-23 15:43:46 -08002143 uint8_t state = ExamineObject(reinterpret_cast<const Object*>(user_ptr), (type_ == CHUNK_TYPE("NHSG")));
Elliott Hughesa2155262011-11-16 16:26:58 -08002144
2145 // Write out the chunk description.
2146 chunk_len /= ALLOCATION_UNIT_SIZE; // convert to allocation units
Ian Rogers30fab402012-01-23 15:43:46 -08002147 totalAllocationUnits_ += chunk_len;
Elliott Hughesa2155262011-11-16 16:26:58 -08002148 while (chunk_len > 256) {
Ian Rogers30fab402012-01-23 15:43:46 -08002149 *p_++ = state | HPSG_PARTIAL;
2150 *p_++ = 255; // length - 1
Elliott Hughesa2155262011-11-16 16:26:58 -08002151 chunk_len -= 256;
2152 }
Ian Rogers30fab402012-01-23 15:43:46 -08002153 *p_++ = state;
2154 *p_++ = chunk_len - 1;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002155 }
2156
Elliott Hughesa2155262011-11-16 16:26:58 -08002157 uint8_t ExamineObject(const Object* o, bool is_native_heap) {
2158 if (o == NULL) {
2159 return HPSG_STATE(SOLIDITY_FREE, 0);
2160 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002161
Elliott Hughesa2155262011-11-16 16:26:58 -08002162 // It's an allocated chunk. Figure out what it is.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002163
Elliott Hughesa2155262011-11-16 16:26:58 -08002164 // If we're looking at the native heap, we'll just return
2165 // (SOLIDITY_HARD, KIND_NATIVE) for all allocated chunks.
2166 if (is_native_heap || !Heap::IsLiveObjectLocked(o)) {
2167 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
2168 }
2169
2170 Class* c = o->GetClass();
2171 if (c == NULL) {
2172 // The object was probably just created but hasn't been initialized yet.
2173 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
2174 }
2175
2176 if (!Heap::IsHeapAddress(c)) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08002177 LOG(WARNING) << "Invalid class for managed heap object: " << o << " " << c;
Elliott Hughesa2155262011-11-16 16:26:58 -08002178 return HPSG_STATE(SOLIDITY_HARD, KIND_UNKNOWN);
2179 }
2180
2181 if (c->IsClassClass()) {
2182 return HPSG_STATE(SOLIDITY_HARD, KIND_CLASS_OBJECT);
2183 }
2184
2185 if (c->IsArrayClass()) {
2186 if (o->IsObjectArray()) {
2187 return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
2188 }
2189 switch (c->GetComponentSize()) {
2190 case 1: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_1);
2191 case 2: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_2);
2192 case 4: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
2193 case 8: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_8);
2194 }
2195 }
2196
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002197 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
2198 }
2199
Ian Rogers30fab402012-01-23 15:43:46 -08002200 std::vector<uint8_t> buf_;
2201 uint8_t* p_;
2202 uint8_t* pieceLenField_;
2203 size_t totalAllocationUnits_;
2204 uint32_t type_;
2205 bool merge_;
2206 bool needHeader_;
2207
Elliott Hughesa2155262011-11-16 16:26:58 -08002208 DISALLOW_COPY_AND_ASSIGN(HeapChunkContext);
2209};
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002210
2211void Dbg::DdmSendHeapSegments(bool native) {
2212 Dbg::HpsgWhen when;
2213 Dbg::HpsgWhat what;
2214 if (!native) {
2215 when = gDdmHpsgWhen;
2216 what = gDdmHpsgWhat;
2217 } else {
2218 when = gDdmNhsgWhen;
2219 what = gDdmNhsgWhat;
2220 }
2221 if (when == HPSG_WHEN_NEVER) {
2222 return;
2223 }
2224
2225 // Figure out what kind of chunks we'll be sending.
2226 CHECK(what == HPSG_WHAT_MERGED_OBJECTS || what == HPSG_WHAT_DISTINCT_OBJECTS) << static_cast<int>(what);
2227
2228 // First, send a heap start chunk.
2229 uint8_t heap_id[4];
2230 JDWP::Set4BE(&heap_id[0], 1); // Heap id (bogus; we only have one heap).
2231 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHST") : CHUNK_TYPE("HPST"), sizeof(heap_id), heap_id);
2232
2233 // Send a series of heap segment chunks.
Elliott Hughesa2155262011-11-16 16:26:58 -08002234 HeapChunkContext context((what == HPSG_WHAT_MERGED_OBJECTS), native);
2235 if (native) {
Ian Rogers30fab402012-01-23 15:43:46 -08002236 // TODO: enable when bionic has moved to dlmalloc 2.8.5
2237 // dlmalloc_inspect_all(HeapChunkContext::HeapChunkCallback, &context);
2238 UNIMPLEMENTED(WARNING) << "Native heap send heap segments";
Elliott Hughesa2155262011-11-16 16:26:58 -08002239 } else {
Ian Rogers30fab402012-01-23 15:43:46 -08002240 Heap::GetAllocSpace()->Walk(HeapChunkContext::HeapChunkCallback, &context);
Elliott Hughesa2155262011-11-16 16:26:58 -08002241 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002242
2243 // Finally, send a heap end chunk.
2244 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHEN") : CHUNK_TYPE("HPEN"), sizeof(heap_id), heap_id);
Elliott Hughes767a1472011-10-26 18:49:02 -07002245}
2246
Elliott Hughes545a0642011-11-08 19:10:03 -08002247void Dbg::SetAllocTrackingEnabled(bool enabled) {
2248 MutexLock mu(gAllocTrackerLock);
2249 if (enabled) {
2250 if (recent_allocation_records_ == NULL) {
2251 LOG(INFO) << "Enabling alloc tracker (" << kNumAllocRecords << " entries, "
2252 << kMaxAllocRecordStackDepth << " frames --> "
2253 << (sizeof(AllocRecord) * kNumAllocRecords) << " bytes)";
2254 gAllocRecordHead = gAllocRecordCount = 0;
2255 recent_allocation_records_ = new AllocRecord[kNumAllocRecords];
2256 CHECK(recent_allocation_records_ != NULL);
2257 }
2258 } else {
2259 delete[] recent_allocation_records_;
2260 recent_allocation_records_ = NULL;
2261 }
2262}
2263
2264struct AllocRecordStackVisitor : public Thread::StackVisitor {
Elliott Hughesba8eee12012-01-24 20:25:24 -08002265 explicit AllocRecordStackVisitor(AllocRecord* record) : record(record), depth(0) {
Elliott Hughes545a0642011-11-08 19:10:03 -08002266 }
2267
2268 virtual void VisitFrame(const Frame& f, uintptr_t pc) {
2269 if (depth >= kMaxAllocRecordStackDepth) {
2270 return;
2271 }
2272 Method* m = f.GetMethod();
2273 if (m == NULL || m->IsCalleeSaveMethod()) {
2274 return;
2275 }
2276 record->stack[depth].method = m;
2277 record->stack[depth].raw_pc = pc;
2278 ++depth;
2279 }
2280
2281 ~AllocRecordStackVisitor() {
2282 // Clear out any unused stack trace elements.
2283 for (; depth < kMaxAllocRecordStackDepth; ++depth) {
2284 record->stack[depth].method = NULL;
2285 record->stack[depth].raw_pc = 0;
2286 }
2287 }
2288
2289 AllocRecord* record;
2290 size_t depth;
2291};
2292
2293void Dbg::RecordAllocation(Class* type, size_t byte_count) {
2294 Thread* self = Thread::Current();
2295 CHECK(self != NULL);
2296
2297 MutexLock mu(gAllocTrackerLock);
2298 if (recent_allocation_records_ == NULL) {
2299 return;
2300 }
2301
2302 // Advance and clip.
2303 if (++gAllocRecordHead == kNumAllocRecords) {
2304 gAllocRecordHead = 0;
2305 }
2306
2307 // Fill in the basics.
2308 AllocRecord* record = &recent_allocation_records_[gAllocRecordHead];
2309 record->type = type;
2310 record->byte_count = byte_count;
2311 record->thin_lock_id = self->GetThinLockId();
2312
2313 // Fill in the stack trace.
2314 AllocRecordStackVisitor visitor(record);
2315 self->WalkStack(&visitor);
2316
2317 if (gAllocRecordCount < kNumAllocRecords) {
2318 ++gAllocRecordCount;
2319 }
2320}
2321
2322/*
2323 * Return the index of the head element.
2324 *
2325 * We point at the most-recently-written record, so if allocRecordCount is 1
2326 * we want to use the current element. Take "head+1" and subtract count
2327 * from it.
2328 *
2329 * We need to handle underflow in our circular buffer, so we add
2330 * kNumAllocRecords and then mask it back down.
2331 */
2332inline static int headIndex() {
2333 return (gAllocRecordHead+1 + kNumAllocRecords - gAllocRecordCount) & (kNumAllocRecords-1);
2334}
2335
2336void Dbg::DumpRecentAllocations() {
2337 MutexLock mu(gAllocTrackerLock);
2338 if (recent_allocation_records_ == NULL) {
2339 LOG(INFO) << "Not recording tracked allocations";
2340 return;
2341 }
2342
2343 // "i" is the head of the list. We want to start at the end of the
2344 // list and move forward to the tail.
2345 size_t i = headIndex();
2346 size_t count = gAllocRecordCount;
2347
2348 LOG(INFO) << "Tracked allocations, (head=" << gAllocRecordHead << " count=" << count << ")";
2349 while (count--) {
2350 AllocRecord* record = &recent_allocation_records_[i];
2351
Elliott Hughesaa6e1cd2012-01-18 19:26:06 -08002352 LOG(INFO) << StringPrintf(" T=%-2d %6zd ", record->thin_lock_id, record->byte_count)
Elliott Hughes545a0642011-11-08 19:10:03 -08002353 << PrettyClass(record->type);
2354
2355 for (size_t stack_frame = 0; stack_frame < kMaxAllocRecordStackDepth; ++stack_frame) {
2356 const Method* m = record->stack[stack_frame].method;
2357 if (m == NULL) {
2358 break;
2359 }
2360 LOG(INFO) << " " << PrettyMethod(m) << " line " << record->stack[stack_frame].LineNumber();
2361 }
2362
2363 // pause periodically to help logcat catch up
2364 if ((count % 5) == 0) {
2365 usleep(40000);
2366 }
2367
2368 i = (i + 1) & (kNumAllocRecords-1);
2369 }
2370}
2371
2372class StringTable {
2373 public:
2374 StringTable() {
2375 }
2376
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002377 void Add(const char* s) {
Elliott Hughes545a0642011-11-08 19:10:03 -08002378 table_.insert(s);
2379 }
2380
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002381 size_t IndexOf(const char* s) {
Elliott Hughes545a0642011-11-08 19:10:03 -08002382 return std::distance(table_.begin(), table_.find(s));
2383 }
2384
2385 size_t Size() {
2386 return table_.size();
2387 }
2388
2389 void WriteTo(std::vector<uint8_t>& bytes) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002390 typedef std::set<const char*>::const_iterator It; // TODO: C++0x auto
Elliott Hughes545a0642011-11-08 19:10:03 -08002391 for (It it = table_.begin(); it != table_.end(); ++it) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002392 const char* s = *it;
2393 size_t s_len = CountModifiedUtf8Chars(s);
2394 UniquePtr<uint16_t> s_utf16(new uint16_t[s_len]);
2395 ConvertModifiedUtf8ToUtf16(s_utf16.get(), s);
2396 JDWP::AppendUtf16BE(bytes, s_utf16.get(), s_len);
Elliott Hughes545a0642011-11-08 19:10:03 -08002397 }
2398 }
2399
2400 private:
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002401 std::set<const char*> table_;
Elliott Hughes545a0642011-11-08 19:10:03 -08002402 DISALLOW_COPY_AND_ASSIGN(StringTable);
2403};
2404
2405/*
2406 * The data we send to DDMS contains everything we have recorded.
2407 *
2408 * Message header (all values big-endian):
2409 * (1b) message header len (to allow future expansion); includes itself
2410 * (1b) entry header len
2411 * (1b) stack frame len
2412 * (2b) number of entries
2413 * (4b) offset to string table from start of message
2414 * (2b) number of class name strings
2415 * (2b) number of method name strings
2416 * (2b) number of source file name strings
2417 * For each entry:
2418 * (4b) total allocation size
2419 * (2b) threadId
2420 * (2b) allocated object's class name index
2421 * (1b) stack depth
2422 * For each stack frame:
2423 * (2b) method's class name
2424 * (2b) method name
2425 * (2b) method source file
2426 * (2b) line number, clipped to 32767; -2 if native; -1 if no source
2427 * (xb) class name strings
2428 * (xb) method name strings
2429 * (xb) source file strings
2430 *
2431 * As with other DDM traffic, strings are sent as a 4-byte length
2432 * followed by UTF-16 data.
2433 *
2434 * We send up 16-bit unsigned indexes into string tables. In theory there
2435 * can be (kMaxAllocRecordStackDepth * kNumAllocRecords) unique strings in
2436 * each table, but in practice there should be far fewer.
2437 *
2438 * The chief reason for using a string table here is to keep the size of
2439 * the DDMS message to a minimum. This is partly to make the protocol
2440 * efficient, but also because we have to form the whole thing up all at
2441 * once in a memory buffer.
2442 *
2443 * We use separate string tables for class names, method names, and source
2444 * files to keep the indexes small. There will generally be no overlap
2445 * between the contents of these tables.
2446 */
2447jbyteArray Dbg::GetRecentAllocations() {
2448 if (false) {
2449 DumpRecentAllocations();
2450 }
2451
2452 MutexLock mu(gAllocTrackerLock);
2453
2454 /*
2455 * Part 1: generate string tables.
2456 */
2457 StringTable class_names;
2458 StringTable method_names;
2459 StringTable filenames;
2460
2461 int count = gAllocRecordCount;
2462 int idx = headIndex();
2463 while (count--) {
2464 AllocRecord* record = &recent_allocation_records_[idx];
2465
Elliott Hughes91250e02011-12-13 22:30:35 -08002466 class_names.Add(ClassHelper(record->type).GetDescriptor());
Elliott Hughes545a0642011-11-08 19:10:03 -08002467
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002468 MethodHelper mh;
Elliott Hughes545a0642011-11-08 19:10:03 -08002469 for (size_t i = 0; i < kMaxAllocRecordStackDepth; i++) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002470 Method* m = record->stack[i].method;
2471 mh.ChangeMethod(m);
Elliott Hughes545a0642011-11-08 19:10:03 -08002472 if (m != NULL) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002473 class_names.Add(mh.GetDeclaringClassDescriptor());
2474 method_names.Add(mh.GetName());
2475 filenames.Add(mh.GetDeclaringClassSourceFile());
Elliott Hughes545a0642011-11-08 19:10:03 -08002476 }
2477 }
2478
2479 idx = (idx + 1) & (kNumAllocRecords-1);
2480 }
2481
2482 LOG(INFO) << "allocation records: " << gAllocRecordCount;
2483
2484 /*
2485 * Part 2: allocate a buffer and generate the output.
2486 */
2487 std::vector<uint8_t> bytes;
2488
2489 // (1b) message header len (to allow future expansion); includes itself
2490 // (1b) entry header len
2491 // (1b) stack frame len
2492 const int kMessageHeaderLen = 15;
2493 const int kEntryHeaderLen = 9;
2494 const int kStackFrameLen = 8;
2495 JDWP::Append1BE(bytes, kMessageHeaderLen);
2496 JDWP::Append1BE(bytes, kEntryHeaderLen);
2497 JDWP::Append1BE(bytes, kStackFrameLen);
2498
2499 // (2b) number of entries
2500 // (4b) offset to string table from start of message
2501 // (2b) number of class name strings
2502 // (2b) number of method name strings
2503 // (2b) number of source file name strings
2504 JDWP::Append2BE(bytes, gAllocRecordCount);
2505 size_t string_table_offset = bytes.size();
2506 JDWP::Append4BE(bytes, 0); // We'll patch this later...
2507 JDWP::Append2BE(bytes, class_names.Size());
2508 JDWP::Append2BE(bytes, method_names.Size());
2509 JDWP::Append2BE(bytes, filenames.Size());
2510
2511 count = gAllocRecordCount;
2512 idx = headIndex();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002513 ClassHelper kh;
Elliott Hughes545a0642011-11-08 19:10:03 -08002514 while (count--) {
2515 // For each entry:
2516 // (4b) total allocation size
2517 // (2b) thread id
2518 // (2b) allocated object's class name index
2519 // (1b) stack depth
2520 AllocRecord* record = &recent_allocation_records_[idx];
2521 size_t stack_depth = record->GetDepth();
2522 JDWP::Append4BE(bytes, record->byte_count);
2523 JDWP::Append2BE(bytes, record->thin_lock_id);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002524 kh.ChangeClass(record->type);
Elliott Hughes91250e02011-12-13 22:30:35 -08002525 JDWP::Append2BE(bytes, class_names.IndexOf(kh.GetDescriptor()));
Elliott Hughes545a0642011-11-08 19:10:03 -08002526 JDWP::Append1BE(bytes, stack_depth);
2527
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002528 MethodHelper mh;
Elliott Hughes545a0642011-11-08 19:10:03 -08002529 for (size_t stack_frame = 0; stack_frame < stack_depth; ++stack_frame) {
2530 // For each stack frame:
2531 // (2b) method's class name
2532 // (2b) method name
2533 // (2b) method source file
2534 // (2b) line number, clipped to 32767; -2 if native; -1 if no source
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002535 mh.ChangeMethod(record->stack[stack_frame].method);
2536 JDWP::Append2BE(bytes, class_names.IndexOf(mh.GetDeclaringClassDescriptor()));
2537 JDWP::Append2BE(bytes, method_names.IndexOf(mh.GetName()));
2538 JDWP::Append2BE(bytes, filenames.IndexOf(mh.GetDeclaringClassSourceFile()));
Elliott Hughes545a0642011-11-08 19:10:03 -08002539 JDWP::Append2BE(bytes, record->stack[stack_frame].LineNumber());
2540 }
2541
2542 idx = (idx + 1) & (kNumAllocRecords-1);
2543 }
2544
2545 // (xb) class name strings
2546 // (xb) method name strings
2547 // (xb) source file strings
2548 JDWP::Set4BE(&bytes[string_table_offset], bytes.size());
2549 class_names.WriteTo(bytes);
2550 method_names.WriteTo(bytes);
2551 filenames.WriteTo(bytes);
2552
2553 JNIEnv* env = Thread::Current()->GetJniEnv();
2554 jbyteArray result = env->NewByteArray(bytes.size());
2555 if (result != NULL) {
2556 env->SetByteArrayRegion(result, 0, bytes.size(), reinterpret_cast<const jbyte*>(&bytes[0]));
2557 }
2558 return result;
2559}
2560
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002561} // namespace art