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