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