debugger.cc revision 59d9d668d4f4286813afe2b4e7c6db839222ce96
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 Thread* thread = ThreadList::SuspendThreadByPeer(peer.get(), request_suspension, true, 2285 &timed_out); 2286 if (thread != NULL) { 2287 return JDWP::ERR_NONE; 2288 } else if (timed_out) { 2289 return JDWP::ERR_INTERNAL; 2290 } else { 2291 return JDWP::ERR_THREAD_NOT_ALIVE; 2292 } 2293} 2294 2295void Dbg::ResumeThread(JDWP::ObjectId thread_id) { 2296 ScopedObjectAccessUnchecked soa(Thread::Current()); 2297 mirror::Object* peer = gRegistry->Get<mirror::Object*>(thread_id); 2298 Thread* thread; 2299 { 2300 MutexLock mu(soa.Self(), *Locks::thread_list_lock_); 2301 thread = Thread::FromManagedThread(soa, peer); 2302 } 2303 if (thread == NULL) { 2304 LOG(WARNING) << "No such thread for resume: " << peer; 2305 return; 2306 } 2307 bool needs_resume; 2308 { 2309 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_); 2310 needs_resume = thread->GetSuspendCount() > 0; 2311 } 2312 if (needs_resume) { 2313 Runtime::Current()->GetThreadList()->Resume(thread, true); 2314 } 2315} 2316 2317void Dbg::SuspendSelf() { 2318 Runtime::Current()->GetThreadList()->SuspendSelfForDebugger(); 2319} 2320 2321struct GetThisVisitor : public StackVisitor { 2322 GetThisVisitor(Thread* thread, Context* context, JDWP::FrameId frame_id) 2323 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) 2324 : StackVisitor(thread, context), this_object(NULL), frame_id(frame_id) {} 2325 2326 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses 2327 // annotalysis. 2328 virtual bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS { 2329 if (frame_id != GetFrameId()) { 2330 return true; // continue 2331 } else { 2332 this_object = GetThisObject(); 2333 return false; 2334 } 2335 } 2336 2337 mirror::Object* this_object; 2338 JDWP::FrameId frame_id; 2339}; 2340 2341JDWP::JdwpError Dbg::GetThisObject(JDWP::ObjectId thread_id, JDWP::FrameId frame_id, 2342 JDWP::ObjectId* result) { 2343 ScopedObjectAccessUnchecked soa(Thread::Current()); 2344 Thread* thread; 2345 { 2346 MutexLock mu(soa.Self(), *Locks::thread_list_lock_); 2347 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread); 2348 if (error != JDWP::ERR_NONE) { 2349 return error; 2350 } 2351 if (!IsSuspendedForDebugger(soa, thread)) { 2352 return JDWP::ERR_THREAD_NOT_SUSPENDED; 2353 } 2354 } 2355 std::unique_ptr<Context> context(Context::Create()); 2356 GetThisVisitor visitor(thread, context.get(), frame_id); 2357 visitor.WalkStack(); 2358 *result = gRegistry->Add(visitor.this_object); 2359 return JDWP::ERR_NONE; 2360} 2361 2362JDWP::JdwpError Dbg::GetLocalValue(JDWP::ObjectId thread_id, JDWP::FrameId frame_id, int slot, 2363 JDWP::JdwpTag tag, uint8_t* buf, size_t width) { 2364 struct GetLocalVisitor : public StackVisitor { 2365 GetLocalVisitor(const ScopedObjectAccessUnchecked& soa, Thread* thread, Context* context, 2366 JDWP::FrameId frame_id, int slot, JDWP::JdwpTag tag, uint8_t* buf, size_t width) 2367 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) 2368 : StackVisitor(thread, context), soa_(soa), frame_id_(frame_id), slot_(slot), tag_(tag), 2369 buf_(buf), width_(width), error_(JDWP::ERR_NONE) {} 2370 2371 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses 2372 // annotalysis. 2373 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS { 2374 if (GetFrameId() != frame_id_) { 2375 return true; // Not our frame, carry on. 2376 } 2377 // TODO: check that the tag is compatible with the actual type of the slot! 2378 // TODO: check slot is valid for this method or return INVALID_SLOT error. 2379 mirror::ArtMethod* m = GetMethod(); 2380 if (m->IsNative()) { 2381 // We can't read local value from native method. 2382 error_ = JDWP::ERR_OPAQUE_FRAME; 2383 return false; 2384 } 2385 uint16_t reg = DemangleSlot(slot_, m); 2386 constexpr JDWP::JdwpError kFailureErrorCode = JDWP::ERR_ABSENT_INFORMATION; 2387 switch (tag_) { 2388 case JDWP::JT_BOOLEAN: { 2389 CHECK_EQ(width_, 1U); 2390 uint32_t intVal; 2391 if (GetVReg(m, reg, kIntVReg, &intVal)) { 2392 VLOG(jdwp) << "get boolean local " << reg << " = " << intVal; 2393 JDWP::Set1(buf_+1, intVal != 0); 2394 } else { 2395 VLOG(jdwp) << "failed to get boolean local " << reg; 2396 error_ = kFailureErrorCode; 2397 } 2398 break; 2399 } 2400 case JDWP::JT_BYTE: { 2401 CHECK_EQ(width_, 1U); 2402 uint32_t intVal; 2403 if (GetVReg(m, reg, kIntVReg, &intVal)) { 2404 VLOG(jdwp) << "get byte local " << reg << " = " << intVal; 2405 JDWP::Set1(buf_+1, intVal); 2406 } else { 2407 VLOG(jdwp) << "failed to get byte local " << reg; 2408 error_ = kFailureErrorCode; 2409 } 2410 break; 2411 } 2412 case JDWP::JT_SHORT: 2413 case JDWP::JT_CHAR: { 2414 CHECK_EQ(width_, 2U); 2415 uint32_t intVal; 2416 if (GetVReg(m, reg, kIntVReg, &intVal)) { 2417 VLOG(jdwp) << "get short/char local " << reg << " = " << intVal; 2418 JDWP::Set2BE(buf_+1, intVal); 2419 } else { 2420 VLOG(jdwp) << "failed to get short/char local " << reg; 2421 error_ = kFailureErrorCode; 2422 } 2423 break; 2424 } 2425 case JDWP::JT_INT: { 2426 CHECK_EQ(width_, 4U); 2427 uint32_t intVal; 2428 if (GetVReg(m, reg, kIntVReg, &intVal)) { 2429 VLOG(jdwp) << "get int local " << reg << " = " << intVal; 2430 JDWP::Set4BE(buf_+1, intVal); 2431 } else { 2432 VLOG(jdwp) << "failed to get int local " << reg; 2433 error_ = kFailureErrorCode; 2434 } 2435 break; 2436 } 2437 case JDWP::JT_FLOAT: { 2438 CHECK_EQ(width_, 4U); 2439 uint32_t intVal; 2440 if (GetVReg(m, reg, kFloatVReg, &intVal)) { 2441 VLOG(jdwp) << "get float local " << reg << " = " << intVal; 2442 JDWP::Set4BE(buf_+1, intVal); 2443 } else { 2444 VLOG(jdwp) << "failed to get float local " << reg; 2445 error_ = kFailureErrorCode; 2446 } 2447 break; 2448 } 2449 case JDWP::JT_ARRAY: 2450 case JDWP::JT_CLASS_LOADER: 2451 case JDWP::JT_CLASS_OBJECT: 2452 case JDWP::JT_OBJECT: 2453 case JDWP::JT_STRING: 2454 case JDWP::JT_THREAD: 2455 case JDWP::JT_THREAD_GROUP: { 2456 CHECK_EQ(width_, sizeof(JDWP::ObjectId)); 2457 uint32_t intVal; 2458 if (GetVReg(m, reg, kReferenceVReg, &intVal)) { 2459 mirror::Object* o = reinterpret_cast<mirror::Object*>(intVal); 2460 VLOG(jdwp) << "get " << tag_ << " object local " << reg << " = " << o; 2461 if (!Runtime::Current()->GetHeap()->IsValidObjectAddress(o)) { 2462 LOG(FATAL) << "Register " << reg << " expected to hold " << tag_ << " object: " << o; 2463 } 2464 tag_ = TagFromObject(soa_, o); 2465 JDWP::SetObjectId(buf_+1, gRegistry->Add(o)); 2466 } else { 2467 VLOG(jdwp) << "failed to get " << tag_ << " object local " << reg; 2468 error_ = kFailureErrorCode; 2469 } 2470 break; 2471 } 2472 case JDWP::JT_DOUBLE: { 2473 CHECK_EQ(width_, 8U); 2474 uint64_t longVal; 2475 if (GetVRegPair(m, reg, kDoubleLoVReg, kDoubleHiVReg, &longVal)) { 2476 VLOG(jdwp) << "get double local " << reg << " = " << longVal; 2477 JDWP::Set8BE(buf_+1, longVal); 2478 } else { 2479 VLOG(jdwp) << "failed to get double local " << reg; 2480 error_ = kFailureErrorCode; 2481 } 2482 break; 2483 } 2484 case JDWP::JT_LONG: { 2485 CHECK_EQ(width_, 8U); 2486 uint64_t longVal; 2487 if (GetVRegPair(m, reg, kLongLoVReg, kLongHiVReg, &longVal)) { 2488 VLOG(jdwp) << "get long local " << reg << " = " << longVal; 2489 JDWP::Set8BE(buf_+1, longVal); 2490 } else { 2491 VLOG(jdwp) << "failed to get long local " << reg; 2492 error_ = kFailureErrorCode; 2493 } 2494 break; 2495 } 2496 default: 2497 LOG(FATAL) << "Unknown tag " << tag_; 2498 break; 2499 } 2500 2501 // Prepend tag, which may have been updated. 2502 JDWP::Set1(buf_, tag_); 2503 return false; 2504 } 2505 const ScopedObjectAccessUnchecked& soa_; 2506 const JDWP::FrameId frame_id_; 2507 const int slot_; 2508 JDWP::JdwpTag tag_; 2509 uint8_t* const buf_; 2510 const size_t width_; 2511 JDWP::JdwpError error_; 2512 }; 2513 2514 ScopedObjectAccessUnchecked soa(Thread::Current()); 2515 MutexLock mu(soa.Self(), *Locks::thread_list_lock_); 2516 Thread* thread; 2517 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread); 2518 if (error != JDWP::ERR_NONE) { 2519 return error; 2520 } 2521 // TODO check thread is suspended by the debugger ? 2522 std::unique_ptr<Context> context(Context::Create()); 2523 GetLocalVisitor visitor(soa, thread, context.get(), frame_id, slot, tag, buf, width); 2524 visitor.WalkStack(); 2525 return visitor.error_; 2526} 2527 2528JDWP::JdwpError Dbg::SetLocalValue(JDWP::ObjectId thread_id, JDWP::FrameId frame_id, int slot, 2529 JDWP::JdwpTag tag, uint64_t value, size_t width) { 2530 struct SetLocalVisitor : public StackVisitor { 2531 SetLocalVisitor(Thread* thread, Context* context, 2532 JDWP::FrameId frame_id, int slot, JDWP::JdwpTag tag, uint64_t value, 2533 size_t width) 2534 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) 2535 : StackVisitor(thread, context), 2536 frame_id_(frame_id), slot_(slot), tag_(tag), value_(value), width_(width), 2537 error_(JDWP::ERR_NONE) {} 2538 2539 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses 2540 // annotalysis. 2541 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS { 2542 if (GetFrameId() != frame_id_) { 2543 return true; // Not our frame, carry on. 2544 } 2545 // TODO: check that the tag is compatible with the actual type of the slot! 2546 // TODO: check slot is valid for this method or return INVALID_SLOT error. 2547 mirror::ArtMethod* m = GetMethod(); 2548 if (m->IsNative()) { 2549 // We can't read local value from native method. 2550 error_ = JDWP::ERR_OPAQUE_FRAME; 2551 return false; 2552 } 2553 uint16_t reg = DemangleSlot(slot_, m); 2554 constexpr JDWP::JdwpError kFailureErrorCode = JDWP::ERR_ABSENT_INFORMATION; 2555 switch (tag_) { 2556 case JDWP::JT_BOOLEAN: 2557 case JDWP::JT_BYTE: 2558 CHECK_EQ(width_, 1U); 2559 if (!SetVReg(m, reg, static_cast<uint32_t>(value_), kIntVReg)) { 2560 VLOG(jdwp) << "failed to set boolean/byte local " << reg << " = " 2561 << static_cast<uint32_t>(value_); 2562 error_ = kFailureErrorCode; 2563 } 2564 break; 2565 case JDWP::JT_SHORT: 2566 case JDWP::JT_CHAR: 2567 CHECK_EQ(width_, 2U); 2568 if (!SetVReg(m, reg, static_cast<uint32_t>(value_), kIntVReg)) { 2569 VLOG(jdwp) << "failed to set short/char local " << reg << " = " 2570 << static_cast<uint32_t>(value_); 2571 error_ = kFailureErrorCode; 2572 } 2573 break; 2574 case JDWP::JT_INT: 2575 CHECK_EQ(width_, 4U); 2576 if (!SetVReg(m, reg, static_cast<uint32_t>(value_), kIntVReg)) { 2577 VLOG(jdwp) << "failed to set int local " << reg << " = " 2578 << static_cast<uint32_t>(value_); 2579 error_ = kFailureErrorCode; 2580 } 2581 break; 2582 case JDWP::JT_FLOAT: 2583 CHECK_EQ(width_, 4U); 2584 if (!SetVReg(m, reg, static_cast<uint32_t>(value_), kFloatVReg)) { 2585 VLOG(jdwp) << "failed to set float local " << reg << " = " 2586 << static_cast<uint32_t>(value_); 2587 error_ = kFailureErrorCode; 2588 } 2589 break; 2590 case JDWP::JT_ARRAY: 2591 case JDWP::JT_CLASS_LOADER: 2592 case JDWP::JT_CLASS_OBJECT: 2593 case JDWP::JT_OBJECT: 2594 case JDWP::JT_STRING: 2595 case JDWP::JT_THREAD: 2596 case JDWP::JT_THREAD_GROUP: { 2597 CHECK_EQ(width_, sizeof(JDWP::ObjectId)); 2598 mirror::Object* o = gRegistry->Get<mirror::Object*>(static_cast<JDWP::ObjectId>(value_)); 2599 if (o == ObjectRegistry::kInvalidObject) { 2600 VLOG(jdwp) << tag_ << " object " << o << " is an invalid object"; 2601 error_ = JDWP::ERR_INVALID_OBJECT; 2602 } else if (!SetVReg(m, reg, static_cast<uint32_t>(reinterpret_cast<uintptr_t>(o)), 2603 kReferenceVReg)) { 2604 VLOG(jdwp) << "failed to set " << tag_ << " object local " << reg << " = " << o; 2605 error_ = kFailureErrorCode; 2606 } 2607 break; 2608 } 2609 case JDWP::JT_DOUBLE: { 2610 CHECK_EQ(width_, 8U); 2611 bool success = SetVRegPair(m, reg, value_, kDoubleLoVReg, kDoubleHiVReg); 2612 if (!success) { 2613 VLOG(jdwp) << "failed to set double local " << reg << " = " << value_; 2614 error_ = kFailureErrorCode; 2615 } 2616 break; 2617 } 2618 case JDWP::JT_LONG: { 2619 CHECK_EQ(width_, 8U); 2620 bool success = SetVRegPair(m, reg, value_, kLongLoVReg, kLongHiVReg); 2621 if (!success) { 2622 VLOG(jdwp) << "failed to set double local " << reg << " = " << value_; 2623 error_ = kFailureErrorCode; 2624 } 2625 break; 2626 } 2627 default: 2628 LOG(FATAL) << "Unknown tag " << tag_; 2629 break; 2630 } 2631 return false; 2632 } 2633 2634 const JDWP::FrameId frame_id_; 2635 const int slot_; 2636 const JDWP::JdwpTag tag_; 2637 const uint64_t value_; 2638 const size_t width_; 2639 JDWP::JdwpError error_; 2640 }; 2641 2642 ScopedObjectAccessUnchecked soa(Thread::Current()); 2643 MutexLock mu(soa.Self(), *Locks::thread_list_lock_); 2644 Thread* thread; 2645 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread); 2646 if (error != JDWP::ERR_NONE) { 2647 return error; 2648 } 2649 // TODO check thread is suspended by the debugger ? 2650 std::unique_ptr<Context> context(Context::Create()); 2651 SetLocalVisitor visitor(thread, context.get(), frame_id, slot, tag, value, width); 2652 visitor.WalkStack(); 2653 return visitor.error_; 2654} 2655 2656JDWP::ObjectId Dbg::GetThisObjectIdForEvent(mirror::Object* this_object) { 2657 // If 'this_object' isn't already in the registry, we know that we're not looking for it, so 2658 // there's no point adding it to the registry and burning through ids. 2659 // When registering an event request with an instance filter, we've been given an existing object 2660 // id so it must already be present in the registry when the event fires. 2661 JDWP::ObjectId this_id = 0; 2662 if (this_object != nullptr && gRegistry->Contains(this_object)) { 2663 this_id = gRegistry->Add(this_object); 2664 } 2665 return this_id; 2666} 2667 2668void Dbg::PostLocationEvent(mirror::ArtMethod* m, int dex_pc, mirror::Object* this_object, 2669 int event_flags, const JValue* return_value) { 2670 if (!IsDebuggerActive()) { 2671 return; 2672 } 2673 DCHECK(m != nullptr); 2674 DCHECK_EQ(m->IsStatic(), this_object == nullptr); 2675 JDWP::JdwpLocation location; 2676 SetLocation(location, m, dex_pc); 2677 2678 // We need 'this' for InstanceOnly filters only. 2679 JDWP::ObjectId this_id = GetThisObjectIdForEvent(this_object); 2680 gJdwpState->PostLocationEvent(&location, this_id, event_flags, return_value); 2681} 2682 2683void Dbg::PostFieldAccessEvent(mirror::ArtMethod* m, int dex_pc, 2684 mirror::Object* this_object, mirror::ArtField* f) { 2685 if (!IsDebuggerActive()) { 2686 return; 2687 } 2688 DCHECK(m != nullptr); 2689 DCHECK(f != nullptr); 2690 JDWP::JdwpLocation location; 2691 SetLocation(location, m, dex_pc); 2692 2693 JDWP::RefTypeId type_id = gRegistry->AddRefType(f->GetDeclaringClass()); 2694 JDWP::FieldId field_id = ToFieldId(f); 2695 JDWP::ObjectId this_id = gRegistry->Add(this_object); 2696 2697 gJdwpState->PostFieldEvent(&location, type_id, field_id, this_id, nullptr, false); 2698} 2699 2700void Dbg::PostFieldModificationEvent(mirror::ArtMethod* m, int dex_pc, 2701 mirror::Object* this_object, mirror::ArtField* f, 2702 const JValue* field_value) { 2703 if (!IsDebuggerActive()) { 2704 return; 2705 } 2706 DCHECK(m != nullptr); 2707 DCHECK(f != nullptr); 2708 DCHECK(field_value != nullptr); 2709 JDWP::JdwpLocation location; 2710 SetLocation(location, m, dex_pc); 2711 2712 JDWP::RefTypeId type_id = gRegistry->AddRefType(f->GetDeclaringClass()); 2713 JDWP::FieldId field_id = ToFieldId(f); 2714 JDWP::ObjectId this_id = gRegistry->Add(this_object); 2715 2716 gJdwpState->PostFieldEvent(&location, type_id, field_id, this_id, field_value, true); 2717} 2718 2719void Dbg::PostException(const ThrowLocation& throw_location, 2720 mirror::ArtMethod* catch_method, 2721 uint32_t catch_dex_pc, mirror::Throwable* exception_object) { 2722 if (!IsDebuggerActive()) { 2723 return; 2724 } 2725 2726 JDWP::JdwpLocation jdwp_throw_location; 2727 SetLocation(jdwp_throw_location, throw_location.GetMethod(), throw_location.GetDexPc()); 2728 JDWP::JdwpLocation catch_location; 2729 SetLocation(catch_location, catch_method, catch_dex_pc); 2730 2731 // We need 'this' for InstanceOnly filters only. 2732 JDWP::ObjectId this_id = GetThisObjectIdForEvent(throw_location.GetThis()); 2733 JDWP::ObjectId exception_id = gRegistry->Add(exception_object); 2734 JDWP::RefTypeId exception_class_id = gRegistry->AddRefType(exception_object->GetClass()); 2735 2736 gJdwpState->PostException(&jdwp_throw_location, exception_id, exception_class_id, &catch_location, 2737 this_id); 2738} 2739 2740void Dbg::PostClassPrepare(mirror::Class* c) { 2741 if (!IsDebuggerActive()) { 2742 return; 2743 } 2744 2745 // OLD-TODO - we currently always send both "verified" and "prepared" since 2746 // debuggers seem to like that. There might be some advantage to honesty, 2747 // since the class may not yet be verified. 2748 int state = JDWP::CS_VERIFIED | JDWP::CS_PREPARED; 2749 JDWP::JdwpTypeTag tag = GetTypeTag(c); 2750 std::string temp; 2751 gJdwpState->PostClassPrepare(tag, gRegistry->Add(c), c->GetDescriptor(&temp), state); 2752} 2753 2754void Dbg::UpdateDebugger(Thread* thread, mirror::Object* this_object, 2755 mirror::ArtMethod* m, uint32_t dex_pc, 2756 int event_flags, const JValue* return_value) { 2757 if (!IsDebuggerActive() || dex_pc == static_cast<uint32_t>(-2) /* fake method exit */) { 2758 return; 2759 } 2760 2761 if (IsBreakpoint(m, dex_pc)) { 2762 event_flags |= kBreakpoint; 2763 } 2764 2765 // If the debugger is single-stepping one of our threads, check to 2766 // see if we're that thread and we've reached a step point. 2767 const SingleStepControl* single_step_control = thread->GetSingleStepControl(); 2768 DCHECK(single_step_control != nullptr); 2769 if (single_step_control->is_active) { 2770 CHECK(!m->IsNative()); 2771 if (single_step_control->step_depth == JDWP::SD_INTO) { 2772 // Step into method calls. We break when the line number 2773 // or method pointer changes. If we're in SS_MIN mode, we 2774 // always stop. 2775 if (single_step_control->method != m) { 2776 event_flags |= kSingleStep; 2777 VLOG(jdwp) << "SS new method"; 2778 } else if (single_step_control->step_size == JDWP::SS_MIN) { 2779 event_flags |= kSingleStep; 2780 VLOG(jdwp) << "SS new instruction"; 2781 } else if (single_step_control->ContainsDexPc(dex_pc)) { 2782 event_flags |= kSingleStep; 2783 VLOG(jdwp) << "SS new line"; 2784 } 2785 } else if (single_step_control->step_depth == JDWP::SD_OVER) { 2786 // Step over method calls. We break when the line number is 2787 // different and the frame depth is <= the original frame 2788 // depth. (We can't just compare on the method, because we 2789 // might get unrolled past it by an exception, and it's tricky 2790 // to identify recursion.) 2791 2792 int stack_depth = GetStackDepth(thread); 2793 2794 if (stack_depth < single_step_control->stack_depth) { 2795 // Popped up one or more frames, always trigger. 2796 event_flags |= kSingleStep; 2797 VLOG(jdwp) << "SS method pop"; 2798 } else if (stack_depth == single_step_control->stack_depth) { 2799 // Same depth, see if we moved. 2800 if (single_step_control->step_size == JDWP::SS_MIN) { 2801 event_flags |= kSingleStep; 2802 VLOG(jdwp) << "SS new instruction"; 2803 } else if (single_step_control->ContainsDexPc(dex_pc)) { 2804 event_flags |= kSingleStep; 2805 VLOG(jdwp) << "SS new line"; 2806 } 2807 } 2808 } else { 2809 CHECK_EQ(single_step_control->step_depth, JDWP::SD_OUT); 2810 // Return from the current method. We break when the frame 2811 // depth pops up. 2812 2813 // This differs from the "method exit" break in that it stops 2814 // with the PC at the next instruction in the returned-to 2815 // function, rather than the end of the returning function. 2816 2817 int stack_depth = GetStackDepth(thread); 2818 if (stack_depth < single_step_control->stack_depth) { 2819 event_flags |= kSingleStep; 2820 VLOG(jdwp) << "SS method pop"; 2821 } 2822 } 2823 } 2824 2825 // If there's something interesting going on, see if it matches one 2826 // of the debugger filters. 2827 if (event_flags != 0) { 2828 Dbg::PostLocationEvent(m, dex_pc, this_object, event_flags, return_value); 2829 } 2830} 2831 2832size_t* Dbg::GetReferenceCounterForEvent(uint32_t instrumentation_event) { 2833 switch (instrumentation_event) { 2834 case instrumentation::Instrumentation::kMethodEntered: 2835 return &method_enter_event_ref_count_; 2836 case instrumentation::Instrumentation::kMethodExited: 2837 return &method_exit_event_ref_count_; 2838 case instrumentation::Instrumentation::kDexPcMoved: 2839 return &dex_pc_change_event_ref_count_; 2840 case instrumentation::Instrumentation::kFieldRead: 2841 return &field_read_event_ref_count_; 2842 case instrumentation::Instrumentation::kFieldWritten: 2843 return &field_write_event_ref_count_; 2844 case instrumentation::Instrumentation::kExceptionCaught: 2845 return &exception_catch_event_ref_count_; 2846 default: 2847 return nullptr; 2848 } 2849} 2850 2851// Process request while all mutator threads are suspended. 2852void Dbg::ProcessDeoptimizationRequest(const DeoptimizationRequest& request) { 2853 instrumentation::Instrumentation* instrumentation = Runtime::Current()->GetInstrumentation(); 2854 switch (request.GetKind()) { 2855 case DeoptimizationRequest::kNothing: 2856 LOG(WARNING) << "Ignoring empty deoptimization request."; 2857 break; 2858 case DeoptimizationRequest::kRegisterForEvent: 2859 VLOG(jdwp) << StringPrintf("Add debugger as listener for instrumentation event 0x%x", 2860 request.InstrumentationEvent()); 2861 instrumentation->AddListener(&gDebugInstrumentationListener, request.InstrumentationEvent()); 2862 instrumentation_events_ |= request.InstrumentationEvent(); 2863 break; 2864 case DeoptimizationRequest::kUnregisterForEvent: 2865 VLOG(jdwp) << StringPrintf("Remove debugger as listener for instrumentation event 0x%x", 2866 request.InstrumentationEvent()); 2867 instrumentation->RemoveListener(&gDebugInstrumentationListener, 2868 request.InstrumentationEvent()); 2869 instrumentation_events_ &= ~request.InstrumentationEvent(); 2870 break; 2871 case DeoptimizationRequest::kFullDeoptimization: 2872 VLOG(jdwp) << "Deoptimize the world ..."; 2873 instrumentation->DeoptimizeEverything(); 2874 VLOG(jdwp) << "Deoptimize the world DONE"; 2875 break; 2876 case DeoptimizationRequest::kFullUndeoptimization: 2877 VLOG(jdwp) << "Undeoptimize the world ..."; 2878 instrumentation->UndeoptimizeEverything(); 2879 VLOG(jdwp) << "Undeoptimize the world DONE"; 2880 break; 2881 case DeoptimizationRequest::kSelectiveDeoptimization: 2882 VLOG(jdwp) << "Deoptimize method " << PrettyMethod(request.Method()) << " ..."; 2883 instrumentation->Deoptimize(request.Method()); 2884 VLOG(jdwp) << "Deoptimize method " << PrettyMethod(request.Method()) << " DONE"; 2885 break; 2886 case DeoptimizationRequest::kSelectiveUndeoptimization: 2887 VLOG(jdwp) << "Undeoptimize method " << PrettyMethod(request.Method()) << " ..."; 2888 instrumentation->Undeoptimize(request.Method()); 2889 VLOG(jdwp) << "Undeoptimize method " << PrettyMethod(request.Method()) << " DONE"; 2890 break; 2891 default: 2892 LOG(FATAL) << "Unsupported deoptimization request kind " << request.GetKind(); 2893 break; 2894 } 2895} 2896 2897void Dbg::DelayFullUndeoptimization() { 2898 MutexLock mu(Thread::Current(), *deoptimization_lock_); 2899 ++delayed_full_undeoptimization_count_; 2900 DCHECK_LE(delayed_full_undeoptimization_count_, full_deoptimization_event_count_); 2901} 2902 2903void Dbg::ProcessDelayedFullUndeoptimizations() { 2904 // TODO: avoid taking the lock twice (once here and once in ManageDeoptimization). 2905 { 2906 MutexLock mu(Thread::Current(), *deoptimization_lock_); 2907 while (delayed_full_undeoptimization_count_ > 0) { 2908 DeoptimizationRequest req; 2909 req.SetKind(DeoptimizationRequest::kFullUndeoptimization); 2910 req.SetMethod(nullptr); 2911 RequestDeoptimizationLocked(req); 2912 --delayed_full_undeoptimization_count_; 2913 } 2914 } 2915 ManageDeoptimization(); 2916} 2917 2918void Dbg::RequestDeoptimization(const DeoptimizationRequest& req) { 2919 if (req.GetKind() == DeoptimizationRequest::kNothing) { 2920 // Nothing to do. 2921 return; 2922 } 2923 MutexLock mu(Thread::Current(), *deoptimization_lock_); 2924 RequestDeoptimizationLocked(req); 2925} 2926 2927void Dbg::RequestDeoptimizationLocked(const DeoptimizationRequest& req) { 2928 switch (req.GetKind()) { 2929 case DeoptimizationRequest::kRegisterForEvent: { 2930 DCHECK_NE(req.InstrumentationEvent(), 0u); 2931 size_t* counter = GetReferenceCounterForEvent(req.InstrumentationEvent()); 2932 CHECK(counter != nullptr) << StringPrintf("No counter for instrumentation event 0x%x", 2933 req.InstrumentationEvent()); 2934 if (*counter == 0) { 2935 VLOG(jdwp) << StringPrintf("Queue request #%zd to start listening to instrumentation event 0x%x", 2936 deoptimization_requests_.size(), req.InstrumentationEvent()); 2937 deoptimization_requests_.push_back(req); 2938 } 2939 *counter = *counter + 1; 2940 break; 2941 } 2942 case DeoptimizationRequest::kUnregisterForEvent: { 2943 DCHECK_NE(req.InstrumentationEvent(), 0u); 2944 size_t* counter = GetReferenceCounterForEvent(req.InstrumentationEvent()); 2945 CHECK(counter != nullptr) << StringPrintf("No counter for instrumentation event 0x%x", 2946 req.InstrumentationEvent()); 2947 *counter = *counter - 1; 2948 if (*counter == 0) { 2949 VLOG(jdwp) << StringPrintf("Queue request #%zd to stop listening to instrumentation event 0x%x", 2950 deoptimization_requests_.size(), req.InstrumentationEvent()); 2951 deoptimization_requests_.push_back(req); 2952 } 2953 break; 2954 } 2955 case DeoptimizationRequest::kFullDeoptimization: { 2956 DCHECK(req.Method() == nullptr); 2957 if (full_deoptimization_event_count_ == 0) { 2958 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size() 2959 << " for full deoptimization"; 2960 deoptimization_requests_.push_back(req); 2961 } 2962 ++full_deoptimization_event_count_; 2963 break; 2964 } 2965 case DeoptimizationRequest::kFullUndeoptimization: { 2966 DCHECK(req.Method() == nullptr); 2967 DCHECK_GT(full_deoptimization_event_count_, 0U); 2968 --full_deoptimization_event_count_; 2969 if (full_deoptimization_event_count_ == 0) { 2970 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size() 2971 << " for full undeoptimization"; 2972 deoptimization_requests_.push_back(req); 2973 } 2974 break; 2975 } 2976 case DeoptimizationRequest::kSelectiveDeoptimization: { 2977 DCHECK(req.Method() != nullptr); 2978 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size() 2979 << " for deoptimization of " << PrettyMethod(req.Method()); 2980 deoptimization_requests_.push_back(req); 2981 break; 2982 } 2983 case DeoptimizationRequest::kSelectiveUndeoptimization: { 2984 DCHECK(req.Method() != nullptr); 2985 VLOG(jdwp) << "Queue request #" << deoptimization_requests_.size() 2986 << " for undeoptimization of " << PrettyMethod(req.Method()); 2987 deoptimization_requests_.push_back(req); 2988 break; 2989 } 2990 default: { 2991 LOG(FATAL) << "Unknown deoptimization request kind " << req.GetKind(); 2992 break; 2993 } 2994 } 2995} 2996 2997void Dbg::ManageDeoptimization() { 2998 Thread* const self = Thread::Current(); 2999 { 3000 // Avoid suspend/resume if there is no pending request. 3001 MutexLock mu(self, *deoptimization_lock_); 3002 if (deoptimization_requests_.empty()) { 3003 return; 3004 } 3005 } 3006 CHECK_EQ(self->GetState(), kRunnable); 3007 self->TransitionFromRunnableToSuspended(kWaitingForDeoptimization); 3008 // We need to suspend mutator threads first. 3009 Runtime* const runtime = Runtime::Current(); 3010 runtime->GetThreadList()->SuspendAll(); 3011 const ThreadState old_state = self->SetStateUnsafe(kRunnable); 3012 { 3013 MutexLock mu(self, *deoptimization_lock_); 3014 size_t req_index = 0; 3015 for (DeoptimizationRequest& request : deoptimization_requests_) { 3016 VLOG(jdwp) << "Process deoptimization request #" << req_index++; 3017 ProcessDeoptimizationRequest(request); 3018 } 3019 deoptimization_requests_.clear(); 3020 } 3021 CHECK_EQ(self->SetStateUnsafe(old_state), kRunnable); 3022 runtime->GetThreadList()->ResumeAll(); 3023 self->TransitionFromSuspendedToRunnable(); 3024} 3025 3026static bool IsMethodPossiblyInlined(Thread* self, mirror::ArtMethod* m) 3027 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 3028 const DexFile::CodeItem* code_item = m->GetCodeItem(); 3029 if (code_item == nullptr) { 3030 // TODO We should not be asked to watch location in a native or abstract method so the code item 3031 // should never be null. We could just check we never encounter this case. 3032 return false; 3033 } 3034 StackHandleScope<2> hs(self); 3035 mirror::Class* declaring_class = m->GetDeclaringClass(); 3036 Handle<mirror::DexCache> dex_cache(hs.NewHandle(declaring_class->GetDexCache())); 3037 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(declaring_class->GetClassLoader())); 3038 verifier::MethodVerifier verifier(dex_cache->GetDexFile(), &dex_cache, &class_loader, 3039 &m->GetClassDef(), code_item, m->GetDexMethodIndex(), m, 3040 m->GetAccessFlags(), false, true, false); 3041 // Note: we don't need to verify the method. 3042 return InlineMethodAnalyser::AnalyseMethodCode(&verifier, nullptr); 3043} 3044 3045static const Breakpoint* FindFirstBreakpointForMethod(mirror::ArtMethod* m) 3046 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::breakpoint_lock_) { 3047 for (Breakpoint& breakpoint : gBreakpoints) { 3048 if (breakpoint.Method() == m) { 3049 return &breakpoint; 3050 } 3051 } 3052 return nullptr; 3053} 3054 3055// Sanity checks all existing breakpoints on the same method. 3056static void SanityCheckExistingBreakpoints(mirror::ArtMethod* m, bool need_full_deoptimization) 3057 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::breakpoint_lock_) { 3058 if (kIsDebugBuild) { 3059 for (const Breakpoint& breakpoint : gBreakpoints) { 3060 CHECK_EQ(need_full_deoptimization, breakpoint.NeedFullDeoptimization()); 3061 } 3062 if (need_full_deoptimization) { 3063 // We should have deoptimized everything but not "selectively" deoptimized this method. 3064 CHECK(Runtime::Current()->GetInstrumentation()->AreAllMethodsDeoptimized()); 3065 CHECK(!Runtime::Current()->GetInstrumentation()->IsDeoptimized(m)); 3066 } else { 3067 // We should have "selectively" deoptimized this method. 3068 // Note: while we have not deoptimized everything for this method, we may have done it for 3069 // another event. 3070 CHECK(Runtime::Current()->GetInstrumentation()->IsDeoptimized(m)); 3071 } 3072 } 3073} 3074 3075// Installs a breakpoint at the specified location. Also indicates through the deoptimization 3076// request if we need to deoptimize. 3077void Dbg::WatchLocation(const JDWP::JdwpLocation* location, DeoptimizationRequest* req) { 3078 Thread* const self = Thread::Current(); 3079 mirror::ArtMethod* m = FromMethodId(location->method_id); 3080 DCHECK(m != nullptr) << "No method for method id " << location->method_id; 3081 3082 WriterMutexLock mu(self, *Locks::breakpoint_lock_); 3083 const Breakpoint* const existing_breakpoint = FindFirstBreakpointForMethod(m); 3084 bool need_full_deoptimization; 3085 if (existing_breakpoint == nullptr) { 3086 // There is no breakpoint on this method yet: we need to deoptimize. If this method may be 3087 // inlined, we deoptimize everything; otherwise we deoptimize only this method. 3088 need_full_deoptimization = IsMethodPossiblyInlined(self, m); 3089 if (need_full_deoptimization) { 3090 req->SetKind(DeoptimizationRequest::kFullDeoptimization); 3091 req->SetMethod(nullptr); 3092 } else { 3093 req->SetKind(DeoptimizationRequest::kSelectiveDeoptimization); 3094 req->SetMethod(m); 3095 } 3096 } else { 3097 // There is at least one breakpoint for this method: we don't need to deoptimize. 3098 req->SetKind(DeoptimizationRequest::kNothing); 3099 req->SetMethod(nullptr); 3100 3101 need_full_deoptimization = existing_breakpoint->NeedFullDeoptimization(); 3102 SanityCheckExistingBreakpoints(m, need_full_deoptimization); 3103 } 3104 3105 gBreakpoints.push_back(Breakpoint(m, location->dex_pc, need_full_deoptimization)); 3106 VLOG(jdwp) << "Set breakpoint #" << (gBreakpoints.size() - 1) << ": " 3107 << gBreakpoints[gBreakpoints.size() - 1]; 3108} 3109 3110// Uninstalls a breakpoint at the specified location. Also indicates through the deoptimization 3111// request if we need to undeoptimize. 3112void Dbg::UnwatchLocation(const JDWP::JdwpLocation* location, DeoptimizationRequest* req) { 3113 WriterMutexLock mu(Thread::Current(), *Locks::breakpoint_lock_); 3114 mirror::ArtMethod* m = FromMethodId(location->method_id); 3115 DCHECK(m != nullptr) << "No method for method id " << location->method_id; 3116 bool need_full_deoptimization = false; 3117 for (size_t i = 0, e = gBreakpoints.size(); i < e; ++i) { 3118 if (gBreakpoints[i].DexPc() == location->dex_pc && gBreakpoints[i].Method() == m) { 3119 VLOG(jdwp) << "Removed breakpoint #" << i << ": " << gBreakpoints[i]; 3120 need_full_deoptimization = gBreakpoints[i].NeedFullDeoptimization(); 3121 DCHECK_NE(need_full_deoptimization, Runtime::Current()->GetInstrumentation()->IsDeoptimized(m)); 3122 gBreakpoints.erase(gBreakpoints.begin() + i); 3123 break; 3124 } 3125 } 3126 const Breakpoint* const existing_breakpoint = FindFirstBreakpointForMethod(m); 3127 if (existing_breakpoint == nullptr) { 3128 // There is no more breakpoint on this method: we need to undeoptimize. 3129 if (need_full_deoptimization) { 3130 // This method required full deoptimization: we need to undeoptimize everything. 3131 req->SetKind(DeoptimizationRequest::kFullUndeoptimization); 3132 req->SetMethod(nullptr); 3133 } else { 3134 // This method required selective deoptimization: we need to undeoptimize only that method. 3135 req->SetKind(DeoptimizationRequest::kSelectiveUndeoptimization); 3136 req->SetMethod(m); 3137 } 3138 } else { 3139 // There is at least one breakpoint for this method: we don't need to undeoptimize. 3140 req->SetKind(DeoptimizationRequest::kNothing); 3141 req->SetMethod(nullptr); 3142 SanityCheckExistingBreakpoints(m, need_full_deoptimization); 3143 } 3144} 3145 3146// Scoped utility class to suspend a thread so that we may do tasks such as walk its stack. Doesn't 3147// cause suspension if the thread is the current thread. 3148class ScopedThreadSuspension { 3149 public: 3150 ScopedThreadSuspension(Thread* self, JDWP::ObjectId thread_id) 3151 LOCKS_EXCLUDED(Locks::thread_list_lock_) 3152 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) : 3153 thread_(nullptr), 3154 error_(JDWP::ERR_NONE), 3155 self_suspend_(false), 3156 other_suspend_(false) { 3157 ScopedObjectAccessUnchecked soa(self); 3158 { 3159 MutexLock mu(soa.Self(), *Locks::thread_list_lock_); 3160 error_ = DecodeThread(soa, thread_id, thread_); 3161 } 3162 if (error_ == JDWP::ERR_NONE) { 3163 if (thread_ == soa.Self()) { 3164 self_suspend_ = true; 3165 } else { 3166 soa.Self()->TransitionFromRunnableToSuspended(kWaitingForDebuggerSuspension); 3167 jobject thread_peer = gRegistry->GetJObject(thread_id); 3168 bool timed_out; 3169 Thread* suspended_thread; 3170 { 3171 // Take suspend thread lock to avoid races with threads trying to suspend this one. 3172 MutexLock mu(soa.Self(), *Locks::thread_list_suspend_thread_lock_); 3173 suspended_thread = ThreadList::SuspendThreadByPeer(thread_peer, true, true, 3174 &timed_out); 3175 } 3176 CHECK_EQ(soa.Self()->TransitionFromSuspendedToRunnable(), kWaitingForDebuggerSuspension); 3177 if (suspended_thread == nullptr) { 3178 // Thread terminated from under us while suspending. 3179 error_ = JDWP::ERR_INVALID_THREAD; 3180 } else { 3181 CHECK_EQ(suspended_thread, thread_); 3182 other_suspend_ = true; 3183 } 3184 } 3185 } 3186 } 3187 3188 Thread* GetThread() const { 3189 return thread_; 3190 } 3191 3192 JDWP::JdwpError GetError() const { 3193 return error_; 3194 } 3195 3196 ~ScopedThreadSuspension() { 3197 if (other_suspend_) { 3198 Runtime::Current()->GetThreadList()->Resume(thread_, true); 3199 } 3200 } 3201 3202 private: 3203 Thread* thread_; 3204 JDWP::JdwpError error_; 3205 bool self_suspend_; 3206 bool other_suspend_; 3207}; 3208 3209JDWP::JdwpError Dbg::ConfigureStep(JDWP::ObjectId thread_id, JDWP::JdwpStepSize step_size, 3210 JDWP::JdwpStepDepth step_depth) { 3211 Thread* self = Thread::Current(); 3212 ScopedThreadSuspension sts(self, thread_id); 3213 if (sts.GetError() != JDWP::ERR_NONE) { 3214 return sts.GetError(); 3215 } 3216 3217 // 3218 // Work out what Method* we're in, the current line number, and how deep the stack currently 3219 // is for step-out. 3220 // 3221 3222 struct SingleStepStackVisitor : public StackVisitor { 3223 explicit SingleStepStackVisitor(Thread* thread, SingleStepControl* single_step_control, 3224 int32_t* line_number) 3225 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) 3226 : StackVisitor(thread, NULL), single_step_control_(single_step_control), 3227 line_number_(line_number) { 3228 DCHECK_EQ(single_step_control_, thread->GetSingleStepControl()); 3229 single_step_control_->method = NULL; 3230 single_step_control_->stack_depth = 0; 3231 } 3232 3233 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses 3234 // annotalysis. 3235 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS { 3236 mirror::ArtMethod* m = GetMethod(); 3237 if (!m->IsRuntimeMethod()) { 3238 ++single_step_control_->stack_depth; 3239 if (single_step_control_->method == NULL) { 3240 mirror::DexCache* dex_cache = m->GetDeclaringClass()->GetDexCache(); 3241 single_step_control_->method = m; 3242 *line_number_ = -1; 3243 if (dex_cache != NULL) { 3244 const DexFile& dex_file = *dex_cache->GetDexFile(); 3245 *line_number_ = dex_file.GetLineNumFromPC(m, GetDexPc()); 3246 } 3247 } 3248 } 3249 return true; 3250 } 3251 3252 SingleStepControl* const single_step_control_; 3253 int32_t* const line_number_; 3254 }; 3255 3256 Thread* const thread = sts.GetThread(); 3257 SingleStepControl* const single_step_control = thread->GetSingleStepControl(); 3258 DCHECK(single_step_control != nullptr); 3259 int32_t line_number = -1; 3260 SingleStepStackVisitor visitor(thread, single_step_control, &line_number); 3261 visitor.WalkStack(); 3262 3263 // 3264 // Find the dex_pc values that correspond to the current line, for line-based single-stepping. 3265 // 3266 3267 struct DebugCallbackContext { 3268 explicit DebugCallbackContext(SingleStepControl* single_step_control, int32_t line_number, 3269 const DexFile::CodeItem* code_item) 3270 : single_step_control_(single_step_control), line_number_(line_number), code_item_(code_item), 3271 last_pc_valid(false), last_pc(0) { 3272 } 3273 3274 static bool Callback(void* raw_context, uint32_t address, uint32_t line_number) { 3275 DebugCallbackContext* context = reinterpret_cast<DebugCallbackContext*>(raw_context); 3276 if (static_cast<int32_t>(line_number) == context->line_number_) { 3277 if (!context->last_pc_valid) { 3278 // Everything from this address until the next line change is ours. 3279 context->last_pc = address; 3280 context->last_pc_valid = true; 3281 } 3282 // Otherwise, if we're already in a valid range for this line, 3283 // just keep going (shouldn't really happen)... 3284 } else if (context->last_pc_valid) { // and the line number is new 3285 // Add everything from the last entry up until here to the set 3286 for (uint32_t dex_pc = context->last_pc; dex_pc < address; ++dex_pc) { 3287 context->single_step_control_->dex_pcs.insert(dex_pc); 3288 } 3289 context->last_pc_valid = false; 3290 } 3291 return false; // There may be multiple entries for any given line. 3292 } 3293 3294 ~DebugCallbackContext() { 3295 // If the line number was the last in the position table... 3296 if (last_pc_valid) { 3297 size_t end = code_item_->insns_size_in_code_units_; 3298 for (uint32_t dex_pc = last_pc; dex_pc < end; ++dex_pc) { 3299 single_step_control_->dex_pcs.insert(dex_pc); 3300 } 3301 } 3302 } 3303 3304 SingleStepControl* const single_step_control_; 3305 const int32_t line_number_; 3306 const DexFile::CodeItem* const code_item_; 3307 bool last_pc_valid; 3308 uint32_t last_pc; 3309 }; 3310 single_step_control->dex_pcs.clear(); 3311 mirror::ArtMethod* m = single_step_control->method; 3312 if (!m->IsNative()) { 3313 const DexFile::CodeItem* const code_item = m->GetCodeItem(); 3314 DebugCallbackContext context(single_step_control, line_number, code_item); 3315 m->GetDexFile()->DecodeDebugInfo(code_item, m->IsStatic(), m->GetDexMethodIndex(), 3316 DebugCallbackContext::Callback, NULL, &context); 3317 } 3318 3319 // 3320 // Everything else... 3321 // 3322 3323 single_step_control->step_size = step_size; 3324 single_step_control->step_depth = step_depth; 3325 single_step_control->is_active = true; 3326 3327 if (VLOG_IS_ON(jdwp)) { 3328 VLOG(jdwp) << "Single-step thread: " << *thread; 3329 VLOG(jdwp) << "Single-step step size: " << single_step_control->step_size; 3330 VLOG(jdwp) << "Single-step step depth: " << single_step_control->step_depth; 3331 VLOG(jdwp) << "Single-step current method: " << PrettyMethod(single_step_control->method); 3332 VLOG(jdwp) << "Single-step current line: " << line_number; 3333 VLOG(jdwp) << "Single-step current stack depth: " << single_step_control->stack_depth; 3334 VLOG(jdwp) << "Single-step dex_pc values:"; 3335 for (uint32_t dex_pc : single_step_control->dex_pcs) { 3336 VLOG(jdwp) << StringPrintf(" %#x", dex_pc); 3337 } 3338 } 3339 3340 return JDWP::ERR_NONE; 3341} 3342 3343void Dbg::UnconfigureStep(JDWP::ObjectId thread_id) { 3344 ScopedObjectAccessUnchecked soa(Thread::Current()); 3345 MutexLock mu(soa.Self(), *Locks::thread_list_lock_); 3346 Thread* thread; 3347 JDWP::JdwpError error = DecodeThread(soa, thread_id, thread); 3348 if (error == JDWP::ERR_NONE) { 3349 SingleStepControl* single_step_control = thread->GetSingleStepControl(); 3350 DCHECK(single_step_control != nullptr); 3351 single_step_control->Clear(); 3352 } 3353} 3354 3355static char JdwpTagToShortyChar(JDWP::JdwpTag tag) { 3356 switch (tag) { 3357 default: 3358 LOG(FATAL) << "unknown JDWP tag: " << PrintableChar(tag); 3359 3360 // Primitives. 3361 case JDWP::JT_BYTE: return 'B'; 3362 case JDWP::JT_CHAR: return 'C'; 3363 case JDWP::JT_FLOAT: return 'F'; 3364 case JDWP::JT_DOUBLE: return 'D'; 3365 case JDWP::JT_INT: return 'I'; 3366 case JDWP::JT_LONG: return 'J'; 3367 case JDWP::JT_SHORT: return 'S'; 3368 case JDWP::JT_VOID: return 'V'; 3369 case JDWP::JT_BOOLEAN: return 'Z'; 3370 3371 // Reference types. 3372 case JDWP::JT_ARRAY: 3373 case JDWP::JT_OBJECT: 3374 case JDWP::JT_STRING: 3375 case JDWP::JT_THREAD: 3376 case JDWP::JT_THREAD_GROUP: 3377 case JDWP::JT_CLASS_LOADER: 3378 case JDWP::JT_CLASS_OBJECT: 3379 return 'L'; 3380 } 3381} 3382 3383JDWP::JdwpError Dbg::InvokeMethod(JDWP::ObjectId thread_id, JDWP::ObjectId object_id, 3384 JDWP::RefTypeId class_id, JDWP::MethodId method_id, 3385 uint32_t arg_count, uint64_t* arg_values, 3386 JDWP::JdwpTag* arg_types, uint32_t options, 3387 JDWP::JdwpTag* pResultTag, uint64_t* pResultValue, 3388 JDWP::ObjectId* pExceptionId) { 3389 ThreadList* thread_list = Runtime::Current()->GetThreadList(); 3390 3391 Thread* targetThread = NULL; 3392 DebugInvokeReq* req = NULL; 3393 Thread* self = Thread::Current(); 3394 { 3395 ScopedObjectAccessUnchecked soa(self); 3396 MutexLock mu(soa.Self(), *Locks::thread_list_lock_); 3397 JDWP::JdwpError error = DecodeThread(soa, thread_id, targetThread); 3398 if (error != JDWP::ERR_NONE) { 3399 LOG(ERROR) << "InvokeMethod request for invalid thread id " << thread_id; 3400 return error; 3401 } 3402 req = targetThread->GetInvokeReq(); 3403 if (!req->ready) { 3404 LOG(ERROR) << "InvokeMethod request for thread not stopped by event: " << *targetThread; 3405 return JDWP::ERR_INVALID_THREAD; 3406 } 3407 3408 /* 3409 * We currently have a bug where we don't successfully resume the 3410 * target thread if the suspend count is too deep. We're expected to 3411 * require one "resume" for each "suspend", but when asked to execute 3412 * a method we have to resume fully and then re-suspend it back to the 3413 * same level. (The easiest way to cause this is to type "suspend" 3414 * multiple times in jdb.) 3415 * 3416 * It's unclear what this means when the event specifies "resume all" 3417 * and some threads are suspended more deeply than others. This is 3418 * a rare problem, so for now we just prevent it from hanging forever 3419 * by rejecting the method invocation request. Without this, we will 3420 * be stuck waiting on a suspended thread. 3421 */ 3422 int suspend_count; 3423 { 3424 MutexLock mu2(soa.Self(), *Locks::thread_suspend_count_lock_); 3425 suspend_count = targetThread->GetSuspendCount(); 3426 } 3427 if (suspend_count > 1) { 3428 LOG(ERROR) << *targetThread << " suspend count too deep for method invocation: " << suspend_count; 3429 return JDWP::ERR_THREAD_SUSPENDED; // Probably not expected here. 3430 } 3431 3432 JDWP::JdwpError status; 3433 mirror::Object* receiver = gRegistry->Get<mirror::Object*>(object_id); 3434 if (receiver == ObjectRegistry::kInvalidObject) { 3435 return JDWP::ERR_INVALID_OBJECT; 3436 } 3437 3438 mirror::Object* thread = gRegistry->Get<mirror::Object*>(thread_id); 3439 if (thread == ObjectRegistry::kInvalidObject) { 3440 return JDWP::ERR_INVALID_OBJECT; 3441 } 3442 // TODO: check that 'thread' is actually a java.lang.Thread! 3443 3444 mirror::Class* c = DecodeClass(class_id, status); 3445 if (c == NULL) { 3446 return status; 3447 } 3448 3449 mirror::ArtMethod* m = FromMethodId(method_id); 3450 if (m->IsStatic() != (receiver == NULL)) { 3451 return JDWP::ERR_INVALID_METHODID; 3452 } 3453 if (m->IsStatic()) { 3454 if (m->GetDeclaringClass() != c) { 3455 return JDWP::ERR_INVALID_METHODID; 3456 } 3457 } else { 3458 if (!m->GetDeclaringClass()->IsAssignableFrom(c)) { 3459 return JDWP::ERR_INVALID_METHODID; 3460 } 3461 } 3462 3463 // Check the argument list matches the method. 3464 uint32_t shorty_len = 0; 3465 const char* shorty = m->GetShorty(&shorty_len); 3466 if (shorty_len - 1 != arg_count) { 3467 return JDWP::ERR_ILLEGAL_ARGUMENT; 3468 } 3469 3470 { 3471 StackHandleScope<3> hs(soa.Self()); 3472 MethodHelper mh(hs.NewHandle(m)); 3473 HandleWrapper<mirror::Object> h_obj(hs.NewHandleWrapper(&receiver)); 3474 HandleWrapper<mirror::Class> h_klass(hs.NewHandleWrapper(&c)); 3475 const DexFile::TypeList* types = m->GetParameterTypeList(); 3476 for (size_t i = 0; i < arg_count; ++i) { 3477 if (shorty[i + 1] != JdwpTagToShortyChar(arg_types[i])) { 3478 return JDWP::ERR_ILLEGAL_ARGUMENT; 3479 } 3480 3481 if (shorty[i + 1] == 'L') { 3482 // Did we really get an argument of an appropriate reference type? 3483 mirror::Class* parameter_type = mh.GetClassFromTypeIdx(types->GetTypeItem(i).type_idx_); 3484 mirror::Object* argument = gRegistry->Get<mirror::Object*>(arg_values[i]); 3485 if (argument == ObjectRegistry::kInvalidObject) { 3486 return JDWP::ERR_INVALID_OBJECT; 3487 } 3488 if (argument != NULL && !argument->InstanceOf(parameter_type)) { 3489 return JDWP::ERR_ILLEGAL_ARGUMENT; 3490 } 3491 3492 // Turn the on-the-wire ObjectId into a jobject. 3493 jvalue& v = reinterpret_cast<jvalue&>(arg_values[i]); 3494 v.l = gRegistry->GetJObject(arg_values[i]); 3495 } 3496 } 3497 // Update in case it moved. 3498 m = mh.GetMethod(); 3499 } 3500 3501 req->receiver = receiver; 3502 req->thread = thread; 3503 req->klass = c; 3504 req->method = m; 3505 req->arg_count = arg_count; 3506 req->arg_values = arg_values; 3507 req->options = options; 3508 req->invoke_needed = true; 3509 } 3510 3511 // The fact that we've released the thread list lock is a bit risky --- if the thread goes 3512 // away we're sitting high and dry -- but we must release this before the ResumeAllThreads 3513 // call, and it's unwise to hold it during WaitForSuspend. 3514 3515 { 3516 /* 3517 * We change our (JDWP thread) status, which should be THREAD_RUNNING, 3518 * so we can suspend for a GC if the invoke request causes us to 3519 * run out of memory. It's also a good idea to change it before locking 3520 * the invokeReq mutex, although that should never be held for long. 3521 */ 3522 self->TransitionFromRunnableToSuspended(kWaitingForDebuggerSend); 3523 3524 VLOG(jdwp) << " Transferring control to event thread"; 3525 { 3526 MutexLock mu(self, req->lock); 3527 3528 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) { 3529 VLOG(jdwp) << " Resuming all threads"; 3530 thread_list->UndoDebuggerSuspensions(); 3531 } else { 3532 VLOG(jdwp) << " Resuming event thread only"; 3533 thread_list->Resume(targetThread, true); 3534 } 3535 3536 // Wait for the request to finish executing. 3537 while (req->invoke_needed) { 3538 req->cond.Wait(self); 3539 } 3540 } 3541 VLOG(jdwp) << " Control has returned from event thread"; 3542 3543 /* wait for thread to re-suspend itself */ 3544 SuspendThread(thread_id, false /* request_suspension */); 3545 self->TransitionFromSuspendedToRunnable(); 3546 } 3547 3548 /* 3549 * Suspend the threads. We waited for the target thread to suspend 3550 * itself, so all we need to do is suspend the others. 3551 * 3552 * The suspendAllThreads() call will double-suspend the event thread, 3553 * so we want to resume the target thread once to keep the books straight. 3554 */ 3555 if ((options & JDWP::INVOKE_SINGLE_THREADED) == 0) { 3556 self->TransitionFromRunnableToSuspended(kWaitingForDebuggerSuspension); 3557 VLOG(jdwp) << " Suspending all threads"; 3558 thread_list->SuspendAllForDebugger(); 3559 self->TransitionFromSuspendedToRunnable(); 3560 VLOG(jdwp) << " Resuming event thread to balance the count"; 3561 thread_list->Resume(targetThread, true); 3562 } 3563 3564 // Copy the result. 3565 *pResultTag = req->result_tag; 3566 if (IsPrimitiveTag(req->result_tag)) { 3567 *pResultValue = req->result_value.GetJ(); 3568 } else { 3569 *pResultValue = gRegistry->Add(req->result_value.GetL()); 3570 } 3571 *pExceptionId = req->exception; 3572 return req->error; 3573} 3574 3575void Dbg::ExecuteMethod(DebugInvokeReq* pReq) { 3576 ScopedObjectAccess soa(Thread::Current()); 3577 3578 // We can be called while an exception is pending. We need 3579 // to preserve that across the method invocation. 3580 StackHandleScope<4> hs(soa.Self()); 3581 auto old_throw_this_object = hs.NewHandle<mirror::Object>(nullptr); 3582 auto old_throw_method = hs.NewHandle<mirror::ArtMethod>(nullptr); 3583 auto old_exception = hs.NewHandle<mirror::Throwable>(nullptr); 3584 uint32_t old_throw_dex_pc; 3585 bool old_exception_report_flag; 3586 { 3587 ThrowLocation old_throw_location; 3588 mirror::Throwable* old_exception_obj = soa.Self()->GetException(&old_throw_location); 3589 old_throw_this_object.Assign(old_throw_location.GetThis()); 3590 old_throw_method.Assign(old_throw_location.GetMethod()); 3591 old_exception.Assign(old_exception_obj); 3592 old_throw_dex_pc = old_throw_location.GetDexPc(); 3593 old_exception_report_flag = soa.Self()->IsExceptionReportedToInstrumentation(); 3594 soa.Self()->ClearException(); 3595 } 3596 3597 // Translate the method through the vtable, unless the debugger wants to suppress it. 3598 Handle<mirror::ArtMethod> m(hs.NewHandle(pReq->method)); 3599 if ((pReq->options & JDWP::INVOKE_NONVIRTUAL) == 0 && pReq->receiver != NULL) { 3600 mirror::ArtMethod* actual_method = pReq->klass->FindVirtualMethodForVirtualOrInterface(m.Get()); 3601 if (actual_method != m.Get()) { 3602 VLOG(jdwp) << "ExecuteMethod translated " << PrettyMethod(m.Get()) << " to " << PrettyMethod(actual_method); 3603 m.Assign(actual_method); 3604 } 3605 } 3606 VLOG(jdwp) << "ExecuteMethod " << PrettyMethod(m.Get()) 3607 << " receiver=" << pReq->receiver 3608 << " arg_count=" << pReq->arg_count; 3609 CHECK(m.Get() != nullptr); 3610 3611 CHECK_EQ(sizeof(jvalue), sizeof(uint64_t)); 3612 3613 pReq->result_value = InvokeWithJValues(soa, pReq->receiver, soa.EncodeMethod(m.Get()), 3614 reinterpret_cast<jvalue*>(pReq->arg_values)); 3615 3616 mirror::Throwable* exception = soa.Self()->GetException(NULL); 3617 soa.Self()->ClearException(); 3618 pReq->exception = gRegistry->Add(exception); 3619 pReq->result_tag = BasicTagFromDescriptor(m.Get()->GetShorty()); 3620 if (pReq->exception != 0) { 3621 VLOG(jdwp) << " JDWP invocation returning with exception=" << exception 3622 << " " << exception->Dump(); 3623 pReq->result_value.SetJ(0); 3624 } else if (pReq->result_tag == JDWP::JT_OBJECT) { 3625 /* if no exception thrown, examine object result more closely */ 3626 JDWP::JdwpTag new_tag = TagFromObject(soa, pReq->result_value.GetL()); 3627 if (new_tag != pReq->result_tag) { 3628 VLOG(jdwp) << " JDWP promoted result from " << pReq->result_tag << " to " << new_tag; 3629 pReq->result_tag = new_tag; 3630 } 3631 3632 /* 3633 * Register the object. We don't actually need an ObjectId yet, 3634 * but we do need to be sure that the GC won't move or discard the 3635 * object when we switch out of RUNNING. The ObjectId conversion 3636 * will add the object to the "do not touch" list. 3637 * 3638 * We can't use the "tracked allocation" mechanism here because 3639 * the object is going to be handed off to a different thread. 3640 */ 3641 gRegistry->Add(pReq->result_value.GetL()); 3642 } 3643 3644 if (old_exception.Get() != NULL) { 3645 ThrowLocation gc_safe_throw_location(old_throw_this_object.Get(), old_throw_method.Get(), 3646 old_throw_dex_pc); 3647 soa.Self()->SetException(gc_safe_throw_location, old_exception.Get()); 3648 soa.Self()->SetExceptionReportedToInstrumentation(old_exception_report_flag); 3649 } 3650} 3651 3652/* 3653 * "request" contains a full JDWP packet, possibly with multiple chunks. We 3654 * need to process each, accumulate the replies, and ship the whole thing 3655 * back. 3656 * 3657 * Returns "true" if we have a reply. The reply buffer is newly allocated, 3658 * and includes the chunk type/length, followed by the data. 3659 * 3660 * OLD-TODO: we currently assume that the request and reply include a single 3661 * chunk. If this becomes inconvenient we will need to adapt. 3662 */ 3663bool Dbg::DdmHandlePacket(JDWP::Request& request, uint8_t** pReplyBuf, int* pReplyLen) { 3664 Thread* self = Thread::Current(); 3665 JNIEnv* env = self->GetJniEnv(); 3666 3667 uint32_t type = request.ReadUnsigned32("type"); 3668 uint32_t length = request.ReadUnsigned32("length"); 3669 3670 // Create a byte[] corresponding to 'request'. 3671 size_t request_length = request.size(); 3672 ScopedLocalRef<jbyteArray> dataArray(env, env->NewByteArray(request_length)); 3673 if (dataArray.get() == NULL) { 3674 LOG(WARNING) << "byte[] allocation failed: " << request_length; 3675 env->ExceptionClear(); 3676 return false; 3677 } 3678 env->SetByteArrayRegion(dataArray.get(), 0, request_length, reinterpret_cast<const jbyte*>(request.data())); 3679 request.Skip(request_length); 3680 3681 // Run through and find all chunks. [Currently just find the first.] 3682 ScopedByteArrayRO contents(env, dataArray.get()); 3683 if (length != request_length) { 3684 LOG(WARNING) << StringPrintf("bad chunk found (len=%u pktLen=%zd)", length, request_length); 3685 return false; 3686 } 3687 3688 // Call "private static Chunk dispatch(int type, byte[] data, int offset, int length)". 3689 ScopedLocalRef<jobject> chunk(env, env->CallStaticObjectMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer, 3690 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_dispatch, 3691 type, dataArray.get(), 0, length)); 3692 if (env->ExceptionCheck()) { 3693 LOG(INFO) << StringPrintf("Exception thrown by dispatcher for 0x%08x", type); 3694 env->ExceptionDescribe(); 3695 env->ExceptionClear(); 3696 return false; 3697 } 3698 3699 if (chunk.get() == NULL) { 3700 return false; 3701 } 3702 3703 /* 3704 * Pull the pieces out of the chunk. We copy the results into a 3705 * newly-allocated buffer that the caller can free. We don't want to 3706 * continue using the Chunk object because nothing has a reference to it. 3707 * 3708 * We could avoid this by returning type/data/offset/length and having 3709 * the caller be aware of the object lifetime issues, but that 3710 * integrates the JDWP code more tightly into the rest of the runtime, and doesn't work 3711 * if we have responses for multiple chunks. 3712 * 3713 * So we're pretty much stuck with copying data around multiple times. 3714 */ 3715 ScopedLocalRef<jbyteArray> replyData(env, reinterpret_cast<jbyteArray>(env->GetObjectField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_data))); 3716 jint offset = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_offset); 3717 length = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_length); 3718 type = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_type); 3719 3720 VLOG(jdwp) << StringPrintf("DDM reply: type=0x%08x data=%p offset=%d length=%d", type, replyData.get(), offset, length); 3721 if (length == 0 || replyData.get() == NULL) { 3722 return false; 3723 } 3724 3725 const int kChunkHdrLen = 8; 3726 uint8_t* reply = new uint8_t[length + kChunkHdrLen]; 3727 if (reply == NULL) { 3728 LOG(WARNING) << "malloc failed: " << (length + kChunkHdrLen); 3729 return false; 3730 } 3731 JDWP::Set4BE(reply + 0, type); 3732 JDWP::Set4BE(reply + 4, length); 3733 env->GetByteArrayRegion(replyData.get(), offset, length, reinterpret_cast<jbyte*>(reply + kChunkHdrLen)); 3734 3735 *pReplyBuf = reply; 3736 *pReplyLen = length + kChunkHdrLen; 3737 3738 VLOG(jdwp) << StringPrintf("dvmHandleDdm returning type=%.4s %p len=%d", reinterpret_cast<char*>(reply), reply, length); 3739 return true; 3740} 3741 3742void Dbg::DdmBroadcast(bool connect) { 3743 VLOG(jdwp) << "Broadcasting DDM " << (connect ? "connect" : "disconnect") << "..."; 3744 3745 Thread* self = Thread::Current(); 3746 if (self->GetState() != kRunnable) { 3747 LOG(ERROR) << "DDM broadcast in thread state " << self->GetState(); 3748 /* try anyway? */ 3749 } 3750 3751 JNIEnv* env = self->GetJniEnv(); 3752 jint event = connect ? 1 /*DdmServer.CONNECTED*/ : 2 /*DdmServer.DISCONNECTED*/; 3753 env->CallStaticVoidMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer, 3754 WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_broadcast, 3755 event); 3756 if (env->ExceptionCheck()) { 3757 LOG(ERROR) << "DdmServer.broadcast " << event << " failed"; 3758 env->ExceptionDescribe(); 3759 env->ExceptionClear(); 3760 } 3761} 3762 3763void Dbg::DdmConnected() { 3764 Dbg::DdmBroadcast(true); 3765} 3766 3767void Dbg::DdmDisconnected() { 3768 Dbg::DdmBroadcast(false); 3769 gDdmThreadNotification = false; 3770} 3771 3772/* 3773 * Send a notification when a thread starts, stops, or changes its name. 3774 * 3775 * Because we broadcast the full set of threads when the notifications are 3776 * first enabled, it's possible for "thread" to be actively executing. 3777 */ 3778void Dbg::DdmSendThreadNotification(Thread* t, uint32_t type) { 3779 if (!gDdmThreadNotification) { 3780 return; 3781 } 3782 3783 if (type == CHUNK_TYPE("THDE")) { 3784 uint8_t buf[4]; 3785 JDWP::Set4BE(&buf[0], t->GetThreadId()); 3786 Dbg::DdmSendChunk(CHUNK_TYPE("THDE"), 4, buf); 3787 } else { 3788 CHECK(type == CHUNK_TYPE("THCR") || type == CHUNK_TYPE("THNM")) << type; 3789 ScopedObjectAccessUnchecked soa(Thread::Current()); 3790 StackHandleScope<1> hs(soa.Self()); 3791 Handle<mirror::String> name(hs.NewHandle(t->GetThreadName(soa))); 3792 size_t char_count = (name.Get() != NULL) ? name->GetLength() : 0; 3793 const jchar* chars = (name.Get() != NULL) ? name->GetCharArray()->GetData() : NULL; 3794 3795 std::vector<uint8_t> bytes; 3796 JDWP::Append4BE(bytes, t->GetThreadId()); 3797 JDWP::AppendUtf16BE(bytes, chars, char_count); 3798 CHECK_EQ(bytes.size(), char_count*2 + sizeof(uint32_t)*2); 3799 Dbg::DdmSendChunk(type, bytes); 3800 } 3801} 3802 3803void Dbg::DdmSetThreadNotification(bool enable) { 3804 // Enable/disable thread notifications. 3805 gDdmThreadNotification = enable; 3806 if (enable) { 3807 // Suspend the VM then post thread start notifications for all threads. Threads attaching will 3808 // see a suspension in progress and block until that ends. They then post their own start 3809 // notification. 3810 SuspendVM(); 3811 std::list<Thread*> threads; 3812 Thread* self = Thread::Current(); 3813 { 3814 MutexLock mu(self, *Locks::thread_list_lock_); 3815 threads = Runtime::Current()->GetThreadList()->GetList(); 3816 } 3817 { 3818 ScopedObjectAccess soa(self); 3819 for (Thread* thread : threads) { 3820 Dbg::DdmSendThreadNotification(thread, CHUNK_TYPE("THCR")); 3821 } 3822 } 3823 ResumeVM(); 3824 } 3825} 3826 3827void Dbg::PostThreadStartOrStop(Thread* t, uint32_t type) { 3828 if (IsDebuggerActive()) { 3829 ScopedObjectAccessUnchecked soa(Thread::Current()); 3830 JDWP::ObjectId id = gRegistry->Add(t->GetPeer()); 3831 gJdwpState->PostThreadChange(id, type == CHUNK_TYPE("THCR")); 3832 } 3833 Dbg::DdmSendThreadNotification(t, type); 3834} 3835 3836void Dbg::PostThreadStart(Thread* t) { 3837 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THCR")); 3838} 3839 3840void Dbg::PostThreadDeath(Thread* t) { 3841 Dbg::PostThreadStartOrStop(t, CHUNK_TYPE("THDE")); 3842} 3843 3844void Dbg::DdmSendChunk(uint32_t type, size_t byte_count, const uint8_t* buf) { 3845 CHECK(buf != NULL); 3846 iovec vec[1]; 3847 vec[0].iov_base = reinterpret_cast<void*>(const_cast<uint8_t*>(buf)); 3848 vec[0].iov_len = byte_count; 3849 Dbg::DdmSendChunkV(type, vec, 1); 3850} 3851 3852void Dbg::DdmSendChunk(uint32_t type, const std::vector<uint8_t>& bytes) { 3853 DdmSendChunk(type, bytes.size(), &bytes[0]); 3854} 3855 3856void Dbg::DdmSendChunkV(uint32_t type, const iovec* iov, int iov_count) { 3857 if (gJdwpState == NULL) { 3858 VLOG(jdwp) << "Debugger thread not active, ignoring DDM send: " << type; 3859 } else { 3860 gJdwpState->DdmSendChunkV(type, iov, iov_count); 3861 } 3862} 3863 3864int Dbg::DdmHandleHpifChunk(HpifWhen when) { 3865 if (when == HPIF_WHEN_NOW) { 3866 DdmSendHeapInfo(when); 3867 return true; 3868 } 3869 3870 if (when != HPIF_WHEN_NEVER && when != HPIF_WHEN_NEXT_GC && when != HPIF_WHEN_EVERY_GC) { 3871 LOG(ERROR) << "invalid HpifWhen value: " << static_cast<int>(when); 3872 return false; 3873 } 3874 3875 gDdmHpifWhen = when; 3876 return true; 3877} 3878 3879bool Dbg::DdmHandleHpsgNhsgChunk(Dbg::HpsgWhen when, Dbg::HpsgWhat what, bool native) { 3880 if (when != HPSG_WHEN_NEVER && when != HPSG_WHEN_EVERY_GC) { 3881 LOG(ERROR) << "invalid HpsgWhen value: " << static_cast<int>(when); 3882 return false; 3883 } 3884 3885 if (what != HPSG_WHAT_MERGED_OBJECTS && what != HPSG_WHAT_DISTINCT_OBJECTS) { 3886 LOG(ERROR) << "invalid HpsgWhat value: " << static_cast<int>(what); 3887 return false; 3888 } 3889 3890 if (native) { 3891 gDdmNhsgWhen = when; 3892 gDdmNhsgWhat = what; 3893 } else { 3894 gDdmHpsgWhen = when; 3895 gDdmHpsgWhat = what; 3896 } 3897 return true; 3898} 3899 3900void Dbg::DdmSendHeapInfo(HpifWhen reason) { 3901 // If there's a one-shot 'when', reset it. 3902 if (reason == gDdmHpifWhen) { 3903 if (gDdmHpifWhen == HPIF_WHEN_NEXT_GC) { 3904 gDdmHpifWhen = HPIF_WHEN_NEVER; 3905 } 3906 } 3907 3908 /* 3909 * Chunk HPIF (client --> server) 3910 * 3911 * Heap Info. General information about the heap, 3912 * suitable for a summary display. 3913 * 3914 * [u4]: number of heaps 3915 * 3916 * For each heap: 3917 * [u4]: heap ID 3918 * [u8]: timestamp in ms since Unix epoch 3919 * [u1]: capture reason (same as 'when' value from server) 3920 * [u4]: max heap size in bytes (-Xmx) 3921 * [u4]: current heap size in bytes 3922 * [u4]: current number of bytes allocated 3923 * [u4]: current number of objects allocated 3924 */ 3925 uint8_t heap_count = 1; 3926 gc::Heap* heap = Runtime::Current()->GetHeap(); 3927 std::vector<uint8_t> bytes; 3928 JDWP::Append4BE(bytes, heap_count); 3929 JDWP::Append4BE(bytes, 1); // Heap id (bogus; we only have one heap). 3930 JDWP::Append8BE(bytes, MilliTime()); 3931 JDWP::Append1BE(bytes, reason); 3932 JDWP::Append4BE(bytes, heap->GetMaxMemory()); // Max allowed heap size in bytes. 3933 JDWP::Append4BE(bytes, heap->GetTotalMemory()); // Current heap size in bytes. 3934 JDWP::Append4BE(bytes, heap->GetBytesAllocated()); 3935 JDWP::Append4BE(bytes, heap->GetObjectsAllocated()); 3936 CHECK_EQ(bytes.size(), 4U + (heap_count * (4 + 8 + 1 + 4 + 4 + 4 + 4))); 3937 Dbg::DdmSendChunk(CHUNK_TYPE("HPIF"), bytes); 3938} 3939 3940enum HpsgSolidity { 3941 SOLIDITY_FREE = 0, 3942 SOLIDITY_HARD = 1, 3943 SOLIDITY_SOFT = 2, 3944 SOLIDITY_WEAK = 3, 3945 SOLIDITY_PHANTOM = 4, 3946 SOLIDITY_FINALIZABLE = 5, 3947 SOLIDITY_SWEEP = 6, 3948}; 3949 3950enum HpsgKind { 3951 KIND_OBJECT = 0, 3952 KIND_CLASS_OBJECT = 1, 3953 KIND_ARRAY_1 = 2, 3954 KIND_ARRAY_2 = 3, 3955 KIND_ARRAY_4 = 4, 3956 KIND_ARRAY_8 = 5, 3957 KIND_UNKNOWN = 6, 3958 KIND_NATIVE = 7, 3959}; 3960 3961#define HPSG_PARTIAL (1<<7) 3962#define HPSG_STATE(solidity, kind) ((uint8_t)((((kind) & 0x7) << 3) | ((solidity) & 0x7))) 3963 3964class HeapChunkContext { 3965 public: 3966 // Maximum chunk size. Obtain this from the formula: 3967 // (((maximum_heap_size / ALLOCATION_UNIT_SIZE) + 255) / 256) * 2 3968 HeapChunkContext(bool merge, bool native) 3969 : buf_(16384 - 16), 3970 type_(0), 3971 merge_(merge), 3972 chunk_overhead_(0) { 3973 Reset(); 3974 if (native) { 3975 type_ = CHUNK_TYPE("NHSG"); 3976 } else { 3977 type_ = merge ? CHUNK_TYPE("HPSG") : CHUNK_TYPE("HPSO"); 3978 } 3979 } 3980 3981 ~HeapChunkContext() { 3982 if (p_ > &buf_[0]) { 3983 Flush(); 3984 } 3985 } 3986 3987 void SetChunkOverhead(size_t chunk_overhead) { 3988 chunk_overhead_ = chunk_overhead; 3989 } 3990 3991 void ResetStartOfNextChunk() { 3992 startOfNextMemoryChunk_ = nullptr; 3993 } 3994 3995 void EnsureHeader(const void* chunk_ptr) { 3996 if (!needHeader_) { 3997 return; 3998 } 3999 4000 // Start a new HPSx chunk. 4001 JDWP::Write4BE(&p_, 1); // Heap id (bogus; we only have one heap). 4002 JDWP::Write1BE(&p_, 8); // Size of allocation unit, in bytes. 4003 4004 JDWP::Write4BE(&p_, reinterpret_cast<uintptr_t>(chunk_ptr)); // virtual address of segment start. 4005 JDWP::Write4BE(&p_, 0); // offset of this piece (relative to the virtual address). 4006 // [u4]: length of piece, in allocation units 4007 // We won't know this until we're done, so save the offset and stuff in a dummy value. 4008 pieceLenField_ = p_; 4009 JDWP::Write4BE(&p_, 0x55555555); 4010 needHeader_ = false; 4011 } 4012 4013 void Flush() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 4014 if (pieceLenField_ == NULL) { 4015 // Flush immediately post Reset (maybe back-to-back Flush). Ignore. 4016 CHECK(needHeader_); 4017 return; 4018 } 4019 // Patch the "length of piece" field. 4020 CHECK_LE(&buf_[0], pieceLenField_); 4021 CHECK_LE(pieceLenField_, p_); 4022 JDWP::Set4BE(pieceLenField_, totalAllocationUnits_); 4023 4024 Dbg::DdmSendChunk(type_, p_ - &buf_[0], &buf_[0]); 4025 Reset(); 4026 } 4027 4028 static void HeapChunkCallback(void* start, void* end, size_t used_bytes, void* arg) 4029 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_, 4030 Locks::mutator_lock_) { 4031 reinterpret_cast<HeapChunkContext*>(arg)->HeapChunkCallback(start, end, used_bytes); 4032 } 4033 4034 private: 4035 enum { ALLOCATION_UNIT_SIZE = 8 }; 4036 4037 void Reset() { 4038 p_ = &buf_[0]; 4039 ResetStartOfNextChunk(); 4040 totalAllocationUnits_ = 0; 4041 needHeader_ = true; 4042 pieceLenField_ = NULL; 4043 } 4044 4045 void HeapChunkCallback(void* start, void* /*end*/, size_t used_bytes) 4046 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_, 4047 Locks::mutator_lock_) { 4048 // Note: heap call backs cannot manipulate the heap upon which they are crawling, care is taken 4049 // in the following code not to allocate memory, by ensuring buf_ is of the correct size 4050 if (used_bytes == 0) { 4051 if (start == NULL) { 4052 // Reset for start of new heap. 4053 startOfNextMemoryChunk_ = NULL; 4054 Flush(); 4055 } 4056 // Only process in use memory so that free region information 4057 // also includes dlmalloc book keeping. 4058 return; 4059 } 4060 4061 /* If we're looking at the native heap, we'll just return 4062 * (SOLIDITY_HARD, KIND_NATIVE) for all allocated chunks 4063 */ 4064 bool native = type_ == CHUNK_TYPE("NHSG"); 4065 4066 // TODO: I'm not sure using start of next chunk works well with multiple spaces. We shouldn't 4067 // count gaps inbetween spaces as free memory. 4068 if (startOfNextMemoryChunk_ != NULL) { 4069 // Transmit any pending free memory. Native free memory of 4070 // over kMaxFreeLen could be because of the use of mmaps, so 4071 // don't report. If not free memory then start a new segment. 4072 bool flush = true; 4073 if (start > startOfNextMemoryChunk_) { 4074 const size_t kMaxFreeLen = 2 * kPageSize; 4075 void* freeStart = startOfNextMemoryChunk_; 4076 void* freeEnd = start; 4077 size_t freeLen = reinterpret_cast<char*>(freeEnd) - reinterpret_cast<char*>(freeStart); 4078 if (!native || freeLen < kMaxFreeLen) { 4079 AppendChunk(HPSG_STATE(SOLIDITY_FREE, 0), freeStart, freeLen); 4080 flush = false; 4081 } 4082 } 4083 if (flush) { 4084 startOfNextMemoryChunk_ = NULL; 4085 Flush(); 4086 } 4087 } 4088 mirror::Object* obj = reinterpret_cast<mirror::Object*>(start); 4089 4090 // Determine the type of this chunk. 4091 // OLD-TODO: if context.merge, see if this chunk is different from the last chunk. 4092 // If it's the same, we should combine them. 4093 uint8_t state = ExamineObject(obj, native); 4094 AppendChunk(state, start, used_bytes + chunk_overhead_); 4095 startOfNextMemoryChunk_ = reinterpret_cast<char*>(start) + used_bytes + chunk_overhead_; 4096 } 4097 4098 void AppendChunk(uint8_t state, void* ptr, size_t length) 4099 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 4100 // Make sure there's enough room left in the buffer. 4101 // We need to use two bytes for every fractional 256 allocation units used by the chunk plus 4102 // 17 bytes for any header. 4103 size_t needed = (((length/ALLOCATION_UNIT_SIZE + 255) / 256) * 2) + 17; 4104 size_t bytesLeft = buf_.size() - (size_t)(p_ - &buf_[0]); 4105 if (bytesLeft < needed) { 4106 Flush(); 4107 } 4108 4109 bytesLeft = buf_.size() - (size_t)(p_ - &buf_[0]); 4110 if (bytesLeft < needed) { 4111 LOG(WARNING) << "Chunk is too big to transmit (chunk_len=" << length << ", " 4112 << needed << " bytes)"; 4113 return; 4114 } 4115 EnsureHeader(ptr); 4116 // Write out the chunk description. 4117 length /= ALLOCATION_UNIT_SIZE; // Convert to allocation units. 4118 totalAllocationUnits_ += length; 4119 while (length > 256) { 4120 *p_++ = state | HPSG_PARTIAL; 4121 *p_++ = 255; // length - 1 4122 length -= 256; 4123 } 4124 *p_++ = state; 4125 *p_++ = length - 1; 4126 } 4127 4128 uint8_t ExamineObject(mirror::Object* o, bool is_native_heap) 4129 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) { 4130 if (o == NULL) { 4131 return HPSG_STATE(SOLIDITY_FREE, 0); 4132 } 4133 4134 // It's an allocated chunk. Figure out what it is. 4135 4136 // If we're looking at the native heap, we'll just return 4137 // (SOLIDITY_HARD, KIND_NATIVE) for all allocated chunks. 4138 if (is_native_heap) { 4139 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE); 4140 } 4141 4142 if (!Runtime::Current()->GetHeap()->IsLiveObjectLocked(o)) { 4143 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE); 4144 } 4145 4146 mirror::Class* c = o->GetClass(); 4147 if (c == NULL) { 4148 // The object was probably just created but hasn't been initialized yet. 4149 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT); 4150 } 4151 4152 if (!Runtime::Current()->GetHeap()->IsValidObjectAddress(c)) { 4153 LOG(ERROR) << "Invalid class for managed heap object: " << o << " " << c; 4154 return HPSG_STATE(SOLIDITY_HARD, KIND_UNKNOWN); 4155 } 4156 4157 if (c->IsClassClass()) { 4158 return HPSG_STATE(SOLIDITY_HARD, KIND_CLASS_OBJECT); 4159 } 4160 4161 if (c->IsArrayClass()) { 4162 if (o->IsObjectArray()) { 4163 return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4); 4164 } 4165 switch (c->GetComponentSize()) { 4166 case 1: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_1); 4167 case 2: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_2); 4168 case 4: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4); 4169 case 8: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_8); 4170 } 4171 } 4172 4173 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT); 4174 } 4175 4176 std::vector<uint8_t> buf_; 4177 uint8_t* p_; 4178 uint8_t* pieceLenField_; 4179 void* startOfNextMemoryChunk_; 4180 size_t totalAllocationUnits_; 4181 uint32_t type_; 4182 bool merge_; 4183 bool needHeader_; 4184 size_t chunk_overhead_; 4185 4186 DISALLOW_COPY_AND_ASSIGN(HeapChunkContext); 4187}; 4188 4189static void BumpPointerSpaceCallback(mirror::Object* obj, void* arg) 4190 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) EXCLUSIVE_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) { 4191 const size_t size = RoundUp(obj->SizeOf(), kObjectAlignment); 4192 HeapChunkContext::HeapChunkCallback( 4193 obj, reinterpret_cast<void*>(reinterpret_cast<uintptr_t>(obj) + size), size, arg); 4194} 4195 4196void Dbg::DdmSendHeapSegments(bool native) { 4197 Dbg::HpsgWhen when; 4198 Dbg::HpsgWhat what; 4199 if (!native) { 4200 when = gDdmHpsgWhen; 4201 what = gDdmHpsgWhat; 4202 } else { 4203 when = gDdmNhsgWhen; 4204 what = gDdmNhsgWhat; 4205 } 4206 if (when == HPSG_WHEN_NEVER) { 4207 return; 4208 } 4209 4210 // Figure out what kind of chunks we'll be sending. 4211 CHECK(what == HPSG_WHAT_MERGED_OBJECTS || what == HPSG_WHAT_DISTINCT_OBJECTS) << static_cast<int>(what); 4212 4213 // First, send a heap start chunk. 4214 uint8_t heap_id[4]; 4215 JDWP::Set4BE(&heap_id[0], 1); // Heap id (bogus; we only have one heap). 4216 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHST") : CHUNK_TYPE("HPST"), sizeof(heap_id), heap_id); 4217 4218 Thread* self = Thread::Current(); 4219 4220 // To allow the Walk/InspectAll() below to exclusively-lock the 4221 // mutator lock, temporarily release the shared access to the 4222 // mutator lock here by transitioning to the suspended state. 4223 Locks::mutator_lock_->AssertSharedHeld(self); 4224 self->TransitionFromRunnableToSuspended(kSuspended); 4225 4226 // Send a series of heap segment chunks. 4227 HeapChunkContext context((what == HPSG_WHAT_MERGED_OBJECTS), native); 4228 if (native) { 4229#ifdef USE_DLMALLOC 4230 dlmalloc_inspect_all(HeapChunkContext::HeapChunkCallback, &context); 4231#else 4232 UNIMPLEMENTED(WARNING) << "Native heap inspection is only supported with dlmalloc"; 4233#endif 4234 } else { 4235 gc::Heap* heap = Runtime::Current()->GetHeap(); 4236 for (const auto& space : heap->GetContinuousSpaces()) { 4237 if (space->IsDlMallocSpace()) { 4238 // dlmalloc's chunk header is 2 * sizeof(size_t), but if the previous chunk is in use for an 4239 // allocation then the first sizeof(size_t) may belong to it. 4240 context.SetChunkOverhead(sizeof(size_t)); 4241 space->AsDlMallocSpace()->Walk(HeapChunkContext::HeapChunkCallback, &context); 4242 } else if (space->IsRosAllocSpace()) { 4243 context.SetChunkOverhead(0); 4244 space->AsRosAllocSpace()->Walk(HeapChunkContext::HeapChunkCallback, &context); 4245 } else if (space->IsBumpPointerSpace()) { 4246 context.SetChunkOverhead(0); 4247 ReaderMutexLock mu(self, *Locks::mutator_lock_); 4248 WriterMutexLock mu2(self, *Locks::heap_bitmap_lock_); 4249 space->AsBumpPointerSpace()->Walk(BumpPointerSpaceCallback, &context); 4250 } else { 4251 UNIMPLEMENTED(WARNING) << "Not counting objects in space " << *space; 4252 } 4253 context.ResetStartOfNextChunk(); 4254 } 4255 // Walk the large objects, these are not in the AllocSpace. 4256 context.SetChunkOverhead(0); 4257 heap->GetLargeObjectsSpace()->Walk(HeapChunkContext::HeapChunkCallback, &context); 4258 } 4259 4260 // Shared-lock the mutator lock back. 4261 self->TransitionFromSuspendedToRunnable(); 4262 Locks::mutator_lock_->AssertSharedHeld(self); 4263 4264 // Finally, send a heap end chunk. 4265 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHEN") : CHUNK_TYPE("HPEN"), sizeof(heap_id), heap_id); 4266} 4267 4268static size_t GetAllocTrackerMax() { 4269#ifdef HAVE_ANDROID_OS 4270 // Check whether there's a system property overriding the number of records. 4271 const char* propertyName = "dalvik.vm.allocTrackerMax"; 4272 char allocRecordMaxString[PROPERTY_VALUE_MAX]; 4273 if (property_get(propertyName, allocRecordMaxString, "") > 0) { 4274 char* end; 4275 size_t value = strtoul(allocRecordMaxString, &end, 10); 4276 if (*end != '\0') { 4277 LOG(ERROR) << "Ignoring " << propertyName << " '" << allocRecordMaxString 4278 << "' --- invalid"; 4279 return kDefaultNumAllocRecords; 4280 } 4281 if (!IsPowerOfTwo(value)) { 4282 LOG(ERROR) << "Ignoring " << propertyName << " '" << allocRecordMaxString 4283 << "' --- not power of two"; 4284 return kDefaultNumAllocRecords; 4285 } 4286 return value; 4287 } 4288#endif 4289 return kDefaultNumAllocRecords; 4290} 4291 4292void Dbg::SetAllocTrackingEnabled(bool enabled) { 4293 if (enabled) { 4294 { 4295 MutexLock mu(Thread::Current(), *alloc_tracker_lock_); 4296 if (recent_allocation_records_ == NULL) { 4297 alloc_record_max_ = GetAllocTrackerMax(); 4298 LOG(INFO) << "Enabling alloc tracker (" << alloc_record_max_ << " entries of " 4299 << kMaxAllocRecordStackDepth << " frames, taking " 4300 << PrettySize(sizeof(AllocRecord) * alloc_record_max_) << ")"; 4301 alloc_record_head_ = alloc_record_count_ = 0; 4302 recent_allocation_records_ = new AllocRecord[alloc_record_max_]; 4303 CHECK(recent_allocation_records_ != NULL); 4304 } 4305 } 4306 Runtime::Current()->GetInstrumentation()->InstrumentQuickAllocEntryPoints(); 4307 } else { 4308 Runtime::Current()->GetInstrumentation()->UninstrumentQuickAllocEntryPoints(); 4309 { 4310 MutexLock mu(Thread::Current(), *alloc_tracker_lock_); 4311 LOG(INFO) << "Disabling alloc tracker"; 4312 delete[] recent_allocation_records_; 4313 recent_allocation_records_ = NULL; 4314 type_cache_.Clear(); 4315 } 4316 } 4317} 4318 4319struct AllocRecordStackVisitor : public StackVisitor { 4320 AllocRecordStackVisitor(Thread* thread, AllocRecord* record) 4321 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) 4322 : StackVisitor(thread, NULL), record(record), depth(0) {} 4323 4324 // TODO: Enable annotalysis. We know lock is held in constructor, but abstraction confuses 4325 // annotalysis. 4326 bool VisitFrame() NO_THREAD_SAFETY_ANALYSIS { 4327 if (depth >= kMaxAllocRecordStackDepth) { 4328 return false; 4329 } 4330 mirror::ArtMethod* m = GetMethod(); 4331 if (!m->IsRuntimeMethod()) { 4332 record->StackElement(depth)->SetMethod(m); 4333 record->StackElement(depth)->SetDexPc(GetDexPc()); 4334 ++depth; 4335 } 4336 return true; 4337 } 4338 4339 ~AllocRecordStackVisitor() { 4340 // Clear out any unused stack trace elements. 4341 for (; depth < kMaxAllocRecordStackDepth; ++depth) { 4342 record->StackElement(depth)->SetMethod(nullptr); 4343 record->StackElement(depth)->SetDexPc(0); 4344 } 4345 } 4346 4347 AllocRecord* record; 4348 size_t depth; 4349}; 4350 4351void Dbg::RecordAllocation(mirror::Class* type, size_t byte_count) { 4352 Thread* self = Thread::Current(); 4353 CHECK(self != NULL); 4354 4355 MutexLock mu(self, *alloc_tracker_lock_); 4356 if (recent_allocation_records_ == NULL) { 4357 return; 4358 } 4359 4360 // Advance and clip. 4361 if (++alloc_record_head_ == alloc_record_max_) { 4362 alloc_record_head_ = 0; 4363 } 4364 4365 // Fill in the basics. 4366 AllocRecord* record = &recent_allocation_records_[alloc_record_head_]; 4367 record->SetType(type); 4368 record->SetByteCount(byte_count); 4369 record->SetThinLockId(self->GetThreadId()); 4370 4371 // Fill in the stack trace. 4372 AllocRecordStackVisitor visitor(self, record); 4373 visitor.WalkStack(); 4374 4375 if (alloc_record_count_ < alloc_record_max_) { 4376 ++alloc_record_count_; 4377 } 4378} 4379 4380// Returns the index of the head element. 4381// 4382// We point at the most-recently-written record, so if gAllocRecordCount is 1 4383// we want to use the current element. Take "head+1" and subtract count 4384// from it. 4385// 4386// We need to handle underflow in our circular buffer, so we add 4387// gAllocRecordMax and then mask it back down. 4388size_t Dbg::HeadIndex() { 4389 return (Dbg::alloc_record_head_ + 1 + Dbg::alloc_record_max_ - Dbg::alloc_record_count_) & 4390 (Dbg::alloc_record_max_ - 1); 4391} 4392 4393void Dbg::DumpRecentAllocations() { 4394 ScopedObjectAccess soa(Thread::Current()); 4395 MutexLock mu(soa.Self(), *alloc_tracker_lock_); 4396 if (recent_allocation_records_ == NULL) { 4397 LOG(INFO) << "Not recording tracked allocations"; 4398 return; 4399 } 4400 4401 // "i" is the head of the list. We want to start at the end of the 4402 // list and move forward to the tail. 4403 size_t i = HeadIndex(); 4404 size_t count = alloc_record_count_; 4405 4406 LOG(INFO) << "Tracked allocations, (head=" << alloc_record_head_ << " count=" << count << ")"; 4407 while (count--) { 4408 AllocRecord* record = &recent_allocation_records_[i]; 4409 4410 LOG(INFO) << StringPrintf(" Thread %-2d %6zd bytes ", record->ThinLockId(), record->ByteCount()) 4411 << PrettyClass(record->Type()); 4412 4413 for (size_t stack_frame = 0; stack_frame < kMaxAllocRecordStackDepth; ++stack_frame) { 4414 AllocRecordStackTraceElement* stack_element = record->StackElement(stack_frame); 4415 mirror::ArtMethod* m = stack_element->Method(); 4416 if (m == NULL) { 4417 break; 4418 } 4419 LOG(INFO) << " " << PrettyMethod(m) << " line " << stack_element->LineNumber(); 4420 } 4421 4422 // pause periodically to help logcat catch up 4423 if ((count % 5) == 0) { 4424 usleep(40000); 4425 } 4426 4427 i = (i + 1) & (alloc_record_max_ - 1); 4428 } 4429} 4430 4431class StringTable { 4432 public: 4433 StringTable() { 4434 } 4435 4436 void Add(const std::string& str) { 4437 table_.insert(str); 4438 } 4439 4440 void Add(const char* str) { 4441 table_.insert(str); 4442 } 4443 4444 size_t IndexOf(const char* s) const { 4445 auto it = table_.find(s); 4446 if (it == table_.end()) { 4447 LOG(FATAL) << "IndexOf(\"" << s << "\") failed"; 4448 } 4449 return std::distance(table_.begin(), it); 4450 } 4451 4452 size_t Size() const { 4453 return table_.size(); 4454 } 4455 4456 void WriteTo(std::vector<uint8_t>& bytes) const { 4457 for (const std::string& str : table_) { 4458 const char* s = str.c_str(); 4459 size_t s_len = CountModifiedUtf8Chars(s); 4460 std::unique_ptr<uint16_t> s_utf16(new uint16_t[s_len]); 4461 ConvertModifiedUtf8ToUtf16(s_utf16.get(), s); 4462 JDWP::AppendUtf16BE(bytes, s_utf16.get(), s_len); 4463 } 4464 } 4465 4466 private: 4467 std::set<std::string> table_; 4468 DISALLOW_COPY_AND_ASSIGN(StringTable); 4469}; 4470 4471static const char* GetMethodSourceFile(mirror::ArtMethod* method) 4472 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 4473 DCHECK(method != nullptr); 4474 const char* source_file = method->GetDeclaringClassSourceFile(); 4475 return (source_file != nullptr) ? source_file : ""; 4476} 4477 4478/* 4479 * The data we send to DDMS contains everything we have recorded. 4480 * 4481 * Message header (all values big-endian): 4482 * (1b) message header len (to allow future expansion); includes itself 4483 * (1b) entry header len 4484 * (1b) stack frame len 4485 * (2b) number of entries 4486 * (4b) offset to string table from start of message 4487 * (2b) number of class name strings 4488 * (2b) number of method name strings 4489 * (2b) number of source file name strings 4490 * For each entry: 4491 * (4b) total allocation size 4492 * (2b) thread id 4493 * (2b) allocated object's class name index 4494 * (1b) stack depth 4495 * For each stack frame: 4496 * (2b) method's class name 4497 * (2b) method name 4498 * (2b) method source file 4499 * (2b) line number, clipped to 32767; -2 if native; -1 if no source 4500 * (xb) class name strings 4501 * (xb) method name strings 4502 * (xb) source file strings 4503 * 4504 * As with other DDM traffic, strings are sent as a 4-byte length 4505 * followed by UTF-16 data. 4506 * 4507 * We send up 16-bit unsigned indexes into string tables. In theory there 4508 * can be (kMaxAllocRecordStackDepth * gAllocRecordMax) unique strings in 4509 * each table, but in practice there should be far fewer. 4510 * 4511 * The chief reason for using a string table here is to keep the size of 4512 * the DDMS message to a minimum. This is partly to make the protocol 4513 * efficient, but also because we have to form the whole thing up all at 4514 * once in a memory buffer. 4515 * 4516 * We use separate string tables for class names, method names, and source 4517 * files to keep the indexes small. There will generally be no overlap 4518 * between the contents of these tables. 4519 */ 4520jbyteArray Dbg::GetRecentAllocations() { 4521 if (false) { 4522 DumpRecentAllocations(); 4523 } 4524 4525 Thread* self = Thread::Current(); 4526 std::vector<uint8_t> bytes; 4527 { 4528 MutexLock mu(self, *alloc_tracker_lock_); 4529 // 4530 // Part 1: generate string tables. 4531 // 4532 StringTable class_names; 4533 StringTable method_names; 4534 StringTable filenames; 4535 4536 int count = alloc_record_count_; 4537 int idx = HeadIndex(); 4538 while (count--) { 4539 AllocRecord* record = &recent_allocation_records_[idx]; 4540 std::string temp; 4541 class_names.Add(record->Type()->GetDescriptor(&temp)); 4542 for (size_t i = 0; i < kMaxAllocRecordStackDepth; i++) { 4543 mirror::ArtMethod* m = record->StackElement(i)->Method(); 4544 if (m != NULL) { 4545 class_names.Add(m->GetDeclaringClassDescriptor()); 4546 method_names.Add(m->GetName()); 4547 filenames.Add(GetMethodSourceFile(m)); 4548 } 4549 } 4550 4551 idx = (idx + 1) & (alloc_record_max_ - 1); 4552 } 4553 4554 LOG(INFO) << "allocation records: " << alloc_record_count_; 4555 4556 // 4557 // Part 2: Generate the output and store it in the buffer. 4558 // 4559 4560 // (1b) message header len (to allow future expansion); includes itself 4561 // (1b) entry header len 4562 // (1b) stack frame len 4563 const int kMessageHeaderLen = 15; 4564 const int kEntryHeaderLen = 9; 4565 const int kStackFrameLen = 8; 4566 JDWP::Append1BE(bytes, kMessageHeaderLen); 4567 JDWP::Append1BE(bytes, kEntryHeaderLen); 4568 JDWP::Append1BE(bytes, kStackFrameLen); 4569 4570 // (2b) number of entries 4571 // (4b) offset to string table from start of message 4572 // (2b) number of class name strings 4573 // (2b) number of method name strings 4574 // (2b) number of source file name strings 4575 JDWP::Append2BE(bytes, alloc_record_count_); 4576 size_t string_table_offset = bytes.size(); 4577 JDWP::Append4BE(bytes, 0); // We'll patch this later... 4578 JDWP::Append2BE(bytes, class_names.Size()); 4579 JDWP::Append2BE(bytes, method_names.Size()); 4580 JDWP::Append2BE(bytes, filenames.Size()); 4581 4582 idx = HeadIndex(); 4583 std::string temp; 4584 for (count = alloc_record_count_; count != 0; --count) { 4585 // For each entry: 4586 // (4b) total allocation size 4587 // (2b) thread id 4588 // (2b) allocated object's class name index 4589 // (1b) stack depth 4590 AllocRecord* record = &recent_allocation_records_[idx]; 4591 size_t stack_depth = record->GetDepth(); 4592 size_t allocated_object_class_name_index = 4593 class_names.IndexOf(record->Type()->GetDescriptor(&temp)); 4594 JDWP::Append4BE(bytes, record->ByteCount()); 4595 JDWP::Append2BE(bytes, record->ThinLockId()); 4596 JDWP::Append2BE(bytes, allocated_object_class_name_index); 4597 JDWP::Append1BE(bytes, stack_depth); 4598 4599 for (size_t stack_frame = 0; stack_frame < stack_depth; ++stack_frame) { 4600 // For each stack frame: 4601 // (2b) method's class name 4602 // (2b) method name 4603 // (2b) method source file 4604 // (2b) line number, clipped to 32767; -2 if native; -1 if no source 4605 mirror::ArtMethod* m = record->StackElement(stack_frame)->Method(); 4606 size_t class_name_index = class_names.IndexOf(m->GetDeclaringClassDescriptor()); 4607 size_t method_name_index = method_names.IndexOf(m->GetName()); 4608 size_t file_name_index = filenames.IndexOf(GetMethodSourceFile(m)); 4609 JDWP::Append2BE(bytes, class_name_index); 4610 JDWP::Append2BE(bytes, method_name_index); 4611 JDWP::Append2BE(bytes, file_name_index); 4612 JDWP::Append2BE(bytes, record->StackElement(stack_frame)->LineNumber()); 4613 } 4614 idx = (idx + 1) & (alloc_record_max_ - 1); 4615 } 4616 4617 // (xb) class name strings 4618 // (xb) method name strings 4619 // (xb) source file strings 4620 JDWP::Set4BE(&bytes[string_table_offset], bytes.size()); 4621 class_names.WriteTo(bytes); 4622 method_names.WriteTo(bytes); 4623 filenames.WriteTo(bytes); 4624 } 4625 JNIEnv* env = self->GetJniEnv(); 4626 jbyteArray result = env->NewByteArray(bytes.size()); 4627 if (result != NULL) { 4628 env->SetByteArrayRegion(result, 0, bytes.size(), reinterpret_cast<const jbyte*>(&bytes[0])); 4629 } 4630 return result; 4631} 4632 4633mirror::ArtMethod* DeoptimizationRequest::Method() const { 4634 ScopedObjectAccessUnchecked soa(Thread::Current()); 4635 return soa.DecodeMethod(method_); 4636} 4637 4638void DeoptimizationRequest::SetMethod(mirror::ArtMethod* m) { 4639 ScopedObjectAccessUnchecked soa(Thread::Current()); 4640 method_ = soa.EncodeMethod(m); 4641} 4642 4643} // namespace art 4644