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