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