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