blob: f4969dc54cf43176f28ae76e85b6a3e3f9027bbd [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
478bool Dbg::IsInterface(JDWP::RefTypeId id) {
479 UNIMPLEMENTED(FATAL);
480 return false;
481}
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 Hughesdbb40792011-11-18 17:05:22 -0800584size_t Dbg::GetTagWidth(int tag) {
585 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) {
662 Object* element = oa->Get(i);
663 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
672bool Dbg::SetArrayElements(JDWP::ObjectId arrayId, int firstIndex, int count, const uint8_t* buf) {
673 UNIMPLEMENTED(FATAL);
674 return false;
675}
676
677JDWP::ObjectId Dbg::CreateString(const char* str) {
678 UNIMPLEMENTED(FATAL);
679 return 0;
680}
681
682JDWP::ObjectId Dbg::CreateObject(JDWP::RefTypeId classId) {
683 UNIMPLEMENTED(FATAL);
684 return 0;
685}
686
687JDWP::ObjectId Dbg::CreateArrayObject(JDWP::RefTypeId arrayTypeId, uint32_t length) {
688 UNIMPLEMENTED(FATAL);
689 return 0;
690}
691
692bool Dbg::MatchType(JDWP::RefTypeId instClassId, JDWP::RefTypeId classId) {
693 UNIMPLEMENTED(FATAL);
694 return false;
695}
696
Elliott Hughes03181a82011-11-17 17:22:21 -0800697JDWP::FieldId ToFieldId(Field* f) {
698#ifdef MOVING_GARBAGE_COLLECTOR
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700699 UNIMPLEMENTED(FATAL);
Elliott Hughes03181a82011-11-17 17:22:21 -0800700#else
701 return static_cast<JDWP::FieldId>(reinterpret_cast<uintptr_t>(f));
702#endif
703}
704
705JDWP::MethodId ToMethodId(Method* m) {
706#ifdef MOVING_GARBAGE_COLLECTOR
707 UNIMPLEMENTED(FATAL);
708#else
709 return static_cast<JDWP::MethodId>(reinterpret_cast<uintptr_t>(m));
710#endif
711}
712
713Method* FromMethodId(JDWP::MethodId mid) {
714#ifdef MOVING_GARBAGE_COLLECTOR
715 UNIMPLEMENTED(FATAL);
716#else
717 return reinterpret_cast<Method*>(static_cast<uintptr_t>(mid));
718#endif
719}
720
721std::string Dbg::GetMethodName(JDWP::RefTypeId refTypeId, JDWP::MethodId methodId) {
722 return FromMethodId(methodId)->GetName()->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700723}
724
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800725/*
726 * Augment the access flags for synthetic methods and fields by setting
727 * the (as described by the spec) "0xf0000000 bit". Also, strip out any
728 * flags not specified by the Java programming language.
729 */
730static uint32_t MangleAccessFlags(uint32_t accessFlags) {
731 accessFlags &= kAccJavaFlagsMask;
732 if ((accessFlags & kAccSynthetic) != 0) {
733 accessFlags |= 0xf0000000;
734 }
735 return accessFlags;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700736}
737
Elliott Hughesdbb40792011-11-18 17:05:22 -0800738static const uint16_t kEclipseWorkaroundSlot = 1000;
739
740/*
741 * Eclipse appears to expect that the "this" reference is in slot zero.
742 * If it's not, the "variables" display will show two copies of "this",
743 * possibly because it gets "this" from SF.ThisObject and then displays
744 * all locals with nonzero slot numbers.
745 *
746 * So, we remap the item in slot 0 to 1000, and remap "this" to zero. On
747 * SF.GetValues / SF.SetValues we map them back.
Elliott Hughesc5b734a2011-12-01 17:20:58 -0800748 *
749 * TODO: jdb uses the value to determine whether a variable is a local or an argument,
750 * by checking whether it's less than the number of arguments. To make that work, we'd
751 * have to "mangle" all the arguments to come first, not just the implicit argument 'this'.
Elliott Hughesdbb40792011-11-18 17:05:22 -0800752 */
753static uint16_t MangleSlot(uint16_t slot, const char* name) {
754 uint16_t newSlot = slot;
755 if (strcmp(name, "this") == 0) {
756 newSlot = 0;
757 } else if (slot == 0) {
758 newSlot = kEclipseWorkaroundSlot;
759 }
760 return newSlot;
761}
762
Elliott Hughes68fdbd02011-11-29 19:22:47 -0800763static uint16_t DemangleSlot(uint16_t slot, Frame& f) {
Elliott Hughesdbb40792011-11-18 17:05:22 -0800764 if (slot == kEclipseWorkaroundSlot) {
Elliott Hughes68fdbd02011-11-29 19:22:47 -0800765 return 0;
Elliott Hughesdbb40792011-11-18 17:05:22 -0800766 } else if (slot == 0) {
Elliott Hughesdbb40792011-11-18 17:05:22 -0800767 Method* m = f.GetMethod();
Elliott Hughes68fdbd02011-11-29 19:22:47 -0800768 return m->NumRegisters() - m->NumIns();
Elliott Hughesdbb40792011-11-18 17:05:22 -0800769 }
Elliott Hughes68fdbd02011-11-29 19:22:47 -0800770 return slot;
Elliott Hughesdbb40792011-11-18 17:05:22 -0800771}
772
Elliott Hughesc5b734a2011-12-01 17:20:58 -0800773void Dbg::OutputDeclaredFields(JDWP::RefTypeId refTypeId, bool with_generic, JDWP::ExpandBuf* pReply) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800774 Class* c = gRegistry->Get<Class*>(refTypeId);
775 CHECK(c != NULL);
776
777 size_t instance_field_count = c->NumInstanceFields();
778 size_t static_field_count = c->NumStaticFields();
779
780 expandBufAdd4BE(pReply, instance_field_count + static_field_count);
781
782 for (size_t i = 0; i < instance_field_count + static_field_count; ++i) {
783 Field* f = (i < instance_field_count) ? c->GetInstanceField(i) : c->GetStaticField(i - instance_field_count);
784
785 expandBufAddFieldId(pReply, ToFieldId(f));
786 expandBufAddUtf8String(pReply, f->GetName()->ToModifiedUtf8().c_str());
787 expandBufAddUtf8String(pReply, f->GetTypeDescriptor());
Elliott Hughesc5b734a2011-12-01 17:20:58 -0800788 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800789 static const char genericSignature[1] = "";
790 expandBufAddUtf8String(pReply, genericSignature);
791 }
792 expandBufAdd4BE(pReply, MangleAccessFlags(f->GetAccessFlags()));
793 }
794}
795
Elliott Hughesc5b734a2011-12-01 17:20:58 -0800796void Dbg::OutputDeclaredMethods(JDWP::RefTypeId refTypeId, bool with_generic, JDWP::ExpandBuf* pReply) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800797 Class* c = gRegistry->Get<Class*>(refTypeId);
798 CHECK(c != NULL);
799
800 size_t direct_method_count = c->NumDirectMethods();
801 size_t virtual_method_count = c->NumVirtualMethods();
802
803 expandBufAdd4BE(pReply, direct_method_count + virtual_method_count);
804
805 for (size_t i = 0; i < direct_method_count + virtual_method_count; ++i) {
806 Method* m = (i < direct_method_count) ? c->GetDirectMethod(i) : c->GetVirtualMethod(i - direct_method_count);
807
808 expandBufAddMethodId(pReply, ToMethodId(m));
809 expandBufAddUtf8String(pReply, m->GetName()->ToModifiedUtf8().c_str());
810 expandBufAddUtf8String(pReply, m->GetSignature()->ToModifiedUtf8().c_str());
Elliott Hughesc5b734a2011-12-01 17:20:58 -0800811 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800812 static const char genericSignature[1] = "";
813 expandBufAddUtf8String(pReply, genericSignature);
814 }
815 expandBufAdd4BE(pReply, MangleAccessFlags(m->GetAccessFlags()));
816 }
817}
818
819void Dbg::OutputDeclaredInterfaces(JDWP::RefTypeId refTypeId, JDWP::ExpandBuf* pReply) {
820 Class* c = gRegistry->Get<Class*>(refTypeId);
821 CHECK(c != NULL);
822 size_t interface_count = c->NumInterfaces();
823 expandBufAdd4BE(pReply, interface_count);
824 for (size_t i = 0; i < interface_count; ++i) {
825 expandBufAddRefTypeId(pReply, gRegistry->Add(c->GetInterface(i)));
826 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700827}
828
829void Dbg::OutputLineTable(JDWP::RefTypeId refTypeId, JDWP::MethodId methodId, JDWP::ExpandBuf* pReply) {
Elliott Hughes03181a82011-11-17 17:22:21 -0800830 struct DebugCallbackContext {
831 int numItems;
832 JDWP::ExpandBuf* pReply;
833
834 static bool Callback(void* context, uint32_t address, uint32_t lineNum) {
835 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
836 expandBufAdd8BE(pContext->pReply, address);
837 expandBufAdd4BE(pContext->pReply, lineNum);
838 pContext->numItems++;
839 return true;
840 }
841 };
842
843 Method* m = FromMethodId(methodId);
844 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
845 const DexFile& dex_file = class_linker->FindDexFile(m->GetDeclaringClass()->GetDexCache());
846 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(m->GetCodeItemOffset());
847
848 uint64_t start, end;
849 if (m->IsNative()) {
850 start = -1;
851 end = -1;
852 } else {
853 start = 0;
854 end = code_item->insns_size_in_code_units_; // TODO: what are the units supposed to be? *2?
855 }
856
857 expandBufAdd8BE(pReply, start);
858 expandBufAdd8BE(pReply, end);
859
860 // Add numLines later
861 size_t numLinesOffset = expandBufGetLength(pReply);
862 expandBufAdd4BE(pReply, 0);
863
864 DebugCallbackContext context;
865 context.numItems = 0;
866 context.pReply = pReply;
867
868 dex_file.DecodeDebugInfo(code_item, m, DebugCallbackContext::Callback, NULL, &context);
869
870 JDWP::Set4BE(expandBufGetBuffer(pReply) + numLinesOffset, context.numItems);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700871}
872
Elliott Hughesc5b734a2011-12-01 17:20:58 -0800873void Dbg::OutputVariableTable(JDWP::RefTypeId refTypeId, JDWP::MethodId methodId, bool with_generic, JDWP::ExpandBuf* pReply) {
Elliott Hughesdbb40792011-11-18 17:05:22 -0800874 struct DebugCallbackContext {
Elliott Hughesdbb40792011-11-18 17:05:22 -0800875 JDWP::ExpandBuf* pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -0800876 size_t variable_count;
877 bool with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -0800878
Elliott Hughesc5b734a2011-12-01 17:20:58 -0800879 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 -0800880 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
881
Elliott Hughesc5b734a2011-12-01 17:20:58 -0800882 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 -0800883
Elliott Hughes68fdbd02011-11-29 19:22:47 -0800884 slot = MangleSlot(slot, name);
885
Elliott Hughesdbb40792011-11-18 17:05:22 -0800886 expandBufAdd8BE(pContext->pReply, startAddress);
887 expandBufAddUtf8String(pContext->pReply, name);
888 expandBufAddUtf8String(pContext->pReply, descriptor);
Elliott Hughesc5b734a2011-12-01 17:20:58 -0800889 if (pContext->with_generic) {
Elliott Hughesdbb40792011-11-18 17:05:22 -0800890 expandBufAddUtf8String(pContext->pReply, signature);
891 }
892 expandBufAdd4BE(pContext->pReply, endAddress - startAddress);
893 expandBufAdd4BE(pContext->pReply, slot);
894
Elliott Hughesc5b734a2011-12-01 17:20:58 -0800895 ++pContext->variable_count;
Elliott Hughesdbb40792011-11-18 17:05:22 -0800896 }
897 };
898
899 Method* m = FromMethodId(methodId);
900 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
901 const DexFile& dex_file = class_linker->FindDexFile(m->GetDeclaringClass()->GetDexCache());
902 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(m->GetCodeItemOffset());
903
Elliott Hughesc5b734a2011-12-01 17:20:58 -0800904 // arg_count considers doubles and longs to take 2 units.
905 // variable_count considers everything to take 1 unit.
906 std::string shorty(m->GetShorty()->ToModifiedUtf8());
907 expandBufAdd4BE(pReply, m->NumArgRegisters(shorty));
Elliott Hughesdbb40792011-11-18 17:05:22 -0800908
Elliott Hughesc5b734a2011-12-01 17:20:58 -0800909 // We don't know the total number of variables yet, so leave a blank and update it later.
910 size_t variable_count_offset = expandBufGetLength(pReply);
Elliott Hughesdbb40792011-11-18 17:05:22 -0800911 expandBufAdd4BE(pReply, 0);
912
913 DebugCallbackContext context;
Elliott Hughesdbb40792011-11-18 17:05:22 -0800914 context.pReply = pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -0800915 context.variable_count = 0;
916 context.with_generic = with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -0800917
918 dex_file.DecodeDebugInfo(code_item, m, NULL, DebugCallbackContext::Callback, &context);
919
Elliott Hughesc5b734a2011-12-01 17:20:58 -0800920 JDWP::Set4BE(expandBufGetBuffer(pReply) + variable_count_offset, context.variable_count);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700921}
922
923uint8_t Dbg::GetFieldBasicTag(JDWP::ObjectId objId, JDWP::FieldId fieldId) {
924 UNIMPLEMENTED(FATAL);
925 return 0;
926}
927
928uint8_t Dbg::GetStaticFieldBasicTag(JDWP::RefTypeId refTypeId, JDWP::FieldId fieldId) {
929 UNIMPLEMENTED(FATAL);
930 return 0;
931}
932
933void Dbg::GetFieldValue(JDWP::ObjectId objectId, JDWP::FieldId fieldId, JDWP::ExpandBuf* pReply) {
934 UNIMPLEMENTED(FATAL);
935}
936
937void Dbg::SetFieldValue(JDWP::ObjectId objectId, JDWP::FieldId fieldId, uint64_t value, int width) {
938 UNIMPLEMENTED(FATAL);
939}
940
941void Dbg::GetStaticFieldValue(JDWP::RefTypeId refTypeId, JDWP::FieldId fieldId, JDWP::ExpandBuf* pReply) {
942 UNIMPLEMENTED(FATAL);
943}
944
945void Dbg::SetStaticFieldValue(JDWP::RefTypeId refTypeId, JDWP::FieldId fieldId, uint64_t rawValue, int width) {
946 UNIMPLEMENTED(FATAL);
947}
948
Elliott Hughes68fdbd02011-11-29 19:22:47 -0800949std::string Dbg::StringToUtf8(JDWP::ObjectId strId) {
950 String* s = gRegistry->Get<String*>(strId);
951 return s->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700952}
953
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800954Thread* DecodeThread(JDWP::ObjectId threadId) {
955 Object* thread_peer = gRegistry->Get<Object*>(threadId);
956 CHECK(thread_peer != NULL);
957 return Thread::FromManagedThread(thread_peer);
958}
959
960bool Dbg::GetThreadName(JDWP::ObjectId threadId, std::string& name) {
961 ScopedThreadListLock thread_list_lock;
962 Thread* thread = DecodeThread(threadId);
963 if (thread == NULL) {
964 return false;
965 }
966 StringAppendF(&name, "<%d> %s", thread->GetThinLockId(), thread->GetName()->ToModifiedUtf8().c_str());
967 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700968}
969
970JDWP::ObjectId Dbg::GetThreadGroup(JDWP::ObjectId threadId) {
Elliott Hughes499c5132011-11-17 14:55:11 -0800971 Object* thread = gRegistry->Get<Object*>(threadId);
972 CHECK(thread != NULL);
973
974 Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/Thread;");
975 CHECK(c != NULL);
976 Field* f = c->FindInstanceField("group", "Ljava/lang/ThreadGroup;");
977 CHECK(f != NULL);
978 Object* group = f->GetObject(thread);
979 CHECK(group != NULL);
980 return gRegistry->Add(group);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700981}
982
Elliott Hughes499c5132011-11-17 14:55:11 -0800983std::string Dbg::GetThreadGroupName(JDWP::ObjectId threadGroupId) {
984 Object* thread_group = gRegistry->Get<Object*>(threadGroupId);
985 CHECK(thread_group != NULL);
986
987 Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/ThreadGroup;");
988 CHECK(c != NULL);
989 Field* f = c->FindInstanceField("name", "Ljava/lang/String;");
990 CHECK(f != NULL);
991 String* s = reinterpret_cast<String*>(f->GetObject(thread_group));
992 return s->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700993}
994
995JDWP::ObjectId Dbg::GetThreadGroupParent(JDWP::ObjectId threadGroupId) {
996 UNIMPLEMENTED(FATAL);
997 return 0;
998}
999
Elliott Hughes499c5132011-11-17 14:55:11 -08001000static Object* GetStaticThreadGroup(const char* field_name) {
1001 Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/ThreadGroup;");
1002 CHECK(c != NULL);
1003 Field* f = c->FindStaticField(field_name, "Ljava/lang/ThreadGroup;");
1004 CHECK(f != NULL);
1005 Object* group = f->GetObject(NULL);
1006 CHECK(group != NULL);
1007 return group;
1008}
1009
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001010JDWP::ObjectId Dbg::GetSystemThreadGroupId() {
Elliott Hughes499c5132011-11-17 14:55:11 -08001011 return gRegistry->Add(GetStaticThreadGroup("mSystem"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001012}
1013
1014JDWP::ObjectId Dbg::GetMainThreadGroupId() {
Elliott Hughes499c5132011-11-17 14:55:11 -08001015 return gRegistry->Add(GetStaticThreadGroup("mMain"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001016}
1017
Elliott Hughes499c5132011-11-17 14:55:11 -08001018bool Dbg::GetThreadStatus(JDWP::ObjectId threadId, uint32_t* pThreadStatus, uint32_t* pSuspendStatus) {
1019 ScopedThreadListLock thread_list_lock;
1020
1021 Thread* thread = DecodeThread(threadId);
1022 if (thread == NULL) {
1023 return false;
1024 }
1025
1026 switch (thread->GetState()) {
1027 case Thread::kTerminated: *pThreadStatus = JDWP::TS_ZOMBIE; break;
1028 case Thread::kRunnable: *pThreadStatus = JDWP::TS_RUNNING; break;
1029 case Thread::kTimedWaiting: *pThreadStatus = JDWP::TS_SLEEPING; break;
1030 case Thread::kBlocked: *pThreadStatus = JDWP::TS_MONITOR; break;
1031 case Thread::kWaiting: *pThreadStatus = JDWP::TS_WAIT; break;
1032 case Thread::kInitializing: *pThreadStatus = JDWP::TS_ZOMBIE; break;
1033 case Thread::kStarting: *pThreadStatus = JDWP::TS_ZOMBIE; break;
1034 case Thread::kNative: *pThreadStatus = JDWP::TS_RUNNING; break;
1035 case Thread::kVmWait: *pThreadStatus = JDWP::TS_WAIT; break;
1036 case Thread::kSuspended: *pThreadStatus = JDWP::TS_RUNNING; break;
1037 default:
1038 LOG(FATAL) << "unknown thread state " << thread->GetState();
1039 }
1040
1041 *pSuspendStatus = (thread->IsSuspended() ? JDWP::SUSPEND_STATUS_SUSPENDED : 0);
1042
1043 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001044}
1045
1046uint32_t Dbg::GetThreadSuspendCount(JDWP::ObjectId threadId) {
1047 UNIMPLEMENTED(FATAL);
1048 return 0;
1049}
1050
1051bool Dbg::ThreadExists(JDWP::ObjectId threadId) {
Elliott Hughes761928d2011-11-16 18:33:03 -08001052 return DecodeThread(threadId) != NULL;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001053}
1054
1055bool Dbg::IsSuspended(JDWP::ObjectId threadId) {
Elliott Hughes761928d2011-11-16 18:33:03 -08001056 return DecodeThread(threadId)->IsSuspended();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001057}
1058
1059//void Dbg::WaitForSuspend(JDWP::ObjectId threadId);
1060
Elliott Hughesa2155262011-11-16 16:26:58 -08001061void Dbg::GetThreadGroupThreadsImpl(Object* thread_group, JDWP::ObjectId** ppThreadIds, uint32_t* pThreadCount) {
1062 struct ThreadListVisitor {
1063 static void Visit(Thread* t, void* arg) {
1064 reinterpret_cast<ThreadListVisitor*>(arg)->Visit(t);
1065 }
1066
1067 void Visit(Thread* t) {
1068 if (t == Dbg::GetDebugThread()) {
1069 // Skip the JDWP thread. Some debuggers get bent out of shape when they can't suspend and
1070 // query all threads, so it's easier if we just don't tell them about this thread.
1071 return;
1072 }
1073 if (thread_group == NULL || t->GetThreadGroup() == thread_group) {
1074 threads.push_back(gRegistry->Add(t->GetPeer()));
1075 }
1076 }
1077
1078 Object* thread_group;
1079 std::vector<JDWP::ObjectId> threads;
1080 };
1081
1082 ThreadListVisitor tlv;
1083 tlv.thread_group = thread_group;
1084
1085 {
1086 ScopedThreadListLock thread_list_lock;
1087 Runtime::Current()->GetThreadList()->ForEach(ThreadListVisitor::Visit, &tlv);
1088 }
1089
1090 *pThreadCount = tlv.threads.size();
1091 if (*pThreadCount == 0) {
1092 *ppThreadIds = NULL;
1093 } else {
1094 *ppThreadIds = new JDWP::ObjectId[*pThreadCount];
1095 for (size_t i = 0; i < *pThreadCount; ++i) {
1096 (*ppThreadIds)[i] = tlv.threads[i];
1097 }
1098 }
1099}
1100
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001101void Dbg::GetThreadGroupThreads(JDWP::ObjectId threadGroupId, JDWP::ObjectId** ppThreadIds, uint32_t* pThreadCount) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001102 GetThreadGroupThreadsImpl(gRegistry->Get<Object*>(threadGroupId), ppThreadIds, pThreadCount);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001103}
1104
1105void Dbg::GetAllThreads(JDWP::ObjectId** ppThreadIds, uint32_t* pThreadCount) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001106 GetThreadGroupThreadsImpl(NULL, ppThreadIds, pThreadCount);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001107}
1108
1109int Dbg::GetThreadFrameCount(JDWP::ObjectId threadId) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001110 ScopedThreadListLock thread_list_lock;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001111 struct CountStackDepthVisitor : public Thread::StackVisitor {
1112 CountStackDepthVisitor() : depth(0) {}
Elliott Hughesf8a2df72011-12-01 12:19:54 -08001113 virtual void VisitFrame(const Frame& f, uintptr_t) {
1114 // TODO: we'll need to skip callee-save frames too.
1115 if (f.HasMethod()) {
1116 ++depth;
1117 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001118 }
1119 size_t depth;
1120 };
1121 CountStackDepthVisitor visitor;
1122 DecodeThread(threadId)->WalkStack(&visitor);
1123 return visitor.depth;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001124}
1125
Elliott Hughes03181a82011-11-17 17:22:21 -08001126bool Dbg::GetThreadFrame(JDWP::ObjectId threadId, int desired_frame_number, JDWP::FrameId* pFrameId, JDWP::JdwpLocation* pLoc) {
1127 ScopedThreadListLock thread_list_lock;
1128 struct GetFrameVisitor : public Thread::StackVisitor {
1129 GetFrameVisitor(int desired_frame_number, JDWP::FrameId* pFrameId, JDWP::JdwpLocation* pLoc)
1130 : found(false) ,depth(0), desired_frame_number(desired_frame_number), pFrameId(pFrameId), pLoc(pLoc) {
1131 }
1132 virtual void VisitFrame(const Frame& f, uintptr_t pc) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -08001133 // TODO: we'll need to skip callee-save frames too.
Elliott Hughes03181a82011-11-17 17:22:21 -08001134 if (!f.HasMethod()) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -08001135 return; // The debugger can't do anything useful with a frame that has no Method*.
Elliott Hughes03181a82011-11-17 17:22:21 -08001136 }
1137
1138 if (depth == desired_frame_number) {
1139 *pFrameId = reinterpret_cast<JDWP::FrameId>(f.GetSP());
1140
1141 Method* m = f.GetMethod();
1142 Class* c = m->GetDeclaringClass();
1143
1144 pLoc->typeTag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
1145 pLoc->classId = gRegistry->Add(c);
1146 pLoc->methodId = ToMethodId(m);
1147 pLoc->idx = m->IsNative() ? -1 : m->ToDexPC(pc);
1148
1149 found = true;
1150 }
1151 ++depth;
1152 }
1153 bool found;
1154 int depth;
1155 int desired_frame_number;
1156 JDWP::FrameId* pFrameId;
1157 JDWP::JdwpLocation* pLoc;
1158 };
1159 GetFrameVisitor visitor(desired_frame_number, pFrameId, pLoc);
1160 visitor.desired_frame_number = desired_frame_number;
1161 DecodeThread(threadId)->WalkStack(&visitor);
1162 return visitor.found;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001163}
1164
1165JDWP::ObjectId Dbg::GetThreadSelfId() {
Elliott Hughes475fc232011-10-25 15:00:35 -07001166 return gRegistry->Add(Thread::Current()->GetPeer());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001167}
1168
Elliott Hughes475fc232011-10-25 15:00:35 -07001169void Dbg::SuspendVM() {
Elliott Hughesa2155262011-11-16 16:26:58 -08001170 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 -07001171 Runtime::Current()->GetThreadList()->SuspendAll(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001172}
1173
1174void Dbg::ResumeVM() {
Elliott Hughes475fc232011-10-25 15:00:35 -07001175 Runtime::Current()->GetThreadList()->ResumeAll(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001176}
1177
1178void Dbg::SuspendThread(JDWP::ObjectId threadId) {
1179 UNIMPLEMENTED(FATAL);
1180}
1181
1182void Dbg::ResumeThread(JDWP::ObjectId threadId) {
1183 UNIMPLEMENTED(FATAL);
1184}
1185
1186void Dbg::SuspendSelf() {
Elliott Hughes475fc232011-10-25 15:00:35 -07001187 Runtime::Current()->GetThreadList()->SuspendSelfForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001188}
1189
1190bool Dbg::GetThisObject(JDWP::ObjectId threadId, JDWP::FrameId frameId, JDWP::ObjectId* pThisId) {
1191 UNIMPLEMENTED(FATAL);
1192 return false;
1193}
1194
Elliott Hughesdbb40792011-11-18 17:05:22 -08001195void Dbg::GetLocalValue(JDWP::ObjectId threadId, JDWP::FrameId frameId, int slot, JDWP::JdwpTag tag, uint8_t* buf, size_t expectedLen) {
1196 Method** sp = reinterpret_cast<Method**>(frameId);
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001197 Frame f;
1198 f.SetSP(sp);
1199 uint16_t reg = DemangleSlot(slot, f);
1200 Method* m = f.GetMethod();
1201
1202 const VmapTable vmap_table(m->GetVmapTableRaw());
1203 uint32_t vmap_offset;
1204 if (vmap_table.IsInContext(reg, vmap_offset)) {
1205 UNIMPLEMENTED(FATAL) << "don't know how to pull locals from callee save frames: " << vmap_offset;
1206 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001207
1208 switch (tag) {
1209 case JDWP::JT_BOOLEAN:
1210 {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001211 CHECK_EQ(expectedLen, 1U);
Elliott Hughes1bba14f2011-12-01 18:00:36 -08001212 uint32_t intVal = f.GetVReg(m, reg);
1213 LOG(VERBOSE) << "get boolean local " << reg << " = " << intVal;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001214 JDWP::Set1(buf+1, intVal != 0);
1215 }
1216 break;
1217 case JDWP::JT_BYTE:
1218 {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001219 CHECK_EQ(expectedLen, 1U);
Elliott Hughes1bba14f2011-12-01 18:00:36 -08001220 uint32_t intVal = f.GetVReg(m, reg);
1221 LOG(VERBOSE) << "get byte local " << reg << " = " << intVal;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001222 JDWP::Set1(buf+1, intVal);
1223 }
1224 break;
1225 case JDWP::JT_SHORT:
1226 case JDWP::JT_CHAR:
1227 {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001228 CHECK_EQ(expectedLen, 2U);
Elliott Hughes1bba14f2011-12-01 18:00:36 -08001229 uint32_t intVal = f.GetVReg(m, reg);
1230 LOG(VERBOSE) << "get short/char local " << reg << " = " << intVal;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001231 JDWP::Set2BE(buf+1, intVal);
1232 }
1233 break;
1234 case JDWP::JT_INT:
1235 case JDWP::JT_FLOAT:
1236 {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001237 CHECK_EQ(expectedLen, 4U);
Elliott Hughes1bba14f2011-12-01 18:00:36 -08001238 uint32_t intVal = f.GetVReg(m, reg);
1239 LOG(VERBOSE) << "get int/float local " << reg << " = " << intVal;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001240 JDWP::Set4BE(buf+1, intVal);
1241 }
1242 break;
1243 case JDWP::JT_ARRAY:
1244 {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001245 CHECK_EQ(expectedLen, sizeof(JDWP::ObjectId));
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001246 Object* o = reinterpret_cast<Object*>(f.GetVReg(m, reg));
Elliott Hughes1bba14f2011-12-01 18:00:36 -08001247 LOG(VERBOSE) << "get array local " << reg << " = " << o;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001248 if (o != NULL && !Heap::IsHeapAddress(o)) {
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001249 LOG(FATAL) << "reg " << reg << " expected to hold array: " << o;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001250 }
1251 JDWP::SetObjectId(buf+1, gRegistry->Add(o));
1252 }
1253 break;
1254 case JDWP::JT_OBJECT:
1255 {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001256 CHECK_EQ(expectedLen, sizeof(JDWP::ObjectId));
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001257 Object* o = reinterpret_cast<Object*>(f.GetVReg(m, reg));
Elliott Hughes1bba14f2011-12-01 18:00:36 -08001258 LOG(VERBOSE) << "get object local " << reg << " = " << o;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001259 if (o != NULL && !Heap::IsHeapAddress(o)) {
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001260 LOG(FATAL) << "reg " << reg << " expected to hold object: " << o;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001261 }
1262 tag = TagFromObject(o);
1263 JDWP::SetObjectId(buf+1, gRegistry->Add(o));
1264 }
1265 break;
1266 case JDWP::JT_DOUBLE:
1267 case JDWP::JT_LONG:
1268 {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001269 CHECK_EQ(expectedLen, 8U);
Elliott Hughes1bba14f2011-12-01 18:00:36 -08001270 uint32_t lo = f.GetVReg(m, reg);
1271 uint64_t hi = f.GetVReg(m, reg + 1);
1272 uint64_t longVal = (hi << 32) | lo;
1273 LOG(VERBOSE) << "get double/long local " << hi << ":" << lo << " = " << longVal;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001274 JDWP::Set8BE(buf+1, longVal);
1275 }
1276 break;
1277 default:
1278 LOG(FATAL) << "unknown tag " << tag;
1279 break;
1280 }
1281
1282 // Prepend tag, which may have been updated.
1283 JDWP::Set1(buf, tag);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001284}
1285
Elliott Hughesdbb40792011-11-18 17:05:22 -08001286void 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 -07001287 UNIMPLEMENTED(FATAL);
1288}
1289
1290void Dbg::PostLocationEvent(const Method* method, int pcOffset, Object* thisPtr, int eventFlags) {
1291 UNIMPLEMENTED(FATAL);
1292}
1293
1294void Dbg::PostException(void* throwFp, int throwRelPc, void* catchFp, int catchRelPc, Object* exception) {
1295 UNIMPLEMENTED(FATAL);
1296}
1297
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001298void Dbg::PostClassPrepare(Class* c) {
1299 UNIMPLEMENTED(FATAL);
1300}
1301
1302bool Dbg::WatchLocation(const JDWP::JdwpLocation* pLoc) {
1303 UNIMPLEMENTED(FATAL);
1304 return false;
1305}
1306
1307void Dbg::UnwatchLocation(const JDWP::JdwpLocation* pLoc) {
1308 UNIMPLEMENTED(FATAL);
1309}
1310
1311bool Dbg::ConfigureStep(JDWP::ObjectId threadId, JDWP::JdwpStepSize size, JDWP::JdwpStepDepth depth) {
1312 UNIMPLEMENTED(FATAL);
1313 return false;
1314}
1315
1316void Dbg::UnconfigureStep(JDWP::ObjectId threadId) {
1317 UNIMPLEMENTED(FATAL);
1318}
1319
1320JDWP::JdwpError Dbg::InvokeMethod(JDWP::ObjectId threadId, JDWP::ObjectId objectId, JDWP::RefTypeId classId, JDWP::MethodId methodId, uint32_t numArgs, uint64_t* argArray, uint32_t options, uint8_t* pResultTag, uint64_t* pResultValue, JDWP::ObjectId* pExceptObj) {
1321 UNIMPLEMENTED(FATAL);
1322 return JDWP::ERR_NONE;
1323}
1324
1325void Dbg::ExecuteMethod(DebugInvokeReq* pReq) {
1326 UNIMPLEMENTED(FATAL);
1327}
1328
1329void Dbg::RegisterObjectId(JDWP::ObjectId id) {
1330 UNIMPLEMENTED(FATAL);
1331}
1332
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001333/*
1334 * "buf" contains a full JDWP packet, possibly with multiple chunks. We
1335 * need to process each, accumulate the replies, and ship the whole thing
1336 * back.
1337 *
1338 * Returns "true" if we have a reply. The reply buffer is newly allocated,
1339 * and includes the chunk type/length, followed by the data.
1340 *
1341 * TODO: we currently assume that the request and reply include a single
1342 * chunk. If this becomes inconvenient we will need to adapt.
1343 */
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001344bool Dbg::DdmHandlePacket(const uint8_t* buf, int dataLen, uint8_t** pReplyBuf, int* pReplyLen) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001345 CHECK_GE(dataLen, 0);
1346
1347 Thread* self = Thread::Current();
1348 JNIEnv* env = self->GetJniEnv();
1349
1350 static jclass Chunk_class = env->FindClass("org/apache/harmony/dalvik/ddmc/Chunk");
1351 static jclass DdmServer_class = env->FindClass("org/apache/harmony/dalvik/ddmc/DdmServer");
1352 static jmethodID dispatch_mid = env->GetStaticMethodID(DdmServer_class, "dispatch",
1353 "(I[BII)Lorg/apache/harmony/dalvik/ddmc/Chunk;");
1354 static jfieldID data_fid = env->GetFieldID(Chunk_class, "data", "[B");
1355 static jfieldID length_fid = env->GetFieldID(Chunk_class, "length", "I");
1356 static jfieldID offset_fid = env->GetFieldID(Chunk_class, "offset", "I");
1357 static jfieldID type_fid = env->GetFieldID(Chunk_class, "type", "I");
1358
1359 // Create a byte[] corresponding to 'buf'.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001360 ScopedLocalRef<jbyteArray> dataArray(env, env->NewByteArray(dataLen));
1361 if (dataArray.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001362 LOG(WARNING) << "byte[] allocation failed: " << dataLen;
1363 env->ExceptionClear();
1364 return false;
1365 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001366 env->SetByteArrayRegion(dataArray.get(), 0, dataLen, reinterpret_cast<const jbyte*>(buf));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001367
1368 const int kChunkHdrLen = 8;
1369
1370 // Run through and find all chunks. [Currently just find the first.]
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001371 ScopedByteArrayRO contents(env, dataArray.get());
Elliott Hughesf7c3b662011-10-27 12:04:56 -07001372 jint type = JDWP::Get4BE(reinterpret_cast<const uint8_t*>(&contents[0]));
1373 jint length = JDWP::Get4BE(reinterpret_cast<const uint8_t*>(&contents[4]));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001374 jint offset = kChunkHdrLen;
1375 if (offset + length > dataLen) {
1376 LOG(WARNING) << StringPrintf("bad chunk found (len=%u pktLen=%d)", length, dataLen);
1377 return false;
1378 }
1379
1380 // Call "private static Chunk dispatch(int type, byte[] data, int offset, int length)".
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001381 ScopedLocalRef<jobject> chunk(env, env->CallStaticObjectMethod(DdmServer_class, dispatch_mid, type, dataArray.get(), offset, length));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001382 if (env->ExceptionCheck()) {
1383 LOG(INFO) << StringPrintf("Exception thrown by dispatcher for 0x%08x", type);
1384 env->ExceptionDescribe();
1385 env->ExceptionClear();
1386 return false;
1387 }
1388
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001389 if (chunk.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001390 return false;
1391 }
1392
1393 /*
1394 * Pull the pieces out of the chunk. We copy the results into a
1395 * newly-allocated buffer that the caller can free. We don't want to
1396 * continue using the Chunk object because nothing has a reference to it.
1397 *
1398 * We could avoid this by returning type/data/offset/length and having
1399 * the caller be aware of the object lifetime issues, but that
1400 * integrates the JDWP code more tightly into the VM, and doesn't work
1401 * if we have responses for multiple chunks.
1402 *
1403 * So we're pretty much stuck with copying data around multiple times.
1404 */
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001405 ScopedLocalRef<jbyteArray> replyData(env, reinterpret_cast<jbyteArray>(env->GetObjectField(chunk.get(), data_fid)));
1406 length = env->GetIntField(chunk.get(), length_fid);
1407 offset = env->GetIntField(chunk.get(), offset_fid);
1408 type = env->GetIntField(chunk.get(), type_fid);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001409
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001410 LOG(VERBOSE) << StringPrintf("DDM reply: type=0x%08x data=%p offset=%d length=%d", type, replyData.get(), offset, length);
1411 if (length == 0 || replyData.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001412 return false;
1413 }
1414
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001415 jsize replyLength = env->GetArrayLength(replyData.get());
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001416 if (offset + length > replyLength) {
1417 LOG(WARNING) << StringPrintf("chunk off=%d len=%d exceeds reply array len %d", offset, length, replyLength);
1418 return false;
1419 }
1420
1421 uint8_t* reply = new uint8_t[length + kChunkHdrLen];
1422 if (reply == NULL) {
1423 LOG(WARNING) << "malloc failed: " << (length + kChunkHdrLen);
1424 return false;
1425 }
Elliott Hughesf7c3b662011-10-27 12:04:56 -07001426 JDWP::Set4BE(reply + 0, type);
1427 JDWP::Set4BE(reply + 4, length);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001428 env->GetByteArrayRegion(replyData.get(), offset, length, reinterpret_cast<jbyte*>(reply + kChunkHdrLen));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001429
1430 *pReplyBuf = reply;
1431 *pReplyLen = length + kChunkHdrLen;
1432
1433 LOG(VERBOSE) << StringPrintf("dvmHandleDdm returning type=%.4s buf=%p len=%d", (char*) reply, reply, length);
1434 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001435}
1436
Elliott Hughesa2155262011-11-16 16:26:58 -08001437void Dbg::DdmBroadcast(bool connect) {
Elliott Hughes47fce012011-10-25 18:37:19 -07001438 LOG(VERBOSE) << "Broadcasting DDM " << (connect ? "connect" : "disconnect") << "...";
1439
1440 Thread* self = Thread::Current();
1441 if (self->GetState() != Thread::kRunnable) {
1442 LOG(ERROR) << "DDM broadcast in thread state " << self->GetState();
1443 /* try anyway? */
1444 }
1445
1446 JNIEnv* env = self->GetJniEnv();
1447 static jclass DdmServer_class = env->FindClass("org/apache/harmony/dalvik/ddmc/DdmServer");
1448 static jmethodID broadcast_mid = env->GetStaticMethodID(DdmServer_class, "broadcast", "(I)V");
1449 jint event = connect ? 1 /*DdmServer.CONNECTED*/ : 2 /*DdmServer.DISCONNECTED*/;
1450 env->CallStaticVoidMethod(DdmServer_class, broadcast_mid, event);
1451 if (env->ExceptionCheck()) {
1452 LOG(ERROR) << "DdmServer.broadcast " << event << " failed";
1453 env->ExceptionDescribe();
1454 env->ExceptionClear();
1455 }
1456}
1457
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001458void Dbg::DdmConnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08001459 Dbg::DdmBroadcast(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001460}
1461
1462void Dbg::DdmDisconnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08001463 Dbg::DdmBroadcast(false);
Elliott Hughes47fce012011-10-25 18:37:19 -07001464 gDdmThreadNotification = false;
1465}
1466
1467/*
Elliott Hughes82188472011-11-07 18:11:48 -08001468 * Send a notification when a thread starts, stops, or changes its name.
Elliott Hughes47fce012011-10-25 18:37:19 -07001469 *
1470 * Because we broadcast the full set of threads when the notifications are
1471 * first enabled, it's possible for "thread" to be actively executing.
1472 */
Elliott Hughes82188472011-11-07 18:11:48 -08001473void Dbg::DdmSendThreadNotification(Thread* t, uint32_t type) {
Elliott Hughes47fce012011-10-25 18:37:19 -07001474 if (!gDdmThreadNotification) {
1475 return;
1476 }
1477
Elliott Hughes82188472011-11-07 18:11:48 -08001478 if (type == CHUNK_TYPE("THDE")) {
Elliott Hughes47fce012011-10-25 18:37:19 -07001479 uint8_t buf[4];
Elliott Hughesf7c3b662011-10-27 12:04:56 -07001480 JDWP::Set4BE(&buf[0], t->GetThinLockId());
Elliott Hughes47fce012011-10-25 18:37:19 -07001481 Dbg::DdmSendChunk(CHUNK_TYPE("THDE"), 4, buf);
Elliott Hughes82188472011-11-07 18:11:48 -08001482 } else {
1483 CHECK(type == CHUNK_TYPE("THCR") || type == CHUNK_TYPE("THNM")) << type;
1484 SirtRef<String> name(t->GetName());
1485 size_t char_count = (name.get() != NULL) ? name->GetLength() : 0;
1486 const jchar* chars = name->GetCharArray()->GetData();
1487
Elliott Hughes21f32d72011-11-09 17:44:13 -08001488 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08001489 JDWP::Append4BE(bytes, t->GetThinLockId());
1490 JDWP::AppendUtf16BE(bytes, chars, char_count);
Elliott Hughes21f32d72011-11-09 17:44:13 -08001491 CHECK_EQ(bytes.size(), char_count*2 + sizeof(uint32_t)*2);
1492 Dbg::DdmSendChunk(type, bytes);
Elliott Hughes47fce012011-10-25 18:37:19 -07001493 }
1494}
1495
Elliott Hughesa2155262011-11-16 16:26:58 -08001496static void DdmSendThreadStartCallback(Thread* t, void*) {
Elliott Hughes82188472011-11-07 18:11:48 -08001497 Dbg::DdmSendThreadNotification(t, CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07001498}
1499
1500void Dbg::DdmSetThreadNotification(bool enable) {
1501 // We lock the thread list to avoid sending duplicate events or missing
1502 // a thread change. We should be okay holding this lock while sending
1503 // the messages out. (We have to hold it while accessing a live thread.)
Elliott Hughesbbd9d832011-11-07 14:40:00 -08001504 ScopedThreadListLock thread_list_lock;
Elliott Hughes47fce012011-10-25 18:37:19 -07001505
1506 gDdmThreadNotification = enable;
1507 if (enable) {
Elliott Hughesbfe487b2011-10-26 15:48:55 -07001508 Runtime::Current()->GetThreadList()->ForEach(DdmSendThreadStartCallback, NULL);
Elliott Hughes47fce012011-10-25 18:37:19 -07001509 }
1510}
1511
Elliott Hughesa2155262011-11-16 16:26:58 -08001512void Dbg::PostThreadStartOrStop(Thread* t, uint32_t type) {
Elliott Hughes47fce012011-10-25 18:37:19 -07001513 if (gDebuggerActive) {
1514 JDWP::ObjectId id = gRegistry->Add(t->GetPeer());
Elliott Hughes82188472011-11-07 18:11:48 -08001515 gJdwpState->PostThreadChange(id, type == CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07001516 }
Elliott Hughes82188472011-11-07 18:11:48 -08001517 Dbg::DdmSendThreadNotification(t, type);
Elliott Hughes47fce012011-10-25 18:37:19 -07001518}
1519
1520void Dbg::PostThreadStart(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001521 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07001522}
1523
1524void Dbg::PostThreadDeath(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001525 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THDE"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001526}
1527
Elliott Hughes82188472011-11-07 18:11:48 -08001528void Dbg::DdmSendChunk(uint32_t type, size_t byte_count, const uint8_t* buf) {
Elliott Hughes3bb81562011-10-21 18:52:59 -07001529 CHECK(buf != NULL);
1530 iovec vec[1];
1531 vec[0].iov_base = reinterpret_cast<void*>(const_cast<uint8_t*>(buf));
1532 vec[0].iov_len = byte_count;
1533 Dbg::DdmSendChunkV(type, vec, 1);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001534}
1535
Elliott Hughes21f32d72011-11-09 17:44:13 -08001536void Dbg::DdmSendChunk(uint32_t type, const std::vector<uint8_t>& bytes) {
1537 DdmSendChunk(type, bytes.size(), &bytes[0]);
1538}
1539
Elliott Hughes82188472011-11-07 18:11:48 -08001540void Dbg::DdmSendChunkV(uint32_t type, const struct iovec* iov, int iovcnt) {
Elliott Hughes3bb81562011-10-21 18:52:59 -07001541 if (gJdwpState == NULL) {
1542 LOG(VERBOSE) << "Debugger thread not active, ignoring DDM send: " << type;
1543 } else {
Elliott Hughes376a7a02011-10-24 18:35:55 -07001544 gJdwpState->DdmSendChunkV(type, iov, iovcnt);
Elliott Hughes3bb81562011-10-21 18:52:59 -07001545 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001546}
1547
Elliott Hughes767a1472011-10-26 18:49:02 -07001548int Dbg::DdmHandleHpifChunk(HpifWhen when) {
1549 if (when == HPIF_WHEN_NOW) {
Elliott Hughes7162ad92011-10-27 14:08:42 -07001550 DdmSendHeapInfo(when);
Elliott Hughes767a1472011-10-26 18:49:02 -07001551 return true;
1552 }
1553
1554 if (when != HPIF_WHEN_NEVER && when != HPIF_WHEN_NEXT_GC && when != HPIF_WHEN_EVERY_GC) {
1555 LOG(ERROR) << "invalid HpifWhen value: " << static_cast<int>(when);
1556 return false;
1557 }
1558
1559 gDdmHpifWhen = when;
1560 return true;
1561}
1562
1563bool Dbg::DdmHandleHpsgNhsgChunk(Dbg::HpsgWhen when, Dbg::HpsgWhat what, bool native) {
1564 if (when != HPSG_WHEN_NEVER && when != HPSG_WHEN_EVERY_GC) {
1565 LOG(ERROR) << "invalid HpsgWhen value: " << static_cast<int>(when);
1566 return false;
1567 }
1568
1569 if (what != HPSG_WHAT_MERGED_OBJECTS && what != HPSG_WHAT_DISTINCT_OBJECTS) {
1570 LOG(ERROR) << "invalid HpsgWhat value: " << static_cast<int>(what);
1571 return false;
1572 }
1573
1574 if (native) {
1575 gDdmNhsgWhen = when;
1576 gDdmNhsgWhat = what;
1577 } else {
1578 gDdmHpsgWhen = when;
1579 gDdmHpsgWhat = what;
1580 }
1581 return true;
1582}
1583
Elliott Hughes7162ad92011-10-27 14:08:42 -07001584void Dbg::DdmSendHeapInfo(HpifWhen reason) {
1585 // If there's a one-shot 'when', reset it.
1586 if (reason == gDdmHpifWhen) {
1587 if (gDdmHpifWhen == HPIF_WHEN_NEXT_GC) {
1588 gDdmHpifWhen = HPIF_WHEN_NEVER;
1589 }
1590 }
1591
1592 /*
1593 * Chunk HPIF (client --> server)
1594 *
1595 * Heap Info. General information about the heap,
1596 * suitable for a summary display.
1597 *
1598 * [u4]: number of heaps
1599 *
1600 * For each heap:
1601 * [u4]: heap ID
1602 * [u8]: timestamp in ms since Unix epoch
1603 * [u1]: capture reason (same as 'when' value from server)
1604 * [u4]: max heap size in bytes (-Xmx)
1605 * [u4]: current heap size in bytes
1606 * [u4]: current number of bytes allocated
1607 * [u4]: current number of objects allocated
1608 */
1609 uint8_t heap_count = 1;
Elliott Hughes21f32d72011-11-09 17:44:13 -08001610 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08001611 JDWP::Append4BE(bytes, heap_count);
1612 JDWP::Append4BE(bytes, 1); // Heap id (bogus; we only have one heap).
1613 JDWP::Append8BE(bytes, MilliTime());
1614 JDWP::Append1BE(bytes, reason);
1615 JDWP::Append4BE(bytes, Heap::GetMaxMemory()); // Max allowed heap size in bytes.
1616 JDWP::Append4BE(bytes, Heap::GetTotalMemory()); // Current heap size in bytes.
1617 JDWP::Append4BE(bytes, Heap::GetBytesAllocated());
1618 JDWP::Append4BE(bytes, Heap::GetObjectsAllocated());
Elliott Hughes21f32d72011-11-09 17:44:13 -08001619 CHECK_EQ(bytes.size(), 4U + (heap_count * (4 + 8 + 1 + 4 + 4 + 4 + 4)));
1620 Dbg::DdmSendChunk(CHUNK_TYPE("HPIF"), bytes);
Elliott Hughes767a1472011-10-26 18:49:02 -07001621}
1622
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001623enum HpsgSolidity {
1624 SOLIDITY_FREE = 0,
1625 SOLIDITY_HARD = 1,
1626 SOLIDITY_SOFT = 2,
1627 SOLIDITY_WEAK = 3,
1628 SOLIDITY_PHANTOM = 4,
1629 SOLIDITY_FINALIZABLE = 5,
1630 SOLIDITY_SWEEP = 6,
1631};
1632
1633enum HpsgKind {
1634 KIND_OBJECT = 0,
1635 KIND_CLASS_OBJECT = 1,
1636 KIND_ARRAY_1 = 2,
1637 KIND_ARRAY_2 = 3,
1638 KIND_ARRAY_4 = 4,
1639 KIND_ARRAY_8 = 5,
1640 KIND_UNKNOWN = 6,
1641 KIND_NATIVE = 7,
1642};
1643
1644#define HPSG_PARTIAL (1<<7)
1645#define HPSG_STATE(solidity, kind) ((uint8_t)((((kind) & 0x7) << 3) | ((solidity) & 0x7)))
1646
1647struct HeapChunkContext {
1648 std::vector<uint8_t> buf;
1649 uint8_t* p;
1650 uint8_t* pieceLenField;
1651 size_t totalAllocationUnits;
Elliott Hughes82188472011-11-07 18:11:48 -08001652 uint32_t type;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001653 bool merge;
1654 bool needHeader;
1655
1656 // Maximum chunk size. Obtain this from the formula:
1657 // (((maximum_heap_size / ALLOCATION_UNIT_SIZE) + 255) / 256) * 2
1658 HeapChunkContext(bool merge, bool native)
1659 : buf(16384 - 16),
1660 type(0),
1661 merge(merge) {
1662 Reset();
1663 if (native) {
1664 type = CHUNK_TYPE("NHSG");
1665 } else {
1666 type = merge ? CHUNK_TYPE("HPSG") : CHUNK_TYPE("HPSO");
1667 }
1668 }
1669
1670 ~HeapChunkContext() {
1671 if (p > &buf[0]) {
1672 Flush();
1673 }
1674 }
1675
1676 void EnsureHeader(const void* chunk_ptr) {
1677 if (!needHeader) {
1678 return;
1679 }
1680
1681 // Start a new HPSx chunk.
1682 JDWP::Write4BE(&p, 1); // Heap id (bogus; we only have one heap).
1683 JDWP::Write1BE(&p, 8); // Size of allocation unit, in bytes.
1684
1685 JDWP::Write4BE(&p, reinterpret_cast<uintptr_t>(chunk_ptr)); // virtual address of segment start.
1686 JDWP::Write4BE(&p, 0); // offset of this piece (relative to the virtual address).
1687 // [u4]: length of piece, in allocation units
1688 // We won't know this until we're done, so save the offset and stuff in a dummy value.
1689 pieceLenField = p;
1690 JDWP::Write4BE(&p, 0x55555555);
1691 needHeader = false;
1692 }
1693
1694 void Flush() {
1695 // Patch the "length of piece" field.
1696 CHECK_LE(&buf[0], pieceLenField);
1697 CHECK_LE(pieceLenField, p);
1698 JDWP::Set4BE(pieceLenField, totalAllocationUnits);
1699
1700 Dbg::DdmSendChunk(type, p - &buf[0], &buf[0]);
1701 Reset();
1702 }
1703
Elliott Hughesa2155262011-11-16 16:26:58 -08001704 static void HeapChunkCallback(const void* chunk_ptr, size_t chunk_len, const void* user_ptr, size_t user_len, void* arg) {
1705 reinterpret_cast<HeapChunkContext*>(arg)->HeapChunkCallback(chunk_ptr, chunk_len, user_ptr, user_len);
1706 }
1707
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001708 private:
Elliott Hughesa2155262011-11-16 16:26:58 -08001709 enum { ALLOCATION_UNIT_SIZE = 8 };
1710
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001711 void Reset() {
1712 p = &buf[0];
1713 totalAllocationUnits = 0;
1714 needHeader = true;
1715 pieceLenField = NULL;
1716 }
1717
Elliott Hughesa2155262011-11-16 16:26:58 -08001718 void HeapChunkCallback(const void* chunk_ptr, size_t chunk_len, const void* user_ptr, size_t user_len) {
1719 CHECK_EQ((chunk_len & (ALLOCATION_UNIT_SIZE-1)), 0U);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001720
Elliott Hughesa2155262011-11-16 16:26:58 -08001721 /* Make sure there's enough room left in the buffer.
1722 * We need to use two bytes for every fractional 256
1723 * allocation units used by the chunk.
1724 */
1725 {
1726 size_t needed = (((chunk_len/ALLOCATION_UNIT_SIZE + 255) / 256) * 2);
1727 size_t bytesLeft = buf.size() - (size_t)(p - &buf[0]);
1728 if (bytesLeft < needed) {
1729 Flush();
1730 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001731
Elliott Hughesa2155262011-11-16 16:26:58 -08001732 bytesLeft = buf.size() - (size_t)(p - &buf[0]);
1733 if (bytesLeft < needed) {
1734 LOG(WARNING) << "chunk is too big to transmit (chunk_len=" << chunk_len << ", " << needed << " bytes)";
1735 return;
1736 }
1737 }
1738
1739 // OLD-TODO: notice when there's a gap and start a new heap, or at least a new range.
1740 EnsureHeader(chunk_ptr);
1741
1742 // Determine the type of this chunk.
1743 // OLD-TODO: if context.merge, see if this chunk is different from the last chunk.
1744 // If it's the same, we should combine them.
1745 uint8_t state = ExamineObject(reinterpret_cast<const Object*>(user_ptr), (type == CHUNK_TYPE("NHSG")));
1746
1747 // Write out the chunk description.
1748 chunk_len /= ALLOCATION_UNIT_SIZE; // convert to allocation units
1749 totalAllocationUnits += chunk_len;
1750 while (chunk_len > 256) {
1751 *p++ = state | HPSG_PARTIAL;
1752 *p++ = 255; // length - 1
1753 chunk_len -= 256;
1754 }
1755 *p++ = state;
1756 *p++ = chunk_len - 1;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001757 }
1758
Elliott Hughesa2155262011-11-16 16:26:58 -08001759 uint8_t ExamineObject(const Object* o, bool is_native_heap) {
1760 if (o == NULL) {
1761 return HPSG_STATE(SOLIDITY_FREE, 0);
1762 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001763
Elliott Hughesa2155262011-11-16 16:26:58 -08001764 // It's an allocated chunk. Figure out what it is.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001765
Elliott Hughesa2155262011-11-16 16:26:58 -08001766 // If we're looking at the native heap, we'll just return
1767 // (SOLIDITY_HARD, KIND_NATIVE) for all allocated chunks.
1768 if (is_native_heap || !Heap::IsLiveObjectLocked(o)) {
1769 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
1770 }
1771
1772 Class* c = o->GetClass();
1773 if (c == NULL) {
1774 // The object was probably just created but hasn't been initialized yet.
1775 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
1776 }
1777
1778 if (!Heap::IsHeapAddress(c)) {
1779 LOG(WARNING) << "invalid class for managed heap object: " << o << " " << c;
1780 return HPSG_STATE(SOLIDITY_HARD, KIND_UNKNOWN);
1781 }
1782
1783 if (c->IsClassClass()) {
1784 return HPSG_STATE(SOLIDITY_HARD, KIND_CLASS_OBJECT);
1785 }
1786
1787 if (c->IsArrayClass()) {
1788 if (o->IsObjectArray()) {
1789 return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
1790 }
1791 switch (c->GetComponentSize()) {
1792 case 1: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_1);
1793 case 2: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_2);
1794 case 4: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
1795 case 8: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_8);
1796 }
1797 }
1798
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001799 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
1800 }
1801
Elliott Hughesa2155262011-11-16 16:26:58 -08001802 DISALLOW_COPY_AND_ASSIGN(HeapChunkContext);
1803};
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001804
1805void Dbg::DdmSendHeapSegments(bool native) {
1806 Dbg::HpsgWhen when;
1807 Dbg::HpsgWhat what;
1808 if (!native) {
1809 when = gDdmHpsgWhen;
1810 what = gDdmHpsgWhat;
1811 } else {
1812 when = gDdmNhsgWhen;
1813 what = gDdmNhsgWhat;
1814 }
1815 if (when == HPSG_WHEN_NEVER) {
1816 return;
1817 }
1818
1819 // Figure out what kind of chunks we'll be sending.
1820 CHECK(what == HPSG_WHAT_MERGED_OBJECTS || what == HPSG_WHAT_DISTINCT_OBJECTS) << static_cast<int>(what);
1821
1822 // First, send a heap start chunk.
1823 uint8_t heap_id[4];
1824 JDWP::Set4BE(&heap_id[0], 1); // Heap id (bogus; we only have one heap).
1825 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHST") : CHUNK_TYPE("HPST"), sizeof(heap_id), heap_id);
1826
1827 // Send a series of heap segment chunks.
Elliott Hughesa2155262011-11-16 16:26:58 -08001828 HeapChunkContext context((what == HPSG_WHAT_MERGED_OBJECTS), native);
1829 if (native) {
1830 dlmalloc_walk_heap(HeapChunkContext::HeapChunkCallback, &context);
1831 } else {
1832 Heap::WalkHeap(HeapChunkContext::HeapChunkCallback, &context);
1833 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001834
1835 // Finally, send a heap end chunk.
1836 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHEN") : CHUNK_TYPE("HPEN"), sizeof(heap_id), heap_id);
Elliott Hughes767a1472011-10-26 18:49:02 -07001837}
1838
Elliott Hughes545a0642011-11-08 19:10:03 -08001839void Dbg::SetAllocTrackingEnabled(bool enabled) {
1840 MutexLock mu(gAllocTrackerLock);
1841 if (enabled) {
1842 if (recent_allocation_records_ == NULL) {
1843 LOG(INFO) << "Enabling alloc tracker (" << kNumAllocRecords << " entries, "
1844 << kMaxAllocRecordStackDepth << " frames --> "
1845 << (sizeof(AllocRecord) * kNumAllocRecords) << " bytes)";
1846 gAllocRecordHead = gAllocRecordCount = 0;
1847 recent_allocation_records_ = new AllocRecord[kNumAllocRecords];
1848 CHECK(recent_allocation_records_ != NULL);
1849 }
1850 } else {
1851 delete[] recent_allocation_records_;
1852 recent_allocation_records_ = NULL;
1853 }
1854}
1855
1856struct AllocRecordStackVisitor : public Thread::StackVisitor {
1857 AllocRecordStackVisitor(AllocRecord* record) : record(record), depth(0) {
1858 }
1859
1860 virtual void VisitFrame(const Frame& f, uintptr_t pc) {
1861 if (depth >= kMaxAllocRecordStackDepth) {
1862 return;
1863 }
1864 Method* m = f.GetMethod();
1865 if (m == NULL || m->IsCalleeSaveMethod()) {
1866 return;
1867 }
1868 record->stack[depth].method = m;
1869 record->stack[depth].raw_pc = pc;
1870 ++depth;
1871 }
1872
1873 ~AllocRecordStackVisitor() {
1874 // Clear out any unused stack trace elements.
1875 for (; depth < kMaxAllocRecordStackDepth; ++depth) {
1876 record->stack[depth].method = NULL;
1877 record->stack[depth].raw_pc = 0;
1878 }
1879 }
1880
1881 AllocRecord* record;
1882 size_t depth;
1883};
1884
1885void Dbg::RecordAllocation(Class* type, size_t byte_count) {
1886 Thread* self = Thread::Current();
1887 CHECK(self != NULL);
1888
1889 MutexLock mu(gAllocTrackerLock);
1890 if (recent_allocation_records_ == NULL) {
1891 return;
1892 }
1893
1894 // Advance and clip.
1895 if (++gAllocRecordHead == kNumAllocRecords) {
1896 gAllocRecordHead = 0;
1897 }
1898
1899 // Fill in the basics.
1900 AllocRecord* record = &recent_allocation_records_[gAllocRecordHead];
1901 record->type = type;
1902 record->byte_count = byte_count;
1903 record->thin_lock_id = self->GetThinLockId();
1904
1905 // Fill in the stack trace.
1906 AllocRecordStackVisitor visitor(record);
1907 self->WalkStack(&visitor);
1908
1909 if (gAllocRecordCount < kNumAllocRecords) {
1910 ++gAllocRecordCount;
1911 }
1912}
1913
1914/*
1915 * Return the index of the head element.
1916 *
1917 * We point at the most-recently-written record, so if allocRecordCount is 1
1918 * we want to use the current element. Take "head+1" and subtract count
1919 * from it.
1920 *
1921 * We need to handle underflow in our circular buffer, so we add
1922 * kNumAllocRecords and then mask it back down.
1923 */
1924inline static int headIndex() {
1925 return (gAllocRecordHead+1 + kNumAllocRecords - gAllocRecordCount) & (kNumAllocRecords-1);
1926}
1927
1928void Dbg::DumpRecentAllocations() {
1929 MutexLock mu(gAllocTrackerLock);
1930 if (recent_allocation_records_ == NULL) {
1931 LOG(INFO) << "Not recording tracked allocations";
1932 return;
1933 }
1934
1935 // "i" is the head of the list. We want to start at the end of the
1936 // list and move forward to the tail.
1937 size_t i = headIndex();
1938 size_t count = gAllocRecordCount;
1939
1940 LOG(INFO) << "Tracked allocations, (head=" << gAllocRecordHead << " count=" << count << ")";
1941 while (count--) {
1942 AllocRecord* record = &recent_allocation_records_[i];
1943
1944 LOG(INFO) << StringPrintf(" T=%-2d %6d ", record->thin_lock_id, record->byte_count)
1945 << PrettyClass(record->type);
1946
1947 for (size_t stack_frame = 0; stack_frame < kMaxAllocRecordStackDepth; ++stack_frame) {
1948 const Method* m = record->stack[stack_frame].method;
1949 if (m == NULL) {
1950 break;
1951 }
1952 LOG(INFO) << " " << PrettyMethod(m) << " line " << record->stack[stack_frame].LineNumber();
1953 }
1954
1955 // pause periodically to help logcat catch up
1956 if ((count % 5) == 0) {
1957 usleep(40000);
1958 }
1959
1960 i = (i + 1) & (kNumAllocRecords-1);
1961 }
1962}
1963
1964class StringTable {
1965 public:
1966 StringTable() {
1967 }
1968
1969 void Add(const String* s) {
1970 table_.insert(s);
1971 }
1972
1973 size_t IndexOf(const String* s) {
1974 return std::distance(table_.begin(), table_.find(s));
1975 }
1976
1977 size_t Size() {
1978 return table_.size();
1979 }
1980
1981 void WriteTo(std::vector<uint8_t>& bytes) {
1982 typedef std::set<const String*>::const_iterator It; // TODO: C++0x auto
1983 for (It it = table_.begin(); it != table_.end(); ++it) {
1984 const String* s = *it;
1985 JDWP::AppendUtf16BE(bytes, s->GetCharArray()->GetData(), s->GetLength());
1986 }
1987 }
1988
1989 private:
1990 std::set<const String*> table_;
1991 DISALLOW_COPY_AND_ASSIGN(StringTable);
1992};
1993
1994/*
1995 * The data we send to DDMS contains everything we have recorded.
1996 *
1997 * Message header (all values big-endian):
1998 * (1b) message header len (to allow future expansion); includes itself
1999 * (1b) entry header len
2000 * (1b) stack frame len
2001 * (2b) number of entries
2002 * (4b) offset to string table from start of message
2003 * (2b) number of class name strings
2004 * (2b) number of method name strings
2005 * (2b) number of source file name strings
2006 * For each entry:
2007 * (4b) total allocation size
2008 * (2b) threadId
2009 * (2b) allocated object's class name index
2010 * (1b) stack depth
2011 * For each stack frame:
2012 * (2b) method's class name
2013 * (2b) method name
2014 * (2b) method source file
2015 * (2b) line number, clipped to 32767; -2 if native; -1 if no source
2016 * (xb) class name strings
2017 * (xb) method name strings
2018 * (xb) source file strings
2019 *
2020 * As with other DDM traffic, strings are sent as a 4-byte length
2021 * followed by UTF-16 data.
2022 *
2023 * We send up 16-bit unsigned indexes into string tables. In theory there
2024 * can be (kMaxAllocRecordStackDepth * kNumAllocRecords) unique strings in
2025 * each table, but in practice there should be far fewer.
2026 *
2027 * The chief reason for using a string table here is to keep the size of
2028 * the DDMS message to a minimum. This is partly to make the protocol
2029 * efficient, but also because we have to form the whole thing up all at
2030 * once in a memory buffer.
2031 *
2032 * We use separate string tables for class names, method names, and source
2033 * files to keep the indexes small. There will generally be no overlap
2034 * between the contents of these tables.
2035 */
2036jbyteArray Dbg::GetRecentAllocations() {
2037 if (false) {
2038 DumpRecentAllocations();
2039 }
2040
2041 MutexLock mu(gAllocTrackerLock);
2042
2043 /*
2044 * Part 1: generate string tables.
2045 */
2046 StringTable class_names;
2047 StringTable method_names;
2048 StringTable filenames;
2049
2050 int count = gAllocRecordCount;
2051 int idx = headIndex();
2052 while (count--) {
2053 AllocRecord* record = &recent_allocation_records_[idx];
2054
2055 class_names.Add(record->type->GetDescriptor());
2056
2057 for (size_t i = 0; i < kMaxAllocRecordStackDepth; i++) {
2058 const Method* m = record->stack[i].method;
2059 if (m != NULL) {
2060 class_names.Add(m->GetDeclaringClass()->GetDescriptor());
2061 method_names.Add(m->GetName());
2062 filenames.Add(m->GetDeclaringClass()->GetSourceFile());
2063 }
2064 }
2065
2066 idx = (idx + 1) & (kNumAllocRecords-1);
2067 }
2068
2069 LOG(INFO) << "allocation records: " << gAllocRecordCount;
2070
2071 /*
2072 * Part 2: allocate a buffer and generate the output.
2073 */
2074 std::vector<uint8_t> bytes;
2075
2076 // (1b) message header len (to allow future expansion); includes itself
2077 // (1b) entry header len
2078 // (1b) stack frame len
2079 const int kMessageHeaderLen = 15;
2080 const int kEntryHeaderLen = 9;
2081 const int kStackFrameLen = 8;
2082 JDWP::Append1BE(bytes, kMessageHeaderLen);
2083 JDWP::Append1BE(bytes, kEntryHeaderLen);
2084 JDWP::Append1BE(bytes, kStackFrameLen);
2085
2086 // (2b) number of entries
2087 // (4b) offset to string table from start of message
2088 // (2b) number of class name strings
2089 // (2b) number of method name strings
2090 // (2b) number of source file name strings
2091 JDWP::Append2BE(bytes, gAllocRecordCount);
2092 size_t string_table_offset = bytes.size();
2093 JDWP::Append4BE(bytes, 0); // We'll patch this later...
2094 JDWP::Append2BE(bytes, class_names.Size());
2095 JDWP::Append2BE(bytes, method_names.Size());
2096 JDWP::Append2BE(bytes, filenames.Size());
2097
2098 count = gAllocRecordCount;
2099 idx = headIndex();
2100 while (count--) {
2101 // For each entry:
2102 // (4b) total allocation size
2103 // (2b) thread id
2104 // (2b) allocated object's class name index
2105 // (1b) stack depth
2106 AllocRecord* record = &recent_allocation_records_[idx];
2107 size_t stack_depth = record->GetDepth();
2108 JDWP::Append4BE(bytes, record->byte_count);
2109 JDWP::Append2BE(bytes, record->thin_lock_id);
2110 JDWP::Append2BE(bytes, class_names.IndexOf(record->type->GetDescriptor()));
2111 JDWP::Append1BE(bytes, stack_depth);
2112
2113 for (size_t stack_frame = 0; stack_frame < stack_depth; ++stack_frame) {
2114 // For each stack frame:
2115 // (2b) method's class name
2116 // (2b) method name
2117 // (2b) method source file
2118 // (2b) line number, clipped to 32767; -2 if native; -1 if no source
2119 const Method* m = record->stack[stack_frame].method;
2120 JDWP::Append2BE(bytes, class_names.IndexOf(m->GetDeclaringClass()->GetDescriptor()));
2121 JDWP::Append2BE(bytes, method_names.IndexOf(m->GetName()));
2122 JDWP::Append2BE(bytes, filenames.IndexOf(m->GetDeclaringClass()->GetSourceFile()));
2123 JDWP::Append2BE(bytes, record->stack[stack_frame].LineNumber());
2124 }
2125
2126 idx = (idx + 1) & (kNumAllocRecords-1);
2127 }
2128
2129 // (xb) class name strings
2130 // (xb) method name strings
2131 // (xb) source file strings
2132 JDWP::Set4BE(&bytes[string_table_offset], bytes.size());
2133 class_names.WriteTo(bytes);
2134 method_names.WriteTo(bytes);
2135 filenames.WriteTo(bytes);
2136
2137 JNIEnv* env = Thread::Current()->GetJniEnv();
2138 jbyteArray result = env->NewByteArray(bytes.size());
2139 if (result != NULL) {
2140 env->SetByteArrayRegion(result, 0, bytes.size(), reinterpret_cast<const jbyte*>(&bytes[0]));
2141 }
2142 return result;
2143}
2144
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002145} // namespace art