debugger.cc revision 87118ed6f3f99e7df33214c277cf200a7b9a7499
1/* 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 19#include <sys/uio.h> 20 21#include <set> 22 23#include "arch/context.h" 24#include "class_linker.h" 25#include "class_linker-inl.h" 26#include "dex_file-inl.h" 27#include "dex_instruction.h" 28#include "gc/accounting/card_table-inl.h" 29#include "gc/space/large_object_space.h" 30#include "gc/space/space-inl.h" 31#include "invoke_arg_array_builder.h" 32#include "jdwp/object_registry.h" 33#include "mirror/art_field-inl.h" 34#include "mirror/art_method-inl.h" 35#include "mirror/class.h" 36#include "mirror/class-inl.h" 37#include "mirror/class_loader.h" 38#include "mirror/object-inl.h" 39#include "mirror/object_array-inl.h" 40#include "mirror/throwable.h" 41#include "object_utils.h" 42#include "safe_map.h" 43#include "scoped_thread_state_change.h" 44#include "ScopedLocalRef.h" 45#include "ScopedPrimitiveArray.h" 46#include "sirt_ref.h" 47#include "stack_indirect_reference_table.h" 48#include "thread_list.h" 49#include "throw_location.h" 50#include "utf.h" 51#include "well_known_classes.h" 52 53#ifdef HAVE_ANDROID_OS 54#include "cutils/properties.h" 55#endif 56 57namespace art { 58 59static const size_t kMaxAllocRecordStackDepth = 16; // Max 255. 60static const size_t kDefaultNumAllocRecords = 64*1024; // Must be a power of 2. 61 62struct AllocRecordStackTraceElement { 63 mirror::ArtMethod* method; 64 uint32_t dex_pc; 65 66 int32_t LineNumber() const SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 67 return MethodHelper(method).GetLineNumFromDexPC(dex_pc); 68 } 69}; 70 71struct AllocRecord { 72 mirror::Class* type; 73 size_t byte_count; 74 uint16_t thin_lock_id; 75 AllocRecordStackTraceElement stack[kMaxAllocRecordStackDepth]; // Unused entries have NULL method. 76 77 size_t GetDepth() { 78 size_t depth = 0; 79 while (depth < kMaxAllocRecordStackDepth && stack[depth].method != NULL) { 80 ++depth; 81 } 82 return depth; 83 } 84}; 85 86struct Breakpoint { 87 mirror::ArtMethod* method; 88 uint32_t dex_pc; 89 Breakpoint(mirror::ArtMethod* method, uint32_t dex_pc) : method(method), dex_pc(dex_pc) {} 90}; 91 92static std::ostream& operator<<(std::ostream& os, const Breakpoint& rhs) 93 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 94 os << StringPrintf("Breakpoint[%s @%#x]", PrettyMethod(rhs.method).c_str(), rhs.dex_pc); 95 return os; 96} 97 98class DebugInstrumentationListener : public instrumentation::InstrumentationListener { 99 public: 100 DebugInstrumentationListener() {} 101 virtual ~DebugInstrumentationListener() {} 102 103 virtual void MethodEntered(Thread* thread, mirror::Object* this_object, 104 const mirror::ArtMethod* method, uint32_t dex_pc) 105 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 106 if (method->IsNative()) { 107 // TODO: post location events is a suspension point and native method entry stubs aren't. 108 return; 109 } 110 Dbg::PostLocationEvent(method, 0, this_object, Dbg::kMethodEntry, nullptr); 111 } 112 113 virtual void MethodExited(Thread* thread, mirror::Object* this_object, 114 const mirror::ArtMethod* method, 115 uint32_t dex_pc, const JValue& return_value) 116 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 117 if (method->IsNative()) { 118 // TODO: post location events is a suspension point and native method entry stubs aren't. 119 return; 120 } 121 Dbg::PostLocationEvent(method, dex_pc, this_object, Dbg::kMethodExit, &return_value); 122 } 123 124 virtual void MethodUnwind(Thread* thread, mirror::Object* this_object, 125 const mirror::ArtMethod* method, uint32_t dex_pc) 126 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 127 // We're not recorded to listen to this kind of event, so complain. 128 LOG(ERROR) << "Unexpected method unwind event in debugger " << PrettyMethod(method) 129 << " " << dex_pc; 130 } 131 132 virtual void DexPcMoved(Thread* thread, mirror::Object* this_object, 133 const mirror::ArtMethod* method, uint32_t new_dex_pc) 134 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 135 Dbg::UpdateDebugger(thread, this_object, method, new_dex_pc); 136 } 137 138 virtual void ExceptionCaught(Thread* thread, const ThrowLocation& throw_location, 139 mirror::ArtMethod* catch_method, uint32_t catch_dex_pc, 140 mirror::Throwable* exception_object) 141 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 142 Dbg::PostException(thread, throw_location, catch_method, catch_dex_pc, exception_object); 143 } 144} gDebugInstrumentationListener; 145 146// JDWP is allowed unless the Zygote forbids it. 147static bool gJdwpAllowed = true; 148 149// Was there a -Xrunjdwp or -agentlib:jdwp= argument on the command line? 150static bool gJdwpConfigured = false; 151 152// Broken-down JDWP options. (Only valid if IsJdwpConfigured() is true.) 153static JDWP::JdwpOptions gJdwpOptions; 154 155// Runtime JDWP state. 156static JDWP::JdwpState* gJdwpState = NULL; 157static bool gDebuggerConnected; // debugger or DDMS is connected. 158static bool gDebuggerActive; // debugger is making requests. 159static bool gDisposed; // debugger called VirtualMachine.Dispose, so we should drop the connection. 160 161static bool gDdmThreadNotification = false; 162 163// DDMS GC-related settings. 164static Dbg::HpifWhen gDdmHpifWhen = Dbg::HPIF_WHEN_NEVER; 165static Dbg::HpsgWhen gDdmHpsgWhen = Dbg::HPSG_WHEN_NEVER; 166static Dbg::HpsgWhat gDdmHpsgWhat; 167static Dbg::HpsgWhen gDdmNhsgWhen = Dbg::HPSG_WHEN_NEVER; 168static Dbg::HpsgWhat gDdmNhsgWhat; 169 170static ObjectRegistry* gRegistry = NULL; 171 172// Recent allocation tracking. 173static Mutex gAllocTrackerLock DEFAULT_MUTEX_ACQUIRED_AFTER("AllocTracker lock"); 174AllocRecord* Dbg::recent_allocation_records_ PT_GUARDED_BY(gAllocTrackerLock) = NULL; // TODO: CircularBuffer<AllocRecord> 175static size_t gAllocRecordMax GUARDED_BY(gAllocTrackerLock) = 0; 176static size_t gAllocRecordHead GUARDED_BY(gAllocTrackerLock) = 0; 177static size_t gAllocRecordCount GUARDED_BY(gAllocTrackerLock) = 0; 178 179// Breakpoints and single-stepping. 180static std::vector<Breakpoint> gBreakpoints GUARDED_BY(Locks::breakpoint_lock_); 181 182static bool IsBreakpoint(const mirror::ArtMethod* m, uint32_t dex_pc) 183 LOCKS_EXCLUDED(Locks::breakpoint_lock_) 184 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 185 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_); 186 for (size_t i = 0; i < gBreakpoints.size(); ++i) { 187 if (gBreakpoints[i].method == m && gBreakpoints[i].dex_pc == dex_pc) { 188 VLOG(jdwp) << "Hit breakpoint #" << i << ": " << gBreakpoints[i]; 189 return true; 190 } 191 } 192 return false; 193} 194 195static bool IsSuspendedForDebugger(ScopedObjectAccessUnchecked& soa, Thread* thread) { 196 MutexLock mu(soa.Self(), *Locks::thread_suspend_count_lock_); 197 // A thread may be suspended for GC; in this code, we really want to know whether 198 // there's a debugger suspension active. 199 return thread->IsSuspended() && thread->GetDebugSuspendCount() > 0; 200} 201 202static mirror::Array* DecodeArray(JDWP::RefTypeId id, JDWP::JdwpError& status) 203 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 204 mirror::Object* o = gRegistry->Get<mirror::Object*>(id); 205 if (o == NULL || o == ObjectRegistry::kInvalidObject) { 206 status = JDWP::ERR_INVALID_OBJECT; 207 return NULL; 208 } 209 if (!o->IsArrayInstance()) { 210 status = JDWP::ERR_INVALID_ARRAY; 211 return NULL; 212 } 213 status = JDWP::ERR_NONE; 214 return o->AsArray(); 215} 216 217static mirror::Class* DecodeClass(JDWP::RefTypeId id, JDWP::JdwpError& status) 218 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 219 mirror::Object* o = gRegistry->Get<mirror::Object*>(id); 220 if (o == NULL || o == ObjectRegistry::kInvalidObject) { 221 status = JDWP::ERR_INVALID_OBJECT; 222 return NULL; 223 } 224 if (!o->IsClass()) { 225 status = JDWP::ERR_INVALID_CLASS; 226 return NULL; 227 } 228 status = JDWP::ERR_NONE; 229 return o->AsClass(); 230} 231 232static JDWP::JdwpError DecodeThread(ScopedObjectAccessUnchecked& soa, JDWP::ObjectId thread_id, Thread*& thread) 233 EXCLUSIVE_LOCKS_REQUIRED(Locks::thread_list_lock_) 234 LOCKS_EXCLUDED(Locks::thread_suspend_count_lock_) 235 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 236 mirror::Object* thread_peer = gRegistry->Get<mirror::Object*>(thread_id); 237 if (thread_peer == NULL || thread_peer == ObjectRegistry::kInvalidObject) { 238 // This isn't even an object. 239 return JDWP::ERR_INVALID_OBJECT; 240 } 241 242 mirror::Class* java_lang_Thread = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_Thread); 243 if (!java_lang_Thread->IsAssignableFrom(thread_peer->GetClass())) { 244 // This isn't a thread. 245 return JDWP::ERR_INVALID_THREAD; 246 } 247 248 thread = Thread::FromManagedThread(soa, thread_peer); 249 if (thread == NULL) { 250 // This is a java.lang.Thread without a Thread*. Must be a zombie. 251 return JDWP::ERR_THREAD_NOT_ALIVE; 252 } 253 return JDWP::ERR_NONE; 254} 255 256static JDWP::JdwpTag BasicTagFromDescriptor(const char* descriptor) { 257 // JDWP deliberately uses the descriptor characters' ASCII values for its enum. 258 // Note that by "basic" we mean that we don't get more specific than JT_OBJECT. 259 return static_cast<JDWP::JdwpTag>(descriptor[0]); 260} 261 262static JDWP::JdwpTag TagFromClass(mirror::Class* c) 263 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 264 CHECK(c != NULL); 265 if (c->IsArrayClass()) { 266 return JDWP::JT_ARRAY; 267 } 268 269 ClassLinker* class_linker = Runtime::Current()->GetClassLinker(); 270 if (c->IsStringClass()) { 271 return JDWP::JT_STRING; 272 } else if (c->IsClassClass()) { 273 return JDWP::JT_CLASS_OBJECT; 274 } else if (class_linker->FindSystemClass("Ljava/lang/Thread;")->IsAssignableFrom(c)) { 275 return JDWP::JT_THREAD; 276 } else if (class_linker->FindSystemClass("Ljava/lang/ThreadGroup;")->IsAssignableFrom(c)) { 277 return JDWP::JT_THREAD_GROUP; 278 } else if (class_linker->FindSystemClass("Ljava/lang/ClassLoader;")->IsAssignableFrom(c)) { 279 return JDWP::JT_CLASS_LOADER; 280 } else { 281 return JDWP::JT_OBJECT; 282 } 283} 284 285/* 286 * Objects declared to hold Object might actually hold a more specific 287 * type. The debugger may take a special interest in these (e.g. it 288 * wants to display the contents of Strings), so we want to return an 289 * appropriate tag. 290 * 291 * Null objects are tagged JT_OBJECT. 292 */ 293static JDWP::JdwpTag TagFromObject(const mirror::Object* o) 294 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 295 return (o == NULL) ? JDWP::JT_OBJECT : TagFromClass(o->GetClass()); 296} 297 298static bool IsPrimitiveTag(JDWP::JdwpTag tag) { 299 switch (tag) { 300 case JDWP::JT_BOOLEAN: 301 case JDWP::JT_BYTE: 302 case JDWP::JT_CHAR: 303 case JDWP::JT_FLOAT: 304 case JDWP::JT_DOUBLE: 305 case JDWP::JT_INT: 306 case JDWP::JT_LONG: 307 case JDWP::JT_SHORT: 308 case JDWP::JT_VOID: 309 return true; 310 default: 311 return false; 312 } 313} 314 315/* 316 * Handle one of the JDWP name/value pairs. 317 * 318 * JDWP options are: 319 * help: if specified, show help message and bail 320 * transport: may be dt_socket or dt_shmem 321 * address: for dt_socket, "host:port", or just "port" when listening 322 * server: if "y", wait for debugger to attach; if "n", attach to debugger 323 * timeout: how long to wait for debugger to connect / listen 324 * 325 * Useful with server=n (these aren't supported yet): 326 * onthrow=<exception-name>: connect to debugger when exception thrown 327 * onuncaught=y|n: connect to debugger when uncaught exception thrown 328 * launch=<command-line>: launch the debugger itself 329 * 330 * The "transport" option is required, as is "address" if server=n. 331 */ 332static bool ParseJdwpOption(const std::string& name, const std::string& value) { 333 if (name == "transport") { 334 if (value == "dt_socket") { 335 gJdwpOptions.transport = JDWP::kJdwpTransportSocket; 336 } else if (value == "dt_android_adb") { 337 gJdwpOptions.transport = JDWP::kJdwpTransportAndroidAdb; 338 } else { 339 LOG(ERROR) << "JDWP transport not supported: " << value; 340 return false; 341 } 342 } else if (name == "server") { 343 if (value == "n") { 344 gJdwpOptions.server = false; 345 } else if (value == "y") { 346 gJdwpOptions.server = true; 347 } else { 348 LOG(ERROR) << "JDWP option 'server' must be 'y' or 'n'"; 349 return false; 350 } 351 } else if (name == "suspend") { 352 if (value == "n") { 353 gJdwpOptions.suspend = false; 354 } else if (value == "y") { 355 gJdwpOptions.suspend = true; 356 } else { 357 LOG(ERROR) << "JDWP option 'suspend' must be 'y' or 'n'"; 358 return false; 359 } 360 } else if (name == "address") { 361 /* this is either <port> or <host>:<port> */ 362 std::string port_string; 363 gJdwpOptions.host.clear(); 364 std::string::size_type colon = value.find(':'); 365 if (colon != std::string::npos) { 366 gJdwpOptions.host = value.substr(0, colon); 367 port_string = value.substr(colon + 1); 368 } else { 369 port_string = value; 370 } 371 if (port_string.empty()) { 372 LOG(ERROR) << "JDWP address missing port: " << value; 373 return false; 374 } 375 char* end; 376 uint64_t port = strtoul(port_string.c_str(), &end, 10); 377 if (*end != '\0' || port > 0xffff) { 378 LOG(ERROR) << "JDWP address has junk in port field: " << value; 379 return false; 380 } 381 gJdwpOptions.port = port; 382 } else if (name == "launch" || name == "onthrow" || name == "oncaught" || name == "timeout") { 383 /* valid but unsupported */ 384 LOG(INFO) << "Ignoring JDWP option '" << name << "'='" << value << "'"; 385 } else { 386 LOG(INFO) << "Ignoring unrecognized JDWP option '" << name << "'='" << value << "'"; 387 } 388 389 return true; 390} 391 392/* 393 * Parse the latter half of a -Xrunjdwp/-agentlib:jdwp= string, e.g.: 394 * "transport=dt_socket,address=8000,server=y,suspend=n" 395 */ 396bool Dbg::ParseJdwpOptions(const std::string& options) { 397 VLOG(jdwp) << "ParseJdwpOptions: " << options; 398 399 std::vector<std::string> pairs; 400 Split(options, ',', pairs); 401 402 for (size_t i = 0; i < pairs.size(); ++i) { 403 std::string::size_type equals = pairs[i].find('='); 404 if (equals == std::string::npos) { 405 LOG(ERROR) << "Can't parse JDWP option '" << pairs[i] << "' in '" << options << "'"; 406 return false; 407 } 408 ParseJdwpOption(pairs[i].substr(0, equals), pairs[i].substr(equals + 1)); 409 } 410 411 if (gJdwpOptions.transport == JDWP::kJdwpTransportUnknown) { 412 LOG(ERROR) << "Must specify JDWP transport: " << options; 413 } 414 if (!gJdwpOptions.server && (gJdwpOptions.host.empty() || gJdwpOptions.port == 0)) { 415 LOG(ERROR) << "Must specify JDWP host and port when server=n: " << options; 416 return false; 417 } 418 419 gJdwpConfigured = true; 420 return true; 421} 422 423void Dbg::StartJdwp() { 424 if (!gJdwpAllowed || !IsJdwpConfigured()) { 425 // No JDWP for you! 426 return; 427 } 428 429 CHECK(gRegistry == NULL); 430 gRegistry = new ObjectRegistry; 431 432 // Init JDWP if the debugger is enabled. This may connect out to a 433 // debugger, passively listen for a debugger, or block waiting for a 434 // debugger. 435 gJdwpState = JDWP::JdwpState::Create(&gJdwpOptions); 436 if (gJdwpState == NULL) { 437 // We probably failed because some other process has the port already, which means that 438 // if we don't abort the user is likely to think they're talking to us when they're actually 439 // talking to that other process. 440 LOG(FATAL) << "Debugger thread failed to initialize"; 441 } 442 443 // If a debugger has already attached, send the "welcome" message. 444 // This may cause us to suspend all threads. 445 if (gJdwpState->IsActive()) { 446 ScopedObjectAccess soa(Thread::Current()); 447 if (!gJdwpState->PostVMStart()) { 448 LOG(WARNING) << "Failed to post 'start' message to debugger"; 449 } 450 } 451} 452 453void Dbg::StopJdwp() { 454 delete gJdwpState; 455 delete gRegistry; 456 gRegistry = NULL; 457} 458 459void Dbg::GcDidFinish() { 460 if (gDdmHpifWhen != HPIF_WHEN_NEVER) { 461 ScopedObjectAccess soa(Thread::Current()); 462 LOG(DEBUG) << "Sending heap info to DDM"; 463 DdmSendHeapInfo(gDdmHpifWhen); 464 } 465 if (gDdmHpsgWhen != HPSG_WHEN_NEVER) { 466 ScopedObjectAccess soa(Thread::Current()); 467 LOG(DEBUG) << "Dumping heap to DDM"; 468 DdmSendHeapSegments(false); 469 } 470 if (gDdmNhsgWhen != HPSG_WHEN_NEVER) { 471 ScopedObjectAccess soa(Thread::Current()); 472 LOG(DEBUG) << "Dumping native heap to DDM"; 473 DdmSendHeapSegments(true); 474 } 475} 476 477void Dbg::SetJdwpAllowed(bool allowed) { 478 gJdwpAllowed = allowed; 479} 480 481DebugInvokeReq* Dbg::GetInvokeReq() { 482 return Thread::Current()->GetInvokeReq(); 483} 484 485Thread* Dbg::GetDebugThread() { 486 return (gJdwpState != NULL) ? gJdwpState->GetDebugThread() : NULL; 487} 488 489void Dbg::ClearWaitForEventThread() { 490 gJdwpState->ClearWaitForEventThread(); 491} 492 493void Dbg::Connected() { 494 CHECK(!gDebuggerConnected); 495 VLOG(jdwp) << "JDWP has attached"; 496 gDebuggerConnected = true; 497 gDisposed = false; 498} 499 500void Dbg::Disposed() { 501 gDisposed = true; 502} 503 504bool Dbg::IsDisposed() { 505 return gDisposed; 506} 507 508void Dbg::GoActive() { 509 // Enable all debugging features, including scans for breakpoints. 510 // This is a no-op if we're already active. 511 // Only called from the JDWP handler thread. 512 if (gDebuggerActive) { 513 return; 514 } 515 516 { 517 // TODO: dalvik only warned if there were breakpoints left over. clear in Dbg::Disconnected? 518 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_); 519 CHECK_EQ(gBreakpoints.size(), 0U); 520 } 521 522 Runtime* runtime = Runtime::Current(); 523 runtime->GetThreadList()->SuspendAll(); 524 Thread* self = Thread::Current(); 525 ThreadState old_state = self->SetStateUnsafe(kRunnable); 526 CHECK_NE(old_state, kRunnable); 527 runtime->GetInstrumentation()->AddListener(&gDebugInstrumentationListener, 528 instrumentation::Instrumentation::kMethodEntered | 529 instrumentation::Instrumentation::kMethodExited | 530 instrumentation::Instrumentation::kDexPcMoved | 531 instrumentation::Instrumentation::kExceptionCaught); 532 gDebuggerActive = true; 533 CHECK_EQ(self->SetStateUnsafe(old_state), kRunnable); 534 runtime->GetThreadList()->ResumeAll(); 535 536 LOG(INFO) << "Debugger is active"; 537} 538 539void Dbg::Disconnected() { 540 CHECK(gDebuggerConnected); 541 542 LOG(INFO) << "Debugger is no longer active"; 543 544 // Suspend all threads and exclusively acquire the mutator lock. Set the state of the thread 545 // to kRunnable to avoid scoped object access transitions. Remove the debugger as a listener 546 // and clear the object registry. 547 Runtime* runtime = Runtime::Current(); 548 runtime->GetThreadList()->SuspendAll(); 549 Thread* self = Thread::Current(); 550 ThreadState old_state = self->SetStateUnsafe(kRunnable); 551 runtime->GetInstrumentation()->RemoveListener(&gDebugInstrumentationListener, 552 instrumentation::Instrumentation::kMethodEntered | 553 instrumentation::Instrumentation::kMethodExited | 554 instrumentation::Instrumentation::kDexPcMoved | 555 instrumentation::Instrumentation::kExceptionCaught); 556 gDebuggerActive = false; 557 gRegistry->Clear(); 558 gDebuggerConnected = false; 559 CHECK_EQ(self->SetStateUnsafe(old_state), kRunnable); 560 runtime->GetThreadList()->ResumeAll(); 561} 562 563bool Dbg::IsDebuggerActive() { 564 return gDebuggerActive; 565} 566 567bool Dbg::IsJdwpConfigured() { 568 return gJdwpConfigured; 569} 570 571int64_t Dbg::LastDebuggerActivity() { 572 return gJdwpState->LastDebuggerActivity(); 573} 574 575void Dbg::UndoDebuggerSuspensions() { 576 Runtime::Current()->GetThreadList()->UndoDebuggerSuspensions(); 577} 578 579std::string Dbg::GetClassName(JDWP::RefTypeId class_id) { 580 mirror::Object* o = gRegistry->Get<mirror::Object*>(class_id); 581 if (o == NULL) { 582 return "NULL"; 583 } 584 if (o == ObjectRegistry::kInvalidObject) { 585 return StringPrintf("invalid object %p", reinterpret_cast<void*>(class_id)); 586 } 587 if (!o->IsClass()) { 588 return StringPrintf("non-class %p", o); // This is only used for debugging output anyway. 589 } 590 return DescriptorToName(ClassHelper(o->AsClass()).GetDescriptor()); 591} 592 593JDWP::JdwpError Dbg::GetClassObject(JDWP::RefTypeId id, JDWP::ObjectId& class_object_id) { 594 JDWP::JdwpError status; 595 mirror::Class* c = DecodeClass(id, status); 596 if (c == NULL) { 597 return status; 598 } 599 class_object_id = gRegistry->Add(c); 600 return JDWP::ERR_NONE; 601} 602 603JDWP::JdwpError Dbg::GetSuperclass(JDWP::RefTypeId id, JDWP::RefTypeId& superclass_id) { 604 JDWP::JdwpError status; 605 mirror::Class* c = DecodeClass(id, status); 606 if (c == NULL) { 607 return status; 608 } 609 if (c->IsInterface()) { 610 // http://code.google.com/p/android/issues/detail?id=20856 611 superclass_id = 0; 612 } else { 613 superclass_id = gRegistry->Add(c->GetSuperClass()); 614 } 615 return JDWP::ERR_NONE; 616} 617 618JDWP::JdwpError Dbg::GetClassLoader(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) { 619 mirror::Object* o = gRegistry->Get<mirror::Object*>(id); 620 if (o == NULL || o == ObjectRegistry::kInvalidObject) { 621 return JDWP::ERR_INVALID_OBJECT; 622 } 623 expandBufAddObjectId(pReply, gRegistry->Add(o->GetClass()->GetClassLoader())); 624 return JDWP::ERR_NONE; 625} 626 627JDWP::JdwpError Dbg::GetModifiers(JDWP::RefTypeId id, JDWP::ExpandBuf* pReply) { 628 JDWP::JdwpError status; 629 mirror::Class* c = DecodeClass(id, status); 630 if (c == NULL) { 631 return status; 632 } 633 634 uint32_t access_flags = c->GetAccessFlags() & kAccJavaFlagsMask; 635 636 // Set ACC_SUPER; dex files don't contain this flag, but all classes are supposed to have it set. 637 // Class.getModifiers doesn't return it, but JDWP does, so we set it here. 638 access_flags |= kAccSuper; 639 640 expandBufAdd4BE(pReply, access_flags); 641 642 return JDWP::ERR_NONE; 643} 644 645JDWP::JdwpError Dbg::GetMonitorInfo(JDWP::ObjectId object_id, JDWP::ExpandBuf* reply) 646 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 647 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id); 648 if (o == NULL || o == ObjectRegistry::kInvalidObject) { 649 return JDWP::ERR_INVALID_OBJECT; 650 } 651 652 // Ensure all threads are suspended while we read objects' lock words. 653 Thread* self = Thread::Current(); 654 Locks::mutator_lock_->SharedUnlock(self); 655 Locks::mutator_lock_->ExclusiveLock(self); 656 657 MonitorInfo monitor_info(o); 658 659 Locks::mutator_lock_->ExclusiveUnlock(self); 660 Locks::mutator_lock_->SharedLock(self); 661 662 if (monitor_info.owner_ != NULL) { 663 expandBufAddObjectId(reply, gRegistry->Add(monitor_info.owner_->GetPeer())); 664 } else { 665 expandBufAddObjectId(reply, gRegistry->Add(NULL)); 666 } 667 expandBufAdd4BE(reply, monitor_info.entry_count_); 668 expandBufAdd4BE(reply, monitor_info.waiters_.size()); 669 for (size_t i = 0; i < monitor_info.waiters_.size(); ++i) { 670 expandBufAddObjectId(reply, gRegistry->Add(monitor_info.waiters_[i]->GetPeer())); 671 } 672 return JDWP::ERR_NONE; 673} 674 675JDWP::JdwpError Dbg::GetOwnedMonitors(JDWP::ObjectId thread_id, 676 std::vector<JDWP::ObjectId>& monitors, 677 std::vector<uint32_t>& stack_depths) 678 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 679 ScopedObjectAccessUnchecked soa(Thread::Current()); 680 MutexLock mu(soa.Self(), *Locks::thread_list_lock_); 681 Thread* thread; 682 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread); 683 if (error != JDWP::ERR_NONE) { 684 return error; 685 } 686 if (!IsSuspendedForDebugger(soa, thread)) { 687 return JDWP::ERR_THREAD_NOT_SUSPENDED; 688 } 689 690 struct OwnedMonitorVisitor : public StackVisitor { 691 OwnedMonitorVisitor(Thread* thread, Context* context) 692 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) 693 : StackVisitor(thread, context), current_stack_depth(0) {} 694 695 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses 696 // annotalysis. 697 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS { 698 if (!GetMethod()->IsRuntimeMethod()) { 699 Monitor::VisitLocks(this, AppendOwnedMonitors, this); 700 ++current_stack_depth; 701 } 702 return true; 703 } 704 705 static void AppendOwnedMonitors(mirror::Object* owned_monitor, void* arg) { 706 OwnedMonitorVisitor* visitor = reinterpret_cast<OwnedMonitorVisitor*>(arg); 707 visitor->monitors.push_back(owned_monitor); 708 visitor->stack_depths.push_back(visitor->current_stack_depth); 709 } 710 711 size_t current_stack_depth; 712 std::vector<mirror::Object*> monitors; 713 std::vector<uint32_t> stack_depths; 714 }; 715 UniquePtr<Context> context(Context::Create()); 716 OwnedMonitorVisitor visitor(thread, context.get()); 717 visitor.WalkStack(); 718 719 for (size_t i = 0; i < visitor.monitors.size(); ++i) { 720 monitors.push_back(gRegistry->Add(visitor.monitors[i])); 721 stack_depths.push_back(visitor.stack_depths[i]); 722 } 723 724 return JDWP::ERR_NONE; 725} 726 727JDWP::JdwpError Dbg::GetContendedMonitor(JDWP::ObjectId thread_id, JDWP::ObjectId& contended_monitor) 728 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 729 ScopedObjectAccessUnchecked soa(Thread::Current()); 730 MutexLock mu(soa.Self(), *Locks::thread_list_lock_); 731 Thread* thread; 732 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread); 733 if (error != JDWP::ERR_NONE) { 734 return error; 735 } 736 if (!IsSuspendedForDebugger(soa, thread)) { 737 return JDWP::ERR_THREAD_NOT_SUSPENDED; 738 } 739 740 contended_monitor = gRegistry->Add(Monitor::GetContendedMonitor(thread)); 741 742 return JDWP::ERR_NONE; 743} 744 745JDWP::JdwpError Dbg::GetInstanceCounts(const std::vector<JDWP::RefTypeId>& class_ids, 746 std::vector<uint64_t>& counts) 747 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 748 std::vector<mirror::Class*> classes; 749 counts.clear(); 750 for (size_t i = 0; i < class_ids.size(); ++i) { 751 JDWP::JdwpError status; 752 mirror::Class* c = DecodeClass(class_ids[i], status); 753 if (c == NULL) { 754 return status; 755 } 756 classes.push_back(c); 757 counts.push_back(0); 758 } 759 760 Runtime::Current()->GetHeap()->CountInstances(classes, false, &counts[0]); 761 return JDWP::ERR_NONE; 762} 763 764JDWP::JdwpError Dbg::GetInstances(JDWP::RefTypeId class_id, int32_t max_count, std::vector<JDWP::ObjectId>& instances) 765 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 766 JDWP::JdwpError status; 767 mirror::Class* c = DecodeClass(class_id, status); 768 if (c == NULL) { 769 return status; 770 } 771 772 std::vector<mirror::Object*> raw_instances; 773 Runtime::Current()->GetHeap()->GetInstances(c, max_count, raw_instances); 774 for (size_t i = 0; i < raw_instances.size(); ++i) { 775 instances.push_back(gRegistry->Add(raw_instances[i])); 776 } 777 return JDWP::ERR_NONE; 778} 779 780JDWP::JdwpError Dbg::GetReferringObjects(JDWP::ObjectId object_id, int32_t max_count, 781 std::vector<JDWP::ObjectId>& referring_objects) 782 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 783 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id); 784 if (o == NULL || o == ObjectRegistry::kInvalidObject) { 785 return JDWP::ERR_INVALID_OBJECT; 786 } 787 788 std::vector<mirror::Object*> raw_instances; 789 Runtime::Current()->GetHeap()->GetReferringObjects(o, max_count, raw_instances); 790 for (size_t i = 0; i < raw_instances.size(); ++i) { 791 referring_objects.push_back(gRegistry->Add(raw_instances[i])); 792 } 793 return JDWP::ERR_NONE; 794} 795 796JDWP::JdwpError Dbg::DisableCollection(JDWP::ObjectId object_id) 797 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 798 gRegistry->DisableCollection(object_id); 799 return JDWP::ERR_NONE; 800} 801 802JDWP::JdwpError Dbg::EnableCollection(JDWP::ObjectId object_id) 803 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 804 gRegistry->EnableCollection(object_id); 805 return JDWP::ERR_NONE; 806} 807 808JDWP::JdwpError Dbg::IsCollected(JDWP::ObjectId object_id, bool& is_collected) 809 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 810 is_collected = gRegistry->IsCollected(object_id); 811 return JDWP::ERR_NONE; 812} 813 814void Dbg::DisposeObject(JDWP::ObjectId object_id, uint32_t reference_count) 815 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 816 gRegistry->DisposeObject(object_id, reference_count); 817} 818 819JDWP::JdwpError Dbg::GetReflectedType(JDWP::RefTypeId class_id, JDWP::ExpandBuf* pReply) { 820 JDWP::JdwpError status; 821 mirror::Class* c = DecodeClass(class_id, status); 822 if (c == NULL) { 823 return status; 824 } 825 826 expandBufAdd1(pReply, c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS); 827 expandBufAddRefTypeId(pReply, class_id); 828 return JDWP::ERR_NONE; 829} 830 831void Dbg::GetClassList(std::vector<JDWP::RefTypeId>& classes) { 832 // Get the complete list of reference classes (i.e. all classes except 833 // the primitive types). 834 // Returns a newly-allocated buffer full of RefTypeId values. 835 struct ClassListCreator { 836 explicit ClassListCreator(std::vector<JDWP::RefTypeId>& classes) : classes(classes) { 837 } 838 839 static bool Visit(mirror::Class* c, void* arg) { 840 return reinterpret_cast<ClassListCreator*>(arg)->Visit(c); 841 } 842 843 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses 844 // annotalysis. 845 bool Visit(mirror::Class* c) NO_THREAD_SAFETY_ANALYSIS { 846 if (!c->IsPrimitive()) { 847 classes.push_back(gRegistry->AddRefType(c)); 848 } 849 return true; 850 } 851 852 std::vector<JDWP::RefTypeId>& classes; 853 }; 854 855 ClassListCreator clc(classes); 856 Runtime::Current()->GetClassLinker()->VisitClasses(ClassListCreator::Visit, &clc); 857} 858 859JDWP::JdwpError Dbg::GetClassInfo(JDWP::RefTypeId class_id, JDWP::JdwpTypeTag* pTypeTag, uint32_t* pStatus, std::string* pDescriptor) { 860 JDWP::JdwpError status; 861 mirror::Class* c = DecodeClass(class_id, status); 862 if (c == NULL) { 863 return status; 864 } 865 866 if (c->IsArrayClass()) { 867 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED; 868 *pTypeTag = JDWP::TT_ARRAY; 869 } else { 870 if (c->IsErroneous()) { 871 *pStatus = JDWP::CS_ERROR; 872 } else { 873 *pStatus = JDWP::CS_VERIFIED | JDWP::CS_PREPARED | JDWP::CS_INITIALIZED; 874 } 875 *pTypeTag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS; 876 } 877 878 if (pDescriptor != NULL) { 879 *pDescriptor = ClassHelper(c).GetDescriptor(); 880 } 881 return JDWP::ERR_NONE; 882} 883 884void Dbg::FindLoadedClassBySignature(const char* descriptor, std::vector<JDWP::RefTypeId>& ids) { 885 std::vector<mirror::Class*> classes; 886 Runtime::Current()->GetClassLinker()->LookupClasses(descriptor, classes); 887 ids.clear(); 888 for (size_t i = 0; i < classes.size(); ++i) { 889 ids.push_back(gRegistry->Add(classes[i])); 890 } 891} 892 893JDWP::JdwpError Dbg::GetReferenceType(JDWP::ObjectId object_id, JDWP::ExpandBuf* pReply) 894 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 895 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id); 896 if (o == NULL || o == ObjectRegistry::kInvalidObject) { 897 return JDWP::ERR_INVALID_OBJECT; 898 } 899 900 JDWP::JdwpTypeTag type_tag; 901 if (o->GetClass()->IsArrayClass()) { 902 type_tag = JDWP::TT_ARRAY; 903 } else if (o->GetClass()->IsInterface()) { 904 type_tag = JDWP::TT_INTERFACE; 905 } else { 906 type_tag = JDWP::TT_CLASS; 907 } 908 JDWP::RefTypeId type_id = gRegistry->AddRefType(o->GetClass()); 909 910 expandBufAdd1(pReply, type_tag); 911 expandBufAddRefTypeId(pReply, type_id); 912 913 return JDWP::ERR_NONE; 914} 915 916JDWP::JdwpError Dbg::GetSignature(JDWP::RefTypeId class_id, std::string* signature) { 917 JDWP::JdwpError status; 918 mirror::Class* c = DecodeClass(class_id, status); 919 if (c == NULL) { 920 return status; 921 } 922 *signature = ClassHelper(c).GetDescriptor(); 923 return JDWP::ERR_NONE; 924} 925 926JDWP::JdwpError Dbg::GetSourceFile(JDWP::RefTypeId class_id, std::string& result) { 927 JDWP::JdwpError status; 928 mirror::Class* c = DecodeClass(class_id, status); 929 if (c == NULL) { 930 return status; 931 } 932 result = ClassHelper(c).GetSourceFile(); 933 return JDWP::ERR_NONE; 934} 935 936JDWP::JdwpError Dbg::GetObjectTag(JDWP::ObjectId object_id, uint8_t& tag) { 937 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id); 938 if (o == ObjectRegistry::kInvalidObject) { 939 return JDWP::ERR_INVALID_OBJECT; 940 } 941 tag = TagFromObject(o); 942 return JDWP::ERR_NONE; 943} 944 945size_t Dbg::GetTagWidth(JDWP::JdwpTag tag) { 946 switch (tag) { 947 case JDWP::JT_VOID: 948 return 0; 949 case JDWP::JT_BYTE: 950 case JDWP::JT_BOOLEAN: 951 return 1; 952 case JDWP::JT_CHAR: 953 case JDWP::JT_SHORT: 954 return 2; 955 case JDWP::JT_FLOAT: 956 case JDWP::JT_INT: 957 return 4; 958 case JDWP::JT_ARRAY: 959 case JDWP::JT_OBJECT: 960 case JDWP::JT_STRING: 961 case JDWP::JT_THREAD: 962 case JDWP::JT_THREAD_GROUP: 963 case JDWP::JT_CLASS_LOADER: 964 case JDWP::JT_CLASS_OBJECT: 965 return sizeof(JDWP::ObjectId); 966 case JDWP::JT_DOUBLE: 967 case JDWP::JT_LONG: 968 return 8; 969 default: 970 LOG(FATAL) << "Unknown tag " << tag; 971 return -1; 972 } 973} 974 975JDWP::JdwpError Dbg::GetArrayLength(JDWP::ObjectId array_id, int& length) { 976 JDWP::JdwpError status; 977 mirror::Array* a = DecodeArray(array_id, status); 978 if (a == NULL) { 979 return status; 980 } 981 length = a->GetLength(); 982 return JDWP::ERR_NONE; 983} 984 985JDWP::JdwpError Dbg::OutputArray(JDWP::ObjectId array_id, int offset, int count, JDWP::ExpandBuf* pReply) { 986 JDWP::JdwpError status; 987 mirror::Array* a = DecodeArray(array_id, status); 988 if (a == NULL) { 989 return status; 990 } 991 992 if (offset < 0 || count < 0 || offset > a->GetLength() || a->GetLength() - offset < count) { 993 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count; 994 return JDWP::ERR_INVALID_LENGTH; 995 } 996 std::string descriptor(ClassHelper(a->GetClass()).GetDescriptor()); 997 JDWP::JdwpTag tag = BasicTagFromDescriptor(descriptor.c_str() + 1); 998 999 expandBufAdd1(pReply, tag); 1000 expandBufAdd4BE(pReply, count); 1001 1002 if (IsPrimitiveTag(tag)) { 1003 size_t width = GetTagWidth(tag); 1004 uint8_t* dst = expandBufAddSpace(pReply, count * width); 1005 if (width == 8) { 1006 const uint64_t* src8 = reinterpret_cast<uint64_t*>(a->GetRawData(sizeof(uint64_t))); 1007 for (int i = 0; i < count; ++i) JDWP::Write8BE(&dst, src8[offset + i]); 1008 } else if (width == 4) { 1009 const uint32_t* src4 = reinterpret_cast<uint32_t*>(a->GetRawData(sizeof(uint32_t))); 1010 for (int i = 0; i < count; ++i) JDWP::Write4BE(&dst, src4[offset + i]); 1011 } else if (width == 2) { 1012 const uint16_t* src2 = reinterpret_cast<uint16_t*>(a->GetRawData(sizeof(uint16_t))); 1013 for (int i = 0; i < count; ++i) JDWP::Write2BE(&dst, src2[offset + i]); 1014 } else { 1015 const uint8_t* src = reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint8_t))); 1016 memcpy(dst, &src[offset * width], count * width); 1017 } 1018 } else { 1019 mirror::ObjectArray<mirror::Object>* oa = a->AsObjectArray<mirror::Object>(); 1020 for (int i = 0; i < count; ++i) { 1021 mirror::Object* element = oa->Get(offset + i); 1022 JDWP::JdwpTag specific_tag = (element != NULL) ? TagFromObject(element) : tag; 1023 expandBufAdd1(pReply, specific_tag); 1024 expandBufAddObjectId(pReply, gRegistry->Add(element)); 1025 } 1026 } 1027 1028 return JDWP::ERR_NONE; 1029} 1030 1031template <typename T> void CopyArrayData(mirror::Array* a, JDWP::Request& src, int offset, int count) { 1032 DCHECK(a->GetClass()->IsPrimitiveArray()); 1033 1034 T* dst = &(reinterpret_cast<T*>(a->GetRawData(sizeof(T)))[offset * sizeof(T)]); 1035 for (int i = 0; i < count; ++i) { 1036 *dst++ = src.ReadValue(sizeof(T)); 1037 } 1038} 1039 1040JDWP::JdwpError Dbg::SetArrayElements(JDWP::ObjectId array_id, int offset, int count, 1041 JDWP::Request& request) 1042 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 1043 JDWP::JdwpError status; 1044 mirror::Array* dst = DecodeArray(array_id, status); 1045 if (dst == NULL) { 1046 return status; 1047 } 1048 1049 if (offset < 0 || count < 0 || offset > dst->GetLength() || dst->GetLength() - offset < count) { 1050 LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count; 1051 return JDWP::ERR_INVALID_LENGTH; 1052 } 1053 const char* descriptor = ClassHelper(dst->GetClass()).GetDescriptor(); 1054 JDWP::JdwpTag tag = BasicTagFromDescriptor(descriptor + 1); 1055 1056 if (IsPrimitiveTag(tag)) { 1057 size_t width = GetTagWidth(tag); 1058 if (width == 8) { 1059 CopyArrayData<uint64_t>(dst, request, offset, count); 1060 } else if (width == 4) { 1061 CopyArrayData<uint32_t>(dst, request, offset, count); 1062 } else if (width == 2) { 1063 CopyArrayData<uint16_t>(dst, request, offset, count); 1064 } else { 1065 CopyArrayData<uint8_t>(dst, request, offset, count); 1066 } 1067 } else { 1068 mirror::ObjectArray<mirror::Object>* oa = dst->AsObjectArray<mirror::Object>(); 1069 for (int i = 0; i < count; ++i) { 1070 JDWP::ObjectId id = request.ReadObjectId(); 1071 mirror::Object* o = gRegistry->Get<mirror::Object*>(id); 1072 if (o == ObjectRegistry::kInvalidObject) { 1073 return JDWP::ERR_INVALID_OBJECT; 1074 } 1075 oa->Set(offset + i, o); 1076 } 1077 } 1078 1079 return JDWP::ERR_NONE; 1080} 1081 1082JDWP::ObjectId Dbg::CreateString(const std::string& str) { 1083 return gRegistry->Add(mirror::String::AllocFromModifiedUtf8(Thread::Current(), str.c_str())); 1084} 1085 1086JDWP::JdwpError Dbg::CreateObject(JDWP::RefTypeId class_id, JDWP::ObjectId& new_object) { 1087 JDWP::JdwpError status; 1088 mirror::Class* c = DecodeClass(class_id, status); 1089 if (c == NULL) { 1090 return status; 1091 } 1092 new_object = gRegistry->Add(c->AllocObject(Thread::Current())); 1093 return JDWP::ERR_NONE; 1094} 1095 1096/* 1097 * Used by Eclipse's "Display" view to evaluate "new byte[5]" to get "(byte[]) [0, 0, 0, 0, 0]". 1098 */ 1099JDWP::JdwpError Dbg::CreateArrayObject(JDWP::RefTypeId array_class_id, uint32_t length, 1100 JDWP::ObjectId& new_array) { 1101 JDWP::JdwpError status; 1102 mirror::Class* c = DecodeClass(array_class_id, status); 1103 if (c == NULL) { 1104 return status; 1105 } 1106 new_array = gRegistry->Add(mirror::Array::Alloc<true>(Thread::Current(), c, length)); 1107 return JDWP::ERR_NONE; 1108} 1109 1110bool Dbg::MatchType(JDWP::RefTypeId instance_class_id, JDWP::RefTypeId class_id) { 1111 JDWP::JdwpError status; 1112 mirror::Class* c1 = DecodeClass(instance_class_id, status); 1113 CHECK(c1 != NULL); 1114 mirror::Class* c2 = DecodeClass(class_id, status); 1115 CHECK(c2 != NULL); 1116 return c1->IsAssignableFrom(c2); 1117} 1118 1119static JDWP::FieldId ToFieldId(const mirror::ArtField* f) 1120 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 1121 CHECK(!kMovingFields); 1122 return static_cast<JDWP::FieldId>(reinterpret_cast<uintptr_t>(f)); 1123} 1124 1125static JDWP::MethodId ToMethodId(const mirror::ArtMethod* m) 1126 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 1127 CHECK(!kMovingMethods); 1128 return static_cast<JDWP::MethodId>(reinterpret_cast<uintptr_t>(m)); 1129} 1130 1131static mirror::ArtField* FromFieldId(JDWP::FieldId fid) 1132 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 1133 CHECK(!kMovingFields); 1134 return reinterpret_cast<mirror::ArtField*>(static_cast<uintptr_t>(fid)); 1135} 1136 1137static mirror::ArtMethod* FromMethodId(JDWP::MethodId mid) 1138 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 1139 CHECK(!kMovingMethods); 1140 return reinterpret_cast<mirror::ArtMethod*>(static_cast<uintptr_t>(mid)); 1141} 1142 1143static void SetLocation(JDWP::JdwpLocation& location, mirror::ArtMethod* m, uint32_t dex_pc) 1144 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 1145 if (m == NULL) { 1146 memset(&location, 0, sizeof(location)); 1147 } else { 1148 mirror::Class* c = m->GetDeclaringClass(); 1149 location.type_tag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS; 1150 location.class_id = gRegistry->Add(c); 1151 location.method_id = ToMethodId(m); 1152 location.dex_pc = dex_pc; 1153 } 1154} 1155 1156std::string Dbg::GetMethodName(JDWP::MethodId method_id) 1157 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 1158 mirror::ArtMethod* m = FromMethodId(method_id); 1159 return MethodHelper(m).GetName(); 1160} 1161 1162std::string Dbg::GetFieldName(JDWP::FieldId field_id) 1163 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 1164 mirror::ArtField* f = FromFieldId(field_id); 1165 return FieldHelper(f).GetName(); 1166} 1167 1168/* 1169 * Augment the access flags for synthetic methods and fields by setting 1170 * the (as described by the spec) "0xf0000000 bit". Also, strip out any 1171 * flags not specified by the Java programming language. 1172 */ 1173static uint32_t MangleAccessFlags(uint32_t accessFlags) { 1174 accessFlags &= kAccJavaFlagsMask; 1175 if ((accessFlags & kAccSynthetic) != 0) { 1176 accessFlags |= 0xf0000000; 1177 } 1178 return accessFlags; 1179} 1180 1181/* 1182 * Circularly shifts registers so that arguments come first. Debuggers 1183 * expect slots to begin with arguments, but dex code places them at 1184 * the end. 1185 */ 1186static uint16_t MangleSlot(uint16_t slot, mirror::ArtMethod* m) 1187 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 1188 const DexFile::CodeItem* code_item = MethodHelper(m).GetCodeItem(); 1189 uint16_t ins_size = code_item->ins_size_; 1190 uint16_t locals_size = code_item->registers_size_ - ins_size; 1191 if (slot >= locals_size) { 1192 return slot - locals_size; 1193 } else { 1194 return slot + ins_size; 1195 } 1196} 1197 1198/* 1199 * Circularly shifts registers so that arguments come last. Reverts 1200 * slots to dex style argument placement. 1201 */ 1202static uint16_t DemangleSlot(uint16_t slot, mirror::ArtMethod* m) 1203 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 1204 const DexFile::CodeItem* code_item = MethodHelper(m).GetCodeItem(); 1205 uint16_t ins_size = code_item->ins_size_; 1206 uint16_t locals_size = code_item->registers_size_ - ins_size; 1207 if (slot < ins_size) { 1208 return slot + locals_size; 1209 } else { 1210 return slot - ins_size; 1211 } 1212} 1213 1214JDWP::JdwpError Dbg::OutputDeclaredFields(JDWP::RefTypeId class_id, bool with_generic, JDWP::ExpandBuf* pReply) { 1215 JDWP::JdwpError status; 1216 mirror::Class* c = DecodeClass(class_id, status); 1217 if (c == NULL) { 1218 return status; 1219 } 1220 1221 size_t instance_field_count = c->NumInstanceFields(); 1222 size_t static_field_count = c->NumStaticFields(); 1223 1224 expandBufAdd4BE(pReply, instance_field_count + static_field_count); 1225 1226 for (size_t i = 0; i < instance_field_count + static_field_count; ++i) { 1227 mirror::ArtField* f = (i < instance_field_count) ? c->GetInstanceField(i) : c->GetStaticField(i - instance_field_count); 1228 FieldHelper fh(f); 1229 expandBufAddFieldId(pReply, ToFieldId(f)); 1230 expandBufAddUtf8String(pReply, fh.GetName()); 1231 expandBufAddUtf8String(pReply, fh.GetTypeDescriptor()); 1232 if (with_generic) { 1233 static const char genericSignature[1] = ""; 1234 expandBufAddUtf8String(pReply, genericSignature); 1235 } 1236 expandBufAdd4BE(pReply, MangleAccessFlags(f->GetAccessFlags())); 1237 } 1238 return JDWP::ERR_NONE; 1239} 1240 1241JDWP::JdwpError Dbg::OutputDeclaredMethods(JDWP::RefTypeId class_id, bool with_generic, 1242 JDWP::ExpandBuf* pReply) { 1243 JDWP::JdwpError status; 1244 mirror::Class* c = DecodeClass(class_id, status); 1245 if (c == NULL) { 1246 return status; 1247 } 1248 1249 size_t direct_method_count = c->NumDirectMethods(); 1250 size_t virtual_method_count = c->NumVirtualMethods(); 1251 1252 expandBufAdd4BE(pReply, direct_method_count + virtual_method_count); 1253 1254 for (size_t i = 0; i < direct_method_count + virtual_method_count; ++i) { 1255 mirror::ArtMethod* m = (i < direct_method_count) ? c->GetDirectMethod(i) : c->GetVirtualMethod(i - direct_method_count); 1256 MethodHelper mh(m); 1257 expandBufAddMethodId(pReply, ToMethodId(m)); 1258 expandBufAddUtf8String(pReply, mh.GetName()); 1259 expandBufAddUtf8String(pReply, mh.GetSignature().ToString()); 1260 if (with_generic) { 1261 static const char genericSignature[1] = ""; 1262 expandBufAddUtf8String(pReply, genericSignature); 1263 } 1264 expandBufAdd4BE(pReply, MangleAccessFlags(m->GetAccessFlags())); 1265 } 1266 return JDWP::ERR_NONE; 1267} 1268 1269JDWP::JdwpError Dbg::OutputDeclaredInterfaces(JDWP::RefTypeId class_id, JDWP::ExpandBuf* pReply) { 1270 JDWP::JdwpError status; 1271 mirror::Class* c = DecodeClass(class_id, status); 1272 if (c == NULL) { 1273 return status; 1274 } 1275 1276 ClassHelper kh(c); 1277 size_t interface_count = kh.NumDirectInterfaces(); 1278 expandBufAdd4BE(pReply, interface_count); 1279 for (size_t i = 0; i < interface_count; ++i) { 1280 expandBufAddRefTypeId(pReply, gRegistry->AddRefType(kh.GetDirectInterface(i))); 1281 } 1282 return JDWP::ERR_NONE; 1283} 1284 1285void Dbg::OutputLineTable(JDWP::RefTypeId, JDWP::MethodId method_id, JDWP::ExpandBuf* pReply) 1286 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 1287 struct DebugCallbackContext { 1288 int numItems; 1289 JDWP::ExpandBuf* pReply; 1290 1291 static bool Callback(void* context, uint32_t address, uint32_t line_number) { 1292 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context); 1293 expandBufAdd8BE(pContext->pReply, address); 1294 expandBufAdd4BE(pContext->pReply, line_number); 1295 pContext->numItems++; 1296 return false; 1297 } 1298 }; 1299 mirror::ArtMethod* m = FromMethodId(method_id); 1300 MethodHelper mh(m); 1301 uint64_t start, end; 1302 if (m->IsNative()) { 1303 start = -1; 1304 end = -1; 1305 } else { 1306 start = 0; 1307 // Return the index of the last instruction 1308 end = mh.GetCodeItem()->insns_size_in_code_units_ - 1; 1309 } 1310 1311 expandBufAdd8BE(pReply, start); 1312 expandBufAdd8BE(pReply, end); 1313 1314 // Add numLines later 1315 size_t numLinesOffset = expandBufGetLength(pReply); 1316 expandBufAdd4BE(pReply, 0); 1317 1318 DebugCallbackContext context; 1319 context.numItems = 0; 1320 context.pReply = pReply; 1321 1322 mh.GetDexFile().DecodeDebugInfo(mh.GetCodeItem(), m->IsStatic(), m->GetDexMethodIndex(), 1323 DebugCallbackContext::Callback, NULL, &context); 1324 1325 JDWP::Set4BE(expandBufGetBuffer(pReply) + numLinesOffset, context.numItems); 1326} 1327 1328void Dbg::OutputVariableTable(JDWP::RefTypeId, JDWP::MethodId method_id, bool with_generic, JDWP::ExpandBuf* pReply) { 1329 struct DebugCallbackContext { 1330 mirror::ArtMethod* method; 1331 JDWP::ExpandBuf* pReply; 1332 size_t variable_count; 1333 bool with_generic; 1334 1335 static void Callback(void* context, uint16_t slot, uint32_t startAddress, uint32_t endAddress, const char* name, const char* descriptor, const char* signature) 1336 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 1337 DebugCallbackContext* pContext = reinterpret_cast<DebugCallbackContext*>(context); 1338 1339 VLOG(jdwp) << StringPrintf(" %2zd: %d(%d) '%s' '%s' '%s' actual slot=%d mangled slot=%d", pContext->variable_count, startAddress, endAddress - startAddress, name, descriptor, signature, slot, MangleSlot(slot, pContext->method)); 1340 1341 slot = MangleSlot(slot, pContext->method); 1342 1343 expandBufAdd8BE(pContext->pReply, startAddress); 1344 expandBufAddUtf8String(pContext->pReply, name); 1345 expandBufAddUtf8String(pContext->pReply, descriptor); 1346 if (pContext->with_generic) { 1347 expandBufAddUtf8String(pContext->pReply, signature); 1348 } 1349 expandBufAdd4BE(pContext->pReply, endAddress - startAddress); 1350 expandBufAdd4BE(pContext->pReply, slot); 1351 1352 ++pContext->variable_count; 1353 } 1354 }; 1355 mirror::ArtMethod* m = FromMethodId(method_id); 1356 MethodHelper mh(m); 1357 const DexFile::CodeItem* code_item = mh.GetCodeItem(); 1358 1359 // arg_count considers doubles and longs to take 2 units. 1360 // variable_count considers everything to take 1 unit. 1361 std::string shorty(mh.GetShorty()); 1362 expandBufAdd4BE(pReply, mirror::ArtMethod::NumArgRegisters(shorty)); 1363 1364 // We don't know the total number of variables yet, so leave a blank and update it later. 1365 size_t variable_count_offset = expandBufGetLength(pReply); 1366 expandBufAdd4BE(pReply, 0); 1367 1368 DebugCallbackContext context; 1369 context.method = m; 1370 context.pReply = pReply; 1371 context.variable_count = 0; 1372 context.with_generic = with_generic; 1373 1374 mh.GetDexFile().DecodeDebugInfo(code_item, m->IsStatic(), m->GetDexMethodIndex(), NULL, 1375 DebugCallbackContext::Callback, &context); 1376 1377 JDWP::Set4BE(expandBufGetBuffer(pReply) + variable_count_offset, context.variable_count); 1378} 1379 1380void Dbg::OutputMethodReturnValue(JDWP::MethodId method_id, const JValue* return_value, 1381 JDWP::ExpandBuf* pReply) { 1382 mirror::ArtMethod* m = FromMethodId(method_id); 1383 JDWP::JdwpTag tag = BasicTagFromDescriptor(MethodHelper(m).GetShorty()); 1384 OutputJValue(tag, return_value, pReply); 1385} 1386 1387JDWP::JdwpError Dbg::GetBytecodes(JDWP::RefTypeId, JDWP::MethodId method_id, 1388 std::vector<uint8_t>& bytecodes) 1389 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 1390 mirror::ArtMethod* m = FromMethodId(method_id); 1391 if (m == NULL) { 1392 return JDWP::ERR_INVALID_METHODID; 1393 } 1394 MethodHelper mh(m); 1395 const DexFile::CodeItem* code_item = mh.GetCodeItem(); 1396 size_t byte_count = code_item->insns_size_in_code_units_ * 2; 1397 const uint8_t* begin = reinterpret_cast<const uint8_t*>(code_item->insns_); 1398 const uint8_t* end = begin + byte_count; 1399 for (const uint8_t* p = begin; p != end; ++p) { 1400 bytecodes.push_back(*p); 1401 } 1402 return JDWP::ERR_NONE; 1403} 1404 1405JDWP::JdwpTag Dbg::GetFieldBasicTag(JDWP::FieldId field_id) { 1406 return BasicTagFromDescriptor(FieldHelper(FromFieldId(field_id)).GetTypeDescriptor()); 1407} 1408 1409JDWP::JdwpTag Dbg::GetStaticFieldBasicTag(JDWP::FieldId field_id) { 1410 return BasicTagFromDescriptor(FieldHelper(FromFieldId(field_id)).GetTypeDescriptor()); 1411} 1412 1413static JDWP::JdwpError GetFieldValueImpl(JDWP::RefTypeId ref_type_id, JDWP::ObjectId object_id, 1414 JDWP::FieldId field_id, JDWP::ExpandBuf* pReply, 1415 bool is_static) 1416 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 1417 JDWP::JdwpError status; 1418 mirror::Class* c = DecodeClass(ref_type_id, status); 1419 if (ref_type_id != 0 && c == NULL) { 1420 return status; 1421 } 1422 1423 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id); 1424 if ((!is_static && o == NULL) || o == ObjectRegistry::kInvalidObject) { 1425 return JDWP::ERR_INVALID_OBJECT; 1426 } 1427 mirror::ArtField* f = FromFieldId(field_id); 1428 1429 mirror::Class* receiver_class = c; 1430 if (receiver_class == NULL && o != NULL) { 1431 receiver_class = o->GetClass(); 1432 } 1433 // TODO: should we give up now if receiver_class is NULL? 1434 if (receiver_class != NULL && !f->GetDeclaringClass()->IsAssignableFrom(receiver_class)) { 1435 LOG(INFO) << "ERR_INVALID_FIELDID: " << PrettyField(f) << " " << PrettyClass(receiver_class); 1436 return JDWP::ERR_INVALID_FIELDID; 1437 } 1438 1439 // The RI only enforces the static/non-static mismatch in one direction. 1440 // TODO: should we change the tests and check both? 1441 if (is_static) { 1442 if (!f->IsStatic()) { 1443 return JDWP::ERR_INVALID_FIELDID; 1444 } 1445 } else { 1446 if (f->IsStatic()) { 1447 LOG(WARNING) << "Ignoring non-NULL receiver for ObjectReference.SetValues on static field " << PrettyField(f); 1448 } 1449 } 1450 if (f->IsStatic()) { 1451 o = f->GetDeclaringClass(); 1452 } 1453 1454 JDWP::JdwpTag tag = BasicTagFromDescriptor(FieldHelper(f).GetTypeDescriptor()); 1455 JValue field_value; 1456 if (tag == JDWP::JT_VOID) { 1457 LOG(FATAL) << "Unknown tag: " << tag; 1458 } else if (!IsPrimitiveTag(tag)) { 1459 field_value.SetL(f->GetObject(o)); 1460 } else if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) { 1461 field_value.SetJ(f->Get64(o)); 1462 } else { 1463 field_value.SetI(f->Get32(o)); 1464 } 1465 Dbg::OutputJValue(tag, &field_value, pReply); 1466 1467 return JDWP::ERR_NONE; 1468} 1469 1470JDWP::JdwpError Dbg::GetFieldValue(JDWP::ObjectId object_id, JDWP::FieldId field_id, 1471 JDWP::ExpandBuf* pReply) { 1472 return GetFieldValueImpl(0, object_id, field_id, pReply, false); 1473} 1474 1475JDWP::JdwpError Dbg::GetStaticFieldValue(JDWP::RefTypeId ref_type_id, JDWP::FieldId field_id, JDWP::ExpandBuf* pReply) { 1476 return GetFieldValueImpl(ref_type_id, 0, field_id, pReply, true); 1477} 1478 1479static JDWP::JdwpError SetFieldValueImpl(JDWP::ObjectId object_id, JDWP::FieldId field_id, 1480 uint64_t value, int width, bool is_static) 1481 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 1482 mirror::Object* o = gRegistry->Get<mirror::Object*>(object_id); 1483 if ((!is_static && o == NULL) || o == ObjectRegistry::kInvalidObject) { 1484 return JDWP::ERR_INVALID_OBJECT; 1485 } 1486 mirror::ArtField* f = FromFieldId(field_id); 1487 1488 // The RI only enforces the static/non-static mismatch in one direction. 1489 // TODO: should we change the tests and check both? 1490 if (is_static) { 1491 if (!f->IsStatic()) { 1492 return JDWP::ERR_INVALID_FIELDID; 1493 } 1494 } else { 1495 if (f->IsStatic()) { 1496 LOG(WARNING) << "Ignoring non-NULL receiver for ObjectReference.SetValues on static field " << PrettyField(f); 1497 } 1498 } 1499 if (f->IsStatic()) { 1500 o = f->GetDeclaringClass(); 1501 } 1502 1503 JDWP::JdwpTag tag = BasicTagFromDescriptor(FieldHelper(f).GetTypeDescriptor()); 1504 1505 if (IsPrimitiveTag(tag)) { 1506 if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) { 1507 CHECK_EQ(width, 8); 1508 f->Set64(o, value); 1509 } else { 1510 CHECK_LE(width, 4); 1511 f->Set32(o, value); 1512 } 1513 } else { 1514 mirror::Object* v = gRegistry->Get<mirror::Object*>(value); 1515 if (v == ObjectRegistry::kInvalidObject) { 1516 return JDWP::ERR_INVALID_OBJECT; 1517 } 1518 if (v != NULL) { 1519 mirror::Class* field_type = FieldHelper(f).GetType(); 1520 if (!field_type->IsAssignableFrom(v->GetClass())) { 1521 return JDWP::ERR_INVALID_OBJECT; 1522 } 1523 } 1524 f->SetObject(o, v); 1525 } 1526 1527 return JDWP::ERR_NONE; 1528} 1529 1530JDWP::JdwpError Dbg::SetFieldValue(JDWP::ObjectId object_id, JDWP::FieldId field_id, uint64_t value, 1531 int width) { 1532 return SetFieldValueImpl(object_id, field_id, value, width, false); 1533} 1534 1535JDWP::JdwpError Dbg::SetStaticFieldValue(JDWP::FieldId field_id, uint64_t value, int width) { 1536 return SetFieldValueImpl(0, field_id, value, width, true); 1537} 1538 1539std::string Dbg::StringToUtf8(JDWP::ObjectId string_id) { 1540 mirror::String* s = gRegistry->Get<mirror::String*>(string_id); 1541 return s->ToModifiedUtf8(); 1542} 1543 1544void Dbg::OutputJValue(JDWP::JdwpTag tag, const JValue* return_value, JDWP::ExpandBuf* pReply) { 1545 if (IsPrimitiveTag(tag)) { 1546 expandBufAdd1(pReply, tag); 1547 if (tag == JDWP::JT_BOOLEAN || tag == JDWP::JT_BYTE) { 1548 expandBufAdd1(pReply, return_value->GetI()); 1549 } else if (tag == JDWP::JT_CHAR || tag == JDWP::JT_SHORT) { 1550 expandBufAdd2BE(pReply, return_value->GetI()); 1551 } else if (tag == JDWP::JT_FLOAT || tag == JDWP::JT_INT) { 1552 expandBufAdd4BE(pReply, return_value->GetI()); 1553 } else if (tag == JDWP::JT_DOUBLE || tag == JDWP::JT_LONG) { 1554 expandBufAdd8BE(pReply, return_value->GetJ()); 1555 } else { 1556 CHECK_EQ(tag, JDWP::JT_VOID); 1557 } 1558 } else { 1559 mirror::Object* value = return_value->GetL(); 1560 expandBufAdd1(pReply, TagFromObject(value)); 1561 expandBufAddObjectId(pReply, gRegistry->Add(value)); 1562 } 1563} 1564 1565JDWP::JdwpError Dbg::GetThreadName(JDWP::ObjectId thread_id, std::string& name) { 1566 ScopedObjectAccessUnchecked soa(Thread::Current()); 1567 MutexLock mu(soa.Self(), *Locks::thread_list_lock_); 1568 Thread* thread; 1569 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread); 1570 if (error != JDWP::ERR_NONE && error != JDWP::ERR_THREAD_NOT_ALIVE) { 1571 return error; 1572 } 1573 1574 // We still need to report the zombie threads' names, so we can't just call Thread::GetThreadName. 1575 mirror::Object* thread_object = gRegistry->Get<mirror::Object*>(thread_id); 1576 mirror::ArtField* java_lang_Thread_name_field = 1577 soa.DecodeField(WellKnownClasses::java_lang_Thread_name); 1578 mirror::String* s = 1579 reinterpret_cast<mirror::String*>(java_lang_Thread_name_field->GetObject(thread_object)); 1580 if (s != NULL) { 1581 name = s->ToModifiedUtf8(); 1582 } 1583 return JDWP::ERR_NONE; 1584} 1585 1586JDWP::JdwpError Dbg::GetThreadGroup(JDWP::ObjectId thread_id, JDWP::ExpandBuf* pReply) { 1587 ScopedObjectAccess soa(Thread::Current()); 1588 mirror::Object* thread_object = gRegistry->Get<mirror::Object*>(thread_id); 1589 if (thread_object == ObjectRegistry::kInvalidObject) { 1590 return JDWP::ERR_INVALID_OBJECT; 1591 } 1592 1593 // Okay, so it's an object, but is it actually a thread? 1594 MutexLock mu(soa.Self(), *Locks::thread_list_lock_); 1595 Thread* thread; 1596 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread); 1597 if (error == JDWP::ERR_THREAD_NOT_ALIVE) { 1598 // Zombie threads are in the null group. 1599 expandBufAddObjectId(pReply, JDWP::ObjectId(0)); 1600 return JDWP::ERR_NONE; 1601 } 1602 if (error != JDWP::ERR_NONE) { 1603 return error; 1604 } 1605 1606 mirror::Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/Thread;"); 1607 CHECK(c != NULL); 1608 mirror::ArtField* f = c->FindInstanceField("group", "Ljava/lang/ThreadGroup;"); 1609 CHECK(f != NULL); 1610 mirror::Object* group = f->GetObject(thread_object); 1611 CHECK(group != NULL); 1612 JDWP::ObjectId thread_group_id = gRegistry->Add(group); 1613 1614 expandBufAddObjectId(pReply, thread_group_id); 1615 return JDWP::ERR_NONE; 1616} 1617 1618std::string Dbg::GetThreadGroupName(JDWP::ObjectId thread_group_id) { 1619 ScopedObjectAccess soa(Thread::Current()); 1620 mirror::Object* thread_group = gRegistry->Get<mirror::Object*>(thread_group_id); 1621 CHECK(thread_group != NULL); 1622 1623 mirror::Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/ThreadGroup;"); 1624 CHECK(c != NULL); 1625 mirror::ArtField* f = c->FindInstanceField("name", "Ljava/lang/String;"); 1626 CHECK(f != NULL); 1627 mirror::String* s = reinterpret_cast<mirror::String*>(f->GetObject(thread_group)); 1628 return s->ToModifiedUtf8(); 1629} 1630 1631JDWP::ObjectId Dbg::GetThreadGroupParent(JDWP::ObjectId thread_group_id) { 1632 mirror::Object* thread_group = gRegistry->Get<mirror::Object*>(thread_group_id); 1633 CHECK(thread_group != NULL); 1634 1635 mirror::Class* c = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/ThreadGroup;"); 1636 CHECK(c != NULL); 1637 mirror::ArtField* f = c->FindInstanceField("parent", "Ljava/lang/ThreadGroup;"); 1638 CHECK(f != NULL); 1639 mirror::Object* parent = f->GetObject(thread_group); 1640 return gRegistry->Add(parent); 1641} 1642 1643JDWP::ObjectId Dbg::GetSystemThreadGroupId() { 1644 ScopedObjectAccessUnchecked soa(Thread::Current()); 1645 mirror::ArtField* f = soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_systemThreadGroup); 1646 mirror::Object* group = f->GetObject(f->GetDeclaringClass()); 1647 return gRegistry->Add(group); 1648} 1649 1650JDWP::ObjectId Dbg::GetMainThreadGroupId() { 1651 ScopedObjectAccess soa(Thread::Current()); 1652 mirror::ArtField* f = soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_mainThreadGroup); 1653 mirror::Object* group = f->GetObject(f->GetDeclaringClass()); 1654 return gRegistry->Add(group); 1655} 1656 1657JDWP::JdwpThreadStatus Dbg::ToJdwpThreadStatus(ThreadState state) { 1658 switch (state) { 1659 case kBlocked: 1660 return JDWP::TS_MONITOR; 1661 case kNative: 1662 case kRunnable: 1663 case kSuspended: 1664 return JDWP::TS_RUNNING; 1665 case kSleeping: 1666 return JDWP::TS_SLEEPING; 1667 case kStarting: 1668 case kTerminated: 1669 return JDWP::TS_ZOMBIE; 1670 case kTimedWaiting: 1671 case kWaitingForDebuggerSend: 1672 case kWaitingForDebuggerSuspension: 1673 case kWaitingForDebuggerToAttach: 1674 case kWaitingForGcToComplete: 1675 case kWaitingForCheckPointsToRun: 1676 case kWaitingForJniOnLoad: 1677 case kWaitingForSignalCatcherOutput: 1678 case kWaitingInMainDebuggerLoop: 1679 case kWaitingInMainSignalCatcherLoop: 1680 case kWaitingPerformingGc: 1681 case kWaiting: 1682 return JDWP::TS_WAIT; 1683 // Don't add a 'default' here so the compiler can spot incompatible enum changes. 1684 } 1685 LOG(FATAL) << "Unknown thread state: " << state; 1686 return JDWP::TS_ZOMBIE; 1687} 1688 1689JDWP::JdwpError Dbg::GetThreadStatus(JDWP::ObjectId thread_id, JDWP::JdwpThreadStatus* pThreadStatus, JDWP::JdwpSuspendStatus* pSuspendStatus) { 1690 ScopedObjectAccess soa(Thread::Current()); 1691 1692 *pSuspendStatus = JDWP::SUSPEND_STATUS_NOT_SUSPENDED; 1693 1694 MutexLock mu(soa.Self(), *Locks::thread_list_lock_); 1695 Thread* thread; 1696 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread); 1697 if (error != JDWP::ERR_NONE) { 1698 if (error == JDWP::ERR_THREAD_NOT_ALIVE) { 1699 *pThreadStatus = JDWP::TS_ZOMBIE; 1700 return JDWP::ERR_NONE; 1701 } 1702 return error; 1703 } 1704 1705 if (IsSuspendedForDebugger(soa, thread)) { 1706 *pSuspendStatus = JDWP::SUSPEND_STATUS_SUSPENDED; 1707 } 1708 1709 *pThreadStatus = ToJdwpThreadStatus(thread->GetState()); 1710 return JDWP::ERR_NONE; 1711} 1712 1713JDWP::JdwpError Dbg::GetThreadDebugSuspendCount(JDWP::ObjectId thread_id, JDWP::ExpandBuf* pReply) { 1714 ScopedObjectAccess soa(Thread::Current()); 1715 MutexLock mu(soa.Self(), *Locks::thread_list_lock_); 1716 Thread* thread; 1717 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread); 1718 if (error != JDWP::ERR_NONE) { 1719 return error; 1720 } 1721 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_); 1722 expandBufAdd4BE(pReply, thread->GetDebugSuspendCount()); 1723 return JDWP::ERR_NONE; 1724} 1725 1726JDWP::JdwpError Dbg::Interrupt(JDWP::ObjectId thread_id) { 1727 ScopedObjectAccess soa(Thread::Current()); 1728 MutexLock mu(soa.Self(), *Locks::thread_list_lock_); 1729 Thread* thread; 1730 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread); 1731 if (error != JDWP::ERR_NONE) { 1732 return error; 1733 } 1734 thread->Interrupt(); 1735 return JDWP::ERR_NONE; 1736} 1737 1738void Dbg::GetThreads(JDWP::ObjectId thread_group_id, std::vector<JDWP::ObjectId>& thread_ids) { 1739 class ThreadListVisitor { 1740 public: 1741 ThreadListVisitor(const ScopedObjectAccessUnchecked& soa, mirror::Object* desired_thread_group, 1742 std::vector<JDWP::ObjectId>& thread_ids) 1743 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) 1744 : soa_(soa), desired_thread_group_(desired_thread_group), thread_ids_(thread_ids) {} 1745 1746 static void Visit(Thread* t, void* arg) { 1747 reinterpret_cast<ThreadListVisitor*>(arg)->Visit(t); 1748 } 1749 1750 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses 1751 // annotalysis. 1752 void Visit(Thread* t) NO_THREAD_SAFETY_ANALYSIS { 1753 if (t == Dbg::GetDebugThread()) { 1754 // Skip the JDWP thread. Some debuggers get bent out of shape when they can't suspend and 1755 // query all threads, so it's easier if we just don't tell them about this thread. 1756 return; 1757 } 1758 mirror::Object* peer = t->GetPeer(); 1759 if (IsInDesiredThreadGroup(peer)) { 1760 thread_ids_.push_back(gRegistry->Add(peer)); 1761 } 1762 } 1763 1764 private: 1765 bool IsInDesiredThreadGroup(mirror::Object* peer) 1766 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 1767 // peer might be NULL if the thread is still starting up. 1768 if (peer == NULL) { 1769 // We can't tell the debugger about this thread yet. 1770 // TODO: if we identified threads to the debugger by their Thread* 1771 // rather than their peer's mirror::Object*, we could fix this. 1772 // Doing so might help us report ZOMBIE threads too. 1773 return false; 1774 } 1775 // Do we want threads from all thread groups? 1776 if (desired_thread_group_ == NULL) { 1777 return true; 1778 } 1779 mirror::Object* group = soa_.DecodeField(WellKnownClasses::java_lang_Thread_group)->GetObject(peer); 1780 return (group == desired_thread_group_); 1781 } 1782 1783 const ScopedObjectAccessUnchecked& soa_; 1784 mirror::Object* const desired_thread_group_; 1785 std::vector<JDWP::ObjectId>& thread_ids_; 1786 }; 1787 1788 ScopedObjectAccessUnchecked soa(Thread::Current()); 1789 mirror::Object* thread_group = gRegistry->Get<mirror::Object*>(thread_group_id); 1790 ThreadListVisitor tlv(soa, thread_group, thread_ids); 1791 MutexLock mu(soa.Self(), *Locks::thread_list_lock_); 1792 Runtime::Current()->GetThreadList()->ForEach(ThreadListVisitor::Visit, &tlv); 1793} 1794 1795void Dbg::GetChildThreadGroups(JDWP::ObjectId thread_group_id, std::vector<JDWP::ObjectId>& child_thread_group_ids) { 1796 ScopedObjectAccess soa(Thread::Current()); 1797 mirror::Object* thread_group = gRegistry->Get<mirror::Object*>(thread_group_id); 1798 1799 // Get the ArrayList<ThreadGroup> "groups" out of this thread group... 1800 mirror::ArtField* groups_field = thread_group->GetClass()->FindInstanceField("groups", "Ljava/util/List;"); 1801 mirror::Object* groups_array_list = groups_field->GetObject(thread_group); 1802 1803 // Get the array and size out of the ArrayList<ThreadGroup>... 1804 mirror::ArtField* array_field = groups_array_list->GetClass()->FindInstanceField("array", "[Ljava/lang/Object;"); 1805 mirror::ArtField* size_field = groups_array_list->GetClass()->FindInstanceField("size", "I"); 1806 mirror::ObjectArray<mirror::Object>* groups_array = 1807 array_field->GetObject(groups_array_list)->AsObjectArray<mirror::Object>(); 1808 const int32_t size = size_field->GetInt(groups_array_list); 1809 1810 // Copy the first 'size' elements out of the array into the result. 1811 for (int32_t i = 0; i < size; ++i) { 1812 child_thread_group_ids.push_back(gRegistry->Add(groups_array->Get(i))); 1813 } 1814} 1815 1816static int GetStackDepth(Thread* thread) 1817 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 1818 struct CountStackDepthVisitor : public StackVisitor { 1819 explicit CountStackDepthVisitor(Thread* thread) 1820 : StackVisitor(thread, NULL), depth(0) {} 1821 1822 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses 1823 // annotalysis. 1824 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS { 1825 if (!GetMethod()->IsRuntimeMethod()) { 1826 ++depth; 1827 } 1828 return true; 1829 } 1830 size_t depth; 1831 }; 1832 1833 CountStackDepthVisitor visitor(thread); 1834 visitor.WalkStack(); 1835 return visitor.depth; 1836} 1837 1838JDWP::JdwpError Dbg::GetThreadFrameCount(JDWP::ObjectId thread_id, size_t& result) { 1839 ScopedObjectAccess soa(Thread::Current()); 1840 MutexLock mu(soa.Self(), *Locks::thread_list_lock_); 1841 Thread* thread; 1842 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread); 1843 if (error != JDWP::ERR_NONE) { 1844 return error; 1845 } 1846 if (!IsSuspendedForDebugger(soa, thread)) { 1847 return JDWP::ERR_THREAD_NOT_SUSPENDED; 1848 } 1849 result = GetStackDepth(thread); 1850 return JDWP::ERR_NONE; 1851} 1852 1853JDWP::JdwpError Dbg::GetThreadFrames(JDWP::ObjectId thread_id, size_t start_frame, 1854 size_t frame_count, JDWP::ExpandBuf* buf) { 1855 class GetFrameVisitor : public StackVisitor { 1856 public: 1857 GetFrameVisitor(Thread* thread, size_t start_frame, size_t frame_count, JDWP::ExpandBuf* buf) 1858 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) 1859 : StackVisitor(thread, NULL), depth_(0), 1860 start_frame_(start_frame), frame_count_(frame_count), buf_(buf) { 1861 expandBufAdd4BE(buf_, frame_count_); 1862 } 1863 1864 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses 1865 // annotalysis. 1866 virtual bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS { 1867 if (GetMethod()->IsRuntimeMethod()) { 1868 return true; // The debugger can't do anything useful with a frame that has no Method*. 1869 } 1870 if (depth_ >= start_frame_ + frame_count_) { 1871 return false; 1872 } 1873 if (depth_ >= start_frame_) { 1874 JDWP::FrameId frame_id(GetFrameId()); 1875 JDWP::JdwpLocation location; 1876 SetLocation(location, GetMethod(), GetDexPc()); 1877 VLOG(jdwp) << StringPrintf(" Frame %3zd: id=%3lld ", depth_, frame_id) << location; 1878 expandBufAdd8BE(buf_, frame_id); 1879 expandBufAddLocation(buf_, location); 1880 } 1881 ++depth_; 1882 return true; 1883 } 1884 1885 private: 1886 size_t depth_; 1887 const size_t start_frame_; 1888 const size_t frame_count_; 1889 JDWP::ExpandBuf* buf_; 1890 }; 1891 1892 ScopedObjectAccessUnchecked soa(Thread::Current()); 1893 MutexLock mu(soa.Self(), *Locks::thread_list_lock_); 1894 Thread* thread; 1895 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread); 1896 if (error != JDWP::ERR_NONE) { 1897 return error; 1898 } 1899 if (!IsSuspendedForDebugger(soa, thread)) { 1900 return JDWP::ERR_THREAD_NOT_SUSPENDED; 1901 } 1902 GetFrameVisitor visitor(thread, start_frame, frame_count, buf); 1903 visitor.WalkStack(); 1904 return JDWP::ERR_NONE; 1905} 1906 1907JDWP::ObjectId Dbg::GetThreadSelfId() { 1908 ScopedObjectAccessUnchecked soa(Thread::Current()); 1909 return gRegistry->Add(soa.Self()->GetPeer()); 1910} 1911 1912void Dbg::SuspendVM() { 1913 Runtime::Current()->GetThreadList()->SuspendAllForDebugger(); 1914} 1915 1916void Dbg::ResumeVM() { 1917 Runtime::Current()->GetThreadList()->UndoDebuggerSuspensions(); 1918} 1919 1920JDWP::JdwpError Dbg::SuspendThread(JDWP::ObjectId thread_id, bool request_suspension) { 1921 ScopedLocalRef<jobject> peer(Thread::Current()->GetJniEnv(), NULL); 1922 { 1923 ScopedObjectAccess soa(Thread::Current()); 1924 peer.reset(soa.AddLocalReference<jobject>(gRegistry->Get<mirror::Object*>(thread_id))); 1925 } 1926 if (peer.get() == NULL) { 1927 return JDWP::ERR_THREAD_NOT_ALIVE; 1928 } 1929 // Suspend thread to build stack trace. 1930 bool timed_out; 1931 Thread* thread = ThreadList::SuspendThreadByPeer(peer.get(), request_suspension, true, 1932 &timed_out); 1933 if (thread != NULL) { 1934 return JDWP::ERR_NONE; 1935 } else if (timed_out) { 1936 return JDWP::ERR_INTERNAL; 1937 } else { 1938 return JDWP::ERR_THREAD_NOT_ALIVE; 1939 } 1940} 1941 1942void Dbg::ResumeThread(JDWP::ObjectId thread_id) { 1943 ScopedObjectAccessUnchecked soa(Thread::Current()); 1944 mirror::Object* peer = gRegistry->Get<mirror::Object*>(thread_id); 1945 Thread* thread; 1946 { 1947 MutexLock mu(soa.Self(), *Locks::thread_list_lock_); 1948 thread = Thread::FromManagedThread(soa, peer); 1949 } 1950 if (thread == NULL) { 1951 LOG(WARNING) << "No such thread for resume: " << peer; 1952 return; 1953 } 1954 bool needs_resume; 1955 { 1956 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_); 1957 needs_resume = thread->GetSuspendCount() > 0; 1958 } 1959 if (needs_resume) { 1960 Runtime::Current()->GetThreadList()->Resume(thread, true); 1961 } 1962} 1963 1964void Dbg::SuspendSelf() { 1965 Runtime::Current()->GetThreadList()->SuspendSelfForDebugger(); 1966} 1967 1968struct GetThisVisitor : public StackVisitor { 1969 GetThisVisitor(Thread* thread, Context* context, JDWP::FrameId frame_id) 1970 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) 1971 : StackVisitor(thread, context), this_object(NULL), frame_id(frame_id) {} 1972 1973 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses 1974 // annotalysis. 1975 virtual bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS { 1976 if (frame_id != GetFrameId()) { 1977 return true; // continue 1978 } else { 1979 this_object = GetThisObject(); 1980 return false; 1981 } 1982 } 1983 1984 mirror::Object* this_object; 1985 JDWP::FrameId frame_id; 1986}; 1987 1988JDWP::JdwpError Dbg::GetThisObject(JDWP::ObjectId thread_id, JDWP::FrameId frame_id, 1989 JDWP::ObjectId* result) { 1990 ScopedObjectAccessUnchecked soa(Thread::Current()); 1991 Thread* thread; 1992 { 1993 MutexLock mu(soa.Self(), *Locks::thread_list_lock_); 1994 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread); 1995 if (error != JDWP::ERR_NONE) { 1996 return error; 1997 } 1998 if (!IsSuspendedForDebugger(soa, thread)) { 1999 return JDWP::ERR_THREAD_NOT_SUSPENDED; 2000 } 2001 } 2002 UniquePtr<Context> context(Context::Create()); 2003 GetThisVisitor visitor(thread, context.get(), frame_id); 2004 visitor.WalkStack(); 2005 *result = gRegistry->Add(visitor.this_object); 2006 return JDWP::ERR_NONE; 2007} 2008 2009void Dbg::GetLocalValue(JDWP::ObjectId thread_id, JDWP::FrameId frame_id, int slot, JDWP::JdwpTag tag, 2010 uint8_t* buf, size_t width) { 2011 struct GetLocalVisitor : public StackVisitor { 2012 GetLocalVisitor(Thread* thread, Context* context, JDWP::FrameId frame_id, int slot, 2013 JDWP::JdwpTag tag, uint8_t* buf, size_t width) 2014 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) 2015 : StackVisitor(thread, context), frame_id_(frame_id), slot_(slot), tag_(tag), 2016 buf_(buf), width_(width) {} 2017 2018 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses 2019 // annotalysis. 2020 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS { 2021 if (GetFrameId() != frame_id_) { 2022 return true; // Not our frame, carry on. 2023 } 2024 // TODO: check that the tag is compatible with the actual type of the slot! 2025 mirror::ArtMethod* m = GetMethod(); 2026 uint16_t reg = DemangleSlot(slot_, m); 2027 2028 switch (tag_) { 2029 case JDWP::JT_BOOLEAN: 2030 { 2031 CHECK_EQ(width_, 1U); 2032 uint32_t intVal = GetVReg(m, reg, kIntVReg); 2033 VLOG(jdwp) << "get boolean local " << reg << " = " << intVal; 2034 JDWP::Set1(buf_+1, intVal != 0); 2035 } 2036 break; 2037 case JDWP::JT_BYTE: 2038 { 2039 CHECK_EQ(width_, 1U); 2040 uint32_t intVal = GetVReg(m, reg, kIntVReg); 2041 VLOG(jdwp) << "get byte local " << reg << " = " << intVal; 2042 JDWP::Set1(buf_+1, intVal); 2043 } 2044 break; 2045 case JDWP::JT_SHORT: 2046 case JDWP::JT_CHAR: 2047 { 2048 CHECK_EQ(width_, 2U); 2049 uint32_t intVal = GetVReg(m, reg, kIntVReg); 2050 VLOG(jdwp) << "get short/char local " << reg << " = " << intVal; 2051 JDWP::Set2BE(buf_+1, intVal); 2052 } 2053 break; 2054 case JDWP::JT_INT: 2055 { 2056 CHECK_EQ(width_, 4U); 2057 uint32_t intVal = GetVReg(m, reg, kIntVReg); 2058 VLOG(jdwp) << "get int local " << reg << " = " << intVal; 2059 JDWP::Set4BE(buf_+1, intVal); 2060 } 2061 break; 2062 case JDWP::JT_FLOAT: 2063 { 2064 CHECK_EQ(width_, 4U); 2065 uint32_t intVal = GetVReg(m, reg, kFloatVReg); 2066 VLOG(jdwp) << "get int/float local " << reg << " = " << intVal; 2067 JDWP::Set4BE(buf_+1, intVal); 2068 } 2069 break; 2070 case JDWP::JT_ARRAY: 2071 { 2072 CHECK_EQ(width_, sizeof(JDWP::ObjectId)); 2073 mirror::Object* o = reinterpret_cast<mirror::Object*>(GetVReg(m, reg, kReferenceVReg)); 2074 VLOG(jdwp) << "get array local " << reg << " = " << o; 2075 if (!Runtime::Current()->GetHeap()->IsValidObjectAddress(o)) { 2076 LOG(FATAL) << "Register " << reg << " expected to hold array: " << o; 2077 } 2078 JDWP::SetObjectId(buf_+1, gRegistry->Add(o)); 2079 } 2080 break; 2081 case JDWP::JT_CLASS_LOADER: 2082 case JDWP::JT_CLASS_OBJECT: 2083 case JDWP::JT_OBJECT: 2084 case JDWP::JT_STRING: 2085 case JDWP::JT_THREAD: 2086 case JDWP::JT_THREAD_GROUP: 2087 { 2088 CHECK_EQ(width_, sizeof(JDWP::ObjectId)); 2089 mirror::Object* o = reinterpret_cast<mirror::Object*>(GetVReg(m, reg, kReferenceVReg)); 2090 VLOG(jdwp) << "get object local " << reg << " = " << o; 2091 if (!Runtime::Current()->GetHeap()->IsValidObjectAddress(o)) { 2092 LOG(FATAL) << "Register " << reg << " expected to hold object: " << o; 2093 } 2094 tag_ = TagFromObject(o); 2095 JDWP::SetObjectId(buf_+1, gRegistry->Add(o)); 2096 } 2097 break; 2098 case JDWP::JT_DOUBLE: 2099 { 2100 CHECK_EQ(width_, 8U); 2101 uint32_t lo = GetVReg(m, reg, kDoubleLoVReg); 2102 uint64_t hi = GetVReg(m, reg + 1, kDoubleHiVReg); 2103 uint64_t longVal = (hi << 32) | lo; 2104 VLOG(jdwp) << "get double/long local " << hi << ":" << lo << " = " << longVal; 2105 JDWP::Set8BE(buf_+1, longVal); 2106 } 2107 break; 2108 case JDWP::JT_LONG: 2109 { 2110 CHECK_EQ(width_, 8U); 2111 uint32_t lo = GetVReg(m, reg, kLongLoVReg); 2112 uint64_t hi = GetVReg(m, reg + 1, kLongHiVReg); 2113 uint64_t longVal = (hi << 32) | lo; 2114 VLOG(jdwp) << "get double/long local " << hi << ":" << lo << " = " << longVal; 2115 JDWP::Set8BE(buf_+1, longVal); 2116 } 2117 break; 2118 default: 2119 LOG(FATAL) << "Unknown tag " << tag_; 2120 break; 2121 } 2122 2123 // Prepend tag, which may have been updated. 2124 JDWP::Set1(buf_, tag_); 2125 return false; 2126 } 2127 2128 const JDWP::FrameId frame_id_; 2129 const int slot_; 2130 JDWP::JdwpTag tag_; 2131 uint8_t* const buf_; 2132 const size_t width_; 2133 }; 2134 2135 ScopedObjectAccessUnchecked soa(Thread::Current()); 2136 MutexLock mu(soa.Self(), *Locks::thread_list_lock_); 2137 Thread* thread; 2138 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread); 2139 if (error != JDWP::ERR_NONE) { 2140 return; 2141 } 2142 UniquePtr<Context> context(Context::Create()); 2143 GetLocalVisitor visitor(thread, context.get(), frame_id, slot, tag, buf, width); 2144 visitor.WalkStack(); 2145} 2146 2147void Dbg::SetLocalValue(JDWP::ObjectId thread_id, JDWP::FrameId frame_id, int slot, JDWP::JdwpTag tag, 2148 uint64_t value, size_t width) { 2149 struct SetLocalVisitor : public StackVisitor { 2150 SetLocalVisitor(Thread* thread, Context* context, 2151 JDWP::FrameId frame_id, int slot, JDWP::JdwpTag tag, uint64_t value, 2152 size_t width) 2153 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) 2154 : StackVisitor(thread, context), 2155 frame_id_(frame_id), slot_(slot), tag_(tag), value_(value), width_(width) {} 2156 2157 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses 2158 // annotalysis. 2159 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS { 2160 if (GetFrameId() != frame_id_) { 2161 return true; // Not our frame, carry on. 2162 } 2163 // TODO: check that the tag is compatible with the actual type of the slot! 2164 mirror::ArtMethod* m = GetMethod(); 2165 uint16_t reg = DemangleSlot(slot_, m); 2166 2167 switch (tag_) { 2168 case JDWP::JT_BOOLEAN: 2169 case JDWP::JT_BYTE: 2170 CHECK_EQ(width_, 1U); 2171 SetVReg(m, reg, static_cast<uint32_t>(value_), kIntVReg); 2172 break; 2173 case JDWP::JT_SHORT: 2174 case JDWP::JT_CHAR: 2175 CHECK_EQ(width_, 2U); 2176 SetVReg(m, reg, static_cast<uint32_t>(value_), kIntVReg); 2177 break; 2178 case JDWP::JT_INT: 2179 CHECK_EQ(width_, 4U); 2180 SetVReg(m, reg, static_cast<uint32_t>(value_), kIntVReg); 2181 break; 2182 case JDWP::JT_FLOAT: 2183 CHECK_EQ(width_, 4U); 2184 SetVReg(m, reg, static_cast<uint32_t>(value_), kFloatVReg); 2185 break; 2186 case JDWP::JT_ARRAY: 2187 case JDWP::JT_OBJECT: 2188 case JDWP::JT_STRING: 2189 { 2190 CHECK_EQ(width_, sizeof(JDWP::ObjectId)); 2191 mirror::Object* o = gRegistry->Get<mirror::Object*>(static_cast<JDWP::ObjectId>(value_)); 2192 if (o == ObjectRegistry::kInvalidObject) { 2193 UNIMPLEMENTED(FATAL) << "return an error code when given an invalid object to store"; 2194 } 2195 SetVReg(m, reg, static_cast<uint32_t>(reinterpret_cast<uintptr_t>(o)), kReferenceVReg); 2196 } 2197 break; 2198 case JDWP::JT_DOUBLE: 2199 CHECK_EQ(width_, 8U); 2200 SetVReg(m, reg, static_cast<uint32_t>(value_), kDoubleLoVReg); 2201 SetVReg(m, reg + 1, static_cast<uint32_t>(value_ >> 32), kDoubleHiVReg); 2202 break; 2203 case JDWP::JT_LONG: 2204 CHECK_EQ(width_, 8U); 2205 SetVReg(m, reg, static_cast<uint32_t>(value_), kLongLoVReg); 2206 SetVReg(m, reg + 1, static_cast<uint32_t>(value_ >> 32), kLongHiVReg); 2207 break; 2208 default: 2209 LOG(FATAL) << "Unknown tag " << tag_; 2210 break; 2211 } 2212 return false; 2213 } 2214 2215 const JDWP::FrameId frame_id_; 2216 const int slot_; 2217 const JDWP::JdwpTag tag_; 2218 const uint64_t value_; 2219 const size_t width_; 2220 }; 2221 2222 ScopedObjectAccessUnchecked soa(Thread::Current()); 2223 MutexLock mu(soa.Self(), *Locks::thread_list_lock_); 2224 Thread* thread; 2225 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread); 2226 if (error != JDWP::ERR_NONE) { 2227 return; 2228 } 2229 UniquePtr<Context> context(Context::Create()); 2230 SetLocalVisitor visitor(thread, context.get(), frame_id, slot, tag, value, width); 2231 visitor.WalkStack(); 2232} 2233 2234void Dbg::PostLocationEvent(const mirror::ArtMethod* m, int dex_pc, mirror::Object* this_object, 2235 int event_flags, const JValue* return_value) { 2236 mirror::Class* c = m->GetDeclaringClass(); 2237 2238 JDWP::JdwpLocation location; 2239 location.type_tag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS; 2240 location.class_id = gRegistry->AddRefType(c); 2241 location.method_id = ToMethodId(m); 2242 location.dex_pc = m->IsNative() ? -1 : dex_pc; 2243 2244 // If 'this_object' isn't already in the registry, we know that we're not looking for it, 2245 // so there's no point adding it to the registry and burning through ids. 2246 JDWP::ObjectId this_id = 0; 2247 if (gRegistry->Contains(this_object)) { 2248 this_id = gRegistry->Add(this_object); 2249 } 2250 gJdwpState->PostLocationEvent(&location, this_id, event_flags, return_value); 2251} 2252 2253void Dbg::PostException(Thread* thread, const ThrowLocation& throw_location, 2254 mirror::ArtMethod* catch_method, 2255 uint32_t catch_dex_pc, mirror::Throwable* exception_object) { 2256 if (!IsDebuggerActive()) { 2257 return; 2258 } 2259 2260 JDWP::JdwpLocation jdwp_throw_location; 2261 SetLocation(jdwp_throw_location, throw_location.GetMethod(), throw_location.GetDexPc()); 2262 JDWP::JdwpLocation catch_location; 2263 SetLocation(catch_location, catch_method, catch_dex_pc); 2264 2265 // We need 'this' for InstanceOnly filters. 2266 JDWP::ObjectId this_id = gRegistry->Add(throw_location.GetThis()); 2267 JDWP::ObjectId exception_id = gRegistry->Add(exception_object); 2268 JDWP::RefTypeId exception_class_id = gRegistry->AddRefType(exception_object->GetClass()); 2269 2270 gJdwpState->PostException(&jdwp_throw_location, exception_id, exception_class_id, &catch_location, 2271 this_id); 2272} 2273 2274void Dbg::PostClassPrepare(mirror::Class* c) { 2275 if (!IsDebuggerActive()) { 2276 return; 2277 } 2278 2279 // OLD-TODO - we currently always send both "verified" and "prepared" since 2280 // debuggers seem to like that. There might be some advantage to honesty, 2281 // since the class may not yet be verified. 2282 int state = JDWP::CS_VERIFIED | JDWP::CS_PREPARED; 2283 JDWP::JdwpTypeTag tag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS; 2284 gJdwpState->PostClassPrepare(tag, gRegistry->Add(c), 2285 ClassHelper(c).GetDescriptor(), state); 2286} 2287 2288void Dbg::UpdateDebugger(Thread* thread, mirror::Object* this_object, 2289 const mirror::ArtMethod* m, uint32_t dex_pc) { 2290 if (!IsDebuggerActive() || dex_pc == static_cast<uint32_t>(-2) /* fake method exit */) { 2291 return; 2292 } 2293 2294 int event_flags = 0; 2295 2296 if (IsBreakpoint(m, dex_pc)) { 2297 event_flags |= kBreakpoint; 2298 } 2299 2300 // If the debugger is single-stepping one of our threads, check to 2301 // see if we're that thread and we've reached a step point. 2302 const SingleStepControl* single_step_control = thread->GetSingleStepControl(); 2303 DCHECK(single_step_control != nullptr); 2304 if (single_step_control->is_active) { 2305 CHECK(!m->IsNative()); 2306 if (single_step_control->step_depth == JDWP::SD_INTO) { 2307 // Step into method calls. We break when the line number 2308 // or method pointer changes. If we're in SS_MIN mode, we 2309 // always stop. 2310 if (single_step_control->method != m) { 2311 event_flags |= kSingleStep; 2312 VLOG(jdwp) << "SS new method"; 2313 } else if (single_step_control->step_size == JDWP::SS_MIN) { 2314 event_flags |= kSingleStep; 2315 VLOG(jdwp) << "SS new instruction"; 2316 } else if (single_step_control->dex_pcs.find(dex_pc) == single_step_control->dex_pcs.end()) { 2317 event_flags |= kSingleStep; 2318 VLOG(jdwp) << "SS new line"; 2319 } 2320 } else if (single_step_control->step_depth == JDWP::SD_OVER) { 2321 // Step over method calls. We break when the line number is 2322 // different and the frame depth is <= the original frame 2323 // depth. (We can't just compare on the method, because we 2324 // might get unrolled past it by an exception, and it's tricky 2325 // to identify recursion.) 2326 2327 int stack_depth = GetStackDepth(thread); 2328 2329 if (stack_depth < single_step_control->stack_depth) { 2330 // Popped up one or more frames, always trigger. 2331 event_flags |= kSingleStep; 2332 VLOG(jdwp) << "SS method pop"; 2333 } else if (stack_depth == single_step_control->stack_depth) { 2334 // Same depth, see if we moved. 2335 if (single_step_control->step_size == JDWP::SS_MIN) { 2336 event_flags |= kSingleStep; 2337 VLOG(jdwp) << "SS new instruction"; 2338 } else if (single_step_control->dex_pcs.find(dex_pc) == single_step_control->dex_pcs.end()) { 2339 event_flags |= kSingleStep; 2340 VLOG(jdwp) << "SS new line"; 2341 } 2342 } 2343 } else { 2344 CHECK_EQ(single_step_control->step_depth, JDWP::SD_OUT); 2345 // Return from the current method. We break when the frame 2346 // depth pops up. 2347 2348 // This differs from the "method exit" break in that it stops 2349 // with the PC at the next instruction in the returned-to 2350 // function, rather than the end of the returning function. 2351 2352 int stack_depth = GetStackDepth(thread); 2353 if (stack_depth < single_step_control->stack_depth) { 2354 event_flags |= kSingleStep; 2355 VLOG(jdwp) << "SS method pop"; 2356 } 2357 } 2358 } 2359 2360 // If there's something interesting going on, see if it matches one 2361 // of the debugger filters. 2362 if (event_flags != 0) { 2363 Dbg::PostLocationEvent(m, dex_pc, this_object, event_flags, nullptr); 2364 } 2365} 2366 2367void Dbg::WatchLocation(const JDWP::JdwpLocation* location) { 2368 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_); 2369 mirror::ArtMethod* m = FromMethodId(location->method_id); 2370 gBreakpoints.push_back(Breakpoint(m, location->dex_pc)); 2371 VLOG(jdwp) << "Set breakpoint #" << (gBreakpoints.size() - 1) << ": " << gBreakpoints[gBreakpoints.size() - 1]; 2372} 2373 2374void Dbg::UnwatchLocation(const JDWP::JdwpLocation* location) { 2375 MutexLock mu(Thread::Current(), *Locks::breakpoint_lock_); 2376 mirror::ArtMethod* m = FromMethodId(location->method_id); 2377 for (size_t i = 0; i < gBreakpoints.size(); ++i) { 2378 if (gBreakpoints[i].method == m && gBreakpoints[i].dex_pc == location->dex_pc) { 2379 VLOG(jdwp) << "Removed breakpoint #" << i << ": " << gBreakpoints[i]; 2380 gBreakpoints.erase(gBreakpoints.begin() + i); 2381 return; 2382 } 2383 } 2384} 2385 2386// Scoped utility class to suspend a thread so that we may do tasks such as walk its stack. Doesn't 2387// cause suspension if the thread is the current thread. 2388class ScopedThreadSuspension { 2389 public: 2390 ScopedThreadSuspension(Thread* self, JDWP::ObjectId thread_id) 2391 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) : 2392 thread_(NULL), 2393 error_(JDWP::ERR_NONE), 2394 self_suspend_(false), 2395 other_suspend_(false) { 2396 ScopedObjectAccessUnchecked soa(self); 2397 { 2398 MutexLock mu(soa.Self(), *Locks::thread_list_lock_); 2399 error_ = DecodeThread(soa, thread_id, thread_); 2400 } 2401 if (error_ == JDWP::ERR_NONE) { 2402 if (thread_ == soa.Self()) { 2403 self_suspend_ = true; 2404 } else { 2405 soa.Self()->TransitionFromRunnableToSuspended(kWaitingForDebuggerSuspension); 2406 jobject thread_peer = gRegistry->GetJObject(thread_id); 2407 bool timed_out; 2408 Thread* suspended_thread = ThreadList::SuspendThreadByPeer(thread_peer, true, true, 2409 &timed_out); 2410 CHECK_EQ(soa.Self()->TransitionFromSuspendedToRunnable(), kWaitingForDebuggerSuspension); 2411 if (suspended_thread == NULL) { 2412 // Thread terminated from under us while suspending. 2413 error_ = JDWP::ERR_INVALID_THREAD; 2414 } else { 2415 CHECK_EQ(suspended_thread, thread_); 2416 other_suspend_ = true; 2417 } 2418 } 2419 } 2420 } 2421 2422 Thread* GetThread() const { 2423 return thread_; 2424 } 2425 2426 JDWP::JdwpError GetError() const { 2427 return error_; 2428 } 2429 2430 ~ScopedThreadSuspension() { 2431 if (other_suspend_) { 2432 Runtime::Current()->GetThreadList()->Resume(thread_, true); 2433 } 2434 } 2435 2436 private: 2437 Thread* thread_; 2438 JDWP::JdwpError error_; 2439 bool self_suspend_; 2440 bool other_suspend_; 2441}; 2442 2443JDWP::JdwpError Dbg::ConfigureStep(JDWP::ObjectId thread_id, JDWP::JdwpStepSize step_size, 2444 JDWP::JdwpStepDepth step_depth) { 2445 Thread* self = Thread::Current(); 2446 ScopedThreadSuspension sts(self, thread_id); 2447 if (sts.GetError() != JDWP::ERR_NONE) { 2448 return sts.GetError(); 2449 } 2450 2451 // 2452 // Work out what Method* we're in, the current line number, and how deep the stack currently 2453 // is for step-out. 2454 // 2455 2456 struct SingleStepStackVisitor : public StackVisitor { 2457 explicit SingleStepStackVisitor(Thread* thread, SingleStepControl* single_step_control, 2458 int32_t* line_number) 2459 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) 2460 : StackVisitor(thread, NULL), single_step_control_(single_step_control), 2461 line_number_(line_number) { 2462 DCHECK_EQ(single_step_control_, thread->GetSingleStepControl()); 2463 single_step_control_->method = NULL; 2464 single_step_control_->stack_depth = 0; 2465 } 2466 2467 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses 2468 // annotalysis. 2469 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS { 2470 mirror::ArtMethod* m = GetMethod(); 2471 if (!m->IsRuntimeMethod()) { 2472 ++single_step_control_->stack_depth; 2473 if (single_step_control_->method == NULL) { 2474 const mirror::DexCache* dex_cache = m->GetDeclaringClass()->GetDexCache(); 2475 single_step_control_->method = m; 2476 *line_number_ = -1; 2477 if (dex_cache != NULL) { 2478 const DexFile& dex_file = *dex_cache->GetDexFile(); 2479 *line_number_ = dex_file.GetLineNumFromPC(m, GetDexPc()); 2480 } 2481 } 2482 } 2483 return true; 2484 } 2485 2486 SingleStepControl* const single_step_control_; 2487 int32_t* const line_number_; 2488 }; 2489 2490 Thread* const thread = sts.GetThread(); 2491 SingleStepControl* const single_step_control = thread->GetSingleStepControl(); 2492 DCHECK(single_step_control != nullptr); 2493 int32_t line_number = -1; 2494 SingleStepStackVisitor visitor(thread, single_step_control, &line_number); 2495 visitor.WalkStack(); 2496 2497 // 2498 // Find the dex_pc values that correspond to the current line, for line-based single-stepping. 2499 // 2500 2501 struct DebugCallbackContext { 2502 explicit DebugCallbackContext(SingleStepControl* single_step_control, int32_t line_number) 2503 : single_step_control_(single_step_control), line_number_(line_number), 2504 last_pc_valid(false), last_pc(0) { 2505 } 2506 2507 static bool Callback(void* raw_context, uint32_t address, uint32_t line_number) { 2508 DebugCallbackContext* context = reinterpret_cast<DebugCallbackContext*>(raw_context); 2509 if (static_cast<int32_t>(line_number) == context->line_number_) { 2510 if (!context->last_pc_valid) { 2511 // Everything from this address until the next line change is ours. 2512 context->last_pc = address; 2513 context->last_pc_valid = true; 2514 } 2515 // Otherwise, if we're already in a valid range for this line, 2516 // just keep going (shouldn't really happen)... 2517 } else if (context->last_pc_valid) { // and the line number is new 2518 // Add everything from the last entry up until here to the set 2519 for (uint32_t dex_pc = context->last_pc; dex_pc < address; ++dex_pc) { 2520 context->single_step_control_->dex_pcs.insert(dex_pc); 2521 } 2522 context->last_pc_valid = false; 2523 } 2524 return false; // There may be multiple entries for any given line. 2525 } 2526 2527 ~DebugCallbackContext() { 2528 // If the line number was the last in the position table... 2529 if (last_pc_valid) { 2530 size_t end = MethodHelper(single_step_control_->method).GetCodeItem()->insns_size_in_code_units_; 2531 for (uint32_t dex_pc = last_pc; dex_pc < end; ++dex_pc) { 2532 single_step_control_->dex_pcs.insert(dex_pc); 2533 } 2534 } 2535 } 2536 2537 SingleStepControl* const single_step_control_; 2538 const int32_t line_number_; 2539 bool last_pc_valid; 2540 uint32_t last_pc; 2541 }; 2542 single_step_control->dex_pcs.clear(); 2543 const mirror::ArtMethod* m = single_step_control->method; 2544 if (!m->IsNative()) { 2545 DebugCallbackContext context(single_step_control, line_number); 2546 MethodHelper mh(m); 2547 mh.GetDexFile().DecodeDebugInfo(mh.GetCodeItem(), m->IsStatic(), m->GetDexMethodIndex(), 2548 DebugCallbackContext::Callback, NULL, &context); 2549 } 2550 2551 // 2552 // Everything else... 2553 // 2554 2555 single_step_control->step_size = step_size; 2556 single_step_control->step_depth = step_depth; 2557 single_step_control->is_active = true; 2558 2559 if (VLOG_IS_ON(jdwp)) { 2560 VLOG(jdwp) << "Single-step thread: " << *thread; 2561 VLOG(jdwp) << "Single-step step size: " << single_step_control->step_size; 2562 VLOG(jdwp) << "Single-step step depth: " << single_step_control->step_depth; 2563 VLOG(jdwp) << "Single-step current method: " << PrettyMethod(single_step_control->method); 2564 VLOG(jdwp) << "Single-step current line: " << line_number; 2565 VLOG(jdwp) << "Single-step current stack depth: " << single_step_control->stack_depth; 2566 VLOG(jdwp) << "Single-step dex_pc values:"; 2567 for (std::set<uint32_t>::iterator it = single_step_control->dex_pcs.begin(); it != single_step_control->dex_pcs.end(); ++it) { 2568 VLOG(jdwp) << StringPrintf(" %#x", *it); 2569 } 2570 } 2571 2572 return JDWP::ERR_NONE; 2573} 2574 2575void Dbg::UnconfigureStep(JDWP::ObjectId thread_id) { 2576 ScopedObjectAccessUnchecked soa(Thread::Current()); 2577 MutexLock mu(soa.Self(), *Locks::thread_list_lock_); 2578 Thread* thread; 2579 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread); 2580 if (error == JDWP::ERR_NONE) { 2581 SingleStepControl* single_step_control = thread->GetSingleStepControl(); 2582 DCHECK(single_step_control != nullptr); 2583 single_step_control->is_active = false; 2584 single_step_control->dex_pcs.clear(); 2585 } 2586} 2587 2588static char JdwpTagToShortyChar(JDWP::JdwpTag tag) { 2589 switch (tag) { 2590 default: 2591 LOG(FATAL) << "unknown JDWP tag: " << PrintableChar(tag); 2592 2593 // Primitives. 2594 case JDWP::JT_BYTE: return 'B'; 2595 case JDWP::JT_CHAR: return 'C'; 2596 case JDWP::JT_FLOAT: return 'F'; 2597 case JDWP::JT_DOUBLE: return 'D'; 2598 case JDWP::JT_INT: return 'I'; 2599 case JDWP::JT_LONG: return 'J'; 2600 case JDWP::JT_SHORT: return 'S'; 2601 case JDWP::JT_VOID: return 'V'; 2602 case JDWP::JT_BOOLEAN: return 'Z'; 2603 2604 // Reference types. 2605 case JDWP::JT_ARRAY: 2606 case JDWP::JT_OBJECT: 2607 case JDWP::JT_STRING: 2608 case JDWP::JT_THREAD: 2609 case JDWP::JT_THREAD_GROUP: 2610 case JDWP::JT_CLASS_LOADER: 2611 case JDWP::JT_CLASS_OBJECT: 2612 return 'L'; 2613 } 2614} 2615 2616JDWP::JdwpError Dbg::InvokeMethod(JDWP::ObjectId thread_id, JDWP::ObjectId object_id, 2617 JDWP::RefTypeId class_id, JDWP::MethodId method_id, 2618 uint32_t arg_count, uint64_t* arg_values, 2619 JDWP::JdwpTag* arg_types, uint32_t options, 2620 JDWP::JdwpTag* pResultTag, uint64_t* pResultValue, 2621 JDWP::ObjectId* pExceptionId) { 2622 ThreadList* thread_list = Runtime::Current()->GetThreadList(); 2623 2624 Thread* targetThread = NULL; 2625 DebugInvokeReq* req = NULL; 2626 Thread* self = Thread::Current(); 2627 { 2628 ScopedObjectAccessUnchecked soa(self); 2629 MutexLock mu(soa.Self(), *Locks::thread_list_lock_); 2630 JDWP::JdwpError error = DecodeThread(soa, thread_id, targetThread); 2631 if (error != JDWP::ERR_NONE) { 2632 LOG(ERROR) << "InvokeMethod request for invalid thread id " << thread_id; 2633 return error; 2634 } 2635 req = targetThread->GetInvokeReq(); 2636 if (!req->ready) { 2637 LOG(ERROR) << "InvokeMethod request for thread not stopped by event: " << *targetThread; 2638 return JDWP::ERR_INVALID_THREAD; 2639 } 2640 2641 /* 2642 * We currently have a bug where we don't successfully resume the 2643 * target thread if the suspend count is too deep. We're expected to 2644 * require one "resume" for each "suspend", but when asked to execute 2645 * a method we have to resume fully and then re-suspend it back to the 2646 * same level. (The easiest way to cause this is to type "suspend" 2647 * multiple times in jdb.) 2648 * 2649 * It's unclear what this means when the event specifies "resume all" 2650 * and some threads are suspended more deeply than others. This is 2651 * a rare problem, so for now we just prevent it from hanging forever 2652 * by rejecting the method invocation request. Without this, we will 2653 * be stuck waiting on a suspended thread. 2654 */ 2655 int suspend_count; 2656 { 2657 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_); 2658 suspend_count = targetThread->GetSuspendCount(); 2659 } 2660 if (suspend_count > 1) { 2661 LOG(ERROR) << *targetThread << " suspend count too deep for method invocation: " << suspend_count; 2662 return JDWP::ERR_THREAD_SUSPENDED; // Probably not expected here. 2663 } 2664 2665 JDWP::JdwpError status; 2666 mirror::Object* receiver = gRegistry->Get<mirror::Object*>(object_id); 2667 if (receiver == ObjectRegistry::kInvalidObject) { 2668 return JDWP::ERR_INVALID_OBJECT; 2669 } 2670 2671 mirror::Object* thread = gRegistry->Get<mirror::Object*>(thread_id); 2672 if (thread == ObjectRegistry::kInvalidObject) { 2673 return JDWP::ERR_INVALID_OBJECT; 2674 } 2675 // TODO: check that 'thread' is actually a java.lang.Thread! 2676 2677 mirror::Class* c = DecodeClass(class_id, status); 2678 if (c == NULL) { 2679 return status; 2680 } 2681 2682 mirror::ArtMethod* m = FromMethodId(method_id); 2683 if (m->IsStatic() != (receiver == NULL)) { 2684 return JDWP::ERR_INVALID_METHODID; 2685 } 2686 if (m->IsStatic()) { 2687 if (m->GetDeclaringClass() != c) { 2688 return JDWP::ERR_INVALID_METHODID; 2689 } 2690 } else { 2691 if (!m->GetDeclaringClass()->IsAssignableFrom(c)) { 2692 return JDWP::ERR_INVALID_METHODID; 2693 } 2694 } 2695 2696 // Check the argument list matches the method. 2697 MethodHelper mh(m); 2698 if (mh.GetShortyLength() - 1 != arg_count) { 2699 return JDWP::ERR_ILLEGAL_ARGUMENT; 2700 } 2701 const char* shorty = mh.GetShorty(); 2702 const DexFile::TypeList* types = mh.GetParameterTypeList(); 2703 for (size_t i = 0; i < arg_count; ++i) { 2704 if (shorty[i + 1] != JdwpTagToShortyChar(arg_types[i])) { 2705 return JDWP::ERR_ILLEGAL_ARGUMENT; 2706 } 2707 2708 if (shorty[i + 1] == 'L') { 2709 // Did we really get an argument of an appropriate reference type? 2710 mirror::Class* parameter_type = mh.GetClassFromTypeIdx(types->GetTypeItem(i).type_idx_); 2711 mirror::Object* argument = gRegistry->Get<mirror::Object*>(arg_values[i]); 2712 if (argument == ObjectRegistry::kInvalidObject) { 2713 return JDWP::ERR_INVALID_OBJECT; 2714 } 2715 if (!argument->InstanceOf(parameter_type)) { 2716 return JDWP::ERR_ILLEGAL_ARGUMENT; 2717 } 2718 2719 // Turn the on-the-wire ObjectId into a jobject. 2720 jvalue& v = reinterpret_cast<jvalue&>(arg_values[i]); 2721 v.l = gRegistry->GetJObject(arg_values[i]); 2722 } 2723 } 2724 2725 req->receiver = receiver; 2726 req->thread = thread; 2727 req->klass = c; 2728 req->method = m; 2729 req->arg_count = arg_count; 2730 req->arg_values = arg_values; 2731 req->options = options; 2732 req->invoke_needed = true; 2733 } 2734 2735 // The fact that we've released the thread list lock is a bit risky --- if the thread goes 2736 // away we're sitting high and dry -- but we must release this before the ResumeAllThreads 2737 // call, and it's unwise to hold it during WaitForSuspend. 2738 2739 { 2740 /* 2741 * We change our (JDWP thread) status, which should be THREAD_RUNNING, 2742 * so we can suspend for a GC if the invoke request causes us to 2743 * run out of memory. It's also a good idea to change it before locking 2744 * the invokeReq mutex, although that should never be held for long. 2745 */ 2746 self->TransitionFromRunnableToSuspended(kWaitingForDebuggerSend); 2747 2748 VLOG(jdwp) << " Transferring control to event thread"; 2749 { 2750 MutexLock mu(self, req->lock); 2751 2752 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) { 2753 VLOG(jdwp) << " Resuming all threads"; 2754 thread_list->UndoDebuggerSuspensions(); 2755 } else { 2756 VLOG(jdwp) << " Resuming event thread only"; 2757 thread_list->Resume(targetThread, true); 2758 } 2759 2760 // Wait for the request to finish executing. 2761 while (req->invoke_needed) { 2762 req->cond.Wait(self); 2763 } 2764 } 2765 VLOG(jdwp) << " Control has returned from event thread"; 2766 2767 /* wait for thread to re-suspend itself */ 2768 SuspendThread(thread_id, false /* request_suspension */); 2769 self->TransitionFromSuspendedToRunnable(); 2770 } 2771 2772 /* 2773 * Suspend the threads. We waited for the target thread to suspend 2774 * itself, so all we need to do is suspend the others. 2775 * 2776 * The suspendAllThreads() call will double-suspend the event thread, 2777 * so we want to resume the target thread once to keep the books straight. 2778 */ 2779 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) { 2780 self->TransitionFromRunnableToSuspended(kWaitingForDebuggerSuspension); 2781 VLOG(jdwp) << " Suspending all threads"; 2782 thread_list->SuspendAllForDebugger(); 2783 self->TransitionFromSuspendedToRunnable(); 2784 VLOG(jdwp) << " Resuming event thread to balance the count"; 2785 thread_list->Resume(targetThread, true); 2786 } 2787 2788 // Copy the result. 2789 *pResultTag = req->result_tag; 2790 if (IsPrimitiveTag(req->result_tag)) { 2791 *pResultValue = req->result_value.GetJ(); 2792 } else { 2793 *pResultValue = gRegistry->Add(req->result_value.GetL()); 2794 } 2795 *pExceptionId = req->exception; 2796 return req->error; 2797} 2798 2799void Dbg::ExecuteMethod(DebugInvokeReq* pReq) { 2800 ScopedObjectAccess soa(Thread::Current()); 2801 2802 // We can be called while an exception is pending. We need 2803 // to preserve that across the method invocation. 2804 SirtRef<mirror::Object> old_throw_this_object(soa.Self(), NULL); 2805 SirtRef<mirror::ArtMethod> old_throw_method(soa.Self(), NULL); 2806 SirtRef<mirror::Throwable> old_exception(soa.Self(), NULL); 2807 uint32_t old_throw_dex_pc; 2808 { 2809 ThrowLocation old_throw_location; 2810 mirror::Throwable* old_exception_obj = soa.Self()->GetException(&old_throw_location); 2811 old_throw_this_object.reset(old_throw_location.GetThis()); 2812 old_throw_method.reset(old_throw_location.GetMethod()); 2813 old_exception.reset(old_exception_obj); 2814 old_throw_dex_pc = old_throw_location.GetDexPc(); 2815 soa.Self()->ClearException(); 2816 } 2817 2818 // Translate the method through the vtable, unless the debugger wants to suppress it. 2819 mirror::ArtMethod* m = pReq->method; 2820 if ((pReq->options & JDWP::INVOKE_NONVIRTUAL) == 0 && pReq->receiver != NULL) { 2821 mirror::ArtMethod* actual_method = pReq->klass->FindVirtualMethodForVirtualOrInterface(pReq->method); 2822 if (actual_method != m) { 2823 VLOG(jdwp) << "ExecuteMethod translated " << PrettyMethod(m) << " to " << PrettyMethod(actual_method); 2824 m = actual_method; 2825 } 2826 } 2827 VLOG(jdwp) << "ExecuteMethod " << PrettyMethod(m) 2828 << " receiver=" << pReq->receiver 2829 << " arg_count=" << pReq->arg_count; 2830 CHECK(m != NULL); 2831 2832 CHECK_EQ(sizeof(jvalue), sizeof(uint64_t)); 2833 2834 MethodHelper mh(m); 2835 ArgArray arg_array(mh.GetShorty(), mh.GetShortyLength()); 2836 arg_array.BuildArgArray(soa, pReq->receiver, reinterpret_cast<jvalue*>(pReq->arg_values)); 2837 InvokeWithArgArray(soa, m, &arg_array, &pReq->result_value, mh.GetShorty()[0]); 2838 2839 mirror::Throwable* exception = soa.Self()->GetException(NULL); 2840 soa.Self()->ClearException(); 2841 pReq->exception = gRegistry->Add(exception); 2842 pReq->result_tag = BasicTagFromDescriptor(MethodHelper(m).GetShorty()); 2843 if (pReq->exception != 0) { 2844 VLOG(jdwp) << " JDWP invocation returning with exception=" << exception 2845 << " " << exception->Dump(); 2846 pReq->result_value.SetJ(0); 2847 } else if (pReq->result_tag == JDWP::JT_OBJECT) { 2848 /* if no exception thrown, examine object result more closely */ 2849 JDWP::JdwpTag new_tag = TagFromObject(pReq->result_value.GetL()); 2850 if (new_tag != pReq->result_tag) { 2851 VLOG(jdwp) << " JDWP promoted result from " << pReq->result_tag << " to " << new_tag; 2852 pReq->result_tag = new_tag; 2853 } 2854 2855 /* 2856 * Register the object. We don't actually need an ObjectId yet, 2857 * but we do need to be sure that the GC won't move or discard the 2858 * object when we switch out of RUNNING. The ObjectId conversion 2859 * will add the object to the "do not touch" list. 2860 * 2861 * We can't use the "tracked allocation" mechanism here because 2862 * the object is going to be handed off to a different thread. 2863 */ 2864 gRegistry->Add(pReq->result_value.GetL()); 2865 } 2866 2867 if (old_exception.get() != NULL) { 2868 ThrowLocation gc_safe_throw_location(old_throw_this_object.get(), old_throw_method.get(), 2869 old_throw_dex_pc); 2870 soa.Self()->SetException(gc_safe_throw_location, old_exception.get()); 2871 } 2872} 2873 2874/* 2875 * "request" contains a full JDWP packet, possibly with multiple chunks. We 2876 * need to process each, accumulate the replies, and ship the whole thing 2877 * back. 2878 * 2879 * Returns "true" if we have a reply. The reply buffer is newly allocated, 2880 * and includes the chunk type/length, followed by the data. 2881 * 2882 * OLD-TODO: we currently assume that the request and reply include a single 2883 * chunk. If this becomes inconvenient we will need to adapt. 2884 */ 2885bool Dbg::DdmHandlePacket(JDWP::Request& request, uint8_t** pReplyBuf, int* pReplyLen) { 2886 Thread* self = Thread::Current(); 2887 JNIEnv* env = self->GetJniEnv(); 2888 2889 uint32_t type = request.ReadUnsigned32("type"); 2890 uint32_t length = request.ReadUnsigned32("length"); 2891 2892 // Create a byte[] corresponding to 'request'. 2893 size_t request_length = request.size(); 2894 ScopedLocalRef<jbyteArray> dataArray(env, env->NewByteArray(request_length)); 2895 if (dataArray.get() == NULL) { 2896 LOG(WARNING) << "byte[] allocation failed: " << request_length; 2897 env->ExceptionClear(); 2898 return false; 2899 } 2900 env->SetByteArrayRegion(dataArray.get(), 0, request_length, reinterpret_cast<const jbyte*>(request.data())); 2901 request.Skip(request_length); 2902 2903 // Run through and find all chunks. [Currently just find the first.] 2904 ScopedByteArrayRO contents(env, dataArray.get()); 2905 if (length != request_length) { 2906 LOG(WARNING) << StringPrintf("bad chunk found (len=%u pktLen=%d)", length, request_length); 2907 return false; 2908 } 2909 2910 // Call "private static Chunk dispatch(int type, byte[] data, int offset, int length)". 2911 ScopedLocalRef<jobject> chunk(env, env->CallStaticObjectMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer, 2912 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_dispatch, 2913 type, dataArray.get(), 0, length)); 2914 if (env->ExceptionCheck()) { 2915 LOG(INFO) << StringPrintf("Exception thrown by dispatcher for 0x%08x", type); 2916 env->ExceptionDescribe(); 2917 env->ExceptionClear(); 2918 return false; 2919 } 2920 2921 if (chunk.get() == NULL) { 2922 return false; 2923 } 2924 2925 /* 2926 * Pull the pieces out of the chunk. We copy the results into a 2927 * newly-allocated buffer that the caller can free. We don't want to 2928 * continue using the Chunk object because nothing has a reference to it. 2929 * 2930 * We could avoid this by returning type/data/offset/length and having 2931 * the caller be aware of the object lifetime issues, but that 2932 * integrates the JDWP code more tightly into the rest of the runtime, and doesn't work 2933 * if we have responses for multiple chunks. 2934 * 2935 * So we're pretty much stuck with copying data around multiple times. 2936 */ 2937 ScopedLocalRef<jbyteArray> replyData(env, reinterpret_cast<jbyteArray>(env->GetObjectField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_data))); 2938 jint offset = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_offset); 2939 length = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_length); 2940 type = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_type); 2941 2942 VLOG(jdwp) << StringPrintf("DDM reply: type=0x%08x data=%p offset=%d length=%d", type, replyData.get(), offset, length); 2943 if (length == 0 || replyData.get() == NULL) { 2944 return false; 2945 } 2946 2947 const int kChunkHdrLen = 8; 2948 uint8_t* reply = new uint8_t[length + kChunkHdrLen]; 2949 if (reply == NULL) { 2950 LOG(WARNING) << "malloc failed: " << (length + kChunkHdrLen); 2951 return false; 2952 } 2953 JDWP::Set4BE(reply + 0, type); 2954 JDWP::Set4BE(reply + 4, length); 2955 env->GetByteArrayRegion(replyData.get(), offset, length, reinterpret_cast<jbyte*>(reply + kChunkHdrLen)); 2956 2957 *pReplyBuf = reply; 2958 *pReplyLen = length + kChunkHdrLen; 2959 2960 VLOG(jdwp) << StringPrintf("dvmHandleDdm returning type=%.4s %p len=%d", reinterpret_cast<char*>(reply), reply, length); 2961 return true; 2962} 2963 2964void Dbg::DdmBroadcast(bool connect) { 2965 VLOG(jdwp) << "Broadcasting DDM " << (connect ? "connect" : "disconnect") << "..."; 2966 2967 Thread* self = Thread::Current(); 2968 if (self->GetState() != kRunnable) { 2969 LOG(ERROR) << "DDM broadcast in thread state " << self->GetState(); 2970 /* try anyway? */ 2971 } 2972 2973 JNIEnv* env = self->GetJniEnv(); 2974 jint event = connect ? 1 /*DdmServer.CONNECTED*/ : 2 /*DdmServer.DISCONNECTED*/; 2975 env->CallStaticVoidMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer, 2976 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_broadcast, 2977 event); 2978 if (env->ExceptionCheck()) { 2979 LOG(ERROR) << "DdmServer.broadcast " << event << " failed"; 2980 env->ExceptionDescribe(); 2981 env->ExceptionClear(); 2982 } 2983} 2984 2985void Dbg::DdmConnected() { 2986 Dbg::DdmBroadcast(true); 2987} 2988 2989void Dbg::DdmDisconnected() { 2990 Dbg::DdmBroadcast(false); 2991 gDdmThreadNotification = false; 2992} 2993 2994/* 2995 * Send a notification when a thread starts, stops, or changes its name. 2996 * 2997 * Because we broadcast the full set of threads when the notifications are 2998 * first enabled, it's possible for "thread" to be actively executing. 2999 */ 3000void Dbg::DdmSendThreadNotification(Thread* t, uint32_t type) { 3001 if (!gDdmThreadNotification) { 3002 return; 3003 } 3004 3005 if (type == CHUNK_TYPE("THDE")) { 3006 uint8_t buf[4]; 3007 JDWP::Set4BE(&buf[0], t->GetThreadId()); 3008 Dbg::DdmSendChunk(CHUNK_TYPE("THDE"), 4, buf); 3009 } else { 3010 CHECK(type == CHUNK_TYPE("THCR") || type == CHUNK_TYPE("THNM")) << type; 3011 ScopedObjectAccessUnchecked soa(Thread::Current()); 3012 SirtRef<mirror::String> name(soa.Self(), t->GetThreadName(soa)); 3013 size_t char_count = (name.get() != NULL) ? name->GetLength() : 0; 3014 const jchar* chars = (name.get() != NULL) ? name->GetCharArray()->GetData() : NULL; 3015 3016 std::vector<uint8_t> bytes; 3017 JDWP::Append4BE(bytes, t->GetThreadId()); 3018 JDWP::AppendUtf16BE(bytes, chars, char_count); 3019 CHECK_EQ(bytes.size(), char_count*2 + sizeof(uint32_t)*2); 3020 Dbg::DdmSendChunk(type, bytes); 3021 } 3022} 3023 3024void Dbg::DdmSetThreadNotification(bool enable) { 3025 // Enable/disable thread notifications. 3026 gDdmThreadNotification = enable; 3027 if (enable) { 3028 // Suspend the VM then post thread start notifications for all threads. Threads attaching will 3029 // see a suspension in progress and block until that ends. They then post their own start 3030 // notification. 3031 SuspendVM(); 3032 std::list<Thread*> threads; 3033 Thread* self = Thread::Current(); 3034 { 3035 MutexLock mu(self, *Locks::thread_list_lock_); 3036 threads = Runtime::Current()->GetThreadList()->GetList(); 3037 } 3038 { 3039 ScopedObjectAccess soa(self); 3040 for (Thread* thread : threads) { 3041 Dbg::DdmSendThreadNotification(thread, CHUNK_TYPE("THCR")); 3042 } 3043 } 3044 ResumeVM(); 3045 } 3046} 3047 3048void Dbg::PostThreadStartOrStop(Thread* t, uint32_t type) { 3049 if (IsDebuggerActive()) { 3050 ScopedObjectAccessUnchecked soa(Thread::Current()); 3051 JDWP::ObjectId id = gRegistry->Add(t->GetPeer()); 3052 gJdwpState->PostThreadChange(id, type == CHUNK_TYPE("THCR")); 3053 } 3054 Dbg::DdmSendThreadNotification(t, type); 3055} 3056 3057void Dbg::PostThreadStart(Thread* t) { 3058 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THCR")); 3059} 3060 3061void Dbg::PostThreadDeath(Thread* t) { 3062 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THDE")); 3063} 3064 3065void Dbg::DdmSendChunk(uint32_t type, size_t byte_count, const uint8_t* buf) { 3066 CHECK(buf != NULL); 3067 iovec vec[1]; 3068 vec[0].iov_base = reinterpret_cast<void*>(const_cast<uint8_t*>(buf)); 3069 vec[0].iov_len = byte_count; 3070 Dbg::DdmSendChunkV(type, vec, 1); 3071} 3072 3073void Dbg::DdmSendChunk(uint32_t type, const std::vector<uint8_t>& bytes) { 3074 DdmSendChunk(type, bytes.size(), &bytes[0]); 3075} 3076 3077void Dbg::DdmSendChunkV(uint32_t type, const iovec* iov, int iov_count) { 3078 if (gJdwpState == NULL) { 3079 VLOG(jdwp) << "Debugger thread not active, ignoring DDM send: " << type; 3080 } else { 3081 gJdwpState->DdmSendChunkV(type, iov, iov_count); 3082 } 3083} 3084 3085int Dbg::DdmHandleHpifChunk(HpifWhen when) { 3086 if (when == HPIF_WHEN_NOW) { 3087 DdmSendHeapInfo(when); 3088 return true; 3089 } 3090 3091 if (when != HPIF_WHEN_NEVER && when != HPIF_WHEN_NEXT_GC && when != HPIF_WHEN_EVERY_GC) { 3092 LOG(ERROR) << "invalid HpifWhen value: " << static_cast<int>(when); 3093 return false; 3094 } 3095 3096 gDdmHpifWhen = when; 3097 return true; 3098} 3099 3100bool Dbg::DdmHandleHpsgNhsgChunk(Dbg::HpsgWhen when, Dbg::HpsgWhat what, bool native) { 3101 if (when != HPSG_WHEN_NEVER && when != HPSG_WHEN_EVERY_GC) { 3102 LOG(ERROR) << "invalid HpsgWhen value: " << static_cast<int>(when); 3103 return false; 3104 } 3105 3106 if (what != HPSG_WHAT_MERGED_OBJECTS && what != HPSG_WHAT_DISTINCT_OBJECTS) { 3107 LOG(ERROR) << "invalid HpsgWhat value: " << static_cast<int>(what); 3108 return false; 3109 } 3110 3111 if (native) { 3112 gDdmNhsgWhen = when; 3113 gDdmNhsgWhat = what; 3114 } else { 3115 gDdmHpsgWhen = when; 3116 gDdmHpsgWhat = what; 3117 } 3118 return true; 3119} 3120 3121void Dbg::DdmSendHeapInfo(HpifWhen reason) { 3122 // If there's a one-shot 'when', reset it. 3123 if (reason == gDdmHpifWhen) { 3124 if (gDdmHpifWhen == HPIF_WHEN_NEXT_GC) { 3125 gDdmHpifWhen = HPIF_WHEN_NEVER; 3126 } 3127 } 3128 3129 /* 3130 * Chunk HPIF (client --> server) 3131 * 3132 * Heap Info. General information about the heap, 3133 * suitable for a summary display. 3134 * 3135 * [u4]: number of heaps 3136 * 3137 * For each heap: 3138 * [u4]: heap ID 3139 * [u8]: timestamp in ms since Unix epoch 3140 * [u1]: capture reason (same as 'when' value from server) 3141 * [u4]: max heap size in bytes (-Xmx) 3142 * [u4]: current heap size in bytes 3143 * [u4]: current number of bytes allocated 3144 * [u4]: current number of objects allocated 3145 */ 3146 uint8_t heap_count = 1; 3147 gc::Heap* heap = Runtime::Current()->GetHeap(); 3148 std::vector<uint8_t> bytes; 3149 JDWP::Append4BE(bytes, heap_count); 3150 JDWP::Append4BE(bytes, 1); // Heap id (bogus; we only have one heap). 3151 JDWP::Append8BE(bytes, MilliTime()); 3152 JDWP::Append1BE(bytes, reason); 3153 JDWP::Append4BE(bytes, heap->GetMaxMemory()); // Max allowed heap size in bytes. 3154 JDWP::Append4BE(bytes, heap->GetTotalMemory()); // Current heap size in bytes. 3155 JDWP::Append4BE(bytes, heap->GetBytesAllocated()); 3156 JDWP::Append4BE(bytes, heap->GetObjectsAllocated()); 3157 CHECK_EQ(bytes.size(), 4U + (heap_count * (4 + 8 + 1 + 4 + 4 + 4 + 4))); 3158 Dbg::DdmSendChunk(CHUNK_TYPE("HPIF"), bytes); 3159} 3160 3161enum HpsgSolidity { 3162 SOLIDITY_FREE = 0, 3163 SOLIDITY_HARD = 1, 3164 SOLIDITY_SOFT = 2, 3165 SOLIDITY_WEAK = 3, 3166 SOLIDITY_PHANTOM = 4, 3167 SOLIDITY_FINALIZABLE = 5, 3168 SOLIDITY_SWEEP = 6, 3169}; 3170 3171enum HpsgKind { 3172 KIND_OBJECT = 0, 3173 KIND_CLASS_OBJECT = 1, 3174 KIND_ARRAY_1 = 2, 3175 KIND_ARRAY_2 = 3, 3176 KIND_ARRAY_4 = 4, 3177 KIND_ARRAY_8 = 5, 3178 KIND_UNKNOWN = 6, 3179 KIND_NATIVE = 7, 3180}; 3181 3182#define HPSG_PARTIAL (1<<7) 3183#define HPSG_STATE(solidity, kind) ((uint8_t)((((kind) & 0x7) << 3) | ((solidity) & 0x7))) 3184 3185class HeapChunkContext { 3186 public: 3187 // Maximum chunk size. Obtain this from the formula: 3188 // (((maximum_heap_size / ALLOCATION_UNIT_SIZE) + 255) / 256) * 2 3189 HeapChunkContext(bool merge, bool native) 3190 : buf_(16384 - 16), 3191 type_(0), 3192 merge_(merge) { 3193 Reset(); 3194 if (native) { 3195 type_ = CHUNK_TYPE("NHSG"); 3196 } else { 3197 type_ = merge ? CHUNK_TYPE("HPSG") : CHUNK_TYPE("HPSO"); 3198 } 3199 } 3200 3201 ~HeapChunkContext() { 3202 if (p_ > &buf_[0]) { 3203 Flush(); 3204 } 3205 } 3206 3207 void EnsureHeader(const void* chunk_ptr) { 3208 if (!needHeader_) { 3209 return; 3210 } 3211 3212 // Start a new HPSx chunk. 3213 JDWP::Write4BE(&p_, 1); // Heap id (bogus; we only have one heap). 3214 JDWP::Write1BE(&p_, 8); // Size of allocation unit, in bytes. 3215 3216 JDWP::Write4BE(&p_, reinterpret_cast<uintptr_t>(chunk_ptr)); // virtual address of segment start. 3217 JDWP::Write4BE(&p_, 0); // offset of this piece (relative to the virtual address). 3218 // [u4]: length of piece, in allocation units 3219 // We won't know this until we're done, so save the offset and stuff in a dummy value. 3220 pieceLenField_ = p_; 3221 JDWP::Write4BE(&p_, 0x55555555); 3222 needHeader_ = false; 3223 } 3224 3225 void Flush() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 3226 if (pieceLenField_ == NULL) { 3227 // Flush immediately post Reset (maybe back-to-back Flush). Ignore. 3228 CHECK(needHeader_); 3229 return; 3230 } 3231 // Patch the "length of piece" field. 3232 CHECK_LE(&buf_[0], pieceLenField_); 3233 CHECK_LE(pieceLenField_, p_); 3234 JDWP::Set4BE(pieceLenField_, totalAllocationUnits_); 3235 3236 Dbg::DdmSendChunk(type_, p_ - &buf_[0], &buf_[0]); 3237 Reset(); 3238 } 3239 3240 static void HeapChunkCallback(void* start, void* end, size_t used_bytes, void* arg) 3241 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_, 3242 Locks::mutator_lock_) { 3243 reinterpret_cast<HeapChunkContext*>(arg)->HeapChunkCallback(start, end, used_bytes); 3244 } 3245 3246 private: 3247 enum { ALLOCATION_UNIT_SIZE = 8 }; 3248 3249 void Reset() { 3250 p_ = &buf_[0]; 3251 startOfNextMemoryChunk_ = NULL; 3252 totalAllocationUnits_ = 0; 3253 needHeader_ = true; 3254 pieceLenField_ = NULL; 3255 } 3256 3257 void HeapChunkCallback(void* start, void* /*end*/, size_t used_bytes) 3258 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_, 3259 Locks::mutator_lock_) { 3260 // Note: heap call backs cannot manipulate the heap upon which they are crawling, care is taken 3261 // in the following code not to allocate memory, by ensuring buf_ is of the correct size 3262 if (used_bytes == 0) { 3263 if (start == NULL) { 3264 // Reset for start of new heap. 3265 startOfNextMemoryChunk_ = NULL; 3266 Flush(); 3267 } 3268 // Only process in use memory so that free region information 3269 // also includes dlmalloc book keeping. 3270 return; 3271 } 3272 3273 /* If we're looking at the native heap, we'll just return 3274 * (SOLIDITY_HARD, KIND_NATIVE) for all allocated chunks 3275 */ 3276 bool native = type_ == CHUNK_TYPE("NHSG"); 3277 3278 if (startOfNextMemoryChunk_ != NULL) { 3279 // Transmit any pending free memory. Native free memory of 3280 // over kMaxFreeLen could be because of the use of mmaps, so 3281 // don't report. If not free memory then start a new segment. 3282 bool flush = true; 3283 if (start > startOfNextMemoryChunk_) { 3284 const size_t kMaxFreeLen = 2 * kPageSize; 3285 void* freeStart = startOfNextMemoryChunk_; 3286 void* freeEnd = start; 3287 size_t freeLen = reinterpret_cast<char*>(freeEnd) - reinterpret_cast<char*>(freeStart); 3288 if (!native || freeLen < kMaxFreeLen) { 3289 AppendChunk(HPSG_STATE(SOLIDITY_FREE, 0), freeStart, freeLen); 3290 flush = false; 3291 } 3292 } 3293 if (flush) { 3294 startOfNextMemoryChunk_ = NULL; 3295 Flush(); 3296 } 3297 } 3298 const mirror::Object* obj = reinterpret_cast<const mirror::Object*>(start); 3299 3300 // Determine the type of this chunk. 3301 // OLD-TODO: if context.merge, see if this chunk is different from the last chunk. 3302 // If it's the same, we should combine them. 3303 uint8_t state = ExamineObject(obj, native); 3304 // dlmalloc's chunk header is 2 * sizeof(size_t), but if the previous chunk is in use for an 3305 // allocation then the first sizeof(size_t) may belong to it. 3306 const size_t dlMallocOverhead = sizeof(size_t); 3307 AppendChunk(state, start, used_bytes + dlMallocOverhead); 3308 startOfNextMemoryChunk_ = reinterpret_cast<char*>(start) + used_bytes + dlMallocOverhead; 3309 } 3310 3311 void AppendChunk(uint8_t state, void* ptr, size_t length) 3312 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 3313 // Make sure there's enough room left in the buffer. 3314 // We need to use two bytes for every fractional 256 allocation units used by the chunk plus 3315 // 17 bytes for any header. 3316 size_t needed = (((length/ALLOCATION_UNIT_SIZE + 255) / 256) * 2) + 17; 3317 size_t bytesLeft = buf_.size() - (size_t)(p_ - &buf_[0]); 3318 if (bytesLeft < needed) { 3319 Flush(); 3320 } 3321 3322 bytesLeft = buf_.size() - (size_t)(p_ - &buf_[0]); 3323 if (bytesLeft < needed) { 3324 LOG(WARNING) << "Chunk is too big to transmit (chunk_len=" << length << ", " 3325 << needed << " bytes)"; 3326 return; 3327 } 3328 EnsureHeader(ptr); 3329 // Write out the chunk description. 3330 length /= ALLOCATION_UNIT_SIZE; // Convert to allocation units. 3331 totalAllocationUnits_ += length; 3332 while (length > 256) { 3333 *p_++ = state | HPSG_PARTIAL; 3334 *p_++ = 255; // length - 1 3335 length -= 256; 3336 } 3337 *p_++ = state; 3338 *p_++ = length - 1; 3339 } 3340 3341 uint8_t ExamineObject(const mirror::Object* o, bool is_native_heap) 3342 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) { 3343 if (o == NULL) { 3344 return HPSG_STATE(SOLIDITY_FREE, 0); 3345 } 3346 3347 // It's an allocated chunk. Figure out what it is. 3348 3349 // If we're looking at the native heap, we'll just return 3350 // (SOLIDITY_HARD, KIND_NATIVE) for all allocated chunks. 3351 if (is_native_heap) { 3352 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE); 3353 } 3354 3355 if (!Runtime::Current()->GetHeap()->IsLiveObjectLocked(o)) { 3356 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE); 3357 } 3358 3359 mirror::Class* c = o->GetClass(); 3360 if (c == NULL) { 3361 // The object was probably just created but hasn't been initialized yet. 3362 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT); 3363 } 3364 3365 if (!Runtime::Current()->GetHeap()->IsValidObjectAddress(c)) { 3366 LOG(ERROR) << "Invalid class for managed heap object: " << o << " " << c; 3367 return HPSG_STATE(SOLIDITY_HARD, KIND_UNKNOWN); 3368 } 3369 3370 if (c->IsClassClass()) { 3371 return HPSG_STATE(SOLIDITY_HARD, KIND_CLASS_OBJECT); 3372 } 3373 3374 if (c->IsArrayClass()) { 3375 if (o->IsObjectArray()) { 3376 return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4); 3377 } 3378 switch (c->GetComponentSize()) { 3379 case 1: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_1); 3380 case 2: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_2); 3381 case 4: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4); 3382 case 8: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_8); 3383 } 3384 } 3385 3386 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT); 3387 } 3388 3389 std::vector<uint8_t> buf_; 3390 uint8_t* p_; 3391 uint8_t* pieceLenField_; 3392 void* startOfNextMemoryChunk_; 3393 size_t totalAllocationUnits_; 3394 uint32_t type_; 3395 bool merge_; 3396 bool needHeader_; 3397 3398 DISALLOW_COPY_AND_ASSIGN(HeapChunkContext); 3399}; 3400 3401void Dbg::DdmSendHeapSegments(bool native) { 3402 Dbg::HpsgWhen when; 3403 Dbg::HpsgWhat what; 3404 if (!native) { 3405 when = gDdmHpsgWhen; 3406 what = gDdmHpsgWhat; 3407 } else { 3408 when = gDdmNhsgWhen; 3409 what = gDdmNhsgWhat; 3410 } 3411 if (when == HPSG_WHEN_NEVER) { 3412 return; 3413 } 3414 3415 // Figure out what kind of chunks we'll be sending. 3416 CHECK(what == HPSG_WHAT_MERGED_OBJECTS || what == HPSG_WHAT_DISTINCT_OBJECTS) << static_cast<int>(what); 3417 3418 // First, send a heap start chunk. 3419 uint8_t heap_id[4]; 3420 JDWP::Set4BE(&heap_id[0], 1); // Heap id (bogus; we only have one heap). 3421 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHST") : CHUNK_TYPE("HPST"), sizeof(heap_id), heap_id); 3422 3423 Thread* self = Thread::Current(); 3424 3425 // To allow the Walk/InspectAll() below to exclusively-lock the 3426 // mutator lock, temporarily release the shared access to the 3427 // mutator lock here by transitioning to the suspended state. 3428 Locks::mutator_lock_->AssertSharedHeld(self); 3429 self->TransitionFromRunnableToSuspended(kSuspended); 3430 3431 // Send a series of heap segment chunks. 3432 HeapChunkContext context((what == HPSG_WHAT_MERGED_OBJECTS), native); 3433 if (native) { 3434 dlmalloc_inspect_all(HeapChunkContext::HeapChunkCallback, &context); 3435 } else { 3436 gc::Heap* heap = Runtime::Current()->GetHeap(); 3437 const std::vector<gc::space::ContinuousSpace*>& spaces = heap->GetContinuousSpaces(); 3438 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_); 3439 typedef std::vector<gc::space::ContinuousSpace*>::const_iterator It; 3440 for (It cur = spaces.begin(), end = spaces.end(); cur != end; ++cur) { 3441 if ((*cur)->IsMallocSpace()) { 3442 (*cur)->AsMallocSpace()->Walk(HeapChunkContext::HeapChunkCallback, &context); 3443 } 3444 } 3445 // Walk the large objects, these are not in the AllocSpace. 3446 heap->GetLargeObjectsSpace()->Walk(HeapChunkContext::HeapChunkCallback, &context); 3447 } 3448 3449 // Shared-lock the mutator lock back. 3450 self->TransitionFromSuspendedToRunnable(); 3451 Locks::mutator_lock_->AssertSharedHeld(self); 3452 3453 // Finally, send a heap end chunk. 3454 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHEN") : CHUNK_TYPE("HPEN"), sizeof(heap_id), heap_id); 3455} 3456 3457static size_t GetAllocTrackerMax() { 3458#ifdef HAVE_ANDROID_OS 3459 // Check whether there's a system property overriding the number of records. 3460 const char* propertyName = "dalvik.vm.allocTrackerMax"; 3461 char allocRecordMaxString[PROPERTY_VALUE_MAX]; 3462 if (property_get(propertyName, allocRecordMaxString, "") > 0) { 3463 char* end; 3464 size_t value = strtoul(allocRecordMaxString, &end, 10); 3465 if (*end != '\0') { 3466 LOG(ERROR) << "Ignoring " << propertyName << " '" << allocRecordMaxString 3467 << "' --- invalid"; 3468 return kDefaultNumAllocRecords; 3469 } 3470 if (!IsPowerOfTwo(value)) { 3471 LOG(ERROR) << "Ignoring " << propertyName << " '" << allocRecordMaxString 3472 << "' --- not power of two"; 3473 return kDefaultNumAllocRecords; 3474 } 3475 return value; 3476 } 3477#endif 3478 return kDefaultNumAllocRecords; 3479} 3480 3481void Dbg::SetAllocTrackingEnabled(bool enabled) { 3482 MutexLock mu(Thread::Current(), gAllocTrackerLock); 3483 if (enabled) { 3484 if (recent_allocation_records_ == NULL) { 3485 gAllocRecordMax = GetAllocTrackerMax(); 3486 LOG(INFO) << "Enabling alloc tracker (" << gAllocRecordMax << " entries of " 3487 << kMaxAllocRecordStackDepth << " frames, taking " 3488 << PrettySize(sizeof(AllocRecord) * gAllocRecordMax) << ")"; 3489 gAllocRecordHead = gAllocRecordCount = 0; 3490 recent_allocation_records_ = new AllocRecord[gAllocRecordMax]; 3491 CHECK(recent_allocation_records_ != NULL); 3492 } 3493 Runtime::Current()->GetInstrumentation()->InstrumentQuickAllocEntryPoints(); 3494 } else { 3495 Runtime::Current()->GetInstrumentation()->UninstrumentQuickAllocEntryPoints(); 3496 delete[] recent_allocation_records_; 3497 recent_allocation_records_ = NULL; 3498 } 3499} 3500 3501struct AllocRecordStackVisitor : public StackVisitor { 3502 AllocRecordStackVisitor(Thread* thread, AllocRecord* record) 3503 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) 3504 : StackVisitor(thread, NULL), record(record), depth(0) {} 3505 3506 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses 3507 // annotalysis. 3508 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS { 3509 if (depth >= kMaxAllocRecordStackDepth) { 3510 return false; 3511 } 3512 mirror::ArtMethod* m = GetMethod(); 3513 if (!m->IsRuntimeMethod()) { 3514 record->stack[depth].method = m; 3515 record->stack[depth].dex_pc = GetDexPc(); 3516 ++depth; 3517 } 3518 return true; 3519 } 3520 3521 ~AllocRecordStackVisitor() { 3522 // Clear out any unused stack trace elements. 3523 for (; depth < kMaxAllocRecordStackDepth; ++depth) { 3524 record->stack[depth].method = NULL; 3525 record->stack[depth].dex_pc = 0; 3526 } 3527 } 3528 3529 AllocRecord* record; 3530 size_t depth; 3531}; 3532 3533void Dbg::RecordAllocation(mirror::Class* type, size_t byte_count) { 3534 Thread* self = Thread::Current(); 3535 CHECK(self != NULL); 3536 3537 MutexLock mu(self, gAllocTrackerLock); 3538 if (recent_allocation_records_ == NULL) { 3539 return; 3540 } 3541 3542 // Advance and clip. 3543 if (++gAllocRecordHead == gAllocRecordMax) { 3544 gAllocRecordHead = 0; 3545 } 3546 3547 // Fill in the basics. 3548 AllocRecord* record = &recent_allocation_records_[gAllocRecordHead]; 3549 record->type = type; 3550 record->byte_count = byte_count; 3551 record->thin_lock_id = self->GetThreadId(); 3552 3553 // Fill in the stack trace. 3554 AllocRecordStackVisitor visitor(self, record); 3555 visitor.WalkStack(); 3556 3557 if (gAllocRecordCount < gAllocRecordMax) { 3558 ++gAllocRecordCount; 3559 } 3560} 3561 3562// Returns the index of the head element. 3563// 3564// We point at the most-recently-written record, so if gAllocRecordCount is 1 3565// we want to use the current element. Take "head+1" and subtract count 3566// from it. 3567// 3568// We need to handle underflow in our circular buffer, so we add 3569// gAllocRecordMax and then mask it back down. 3570static inline int HeadIndex() EXCLUSIVE_LOCKS_REQUIRED(gAllocTrackerLock) { 3571 return (gAllocRecordHead+1 + gAllocRecordMax - gAllocRecordCount) & (gAllocRecordMax-1); 3572} 3573 3574void Dbg::DumpRecentAllocations() { 3575 ScopedObjectAccess soa(Thread::Current()); 3576 MutexLock mu(soa.Self(), gAllocTrackerLock); 3577 if (recent_allocation_records_ == NULL) { 3578 LOG(INFO) << "Not recording tracked allocations"; 3579 return; 3580 } 3581 3582 // "i" is the head of the list. We want to start at the end of the 3583 // list and move forward to the tail. 3584 size_t i = HeadIndex(); 3585 size_t count = gAllocRecordCount; 3586 3587 LOG(INFO) << "Tracked allocations, (head=" << gAllocRecordHead << " count=" << count << ")"; 3588 while (count--) { 3589 AllocRecord* record = &recent_allocation_records_[i]; 3590 3591 LOG(INFO) << StringPrintf(" Thread %-2d %6zd bytes ", record->thin_lock_id, record->byte_count) 3592 << PrettyClass(record->type); 3593 3594 for (size_t stack_frame = 0; stack_frame < kMaxAllocRecordStackDepth; ++stack_frame) { 3595 const mirror::ArtMethod* m = record->stack[stack_frame].method; 3596 if (m == NULL) { 3597 break; 3598 } 3599 LOG(INFO) << " " << PrettyMethod(m) << " line " << record->stack[stack_frame].LineNumber(); 3600 } 3601 3602 // pause periodically to help logcat catch up 3603 if ((count % 5) == 0) { 3604 usleep(40000); 3605 } 3606 3607 i = (i + 1) & (gAllocRecordMax-1); 3608 } 3609} 3610 3611class StringTable { 3612 public: 3613 StringTable() { 3614 } 3615 3616 void Add(const char* s) { 3617 table_.insert(s); 3618 } 3619 3620 size_t IndexOf(const char* s) const { 3621 auto it = table_.find(s); 3622 if (it == table_.end()) { 3623 LOG(FATAL) << "IndexOf(\"" << s << "\") failed"; 3624 } 3625 return std::distance(table_.begin(), it); 3626 } 3627 3628 size_t Size() const { 3629 return table_.size(); 3630 } 3631 3632 void WriteTo(std::vector<uint8_t>& bytes) const { 3633 for (const std::string& str : table_) { 3634 const char* s = str.c_str(); 3635 size_t s_len = CountModifiedUtf8Chars(s); 3636 UniquePtr<uint16_t> s_utf16(new uint16_t[s_len]); 3637 ConvertModifiedUtf8ToUtf16(s_utf16.get(), s); 3638 JDWP::AppendUtf16BE(bytes, s_utf16.get(), s_len); 3639 } 3640 } 3641 3642 private: 3643 std::set<std::string> table_; 3644 DISALLOW_COPY_AND_ASSIGN(StringTable); 3645}; 3646 3647/* 3648 * The data we send to DDMS contains everything we have recorded. 3649 * 3650 * Message header (all values big-endian): 3651 * (1b) message header len (to allow future expansion); includes itself 3652 * (1b) entry header len 3653 * (1b) stack frame len 3654 * (2b) number of entries 3655 * (4b) offset to string table from start of message 3656 * (2b) number of class name strings 3657 * (2b) number of method name strings 3658 * (2b) number of source file name strings 3659 * For each entry: 3660 * (4b) total allocation size 3661 * (2b) thread id 3662 * (2b) allocated object's class name index 3663 * (1b) stack depth 3664 * For each stack frame: 3665 * (2b) method's class name 3666 * (2b) method name 3667 * (2b) method source file 3668 * (2b) line number, clipped to 32767; -2 if native; -1 if no source 3669 * (xb) class name strings 3670 * (xb) method name strings 3671 * (xb) source file strings 3672 * 3673 * As with other DDM traffic, strings are sent as a 4-byte length 3674 * followed by UTF-16 data. 3675 * 3676 * We send up 16-bit unsigned indexes into string tables. In theory there 3677 * can be (kMaxAllocRecordStackDepth * gAllocRecordMax) unique strings in 3678 * each table, but in practice there should be far fewer. 3679 * 3680 * The chief reason for using a string table here is to keep the size of 3681 * the DDMS message to a minimum. This is partly to make the protocol 3682 * efficient, but also because we have to form the whole thing up all at 3683 * once in a memory buffer. 3684 * 3685 * We use separate string tables for class names, method names, and source 3686 * files to keep the indexes small. There will generally be no overlap 3687 * between the contents of these tables. 3688 */ 3689jbyteArray Dbg::GetRecentAllocations() { 3690 if (false) { 3691 DumpRecentAllocations(); 3692 } 3693 3694 Thread* self = Thread::Current(); 3695 std::vector<uint8_t> bytes; 3696 { 3697 MutexLock mu(self, gAllocTrackerLock); 3698 // 3699 // Part 1: generate string tables. 3700 // 3701 StringTable class_names; 3702 StringTable method_names; 3703 StringTable filenames; 3704 3705 int count = gAllocRecordCount; 3706 int idx = HeadIndex(); 3707 while (count--) { 3708 AllocRecord* record = &recent_allocation_records_[idx]; 3709 3710 class_names.Add(ClassHelper(record->type).GetDescriptor()); 3711 3712 MethodHelper mh; 3713 for (size_t i = 0; i < kMaxAllocRecordStackDepth; i++) { 3714 mirror::ArtMethod* m = record->stack[i].method; 3715 if (m != NULL) { 3716 mh.ChangeMethod(m); 3717 class_names.Add(mh.GetDeclaringClassDescriptor()); 3718 method_names.Add(mh.GetName()); 3719 filenames.Add(mh.GetDeclaringClassSourceFile()); 3720 } 3721 } 3722 3723 idx = (idx + 1) & (gAllocRecordMax-1); 3724 } 3725 3726 LOG(INFO) << "allocation records: " << gAllocRecordCount; 3727 3728 // 3729 // Part 2: Generate the output and store it in the buffer. 3730 // 3731 3732 // (1b) message header len (to allow future expansion); includes itself 3733 // (1b) entry header len 3734 // (1b) stack frame len 3735 const int kMessageHeaderLen = 15; 3736 const int kEntryHeaderLen = 9; 3737 const int kStackFrameLen = 8; 3738 JDWP::Append1BE(bytes, kMessageHeaderLen); 3739 JDWP::Append1BE(bytes, kEntryHeaderLen); 3740 JDWP::Append1BE(bytes, kStackFrameLen); 3741 3742 // (2b) number of entries 3743 // (4b) offset to string table from start of message 3744 // (2b) number of class name strings 3745 // (2b) number of method name strings 3746 // (2b) number of source file name strings 3747 JDWP::Append2BE(bytes, gAllocRecordCount); 3748 size_t string_table_offset = bytes.size(); 3749 JDWP::Append4BE(bytes, 0); // We'll patch this later... 3750 JDWP::Append2BE(bytes, class_names.Size()); 3751 JDWP::Append2BE(bytes, method_names.Size()); 3752 JDWP::Append2BE(bytes, filenames.Size()); 3753 3754 count = gAllocRecordCount; 3755 idx = HeadIndex(); 3756 while (count--) { 3757 // For each entry: 3758 // (4b) total allocation size 3759 // (2b) thread id 3760 // (2b) allocated object's class name index 3761 // (1b) stack depth 3762 AllocRecord* record = &recent_allocation_records_[idx]; 3763 size_t stack_depth = record->GetDepth(); 3764 ClassHelper kh(record->type); 3765 size_t allocated_object_class_name_index = class_names.IndexOf(kh.GetDescriptor()); 3766 JDWP::Append4BE(bytes, record->byte_count); 3767 JDWP::Append2BE(bytes, record->thin_lock_id); 3768 JDWP::Append2BE(bytes, allocated_object_class_name_index); 3769 JDWP::Append1BE(bytes, stack_depth); 3770 3771 MethodHelper mh; 3772 for (size_t stack_frame = 0; stack_frame < stack_depth; ++stack_frame) { 3773 // For each stack frame: 3774 // (2b) method's class name 3775 // (2b) method name 3776 // (2b) method source file 3777 // (2b) line number, clipped to 32767; -2 if native; -1 if no source 3778 mh.ChangeMethod(record->stack[stack_frame].method); 3779 size_t class_name_index = class_names.IndexOf(mh.GetDeclaringClassDescriptor()); 3780 size_t method_name_index = method_names.IndexOf(mh.GetName()); 3781 size_t file_name_index = filenames.IndexOf(mh.GetDeclaringClassSourceFile()); 3782 JDWP::Append2BE(bytes, class_name_index); 3783 JDWP::Append2BE(bytes, method_name_index); 3784 JDWP::Append2BE(bytes, file_name_index); 3785 JDWP::Append2BE(bytes, record->stack[stack_frame].LineNumber()); 3786 } 3787 3788 idx = (idx + 1) & (gAllocRecordMax-1); 3789 } 3790 3791 // (xb) class name strings 3792 // (xb) method name strings 3793 // (xb) source file strings 3794 JDWP::Set4BE(&bytes[string_table_offset], bytes.size()); 3795 class_names.WriteTo(bytes); 3796 method_names.WriteTo(bytes); 3797 filenames.WriteTo(bytes); 3798 } 3799 JNIEnv* env = self->GetJniEnv(); 3800 jbyteArray result = env->NewByteArray(bytes.size()); 3801 if (result != NULL) { 3802 env->SetByteArrayRegion(result, 0, bytes.size(), reinterpret_cast<const jbyte*>(&bytes[0])); 3803 } 3804 return result; 3805} 3806 3807} // namespace art 3808