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