blob: 613e27eb559b89d13ac40e7bc068ecca37a2b837 [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"
Elliott Hughes6a5bd492011-10-28 14:33:57 -070026#include "ScopedLocalRef.h"
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -070027#include "ScopedPrimitiveArray.h"
Elliott Hughes47fce012011-10-25 18:37:19 -070028#include "stack_indirect_reference_table.h"
Elliott Hughes475fc232011-10-25 15:00:35 -070029#include "thread_list.h"
30
Elliott Hughes6a5bd492011-10-28 14:33:57 -070031extern "C" void dlmalloc_walk_heap(void(*)(const void*, size_t, const void*, size_t, void*), void*);
32#ifndef HAVE_ANDROID_OS
33void dlmalloc_walk_heap(void(*)(const void*, size_t, const void*, size_t, void*), void*) {
34 // No-op for glibc.
35}
36#endif
37
Elliott Hughes872d4ec2011-10-21 17:07:15 -070038namespace art {
39
Elliott Hughes545a0642011-11-08 19:10:03 -080040static const size_t kMaxAllocRecordStackDepth = 16; // Max 255.
41static const size_t kNumAllocRecords = 512; // Must be power of 2.
42
Elliott Hughes475fc232011-10-25 15:00:35 -070043class ObjectRegistry {
44 public:
45 ObjectRegistry() : lock_("ObjectRegistry lock") {
46 }
47
48 JDWP::ObjectId Add(Object* o) {
49 if (o == NULL) {
50 return 0;
51 }
52 JDWP::ObjectId id = static_cast<JDWP::ObjectId>(reinterpret_cast<uintptr_t>(o));
53 MutexLock mu(lock_);
54 map_[id] = o;
55 return id;
56 }
57
Elliott Hughes234ab152011-10-26 14:02:26 -070058 void Clear() {
59 MutexLock mu(lock_);
60 LOG(DEBUG) << "Debugger has detached; object registry had " << map_.size() << " entries";
61 map_.clear();
62 }
63
Elliott Hughes475fc232011-10-25 15:00:35 -070064 bool Contains(JDWP::ObjectId id) {
65 MutexLock mu(lock_);
66 return map_.find(id) != map_.end();
67 }
68
Elliott Hughesa2155262011-11-16 16:26:58 -080069 template<typename T> T Get(JDWP::ObjectId id) {
70 MutexLock mu(lock_);
71 typedef std::map<JDWP::ObjectId, Object*>::iterator It; // C++0x auto
72 It it = map_.find(id);
73 return (it != map_.end()) ? reinterpret_cast<T>(it->second) : NULL;
74 }
75
Elliott Hughesbfe487b2011-10-26 15:48:55 -070076 void VisitRoots(Heap::RootVisitor* visitor, void* arg) {
77 MutexLock mu(lock_);
78 typedef std::map<JDWP::ObjectId, Object*>::iterator It; // C++0x auto
79 for (It it = map_.begin(); it != map_.end(); ++it) {
80 visitor(it->second, arg);
81 }
82 }
83
Elliott Hughes475fc232011-10-25 15:00:35 -070084 private:
85 Mutex lock_;
86 std::map<JDWP::ObjectId, Object*> map_;
87};
88
Elliott Hughes545a0642011-11-08 19:10:03 -080089struct AllocRecordStackTraceElement {
90 const Method* method;
91 uintptr_t raw_pc;
92
93 int32_t LineNumber() const {
94 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
95 Class* c = method->GetDeclaringClass();
96 DexCache* dex_cache = c->GetDexCache();
97 const DexFile& dex_file = class_linker->FindDexFile(dex_cache);
98 return dex_file.GetLineNumFromPC(method, method->ToDexPC(raw_pc));
99 }
100};
101
102struct AllocRecord {
103 Class* type;
104 size_t byte_count;
105 uint16_t thin_lock_id;
106 AllocRecordStackTraceElement stack[kMaxAllocRecordStackDepth]; // Unused entries have NULL method.
107
108 size_t GetDepth() {
109 size_t depth = 0;
110 while (depth < kMaxAllocRecordStackDepth && stack[depth].method != NULL) {
111 ++depth;
112 }
113 return depth;
114 }
115};
116
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700117// JDWP is allowed unless the Zygote forbids it.
118static bool gJdwpAllowed = true;
119
Elliott Hughes3bb81562011-10-21 18:52:59 -0700120// Was there a -Xrunjdwp or -agent argument on the command-line?
121static bool gJdwpConfigured = false;
122
123// Broken-down JDWP options. (Only valid if gJdwpConfigured is true.)
Elliott Hughes376a7a02011-10-24 18:35:55 -0700124static JDWP::JdwpOptions gJdwpOptions;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700125
126// Runtime JDWP state.
127static JDWP::JdwpState* gJdwpState = NULL;
128static bool gDebuggerConnected; // debugger or DDMS is connected.
129static bool gDebuggerActive; // debugger is making requests.
130
Elliott Hughes47fce012011-10-25 18:37:19 -0700131static bool gDdmThreadNotification = false;
132
Elliott Hughes767a1472011-10-26 18:49:02 -0700133// DDMS GC-related settings.
134static Dbg::HpifWhen gDdmHpifWhen = Dbg::HPIF_WHEN_NEVER;
135static Dbg::HpsgWhen gDdmHpsgWhen = Dbg::HPSG_WHEN_NEVER;
136static Dbg::HpsgWhat gDdmHpsgWhat;
137static Dbg::HpsgWhen gDdmNhsgWhen = Dbg::HPSG_WHEN_NEVER;
138static Dbg::HpsgWhat gDdmNhsgWhat;
139
Elliott Hughes475fc232011-10-25 15:00:35 -0700140static ObjectRegistry* gRegistry = NULL;
141
Elliott Hughes545a0642011-11-08 19:10:03 -0800142// Recent allocation tracking.
143static Mutex gAllocTrackerLock("AllocTracker lock");
144AllocRecord* Dbg::recent_allocation_records_ = NULL; // TODO: CircularBuffer<AllocRecord>
145static size_t gAllocRecordHead = 0;
146static size_t gAllocRecordCount = 0;
147
Elliott Hughes24437992011-11-30 14:49:33 -0800148static JDWP::JdwpTag BasicTagFromDescriptor(const char* descriptor) {
149 // JDWP deliberately uses the descriptor characters' ASCII values for its enum.
150 // Note that by "basic" we mean that we don't get more specific than JT_OBJECT.
151 return static_cast<JDWP::JdwpTag>(descriptor[0]);
152}
153
154static JDWP::JdwpTag TagFromClass(Class* c) {
155 if (c->IsArrayClass()) {
156 return JDWP::JT_ARRAY;
157 }
158
159 if (c->IsStringClass()) {
160 return JDWP::JT_STRING;
161 } else if (c->IsClassClass()) {
162 return JDWP::JT_CLASS_OBJECT;
163#if 0 // TODO
164 } else if (dvmInstanceof(clazz, gDvm.classJavaLangThread)) {
165 return JDWP::JT_THREAD;
166 } else if (dvmInstanceof(clazz, gDvm.classJavaLangThreadGroup)) {
167 return JDWP::JT_THREAD_GROUP;
168 } else if (dvmInstanceof(clazz, gDvm.classJavaLangClassLoader)) {
169 return JDWP::JT_CLASS_LOADER;
170#endif
171 } else {
172 return JDWP::JT_OBJECT;
173 }
174}
175
176/*
177 * Objects declared to hold Object might actually hold a more specific
178 * type. The debugger may take a special interest in these (e.g. it
179 * wants to display the contents of Strings), so we want to return an
180 * appropriate tag.
181 *
182 * Null objects are tagged JT_OBJECT.
183 */
184static JDWP::JdwpTag TagFromObject(const Object* o) {
185 return (o == NULL) ? JDWP::JT_OBJECT : TagFromClass(o->GetClass());
186}
187
188static bool IsPrimitiveTag(JDWP::JdwpTag tag) {
189 switch (tag) {
190 case JDWP::JT_BOOLEAN:
191 case JDWP::JT_BYTE:
192 case JDWP::JT_CHAR:
193 case JDWP::JT_FLOAT:
194 case JDWP::JT_DOUBLE:
195 case JDWP::JT_INT:
196 case JDWP::JT_LONG:
197 case JDWP::JT_SHORT:
198 case JDWP::JT_VOID:
199 return true;
200 default:
201 return false;
202 }
203}
204
Elliott Hughes3bb81562011-10-21 18:52:59 -0700205/*
206 * Handle one of the JDWP name/value pairs.
207 *
208 * JDWP options are:
209 * help: if specified, show help message and bail
210 * transport: may be dt_socket or dt_shmem
211 * address: for dt_socket, "host:port", or just "port" when listening
212 * server: if "y", wait for debugger to attach; if "n", attach to debugger
213 * timeout: how long to wait for debugger to connect / listen
214 *
215 * Useful with server=n (these aren't supported yet):
216 * onthrow=<exception-name>: connect to debugger when exception thrown
217 * onuncaught=y|n: connect to debugger when uncaught exception thrown
218 * launch=<command-line>: launch the debugger itself
219 *
220 * The "transport" option is required, as is "address" if server=n.
221 */
222static bool ParseJdwpOption(const std::string& name, const std::string& value) {
223 if (name == "transport") {
224 if (value == "dt_socket") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700225 gJdwpOptions.transport = JDWP::kJdwpTransportSocket;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700226 } else if (value == "dt_android_adb") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700227 gJdwpOptions.transport = JDWP::kJdwpTransportAndroidAdb;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700228 } else {
229 LOG(ERROR) << "JDWP transport not supported: " << value;
230 return false;
231 }
232 } else if (name == "server") {
233 if (value == "n") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700234 gJdwpOptions.server = false;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700235 } else if (value == "y") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700236 gJdwpOptions.server = true;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700237 } else {
238 LOG(ERROR) << "JDWP option 'server' must be 'y' or 'n'";
239 return false;
240 }
241 } else if (name == "suspend") {
242 if (value == "n") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700243 gJdwpOptions.suspend = false;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700244 } else if (value == "y") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700245 gJdwpOptions.suspend = true;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700246 } else {
247 LOG(ERROR) << "JDWP option 'suspend' must be 'y' or 'n'";
248 return false;
249 }
250 } else if (name == "address") {
251 /* this is either <port> or <host>:<port> */
252 std::string port_string;
Elliott Hughes376a7a02011-10-24 18:35:55 -0700253 gJdwpOptions.host.clear();
Elliott Hughes3bb81562011-10-21 18:52:59 -0700254 std::string::size_type colon = value.find(':');
255 if (colon != std::string::npos) {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700256 gJdwpOptions.host = value.substr(0, colon);
Elliott Hughes3bb81562011-10-21 18:52:59 -0700257 port_string = value.substr(colon + 1);
258 } else {
259 port_string = value;
260 }
261 if (port_string.empty()) {
262 LOG(ERROR) << "JDWP address missing port: " << value;
263 return false;
264 }
265 char* end;
266 long port = strtol(port_string.c_str(), &end, 10);
267 if (*end != '\0') {
268 LOG(ERROR) << "JDWP address has junk in port field: " << value;
269 return false;
270 }
Elliott Hughes376a7a02011-10-24 18:35:55 -0700271 gJdwpOptions.port = port;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700272 } else if (name == "launch" || name == "onthrow" || name == "oncaught" || name == "timeout") {
273 /* valid but unsupported */
274 LOG(INFO) << "Ignoring JDWP option '" << name << "'='" << value << "'";
275 } else {
276 LOG(INFO) << "Ignoring unrecognized JDWP option '" << name << "'='" << value << "'";
277 }
278
279 return true;
280}
281
282/*
283 * Parse the latter half of a -Xrunjdwp/-agentlib:jdwp= string, e.g.:
284 * "transport=dt_socket,address=8000,server=y,suspend=n"
285 */
286bool Dbg::ParseJdwpOptions(const std::string& options) {
Elliott Hughes47fce012011-10-25 18:37:19 -0700287 LOG(VERBOSE) << "ParseJdwpOptions: " << options;
288
Elliott Hughes3bb81562011-10-21 18:52:59 -0700289 std::vector<std::string> pairs;
290 Split(options, ',', pairs);
291
292 for (size_t i = 0; i < pairs.size(); ++i) {
293 std::string::size_type equals = pairs[i].find('=');
294 if (equals == std::string::npos) {
295 LOG(ERROR) << "Can't parse JDWP option '" << pairs[i] << "' in '" << options << "'";
296 return false;
297 }
298 ParseJdwpOption(pairs[i].substr(0, equals), pairs[i].substr(equals + 1));
299 }
300
Elliott Hughes376a7a02011-10-24 18:35:55 -0700301 if (gJdwpOptions.transport == JDWP::kJdwpTransportUnknown) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700302 LOG(ERROR) << "Must specify JDWP transport: " << options;
303 }
Elliott Hughes376a7a02011-10-24 18:35:55 -0700304 if (!gJdwpOptions.server && (gJdwpOptions.host.empty() || gJdwpOptions.port == 0)) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700305 LOG(ERROR) << "Must specify JDWP host and port when server=n: " << options;
306 return false;
307 }
308
309 gJdwpConfigured = true;
310 return true;
311}
312
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700313void Dbg::StartJdwp() {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700314 if (!gJdwpAllowed || !gJdwpConfigured) {
315 // No JDWP for you!
316 return;
317 }
318
Elliott Hughes475fc232011-10-25 15:00:35 -0700319 CHECK(gRegistry == NULL);
320 gRegistry = new ObjectRegistry;
321
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700322 // Init JDWP if the debugger is enabled. This may connect out to a
323 // debugger, passively listen for a debugger, or block waiting for a
324 // debugger.
Elliott Hughes376a7a02011-10-24 18:35:55 -0700325 gJdwpState = JDWP::JdwpState::Create(&gJdwpOptions);
326 if (gJdwpState == NULL) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -0800327 // We probably failed because some other process has the port already, which means that
328 // if we don't abort the user is likely to think they're talking to us when they're actually
329 // talking to that other process.
330 LOG(FATAL) << "debugger thread failed to initialize";
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700331 }
332
333 // If a debugger has already attached, send the "welcome" message.
334 // This may cause us to suspend all threads.
Elliott Hughes376a7a02011-10-24 18:35:55 -0700335 if (gJdwpState->IsActive()) {
Elliott Hughesa2155262011-11-16 16:26:58 -0800336 //ScopedThreadStateChange tsc(Thread::Current(), Thread::kRunnable);
Elliott Hughes376a7a02011-10-24 18:35:55 -0700337 if (!gJdwpState->PostVMStart()) {
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700338 LOG(WARNING) << "failed to post 'start' message to debugger";
339 }
340 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700341}
342
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700343void Dbg::StopJdwp() {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700344 delete gJdwpState;
Elliott Hughes475fc232011-10-25 15:00:35 -0700345 delete gRegistry;
346 gRegistry = NULL;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700347}
348
Elliott Hughes767a1472011-10-26 18:49:02 -0700349void Dbg::GcDidFinish() {
350 if (gDdmHpifWhen != HPIF_WHEN_NEVER) {
351 LOG(DEBUG) << "Sending VM heap info to DDM";
Elliott Hughes7162ad92011-10-27 14:08:42 -0700352 DdmSendHeapInfo(gDdmHpifWhen);
Elliott Hughes767a1472011-10-26 18:49:02 -0700353 }
354 if (gDdmHpsgWhen != HPSG_WHEN_NEVER) {
355 LOG(DEBUG) << "Dumping VM heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700356 DdmSendHeapSegments(false);
Elliott Hughes767a1472011-10-26 18:49:02 -0700357 }
358 if (gDdmNhsgWhen != HPSG_WHEN_NEVER) {
359 LOG(DEBUG) << "Dumping native heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700360 DdmSendHeapSegments(true);
Elliott Hughes767a1472011-10-26 18:49:02 -0700361 }
362}
363
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700364void Dbg::SetJdwpAllowed(bool allowed) {
365 gJdwpAllowed = allowed;
366}
367
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700368DebugInvokeReq* Dbg::GetInvokeReq() {
Elliott Hughes475fc232011-10-25 15:00:35 -0700369 return Thread::Current()->GetInvokeReq();
370}
371
372Thread* Dbg::GetDebugThread() {
373 return (gJdwpState != NULL) ? gJdwpState->GetDebugThread() : NULL;
374}
375
376void Dbg::ClearWaitForEventThread() {
377 gJdwpState->ClearWaitForEventThread();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700378}
379
380void Dbg::Connected() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700381 CHECK(!gDebuggerConnected);
382 LOG(VERBOSE) << "JDWP has attached";
383 gDebuggerConnected = true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700384}
385
Elliott Hughesa2155262011-11-16 16:26:58 -0800386void Dbg::GoActive() {
387 // Enable all debugging features, including scans for breakpoints.
388 // This is a no-op if we're already active.
389 // Only called from the JDWP handler thread.
390 if (gDebuggerActive) {
391 return;
392 }
393
394 LOG(INFO) << "Debugger is active";
395
396 // TODO: CHECK we don't have any outstanding breakpoints.
397
398 gDebuggerActive = true;
399
400 //dvmEnableAllSubMode(kSubModeDebuggerActive);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700401}
402
403void Dbg::Disconnected() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700404 CHECK(gDebuggerConnected);
405
406 gDebuggerActive = false;
407
408 //dvmDisableAllSubMode(kSubModeDebuggerActive);
409
410 gRegistry->Clear();
411 gDebuggerConnected = false;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700412}
413
414bool Dbg::IsDebuggerConnected() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700415 return gDebuggerActive;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700416}
417
418bool Dbg::IsDebuggingEnabled() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700419 return gJdwpConfigured;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700420}
421
422int64_t Dbg::LastDebuggerActivity() {
423 UNIMPLEMENTED(WARNING);
424 return -1;
425}
426
427int Dbg::ThreadRunning() {
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700428 return static_cast<int>(Thread::Current()->SetState(Thread::kRunnable));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700429}
430
431int Dbg::ThreadWaiting() {
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700432 return static_cast<int>(Thread::Current()->SetState(Thread::kVmWait));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700433}
434
Elliott Hughes6ba581a2011-10-25 11:45:35 -0700435int Dbg::ThreadContinuing(int new_state) {
436 return static_cast<int>(Thread::Current()->SetState(static_cast<Thread::State>(new_state)));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700437}
438
439void Dbg::UndoDebuggerSuspensions() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700440 Runtime::Current()->GetThreadList()->UndoDebuggerSuspensions();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700441}
442
443void Dbg::Exit(int status) {
Elliott Hughes1bba14f2011-12-01 18:00:36 -0800444 exit(status); // This is all dalvik did.
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700445}
446
Elliott Hughesbfe487b2011-10-26 15:48:55 -0700447void Dbg::VisitRoots(Heap::RootVisitor* visitor, void* arg) {
448 if (gRegistry != NULL) {
449 gRegistry->VisitRoots(visitor, arg);
450 }
451}
452
Elliott Hughesa2155262011-11-16 16:26:58 -0800453std::string Dbg::GetClassDescriptor(JDWP::RefTypeId classId) {
454 Class* c = gRegistry->Get<Class*>(classId);
455 return c->GetDescriptor()->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700456}
457
458JDWP::ObjectId Dbg::GetClassObject(JDWP::RefTypeId id) {
459 UNIMPLEMENTED(FATAL);
460 return 0;
461}
462
463JDWP::RefTypeId Dbg::GetSuperclass(JDWP::RefTypeId id) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800464 Class* c = gRegistry->Get<Class*>(id);
465 return gRegistry->Add(c->GetSuperClass());
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700466}
467
468JDWP::ObjectId Dbg::GetClassLoader(JDWP::RefTypeId id) {
Elliott Hughes1bba14f2011-12-01 18:00:36 -0800469 Object* o = gRegistry->Get<Object*>(id);
470 return gRegistry->Add(o->GetClass()->GetClassLoader());
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700471}
472
473uint32_t Dbg::GetAccessFlags(JDWP::RefTypeId id) {
474 UNIMPLEMENTED(FATAL);
475 return 0;
476}
477
Elliott Hughesaed4be92011-12-02 16:16:23 -0800478bool Dbg::IsInterface(JDWP::RefTypeId classId) {
479 Class* c = gRegistry->Get<Class*>(classId);
480 return c->IsInterface();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700481}
482
Elliott Hughesa2155262011-11-16 16:26:58 -0800483void Dbg::GetClassList(uint32_t* pClassCount, JDWP::RefTypeId** pClasses) {
484 // Get the complete list of reference classes (i.e. all classes except
485 // the primitive types).
486 // Returns a newly-allocated buffer full of RefTypeId values.
487 struct ClassListCreator {
488 static bool Visit(Class* c, void* arg) {
489 return reinterpret_cast<ClassListCreator*>(arg)->Visit(c);
490 }
491
492 bool Visit(Class* c) {
493 if (!c->IsPrimitive()) {
494 classes.push_back(static_cast<JDWP::RefTypeId>(gRegistry->Add(c)));
495 }
496 return true;
497 }
498
499 std::vector<JDWP::RefTypeId> classes;
500 };
501
502 ClassListCreator clc;
503 Runtime::Current()->GetClassLinker()->VisitClasses(ClassListCreator::Visit, &clc);
504 *pClassCount = clc.classes.size();
505 *pClasses = new JDWP::RefTypeId[clc.classes.size()];
506 for (size_t i = 0; i < clc.classes.size(); ++i) {
507 (*pClasses)[i] = clc.classes[i];
508 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700509}
510
511void Dbg::GetVisibleClassList(JDWP::ObjectId classLoaderId, uint32_t* pNumClasses, JDWP::RefTypeId** pClassRefBuf) {
512 UNIMPLEMENTED(FATAL);
513}
514
Elliott Hughesa2155262011-11-16 16:26:58 -0800515void Dbg::GetClassInfo(JDWP::RefTypeId classId, uint8_t* pTypeTag, uint32_t* pStatus, std::string* pDescriptor) {
516 Class* c = gRegistry->Get<Class*>(classId);
517 if (c->IsArrayClass()) {
518 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
519 *pTypeTag = JDWP::TT_ARRAY;
520 } else {
521 if (c->IsErroneous()) {
522 *pStatus = JDWP::CS_ERROR;
523 } else {
524 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED | JDWP::CS_INITIALIZED;
525 }
526 *pTypeTag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
527 }
528
529 if (pDescriptor != NULL) {
530 *pDescriptor = c->GetDescriptor()->ToModifiedUtf8();
531 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700532}
533
534bool Dbg::FindLoadedClassBySignature(const char* classDescriptor, JDWP::RefTypeId* pRefTypeId) {
535 UNIMPLEMENTED(FATAL);
536 return false;
537}
538
539void Dbg::GetObjectType(JDWP::ObjectId objectId, uint8_t* pRefTypeTag, JDWP::RefTypeId* pRefTypeId) {
Elliott Hughes499c5132011-11-17 14:55:11 -0800540 Object* o = gRegistry->Get<Object*>(objectId);
541 if (o->GetClass()->IsArrayClass()) {
542 *pRefTypeTag = JDWP::TT_ARRAY;
543 } else if (o->GetClass()->IsInterface()) {
544 *pRefTypeTag = JDWP::TT_INTERFACE;
545 } else {
546 *pRefTypeTag = JDWP::TT_CLASS;
547 }
548 *pRefTypeId = gRegistry->Add(o->GetClass());
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700549}
550
551uint8_t Dbg::GetClassObjectType(JDWP::RefTypeId refTypeId) {
552 UNIMPLEMENTED(FATAL);
553 return 0;
554}
555
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800556std::string Dbg::GetSignature(JDWP::RefTypeId refTypeId) {
557 Class* c = gRegistry->Get<Class*>(refTypeId);
558 CHECK(c != NULL);
559 return c->GetDescriptor()->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700560}
561
Elliott Hughes03181a82011-11-17 17:22:21 -0800562bool Dbg::GetSourceFile(JDWP::RefTypeId refTypeId, std::string& result) {
563 Class* c = gRegistry->Get<Class*>(refTypeId);
564 CHECK(c != NULL);
565
566 String* source_file = c->GetSourceFile();
567 if (source_file == NULL) {
568 return false;
569 }
570 result = source_file->ToModifiedUtf8();
571 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700572}
573
574const char* Dbg::GetObjectTypeName(JDWP::ObjectId objectId) {
575 UNIMPLEMENTED(FATAL);
576 return NULL;
577}
578
579uint8_t Dbg::GetObjectTag(JDWP::ObjectId objectId) {
Elliott Hughes24437992011-11-30 14:49:33 -0800580 Object* o = gRegistry->Get<Object*>(objectId);
581 return TagFromObject(o);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700582}
583
Elliott Hughesaed4be92011-12-02 16:16:23 -0800584size_t Dbg::GetTagWidth(JDWP::JdwpTag tag) {
Elliott Hughesdbb40792011-11-18 17:05:22 -0800585 switch (tag) {
586 case JDWP::JT_VOID:
587 return 0;
588 case JDWP::JT_BYTE:
589 case JDWP::JT_BOOLEAN:
590 return 1;
591 case JDWP::JT_CHAR:
592 case JDWP::JT_SHORT:
593 return 2;
594 case JDWP::JT_FLOAT:
595 case JDWP::JT_INT:
596 return 4;
597 case JDWP::JT_ARRAY:
598 case JDWP::JT_OBJECT:
599 case JDWP::JT_STRING:
600 case JDWP::JT_THREAD:
601 case JDWP::JT_THREAD_GROUP:
602 case JDWP::JT_CLASS_LOADER:
603 case JDWP::JT_CLASS_OBJECT:
604 return sizeof(JDWP::ObjectId);
605 case JDWP::JT_DOUBLE:
606 case JDWP::JT_LONG:
607 return 8;
608 default:
609 LOG(FATAL) << "unknown tag " << tag;
610 return -1;
611 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700612}
613
614int Dbg::GetArrayLength(JDWP::ObjectId arrayId) {
Elliott Hughes68fdbd02011-11-29 19:22:47 -0800615 Object* o = gRegistry->Get<Object*>(arrayId);
616 Array* a = o->AsArray();
617 return a->GetLength();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700618}
619
620uint8_t Dbg::GetArrayElementTag(JDWP::ObjectId arrayId) {
Elliott Hughes24437992011-11-30 14:49:33 -0800621 Object* o = gRegistry->Get<Object*>(arrayId);
622 Array* a = o->AsArray();
623 std::string descriptor(a->GetClass()->GetDescriptor()->ToModifiedUtf8());
624 JDWP::JdwpTag tag = BasicTagFromDescriptor(descriptor.c_str() + 1);
625 if (!IsPrimitiveTag(tag)) {
626 tag = TagFromClass(a->GetClass()->GetComponentType());
627 }
628 return tag;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700629}
630
Elliott Hughes24437992011-11-30 14:49:33 -0800631bool Dbg::OutputArray(JDWP::ObjectId arrayId, int offset, int count, JDWP::ExpandBuf* pReply) {
632 Object* o = gRegistry->Get<Object*>(arrayId);
633 Array* a = o->AsArray();
634
635 if (offset < 0 || count < 0 || offset > a->GetLength() || a->GetLength() - offset < count) {
636 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
637 return false;
638 }
639
640 std::string descriptor(a->GetClass()->GetDescriptor()->ToModifiedUtf8());
641 JDWP::JdwpTag tag = BasicTagFromDescriptor(descriptor.c_str() + 1);
642
643 if (IsPrimitiveTag(tag)) {
644 size_t width = GetTagWidth(tag);
645 const uint8_t* src = reinterpret_cast<uint8_t*>(a->GetRawData());
646 uint8_t* dst = expandBufAddSpace(pReply, count * width);
647 if (width == 8) {
648 const uint64_t* src8 = reinterpret_cast<const uint64_t*>(src);
649 for (int i = 0; i < count; ++i) JDWP::Write8BE(&dst, src8[offset + i]);
650 } else if (width == 4) {
651 const uint32_t* src4 = reinterpret_cast<const uint32_t*>(src);
652 for (int i = 0; i < count; ++i) JDWP::Write4BE(&dst, src4[offset + i]);
653 } else if (width == 2) {
654 const uint16_t* src2 = reinterpret_cast<const uint16_t*>(src);
655 for (int i = 0; i < count; ++i) JDWP::Write2BE(&dst, src2[offset + i]);
656 } else {
657 memcpy(dst, &src[offset * width], count * width);
658 }
659 } else {
660 ObjectArray<Object>* oa = a->AsObjectArray<Object>();
661 for (int i = 0; i < count; ++i) {
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800662 Object* element = oa->Get(offset + i);
Elliott Hughes24437992011-11-30 14:49:33 -0800663 JDWP::JdwpTag specific_tag = (element != NULL) ? TagFromObject(element) : tag;
664 expandBufAdd1(pReply, specific_tag);
665 expandBufAddObjectId(pReply, gRegistry->Add(element));
666 }
667 }
668
669 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700670}
671
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800672bool Dbg::SetArrayElements(JDWP::ObjectId arrayId, int offset, int count, const uint8_t* src) {
673 Object* o = gRegistry->Get<Object*>(arrayId);
674 Array* a = o->AsArray();
675
676 if (offset < 0 || count < 0 || offset > a->GetLength() || a->GetLength() - offset < count) {
677 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
678 return false;
679 }
680
681 std::string descriptor(a->GetClass()->GetDescriptor()->ToModifiedUtf8());
682 JDWP::JdwpTag tag = BasicTagFromDescriptor(descriptor.c_str() + 1);
683
684 if (IsPrimitiveTag(tag)) {
685 size_t width = GetTagWidth(tag);
686 uint8_t* dst = &(reinterpret_cast<uint8_t*>(a->GetRawData())[offset * width]);
687 if (width == 8) {
688 for (int i = 0; i < count; ++i) {
689 // Handle potentially non-aligned memory access one byte at a time for ARM's benefit.
690 uint64_t value;
691 for (size_t j = 0; j < sizeof(uint64_t); ++j) reinterpret_cast<uint8_t*>(&value)[j] = src[j];
692 src += sizeof(uint64_t);
693 JDWP::Write8BE(&dst, value);
694 }
695 } else if (width == 4) {
696 const uint32_t* src4 = reinterpret_cast<const uint32_t*>(src);
697 for (int i = 0; i < count; ++i) JDWP::Write4BE(&dst, src4[i]);
698 } else if (width == 2) {
699 const uint16_t* src2 = reinterpret_cast<const uint16_t*>(src);
700 for (int i = 0; i < count; ++i) JDWP::Write2BE(&dst, src2[i]);
701 } else {
702 memcpy(&dst[offset * width], src, count * width);
703 }
704 } else {
705 ObjectArray<Object>* oa = a->AsObjectArray<Object>();
706 for (int i = 0; i < count; ++i) {
707 JDWP::ObjectId id = JDWP::ReadObjectId(&src);
708 oa->Set(offset + i, gRegistry->Get<Object*>(id));
709 }
710 }
711
712 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700713}
714
715JDWP::ObjectId Dbg::CreateString(const char* str) {
716 UNIMPLEMENTED(FATAL);
717 return 0;
718}
719
720JDWP::ObjectId Dbg::CreateObject(JDWP::RefTypeId classId) {
721 UNIMPLEMENTED(FATAL);
722 return 0;
723}
724
725JDWP::ObjectId Dbg::CreateArrayObject(JDWP::RefTypeId arrayTypeId, uint32_t length) {
726 UNIMPLEMENTED(FATAL);
727 return 0;
728}
729
730bool Dbg::MatchType(JDWP::RefTypeId instClassId, JDWP::RefTypeId classId) {
731 UNIMPLEMENTED(FATAL);
732 return false;
733}
734
Elliott Hughes03181a82011-11-17 17:22:21 -0800735JDWP::FieldId ToFieldId(Field* f) {
736#ifdef MOVING_GARBAGE_COLLECTOR
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700737 UNIMPLEMENTED(FATAL);
Elliott Hughes03181a82011-11-17 17:22:21 -0800738#else
739 return static_cast<JDWP::FieldId>(reinterpret_cast<uintptr_t>(f));
740#endif
741}
742
743JDWP::MethodId ToMethodId(Method* m) {
744#ifdef MOVING_GARBAGE_COLLECTOR
745 UNIMPLEMENTED(FATAL);
746#else
747 return static_cast<JDWP::MethodId>(reinterpret_cast<uintptr_t>(m));
748#endif
749}
750
Elliott Hughesaed4be92011-12-02 16:16:23 -0800751Field* FromFieldId(JDWP::FieldId fid) {
752#ifdef MOVING_GARBAGE_COLLECTOR
753 UNIMPLEMENTED(FATAL);
754#else
755 return reinterpret_cast<Field*>(static_cast<uintptr_t>(fid));
756#endif
757}
758
Elliott Hughes03181a82011-11-17 17:22:21 -0800759Method* FromMethodId(JDWP::MethodId mid) {
760#ifdef MOVING_GARBAGE_COLLECTOR
761 UNIMPLEMENTED(FATAL);
762#else
763 return reinterpret_cast<Method*>(static_cast<uintptr_t>(mid));
764#endif
765}
766
767std::string Dbg::GetMethodName(JDWP::RefTypeId refTypeId, JDWP::MethodId methodId) {
768 return FromMethodId(methodId)->GetName()->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700769}
770
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800771/*
772 * Augment the access flags for synthetic methods and fields by setting
773 * the (as described by the spec) "0xf0000000 bit". Also, strip out any
774 * flags not specified by the Java programming language.
775 */
776static uint32_t MangleAccessFlags(uint32_t accessFlags) {
777 accessFlags &= kAccJavaFlagsMask;
778 if ((accessFlags & kAccSynthetic) != 0) {
779 accessFlags |= 0xf0000000;
780 }
781 return accessFlags;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700782}
783
Elliott Hughesdbb40792011-11-18 17:05:22 -0800784static const uint16_t kEclipseWorkaroundSlot = 1000;
785
786/*
787 * Eclipse appears to expect that the "this" reference is in slot zero.
788 * If it's not, the "variables" display will show two copies of "this",
789 * possibly because it gets "this" from SF.ThisObject and then displays
790 * all locals with nonzero slot numbers.
791 *
792 * So, we remap the item in slot 0 to 1000, and remap "this" to zero. On
793 * SF.GetValues / SF.SetValues we map them back.
Elliott Hughesc5b734a2011-12-01 17:20:58 -0800794 *
795 * TODO: jdb uses the value to determine whether a variable is a local or an argument,
796 * by checking whether it's less than the number of arguments. To make that work, we'd
797 * have to "mangle" all the arguments to come first, not just the implicit argument 'this'.
Elliott Hughesdbb40792011-11-18 17:05:22 -0800798 */
799static uint16_t MangleSlot(uint16_t slot, const char* name) {
800 uint16_t newSlot = slot;
801 if (strcmp(name, "this") == 0) {
802 newSlot = 0;
803 } else if (slot == 0) {
804 newSlot = kEclipseWorkaroundSlot;
805 }
806 return newSlot;
807}
808
Elliott Hughes68fdbd02011-11-29 19:22:47 -0800809static uint16_t DemangleSlot(uint16_t slot, Frame& f) {
Elliott Hughesdbb40792011-11-18 17:05:22 -0800810 if (slot == kEclipseWorkaroundSlot) {
Elliott Hughes68fdbd02011-11-29 19:22:47 -0800811 return 0;
Elliott Hughesdbb40792011-11-18 17:05:22 -0800812 } else if (slot == 0) {
Elliott Hughesdbb40792011-11-18 17:05:22 -0800813 Method* m = f.GetMethod();
Elliott Hughes68fdbd02011-11-29 19:22:47 -0800814 return m->NumRegisters() - m->NumIns();
Elliott Hughesdbb40792011-11-18 17:05:22 -0800815 }
Elliott Hughes68fdbd02011-11-29 19:22:47 -0800816 return slot;
Elliott Hughesdbb40792011-11-18 17:05:22 -0800817}
818
Elliott Hughesc5b734a2011-12-01 17:20:58 -0800819void Dbg::OutputDeclaredFields(JDWP::RefTypeId refTypeId, bool with_generic, JDWP::ExpandBuf* pReply) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800820 Class* c = gRegistry->Get<Class*>(refTypeId);
821 CHECK(c != NULL);
822
823 size_t instance_field_count = c->NumInstanceFields();
824 size_t static_field_count = c->NumStaticFields();
825
826 expandBufAdd4BE(pReply, instance_field_count + static_field_count);
827
828 for (size_t i = 0; i < instance_field_count + static_field_count; ++i) {
829 Field* f = (i < instance_field_count) ? c->GetInstanceField(i) : c->GetStaticField(i - instance_field_count);
830
831 expandBufAddFieldId(pReply, ToFieldId(f));
832 expandBufAddUtf8String(pReply, f->GetName()->ToModifiedUtf8().c_str());
833 expandBufAddUtf8String(pReply, f->GetTypeDescriptor());
Elliott Hughesc5b734a2011-12-01 17:20:58 -0800834 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800835 static const char genericSignature[1] = "";
836 expandBufAddUtf8String(pReply, genericSignature);
837 }
838 expandBufAdd4BE(pReply, MangleAccessFlags(f->GetAccessFlags()));
839 }
840}
841
Elliott Hughesc5b734a2011-12-01 17:20:58 -0800842void Dbg::OutputDeclaredMethods(JDWP::RefTypeId refTypeId, bool with_generic, JDWP::ExpandBuf* pReply) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800843 Class* c = gRegistry->Get<Class*>(refTypeId);
844 CHECK(c != NULL);
845
846 size_t direct_method_count = c->NumDirectMethods();
847 size_t virtual_method_count = c->NumVirtualMethods();
848
849 expandBufAdd4BE(pReply, direct_method_count + virtual_method_count);
850
851 for (size_t i = 0; i < direct_method_count + virtual_method_count; ++i) {
852 Method* m = (i < direct_method_count) ? c->GetDirectMethod(i) : c->GetVirtualMethod(i - direct_method_count);
853
854 expandBufAddMethodId(pReply, ToMethodId(m));
855 expandBufAddUtf8String(pReply, m->GetName()->ToModifiedUtf8().c_str());
856 expandBufAddUtf8String(pReply, m->GetSignature()->ToModifiedUtf8().c_str());
Elliott Hughesc5b734a2011-12-01 17:20:58 -0800857 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800858 static const char genericSignature[1] = "";
859 expandBufAddUtf8String(pReply, genericSignature);
860 }
861 expandBufAdd4BE(pReply, MangleAccessFlags(m->GetAccessFlags()));
862 }
863}
864
865void Dbg::OutputDeclaredInterfaces(JDWP::RefTypeId refTypeId, JDWP::ExpandBuf* pReply) {
866 Class* c = gRegistry->Get<Class*>(refTypeId);
867 CHECK(c != NULL);
868 size_t interface_count = c->NumInterfaces();
869 expandBufAdd4BE(pReply, interface_count);
870 for (size_t i = 0; i < interface_count; ++i) {
871 expandBufAddRefTypeId(pReply, gRegistry->Add(c->GetInterface(i)));
872 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700873}
874
875void Dbg::OutputLineTable(JDWP::RefTypeId refTypeId, JDWP::MethodId methodId, JDWP::ExpandBuf* pReply) {
Elliott Hughes03181a82011-11-17 17:22:21 -0800876 struct DebugCallbackContext {
877 int numItems;
878 JDWP::ExpandBuf* pReply;
879
880 static bool Callback(void* context, uint32_t address, uint32_t lineNum) {
881 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
882 expandBufAdd8BE(pContext->pReply, address);
883 expandBufAdd4BE(pContext->pReply, lineNum);
884 pContext->numItems++;
885 return true;
886 }
887 };
888
889 Method* m = FromMethodId(methodId);
890 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
891 const DexFile& dex_file = class_linker->FindDexFile(m->GetDeclaringClass()->GetDexCache());
892 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(m->GetCodeItemOffset());
893
894 uint64_t start, end;
895 if (m->IsNative()) {
896 start = -1;
897 end = -1;
898 } else {
899 start = 0;
900 end = code_item->insns_size_in_code_units_; // TODO: what are the units supposed to be? *2?
901 }
902
903 expandBufAdd8BE(pReply, start);
904 expandBufAdd8BE(pReply, end);
905
906 // Add numLines later
907 size_t numLinesOffset = expandBufGetLength(pReply);
908 expandBufAdd4BE(pReply, 0);
909
910 DebugCallbackContext context;
911 context.numItems = 0;
912 context.pReply = pReply;
913
914 dex_file.DecodeDebugInfo(code_item, m, DebugCallbackContext::Callback, NULL, &context);
915
916 JDWP::Set4BE(expandBufGetBuffer(pReply) + numLinesOffset, context.numItems);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700917}
918
Elliott Hughesc5b734a2011-12-01 17:20:58 -0800919void Dbg::OutputVariableTable(JDWP::RefTypeId refTypeId, JDWP::MethodId methodId, bool with_generic, JDWP::ExpandBuf* pReply) {
Elliott Hughesdbb40792011-11-18 17:05:22 -0800920 struct DebugCallbackContext {
Elliott Hughesdbb40792011-11-18 17:05:22 -0800921 JDWP::ExpandBuf* pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -0800922 size_t variable_count;
923 bool with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -0800924
Elliott Hughesc5b734a2011-12-01 17:20:58 -0800925 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 -0800926 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
927
Elliott Hughesc5b734a2011-12-01 17:20:58 -0800928 LOG(VERBOSE) << StringPrintf(" %2d: %d(%d) '%s' '%s' '%s' slot=%d", pContext->variable_count, startAddress, endAddress - startAddress, name, descriptor, signature, slot);
Elliott Hughesdbb40792011-11-18 17:05:22 -0800929
Elliott Hughes68fdbd02011-11-29 19:22:47 -0800930 slot = MangleSlot(slot, name);
931
Elliott Hughesdbb40792011-11-18 17:05:22 -0800932 expandBufAdd8BE(pContext->pReply, startAddress);
933 expandBufAddUtf8String(pContext->pReply, name);
934 expandBufAddUtf8String(pContext->pReply, descriptor);
Elliott Hughesc5b734a2011-12-01 17:20:58 -0800935 if (pContext->with_generic) {
Elliott Hughesdbb40792011-11-18 17:05:22 -0800936 expandBufAddUtf8String(pContext->pReply, signature);
937 }
938 expandBufAdd4BE(pContext->pReply, endAddress - startAddress);
939 expandBufAdd4BE(pContext->pReply, slot);
940
Elliott Hughesc5b734a2011-12-01 17:20:58 -0800941 ++pContext->variable_count;
Elliott Hughesdbb40792011-11-18 17:05:22 -0800942 }
943 };
944
945 Method* m = FromMethodId(methodId);
946 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
947 const DexFile& dex_file = class_linker->FindDexFile(m->GetDeclaringClass()->GetDexCache());
948 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(m->GetCodeItemOffset());
949
Elliott Hughesc5b734a2011-12-01 17:20:58 -0800950 // arg_count considers doubles and longs to take 2 units.
951 // variable_count considers everything to take 1 unit.
952 std::string shorty(m->GetShorty()->ToModifiedUtf8());
953 expandBufAdd4BE(pReply, m->NumArgRegisters(shorty));
Elliott Hughesdbb40792011-11-18 17:05:22 -0800954
Elliott Hughesc5b734a2011-12-01 17:20:58 -0800955 // We don't know the total number of variables yet, so leave a blank and update it later.
956 size_t variable_count_offset = expandBufGetLength(pReply);
Elliott Hughesdbb40792011-11-18 17:05:22 -0800957 expandBufAdd4BE(pReply, 0);
958
959 DebugCallbackContext context;
Elliott Hughesdbb40792011-11-18 17:05:22 -0800960 context.pReply = pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -0800961 context.variable_count = 0;
962 context.with_generic = with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -0800963
964 dex_file.DecodeDebugInfo(code_item, m, NULL, DebugCallbackContext::Callback, &context);
965
Elliott Hughesc5b734a2011-12-01 17:20:58 -0800966 JDWP::Set4BE(expandBufGetBuffer(pReply) + variable_count_offset, context.variable_count);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700967}
968
Elliott Hughesaed4be92011-12-02 16:16:23 -0800969JDWP::JdwpTag Dbg::GetFieldBasicTag(JDWP::FieldId fieldId) {
970 return BasicTagFromDescriptor(FromFieldId(fieldId)->GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700971}
972
Elliott Hughesaed4be92011-12-02 16:16:23 -0800973JDWP::JdwpTag Dbg::GetStaticFieldBasicTag(JDWP::FieldId fieldId) {
974 return BasicTagFromDescriptor(FromFieldId(fieldId)->GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700975}
976
977void Dbg::GetFieldValue(JDWP::ObjectId objectId, JDWP::FieldId fieldId, JDWP::ExpandBuf* pReply) {
Elliott Hughesaed4be92011-12-02 16:16:23 -0800978 Object* o = gRegistry->Get<Object*>(objectId);
979 Field* f = FromFieldId(fieldId);
980
981 JDWP::JdwpTag tag = BasicTagFromDescriptor(f->GetTypeDescriptor());
982
983 if (IsPrimitiveTag(tag)) {
984 expandBufAdd1(pReply, tag);
985 if (tag == JDWP::JT_BOOLEAN || tag == JDWP::JT_BYTE) {
986 expandBufAdd1(pReply, f->Get32(o));
987 } else if (tag == JDWP::JT_CHAR || tag == JDWP::JT_SHORT) {
988 expandBufAdd2BE(pReply, f->Get32(o));
989 } else if (tag == JDWP::JT_FLOAT || tag == JDWP::JT_INT) {
990 expandBufAdd4BE(pReply, f->Get32(o));
991 } else if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
992 expandBufAdd8BE(pReply, f->Get64(o));
993 } else {
994 LOG(FATAL) << "unknown tag: " << tag;
995 }
996 } else {
997 Object* value = f->GetObject(o);
998 expandBufAdd1(pReply, TagFromObject(value));
999 expandBufAddObjectId(pReply, gRegistry->Add(value));
1000 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001001}
1002
1003void Dbg::SetFieldValue(JDWP::ObjectId objectId, JDWP::FieldId fieldId, uint64_t value, int width) {
Elliott Hughesaed4be92011-12-02 16:16:23 -08001004 Object* o = gRegistry->Get<Object*>(objectId);
1005 Field* f = FromFieldId(fieldId);
1006
1007 JDWP::JdwpTag tag = BasicTagFromDescriptor(f->GetTypeDescriptor());
1008
1009 if (IsPrimitiveTag(tag)) {
1010 if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
1011 f->Set64(o, value);
1012 } else {
1013 f->Set32(o, value);
1014 }
1015 } else {
1016 f->SetObject(o, gRegistry->Get<Object*>(value));
1017 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001018}
1019
1020void Dbg::GetStaticFieldValue(JDWP::RefTypeId refTypeId, JDWP::FieldId fieldId, JDWP::ExpandBuf* pReply) {
1021 UNIMPLEMENTED(FATAL);
1022}
1023
1024void Dbg::SetStaticFieldValue(JDWP::RefTypeId refTypeId, JDWP::FieldId fieldId, uint64_t rawValue, int width) {
1025 UNIMPLEMENTED(FATAL);
1026}
1027
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001028std::string Dbg::StringToUtf8(JDWP::ObjectId strId) {
1029 String* s = gRegistry->Get<String*>(strId);
1030 return s->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001031}
1032
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001033Thread* DecodeThread(JDWP::ObjectId threadId) {
1034 Object* thread_peer = gRegistry->Get<Object*>(threadId);
1035 CHECK(thread_peer != NULL);
1036 return Thread::FromManagedThread(thread_peer);
1037}
1038
1039bool Dbg::GetThreadName(JDWP::ObjectId threadId, std::string& name) {
1040 ScopedThreadListLock thread_list_lock;
1041 Thread* thread = DecodeThread(threadId);
1042 if (thread == NULL) {
1043 return false;
1044 }
1045 StringAppendF(&name, "<%d> %s", thread->GetThinLockId(), thread->GetName()->ToModifiedUtf8().c_str());
1046 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001047}
1048
1049JDWP::ObjectId Dbg::GetThreadGroup(JDWP::ObjectId threadId) {
Elliott Hughes499c5132011-11-17 14:55:11 -08001050 Object* thread = gRegistry->Get<Object*>(threadId);
1051 CHECK(thread != NULL);
1052
1053 Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/Thread;");
1054 CHECK(c != NULL);
1055 Field* f = c->FindInstanceField("group", "Ljava/lang/ThreadGroup;");
1056 CHECK(f != NULL);
1057 Object* group = f->GetObject(thread);
1058 CHECK(group != NULL);
1059 return gRegistry->Add(group);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001060}
1061
Elliott Hughes499c5132011-11-17 14:55:11 -08001062std::string Dbg::GetThreadGroupName(JDWP::ObjectId threadGroupId) {
1063 Object* thread_group = gRegistry->Get<Object*>(threadGroupId);
1064 CHECK(thread_group != NULL);
1065
1066 Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/ThreadGroup;");
1067 CHECK(c != NULL);
1068 Field* f = c->FindInstanceField("name", "Ljava/lang/String;");
1069 CHECK(f != NULL);
1070 String* s = reinterpret_cast<String*>(f->GetObject(thread_group));
1071 return s->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001072}
1073
1074JDWP::ObjectId Dbg::GetThreadGroupParent(JDWP::ObjectId threadGroupId) {
Elliott Hughes4e235312011-12-02 11:34:15 -08001075 Object* thread_group = gRegistry->Get<Object*>(threadGroupId);
1076 CHECK(thread_group != NULL);
1077
1078 Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/ThreadGroup;");
1079 CHECK(c != NULL);
1080 Field* f = c->FindInstanceField("parent", "Ljava/lang/ThreadGroup;");
1081 CHECK(f != NULL);
1082 Object* parent = f->GetObject(thread_group);
1083 return gRegistry->Add(parent);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001084}
1085
Elliott Hughes499c5132011-11-17 14:55:11 -08001086static Object* GetStaticThreadGroup(const char* field_name) {
1087 Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/ThreadGroup;");
1088 CHECK(c != NULL);
1089 Field* f = c->FindStaticField(field_name, "Ljava/lang/ThreadGroup;");
1090 CHECK(f != NULL);
1091 Object* group = f->GetObject(NULL);
1092 CHECK(group != NULL);
1093 return group;
1094}
1095
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001096JDWP::ObjectId Dbg::GetSystemThreadGroupId() {
Elliott Hughes499c5132011-11-17 14:55:11 -08001097 return gRegistry->Add(GetStaticThreadGroup("mSystem"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001098}
1099
1100JDWP::ObjectId Dbg::GetMainThreadGroupId() {
Elliott Hughes499c5132011-11-17 14:55:11 -08001101 return gRegistry->Add(GetStaticThreadGroup("mMain"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001102}
1103
Elliott Hughes499c5132011-11-17 14:55:11 -08001104bool Dbg::GetThreadStatus(JDWP::ObjectId threadId, uint32_t* pThreadStatus, uint32_t* pSuspendStatus) {
1105 ScopedThreadListLock thread_list_lock;
1106
1107 Thread* thread = DecodeThread(threadId);
1108 if (thread == NULL) {
1109 return false;
1110 }
1111
1112 switch (thread->GetState()) {
1113 case Thread::kTerminated: *pThreadStatus = JDWP::TS_ZOMBIE; break;
1114 case Thread::kRunnable: *pThreadStatus = JDWP::TS_RUNNING; break;
1115 case Thread::kTimedWaiting: *pThreadStatus = JDWP::TS_SLEEPING; break;
1116 case Thread::kBlocked: *pThreadStatus = JDWP::TS_MONITOR; break;
1117 case Thread::kWaiting: *pThreadStatus = JDWP::TS_WAIT; break;
1118 case Thread::kInitializing: *pThreadStatus = JDWP::TS_ZOMBIE; break;
1119 case Thread::kStarting: *pThreadStatus = JDWP::TS_ZOMBIE; break;
1120 case Thread::kNative: *pThreadStatus = JDWP::TS_RUNNING; break;
1121 case Thread::kVmWait: *pThreadStatus = JDWP::TS_WAIT; break;
1122 case Thread::kSuspended: *pThreadStatus = JDWP::TS_RUNNING; break;
1123 default:
1124 LOG(FATAL) << "unknown thread state " << thread->GetState();
1125 }
1126
1127 *pSuspendStatus = (thread->IsSuspended() ? JDWP::SUSPEND_STATUS_SUSPENDED : 0);
1128
1129 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001130}
1131
1132uint32_t Dbg::GetThreadSuspendCount(JDWP::ObjectId threadId) {
1133 UNIMPLEMENTED(FATAL);
1134 return 0;
1135}
1136
1137bool Dbg::ThreadExists(JDWP::ObjectId threadId) {
Elliott Hughes761928d2011-11-16 18:33:03 -08001138 return DecodeThread(threadId) != NULL;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001139}
1140
1141bool Dbg::IsSuspended(JDWP::ObjectId threadId) {
Elliott Hughes761928d2011-11-16 18:33:03 -08001142 return DecodeThread(threadId)->IsSuspended();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001143}
1144
1145//void Dbg::WaitForSuspend(JDWP::ObjectId threadId);
1146
Elliott Hughesa2155262011-11-16 16:26:58 -08001147void Dbg::GetThreadGroupThreadsImpl(Object* thread_group, JDWP::ObjectId** ppThreadIds, uint32_t* pThreadCount) {
1148 struct ThreadListVisitor {
1149 static void Visit(Thread* t, void* arg) {
1150 reinterpret_cast<ThreadListVisitor*>(arg)->Visit(t);
1151 }
1152
1153 void Visit(Thread* t) {
1154 if (t == Dbg::GetDebugThread()) {
1155 // Skip the JDWP thread. Some debuggers get bent out of shape when they can't suspend and
1156 // query all threads, so it's easier if we just don't tell them about this thread.
1157 return;
1158 }
1159 if (thread_group == NULL || t->GetThreadGroup() == thread_group) {
1160 threads.push_back(gRegistry->Add(t->GetPeer()));
1161 }
1162 }
1163
1164 Object* thread_group;
1165 std::vector<JDWP::ObjectId> threads;
1166 };
1167
1168 ThreadListVisitor tlv;
1169 tlv.thread_group = thread_group;
1170
1171 {
1172 ScopedThreadListLock thread_list_lock;
1173 Runtime::Current()->GetThreadList()->ForEach(ThreadListVisitor::Visit, &tlv);
1174 }
1175
1176 *pThreadCount = tlv.threads.size();
1177 if (*pThreadCount == 0) {
1178 *ppThreadIds = NULL;
1179 } else {
1180 *ppThreadIds = new JDWP::ObjectId[*pThreadCount];
1181 for (size_t i = 0; i < *pThreadCount; ++i) {
1182 (*ppThreadIds)[i] = tlv.threads[i];
1183 }
1184 }
1185}
1186
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001187void Dbg::GetThreadGroupThreads(JDWP::ObjectId threadGroupId, JDWP::ObjectId** ppThreadIds, uint32_t* pThreadCount) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001188 GetThreadGroupThreadsImpl(gRegistry->Get<Object*>(threadGroupId), ppThreadIds, pThreadCount);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001189}
1190
1191void Dbg::GetAllThreads(JDWP::ObjectId** ppThreadIds, uint32_t* pThreadCount) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001192 GetThreadGroupThreadsImpl(NULL, ppThreadIds, pThreadCount);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001193}
1194
1195int Dbg::GetThreadFrameCount(JDWP::ObjectId threadId) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001196 ScopedThreadListLock thread_list_lock;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001197 struct CountStackDepthVisitor : public Thread::StackVisitor {
1198 CountStackDepthVisitor() : depth(0) {}
Elliott Hughesf8a2df72011-12-01 12:19:54 -08001199 virtual void VisitFrame(const Frame& f, uintptr_t) {
1200 // TODO: we'll need to skip callee-save frames too.
1201 if (f.HasMethod()) {
1202 ++depth;
1203 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001204 }
1205 size_t depth;
1206 };
1207 CountStackDepthVisitor visitor;
1208 DecodeThread(threadId)->WalkStack(&visitor);
1209 return visitor.depth;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001210}
1211
Elliott Hughes03181a82011-11-17 17:22:21 -08001212bool Dbg::GetThreadFrame(JDWP::ObjectId threadId, int desired_frame_number, JDWP::FrameId* pFrameId, JDWP::JdwpLocation* pLoc) {
1213 ScopedThreadListLock thread_list_lock;
1214 struct GetFrameVisitor : public Thread::StackVisitor {
1215 GetFrameVisitor(int desired_frame_number, JDWP::FrameId* pFrameId, JDWP::JdwpLocation* pLoc)
1216 : found(false) ,depth(0), desired_frame_number(desired_frame_number), pFrameId(pFrameId), pLoc(pLoc) {
1217 }
1218 virtual void VisitFrame(const Frame& f, uintptr_t pc) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -08001219 // TODO: we'll need to skip callee-save frames too.
Elliott Hughes03181a82011-11-17 17:22:21 -08001220 if (!f.HasMethod()) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -08001221 return; // The debugger can't do anything useful with a frame that has no Method*.
Elliott Hughes03181a82011-11-17 17:22:21 -08001222 }
1223
1224 if (depth == desired_frame_number) {
1225 *pFrameId = reinterpret_cast<JDWP::FrameId>(f.GetSP());
1226
1227 Method* m = f.GetMethod();
1228 Class* c = m->GetDeclaringClass();
1229
1230 pLoc->typeTag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
1231 pLoc->classId = gRegistry->Add(c);
1232 pLoc->methodId = ToMethodId(m);
1233 pLoc->idx = m->IsNative() ? -1 : m->ToDexPC(pc);
1234
1235 found = true;
1236 }
1237 ++depth;
1238 }
1239 bool found;
1240 int depth;
1241 int desired_frame_number;
1242 JDWP::FrameId* pFrameId;
1243 JDWP::JdwpLocation* pLoc;
1244 };
1245 GetFrameVisitor visitor(desired_frame_number, pFrameId, pLoc);
1246 visitor.desired_frame_number = desired_frame_number;
1247 DecodeThread(threadId)->WalkStack(&visitor);
1248 return visitor.found;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001249}
1250
1251JDWP::ObjectId Dbg::GetThreadSelfId() {
Elliott Hughes475fc232011-10-25 15:00:35 -07001252 return gRegistry->Add(Thread::Current()->GetPeer());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001253}
1254
Elliott Hughes475fc232011-10-25 15:00:35 -07001255void Dbg::SuspendVM() {
Elliott Hughesa2155262011-11-16 16:26:58 -08001256 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 -07001257 Runtime::Current()->GetThreadList()->SuspendAll(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001258}
1259
1260void Dbg::ResumeVM() {
Elliott Hughes475fc232011-10-25 15:00:35 -07001261 Runtime::Current()->GetThreadList()->ResumeAll(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001262}
1263
1264void Dbg::SuspendThread(JDWP::ObjectId threadId) {
Elliott Hughes4e235312011-12-02 11:34:15 -08001265 Object* peer = gRegistry->Get<Object*>(threadId);
1266 ScopedThreadListLock thread_list_lock;
1267 Thread* thread = Thread::FromManagedThread(peer);
1268 if (thread == NULL) {
1269 LOG(WARNING) << "No such thread for suspend: " << peer;
1270 return;
1271 }
1272 Runtime::Current()->GetThreadList()->Suspend(thread, true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001273}
1274
1275void Dbg::ResumeThread(JDWP::ObjectId threadId) {
Elliott Hughes4e235312011-12-02 11:34:15 -08001276 Object* peer = gRegistry->Get<Object*>(threadId);
1277 ScopedThreadListLock thread_list_lock;
1278 Thread* thread = Thread::FromManagedThread(peer);
1279 if (thread == NULL) {
1280 LOG(WARNING) << "No such thread for resume: " << peer;
1281 return;
1282 }
1283 Runtime::Current()->GetThreadList()->Resume(thread, true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001284}
1285
1286void Dbg::SuspendSelf() {
Elliott Hughes475fc232011-10-25 15:00:35 -07001287 Runtime::Current()->GetThreadList()->SuspendSelfForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001288}
1289
1290bool Dbg::GetThisObject(JDWP::ObjectId threadId, JDWP::FrameId frameId, JDWP::ObjectId* pThisId) {
1291 UNIMPLEMENTED(FATAL);
1292 return false;
1293}
1294
Elliott Hughesdbb40792011-11-18 17:05:22 -08001295void Dbg::GetLocalValue(JDWP::ObjectId threadId, JDWP::FrameId frameId, int slot, JDWP::JdwpTag tag, uint8_t* buf, size_t expectedLen) {
1296 Method** sp = reinterpret_cast<Method**>(frameId);
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001297 Frame f;
1298 f.SetSP(sp);
1299 uint16_t reg = DemangleSlot(slot, f);
1300 Method* m = f.GetMethod();
1301
1302 const VmapTable vmap_table(m->GetVmapTableRaw());
1303 uint32_t vmap_offset;
1304 if (vmap_table.IsInContext(reg, vmap_offset)) {
1305 UNIMPLEMENTED(FATAL) << "don't know how to pull locals from callee save frames: " << vmap_offset;
1306 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001307
1308 switch (tag) {
1309 case JDWP::JT_BOOLEAN:
1310 {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001311 CHECK_EQ(expectedLen, 1U);
Elliott Hughes1bba14f2011-12-01 18:00:36 -08001312 uint32_t intVal = f.GetVReg(m, reg);
1313 LOG(VERBOSE) << "get boolean local " << reg << " = " << intVal;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001314 JDWP::Set1(buf+1, intVal != 0);
1315 }
1316 break;
1317 case JDWP::JT_BYTE:
1318 {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001319 CHECK_EQ(expectedLen, 1U);
Elliott Hughes1bba14f2011-12-01 18:00:36 -08001320 uint32_t intVal = f.GetVReg(m, reg);
1321 LOG(VERBOSE) << "get byte local " << reg << " = " << intVal;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001322 JDWP::Set1(buf+1, intVal);
1323 }
1324 break;
1325 case JDWP::JT_SHORT:
1326 case JDWP::JT_CHAR:
1327 {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001328 CHECK_EQ(expectedLen, 2U);
Elliott Hughes1bba14f2011-12-01 18:00:36 -08001329 uint32_t intVal = f.GetVReg(m, reg);
1330 LOG(VERBOSE) << "get short/char local " << reg << " = " << intVal;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001331 JDWP::Set2BE(buf+1, intVal);
1332 }
1333 break;
1334 case JDWP::JT_INT:
1335 case JDWP::JT_FLOAT:
1336 {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001337 CHECK_EQ(expectedLen, 4U);
Elliott Hughes1bba14f2011-12-01 18:00:36 -08001338 uint32_t intVal = f.GetVReg(m, reg);
1339 LOG(VERBOSE) << "get int/float local " << reg << " = " << intVal;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001340 JDWP::Set4BE(buf+1, intVal);
1341 }
1342 break;
1343 case JDWP::JT_ARRAY:
1344 {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001345 CHECK_EQ(expectedLen, sizeof(JDWP::ObjectId));
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001346 Object* o = reinterpret_cast<Object*>(f.GetVReg(m, reg));
Elliott Hughes1bba14f2011-12-01 18:00:36 -08001347 LOG(VERBOSE) << "get array local " << reg << " = " << o;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001348 if (o != NULL && !Heap::IsHeapAddress(o)) {
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001349 LOG(FATAL) << "reg " << reg << " expected to hold array: " << o;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001350 }
1351 JDWP::SetObjectId(buf+1, gRegistry->Add(o));
1352 }
1353 break;
1354 case JDWP::JT_OBJECT:
1355 {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001356 CHECK_EQ(expectedLen, sizeof(JDWP::ObjectId));
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001357 Object* o = reinterpret_cast<Object*>(f.GetVReg(m, reg));
Elliott Hughes1bba14f2011-12-01 18:00:36 -08001358 LOG(VERBOSE) << "get object local " << reg << " = " << o;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001359 if (o != NULL && !Heap::IsHeapAddress(o)) {
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001360 LOG(FATAL) << "reg " << reg << " expected to hold object: " << o;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001361 }
1362 tag = TagFromObject(o);
1363 JDWP::SetObjectId(buf+1, gRegistry->Add(o));
1364 }
1365 break;
1366 case JDWP::JT_DOUBLE:
1367 case JDWP::JT_LONG:
1368 {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001369 CHECK_EQ(expectedLen, 8U);
Elliott Hughes1bba14f2011-12-01 18:00:36 -08001370 uint32_t lo = f.GetVReg(m, reg);
1371 uint64_t hi = f.GetVReg(m, reg + 1);
1372 uint64_t longVal = (hi << 32) | lo;
1373 LOG(VERBOSE) << "get double/long local " << hi << ":" << lo << " = " << longVal;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001374 JDWP::Set8BE(buf+1, longVal);
1375 }
1376 break;
1377 default:
1378 LOG(FATAL) << "unknown tag " << tag;
1379 break;
1380 }
1381
1382 // Prepend tag, which may have been updated.
1383 JDWP::Set1(buf, tag);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001384}
1385
Elliott Hughesdbb40792011-11-18 17:05:22 -08001386void Dbg::SetLocalValue(JDWP::ObjectId threadId, JDWP::FrameId frameId, int slot, JDWP::JdwpTag tag, uint64_t value, size_t width) {
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001387 UNIMPLEMENTED(FATAL);
1388}
1389
1390void Dbg::PostLocationEvent(const Method* method, int pcOffset, Object* thisPtr, int eventFlags) {
1391 UNIMPLEMENTED(FATAL);
1392}
1393
1394void Dbg::PostException(void* throwFp, int throwRelPc, void* catchFp, int catchRelPc, Object* exception) {
1395 UNIMPLEMENTED(FATAL);
1396}
1397
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001398void Dbg::PostClassPrepare(Class* c) {
1399 UNIMPLEMENTED(FATAL);
1400}
1401
1402bool Dbg::WatchLocation(const JDWP::JdwpLocation* pLoc) {
1403 UNIMPLEMENTED(FATAL);
1404 return false;
1405}
1406
1407void Dbg::UnwatchLocation(const JDWP::JdwpLocation* pLoc) {
1408 UNIMPLEMENTED(FATAL);
1409}
1410
1411bool Dbg::ConfigureStep(JDWP::ObjectId threadId, JDWP::JdwpStepSize size, JDWP::JdwpStepDepth depth) {
1412 UNIMPLEMENTED(FATAL);
1413 return false;
1414}
1415
1416void Dbg::UnconfigureStep(JDWP::ObjectId threadId) {
1417 UNIMPLEMENTED(FATAL);
1418}
1419
Elliott Hughesaed4be92011-12-02 16:16:23 -08001420JDWP::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* pExceptObj) {
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001421 UNIMPLEMENTED(FATAL);
1422 return JDWP::ERR_NONE;
1423}
1424
1425void Dbg::ExecuteMethod(DebugInvokeReq* pReq) {
1426 UNIMPLEMENTED(FATAL);
1427}
1428
1429void Dbg::RegisterObjectId(JDWP::ObjectId id) {
1430 UNIMPLEMENTED(FATAL);
1431}
1432
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001433/*
1434 * "buf" contains a full JDWP packet, possibly with multiple chunks. We
1435 * need to process each, accumulate the replies, and ship the whole thing
1436 * back.
1437 *
1438 * Returns "true" if we have a reply. The reply buffer is newly allocated,
1439 * and includes the chunk type/length, followed by the data.
1440 *
1441 * TODO: we currently assume that the request and reply include a single
1442 * chunk. If this becomes inconvenient we will need to adapt.
1443 */
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001444bool Dbg::DdmHandlePacket(const uint8_t* buf, int dataLen, uint8_t** pReplyBuf, int* pReplyLen) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001445 CHECK_GE(dataLen, 0);
1446
1447 Thread* self = Thread::Current();
1448 JNIEnv* env = self->GetJniEnv();
1449
1450 static jclass Chunk_class = env->FindClass("org/apache/harmony/dalvik/ddmc/Chunk");
1451 static jclass DdmServer_class = env->FindClass("org/apache/harmony/dalvik/ddmc/DdmServer");
1452 static jmethodID dispatch_mid = env->GetStaticMethodID(DdmServer_class, "dispatch",
1453 "(I[BII)Lorg/apache/harmony/dalvik/ddmc/Chunk;");
1454 static jfieldID data_fid = env->GetFieldID(Chunk_class, "data", "[B");
1455 static jfieldID length_fid = env->GetFieldID(Chunk_class, "length", "I");
1456 static jfieldID offset_fid = env->GetFieldID(Chunk_class, "offset", "I");
1457 static jfieldID type_fid = env->GetFieldID(Chunk_class, "type", "I");
1458
1459 // Create a byte[] corresponding to 'buf'.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001460 ScopedLocalRef<jbyteArray> dataArray(env, env->NewByteArray(dataLen));
1461 if (dataArray.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001462 LOG(WARNING) << "byte[] allocation failed: " << dataLen;
1463 env->ExceptionClear();
1464 return false;
1465 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001466 env->SetByteArrayRegion(dataArray.get(), 0, dataLen, reinterpret_cast<const jbyte*>(buf));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001467
1468 const int kChunkHdrLen = 8;
1469
1470 // Run through and find all chunks. [Currently just find the first.]
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001471 ScopedByteArrayRO contents(env, dataArray.get());
Elliott Hughesf7c3b662011-10-27 12:04:56 -07001472 jint type = JDWP::Get4BE(reinterpret_cast<const uint8_t*>(&contents[0]));
1473 jint length = JDWP::Get4BE(reinterpret_cast<const uint8_t*>(&contents[4]));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001474 jint offset = kChunkHdrLen;
1475 if (offset + length > dataLen) {
1476 LOG(WARNING) << StringPrintf("bad chunk found (len=%u pktLen=%d)", length, dataLen);
1477 return false;
1478 }
1479
1480 // Call "private static Chunk dispatch(int type, byte[] data, int offset, int length)".
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001481 ScopedLocalRef<jobject> chunk(env, env->CallStaticObjectMethod(DdmServer_class, dispatch_mid, type, dataArray.get(), offset, length));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001482 if (env->ExceptionCheck()) {
1483 LOG(INFO) << StringPrintf("Exception thrown by dispatcher for 0x%08x", type);
1484 env->ExceptionDescribe();
1485 env->ExceptionClear();
1486 return false;
1487 }
1488
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001489 if (chunk.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001490 return false;
1491 }
1492
1493 /*
1494 * Pull the pieces out of the chunk. We copy the results into a
1495 * newly-allocated buffer that the caller can free. We don't want to
1496 * continue using the Chunk object because nothing has a reference to it.
1497 *
1498 * We could avoid this by returning type/data/offset/length and having
1499 * the caller be aware of the object lifetime issues, but that
1500 * integrates the JDWP code more tightly into the VM, and doesn't work
1501 * if we have responses for multiple chunks.
1502 *
1503 * So we're pretty much stuck with copying data around multiple times.
1504 */
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001505 ScopedLocalRef<jbyteArray> replyData(env, reinterpret_cast<jbyteArray>(env->GetObjectField(chunk.get(), data_fid)));
1506 length = env->GetIntField(chunk.get(), length_fid);
1507 offset = env->GetIntField(chunk.get(), offset_fid);
1508 type = env->GetIntField(chunk.get(), type_fid);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001509
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001510 LOG(VERBOSE) << StringPrintf("DDM reply: type=0x%08x data=%p offset=%d length=%d", type, replyData.get(), offset, length);
1511 if (length == 0 || replyData.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001512 return false;
1513 }
1514
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001515 jsize replyLength = env->GetArrayLength(replyData.get());
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001516 if (offset + length > replyLength) {
1517 LOG(WARNING) << StringPrintf("chunk off=%d len=%d exceeds reply array len %d", offset, length, replyLength);
1518 return false;
1519 }
1520
1521 uint8_t* reply = new uint8_t[length + kChunkHdrLen];
1522 if (reply == NULL) {
1523 LOG(WARNING) << "malloc failed: " << (length + kChunkHdrLen);
1524 return false;
1525 }
Elliott Hughesf7c3b662011-10-27 12:04:56 -07001526 JDWP::Set4BE(reply + 0, type);
1527 JDWP::Set4BE(reply + 4, length);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001528 env->GetByteArrayRegion(replyData.get(), offset, length, reinterpret_cast<jbyte*>(reply + kChunkHdrLen));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001529
1530 *pReplyBuf = reply;
1531 *pReplyLen = length + kChunkHdrLen;
1532
1533 LOG(VERBOSE) << StringPrintf("dvmHandleDdm returning type=%.4s buf=%p len=%d", (char*) reply, reply, length);
1534 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001535}
1536
Elliott Hughesa2155262011-11-16 16:26:58 -08001537void Dbg::DdmBroadcast(bool connect) {
Elliott Hughes47fce012011-10-25 18:37:19 -07001538 LOG(VERBOSE) << "Broadcasting DDM " << (connect ? "connect" : "disconnect") << "...";
1539
1540 Thread* self = Thread::Current();
1541 if (self->GetState() != Thread::kRunnable) {
1542 LOG(ERROR) << "DDM broadcast in thread state " << self->GetState();
1543 /* try anyway? */
1544 }
1545
1546 JNIEnv* env = self->GetJniEnv();
1547 static jclass DdmServer_class = env->FindClass("org/apache/harmony/dalvik/ddmc/DdmServer");
1548 static jmethodID broadcast_mid = env->GetStaticMethodID(DdmServer_class, "broadcast", "(I)V");
1549 jint event = connect ? 1 /*DdmServer.CONNECTED*/ : 2 /*DdmServer.DISCONNECTED*/;
1550 env->CallStaticVoidMethod(DdmServer_class, broadcast_mid, event);
1551 if (env->ExceptionCheck()) {
1552 LOG(ERROR) << "DdmServer.broadcast " << event << " failed";
1553 env->ExceptionDescribe();
1554 env->ExceptionClear();
1555 }
1556}
1557
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001558void Dbg::DdmConnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08001559 Dbg::DdmBroadcast(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001560}
1561
1562void Dbg::DdmDisconnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08001563 Dbg::DdmBroadcast(false);
Elliott Hughes47fce012011-10-25 18:37:19 -07001564 gDdmThreadNotification = false;
1565}
1566
1567/*
Elliott Hughes82188472011-11-07 18:11:48 -08001568 * Send a notification when a thread starts, stops, or changes its name.
Elliott Hughes47fce012011-10-25 18:37:19 -07001569 *
1570 * Because we broadcast the full set of threads when the notifications are
1571 * first enabled, it's possible for "thread" to be actively executing.
1572 */
Elliott Hughes82188472011-11-07 18:11:48 -08001573void Dbg::DdmSendThreadNotification(Thread* t, uint32_t type) {
Elliott Hughes47fce012011-10-25 18:37:19 -07001574 if (!gDdmThreadNotification) {
1575 return;
1576 }
1577
Elliott Hughes82188472011-11-07 18:11:48 -08001578 if (type == CHUNK_TYPE("THDE")) {
Elliott Hughes47fce012011-10-25 18:37:19 -07001579 uint8_t buf[4];
Elliott Hughesf7c3b662011-10-27 12:04:56 -07001580 JDWP::Set4BE(&buf[0], t->GetThinLockId());
Elliott Hughes47fce012011-10-25 18:37:19 -07001581 Dbg::DdmSendChunk(CHUNK_TYPE("THDE"), 4, buf);
Elliott Hughes82188472011-11-07 18:11:48 -08001582 } else {
1583 CHECK(type == CHUNK_TYPE("THCR") || type == CHUNK_TYPE("THNM")) << type;
1584 SirtRef<String> name(t->GetName());
1585 size_t char_count = (name.get() != NULL) ? name->GetLength() : 0;
1586 const jchar* chars = name->GetCharArray()->GetData();
1587
Elliott Hughes21f32d72011-11-09 17:44:13 -08001588 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08001589 JDWP::Append4BE(bytes, t->GetThinLockId());
1590 JDWP::AppendUtf16BE(bytes, chars, char_count);
Elliott Hughes21f32d72011-11-09 17:44:13 -08001591 CHECK_EQ(bytes.size(), char_count*2 + sizeof(uint32_t)*2);
1592 Dbg::DdmSendChunk(type, bytes);
Elliott Hughes47fce012011-10-25 18:37:19 -07001593 }
1594}
1595
Elliott Hughesa2155262011-11-16 16:26:58 -08001596static void DdmSendThreadStartCallback(Thread* t, void*) {
Elliott Hughes82188472011-11-07 18:11:48 -08001597 Dbg::DdmSendThreadNotification(t, CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07001598}
1599
1600void Dbg::DdmSetThreadNotification(bool enable) {
1601 // We lock the thread list to avoid sending duplicate events or missing
1602 // a thread change. We should be okay holding this lock while sending
1603 // the messages out. (We have to hold it while accessing a live thread.)
Elliott Hughesbbd9d832011-11-07 14:40:00 -08001604 ScopedThreadListLock thread_list_lock;
Elliott Hughes47fce012011-10-25 18:37:19 -07001605
1606 gDdmThreadNotification = enable;
1607 if (enable) {
Elliott Hughesbfe487b2011-10-26 15:48:55 -07001608 Runtime::Current()->GetThreadList()->ForEach(DdmSendThreadStartCallback, NULL);
Elliott Hughes47fce012011-10-25 18:37:19 -07001609 }
1610}
1611
Elliott Hughesa2155262011-11-16 16:26:58 -08001612void Dbg::PostThreadStartOrStop(Thread* t, uint32_t type) {
Elliott Hughes47fce012011-10-25 18:37:19 -07001613 if (gDebuggerActive) {
1614 JDWP::ObjectId id = gRegistry->Add(t->GetPeer());
Elliott Hughes82188472011-11-07 18:11:48 -08001615 gJdwpState->PostThreadChange(id, type == CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07001616 }
Elliott Hughes82188472011-11-07 18:11:48 -08001617 Dbg::DdmSendThreadNotification(t, type);
Elliott Hughes47fce012011-10-25 18:37:19 -07001618}
1619
1620void Dbg::PostThreadStart(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001621 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07001622}
1623
1624void Dbg::PostThreadDeath(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001625 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THDE"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001626}
1627
Elliott Hughes82188472011-11-07 18:11:48 -08001628void Dbg::DdmSendChunk(uint32_t type, size_t byte_count, const uint8_t* buf) {
Elliott Hughes3bb81562011-10-21 18:52:59 -07001629 CHECK(buf != NULL);
1630 iovec vec[1];
1631 vec[0].iov_base = reinterpret_cast<void*>(const_cast<uint8_t*>(buf));
1632 vec[0].iov_len = byte_count;
1633 Dbg::DdmSendChunkV(type, vec, 1);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001634}
1635
Elliott Hughes21f32d72011-11-09 17:44:13 -08001636void Dbg::DdmSendChunk(uint32_t type, const std::vector<uint8_t>& bytes) {
1637 DdmSendChunk(type, bytes.size(), &bytes[0]);
1638}
1639
Elliott Hughes82188472011-11-07 18:11:48 -08001640void Dbg::DdmSendChunkV(uint32_t type, const struct iovec* iov, int iovcnt) {
Elliott Hughes3bb81562011-10-21 18:52:59 -07001641 if (gJdwpState == NULL) {
1642 LOG(VERBOSE) << "Debugger thread not active, ignoring DDM send: " << type;
1643 } else {
Elliott Hughes376a7a02011-10-24 18:35:55 -07001644 gJdwpState->DdmSendChunkV(type, iov, iovcnt);
Elliott Hughes3bb81562011-10-21 18:52:59 -07001645 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001646}
1647
Elliott Hughes767a1472011-10-26 18:49:02 -07001648int Dbg::DdmHandleHpifChunk(HpifWhen when) {
1649 if (when == HPIF_WHEN_NOW) {
Elliott Hughes7162ad92011-10-27 14:08:42 -07001650 DdmSendHeapInfo(when);
Elliott Hughes767a1472011-10-26 18:49:02 -07001651 return true;
1652 }
1653
1654 if (when != HPIF_WHEN_NEVER && when != HPIF_WHEN_NEXT_GC && when != HPIF_WHEN_EVERY_GC) {
1655 LOG(ERROR) << "invalid HpifWhen value: " << static_cast<int>(when);
1656 return false;
1657 }
1658
1659 gDdmHpifWhen = when;
1660 return true;
1661}
1662
1663bool Dbg::DdmHandleHpsgNhsgChunk(Dbg::HpsgWhen when, Dbg::HpsgWhat what, bool native) {
1664 if (when != HPSG_WHEN_NEVER && when != HPSG_WHEN_EVERY_GC) {
1665 LOG(ERROR) << "invalid HpsgWhen value: " << static_cast<int>(when);
1666 return false;
1667 }
1668
1669 if (what != HPSG_WHAT_MERGED_OBJECTS && what != HPSG_WHAT_DISTINCT_OBJECTS) {
1670 LOG(ERROR) << "invalid HpsgWhat value: " << static_cast<int>(what);
1671 return false;
1672 }
1673
1674 if (native) {
1675 gDdmNhsgWhen = when;
1676 gDdmNhsgWhat = what;
1677 } else {
1678 gDdmHpsgWhen = when;
1679 gDdmHpsgWhat = what;
1680 }
1681 return true;
1682}
1683
Elliott Hughes7162ad92011-10-27 14:08:42 -07001684void Dbg::DdmSendHeapInfo(HpifWhen reason) {
1685 // If there's a one-shot 'when', reset it.
1686 if (reason == gDdmHpifWhen) {
1687 if (gDdmHpifWhen == HPIF_WHEN_NEXT_GC) {
1688 gDdmHpifWhen = HPIF_WHEN_NEVER;
1689 }
1690 }
1691
1692 /*
1693 * Chunk HPIF (client --> server)
1694 *
1695 * Heap Info. General information about the heap,
1696 * suitable for a summary display.
1697 *
1698 * [u4]: number of heaps
1699 *
1700 * For each heap:
1701 * [u4]: heap ID
1702 * [u8]: timestamp in ms since Unix epoch
1703 * [u1]: capture reason (same as 'when' value from server)
1704 * [u4]: max heap size in bytes (-Xmx)
1705 * [u4]: current heap size in bytes
1706 * [u4]: current number of bytes allocated
1707 * [u4]: current number of objects allocated
1708 */
1709 uint8_t heap_count = 1;
Elliott Hughes21f32d72011-11-09 17:44:13 -08001710 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08001711 JDWP::Append4BE(bytes, heap_count);
1712 JDWP::Append4BE(bytes, 1); // Heap id (bogus; we only have one heap).
1713 JDWP::Append8BE(bytes, MilliTime());
1714 JDWP::Append1BE(bytes, reason);
1715 JDWP::Append4BE(bytes, Heap::GetMaxMemory()); // Max allowed heap size in bytes.
1716 JDWP::Append4BE(bytes, Heap::GetTotalMemory()); // Current heap size in bytes.
1717 JDWP::Append4BE(bytes, Heap::GetBytesAllocated());
1718 JDWP::Append4BE(bytes, Heap::GetObjectsAllocated());
Elliott Hughes21f32d72011-11-09 17:44:13 -08001719 CHECK_EQ(bytes.size(), 4U + (heap_count * (4 + 8 + 1 + 4 + 4 + 4 + 4)));
1720 Dbg::DdmSendChunk(CHUNK_TYPE("HPIF"), bytes);
Elliott Hughes767a1472011-10-26 18:49:02 -07001721}
1722
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001723enum HpsgSolidity {
1724 SOLIDITY_FREE = 0,
1725 SOLIDITY_HARD = 1,
1726 SOLIDITY_SOFT = 2,
1727 SOLIDITY_WEAK = 3,
1728 SOLIDITY_PHANTOM = 4,
1729 SOLIDITY_FINALIZABLE = 5,
1730 SOLIDITY_SWEEP = 6,
1731};
1732
1733enum HpsgKind {
1734 KIND_OBJECT = 0,
1735 KIND_CLASS_OBJECT = 1,
1736 KIND_ARRAY_1 = 2,
1737 KIND_ARRAY_2 = 3,
1738 KIND_ARRAY_4 = 4,
1739 KIND_ARRAY_8 = 5,
1740 KIND_UNKNOWN = 6,
1741 KIND_NATIVE = 7,
1742};
1743
1744#define HPSG_PARTIAL (1<<7)
1745#define HPSG_STATE(solidity, kind) ((uint8_t)((((kind) & 0x7) << 3) | ((solidity) & 0x7)))
1746
1747struct HeapChunkContext {
1748 std::vector<uint8_t> buf;
1749 uint8_t* p;
1750 uint8_t* pieceLenField;
1751 size_t totalAllocationUnits;
Elliott Hughes82188472011-11-07 18:11:48 -08001752 uint32_t type;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001753 bool merge;
1754 bool needHeader;
1755
1756 // Maximum chunk size. Obtain this from the formula:
1757 // (((maximum_heap_size / ALLOCATION_UNIT_SIZE) + 255) / 256) * 2
1758 HeapChunkContext(bool merge, bool native)
1759 : buf(16384 - 16),
1760 type(0),
1761 merge(merge) {
1762 Reset();
1763 if (native) {
1764 type = CHUNK_TYPE("NHSG");
1765 } else {
1766 type = merge ? CHUNK_TYPE("HPSG") : CHUNK_TYPE("HPSO");
1767 }
1768 }
1769
1770 ~HeapChunkContext() {
1771 if (p > &buf[0]) {
1772 Flush();
1773 }
1774 }
1775
1776 void EnsureHeader(const void* chunk_ptr) {
1777 if (!needHeader) {
1778 return;
1779 }
1780
1781 // Start a new HPSx chunk.
1782 JDWP::Write4BE(&p, 1); // Heap id (bogus; we only have one heap).
1783 JDWP::Write1BE(&p, 8); // Size of allocation unit, in bytes.
1784
1785 JDWP::Write4BE(&p, reinterpret_cast<uintptr_t>(chunk_ptr)); // virtual address of segment start.
1786 JDWP::Write4BE(&p, 0); // offset of this piece (relative to the virtual address).
1787 // [u4]: length of piece, in allocation units
1788 // We won't know this until we're done, so save the offset and stuff in a dummy value.
1789 pieceLenField = p;
1790 JDWP::Write4BE(&p, 0x55555555);
1791 needHeader = false;
1792 }
1793
1794 void Flush() {
1795 // Patch the "length of piece" field.
1796 CHECK_LE(&buf[0], pieceLenField);
1797 CHECK_LE(pieceLenField, p);
1798 JDWP::Set4BE(pieceLenField, totalAllocationUnits);
1799
1800 Dbg::DdmSendChunk(type, p - &buf[0], &buf[0]);
1801 Reset();
1802 }
1803
Elliott Hughesa2155262011-11-16 16:26:58 -08001804 static void HeapChunkCallback(const void* chunk_ptr, size_t chunk_len, const void* user_ptr, size_t user_len, void* arg) {
1805 reinterpret_cast<HeapChunkContext*>(arg)->HeapChunkCallback(chunk_ptr, chunk_len, user_ptr, user_len);
1806 }
1807
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001808 private:
Elliott Hughesa2155262011-11-16 16:26:58 -08001809 enum { ALLOCATION_UNIT_SIZE = 8 };
1810
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001811 void Reset() {
1812 p = &buf[0];
1813 totalAllocationUnits = 0;
1814 needHeader = true;
1815 pieceLenField = NULL;
1816 }
1817
Elliott Hughesa2155262011-11-16 16:26:58 -08001818 void HeapChunkCallback(const void* chunk_ptr, size_t chunk_len, const void* user_ptr, size_t user_len) {
1819 CHECK_EQ((chunk_len & (ALLOCATION_UNIT_SIZE-1)), 0U);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001820
Elliott Hughesa2155262011-11-16 16:26:58 -08001821 /* Make sure there's enough room left in the buffer.
1822 * We need to use two bytes for every fractional 256
1823 * allocation units used by the chunk.
1824 */
1825 {
1826 size_t needed = (((chunk_len/ALLOCATION_UNIT_SIZE + 255) / 256) * 2);
1827 size_t bytesLeft = buf.size() - (size_t)(p - &buf[0]);
1828 if (bytesLeft < needed) {
1829 Flush();
1830 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001831
Elliott Hughesa2155262011-11-16 16:26:58 -08001832 bytesLeft = buf.size() - (size_t)(p - &buf[0]);
1833 if (bytesLeft < needed) {
1834 LOG(WARNING) << "chunk is too big to transmit (chunk_len=" << chunk_len << ", " << needed << " bytes)";
1835 return;
1836 }
1837 }
1838
1839 // OLD-TODO: notice when there's a gap and start a new heap, or at least a new range.
1840 EnsureHeader(chunk_ptr);
1841
1842 // Determine the type of this chunk.
1843 // OLD-TODO: if context.merge, see if this chunk is different from the last chunk.
1844 // If it's the same, we should combine them.
1845 uint8_t state = ExamineObject(reinterpret_cast<const Object*>(user_ptr), (type == CHUNK_TYPE("NHSG")));
1846
1847 // Write out the chunk description.
1848 chunk_len /= ALLOCATION_UNIT_SIZE; // convert to allocation units
1849 totalAllocationUnits += chunk_len;
1850 while (chunk_len > 256) {
1851 *p++ = state | HPSG_PARTIAL;
1852 *p++ = 255; // length - 1
1853 chunk_len -= 256;
1854 }
1855 *p++ = state;
1856 *p++ = chunk_len - 1;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001857 }
1858
Elliott Hughesa2155262011-11-16 16:26:58 -08001859 uint8_t ExamineObject(const Object* o, bool is_native_heap) {
1860 if (o == NULL) {
1861 return HPSG_STATE(SOLIDITY_FREE, 0);
1862 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001863
Elliott Hughesa2155262011-11-16 16:26:58 -08001864 // It's an allocated chunk. Figure out what it is.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001865
Elliott Hughesa2155262011-11-16 16:26:58 -08001866 // If we're looking at the native heap, we'll just return
1867 // (SOLIDITY_HARD, KIND_NATIVE) for all allocated chunks.
1868 if (is_native_heap || !Heap::IsLiveObjectLocked(o)) {
1869 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
1870 }
1871
1872 Class* c = o->GetClass();
1873 if (c == NULL) {
1874 // The object was probably just created but hasn't been initialized yet.
1875 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
1876 }
1877
1878 if (!Heap::IsHeapAddress(c)) {
1879 LOG(WARNING) << "invalid class for managed heap object: " << o << " " << c;
1880 return HPSG_STATE(SOLIDITY_HARD, KIND_UNKNOWN);
1881 }
1882
1883 if (c->IsClassClass()) {
1884 return HPSG_STATE(SOLIDITY_HARD, KIND_CLASS_OBJECT);
1885 }
1886
1887 if (c->IsArrayClass()) {
1888 if (o->IsObjectArray()) {
1889 return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
1890 }
1891 switch (c->GetComponentSize()) {
1892 case 1: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_1);
1893 case 2: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_2);
1894 case 4: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
1895 case 8: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_8);
1896 }
1897 }
1898
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001899 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
1900 }
1901
Elliott Hughesa2155262011-11-16 16:26:58 -08001902 DISALLOW_COPY_AND_ASSIGN(HeapChunkContext);
1903};
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001904
1905void Dbg::DdmSendHeapSegments(bool native) {
1906 Dbg::HpsgWhen when;
1907 Dbg::HpsgWhat what;
1908 if (!native) {
1909 when = gDdmHpsgWhen;
1910 what = gDdmHpsgWhat;
1911 } else {
1912 when = gDdmNhsgWhen;
1913 what = gDdmNhsgWhat;
1914 }
1915 if (when == HPSG_WHEN_NEVER) {
1916 return;
1917 }
1918
1919 // Figure out what kind of chunks we'll be sending.
1920 CHECK(what == HPSG_WHAT_MERGED_OBJECTS || what == HPSG_WHAT_DISTINCT_OBJECTS) << static_cast<int>(what);
1921
1922 // First, send a heap start chunk.
1923 uint8_t heap_id[4];
1924 JDWP::Set4BE(&heap_id[0], 1); // Heap id (bogus; we only have one heap).
1925 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHST") : CHUNK_TYPE("HPST"), sizeof(heap_id), heap_id);
1926
1927 // Send a series of heap segment chunks.
Elliott Hughesa2155262011-11-16 16:26:58 -08001928 HeapChunkContext context((what == HPSG_WHAT_MERGED_OBJECTS), native);
1929 if (native) {
1930 dlmalloc_walk_heap(HeapChunkContext::HeapChunkCallback, &context);
1931 } else {
1932 Heap::WalkHeap(HeapChunkContext::HeapChunkCallback, &context);
1933 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001934
1935 // Finally, send a heap end chunk.
1936 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHEN") : CHUNK_TYPE("HPEN"), sizeof(heap_id), heap_id);
Elliott Hughes767a1472011-10-26 18:49:02 -07001937}
1938
Elliott Hughes545a0642011-11-08 19:10:03 -08001939void Dbg::SetAllocTrackingEnabled(bool enabled) {
1940 MutexLock mu(gAllocTrackerLock);
1941 if (enabled) {
1942 if (recent_allocation_records_ == NULL) {
1943 LOG(INFO) << "Enabling alloc tracker (" << kNumAllocRecords << " entries, "
1944 << kMaxAllocRecordStackDepth << " frames --> "
1945 << (sizeof(AllocRecord) * kNumAllocRecords) << " bytes)";
1946 gAllocRecordHead = gAllocRecordCount = 0;
1947 recent_allocation_records_ = new AllocRecord[kNumAllocRecords];
1948 CHECK(recent_allocation_records_ != NULL);
1949 }
1950 } else {
1951 delete[] recent_allocation_records_;
1952 recent_allocation_records_ = NULL;
1953 }
1954}
1955
1956struct AllocRecordStackVisitor : public Thread::StackVisitor {
1957 AllocRecordStackVisitor(AllocRecord* record) : record(record), depth(0) {
1958 }
1959
1960 virtual void VisitFrame(const Frame& f, uintptr_t pc) {
1961 if (depth >= kMaxAllocRecordStackDepth) {
1962 return;
1963 }
1964 Method* m = f.GetMethod();
1965 if (m == NULL || m->IsCalleeSaveMethod()) {
1966 return;
1967 }
1968 record->stack[depth].method = m;
1969 record->stack[depth].raw_pc = pc;
1970 ++depth;
1971 }
1972
1973 ~AllocRecordStackVisitor() {
1974 // Clear out any unused stack trace elements.
1975 for (; depth < kMaxAllocRecordStackDepth; ++depth) {
1976 record->stack[depth].method = NULL;
1977 record->stack[depth].raw_pc = 0;
1978 }
1979 }
1980
1981 AllocRecord* record;
1982 size_t depth;
1983};
1984
1985void Dbg::RecordAllocation(Class* type, size_t byte_count) {
1986 Thread* self = Thread::Current();
1987 CHECK(self != NULL);
1988
1989 MutexLock mu(gAllocTrackerLock);
1990 if (recent_allocation_records_ == NULL) {
1991 return;
1992 }
1993
1994 // Advance and clip.
1995 if (++gAllocRecordHead == kNumAllocRecords) {
1996 gAllocRecordHead = 0;
1997 }
1998
1999 // Fill in the basics.
2000 AllocRecord* record = &recent_allocation_records_[gAllocRecordHead];
2001 record->type = type;
2002 record->byte_count = byte_count;
2003 record->thin_lock_id = self->GetThinLockId();
2004
2005 // Fill in the stack trace.
2006 AllocRecordStackVisitor visitor(record);
2007 self->WalkStack(&visitor);
2008
2009 if (gAllocRecordCount < kNumAllocRecords) {
2010 ++gAllocRecordCount;
2011 }
2012}
2013
2014/*
2015 * Return the index of the head element.
2016 *
2017 * We point at the most-recently-written record, so if allocRecordCount is 1
2018 * we want to use the current element. Take "head+1" and subtract count
2019 * from it.
2020 *
2021 * We need to handle underflow in our circular buffer, so we add
2022 * kNumAllocRecords and then mask it back down.
2023 */
2024inline static int headIndex() {
2025 return (gAllocRecordHead+1 + kNumAllocRecords - gAllocRecordCount) & (kNumAllocRecords-1);
2026}
2027
2028void Dbg::DumpRecentAllocations() {
2029 MutexLock mu(gAllocTrackerLock);
2030 if (recent_allocation_records_ == NULL) {
2031 LOG(INFO) << "Not recording tracked allocations";
2032 return;
2033 }
2034
2035 // "i" is the head of the list. We want to start at the end of the
2036 // list and move forward to the tail.
2037 size_t i = headIndex();
2038 size_t count = gAllocRecordCount;
2039
2040 LOG(INFO) << "Tracked allocations, (head=" << gAllocRecordHead << " count=" << count << ")";
2041 while (count--) {
2042 AllocRecord* record = &recent_allocation_records_[i];
2043
2044 LOG(INFO) << StringPrintf(" T=%-2d %6d ", record->thin_lock_id, record->byte_count)
2045 << PrettyClass(record->type);
2046
2047 for (size_t stack_frame = 0; stack_frame < kMaxAllocRecordStackDepth; ++stack_frame) {
2048 const Method* m = record->stack[stack_frame].method;
2049 if (m == NULL) {
2050 break;
2051 }
2052 LOG(INFO) << " " << PrettyMethod(m) << " line " << record->stack[stack_frame].LineNumber();
2053 }
2054
2055 // pause periodically to help logcat catch up
2056 if ((count % 5) == 0) {
2057 usleep(40000);
2058 }
2059
2060 i = (i + 1) & (kNumAllocRecords-1);
2061 }
2062}
2063
2064class StringTable {
2065 public:
2066 StringTable() {
2067 }
2068
2069 void Add(const String* s) {
2070 table_.insert(s);
2071 }
2072
2073 size_t IndexOf(const String* s) {
2074 return std::distance(table_.begin(), table_.find(s));
2075 }
2076
2077 size_t Size() {
2078 return table_.size();
2079 }
2080
2081 void WriteTo(std::vector<uint8_t>& bytes) {
2082 typedef std::set<const String*>::const_iterator It; // TODO: C++0x auto
2083 for (It it = table_.begin(); it != table_.end(); ++it) {
2084 const String* s = *it;
2085 JDWP::AppendUtf16BE(bytes, s->GetCharArray()->GetData(), s->GetLength());
2086 }
2087 }
2088
2089 private:
2090 std::set<const String*> table_;
2091 DISALLOW_COPY_AND_ASSIGN(StringTable);
2092};
2093
2094/*
2095 * The data we send to DDMS contains everything we have recorded.
2096 *
2097 * Message header (all values big-endian):
2098 * (1b) message header len (to allow future expansion); includes itself
2099 * (1b) entry header len
2100 * (1b) stack frame len
2101 * (2b) number of entries
2102 * (4b) offset to string table from start of message
2103 * (2b) number of class name strings
2104 * (2b) number of method name strings
2105 * (2b) number of source file name strings
2106 * For each entry:
2107 * (4b) total allocation size
2108 * (2b) threadId
2109 * (2b) allocated object's class name index
2110 * (1b) stack depth
2111 * For each stack frame:
2112 * (2b) method's class name
2113 * (2b) method name
2114 * (2b) method source file
2115 * (2b) line number, clipped to 32767; -2 if native; -1 if no source
2116 * (xb) class name strings
2117 * (xb) method name strings
2118 * (xb) source file strings
2119 *
2120 * As with other DDM traffic, strings are sent as a 4-byte length
2121 * followed by UTF-16 data.
2122 *
2123 * We send up 16-bit unsigned indexes into string tables. In theory there
2124 * can be (kMaxAllocRecordStackDepth * kNumAllocRecords) unique strings in
2125 * each table, but in practice there should be far fewer.
2126 *
2127 * The chief reason for using a string table here is to keep the size of
2128 * the DDMS message to a minimum. This is partly to make the protocol
2129 * efficient, but also because we have to form the whole thing up all at
2130 * once in a memory buffer.
2131 *
2132 * We use separate string tables for class names, method names, and source
2133 * files to keep the indexes small. There will generally be no overlap
2134 * between the contents of these tables.
2135 */
2136jbyteArray Dbg::GetRecentAllocations() {
2137 if (false) {
2138 DumpRecentAllocations();
2139 }
2140
2141 MutexLock mu(gAllocTrackerLock);
2142
2143 /*
2144 * Part 1: generate string tables.
2145 */
2146 StringTable class_names;
2147 StringTable method_names;
2148 StringTable filenames;
2149
2150 int count = gAllocRecordCount;
2151 int idx = headIndex();
2152 while (count--) {
2153 AllocRecord* record = &recent_allocation_records_[idx];
2154
2155 class_names.Add(record->type->GetDescriptor());
2156
2157 for (size_t i = 0; i < kMaxAllocRecordStackDepth; i++) {
2158 const Method* m = record->stack[i].method;
2159 if (m != NULL) {
2160 class_names.Add(m->GetDeclaringClass()->GetDescriptor());
2161 method_names.Add(m->GetName());
2162 filenames.Add(m->GetDeclaringClass()->GetSourceFile());
2163 }
2164 }
2165
2166 idx = (idx + 1) & (kNumAllocRecords-1);
2167 }
2168
2169 LOG(INFO) << "allocation records: " << gAllocRecordCount;
2170
2171 /*
2172 * Part 2: allocate a buffer and generate the output.
2173 */
2174 std::vector<uint8_t> bytes;
2175
2176 // (1b) message header len (to allow future expansion); includes itself
2177 // (1b) entry header len
2178 // (1b) stack frame len
2179 const int kMessageHeaderLen = 15;
2180 const int kEntryHeaderLen = 9;
2181 const int kStackFrameLen = 8;
2182 JDWP::Append1BE(bytes, kMessageHeaderLen);
2183 JDWP::Append1BE(bytes, kEntryHeaderLen);
2184 JDWP::Append1BE(bytes, kStackFrameLen);
2185
2186 // (2b) number of entries
2187 // (4b) offset to string table from start of message
2188 // (2b) number of class name strings
2189 // (2b) number of method name strings
2190 // (2b) number of source file name strings
2191 JDWP::Append2BE(bytes, gAllocRecordCount);
2192 size_t string_table_offset = bytes.size();
2193 JDWP::Append4BE(bytes, 0); // We'll patch this later...
2194 JDWP::Append2BE(bytes, class_names.Size());
2195 JDWP::Append2BE(bytes, method_names.Size());
2196 JDWP::Append2BE(bytes, filenames.Size());
2197
2198 count = gAllocRecordCount;
2199 idx = headIndex();
2200 while (count--) {
2201 // For each entry:
2202 // (4b) total allocation size
2203 // (2b) thread id
2204 // (2b) allocated object's class name index
2205 // (1b) stack depth
2206 AllocRecord* record = &recent_allocation_records_[idx];
2207 size_t stack_depth = record->GetDepth();
2208 JDWP::Append4BE(bytes, record->byte_count);
2209 JDWP::Append2BE(bytes, record->thin_lock_id);
2210 JDWP::Append2BE(bytes, class_names.IndexOf(record->type->GetDescriptor()));
2211 JDWP::Append1BE(bytes, stack_depth);
2212
2213 for (size_t stack_frame = 0; stack_frame < stack_depth; ++stack_frame) {
2214 // For each stack frame:
2215 // (2b) method's class name
2216 // (2b) method name
2217 // (2b) method source file
2218 // (2b) line number, clipped to 32767; -2 if native; -1 if no source
2219 const Method* m = record->stack[stack_frame].method;
2220 JDWP::Append2BE(bytes, class_names.IndexOf(m->GetDeclaringClass()->GetDescriptor()));
2221 JDWP::Append2BE(bytes, method_names.IndexOf(m->GetName()));
2222 JDWP::Append2BE(bytes, filenames.IndexOf(m->GetDeclaringClass()->GetSourceFile()));
2223 JDWP::Append2BE(bytes, record->stack[stack_frame].LineNumber());
2224 }
2225
2226 idx = (idx + 1) & (kNumAllocRecords-1);
2227 }
2228
2229 // (xb) class name strings
2230 // (xb) method name strings
2231 // (xb) source file strings
2232 JDWP::Set4BE(&bytes[string_table_offset], bytes.size());
2233 class_names.WriteTo(bytes);
2234 method_names.WriteTo(bytes);
2235 filenames.WriteTo(bytes);
2236
2237 JNIEnv* env = Thread::Current()->GetJniEnv();
2238 jbyteArray result = env->NewByteArray(bytes.size());
2239 if (result != NULL) {
2240 env->SetByteArrayRegion(result, 0, bytes.size(), reinterpret_cast<const jbyte*>(&bytes[0]));
2241 }
2242 return result;
2243}
2244
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002245} // namespace art