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