blob: 025577516f3cd7d67487d99c82946210feb9c7c1 [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;
Elliott Hughesa656a0f2012-02-21 18:03:44 -0800125 uint32_t dex_pc;
126 Breakpoint(Method* method, uint32_t dex_pc) : method(method), dex_pc(dex_pc) {}
Elliott Hughes86964332012-02-15 19:37:42 -0800127};
128
129static std::ostream& operator<<(std::ostream& os, const Breakpoint& rhs) {
Elliott Hughes229feb72012-02-23 13:33:29 -0800130 os << StringPrintf("Breakpoint[%s @%#x]", PrettyMethod(rhs.method).c_str(), rhs.dex_pc);
Elliott Hughes86964332012-02-15 19:37:42 -0800131 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);
187 for (size_t i = 0; i < gBreakpoints.size(); ++i) {
Elliott Hughesa656a0f2012-02-21 18:03:44 -0800188 if (gBreakpoints[i].method == m && gBreakpoints[i].dex_pc == dex_pc) {
Elliott Hughes86964332012-02-15 19:37:42 -0800189 VLOG(jdwp) << "Hit breakpoint #" << i << ": " << gBreakpoints[i];
190 return true;
191 }
192 }
193 return false;
194}
195
Elliott Hughes436e3722012-02-17 20:01:47 -0800196static Array* DecodeArray(JDWP::RefTypeId id, JDWP::JdwpError& status) {
197 Object* o = gRegistry->Get<Object*>(id);
198 if (o == NULL || o == kInvalidObject) {
199 status = JDWP::ERR_INVALID_OBJECT;
200 return NULL;
201 }
202 if (!o->IsArrayInstance()) {
203 status = JDWP::ERR_INVALID_ARRAY;
204 return NULL;
205 }
206 status = JDWP::ERR_NONE;
207 return o->AsArray();
208}
209
210static Class* DecodeClass(JDWP::RefTypeId id, JDWP::JdwpError& status) {
211 Object* o = gRegistry->Get<Object*>(id);
212 if (o == NULL || o == kInvalidObject) {
213 status = JDWP::ERR_INVALID_OBJECT;
214 return NULL;
215 }
216 if (!o->IsClass()) {
217 status = JDWP::ERR_INVALID_CLASS;
218 return NULL;
219 }
220 status = JDWP::ERR_NONE;
221 return o->AsClass();
222}
223
224static Thread* DecodeThread(JDWP::ObjectId threadId) {
225 Object* thread_peer = gRegistry->Get<Object*>(threadId);
226 if (thread_peer == NULL || thread_peer == kInvalidObject) {
227 return NULL;
228 }
229 return Thread::FromManagedThread(thread_peer);
230}
231
Elliott Hughes24437992011-11-30 14:49:33 -0800232static JDWP::JdwpTag BasicTagFromDescriptor(const char* descriptor) {
233 // JDWP deliberately uses the descriptor characters' ASCII values for its enum.
234 // Note that by "basic" we mean that we don't get more specific than JT_OBJECT.
235 return static_cast<JDWP::JdwpTag>(descriptor[0]);
236}
237
238static JDWP::JdwpTag TagFromClass(Class* c) {
Elliott Hughes86b00102011-12-05 17:54:26 -0800239 CHECK(c != NULL);
Elliott Hughes24437992011-11-30 14:49:33 -0800240 if (c->IsArrayClass()) {
241 return JDWP::JT_ARRAY;
242 }
243
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800244 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Elliott Hughes24437992011-11-30 14:49:33 -0800245 if (c->IsStringClass()) {
246 return JDWP::JT_STRING;
247 } else if (c->IsClassClass()) {
248 return JDWP::JT_CLASS_OBJECT;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800249 } else if (class_linker->FindSystemClass("Ljava/lang/Thread;")->IsAssignableFrom(c)) {
Elliott Hughes24437992011-11-30 14:49:33 -0800250 return JDWP::JT_THREAD;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800251 } else if (class_linker->FindSystemClass("Ljava/lang/ThreadGroup;")->IsAssignableFrom(c)) {
Elliott Hughes24437992011-11-30 14:49:33 -0800252 return JDWP::JT_THREAD_GROUP;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800253 } else if (class_linker->FindSystemClass("Ljava/lang/ClassLoader;")->IsAssignableFrom(c)) {
Elliott Hughes24437992011-11-30 14:49:33 -0800254 return JDWP::JT_CLASS_LOADER;
Elliott Hughes24437992011-11-30 14:49:33 -0800255 } else {
256 return JDWP::JT_OBJECT;
257 }
258}
259
260/*
261 * Objects declared to hold Object might actually hold a more specific
262 * type. The debugger may take a special interest in these (e.g. it
263 * wants to display the contents of Strings), so we want to return an
264 * appropriate tag.
265 *
266 * Null objects are tagged JT_OBJECT.
267 */
268static JDWP::JdwpTag TagFromObject(const Object* o) {
269 return (o == NULL) ? JDWP::JT_OBJECT : TagFromClass(o->GetClass());
270}
271
272static bool IsPrimitiveTag(JDWP::JdwpTag tag) {
273 switch (tag) {
274 case JDWP::JT_BOOLEAN:
275 case JDWP::JT_BYTE:
276 case JDWP::JT_CHAR:
277 case JDWP::JT_FLOAT:
278 case JDWP::JT_DOUBLE:
279 case JDWP::JT_INT:
280 case JDWP::JT_LONG:
281 case JDWP::JT_SHORT:
282 case JDWP::JT_VOID:
283 return true;
284 default:
285 return false;
286 }
287}
288
Elliott Hughes3bb81562011-10-21 18:52:59 -0700289/*
290 * Handle one of the JDWP name/value pairs.
291 *
292 * JDWP options are:
293 * help: if specified, show help message and bail
294 * transport: may be dt_socket or dt_shmem
295 * address: for dt_socket, "host:port", or just "port" when listening
296 * server: if "y", wait for debugger to attach; if "n", attach to debugger
297 * timeout: how long to wait for debugger to connect / listen
298 *
299 * Useful with server=n (these aren't supported yet):
300 * onthrow=<exception-name>: connect to debugger when exception thrown
301 * onuncaught=y|n: connect to debugger when uncaught exception thrown
302 * launch=<command-line>: launch the debugger itself
303 *
304 * The "transport" option is required, as is "address" if server=n.
305 */
306static bool ParseJdwpOption(const std::string& name, const std::string& value) {
307 if (name == "transport") {
308 if (value == "dt_socket") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700309 gJdwpOptions.transport = JDWP::kJdwpTransportSocket;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700310 } else if (value == "dt_android_adb") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700311 gJdwpOptions.transport = JDWP::kJdwpTransportAndroidAdb;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700312 } else {
313 LOG(ERROR) << "JDWP transport not supported: " << value;
314 return false;
315 }
316 } else if (name == "server") {
317 if (value == "n") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700318 gJdwpOptions.server = false;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700319 } else if (value == "y") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700320 gJdwpOptions.server = true;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700321 } else {
322 LOG(ERROR) << "JDWP option 'server' must be 'y' or 'n'";
323 return false;
324 }
325 } else if (name == "suspend") {
326 if (value == "n") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700327 gJdwpOptions.suspend = false;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700328 } else if (value == "y") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700329 gJdwpOptions.suspend = true;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700330 } else {
331 LOG(ERROR) << "JDWP option 'suspend' must be 'y' or 'n'";
332 return false;
333 }
334 } else if (name == "address") {
335 /* this is either <port> or <host>:<port> */
336 std::string port_string;
Elliott Hughes376a7a02011-10-24 18:35:55 -0700337 gJdwpOptions.host.clear();
Elliott Hughes3bb81562011-10-21 18:52:59 -0700338 std::string::size_type colon = value.find(':');
339 if (colon != std::string::npos) {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700340 gJdwpOptions.host = value.substr(0, colon);
Elliott Hughes3bb81562011-10-21 18:52:59 -0700341 port_string = value.substr(colon + 1);
342 } else {
343 port_string = value;
344 }
345 if (port_string.empty()) {
346 LOG(ERROR) << "JDWP address missing port: " << value;
347 return false;
348 }
349 char* end;
Elliott Hughesba8eee12012-01-24 20:25:24 -0800350 uint64_t port = strtoul(port_string.c_str(), &end, 10);
351 if (*end != '\0' || port > 0xffff) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700352 LOG(ERROR) << "JDWP address has junk in port field: " << value;
353 return false;
354 }
Elliott Hughes376a7a02011-10-24 18:35:55 -0700355 gJdwpOptions.port = port;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700356 } else if (name == "launch" || name == "onthrow" || name == "oncaught" || name == "timeout") {
357 /* valid but unsupported */
358 LOG(INFO) << "Ignoring JDWP option '" << name << "'='" << value << "'";
359 } else {
360 LOG(INFO) << "Ignoring unrecognized JDWP option '" << name << "'='" << value << "'";
361 }
362
363 return true;
364}
365
366/*
367 * Parse the latter half of a -Xrunjdwp/-agentlib:jdwp= string, e.g.:
368 * "transport=dt_socket,address=8000,server=y,suspend=n"
369 */
370bool Dbg::ParseJdwpOptions(const std::string& options) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800371 VLOG(jdwp) << "ParseJdwpOptions: " << options;
Elliott Hughes47fce012011-10-25 18:37:19 -0700372
Elliott Hughes3bb81562011-10-21 18:52:59 -0700373 std::vector<std::string> pairs;
374 Split(options, ',', pairs);
375
376 for (size_t i = 0; i < pairs.size(); ++i) {
377 std::string::size_type equals = pairs[i].find('=');
378 if (equals == std::string::npos) {
379 LOG(ERROR) << "Can't parse JDWP option '" << pairs[i] << "' in '" << options << "'";
380 return false;
381 }
382 ParseJdwpOption(pairs[i].substr(0, equals), pairs[i].substr(equals + 1));
383 }
384
Elliott Hughes376a7a02011-10-24 18:35:55 -0700385 if (gJdwpOptions.transport == JDWP::kJdwpTransportUnknown) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700386 LOG(ERROR) << "Must specify JDWP transport: " << options;
387 }
Elliott Hughes376a7a02011-10-24 18:35:55 -0700388 if (!gJdwpOptions.server && (gJdwpOptions.host.empty() || gJdwpOptions.port == 0)) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700389 LOG(ERROR) << "Must specify JDWP host and port when server=n: " << options;
390 return false;
391 }
392
393 gJdwpConfigured = true;
394 return true;
395}
396
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700397void Dbg::StartJdwp() {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700398 if (!gJdwpAllowed || !gJdwpConfigured) {
399 // No JDWP for you!
400 return;
401 }
402
Elliott Hughes475fc232011-10-25 15:00:35 -0700403 CHECK(gRegistry == NULL);
404 gRegistry = new ObjectRegistry;
405
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700406 // Init JDWP if the debugger is enabled. This may connect out to a
407 // debugger, passively listen for a debugger, or block waiting for a
408 // debugger.
Elliott Hughes376a7a02011-10-24 18:35:55 -0700409 gJdwpState = JDWP::JdwpState::Create(&gJdwpOptions);
410 if (gJdwpState == NULL) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -0800411 // We probably failed because some other process has the port already, which means that
412 // if we don't abort the user is likely to think they're talking to us when they're actually
413 // talking to that other process.
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800414 LOG(FATAL) << "Debugger thread failed to initialize";
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700415 }
416
417 // If a debugger has already attached, send the "welcome" message.
418 // This may cause us to suspend all threads.
Elliott Hughes376a7a02011-10-24 18:35:55 -0700419 if (gJdwpState->IsActive()) {
Elliott Hughesa2155262011-11-16 16:26:58 -0800420 //ScopedThreadStateChange tsc(Thread::Current(), Thread::kRunnable);
Elliott Hughes376a7a02011-10-24 18:35:55 -0700421 if (!gJdwpState->PostVMStart()) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800422 LOG(WARNING) << "Failed to post 'start' message to debugger";
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700423 }
424 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700425}
426
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700427void Dbg::StopJdwp() {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700428 delete gJdwpState;
Elliott Hughes475fc232011-10-25 15:00:35 -0700429 delete gRegistry;
430 gRegistry = NULL;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700431}
432
Elliott Hughes767a1472011-10-26 18:49:02 -0700433void Dbg::GcDidFinish() {
434 if (gDdmHpifWhen != HPIF_WHEN_NEVER) {
435 LOG(DEBUG) << "Sending VM heap info to DDM";
Elliott Hughes7162ad92011-10-27 14:08:42 -0700436 DdmSendHeapInfo(gDdmHpifWhen);
Elliott Hughes767a1472011-10-26 18:49:02 -0700437 }
438 if (gDdmHpsgWhen != HPSG_WHEN_NEVER) {
439 LOG(DEBUG) << "Dumping VM heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700440 DdmSendHeapSegments(false);
Elliott Hughes767a1472011-10-26 18:49:02 -0700441 }
442 if (gDdmNhsgWhen != HPSG_WHEN_NEVER) {
443 LOG(DEBUG) << "Dumping native heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700444 DdmSendHeapSegments(true);
Elliott Hughes767a1472011-10-26 18:49:02 -0700445 }
446}
447
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700448void Dbg::SetJdwpAllowed(bool allowed) {
449 gJdwpAllowed = allowed;
450}
451
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700452DebugInvokeReq* Dbg::GetInvokeReq() {
Elliott Hughes475fc232011-10-25 15:00:35 -0700453 return Thread::Current()->GetInvokeReq();
454}
455
456Thread* Dbg::GetDebugThread() {
457 return (gJdwpState != NULL) ? gJdwpState->GetDebugThread() : NULL;
458}
459
460void Dbg::ClearWaitForEventThread() {
461 gJdwpState->ClearWaitForEventThread();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700462}
463
464void Dbg::Connected() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700465 CHECK(!gDebuggerConnected);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800466 VLOG(jdwp) << "JDWP has attached";
Elliott Hughes3bb81562011-10-21 18:52:59 -0700467 gDebuggerConnected = true;
Elliott Hughes86964332012-02-15 19:37:42 -0800468 gDisposed = false;
469}
470
471void Dbg::Disposed() {
472 gDisposed = true;
473}
474
475bool Dbg::IsDisposed() {
476 return gDisposed;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700477}
478
Elliott Hughesa2155262011-11-16 16:26:58 -0800479void Dbg::GoActive() {
480 // Enable all debugging features, including scans for breakpoints.
481 // This is a no-op if we're already active.
482 // Only called from the JDWP handler thread.
483 if (gDebuggerActive) {
484 return;
485 }
486
487 LOG(INFO) << "Debugger is active";
488
489 // TODO: CHECK we don't have any outstanding breakpoints.
490
491 gDebuggerActive = true;
492
493 //dvmEnableAllSubMode(kSubModeDebuggerActive);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700494}
495
496void Dbg::Disconnected() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700497 CHECK(gDebuggerConnected);
498
499 gDebuggerActive = false;
500
501 //dvmDisableAllSubMode(kSubModeDebuggerActive);
502
503 gRegistry->Clear();
504 gDebuggerConnected = false;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700505}
506
507bool Dbg::IsDebuggerConnected() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700508 return gDebuggerActive;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700509}
510
511bool Dbg::IsDebuggingEnabled() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700512 return gJdwpConfigured;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700513}
514
515int64_t Dbg::LastDebuggerActivity() {
Elliott Hughesca951522011-12-05 12:01:32 -0800516 return gJdwpState->LastDebuggerActivity();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700517}
518
519int Dbg::ThreadRunning() {
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700520 return static_cast<int>(Thread::Current()->SetState(Thread::kRunnable));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700521}
522
523int Dbg::ThreadWaiting() {
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700524 return static_cast<int>(Thread::Current()->SetState(Thread::kVmWait));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700525}
526
Elliott Hughes6ba581a2011-10-25 11:45:35 -0700527int Dbg::ThreadContinuing(int new_state) {
528 return static_cast<int>(Thread::Current()->SetState(static_cast<Thread::State>(new_state)));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700529}
530
531void Dbg::UndoDebuggerSuspensions() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700532 Runtime::Current()->GetThreadList()->UndoDebuggerSuspensions();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700533}
534
535void Dbg::Exit(int status) {
Elliott Hughes1bba14f2011-12-01 18:00:36 -0800536 exit(status); // This is all dalvik did.
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700537}
538
Elliott Hughesbfe487b2011-10-26 15:48:55 -0700539void Dbg::VisitRoots(Heap::RootVisitor* visitor, void* arg) {
540 if (gRegistry != NULL) {
541 gRegistry->VisitRoots(visitor, arg);
542 }
543}
544
Elliott Hughesc308a5d2012-02-16 17:12:06 -0800545std::string Dbg::GetClassName(JDWP::RefTypeId classId) {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800546 Object* o = gRegistry->Get<Object*>(classId);
Elliott Hughes436e3722012-02-17 20:01:47 -0800547 if (o == NULL) {
548 return "NULL";
549 }
550 if (o == kInvalidObject) {
551 return StringPrintf("invalid object %p", reinterpret_cast<void*>(classId));
552 }
553 if (!o->IsClass()) {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800554 return StringPrintf("non-class %p", o); // This is only used for debugging output anyway.
555 }
Elliott Hughesc308a5d2012-02-16 17:12:06 -0800556 return DescriptorToName(ClassHelper(o->AsClass()).GetDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700557}
558
Elliott Hughes436e3722012-02-17 20:01:47 -0800559JDWP::JdwpError Dbg::GetClassObject(JDWP::RefTypeId id, JDWP::ObjectId& classObjectId) {
560 JDWP::JdwpError status;
561 Class* c = DecodeClass(id, status);
562 if (c == NULL) {
563 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800564 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800565 classObjectId = gRegistry->Add(c);
566 return JDWP::ERR_NONE;
Elliott Hughes86964332012-02-15 19:37:42 -0800567}
568
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800569JDWP::JdwpError Dbg::GetSuperclass(JDWP::RefTypeId id, JDWP::RefTypeId& superclassId) {
570 JDWP::JdwpError status;
571 Class* c = DecodeClass(id, status);
572 if (c == NULL) {
573 return status;
574 }
575 if (c->IsInterface()) {
576 // http://code.google.com/p/android/issues/detail?id=20856
577 superclassId = NULL;
578 } else {
579 superclassId = gRegistry->Add(c->GetSuperClass());
580 }
581 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700582}
583
Elliott Hughes436e3722012-02-17 20:01:47 -0800584JDWP::JdwpError Dbg::GetClassLoader(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) {
Elliott Hughes1bba14f2011-12-01 18:00:36 -0800585 Object* o = gRegistry->Get<Object*>(id);
Elliott Hughes436e3722012-02-17 20:01:47 -0800586 if (o == NULL || o == kInvalidObject) {
587 return JDWP::ERR_INVALID_OBJECT;
588 }
589 expandBufAddObjectId(pReply, gRegistry->Add(o->GetClass()->GetClassLoader()));
590 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700591}
592
Elliott Hughes436e3722012-02-17 20:01:47 -0800593JDWP::JdwpError Dbg::GetModifiers(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) {
594 JDWP::JdwpError status;
595 Class* c = DecodeClass(id, status);
596 if (c == NULL) {
597 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800598 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800599
600 uint32_t access_flags = c->GetAccessFlags() & kAccJavaFlagsMask;
601
602 // Set ACC_SUPER; dex files don't contain this flag, but all classes are supposed to have it set.
603 // Class.getModifiers doesn't return it, but JDWP does, so we set it here.
604 access_flags |= kAccSuper;
605
606 expandBufAdd4BE(pReply, access_flags);
607
608 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700609}
610
Elliott Hughes436e3722012-02-17 20:01:47 -0800611JDWP::JdwpError Dbg::GetReflectedType(JDWP::RefTypeId classId, JDWP::ExpandBuf* pReply) {
612 JDWP::JdwpError status;
613 Class* c = DecodeClass(classId, status);
614 if (c == NULL) {
615 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800616 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800617
618 expandBufAdd1(pReply, c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS);
619 expandBufAddRefTypeId(pReply, classId);
620 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700621}
622
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800623void Dbg::GetClassList(std::vector<JDWP::RefTypeId>& classes) {
Elliott Hughesa2155262011-11-16 16:26:58 -0800624 // Get the complete list of reference classes (i.e. all classes except
625 // the primitive types).
626 // Returns a newly-allocated buffer full of RefTypeId values.
627 struct ClassListCreator {
Elliott Hughesba8eee12012-01-24 20:25:24 -0800628 explicit ClassListCreator(std::vector<JDWP::RefTypeId>& classes) : classes(classes) {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800629 }
630
Elliott Hughesa2155262011-11-16 16:26:58 -0800631 static bool Visit(Class* c, void* arg) {
632 return reinterpret_cast<ClassListCreator*>(arg)->Visit(c);
633 }
634
635 bool Visit(Class* c) {
636 if (!c->IsPrimitive()) {
637 classes.push_back(static_cast<JDWP::RefTypeId>(gRegistry->Add(c)));
638 }
639 return true;
640 }
641
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800642 std::vector<JDWP::RefTypeId>& classes;
Elliott Hughesa2155262011-11-16 16:26:58 -0800643 };
644
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800645 ClassListCreator clc(classes);
Elliott Hughesa2155262011-11-16 16:26:58 -0800646 Runtime::Current()->GetClassLinker()->VisitClasses(ClassListCreator::Visit, &clc);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700647}
648
Elliott Hughes436e3722012-02-17 20:01:47 -0800649JDWP::JdwpError Dbg::GetClassInfo(JDWP::RefTypeId classId, JDWP::JdwpTypeTag* pTypeTag, uint32_t* pStatus, std::string* pDescriptor) {
650 JDWP::JdwpError status;
651 Class* c = DecodeClass(classId, status);
652 if (c == NULL) {
653 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800654 }
655
Elliott Hughesa2155262011-11-16 16:26:58 -0800656 if (c->IsArrayClass()) {
657 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
658 *pTypeTag = JDWP::TT_ARRAY;
659 } else {
660 if (c->IsErroneous()) {
661 *pStatus = JDWP::CS_ERROR;
662 } else {
663 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED | JDWP::CS_INITIALIZED;
664 }
665 *pTypeTag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
666 }
667
668 if (pDescriptor != NULL) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800669 *pDescriptor = ClassHelper(c).GetDescriptor();
Elliott Hughesa2155262011-11-16 16:26:58 -0800670 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800671 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700672}
673
Elliott Hughesc3b77c72011-12-15 20:56:48 -0800674void Dbg::FindLoadedClassBySignature(const char* descriptor, std::vector<JDWP::RefTypeId>& ids) {
Elliott Hughes6fa602d2011-12-02 17:54:25 -0800675 std::vector<Class*> classes;
676 Runtime::Current()->GetClassLinker()->LookupClasses(descriptor, classes);
677 ids.clear();
678 for (size_t i = 0; i < classes.size(); ++i) {
679 ids.push_back(gRegistry->Add(classes[i]));
680 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700681}
682
Elliott Hughes2435a572012-02-17 16:07:41 -0800683JDWP::JdwpError Dbg::GetReferenceType(JDWP::ObjectId objectId, JDWP::ExpandBuf* pReply) {
Elliott Hughes499c5132011-11-17 14:55:11 -0800684 Object* o = gRegistry->Get<Object*>(objectId);
Elliott Hughes436e3722012-02-17 20:01:47 -0800685 if (o == NULL || o == kInvalidObject) {
Elliott Hughes2435a572012-02-17 16:07:41 -0800686 return JDWP::ERR_INVALID_OBJECT;
Elliott Hughes499c5132011-11-17 14:55:11 -0800687 }
Elliott Hughes2435a572012-02-17 16:07:41 -0800688
689 JDWP::JdwpTypeTag type_tag;
690 if (o->GetClass()->IsArrayClass()) {
691 type_tag = JDWP::TT_ARRAY;
692 } else if (o->GetClass()->IsInterface()) {
693 type_tag = JDWP::TT_INTERFACE;
694 } else {
695 type_tag = JDWP::TT_CLASS;
696 }
697 JDWP::RefTypeId type_id = gRegistry->Add(o->GetClass());
698
699 expandBufAdd1(pReply, type_tag);
700 expandBufAddRefTypeId(pReply, type_id);
701
702 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700703}
704
Elliott Hughes436e3722012-02-17 20:01:47 -0800705JDWP::JdwpError Dbg::GetSignature(JDWP::RefTypeId classId, std::string& signature) {
Elliott Hughes1fe7afb2012-02-13 17:23:03 -0800706 JDWP::JdwpError status;
Elliott Hughes436e3722012-02-17 20:01:47 -0800707 Class* c = DecodeClass(classId, status);
Elliott Hughes1fe7afb2012-02-13 17:23:03 -0800708 if (c == NULL) {
709 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800710 }
Elliott Hughes1fe7afb2012-02-13 17:23:03 -0800711 signature = ClassHelper(c).GetDescriptor();
712 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700713}
714
Elliott Hughes436e3722012-02-17 20:01:47 -0800715JDWP::JdwpError Dbg::GetSourceFile(JDWP::RefTypeId classId, std::string& result) {
716 JDWP::JdwpError status;
717 Class* c = DecodeClass(classId, status);
718 if (c == NULL) {
719 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800720 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800721 result = ClassHelper(c).GetSourceFile();
722 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700723}
724
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700725uint8_t Dbg::GetObjectTag(JDWP::ObjectId objectId) {
Elliott Hughes24437992011-11-30 14:49:33 -0800726 Object* o = gRegistry->Get<Object*>(objectId);
727 return TagFromObject(o);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700728}
729
Elliott Hughesaed4be92011-12-02 16:16:23 -0800730size_t Dbg::GetTagWidth(JDWP::JdwpTag tag) {
Elliott Hughesdbb40792011-11-18 17:05:22 -0800731 switch (tag) {
732 case JDWP::JT_VOID:
733 return 0;
734 case JDWP::JT_BYTE:
735 case JDWP::JT_BOOLEAN:
736 return 1;
737 case JDWP::JT_CHAR:
738 case JDWP::JT_SHORT:
739 return 2;
740 case JDWP::JT_FLOAT:
741 case JDWP::JT_INT:
742 return 4;
743 case JDWP::JT_ARRAY:
744 case JDWP::JT_OBJECT:
745 case JDWP::JT_STRING:
746 case JDWP::JT_THREAD:
747 case JDWP::JT_THREAD_GROUP:
748 case JDWP::JT_CLASS_LOADER:
749 case JDWP::JT_CLASS_OBJECT:
750 return sizeof(JDWP::ObjectId);
751 case JDWP::JT_DOUBLE:
752 case JDWP::JT_LONG:
753 return 8;
754 default:
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800755 LOG(FATAL) << "Unknown tag " << tag;
Elliott Hughesdbb40792011-11-18 17:05:22 -0800756 return -1;
757 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700758}
759
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800760JDWP::JdwpError Dbg::GetArrayLength(JDWP::ObjectId arrayId, int& length) {
761 JDWP::JdwpError status;
762 Array* a = DecodeArray(arrayId, status);
763 if (a == NULL) {
764 return status;
Elliott Hughes24437992011-11-30 14:49:33 -0800765 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800766 length = a->GetLength();
767 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700768}
769
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800770JDWP::JdwpError Dbg::OutputArray(JDWP::ObjectId arrayId, int offset, int count, JDWP::ExpandBuf* pReply) {
771 JDWP::JdwpError status;
772 Array* a = DecodeArray(arrayId, status);
773 if (a == NULL) {
774 return status;
775 }
Elliott Hughes24437992011-11-30 14:49:33 -0800776
777 if (offset < 0 || count < 0 || offset > a->GetLength() || a->GetLength() - offset < count) {
778 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800779 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughes24437992011-11-30 14:49:33 -0800780 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800781 std::string descriptor(ClassHelper(a->GetClass()).GetDescriptor());
Elliott Hughes24437992011-11-30 14:49:33 -0800782 JDWP::JdwpTag tag = BasicTagFromDescriptor(descriptor.c_str() + 1);
783
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800784 expandBufAdd1(pReply, tag);
785 expandBufAdd4BE(pReply, count);
786
Elliott Hughes24437992011-11-30 14:49:33 -0800787 if (IsPrimitiveTag(tag)) {
788 size_t width = GetTagWidth(tag);
Elliott Hughes24437992011-11-30 14:49:33 -0800789 uint8_t* dst = expandBufAddSpace(pReply, count * width);
790 if (width == 8) {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800791 const uint64_t* src8 = reinterpret_cast<uint64_t*>(a->GetRawData(sizeof(uint64_t)));
Elliott Hughes24437992011-11-30 14:49:33 -0800792 for (int i = 0; i < count; ++i) JDWP::Write8BE(&dst, src8[offset + i]);
793 } else if (width == 4) {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800794 const uint32_t* src4 = reinterpret_cast<uint32_t*>(a->GetRawData(sizeof(uint32_t)));
Elliott Hughes24437992011-11-30 14:49:33 -0800795 for (int i = 0; i < count; ++i) JDWP::Write4BE(&dst, src4[offset + i]);
796 } else if (width == 2) {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800797 const uint16_t* src2 = reinterpret_cast<uint16_t*>(a->GetRawData(sizeof(uint16_t)));
Elliott Hughes24437992011-11-30 14:49:33 -0800798 for (int i = 0; i < count; ++i) JDWP::Write2BE(&dst, src2[offset + i]);
799 } else {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800800 const uint8_t* src = reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint8_t)));
Elliott Hughes24437992011-11-30 14:49:33 -0800801 memcpy(dst, &src[offset * width], count * width);
802 }
803 } else {
804 ObjectArray<Object>* oa = a->AsObjectArray<Object>();
805 for (int i = 0; i < count; ++i) {
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800806 Object* element = oa->Get(offset + i);
Elliott Hughes24437992011-11-30 14:49:33 -0800807 JDWP::JdwpTag specific_tag = (element != NULL) ? TagFromObject(element) : tag;
808 expandBufAdd1(pReply, specific_tag);
809 expandBufAddObjectId(pReply, gRegistry->Add(element));
810 }
811 }
812
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800813 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700814}
815
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800816JDWP::JdwpError Dbg::SetArrayElements(JDWP::ObjectId arrayId, int offset, int count, const uint8_t* src) {
817 JDWP::JdwpError status;
818 Array* a = DecodeArray(arrayId, status);
819 if (a == NULL) {
820 return status;
821 }
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800822
823 if (offset < 0 || count < 0 || offset > a->GetLength() || a->GetLength() - offset < count) {
824 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800825 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800826 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800827 std::string descriptor(ClassHelper(a->GetClass()).GetDescriptor());
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800828 JDWP::JdwpTag tag = BasicTagFromDescriptor(descriptor.c_str() + 1);
829
830 if (IsPrimitiveTag(tag)) {
831 size_t width = GetTagWidth(tag);
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800832 if (width == 8) {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800833 uint8_t* dst = &(reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint64_t)))[offset * width]);
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800834 for (int i = 0; i < count; ++i) {
835 // Handle potentially non-aligned memory access one byte at a time for ARM's benefit.
836 uint64_t value;
837 for (size_t j = 0; j < sizeof(uint64_t); ++j) reinterpret_cast<uint8_t*>(&value)[j] = src[j];
838 src += sizeof(uint64_t);
839 JDWP::Write8BE(&dst, value);
840 }
841 } else if (width == 4) {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800842 uint8_t* dst = &(reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint32_t)))[offset * width]);
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800843 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) {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800846 uint8_t* dst = &(reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint16_t)))[offset * width]);
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800847 const uint16_t* src2 = reinterpret_cast<const uint16_t*>(src);
848 for (int i = 0; i < count; ++i) JDWP::Write2BE(&dst, src2[i]);
849 } else {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800850 uint8_t* dst = &(reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint8_t)))[offset * width]);
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800851 memcpy(&dst[offset * width], src, count * width);
852 }
853 } else {
854 ObjectArray<Object>* oa = a->AsObjectArray<Object>();
855 for (int i = 0; i < count; ++i) {
856 JDWP::ObjectId id = JDWP::ReadObjectId(&src);
Elliott Hughes436e3722012-02-17 20:01:47 -0800857 Object* o = gRegistry->Get<Object*>(id);
858 if (o == kInvalidObject) {
859 return JDWP::ERR_INVALID_OBJECT;
860 }
861 oa->Set(offset + i, o);
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800862 }
863 }
864
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800865 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700866}
867
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800868JDWP::ObjectId Dbg::CreateString(const std::string& str) {
869 return gRegistry->Add(String::AllocFromModifiedUtf8(str.c_str()));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700870}
871
Elliott Hughes436e3722012-02-17 20:01:47 -0800872JDWP::JdwpError Dbg::CreateObject(JDWP::RefTypeId classId, JDWP::ObjectId& new_object) {
873 JDWP::JdwpError status;
874 Class* c = DecodeClass(classId, status);
875 if (c == NULL) {
876 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800877 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800878 new_object = gRegistry->Add(c->AllocObject());
879 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700880}
881
Elliott Hughesbf13d362011-12-08 15:51:37 -0800882/*
883 * Used by Eclipse's "Display" view to evaluate "new byte[5]" to get "(byte[]) [0, 0, 0, 0, 0]".
884 */
Elliott Hughes436e3722012-02-17 20:01:47 -0800885JDWP::JdwpError Dbg::CreateArrayObject(JDWP::RefTypeId arrayClassId, uint32_t length, JDWP::ObjectId& new_array) {
886 JDWP::JdwpError status;
887 Class* c = DecodeClass(arrayClassId, status);
888 if (c == NULL) {
889 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800890 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800891 new_array = gRegistry->Add(Array::Alloc(c, length));
892 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700893}
894
895bool Dbg::MatchType(JDWP::RefTypeId instClassId, JDWP::RefTypeId classId) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800896 JDWP::JdwpError status;
897 Class* c1 = DecodeClass(instClassId, status);
Elliott Hughesa656a0f2012-02-21 18:03:44 -0800898 CHECK(c1 != NULL);
Elliott Hughes436e3722012-02-17 20:01:47 -0800899 Class* c2 = DecodeClass(classId, status);
Elliott Hughesa656a0f2012-02-21 18:03:44 -0800900 CHECK(c2 != NULL);
901 return c1->IsAssignableFrom(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 Hughes972a47b2012-02-21 18:16:06 -0800944 location.dex_pc = m->IsNative() ? -1 : m->ToDexPC(native_pc);
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 Hughesad3da692012-02-24 16:51:35 -08001124 VLOG(jdwp) << StringPrintf(" %2zd: %d(%d) '%s' '%s' '%s' actual slot=%d mangled slot=%d", pContext->variable_count, startAddress, endAddress - startAddress, name, descriptor, signature, slot, MangleSlot(slot, name));
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 Hughes0cf74332012-02-23 23:14:00 -08001173static JDWP::JdwpError GetFieldValueImpl(JDWP::RefTypeId refTypeId, JDWP::ObjectId objectId, JDWP::FieldId fieldId, JDWP::ExpandBuf* pReply, bool is_static) {
1174 JDWP::JdwpError status;
1175 Class* c = DecodeClass(refTypeId, status);
1176 if (refTypeId != 0 && c == NULL) {
1177 return status;
1178 }
1179
Elliott Hughesaed4be92011-12-02 16:16:23 -08001180 Object* o = gRegistry->Get<Object*>(objectId);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001181 if ((!is_static && o == NULL) || o == kInvalidObject) {
1182 return JDWP::ERR_INVALID_OBJECT;
1183 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001184 Field* f = FromFieldId(fieldId);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001185
1186 Class* receiver_class = c;
1187 if (receiver_class == NULL && o != NULL) {
1188 receiver_class = o->GetClass();
1189 }
1190 // TODO: should we give up now if receiver_class is NULL?
1191 if (receiver_class != NULL && !f->GetDeclaringClass()->IsAssignableFrom(receiver_class)) {
1192 LOG(INFO) << "ERR_INVALID_FIELDID: " << PrettyField(f) << " " << PrettyClass(receiver_class);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001193 return JDWP::ERR_INVALID_FIELDID;
1194 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001195
Elliott Hughes0cf74332012-02-23 23:14:00 -08001196 // The RI only enforces the static/non-static mismatch in one direction.
1197 // TODO: should we change the tests and check both?
1198 if (is_static) {
1199 if (!f->IsStatic()) {
1200 return JDWP::ERR_INVALID_FIELDID;
1201 }
1202 } else {
1203 if (f->IsStatic()) {
1204 LOG(WARNING) << "Ignoring non-NULL receiver for ObjectReference.SetValues on static field " << PrettyField(f);
1205 o = NULL;
1206 }
1207 }
1208
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001209 JDWP::JdwpTag tag = BasicTagFromDescriptor(FieldHelper(f).GetTypeDescriptor());
Elliott Hughesaed4be92011-12-02 16:16:23 -08001210
1211 if (IsPrimitiveTag(tag)) {
1212 expandBufAdd1(pReply, tag);
1213 if (tag == JDWP::JT_BOOLEAN || tag == JDWP::JT_BYTE) {
1214 expandBufAdd1(pReply, f->Get32(o));
1215 } else if (tag == JDWP::JT_CHAR || tag == JDWP::JT_SHORT) {
1216 expandBufAdd2BE(pReply, f->Get32(o));
1217 } else if (tag == JDWP::JT_FLOAT || tag == JDWP::JT_INT) {
1218 expandBufAdd4BE(pReply, f->Get32(o));
1219 } else if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
1220 expandBufAdd8BE(pReply, f->Get64(o));
1221 } else {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001222 LOG(FATAL) << "Unknown tag: " << tag;
Elliott Hughesaed4be92011-12-02 16:16:23 -08001223 }
1224 } else {
1225 Object* value = f->GetObject(o);
1226 expandBufAdd1(pReply, TagFromObject(value));
1227 expandBufAddObjectId(pReply, gRegistry->Add(value));
1228 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001229 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001230}
1231
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001232JDWP::JdwpError Dbg::GetFieldValue(JDWP::ObjectId objectId, JDWP::FieldId fieldId, JDWP::ExpandBuf* pReply) {
Elliott Hughes0cf74332012-02-23 23:14:00 -08001233 return GetFieldValueImpl(0, objectId, fieldId, pReply, false);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001234}
1235
Elliott Hughes0cf74332012-02-23 23:14:00 -08001236JDWP::JdwpError Dbg::GetStaticFieldValue(JDWP::RefTypeId refTypeId, JDWP::FieldId fieldId, JDWP::ExpandBuf* pReply) {
1237 return GetFieldValueImpl(refTypeId, 0, fieldId, pReply, true);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001238}
1239
1240static JDWP::JdwpError SetFieldValueImpl(JDWP::ObjectId objectId, JDWP::FieldId fieldId, uint64_t value, int width, bool is_static) {
Elliott Hughesaed4be92011-12-02 16:16:23 -08001241 Object* o = gRegistry->Get<Object*>(objectId);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001242 if ((!is_static && o == NULL) || o == kInvalidObject) {
1243 return JDWP::ERR_INVALID_OBJECT;
1244 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001245 Field* f = FromFieldId(fieldId);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001246
1247 // The RI only enforces the static/non-static mismatch in one direction.
1248 // TODO: should we change the tests and check both?
1249 if (is_static) {
1250 if (!f->IsStatic()) {
1251 return JDWP::ERR_INVALID_FIELDID;
1252 }
1253 } else {
1254 if (f->IsStatic()) {
1255 LOG(WARNING) << "Ignoring non-NULL receiver for ObjectReference.SetValues on static field " << PrettyField(f);
1256 o = NULL;
1257 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001258 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001259
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001260 JDWP::JdwpTag tag = BasicTagFromDescriptor(FieldHelper(f).GetTypeDescriptor());
Elliott Hughesaed4be92011-12-02 16:16:23 -08001261
1262 if (IsPrimitiveTag(tag)) {
1263 if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
1264 f->Set64(o, value);
1265 } else {
1266 f->Set32(o, value);
1267 }
1268 } else {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001269 Object* v = gRegistry->Get<Object*>(value);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001270 if (v == kInvalidObject) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001271 return JDWP::ERR_INVALID_OBJECT;
1272 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001273 if (v != NULL) {
1274 Class* field_type = FieldHelper(f).GetType();
1275 if (!field_type->IsAssignableFrom(v->GetClass())) {
1276 return JDWP::ERR_INVALID_OBJECT;
1277 }
1278 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001279 f->SetObject(o, v);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001280 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001281
1282 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001283}
1284
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001285JDWP::JdwpError Dbg::SetFieldValue(JDWP::ObjectId objectId, JDWP::FieldId fieldId, uint64_t value, int width) {
1286 return SetFieldValueImpl(objectId, fieldId, value, width, false);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001287}
1288
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001289JDWP::JdwpError Dbg::SetStaticFieldValue(JDWP::FieldId fieldId, uint64_t value, int width) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001290 return SetFieldValueImpl(0, fieldId, value, width, true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001291}
1292
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001293std::string Dbg::StringToUtf8(JDWP::ObjectId strId) {
1294 String* s = gRegistry->Get<String*>(strId);
1295 return s->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001296}
1297
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001298bool Dbg::GetThreadName(JDWP::ObjectId threadId, std::string& name) {
1299 ScopedThreadListLock thread_list_lock;
1300 Thread* thread = DecodeThread(threadId);
1301 if (thread == NULL) {
1302 return false;
1303 }
Elliott Hughesffb465f2012-03-01 18:46:05 -08001304 thread->GetThreadName(name);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001305 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001306}
1307
Elliott Hughes2435a572012-02-17 16:07:41 -08001308JDWP::JdwpError Dbg::GetThreadGroup(JDWP::ObjectId threadId, JDWP::ExpandBuf* pReply) {
Elliott Hughes499c5132011-11-17 14:55:11 -08001309 Object* thread = gRegistry->Get<Object*>(threadId);
Elliott Hughes436e3722012-02-17 20:01:47 -08001310 if (thread == kInvalidObject) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001311 return JDWP::ERR_INVALID_OBJECT;
1312 }
1313
1314 // Okay, so it's an object, but is it actually a thread?
Elliott Hughes436e3722012-02-17 20:01:47 -08001315 if (DecodeThread(threadId) == NULL) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001316 return JDWP::ERR_INVALID_THREAD;
1317 }
Elliott Hughes499c5132011-11-17 14:55:11 -08001318
1319 Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/Thread;");
1320 CHECK(c != NULL);
1321 Field* f = c->FindInstanceField("group", "Ljava/lang/ThreadGroup;");
1322 CHECK(f != NULL);
1323 Object* group = f->GetObject(thread);
1324 CHECK(group != NULL);
Elliott Hughes2435a572012-02-17 16:07:41 -08001325 JDWP::ObjectId thread_group_id = gRegistry->Add(group);
1326
1327 expandBufAddObjectId(pReply, thread_group_id);
1328 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001329}
1330
Elliott Hughes499c5132011-11-17 14:55:11 -08001331std::string Dbg::GetThreadGroupName(JDWP::ObjectId threadGroupId) {
1332 Object* thread_group = gRegistry->Get<Object*>(threadGroupId);
1333 CHECK(thread_group != NULL);
1334
1335 Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/ThreadGroup;");
1336 CHECK(c != NULL);
1337 Field* f = c->FindInstanceField("name", "Ljava/lang/String;");
1338 CHECK(f != NULL);
1339 String* s = reinterpret_cast<String*>(f->GetObject(thread_group));
1340 return s->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001341}
1342
1343JDWP::ObjectId Dbg::GetThreadGroupParent(JDWP::ObjectId threadGroupId) {
Elliott Hughes4e235312011-12-02 11:34:15 -08001344 Object* thread_group = gRegistry->Get<Object*>(threadGroupId);
1345 CHECK(thread_group != NULL);
1346
1347 Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/ThreadGroup;");
1348 CHECK(c != NULL);
1349 Field* f = c->FindInstanceField("parent", "Ljava/lang/ThreadGroup;");
1350 CHECK(f != NULL);
1351 Object* parent = f->GetObject(thread_group);
1352 return gRegistry->Add(parent);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001353}
1354
Elliott Hughes499c5132011-11-17 14:55:11 -08001355static Object* GetStaticThreadGroup(const char* field_name) {
1356 Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/ThreadGroup;");
1357 CHECK(c != NULL);
1358 Field* f = c->FindStaticField(field_name, "Ljava/lang/ThreadGroup;");
1359 CHECK(f != NULL);
1360 Object* group = f->GetObject(NULL);
1361 CHECK(group != NULL);
1362 return group;
1363}
1364
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001365JDWP::ObjectId Dbg::GetSystemThreadGroupId() {
Elliott Hughes499c5132011-11-17 14:55:11 -08001366 return gRegistry->Add(GetStaticThreadGroup("mSystem"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001367}
1368
1369JDWP::ObjectId Dbg::GetMainThreadGroupId() {
Elliott Hughes499c5132011-11-17 14:55:11 -08001370 return gRegistry->Add(GetStaticThreadGroup("mMain"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001371}
1372
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001373bool Dbg::GetThreadStatus(JDWP::ObjectId threadId, JDWP::JdwpThreadStatus* pThreadStatus, JDWP::JdwpSuspendStatus* pSuspendStatus) {
Elliott Hughes499c5132011-11-17 14:55:11 -08001374 ScopedThreadListLock thread_list_lock;
1375
1376 Thread* thread = DecodeThread(threadId);
1377 if (thread == NULL) {
1378 return false;
1379 }
1380
Elliott Hughes3ce4b262012-02-24 11:24:02 -08001381 // TODO: if we're in Thread.sleep(long), we should return TS_SLEEPING,
1382 // even if it's implemented using Object.wait(long).
Elliott Hughes499c5132011-11-17 14:55:11 -08001383 switch (thread->GetState()) {
1384 case Thread::kTerminated: *pThreadStatus = JDWP::TS_ZOMBIE; break;
1385 case Thread::kRunnable: *pThreadStatus = JDWP::TS_RUNNING; break;
Elliott Hughes3ce4b262012-02-24 11:24:02 -08001386 case Thread::kTimedWaiting: *pThreadStatus = JDWP::TS_WAIT; break;
Elliott Hughes499c5132011-11-17 14:55:11 -08001387 case Thread::kBlocked: *pThreadStatus = JDWP::TS_MONITOR; break;
1388 case Thread::kWaiting: *pThreadStatus = JDWP::TS_WAIT; break;
1389 case Thread::kInitializing: *pThreadStatus = JDWP::TS_ZOMBIE; break;
1390 case Thread::kStarting: *pThreadStatus = JDWP::TS_ZOMBIE; break;
1391 case Thread::kNative: *pThreadStatus = JDWP::TS_RUNNING; break;
1392 case Thread::kVmWait: *pThreadStatus = JDWP::TS_WAIT; break;
1393 case Thread::kSuspended: *pThreadStatus = JDWP::TS_RUNNING; break;
1394 default:
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001395 LOG(FATAL) << "Unknown thread state " << thread->GetState();
Elliott Hughes499c5132011-11-17 14:55:11 -08001396 }
1397
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001398 *pSuspendStatus = (thread->IsSuspended() ? JDWP::SUSPEND_STATUS_SUSPENDED : JDWP::SUSPEND_STATUS_NOT_SUSPENDED);
Elliott Hughes499c5132011-11-17 14:55:11 -08001399
1400 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001401}
1402
Elliott Hughes2435a572012-02-17 16:07:41 -08001403JDWP::JdwpError Dbg::GetThreadSuspendCount(JDWP::ObjectId threadId, JDWP::ExpandBuf* pReply) {
1404 Thread* thread = DecodeThread(threadId);
1405 if (thread == NULL) {
1406 return JDWP::ERR_INVALID_THREAD;
1407 }
1408 expandBufAdd4BE(pReply, thread->GetSuspendCount());
1409 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001410}
1411
1412bool Dbg::ThreadExists(JDWP::ObjectId threadId) {
Elliott Hughes761928d2011-11-16 18:33:03 -08001413 return DecodeThread(threadId) != NULL;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001414}
1415
1416bool Dbg::IsSuspended(JDWP::ObjectId threadId) {
Elliott Hughes761928d2011-11-16 18:33:03 -08001417 return DecodeThread(threadId)->IsSuspended();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001418}
1419
Elliott Hughesa2155262011-11-16 16:26:58 -08001420void Dbg::GetThreadGroupThreadsImpl(Object* thread_group, JDWP::ObjectId** ppThreadIds, uint32_t* pThreadCount) {
1421 struct ThreadListVisitor {
1422 static void Visit(Thread* t, void* arg) {
1423 reinterpret_cast<ThreadListVisitor*>(arg)->Visit(t);
1424 }
1425
1426 void Visit(Thread* t) {
1427 if (t == Dbg::GetDebugThread()) {
1428 // Skip the JDWP thread. Some debuggers get bent out of shape when they can't suspend and
1429 // query all threads, so it's easier if we just don't tell them about this thread.
1430 return;
1431 }
1432 if (thread_group == NULL || t->GetThreadGroup() == thread_group) {
1433 threads.push_back(gRegistry->Add(t->GetPeer()));
1434 }
1435 }
1436
1437 Object* thread_group;
1438 std::vector<JDWP::ObjectId> threads;
1439 };
1440
1441 ThreadListVisitor tlv;
1442 tlv.thread_group = thread_group;
1443
1444 {
1445 ScopedThreadListLock thread_list_lock;
1446 Runtime::Current()->GetThreadList()->ForEach(ThreadListVisitor::Visit, &tlv);
1447 }
1448
1449 *pThreadCount = tlv.threads.size();
1450 if (*pThreadCount == 0) {
1451 *ppThreadIds = NULL;
1452 } else {
1453 *ppThreadIds = new JDWP::ObjectId[*pThreadCount];
1454 for (size_t i = 0; i < *pThreadCount; ++i) {
1455 (*ppThreadIds)[i] = tlv.threads[i];
1456 }
1457 }
1458}
1459
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001460void Dbg::GetThreadGroupThreads(JDWP::ObjectId threadGroupId, JDWP::ObjectId** ppThreadIds, uint32_t* pThreadCount) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001461 GetThreadGroupThreadsImpl(gRegistry->Get<Object*>(threadGroupId), ppThreadIds, pThreadCount);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001462}
1463
1464void Dbg::GetAllThreads(JDWP::ObjectId** ppThreadIds, uint32_t* pThreadCount) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001465 GetThreadGroupThreadsImpl(NULL, ppThreadIds, pThreadCount);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001466}
1467
Elliott Hughes86964332012-02-15 19:37:42 -08001468static int GetStackDepth(Thread* thread) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001469 struct CountStackDepthVisitor : public Thread::StackVisitor {
1470 CountStackDepthVisitor() : depth(0) {}
Elliott Hughes530fa002012-03-12 11:44:49 -07001471 bool VisitFrame(const Frame& f, uintptr_t) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -08001472 if (f.HasMethod()) {
1473 ++depth;
1474 }
Elliott Hughes530fa002012-03-12 11:44:49 -07001475 return true;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001476 }
1477 size_t depth;
1478 };
1479 CountStackDepthVisitor visitor;
Elliott Hughes86964332012-02-15 19:37:42 -08001480 thread->WalkStack(&visitor);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001481 return visitor.depth;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001482}
1483
Elliott Hughes86964332012-02-15 19:37:42 -08001484int Dbg::GetThreadFrameCount(JDWP::ObjectId threadId) {
1485 ScopedThreadListLock thread_list_lock;
1486 return GetStackDepth(DecodeThread(threadId));
1487}
1488
Elliott Hughes530fa002012-03-12 11:44:49 -07001489void Dbg::GetThreadFrame(JDWP::ObjectId threadId, int desired_frame_number, JDWP::FrameId* pFrameId, JDWP::JdwpLocation* pLoc) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001490 ScopedThreadListLock thread_list_lock;
1491 struct GetFrameVisitor : public Thread::StackVisitor {
1492 GetFrameVisitor(int desired_frame_number, JDWP::FrameId* pFrameId, JDWP::JdwpLocation* pLoc)
Elliott Hughes530fa002012-03-12 11:44:49 -07001493 : depth(0), desired_frame_number(desired_frame_number), pFrameId(pFrameId), pLoc(pLoc) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001494 }
Elliott Hughes530fa002012-03-12 11:44:49 -07001495 bool VisitFrame(const Frame& f, uintptr_t pc) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001496 if (!f.HasMethod()) {
Elliott Hughes530fa002012-03-12 11:44:49 -07001497 return true; // The debugger can't do anything useful with a frame that has no Method*.
Elliott Hughes03181a82011-11-17 17:22:21 -08001498 }
Elliott Hughes03181a82011-11-17 17:22:21 -08001499 if (depth == desired_frame_number) {
1500 *pFrameId = reinterpret_cast<JDWP::FrameId>(f.GetSP());
Elliott Hughesd07986f2011-12-06 18:27:45 -08001501 SetLocation(*pLoc, f.GetMethod(), pc);
Elliott Hughes530fa002012-03-12 11:44:49 -07001502 return false;
Elliott Hughes03181a82011-11-17 17:22:21 -08001503 }
1504 ++depth;
Elliott Hughes530fa002012-03-12 11:44:49 -07001505 return true;
Elliott Hughes03181a82011-11-17 17:22:21 -08001506 }
Elliott Hughes03181a82011-11-17 17:22:21 -08001507 int depth;
1508 int desired_frame_number;
1509 JDWP::FrameId* pFrameId;
1510 JDWP::JdwpLocation* pLoc;
1511 };
1512 GetFrameVisitor visitor(desired_frame_number, pFrameId, pLoc);
1513 visitor.desired_frame_number = desired_frame_number;
1514 DecodeThread(threadId)->WalkStack(&visitor);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001515}
1516
1517JDWP::ObjectId Dbg::GetThreadSelfId() {
Elliott Hughes475fc232011-10-25 15:00:35 -07001518 return gRegistry->Add(Thread::Current()->GetPeer());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001519}
1520
Elliott Hughes475fc232011-10-25 15:00:35 -07001521void Dbg::SuspendVM() {
Elliott Hughesa2155262011-11-16 16:26:58 -08001522 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 -07001523 Runtime::Current()->GetThreadList()->SuspendAll(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001524}
1525
1526void Dbg::ResumeVM() {
Elliott Hughes475fc232011-10-25 15:00:35 -07001527 Runtime::Current()->GetThreadList()->ResumeAll(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001528}
1529
1530void Dbg::SuspendThread(JDWP::ObjectId threadId) {
Elliott Hughes4e235312011-12-02 11:34:15 -08001531 Object* peer = gRegistry->Get<Object*>(threadId);
1532 ScopedThreadListLock thread_list_lock;
1533 Thread* thread = Thread::FromManagedThread(peer);
1534 if (thread == NULL) {
1535 LOG(WARNING) << "No such thread for suspend: " << peer;
1536 return;
1537 }
1538 Runtime::Current()->GetThreadList()->Suspend(thread, true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001539}
1540
1541void Dbg::ResumeThread(JDWP::ObjectId threadId) {
Elliott Hughes4e235312011-12-02 11:34:15 -08001542 Object* peer = gRegistry->Get<Object*>(threadId);
1543 ScopedThreadListLock thread_list_lock;
1544 Thread* thread = Thread::FromManagedThread(peer);
1545 if (thread == NULL) {
1546 LOG(WARNING) << "No such thread for resume: " << peer;
1547 return;
1548 }
1549 Runtime::Current()->GetThreadList()->Resume(thread, true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001550}
1551
1552void Dbg::SuspendSelf() {
Elliott Hughes475fc232011-10-25 15:00:35 -07001553 Runtime::Current()->GetThreadList()->SuspendSelfForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001554}
1555
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001556static Object* GetThis(Frame& f) {
Elliott Hughes86b00102011-12-05 17:54:26 -08001557 Method* m = f.GetMethod();
Elliott Hughes86b00102011-12-05 17:54:26 -08001558 Object* o = NULL;
1559 if (!m->IsNative() && !m->IsStatic()) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001560 uint16_t reg = DemangleSlot(0, m);
Elliott Hughes86b00102011-12-05 17:54:26 -08001561 o = reinterpret_cast<Object*>(f.GetVReg(m, reg));
1562 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001563 return o;
1564}
1565
1566void Dbg::GetThisObject(JDWP::FrameId frameId, JDWP::ObjectId* pThisId) {
1567 Method** sp = reinterpret_cast<Method**>(frameId);
1568 Frame f(sp);
1569 Object* o = GetThis(f);
Elliott Hughes86b00102011-12-05 17:54:26 -08001570 *pThisId = gRegistry->Add(o);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001571}
1572
Elliott Hughescccd84f2011-12-05 16:51:54 -08001573void 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 -08001574 Method** sp = reinterpret_cast<Method**>(frameId);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001575 Frame f(sp);
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001576 Method* m = f.GetMethod();
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001577 uint16_t reg = DemangleSlot(slot, m);
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001578
1579 const VmapTable vmap_table(m->GetVmapTableRaw());
1580 uint32_t vmap_offset;
1581 if (vmap_table.IsInContext(reg, vmap_offset)) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001582 UNIMPLEMENTED(FATAL) << "Don't know how to pull locals from callee save frames: " << vmap_offset;
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001583 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001584
Elliott Hughesad3da692012-02-24 16:51:35 -08001585 // TODO: check that the tag is compatible with the actual type of the slot!
1586
Elliott Hughesdbb40792011-11-18 17:05:22 -08001587 switch (tag) {
1588 case JDWP::JT_BOOLEAN:
1589 {
Elliott Hughescccd84f2011-12-05 16:51:54 -08001590 CHECK_EQ(width, 1U);
Elliott Hughes1bba14f2011-12-01 18:00:36 -08001591 uint32_t intVal = f.GetVReg(m, reg);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001592 VLOG(jdwp) << "get boolean local " << reg << " = " << intVal;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001593 JDWP::Set1(buf+1, intVal != 0);
1594 }
1595 break;
1596 case JDWP::JT_BYTE:
1597 {
Elliott Hughescccd84f2011-12-05 16:51:54 -08001598 CHECK_EQ(width, 1U);
Elliott Hughes1bba14f2011-12-01 18:00:36 -08001599 uint32_t intVal = f.GetVReg(m, reg);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001600 VLOG(jdwp) << "get byte local " << reg << " = " << intVal;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001601 JDWP::Set1(buf+1, intVal);
1602 }
1603 break;
1604 case JDWP::JT_SHORT:
1605 case JDWP::JT_CHAR:
1606 {
Elliott Hughescccd84f2011-12-05 16:51:54 -08001607 CHECK_EQ(width, 2U);
Elliott Hughes1bba14f2011-12-01 18:00:36 -08001608 uint32_t intVal = f.GetVReg(m, reg);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001609 VLOG(jdwp) << "get short/char local " << reg << " = " << intVal;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001610 JDWP::Set2BE(buf+1, intVal);
1611 }
1612 break;
1613 case JDWP::JT_INT:
1614 case JDWP::JT_FLOAT:
1615 {
Elliott Hughescccd84f2011-12-05 16:51:54 -08001616 CHECK_EQ(width, 4U);
Elliott Hughes1bba14f2011-12-01 18:00:36 -08001617 uint32_t intVal = f.GetVReg(m, reg);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001618 VLOG(jdwp) << "get int/float local " << reg << " = " << intVal;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001619 JDWP::Set4BE(buf+1, intVal);
1620 }
1621 break;
1622 case JDWP::JT_ARRAY:
1623 {
Elliott Hughescccd84f2011-12-05 16:51:54 -08001624 CHECK_EQ(width, sizeof(JDWP::ObjectId));
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001625 Object* o = reinterpret_cast<Object*>(f.GetVReg(m, reg));
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001626 VLOG(jdwp) << "get array local " << reg << " = " << o;
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001627 if (o != NULL && !Runtime::Current()->GetHeap()->IsHeapAddress(o)) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001628 LOG(FATAL) << "Register " << reg << " expected to hold array: " << o;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001629 }
1630 JDWP::SetObjectId(buf+1, gRegistry->Add(o));
1631 }
1632 break;
Elliott Hughesad3da692012-02-24 16:51:35 -08001633 case JDWP::JT_CLASS_LOADER:
1634 case JDWP::JT_CLASS_OBJECT:
Elliott Hughesdbb40792011-11-18 17:05:22 -08001635 case JDWP::JT_OBJECT:
Elliott Hughesad3da692012-02-24 16:51:35 -08001636 case JDWP::JT_STRING:
1637 case JDWP::JT_THREAD:
1638 case JDWP::JT_THREAD_GROUP:
Elliott Hughesdbb40792011-11-18 17:05:22 -08001639 {
Elliott Hughescccd84f2011-12-05 16:51:54 -08001640 CHECK_EQ(width, sizeof(JDWP::ObjectId));
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001641 Object* o = reinterpret_cast<Object*>(f.GetVReg(m, reg));
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001642 VLOG(jdwp) << "get object local " << reg << " = " << o;
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001643 if (o != NULL && !Runtime::Current()->GetHeap()->IsHeapAddress(o)) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001644 LOG(FATAL) << "Register " << reg << " expected to hold object: " << o;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001645 }
1646 tag = TagFromObject(o);
1647 JDWP::SetObjectId(buf+1, gRegistry->Add(o));
1648 }
1649 break;
1650 case JDWP::JT_DOUBLE:
1651 case JDWP::JT_LONG:
1652 {
Elliott Hughescccd84f2011-12-05 16:51:54 -08001653 CHECK_EQ(width, 8U);
Elliott Hughes1bba14f2011-12-01 18:00:36 -08001654 uint32_t lo = f.GetVReg(m, reg);
1655 uint64_t hi = f.GetVReg(m, reg + 1);
1656 uint64_t longVal = (hi << 32) | lo;
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001657 VLOG(jdwp) << "get double/long local " << hi << ":" << lo << " = " << longVal;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001658 JDWP::Set8BE(buf+1, longVal);
1659 }
1660 break;
1661 default:
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001662 LOG(FATAL) << "Unknown tag " << tag;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001663 break;
1664 }
1665
1666 // Prepend tag, which may have been updated.
1667 JDWP::Set1(buf, tag);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001668}
1669
Elliott Hughesdbb40792011-11-18 17:05:22 -08001670void 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 -08001671 Method** sp = reinterpret_cast<Method**>(frameId);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001672 Frame f(sp);
Elliott Hughescccd84f2011-12-05 16:51:54 -08001673 Method* m = f.GetMethod();
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001674 uint16_t reg = DemangleSlot(slot, m);
Elliott Hughescccd84f2011-12-05 16:51:54 -08001675
1676 const VmapTable vmap_table(m->GetVmapTableRaw());
1677 uint32_t vmap_offset;
1678 if (vmap_table.IsInContext(reg, vmap_offset)) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001679 UNIMPLEMENTED(FATAL) << "Don't know how to pull locals from callee save frames: " << vmap_offset;
Elliott Hughescccd84f2011-12-05 16:51:54 -08001680 }
1681
Elliott Hughesad3da692012-02-24 16:51:35 -08001682 // TODO: check that the tag is compatible with the actual type of the slot!
1683
Elliott Hughescccd84f2011-12-05 16:51:54 -08001684 switch (tag) {
1685 case JDWP::JT_BOOLEAN:
1686 case JDWP::JT_BYTE:
1687 CHECK_EQ(width, 1U);
1688 f.SetVReg(m, reg, static_cast<uint32_t>(value));
1689 break;
1690 case JDWP::JT_SHORT:
1691 case JDWP::JT_CHAR:
1692 CHECK_EQ(width, 2U);
1693 f.SetVReg(m, reg, static_cast<uint32_t>(value));
1694 break;
1695 case JDWP::JT_INT:
1696 case JDWP::JT_FLOAT:
1697 CHECK_EQ(width, 4U);
1698 f.SetVReg(m, reg, static_cast<uint32_t>(value));
1699 break;
1700 case JDWP::JT_ARRAY:
1701 case JDWP::JT_OBJECT:
1702 case JDWP::JT_STRING:
1703 {
1704 CHECK_EQ(width, sizeof(JDWP::ObjectId));
1705 Object* o = gRegistry->Get<Object*>(static_cast<JDWP::ObjectId>(value));
Elliott Hughesad3da692012-02-24 16:51:35 -08001706 if (o == kInvalidObject) {
1707 UNIMPLEMENTED(FATAL) << "return an error code when given an invalid object to store";
1708 }
Elliott Hughescccd84f2011-12-05 16:51:54 -08001709 f.SetVReg(m, reg, static_cast<uint32_t>(reinterpret_cast<uintptr_t>(o)));
1710 }
1711 break;
1712 case JDWP::JT_DOUBLE:
1713 case JDWP::JT_LONG:
1714 CHECK_EQ(width, 8U);
1715 f.SetVReg(m, reg, static_cast<uint32_t>(value));
1716 f.SetVReg(m, reg + 1, static_cast<uint32_t>(value >> 32));
1717 break;
1718 default:
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001719 LOG(FATAL) << "Unknown tag " << tag;
Elliott Hughescccd84f2011-12-05 16:51:54 -08001720 break;
1721 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001722}
1723
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001724void Dbg::PostLocationEvent(const Method* m, int dex_pc, Object* this_object, int event_flags) {
1725 Class* c = m->GetDeclaringClass();
1726
1727 JDWP::JdwpLocation location;
1728 location.typeTag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
1729 location.classId = gRegistry->Add(c);
1730 location.methodId = ToMethodId(m);
Elliott Hughes972a47b2012-02-21 18:16:06 -08001731 location.dex_pc = m->IsNative() ? -1 : dex_pc;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001732
1733 // Note we use "NoReg" so we don't keep track of references that are
1734 // never actually sent to the debugger. 'this_id' is only used to
1735 // compare against registered events...
1736 JDWP::ObjectId this_id = static_cast<JDWP::ObjectId>(reinterpret_cast<uintptr_t>(this_object));
1737 if (gJdwpState->PostLocationEvent(&location, this_id, event_flags)) {
1738 // ...unless there's a registered event, in which case we
1739 // need to really track the class and 'this'.
1740 gRegistry->Add(c);
1741 gRegistry->Add(this_object);
1742 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001743}
1744
Elliott Hughesd07986f2011-12-06 18:27:45 -08001745void Dbg::PostException(Method** sp, Method* throwMethod, uintptr_t throwNativePc, Method* catchMethod, uintptr_t catchNativePc, Object* exception) {
Ian Rogers0ad5bb82011-12-07 10:16:32 -08001746 if (!gDebuggerActive) {
1747 return;
1748 }
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001749
Elliott Hughesd07986f2011-12-06 18:27:45 -08001750 JDWP::JdwpLocation throw_location;
1751 SetLocation(throw_location, throwMethod, throwNativePc);
1752 JDWP::JdwpLocation catch_location;
1753 SetLocation(catch_location, catchMethod, catchNativePc);
1754
1755 // We need 'this' for InstanceOnly filters.
1756 JDWP::ObjectId this_id;
1757 GetThisObject(reinterpret_cast<JDWP::FrameId>(sp), &this_id);
1758
1759 /*
1760 * Hand the event to the JDWP exception handler. Note we're using the
1761 * "NoReg" objectID on the exception, which is not strictly correct --
1762 * the exception object WILL be passed up to the debugger if the
1763 * debugger is interested in the event. We do this because the current
1764 * implementation of the debugger object registry never throws anything
1765 * away, and some people were experiencing a fatal build up of exception
1766 * objects when dealing with certain libraries.
1767 */
1768 JDWP::ObjectId exception_id = static_cast<JDWP::ObjectId>(reinterpret_cast<uintptr_t>(exception));
1769 JDWP::RefTypeId exception_class_id = gRegistry->Add(exception->GetClass());
1770
1771 gJdwpState->PostException(&throw_location, exception_id, exception_class_id, &catch_location, this_id);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001772}
1773
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001774void Dbg::PostClassPrepare(Class* c) {
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001775 if (!gDebuggerActive) {
1776 return;
1777 }
1778
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001779 // OLD-TODO - we currently always send both "verified" and "prepared" since
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001780 // debuggers seem to like that. There might be some advantage to honesty,
1781 // since the class may not yet be verified.
1782 int state = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
1783 JDWP::JdwpTypeTag tag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
1784 gJdwpState->PostClassPrepare(tag, gRegistry->Add(c), ClassHelper(c).GetDescriptor(), state);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001785}
1786
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001787void Dbg::UpdateDebugger(int32_t dex_pc, Thread* self, Method** sp) {
Elliott Hughes2aa2e392012-02-17 17:15:43 -08001788 if (!gDebuggerActive || dex_pc == -2 /* fake method exit */) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001789 return;
1790 }
1791
Elliott Hughes86964332012-02-15 19:37:42 -08001792 Frame f(sp);
1793 f.Next(); // Skip callee save frame.
1794 Method* m = f.GetMethod();
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001795
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001796 if (dex_pc == -1) {
Elliott Hughes2aa2e392012-02-17 17:15:43 -08001797 // We use a pc of -1 to represent method entry, since we might branch back to pc 0 later.
1798 // This means that for this special notification, there can't be anything else interesting
1799 // going on, so we're done already.
1800 Dbg::PostLocationEvent(m, 0, GetThis(f), kMethodEntry);
1801 return;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001802 }
1803
Elliott Hughes2aa2e392012-02-17 17:15:43 -08001804 int event_flags = 0;
1805
Elliott Hughes86964332012-02-15 19:37:42 -08001806 if (IsBreakpoint(m, dex_pc)) {
1807 event_flags |= kBreakpoint;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001808 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001809
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001810 // If the debugger is single-stepping one of our threads, check to
1811 // see if we're that thread and we've reached a step point.
Elliott Hughes86964332012-02-15 19:37:42 -08001812 if (gSingleStepControl.is_active && gSingleStepControl.thread == self) {
1813 CHECK(!m->IsNative());
1814 if (gSingleStepControl.step_depth == JDWP::SD_INTO) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001815 // Step into method calls. We break when the line number
1816 // or method pointer changes. If we're in SS_MIN mode, we
1817 // always stop.
Elliott Hughes86964332012-02-15 19:37:42 -08001818 if (gSingleStepControl.method != m) {
1819 event_flags |= kSingleStep;
1820 VLOG(jdwp) << "SS new method";
1821 } else if (gSingleStepControl.step_size == JDWP::SS_MIN) {
1822 event_flags |= kSingleStep;
1823 VLOG(jdwp) << "SS new instruction";
Elliott Hughes2435a572012-02-17 16:07:41 -08001824 } else if (gSingleStepControl.dex_pcs.find(dex_pc) == gSingleStepControl.dex_pcs.end()) {
1825 event_flags |= kSingleStep;
1826 VLOG(jdwp) << "SS new line";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001827 }
Elliott Hughes86964332012-02-15 19:37:42 -08001828 } else if (gSingleStepControl.step_depth == JDWP::SD_OVER) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001829 // Step over method calls. We break when the line number is
1830 // different and the frame depth is <= the original frame
1831 // depth. (We can't just compare on the method, because we
1832 // might get unrolled past it by an exception, and it's tricky
1833 // to identify recursion.)
Elliott Hughes86964332012-02-15 19:37:42 -08001834
1835 // TODO: can we just use the value of 'sp'?
1836 int stack_depth = GetStackDepth(self);
1837
1838 if (stack_depth < gSingleStepControl.stack_depth) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001839 // popped up one or more frames, always trigger
Elliott Hughes86964332012-02-15 19:37:42 -08001840 event_flags |= kSingleStep;
1841 VLOG(jdwp) << "SS method pop";
1842 } else if (stack_depth == gSingleStepControl.stack_depth) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001843 // same depth, see if we moved
Elliott Hughes86964332012-02-15 19:37:42 -08001844 if (gSingleStepControl.step_size == JDWP::SS_MIN) {
1845 event_flags |= kSingleStep;
1846 VLOG(jdwp) << "SS new instruction";
Elliott Hughes2435a572012-02-17 16:07:41 -08001847 } else if (gSingleStepControl.dex_pcs.find(dex_pc) == gSingleStepControl.dex_pcs.end()) {
1848 event_flags |= kSingleStep;
1849 VLOG(jdwp) << "SS new line";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001850 }
1851 }
1852 } else {
Elliott Hughes86964332012-02-15 19:37:42 -08001853 CHECK_EQ(gSingleStepControl.step_depth, JDWP::SD_OUT);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001854 // Return from the current method. We break when the frame
1855 // depth pops up.
1856
1857 // This differs from the "method exit" break in that it stops
1858 // with the PC at the next instruction in the returned-to
1859 // function, rather than the end of the returning function.
Elliott Hughes86964332012-02-15 19:37:42 -08001860
1861 // TODO: can we just use the value of 'sp'?
1862 int stack_depth = GetStackDepth(self);
1863 if (stack_depth < gSingleStepControl.stack_depth) {
1864 event_flags |= kSingleStep;
1865 VLOG(jdwp) << "SS method pop";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001866 }
1867 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001868 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001869
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001870 // Check to see if this is a "return" instruction. JDWP says we should
1871 // send the event *after* the code has been executed, but it also says
1872 // the location we provide is the last instruction. Since the "return"
1873 // instruction has no interesting side effects, we should be safe.
1874 // (We can't just move this down to the returnFromMethod label because
1875 // we potentially need to combine it with other events.)
1876 // We're also not supposed to generate a method exit event if the method
1877 // terminates "with a thrown exception".
Elliott Hughes86964332012-02-15 19:37:42 -08001878 if (dex_pc >= 0) {
1879 const DexFile::CodeItem* code_item = MethodHelper(m).GetCodeItem();
1880 CHECK(code_item != NULL);
1881 CHECK_LT(dex_pc, static_cast<int32_t>(code_item->insns_size_in_code_units_));
1882 if (Instruction::At(&code_item->insns_[dex_pc])->IsReturn()) {
1883 event_flags |= kMethodExit;
1884 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001885 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001886
1887 // If there's something interesting going on, see if it matches one
1888 // of the debugger filters.
1889 if (event_flags != 0) {
Elliott Hughes86964332012-02-15 19:37:42 -08001890 Dbg::PostLocationEvent(m, dex_pc, GetThis(f), event_flags);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001891 }
1892}
1893
Elliott Hughes86964332012-02-15 19:37:42 -08001894void Dbg::WatchLocation(const JDWP::JdwpLocation* location) {
1895 MutexLock mu(gBreakpointsLock);
1896 Method* m = FromMethodId(location->methodId);
Elliott Hughes972a47b2012-02-21 18:16:06 -08001897 gBreakpoints.push_back(Breakpoint(m, location->dex_pc));
Elliott Hughes86964332012-02-15 19:37:42 -08001898 VLOG(jdwp) << "Set breakpoint #" << (gBreakpoints.size() - 1) << ": " << gBreakpoints[gBreakpoints.size() - 1];
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001899}
1900
Elliott Hughes86964332012-02-15 19:37:42 -08001901void Dbg::UnwatchLocation(const JDWP::JdwpLocation* location) {
1902 MutexLock mu(gBreakpointsLock);
1903 Method* m = FromMethodId(location->methodId);
1904 for (size_t i = 0; i < gBreakpoints.size(); ++i) {
Elliott Hughes972a47b2012-02-21 18:16:06 -08001905 if (gBreakpoints[i].method == m && gBreakpoints[i].dex_pc == location->dex_pc) {
Elliott Hughes86964332012-02-15 19:37:42 -08001906 VLOG(jdwp) << "Removed breakpoint #" << i << ": " << gBreakpoints[i];
1907 gBreakpoints.erase(gBreakpoints.begin() + i);
1908 return;
1909 }
1910 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001911}
1912
Elliott Hughes2435a572012-02-17 16:07:41 -08001913JDWP::JdwpError Dbg::ConfigureStep(JDWP::ObjectId threadId, JDWP::JdwpStepSize step_size, JDWP::JdwpStepDepth step_depth) {
Elliott Hughes86964332012-02-15 19:37:42 -08001914 Thread* thread = DecodeThread(threadId);
Elliott Hughes2435a572012-02-17 16:07:41 -08001915 if (thread == NULL) {
1916 return JDWP::ERR_INVALID_THREAD;
1917 }
Elliott Hughes86964332012-02-15 19:37:42 -08001918
1919 // TODO: there's no theoretical reason why we couldn't support single-stepping
1920 // of multiple threads at once, but we never did so historically.
1921 if (gSingleStepControl.thread != NULL && thread != gSingleStepControl.thread) {
1922 LOG(WARNING) << "single-step already active for " << *gSingleStepControl.thread
1923 << "; switching to " << *thread;
1924 }
1925
Elliott Hughes2435a572012-02-17 16:07:41 -08001926 //
1927 // Work out what Method* we're in, the current line number, and how deep the stack currently
1928 // is for step-out.
1929 //
1930
Elliott Hughes86964332012-02-15 19:37:42 -08001931 struct SingleStepStackVisitor : public Thread::StackVisitor {
1932 SingleStepStackVisitor() {
1933 gSingleStepControl.method = NULL;
1934 gSingleStepControl.stack_depth = 0;
1935 }
Elliott Hughes530fa002012-03-12 11:44:49 -07001936 bool VisitFrame(const Frame& f, uintptr_t pc) {
Elliott Hughes86964332012-02-15 19:37:42 -08001937 if (f.HasMethod()) {
1938 ++gSingleStepControl.stack_depth;
1939 if (gSingleStepControl.method == NULL) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001940 const Method* m = f.GetMethod();
1941 const DexCache* dex_cache = m->GetDeclaringClass()->GetDexCache();
1942 gSingleStepControl.method = m;
1943 gSingleStepControl.line_number = -1;
1944 if (dex_cache != NULL) {
1945 const DexFile& dex_file = Runtime::Current()->GetClassLinker()->FindDexFile(dex_cache);
1946 gSingleStepControl.line_number = dex_file.GetLineNumFromPC(m, m->ToDexPC(pc));
1947 }
Elliott Hughes86964332012-02-15 19:37:42 -08001948 }
1949 }
Elliott Hughes530fa002012-03-12 11:44:49 -07001950 return true;
Elliott Hughes86964332012-02-15 19:37:42 -08001951 }
1952 };
1953 SingleStepStackVisitor visitor;
1954 thread->WalkStack(&visitor);
1955
Elliott Hughes2435a572012-02-17 16:07:41 -08001956 //
1957 // Find the dex_pc values that correspond to the current line, for line-based single-stepping.
1958 //
1959
1960 struct DebugCallbackContext {
1961 DebugCallbackContext() {
1962 last_pc_valid = false;
1963 last_pc = 0;
Elliott Hughes2435a572012-02-17 16:07:41 -08001964 }
1965
1966 static bool Callback(void* raw_context, uint32_t address, uint32_t line_number) {
1967 DebugCallbackContext* context = reinterpret_cast<DebugCallbackContext*>(raw_context);
1968 if (static_cast<int32_t>(line_number) == gSingleStepControl.line_number) {
1969 if (!context->last_pc_valid) {
1970 // Everything from this address until the next line change is ours.
1971 context->last_pc = address;
1972 context->last_pc_valid = true;
1973 }
1974 // Otherwise, if we're already in a valid range for this line,
1975 // just keep going (shouldn't really happen)...
1976 } else if (context->last_pc_valid) { // and the line number is new
1977 // Add everything from the last entry up until here to the set
1978 for (uint32_t dex_pc = context->last_pc; dex_pc < address; ++dex_pc) {
1979 gSingleStepControl.dex_pcs.insert(dex_pc);
1980 }
1981 context->last_pc_valid = false;
1982 }
1983 return false; // There may be multiple entries for any given line.
1984 }
1985
1986 ~DebugCallbackContext() {
1987 // If the line number was the last in the position table...
1988 if (last_pc_valid) {
1989 size_t end = MethodHelper(gSingleStepControl.method).GetCodeItem()->insns_size_in_code_units_;
1990 for (uint32_t dex_pc = last_pc; dex_pc < end; ++dex_pc) {
1991 gSingleStepControl.dex_pcs.insert(dex_pc);
1992 }
1993 }
1994 }
1995
1996 bool last_pc_valid;
1997 uint32_t last_pc;
1998 };
Elliott Hughes3e2e1a22012-02-21 11:33:41 -08001999 gSingleStepControl.dex_pcs.clear();
Elliott Hughes2435a572012-02-17 16:07:41 -08002000 const Method* m = gSingleStepControl.method;
Elliott Hughes3e2e1a22012-02-21 11:33:41 -08002001 if (m->IsNative()) {
2002 gSingleStepControl.line_number = -1;
2003 } else {
2004 DebugCallbackContext context;
2005 MethodHelper mh(m);
2006 mh.GetDexFile().DecodeDebugInfo(mh.GetCodeItem(), m->IsStatic(), m->GetDexMethodIndex(),
2007 DebugCallbackContext::Callback, NULL, &context);
2008 }
Elliott Hughes2435a572012-02-17 16:07:41 -08002009
2010 //
2011 // Everything else...
2012 //
2013
Elliott Hughes86964332012-02-15 19:37:42 -08002014 gSingleStepControl.thread = thread;
2015 gSingleStepControl.step_size = step_size;
2016 gSingleStepControl.step_depth = step_depth;
2017 gSingleStepControl.is_active = true;
2018
Elliott Hughes2435a572012-02-17 16:07:41 -08002019 if (VLOG_IS_ON(jdwp)) {
2020 VLOG(jdwp) << "Single-step thread: " << *gSingleStepControl.thread;
2021 VLOG(jdwp) << "Single-step step size: " << gSingleStepControl.step_size;
2022 VLOG(jdwp) << "Single-step step depth: " << gSingleStepControl.step_depth;
2023 VLOG(jdwp) << "Single-step current method: " << PrettyMethod(gSingleStepControl.method);
2024 VLOG(jdwp) << "Single-step current line: " << gSingleStepControl.line_number;
2025 VLOG(jdwp) << "Single-step current stack depth: " << gSingleStepControl.stack_depth;
2026 VLOG(jdwp) << "Single-step dex_pc values:";
2027 for (std::set<uint32_t>::iterator it = gSingleStepControl.dex_pcs.begin() ; it != gSingleStepControl.dex_pcs.end(); ++it) {
Elliott Hughes229feb72012-02-23 13:33:29 -08002028 VLOG(jdwp) << StringPrintf(" %#x", *it);
Elliott Hughes2435a572012-02-17 16:07:41 -08002029 }
2030 }
2031
2032 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002033}
2034
2035void Dbg::UnconfigureStep(JDWP::ObjectId threadId) {
Elliott Hughes86964332012-02-15 19:37:42 -08002036 gSingleStepControl.is_active = false;
2037 gSingleStepControl.thread = NULL;
Elliott Hughes2435a572012-02-17 16:07:41 -08002038 gSingleStepControl.dex_pcs.clear();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002039}
2040
Elliott Hughes45651fd2012-02-21 15:48:20 -08002041static char JdwpTagToShortyChar(JDWP::JdwpTag tag) {
2042 switch (tag) {
2043 default:
2044 LOG(FATAL) << "unknown JDWP tag: " << PrintableChar(tag);
2045
2046 // Primitives.
2047 case JDWP::JT_BYTE: return 'B';
2048 case JDWP::JT_CHAR: return 'C';
2049 case JDWP::JT_FLOAT: return 'F';
2050 case JDWP::JT_DOUBLE: return 'D';
2051 case JDWP::JT_INT: return 'I';
2052 case JDWP::JT_LONG: return 'J';
2053 case JDWP::JT_SHORT: return 'S';
2054 case JDWP::JT_VOID: return 'V';
2055 case JDWP::JT_BOOLEAN: return 'Z';
2056
2057 // Reference types.
2058 case JDWP::JT_ARRAY:
2059 case JDWP::JT_OBJECT:
2060 case JDWP::JT_STRING:
2061 case JDWP::JT_THREAD:
2062 case JDWP::JT_THREAD_GROUP:
2063 case JDWP::JT_CLASS_LOADER:
2064 case JDWP::JT_CLASS_OBJECT:
2065 return 'L';
2066 }
2067}
2068
2069JDWP::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 -08002070 ThreadList* thread_list = Runtime::Current()->GetThreadList();
2071
2072 Thread* targetThread = NULL;
2073 DebugInvokeReq* req = NULL;
2074 {
2075 ScopedThreadListLock thread_list_lock;
2076 targetThread = DecodeThread(threadId);
2077 if (targetThread == NULL) {
2078 LOG(ERROR) << "InvokeMethod request for non-existent thread " << threadId;
2079 return JDWP::ERR_INVALID_THREAD;
2080 }
2081 req = targetThread->GetInvokeReq();
2082 if (!req->ready) {
2083 LOG(ERROR) << "InvokeMethod request for thread not stopped by event: " << *targetThread;
2084 return JDWP::ERR_INVALID_THREAD;
2085 }
2086
2087 /*
2088 * We currently have a bug where we don't successfully resume the
2089 * target thread if the suspend count is too deep. We're expected to
2090 * require one "resume" for each "suspend", but when asked to execute
2091 * a method we have to resume fully and then re-suspend it back to the
2092 * same level. (The easiest way to cause this is to type "suspend"
2093 * multiple times in jdb.)
2094 *
2095 * It's unclear what this means when the event specifies "resume all"
2096 * and some threads are suspended more deeply than others. This is
2097 * a rare problem, so for now we just prevent it from hanging forever
2098 * by rejecting the method invocation request. Without this, we will
2099 * be stuck waiting on a suspended thread.
2100 */
2101 int suspend_count = targetThread->GetSuspendCount();
2102 if (suspend_count > 1) {
2103 LOG(ERROR) << *targetThread << " suspend count too deep for method invocation: " << suspend_count;
2104 return JDWP::ERR_THREAD_SUSPENDED; // Probably not expected here.
2105 }
2106
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002107 JDWP::JdwpError status;
Elliott Hughes45651fd2012-02-21 15:48:20 -08002108 Object* receiver = gRegistry->Get<Object*>(objectId);
2109 if (receiver == kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002110 return JDWP::ERR_INVALID_OBJECT;
2111 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002112
2113 Object* thread = gRegistry->Get<Object*>(threadId);
2114 if (thread == kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002115 return JDWP::ERR_INVALID_OBJECT;
2116 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002117 // TODO: check that 'thread' is actually a java.lang.Thread!
2118
2119 Class* c = DecodeClass(classId, status);
2120 if (c == NULL) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002121 return status;
2122 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002123
2124 Method* m = FromMethodId(methodId);
2125 if (m->IsStatic() != (receiver == NULL)) {
2126 return JDWP::ERR_INVALID_METHODID;
2127 }
2128 if (m->IsStatic()) {
2129 if (m->GetDeclaringClass() != c) {
2130 return JDWP::ERR_INVALID_METHODID;
2131 }
2132 } else {
2133 if (!m->GetDeclaringClass()->IsAssignableFrom(c)) {
2134 return JDWP::ERR_INVALID_METHODID;
2135 }
2136 }
2137
2138 // Check the argument list matches the method.
2139 MethodHelper mh(m);
2140 if (mh.GetShortyLength() - 1 != arg_count) {
2141 return JDWP::ERR_ILLEGAL_ARGUMENT;
2142 }
2143 const char* shorty = mh.GetShorty();
2144 for (size_t i = 0; i < arg_count; ++i) {
2145 if (shorty[i + 1] != JdwpTagToShortyChar(arg_types[i])) {
2146 return JDWP::ERR_ILLEGAL_ARGUMENT;
2147 }
2148 }
2149
2150 req->receiver_ = receiver;
2151 req->thread_ = thread;
2152 req->class_ = c;
2153 req->method_ = m;
2154 req->arg_count_ = arg_count;
2155 req->arg_values_ = arg_values;
Elliott Hughesd07986f2011-12-06 18:27:45 -08002156 req->options_ = options;
2157 req->invoke_needed_ = true;
2158 }
2159
2160 // The fact that we've released the thread list lock is a bit risky --- if the thread goes
2161 // away we're sitting high and dry -- but we must release this before the ResumeAllThreads
2162 // call, and it's unwise to hold it during WaitForSuspend.
2163
2164 {
2165 /*
2166 * We change our (JDWP thread) status, which should be THREAD_RUNNING,
2167 * so the VM can suspend for a GC if the invoke request causes us to
2168 * run out of memory. It's also a good idea to change it before locking
2169 * the invokeReq mutex, although that should never be held for long.
2170 */
2171 ScopedThreadStateChange tsc(Thread::Current(), Thread::kVmWait);
2172
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002173 VLOG(jdwp) << " Transferring control to event thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002174 {
2175 MutexLock mu(req->lock_);
2176
2177 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002178 VLOG(jdwp) << " Resuming all threads";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002179 thread_list->ResumeAll(true);
2180 } else {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002181 VLOG(jdwp) << " Resuming event thread only";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002182 thread_list->Resume(targetThread, true);
2183 }
2184
2185 // Wait for the request to finish executing.
2186 while (req->invoke_needed_) {
2187 req->cond_.Wait(req->lock_);
2188 }
2189 }
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002190 VLOG(jdwp) << " Control has returned from event thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002191
2192 /* wait for thread to re-suspend itself */
2193 targetThread->WaitUntilSuspended();
2194 //dvmWaitForSuspend(targetThread);
2195 }
2196
2197 /*
2198 * Suspend the threads. We waited for the target thread to suspend
2199 * itself, so all we need to do is suspend the others.
2200 *
2201 * The suspendAllThreads() call will double-suspend the event thread,
2202 * so we want to resume the target thread once to keep the books straight.
2203 */
2204 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002205 VLOG(jdwp) << " Suspending all threads";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002206 thread_list->SuspendAll(true);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002207 VLOG(jdwp) << " Resuming event thread to balance the count";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002208 thread_list->Resume(targetThread, true);
2209 }
2210
2211 // Copy the result.
2212 *pResultTag = req->result_tag;
2213 if (IsPrimitiveTag(req->result_tag)) {
2214 *pResultValue = req->result_value.j;
2215 } else {
2216 *pResultValue = gRegistry->Add(req->result_value.l);
2217 }
2218 *pExceptionId = req->exception;
2219 return req->error;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002220}
2221
2222void Dbg::ExecuteMethod(DebugInvokeReq* pReq) {
Elliott Hughesd07986f2011-12-06 18:27:45 -08002223 Thread* self = Thread::Current();
2224
2225 // We can be called while an exception is pending in the VM. We need
2226 // to preserve that across the method invocation.
2227 SirtRef<Throwable> old_exception(self->GetException());
2228 self->ClearException();
2229
2230 ScopedThreadStateChange tsc(self, Thread::kRunnable);
2231
2232 // Translate the method through the vtable, unless the debugger wants to suppress it.
2233 Method* m = pReq->method_;
2234 if ((pReq->options_ & JDWP::INVOKE_NONVIRTUAL) == 0 && pReq->receiver_ != NULL) {
Elliott Hughes45651fd2012-02-21 15:48:20 -08002235 Method* actual_method = pReq->class_->FindVirtualMethodForVirtualOrInterface(pReq->method_);
2236 if (actual_method != m) {
2237 VLOG(jdwp) << "ExecuteMethod translated " << PrettyMethod(m) << " to " << PrettyMethod(actual_method);
2238 m = actual_method;
2239 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08002240 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002241 VLOG(jdwp) << "ExecuteMethod " << PrettyMethod(m);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002242 CHECK(m != NULL);
2243
2244 CHECK_EQ(sizeof(jvalue), sizeof(uint64_t));
2245
Elliott Hughes45651fd2012-02-21 15:48:20 -08002246 LOG(INFO) << "self=" << self << " pReq->receiver_=" << pReq->receiver_ << " m=" << m << " #" << pReq->arg_count_ << " " << pReq->arg_values_;
2247 pReq->result_value = InvokeWithJValues(self, pReq->receiver_, m, reinterpret_cast<JValue*>(pReq->arg_values_));
Elliott Hughesd07986f2011-12-06 18:27:45 -08002248
2249 pReq->exception = gRegistry->Add(self->GetException());
2250 pReq->result_tag = BasicTagFromDescriptor(MethodHelper(m).GetShorty());
2251 if (pReq->exception != 0) {
2252 Object* exc = self->GetException();
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002253 VLOG(jdwp) << " JDWP invocation returning with exception=" << exc << " " << PrettyTypeOf(exc);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002254 self->ClearException();
2255 pReq->result_value.j = 0;
2256 } else if (pReq->result_tag == JDWP::JT_OBJECT) {
2257 /* if no exception thrown, examine object result more closely */
2258 JDWP::JdwpTag new_tag = TagFromObject(pReq->result_value.l);
2259 if (new_tag != pReq->result_tag) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002260 VLOG(jdwp) << " JDWP promoted result from " << pReq->result_tag << " to " << new_tag;
Elliott Hughesd07986f2011-12-06 18:27:45 -08002261 pReq->result_tag = new_tag;
2262 }
2263
2264 /*
2265 * Register the object. We don't actually need an ObjectId yet,
2266 * but we do need to be sure that the GC won't move or discard the
2267 * object when we switch out of RUNNING. The ObjectId conversion
2268 * will add the object to the "do not touch" list.
2269 *
2270 * We can't use the "tracked allocation" mechanism here because
2271 * the object is going to be handed off to a different thread.
2272 */
2273 gRegistry->Add(pReq->result_value.l);
2274 }
2275
2276 if (old_exception.get() != NULL) {
2277 self->SetException(old_exception.get());
2278 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002279}
2280
Elliott Hughesd07986f2011-12-06 18:27:45 -08002281/*
2282 * Register an object ID that might not have been registered previously.
2283 *
2284 * Normally this wouldn't happen -- the conversion to an ObjectId would
2285 * have added the object to the registry -- but in some cases (e.g.
2286 * throwing exceptions) we really want to do the registration late.
2287 */
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002288void Dbg::RegisterObjectId(JDWP::ObjectId id) {
Elliott Hughesd07986f2011-12-06 18:27:45 -08002289 gRegistry->Add(reinterpret_cast<Object*>(id));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002290}
2291
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002292/*
2293 * "buf" contains a full JDWP packet, possibly with multiple chunks. We
2294 * need to process each, accumulate the replies, and ship the whole thing
2295 * back.
2296 *
2297 * Returns "true" if we have a reply. The reply buffer is newly allocated,
2298 * and includes the chunk type/length, followed by the data.
2299 *
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08002300 * OLD-TODO: we currently assume that the request and reply include a single
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002301 * chunk. If this becomes inconvenient we will need to adapt.
2302 */
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002303bool Dbg::DdmHandlePacket(const uint8_t* buf, int dataLen, uint8_t** pReplyBuf, int* pReplyLen) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002304 CHECK_GE(dataLen, 0);
2305
2306 Thread* self = Thread::Current();
2307 JNIEnv* env = self->GetJniEnv();
2308
Elliott Hughes844f9a02012-01-24 20:19:58 -08002309 static jclass Chunk_class = CacheClass(env, "org/apache/harmony/dalvik/ddmc/Chunk");
2310 static jclass DdmServer_class = CacheClass(env, "org/apache/harmony/dalvik/ddmc/DdmServer");
2311 static jmethodID dispatch_mid = env->GetStaticMethodID(DdmServer_class, "dispatch", "(I[BII)Lorg/apache/harmony/dalvik/ddmc/Chunk;");
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002312 static jfieldID data_fid = env->GetFieldID(Chunk_class, "data", "[B");
2313 static jfieldID length_fid = env->GetFieldID(Chunk_class, "length", "I");
2314 static jfieldID offset_fid = env->GetFieldID(Chunk_class, "offset", "I");
2315 static jfieldID type_fid = env->GetFieldID(Chunk_class, "type", "I");
2316
2317 // Create a byte[] corresponding to 'buf'.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002318 ScopedLocalRef<jbyteArray> dataArray(env, env->NewByteArray(dataLen));
2319 if (dataArray.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002320 LOG(WARNING) << "byte[] allocation failed: " << dataLen;
2321 env->ExceptionClear();
2322 return false;
2323 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002324 env->SetByteArrayRegion(dataArray.get(), 0, dataLen, reinterpret_cast<const jbyte*>(buf));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002325
2326 const int kChunkHdrLen = 8;
2327
2328 // Run through and find all chunks. [Currently just find the first.]
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002329 ScopedByteArrayRO contents(env, dataArray.get());
Elliott Hughesf7c3b662011-10-27 12:04:56 -07002330 jint type = JDWP::Get4BE(reinterpret_cast<const uint8_t*>(&contents[0]));
2331 jint length = JDWP::Get4BE(reinterpret_cast<const uint8_t*>(&contents[4]));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002332 jint offset = kChunkHdrLen;
2333 if (offset + length > dataLen) {
2334 LOG(WARNING) << StringPrintf("bad chunk found (len=%u pktLen=%d)", length, dataLen);
2335 return false;
2336 }
2337
2338 // Call "private static Chunk dispatch(int type, byte[] data, int offset, int length)".
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002339 ScopedLocalRef<jobject> chunk(env, env->CallStaticObjectMethod(DdmServer_class, dispatch_mid, type, dataArray.get(), offset, length));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002340 if (env->ExceptionCheck()) {
2341 LOG(INFO) << StringPrintf("Exception thrown by dispatcher for 0x%08x", type);
2342 env->ExceptionDescribe();
2343 env->ExceptionClear();
2344 return false;
2345 }
2346
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002347 if (chunk.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002348 return false;
2349 }
2350
2351 /*
2352 * Pull the pieces out of the chunk. We copy the results into a
2353 * newly-allocated buffer that the caller can free. We don't want to
2354 * continue using the Chunk object because nothing has a reference to it.
2355 *
2356 * We could avoid this by returning type/data/offset/length and having
2357 * the caller be aware of the object lifetime issues, but that
2358 * integrates the JDWP code more tightly into the VM, and doesn't work
2359 * if we have responses for multiple chunks.
2360 *
2361 * So we're pretty much stuck with copying data around multiple times.
2362 */
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002363 ScopedLocalRef<jbyteArray> replyData(env, reinterpret_cast<jbyteArray>(env->GetObjectField(chunk.get(), data_fid)));
2364 length = env->GetIntField(chunk.get(), length_fid);
2365 offset = env->GetIntField(chunk.get(), offset_fid);
2366 type = env->GetIntField(chunk.get(), type_fid);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002367
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002368 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 -07002369 if (length == 0 || replyData.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002370 return false;
2371 }
2372
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002373 jsize replyLength = env->GetArrayLength(replyData.get());
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002374 if (offset + length > replyLength) {
2375 LOG(WARNING) << StringPrintf("chunk off=%d len=%d exceeds reply array len %d", offset, length, replyLength);
2376 return false;
2377 }
2378
2379 uint8_t* reply = new uint8_t[length + kChunkHdrLen];
2380 if (reply == NULL) {
2381 LOG(WARNING) << "malloc failed: " << (length + kChunkHdrLen);
2382 return false;
2383 }
Elliott Hughesf7c3b662011-10-27 12:04:56 -07002384 JDWP::Set4BE(reply + 0, type);
2385 JDWP::Set4BE(reply + 4, length);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002386 env->GetByteArrayRegion(replyData.get(), offset, length, reinterpret_cast<jbyte*>(reply + kChunkHdrLen));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002387
2388 *pReplyBuf = reply;
2389 *pReplyLen = length + kChunkHdrLen;
2390
Elliott Hughesba8eee12012-01-24 20:25:24 -08002391 VLOG(jdwp) << StringPrintf("dvmHandleDdm returning type=%.4s buf=%p len=%d", reinterpret_cast<char*>(reply), reply, length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002392 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002393}
2394
Elliott Hughesa2155262011-11-16 16:26:58 -08002395void Dbg::DdmBroadcast(bool connect) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002396 VLOG(jdwp) << "Broadcasting DDM " << (connect ? "connect" : "disconnect") << "...";
Elliott Hughes47fce012011-10-25 18:37:19 -07002397
2398 Thread* self = Thread::Current();
2399 if (self->GetState() != Thread::kRunnable) {
2400 LOG(ERROR) << "DDM broadcast in thread state " << self->GetState();
2401 /* try anyway? */
2402 }
2403
2404 JNIEnv* env = self->GetJniEnv();
Elliott Hughes844f9a02012-01-24 20:19:58 -08002405 static jclass DdmServer_class = CacheClass(env, "org/apache/harmony/dalvik/ddmc/DdmServer");
Elliott Hughes47fce012011-10-25 18:37:19 -07002406 static jmethodID broadcast_mid = env->GetStaticMethodID(DdmServer_class, "broadcast", "(I)V");
2407 jint event = connect ? 1 /*DdmServer.CONNECTED*/ : 2 /*DdmServer.DISCONNECTED*/;
2408 env->CallStaticVoidMethod(DdmServer_class, broadcast_mid, event);
2409 if (env->ExceptionCheck()) {
2410 LOG(ERROR) << "DdmServer.broadcast " << event << " failed";
2411 env->ExceptionDescribe();
2412 env->ExceptionClear();
2413 }
2414}
2415
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002416void Dbg::DdmConnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08002417 Dbg::DdmBroadcast(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002418}
2419
2420void Dbg::DdmDisconnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08002421 Dbg::DdmBroadcast(false);
Elliott Hughes47fce012011-10-25 18:37:19 -07002422 gDdmThreadNotification = false;
2423}
2424
2425/*
Elliott Hughes82188472011-11-07 18:11:48 -08002426 * Send a notification when a thread starts, stops, or changes its name.
Elliott Hughes47fce012011-10-25 18:37:19 -07002427 *
2428 * Because we broadcast the full set of threads when the notifications are
2429 * first enabled, it's possible for "thread" to be actively executing.
2430 */
Elliott Hughes82188472011-11-07 18:11:48 -08002431void Dbg::DdmSendThreadNotification(Thread* t, uint32_t type) {
Elliott Hughes47fce012011-10-25 18:37:19 -07002432 if (!gDdmThreadNotification) {
2433 return;
2434 }
2435
Elliott Hughes82188472011-11-07 18:11:48 -08002436 if (type == CHUNK_TYPE("THDE")) {
Elliott Hughes47fce012011-10-25 18:37:19 -07002437 uint8_t buf[4];
Elliott Hughesf7c3b662011-10-27 12:04:56 -07002438 JDWP::Set4BE(&buf[0], t->GetThinLockId());
Elliott Hughes47fce012011-10-25 18:37:19 -07002439 Dbg::DdmSendChunk(CHUNK_TYPE("THDE"), 4, buf);
Elliott Hughes82188472011-11-07 18:11:48 -08002440 } else {
2441 CHECK(type == CHUNK_TYPE("THCR") || type == CHUNK_TYPE("THNM")) << type;
Elliott Hughes899e7892012-01-24 14:57:32 -08002442 SirtRef<String> name(t->GetThreadName());
Elliott Hughes82188472011-11-07 18:11:48 -08002443 size_t char_count = (name.get() != NULL) ? name->GetLength() : 0;
2444 const jchar* chars = name->GetCharArray()->GetData();
2445
Elliott Hughes21f32d72011-11-09 17:44:13 -08002446 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08002447 JDWP::Append4BE(bytes, t->GetThinLockId());
2448 JDWP::AppendUtf16BE(bytes, chars, char_count);
Elliott Hughes21f32d72011-11-09 17:44:13 -08002449 CHECK_EQ(bytes.size(), char_count*2 + sizeof(uint32_t)*2);
2450 Dbg::DdmSendChunk(type, bytes);
Elliott Hughes47fce012011-10-25 18:37:19 -07002451 }
2452}
2453
Elliott Hughesa2155262011-11-16 16:26:58 -08002454static void DdmSendThreadStartCallback(Thread* t, void*) {
Elliott Hughes82188472011-11-07 18:11:48 -08002455 Dbg::DdmSendThreadNotification(t, CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07002456}
2457
2458void Dbg::DdmSetThreadNotification(bool enable) {
2459 // We lock the thread list to avoid sending duplicate events or missing
2460 // a thread change. We should be okay holding this lock while sending
2461 // the messages out. (We have to hold it while accessing a live thread.)
Elliott Hughesbbd9d832011-11-07 14:40:00 -08002462 ScopedThreadListLock thread_list_lock;
Elliott Hughes47fce012011-10-25 18:37:19 -07002463
2464 gDdmThreadNotification = enable;
2465 if (enable) {
Elliott Hughesbfe487b2011-10-26 15:48:55 -07002466 Runtime::Current()->GetThreadList()->ForEach(DdmSendThreadStartCallback, NULL);
Elliott Hughes47fce012011-10-25 18:37:19 -07002467 }
2468}
2469
Elliott Hughesa2155262011-11-16 16:26:58 -08002470void Dbg::PostThreadStartOrStop(Thread* t, uint32_t type) {
Elliott Hughes47fce012011-10-25 18:37:19 -07002471 if (gDebuggerActive) {
2472 JDWP::ObjectId id = gRegistry->Add(t->GetPeer());
Elliott Hughes82188472011-11-07 18:11:48 -08002473 gJdwpState->PostThreadChange(id, type == CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07002474 }
Elliott Hughes82188472011-11-07 18:11:48 -08002475 Dbg::DdmSendThreadNotification(t, type);
Elliott Hughes47fce012011-10-25 18:37:19 -07002476}
2477
2478void Dbg::PostThreadStart(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08002479 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07002480}
2481
2482void Dbg::PostThreadDeath(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08002483 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THDE"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002484}
2485
Elliott Hughes82188472011-11-07 18:11:48 -08002486void Dbg::DdmSendChunk(uint32_t type, size_t byte_count, const uint8_t* buf) {
Elliott Hughes3bb81562011-10-21 18:52:59 -07002487 CHECK(buf != NULL);
2488 iovec vec[1];
2489 vec[0].iov_base = reinterpret_cast<void*>(const_cast<uint8_t*>(buf));
2490 vec[0].iov_len = byte_count;
2491 Dbg::DdmSendChunkV(type, vec, 1);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002492}
2493
Elliott Hughes21f32d72011-11-09 17:44:13 -08002494void Dbg::DdmSendChunk(uint32_t type, const std::vector<uint8_t>& bytes) {
2495 DdmSendChunk(type, bytes.size(), &bytes[0]);
2496}
2497
Elliott Hughescccd84f2011-12-05 16:51:54 -08002498void Dbg::DdmSendChunkV(uint32_t type, const struct iovec* iov, int iov_count) {
Elliott Hughes3bb81562011-10-21 18:52:59 -07002499 if (gJdwpState == NULL) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002500 VLOG(jdwp) << "Debugger thread not active, ignoring DDM send: " << type;
Elliott Hughes3bb81562011-10-21 18:52:59 -07002501 } else {
Elliott Hughescccd84f2011-12-05 16:51:54 -08002502 gJdwpState->DdmSendChunkV(type, iov, iov_count);
Elliott Hughes3bb81562011-10-21 18:52:59 -07002503 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002504}
2505
Elliott Hughes767a1472011-10-26 18:49:02 -07002506int Dbg::DdmHandleHpifChunk(HpifWhen when) {
2507 if (when == HPIF_WHEN_NOW) {
Elliott Hughes7162ad92011-10-27 14:08:42 -07002508 DdmSendHeapInfo(when);
Elliott Hughes767a1472011-10-26 18:49:02 -07002509 return true;
2510 }
2511
2512 if (when != HPIF_WHEN_NEVER && when != HPIF_WHEN_NEXT_GC && when != HPIF_WHEN_EVERY_GC) {
2513 LOG(ERROR) << "invalid HpifWhen value: " << static_cast<int>(when);
2514 return false;
2515 }
2516
2517 gDdmHpifWhen = when;
2518 return true;
2519}
2520
2521bool Dbg::DdmHandleHpsgNhsgChunk(Dbg::HpsgWhen when, Dbg::HpsgWhat what, bool native) {
2522 if (when != HPSG_WHEN_NEVER && when != HPSG_WHEN_EVERY_GC) {
2523 LOG(ERROR) << "invalid HpsgWhen value: " << static_cast<int>(when);
2524 return false;
2525 }
2526
2527 if (what != HPSG_WHAT_MERGED_OBJECTS && what != HPSG_WHAT_DISTINCT_OBJECTS) {
2528 LOG(ERROR) << "invalid HpsgWhat value: " << static_cast<int>(what);
2529 return false;
2530 }
2531
2532 if (native) {
2533 gDdmNhsgWhen = when;
2534 gDdmNhsgWhat = what;
2535 } else {
2536 gDdmHpsgWhen = when;
2537 gDdmHpsgWhat = what;
2538 }
2539 return true;
2540}
2541
Elliott Hughes7162ad92011-10-27 14:08:42 -07002542void Dbg::DdmSendHeapInfo(HpifWhen reason) {
2543 // If there's a one-shot 'when', reset it.
2544 if (reason == gDdmHpifWhen) {
2545 if (gDdmHpifWhen == HPIF_WHEN_NEXT_GC) {
2546 gDdmHpifWhen = HPIF_WHEN_NEVER;
2547 }
2548 }
2549
2550 /*
2551 * Chunk HPIF (client --> server)
2552 *
2553 * Heap Info. General information about the heap,
2554 * suitable for a summary display.
2555 *
2556 * [u4]: number of heaps
2557 *
2558 * For each heap:
2559 * [u4]: heap ID
2560 * [u8]: timestamp in ms since Unix epoch
2561 * [u1]: capture reason (same as 'when' value from server)
2562 * [u4]: max heap size in bytes (-Xmx)
2563 * [u4]: current heap size in bytes
2564 * [u4]: current number of bytes allocated
2565 * [u4]: current number of objects allocated
2566 */
2567 uint8_t heap_count = 1;
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08002568 Heap* heap = Runtime::Current()->GetHeap();
Elliott Hughes21f32d72011-11-09 17:44:13 -08002569 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08002570 JDWP::Append4BE(bytes, heap_count);
2571 JDWP::Append4BE(bytes, 1); // Heap id (bogus; we only have one heap).
2572 JDWP::Append8BE(bytes, MilliTime());
2573 JDWP::Append1BE(bytes, reason);
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08002574 JDWP::Append4BE(bytes, heap->GetMaxMemory()); // Max allowed heap size in bytes.
2575 JDWP::Append4BE(bytes, heap->GetTotalMemory()); // Current heap size in bytes.
2576 JDWP::Append4BE(bytes, heap->GetBytesAllocated());
2577 JDWP::Append4BE(bytes, heap->GetObjectsAllocated());
Elliott Hughes21f32d72011-11-09 17:44:13 -08002578 CHECK_EQ(bytes.size(), 4U + (heap_count * (4 + 8 + 1 + 4 + 4 + 4 + 4)));
2579 Dbg::DdmSendChunk(CHUNK_TYPE("HPIF"), bytes);
Elliott Hughes767a1472011-10-26 18:49:02 -07002580}
2581
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002582enum HpsgSolidity {
2583 SOLIDITY_FREE = 0,
2584 SOLIDITY_HARD = 1,
2585 SOLIDITY_SOFT = 2,
2586 SOLIDITY_WEAK = 3,
2587 SOLIDITY_PHANTOM = 4,
2588 SOLIDITY_FINALIZABLE = 5,
2589 SOLIDITY_SWEEP = 6,
2590};
2591
2592enum HpsgKind {
2593 KIND_OBJECT = 0,
2594 KIND_CLASS_OBJECT = 1,
2595 KIND_ARRAY_1 = 2,
2596 KIND_ARRAY_2 = 3,
2597 KIND_ARRAY_4 = 4,
2598 KIND_ARRAY_8 = 5,
2599 KIND_UNKNOWN = 6,
2600 KIND_NATIVE = 7,
2601};
2602
2603#define HPSG_PARTIAL (1<<7)
2604#define HPSG_STATE(solidity, kind) ((uint8_t)((((kind) & 0x7) << 3) | ((solidity) & 0x7)))
2605
Ian Rogers30fab402012-01-23 15:43:46 -08002606class HeapChunkContext {
2607 public:
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002608 // Maximum chunk size. Obtain this from the formula:
2609 // (((maximum_heap_size / ALLOCATION_UNIT_SIZE) + 255) / 256) * 2
2610 HeapChunkContext(bool merge, bool native)
Ian Rogers30fab402012-01-23 15:43:46 -08002611 : buf_(16384 - 16),
2612 type_(0),
2613 merge_(merge) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002614 Reset();
2615 if (native) {
Ian Rogers30fab402012-01-23 15:43:46 -08002616 type_ = CHUNK_TYPE("NHSG");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002617 } else {
Ian Rogers30fab402012-01-23 15:43:46 -08002618 type_ = merge ? CHUNK_TYPE("HPSG") : CHUNK_TYPE("HPSO");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002619 }
2620 }
2621
2622 ~HeapChunkContext() {
Ian Rogers30fab402012-01-23 15:43:46 -08002623 if (p_ > &buf_[0]) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002624 Flush();
2625 }
2626 }
2627
2628 void EnsureHeader(const void* chunk_ptr) {
Ian Rogers30fab402012-01-23 15:43:46 -08002629 if (!needHeader_) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002630 return;
2631 }
2632
2633 // Start a new HPSx chunk.
Ian Rogers30fab402012-01-23 15:43:46 -08002634 JDWP::Write4BE(&p_, 1); // Heap id (bogus; we only have one heap).
2635 JDWP::Write1BE(&p_, 8); // Size of allocation unit, in bytes.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002636
Ian Rogers30fab402012-01-23 15:43:46 -08002637 JDWP::Write4BE(&p_, reinterpret_cast<uintptr_t>(chunk_ptr)); // virtual address of segment start.
2638 JDWP::Write4BE(&p_, 0); // offset of this piece (relative to the virtual address).
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002639 // [u4]: length of piece, in allocation units
2640 // 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 -08002641 pieceLenField_ = p_;
2642 JDWP::Write4BE(&p_, 0x55555555);
2643 needHeader_ = false;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002644 }
2645
2646 void Flush() {
2647 // Patch the "length of piece" field.
Ian Rogers30fab402012-01-23 15:43:46 -08002648 CHECK_LE(&buf_[0], pieceLenField_);
2649 CHECK_LE(pieceLenField_, p_);
2650 JDWP::Set4BE(pieceLenField_, totalAllocationUnits_);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002651
Ian Rogers30fab402012-01-23 15:43:46 -08002652 Dbg::DdmSendChunk(type_, p_ - &buf_[0], &buf_[0]);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002653 Reset();
2654 }
2655
Ian Rogers30fab402012-01-23 15:43:46 -08002656 static void HeapChunkCallback(void* start, void* end, size_t used_bytes, void* arg) {
2657 reinterpret_cast<HeapChunkContext*>(arg)->HeapChunkCallback(start, end, used_bytes);
Elliott Hughesa2155262011-11-16 16:26:58 -08002658 }
2659
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002660 private:
Elliott Hughesa2155262011-11-16 16:26:58 -08002661 enum { ALLOCATION_UNIT_SIZE = 8 };
2662
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002663 void Reset() {
Ian Rogers30fab402012-01-23 15:43:46 -08002664 p_ = &buf_[0];
2665 totalAllocationUnits_ = 0;
2666 needHeader_ = true;
2667 pieceLenField_ = NULL;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002668 }
2669
Ian Rogers30fab402012-01-23 15:43:46 -08002670 void HeapChunkCallback(void* start, void* end, size_t used_bytes) {
2671 // Note: heap call backs cannot manipulate the heap upon which they are crawling, care is taken
2672 // in the following code not to allocate memory, by ensuring buf_ is of the correct size
2673
2674 const void* user_ptr = used_bytes > 0 ? const_cast<void*>(start) : NULL;
2675 // from malloc.c mem2chunk(mem)
2676 const void* chunk_ptr =
2677 reinterpret_cast<const void*>(reinterpret_cast<const char*>(const_cast<void*>(start)) -
2678 (2 * sizeof(size_t)));
2679 // from malloc.c chunksize
2680 size_t chunk_len = (*reinterpret_cast<size_t* const*>(chunk_ptr))[1] & ~7;
2681
2682
2683 //size_t chunk_len = malloc_usable_size(user_ptr);
Elliott Hughesa2155262011-11-16 16:26:58 -08002684 CHECK_EQ((chunk_len & (ALLOCATION_UNIT_SIZE-1)), 0U);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002685
Elliott Hughesa2155262011-11-16 16:26:58 -08002686 /* Make sure there's enough room left in the buffer.
2687 * We need to use two bytes for every fractional 256
2688 * allocation units used by the chunk.
2689 */
2690 {
2691 size_t needed = (((chunk_len/ALLOCATION_UNIT_SIZE + 255) / 256) * 2);
Ian Rogers30fab402012-01-23 15:43:46 -08002692 size_t bytesLeft = buf_.size() - (size_t)(p_ - &buf_[0]);
Elliott Hughesa2155262011-11-16 16:26:58 -08002693 if (bytesLeft < needed) {
2694 Flush();
2695 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002696
Ian Rogers30fab402012-01-23 15:43:46 -08002697 bytesLeft = buf_.size() - (size_t)(p_ - &buf_[0]);
Elliott Hughesa2155262011-11-16 16:26:58 -08002698 if (bytesLeft < needed) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08002699 LOG(WARNING) << "Chunk is too big to transmit (chunk_len=" << chunk_len << ", " << needed << " bytes)";
Elliott Hughesa2155262011-11-16 16:26:58 -08002700 return;
2701 }
2702 }
2703
2704 // OLD-TODO: notice when there's a gap and start a new heap, or at least a new range.
2705 EnsureHeader(chunk_ptr);
2706
2707 // Determine the type of this chunk.
2708 // OLD-TODO: if context.merge, see if this chunk is different from the last chunk.
2709 // If it's the same, we should combine them.
Ian Rogers30fab402012-01-23 15:43:46 -08002710 uint8_t state = ExamineObject(reinterpret_cast<const Object*>(user_ptr), (type_ == CHUNK_TYPE("NHSG")));
Elliott Hughesa2155262011-11-16 16:26:58 -08002711
2712 // Write out the chunk description.
2713 chunk_len /= ALLOCATION_UNIT_SIZE; // convert to allocation units
Ian Rogers30fab402012-01-23 15:43:46 -08002714 totalAllocationUnits_ += chunk_len;
Elliott Hughesa2155262011-11-16 16:26:58 -08002715 while (chunk_len > 256) {
Ian Rogers30fab402012-01-23 15:43:46 -08002716 *p_++ = state | HPSG_PARTIAL;
2717 *p_++ = 255; // length - 1
Elliott Hughesa2155262011-11-16 16:26:58 -08002718 chunk_len -= 256;
2719 }
Ian Rogers30fab402012-01-23 15:43:46 -08002720 *p_++ = state;
2721 *p_++ = chunk_len - 1;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002722 }
2723
Elliott Hughesa2155262011-11-16 16:26:58 -08002724 uint8_t ExamineObject(const Object* o, bool is_native_heap) {
2725 if (o == NULL) {
2726 return HPSG_STATE(SOLIDITY_FREE, 0);
2727 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002728
Elliott Hughesa2155262011-11-16 16:26:58 -08002729 // It's an allocated chunk. Figure out what it is.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002730
Elliott Hughesa2155262011-11-16 16:26:58 -08002731 // If we're looking at the native heap, we'll just return
2732 // (SOLIDITY_HARD, KIND_NATIVE) for all allocated chunks.
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08002733 if (is_native_heap || !Runtime::Current()->GetHeap()->IsLiveObjectLocked(o)) {
Elliott Hughesa2155262011-11-16 16:26:58 -08002734 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
2735 }
2736
2737 Class* c = o->GetClass();
2738 if (c == NULL) {
2739 // The object was probably just created but hasn't been initialized yet.
2740 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
2741 }
2742
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08002743 if (!Runtime::Current()->GetHeap()->IsHeapAddress(c)) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08002744 LOG(WARNING) << "Invalid class for managed heap object: " << o << " " << c;
Elliott Hughesa2155262011-11-16 16:26:58 -08002745 return HPSG_STATE(SOLIDITY_HARD, KIND_UNKNOWN);
2746 }
2747
2748 if (c->IsClassClass()) {
2749 return HPSG_STATE(SOLIDITY_HARD, KIND_CLASS_OBJECT);
2750 }
2751
2752 if (c->IsArrayClass()) {
2753 if (o->IsObjectArray()) {
2754 return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
2755 }
2756 switch (c->GetComponentSize()) {
2757 case 1: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_1);
2758 case 2: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_2);
2759 case 4: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
2760 case 8: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_8);
2761 }
2762 }
2763
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002764 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
2765 }
2766
Ian Rogers30fab402012-01-23 15:43:46 -08002767 std::vector<uint8_t> buf_;
2768 uint8_t* p_;
2769 uint8_t* pieceLenField_;
2770 size_t totalAllocationUnits_;
2771 uint32_t type_;
2772 bool merge_;
2773 bool needHeader_;
2774
Elliott Hughesa2155262011-11-16 16:26:58 -08002775 DISALLOW_COPY_AND_ASSIGN(HeapChunkContext);
2776};
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002777
2778void Dbg::DdmSendHeapSegments(bool native) {
2779 Dbg::HpsgWhen when;
2780 Dbg::HpsgWhat what;
2781 if (!native) {
2782 when = gDdmHpsgWhen;
2783 what = gDdmHpsgWhat;
2784 } else {
2785 when = gDdmNhsgWhen;
2786 what = gDdmNhsgWhat;
2787 }
2788 if (when == HPSG_WHEN_NEVER) {
2789 return;
2790 }
2791
2792 // Figure out what kind of chunks we'll be sending.
2793 CHECK(what == HPSG_WHAT_MERGED_OBJECTS || what == HPSG_WHAT_DISTINCT_OBJECTS) << static_cast<int>(what);
2794
2795 // First, send a heap start chunk.
2796 uint8_t heap_id[4];
2797 JDWP::Set4BE(&heap_id[0], 1); // Heap id (bogus; we only have one heap).
2798 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHST") : CHUNK_TYPE("HPST"), sizeof(heap_id), heap_id);
2799
2800 // Send a series of heap segment chunks.
Elliott Hughesa2155262011-11-16 16:26:58 -08002801 HeapChunkContext context((what == HPSG_WHAT_MERGED_OBJECTS), native);
2802 if (native) {
Ian Rogers30fab402012-01-23 15:43:46 -08002803 // TODO: enable when bionic has moved to dlmalloc 2.8.5
2804 // dlmalloc_inspect_all(HeapChunkContext::HeapChunkCallback, &context);
2805 UNIMPLEMENTED(WARNING) << "Native heap send heap segments";
Elliott Hughesa2155262011-11-16 16:26:58 -08002806 } else {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08002807 Heap* heap = Runtime::Current()->GetHeap();
2808 heap->GetAllocSpace()->Walk(HeapChunkContext::HeapChunkCallback, &context);
Elliott Hughesa2155262011-11-16 16:26:58 -08002809 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002810
2811 // Finally, send a heap end chunk.
2812 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHEN") : CHUNK_TYPE("HPEN"), sizeof(heap_id), heap_id);
Elliott Hughes767a1472011-10-26 18:49:02 -07002813}
2814
Elliott Hughes545a0642011-11-08 19:10:03 -08002815void Dbg::SetAllocTrackingEnabled(bool enabled) {
2816 MutexLock mu(gAllocTrackerLock);
2817 if (enabled) {
2818 if (recent_allocation_records_ == NULL) {
2819 LOG(INFO) << "Enabling alloc tracker (" << kNumAllocRecords << " entries, "
2820 << kMaxAllocRecordStackDepth << " frames --> "
2821 << (sizeof(AllocRecord) * kNumAllocRecords) << " bytes)";
2822 gAllocRecordHead = gAllocRecordCount = 0;
2823 recent_allocation_records_ = new AllocRecord[kNumAllocRecords];
2824 CHECK(recent_allocation_records_ != NULL);
2825 }
2826 } else {
2827 delete[] recent_allocation_records_;
2828 recent_allocation_records_ = NULL;
2829 }
2830}
2831
2832struct AllocRecordStackVisitor : public Thread::StackVisitor {
Elliott Hughesba8eee12012-01-24 20:25:24 -08002833 explicit AllocRecordStackVisitor(AllocRecord* record) : record(record), depth(0) {
Elliott Hughes545a0642011-11-08 19:10:03 -08002834 }
2835
Elliott Hughes530fa002012-03-12 11:44:49 -07002836 bool VisitFrame(const Frame& f, uintptr_t pc) {
Elliott Hughes545a0642011-11-08 19:10:03 -08002837 if (depth >= kMaxAllocRecordStackDepth) {
Elliott Hughes530fa002012-03-12 11:44:49 -07002838 return false;
Elliott Hughes545a0642011-11-08 19:10:03 -08002839 }
Elliott Hughes530fa002012-03-12 11:44:49 -07002840 if (f.HasMethod()) {
2841 record->stack[depth].method = f.GetMethod();
2842 record->stack[depth].raw_pc = pc;
2843 ++depth;
Elliott Hughes545a0642011-11-08 19:10:03 -08002844 }
Elliott Hughes530fa002012-03-12 11:44:49 -07002845 return true;
Elliott Hughes545a0642011-11-08 19:10:03 -08002846 }
2847
2848 ~AllocRecordStackVisitor() {
2849 // Clear out any unused stack trace elements.
2850 for (; depth < kMaxAllocRecordStackDepth; ++depth) {
2851 record->stack[depth].method = NULL;
2852 record->stack[depth].raw_pc = 0;
2853 }
2854 }
2855
2856 AllocRecord* record;
2857 size_t depth;
2858};
2859
2860void Dbg::RecordAllocation(Class* type, size_t byte_count) {
2861 Thread* self = Thread::Current();
2862 CHECK(self != NULL);
2863
2864 MutexLock mu(gAllocTrackerLock);
2865 if (recent_allocation_records_ == NULL) {
2866 return;
2867 }
2868
2869 // Advance and clip.
2870 if (++gAllocRecordHead == kNumAllocRecords) {
2871 gAllocRecordHead = 0;
2872 }
2873
2874 // Fill in the basics.
2875 AllocRecord* record = &recent_allocation_records_[gAllocRecordHead];
2876 record->type = type;
2877 record->byte_count = byte_count;
2878 record->thin_lock_id = self->GetThinLockId();
2879
2880 // Fill in the stack trace.
2881 AllocRecordStackVisitor visitor(record);
2882 self->WalkStack(&visitor);
2883
2884 if (gAllocRecordCount < kNumAllocRecords) {
2885 ++gAllocRecordCount;
2886 }
2887}
2888
2889/*
2890 * Return the index of the head element.
2891 *
2892 * We point at the most-recently-written record, so if allocRecordCount is 1
2893 * we want to use the current element. Take "head+1" and subtract count
2894 * from it.
2895 *
2896 * We need to handle underflow in our circular buffer, so we add
2897 * kNumAllocRecords and then mask it back down.
2898 */
2899inline static int headIndex() {
2900 return (gAllocRecordHead+1 + kNumAllocRecords - gAllocRecordCount) & (kNumAllocRecords-1);
2901}
2902
2903void Dbg::DumpRecentAllocations() {
2904 MutexLock mu(gAllocTrackerLock);
2905 if (recent_allocation_records_ == NULL) {
2906 LOG(INFO) << "Not recording tracked allocations";
2907 return;
2908 }
2909
2910 // "i" is the head of the list. We want to start at the end of the
2911 // list and move forward to the tail.
2912 size_t i = headIndex();
2913 size_t count = gAllocRecordCount;
2914
2915 LOG(INFO) << "Tracked allocations, (head=" << gAllocRecordHead << " count=" << count << ")";
2916 while (count--) {
2917 AllocRecord* record = &recent_allocation_records_[i];
2918
Elliott Hughesaa6e1cd2012-01-18 19:26:06 -08002919 LOG(INFO) << StringPrintf(" T=%-2d %6zd ", record->thin_lock_id, record->byte_count)
Elliott Hughes545a0642011-11-08 19:10:03 -08002920 << PrettyClass(record->type);
2921
2922 for (size_t stack_frame = 0; stack_frame < kMaxAllocRecordStackDepth; ++stack_frame) {
2923 const Method* m = record->stack[stack_frame].method;
2924 if (m == NULL) {
2925 break;
2926 }
2927 LOG(INFO) << " " << PrettyMethod(m) << " line " << record->stack[stack_frame].LineNumber();
2928 }
2929
2930 // pause periodically to help logcat catch up
2931 if ((count % 5) == 0) {
2932 usleep(40000);
2933 }
2934
2935 i = (i + 1) & (kNumAllocRecords-1);
2936 }
2937}
2938
2939class StringTable {
2940 public:
2941 StringTable() {
2942 }
2943
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002944 void Add(const char* s) {
Elliott Hughes545a0642011-11-08 19:10:03 -08002945 table_.insert(s);
2946 }
2947
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002948 size_t IndexOf(const char* s) {
Elliott Hughes545a0642011-11-08 19:10:03 -08002949 return std::distance(table_.begin(), table_.find(s));
2950 }
2951
2952 size_t Size() {
2953 return table_.size();
2954 }
2955
2956 void WriteTo(std::vector<uint8_t>& bytes) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002957 typedef std::set<const char*>::const_iterator It; // TODO: C++0x auto
Elliott Hughes545a0642011-11-08 19:10:03 -08002958 for (It it = table_.begin(); it != table_.end(); ++it) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002959 const char* s = *it;
2960 size_t s_len = CountModifiedUtf8Chars(s);
2961 UniquePtr<uint16_t> s_utf16(new uint16_t[s_len]);
2962 ConvertModifiedUtf8ToUtf16(s_utf16.get(), s);
2963 JDWP::AppendUtf16BE(bytes, s_utf16.get(), s_len);
Elliott Hughes545a0642011-11-08 19:10:03 -08002964 }
2965 }
2966
2967 private:
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002968 std::set<const char*> table_;
Elliott Hughes545a0642011-11-08 19:10:03 -08002969 DISALLOW_COPY_AND_ASSIGN(StringTable);
2970};
2971
2972/*
2973 * The data we send to DDMS contains everything we have recorded.
2974 *
2975 * Message header (all values big-endian):
2976 * (1b) message header len (to allow future expansion); includes itself
2977 * (1b) entry header len
2978 * (1b) stack frame len
2979 * (2b) number of entries
2980 * (4b) offset to string table from start of message
2981 * (2b) number of class name strings
2982 * (2b) number of method name strings
2983 * (2b) number of source file name strings
2984 * For each entry:
2985 * (4b) total allocation size
2986 * (2b) threadId
2987 * (2b) allocated object's class name index
2988 * (1b) stack depth
2989 * For each stack frame:
2990 * (2b) method's class name
2991 * (2b) method name
2992 * (2b) method source file
2993 * (2b) line number, clipped to 32767; -2 if native; -1 if no source
2994 * (xb) class name strings
2995 * (xb) method name strings
2996 * (xb) source file strings
2997 *
2998 * As with other DDM traffic, strings are sent as a 4-byte length
2999 * followed by UTF-16 data.
3000 *
3001 * We send up 16-bit unsigned indexes into string tables. In theory there
3002 * can be (kMaxAllocRecordStackDepth * kNumAllocRecords) unique strings in
3003 * each table, but in practice there should be far fewer.
3004 *
3005 * The chief reason for using a string table here is to keep the size of
3006 * the DDMS message to a minimum. This is partly to make the protocol
3007 * efficient, but also because we have to form the whole thing up all at
3008 * once in a memory buffer.
3009 *
3010 * We use separate string tables for class names, method names, and source
3011 * files to keep the indexes small. There will generally be no overlap
3012 * between the contents of these tables.
3013 */
3014jbyteArray Dbg::GetRecentAllocations() {
3015 if (false) {
3016 DumpRecentAllocations();
3017 }
3018
3019 MutexLock mu(gAllocTrackerLock);
3020
3021 /*
3022 * Part 1: generate string tables.
3023 */
3024 StringTable class_names;
3025 StringTable method_names;
3026 StringTable filenames;
3027
3028 int count = gAllocRecordCount;
3029 int idx = headIndex();
3030 while (count--) {
3031 AllocRecord* record = &recent_allocation_records_[idx];
3032
Elliott Hughes91250e02011-12-13 22:30:35 -08003033 class_names.Add(ClassHelper(record->type).GetDescriptor());
Elliott Hughes545a0642011-11-08 19:10:03 -08003034
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003035 MethodHelper mh;
Elliott Hughes545a0642011-11-08 19:10:03 -08003036 for (size_t i = 0; i < kMaxAllocRecordStackDepth; i++) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003037 Method* m = record->stack[i].method;
3038 mh.ChangeMethod(m);
Elliott Hughes545a0642011-11-08 19:10:03 -08003039 if (m != NULL) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003040 class_names.Add(mh.GetDeclaringClassDescriptor());
3041 method_names.Add(mh.GetName());
3042 filenames.Add(mh.GetDeclaringClassSourceFile());
Elliott Hughes545a0642011-11-08 19:10:03 -08003043 }
3044 }
3045
3046 idx = (idx + 1) & (kNumAllocRecords-1);
3047 }
3048
3049 LOG(INFO) << "allocation records: " << gAllocRecordCount;
3050
3051 /*
3052 * Part 2: allocate a buffer and generate the output.
3053 */
3054 std::vector<uint8_t> bytes;
3055
3056 // (1b) message header len (to allow future expansion); includes itself
3057 // (1b) entry header len
3058 // (1b) stack frame len
3059 const int kMessageHeaderLen = 15;
3060 const int kEntryHeaderLen = 9;
3061 const int kStackFrameLen = 8;
3062 JDWP::Append1BE(bytes, kMessageHeaderLen);
3063 JDWP::Append1BE(bytes, kEntryHeaderLen);
3064 JDWP::Append1BE(bytes, kStackFrameLen);
3065
3066 // (2b) number of entries
3067 // (4b) offset to string table from start of message
3068 // (2b) number of class name strings
3069 // (2b) number of method name strings
3070 // (2b) number of source file name strings
3071 JDWP::Append2BE(bytes, gAllocRecordCount);
3072 size_t string_table_offset = bytes.size();
3073 JDWP::Append4BE(bytes, 0); // We'll patch this later...
3074 JDWP::Append2BE(bytes, class_names.Size());
3075 JDWP::Append2BE(bytes, method_names.Size());
3076 JDWP::Append2BE(bytes, filenames.Size());
3077
3078 count = gAllocRecordCount;
3079 idx = headIndex();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003080 ClassHelper kh;
Elliott Hughes545a0642011-11-08 19:10:03 -08003081 while (count--) {
3082 // For each entry:
3083 // (4b) total allocation size
3084 // (2b) thread id
3085 // (2b) allocated object's class name index
3086 // (1b) stack depth
3087 AllocRecord* record = &recent_allocation_records_[idx];
3088 size_t stack_depth = record->GetDepth();
3089 JDWP::Append4BE(bytes, record->byte_count);
3090 JDWP::Append2BE(bytes, record->thin_lock_id);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003091 kh.ChangeClass(record->type);
Elliott Hughes91250e02011-12-13 22:30:35 -08003092 JDWP::Append2BE(bytes, class_names.IndexOf(kh.GetDescriptor()));
Elliott Hughes545a0642011-11-08 19:10:03 -08003093 JDWP::Append1BE(bytes, stack_depth);
3094
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003095 MethodHelper mh;
Elliott Hughes545a0642011-11-08 19:10:03 -08003096 for (size_t stack_frame = 0; stack_frame < stack_depth; ++stack_frame) {
3097 // For each stack frame:
3098 // (2b) method's class name
3099 // (2b) method name
3100 // (2b) method source file
3101 // (2b) line number, clipped to 32767; -2 if native; -1 if no source
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003102 mh.ChangeMethod(record->stack[stack_frame].method);
3103 JDWP::Append2BE(bytes, class_names.IndexOf(mh.GetDeclaringClassDescriptor()));
3104 JDWP::Append2BE(bytes, method_names.IndexOf(mh.GetName()));
3105 JDWP::Append2BE(bytes, filenames.IndexOf(mh.GetDeclaringClassSourceFile()));
Elliott Hughes545a0642011-11-08 19:10:03 -08003106 JDWP::Append2BE(bytes, record->stack[stack_frame].LineNumber());
3107 }
3108
3109 idx = (idx + 1) & (kNumAllocRecords-1);
3110 }
3111
3112 // (xb) class name strings
3113 // (xb) method name strings
3114 // (xb) source file strings
3115 JDWP::Set4BE(&bytes[string_table_offset], bytes.size());
3116 class_names.WriteTo(bytes);
3117 method_names.WriteTo(bytes);
3118 filenames.WriteTo(bytes);
3119
3120 JNIEnv* env = Thread::Current()->GetJniEnv();
3121 jbyteArray result = env->NewByteArray(bytes.size());
3122 if (result != NULL) {
3123 env->SetByteArrayRegion(result, 0, bytes.size(), reinterpret_cast<const jbyte*>(&bytes[0]));
3124 }
3125 return result;
3126}
3127
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003128} // namespace art