Coverage Report

Created: 2022-01-18 06:27

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