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