blob: 1f7b0dee8093f988e55fc71de0c03b68009cd9ca [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"
Elliott Hughes88c5c352012-03-15 18:49:48 -070030#include "scoped_thread_list_lock.h"
Ian Rogers30fab402012-01-23 15:43:46 -080031#include "space.h"
Elliott Hughes47fce012011-10-25 18:37:19 -070032#include "stack_indirect_reference_table.h"
Elliott Hughes475fc232011-10-25 15:00:35 -070033#include "thread_list.h"
34
Elliott Hughes6a5bd492011-10-28 14:33:57 -070035extern "C" void dlmalloc_walk_heap(void(*)(const void*, size_t, const void*, size_t, void*), void*);
36#ifndef HAVE_ANDROID_OS
37void dlmalloc_walk_heap(void(*)(const void*, size_t, const void*, size_t, void*), void*) {
38 // No-op for glibc.
39}
40#endif
41
Elliott Hughes872d4ec2011-10-21 17:07:15 -070042namespace art {
43
Elliott Hughes545a0642011-11-08 19:10:03 -080044static const size_t kMaxAllocRecordStackDepth = 16; // Max 255.
45static const size_t kNumAllocRecords = 512; // Must be power of 2.
46
Elliott Hughes436e3722012-02-17 20:01:47 -080047static const uintptr_t kInvalidId = 1;
48static const Object* kInvalidObject = reinterpret_cast<Object*>(kInvalidId);
49
Elliott Hughes475fc232011-10-25 15:00:35 -070050class ObjectRegistry {
51 public:
52 ObjectRegistry() : lock_("ObjectRegistry lock") {
53 }
54
55 JDWP::ObjectId Add(Object* o) {
56 if (o == NULL) {
57 return 0;
58 }
59 JDWP::ObjectId id = static_cast<JDWP::ObjectId>(reinterpret_cast<uintptr_t>(o));
60 MutexLock mu(lock_);
61 map_[id] = o;
62 return id;
63 }
64
Elliott Hughes234ab152011-10-26 14:02:26 -070065 void Clear() {
66 MutexLock mu(lock_);
67 LOG(DEBUG) << "Debugger has detached; object registry had " << map_.size() << " entries";
68 map_.clear();
69 }
70
Elliott Hughes475fc232011-10-25 15:00:35 -070071 bool Contains(JDWP::ObjectId id) {
72 MutexLock mu(lock_);
73 return map_.find(id) != map_.end();
74 }
75
Elliott Hughesa2155262011-11-16 16:26:58 -080076 template<typename T> T Get(JDWP::ObjectId id) {
Elliott Hughes436e3722012-02-17 20:01:47 -080077 if (id == 0) {
78 return NULL;
79 }
80
Elliott Hughesa2155262011-11-16 16:26:58 -080081 MutexLock mu(lock_);
82 typedef std::map<JDWP::ObjectId, Object*>::iterator It; // C++0x auto
83 It it = map_.find(id);
Elliott Hughes436e3722012-02-17 20:01:47 -080084 return (it != map_.end()) ? reinterpret_cast<T>(it->second) : reinterpret_cast<T>(kInvalidId);
Elliott Hughesa2155262011-11-16 16:26:58 -080085 }
86
Elliott Hughesbfe487b2011-10-26 15:48:55 -070087 void VisitRoots(Heap::RootVisitor* visitor, void* arg) {
88 MutexLock mu(lock_);
89 typedef std::map<JDWP::ObjectId, Object*>::iterator It; // C++0x auto
90 for (It it = map_.begin(); it != map_.end(); ++it) {
91 visitor(it->second, arg);
92 }
93 }
94
Elliott Hughes475fc232011-10-25 15:00:35 -070095 private:
96 Mutex lock_;
97 std::map<JDWP::ObjectId, Object*> map_;
98};
99
Elliott Hughes545a0642011-11-08 19:10:03 -0800100struct AllocRecordStackTraceElement {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800101 Method* method;
Elliott Hughes545a0642011-11-08 19:10:03 -0800102 uintptr_t raw_pc;
103
104 int32_t LineNumber() const {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800105 return MethodHelper(method).GetLineNumFromNativePC(raw_pc);
Elliott Hughes545a0642011-11-08 19:10:03 -0800106 }
107};
108
109struct AllocRecord {
110 Class* type;
111 size_t byte_count;
112 uint16_t thin_lock_id;
113 AllocRecordStackTraceElement stack[kMaxAllocRecordStackDepth]; // Unused entries have NULL method.
114
115 size_t GetDepth() {
116 size_t depth = 0;
117 while (depth < kMaxAllocRecordStackDepth && stack[depth].method != NULL) {
118 ++depth;
119 }
120 return depth;
121 }
122};
123
Elliott Hughes86964332012-02-15 19:37:42 -0800124struct Breakpoint {
125 Method* method;
Elliott Hughesa656a0f2012-02-21 18:03:44 -0800126 uint32_t dex_pc;
127 Breakpoint(Method* method, uint32_t dex_pc) : method(method), dex_pc(dex_pc) {}
Elliott Hughes86964332012-02-15 19:37:42 -0800128};
129
130static std::ostream& operator<<(std::ostream& os, const Breakpoint& rhs) {
Elliott Hughes229feb72012-02-23 13:33:29 -0800131 os << StringPrintf("Breakpoint[%s @%#x]", PrettyMethod(rhs.method).c_str(), rhs.dex_pc);
Elliott Hughes86964332012-02-15 19:37:42 -0800132 return os;
133}
134
135struct SingleStepControl {
136 // Are we single-stepping right now?
137 bool is_active;
138 Thread* thread;
139
140 JDWP::JdwpStepSize step_size;
141 JDWP::JdwpStepDepth step_depth;
142
143 const Method* method;
Elliott Hughes2435a572012-02-17 16:07:41 -0800144 int32_t line_number; // Or -1 for native methods.
145 std::set<uint32_t> dex_pcs;
Elliott Hughes86964332012-02-15 19:37:42 -0800146 int stack_depth;
147};
148
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700149// JDWP is allowed unless the Zygote forbids it.
150static bool gJdwpAllowed = true;
151
Elliott Hughes3bb81562011-10-21 18:52:59 -0700152// Was there a -Xrunjdwp or -agent argument on the command-line?
153static bool gJdwpConfigured = false;
154
155// Broken-down JDWP options. (Only valid if gJdwpConfigured is true.)
Elliott Hughes376a7a02011-10-24 18:35:55 -0700156static JDWP::JdwpOptions gJdwpOptions;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700157
158// Runtime JDWP state.
159static JDWP::JdwpState* gJdwpState = NULL;
160static bool gDebuggerConnected; // debugger or DDMS is connected.
161static bool gDebuggerActive; // debugger is making requests.
Elliott Hughes86964332012-02-15 19:37:42 -0800162static bool gDisposed; // debugger called VirtualMachine.Dispose, so we should drop the connection.
Elliott Hughes3bb81562011-10-21 18:52:59 -0700163
Elliott Hughes47fce012011-10-25 18:37:19 -0700164static bool gDdmThreadNotification = false;
165
Elliott Hughes767a1472011-10-26 18:49:02 -0700166// DDMS GC-related settings.
167static Dbg::HpifWhen gDdmHpifWhen = Dbg::HPIF_WHEN_NEVER;
168static Dbg::HpsgWhen gDdmHpsgWhen = Dbg::HPSG_WHEN_NEVER;
169static Dbg::HpsgWhat gDdmHpsgWhat;
170static Dbg::HpsgWhen gDdmNhsgWhen = Dbg::HPSG_WHEN_NEVER;
171static Dbg::HpsgWhat gDdmNhsgWhat;
172
Elliott Hughes475fc232011-10-25 15:00:35 -0700173static ObjectRegistry* gRegistry = NULL;
174
Elliott Hughes545a0642011-11-08 19:10:03 -0800175// Recent allocation tracking.
176static Mutex gAllocTrackerLock("AllocTracker lock");
177AllocRecord* Dbg::recent_allocation_records_ = NULL; // TODO: CircularBuffer<AllocRecord>
178static size_t gAllocRecordHead = 0;
179static size_t gAllocRecordCount = 0;
180
Elliott Hughes86964332012-02-15 19:37:42 -0800181// Breakpoints and single-stepping.
182static Mutex gBreakpointsLock("breakpoints lock");
183static std::vector<Breakpoint> gBreakpoints;
184static SingleStepControl gSingleStepControl;
185
186static bool IsBreakpoint(Method* m, uint32_t dex_pc) {
187 MutexLock mu(gBreakpointsLock);
188 for (size_t i = 0; i < gBreakpoints.size(); ++i) {
Elliott Hughesa656a0f2012-02-21 18:03:44 -0800189 if (gBreakpoints[i].method == m && gBreakpoints[i].dex_pc == dex_pc) {
Elliott Hughes86964332012-02-15 19:37:42 -0800190 VLOG(jdwp) << "Hit breakpoint #" << i << ": " << gBreakpoints[i];
191 return true;
192 }
193 }
194 return false;
195}
196
Elliott Hughes436e3722012-02-17 20:01:47 -0800197static Array* DecodeArray(JDWP::RefTypeId id, JDWP::JdwpError& status) {
198 Object* o = gRegistry->Get<Object*>(id);
199 if (o == NULL || o == kInvalidObject) {
200 status = JDWP::ERR_INVALID_OBJECT;
201 return NULL;
202 }
203 if (!o->IsArrayInstance()) {
204 status = JDWP::ERR_INVALID_ARRAY;
205 return NULL;
206 }
207 status = JDWP::ERR_NONE;
208 return o->AsArray();
209}
210
211static Class* DecodeClass(JDWP::RefTypeId id, JDWP::JdwpError& status) {
212 Object* o = gRegistry->Get<Object*>(id);
213 if (o == NULL || o == kInvalidObject) {
214 status = JDWP::ERR_INVALID_OBJECT;
215 return NULL;
216 }
217 if (!o->IsClass()) {
218 status = JDWP::ERR_INVALID_CLASS;
219 return NULL;
220 }
221 status = JDWP::ERR_NONE;
222 return o->AsClass();
223}
224
225static Thread* DecodeThread(JDWP::ObjectId threadId) {
226 Object* thread_peer = gRegistry->Get<Object*>(threadId);
227 if (thread_peer == NULL || thread_peer == kInvalidObject) {
228 return NULL;
229 }
230 return Thread::FromManagedThread(thread_peer);
231}
232
Elliott Hughes24437992011-11-30 14:49:33 -0800233static JDWP::JdwpTag BasicTagFromDescriptor(const char* descriptor) {
234 // JDWP deliberately uses the descriptor characters' ASCII values for its enum.
235 // Note that by "basic" we mean that we don't get more specific than JT_OBJECT.
236 return static_cast<JDWP::JdwpTag>(descriptor[0]);
237}
238
239static JDWP::JdwpTag TagFromClass(Class* c) {
Elliott Hughes86b00102011-12-05 17:54:26 -0800240 CHECK(c != NULL);
Elliott Hughes24437992011-11-30 14:49:33 -0800241 if (c->IsArrayClass()) {
242 return JDWP::JT_ARRAY;
243 }
244
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800245 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Elliott Hughes24437992011-11-30 14:49:33 -0800246 if (c->IsStringClass()) {
247 return JDWP::JT_STRING;
248 } else if (c->IsClassClass()) {
249 return JDWP::JT_CLASS_OBJECT;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800250 } else if (class_linker->FindSystemClass("Ljava/lang/Thread;")->IsAssignableFrom(c)) {
Elliott Hughes24437992011-11-30 14:49:33 -0800251 return JDWP::JT_THREAD;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800252 } else if (class_linker->FindSystemClass("Ljava/lang/ThreadGroup;")->IsAssignableFrom(c)) {
Elliott Hughes24437992011-11-30 14:49:33 -0800253 return JDWP::JT_THREAD_GROUP;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800254 } else if (class_linker->FindSystemClass("Ljava/lang/ClassLoader;")->IsAssignableFrom(c)) {
Elliott Hughes24437992011-11-30 14:49:33 -0800255 return JDWP::JT_CLASS_LOADER;
Elliott Hughes24437992011-11-30 14:49:33 -0800256 } else {
257 return JDWP::JT_OBJECT;
258 }
259}
260
261/*
262 * Objects declared to hold Object might actually hold a more specific
263 * type. The debugger may take a special interest in these (e.g. it
264 * wants to display the contents of Strings), so we want to return an
265 * appropriate tag.
266 *
267 * Null objects are tagged JT_OBJECT.
268 */
269static JDWP::JdwpTag TagFromObject(const Object* o) {
270 return (o == NULL) ? JDWP::JT_OBJECT : TagFromClass(o->GetClass());
271}
272
273static bool IsPrimitiveTag(JDWP::JdwpTag tag) {
274 switch (tag) {
275 case JDWP::JT_BOOLEAN:
276 case JDWP::JT_BYTE:
277 case JDWP::JT_CHAR:
278 case JDWP::JT_FLOAT:
279 case JDWP::JT_DOUBLE:
280 case JDWP::JT_INT:
281 case JDWP::JT_LONG:
282 case JDWP::JT_SHORT:
283 case JDWP::JT_VOID:
284 return true;
285 default:
286 return false;
287 }
288}
289
Elliott Hughes3bb81562011-10-21 18:52:59 -0700290/*
291 * Handle one of the JDWP name/value pairs.
292 *
293 * JDWP options are:
294 * help: if specified, show help message and bail
295 * transport: may be dt_socket or dt_shmem
296 * address: for dt_socket, "host:port", or just "port" when listening
297 * server: if "y", wait for debugger to attach; if "n", attach to debugger
298 * timeout: how long to wait for debugger to connect / listen
299 *
300 * Useful with server=n (these aren't supported yet):
301 * onthrow=<exception-name>: connect to debugger when exception thrown
302 * onuncaught=y|n: connect to debugger when uncaught exception thrown
303 * launch=<command-line>: launch the debugger itself
304 *
305 * The "transport" option is required, as is "address" if server=n.
306 */
307static bool ParseJdwpOption(const std::string& name, const std::string& value) {
308 if (name == "transport") {
309 if (value == "dt_socket") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700310 gJdwpOptions.transport = JDWP::kJdwpTransportSocket;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700311 } else if (value == "dt_android_adb") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700312 gJdwpOptions.transport = JDWP::kJdwpTransportAndroidAdb;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700313 } else {
314 LOG(ERROR) << "JDWP transport not supported: " << value;
315 return false;
316 }
317 } else if (name == "server") {
318 if (value == "n") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700319 gJdwpOptions.server = false;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700320 } else if (value == "y") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700321 gJdwpOptions.server = true;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700322 } else {
323 LOG(ERROR) << "JDWP option 'server' must be 'y' or 'n'";
324 return false;
325 }
326 } else if (name == "suspend") {
327 if (value == "n") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700328 gJdwpOptions.suspend = false;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700329 } else if (value == "y") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700330 gJdwpOptions.suspend = true;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700331 } else {
332 LOG(ERROR) << "JDWP option 'suspend' must be 'y' or 'n'";
333 return false;
334 }
335 } else if (name == "address") {
336 /* this is either <port> or <host>:<port> */
337 std::string port_string;
Elliott Hughes376a7a02011-10-24 18:35:55 -0700338 gJdwpOptions.host.clear();
Elliott Hughes3bb81562011-10-21 18:52:59 -0700339 std::string::size_type colon = value.find(':');
340 if (colon != std::string::npos) {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700341 gJdwpOptions.host = value.substr(0, colon);
Elliott Hughes3bb81562011-10-21 18:52:59 -0700342 port_string = value.substr(colon + 1);
343 } else {
344 port_string = value;
345 }
346 if (port_string.empty()) {
347 LOG(ERROR) << "JDWP address missing port: " << value;
348 return false;
349 }
350 char* end;
Elliott Hughesba8eee12012-01-24 20:25:24 -0800351 uint64_t port = strtoul(port_string.c_str(), &end, 10);
352 if (*end != '\0' || port > 0xffff) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700353 LOG(ERROR) << "JDWP address has junk in port field: " << value;
354 return false;
355 }
Elliott Hughes376a7a02011-10-24 18:35:55 -0700356 gJdwpOptions.port = port;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700357 } else if (name == "launch" || name == "onthrow" || name == "oncaught" || name == "timeout") {
358 /* valid but unsupported */
359 LOG(INFO) << "Ignoring JDWP option '" << name << "'='" << value << "'";
360 } else {
361 LOG(INFO) << "Ignoring unrecognized JDWP option '" << name << "'='" << value << "'";
362 }
363
364 return true;
365}
366
367/*
368 * Parse the latter half of a -Xrunjdwp/-agentlib:jdwp= string, e.g.:
369 * "transport=dt_socket,address=8000,server=y,suspend=n"
370 */
371bool Dbg::ParseJdwpOptions(const std::string& options) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800372 VLOG(jdwp) << "ParseJdwpOptions: " << options;
Elliott Hughes47fce012011-10-25 18:37:19 -0700373
Elliott Hughes3bb81562011-10-21 18:52:59 -0700374 std::vector<std::string> pairs;
375 Split(options, ',', pairs);
376
377 for (size_t i = 0; i < pairs.size(); ++i) {
378 std::string::size_type equals = pairs[i].find('=');
379 if (equals == std::string::npos) {
380 LOG(ERROR) << "Can't parse JDWP option '" << pairs[i] << "' in '" << options << "'";
381 return false;
382 }
383 ParseJdwpOption(pairs[i].substr(0, equals), pairs[i].substr(equals + 1));
384 }
385
Elliott Hughes376a7a02011-10-24 18:35:55 -0700386 if (gJdwpOptions.transport == JDWP::kJdwpTransportUnknown) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700387 LOG(ERROR) << "Must specify JDWP transport: " << options;
388 }
Elliott Hughes376a7a02011-10-24 18:35:55 -0700389 if (!gJdwpOptions.server && (gJdwpOptions.host.empty() || gJdwpOptions.port == 0)) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700390 LOG(ERROR) << "Must specify JDWP host and port when server=n: " << options;
391 return false;
392 }
393
394 gJdwpConfigured = true;
395 return true;
396}
397
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700398void Dbg::StartJdwp() {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700399 if (!gJdwpAllowed || !gJdwpConfigured) {
400 // No JDWP for you!
401 return;
402 }
403
Elliott Hughes475fc232011-10-25 15:00:35 -0700404 CHECK(gRegistry == NULL);
405 gRegistry = new ObjectRegistry;
406
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700407 // Init JDWP if the debugger is enabled. This may connect out to a
408 // debugger, passively listen for a debugger, or block waiting for a
409 // debugger.
Elliott Hughes376a7a02011-10-24 18:35:55 -0700410 gJdwpState = JDWP::JdwpState::Create(&gJdwpOptions);
411 if (gJdwpState == NULL) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -0800412 // We probably failed because some other process has the port already, which means that
413 // if we don't abort the user is likely to think they're talking to us when they're actually
414 // talking to that other process.
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800415 LOG(FATAL) << "Debugger thread failed to initialize";
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700416 }
417
418 // If a debugger has already attached, send the "welcome" message.
419 // This may cause us to suspend all threads.
Elliott Hughes376a7a02011-10-24 18:35:55 -0700420 if (gJdwpState->IsActive()) {
Elliott Hughesa2155262011-11-16 16:26:58 -0800421 //ScopedThreadStateChange tsc(Thread::Current(), Thread::kRunnable);
Elliott Hughes376a7a02011-10-24 18:35:55 -0700422 if (!gJdwpState->PostVMStart()) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800423 LOG(WARNING) << "Failed to post 'start' message to debugger";
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700424 }
425 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700426}
427
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700428void Dbg::StopJdwp() {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700429 delete gJdwpState;
Elliott Hughes475fc232011-10-25 15:00:35 -0700430 delete gRegistry;
431 gRegistry = NULL;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700432}
433
Elliott Hughes767a1472011-10-26 18:49:02 -0700434void Dbg::GcDidFinish() {
435 if (gDdmHpifWhen != HPIF_WHEN_NEVER) {
Elliott Hughes81ff3182012-03-23 20:35:56 -0700436 LOG(DEBUG) << "Sending heap info to DDM";
Elliott Hughes7162ad92011-10-27 14:08:42 -0700437 DdmSendHeapInfo(gDdmHpifWhen);
Elliott Hughes767a1472011-10-26 18:49:02 -0700438 }
439 if (gDdmHpsgWhen != HPSG_WHEN_NEVER) {
Elliott Hughes81ff3182012-03-23 20:35:56 -0700440 LOG(DEBUG) << "Dumping heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700441 DdmSendHeapSegments(false);
Elliott Hughes767a1472011-10-26 18:49:02 -0700442 }
443 if (gDdmNhsgWhen != HPSG_WHEN_NEVER) {
444 LOG(DEBUG) << "Dumping native heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700445 DdmSendHeapSegments(true);
Elliott Hughes767a1472011-10-26 18:49:02 -0700446 }
447}
448
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700449void Dbg::SetJdwpAllowed(bool allowed) {
450 gJdwpAllowed = allowed;
451}
452
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700453DebugInvokeReq* Dbg::GetInvokeReq() {
Elliott Hughes475fc232011-10-25 15:00:35 -0700454 return Thread::Current()->GetInvokeReq();
455}
456
457Thread* Dbg::GetDebugThread() {
458 return (gJdwpState != NULL) ? gJdwpState->GetDebugThread() : NULL;
459}
460
461void Dbg::ClearWaitForEventThread() {
462 gJdwpState->ClearWaitForEventThread();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700463}
464
465void Dbg::Connected() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700466 CHECK(!gDebuggerConnected);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800467 VLOG(jdwp) << "JDWP has attached";
Elliott Hughes3bb81562011-10-21 18:52:59 -0700468 gDebuggerConnected = true;
Elliott Hughes86964332012-02-15 19:37:42 -0800469 gDisposed = false;
470}
471
472void Dbg::Disposed() {
473 gDisposed = true;
474}
475
476bool Dbg::IsDisposed() {
477 return gDisposed;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700478}
479
Elliott Hughesa2155262011-11-16 16:26:58 -0800480void Dbg::GoActive() {
481 // Enable all debugging features, including scans for breakpoints.
482 // This is a no-op if we're already active.
483 // Only called from the JDWP handler thread.
484 if (gDebuggerActive) {
485 return;
486 }
487
488 LOG(INFO) << "Debugger is active";
489
490 // TODO: CHECK we don't have any outstanding breakpoints.
491
492 gDebuggerActive = true;
493
494 //dvmEnableAllSubMode(kSubModeDebuggerActive);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700495}
496
497void Dbg::Disconnected() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700498 CHECK(gDebuggerConnected);
499
500 gDebuggerActive = false;
501
502 //dvmDisableAllSubMode(kSubModeDebuggerActive);
503
504 gRegistry->Clear();
505 gDebuggerConnected = false;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700506}
507
508bool Dbg::IsDebuggerConnected() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700509 return gDebuggerActive;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700510}
511
512bool Dbg::IsDebuggingEnabled() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700513 return gJdwpConfigured;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700514}
515
516int64_t Dbg::LastDebuggerActivity() {
Elliott Hughesca951522011-12-05 12:01:32 -0800517 return gJdwpState->LastDebuggerActivity();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700518}
519
520int Dbg::ThreadRunning() {
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700521 return static_cast<int>(Thread::Current()->SetState(Thread::kRunnable));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700522}
523
524int Dbg::ThreadWaiting() {
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700525 return static_cast<int>(Thread::Current()->SetState(Thread::kVmWait));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700526}
527
Elliott Hughes6ba581a2011-10-25 11:45:35 -0700528int Dbg::ThreadContinuing(int new_state) {
529 return static_cast<int>(Thread::Current()->SetState(static_cast<Thread::State>(new_state)));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700530}
531
532void Dbg::UndoDebuggerSuspensions() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700533 Runtime::Current()->GetThreadList()->UndoDebuggerSuspensions();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700534}
535
536void Dbg::Exit(int status) {
Elliott Hughes1bba14f2011-12-01 18:00:36 -0800537 exit(status); // This is all dalvik did.
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700538}
539
Elliott Hughesbfe487b2011-10-26 15:48:55 -0700540void Dbg::VisitRoots(Heap::RootVisitor* visitor, void* arg) {
541 if (gRegistry != NULL) {
542 gRegistry->VisitRoots(visitor, arg);
543 }
544}
545
Elliott Hughesc308a5d2012-02-16 17:12:06 -0800546std::string Dbg::GetClassName(JDWP::RefTypeId classId) {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800547 Object* o = gRegistry->Get<Object*>(classId);
Elliott Hughes436e3722012-02-17 20:01:47 -0800548 if (o == NULL) {
549 return "NULL";
550 }
551 if (o == kInvalidObject) {
552 return StringPrintf("invalid object %p", reinterpret_cast<void*>(classId));
553 }
554 if (!o->IsClass()) {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800555 return StringPrintf("non-class %p", o); // This is only used for debugging output anyway.
556 }
Elliott Hughesc308a5d2012-02-16 17:12:06 -0800557 return DescriptorToName(ClassHelper(o->AsClass()).GetDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700558}
559
Elliott Hughes436e3722012-02-17 20:01:47 -0800560JDWP::JdwpError Dbg::GetClassObject(JDWP::RefTypeId id, JDWP::ObjectId& classObjectId) {
561 JDWP::JdwpError status;
562 Class* c = DecodeClass(id, status);
563 if (c == NULL) {
564 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800565 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800566 classObjectId = gRegistry->Add(c);
567 return JDWP::ERR_NONE;
Elliott Hughes86964332012-02-15 19:37:42 -0800568}
569
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800570JDWP::JdwpError Dbg::GetSuperclass(JDWP::RefTypeId id, JDWP::RefTypeId& superclassId) {
571 JDWP::JdwpError status;
572 Class* c = DecodeClass(id, status);
573 if (c == NULL) {
574 return status;
575 }
576 if (c->IsInterface()) {
577 // http://code.google.com/p/android/issues/detail?id=20856
578 superclassId = NULL;
579 } else {
580 superclassId = gRegistry->Add(c->GetSuperClass());
581 }
582 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700583}
584
Elliott Hughes436e3722012-02-17 20:01:47 -0800585JDWP::JdwpError Dbg::GetClassLoader(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) {
Elliott Hughes1bba14f2011-12-01 18:00:36 -0800586 Object* o = gRegistry->Get<Object*>(id);
Elliott Hughes436e3722012-02-17 20:01:47 -0800587 if (o == NULL || o == kInvalidObject) {
588 return JDWP::ERR_INVALID_OBJECT;
589 }
590 expandBufAddObjectId(pReply, gRegistry->Add(o->GetClass()->GetClassLoader()));
591 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700592}
593
Elliott Hughes436e3722012-02-17 20:01:47 -0800594JDWP::JdwpError Dbg::GetModifiers(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) {
595 JDWP::JdwpError status;
596 Class* c = DecodeClass(id, status);
597 if (c == NULL) {
598 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800599 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800600
601 uint32_t access_flags = c->GetAccessFlags() & kAccJavaFlagsMask;
602
603 // Set ACC_SUPER; dex files don't contain this flag, but all classes are supposed to have it set.
604 // Class.getModifiers doesn't return it, but JDWP does, so we set it here.
605 access_flags |= kAccSuper;
606
607 expandBufAdd4BE(pReply, access_flags);
608
609 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700610}
611
Elliott Hughes436e3722012-02-17 20:01:47 -0800612JDWP::JdwpError Dbg::GetReflectedType(JDWP::RefTypeId classId, JDWP::ExpandBuf* pReply) {
613 JDWP::JdwpError status;
614 Class* c = DecodeClass(classId, status);
615 if (c == NULL) {
616 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800617 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800618
619 expandBufAdd1(pReply, c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS);
620 expandBufAddRefTypeId(pReply, classId);
621 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700622}
623
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800624void Dbg::GetClassList(std::vector<JDWP::RefTypeId>& classes) {
Elliott Hughesa2155262011-11-16 16:26:58 -0800625 // Get the complete list of reference classes (i.e. all classes except
626 // the primitive types).
627 // Returns a newly-allocated buffer full of RefTypeId values.
628 struct ClassListCreator {
Elliott Hughesba8eee12012-01-24 20:25:24 -0800629 explicit ClassListCreator(std::vector<JDWP::RefTypeId>& classes) : classes(classes) {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800630 }
631
Elliott Hughesa2155262011-11-16 16:26:58 -0800632 static bool Visit(Class* c, void* arg) {
633 return reinterpret_cast<ClassListCreator*>(arg)->Visit(c);
634 }
635
636 bool Visit(Class* c) {
637 if (!c->IsPrimitive()) {
638 classes.push_back(static_cast<JDWP::RefTypeId>(gRegistry->Add(c)));
639 }
640 return true;
641 }
642
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800643 std::vector<JDWP::RefTypeId>& classes;
Elliott Hughesa2155262011-11-16 16:26:58 -0800644 };
645
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800646 ClassListCreator clc(classes);
Elliott Hughesa2155262011-11-16 16:26:58 -0800647 Runtime::Current()->GetClassLinker()->VisitClasses(ClassListCreator::Visit, &clc);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700648}
649
Elliott Hughes436e3722012-02-17 20:01:47 -0800650JDWP::JdwpError Dbg::GetClassInfo(JDWP::RefTypeId classId, JDWP::JdwpTypeTag* pTypeTag, uint32_t* pStatus, std::string* pDescriptor) {
651 JDWP::JdwpError status;
652 Class* c = DecodeClass(classId, status);
653 if (c == NULL) {
654 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800655 }
656
Elliott Hughesa2155262011-11-16 16:26:58 -0800657 if (c->IsArrayClass()) {
658 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
659 *pTypeTag = JDWP::TT_ARRAY;
660 } else {
661 if (c->IsErroneous()) {
662 *pStatus = JDWP::CS_ERROR;
663 } else {
664 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED | JDWP::CS_INITIALIZED;
665 }
666 *pTypeTag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
667 }
668
669 if (pDescriptor != NULL) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800670 *pDescriptor = ClassHelper(c).GetDescriptor();
Elliott Hughesa2155262011-11-16 16:26:58 -0800671 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800672 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700673}
674
Elliott Hughesc3b77c72011-12-15 20:56:48 -0800675void Dbg::FindLoadedClassBySignature(const char* descriptor, std::vector<JDWP::RefTypeId>& ids) {
Elliott Hughes6fa602d2011-12-02 17:54:25 -0800676 std::vector<Class*> classes;
677 Runtime::Current()->GetClassLinker()->LookupClasses(descriptor, classes);
678 ids.clear();
679 for (size_t i = 0; i < classes.size(); ++i) {
680 ids.push_back(gRegistry->Add(classes[i]));
681 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700682}
683
Elliott Hughes2435a572012-02-17 16:07:41 -0800684JDWP::JdwpError Dbg::GetReferenceType(JDWP::ObjectId objectId, JDWP::ExpandBuf* pReply) {
Elliott Hughes499c5132011-11-17 14:55:11 -0800685 Object* o = gRegistry->Get<Object*>(objectId);
Elliott Hughes436e3722012-02-17 20:01:47 -0800686 if (o == NULL || o == kInvalidObject) {
Elliott Hughes2435a572012-02-17 16:07:41 -0800687 return JDWP::ERR_INVALID_OBJECT;
Elliott Hughes499c5132011-11-17 14:55:11 -0800688 }
Elliott Hughes2435a572012-02-17 16:07:41 -0800689
690 JDWP::JdwpTypeTag type_tag;
691 if (o->GetClass()->IsArrayClass()) {
692 type_tag = JDWP::TT_ARRAY;
693 } else if (o->GetClass()->IsInterface()) {
694 type_tag = JDWP::TT_INTERFACE;
695 } else {
696 type_tag = JDWP::TT_CLASS;
697 }
698 JDWP::RefTypeId type_id = gRegistry->Add(o->GetClass());
699
700 expandBufAdd1(pReply, type_tag);
701 expandBufAddRefTypeId(pReply, type_id);
702
703 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700704}
705
Elliott Hughes436e3722012-02-17 20:01:47 -0800706JDWP::JdwpError Dbg::GetSignature(JDWP::RefTypeId classId, std::string& signature) {
Elliott Hughes1fe7afb2012-02-13 17:23:03 -0800707 JDWP::JdwpError status;
Elliott Hughes436e3722012-02-17 20:01:47 -0800708 Class* c = DecodeClass(classId, status);
Elliott Hughes1fe7afb2012-02-13 17:23:03 -0800709 if (c == NULL) {
710 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800711 }
Elliott Hughes1fe7afb2012-02-13 17:23:03 -0800712 signature = ClassHelper(c).GetDescriptor();
713 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700714}
715
Elliott Hughes436e3722012-02-17 20:01:47 -0800716JDWP::JdwpError Dbg::GetSourceFile(JDWP::RefTypeId classId, std::string& result) {
717 JDWP::JdwpError status;
718 Class* c = DecodeClass(classId, status);
719 if (c == NULL) {
720 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800721 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800722 result = ClassHelper(c).GetSourceFile();
723 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700724}
725
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700726uint8_t Dbg::GetObjectTag(JDWP::ObjectId objectId) {
Elliott Hughes24437992011-11-30 14:49:33 -0800727 Object* o = gRegistry->Get<Object*>(objectId);
728 return TagFromObject(o);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700729}
730
Elliott Hughesaed4be92011-12-02 16:16:23 -0800731size_t Dbg::GetTagWidth(JDWP::JdwpTag tag) {
Elliott Hughesdbb40792011-11-18 17:05:22 -0800732 switch (tag) {
733 case JDWP::JT_VOID:
734 return 0;
735 case JDWP::JT_BYTE:
736 case JDWP::JT_BOOLEAN:
737 return 1;
738 case JDWP::JT_CHAR:
739 case JDWP::JT_SHORT:
740 return 2;
741 case JDWP::JT_FLOAT:
742 case JDWP::JT_INT:
743 return 4;
744 case JDWP::JT_ARRAY:
745 case JDWP::JT_OBJECT:
746 case JDWP::JT_STRING:
747 case JDWP::JT_THREAD:
748 case JDWP::JT_THREAD_GROUP:
749 case JDWP::JT_CLASS_LOADER:
750 case JDWP::JT_CLASS_OBJECT:
751 return sizeof(JDWP::ObjectId);
752 case JDWP::JT_DOUBLE:
753 case JDWP::JT_LONG:
754 return 8;
755 default:
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800756 LOG(FATAL) << "Unknown tag " << tag;
Elliott Hughesdbb40792011-11-18 17:05:22 -0800757 return -1;
758 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700759}
760
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800761JDWP::JdwpError Dbg::GetArrayLength(JDWP::ObjectId arrayId, int& length) {
762 JDWP::JdwpError status;
763 Array* a = DecodeArray(arrayId, status);
764 if (a == NULL) {
765 return status;
Elliott Hughes24437992011-11-30 14:49:33 -0800766 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800767 length = a->GetLength();
768 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700769}
770
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800771JDWP::JdwpError Dbg::OutputArray(JDWP::ObjectId arrayId, int offset, int count, JDWP::ExpandBuf* pReply) {
772 JDWP::JdwpError status;
773 Array* a = DecodeArray(arrayId, status);
774 if (a == NULL) {
775 return status;
776 }
Elliott Hughes24437992011-11-30 14:49:33 -0800777
778 if (offset < 0 || count < 0 || offset > a->GetLength() || a->GetLength() - offset < count) {
779 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800780 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughes24437992011-11-30 14:49:33 -0800781 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800782 std::string descriptor(ClassHelper(a->GetClass()).GetDescriptor());
Elliott Hughes24437992011-11-30 14:49:33 -0800783 JDWP::JdwpTag tag = BasicTagFromDescriptor(descriptor.c_str() + 1);
784
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800785 expandBufAdd1(pReply, tag);
786 expandBufAdd4BE(pReply, count);
787
Elliott Hughes24437992011-11-30 14:49:33 -0800788 if (IsPrimitiveTag(tag)) {
789 size_t width = GetTagWidth(tag);
Elliott Hughes24437992011-11-30 14:49:33 -0800790 uint8_t* dst = expandBufAddSpace(pReply, count * width);
791 if (width == 8) {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800792 const uint64_t* src8 = reinterpret_cast<uint64_t*>(a->GetRawData(sizeof(uint64_t)));
Elliott Hughes24437992011-11-30 14:49:33 -0800793 for (int i = 0; i < count; ++i) JDWP::Write8BE(&dst, src8[offset + i]);
794 } else if (width == 4) {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800795 const uint32_t* src4 = reinterpret_cast<uint32_t*>(a->GetRawData(sizeof(uint32_t)));
Elliott Hughes24437992011-11-30 14:49:33 -0800796 for (int i = 0; i < count; ++i) JDWP::Write4BE(&dst, src4[offset + i]);
797 } else if (width == 2) {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800798 const uint16_t* src2 = reinterpret_cast<uint16_t*>(a->GetRawData(sizeof(uint16_t)));
Elliott Hughes24437992011-11-30 14:49:33 -0800799 for (int i = 0; i < count; ++i) JDWP::Write2BE(&dst, src2[offset + i]);
800 } else {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800801 const uint8_t* src = reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint8_t)));
Elliott Hughes24437992011-11-30 14:49:33 -0800802 memcpy(dst, &src[offset * width], count * width);
803 }
804 } else {
805 ObjectArray<Object>* oa = a->AsObjectArray<Object>();
806 for (int i = 0; i < count; ++i) {
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800807 Object* element = oa->Get(offset + i);
Elliott Hughes24437992011-11-30 14:49:33 -0800808 JDWP::JdwpTag specific_tag = (element != NULL) ? TagFromObject(element) : tag;
809 expandBufAdd1(pReply, specific_tag);
810 expandBufAddObjectId(pReply, gRegistry->Add(element));
811 }
812 }
813
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800814 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700815}
816
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800817JDWP::JdwpError Dbg::SetArrayElements(JDWP::ObjectId arrayId, int offset, int count, const uint8_t* src) {
818 JDWP::JdwpError status;
819 Array* a = DecodeArray(arrayId, status);
820 if (a == NULL) {
821 return status;
822 }
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800823
824 if (offset < 0 || count < 0 || offset > a->GetLength() || a->GetLength() - offset < count) {
825 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800826 return JDWP::ERR_INVALID_LENGTH;
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800827 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800828 std::string descriptor(ClassHelper(a->GetClass()).GetDescriptor());
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800829 JDWP::JdwpTag tag = BasicTagFromDescriptor(descriptor.c_str() + 1);
830
831 if (IsPrimitiveTag(tag)) {
832 size_t width = GetTagWidth(tag);
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800833 if (width == 8) {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800834 uint8_t* dst = &(reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint64_t)))[offset * width]);
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800835 for (int i = 0; i < count; ++i) {
836 // Handle potentially non-aligned memory access one byte at a time for ARM's benefit.
837 uint64_t value;
838 for (size_t j = 0; j < sizeof(uint64_t); ++j) reinterpret_cast<uint8_t*>(&value)[j] = src[j];
839 src += sizeof(uint64_t);
840 JDWP::Write8BE(&dst, value);
841 }
842 } else if (width == 4) {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800843 uint8_t* dst = &(reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint32_t)))[offset * width]);
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800844 const uint32_t* src4 = reinterpret_cast<const uint32_t*>(src);
845 for (int i = 0; i < count; ++i) JDWP::Write4BE(&dst, src4[i]);
846 } else if (width == 2) {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800847 uint8_t* dst = &(reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint16_t)))[offset * width]);
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800848 const uint16_t* src2 = reinterpret_cast<const uint16_t*>(src);
849 for (int i = 0; i < count; ++i) JDWP::Write2BE(&dst, src2[i]);
850 } else {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800851 uint8_t* dst = &(reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint8_t)))[offset * width]);
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800852 memcpy(&dst[offset * width], src, count * width);
853 }
854 } else {
855 ObjectArray<Object>* oa = a->AsObjectArray<Object>();
856 for (int i = 0; i < count; ++i) {
857 JDWP::ObjectId id = JDWP::ReadObjectId(&src);
Elliott Hughes436e3722012-02-17 20:01:47 -0800858 Object* o = gRegistry->Get<Object*>(id);
859 if (o == kInvalidObject) {
860 return JDWP::ERR_INVALID_OBJECT;
861 }
862 oa->Set(offset + i, o);
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800863 }
864 }
865
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -0800866 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700867}
868
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800869JDWP::ObjectId Dbg::CreateString(const std::string& str) {
870 return gRegistry->Add(String::AllocFromModifiedUtf8(str.c_str()));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700871}
872
Elliott Hughes436e3722012-02-17 20:01:47 -0800873JDWP::JdwpError Dbg::CreateObject(JDWP::RefTypeId classId, JDWP::ObjectId& new_object) {
874 JDWP::JdwpError status;
875 Class* c = DecodeClass(classId, status);
876 if (c == NULL) {
877 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800878 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800879 new_object = gRegistry->Add(c->AllocObject());
880 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700881}
882
Elliott Hughesbf13d362011-12-08 15:51:37 -0800883/*
884 * Used by Eclipse's "Display" view to evaluate "new byte[5]" to get "(byte[]) [0, 0, 0, 0, 0]".
885 */
Elliott Hughes436e3722012-02-17 20:01:47 -0800886JDWP::JdwpError Dbg::CreateArrayObject(JDWP::RefTypeId arrayClassId, uint32_t length, JDWP::ObjectId& new_array) {
887 JDWP::JdwpError status;
888 Class* c = DecodeClass(arrayClassId, status);
889 if (c == NULL) {
890 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800891 }
Elliott Hughes436e3722012-02-17 20:01:47 -0800892 new_array = gRegistry->Add(Array::Alloc(c, length));
893 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700894}
895
896bool Dbg::MatchType(JDWP::RefTypeId instClassId, JDWP::RefTypeId classId) {
Elliott Hughes436e3722012-02-17 20:01:47 -0800897 JDWP::JdwpError status;
898 Class* c1 = DecodeClass(instClassId, status);
Elliott Hughesa656a0f2012-02-21 18:03:44 -0800899 CHECK(c1 != NULL);
Elliott Hughes436e3722012-02-17 20:01:47 -0800900 Class* c2 = DecodeClass(classId, status);
Elliott Hughesa656a0f2012-02-21 18:03:44 -0800901 CHECK(c2 != NULL);
902 return c1->IsAssignableFrom(c2);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700903}
904
Elliott Hughes86964332012-02-15 19:37:42 -0800905static JDWP::FieldId ToFieldId(const Field* f) {
Elliott Hughes03181a82011-11-17 17:22:21 -0800906#ifdef MOVING_GARBAGE_COLLECTOR
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700907 UNIMPLEMENTED(FATAL);
Elliott Hughes03181a82011-11-17 17:22:21 -0800908#else
909 return static_cast<JDWP::FieldId>(reinterpret_cast<uintptr_t>(f));
910#endif
911}
912
Elliott Hughes86964332012-02-15 19:37:42 -0800913static JDWP::MethodId ToMethodId(const Method* m) {
Elliott Hughes03181a82011-11-17 17:22:21 -0800914#ifdef MOVING_GARBAGE_COLLECTOR
915 UNIMPLEMENTED(FATAL);
916#else
917 return static_cast<JDWP::MethodId>(reinterpret_cast<uintptr_t>(m));
918#endif
919}
920
Elliott Hughes86964332012-02-15 19:37:42 -0800921static Field* FromFieldId(JDWP::FieldId fid) {
Elliott Hughesaed4be92011-12-02 16:16:23 -0800922#ifdef MOVING_GARBAGE_COLLECTOR
923 UNIMPLEMENTED(FATAL);
924#else
925 return reinterpret_cast<Field*>(static_cast<uintptr_t>(fid));
926#endif
927}
928
Elliott Hughes86964332012-02-15 19:37:42 -0800929static Method* FromMethodId(JDWP::MethodId mid) {
Elliott Hughes03181a82011-11-17 17:22:21 -0800930#ifdef MOVING_GARBAGE_COLLECTOR
931 UNIMPLEMENTED(FATAL);
932#else
933 return reinterpret_cast<Method*>(static_cast<uintptr_t>(mid));
934#endif
935}
936
Elliott Hughes86964332012-02-15 19:37:42 -0800937static void SetLocation(JDWP::JdwpLocation& location, Method* m, uintptr_t native_pc) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -0800938 if (m == NULL) {
939 memset(&location, 0, sizeof(location));
940 } else {
941 Class* c = m->GetDeclaringClass();
942 location.typeTag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
943 location.classId = gRegistry->Add(c);
944 location.methodId = ToMethodId(m);
Elliott Hughes972a47b2012-02-21 18:16:06 -0800945 location.dex_pc = m->IsNative() ? -1 : m->ToDexPC(native_pc);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -0800946 }
Elliott Hughesd07986f2011-12-06 18:27:45 -0800947}
948
Elliott Hughes436e3722012-02-17 20:01:47 -0800949std::string Dbg::GetMethodName(JDWP::RefTypeId, JDWP::MethodId methodId) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800950 Method* m = FromMethodId(methodId);
951 return MethodHelper(m).GetName();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700952}
953
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800954/*
955 * Augment the access flags for synthetic methods and fields by setting
956 * the (as described by the spec) "0xf0000000 bit". Also, strip out any
957 * flags not specified by the Java programming language.
958 */
959static uint32_t MangleAccessFlags(uint32_t accessFlags) {
960 accessFlags &= kAccJavaFlagsMask;
961 if ((accessFlags & kAccSynthetic) != 0) {
962 accessFlags |= 0xf0000000;
963 }
964 return accessFlags;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700965}
966
Elliott Hughesdbb40792011-11-18 17:05:22 -0800967static const uint16_t kEclipseWorkaroundSlot = 1000;
968
969/*
970 * Eclipse appears to expect that the "this" reference is in slot zero.
971 * If it's not, the "variables" display will show two copies of "this",
972 * possibly because it gets "this" from SF.ThisObject and then displays
973 * all locals with nonzero slot numbers.
974 *
975 * So, we remap the item in slot 0 to 1000, and remap "this" to zero. On
976 * SF.GetValues / SF.SetValues we map them back.
Elliott Hughesc5b734a2011-12-01 17:20:58 -0800977 *
978 * TODO: jdb uses the value to determine whether a variable is a local or an argument,
979 * by checking whether it's less than the number of arguments. To make that work, we'd
980 * have to "mangle" all the arguments to come first, not just the implicit argument 'this'.
Elliott Hughesdbb40792011-11-18 17:05:22 -0800981 */
982static uint16_t MangleSlot(uint16_t slot, const char* name) {
983 uint16_t newSlot = slot;
984 if (strcmp(name, "this") == 0) {
985 newSlot = 0;
986 } else if (slot == 0) {
987 newSlot = kEclipseWorkaroundSlot;
988 }
989 return newSlot;
990}
991
Elliott Hughes91bf6cd2012-02-14 17:27:48 -0800992static uint16_t DemangleSlot(uint16_t slot, Method* m) {
Elliott Hughesdbb40792011-11-18 17:05:22 -0800993 if (slot == kEclipseWorkaroundSlot) {
Elliott Hughes68fdbd02011-11-29 19:22:47 -0800994 return 0;
Elliott Hughesdbb40792011-11-18 17:05:22 -0800995 } else if (slot == 0) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -0800996 const DexFile::CodeItem* code_item = MethodHelper(m).GetCodeItem();
997 CHECK(code_item != NULL);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800998 return code_item->registers_size_ - code_item->ins_size_;
Elliott Hughesdbb40792011-11-18 17:05:22 -0800999 }
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001000 return slot;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001001}
1002
Elliott Hughes436e3722012-02-17 20:01:47 -08001003JDWP::JdwpError Dbg::OutputDeclaredFields(JDWP::RefTypeId classId, bool with_generic, JDWP::ExpandBuf* pReply) {
1004 JDWP::JdwpError status;
1005 Class* c = DecodeClass(classId, status);
1006 if (c == NULL) {
1007 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001008 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001009
1010 size_t instance_field_count = c->NumInstanceFields();
1011 size_t static_field_count = c->NumStaticFields();
1012
1013 expandBufAdd4BE(pReply, instance_field_count + static_field_count);
1014
1015 for (size_t i = 0; i < instance_field_count + static_field_count; ++i) {
1016 Field* f = (i < instance_field_count) ? c->GetInstanceField(i) : c->GetStaticField(i - instance_field_count);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001017 FieldHelper fh(f);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001018 expandBufAddFieldId(pReply, ToFieldId(f));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001019 expandBufAddUtf8String(pReply, fh.GetName());
1020 expandBufAddUtf8String(pReply, fh.GetTypeDescriptor());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001021 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001022 static const char genericSignature[1] = "";
1023 expandBufAddUtf8String(pReply, genericSignature);
1024 }
1025 expandBufAdd4BE(pReply, MangleAccessFlags(f->GetAccessFlags()));
1026 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001027 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001028}
1029
Elliott Hughes436e3722012-02-17 20:01:47 -08001030JDWP::JdwpError Dbg::OutputDeclaredMethods(JDWP::RefTypeId classId, bool with_generic, JDWP::ExpandBuf* pReply) {
1031 JDWP::JdwpError status;
1032 Class* c = DecodeClass(classId, status);
1033 if (c == NULL) {
1034 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001035 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001036
1037 size_t direct_method_count = c->NumDirectMethods();
1038 size_t virtual_method_count = c->NumVirtualMethods();
1039
1040 expandBufAdd4BE(pReply, direct_method_count + virtual_method_count);
1041
1042 for (size_t i = 0; i < direct_method_count + virtual_method_count; ++i) {
1043 Method* m = (i < direct_method_count) ? c->GetDirectMethod(i) : c->GetVirtualMethod(i - direct_method_count);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001044 MethodHelper mh(m);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001045 expandBufAddMethodId(pReply, ToMethodId(m));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001046 expandBufAddUtf8String(pReply, mh.GetName());
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001047 expandBufAddUtf8String(pReply, mh.GetSignature());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001048 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001049 static const char genericSignature[1] = "";
1050 expandBufAddUtf8String(pReply, genericSignature);
1051 }
1052 expandBufAdd4BE(pReply, MangleAccessFlags(m->GetAccessFlags()));
1053 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001054 return JDWP::ERR_NONE;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001055}
1056
Elliott Hughes436e3722012-02-17 20:01:47 -08001057JDWP::JdwpError Dbg::OutputDeclaredInterfaces(JDWP::RefTypeId classId, JDWP::ExpandBuf* pReply) {
1058 JDWP::JdwpError status;
1059 Class* c = DecodeClass(classId, status);
1060 if (c == NULL) {
1061 return status;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001062 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001063
1064 ClassHelper kh(c);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001065 size_t interface_count = kh.NumInterfaces();
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001066 expandBufAdd4BE(pReply, interface_count);
1067 for (size_t i = 0; i < interface_count; ++i) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001068 expandBufAddRefTypeId(pReply, gRegistry->Add(kh.GetInterface(i)));
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001069 }
Elliott Hughes436e3722012-02-17 20:01:47 -08001070 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001071}
1072
Elliott Hughes436e3722012-02-17 20:01:47 -08001073void Dbg::OutputLineTable(JDWP::RefTypeId, JDWP::MethodId methodId, JDWP::ExpandBuf* pReply) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001074 struct DebugCallbackContext {
1075 int numItems;
1076 JDWP::ExpandBuf* pReply;
1077
Elliott Hughes2435a572012-02-17 16:07:41 -08001078 static bool Callback(void* context, uint32_t address, uint32_t line_number) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001079 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
1080 expandBufAdd8BE(pContext->pReply, address);
Elliott Hughes2435a572012-02-17 16:07:41 -08001081 expandBufAdd4BE(pContext->pReply, line_number);
Elliott Hughes03181a82011-11-17 17:22:21 -08001082 pContext->numItems++;
1083 return true;
1084 }
1085 };
1086
1087 Method* m = FromMethodId(methodId);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001088 MethodHelper mh(m);
Elliott Hughes03181a82011-11-17 17:22:21 -08001089 uint64_t start, end;
1090 if (m->IsNative()) {
1091 start = -1;
1092 end = -1;
1093 } else {
1094 start = 0;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001095 // TODO: what are the units supposed to be? *2?
1096 end = mh.GetCodeItem()->insns_size_in_code_units_;
Elliott Hughes03181a82011-11-17 17:22:21 -08001097 }
1098
1099 expandBufAdd8BE(pReply, start);
1100 expandBufAdd8BE(pReply, end);
1101
1102 // Add numLines later
1103 size_t numLinesOffset = expandBufGetLength(pReply);
1104 expandBufAdd4BE(pReply, 0);
1105
1106 DebugCallbackContext context;
1107 context.numItems = 0;
1108 context.pReply = pReply;
1109
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001110 mh.GetDexFile().DecodeDebugInfo(mh.GetCodeItem(), m->IsStatic(), m->GetDexMethodIndex(),
1111 DebugCallbackContext::Callback, NULL, &context);
Elliott Hughes03181a82011-11-17 17:22:21 -08001112
1113 JDWP::Set4BE(expandBufGetBuffer(pReply) + numLinesOffset, context.numItems);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001114}
1115
Elliott Hughes436e3722012-02-17 20:01:47 -08001116void Dbg::OutputVariableTable(JDWP::RefTypeId, JDWP::MethodId methodId, bool with_generic, JDWP::ExpandBuf* pReply) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001117 struct DebugCallbackContext {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001118 JDWP::ExpandBuf* pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001119 size_t variable_count;
1120 bool with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001121
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001122 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 -08001123 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
1124
Elliott Hughesad3da692012-02-24 16:51:35 -08001125 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 -08001126
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001127 slot = MangleSlot(slot, name);
1128
Elliott Hughesdbb40792011-11-18 17:05:22 -08001129 expandBufAdd8BE(pContext->pReply, startAddress);
1130 expandBufAddUtf8String(pContext->pReply, name);
1131 expandBufAddUtf8String(pContext->pReply, descriptor);
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001132 if (pContext->with_generic) {
Elliott Hughesdbb40792011-11-18 17:05:22 -08001133 expandBufAddUtf8String(pContext->pReply, signature);
1134 }
1135 expandBufAdd4BE(pContext->pReply, endAddress - startAddress);
1136 expandBufAdd4BE(pContext->pReply, slot);
1137
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001138 ++pContext->variable_count;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001139 }
1140 };
1141
1142 Method* m = FromMethodId(methodId);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001143 MethodHelper mh(m);
1144 const DexFile::CodeItem* code_item = mh.GetCodeItem();
Elliott Hughesdbb40792011-11-18 17:05:22 -08001145
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001146 // arg_count considers doubles and longs to take 2 units.
1147 // variable_count considers everything to take 1 unit.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001148 std::string shorty(mh.GetShorty());
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001149 expandBufAdd4BE(pReply, m->NumArgRegisters(shorty));
Elliott Hughesdbb40792011-11-18 17:05:22 -08001150
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001151 // We don't know the total number of variables yet, so leave a blank and update it later.
1152 size_t variable_count_offset = expandBufGetLength(pReply);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001153 expandBufAdd4BE(pReply, 0);
1154
1155 DebugCallbackContext context;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001156 context.pReply = pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001157 context.variable_count = 0;
1158 context.with_generic = with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001159
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001160 mh.GetDexFile().DecodeDebugInfo(code_item, m->IsStatic(), m->GetDexMethodIndex(), NULL,
1161 DebugCallbackContext::Callback, &context);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001162
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001163 JDWP::Set4BE(expandBufGetBuffer(pReply) + variable_count_offset, context.variable_count);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001164}
1165
Elliott Hughesaed4be92011-12-02 16:16:23 -08001166JDWP::JdwpTag Dbg::GetFieldBasicTag(JDWP::FieldId fieldId) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001167 return BasicTagFromDescriptor(FieldHelper(FromFieldId(fieldId)).GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001168}
1169
Elliott Hughesaed4be92011-12-02 16:16:23 -08001170JDWP::JdwpTag Dbg::GetStaticFieldBasicTag(JDWP::FieldId fieldId) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001171 return BasicTagFromDescriptor(FieldHelper(FromFieldId(fieldId)).GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001172}
1173
Elliott Hughes0cf74332012-02-23 23:14:00 -08001174static JDWP::JdwpError GetFieldValueImpl(JDWP::RefTypeId refTypeId, JDWP::ObjectId objectId, JDWP::FieldId fieldId, JDWP::ExpandBuf* pReply, bool is_static) {
1175 JDWP::JdwpError status;
1176 Class* c = DecodeClass(refTypeId, status);
1177 if (refTypeId != 0 && c == NULL) {
1178 return status;
1179 }
1180
Elliott Hughesaed4be92011-12-02 16:16:23 -08001181 Object* o = gRegistry->Get<Object*>(objectId);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001182 if ((!is_static && o == NULL) || o == kInvalidObject) {
1183 return JDWP::ERR_INVALID_OBJECT;
1184 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001185 Field* f = FromFieldId(fieldId);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001186
1187 Class* receiver_class = c;
1188 if (receiver_class == NULL && o != NULL) {
1189 receiver_class = o->GetClass();
1190 }
1191 // TODO: should we give up now if receiver_class is NULL?
1192 if (receiver_class != NULL && !f->GetDeclaringClass()->IsAssignableFrom(receiver_class)) {
1193 LOG(INFO) << "ERR_INVALID_FIELDID: " << PrettyField(f) << " " << PrettyClass(receiver_class);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001194 return JDWP::ERR_INVALID_FIELDID;
1195 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001196
Elliott Hughes0cf74332012-02-23 23:14:00 -08001197 // The RI only enforces the static/non-static mismatch in one direction.
1198 // TODO: should we change the tests and check both?
1199 if (is_static) {
1200 if (!f->IsStatic()) {
1201 return JDWP::ERR_INVALID_FIELDID;
1202 }
1203 } else {
1204 if (f->IsStatic()) {
1205 LOG(WARNING) << "Ignoring non-NULL receiver for ObjectReference.SetValues on static field " << PrettyField(f);
1206 o = NULL;
1207 }
1208 }
1209
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001210 JDWP::JdwpTag tag = BasicTagFromDescriptor(FieldHelper(f).GetTypeDescriptor());
Elliott Hughesaed4be92011-12-02 16:16:23 -08001211
1212 if (IsPrimitiveTag(tag)) {
1213 expandBufAdd1(pReply, tag);
1214 if (tag == JDWP::JT_BOOLEAN || tag == JDWP::JT_BYTE) {
1215 expandBufAdd1(pReply, f->Get32(o));
1216 } else if (tag == JDWP::JT_CHAR || tag == JDWP::JT_SHORT) {
1217 expandBufAdd2BE(pReply, f->Get32(o));
1218 } else if (tag == JDWP::JT_FLOAT || tag == JDWP::JT_INT) {
1219 expandBufAdd4BE(pReply, f->Get32(o));
1220 } else if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
1221 expandBufAdd8BE(pReply, f->Get64(o));
1222 } else {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001223 LOG(FATAL) << "Unknown tag: " << tag;
Elliott Hughesaed4be92011-12-02 16:16:23 -08001224 }
1225 } else {
1226 Object* value = f->GetObject(o);
1227 expandBufAdd1(pReply, TagFromObject(value));
1228 expandBufAddObjectId(pReply, gRegistry->Add(value));
1229 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001230 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001231}
1232
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001233JDWP::JdwpError Dbg::GetFieldValue(JDWP::ObjectId objectId, JDWP::FieldId fieldId, JDWP::ExpandBuf* pReply) {
Elliott Hughes0cf74332012-02-23 23:14:00 -08001234 return GetFieldValueImpl(0, objectId, fieldId, pReply, false);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001235}
1236
Elliott Hughes0cf74332012-02-23 23:14:00 -08001237JDWP::JdwpError Dbg::GetStaticFieldValue(JDWP::RefTypeId refTypeId, JDWP::FieldId fieldId, JDWP::ExpandBuf* pReply) {
1238 return GetFieldValueImpl(refTypeId, 0, fieldId, pReply, true);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001239}
1240
1241static JDWP::JdwpError SetFieldValueImpl(JDWP::ObjectId objectId, JDWP::FieldId fieldId, uint64_t value, int width, bool is_static) {
Elliott Hughesaed4be92011-12-02 16:16:23 -08001242 Object* o = gRegistry->Get<Object*>(objectId);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001243 if ((!is_static && o == NULL) || o == kInvalidObject) {
1244 return JDWP::ERR_INVALID_OBJECT;
1245 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001246 Field* f = FromFieldId(fieldId);
Elliott Hughes0cf74332012-02-23 23:14:00 -08001247
1248 // The RI only enforces the static/non-static mismatch in one direction.
1249 // TODO: should we change the tests and check both?
1250 if (is_static) {
1251 if (!f->IsStatic()) {
1252 return JDWP::ERR_INVALID_FIELDID;
1253 }
1254 } else {
1255 if (f->IsStatic()) {
1256 LOG(WARNING) << "Ignoring non-NULL receiver for ObjectReference.SetValues on static field " << PrettyField(f);
1257 o = NULL;
1258 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001259 }
Elliott Hughesaed4be92011-12-02 16:16:23 -08001260
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001261 JDWP::JdwpTag tag = BasicTagFromDescriptor(FieldHelper(f).GetTypeDescriptor());
Elliott Hughesaed4be92011-12-02 16:16:23 -08001262
1263 if (IsPrimitiveTag(tag)) {
1264 if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001265 CHECK_EQ(width, 8);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001266 f->Set64(o, value);
1267 } else {
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001268 CHECK_LE(width, 4);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001269 f->Set32(o, value);
1270 }
1271 } else {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001272 Object* v = gRegistry->Get<Object*>(value);
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001273 if (v == kInvalidObject) {
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001274 return JDWP::ERR_INVALID_OBJECT;
1275 }
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001276 if (v != NULL) {
1277 Class* field_type = FieldHelper(f).GetType();
1278 if (!field_type->IsAssignableFrom(v->GetClass())) {
1279 return JDWP::ERR_INVALID_OBJECT;
1280 }
1281 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001282 f->SetObject(o, v);
Elliott Hughesaed4be92011-12-02 16:16:23 -08001283 }
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001284
1285 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001286}
1287
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001288JDWP::JdwpError Dbg::SetFieldValue(JDWP::ObjectId objectId, JDWP::FieldId fieldId, uint64_t value, int width) {
1289 return SetFieldValueImpl(objectId, fieldId, value, width, false);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001290}
1291
Elliott Hughes3d1ca6d2012-02-13 15:43:19 -08001292JDWP::JdwpError Dbg::SetStaticFieldValue(JDWP::FieldId fieldId, uint64_t value, int width) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08001293 return SetFieldValueImpl(0, fieldId, value, width, true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001294}
1295
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001296std::string Dbg::StringToUtf8(JDWP::ObjectId strId) {
1297 String* s = gRegistry->Get<String*>(strId);
1298 return s->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001299}
1300
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001301bool Dbg::GetThreadName(JDWP::ObjectId threadId, std::string& name) {
1302 ScopedThreadListLock thread_list_lock;
1303 Thread* thread = DecodeThread(threadId);
1304 if (thread == NULL) {
1305 return false;
1306 }
Elliott Hughesffb465f2012-03-01 18:46:05 -08001307 thread->GetThreadName(name);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001308 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001309}
1310
Elliott Hughes2435a572012-02-17 16:07:41 -08001311JDWP::JdwpError Dbg::GetThreadGroup(JDWP::ObjectId threadId, JDWP::ExpandBuf* pReply) {
Elliott Hughes499c5132011-11-17 14:55:11 -08001312 Object* thread = gRegistry->Get<Object*>(threadId);
Elliott Hughes436e3722012-02-17 20:01:47 -08001313 if (thread == kInvalidObject) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001314 return JDWP::ERR_INVALID_OBJECT;
1315 }
1316
1317 // Okay, so it's an object, but is it actually a thread?
Elliott Hughes436e3722012-02-17 20:01:47 -08001318 if (DecodeThread(threadId) == NULL) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001319 return JDWP::ERR_INVALID_THREAD;
1320 }
Elliott Hughes499c5132011-11-17 14:55:11 -08001321
1322 Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/Thread;");
1323 CHECK(c != NULL);
1324 Field* f = c->FindInstanceField("group", "Ljava/lang/ThreadGroup;");
1325 CHECK(f != NULL);
1326 Object* group = f->GetObject(thread);
1327 CHECK(group != NULL);
Elliott Hughes2435a572012-02-17 16:07:41 -08001328 JDWP::ObjectId thread_group_id = gRegistry->Add(group);
1329
1330 expandBufAddObjectId(pReply, thread_group_id);
1331 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001332}
1333
Elliott Hughes499c5132011-11-17 14:55:11 -08001334std::string Dbg::GetThreadGroupName(JDWP::ObjectId threadGroupId) {
1335 Object* thread_group = gRegistry->Get<Object*>(threadGroupId);
1336 CHECK(thread_group != NULL);
1337
1338 Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/ThreadGroup;");
1339 CHECK(c != NULL);
1340 Field* f = c->FindInstanceField("name", "Ljava/lang/String;");
1341 CHECK(f != NULL);
1342 String* s = reinterpret_cast<String*>(f->GetObject(thread_group));
1343 return s->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001344}
1345
1346JDWP::ObjectId Dbg::GetThreadGroupParent(JDWP::ObjectId threadGroupId) {
Elliott Hughes4e235312011-12-02 11:34:15 -08001347 Object* thread_group = gRegistry->Get<Object*>(threadGroupId);
1348 CHECK(thread_group != NULL);
1349
1350 Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/ThreadGroup;");
1351 CHECK(c != NULL);
1352 Field* f = c->FindInstanceField("parent", "Ljava/lang/ThreadGroup;");
1353 CHECK(f != NULL);
1354 Object* parent = f->GetObject(thread_group);
1355 return gRegistry->Add(parent);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001356}
1357
Elliott Hughes499c5132011-11-17 14:55:11 -08001358static Object* GetStaticThreadGroup(const char* field_name) {
1359 Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/ThreadGroup;");
1360 CHECK(c != NULL);
1361 Field* f = c->FindStaticField(field_name, "Ljava/lang/ThreadGroup;");
1362 CHECK(f != NULL);
1363 Object* group = f->GetObject(NULL);
1364 CHECK(group != NULL);
1365 return group;
1366}
1367
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001368JDWP::ObjectId Dbg::GetSystemThreadGroupId() {
Elliott Hughes499c5132011-11-17 14:55:11 -08001369 return gRegistry->Add(GetStaticThreadGroup("mSystem"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001370}
1371
1372JDWP::ObjectId Dbg::GetMainThreadGroupId() {
Elliott Hughes499c5132011-11-17 14:55:11 -08001373 return gRegistry->Add(GetStaticThreadGroup("mMain"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001374}
1375
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001376bool Dbg::GetThreadStatus(JDWP::ObjectId threadId, JDWP::JdwpThreadStatus* pThreadStatus, JDWP::JdwpSuspendStatus* pSuspendStatus) {
Elliott Hughes499c5132011-11-17 14:55:11 -08001377 ScopedThreadListLock thread_list_lock;
1378
1379 Thread* thread = DecodeThread(threadId);
1380 if (thread == NULL) {
1381 return false;
1382 }
1383
Elliott Hughes3ce4b262012-02-24 11:24:02 -08001384 // TODO: if we're in Thread.sleep(long), we should return TS_SLEEPING,
1385 // even if it's implemented using Object.wait(long).
Elliott Hughes499c5132011-11-17 14:55:11 -08001386 switch (thread->GetState()) {
1387 case Thread::kTerminated: *pThreadStatus = JDWP::TS_ZOMBIE; break;
1388 case Thread::kRunnable: *pThreadStatus = JDWP::TS_RUNNING; break;
Elliott Hughes3ce4b262012-02-24 11:24:02 -08001389 case Thread::kTimedWaiting: *pThreadStatus = JDWP::TS_WAIT; break;
Elliott Hughes499c5132011-11-17 14:55:11 -08001390 case Thread::kBlocked: *pThreadStatus = JDWP::TS_MONITOR; break;
1391 case Thread::kWaiting: *pThreadStatus = JDWP::TS_WAIT; break;
1392 case Thread::kInitializing: *pThreadStatus = JDWP::TS_ZOMBIE; break;
1393 case Thread::kStarting: *pThreadStatus = JDWP::TS_ZOMBIE; break;
1394 case Thread::kNative: *pThreadStatus = JDWP::TS_RUNNING; break;
1395 case Thread::kVmWait: *pThreadStatus = JDWP::TS_WAIT; break;
1396 case Thread::kSuspended: *pThreadStatus = JDWP::TS_RUNNING; break;
1397 default:
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001398 LOG(FATAL) << "Unknown thread state " << thread->GetState();
Elliott Hughes499c5132011-11-17 14:55:11 -08001399 }
1400
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001401 *pSuspendStatus = (thread->IsSuspended() ? JDWP::SUSPEND_STATUS_SUSPENDED : JDWP::SUSPEND_STATUS_NOT_SUSPENDED);
Elliott Hughes499c5132011-11-17 14:55:11 -08001402
1403 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001404}
1405
Elliott Hughes2435a572012-02-17 16:07:41 -08001406JDWP::JdwpError Dbg::GetThreadSuspendCount(JDWP::ObjectId threadId, JDWP::ExpandBuf* pReply) {
1407 Thread* thread = DecodeThread(threadId);
1408 if (thread == NULL) {
1409 return JDWP::ERR_INVALID_THREAD;
1410 }
1411 expandBufAdd4BE(pReply, thread->GetSuspendCount());
1412 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001413}
1414
1415bool Dbg::ThreadExists(JDWP::ObjectId threadId) {
Elliott Hughes761928d2011-11-16 18:33:03 -08001416 return DecodeThread(threadId) != NULL;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001417}
1418
1419bool Dbg::IsSuspended(JDWP::ObjectId threadId) {
Elliott Hughes761928d2011-11-16 18:33:03 -08001420 return DecodeThread(threadId)->IsSuspended();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001421}
1422
Elliott Hughesa2155262011-11-16 16:26:58 -08001423void Dbg::GetThreadGroupThreadsImpl(Object* thread_group, JDWP::ObjectId** ppThreadIds, uint32_t* pThreadCount) {
1424 struct ThreadListVisitor {
1425 static void Visit(Thread* t, void* arg) {
1426 reinterpret_cast<ThreadListVisitor*>(arg)->Visit(t);
1427 }
1428
1429 void Visit(Thread* t) {
1430 if (t == Dbg::GetDebugThread()) {
1431 // Skip the JDWP thread. Some debuggers get bent out of shape when they can't suspend and
1432 // query all threads, so it's easier if we just don't tell them about this thread.
1433 return;
1434 }
1435 if (thread_group == NULL || t->GetThreadGroup() == thread_group) {
1436 threads.push_back(gRegistry->Add(t->GetPeer()));
1437 }
1438 }
1439
1440 Object* thread_group;
1441 std::vector<JDWP::ObjectId> threads;
1442 };
1443
1444 ThreadListVisitor tlv;
1445 tlv.thread_group = thread_group;
1446
1447 {
1448 ScopedThreadListLock thread_list_lock;
1449 Runtime::Current()->GetThreadList()->ForEach(ThreadListVisitor::Visit, &tlv);
1450 }
1451
1452 *pThreadCount = tlv.threads.size();
1453 if (*pThreadCount == 0) {
1454 *ppThreadIds = NULL;
1455 } else {
1456 *ppThreadIds = new JDWP::ObjectId[*pThreadCount];
1457 for (size_t i = 0; i < *pThreadCount; ++i) {
1458 (*ppThreadIds)[i] = tlv.threads[i];
1459 }
1460 }
1461}
1462
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001463void Dbg::GetThreadGroupThreads(JDWP::ObjectId threadGroupId, JDWP::ObjectId** ppThreadIds, uint32_t* pThreadCount) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001464 GetThreadGroupThreadsImpl(gRegistry->Get<Object*>(threadGroupId), ppThreadIds, pThreadCount);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001465}
1466
1467void Dbg::GetAllThreads(JDWP::ObjectId** ppThreadIds, uint32_t* pThreadCount) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001468 GetThreadGroupThreadsImpl(NULL, ppThreadIds, pThreadCount);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001469}
1470
Elliott Hughes86964332012-02-15 19:37:42 -08001471static int GetStackDepth(Thread* thread) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001472 struct CountStackDepthVisitor : public Thread::StackVisitor {
1473 CountStackDepthVisitor() : depth(0) {}
Elliott Hughes530fa002012-03-12 11:44:49 -07001474 bool VisitFrame(const Frame& f, uintptr_t) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -08001475 if (f.HasMethod()) {
1476 ++depth;
1477 }
Elliott Hughes530fa002012-03-12 11:44:49 -07001478 return true;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001479 }
1480 size_t depth;
1481 };
1482 CountStackDepthVisitor visitor;
Elliott Hughes86964332012-02-15 19:37:42 -08001483 thread->WalkStack(&visitor);
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001484 return visitor.depth;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001485}
1486
Elliott Hughes86964332012-02-15 19:37:42 -08001487int Dbg::GetThreadFrameCount(JDWP::ObjectId threadId) {
1488 ScopedThreadListLock thread_list_lock;
1489 return GetStackDepth(DecodeThread(threadId));
1490}
1491
Elliott Hughes530fa002012-03-12 11:44:49 -07001492void Dbg::GetThreadFrame(JDWP::ObjectId threadId, int desired_frame_number, JDWP::FrameId* pFrameId, JDWP::JdwpLocation* pLoc) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001493 ScopedThreadListLock thread_list_lock;
1494 struct GetFrameVisitor : public Thread::StackVisitor {
1495 GetFrameVisitor(int desired_frame_number, JDWP::FrameId* pFrameId, JDWP::JdwpLocation* pLoc)
Elliott Hughes530fa002012-03-12 11:44:49 -07001496 : depth(0), desired_frame_number(desired_frame_number), pFrameId(pFrameId), pLoc(pLoc) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001497 }
Elliott Hughes530fa002012-03-12 11:44:49 -07001498 bool VisitFrame(const Frame& f, uintptr_t pc) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001499 if (!f.HasMethod()) {
Elliott Hughes530fa002012-03-12 11:44:49 -07001500 return true; // The debugger can't do anything useful with a frame that has no Method*.
Elliott Hughes03181a82011-11-17 17:22:21 -08001501 }
Elliott Hughes03181a82011-11-17 17:22:21 -08001502 if (depth == desired_frame_number) {
1503 *pFrameId = reinterpret_cast<JDWP::FrameId>(f.GetSP());
Elliott Hughesd07986f2011-12-06 18:27:45 -08001504 SetLocation(*pLoc, f.GetMethod(), pc);
Elliott Hughes530fa002012-03-12 11:44:49 -07001505 return false;
Elliott Hughes03181a82011-11-17 17:22:21 -08001506 }
1507 ++depth;
Elliott Hughes530fa002012-03-12 11:44:49 -07001508 return true;
Elliott Hughes03181a82011-11-17 17:22:21 -08001509 }
Elliott Hughes03181a82011-11-17 17:22:21 -08001510 int depth;
1511 int desired_frame_number;
1512 JDWP::FrameId* pFrameId;
1513 JDWP::JdwpLocation* pLoc;
1514 };
1515 GetFrameVisitor visitor(desired_frame_number, pFrameId, pLoc);
1516 visitor.desired_frame_number = desired_frame_number;
1517 DecodeThread(threadId)->WalkStack(&visitor);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001518}
1519
1520JDWP::ObjectId Dbg::GetThreadSelfId() {
Elliott Hughes475fc232011-10-25 15:00:35 -07001521 return gRegistry->Add(Thread::Current()->GetPeer());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001522}
1523
Elliott Hughes475fc232011-10-25 15:00:35 -07001524void Dbg::SuspendVM() {
Elliott Hughesa2155262011-11-16 16:26:58 -08001525 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 -07001526 Runtime::Current()->GetThreadList()->SuspendAll(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001527}
1528
1529void Dbg::ResumeVM() {
Elliott Hughes475fc232011-10-25 15:00:35 -07001530 Runtime::Current()->GetThreadList()->ResumeAll(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001531}
1532
1533void Dbg::SuspendThread(JDWP::ObjectId threadId) {
Elliott Hughes4e235312011-12-02 11:34:15 -08001534 Object* peer = gRegistry->Get<Object*>(threadId);
1535 ScopedThreadListLock thread_list_lock;
1536 Thread* thread = Thread::FromManagedThread(peer);
1537 if (thread == NULL) {
1538 LOG(WARNING) << "No such thread for suspend: " << peer;
1539 return;
1540 }
1541 Runtime::Current()->GetThreadList()->Suspend(thread, true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001542}
1543
1544void Dbg::ResumeThread(JDWP::ObjectId threadId) {
Elliott Hughes4e235312011-12-02 11:34:15 -08001545 Object* peer = gRegistry->Get<Object*>(threadId);
1546 ScopedThreadListLock thread_list_lock;
1547 Thread* thread = Thread::FromManagedThread(peer);
1548 if (thread == NULL) {
1549 LOG(WARNING) << "No such thread for resume: " << peer;
1550 return;
1551 }
1552 Runtime::Current()->GetThreadList()->Resume(thread, true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001553}
1554
1555void Dbg::SuspendSelf() {
Elliott Hughes475fc232011-10-25 15:00:35 -07001556 Runtime::Current()->GetThreadList()->SuspendSelfForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001557}
1558
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001559static Object* GetThis(Frame& f) {
Elliott Hughes86b00102011-12-05 17:54:26 -08001560 Method* m = f.GetMethod();
Elliott Hughes86b00102011-12-05 17:54:26 -08001561 Object* o = NULL;
1562 if (!m->IsNative() && !m->IsStatic()) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001563 uint16_t reg = DemangleSlot(0, m);
Elliott Hughes86b00102011-12-05 17:54:26 -08001564 o = reinterpret_cast<Object*>(f.GetVReg(m, reg));
1565 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001566 return o;
1567}
1568
1569void Dbg::GetThisObject(JDWP::FrameId frameId, JDWP::ObjectId* pThisId) {
1570 Method** sp = reinterpret_cast<Method**>(frameId);
1571 Frame f(sp);
1572 Object* o = GetThis(f);
Elliott Hughes86b00102011-12-05 17:54:26 -08001573 *pThisId = gRegistry->Add(o);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001574}
1575
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001576void 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 -08001577 Method** sp = reinterpret_cast<Method**>(frameId);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001578 Frame f(sp);
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001579 Method* m = f.GetMethod();
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001580 uint16_t reg = DemangleSlot(slot, m);
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001581
1582 const VmapTable vmap_table(m->GetVmapTableRaw());
1583 uint32_t vmap_offset;
1584 if (vmap_table.IsInContext(reg, vmap_offset)) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001585 UNIMPLEMENTED(FATAL) << "Don't know how to pull locals from callee save frames: " << vmap_offset;
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001586 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001587
Elliott Hughesad3da692012-02-24 16:51:35 -08001588 // TODO: check that the tag is compatible with the actual type of the slot!
1589
Elliott Hughesdbb40792011-11-18 17:05:22 -08001590 switch (tag) {
1591 case JDWP::JT_BOOLEAN:
1592 {
Elliott Hughescccd84f2011-12-05 16:51:54 -08001593 CHECK_EQ(width, 1U);
Elliott Hughes1bba14f2011-12-01 18:00:36 -08001594 uint32_t intVal = f.GetVReg(m, reg);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001595 VLOG(jdwp) << "get boolean local " << reg << " = " << intVal;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001596 JDWP::Set1(buf+1, intVal != 0);
1597 }
1598 break;
1599 case JDWP::JT_BYTE:
1600 {
Elliott Hughescccd84f2011-12-05 16:51:54 -08001601 CHECK_EQ(width, 1U);
Elliott Hughes1bba14f2011-12-01 18:00:36 -08001602 uint32_t intVal = f.GetVReg(m, reg);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001603 VLOG(jdwp) << "get byte local " << reg << " = " << intVal;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001604 JDWP::Set1(buf+1, intVal);
1605 }
1606 break;
1607 case JDWP::JT_SHORT:
1608 case JDWP::JT_CHAR:
1609 {
Elliott Hughescccd84f2011-12-05 16:51:54 -08001610 CHECK_EQ(width, 2U);
Elliott Hughes1bba14f2011-12-01 18:00:36 -08001611 uint32_t intVal = f.GetVReg(m, reg);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001612 VLOG(jdwp) << "get short/char local " << reg << " = " << intVal;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001613 JDWP::Set2BE(buf+1, intVal);
1614 }
1615 break;
1616 case JDWP::JT_INT:
1617 case JDWP::JT_FLOAT:
1618 {
Elliott Hughescccd84f2011-12-05 16:51:54 -08001619 CHECK_EQ(width, 4U);
Elliott Hughes1bba14f2011-12-01 18:00:36 -08001620 uint32_t intVal = f.GetVReg(m, reg);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001621 VLOG(jdwp) << "get int/float local " << reg << " = " << intVal;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001622 JDWP::Set4BE(buf+1, intVal);
1623 }
1624 break;
1625 case JDWP::JT_ARRAY:
1626 {
Elliott Hughescccd84f2011-12-05 16:51:54 -08001627 CHECK_EQ(width, sizeof(JDWP::ObjectId));
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001628 Object* o = reinterpret_cast<Object*>(f.GetVReg(m, reg));
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001629 VLOG(jdwp) << "get array local " << reg << " = " << o;
Elliott Hughes88c5c352012-03-15 18:49:48 -07001630 if (!Runtime::Current()->GetHeap()->IsHeapAddress(o)) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001631 LOG(FATAL) << "Register " << reg << " expected to hold array: " << o;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001632 }
1633 JDWP::SetObjectId(buf+1, gRegistry->Add(o));
1634 }
1635 break;
Elliott Hughesad3da692012-02-24 16:51:35 -08001636 case JDWP::JT_CLASS_LOADER:
1637 case JDWP::JT_CLASS_OBJECT:
Elliott Hughesdbb40792011-11-18 17:05:22 -08001638 case JDWP::JT_OBJECT:
Elliott Hughesad3da692012-02-24 16:51:35 -08001639 case JDWP::JT_STRING:
1640 case JDWP::JT_THREAD:
1641 case JDWP::JT_THREAD_GROUP:
Elliott Hughesdbb40792011-11-18 17:05:22 -08001642 {
Elliott Hughescccd84f2011-12-05 16:51:54 -08001643 CHECK_EQ(width, sizeof(JDWP::ObjectId));
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001644 Object* o = reinterpret_cast<Object*>(f.GetVReg(m, reg));
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001645 VLOG(jdwp) << "get object local " << reg << " = " << o;
Elliott Hughes88c5c352012-03-15 18:49:48 -07001646 if (!Runtime::Current()->GetHeap()->IsHeapAddress(o)) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001647 LOG(FATAL) << "Register " << reg << " expected to hold object: " << o;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001648 }
1649 tag = TagFromObject(o);
1650 JDWP::SetObjectId(buf+1, gRegistry->Add(o));
1651 }
1652 break;
1653 case JDWP::JT_DOUBLE:
1654 case JDWP::JT_LONG:
1655 {
Elliott Hughescccd84f2011-12-05 16:51:54 -08001656 CHECK_EQ(width, 8U);
Elliott Hughes1bba14f2011-12-01 18:00:36 -08001657 uint32_t lo = f.GetVReg(m, reg);
1658 uint64_t hi = f.GetVReg(m, reg + 1);
1659 uint64_t longVal = (hi << 32) | lo;
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001660 VLOG(jdwp) << "get double/long local " << hi << ":" << lo << " = " << longVal;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001661 JDWP::Set8BE(buf+1, longVal);
1662 }
1663 break;
1664 default:
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001665 LOG(FATAL) << "Unknown tag " << tag;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001666 break;
1667 }
1668
1669 // Prepend tag, which may have been updated.
1670 JDWP::Set1(buf, tag);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001671}
1672
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001673void 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 -08001674 Method** sp = reinterpret_cast<Method**>(frameId);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001675 Frame f(sp);
Elliott Hughescccd84f2011-12-05 16:51:54 -08001676 Method* m = f.GetMethod();
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001677 uint16_t reg = DemangleSlot(slot, m);
Elliott Hughescccd84f2011-12-05 16:51:54 -08001678
1679 const VmapTable vmap_table(m->GetVmapTableRaw());
1680 uint32_t vmap_offset;
1681 if (vmap_table.IsInContext(reg, vmap_offset)) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001682 UNIMPLEMENTED(FATAL) << "Don't know how to pull locals from callee save frames: " << vmap_offset;
Elliott Hughescccd84f2011-12-05 16:51:54 -08001683 }
1684
Elliott Hughesad3da692012-02-24 16:51:35 -08001685 // TODO: check that the tag is compatible with the actual type of the slot!
1686
Elliott Hughescccd84f2011-12-05 16:51:54 -08001687 switch (tag) {
1688 case JDWP::JT_BOOLEAN:
1689 case JDWP::JT_BYTE:
1690 CHECK_EQ(width, 1U);
1691 f.SetVReg(m, reg, static_cast<uint32_t>(value));
1692 break;
1693 case JDWP::JT_SHORT:
1694 case JDWP::JT_CHAR:
1695 CHECK_EQ(width, 2U);
1696 f.SetVReg(m, reg, static_cast<uint32_t>(value));
1697 break;
1698 case JDWP::JT_INT:
1699 case JDWP::JT_FLOAT:
1700 CHECK_EQ(width, 4U);
1701 f.SetVReg(m, reg, static_cast<uint32_t>(value));
1702 break;
1703 case JDWP::JT_ARRAY:
1704 case JDWP::JT_OBJECT:
1705 case JDWP::JT_STRING:
1706 {
1707 CHECK_EQ(width, sizeof(JDWP::ObjectId));
1708 Object* o = gRegistry->Get<Object*>(static_cast<JDWP::ObjectId>(value));
Elliott Hughesad3da692012-02-24 16:51:35 -08001709 if (o == kInvalidObject) {
1710 UNIMPLEMENTED(FATAL) << "return an error code when given an invalid object to store";
1711 }
Elliott Hughescccd84f2011-12-05 16:51:54 -08001712 f.SetVReg(m, reg, static_cast<uint32_t>(reinterpret_cast<uintptr_t>(o)));
1713 }
1714 break;
1715 case JDWP::JT_DOUBLE:
1716 case JDWP::JT_LONG:
1717 CHECK_EQ(width, 8U);
1718 f.SetVReg(m, reg, static_cast<uint32_t>(value));
1719 f.SetVReg(m, reg + 1, static_cast<uint32_t>(value >> 32));
1720 break;
1721 default:
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001722 LOG(FATAL) << "Unknown tag " << tag;
Elliott Hughescccd84f2011-12-05 16:51:54 -08001723 break;
1724 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001725}
1726
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001727void Dbg::PostLocationEvent(const Method* m, int dex_pc, Object* this_object, int event_flags) {
1728 Class* c = m->GetDeclaringClass();
1729
1730 JDWP::JdwpLocation location;
1731 location.typeTag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
1732 location.classId = gRegistry->Add(c);
1733 location.methodId = ToMethodId(m);
Elliott Hughes972a47b2012-02-21 18:16:06 -08001734 location.dex_pc = m->IsNative() ? -1 : dex_pc;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001735
1736 // Note we use "NoReg" so we don't keep track of references that are
1737 // never actually sent to the debugger. 'this_id' is only used to
1738 // compare against registered events...
1739 JDWP::ObjectId this_id = static_cast<JDWP::ObjectId>(reinterpret_cast<uintptr_t>(this_object));
1740 if (gJdwpState->PostLocationEvent(&location, this_id, event_flags)) {
1741 // ...unless there's a registered event, in which case we
1742 // need to really track the class and 'this'.
1743 gRegistry->Add(c);
1744 gRegistry->Add(this_object);
1745 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001746}
1747
Elliott Hughesd07986f2011-12-06 18:27:45 -08001748void Dbg::PostException(Method** sp, Method* throwMethod, uintptr_t throwNativePc, Method* catchMethod, uintptr_t catchNativePc, Object* exception) {
Ian Rogers0ad5bb82011-12-07 10:16:32 -08001749 if (!gDebuggerActive) {
1750 return;
1751 }
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001752
Elliott Hughesd07986f2011-12-06 18:27:45 -08001753 JDWP::JdwpLocation throw_location;
1754 SetLocation(throw_location, throwMethod, throwNativePc);
1755 JDWP::JdwpLocation catch_location;
1756 SetLocation(catch_location, catchMethod, catchNativePc);
1757
1758 // We need 'this' for InstanceOnly filters.
1759 JDWP::ObjectId this_id;
1760 GetThisObject(reinterpret_cast<JDWP::FrameId>(sp), &this_id);
1761
1762 /*
1763 * Hand the event to the JDWP exception handler. Note we're using the
1764 * "NoReg" objectID on the exception, which is not strictly correct --
1765 * the exception object WILL be passed up to the debugger if the
1766 * debugger is interested in the event. We do this because the current
1767 * implementation of the debugger object registry never throws anything
1768 * away, and some people were experiencing a fatal build up of exception
1769 * objects when dealing with certain libraries.
1770 */
1771 JDWP::ObjectId exception_id = static_cast<JDWP::ObjectId>(reinterpret_cast<uintptr_t>(exception));
1772 JDWP::RefTypeId exception_class_id = gRegistry->Add(exception->GetClass());
1773
1774 gJdwpState->PostException(&throw_location, exception_id, exception_class_id, &catch_location, this_id);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001775}
1776
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001777void Dbg::PostClassPrepare(Class* c) {
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001778 if (!gDebuggerActive) {
1779 return;
1780 }
1781
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001782 // OLD-TODO - we currently always send both "verified" and "prepared" since
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001783 // debuggers seem to like that. There might be some advantage to honesty,
1784 // since the class may not yet be verified.
1785 int state = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
1786 JDWP::JdwpTypeTag tag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
1787 gJdwpState->PostClassPrepare(tag, gRegistry->Add(c), ClassHelper(c).GetDescriptor(), state);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001788}
1789
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001790void Dbg::UpdateDebugger(int32_t dex_pc, Thread* self, Method** sp) {
Elliott Hughes2aa2e392012-02-17 17:15:43 -08001791 if (!gDebuggerActive || dex_pc == -2 /* fake method exit */) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001792 return;
1793 }
1794
Elliott Hughes86964332012-02-15 19:37:42 -08001795 Frame f(sp);
1796 f.Next(); // Skip callee save frame.
1797 Method* m = f.GetMethod();
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001798
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001799 if (dex_pc == -1) {
Elliott Hughes2aa2e392012-02-17 17:15:43 -08001800 // We use a pc of -1 to represent method entry, since we might branch back to pc 0 later.
1801 // This means that for this special notification, there can't be anything else interesting
1802 // going on, so we're done already.
1803 Dbg::PostLocationEvent(m, 0, GetThis(f), kMethodEntry);
1804 return;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001805 }
1806
Elliott Hughes2aa2e392012-02-17 17:15:43 -08001807 int event_flags = 0;
1808
Elliott Hughes86964332012-02-15 19:37:42 -08001809 if (IsBreakpoint(m, dex_pc)) {
1810 event_flags |= kBreakpoint;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001811 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001812
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001813 // If the debugger is single-stepping one of our threads, check to
1814 // see if we're that thread and we've reached a step point.
Elliott Hughes86964332012-02-15 19:37:42 -08001815 if (gSingleStepControl.is_active && gSingleStepControl.thread == self) {
1816 CHECK(!m->IsNative());
1817 if (gSingleStepControl.step_depth == JDWP::SD_INTO) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001818 // Step into method calls. We break when the line number
1819 // or method pointer changes. If we're in SS_MIN mode, we
1820 // always stop.
Elliott Hughes86964332012-02-15 19:37:42 -08001821 if (gSingleStepControl.method != m) {
1822 event_flags |= kSingleStep;
1823 VLOG(jdwp) << "SS new method";
1824 } else if (gSingleStepControl.step_size == JDWP::SS_MIN) {
1825 event_flags |= kSingleStep;
1826 VLOG(jdwp) << "SS new instruction";
Elliott Hughes2435a572012-02-17 16:07:41 -08001827 } else if (gSingleStepControl.dex_pcs.find(dex_pc) == gSingleStepControl.dex_pcs.end()) {
1828 event_flags |= kSingleStep;
1829 VLOG(jdwp) << "SS new line";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001830 }
Elliott Hughes86964332012-02-15 19:37:42 -08001831 } else if (gSingleStepControl.step_depth == JDWP::SD_OVER) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001832 // Step over method calls. We break when the line number is
1833 // different and the frame depth is <= the original frame
1834 // depth. (We can't just compare on the method, because we
1835 // might get unrolled past it by an exception, and it's tricky
1836 // to identify recursion.)
Elliott Hughes86964332012-02-15 19:37:42 -08001837
1838 // TODO: can we just use the value of 'sp'?
1839 int stack_depth = GetStackDepth(self);
1840
1841 if (stack_depth < gSingleStepControl.stack_depth) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001842 // popped up one or more frames, always trigger
Elliott Hughes86964332012-02-15 19:37:42 -08001843 event_flags |= kSingleStep;
1844 VLOG(jdwp) << "SS method pop";
1845 } else if (stack_depth == gSingleStepControl.stack_depth) {
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001846 // same depth, see if we moved
Elliott Hughes86964332012-02-15 19:37:42 -08001847 if (gSingleStepControl.step_size == JDWP::SS_MIN) {
1848 event_flags |= kSingleStep;
1849 VLOG(jdwp) << "SS new instruction";
Elliott Hughes2435a572012-02-17 16:07:41 -08001850 } else if (gSingleStepControl.dex_pcs.find(dex_pc) == gSingleStepControl.dex_pcs.end()) {
1851 event_flags |= kSingleStep;
1852 VLOG(jdwp) << "SS new line";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001853 }
1854 }
1855 } else {
Elliott Hughes86964332012-02-15 19:37:42 -08001856 CHECK_EQ(gSingleStepControl.step_depth, JDWP::SD_OUT);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001857 // Return from the current method. We break when the frame
1858 // depth pops up.
1859
1860 // This differs from the "method exit" break in that it stops
1861 // with the PC at the next instruction in the returned-to
1862 // function, rather than the end of the returning function.
Elliott Hughes86964332012-02-15 19:37:42 -08001863
1864 // TODO: can we just use the value of 'sp'?
1865 int stack_depth = GetStackDepth(self);
1866 if (stack_depth < gSingleStepControl.stack_depth) {
1867 event_flags |= kSingleStep;
1868 VLOG(jdwp) << "SS method pop";
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001869 }
1870 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001871 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001872
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001873 // Check to see if this is a "return" instruction. JDWP says we should
1874 // send the event *after* the code has been executed, but it also says
1875 // the location we provide is the last instruction. Since the "return"
1876 // instruction has no interesting side effects, we should be safe.
1877 // (We can't just move this down to the returnFromMethod label because
1878 // we potentially need to combine it with other events.)
1879 // We're also not supposed to generate a method exit event if the method
1880 // terminates "with a thrown exception".
Elliott Hughes86964332012-02-15 19:37:42 -08001881 if (dex_pc >= 0) {
1882 const DexFile::CodeItem* code_item = MethodHelper(m).GetCodeItem();
1883 CHECK(code_item != NULL);
1884 CHECK_LT(dex_pc, static_cast<int32_t>(code_item->insns_size_in_code_units_));
1885 if (Instruction::At(&code_item->insns_[dex_pc])->IsReturn()) {
1886 event_flags |= kMethodExit;
1887 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001888 }
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001889
1890 // If there's something interesting going on, see if it matches one
1891 // of the debugger filters.
1892 if (event_flags != 0) {
Elliott Hughes86964332012-02-15 19:37:42 -08001893 Dbg::PostLocationEvent(m, dex_pc, GetThis(f), event_flags);
Elliott Hughes91bf6cd2012-02-14 17:27:48 -08001894 }
1895}
1896
Elliott Hughes86964332012-02-15 19:37:42 -08001897void Dbg::WatchLocation(const JDWP::JdwpLocation* location) {
1898 MutexLock mu(gBreakpointsLock);
1899 Method* m = FromMethodId(location->methodId);
Elliott Hughes972a47b2012-02-21 18:16:06 -08001900 gBreakpoints.push_back(Breakpoint(m, location->dex_pc));
Elliott Hughes86964332012-02-15 19:37:42 -08001901 VLOG(jdwp) << "Set breakpoint #" << (gBreakpoints.size() - 1) << ": " << gBreakpoints[gBreakpoints.size() - 1];
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001902}
1903
Elliott Hughes86964332012-02-15 19:37:42 -08001904void Dbg::UnwatchLocation(const JDWP::JdwpLocation* location) {
1905 MutexLock mu(gBreakpointsLock);
1906 Method* m = FromMethodId(location->methodId);
1907 for (size_t i = 0; i < gBreakpoints.size(); ++i) {
Elliott Hughes972a47b2012-02-21 18:16:06 -08001908 if (gBreakpoints[i].method == m && gBreakpoints[i].dex_pc == location->dex_pc) {
Elliott Hughes86964332012-02-15 19:37:42 -08001909 VLOG(jdwp) << "Removed breakpoint #" << i << ": " << gBreakpoints[i];
1910 gBreakpoints.erase(gBreakpoints.begin() + i);
1911 return;
1912 }
1913 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001914}
1915
Elliott Hughes2435a572012-02-17 16:07:41 -08001916JDWP::JdwpError Dbg::ConfigureStep(JDWP::ObjectId threadId, JDWP::JdwpStepSize step_size, JDWP::JdwpStepDepth step_depth) {
Elliott Hughes86964332012-02-15 19:37:42 -08001917 Thread* thread = DecodeThread(threadId);
Elliott Hughes2435a572012-02-17 16:07:41 -08001918 if (thread == NULL) {
1919 return JDWP::ERR_INVALID_THREAD;
1920 }
Elliott Hughes86964332012-02-15 19:37:42 -08001921
1922 // TODO: there's no theoretical reason why we couldn't support single-stepping
1923 // of multiple threads at once, but we never did so historically.
1924 if (gSingleStepControl.thread != NULL && thread != gSingleStepControl.thread) {
1925 LOG(WARNING) << "single-step already active for " << *gSingleStepControl.thread
1926 << "; switching to " << *thread;
1927 }
1928
Elliott Hughes2435a572012-02-17 16:07:41 -08001929 //
1930 // Work out what Method* we're in, the current line number, and how deep the stack currently
1931 // is for step-out.
1932 //
1933
Elliott Hughes86964332012-02-15 19:37:42 -08001934 struct SingleStepStackVisitor : public Thread::StackVisitor {
1935 SingleStepStackVisitor() {
1936 gSingleStepControl.method = NULL;
1937 gSingleStepControl.stack_depth = 0;
1938 }
Elliott Hughes530fa002012-03-12 11:44:49 -07001939 bool VisitFrame(const Frame& f, uintptr_t pc) {
Elliott Hughes86964332012-02-15 19:37:42 -08001940 if (f.HasMethod()) {
1941 ++gSingleStepControl.stack_depth;
1942 if (gSingleStepControl.method == NULL) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001943 const Method* m = f.GetMethod();
1944 const DexCache* dex_cache = m->GetDeclaringClass()->GetDexCache();
1945 gSingleStepControl.method = m;
1946 gSingleStepControl.line_number = -1;
1947 if (dex_cache != NULL) {
1948 const DexFile& dex_file = Runtime::Current()->GetClassLinker()->FindDexFile(dex_cache);
1949 gSingleStepControl.line_number = dex_file.GetLineNumFromPC(m, m->ToDexPC(pc));
1950 }
Elliott Hughes86964332012-02-15 19:37:42 -08001951 }
1952 }
Elliott Hughes530fa002012-03-12 11:44:49 -07001953 return true;
Elliott Hughes86964332012-02-15 19:37:42 -08001954 }
1955 };
1956 SingleStepStackVisitor visitor;
1957 thread->WalkStack(&visitor);
1958
Elliott Hughes2435a572012-02-17 16:07:41 -08001959 //
1960 // Find the dex_pc values that correspond to the current line, for line-based single-stepping.
1961 //
1962
1963 struct DebugCallbackContext {
1964 DebugCallbackContext() {
1965 last_pc_valid = false;
1966 last_pc = 0;
Elliott Hughes2435a572012-02-17 16:07:41 -08001967 }
1968
1969 static bool Callback(void* raw_context, uint32_t address, uint32_t line_number) {
1970 DebugCallbackContext* context = reinterpret_cast<DebugCallbackContext*>(raw_context);
1971 if (static_cast<int32_t>(line_number) == gSingleStepControl.line_number) {
1972 if (!context->last_pc_valid) {
1973 // Everything from this address until the next line change is ours.
1974 context->last_pc = address;
1975 context->last_pc_valid = true;
1976 }
1977 // Otherwise, if we're already in a valid range for this line,
1978 // just keep going (shouldn't really happen)...
1979 } else if (context->last_pc_valid) { // and the line number is new
1980 // Add everything from the last entry up until here to the set
1981 for (uint32_t dex_pc = context->last_pc; dex_pc < address; ++dex_pc) {
1982 gSingleStepControl.dex_pcs.insert(dex_pc);
1983 }
1984 context->last_pc_valid = false;
1985 }
1986 return false; // There may be multiple entries for any given line.
1987 }
1988
1989 ~DebugCallbackContext() {
1990 // If the line number was the last in the position table...
1991 if (last_pc_valid) {
1992 size_t end = MethodHelper(gSingleStepControl.method).GetCodeItem()->insns_size_in_code_units_;
1993 for (uint32_t dex_pc = last_pc; dex_pc < end; ++dex_pc) {
1994 gSingleStepControl.dex_pcs.insert(dex_pc);
1995 }
1996 }
1997 }
1998
1999 bool last_pc_valid;
2000 uint32_t last_pc;
2001 };
Elliott Hughes3e2e1a22012-02-21 11:33:41 -08002002 gSingleStepControl.dex_pcs.clear();
Elliott Hughes2435a572012-02-17 16:07:41 -08002003 const Method* m = gSingleStepControl.method;
Elliott Hughes3e2e1a22012-02-21 11:33:41 -08002004 if (m->IsNative()) {
2005 gSingleStepControl.line_number = -1;
2006 } else {
2007 DebugCallbackContext context;
2008 MethodHelper mh(m);
2009 mh.GetDexFile().DecodeDebugInfo(mh.GetCodeItem(), m->IsStatic(), m->GetDexMethodIndex(),
2010 DebugCallbackContext::Callback, NULL, &context);
2011 }
Elliott Hughes2435a572012-02-17 16:07:41 -08002012
2013 //
2014 // Everything else...
2015 //
2016
Elliott Hughes86964332012-02-15 19:37:42 -08002017 gSingleStepControl.thread = thread;
2018 gSingleStepControl.step_size = step_size;
2019 gSingleStepControl.step_depth = step_depth;
2020 gSingleStepControl.is_active = true;
2021
Elliott Hughes2435a572012-02-17 16:07:41 -08002022 if (VLOG_IS_ON(jdwp)) {
2023 VLOG(jdwp) << "Single-step thread: " << *gSingleStepControl.thread;
2024 VLOG(jdwp) << "Single-step step size: " << gSingleStepControl.step_size;
2025 VLOG(jdwp) << "Single-step step depth: " << gSingleStepControl.step_depth;
2026 VLOG(jdwp) << "Single-step current method: " << PrettyMethod(gSingleStepControl.method);
2027 VLOG(jdwp) << "Single-step current line: " << gSingleStepControl.line_number;
2028 VLOG(jdwp) << "Single-step current stack depth: " << gSingleStepControl.stack_depth;
2029 VLOG(jdwp) << "Single-step dex_pc values:";
2030 for (std::set<uint32_t>::iterator it = gSingleStepControl.dex_pcs.begin() ; it != gSingleStepControl.dex_pcs.end(); ++it) {
Elliott Hughes229feb72012-02-23 13:33:29 -08002031 VLOG(jdwp) << StringPrintf(" %#x", *it);
Elliott Hughes2435a572012-02-17 16:07:41 -08002032 }
2033 }
2034
2035 return JDWP::ERR_NONE;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002036}
2037
Elliott Hughes1bac54f2012-03-16 12:48:31 -07002038void Dbg::UnconfigureStep(JDWP::ObjectId /*threadId*/) {
Elliott Hughes86964332012-02-15 19:37:42 -08002039 gSingleStepControl.is_active = false;
2040 gSingleStepControl.thread = NULL;
Elliott Hughes2435a572012-02-17 16:07:41 -08002041 gSingleStepControl.dex_pcs.clear();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002042}
2043
Elliott Hughes45651fd2012-02-21 15:48:20 -08002044static char JdwpTagToShortyChar(JDWP::JdwpTag tag) {
2045 switch (tag) {
2046 default:
2047 LOG(FATAL) << "unknown JDWP tag: " << PrintableChar(tag);
2048
2049 // Primitives.
2050 case JDWP::JT_BYTE: return 'B';
2051 case JDWP::JT_CHAR: return 'C';
2052 case JDWP::JT_FLOAT: return 'F';
2053 case JDWP::JT_DOUBLE: return 'D';
2054 case JDWP::JT_INT: return 'I';
2055 case JDWP::JT_LONG: return 'J';
2056 case JDWP::JT_SHORT: return 'S';
2057 case JDWP::JT_VOID: return 'V';
2058 case JDWP::JT_BOOLEAN: return 'Z';
2059
2060 // Reference types.
2061 case JDWP::JT_ARRAY:
2062 case JDWP::JT_OBJECT:
2063 case JDWP::JT_STRING:
2064 case JDWP::JT_THREAD:
2065 case JDWP::JT_THREAD_GROUP:
2066 case JDWP::JT_CLASS_LOADER:
2067 case JDWP::JT_CLASS_OBJECT:
2068 return 'L';
2069 }
2070}
2071
2072JDWP::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 -08002073 ThreadList* thread_list = Runtime::Current()->GetThreadList();
2074
2075 Thread* targetThread = NULL;
2076 DebugInvokeReq* req = NULL;
2077 {
2078 ScopedThreadListLock thread_list_lock;
2079 targetThread = DecodeThread(threadId);
2080 if (targetThread == NULL) {
2081 LOG(ERROR) << "InvokeMethod request for non-existent thread " << threadId;
2082 return JDWP::ERR_INVALID_THREAD;
2083 }
2084 req = targetThread->GetInvokeReq();
2085 if (!req->ready) {
2086 LOG(ERROR) << "InvokeMethod request for thread not stopped by event: " << *targetThread;
2087 return JDWP::ERR_INVALID_THREAD;
2088 }
2089
2090 /*
2091 * We currently have a bug where we don't successfully resume the
2092 * target thread if the suspend count is too deep. We're expected to
2093 * require one "resume" for each "suspend", but when asked to execute
2094 * a method we have to resume fully and then re-suspend it back to the
2095 * same level. (The easiest way to cause this is to type "suspend"
2096 * multiple times in jdb.)
2097 *
2098 * It's unclear what this means when the event specifies "resume all"
2099 * and some threads are suspended more deeply than others. This is
2100 * a rare problem, so for now we just prevent it from hanging forever
2101 * by rejecting the method invocation request. Without this, we will
2102 * be stuck waiting on a suspended thread.
2103 */
2104 int suspend_count = targetThread->GetSuspendCount();
2105 if (suspend_count > 1) {
2106 LOG(ERROR) << *targetThread << " suspend count too deep for method invocation: " << suspend_count;
2107 return JDWP::ERR_THREAD_SUSPENDED; // Probably not expected here.
2108 }
2109
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002110 JDWP::JdwpError status;
Elliott Hughes45651fd2012-02-21 15:48:20 -08002111 Object* receiver = gRegistry->Get<Object*>(objectId);
2112 if (receiver == kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002113 return JDWP::ERR_INVALID_OBJECT;
2114 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002115
2116 Object* thread = gRegistry->Get<Object*>(threadId);
2117 if (thread == kInvalidObject) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002118 return JDWP::ERR_INVALID_OBJECT;
2119 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002120 // TODO: check that 'thread' is actually a java.lang.Thread!
2121
2122 Class* c = DecodeClass(classId, status);
2123 if (c == NULL) {
Elliott Hughes3f4d58f2012-02-18 20:05:37 -08002124 return status;
2125 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002126
2127 Method* m = FromMethodId(methodId);
2128 if (m->IsStatic() != (receiver == NULL)) {
2129 return JDWP::ERR_INVALID_METHODID;
2130 }
2131 if (m->IsStatic()) {
2132 if (m->GetDeclaringClass() != c) {
2133 return JDWP::ERR_INVALID_METHODID;
2134 }
2135 } else {
2136 if (!m->GetDeclaringClass()->IsAssignableFrom(c)) {
2137 return JDWP::ERR_INVALID_METHODID;
2138 }
2139 }
2140
2141 // Check the argument list matches the method.
2142 MethodHelper mh(m);
2143 if (mh.GetShortyLength() - 1 != arg_count) {
2144 return JDWP::ERR_ILLEGAL_ARGUMENT;
2145 }
2146 const char* shorty = mh.GetShorty();
2147 for (size_t i = 0; i < arg_count; ++i) {
2148 if (shorty[i + 1] != JdwpTagToShortyChar(arg_types[i])) {
2149 return JDWP::ERR_ILLEGAL_ARGUMENT;
2150 }
2151 }
2152
2153 req->receiver_ = receiver;
2154 req->thread_ = thread;
2155 req->class_ = c;
2156 req->method_ = m;
2157 req->arg_count_ = arg_count;
2158 req->arg_values_ = arg_values;
Elliott Hughesd07986f2011-12-06 18:27:45 -08002159 req->options_ = options;
2160 req->invoke_needed_ = true;
2161 }
2162
2163 // The fact that we've released the thread list lock is a bit risky --- if the thread goes
2164 // away we're sitting high and dry -- but we must release this before the ResumeAllThreads
2165 // call, and it's unwise to hold it during WaitForSuspend.
2166
2167 {
2168 /*
2169 * We change our (JDWP thread) status, which should be THREAD_RUNNING,
Elliott Hughes81ff3182012-03-23 20:35:56 -07002170 * so we can suspend for a GC if the invoke request causes us to
Elliott Hughesd07986f2011-12-06 18:27:45 -08002171 * run out of memory. It's also a good idea to change it before locking
2172 * the invokeReq mutex, although that should never be held for long.
2173 */
2174 ScopedThreadStateChange tsc(Thread::Current(), Thread::kVmWait);
2175
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002176 VLOG(jdwp) << " Transferring control to event thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002177 {
2178 MutexLock mu(req->lock_);
2179
2180 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002181 VLOG(jdwp) << " Resuming all threads";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002182 thread_list->ResumeAll(true);
2183 } else {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002184 VLOG(jdwp) << " Resuming event thread only";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002185 thread_list->Resume(targetThread, true);
2186 }
2187
2188 // Wait for the request to finish executing.
2189 while (req->invoke_needed_) {
2190 req->cond_.Wait(req->lock_);
2191 }
2192 }
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002193 VLOG(jdwp) << " Control has returned from event thread";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002194
2195 /* wait for thread to re-suspend itself */
2196 targetThread->WaitUntilSuspended();
2197 //dvmWaitForSuspend(targetThread);
2198 }
2199
2200 /*
2201 * Suspend the threads. We waited for the target thread to suspend
2202 * itself, so all we need to do is suspend the others.
2203 *
2204 * The suspendAllThreads() call will double-suspend the event thread,
2205 * so we want to resume the target thread once to keep the books straight.
2206 */
2207 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002208 VLOG(jdwp) << " Suspending all threads";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002209 thread_list->SuspendAll(true);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002210 VLOG(jdwp) << " Resuming event thread to balance the count";
Elliott Hughesd07986f2011-12-06 18:27:45 -08002211 thread_list->Resume(targetThread, true);
2212 }
2213
2214 // Copy the result.
2215 *pResultTag = req->result_tag;
2216 if (IsPrimitiveTag(req->result_tag)) {
2217 *pResultValue = req->result_value.j;
2218 } else {
2219 *pResultValue = gRegistry->Add(req->result_value.l);
2220 }
2221 *pExceptionId = req->exception;
2222 return req->error;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002223}
2224
2225void Dbg::ExecuteMethod(DebugInvokeReq* pReq) {
Elliott Hughesd07986f2011-12-06 18:27:45 -08002226 Thread* self = Thread::Current();
2227
Elliott Hughes81ff3182012-03-23 20:35:56 -07002228 // We can be called while an exception is pending. We need
Elliott Hughesd07986f2011-12-06 18:27:45 -08002229 // to preserve that across the method invocation.
2230 SirtRef<Throwable> old_exception(self->GetException());
2231 self->ClearException();
2232
2233 ScopedThreadStateChange tsc(self, Thread::kRunnable);
2234
2235 // Translate the method through the vtable, unless the debugger wants to suppress it.
2236 Method* m = pReq->method_;
2237 if ((pReq->options_ & JDWP::INVOKE_NONVIRTUAL) == 0 && pReq->receiver_ != NULL) {
Elliott Hughes45651fd2012-02-21 15:48:20 -08002238 Method* actual_method = pReq->class_->FindVirtualMethodForVirtualOrInterface(pReq->method_);
2239 if (actual_method != m) {
2240 VLOG(jdwp) << "ExecuteMethod translated " << PrettyMethod(m) << " to " << PrettyMethod(actual_method);
2241 m = actual_method;
2242 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08002243 }
Elliott Hughes45651fd2012-02-21 15:48:20 -08002244 VLOG(jdwp) << "ExecuteMethod " << PrettyMethod(m);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002245 CHECK(m != NULL);
2246
2247 CHECK_EQ(sizeof(jvalue), sizeof(uint64_t));
2248
Elliott Hughes45651fd2012-02-21 15:48:20 -08002249 LOG(INFO) << "self=" << self << " pReq->receiver_=" << pReq->receiver_ << " m=" << m << " #" << pReq->arg_count_ << " " << pReq->arg_values_;
2250 pReq->result_value = InvokeWithJValues(self, pReq->receiver_, m, reinterpret_cast<JValue*>(pReq->arg_values_));
Elliott Hughesd07986f2011-12-06 18:27:45 -08002251
2252 pReq->exception = gRegistry->Add(self->GetException());
2253 pReq->result_tag = BasicTagFromDescriptor(MethodHelper(m).GetShorty());
2254 if (pReq->exception != 0) {
2255 Object* exc = self->GetException();
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002256 VLOG(jdwp) << " JDWP invocation returning with exception=" << exc << " " << PrettyTypeOf(exc);
Elliott Hughesd07986f2011-12-06 18:27:45 -08002257 self->ClearException();
2258 pReq->result_value.j = 0;
2259 } else if (pReq->result_tag == JDWP::JT_OBJECT) {
2260 /* if no exception thrown, examine object result more closely */
2261 JDWP::JdwpTag new_tag = TagFromObject(pReq->result_value.l);
2262 if (new_tag != pReq->result_tag) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002263 VLOG(jdwp) << " JDWP promoted result from " << pReq->result_tag << " to " << new_tag;
Elliott Hughesd07986f2011-12-06 18:27:45 -08002264 pReq->result_tag = new_tag;
2265 }
2266
2267 /*
2268 * Register the object. We don't actually need an ObjectId yet,
2269 * but we do need to be sure that the GC won't move or discard the
2270 * object when we switch out of RUNNING. The ObjectId conversion
2271 * will add the object to the "do not touch" list.
2272 *
2273 * We can't use the "tracked allocation" mechanism here because
2274 * the object is going to be handed off to a different thread.
2275 */
2276 gRegistry->Add(pReq->result_value.l);
2277 }
2278
2279 if (old_exception.get() != NULL) {
2280 self->SetException(old_exception.get());
2281 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002282}
2283
Elliott Hughesd07986f2011-12-06 18:27:45 -08002284/*
2285 * Register an object ID that might not have been registered previously.
2286 *
2287 * Normally this wouldn't happen -- the conversion to an ObjectId would
2288 * have added the object to the registry -- but in some cases (e.g.
2289 * throwing exceptions) we really want to do the registration late.
2290 */
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002291void Dbg::RegisterObjectId(JDWP::ObjectId id) {
Elliott Hughesd07986f2011-12-06 18:27:45 -08002292 gRegistry->Add(reinterpret_cast<Object*>(id));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002293}
2294
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002295/*
2296 * "buf" contains a full JDWP packet, possibly with multiple chunks. We
2297 * need to process each, accumulate the replies, and ship the whole thing
2298 * back.
2299 *
2300 * Returns "true" if we have a reply. The reply buffer is newly allocated,
2301 * and includes the chunk type/length, followed by the data.
2302 *
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08002303 * OLD-TODO: we currently assume that the request and reply include a single
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002304 * chunk. If this becomes inconvenient we will need to adapt.
2305 */
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002306bool Dbg::DdmHandlePacket(const uint8_t* buf, int dataLen, uint8_t** pReplyBuf, int* pReplyLen) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002307 CHECK_GE(dataLen, 0);
2308
2309 Thread* self = Thread::Current();
2310 JNIEnv* env = self->GetJniEnv();
2311
Elliott Hughes844f9a02012-01-24 20:19:58 -08002312 static jclass Chunk_class = CacheClass(env, "org/apache/harmony/dalvik/ddmc/Chunk");
2313 static jclass DdmServer_class = CacheClass(env, "org/apache/harmony/dalvik/ddmc/DdmServer");
2314 static jmethodID dispatch_mid = env->GetStaticMethodID(DdmServer_class, "dispatch", "(I[BII)Lorg/apache/harmony/dalvik/ddmc/Chunk;");
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002315 static jfieldID data_fid = env->GetFieldID(Chunk_class, "data", "[B");
2316 static jfieldID length_fid = env->GetFieldID(Chunk_class, "length", "I");
2317 static jfieldID offset_fid = env->GetFieldID(Chunk_class, "offset", "I");
2318 static jfieldID type_fid = env->GetFieldID(Chunk_class, "type", "I");
2319
2320 // Create a byte[] corresponding to 'buf'.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002321 ScopedLocalRef<jbyteArray> dataArray(env, env->NewByteArray(dataLen));
2322 if (dataArray.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002323 LOG(WARNING) << "byte[] allocation failed: " << dataLen;
2324 env->ExceptionClear();
2325 return false;
2326 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002327 env->SetByteArrayRegion(dataArray.get(), 0, dataLen, reinterpret_cast<const jbyte*>(buf));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002328
2329 const int kChunkHdrLen = 8;
2330
2331 // Run through and find all chunks. [Currently just find the first.]
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002332 ScopedByteArrayRO contents(env, dataArray.get());
Elliott Hughesf7c3b662011-10-27 12:04:56 -07002333 jint type = JDWP::Get4BE(reinterpret_cast<const uint8_t*>(&contents[0]));
2334 jint length = JDWP::Get4BE(reinterpret_cast<const uint8_t*>(&contents[4]));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002335 jint offset = kChunkHdrLen;
2336 if (offset + length > dataLen) {
2337 LOG(WARNING) << StringPrintf("bad chunk found (len=%u pktLen=%d)", length, dataLen);
2338 return false;
2339 }
2340
2341 // Call "private static Chunk dispatch(int type, byte[] data, int offset, int length)".
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002342 ScopedLocalRef<jobject> chunk(env, env->CallStaticObjectMethod(DdmServer_class, dispatch_mid, type, dataArray.get(), offset, length));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002343 if (env->ExceptionCheck()) {
2344 LOG(INFO) << StringPrintf("Exception thrown by dispatcher for 0x%08x", type);
2345 env->ExceptionDescribe();
2346 env->ExceptionClear();
2347 return false;
2348 }
2349
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002350 if (chunk.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002351 return false;
2352 }
2353
2354 /*
2355 * Pull the pieces out of the chunk. We copy the results into a
2356 * newly-allocated buffer that the caller can free. We don't want to
2357 * continue using the Chunk object because nothing has a reference to it.
2358 *
2359 * We could avoid this by returning type/data/offset/length and having
2360 * the caller be aware of the object lifetime issues, but that
Elliott Hughes81ff3182012-03-23 20:35:56 -07002361 * integrates the JDWP code more tightly into the rest of the runtime, and doesn't work
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002362 * if we have responses for multiple chunks.
2363 *
2364 * So we're pretty much stuck with copying data around multiple times.
2365 */
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002366 ScopedLocalRef<jbyteArray> replyData(env, reinterpret_cast<jbyteArray>(env->GetObjectField(chunk.get(), data_fid)));
2367 length = env->GetIntField(chunk.get(), length_fid);
2368 offset = env->GetIntField(chunk.get(), offset_fid);
2369 type = env->GetIntField(chunk.get(), type_fid);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002370
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002371 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 -07002372 if (length == 0 || replyData.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002373 return false;
2374 }
2375
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002376 jsize replyLength = env->GetArrayLength(replyData.get());
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002377 if (offset + length > replyLength) {
2378 LOG(WARNING) << StringPrintf("chunk off=%d len=%d exceeds reply array len %d", offset, length, replyLength);
2379 return false;
2380 }
2381
2382 uint8_t* reply = new uint8_t[length + kChunkHdrLen];
2383 if (reply == NULL) {
2384 LOG(WARNING) << "malloc failed: " << (length + kChunkHdrLen);
2385 return false;
2386 }
Elliott Hughesf7c3b662011-10-27 12:04:56 -07002387 JDWP::Set4BE(reply + 0, type);
2388 JDWP::Set4BE(reply + 4, length);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002389 env->GetByteArrayRegion(replyData.get(), offset, length, reinterpret_cast<jbyte*>(reply + kChunkHdrLen));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002390
2391 *pReplyBuf = reply;
2392 *pReplyLen = length + kChunkHdrLen;
2393
Elliott Hughesba8eee12012-01-24 20:25:24 -08002394 VLOG(jdwp) << StringPrintf("dvmHandleDdm returning type=%.4s buf=%p len=%d", reinterpret_cast<char*>(reply), reply, length);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07002395 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002396}
2397
Elliott Hughesa2155262011-11-16 16:26:58 -08002398void Dbg::DdmBroadcast(bool connect) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002399 VLOG(jdwp) << "Broadcasting DDM " << (connect ? "connect" : "disconnect") << "...";
Elliott Hughes47fce012011-10-25 18:37:19 -07002400
2401 Thread* self = Thread::Current();
2402 if (self->GetState() != Thread::kRunnable) {
2403 LOG(ERROR) << "DDM broadcast in thread state " << self->GetState();
2404 /* try anyway? */
2405 }
2406
2407 JNIEnv* env = self->GetJniEnv();
Elliott Hughes844f9a02012-01-24 20:19:58 -08002408 static jclass DdmServer_class = CacheClass(env, "org/apache/harmony/dalvik/ddmc/DdmServer");
Elliott Hughes47fce012011-10-25 18:37:19 -07002409 static jmethodID broadcast_mid = env->GetStaticMethodID(DdmServer_class, "broadcast", "(I)V");
2410 jint event = connect ? 1 /*DdmServer.CONNECTED*/ : 2 /*DdmServer.DISCONNECTED*/;
2411 env->CallStaticVoidMethod(DdmServer_class, broadcast_mid, event);
2412 if (env->ExceptionCheck()) {
2413 LOG(ERROR) << "DdmServer.broadcast " << event << " failed";
2414 env->ExceptionDescribe();
2415 env->ExceptionClear();
2416 }
2417}
2418
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002419void Dbg::DdmConnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08002420 Dbg::DdmBroadcast(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002421}
2422
2423void Dbg::DdmDisconnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08002424 Dbg::DdmBroadcast(false);
Elliott Hughes47fce012011-10-25 18:37:19 -07002425 gDdmThreadNotification = false;
2426}
2427
2428/*
Elliott Hughes82188472011-11-07 18:11:48 -08002429 * Send a notification when a thread starts, stops, or changes its name.
Elliott Hughes47fce012011-10-25 18:37:19 -07002430 *
2431 * Because we broadcast the full set of threads when the notifications are
2432 * first enabled, it's possible for "thread" to be actively executing.
2433 */
Elliott Hughes82188472011-11-07 18:11:48 -08002434void Dbg::DdmSendThreadNotification(Thread* t, uint32_t type) {
Elliott Hughes47fce012011-10-25 18:37:19 -07002435 if (!gDdmThreadNotification) {
2436 return;
2437 }
2438
Elliott Hughes82188472011-11-07 18:11:48 -08002439 if (type == CHUNK_TYPE("THDE")) {
Elliott Hughes47fce012011-10-25 18:37:19 -07002440 uint8_t buf[4];
Elliott Hughesf7c3b662011-10-27 12:04:56 -07002441 JDWP::Set4BE(&buf[0], t->GetThinLockId());
Elliott Hughes47fce012011-10-25 18:37:19 -07002442 Dbg::DdmSendChunk(CHUNK_TYPE("THDE"), 4, buf);
Elliott Hughes82188472011-11-07 18:11:48 -08002443 } else {
2444 CHECK(type == CHUNK_TYPE("THCR") || type == CHUNK_TYPE("THNM")) << type;
Elliott Hughes899e7892012-01-24 14:57:32 -08002445 SirtRef<String> name(t->GetThreadName());
Elliott Hughes82188472011-11-07 18:11:48 -08002446 size_t char_count = (name.get() != NULL) ? name->GetLength() : 0;
2447 const jchar* chars = name->GetCharArray()->GetData();
2448
Elliott Hughes21f32d72011-11-09 17:44:13 -08002449 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08002450 JDWP::Append4BE(bytes, t->GetThinLockId());
2451 JDWP::AppendUtf16BE(bytes, chars, char_count);
Elliott Hughes21f32d72011-11-09 17:44:13 -08002452 CHECK_EQ(bytes.size(), char_count*2 + sizeof(uint32_t)*2);
2453 Dbg::DdmSendChunk(type, bytes);
Elliott Hughes47fce012011-10-25 18:37:19 -07002454 }
2455}
2456
Elliott Hughesa2155262011-11-16 16:26:58 -08002457static void DdmSendThreadStartCallback(Thread* t, void*) {
Elliott Hughes82188472011-11-07 18:11:48 -08002458 Dbg::DdmSendThreadNotification(t, CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07002459}
2460
2461void Dbg::DdmSetThreadNotification(bool enable) {
2462 // We lock the thread list to avoid sending duplicate events or missing
2463 // a thread change. We should be okay holding this lock while sending
2464 // the messages out. (We have to hold it while accessing a live thread.)
Elliott Hughesbbd9d832011-11-07 14:40:00 -08002465 ScopedThreadListLock thread_list_lock;
Elliott Hughes47fce012011-10-25 18:37:19 -07002466
2467 gDdmThreadNotification = enable;
2468 if (enable) {
Elliott Hughesbfe487b2011-10-26 15:48:55 -07002469 Runtime::Current()->GetThreadList()->ForEach(DdmSendThreadStartCallback, NULL);
Elliott Hughes47fce012011-10-25 18:37:19 -07002470 }
2471}
2472
Elliott Hughesa2155262011-11-16 16:26:58 -08002473void Dbg::PostThreadStartOrStop(Thread* t, uint32_t type) {
Elliott Hughes47fce012011-10-25 18:37:19 -07002474 if (gDebuggerActive) {
2475 JDWP::ObjectId id = gRegistry->Add(t->GetPeer());
Elliott Hughes82188472011-11-07 18:11:48 -08002476 gJdwpState->PostThreadChange(id, type == CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07002477 }
Elliott Hughes82188472011-11-07 18:11:48 -08002478 Dbg::DdmSendThreadNotification(t, type);
Elliott Hughes47fce012011-10-25 18:37:19 -07002479}
2480
2481void Dbg::PostThreadStart(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08002482 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07002483}
2484
2485void Dbg::PostThreadDeath(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08002486 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THDE"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002487}
2488
Elliott Hughes82188472011-11-07 18:11:48 -08002489void Dbg::DdmSendChunk(uint32_t type, size_t byte_count, const uint8_t* buf) {
Elliott Hughes3bb81562011-10-21 18:52:59 -07002490 CHECK(buf != NULL);
2491 iovec vec[1];
2492 vec[0].iov_base = reinterpret_cast<void*>(const_cast<uint8_t*>(buf));
2493 vec[0].iov_len = byte_count;
2494 Dbg::DdmSendChunkV(type, vec, 1);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002495}
2496
Elliott Hughes21f32d72011-11-09 17:44:13 -08002497void Dbg::DdmSendChunk(uint32_t type, const std::vector<uint8_t>& bytes) {
2498 DdmSendChunk(type, bytes.size(), &bytes[0]);
2499}
2500
Elliott Hughescccd84f2011-12-05 16:51:54 -08002501void Dbg::DdmSendChunkV(uint32_t type, const struct iovec* iov, int iov_count) {
Elliott Hughes3bb81562011-10-21 18:52:59 -07002502 if (gJdwpState == NULL) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002503 VLOG(jdwp) << "Debugger thread not active, ignoring DDM send: " << type;
Elliott Hughes3bb81562011-10-21 18:52:59 -07002504 } else {
Elliott Hughescccd84f2011-12-05 16:51:54 -08002505 gJdwpState->DdmSendChunkV(type, iov, iov_count);
Elliott Hughes3bb81562011-10-21 18:52:59 -07002506 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002507}
2508
Elliott Hughes767a1472011-10-26 18:49:02 -07002509int Dbg::DdmHandleHpifChunk(HpifWhen when) {
2510 if (when == HPIF_WHEN_NOW) {
Elliott Hughes7162ad92011-10-27 14:08:42 -07002511 DdmSendHeapInfo(when);
Elliott Hughes767a1472011-10-26 18:49:02 -07002512 return true;
2513 }
2514
2515 if (when != HPIF_WHEN_NEVER && when != HPIF_WHEN_NEXT_GC && when != HPIF_WHEN_EVERY_GC) {
2516 LOG(ERROR) << "invalid HpifWhen value: " << static_cast<int>(when);
2517 return false;
2518 }
2519
2520 gDdmHpifWhen = when;
2521 return true;
2522}
2523
2524bool Dbg::DdmHandleHpsgNhsgChunk(Dbg::HpsgWhen when, Dbg::HpsgWhat what, bool native) {
2525 if (when != HPSG_WHEN_NEVER && when != HPSG_WHEN_EVERY_GC) {
2526 LOG(ERROR) << "invalid HpsgWhen value: " << static_cast<int>(when);
2527 return false;
2528 }
2529
2530 if (what != HPSG_WHAT_MERGED_OBJECTS && what != HPSG_WHAT_DISTINCT_OBJECTS) {
2531 LOG(ERROR) << "invalid HpsgWhat value: " << static_cast<int>(what);
2532 return false;
2533 }
2534
2535 if (native) {
2536 gDdmNhsgWhen = when;
2537 gDdmNhsgWhat = what;
2538 } else {
2539 gDdmHpsgWhen = when;
2540 gDdmHpsgWhat = what;
2541 }
2542 return true;
2543}
2544
Elliott Hughes7162ad92011-10-27 14:08:42 -07002545void Dbg::DdmSendHeapInfo(HpifWhen reason) {
2546 // If there's a one-shot 'when', reset it.
2547 if (reason == gDdmHpifWhen) {
2548 if (gDdmHpifWhen == HPIF_WHEN_NEXT_GC) {
2549 gDdmHpifWhen = HPIF_WHEN_NEVER;
2550 }
2551 }
2552
2553 /*
2554 * Chunk HPIF (client --> server)
2555 *
2556 * Heap Info. General information about the heap,
2557 * suitable for a summary display.
2558 *
2559 * [u4]: number of heaps
2560 *
2561 * For each heap:
2562 * [u4]: heap ID
2563 * [u8]: timestamp in ms since Unix epoch
2564 * [u1]: capture reason (same as 'when' value from server)
2565 * [u4]: max heap size in bytes (-Xmx)
2566 * [u4]: current heap size in bytes
2567 * [u4]: current number of bytes allocated
2568 * [u4]: current number of objects allocated
2569 */
2570 uint8_t heap_count = 1;
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08002571 Heap* heap = Runtime::Current()->GetHeap();
Elliott Hughes21f32d72011-11-09 17:44:13 -08002572 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08002573 JDWP::Append4BE(bytes, heap_count);
2574 JDWP::Append4BE(bytes, 1); // Heap id (bogus; we only have one heap).
2575 JDWP::Append8BE(bytes, MilliTime());
2576 JDWP::Append1BE(bytes, reason);
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08002577 JDWP::Append4BE(bytes, heap->GetMaxMemory()); // Max allowed heap size in bytes.
2578 JDWP::Append4BE(bytes, heap->GetTotalMemory()); // Current heap size in bytes.
2579 JDWP::Append4BE(bytes, heap->GetBytesAllocated());
2580 JDWP::Append4BE(bytes, heap->GetObjectsAllocated());
Elliott Hughes21f32d72011-11-09 17:44:13 -08002581 CHECK_EQ(bytes.size(), 4U + (heap_count * (4 + 8 + 1 + 4 + 4 + 4 + 4)));
2582 Dbg::DdmSendChunk(CHUNK_TYPE("HPIF"), bytes);
Elliott Hughes767a1472011-10-26 18:49:02 -07002583}
2584
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002585enum HpsgSolidity {
2586 SOLIDITY_FREE = 0,
2587 SOLIDITY_HARD = 1,
2588 SOLIDITY_SOFT = 2,
2589 SOLIDITY_WEAK = 3,
2590 SOLIDITY_PHANTOM = 4,
2591 SOLIDITY_FINALIZABLE = 5,
2592 SOLIDITY_SWEEP = 6,
2593};
2594
2595enum HpsgKind {
2596 KIND_OBJECT = 0,
2597 KIND_CLASS_OBJECT = 1,
2598 KIND_ARRAY_1 = 2,
2599 KIND_ARRAY_2 = 3,
2600 KIND_ARRAY_4 = 4,
2601 KIND_ARRAY_8 = 5,
2602 KIND_UNKNOWN = 6,
2603 KIND_NATIVE = 7,
2604};
2605
2606#define HPSG_PARTIAL (1<<7)
2607#define HPSG_STATE(solidity, kind) ((uint8_t)((((kind) & 0x7) << 3) | ((solidity) & 0x7)))
2608
Ian Rogers30fab402012-01-23 15:43:46 -08002609class HeapChunkContext {
2610 public:
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002611 // Maximum chunk size. Obtain this from the formula:
2612 // (((maximum_heap_size / ALLOCATION_UNIT_SIZE) + 255) / 256) * 2
2613 HeapChunkContext(bool merge, bool native)
Ian Rogers30fab402012-01-23 15:43:46 -08002614 : buf_(16384 - 16),
2615 type_(0),
2616 merge_(merge) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002617 Reset();
2618 if (native) {
Ian Rogers30fab402012-01-23 15:43:46 -08002619 type_ = CHUNK_TYPE("NHSG");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002620 } else {
Ian Rogers30fab402012-01-23 15:43:46 -08002621 type_ = merge ? CHUNK_TYPE("HPSG") : CHUNK_TYPE("HPSO");
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002622 }
2623 }
2624
2625 ~HeapChunkContext() {
Ian Rogers30fab402012-01-23 15:43:46 -08002626 if (p_ > &buf_[0]) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002627 Flush();
2628 }
2629 }
2630
2631 void EnsureHeader(const void* chunk_ptr) {
Ian Rogers30fab402012-01-23 15:43:46 -08002632 if (!needHeader_) {
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002633 return;
2634 }
2635
2636 // Start a new HPSx chunk.
Ian Rogers30fab402012-01-23 15:43:46 -08002637 JDWP::Write4BE(&p_, 1); // Heap id (bogus; we only have one heap).
2638 JDWP::Write1BE(&p_, 8); // Size of allocation unit, in bytes.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002639
Ian Rogers30fab402012-01-23 15:43:46 -08002640 JDWP::Write4BE(&p_, reinterpret_cast<uintptr_t>(chunk_ptr)); // virtual address of segment start.
2641 JDWP::Write4BE(&p_, 0); // offset of this piece (relative to the virtual address).
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002642 // [u4]: length of piece, in allocation units
2643 // 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 -08002644 pieceLenField_ = p_;
2645 JDWP::Write4BE(&p_, 0x55555555);
2646 needHeader_ = false;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002647 }
2648
2649 void Flush() {
2650 // Patch the "length of piece" field.
Ian Rogers30fab402012-01-23 15:43:46 -08002651 CHECK_LE(&buf_[0], pieceLenField_);
2652 CHECK_LE(pieceLenField_, p_);
2653 JDWP::Set4BE(pieceLenField_, totalAllocationUnits_);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002654
Ian Rogers30fab402012-01-23 15:43:46 -08002655 Dbg::DdmSendChunk(type_, p_ - &buf_[0], &buf_[0]);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002656 Reset();
2657 }
2658
Ian Rogers30fab402012-01-23 15:43:46 -08002659 static void HeapChunkCallback(void* start, void* end, size_t used_bytes, void* arg) {
2660 reinterpret_cast<HeapChunkContext*>(arg)->HeapChunkCallback(start, end, used_bytes);
Elliott Hughesa2155262011-11-16 16:26:58 -08002661 }
2662
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002663 private:
Elliott Hughesa2155262011-11-16 16:26:58 -08002664 enum { ALLOCATION_UNIT_SIZE = 8 };
2665
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002666 void Reset() {
Ian Rogers30fab402012-01-23 15:43:46 -08002667 p_ = &buf_[0];
2668 totalAllocationUnits_ = 0;
2669 needHeader_ = true;
2670 pieceLenField_ = NULL;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002671 }
2672
Elliott Hughes1bac54f2012-03-16 12:48:31 -07002673 void HeapChunkCallback(void* start, void* /*end*/, size_t used_bytes) {
Ian Rogers30fab402012-01-23 15:43:46 -08002674 // Note: heap call backs cannot manipulate the heap upon which they are crawling, care is taken
2675 // in the following code not to allocate memory, by ensuring buf_ is of the correct size
2676
2677 const void* user_ptr = used_bytes > 0 ? const_cast<void*>(start) : NULL;
2678 // from malloc.c mem2chunk(mem)
2679 const void* chunk_ptr =
2680 reinterpret_cast<const void*>(reinterpret_cast<const char*>(const_cast<void*>(start)) -
2681 (2 * sizeof(size_t)));
2682 // from malloc.c chunksize
2683 size_t chunk_len = (*reinterpret_cast<size_t* const*>(chunk_ptr))[1] & ~7;
2684
2685
2686 //size_t chunk_len = malloc_usable_size(user_ptr);
Elliott Hughesa2155262011-11-16 16:26:58 -08002687 CHECK_EQ((chunk_len & (ALLOCATION_UNIT_SIZE-1)), 0U);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002688
Elliott Hughesa2155262011-11-16 16:26:58 -08002689 /* Make sure there's enough room left in the buffer.
2690 * We need to use two bytes for every fractional 256
2691 * allocation units used by the chunk.
2692 */
2693 {
2694 size_t needed = (((chunk_len/ALLOCATION_UNIT_SIZE + 255) / 256) * 2);
Ian Rogers30fab402012-01-23 15:43:46 -08002695 size_t bytesLeft = buf_.size() - (size_t)(p_ - &buf_[0]);
Elliott Hughesa2155262011-11-16 16:26:58 -08002696 if (bytesLeft < needed) {
2697 Flush();
2698 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002699
Ian Rogers30fab402012-01-23 15:43:46 -08002700 bytesLeft = buf_.size() - (size_t)(p_ - &buf_[0]);
Elliott Hughesa2155262011-11-16 16:26:58 -08002701 if (bytesLeft < needed) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08002702 LOG(WARNING) << "Chunk is too big to transmit (chunk_len=" << chunk_len << ", " << needed << " bytes)";
Elliott Hughesa2155262011-11-16 16:26:58 -08002703 return;
2704 }
2705 }
2706
2707 // OLD-TODO: notice when there's a gap and start a new heap, or at least a new range.
2708 EnsureHeader(chunk_ptr);
2709
2710 // Determine the type of this chunk.
2711 // OLD-TODO: if context.merge, see if this chunk is different from the last chunk.
2712 // If it's the same, we should combine them.
Ian Rogers30fab402012-01-23 15:43:46 -08002713 uint8_t state = ExamineObject(reinterpret_cast<const Object*>(user_ptr), (type_ == CHUNK_TYPE("NHSG")));
Elliott Hughesa2155262011-11-16 16:26:58 -08002714
2715 // Write out the chunk description.
2716 chunk_len /= ALLOCATION_UNIT_SIZE; // convert to allocation units
Ian Rogers30fab402012-01-23 15:43:46 -08002717 totalAllocationUnits_ += chunk_len;
Elliott Hughesa2155262011-11-16 16:26:58 -08002718 while (chunk_len > 256) {
Ian Rogers30fab402012-01-23 15:43:46 -08002719 *p_++ = state | HPSG_PARTIAL;
2720 *p_++ = 255; // length - 1
Elliott Hughesa2155262011-11-16 16:26:58 -08002721 chunk_len -= 256;
2722 }
Ian Rogers30fab402012-01-23 15:43:46 -08002723 *p_++ = state;
2724 *p_++ = chunk_len - 1;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002725 }
2726
Elliott Hughesa2155262011-11-16 16:26:58 -08002727 uint8_t ExamineObject(const Object* o, bool is_native_heap) {
2728 if (o == NULL) {
2729 return HPSG_STATE(SOLIDITY_FREE, 0);
2730 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002731
Elliott Hughesa2155262011-11-16 16:26:58 -08002732 // It's an allocated chunk. Figure out what it is.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002733
Elliott Hughesa2155262011-11-16 16:26:58 -08002734 // If we're looking at the native heap, we'll just return
2735 // (SOLIDITY_HARD, KIND_NATIVE) for all allocated chunks.
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08002736 if (is_native_heap || !Runtime::Current()->GetHeap()->IsLiveObjectLocked(o)) {
Elliott Hughesa2155262011-11-16 16:26:58 -08002737 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
2738 }
2739
2740 Class* c = o->GetClass();
2741 if (c == NULL) {
2742 // The object was probably just created but hasn't been initialized yet.
2743 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
2744 }
2745
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08002746 if (!Runtime::Current()->GetHeap()->IsHeapAddress(c)) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08002747 LOG(WARNING) << "Invalid class for managed heap object: " << o << " " << c;
Elliott Hughesa2155262011-11-16 16:26:58 -08002748 return HPSG_STATE(SOLIDITY_HARD, KIND_UNKNOWN);
2749 }
2750
2751 if (c->IsClassClass()) {
2752 return HPSG_STATE(SOLIDITY_HARD, KIND_CLASS_OBJECT);
2753 }
2754
2755 if (c->IsArrayClass()) {
2756 if (o->IsObjectArray()) {
2757 return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
2758 }
2759 switch (c->GetComponentSize()) {
2760 case 1: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_1);
2761 case 2: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_2);
2762 case 4: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
2763 case 8: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_8);
2764 }
2765 }
2766
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002767 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
2768 }
2769
Ian Rogers30fab402012-01-23 15:43:46 -08002770 std::vector<uint8_t> buf_;
2771 uint8_t* p_;
2772 uint8_t* pieceLenField_;
2773 size_t totalAllocationUnits_;
2774 uint32_t type_;
2775 bool merge_;
2776 bool needHeader_;
2777
Elliott Hughesa2155262011-11-16 16:26:58 -08002778 DISALLOW_COPY_AND_ASSIGN(HeapChunkContext);
2779};
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002780
2781void Dbg::DdmSendHeapSegments(bool native) {
2782 Dbg::HpsgWhen when;
2783 Dbg::HpsgWhat what;
2784 if (!native) {
2785 when = gDdmHpsgWhen;
2786 what = gDdmHpsgWhat;
2787 } else {
2788 when = gDdmNhsgWhen;
2789 what = gDdmNhsgWhat;
2790 }
2791 if (when == HPSG_WHEN_NEVER) {
2792 return;
2793 }
2794
2795 // Figure out what kind of chunks we'll be sending.
2796 CHECK(what == HPSG_WHAT_MERGED_OBJECTS || what == HPSG_WHAT_DISTINCT_OBJECTS) << static_cast<int>(what);
2797
2798 // First, send a heap start chunk.
2799 uint8_t heap_id[4];
2800 JDWP::Set4BE(&heap_id[0], 1); // Heap id (bogus; we only have one heap).
2801 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHST") : CHUNK_TYPE("HPST"), sizeof(heap_id), heap_id);
2802
2803 // Send a series of heap segment chunks.
Elliott Hughesa2155262011-11-16 16:26:58 -08002804 HeapChunkContext context((what == HPSG_WHAT_MERGED_OBJECTS), native);
2805 if (native) {
Ian Rogers30fab402012-01-23 15:43:46 -08002806 // TODO: enable when bionic has moved to dlmalloc 2.8.5
2807 // dlmalloc_inspect_all(HeapChunkContext::HeapChunkCallback, &context);
2808 UNIMPLEMENTED(WARNING) << "Native heap send heap segments";
Elliott Hughesa2155262011-11-16 16:26:58 -08002809 } else {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08002810 Heap* heap = Runtime::Current()->GetHeap();
2811 heap->GetAllocSpace()->Walk(HeapChunkContext::HeapChunkCallback, &context);
Elliott Hughesa2155262011-11-16 16:26:58 -08002812 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002813
2814 // Finally, send a heap end chunk.
2815 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHEN") : CHUNK_TYPE("HPEN"), sizeof(heap_id), heap_id);
Elliott Hughes767a1472011-10-26 18:49:02 -07002816}
2817
Elliott Hughes545a0642011-11-08 19:10:03 -08002818void Dbg::SetAllocTrackingEnabled(bool enabled) {
2819 MutexLock mu(gAllocTrackerLock);
2820 if (enabled) {
2821 if (recent_allocation_records_ == NULL) {
2822 LOG(INFO) << "Enabling alloc tracker (" << kNumAllocRecords << " entries, "
2823 << kMaxAllocRecordStackDepth << " frames --> "
2824 << (sizeof(AllocRecord) * kNumAllocRecords) << " bytes)";
2825 gAllocRecordHead = gAllocRecordCount = 0;
2826 recent_allocation_records_ = new AllocRecord[kNumAllocRecords];
2827 CHECK(recent_allocation_records_ != NULL);
2828 }
2829 } else {
2830 delete[] recent_allocation_records_;
2831 recent_allocation_records_ = NULL;
2832 }
2833}
2834
2835struct AllocRecordStackVisitor : public Thread::StackVisitor {
Elliott Hughesba8eee12012-01-24 20:25:24 -08002836 explicit AllocRecordStackVisitor(AllocRecord* record) : record(record), depth(0) {
Elliott Hughes545a0642011-11-08 19:10:03 -08002837 }
2838
Elliott Hughes530fa002012-03-12 11:44:49 -07002839 bool VisitFrame(const Frame& f, uintptr_t pc) {
Elliott Hughes545a0642011-11-08 19:10:03 -08002840 if (depth >= kMaxAllocRecordStackDepth) {
Elliott Hughes530fa002012-03-12 11:44:49 -07002841 return false;
Elliott Hughes545a0642011-11-08 19:10:03 -08002842 }
Elliott Hughes530fa002012-03-12 11:44:49 -07002843 if (f.HasMethod()) {
2844 record->stack[depth].method = f.GetMethod();
2845 record->stack[depth].raw_pc = pc;
2846 ++depth;
Elliott Hughes545a0642011-11-08 19:10:03 -08002847 }
Elliott Hughes530fa002012-03-12 11:44:49 -07002848 return true;
Elliott Hughes545a0642011-11-08 19:10:03 -08002849 }
2850
2851 ~AllocRecordStackVisitor() {
2852 // Clear out any unused stack trace elements.
2853 for (; depth < kMaxAllocRecordStackDepth; ++depth) {
2854 record->stack[depth].method = NULL;
2855 record->stack[depth].raw_pc = 0;
2856 }
2857 }
2858
2859 AllocRecord* record;
2860 size_t depth;
2861};
2862
2863void Dbg::RecordAllocation(Class* type, size_t byte_count) {
2864 Thread* self = Thread::Current();
2865 CHECK(self != NULL);
2866
2867 MutexLock mu(gAllocTrackerLock);
2868 if (recent_allocation_records_ == NULL) {
2869 return;
2870 }
2871
2872 // Advance and clip.
2873 if (++gAllocRecordHead == kNumAllocRecords) {
2874 gAllocRecordHead = 0;
2875 }
2876
2877 // Fill in the basics.
2878 AllocRecord* record = &recent_allocation_records_[gAllocRecordHead];
2879 record->type = type;
2880 record->byte_count = byte_count;
2881 record->thin_lock_id = self->GetThinLockId();
2882
2883 // Fill in the stack trace.
2884 AllocRecordStackVisitor visitor(record);
2885 self->WalkStack(&visitor);
2886
2887 if (gAllocRecordCount < kNumAllocRecords) {
2888 ++gAllocRecordCount;
2889 }
2890}
2891
2892/*
2893 * Return the index of the head element.
2894 *
2895 * We point at the most-recently-written record, so if allocRecordCount is 1
2896 * we want to use the current element. Take "head+1" and subtract count
2897 * from it.
2898 *
2899 * We need to handle underflow in our circular buffer, so we add
2900 * kNumAllocRecords and then mask it back down.
2901 */
2902inline static int headIndex() {
2903 return (gAllocRecordHead+1 + kNumAllocRecords - gAllocRecordCount) & (kNumAllocRecords-1);
2904}
2905
2906void Dbg::DumpRecentAllocations() {
2907 MutexLock mu(gAllocTrackerLock);
2908 if (recent_allocation_records_ == NULL) {
2909 LOG(INFO) << "Not recording tracked allocations";
2910 return;
2911 }
2912
2913 // "i" is the head of the list. We want to start at the end of the
2914 // list and move forward to the tail.
2915 size_t i = headIndex();
2916 size_t count = gAllocRecordCount;
2917
2918 LOG(INFO) << "Tracked allocations, (head=" << gAllocRecordHead << " count=" << count << ")";
2919 while (count--) {
2920 AllocRecord* record = &recent_allocation_records_[i];
2921
Elliott Hughesaa6e1cd2012-01-18 19:26:06 -08002922 LOG(INFO) << StringPrintf(" T=%-2d %6zd ", record->thin_lock_id, record->byte_count)
Elliott Hughes545a0642011-11-08 19:10:03 -08002923 << PrettyClass(record->type);
2924
2925 for (size_t stack_frame = 0; stack_frame < kMaxAllocRecordStackDepth; ++stack_frame) {
2926 const Method* m = record->stack[stack_frame].method;
2927 if (m == NULL) {
2928 break;
2929 }
2930 LOG(INFO) << " " << PrettyMethod(m) << " line " << record->stack[stack_frame].LineNumber();
2931 }
2932
2933 // pause periodically to help logcat catch up
2934 if ((count % 5) == 0) {
2935 usleep(40000);
2936 }
2937
2938 i = (i + 1) & (kNumAllocRecords-1);
2939 }
2940}
2941
2942class StringTable {
2943 public:
2944 StringTable() {
2945 }
2946
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002947 void Add(const char* s) {
Elliott Hughes545a0642011-11-08 19:10:03 -08002948 table_.insert(s);
2949 }
2950
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002951 size_t IndexOf(const char* s) {
Elliott Hughes545a0642011-11-08 19:10:03 -08002952 return std::distance(table_.begin(), table_.find(s));
2953 }
2954
2955 size_t Size() {
2956 return table_.size();
2957 }
2958
2959 void WriteTo(std::vector<uint8_t>& bytes) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002960 typedef std::set<const char*>::const_iterator It; // TODO: C++0x auto
Elliott Hughes545a0642011-11-08 19:10:03 -08002961 for (It it = table_.begin(); it != table_.end(); ++it) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002962 const char* s = *it;
2963 size_t s_len = CountModifiedUtf8Chars(s);
2964 UniquePtr<uint16_t> s_utf16(new uint16_t[s_len]);
2965 ConvertModifiedUtf8ToUtf16(s_utf16.get(), s);
2966 JDWP::AppendUtf16BE(bytes, s_utf16.get(), s_len);
Elliott Hughes545a0642011-11-08 19:10:03 -08002967 }
2968 }
2969
2970 private:
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002971 std::set<const char*> table_;
Elliott Hughes545a0642011-11-08 19:10:03 -08002972 DISALLOW_COPY_AND_ASSIGN(StringTable);
2973};
2974
2975/*
2976 * The data we send to DDMS contains everything we have recorded.
2977 *
2978 * Message header (all values big-endian):
2979 * (1b) message header len (to allow future expansion); includes itself
2980 * (1b) entry header len
2981 * (1b) stack frame len
2982 * (2b) number of entries
2983 * (4b) offset to string table from start of message
2984 * (2b) number of class name strings
2985 * (2b) number of method name strings
2986 * (2b) number of source file name strings
2987 * For each entry:
2988 * (4b) total allocation size
2989 * (2b) threadId
2990 * (2b) allocated object's class name index
2991 * (1b) stack depth
2992 * For each stack frame:
2993 * (2b) method's class name
2994 * (2b) method name
2995 * (2b) method source file
2996 * (2b) line number, clipped to 32767; -2 if native; -1 if no source
2997 * (xb) class name strings
2998 * (xb) method name strings
2999 * (xb) source file strings
3000 *
3001 * As with other DDM traffic, strings are sent as a 4-byte length
3002 * followed by UTF-16 data.
3003 *
3004 * We send up 16-bit unsigned indexes into string tables. In theory there
3005 * can be (kMaxAllocRecordStackDepth * kNumAllocRecords) unique strings in
3006 * each table, but in practice there should be far fewer.
3007 *
3008 * The chief reason for using a string table here is to keep the size of
3009 * the DDMS message to a minimum. This is partly to make the protocol
3010 * efficient, but also because we have to form the whole thing up all at
3011 * once in a memory buffer.
3012 *
3013 * We use separate string tables for class names, method names, and source
3014 * files to keep the indexes small. There will generally be no overlap
3015 * between the contents of these tables.
3016 */
3017jbyteArray Dbg::GetRecentAllocations() {
3018 if (false) {
3019 DumpRecentAllocations();
3020 }
3021
3022 MutexLock mu(gAllocTrackerLock);
3023
3024 /*
3025 * Part 1: generate string tables.
3026 */
3027 StringTable class_names;
3028 StringTable method_names;
3029 StringTable filenames;
3030
3031 int count = gAllocRecordCount;
3032 int idx = headIndex();
3033 while (count--) {
3034 AllocRecord* record = &recent_allocation_records_[idx];
3035
Elliott Hughes91250e02011-12-13 22:30:35 -08003036 class_names.Add(ClassHelper(record->type).GetDescriptor());
Elliott Hughes545a0642011-11-08 19:10:03 -08003037
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003038 MethodHelper mh;
Elliott Hughes545a0642011-11-08 19:10:03 -08003039 for (size_t i = 0; i < kMaxAllocRecordStackDepth; i++) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003040 Method* m = record->stack[i].method;
3041 mh.ChangeMethod(m);
Elliott Hughes545a0642011-11-08 19:10:03 -08003042 if (m != NULL) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003043 class_names.Add(mh.GetDeclaringClassDescriptor());
3044 method_names.Add(mh.GetName());
3045 filenames.Add(mh.GetDeclaringClassSourceFile());
Elliott Hughes545a0642011-11-08 19:10:03 -08003046 }
3047 }
3048
3049 idx = (idx + 1) & (kNumAllocRecords-1);
3050 }
3051
3052 LOG(INFO) << "allocation records: " << gAllocRecordCount;
3053
3054 /*
3055 * Part 2: allocate a buffer and generate the output.
3056 */
3057 std::vector<uint8_t> bytes;
3058
3059 // (1b) message header len (to allow future expansion); includes itself
3060 // (1b) entry header len
3061 // (1b) stack frame len
3062 const int kMessageHeaderLen = 15;
3063 const int kEntryHeaderLen = 9;
3064 const int kStackFrameLen = 8;
3065 JDWP::Append1BE(bytes, kMessageHeaderLen);
3066 JDWP::Append1BE(bytes, kEntryHeaderLen);
3067 JDWP::Append1BE(bytes, kStackFrameLen);
3068
3069 // (2b) number of entries
3070 // (4b) offset to string table from start of message
3071 // (2b) number of class name strings
3072 // (2b) number of method name strings
3073 // (2b) number of source file name strings
3074 JDWP::Append2BE(bytes, gAllocRecordCount);
3075 size_t string_table_offset = bytes.size();
3076 JDWP::Append4BE(bytes, 0); // We'll patch this later...
3077 JDWP::Append2BE(bytes, class_names.Size());
3078 JDWP::Append2BE(bytes, method_names.Size());
3079 JDWP::Append2BE(bytes, filenames.Size());
3080
3081 count = gAllocRecordCount;
3082 idx = headIndex();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003083 ClassHelper kh;
Elliott Hughes545a0642011-11-08 19:10:03 -08003084 while (count--) {
3085 // For each entry:
3086 // (4b) total allocation size
3087 // (2b) thread id
3088 // (2b) allocated object's class name index
3089 // (1b) stack depth
3090 AllocRecord* record = &recent_allocation_records_[idx];
3091 size_t stack_depth = record->GetDepth();
3092 JDWP::Append4BE(bytes, record->byte_count);
3093 JDWP::Append2BE(bytes, record->thin_lock_id);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003094 kh.ChangeClass(record->type);
Elliott Hughes91250e02011-12-13 22:30:35 -08003095 JDWP::Append2BE(bytes, class_names.IndexOf(kh.GetDescriptor()));
Elliott Hughes545a0642011-11-08 19:10:03 -08003096 JDWP::Append1BE(bytes, stack_depth);
3097
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003098 MethodHelper mh;
Elliott Hughes545a0642011-11-08 19:10:03 -08003099 for (size_t stack_frame = 0; stack_frame < stack_depth; ++stack_frame) {
3100 // For each stack frame:
3101 // (2b) method's class name
3102 // (2b) method name
3103 // (2b) method source file
3104 // (2b) line number, clipped to 32767; -2 if native; -1 if no source
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003105 mh.ChangeMethod(record->stack[stack_frame].method);
3106 JDWP::Append2BE(bytes, class_names.IndexOf(mh.GetDeclaringClassDescriptor()));
3107 JDWP::Append2BE(bytes, method_names.IndexOf(mh.GetName()));
3108 JDWP::Append2BE(bytes, filenames.IndexOf(mh.GetDeclaringClassSourceFile()));
Elliott Hughes545a0642011-11-08 19:10:03 -08003109 JDWP::Append2BE(bytes, record->stack[stack_frame].LineNumber());
3110 }
3111
3112 idx = (idx + 1) & (kNumAllocRecords-1);
3113 }
3114
3115 // (xb) class name strings
3116 // (xb) method name strings
3117 // (xb) source file strings
3118 JDWP::Set4BE(&bytes[string_table_offset], bytes.size());
3119 class_names.WriteTo(bytes);
3120 method_names.WriteTo(bytes);
3121 filenames.WriteTo(bytes);
3122
3123 JNIEnv* env = Thread::Current()->GetJniEnv();
3124 jbyteArray result = env->NewByteArray(bytes.size());
3125 if (result != NULL) {
3126 env->SetByteArrayRegion(result, 0, bytes.size(), reinterpret_cast<const jbyte*>(&bytes[0]));
3127 }
3128 return result;
3129}
3130
Elliott Hughes872d4ec2011-10-21 17:07:15 -07003131} // namespace art