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