blob: eede552e5954fb544f9e3e8ba0ebc6b13beff325 [file] [log] [blame]
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "debugger.h"
18
Elliott Hughes3bb81562011-10-21 18:52:59 -070019#include <sys/uio.h>
20
Elliott Hughes545a0642011-11-08 19:10:03 -080021#include <set>
22
23#include "class_linker.h"
Elliott Hughes1bba14f2011-12-01 18:00:36 -080024#include "class_loader.h"
Elliott Hughes68fdbd02011-11-29 19:22:47 -080025#include "context.h"
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080026#include "object_utils.h"
Elliott Hughes6a5bd492011-10-28 14:33:57 -070027#include "ScopedLocalRef.h"
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -070028#include "ScopedPrimitiveArray.h"
Elliott Hughes47fce012011-10-25 18:37:19 -070029#include "stack_indirect_reference_table.h"
Elliott Hughes475fc232011-10-25 15:00:35 -070030#include "thread_list.h"
31
Elliott Hughes6a5bd492011-10-28 14:33:57 -070032extern "C" void dlmalloc_walk_heap(void(*)(const void*, size_t, const void*, size_t, void*), void*);
33#ifndef HAVE_ANDROID_OS
34void dlmalloc_walk_heap(void(*)(const void*, size_t, const void*, size_t, void*), void*) {
35 // No-op for glibc.
36}
37#endif
38
Elliott Hughes872d4ec2011-10-21 17:07:15 -070039namespace art {
40
Elliott Hughes545a0642011-11-08 19:10:03 -080041static const size_t kMaxAllocRecordStackDepth = 16; // Max 255.
42static const size_t kNumAllocRecords = 512; // Must be power of 2.
43
Elliott Hughes475fc232011-10-25 15:00:35 -070044class ObjectRegistry {
45 public:
46 ObjectRegistry() : lock_("ObjectRegistry lock") {
47 }
48
49 JDWP::ObjectId Add(Object* o) {
50 if (o == NULL) {
51 return 0;
52 }
53 JDWP::ObjectId id = static_cast<JDWP::ObjectId>(reinterpret_cast<uintptr_t>(o));
54 MutexLock mu(lock_);
55 map_[id] = o;
56 return id;
57 }
58
Elliott Hughes234ab152011-10-26 14:02:26 -070059 void Clear() {
60 MutexLock mu(lock_);
61 LOG(DEBUG) << "Debugger has detached; object registry had " << map_.size() << " entries";
62 map_.clear();
63 }
64
Elliott Hughes475fc232011-10-25 15:00:35 -070065 bool Contains(JDWP::ObjectId id) {
66 MutexLock mu(lock_);
67 return map_.find(id) != map_.end();
68 }
69
Elliott Hughesa2155262011-11-16 16:26:58 -080070 template<typename T> T Get(JDWP::ObjectId id) {
71 MutexLock mu(lock_);
72 typedef std::map<JDWP::ObjectId, Object*>::iterator It; // C++0x auto
73 It it = map_.find(id);
74 return (it != map_.end()) ? reinterpret_cast<T>(it->second) : NULL;
75 }
76
Elliott Hughesbfe487b2011-10-26 15:48:55 -070077 void VisitRoots(Heap::RootVisitor* visitor, void* arg) {
78 MutexLock mu(lock_);
79 typedef std::map<JDWP::ObjectId, Object*>::iterator It; // C++0x auto
80 for (It it = map_.begin(); it != map_.end(); ++it) {
81 visitor(it->second, arg);
82 }
83 }
84
Elliott Hughes475fc232011-10-25 15:00:35 -070085 private:
86 Mutex lock_;
87 std::map<JDWP::ObjectId, Object*> map_;
88};
89
Elliott Hughes545a0642011-11-08 19:10:03 -080090struct AllocRecordStackTraceElement {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080091 Method* method;
Elliott Hughes545a0642011-11-08 19:10:03 -080092 uintptr_t raw_pc;
93
94 int32_t LineNumber() const {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080095 return MethodHelper(method).GetLineNumFromNativePC(raw_pc);
Elliott Hughes545a0642011-11-08 19:10:03 -080096 }
97};
98
99struct AllocRecord {
100 Class* type;
101 size_t byte_count;
102 uint16_t thin_lock_id;
103 AllocRecordStackTraceElement stack[kMaxAllocRecordStackDepth]; // Unused entries have NULL method.
104
105 size_t GetDepth() {
106 size_t depth = 0;
107 while (depth < kMaxAllocRecordStackDepth && stack[depth].method != NULL) {
108 ++depth;
109 }
110 return depth;
111 }
112};
113
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700114// JDWP is allowed unless the Zygote forbids it.
115static bool gJdwpAllowed = true;
116
Elliott Hughes3bb81562011-10-21 18:52:59 -0700117// Was there a -Xrunjdwp or -agent argument on the command-line?
118static bool gJdwpConfigured = false;
119
120// Broken-down JDWP options. (Only valid if gJdwpConfigured is true.)
Elliott Hughes376a7a02011-10-24 18:35:55 -0700121static JDWP::JdwpOptions gJdwpOptions;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700122
123// Runtime JDWP state.
124static JDWP::JdwpState* gJdwpState = NULL;
125static bool gDebuggerConnected; // debugger or DDMS is connected.
126static bool gDebuggerActive; // debugger is making requests.
127
Elliott Hughes47fce012011-10-25 18:37:19 -0700128static bool gDdmThreadNotification = false;
129
Elliott Hughes767a1472011-10-26 18:49:02 -0700130// DDMS GC-related settings.
131static Dbg::HpifWhen gDdmHpifWhen = Dbg::HPIF_WHEN_NEVER;
132static Dbg::HpsgWhen gDdmHpsgWhen = Dbg::HPSG_WHEN_NEVER;
133static Dbg::HpsgWhat gDdmHpsgWhat;
134static Dbg::HpsgWhen gDdmNhsgWhen = Dbg::HPSG_WHEN_NEVER;
135static Dbg::HpsgWhat gDdmNhsgWhat;
136
Elliott Hughes475fc232011-10-25 15:00:35 -0700137static ObjectRegistry* gRegistry = NULL;
138
Elliott Hughes545a0642011-11-08 19:10:03 -0800139// Recent allocation tracking.
140static Mutex gAllocTrackerLock("AllocTracker lock");
141AllocRecord* Dbg::recent_allocation_records_ = NULL; // TODO: CircularBuffer<AllocRecord>
142static size_t gAllocRecordHead = 0;
143static size_t gAllocRecordCount = 0;
144
Elliott Hughes24437992011-11-30 14:49:33 -0800145static JDWP::JdwpTag BasicTagFromDescriptor(const char* descriptor) {
146 // JDWP deliberately uses the descriptor characters' ASCII values for its enum.
147 // Note that by "basic" we mean that we don't get more specific than JT_OBJECT.
148 return static_cast<JDWP::JdwpTag>(descriptor[0]);
149}
150
151static JDWP::JdwpTag TagFromClass(Class* c) {
Elliott Hughes86b00102011-12-05 17:54:26 -0800152 CHECK(c != NULL);
Elliott Hughes24437992011-11-30 14:49:33 -0800153 if (c->IsArrayClass()) {
154 return JDWP::JT_ARRAY;
155 }
156
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800157 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Elliott Hughes24437992011-11-30 14:49:33 -0800158 if (c->IsStringClass()) {
159 return JDWP::JT_STRING;
160 } else if (c->IsClassClass()) {
161 return JDWP::JT_CLASS_OBJECT;
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800162 } else if (c->InstanceOf(class_linker->FindSystemClass("Ljava/lang/Thread;"))) {
Elliott Hughes24437992011-11-30 14:49:33 -0800163 return JDWP::JT_THREAD;
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800164 } else if (c->InstanceOf(class_linker->FindSystemClass("Ljava/lang/ThreadGroup;"))) {
Elliott Hughes24437992011-11-30 14:49:33 -0800165 return JDWP::JT_THREAD_GROUP;
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800166 } else if (c->InstanceOf(class_linker->FindSystemClass("Ljava/lang/ClassLoader;"))) {
Elliott Hughes24437992011-11-30 14:49:33 -0800167 return JDWP::JT_CLASS_LOADER;
Elliott Hughes24437992011-11-30 14:49:33 -0800168 } else {
169 return JDWP::JT_OBJECT;
170 }
171}
172
173/*
174 * Objects declared to hold Object might actually hold a more specific
175 * type. The debugger may take a special interest in these (e.g. it
176 * wants to display the contents of Strings), so we want to return an
177 * appropriate tag.
178 *
179 * Null objects are tagged JT_OBJECT.
180 */
181static JDWP::JdwpTag TagFromObject(const Object* o) {
182 return (o == NULL) ? JDWP::JT_OBJECT : TagFromClass(o->GetClass());
183}
184
185static bool IsPrimitiveTag(JDWP::JdwpTag tag) {
186 switch (tag) {
187 case JDWP::JT_BOOLEAN:
188 case JDWP::JT_BYTE:
189 case JDWP::JT_CHAR:
190 case JDWP::JT_FLOAT:
191 case JDWP::JT_DOUBLE:
192 case JDWP::JT_INT:
193 case JDWP::JT_LONG:
194 case JDWP::JT_SHORT:
195 case JDWP::JT_VOID:
196 return true;
197 default:
198 return false;
199 }
200}
201
Elliott Hughes3bb81562011-10-21 18:52:59 -0700202/*
203 * Handle one of the JDWP name/value pairs.
204 *
205 * JDWP options are:
206 * help: if specified, show help message and bail
207 * transport: may be dt_socket or dt_shmem
208 * address: for dt_socket, "host:port", or just "port" when listening
209 * server: if "y", wait for debugger to attach; if "n", attach to debugger
210 * timeout: how long to wait for debugger to connect / listen
211 *
212 * Useful with server=n (these aren't supported yet):
213 * onthrow=<exception-name>: connect to debugger when exception thrown
214 * onuncaught=y|n: connect to debugger when uncaught exception thrown
215 * launch=<command-line>: launch the debugger itself
216 *
217 * The "transport" option is required, as is "address" if server=n.
218 */
219static bool ParseJdwpOption(const std::string& name, const std::string& value) {
220 if (name == "transport") {
221 if (value == "dt_socket") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700222 gJdwpOptions.transport = JDWP::kJdwpTransportSocket;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700223 } else if (value == "dt_android_adb") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700224 gJdwpOptions.transport = JDWP::kJdwpTransportAndroidAdb;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700225 } else {
226 LOG(ERROR) << "JDWP transport not supported: " << value;
227 return false;
228 }
229 } else if (name == "server") {
230 if (value == "n") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700231 gJdwpOptions.server = false;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700232 } else if (value == "y") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700233 gJdwpOptions.server = true;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700234 } else {
235 LOG(ERROR) << "JDWP option 'server' must be 'y' or 'n'";
236 return false;
237 }
238 } else if (name == "suspend") {
239 if (value == "n") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700240 gJdwpOptions.suspend = false;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700241 } else if (value == "y") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700242 gJdwpOptions.suspend = true;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700243 } else {
244 LOG(ERROR) << "JDWP option 'suspend' must be 'y' or 'n'";
245 return false;
246 }
247 } else if (name == "address") {
248 /* this is either <port> or <host>:<port> */
249 std::string port_string;
Elliott Hughes376a7a02011-10-24 18:35:55 -0700250 gJdwpOptions.host.clear();
Elliott Hughes3bb81562011-10-21 18:52:59 -0700251 std::string::size_type colon = value.find(':');
252 if (colon != std::string::npos) {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700253 gJdwpOptions.host = value.substr(0, colon);
Elliott Hughes3bb81562011-10-21 18:52:59 -0700254 port_string = value.substr(colon + 1);
255 } else {
256 port_string = value;
257 }
258 if (port_string.empty()) {
259 LOG(ERROR) << "JDWP address missing port: " << value;
260 return false;
261 }
262 char* end;
263 long port = strtol(port_string.c_str(), &end, 10);
264 if (*end != '\0') {
265 LOG(ERROR) << "JDWP address has junk in port field: " << value;
266 return false;
267 }
Elliott Hughes376a7a02011-10-24 18:35:55 -0700268 gJdwpOptions.port = port;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700269 } else if (name == "launch" || name == "onthrow" || name == "oncaught" || name == "timeout") {
270 /* valid but unsupported */
271 LOG(INFO) << "Ignoring JDWP option '" << name << "'='" << value << "'";
272 } else {
273 LOG(INFO) << "Ignoring unrecognized JDWP option '" << name << "'='" << value << "'";
274 }
275
276 return true;
277}
278
279/*
280 * Parse the latter half of a -Xrunjdwp/-agentlib:jdwp= string, e.g.:
281 * "transport=dt_socket,address=8000,server=y,suspend=n"
282 */
283bool Dbg::ParseJdwpOptions(const std::string& options) {
Elliott Hughes47fce012011-10-25 18:37:19 -0700284 LOG(VERBOSE) << "ParseJdwpOptions: " << options;
285
Elliott Hughes3bb81562011-10-21 18:52:59 -0700286 std::vector<std::string> pairs;
287 Split(options, ',', pairs);
288
289 for (size_t i = 0; i < pairs.size(); ++i) {
290 std::string::size_type equals = pairs[i].find('=');
291 if (equals == std::string::npos) {
292 LOG(ERROR) << "Can't parse JDWP option '" << pairs[i] << "' in '" << options << "'";
293 return false;
294 }
295 ParseJdwpOption(pairs[i].substr(0, equals), pairs[i].substr(equals + 1));
296 }
297
Elliott Hughes376a7a02011-10-24 18:35:55 -0700298 if (gJdwpOptions.transport == JDWP::kJdwpTransportUnknown) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700299 LOG(ERROR) << "Must specify JDWP transport: " << options;
300 }
Elliott Hughes376a7a02011-10-24 18:35:55 -0700301 if (!gJdwpOptions.server && (gJdwpOptions.host.empty() || gJdwpOptions.port == 0)) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700302 LOG(ERROR) << "Must specify JDWP host and port when server=n: " << options;
303 return false;
304 }
305
306 gJdwpConfigured = true;
307 return true;
308}
309
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700310void Dbg::StartJdwp() {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700311 if (!gJdwpAllowed || !gJdwpConfigured) {
312 // No JDWP for you!
313 return;
314 }
315
Elliott Hughes475fc232011-10-25 15:00:35 -0700316 CHECK(gRegistry == NULL);
317 gRegistry = new ObjectRegistry;
318
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700319 // Init JDWP if the debugger is enabled. This may connect out to a
320 // debugger, passively listen for a debugger, or block waiting for a
321 // debugger.
Elliott Hughes376a7a02011-10-24 18:35:55 -0700322 gJdwpState = JDWP::JdwpState::Create(&gJdwpOptions);
323 if (gJdwpState == NULL) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -0800324 // We probably failed because some other process has the port already, which means that
325 // if we don't abort the user is likely to think they're talking to us when they're actually
326 // talking to that other process.
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800327 LOG(FATAL) << "Debugger thread failed to initialize";
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700328 }
329
330 // If a debugger has already attached, send the "welcome" message.
331 // This may cause us to suspend all threads.
Elliott Hughes376a7a02011-10-24 18:35:55 -0700332 if (gJdwpState->IsActive()) {
Elliott Hughesa2155262011-11-16 16:26:58 -0800333 //ScopedThreadStateChange tsc(Thread::Current(), Thread::kRunnable);
Elliott Hughes376a7a02011-10-24 18:35:55 -0700334 if (!gJdwpState->PostVMStart()) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800335 LOG(WARNING) << "Failed to post 'start' message to debugger";
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700336 }
337 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700338}
339
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700340void Dbg::StopJdwp() {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700341 delete gJdwpState;
Elliott Hughes475fc232011-10-25 15:00:35 -0700342 delete gRegistry;
343 gRegistry = NULL;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700344}
345
Elliott Hughes767a1472011-10-26 18:49:02 -0700346void Dbg::GcDidFinish() {
347 if (gDdmHpifWhen != HPIF_WHEN_NEVER) {
348 LOG(DEBUG) << "Sending VM heap info to DDM";
Elliott Hughes7162ad92011-10-27 14:08:42 -0700349 DdmSendHeapInfo(gDdmHpifWhen);
Elliott Hughes767a1472011-10-26 18:49:02 -0700350 }
351 if (gDdmHpsgWhen != HPSG_WHEN_NEVER) {
352 LOG(DEBUG) << "Dumping VM heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700353 DdmSendHeapSegments(false);
Elliott Hughes767a1472011-10-26 18:49:02 -0700354 }
355 if (gDdmNhsgWhen != HPSG_WHEN_NEVER) {
356 LOG(DEBUG) << "Dumping native heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700357 DdmSendHeapSegments(true);
Elliott Hughes767a1472011-10-26 18:49:02 -0700358 }
359}
360
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700361void Dbg::SetJdwpAllowed(bool allowed) {
362 gJdwpAllowed = allowed;
363}
364
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700365DebugInvokeReq* Dbg::GetInvokeReq() {
Elliott Hughes475fc232011-10-25 15:00:35 -0700366 return Thread::Current()->GetInvokeReq();
367}
368
369Thread* Dbg::GetDebugThread() {
370 return (gJdwpState != NULL) ? gJdwpState->GetDebugThread() : NULL;
371}
372
373void Dbg::ClearWaitForEventThread() {
374 gJdwpState->ClearWaitForEventThread();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700375}
376
377void Dbg::Connected() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700378 CHECK(!gDebuggerConnected);
379 LOG(VERBOSE) << "JDWP has attached";
380 gDebuggerConnected = true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700381}
382
Elliott Hughesa2155262011-11-16 16:26:58 -0800383void Dbg::GoActive() {
384 // Enable all debugging features, including scans for breakpoints.
385 // This is a no-op if we're already active.
386 // Only called from the JDWP handler thread.
387 if (gDebuggerActive) {
388 return;
389 }
390
391 LOG(INFO) << "Debugger is active";
392
393 // TODO: CHECK we don't have any outstanding breakpoints.
394
395 gDebuggerActive = true;
396
397 //dvmEnableAllSubMode(kSubModeDebuggerActive);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700398}
399
400void Dbg::Disconnected() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700401 CHECK(gDebuggerConnected);
402
403 gDebuggerActive = false;
404
405 //dvmDisableAllSubMode(kSubModeDebuggerActive);
406
407 gRegistry->Clear();
408 gDebuggerConnected = false;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700409}
410
411bool Dbg::IsDebuggerConnected() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700412 return gDebuggerActive;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700413}
414
415bool Dbg::IsDebuggingEnabled() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700416 return gJdwpConfigured;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700417}
418
419int64_t Dbg::LastDebuggerActivity() {
Elliott Hughesca951522011-12-05 12:01:32 -0800420 return gJdwpState->LastDebuggerActivity();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700421}
422
423int Dbg::ThreadRunning() {
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700424 return static_cast<int>(Thread::Current()->SetState(Thread::kRunnable));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700425}
426
427int Dbg::ThreadWaiting() {
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700428 return static_cast<int>(Thread::Current()->SetState(Thread::kVmWait));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700429}
430
Elliott Hughes6ba581a2011-10-25 11:45:35 -0700431int Dbg::ThreadContinuing(int new_state) {
432 return static_cast<int>(Thread::Current()->SetState(static_cast<Thread::State>(new_state)));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700433}
434
435void Dbg::UndoDebuggerSuspensions() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700436 Runtime::Current()->GetThreadList()->UndoDebuggerSuspensions();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700437}
438
439void Dbg::Exit(int status) {
Elliott Hughes1bba14f2011-12-01 18:00:36 -0800440 exit(status); // This is all dalvik did.
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700441}
442
Elliott Hughesbfe487b2011-10-26 15:48:55 -0700443void Dbg::VisitRoots(Heap::RootVisitor* visitor, void* arg) {
444 if (gRegistry != NULL) {
445 gRegistry->VisitRoots(visitor, arg);
446 }
447}
448
Elliott Hughesa2155262011-11-16 16:26:58 -0800449std::string Dbg::GetClassDescriptor(JDWP::RefTypeId classId) {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800450 Object* o = gRegistry->Get<Object*>(classId);
451 if (o == NULL || !o->IsClass()) {
452 return StringPrintf("non-class %p", o); // This is only used for debugging output anyway.
453 }
454 return ClassHelper(o->AsClass()).GetDescriptor();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700455}
456
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800457bool Dbg::GetClassObject(JDWP::RefTypeId id, JDWP::ObjectId& classObjectId) {
458 Object* o = gRegistry->Get<Object*>(id);
459 if (o == NULL || !o->IsClass()) {
460 return false;
461 }
462 classObjectId = gRegistry->Add(o);
463 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700464}
465
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800466bool Dbg::GetSuperclass(JDWP::RefTypeId id, JDWP::RefTypeId& superclassId) {
467 Object* o = gRegistry->Get<Object*>(id);
468 if (o == NULL || !o->IsClass()) {
469 return false;
470 }
471 superclassId = gRegistry->Add(o->AsClass()->GetSuperClass());
472 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700473}
474
475JDWP::ObjectId Dbg::GetClassLoader(JDWP::RefTypeId id) {
Elliott Hughes1bba14f2011-12-01 18:00:36 -0800476 Object* o = gRegistry->Get<Object*>(id);
477 return gRegistry->Add(o->GetClass()->GetClassLoader());
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700478}
479
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800480bool Dbg::GetAccessFlags(JDWP::RefTypeId id, uint32_t& access_flags) {
481 Object* o = gRegistry->Get<Object*>(id);
482 if (o == NULL || !o->IsClass()) {
483 return false;
484 }
485 access_flags = o->AsClass()->GetAccessFlags() & kAccJavaFlagsMask;
486 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700487}
488
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800489bool Dbg::IsInterface(JDWP::RefTypeId classId, bool& is_interface) {
490 Object* o = gRegistry->Get<Object*>(classId);
491 if (o == NULL || !o->IsClass()) {
492 return false;
493 }
494 is_interface = o->AsClass()->IsInterface();
495 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700496}
497
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800498void Dbg::GetClassList(std::vector<JDWP::RefTypeId>& classes) {
Elliott Hughesa2155262011-11-16 16:26:58 -0800499 // Get the complete list of reference classes (i.e. all classes except
500 // the primitive types).
501 // Returns a newly-allocated buffer full of RefTypeId values.
502 struct ClassListCreator {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800503 ClassListCreator(std::vector<JDWP::RefTypeId>& classes) : classes(classes) {
504 }
505
Elliott Hughesa2155262011-11-16 16:26:58 -0800506 static bool Visit(Class* c, void* arg) {
507 return reinterpret_cast<ClassListCreator*>(arg)->Visit(c);
508 }
509
510 bool Visit(Class* c) {
511 if (!c->IsPrimitive()) {
512 classes.push_back(static_cast<JDWP::RefTypeId>(gRegistry->Add(c)));
513 }
514 return true;
515 }
516
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800517 std::vector<JDWP::RefTypeId>& classes;
Elliott Hughesa2155262011-11-16 16:26:58 -0800518 };
519
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800520 ClassListCreator clc(classes);
Elliott Hughesa2155262011-11-16 16:26:58 -0800521 Runtime::Current()->GetClassLinker()->VisitClasses(ClassListCreator::Visit, &clc);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700522}
523
524void Dbg::GetVisibleClassList(JDWP::ObjectId classLoaderId, uint32_t* pNumClasses, JDWP::RefTypeId** pClassRefBuf) {
525 UNIMPLEMENTED(FATAL);
526}
527
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800528bool Dbg::GetClassInfo(JDWP::RefTypeId classId, JDWP::JdwpTypeTag* pTypeTag, uint32_t* pStatus, std::string* pDescriptor) {
529 Object* o = gRegistry->Get<Object*>(classId);
530 if (o == NULL || !o->IsClass()) {
531 return false;
532 }
533
534 Class* c = o->AsClass();
Elliott Hughesa2155262011-11-16 16:26:58 -0800535 if (c->IsArrayClass()) {
536 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
537 *pTypeTag = JDWP::TT_ARRAY;
538 } else {
539 if (c->IsErroneous()) {
540 *pStatus = JDWP::CS_ERROR;
541 } else {
542 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED | JDWP::CS_INITIALIZED;
543 }
544 *pTypeTag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
545 }
546
547 if (pDescriptor != NULL) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800548 *pDescriptor = ClassHelper(c).GetDescriptor();
Elliott Hughesa2155262011-11-16 16:26:58 -0800549 }
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800550 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700551}
552
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800553void Dbg::FindLoadedClassBySignature(const std::string& descriptor, std::vector<JDWP::RefTypeId>& ids) {
Elliott Hughes6fa602d2011-12-02 17:54:25 -0800554 std::vector<Class*> classes;
555 Runtime::Current()->GetClassLinker()->LookupClasses(descriptor, classes);
556 ids.clear();
557 for (size_t i = 0; i < classes.size(); ++i) {
558 ids.push_back(gRegistry->Add(classes[i]));
559 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700560}
561
Elliott Hughes6fa602d2011-12-02 17:54:25 -0800562void Dbg::GetObjectType(JDWP::ObjectId objectId, JDWP::JdwpTypeTag* pRefTypeTag, JDWP::RefTypeId* pRefTypeId) {
Elliott Hughes499c5132011-11-17 14:55:11 -0800563 Object* o = gRegistry->Get<Object*>(objectId);
564 if (o->GetClass()->IsArrayClass()) {
565 *pRefTypeTag = JDWP::TT_ARRAY;
566 } else if (o->GetClass()->IsInterface()) {
567 *pRefTypeTag = JDWP::TT_INTERFACE;
568 } else {
569 *pRefTypeTag = JDWP::TT_CLASS;
570 }
571 *pRefTypeId = gRegistry->Add(o->GetClass());
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700572}
573
574uint8_t Dbg::GetClassObjectType(JDWP::RefTypeId refTypeId) {
575 UNIMPLEMENTED(FATAL);
576 return 0;
577}
578
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800579bool Dbg::GetSignature(JDWP::RefTypeId refTypeId, std::string& signature) {
580 Object* o = gRegistry->Get<Object*>(refTypeId);
581 if (o == NULL || !o->IsClass()) {
582 return false;
583 }
584 signature = ClassHelper(o->AsClass()).GetDescriptor();
585 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700586}
587
Elliott Hughes03181a82011-11-17 17:22:21 -0800588bool Dbg::GetSourceFile(JDWP::RefTypeId refTypeId, std::string& result) {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800589 Object* o = gRegistry->Get<Object*>(refTypeId);
590 if (o == NULL || !o->IsClass()) {
591 return false;
592 }
593 result = ClassHelper(o->AsClass()).GetSourceFile();
594 return result != NULL;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700595}
596
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700597uint8_t Dbg::GetObjectTag(JDWP::ObjectId objectId) {
Elliott Hughes24437992011-11-30 14:49:33 -0800598 Object* o = gRegistry->Get<Object*>(objectId);
599 return TagFromObject(o);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700600}
601
Elliott Hughesaed4be92011-12-02 16:16:23 -0800602size_t Dbg::GetTagWidth(JDWP::JdwpTag tag) {
Elliott Hughesdbb40792011-11-18 17:05:22 -0800603 switch (tag) {
604 case JDWP::JT_VOID:
605 return 0;
606 case JDWP::JT_BYTE:
607 case JDWP::JT_BOOLEAN:
608 return 1;
609 case JDWP::JT_CHAR:
610 case JDWP::JT_SHORT:
611 return 2;
612 case JDWP::JT_FLOAT:
613 case JDWP::JT_INT:
614 return 4;
615 case JDWP::JT_ARRAY:
616 case JDWP::JT_OBJECT:
617 case JDWP::JT_STRING:
618 case JDWP::JT_THREAD:
619 case JDWP::JT_THREAD_GROUP:
620 case JDWP::JT_CLASS_LOADER:
621 case JDWP::JT_CLASS_OBJECT:
622 return sizeof(JDWP::ObjectId);
623 case JDWP::JT_DOUBLE:
624 case JDWP::JT_LONG:
625 return 8;
626 default:
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800627 LOG(FATAL) << "Unknown tag " << tag;
Elliott Hughesdbb40792011-11-18 17:05:22 -0800628 return -1;
629 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700630}
631
632int Dbg::GetArrayLength(JDWP::ObjectId arrayId) {
Elliott Hughes68fdbd02011-11-29 19:22:47 -0800633 Object* o = gRegistry->Get<Object*>(arrayId);
634 Array* a = o->AsArray();
635 return a->GetLength();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700636}
637
638uint8_t Dbg::GetArrayElementTag(JDWP::ObjectId arrayId) {
Elliott Hughes24437992011-11-30 14:49:33 -0800639 Object* o = gRegistry->Get<Object*>(arrayId);
640 Array* a = o->AsArray();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800641 std::string descriptor(ClassHelper(a->GetClass()).GetDescriptor());
Elliott Hughes24437992011-11-30 14:49:33 -0800642 JDWP::JdwpTag tag = BasicTagFromDescriptor(descriptor.c_str() + 1);
643 if (!IsPrimitiveTag(tag)) {
644 tag = TagFromClass(a->GetClass()->GetComponentType());
645 }
646 return tag;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700647}
648
Elliott Hughes24437992011-11-30 14:49:33 -0800649bool Dbg::OutputArray(JDWP::ObjectId arrayId, int offset, int count, JDWP::ExpandBuf* pReply) {
650 Object* o = gRegistry->Get<Object*>(arrayId);
651 Array* a = o->AsArray();
652
653 if (offset < 0 || count < 0 || offset > a->GetLength() || a->GetLength() - offset < count) {
654 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
655 return false;
656 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800657 std::string descriptor(ClassHelper(a->GetClass()).GetDescriptor());
Elliott Hughes24437992011-11-30 14:49:33 -0800658 JDWP::JdwpTag tag = BasicTagFromDescriptor(descriptor.c_str() + 1);
659
660 if (IsPrimitiveTag(tag)) {
661 size_t width = GetTagWidth(tag);
662 const uint8_t* src = reinterpret_cast<uint8_t*>(a->GetRawData());
663 uint8_t* dst = expandBufAddSpace(pReply, count * width);
664 if (width == 8) {
665 const uint64_t* src8 = reinterpret_cast<const uint64_t*>(src);
666 for (int i = 0; i < count; ++i) JDWP::Write8BE(&dst, src8[offset + i]);
667 } else if (width == 4) {
668 const uint32_t* src4 = reinterpret_cast<const uint32_t*>(src);
669 for (int i = 0; i < count; ++i) JDWP::Write4BE(&dst, src4[offset + i]);
670 } else if (width == 2) {
671 const uint16_t* src2 = reinterpret_cast<const uint16_t*>(src);
672 for (int i = 0; i < count; ++i) JDWP::Write2BE(&dst, src2[offset + i]);
673 } else {
674 memcpy(dst, &src[offset * width], count * width);
675 }
676 } else {
677 ObjectArray<Object>* oa = a->AsObjectArray<Object>();
678 for (int i = 0; i < count; ++i) {
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800679 Object* element = oa->Get(offset + i);
Elliott Hughes24437992011-11-30 14:49:33 -0800680 JDWP::JdwpTag specific_tag = (element != NULL) ? TagFromObject(element) : tag;
681 expandBufAdd1(pReply, specific_tag);
682 expandBufAddObjectId(pReply, gRegistry->Add(element));
683 }
684 }
685
686 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700687}
688
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800689bool Dbg::SetArrayElements(JDWP::ObjectId arrayId, int offset, int count, const uint8_t* src) {
690 Object* o = gRegistry->Get<Object*>(arrayId);
691 Array* a = o->AsArray();
692
693 if (offset < 0 || count < 0 || offset > a->GetLength() || a->GetLength() - offset < count) {
694 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
695 return false;
696 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800697 std::string descriptor(ClassHelper(a->GetClass()).GetDescriptor());
Elliott Hughesf03b8f62011-12-02 14:26:25 -0800698 JDWP::JdwpTag tag = BasicTagFromDescriptor(descriptor.c_str() + 1);
699
700 if (IsPrimitiveTag(tag)) {
701 size_t width = GetTagWidth(tag);
702 uint8_t* dst = &(reinterpret_cast<uint8_t*>(a->GetRawData())[offset * width]);
703 if (width == 8) {
704 for (int i = 0; i < count; ++i) {
705 // Handle potentially non-aligned memory access one byte at a time for ARM's benefit.
706 uint64_t value;
707 for (size_t j = 0; j < sizeof(uint64_t); ++j) reinterpret_cast<uint8_t*>(&value)[j] = src[j];
708 src += sizeof(uint64_t);
709 JDWP::Write8BE(&dst, value);
710 }
711 } else if (width == 4) {
712 const uint32_t* src4 = reinterpret_cast<const uint32_t*>(src);
713 for (int i = 0; i < count; ++i) JDWP::Write4BE(&dst, src4[i]);
714 } else if (width == 2) {
715 const uint16_t* src2 = reinterpret_cast<const uint16_t*>(src);
716 for (int i = 0; i < count; ++i) JDWP::Write2BE(&dst, src2[i]);
717 } else {
718 memcpy(&dst[offset * width], src, count * width);
719 }
720 } else {
721 ObjectArray<Object>* oa = a->AsObjectArray<Object>();
722 for (int i = 0; i < count; ++i) {
723 JDWP::ObjectId id = JDWP::ReadObjectId(&src);
724 oa->Set(offset + i, gRegistry->Get<Object*>(id));
725 }
726 }
727
728 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700729}
730
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800731JDWP::ObjectId Dbg::CreateString(const std::string& str) {
732 return gRegistry->Add(String::AllocFromModifiedUtf8(str.c_str()));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700733}
734
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800735bool Dbg::CreateObject(JDWP::RefTypeId classId, JDWP::ObjectId& new_object) {
736 Object* o = gRegistry->Get<Object*>(classId);
737 if (o == NULL || !o->IsClass()) {
738 return false;
739 }
740 new_object = gRegistry->Add(o->AsClass()->AllocObject());
741 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700742}
743
Elliott Hughesbf13d362011-12-08 15:51:37 -0800744/*
745 * Used by Eclipse's "Display" view to evaluate "new byte[5]" to get "(byte[]) [0, 0, 0, 0, 0]".
746 */
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800747bool Dbg::CreateArrayObject(JDWP::RefTypeId arrayTypeId, uint32_t length, JDWP::ObjectId& new_array) {
748 Object* o = gRegistry->Get<Object*>(arrayTypeId);
749 if (o == NULL || !o->IsClass()) {
750 return false;
751 }
752 new_array = gRegistry->Add(Array::Alloc(o->AsClass(), length));
753 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700754}
755
756bool Dbg::MatchType(JDWP::RefTypeId instClassId, JDWP::RefTypeId classId) {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800757 // TODO: error handling if the RefTypeIds aren't actually Class*s.
Elliott Hughesd07986f2011-12-06 18:27:45 -0800758 return gRegistry->Get<Class*>(instClassId)->InstanceOf(gRegistry->Get<Class*>(classId));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700759}
760
Elliott Hughes03181a82011-11-17 17:22:21 -0800761JDWP::FieldId ToFieldId(Field* f) {
762#ifdef MOVING_GARBAGE_COLLECTOR
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700763 UNIMPLEMENTED(FATAL);
Elliott Hughes03181a82011-11-17 17:22:21 -0800764#else
765 return static_cast<JDWP::FieldId>(reinterpret_cast<uintptr_t>(f));
766#endif
767}
768
769JDWP::MethodId ToMethodId(Method* m) {
770#ifdef MOVING_GARBAGE_COLLECTOR
771 UNIMPLEMENTED(FATAL);
772#else
773 return static_cast<JDWP::MethodId>(reinterpret_cast<uintptr_t>(m));
774#endif
775}
776
Elliott Hughesaed4be92011-12-02 16:16:23 -0800777Field* FromFieldId(JDWP::FieldId fid) {
778#ifdef MOVING_GARBAGE_COLLECTOR
779 UNIMPLEMENTED(FATAL);
780#else
781 return reinterpret_cast<Field*>(static_cast<uintptr_t>(fid));
782#endif
783}
784
Elliott Hughes03181a82011-11-17 17:22:21 -0800785Method* FromMethodId(JDWP::MethodId mid) {
786#ifdef MOVING_GARBAGE_COLLECTOR
787 UNIMPLEMENTED(FATAL);
788#else
789 return reinterpret_cast<Method*>(static_cast<uintptr_t>(mid));
790#endif
791}
792
Elliott Hughesd07986f2011-12-06 18:27:45 -0800793void SetLocation(JDWP::JdwpLocation& location, Method* m, uintptr_t native_pc) {
794 Class* c = m->GetDeclaringClass();
795 location.typeTag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
796 location.classId = gRegistry->Add(c);
797 location.methodId = ToMethodId(m);
798 location.idx = m->IsNative() ? -1 : m->ToDexPC(native_pc);
799}
800
Elliott Hughes03181a82011-11-17 17:22:21 -0800801std::string Dbg::GetMethodName(JDWP::RefTypeId refTypeId, JDWP::MethodId methodId) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800802 Method* m = FromMethodId(methodId);
803 return MethodHelper(m).GetName();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700804}
805
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800806/*
807 * Augment the access flags for synthetic methods and fields by setting
808 * the (as described by the spec) "0xf0000000 bit". Also, strip out any
809 * flags not specified by the Java programming language.
810 */
811static uint32_t MangleAccessFlags(uint32_t accessFlags) {
812 accessFlags &= kAccJavaFlagsMask;
813 if ((accessFlags & kAccSynthetic) != 0) {
814 accessFlags |= 0xf0000000;
815 }
816 return accessFlags;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700817}
818
Elliott Hughesdbb40792011-11-18 17:05:22 -0800819static const uint16_t kEclipseWorkaroundSlot = 1000;
820
821/*
822 * Eclipse appears to expect that the "this" reference is in slot zero.
823 * If it's not, the "variables" display will show two copies of "this",
824 * possibly because it gets "this" from SF.ThisObject and then displays
825 * all locals with nonzero slot numbers.
826 *
827 * So, we remap the item in slot 0 to 1000, and remap "this" to zero. On
828 * SF.GetValues / SF.SetValues we map them back.
Elliott Hughesc5b734a2011-12-01 17:20:58 -0800829 *
830 * TODO: jdb uses the value to determine whether a variable is a local or an argument,
831 * by checking whether it's less than the number of arguments. To make that work, we'd
832 * have to "mangle" all the arguments to come first, not just the implicit argument 'this'.
Elliott Hughesdbb40792011-11-18 17:05:22 -0800833 */
834static uint16_t MangleSlot(uint16_t slot, const char* name) {
835 uint16_t newSlot = slot;
836 if (strcmp(name, "this") == 0) {
837 newSlot = 0;
838 } else if (slot == 0) {
839 newSlot = kEclipseWorkaroundSlot;
840 }
841 return newSlot;
842}
843
Elliott Hughes68fdbd02011-11-29 19:22:47 -0800844static uint16_t DemangleSlot(uint16_t slot, Frame& f) {
Elliott Hughesdbb40792011-11-18 17:05:22 -0800845 if (slot == kEclipseWorkaroundSlot) {
Elliott Hughes68fdbd02011-11-29 19:22:47 -0800846 return 0;
Elliott Hughesdbb40792011-11-18 17:05:22 -0800847 } else if (slot == 0) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800848 const DexFile::CodeItem* code_item = MethodHelper(f.GetMethod()).GetCodeItem();
849 return code_item->registers_size_ - code_item->ins_size_;
Elliott Hughesdbb40792011-11-18 17:05:22 -0800850 }
Elliott Hughes68fdbd02011-11-29 19:22:47 -0800851 return slot;
Elliott Hughesdbb40792011-11-18 17:05:22 -0800852}
853
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800854bool Dbg::OutputDeclaredFields(JDWP::RefTypeId refTypeId, bool with_generic, JDWP::ExpandBuf* pReply) {
855 Object* o = gRegistry->Get<Object*>(refTypeId);
856 if (o == NULL || !o->IsClass()) {
857 return false;
858 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800859
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800860 Class* c = o->AsClass();
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800861 size_t instance_field_count = c->NumInstanceFields();
862 size_t static_field_count = c->NumStaticFields();
863
864 expandBufAdd4BE(pReply, instance_field_count + static_field_count);
865
866 for (size_t i = 0; i < instance_field_count + static_field_count; ++i) {
867 Field* f = (i < instance_field_count) ? c->GetInstanceField(i) : c->GetStaticField(i - instance_field_count);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800868 FieldHelper fh(f);
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800869 expandBufAddFieldId(pReply, ToFieldId(f));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800870 expandBufAddUtf8String(pReply, fh.GetName());
871 expandBufAddUtf8String(pReply, fh.GetTypeDescriptor());
Elliott Hughesc5b734a2011-12-01 17:20:58 -0800872 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800873 static const char genericSignature[1] = "";
874 expandBufAddUtf8String(pReply, genericSignature);
875 }
876 expandBufAdd4BE(pReply, MangleAccessFlags(f->GetAccessFlags()));
877 }
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800878 return true;
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800879}
880
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800881bool Dbg::OutputDeclaredMethods(JDWP::RefTypeId refTypeId, bool with_generic, JDWP::ExpandBuf* pReply) {
882 Object* o = gRegistry->Get<Object*>(refTypeId);
883 if (o == NULL || !o->IsClass()) {
884 return false;
885 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800886
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800887 Class* c = o->AsClass();
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800888 size_t direct_method_count = c->NumDirectMethods();
889 size_t virtual_method_count = c->NumVirtualMethods();
890
891 expandBufAdd4BE(pReply, direct_method_count + virtual_method_count);
892
893 for (size_t i = 0; i < direct_method_count + virtual_method_count; ++i) {
894 Method* m = (i < direct_method_count) ? c->GetDirectMethod(i) : c->GetVirtualMethod(i - direct_method_count);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800895 MethodHelper mh(m);
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800896 expandBufAddMethodId(pReply, ToMethodId(m));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800897 expandBufAddUtf8String(pReply, mh.GetName());
Elliott Hughes4740cdf2011-12-07 14:07:12 -0800898 expandBufAddUtf8String(pReply, mh.GetSignature());
Elliott Hughesc5b734a2011-12-01 17:20:58 -0800899 if (with_generic) {
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800900 static const char genericSignature[1] = "";
901 expandBufAddUtf8String(pReply, genericSignature);
902 }
903 expandBufAdd4BE(pReply, MangleAccessFlags(m->GetAccessFlags()));
904 }
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800905 return true;
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800906}
907
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800908bool Dbg::OutputDeclaredInterfaces(JDWP::RefTypeId refTypeId, JDWP::ExpandBuf* pReply) {
909 Object* o = gRegistry->Get<Object*>(refTypeId);
910 if (o == NULL || !o->IsClass()) {
911 return false;
912 }
913 ClassHelper kh(o->AsClass());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800914 size_t interface_count = kh.NumInterfaces();
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800915 expandBufAdd4BE(pReply, interface_count);
916 for (size_t i = 0; i < interface_count; ++i) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800917 expandBufAddRefTypeId(pReply, gRegistry->Add(kh.GetInterface(i)));
Elliott Hughesa2e54f62011-11-17 13:01:30 -0800918 }
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800919 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700920}
921
922void Dbg::OutputLineTable(JDWP::RefTypeId refTypeId, JDWP::MethodId methodId, JDWP::ExpandBuf* pReply) {
Elliott Hughes03181a82011-11-17 17:22:21 -0800923 struct DebugCallbackContext {
924 int numItems;
925 JDWP::ExpandBuf* pReply;
926
927 static bool Callback(void* context, uint32_t address, uint32_t lineNum) {
928 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
929 expandBufAdd8BE(pContext->pReply, address);
930 expandBufAdd4BE(pContext->pReply, lineNum);
931 pContext->numItems++;
932 return true;
933 }
934 };
935
936 Method* m = FromMethodId(methodId);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800937 MethodHelper mh(m);
Elliott Hughes03181a82011-11-17 17:22:21 -0800938 uint64_t start, end;
939 if (m->IsNative()) {
940 start = -1;
941 end = -1;
942 } else {
943 start = 0;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800944 // TODO: what are the units supposed to be? *2?
945 end = mh.GetCodeItem()->insns_size_in_code_units_;
Elliott Hughes03181a82011-11-17 17:22:21 -0800946 }
947
948 expandBufAdd8BE(pReply, start);
949 expandBufAdd8BE(pReply, end);
950
951 // Add numLines later
952 size_t numLinesOffset = expandBufGetLength(pReply);
953 expandBufAdd4BE(pReply, 0);
954
955 DebugCallbackContext context;
956 context.numItems = 0;
957 context.pReply = pReply;
958
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800959 mh.GetDexFile().DecodeDebugInfo(mh.GetCodeItem(), m->IsStatic(), m->GetDexMethodIndex(),
960 DebugCallbackContext::Callback, NULL, &context);
Elliott Hughes03181a82011-11-17 17:22:21 -0800961
962 JDWP::Set4BE(expandBufGetBuffer(pReply) + numLinesOffset, context.numItems);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700963}
964
Elliott Hughesc5b734a2011-12-01 17:20:58 -0800965void Dbg::OutputVariableTable(JDWP::RefTypeId refTypeId, JDWP::MethodId methodId, bool with_generic, JDWP::ExpandBuf* pReply) {
Elliott Hughesdbb40792011-11-18 17:05:22 -0800966 struct DebugCallbackContext {
Elliott Hughesdbb40792011-11-18 17:05:22 -0800967 JDWP::ExpandBuf* pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -0800968 size_t variable_count;
969 bool with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -0800970
Elliott Hughesc5b734a2011-12-01 17:20:58 -0800971 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 -0800972 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context);
973
Elliott Hughesc5b734a2011-12-01 17:20:58 -0800974 LOG(VERBOSE) << StringPrintf(" %2d: %d(%d) '%s' '%s' '%s' slot=%d", pContext->variable_count, startAddress, endAddress - startAddress, name, descriptor, signature, slot);
Elliott Hughesdbb40792011-11-18 17:05:22 -0800975
Elliott Hughes68fdbd02011-11-29 19:22:47 -0800976 slot = MangleSlot(slot, name);
977
Elliott Hughesdbb40792011-11-18 17:05:22 -0800978 expandBufAdd8BE(pContext->pReply, startAddress);
979 expandBufAddUtf8String(pContext->pReply, name);
980 expandBufAddUtf8String(pContext->pReply, descriptor);
Elliott Hughesc5b734a2011-12-01 17:20:58 -0800981 if (pContext->with_generic) {
Elliott Hughesdbb40792011-11-18 17:05:22 -0800982 expandBufAddUtf8String(pContext->pReply, signature);
983 }
984 expandBufAdd4BE(pContext->pReply, endAddress - startAddress);
985 expandBufAdd4BE(pContext->pReply, slot);
986
Elliott Hughesc5b734a2011-12-01 17:20:58 -0800987 ++pContext->variable_count;
Elliott Hughesdbb40792011-11-18 17:05:22 -0800988 }
989 };
990
991 Method* m = FromMethodId(methodId);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800992 MethodHelper mh(m);
993 const DexFile::CodeItem* code_item = mh.GetCodeItem();
Elliott Hughesdbb40792011-11-18 17:05:22 -0800994
Elliott Hughesc5b734a2011-12-01 17:20:58 -0800995 // arg_count considers doubles and longs to take 2 units.
996 // variable_count considers everything to take 1 unit.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800997 std::string shorty(mh.GetShorty());
Elliott Hughesc5b734a2011-12-01 17:20:58 -0800998 expandBufAdd4BE(pReply, m->NumArgRegisters(shorty));
Elliott Hughesdbb40792011-11-18 17:05:22 -0800999
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001000 // We don't know the total number of variables yet, so leave a blank and update it later.
1001 size_t variable_count_offset = expandBufGetLength(pReply);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001002 expandBufAdd4BE(pReply, 0);
1003
1004 DebugCallbackContext context;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001005 context.pReply = pReply;
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001006 context.variable_count = 0;
1007 context.with_generic = with_generic;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001008
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001009 mh.GetDexFile().DecodeDebugInfo(code_item, m->IsStatic(), m->GetDexMethodIndex(), NULL,
1010 DebugCallbackContext::Callback, &context);
Elliott Hughesdbb40792011-11-18 17:05:22 -08001011
Elliott Hughesc5b734a2011-12-01 17:20:58 -08001012 JDWP::Set4BE(expandBufGetBuffer(pReply) + variable_count_offset, context.variable_count);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001013}
1014
Elliott Hughesaed4be92011-12-02 16:16:23 -08001015JDWP::JdwpTag Dbg::GetFieldBasicTag(JDWP::FieldId fieldId) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001016 return BasicTagFromDescriptor(FieldHelper(FromFieldId(fieldId)).GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001017}
1018
Elliott Hughesaed4be92011-12-02 16:16:23 -08001019JDWP::JdwpTag Dbg::GetStaticFieldBasicTag(JDWP::FieldId fieldId) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001020 return BasicTagFromDescriptor(FieldHelper(FromFieldId(fieldId)).GetTypeDescriptor());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001021}
1022
1023void Dbg::GetFieldValue(JDWP::ObjectId objectId, JDWP::FieldId fieldId, JDWP::ExpandBuf* pReply) {
Elliott Hughesaed4be92011-12-02 16:16:23 -08001024 Object* o = gRegistry->Get<Object*>(objectId);
1025 Field* f = FromFieldId(fieldId);
1026
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001027 JDWP::JdwpTag tag = BasicTagFromDescriptor(FieldHelper(f).GetTypeDescriptor());
Elliott Hughesaed4be92011-12-02 16:16:23 -08001028
1029 if (IsPrimitiveTag(tag)) {
1030 expandBufAdd1(pReply, tag);
1031 if (tag == JDWP::JT_BOOLEAN || tag == JDWP::JT_BYTE) {
1032 expandBufAdd1(pReply, f->Get32(o));
1033 } else if (tag == JDWP::JT_CHAR || tag == JDWP::JT_SHORT) {
1034 expandBufAdd2BE(pReply, f->Get32(o));
1035 } else if (tag == JDWP::JT_FLOAT || tag == JDWP::JT_INT) {
1036 expandBufAdd4BE(pReply, f->Get32(o));
1037 } else if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
1038 expandBufAdd8BE(pReply, f->Get64(o));
1039 } else {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001040 LOG(FATAL) << "Unknown tag: " << tag;
Elliott Hughesaed4be92011-12-02 16:16:23 -08001041 }
1042 } else {
1043 Object* value = f->GetObject(o);
1044 expandBufAdd1(pReply, TagFromObject(value));
1045 expandBufAddObjectId(pReply, gRegistry->Add(value));
1046 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001047}
1048
1049void Dbg::SetFieldValue(JDWP::ObjectId objectId, JDWP::FieldId fieldId, uint64_t value, int width) {
Elliott Hughesaed4be92011-12-02 16:16:23 -08001050 Object* o = gRegistry->Get<Object*>(objectId);
1051 Field* f = FromFieldId(fieldId);
1052
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001053 JDWP::JdwpTag tag = BasicTagFromDescriptor(FieldHelper(f).GetTypeDescriptor());
Elliott Hughesaed4be92011-12-02 16:16:23 -08001054
1055 if (IsPrimitiveTag(tag)) {
1056 if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) {
1057 f->Set64(o, value);
1058 } else {
1059 f->Set32(o, value);
1060 }
1061 } else {
1062 f->SetObject(o, gRegistry->Get<Object*>(value));
1063 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001064}
1065
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001066void Dbg::GetStaticFieldValue(JDWP::FieldId fieldId, JDWP::ExpandBuf* pReply) {
1067 GetFieldValue(0, fieldId, pReply);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001068}
1069
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001070void Dbg::SetStaticFieldValue(JDWP::FieldId fieldId, uint64_t value, int width) {
1071 SetFieldValue(0, fieldId, value, width);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001072}
1073
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001074std::string Dbg::StringToUtf8(JDWP::ObjectId strId) {
1075 String* s = gRegistry->Get<String*>(strId);
1076 return s->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001077}
1078
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001079Thread* DecodeThread(JDWP::ObjectId threadId) {
1080 Object* thread_peer = gRegistry->Get<Object*>(threadId);
1081 CHECK(thread_peer != NULL);
1082 return Thread::FromManagedThread(thread_peer);
1083}
1084
1085bool Dbg::GetThreadName(JDWP::ObjectId threadId, std::string& name) {
1086 ScopedThreadListLock thread_list_lock;
1087 Thread* thread = DecodeThread(threadId);
1088 if (thread == NULL) {
1089 return false;
1090 }
1091 StringAppendF(&name, "<%d> %s", thread->GetThinLockId(), thread->GetName()->ToModifiedUtf8().c_str());
1092 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001093}
1094
1095JDWP::ObjectId Dbg::GetThreadGroup(JDWP::ObjectId threadId) {
Elliott Hughes499c5132011-11-17 14:55:11 -08001096 Object* thread = gRegistry->Get<Object*>(threadId);
1097 CHECK(thread != NULL);
1098
1099 Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/Thread;");
1100 CHECK(c != NULL);
1101 Field* f = c->FindInstanceField("group", "Ljava/lang/ThreadGroup;");
1102 CHECK(f != NULL);
1103 Object* group = f->GetObject(thread);
1104 CHECK(group != NULL);
1105 return gRegistry->Add(group);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001106}
1107
Elliott Hughes499c5132011-11-17 14:55:11 -08001108std::string Dbg::GetThreadGroupName(JDWP::ObjectId threadGroupId) {
1109 Object* thread_group = gRegistry->Get<Object*>(threadGroupId);
1110 CHECK(thread_group != NULL);
1111
1112 Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/ThreadGroup;");
1113 CHECK(c != NULL);
1114 Field* f = c->FindInstanceField("name", "Ljava/lang/String;");
1115 CHECK(f != NULL);
1116 String* s = reinterpret_cast<String*>(f->GetObject(thread_group));
1117 return s->ToModifiedUtf8();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001118}
1119
1120JDWP::ObjectId Dbg::GetThreadGroupParent(JDWP::ObjectId threadGroupId) {
Elliott Hughes4e235312011-12-02 11:34:15 -08001121 Object* thread_group = gRegistry->Get<Object*>(threadGroupId);
1122 CHECK(thread_group != NULL);
1123
1124 Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/ThreadGroup;");
1125 CHECK(c != NULL);
1126 Field* f = c->FindInstanceField("parent", "Ljava/lang/ThreadGroup;");
1127 CHECK(f != NULL);
1128 Object* parent = f->GetObject(thread_group);
1129 return gRegistry->Add(parent);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001130}
1131
Elliott Hughes499c5132011-11-17 14:55:11 -08001132static Object* GetStaticThreadGroup(const char* field_name) {
1133 Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/ThreadGroup;");
1134 CHECK(c != NULL);
1135 Field* f = c->FindStaticField(field_name, "Ljava/lang/ThreadGroup;");
1136 CHECK(f != NULL);
1137 Object* group = f->GetObject(NULL);
1138 CHECK(group != NULL);
1139 return group;
1140}
1141
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001142JDWP::ObjectId Dbg::GetSystemThreadGroupId() {
Elliott Hughes499c5132011-11-17 14:55:11 -08001143 return gRegistry->Add(GetStaticThreadGroup("mSystem"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001144}
1145
1146JDWP::ObjectId Dbg::GetMainThreadGroupId() {
Elliott Hughes499c5132011-11-17 14:55:11 -08001147 return gRegistry->Add(GetStaticThreadGroup("mMain"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001148}
1149
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001150bool Dbg::GetThreadStatus(JDWP::ObjectId threadId, JDWP::JdwpThreadStatus* pThreadStatus, JDWP::JdwpSuspendStatus* pSuspendStatus) {
Elliott Hughes499c5132011-11-17 14:55:11 -08001151 ScopedThreadListLock thread_list_lock;
1152
1153 Thread* thread = DecodeThread(threadId);
1154 if (thread == NULL) {
1155 return false;
1156 }
1157
1158 switch (thread->GetState()) {
1159 case Thread::kTerminated: *pThreadStatus = JDWP::TS_ZOMBIE; break;
1160 case Thread::kRunnable: *pThreadStatus = JDWP::TS_RUNNING; break;
1161 case Thread::kTimedWaiting: *pThreadStatus = JDWP::TS_SLEEPING; break;
1162 case Thread::kBlocked: *pThreadStatus = JDWP::TS_MONITOR; break;
1163 case Thread::kWaiting: *pThreadStatus = JDWP::TS_WAIT; break;
1164 case Thread::kInitializing: *pThreadStatus = JDWP::TS_ZOMBIE; break;
1165 case Thread::kStarting: *pThreadStatus = JDWP::TS_ZOMBIE; break;
1166 case Thread::kNative: *pThreadStatus = JDWP::TS_RUNNING; break;
1167 case Thread::kVmWait: *pThreadStatus = JDWP::TS_WAIT; break;
1168 case Thread::kSuspended: *pThreadStatus = JDWP::TS_RUNNING; break;
1169 default:
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001170 LOG(FATAL) << "Unknown thread state " << thread->GetState();
Elliott Hughes499c5132011-11-17 14:55:11 -08001171 }
1172
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001173 *pSuspendStatus = (thread->IsSuspended() ? JDWP::SUSPEND_STATUS_SUSPENDED : JDWP::SUSPEND_STATUS_NOT_SUSPENDED);
Elliott Hughes499c5132011-11-17 14:55:11 -08001174
1175 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001176}
1177
1178uint32_t Dbg::GetThreadSuspendCount(JDWP::ObjectId threadId) {
Elliott Hughesd07986f2011-12-06 18:27:45 -08001179 return DecodeThread(threadId)->GetSuspendCount();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001180}
1181
1182bool Dbg::ThreadExists(JDWP::ObjectId threadId) {
Elliott Hughes761928d2011-11-16 18:33:03 -08001183 return DecodeThread(threadId) != NULL;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001184}
1185
1186bool Dbg::IsSuspended(JDWP::ObjectId threadId) {
Elliott Hughes761928d2011-11-16 18:33:03 -08001187 return DecodeThread(threadId)->IsSuspended();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001188}
1189
Elliott Hughesa2155262011-11-16 16:26:58 -08001190void Dbg::GetThreadGroupThreadsImpl(Object* thread_group, JDWP::ObjectId** ppThreadIds, uint32_t* pThreadCount) {
1191 struct ThreadListVisitor {
1192 static void Visit(Thread* t, void* arg) {
1193 reinterpret_cast<ThreadListVisitor*>(arg)->Visit(t);
1194 }
1195
1196 void Visit(Thread* t) {
1197 if (t == Dbg::GetDebugThread()) {
1198 // Skip the JDWP thread. Some debuggers get bent out of shape when they can't suspend and
1199 // query all threads, so it's easier if we just don't tell them about this thread.
1200 return;
1201 }
1202 if (thread_group == NULL || t->GetThreadGroup() == thread_group) {
1203 threads.push_back(gRegistry->Add(t->GetPeer()));
1204 }
1205 }
1206
1207 Object* thread_group;
1208 std::vector<JDWP::ObjectId> threads;
1209 };
1210
1211 ThreadListVisitor tlv;
1212 tlv.thread_group = thread_group;
1213
1214 {
1215 ScopedThreadListLock thread_list_lock;
1216 Runtime::Current()->GetThreadList()->ForEach(ThreadListVisitor::Visit, &tlv);
1217 }
1218
1219 *pThreadCount = tlv.threads.size();
1220 if (*pThreadCount == 0) {
1221 *ppThreadIds = NULL;
1222 } else {
1223 *ppThreadIds = new JDWP::ObjectId[*pThreadCount];
1224 for (size_t i = 0; i < *pThreadCount; ++i) {
1225 (*ppThreadIds)[i] = tlv.threads[i];
1226 }
1227 }
1228}
1229
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001230void Dbg::GetThreadGroupThreads(JDWP::ObjectId threadGroupId, JDWP::ObjectId** ppThreadIds, uint32_t* pThreadCount) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001231 GetThreadGroupThreadsImpl(gRegistry->Get<Object*>(threadGroupId), ppThreadIds, pThreadCount);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001232}
1233
1234void Dbg::GetAllThreads(JDWP::ObjectId** ppThreadIds, uint32_t* pThreadCount) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001235 GetThreadGroupThreadsImpl(NULL, ppThreadIds, pThreadCount);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001236}
1237
1238int Dbg::GetThreadFrameCount(JDWP::ObjectId threadId) {
Elliott Hughes03181a82011-11-17 17:22:21 -08001239 ScopedThreadListLock thread_list_lock;
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001240 struct CountStackDepthVisitor : public Thread::StackVisitor {
1241 CountStackDepthVisitor() : depth(0) {}
Elliott Hughesf8a2df72011-12-01 12:19:54 -08001242 virtual void VisitFrame(const Frame& f, uintptr_t) {
1243 // TODO: we'll need to skip callee-save frames too.
1244 if (f.HasMethod()) {
1245 ++depth;
1246 }
Elliott Hughesa2e54f62011-11-17 13:01:30 -08001247 }
1248 size_t depth;
1249 };
1250 CountStackDepthVisitor visitor;
1251 DecodeThread(threadId)->WalkStack(&visitor);
1252 return visitor.depth;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001253}
1254
Elliott Hughes03181a82011-11-17 17:22:21 -08001255bool Dbg::GetThreadFrame(JDWP::ObjectId threadId, int desired_frame_number, JDWP::FrameId* pFrameId, JDWP::JdwpLocation* pLoc) {
1256 ScopedThreadListLock thread_list_lock;
1257 struct GetFrameVisitor : public Thread::StackVisitor {
1258 GetFrameVisitor(int desired_frame_number, JDWP::FrameId* pFrameId, JDWP::JdwpLocation* pLoc)
1259 : found(false) ,depth(0), desired_frame_number(desired_frame_number), pFrameId(pFrameId), pLoc(pLoc) {
1260 }
1261 virtual void VisitFrame(const Frame& f, uintptr_t pc) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -08001262 // TODO: we'll need to skip callee-save frames too.
Elliott Hughes03181a82011-11-17 17:22:21 -08001263 if (!f.HasMethod()) {
Elliott Hughesf8a2df72011-12-01 12:19:54 -08001264 return; // The debugger can't do anything useful with a frame that has no Method*.
Elliott Hughes03181a82011-11-17 17:22:21 -08001265 }
1266
1267 if (depth == desired_frame_number) {
1268 *pFrameId = reinterpret_cast<JDWP::FrameId>(f.GetSP());
Elliott Hughesd07986f2011-12-06 18:27:45 -08001269 SetLocation(*pLoc, f.GetMethod(), pc);
Elliott Hughes03181a82011-11-17 17:22:21 -08001270 found = true;
1271 }
1272 ++depth;
1273 }
1274 bool found;
1275 int depth;
1276 int desired_frame_number;
1277 JDWP::FrameId* pFrameId;
1278 JDWP::JdwpLocation* pLoc;
1279 };
1280 GetFrameVisitor visitor(desired_frame_number, pFrameId, pLoc);
1281 visitor.desired_frame_number = desired_frame_number;
1282 DecodeThread(threadId)->WalkStack(&visitor);
1283 return visitor.found;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001284}
1285
1286JDWP::ObjectId Dbg::GetThreadSelfId() {
Elliott Hughes475fc232011-10-25 15:00:35 -07001287 return gRegistry->Add(Thread::Current()->GetPeer());
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001288}
1289
Elliott Hughes475fc232011-10-25 15:00:35 -07001290void Dbg::SuspendVM() {
Elliott Hughesa2155262011-11-16 16:26:58 -08001291 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 -07001292 Runtime::Current()->GetThreadList()->SuspendAll(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001293}
1294
1295void Dbg::ResumeVM() {
Elliott Hughes475fc232011-10-25 15:00:35 -07001296 Runtime::Current()->GetThreadList()->ResumeAll(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001297}
1298
1299void Dbg::SuspendThread(JDWP::ObjectId threadId) {
Elliott Hughes4e235312011-12-02 11:34:15 -08001300 Object* peer = gRegistry->Get<Object*>(threadId);
1301 ScopedThreadListLock thread_list_lock;
1302 Thread* thread = Thread::FromManagedThread(peer);
1303 if (thread == NULL) {
1304 LOG(WARNING) << "No such thread for suspend: " << peer;
1305 return;
1306 }
1307 Runtime::Current()->GetThreadList()->Suspend(thread, true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001308}
1309
1310void Dbg::ResumeThread(JDWP::ObjectId threadId) {
Elliott Hughes4e235312011-12-02 11:34:15 -08001311 Object* peer = gRegistry->Get<Object*>(threadId);
1312 ScopedThreadListLock thread_list_lock;
1313 Thread* thread = Thread::FromManagedThread(peer);
1314 if (thread == NULL) {
1315 LOG(WARNING) << "No such thread for resume: " << peer;
1316 return;
1317 }
1318 Runtime::Current()->GetThreadList()->Resume(thread, true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001319}
1320
1321void Dbg::SuspendSelf() {
Elliott Hughes475fc232011-10-25 15:00:35 -07001322 Runtime::Current()->GetThreadList()->SuspendSelfForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001323}
1324
Elliott Hughesd07986f2011-12-06 18:27:45 -08001325bool Dbg::GetThisObject(JDWP::FrameId frameId, JDWP::ObjectId* pThisId) {
Elliott Hughes86b00102011-12-05 17:54:26 -08001326 Method** sp = reinterpret_cast<Method**>(frameId);
1327 Frame f;
1328 f.SetSP(sp);
Elliott Hughes86b00102011-12-05 17:54:26 -08001329 Method* m = f.GetMethod();
1330
1331 Object* o = NULL;
1332 if (!m->IsNative() && !m->IsStatic()) {
Elliott Hughesd07986f2011-12-06 18:27:45 -08001333 uint16_t reg = DemangleSlot(0, f);
Elliott Hughes86b00102011-12-05 17:54:26 -08001334 o = reinterpret_cast<Object*>(f.GetVReg(m, reg));
1335 }
1336 *pThisId = gRegistry->Add(o);
1337 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001338}
1339
Elliott Hughescccd84f2011-12-05 16:51:54 -08001340void 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 -08001341 Method** sp = reinterpret_cast<Method**>(frameId);
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001342 Frame f;
1343 f.SetSP(sp);
1344 uint16_t reg = DemangleSlot(slot, f);
1345 Method* m = f.GetMethod();
1346
1347 const VmapTable vmap_table(m->GetVmapTableRaw());
1348 uint32_t vmap_offset;
1349 if (vmap_table.IsInContext(reg, vmap_offset)) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001350 UNIMPLEMENTED(FATAL) << "Don't know how to pull locals from callee save frames: " << vmap_offset;
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001351 }
Elliott Hughesdbb40792011-11-18 17:05:22 -08001352
1353 switch (tag) {
1354 case JDWP::JT_BOOLEAN:
1355 {
Elliott Hughescccd84f2011-12-05 16:51:54 -08001356 CHECK_EQ(width, 1U);
Elliott Hughes1bba14f2011-12-01 18:00:36 -08001357 uint32_t intVal = f.GetVReg(m, reg);
1358 LOG(VERBOSE) << "get boolean local " << reg << " = " << intVal;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001359 JDWP::Set1(buf+1, intVal != 0);
1360 }
1361 break;
1362 case JDWP::JT_BYTE:
1363 {
Elliott Hughescccd84f2011-12-05 16:51:54 -08001364 CHECK_EQ(width, 1U);
Elliott Hughes1bba14f2011-12-01 18:00:36 -08001365 uint32_t intVal = f.GetVReg(m, reg);
1366 LOG(VERBOSE) << "get byte local " << reg << " = " << intVal;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001367 JDWP::Set1(buf+1, intVal);
1368 }
1369 break;
1370 case JDWP::JT_SHORT:
1371 case JDWP::JT_CHAR:
1372 {
Elliott Hughescccd84f2011-12-05 16:51:54 -08001373 CHECK_EQ(width, 2U);
Elliott Hughes1bba14f2011-12-01 18:00:36 -08001374 uint32_t intVal = f.GetVReg(m, reg);
1375 LOG(VERBOSE) << "get short/char local " << reg << " = " << intVal;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001376 JDWP::Set2BE(buf+1, intVal);
1377 }
1378 break;
1379 case JDWP::JT_INT:
1380 case JDWP::JT_FLOAT:
1381 {
Elliott Hughescccd84f2011-12-05 16:51:54 -08001382 CHECK_EQ(width, 4U);
Elliott Hughes1bba14f2011-12-01 18:00:36 -08001383 uint32_t intVal = f.GetVReg(m, reg);
1384 LOG(VERBOSE) << "get int/float local " << reg << " = " << intVal;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001385 JDWP::Set4BE(buf+1, intVal);
1386 }
1387 break;
1388 case JDWP::JT_ARRAY:
1389 {
Elliott Hughescccd84f2011-12-05 16:51:54 -08001390 CHECK_EQ(width, sizeof(JDWP::ObjectId));
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001391 Object* o = reinterpret_cast<Object*>(f.GetVReg(m, reg));
Elliott Hughes1bba14f2011-12-01 18:00:36 -08001392 LOG(VERBOSE) << "get array local " << reg << " = " << o;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001393 if (o != NULL && !Heap::IsHeapAddress(o)) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001394 LOG(FATAL) << "Register " << reg << " expected to hold array: " << o;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001395 }
1396 JDWP::SetObjectId(buf+1, gRegistry->Add(o));
1397 }
1398 break;
1399 case JDWP::JT_OBJECT:
1400 {
Elliott Hughescccd84f2011-12-05 16:51:54 -08001401 CHECK_EQ(width, sizeof(JDWP::ObjectId));
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001402 Object* o = reinterpret_cast<Object*>(f.GetVReg(m, reg));
Elliott Hughes1bba14f2011-12-01 18:00:36 -08001403 LOG(VERBOSE) << "get object local " << reg << " = " << o;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001404 if (o != NULL && !Heap::IsHeapAddress(o)) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001405 LOG(FATAL) << "Register " << reg << " expected to hold object: " << o;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001406 }
1407 tag = TagFromObject(o);
1408 JDWP::SetObjectId(buf+1, gRegistry->Add(o));
1409 }
1410 break;
1411 case JDWP::JT_DOUBLE:
1412 case JDWP::JT_LONG:
1413 {
Elliott Hughescccd84f2011-12-05 16:51:54 -08001414 CHECK_EQ(width, 8U);
Elliott Hughes1bba14f2011-12-01 18:00:36 -08001415 uint32_t lo = f.GetVReg(m, reg);
1416 uint64_t hi = f.GetVReg(m, reg + 1);
1417 uint64_t longVal = (hi << 32) | lo;
1418 LOG(VERBOSE) << "get double/long local " << hi << ":" << lo << " = " << longVal;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001419 JDWP::Set8BE(buf+1, longVal);
1420 }
1421 break;
1422 default:
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001423 LOG(FATAL) << "Unknown tag " << tag;
Elliott Hughesdbb40792011-11-18 17:05:22 -08001424 break;
1425 }
1426
1427 // Prepend tag, which may have been updated.
1428 JDWP::Set1(buf, tag);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001429}
1430
Elliott Hughesdbb40792011-11-18 17:05:22 -08001431void 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 -08001432 Method** sp = reinterpret_cast<Method**>(frameId);
1433 Frame f;
1434 f.SetSP(sp);
1435 uint16_t reg = DemangleSlot(slot, f);
1436 Method* m = f.GetMethod();
1437
1438 const VmapTable vmap_table(m->GetVmapTableRaw());
1439 uint32_t vmap_offset;
1440 if (vmap_table.IsInContext(reg, vmap_offset)) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001441 UNIMPLEMENTED(FATAL) << "Don't know how to pull locals from callee save frames: " << vmap_offset;
Elliott Hughescccd84f2011-12-05 16:51:54 -08001442 }
1443
1444 switch (tag) {
1445 case JDWP::JT_BOOLEAN:
1446 case JDWP::JT_BYTE:
1447 CHECK_EQ(width, 1U);
1448 f.SetVReg(m, reg, static_cast<uint32_t>(value));
1449 break;
1450 case JDWP::JT_SHORT:
1451 case JDWP::JT_CHAR:
1452 CHECK_EQ(width, 2U);
1453 f.SetVReg(m, reg, static_cast<uint32_t>(value));
1454 break;
1455 case JDWP::JT_INT:
1456 case JDWP::JT_FLOAT:
1457 CHECK_EQ(width, 4U);
1458 f.SetVReg(m, reg, static_cast<uint32_t>(value));
1459 break;
1460 case JDWP::JT_ARRAY:
1461 case JDWP::JT_OBJECT:
1462 case JDWP::JT_STRING:
1463 {
1464 CHECK_EQ(width, sizeof(JDWP::ObjectId));
1465 Object* o = gRegistry->Get<Object*>(static_cast<JDWP::ObjectId>(value));
1466 f.SetVReg(m, reg, static_cast<uint32_t>(reinterpret_cast<uintptr_t>(o)));
1467 }
1468 break;
1469 case JDWP::JT_DOUBLE:
1470 case JDWP::JT_LONG:
1471 CHECK_EQ(width, 8U);
1472 f.SetVReg(m, reg, static_cast<uint32_t>(value));
1473 f.SetVReg(m, reg + 1, static_cast<uint32_t>(value >> 32));
1474 break;
1475 default:
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001476 LOG(FATAL) << "Unknown tag " << tag;
Elliott Hughescccd84f2011-12-05 16:51:54 -08001477 break;
1478 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001479}
1480
1481void Dbg::PostLocationEvent(const Method* method, int pcOffset, Object* thisPtr, int eventFlags) {
1482 UNIMPLEMENTED(FATAL);
1483}
1484
Elliott Hughesd07986f2011-12-06 18:27:45 -08001485void Dbg::PostException(Method** sp, Method* throwMethod, uintptr_t throwNativePc, Method* catchMethod, uintptr_t catchNativePc, Object* exception) {
Ian Rogers0ad5bb82011-12-07 10:16:32 -08001486 if (!gDebuggerActive) {
1487 return;
1488 }
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001489
Elliott Hughesd07986f2011-12-06 18:27:45 -08001490 JDWP::JdwpLocation throw_location;
1491 SetLocation(throw_location, throwMethod, throwNativePc);
1492 JDWP::JdwpLocation catch_location;
1493 SetLocation(catch_location, catchMethod, catchNativePc);
1494
1495 // We need 'this' for InstanceOnly filters.
1496 JDWP::ObjectId this_id;
1497 GetThisObject(reinterpret_cast<JDWP::FrameId>(sp), &this_id);
1498
1499 /*
1500 * Hand the event to the JDWP exception handler. Note we're using the
1501 * "NoReg" objectID on the exception, which is not strictly correct --
1502 * the exception object WILL be passed up to the debugger if the
1503 * debugger is interested in the event. We do this because the current
1504 * implementation of the debugger object registry never throws anything
1505 * away, and some people were experiencing a fatal build up of exception
1506 * objects when dealing with certain libraries.
1507 */
1508 JDWP::ObjectId exception_id = static_cast<JDWP::ObjectId>(reinterpret_cast<uintptr_t>(exception));
1509 JDWP::RefTypeId exception_class_id = gRegistry->Add(exception->GetClass());
1510
1511 gJdwpState->PostException(&throw_location, exception_id, exception_class_id, &catch_location, this_id);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001512}
1513
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001514void Dbg::PostClassPrepare(Class* c) {
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001515 if (!gDebuggerActive) {
1516 return;
1517 }
1518
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001519 // OLD-TODO - we currently always send both "verified" and "prepared" since
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001520 // debuggers seem to like that. There might be some advantage to honesty,
1521 // since the class may not yet be verified.
1522 int state = JDWP::CS_VERIFIED | JDWP::CS_PREPARED;
1523 JDWP::JdwpTypeTag tag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
1524 gJdwpState->PostClassPrepare(tag, gRegistry->Add(c), ClassHelper(c).GetDescriptor(), state);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001525}
1526
1527bool Dbg::WatchLocation(const JDWP::JdwpLocation* pLoc) {
1528 UNIMPLEMENTED(FATAL);
1529 return false;
1530}
1531
1532void Dbg::UnwatchLocation(const JDWP::JdwpLocation* pLoc) {
1533 UNIMPLEMENTED(FATAL);
1534}
1535
1536bool Dbg::ConfigureStep(JDWP::ObjectId threadId, JDWP::JdwpStepSize size, JDWP::JdwpStepDepth depth) {
1537 UNIMPLEMENTED(FATAL);
1538 return false;
1539}
1540
1541void Dbg::UnconfigureStep(JDWP::ObjectId threadId) {
1542 UNIMPLEMENTED(FATAL);
1543}
1544
Elliott Hughesd07986f2011-12-06 18:27:45 -08001545JDWP::JdwpError Dbg::InvokeMethod(JDWP::ObjectId threadId, JDWP::ObjectId objectId, JDWP::RefTypeId classId, JDWP::MethodId methodId, uint32_t numArgs, uint64_t* argArray, uint32_t options, JDWP::JdwpTag* pResultTag, uint64_t* pResultValue, JDWP::ObjectId* pExceptionId) {
1546 ThreadList* thread_list = Runtime::Current()->GetThreadList();
1547
1548 Thread* targetThread = NULL;
1549 DebugInvokeReq* req = NULL;
1550 {
1551 ScopedThreadListLock thread_list_lock;
1552 targetThread = DecodeThread(threadId);
1553 if (targetThread == NULL) {
1554 LOG(ERROR) << "InvokeMethod request for non-existent thread " << threadId;
1555 return JDWP::ERR_INVALID_THREAD;
1556 }
1557 req = targetThread->GetInvokeReq();
1558 if (!req->ready) {
1559 LOG(ERROR) << "InvokeMethod request for thread not stopped by event: " << *targetThread;
1560 return JDWP::ERR_INVALID_THREAD;
1561 }
1562
1563 /*
1564 * We currently have a bug where we don't successfully resume the
1565 * target thread if the suspend count is too deep. We're expected to
1566 * require one "resume" for each "suspend", but when asked to execute
1567 * a method we have to resume fully and then re-suspend it back to the
1568 * same level. (The easiest way to cause this is to type "suspend"
1569 * multiple times in jdb.)
1570 *
1571 * It's unclear what this means when the event specifies "resume all"
1572 * and some threads are suspended more deeply than others. This is
1573 * a rare problem, so for now we just prevent it from hanging forever
1574 * by rejecting the method invocation request. Without this, we will
1575 * be stuck waiting on a suspended thread.
1576 */
1577 int suspend_count = targetThread->GetSuspendCount();
1578 if (suspend_count > 1) {
1579 LOG(ERROR) << *targetThread << " suspend count too deep for method invocation: " << suspend_count;
1580 return JDWP::ERR_THREAD_SUSPENDED; // Probably not expected here.
1581 }
1582
1583 /*
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001584 * OLD-TODO: ought to screen the various IDs, and verify that the argument
Elliott Hughesd07986f2011-12-06 18:27:45 -08001585 * list is valid.
1586 */
1587 req->receiver_ = gRegistry->Get<Object*>(objectId);
1588 req->thread_ = gRegistry->Get<Object*>(threadId);
1589 req->class_ = gRegistry->Get<Class*>(classId);
1590 req->method_ = FromMethodId(methodId);
1591 req->num_args_ = numArgs;
1592 req->arg_array_ = argArray;
1593 req->options_ = options;
1594 req->invoke_needed_ = true;
1595 }
1596
1597 // The fact that we've released the thread list lock is a bit risky --- if the thread goes
1598 // away we're sitting high and dry -- but we must release this before the ResumeAllThreads
1599 // call, and it's unwise to hold it during WaitForSuspend.
1600
1601 {
1602 /*
1603 * We change our (JDWP thread) status, which should be THREAD_RUNNING,
1604 * so the VM can suspend for a GC if the invoke request causes us to
1605 * run out of memory. It's also a good idea to change it before locking
1606 * the invokeReq mutex, although that should never be held for long.
1607 */
1608 ScopedThreadStateChange tsc(Thread::Current(), Thread::kVmWait);
1609
1610 LOG(VERBOSE) << " Transferring control to event thread";
1611 {
1612 MutexLock mu(req->lock_);
1613
1614 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
1615 LOG(VERBOSE) << " Resuming all threads";
1616 thread_list->ResumeAll(true);
1617 } else {
1618 LOG(VERBOSE) << " Resuming event thread only";
1619 thread_list->Resume(targetThread, true);
1620 }
1621
1622 // Wait for the request to finish executing.
1623 while (req->invoke_needed_) {
1624 req->cond_.Wait(req->lock_);
1625 }
1626 }
1627 LOG(VERBOSE) << " Control has returned from event thread";
1628
1629 /* wait for thread to re-suspend itself */
1630 targetThread->WaitUntilSuspended();
1631 //dvmWaitForSuspend(targetThread);
1632 }
1633
1634 /*
1635 * Suspend the threads. We waited for the target thread to suspend
1636 * itself, so all we need to do is suspend the others.
1637 *
1638 * The suspendAllThreads() call will double-suspend the event thread,
1639 * so we want to resume the target thread once to keep the books straight.
1640 */
1641 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) {
1642 LOG(VERBOSE) << " Suspending all threads";
1643 thread_list->SuspendAll(true);
1644 LOG(VERBOSE) << " Resuming event thread to balance the count";
1645 thread_list->Resume(targetThread, true);
1646 }
1647
1648 // Copy the result.
1649 *pResultTag = req->result_tag;
1650 if (IsPrimitiveTag(req->result_tag)) {
1651 *pResultValue = req->result_value.j;
1652 } else {
1653 *pResultValue = gRegistry->Add(req->result_value.l);
1654 }
1655 *pExceptionId = req->exception;
1656 return req->error;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001657}
1658
1659void Dbg::ExecuteMethod(DebugInvokeReq* pReq) {
Elliott Hughesd07986f2011-12-06 18:27:45 -08001660 Thread* self = Thread::Current();
1661
1662 // We can be called while an exception is pending in the VM. We need
1663 // to preserve that across the method invocation.
1664 SirtRef<Throwable> old_exception(self->GetException());
1665 self->ClearException();
1666
1667 ScopedThreadStateChange tsc(self, Thread::kRunnable);
1668
1669 // Translate the method through the vtable, unless the debugger wants to suppress it.
1670 Method* m = pReq->method_;
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001671 LOG(VERBOSE) << "ExecuteMethod " << PrettyMethod(m);
Elliott Hughesd07986f2011-12-06 18:27:45 -08001672 if ((pReq->options_ & JDWP::INVOKE_NONVIRTUAL) == 0 && pReq->receiver_ != NULL) {
1673 m = pReq->class_->FindVirtualMethodForVirtualOrInterface(pReq->method_);
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -08001674 LOG(VERBOSE) << "ExecuteMethod " << PrettyMethod(m);
Elliott Hughesd07986f2011-12-06 18:27:45 -08001675 }
1676 CHECK(m != NULL);
1677
1678 CHECK_EQ(sizeof(jvalue), sizeof(uint64_t));
1679
1680 pReq->result_value = InvokeWithJValues(self, pReq->receiver_, m, reinterpret_cast<JValue*>(pReq->arg_array_));
1681
1682 pReq->exception = gRegistry->Add(self->GetException());
1683 pReq->result_tag = BasicTagFromDescriptor(MethodHelper(m).GetShorty());
1684 if (pReq->exception != 0) {
1685 Object* exc = self->GetException();
1686 LOG(VERBOSE) << " JDWP invocation returning with exception=" << exc << " " << PrettyTypeOf(exc);
1687 self->ClearException();
1688 pReq->result_value.j = 0;
1689 } else if (pReq->result_tag == JDWP::JT_OBJECT) {
1690 /* if no exception thrown, examine object result more closely */
1691 JDWP::JdwpTag new_tag = TagFromObject(pReq->result_value.l);
1692 if (new_tag != pReq->result_tag) {
1693 LOG(VERBOSE) << " JDWP promoted result from " << pReq->result_tag << " to " << new_tag;
1694 pReq->result_tag = new_tag;
1695 }
1696
1697 /*
1698 * Register the object. We don't actually need an ObjectId yet,
1699 * but we do need to be sure that the GC won't move or discard the
1700 * object when we switch out of RUNNING. The ObjectId conversion
1701 * will add the object to the "do not touch" list.
1702 *
1703 * We can't use the "tracked allocation" mechanism here because
1704 * the object is going to be handed off to a different thread.
1705 */
1706 gRegistry->Add(pReq->result_value.l);
1707 }
1708
1709 if (old_exception.get() != NULL) {
1710 self->SetException(old_exception.get());
1711 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001712}
1713
Elliott Hughesd07986f2011-12-06 18:27:45 -08001714/*
1715 * Register an object ID that might not have been registered previously.
1716 *
1717 * Normally this wouldn't happen -- the conversion to an ObjectId would
1718 * have added the object to the registry -- but in some cases (e.g.
1719 * throwing exceptions) we really want to do the registration late.
1720 */
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001721void Dbg::RegisterObjectId(JDWP::ObjectId id) {
Elliott Hughesd07986f2011-12-06 18:27:45 -08001722 gRegistry->Add(reinterpret_cast<Object*>(id));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001723}
1724
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001725/*
1726 * "buf" contains a full JDWP packet, possibly with multiple chunks. We
1727 * need to process each, accumulate the replies, and ship the whole thing
1728 * back.
1729 *
1730 * Returns "true" if we have a reply. The reply buffer is newly allocated,
1731 * and includes the chunk type/length, followed by the data.
1732 *
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08001733 * OLD-TODO: we currently assume that the request and reply include a single
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001734 * chunk. If this becomes inconvenient we will need to adapt.
1735 */
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001736bool Dbg::DdmHandlePacket(const uint8_t* buf, int dataLen, uint8_t** pReplyBuf, int* pReplyLen) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001737 CHECK_GE(dataLen, 0);
1738
1739 Thread* self = Thread::Current();
1740 JNIEnv* env = self->GetJniEnv();
1741
1742 static jclass Chunk_class = env->FindClass("org/apache/harmony/dalvik/ddmc/Chunk");
1743 static jclass DdmServer_class = env->FindClass("org/apache/harmony/dalvik/ddmc/DdmServer");
1744 static jmethodID dispatch_mid = env->GetStaticMethodID(DdmServer_class, "dispatch",
1745 "(I[BII)Lorg/apache/harmony/dalvik/ddmc/Chunk;");
1746 static jfieldID data_fid = env->GetFieldID(Chunk_class, "data", "[B");
1747 static jfieldID length_fid = env->GetFieldID(Chunk_class, "length", "I");
1748 static jfieldID offset_fid = env->GetFieldID(Chunk_class, "offset", "I");
1749 static jfieldID type_fid = env->GetFieldID(Chunk_class, "type", "I");
1750
1751 // Create a byte[] corresponding to 'buf'.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001752 ScopedLocalRef<jbyteArray> dataArray(env, env->NewByteArray(dataLen));
1753 if (dataArray.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001754 LOG(WARNING) << "byte[] allocation failed: " << dataLen;
1755 env->ExceptionClear();
1756 return false;
1757 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001758 env->SetByteArrayRegion(dataArray.get(), 0, dataLen, reinterpret_cast<const jbyte*>(buf));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001759
1760 const int kChunkHdrLen = 8;
1761
1762 // Run through and find all chunks. [Currently just find the first.]
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001763 ScopedByteArrayRO contents(env, dataArray.get());
Elliott Hughesf7c3b662011-10-27 12:04:56 -07001764 jint type = JDWP::Get4BE(reinterpret_cast<const uint8_t*>(&contents[0]));
1765 jint length = JDWP::Get4BE(reinterpret_cast<const uint8_t*>(&contents[4]));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001766 jint offset = kChunkHdrLen;
1767 if (offset + length > dataLen) {
1768 LOG(WARNING) << StringPrintf("bad chunk found (len=%u pktLen=%d)", length, dataLen);
1769 return false;
1770 }
1771
1772 // Call "private static Chunk dispatch(int type, byte[] data, int offset, int length)".
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001773 ScopedLocalRef<jobject> chunk(env, env->CallStaticObjectMethod(DdmServer_class, dispatch_mid, type, dataArray.get(), offset, length));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001774 if (env->ExceptionCheck()) {
1775 LOG(INFO) << StringPrintf("Exception thrown by dispatcher for 0x%08x", type);
1776 env->ExceptionDescribe();
1777 env->ExceptionClear();
1778 return false;
1779 }
1780
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001781 if (chunk.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001782 return false;
1783 }
1784
1785 /*
1786 * Pull the pieces out of the chunk. We copy the results into a
1787 * newly-allocated buffer that the caller can free. We don't want to
1788 * continue using the Chunk object because nothing has a reference to it.
1789 *
1790 * We could avoid this by returning type/data/offset/length and having
1791 * the caller be aware of the object lifetime issues, but that
1792 * integrates the JDWP code more tightly into the VM, and doesn't work
1793 * if we have responses for multiple chunks.
1794 *
1795 * So we're pretty much stuck with copying data around multiple times.
1796 */
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001797 ScopedLocalRef<jbyteArray> replyData(env, reinterpret_cast<jbyteArray>(env->GetObjectField(chunk.get(), data_fid)));
1798 length = env->GetIntField(chunk.get(), length_fid);
1799 offset = env->GetIntField(chunk.get(), offset_fid);
1800 type = env->GetIntField(chunk.get(), type_fid);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001801
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001802 LOG(VERBOSE) << StringPrintf("DDM reply: type=0x%08x data=%p offset=%d length=%d", type, replyData.get(), offset, length);
1803 if (length == 0 || replyData.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001804 return false;
1805 }
1806
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001807 jsize replyLength = env->GetArrayLength(replyData.get());
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001808 if (offset + length > replyLength) {
1809 LOG(WARNING) << StringPrintf("chunk off=%d len=%d exceeds reply array len %d", offset, length, replyLength);
1810 return false;
1811 }
1812
1813 uint8_t* reply = new uint8_t[length + kChunkHdrLen];
1814 if (reply == NULL) {
1815 LOG(WARNING) << "malloc failed: " << (length + kChunkHdrLen);
1816 return false;
1817 }
Elliott Hughesf7c3b662011-10-27 12:04:56 -07001818 JDWP::Set4BE(reply + 0, type);
1819 JDWP::Set4BE(reply + 4, length);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001820 env->GetByteArrayRegion(replyData.get(), offset, length, reinterpret_cast<jbyte*>(reply + kChunkHdrLen));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -07001821
1822 *pReplyBuf = reply;
1823 *pReplyLen = length + kChunkHdrLen;
1824
1825 LOG(VERBOSE) << StringPrintf("dvmHandleDdm returning type=%.4s buf=%p len=%d", (char*) reply, reply, length);
1826 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001827}
1828
Elliott Hughesa2155262011-11-16 16:26:58 -08001829void Dbg::DdmBroadcast(bool connect) {
Elliott Hughes47fce012011-10-25 18:37:19 -07001830 LOG(VERBOSE) << "Broadcasting DDM " << (connect ? "connect" : "disconnect") << "...";
1831
1832 Thread* self = Thread::Current();
1833 if (self->GetState() != Thread::kRunnable) {
1834 LOG(ERROR) << "DDM broadcast in thread state " << self->GetState();
1835 /* try anyway? */
1836 }
1837
1838 JNIEnv* env = self->GetJniEnv();
1839 static jclass DdmServer_class = env->FindClass("org/apache/harmony/dalvik/ddmc/DdmServer");
1840 static jmethodID broadcast_mid = env->GetStaticMethodID(DdmServer_class, "broadcast", "(I)V");
1841 jint event = connect ? 1 /*DdmServer.CONNECTED*/ : 2 /*DdmServer.DISCONNECTED*/;
1842 env->CallStaticVoidMethod(DdmServer_class, broadcast_mid, event);
1843 if (env->ExceptionCheck()) {
1844 LOG(ERROR) << "DdmServer.broadcast " << event << " failed";
1845 env->ExceptionDescribe();
1846 env->ExceptionClear();
1847 }
1848}
1849
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001850void Dbg::DdmConnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08001851 Dbg::DdmBroadcast(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001852}
1853
1854void Dbg::DdmDisconnected() {
Elliott Hughesa2155262011-11-16 16:26:58 -08001855 Dbg::DdmBroadcast(false);
Elliott Hughes47fce012011-10-25 18:37:19 -07001856 gDdmThreadNotification = false;
1857}
1858
1859/*
Elliott Hughes82188472011-11-07 18:11:48 -08001860 * Send a notification when a thread starts, stops, or changes its name.
Elliott Hughes47fce012011-10-25 18:37:19 -07001861 *
1862 * Because we broadcast the full set of threads when the notifications are
1863 * first enabled, it's possible for "thread" to be actively executing.
1864 */
Elliott Hughes82188472011-11-07 18:11:48 -08001865void Dbg::DdmSendThreadNotification(Thread* t, uint32_t type) {
Elliott Hughes47fce012011-10-25 18:37:19 -07001866 if (!gDdmThreadNotification) {
1867 return;
1868 }
1869
Elliott Hughes82188472011-11-07 18:11:48 -08001870 if (type == CHUNK_TYPE("THDE")) {
Elliott Hughes47fce012011-10-25 18:37:19 -07001871 uint8_t buf[4];
Elliott Hughesf7c3b662011-10-27 12:04:56 -07001872 JDWP::Set4BE(&buf[0], t->GetThinLockId());
Elliott Hughes47fce012011-10-25 18:37:19 -07001873 Dbg::DdmSendChunk(CHUNK_TYPE("THDE"), 4, buf);
Elliott Hughes82188472011-11-07 18:11:48 -08001874 } else {
1875 CHECK(type == CHUNK_TYPE("THCR") || type == CHUNK_TYPE("THNM")) << type;
1876 SirtRef<String> name(t->GetName());
1877 size_t char_count = (name.get() != NULL) ? name->GetLength() : 0;
1878 const jchar* chars = name->GetCharArray()->GetData();
1879
Elliott Hughes21f32d72011-11-09 17:44:13 -08001880 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08001881 JDWP::Append4BE(bytes, t->GetThinLockId());
1882 JDWP::AppendUtf16BE(bytes, chars, char_count);
Elliott Hughes21f32d72011-11-09 17:44:13 -08001883 CHECK_EQ(bytes.size(), char_count*2 + sizeof(uint32_t)*2);
1884 Dbg::DdmSendChunk(type, bytes);
Elliott Hughes47fce012011-10-25 18:37:19 -07001885 }
1886}
1887
Elliott Hughesa2155262011-11-16 16:26:58 -08001888static void DdmSendThreadStartCallback(Thread* t, void*) {
Elliott Hughes82188472011-11-07 18:11:48 -08001889 Dbg::DdmSendThreadNotification(t, CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07001890}
1891
1892void Dbg::DdmSetThreadNotification(bool enable) {
1893 // We lock the thread list to avoid sending duplicate events or missing
1894 // a thread change. We should be okay holding this lock while sending
1895 // the messages out. (We have to hold it while accessing a live thread.)
Elliott Hughesbbd9d832011-11-07 14:40:00 -08001896 ScopedThreadListLock thread_list_lock;
Elliott Hughes47fce012011-10-25 18:37:19 -07001897
1898 gDdmThreadNotification = enable;
1899 if (enable) {
Elliott Hughesbfe487b2011-10-26 15:48:55 -07001900 Runtime::Current()->GetThreadList()->ForEach(DdmSendThreadStartCallback, NULL);
Elliott Hughes47fce012011-10-25 18:37:19 -07001901 }
1902}
1903
Elliott Hughesa2155262011-11-16 16:26:58 -08001904void Dbg::PostThreadStartOrStop(Thread* t, uint32_t type) {
Elliott Hughes47fce012011-10-25 18:37:19 -07001905 if (gDebuggerActive) {
1906 JDWP::ObjectId id = gRegistry->Add(t->GetPeer());
Elliott Hughes82188472011-11-07 18:11:48 -08001907 gJdwpState->PostThreadChange(id, type == CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07001908 }
Elliott Hughes82188472011-11-07 18:11:48 -08001909 Dbg::DdmSendThreadNotification(t, type);
Elliott Hughes47fce012011-10-25 18:37:19 -07001910}
1911
1912void Dbg::PostThreadStart(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001913 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THCR"));
Elliott Hughes47fce012011-10-25 18:37:19 -07001914}
1915
1916void Dbg::PostThreadDeath(Thread* t) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001917 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THDE"));
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001918}
1919
Elliott Hughes82188472011-11-07 18:11:48 -08001920void Dbg::DdmSendChunk(uint32_t type, size_t byte_count, const uint8_t* buf) {
Elliott Hughes3bb81562011-10-21 18:52:59 -07001921 CHECK(buf != NULL);
1922 iovec vec[1];
1923 vec[0].iov_base = reinterpret_cast<void*>(const_cast<uint8_t*>(buf));
1924 vec[0].iov_len = byte_count;
1925 Dbg::DdmSendChunkV(type, vec, 1);
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001926}
1927
Elliott Hughes21f32d72011-11-09 17:44:13 -08001928void Dbg::DdmSendChunk(uint32_t type, const std::vector<uint8_t>& bytes) {
1929 DdmSendChunk(type, bytes.size(), &bytes[0]);
1930}
1931
Elliott Hughescccd84f2011-12-05 16:51:54 -08001932void Dbg::DdmSendChunkV(uint32_t type, const struct iovec* iov, int iov_count) {
Elliott Hughes3bb81562011-10-21 18:52:59 -07001933 if (gJdwpState == NULL) {
1934 LOG(VERBOSE) << "Debugger thread not active, ignoring DDM send: " << type;
1935 } else {
Elliott Hughescccd84f2011-12-05 16:51:54 -08001936 gJdwpState->DdmSendChunkV(type, iov, iov_count);
Elliott Hughes3bb81562011-10-21 18:52:59 -07001937 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001938}
1939
Elliott Hughes767a1472011-10-26 18:49:02 -07001940int Dbg::DdmHandleHpifChunk(HpifWhen when) {
1941 if (when == HPIF_WHEN_NOW) {
Elliott Hughes7162ad92011-10-27 14:08:42 -07001942 DdmSendHeapInfo(when);
Elliott Hughes767a1472011-10-26 18:49:02 -07001943 return true;
1944 }
1945
1946 if (when != HPIF_WHEN_NEVER && when != HPIF_WHEN_NEXT_GC && when != HPIF_WHEN_EVERY_GC) {
1947 LOG(ERROR) << "invalid HpifWhen value: " << static_cast<int>(when);
1948 return false;
1949 }
1950
1951 gDdmHpifWhen = when;
1952 return true;
1953}
1954
1955bool Dbg::DdmHandleHpsgNhsgChunk(Dbg::HpsgWhen when, Dbg::HpsgWhat what, bool native) {
1956 if (when != HPSG_WHEN_NEVER && when != HPSG_WHEN_EVERY_GC) {
1957 LOG(ERROR) << "invalid HpsgWhen value: " << static_cast<int>(when);
1958 return false;
1959 }
1960
1961 if (what != HPSG_WHAT_MERGED_OBJECTS && what != HPSG_WHAT_DISTINCT_OBJECTS) {
1962 LOG(ERROR) << "invalid HpsgWhat value: " << static_cast<int>(what);
1963 return false;
1964 }
1965
1966 if (native) {
1967 gDdmNhsgWhen = when;
1968 gDdmNhsgWhat = what;
1969 } else {
1970 gDdmHpsgWhen = when;
1971 gDdmHpsgWhat = what;
1972 }
1973 return true;
1974}
1975
Elliott Hughes7162ad92011-10-27 14:08:42 -07001976void Dbg::DdmSendHeapInfo(HpifWhen reason) {
1977 // If there's a one-shot 'when', reset it.
1978 if (reason == gDdmHpifWhen) {
1979 if (gDdmHpifWhen == HPIF_WHEN_NEXT_GC) {
1980 gDdmHpifWhen = HPIF_WHEN_NEVER;
1981 }
1982 }
1983
1984 /*
1985 * Chunk HPIF (client --> server)
1986 *
1987 * Heap Info. General information about the heap,
1988 * suitable for a summary display.
1989 *
1990 * [u4]: number of heaps
1991 *
1992 * For each heap:
1993 * [u4]: heap ID
1994 * [u8]: timestamp in ms since Unix epoch
1995 * [u1]: capture reason (same as 'when' value from server)
1996 * [u4]: max heap size in bytes (-Xmx)
1997 * [u4]: current heap size in bytes
1998 * [u4]: current number of bytes allocated
1999 * [u4]: current number of objects allocated
2000 */
2001 uint8_t heap_count = 1;
Elliott Hughes21f32d72011-11-09 17:44:13 -08002002 std::vector<uint8_t> bytes;
Elliott Hughes545a0642011-11-08 19:10:03 -08002003 JDWP::Append4BE(bytes, heap_count);
2004 JDWP::Append4BE(bytes, 1); // Heap id (bogus; we only have one heap).
2005 JDWP::Append8BE(bytes, MilliTime());
2006 JDWP::Append1BE(bytes, reason);
2007 JDWP::Append4BE(bytes, Heap::GetMaxMemory()); // Max allowed heap size in bytes.
2008 JDWP::Append4BE(bytes, Heap::GetTotalMemory()); // Current heap size in bytes.
2009 JDWP::Append4BE(bytes, Heap::GetBytesAllocated());
2010 JDWP::Append4BE(bytes, Heap::GetObjectsAllocated());
Elliott Hughes21f32d72011-11-09 17:44:13 -08002011 CHECK_EQ(bytes.size(), 4U + (heap_count * (4 + 8 + 1 + 4 + 4 + 4 + 4)));
2012 Dbg::DdmSendChunk(CHUNK_TYPE("HPIF"), bytes);
Elliott Hughes767a1472011-10-26 18:49:02 -07002013}
2014
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002015enum HpsgSolidity {
2016 SOLIDITY_FREE = 0,
2017 SOLIDITY_HARD = 1,
2018 SOLIDITY_SOFT = 2,
2019 SOLIDITY_WEAK = 3,
2020 SOLIDITY_PHANTOM = 4,
2021 SOLIDITY_FINALIZABLE = 5,
2022 SOLIDITY_SWEEP = 6,
2023};
2024
2025enum HpsgKind {
2026 KIND_OBJECT = 0,
2027 KIND_CLASS_OBJECT = 1,
2028 KIND_ARRAY_1 = 2,
2029 KIND_ARRAY_2 = 3,
2030 KIND_ARRAY_4 = 4,
2031 KIND_ARRAY_8 = 5,
2032 KIND_UNKNOWN = 6,
2033 KIND_NATIVE = 7,
2034};
2035
2036#define HPSG_PARTIAL (1<<7)
2037#define HPSG_STATE(solidity, kind) ((uint8_t)((((kind) & 0x7) << 3) | ((solidity) & 0x7)))
2038
2039struct HeapChunkContext {
2040 std::vector<uint8_t> buf;
2041 uint8_t* p;
2042 uint8_t* pieceLenField;
2043 size_t totalAllocationUnits;
Elliott Hughes82188472011-11-07 18:11:48 -08002044 uint32_t type;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002045 bool merge;
2046 bool needHeader;
2047
2048 // Maximum chunk size. Obtain this from the formula:
2049 // (((maximum_heap_size / ALLOCATION_UNIT_SIZE) + 255) / 256) * 2
2050 HeapChunkContext(bool merge, bool native)
2051 : buf(16384 - 16),
2052 type(0),
2053 merge(merge) {
2054 Reset();
2055 if (native) {
2056 type = CHUNK_TYPE("NHSG");
2057 } else {
2058 type = merge ? CHUNK_TYPE("HPSG") : CHUNK_TYPE("HPSO");
2059 }
2060 }
2061
2062 ~HeapChunkContext() {
2063 if (p > &buf[0]) {
2064 Flush();
2065 }
2066 }
2067
2068 void EnsureHeader(const void* chunk_ptr) {
2069 if (!needHeader) {
2070 return;
2071 }
2072
2073 // Start a new HPSx chunk.
2074 JDWP::Write4BE(&p, 1); // Heap id (bogus; we only have one heap).
2075 JDWP::Write1BE(&p, 8); // Size of allocation unit, in bytes.
2076
2077 JDWP::Write4BE(&p, reinterpret_cast<uintptr_t>(chunk_ptr)); // virtual address of segment start.
2078 JDWP::Write4BE(&p, 0); // offset of this piece (relative to the virtual address).
2079 // [u4]: length of piece, in allocation units
2080 // We won't know this until we're done, so save the offset and stuff in a dummy value.
2081 pieceLenField = p;
2082 JDWP::Write4BE(&p, 0x55555555);
2083 needHeader = false;
2084 }
2085
2086 void Flush() {
2087 // Patch the "length of piece" field.
2088 CHECK_LE(&buf[0], pieceLenField);
2089 CHECK_LE(pieceLenField, p);
2090 JDWP::Set4BE(pieceLenField, totalAllocationUnits);
2091
2092 Dbg::DdmSendChunk(type, p - &buf[0], &buf[0]);
2093 Reset();
2094 }
2095
Elliott Hughesa2155262011-11-16 16:26:58 -08002096 static void HeapChunkCallback(const void* chunk_ptr, size_t chunk_len, const void* user_ptr, size_t user_len, void* arg) {
2097 reinterpret_cast<HeapChunkContext*>(arg)->HeapChunkCallback(chunk_ptr, chunk_len, user_ptr, user_len);
2098 }
2099
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002100 private:
Elliott Hughesa2155262011-11-16 16:26:58 -08002101 enum { ALLOCATION_UNIT_SIZE = 8 };
2102
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002103 void Reset() {
2104 p = &buf[0];
2105 totalAllocationUnits = 0;
2106 needHeader = true;
2107 pieceLenField = NULL;
2108 }
2109
Elliott Hughesa2155262011-11-16 16:26:58 -08002110 void HeapChunkCallback(const void* chunk_ptr, size_t chunk_len, const void* user_ptr, size_t user_len) {
2111 CHECK_EQ((chunk_len & (ALLOCATION_UNIT_SIZE-1)), 0U);
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002112
Elliott Hughesa2155262011-11-16 16:26:58 -08002113 /* Make sure there's enough room left in the buffer.
2114 * We need to use two bytes for every fractional 256
2115 * allocation units used by the chunk.
2116 */
2117 {
2118 size_t needed = (((chunk_len/ALLOCATION_UNIT_SIZE + 255) / 256) * 2);
2119 size_t bytesLeft = buf.size() - (size_t)(p - &buf[0]);
2120 if (bytesLeft < needed) {
2121 Flush();
2122 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002123
Elliott Hughesa2155262011-11-16 16:26:58 -08002124 bytesLeft = buf.size() - (size_t)(p - &buf[0]);
2125 if (bytesLeft < needed) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08002126 LOG(WARNING) << "Chunk is too big to transmit (chunk_len=" << chunk_len << ", " << needed << " bytes)";
Elliott Hughesa2155262011-11-16 16:26:58 -08002127 return;
2128 }
2129 }
2130
2131 // OLD-TODO: notice when there's a gap and start a new heap, or at least a new range.
2132 EnsureHeader(chunk_ptr);
2133
2134 // Determine the type of this chunk.
2135 // OLD-TODO: if context.merge, see if this chunk is different from the last chunk.
2136 // If it's the same, we should combine them.
2137 uint8_t state = ExamineObject(reinterpret_cast<const Object*>(user_ptr), (type == CHUNK_TYPE("NHSG")));
2138
2139 // Write out the chunk description.
2140 chunk_len /= ALLOCATION_UNIT_SIZE; // convert to allocation units
2141 totalAllocationUnits += chunk_len;
2142 while (chunk_len > 256) {
2143 *p++ = state | HPSG_PARTIAL;
2144 *p++ = 255; // length - 1
2145 chunk_len -= 256;
2146 }
2147 *p++ = state;
2148 *p++ = chunk_len - 1;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002149 }
2150
Elliott Hughesa2155262011-11-16 16:26:58 -08002151 uint8_t ExamineObject(const Object* o, bool is_native_heap) {
2152 if (o == NULL) {
2153 return HPSG_STATE(SOLIDITY_FREE, 0);
2154 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002155
Elliott Hughesa2155262011-11-16 16:26:58 -08002156 // It's an allocated chunk. Figure out what it is.
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002157
Elliott Hughesa2155262011-11-16 16:26:58 -08002158 // If we're looking at the native heap, we'll just return
2159 // (SOLIDITY_HARD, KIND_NATIVE) for all allocated chunks.
2160 if (is_native_heap || !Heap::IsLiveObjectLocked(o)) {
2161 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
2162 }
2163
2164 Class* c = o->GetClass();
2165 if (c == NULL) {
2166 // The object was probably just created but hasn't been initialized yet.
2167 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
2168 }
2169
2170 if (!Heap::IsHeapAddress(c)) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -08002171 LOG(WARNING) << "Invalid class for managed heap object: " << o << " " << c;
Elliott Hughesa2155262011-11-16 16:26:58 -08002172 return HPSG_STATE(SOLIDITY_HARD, KIND_UNKNOWN);
2173 }
2174
2175 if (c->IsClassClass()) {
2176 return HPSG_STATE(SOLIDITY_HARD, KIND_CLASS_OBJECT);
2177 }
2178
2179 if (c->IsArrayClass()) {
2180 if (o->IsObjectArray()) {
2181 return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
2182 }
2183 switch (c->GetComponentSize()) {
2184 case 1: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_1);
2185 case 2: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_2);
2186 case 4: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
2187 case 8: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_8);
2188 }
2189 }
2190
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002191 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
2192 }
2193
Elliott Hughesa2155262011-11-16 16:26:58 -08002194 DISALLOW_COPY_AND_ASSIGN(HeapChunkContext);
2195};
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002196
2197void Dbg::DdmSendHeapSegments(bool native) {
2198 Dbg::HpsgWhen when;
2199 Dbg::HpsgWhat what;
2200 if (!native) {
2201 when = gDdmHpsgWhen;
2202 what = gDdmHpsgWhat;
2203 } else {
2204 when = gDdmNhsgWhen;
2205 what = gDdmNhsgWhat;
2206 }
2207 if (when == HPSG_WHEN_NEVER) {
2208 return;
2209 }
2210
2211 // Figure out what kind of chunks we'll be sending.
2212 CHECK(what == HPSG_WHAT_MERGED_OBJECTS || what == HPSG_WHAT_DISTINCT_OBJECTS) << static_cast<int>(what);
2213
2214 // First, send a heap start chunk.
2215 uint8_t heap_id[4];
2216 JDWP::Set4BE(&heap_id[0], 1); // Heap id (bogus; we only have one heap).
2217 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHST") : CHUNK_TYPE("HPST"), sizeof(heap_id), heap_id);
2218
2219 // Send a series of heap segment chunks.
Elliott Hughesa2155262011-11-16 16:26:58 -08002220 HeapChunkContext context((what == HPSG_WHAT_MERGED_OBJECTS), native);
2221 if (native) {
2222 dlmalloc_walk_heap(HeapChunkContext::HeapChunkCallback, &context);
2223 } else {
2224 Heap::WalkHeap(HeapChunkContext::HeapChunkCallback, &context);
2225 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -07002226
2227 // Finally, send a heap end chunk.
2228 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHEN") : CHUNK_TYPE("HPEN"), sizeof(heap_id), heap_id);
Elliott Hughes767a1472011-10-26 18:49:02 -07002229}
2230
Elliott Hughes545a0642011-11-08 19:10:03 -08002231void Dbg::SetAllocTrackingEnabled(bool enabled) {
2232 MutexLock mu(gAllocTrackerLock);
2233 if (enabled) {
2234 if (recent_allocation_records_ == NULL) {
2235 LOG(INFO) << "Enabling alloc tracker (" << kNumAllocRecords << " entries, "
2236 << kMaxAllocRecordStackDepth << " frames --> "
2237 << (sizeof(AllocRecord) * kNumAllocRecords) << " bytes)";
2238 gAllocRecordHead = gAllocRecordCount = 0;
2239 recent_allocation_records_ = new AllocRecord[kNumAllocRecords];
2240 CHECK(recent_allocation_records_ != NULL);
2241 }
2242 } else {
2243 delete[] recent_allocation_records_;
2244 recent_allocation_records_ = NULL;
2245 }
2246}
2247
2248struct AllocRecordStackVisitor : public Thread::StackVisitor {
2249 AllocRecordStackVisitor(AllocRecord* record) : record(record), depth(0) {
2250 }
2251
2252 virtual void VisitFrame(const Frame& f, uintptr_t pc) {
2253 if (depth >= kMaxAllocRecordStackDepth) {
2254 return;
2255 }
2256 Method* m = f.GetMethod();
2257 if (m == NULL || m->IsCalleeSaveMethod()) {
2258 return;
2259 }
2260 record->stack[depth].method = m;
2261 record->stack[depth].raw_pc = pc;
2262 ++depth;
2263 }
2264
2265 ~AllocRecordStackVisitor() {
2266 // Clear out any unused stack trace elements.
2267 for (; depth < kMaxAllocRecordStackDepth; ++depth) {
2268 record->stack[depth].method = NULL;
2269 record->stack[depth].raw_pc = 0;
2270 }
2271 }
2272
2273 AllocRecord* record;
2274 size_t depth;
2275};
2276
2277void Dbg::RecordAllocation(Class* type, size_t byte_count) {
2278 Thread* self = Thread::Current();
2279 CHECK(self != NULL);
2280
2281 MutexLock mu(gAllocTrackerLock);
2282 if (recent_allocation_records_ == NULL) {
2283 return;
2284 }
2285
2286 // Advance and clip.
2287 if (++gAllocRecordHead == kNumAllocRecords) {
2288 gAllocRecordHead = 0;
2289 }
2290
2291 // Fill in the basics.
2292 AllocRecord* record = &recent_allocation_records_[gAllocRecordHead];
2293 record->type = type;
2294 record->byte_count = byte_count;
2295 record->thin_lock_id = self->GetThinLockId();
2296
2297 // Fill in the stack trace.
2298 AllocRecordStackVisitor visitor(record);
2299 self->WalkStack(&visitor);
2300
2301 if (gAllocRecordCount < kNumAllocRecords) {
2302 ++gAllocRecordCount;
2303 }
2304}
2305
2306/*
2307 * Return the index of the head element.
2308 *
2309 * We point at the most-recently-written record, so if allocRecordCount is 1
2310 * we want to use the current element. Take "head+1" and subtract count
2311 * from it.
2312 *
2313 * We need to handle underflow in our circular buffer, so we add
2314 * kNumAllocRecords and then mask it back down.
2315 */
2316inline static int headIndex() {
2317 return (gAllocRecordHead+1 + kNumAllocRecords - gAllocRecordCount) & (kNumAllocRecords-1);
2318}
2319
2320void Dbg::DumpRecentAllocations() {
2321 MutexLock mu(gAllocTrackerLock);
2322 if (recent_allocation_records_ == NULL) {
2323 LOG(INFO) << "Not recording tracked allocations";
2324 return;
2325 }
2326
2327 // "i" is the head of the list. We want to start at the end of the
2328 // list and move forward to the tail.
2329 size_t i = headIndex();
2330 size_t count = gAllocRecordCount;
2331
2332 LOG(INFO) << "Tracked allocations, (head=" << gAllocRecordHead << " count=" << count << ")";
2333 while (count--) {
2334 AllocRecord* record = &recent_allocation_records_[i];
2335
2336 LOG(INFO) << StringPrintf(" T=%-2d %6d ", record->thin_lock_id, record->byte_count)
2337 << PrettyClass(record->type);
2338
2339 for (size_t stack_frame = 0; stack_frame < kMaxAllocRecordStackDepth; ++stack_frame) {
2340 const Method* m = record->stack[stack_frame].method;
2341 if (m == NULL) {
2342 break;
2343 }
2344 LOG(INFO) << " " << PrettyMethod(m) << " line " << record->stack[stack_frame].LineNumber();
2345 }
2346
2347 // pause periodically to help logcat catch up
2348 if ((count % 5) == 0) {
2349 usleep(40000);
2350 }
2351
2352 i = (i + 1) & (kNumAllocRecords-1);
2353 }
2354}
2355
2356class StringTable {
2357 public:
2358 StringTable() {
2359 }
2360
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002361 void Add(const char* s) {
Elliott Hughes545a0642011-11-08 19:10:03 -08002362 table_.insert(s);
2363 }
2364
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002365 size_t IndexOf(const char* s) {
Elliott Hughes545a0642011-11-08 19:10:03 -08002366 return std::distance(table_.begin(), table_.find(s));
2367 }
2368
2369 size_t Size() {
2370 return table_.size();
2371 }
2372
2373 void WriteTo(std::vector<uint8_t>& bytes) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002374 typedef std::set<const char*>::const_iterator It; // TODO: C++0x auto
Elliott Hughes545a0642011-11-08 19:10:03 -08002375 for (It it = table_.begin(); it != table_.end(); ++it) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002376 const char* s = *it;
2377 size_t s_len = CountModifiedUtf8Chars(s);
2378 UniquePtr<uint16_t> s_utf16(new uint16_t[s_len]);
2379 ConvertModifiedUtf8ToUtf16(s_utf16.get(), s);
2380 JDWP::AppendUtf16BE(bytes, s_utf16.get(), s_len);
Elliott Hughes545a0642011-11-08 19:10:03 -08002381 }
2382 }
2383
2384 private:
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002385 std::set<const char*> table_;
Elliott Hughes545a0642011-11-08 19:10:03 -08002386 DISALLOW_COPY_AND_ASSIGN(StringTable);
2387};
2388
2389/*
2390 * The data we send to DDMS contains everything we have recorded.
2391 *
2392 * Message header (all values big-endian):
2393 * (1b) message header len (to allow future expansion); includes itself
2394 * (1b) entry header len
2395 * (1b) stack frame len
2396 * (2b) number of entries
2397 * (4b) offset to string table from start of message
2398 * (2b) number of class name strings
2399 * (2b) number of method name strings
2400 * (2b) number of source file name strings
2401 * For each entry:
2402 * (4b) total allocation size
2403 * (2b) threadId
2404 * (2b) allocated object's class name index
2405 * (1b) stack depth
2406 * For each stack frame:
2407 * (2b) method's class name
2408 * (2b) method name
2409 * (2b) method source file
2410 * (2b) line number, clipped to 32767; -2 if native; -1 if no source
2411 * (xb) class name strings
2412 * (xb) method name strings
2413 * (xb) source file strings
2414 *
2415 * As with other DDM traffic, strings are sent as a 4-byte length
2416 * followed by UTF-16 data.
2417 *
2418 * We send up 16-bit unsigned indexes into string tables. In theory there
2419 * can be (kMaxAllocRecordStackDepth * kNumAllocRecords) unique strings in
2420 * each table, but in practice there should be far fewer.
2421 *
2422 * The chief reason for using a string table here is to keep the size of
2423 * the DDMS message to a minimum. This is partly to make the protocol
2424 * efficient, but also because we have to form the whole thing up all at
2425 * once in a memory buffer.
2426 *
2427 * We use separate string tables for class names, method names, and source
2428 * files to keep the indexes small. There will generally be no overlap
2429 * between the contents of these tables.
2430 */
2431jbyteArray Dbg::GetRecentAllocations() {
2432 if (false) {
2433 DumpRecentAllocations();
2434 }
2435
2436 MutexLock mu(gAllocTrackerLock);
2437
2438 /*
2439 * Part 1: generate string tables.
2440 */
2441 StringTable class_names;
2442 StringTable method_names;
2443 StringTable filenames;
2444
2445 int count = gAllocRecordCount;
2446 int idx = headIndex();
2447 while (count--) {
2448 AllocRecord* record = &recent_allocation_records_[idx];
2449
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002450 class_names.Add(ClassHelper(record->type).GetDescriptor().c_str());
Elliott Hughes545a0642011-11-08 19:10:03 -08002451
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002452 MethodHelper mh;
Elliott Hughes545a0642011-11-08 19:10:03 -08002453 for (size_t i = 0; i < kMaxAllocRecordStackDepth; i++) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002454 Method* m = record->stack[i].method;
2455 mh.ChangeMethod(m);
Elliott Hughes545a0642011-11-08 19:10:03 -08002456 if (m != NULL) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002457 class_names.Add(mh.GetDeclaringClassDescriptor());
2458 method_names.Add(mh.GetName());
2459 filenames.Add(mh.GetDeclaringClassSourceFile());
Elliott Hughes545a0642011-11-08 19:10:03 -08002460 }
2461 }
2462
2463 idx = (idx + 1) & (kNumAllocRecords-1);
2464 }
2465
2466 LOG(INFO) << "allocation records: " << gAllocRecordCount;
2467
2468 /*
2469 * Part 2: allocate a buffer and generate the output.
2470 */
2471 std::vector<uint8_t> bytes;
2472
2473 // (1b) message header len (to allow future expansion); includes itself
2474 // (1b) entry header len
2475 // (1b) stack frame len
2476 const int kMessageHeaderLen = 15;
2477 const int kEntryHeaderLen = 9;
2478 const int kStackFrameLen = 8;
2479 JDWP::Append1BE(bytes, kMessageHeaderLen);
2480 JDWP::Append1BE(bytes, kEntryHeaderLen);
2481 JDWP::Append1BE(bytes, kStackFrameLen);
2482
2483 // (2b) number of entries
2484 // (4b) offset to string table from start of message
2485 // (2b) number of class name strings
2486 // (2b) number of method name strings
2487 // (2b) number of source file name strings
2488 JDWP::Append2BE(bytes, gAllocRecordCount);
2489 size_t string_table_offset = bytes.size();
2490 JDWP::Append4BE(bytes, 0); // We'll patch this later...
2491 JDWP::Append2BE(bytes, class_names.Size());
2492 JDWP::Append2BE(bytes, method_names.Size());
2493 JDWP::Append2BE(bytes, filenames.Size());
2494
2495 count = gAllocRecordCount;
2496 idx = headIndex();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002497 ClassHelper kh;
Elliott Hughes545a0642011-11-08 19:10:03 -08002498 while (count--) {
2499 // For each entry:
2500 // (4b) total allocation size
2501 // (2b) thread id
2502 // (2b) allocated object's class name index
2503 // (1b) stack depth
2504 AllocRecord* record = &recent_allocation_records_[idx];
2505 size_t stack_depth = record->GetDepth();
2506 JDWP::Append4BE(bytes, record->byte_count);
2507 JDWP::Append2BE(bytes, record->thin_lock_id);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002508 kh.ChangeClass(record->type);
2509 JDWP::Append2BE(bytes, class_names.IndexOf(kh.GetDescriptor().c_str()));
Elliott Hughes545a0642011-11-08 19:10:03 -08002510 JDWP::Append1BE(bytes, stack_depth);
2511
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002512 MethodHelper mh;
Elliott Hughes545a0642011-11-08 19:10:03 -08002513 for (size_t stack_frame = 0; stack_frame < stack_depth; ++stack_frame) {
2514 // For each stack frame:
2515 // (2b) method's class name
2516 // (2b) method name
2517 // (2b) method source file
2518 // (2b) line number, clipped to 32767; -2 if native; -1 if no source
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002519 mh.ChangeMethod(record->stack[stack_frame].method);
2520 JDWP::Append2BE(bytes, class_names.IndexOf(mh.GetDeclaringClassDescriptor()));
2521 JDWP::Append2BE(bytes, method_names.IndexOf(mh.GetName()));
2522 JDWP::Append2BE(bytes, filenames.IndexOf(mh.GetDeclaringClassSourceFile()));
Elliott Hughes545a0642011-11-08 19:10:03 -08002523 JDWP::Append2BE(bytes, record->stack[stack_frame].LineNumber());
2524 }
2525
2526 idx = (idx + 1) & (kNumAllocRecords-1);
2527 }
2528
2529 // (xb) class name strings
2530 // (xb) method name strings
2531 // (xb) source file strings
2532 JDWP::Set4BE(&bytes[string_table_offset], bytes.size());
2533 class_names.WriteTo(bytes);
2534 method_names.WriteTo(bytes);
2535 filenames.WriteTo(bytes);
2536
2537 JNIEnv* env = Thread::Current()->GetJniEnv();
2538 jbyteArray result = env->NewByteArray(bytes.size());
2539 if (result != NULL) {
2540 env->SetByteArrayRegion(result, 0, bytes.size(), reinterpret_cast<const jbyte*>(&bytes[0]));
2541 }
2542 return result;
2543}
2544
Elliott Hughes872d4ec2011-10-21 17:07:15 -07002545} // namespace art