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