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 if (m_memory_module_sp.get() != NULL) 672 return true; 673 if (m_load_address == LLDB_INVALID_ADDRESS) 674 return false; 675 676 FileSpec file_spec; 677 file_spec.SetFile (m_name.c_str(), false); 678 679 ModuleSP memory_module_sp = process->ReadModuleFromMemory (file_spec, m_load_address); 680 681 if (memory_module_sp.get() == NULL) 682 return false; 683 684 bool is_kernel = false; 685 if (memory_module_sp->GetObjectFile()) 686 { 687 if (memory_module_sp->GetObjectFile()->GetType() == ObjectFile::eTypeExecutable 688 && memory_module_sp->GetObjectFile()->GetStrata() == ObjectFile::eStrataKernel) 689 { 690 is_kernel = true; 691 } 692 else if (memory_module_sp->GetObjectFile()->GetType() == ObjectFile::eTypeSharedLibrary) 693 { 694 is_kernel = false; 695 } 696 } 697 698 // If this is a kext, and the kernel specified what UUID we should find at this 699 // load address, require that the memory module have a matching UUID or something 700 // has gone wrong and we should discard it. 701 if (m_uuid.IsValid()) 702 { 703 if (m_uuid != memory_module_sp->GetUUID()) 704 { 705 return false; 706 } 707 } 708 709 // If the in-memory Module has a UUID, let's use that. 710 if (!m_uuid.IsValid() && memory_module_sp->GetUUID().IsValid()) 711 { 712 m_uuid = memory_module_sp->GetUUID(); 713 } 714 715 m_memory_module_sp = memory_module_sp; 716 m_kernel_image = is_kernel; 717 if (is_kernel) 718 { 719 if (memory_module_sp->GetArchitecture().IsValid()) 720 { 721 process->GetTarget().SetArchitecture(memory_module_sp->GetArchitecture()); 722 } 723 if (m_uuid.IsValid()) 724 { 725 ModuleSP exe_module_sp = process->GetTarget().GetExecutableModule(); 726 if (exe_module_sp.get() && exe_module_sp->GetUUID().IsValid()) 727 { 728 if (m_uuid != exe_module_sp->GetUUID()) 729 { 730 // The user specified a kernel binary that has a different UUID than 731 // the kernel actually running in memory. This never ends well; 732 // clear the user specified kernel binary from the Target. 733 734 m_module_sp.reset(); 735 736 ModuleList user_specified_kernel_list; 737 user_specified_kernel_list.Append (exe_module_sp); 738 process->GetTarget().GetImages().Remove (user_specified_kernel_list); 739 } 740 } 741 } 742 } 743 744 return true; 745 } 746 747 bool 748 DynamicLoaderDarwinKernel::KextImageInfo::IsKernel () const 749 { 750 return m_kernel_image == true; 751 } 752 753 void 754 DynamicLoaderDarwinKernel::KextImageInfo::SetIsKernel (bool is_kernel) 755 { 756 m_kernel_image = is_kernel; 757 } 758 759 bool 760 DynamicLoaderDarwinKernel::KextImageInfo::LoadImageUsingMemoryModule (Process *process) 761 { 762 if (IsLoaded()) 763 return true; 764 765 766 Target &target = process->GetTarget(); 767 768 // If we don't have / can't create a memory module for this kext, don't try to load it - we won't 769 // have the correct segment load addresses. 770 if (!ReadMemoryModule (process)) 771 { 772 return false; 773 } 774 775 bool uuid_is_valid = m_uuid.IsValid(); 776 777 if (IsKernel() && uuid_is_valid && m_memory_module_sp.get()) 778 { 779 Stream *s = target.GetDebugger().GetOutputFile().get(); 780 if (s) 781 { 782 s->Printf ("Kernel UUID: %s\n", m_memory_module_sp->GetUUID().GetAsString().c_str()); 783 s->Printf ("Load Address: 0x%" PRIx64 "\n", m_load_address); 784 } 785 } 786 787 if (!m_module_sp) 788 { 789 // See if the kext has already been loaded into the target, probably by the user doing target modules add. 790 const ModuleList &target_images = target.GetImages(); 791 m_module_sp = target_images.FindModule(m_uuid); 792 793 // Search for the kext on the local filesystem via the UUID 794 if (!m_module_sp && uuid_is_valid) 795 { 796 ModuleSpec module_spec; 797 module_spec.GetUUID() = m_uuid; 798 module_spec.GetArchitecture() = target.GetArchitecture(); 799 800 // For the kernel, we really do need an on-disk file copy of the binary to do anything useful. 801 // This will force a clal to 802 if (IsKernel()) 803 { 804 if (Symbols::DownloadObjectAndSymbolFile (module_spec, true)) 805 { 806 if (module_spec.GetFileSpec().Exists()) 807 { 808 m_module_sp.reset(new Module (module_spec.GetFileSpec(), target.GetArchitecture())); 809 if (m_module_sp.get() && m_module_sp->MatchesModuleSpec (module_spec)) 810 { 811 ModuleList loaded_module_list; 812 loaded_module_list.Append (m_module_sp); 813 target.ModulesDidLoad (loaded_module_list); 814 } 815 } 816 } 817 } 818 819 // If the current platform is PlatformDarwinKernel, create a ModuleSpec with the filename set 820 // to be the bundle ID for this kext, e.g. "com.apple.filesystems.msdosfs", and ask the platform 821 // to find it. 822 PlatformSP platform_sp (target.GetPlatform()); 823 if (!m_module_sp && platform_sp) 824 { 825 ConstString platform_name (platform_sp->GetPluginName()); 826 static ConstString g_platform_name (PlatformDarwinKernel::GetPluginNameStatic()); 827 if (platform_name == g_platform_name) 828 { 829 ModuleSpec kext_bundle_module_spec(module_spec); 830 FileSpec kext_filespec(m_name.c_str(), false); 831 kext_bundle_module_spec.GetFileSpec() = kext_filespec; 832 platform_sp->GetSharedModule (kext_bundle_module_spec, process, m_module_sp, &target.GetExecutableSearchPaths(), NULL, NULL); 833 } 834 } 835 836 // Ask the Target to find this file on the local system, if possible. 837 // This will search in the list of currently-loaded files, look in the 838 // standard search paths on the system, and on a Mac it will try calling 839 // the DebugSymbols framework with the UUID to find the binary via its 840 // search methods. 841 if (!m_module_sp) 842 { 843 m_module_sp = target.GetSharedModule (module_spec); 844 } 845 846 if (IsKernel() && !m_module_sp) 847 { 848 Stream *s = target.GetDebugger().GetOutputFile().get(); 849 if (s) 850 { 851 s->Printf ("WARNING: Unable to locate kernel binary on the debugger system.\n"); 852 } 853 } 854 } 855 856 // If we managed to find a module, append it to the target's list of images. 857 // If we also have a memory module, require that they have matching UUIDs 858 if (m_module_sp) 859 { 860 bool uuid_match_ok = true; 861 if (m_memory_module_sp) 862 { 863 if (m_module_sp->GetUUID() != m_memory_module_sp->GetUUID()) 864 { 865 uuid_match_ok = false; 866 } 867 } 868 if (uuid_match_ok) 869 { 870 target.GetImages().AppendIfNeeded(m_module_sp); 871 if (IsKernel() && target.GetExecutableModulePointer() != m_module_sp.get()) 872 { 873 target.SetExecutableModule (m_module_sp, false); 874 } 875 } 876 } 877 } 878 879 if (!m_module_sp && !IsKernel() && m_uuid.IsValid() && !m_name.empty()) 880 { 881 Stream *s = target.GetDebugger().GetOutputFile().get(); 882 if (s) 883 { 884 s->Printf ("warning: Can't find binary/dSYM for %s (%s)\n", 885 m_name.c_str(), m_uuid.GetAsString().c_str()); 886 } 887 } 888 889 static ConstString g_section_name_LINKEDIT ("__LINKEDIT"); 890 891 if (m_memory_module_sp && m_module_sp) 892 { 893 if (m_module_sp->GetUUID() == m_memory_module_sp->GetUUID()) 894 { 895 ObjectFile *ondisk_object_file = m_module_sp->GetObjectFile(); 896 ObjectFile *memory_object_file = m_memory_module_sp->GetObjectFile(); 897 898 if (memory_object_file && ondisk_object_file) 899 { 900 // The memory_module for kexts may have an invalid __LINKEDIT seg; skip it. 901 const bool ignore_linkedit = !IsKernel (); 902 903 SectionList *ondisk_section_list = ondisk_object_file->GetSectionList (); 904 SectionList *memory_section_list = memory_object_file->GetSectionList (); 905 if (memory_section_list && ondisk_section_list) 906 { 907 const uint32_t num_ondisk_sections = ondisk_section_list->GetSize(); 908 // There may be CTF sections in the memory image so we can't 909 // always just compare the number of sections (which are actually 910 // segments in mach-o parlance) 911 uint32_t sect_idx = 0; 912 913 // Use the memory_module's addresses for each section to set the 914 // file module's load address as appropriate. We don't want to use 915 // a single slide value for the entire kext - different segments may 916 // be slid different amounts by the kext loader. 917 918 uint32_t num_sections_loaded = 0; 919 for (sect_idx=0; sect_idx<num_ondisk_sections; ++sect_idx) 920 { 921 SectionSP ondisk_section_sp(ondisk_section_list->GetSectionAtIndex(sect_idx)); 922 if (ondisk_section_sp) 923 { 924 // Don't ever load __LINKEDIT as it may or may not be actually 925 // mapped into memory and there is no current way to tell. 926 // I filed rdar://problem/12851706 to track being able to tell 927 // if the __LINKEDIT is actually mapped, but until then, we need 928 // to not load the __LINKEDIT 929 if (ignore_linkedit && ondisk_section_sp->GetName() == g_section_name_LINKEDIT) 930 continue; 931 932 const Section *memory_section = memory_section_list->FindSectionByName(ondisk_section_sp->GetName()).get(); 933 if (memory_section) 934 { 935 target.SetSectionLoadAddress (ondisk_section_sp, memory_section->GetFileAddress()); 936 ++num_sections_loaded; 937 } 938 } 939 } 940 if (num_sections_loaded > 0) 941 m_load_process_stop_id = process->GetStopID(); 942 else 943 m_module_sp.reset(); // No sections were loaded 944 } 945 else 946 m_module_sp.reset(); // One or both section lists 947 } 948 else 949 m_module_sp.reset(); // One or both object files missing 950 } 951 else 952 m_module_sp.reset(); // UUID mismatch 953 } 954 955 bool is_loaded = IsLoaded(); 956 957 if (is_loaded && m_module_sp && IsKernel()) 958 { 959 Stream *s = target.GetDebugger().GetOutputFile().get(); 960 if (s) 961 { 962 ObjectFile *kernel_object_file = m_module_sp->GetObjectFile(); 963 if (kernel_object_file) 964 { 965 addr_t file_address = kernel_object_file->GetHeaderAddress().GetFileAddress(); 966 if (m_load_address != LLDB_INVALID_ADDRESS && file_address != LLDB_INVALID_ADDRESS) 967 { 968 s->Printf ("Kernel slid 0x%" PRIx64 " in memory.\n", m_load_address - file_address); 969 } 970 } 971 { 972 s->Printf ("Loaded kernel file %s\n", 973 m_module_sp->GetFileSpec().GetPath().c_str()); 974 } 975 s->Flush (); 976 } 977 } 978 return is_loaded; 979 } 980 981 uint32_t 982 DynamicLoaderDarwinKernel::KextImageInfo::GetAddressByteSize () 983 { 984 if (m_memory_module_sp) 985 return m_memory_module_sp->GetArchitecture().GetAddressByteSize(); 986 if (m_module_sp) 987 return m_module_sp->GetArchitecture().GetAddressByteSize(); 988 return 0; 989 } 990 991 lldb::ByteOrder 992 DynamicLoaderDarwinKernel::KextImageInfo::GetByteOrder() 993 { 994 if (m_memory_module_sp) 995 return m_memory_module_sp->GetArchitecture().GetByteOrder(); 996 if (m_module_sp) 997 return m_module_sp->GetArchitecture().GetByteOrder(); 998 return lldb::endian::InlHostByteOrder(); 999 } 1000 1001 lldb_private::ArchSpec 1002 DynamicLoaderDarwinKernel::KextImageInfo::GetArchitecture () const 1003 { 1004 if (m_memory_module_sp) 1005 return m_memory_module_sp->GetArchitecture(); 1006 if (m_module_sp) 1007 return m_module_sp->GetArchitecture(); 1008 return lldb_private::ArchSpec (); 1009 } 1010 1011 1012 //---------------------------------------------------------------------- 1013 // Load the kernel module and initialize the "m_kernel" member. Return 1014 // true _only_ if the kernel is loaded the first time through (subsequent 1015 // calls to this function should return false after the kernel has been 1016 // already loaded). 1017 //---------------------------------------------------------------------- 1018 void 1019 DynamicLoaderDarwinKernel::LoadKernelModuleIfNeeded() 1020 { 1021 if (!m_kext_summary_header_ptr_addr.IsValid()) 1022 { 1023 m_kernel.Clear(); 1024 m_kernel.SetModule (m_process->GetTarget().GetExecutableModule()); 1025 m_kernel.SetIsKernel(true); 1026 1027 ConstString kernel_name("mach_kernel"); 1028 if (m_kernel.GetModule().get() 1029 && m_kernel.GetModule()->GetObjectFile() 1030 && !m_kernel.GetModule()->GetObjectFile()->GetFileSpec().GetFilename().IsEmpty()) 1031 { 1032 kernel_name = m_kernel.GetModule()->GetObjectFile()->GetFileSpec().GetFilename(); 1033 } 1034 m_kernel.SetName (kernel_name.AsCString()); 1035 1036 if (m_kernel.GetLoadAddress() == LLDB_INVALID_ADDRESS) 1037 { 1038 m_kernel.SetLoadAddress(m_kernel_load_address); 1039 if (m_kernel.GetLoadAddress() == LLDB_INVALID_ADDRESS && m_kernel.GetModule()) 1040 { 1041 // We didn't get a hint from the process, so we will 1042 // try the kernel at the address that it exists at in 1043 // the file if we have one 1044 ObjectFile *kernel_object_file = m_kernel.GetModule()->GetObjectFile(); 1045 if (kernel_object_file) 1046 { 1047 addr_t load_address = kernel_object_file->GetHeaderAddress().GetLoadAddress(&m_process->GetTarget()); 1048 addr_t file_address = kernel_object_file->GetHeaderAddress().GetFileAddress(); 1049 if (load_address != LLDB_INVALID_ADDRESS && load_address != 0) 1050 { 1051 m_kernel.SetLoadAddress (load_address); 1052 if (load_address != file_address) 1053 { 1054 // Don't accidentally relocate the kernel to the File address -- 1055 // the Load address has already been set to its actual in-memory address. 1056 // Mark it as IsLoaded. 1057 m_kernel.SetProcessStopId (m_process->GetStopID()); 1058 } 1059 } 1060 else 1061 { 1062 m_kernel.SetLoadAddress(file_address); 1063 } 1064 } 1065 } 1066 } 1067 1068 if (m_kernel.GetLoadAddress() != LLDB_INVALID_ADDRESS) 1069 { 1070 if (!m_kernel.LoadImageUsingMemoryModule (m_process)) 1071 { 1072 m_kernel.LoadImageAtFileAddress (m_process); 1073 } 1074 } 1075 1076 if (m_kernel.IsLoaded() && m_kernel.GetModule()) 1077 { 1078 static ConstString kext_summary_symbol ("gLoadedKextSummaries"); 1079 const Symbol *symbol = m_kernel.GetModule()->FindFirstSymbolWithNameAndType (kext_summary_symbol, eSymbolTypeData); 1080 if (symbol) 1081 { 1082 m_kext_summary_header_ptr_addr = symbol->GetAddress(); 1083 // Update all image infos 1084 ReadAllKextSummaries (); 1085 } 1086 } 1087 else 1088 { 1089 m_kernel.Clear(); 1090 } 1091 } 1092 } 1093 1094 //---------------------------------------------------------------------- 1095 // Static callback function that gets called when our DYLD notification 1096 // breakpoint gets hit. We update all of our image infos and then 1097 // let our super class DynamicLoader class decide if we should stop 1098 // or not (based on global preference). 1099 //---------------------------------------------------------------------- 1100 bool 1101 DynamicLoaderDarwinKernel::BreakpointHitCallback (void *baton, 1102 StoppointCallbackContext *context, 1103 user_id_t break_id, 1104 user_id_t break_loc_id) 1105 { 1106 return static_cast<DynamicLoaderDarwinKernel*>(baton)->BreakpointHit (context, break_id, break_loc_id); 1107 } 1108 1109 bool 1110 DynamicLoaderDarwinKernel::BreakpointHit (StoppointCallbackContext *context, 1111 user_id_t break_id, 1112 user_id_t break_loc_id) 1113 { 1114 Log *log(GetLogIfAnyCategoriesSet (LIBLLDB_LOG_DYNAMIC_LOADER)); 1115 if (log) 1116 log->Printf ("DynamicLoaderDarwinKernel::BreakpointHit (...)\n"); 1117 1118 ReadAllKextSummaries (); 1119 1120 if (log) 1121 PutToLog(log); 1122 1123 return GetStopWhenImagesChange(); 1124 } 1125 1126 1127 bool 1128 DynamicLoaderDarwinKernel::ReadKextSummaryHeader () 1129 { 1130 Mutex::Locker locker(m_mutex); 1131 1132 // the all image infos is already valid for this process stop ID 1133 1134 if (m_kext_summary_header_ptr_addr.IsValid()) 1135 { 1136 const uint32_t addr_size = m_kernel.GetAddressByteSize (); 1137 const ByteOrder byte_order = m_kernel.GetByteOrder(); 1138 Error error; 1139 // Read enough bytes for a "OSKextLoadedKextSummaryHeader" structure 1140 // which is currently 4 uint32_t and a pointer. 1141 uint8_t buf[24]; 1142 DataExtractor data (buf, sizeof(buf), byte_order, addr_size); 1143 const size_t count = 4 * sizeof(uint32_t) + addr_size; 1144 const bool prefer_file_cache = false; 1145 if (m_process->GetTarget().ReadPointerFromMemory (m_kext_summary_header_ptr_addr, 1146 prefer_file_cache, 1147 error, 1148 m_kext_summary_header_addr)) 1149 { 1150 // We got a valid address for our kext summary header and make sure it isn't NULL 1151 if (m_kext_summary_header_addr.IsValid() && 1152 m_kext_summary_header_addr.GetFileAddress() != 0) 1153 { 1154 const size_t bytes_read = m_process->GetTarget().ReadMemory (m_kext_summary_header_addr, prefer_file_cache, buf, count, error); 1155 if (bytes_read == count) 1156 { 1157 lldb::offset_t offset = 0; 1158 m_kext_summary_header.version = data.GetU32(&offset); 1159 if (m_kext_summary_header.version > 128) 1160 { 1161 Stream *s = m_process->GetTarget().GetDebugger().GetOutputFile().get(); 1162 s->Printf ("WARNING: Unable to read kext summary header, got improbable version number %u\n", m_kext_summary_header.version); 1163 // If we get an improbably large version number, we're probably getting bad memory. 1164 m_kext_summary_header_addr.Clear(); 1165 return false; 1166 } 1167 if (m_kext_summary_header.version >= 2) 1168 { 1169 m_kext_summary_header.entry_size = data.GetU32(&offset); 1170 if (m_kext_summary_header.entry_size > 4096) 1171 { 1172 // If we get an improbably large entry_size, we're probably getting bad memory. 1173 Stream *s = m_process->GetTarget().GetDebugger().GetOutputFile().get(); 1174 s->Printf ("WARNING: Unable to read kext summary header, got improbable entry_size %u\n", m_kext_summary_header.entry_size); 1175 m_kext_summary_header_addr.Clear(); 1176 return false; 1177 } 1178 } 1179 else 1180 { 1181 // Versions less than 2 didn't have an entry size, it was hard coded 1182 m_kext_summary_header.entry_size = KERNEL_MODULE_ENTRY_SIZE_VERSION_1; 1183 } 1184 m_kext_summary_header.entry_count = data.GetU32(&offset); 1185 if (m_kext_summary_header.entry_count > 10000) 1186 { 1187 // If we get an improbably large number of kexts, we're probably getting bad memory. 1188 Stream *s = m_process->GetTarget().GetDebugger().GetOutputFile().get(); 1189 s->Printf ("WARNING: Unable to read kext summary header, got improbable number of kexts %u\n", m_kext_summary_header.entry_count); 1190 m_kext_summary_header_addr.Clear(); 1191 return false; 1192 } 1193 return true; 1194 } 1195 } 1196 } 1197 } 1198 m_kext_summary_header_addr.Clear(); 1199 return false; 1200 } 1201 1202 // We've either (a) just attached to a new kernel, or (b) the kexts-changed breakpoint was hit 1203 // and we need to figure out what kexts have been added or removed. 1204 // Read the kext summaries from the inferior kernel memory, compare them against the 1205 // m_known_kexts vector and update the m_known_kexts vector as needed to keep in sync with the 1206 // inferior. 1207 1208 bool 1209 DynamicLoaderDarwinKernel::ParseKextSummaries (const Address &kext_summary_addr, uint32_t count) 1210 { 1211 KextImageInfo::collection kext_summaries; 1212 Log *log(GetLogIfAnyCategoriesSet (LIBLLDB_LOG_DYNAMIC_LOADER)); 1213 if (log) 1214 log->Printf ("Kexts-changed breakpoint hit, there are %d kexts currently.\n", count); 1215 1216 Mutex::Locker locker(m_mutex); 1217 1218 if (!ReadKextSummaries (kext_summary_addr, count, kext_summaries)) 1219 return false; 1220 1221 // read the plugin.dynamic-loader.darwin-kernel.load-kexts setting -- if the user requested no 1222 // kext loading, don't print any messages about kexts & don't try to read them. 1223 const bool load_kexts = GetGlobalProperties()->GetLoadKexts(); 1224 1225 // By default, all kexts we've loaded in the past are marked as "remove" and all of the kexts 1226 // we just found out about from ReadKextSummaries are marked as "add". 1227 std::vector<bool> to_be_removed(m_known_kexts.size(), true); 1228 std::vector<bool> to_be_added(count, true); 1229 1230 int number_of_new_kexts_being_added = 0; 1231 int number_of_old_kexts_being_removed = m_known_kexts.size(); 1232 1233 const uint32_t new_kexts_size = kext_summaries.size(); 1234 const uint32_t old_kexts_size = m_known_kexts.size(); 1235 1236 // The m_known_kexts vector may have entries that have been Cleared, 1237 // or are a kernel. 1238 for (uint32_t old_kext = 0; old_kext < old_kexts_size; old_kext++) 1239 { 1240 bool ignore = false; 1241 KextImageInfo &image_info = m_known_kexts[old_kext]; 1242 if (image_info.IsKernel()) 1243 { 1244 ignore = true; 1245 } 1246 else if (image_info.GetLoadAddress() == LLDB_INVALID_ADDRESS && !image_info.GetModule()) 1247 { 1248 ignore = true; 1249 } 1250 1251 if (ignore) 1252 { 1253 number_of_old_kexts_being_removed--; 1254 to_be_removed[old_kext] = false; 1255 } 1256 } 1257 1258 // Scan over the list of kexts we just read from the kernel, note those that 1259 // need to be added and those already loaded. 1260 for (uint32_t new_kext = 0; new_kext < new_kexts_size; new_kext++) 1261 { 1262 bool add_this_one = true; 1263 for (uint32_t old_kext = 0; old_kext < old_kexts_size; old_kext++) 1264 { 1265 if (m_known_kexts[old_kext] == kext_summaries[new_kext]) 1266 { 1267 // We already have this kext, don't re-load it. 1268 to_be_added[new_kext] = false; 1269 // This kext is still present, do not remove it. 1270 to_be_removed[old_kext] = false; 1271 1272 number_of_old_kexts_being_removed--; 1273 add_this_one = false; 1274 break; 1275 } 1276 } 1277 if (add_this_one) 1278 { 1279 number_of_new_kexts_being_added++; 1280 } 1281 } 1282 1283 if (number_of_new_kexts_being_added == 0 && number_of_old_kexts_being_removed == 0) 1284 return true; 1285 1286 Stream *s = m_process->GetTarget().GetDebugger().GetOutputFile().get(); 1287 if (s && load_kexts) 1288 { 1289 if (number_of_new_kexts_being_added > 0 && number_of_old_kexts_being_removed > 0) 1290 { 1291 s->Printf ("Loading %d kext modules and unloading %d kext modules ", number_of_new_kexts_being_added, number_of_old_kexts_being_removed); 1292 } 1293 else if (number_of_new_kexts_being_added > 0) 1294 { 1295 s->Printf ("Loading %d kext modules ", number_of_new_kexts_being_added); 1296 } 1297 else if (number_of_old_kexts_being_removed > 0) 1298 { 1299 s->Printf ("Unloading %d kext modules ", number_of_old_kexts_being_removed); 1300 } 1301 } 1302 1303 if (log) 1304 { 1305 if (load_kexts) 1306 { 1307 log->Printf ("DynamicLoaderDarwinKernel::ParseKextSummaries: %d kexts added, %d kexts removed", number_of_new_kexts_being_added, number_of_old_kexts_being_removed); 1308 } 1309 else 1310 { 1311 log->Printf ("DynamicLoaderDarwinKernel::ParseKextSummaries kext loading is disabled, else would have %d kexts added, %d kexts removed", number_of_new_kexts_being_added, number_of_old_kexts_being_removed); 1312 } 1313 } 1314 1315 1316 if (number_of_new_kexts_being_added > 0) 1317 { 1318 ModuleList loaded_module_list; 1319 1320 const uint32_t num_of_new_kexts = kext_summaries.size(); 1321 for (uint32_t new_kext = 0; new_kext < num_of_new_kexts; new_kext++) 1322 { 1323 if (to_be_added[new_kext] == true) 1324 { 1325 KextImageInfo &image_info = kext_summaries[new_kext]; 1326 if (load_kexts) 1327 { 1328 if (!image_info.LoadImageUsingMemoryModule (m_process)) 1329 { 1330 image_info.LoadImageAtFileAddress (m_process); 1331 } 1332 } 1333 1334 m_known_kexts.push_back(image_info); 1335 1336 if (image_info.GetModule() && m_process->GetStopID() == image_info.GetProcessStopId()) 1337 loaded_module_list.AppendIfNeeded (image_info.GetModule()); 1338 1339 if (s && load_kexts) 1340 s->Printf ("."); 1341 1342 if (log) 1343 kext_summaries[new_kext].PutToLog (log); 1344 } 1345 } 1346 m_process->GetTarget().ModulesDidLoad (loaded_module_list); 1347 } 1348 1349 if (number_of_old_kexts_being_removed > 0) 1350 { 1351 ModuleList loaded_module_list; 1352 const uint32_t num_of_old_kexts = m_known_kexts.size(); 1353 for (uint32_t old_kext = 0; old_kext < num_of_old_kexts; old_kext++) 1354 { 1355 ModuleList unloaded_module_list; 1356 if (to_be_removed[old_kext]) 1357 { 1358 KextImageInfo &image_info = m_known_kexts[old_kext]; 1359 // You can't unload the kernel. 1360 if (!image_info.IsKernel()) 1361 { 1362 if (image_info.GetModule()) 1363 { 1364 unloaded_module_list.AppendIfNeeded (image_info.GetModule()); 1365 } 1366 if (s) 1367 s->Printf ("."); 1368 image_info.Clear(); 1369 // should pull it out of the KextImageInfos vector but that would mutate the list and invalidate 1370 // the to_be_removed bool vector; leaving it in place once Cleared() is relatively harmless. 1371 } 1372 } 1373 m_process->GetTarget().ModulesDidUnload (unloaded_module_list, false); 1374 } 1375 } 1376 1377 if (s && load_kexts) 1378 { 1379 s->Printf (" done.\n"); 1380 s->Flush (); 1381 } 1382 1383 return true; 1384 } 1385 1386 uint32_t 1387 DynamicLoaderDarwinKernel::ReadKextSummaries (const Address &kext_summary_addr, 1388 uint32_t image_infos_count, 1389 KextImageInfo::collection &image_infos) 1390 { 1391 const ByteOrder endian = m_kernel.GetByteOrder(); 1392 const uint32_t addr_size = m_kernel.GetAddressByteSize(); 1393 1394 image_infos.resize(image_infos_count); 1395 const size_t count = image_infos.size() * m_kext_summary_header.entry_size; 1396 DataBufferHeap data(count, 0); 1397 Error error; 1398 1399 const bool prefer_file_cache = false; 1400 const size_t bytes_read = m_process->GetTarget().ReadMemory (kext_summary_addr, 1401 prefer_file_cache, 1402 data.GetBytes(), 1403 data.GetByteSize(), 1404 error); 1405 if (bytes_read == count) 1406 { 1407 1408 DataExtractor extractor (data.GetBytes(), data.GetByteSize(), endian, addr_size); 1409 uint32_t i=0; 1410 for (uint32_t kext_summary_offset = 0; 1411 i < image_infos.size() && extractor.ValidOffsetForDataOfSize(kext_summary_offset, m_kext_summary_header.entry_size); 1412 ++i, kext_summary_offset += m_kext_summary_header.entry_size) 1413 { 1414 lldb::offset_t offset = kext_summary_offset; 1415 const void *name_data = extractor.GetData(&offset, KERNEL_MODULE_MAX_NAME); 1416 if (name_data == NULL) 1417 break; 1418 image_infos[i].SetName ((const char *) name_data); 1419 UUID uuid (extractor.GetData (&offset, 16), 16); 1420 image_infos[i].SetUUID (uuid); 1421 image_infos[i].SetLoadAddress (extractor.GetU64(&offset)); 1422 image_infos[i].SetSize (extractor.GetU64(&offset)); 1423 } 1424 if (i < image_infos.size()) 1425 image_infos.resize(i); 1426 } 1427 else 1428 { 1429 image_infos.clear(); 1430 } 1431 return image_infos.size(); 1432 } 1433 1434 bool 1435 DynamicLoaderDarwinKernel::ReadAllKextSummaries () 1436 { 1437 Mutex::Locker locker(m_mutex); 1438 1439 if (ReadKextSummaryHeader ()) 1440 { 1441 if (m_kext_summary_header.entry_count > 0 && m_kext_summary_header_addr.IsValid()) 1442 { 1443 Address summary_addr (m_kext_summary_header_addr); 1444 summary_addr.Slide(m_kext_summary_header.GetSize()); 1445 if (!ParseKextSummaries (summary_addr, m_kext_summary_header.entry_count)) 1446 { 1447 m_known_kexts.clear(); 1448 } 1449 return true; 1450 } 1451 } 1452 return false; 1453 } 1454 1455 //---------------------------------------------------------------------- 1456 // Dump an image info structure to the file handle provided. 1457 //---------------------------------------------------------------------- 1458 void 1459 DynamicLoaderDarwinKernel::KextImageInfo::PutToLog (Log *log) const 1460 { 1461 if (log == NULL) 1462 return; 1463 const uint8_t *u = (uint8_t *) m_uuid.GetBytes(); 1464 1465 if (m_load_address == LLDB_INVALID_ADDRESS) 1466 { 1467 if (u) 1468 { 1469 log->Printf("\tuuid=%2.2X%2.2X%2.2X%2.2X-%2.2X%2.2X-%2.2X%2.2X-%2.2X%2.2X-%2.2X%2.2X%2.2X%2.2X%2.2X%2.2X name=\"%s\" (UNLOADED)", 1470 u[ 0], u[ 1], u[ 2], u[ 3], 1471 u[ 4], u[ 5], u[ 6], u[ 7], 1472 u[ 8], u[ 9], u[10], u[11], 1473 u[12], u[13], u[14], u[15], 1474 m_name.c_str()); 1475 } 1476 else 1477 log->Printf("\tname=\"%s\" (UNLOADED)", m_name.c_str()); 1478 } 1479 else 1480 { 1481 if (u) 1482 { 1483 log->Printf("\taddr=0x%16.16" PRIx64 " size=0x%16.16" PRIx64 " uuid=%2.2X%2.2X%2.2X%2.2X-%2.2X%2.2X-%2.2X%2.2X-%2.2X%2.2X-%2.2X%2.2X%2.2X%2.2X%2.2X%2.2X name=\"%s\"", 1484 m_load_address, m_size, 1485 u[ 0], u[ 1], u[ 2], u[ 3], u[ 4], u[ 5], u[ 6], u[ 7], 1486 u[ 8], u[ 9], u[10], u[11], u[12], u[13], u[14], u[15], 1487 m_name.c_str()); 1488 } 1489 else 1490 { 1491 log->Printf("\t[0x%16.16" PRIx64 " - 0x%16.16" PRIx64 ") name=\"%s\"", 1492 m_load_address, m_load_address+m_size, m_name.c_str()); 1493 } 1494 } 1495 } 1496 1497 //---------------------------------------------------------------------- 1498 // Dump the _dyld_all_image_infos members and all current image infos 1499 // that we have parsed to the file handle provided. 1500 //---------------------------------------------------------------------- 1501 void 1502 DynamicLoaderDarwinKernel::PutToLog(Log *log) const 1503 { 1504 if (log == NULL) 1505 return; 1506 1507 Mutex::Locker locker(m_mutex); 1508 log->Printf("gLoadedKextSummaries = 0x%16.16" PRIx64 " { version=%u, entry_size=%u, entry_count=%u }", 1509 m_kext_summary_header_addr.GetFileAddress(), 1510 m_kext_summary_header.version, 1511 m_kext_summary_header.entry_size, 1512 m_kext_summary_header.entry_count); 1513 1514 size_t i; 1515 const size_t count = m_known_kexts.size(); 1516 if (count > 0) 1517 { 1518 log->PutCString("Loaded:"); 1519 for (i = 0; i<count; i++) 1520 m_known_kexts[i].PutToLog(log); 1521 } 1522 } 1523 1524 void 1525 DynamicLoaderDarwinKernel::PrivateInitialize(Process *process) 1526 { 1527 DEBUG_PRINTF("DynamicLoaderDarwinKernel::%s() process state = %s\n", __FUNCTION__, StateAsCString(m_process->GetState())); 1528 Clear(true); 1529 m_process = process; 1530 } 1531 1532 void 1533 DynamicLoaderDarwinKernel::SetNotificationBreakpointIfNeeded () 1534 { 1535 if (m_break_id == LLDB_INVALID_BREAK_ID && m_kernel.GetModule()) 1536 { 1537 DEBUG_PRINTF("DynamicLoaderDarwinKernel::%s() process state = %s\n", __FUNCTION__, StateAsCString(m_process->GetState())); 1538 1539 1540 const bool internal_bp = true; 1541 const bool hardware = false; 1542 const LazyBool skip_prologue = eLazyBoolNo; 1543 FileSpecList module_spec_list; 1544 module_spec_list.Append (m_kernel.GetModule()->GetFileSpec()); 1545 Breakpoint *bp = m_process->GetTarget().CreateBreakpoint (&module_spec_list, 1546 NULL, 1547 "OSKextLoadedKextSummariesUpdated", 1548 eFunctionNameTypeFull, 1549 skip_prologue, 1550 internal_bp, 1551 hardware).get(); 1552 1553 bp->SetCallback (DynamicLoaderDarwinKernel::BreakpointHitCallback, this, true); 1554 m_break_id = bp->GetID(); 1555 } 1556 } 1557 1558 //---------------------------------------------------------------------- 1559 // Member function that gets called when the process state changes. 1560 //---------------------------------------------------------------------- 1561 void 1562 DynamicLoaderDarwinKernel::PrivateProcessStateChanged (Process *process, StateType state) 1563 { 1564 DEBUG_PRINTF("DynamicLoaderDarwinKernel::%s(%s)\n", __FUNCTION__, StateAsCString(state)); 1565 switch (state) 1566 { 1567 case eStateConnected: 1568 case eStateAttaching: 1569 case eStateLaunching: 1570 case eStateInvalid: 1571 case eStateUnloaded: 1572 case eStateExited: 1573 case eStateDetached: 1574 Clear(false); 1575 break; 1576 1577 case eStateStopped: 1578 UpdateIfNeeded(); 1579 break; 1580 1581 case eStateRunning: 1582 case eStateStepping: 1583 case eStateCrashed: 1584 case eStateSuspended: 1585 break; 1586 } 1587 } 1588 1589 ThreadPlanSP 1590 DynamicLoaderDarwinKernel::GetStepThroughTrampolinePlan (Thread &thread, bool stop_others) 1591 { 1592 ThreadPlanSP thread_plan_sp; 1593 Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP)); 1594 if (log) 1595 log->Printf ("Could not find symbol for step through."); 1596 return thread_plan_sp; 1597 } 1598 1599 Error 1600 DynamicLoaderDarwinKernel::CanLoadImage () 1601 { 1602 Error error; 1603 error.SetErrorString("always unsafe to load or unload shared libraries in the darwin kernel"); 1604 return error; 1605 } 1606 1607 void 1608 DynamicLoaderDarwinKernel::Initialize() 1609 { 1610 PluginManager::RegisterPlugin (GetPluginNameStatic(), 1611 GetPluginDescriptionStatic(), 1612 CreateInstance, 1613 DebuggerInitialize); 1614 } 1615 1616 void 1617 DynamicLoaderDarwinKernel::Terminate() 1618 { 1619 PluginManager::UnregisterPlugin (CreateInstance); 1620 } 1621 1622 void 1623 DynamicLoaderDarwinKernel::DebuggerInitialize (lldb_private::Debugger &debugger) 1624 { 1625 if (!PluginManager::GetSettingForDynamicLoaderPlugin (debugger, DynamicLoaderDarwinKernelProperties::GetSettingName())) 1626 { 1627 const bool is_global_setting = true; 1628 PluginManager::CreateSettingForDynamicLoaderPlugin (debugger, 1629 GetGlobalProperties()->GetValueProperties(), 1630 ConstString ("Properties for the DynamicLoaderDarwinKernel plug-in."), 1631 is_global_setting); 1632 } 1633 } 1634 1635 lldb_private::ConstString 1636 DynamicLoaderDarwinKernel::GetPluginNameStatic() 1637 { 1638 static ConstString g_name("darwin-kernel"); 1639 return g_name; 1640 } 1641 1642 const char * 1643 DynamicLoaderDarwinKernel::GetPluginDescriptionStatic() 1644 { 1645 return "Dynamic loader plug-in that watches for shared library loads/unloads in the MacOSX kernel."; 1646 } 1647 1648 1649 //------------------------------------------------------------------ 1650 // PluginInterface protocol 1651 //------------------------------------------------------------------ 1652 lldb_private::ConstString 1653 DynamicLoaderDarwinKernel::GetPluginName() 1654 { 1655 return GetPluginNameStatic(); 1656 } 1657 1658 uint32_t 1659 DynamicLoaderDarwinKernel::GetPluginVersion() 1660 { 1661 return 1; 1662 } 1663 1664 lldb::ByteOrder 1665 DynamicLoaderDarwinKernel::GetByteOrderFromMagic (uint32_t magic) 1666 { 1667 switch (magic) 1668 { 1669 case llvm::MachO::MH_MAGIC: 1670 case llvm::MachO::MH_MAGIC_64: 1671 return lldb::endian::InlHostByteOrder(); 1672 1673 case llvm::MachO::MH_CIGAM: 1674 case llvm::MachO::MH_CIGAM_64: 1675 if (lldb::endian::InlHostByteOrder() == lldb::eByteOrderBig) 1676 return lldb::eByteOrderLittle; 1677 else 1678 return lldb::eByteOrderBig; 1679 1680 default: 1681 break; 1682 } 1683 return lldb::eByteOrderInvalid; 1684 } 1685 1686