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