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