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