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