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 if (!m_module_sp && !IsKernel() && m_uuid.IsValid() && !m_name.empty()) { 877 Stream *s = target.GetDebugger().GetOutputFile().get(); 878 if (s) { 879 s->Printf("warning: Can't find binary/dSYM for %s (%s)\n", m_name.c_str(), 880 m_uuid.GetAsString().c_str()); 881 } 882 } 883 884 static ConstString g_section_name_LINKEDIT("__LINKEDIT"); 885 886 if (m_memory_module_sp && m_module_sp) { 887 if (m_module_sp->GetUUID() == m_memory_module_sp->GetUUID()) { 888 ObjectFile *ondisk_object_file = m_module_sp->GetObjectFile(); 889 ObjectFile *memory_object_file = m_memory_module_sp->GetObjectFile(); 890 891 if (memory_object_file && ondisk_object_file) { 892 // The memory_module for kexts may have an invalid __LINKEDIT seg; skip 893 // it. 894 const bool ignore_linkedit = !IsKernel(); 895 896 SectionList *ondisk_section_list = ondisk_object_file->GetSectionList(); 897 SectionList *memory_section_list = memory_object_file->GetSectionList(); 898 if (memory_section_list && ondisk_section_list) { 899 const uint32_t num_ondisk_sections = ondisk_section_list->GetSize(); 900 // There may be CTF sections in the memory image so we can't always 901 // just compare the number of sections (which are actually segments 902 // in mach-o parlance) 903 uint32_t sect_idx = 0; 904 905 // Use the memory_module's addresses for each section to set the file 906 // module's load address as appropriate. We don't want to use a 907 // single slide value for the entire kext - different segments may be 908 // slid different amounts by the kext loader. 909 910 uint32_t num_sections_loaded = 0; 911 for (sect_idx = 0; sect_idx < num_ondisk_sections; ++sect_idx) { 912 SectionSP ondisk_section_sp( 913 ondisk_section_list->GetSectionAtIndex(sect_idx)); 914 if (ondisk_section_sp) { 915 // Don't ever load __LINKEDIT as it may or may not be actually 916 // mapped into memory and there is no current way to tell. 917 // I filed rdar://problem/12851706 to track being able to tell 918 // if the __LINKEDIT is actually mapped, but until then, we need 919 // to not load the __LINKEDIT 920 if (ignore_linkedit && 921 ondisk_section_sp->GetName() == g_section_name_LINKEDIT) 922 continue; 923 924 const Section *memory_section = 925 memory_section_list 926 ->FindSectionByName(ondisk_section_sp->GetName()) 927 .get(); 928 if (memory_section) { 929 target.SetSectionLoadAddress(ondisk_section_sp, 930 memory_section->GetFileAddress()); 931 ++num_sections_loaded; 932 } 933 } 934 } 935 if (num_sections_loaded > 0) 936 m_load_process_stop_id = process->GetStopID(); 937 else 938 m_module_sp.reset(); // No sections were loaded 939 } else 940 m_module_sp.reset(); // One or both section lists 941 } else 942 m_module_sp.reset(); // One or both object files missing 943 } else 944 m_module_sp.reset(); // UUID mismatch 945 } 946 947 bool is_loaded = IsLoaded(); 948 949 if (is_loaded && m_module_sp && IsKernel()) { 950 Stream *s = target.GetDebugger().GetOutputFile().get(); 951 if (s) { 952 ObjectFile *kernel_object_file = m_module_sp->GetObjectFile(); 953 if (kernel_object_file) { 954 addr_t file_address = 955 kernel_object_file->GetBaseAddress().GetFileAddress(); 956 if (m_load_address != LLDB_INVALID_ADDRESS && 957 file_address != LLDB_INVALID_ADDRESS) { 958 s->Printf("Kernel slid 0x%" PRIx64 " in memory.\n", 959 m_load_address - file_address); 960 } 961 } 962 { 963 s->Printf("Loaded kernel file %s\n", 964 m_module_sp->GetFileSpec().GetPath().c_str()); 965 } 966 s->Flush(); 967 } 968 } 969 return is_loaded; 970 } 971 972 uint32_t DynamicLoaderDarwinKernel::KextImageInfo::GetAddressByteSize() { 973 if (m_memory_module_sp) 974 return m_memory_module_sp->GetArchitecture().GetAddressByteSize(); 975 if (m_module_sp) 976 return m_module_sp->GetArchitecture().GetAddressByteSize(); 977 return 0; 978 } 979 980 lldb::ByteOrder DynamicLoaderDarwinKernel::KextImageInfo::GetByteOrder() { 981 if (m_memory_module_sp) 982 return m_memory_module_sp->GetArchitecture().GetByteOrder(); 983 if (m_module_sp) 984 return m_module_sp->GetArchitecture().GetByteOrder(); 985 return endian::InlHostByteOrder(); 986 } 987 988 lldb_private::ArchSpec 989 DynamicLoaderDarwinKernel::KextImageInfo::GetArchitecture() const { 990 if (m_memory_module_sp) 991 return m_memory_module_sp->GetArchitecture(); 992 if (m_module_sp) 993 return m_module_sp->GetArchitecture(); 994 return lldb_private::ArchSpec(); 995 } 996 997 //---------------------------------------------------------------------- 998 // Load the kernel module and initialize the "m_kernel" member. Return true 999 // _only_ if the kernel is loaded the first time through (subsequent calls to 1000 // this function should return false after the kernel has been already loaded). 1001 //---------------------------------------------------------------------- 1002 void DynamicLoaderDarwinKernel::LoadKernelModuleIfNeeded() { 1003 if (!m_kext_summary_header_ptr_addr.IsValid()) { 1004 m_kernel.Clear(); 1005 m_kernel.SetModule(m_process->GetTarget().GetExecutableModule()); 1006 m_kernel.SetIsKernel(true); 1007 1008 ConstString kernel_name("mach_kernel"); 1009 if (m_kernel.GetModule().get() && m_kernel.GetModule()->GetObjectFile() && 1010 !m_kernel.GetModule() 1011 ->GetObjectFile() 1012 ->GetFileSpec() 1013 .GetFilename() 1014 .IsEmpty()) { 1015 kernel_name = 1016 m_kernel.GetModule()->GetObjectFile()->GetFileSpec().GetFilename(); 1017 } 1018 m_kernel.SetName(kernel_name.AsCString()); 1019 1020 if (m_kernel.GetLoadAddress() == LLDB_INVALID_ADDRESS) { 1021 m_kernel.SetLoadAddress(m_kernel_load_address); 1022 if (m_kernel.GetLoadAddress() == LLDB_INVALID_ADDRESS && 1023 m_kernel.GetModule()) { 1024 // We didn't get a hint from the process, so we will try the kernel at 1025 // the address that it exists at in the file if we have one 1026 ObjectFile *kernel_object_file = m_kernel.GetModule()->GetObjectFile(); 1027 if (kernel_object_file) { 1028 addr_t load_address = 1029 kernel_object_file->GetBaseAddress().GetLoadAddress( 1030 &m_process->GetTarget()); 1031 addr_t file_address = 1032 kernel_object_file->GetBaseAddress().GetFileAddress(); 1033 if (load_address != LLDB_INVALID_ADDRESS && load_address != 0) { 1034 m_kernel.SetLoadAddress(load_address); 1035 if (load_address != file_address) { 1036 // Don't accidentally relocate the kernel to the File address -- 1037 // the Load address has already been set to its actual in-memory 1038 // address. Mark it as IsLoaded. 1039 m_kernel.SetProcessStopId(m_process->GetStopID()); 1040 } 1041 } else { 1042 m_kernel.SetLoadAddress(file_address); 1043 } 1044 } 1045 } 1046 } 1047 1048 if (m_kernel.GetLoadAddress() != LLDB_INVALID_ADDRESS) { 1049 if (!m_kernel.LoadImageUsingMemoryModule(m_process)) { 1050 m_kernel.LoadImageAtFileAddress(m_process); 1051 } 1052 } 1053 1054 // The operating system plugin gets loaded and initialized in 1055 // LoadImageUsingMemoryModule when we discover the kernel dSYM. For a core 1056 // file in particular, that's the wrong place to do this, since we haven't 1057 // fixed up the section addresses yet. So let's redo it here. 1058 LoadOperatingSystemPlugin(false); 1059 1060 if (m_kernel.IsLoaded() && m_kernel.GetModule()) { 1061 static ConstString kext_summary_symbol("gLoadedKextSummaries"); 1062 const Symbol *symbol = 1063 m_kernel.GetModule()->FindFirstSymbolWithNameAndType( 1064 kext_summary_symbol, eSymbolTypeData); 1065 if (symbol) { 1066 m_kext_summary_header_ptr_addr = symbol->GetAddress(); 1067 // Update all image infos 1068 ReadAllKextSummaries(); 1069 } 1070 } else { 1071 m_kernel.Clear(); 1072 } 1073 } 1074 } 1075 1076 //---------------------------------------------------------------------- 1077 // Static callback function that gets called when our DYLD notification 1078 // breakpoint gets hit. We update all of our image infos and then let our super 1079 // class DynamicLoader class decide if we should stop or not (based on global 1080 // preference). 1081 //---------------------------------------------------------------------- 1082 bool DynamicLoaderDarwinKernel::BreakpointHitCallback( 1083 void *baton, StoppointCallbackContext *context, user_id_t break_id, 1084 user_id_t break_loc_id) { 1085 return static_cast<DynamicLoaderDarwinKernel *>(baton)->BreakpointHit( 1086 context, break_id, break_loc_id); 1087 } 1088 1089 bool DynamicLoaderDarwinKernel::BreakpointHit(StoppointCallbackContext *context, 1090 user_id_t break_id, 1091 user_id_t break_loc_id) { 1092 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER)); 1093 if (log) 1094 log->Printf("DynamicLoaderDarwinKernel::BreakpointHit (...)\n"); 1095 1096 ReadAllKextSummaries(); 1097 1098 if (log) 1099 PutToLog(log); 1100 1101 return GetStopWhenImagesChange(); 1102 } 1103 1104 bool DynamicLoaderDarwinKernel::ReadKextSummaryHeader() { 1105 std::lock_guard<std::recursive_mutex> guard(m_mutex); 1106 1107 // the all image infos is already valid for this process stop ID 1108 1109 if (m_kext_summary_header_ptr_addr.IsValid()) { 1110 const uint32_t addr_size = m_kernel.GetAddressByteSize(); 1111 const ByteOrder byte_order = m_kernel.GetByteOrder(); 1112 Status error; 1113 // Read enough bytes for a "OSKextLoadedKextSummaryHeader" structure which 1114 // is currently 4 uint32_t and a pointer. 1115 uint8_t buf[24]; 1116 DataExtractor data(buf, sizeof(buf), byte_order, addr_size); 1117 const size_t count = 4 * sizeof(uint32_t) + addr_size; 1118 const bool prefer_file_cache = false; 1119 if (m_process->GetTarget().ReadPointerFromMemory( 1120 m_kext_summary_header_ptr_addr, prefer_file_cache, error, 1121 m_kext_summary_header_addr)) { 1122 // We got a valid address for our kext summary header and make sure it 1123 // isn't NULL 1124 if (m_kext_summary_header_addr.IsValid() && 1125 m_kext_summary_header_addr.GetFileAddress() != 0) { 1126 const size_t bytes_read = m_process->GetTarget().ReadMemory( 1127 m_kext_summary_header_addr, prefer_file_cache, buf, count, error); 1128 if (bytes_read == count) { 1129 lldb::offset_t offset = 0; 1130 m_kext_summary_header.version = data.GetU32(&offset); 1131 if (m_kext_summary_header.version > 128) { 1132 Stream *s = 1133 m_process->GetTarget().GetDebugger().GetOutputFile().get(); 1134 s->Printf("WARNING: Unable to read kext summary header, got " 1135 "improbable version number %u\n", 1136 m_kext_summary_header.version); 1137 // If we get an improbably large version number, we're probably 1138 // getting bad memory. 1139 m_kext_summary_header_addr.Clear(); 1140 return false; 1141 } 1142 if (m_kext_summary_header.version >= 2) { 1143 m_kext_summary_header.entry_size = data.GetU32(&offset); 1144 if (m_kext_summary_header.entry_size > 4096) { 1145 // If we get an improbably large entry_size, we're probably 1146 // getting bad memory. 1147 Stream *s = 1148 m_process->GetTarget().GetDebugger().GetOutputFile().get(); 1149 s->Printf("WARNING: Unable to read kext summary header, got " 1150 "improbable entry_size %u\n", 1151 m_kext_summary_header.entry_size); 1152 m_kext_summary_header_addr.Clear(); 1153 return false; 1154 } 1155 } else { 1156 // Versions less than 2 didn't have an entry size, it was hard 1157 // coded 1158 m_kext_summary_header.entry_size = 1159 KERNEL_MODULE_ENTRY_SIZE_VERSION_1; 1160 } 1161 m_kext_summary_header.entry_count = data.GetU32(&offset); 1162 if (m_kext_summary_header.entry_count > 10000) { 1163 // If we get an improbably large number of kexts, we're probably 1164 // getting bad memory. 1165 Stream *s = 1166 m_process->GetTarget().GetDebugger().GetOutputFile().get(); 1167 s->Printf("WARNING: Unable to read kext summary header, got " 1168 "improbable number of kexts %u\n", 1169 m_kext_summary_header.entry_count); 1170 m_kext_summary_header_addr.Clear(); 1171 return false; 1172 } 1173 return true; 1174 } 1175 } 1176 } 1177 } 1178 m_kext_summary_header_addr.Clear(); 1179 return false; 1180 } 1181 1182 // We've either (a) just attached to a new kernel, or (b) the kexts-changed 1183 // breakpoint was hit and we need to figure out what kexts have been added or 1184 // removed. Read the kext summaries from the inferior kernel memory, compare 1185 // them against the m_known_kexts vector and update the m_known_kexts vector as 1186 // needed to keep in sync with the inferior. 1187 1188 bool DynamicLoaderDarwinKernel::ParseKextSummaries( 1189 const Address &kext_summary_addr, uint32_t count) { 1190 KextImageInfo::collection kext_summaries; 1191 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER)); 1192 if (log) 1193 log->Printf("Kexts-changed breakpoint hit, there are %d kexts currently.\n", 1194 count); 1195 1196 std::lock_guard<std::recursive_mutex> guard(m_mutex); 1197 1198 if (!ReadKextSummaries(kext_summary_addr, count, kext_summaries)) 1199 return false; 1200 1201 // read the plugin.dynamic-loader.darwin-kernel.load-kexts setting -- if the 1202 // user requested no kext loading, don't print any messages about kexts & 1203 // don't try to read them. 1204 const bool load_kexts = GetGlobalProperties()->GetLoadKexts(); 1205 1206 // By default, all kexts we've loaded in the past are marked as "remove" and 1207 // all of the kexts we just found out about from ReadKextSummaries are marked 1208 // as "add". 1209 std::vector<bool> to_be_removed(m_known_kexts.size(), true); 1210 std::vector<bool> to_be_added(count, true); 1211 1212 int number_of_new_kexts_being_added = 0; 1213 int number_of_old_kexts_being_removed = m_known_kexts.size(); 1214 1215 const uint32_t new_kexts_size = kext_summaries.size(); 1216 const uint32_t old_kexts_size = m_known_kexts.size(); 1217 1218 // The m_known_kexts vector may have entries that have been Cleared, or are a 1219 // kernel. 1220 for (uint32_t old_kext = 0; old_kext < old_kexts_size; old_kext++) { 1221 bool ignore = false; 1222 KextImageInfo &image_info = m_known_kexts[old_kext]; 1223 if (image_info.IsKernel()) { 1224 ignore = true; 1225 } else if (image_info.GetLoadAddress() == LLDB_INVALID_ADDRESS && 1226 !image_info.GetModule()) { 1227 ignore = true; 1228 } 1229 1230 if (ignore) { 1231 number_of_old_kexts_being_removed--; 1232 to_be_removed[old_kext] = false; 1233 } 1234 } 1235 1236 // Scan over the list of kexts we just read from the kernel, note those that 1237 // need to be added and those already loaded. 1238 for (uint32_t new_kext = 0; new_kext < new_kexts_size; new_kext++) { 1239 bool add_this_one = true; 1240 for (uint32_t old_kext = 0; old_kext < old_kexts_size; old_kext++) { 1241 if (m_known_kexts[old_kext] == kext_summaries[new_kext]) { 1242 // We already have this kext, don't re-load it. 1243 to_be_added[new_kext] = false; 1244 // This kext is still present, do not remove it. 1245 to_be_removed[old_kext] = false; 1246 1247 number_of_old_kexts_being_removed--; 1248 add_this_one = false; 1249 break; 1250 } 1251 } 1252 // If this "kext" entry is actually an alias for the kernel -- the kext was 1253 // compiled into the kernel or something -- then we don't want to load the 1254 // kernel's text section at a different address. Ignore this kext entry. 1255 if (kext_summaries[new_kext].GetUUID().IsValid() 1256 && m_kernel.GetUUID().IsValid() 1257 && kext_summaries[new_kext].GetUUID() == m_kernel.GetUUID()) { 1258 to_be_added[new_kext] = false; 1259 break; 1260 } 1261 if (add_this_one) { 1262 number_of_new_kexts_being_added++; 1263 } 1264 } 1265 1266 if (number_of_new_kexts_being_added == 0 && 1267 number_of_old_kexts_being_removed == 0) 1268 return true; 1269 1270 Stream *s = m_process->GetTarget().GetDebugger().GetOutputFile().get(); 1271 if (s && load_kexts) { 1272 if (number_of_new_kexts_being_added > 0 && 1273 number_of_old_kexts_being_removed > 0) { 1274 s->Printf("Loading %d kext modules and unloading %d kext modules ", 1275 number_of_new_kexts_being_added, 1276 number_of_old_kexts_being_removed); 1277 } else if (number_of_new_kexts_being_added > 0) { 1278 s->Printf("Loading %d kext modules ", number_of_new_kexts_being_added); 1279 } else if (number_of_old_kexts_being_removed > 0) { 1280 s->Printf("Unloading %d kext modules ", 1281 number_of_old_kexts_being_removed); 1282 } 1283 } 1284 1285 if (log) { 1286 if (load_kexts) { 1287 log->Printf("DynamicLoaderDarwinKernel::ParseKextSummaries: %d kexts " 1288 "added, %d kexts removed", 1289 number_of_new_kexts_being_added, 1290 number_of_old_kexts_being_removed); 1291 } else { 1292 log->Printf( 1293 "DynamicLoaderDarwinKernel::ParseKextSummaries kext loading is " 1294 "disabled, else would have %d kexts added, %d kexts removed", 1295 number_of_new_kexts_being_added, number_of_old_kexts_being_removed); 1296 } 1297 } 1298 1299 if (number_of_new_kexts_being_added > 0) { 1300 ModuleList loaded_module_list; 1301 1302 const uint32_t num_of_new_kexts = kext_summaries.size(); 1303 for (uint32_t new_kext = 0; new_kext < num_of_new_kexts; new_kext++) { 1304 if (to_be_added[new_kext]) { 1305 KextImageInfo &image_info = kext_summaries[new_kext]; 1306 if (load_kexts) { 1307 if (!image_info.LoadImageUsingMemoryModule(m_process)) { 1308 image_info.LoadImageAtFileAddress(m_process); 1309 } 1310 } 1311 1312 m_known_kexts.push_back(image_info); 1313 1314 if (image_info.GetModule() && 1315 m_process->GetStopID() == image_info.GetProcessStopId()) 1316 loaded_module_list.AppendIfNeeded(image_info.GetModule()); 1317 1318 if (s && load_kexts) 1319 s->Printf("."); 1320 1321 if (log) 1322 kext_summaries[new_kext].PutToLog(log); 1323 } 1324 } 1325 m_process->GetTarget().ModulesDidLoad(loaded_module_list); 1326 } 1327 1328 if (number_of_old_kexts_being_removed > 0) { 1329 ModuleList loaded_module_list; 1330 const uint32_t num_of_old_kexts = m_known_kexts.size(); 1331 for (uint32_t old_kext = 0; old_kext < num_of_old_kexts; old_kext++) { 1332 ModuleList unloaded_module_list; 1333 if (to_be_removed[old_kext]) { 1334 KextImageInfo &image_info = m_known_kexts[old_kext]; 1335 // You can't unload the kernel. 1336 if (!image_info.IsKernel()) { 1337 if (image_info.GetModule()) { 1338 unloaded_module_list.AppendIfNeeded(image_info.GetModule()); 1339 } 1340 if (s) 1341 s->Printf("."); 1342 image_info.Clear(); 1343 // should pull it out of the KextImageInfos vector but that would 1344 // mutate the list and invalidate the to_be_removed bool vector; 1345 // leaving it in place once Cleared() is relatively harmless. 1346 } 1347 } 1348 m_process->GetTarget().ModulesDidUnload(unloaded_module_list, false); 1349 } 1350 } 1351 1352 if (s && load_kexts) { 1353 s->Printf(" done.\n"); 1354 s->Flush(); 1355 } 1356 1357 return true; 1358 } 1359 1360 uint32_t DynamicLoaderDarwinKernel::ReadKextSummaries( 1361 const Address &kext_summary_addr, uint32_t image_infos_count, 1362 KextImageInfo::collection &image_infos) { 1363 const ByteOrder endian = m_kernel.GetByteOrder(); 1364 const uint32_t addr_size = m_kernel.GetAddressByteSize(); 1365 1366 image_infos.resize(image_infos_count); 1367 const size_t count = image_infos.size() * m_kext_summary_header.entry_size; 1368 DataBufferHeap data(count, 0); 1369 Status error; 1370 1371 const bool prefer_file_cache = false; 1372 const size_t bytes_read = m_process->GetTarget().ReadMemory( 1373 kext_summary_addr, prefer_file_cache, data.GetBytes(), data.GetByteSize(), 1374 error); 1375 if (bytes_read == count) { 1376 1377 DataExtractor extractor(data.GetBytes(), data.GetByteSize(), endian, 1378 addr_size); 1379 uint32_t i = 0; 1380 for (uint32_t kext_summary_offset = 0; 1381 i < image_infos.size() && 1382 extractor.ValidOffsetForDataOfSize(kext_summary_offset, 1383 m_kext_summary_header.entry_size); 1384 ++i, kext_summary_offset += m_kext_summary_header.entry_size) { 1385 lldb::offset_t offset = kext_summary_offset; 1386 const void *name_data = 1387 extractor.GetData(&offset, KERNEL_MODULE_MAX_NAME); 1388 if (name_data == NULL) 1389 break; 1390 image_infos[i].SetName((const char *)name_data); 1391 UUID uuid = UUID::fromOptionalData(extractor.GetData(&offset, 16), 16); 1392 image_infos[i].SetUUID(uuid); 1393 image_infos[i].SetLoadAddress(extractor.GetU64(&offset)); 1394 image_infos[i].SetSize(extractor.GetU64(&offset)); 1395 } 1396 if (i < image_infos.size()) 1397 image_infos.resize(i); 1398 } else { 1399 image_infos.clear(); 1400 } 1401 return image_infos.size(); 1402 } 1403 1404 bool DynamicLoaderDarwinKernel::ReadAllKextSummaries() { 1405 std::lock_guard<std::recursive_mutex> guard(m_mutex); 1406 1407 if (ReadKextSummaryHeader()) { 1408 if (m_kext_summary_header.entry_count > 0 && 1409 m_kext_summary_header_addr.IsValid()) { 1410 Address summary_addr(m_kext_summary_header_addr); 1411 summary_addr.Slide(m_kext_summary_header.GetSize()); 1412 if (!ParseKextSummaries(summary_addr, 1413 m_kext_summary_header.entry_count)) { 1414 m_known_kexts.clear(); 1415 } 1416 return true; 1417 } 1418 } 1419 return false; 1420 } 1421 1422 //---------------------------------------------------------------------- 1423 // Dump an image info structure to the file handle provided. 1424 //---------------------------------------------------------------------- 1425 void DynamicLoaderDarwinKernel::KextImageInfo::PutToLog(Log *log) const { 1426 if (m_load_address == LLDB_INVALID_ADDRESS) { 1427 LLDB_LOG(log, "uuid={0} name=\"{1}\" (UNLOADED)", m_uuid.GetAsString(), 1428 m_name); 1429 } else { 1430 LLDB_LOG(log, "addr={0:x+16} size={1:x+16} uuid={2} name=\"{3}\"", 1431 m_load_address, m_size, m_uuid.GetAsString(), m_name); 1432 } 1433 } 1434 1435 //---------------------------------------------------------------------- 1436 // Dump the _dyld_all_image_infos members and all current image infos that we 1437 // have parsed to the file handle provided. 1438 //---------------------------------------------------------------------- 1439 void DynamicLoaderDarwinKernel::PutToLog(Log *log) const { 1440 if (log == NULL) 1441 return; 1442 1443 std::lock_guard<std::recursive_mutex> guard(m_mutex); 1444 log->Printf("gLoadedKextSummaries = 0x%16.16" PRIx64 1445 " { version=%u, entry_size=%u, entry_count=%u }", 1446 m_kext_summary_header_addr.GetFileAddress(), 1447 m_kext_summary_header.version, m_kext_summary_header.entry_size, 1448 m_kext_summary_header.entry_count); 1449 1450 size_t i; 1451 const size_t count = m_known_kexts.size(); 1452 if (count > 0) { 1453 log->PutCString("Loaded:"); 1454 for (i = 0; i < count; i++) 1455 m_known_kexts[i].PutToLog(log); 1456 } 1457 } 1458 1459 void DynamicLoaderDarwinKernel::PrivateInitialize(Process *process) { 1460 DEBUG_PRINTF("DynamicLoaderDarwinKernel::%s() process state = %s\n", 1461 __FUNCTION__, StateAsCString(m_process->GetState())); 1462 Clear(true); 1463 m_process = process; 1464 } 1465 1466 void DynamicLoaderDarwinKernel::SetNotificationBreakpointIfNeeded() { 1467 if (m_break_id == LLDB_INVALID_BREAK_ID && m_kernel.GetModule()) { 1468 DEBUG_PRINTF("DynamicLoaderDarwinKernel::%s() process state = %s\n", 1469 __FUNCTION__, StateAsCString(m_process->GetState())); 1470 1471 const bool internal_bp = true; 1472 const bool hardware = false; 1473 const LazyBool skip_prologue = eLazyBoolNo; 1474 FileSpecList module_spec_list; 1475 module_spec_list.Append(m_kernel.GetModule()->GetFileSpec()); 1476 Breakpoint *bp = 1477 m_process->GetTarget() 1478 .CreateBreakpoint(&module_spec_list, NULL, 1479 "OSKextLoadedKextSummariesUpdated", 1480 eFunctionNameTypeFull, eLanguageTypeUnknown, 0, 1481 skip_prologue, internal_bp, hardware) 1482 .get(); 1483 1484 bp->SetCallback(DynamicLoaderDarwinKernel::BreakpointHitCallback, this, 1485 true); 1486 m_break_id = bp->GetID(); 1487 } 1488 } 1489 1490 //---------------------------------------------------------------------- 1491 // Member function that gets called when the process state changes. 1492 //---------------------------------------------------------------------- 1493 void DynamicLoaderDarwinKernel::PrivateProcessStateChanged(Process *process, 1494 StateType state) { 1495 DEBUG_PRINTF("DynamicLoaderDarwinKernel::%s(%s)\n", __FUNCTION__, 1496 StateAsCString(state)); 1497 switch (state) { 1498 case eStateConnected: 1499 case eStateAttaching: 1500 case eStateLaunching: 1501 case eStateInvalid: 1502 case eStateUnloaded: 1503 case eStateExited: 1504 case eStateDetached: 1505 Clear(false); 1506 break; 1507 1508 case eStateStopped: 1509 UpdateIfNeeded(); 1510 break; 1511 1512 case eStateRunning: 1513 case eStateStepping: 1514 case eStateCrashed: 1515 case eStateSuspended: 1516 break; 1517 } 1518 } 1519 1520 ThreadPlanSP 1521 DynamicLoaderDarwinKernel::GetStepThroughTrampolinePlan(Thread &thread, 1522 bool stop_others) { 1523 ThreadPlanSP thread_plan_sp; 1524 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP)); 1525 if (log) 1526 log->Printf("Could not find symbol for step through."); 1527 return thread_plan_sp; 1528 } 1529 1530 Status DynamicLoaderDarwinKernel::CanLoadImage() { 1531 Status error; 1532 error.SetErrorString( 1533 "always unsafe to load or unload shared libraries in the darwin kernel"); 1534 return error; 1535 } 1536 1537 void DynamicLoaderDarwinKernel::Initialize() { 1538 PluginManager::RegisterPlugin(GetPluginNameStatic(), 1539 GetPluginDescriptionStatic(), CreateInstance, 1540 DebuggerInitialize); 1541 } 1542 1543 void DynamicLoaderDarwinKernel::Terminate() { 1544 PluginManager::UnregisterPlugin(CreateInstance); 1545 } 1546 1547 void DynamicLoaderDarwinKernel::DebuggerInitialize( 1548 lldb_private::Debugger &debugger) { 1549 if (!PluginManager::GetSettingForDynamicLoaderPlugin( 1550 debugger, DynamicLoaderDarwinKernelProperties::GetSettingName())) { 1551 const bool is_global_setting = true; 1552 PluginManager::CreateSettingForDynamicLoaderPlugin( 1553 debugger, GetGlobalProperties()->GetValueProperties(), 1554 ConstString("Properties for the DynamicLoaderDarwinKernel plug-in."), 1555 is_global_setting); 1556 } 1557 } 1558 1559 lldb_private::ConstString DynamicLoaderDarwinKernel::GetPluginNameStatic() { 1560 static ConstString g_name("darwin-kernel"); 1561 return g_name; 1562 } 1563 1564 const char *DynamicLoaderDarwinKernel::GetPluginDescriptionStatic() { 1565 return "Dynamic loader plug-in that watches for shared library loads/unloads " 1566 "in the MacOSX kernel."; 1567 } 1568 1569 //------------------------------------------------------------------ 1570 // PluginInterface protocol 1571 //------------------------------------------------------------------ 1572 lldb_private::ConstString DynamicLoaderDarwinKernel::GetPluginName() { 1573 return GetPluginNameStatic(); 1574 } 1575 1576 uint32_t DynamicLoaderDarwinKernel::GetPluginVersion() { return 1; } 1577 1578 lldb::ByteOrder 1579 DynamicLoaderDarwinKernel::GetByteOrderFromMagic(uint32_t magic) { 1580 switch (magic) { 1581 case llvm::MachO::MH_MAGIC: 1582 case llvm::MachO::MH_MAGIC_64: 1583 return endian::InlHostByteOrder(); 1584 1585 case llvm::MachO::MH_CIGAM: 1586 case llvm::MachO::MH_CIGAM_64: 1587 if (endian::InlHostByteOrder() == lldb::eByteOrderBig) 1588 return lldb::eByteOrderLittle; 1589 else 1590 return lldb::eByteOrderBig; 1591 1592 default: 1593 break; 1594 } 1595 return lldb::eByteOrderInvalid; 1596 } 1597