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