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