blob: c95d64abc00c5149299ce7fd02ffdaaf156a3baa [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 Hughes68fdbd02011-11-29 19:22:47 -080024#include "context.h"
Elliott Hughes6a5bd492011-10-28 14:33:57 -070025#include "ScopedLocalRef.h"
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -070026#include "ScopedPrimitiveArray.h"
Elliott Hughes47fce012011-10-25 18:37:19 -070027#include "stack_indirect_reference_table.h"
Elliott Hughes475fc232011-10-25 15:00:35 -070028#include "thread_list.h"
29
Elliott Hughes6a5bd492011-10-28 14:33:57 -070030extern "C" void dlmalloc_walk_heap(void(*)(const void*, size_t, const void*, size_t, void*), void*);
31#ifndef HAVE_ANDROID_OS
32void dlmalloc_walk_heap(void(*)(const void*, size_t, const void*, size_t, void*), void*) {
33 // No-op for glibc.
34}
35#endif
36
Elliott Hughes872d4ec2011-10-21 17:07:15 -070037namespace art {
38
Elliott Hughes545a0642011-11-08 19:10:03 -080039static const size_t kMaxAllocRecordStackDepth = 16; // Max 255.
40static const size_t kNumAllocRecords = 512; // Must be power of 2.
41
Elliott Hughes475fc232011-10-25 15:00:35 -070042class ObjectRegistry {
43 public:
44 ObjectRegistry() : lock_("ObjectRegistry lock") {
45 }
46
47 JDWP::ObjectId Add(Object* o) {
48 if (o == NULL) {
49 return 0;
50 }
51 JDWP::ObjectId id = static_cast<JDWP::ObjectId>(reinterpret_cast<uintptr_t>(o));
52 MutexLock mu(lock_);
53 map_[id] = o;
54 return id;
55 }
56
Elliott Hughes234ab152011-10-26 14:02:26 -070057 void Clear() {
58 MutexLock mu(lock_);
59 LOG(DEBUG) << "Debugger has detached; object registry had " << map_.size() << " entries";
60 map_.clear();
61 }
62
Elliott Hughes475fc232011-10-25 15:00:35 -070063 bool Contains(JDWP::ObjectId id) {
64 MutexLock mu(lock_);
65 return map_.find(id) != map_.end();
66 }
67
Elliott Hughesa2155262011-11-16 16:26:58 -080068 template<typename T> T Get(JDWP::ObjectId id) {
69 MutexLock mu(lock_);
70 typedef std::map<JDWP::ObjectId, Object*>::iterator It; // C++0x auto
71 It it = map_.find(id);
72 return (it != map_.end()) ? reinterpret_cast<T>(it->second) : NULL;
73 }
74
Elliott Hughesbfe487b2011-10-26 15:48:55 -070075 void VisitRoots(Heap::RootVisitor* visitor, void* arg) {
76 MutexLock mu(lock_);
77 typedef std::map<JDWP::ObjectId, Object*>::iterator It; // C++0x auto
78 for (It it = map_.begin(); it != map_.end(); ++it) {
79 visitor(it->second, arg);
80 }
81 }
82
Elliott Hughes475fc232011-10-25 15:00:35 -070083 private:
84 Mutex lock_;
85 std::map<JDWP::ObjectId, Object*> map_;
86};
87
Elliott Hughes545a0642011-11-08 19:10:03 -080088struct AllocRecordStackTraceElement {
89 const Method* method;
90 uintptr_t raw_pc;
91
92 int32_t LineNumber() const {
93 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
94 Class* c = method->GetDeclaringClass();
95 DexCache* dex_cache = c->GetDexCache();
96 const DexFile& dex_file = class_linker->FindDexFile(dex_cache);
97 return dex_file.GetLineNumFromPC(method, method->ToDexPC(raw_pc));
98 }
99};
100
101struct AllocRecord {
102 Class* type;
103 size_t byte_count;
104 uint16_t thin_lock_id;
105 AllocRecordStackTraceElement stack[kMaxAllocRecordStackDepth]; // Unused entries have NULL method.
106
107 size_t GetDepth() {
108 size_t depth = 0;
109 while (depth < kMaxAllocRecordStackDepth && stack[depth].method != NULL) {
110 ++depth;
111 }
112 return depth;
113 }
114};
115
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700116// JDWP is allowed unless the Zygote forbids it.
117static bool gJdwpAllowed = true;
118
Elliott Hughes3bb81562011-10-21 18:52:59 -0700119// Was there a -Xrunjdwp or -agent argument on the command-line?
120static bool gJdwpConfigured = false;
121
122// Broken-down JDWP options. (Only valid if gJdwpConfigured is true.)
Elliott Hughes376a7a02011-10-24 18:35:55 -0700123static JDWP::JdwpOptions gJdwpOptions;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700124
125// Runtime JDWP state.
126static JDWP::JdwpState* gJdwpState = NULL;
127static bool gDebuggerConnected; // debugger or DDMS is connected.
128static bool gDebuggerActive; // debugger is making requests.
129
Elliott Hughes47fce012011-10-25 18:37:19 -0700130static bool gDdmThreadNotification = false;
131
Elliott Hughes767a1472011-10-26 18:49:02 -0700132// DDMS GC-related settings.
133static Dbg::HpifWhen gDdmHpifWhen = Dbg::HPIF_WHEN_NEVER;
134static Dbg::HpsgWhen gDdmHpsgWhen = Dbg::HPSG_WHEN_NEVER;
135static Dbg::HpsgWhat gDdmHpsgWhat;
136static Dbg::HpsgWhen gDdmNhsgWhen = Dbg::HPSG_WHEN_NEVER;
137static Dbg::HpsgWhat gDdmNhsgWhat;
138
Elliott Hughes475fc232011-10-25 15:00:35 -0700139static ObjectRegistry* gRegistry = NULL;
140
Elliott Hughes545a0642011-11-08 19:10:03 -0800141// Recent allocation tracking.
142static Mutex gAllocTrackerLock("AllocTracker lock");
143AllocRecord* Dbg::recent_allocation_records_ = NULL; // TODO: CircularBuffer<AllocRecord>
144static size_t gAllocRecordHead = 0;
145static size_t gAllocRecordCount = 0;
146
Elliott Hughes24437992011-11-30 14:49:33 -0800147static JDWP::JdwpTag BasicTagFromDescriptor(const char* descriptor) {
148 // JDWP deliberately uses the descriptor characters' ASCII values for its enum.
149 // Note that by "basic" we mean that we don't get more specific than JT_OBJECT.
150 return static_cast<JDWP::JdwpTag>(descriptor[0]);
151}
152
153static JDWP::JdwpTag TagFromClass(Class* c) {
154 if (c->IsArrayClass()) {
155 return JDWP::JT_ARRAY;
156 }
157
158 if (c->IsStringClass()) {
159 return JDWP::JT_STRING;
160 } else if (c->IsClassClass()) {
161 return JDWP::JT_CLASS_OBJECT;
162#if 0 // TODO
163 } else if (dvmInstanceof(clazz, gDvm.classJavaLangThread)) {
164 return JDWP::JT_THREAD;
165 } else if (dvmInstanceof(clazz, gDvm.classJavaLangThreadGroup)) {
166 return JDWP::JT_THREAD_GROUP;
167 } else if (dvmInstanceof(clazz, gDvm.classJavaLangClassLoader)) {
168 return JDWP::JT_CLASS_LOADER;
169#endif
170 } else {
171 return JDWP::JT_OBJECT;
172 }
173}
174
175/*
176 * Objects declared to hold Object might actually hold a more specific
177 * type. The debugger may take a special interest in these (e.g. it
178 * wants to display the contents of Strings), so we want to return an
179 * appropriate tag.
180 *
181 * Null objects are tagged JT_OBJECT.
182 */
183static JDWP::JdwpTag TagFromObject(const Object* o) {
184 return (o == NULL) ? JDWP::JT_OBJECT : TagFromClass(o->GetClass());
185}
186
187static bool IsPrimitiveTag(JDWP::JdwpTag tag) {
188 switch (tag) {
189 case JDWP::JT_BOOLEAN:
190 case JDWP::JT_BYTE:
191 case JDWP::JT_CHAR:
192 case JDWP::JT_FLOAT:
193 case JDWP::JT_DOUBLE:
194 case JDWP::JT_INT:
195 case JDWP::JT_LONG:
196 case JDWP::JT_SHORT:
197 case JDWP::JT_VOID:
198 return true;
199 default:
200 return false;
201 }
202}
203
Elliott Hughes3bb81562011-10-21 18:52:59 -0700204/*
205 * Handle one of the JDWP name/value pairs.
206 *
207 * JDWP options are:
208 * help: if specified, show help message and bail
209 * transport: may be dt_socket or dt_shmem
210 * address: for dt_socket, "host:port", or just "port" when listening
211 * server: if "y", wait for debugger to attach; if "n", attach to debugger
212 * timeout: how long to wait for debugger to connect / listen
213 *
214 * Useful with server=n (these aren't supported yet):
215 * onthrow=<exception-name>: connect to debugger when exception thrown
216 * onuncaught=y|n: connect to debugger when uncaught exception thrown
217 * launch=<command-line>: launch the debugger itself
218 *
219 * The "transport" option is required, as is "address" if server=n.
220 */
221static bool ParseJdwpOption(const std::string& name, const std::string& value) {
222 if (name == "transport") {
223 if (value == "dt_socket") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700224 gJdwpOptions.transport = JDWP::kJdwpTransportSocket;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700225 } else if (value == "dt_android_adb") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700226 gJdwpOptions.transport = JDWP::kJdwpTransportAndroidAdb;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700227 } else {
228 LOG(ERROR) << "JDWP transport not supported: " << value;
229 return false;
230 }
231 } else if (name == "server") {
232 if (value == "n") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700233 gJdwpOptions.server = false;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700234 } else if (value == "y") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700235 gJdwpOptions.server = true;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700236 } else {
237 LOG(ERROR) << "JDWP option 'server' must be 'y' or 'n'";
238 return false;
239 }
240 } else if (name == "suspend") {
241 if (value == "n") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700242 gJdwpOptions.suspend = false;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700243 } else if (value == "y") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700244 gJdwpOptions.suspend = true;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700245 } else {
246 LOG(ERROR) << "JDWP option 'suspend' must be 'y' or 'n'";
247 return false;
248 }
249 } else if (name == "address") {
250 /* this is either <port> or <host>:<port> */
251 std::string port_string;
Elliott Hughes376a7a02011-10-24 18:35:55 -0700252 gJdwpOptions.host.clear();
Elliott Hughes3bb81562011-10-21 18:52:59 -0700253 std::string::size_type colon = value.find(':');
254 if (colon != std::string::npos) {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700255 gJdwpOptions.host = value.substr(0, colon);
Elliott Hughes3bb81562011-10-21 18:52:59 -0700256 port_string = value.substr(colon + 1);
257 } else {
258 port_string = value;
259 }
260 if (port_string.empty()) {
261 LOG(ERROR) << "JDWP address missing port: " << value;
262 return false;
263 }
264 char* end;
265 long port = strtol(port_string.c_str(), &end, 10);
266 if (*end != '\0') {
267 LOG(ERROR) << "JDWP address has junk in port field: " << value;
268 return false;
269 }
Elliott Hughes376a7a02011-10-24 18:35:55 -0700270 gJdwpOptions.port = port;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700271 } else if (name == "launch" || name == "onthrow" || name == "oncaught" || name == "timeout") {
272 /* valid but unsupported */
273 LOG(INFO) << "Ignoring JDWP option '" << name << "'='" << value << "'";
274 } else {
275 LOG(INFO) << "Ignoring unrecognized JDWP option '" << name << "'='" << value << "'";
276 }
277
278 return true;
279}
280
281/*
282 * Parse the latter half of a -Xrunjdwp/-agentlib:jdwp= string, e.g.:
283 * "transport=dt_socket,address=8000,server=y,suspend=n"
284 */
285bool Dbg::ParseJdwpOptions(const std::string& options) {
Elliott Hughes47fce012011-10-25 18:37:19 -0700286 LOG(VERBOSE) << "ParseJdwpOptions: " << options;
287
Elliott Hughes3bb81562011-10-21 18:52:59 -0700288 std::vector<std::string> pairs;
289 Split(options, ',', pairs);
290
291 for (size_t i = 0; i < pairs.size(); ++i) {
292 std::string::size_type equals = pairs[i].find('=');
293 if (equals == std::string::npos) {
294 LOG(ERROR) << "Can't parse JDWP option '" << pairs[i] << "' in '" << options << "'";
295 return false;
296 }
297 ParseJdwpOption(pairs[i].substr(0, equals), pairs[i].substr(equals + 1));
298 }
299
Elliott Hughes376a7a02011-10-24 18:35:55 -0700300 if (gJdwpOptions.transport == JDWP::kJdwpTransportUnknown) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700301 LOG(ERROR) << "Must specify JDWP transport: " << options;
302 }
Elliott Hughes376a7a02011-10-24 18:35:55 -0700303 if (!gJdwpOptions.server && (gJdwpOptions.host.empty() || gJdwpOptions.port == 0)) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700304 LOG(ERROR) << "Must specify JDWP host and port when server=n: " << options;
305 return false;
306 }
307
308 gJdwpConfigured = true;
309 return true;
310}
311
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700312void Dbg::StartJdwp() {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700313 if (!gJdwpAllowed || !gJdwpConfigured) {
314 // No JDWP for you!
315 return;
316 }
317
Elliott Hughes475fc232011-10-25 15:00:35 -0700318 CHECK(gRegistry == NULL);
319 gRegistry = new ObjectRegistry;
320
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700321 // Init JDWP if the debugger is enabled. This may connect out to a
322 // debugger, passively listen for a debugger, or block waiting for a
323 // debugger.
Elliott Hughes376a7a02011-10-24 18:35:55 -0700324 gJdwpState = JDWP::JdwpState::Create(&gJdwpOptions);
325 if (gJdwpState == NULL) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -0800326 // We probably failed because some other process has the port already, which means that
327 // if we don't abort the user is likely to think they're talking to us when they're actually
328 // talking to that other process.
329 LOG(FATAL) << "debugger thread failed to initialize";
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700330 }
331
332 // If a debugger has already attached, send the "welcome" message.
333 // This may cause us to suspend all threads.
Elliott Hughes376a7a02011-10-24 18:35:55 -0700334 if (gJdwpState->IsActive()) {
Elliott Hughesa2155262011-11-16 16:26:58 -0800335 //ScopedThreadStateChange tsc(Thread::Current(), Thread::kRunnable);
Elliott Hughes376a7a02011-10-24 18:35:55 -0700336 if (!gJdwpState->PostVMStart()) {
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700337 LOG(WARNING) << "failed to post 'start' message to debugger";
338 }
339 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700340}
341
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700342void Dbg::StopJdwp() {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700343 delete gJdwpState;
Elliott Hughes475fc232011-10-25 15:00:35 -0700344 delete gRegistry;
345 gRegistry = NULL;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700346}
347
Elliott Hughes767a1472011-10-26 18:49:02 -0700348void Dbg::GcDidFinish() {
349 if (gDdmHpifWhen != HPIF_WHEN_NEVER) {
350 LOG(DEBUG) << "Sending VM heap info to DDM";
Elliott Hughes7162ad92011-10-27 14:08:42 -0700351 DdmSendHeapInfo(gDdmHpifWhen);
Elliott Hughes767a1472011-10-26 18:49:02 -0700352 }
353 if (gDdmHpsgWhen != HPSG_WHEN_NEVER) {
354 LOG(DEBUG) << "Dumping VM heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700355 DdmSendHeapSegments(false);
Elliott Hughes767a1472011-10-26 18:49:02 -0700356 }
357 if (gDdmNhsgWhen != HPSG_WHEN_NEVER) {
358 LOG(DEBUG) << "Dumping native heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700359 DdmSendHeapSegments(true);
Elliott Hughes767a1472011-10-26 18:49:02 -0700360 }
361}
362
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700363void Dbg::SetJdwpAllowed(bool allowed) {
364 gJdwpAllowed = allowed;
365}
366
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700367DebugInvokeReq* Dbg::GetInvokeReq() {
Elliott Hughes475fc232011-10-25 15:00:35 -0700368 return Thread::Current()->GetInvokeReq();
369}
370
371Thread* Dbg::GetDebugThread() {
372 return (gJdwpState != NULL) ? gJdwpState->GetDebugThread() : NULL;
373}
374
375void Dbg::ClearWaitForEventThread() {
376 gJdwpState->ClearWaitForEventThread();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700377}
378
379void Dbg::Connected() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700380 CHECK(!gDebuggerConnected);
381 LOG(VERBOSE) << "JDWP has attached";
382 gDebuggerConnected = true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700383}
384
Elliott Hughesa2155262011-11-16 16:26:58 -0800385void Dbg::GoActive() {
386 // Enable all debugging features, including scans for breakpoints.
387 // This is a no-op if we're already active.
388 // Only called from the JDWP handler thread.
389 if (gDebuggerActive) {
390 return;
391 }
392
393 LOG(INFO) << "Debugger is active";
394
395 // TODO: CHECK we don't have any outstanding breakpoints.
396
397 gDebuggerActive = true;
398
399 //dvmEnableAllSubMode(kSubModeDebuggerActive);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700400}
401
402void Dbg::Disconnected() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700403 CHECK(gDebuggerConnected);
404
405 gDebuggerActive = false;
406
407 //dvmDisableAllSubMode(kSubModeDebuggerActive);
408
409 gRegistry->Clear();
410 gDebuggerConnected = false;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700411}
412
413bool Dbg::IsDebuggerConnected() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700414 return gDebuggerActive;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700415}
416
417bool Dbg::IsDebuggingEnabled() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700418 return gJdwpConfigured;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700419}
420
421int64_t Dbg::LastDebuggerActivity() {
422 UNIMPLEMENTED(WARNING);
423 return -1;
424}
425
426int Dbg::ThreadRunning() {
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700427 return static_cast<int>(Thread::Current()->SetState(Thread::kRunnable));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700428}
429
430int Dbg::ThreadWaiting() {
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700431 return static_cast<int>(Thread::Current()->SetState(Thread::kVmWait));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700432}
433
Elliott Hughes6ba581a2011-10-25 11:45:35 -0700434int Dbg::ThreadContinuing(int new_state) {
435 return static_cast<int>(Thread::Current()->SetState(static_cast<Thread::State>(new_state)));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700436}
437
438void Dbg::UndoDebuggerSuspensions() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700439 Runtime::Current()->GetThreadList()->UndoDebuggerSuspensions();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700440}
441
442void Dbg::Exit(int status) {
443 UNIMPLEMENTED(FATAL);
444}
445
Elliott Hughesbfe487b2011-10-26 15:48:55 -0700446void Dbg::VisitRoots(Heap::RootVisitor* visitor, void* arg) {
447 if (gRegistry != NULL) {
448 gRegistry->VisitRoots(visitor, arg);
449 }
450}
451
Elliott Hughesa2155262011-11-16 16:26:58 -0800452std::string Dbg::GetClassDescriptor(JDWP::RefTypeId classId) {
453 Class* c = gRegistry->Get<Class*>(classId);
454 return c->GetDescriptor()->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700455}
456
457JDWP::ObjectId Dbg::GetClassObject(JDWP::RefTypeId id) {
458 UNIMPLEMENTED(FATAL);
459 return 0;
460}
461
462JDWP::RefTypeId Dbg::GetSuperclass(JDWP::RefTypeId id) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800463 Class* c = gRegistry->Get<Class*>(id);
464 return gRegistry->Add(c->GetSuperClass());
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700465}
466
467JDWP::ObjectId Dbg::GetClassLoader(JDWP::RefTypeId id) {
468 UNIMPLEMENTED(FATAL);
469 return 0;
470}
471
472uint32_t Dbg::GetAccessFlags(JDWP::RefTypeId id) {
473 UNIMPLEMENTED(FATAL);
474 return 0;
475}
476
477bool Dbg::IsInterface(JDWP::RefTypeId id) {
478 UNIMPLEMENTED(FATAL);
479 return false;
480}
481
Elliott Hughesa2155262011-11-16 16:26:58 -0800482void Dbg::GetClassList(uint32_t* pClassCount, JDWP::RefTypeId** pClasses) {
483 // Get the complete list of reference classes (i.e. all classes except
484 // the primitive types).
485 // Returns a newly-allocated buffer full of RefTypeId values.
486 struct ClassListCreator {
487 static bool Visit(Class* c, void* arg) {
488 return reinterpret_cast<ClassListCreator*>(arg)->Visit(c);
489 }
490
491 bool Visit(Class* c) {
492 if (!c->IsPrimitive()) {
493 classes.push_back(static_cast<JDWP::RefTypeId>(gRegistry->Add(c)));
494 }
495 return true;
496 }
497
498 std::vector<JDWP::RefTypeId> classes;
499 };
500
501 ClassListCreator clc;
502 Runtime::Current()->GetClassLinker()->VisitClasses(ClassListCreator::Visit, &clc);
503 *pClassCount = clc.classes.size();
504 *pClasses = new JDWP::RefTypeId[clc.classes.size()];
505 for (size_t i = 0; i < clc.classes.size(); ++i) {
506 (*pClasses)[i] = clc.classes[i];
507 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700508}
509
510void Dbg::GetVisibleClassList(JDWP::ObjectId classLoaderId, uint32_t* pNumClasses, JDWP::RefTypeId** pClassRefBuf) {
511 UNIMPLEMENTED(FATAL);
512}
513
Elliott Hughesa2155262011-11-16 16:26:58 -0800514void Dbg::GetClassInfo(JDWP::RefTypeId classId, uint8_t* pTypeTag, uint32_t* pStatus, std::string* pDescriptor) {
515 Class* c = gRegistry->Get<Class*>(classId);
516 if (c->IsArrayClass()) {
517 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
518 *pTypeTag = JDWP::TT_ARRAY;
519 } else {
520 if (c->IsErroneous()) {
521 *pStatus = JDWP::CS_ERROR;
522 } else {
523 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED | JDWP::CS_INITIALIZED;
524 }
525 *pTypeTag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
526 }
527
528 if (pDescriptor != NULL) {
529 *pDescriptor = c->GetDescriptor()->ToModifiedUtf8();
530 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700531}
532
533bool Dbg::FindLoadedClassBySignature(const char* classDescriptor, JDWP::RefTypeId* pRefTypeId) {
534 UNIMPLEMENTED(FATAL);
535 return false;
536}
537
538void Dbg::GetObjectType(JDWP::ObjectId objectId, uint8_t* pRefTypeTag, JDWP::RefTypeId* pRefTypeId) {
Elliott Hughes499c5132011-11-17 14:55:11 -0800539 Object* o = gRegistry->Get<Object*>(objectId);
540 if (o->GetClass()->IsArrayClass()) {
541 *pRefTypeTag = JDWP::TT_ARRAY;
542 } else if (o->GetClass()->IsInterface()) {
543 *pRefTypeTag = JDWP::TT_INTERFACE;
544 } else {
545 *pRefTypeTag = JDWP::TT_CLASS;
546 }
547 *pRefTypeId = gRegistry->Add(o->GetClass());
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700548}
549
550uint8_t Dbg::GetClassObjectType(JDWP::RefTypeId refTypeId) {
551 UNIMPLEMENTED(FATAL);
552 return 0;
553}
554
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800555std::string Dbg::GetSignature(JDWP::RefTypeId refTypeId) {
556 Class* c = gRegistry->Get<Class*>(refTypeId);
557 CHECK(c != NULL);
558 return c->GetDescriptor()->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700559}
560
Elliott Hughes03181a82011-11-17 17:22:21 -0800561bool Dbg::GetSourceFile(JDWP::RefTypeId refTypeId, std::string& result) {
562 Class* c = gRegistry->Get<Class*>(refTypeId);
563 CHECK(c != NULL);
564
565 String* source_file = c->GetSourceFile();
566 if (source_file == NULL) {
567 return false;
568 }
569 result = source_file->ToModifiedUtf8();
570 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700571}
572
573const char* Dbg::GetObjectTypeName(JDWP::ObjectId objectId) {
574 UNIMPLEMENTED(FATAL);
575 return NULL;
576}
577
578uint8_t Dbg::GetObjectTag(JDWP::ObjectId objectId) {
Elliott Hughes24437992011-11-30 14:49:33 -0800579 Object* o = gRegistry->Get<Object*>(objectId);
580 return TagFromObject(o);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700581}
582
Elliott Hughesdbb40792011-11-18 17:05:22 -0800583size_t Dbg::GetTagWidth(int tag) {
584 switch (tag) {
585 case JDWP::JT_VOID:
586 return 0;
587 case JDWP::JT_BYTE:
588 case JDWP::JT_BOOLEAN:
589 return 1;
590 case JDWP::JT_CHAR:
591 case JDWP::JT_SHORT:
592 return 2;
593 case JDWP::JT_FLOAT:
594 case JDWP::JT_INT:
595 return 4;
596 case JDWP::JT_ARRAY:
597 case JDWP::JT_OBJECT:
598 case JDWP::JT_STRING:
599 case JDWP::JT_THREAD:
600 case JDWP::JT_THREAD_GROUP:
601 case JDWP::JT_CLASS_LOADER:
602 case JDWP::JT_CLASS_OBJECT:
603 return sizeof(JDWP::ObjectId);
604 case JDWP::JT_DOUBLE:
605 case JDWP::JT_LONG:
606 return 8;
607 default:
608 LOG(FATAL) << "unknown tag " << tag;
609 return -1;
610 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700611}
612
613int Dbg::GetArrayLength(JDWP::ObjectId arrayId) {
Elliott Hughes68fdbd02011-11-29 19:22:47 -0800614 Object* o = gRegistry->Get<Object*>(arrayId);
615 Array* a = o->AsArray();
616 return a->GetLength();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700617}
618
619uint8_t Dbg::GetArrayElementTag(JDWP::ObjectId arrayId) {
Elliott Hughes24437992011-11-30 14:49:33 -0800620 Object* o = gRegistry->Get<Object*>(arrayId);
621 Array* a = o->AsArray();
622 std::string descriptor(a->GetClass()->GetDescriptor()->ToModifiedUtf8());
623 JDWP::JdwpTag tag = BasicTagFromDescriptor(descriptor.c_str() + 1);
624 if (!IsPrimitiveTag(tag)) {
625 tag = TagFromClass(a->GetClass()->GetComponentType());
626 }
627 return tag;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700628}
629
Elliott Hughes24437992011-11-30 14:49:33 -0800630bool Dbg::OutputArray(JDWP::ObjectId arrayId, int offset, int count, JDWP::ExpandBuf* pReply) {
631 Object* o = gRegistry->Get<Object*>(arrayId);
632 Array* a = o->AsArray();
633
634 if (offset < 0 || count < 0 || offset > a->GetLength() || a->GetLength() - offset < count) {
635 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
636 return false;
637 }
638
639 std::string descriptor(a->GetClass()->GetDescriptor()->ToModifiedUtf8());
640 JDWP::JdwpTag tag = BasicTagFromDescriptor(descriptor.c_str() + 1);
641
642 if (IsPrimitiveTag(tag)) {
643 size_t width = GetTagWidth(tag);
644 const uint8_t* src = reinterpret_cast<uint8_t*>(a->GetRawData());
645 uint8_t* dst = expandBufAddSpace(pReply, count * width);
646 if (width == 8) {
647 const uint64_t* src8 = reinterpret_cast<const uint64_t*>(src);
648 for (int i = 0; i < count; ++i) JDWP::Write8BE(&dst, src8[offset + i]);
649 } else if (width == 4) {
650 const uint32_t* src4 = reinterpret_cast<const uint32_t*>(src);
651 for (int i = 0; i < count; ++i) JDWP::Write4BE(&dst, src4[offset + i]);
652 } else if (width == 2) {
653 const uint16_t* src2 = reinterpret_cast<const uint16_t*>(src);
654 for (int i = 0; i < count; ++i) JDWP::Write2BE(&dst, src2[offset + i]);
655 } else {
656 memcpy(dst, &src[offset * width], count * width);
657 }
658 } else {
659 ObjectArray<Object>* oa = a->AsObjectArray<Object>();
660 for (int i = 0; i < count; ++i) {
661 Object* element = oa->Get(i);
662 JDWP::JdwpTag specific_tag = (element != NULL) ? TagFromObject(element) : tag;
663 expandBufAdd1(pReply, specific_tag);
664 expandBufAddObjectId(pReply, gRegistry->Add(element));
665 }
666 }
667
668 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700669}
670
671bool Dbg::SetArrayElements(JDWP::ObjectId arrayId, int firstIndex, int count, const uint8_t* buf) {
672 UNIMPLEMENTED(FATAL);
673 return false;
674}
675
676JDWP::ObjectId Dbg::CreateString(const char* str) {
677 UNIMPLEMENTED(FATAL);
678 return 0;
679}
680
681JDWP::ObjectId Dbg::CreateObject(JDWP::RefTypeId classId) {
682 UNIMPLEMENTED(FATAL);
683 return 0;
684}
685
686JDWP::ObjectId Dbg::CreateArrayObject(JDWP::RefTypeId arrayTypeId, uint32_t length) {
687 UNIMPLEMENTED(FATAL);
688 return 0;
689}
690
691bool Dbg::MatchType(JDWP::RefTypeId instClassId, JDWP::RefTypeId classId) {
692 UNIMPLEMENTED(FATAL);
693 return false;
694}
695
Elliott Hughes03181a82011-11-17 17:22:21 -0800696JDWP::FieldId ToFieldId(Field* f) {
697#ifdef MOVING_GARBAGE_COLLECTOR
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700698 UNIMPLEMENTED(FATAL);
Elliott Hughes03181a82011-11-17 17:22:21 -0800699#else
700 return static_cast<JDWP::FieldId>(reinterpret_cast<uintptr_t>(f));
701#endif
702}
703
704JDWP::MethodId ToMethodId(Method* m) {
705#ifdef MOVING_GARBAGE_COLLECTOR
706 UNIMPLEMENTED(FATAL);
707#else
708 return static_cast<JDWP::MethodId>(reinterpret_cast<uintptr_t>(m));
709#endif
710}
711
712Method* FromMethodId(JDWP::MethodId mid) {
713#ifdef MOVING_GARBAGE_COLLECTOR
714 UNIMPLEMENTED(FATAL);
715#else
716 return reinterpret_cast<Method*>(static_cast<uintptr_t>(mid));
717#endif
718}
719
720std::string Dbg::GetMethodName(JDWP::RefTypeId refTypeId, JDWP::MethodId methodId) {
721 return FromMethodId(methodId)->GetName()->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700722}
723
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800724/*
725 * Augment the access flags for synthetic methods and fields by setting
726 * the (as described by the spec) "0xf0000000 bit". Also, strip out any
727 * flags not specified by the Java programming language.
728 */
729static uint32_t MangleAccessFlags(uint32_t accessFlags) {
730 accessFlags &= kAccJavaFlagsMask;
731 if ((accessFlags & kAccSynthetic) != 0) {
732 accessFlags |= 0xf0000000;
733 }
734 return accessFlags;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700735}
736
Elliott Hughesdbb40792011-11-18 17:05:22 -0800737static const uint16_t kEclipseWorkaroundSlot = 1000;
738
739/*
740 * Eclipse appears to expect that the "this" reference is in slot zero.
741 * If it's not, the "variables" display will show two copies of "this",
742 * possibly because it gets "this" from SF.ThisObject and then displays
743 * all locals with nonzero slot numbers.
744 *
745 * So, we remap the item in slot 0 to 1000, and remap "this" to zero. On
746 * SF.GetValues / SF.SetValues we map them back.
Elliott Hughesc5b734a2011-12-01 17:20:58 -0800747 *
748 * TODO: jdb uses the value to determine whether a variable is a local or an argument,
749 * by checking whether it's less than the number of arguments. To make that work, we'd
750 * have to "mangle" all the arguments to come first, not just the implicit argument 'this'.
Elliott Hughesdbb40792011-11-18 17:05:22 -0800751 */
752static uint16_t MangleSlot(uint16_t slot, const char* name) {
753 uint16_t newSlot = slot;
754 if (strcmp(name, "this") == 0) {
755 newSlot = 0;
756 } else if (slot == 0) {
757 newSlot = kEclipseWorkaroundSlot;
758 }
759 return newSlot;
760}
761
Elliott Hughes68fdbd02011-11-29 19:22:47 -0800762static uint16_t DemangleSlot(uint16_t slot, Frame& f) {
Elliott Hughesdbb40792011-11-18 17:05:22 -0800763 if (slot == kEclipseWorkaroundSlot) {
Elliott Hughes68fdbd02011-11-29 19:22:47 -0800764 return 0;
Elliott Hughesdbb40792011-11-18 17:05:22 -0800765 } else if (slot == 0) {
Elliott Hughesdbb40792011-11-18 17:05:22 -0800766 Method* m = f.GetMethod();
Elliott Hughes68fdbd02011-11-29 19:22:47 -0800767 return m->NumRegisters() - m->NumIns();
Elliott Hughesdbb40792011-11-18 17:05:22 -0800768 }
Elliott Hughes68fdbd02011-11-29 19:22:47 -0800769 return slot;
Elliott Hughesdbb40792011-11-18 17:05:22 -0800770}
771
Elliott Hughesc5b734a2011-12-01 17:20:58 -0800772void Dbg::OutputDeclaredFields(JDWP::RefTypeId refTypeId, bool with_generic, JDWP::ExpandBuf* pReply) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800773 Class* c = gRegistry->Get<Class*>(refTypeId);
774 CHECK(c != NULL);
775
776 size_t instance_field_count = c->NumInstanceFields();
777 size_t static_field_count = c->NumStaticFields();
778
779 expandBufAdd4BE(pReply, instance_field_count + static_field_count);
780
781 for (size_t i = 0; i < instance_field_count + static_field_count; ++i) {
782 Field* f = (i < instance_field_count) ? c->GetInstanceField(i) : c->GetStaticField(i - instance_field_count);
783
784 expandBufAddFieldId(pReply, ToFieldId(f));
785 expandBufAddUtf8String(pReply, f->GetName()->ToModifiedUtf8().c_str());
786 expandBufAddUtf8String(pReply, f->GetTypeDescriptor());
Elliott Hughesc5b734a2011-12-01 17:20:58 -0800787 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800788 static const char genericSignature[1] = "";
789 expandBufAddUtf8String(pReply, genericSignature);
790 }
791 expandBufAdd4BE(pReply, MangleAccessFlags(f->GetAccessFlags()));
792 }
793}
794
Elliott Hughesc5b734a2011-12-01 17:20:58 -0800795void Dbg::OutputDeclaredMethods(JDWP::RefTypeId refTypeId, bool with_generic, JDWP::ExpandBuf* pReply) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800796 Class* c = gRegistry->Get<Class*>(refTypeId);
797 CHECK(c != NULL);
798
799 size_t direct_method_count = c->NumDirectMethods();
800 size_t virtual_method_count = c->NumVirtualMethods();
801
802 expandBufAdd4BE(pReply, direct_method_count + virtual_method_count);
803
804 for (size_t i = 0; i < direct_method_count + virtual_method_count; ++i) {
805 Method* m = (i < direct_method_count) ? c->GetDirectMethod(i) : c->GetVirtualMethod(i - direct_method_count);
806
807 expandBufAddMethodId(pReply, ToMethodId(m));
808 expandBufAddUtf8String(pReply, m->GetName()->ToModifiedUtf8().c_str());
809 expandBufAddUtf8String(pReply, m->GetSignature()->ToModifiedUtf8().c_str());
Elliott Hughesc5b734a2011-12-01 17:20:58 -0800810 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800811 static const char genericSignature[1] = "";
812 expandBufAddUtf8String(pReply, genericSignature);
813 }
814 expandBufAdd4BE(pReply, MangleAccessFlags(m->GetAccessFlags()));
815 }
816}
817
818void Dbg::OutputDeclaredInterfaces(JDWP::RefTypeId refTypeId, JDWP::ExpandBuf* pReply) {
819 Class* c = gRegistry->Get<Class*>(refTypeId);
820 CHECK(c != NULL);
821 size_t interface_count = c->NumInterfaces();
822 expandBufAdd4BE(pReply, interface_count);
823 for (size_t i = 0; i < interface_count; ++i) {
824 expandBufAddRefTypeId(pReply, gRegistry->Add(c->GetInterface(i)));
825 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700826}
827
828void Dbg::OutputLineTable(JDWP::RefTypeId refTypeId, JDWP::MethodId methodId, JDWP::ExpandBuf* pReply) {
Elliott Hughes03181a82011-11-17 17:22:21 -0800829 struct DebugCallbackContext {
830 int numItems;
831 JDWP::ExpandBuf* pReply;
832
833 static bool Callback(void* context, uint32_t address, uint32_t lineNum) {
834 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
835 expandBufAdd8BE(pContext->pReply, address);
836 expandBufAdd4BE(pContext->pReply, lineNum);
837 pContext->numItems++;
838 return true;
839 }
840 };
841
842 Method* m = FromMethodId(methodId);
843 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
844 const DexFile& dex_file = class_linker->FindDexFile(m->GetDeclaringClass()->GetDexCache());
845 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(m->GetCodeItemOffset());
846
847 uint64_t start, end;
848 if (m->IsNative()) {
849 start = -1;
850 end = -1;
851 } else {
852 start = 0;
853 end = code_item->insns_size_in_code_units_; // TODO: what are the units supposed to be? *2?
854 }
855
856 expandBufAdd8BE(pReply, start);
857 expandBufAdd8BE(pReply, end);
858
859 // Add numLines later
860 size_t numLinesOffset = expandBufGetLength(pReply);
861 expandBufAdd4BE(pReply, 0);
862
863 DebugCallbackContext context;
864 context.numItems = 0;
865 context.pReply = pReply;
866
867 dex_file.DecodeDebugInfo(code_item, m, DebugCallbackContext::Callback, NULL, &context);
868
869 JDWP::Set4BE(expandBufGetBuffer(pReply) + numLinesOffset, context.numItems);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700870}
871
Elliott Hughesc5b734a2011-12-01 17:20:58 -0800872void Dbg::OutputVariableTable(JDWP::RefTypeId refTypeId, JDWP::MethodId methodId, bool with_generic, JDWP::ExpandBuf* pReply) {
Elliott Hughesdbb40792011-11-18 17:05:22 -0800873 struct DebugCallbackContext {
Elliott Hughesdbb40792011-11-18 17:05:22 -0800874 JDWP::ExpandBuf* pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -0800875 size_t variable_count;
876 bool with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -0800877
Elliott Hughesc5b734a2011-12-01 17:20:58 -0800878 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 -0800879 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
880
Elliott Hughesc5b734a2011-12-01 17:20:58 -0800881 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 -0800882
Elliott Hughes68fdbd02011-11-29 19:22:47 -0800883 slot = MangleSlot(slot, name);
884
Elliott Hughesdbb40792011-11-18 17:05:22 -0800885 expandBufAdd8BE(pContext->pReply, startAddress);
886 expandBufAddUtf8String(pContext->pReply, name);
887 expandBufAddUtf8String(pContext->pReply, descriptor);
Elliott Hughesc5b734a2011-12-01 17:20:58 -0800888 if (pContext->with_generic) {
Elliott Hughesdbb40792011-11-18 17:05:22 -0800889 expandBufAddUtf8String(pContext->pReply, signature);
890 }
891 expandBufAdd4BE(pContext->pReply, endAddress - startAddress);
892 expandBufAdd4BE(pContext->pReply, slot);
893
Elliott Hughesc5b734a2011-12-01 17:20:58 -0800894 ++pContext->variable_count;
Elliott Hughesdbb40792011-11-18 17:05:22 -0800895 }
896 };
897
898 Method* m = FromMethodId(methodId);
899 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
900 const DexFile& dex_file = class_linker->FindDexFile(m->GetDeclaringClass()->GetDexCache());
901 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(m->GetCodeItemOffset());
902
Elliott Hughesc5b734a2011-12-01 17:20:58 -0800903 // arg_count considers doubles and longs to take 2 units.
904 // variable_count considers everything to take 1 unit.
905 std::string shorty(m->GetShorty()->ToModifiedUtf8());
906 expandBufAdd4BE(pReply, m->NumArgRegisters(shorty));
Elliott Hughesdbb40792011-11-18 17:05:22 -0800907
Elliott Hughesc5b734a2011-12-01 17:20:58 -0800908 // We don't know the total number of variables yet, so leave a blank and update it later.
909 size_t variable_count_offset = expandBufGetLength(pReply);
Elliott Hughesdbb40792011-11-18 17:05:22 -0800910 expandBufAdd4BE(pReply, 0);
911
912 DebugCallbackContext context;
Elliott Hughesdbb40792011-11-18 17:05:22 -0800913 context.pReply = pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -0800914 context.variable_count = 0;
915 context.with_generic = with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -0800916
917 dex_file.DecodeDebugInfo(code_item, m, NULL, DebugCallbackContext::Callback, &context);
918
Elliott Hughesc5b734a2011-12-01 17:20:58 -0800919 JDWP::Set4BE(expandBufGetBuffer(pReply) + variable_count_offset, context.variable_count);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700920}
921
922uint8_t Dbg::GetFieldBasicTag(JDWP::ObjectId objId, JDWP::FieldId fieldId) {
923 UNIMPLEMENTED(FATAL);
924 return 0;
925}
926
927uint8_t Dbg::GetStaticFieldBasicTag(JDWP::RefTypeId refTypeId, JDWP::FieldId fieldId) {
928 UNIMPLEMENTED(FATAL);
929 return 0;
930}
931
932void Dbg::GetFieldValue(JDWP::ObjectId objectId, JDWP::FieldId fieldId, JDWP::ExpandBuf* pReply) {
933 UNIMPLEMENTED(FATAL);
934}
935
936void Dbg::SetFieldValue(JDWP::ObjectId objectId, JDWP::FieldId fieldId, uint64_t value, int width) {
937 UNIMPLEMENTED(FATAL);
938}
939
940void Dbg::GetStaticFieldValue(JDWP::RefTypeId refTypeId, JDWP::FieldId fieldId, JDWP::ExpandBuf* pReply) {
941 UNIMPLEMENTED(FATAL);
942}
943
944void Dbg::SetStaticFieldValue(JDWP::RefTypeId refTypeId, JDWP::FieldId fieldId, uint64_t rawValue, int width) {
945 UNIMPLEMENTED(FATAL);
946}
947
Elliott Hughes68fdbd02011-11-29 19:22:47 -0800948std::string Dbg::StringToUtf8(JDWP::ObjectId strId) {
949 String* s = gRegistry->Get<String*>(strId);
950 return s->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700951}
952
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800953Thread* DecodeThread(JDWP::ObjectId threadId) {
954 Object* thread_peer = gRegistry->Get<Object*>(threadId);
955 CHECK(thread_peer != NULL);
956 return Thread::FromManagedThread(thread_peer);
957}
958
959bool Dbg::GetThreadName(JDWP::ObjectId threadId, std::string& name) {
960 ScopedThreadListLock thread_list_lock;
961 Thread* thread = DecodeThread(threadId);
962 if (thread == NULL) {
963 return false;
964 }
965 StringAppendF(&name, "<%d> %s", thread->GetThinLockId(), thread->GetName()->ToModifiedUtf8().c_str());
966 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700967}
968
969JDWP::ObjectId Dbg::GetThreadGroup(JDWP::ObjectId threadId) {
Elliott Hughes499c5132011-11-17 14:55:11 -0800970 Object* thread = gRegistry->Get<Object*>(threadId);
971 CHECK(thread != NULL);
972
973 Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/Thread;");
974 CHECK(c != NULL);
975 Field* f = c->FindInstanceField("group", "Ljava/lang/ThreadGroup;");
976 CHECK(f != NULL);
977 Object* group = f->GetObject(thread);
978 CHECK(group != NULL);
979 return gRegistry->Add(group);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700980}
981
Elliott Hughes499c5132011-11-17 14:55:11 -0800982std::string Dbg::GetThreadGroupName(JDWP::ObjectId threadGroupId) {
983 Object* thread_group = gRegistry->Get<Object*>(threadGroupId);
984 CHECK(thread_group != NULL);
985
986 Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/ThreadGroup;");
987 CHECK(c != NULL);
988 Field* f = c->FindInstanceField("name", "Ljava/lang/String;");
989 CHECK(f != NULL);
990 String* s = reinterpret_cast<String*>(f->GetObject(thread_group));
991 return s->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700992}
993
994JDWP::ObjectId Dbg::GetThreadGroupParent(JDWP::ObjectId threadGroupId) {
995 UNIMPLEMENTED(FATAL);
996 return 0;
997}
998
Elliott Hughes499c5132011-11-17 14:55:11 -0800999static Object* GetStaticThreadGroup(const char* field_name) {
1000 Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/ThreadGroup;");
1001 CHECK(c != NULL);
1002 Field* f = c->FindStaticField(field_name, "Ljava/lang/ThreadGroup;");
1003 CHECK(f != NULL);
1004 Object* group = f->GetObject(NULL);
1005 CHECK(group != NULL);
1006 return group;
1007}
1008
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001009JDWP::ObjectId Dbg::GetSystemThreadGroupId() {
Elliott Hughes499c5132011-11-17 14:55:11 -08001010 return gRegistry->Add(GetStaticThreadGroup("mSystem"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001011}
1012
1013JDWP::ObjectId Dbg::GetMainThreadGroupId() {
Elliott Hughes499c5132011-11-17 14:55:11 -08001014 return gRegistry->Add(GetStaticThreadGroup("mMain"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001015}
1016
Elliott Hughes499c5132011-11-17 14:55:11 -08001017bool Dbg::GetThreadStatus(JDWP::ObjectId threadId, uint32_t* pThreadStatus, uint32_t* pSuspendStatus) {
1018 ScopedThreadListLock thread_list_lock;
1019
1020 Thread* thread = DecodeThread(threadId);
1021 if (thread == NULL) {
1022 return false;
1023 }
1024
1025 switch (thread->GetState()) {
1026 case Thread::kTerminated: *pThreadStatus = JDWP::TS_ZOMBIE; break;
1027 case Thread::kRunnable: *pThreadStatus = JDWP::TS_RUNNING; break;
1028 case Thread::kTimedWaiting: *pThreadStatus = JDWP::TS_SLEEPING; break;
1029 case Thread::kBlocked: *pThreadStatus = JDWP::TS_MONITOR; break;
1030 case Thread::kWaiting: *pThreadStatus = JDWP::TS_WAIT; break;
1031 case Thread::kInitializing: *pThreadStatus = JDWP::TS_ZOMBIE; break;
1032 case Thread::kStarting: *pThreadStatus = JDWP::TS_ZOMBIE; break;
1033 case Thread::kNative: *pThreadStatus = JDWP::TS_RUNNING; break;
1034 case Thread::kVmWait: *pThreadStatus = JDWP::TS_WAIT; break;
1035 case Thread::kSuspended: *pThreadStatus = JDWP::TS_RUNNING; break;
1036 default:
1037 LOG(FATAL) << "unknown thread state " << thread->GetState();
1038 }
1039
1040 *pSuspendStatus = (thread->IsSuspended() ? JDWP::SUSPEND_STATUS_SUSPENDED : 0);
1041
1042 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001043}
1044
1045uint32_t Dbg::GetThreadSuspendCount(JDWP::ObjectId threadId) {
1046 UNIMPLEMENTED(FATAL);
1047 return 0;
1048}
1049
1050bool Dbg::ThreadExists(JDWP::ObjectId threadId) {
Elliott Hughes761928d2011-11-16 18:33:03 -08001051 return DecodeThread(threadId) != NULL;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001052}
1053
1054bool Dbg::IsSuspended(JDWP::ObjectId threadId) {
Elliott Hughes761928d2011-11-16 18:33:03 -08001055 return DecodeThread(threadId)->IsSuspended();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001056}
1057
1058//void Dbg::WaitForSuspend(JDWP::ObjectId threadId);
1059
Elliott Hughesa2155262011-11-16 16:26:58 -08001060void Dbg::GetThreadGroupThreadsImpl(Object* thread_group, JDWP::ObjectId** ppThreadIds, uint32_t* pThreadCount) {
1061 struct ThreadListVisitor {
1062 static void Visit(Thread* t, void* arg) {
1063 reinterpret_cast<ThreadListVisitor*>(arg)->Visit(t);
1064 }
1065
1066 void Visit(Thread* t) {
1067 if (t == Dbg::GetDebugThread()) {
1068 // Skip the JDWP thread. Some debuggers get bent out of shape when they can't suspend and
1069 // query all threads, so it's easier if we just don't tell them about this thread.
1070 return;
1071 }
1072 if (thread_group == NULL || t->GetThreadGroup() == thread_group) {
1073 threads.push_back(gRegistry->Add(t->GetPeer()));
1074 }
1075 }
1076
1077 Object* thread_group;
1078 std::vector<JDWP::ObjectId> threads;
1079 };
1080
1081 ThreadListVisitor tlv;
1082 tlv.thread_group = thread_group;
1083
1084 {
1085 ScopedThreadListLock thread_list_lock;
1086 Runtime::Current()->GetThreadList()->ForEach(ThreadListVisitor::Visit, &tlv);
1087 }
1088
1089 *pThreadCount = tlv.threads.size();
1090 if (*pThreadCount == 0) {
1091 *ppThreadIds = NULL;
1092 } else {
1093 *ppThreadIds = new JDWP::ObjectId[*pThreadCount];
1094 for (size_t i = 0; i < *pThreadCount; ++i) {
1095 (*ppThreadIds)[i] = tlv.threads[i];
1096 }
1097 }
1098}
1099
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001100void Dbg::GetThreadGroupThreads(JDWP::ObjectId threadGroupId, JDWP::ObjectId** ppThreadIds, uint32_t* pThreadCount) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001101 GetThreadGroupThreadsImpl(gRegistry->Get<Object*>(threadGroupId), ppThreadIds, pThreadCount);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001102}
1103
1104void Dbg::GetAllThreads(JDWP::ObjectId** ppThreadIds, uint32_t* pThreadCount) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001105 GetThreadGroupThreadsImpl(NULL, ppThreadIds, pThreadCount);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001106}
1107
1108int Dbg::GetThreadFrameCount(JDWP::ObjectId threadId) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001109 ScopedThreadListLock thread_list_lock;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001110 struct CountStackDepthVisitor : public Thread::StackVisitor {
1111 CountStackDepthVisitor() : depth(0) {}
Elliott Hughesf8a2df72011-12-01 12:19:54 -08001112 virtual void VisitFrame(const Frame& f, uintptr_t) {
1113 // TODO: we'll need to skip callee-save frames too.
1114 if (f.HasMethod()) {
1115 ++depth;
1116 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001117 }
1118 size_t depth;
1119 };
1120 CountStackDepthVisitor visitor;
1121 DecodeThread(threadId)->WalkStack(&visitor);
1122 return visitor.depth;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001123}
1124
Elliott Hughes03181a82011-11-17 17:22:21 -08001125bool Dbg::GetThreadFrame(JDWP::ObjectId threadId, int desired_frame_number, JDWP::FrameId* pFrameId, JDWP::JdwpLocation* pLoc) {
1126 ScopedThreadListLock thread_list_lock;
1127 struct GetFrameVisitor : public Thread::StackVisitor {
1128 GetFrameVisitor(int desired_frame_number, JDWP::FrameId* pFrameId, JDWP::JdwpLocation* pLoc)
1129 : found(false) ,depth(0), desired_frame_number(desired_frame_number), pFrameId(pFrameId), pLoc(pLoc) {
1130 }
1131 virtual void VisitFrame(const Frame& f, uintptr_t pc) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -08001132 // TODO: we'll need to skip callee-save frames too.
Elliott Hughes03181a82011-11-17 17:22:21 -08001133 if (!f.HasMethod()) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -08001134 return; // The debugger can't do anything useful with a frame that has no Method*.
Elliott Hughes03181a82011-11-17 17:22:21 -08001135 }
1136
1137 if (depth == desired_frame_number) {
1138 *pFrameId = reinterpret_cast<JDWP::FrameId>(f.GetSP());
1139
1140 Method* m = f.GetMethod();
1141 Class* c = m->GetDeclaringClass();
1142
1143 pLoc->typeTag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
1144 pLoc->classId = gRegistry->Add(c);
1145 pLoc->methodId = ToMethodId(m);
1146 pLoc->idx = m->IsNative() ? -1 : m->ToDexPC(pc);
1147
1148 found = true;
1149 }
1150 ++depth;
1151 }
1152 bool found;
1153 int depth;
1154 int desired_frame_number;
1155 JDWP::FrameId* pFrameId;
1156 JDWP::JdwpLocation* pLoc;
1157 };
1158 GetFrameVisitor visitor(desired_frame_number, pFrameId, pLoc);
1159 visitor.desired_frame_number = desired_frame_number;
1160 DecodeThread(threadId)->WalkStack(&visitor);
1161 return visitor.found;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001162}
1163
1164JDWP::ObjectId Dbg::GetThreadSelfId() {
Elliott Hughes475fc232011-10-25 15:00:35 -07001165 return gRegistry->Add(Thread::Current()->GetPeer());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001166}
1167
Elliott Hughes475fc232011-10-25 15:00:35 -07001168void Dbg::SuspendVM() {
Elliott Hughesa2155262011-11-16 16:26:58 -08001169 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 -07001170 Runtime::Current()->GetThreadList()->SuspendAll(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001171}
1172
1173void Dbg::ResumeVM() {
Elliott Hughes475fc232011-10-25 15:00:35 -07001174 Runtime::Current()->GetThreadList()->ResumeAll(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001175}
1176
1177void Dbg::SuspendThread(JDWP::ObjectId threadId) {
1178 UNIMPLEMENTED(FATAL);
1179}
1180
1181void Dbg::ResumeThread(JDWP::ObjectId threadId) {
1182 UNIMPLEMENTED(FATAL);
1183}
1184
1185void Dbg::SuspendSelf() {
Elliott Hughes475fc232011-10-25 15:00:35 -07001186 Runtime::Current()->GetThreadList()->SuspendSelfForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001187}
1188
1189bool Dbg::GetThisObject(JDWP::ObjectId threadId, JDWP::FrameId frameId, JDWP::ObjectId* pThisId) {
1190 UNIMPLEMENTED(FATAL);
1191 return false;
1192}
1193
Elliott Hughesdbb40792011-11-18 17:05:22 -08001194void Dbg::GetLocalValue(JDWP::ObjectId threadId, JDWP::FrameId frameId, int slot, JDWP::JdwpTag tag, uint8_t* buf, size_t expectedLen) {
1195 Method** sp = reinterpret_cast<Method**>(frameId);
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001196 Frame f;
1197 f.SetSP(sp);
1198 uint16_t reg = DemangleSlot(slot, f);
1199 Method* m = f.GetMethod();
1200
1201 const VmapTable vmap_table(m->GetVmapTableRaw());
1202 uint32_t vmap_offset;
1203 if (vmap_table.IsInContext(reg, vmap_offset)) {
1204 UNIMPLEMENTED(FATAL) << "don't know how to pull locals from callee save frames: " << vmap_offset;
1205 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001206
1207 switch (tag) {
1208 case JDWP::JT_BOOLEAN:
1209 {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001210 CHECK_EQ(expectedLen, 1U);
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001211 uint32_t intVal = static_cast<uint32_t>(f.GetVReg(m, reg));
1212 LOG(WARNING) << "get boolean local " << reg << " = " << intVal;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001213 JDWP::Set1(buf+1, intVal != 0);
1214 }
1215 break;
1216 case JDWP::JT_BYTE:
1217 {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001218 CHECK_EQ(expectedLen, 1U);
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001219 uint32_t intVal = static_cast<uint32_t>(f.GetVReg(m, reg));
1220 LOG(WARNING) << "get byte local " << reg << " = " << intVal;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001221 JDWP::Set1(buf+1, intVal);
1222 }
1223 break;
1224 case JDWP::JT_SHORT:
1225 case JDWP::JT_CHAR:
1226 {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001227 CHECK_EQ(expectedLen, 2U);
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001228 uint32_t intVal = static_cast<uint32_t>(f.GetVReg(m, reg));
1229 LOG(WARNING) << "get short/char local " << reg << " = " << intVal;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001230 JDWP::Set2BE(buf+1, intVal);
1231 }
1232 break;
1233 case JDWP::JT_INT:
1234 case JDWP::JT_FLOAT:
1235 {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001236 CHECK_EQ(expectedLen, 4U);
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001237 uint32_t intVal = static_cast<uint32_t>(f.GetVReg(m, reg));
1238 LOG(WARNING) << "get int/float local " << reg << " = " << intVal;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001239 JDWP::Set4BE(buf+1, intVal);
1240 }
1241 break;
1242 case JDWP::JT_ARRAY:
1243 {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001244 CHECK_EQ(expectedLen, sizeof(JDWP::ObjectId));
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001245 Object* o = reinterpret_cast<Object*>(f.GetVReg(m, reg));
1246 LOG(WARNING) << "get array local " << reg << " = " << o;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001247 if (o != NULL && !Heap::IsHeapAddress(o)) {
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001248 LOG(FATAL) << "reg " << reg << " expected to hold array: " << o;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001249 }
1250 JDWP::SetObjectId(buf+1, gRegistry->Add(o));
1251 }
1252 break;
1253 case JDWP::JT_OBJECT:
1254 {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001255 CHECK_EQ(expectedLen, sizeof(JDWP::ObjectId));
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001256 Object* o = reinterpret_cast<Object*>(f.GetVReg(m, reg));
1257 LOG(WARNING) << "get object local " << reg << " = " << o;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001258 if (o != NULL && !Heap::IsHeapAddress(o)) {
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001259 LOG(FATAL) << "reg " << reg << " expected to hold object: " << o;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001260 }
1261 tag = TagFromObject(o);
1262 JDWP::SetObjectId(buf+1, gRegistry->Add(o));
1263 }
1264 break;
1265 case JDWP::JT_DOUBLE:
1266 case JDWP::JT_LONG:
1267 {
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001268 UNIMPLEMENTED(WARNING) << "get 64-bit local " << reg;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001269 CHECK_EQ(expectedLen, 8U);
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001270 uint64_t longVal = 0; // memcpy(&longVal, &framePtr[reg], 8);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001271 JDWP::Set8BE(buf+1, longVal);
1272 }
1273 break;
1274 default:
1275 LOG(FATAL) << "unknown tag " << tag;
1276 break;
1277 }
1278
1279 // Prepend tag, which may have been updated.
1280 JDWP::Set1(buf, tag);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001281}
1282
Elliott Hughesdbb40792011-11-18 17:05:22 -08001283void 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 -07001284 UNIMPLEMENTED(FATAL);
1285}
1286
1287void Dbg::PostLocationEvent(const Method* method, int pcOffset, Object* thisPtr, int eventFlags) {
1288 UNIMPLEMENTED(FATAL);
1289}
1290
1291void Dbg::PostException(void* throwFp, int throwRelPc, void* catchFp, int catchRelPc, Object* exception) {
1292 UNIMPLEMENTED(FATAL);
1293}
1294
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001295void Dbg::PostClassPrepare(Class* c) {
1296 UNIMPLEMENTED(FATAL);
1297}
1298
1299bool Dbg::WatchLocation(const JDWP::JdwpLocation* pLoc) {
1300 UNIMPLEMENTED(FATAL);
1301 return false;
1302}
1303
1304void Dbg::UnwatchLocation(const JDWP::JdwpLocation* pLoc) {
1305 UNIMPLEMENTED(FATAL);
1306}
1307
1308bool Dbg::ConfigureStep(JDWP::ObjectId threadId, JDWP::JdwpStepSize size, JDWP::JdwpStepDepth depth) {
1309 UNIMPLEMENTED(FATAL);
1310 return false;
1311}
1312
1313void Dbg::UnconfigureStep(JDWP::ObjectId threadId) {
1314 UNIMPLEMENTED(FATAL);
1315}
1316
1317JDWP::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) {
1318 UNIMPLEMENTED(FATAL);
1319 return JDWP::ERR_NONE;
1320}
1321
1322void Dbg::ExecuteMethod(DebugInvokeReq* pReq) {
1323 UNIMPLEMENTED(FATAL);
1324}
1325
1326void Dbg::RegisterObjectId(JDWP::ObjectId id) {
1327 UNIMPLEMENTED(FATAL);
1328}
1329
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001330/*
1331 * "buf" contains a full JDWP packet, possibly with multiple chunks. We
1332 * need to process each, accumulate the replies, and ship the whole thing
1333 * back.
1334 *
1335 * Returns "true" if we have a reply. The reply buffer is newly allocated,
1336 * and includes the chunk type/length, followed by the data.
1337 *
1338 * TODO: we currently assume that the request and reply include a single
1339 * chunk. If this becomes inconvenient we will need to adapt.
1340 */
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001341bool Dbg::DdmHandlePacket(const uint8_t* buf, int dataLen, uint8_t** pReplyBuf, int* pReplyLen) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001342 CHECK_GE(dataLen, 0);
1343
1344 Thread* self = Thread::Current();
1345 JNIEnv* env = self->GetJniEnv();
1346
1347 static jclass Chunk_class = env->FindClass("org/apache/harmony/dalvik/ddmc/Chunk");
1348 static jclass DdmServer_class = env->FindClass("org/apache/harmony/dalvik/ddmc/DdmServer");
1349 static jmethodID dispatch_mid = env->GetStaticMethodID(DdmServer_class, "dispatch",
1350 "(I[BII)Lorg/apache/harmony/dalvik/ddmc/Chunk;");
1351 static jfieldID data_fid = env->GetFieldID(Chunk_class, "data", "[B");
1352 static jfieldID length_fid = env->GetFieldID(Chunk_class, "length", "I");
1353 static jfieldID offset_fid = env->GetFieldID(Chunk_class, "offset", "I");
1354 static jfieldID type_fid = env->GetFieldID(Chunk_class, "type", "I");
1355
1356 // Create a byte[] corresponding to 'buf'.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001357 ScopedLocalRef<jbyteArray> dataArray(env, env->NewByteArray(dataLen));
1358 if (dataArray.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001359 LOG(WARNING) << "byte[] allocation failed: " << dataLen;
1360 env->ExceptionClear();
1361 return false;
1362 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001363 env->SetByteArrayRegion(dataArray.get(), 0, dataLen, reinterpret_cast<const jbyte*>(buf));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001364
1365 const int kChunkHdrLen = 8;
1366
1367 // Run through and find all chunks. [Currently just find the first.]
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001368 ScopedByteArrayRO contents(env, dataArray.get());
Elliott Hughesf7c3b662011-10-27 12:04:56 -07001369 jint type = JDWP::Get4BE(reinterpret_cast<const uint8_t*>(&contents[0]));
1370 jint length = JDWP::Get4BE(reinterpret_cast<const uint8_t*>(&contents[4]));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001371 jint offset = kChunkHdrLen;
1372 if (offset + length > dataLen) {
1373 LOG(WARNING) << StringPrintf("bad chunk found (len=%u pktLen=%d)", length, dataLen);
1374 return false;
1375 }
1376
1377 // Call "private static Chunk dispatch(int type, byte[] data, int offset, int length)".
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001378 ScopedLocalRef<jobject> chunk(env, env->CallStaticObjectMethod(DdmServer_class, dispatch_mid, type, dataArray.get(), offset, length));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001379 if (env->ExceptionCheck()) {
1380 LOG(INFO) << StringPrintf("Exception thrown by dispatcher for 0x%08x", type);
1381 env->ExceptionDescribe();
1382 env->ExceptionClear();
1383 return false;
1384 }
1385
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001386 if (chunk.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001387 return false;
1388 }
1389
1390 /*
1391 * Pull the pieces out of the chunk. We copy the results into a
1392 * newly-allocated buffer that the caller can free. We don't want to
1393 * continue using the Chunk object because nothing has a reference to it.
1394 *
1395 * We could avoid this by returning type/data/offset/length and having
1396 * the caller be aware of the object lifetime issues, but that
1397 * integrates the JDWP code more tightly into the VM, and doesn't work
1398 * if we have responses for multiple chunks.
1399 *
1400 * So we're pretty much stuck with copying data around multiple times.
1401 */
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001402 ScopedLocalRef<jbyteArray> replyData(env, reinterpret_cast<jbyteArray>(env->GetObjectField(chunk.get(), data_fid)));
1403 length = env->GetIntField(chunk.get(), length_fid);
1404 offset = env->GetIntField(chunk.get(), offset_fid);
1405 type = env->GetIntField(chunk.get(), type_fid);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001406
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001407 LOG(VERBOSE) << StringPrintf("DDM reply: type=0x%08x data=%p offset=%d length=%d", type, replyData.get(), offset, length);
1408 if (length == 0 || replyData.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001409 return false;
1410 }
1411
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001412 jsize replyLength = env->GetArrayLength(replyData.get());
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001413 if (offset + length > replyLength) {
1414 LOG(WARNING) << StringPrintf("chunk off=%d len=%d exceeds reply array len %d", offset, length, replyLength);
1415 return false;
1416 }
1417
1418 uint8_t* reply = new uint8_t[length + kChunkHdrLen];
1419 if (reply == NULL) {
1420 LOG(WARNING) << "malloc failed: " << (length + kChunkHdrLen);
1421 return false;
1422 }
Elliott Hughesf7c3b662011-10-27 12:04:56 -07001423 JDWP::Set4BE(reply + 0, type);
1424 JDWP::Set4BE(reply + 4, length);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001425 env->GetByteArrayRegion(replyData.get(), offset, length, reinterpret_cast<jbyte*>(reply + kChunkHdrLen));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001426
1427 *pReplyBuf = reply;
1428 *pReplyLen = length + kChunkHdrLen;
1429
1430 LOG(VERBOSE) << StringPrintf("dvmHandleDdm returning type=%.4s buf=%p len=%d", (char*) reply, reply, length);
1431 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001432}
1433
Elliott Hughesa2155262011-11-16 16:26:58 -08001434void Dbg::DdmBroadcast(bool connect) {
Elliott Hughes47fce012011-10-25 18:37:19 -07001435 LOG(VERBOSE) << "Broadcasting DDM " << (connect ? "connect" : "disconnect") << "...";
1436
1437 Thread* self = Thread::Current();
1438 if (self->GetState() != Thread::kRunnable) {
1439 LOG(ERROR) << "DDM broadcast in thread state " << self->GetState();
1440 /* try anyway? */
1441 }
1442
1443 JNIEnv* env = self->GetJniEnv();
1444 static jclass DdmServer_class = env->FindClass("org/apache/harmony/dalvik/ddmc/DdmServer");
1445 static jmethodID broadcast_mid = env->GetStaticMethodID(DdmServer_class, "broadcast", "(I)V");
1446 jint event = connect ? 1 /*DdmServer.CONNECTED*/ : 2 /*DdmServer.DISCONNECTED*/;
1447 env->CallStaticVoidMethod(DdmServer_class, broadcast_mid, event);
1448 if (env->ExceptionCheck()) {
1449 LOG(ERROR) << "DdmServer.broadcast " << event << " failed";
1450 env->ExceptionDescribe();
1451 env->ExceptionClear();
1452 }
1453}
1454
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001455void Dbg::DdmConnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08001456 Dbg::DdmBroadcast(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001457}
1458
1459void Dbg::DdmDisconnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08001460 Dbg::DdmBroadcast(false);
Elliott Hughes47fce012011-10-25 18:37:19 -07001461 gDdmThreadNotification = false;
1462}
1463
1464/*
Elliott Hughes82188472011-11-07 18:11:48 -08001465 * Send a notification when a thread starts, stops, or changes its name.
Elliott Hughes47fce012011-10-25 18:37:19 -07001466 *
1467 * Because we broadcast the full set of threads when the notifications are
1468 * first enabled, it's possible for "thread" to be actively executing.
1469 */
Elliott Hughes82188472011-11-07 18:11:48 -08001470void Dbg::DdmSendThreadNotification(Thread* t, uint32_t type) {
Elliott Hughes47fce012011-10-25 18:37:19 -07001471 if (!gDdmThreadNotification) {
1472 return;
1473 }
1474
Elliott Hughes82188472011-11-07 18:11:48 -08001475 if (type == CHUNK_TYPE("THDE")) {
Elliott Hughes47fce012011-10-25 18:37:19 -07001476 uint8_t buf[4];
Elliott Hughesf7c3b662011-10-27 12:04:56 -07001477 JDWP::Set4BE(&buf[0], t->GetThinLockId());
Elliott Hughes47fce012011-10-25 18:37:19 -07001478 Dbg::DdmSendChunk(CHUNK_TYPE("THDE"), 4, buf);
Elliott Hughes82188472011-11-07 18:11:48 -08001479 } else {
1480 CHECK(type == CHUNK_TYPE("THCR") || type == CHUNK_TYPE("THNM")) << type;
1481 SirtRef<String> name(t->GetName());
1482 size_t char_count = (name.get() != NULL) ? name->GetLength() : 0;
1483 const jchar* chars = name->GetCharArray()->GetData();
1484
Elliott Hughes21f32d72011-11-09 17:44:13 -08001485 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08001486 JDWP::Append4BE(bytes, t->GetThinLockId());
1487 JDWP::AppendUtf16BE(bytes, chars, char_count);
Elliott Hughes21f32d72011-11-09 17:44:13 -08001488 CHECK_EQ(bytes.size(), char_count*2 + sizeof(uint32_t)*2);
1489 Dbg::DdmSendChunk(type, bytes);
Elliott Hughes47fce012011-10-25 18:37:19 -07001490 }
1491}
1492
Elliott Hughesa2155262011-11-16 16:26:58 -08001493static void DdmSendThreadStartCallback(Thread* t, void*) {
Elliott Hughes82188472011-11-07 18:11:48 -08001494 Dbg::DdmSendThreadNotification(t, CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07001495}
1496
1497void Dbg::DdmSetThreadNotification(bool enable) {
1498 // We lock the thread list to avoid sending duplicate events or missing
1499 // a thread change. We should be okay holding this lock while sending
1500 // the messages out. (We have to hold it while accessing a live thread.)
Elliott Hughesbbd9d832011-11-07 14:40:00 -08001501 ScopedThreadListLock thread_list_lock;
Elliott Hughes47fce012011-10-25 18:37:19 -07001502
1503 gDdmThreadNotification = enable;
1504 if (enable) {
Elliott Hughesbfe487b2011-10-26 15:48:55 -07001505 Runtime::Current()->GetThreadList()->ForEach(DdmSendThreadStartCallback, NULL);
Elliott Hughes47fce012011-10-25 18:37:19 -07001506 }
1507}
1508
Elliott Hughesa2155262011-11-16 16:26:58 -08001509void Dbg::PostThreadStartOrStop(Thread* t, uint32_t type) {
Elliott Hughes47fce012011-10-25 18:37:19 -07001510 if (gDebuggerActive) {
1511 JDWP::ObjectId id = gRegistry->Add(t->GetPeer());
Elliott Hughes82188472011-11-07 18:11:48 -08001512 gJdwpState->PostThreadChange(id, type == CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07001513 }
Elliott Hughes82188472011-11-07 18:11:48 -08001514 Dbg::DdmSendThreadNotification(t, type);
Elliott Hughes47fce012011-10-25 18:37:19 -07001515}
1516
1517void Dbg::PostThreadStart(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001518 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07001519}
1520
1521void Dbg::PostThreadDeath(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001522 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THDE"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001523}
1524
Elliott Hughes82188472011-11-07 18:11:48 -08001525void Dbg::DdmSendChunk(uint32_t type, size_t byte_count, const uint8_t* buf) {
Elliott Hughes3bb81562011-10-21 18:52:59 -07001526 CHECK(buf != NULL);
1527 iovec vec[1];
1528 vec[0].iov_base = reinterpret_cast<void*>(const_cast<uint8_t*>(buf));
1529 vec[0].iov_len = byte_count;
1530 Dbg::DdmSendChunkV(type, vec, 1);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001531}
1532
Elliott Hughes21f32d72011-11-09 17:44:13 -08001533void Dbg::DdmSendChunk(uint32_t type, const std::vector<uint8_t>& bytes) {
1534 DdmSendChunk(type, bytes.size(), &bytes[0]);
1535}
1536
Elliott Hughes82188472011-11-07 18:11:48 -08001537void Dbg::DdmSendChunkV(uint32_t type, const struct iovec* iov, int iovcnt) {
Elliott Hughes3bb81562011-10-21 18:52:59 -07001538 if (gJdwpState == NULL) {
1539 LOG(VERBOSE) << "Debugger thread not active, ignoring DDM send: " << type;
1540 } else {
Elliott Hughes376a7a02011-10-24 18:35:55 -07001541 gJdwpState->DdmSendChunkV(type, iov, iovcnt);
Elliott Hughes3bb81562011-10-21 18:52:59 -07001542 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001543}
1544
Elliott Hughes767a1472011-10-26 18:49:02 -07001545int Dbg::DdmHandleHpifChunk(HpifWhen when) {
1546 if (when == HPIF_WHEN_NOW) {
Elliott Hughes7162ad92011-10-27 14:08:42 -07001547 DdmSendHeapInfo(when);
Elliott Hughes767a1472011-10-26 18:49:02 -07001548 return true;
1549 }
1550
1551 if (when != HPIF_WHEN_NEVER && when != HPIF_WHEN_NEXT_GC && when != HPIF_WHEN_EVERY_GC) {
1552 LOG(ERROR) << "invalid HpifWhen value: " << static_cast<int>(when);
1553 return false;
1554 }
1555
1556 gDdmHpifWhen = when;
1557 return true;
1558}
1559
1560bool Dbg::DdmHandleHpsgNhsgChunk(Dbg::HpsgWhen when, Dbg::HpsgWhat what, bool native) {
1561 if (when != HPSG_WHEN_NEVER && when != HPSG_WHEN_EVERY_GC) {
1562 LOG(ERROR) << "invalid HpsgWhen value: " << static_cast<int>(when);
1563 return false;
1564 }
1565
1566 if (what != HPSG_WHAT_MERGED_OBJECTS && what != HPSG_WHAT_DISTINCT_OBJECTS) {
1567 LOG(ERROR) << "invalid HpsgWhat value: " << static_cast<int>(what);
1568 return false;
1569 }
1570
1571 if (native) {
1572 gDdmNhsgWhen = when;
1573 gDdmNhsgWhat = what;
1574 } else {
1575 gDdmHpsgWhen = when;
1576 gDdmHpsgWhat = what;
1577 }
1578 return true;
1579}
1580
Elliott Hughes7162ad92011-10-27 14:08:42 -07001581void Dbg::DdmSendHeapInfo(HpifWhen reason) {
1582 // If there's a one-shot 'when', reset it.
1583 if (reason == gDdmHpifWhen) {
1584 if (gDdmHpifWhen == HPIF_WHEN_NEXT_GC) {
1585 gDdmHpifWhen = HPIF_WHEN_NEVER;
1586 }
1587 }
1588
1589 /*
1590 * Chunk HPIF (client --> server)
1591 *
1592 * Heap Info. General information about the heap,
1593 * suitable for a summary display.
1594 *
1595 * [u4]: number of heaps
1596 *
1597 * For each heap:
1598 * [u4]: heap ID
1599 * [u8]: timestamp in ms since Unix epoch
1600 * [u1]: capture reason (same as 'when' value from server)
1601 * [u4]: max heap size in bytes (-Xmx)
1602 * [u4]: current heap size in bytes
1603 * [u4]: current number of bytes allocated
1604 * [u4]: current number of objects allocated
1605 */
1606 uint8_t heap_count = 1;
Elliott Hughes21f32d72011-11-09 17:44:13 -08001607 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08001608 JDWP::Append4BE(bytes, heap_count);
1609 JDWP::Append4BE(bytes, 1); // Heap id (bogus; we only have one heap).
1610 JDWP::Append8BE(bytes, MilliTime());
1611 JDWP::Append1BE(bytes, reason);
1612 JDWP::Append4BE(bytes, Heap::GetMaxMemory()); // Max allowed heap size in bytes.
1613 JDWP::Append4BE(bytes, Heap::GetTotalMemory()); // Current heap size in bytes.
1614 JDWP::Append4BE(bytes, Heap::GetBytesAllocated());
1615 JDWP::Append4BE(bytes, Heap::GetObjectsAllocated());
Elliott Hughes21f32d72011-11-09 17:44:13 -08001616 CHECK_EQ(bytes.size(), 4U + (heap_count * (4 + 8 + 1 + 4 + 4 + 4 + 4)));
1617 Dbg::DdmSendChunk(CHUNK_TYPE("HPIF"), bytes);
Elliott Hughes767a1472011-10-26 18:49:02 -07001618}
1619
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001620enum HpsgSolidity {
1621 SOLIDITY_FREE = 0,
1622 SOLIDITY_HARD = 1,
1623 SOLIDITY_SOFT = 2,
1624 SOLIDITY_WEAK = 3,
1625 SOLIDITY_PHANTOM = 4,
1626 SOLIDITY_FINALIZABLE = 5,
1627 SOLIDITY_SWEEP = 6,
1628};
1629
1630enum HpsgKind {
1631 KIND_OBJECT = 0,
1632 KIND_CLASS_OBJECT = 1,
1633 KIND_ARRAY_1 = 2,
1634 KIND_ARRAY_2 = 3,
1635 KIND_ARRAY_4 = 4,
1636 KIND_ARRAY_8 = 5,
1637 KIND_UNKNOWN = 6,
1638 KIND_NATIVE = 7,
1639};
1640
1641#define HPSG_PARTIAL (1<<7)
1642#define HPSG_STATE(solidity, kind) ((uint8_t)((((kind) & 0x7) << 3) | ((solidity) & 0x7)))
1643
1644struct HeapChunkContext {
1645 std::vector<uint8_t> buf;
1646 uint8_t* p;
1647 uint8_t* pieceLenField;
1648 size_t totalAllocationUnits;
Elliott Hughes82188472011-11-07 18:11:48 -08001649 uint32_t type;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001650 bool merge;
1651 bool needHeader;
1652
1653 // Maximum chunk size. Obtain this from the formula:
1654 // (((maximum_heap_size / ALLOCATION_UNIT_SIZE) + 255) / 256) * 2
1655 HeapChunkContext(bool merge, bool native)
1656 : buf(16384 - 16),
1657 type(0),
1658 merge(merge) {
1659 Reset();
1660 if (native) {
1661 type = CHUNK_TYPE("NHSG");
1662 } else {
1663 type = merge ? CHUNK_TYPE("HPSG") : CHUNK_TYPE("HPSO");
1664 }
1665 }
1666
1667 ~HeapChunkContext() {
1668 if (p > &buf[0]) {
1669 Flush();
1670 }
1671 }
1672
1673 void EnsureHeader(const void* chunk_ptr) {
1674 if (!needHeader) {
1675 return;
1676 }
1677
1678 // Start a new HPSx chunk.
1679 JDWP::Write4BE(&p, 1); // Heap id (bogus; we only have one heap).
1680 JDWP::Write1BE(&p, 8); // Size of allocation unit, in bytes.
1681
1682 JDWP::Write4BE(&p, reinterpret_cast<uintptr_t>(chunk_ptr)); // virtual address of segment start.
1683 JDWP::Write4BE(&p, 0); // offset of this piece (relative to the virtual address).
1684 // [u4]: length of piece, in allocation units
1685 // We won't know this until we're done, so save the offset and stuff in a dummy value.
1686 pieceLenField = p;
1687 JDWP::Write4BE(&p, 0x55555555);
1688 needHeader = false;
1689 }
1690
1691 void Flush() {
1692 // Patch the "length of piece" field.
1693 CHECK_LE(&buf[0], pieceLenField);
1694 CHECK_LE(pieceLenField, p);
1695 JDWP::Set4BE(pieceLenField, totalAllocationUnits);
1696
1697 Dbg::DdmSendChunk(type, p - &buf[0], &buf[0]);
1698 Reset();
1699 }
1700
Elliott Hughesa2155262011-11-16 16:26:58 -08001701 static void HeapChunkCallback(const void* chunk_ptr, size_t chunk_len, const void* user_ptr, size_t user_len, void* arg) {
1702 reinterpret_cast<HeapChunkContext*>(arg)->HeapChunkCallback(chunk_ptr, chunk_len, user_ptr, user_len);
1703 }
1704
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001705 private:
Elliott Hughesa2155262011-11-16 16:26:58 -08001706 enum { ALLOCATION_UNIT_SIZE = 8 };
1707
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001708 void Reset() {
1709 p = &buf[0];
1710 totalAllocationUnits = 0;
1711 needHeader = true;
1712 pieceLenField = NULL;
1713 }
1714
Elliott Hughesa2155262011-11-16 16:26:58 -08001715 void HeapChunkCallback(const void* chunk_ptr, size_t chunk_len, const void* user_ptr, size_t user_len) {
1716 CHECK_EQ((chunk_len & (ALLOCATION_UNIT_SIZE-1)), 0U);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001717
Elliott Hughesa2155262011-11-16 16:26:58 -08001718 /* Make sure there's enough room left in the buffer.
1719 * We need to use two bytes for every fractional 256
1720 * allocation units used by the chunk.
1721 */
1722 {
1723 size_t needed = (((chunk_len/ALLOCATION_UNIT_SIZE + 255) / 256) * 2);
1724 size_t bytesLeft = buf.size() - (size_t)(p - &buf[0]);
1725 if (bytesLeft < needed) {
1726 Flush();
1727 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001728
Elliott Hughesa2155262011-11-16 16:26:58 -08001729 bytesLeft = buf.size() - (size_t)(p - &buf[0]);
1730 if (bytesLeft < needed) {
1731 LOG(WARNING) << "chunk is too big to transmit (chunk_len=" << chunk_len << ", " << needed << " bytes)";
1732 return;
1733 }
1734 }
1735
1736 // OLD-TODO: notice when there's a gap and start a new heap, or at least a new range.
1737 EnsureHeader(chunk_ptr);
1738
1739 // Determine the type of this chunk.
1740 // OLD-TODO: if context.merge, see if this chunk is different from the last chunk.
1741 // If it's the same, we should combine them.
1742 uint8_t state = ExamineObject(reinterpret_cast<const Object*>(user_ptr), (type == CHUNK_TYPE("NHSG")));
1743
1744 // Write out the chunk description.
1745 chunk_len /= ALLOCATION_UNIT_SIZE; // convert to allocation units
1746 totalAllocationUnits += chunk_len;
1747 while (chunk_len > 256) {
1748 *p++ = state | HPSG_PARTIAL;
1749 *p++ = 255; // length - 1
1750 chunk_len -= 256;
1751 }
1752 *p++ = state;
1753 *p++ = chunk_len - 1;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001754 }
1755
Elliott Hughesa2155262011-11-16 16:26:58 -08001756 uint8_t ExamineObject(const Object* o, bool is_native_heap) {
1757 if (o == NULL) {
1758 return HPSG_STATE(SOLIDITY_FREE, 0);
1759 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001760
Elliott Hughesa2155262011-11-16 16:26:58 -08001761 // It's an allocated chunk. Figure out what it is.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001762
Elliott Hughesa2155262011-11-16 16:26:58 -08001763 // If we're looking at the native heap, we'll just return
1764 // (SOLIDITY_HARD, KIND_NATIVE) for all allocated chunks.
1765 if (is_native_heap || !Heap::IsLiveObjectLocked(o)) {
1766 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
1767 }
1768
1769 Class* c = o->GetClass();
1770 if (c == NULL) {
1771 // The object was probably just created but hasn't been initialized yet.
1772 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
1773 }
1774
1775 if (!Heap::IsHeapAddress(c)) {
1776 LOG(WARNING) << "invalid class for managed heap object: " << o << " " << c;
1777 return HPSG_STATE(SOLIDITY_HARD, KIND_UNKNOWN);
1778 }
1779
1780 if (c->IsClassClass()) {
1781 return HPSG_STATE(SOLIDITY_HARD, KIND_CLASS_OBJECT);
1782 }
1783
1784 if (c->IsArrayClass()) {
1785 if (o->IsObjectArray()) {
1786 return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
1787 }
1788 switch (c->GetComponentSize()) {
1789 case 1: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_1);
1790 case 2: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_2);
1791 case 4: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
1792 case 8: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_8);
1793 }
1794 }
1795
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001796 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
1797 }
1798
Elliott Hughesa2155262011-11-16 16:26:58 -08001799 DISALLOW_COPY_AND_ASSIGN(HeapChunkContext);
1800};
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001801
1802void Dbg::DdmSendHeapSegments(bool native) {
1803 Dbg::HpsgWhen when;
1804 Dbg::HpsgWhat what;
1805 if (!native) {
1806 when = gDdmHpsgWhen;
1807 what = gDdmHpsgWhat;
1808 } else {
1809 when = gDdmNhsgWhen;
1810 what = gDdmNhsgWhat;
1811 }
1812 if (when == HPSG_WHEN_NEVER) {
1813 return;
1814 }
1815
1816 // Figure out what kind of chunks we'll be sending.
1817 CHECK(what == HPSG_WHAT_MERGED_OBJECTS || what == HPSG_WHAT_DISTINCT_OBJECTS) << static_cast<int>(what);
1818
1819 // First, send a heap start chunk.
1820 uint8_t heap_id[4];
1821 JDWP::Set4BE(&heap_id[0], 1); // Heap id (bogus; we only have one heap).
1822 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHST") : CHUNK_TYPE("HPST"), sizeof(heap_id), heap_id);
1823
1824 // Send a series of heap segment chunks.
Elliott Hughesa2155262011-11-16 16:26:58 -08001825 HeapChunkContext context((what == HPSG_WHAT_MERGED_OBJECTS), native);
1826 if (native) {
1827 dlmalloc_walk_heap(HeapChunkContext::HeapChunkCallback, &context);
1828 } else {
1829 Heap::WalkHeap(HeapChunkContext::HeapChunkCallback, &context);
1830 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001831
1832 // Finally, send a heap end chunk.
1833 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHEN") : CHUNK_TYPE("HPEN"), sizeof(heap_id), heap_id);
Elliott Hughes767a1472011-10-26 18:49:02 -07001834}
1835
Elliott Hughes545a0642011-11-08 19:10:03 -08001836void Dbg::SetAllocTrackingEnabled(bool enabled) {
1837 MutexLock mu(gAllocTrackerLock);
1838 if (enabled) {
1839 if (recent_allocation_records_ == NULL) {
1840 LOG(INFO) << "Enabling alloc tracker (" << kNumAllocRecords << " entries, "
1841 << kMaxAllocRecordStackDepth << " frames --> "
1842 << (sizeof(AllocRecord) * kNumAllocRecords) << " bytes)";
1843 gAllocRecordHead = gAllocRecordCount = 0;
1844 recent_allocation_records_ = new AllocRecord[kNumAllocRecords];
1845 CHECK(recent_allocation_records_ != NULL);
1846 }
1847 } else {
1848 delete[] recent_allocation_records_;
1849 recent_allocation_records_ = NULL;
1850 }
1851}
1852
1853struct AllocRecordStackVisitor : public Thread::StackVisitor {
1854 AllocRecordStackVisitor(AllocRecord* record) : record(record), depth(0) {
1855 }
1856
1857 virtual void VisitFrame(const Frame& f, uintptr_t pc) {
1858 if (depth >= kMaxAllocRecordStackDepth) {
1859 return;
1860 }
1861 Method* m = f.GetMethod();
1862 if (m == NULL || m->IsCalleeSaveMethod()) {
1863 return;
1864 }
1865 record->stack[depth].method = m;
1866 record->stack[depth].raw_pc = pc;
1867 ++depth;
1868 }
1869
1870 ~AllocRecordStackVisitor() {
1871 // Clear out any unused stack trace elements.
1872 for (; depth < kMaxAllocRecordStackDepth; ++depth) {
1873 record->stack[depth].method = NULL;
1874 record->stack[depth].raw_pc = 0;
1875 }
1876 }
1877
1878 AllocRecord* record;
1879 size_t depth;
1880};
1881
1882void Dbg::RecordAllocation(Class* type, size_t byte_count) {
1883 Thread* self = Thread::Current();
1884 CHECK(self != NULL);
1885
1886 MutexLock mu(gAllocTrackerLock);
1887 if (recent_allocation_records_ == NULL) {
1888 return;
1889 }
1890
1891 // Advance and clip.
1892 if (++gAllocRecordHead == kNumAllocRecords) {
1893 gAllocRecordHead = 0;
1894 }
1895
1896 // Fill in the basics.
1897 AllocRecord* record = &recent_allocation_records_[gAllocRecordHead];
1898 record->type = type;
1899 record->byte_count = byte_count;
1900 record->thin_lock_id = self->GetThinLockId();
1901
1902 // Fill in the stack trace.
1903 AllocRecordStackVisitor visitor(record);
1904 self->WalkStack(&visitor);
1905
1906 if (gAllocRecordCount < kNumAllocRecords) {
1907 ++gAllocRecordCount;
1908 }
1909}
1910
1911/*
1912 * Return the index of the head element.
1913 *
1914 * We point at the most-recently-written record, so if allocRecordCount is 1
1915 * we want to use the current element. Take "head+1" and subtract count
1916 * from it.
1917 *
1918 * We need to handle underflow in our circular buffer, so we add
1919 * kNumAllocRecords and then mask it back down.
1920 */
1921inline static int headIndex() {
1922 return (gAllocRecordHead+1 + kNumAllocRecords - gAllocRecordCount) & (kNumAllocRecords-1);
1923}
1924
1925void Dbg::DumpRecentAllocations() {
1926 MutexLock mu(gAllocTrackerLock);
1927 if (recent_allocation_records_ == NULL) {
1928 LOG(INFO) << "Not recording tracked allocations";
1929 return;
1930 }
1931
1932 // "i" is the head of the list. We want to start at the end of the
1933 // list and move forward to the tail.
1934 size_t i = headIndex();
1935 size_t count = gAllocRecordCount;
1936
1937 LOG(INFO) << "Tracked allocations, (head=" << gAllocRecordHead << " count=" << count << ")";
1938 while (count--) {
1939 AllocRecord* record = &recent_allocation_records_[i];
1940
1941 LOG(INFO) << StringPrintf(" T=%-2d %6d ", record->thin_lock_id, record->byte_count)
1942 << PrettyClass(record->type);
1943
1944 for (size_t stack_frame = 0; stack_frame < kMaxAllocRecordStackDepth; ++stack_frame) {
1945 const Method* m = record->stack[stack_frame].method;
1946 if (m == NULL) {
1947 break;
1948 }
1949 LOG(INFO) << " " << PrettyMethod(m) << " line " << record->stack[stack_frame].LineNumber();
1950 }
1951
1952 // pause periodically to help logcat catch up
1953 if ((count % 5) == 0) {
1954 usleep(40000);
1955 }
1956
1957 i = (i + 1) & (kNumAllocRecords-1);
1958 }
1959}
1960
1961class StringTable {
1962 public:
1963 StringTable() {
1964 }
1965
1966 void Add(const String* s) {
1967 table_.insert(s);
1968 }
1969
1970 size_t IndexOf(const String* s) {
1971 return std::distance(table_.begin(), table_.find(s));
1972 }
1973
1974 size_t Size() {
1975 return table_.size();
1976 }
1977
1978 void WriteTo(std::vector<uint8_t>& bytes) {
1979 typedef std::set<const String*>::const_iterator It; // TODO: C++0x auto
1980 for (It it = table_.begin(); it != table_.end(); ++it) {
1981 const String* s = *it;
1982 JDWP::AppendUtf16BE(bytes, s->GetCharArray()->GetData(), s->GetLength());
1983 }
1984 }
1985
1986 private:
1987 std::set<const String*> table_;
1988 DISALLOW_COPY_AND_ASSIGN(StringTable);
1989};
1990
1991/*
1992 * The data we send to DDMS contains everything we have recorded.
1993 *
1994 * Message header (all values big-endian):
1995 * (1b) message header len (to allow future expansion); includes itself
1996 * (1b) entry header len
1997 * (1b) stack frame len
1998 * (2b) number of entries
1999 * (4b) offset to string table from start of message
2000 * (2b) number of class name strings
2001 * (2b) number of method name strings
2002 * (2b) number of source file name strings
2003 * For each entry:
2004 * (4b) total allocation size
2005 * (2b) threadId
2006 * (2b) allocated object's class name index
2007 * (1b) stack depth
2008 * For each stack frame:
2009 * (2b) method's class name
2010 * (2b) method name
2011 * (2b) method source file
2012 * (2b) line number, clipped to 32767; -2 if native; -1 if no source
2013 * (xb) class name strings
2014 * (xb) method name strings
2015 * (xb) source file strings
2016 *
2017 * As with other DDM traffic, strings are sent as a 4-byte length
2018 * followed by UTF-16 data.
2019 *
2020 * We send up 16-bit unsigned indexes into string tables. In theory there
2021 * can be (kMaxAllocRecordStackDepth * kNumAllocRecords) unique strings in
2022 * each table, but in practice there should be far fewer.
2023 *
2024 * The chief reason for using a string table here is to keep the size of
2025 * the DDMS message to a minimum. This is partly to make the protocol
2026 * efficient, but also because we have to form the whole thing up all at
2027 * once in a memory buffer.
2028 *
2029 * We use separate string tables for class names, method names, and source
2030 * files to keep the indexes small. There will generally be no overlap
2031 * between the contents of these tables.
2032 */
2033jbyteArray Dbg::GetRecentAllocations() {
2034 if (false) {
2035 DumpRecentAllocations();
2036 }
2037
2038 MutexLock mu(gAllocTrackerLock);
2039
2040 /*
2041 * Part 1: generate string tables.
2042 */
2043 StringTable class_names;
2044 StringTable method_names;
2045 StringTable filenames;
2046
2047 int count = gAllocRecordCount;
2048 int idx = headIndex();
2049 while (count--) {
2050 AllocRecord* record = &recent_allocation_records_[idx];
2051
2052 class_names.Add(record->type->GetDescriptor());
2053
2054 for (size_t i = 0; i < kMaxAllocRecordStackDepth; i++) {
2055 const Method* m = record->stack[i].method;
2056 if (m != NULL) {
2057 class_names.Add(m->GetDeclaringClass()->GetDescriptor());
2058 method_names.Add(m->GetName());
2059 filenames.Add(m->GetDeclaringClass()->GetSourceFile());
2060 }
2061 }
2062
2063 idx = (idx + 1) & (kNumAllocRecords-1);
2064 }
2065
2066 LOG(INFO) << "allocation records: " << gAllocRecordCount;
2067
2068 /*
2069 * Part 2: allocate a buffer and generate the output.
2070 */
2071 std::vector<uint8_t> bytes;
2072
2073 // (1b) message header len (to allow future expansion); includes itself
2074 // (1b) entry header len
2075 // (1b) stack frame len
2076 const int kMessageHeaderLen = 15;
2077 const int kEntryHeaderLen = 9;
2078 const int kStackFrameLen = 8;
2079 JDWP::Append1BE(bytes, kMessageHeaderLen);
2080 JDWP::Append1BE(bytes, kEntryHeaderLen);
2081 JDWP::Append1BE(bytes, kStackFrameLen);
2082
2083 // (2b) number of entries
2084 // (4b) offset to string table from start of message
2085 // (2b) number of class name strings
2086 // (2b) number of method name strings
2087 // (2b) number of source file name strings
2088 JDWP::Append2BE(bytes, gAllocRecordCount);
2089 size_t string_table_offset = bytes.size();
2090 JDWP::Append4BE(bytes, 0); // We'll patch this later...
2091 JDWP::Append2BE(bytes, class_names.Size());
2092 JDWP::Append2BE(bytes, method_names.Size());
2093 JDWP::Append2BE(bytes, filenames.Size());
2094
2095 count = gAllocRecordCount;
2096 idx = headIndex();
2097 while (count--) {
2098 // For each entry:
2099 // (4b) total allocation size
2100 // (2b) thread id
2101 // (2b) allocated object's class name index
2102 // (1b) stack depth
2103 AllocRecord* record = &recent_allocation_records_[idx];
2104 size_t stack_depth = record->GetDepth();
2105 JDWP::Append4BE(bytes, record->byte_count);
2106 JDWP::Append2BE(bytes, record->thin_lock_id);
2107 JDWP::Append2BE(bytes, class_names.IndexOf(record->type->GetDescriptor()));
2108 JDWP::Append1BE(bytes, stack_depth);
2109
2110 for (size_t stack_frame = 0; stack_frame < stack_depth; ++stack_frame) {
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 const Method* m = record->stack[stack_frame].method;
2117 JDWP::Append2BE(bytes, class_names.IndexOf(m->GetDeclaringClass()->GetDescriptor()));
2118 JDWP::Append2BE(bytes, method_names.IndexOf(m->GetName()));
2119 JDWP::Append2BE(bytes, filenames.IndexOf(m->GetDeclaringClass()->GetSourceFile()));
2120 JDWP::Append2BE(bytes, record->stack[stack_frame].LineNumber());
2121 }
2122
2123 idx = (idx + 1) & (kNumAllocRecords-1);
2124 }
2125
2126 // (xb) class name strings
2127 // (xb) method name strings
2128 // (xb) source file strings
2129 JDWP::Set4BE(&bytes[string_table_offset], bytes.size());
2130 class_names.WriteTo(bytes);
2131 method_names.WriteTo(bytes);
2132 filenames.WriteTo(bytes);
2133
2134 JNIEnv* env = Thread::Current()->GetJniEnv();
2135 jbyteArray result = env->NewByteArray(bytes.size());
2136 if (result != NULL) {
2137 env->SetByteArrayRegion(result, 0, bytes.size(), reinterpret_cast<const jbyte*>(&bytes[0]));
2138 }
2139 return result;
2140}
2141
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002142} // namespace art