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