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   ~DynamicLoaderDarwinKernelProperties() override {}
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 	  FileSpecList search_paths = target.GetExecutableSearchPaths();
808           kext_bundle_module_spec.GetFileSpec() = kext_filespec;
809           platform_sp->GetSharedModule(
810               kext_bundle_module_spec, process, m_module_sp,
811               &search_paths, NULL, NULL);
812         }
813       }
814 
815       // Ask the Target to find this file on the local system, if possible.
816       // This will search in the list of currently-loaded files, look in the
817       // standard search paths on the system, and on a Mac it will try calling
818       // the DebugSymbols framework with the UUID to find the binary via its
819       // search methods.
820       if (!m_module_sp) {
821         m_module_sp = target.GetOrCreateModule(module_spec, true /* notify */);
822       }
823 
824       if (IsKernel() && !m_module_sp) {
825         Stream *s = target.GetDebugger().GetOutputFile().get();
826         if (s) {
827           s->Printf("WARNING: Unable to locate kernel binary on the debugger "
828                     "system.\n");
829         }
830       }
831     }
832 
833     // If we managed to find a module, append it to the target's list of
834     // images. If we also have a memory module, require that they have matching
835     // UUIDs
836     if (m_module_sp) {
837       if (m_uuid.IsValid() && m_module_sp->GetUUID() == m_uuid) {
838         target.GetImages().AppendIfNeeded(m_module_sp);
839         if (IsKernel() &&
840             target.GetExecutableModulePointer() != m_module_sp.get()) {
841           target.SetExecutableModule(m_module_sp, eLoadDependentsNo);
842         }
843       }
844     }
845   }
846 
847   // If we've found a binary, read the load commands out of memory so we
848   // can set the segment load addresses.
849   if (m_module_sp)
850     ReadMemoryModule (process);
851 
852   static ConstString g_section_name_LINKEDIT("__LINKEDIT");
853 
854   if (m_memory_module_sp && m_module_sp) {
855     if (m_module_sp->GetUUID() == m_memory_module_sp->GetUUID()) {
856       ObjectFile *ondisk_object_file = m_module_sp->GetObjectFile();
857       ObjectFile *memory_object_file = m_memory_module_sp->GetObjectFile();
858 
859       if (memory_object_file && ondisk_object_file) {
860         // The memory_module for kexts may have an invalid __LINKEDIT seg; skip
861         // it.
862         const bool ignore_linkedit = !IsKernel();
863 
864         SectionList *ondisk_section_list = ondisk_object_file->GetSectionList();
865         SectionList *memory_section_list = memory_object_file->GetSectionList();
866         if (memory_section_list && ondisk_section_list) {
867           const uint32_t num_ondisk_sections = ondisk_section_list->GetSize();
868           // There may be CTF sections in the memory image so we can't always
869           // just compare the number of sections (which are actually segments
870           // in mach-o parlance)
871           uint32_t sect_idx = 0;
872 
873           // Use the memory_module's addresses for each section to set the file
874           // module's load address as appropriate.  We don't want to use a
875           // single slide value for the entire kext - different segments may be
876           // slid different amounts by the kext loader.
877 
878           uint32_t num_sections_loaded = 0;
879           for (sect_idx = 0; sect_idx < num_ondisk_sections; ++sect_idx) {
880             SectionSP ondisk_section_sp(
881                 ondisk_section_list->GetSectionAtIndex(sect_idx));
882             if (ondisk_section_sp) {
883               // Don't ever load __LINKEDIT as it may or may not be actually
884               // mapped into memory and there is no current way to tell.
885               // I filed rdar://problem/12851706 to track being able to tell
886               // if the __LINKEDIT is actually mapped, but until then, we need
887               // to not load the __LINKEDIT
888               if (ignore_linkedit &&
889                   ondisk_section_sp->GetName() == g_section_name_LINKEDIT)
890                 continue;
891 
892               const Section *memory_section =
893                   memory_section_list
894                       ->FindSectionByName(ondisk_section_sp->GetName())
895                       .get();
896               if (memory_section) {
897                 target.SetSectionLoadAddress(ondisk_section_sp,
898                                              memory_section->GetFileAddress());
899                 ++num_sections_loaded;
900               }
901             }
902           }
903           if (num_sections_loaded > 0)
904             m_load_process_stop_id = process->GetStopID();
905           else
906             m_module_sp.reset(); // No sections were loaded
907         } else
908           m_module_sp.reset(); // One or both section lists
909       } else
910         m_module_sp.reset(); // One or both object files missing
911     } else
912       m_module_sp.reset(); // UUID mismatch
913   }
914 
915   bool is_loaded = IsLoaded();
916 
917   if (is_loaded && m_module_sp && IsKernel()) {
918     Stream *s = target.GetDebugger().GetOutputFile().get();
919     if (s) {
920       ObjectFile *kernel_object_file = m_module_sp->GetObjectFile();
921       if (kernel_object_file) {
922         addr_t file_address =
923             kernel_object_file->GetBaseAddress().GetFileAddress();
924         if (m_load_address != LLDB_INVALID_ADDRESS &&
925             file_address != LLDB_INVALID_ADDRESS) {
926           s->Printf("Kernel slid 0x%" PRIx64 " in memory.\n",
927                     m_load_address - file_address);
928         }
929       }
930       {
931         s->Printf("Loaded kernel file %s\n",
932                   m_module_sp->GetFileSpec().GetPath().c_str());
933       }
934       s->Flush();
935     }
936   }
937   return is_loaded;
938 }
939 
940 uint32_t DynamicLoaderDarwinKernel::KextImageInfo::GetAddressByteSize() {
941   if (m_memory_module_sp)
942     return m_memory_module_sp->GetArchitecture().GetAddressByteSize();
943   if (m_module_sp)
944     return m_module_sp->GetArchitecture().GetAddressByteSize();
945   return 0;
946 }
947 
948 lldb::ByteOrder DynamicLoaderDarwinKernel::KextImageInfo::GetByteOrder() {
949   if (m_memory_module_sp)
950     return m_memory_module_sp->GetArchitecture().GetByteOrder();
951   if (m_module_sp)
952     return m_module_sp->GetArchitecture().GetByteOrder();
953   return endian::InlHostByteOrder();
954 }
955 
956 lldb_private::ArchSpec
957 DynamicLoaderDarwinKernel::KextImageInfo::GetArchitecture() const {
958   if (m_memory_module_sp)
959     return m_memory_module_sp->GetArchitecture();
960   if (m_module_sp)
961     return m_module_sp->GetArchitecture();
962   return lldb_private::ArchSpec();
963 }
964 
965 // Load the kernel module and initialize the "m_kernel" member. Return true
966 // _only_ if the kernel is loaded the first time through (subsequent calls to
967 // this function should return false after the kernel has been already loaded).
968 void DynamicLoaderDarwinKernel::LoadKernelModuleIfNeeded() {
969   if (!m_kext_summary_header_ptr_addr.IsValid()) {
970     m_kernel.Clear();
971     m_kernel.SetModule(m_process->GetTarget().GetExecutableModule());
972     m_kernel.SetIsKernel(true);
973 
974     ConstString kernel_name("mach_kernel");
975     if (m_kernel.GetModule().get() && m_kernel.GetModule()->GetObjectFile() &&
976         !m_kernel.GetModule()
977              ->GetObjectFile()
978              ->GetFileSpec()
979              .GetFilename()
980              .IsEmpty()) {
981       kernel_name =
982           m_kernel.GetModule()->GetObjectFile()->GetFileSpec().GetFilename();
983     }
984     m_kernel.SetName(kernel_name.AsCString());
985 
986     if (m_kernel.GetLoadAddress() == LLDB_INVALID_ADDRESS) {
987       m_kernel.SetLoadAddress(m_kernel_load_address);
988       if (m_kernel.GetLoadAddress() == LLDB_INVALID_ADDRESS &&
989           m_kernel.GetModule()) {
990         // We didn't get a hint from the process, so we will try the kernel at
991         // the address that it exists at in the file if we have one
992         ObjectFile *kernel_object_file = m_kernel.GetModule()->GetObjectFile();
993         if (kernel_object_file) {
994           addr_t load_address =
995               kernel_object_file->GetBaseAddress().GetLoadAddress(
996                   &m_process->GetTarget());
997           addr_t file_address =
998               kernel_object_file->GetBaseAddress().GetFileAddress();
999           if (load_address != LLDB_INVALID_ADDRESS && load_address != 0) {
1000             m_kernel.SetLoadAddress(load_address);
1001             if (load_address != file_address) {
1002               // Don't accidentally relocate the kernel to the File address --
1003               // the Load address has already been set to its actual in-memory
1004               // address. Mark it as IsLoaded.
1005               m_kernel.SetProcessStopId(m_process->GetStopID());
1006             }
1007           } else {
1008             m_kernel.SetLoadAddress(file_address);
1009           }
1010         }
1011       }
1012     }
1013 
1014     if (m_kernel.GetLoadAddress() != LLDB_INVALID_ADDRESS) {
1015       if (!m_kernel.LoadImageUsingMemoryModule(m_process)) {
1016         m_kernel.LoadImageAtFileAddress(m_process);
1017       }
1018     }
1019 
1020     // The operating system plugin gets loaded and initialized in
1021     // LoadImageUsingMemoryModule when we discover the kernel dSYM.  For a core
1022     // file in particular, that's the wrong place to do this, since  we haven't
1023     // fixed up the section addresses yet.  So let's redo it here.
1024     LoadOperatingSystemPlugin(false);
1025 
1026     if (m_kernel.IsLoaded() && m_kernel.GetModule()) {
1027       static ConstString kext_summary_symbol("gLoadedKextSummaries");
1028       const Symbol *symbol =
1029           m_kernel.GetModule()->FindFirstSymbolWithNameAndType(
1030               kext_summary_symbol, eSymbolTypeData);
1031       if (symbol) {
1032         m_kext_summary_header_ptr_addr = symbol->GetAddress();
1033         // Update all image infos
1034         ReadAllKextSummaries();
1035       }
1036     } else {
1037       m_kernel.Clear();
1038     }
1039   }
1040 }
1041 
1042 // Static callback function that gets called when our DYLD notification
1043 // breakpoint gets hit. We update all of our image infos and then let our super
1044 // class DynamicLoader class decide if we should stop or not (based on global
1045 // preference).
1046 bool DynamicLoaderDarwinKernel::BreakpointHitCallback(
1047     void *baton, StoppointCallbackContext *context, user_id_t break_id,
1048     user_id_t break_loc_id) {
1049   return static_cast<DynamicLoaderDarwinKernel *>(baton)->BreakpointHit(
1050       context, break_id, break_loc_id);
1051 }
1052 
1053 bool DynamicLoaderDarwinKernel::BreakpointHit(StoppointCallbackContext *context,
1054                                               user_id_t break_id,
1055                                               user_id_t break_loc_id) {
1056   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER));
1057   if (log)
1058     log->Printf("DynamicLoaderDarwinKernel::BreakpointHit (...)\n");
1059 
1060   ReadAllKextSummaries();
1061 
1062   if (log)
1063     PutToLog(log);
1064 
1065   return GetStopWhenImagesChange();
1066 }
1067 
1068 bool DynamicLoaderDarwinKernel::ReadKextSummaryHeader() {
1069   std::lock_guard<std::recursive_mutex> guard(m_mutex);
1070 
1071   // the all image infos is already valid for this process stop ID
1072 
1073   if (m_kext_summary_header_ptr_addr.IsValid()) {
1074     const uint32_t addr_size = m_kernel.GetAddressByteSize();
1075     const ByteOrder byte_order = m_kernel.GetByteOrder();
1076     Status error;
1077     // Read enough bytes for a "OSKextLoadedKextSummaryHeader" structure which
1078     // is currently 4 uint32_t and a pointer.
1079     uint8_t buf[24];
1080     DataExtractor data(buf, sizeof(buf), byte_order, addr_size);
1081     const size_t count = 4 * sizeof(uint32_t) + addr_size;
1082     const bool prefer_file_cache = false;
1083     if (m_process->GetTarget().ReadPointerFromMemory(
1084             m_kext_summary_header_ptr_addr, prefer_file_cache, error,
1085             m_kext_summary_header_addr)) {
1086       // We got a valid address for our kext summary header and make sure it
1087       // isn't NULL
1088       if (m_kext_summary_header_addr.IsValid() &&
1089           m_kext_summary_header_addr.GetFileAddress() != 0) {
1090         const size_t bytes_read = m_process->GetTarget().ReadMemory(
1091             m_kext_summary_header_addr, prefer_file_cache, buf, count, error);
1092         if (bytes_read == count) {
1093           lldb::offset_t offset = 0;
1094           m_kext_summary_header.version = data.GetU32(&offset);
1095           if (m_kext_summary_header.version > 128) {
1096             Stream *s =
1097                 m_process->GetTarget().GetDebugger().GetOutputFile().get();
1098             s->Printf("WARNING: Unable to read kext summary header, got "
1099                       "improbable version number %u\n",
1100                       m_kext_summary_header.version);
1101             // If we get an improbably large version number, we're probably
1102             // getting bad memory.
1103             m_kext_summary_header_addr.Clear();
1104             return false;
1105           }
1106           if (m_kext_summary_header.version >= 2) {
1107             m_kext_summary_header.entry_size = data.GetU32(&offset);
1108             if (m_kext_summary_header.entry_size > 4096) {
1109               // If we get an improbably large entry_size, we're probably
1110               // getting bad memory.
1111               Stream *s =
1112                   m_process->GetTarget().GetDebugger().GetOutputFile().get();
1113               s->Printf("WARNING: Unable to read kext summary header, got "
1114                         "improbable entry_size %u\n",
1115                         m_kext_summary_header.entry_size);
1116               m_kext_summary_header_addr.Clear();
1117               return false;
1118             }
1119           } else {
1120             // Versions less than 2 didn't have an entry size, it was hard
1121             // coded
1122             m_kext_summary_header.entry_size =
1123                 KERNEL_MODULE_ENTRY_SIZE_VERSION_1;
1124           }
1125           m_kext_summary_header.entry_count = data.GetU32(&offset);
1126           if (m_kext_summary_header.entry_count > 10000) {
1127             // If we get an improbably large number of kexts, we're probably
1128             // getting bad memory.
1129             Stream *s =
1130                 m_process->GetTarget().GetDebugger().GetOutputFile().get();
1131             s->Printf("WARNING: Unable to read kext summary header, got "
1132                       "improbable number of kexts %u\n",
1133                       m_kext_summary_header.entry_count);
1134             m_kext_summary_header_addr.Clear();
1135             return false;
1136           }
1137           return true;
1138         }
1139       }
1140     }
1141   }
1142   m_kext_summary_header_addr.Clear();
1143   return false;
1144 }
1145 
1146 // We've either (a) just attached to a new kernel, or (b) the kexts-changed
1147 // breakpoint was hit and we need to figure out what kexts have been added or
1148 // removed. Read the kext summaries from the inferior kernel memory, compare
1149 // them against the m_known_kexts vector and update the m_known_kexts vector as
1150 // needed to keep in sync with the inferior.
1151 
1152 bool DynamicLoaderDarwinKernel::ParseKextSummaries(
1153     const Address &kext_summary_addr, uint32_t count) {
1154   KextImageInfo::collection kext_summaries;
1155   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER));
1156   if (log)
1157     log->Printf("Kexts-changed breakpoint hit, there are %d kexts currently.\n",
1158                 count);
1159 
1160   std::lock_guard<std::recursive_mutex> guard(m_mutex);
1161 
1162   if (!ReadKextSummaries(kext_summary_addr, count, kext_summaries))
1163     return false;
1164 
1165   // read the plugin.dynamic-loader.darwin-kernel.load-kexts setting -- if the
1166   // user requested no kext loading, don't print any messages about kexts &
1167   // don't try to read them.
1168   const bool load_kexts = GetGlobalProperties()->GetLoadKexts();
1169 
1170   // By default, all kexts we've loaded in the past are marked as "remove" and
1171   // all of the kexts we just found out about from ReadKextSummaries are marked
1172   // as "add".
1173   std::vector<bool> to_be_removed(m_known_kexts.size(), true);
1174   std::vector<bool> to_be_added(count, true);
1175 
1176   int number_of_new_kexts_being_added = 0;
1177   int number_of_old_kexts_being_removed = m_known_kexts.size();
1178 
1179   const uint32_t new_kexts_size = kext_summaries.size();
1180   const uint32_t old_kexts_size = m_known_kexts.size();
1181 
1182   // The m_known_kexts vector may have entries that have been Cleared, or are a
1183   // kernel.
1184   for (uint32_t old_kext = 0; old_kext < old_kexts_size; old_kext++) {
1185     bool ignore = false;
1186     KextImageInfo &image_info = m_known_kexts[old_kext];
1187     if (image_info.IsKernel()) {
1188       ignore = true;
1189     } else if (image_info.GetLoadAddress() == LLDB_INVALID_ADDRESS &&
1190                !image_info.GetModule()) {
1191       ignore = true;
1192     }
1193 
1194     if (ignore) {
1195       number_of_old_kexts_being_removed--;
1196       to_be_removed[old_kext] = false;
1197     }
1198   }
1199 
1200   // Scan over the list of kexts we just read from the kernel, note those that
1201   // need to be added and those already loaded.
1202   for (uint32_t new_kext = 0; new_kext < new_kexts_size; new_kext++) {
1203     bool add_this_one = true;
1204     for (uint32_t old_kext = 0; old_kext < old_kexts_size; old_kext++) {
1205       if (m_known_kexts[old_kext] == kext_summaries[new_kext]) {
1206         // We already have this kext, don't re-load it.
1207         to_be_added[new_kext] = false;
1208         // This kext is still present, do not remove it.
1209         to_be_removed[old_kext] = false;
1210 
1211         number_of_old_kexts_being_removed--;
1212         add_this_one = false;
1213         break;
1214       }
1215     }
1216     // If this "kext" entry is actually an alias for the kernel -- the kext was
1217     // compiled into the kernel or something -- then we don't want to load the
1218     // kernel's text section at a different address.  Ignore this kext entry.
1219     if (kext_summaries[new_kext].GetUUID().IsValid() &&
1220         m_kernel.GetUUID().IsValid() &&
1221         kext_summaries[new_kext].GetUUID() == m_kernel.GetUUID()) {
1222       to_be_added[new_kext] = false;
1223       break;
1224     }
1225     if (add_this_one) {
1226       number_of_new_kexts_being_added++;
1227     }
1228   }
1229 
1230   if (number_of_new_kexts_being_added == 0 &&
1231       number_of_old_kexts_being_removed == 0)
1232     return true;
1233 
1234   Stream *s = m_process->GetTarget().GetDebugger().GetOutputFile().get();
1235   if (s && load_kexts) {
1236     if (number_of_new_kexts_being_added > 0 &&
1237         number_of_old_kexts_being_removed > 0) {
1238       s->Printf("Loading %d kext modules and unloading %d kext modules ",
1239                 number_of_new_kexts_being_added,
1240                 number_of_old_kexts_being_removed);
1241     } else if (number_of_new_kexts_being_added > 0) {
1242       s->Printf("Loading %d kext modules ", number_of_new_kexts_being_added);
1243     } else if (number_of_old_kexts_being_removed > 0) {
1244       s->Printf("Unloading %d kext modules ",
1245                 number_of_old_kexts_being_removed);
1246     }
1247   }
1248 
1249   if (log) {
1250     if (load_kexts) {
1251       log->Printf("DynamicLoaderDarwinKernel::ParseKextSummaries: %d kexts "
1252                   "added, %d kexts removed",
1253                   number_of_new_kexts_being_added,
1254                   number_of_old_kexts_being_removed);
1255     } else {
1256       log->Printf(
1257           "DynamicLoaderDarwinKernel::ParseKextSummaries kext loading is "
1258           "disabled, else would have %d kexts added, %d kexts removed",
1259           number_of_new_kexts_being_added, number_of_old_kexts_being_removed);
1260     }
1261   }
1262 
1263   // Build up a list of <kext-name, uuid> for any kexts that fail to load
1264   std::vector<std::pair<std::string, UUID>> kexts_failed_to_load;
1265   if (number_of_new_kexts_being_added > 0) {
1266     ModuleList loaded_module_list;
1267 
1268     const uint32_t num_of_new_kexts = kext_summaries.size();
1269     for (uint32_t new_kext = 0; new_kext < num_of_new_kexts; new_kext++) {
1270       if (to_be_added[new_kext]) {
1271         KextImageInfo &image_info = kext_summaries[new_kext];
1272         bool kext_successfully_added = true;
1273         if (load_kexts) {
1274           if (!image_info.LoadImageUsingMemoryModule(m_process)) {
1275             kexts_failed_to_load.push_back(std::pair<std::string, UUID>(
1276                 kext_summaries[new_kext].GetName(),
1277                 kext_summaries[new_kext].GetUUID()));
1278             image_info.LoadImageAtFileAddress(m_process);
1279             kext_successfully_added = false;
1280           }
1281         }
1282 
1283         m_known_kexts.push_back(image_info);
1284 
1285         if (image_info.GetModule() &&
1286             m_process->GetStopID() == image_info.GetProcessStopId())
1287           loaded_module_list.AppendIfNeeded(image_info.GetModule());
1288 
1289         if (s && load_kexts) {
1290           if (kext_successfully_added)
1291             s->Printf(".");
1292           else
1293             s->Printf("-");
1294         }
1295 
1296         if (log)
1297           kext_summaries[new_kext].PutToLog(log);
1298       }
1299     }
1300     m_process->GetTarget().ModulesDidLoad(loaded_module_list);
1301   }
1302 
1303   if (number_of_old_kexts_being_removed > 0) {
1304     ModuleList loaded_module_list;
1305     const uint32_t num_of_old_kexts = m_known_kexts.size();
1306     for (uint32_t old_kext = 0; old_kext < num_of_old_kexts; old_kext++) {
1307       ModuleList unloaded_module_list;
1308       if (to_be_removed[old_kext]) {
1309         KextImageInfo &image_info = m_known_kexts[old_kext];
1310         // You can't unload the kernel.
1311         if (!image_info.IsKernel()) {
1312           if (image_info.GetModule()) {
1313             unloaded_module_list.AppendIfNeeded(image_info.GetModule());
1314           }
1315           if (s)
1316             s->Printf(".");
1317           image_info.Clear();
1318           // should pull it out of the KextImageInfos vector but that would
1319           // mutate the list and invalidate the to_be_removed bool vector;
1320           // leaving it in place once Cleared() is relatively harmless.
1321         }
1322       }
1323       m_process->GetTarget().ModulesDidUnload(unloaded_module_list, false);
1324     }
1325   }
1326 
1327   if (s && load_kexts) {
1328     s->Printf(" done.\n");
1329     if (kexts_failed_to_load.size() > 0 && number_of_new_kexts_being_added > 0) {
1330       s->Printf("Failed to load %d of %d kexts:\n",
1331                 (int)kexts_failed_to_load.size(),
1332                 number_of_new_kexts_being_added);
1333       // print a sorted list of <kext-name, uuid> kexts which failed to load
1334       unsigned longest_name = 0;
1335       std::sort(kexts_failed_to_load.begin(), kexts_failed_to_load.end());
1336       for (const auto &ku : kexts_failed_to_load) {
1337         if (ku.first.size() > longest_name)
1338           longest_name = ku.first.size();
1339       }
1340       for (const auto &ku : kexts_failed_to_load) {
1341         std::string uuid;
1342         if (ku.second.IsValid())
1343           uuid = ku.second.GetAsString();
1344         s->Printf (" %-*s %s\n", longest_name, ku.first.c_str(), uuid.c_str());
1345       }
1346     }
1347     s->Flush();
1348   }
1349 
1350   return true;
1351 }
1352 
1353 uint32_t DynamicLoaderDarwinKernel::ReadKextSummaries(
1354     const Address &kext_summary_addr, uint32_t image_infos_count,
1355     KextImageInfo::collection &image_infos) {
1356   const ByteOrder endian = m_kernel.GetByteOrder();
1357   const uint32_t addr_size = m_kernel.GetAddressByteSize();
1358 
1359   image_infos.resize(image_infos_count);
1360   const size_t count = image_infos.size() * m_kext_summary_header.entry_size;
1361   DataBufferHeap data(count, 0);
1362   Status error;
1363 
1364   const bool prefer_file_cache = false;
1365   const size_t bytes_read = m_process->GetTarget().ReadMemory(
1366       kext_summary_addr, prefer_file_cache, data.GetBytes(), data.GetByteSize(),
1367       error);
1368   if (bytes_read == count) {
1369 
1370     DataExtractor extractor(data.GetBytes(), data.GetByteSize(), endian,
1371                             addr_size);
1372     uint32_t i = 0;
1373     for (uint32_t kext_summary_offset = 0;
1374          i < image_infos.size() &&
1375          extractor.ValidOffsetForDataOfSize(kext_summary_offset,
1376                                             m_kext_summary_header.entry_size);
1377          ++i, kext_summary_offset += m_kext_summary_header.entry_size) {
1378       lldb::offset_t offset = kext_summary_offset;
1379       const void *name_data =
1380           extractor.GetData(&offset, KERNEL_MODULE_MAX_NAME);
1381       if (name_data == NULL)
1382         break;
1383       image_infos[i].SetName((const char *)name_data);
1384       UUID uuid = UUID::fromOptionalData(extractor.GetData(&offset, 16), 16);
1385       image_infos[i].SetUUID(uuid);
1386       image_infos[i].SetLoadAddress(extractor.GetU64(&offset));
1387       image_infos[i].SetSize(extractor.GetU64(&offset));
1388     }
1389     if (i < image_infos.size())
1390       image_infos.resize(i);
1391   } else {
1392     image_infos.clear();
1393   }
1394   return image_infos.size();
1395 }
1396 
1397 bool DynamicLoaderDarwinKernel::ReadAllKextSummaries() {
1398   std::lock_guard<std::recursive_mutex> guard(m_mutex);
1399 
1400   if (ReadKextSummaryHeader()) {
1401     if (m_kext_summary_header.entry_count > 0 &&
1402         m_kext_summary_header_addr.IsValid()) {
1403       Address summary_addr(m_kext_summary_header_addr);
1404       summary_addr.Slide(m_kext_summary_header.GetSize());
1405       if (!ParseKextSummaries(summary_addr,
1406                               m_kext_summary_header.entry_count)) {
1407         m_known_kexts.clear();
1408       }
1409       return true;
1410     }
1411   }
1412   return false;
1413 }
1414 
1415 // Dump an image info structure to the file handle provided.
1416 void DynamicLoaderDarwinKernel::KextImageInfo::PutToLog(Log *log) const {
1417   if (m_load_address == LLDB_INVALID_ADDRESS) {
1418     LLDB_LOG(log, "uuid={0} name=\"{1}\" (UNLOADED)", m_uuid.GetAsString(),
1419              m_name);
1420   } else {
1421     LLDB_LOG(log, "addr={0:x+16} size={1:x+16} uuid={2} name=\"{3}\"",
1422         m_load_address, m_size, m_uuid.GetAsString(), m_name);
1423   }
1424 }
1425 
1426 // Dump the _dyld_all_image_infos members and all current image infos that we
1427 // have parsed to the file handle provided.
1428 void DynamicLoaderDarwinKernel::PutToLog(Log *log) const {
1429   if (log == NULL)
1430     return;
1431 
1432   std::lock_guard<std::recursive_mutex> guard(m_mutex);
1433   log->Printf("gLoadedKextSummaries = 0x%16.16" PRIx64
1434               " { version=%u, entry_size=%u, entry_count=%u }",
1435               m_kext_summary_header_addr.GetFileAddress(),
1436               m_kext_summary_header.version, m_kext_summary_header.entry_size,
1437               m_kext_summary_header.entry_count);
1438 
1439   size_t i;
1440   const size_t count = m_known_kexts.size();
1441   if (count > 0) {
1442     log->PutCString("Loaded:");
1443     for (i = 0; i < count; i++)
1444       m_known_kexts[i].PutToLog(log);
1445   }
1446 }
1447 
1448 void DynamicLoaderDarwinKernel::PrivateInitialize(Process *process) {
1449   DEBUG_PRINTF("DynamicLoaderDarwinKernel::%s() process state = %s\n",
1450                __FUNCTION__, StateAsCString(m_process->GetState()));
1451   Clear(true);
1452   m_process = process;
1453 }
1454 
1455 void DynamicLoaderDarwinKernel::SetNotificationBreakpointIfNeeded() {
1456   if (m_break_id == LLDB_INVALID_BREAK_ID && m_kernel.GetModule()) {
1457     DEBUG_PRINTF("DynamicLoaderDarwinKernel::%s() process state = %s\n",
1458                  __FUNCTION__, StateAsCString(m_process->GetState()));
1459 
1460     const bool internal_bp = true;
1461     const bool hardware = false;
1462     const LazyBool skip_prologue = eLazyBoolNo;
1463     FileSpecList module_spec_list;
1464     module_spec_list.Append(m_kernel.GetModule()->GetFileSpec());
1465     Breakpoint *bp =
1466         m_process->GetTarget()
1467             .CreateBreakpoint(&module_spec_list, NULL,
1468                               "OSKextLoadedKextSummariesUpdated",
1469                               eFunctionNameTypeFull, eLanguageTypeUnknown, 0,
1470                               skip_prologue, internal_bp, hardware)
1471             .get();
1472 
1473     bp->SetCallback(DynamicLoaderDarwinKernel::BreakpointHitCallback, this,
1474                     true);
1475     m_break_id = bp->GetID();
1476   }
1477 }
1478 
1479 // Member function that gets called when the process state changes.
1480 void DynamicLoaderDarwinKernel::PrivateProcessStateChanged(Process *process,
1481                                                            StateType state) {
1482   DEBUG_PRINTF("DynamicLoaderDarwinKernel::%s(%s)\n", __FUNCTION__,
1483                StateAsCString(state));
1484   switch (state) {
1485   case eStateConnected:
1486   case eStateAttaching:
1487   case eStateLaunching:
1488   case eStateInvalid:
1489   case eStateUnloaded:
1490   case eStateExited:
1491   case eStateDetached:
1492     Clear(false);
1493     break;
1494 
1495   case eStateStopped:
1496     UpdateIfNeeded();
1497     break;
1498 
1499   case eStateRunning:
1500   case eStateStepping:
1501   case eStateCrashed:
1502   case eStateSuspended:
1503     break;
1504   }
1505 }
1506 
1507 ThreadPlanSP
1508 DynamicLoaderDarwinKernel::GetStepThroughTrampolinePlan(Thread &thread,
1509                                                         bool stop_others) {
1510   ThreadPlanSP thread_plan_sp;
1511   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
1512   if (log)
1513     log->Printf("Could not find symbol for step through.");
1514   return thread_plan_sp;
1515 }
1516 
1517 Status DynamicLoaderDarwinKernel::CanLoadImage() {
1518   Status error;
1519   error.SetErrorString(
1520       "always unsafe to load or unload shared libraries in the darwin kernel");
1521   return error;
1522 }
1523 
1524 void DynamicLoaderDarwinKernel::Initialize() {
1525   PluginManager::RegisterPlugin(GetPluginNameStatic(),
1526                                 GetPluginDescriptionStatic(), CreateInstance,
1527                                 DebuggerInitialize);
1528 }
1529 
1530 void DynamicLoaderDarwinKernel::Terminate() {
1531   PluginManager::UnregisterPlugin(CreateInstance);
1532 }
1533 
1534 void DynamicLoaderDarwinKernel::DebuggerInitialize(
1535     lldb_private::Debugger &debugger) {
1536   if (!PluginManager::GetSettingForDynamicLoaderPlugin(
1537           debugger, DynamicLoaderDarwinKernelProperties::GetSettingName())) {
1538     const bool is_global_setting = true;
1539     PluginManager::CreateSettingForDynamicLoaderPlugin(
1540         debugger, GetGlobalProperties()->GetValueProperties(),
1541         ConstString("Properties for the DynamicLoaderDarwinKernel plug-in."),
1542         is_global_setting);
1543   }
1544 }
1545 
1546 lldb_private::ConstString DynamicLoaderDarwinKernel::GetPluginNameStatic() {
1547   static ConstString g_name("darwin-kernel");
1548   return g_name;
1549 }
1550 
1551 const char *DynamicLoaderDarwinKernel::GetPluginDescriptionStatic() {
1552   return "Dynamic loader plug-in that watches for shared library loads/unloads "
1553          "in the MacOSX kernel.";
1554 }
1555 
1556 // PluginInterface protocol
1557 lldb_private::ConstString DynamicLoaderDarwinKernel::GetPluginName() {
1558   return GetPluginNameStatic();
1559 }
1560 
1561 uint32_t DynamicLoaderDarwinKernel::GetPluginVersion() { return 1; }
1562 
1563 lldb::ByteOrder
1564 DynamicLoaderDarwinKernel::GetByteOrderFromMagic(uint32_t magic) {
1565   switch (magic) {
1566   case llvm::MachO::MH_MAGIC:
1567   case llvm::MachO::MH_MAGIC_64:
1568     return endian::InlHostByteOrder();
1569 
1570   case llvm::MachO::MH_CIGAM:
1571   case llvm::MachO::MH_CIGAM_64:
1572     if (endian::InlHostByteOrder() == lldb::eByteOrderBig)
1573       return lldb::eByteOrderLittle;
1574     else
1575       return lldb::eByteOrderBig;
1576 
1577   default:
1578     break;
1579   }
1580   return lldb::eByteOrderInvalid;
1581 }
1582