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