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