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/Section.h"
17 #include "lldb/Interpreter/OptionValueProperties.h"
18 #include "lldb/Symbol/LocateSymbolFile.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/DataBuffer.h"
27 #include "lldb/Utility/DataBufferHeap.h"
28 #include "lldb/Utility/LLDBLog.h"
29 #include "lldb/Utility/Log.h"
30 #include "lldb/Utility/State.h"
32 #include "DynamicLoaderDarwinKernel.h"
37 //#define ENABLE_DEBUG_PRINTF // COMMENT THIS LINE OUT PRIOR TO CHECKIN
38 #ifdef ENABLE_DEBUG_PRINTF
40 #define DEBUG_PRINTF(fmt, ...) printf(fmt, ##__VA_ARGS__)
42 #define DEBUG_PRINTF(fmt, ...)
46 using namespace lldb_private
;
48 LLDB_PLUGIN_DEFINE(DynamicLoaderDarwinKernel
)
50 // Progressively greater amounts of scanning we will allow For some targets
51 // very early in startup, we can't do any random reads of memory or we can
52 // crash the device so a setting is needed that can completely disable the
56 eKASLRScanNone
= 0, // No reading into the inferior at all
57 eKASLRScanLowgloAddresses
, // Check one word of memory for a possible kernel
58 // addr, then see if a kernel is there
59 eKASLRScanNearPC
, // Scan backwards from the current $pc looking for kernel;
60 // checking at 96 locations total
61 eKASLRScanExhaustiveScan
// Scan through the entire possible kernel address
62 // range looking for a kernel
65 static constexpr OptionEnumValueElement g_kaslr_kernel_scan_enum_values
[] = {
69 "Do not read memory looking for a Darwin kernel when attaching.",
72 eKASLRScanLowgloAddresses
,
74 "Check for the Darwin kernel's load addr in the lowglo page "
75 "(boot-args=debug) only.",
80 "Scan near the pc value on attach to find the Darwin kernel's load "
84 eKASLRScanExhaustiveScan
,
86 "Scan through the entire potential address range of Darwin kernel "
87 "(only on 32-bit targets).",
91 #define LLDB_PROPERTIES_dynamicloaderdarwinkernel
92 #include "DynamicLoaderDarwinKernelProperties.inc"
95 #define LLDB_PROPERTIES_dynamicloaderdarwinkernel
96 #include "DynamicLoaderDarwinKernelPropertiesEnum.inc"
99 class DynamicLoaderDarwinKernelProperties
: public Properties
{
101 static llvm::StringRef
GetSettingName() {
102 static constexpr llvm::StringLiteral
g_setting_name("darwin-kernel");
103 return g_setting_name
;
106 DynamicLoaderDarwinKernelProperties() : Properties() {
107 m_collection_sp
= std::make_shared
<OptionValueProperties
>(GetSettingName());
108 m_collection_sp
->Initialize(g_dynamicloaderdarwinkernel_properties
);
111 ~DynamicLoaderDarwinKernelProperties() override
= default;
113 bool GetLoadKexts() const {
114 const uint32_t idx
= ePropertyLoadKexts
;
115 return GetPropertyAtIndexAs
<bool>(
117 g_dynamicloaderdarwinkernel_properties
[idx
].default_uint_value
!= 0);
120 KASLRScanType
GetScanType() const {
121 const uint32_t idx
= ePropertyScanType
;
122 return GetPropertyAtIndexAs
<KASLRScanType
>(
124 static_cast<KASLRScanType
>(
125 g_dynamicloaderdarwinkernel_properties
[idx
].default_uint_value
));
129 static DynamicLoaderDarwinKernelProperties
&GetGlobalProperties() {
130 static DynamicLoaderDarwinKernelProperties g_settings
;
134 static bool is_kernel(Module
*module
) {
137 ObjectFile
*objfile
= module
->GetObjectFile();
140 if (objfile
->GetType() != ObjectFile::eTypeExecutable
)
142 if (objfile
->GetStrata() != ObjectFile::eStrataKernel
)
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.
151 DynamicLoader
*DynamicLoaderDarwinKernel::CreateInstance(Process
*process
,
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
))
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
) {
175 // If we have triple like armv7-unknown-unknown, we should try looking for
177 case llvm::Triple::UnknownOS
:
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
);
196 DynamicLoaderDarwinKernel::SearchForDarwinKernel(Process
*process
) {
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
);
207 return kernel_load_address
;
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.
214 DynamicLoaderDarwinKernel::SearchForKernelAtSameLoadAddr(Process
*process
) {
215 Module
*exe_module
= process
->GetTarget().GetExecutableModulePointer();
217 if (!is_kernel(process
->GetTarget().GetExecutableModulePointer()))
218 return LLDB_INVALID_ADDRESS
;
220 ObjectFile
*exe_objfile
= exe_module
->GetObjectFile();
222 if (!exe_objfile
->GetBaseAddress().IsValid())
223 return LLDB_INVALID_ADDRESS
;
225 if (CheckForKernelImageAtAddress(
226 exe_objfile
->GetBaseAddress().GetFileAddress(), process
) ==
227 exe_module
->GetUUID())
228 return exe_objfile
->GetBaseAddress().GetFileAddress();
230 return LLDB_INVALID_ADDRESS
;
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.
237 DynamicLoaderDarwinKernel::SearchForKernelWithDebugHints(Process
*process
) {
238 if (GetGlobalProperties().GetScanType() == eKASLRScanNone
)
239 return LLDB_INVALID_ADDRESS
;
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
247 LLDB_INVALID_ADDRESS
};
248 addr_t kernel_addresses_32
[] = {0xffff0110, // 2016 and earlier armv7 devices
249 0xffff1010, LLDB_INVALID_ADDRESS
};
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)
256 DataExtractor
data (&uval
, 8, process
->GetByteOrder(), process
->GetAddressByteSize());
258 uint64_t addr
= data
.GetU64 (&offset
);
259 if (CheckForKernelImageAtAddress(addr
, process
).IsValid()) {
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)
270 DataExtractor
data (&uval
, 4, process
->GetByteOrder(), process
->GetAddressByteSize());
272 uint32_t addr
= data
.GetU32 (&offset
);
273 if (CheckForKernelImageAtAddress(addr
, process
).IsValid()) {
280 return LLDB_INVALID_ADDRESS
;
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.
289 DynamicLoaderDarwinKernel::SearchForKernelNearPC(Process
*process
) {
290 if (GetGlobalProperties().GetScanType() == eKASLRScanNone
||
291 GetGlobalProperties().GetScanType() == eKASLRScanLowgloAddresses
) {
292 return LLDB_INVALID_ADDRESS
;
295 ThreadSP thread
= process
->GetThreadList().GetSelectedThread();
296 if (thread
.get() == nullptr)
297 return LLDB_INVALID_ADDRESS
;
298 addr_t pc
= thread
->GetRegisterContext()->GetPC(LLDB_INVALID_ADDRESS
);
300 int ptrsize
= process
->GetTarget().GetArchitecture().GetAddressByteSize();
302 // The kernel is always loaded in high memory, if the top bit is zero,
303 // this isn't a kernel.
305 if ((pc
& (1ULL << 63)) == 0) {
306 return LLDB_INVALID_ADDRESS
;
309 if ((pc
& (1ULL << 31)) == 0) {
310 return LLDB_INVALID_ADDRESS
;
314 if (pc
== LLDB_INVALID_ADDRESS
)
315 return LLDB_INVALID_ADDRESS
;
317 int pagesize
= 0x4000; // 16k pages on 64-bit targets
319 pagesize
= 0x1000; // 4k pages on 32-bit targets
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);
325 // Search backwards for 128 megabytes, or first memory read error.
326 while (pc
- addr
< 128 * 0x100000) {
328 if (CheckForKernelImageAtAddress(addr
, process
, &read_error
).IsValid())
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)
339 return LLDB_INVALID_ADDRESS
;
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.
346 lldb::addr_t
DynamicLoaderDarwinKernel::SearchForKernelViaExhaustiveSearch(
348 if (GetGlobalProperties().GetScanType() != eKASLRScanExhaustiveScan
) {
349 return LLDB_INVALID_ADDRESS
;
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
;
357 kernel_range_low
= 1ULL << 31;
358 kernel_range_high
= UINT32_MAX
;
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)
366 return LLDB_INVALID_ADDRESS
;
368 addr_t addr
= kernel_range_low
;
370 while (addr
>= kernel_range_low
&& addr
< kernel_range_high
) {
371 // x86_64 kernels are at offset 0
372 if (CheckForKernelImageAtAddress(addr
, process
).IsValid())
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;
382 return LLDB_INVALID_ADDRESS
;
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
391 DynamicLoaderDarwinKernel::ReadMachHeader(addr_t addr
, Process
*process
, llvm::MachO::mach_header
&header
,
397 // Read the mach header and see whether it looks like a kernel
398 if (process
->ReadMemory(addr
, &header
, sizeof(header
), error
) !=
405 const uint32_t magicks
[] = { llvm::MachO::MH_MAGIC_64
, llvm::MachO::MH_MAGIC
, llvm::MachO::MH_CIGAM
, llvm::MachO::MH_CIGAM_64
};
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;
412 if (!found_matching_pattern
)
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
);
429 // Given an address in memory, look to see if there is a kernel image at that
431 // Returns a UUID; if a kernel was not found at that address, UUID.IsValid()
434 DynamicLoaderDarwinKernel::CheckForKernelImageAtAddress(lldb::addr_t addr
,
437 Log
*log
= GetLog(LLDBLog::DynamicLoader
);
438 if (addr
== LLDB_INVALID_ADDRESS
) {
445 "DynamicLoaderDarwinKernel::CheckForKernelImageAtAddress: "
446 "looking for kernel binary at 0x%" PRIx64
,
449 llvm::MachO::mach_header header
;
451 if (!ReadMachHeader(addr
, process
, header
, read_error
))
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
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())
467 ObjectFile
*exe_objfile
= memory_module_sp
->GetObjectFile();
468 if (exe_objfile
== nullptr) {
470 "DynamicLoaderDarwinKernel::CheckForKernelImageAtAddress "
471 "found a binary at 0x%" PRIx64
472 " but could not create an object file from memory",
477 if (is_kernel(memory_module_sp
.get())) {
478 ArchSpec
kernel_arch(eArchTypeMachO
, header
.cputype
, header
.cpusubtype
);
479 if (!process
->GetTarget().GetArchitecture().IsCompatibleMatch(
481 process
->GetTarget().SetArchitecture(kernel_arch
);
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();
489 uuid_str
= "and no LC_UUID found in load commands ";
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());
497 return memory_module_sp
->GetUUID();
505 DynamicLoaderDarwinKernel::DynamicLoaderDarwinKernel(Process
*process
,
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
=
514 process
->GetTarget().GetDebugger().GetPlatformList().Create(
515 PlatformDarwinKernel::GetPluginNameStatic());
516 if (platform_sp
.get())
517 process
->GetTarget().SetPlatform(platform_sp
);
521 DynamicLoaderDarwinKernel::~DynamicLoaderDarwinKernel() { Clear(true); }
523 void DynamicLoaderDarwinKernel::UpdateIfNeeded() {
524 LoadKernelModuleIfNeeded();
525 SetNotificationBreakpointIfNeeded();
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.
531 void DynamicLoaderDarwinKernel::DidAttach() {
532 PrivateInitialize(m_process
);
536 /// Called after attaching a process.
538 /// Allow DynamicLoader plug-ins to execute some code after
539 /// attaching to a process.
540 void DynamicLoaderDarwinKernel::DidLaunch() {
541 PrivateInitialize(m_process
);
545 // Clear out the state of this class.
546 void DynamicLoaderDarwinKernel::Clear(bool clear_process
) {
547 std::lock_guard
<std::recursive_mutex
> guard(m_mutex
);
549 if (m_process
->IsAlive() && LLDB_BREAK_ID_IS_VALID(m_break_id
))
550 m_process
->ClearBreakpointSiteByID(m_break_id
);
555 m_known_kexts
.clear();
556 m_kext_summary_header_ptr_addr
.Clear();
557 m_kext_summary_header_addr
.Clear();
558 m_break_id
= LLDB_INVALID_BREAK_ID
;
561 bool DynamicLoaderDarwinKernel::KextImageInfo::LoadImageAtFileAddress(
567 bool changed
= false;
568 if (m_module_sp
->SetLoadAddress(process
->GetTarget(), 0, true, changed
))
569 m_load_process_stop_id
= process
->GetStopID();
574 void DynamicLoaderDarwinKernel::KextImageInfo::SetModule(ModuleSP module_sp
) {
575 m_module_sp
= module_sp
;
576 m_kernel_image
= is_kernel(module_sp
.get());
579 ModuleSP
DynamicLoaderDarwinKernel::KextImageInfo::GetModule() {
583 void DynamicLoaderDarwinKernel::KextImageInfo::SetLoadAddress(
585 m_load_address
= load_addr
;
588 addr_t
DynamicLoaderDarwinKernel::KextImageInfo::GetLoadAddress() const {
589 return m_load_address
;
592 uint64_t DynamicLoaderDarwinKernel::KextImageInfo::GetSize() const {
596 void DynamicLoaderDarwinKernel::KextImageInfo::SetSize(uint64_t size
) {
600 uint32_t DynamicLoaderDarwinKernel::KextImageInfo::GetProcessStopId() const {
601 return m_load_process_stop_id
;
604 void DynamicLoaderDarwinKernel::KextImageInfo::SetProcessStopId(
606 m_load_process_stop_id
= stop_id
;
609 bool DynamicLoaderDarwinKernel::KextImageInfo::operator==(
610 const KextImageInfo
&rhs
) const {
611 if (m_uuid
.IsValid() || rhs
.GetUUID().IsValid()) {
612 return m_uuid
== rhs
.GetUUID();
615 return m_name
== rhs
.GetName() && m_load_address
== rhs
.GetLoadAddress();
618 void DynamicLoaderDarwinKernel::KextImageInfo::SetName(const char *name
) {
622 std::string
DynamicLoaderDarwinKernel::KextImageInfo::GetName() const {
626 void DynamicLoaderDarwinKernel::KextImageInfo::SetUUID(const UUID
&uuid
) {
630 UUID
DynamicLoaderDarwinKernel::KextImageInfo::GetUUID() const {
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.
638 // Returns true if m_memory_module_sp is now set to a valid Module.
640 bool DynamicLoaderDarwinKernel::KextImageInfo::ReadMemoryModule(
642 Log
*log
= GetLog(LLDBLog::Host
);
643 if (m_memory_module_sp
.get() != nullptr)
645 if (m_load_address
== LLDB_INVALID_ADDRESS
)
648 FileSpec
file_spec(m_name
.c_str());
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
;
660 ModuleSP memory_module_sp
=
661 process
->ReadModuleFromMemory(file_spec
, m_load_address
, size_to_read
);
663 if (memory_module_sp
.get() == nullptr)
666 bool this_is_kernel
= is_kernel(memory_module_sp
.get());
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()) {
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());
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();
690 m_memory_module_sp
= memory_module_sp
;
691 m_kernel_image
= this_is_kernel
;
692 if (this_is_kernel
) {
694 // This is unusual and probably not intended
696 "KextImageInfo::ReadMemoryModule read the kernel binary out "
699 if (memory_module_sp
->GetArchitecture().IsValid()) {
700 process
->GetTarget().SetArchitecture(memory_module_sp
->GetArchitecture());
707 bool DynamicLoaderDarwinKernel::KextImageInfo::IsKernel() const {
708 return m_kernel_image
;
711 void DynamicLoaderDarwinKernel::KextImageInfo::SetIsKernel(bool is_kernel
) {
712 m_kernel_image
= is_kernel
;
715 bool DynamicLoaderDarwinKernel::KextImageInfo::LoadImageUsingMemoryModule(
717 Log
*log
= GetLog(LLDBLog::DynamicLoader
);
721 Target
&target
= process
->GetTarget();
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
);
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
);
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
);
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
);
750 target
.GetImages().Remove(incorrect_kernels
);
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
);
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();
765 // If the current platform is PlatformDarwinKernel, create a ModuleSpec
766 // with the filename set to be the bundle ID for this kext, e.g.
767 // "com.apple.filesystems.msdosfs", and ask the platform to find it.
768 // PlatformDarwinKernel does a special scan for kexts on the local
770 PlatformSP
platform_sp(target
.GetPlatform());
772 static ConstString
g_platform_name(
773 PlatformDarwinKernel::GetPluginNameStatic());
774 if (platform_sp
->GetPluginName() == g_platform_name
.GetStringRef()) {
775 ModuleSpec
kext_bundle_module_spec(module_spec
);
776 FileSpec
kext_filespec(m_name
.c_str());
777 FileSpecList search_paths
= target
.GetExecutableSearchPaths();
778 kext_bundle_module_spec
.GetFileSpec() = kext_filespec
;
779 platform_sp
->GetSharedModule(kext_bundle_module_spec
, process
,
780 m_module_sp
, &search_paths
, nullptr,
785 // Ask the Target to find this file on the local system, if possible.
786 // This will search in the list of currently-loaded files, look in the
787 // standard search paths on the system, and on a Mac it will try calling
788 // the DebugSymbols framework with the UUID to find the binary via its
791 m_module_sp
= target
.GetOrCreateModule(module_spec
, true /* notify */);
794 // For the kernel, we really do need an on-disk file copy of the binary
795 // to do anything useful. This will force a call to dsymForUUID if it
796 // exists, instead of depending on the DebugSymbols preferences being
798 Status kernel_search_error
;
800 (!m_module_sp
|| !m_module_sp
->GetSymbolFileFileSpec())) {
801 if (Symbols::DownloadObjectAndSymbolFile(module_spec
,
802 kernel_search_error
, true)) {
803 if (FileSystem::Instance().Exists(module_spec
.GetFileSpec())) {
804 m_module_sp
= std::make_shared
<Module
>(module_spec
.GetFileSpec(),
805 target
.GetArchitecture());
810 if (IsKernel() && !m_module_sp
) {
811 Stream
&s
= target
.GetDebugger().GetErrorStream();
812 s
.Printf("WARNING: Unable to locate kernel binary on the debugger "
814 if (kernel_search_error
.Fail() && kernel_search_error
.AsCString("") &&
815 kernel_search_error
.AsCString("")[0] != '\0') {
816 s
<< kernel_search_error
.AsCString();
821 if (m_module_sp
&& m_uuid
.IsValid() && m_module_sp
->GetUUID() == m_uuid
&&
822 m_module_sp
->GetObjectFile()) {
823 if (ObjectFileMachO
*ondisk_objfile_macho
=
824 llvm::dyn_cast
<ObjectFileMachO
>(m_module_sp
->GetObjectFile())) {
825 if (!IsKernel() && !ondisk_objfile_macho
->IsKext()) {
826 // We have a non-kext, non-kernel binary. If we already have this
827 // loaded in the Target with load addresses, don't re-load it again.
828 ModuleSP existing_module_sp
= target
.GetImages().FindModule(m_uuid
);
829 if (existing_module_sp
&&
830 existing_module_sp
->IsLoadedInTarget(&target
)) {
832 "'%s' with UUID %s is not a kext or kernel, and is "
833 "already registered in target, not loading.",
834 m_name
.c_str(), m_uuid
.GetAsString().c_str());
835 // It's already loaded, return true.
842 // If we managed to find a module, append it to the target's list of
843 // images. If we also have a memory module, require that they have matching
846 if (m_uuid
.IsValid() && m_module_sp
->GetUUID() == m_uuid
) {
847 target
.GetImages().AppendIfNeeded(m_module_sp
, false);
852 // If we've found a binary, read the load commands out of memory so we
853 // can set the segment load addresses.
855 ReadMemoryModule (process
);
857 static ConstString
g_section_name_LINKEDIT("__LINKEDIT");
859 if (m_memory_module_sp
&& m_module_sp
) {
860 if (m_module_sp
->GetUUID() == m_memory_module_sp
->GetUUID()) {
861 ObjectFile
*ondisk_object_file
= m_module_sp
->GetObjectFile();
862 ObjectFile
*memory_object_file
= m_memory_module_sp
->GetObjectFile();
864 if (memory_object_file
&& ondisk_object_file
) {
865 // The memory_module for kexts may have an invalid __LINKEDIT seg; skip
867 const bool ignore_linkedit
= !IsKernel();
869 // Normally a kext will have its segment load commands
870 // (LC_SEGMENT vmaddrs) corrected in memory to have their
871 // actual segment addresses.
872 // Userland proceses have their libraries updated the same way
873 // by dyld. The Mach-O load commands in memory are the canonical
876 // If the kernel gives us a binary where the in-memory segment
877 // vmaddr is incorrect, then this binary was put in memory without
878 // updating its Mach-O load commands. We should assume a static
879 // slide value will be applied to every segment; we don't have the
880 // correct addresses for each individual segment.
881 addr_t fixed_slide
= LLDB_INVALID_ADDRESS
;
882 if (ObjectFileMachO
*memory_objfile_macho
=
883 llvm::dyn_cast
<ObjectFileMachO
>(memory_object_file
)) {
884 if (Section
*header_sect
=
885 memory_objfile_macho
->GetMachHeaderSection()) {
886 if (header_sect
->GetFileAddress() != m_load_address
) {
887 fixed_slide
= m_load_address
- header_sect
->GetFileAddress();
890 "kext %s in-memory LC_SEGMENT vmaddr is not correct, using a "
891 "fixed slide of 0x%" PRIx64
,
892 m_name
.c_str(), fixed_slide
);
897 SectionList
*ondisk_section_list
= ondisk_object_file
->GetSectionList();
898 SectionList
*memory_section_list
= memory_object_file
->GetSectionList();
899 if (memory_section_list
&& ondisk_section_list
) {
900 const uint32_t num_ondisk_sections
= ondisk_section_list
->GetSize();
901 // There may be CTF sections in the memory image so we can't always
902 // just compare the number of sections (which are actually segments
903 // in mach-o parlance)
904 uint32_t sect_idx
= 0;
906 // Use the memory_module's addresses for each section to set the file
907 // module's load address as appropriate. We don't want to use a
908 // single slide value for the entire kext - different segments may be
909 // slid different amounts by the kext loader.
911 uint32_t num_sections_loaded
= 0;
912 for (sect_idx
= 0; sect_idx
< num_ondisk_sections
; ++sect_idx
) {
913 SectionSP
ondisk_section_sp(
914 ondisk_section_list
->GetSectionAtIndex(sect_idx
));
915 if (ondisk_section_sp
) {
916 // Don't ever load __LINKEDIT as it may or may not be actually
917 // mapped into memory and there is no current way to tell. Until
918 // such an ability exists, do not load the __LINKEDIT.
919 if (ignore_linkedit
&&
920 ondisk_section_sp
->GetName() == g_section_name_LINKEDIT
)
923 if (fixed_slide
!= LLDB_INVALID_ADDRESS
) {
924 target
.SetSectionLoadAddress(
926 ondisk_section_sp
->GetFileAddress() + fixed_slide
);
928 const Section
*memory_section
=
930 ->FindSectionByName(ondisk_section_sp
->GetName())
932 if (memory_section
) {
933 target
.SetSectionLoadAddress(
934 ondisk_section_sp
, memory_section
->GetFileAddress());
935 ++num_sections_loaded
;
940 if (num_sections_loaded
> 0)
941 m_load_process_stop_id
= process
->GetStopID();
943 m_module_sp
.reset(); // No sections were loaded
945 m_module_sp
.reset(); // One or both section lists
947 m_module_sp
.reset(); // One or both object files missing
949 m_module_sp
.reset(); // UUID mismatch
952 bool is_loaded
= IsLoaded();
954 if (is_loaded
&& m_module_sp
&& IsKernel()) {
955 Stream
&s
= target
.GetDebugger().GetOutputStream();
956 ObjectFile
*kernel_object_file
= m_module_sp
->GetObjectFile();
957 if (kernel_object_file
) {
958 addr_t file_address
=
959 kernel_object_file
->GetBaseAddress().GetFileAddress();
960 if (m_load_address
!= LLDB_INVALID_ADDRESS
&&
961 file_address
!= LLDB_INVALID_ADDRESS
) {
962 s
.Printf("Kernel slid 0x%" PRIx64
" in memory.\n",
963 m_load_address
- file_address
);
967 s
.Printf("Loaded kernel file %s\n",
968 m_module_sp
->GetFileSpec().GetPath().c_str());
973 // Notify the target about the module being added;
974 // set breakpoints, load dSYM scripts, etc. as needed.
975 if (is_loaded
&& m_module_sp
) {
976 ModuleList loaded_module_list
;
977 loaded_module_list
.Append(m_module_sp
);
978 target
.ModulesDidLoad(loaded_module_list
);
984 uint32_t DynamicLoaderDarwinKernel::KextImageInfo::GetAddressByteSize() {
985 if (m_memory_module_sp
)
986 return m_memory_module_sp
->GetArchitecture().GetAddressByteSize();
988 return m_module_sp
->GetArchitecture().GetAddressByteSize();
992 lldb::ByteOrder
DynamicLoaderDarwinKernel::KextImageInfo::GetByteOrder() {
993 if (m_memory_module_sp
)
994 return m_memory_module_sp
->GetArchitecture().GetByteOrder();
996 return m_module_sp
->GetArchitecture().GetByteOrder();
997 return endian::InlHostByteOrder();
1000 lldb_private::ArchSpec
1001 DynamicLoaderDarwinKernel::KextImageInfo::GetArchitecture() const {
1002 if (m_memory_module_sp
)
1003 return m_memory_module_sp
->GetArchitecture();
1005 return m_module_sp
->GetArchitecture();
1006 return lldb_private::ArchSpec();
1009 // Load the kernel module and initialize the "m_kernel" member. Return true
1010 // _only_ if the kernel is loaded the first time through (subsequent calls to
1011 // this function should return false after the kernel has been already loaded).
1012 void DynamicLoaderDarwinKernel::LoadKernelModuleIfNeeded() {
1013 if (!m_kext_summary_header_ptr_addr
.IsValid()) {
1015 ModuleSP module_sp
= m_process
->GetTarget().GetExecutableModule();
1016 if (is_kernel(module_sp
.get())) {
1017 m_kernel
.SetModule(module_sp
);
1018 m_kernel
.SetIsKernel(true);
1021 ConstString
kernel_name("mach_kernel");
1022 if (m_kernel
.GetModule().get() && m_kernel
.GetModule()->GetObjectFile() &&
1023 !m_kernel
.GetModule()
1029 m_kernel
.GetModule()->GetObjectFile()->GetFileSpec().GetFilename();
1031 m_kernel
.SetName(kernel_name
.AsCString());
1033 if (m_kernel
.GetLoadAddress() == LLDB_INVALID_ADDRESS
) {
1034 m_kernel
.SetLoadAddress(m_kernel_load_address
);
1035 if (m_kernel
.GetLoadAddress() == LLDB_INVALID_ADDRESS
&&
1036 m_kernel
.GetModule()) {
1037 // We didn't get a hint from the process, so we will try the kernel at
1038 // the address that it exists at in the file if we have one
1039 ObjectFile
*kernel_object_file
= m_kernel
.GetModule()->GetObjectFile();
1040 if (kernel_object_file
) {
1041 addr_t load_address
=
1042 kernel_object_file
->GetBaseAddress().GetLoadAddress(
1043 &m_process
->GetTarget());
1044 addr_t file_address
=
1045 kernel_object_file
->GetBaseAddress().GetFileAddress();
1046 if (load_address
!= LLDB_INVALID_ADDRESS
&& load_address
!= 0) {
1047 m_kernel
.SetLoadAddress(load_address
);
1048 if (load_address
!= file_address
) {
1049 // Don't accidentally relocate the kernel to the File address --
1050 // the Load address has already been set to its actual in-memory
1051 // address. Mark it as IsLoaded.
1052 m_kernel
.SetProcessStopId(m_process
->GetStopID());
1055 m_kernel
.SetLoadAddress(file_address
);
1061 if (m_kernel
.GetLoadAddress() != LLDB_INVALID_ADDRESS
) {
1062 if (!m_kernel
.LoadImageUsingMemoryModule(m_process
)) {
1063 m_kernel
.LoadImageAtFileAddress(m_process
);
1067 // The operating system plugin gets loaded and initialized in
1068 // LoadImageUsingMemoryModule when we discover the kernel dSYM. For a core
1069 // file in particular, that's the wrong place to do this, since we haven't
1070 // fixed up the section addresses yet. So let's redo it here.
1071 LoadOperatingSystemPlugin(false);
1073 if (m_kernel
.IsLoaded() && m_kernel
.GetModule()) {
1074 static ConstString
kext_summary_symbol("gLoadedKextSummaries");
1075 static ConstString
arm64_T1Sz_value("gT1Sz");
1076 const Symbol
*symbol
=
1077 m_kernel
.GetModule()->FindFirstSymbolWithNameAndType(
1078 kext_summary_symbol
, eSymbolTypeData
);
1080 m_kext_summary_header_ptr_addr
= symbol
->GetAddress();
1081 // Update all image infos
1082 ReadAllKextSummaries();
1084 // If the kernel global with the T1Sz setting is available,
1085 // update the target.process.virtual-addressable-bits to be correct.
1086 // NB the xnu kernel always has T0Sz and T1Sz the same value. If
1087 // it wasn't the same, we would need to set
1088 // target.process.virtual-addressable-bits = T0Sz
1089 // target.process.highmem-virtual-addressable-bits = T1Sz
1090 symbol
= m_kernel
.GetModule()->FindFirstSymbolWithNameAndType(
1091 arm64_T1Sz_value
, eSymbolTypeData
);
1093 const addr_t orig_code_mask
= m_process
->GetCodeAddressMask();
1094 const addr_t orig_data_mask
= m_process
->GetDataAddressMask();
1096 m_process
->SetCodeAddressMask(0);
1097 m_process
->SetDataAddressMask(0);
1099 // gT1Sz is 8 bytes. We may run on a stripped kernel binary
1100 // where we can't get the size accurately. Hardcode it.
1101 const size_t sym_bytesize
= 8; // size of gT1Sz value
1102 uint64_t sym_value
=
1103 m_process
->GetTarget().ReadUnsignedIntegerFromMemory(
1104 symbol
->GetAddress(), sym_bytesize
, 0, error
);
1105 if (error
.Success()) {
1106 // 64 - T1Sz is the highest bit used for auth.
1107 // The value we pass in to SetVirtualAddressableBits is
1108 // the number of bits used for addressing, so if
1109 // T1Sz is 25, then 64-25 == 39, bits 0..38 are used for
1110 // addressing, bits 39..63 are used for PAC/TBI or whatever.
1111 uint32_t virt_addr_bits
= 64 - sym_value
;
1112 addr_t mask
= ~((1ULL << virt_addr_bits
) - 1);
1113 m_process
->SetCodeAddressMask(mask
);
1114 m_process
->SetDataAddressMask(mask
);
1116 m_process
->SetCodeAddressMask(orig_code_mask
);
1117 m_process
->SetDataAddressMask(orig_data_mask
);
1126 // Static callback function that gets called when our DYLD notification
1127 // breakpoint gets hit. We update all of our image infos and then let our super
1128 // class DynamicLoader class decide if we should stop or not (based on global
1130 bool DynamicLoaderDarwinKernel::BreakpointHitCallback(
1131 void *baton
, StoppointCallbackContext
*context
, user_id_t break_id
,
1132 user_id_t break_loc_id
) {
1133 return static_cast<DynamicLoaderDarwinKernel
*>(baton
)->BreakpointHit(
1134 context
, break_id
, break_loc_id
);
1137 bool DynamicLoaderDarwinKernel::BreakpointHit(StoppointCallbackContext
*context
,
1139 user_id_t break_loc_id
) {
1140 Log
*log
= GetLog(LLDBLog::DynamicLoader
);
1141 LLDB_LOGF(log
, "DynamicLoaderDarwinKernel::BreakpointHit (...)\n");
1143 ReadAllKextSummaries();
1148 return GetStopWhenImagesChange();
1151 bool DynamicLoaderDarwinKernel::ReadKextSummaryHeader() {
1152 std::lock_guard
<std::recursive_mutex
> guard(m_mutex
);
1154 // the all image infos is already valid for this process stop ID
1156 if (m_kext_summary_header_ptr_addr
.IsValid()) {
1157 const uint32_t addr_size
= m_kernel
.GetAddressByteSize();
1158 const ByteOrder byte_order
= m_kernel
.GetByteOrder();
1160 // Read enough bytes for a "OSKextLoadedKextSummaryHeader" structure which
1161 // is currently 4 uint32_t and a pointer.
1163 DataExtractor
data(buf
, sizeof(buf
), byte_order
, addr_size
);
1164 const size_t count
= 4 * sizeof(uint32_t) + addr_size
;
1165 const bool force_live_memory
= true;
1166 if (m_process
->GetTarget().ReadPointerFromMemory(
1167 m_kext_summary_header_ptr_addr
, error
,
1168 m_kext_summary_header_addr
, force_live_memory
)) {
1169 // We got a valid address for our kext summary header and make sure it
1171 if (m_kext_summary_header_addr
.IsValid() &&
1172 m_kext_summary_header_addr
.GetFileAddress() != 0) {
1173 const size_t bytes_read
= m_process
->GetTarget().ReadMemory(
1174 m_kext_summary_header_addr
, buf
, count
, error
, force_live_memory
);
1175 if (bytes_read
== count
) {
1176 lldb::offset_t offset
= 0;
1177 m_kext_summary_header
.version
= data
.GetU32(&offset
);
1178 if (m_kext_summary_header
.version
> 128) {
1179 Stream
&s
= m_process
->GetTarget().GetDebugger().GetOutputStream();
1180 s
.Printf("WARNING: Unable to read kext summary header, got "
1181 "improbable version number %u\n",
1182 m_kext_summary_header
.version
);
1183 // If we get an improbably large version number, we're probably
1184 // getting bad memory.
1185 m_kext_summary_header_addr
.Clear();
1188 if (m_kext_summary_header
.version
>= 2) {
1189 m_kext_summary_header
.entry_size
= data
.GetU32(&offset
);
1190 if (m_kext_summary_header
.entry_size
> 4096) {
1191 // If we get an improbably large entry_size, we're probably
1192 // getting bad memory.
1194 m_process
->GetTarget().GetDebugger().GetOutputStream();
1195 s
.Printf("WARNING: Unable to read kext summary header, got "
1196 "improbable entry_size %u\n",
1197 m_kext_summary_header
.entry_size
);
1198 m_kext_summary_header_addr
.Clear();
1202 // Versions less than 2 didn't have an entry size, it was hard
1204 m_kext_summary_header
.entry_size
=
1205 KERNEL_MODULE_ENTRY_SIZE_VERSION_1
;
1207 m_kext_summary_header
.entry_count
= data
.GetU32(&offset
);
1208 if (m_kext_summary_header
.entry_count
> 10000) {
1209 // If we get an improbably large number of kexts, we're probably
1210 // getting bad memory.
1211 Stream
&s
= m_process
->GetTarget().GetDebugger().GetOutputStream();
1212 s
.Printf("WARNING: Unable to read kext summary header, got "
1213 "improbable number of kexts %u\n",
1214 m_kext_summary_header
.entry_count
);
1215 m_kext_summary_header_addr
.Clear();
1223 m_kext_summary_header_addr
.Clear();
1227 // We've either (a) just attached to a new kernel, or (b) the kexts-changed
1228 // breakpoint was hit and we need to figure out what kexts have been added or
1229 // removed. Read the kext summaries from the inferior kernel memory, compare
1230 // them against the m_known_kexts vector and update the m_known_kexts vector as
1231 // needed to keep in sync with the inferior.
1233 bool DynamicLoaderDarwinKernel::ParseKextSummaries(
1234 const Address
&kext_summary_addr
, uint32_t count
) {
1235 KextImageInfo::collection kext_summaries
;
1236 Log
*log
= GetLog(LLDBLog::DynamicLoader
);
1238 "Kexts-changed breakpoint hit, there are %d kexts currently.\n",
1241 std::lock_guard
<std::recursive_mutex
> guard(m_mutex
);
1243 if (!ReadKextSummaries(kext_summary_addr
, count
, kext_summaries
))
1246 // read the plugin.dynamic-loader.darwin-kernel.load-kexts setting -- if the
1247 // user requested no kext loading, don't print any messages about kexts &
1248 // don't try to read them.
1249 const bool load_kexts
= GetGlobalProperties().GetLoadKexts();
1251 // By default, all kexts we've loaded in the past are marked as "remove" and
1252 // all of the kexts we just found out about from ReadKextSummaries are marked
1254 std::vector
<bool> to_be_removed(m_known_kexts
.size(), true);
1255 std::vector
<bool> to_be_added(count
, true);
1257 int number_of_new_kexts_being_added
= 0;
1258 int number_of_old_kexts_being_removed
= m_known_kexts
.size();
1260 const uint32_t new_kexts_size
= kext_summaries
.size();
1261 const uint32_t old_kexts_size
= m_known_kexts
.size();
1263 // The m_known_kexts vector may have entries that have been Cleared, or are a
1265 for (uint32_t old_kext
= 0; old_kext
< old_kexts_size
; old_kext
++) {
1266 bool ignore
= false;
1267 KextImageInfo
&image_info
= m_known_kexts
[old_kext
];
1268 if (image_info
.IsKernel()) {
1270 } else if (image_info
.GetLoadAddress() == LLDB_INVALID_ADDRESS
&&
1271 !image_info
.GetModule()) {
1276 number_of_old_kexts_being_removed
--;
1277 to_be_removed
[old_kext
] = false;
1281 // Scan over the list of kexts we just read from the kernel, note those that
1282 // need to be added and those already loaded.
1283 for (uint32_t new_kext
= 0; new_kext
< new_kexts_size
; new_kext
++) {
1284 bool add_this_one
= true;
1285 for (uint32_t old_kext
= 0; old_kext
< old_kexts_size
; old_kext
++) {
1286 if (m_known_kexts
[old_kext
] == kext_summaries
[new_kext
]) {
1287 // We already have this kext, don't re-load it.
1288 to_be_added
[new_kext
] = false;
1289 // This kext is still present, do not remove it.
1290 to_be_removed
[old_kext
] = false;
1292 number_of_old_kexts_being_removed
--;
1293 add_this_one
= false;
1297 // If this "kext" entry is actually an alias for the kernel -- the kext was
1298 // compiled into the kernel or something -- then we don't want to load the
1299 // kernel's text section at a different address. Ignore this kext entry.
1300 if (kext_summaries
[new_kext
].GetUUID().IsValid() &&
1301 m_kernel
.GetUUID().IsValid() &&
1302 kext_summaries
[new_kext
].GetUUID() == m_kernel
.GetUUID()) {
1303 to_be_added
[new_kext
] = false;
1307 number_of_new_kexts_being_added
++;
1311 if (number_of_new_kexts_being_added
== 0 &&
1312 number_of_old_kexts_being_removed
== 0)
1315 Stream
&s
= m_process
->GetTarget().GetDebugger().GetOutputStream();
1317 if (number_of_new_kexts_being_added
> 0 &&
1318 number_of_old_kexts_being_removed
> 0) {
1319 s
.Printf("Loading %d kext modules and unloading %d kext modules ",
1320 number_of_new_kexts_being_added
,
1321 number_of_old_kexts_being_removed
);
1322 } else if (number_of_new_kexts_being_added
> 0) {
1323 s
.Printf("Loading %d kext modules ", number_of_new_kexts_being_added
);
1324 } else if (number_of_old_kexts_being_removed
> 0) {
1325 s
.Printf("Unloading %d kext modules ", number_of_old_kexts_being_removed
);
1332 "DynamicLoaderDarwinKernel::ParseKextSummaries: %d kexts "
1333 "added, %d kexts removed",
1334 number_of_new_kexts_being_added
,
1335 number_of_old_kexts_being_removed
);
1338 "DynamicLoaderDarwinKernel::ParseKextSummaries kext loading is "
1339 "disabled, else would have %d kexts added, %d kexts removed",
1340 number_of_new_kexts_being_added
,
1341 number_of_old_kexts_being_removed
);
1345 // Build up a list of <kext-name, uuid> for any kexts that fail to load
1346 std::vector
<std::pair
<std::string
, UUID
>> kexts_failed_to_load
;
1347 if (number_of_new_kexts_being_added
> 0) {
1348 ModuleList loaded_module_list
;
1350 const uint32_t num_of_new_kexts
= kext_summaries
.size();
1351 for (uint32_t new_kext
= 0; new_kext
< num_of_new_kexts
; new_kext
++) {
1352 if (to_be_added
[new_kext
]) {
1353 KextImageInfo
&image_info
= kext_summaries
[new_kext
];
1354 bool kext_successfully_added
= true;
1356 if (!image_info
.LoadImageUsingMemoryModule(m_process
)) {
1357 kexts_failed_to_load
.push_back(std::pair
<std::string
, UUID
>(
1358 kext_summaries
[new_kext
].GetName(),
1359 kext_summaries
[new_kext
].GetUUID()));
1360 image_info
.LoadImageAtFileAddress(m_process
);
1361 kext_successfully_added
= false;
1365 m_known_kexts
.push_back(image_info
);
1367 if (image_info
.GetModule() &&
1368 m_process
->GetStopID() == image_info
.GetProcessStopId())
1369 loaded_module_list
.AppendIfNeeded(image_info
.GetModule());
1372 if (kext_successfully_added
)
1379 kext_summaries
[new_kext
].PutToLog(log
);
1382 m_process
->GetTarget().ModulesDidLoad(loaded_module_list
);
1385 if (number_of_old_kexts_being_removed
> 0) {
1386 ModuleList loaded_module_list
;
1387 const uint32_t num_of_old_kexts
= m_known_kexts
.size();
1388 for (uint32_t old_kext
= 0; old_kext
< num_of_old_kexts
; old_kext
++) {
1389 ModuleList unloaded_module_list
;
1390 if (to_be_removed
[old_kext
]) {
1391 KextImageInfo
&image_info
= m_known_kexts
[old_kext
];
1392 // You can't unload the kernel.
1393 if (!image_info
.IsKernel()) {
1394 if (image_info
.GetModule()) {
1395 unloaded_module_list
.AppendIfNeeded(image_info
.GetModule());
1399 // should pull it out of the KextImageInfos vector but that would
1400 // mutate the list and invalidate the to_be_removed bool vector;
1401 // leaving it in place once Cleared() is relatively harmless.
1404 m_process
->GetTarget().ModulesDidUnload(unloaded_module_list
, false);
1409 s
.Printf(" done.\n");
1410 if (kexts_failed_to_load
.size() > 0 && number_of_new_kexts_being_added
> 0) {
1411 s
.Printf("Failed to load %d of %d kexts:\n",
1412 (int)kexts_failed_to_load
.size(),
1413 number_of_new_kexts_being_added
);
1414 // print a sorted list of <kext-name, uuid> kexts which failed to load
1415 unsigned longest_name
= 0;
1416 std::sort(kexts_failed_to_load
.begin(), kexts_failed_to_load
.end());
1417 for (const auto &ku
: kexts_failed_to_load
) {
1418 if (ku
.first
.size() > longest_name
)
1419 longest_name
= ku
.first
.size();
1421 for (const auto &ku
: kexts_failed_to_load
) {
1423 if (ku
.second
.IsValid())
1424 uuid
= ku
.second
.GetAsString();
1425 s
.Printf(" %-*s %s\n", longest_name
, ku
.first
.c_str(), uuid
.c_str());
1434 uint32_t DynamicLoaderDarwinKernel::ReadKextSummaries(
1435 const Address
&kext_summary_addr
, uint32_t image_infos_count
,
1436 KextImageInfo::collection
&image_infos
) {
1437 const ByteOrder endian
= m_kernel
.GetByteOrder();
1438 const uint32_t addr_size
= m_kernel
.GetAddressByteSize();
1440 image_infos
.resize(image_infos_count
);
1441 const size_t count
= image_infos
.size() * m_kext_summary_header
.entry_size
;
1442 DataBufferHeap
data(count
, 0);
1445 const bool force_live_memory
= true;
1446 const size_t bytes_read
= m_process
->GetTarget().ReadMemory(
1447 kext_summary_addr
, data
.GetBytes(), data
.GetByteSize(), error
, force_live_memory
);
1448 if (bytes_read
== count
) {
1450 DataExtractor
extractor(data
.GetBytes(), data
.GetByteSize(), endian
,
1453 for (uint32_t kext_summary_offset
= 0;
1454 i
< image_infos
.size() &&
1455 extractor
.ValidOffsetForDataOfSize(kext_summary_offset
,
1456 m_kext_summary_header
.entry_size
);
1457 ++i
, kext_summary_offset
+= m_kext_summary_header
.entry_size
) {
1458 lldb::offset_t offset
= kext_summary_offset
;
1459 const void *name_data
=
1460 extractor
.GetData(&offset
, KERNEL_MODULE_MAX_NAME
);
1461 if (name_data
== nullptr)
1463 image_infos
[i
].SetName((const char *)name_data
);
1464 UUID
uuid(extractor
.GetData(&offset
, 16), 16);
1465 image_infos
[i
].SetUUID(uuid
);
1466 image_infos
[i
].SetLoadAddress(extractor
.GetU64(&offset
));
1467 image_infos
[i
].SetSize(extractor
.GetU64(&offset
));
1469 if (i
< image_infos
.size())
1470 image_infos
.resize(i
);
1472 image_infos
.clear();
1474 return image_infos
.size();
1477 bool DynamicLoaderDarwinKernel::ReadAllKextSummaries() {
1478 std::lock_guard
<std::recursive_mutex
> guard(m_mutex
);
1480 if (ReadKextSummaryHeader()) {
1481 if (m_kext_summary_header
.entry_count
> 0 &&
1482 m_kext_summary_header_addr
.IsValid()) {
1483 Address
summary_addr(m_kext_summary_header_addr
);
1484 summary_addr
.Slide(m_kext_summary_header
.GetSize());
1485 if (!ParseKextSummaries(summary_addr
,
1486 m_kext_summary_header
.entry_count
)) {
1487 m_known_kexts
.clear();
1495 // Dump an image info structure to the file handle provided.
1496 void DynamicLoaderDarwinKernel::KextImageInfo::PutToLog(Log
*log
) const {
1497 if (m_load_address
== LLDB_INVALID_ADDRESS
) {
1498 LLDB_LOG(log
, "uuid={0} name=\"{1}\" (UNLOADED)", m_uuid
.GetAsString(),
1501 LLDB_LOG(log
, "addr={0:x+16} size={1:x+16} uuid={2} name=\"{3}\"",
1502 m_load_address
, m_size
, m_uuid
.GetAsString(), m_name
);
1506 // Dump the _dyld_all_image_infos members and all current image infos that we
1507 // have parsed to the file handle provided.
1508 void DynamicLoaderDarwinKernel::PutToLog(Log
*log
) const {
1512 std::lock_guard
<std::recursive_mutex
> guard(m_mutex
);
1514 "gLoadedKextSummaries = 0x%16.16" PRIx64
1515 " { version=%u, entry_size=%u, entry_count=%u }",
1516 m_kext_summary_header_addr
.GetFileAddress(),
1517 m_kext_summary_header
.version
, m_kext_summary_header
.entry_size
,
1518 m_kext_summary_header
.entry_count
);
1521 const size_t count
= m_known_kexts
.size();
1523 log
->PutCString("Loaded:");
1524 for (i
= 0; i
< count
; i
++)
1525 m_known_kexts
[i
].PutToLog(log
);
1529 void DynamicLoaderDarwinKernel::PrivateInitialize(Process
*process
) {
1530 DEBUG_PRINTF("DynamicLoaderDarwinKernel::%s() process state = %s\n",
1531 __FUNCTION__
, StateAsCString(m_process
->GetState()));
1533 m_process
= process
;
1536 void DynamicLoaderDarwinKernel::SetNotificationBreakpointIfNeeded() {
1537 if (m_break_id
== LLDB_INVALID_BREAK_ID
&& m_kernel
.GetModule()) {
1538 DEBUG_PRINTF("DynamicLoaderDarwinKernel::%s() process state = %s\n",
1539 __FUNCTION__
, StateAsCString(m_process
->GetState()));
1541 const bool internal_bp
= true;
1542 const bool hardware
= false;
1543 const LazyBool skip_prologue
= eLazyBoolNo
;
1544 FileSpecList module_spec_list
;
1545 module_spec_list
.Append(m_kernel
.GetModule()->GetFileSpec());
1547 m_process
->GetTarget()
1548 .CreateBreakpoint(&module_spec_list
, nullptr,
1549 "OSKextLoadedKextSummariesUpdated",
1550 eFunctionNameTypeFull
, eLanguageTypeUnknown
, 0,
1551 skip_prologue
, internal_bp
, hardware
)
1554 bp
->SetCallback(DynamicLoaderDarwinKernel::BreakpointHitCallback
, this,
1556 m_break_id
= bp
->GetID();
1560 // Member function that gets called when the process state changes.
1561 void DynamicLoaderDarwinKernel::PrivateProcessStateChanged(Process
*process
,
1563 DEBUG_PRINTF("DynamicLoaderDarwinKernel::%s(%s)\n", __FUNCTION__
,
1564 StateAsCString(state
));
1566 case eStateConnected
:
1567 case eStateAttaching
:
1568 case eStateLaunching
:
1570 case eStateUnloaded
:
1572 case eStateDetached
:
1581 case eStateStepping
:
1583 case eStateSuspended
:
1589 DynamicLoaderDarwinKernel::GetStepThroughTrampolinePlan(Thread
&thread
,
1591 ThreadPlanSP thread_plan_sp
;
1592 Log
*log
= GetLog(LLDBLog::Step
);
1593 LLDB_LOGF(log
, "Could not find symbol for step through.");
1594 return thread_plan_sp
;
1597 Status
DynamicLoaderDarwinKernel::CanLoadImage() {
1599 error
.SetErrorString(
1600 "always unsafe to load or unload shared libraries in the darwin kernel");
1604 void DynamicLoaderDarwinKernel::Initialize() {
1605 PluginManager::RegisterPlugin(GetPluginNameStatic(),
1606 GetPluginDescriptionStatic(), CreateInstance
,
1607 DebuggerInitialize
);
1610 void DynamicLoaderDarwinKernel::Terminate() {
1611 PluginManager::UnregisterPlugin(CreateInstance
);
1614 void DynamicLoaderDarwinKernel::DebuggerInitialize(
1615 lldb_private::Debugger
&debugger
) {
1616 if (!PluginManager::GetSettingForDynamicLoaderPlugin(
1617 debugger
, DynamicLoaderDarwinKernelProperties::GetSettingName())) {
1618 const bool is_global_setting
= true;
1619 PluginManager::CreateSettingForDynamicLoaderPlugin(
1620 debugger
, GetGlobalProperties().GetValueProperties(),
1621 "Properties for the DynamicLoaderDarwinKernel plug-in.",
1626 llvm::StringRef
DynamicLoaderDarwinKernel::GetPluginDescriptionStatic() {
1627 return "Dynamic loader plug-in that watches for shared library loads/unloads "
1628 "in the MacOSX kernel.";
1632 DynamicLoaderDarwinKernel::GetByteOrderFromMagic(uint32_t magic
) {
1634 case llvm::MachO::MH_MAGIC
:
1635 case llvm::MachO::MH_MAGIC_64
:
1636 return endian::InlHostByteOrder();
1638 case llvm::MachO::MH_CIGAM
:
1639 case llvm::MachO::MH_CIGAM_64
:
1640 if (endian::InlHostByteOrder() == lldb::eByteOrderBig
)
1641 return lldb::eByteOrderLittle
;
1643 return lldb::eByteOrderBig
;
1648 return lldb::eByteOrderInvalid
;