1 //===-- DynamicLoaderDarwinKernel.cpp -------------------------------------===//
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
7 //===----------------------------------------------------------------------===//
9 #include "Plugins/ObjectFile/Mach-O/ObjectFileMachO.h"
10 #include "Plugins/Platform/MacOSX/PlatformDarwinKernel.h"
11 #include "lldb/Breakpoint/StoppointCallbackContext.h"
12 #include "lldb/Core/Debugger.h"
13 #include "lldb/Core/Module.h"
14 #include "lldb/Core/ModuleSpec.h"
15 #include "lldb/Core/PluginManager.h"
16 #include "lldb/Core/Progress.h"
17 #include "lldb/Core/Section.h"
18 #include "lldb/Interpreter/OptionValueProperties.h"
19 #include "lldb/Symbol/ObjectFile.h"
20 #include "lldb/Target/OperatingSystem.h"
21 #include "lldb/Target/RegisterContext.h"
22 #include "lldb/Target/StackFrame.h"
23 #include "lldb/Target/Target.h"
24 #include "lldb/Target/Thread.h"
25 #include "lldb/Target/ThreadPlanRunToAddress.h"
26 #include "lldb/Utility/AddressableBits.h"
27 #include "lldb/Utility/DataBuffer.h"
28 #include "lldb/Utility/DataBufferHeap.h"
29 #include "lldb/Utility/LLDBLog.h"
30 #include "lldb/Utility/Log.h"
31 #include "lldb/Utility/State.h"
33 #include "DynamicLoaderDarwinKernel.h"
38 //#define ENABLE_DEBUG_PRINTF // COMMENT THIS LINE OUT PRIOR TO CHECKIN
39 #ifdef ENABLE_DEBUG_PRINTF
41 #define DEBUG_PRINTF(fmt, ...) printf(fmt, ##__VA_ARGS__)
43 #define DEBUG_PRINTF(fmt, ...)
47 using namespace lldb_private
;
49 LLDB_PLUGIN_DEFINE(DynamicLoaderDarwinKernel
)
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
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
66 static constexpr OptionEnumValueElement g_kaslr_kernel_scan_enum_values
[] = {
70 "Do not read memory looking for a Darwin kernel when attaching.",
73 eKASLRScanLowgloAddresses
,
75 "Check for the Darwin kernel's load addr in the lowglo page "
76 "(boot-args=debug) only.",
81 "Scan near the pc value on attach to find the Darwin kernel's load "
85 eKASLRScanExhaustiveScan
,
87 "Scan through the entire potential address range of Darwin kernel "
88 "(only on 32-bit targets).",
92 #define LLDB_PROPERTIES_dynamicloaderdarwinkernel
93 #include "DynamicLoaderDarwinKernelProperties.inc"
96 #define LLDB_PROPERTIES_dynamicloaderdarwinkernel
97 #include "DynamicLoaderDarwinKernelPropertiesEnum.inc"
100 class DynamicLoaderDarwinKernelProperties
: public Properties
{
102 static llvm::StringRef
GetSettingName() {
103 static constexpr llvm::StringLiteral
g_setting_name("darwin-kernel");
104 return g_setting_name
;
107 DynamicLoaderDarwinKernelProperties() : Properties() {
108 m_collection_sp
= std::make_shared
<OptionValueProperties
>(GetSettingName());
109 m_collection_sp
->Initialize(g_dynamicloaderdarwinkernel_properties
);
112 ~DynamicLoaderDarwinKernelProperties() override
= default;
114 bool GetLoadKexts() const {
115 const uint32_t idx
= ePropertyLoadKexts
;
116 return GetPropertyAtIndexAs
<bool>(
118 g_dynamicloaderdarwinkernel_properties
[idx
].default_uint_value
!= 0);
121 KASLRScanType
GetScanType() const {
122 const uint32_t idx
= ePropertyScanType
;
123 return GetPropertyAtIndexAs
<KASLRScanType
>(
125 static_cast<KASLRScanType
>(
126 g_dynamicloaderdarwinkernel_properties
[idx
].default_uint_value
));
130 static DynamicLoaderDarwinKernelProperties
&GetGlobalProperties() {
131 static DynamicLoaderDarwinKernelProperties g_settings
;
135 static bool is_kernel(Module
*module
) {
138 ObjectFile
*objfile
= module
->GetObjectFile();
141 if (objfile
->GetType() != ObjectFile::eTypeExecutable
)
143 if (objfile
->GetStrata() != ObjectFile::eStrataKernel
)
149 // Create an instance of this class. This function is filled into the plugin
150 // info class that gets handed out by the plugin factory and allows the lldb to
151 // instantiate an instance of this class.
152 DynamicLoader
*DynamicLoaderDarwinKernel::CreateInstance(Process
*process
,
155 // If the user provided an executable binary and it is not a kernel, this
156 // plugin should not create an instance.
157 Module
*exec
= process
->GetTarget().GetExecutableModulePointer();
158 if (exec
&& !is_kernel(exec
))
161 // If the target's architecture does not look like an Apple environment,
162 // this plugin should not create an instance.
163 const llvm::Triple
&triple_ref
=
164 process
->GetTarget().GetArchitecture().GetTriple();
165 switch (triple_ref
.getOS()) {
166 case llvm::Triple::Darwin
:
167 case llvm::Triple::MacOSX
:
168 case llvm::Triple::IOS
:
169 case llvm::Triple::TvOS
:
170 case llvm::Triple::WatchOS
:
171 case llvm::Triple::XROS
:
172 case llvm::Triple::BridgeOS
:
173 if (triple_ref
.getVendor() != llvm::Triple::Apple
) {
177 // If we have triple like armv7-unknown-unknown, we should try looking for
179 case llvm::Triple::UnknownOS
:
187 // At this point if there is an ExecutableModule, it is a kernel and the
188 // Target is some variant of an Apple system. If the Process hasn't provided
189 // the kernel load address, we need to look around in memory to find it.
190 const addr_t kernel_load_address
= SearchForDarwinKernel(process
);
191 if (CheckForKernelImageAtAddress(kernel_load_address
, process
).IsValid()) {
192 return new DynamicLoaderDarwinKernel(process
, kernel_load_address
);
198 DynamicLoaderDarwinKernel::SearchForDarwinKernel(Process
*process
) {
199 addr_t kernel_load_address
= process
->GetImageInfoAddress();
200 if (kernel_load_address
== LLDB_INVALID_ADDRESS
)
201 kernel_load_address
= SearchForKernelAtSameLoadAddr(process
);
202 if (kernel_load_address
== LLDB_INVALID_ADDRESS
)
203 kernel_load_address
= SearchForKernelWithDebugHints(process
);
204 if (kernel_load_address
== LLDB_INVALID_ADDRESS
)
205 kernel_load_address
= SearchForKernelNearPC(process
);
206 if (kernel_load_address
== LLDB_INVALID_ADDRESS
)
207 kernel_load_address
= SearchForKernelViaExhaustiveSearch(process
);
209 return kernel_load_address
;
212 // Check if the kernel binary is loaded in memory without a slide. First verify
213 // that the ExecutableModule is a kernel before we proceed. Returns the address
214 // of the kernel if one was found, else LLDB_INVALID_ADDRESS.
216 DynamicLoaderDarwinKernel::SearchForKernelAtSameLoadAddr(Process
*process
) {
217 Module
*exe_module
= process
->GetTarget().GetExecutableModulePointer();
219 if (!is_kernel(process
->GetTarget().GetExecutableModulePointer()))
220 return LLDB_INVALID_ADDRESS
;
222 ObjectFile
*exe_objfile
= exe_module
->GetObjectFile();
224 if (!exe_objfile
->GetBaseAddress().IsValid())
225 return LLDB_INVALID_ADDRESS
;
227 if (CheckForKernelImageAtAddress(
228 exe_objfile
->GetBaseAddress().GetFileAddress(), process
) ==
229 exe_module
->GetUUID())
230 return exe_objfile
->GetBaseAddress().GetFileAddress();
232 return LLDB_INVALID_ADDRESS
;
235 // If the debug flag is included in the boot-args nvram setting, the kernel's
236 // load address will be noted in the lowglo page at a fixed address Returns the
237 // address of the kernel if one was found, else LLDB_INVALID_ADDRESS.
239 DynamicLoaderDarwinKernel::SearchForKernelWithDebugHints(Process
*process
) {
240 if (GetGlobalProperties().GetScanType() == eKASLRScanNone
)
241 return LLDB_INVALID_ADDRESS
;
244 addr_t kernel_addresses_64
[] = {
245 0xfffffff000002010ULL
,
246 0xfffffff000004010ULL
, // newest arm64 devices
247 0xffffff8000004010ULL
, // 2014-2015-ish arm64 devices
248 0xffffff8000002010ULL
, // oldest arm64 devices
249 LLDB_INVALID_ADDRESS
};
250 addr_t kernel_addresses_32
[] = {0xffff0110, // 2016 and earlier armv7 devices
251 0xffff1010, LLDB_INVALID_ADDRESS
};
254 if (process
->GetAddressByteSize() == 8) {
255 for (size_t i
= 0; kernel_addresses_64
[i
] != LLDB_INVALID_ADDRESS
; i
++) {
256 if (process
->ReadMemoryFromInferior (kernel_addresses_64
[i
], uval
, 8, read_err
) == 8)
258 DataExtractor
data (&uval
, 8, process
->GetByteOrder(), process
->GetAddressByteSize());
259 lldb::offset_t offset
= 0;
260 uint64_t addr
= data
.GetU64 (&offset
);
261 if (CheckForKernelImageAtAddress(addr
, process
).IsValid()) {
268 if (process
->GetAddressByteSize() == 4) {
269 for (size_t i
= 0; kernel_addresses_32
[i
] != LLDB_INVALID_ADDRESS
; i
++) {
270 if (process
->ReadMemoryFromInferior (kernel_addresses_32
[i
], uval
, 4, read_err
) == 4)
272 DataExtractor
data (&uval
, 4, process
->GetByteOrder(), process
->GetAddressByteSize());
273 lldb::offset_t offset
= 0;
274 uint32_t addr
= data
.GetU32 (&offset
);
275 if (CheckForKernelImageAtAddress(addr
, process
).IsValid()) {
282 return LLDB_INVALID_ADDRESS
;
285 // If the kernel is currently executing when lldb attaches, and we don't have a
286 // better way of finding the kernel's load address, try searching backwards
287 // from the current pc value looking for the kernel's Mach header in memory.
288 // Returns the address of the kernel if one was found, else
289 // LLDB_INVALID_ADDRESS.
291 DynamicLoaderDarwinKernel::SearchForKernelNearPC(Process
*process
) {
292 if (GetGlobalProperties().GetScanType() == eKASLRScanNone
||
293 GetGlobalProperties().GetScanType() == eKASLRScanLowgloAddresses
) {
294 return LLDB_INVALID_ADDRESS
;
297 ThreadSP thread
= process
->GetThreadList().GetSelectedThread();
298 if (thread
.get() == nullptr)
299 return LLDB_INVALID_ADDRESS
;
300 addr_t pc
= thread
->GetRegisterContext()->GetPC(LLDB_INVALID_ADDRESS
);
302 int ptrsize
= process
->GetTarget().GetArchitecture().GetAddressByteSize();
304 // The kernel is always loaded in high memory, if the top bit is zero,
305 // this isn't a kernel.
307 if ((pc
& (1ULL << 63)) == 0) {
308 return LLDB_INVALID_ADDRESS
;
311 if ((pc
& (1ULL << 31)) == 0) {
312 return LLDB_INVALID_ADDRESS
;
316 if (pc
== LLDB_INVALID_ADDRESS
)
317 return LLDB_INVALID_ADDRESS
;
319 int pagesize
= 0x4000; // 16k pages on 64-bit targets
321 pagesize
= 0x1000; // 4k pages on 32-bit targets
323 // The kernel will be loaded on a page boundary.
324 // Round the current pc down to the nearest page boundary.
325 addr_t addr
= pc
& ~(pagesize
- 1ULL);
327 // Search backwards for 128 megabytes, or first memory read error.
328 while (pc
- addr
< 128 * 0x100000) {
330 if (CheckForKernelImageAtAddress(addr
, process
, &read_error
).IsValid())
333 // Stop scanning on the first read error we encounter; we've walked
334 // past this executable block of memory.
335 if (read_error
== true)
341 return LLDB_INVALID_ADDRESS
;
344 // Scan through the valid address range for a kernel binary. This is uselessly
345 // slow in 64-bit environments so we don't even try it. This scan is not
346 // enabled by default even for 32-bit targets. Returns the address of the
347 // kernel if one was found, else LLDB_INVALID_ADDRESS.
348 lldb::addr_t
DynamicLoaderDarwinKernel::SearchForKernelViaExhaustiveSearch(
350 if (GetGlobalProperties().GetScanType() != eKASLRScanExhaustiveScan
) {
351 return LLDB_INVALID_ADDRESS
;
354 addr_t kernel_range_low
, kernel_range_high
;
355 if (process
->GetTarget().GetArchitecture().GetAddressByteSize() == 8) {
356 kernel_range_low
= 1ULL << 63;
357 kernel_range_high
= UINT64_MAX
;
359 kernel_range_low
= 1ULL << 31;
360 kernel_range_high
= UINT32_MAX
;
363 // Stepping through memory at one-megabyte resolution looking for a kernel
364 // rarely works (fast enough) with a 64-bit address space -- for now, let's
365 // not even bother. We may be attaching to something which *isn't* a kernel
366 // and we don't want to spin for minutes on-end looking for a kernel.
367 if (process
->GetTarget().GetArchitecture().GetAddressByteSize() == 8)
368 return LLDB_INVALID_ADDRESS
;
370 addr_t addr
= kernel_range_low
;
372 while (addr
>= kernel_range_low
&& addr
< kernel_range_high
) {
373 // x86_64 kernels are at offset 0
374 if (CheckForKernelImageAtAddress(addr
, process
).IsValid())
376 // 32-bit arm kernels are at offset 0x1000 (one 4k page)
377 if (CheckForKernelImageAtAddress(addr
+ 0x1000, process
).IsValid())
378 return addr
+ 0x1000;
379 // 64-bit arm kernels are at offset 0x4000 (one 16k page)
380 if (CheckForKernelImageAtAddress(addr
+ 0x4000, process
).IsValid())
381 return addr
+ 0x4000;
384 return LLDB_INVALID_ADDRESS
;
387 // Read the mach_header struct out of memory and return it.
388 // Returns true if the mach_header was successfully read,
389 // Returns false if there was a problem reading the header, or it was not
393 DynamicLoaderDarwinKernel::ReadMachHeader(addr_t addr
, Process
*process
, llvm::MachO::mach_header
&header
,
399 // Read the mach header and see whether it looks like a kernel
400 if (process
->ReadMemory(addr
, &header
, sizeof(header
), error
) !=
407 const uint32_t magicks
[] = { llvm::MachO::MH_MAGIC_64
, llvm::MachO::MH_MAGIC
, llvm::MachO::MH_CIGAM
, llvm::MachO::MH_CIGAM_64
};
409 bool found_matching_pattern
= false;
410 for (size_t i
= 0; i
< std::size(magicks
); i
++)
411 if (::memcmp (&header
.magic
, &magicks
[i
], sizeof (uint32_t)) == 0)
412 found_matching_pattern
= true;
414 if (!found_matching_pattern
)
417 if (header
.magic
== llvm::MachO::MH_CIGAM
||
418 header
.magic
== llvm::MachO::MH_CIGAM_64
) {
419 header
.magic
= llvm::byteswap
<uint32_t>(header
.magic
);
420 header
.cputype
= llvm::byteswap
<uint32_t>(header
.cputype
);
421 header
.cpusubtype
= llvm::byteswap
<uint32_t>(header
.cpusubtype
);
422 header
.filetype
= llvm::byteswap
<uint32_t>(header
.filetype
);
423 header
.ncmds
= llvm::byteswap
<uint32_t>(header
.ncmds
);
424 header
.sizeofcmds
= llvm::byteswap
<uint32_t>(header
.sizeofcmds
);
425 header
.flags
= llvm::byteswap
<uint32_t>(header
.flags
);
431 // Given an address in memory, look to see if there is a kernel image at that
433 // Returns a UUID; if a kernel was not found at that address, UUID.IsValid()
436 DynamicLoaderDarwinKernel::CheckForKernelImageAtAddress(lldb::addr_t addr
,
439 Log
*log
= GetLog(LLDBLog::DynamicLoader
);
440 if (addr
== LLDB_INVALID_ADDRESS
) {
447 "DynamicLoaderDarwinKernel::CheckForKernelImageAtAddress: "
448 "looking for kernel binary at 0x%" PRIx64
,
451 llvm::MachO::mach_header header
;
453 if (!ReadMachHeader(addr
, process
, header
, read_error
))
456 // First try a quick test -- read the first 4 bytes and see if there is a
457 // valid Mach-O magic field there
458 // (the first field of the mach_header/mach_header_64 struct).
459 // A kernel is an executable which does not have the dynamic link object flag
461 if (header
.filetype
== llvm::MachO::MH_EXECUTE
&&
462 (header
.flags
& llvm::MachO::MH_DYLDLINK
) == 0) {
463 // Create a full module to get the UUID
464 ModuleSP memory_module_sp
=
465 process
->ReadModuleFromMemory(FileSpec("temp_mach_kernel"), addr
);
466 if (!memory_module_sp
.get())
469 ObjectFile
*exe_objfile
= memory_module_sp
->GetObjectFile();
470 if (exe_objfile
== nullptr) {
472 "DynamicLoaderDarwinKernel::CheckForKernelImageAtAddress "
473 "found a binary at 0x%" PRIx64
474 " but could not create an object file from memory",
479 if (is_kernel(memory_module_sp
.get())) {
480 ArchSpec
kernel_arch(eArchTypeMachO
, header
.cputype
, header
.cpusubtype
);
481 if (!process
->GetTarget().GetArchitecture().IsCompatibleMatch(
483 process
->GetTarget().SetArchitecture(kernel_arch
);
486 std::string uuid_str
;
487 if (memory_module_sp
->GetUUID().IsValid()) {
488 uuid_str
= "with UUID ";
489 uuid_str
+= memory_module_sp
->GetUUID().GetAsString();
491 uuid_str
= "and no LC_UUID found in load commands ";
495 "DynamicLoaderDarwinKernel::CheckForKernelImageAtAddress: "
496 "kernel binary image found at 0x%" PRIx64
" with arch '%s' %s",
497 addr
, kernel_arch
.GetTriple().str().c_str(), uuid_str
.c_str());
499 return memory_module_sp
->GetUUID();
507 DynamicLoaderDarwinKernel::DynamicLoaderDarwinKernel(Process
*process
,
508 lldb::addr_t kernel_addr
)
509 : DynamicLoader(process
), m_kernel_load_address(kernel_addr
), m_kernel(),
510 m_kext_summary_header_ptr_addr(), m_kext_summary_header_addr(),
511 m_kext_summary_header(), m_known_kexts(), m_mutex(),
512 m_break_id(LLDB_INVALID_BREAK_ID
) {
514 process
->SetCanRunCode(false);
515 PlatformSP platform_sp
=
516 process
->GetTarget().GetDebugger().GetPlatformList().Create(
517 PlatformDarwinKernel::GetPluginNameStatic());
518 if (platform_sp
.get())
519 process
->GetTarget().SetPlatform(platform_sp
);
523 DynamicLoaderDarwinKernel::~DynamicLoaderDarwinKernel() { Clear(true); }
525 void DynamicLoaderDarwinKernel::UpdateIfNeeded() {
526 LoadKernelModuleIfNeeded();
527 SetNotificationBreakpointIfNeeded();
530 /// We've attached to a remote connection, or read a corefile.
531 /// Now load the kernel binary and potentially the kexts, add
532 /// them to the Target.
533 void DynamicLoaderDarwinKernel::DidAttach() {
534 PrivateInitialize(m_process
);
538 /// Called after attaching a process.
540 /// Allow DynamicLoader plug-ins to execute some code after
541 /// attaching to a process.
542 void DynamicLoaderDarwinKernel::DidLaunch() {
543 PrivateInitialize(m_process
);
547 // Clear out the state of this class.
548 void DynamicLoaderDarwinKernel::Clear(bool clear_process
) {
549 std::lock_guard
<std::recursive_mutex
> guard(m_mutex
);
551 if (m_process
->IsAlive() && LLDB_BREAK_ID_IS_VALID(m_break_id
))
552 m_process
->ClearBreakpointSiteByID(m_break_id
);
557 m_known_kexts
.clear();
558 m_kext_summary_header_ptr_addr
.Clear();
559 m_kext_summary_header_addr
.Clear();
560 m_break_id
= LLDB_INVALID_BREAK_ID
;
563 bool DynamicLoaderDarwinKernel::KextImageInfo::LoadImageAtFileAddress(
569 bool changed
= false;
570 if (m_module_sp
->SetLoadAddress(process
->GetTarget(), 0, true, changed
))
571 m_load_process_stop_id
= process
->GetStopID();
576 void DynamicLoaderDarwinKernel::KextImageInfo::SetModule(ModuleSP module_sp
) {
577 m_module_sp
= module_sp
;
578 m_kernel_image
= is_kernel(module_sp
.get());
581 ModuleSP
DynamicLoaderDarwinKernel::KextImageInfo::GetModule() {
585 void DynamicLoaderDarwinKernel::KextImageInfo::SetLoadAddress(
587 m_load_address
= load_addr
;
590 addr_t
DynamicLoaderDarwinKernel::KextImageInfo::GetLoadAddress() const {
591 return m_load_address
;
594 uint64_t DynamicLoaderDarwinKernel::KextImageInfo::GetSize() const {
598 void DynamicLoaderDarwinKernel::KextImageInfo::SetSize(uint64_t size
) {
602 uint32_t DynamicLoaderDarwinKernel::KextImageInfo::GetProcessStopId() const {
603 return m_load_process_stop_id
;
606 void DynamicLoaderDarwinKernel::KextImageInfo::SetProcessStopId(
608 m_load_process_stop_id
= stop_id
;
611 bool DynamicLoaderDarwinKernel::KextImageInfo::operator==(
612 const KextImageInfo
&rhs
) const {
613 if (m_uuid
.IsValid() || rhs
.GetUUID().IsValid()) {
614 return m_uuid
== rhs
.GetUUID();
617 return m_name
== rhs
.GetName() && m_load_address
== rhs
.GetLoadAddress();
620 void DynamicLoaderDarwinKernel::KextImageInfo::SetName(const char *name
) {
624 std::string
DynamicLoaderDarwinKernel::KextImageInfo::GetName() const {
628 void DynamicLoaderDarwinKernel::KextImageInfo::SetUUID(const UUID
&uuid
) {
632 UUID
DynamicLoaderDarwinKernel::KextImageInfo::GetUUID() const {
636 // Given the m_load_address from the kext summaries, and a UUID, try to create
637 // an in-memory Module at that address. Require that the MemoryModule have a
638 // matching UUID and detect if this MemoryModule is a kernel or a kext.
640 // Returns true if m_memory_module_sp is now set to a valid Module.
642 bool DynamicLoaderDarwinKernel::KextImageInfo::ReadMemoryModule(
644 Log
*log
= GetLog(LLDBLog::Host
);
645 if (m_memory_module_sp
.get() != nullptr)
647 if (m_load_address
== LLDB_INVALID_ADDRESS
)
650 FileSpec
file_spec(m_name
.c_str());
652 llvm::MachO::mach_header mh
;
653 size_t size_to_read
= 512;
654 if (ReadMachHeader(m_load_address
, process
, mh
)) {
655 if (mh
.magic
== llvm::MachO::MH_CIGAM
|| mh
.magic
== llvm::MachO::MH_MAGIC
)
656 size_to_read
= sizeof(llvm::MachO::mach_header
) + mh
.sizeofcmds
;
657 if (mh
.magic
== llvm::MachO::MH_CIGAM_64
||
658 mh
.magic
== llvm::MachO::MH_MAGIC_64
)
659 size_to_read
= sizeof(llvm::MachO::mach_header_64
) + mh
.sizeofcmds
;
662 ModuleSP memory_module_sp
=
663 process
->ReadModuleFromMemory(file_spec
, m_load_address
, size_to_read
);
665 if (memory_module_sp
.get() == nullptr)
668 bool this_is_kernel
= is_kernel(memory_module_sp
.get());
670 // If this is a kext, and the kernel specified what UUID we should find at
671 // this load address, require that the memory module have a matching UUID or
672 // something has gone wrong and we should discard it.
673 if (m_uuid
.IsValid()) {
674 if (m_uuid
!= memory_module_sp
->GetUUID()) {
677 "KextImageInfo::ReadMemoryModule the kernel said to find "
678 "uuid %s at 0x%" PRIx64
679 " but instead we found uuid %s, throwing it away",
680 m_uuid
.GetAsString().c_str(), m_load_address
,
681 memory_module_sp
->GetUUID().GetAsString().c_str());
687 // If the in-memory Module has a UUID, let's use that.
688 if (!m_uuid
.IsValid() && memory_module_sp
->GetUUID().IsValid()) {
689 m_uuid
= memory_module_sp
->GetUUID();
692 m_memory_module_sp
= memory_module_sp
;
693 m_kernel_image
= this_is_kernel
;
694 if (this_is_kernel
) {
696 // This is unusual and probably not intended
698 "KextImageInfo::ReadMemoryModule read the kernel binary out "
701 if (memory_module_sp
->GetArchitecture().IsValid()) {
702 process
->GetTarget().SetArchitecture(memory_module_sp
->GetArchitecture());
709 bool DynamicLoaderDarwinKernel::KextImageInfo::IsKernel() const {
710 return m_kernel_image
;
713 void DynamicLoaderDarwinKernel::KextImageInfo::SetIsKernel(bool is_kernel
) {
714 m_kernel_image
= is_kernel
;
717 bool DynamicLoaderDarwinKernel::KextImageInfo::LoadImageUsingMemoryModule(
718 Process
*process
, Progress
*progress
) {
719 Log
*log
= GetLog(LLDBLog::DynamicLoader
);
723 Target
&target
= process
->GetTarget();
725 // kexts will have a uuid from the table.
726 // for the kernel, we'll need to read the load commands out of memory to get it.
727 if (m_uuid
.IsValid() == false) {
728 if (ReadMemoryModule(process
) == false) {
729 Log
*log
= GetLog(LLDBLog::DynamicLoader
);
731 "Unable to read '%s' from memory at address 0x%" PRIx64
732 " to get the segment load addresses.",
733 m_name
.c_str(), m_load_address
);
738 if (IsKernel() && m_uuid
.IsValid()) {
739 Stream
&s
= target
.GetDebugger().GetOutputStream();
740 s
.Printf("Kernel UUID: %s\n", m_uuid
.GetAsString().c_str());
741 s
.Printf("Load Address: 0x%" PRIx64
"\n", m_load_address
);
743 // Start of a kernel debug session, we have the UUID of the kernel.
744 // Go through the target's list of modules and if there are any kernel
745 // modules with non-matching UUIDs, remove them. The user may have added
746 // the wrong kernel binary manually and it will only confuse things.
747 ModuleList incorrect_kernels
;
748 for (ModuleSP module_sp
: target
.GetImages().Modules()) {
749 if (is_kernel(module_sp
.get()) && module_sp
->GetUUID() != m_uuid
)
750 incorrect_kernels
.Append(module_sp
);
752 target
.GetImages().Remove(incorrect_kernels
);
756 // See if the kext has already been loaded into the target, probably by the
757 // user doing target modules add.
758 const ModuleList
&target_images
= target
.GetImages();
759 m_module_sp
= target_images
.FindModule(m_uuid
);
761 StreamString prog_str
;
762 // 'mach_kernel' is a fake name we make up to find kernels
763 // that were located by the local filesystem scan.
764 if (GetName() != "mach_kernel")
765 prog_str
<< GetName() << " ";
766 if (GetUUID().IsValid())
767 prog_str
<< GetUUID().GetAsString() << " ";
768 if (GetLoadAddress() != LLDB_INVALID_ADDRESS
) {
770 prog_str
.PutHex64(GetLoadAddress());
773 std::unique_ptr
<Progress
> progress_up
;
775 progress
->Increment(1, prog_str
.GetString().str());
778 progress_up
= std::make_unique
<Progress
>("Loading kernel",
779 prog_str
.GetString().str());
781 progress_up
= std::make_unique
<Progress
>("Loading kext",
782 prog_str
.GetString().str());
785 // Search for the kext on the local filesystem via the UUID
786 if (!m_module_sp
&& m_uuid
.IsValid()) {
787 ModuleSpec module_spec
;
788 module_spec
.GetUUID() = m_uuid
;
789 if (!m_uuid
.IsValid())
790 module_spec
.GetArchitecture() = target
.GetArchitecture();
791 module_spec
.GetFileSpec() = FileSpec(m_name
);
793 // If the current platform is PlatformDarwinKernel, create a ModuleSpec
794 // with the filename set to be the bundle ID for this kext, e.g.
795 // "com.apple.filesystems.msdosfs", and ask the platform to find it.
796 // PlatformDarwinKernel does a special scan for kexts on the local
798 PlatformSP
platform_sp(target
.GetPlatform());
800 FileSpecList search_paths
= target
.GetExecutableSearchPaths();
801 platform_sp
->GetSharedModule(module_spec
, process
, m_module_sp
,
802 &search_paths
, nullptr, nullptr);
805 // Ask the Target to find this file on the local system, if possible.
806 // This will search in the list of currently-loaded files, look in the
807 // standard search paths on the system, and on a Mac it will try calling
808 // the DebugSymbols framework with the UUID to find the binary via its
811 m_module_sp
= target
.GetOrCreateModule(module_spec
, true /* notify */);
814 // For the kernel, we really do need an on-disk file copy of the binary
815 // to do anything useful. This will force a call to dsymForUUID if it
816 // exists, instead of depending on the DebugSymbols preferences being
818 Status kernel_search_error
;
820 (!m_module_sp
|| !m_module_sp
->GetSymbolFileFileSpec())) {
821 if (PluginManager::DownloadObjectAndSymbolFile(
822 module_spec
, kernel_search_error
, true)) {
823 if (FileSystem::Instance().Exists(module_spec
.GetFileSpec())) {
824 m_module_sp
= std::make_shared
<Module
>(module_spec
.GetFileSpec(),
825 target
.GetArchitecture());
830 if (IsKernel() && !m_module_sp
) {
831 Stream
&s
= target
.GetDebugger().GetErrorStream();
832 s
.Printf("WARNING: Unable to locate kernel binary on the debugger "
834 if (kernel_search_error
.Fail() && kernel_search_error
.AsCString("") &&
835 kernel_search_error
.AsCString("")[0] != '\0') {
836 s
<< kernel_search_error
.AsCString();
841 if (m_module_sp
&& m_uuid
.IsValid() && m_module_sp
->GetUUID() == m_uuid
&&
842 m_module_sp
->GetObjectFile()) {
843 if (ObjectFileMachO
*ondisk_objfile_macho
=
844 llvm::dyn_cast
<ObjectFileMachO
>(m_module_sp
->GetObjectFile())) {
845 if (!IsKernel() && !ondisk_objfile_macho
->IsKext()) {
846 // We have a non-kext, non-kernel binary. If we already have this
847 // loaded in the Target with load addresses, don't re-load it again.
848 ModuleSP existing_module_sp
= target
.GetImages().FindModule(m_uuid
);
849 if (existing_module_sp
&&
850 existing_module_sp
->IsLoadedInTarget(&target
)) {
852 "'%s' with UUID %s is not a kext or kernel, and is "
853 "already registered in target, not loading.",
854 m_name
.c_str(), m_uuid
.GetAsString().c_str());
855 // It's already loaded, return true.
862 // If we managed to find a module, append it to the target's list of
863 // images. If we also have a memory module, require that they have matching
866 if (m_uuid
.IsValid() && m_module_sp
->GetUUID() == m_uuid
) {
867 target
.GetImages().AppendIfNeeded(m_module_sp
, false);
872 // If we've found a binary, read the load commands out of memory so we
873 // can set the segment load addresses.
875 ReadMemoryModule (process
);
877 static ConstString
g_section_name_LINKEDIT("__LINKEDIT");
879 if (m_memory_module_sp
&& m_module_sp
) {
880 if (m_module_sp
->GetUUID() == m_memory_module_sp
->GetUUID()) {
881 ObjectFile
*ondisk_object_file
= m_module_sp
->GetObjectFile();
882 ObjectFile
*memory_object_file
= m_memory_module_sp
->GetObjectFile();
884 if (memory_object_file
&& ondisk_object_file
) {
885 // The memory_module for kexts may have an invalid __LINKEDIT seg; skip
887 const bool ignore_linkedit
= !IsKernel();
889 // Normally a kext will have its segment load commands
890 // (LC_SEGMENT vmaddrs) corrected in memory to have their
891 // actual segment addresses.
892 // Userland proceses have their libraries updated the same way
893 // by dyld. The Mach-O load commands in memory are the canonical
896 // If the kernel gives us a binary where the in-memory segment
897 // vmaddr is incorrect, then this binary was put in memory without
898 // updating its Mach-O load commands. We should assume a static
899 // slide value will be applied to every segment; we don't have the
900 // correct addresses for each individual segment.
901 addr_t fixed_slide
= LLDB_INVALID_ADDRESS
;
902 if (ObjectFileMachO
*memory_objfile_macho
=
903 llvm::dyn_cast
<ObjectFileMachO
>(memory_object_file
)) {
904 if (Section
*header_sect
=
905 memory_objfile_macho
->GetMachHeaderSection()) {
906 if (header_sect
->GetFileAddress() != m_load_address
) {
907 fixed_slide
= m_load_address
- header_sect
->GetFileAddress();
910 "kext %s in-memory LC_SEGMENT vmaddr is not correct, using a "
911 "fixed slide of 0x%" PRIx64
,
912 m_name
.c_str(), fixed_slide
);
917 SectionList
*ondisk_section_list
= ondisk_object_file
->GetSectionList();
918 SectionList
*memory_section_list
= memory_object_file
->GetSectionList();
919 if (memory_section_list
&& ondisk_section_list
) {
920 const uint32_t num_ondisk_sections
= ondisk_section_list
->GetSize();
921 // There may be CTF sections in the memory image so we can't always
922 // just compare the number of sections (which are actually segments
923 // in mach-o parlance)
924 uint32_t sect_idx
= 0;
926 // Use the memory_module's addresses for each section to set the file
927 // module's load address as appropriate. We don't want to use a
928 // single slide value for the entire kext - different segments may be
929 // slid different amounts by the kext loader.
931 uint32_t num_sections_loaded
= 0;
932 for (sect_idx
= 0; sect_idx
< num_ondisk_sections
; ++sect_idx
) {
933 SectionSP
ondisk_section_sp(
934 ondisk_section_list
->GetSectionAtIndex(sect_idx
));
935 if (ondisk_section_sp
) {
936 // Don't ever load __LINKEDIT as it may or may not be actually
937 // mapped into memory and there is no current way to tell. Until
938 // such an ability exists, do not load the __LINKEDIT.
939 if (ignore_linkedit
&&
940 ondisk_section_sp
->GetName() == g_section_name_LINKEDIT
)
943 if (fixed_slide
!= LLDB_INVALID_ADDRESS
) {
944 target
.SetSectionLoadAddress(
946 ondisk_section_sp
->GetFileAddress() + fixed_slide
);
948 const Section
*memory_section
=
950 ->FindSectionByName(ondisk_section_sp
->GetName())
952 if (memory_section
) {
953 target
.SetSectionLoadAddress(
954 ondisk_section_sp
, memory_section
->GetFileAddress());
955 ++num_sections_loaded
;
960 if (num_sections_loaded
> 0)
961 m_load_process_stop_id
= process
->GetStopID();
963 m_module_sp
.reset(); // No sections were loaded
965 m_module_sp
.reset(); // One or both section lists
967 m_module_sp
.reset(); // One or both object files missing
969 m_module_sp
.reset(); // UUID mismatch
972 bool is_loaded
= IsLoaded();
974 if (is_loaded
&& m_module_sp
&& IsKernel()) {
975 Stream
&s
= target
.GetDebugger().GetOutputStream();
976 ObjectFile
*kernel_object_file
= m_module_sp
->GetObjectFile();
977 if (kernel_object_file
) {
978 addr_t file_address
=
979 kernel_object_file
->GetBaseAddress().GetFileAddress();
980 if (m_load_address
!= LLDB_INVALID_ADDRESS
&&
981 file_address
!= LLDB_INVALID_ADDRESS
) {
982 s
.Printf("Kernel slid 0x%" PRIx64
" in memory.\n",
983 m_load_address
- file_address
);
987 s
.Printf("Loaded kernel file %s\n",
988 m_module_sp
->GetFileSpec().GetPath().c_str());
993 // Notify the target about the module being added;
994 // set breakpoints, load dSYM scripts, etc. as needed.
995 if (is_loaded
&& m_module_sp
) {
996 ModuleList loaded_module_list
;
997 loaded_module_list
.Append(m_module_sp
);
998 target
.ModulesDidLoad(loaded_module_list
);
1004 uint32_t DynamicLoaderDarwinKernel::KextImageInfo::GetAddressByteSize() {
1005 if (m_memory_module_sp
)
1006 return m_memory_module_sp
->GetArchitecture().GetAddressByteSize();
1008 return m_module_sp
->GetArchitecture().GetAddressByteSize();
1012 lldb::ByteOrder
DynamicLoaderDarwinKernel::KextImageInfo::GetByteOrder() {
1013 if (m_memory_module_sp
)
1014 return m_memory_module_sp
->GetArchitecture().GetByteOrder();
1016 return m_module_sp
->GetArchitecture().GetByteOrder();
1017 return endian::InlHostByteOrder();
1020 lldb_private::ArchSpec
1021 DynamicLoaderDarwinKernel::KextImageInfo::GetArchitecture() const {
1022 if (m_memory_module_sp
)
1023 return m_memory_module_sp
->GetArchitecture();
1025 return m_module_sp
->GetArchitecture();
1026 return lldb_private::ArchSpec();
1029 // Load the kernel module and initialize the "m_kernel" member. Return true
1030 // _only_ if the kernel is loaded the first time through (subsequent calls to
1031 // this function should return false after the kernel has been already loaded).
1032 void DynamicLoaderDarwinKernel::LoadKernelModuleIfNeeded() {
1033 if (!m_kext_summary_header_ptr_addr
.IsValid()) {
1035 ModuleSP module_sp
= m_process
->GetTarget().GetExecutableModule();
1036 if (is_kernel(module_sp
.get())) {
1037 m_kernel
.SetModule(module_sp
);
1038 m_kernel
.SetIsKernel(true);
1041 ConstString
kernel_name("mach_kernel");
1042 if (m_kernel
.GetModule().get() && m_kernel
.GetModule()->GetObjectFile() &&
1043 !m_kernel
.GetModule()
1049 m_kernel
.GetModule()->GetObjectFile()->GetFileSpec().GetFilename();
1051 m_kernel
.SetName(kernel_name
.AsCString());
1053 if (m_kernel
.GetLoadAddress() == LLDB_INVALID_ADDRESS
) {
1054 m_kernel
.SetLoadAddress(m_kernel_load_address
);
1055 if (m_kernel
.GetLoadAddress() == LLDB_INVALID_ADDRESS
&&
1056 m_kernel
.GetModule()) {
1057 // We didn't get a hint from the process, so we will try the kernel at
1058 // the address that it exists at in the file if we have one
1059 ObjectFile
*kernel_object_file
= m_kernel
.GetModule()->GetObjectFile();
1060 if (kernel_object_file
) {
1061 addr_t load_address
=
1062 kernel_object_file
->GetBaseAddress().GetLoadAddress(
1063 &m_process
->GetTarget());
1064 addr_t file_address
=
1065 kernel_object_file
->GetBaseAddress().GetFileAddress();
1066 if (load_address
!= LLDB_INVALID_ADDRESS
&& load_address
!= 0) {
1067 m_kernel
.SetLoadAddress(load_address
);
1068 if (load_address
!= file_address
) {
1069 // Don't accidentally relocate the kernel to the File address --
1070 // the Load address has already been set to its actual in-memory
1071 // address. Mark it as IsLoaded.
1072 m_kernel
.SetProcessStopId(m_process
->GetStopID());
1075 m_kernel
.SetLoadAddress(file_address
);
1080 if (m_kernel
.GetLoadAddress() != LLDB_INVALID_ADDRESS
)
1081 if (!m_kernel
.LoadImageUsingMemoryModule(m_process
))
1082 m_kernel
.LoadImageAtFileAddress(m_process
);
1084 // The operating system plugin gets loaded and initialized in
1085 // LoadImageUsingMemoryModule when we discover the kernel dSYM. For a core
1086 // file in particular, that's the wrong place to do this, since we haven't
1087 // fixed up the section addresses yet. So let's redo it here.
1088 LoadOperatingSystemPlugin(false);
1090 if (m_kernel
.IsLoaded() && m_kernel
.GetModule()) {
1091 static ConstString
kext_summary_symbol("gLoadedKextSummaries");
1092 static ConstString
arm64_T1Sz_value("gT1Sz");
1093 const Symbol
*symbol
=
1094 m_kernel
.GetModule()->FindFirstSymbolWithNameAndType(
1095 kext_summary_symbol
, eSymbolTypeData
);
1097 m_kext_summary_header_ptr_addr
= symbol
->GetAddress();
1098 // Update all image infos
1099 ReadAllKextSummaries();
1101 // If the kernel global with the T1Sz setting is available,
1102 // update the target.process.virtual-addressable-bits to be correct.
1103 // NB the xnu kernel always has T0Sz and T1Sz the same value. If
1104 // it wasn't the same, we would need to set
1105 // target.process.virtual-addressable-bits = T0Sz
1106 // target.process.highmem-virtual-addressable-bits = T1Sz
1107 symbol
= m_kernel
.GetModule()->FindFirstSymbolWithNameAndType(
1108 arm64_T1Sz_value
, eSymbolTypeData
);
1110 const addr_t orig_code_mask
= m_process
->GetCodeAddressMask();
1111 const addr_t orig_data_mask
= m_process
->GetDataAddressMask();
1113 m_process
->SetCodeAddressMask(0);
1114 m_process
->SetDataAddressMask(0);
1116 // gT1Sz is 8 bytes. We may run on a stripped kernel binary
1117 // where we can't get the size accurately. Hardcode it.
1118 const size_t sym_bytesize
= 8; // size of gT1Sz value
1119 uint64_t sym_value
=
1120 m_process
->GetTarget().ReadUnsignedIntegerFromMemory(
1121 symbol
->GetAddress(), sym_bytesize
, 0, error
);
1122 if (error
.Success()) {
1123 // 64 - T1Sz is the highest bit used for auth.
1124 // The value we pass in to SetVirtualAddressableBits is
1125 // the number of bits used for addressing, so if
1126 // T1Sz is 25, then 64-25 == 39, bits 0..38 are used for
1127 // addressing, bits 39..63 are used for PAC/TBI or whatever.
1128 uint32_t virt_addr_bits
= 64 - sym_value
;
1129 addr_t mask
= AddressableBits::AddressableBitToMask(virt_addr_bits
);
1130 m_process
->SetCodeAddressMask(mask
);
1131 m_process
->SetDataAddressMask(mask
);
1133 m_process
->SetCodeAddressMask(orig_code_mask
);
1134 m_process
->SetDataAddressMask(orig_data_mask
);
1143 // Static callback function that gets called when our DYLD notification
1144 // breakpoint gets hit. We update all of our image infos and then let our super
1145 // class DynamicLoader class decide if we should stop or not (based on global
1147 bool DynamicLoaderDarwinKernel::BreakpointHitCallback(
1148 void *baton
, StoppointCallbackContext
*context
, user_id_t break_id
,
1149 user_id_t break_loc_id
) {
1150 return static_cast<DynamicLoaderDarwinKernel
*>(baton
)->BreakpointHit(
1151 context
, break_id
, break_loc_id
);
1154 bool DynamicLoaderDarwinKernel::BreakpointHit(StoppointCallbackContext
*context
,
1156 user_id_t break_loc_id
) {
1157 Log
*log
= GetLog(LLDBLog::DynamicLoader
);
1158 LLDB_LOGF(log
, "DynamicLoaderDarwinKernel::BreakpointHit (...)\n");
1160 ReadAllKextSummaries();
1165 return GetStopWhenImagesChange();
1168 bool DynamicLoaderDarwinKernel::ReadKextSummaryHeader() {
1169 std::lock_guard
<std::recursive_mutex
> guard(m_mutex
);
1171 // the all image infos is already valid for this process stop ID
1173 if (m_kext_summary_header_ptr_addr
.IsValid()) {
1174 const uint32_t addr_size
= m_kernel
.GetAddressByteSize();
1175 const ByteOrder byte_order
= m_kernel
.GetByteOrder();
1177 // Read enough bytes for a "OSKextLoadedKextSummaryHeader" structure which
1178 // is currently 4 uint32_t and a pointer.
1180 DataExtractor
data(buf
, sizeof(buf
), byte_order
, addr_size
);
1181 const size_t count
= 4 * sizeof(uint32_t) + addr_size
;
1182 const bool force_live_memory
= true;
1183 if (m_process
->GetTarget().ReadPointerFromMemory(
1184 m_kext_summary_header_ptr_addr
, error
,
1185 m_kext_summary_header_addr
, force_live_memory
)) {
1186 // We got a valid address for our kext summary header and make sure it
1188 if (m_kext_summary_header_addr
.IsValid() &&
1189 m_kext_summary_header_addr
.GetFileAddress() != 0) {
1190 const size_t bytes_read
= m_process
->GetTarget().ReadMemory(
1191 m_kext_summary_header_addr
, buf
, count
, error
, force_live_memory
);
1192 if (bytes_read
== count
) {
1193 lldb::offset_t offset
= 0;
1194 m_kext_summary_header
.version
= data
.GetU32(&offset
);
1195 if (m_kext_summary_header
.version
> 128) {
1196 Stream
&s
= m_process
->GetTarget().GetDebugger().GetOutputStream();
1197 s
.Printf("WARNING: Unable to read kext summary header, got "
1198 "improbable version number %u\n",
1199 m_kext_summary_header
.version
);
1200 // If we get an improbably large version number, we're probably
1201 // getting bad memory.
1202 m_kext_summary_header_addr
.Clear();
1205 if (m_kext_summary_header
.version
>= 2) {
1206 m_kext_summary_header
.entry_size
= data
.GetU32(&offset
);
1207 if (m_kext_summary_header
.entry_size
> 4096) {
1208 // If we get an improbably large entry_size, we're probably
1209 // getting bad memory.
1211 m_process
->GetTarget().GetDebugger().GetOutputStream();
1212 s
.Printf("WARNING: Unable to read kext summary header, got "
1213 "improbable entry_size %u\n",
1214 m_kext_summary_header
.entry_size
);
1215 m_kext_summary_header_addr
.Clear();
1219 // Versions less than 2 didn't have an entry size, it was hard
1221 m_kext_summary_header
.entry_size
=
1222 KERNEL_MODULE_ENTRY_SIZE_VERSION_1
;
1224 m_kext_summary_header
.entry_count
= data
.GetU32(&offset
);
1225 if (m_kext_summary_header
.entry_count
> 10000) {
1226 // If we get an improbably large number of kexts, we're probably
1227 // getting bad memory.
1228 Stream
&s
= m_process
->GetTarget().GetDebugger().GetOutputStream();
1229 s
.Printf("WARNING: Unable to read kext summary header, got "
1230 "improbable number of kexts %u\n",
1231 m_kext_summary_header
.entry_count
);
1232 m_kext_summary_header_addr
.Clear();
1240 m_kext_summary_header_addr
.Clear();
1244 // We've either (a) just attached to a new kernel, or (b) the kexts-changed
1245 // breakpoint was hit and we need to figure out what kexts have been added or
1246 // removed. Read the kext summaries from the inferior kernel memory, compare
1247 // them against the m_known_kexts vector and update the m_known_kexts vector as
1248 // needed to keep in sync with the inferior.
1250 bool DynamicLoaderDarwinKernel::ParseKextSummaries(
1251 const Address
&kext_summary_addr
, uint32_t count
) {
1252 KextImageInfo::collection kext_summaries
;
1253 Log
*log
= GetLog(LLDBLog::DynamicLoader
);
1255 "Kexts-changed breakpoint hit, there are %d kexts currently.\n",
1258 std::lock_guard
<std::recursive_mutex
> guard(m_mutex
);
1260 if (!ReadKextSummaries(kext_summary_addr
, count
, kext_summaries
))
1263 // read the plugin.dynamic-loader.darwin-kernel.load-kexts setting -- if the
1264 // user requested no kext loading, don't print any messages about kexts &
1265 // don't try to read them.
1266 const bool load_kexts
= GetGlobalProperties().GetLoadKexts();
1268 // By default, all kexts we've loaded in the past are marked as "remove" and
1269 // all of the kexts we just found out about from ReadKextSummaries are marked
1271 std::vector
<bool> to_be_removed(m_known_kexts
.size(), true);
1272 std::vector
<bool> to_be_added(count
, true);
1274 int number_of_new_kexts_being_added
= 0;
1275 int number_of_old_kexts_being_removed
= m_known_kexts
.size();
1277 const uint32_t new_kexts_size
= kext_summaries
.size();
1278 const uint32_t old_kexts_size
= m_known_kexts
.size();
1280 // The m_known_kexts vector may have entries that have been Cleared, or are a
1282 for (uint32_t old_kext
= 0; old_kext
< old_kexts_size
; old_kext
++) {
1283 bool ignore
= false;
1284 KextImageInfo
&image_info
= m_known_kexts
[old_kext
];
1285 if (image_info
.IsKernel()) {
1287 } else if (image_info
.GetLoadAddress() == LLDB_INVALID_ADDRESS
&&
1288 !image_info
.GetModule()) {
1293 number_of_old_kexts_being_removed
--;
1294 to_be_removed
[old_kext
] = false;
1298 // Scan over the list of kexts we just read from the kernel, note those that
1299 // need to be added and those already loaded.
1300 for (uint32_t new_kext
= 0; new_kext
< new_kexts_size
; new_kext
++) {
1301 bool add_this_one
= true;
1302 for (uint32_t old_kext
= 0; old_kext
< old_kexts_size
; old_kext
++) {
1303 if (m_known_kexts
[old_kext
] == kext_summaries
[new_kext
]) {
1304 // We already have this kext, don't re-load it.
1305 to_be_added
[new_kext
] = false;
1306 // This kext is still present, do not remove it.
1307 to_be_removed
[old_kext
] = false;
1309 number_of_old_kexts_being_removed
--;
1310 add_this_one
= false;
1314 // If this "kext" entry is actually an alias for the kernel -- the kext was
1315 // compiled into the kernel or something -- then we don't want to load the
1316 // kernel's text section at a different address. Ignore this kext entry.
1317 if (kext_summaries
[new_kext
].GetUUID().IsValid() &&
1318 m_kernel
.GetUUID().IsValid() &&
1319 kext_summaries
[new_kext
].GetUUID() == m_kernel
.GetUUID()) {
1320 to_be_added
[new_kext
] = false;
1324 number_of_new_kexts_being_added
++;
1328 if (number_of_new_kexts_being_added
== 0 &&
1329 number_of_old_kexts_being_removed
== 0)
1332 Stream
&s
= m_process
->GetTarget().GetDebugger().GetOutputStream();
1334 if (number_of_new_kexts_being_added
> 0 &&
1335 number_of_old_kexts_being_removed
> 0) {
1336 s
.Printf("Loading %d kext modules and unloading %d kext modules ",
1337 number_of_new_kexts_being_added
,
1338 number_of_old_kexts_being_removed
);
1339 } else if (number_of_new_kexts_being_added
> 0) {
1340 s
.Printf("Loading %d kext modules ", number_of_new_kexts_being_added
);
1341 } else if (number_of_old_kexts_being_removed
> 0) {
1342 s
.Printf("Unloading %d kext modules ", number_of_old_kexts_being_removed
);
1349 "DynamicLoaderDarwinKernel::ParseKextSummaries: %d kexts "
1350 "added, %d kexts removed",
1351 number_of_new_kexts_being_added
,
1352 number_of_old_kexts_being_removed
);
1355 "DynamicLoaderDarwinKernel::ParseKextSummaries kext loading is "
1356 "disabled, else would have %d kexts added, %d kexts removed",
1357 number_of_new_kexts_being_added
,
1358 number_of_old_kexts_being_removed
);
1362 // Build up a list of <kext-name, uuid> for any kexts that fail to load
1363 std::vector
<std::pair
<std::string
, UUID
>> kexts_failed_to_load
;
1364 if (number_of_new_kexts_being_added
> 0) {
1365 ModuleList loaded_module_list
;
1366 Progress
progress("Loading kext", "", number_of_new_kexts_being_added
);
1368 const uint32_t num_of_new_kexts
= kext_summaries
.size();
1369 for (uint32_t new_kext
= 0; new_kext
< num_of_new_kexts
; new_kext
++) {
1370 if (to_be_added
[new_kext
]) {
1371 KextImageInfo
&image_info
= kext_summaries
[new_kext
];
1373 if (!image_info
.LoadImageUsingMemoryModule(m_process
, &progress
)) {
1374 kexts_failed_to_load
.push_back(std::pair
<std::string
, UUID
>(
1375 kext_summaries
[new_kext
].GetName(),
1376 kext_summaries
[new_kext
].GetUUID()));
1377 image_info
.LoadImageAtFileAddress(m_process
);
1381 m_known_kexts
.push_back(image_info
);
1383 if (image_info
.GetModule() &&
1384 m_process
->GetStopID() == image_info
.GetProcessStopId())
1385 loaded_module_list
.AppendIfNeeded(image_info
.GetModule());
1388 kext_summaries
[new_kext
].PutToLog(log
);
1391 m_process
->GetTarget().ModulesDidLoad(loaded_module_list
);
1394 if (number_of_old_kexts_being_removed
> 0) {
1395 ModuleList loaded_module_list
;
1396 const uint32_t num_of_old_kexts
= m_known_kexts
.size();
1397 for (uint32_t old_kext
= 0; old_kext
< num_of_old_kexts
; old_kext
++) {
1398 ModuleList unloaded_module_list
;
1399 if (to_be_removed
[old_kext
]) {
1400 KextImageInfo
&image_info
= m_known_kexts
[old_kext
];
1401 // You can't unload the kernel.
1402 if (!image_info
.IsKernel()) {
1403 if (image_info
.GetModule()) {
1404 unloaded_module_list
.AppendIfNeeded(image_info
.GetModule());
1408 // should pull it out of the KextImageInfos vector but that would
1409 // mutate the list and invalidate the to_be_removed bool vector;
1410 // leaving it in place once Cleared() is relatively harmless.
1413 m_process
->GetTarget().ModulesDidUnload(unloaded_module_list
, false);
1418 s
.Printf(" done.\n");
1419 if (kexts_failed_to_load
.size() > 0 && number_of_new_kexts_being_added
> 0) {
1420 s
.Printf("Failed to load %d of %d kexts:\n",
1421 (int)kexts_failed_to_load
.size(),
1422 number_of_new_kexts_being_added
);
1423 // print a sorted list of <kext-name, uuid> kexts which failed to load
1424 unsigned longest_name
= 0;
1425 std::sort(kexts_failed_to_load
.begin(), kexts_failed_to_load
.end());
1426 for (const auto &ku
: kexts_failed_to_load
) {
1427 if (ku
.first
.size() > longest_name
)
1428 longest_name
= ku
.first
.size();
1430 for (const auto &ku
: kexts_failed_to_load
) {
1432 if (ku
.second
.IsValid())
1433 uuid
= ku
.second
.GetAsString();
1434 s
.Printf(" %-*s %s\n", longest_name
, ku
.first
.c_str(), uuid
.c_str());
1443 uint32_t DynamicLoaderDarwinKernel::ReadKextSummaries(
1444 const Address
&kext_summary_addr
, uint32_t image_infos_count
,
1445 KextImageInfo::collection
&image_infos
) {
1446 const ByteOrder endian
= m_kernel
.GetByteOrder();
1447 const uint32_t addr_size
= m_kernel
.GetAddressByteSize();
1449 image_infos
.resize(image_infos_count
);
1450 const size_t count
= image_infos
.size() * m_kext_summary_header
.entry_size
;
1451 DataBufferHeap
data(count
, 0);
1454 const bool force_live_memory
= true;
1455 const size_t bytes_read
= m_process
->GetTarget().ReadMemory(
1456 kext_summary_addr
, data
.GetBytes(), data
.GetByteSize(), error
, force_live_memory
);
1457 if (bytes_read
== count
) {
1459 DataExtractor
extractor(data
.GetBytes(), data
.GetByteSize(), endian
,
1462 for (uint32_t kext_summary_offset
= 0;
1463 i
< image_infos
.size() &&
1464 extractor
.ValidOffsetForDataOfSize(kext_summary_offset
,
1465 m_kext_summary_header
.entry_size
);
1466 ++i
, kext_summary_offset
+= m_kext_summary_header
.entry_size
) {
1467 lldb::offset_t offset
= kext_summary_offset
;
1468 const void *name_data
=
1469 extractor
.GetData(&offset
, KERNEL_MODULE_MAX_NAME
);
1470 if (name_data
== nullptr)
1472 image_infos
[i
].SetName((const char *)name_data
);
1473 UUID
uuid(extractor
.GetData(&offset
, 16), 16);
1474 image_infos
[i
].SetUUID(uuid
);
1475 image_infos
[i
].SetLoadAddress(extractor
.GetU64(&offset
));
1476 image_infos
[i
].SetSize(extractor
.GetU64(&offset
));
1478 if (i
< image_infos
.size())
1479 image_infos
.resize(i
);
1481 image_infos
.clear();
1483 return image_infos
.size();
1486 bool DynamicLoaderDarwinKernel::ReadAllKextSummaries() {
1487 std::lock_guard
<std::recursive_mutex
> guard(m_mutex
);
1489 if (ReadKextSummaryHeader()) {
1490 if (m_kext_summary_header
.entry_count
> 0 &&
1491 m_kext_summary_header_addr
.IsValid()) {
1492 Address
summary_addr(m_kext_summary_header_addr
);
1493 summary_addr
.Slide(m_kext_summary_header
.GetSize());
1494 if (!ParseKextSummaries(summary_addr
,
1495 m_kext_summary_header
.entry_count
)) {
1496 m_known_kexts
.clear();
1504 // Dump an image info structure to the file handle provided.
1505 void DynamicLoaderDarwinKernel::KextImageInfo::PutToLog(Log
*log
) const {
1506 if (m_load_address
== LLDB_INVALID_ADDRESS
) {
1507 LLDB_LOG(log
, "uuid={0} name=\"{1}\" (UNLOADED)", m_uuid
.GetAsString(),
1510 LLDB_LOG(log
, "addr={0:x+16} size={1:x+16} uuid={2} name=\"{3}\"",
1511 m_load_address
, m_size
, m_uuid
.GetAsString(), m_name
);
1515 // Dump the _dyld_all_image_infos members and all current image infos that we
1516 // have parsed to the file handle provided.
1517 void DynamicLoaderDarwinKernel::PutToLog(Log
*log
) const {
1521 std::lock_guard
<std::recursive_mutex
> guard(m_mutex
);
1523 "gLoadedKextSummaries = 0x%16.16" PRIx64
1524 " { version=%u, entry_size=%u, entry_count=%u }",
1525 m_kext_summary_header_addr
.GetFileAddress(),
1526 m_kext_summary_header
.version
, m_kext_summary_header
.entry_size
,
1527 m_kext_summary_header
.entry_count
);
1530 const size_t count
= m_known_kexts
.size();
1532 log
->PutCString("Loaded:");
1533 for (i
= 0; i
< count
; i
++)
1534 m_known_kexts
[i
].PutToLog(log
);
1538 void DynamicLoaderDarwinKernel::PrivateInitialize(Process
*process
) {
1539 DEBUG_PRINTF("DynamicLoaderDarwinKernel::%s() process state = %s\n",
1540 __FUNCTION__
, StateAsCString(m_process
->GetState()));
1542 m_process
= process
;
1545 void DynamicLoaderDarwinKernel::SetNotificationBreakpointIfNeeded() {
1546 if (m_break_id
== LLDB_INVALID_BREAK_ID
&& m_kernel
.GetModule()) {
1547 DEBUG_PRINTF("DynamicLoaderDarwinKernel::%s() process state = %s\n",
1548 __FUNCTION__
, StateAsCString(m_process
->GetState()));
1550 const bool internal_bp
= true;
1551 const bool hardware
= false;
1552 const LazyBool skip_prologue
= eLazyBoolNo
;
1553 FileSpecList module_spec_list
;
1554 module_spec_list
.Append(m_kernel
.GetModule()->GetFileSpec());
1556 m_process
->GetTarget()
1557 .CreateBreakpoint(&module_spec_list
, nullptr,
1558 "OSKextLoadedKextSummariesUpdated",
1559 eFunctionNameTypeFull
, eLanguageTypeUnknown
, 0,
1560 skip_prologue
, internal_bp
, hardware
)
1563 bp
->SetCallback(DynamicLoaderDarwinKernel::BreakpointHitCallback
, this,
1565 m_break_id
= bp
->GetID();
1569 // Member function that gets called when the process state changes.
1570 void DynamicLoaderDarwinKernel::PrivateProcessStateChanged(Process
*process
,
1572 DEBUG_PRINTF("DynamicLoaderDarwinKernel::%s(%s)\n", __FUNCTION__
,
1573 StateAsCString(state
));
1575 case eStateConnected
:
1576 case eStateAttaching
:
1577 case eStateLaunching
:
1579 case eStateUnloaded
:
1581 case eStateDetached
:
1590 case eStateStepping
:
1592 case eStateSuspended
:
1598 DynamicLoaderDarwinKernel::GetStepThroughTrampolinePlan(Thread
&thread
,
1600 ThreadPlanSP thread_plan_sp
;
1601 Log
*log
= GetLog(LLDBLog::Step
);
1602 LLDB_LOGF(log
, "Could not find symbol for step through.");
1603 return thread_plan_sp
;
1606 Status
DynamicLoaderDarwinKernel::CanLoadImage() {
1608 error
= Status::FromErrorString(
1609 "always unsafe to load or unload shared libraries in the darwin kernel");
1613 void DynamicLoaderDarwinKernel::Initialize() {
1614 PluginManager::RegisterPlugin(GetPluginNameStatic(),
1615 GetPluginDescriptionStatic(), CreateInstance
,
1616 DebuggerInitialize
);
1619 void DynamicLoaderDarwinKernel::Terminate() {
1620 PluginManager::UnregisterPlugin(CreateInstance
);
1623 void DynamicLoaderDarwinKernel::DebuggerInitialize(
1624 lldb_private::Debugger
&debugger
) {
1625 if (!PluginManager::GetSettingForDynamicLoaderPlugin(
1626 debugger
, DynamicLoaderDarwinKernelProperties::GetSettingName())) {
1627 const bool is_global_setting
= true;
1628 PluginManager::CreateSettingForDynamicLoaderPlugin(
1629 debugger
, GetGlobalProperties().GetValueProperties(),
1630 "Properties for the DynamicLoaderDarwinKernel plug-in.",
1635 llvm::StringRef
DynamicLoaderDarwinKernel::GetPluginDescriptionStatic() {
1636 return "Dynamic loader plug-in that watches for shared library loads/unloads "
1637 "in the MacOSX kernel.";
1641 DynamicLoaderDarwinKernel::GetByteOrderFromMagic(uint32_t magic
) {
1643 case llvm::MachO::MH_MAGIC
:
1644 case llvm::MachO::MH_MAGIC_64
:
1645 return endian::InlHostByteOrder();
1647 case llvm::MachO::MH_CIGAM
:
1648 case llvm::MachO::MH_CIGAM_64
:
1649 if (endian::InlHostByteOrder() == lldb::eByteOrderBig
)
1650 return lldb::eByteOrderLittle
;
1652 return lldb::eByteOrderBig
;
1657 return lldb::eByteOrderInvalid
;