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