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