xref: /llvm-project/lldb/source/Plugins/DynamicLoader/Darwin-Kernel/DynamicLoaderDarwinKernel.cpp (revision 0642cd768b80665585c8500bed2933a3b99123dc)
1 //===-- DynamicLoaderDarwinKernel.cpp -------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
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"
32 
33 #include "DynamicLoaderDarwinKernel.h"
34 
35 #include <algorithm>
36 #include <memory>
37 
38 //#define ENABLE_DEBUG_PRINTF // COMMENT THIS LINE OUT PRIOR TO CHECKIN
39 #ifdef ENABLE_DEBUG_PRINTF
40 #include <cstdio>
41 #define DEBUG_PRINTF(fmt, ...) printf(fmt, ##__VA_ARGS__)
42 #else
43 #define DEBUG_PRINTF(fmt, ...)
44 #endif
45 
46 using namespace lldb;
47 using namespace lldb_private;
48 
49 LLDB_PLUGIN_DEFINE(DynamicLoaderDarwinKernel)
50 
51 // Progressively greater amounts of scanning we will allow For some targets
52 // very early in startup, we can't do any random reads of memory or we can
53 // crash the device so a setting is needed that can completely disable the
54 // KASLR scans.
55 
56 enum KASLRScanType {
57   eKASLRScanNone = 0,        // No reading into the inferior at all
58   eKASLRScanLowgloAddresses, // Check one word of memory for a possible kernel
59                              // addr, then see if a kernel is there
60   eKASLRScanNearPC, // Scan backwards from the current $pc looking for kernel;
61                     // checking at 96 locations total
62   eKASLRScanExhaustiveScan // Scan through the entire possible kernel address
63                            // range looking for a kernel
64 };
65 
66 static constexpr OptionEnumValueElement g_kaslr_kernel_scan_enum_values[] = {
67     {
68         eKASLRScanNone,
69         "none",
70         "Do not read memory looking for a Darwin kernel when attaching.",
71     },
72     {
73         eKASLRScanLowgloAddresses,
74         "basic",
75         "Check for the Darwin kernel's load addr in the lowglo page "
76         "(boot-args=debug) only.",
77     },
78     {
79         eKASLRScanNearPC,
80         "fast-scan",
81         "Scan near the pc value on attach to find the Darwin kernel's load "
82         "address.",
83     },
84     {
85         eKASLRScanExhaustiveScan,
86         "exhaustive-scan",
87         "Scan through the entire potential address range of Darwin kernel "
88         "(only on 32-bit targets).",
89     },
90 };
91 
92 #define LLDB_PROPERTIES_dynamicloaderdarwinkernel
93 #include "DynamicLoaderDarwinKernelProperties.inc"
94 
95 enum {
96 #define LLDB_PROPERTIES_dynamicloaderdarwinkernel
97 #include "DynamicLoaderDarwinKernelPropertiesEnum.inc"
98 };
99 
100 class DynamicLoaderDarwinKernelProperties : public Properties {
101 public:
102   static llvm::StringRef GetSettingName() {
103     static constexpr llvm::StringLiteral g_setting_name("darwin-kernel");
104     return g_setting_name;
105   }
106 
107   DynamicLoaderDarwinKernelProperties() : Properties() {
108     m_collection_sp = std::make_shared<OptionValueProperties>(GetSettingName());
109     m_collection_sp->Initialize(g_dynamicloaderdarwinkernel_properties);
110   }
111 
112   ~DynamicLoaderDarwinKernelProperties() override = default;
113 
114   bool GetLoadKexts() const {
115     const uint32_t idx = ePropertyLoadKexts;
116     return GetPropertyAtIndexAs<bool>(
117         idx,
118         g_dynamicloaderdarwinkernel_properties[idx].default_uint_value != 0);
119   }
120 
121   KASLRScanType GetScanType() const {
122     const uint32_t idx = ePropertyScanType;
123     return GetPropertyAtIndexAs<KASLRScanType>(
124         idx,
125         static_cast<KASLRScanType>(
126             g_dynamicloaderdarwinkernel_properties[idx].default_uint_value));
127   }
128 };
129 
130 static DynamicLoaderDarwinKernelProperties &GetGlobalProperties() {
131   static DynamicLoaderDarwinKernelProperties g_settings;
132   return g_settings;
133 }
134 
135 static bool is_kernel(Module *module) {
136   if (!module)
137     return false;
138   ObjectFile *objfile = module->GetObjectFile();
139   if (!objfile)
140     return false;
141   if (objfile->GetType() != ObjectFile::eTypeExecutable)
142     return false;
143   if (objfile->GetStrata() != ObjectFile::eStrataKernel)
144     return false;
145 
146   return true;
147 }
148 
149 // Create an instance of this class. This function is filled into the plugin
150 // info class that gets handed out by the plugin factory and allows the lldb to
151 // instantiate an instance of this class.
152 DynamicLoader *DynamicLoaderDarwinKernel::CreateInstance(Process *process,
153                                                          bool force) {
154   if (!force) {
155     // If the user provided an executable binary and it is not a kernel, this
156     // plugin should not create an instance.
157     Module *exec = process->GetTarget().GetExecutableModulePointer();
158     if (exec && !is_kernel(exec))
159       return nullptr;
160 
161     // If the target's architecture does not look like an Apple environment,
162     // this plugin should not create an instance.
163     const llvm::Triple &triple_ref =
164         process->GetTarget().GetArchitecture().GetTriple();
165     switch (triple_ref.getOS()) {
166     case llvm::Triple::Darwin:
167     case llvm::Triple::MacOSX:
168     case llvm::Triple::IOS:
169     case llvm::Triple::TvOS:
170     case llvm::Triple::WatchOS:
171     case llvm::Triple::XROS:
172     case llvm::Triple::BridgeOS:
173       if (triple_ref.getVendor() != llvm::Triple::Apple) {
174         return nullptr;
175       }
176       break;
177     // If we have triple like armv7-unknown-unknown, we should try looking for
178     // a Darwin kernel.
179     case llvm::Triple::UnknownOS:
180       break;
181     default:
182       return nullptr;
183       break;
184     }
185   }
186 
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);
193   }
194   return nullptr;
195 }
196 
197 lldb::addr_t
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);
208 
209   return kernel_load_address;
210 }
211 
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.
215 lldb::addr_t
216 DynamicLoaderDarwinKernel::SearchForKernelAtSameLoadAddr(Process *process) {
217   Module *exe_module = process->GetTarget().GetExecutableModulePointer();
218 
219   if (!is_kernel(process->GetTarget().GetExecutableModulePointer()))
220     return LLDB_INVALID_ADDRESS;
221 
222   ObjectFile *exe_objfile = exe_module->GetObjectFile();
223 
224   if (!exe_objfile->GetBaseAddress().IsValid())
225     return LLDB_INVALID_ADDRESS;
226 
227   if (CheckForKernelImageAtAddress(
228           exe_objfile->GetBaseAddress().GetFileAddress(), process) ==
229       exe_module->GetUUID())
230     return exe_objfile->GetBaseAddress().GetFileAddress();
231 
232   return LLDB_INVALID_ADDRESS;
233 }
234 
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.
238 lldb::addr_t
239 DynamicLoaderDarwinKernel::SearchForKernelWithDebugHints(Process *process) {
240   if (GetGlobalProperties().GetScanType() == eKASLRScanNone)
241     return LLDB_INVALID_ADDRESS;
242 
243   Status read_err;
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};
252 
253   uint8_t uval[8];
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)
257       {
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()) {
262               return addr;
263           }
264       }
265   }
266   }
267 
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)
271       {
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()) {
276               return addr;
277           }
278       }
279   }
280   }
281 
282   return LLDB_INVALID_ADDRESS;
283 }
284 
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.
290 lldb::addr_t
291 DynamicLoaderDarwinKernel::SearchForKernelNearPC(Process *process) {
292   if (GetGlobalProperties().GetScanType() == eKASLRScanNone ||
293       GetGlobalProperties().GetScanType() == eKASLRScanLowgloAddresses) {
294     return LLDB_INVALID_ADDRESS;
295   }
296 
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);
301 
302   int ptrsize = process->GetTarget().GetArchitecture().GetAddressByteSize();
303 
304   // The kernel is always loaded in high memory, if the top bit is zero,
305   // this isn't a kernel.
306   if (ptrsize == 8) {
307     if ((pc & (1ULL << 63)) == 0) {
308       return LLDB_INVALID_ADDRESS;
309     }
310   } else {
311     if ((pc & (1ULL << 31)) == 0) {
312       return LLDB_INVALID_ADDRESS;
313     }
314   }
315 
316   if (pc == LLDB_INVALID_ADDRESS)
317     return LLDB_INVALID_ADDRESS;
318 
319   int pagesize = 0x4000;  // 16k pages on 64-bit targets
320   if (ptrsize == 4)
321     pagesize = 0x1000;    // 4k pages on 32-bit targets
322 
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);
326 
327   // Search backwards for 128 megabytes, or first memory read error.
328   while (pc - addr < 128 * 0x100000) {
329     bool read_error;
330     if (CheckForKernelImageAtAddress(addr, process, &read_error).IsValid())
331       return addr;
332 
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)
336       break;
337 
338     addr -= pagesize;
339   }
340 
341   return LLDB_INVALID_ADDRESS;
342 }
343 
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(
349     Process *process) {
350   if (GetGlobalProperties().GetScanType() != eKASLRScanExhaustiveScan) {
351     return LLDB_INVALID_ADDRESS;
352   }
353 
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;
358   } else {
359     kernel_range_low = 1ULL << 31;
360     kernel_range_high = UINT32_MAX;
361   }
362 
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;
369 
370   addr_t addr = kernel_range_low;
371 
372   while (addr >= kernel_range_low && addr < kernel_range_high) {
373     // x86_64 kernels are at offset 0
374     if (CheckForKernelImageAtAddress(addr, process).IsValid())
375       return addr;
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;
382     addr += 0x100000;
383   }
384   return LLDB_INVALID_ADDRESS;
385 }
386 
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
390 // a Mach-O header.
391 
392 bool
393 DynamicLoaderDarwinKernel::ReadMachHeader(addr_t addr, Process *process, llvm::MachO::mach_header &header,
394                                           bool *read_error) {
395   Status error;
396   if (read_error)
397     *read_error = false;
398 
399   // Read the mach header and see whether it looks like a kernel
400   if (process->ReadMemory(addr, &header, sizeof(header), error) !=
401       sizeof(header)) {
402     if (read_error)
403       *read_error = true;
404     return false;
405   }
406 
407   const uint32_t magicks[] = { llvm::MachO::MH_MAGIC_64, llvm::MachO::MH_MAGIC, llvm::MachO::MH_CIGAM, llvm::MachO::MH_CIGAM_64};
408 
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;
413 
414   if (!found_matching_pattern)
415     return false;
416 
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);
426   }
427 
428   return true;
429 }
430 
431 // Given an address in memory, look to see if there is a kernel image at that
432 // address.
433 // Returns a UUID; if a kernel was not found at that address, UUID.IsValid()
434 // will be false.
435 lldb_private::UUID
436 DynamicLoaderDarwinKernel::CheckForKernelImageAtAddress(lldb::addr_t addr,
437                                                         Process *process,
438                                                         bool *read_error) {
439   Log *log = GetLog(LLDBLog::DynamicLoader);
440   if (addr == LLDB_INVALID_ADDRESS) {
441     if (read_error)
442       *read_error = true;
443     return UUID();
444   }
445 
446   LLDB_LOGF(log,
447             "DynamicLoaderDarwinKernel::CheckForKernelImageAtAddress: "
448             "looking for kernel binary at 0x%" PRIx64,
449             addr);
450 
451   llvm::MachO::mach_header header;
452 
453   if (!ReadMachHeader(addr, process, header, read_error))
454     return UUID();
455 
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
460   // set.
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())
467       return UUID();
468 
469     ObjectFile *exe_objfile = memory_module_sp->GetObjectFile();
470     if (exe_objfile == nullptr) {
471       LLDB_LOGF(log,
472                 "DynamicLoaderDarwinKernel::CheckForKernelImageAtAddress "
473                 "found a binary at 0x%" PRIx64
474                 " but could not create an object file from memory",
475                 addr);
476       return UUID();
477     }
478 
479     if (is_kernel(memory_module_sp.get())) {
480       ArchSpec kernel_arch(eArchTypeMachO, header.cputype, header.cpusubtype);
481       if (!process->GetTarget().GetArchitecture().IsCompatibleMatch(
482               kernel_arch)) {
483         process->GetTarget().SetArchitecture(kernel_arch);
484       }
485       if (log) {
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();
490         } else {
491           uuid_str = "and no LC_UUID found in load commands ";
492         }
493         LLDB_LOGF(
494             log,
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());
498       }
499       return memory_module_sp->GetUUID();
500     }
501   }
502 
503   return UUID();
504 }
505 
506 // Constructor
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) {
513   Status error;
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);
520 }
521 
522 // Destructor
523 DynamicLoaderDarwinKernel::~DynamicLoaderDarwinKernel() { Clear(true); }
524 
525 void DynamicLoaderDarwinKernel::UpdateIfNeeded() {
526   LoadKernelModuleIfNeeded();
527   SetNotificationBreakpointIfNeeded();
528 }
529 
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);
535   UpdateIfNeeded();
536 }
537 
538 /// Called after attaching a process.
539 ///
540 /// Allow DynamicLoader plug-ins to execute some code after
541 /// attaching to a process.
542 void DynamicLoaderDarwinKernel::DidLaunch() {
543   PrivateInitialize(m_process);
544   UpdateIfNeeded();
545 }
546 
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);
550 
551   if (m_process->IsAlive() && LLDB_BREAK_ID_IS_VALID(m_break_id))
552     m_process->ClearBreakpointSiteByID(m_break_id);
553 
554   if (clear_process)
555     m_process = nullptr;
556   m_kernel.Clear();
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;
561 }
562 
563 bool DynamicLoaderDarwinKernel::KextImageInfo::LoadImageAtFileAddress(
564     Process *process) {
565   if (IsLoaded())
566     return true;
567 
568   if (m_module_sp) {
569     bool changed = false;
570     if (m_module_sp->SetLoadAddress(process->GetTarget(), 0, true, changed))
571       m_load_process_stop_id = process->GetStopID();
572   }
573   return false;
574 }
575 
576 void DynamicLoaderDarwinKernel::KextImageInfo::SetModule(ModuleSP module_sp) {
577   m_module_sp = module_sp;
578   m_kernel_image = is_kernel(module_sp.get());
579 }
580 
581 ModuleSP DynamicLoaderDarwinKernel::KextImageInfo::GetModule() {
582   return m_module_sp;
583 }
584 
585 void DynamicLoaderDarwinKernel::KextImageInfo::SetLoadAddress(
586     addr_t load_addr) {
587   m_load_address = load_addr;
588 }
589 
590 addr_t DynamicLoaderDarwinKernel::KextImageInfo::GetLoadAddress() const {
591   return m_load_address;
592 }
593 
594 uint64_t DynamicLoaderDarwinKernel::KextImageInfo::GetSize() const {
595   return m_size;
596 }
597 
598 void DynamicLoaderDarwinKernel::KextImageInfo::SetSize(uint64_t size) {
599   m_size = size;
600 }
601 
602 uint32_t DynamicLoaderDarwinKernel::KextImageInfo::GetProcessStopId() const {
603   return m_load_process_stop_id;
604 }
605 
606 void DynamicLoaderDarwinKernel::KextImageInfo::SetProcessStopId(
607     uint32_t stop_id) {
608   m_load_process_stop_id = stop_id;
609 }
610 
611 bool DynamicLoaderDarwinKernel::KextImageInfo::operator==(
612     const KextImageInfo &rhs) const {
613   if (m_uuid.IsValid() || rhs.GetUUID().IsValid()) {
614     return m_uuid == rhs.GetUUID();
615   }
616 
617   return m_name == rhs.GetName() && m_load_address == rhs.GetLoadAddress();
618 }
619 
620 void DynamicLoaderDarwinKernel::KextImageInfo::SetName(const char *name) {
621   m_name = name;
622 }
623 
624 std::string DynamicLoaderDarwinKernel::KextImageInfo::GetName() const {
625   return m_name;
626 }
627 
628 void DynamicLoaderDarwinKernel::KextImageInfo::SetUUID(const UUID &uuid) {
629   m_uuid = uuid;
630 }
631 
632 UUID DynamicLoaderDarwinKernel::KextImageInfo::GetUUID() const {
633   return m_uuid;
634 }
635 
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.
639 //
640 // Returns true if m_memory_module_sp is now set to a valid Module.
641 
642 bool DynamicLoaderDarwinKernel::KextImageInfo::ReadMemoryModule(
643     Process *process) {
644   Log *log = GetLog(LLDBLog::Host);
645   if (m_memory_module_sp.get() != nullptr)
646     return true;
647   if (m_load_address == LLDB_INVALID_ADDRESS)
648     return false;
649 
650   FileSpec file_spec(m_name.c_str());
651 
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;
660   }
661 
662   ModuleSP memory_module_sp =
663       process->ReadModuleFromMemory(file_spec, m_load_address, size_to_read);
664 
665   if (memory_module_sp.get() == nullptr)
666     return false;
667 
668   bool this_is_kernel = is_kernel(memory_module_sp.get());
669 
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()) {
675       if (log) {
676         LLDB_LOGF(log,
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());
682       }
683       return false;
684     }
685   }
686 
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();
690   }
691 
692   m_memory_module_sp = memory_module_sp;
693   m_kernel_image = this_is_kernel;
694   if (this_is_kernel) {
695     if (log) {
696       // This is unusual and probably not intended
697       LLDB_LOGF(log,
698                 "KextImageInfo::ReadMemoryModule read the kernel binary out "
699                 "of memory");
700     }
701     if (memory_module_sp->GetArchitecture().IsValid()) {
702       process->GetTarget().SetArchitecture(memory_module_sp->GetArchitecture());
703     }
704   }
705 
706   return true;
707 }
708 
709 bool DynamicLoaderDarwinKernel::KextImageInfo::IsKernel() const {
710   return m_kernel_image;
711 }
712 
713 void DynamicLoaderDarwinKernel::KextImageInfo::SetIsKernel(bool is_kernel) {
714   m_kernel_image = is_kernel;
715 }
716 
717 bool DynamicLoaderDarwinKernel::KextImageInfo::LoadImageUsingMemoryModule(
718     Process *process, Progress *progress) {
719   Log *log = GetLog(LLDBLog::DynamicLoader);
720   if (IsLoaded())
721     return true;
722 
723   Target &target = process->GetTarget();
724 
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);
730       LLDB_LOGF(log,
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);
734       return false;
735     }
736   }
737 
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);
742 
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);
751     }
752     target.GetImages().Remove(incorrect_kernels);
753   }
754 
755   if (!m_module_sp) {
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);
760 
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) {
769       prog_str << "at 0x";
770       prog_str.PutHex64(GetLoadAddress());
771     }
772 
773     std::unique_ptr<Progress> progress_up;
774     if (progress)
775       progress->Increment(1, prog_str.GetString().str());
776     else {
777       if (IsKernel())
778         progress_up = std::make_unique<Progress>("Loading kernel",
779                                                  prog_str.GetString().str());
780       else
781         progress_up = std::make_unique<Progress>("Loading kext",
782                                                  prog_str.GetString().str());
783     }
784 
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);
792 
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
797       // system.
798       PlatformSP platform_sp(target.GetPlatform());
799       if (platform_sp) {
800         FileSpecList search_paths = target.GetExecutableSearchPaths();
801         platform_sp->GetSharedModule(module_spec, process, m_module_sp,
802                                      &search_paths, nullptr, nullptr);
803       }
804 
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
809       // search methods.
810       if (!m_module_sp) {
811         m_module_sp = target.GetOrCreateModule(module_spec, true /* notify */);
812       }
813 
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
817       // set.
818       Status kernel_search_error;
819       if (IsKernel() &&
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());
826           }
827         }
828       }
829 
830       if (IsKernel() && !m_module_sp) {
831         Stream &s = target.GetDebugger().GetErrorStream();
832         s.Printf("WARNING: Unable to locate kernel binary on the debugger "
833                  "system.\n");
834         if (kernel_search_error.Fail() && kernel_search_error.AsCString("") &&
835             kernel_search_error.AsCString("")[0] != '\0') {
836           s << kernel_search_error.AsCString();
837         }
838       }
839     }
840 
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)) {
851             LLDB_LOGF(log,
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.
856             return true;
857           }
858         }
859       }
860     }
861 
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
864     // UUIDs
865     if (m_module_sp) {
866       if (m_uuid.IsValid() && m_module_sp->GetUUID() == m_uuid) {
867         target.GetImages().AppendIfNeeded(m_module_sp, false);
868       }
869     }
870   }
871 
872   // If we've found a binary, read the load commands out of memory so we
873   // can set the segment load addresses.
874   if (m_module_sp)
875     ReadMemoryModule (process);
876 
877   static ConstString g_section_name_LINKEDIT("__LINKEDIT");
878 
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();
883 
884       if (memory_object_file && ondisk_object_file) {
885         // The memory_module for kexts may have an invalid __LINKEDIT seg; skip
886         // it.
887         const bool ignore_linkedit = !IsKernel();
888 
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
894         // addresses.
895         //
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();
908               LLDB_LOGF(
909                   log,
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);
913             }
914           }
915         }
916 
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;
925 
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.
930 
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)
941                 continue;
942 
943               if (fixed_slide != LLDB_INVALID_ADDRESS) {
944                 target.SetSectionLoadAddress(
945                     ondisk_section_sp,
946                     ondisk_section_sp->GetFileAddress() + fixed_slide);
947               } else {
948                 const Section *memory_section =
949                     memory_section_list
950                         ->FindSectionByName(ondisk_section_sp->GetName())
951                         .get();
952                 if (memory_section) {
953                   target.SetSectionLoadAddress(
954                       ondisk_section_sp, memory_section->GetFileAddress());
955                   ++num_sections_loaded;
956                 }
957               }
958             }
959           }
960           if (num_sections_loaded > 0)
961             m_load_process_stop_id = process->GetStopID();
962           else
963             m_module_sp.reset(); // No sections were loaded
964         } else
965           m_module_sp.reset(); // One or both section lists
966       } else
967         m_module_sp.reset(); // One or both object files missing
968     } else
969       m_module_sp.reset(); // UUID mismatch
970   }
971 
972   bool is_loaded = IsLoaded();
973 
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);
984       }
985     }
986     {
987       s.Printf("Loaded kernel file %s\n",
988                m_module_sp->GetFileSpec().GetPath().c_str());
989     }
990     s.Flush();
991   }
992 
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);
999   }
1000 
1001   return is_loaded;
1002 }
1003 
1004 uint32_t DynamicLoaderDarwinKernel::KextImageInfo::GetAddressByteSize() {
1005   if (m_memory_module_sp)
1006     return m_memory_module_sp->GetArchitecture().GetAddressByteSize();
1007   if (m_module_sp)
1008     return m_module_sp->GetArchitecture().GetAddressByteSize();
1009   return 0;
1010 }
1011 
1012 lldb::ByteOrder DynamicLoaderDarwinKernel::KextImageInfo::GetByteOrder() {
1013   if (m_memory_module_sp)
1014     return m_memory_module_sp->GetArchitecture().GetByteOrder();
1015   if (m_module_sp)
1016     return m_module_sp->GetArchitecture().GetByteOrder();
1017   return endian::InlHostByteOrder();
1018 }
1019 
1020 lldb_private::ArchSpec
1021 DynamicLoaderDarwinKernel::KextImageInfo::GetArchitecture() const {
1022   if (m_memory_module_sp)
1023     return m_memory_module_sp->GetArchitecture();
1024   if (m_module_sp)
1025     return m_module_sp->GetArchitecture();
1026   return lldb_private::ArchSpec();
1027 }
1028 
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()) {
1034     m_kernel.Clear();
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);
1039     }
1040 
1041     ConstString kernel_name("mach_kernel");
1042     if (m_kernel.GetModule().get() && m_kernel.GetModule()->GetObjectFile() &&
1043         !m_kernel.GetModule()
1044              ->GetObjectFile()
1045              ->GetFileSpec()
1046              .GetFilename()
1047              .IsEmpty()) {
1048       kernel_name =
1049           m_kernel.GetModule()->GetObjectFile()->GetFileSpec().GetFilename();
1050     }
1051     m_kernel.SetName(kernel_name.AsCString());
1052 
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());
1073             }
1074           } else {
1075             m_kernel.SetLoadAddress(file_address);
1076           }
1077         }
1078       }
1079     }
1080     if (m_kernel.GetLoadAddress() != LLDB_INVALID_ADDRESS)
1081       if (!m_kernel.LoadImageUsingMemoryModule(m_process))
1082         m_kernel.LoadImageAtFileAddress(m_process);
1083 
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);
1089 
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);
1096       if (symbol) {
1097         m_kext_summary_header_ptr_addr = symbol->GetAddress();
1098         // Update all image infos
1099         ReadAllKextSummaries();
1100       }
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);
1109       if (symbol) {
1110         const addr_t orig_code_mask = m_process->GetCodeAddressMask();
1111         const addr_t orig_data_mask = m_process->GetDataAddressMask();
1112 
1113         m_process->SetCodeAddressMask(0);
1114         m_process->SetDataAddressMask(0);
1115         Status error;
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);
1132         } else {
1133           m_process->SetCodeAddressMask(orig_code_mask);
1134           m_process->SetDataAddressMask(orig_data_mask);
1135         }
1136       }
1137     } else {
1138       m_kernel.Clear();
1139     }
1140   }
1141 }
1142 
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
1146 // preference).
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);
1152 }
1153 
1154 bool DynamicLoaderDarwinKernel::BreakpointHit(StoppointCallbackContext *context,
1155                                               user_id_t break_id,
1156                                               user_id_t break_loc_id) {
1157   Log *log = GetLog(LLDBLog::DynamicLoader);
1158   LLDB_LOGF(log, "DynamicLoaderDarwinKernel::BreakpointHit (...)\n");
1159 
1160   ReadAllKextSummaries();
1161 
1162   if (log)
1163     PutToLog(log);
1164 
1165   return GetStopWhenImagesChange();
1166 }
1167 
1168 bool DynamicLoaderDarwinKernel::ReadKextSummaryHeader() {
1169   std::lock_guard<std::recursive_mutex> guard(m_mutex);
1170 
1171   // the all image infos is already valid for this process stop ID
1172 
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();
1176     Status error;
1177     // Read enough bytes for a "OSKextLoadedKextSummaryHeader" structure which
1178     // is currently 4 uint32_t and a pointer.
1179     uint8_t buf[24];
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
1187       // isn't NULL
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();
1203             return false;
1204           }
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.
1210               Stream &s =
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();
1216               return false;
1217             }
1218           } else {
1219             // Versions less than 2 didn't have an entry size, it was hard
1220             // coded
1221             m_kext_summary_header.entry_size =
1222                 KERNEL_MODULE_ENTRY_SIZE_VERSION_1;
1223           }
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();
1233             return false;
1234           }
1235           return true;
1236         }
1237       }
1238     }
1239   }
1240   m_kext_summary_header_addr.Clear();
1241   return false;
1242 }
1243 
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.
1249 
1250 bool DynamicLoaderDarwinKernel::ParseKextSummaries(
1251     const Address &kext_summary_addr, uint32_t count) {
1252   KextImageInfo::collection kext_summaries;
1253   Log *log = GetLog(LLDBLog::DynamicLoader);
1254   LLDB_LOGF(log,
1255             "Kexts-changed breakpoint hit, there are %d kexts currently.\n",
1256             count);
1257 
1258   std::lock_guard<std::recursive_mutex> guard(m_mutex);
1259 
1260   if (!ReadKextSummaries(kext_summary_addr, count, kext_summaries))
1261     return false;
1262 
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();
1267 
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
1270   // as "add".
1271   std::vector<bool> to_be_removed(m_known_kexts.size(), true);
1272   std::vector<bool> to_be_added(count, true);
1273 
1274   int number_of_new_kexts_being_added = 0;
1275   int number_of_old_kexts_being_removed = m_known_kexts.size();
1276 
1277   const uint32_t new_kexts_size = kext_summaries.size();
1278   const uint32_t old_kexts_size = m_known_kexts.size();
1279 
1280   // The m_known_kexts vector may have entries that have been Cleared, or are a
1281   // kernel.
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()) {
1286       ignore = true;
1287     } else if (image_info.GetLoadAddress() == LLDB_INVALID_ADDRESS &&
1288                !image_info.GetModule()) {
1289       ignore = true;
1290     }
1291 
1292     if (ignore) {
1293       number_of_old_kexts_being_removed--;
1294       to_be_removed[old_kext] = false;
1295     }
1296   }
1297 
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;
1308 
1309         number_of_old_kexts_being_removed--;
1310         add_this_one = false;
1311         break;
1312       }
1313     }
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;
1321       break;
1322     }
1323     if (add_this_one) {
1324       number_of_new_kexts_being_added++;
1325     }
1326   }
1327 
1328   if (number_of_new_kexts_being_added == 0 &&
1329       number_of_old_kexts_being_removed == 0)
1330     return true;
1331 
1332   Stream &s = m_process->GetTarget().GetDebugger().GetOutputStream();
1333   if (load_kexts) {
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);
1343     }
1344   }
1345 
1346   if (log) {
1347     if (load_kexts) {
1348       LLDB_LOGF(log,
1349                 "DynamicLoaderDarwinKernel::ParseKextSummaries: %d kexts "
1350                 "added, %d kexts removed",
1351                 number_of_new_kexts_being_added,
1352                 number_of_old_kexts_being_removed);
1353     } else {
1354       LLDB_LOGF(log,
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);
1359     }
1360   }
1361 
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);
1367 
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];
1372         if (load_kexts) {
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);
1378           }
1379         }
1380 
1381         m_known_kexts.push_back(image_info);
1382 
1383         if (image_info.GetModule() &&
1384             m_process->GetStopID() == image_info.GetProcessStopId())
1385           loaded_module_list.AppendIfNeeded(image_info.GetModule());
1386 
1387         if (log)
1388           kext_summaries[new_kext].PutToLog(log);
1389       }
1390     }
1391     m_process->GetTarget().ModulesDidLoad(loaded_module_list);
1392   }
1393 
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());
1405           }
1406           s.Printf(".");
1407           image_info.Clear();
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.
1411         }
1412       }
1413       m_process->GetTarget().ModulesDidUnload(unloaded_module_list, false);
1414     }
1415   }
1416 
1417   if (load_kexts) {
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();
1429       }
1430       for (const auto &ku : kexts_failed_to_load) {
1431         std::string uuid;
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());
1435       }
1436     }
1437     s.Flush();
1438   }
1439 
1440   return true;
1441 }
1442 
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();
1448 
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);
1452   Status error;
1453 
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) {
1458 
1459     DataExtractor extractor(data.GetBytes(), data.GetByteSize(), endian,
1460                             addr_size);
1461     uint32_t i = 0;
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)
1471         break;
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));
1477     }
1478     if (i < image_infos.size())
1479       image_infos.resize(i);
1480   } else {
1481     image_infos.clear();
1482   }
1483   return image_infos.size();
1484 }
1485 
1486 bool DynamicLoaderDarwinKernel::ReadAllKextSummaries() {
1487   std::lock_guard<std::recursive_mutex> guard(m_mutex);
1488 
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();
1497       }
1498       return true;
1499     }
1500   }
1501   return false;
1502 }
1503 
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(),
1508              m_name);
1509   } else {
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);
1512   }
1513 }
1514 
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 {
1518   if (log == nullptr)
1519     return;
1520 
1521   std::lock_guard<std::recursive_mutex> guard(m_mutex);
1522   LLDB_LOGF(log,
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);
1528 
1529   size_t i;
1530   const size_t count = m_known_kexts.size();
1531   if (count > 0) {
1532     log->PutCString("Loaded:");
1533     for (i = 0; i < count; i++)
1534       m_known_kexts[i].PutToLog(log);
1535   }
1536 }
1537 
1538 void DynamicLoaderDarwinKernel::PrivateInitialize(Process *process) {
1539   DEBUG_PRINTF("DynamicLoaderDarwinKernel::%s() process state = %s\n",
1540                __FUNCTION__, StateAsCString(m_process->GetState()));
1541   Clear(true);
1542   m_process = process;
1543 }
1544 
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()));
1549 
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());
1555     Breakpoint *bp =
1556         m_process->GetTarget()
1557             .CreateBreakpoint(&module_spec_list, nullptr,
1558                               "OSKextLoadedKextSummariesUpdated",
1559                               eFunctionNameTypeFull, eLanguageTypeUnknown, 0,
1560                               skip_prologue, internal_bp, hardware)
1561             .get();
1562 
1563     bp->SetCallback(DynamicLoaderDarwinKernel::BreakpointHitCallback, this,
1564                     true);
1565     m_break_id = bp->GetID();
1566   }
1567 }
1568 
1569 // Member function that gets called when the process state changes.
1570 void DynamicLoaderDarwinKernel::PrivateProcessStateChanged(Process *process,
1571                                                            StateType state) {
1572   DEBUG_PRINTF("DynamicLoaderDarwinKernel::%s(%s)\n", __FUNCTION__,
1573                StateAsCString(state));
1574   switch (state) {
1575   case eStateConnected:
1576   case eStateAttaching:
1577   case eStateLaunching:
1578   case eStateInvalid:
1579   case eStateUnloaded:
1580   case eStateExited:
1581   case eStateDetached:
1582     Clear(false);
1583     break;
1584 
1585   case eStateStopped:
1586     UpdateIfNeeded();
1587     break;
1588 
1589   case eStateRunning:
1590   case eStateStepping:
1591   case eStateCrashed:
1592   case eStateSuspended:
1593     break;
1594   }
1595 }
1596 
1597 ThreadPlanSP
1598 DynamicLoaderDarwinKernel::GetStepThroughTrampolinePlan(Thread &thread,
1599                                                         bool stop_others) {
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;
1604 }
1605 
1606 Status DynamicLoaderDarwinKernel::CanLoadImage() {
1607   Status error;
1608   error = Status::FromErrorString(
1609       "always unsafe to load or unload shared libraries in the darwin kernel");
1610   return error;
1611 }
1612 
1613 void DynamicLoaderDarwinKernel::Initialize() {
1614   PluginManager::RegisterPlugin(GetPluginNameStatic(),
1615                                 GetPluginDescriptionStatic(), CreateInstance,
1616                                 DebuggerInitialize);
1617 }
1618 
1619 void DynamicLoaderDarwinKernel::Terminate() {
1620   PluginManager::UnregisterPlugin(CreateInstance);
1621 }
1622 
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.",
1631         is_global_setting);
1632   }
1633 }
1634 
1635 llvm::StringRef DynamicLoaderDarwinKernel::GetPluginDescriptionStatic() {
1636   return "Dynamic loader plug-in that watches for shared library loads/unloads "
1637          "in the MacOSX kernel.";
1638 }
1639 
1640 lldb::ByteOrder
1641 DynamicLoaderDarwinKernel::GetByteOrderFromMagic(uint32_t magic) {
1642   switch (magic) {
1643   case llvm::MachO::MH_MAGIC:
1644   case llvm::MachO::MH_MAGIC_64:
1645     return endian::InlHostByteOrder();
1646 
1647   case llvm::MachO::MH_CIGAM:
1648   case llvm::MachO::MH_CIGAM_64:
1649     if (endian::InlHostByteOrder() == lldb::eByteOrderBig)
1650       return lldb::eByteOrderLittle;
1651     else
1652       return lldb::eByteOrderBig;
1653 
1654   default:
1655     break;
1656   }
1657   return lldb::eByteOrderInvalid;
1658 }
1659