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