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