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