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   // kexts will have a uuid from the table.
770   // for the kernel, we'll need to read the load commands out of memory to get it.
771   if (m_uuid.IsValid() == false) {
772     if (ReadMemoryModule(process) == false) {
773       Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER));
774       if (log)
775         log->Printf("Unable to read '%s' from memory at address 0x%" PRIx64
776                     " to get the segment load addresses.",
777                     m_name.c_str(), m_load_address);
778       return false;
779     }
780   }
781 
782   if (IsKernel() && m_uuid.IsValid()) {
783     Stream *s = target.GetDebugger().GetOutputFile().get();
784     if (s) {
785       s->Printf("Kernel UUID: %s\n",
786                 m_uuid.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 && m_uuid.IsValid()) {
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       if (m_uuid.IsValid() && m_module_sp->GetUUID() == m_uuid) {
861         target.GetImages().AppendIfNeeded(m_module_sp);
862         if (IsKernel() &&
863             target.GetExecutableModulePointer() != m_module_sp.get()) {
864           target.SetExecutableModule(m_module_sp, eLoadDependentsNo);
865         }
866       }
867     }
868   }
869 
870   // If we've found a binary, read the load commands out of memory so we
871   // can set the segment load addresses.
872   if (m_module_sp)
873     ReadMemoryModule (process);
874 
875   static ConstString g_section_name_LINKEDIT("__LINKEDIT");
876 
877   if (m_memory_module_sp && m_module_sp) {
878     if (m_module_sp->GetUUID() == m_memory_module_sp->GetUUID()) {
879       ObjectFile *ondisk_object_file = m_module_sp->GetObjectFile();
880       ObjectFile *memory_object_file = m_memory_module_sp->GetObjectFile();
881 
882       if (memory_object_file && ondisk_object_file) {
883         // The memory_module for kexts may have an invalid __LINKEDIT seg; skip
884         // it.
885         const bool ignore_linkedit = !IsKernel();
886 
887         SectionList *ondisk_section_list = ondisk_object_file->GetSectionList();
888         SectionList *memory_section_list = memory_object_file->GetSectionList();
889         if (memory_section_list && ondisk_section_list) {
890           const uint32_t num_ondisk_sections = ondisk_section_list->GetSize();
891           // There may be CTF sections in the memory image so we can't always
892           // just compare the number of sections (which are actually segments
893           // in mach-o parlance)
894           uint32_t sect_idx = 0;
895 
896           // Use the memory_module's addresses for each section to set the file
897           // module's load address as appropriate.  We don't want to use a
898           // single slide value for the entire kext - different segments may be
899           // slid different amounts by the kext loader.
900 
901           uint32_t num_sections_loaded = 0;
902           for (sect_idx = 0; sect_idx < num_ondisk_sections; ++sect_idx) {
903             SectionSP ondisk_section_sp(
904                 ondisk_section_list->GetSectionAtIndex(sect_idx));
905             if (ondisk_section_sp) {
906               // Don't ever load __LINKEDIT as it may or may not be actually
907               // mapped into memory and there is no current way to tell.
908               // I filed rdar://problem/12851706 to track being able to tell
909               // if the __LINKEDIT is actually mapped, but until then, we need
910               // to not load the __LINKEDIT
911               if (ignore_linkedit &&
912                   ondisk_section_sp->GetName() == g_section_name_LINKEDIT)
913                 continue;
914 
915               const Section *memory_section =
916                   memory_section_list
917                       ->FindSectionByName(ondisk_section_sp->GetName())
918                       .get();
919               if (memory_section) {
920                 target.SetSectionLoadAddress(ondisk_section_sp,
921                                              memory_section->GetFileAddress());
922                 ++num_sections_loaded;
923               }
924             }
925           }
926           if (num_sections_loaded > 0)
927             m_load_process_stop_id = process->GetStopID();
928           else
929             m_module_sp.reset(); // No sections were loaded
930         } else
931           m_module_sp.reset(); // One or both section lists
932       } else
933         m_module_sp.reset(); // One or both object files missing
934     } else
935       m_module_sp.reset(); // UUID mismatch
936   }
937 
938   bool is_loaded = IsLoaded();
939 
940   if (is_loaded && m_module_sp && IsKernel()) {
941     Stream *s = target.GetDebugger().GetOutputFile().get();
942     if (s) {
943       ObjectFile *kernel_object_file = m_module_sp->GetObjectFile();
944       if (kernel_object_file) {
945         addr_t file_address =
946             kernel_object_file->GetBaseAddress().GetFileAddress();
947         if (m_load_address != LLDB_INVALID_ADDRESS &&
948             file_address != LLDB_INVALID_ADDRESS) {
949           s->Printf("Kernel slid 0x%" PRIx64 " in memory.\n",
950                     m_load_address - file_address);
951         }
952       }
953       {
954         s->Printf("Loaded kernel file %s\n",
955                   m_module_sp->GetFileSpec().GetPath().c_str());
956       }
957       s->Flush();
958     }
959   }
960   return is_loaded;
961 }
962 
963 uint32_t DynamicLoaderDarwinKernel::KextImageInfo::GetAddressByteSize() {
964   if (m_memory_module_sp)
965     return m_memory_module_sp->GetArchitecture().GetAddressByteSize();
966   if (m_module_sp)
967     return m_module_sp->GetArchitecture().GetAddressByteSize();
968   return 0;
969 }
970 
971 lldb::ByteOrder DynamicLoaderDarwinKernel::KextImageInfo::GetByteOrder() {
972   if (m_memory_module_sp)
973     return m_memory_module_sp->GetArchitecture().GetByteOrder();
974   if (m_module_sp)
975     return m_module_sp->GetArchitecture().GetByteOrder();
976   return endian::InlHostByteOrder();
977 }
978 
979 lldb_private::ArchSpec
980 DynamicLoaderDarwinKernel::KextImageInfo::GetArchitecture() const {
981   if (m_memory_module_sp)
982     return m_memory_module_sp->GetArchitecture();
983   if (m_module_sp)
984     return m_module_sp->GetArchitecture();
985   return lldb_private::ArchSpec();
986 }
987 
988 //----------------------------------------------------------------------
989 // Load the kernel module and initialize the "m_kernel" member. Return true
990 // _only_ if the kernel is loaded the first time through (subsequent calls to
991 // this function should return false after the kernel has been already loaded).
992 //----------------------------------------------------------------------
993 void DynamicLoaderDarwinKernel::LoadKernelModuleIfNeeded() {
994   if (!m_kext_summary_header_ptr_addr.IsValid()) {
995     m_kernel.Clear();
996     m_kernel.SetModule(m_process->GetTarget().GetExecutableModule());
997     m_kernel.SetIsKernel(true);
998 
999     ConstString kernel_name("mach_kernel");
1000     if (m_kernel.GetModule().get() && m_kernel.GetModule()->GetObjectFile() &&
1001         !m_kernel.GetModule()
1002              ->GetObjectFile()
1003              ->GetFileSpec()
1004              .GetFilename()
1005              .IsEmpty()) {
1006       kernel_name =
1007           m_kernel.GetModule()->GetObjectFile()->GetFileSpec().GetFilename();
1008     }
1009     m_kernel.SetName(kernel_name.AsCString());
1010 
1011     if (m_kernel.GetLoadAddress() == LLDB_INVALID_ADDRESS) {
1012       m_kernel.SetLoadAddress(m_kernel_load_address);
1013       if (m_kernel.GetLoadAddress() == LLDB_INVALID_ADDRESS &&
1014           m_kernel.GetModule()) {
1015         // We didn't get a hint from the process, so we will try the kernel at
1016         // the address that it exists at in the file if we have one
1017         ObjectFile *kernel_object_file = m_kernel.GetModule()->GetObjectFile();
1018         if (kernel_object_file) {
1019           addr_t load_address =
1020               kernel_object_file->GetBaseAddress().GetLoadAddress(
1021                   &m_process->GetTarget());
1022           addr_t file_address =
1023               kernel_object_file->GetBaseAddress().GetFileAddress();
1024           if (load_address != LLDB_INVALID_ADDRESS && load_address != 0) {
1025             m_kernel.SetLoadAddress(load_address);
1026             if (load_address != file_address) {
1027               // Don't accidentally relocate the kernel to the File address --
1028               // the Load address has already been set to its actual in-memory
1029               // address. Mark it as IsLoaded.
1030               m_kernel.SetProcessStopId(m_process->GetStopID());
1031             }
1032           } else {
1033             m_kernel.SetLoadAddress(file_address);
1034           }
1035         }
1036       }
1037     }
1038 
1039     if (m_kernel.GetLoadAddress() != LLDB_INVALID_ADDRESS) {
1040       if (!m_kernel.LoadImageUsingMemoryModule(m_process)) {
1041         m_kernel.LoadImageAtFileAddress(m_process);
1042       }
1043     }
1044 
1045     // The operating system plugin gets loaded and initialized in
1046     // LoadImageUsingMemoryModule when we discover the kernel dSYM.  For a core
1047     // file in particular, that's the wrong place to do this, since  we haven't
1048     // fixed up the section addresses yet.  So let's redo it here.
1049     LoadOperatingSystemPlugin(false);
1050 
1051     if (m_kernel.IsLoaded() && m_kernel.GetModule()) {
1052       static ConstString kext_summary_symbol("gLoadedKextSummaries");
1053       const Symbol *symbol =
1054           m_kernel.GetModule()->FindFirstSymbolWithNameAndType(
1055               kext_summary_symbol, eSymbolTypeData);
1056       if (symbol) {
1057         m_kext_summary_header_ptr_addr = symbol->GetAddress();
1058         // Update all image infos
1059         ReadAllKextSummaries();
1060       }
1061     } else {
1062       m_kernel.Clear();
1063     }
1064   }
1065 }
1066 
1067 //----------------------------------------------------------------------
1068 // Static callback function that gets called when our DYLD notification
1069 // breakpoint gets hit. We update all of our image infos and then let our super
1070 // class DynamicLoader class decide if we should stop or not (based on global
1071 // preference).
1072 //----------------------------------------------------------------------
1073 bool DynamicLoaderDarwinKernel::BreakpointHitCallback(
1074     void *baton, StoppointCallbackContext *context, user_id_t break_id,
1075     user_id_t break_loc_id) {
1076   return static_cast<DynamicLoaderDarwinKernel *>(baton)->BreakpointHit(
1077       context, break_id, break_loc_id);
1078 }
1079 
1080 bool DynamicLoaderDarwinKernel::BreakpointHit(StoppointCallbackContext *context,
1081                                               user_id_t break_id,
1082                                               user_id_t break_loc_id) {
1083   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER));
1084   if (log)
1085     log->Printf("DynamicLoaderDarwinKernel::BreakpointHit (...)\n");
1086 
1087   ReadAllKextSummaries();
1088 
1089   if (log)
1090     PutToLog(log);
1091 
1092   return GetStopWhenImagesChange();
1093 }
1094 
1095 bool DynamicLoaderDarwinKernel::ReadKextSummaryHeader() {
1096   std::lock_guard<std::recursive_mutex> guard(m_mutex);
1097 
1098   // the all image infos is already valid for this process stop ID
1099 
1100   if (m_kext_summary_header_ptr_addr.IsValid()) {
1101     const uint32_t addr_size = m_kernel.GetAddressByteSize();
1102     const ByteOrder byte_order = m_kernel.GetByteOrder();
1103     Status error;
1104     // Read enough bytes for a "OSKextLoadedKextSummaryHeader" structure which
1105     // is currently 4 uint32_t and a pointer.
1106     uint8_t buf[24];
1107     DataExtractor data(buf, sizeof(buf), byte_order, addr_size);
1108     const size_t count = 4 * sizeof(uint32_t) + addr_size;
1109     const bool prefer_file_cache = false;
1110     if (m_process->GetTarget().ReadPointerFromMemory(
1111             m_kext_summary_header_ptr_addr, prefer_file_cache, error,
1112             m_kext_summary_header_addr)) {
1113       // We got a valid address for our kext summary header and make sure it
1114       // isn't NULL
1115       if (m_kext_summary_header_addr.IsValid() &&
1116           m_kext_summary_header_addr.GetFileAddress() != 0) {
1117         const size_t bytes_read = m_process->GetTarget().ReadMemory(
1118             m_kext_summary_header_addr, prefer_file_cache, buf, count, error);
1119         if (bytes_read == count) {
1120           lldb::offset_t offset = 0;
1121           m_kext_summary_header.version = data.GetU32(&offset);
1122           if (m_kext_summary_header.version > 128) {
1123             Stream *s =
1124                 m_process->GetTarget().GetDebugger().GetOutputFile().get();
1125             s->Printf("WARNING: Unable to read kext summary header, got "
1126                       "improbable version number %u\n",
1127                       m_kext_summary_header.version);
1128             // If we get an improbably large version number, we're probably
1129             // getting bad memory.
1130             m_kext_summary_header_addr.Clear();
1131             return false;
1132           }
1133           if (m_kext_summary_header.version >= 2) {
1134             m_kext_summary_header.entry_size = data.GetU32(&offset);
1135             if (m_kext_summary_header.entry_size > 4096) {
1136               // If we get an improbably large entry_size, we're probably
1137               // getting bad memory.
1138               Stream *s =
1139                   m_process->GetTarget().GetDebugger().GetOutputFile().get();
1140               s->Printf("WARNING: Unable to read kext summary header, got "
1141                         "improbable entry_size %u\n",
1142                         m_kext_summary_header.entry_size);
1143               m_kext_summary_header_addr.Clear();
1144               return false;
1145             }
1146           } else {
1147             // Versions less than 2 didn't have an entry size, it was hard
1148             // coded
1149             m_kext_summary_header.entry_size =
1150                 KERNEL_MODULE_ENTRY_SIZE_VERSION_1;
1151           }
1152           m_kext_summary_header.entry_count = data.GetU32(&offset);
1153           if (m_kext_summary_header.entry_count > 10000) {
1154             // If we get an improbably large number of kexts, we're probably
1155             // getting bad memory.
1156             Stream *s =
1157                 m_process->GetTarget().GetDebugger().GetOutputFile().get();
1158             s->Printf("WARNING: Unable to read kext summary header, got "
1159                       "improbable number of kexts %u\n",
1160                       m_kext_summary_header.entry_count);
1161             m_kext_summary_header_addr.Clear();
1162             return false;
1163           }
1164           return true;
1165         }
1166       }
1167     }
1168   }
1169   m_kext_summary_header_addr.Clear();
1170   return false;
1171 }
1172 
1173 // We've either (a) just attached to a new kernel, or (b) the kexts-changed
1174 // breakpoint was hit and we need to figure out what kexts have been added or
1175 // removed. Read the kext summaries from the inferior kernel memory, compare
1176 // them against the m_known_kexts vector and update the m_known_kexts vector as
1177 // needed to keep in sync with the inferior.
1178 
1179 bool DynamicLoaderDarwinKernel::ParseKextSummaries(
1180     const Address &kext_summary_addr, uint32_t count) {
1181   KextImageInfo::collection kext_summaries;
1182   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER));
1183   if (log)
1184     log->Printf("Kexts-changed breakpoint hit, there are %d kexts currently.\n",
1185                 count);
1186 
1187   std::lock_guard<std::recursive_mutex> guard(m_mutex);
1188 
1189   if (!ReadKextSummaries(kext_summary_addr, count, kext_summaries))
1190     return false;
1191 
1192   // read the plugin.dynamic-loader.darwin-kernel.load-kexts setting -- if the
1193   // user requested no kext loading, don't print any messages about kexts &
1194   // don't try to read them.
1195   const bool load_kexts = GetGlobalProperties()->GetLoadKexts();
1196 
1197   // By default, all kexts we've loaded in the past are marked as "remove" and
1198   // all of the kexts we just found out about from ReadKextSummaries are marked
1199   // as "add".
1200   std::vector<bool> to_be_removed(m_known_kexts.size(), true);
1201   std::vector<bool> to_be_added(count, true);
1202 
1203   int number_of_new_kexts_being_added = 0;
1204   int number_of_old_kexts_being_removed = m_known_kexts.size();
1205 
1206   const uint32_t new_kexts_size = kext_summaries.size();
1207   const uint32_t old_kexts_size = m_known_kexts.size();
1208 
1209   // The m_known_kexts vector may have entries that have been Cleared, or are a
1210   // kernel.
1211   for (uint32_t old_kext = 0; old_kext < old_kexts_size; old_kext++) {
1212     bool ignore = false;
1213     KextImageInfo &image_info = m_known_kexts[old_kext];
1214     if (image_info.IsKernel()) {
1215       ignore = true;
1216     } else if (image_info.GetLoadAddress() == LLDB_INVALID_ADDRESS &&
1217                !image_info.GetModule()) {
1218       ignore = true;
1219     }
1220 
1221     if (ignore) {
1222       number_of_old_kexts_being_removed--;
1223       to_be_removed[old_kext] = false;
1224     }
1225   }
1226 
1227   // Scan over the list of kexts we just read from the kernel, note those that
1228   // need to be added and those already loaded.
1229   for (uint32_t new_kext = 0; new_kext < new_kexts_size; new_kext++) {
1230     bool add_this_one = true;
1231     for (uint32_t old_kext = 0; old_kext < old_kexts_size; old_kext++) {
1232       if (m_known_kexts[old_kext] == kext_summaries[new_kext]) {
1233         // We already have this kext, don't re-load it.
1234         to_be_added[new_kext] = false;
1235         // This kext is still present, do not remove it.
1236         to_be_removed[old_kext] = false;
1237 
1238         number_of_old_kexts_being_removed--;
1239         add_this_one = false;
1240         break;
1241       }
1242     }
1243     // If this "kext" entry is actually an alias for the kernel -- the kext was
1244     // compiled into the kernel or something -- then we don't want to load the
1245     // kernel's text section at a different address.  Ignore this kext entry.
1246     if (kext_summaries[new_kext].GetUUID().IsValid() &&
1247         m_kernel.GetUUID().IsValid() &&
1248         kext_summaries[new_kext].GetUUID() == m_kernel.GetUUID()) {
1249       to_be_added[new_kext] = false;
1250       break;
1251     }
1252     if (add_this_one) {
1253       number_of_new_kexts_being_added++;
1254     }
1255   }
1256 
1257   if (number_of_new_kexts_being_added == 0 &&
1258       number_of_old_kexts_being_removed == 0)
1259     return true;
1260 
1261   Stream *s = m_process->GetTarget().GetDebugger().GetOutputFile().get();
1262   if (s && load_kexts) {
1263     if (number_of_new_kexts_being_added > 0 &&
1264         number_of_old_kexts_being_removed > 0) {
1265       s->Printf("Loading %d kext modules and unloading %d kext modules ",
1266                 number_of_new_kexts_being_added,
1267                 number_of_old_kexts_being_removed);
1268     } else if (number_of_new_kexts_being_added > 0) {
1269       s->Printf("Loading %d kext modules ", number_of_new_kexts_being_added);
1270     } else if (number_of_old_kexts_being_removed > 0) {
1271       s->Printf("Unloading %d kext modules ",
1272                 number_of_old_kexts_being_removed);
1273     }
1274   }
1275 
1276   if (log) {
1277     if (load_kexts) {
1278       log->Printf("DynamicLoaderDarwinKernel::ParseKextSummaries: %d kexts "
1279                   "added, %d kexts removed",
1280                   number_of_new_kexts_being_added,
1281                   number_of_old_kexts_being_removed);
1282     } else {
1283       log->Printf(
1284           "DynamicLoaderDarwinKernel::ParseKextSummaries kext loading is "
1285           "disabled, else would have %d kexts added, %d kexts removed",
1286           number_of_new_kexts_being_added, number_of_old_kexts_being_removed);
1287     }
1288   }
1289 
1290   // Build up a list of <kext-name, uuid> for any kexts that fail to load
1291   std::vector<std::pair<std::string, UUID>> kexts_failed_to_load;
1292   if (number_of_new_kexts_being_added > 0) {
1293     ModuleList loaded_module_list;
1294 
1295     const uint32_t num_of_new_kexts = kext_summaries.size();
1296     for (uint32_t new_kext = 0; new_kext < num_of_new_kexts; new_kext++) {
1297       if (to_be_added[new_kext]) {
1298         KextImageInfo &image_info = kext_summaries[new_kext];
1299         bool kext_successfully_added = true;
1300         if (load_kexts) {
1301           if (!image_info.LoadImageUsingMemoryModule(m_process)) {
1302             kexts_failed_to_load.push_back(std::pair<std::string, UUID>(
1303                 kext_summaries[new_kext].GetName(),
1304                 kext_summaries[new_kext].GetUUID()));
1305             image_info.LoadImageAtFileAddress(m_process);
1306             kext_successfully_added = false;
1307           }
1308         }
1309 
1310         m_known_kexts.push_back(image_info);
1311 
1312         if (image_info.GetModule() &&
1313             m_process->GetStopID() == image_info.GetProcessStopId())
1314           loaded_module_list.AppendIfNeeded(image_info.GetModule());
1315 
1316         if (s && load_kexts) {
1317           if (kext_successfully_added)
1318             s->Printf(".");
1319           else
1320             s->Printf("-");
1321         }
1322 
1323         if (log)
1324           kext_summaries[new_kext].PutToLog(log);
1325       }
1326     }
1327     m_process->GetTarget().ModulesDidLoad(loaded_module_list);
1328   }
1329 
1330   if (number_of_old_kexts_being_removed > 0) {
1331     ModuleList loaded_module_list;
1332     const uint32_t num_of_old_kexts = m_known_kexts.size();
1333     for (uint32_t old_kext = 0; old_kext < num_of_old_kexts; old_kext++) {
1334       ModuleList unloaded_module_list;
1335       if (to_be_removed[old_kext]) {
1336         KextImageInfo &image_info = m_known_kexts[old_kext];
1337         // You can't unload the kernel.
1338         if (!image_info.IsKernel()) {
1339           if (image_info.GetModule()) {
1340             unloaded_module_list.AppendIfNeeded(image_info.GetModule());
1341           }
1342           if (s)
1343             s->Printf(".");
1344           image_info.Clear();
1345           // should pull it out of the KextImageInfos vector but that would
1346           // mutate the list and invalidate the to_be_removed bool vector;
1347           // leaving it in place once Cleared() is relatively harmless.
1348         }
1349       }
1350       m_process->GetTarget().ModulesDidUnload(unloaded_module_list, false);
1351     }
1352   }
1353 
1354   if (s && load_kexts) {
1355     s->Printf(" done.\n");
1356     if (kexts_failed_to_load.size() > 0 && number_of_new_kexts_being_added > 0) {
1357       s->Printf("Failed to load %d of %d kexts:\n",
1358                 (int)kexts_failed_to_load.size(),
1359                 number_of_new_kexts_being_added);
1360       // print a sorted list of <kext-name, uuid> kexts which failed to load
1361       unsigned longest_name = 0;
1362       std::sort(kexts_failed_to_load.begin(), kexts_failed_to_load.end());
1363       for (const auto &ku : kexts_failed_to_load) {
1364         if (ku.first.size() > longest_name)
1365           longest_name = ku.first.size();
1366       }
1367       for (const auto &ku : kexts_failed_to_load) {
1368         std::string uuid;
1369         if (ku.second.IsValid())
1370           uuid = ku.second.GetAsString();
1371         s->Printf (" %-*s %s\n", longest_name, ku.first.c_str(), uuid.c_str());
1372       }
1373     }
1374     s->Flush();
1375   }
1376 
1377   return true;
1378 }
1379 
1380 uint32_t DynamicLoaderDarwinKernel::ReadKextSummaries(
1381     const Address &kext_summary_addr, uint32_t image_infos_count,
1382     KextImageInfo::collection &image_infos) {
1383   const ByteOrder endian = m_kernel.GetByteOrder();
1384   const uint32_t addr_size = m_kernel.GetAddressByteSize();
1385 
1386   image_infos.resize(image_infos_count);
1387   const size_t count = image_infos.size() * m_kext_summary_header.entry_size;
1388   DataBufferHeap data(count, 0);
1389   Status error;
1390 
1391   const bool prefer_file_cache = false;
1392   const size_t bytes_read = m_process->GetTarget().ReadMemory(
1393       kext_summary_addr, prefer_file_cache, data.GetBytes(), data.GetByteSize(),
1394       error);
1395   if (bytes_read == count) {
1396 
1397     DataExtractor extractor(data.GetBytes(), data.GetByteSize(), endian,
1398                             addr_size);
1399     uint32_t i = 0;
1400     for (uint32_t kext_summary_offset = 0;
1401          i < image_infos.size() &&
1402          extractor.ValidOffsetForDataOfSize(kext_summary_offset,
1403                                             m_kext_summary_header.entry_size);
1404          ++i, kext_summary_offset += m_kext_summary_header.entry_size) {
1405       lldb::offset_t offset = kext_summary_offset;
1406       const void *name_data =
1407           extractor.GetData(&offset, KERNEL_MODULE_MAX_NAME);
1408       if (name_data == NULL)
1409         break;
1410       image_infos[i].SetName((const char *)name_data);
1411       UUID uuid = UUID::fromOptionalData(extractor.GetData(&offset, 16), 16);
1412       image_infos[i].SetUUID(uuid);
1413       image_infos[i].SetLoadAddress(extractor.GetU64(&offset));
1414       image_infos[i].SetSize(extractor.GetU64(&offset));
1415     }
1416     if (i < image_infos.size())
1417       image_infos.resize(i);
1418   } else {
1419     image_infos.clear();
1420   }
1421   return image_infos.size();
1422 }
1423 
1424 bool DynamicLoaderDarwinKernel::ReadAllKextSummaries() {
1425   std::lock_guard<std::recursive_mutex> guard(m_mutex);
1426 
1427   if (ReadKextSummaryHeader()) {
1428     if (m_kext_summary_header.entry_count > 0 &&
1429         m_kext_summary_header_addr.IsValid()) {
1430       Address summary_addr(m_kext_summary_header_addr);
1431       summary_addr.Slide(m_kext_summary_header.GetSize());
1432       if (!ParseKextSummaries(summary_addr,
1433                               m_kext_summary_header.entry_count)) {
1434         m_known_kexts.clear();
1435       }
1436       return true;
1437     }
1438   }
1439   return false;
1440 }
1441 
1442 //----------------------------------------------------------------------
1443 // Dump an image info structure to the file handle provided.
1444 //----------------------------------------------------------------------
1445 void DynamicLoaderDarwinKernel::KextImageInfo::PutToLog(Log *log) const {
1446   if (m_load_address == LLDB_INVALID_ADDRESS) {
1447     LLDB_LOG(log, "uuid={0} name=\"{1}\" (UNLOADED)", m_uuid.GetAsString(),
1448              m_name);
1449   } else {
1450     LLDB_LOG(log, "addr={0:x+16} size={1:x+16} uuid={2} name=\"{3}\"",
1451         m_load_address, m_size, m_uuid.GetAsString(), m_name);
1452   }
1453 }
1454 
1455 //----------------------------------------------------------------------
1456 // Dump the _dyld_all_image_infos members and all current image infos that we
1457 // have parsed to the file handle provided.
1458 //----------------------------------------------------------------------
1459 void DynamicLoaderDarwinKernel::PutToLog(Log *log) const {
1460   if (log == NULL)
1461     return;
1462 
1463   std::lock_guard<std::recursive_mutex> guard(m_mutex);
1464   log->Printf("gLoadedKextSummaries = 0x%16.16" PRIx64
1465               " { version=%u, entry_size=%u, entry_count=%u }",
1466               m_kext_summary_header_addr.GetFileAddress(),
1467               m_kext_summary_header.version, m_kext_summary_header.entry_size,
1468               m_kext_summary_header.entry_count);
1469 
1470   size_t i;
1471   const size_t count = m_known_kexts.size();
1472   if (count > 0) {
1473     log->PutCString("Loaded:");
1474     for (i = 0; i < count; i++)
1475       m_known_kexts[i].PutToLog(log);
1476   }
1477 }
1478 
1479 void DynamicLoaderDarwinKernel::PrivateInitialize(Process *process) {
1480   DEBUG_PRINTF("DynamicLoaderDarwinKernel::%s() process state = %s\n",
1481                __FUNCTION__, StateAsCString(m_process->GetState()));
1482   Clear(true);
1483   m_process = process;
1484 }
1485 
1486 void DynamicLoaderDarwinKernel::SetNotificationBreakpointIfNeeded() {
1487   if (m_break_id == LLDB_INVALID_BREAK_ID && m_kernel.GetModule()) {
1488     DEBUG_PRINTF("DynamicLoaderDarwinKernel::%s() process state = %s\n",
1489                  __FUNCTION__, StateAsCString(m_process->GetState()));
1490 
1491     const bool internal_bp = true;
1492     const bool hardware = false;
1493     const LazyBool skip_prologue = eLazyBoolNo;
1494     FileSpecList module_spec_list;
1495     module_spec_list.Append(m_kernel.GetModule()->GetFileSpec());
1496     Breakpoint *bp =
1497         m_process->GetTarget()
1498             .CreateBreakpoint(&module_spec_list, NULL,
1499                               "OSKextLoadedKextSummariesUpdated",
1500                               eFunctionNameTypeFull, eLanguageTypeUnknown, 0,
1501                               skip_prologue, internal_bp, hardware)
1502             .get();
1503 
1504     bp->SetCallback(DynamicLoaderDarwinKernel::BreakpointHitCallback, this,
1505                     true);
1506     m_break_id = bp->GetID();
1507   }
1508 }
1509 
1510 //----------------------------------------------------------------------
1511 // Member function that gets called when the process state changes.
1512 //----------------------------------------------------------------------
1513 void DynamicLoaderDarwinKernel::PrivateProcessStateChanged(Process *process,
1514                                                            StateType state) {
1515   DEBUG_PRINTF("DynamicLoaderDarwinKernel::%s(%s)\n", __FUNCTION__,
1516                StateAsCString(state));
1517   switch (state) {
1518   case eStateConnected:
1519   case eStateAttaching:
1520   case eStateLaunching:
1521   case eStateInvalid:
1522   case eStateUnloaded:
1523   case eStateExited:
1524   case eStateDetached:
1525     Clear(false);
1526     break;
1527 
1528   case eStateStopped:
1529     UpdateIfNeeded();
1530     break;
1531 
1532   case eStateRunning:
1533   case eStateStepping:
1534   case eStateCrashed:
1535   case eStateSuspended:
1536     break;
1537   }
1538 }
1539 
1540 ThreadPlanSP
1541 DynamicLoaderDarwinKernel::GetStepThroughTrampolinePlan(Thread &thread,
1542                                                         bool stop_others) {
1543   ThreadPlanSP thread_plan_sp;
1544   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
1545   if (log)
1546     log->Printf("Could not find symbol for step through.");
1547   return thread_plan_sp;
1548 }
1549 
1550 Status DynamicLoaderDarwinKernel::CanLoadImage() {
1551   Status error;
1552   error.SetErrorString(
1553       "always unsafe to load or unload shared libraries in the darwin kernel");
1554   return error;
1555 }
1556 
1557 void DynamicLoaderDarwinKernel::Initialize() {
1558   PluginManager::RegisterPlugin(GetPluginNameStatic(),
1559                                 GetPluginDescriptionStatic(), CreateInstance,
1560                                 DebuggerInitialize);
1561 }
1562 
1563 void DynamicLoaderDarwinKernel::Terminate() {
1564   PluginManager::UnregisterPlugin(CreateInstance);
1565 }
1566 
1567 void DynamicLoaderDarwinKernel::DebuggerInitialize(
1568     lldb_private::Debugger &debugger) {
1569   if (!PluginManager::GetSettingForDynamicLoaderPlugin(
1570           debugger, DynamicLoaderDarwinKernelProperties::GetSettingName())) {
1571     const bool is_global_setting = true;
1572     PluginManager::CreateSettingForDynamicLoaderPlugin(
1573         debugger, GetGlobalProperties()->GetValueProperties(),
1574         ConstString("Properties for the DynamicLoaderDarwinKernel plug-in."),
1575         is_global_setting);
1576   }
1577 }
1578 
1579 lldb_private::ConstString DynamicLoaderDarwinKernel::GetPluginNameStatic() {
1580   static ConstString g_name("darwin-kernel");
1581   return g_name;
1582 }
1583 
1584 const char *DynamicLoaderDarwinKernel::GetPluginDescriptionStatic() {
1585   return "Dynamic loader plug-in that watches for shared library loads/unloads "
1586          "in the MacOSX kernel.";
1587 }
1588 
1589 //------------------------------------------------------------------
1590 // PluginInterface protocol
1591 //------------------------------------------------------------------
1592 lldb_private::ConstString DynamicLoaderDarwinKernel::GetPluginName() {
1593   return GetPluginNameStatic();
1594 }
1595 
1596 uint32_t DynamicLoaderDarwinKernel::GetPluginVersion() { return 1; }
1597 
1598 lldb::ByteOrder
1599 DynamicLoaderDarwinKernel::GetByteOrderFromMagic(uint32_t magic) {
1600   switch (magic) {
1601   case llvm::MachO::MH_MAGIC:
1602   case llvm::MachO::MH_MAGIC_64:
1603     return endian::InlHostByteOrder();
1604 
1605   case llvm::MachO::MH_CIGAM:
1606   case llvm::MachO::MH_CIGAM_64:
1607     if (endian::InlHostByteOrder() == lldb::eByteOrderBig)
1608       return lldb::eByteOrderLittle;
1609     else
1610       return lldb::eByteOrderBig;
1611 
1612   default:
1613     break;
1614   }
1615   return lldb::eByteOrderInvalid;
1616 }
1617