1 //===-- DynamicLoaderDarwinKernel.cpp -----------------------------*- C++ -*-===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 10 #include "lldb/lldb-python.h" 11 12 #include "lldb/Breakpoint/StoppointCallbackContext.h" 13 #include "lldb/Core/DataBuffer.h" 14 #include "lldb/Core/DataBufferHeap.h" 15 #include "lldb/Core/Debugger.h" 16 #include "lldb/Core/Log.h" 17 #include "lldb/Core/Module.h" 18 #include "lldb/Core/ModuleSpec.h" 19 #include "lldb/Core/PluginManager.h" 20 #include "lldb/Core/Section.h" 21 #include "lldb/Core/State.h" 22 #include "lldb/Host/Symbols.h" 23 #include "lldb/Symbol/ObjectFile.h" 24 #include "lldb/Target/RegisterContext.h" 25 #include "lldb/Target/StackFrame.h" 26 #include "lldb/Target/Target.h" 27 #include "lldb/Target/Thread.h" 28 #include "lldb/Target/ThreadPlanRunToAddress.h" 29 30 31 #include "DynamicLoaderDarwinKernel.h" 32 33 //#define ENABLE_DEBUG_PRINTF // COMMENT THIS LINE OUT PRIOR TO CHECKIN 34 #ifdef ENABLE_DEBUG_PRINTF 35 #include <stdio.h> 36 #define DEBUG_PRINTF(fmt, ...) printf(fmt, ## __VA_ARGS__) 37 #else 38 #define DEBUG_PRINTF(fmt, ...) 39 #endif 40 41 using namespace lldb; 42 using namespace lldb_private; 43 44 // Progressively greater amounts of scanning we will allow 45 // For some targets very early in startup, we can't do any random reads of memory or we can crash the device 46 // so a setting is needed that can completely disable the KASLR scans. 47 48 enum KASLRScanType 49 { 50 eKASLRScanNone = 0, // No reading into the inferior at all 51 eKASLRScanLowgloAddresses, // Check one word of memory for a possible kernel addr, then see if a kernel is there 52 eKASLRScanNearPC, // Scan backwards from the current $pc looking for kernel; checking at 96 locations total 53 eKASLRScanExhaustiveScan // Scan through the entire possible kernel address range looking for a kernel 54 }; 55 56 OptionEnumValueElement 57 g_kaslr_kernel_scan_enum_values[] = 58 { 59 { eKASLRScanNone, "none", "Do not read memory looking for a Darwin kernel when attaching." }, 60 { eKASLRScanLowgloAddresses, "basic", "Check for the Darwin kernel's load addr in the lowglo page (boot-args=debug) only." }, 61 { eKASLRScanNearPC, "fast-scan", "Scan near the pc value on attach to find the Darwin kernel's load address."}, 62 { eKASLRScanExhaustiveScan, "exhaustive-scan", "Scan through the entire potential address range of Darwin kernel (only on 32-bit targets)."}, 63 { 0, NULL, NULL } 64 }; 65 66 static PropertyDefinition 67 g_properties[] = 68 { 69 { "load-kexts" , OptionValue::eTypeBoolean, true, true, NULL, NULL, "Automatically loads kext images when attaching to a kernel." }, 70 { "scan-type", OptionValue::eTypeEnum, true, eKASLRScanNearPC, NULL, g_kaslr_kernel_scan_enum_values, "Control how many reads lldb will make while searching for a Darwin kernel on attach." }, 71 { NULL , OptionValue::eTypeInvalid, false, 0 , NULL, NULL, NULL } 72 }; 73 74 enum { 75 ePropertyLoadKexts, 76 ePropertyScanType 77 }; 78 79 class DynamicLoaderDarwinKernelProperties : public Properties 80 { 81 public: 82 83 static ConstString & 84 GetSettingName () 85 { 86 static ConstString g_setting_name("darwin-kernel"); 87 return g_setting_name; 88 } 89 90 DynamicLoaderDarwinKernelProperties() : 91 Properties () 92 { 93 m_collection_sp.reset (new OptionValueProperties(GetSettingName())); 94 m_collection_sp->Initialize(g_properties); 95 } 96 97 virtual 98 ~DynamicLoaderDarwinKernelProperties() 99 { 100 } 101 102 bool 103 GetLoadKexts() const 104 { 105 const uint32_t idx = ePropertyLoadKexts; 106 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0); 107 } 108 109 KASLRScanType 110 GetScanType() const 111 { 112 const uint32_t idx = ePropertyScanType; 113 return (KASLRScanType) m_collection_sp->GetPropertyAtIndexAsEnumeration (NULL, idx, g_properties[idx].default_uint_value); 114 } 115 116 117 }; 118 119 typedef STD_SHARED_PTR(DynamicLoaderDarwinKernelProperties) DynamicLoaderDarwinKernelPropertiesSP; 120 121 static const DynamicLoaderDarwinKernelPropertiesSP & 122 GetGlobalProperties() 123 { 124 static DynamicLoaderDarwinKernelPropertiesSP g_settings_sp; 125 if (!g_settings_sp) 126 g_settings_sp.reset (new DynamicLoaderDarwinKernelProperties ()); 127 return g_settings_sp; 128 } 129 130 //---------------------------------------------------------------------- 131 // Create an instance of this class. This function is filled into 132 // the plugin info class that gets handed out by the plugin factory and 133 // allows the lldb to instantiate an instance of this class. 134 //---------------------------------------------------------------------- 135 DynamicLoader * 136 DynamicLoaderDarwinKernel::CreateInstance (Process* process, bool force) 137 { 138 if (!force) 139 { 140 // If the user provided an executable binary and it is not a kernel, 141 // this plugin should not create an instance. 142 Module* exe_module = process->GetTarget().GetExecutableModulePointer(); 143 if (exe_module) 144 { 145 ObjectFile *object_file = exe_module->GetObjectFile(); 146 if (object_file) 147 { 148 if (object_file->GetStrata() != ObjectFile::eStrataKernel) 149 { 150 return NULL; 151 } 152 } 153 } 154 155 // If the target's architecture does not look like an Apple environment, 156 // this plugin should not create an instance. 157 const llvm::Triple &triple_ref = process->GetTarget().GetArchitecture().GetTriple(); 158 switch (triple_ref.getOS()) 159 { 160 case llvm::Triple::Darwin: 161 case llvm::Triple::MacOSX: 162 case llvm::Triple::IOS: 163 if (triple_ref.getVendor() != llvm::Triple::Apple) 164 { 165 return NULL; 166 } 167 break; 168 // If we have triple like armv7-unknown-unknown, we should try looking for a Darwin kernel. 169 case llvm::Triple::UnknownOS: 170 break; 171 default: 172 return NULL; 173 break; 174 } 175 } 176 177 // At this point if there is an ExecutableModule, it is a kernel and the Target is some variant of an Apple system. 178 // If the Process hasn't provided the kernel load address, we need to look around in memory to find it. 179 180 addr_t kernel_load_address = SearchForDarwinKernel (process); 181 if (kernel_load_address != LLDB_INVALID_ADDRESS) 182 { 183 process->SetCanJIT(false); 184 return new DynamicLoaderDarwinKernel (process, kernel_load_address); 185 } 186 return NULL; 187 } 188 189 lldb::addr_t 190 DynamicLoaderDarwinKernel::SearchForDarwinKernel (Process *process) 191 { 192 addr_t kernel_load_address = process->GetImageInfoAddress(); 193 if (kernel_load_address == LLDB_INVALID_ADDRESS) 194 { 195 kernel_load_address = SearchForKernelAtSameLoadAddr (process); 196 if (kernel_load_address == LLDB_INVALID_ADDRESS) 197 { 198 kernel_load_address = SearchForKernelWithDebugHints (process); 199 if (kernel_load_address == LLDB_INVALID_ADDRESS) 200 { 201 kernel_load_address = SearchForKernelNearPC (process); 202 if (kernel_load_address == LLDB_INVALID_ADDRESS) 203 { 204 kernel_load_address = SearchForKernelViaExhaustiveSearch (process); 205 } 206 } 207 } 208 } 209 return kernel_load_address; 210 } 211 212 //---------------------------------------------------------------------- 213 // Check if the kernel binary is loaded in memory without a slide. 214 // First verify that the ExecutableModule is a kernel before we proceed. 215 // Returns the address of the kernel if one was found, else LLDB_INVALID_ADDRESS. 216 //---------------------------------------------------------------------- 217 lldb::addr_t 218 DynamicLoaderDarwinKernel::SearchForKernelAtSameLoadAddr (Process *process) 219 { 220 Module *exe_module = process->GetTarget().GetExecutableModulePointer(); 221 if (exe_module == NULL) 222 return LLDB_INVALID_ADDRESS; 223 224 ObjectFile *exe_objfile = exe_module->GetObjectFile(); 225 if (exe_objfile == NULL) 226 return LLDB_INVALID_ADDRESS; 227 228 if (exe_objfile->GetType() != ObjectFile::eTypeExecutable || exe_objfile->GetStrata() != ObjectFile::eStrataKernel) 229 return LLDB_INVALID_ADDRESS; 230 231 if (!exe_objfile->GetHeaderAddress().IsValid()) 232 return LLDB_INVALID_ADDRESS; 233 234 if (CheckForKernelImageAtAddress (exe_objfile->GetHeaderAddress().GetFileAddress(), process) == exe_module->GetUUID()) 235 return exe_objfile->GetHeaderAddress().GetFileAddress(); 236 237 return LLDB_INVALID_ADDRESS; 238 } 239 240 //---------------------------------------------------------------------- 241 // If the debug flag is included in the boot-args nvram setting, the kernel's load address 242 // will be noted in the lowglo page at a fixed address 243 // Returns the address of the kernel if one was found, else LLDB_INVALID_ADDRESS. 244 //---------------------------------------------------------------------- 245 lldb::addr_t 246 DynamicLoaderDarwinKernel::SearchForKernelWithDebugHints (Process *process) 247 { 248 if (GetGlobalProperties()->GetScanType() == eKASLRScanNone) 249 return LLDB_INVALID_ADDRESS; 250 251 Error read_err; 252 addr_t addr = LLDB_INVALID_ADDRESS; 253 if (process->GetTarget().GetArchitecture().GetAddressByteSize() == 8) 254 { 255 addr = process->ReadUnsignedIntegerFromMemory (0xffffff8000002010ULL, 8, LLDB_INVALID_ADDRESS, read_err); 256 } 257 else 258 { 259 addr = process->ReadUnsignedIntegerFromMemory (0xffff0110, 4, LLDB_INVALID_ADDRESS, read_err); 260 } 261 262 if (addr == 0) 263 addr = LLDB_INVALID_ADDRESS; 264 265 if (addr != LLDB_INVALID_ADDRESS) 266 { 267 if (CheckForKernelImageAtAddress (addr, process).IsValid()) 268 return addr; 269 } 270 271 return LLDB_INVALID_ADDRESS; 272 } 273 274 //---------------------------------------------------------------------- 275 // If the kernel is currently executing when lldb attaches, and we don't have 276 // a better way of finding the kernel's load address, try searching backwards 277 // from the current pc value looking for the kernel's Mach header in memory. 278 // Returns the address of the kernel if one was found, else LLDB_INVALID_ADDRESS. 279 //---------------------------------------------------------------------- 280 lldb::addr_t 281 DynamicLoaderDarwinKernel::SearchForKernelNearPC (Process *process) 282 { 283 if (GetGlobalProperties()->GetScanType() == eKASLRScanNone 284 || GetGlobalProperties()->GetScanType() == eKASLRScanLowgloAddresses) 285 { 286 return LLDB_INVALID_ADDRESS; 287 } 288 289 ThreadSP thread = process->GetThreadList().GetSelectedThread (); 290 if (thread.get() == NULL) 291 return LLDB_INVALID_ADDRESS; 292 addr_t pc = thread->GetRegisterContext ()->GetPC(LLDB_INVALID_ADDRESS); 293 294 if (pc == LLDB_INVALID_ADDRESS) 295 return LLDB_INVALID_ADDRESS; 296 297 addr_t kernel_range_low, kernel_range_high; 298 if (process->GetTarget().GetArchitecture().GetAddressByteSize() == 8) 299 { 300 kernel_range_low = 1ULL << 63; 301 kernel_range_high = UINT64_MAX; 302 } 303 else 304 { 305 kernel_range_low = 1ULL << 31; 306 kernel_range_high = UINT32_MAX; 307 } 308 309 // Outside the normal kernel address range, this is probably userland code running right now 310 if (pc < kernel_range_low) 311 LLDB_INVALID_ADDRESS; 312 313 // The kernel will load at at one megabyte boundary (0x100000), or at that boundary plus 314 // an offset of one page (0x1000) or two, depending on the device. 315 316 // Round the current pc down to the nearest one megabyte boundary - the place where we will start searching. 317 addr_t addr = pc & ~0xfffff; 318 319 int i = 0; 320 while (i < 32 && pc >= kernel_range_low) 321 { 322 if (CheckForKernelImageAtAddress (addr, process).IsValid()) 323 return addr; 324 if (CheckForKernelImageAtAddress (addr + 0x1000, process).IsValid()) 325 return addr + 0x1000; 326 if (CheckForKernelImageAtAddress (addr + 0x2000, process).IsValid()) 327 return addr + 0x2000; 328 i++; 329 addr -= 0x100000; 330 } 331 332 return LLDB_INVALID_ADDRESS; 333 } 334 335 //---------------------------------------------------------------------- 336 // Scan through the valid address range for a kernel binary. 337 // This is uselessly slow in 64-bit environments so we don't even try it. 338 // This scan is not enabled by default even for 32-bit targets. 339 // Returns the address of the kernel if one was found, else LLDB_INVALID_ADDRESS. 340 //---------------------------------------------------------------------- 341 lldb::addr_t 342 DynamicLoaderDarwinKernel::SearchForKernelViaExhaustiveSearch (Process *process) 343 { 344 if (GetGlobalProperties()->GetScanType() != eKASLRScanExhaustiveScan) 345 { 346 return LLDB_INVALID_ADDRESS; 347 } 348 349 addr_t kernel_range_low, kernel_range_high; 350 if (process->GetTarget().GetArchitecture().GetAddressByteSize() == 8) 351 { 352 kernel_range_low = 1ULL << 63; 353 kernel_range_high = UINT64_MAX; 354 } 355 else 356 { 357 kernel_range_low = 1ULL << 31; 358 kernel_range_high = UINT32_MAX; 359 } 360 361 // Stepping through memory at one-megabyte resolution looking for a kernel 362 // rarely works (fast enough) with a 64-bit address space -- for now, let's 363 // not even bother. We may be attaching to something which *isn't* a kernel 364 // and we don't want to spin for minutes on-end looking for a kernel. 365 if (process->GetTarget().GetArchitecture().GetAddressByteSize() == 8) 366 return LLDB_INVALID_ADDRESS; 367 368 addr_t addr = kernel_range_low; 369 370 while (addr >= kernel_range_low && addr < kernel_range_high) 371 { 372 if (CheckForKernelImageAtAddress (addr, process).IsValid()) 373 return addr; 374 if (CheckForKernelImageAtAddress (addr + 0x1000, process).IsValid()) 375 return addr + 0x1000; 376 if (CheckForKernelImageAtAddress (addr + 0x2000, process).IsValid()) 377 return addr + 0x2000; 378 addr += 0x100000; 379 } 380 return LLDB_INVALID_ADDRESS; 381 } 382 383 //---------------------------------------------------------------------- 384 // Given an address in memory, look to see if there is a kernel image at that 385 // address. 386 // Returns a UUID; if a kernel was not found at that address, UUID.IsValid() will be false. 387 //---------------------------------------------------------------------- 388 lldb_private::UUID 389 DynamicLoaderDarwinKernel::CheckForKernelImageAtAddress (lldb::addr_t addr, Process *process) 390 { 391 if (addr == LLDB_INVALID_ADDRESS) 392 return UUID(); 393 394 // First try a quick test -- read the first 4 bytes and see if there is a valid Mach-O magic field there 395 // (the first field of the mach_header/mach_header_64 struct). 396 397 Error read_error; 398 uint64_t result = process->ReadUnsignedIntegerFromMemory (addr, 4, LLDB_INVALID_ADDRESS, read_error); 399 if (result != llvm::MachO::HeaderMagic64 400 && result != llvm::MachO::HeaderMagic32 401 && result != llvm::MachO::HeaderMagic32Swapped 402 && result != llvm::MachO::HeaderMagic64Swapped) 403 { 404 return UUID(); 405 } 406 407 // Read the mach header and see whether it looks like a kernel 408 llvm::MachO::mach_header header; 409 if (process->DoReadMemory (addr, &header, sizeof(header), read_error) != sizeof(header)) 410 return UUID(); 411 412 if (header.magic == llvm::MachO::HeaderMagic32Swapped || 413 header.magic == llvm::MachO::HeaderMagic64Swapped) 414 { 415 header.magic = llvm::ByteSwap_32(header.magic); 416 header.cputype = llvm::ByteSwap_32(header.cputype); 417 header.cpusubtype = llvm::ByteSwap_32(header.cpusubtype); 418 header.filetype = llvm::ByteSwap_32(header.filetype); 419 header.ncmds = llvm::ByteSwap_32(header.ncmds); 420 header.sizeofcmds = llvm::ByteSwap_32(header.sizeofcmds); 421 header.flags = llvm::ByteSwap_32(header.flags); 422 } 423 424 // A kernel is an executable which does not have the dynamic link object flag set. 425 if (header.filetype == llvm::MachO::HeaderFileTypeExecutable 426 && (header.flags & llvm::MachO::HeaderFlagBitIsDynamicLinkObject) == 0) 427 { 428 // Create a full module to get the UUID 429 ModuleSP memory_module_sp = process->ReadModuleFromMemory (FileSpec ("temp_mach_kernel", false), addr); 430 if (!memory_module_sp.get()) 431 return UUID(); 432 433 ObjectFile *exe_objfile = memory_module_sp->GetObjectFile(); 434 if (exe_objfile == NULL) 435 return UUID(); 436 437 if (exe_objfile->GetType() == ObjectFile::eTypeExecutable && exe_objfile->GetStrata() == ObjectFile::eStrataKernel) 438 { 439 return memory_module_sp->GetUUID(); 440 } 441 } 442 443 return UUID(); 444 } 445 446 //---------------------------------------------------------------------- 447 // Constructor 448 //---------------------------------------------------------------------- 449 DynamicLoaderDarwinKernel::DynamicLoaderDarwinKernel (Process* process, lldb::addr_t kernel_addr) : 450 DynamicLoader(process), 451 m_kernel_load_address (kernel_addr), 452 m_kernel(), 453 m_kext_summary_header_ptr_addr (), 454 m_kext_summary_header_addr (), 455 m_kext_summary_header (), 456 m_known_kexts (), 457 m_mutex(Mutex::eMutexTypeRecursive), 458 m_break_id (LLDB_INVALID_BREAK_ID) 459 { 460 } 461 462 //---------------------------------------------------------------------- 463 // Destructor 464 //---------------------------------------------------------------------- 465 DynamicLoaderDarwinKernel::~DynamicLoaderDarwinKernel() 466 { 467 Clear(true); 468 } 469 470 void 471 DynamicLoaderDarwinKernel::UpdateIfNeeded() 472 { 473 LoadKernelModuleIfNeeded(); 474 SetNotificationBreakpointIfNeeded (); 475 } 476 //------------------------------------------------------------------ 477 /// Called after attaching a process. 478 /// 479 /// Allow DynamicLoader plug-ins to execute some code after 480 /// attaching to a process. 481 //------------------------------------------------------------------ 482 void 483 DynamicLoaderDarwinKernel::DidAttach () 484 { 485 PrivateInitialize(m_process); 486 UpdateIfNeeded(); 487 } 488 489 //------------------------------------------------------------------ 490 /// Called after attaching a process. 491 /// 492 /// Allow DynamicLoader plug-ins to execute some code after 493 /// attaching to a process. 494 //------------------------------------------------------------------ 495 void 496 DynamicLoaderDarwinKernel::DidLaunch () 497 { 498 PrivateInitialize(m_process); 499 UpdateIfNeeded(); 500 } 501 502 503 //---------------------------------------------------------------------- 504 // Clear out the state of this class. 505 //---------------------------------------------------------------------- 506 void 507 DynamicLoaderDarwinKernel::Clear (bool clear_process) 508 { 509 Mutex::Locker locker(m_mutex); 510 511 if (m_process->IsAlive() && LLDB_BREAK_ID_IS_VALID(m_break_id)) 512 m_process->ClearBreakpointSiteByID(m_break_id); 513 514 if (clear_process) 515 m_process = NULL; 516 m_kernel.Clear(); 517 m_known_kexts.clear(); 518 m_kext_summary_header_ptr_addr.Clear(); 519 m_kext_summary_header_addr.Clear(); 520 m_break_id = LLDB_INVALID_BREAK_ID; 521 } 522 523 524 bool 525 DynamicLoaderDarwinKernel::KextImageInfo::LoadImageAtFileAddress (Process *process) 526 { 527 if (IsLoaded()) 528 return true; 529 530 if (m_module_sp) 531 { 532 bool changed = false; 533 if (m_module_sp->SetLoadAddress (process->GetTarget(), 0, changed)) 534 m_load_process_stop_id = process->GetStopID(); 535 } 536 return false; 537 } 538 539 void 540 DynamicLoaderDarwinKernel::KextImageInfo::SetModule (ModuleSP module_sp) 541 { 542 m_module_sp = module_sp; 543 if (module_sp.get() && module_sp->GetObjectFile()) 544 { 545 if (module_sp->GetObjectFile()->GetType() == ObjectFile::eTypeExecutable 546 && module_sp->GetObjectFile()->GetStrata() == ObjectFile::eStrataKernel) 547 { 548 m_kernel_image = true; 549 } 550 else 551 { 552 m_kernel_image = false; 553 } 554 } 555 } 556 557 ModuleSP 558 DynamicLoaderDarwinKernel::KextImageInfo::GetModule () 559 { 560 return m_module_sp; 561 } 562 563 void 564 DynamicLoaderDarwinKernel::KextImageInfo::SetLoadAddress (addr_t load_addr) 565 { 566 m_load_address = load_addr; 567 } 568 569 addr_t 570 DynamicLoaderDarwinKernel::KextImageInfo::GetLoadAddress () const 571 { 572 return m_load_address; 573 } 574 575 uint64_t 576 DynamicLoaderDarwinKernel::KextImageInfo::GetSize () const 577 { 578 return m_size; 579 } 580 581 void 582 DynamicLoaderDarwinKernel::KextImageInfo::SetSize (uint64_t size) 583 { 584 m_size = size; 585 } 586 587 uint32_t 588 DynamicLoaderDarwinKernel::KextImageInfo::GetProcessStopId () const 589 { 590 return m_load_process_stop_id; 591 } 592 593 void 594 DynamicLoaderDarwinKernel::KextImageInfo::SetProcessStopId (uint32_t stop_id) 595 { 596 m_load_process_stop_id = stop_id; 597 } 598 599 bool 600 DynamicLoaderDarwinKernel::KextImageInfo::operator== (const KextImageInfo &rhs) 601 { 602 if (m_uuid.IsValid() || rhs.GetUUID().IsValid()) 603 { 604 if (m_uuid == rhs.GetUUID()) 605 { 606 return true; 607 } 608 return false; 609 } 610 611 if (m_name == rhs.GetName() && m_load_address == rhs.GetLoadAddress()) 612 return true; 613 614 return false; 615 } 616 617 void 618 DynamicLoaderDarwinKernel::KextImageInfo::SetName (const char *name) 619 { 620 m_name = name; 621 } 622 623 std::string 624 DynamicLoaderDarwinKernel::KextImageInfo::GetName () const 625 { 626 return m_name; 627 } 628 629 void 630 DynamicLoaderDarwinKernel::KextImageInfo::SetUUID (const UUID &uuid) 631 { 632 m_uuid = uuid; 633 } 634 635 UUID 636 DynamicLoaderDarwinKernel::KextImageInfo::GetUUID () const 637 { 638 return m_uuid; 639 } 640 641 // Given the m_load_address from the kext summaries, and a UUID, try to create an in-memory 642 // Module at that address. Require that the MemoryModule have a matching UUID and detect 643 // if this MemoryModule is a kernel or a kext. 644 // 645 // Returns true if m_memory_module_sp is now set to a valid Module. 646 647 bool 648 DynamicLoaderDarwinKernel::KextImageInfo::ReadMemoryModule (Process *process) 649 { 650 if (m_memory_module_sp.get() != NULL) 651 return true; 652 if (m_load_address == LLDB_INVALID_ADDRESS) 653 return false; 654 655 FileSpec file_spec; 656 file_spec.SetFile (m_name.c_str(), false); 657 658 ModuleSP memory_module_sp = process->ReadModuleFromMemory (file_spec, m_load_address); 659 660 if (memory_module_sp.get() == NULL) 661 return false; 662 663 bool is_kernel = false; 664 if (memory_module_sp->GetObjectFile()) 665 { 666 if (memory_module_sp->GetObjectFile()->GetType() == ObjectFile::eTypeExecutable 667 && memory_module_sp->GetObjectFile()->GetStrata() == ObjectFile::eStrataKernel) 668 { 669 is_kernel = true; 670 } 671 else if (memory_module_sp->GetObjectFile()->GetType() == ObjectFile::eTypeSharedLibrary) 672 { 673 is_kernel = false; 674 } 675 } 676 677 // If this is a kext, and the kernel specified what UUID we should find at this 678 // load address, require that the memory module have a matching UUID or something 679 // has gone wrong and we should discard it. 680 if (m_uuid.IsValid()) 681 { 682 if (m_uuid != memory_module_sp->GetUUID()) 683 { 684 return false; 685 } 686 } 687 688 // If the in-memory Module has a UUID, let's use that. 689 if (!m_uuid.IsValid() && memory_module_sp->GetUUID().IsValid()) 690 { 691 m_uuid = memory_module_sp->GetUUID(); 692 } 693 694 m_memory_module_sp = memory_module_sp; 695 m_kernel_image = is_kernel; 696 if (is_kernel) 697 { 698 if (memory_module_sp->GetArchitecture().IsValid()) 699 { 700 process->GetTarget().SetArchitecture(memory_module_sp->GetArchitecture()); 701 } 702 if (m_uuid.IsValid()) 703 { 704 Module* exe_module = process->GetTarget().GetExecutableModulePointer(); 705 if (exe_module && exe_module->GetUUID().IsValid()) 706 { 707 if (m_uuid != exe_module->GetUUID()) 708 { 709 Stream *s = &process->GetTarget().GetDebugger().GetOutputStream(); 710 if (s) 711 { 712 char memory_module_uuidbuf[64]; 713 char exe_module_uuidbuf[64]; 714 s->Printf ("warning: Host-side kernel file has Mach-O UUID of %s but remote kernel has a UUID of %s -- a mismatched kernel file will result in a poor debugger experience.\n", 715 exe_module->GetUUID().GetAsCString(exe_module_uuidbuf, sizeof (exe_module_uuidbuf)), 716 m_uuid.GetAsCString(memory_module_uuidbuf, sizeof (memory_module_uuidbuf))); 717 s->Flush (); 718 } 719 } 720 } 721 } 722 } 723 724 return true; 725 } 726 727 bool 728 DynamicLoaderDarwinKernel::KextImageInfo::IsKernel () const 729 { 730 return m_kernel_image == true; 731 } 732 733 void 734 DynamicLoaderDarwinKernel::KextImageInfo::SetIsKernel (bool is_kernel) 735 { 736 m_kernel_image = is_kernel; 737 } 738 739 bool 740 DynamicLoaderDarwinKernel::KextImageInfo::LoadImageUsingMemoryModule (Process *process) 741 { 742 if (IsLoaded()) 743 return true; 744 745 746 Target &target = process->GetTarget(); 747 748 // If we don't have / can't create a memory module for this kext, don't try to load it - we won't 749 // have the correct segment load addresses. 750 if (!ReadMemoryModule (process)) 751 { 752 return false; 753 } 754 755 bool uuid_is_valid = m_uuid.IsValid(); 756 757 if (IsKernel() && uuid_is_valid && m_memory_module_sp.get()) 758 { 759 Stream *s = &target.GetDebugger().GetOutputStream(); 760 if (s) 761 { 762 char uuidbuf[64]; 763 s->Printf ("Kernel UUID: %s\n", m_memory_module_sp->GetUUID().GetAsCString(uuidbuf, sizeof (uuidbuf))); 764 s->Printf ("Load Address: 0x%" PRIx64 "\n", m_load_address); 765 } 766 } 767 768 if (!m_module_sp) 769 { 770 // See if the kext has already been loaded into the target, probably by the user doing target modules add. 771 const ModuleList &target_images = target.GetImages(); 772 m_module_sp = target_images.FindModule(m_uuid); 773 774 // Search for the kext on the local filesystem via the UUID 775 if (!m_module_sp && uuid_is_valid) 776 { 777 ModuleSpec module_spec; 778 module_spec.GetUUID() = m_uuid; 779 module_spec.GetArchitecture() = target.GetArchitecture(); 780 781 // For the kernel, we really do need an on-disk file copy of the binary to do anything useful. 782 // This will force a clal to 783 if (IsKernel()) 784 { 785 if (Symbols::DownloadObjectAndSymbolFile (module_spec, true)) 786 { 787 if (module_spec.GetFileSpec().Exists()) 788 { 789 m_module_sp.reset(new Module (module_spec.GetFileSpec(), target.GetArchitecture())); 790 if (m_module_sp.get() && m_module_sp->MatchesModuleSpec (module_spec)) 791 { 792 ModuleList loaded_module_list; 793 loaded_module_list.Append (m_module_sp); 794 target.ModulesDidLoad (loaded_module_list); 795 } 796 } 797 } 798 } 799 800 // Ask the Target to find this file on the local system, if possible. 801 // This will search in the list of currently-loaded files, look in the 802 // standard search paths on the system, and on a Mac it will try calling 803 // the DebugSymbols framework with the UUID to find the binary via its 804 // search methods. 805 if (!m_module_sp) 806 { 807 m_module_sp = target.GetSharedModule (module_spec); 808 } 809 810 if (IsKernel() && !m_module_sp) 811 { 812 Stream *s = &target.GetDebugger().GetOutputStream(); 813 if (s) 814 { 815 s->Printf ("WARNING: Unable to locate kernel binary on this system.\n"); 816 } 817 } 818 } 819 820 // If we managed to find a module, append it to the target's list of images. 821 // If we also have a memory module, require that they have matching UUIDs 822 if (m_module_sp) 823 { 824 bool uuid_match_ok = true; 825 if (m_memory_module_sp) 826 { 827 if (m_module_sp->GetUUID() != m_memory_module_sp->GetUUID()) 828 { 829 uuid_match_ok = false; 830 } 831 } 832 if (uuid_match_ok) 833 { 834 target.GetImages().AppendIfNeeded(m_module_sp); 835 if (IsKernel() && target.GetExecutableModulePointer() != m_module_sp.get()) 836 { 837 target.SetExecutableModule (m_module_sp, false); 838 } 839 } 840 } 841 } 842 843 if (!m_module_sp && !IsKernel() && m_uuid.IsValid() && !m_name.empty()) 844 { 845 Stream *s = &target.GetDebugger().GetOutputStream(); 846 if (s) 847 { 848 char uuidbuf[64]; 849 s->Printf ("warning: Can't find binary/dSYM for %s (%s)\n", 850 m_name.c_str(), m_uuid.GetAsCString(uuidbuf, sizeof (uuidbuf))); 851 } 852 } 853 854 static ConstString g_section_name_LINKEDIT ("__LINKEDIT"); 855 856 if (m_memory_module_sp && m_module_sp) 857 { 858 if (m_module_sp->GetUUID() == m_memory_module_sp->GetUUID()) 859 { 860 ObjectFile *ondisk_object_file = m_module_sp->GetObjectFile(); 861 ObjectFile *memory_object_file = m_memory_module_sp->GetObjectFile(); 862 863 if (memory_object_file && ondisk_object_file) 864 { 865 // The memory_module for kexts may have an invalid __LINKEDIT seg; skip it. 866 const bool ignore_linkedit = !IsKernel (); 867 868 SectionList *ondisk_section_list = ondisk_object_file->GetSectionList (); 869 SectionList *memory_section_list = memory_object_file->GetSectionList (); 870 if (memory_section_list && ondisk_section_list) 871 { 872 const uint32_t num_ondisk_sections = ondisk_section_list->GetSize(); 873 // There may be CTF sections in the memory image so we can't 874 // always just compare the number of sections (which are actually 875 // segments in mach-o parlance) 876 uint32_t sect_idx = 0; 877 878 // Use the memory_module's addresses for each section to set the 879 // file module's load address as appropriate. We don't want to use 880 // a single slide value for the entire kext - different segments may 881 // be slid different amounts by the kext loader. 882 883 uint32_t num_sections_loaded = 0; 884 for (sect_idx=0; sect_idx<num_ondisk_sections; ++sect_idx) 885 { 886 SectionSP ondisk_section_sp(ondisk_section_list->GetSectionAtIndex(sect_idx)); 887 if (ondisk_section_sp) 888 { 889 // Don't ever load __LINKEDIT as it may or may not be actually 890 // mapped into memory and there is no current way to tell. 891 // I filed rdar://problem/12851706 to track being able to tell 892 // if the __LINKEDIT is actually mapped, but until then, we need 893 // to not load the __LINKEDIT 894 if (ignore_linkedit && ondisk_section_sp->GetName() == g_section_name_LINKEDIT) 895 continue; 896 897 const Section *memory_section = memory_section_list->FindSectionByName(ondisk_section_sp->GetName()).get(); 898 if (memory_section) 899 { 900 target.GetSectionLoadList().SetSectionLoadAddress (ondisk_section_sp, memory_section->GetFileAddress()); 901 ++num_sections_loaded; 902 } 903 } 904 } 905 if (num_sections_loaded > 0) 906 m_load_process_stop_id = process->GetStopID(); 907 else 908 m_module_sp.reset(); // No sections were loaded 909 } 910 else 911 m_module_sp.reset(); // One or both section lists 912 } 913 else 914 m_module_sp.reset(); // One or both object files missing 915 } 916 else 917 m_module_sp.reset(); // UUID mismatch 918 } 919 920 bool is_loaded = IsLoaded(); 921 922 if (is_loaded && m_module_sp && IsKernel()) 923 { 924 Stream *s = &target.GetDebugger().GetOutputStream(); 925 if (s) 926 { 927 ObjectFile *kernel_object_file = m_module_sp->GetObjectFile(); 928 if (kernel_object_file) 929 { 930 addr_t file_address = kernel_object_file->GetHeaderAddress().GetFileAddress(); 931 if (m_load_address != LLDB_INVALID_ADDRESS && file_address != LLDB_INVALID_ADDRESS) 932 { 933 s->Printf ("Kernel slid 0x%" PRIx64 " in memory.\n", m_load_address - file_address); 934 } 935 } 936 if (m_module_sp->GetFileSpec().GetDirectory().IsEmpty()) 937 { 938 s->Printf ("Loaded kernel file %s\n", m_module_sp->GetFileSpec().GetFilename().AsCString()); 939 } 940 else 941 { 942 s->Printf ("Loaded kernel file %s/%s\n", 943 m_module_sp->GetFileSpec().GetDirectory().AsCString(), 944 m_module_sp->GetFileSpec().GetFilename().AsCString()); 945 } 946 s->Flush (); 947 } 948 } 949 return is_loaded; 950 } 951 952 uint32_t 953 DynamicLoaderDarwinKernel::KextImageInfo::GetAddressByteSize () 954 { 955 if (m_memory_module_sp) 956 return m_memory_module_sp->GetArchitecture().GetAddressByteSize(); 957 if (m_module_sp) 958 return m_module_sp->GetArchitecture().GetAddressByteSize(); 959 return 0; 960 } 961 962 lldb::ByteOrder 963 DynamicLoaderDarwinKernel::KextImageInfo::GetByteOrder() 964 { 965 if (m_memory_module_sp) 966 return m_memory_module_sp->GetArchitecture().GetByteOrder(); 967 if (m_module_sp) 968 return m_module_sp->GetArchitecture().GetByteOrder(); 969 return lldb::endian::InlHostByteOrder(); 970 } 971 972 lldb_private::ArchSpec 973 DynamicLoaderDarwinKernel::KextImageInfo::GetArchitecture () const 974 { 975 if (m_memory_module_sp) 976 return m_memory_module_sp->GetArchitecture(); 977 if (m_module_sp) 978 return m_module_sp->GetArchitecture(); 979 return lldb_private::ArchSpec (); 980 } 981 982 983 //---------------------------------------------------------------------- 984 // Load the kernel module and initialize the "m_kernel" member. Return 985 // true _only_ if the kernel is loaded the first time through (subsequent 986 // calls to this function should return false after the kernel has been 987 // already loaded). 988 //---------------------------------------------------------------------- 989 void 990 DynamicLoaderDarwinKernel::LoadKernelModuleIfNeeded() 991 { 992 if (!m_kext_summary_header_ptr_addr.IsValid()) 993 { 994 m_kernel.Clear(); 995 m_kernel.SetModule (m_process->GetTarget().GetExecutableModule()); 996 m_kernel.SetIsKernel(true); 997 998 ConstString kernel_name("mach_kernel"); 999 if (m_kernel.GetModule().get() 1000 && m_kernel.GetModule()->GetObjectFile() 1001 && !m_kernel.GetModule()->GetObjectFile()->GetFileSpec().GetFilename().IsEmpty()) 1002 { 1003 kernel_name = m_kernel.GetModule()->GetObjectFile()->GetFileSpec().GetFilename(); 1004 } 1005 m_kernel.SetName (kernel_name.AsCString()); 1006 1007 if (m_kernel.GetLoadAddress() == LLDB_INVALID_ADDRESS) 1008 { 1009 m_kernel.SetLoadAddress(m_kernel_load_address); 1010 if (m_kernel.GetLoadAddress() == LLDB_INVALID_ADDRESS && m_kernel.GetModule()) 1011 { 1012 // We didn't get a hint from the process, so we will 1013 // try the kernel at the address that it exists at in 1014 // the file if we have one 1015 ObjectFile *kernel_object_file = m_kernel.GetModule()->GetObjectFile(); 1016 if (kernel_object_file) 1017 { 1018 addr_t load_address = kernel_object_file->GetHeaderAddress().GetLoadAddress(&m_process->GetTarget()); 1019 addr_t file_address = kernel_object_file->GetHeaderAddress().GetFileAddress(); 1020 if (load_address != LLDB_INVALID_ADDRESS && load_address != 0) 1021 { 1022 m_kernel.SetLoadAddress (load_address); 1023 if (load_address != file_address) 1024 { 1025 // Don't accidentally relocate the kernel to the File address -- 1026 // the Load address has already been set to its actual in-memory address. 1027 // Mark it as IsLoaded. 1028 m_kernel.SetProcessStopId (m_process->GetStopID()); 1029 } 1030 } 1031 else 1032 { 1033 m_kernel.SetLoadAddress(file_address); 1034 } 1035 } 1036 } 1037 } 1038 1039 if (m_kernel.GetLoadAddress() != LLDB_INVALID_ADDRESS) 1040 { 1041 if (!m_kernel.LoadImageUsingMemoryModule (m_process)) 1042 { 1043 m_kernel.LoadImageAtFileAddress (m_process); 1044 } 1045 } 1046 1047 if (m_kernel.IsLoaded() && m_kernel.GetModule()) 1048 { 1049 static ConstString kext_summary_symbol ("gLoadedKextSummaries"); 1050 const Symbol *symbol = m_kernel.GetModule()->FindFirstSymbolWithNameAndType (kext_summary_symbol, eSymbolTypeData); 1051 if (symbol) 1052 { 1053 m_kext_summary_header_ptr_addr = symbol->GetAddress(); 1054 // Update all image infos 1055 ReadAllKextSummaries (); 1056 } 1057 } 1058 else 1059 { 1060 m_kernel.Clear(); 1061 } 1062 } 1063 } 1064 1065 //---------------------------------------------------------------------- 1066 // Static callback function that gets called when our DYLD notification 1067 // breakpoint gets hit. We update all of our image infos and then 1068 // let our super class DynamicLoader class decide if we should stop 1069 // or not (based on global preference). 1070 //---------------------------------------------------------------------- 1071 bool 1072 DynamicLoaderDarwinKernel::BreakpointHitCallback (void *baton, 1073 StoppointCallbackContext *context, 1074 user_id_t break_id, 1075 user_id_t break_loc_id) 1076 { 1077 return static_cast<DynamicLoaderDarwinKernel*>(baton)->BreakpointHit (context, break_id, break_loc_id); 1078 } 1079 1080 bool 1081 DynamicLoaderDarwinKernel::BreakpointHit (StoppointCallbackContext *context, 1082 user_id_t break_id, 1083 user_id_t break_loc_id) 1084 { 1085 Log *log(GetLogIfAnyCategoriesSet (LIBLLDB_LOG_DYNAMIC_LOADER)); 1086 if (log) 1087 log->Printf ("DynamicLoaderDarwinKernel::BreakpointHit (...)\n"); 1088 1089 ReadAllKextSummaries (); 1090 1091 if (log) 1092 PutToLog(log); 1093 1094 return GetStopWhenImagesChange(); 1095 } 1096 1097 1098 bool 1099 DynamicLoaderDarwinKernel::ReadKextSummaryHeader () 1100 { 1101 Mutex::Locker locker(m_mutex); 1102 1103 // the all image infos is already valid for this process stop ID 1104 1105 if (m_kext_summary_header_ptr_addr.IsValid()) 1106 { 1107 const uint32_t addr_size = m_kernel.GetAddressByteSize (); 1108 const ByteOrder byte_order = m_kernel.GetByteOrder(); 1109 Error error; 1110 // Read enough bytes for a "OSKextLoadedKextSummaryHeader" structure 1111 // which is currenty 4 uint32_t and a pointer. 1112 uint8_t buf[24]; 1113 DataExtractor data (buf, sizeof(buf), byte_order, addr_size); 1114 const size_t count = 4 * sizeof(uint32_t) + addr_size; 1115 const bool prefer_file_cache = false; 1116 if (m_process->GetTarget().ReadPointerFromMemory (m_kext_summary_header_ptr_addr, 1117 prefer_file_cache, 1118 error, 1119 m_kext_summary_header_addr)) 1120 { 1121 // We got a valid address for our kext summary header and make sure it isn't NULL 1122 if (m_kext_summary_header_addr.IsValid() && 1123 m_kext_summary_header_addr.GetFileAddress() != 0) 1124 { 1125 const size_t bytes_read = m_process->GetTarget().ReadMemory (m_kext_summary_header_addr, prefer_file_cache, buf, count, error); 1126 if (bytes_read == count) 1127 { 1128 lldb::offset_t offset = 0; 1129 m_kext_summary_header.version = data.GetU32(&offset); 1130 if (m_kext_summary_header.version >= 2) 1131 { 1132 m_kext_summary_header.entry_size = data.GetU32(&offset); 1133 } 1134 else 1135 { 1136 // Versions less than 2 didn't have an entry size, it was hard coded 1137 m_kext_summary_header.entry_size = KERNEL_MODULE_ENTRY_SIZE_VERSION_1; 1138 } 1139 m_kext_summary_header.entry_count = data.GetU32(&offset); 1140 return true; 1141 } 1142 } 1143 } 1144 } 1145 m_kext_summary_header_addr.Clear(); 1146 return false; 1147 } 1148 1149 // We've either (a) just attached to a new kernel, or (b) the kexts-changed breakpoint was hit 1150 // and we need to figure out what kexts have been added or removed. 1151 // Read the kext summaries from the inferior kernel memory, compare them against the 1152 // m_known_kexts vector and update the m_known_kexts vector as needed to keep in sync with the 1153 // inferior. 1154 1155 bool 1156 DynamicLoaderDarwinKernel::ParseKextSummaries (const Address &kext_summary_addr, uint32_t count) 1157 { 1158 KextImageInfo::collection kext_summaries; 1159 Log *log(GetLogIfAnyCategoriesSet (LIBLLDB_LOG_DYNAMIC_LOADER)); 1160 if (log) 1161 log->Printf ("Kexts-changed breakpoint hit, there are %d kexts currently.\n", count); 1162 1163 Mutex::Locker locker(m_mutex); 1164 1165 if (!ReadKextSummaries (kext_summary_addr, count, kext_summaries)) 1166 return false; 1167 1168 // read the plugin.dynamic-loader.darwin-kernel.load-kexts setting -- if the user requested no 1169 // kext loading, don't print any messages about kexts & don't try to read them. 1170 const bool load_kexts = GetGlobalProperties()->GetLoadKexts(); 1171 1172 // By default, all kexts we've loaded in the past are marked as "remove" and all of the kexts 1173 // we just found out about from ReadKextSummaries are marked as "add". 1174 std::vector<bool> to_be_removed(m_known_kexts.size(), true); 1175 std::vector<bool> to_be_added(count, true); 1176 1177 int number_of_new_kexts_being_added = 0; 1178 int number_of_old_kexts_being_removed = m_known_kexts.size(); 1179 1180 const uint32_t new_kexts_size = kext_summaries.size(); 1181 const uint32_t old_kexts_size = m_known_kexts.size(); 1182 1183 // The m_known_kexts vector may have entries that have been Cleared, 1184 // or are a kernel. 1185 for (uint32_t old_kext = 0; old_kext < old_kexts_size; old_kext++) 1186 { 1187 bool ignore = false; 1188 KextImageInfo &image_info = m_known_kexts[old_kext]; 1189 if (image_info.IsKernel()) 1190 { 1191 ignore = true; 1192 } 1193 else if (image_info.GetLoadAddress() == LLDB_INVALID_ADDRESS && !image_info.GetModule()) 1194 { 1195 ignore = true; 1196 } 1197 1198 if (ignore) 1199 { 1200 number_of_old_kexts_being_removed--; 1201 to_be_removed[old_kext] = false; 1202 } 1203 } 1204 1205 // Scan over the list of kexts we just read from the kernel, note those that 1206 // need to be added and those already loaded. 1207 for (uint32_t new_kext = 0; new_kext < new_kexts_size; new_kext++) 1208 { 1209 bool add_this_one = true; 1210 for (uint32_t old_kext = 0; old_kext < old_kexts_size; old_kext++) 1211 { 1212 if (m_known_kexts[old_kext] == kext_summaries[new_kext]) 1213 { 1214 // We already have this kext, don't re-load it. 1215 to_be_added[new_kext] = false; 1216 // This kext is still present, do not remove it. 1217 to_be_removed[old_kext] = false; 1218 1219 number_of_old_kexts_being_removed--; 1220 add_this_one = false; 1221 break; 1222 } 1223 } 1224 if (add_this_one) 1225 { 1226 number_of_new_kexts_being_added++; 1227 } 1228 } 1229 1230 if (number_of_new_kexts_being_added == 0 && number_of_old_kexts_being_removed == 0) 1231 return true; 1232 1233 Stream *s = &m_process->GetTarget().GetDebugger().GetOutputStream(); 1234 if (s && load_kexts) 1235 { 1236 if (number_of_new_kexts_being_added > 0 && number_of_old_kexts_being_removed > 0) 1237 { 1238 s->Printf ("Loading %d kext modules and unloading %d kext modules ", number_of_new_kexts_being_added, number_of_old_kexts_being_removed); 1239 } 1240 else if (number_of_new_kexts_being_added > 0) 1241 { 1242 s->Printf ("Loading %d kext modules ", number_of_new_kexts_being_added); 1243 } 1244 else if (number_of_old_kexts_being_removed > 0) 1245 { 1246 s->Printf ("Unloading %d kext modules ", number_of_old_kexts_being_removed); 1247 } 1248 } 1249 1250 if (log) 1251 { 1252 if (load_kexts) 1253 { 1254 log->Printf ("DynamicLoaderDarwinKernel::ParseKextSummaries: %d kexts added, %d kexts removed", number_of_new_kexts_being_added, number_of_old_kexts_being_removed); 1255 } 1256 else 1257 { 1258 log->Printf ("DynamicLoaderDarwinKernel::ParseKextSummaries kext loading is disabled, else would have %d kexts added, %d kexts removed", number_of_new_kexts_being_added, number_of_old_kexts_being_removed); 1259 } 1260 } 1261 1262 1263 if (number_of_new_kexts_being_added > 0) 1264 { 1265 ModuleList loaded_module_list; 1266 1267 const uint32_t num_of_new_kexts = kext_summaries.size(); 1268 for (uint32_t new_kext = 0; new_kext < num_of_new_kexts; new_kext++) 1269 { 1270 if (to_be_added[new_kext] == true) 1271 { 1272 KextImageInfo &image_info = kext_summaries[new_kext]; 1273 if (load_kexts) 1274 { 1275 if (!image_info.LoadImageUsingMemoryModule (m_process)) 1276 { 1277 image_info.LoadImageAtFileAddress (m_process); 1278 } 1279 } 1280 1281 m_known_kexts.push_back(image_info); 1282 1283 if (image_info.GetModule() && m_process->GetStopID() == image_info.GetProcessStopId()) 1284 loaded_module_list.AppendIfNeeded (image_info.GetModule()); 1285 1286 if (s && load_kexts) 1287 s->Printf ("."); 1288 1289 if (log) 1290 kext_summaries[new_kext].PutToLog (log); 1291 } 1292 } 1293 m_process->GetTarget().ModulesDidLoad (loaded_module_list); 1294 } 1295 1296 if (number_of_old_kexts_being_removed > 0) 1297 { 1298 ModuleList loaded_module_list; 1299 const uint32_t num_of_old_kexts = m_known_kexts.size(); 1300 for (uint32_t old_kext = 0; old_kext < num_of_old_kexts; old_kext++) 1301 { 1302 ModuleList unloaded_module_list; 1303 if (to_be_removed[old_kext]) 1304 { 1305 KextImageInfo &image_info = m_known_kexts[old_kext]; 1306 // You can't unload the kernel. 1307 if (!image_info.IsKernel()) 1308 { 1309 if (image_info.GetModule()) 1310 { 1311 unloaded_module_list.AppendIfNeeded (image_info.GetModule()); 1312 } 1313 if (s) 1314 s->Printf ("."); 1315 image_info.Clear(); 1316 // should pull it out of the KextImageInfos vector but that would mutate the list and invalidate 1317 // the to_be_removed bool vector; leaving it in place once Cleared() is relatively harmless. 1318 } 1319 } 1320 m_process->GetTarget().ModulesDidUnload (unloaded_module_list); 1321 } 1322 } 1323 1324 if (s && load_kexts) 1325 { 1326 s->Printf (" done.\n"); 1327 s->Flush (); 1328 } 1329 1330 return true; 1331 } 1332 1333 uint32_t 1334 DynamicLoaderDarwinKernel::ReadKextSummaries (const Address &kext_summary_addr, 1335 uint32_t image_infos_count, 1336 KextImageInfo::collection &image_infos) 1337 { 1338 const ByteOrder endian = m_kernel.GetByteOrder(); 1339 const uint32_t addr_size = m_kernel.GetAddressByteSize(); 1340 1341 image_infos.resize(image_infos_count); 1342 const size_t count = image_infos.size() * m_kext_summary_header.entry_size; 1343 DataBufferHeap data(count, 0); 1344 Error error; 1345 1346 const bool prefer_file_cache = false; 1347 const size_t bytes_read = m_process->GetTarget().ReadMemory (kext_summary_addr, 1348 prefer_file_cache, 1349 data.GetBytes(), 1350 data.GetByteSize(), 1351 error); 1352 if (bytes_read == count) 1353 { 1354 1355 DataExtractor extractor (data.GetBytes(), data.GetByteSize(), endian, addr_size); 1356 uint32_t i=0; 1357 for (uint32_t kext_summary_offset = 0; 1358 i < image_infos.size() && extractor.ValidOffsetForDataOfSize(kext_summary_offset, m_kext_summary_header.entry_size); 1359 ++i, kext_summary_offset += m_kext_summary_header.entry_size) 1360 { 1361 lldb::offset_t offset = kext_summary_offset; 1362 const void *name_data = extractor.GetData(&offset, KERNEL_MODULE_MAX_NAME); 1363 if (name_data == NULL) 1364 break; 1365 image_infos[i].SetName ((const char *) name_data); 1366 UUID uuid (extractor.GetData (&offset, 16), 16); 1367 image_infos[i].SetUUID (uuid); 1368 image_infos[i].SetLoadAddress (extractor.GetU64(&offset)); 1369 image_infos[i].SetSize (extractor.GetU64(&offset)); 1370 } 1371 if (i < image_infos.size()) 1372 image_infos.resize(i); 1373 } 1374 else 1375 { 1376 image_infos.clear(); 1377 } 1378 return image_infos.size(); 1379 } 1380 1381 bool 1382 DynamicLoaderDarwinKernel::ReadAllKextSummaries () 1383 { 1384 Mutex::Locker locker(m_mutex); 1385 1386 if (ReadKextSummaryHeader ()) 1387 { 1388 if (m_kext_summary_header.entry_count > 0 && m_kext_summary_header_addr.IsValid()) 1389 { 1390 Address summary_addr (m_kext_summary_header_addr); 1391 summary_addr.Slide(m_kext_summary_header.GetSize()); 1392 if (!ParseKextSummaries (summary_addr, m_kext_summary_header.entry_count)) 1393 { 1394 m_known_kexts.clear(); 1395 } 1396 return true; 1397 } 1398 } 1399 return false; 1400 } 1401 1402 //---------------------------------------------------------------------- 1403 // Dump an image info structure to the file handle provided. 1404 //---------------------------------------------------------------------- 1405 void 1406 DynamicLoaderDarwinKernel::KextImageInfo::PutToLog (Log *log) const 1407 { 1408 if (log == NULL) 1409 return; 1410 const uint8_t *u = (uint8_t *) m_uuid.GetBytes(); 1411 1412 if (m_load_address == LLDB_INVALID_ADDRESS) 1413 { 1414 if (u) 1415 { 1416 log->Printf("\tuuid=%2.2X%2.2X%2.2X%2.2X-%2.2X%2.2X-%2.2X%2.2X-%2.2X%2.2X-%2.2X%2.2X%2.2X%2.2X%2.2X%2.2X name=\"%s\" (UNLOADED)", 1417 u[ 0], u[ 1], u[ 2], u[ 3], 1418 u[ 4], u[ 5], u[ 6], u[ 7], 1419 u[ 8], u[ 9], u[10], u[11], 1420 u[12], u[13], u[14], u[15], 1421 m_name.c_str()); 1422 } 1423 else 1424 log->Printf("\tname=\"%s\" (UNLOADED)", m_name.c_str()); 1425 } 1426 else 1427 { 1428 if (u) 1429 { 1430 log->Printf("\taddr=0x%16.16" PRIx64 " size=0x%16.16" PRIx64 " uuid=%2.2X%2.2X%2.2X%2.2X-%2.2X%2.2X-%2.2X%2.2X-%2.2X%2.2X-%2.2X%2.2X%2.2X%2.2X%2.2X%2.2X name=\"%s\"", 1431 m_load_address, m_size, 1432 u[ 0], u[ 1], u[ 2], u[ 3], u[ 4], u[ 5], u[ 6], u[ 7], 1433 u[ 8], u[ 9], u[10], u[11], u[12], u[13], u[14], u[15], 1434 m_name.c_str()); 1435 } 1436 else 1437 { 1438 log->Printf("\t[0x%16.16" PRIx64 " - 0x%16.16" PRIx64 ") name=\"%s\"", 1439 m_load_address, m_load_address+m_size, m_name.c_str()); 1440 } 1441 } 1442 } 1443 1444 //---------------------------------------------------------------------- 1445 // Dump the _dyld_all_image_infos members and all current image infos 1446 // that we have parsed to the file handle provided. 1447 //---------------------------------------------------------------------- 1448 void 1449 DynamicLoaderDarwinKernel::PutToLog(Log *log) const 1450 { 1451 if (log == NULL) 1452 return; 1453 1454 Mutex::Locker locker(m_mutex); 1455 log->Printf("gLoadedKextSummaries = 0x%16.16" PRIx64 " { version=%u, entry_size=%u, entry_count=%u }", 1456 m_kext_summary_header_addr.GetFileAddress(), 1457 m_kext_summary_header.version, 1458 m_kext_summary_header.entry_size, 1459 m_kext_summary_header.entry_count); 1460 1461 size_t i; 1462 const size_t count = m_known_kexts.size(); 1463 if (count > 0) 1464 { 1465 log->PutCString("Loaded:"); 1466 for (i = 0; i<count; i++) 1467 m_known_kexts[i].PutToLog(log); 1468 } 1469 } 1470 1471 void 1472 DynamicLoaderDarwinKernel::PrivateInitialize(Process *process) 1473 { 1474 DEBUG_PRINTF("DynamicLoaderDarwinKernel::%s() process state = %s\n", __FUNCTION__, StateAsCString(m_process->GetState())); 1475 Clear(true); 1476 m_process = process; 1477 } 1478 1479 void 1480 DynamicLoaderDarwinKernel::SetNotificationBreakpointIfNeeded () 1481 { 1482 if (m_break_id == LLDB_INVALID_BREAK_ID && m_kernel.GetModule()) 1483 { 1484 DEBUG_PRINTF("DynamicLoaderDarwinKernel::%s() process state = %s\n", __FUNCTION__, StateAsCString(m_process->GetState())); 1485 1486 1487 const bool internal_bp = true; 1488 const LazyBool skip_prologue = eLazyBoolNo; 1489 FileSpecList module_spec_list; 1490 module_spec_list.Append (m_kernel.GetModule()->GetFileSpec()); 1491 Breakpoint *bp = m_process->GetTarget().CreateBreakpoint (&module_spec_list, 1492 NULL, 1493 "OSKextLoadedKextSummariesUpdated", 1494 eFunctionNameTypeFull, 1495 skip_prologue, 1496 internal_bp).get(); 1497 1498 bp->SetCallback (DynamicLoaderDarwinKernel::BreakpointHitCallback, this, true); 1499 m_break_id = bp->GetID(); 1500 } 1501 } 1502 1503 //---------------------------------------------------------------------- 1504 // Member function that gets called when the process state changes. 1505 //---------------------------------------------------------------------- 1506 void 1507 DynamicLoaderDarwinKernel::PrivateProcessStateChanged (Process *process, StateType state) 1508 { 1509 DEBUG_PRINTF("DynamicLoaderDarwinKernel::%s(%s)\n", __FUNCTION__, StateAsCString(state)); 1510 switch (state) 1511 { 1512 case eStateConnected: 1513 case eStateAttaching: 1514 case eStateLaunching: 1515 case eStateInvalid: 1516 case eStateUnloaded: 1517 case eStateExited: 1518 case eStateDetached: 1519 Clear(false); 1520 break; 1521 1522 case eStateStopped: 1523 UpdateIfNeeded(); 1524 break; 1525 1526 case eStateRunning: 1527 case eStateStepping: 1528 case eStateCrashed: 1529 case eStateSuspended: 1530 break; 1531 } 1532 } 1533 1534 ThreadPlanSP 1535 DynamicLoaderDarwinKernel::GetStepThroughTrampolinePlan (Thread &thread, bool stop_others) 1536 { 1537 ThreadPlanSP thread_plan_sp; 1538 Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP)); 1539 if (log) 1540 log->Printf ("Could not find symbol for step through."); 1541 return thread_plan_sp; 1542 } 1543 1544 Error 1545 DynamicLoaderDarwinKernel::CanLoadImage () 1546 { 1547 Error error; 1548 error.SetErrorString("always unsafe to load or unload shared libraries in the darwin kernel"); 1549 return error; 1550 } 1551 1552 void 1553 DynamicLoaderDarwinKernel::Initialize() 1554 { 1555 PluginManager::RegisterPlugin (GetPluginNameStatic(), 1556 GetPluginDescriptionStatic(), 1557 CreateInstance, 1558 DebuggerInitialize); 1559 } 1560 1561 void 1562 DynamicLoaderDarwinKernel::Terminate() 1563 { 1564 PluginManager::UnregisterPlugin (CreateInstance); 1565 } 1566 1567 void 1568 DynamicLoaderDarwinKernel::DebuggerInitialize (lldb_private::Debugger &debugger) 1569 { 1570 if (!PluginManager::GetSettingForDynamicLoaderPlugin (debugger, DynamicLoaderDarwinKernelProperties::GetSettingName())) 1571 { 1572 const bool is_global_setting = true; 1573 PluginManager::CreateSettingForDynamicLoaderPlugin (debugger, 1574 GetGlobalProperties()->GetValueProperties(), 1575 ConstString ("Properties for the DynamicLoaderDarwinKernel plug-in."), 1576 is_global_setting); 1577 } 1578 } 1579 1580 const char * 1581 DynamicLoaderDarwinKernel::GetPluginNameStatic() 1582 { 1583 return "dynamic-loader.darwin-kernel"; 1584 } 1585 1586 const char * 1587 DynamicLoaderDarwinKernel::GetPluginDescriptionStatic() 1588 { 1589 return "Dynamic loader plug-in that watches for shared library loads/unloads in the MacOSX kernel."; 1590 } 1591 1592 1593 //------------------------------------------------------------------ 1594 // PluginInterface protocol 1595 //------------------------------------------------------------------ 1596 const char * 1597 DynamicLoaderDarwinKernel::GetPluginName() 1598 { 1599 return "DynamicLoaderDarwinKernel"; 1600 } 1601 1602 const char * 1603 DynamicLoaderDarwinKernel::GetShortPluginName() 1604 { 1605 return GetPluginNameStatic(); 1606 } 1607 1608 uint32_t 1609 DynamicLoaderDarwinKernel::GetPluginVersion() 1610 { 1611 return 1; 1612 } 1613 1614 lldb::ByteOrder 1615 DynamicLoaderDarwinKernel::GetByteOrderFromMagic (uint32_t magic) 1616 { 1617 switch (magic) 1618 { 1619 case llvm::MachO::HeaderMagic32: 1620 case llvm::MachO::HeaderMagic64: 1621 return lldb::endian::InlHostByteOrder(); 1622 1623 case llvm::MachO::HeaderMagic32Swapped: 1624 case llvm::MachO::HeaderMagic64Swapped: 1625 if (lldb::endian::InlHostByteOrder() == lldb::eByteOrderBig) 1626 return lldb::eByteOrderLittle; 1627 else 1628 return lldb::eByteOrderBig; 1629 1630 default: 1631 break; 1632 } 1633 return lldb::eByteOrderInvalid; 1634 } 1635 1636