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