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 LLDB_LOGF(log,
694 "KextImageInfo::ReadMemoryModule the kernel said to find "
695 "uuid %s at 0x%" PRIx64
696 " but instead we found uuid %s, throwing it away",
697 m_uuid.GetAsString().c_str(), m_load_address,
698 memory_module_sp->GetUUID().GetAsString().c_str());
699 return false;
700 }
701 }
702
703 // If the in-memory Module has a UUID, let's use that.
704 if (!m_uuid.IsValid() && memory_module_sp->GetUUID().IsValid()) {
705 m_uuid = memory_module_sp->GetUUID();
706 }
707
708 m_memory_module_sp = memory_module_sp;
709 m_kernel_image = this_is_kernel;
710 if (this_is_kernel) {
711 // This is unusual and probably not intended
712 LLDB_LOGF(log, "KextImageInfo::ReadMemoryModule read the kernel binary out "
713 "of memory");
714 if (memory_module_sp->GetArchitecture().IsValid()) {
715 process->GetTarget().SetArchitecture(memory_module_sp->GetArchitecture());
716 }
717 }
718
719 return true;
720}
721
725
729
731 Process *process, Progress *progress) {
733 if (IsLoaded())
734 return true;
735
736 Target &target = process->GetTarget();
737
738 // kexts will have a uuid from the table.
739 // for the kernel, we'll need to read the load commands out of memory to get it.
740 if (m_uuid.IsValid() == false) {
741 if (ReadMemoryModule(process) == false) {
743 LLDB_LOGF(log,
744 "Unable to read '%s' from memory at address 0x%" PRIx64
745 " to get the segment load addresses.",
746 m_name.c_str(), m_load_address);
747 return false;
748 }
749 }
750
751 if (IsKernel() && m_uuid.IsValid()) {
753 s->Printf("Kernel UUID: %s\n", m_uuid.GetAsString().c_str());
754 s->Printf("Load Address: 0x%" PRIx64 "\n", m_load_address);
755
756 // Start of a kernel debug session, we have the UUID of the kernel.
757 // Go through the target's list of modules and if there are any kernel
758 // modules with non-matching UUIDs, remove them. The user may have added
759 // the wrong kernel binary manually and it will only confuse things.
760 ModuleList incorrect_kernels;
761 for (ModuleSP module_sp : target.GetImages().Modules()) {
762 if (is_kernel(module_sp.get()) && module_sp->GetUUID() != m_uuid)
763 incorrect_kernels.Append(module_sp);
764 }
765 target.GetImages().Remove(incorrect_kernels);
766 }
767
768 if (!m_module_sp) {
769 // See if the kext has already been loaded into the target, probably by the
770 // user doing target modules add.
771 const ModuleList &target_images = target.GetImages();
772 m_module_sp = target_images.FindModule(m_uuid);
773
774 StreamString prog_str;
775 // 'mach_kernel' is a fake name we make up to find kernels
776 // that were located by the local filesystem scan.
777 if (GetName() != "mach_kernel")
778 prog_str << GetName() << " ";
779 if (GetUUID().IsValid())
780 prog_str << GetUUID().GetAsString() << " ";
782 prog_str << "at 0x";
783 prog_str.PutHex64(GetLoadAddress());
784 }
785
786 std::unique_ptr<Progress> progress_up;
787 if (progress)
788 progress->Increment(1, prog_str.GetString().str());
789 else {
790 if (IsKernel())
791 progress_up = std::make_unique<Progress>("Loading kernel",
792 prog_str.GetString().str());
793 else
794 progress_up = std::make_unique<Progress>("Loading kext",
795 prog_str.GetString().str());
796 }
797
798 // Search for the kext on the local filesystem via the UUID
799 if (!m_module_sp && m_uuid.IsValid()) {
800 ModuleSpec module_spec;
801 module_spec.SetTarget(target.shared_from_this());
802 module_spec.GetUUID() = m_uuid;
803 if (!m_uuid.IsValid())
804 module_spec.GetArchitecture() = target.GetArchitecture();
805 module_spec.GetFileSpec() = FileSpec(m_name);
806
807 // If the current platform is PlatformDarwinKernel, create a ModuleSpec
808 // with the filename set to be the bundle ID for this kext, e.g.
809 // "com.apple.filesystems.msdosfs", and ask the platform to find it.
810 // PlatformDarwinKernel does a special scan for kexts on the local
811 // system.
812 PlatformSP platform_sp(target.GetPlatform());
813 if (platform_sp) {
814 platform_sp->GetSharedModule(module_spec, process, m_module_sp, nullptr,
815 nullptr);
816 }
817
818 // Ask the Target to find this file on the local system, if possible.
819 // This will search in the list of currently-loaded files, look in the
820 // standard search paths on the system, and on a Mac it will try calling
821 // the DebugSymbols framework with the UUID to find the binary via its
822 // search methods.
823 if (!m_module_sp) {
824 m_module_sp = target.GetOrCreateModule(module_spec, true /* notify */);
825 }
826
827 // For the kernel, we really do need an on-disk file copy of the binary
828 // to do anything useful. This will force a call to dsymForUUID if it
829 // exists, instead of depending on the DebugSymbols preferences being
830 // set.
831 Status kernel_search_error;
832 if (IsKernel() &&
833 (!m_module_sp || !m_module_sp->GetSymbolFileFileSpec())) {
835 module_spec, kernel_search_error, true)) {
836 if (FileSystem::Instance().Exists(module_spec.GetFileSpec())) {
837 m_module_sp = std::make_shared<Module>(module_spec.GetFileSpec(),
838 target.GetArchitecture());
839 }
840 }
841 }
842
843 if (IsKernel() && !m_module_sp) {
845 s->Printf("WARNING: Unable to locate kernel binary on the debugger "
846 "system.\n");
847 if (kernel_search_error.Fail() && kernel_search_error.AsCString("") &&
848 kernel_search_error.AsCString("")[0] != '\0') {
849 *s << kernel_search_error.AsCString();
850 }
851 }
852 }
853
854 if (m_module_sp && m_uuid.IsValid() && m_module_sp->GetUUID() == m_uuid &&
855 m_module_sp->GetObjectFile()) {
856 if (ObjectFileMachO *ondisk_objfile_macho =
857 llvm::dyn_cast<ObjectFileMachO>(m_module_sp->GetObjectFile())) {
858 if (!IsKernel() && !ondisk_objfile_macho->IsKext()) {
859 // We have a non-kext, non-kernel binary. If we already have this
860 // loaded in the Target with load addresses, don't re-load it again.
861 ModuleSP existing_module_sp = target.GetImages().FindModule(m_uuid);
862 if (existing_module_sp &&
863 existing_module_sp->IsLoadedInTarget(&target)) {
864 LLDB_LOGF(log,
865 "'%s' with UUID %s is not a kext or kernel, and is "
866 "already registered in target, not loading.",
867 m_name.c_str(), m_uuid.GetAsString().c_str());
868 // It's already loaded, return true.
869 return true;
870 }
871 }
872 }
873 }
874
875 // If we managed to find a module, append it to the target's list of
876 // images. If we also have a memory module, require that they have matching
877 // UUIDs
878 if (m_module_sp) {
879 if (m_uuid.IsValid() && m_module_sp->GetUUID() == m_uuid) {
880 target.GetImages().AppendIfNeeded(m_module_sp, false);
881 }
882 }
883 }
884
885 // If we've found a binary, read the load commands out of memory so we
886 // can set the segment load addresses.
887 if (m_module_sp)
888 ReadMemoryModule (process);
889
890 static ConstString g_section_name_LINKEDIT("__LINKEDIT");
891
893 if (m_module_sp->GetUUID() == m_memory_module_sp->GetUUID()) {
894 ObjectFile *ondisk_object_file = m_module_sp->GetObjectFile();
895 ObjectFile *memory_object_file = m_memory_module_sp->GetObjectFile();
896
897 if (memory_object_file && ondisk_object_file) {
898 // The memory_module for kexts may have an invalid __LINKEDIT seg; skip
899 // it.
900 const bool ignore_linkedit = !IsKernel();
901
902 // Normally a kext will have its segment load commands
903 // (LC_SEGMENT vmaddrs) corrected in memory to have their
904 // actual segment addresses.
905 // Userland proceses have their libraries updated the same way
906 // by dyld. The Mach-O load commands in memory are the canonical
907 // addresses.
908 //
909 // If the kernel gives us a binary where the in-memory segment
910 // vmaddr is incorrect, then this binary was put in memory without
911 // updating its Mach-O load commands. We should assume a static
912 // slide value will be applied to every segment; we don't have the
913 // correct addresses for each individual segment.
914 addr_t fixed_slide = LLDB_INVALID_ADDRESS;
915 if (ObjectFileMachO *memory_objfile_macho =
916 llvm::dyn_cast<ObjectFileMachO>(memory_object_file)) {
917 if (Section *header_sect =
918 memory_objfile_macho->GetMachHeaderSection()) {
919 if (header_sect->GetFileAddress() != m_load_address) {
920 fixed_slide = m_load_address - header_sect->GetFileAddress();
921 LLDB_LOGF(
922 log,
923 "kext %s in-memory LC_SEGMENT vmaddr is not correct, using a "
924 "fixed slide of 0x%" PRIx64,
925 m_name.c_str(), fixed_slide);
926 }
927 }
928 }
929
930 SectionList *ondisk_section_list = ondisk_object_file->GetSectionList();
931 SectionList *memory_section_list = memory_object_file->GetSectionList();
932 if (memory_section_list && ondisk_section_list) {
933 const uint32_t num_ondisk_sections = ondisk_section_list->GetSize();
934 // There may be CTF sections in the memory image so we can't always
935 // just compare the number of sections (which are actually segments
936 // in mach-o parlance)
937 uint32_t sect_idx = 0;
938
939 // Use the memory_module's addresses for each section to set the file
940 // module's load address as appropriate. We don't want to use a
941 // single slide value for the entire kext - different segments may be
942 // slid different amounts by the kext loader.
943
944 uint32_t num_sections_loaded = 0;
945 for (sect_idx = 0; sect_idx < num_ondisk_sections; ++sect_idx) {
946 SectionSP ondisk_section_sp(
947 ondisk_section_list->GetSectionAtIndex(sect_idx));
948 if (ondisk_section_sp) {
949 // Don't ever load __LINKEDIT as it may or may not be actually
950 // mapped into memory and there is no current way to tell. Until
951 // such an ability exists, do not load the __LINKEDIT.
952 if (ignore_linkedit &&
953 ondisk_section_sp->GetName() == g_section_name_LINKEDIT)
954 continue;
955
956 if (fixed_slide != LLDB_INVALID_ADDRESS) {
958 ondisk_section_sp,
959 ondisk_section_sp->GetFileAddress() + fixed_slide);
960 } else {
961 const Section *memory_section =
962 memory_section_list
963 ->FindSectionByName(ondisk_section_sp->GetName())
964 .get();
965 if (memory_section) {
967 ondisk_section_sp, memory_section->GetFileAddress());
968 ++num_sections_loaded;
969 }
970 }
971 }
972 }
973 if (num_sections_loaded > 0)
975 else
976 m_module_sp.reset(); // No sections were loaded
977 } else
978 m_module_sp.reset(); // One or both section lists
979 } else
980 m_module_sp.reset(); // One or both object files missing
981 } else
982 m_module_sp.reset(); // UUID mismatch
983 }
984
985 bool is_loaded = IsLoaded();
986
987 if (is_loaded && m_module_sp && IsKernel()) {
989 ObjectFile *kernel_object_file = m_module_sp->GetObjectFile();
990 if (kernel_object_file) {
991 addr_t file_address =
992 kernel_object_file->GetBaseAddress().GetFileAddress();
994 file_address != LLDB_INVALID_ADDRESS) {
995 s->Printf("Kernel slid 0x%" PRIx64 " in memory.\n",
996 m_load_address - file_address);
997 }
998 }
999 s->Printf("Loaded kernel file %s\n",
1000 m_module_sp->GetFileSpec().GetPath().c_str());
1001 }
1002
1003 // Notify the target about the module being added;
1004 // set breakpoints, load dSYM scripts, etc. as needed.
1005 if (is_loaded && m_module_sp) {
1006 ModuleList loaded_module_list;
1007 loaded_module_list.Append(m_module_sp);
1008 target.ModulesDidLoad(loaded_module_list);
1009 }
1010
1011 return is_loaded;
1012}
1013
1016 return m_memory_module_sp->GetArchitecture().GetAddressByteSize();
1017 if (m_module_sp)
1018 return m_module_sp->GetArchitecture().GetAddressByteSize();
1019 return 0;
1020}
1021
1024 return m_memory_module_sp->GetArchitecture().GetByteOrder();
1025 if (m_module_sp)
1026 return m_module_sp->GetArchitecture().GetByteOrder();
1027 return endian::InlHostByteOrder();
1028}
1029
1033 return m_memory_module_sp->GetArchitecture();
1034 if (m_module_sp)
1035 return m_module_sp->GetArchitecture();
1036 return lldb_private::ArchSpec();
1037}
1038
1039// Load the kernel module and initialize the "m_kernel" member. Return true
1040// _only_ if the kernel is loaded the first time through (subsequent calls to
1041// this function should return false after the kernel has been already loaded).
1043 if (!m_kext_summary_header_ptr_addr.IsValid()) {
1044 m_kernel.Clear();
1045 ModuleSP module_sp = m_process->GetTarget().GetExecutableModule();
1046 if (is_kernel(module_sp.get())) {
1047 m_kernel.SetModule(module_sp);
1048 m_kernel.SetIsKernel(true);
1049 }
1050
1051 ConstString kernel_name("mach_kernel");
1052 if (m_kernel.GetModule().get() && m_kernel.GetModule()->GetObjectFile() &&
1053 !m_kernel.GetModule()
1054 ->GetObjectFile()
1055 ->GetFileSpec()
1056 .GetFilename()
1057 .IsEmpty()) {
1058 kernel_name =
1059 m_kernel.GetModule()->GetObjectFile()->GetFileSpec().GetFilename();
1060 }
1061 m_kernel.SetName(kernel_name.AsCString());
1062
1063 if (m_kernel.GetLoadAddress() == LLDB_INVALID_ADDRESS) {
1064 m_kernel.SetLoadAddress(m_kernel_load_address);
1065 if (m_kernel.GetLoadAddress() == LLDB_INVALID_ADDRESS &&
1066 m_kernel.GetModule()) {
1067 // We didn't get a hint from the process, so we will try the kernel at
1068 // the address that it exists at in the file if we have one
1069 ObjectFile *kernel_object_file = m_kernel.GetModule()->GetObjectFile();
1070 if (kernel_object_file) {
1071 addr_t load_address =
1072 kernel_object_file->GetBaseAddress().GetLoadAddress(
1073 &m_process->GetTarget());
1074 addr_t file_address =
1075 kernel_object_file->GetBaseAddress().GetFileAddress();
1076 if (load_address != LLDB_INVALID_ADDRESS && load_address != 0) {
1077 m_kernel.SetLoadAddress(load_address);
1078 if (load_address != file_address) {
1079 // Don't accidentally relocate the kernel to the File address --
1080 // the Load address has already been set to its actual in-memory
1081 // address. Mark it as IsLoaded.
1082 m_kernel.SetProcessStopId(m_process->GetStopID());
1083 }
1084 } else {
1085 m_kernel.SetLoadAddress(file_address);
1086 }
1087 }
1088 }
1089 }
1090 if (m_kernel.GetLoadAddress() != LLDB_INVALID_ADDRESS)
1091 if (!m_kernel.LoadImageUsingMemoryModule(m_process))
1092 m_kernel.LoadImageAtFileAddress(m_process);
1093
1094 // The operating system plugin gets loaded and initialized in
1095 // LoadImageUsingMemoryModule when we discover the kernel dSYM. For a core
1096 // file in particular, that's the wrong place to do this, since we haven't
1097 // fixed up the section addresses yet. So let's redo it here.
1099
1100 if (m_kernel.IsLoaded() && m_kernel.GetModule()) {
1101 static ConstString kext_summary_symbol("gLoadedKextSummaries");
1102 static ConstString arm64_T1Sz_value("gT1Sz");
1103 const Symbol *symbol =
1104 m_kernel.GetModule()->FindFirstSymbolWithNameAndType(
1105 kext_summary_symbol, eSymbolTypeAny);
1106 if (symbol) {
1108 // Update all image infos
1110 }
1111 // If the kernel global with the T1Sz setting is available,
1112 // update the target.process.virtual-addressable-bits to be correct.
1113 // NB the xnu kernel always has T0Sz and T1Sz the same value. If
1114 // it wasn't the same, we would need to set
1115 // target.process.virtual-addressable-bits = T0Sz
1116 // target.process.highmem-virtual-addressable-bits = T1Sz
1117 symbol = m_kernel.GetModule()->FindFirstSymbolWithNameAndType(
1118 arm64_T1Sz_value, eSymbolTypeData);
1119 if (symbol) {
1120 const addr_t orig_code_mask = m_process->GetCodeAddressMask();
1121 const addr_t orig_data_mask = m_process->GetDataAddressMask();
1122
1123 m_process->SetCodeAddressMask(0);
1124 m_process->SetDataAddressMask(0);
1125 Status error;
1126 // gT1Sz is 8 bytes. We may run on a stripped kernel binary
1127 // where we can't get the size accurately. Hardcode it.
1128 const size_t sym_bytesize = 8; // size of gT1Sz value
1129 uint64_t sym_value =
1130 m_process->GetTarget().ReadUnsignedIntegerFromMemory(
1131 symbol->GetAddress(), sym_bytesize, 0, error);
1132 if (error.Success()) {
1133 // 64 - T1Sz is the highest bit used for auth.
1134 // The value we pass in to SetVirtualAddressableBits is
1135 // the number of bits used for addressing, so if
1136 // T1Sz is 25, then 64-25 == 39, bits 0..38 are used for
1137 // addressing, bits 39..63 are used for PAC/TBI or whatever.
1138 uint32_t virt_addr_bits = 64 - sym_value;
1139 addr_t mask = AddressableBits::AddressableBitToMask(virt_addr_bits);
1140 m_process->SetCodeAddressMask(mask);
1141 m_process->SetDataAddressMask(mask);
1142 } else {
1143 m_process->SetCodeAddressMask(orig_code_mask);
1144 m_process->SetDataAddressMask(orig_data_mask);
1145 }
1146 }
1147 } else {
1148 m_kernel.Clear();
1149 }
1150 }
1151}
1152
1153// Static callback function that gets called when our DYLD notification
1154// breakpoint gets hit. We update all of our image infos and then let our super
1155// class DynamicLoader class decide if we should stop or not (based on global
1156// preference).
1158 void *baton, StoppointCallbackContext *context, user_id_t break_id,
1159 user_id_t break_loc_id) {
1160 return static_cast<DynamicLoaderDarwinKernel *>(baton)->BreakpointHit(
1161 context, break_id, break_loc_id);
1162}
1163
1165 user_id_t break_id,
1166 user_id_t break_loc_id) {
1168 LLDB_LOGF(log, "DynamicLoaderDarwinKernel::BreakpointHit (...)\n");
1169
1171
1172 if (log)
1173 PutToLog(log);
1174
1175 return GetStopWhenImagesChange();
1176}
1177
1179 std::lock_guard<std::recursive_mutex> guard(m_mutex);
1180
1181 // the all image infos is already valid for this process stop ID
1182
1183 if (m_kext_summary_header_ptr_addr.IsValid()) {
1184 const uint32_t addr_size = m_kernel.GetAddressByteSize();
1185 const ByteOrder byte_order = m_kernel.GetByteOrder();
1186 Status error;
1187 // Read enough bytes for a "OSKextLoadedKextSummaryHeader" structure which
1188 // is currently 4 uint32_t and a pointer.
1189 uint8_t buf[24];
1190 DataExtractor data(buf, sizeof(buf), byte_order, addr_size);
1191 const size_t count = 4 * sizeof(uint32_t) + addr_size;
1192 const bool force_live_memory = true;
1193 if (m_process->GetTarget().ReadPointerFromMemory(
1195 m_kext_summary_header_addr, force_live_memory)) {
1196 // We got a valid address for our kext summary header and make sure it
1197 // isn't NULL
1198 if (m_kext_summary_header_addr.IsValid() &&
1199 m_kext_summary_header_addr.GetFileAddress() != 0) {
1200 const size_t bytes_read = m_process->GetTarget().ReadMemory(
1201 m_kext_summary_header_addr, buf, count, error, force_live_memory);
1202 if (bytes_read == count) {
1203 lldb::offset_t offset = 0;
1204 m_kext_summary_header.version = data.GetU32(&offset);
1205 if (m_kext_summary_header.version > 128) {
1206 lldb::StreamSP s =
1207 m_process->GetTarget().GetDebugger().GetAsyncOutputStream();
1208 s->Printf("WARNING: Unable to read kext summary header, got "
1209 "improbable version number %u\n",
1210 m_kext_summary_header.version);
1211 // If we get an improbably large version number, we're probably
1212 // getting bad memory.
1214 return false;
1215 }
1216 if (m_kext_summary_header.version >= 2) {
1217 m_kext_summary_header.entry_size = data.GetU32(&offset);
1218 if (m_kext_summary_header.entry_size > 4096) {
1219 // If we get an improbably large entry_size, we're probably
1220 // getting bad memory.
1221 lldb::StreamSP s =
1222 m_process->GetTarget().GetDebugger().GetAsyncOutputStream();
1223 s->Printf("WARNING: Unable to read kext summary header, got "
1224 "improbable entry_size %u\n",
1225 m_kext_summary_header.entry_size);
1227 return false;
1228 }
1229 } else {
1230 // Versions less than 2 didn't have an entry size, it was hard
1231 // coded
1232 m_kext_summary_header.entry_size =
1234 }
1235 m_kext_summary_header.entry_count = data.GetU32(&offset);
1236 if (m_kext_summary_header.entry_count > 10000) {
1237 // If we get an improbably large number of kexts, we're probably
1238 // getting bad memory.
1239 lldb::StreamSP s =
1240 m_process->GetTarget().GetDebugger().GetAsyncOutputStream();
1241 s->Printf("WARNING: Unable to read kext summary header, got "
1242 "improbable number of kexts %u\n",
1243 m_kext_summary_header.entry_count);
1245 return false;
1246 }
1247 return true;
1248 }
1249 }
1250 }
1251 }
1253 return false;
1254}
1255
1256// We've either (a) just attached to a new kernel, or (b) the kexts-changed
1257// breakpoint was hit and we need to figure out what kexts have been added or
1258// removed. Read the kext summaries from the inferior kernel memory, compare
1259// them against the m_known_kexts vector and update the m_known_kexts vector as
1260// needed to keep in sync with the inferior.
1261
1263 const Address &kext_summary_addr, uint32_t count) {
1264 KextImageInfo::collection kext_summaries;
1266 LLDB_LOGF(log,
1267 "Kexts-changed breakpoint hit, there are %d kexts currently.\n",
1268 count);
1269
1270 std::lock_guard<std::recursive_mutex> guard(m_mutex);
1271
1272 if (!ReadKextSummaries(kext_summary_addr, count, kext_summaries))
1273 return false;
1274
1275 // read the plugin.dynamic-loader.darwin-kernel.load-kexts setting -- if the
1276 // user requested no kext loading, don't print any messages about kexts &
1277 // don't try to read them.
1278 const bool load_kexts = GetGlobalProperties().GetLoadKexts();
1279
1280 // By default, all kexts we've loaded in the past are marked as "remove" and
1281 // all of the kexts we just found out about from ReadKextSummaries are marked
1282 // as "add".
1283 std::vector<bool> to_be_removed(m_known_kexts.size(), true);
1284 std::vector<bool> to_be_added(count, true);
1285
1286 int number_of_new_kexts_being_added = 0;
1287 int number_of_old_kexts_being_removed = m_known_kexts.size();
1288
1289 const uint32_t new_kexts_size = kext_summaries.size();
1290 const uint32_t old_kexts_size = m_known_kexts.size();
1291
1292 // The m_known_kexts vector may have entries that have been Cleared, or are a
1293 // kernel.
1294 for (uint32_t old_kext = 0; old_kext < old_kexts_size; old_kext++) {
1295 bool ignore = false;
1296 KextImageInfo &image_info = m_known_kexts[old_kext];
1297 if (image_info.IsKernel()) {
1298 ignore = true;
1299 } else if (image_info.GetLoadAddress() == LLDB_INVALID_ADDRESS &&
1300 !image_info.GetModule()) {
1301 ignore = true;
1302 }
1303
1304 if (ignore) {
1305 number_of_old_kexts_being_removed--;
1306 to_be_removed[old_kext] = false;
1307 }
1308 }
1309
1310 // Scan over the list of kexts we just read from the kernel, note those that
1311 // need to be added and those already loaded.
1312 for (uint32_t new_kext = 0; new_kext < new_kexts_size; new_kext++) {
1313 bool add_this_one = true;
1314 for (uint32_t old_kext = 0; old_kext < old_kexts_size; old_kext++) {
1315 if (m_known_kexts[old_kext] == kext_summaries[new_kext]) {
1316 // We already have this kext, don't re-load it.
1317 to_be_added[new_kext] = false;
1318 // This kext is still present, do not remove it.
1319 to_be_removed[old_kext] = false;
1320
1321 number_of_old_kexts_being_removed--;
1322 add_this_one = false;
1323 break;
1324 }
1325 }
1326 // If this "kext" entry is actually an alias for the kernel -- the kext was
1327 // compiled into the kernel or something -- then we don't want to load the
1328 // kernel's text section at a different address. Ignore this kext entry.
1329 if (kext_summaries[new_kext].GetUUID().IsValid() &&
1330 m_kernel.GetUUID().IsValid() &&
1331 kext_summaries[new_kext].GetUUID() == m_kernel.GetUUID()) {
1332 to_be_added[new_kext] = false;
1333 break;
1334 }
1335 if (add_this_one) {
1336 number_of_new_kexts_being_added++;
1337 }
1338 }
1339
1340 if (number_of_new_kexts_being_added == 0 &&
1341 number_of_old_kexts_being_removed == 0)
1342 return true;
1343
1344 lldb::StreamSP s =
1345 m_process->GetTarget().GetDebugger().GetAsyncOutputStream();
1346 if (load_kexts) {
1347 if (number_of_new_kexts_being_added > 0 &&
1348 number_of_old_kexts_being_removed > 0) {
1349 s->Printf("Loading %d kext modules and unloading %d kext modules ",
1350 number_of_new_kexts_being_added,
1351 number_of_old_kexts_being_removed);
1352 } else if (number_of_new_kexts_being_added > 0) {
1353 s->Printf("Loading %d kext modules ", number_of_new_kexts_being_added);
1354 } else if (number_of_old_kexts_being_removed > 0) {
1355 s->Printf("Unloading %d kext modules ",
1356 number_of_old_kexts_being_removed);
1357 }
1358 }
1359
1360 if (load_kexts) {
1361 LLDB_LOGF(log,
1362 "DynamicLoaderDarwinKernel::ParseKextSummaries: %d kexts "
1363 "added, %d kexts removed",
1364 number_of_new_kexts_being_added,
1365 number_of_old_kexts_being_removed);
1366 } else {
1367 LLDB_LOGF(log,
1368 "DynamicLoaderDarwinKernel::ParseKextSummaries kext loading is "
1369 "disabled, else would have %d kexts added, %d kexts removed",
1370 number_of_new_kexts_being_added,
1371 number_of_old_kexts_being_removed);
1372 }
1373
1374 // Build up a list of <kext-name, uuid> for any kexts that fail to load
1375 std::vector<std::pair<std::string, UUID>> kexts_failed_to_load;
1376 if (number_of_new_kexts_being_added > 0) {
1377 ModuleList loaded_module_list;
1378 Progress progress("Loading kext", "", number_of_new_kexts_being_added);
1379
1380 const uint32_t num_of_new_kexts = kext_summaries.size();
1381 for (uint32_t new_kext = 0; new_kext < num_of_new_kexts; new_kext++) {
1382 if (to_be_added[new_kext]) {
1383 KextImageInfo &image_info = kext_summaries[new_kext];
1384 if (load_kexts) {
1385 if (!image_info.LoadImageUsingMemoryModule(m_process, &progress)) {
1386 kexts_failed_to_load.push_back(std::pair<std::string, UUID>(
1387 kext_summaries[new_kext].GetName(),
1388 kext_summaries[new_kext].GetUUID()));
1390 }
1391 }
1392
1393 m_known_kexts.push_back(image_info);
1394
1395 if (image_info.GetModule() &&
1396 m_process->GetStopID() == image_info.GetProcessStopId())
1397 loaded_module_list.AppendIfNeeded(image_info.GetModule());
1398
1399 if (log)
1400 kext_summaries[new_kext].PutToLog(log);
1401 }
1402 }
1403 m_process->GetTarget().ModulesDidLoad(loaded_module_list);
1404 }
1405
1406 if (number_of_old_kexts_being_removed > 0) {
1407 ModuleList loaded_module_list;
1408 const uint32_t num_of_old_kexts = m_known_kexts.size();
1409 for (uint32_t old_kext = 0; old_kext < num_of_old_kexts; old_kext++) {
1410 ModuleList unloaded_module_list;
1411 if (to_be_removed[old_kext]) {
1412 KextImageInfo &image_info = m_known_kexts[old_kext];
1413 // You can't unload the kernel.
1414 if (!image_info.IsKernel()) {
1415 if (image_info.GetModule()) {
1416 unloaded_module_list.AppendIfNeeded(image_info.GetModule());
1417 }
1418 s->Printf(".");
1419 image_info.Clear();
1420 // should pull it out of the KextImageInfos vector but that would
1421 // mutate the list and invalidate the to_be_removed bool vector;
1422 // leaving it in place once Cleared() is relatively harmless.
1423 }
1424 }
1425 m_process->GetTarget().ModulesDidUnload(unloaded_module_list, false);
1426 }
1427 }
1428
1429 if (load_kexts) {
1430 s->Printf(" done.\n");
1431 if (kexts_failed_to_load.size() > 0 && number_of_new_kexts_being_added > 0) {
1432 s->Printf("Failed to load %d of %d kexts:\n",
1433 (int)kexts_failed_to_load.size(),
1434 number_of_new_kexts_being_added);
1435 // print a sorted list of <kext-name, uuid> kexts which failed to load
1436 unsigned longest_name = 0;
1437 std::sort(kexts_failed_to_load.begin(), kexts_failed_to_load.end());
1438 for (const auto &ku : kexts_failed_to_load) {
1439 if (ku.first.size() > longest_name)
1440 longest_name = ku.first.size();
1441 }
1442 for (const auto &ku : kexts_failed_to_load) {
1443 std::string uuid;
1444 if (ku.second.IsValid())
1445 uuid = ku.second.GetAsString();
1446 s->Printf(" %-*s %s\n", longest_name, ku.first.c_str(), uuid.c_str());
1447 }
1448 }
1449 }
1450
1451 return true;
1452}
1453
1455 const Address &kext_summary_addr, uint32_t image_infos_count,
1456 KextImageInfo::collection &image_infos) {
1457 const ByteOrder endian = m_kernel.GetByteOrder();
1458 const uint32_t addr_size = m_kernel.GetAddressByteSize();
1459
1460 image_infos.resize(image_infos_count);
1461 const size_t count = image_infos.size() * m_kext_summary_header.entry_size;
1462 DataBufferHeap data(count, 0);
1463 Status error;
1464
1465 const bool force_live_memory = true;
1466 const size_t bytes_read = m_process->GetTarget().ReadMemory(
1467 kext_summary_addr, data.GetBytes(), data.GetByteSize(), error, force_live_memory);
1468 if (bytes_read == count) {
1469
1470 DataExtractor extractor(data.GetBytes(), data.GetByteSize(), endian,
1471 addr_size);
1472 uint32_t i = 0;
1473 for (uint32_t kext_summary_offset = 0;
1474 i < image_infos.size() &&
1475 extractor.ValidOffsetForDataOfSize(kext_summary_offset,
1476 m_kext_summary_header.entry_size);
1477 ++i, kext_summary_offset += m_kext_summary_header.entry_size) {
1478 lldb::offset_t offset = kext_summary_offset;
1479 const void *name_data =
1480 extractor.GetData(&offset, KERNEL_MODULE_MAX_NAME);
1481 if (name_data == nullptr)
1482 break;
1483 image_infos[i].SetName((const char *)name_data);
1484 UUID uuid(extractor.GetData(&offset, 16), 16);
1485 image_infos[i].SetUUID(uuid);
1486 image_infos[i].SetLoadAddress(extractor.GetU64(&offset));
1487 image_infos[i].SetSize(extractor.GetU64(&offset));
1488 }
1489 if (i < image_infos.size())
1490 image_infos.resize(i);
1491 } else {
1492 image_infos.clear();
1493 }
1494 return image_infos.size();
1495}
1496
1498 std::lock_guard<std::recursive_mutex> guard(m_mutex);
1499
1500 if (ReadKextSummaryHeader()) {
1501 if (m_kext_summary_header.entry_count > 0 &&
1502 m_kext_summary_header_addr.IsValid()) {
1503 Address summary_addr(m_kext_summary_header_addr);
1504 summary_addr.Slide(m_kext_summary_header.GetSize());
1505 if (!ParseKextSummaries(summary_addr,
1506 m_kext_summary_header.entry_count)) {
1507 m_known_kexts.clear();
1508 }
1509 return true;
1510 }
1511 }
1512 return false;
1513}
1514
1515// Dump an image info structure to the file handle provided.
1518 LLDB_LOG(log, "uuid={0} name=\"{1}\" (UNLOADED)", m_uuid.GetAsString(),
1519 m_name);
1520 } else {
1521 LLDB_LOG(log, "addr={0:x+16} size={1:x+16} uuid={2} name=\"{3}\"",
1522 m_load_address, m_size, m_uuid.GetAsString(), m_name);
1523 }
1524}
1525
1526// Dump the _dyld_all_image_infos members and all current image infos that we
1527// have parsed to the file handle provided.
1529 if (log == nullptr)
1530 return;
1531
1532 std::lock_guard<std::recursive_mutex> guard(m_mutex);
1533 LLDB_LOGF(log,
1534 "gLoadedKextSummaries = 0x%16.16" PRIx64
1535 " { version=%u, entry_size=%u, entry_count=%u }",
1536 m_kext_summary_header_addr.GetFileAddress(),
1537 m_kext_summary_header.version, m_kext_summary_header.entry_size,
1538 m_kext_summary_header.entry_count);
1539
1540 size_t i;
1541 const size_t count = m_known_kexts.size();
1542 if (count > 0) {
1543 log->PutCString("Loaded:");
1544 for (i = 0; i < count; i++)
1545 m_known_kexts[i].PutToLog(log);
1546 }
1547}
1548
1550 DEBUG_PRINTF("DynamicLoaderDarwinKernel::%s() process state = %s\n",
1551 __FUNCTION__, StateAsCString(m_process->GetState()));
1552 Clear(true);
1553 m_process = process;
1554}
1555
1557 if (m_break_id == LLDB_INVALID_BREAK_ID && m_kernel.GetModule() &&
1558 m_process->IsLiveDebugSession()) {
1559 DEBUG_PRINTF("DynamicLoaderDarwinKernel::%s() process state = %s\n",
1560 __FUNCTION__, StateAsCString(m_process->GetState()));
1561
1562 const bool internal_bp = true;
1563 const bool hardware = false;
1564 const LazyBool skip_prologue = eLazyBoolNo;
1565 FileSpecList module_spec_list;
1566 module_spec_list.Append(m_kernel.GetModule()->GetFileSpec());
1567 Breakpoint *bp =
1568 m_process->GetTarget()
1569 .CreateBreakpoint(&module_spec_list, nullptr,
1570 "OSKextLoadedKextSummariesUpdated",
1571 eFunctionNameTypeFull, eLanguageTypeUnknown, 0,
1572 /*offset_is_insn_count = */ false, skip_prologue,
1573 internal_bp, hardware)
1574 .get();
1575
1577 true);
1578 m_break_id = bp->GetID();
1579 }
1580}
1581
1582// Member function that gets called when the process state changes.
1584 StateType state) {
1585 DEBUG_PRINTF("DynamicLoaderDarwinKernel::%s(%s)\n", __FUNCTION__,
1586 StateAsCString(state));
1587 switch (state) {
1588 case eStateConnected:
1589 case eStateAttaching:
1590 case eStateLaunching:
1591 case eStateInvalid:
1592 case eStateUnloaded:
1593 case eStateExited:
1594 case eStateDetached:
1595 Clear(false);
1596 break;
1597
1598 case eStateStopped:
1600 break;
1601
1602 case eStateRunning:
1603 case eStateStepping:
1604 case eStateCrashed:
1605 case eStateSuspended:
1606 break;
1607 }
1608}
1609
1612 bool stop_others) {
1613 ThreadPlanSP thread_plan_sp;
1614 Log *log = GetLog(LLDBLog::Step);
1615 LLDB_LOGF(log, "Could not find symbol for step through.");
1616 return thread_plan_sp;
1617}
1618
1620 Status error;
1622 "always unsafe to load or unload shared libraries in the darwin kernel");
1623 return error;
1624}
1625
1631
1635
1637 lldb_private::Debugger &debugger) {
1640 const bool is_global_setting = true;
1642 debugger, GetGlobalProperties().GetValueProperties(),
1643 "Properties for the DynamicLoaderDarwinKernel plug-in.",
1644 is_global_setting);
1645 }
1646}
1647
1649 return "Dynamic loader plug-in that watches for shared library loads/unloads "
1650 "in the MacOSX kernel.";
1651}
1652
1655 switch (magic) {
1656 case llvm::MachO::MH_MAGIC:
1657 case llvm::MachO::MH_MAGIC_64:
1658 return endian::InlHostByteOrder();
1659
1660 case llvm::MachO::MH_CIGAM:
1661 case llvm::MachO::MH_CIGAM_64:
1664 else
1665 return lldb::eByteOrderBig;
1666
1667 default:
1668 break;
1669 }
1671}
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:383
#define LLDB_LOG_ERROR(log, error,...)
Definition Log.h:399
#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:101
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:565
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:344
virtual ObjectFile * GetObjectFile()
Get the object file representation for the current architecture.
Definition Module.cpp:1184
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:462
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:2234
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:1902
lldb::ByteOrder GetByteOrder() const
Definition Process.cpp:3716
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:2594
virtual lldb::addr_t GetImageInfoAddress()
Get the image information address for the current process.
Definition Process.cpp:1450
void SetCanRunCode(bool can_run_code)
Sets whether executing code in this process is possible.
Definition Process.cpp:2561
uint32_t GetAddressByteSize() const
Definition Process.cpp:3720
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:559
size_t GetSize() const
Definition Section.h:77
lldb::SectionSP GetSectionAtIndex(size_t idx) const
Definition Section.cpp:552
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:313
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:1854
Module * GetExecutableModulePointer()
Definition Target.cpp:1541
Debugger & GetDebugger() const
Definition Target.h:1223
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:2347
bool SetArchitecture(const ArchSpec &arch_spec, bool set_platform=false, bool merge=true)
Set the architecture for this target.
Definition Target.cpp:1700
lldb::PlatformSP GetPlatform()
Definition Target.h:1677
const ModuleList & GetImages() const
Get accessor for the images for this process.
Definition Target.h:1140
const ArchSpec & GetArchitecture() const
Definition Target.h:1182
void SetPlatform(const lldb::PlatformSP &platform_sp)
Definition Target.h:1679
bool SetSectionLoadAddress(const lldb::SectionSP &section, lldb::addr_t load_addr, bool warn_multiple=false)
Definition Target.cpp:3339
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