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