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