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