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