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