blob: 494ee730b84df3a54809ad4398b41cdf9a7db777 [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 Hughes86964332012-02-15 19:37:42 -080025#include "dex_verifier.h" // For Instruction.
Elliott Hughes68fdbd02011-11-29 19:22:47 -080026#include "context.h"
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080027#include "object_utils.h"
Elliott Hughes6a5bd492011-10-28 14:33:57 -070028#include "ScopedLocalRef.h"
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -070029#include "ScopedPrimitiveArray.h"
Ian Rogers30fab402012-01-23 15:43:46 -080030#include "space.h"
Elliott Hughes47fce012011-10-25 18:37:19 -070031#include "stack_indirect_reference_table.h"
Elliott Hughes475fc232011-10-25 15:00:35 -070032#include "thread_list.h"
33
Elliott Hughes6a5bd492011-10-28 14:33:57 -070034extern "C" void dlmalloc_walk_heap(void(*)(const void*, size_t, const void*, size_t, void*), void*);
35#ifndef HAVE_ANDROID_OS
36void dlmalloc_walk_heap(void(*)(const void*, size_t, const void*, size_t, void*), void*) {
37 // No-op for glibc.
38}
39#endif
40
Elliott Hughes872d4ec2011-10-21 17:07:15 -070041namespace art {
42
Elliott Hughes545a0642011-11-08 19:10:03 -080043static const size_t kMaxAllocRecordStackDepth = 16; // Max 255.
44static const size_t kNumAllocRecords = 512; // Must be power of 2.
45
Elliott Hughes436e3722012-02-17 20:01:47 -080046static const uintptr_t kInvalidId = 1;
47static const Object* kInvalidObject = reinterpret_cast<Object*>(kInvalidId);
48
Elliott Hughes475fc232011-10-25 15:00:35 -070049class ObjectRegistry {
50 public:
51 ObjectRegistry() : lock_("ObjectRegistry lock") {
52 }
53
54 JDWP::ObjectId Add(Object* o) {
55 if (o == NULL) {
56 return 0;
57 }
58 JDWP::ObjectId id = static_cast<JDWP::ObjectId>(reinterpret_cast<uintptr_t>(o));
59 MutexLock mu(lock_);
60 map_[id] = o;
61 return id;
62 }
63
Elliott Hughes234ab152011-10-26 14:02:26 -070064 void Clear() {
65 MutexLock mu(lock_);
66 LOG(DEBUG) << "Debugger has detached; object registry had " << map_.size() << " entries";
67 map_.clear();
68 }
69
Elliott Hughes475fc232011-10-25 15:00:35 -070070 bool Contains(JDWP::ObjectId id) {
71 MutexLock mu(lock_);
72 return map_.find(id) != map_.end();
73 }
74
Elliott Hughesa2155262011-11-16 16:26:58 -080075 template<typename T> T Get(JDWP::ObjectId id) {
Elliott Hughes436e3722012-02-17 20:01:47 -080076 if (id == 0) {
77 return NULL;
78 }
79
Elliott Hughesa2155262011-11-16 16:26:58 -080080 MutexLock mu(lock_);
81 typedef std::map<JDWP::ObjectId, Object*>::iterator It; // C++0x auto
82 It it = map_.find(id);
Elliott Hughes436e3722012-02-17 20:01:47 -080083 return (it != map_.end()) ? reinterpret_cast<T>(it->second) : reinterpret_cast<T>(kInvalidId);
Elliott Hughesa2155262011-11-16 16:26:58 -080084 }
85
Elliott Hughesbfe487b2011-10-26 15:48:55 -070086 void VisitRoots(Heap::RootVisitor* visitor, void* arg) {
87 MutexLock mu(lock_);
88 typedef std::map<JDWP::ObjectId, Object*>::iterator It; // C++0x auto
89 for (It it = map_.begin(); it != map_.end(); ++it) {
90 visitor(it->second, arg);
91 }
92 }
93
Elliott Hughes475fc232011-10-25 15:00:35 -070094 private:
95 Mutex lock_;
96 std::map<JDWP::ObjectId, Object*> map_;
97};
98
Elliott Hughes545a0642011-11-08 19:10:03 -080099struct AllocRecordStackTraceElement {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800100 Method* method;
Elliott Hughes545a0642011-11-08 19:10:03 -0800101 uintptr_t raw_pc;
102
103 int32_t LineNumber() const {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800104 return MethodHelper(method).GetLineNumFromNativePC(raw_pc);
Elliott Hughes545a0642011-11-08 19:10:03 -0800105 }
106};
107
108struct AllocRecord {
109 Class* type;
110 size_t byte_count;
111 uint16_t thin_lock_id;
112 AllocRecordStackTraceElement stack[kMaxAllocRecordStackDepth]; // Unused entries have NULL method.
113
114 size_t GetDepth() {
115 size_t depth = 0;
116 while (depth < kMaxAllocRecordStackDepth && stack[depth].method != NULL) {
117 ++depth;
118 }
119 return depth;
120 }
121};
122
Elliott Hughes86964332012-02-15 19:37:42 -0800123struct Breakpoint {
124 Method* method;
125 uint32_t pc;
126 Breakpoint(Method* method, uint32_t pc) : method(method), pc(pc) {}
127};
128
129static std::ostream& operator<<(std::ostream& os, const Breakpoint& rhs) {
130 os << "Breakpoint[" << PrettyMethod(rhs.method) << " @" << rhs.pc << "]";
131 return os;
132}
133
134struct SingleStepControl {
135 // Are we single-stepping right now?
136 bool is_active;
137 Thread* thread;
138
139 JDWP::JdwpStepSize step_size;
140 JDWP::JdwpStepDepth step_depth;
141
142 const Method* method;
Elliott Hughes2435a572012-02-17 16:07:41 -0800143 int32_t line_number; // Or -1 for native methods.
144 std::set<uint32_t> dex_pcs;
Elliott Hughes86964332012-02-15 19:37:42 -0800145 int stack_depth;
146};
147
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700148// JDWP is allowed unless the Zygote forbids it.
149static bool gJdwpAllowed = true;
150
Elliott Hughes3bb81562011-10-21 18:52:59 -0700151// Was there a -Xrunjdwp or -agent argument on the command-line?
152static bool gJdwpConfigured = false;
153
154// Broken-down JDWP options. (Only valid if gJdwpConfigured is true.)
Elliott Hughes376a7a02011-10-24 18:35:55 -0700155static JDWP::JdwpOptions gJdwpOptions;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700156
157// Runtime JDWP state.
158static JDWP::JdwpState* gJdwpState = NULL;
159static bool gDebuggerConnected; // debugger or DDMS is connected.
160static bool gDebuggerActive; // debugger is making requests.
Elliott Hughes86964332012-02-15 19:37:42 -0800161static bool gDisposed; // debugger called VirtualMachine.Dispose, so we should drop the connection.
Elliott Hughes3bb81562011-10-21 18:52:59 -0700162
Elliott Hughes47fce012011-10-25 18:37:19 -0700163static bool gDdmThreadNotification = false;
164
Elliott Hughes767a1472011-10-26 18:49:02 -0700165// DDMS GC-related settings.
166static Dbg::HpifWhen gDdmHpifWhen = Dbg::HPIF_WHEN_NEVER;
167static Dbg::HpsgWhen gDdmHpsgWhen = Dbg::HPSG_WHEN_NEVER;
168static Dbg::HpsgWhat gDdmHpsgWhat;
169static Dbg::HpsgWhen gDdmNhsgWhen = Dbg::HPSG_WHEN_NEVER;
170static Dbg::HpsgWhat gDdmNhsgWhat;
171
Elliott Hughes475fc232011-10-25 15:00:35 -0700172static ObjectRegistry* gRegistry = NULL;
173
Elliott Hughes545a0642011-11-08 19:10:03 -0800174// Recent allocation tracking.
175static Mutex gAllocTrackerLock("AllocTracker lock");
176AllocRecord* Dbg::recent_allocation_records_ = NULL; // TODO: CircularBuffer<AllocRecord>
177static size_t gAllocRecordHead = 0;
178static size_t gAllocRecordCount = 0;
179
Elliott Hughes86964332012-02-15 19:37:42 -0800180// Breakpoints and single-stepping.
181static Mutex gBreakpointsLock("breakpoints lock");
182static std::vector<Breakpoint> gBreakpoints;
183static SingleStepControl gSingleStepControl;
184
185static bool IsBreakpoint(Method* m, uint32_t dex_pc) {
186 MutexLock mu(gBreakpointsLock);
Elliott Hughes2aa2e392012-02-17 17:15:43 -0800187 uint32_t pc = dex_pc / 2; // dex bytecodes are twice the size JDWP expects.
Elliott Hughes86964332012-02-15 19:37:42 -0800188 for (size_t i = 0; i < gBreakpoints.size(); ++i) {
Elliott Hughes2aa2e392012-02-17 17:15:43 -0800189 if (gBreakpoints[i].method == m && gBreakpoints[i].pc == pc) {
Elliott Hughes86964332012-02-15 19:37:42 -0800190 VLOG(jdwp) << "Hit breakpoint #" << i << ": " << gBreakpoints[i];
191 return true;
192 }
193 }
194 return false;
195}
196
Elliott Hughes436e3722012-02-17 20:01:47 -0800197static Array* DecodeArray(JDWP::RefTypeId id, JDWP::JdwpError& status) {
198 Object* o = gRegistry->Get<Object*>(id);
199 if (o == NULL || o == kInvalidObject) {
200 status = JDWP::ERR_INVALID_OBJECT;
201 return NULL;
202 }
203 if (!o->IsArrayInstance()) {
204 status = JDWP::ERR_INVALID_ARRAY;
205 return NULL;
206 }
207 status = JDWP::ERR_NONE;
208 return o->AsArray();
209}
210
211static Class* DecodeClass(JDWP::RefTypeId id, JDWP::JdwpError& status) {
212 Object* o = gRegistry->Get<Object*>(id);
213 if (o == NULL || o == kInvalidObject) {
214 status = JDWP::ERR_INVALID_OBJECT;
215 return NULL;
216 }
217 if (!o->IsClass()) {
218 status = JDWP::ERR_INVALID_CLASS;
219 return NULL;
220 }
221 status = JDWP::ERR_NONE;
222 return o->AsClass();
223}
224
225static Thread* DecodeThread(JDWP::ObjectId threadId) {
226 Object* thread_peer = gRegistry->Get<Object*>(threadId);
227 if (thread_peer == NULL || thread_peer == kInvalidObject) {
228 return NULL;
229 }
230 return Thread::FromManagedThread(thread_peer);
231}
232
Elliott Hughes24437992011-11-30 14:49:33 -0800233static JDWP::JdwpTag BasicTagFromDescriptor(const char* descriptor) {
234 // JDWP deliberately uses the descriptor characters' ASCII values for its enum.
235 // Note that by "basic" we mean that we don't get more specific than JT_OBJECT.
236 return static_cast<JDWP::JdwpTag>(descriptor[0]);
237}
238
239static JDWP::JdwpTag TagFromClass(Class* c) {
Elliott Hughes86b00102011-12-05 17:54:26 -0800240 CHECK(c != NULL);
Elliott Hughes24437992011-11-30 14:49:33 -0800241 if (c->IsArrayClass()) {
242 return JDWP::JT_ARRAY;
243 }
244
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800245 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Elliott Hughes24437992011-11-30 14:49:33 -0800246 if (c->IsStringClass()) {
247 return JDWP::JT_STRING;
248 } else if (c->IsClassClass()) {
249 return JDWP::JT_CLASS_OBJECT;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800250 } else if (class_linker->FindSystemClass("Ljava/lang/Thread;")->IsAssignableFrom(c)) {
Elliott Hughes24437992011-11-30 14:49:33 -0800251 return JDWP::JT_THREAD;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800252 } else if (class_linker->FindSystemClass("Ljava/lang/ThreadGroup;")->IsAssignableFrom(c)) {
Elliott Hughes24437992011-11-30 14:49:33 -0800253 return JDWP::JT_THREAD_GROUP;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800254 } else if (class_linker->FindSystemClass("Ljava/lang/ClassLoader;")->IsAssignableFrom(c)) {
Elliott Hughes24437992011-11-30 14:49:33 -0800255 return JDWP::JT_CLASS_LOADER;
Elliott Hughes24437992011-11-30 14:49:33 -0800256 } else {
257 return JDWP::JT_OBJECT;
258 }
259}
260
261/*
262 * Objects declared to hold Object might actually hold a more specific
263 * type. The debugger may take a special interest in these (e.g. it
264 * wants to display the contents of Strings), so we want to return an
265 * appropriate tag.
266 *
267 * Null objects are tagged JT_OBJECT.
268 */
269static JDWP::JdwpTag TagFromObject(const Object* o) {
270 return (o == NULL) ? JDWP::JT_OBJECT : TagFromClass(o->GetClass());
271}
272
273static bool IsPrimitiveTag(JDWP::JdwpTag tag) {
274 switch (tag) {
275 case JDWP::JT_BOOLEAN:
276 case JDWP::JT_BYTE:
277 case JDWP::JT_CHAR:
278 case JDWP::JT_FLOAT:
279 case JDWP::JT_DOUBLE:
280 case JDWP::JT_INT:
281 case JDWP::JT_LONG:
282 case JDWP::JT_SHORT:
283 case JDWP::JT_VOID:
284 return true;
285 default:
286 return false;
287 }
288}
289
Elliott Hughes3bb81562011-10-21 18:52:59 -0700290/*
291 * Handle one of the JDWP name/value pairs.
292 *
293 * JDWP options are:
294 * help: if specified, show help message and bail
295 * transport: may be dt_socket or dt_shmem
296 * address: for dt_socket, "host:port", or just "port" when listening
297 * server: if "y", wait for debugger to attach; if "n", attach to debugger
298 * timeout: how long to wait for debugger to connect / listen
299 *
300 * Useful with server=n (these aren't supported yet):
301 * onthrow=<exception-name>: connect to debugger when exception thrown
302 * onuncaught=y|n: connect to debugger when uncaught exception thrown
303 * launch=<command-line>: launch the debugger itself
304 *
305 * The "transport" option is required, as is "address" if server=n.
306 */
307static bool ParseJdwpOption(const std::string& name, const std::string& value) {
308 if (name == "transport") {
309 if (value == "dt_socket") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700310 gJdwpOptions.transport = JDWP::kJdwpTransportSocket;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700311 } else if (value == "dt_android_adb") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700312 gJdwpOptions.transport = JDWP::kJdwpTransportAndroidAdb;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700313 } else {
314 LOG(ERROR) << "JDWP transport not supported: " << value;
315 return false;
316 }
317 } else if (name == "server") {
318 if (value == "n") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700319 gJdwpOptions.server = false;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700320 } else if (value == "y") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700321 gJdwpOptions.server = true;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700322 } else {
323 LOG(ERROR) << "JDWP option 'server' must be 'y' or 'n'";
324 return false;
325 }
326 } else if (name == "suspend") {
327 if (value == "n") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700328 gJdwpOptions.suspend = false;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700329 } else if (value == "y") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700330 gJdwpOptions.suspend = true;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700331 } else {
332 LOG(ERROR) << "JDWP option 'suspend' must be 'y' or 'n'";
333 return false;
334 }
335 } else if (name == "address") {
336 /* this is either <port> or <host>:<port> */
337 std::string port_string;
Elliott Hughes376a7a02011-10-24 18:35:55 -0700338 gJdwpOptions.host.clear();
Elliott Hughes3bb81562011-10-21 18:52:59 -0700339 std::string::size_type colon = value.find(':');
340 if (colon != std::string::npos) {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700341 gJdwpOptions.host = value.substr(0, colon);
Elliott Hughes3bb81562011-10-21 18:52:59 -0700342 port_string = value.substr(colon + 1);
343 } else {
344 port_string = value;
345 }
346 if (port_string.empty()) {
347 LOG(ERROR) << "JDWP address missing port: " << value;
348 return false;
349 }
350 char* end;
Elliott Hughesba8eee12012-01-24 20:25:24 -0800351 uint64_t port = strtoul(port_string.c_str(), &end, 10);
352 if (*end != '\0' || port > 0xffff) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700353 LOG(ERROR) << "JDWP address has junk in port field: " << value;
354 return false;
355 }
Elliott Hughes376a7a02011-10-24 18:35:55 -0700356 gJdwpOptions.port = port;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700357 } else if (name == "launch" || name == "onthrow" || name == "oncaught" || name == "timeout") {
358 /* valid but unsupported */
359 LOG(INFO) << "Ignoring JDWP option '" << name << "'='" << value << "'";
360 } else {
361 LOG(INFO) << "Ignoring unrecognized JDWP option '" << name << "'='" << value << "'";
362 }
363
364 return true;
365}
366
367/*
368 * Parse the latter half of a -Xrunjdwp/-agentlib:jdwp= string, e.g.:
369 * "transport=dt_socket,address=8000,server=y,suspend=n"
370 */
371bool Dbg::ParseJdwpOptions(const std::string& options) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800372 VLOG(jdwp) << "ParseJdwpOptions: " << options;
Elliott Hughes47fce012011-10-25 18:37:19 -0700373
Elliott Hughes3bb81562011-10-21 18:52:59 -0700374 std::vector<std::string> pairs;
375 Split(options, ',', pairs);
376
377 for (size_t i = 0; i < pairs.size(); ++i) {
378 std::string::size_type equals = pairs[i].find('=');
379 if (equals == std::string::npos) {
380 LOG(ERROR) << "Can't parse JDWP option '" << pairs[i] << "' in '" << options << "'";
381 return false;
382 }
383 ParseJdwpOption(pairs[i].substr(0, equals), pairs[i].substr(equals + 1));
384 }
385
Elliott Hughes376a7a02011-10-24 18:35:55 -0700386 if (gJdwpOptions.transport == JDWP::kJdwpTransportUnknown) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700387 LOG(ERROR) << "Must specify JDWP transport: " << options;
388 }
Elliott Hughes376a7a02011-10-24 18:35:55 -0700389 if (!gJdwpOptions.server && (gJdwpOptions.host.empty() || gJdwpOptions.port == 0)) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700390 LOG(ERROR) << "Must specify JDWP host and port when server=n: " << options;
391 return false;
392 }
393
394 gJdwpConfigured = true;
395 return true;
396}
397
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700398void Dbg::StartJdwp() {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700399 if (!gJdwpAllowed || !gJdwpConfigured) {
400 // No JDWP for you!
401 return;
402 }
403
Elliott Hughes475fc232011-10-25 15:00:35 -0700404 CHECK(gRegistry == NULL);
405 gRegistry = new ObjectRegistry;
406
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700407 // Init JDWP if the debugger is enabled. This may connect out to a
408 // debugger, passively listen for a debugger, or block waiting for a
409 // debugger.
Elliott Hughes376a7a02011-10-24 18:35:55 -0700410 gJdwpState = JDWP::JdwpState::Create(&gJdwpOptions);
411 if (gJdwpState == NULL) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -0800412 // We probably failed because some other process has the port already, which means that
413 // if we don't abort the user is likely to think they're talking to us when they're actually
414 // talking to that other process.
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800415 LOG(FATAL) << "Debugger thread failed to initialize";
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700416 }
417
418 // If a debugger has already attached, send the "welcome" message.
419 // This may cause us to suspend all threads.
Elliott Hughes376a7a02011-10-24 18:35:55 -0700420 if (gJdwpState->IsActive()) {
Elliott Hughesa2155262011-11-16 16:26:58 -0800421 //ScopedThreadStateChange tsc(Thread::Current(), Thread::kRunnable);
Elliott Hughes376a7a02011-10-24 18:35:55 -0700422 if (!gJdwpState->PostVMStart()) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800423 LOG(WARNING) << "Failed to post 'start' message to debugger";
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700424 }
425 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700426}
427
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700428void Dbg::StopJdwp() {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700429 delete gJdwpState;
Elliott Hughes475fc232011-10-25 15:00:35 -0700430 delete gRegistry;
431 gRegistry = NULL;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700432}
433
Elliott Hughes767a1472011-10-26 18:49:02 -0700434void Dbg::GcDidFinish() {
435 if (gDdmHpifWhen != HPIF_WHEN_NEVER) {
436 LOG(DEBUG) << "Sending VM heap info to DDM";
Elliott Hughes7162ad92011-10-27 14:08:42 -0700437 DdmSendHeapInfo(gDdmHpifWhen);
Elliott Hughes767a1472011-10-26 18:49:02 -0700438 }
439 if (gDdmHpsgWhen != HPSG_WHEN_NEVER) {
440 LOG(DEBUG) << "Dumping VM heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700441 DdmSendHeapSegments(false);
Elliott Hughes767a1472011-10-26 18:49:02 -0700442 }
443 if (gDdmNhsgWhen != HPSG_WHEN_NEVER) {
444 LOG(DEBUG) << "Dumping native heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700445 DdmSendHeapSegments(true);
Elliott Hughes767a1472011-10-26 18:49:02 -0700446 }
447}
448
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700449void Dbg::SetJdwpAllowed(bool allowed) {
450 gJdwpAllowed = allowed;
451}
452
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700453DebugInvokeReq* Dbg::GetInvokeReq() {
Elliott Hughes475fc232011-10-25 15:00:35 -0700454 return Thread::Current()->GetInvokeReq();
455}
456
457Thread* Dbg::GetDebugThread() {
458 return (gJdwpState != NULL) ? gJdwpState->GetDebugThread() : NULL;
459}
460
461void Dbg::ClearWaitForEventThread() {
462 gJdwpState->ClearWaitForEventThread();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700463}
464
465void Dbg::Connected() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700466 CHECK(!gDebuggerConnected);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800467 VLOG(jdwp) << "JDWP has attached";
Elliott Hughes3bb81562011-10-21 18:52:59 -0700468 gDebuggerConnected = true;
Elliott Hughes86964332012-02-15 19:37:42 -0800469 gDisposed = false;
470}
471
472void Dbg::Disposed() {
473 gDisposed = true;
474}
475
476bool Dbg::IsDisposed() {
477 return gDisposed;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700478}
479
Elliott Hughesa2155262011-11-16 16:26:58 -0800480void Dbg::GoActive() {
481 // Enable all debugging features, including scans for breakpoints.
482 // This is a no-op if we're already active.
483 // Only called from the JDWP handler thread.
484 if (gDebuggerActive) {
485 return;
486 }
487
488 LOG(INFO) << "Debugger is active";
489
490 // TODO: CHECK we don't have any outstanding breakpoints.
491
492 gDebuggerActive = true;
493
494 //dvmEnableAllSubMode(kSubModeDebuggerActive);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700495}
496
497void Dbg::Disconnected() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700498 CHECK(gDebuggerConnected);
499
500 gDebuggerActive = false;
501
502 //dvmDisableAllSubMode(kSubModeDebuggerActive);
503
504 gRegistry->Clear();
505 gDebuggerConnected = false;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700506}
507
508bool Dbg::IsDebuggerConnected() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700509 return gDebuggerActive;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700510}
511
512bool Dbg::IsDebuggingEnabled() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700513 return gJdwpConfigured;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700514}
515
516int64_t Dbg::LastDebuggerActivity() {
Elliott Hughesca951522011-12-05 12:01:32 -0800517 return gJdwpState->LastDebuggerActivity();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700518}
519
520int Dbg::ThreadRunning() {
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700521 return static_cast<int>(Thread::Current()->SetState(Thread::kRunnable));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700522}
523
524int Dbg::ThreadWaiting() {
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700525 return static_cast<int>(Thread::Current()->SetState(Thread::kVmWait));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700526}
527
Elliott Hughes6ba581a2011-10-25 11:45:35 -0700528int Dbg::ThreadContinuing(int new_state) {
529 return static_cast<int>(Thread::Current()->SetState(static_cast<Thread::State>(new_state)));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700530}
531
532void Dbg::UndoDebuggerSuspensions() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700533 Runtime::Current()->GetThreadList()->UndoDebuggerSuspensions();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700534}
535
536void Dbg::Exit(int status) {
Elliott Hughes1bba14f2011-12-01 18:00:36 -0800537 exit(status); // This is all dalvik did.
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700538}
539
Elliott Hughesbfe487b2011-10-26 15:48:55 -0700540void Dbg::VisitRoots(Heap::RootVisitor* visitor, void* arg) {
541 if (gRegistry != NULL) {
542 gRegistry->VisitRoots(visitor, arg);
543 }
544}
545
Elliott Hughesc308a5d2012-02-16 17:12:06 -0800546std::string Dbg::GetClassName(JDWP::RefTypeId classId) {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800547 Object* o = gRegistry->Get<Object*>(classId);
Elliott Hughes436e3722012-02-17 20:01:47 -0800548 if (o == NULL) {
549 return "NULL";
550 }
551 if (o == kInvalidObject) {
552 return StringPrintf("invalid object %p", reinterpret_cast<void*>(classId));
553 }
554 if (!o->IsClass()) {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800555 return StringPrintf("non-class %p", o); // This is only used for debugging output anyway.
556 }
Elliott Hughesc308a5d2012-02-16 17:12:06 -0800557 return DescriptorToName(ClassHelper(o->AsClass()).GetDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700558}
559
Elliott Hughes436e3722012-02-17 20:01:47 -0800560JDWP::JdwpError Dbg::GetClassObject(JDWP::RefTypeId id, JDWP::ObjectId& classObjectId) {
561 JDWP::JdwpError status;
562 Class* c = DecodeClass(id, status);
563 if (c == NULL) {
564 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800565 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800566 classObjectId = gRegistry->Add(c);
567 return JDWP::ERR_NONE;
Elliott Hughes86964332012-02-15 19:37:42 -0800568}
569
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800570JDWP::JdwpError Dbg::GetSuperclass(JDWP::RefTypeId id, JDWP::RefTypeId& superclassId) {
571 JDWP::JdwpError status;
572 Class* c = DecodeClass(id, status);
573 if (c == NULL) {
574 return status;
575 }
576 if (c->IsInterface()) {
577 // http://code.google.com/p/android/issues/detail?id=20856
578 superclassId = NULL;
579 } else {
580 superclassId = gRegistry->Add(c->GetSuperClass());
581 }
582 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700583}
584
Elliott Hughes436e3722012-02-17 20:01:47 -0800585JDWP::JdwpError Dbg::GetClassLoader(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) {
Elliott Hughes1bba14f2011-12-01 18:00:36 -0800586 Object* o = gRegistry->Get<Object*>(id);
Elliott Hughes436e3722012-02-17 20:01:47 -0800587 if (o == NULL || o == kInvalidObject) {
588 return JDWP::ERR_INVALID_OBJECT;
589 }
590 expandBufAddObjectId(pReply, gRegistry->Add(o->GetClass()->GetClassLoader()));
591 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700592}
593
Elliott Hughes436e3722012-02-17 20:01:47 -0800594JDWP::JdwpError Dbg::GetModifiers(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) {
595 JDWP::JdwpError status;
596 Class* c = DecodeClass(id, status);
597 if (c == NULL) {
598 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800599 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800600
601 uint32_t access_flags = c->GetAccessFlags() & kAccJavaFlagsMask;
602
603 // Set ACC_SUPER; dex files don't contain this flag, but all classes are supposed to have it set.
604 // Class.getModifiers doesn't return it, but JDWP does, so we set it here.
605 access_flags |= kAccSuper;
606
607 expandBufAdd4BE(pReply, access_flags);
608
609 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700610}
611
Elliott Hughes436e3722012-02-17 20:01:47 -0800612JDWP::JdwpError Dbg::GetReflectedType(JDWP::RefTypeId classId, JDWP::ExpandBuf* pReply) {
613 JDWP::JdwpError status;
614 Class* c = DecodeClass(classId, status);
615 if (c == NULL) {
616 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800617 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800618
619 expandBufAdd1(pReply, c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS);
620 expandBufAddRefTypeId(pReply, classId);
621 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700622}
623
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800624void Dbg::GetClassList(std::vector<JDWP::RefTypeId>& classes) {
Elliott Hughesa2155262011-11-16 16:26:58 -0800625 // Get the complete list of reference classes (i.e. all classes except
626 // the primitive types).
627 // Returns a newly-allocated buffer full of RefTypeId values.
628 struct ClassListCreator {
Elliott Hughesba8eee12012-01-24 20:25:24 -0800629 explicit ClassListCreator(std::vector<JDWP::RefTypeId>& classes) : classes(classes) {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800630 }
631
Elliott Hughesa2155262011-11-16 16:26:58 -0800632 static bool Visit(Class* c, void* arg) {
633 return reinterpret_cast<ClassListCreator*>(arg)->Visit(c);
634 }
635
636 bool Visit(Class* c) {
637 if (!c->IsPrimitive()) {
638 classes.push_back(static_cast<JDWP::RefTypeId>(gRegistry->Add(c)));
639 }
640 return true;
641 }
642
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800643 std::vector<JDWP::RefTypeId>& classes;
Elliott Hughesa2155262011-11-16 16:26:58 -0800644 };
645
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800646 ClassListCreator clc(classes);
Elliott Hughesa2155262011-11-16 16:26:58 -0800647 Runtime::Current()->GetClassLinker()->VisitClasses(ClassListCreator::Visit, &clc);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700648}
649
Elliott Hughes436e3722012-02-17 20:01:47 -0800650JDWP::JdwpError Dbg::GetClassInfo(JDWP::RefTypeId classId, JDWP::JdwpTypeTag* pTypeTag, uint32_t* pStatus, std::string* pDescriptor) {
651 JDWP::JdwpError status;
652 Class* c = DecodeClass(classId, status);
653 if (c == NULL) {
654 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800655 }
656
Elliott Hughesa2155262011-11-16 16:26:58 -0800657 if (c->IsArrayClass()) {
658 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
659 *pTypeTag = JDWP::TT_ARRAY;
660 } else {
661 if (c->IsErroneous()) {
662 *pStatus = JDWP::CS_ERROR;
663 } else {
664 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED | JDWP::CS_INITIALIZED;
665 }
666 *pTypeTag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
667 }
668
669 if (pDescriptor != NULL) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800670 *pDescriptor = ClassHelper(c).GetDescriptor();
Elliott Hughesa2155262011-11-16 16:26:58 -0800671 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800672 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700673}
674
Elliott Hughesc3b77c72011-12-15 20:56:48 -0800675void Dbg::FindLoadedClassBySignature(const char* descriptor, std::vector<JDWP::RefTypeId>& ids) {
Elliott Hughes6fa602d2011-12-02 17:54:25 -0800676 std::vector<Class*> classes;
677 Runtime::Current()->GetClassLinker()->LookupClasses(descriptor, classes);
678 ids.clear();
679 for (size_t i = 0; i < classes.size(); ++i) {
680 ids.push_back(gRegistry->Add(classes[i]));
681 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700682}
683
Elliott Hughes2435a572012-02-17 16:07:41 -0800684JDWP::JdwpError Dbg::GetReferenceType(JDWP::ObjectId objectId, JDWP::ExpandBuf* pReply) {
Elliott Hughes499c5132011-11-17 14:55:11 -0800685 Object* o = gRegistry->Get<Object*>(objectId);
Elliott Hughes436e3722012-02-17 20:01:47 -0800686 if (o == NULL || o == kInvalidObject) {
Elliott Hughes2435a572012-02-17 16:07:41 -0800687 return JDWP::ERR_INVALID_OBJECT;
Elliott Hughes499c5132011-11-17 14:55:11 -0800688 }
Elliott Hughes2435a572012-02-17 16:07:41 -0800689
690 JDWP::JdwpTypeTag type_tag;
691 if (o->GetClass()->IsArrayClass()) {
692 type_tag = JDWP::TT_ARRAY;
693 } else if (o->GetClass()->IsInterface()) {
694 type_tag = JDWP::TT_INTERFACE;
695 } else {
696 type_tag = JDWP::TT_CLASS;
697 }
698 JDWP::RefTypeId type_id = gRegistry->Add(o->GetClass());
699
700 expandBufAdd1(pReply, type_tag);
701 expandBufAddRefTypeId(pReply, type_id);
702
703 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700704}
705
Elliott Hughes436e3722012-02-17 20:01:47 -0800706JDWP::JdwpError Dbg::GetSignature(JDWP::RefTypeId classId, std::string& signature) {
Elliott Hughes1fe7afb2012-02-13 17:23:03 -0800707 JDWP::JdwpError status;
Elliott Hughes436e3722012-02-17 20:01:47 -0800708 Class* c = DecodeClass(classId, status);
Elliott Hughes1fe7afb2012-02-13 17:23:03 -0800709 if (c == NULL) {
710 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800711 }
Elliott Hughes1fe7afb2012-02-13 17:23:03 -0800712 signature = ClassHelper(c).GetDescriptor();
713 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700714}
715
Elliott Hughes436e3722012-02-17 20:01:47 -0800716JDWP::JdwpError Dbg::GetSourceFile(JDWP::RefTypeId classId, std::string& result) {
717 JDWP::JdwpError status;
718 Class* c = DecodeClass(classId, status);
719 if (c == NULL) {
720 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800721 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800722 result = ClassHelper(c).GetSourceFile();
723 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700724}
725
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700726uint8_t Dbg::GetObjectTag(JDWP::ObjectId objectId) {
Elliott Hughes24437992011-11-30 14:49:33 -0800727 Object* o = gRegistry->Get<Object*>(objectId);
728 return TagFromObject(o);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700729}
730
Elliott Hughesaed4be92011-12-02 16:16:23 -0800731size_t Dbg::GetTagWidth(JDWP::JdwpTag tag) {
Elliott Hughesdbb40792011-11-18 17:05:22 -0800732 switch (tag) {
733 case JDWP::JT_VOID:
734 return 0;
735 case JDWP::JT_BYTE:
736 case JDWP::JT_BOOLEAN:
737 return 1;
738 case JDWP::JT_CHAR:
739 case JDWP::JT_SHORT:
740 return 2;
741 case JDWP::JT_FLOAT:
742 case JDWP::JT_INT:
743 return 4;
744 case JDWP::JT_ARRAY:
745 case JDWP::JT_OBJECT:
746 case JDWP::JT_STRING:
747 case JDWP::JT_THREAD:
748 case JDWP::JT_THREAD_GROUP:
749 case JDWP::JT_CLASS_LOADER:
750 case JDWP::JT_CLASS_OBJECT:
751 return sizeof(JDWP::ObjectId);
752 case JDWP::JT_DOUBLE:
753 case JDWP::JT_LONG:
754 return 8;
755 default:
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800756 LOG(FATAL) << "Unknown tag " << tag;
Elliott Hughesdbb40792011-11-18 17:05:22 -0800757 return -1;
758 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700759}
760
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800761JDWP::JdwpError Dbg::GetArrayLength(JDWP::ObjectId arrayId, int& length) {
762 JDWP::JdwpError status;
763 Array* a = DecodeArray(arrayId, status);
764 if (a == NULL) {
765 return status;
Elliott Hughes24437992011-11-30 14:49:33 -0800766 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800767 length = a->GetLength();
768 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700769}
770
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800771JDWP::JdwpError Dbg::OutputArray(JDWP::ObjectId arrayId, int offset, int count, JDWP::ExpandBuf* pReply) {
772 JDWP::JdwpError status;
773 Array* a = DecodeArray(arrayId, status);
774 if (a == NULL) {
775 return status;
776 }
Elliott Hughes24437992011-11-30 14:49:33 -0800777
778 if (offset < 0 || count < 0 || offset > a->GetLength() || a->GetLength() - offset < count) {
779 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800780 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughes24437992011-11-30 14:49:33 -0800781 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800782 std::string descriptor(ClassHelper(a->GetClass()).GetDescriptor());
Elliott Hughes24437992011-11-30 14:49:33 -0800783 JDWP::JdwpTag tag = BasicTagFromDescriptor(descriptor.c_str() + 1);
784
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800785 expandBufAdd1(pReply, tag);
786 expandBufAdd4BE(pReply, count);
787
Elliott Hughes24437992011-11-30 14:49:33 -0800788 if (IsPrimitiveTag(tag)) {
789 size_t width = GetTagWidth(tag);
790 const uint8_t* src = reinterpret_cast<uint8_t*>(a->GetRawData());
791 uint8_t* dst = expandBufAddSpace(pReply, count * width);
792 if (width == 8) {
793 const uint64_t* src8 = reinterpret_cast<const uint64_t*>(src);
794 for (int i = 0; i < count; ++i) JDWP::Write8BE(&dst, src8[offset + i]);
795 } else if (width == 4) {
796 const uint32_t* src4 = reinterpret_cast<const uint32_t*>(src);
797 for (int i = 0; i < count; ++i) JDWP::Write4BE(&dst, src4[offset + i]);
798 } else if (width == 2) {
799 const uint16_t* src2 = reinterpret_cast<const uint16_t*>(src);
800 for (int i = 0; i < count; ++i) JDWP::Write2BE(&dst, src2[offset + i]);
801 } else {
802 memcpy(dst, &src[offset * width], count * width);
803 }
804 } else {
805 ObjectArray<Object>* oa = a->AsObjectArray<Object>();
806 for (int i = 0; i < count; ++i) {
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800807 Object* element = oa->Get(offset + i);
Elliott Hughes24437992011-11-30 14:49:33 -0800808 JDWP::JdwpTag specific_tag = (element != NULL) ? TagFromObject(element) : tag;
809 expandBufAdd1(pReply, specific_tag);
810 expandBufAddObjectId(pReply, gRegistry->Add(element));
811 }
812 }
813
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800814 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700815}
816
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800817JDWP::JdwpError Dbg::SetArrayElements(JDWP::ObjectId arrayId, int offset, int count, const uint8_t* src) {
818 JDWP::JdwpError status;
819 Array* a = DecodeArray(arrayId, status);
820 if (a == NULL) {
821 return status;
822 }
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800823
824 if (offset < 0 || count < 0 || offset > a->GetLength() || a->GetLength() - offset < count) {
825 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800826 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800827 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800828 std::string descriptor(ClassHelper(a->GetClass()).GetDescriptor());
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800829 JDWP::JdwpTag tag = BasicTagFromDescriptor(descriptor.c_str() + 1);
830
831 if (IsPrimitiveTag(tag)) {
832 size_t width = GetTagWidth(tag);
833 uint8_t* dst = &(reinterpret_cast<uint8_t*>(a->GetRawData())[offset * width]);
834 if (width == 8) {
835 for (int i = 0; i < count; ++i) {
836 // Handle potentially non-aligned memory access one byte at a time for ARM's benefit.
837 uint64_t value;
838 for (size_t j = 0; j < sizeof(uint64_t); ++j) reinterpret_cast<uint8_t*>(&value)[j] = src[j];
839 src += sizeof(uint64_t);
840 JDWP::Write8BE(&dst, value);
841 }
842 } else if (width == 4) {
843 const uint32_t* src4 = reinterpret_cast<const uint32_t*>(src);
844 for (int i = 0; i < count; ++i) JDWP::Write4BE(&dst, src4[i]);
845 } else if (width == 2) {
846 const uint16_t* src2 = reinterpret_cast<const uint16_t*>(src);
847 for (int i = 0; i < count; ++i) JDWP::Write2BE(&dst, src2[i]);
848 } else {
849 memcpy(&dst[offset * width], src, count * width);
850 }
851 } else {
852 ObjectArray<Object>* oa = a->AsObjectArray<Object>();
853 for (int i = 0; i < count; ++i) {
854 JDWP::ObjectId id = JDWP::ReadObjectId(&src);
Elliott Hughes436e3722012-02-17 20:01:47 -0800855 Object* o = gRegistry->Get<Object*>(id);
856 if (o == kInvalidObject) {
857 return JDWP::ERR_INVALID_OBJECT;
858 }
859 oa->Set(offset + i, o);
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800860 }
861 }
862
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800863 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700864}
865
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800866JDWP::ObjectId Dbg::CreateString(const std::string& str) {
867 return gRegistry->Add(String::AllocFromModifiedUtf8(str.c_str()));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700868}
869
Elliott Hughes436e3722012-02-17 20:01:47 -0800870JDWP::JdwpError Dbg::CreateObject(JDWP::RefTypeId classId, JDWP::ObjectId& new_object) {
871 JDWP::JdwpError status;
872 Class* c = DecodeClass(classId, status);
873 if (c == NULL) {
874 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800875 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800876 new_object = gRegistry->Add(c->AllocObject());
877 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700878}
879
Elliott Hughesbf13d362011-12-08 15:51:37 -0800880/*
881 * Used by Eclipse's "Display" view to evaluate "new byte[5]" to get "(byte[]) [0, 0, 0, 0, 0]".
882 */
Elliott Hughes436e3722012-02-17 20:01:47 -0800883JDWP::JdwpError Dbg::CreateArrayObject(JDWP::RefTypeId arrayClassId, uint32_t length, JDWP::ObjectId& new_array) {
884 JDWP::JdwpError status;
885 Class* c = DecodeClass(arrayClassId, status);
886 if (c == NULL) {
887 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800888 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800889 new_array = gRegistry->Add(Array::Alloc(c, length));
890 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700891}
892
893bool Dbg::MatchType(JDWP::RefTypeId instClassId, JDWP::RefTypeId classId) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800894 JDWP::JdwpError status;
895 Class* c1 = DecodeClass(instClassId, status);
896 Class* c2 = DecodeClass(classId, status);
897 if (c1 == NULL || c2 == NULL) {
898 // TODO: it doesn't seem like we can do any better here?
899 return false;
900 }
901 return c1->InstanceOf(c2);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700902}
903
Elliott Hughes86964332012-02-15 19:37:42 -0800904static JDWP::FieldId ToFieldId(const Field* f) {
Elliott Hughes03181a82011-11-17 17:22:21 -0800905#ifdef MOVING_GARBAGE_COLLECTOR
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700906 UNIMPLEMENTED(FATAL);
Elliott Hughes03181a82011-11-17 17:22:21 -0800907#else
908 return static_cast<JDWP::FieldId>(reinterpret_cast<uintptr_t>(f));
909#endif
910}
911
Elliott Hughes86964332012-02-15 19:37:42 -0800912static JDWP::MethodId ToMethodId(const Method* m) {
Elliott Hughes03181a82011-11-17 17:22:21 -0800913#ifdef MOVING_GARBAGE_COLLECTOR
914 UNIMPLEMENTED(FATAL);
915#else
916 return static_cast<JDWP::MethodId>(reinterpret_cast<uintptr_t>(m));
917#endif
918}
919
Elliott Hughes86964332012-02-15 19:37:42 -0800920static Field* FromFieldId(JDWP::FieldId fid) {
Elliott Hughesaed4be92011-12-02 16:16:23 -0800921#ifdef MOVING_GARBAGE_COLLECTOR
922 UNIMPLEMENTED(FATAL);
923#else
924 return reinterpret_cast<Field*>(static_cast<uintptr_t>(fid));
925#endif
926}
927
Elliott Hughes86964332012-02-15 19:37:42 -0800928static Method* FromMethodId(JDWP::MethodId mid) {
Elliott Hughes03181a82011-11-17 17:22:21 -0800929#ifdef MOVING_GARBAGE_COLLECTOR
930 UNIMPLEMENTED(FATAL);
931#else
932 return reinterpret_cast<Method*>(static_cast<uintptr_t>(mid));
933#endif
934}
935
Elliott Hughes86964332012-02-15 19:37:42 -0800936static void SetLocation(JDWP::JdwpLocation& location, Method* m, uintptr_t native_pc) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -0800937 if (m == NULL) {
938 memset(&location, 0, sizeof(location));
939 } else {
940 Class* c = m->GetDeclaringClass();
941 location.typeTag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
942 location.classId = gRegistry->Add(c);
943 location.methodId = ToMethodId(m);
Elliott Hughes2aa2e392012-02-17 17:15:43 -0800944 location.idx = m->IsNative() ? -1 : m->ToDexPC(native_pc) / 2;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -0800945 }
Elliott Hughesd07986f2011-12-06 18:27:45 -0800946}
947
Elliott Hughes436e3722012-02-17 20:01:47 -0800948std::string Dbg::GetMethodName(JDWP::RefTypeId, JDWP::MethodId methodId) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800949 Method* m = FromMethodId(methodId);
950 return MethodHelper(m).GetName();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700951}
952
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800953/*
954 * Augment the access flags for synthetic methods and fields by setting
955 * the (as described by the spec) "0xf0000000 bit". Also, strip out any
956 * flags not specified by the Java programming language.
957 */
958static uint32_t MangleAccessFlags(uint32_t accessFlags) {
959 accessFlags &= kAccJavaFlagsMask;
960 if ((accessFlags & kAccSynthetic) != 0) {
961 accessFlags |= 0xf0000000;
962 }
963 return accessFlags;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700964}
965
Elliott Hughesdbb40792011-11-18 17:05:22 -0800966static const uint16_t kEclipseWorkaroundSlot = 1000;
967
968/*
969 * Eclipse appears to expect that the "this" reference is in slot zero.
970 * If it's not, the "variables" display will show two copies of "this",
971 * possibly because it gets "this" from SF.ThisObject and then displays
972 * all locals with nonzero slot numbers.
973 *
974 * So, we remap the item in slot 0 to 1000, and remap "this" to zero. On
975 * SF.GetValues / SF.SetValues we map them back.
Elliott Hughesc5b734a2011-12-01 17:20:58 -0800976 *
977 * TODO: jdb uses the value to determine whether a variable is a local or an argument,
978 * by checking whether it's less than the number of arguments. To make that work, we'd
979 * have to "mangle" all the arguments to come first, not just the implicit argument 'this'.
Elliott Hughesdbb40792011-11-18 17:05:22 -0800980 */
981static uint16_t MangleSlot(uint16_t slot, const char* name) {
982 uint16_t newSlot = slot;
983 if (strcmp(name, "this") == 0) {
984 newSlot = 0;
985 } else if (slot == 0) {
986 newSlot = kEclipseWorkaroundSlot;
987 }
988 return newSlot;
989}
990
Elliott Hughes91bf6cd2012-02-14 17:27:48 -0800991static uint16_t DemangleSlot(uint16_t slot, Method* m) {
Elliott Hughesdbb40792011-11-18 17:05:22 -0800992 if (slot == kEclipseWorkaroundSlot) {
Elliott Hughes68fdbd02011-11-29 19:22:47 -0800993 return 0;
Elliott Hughesdbb40792011-11-18 17:05:22 -0800994 } else if (slot == 0) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -0800995 const DexFile::CodeItem* code_item = MethodHelper(m).GetCodeItem();
996 CHECK(code_item != NULL);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800997 return code_item->registers_size_ - code_item->ins_size_;
Elliott Hughesdbb40792011-11-18 17:05:22 -0800998 }
Elliott Hughes68fdbd02011-11-29 19:22:47 -0800999 return slot;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001000}
1001
Elliott Hughes436e3722012-02-17 20:01:47 -08001002JDWP::JdwpError Dbg::OutputDeclaredFields(JDWP::RefTypeId classId, bool with_generic, JDWP::ExpandBuf* pReply) {
1003 JDWP::JdwpError status;
1004 Class* c = DecodeClass(classId, status);
1005 if (c == NULL) {
1006 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001007 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001008
1009 size_t instance_field_count = c->NumInstanceFields();
1010 size_t static_field_count = c->NumStaticFields();
1011
1012 expandBufAdd4BE(pReply, instance_field_count + static_field_count);
1013
1014 for (size_t i = 0; i < instance_field_count + static_field_count; ++i) {
1015 Field* f = (i < instance_field_count) ? c->GetInstanceField(i) : c->GetStaticField(i - instance_field_count);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001016 FieldHelper fh(f);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001017 expandBufAddFieldId(pReply, ToFieldId(f));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001018 expandBufAddUtf8String(pReply, fh.GetName());
1019 expandBufAddUtf8String(pReply, fh.GetTypeDescriptor());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001020 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001021 static const char genericSignature[1] = "";
1022 expandBufAddUtf8String(pReply, genericSignature);
1023 }
1024 expandBufAdd4BE(pReply, MangleAccessFlags(f->GetAccessFlags()));
1025 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001026 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001027}
1028
Elliott Hughes436e3722012-02-17 20:01:47 -08001029JDWP::JdwpError Dbg::OutputDeclaredMethods(JDWP::RefTypeId classId, bool with_generic, JDWP::ExpandBuf* pReply) {
1030 JDWP::JdwpError status;
1031 Class* c = DecodeClass(classId, status);
1032 if (c == NULL) {
1033 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001034 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001035
1036 size_t direct_method_count = c->NumDirectMethods();
1037 size_t virtual_method_count = c->NumVirtualMethods();
1038
1039 expandBufAdd4BE(pReply, direct_method_count + virtual_method_count);
1040
1041 for (size_t i = 0; i < direct_method_count + virtual_method_count; ++i) {
1042 Method* m = (i < direct_method_count) ? c->GetDirectMethod(i) : c->GetVirtualMethod(i - direct_method_count);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001043 MethodHelper mh(m);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001044 expandBufAddMethodId(pReply, ToMethodId(m));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001045 expandBufAddUtf8String(pReply, mh.GetName());
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001046 expandBufAddUtf8String(pReply, mh.GetSignature());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001047 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001048 static const char genericSignature[1] = "";
1049 expandBufAddUtf8String(pReply, genericSignature);
1050 }
1051 expandBufAdd4BE(pReply, MangleAccessFlags(m->GetAccessFlags()));
1052 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001053 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001054}
1055
Elliott Hughes436e3722012-02-17 20:01:47 -08001056JDWP::JdwpError Dbg::OutputDeclaredInterfaces(JDWP::RefTypeId classId, JDWP::ExpandBuf* pReply) {
1057 JDWP::JdwpError status;
1058 Class* c = DecodeClass(classId, status);
1059 if (c == NULL) {
1060 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001061 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001062
1063 ClassHelper kh(c);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001064 size_t interface_count = kh.NumInterfaces();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001065 expandBufAdd4BE(pReply, interface_count);
1066 for (size_t i = 0; i < interface_count; ++i) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001067 expandBufAddRefTypeId(pReply, gRegistry->Add(kh.GetInterface(i)));
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001068 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001069 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001070}
1071
Elliott Hughes436e3722012-02-17 20:01:47 -08001072void Dbg::OutputLineTable(JDWP::RefTypeId, JDWP::MethodId methodId, JDWP::ExpandBuf* pReply) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001073 struct DebugCallbackContext {
1074 int numItems;
1075 JDWP::ExpandBuf* pReply;
1076
Elliott Hughes2435a572012-02-17 16:07:41 -08001077 static bool Callback(void* context, uint32_t address, uint32_t line_number) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001078 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
1079 expandBufAdd8BE(pContext->pReply, address);
Elliott Hughes2435a572012-02-17 16:07:41 -08001080 expandBufAdd4BE(pContext->pReply, line_number);
Elliott Hughes03181a82011-11-17 17:22:21 -08001081 pContext->numItems++;
1082 return true;
1083 }
1084 };
1085
1086 Method* m = FromMethodId(methodId);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001087 MethodHelper mh(m);
Elliott Hughes03181a82011-11-17 17:22:21 -08001088 uint64_t start, end;
1089 if (m->IsNative()) {
1090 start = -1;
1091 end = -1;
1092 } else {
1093 start = 0;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001094 // TODO: what are the units supposed to be? *2?
1095 end = mh.GetCodeItem()->insns_size_in_code_units_;
Elliott Hughes03181a82011-11-17 17:22:21 -08001096 }
1097
1098 expandBufAdd8BE(pReply, start);
1099 expandBufAdd8BE(pReply, end);
1100
1101 // Add numLines later
1102 size_t numLinesOffset = expandBufGetLength(pReply);
1103 expandBufAdd4BE(pReply, 0);
1104
1105 DebugCallbackContext context;
1106 context.numItems = 0;
1107 context.pReply = pReply;
1108
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001109 mh.GetDexFile().DecodeDebugInfo(mh.GetCodeItem(), m->IsStatic(), m->GetDexMethodIndex(),
1110 DebugCallbackContext::Callback, NULL, &context);
Elliott Hughes03181a82011-11-17 17:22:21 -08001111
1112 JDWP::Set4BE(expandBufGetBuffer(pReply) + numLinesOffset, context.numItems);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001113}
1114
Elliott Hughes436e3722012-02-17 20:01:47 -08001115void Dbg::OutputVariableTable(JDWP::RefTypeId, JDWP::MethodId methodId, bool with_generic, JDWP::ExpandBuf* pReply) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001116 struct DebugCallbackContext {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001117 JDWP::ExpandBuf* pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001118 size_t variable_count;
1119 bool with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001120
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001121 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 -08001122 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
1123
Elliott Hughesaa6e1cd2012-01-18 19:26:06 -08001124 VLOG(jdwp) << StringPrintf(" %2zd: %d(%d) '%s' '%s' '%s' slot=%d", pContext->variable_count, startAddress, endAddress - startAddress, name, descriptor, signature, slot);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001125
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001126 slot = MangleSlot(slot, name);
1127
Elliott Hughesdbb40792011-11-18 17:05:22 -08001128 expandBufAdd8BE(pContext->pReply, startAddress);
1129 expandBufAddUtf8String(pContext->pReply, name);
1130 expandBufAddUtf8String(pContext->pReply, descriptor);
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001131 if (pContext->with_generic) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001132 expandBufAddUtf8String(pContext->pReply, signature);
1133 }
1134 expandBufAdd4BE(pContext->pReply, endAddress - startAddress);
1135 expandBufAdd4BE(pContext->pReply, slot);
1136
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001137 ++pContext->variable_count;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001138 }
1139 };
1140
1141 Method* m = FromMethodId(methodId);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001142 MethodHelper mh(m);
1143 const DexFile::CodeItem* code_item = mh.GetCodeItem();
Elliott Hughesdbb40792011-11-18 17:05:22 -08001144
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001145 // arg_count considers doubles and longs to take 2 units.
1146 // variable_count considers everything to take 1 unit.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001147 std::string shorty(mh.GetShorty());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001148 expandBufAdd4BE(pReply, m->NumArgRegisters(shorty));
Elliott Hughesdbb40792011-11-18 17:05:22 -08001149
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001150 // We don't know the total number of variables yet, so leave a blank and update it later.
1151 size_t variable_count_offset = expandBufGetLength(pReply);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001152 expandBufAdd4BE(pReply, 0);
1153
1154 DebugCallbackContext context;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001155 context.pReply = pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001156 context.variable_count = 0;
1157 context.with_generic = with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001158
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001159 mh.GetDexFile().DecodeDebugInfo(code_item, m->IsStatic(), m->GetDexMethodIndex(), NULL,
1160 DebugCallbackContext::Callback, &context);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001161
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001162 JDWP::Set4BE(expandBufGetBuffer(pReply) + variable_count_offset, context.variable_count);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001163}
1164
Elliott Hughesaed4be92011-12-02 16:16:23 -08001165JDWP::JdwpTag Dbg::GetFieldBasicTag(JDWP::FieldId fieldId) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001166 return BasicTagFromDescriptor(FieldHelper(FromFieldId(fieldId)).GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001167}
1168
Elliott Hughesaed4be92011-12-02 16:16:23 -08001169JDWP::JdwpTag Dbg::GetStaticFieldBasicTag(JDWP::FieldId fieldId) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001170 return BasicTagFromDescriptor(FieldHelper(FromFieldId(fieldId)).GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001171}
1172
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001173static JDWP::JdwpError GetFieldValueImpl(JDWP::ObjectId objectId, JDWP::FieldId fieldId, JDWP::ExpandBuf* pReply, bool is_static) {
Elliott Hughesaed4be92011-12-02 16:16:23 -08001174 Object* o = gRegistry->Get<Object*>(objectId);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001175 if ((!is_static && o == NULL) || o == kInvalidObject) {
1176 return JDWP::ERR_INVALID_OBJECT;
1177 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001178 Field* f = FromFieldId(fieldId);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001179 if (f->IsStatic() != is_static) {
1180 return JDWP::ERR_INVALID_FIELDID;
1181 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001182
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001183 JDWP::JdwpTag tag = BasicTagFromDescriptor(FieldHelper(f).GetTypeDescriptor());
Elliott Hughesaed4be92011-12-02 16:16:23 -08001184
1185 if (IsPrimitiveTag(tag)) {
1186 expandBufAdd1(pReply, tag);
1187 if (tag == JDWP::JT_BOOLEAN || tag == JDWP::JT_BYTE) {
1188 expandBufAdd1(pReply, f->Get32(o));
1189 } else if (tag == JDWP::JT_CHAR || tag == JDWP::JT_SHORT) {
1190 expandBufAdd2BE(pReply, f->Get32(o));
1191 } else if (tag == JDWP::JT_FLOAT || tag == JDWP::JT_INT) {
1192 expandBufAdd4BE(pReply, f->Get32(o));
1193 } else if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
1194 expandBufAdd8BE(pReply, f->Get64(o));
1195 } else {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001196 LOG(FATAL) << "Unknown tag: " << tag;
Elliott Hughesaed4be92011-12-02 16:16:23 -08001197 }
1198 } else {
1199 Object* value = f->GetObject(o);
1200 expandBufAdd1(pReply, TagFromObject(value));
1201 expandBufAddObjectId(pReply, gRegistry->Add(value));
1202 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001203 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001204}
1205
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001206JDWP::JdwpError Dbg::GetFieldValue(JDWP::ObjectId objectId, JDWP::FieldId fieldId, JDWP::ExpandBuf* pReply) {
1207 return GetFieldValueImpl(objectId, fieldId, pReply, false);
1208}
1209
1210JDWP::JdwpError Dbg::GetStaticFieldValue(JDWP::FieldId fieldId, JDWP::ExpandBuf* pReply) {
1211 return GetFieldValueImpl(0, fieldId, pReply, true);
1212}
1213
1214static JDWP::JdwpError SetFieldValueImpl(JDWP::ObjectId objectId, JDWP::FieldId fieldId, uint64_t value, int width, bool is_static) {
Elliott Hughesaed4be92011-12-02 16:16:23 -08001215 Object* o = gRegistry->Get<Object*>(objectId);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001216 if ((!is_static && o == NULL) || o == kInvalidObject) {
1217 return JDWP::ERR_INVALID_OBJECT;
1218 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001219 Field* f = FromFieldId(fieldId);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001220 if (f->IsStatic() != is_static) {
1221 return JDWP::ERR_INVALID_FIELDID;
1222 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001223
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001224 JDWP::JdwpTag tag = BasicTagFromDescriptor(FieldHelper(f).GetTypeDescriptor());
Elliott Hughesaed4be92011-12-02 16:16:23 -08001225
1226 if (IsPrimitiveTag(tag)) {
1227 if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
1228 f->Set64(o, value);
1229 } else {
1230 f->Set32(o, value);
1231 }
1232 } else {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001233 Object* v = gRegistry->Get<Object*>(value);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001234 if (v == kInvalidObject) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001235 return JDWP::ERR_INVALID_OBJECT;
1236 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001237 if (v != NULL) {
1238 Class* field_type = FieldHelper(f).GetType();
1239 if (!field_type->IsAssignableFrom(v->GetClass())) {
1240 return JDWP::ERR_INVALID_OBJECT;
1241 }
1242 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001243 f->SetObject(o, v);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001244 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001245
1246 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001247}
1248
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001249JDWP::JdwpError Dbg::SetFieldValue(JDWP::ObjectId objectId, JDWP::FieldId fieldId, uint64_t value, int width) {
1250 return SetFieldValueImpl(objectId, fieldId, value, width, false);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001251}
1252
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001253JDWP::JdwpError Dbg::SetStaticFieldValue(JDWP::FieldId fieldId, uint64_t value, int width) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001254 return SetFieldValueImpl(0, fieldId, value, width, true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001255}
1256
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001257std::string Dbg::StringToUtf8(JDWP::ObjectId strId) {
1258 String* s = gRegistry->Get<String*>(strId);
1259 return s->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001260}
1261
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001262bool Dbg::GetThreadName(JDWP::ObjectId threadId, std::string& name) {
1263 ScopedThreadListLock thread_list_lock;
1264 Thread* thread = DecodeThread(threadId);
1265 if (thread == NULL) {
1266 return false;
1267 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001268 name = thread->GetThreadName()->ToModifiedUtf8();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001269 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001270}
1271
Elliott Hughes2435a572012-02-17 16:07:41 -08001272JDWP::JdwpError Dbg::GetThreadGroup(JDWP::ObjectId threadId, JDWP::ExpandBuf* pReply) {
Elliott Hughes499c5132011-11-17 14:55:11 -08001273 Object* thread = gRegistry->Get<Object*>(threadId);
Elliott Hughes436e3722012-02-17 20:01:47 -08001274 if (thread == kInvalidObject) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001275 return JDWP::ERR_INVALID_OBJECT;
1276 }
1277
1278 // Okay, so it's an object, but is it actually a thread?
Elliott Hughes436e3722012-02-17 20:01:47 -08001279 if (DecodeThread(threadId) == NULL) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001280 return JDWP::ERR_INVALID_THREAD;
1281 }
Elliott Hughes499c5132011-11-17 14:55:11 -08001282
1283 Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/Thread;");
1284 CHECK(c != NULL);
1285 Field* f = c->FindInstanceField("group", "Ljava/lang/ThreadGroup;");
1286 CHECK(f != NULL);
1287 Object* group = f->GetObject(thread);
1288 CHECK(group != NULL);
Elliott Hughes2435a572012-02-17 16:07:41 -08001289 JDWP::ObjectId thread_group_id = gRegistry->Add(group);
1290
1291 expandBufAddObjectId(pReply, thread_group_id);
1292 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001293}
1294
Elliott Hughes499c5132011-11-17 14:55:11 -08001295std::string Dbg::GetThreadGroupName(JDWP::ObjectId threadGroupId) {
1296 Object* thread_group = gRegistry->Get<Object*>(threadGroupId);
1297 CHECK(thread_group != NULL);
1298
1299 Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/ThreadGroup;");
1300 CHECK(c != NULL);
1301 Field* f = c->FindInstanceField("name", "Ljava/lang/String;");
1302 CHECK(f != NULL);
1303 String* s = reinterpret_cast<String*>(f->GetObject(thread_group));
1304 return s->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001305}
1306
1307JDWP::ObjectId Dbg::GetThreadGroupParent(JDWP::ObjectId threadGroupId) {
Elliott Hughes4e235312011-12-02 11:34:15 -08001308 Object* thread_group = gRegistry->Get<Object*>(threadGroupId);
1309 CHECK(thread_group != NULL);
1310
1311 Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/ThreadGroup;");
1312 CHECK(c != NULL);
1313 Field* f = c->FindInstanceField("parent", "Ljava/lang/ThreadGroup;");
1314 CHECK(f != NULL);
1315 Object* parent = f->GetObject(thread_group);
1316 return gRegistry->Add(parent);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001317}
1318
Elliott Hughes499c5132011-11-17 14:55:11 -08001319static Object* GetStaticThreadGroup(const char* field_name) {
1320 Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/ThreadGroup;");
1321 CHECK(c != NULL);
1322 Field* f = c->FindStaticField(field_name, "Ljava/lang/ThreadGroup;");
1323 CHECK(f != NULL);
1324 Object* group = f->GetObject(NULL);
1325 CHECK(group != NULL);
1326 return group;
1327}
1328
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001329JDWP::ObjectId Dbg::GetSystemThreadGroupId() {
Elliott Hughes499c5132011-11-17 14:55:11 -08001330 return gRegistry->Add(GetStaticThreadGroup("mSystem"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001331}
1332
1333JDWP::ObjectId Dbg::GetMainThreadGroupId() {
Elliott Hughes499c5132011-11-17 14:55:11 -08001334 return gRegistry->Add(GetStaticThreadGroup("mMain"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001335}
1336
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001337bool Dbg::GetThreadStatus(JDWP::ObjectId threadId, JDWP::JdwpThreadStatus* pThreadStatus, JDWP::JdwpSuspendStatus* pSuspendStatus) {
Elliott Hughes499c5132011-11-17 14:55:11 -08001338 ScopedThreadListLock thread_list_lock;
1339
1340 Thread* thread = DecodeThread(threadId);
1341 if (thread == NULL) {
1342 return false;
1343 }
1344
1345 switch (thread->GetState()) {
1346 case Thread::kTerminated: *pThreadStatus = JDWP::TS_ZOMBIE; break;
1347 case Thread::kRunnable: *pThreadStatus = JDWP::TS_RUNNING; break;
1348 case Thread::kTimedWaiting: *pThreadStatus = JDWP::TS_SLEEPING; break;
1349 case Thread::kBlocked: *pThreadStatus = JDWP::TS_MONITOR; break;
1350 case Thread::kWaiting: *pThreadStatus = JDWP::TS_WAIT; break;
1351 case Thread::kInitializing: *pThreadStatus = JDWP::TS_ZOMBIE; break;
1352 case Thread::kStarting: *pThreadStatus = JDWP::TS_ZOMBIE; break;
1353 case Thread::kNative: *pThreadStatus = JDWP::TS_RUNNING; break;
1354 case Thread::kVmWait: *pThreadStatus = JDWP::TS_WAIT; break;
1355 case Thread::kSuspended: *pThreadStatus = JDWP::TS_RUNNING; break;
1356 default:
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001357 LOG(FATAL) << "Unknown thread state " << thread->GetState();
Elliott Hughes499c5132011-11-17 14:55:11 -08001358 }
1359
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001360 *pSuspendStatus = (thread->IsSuspended() ? JDWP::SUSPEND_STATUS_SUSPENDED : JDWP::SUSPEND_STATUS_NOT_SUSPENDED);
Elliott Hughes499c5132011-11-17 14:55:11 -08001361
1362 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001363}
1364
Elliott Hughes2435a572012-02-17 16:07:41 -08001365JDWP::JdwpError Dbg::GetThreadSuspendCount(JDWP::ObjectId threadId, JDWP::ExpandBuf* pReply) {
1366 Thread* thread = DecodeThread(threadId);
1367 if (thread == NULL) {
1368 return JDWP::ERR_INVALID_THREAD;
1369 }
1370 expandBufAdd4BE(pReply, thread->GetSuspendCount());
1371 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001372}
1373
1374bool Dbg::ThreadExists(JDWP::ObjectId threadId) {
Elliott Hughes761928d2011-11-16 18:33:03 -08001375 return DecodeThread(threadId) != NULL;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001376}
1377
1378bool Dbg::IsSuspended(JDWP::ObjectId threadId) {
Elliott Hughes761928d2011-11-16 18:33:03 -08001379 return DecodeThread(threadId)->IsSuspended();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001380}
1381
Elliott Hughesa2155262011-11-16 16:26:58 -08001382void Dbg::GetThreadGroupThreadsImpl(Object* thread_group, JDWP::ObjectId** ppThreadIds, uint32_t* pThreadCount) {
1383 struct ThreadListVisitor {
1384 static void Visit(Thread* t, void* arg) {
1385 reinterpret_cast<ThreadListVisitor*>(arg)->Visit(t);
1386 }
1387
1388 void Visit(Thread* t) {
1389 if (t == Dbg::GetDebugThread()) {
1390 // Skip the JDWP thread. Some debuggers get bent out of shape when they can't suspend and
1391 // query all threads, so it's easier if we just don't tell them about this thread.
1392 return;
1393 }
1394 if (thread_group == NULL || t->GetThreadGroup() == thread_group) {
1395 threads.push_back(gRegistry->Add(t->GetPeer()));
1396 }
1397 }
1398
1399 Object* thread_group;
1400 std::vector<JDWP::ObjectId> threads;
1401 };
1402
1403 ThreadListVisitor tlv;
1404 tlv.thread_group = thread_group;
1405
1406 {
1407 ScopedThreadListLock thread_list_lock;
1408 Runtime::Current()->GetThreadList()->ForEach(ThreadListVisitor::Visit, &tlv);
1409 }
1410
1411 *pThreadCount = tlv.threads.size();
1412 if (*pThreadCount == 0) {
1413 *ppThreadIds = NULL;
1414 } else {
1415 *ppThreadIds = new JDWP::ObjectId[*pThreadCount];
1416 for (size_t i = 0; i < *pThreadCount; ++i) {
1417 (*ppThreadIds)[i] = tlv.threads[i];
1418 }
1419 }
1420}
1421
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001422void Dbg::GetThreadGroupThreads(JDWP::ObjectId threadGroupId, JDWP::ObjectId** ppThreadIds, uint32_t* pThreadCount) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001423 GetThreadGroupThreadsImpl(gRegistry->Get<Object*>(threadGroupId), ppThreadIds, pThreadCount);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001424}
1425
1426void Dbg::GetAllThreads(JDWP::ObjectId** ppThreadIds, uint32_t* pThreadCount) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001427 GetThreadGroupThreadsImpl(NULL, ppThreadIds, pThreadCount);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001428}
1429
Elliott Hughes86964332012-02-15 19:37:42 -08001430static int GetStackDepth(Thread* thread) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001431 struct CountStackDepthVisitor : public Thread::StackVisitor {
1432 CountStackDepthVisitor() : depth(0) {}
Elliott Hughesf8a2df72011-12-01 12:19:54 -08001433 virtual void VisitFrame(const Frame& f, uintptr_t) {
1434 // TODO: we'll need to skip callee-save frames too.
1435 if (f.HasMethod()) {
1436 ++depth;
1437 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001438 }
1439 size_t depth;
1440 };
1441 CountStackDepthVisitor visitor;
Elliott Hughes86964332012-02-15 19:37:42 -08001442 thread->WalkStack(&visitor);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001443 return visitor.depth;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001444}
1445
Elliott Hughes86964332012-02-15 19:37:42 -08001446int Dbg::GetThreadFrameCount(JDWP::ObjectId threadId) {
1447 ScopedThreadListLock thread_list_lock;
1448 return GetStackDepth(DecodeThread(threadId));
1449}
1450
Elliott Hughes03181a82011-11-17 17:22:21 -08001451bool Dbg::GetThreadFrame(JDWP::ObjectId threadId, int desired_frame_number, JDWP::FrameId* pFrameId, JDWP::JdwpLocation* pLoc) {
1452 ScopedThreadListLock thread_list_lock;
1453 struct GetFrameVisitor : public Thread::StackVisitor {
1454 GetFrameVisitor(int desired_frame_number, JDWP::FrameId* pFrameId, JDWP::JdwpLocation* pLoc)
Elliott Hughesba8eee12012-01-24 20:25:24 -08001455 : found(false), depth(0), desired_frame_number(desired_frame_number), pFrameId(pFrameId), pLoc(pLoc) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001456 }
1457 virtual void VisitFrame(const Frame& f, uintptr_t pc) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -08001458 // TODO: we'll need to skip callee-save frames too.
Elliott Hughes03181a82011-11-17 17:22:21 -08001459 if (!f.HasMethod()) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -08001460 return; // The debugger can't do anything useful with a frame that has no Method*.
Elliott Hughes03181a82011-11-17 17:22:21 -08001461 }
1462
1463 if (depth == desired_frame_number) {
1464 *pFrameId = reinterpret_cast<JDWP::FrameId>(f.GetSP());
Elliott Hughesd07986f2011-12-06 18:27:45 -08001465 SetLocation(*pLoc, f.GetMethod(), pc);
Elliott Hughes03181a82011-11-17 17:22:21 -08001466 found = true;
1467 }
1468 ++depth;
1469 }
1470 bool found;
1471 int depth;
1472 int desired_frame_number;
1473 JDWP::FrameId* pFrameId;
1474 JDWP::JdwpLocation* pLoc;
1475 };
1476 GetFrameVisitor visitor(desired_frame_number, pFrameId, pLoc);
1477 visitor.desired_frame_number = desired_frame_number;
1478 DecodeThread(threadId)->WalkStack(&visitor);
1479 return visitor.found;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001480}
1481
1482JDWP::ObjectId Dbg::GetThreadSelfId() {
Elliott Hughes475fc232011-10-25 15:00:35 -07001483 return gRegistry->Add(Thread::Current()->GetPeer());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001484}
1485
Elliott Hughes475fc232011-10-25 15:00:35 -07001486void Dbg::SuspendVM() {
Elliott Hughesa2155262011-11-16 16:26:58 -08001487 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 -07001488 Runtime::Current()->GetThreadList()->SuspendAll(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001489}
1490
1491void Dbg::ResumeVM() {
Elliott Hughes475fc232011-10-25 15:00:35 -07001492 Runtime::Current()->GetThreadList()->ResumeAll(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001493}
1494
1495void Dbg::SuspendThread(JDWP::ObjectId threadId) {
Elliott Hughes4e235312011-12-02 11:34:15 -08001496 Object* peer = gRegistry->Get<Object*>(threadId);
1497 ScopedThreadListLock thread_list_lock;
1498 Thread* thread = Thread::FromManagedThread(peer);
1499 if (thread == NULL) {
1500 LOG(WARNING) << "No such thread for suspend: " << peer;
1501 return;
1502 }
1503 Runtime::Current()->GetThreadList()->Suspend(thread, true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001504}
1505
1506void Dbg::ResumeThread(JDWP::ObjectId threadId) {
Elliott Hughes4e235312011-12-02 11:34:15 -08001507 Object* peer = gRegistry->Get<Object*>(threadId);
1508 ScopedThreadListLock thread_list_lock;
1509 Thread* thread = Thread::FromManagedThread(peer);
1510 if (thread == NULL) {
1511 LOG(WARNING) << "No such thread for resume: " << peer;
1512 return;
1513 }
1514 Runtime::Current()->GetThreadList()->Resume(thread, true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001515}
1516
1517void Dbg::SuspendSelf() {
Elliott Hughes475fc232011-10-25 15:00:35 -07001518 Runtime::Current()->GetThreadList()->SuspendSelfForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001519}
1520
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001521static Object* GetThis(Frame& f) {
Elliott Hughes86b00102011-12-05 17:54:26 -08001522 Method* m = f.GetMethod();
Elliott Hughes86b00102011-12-05 17:54:26 -08001523 Object* o = NULL;
1524 if (!m->IsNative() && !m->IsStatic()) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001525 uint16_t reg = DemangleSlot(0, m);
Elliott Hughes86b00102011-12-05 17:54:26 -08001526 o = reinterpret_cast<Object*>(f.GetVReg(m, reg));
1527 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001528 return o;
1529}
1530
1531void Dbg::GetThisObject(JDWP::FrameId frameId, JDWP::ObjectId* pThisId) {
1532 Method** sp = reinterpret_cast<Method**>(frameId);
1533 Frame f(sp);
1534 Object* o = GetThis(f);
Elliott Hughes86b00102011-12-05 17:54:26 -08001535 *pThisId = gRegistry->Add(o);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001536}
1537
Elliott Hughescccd84f2011-12-05 16:51:54 -08001538void Dbg::GetLocalValue(JDWP::ObjectId threadId, JDWP::FrameId frameId, int slot, JDWP::JdwpTag tag, uint8_t* buf, size_t width) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001539 Method** sp = reinterpret_cast<Method**>(frameId);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001540 Frame f(sp);
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001541 Method* m = f.GetMethod();
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001542 uint16_t reg = DemangleSlot(slot, m);
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001543
1544 const VmapTable vmap_table(m->GetVmapTableRaw());
1545 uint32_t vmap_offset;
1546 if (vmap_table.IsInContext(reg, vmap_offset)) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001547 UNIMPLEMENTED(FATAL) << "Don't know how to pull locals from callee save frames: " << vmap_offset;
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001548 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001549
1550 switch (tag) {
1551 case JDWP::JT_BOOLEAN:
1552 {
Elliott Hughescccd84f2011-12-05 16:51:54 -08001553 CHECK_EQ(width, 1U);
Elliott Hughes1bba14f2011-12-01 18:00:36 -08001554 uint32_t intVal = f.GetVReg(m, reg);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001555 VLOG(jdwp) << "get boolean local " << reg << " = " << intVal;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001556 JDWP::Set1(buf+1, intVal != 0);
1557 }
1558 break;
1559 case JDWP::JT_BYTE:
1560 {
Elliott Hughescccd84f2011-12-05 16:51:54 -08001561 CHECK_EQ(width, 1U);
Elliott Hughes1bba14f2011-12-01 18:00:36 -08001562 uint32_t intVal = f.GetVReg(m, reg);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001563 VLOG(jdwp) << "get byte local " << reg << " = " << intVal;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001564 JDWP::Set1(buf+1, intVal);
1565 }
1566 break;
1567 case JDWP::JT_SHORT:
1568 case JDWP::JT_CHAR:
1569 {
Elliott Hughescccd84f2011-12-05 16:51:54 -08001570 CHECK_EQ(width, 2U);
Elliott Hughes1bba14f2011-12-01 18:00:36 -08001571 uint32_t intVal = f.GetVReg(m, reg);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001572 VLOG(jdwp) << "get short/char local " << reg << " = " << intVal;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001573 JDWP::Set2BE(buf+1, intVal);
1574 }
1575 break;
1576 case JDWP::JT_INT:
1577 case JDWP::JT_FLOAT:
1578 {
Elliott Hughescccd84f2011-12-05 16:51:54 -08001579 CHECK_EQ(width, 4U);
Elliott Hughes1bba14f2011-12-01 18:00:36 -08001580 uint32_t intVal = f.GetVReg(m, reg);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001581 VLOG(jdwp) << "get int/float local " << reg << " = " << intVal;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001582 JDWP::Set4BE(buf+1, intVal);
1583 }
1584 break;
1585 case JDWP::JT_ARRAY:
1586 {
Elliott Hughescccd84f2011-12-05 16:51:54 -08001587 CHECK_EQ(width, sizeof(JDWP::ObjectId));
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001588 Object* o = reinterpret_cast<Object*>(f.GetVReg(m, reg));
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001589 VLOG(jdwp) << "get array local " << reg << " = " << o;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001590 if (o != NULL && !Heap::IsHeapAddress(o)) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001591 LOG(FATAL) << "Register " << reg << " expected to hold array: " << o;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001592 }
1593 JDWP::SetObjectId(buf+1, gRegistry->Add(o));
1594 }
1595 break;
1596 case JDWP::JT_OBJECT:
1597 {
Elliott Hughescccd84f2011-12-05 16:51:54 -08001598 CHECK_EQ(width, sizeof(JDWP::ObjectId));
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001599 Object* o = reinterpret_cast<Object*>(f.GetVReg(m, reg));
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001600 VLOG(jdwp) << "get object local " << reg << " = " << o;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001601 if (o != NULL && !Heap::IsHeapAddress(o)) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001602 LOG(FATAL) << "Register " << reg << " expected to hold object: " << o;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001603 }
1604 tag = TagFromObject(o);
1605 JDWP::SetObjectId(buf+1, gRegistry->Add(o));
1606 }
1607 break;
1608 case JDWP::JT_DOUBLE:
1609 case JDWP::JT_LONG:
1610 {
Elliott Hughescccd84f2011-12-05 16:51:54 -08001611 CHECK_EQ(width, 8U);
Elliott Hughes1bba14f2011-12-01 18:00:36 -08001612 uint32_t lo = f.GetVReg(m, reg);
1613 uint64_t hi = f.GetVReg(m, reg + 1);
1614 uint64_t longVal = (hi << 32) | lo;
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001615 VLOG(jdwp) << "get double/long local " << hi << ":" << lo << " = " << longVal;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001616 JDWP::Set8BE(buf+1, longVal);
1617 }
1618 break;
1619 default:
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001620 LOG(FATAL) << "Unknown tag " << tag;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001621 break;
1622 }
1623
1624 // Prepend tag, which may have been updated.
1625 JDWP::Set1(buf, tag);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001626}
1627
Elliott Hughesdbb40792011-11-18 17:05:22 -08001628void Dbg::SetLocalValue(JDWP::ObjectId threadId, JDWP::FrameId frameId, int slot, JDWP::JdwpTag tag, uint64_t value, size_t width) {
Elliott Hughescccd84f2011-12-05 16:51:54 -08001629 Method** sp = reinterpret_cast<Method**>(frameId);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001630 Frame f(sp);
Elliott Hughescccd84f2011-12-05 16:51:54 -08001631 Method* m = f.GetMethod();
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001632 uint16_t reg = DemangleSlot(slot, m);
Elliott Hughescccd84f2011-12-05 16:51:54 -08001633
1634 const VmapTable vmap_table(m->GetVmapTableRaw());
1635 uint32_t vmap_offset;
1636 if (vmap_table.IsInContext(reg, vmap_offset)) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001637 UNIMPLEMENTED(FATAL) << "Don't know how to pull locals from callee save frames: " << vmap_offset;
Elliott Hughescccd84f2011-12-05 16:51:54 -08001638 }
1639
1640 switch (tag) {
1641 case JDWP::JT_BOOLEAN:
1642 case JDWP::JT_BYTE:
1643 CHECK_EQ(width, 1U);
1644 f.SetVReg(m, reg, static_cast<uint32_t>(value));
1645 break;
1646 case JDWP::JT_SHORT:
1647 case JDWP::JT_CHAR:
1648 CHECK_EQ(width, 2U);
1649 f.SetVReg(m, reg, static_cast<uint32_t>(value));
1650 break;
1651 case JDWP::JT_INT:
1652 case JDWP::JT_FLOAT:
1653 CHECK_EQ(width, 4U);
1654 f.SetVReg(m, reg, static_cast<uint32_t>(value));
1655 break;
1656 case JDWP::JT_ARRAY:
1657 case JDWP::JT_OBJECT:
1658 case JDWP::JT_STRING:
1659 {
1660 CHECK_EQ(width, sizeof(JDWP::ObjectId));
1661 Object* o = gRegistry->Get<Object*>(static_cast<JDWP::ObjectId>(value));
1662 f.SetVReg(m, reg, static_cast<uint32_t>(reinterpret_cast<uintptr_t>(o)));
1663 }
1664 break;
1665 case JDWP::JT_DOUBLE:
1666 case JDWP::JT_LONG:
1667 CHECK_EQ(width, 8U);
1668 f.SetVReg(m, reg, static_cast<uint32_t>(value));
1669 f.SetVReg(m, reg + 1, static_cast<uint32_t>(value >> 32));
1670 break;
1671 default:
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001672 LOG(FATAL) << "Unknown tag " << tag;
Elliott Hughescccd84f2011-12-05 16:51:54 -08001673 break;
1674 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001675}
1676
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001677void Dbg::PostLocationEvent(const Method* m, int dex_pc, Object* this_object, int event_flags) {
1678 Class* c = m->GetDeclaringClass();
1679
1680 JDWP::JdwpLocation location;
1681 location.typeTag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
1682 location.classId = gRegistry->Add(c);
1683 location.methodId = ToMethodId(m);
Elliott Hughes2aa2e392012-02-17 17:15:43 -08001684 location.idx = m->IsNative() ? -1 : dex_pc / 2;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001685
1686 // Note we use "NoReg" so we don't keep track of references that are
1687 // never actually sent to the debugger. 'this_id' is only used to
1688 // compare against registered events...
1689 JDWP::ObjectId this_id = static_cast<JDWP::ObjectId>(reinterpret_cast<uintptr_t>(this_object));
1690 if (gJdwpState->PostLocationEvent(&location, this_id, event_flags)) {
1691 // ...unless there's a registered event, in which case we
1692 // need to really track the class and 'this'.
1693 gRegistry->Add(c);
1694 gRegistry->Add(this_object);
1695 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001696}
1697
Elliott Hughesd07986f2011-12-06 18:27:45 -08001698void Dbg::PostException(Method** sp, Method* throwMethod, uintptr_t throwNativePc, Method* catchMethod, uintptr_t catchNativePc, Object* exception) {
Ian Rogers0ad5bb82011-12-07 10:16:32 -08001699 if (!gDebuggerActive) {
1700 return;
1701 }
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001702
Elliott Hughesd07986f2011-12-06 18:27:45 -08001703 JDWP::JdwpLocation throw_location;
1704 SetLocation(throw_location, throwMethod, throwNativePc);
1705 JDWP::JdwpLocation catch_location;
1706 SetLocation(catch_location, catchMethod, catchNativePc);
1707
1708 // We need 'this' for InstanceOnly filters.
1709 JDWP::ObjectId this_id;
1710 GetThisObject(reinterpret_cast<JDWP::FrameId>(sp), &this_id);
1711
1712 /*
1713 * Hand the event to the JDWP exception handler. Note we're using the
1714 * "NoReg" objectID on the exception, which is not strictly correct --
1715 * the exception object WILL be passed up to the debugger if the
1716 * debugger is interested in the event. We do this because the current
1717 * implementation of the debugger object registry never throws anything
1718 * away, and some people were experiencing a fatal build up of exception
1719 * objects when dealing with certain libraries.
1720 */
1721 JDWP::ObjectId exception_id = static_cast<JDWP::ObjectId>(reinterpret_cast<uintptr_t>(exception));
1722 JDWP::RefTypeId exception_class_id = gRegistry->Add(exception->GetClass());
1723
1724 gJdwpState->PostException(&throw_location, exception_id, exception_class_id, &catch_location, this_id);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001725}
1726
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001727void Dbg::PostClassPrepare(Class* c) {
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001728 if (!gDebuggerActive) {
1729 return;
1730 }
1731
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001732 // OLD-TODO - we currently always send both "verified" and "prepared" since
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001733 // debuggers seem to like that. There might be some advantage to honesty,
1734 // since the class may not yet be verified.
1735 int state = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
1736 JDWP::JdwpTypeTag tag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
1737 gJdwpState->PostClassPrepare(tag, gRegistry->Add(c), ClassHelper(c).GetDescriptor(), state);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001738}
1739
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001740void Dbg::UpdateDebugger(int32_t dex_pc, Thread* self, Method** sp) {
Elliott Hughes2aa2e392012-02-17 17:15:43 -08001741 if (!gDebuggerActive || dex_pc == -2 /* fake method exit */) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001742 return;
1743 }
1744
Elliott Hughes86964332012-02-15 19:37:42 -08001745 Frame f(sp);
1746 f.Next(); // Skip callee save frame.
1747 Method* m = f.GetMethod();
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001748
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001749 if (dex_pc == -1) {
Elliott Hughes2aa2e392012-02-17 17:15:43 -08001750 // We use a pc of -1 to represent method entry, since we might branch back to pc 0 later.
1751 // This means that for this special notification, there can't be anything else interesting
1752 // going on, so we're done already.
1753 Dbg::PostLocationEvent(m, 0, GetThis(f), kMethodEntry);
1754 return;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001755 }
1756
Elliott Hughes2aa2e392012-02-17 17:15:43 -08001757 int event_flags = 0;
1758
Elliott Hughes86964332012-02-15 19:37:42 -08001759 if (IsBreakpoint(m, dex_pc)) {
1760 event_flags |= kBreakpoint;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001761 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001762
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001763 // If the debugger is single-stepping one of our threads, check to
1764 // see if we're that thread and we've reached a step point.
Elliott Hughes86964332012-02-15 19:37:42 -08001765 if (gSingleStepControl.is_active && gSingleStepControl.thread == self) {
1766 CHECK(!m->IsNative());
1767 if (gSingleStepControl.step_depth == JDWP::SD_INTO) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001768 // Step into method calls. We break when the line number
1769 // or method pointer changes. If we're in SS_MIN mode, we
1770 // always stop.
Elliott Hughes86964332012-02-15 19:37:42 -08001771 if (gSingleStepControl.method != m) {
1772 event_flags |= kSingleStep;
1773 VLOG(jdwp) << "SS new method";
1774 } else if (gSingleStepControl.step_size == JDWP::SS_MIN) {
1775 event_flags |= kSingleStep;
1776 VLOG(jdwp) << "SS new instruction";
Elliott Hughes2435a572012-02-17 16:07:41 -08001777 } else if (gSingleStepControl.dex_pcs.find(dex_pc) == gSingleStepControl.dex_pcs.end()) {
1778 event_flags |= kSingleStep;
1779 VLOG(jdwp) << "SS new line";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001780 }
Elliott Hughes86964332012-02-15 19:37:42 -08001781 } else if (gSingleStepControl.step_depth == JDWP::SD_OVER) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001782 // Step over method calls. We break when the line number is
1783 // different and the frame depth is <= the original frame
1784 // depth. (We can't just compare on the method, because we
1785 // might get unrolled past it by an exception, and it's tricky
1786 // to identify recursion.)
Elliott Hughes86964332012-02-15 19:37:42 -08001787
1788 // TODO: can we just use the value of 'sp'?
1789 int stack_depth = GetStackDepth(self);
1790
1791 if (stack_depth < gSingleStepControl.stack_depth) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001792 // popped up one or more frames, always trigger
Elliott Hughes86964332012-02-15 19:37:42 -08001793 event_flags |= kSingleStep;
1794 VLOG(jdwp) << "SS method pop";
1795 } else if (stack_depth == gSingleStepControl.stack_depth) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001796 // same depth, see if we moved
Elliott Hughes86964332012-02-15 19:37:42 -08001797 if (gSingleStepControl.step_size == JDWP::SS_MIN) {
1798 event_flags |= kSingleStep;
1799 VLOG(jdwp) << "SS new instruction";
Elliott Hughes2435a572012-02-17 16:07:41 -08001800 } else if (gSingleStepControl.dex_pcs.find(dex_pc) == gSingleStepControl.dex_pcs.end()) {
1801 event_flags |= kSingleStep;
1802 VLOG(jdwp) << "SS new line";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001803 }
1804 }
1805 } else {
Elliott Hughes86964332012-02-15 19:37:42 -08001806 CHECK_EQ(gSingleStepControl.step_depth, JDWP::SD_OUT);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001807 // Return from the current method. We break when the frame
1808 // depth pops up.
1809
1810 // This differs from the "method exit" break in that it stops
1811 // with the PC at the next instruction in the returned-to
1812 // function, rather than the end of the returning function.
Elliott Hughes86964332012-02-15 19:37:42 -08001813
1814 // TODO: can we just use the value of 'sp'?
1815 int stack_depth = GetStackDepth(self);
1816 if (stack_depth < gSingleStepControl.stack_depth) {
1817 event_flags |= kSingleStep;
1818 VLOG(jdwp) << "SS method pop";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001819 }
1820 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001821 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001822
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001823 // Check to see if this is a "return" instruction. JDWP says we should
1824 // send the event *after* the code has been executed, but it also says
1825 // the location we provide is the last instruction. Since the "return"
1826 // instruction has no interesting side effects, we should be safe.
1827 // (We can't just move this down to the returnFromMethod label because
1828 // we potentially need to combine it with other events.)
1829 // We're also not supposed to generate a method exit event if the method
1830 // terminates "with a thrown exception".
Elliott Hughes86964332012-02-15 19:37:42 -08001831 if (dex_pc >= 0) {
1832 const DexFile::CodeItem* code_item = MethodHelper(m).GetCodeItem();
1833 CHECK(code_item != NULL);
1834 CHECK_LT(dex_pc, static_cast<int32_t>(code_item->insns_size_in_code_units_));
1835 if (Instruction::At(&code_item->insns_[dex_pc])->IsReturn()) {
1836 event_flags |= kMethodExit;
1837 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001838 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001839
1840 // If there's something interesting going on, see if it matches one
1841 // of the debugger filters.
1842 if (event_flags != 0) {
Elliott Hughes86964332012-02-15 19:37:42 -08001843 Dbg::PostLocationEvent(m, dex_pc, GetThis(f), event_flags);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001844 }
1845}
1846
Elliott Hughes86964332012-02-15 19:37:42 -08001847void Dbg::WatchLocation(const JDWP::JdwpLocation* location) {
1848 MutexLock mu(gBreakpointsLock);
1849 Method* m = FromMethodId(location->methodId);
1850 gBreakpoints.push_back(Breakpoint(m, location->idx));
1851 VLOG(jdwp) << "Set breakpoint #" << (gBreakpoints.size() - 1) << ": " << gBreakpoints[gBreakpoints.size() - 1];
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001852}
1853
Elliott Hughes86964332012-02-15 19:37:42 -08001854void Dbg::UnwatchLocation(const JDWP::JdwpLocation* location) {
1855 MutexLock mu(gBreakpointsLock);
1856 Method* m = FromMethodId(location->methodId);
1857 for (size_t i = 0; i < gBreakpoints.size(); ++i) {
1858 if (gBreakpoints[i].method == m && gBreakpoints[i].pc == location->idx) {
1859 VLOG(jdwp) << "Removed breakpoint #" << i << ": " << gBreakpoints[i];
1860 gBreakpoints.erase(gBreakpoints.begin() + i);
1861 return;
1862 }
1863 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001864}
1865
Elliott Hughes2435a572012-02-17 16:07:41 -08001866JDWP::JdwpError Dbg::ConfigureStep(JDWP::ObjectId threadId, JDWP::JdwpStepSize step_size, JDWP::JdwpStepDepth step_depth) {
Elliott Hughes86964332012-02-15 19:37:42 -08001867 Thread* thread = DecodeThread(threadId);
Elliott Hughes2435a572012-02-17 16:07:41 -08001868 if (thread == NULL) {
1869 return JDWP::ERR_INVALID_THREAD;
1870 }
Elliott Hughes86964332012-02-15 19:37:42 -08001871
1872 // TODO: there's no theoretical reason why we couldn't support single-stepping
1873 // of multiple threads at once, but we never did so historically.
1874 if (gSingleStepControl.thread != NULL && thread != gSingleStepControl.thread) {
1875 LOG(WARNING) << "single-step already active for " << *gSingleStepControl.thread
1876 << "; switching to " << *thread;
1877 }
1878
Elliott Hughes2435a572012-02-17 16:07:41 -08001879 //
1880 // Work out what Method* we're in, the current line number, and how deep the stack currently
1881 // is for step-out.
1882 //
1883
Elliott Hughes86964332012-02-15 19:37:42 -08001884 struct SingleStepStackVisitor : public Thread::StackVisitor {
1885 SingleStepStackVisitor() {
1886 gSingleStepControl.method = NULL;
1887 gSingleStepControl.stack_depth = 0;
1888 }
Elliott Hughes2435a572012-02-17 16:07:41 -08001889 virtual void VisitFrame(const Frame& f, uintptr_t pc) {
Elliott Hughes86964332012-02-15 19:37:42 -08001890 // TODO: we'll need to skip callee-save frames too.
1891 if (f.HasMethod()) {
1892 ++gSingleStepControl.stack_depth;
1893 if (gSingleStepControl.method == NULL) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001894 const Method* m = f.GetMethod();
1895 const DexCache* dex_cache = m->GetDeclaringClass()->GetDexCache();
1896 gSingleStepControl.method = m;
1897 gSingleStepControl.line_number = -1;
1898 if (dex_cache != NULL) {
1899 const DexFile& dex_file = Runtime::Current()->GetClassLinker()->FindDexFile(dex_cache);
1900 gSingleStepControl.line_number = dex_file.GetLineNumFromPC(m, m->ToDexPC(pc));
1901 }
Elliott Hughes86964332012-02-15 19:37:42 -08001902 }
1903 }
1904 }
1905 };
1906 SingleStepStackVisitor visitor;
1907 thread->WalkStack(&visitor);
1908
Elliott Hughes2435a572012-02-17 16:07:41 -08001909 //
1910 // Find the dex_pc values that correspond to the current line, for line-based single-stepping.
1911 //
1912
1913 struct DebugCallbackContext {
1914 DebugCallbackContext() {
1915 last_pc_valid = false;
1916 last_pc = 0;
Elliott Hughes2435a572012-02-17 16:07:41 -08001917 }
1918
1919 static bool Callback(void* raw_context, uint32_t address, uint32_t line_number) {
1920 DebugCallbackContext* context = reinterpret_cast<DebugCallbackContext*>(raw_context);
1921 if (static_cast<int32_t>(line_number) == gSingleStepControl.line_number) {
1922 if (!context->last_pc_valid) {
1923 // Everything from this address until the next line change is ours.
1924 context->last_pc = address;
1925 context->last_pc_valid = true;
1926 }
1927 // Otherwise, if we're already in a valid range for this line,
1928 // just keep going (shouldn't really happen)...
1929 } else if (context->last_pc_valid) { // and the line number is new
1930 // Add everything from the last entry up until here to the set
1931 for (uint32_t dex_pc = context->last_pc; dex_pc < address; ++dex_pc) {
1932 gSingleStepControl.dex_pcs.insert(dex_pc);
1933 }
1934 context->last_pc_valid = false;
1935 }
1936 return false; // There may be multiple entries for any given line.
1937 }
1938
1939 ~DebugCallbackContext() {
1940 // If the line number was the last in the position table...
1941 if (last_pc_valid) {
1942 size_t end = MethodHelper(gSingleStepControl.method).GetCodeItem()->insns_size_in_code_units_;
1943 for (uint32_t dex_pc = last_pc; dex_pc < end; ++dex_pc) {
1944 gSingleStepControl.dex_pcs.insert(dex_pc);
1945 }
1946 }
1947 }
1948
1949 bool last_pc_valid;
1950 uint32_t last_pc;
1951 };
Elliott Hughes3e2e1a22012-02-21 11:33:41 -08001952 gSingleStepControl.dex_pcs.clear();
Elliott Hughes2435a572012-02-17 16:07:41 -08001953 const Method* m = gSingleStepControl.method;
Elliott Hughes3e2e1a22012-02-21 11:33:41 -08001954 if (m->IsNative()) {
1955 gSingleStepControl.line_number = -1;
1956 } else {
1957 DebugCallbackContext context;
1958 MethodHelper mh(m);
1959 mh.GetDexFile().DecodeDebugInfo(mh.GetCodeItem(), m->IsStatic(), m->GetDexMethodIndex(),
1960 DebugCallbackContext::Callback, NULL, &context);
1961 }
Elliott Hughes2435a572012-02-17 16:07:41 -08001962
1963 //
1964 // Everything else...
1965 //
1966
Elliott Hughes86964332012-02-15 19:37:42 -08001967 gSingleStepControl.thread = thread;
1968 gSingleStepControl.step_size = step_size;
1969 gSingleStepControl.step_depth = step_depth;
1970 gSingleStepControl.is_active = true;
1971
Elliott Hughes2435a572012-02-17 16:07:41 -08001972 if (VLOG_IS_ON(jdwp)) {
1973 VLOG(jdwp) << "Single-step thread: " << *gSingleStepControl.thread;
1974 VLOG(jdwp) << "Single-step step size: " << gSingleStepControl.step_size;
1975 VLOG(jdwp) << "Single-step step depth: " << gSingleStepControl.step_depth;
1976 VLOG(jdwp) << "Single-step current method: " << PrettyMethod(gSingleStepControl.method);
1977 VLOG(jdwp) << "Single-step current line: " << gSingleStepControl.line_number;
1978 VLOG(jdwp) << "Single-step current stack depth: " << gSingleStepControl.stack_depth;
1979 VLOG(jdwp) << "Single-step dex_pc values:";
1980 for (std::set<uint32_t>::iterator it = gSingleStepControl.dex_pcs.begin() ; it != gSingleStepControl.dex_pcs.end(); ++it) {
1981 VLOG(jdwp) << " " << *it;
1982 }
1983 }
1984
1985 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001986}
1987
1988void Dbg::UnconfigureStep(JDWP::ObjectId threadId) {
Elliott Hughes86964332012-02-15 19:37:42 -08001989 gSingleStepControl.is_active = false;
1990 gSingleStepControl.thread = NULL;
Elliott Hughes2435a572012-02-17 16:07:41 -08001991 gSingleStepControl.dex_pcs.clear();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001992}
1993
Elliott Hughes45651fd2012-02-21 15:48:20 -08001994static char JdwpTagToShortyChar(JDWP::JdwpTag tag) {
1995 switch (tag) {
1996 default:
1997 LOG(FATAL) << "unknown JDWP tag: " << PrintableChar(tag);
1998
1999 // Primitives.
2000 case JDWP::JT_BYTE: return 'B';
2001 case JDWP::JT_CHAR: return 'C';
2002 case JDWP::JT_FLOAT: return 'F';
2003 case JDWP::JT_DOUBLE: return 'D';
2004 case JDWP::JT_INT: return 'I';
2005 case JDWP::JT_LONG: return 'J';
2006 case JDWP::JT_SHORT: return 'S';
2007 case JDWP::JT_VOID: return 'V';
2008 case JDWP::JT_BOOLEAN: return 'Z';
2009
2010 // Reference types.
2011 case JDWP::JT_ARRAY:
2012 case JDWP::JT_OBJECT:
2013 case JDWP::JT_STRING:
2014 case JDWP::JT_THREAD:
2015 case JDWP::JT_THREAD_GROUP:
2016 case JDWP::JT_CLASS_LOADER:
2017 case JDWP::JT_CLASS_OBJECT:
2018 return 'L';
2019 }
2020}
2021
2022JDWP::JdwpError Dbg::InvokeMethod(JDWP::ObjectId threadId, JDWP::ObjectId objectId, JDWP::RefTypeId classId, JDWP::MethodId methodId, uint32_t arg_count, uint64_t* arg_values, JDWP::JdwpTag* arg_types, uint32_t options, JDWP::JdwpTag* pResultTag, uint64_t* pResultValue, JDWP::ObjectId* pExceptionId) {
Elliott Hughesd07986f2011-12-06 18:27:45 -08002023 ThreadList* thread_list = Runtime::Current()->GetThreadList();
2024
2025 Thread* targetThread = NULL;
2026 DebugInvokeReq* req = NULL;
2027 {
2028 ScopedThreadListLock thread_list_lock;
2029 targetThread = DecodeThread(threadId);
2030 if (targetThread == NULL) {
2031 LOG(ERROR) << "InvokeMethod request for non-existent thread " << threadId;
2032 return JDWP::ERR_INVALID_THREAD;
2033 }
2034 req = targetThread->GetInvokeReq();
2035 if (!req->ready) {
2036 LOG(ERROR) << "InvokeMethod request for thread not stopped by event: " << *targetThread;
2037 return JDWP::ERR_INVALID_THREAD;
2038 }
2039
2040 /*
2041 * We currently have a bug where we don't successfully resume the
2042 * target thread if the suspend count is too deep. We're expected to
2043 * require one "resume" for each "suspend", but when asked to execute
2044 * a method we have to resume fully and then re-suspend it back to the
2045 * same level. (The easiest way to cause this is to type "suspend"
2046 * multiple times in jdb.)
2047 *
2048 * It's unclear what this means when the event specifies "resume all"
2049 * and some threads are suspended more deeply than others. This is
2050 * a rare problem, so for now we just prevent it from hanging forever
2051 * by rejecting the method invocation request. Without this, we will
2052 * be stuck waiting on a suspended thread.
2053 */
2054 int suspend_count = targetThread->GetSuspendCount();
2055 if (suspend_count > 1) {
2056 LOG(ERROR) << *targetThread << " suspend count too deep for method invocation: " << suspend_count;
2057 return JDWP::ERR_THREAD_SUSPENDED; // Probably not expected here.
2058 }
2059
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002060 JDWP::JdwpError status;
Elliott Hughes45651fd2012-02-21 15:48:20 -08002061 Object* receiver = gRegistry->Get<Object*>(objectId);
2062 if (receiver == kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002063 return JDWP::ERR_INVALID_OBJECT;
2064 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002065
2066 Object* thread = gRegistry->Get<Object*>(threadId);
2067 if (thread == kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002068 return JDWP::ERR_INVALID_OBJECT;
2069 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002070 // TODO: check that 'thread' is actually a java.lang.Thread!
2071
2072 Class* c = DecodeClass(classId, status);
2073 if (c == NULL) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002074 return status;
2075 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002076
2077 Method* m = FromMethodId(methodId);
2078 if (m->IsStatic() != (receiver == NULL)) {
2079 return JDWP::ERR_INVALID_METHODID;
2080 }
2081 if (m->IsStatic()) {
2082 if (m->GetDeclaringClass() != c) {
2083 return JDWP::ERR_INVALID_METHODID;
2084 }
2085 } else {
2086 if (!m->GetDeclaringClass()->IsAssignableFrom(c)) {
2087 return JDWP::ERR_INVALID_METHODID;
2088 }
2089 }
2090
2091 // Check the argument list matches the method.
2092 MethodHelper mh(m);
2093 if (mh.GetShortyLength() - 1 != arg_count) {
2094 return JDWP::ERR_ILLEGAL_ARGUMENT;
2095 }
2096 const char* shorty = mh.GetShorty();
2097 for (size_t i = 0; i < arg_count; ++i) {
2098 if (shorty[i + 1] != JdwpTagToShortyChar(arg_types[i])) {
2099 return JDWP::ERR_ILLEGAL_ARGUMENT;
2100 }
2101 }
2102
2103 req->receiver_ = receiver;
2104 req->thread_ = thread;
2105 req->class_ = c;
2106 req->method_ = m;
2107 req->arg_count_ = arg_count;
2108 req->arg_values_ = arg_values;
Elliott Hughesd07986f2011-12-06 18:27:45 -08002109 req->options_ = options;
2110 req->invoke_needed_ = true;
2111 }
2112
2113 // The fact that we've released the thread list lock is a bit risky --- if the thread goes
2114 // away we're sitting high and dry -- but we must release this before the ResumeAllThreads
2115 // call, and it's unwise to hold it during WaitForSuspend.
2116
2117 {
2118 /*
2119 * We change our (JDWP thread) status, which should be THREAD_RUNNING,
2120 * so the VM can suspend for a GC if the invoke request causes us to
2121 * run out of memory. It's also a good idea to change it before locking
2122 * the invokeReq mutex, although that should never be held for long.
2123 */
2124 ScopedThreadStateChange tsc(Thread::Current(), Thread::kVmWait);
2125
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002126 VLOG(jdwp) << " Transferring control to event thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002127 {
2128 MutexLock mu(req->lock_);
2129
2130 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002131 VLOG(jdwp) << " Resuming all threads";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002132 thread_list->ResumeAll(true);
2133 } else {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002134 VLOG(jdwp) << " Resuming event thread only";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002135 thread_list->Resume(targetThread, true);
2136 }
2137
2138 // Wait for the request to finish executing.
2139 while (req->invoke_needed_) {
2140 req->cond_.Wait(req->lock_);
2141 }
2142 }
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002143 VLOG(jdwp) << " Control has returned from event thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002144
2145 /* wait for thread to re-suspend itself */
2146 targetThread->WaitUntilSuspended();
2147 //dvmWaitForSuspend(targetThread);
2148 }
2149
2150 /*
2151 * Suspend the threads. We waited for the target thread to suspend
2152 * itself, so all we need to do is suspend the others.
2153 *
2154 * The suspendAllThreads() call will double-suspend the event thread,
2155 * so we want to resume the target thread once to keep the books straight.
2156 */
2157 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002158 VLOG(jdwp) << " Suspending all threads";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002159 thread_list->SuspendAll(true);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002160 VLOG(jdwp) << " Resuming event thread to balance the count";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002161 thread_list->Resume(targetThread, true);
2162 }
2163
2164 // Copy the result.
2165 *pResultTag = req->result_tag;
2166 if (IsPrimitiveTag(req->result_tag)) {
2167 *pResultValue = req->result_value.j;
2168 } else {
2169 *pResultValue = gRegistry->Add(req->result_value.l);
2170 }
2171 *pExceptionId = req->exception;
2172 return req->error;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002173}
2174
2175void Dbg::ExecuteMethod(DebugInvokeReq* pReq) {
Elliott Hughesd07986f2011-12-06 18:27:45 -08002176 Thread* self = Thread::Current();
2177
2178 // We can be called while an exception is pending in the VM. We need
2179 // to preserve that across the method invocation.
2180 SirtRef<Throwable> old_exception(self->GetException());
2181 self->ClearException();
2182
2183 ScopedThreadStateChange tsc(self, Thread::kRunnable);
2184
2185 // Translate the method through the vtable, unless the debugger wants to suppress it.
2186 Method* m = pReq->method_;
2187 if ((pReq->options_ & JDWP::INVOKE_NONVIRTUAL) == 0 && pReq->receiver_ != NULL) {
Elliott Hughes45651fd2012-02-21 15:48:20 -08002188 Method* actual_method = pReq->class_->FindVirtualMethodForVirtualOrInterface(pReq->method_);
2189 if (actual_method != m) {
2190 VLOG(jdwp) << "ExecuteMethod translated " << PrettyMethod(m) << " to " << PrettyMethod(actual_method);
2191 m = actual_method;
2192 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08002193 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002194 VLOG(jdwp) << "ExecuteMethod " << PrettyMethod(m);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002195 CHECK(m != NULL);
2196
2197 CHECK_EQ(sizeof(jvalue), sizeof(uint64_t));
2198
Elliott Hughes45651fd2012-02-21 15:48:20 -08002199 LOG(INFO) << "self=" << self << " pReq->receiver_=" << pReq->receiver_ << " m=" << m << " #" << pReq->arg_count_ << " " << pReq->arg_values_;
2200 pReq->result_value = InvokeWithJValues(self, pReq->receiver_, m, reinterpret_cast<JValue*>(pReq->arg_values_));
Elliott Hughesd07986f2011-12-06 18:27:45 -08002201
2202 pReq->exception = gRegistry->Add(self->GetException());
2203 pReq->result_tag = BasicTagFromDescriptor(MethodHelper(m).GetShorty());
2204 if (pReq->exception != 0) {
2205 Object* exc = self->GetException();
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002206 VLOG(jdwp) << " JDWP invocation returning with exception=" << exc << " " << PrettyTypeOf(exc);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002207 self->ClearException();
2208 pReq->result_value.j = 0;
2209 } else if (pReq->result_tag == JDWP::JT_OBJECT) {
2210 /* if no exception thrown, examine object result more closely */
2211 JDWP::JdwpTag new_tag = TagFromObject(pReq->result_value.l);
2212 if (new_tag != pReq->result_tag) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002213 VLOG(jdwp) << " JDWP promoted result from " << pReq->result_tag << " to " << new_tag;
Elliott Hughesd07986f2011-12-06 18:27:45 -08002214 pReq->result_tag = new_tag;
2215 }
2216
2217 /*
2218 * Register the object. We don't actually need an ObjectId yet,
2219 * but we do need to be sure that the GC won't move or discard the
2220 * object when we switch out of RUNNING. The ObjectId conversion
2221 * will add the object to the "do not touch" list.
2222 *
2223 * We can't use the "tracked allocation" mechanism here because
2224 * the object is going to be handed off to a different thread.
2225 */
2226 gRegistry->Add(pReq->result_value.l);
2227 }
2228
2229 if (old_exception.get() != NULL) {
2230 self->SetException(old_exception.get());
2231 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002232}
2233
Elliott Hughesd07986f2011-12-06 18:27:45 -08002234/*
2235 * Register an object ID that might not have been registered previously.
2236 *
2237 * Normally this wouldn't happen -- the conversion to an ObjectId would
2238 * have added the object to the registry -- but in some cases (e.g.
2239 * throwing exceptions) we really want to do the registration late.
2240 */
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002241void Dbg::RegisterObjectId(JDWP::ObjectId id) {
Elliott Hughesd07986f2011-12-06 18:27:45 -08002242 gRegistry->Add(reinterpret_cast<Object*>(id));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002243}
2244
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002245/*
2246 * "buf" contains a full JDWP packet, possibly with multiple chunks. We
2247 * need to process each, accumulate the replies, and ship the whole thing
2248 * back.
2249 *
2250 * Returns "true" if we have a reply. The reply buffer is newly allocated,
2251 * and includes the chunk type/length, followed by the data.
2252 *
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08002253 * OLD-TODO: we currently assume that the request and reply include a single
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002254 * chunk. If this becomes inconvenient we will need to adapt.
2255 */
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002256bool Dbg::DdmHandlePacket(const uint8_t* buf, int dataLen, uint8_t** pReplyBuf, int* pReplyLen) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002257 CHECK_GE(dataLen, 0);
2258
2259 Thread* self = Thread::Current();
2260 JNIEnv* env = self->GetJniEnv();
2261
Elliott Hughes844f9a02012-01-24 20:19:58 -08002262 static jclass Chunk_class = CacheClass(env, "org/apache/harmony/dalvik/ddmc/Chunk");
2263 static jclass DdmServer_class = CacheClass(env, "org/apache/harmony/dalvik/ddmc/DdmServer");
2264 static jmethodID dispatch_mid = env->GetStaticMethodID(DdmServer_class, "dispatch", "(I[BII)Lorg/apache/harmony/dalvik/ddmc/Chunk;");
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002265 static jfieldID data_fid = env->GetFieldID(Chunk_class, "data", "[B");
2266 static jfieldID length_fid = env->GetFieldID(Chunk_class, "length", "I");
2267 static jfieldID offset_fid = env->GetFieldID(Chunk_class, "offset", "I");
2268 static jfieldID type_fid = env->GetFieldID(Chunk_class, "type", "I");
2269
2270 // Create a byte[] corresponding to 'buf'.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002271 ScopedLocalRef<jbyteArray> dataArray(env, env->NewByteArray(dataLen));
2272 if (dataArray.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002273 LOG(WARNING) << "byte[] allocation failed: " << dataLen;
2274 env->ExceptionClear();
2275 return false;
2276 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002277 env->SetByteArrayRegion(dataArray.get(), 0, dataLen, reinterpret_cast<const jbyte*>(buf));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002278
2279 const int kChunkHdrLen = 8;
2280
2281 // Run through and find all chunks. [Currently just find the first.]
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002282 ScopedByteArrayRO contents(env, dataArray.get());
Elliott Hughesf7c3b662011-10-27 12:04:56 -07002283 jint type = JDWP::Get4BE(reinterpret_cast<const uint8_t*>(&contents[0]));
2284 jint length = JDWP::Get4BE(reinterpret_cast<const uint8_t*>(&contents[4]));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002285 jint offset = kChunkHdrLen;
2286 if (offset + length > dataLen) {
2287 LOG(WARNING) << StringPrintf("bad chunk found (len=%u pktLen=%d)", length, dataLen);
2288 return false;
2289 }
2290
2291 // Call "private static Chunk dispatch(int type, byte[] data, int offset, int length)".
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002292 ScopedLocalRef<jobject> chunk(env, env->CallStaticObjectMethod(DdmServer_class, dispatch_mid, type, dataArray.get(), offset, length));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002293 if (env->ExceptionCheck()) {
2294 LOG(INFO) << StringPrintf("Exception thrown by dispatcher for 0x%08x", type);
2295 env->ExceptionDescribe();
2296 env->ExceptionClear();
2297 return false;
2298 }
2299
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002300 if (chunk.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002301 return false;
2302 }
2303
2304 /*
2305 * Pull the pieces out of the chunk. We copy the results into a
2306 * newly-allocated buffer that the caller can free. We don't want to
2307 * continue using the Chunk object because nothing has a reference to it.
2308 *
2309 * We could avoid this by returning type/data/offset/length and having
2310 * the caller be aware of the object lifetime issues, but that
2311 * integrates the JDWP code more tightly into the VM, and doesn't work
2312 * if we have responses for multiple chunks.
2313 *
2314 * So we're pretty much stuck with copying data around multiple times.
2315 */
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002316 ScopedLocalRef<jbyteArray> replyData(env, reinterpret_cast<jbyteArray>(env->GetObjectField(chunk.get(), data_fid)));
2317 length = env->GetIntField(chunk.get(), length_fid);
2318 offset = env->GetIntField(chunk.get(), offset_fid);
2319 type = env->GetIntField(chunk.get(), type_fid);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002320
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002321 VLOG(jdwp) << StringPrintf("DDM reply: type=0x%08x data=%p offset=%d length=%d", type, replyData.get(), offset, length);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002322 if (length == 0 || replyData.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002323 return false;
2324 }
2325
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002326 jsize replyLength = env->GetArrayLength(replyData.get());
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002327 if (offset + length > replyLength) {
2328 LOG(WARNING) << StringPrintf("chunk off=%d len=%d exceeds reply array len %d", offset, length, replyLength);
2329 return false;
2330 }
2331
2332 uint8_t* reply = new uint8_t[length + kChunkHdrLen];
2333 if (reply == NULL) {
2334 LOG(WARNING) << "malloc failed: " << (length + kChunkHdrLen);
2335 return false;
2336 }
Elliott Hughesf7c3b662011-10-27 12:04:56 -07002337 JDWP::Set4BE(reply + 0, type);
2338 JDWP::Set4BE(reply + 4, length);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002339 env->GetByteArrayRegion(replyData.get(), offset, length, reinterpret_cast<jbyte*>(reply + kChunkHdrLen));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002340
2341 *pReplyBuf = reply;
2342 *pReplyLen = length + kChunkHdrLen;
2343
Elliott Hughesba8eee12012-01-24 20:25:24 -08002344 VLOG(jdwp) << StringPrintf("dvmHandleDdm returning type=%.4s buf=%p len=%d", reinterpret_cast<char*>(reply), reply, length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002345 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002346}
2347
Elliott Hughesa2155262011-11-16 16:26:58 -08002348void Dbg::DdmBroadcast(bool connect) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002349 VLOG(jdwp) << "Broadcasting DDM " << (connect ? "connect" : "disconnect") << "...";
Elliott Hughes47fce012011-10-25 18:37:19 -07002350
2351 Thread* self = Thread::Current();
2352 if (self->GetState() != Thread::kRunnable) {
2353 LOG(ERROR) << "DDM broadcast in thread state " << self->GetState();
2354 /* try anyway? */
2355 }
2356
2357 JNIEnv* env = self->GetJniEnv();
Elliott Hughes844f9a02012-01-24 20:19:58 -08002358 static jclass DdmServer_class = CacheClass(env, "org/apache/harmony/dalvik/ddmc/DdmServer");
Elliott Hughes47fce012011-10-25 18:37:19 -07002359 static jmethodID broadcast_mid = env->GetStaticMethodID(DdmServer_class, "broadcast", "(I)V");
2360 jint event = connect ? 1 /*DdmServer.CONNECTED*/ : 2 /*DdmServer.DISCONNECTED*/;
2361 env->CallStaticVoidMethod(DdmServer_class, broadcast_mid, event);
2362 if (env->ExceptionCheck()) {
2363 LOG(ERROR) << "DdmServer.broadcast " << event << " failed";
2364 env->ExceptionDescribe();
2365 env->ExceptionClear();
2366 }
2367}
2368
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002369void Dbg::DdmConnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08002370 Dbg::DdmBroadcast(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002371}
2372
2373void Dbg::DdmDisconnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08002374 Dbg::DdmBroadcast(false);
Elliott Hughes47fce012011-10-25 18:37:19 -07002375 gDdmThreadNotification = false;
2376}
2377
2378/*
Elliott Hughes82188472011-11-07 18:11:48 -08002379 * Send a notification when a thread starts, stops, or changes its name.
Elliott Hughes47fce012011-10-25 18:37:19 -07002380 *
2381 * Because we broadcast the full set of threads when the notifications are
2382 * first enabled, it's possible for "thread" to be actively executing.
2383 */
Elliott Hughes82188472011-11-07 18:11:48 -08002384void Dbg::DdmSendThreadNotification(Thread* t, uint32_t type) {
Elliott Hughes47fce012011-10-25 18:37:19 -07002385 if (!gDdmThreadNotification) {
2386 return;
2387 }
2388
Elliott Hughes82188472011-11-07 18:11:48 -08002389 if (type == CHUNK_TYPE("THDE")) {
Elliott Hughes47fce012011-10-25 18:37:19 -07002390 uint8_t buf[4];
Elliott Hughesf7c3b662011-10-27 12:04:56 -07002391 JDWP::Set4BE(&buf[0], t->GetThinLockId());
Elliott Hughes47fce012011-10-25 18:37:19 -07002392 Dbg::DdmSendChunk(CHUNK_TYPE("THDE"), 4, buf);
Elliott Hughes82188472011-11-07 18:11:48 -08002393 } else {
2394 CHECK(type == CHUNK_TYPE("THCR") || type == CHUNK_TYPE("THNM")) << type;
Elliott Hughes899e7892012-01-24 14:57:32 -08002395 SirtRef<String> name(t->GetThreadName());
Elliott Hughes82188472011-11-07 18:11:48 -08002396 size_t char_count = (name.get() != NULL) ? name->GetLength() : 0;
2397 const jchar* chars = name->GetCharArray()->GetData();
2398
Elliott Hughes21f32d72011-11-09 17:44:13 -08002399 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08002400 JDWP::Append4BE(bytes, t->GetThinLockId());
2401 JDWP::AppendUtf16BE(bytes, chars, char_count);
Elliott Hughes21f32d72011-11-09 17:44:13 -08002402 CHECK_EQ(bytes.size(), char_count*2 + sizeof(uint32_t)*2);
2403 Dbg::DdmSendChunk(type, bytes);
Elliott Hughes47fce012011-10-25 18:37:19 -07002404 }
2405}
2406
Elliott Hughesa2155262011-11-16 16:26:58 -08002407static void DdmSendThreadStartCallback(Thread* t, void*) {
Elliott Hughes82188472011-11-07 18:11:48 -08002408 Dbg::DdmSendThreadNotification(t, CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07002409}
2410
2411void Dbg::DdmSetThreadNotification(bool enable) {
2412 // We lock the thread list to avoid sending duplicate events or missing
2413 // a thread change. We should be okay holding this lock while sending
2414 // the messages out. (We have to hold it while accessing a live thread.)
Elliott Hughesbbd9d832011-11-07 14:40:00 -08002415 ScopedThreadListLock thread_list_lock;
Elliott Hughes47fce012011-10-25 18:37:19 -07002416
2417 gDdmThreadNotification = enable;
2418 if (enable) {
Elliott Hughesbfe487b2011-10-26 15:48:55 -07002419 Runtime::Current()->GetThreadList()->ForEach(DdmSendThreadStartCallback, NULL);
Elliott Hughes47fce012011-10-25 18:37:19 -07002420 }
2421}
2422
Elliott Hughesa2155262011-11-16 16:26:58 -08002423void Dbg::PostThreadStartOrStop(Thread* t, uint32_t type) {
Elliott Hughes47fce012011-10-25 18:37:19 -07002424 if (gDebuggerActive) {
2425 JDWP::ObjectId id = gRegistry->Add(t->GetPeer());
Elliott Hughes82188472011-11-07 18:11:48 -08002426 gJdwpState->PostThreadChange(id, type == CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07002427 }
Elliott Hughes82188472011-11-07 18:11:48 -08002428 Dbg::DdmSendThreadNotification(t, type);
Elliott Hughes47fce012011-10-25 18:37:19 -07002429}
2430
2431void Dbg::PostThreadStart(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08002432 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07002433}
2434
2435void Dbg::PostThreadDeath(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08002436 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THDE"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002437}
2438
Elliott Hughes82188472011-11-07 18:11:48 -08002439void Dbg::DdmSendChunk(uint32_t type, size_t byte_count, const uint8_t* buf) {
Elliott Hughes3bb81562011-10-21 18:52:59 -07002440 CHECK(buf != NULL);
2441 iovec vec[1];
2442 vec[0].iov_base = reinterpret_cast<void*>(const_cast<uint8_t*>(buf));
2443 vec[0].iov_len = byte_count;
2444 Dbg::DdmSendChunkV(type, vec, 1);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002445}
2446
Elliott Hughes21f32d72011-11-09 17:44:13 -08002447void Dbg::DdmSendChunk(uint32_t type, const std::vector<uint8_t>& bytes) {
2448 DdmSendChunk(type, bytes.size(), &bytes[0]);
2449}
2450
Elliott Hughescccd84f2011-12-05 16:51:54 -08002451void Dbg::DdmSendChunkV(uint32_t type, const struct iovec* iov, int iov_count) {
Elliott Hughes3bb81562011-10-21 18:52:59 -07002452 if (gJdwpState == NULL) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002453 VLOG(jdwp) << "Debugger thread not active, ignoring DDM send: " << type;
Elliott Hughes3bb81562011-10-21 18:52:59 -07002454 } else {
Elliott Hughescccd84f2011-12-05 16:51:54 -08002455 gJdwpState->DdmSendChunkV(type, iov, iov_count);
Elliott Hughes3bb81562011-10-21 18:52:59 -07002456 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002457}
2458
Elliott Hughes767a1472011-10-26 18:49:02 -07002459int Dbg::DdmHandleHpifChunk(HpifWhen when) {
2460 if (when == HPIF_WHEN_NOW) {
Elliott Hughes7162ad92011-10-27 14:08:42 -07002461 DdmSendHeapInfo(when);
Elliott Hughes767a1472011-10-26 18:49:02 -07002462 return true;
2463 }
2464
2465 if (when != HPIF_WHEN_NEVER && when != HPIF_WHEN_NEXT_GC && when != HPIF_WHEN_EVERY_GC) {
2466 LOG(ERROR) << "invalid HpifWhen value: " << static_cast<int>(when);
2467 return false;
2468 }
2469
2470 gDdmHpifWhen = when;
2471 return true;
2472}
2473
2474bool Dbg::DdmHandleHpsgNhsgChunk(Dbg::HpsgWhen when, Dbg::HpsgWhat what, bool native) {
2475 if (when != HPSG_WHEN_NEVER && when != HPSG_WHEN_EVERY_GC) {
2476 LOG(ERROR) << "invalid HpsgWhen value: " << static_cast<int>(when);
2477 return false;
2478 }
2479
2480 if (what != HPSG_WHAT_MERGED_OBJECTS && what != HPSG_WHAT_DISTINCT_OBJECTS) {
2481 LOG(ERROR) << "invalid HpsgWhat value: " << static_cast<int>(what);
2482 return false;
2483 }
2484
2485 if (native) {
2486 gDdmNhsgWhen = when;
2487 gDdmNhsgWhat = what;
2488 } else {
2489 gDdmHpsgWhen = when;
2490 gDdmHpsgWhat = what;
2491 }
2492 return true;
2493}
2494
Elliott Hughes7162ad92011-10-27 14:08:42 -07002495void Dbg::DdmSendHeapInfo(HpifWhen reason) {
2496 // If there's a one-shot 'when', reset it.
2497 if (reason == gDdmHpifWhen) {
2498 if (gDdmHpifWhen == HPIF_WHEN_NEXT_GC) {
2499 gDdmHpifWhen = HPIF_WHEN_NEVER;
2500 }
2501 }
2502
2503 /*
2504 * Chunk HPIF (client --> server)
2505 *
2506 * Heap Info. General information about the heap,
2507 * suitable for a summary display.
2508 *
2509 * [u4]: number of heaps
2510 *
2511 * For each heap:
2512 * [u4]: heap ID
2513 * [u8]: timestamp in ms since Unix epoch
2514 * [u1]: capture reason (same as 'when' value from server)
2515 * [u4]: max heap size in bytes (-Xmx)
2516 * [u4]: current heap size in bytes
2517 * [u4]: current number of bytes allocated
2518 * [u4]: current number of objects allocated
2519 */
2520 uint8_t heap_count = 1;
Elliott Hughes21f32d72011-11-09 17:44:13 -08002521 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08002522 JDWP::Append4BE(bytes, heap_count);
2523 JDWP::Append4BE(bytes, 1); // Heap id (bogus; we only have one heap).
2524 JDWP::Append8BE(bytes, MilliTime());
2525 JDWP::Append1BE(bytes, reason);
2526 JDWP::Append4BE(bytes, Heap::GetMaxMemory()); // Max allowed heap size in bytes.
2527 JDWP::Append4BE(bytes, Heap::GetTotalMemory()); // Current heap size in bytes.
2528 JDWP::Append4BE(bytes, Heap::GetBytesAllocated());
2529 JDWP::Append4BE(bytes, Heap::GetObjectsAllocated());
Elliott Hughes21f32d72011-11-09 17:44:13 -08002530 CHECK_EQ(bytes.size(), 4U + (heap_count * (4 + 8 + 1 + 4 + 4 + 4 + 4)));
2531 Dbg::DdmSendChunk(CHUNK_TYPE("HPIF"), bytes);
Elliott Hughes767a1472011-10-26 18:49:02 -07002532}
2533
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002534enum HpsgSolidity {
2535 SOLIDITY_FREE = 0,
2536 SOLIDITY_HARD = 1,
2537 SOLIDITY_SOFT = 2,
2538 SOLIDITY_WEAK = 3,
2539 SOLIDITY_PHANTOM = 4,
2540 SOLIDITY_FINALIZABLE = 5,
2541 SOLIDITY_SWEEP = 6,
2542};
2543
2544enum HpsgKind {
2545 KIND_OBJECT = 0,
2546 KIND_CLASS_OBJECT = 1,
2547 KIND_ARRAY_1 = 2,
2548 KIND_ARRAY_2 = 3,
2549 KIND_ARRAY_4 = 4,
2550 KIND_ARRAY_8 = 5,
2551 KIND_UNKNOWN = 6,
2552 KIND_NATIVE = 7,
2553};
2554
2555#define HPSG_PARTIAL (1<<7)
2556#define HPSG_STATE(solidity, kind) ((uint8_t)((((kind) & 0x7) << 3) | ((solidity) & 0x7)))
2557
Ian Rogers30fab402012-01-23 15:43:46 -08002558class HeapChunkContext {
2559 public:
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002560 // Maximum chunk size. Obtain this from the formula:
2561 // (((maximum_heap_size / ALLOCATION_UNIT_SIZE) + 255) / 256) * 2
2562 HeapChunkContext(bool merge, bool native)
Ian Rogers30fab402012-01-23 15:43:46 -08002563 : buf_(16384 - 16),
2564 type_(0),
2565 merge_(merge) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002566 Reset();
2567 if (native) {
Ian Rogers30fab402012-01-23 15:43:46 -08002568 type_ = CHUNK_TYPE("NHSG");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002569 } else {
Ian Rogers30fab402012-01-23 15:43:46 -08002570 type_ = merge ? CHUNK_TYPE("HPSG") : CHUNK_TYPE("HPSO");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002571 }
2572 }
2573
2574 ~HeapChunkContext() {
Ian Rogers30fab402012-01-23 15:43:46 -08002575 if (p_ > &buf_[0]) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002576 Flush();
2577 }
2578 }
2579
2580 void EnsureHeader(const void* chunk_ptr) {
Ian Rogers30fab402012-01-23 15:43:46 -08002581 if (!needHeader_) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002582 return;
2583 }
2584
2585 // Start a new HPSx chunk.
Ian Rogers30fab402012-01-23 15:43:46 -08002586 JDWP::Write4BE(&p_, 1); // Heap id (bogus; we only have one heap).
2587 JDWP::Write1BE(&p_, 8); // Size of allocation unit, in bytes.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002588
Ian Rogers30fab402012-01-23 15:43:46 -08002589 JDWP::Write4BE(&p_, reinterpret_cast<uintptr_t>(chunk_ptr)); // virtual address of segment start.
2590 JDWP::Write4BE(&p_, 0); // offset of this piece (relative to the virtual address).
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002591 // [u4]: length of piece, in allocation units
2592 // We won't know this until we're done, so save the offset and stuff in a dummy value.
Ian Rogers30fab402012-01-23 15:43:46 -08002593 pieceLenField_ = p_;
2594 JDWP::Write4BE(&p_, 0x55555555);
2595 needHeader_ = false;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002596 }
2597
2598 void Flush() {
2599 // Patch the "length of piece" field.
Ian Rogers30fab402012-01-23 15:43:46 -08002600 CHECK_LE(&buf_[0], pieceLenField_);
2601 CHECK_LE(pieceLenField_, p_);
2602 JDWP::Set4BE(pieceLenField_, totalAllocationUnits_);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002603
Ian Rogers30fab402012-01-23 15:43:46 -08002604 Dbg::DdmSendChunk(type_, p_ - &buf_[0], &buf_[0]);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002605 Reset();
2606 }
2607
Ian Rogers30fab402012-01-23 15:43:46 -08002608 static void HeapChunkCallback(void* start, void* end, size_t used_bytes, void* arg) {
2609 reinterpret_cast<HeapChunkContext*>(arg)->HeapChunkCallback(start, end, used_bytes);
Elliott Hughesa2155262011-11-16 16:26:58 -08002610 }
2611
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002612 private:
Elliott Hughesa2155262011-11-16 16:26:58 -08002613 enum { ALLOCATION_UNIT_SIZE = 8 };
2614
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002615 void Reset() {
Ian Rogers30fab402012-01-23 15:43:46 -08002616 p_ = &buf_[0];
2617 totalAllocationUnits_ = 0;
2618 needHeader_ = true;
2619 pieceLenField_ = NULL;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002620 }
2621
Ian Rogers30fab402012-01-23 15:43:46 -08002622 void HeapChunkCallback(void* start, void* end, size_t used_bytes) {
2623 // Note: heap call backs cannot manipulate the heap upon which they are crawling, care is taken
2624 // in the following code not to allocate memory, by ensuring buf_ is of the correct size
2625
2626 const void* user_ptr = used_bytes > 0 ? const_cast<void*>(start) : NULL;
2627 // from malloc.c mem2chunk(mem)
2628 const void* chunk_ptr =
2629 reinterpret_cast<const void*>(reinterpret_cast<const char*>(const_cast<void*>(start)) -
2630 (2 * sizeof(size_t)));
2631 // from malloc.c chunksize
2632 size_t chunk_len = (*reinterpret_cast<size_t* const*>(chunk_ptr))[1] & ~7;
2633
2634
2635 //size_t chunk_len = malloc_usable_size(user_ptr);
Elliott Hughesa2155262011-11-16 16:26:58 -08002636 CHECK_EQ((chunk_len & (ALLOCATION_UNIT_SIZE-1)), 0U);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002637
Elliott Hughesa2155262011-11-16 16:26:58 -08002638 /* Make sure there's enough room left in the buffer.
2639 * We need to use two bytes for every fractional 256
2640 * allocation units used by the chunk.
2641 */
2642 {
2643 size_t needed = (((chunk_len/ALLOCATION_UNIT_SIZE + 255) / 256) * 2);
Ian Rogers30fab402012-01-23 15:43:46 -08002644 size_t bytesLeft = buf_.size() - (size_t)(p_ - &buf_[0]);
Elliott Hughesa2155262011-11-16 16:26:58 -08002645 if (bytesLeft < needed) {
2646 Flush();
2647 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002648
Ian Rogers30fab402012-01-23 15:43:46 -08002649 bytesLeft = buf_.size() - (size_t)(p_ - &buf_[0]);
Elliott Hughesa2155262011-11-16 16:26:58 -08002650 if (bytesLeft < needed) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08002651 LOG(WARNING) << "Chunk is too big to transmit (chunk_len=" << chunk_len << ", " << needed << " bytes)";
Elliott Hughesa2155262011-11-16 16:26:58 -08002652 return;
2653 }
2654 }
2655
2656 // OLD-TODO: notice when there's a gap and start a new heap, or at least a new range.
2657 EnsureHeader(chunk_ptr);
2658
2659 // Determine the type of this chunk.
2660 // OLD-TODO: if context.merge, see if this chunk is different from the last chunk.
2661 // If it's the same, we should combine them.
Ian Rogers30fab402012-01-23 15:43:46 -08002662 uint8_t state = ExamineObject(reinterpret_cast<const Object*>(user_ptr), (type_ == CHUNK_TYPE("NHSG")));
Elliott Hughesa2155262011-11-16 16:26:58 -08002663
2664 // Write out the chunk description.
2665 chunk_len /= ALLOCATION_UNIT_SIZE; // convert to allocation units
Ian Rogers30fab402012-01-23 15:43:46 -08002666 totalAllocationUnits_ += chunk_len;
Elliott Hughesa2155262011-11-16 16:26:58 -08002667 while (chunk_len > 256) {
Ian Rogers30fab402012-01-23 15:43:46 -08002668 *p_++ = state | HPSG_PARTIAL;
2669 *p_++ = 255; // length - 1
Elliott Hughesa2155262011-11-16 16:26:58 -08002670 chunk_len -= 256;
2671 }
Ian Rogers30fab402012-01-23 15:43:46 -08002672 *p_++ = state;
2673 *p_++ = chunk_len - 1;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002674 }
2675
Elliott Hughesa2155262011-11-16 16:26:58 -08002676 uint8_t ExamineObject(const Object* o, bool is_native_heap) {
2677 if (o == NULL) {
2678 return HPSG_STATE(SOLIDITY_FREE, 0);
2679 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002680
Elliott Hughesa2155262011-11-16 16:26:58 -08002681 // It's an allocated chunk. Figure out what it is.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002682
Elliott Hughesa2155262011-11-16 16:26:58 -08002683 // If we're looking at the native heap, we'll just return
2684 // (SOLIDITY_HARD, KIND_NATIVE) for all allocated chunks.
2685 if (is_native_heap || !Heap::IsLiveObjectLocked(o)) {
2686 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
2687 }
2688
2689 Class* c = o->GetClass();
2690 if (c == NULL) {
2691 // The object was probably just created but hasn't been initialized yet.
2692 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
2693 }
2694
2695 if (!Heap::IsHeapAddress(c)) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08002696 LOG(WARNING) << "Invalid class for managed heap object: " << o << " " << c;
Elliott Hughesa2155262011-11-16 16:26:58 -08002697 return HPSG_STATE(SOLIDITY_HARD, KIND_UNKNOWN);
2698 }
2699
2700 if (c->IsClassClass()) {
2701 return HPSG_STATE(SOLIDITY_HARD, KIND_CLASS_OBJECT);
2702 }
2703
2704 if (c->IsArrayClass()) {
2705 if (o->IsObjectArray()) {
2706 return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
2707 }
2708 switch (c->GetComponentSize()) {
2709 case 1: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_1);
2710 case 2: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_2);
2711 case 4: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
2712 case 8: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_8);
2713 }
2714 }
2715
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002716 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
2717 }
2718
Ian Rogers30fab402012-01-23 15:43:46 -08002719 std::vector<uint8_t> buf_;
2720 uint8_t* p_;
2721 uint8_t* pieceLenField_;
2722 size_t totalAllocationUnits_;
2723 uint32_t type_;
2724 bool merge_;
2725 bool needHeader_;
2726
Elliott Hughesa2155262011-11-16 16:26:58 -08002727 DISALLOW_COPY_AND_ASSIGN(HeapChunkContext);
2728};
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002729
2730void Dbg::DdmSendHeapSegments(bool native) {
2731 Dbg::HpsgWhen when;
2732 Dbg::HpsgWhat what;
2733 if (!native) {
2734 when = gDdmHpsgWhen;
2735 what = gDdmHpsgWhat;
2736 } else {
2737 when = gDdmNhsgWhen;
2738 what = gDdmNhsgWhat;
2739 }
2740 if (when == HPSG_WHEN_NEVER) {
2741 return;
2742 }
2743
2744 // Figure out what kind of chunks we'll be sending.
2745 CHECK(what == HPSG_WHAT_MERGED_OBJECTS || what == HPSG_WHAT_DISTINCT_OBJECTS) << static_cast<int>(what);
2746
2747 // First, send a heap start chunk.
2748 uint8_t heap_id[4];
2749 JDWP::Set4BE(&heap_id[0], 1); // Heap id (bogus; we only have one heap).
2750 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHST") : CHUNK_TYPE("HPST"), sizeof(heap_id), heap_id);
2751
2752 // Send a series of heap segment chunks.
Elliott Hughesa2155262011-11-16 16:26:58 -08002753 HeapChunkContext context((what == HPSG_WHAT_MERGED_OBJECTS), native);
2754 if (native) {
Ian Rogers30fab402012-01-23 15:43:46 -08002755 // TODO: enable when bionic has moved to dlmalloc 2.8.5
2756 // dlmalloc_inspect_all(HeapChunkContext::HeapChunkCallback, &context);
2757 UNIMPLEMENTED(WARNING) << "Native heap send heap segments";
Elliott Hughesa2155262011-11-16 16:26:58 -08002758 } else {
Ian Rogers30fab402012-01-23 15:43:46 -08002759 Heap::GetAllocSpace()->Walk(HeapChunkContext::HeapChunkCallback, &context);
Elliott Hughesa2155262011-11-16 16:26:58 -08002760 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002761
2762 // Finally, send a heap end chunk.
2763 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHEN") : CHUNK_TYPE("HPEN"), sizeof(heap_id), heap_id);
Elliott Hughes767a1472011-10-26 18:49:02 -07002764}
2765
Elliott Hughes545a0642011-11-08 19:10:03 -08002766void Dbg::SetAllocTrackingEnabled(bool enabled) {
2767 MutexLock mu(gAllocTrackerLock);
2768 if (enabled) {
2769 if (recent_allocation_records_ == NULL) {
2770 LOG(INFO) << "Enabling alloc tracker (" << kNumAllocRecords << " entries, "
2771 << kMaxAllocRecordStackDepth << " frames --> "
2772 << (sizeof(AllocRecord) * kNumAllocRecords) << " bytes)";
2773 gAllocRecordHead = gAllocRecordCount = 0;
2774 recent_allocation_records_ = new AllocRecord[kNumAllocRecords];
2775 CHECK(recent_allocation_records_ != NULL);
2776 }
2777 } else {
2778 delete[] recent_allocation_records_;
2779 recent_allocation_records_ = NULL;
2780 }
2781}
2782
2783struct AllocRecordStackVisitor : public Thread::StackVisitor {
Elliott Hughesba8eee12012-01-24 20:25:24 -08002784 explicit AllocRecordStackVisitor(AllocRecord* record) : record(record), depth(0) {
Elliott Hughes545a0642011-11-08 19:10:03 -08002785 }
2786
2787 virtual void VisitFrame(const Frame& f, uintptr_t pc) {
2788 if (depth >= kMaxAllocRecordStackDepth) {
2789 return;
2790 }
2791 Method* m = f.GetMethod();
2792 if (m == NULL || m->IsCalleeSaveMethod()) {
2793 return;
2794 }
2795 record->stack[depth].method = m;
2796 record->stack[depth].raw_pc = pc;
2797 ++depth;
2798 }
2799
2800 ~AllocRecordStackVisitor() {
2801 // Clear out any unused stack trace elements.
2802 for (; depth < kMaxAllocRecordStackDepth; ++depth) {
2803 record->stack[depth].method = NULL;
2804 record->stack[depth].raw_pc = 0;
2805 }
2806 }
2807
2808 AllocRecord* record;
2809 size_t depth;
2810};
2811
2812void Dbg::RecordAllocation(Class* type, size_t byte_count) {
2813 Thread* self = Thread::Current();
2814 CHECK(self != NULL);
2815
2816 MutexLock mu(gAllocTrackerLock);
2817 if (recent_allocation_records_ == NULL) {
2818 return;
2819 }
2820
2821 // Advance and clip.
2822 if (++gAllocRecordHead == kNumAllocRecords) {
2823 gAllocRecordHead = 0;
2824 }
2825
2826 // Fill in the basics.
2827 AllocRecord* record = &recent_allocation_records_[gAllocRecordHead];
2828 record->type = type;
2829 record->byte_count = byte_count;
2830 record->thin_lock_id = self->GetThinLockId();
2831
2832 // Fill in the stack trace.
2833 AllocRecordStackVisitor visitor(record);
2834 self->WalkStack(&visitor);
2835
2836 if (gAllocRecordCount < kNumAllocRecords) {
2837 ++gAllocRecordCount;
2838 }
2839}
2840
2841/*
2842 * Return the index of the head element.
2843 *
2844 * We point at the most-recently-written record, so if allocRecordCount is 1
2845 * we want to use the current element. Take "head+1" and subtract count
2846 * from it.
2847 *
2848 * We need to handle underflow in our circular buffer, so we add
2849 * kNumAllocRecords and then mask it back down.
2850 */
2851inline static int headIndex() {
2852 return (gAllocRecordHead+1 + kNumAllocRecords - gAllocRecordCount) & (kNumAllocRecords-1);
2853}
2854
2855void Dbg::DumpRecentAllocations() {
2856 MutexLock mu(gAllocTrackerLock);
2857 if (recent_allocation_records_ == NULL) {
2858 LOG(INFO) << "Not recording tracked allocations";
2859 return;
2860 }
2861
2862 // "i" is the head of the list. We want to start at the end of the
2863 // list and move forward to the tail.
2864 size_t i = headIndex();
2865 size_t count = gAllocRecordCount;
2866
2867 LOG(INFO) << "Tracked allocations, (head=" << gAllocRecordHead << " count=" << count << ")";
2868 while (count--) {
2869 AllocRecord* record = &recent_allocation_records_[i];
2870
Elliott Hughesaa6e1cd2012-01-18 19:26:06 -08002871 LOG(INFO) << StringPrintf(" T=%-2d %6zd ", record->thin_lock_id, record->byte_count)
Elliott Hughes545a0642011-11-08 19:10:03 -08002872 << PrettyClass(record->type);
2873
2874 for (size_t stack_frame = 0; stack_frame < kMaxAllocRecordStackDepth; ++stack_frame) {
2875 const Method* m = record->stack[stack_frame].method;
2876 if (m == NULL) {
2877 break;
2878 }
2879 LOG(INFO) << " " << PrettyMethod(m) << " line " << record->stack[stack_frame].LineNumber();
2880 }
2881
2882 // pause periodically to help logcat catch up
2883 if ((count % 5) == 0) {
2884 usleep(40000);
2885 }
2886
2887 i = (i + 1) & (kNumAllocRecords-1);
2888 }
2889}
2890
2891class StringTable {
2892 public:
2893 StringTable() {
2894 }
2895
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002896 void Add(const char* s) {
Elliott Hughes545a0642011-11-08 19:10:03 -08002897 table_.insert(s);
2898 }
2899
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002900 size_t IndexOf(const char* s) {
Elliott Hughes545a0642011-11-08 19:10:03 -08002901 return std::distance(table_.begin(), table_.find(s));
2902 }
2903
2904 size_t Size() {
2905 return table_.size();
2906 }
2907
2908 void WriteTo(std::vector<uint8_t>& bytes) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002909 typedef std::set<const char*>::const_iterator It; // TODO: C++0x auto
Elliott Hughes545a0642011-11-08 19:10:03 -08002910 for (It it = table_.begin(); it != table_.end(); ++it) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002911 const char* s = *it;
2912 size_t s_len = CountModifiedUtf8Chars(s);
2913 UniquePtr<uint16_t> s_utf16(new uint16_t[s_len]);
2914 ConvertModifiedUtf8ToUtf16(s_utf16.get(), s);
2915 JDWP::AppendUtf16BE(bytes, s_utf16.get(), s_len);
Elliott Hughes545a0642011-11-08 19:10:03 -08002916 }
2917 }
2918
2919 private:
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002920 std::set<const char*> table_;
Elliott Hughes545a0642011-11-08 19:10:03 -08002921 DISALLOW_COPY_AND_ASSIGN(StringTable);
2922};
2923
2924/*
2925 * The data we send to DDMS contains everything we have recorded.
2926 *
2927 * Message header (all values big-endian):
2928 * (1b) message header len (to allow future expansion); includes itself
2929 * (1b) entry header len
2930 * (1b) stack frame len
2931 * (2b) number of entries
2932 * (4b) offset to string table from start of message
2933 * (2b) number of class name strings
2934 * (2b) number of method name strings
2935 * (2b) number of source file name strings
2936 * For each entry:
2937 * (4b) total allocation size
2938 * (2b) threadId
2939 * (2b) allocated object's class name index
2940 * (1b) stack depth
2941 * For each stack frame:
2942 * (2b) method's class name
2943 * (2b) method name
2944 * (2b) method source file
2945 * (2b) line number, clipped to 32767; -2 if native; -1 if no source
2946 * (xb) class name strings
2947 * (xb) method name strings
2948 * (xb) source file strings
2949 *
2950 * As with other DDM traffic, strings are sent as a 4-byte length
2951 * followed by UTF-16 data.
2952 *
2953 * We send up 16-bit unsigned indexes into string tables. In theory there
2954 * can be (kMaxAllocRecordStackDepth * kNumAllocRecords) unique strings in
2955 * each table, but in practice there should be far fewer.
2956 *
2957 * The chief reason for using a string table here is to keep the size of
2958 * the DDMS message to a minimum. This is partly to make the protocol
2959 * efficient, but also because we have to form the whole thing up all at
2960 * once in a memory buffer.
2961 *
2962 * We use separate string tables for class names, method names, and source
2963 * files to keep the indexes small. There will generally be no overlap
2964 * between the contents of these tables.
2965 */
2966jbyteArray Dbg::GetRecentAllocations() {
2967 if (false) {
2968 DumpRecentAllocations();
2969 }
2970
2971 MutexLock mu(gAllocTrackerLock);
2972
2973 /*
2974 * Part 1: generate string tables.
2975 */
2976 StringTable class_names;
2977 StringTable method_names;
2978 StringTable filenames;
2979
2980 int count = gAllocRecordCount;
2981 int idx = headIndex();
2982 while (count--) {
2983 AllocRecord* record = &recent_allocation_records_[idx];
2984
Elliott Hughes91250e02011-12-13 22:30:35 -08002985 class_names.Add(ClassHelper(record->type).GetDescriptor());
Elliott Hughes545a0642011-11-08 19:10:03 -08002986
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002987 MethodHelper mh;
Elliott Hughes545a0642011-11-08 19:10:03 -08002988 for (size_t i = 0; i < kMaxAllocRecordStackDepth; i++) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002989 Method* m = record->stack[i].method;
2990 mh.ChangeMethod(m);
Elliott Hughes545a0642011-11-08 19:10:03 -08002991 if (m != NULL) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002992 class_names.Add(mh.GetDeclaringClassDescriptor());
2993 method_names.Add(mh.GetName());
2994 filenames.Add(mh.GetDeclaringClassSourceFile());
Elliott Hughes545a0642011-11-08 19:10:03 -08002995 }
2996 }
2997
2998 idx = (idx + 1) & (kNumAllocRecords-1);
2999 }
3000
3001 LOG(INFO) << "allocation records: " << gAllocRecordCount;
3002
3003 /*
3004 * Part 2: allocate a buffer and generate the output.
3005 */
3006 std::vector<uint8_t> bytes;
3007
3008 // (1b) message header len (to allow future expansion); includes itself
3009 // (1b) entry header len
3010 // (1b) stack frame len
3011 const int kMessageHeaderLen = 15;
3012 const int kEntryHeaderLen = 9;
3013 const int kStackFrameLen = 8;
3014 JDWP::Append1BE(bytes, kMessageHeaderLen);
3015 JDWP::Append1BE(bytes, kEntryHeaderLen);
3016 JDWP::Append1BE(bytes, kStackFrameLen);
3017
3018 // (2b) number of entries
3019 // (4b) offset to string table from start of message
3020 // (2b) number of class name strings
3021 // (2b) number of method name strings
3022 // (2b) number of source file name strings
3023 JDWP::Append2BE(bytes, gAllocRecordCount);
3024 size_t string_table_offset = bytes.size();
3025 JDWP::Append4BE(bytes, 0); // We'll patch this later...
3026 JDWP::Append2BE(bytes, class_names.Size());
3027 JDWP::Append2BE(bytes, method_names.Size());
3028 JDWP::Append2BE(bytes, filenames.Size());
3029
3030 count = gAllocRecordCount;
3031 idx = headIndex();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003032 ClassHelper kh;
Elliott Hughes545a0642011-11-08 19:10:03 -08003033 while (count--) {
3034 // For each entry:
3035 // (4b) total allocation size
3036 // (2b) thread id
3037 // (2b) allocated object's class name index
3038 // (1b) stack depth
3039 AllocRecord* record = &recent_allocation_records_[idx];
3040 size_t stack_depth = record->GetDepth();
3041 JDWP::Append4BE(bytes, record->byte_count);
3042 JDWP::Append2BE(bytes, record->thin_lock_id);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003043 kh.ChangeClass(record->type);
Elliott Hughes91250e02011-12-13 22:30:35 -08003044 JDWP::Append2BE(bytes, class_names.IndexOf(kh.GetDescriptor()));
Elliott Hughes545a0642011-11-08 19:10:03 -08003045 JDWP::Append1BE(bytes, stack_depth);
3046
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003047 MethodHelper mh;
Elliott Hughes545a0642011-11-08 19:10:03 -08003048 for (size_t stack_frame = 0; stack_frame < stack_depth; ++stack_frame) {
3049 // For each stack frame:
3050 // (2b) method's class name
3051 // (2b) method name
3052 // (2b) method source file
3053 // (2b) line number, clipped to 32767; -2 if native; -1 if no source
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003054 mh.ChangeMethod(record->stack[stack_frame].method);
3055 JDWP::Append2BE(bytes, class_names.IndexOf(mh.GetDeclaringClassDescriptor()));
3056 JDWP::Append2BE(bytes, method_names.IndexOf(mh.GetName()));
3057 JDWP::Append2BE(bytes, filenames.IndexOf(mh.GetDeclaringClassSourceFile()));
Elliott Hughes545a0642011-11-08 19:10:03 -08003058 JDWP::Append2BE(bytes, record->stack[stack_frame].LineNumber());
3059 }
3060
3061 idx = (idx + 1) & (kNumAllocRecords-1);
3062 }
3063
3064 // (xb) class name strings
3065 // (xb) method name strings
3066 // (xb) source file strings
3067 JDWP::Set4BE(&bytes[string_table_offset], bytes.size());
3068 class_names.WriteTo(bytes);
3069 method_names.WriteTo(bytes);
3070 filenames.WriteTo(bytes);
3071
3072 JNIEnv* env = Thread::Current()->GetJniEnv();
3073 jbyteArray result = env->NewByteArray(bytes.size());
3074 if (result != NULL) {
3075 env->SetByteArrayRegion(result, 0, bytes.size(), reinterpret_cast<const jbyte*>(&bytes[0]));
3076 }
3077 return result;
3078}
3079
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003080} // namespace art